@xylex-group/athena 2.6.0 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +210 -17
  2. package/dist/browser.cjs +2102 -527
  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 +2096 -528
  7. package/dist/browser.js.map +1 -1
  8. package/dist/cli/index.cjs +2116 -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 +2116 -559
  13. package/dist/cli/index.js.map +1 -1
  14. package/dist/cookies.cjs +10 -3
  15. package/dist/cookies.cjs.map +1 -1
  16. package/dist/cookies.js +10 -3
  17. package/dist/cookies.js.map +1 -1
  18. package/dist/index.cjs +2694 -748
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +8 -7
  21. package/dist/index.d.ts +8 -7
  22. package/dist/index.js +2688 -749
  23. package/dist/index.js.map +1 -1
  24. package/dist/model-form-DMed05gE.d.cts +3037 -0
  25. package/dist/model-form-DXPlOnlI.d.ts +3037 -0
  26. package/dist/{pipeline-Ce3pTw5h.d.ts → pipeline-CkMnhwPI.d.ts} +1 -1
  27. package/dist/{pipeline-D1ZYeoH7.d.cts → pipeline-D4sJRKqN.d.cts} +1 -1
  28. package/dist/react-email-DZhDDlEl.d.cts +417 -0
  29. package/dist/react-email-Lrz9A-BW.d.ts +417 -0
  30. package/dist/react.cjs +178 -71
  31. package/dist/react.cjs.map +1 -1
  32. package/dist/react.d.cts +22 -5
  33. package/dist/react.d.ts +22 -5
  34. package/dist/react.js +92 -5
  35. package/dist/react.js.map +1 -1
  36. package/dist/{types-CUuo4NDi.d.cts → types-BzY6fETM.d.ts} +47 -5
  37. package/dist/{types-DapchQY5.d.ts → types-CAtTGGoz.d.cts} +47 -5
  38. package/dist/{types-DSX6AT5B.d.cts → types-vikz9YIO.d.cts} +23 -1
  39. package/dist/{types-DSX6AT5B.d.ts → types-vikz9YIO.d.ts} +23 -1
  40. package/package.json +194 -193
  41. package/dist/model-form-BaHWi3gm.d.cts +0 -1383
  42. package/dist/model-form-Dh6gWjL0.d.ts +0 -1383
  43. package/dist/react-email-B8O1Jeff.d.cts +0 -1230
  44. package/dist/react-email-CDEF0jij.d.ts +0 -1230
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { z } from 'zod';
1
2
  import { existsSync, readFileSync } from 'fs';
2
3
  import { resolve, dirname, posix } from 'path';
3
4
  import { pathToFileURL } from 'url';
@@ -671,9 +672,16 @@ var getSessionCookie = (request, config) => {
671
672
  const { cookieName = "session_token", cookiePrefix = "athena-auth" } = config || {};
672
673
  const parsedCookie = parseCookies(cookies);
673
674
  const getCookie = (name) => parsedCookie.get(name) || parsedCookie.get(`${SECURE_COOKIE_PREFIX}${name}`);
674
- const sessionToken = getCookie(`${cookiePrefix}.${cookieName}`) || getCookie(`${cookiePrefix}-${cookieName}`);
675
- if (sessionToken) {
676
- return sessionToken;
675
+ const candidateCookieNames = Array.from(/* @__PURE__ */ new Set([
676
+ cookieName,
677
+ cookieName.replace(/_/g, "-"),
678
+ cookieName.replace(/-/g, "_")
679
+ ])).filter(Boolean);
680
+ for (const candidateName of candidateCookieNames) {
681
+ const sessionToken = getCookie(`${cookiePrefix}.${candidateName}`) || getCookie(`${cookiePrefix}-${candidateName}`);
682
+ if (sessionToken) {
683
+ return sessionToken;
684
+ }
677
685
  }
678
686
  return null;
679
687
  };
@@ -796,7 +804,7 @@ var getCookieCache = async (request, config) => {
796
804
 
797
805
  // package.json
798
806
  var package_default = {
799
- version: "2.6.0"
807
+ version: "2.8.0"
800
808
  };
801
809
 
802
810
  // src/sdk-version.ts
@@ -3113,7 +3121,7 @@ function normalizeAthenaError(resultOrError, context) {
3113
3121
  const details = resultOrError.errorDetails;
3114
3122
  const message2 = messageFromUnknownError(resultOrError.error) ?? details?.message ?? `Athena ${context?.operation ?? operationFromDetails(details) ?? "request"} failed`;
3115
3123
  const operation = context?.operation ?? operationFromDetails(details);
3116
- const table = context?.table ?? extractTable(message2);
3124
+ const table2 = context?.table ?? extractTable(message2);
3117
3125
  const constraint = extractConstraint(message2);
3118
3126
  const gatewayCode = details?.code ?? gatewayCodeFromUnknownError(resultOrError.error);
3119
3127
  const kind2 = classifyKind(resultOrError.status, gatewayCode, message2);
@@ -3126,7 +3134,7 @@ function normalizeAthenaError(resultOrError, context) {
3126
3134
  retryable: isRetryable(kind2, resultOrError.status),
3127
3135
  status: resultOrError.status,
3128
3136
  constraint,
3129
- table,
3137
+ table: table2,
3130
3138
  operation,
3131
3139
  message: message2,
3132
3140
  raw: resultOrError.raw
@@ -3135,7 +3143,7 @@ function normalizeAthenaError(resultOrError, context) {
3135
3143
  if (isAthenaGatewayError(resultOrError)) {
3136
3144
  const details = resultOrError.toDetails();
3137
3145
  const operation = context?.operation ?? operationFromDetails(details);
3138
- const table = context?.table ?? extractTable(resultOrError.message);
3146
+ const table2 = context?.table ?? extractTable(resultOrError.message);
3139
3147
  const constraint = extractConstraint(resultOrError.message);
3140
3148
  const kind2 = classifyKind(resultOrError.status, resultOrError.code, resultOrError.message);
3141
3149
  const code = toAthenaErrorCode(kind2, resultOrError.status, resultOrError.code);
@@ -3147,7 +3155,7 @@ function normalizeAthenaError(resultOrError, context) {
3147
3155
  retryable: isRetryable(kind2, resultOrError.status),
3148
3156
  status: resultOrError.status,
3149
3157
  constraint,
3150
- table,
3158
+ table: table2,
3151
3159
  operation,
3152
3160
  message: resultOrError.message,
3153
3161
  raw: resultOrError
@@ -3343,23 +3351,24 @@ async function withRetry(config, fn) {
3343
3351
  // src/db/module.ts
3344
3352
  function createDbModule(input) {
3345
3353
  const db = {
3346
- from(table, options) {
3347
- return input.from(table, options);
3348
- },
3349
- select(table, columns, options) {
3350
- return input.from(table).select(columns, options);
3354
+ from: input.from,
3355
+ select(table2, first, second) {
3356
+ if (first && typeof first === "object" && !Array.isArray(first)) {
3357
+ return input.from(table2).select(void 0, first);
3358
+ }
3359
+ return input.from(table2).select(first, second);
3351
3360
  },
3352
- insert(table, values, options) {
3353
- return Array.isArray(values) ? input.from(table).insert(values, options) : input.from(table).insert(values, options);
3361
+ insert(table2, values, options) {
3362
+ return Array.isArray(values) ? input.from(table2).insert(values, options) : input.from(table2).insert(values, options);
3354
3363
  },
3355
- upsert(table, values, options) {
3356
- return Array.isArray(values) ? input.from(table).upsert(values, options) : input.from(table).upsert(values, options);
3364
+ upsert(table2, values, options) {
3365
+ return Array.isArray(values) ? input.from(table2).upsert(values, options) : input.from(table2).upsert(values, options);
3357
3366
  },
3358
- update(table, values, options) {
3359
- return input.from(table).update(values, options);
3367
+ update(table2, values, options) {
3368
+ return input.from(table2).update(values, options);
3360
3369
  },
3361
- delete(table, options) {
3362
- return input.from(table).delete(options);
3370
+ delete(table2, options) {
3371
+ return input.from(table2).delete(options);
3363
3372
  },
3364
3373
  rpc(fn, args, options) {
3365
3374
  return input.rpc(fn, args, options);
@@ -3371,6 +3380,344 @@ function createDbModule(input) {
3371
3380
  return db;
3372
3381
  }
3373
3382
 
3383
+ // src/storage/file.ts
3384
+ function createStorageFileModule(base, config = {}) {
3385
+ const upload = async (input, options) => {
3386
+ const sources = normalizeUploadSources(input);
3387
+ validateUploadConstraints(sources, input);
3388
+ const uploadRequests = sources.map((source, index) => {
3389
+ const storageKey = resolveUploadStorageKey(input, source, index, options, config);
3390
+ return {
3391
+ source,
3392
+ uploadRequest: {
3393
+ s3_id: input.s3_id,
3394
+ bucket: input.bucket,
3395
+ storage_key: storageKey,
3396
+ name: input.name ?? source.fileName,
3397
+ original_name: input.original_name ?? source.fileName,
3398
+ resource_id: input.resource_id ?? input.resourceId,
3399
+ mime_type: input.mime_type ?? source.contentType,
3400
+ content_type: input.content_type ?? source.contentType,
3401
+ size_bytes: source.sizeBytes,
3402
+ public: input.public,
3403
+ metadata: input.metadata
3404
+ }
3405
+ };
3406
+ });
3407
+ input.onProgress?.(createProgressSnapshot("preparing", sources, 0, 0, 0));
3408
+ const uploadUrls = uploadRequests.length === 1 ? [await base.createStorageUploadUrl(uploadRequests[0].uploadRequest, options)] : (await base.createStorageUploadUrls({ files: uploadRequests.map((request) => request.uploadRequest) }, options)).files;
3409
+ const aggregateLoaded = new Array(uploadRequests.length).fill(0);
3410
+ const uploaded = [];
3411
+ for (let index = 0; index < uploadRequests.length; index += 1) {
3412
+ const request = uploadRequests[index];
3413
+ const uploadUrl = uploadUrls[index];
3414
+ const response = await putUploadBody(uploadUrl.upload.url, request.source, input, options, (progress) => {
3415
+ aggregateLoaded[index] = progress.loaded;
3416
+ input.onProgress?.(createProgressSnapshot("uploading", sources, index, progress.loaded, sum(aggregateLoaded)));
3417
+ });
3418
+ uploaded.push({
3419
+ file: uploadUrl.file,
3420
+ upload: uploadUrl.upload,
3421
+ source: request.source.source,
3422
+ fileName: request.source.fileName,
3423
+ storage_key: request.uploadRequest.storage_key,
3424
+ response
3425
+ });
3426
+ aggregateLoaded[index] = request.source.sizeBytes;
3427
+ input.onProgress?.(createProgressSnapshot("complete", sources, index, request.source.sizeBytes, sum(aggregateLoaded)));
3428
+ }
3429
+ return {
3430
+ files: uploaded,
3431
+ count: uploaded.length
3432
+ };
3433
+ };
3434
+ const download = ((input, queryOrOptions, maybeOptions) => {
3435
+ const { fileIds, query, options } = normalizeDownloadArgs(input, queryOrOptions, maybeOptions);
3436
+ const downloads = fileIds.map((fileId) => base.getStorageFileProxy(fileId, query, options));
3437
+ return Array.isArray(input) || isRecord5(input) && Array.isArray(input.fileIds) ? Promise.all(downloads) : downloads[0];
3438
+ });
3439
+ const deleteFile = ((input, options) => {
3440
+ if (Array.isArray(input)) {
3441
+ return Promise.all(input.map((fileId) => base.deleteStorageFile(fileId, options)));
3442
+ }
3443
+ return base.deleteStorageFile(input, options);
3444
+ });
3445
+ return {
3446
+ upload,
3447
+ download,
3448
+ list(input, options) {
3449
+ const prefix = resolveStoragePath(input.prefix ?? "", input, options, config);
3450
+ return base.listStorageFiles(
3451
+ {
3452
+ s3_id: input.s3_id,
3453
+ prefix
3454
+ },
3455
+ options
3456
+ );
3457
+ },
3458
+ delete: deleteFile
3459
+ };
3460
+ }
3461
+ function resolveStoragePath(path, input, options, config = {}) {
3462
+ const context = createPathContext(input, options, config);
3463
+ const prefixPath = input.prefixPath ?? config.prefixPath;
3464
+ const prefix = typeof prefixPath === "function" ? prefixPath(context) : prefixPath;
3465
+ return joinStoragePath(renderStorageTemplate(prefix ?? "", context), renderStorageTemplate(path, context));
3466
+ }
3467
+ function resolveUploadStorageKey(input, source, index, options, config) {
3468
+ const explicitKey = input.storage_key ?? input.storageKey;
3469
+ const keyTemplate = input.storageKeyTemplate;
3470
+ const fallbackName = source.fileName;
3471
+ const context = createPathContext(input, options, config);
3472
+ const key = keyTemplate ? renderStorageTemplate(keyTemplate, {
3473
+ ...context,
3474
+ vars: {
3475
+ ...context.vars,
3476
+ index,
3477
+ fileName: source.fileName,
3478
+ name: source.fileName
3479
+ }
3480
+ }) : explicitKey ?? fallbackName;
3481
+ return resolveStoragePath(key, input, options, config);
3482
+ }
3483
+ function normalizeUploadSources(input) {
3484
+ const files = toArray(input.files);
3485
+ if (files.length === 0) {
3486
+ throw new Error("athena.storage.file.upload requires at least one file");
3487
+ }
3488
+ return files.map((source, index) => {
3489
+ const fileName = input.fileName ?? sourceName(source) ?? `file-${index + 1}`;
3490
+ const sizeBytes = sourceSize(source);
3491
+ const contentType = input.content_type ?? input.mime_type ?? sourceContentType(source);
3492
+ return {
3493
+ source,
3494
+ fileName,
3495
+ sizeBytes,
3496
+ contentType
3497
+ };
3498
+ });
3499
+ }
3500
+ function validateUploadConstraints(sources, input) {
3501
+ const maxFiles = input.maxFiles ?? 1;
3502
+ if (sources.length > maxFiles) {
3503
+ throw new Error(`athena.storage.file.upload accepts at most ${maxFiles} file${maxFiles === 1 ? "" : "s"} for this call`);
3504
+ }
3505
+ const maxFileSizeBytes = input.maxFileSizeBytes ?? (input.maxFileSizeMb === void 0 ? void 0 : Math.floor(input.maxFileSizeMb * 1024 * 1024));
3506
+ if (maxFileSizeBytes !== void 0) {
3507
+ const tooLarge = sources.find((source) => source.sizeBytes > maxFileSizeBytes);
3508
+ if (tooLarge) {
3509
+ throw new Error(`athena.storage.file.upload rejected ${tooLarge.fileName}: file exceeds ${maxFileSizeBytes} bytes`);
3510
+ }
3511
+ }
3512
+ const allowedExtensions = normalizeExtensions(input.allowedExtensions ?? input.extensions);
3513
+ if (allowedExtensions.size > 0) {
3514
+ const invalid = sources.find((source) => !allowedExtensions.has(fileExtension(source.fileName)));
3515
+ if (invalid) {
3516
+ throw new Error(`athena.storage.file.upload rejected ${invalid.fileName}: extension is not allowed`);
3517
+ }
3518
+ }
3519
+ }
3520
+ async function putUploadBody(url, source, input, options, onProgress) {
3521
+ const headers = new Headers(input.uploadHeaders);
3522
+ if (source.contentType && !headers.has("Content-Type")) {
3523
+ headers.set("Content-Type", source.contentType);
3524
+ }
3525
+ if (typeof XMLHttpRequest !== "undefined") {
3526
+ return putUploadBodyWithXhr(url, source, headers, options, onProgress);
3527
+ }
3528
+ onProgress({ loaded: 0 });
3529
+ const response = await fetch(url, {
3530
+ method: "PUT",
3531
+ headers,
3532
+ body: source.source,
3533
+ signal: options?.signal
3534
+ });
3535
+ if (!response.ok) {
3536
+ throw new Error(`athena.storage.file.upload failed with status ${response.status}`);
3537
+ }
3538
+ onProgress({ loaded: source.sizeBytes });
3539
+ return response;
3540
+ }
3541
+ function putUploadBodyWithXhr(url, source, headers, options, onProgress) {
3542
+ const Xhr = XMLHttpRequest;
3543
+ if (Xhr === void 0) {
3544
+ return Promise.reject(new Error("athena.storage.file.upload requires XMLHttpRequest in this runtime"));
3545
+ }
3546
+ return new Promise((resolve3, reject) => {
3547
+ const xhr = new Xhr();
3548
+ const abort = () => xhr.abort();
3549
+ xhr.open("PUT", url);
3550
+ headers.forEach((value, key) => xhr.setRequestHeader(key, value));
3551
+ xhr.upload.onprogress = (event) => {
3552
+ onProgress({ loaded: event.loaded });
3553
+ };
3554
+ xhr.onload = () => {
3555
+ if (options?.signal) {
3556
+ options.signal.removeEventListener("abort", abort);
3557
+ }
3558
+ if (xhr.status < 200 || xhr.status >= 300) {
3559
+ reject(new Error(`athena.storage.file.upload failed with status ${xhr.status}`));
3560
+ return;
3561
+ }
3562
+ onProgress({ loaded: source.sizeBytes });
3563
+ resolve3(new Response(xhr.response, {
3564
+ status: xhr.status,
3565
+ statusText: xhr.statusText,
3566
+ headers: parseXhrHeaders(xhr.getAllResponseHeaders())
3567
+ }));
3568
+ };
3569
+ xhr.onerror = () => {
3570
+ if (options?.signal) {
3571
+ options.signal.removeEventListener("abort", abort);
3572
+ }
3573
+ reject(new Error("athena.storage.file.upload failed with a network error"));
3574
+ };
3575
+ xhr.onabort = () => {
3576
+ if (options?.signal) {
3577
+ options.signal.removeEventListener("abort", abort);
3578
+ }
3579
+ reject(new DOMException("Upload aborted", "AbortError"));
3580
+ };
3581
+ if (options?.signal) {
3582
+ if (options.signal.aborted) {
3583
+ abort();
3584
+ return;
3585
+ }
3586
+ options.signal.addEventListener("abort", abort, { once: true });
3587
+ }
3588
+ xhr.send(source.source);
3589
+ });
3590
+ }
3591
+ function normalizeDownloadArgs(input, queryOrOptions, maybeOptions) {
3592
+ if (typeof input === "string") {
3593
+ return { fileIds: [input], query: queryOrOptions, options: maybeOptions };
3594
+ }
3595
+ if (Array.isArray(input)) {
3596
+ return { fileIds: [...input], query: queryOrOptions, options: maybeOptions };
3597
+ }
3598
+ const downloadInput = input;
3599
+ const { fileId, fileIds, ...query } = downloadInput;
3600
+ return {
3601
+ fileIds: fileIds ? [...fileIds] : fileId ? [fileId] : [],
3602
+ query,
3603
+ options: queryOrOptions
3604
+ };
3605
+ }
3606
+ function createPathContext(input, options, config) {
3607
+ const organizationId = input.organizationId ?? input.organization_id ?? options?.organizationId ?? void 0;
3608
+ const userId = input.userId ?? input.user_id ?? options?.userId ?? void 0;
3609
+ const resourceId = input.resourceId ?? input.resource_id ?? void 0;
3610
+ const vars = {
3611
+ ...config.vars ?? {},
3612
+ ...input.vars ?? {}
3613
+ };
3614
+ if (organizationId !== void 0) {
3615
+ vars.organizationId = organizationId;
3616
+ vars.organization_id = organizationId;
3617
+ }
3618
+ if (userId !== void 0) {
3619
+ vars.userId = userId;
3620
+ vars.user_id = userId;
3621
+ }
3622
+ if (resourceId !== void 0) {
3623
+ vars.resourceId = resourceId;
3624
+ vars.resource_id = resourceId;
3625
+ }
3626
+ return {
3627
+ vars,
3628
+ env: {
3629
+ ...readProcessEnv(),
3630
+ ...config.env ?? {},
3631
+ ...input.env ?? {}
3632
+ },
3633
+ organizationId,
3634
+ organization_id: organizationId,
3635
+ userId,
3636
+ user_id: userId,
3637
+ resourceId,
3638
+ resource_id: resourceId
3639
+ };
3640
+ }
3641
+ function renderStorageTemplate(template, context) {
3642
+ return template.replace(/\$\{([^}]+)\}|\{([^}]+)\}/g, (_match, shellToken, braceToken) => {
3643
+ const token = (shellToken ?? braceToken ?? "").trim();
3644
+ if (!token) return "";
3645
+ const value = resolveTemplateToken(token, context);
3646
+ return value === void 0 || value === null ? "" : String(value);
3647
+ });
3648
+ }
3649
+ function resolveTemplateToken(token, context) {
3650
+ if (token.startsWith("env.")) {
3651
+ return context.env[token.slice(4)];
3652
+ }
3653
+ if (token in context.vars) {
3654
+ return context.vars[token];
3655
+ }
3656
+ return context.env[token];
3657
+ }
3658
+ function joinStoragePath(...parts) {
3659
+ return parts.map((part) => part.trim().replace(/^\/+|\/+$/g, "")).filter(Boolean).join("/");
3660
+ }
3661
+ function toArray(files) {
3662
+ if (isUploadSource(files)) return [files];
3663
+ return Array.from(files);
3664
+ }
3665
+ function isUploadSource(value) {
3666
+ return value instanceof Blob || value instanceof ArrayBuffer || value instanceof Uint8Array;
3667
+ }
3668
+ function sourceName(source) {
3669
+ return isRecord5(source) && typeof source.name === "string" && source.name.trim() ? source.name.trim() : void 0;
3670
+ }
3671
+ function sourceSize(source) {
3672
+ if (source instanceof Blob) return source.size;
3673
+ return source.byteLength;
3674
+ }
3675
+ function sourceContentType(source) {
3676
+ return source instanceof Blob && source.type.trim() ? source.type.trim() : void 0;
3677
+ }
3678
+ function normalizeExtensions(extensions) {
3679
+ return new Set((extensions ?? []).map((extension) => extension.replace(/^\./, "").toLowerCase()).filter(Boolean));
3680
+ }
3681
+ function fileExtension(fileName) {
3682
+ const lastDot = fileName.lastIndexOf(".");
3683
+ return lastDot === -1 ? "" : fileName.slice(lastDot + 1).toLowerCase();
3684
+ }
3685
+ function createProgressSnapshot(phase, sources, fileIndex, loaded, aggregateLoaded) {
3686
+ const total = sources[fileIndex]?.sizeBytes ?? 0;
3687
+ const aggregateTotal = sources.reduce((totalBytes, source) => totalBytes + source.sizeBytes, 0);
3688
+ return {
3689
+ phase,
3690
+ fileIndex,
3691
+ fileCount: sources.length,
3692
+ fileName: sources[fileIndex]?.fileName ?? "",
3693
+ loaded,
3694
+ total,
3695
+ percent: total > 0 ? Math.round(loaded / total * 100) : 100,
3696
+ aggregateLoaded,
3697
+ aggregateTotal,
3698
+ aggregatePercent: aggregateTotal > 0 ? Math.round(aggregateLoaded / aggregateTotal * 100) : 100
3699
+ };
3700
+ }
3701
+ function sum(values) {
3702
+ return values.reduce((total, value) => total + value, 0);
3703
+ }
3704
+ function parseXhrHeaders(raw) {
3705
+ const headers = new Headers();
3706
+ for (const line of raw.trim().split(/[\r\n]+/)) {
3707
+ const index = line.indexOf(":");
3708
+ if (index === -1) continue;
3709
+ headers.set(line.slice(0, index).trim(), line.slice(index + 1).trim());
3710
+ }
3711
+ return headers;
3712
+ }
3713
+ function readProcessEnv() {
3714
+ const processLike = globalThis.process;
3715
+ return processLike?.env ?? {};
3716
+ }
3717
+ function isRecord5(value) {
3718
+ return Boolean(value) && typeof value === "object";
3719
+ }
3720
+
3374
3721
  // src/storage/module.ts
3375
3722
  var storageSdkManifest = {
3376
3723
  namespace: "storage",
@@ -3579,7 +3926,7 @@ var AthenaStorageError = class extends Error {
3579
3926
  };
3580
3927
  }
3581
3928
  };
3582
- function isRecord5(value) {
3929
+ function isRecord6(value) {
3583
3930
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
3584
3931
  }
3585
3932
  function causeToString(cause) {
@@ -3690,11 +4037,20 @@ function appendQuery(path, query) {
3690
4037
  function storagePath(path) {
3691
4038
  return path;
3692
4039
  }
4040
+ function resolveStorageEndpointPath(endpoint, runtimeOptions) {
4041
+ if (!runtimeOptions?.stripBasePath) {
4042
+ return endpoint;
4043
+ }
4044
+ const [pathname, queryText] = String(endpoint).split("?", 2);
4045
+ const trimmedPathname = pathname.startsWith("/storage/") ? pathname.slice("/storage".length) : pathname === "/storage" ? "/" : pathname;
4046
+ const resolvedPath = trimmedPathname.startsWith("/") ? trimmedPathname : `/${trimmedPathname}`;
4047
+ return storagePath(queryText ? `${resolvedPath}?${queryText}` : resolvedPath);
4048
+ }
3693
4049
  function withPathParam(path, name, value) {
3694
4050
  return path.replace(`{${name}}`, encodeURIComponent(value));
3695
4051
  }
3696
4052
  function resolveErrorMessage3(payload, fallback) {
3697
- if (isRecord5(payload)) {
4053
+ if (isRecord6(payload)) {
3698
4054
  const message = payload.message ?? payload.error ?? payload.details;
3699
4055
  if (typeof message === "string" && message.trim()) {
3700
4056
  return message.trim();
@@ -3706,12 +4062,12 @@ function resolveErrorMessage3(payload, fallback) {
3706
4062
  return fallback;
3707
4063
  }
3708
4064
  function resolveErrorHint2(payload) {
3709
- if (!isRecord5(payload)) return void 0;
4065
+ if (!isRecord6(payload)) return void 0;
3710
4066
  const hint = payload.hint ?? payload.suggestion;
3711
4067
  return typeof hint === "string" && hint.trim() ? hint.trim() : void 0;
3712
4068
  }
3713
4069
  function resolveErrorCause(payload) {
3714
- if (!isRecord5(payload)) return void 0;
4070
+ if (!isRecord6(payload)) return void 0;
3715
4071
  const cause = payload.cause ?? payload.reason;
3716
4072
  return typeof cause === "string" && cause.trim() ? cause.trim() : void 0;
3717
4073
  }
@@ -3728,8 +4084,8 @@ async function callStorageEndpoint(gateway, endpoint, method, envelope, payload,
3728
4084
  let url;
3729
4085
  let headers;
3730
4086
  try {
3731
- const baseUrl = options?.baseUrl ? normalizeAthenaGatewayBaseUrl(options.baseUrl) : gateway.baseUrl;
3732
- url = buildAthenaGatewayUrl(baseUrl, endpoint);
4087
+ const baseUrl = options?.baseUrl ? normalizeAthenaGatewayBaseUrl(options.baseUrl) : runtimeOptions?.baseUrl ? normalizeAthenaGatewayBaseUrl(runtimeOptions.baseUrl) : gateway.baseUrl;
4088
+ url = buildAthenaGatewayUrl(baseUrl, resolveStorageEndpointPath(endpoint, runtimeOptions));
3733
4089
  headers = gateway.buildHeaders(options);
3734
4090
  } catch (error) {
3735
4091
  return rejectStorageError(
@@ -3830,7 +4186,7 @@ async function callStorageEndpoint(gateway, endpoint, method, envelope, payload,
3830
4186
  );
3831
4187
  }
3832
4188
  if (envelope === "athena") {
3833
- if (!isRecord5(parsedBody.parsed) || !("data" in parsedBody.parsed)) {
4189
+ if (!isRecord6(parsedBody.parsed) || !("data" in parsedBody.parsed)) {
3834
4190
  return rejectStorageError(
3835
4191
  {
3836
4192
  code: "INVALID_ATHENA_ENVELOPE",
@@ -3853,8 +4209,8 @@ async function callStorageBinaryEndpoint(gateway, endpoint, method, options, run
3853
4209
  let url;
3854
4210
  let headers;
3855
4211
  try {
3856
- const baseUrl = options?.baseUrl ? normalizeAthenaGatewayBaseUrl(options.baseUrl) : gateway.baseUrl;
3857
- url = buildAthenaGatewayUrl(baseUrl, endpoint);
4212
+ const baseUrl = options?.baseUrl ? normalizeAthenaGatewayBaseUrl(options.baseUrl) : runtimeOptions?.baseUrl ? normalizeAthenaGatewayBaseUrl(runtimeOptions.baseUrl) : gateway.baseUrl;
4213
+ url = buildAthenaGatewayUrl(baseUrl, resolveStorageEndpointPath(endpoint, runtimeOptions));
3858
4214
  headers = gateway.buildHeaders(options);
3859
4215
  } catch (error) {
3860
4216
  return rejectStorageError(
@@ -3938,129 +4294,678 @@ async function callStorageBinaryEndpoint(gateway, endpoint, method, options, run
3938
4294
  runtimeOptions
3939
4295
  );
3940
4296
  }
3941
- function createStorageModule(gateway, runtimeOptions) {
4297
+ function isBlobBody(body) {
4298
+ return typeof Blob !== "undefined" && body instanceof Blob;
4299
+ }
4300
+ function isReadableStreamBody(body) {
4301
+ return typeof ReadableStream !== "undefined" && body instanceof ReadableStream;
4302
+ }
4303
+ async function putPresignedUploadBody(uploadUrl, uploadHeaders, body, options) {
4304
+ const headers = new Headers(uploadHeaders);
4305
+ Object.entries(options?.headers ?? {}).forEach(([key, value]) => headers.set(key, value));
4306
+ if (!headers.has("Content-Type") && isBlobBody(body) && body.type) {
4307
+ headers.set("Content-Type", body.type);
4308
+ }
4309
+ const init = {
4310
+ method: "PUT",
4311
+ headers,
4312
+ body,
4313
+ signal: options?.signal
4314
+ };
4315
+ if (isReadableStreamBody(body)) {
4316
+ init.duplex = "half";
4317
+ }
4318
+ return fetch(uploadUrl, init);
4319
+ }
4320
+ function attachManagedUpload(upload) {
4321
+ const headers = {};
4322
+ return {
4323
+ ...upload,
4324
+ method: "PUT",
4325
+ headers,
4326
+ expiresAt: upload.expires_at,
4327
+ put(body, options) {
4328
+ return putPresignedUploadBody(upload.url, headers, body, options);
4329
+ }
4330
+ };
4331
+ }
4332
+ function attachUploadHelper(response) {
4333
+ return {
4334
+ ...response,
4335
+ upload: attachManagedUpload(response.upload)
4336
+ };
4337
+ }
4338
+ function attachUploadHelpers(response) {
4339
+ return {
4340
+ files: response.files.map(attachUploadHelper)
4341
+ };
4342
+ }
4343
+ function normalizeUploadUrlRequest(input) {
4344
+ const s3_id = input.s3_id ?? input.s3Id;
4345
+ const storage_key = input.storage_key ?? input.storageKey;
4346
+ if (!s3_id?.trim()) {
4347
+ throw new Error("athena.storage.file.upload requires s3_id or s3Id");
4348
+ }
4349
+ if (!storage_key?.trim()) {
4350
+ throw new Error("athena.storage.file.upload requires storage_key or storageKey");
4351
+ }
4352
+ const fileName = input.fileName?.trim();
4353
+ const originalName = input.originalName?.trim();
3942
4354
  return {
4355
+ s3_id,
4356
+ bucket: input.bucket,
4357
+ storage_key,
4358
+ name: input.name ?? fileName,
4359
+ original_name: input.original_name ?? originalName ?? fileName,
4360
+ resource_id: input.resource_id ?? input.resourceId,
4361
+ mime_type: input.mime_type ?? input.mimeType,
4362
+ content_type: input.content_type ?? input.contentType,
4363
+ size_bytes: input.size_bytes ?? input.sizeBytes,
4364
+ file_id: input.file_id ?? input.fileId,
4365
+ public: input.public,
4366
+ visibility: input.visibility,
4367
+ metadata: input.metadata
4368
+ };
4369
+ }
4370
+ async function callStorageUploadBinaryEndpoint(gateway, endpoint, body, options, runtimeOptions) {
4371
+ let url;
4372
+ let headers;
4373
+ try {
4374
+ const baseUrl = options?.baseUrl ? normalizeAthenaGatewayBaseUrl(options.baseUrl) : runtimeOptions?.baseUrl ? normalizeAthenaGatewayBaseUrl(runtimeOptions.baseUrl) : gateway.baseUrl;
4375
+ url = buildAthenaGatewayUrl(baseUrl, resolveStorageEndpointPath(endpoint, runtimeOptions));
4376
+ headers = gateway.buildHeaders(options);
4377
+ } catch (error) {
4378
+ return rejectStorageError(
4379
+ {
4380
+ code: storageCodeFromUnknown(error),
4381
+ message: error instanceof Error ? error.message : `Athena storage PUT ${endpoint} failed before sending the request`,
4382
+ status: isAthenaGatewayError(error) ? error.status : 0,
4383
+ endpoint,
4384
+ method: "PUT",
4385
+ raw: error,
4386
+ requestId: isAthenaGatewayError(error) ? error.requestId : void 0,
4387
+ hint: isAthenaGatewayError(error) ? error.hint : void 0,
4388
+ cause: error
4389
+ },
4390
+ options,
4391
+ runtimeOptions
4392
+ );
4393
+ }
4394
+ delete headers["Content-Type"];
4395
+ delete headers["content-type"];
4396
+ if (isBlobBody(body) && body.type) {
4397
+ headers["Content-Type"] = body.type;
4398
+ }
4399
+ const requestInit = {
4400
+ method: "PUT",
4401
+ headers,
4402
+ body,
4403
+ signal: options?.signal
4404
+ };
4405
+ if (isReadableStreamBody(body)) {
4406
+ requestInit.duplex = "half";
4407
+ }
4408
+ let response;
4409
+ try {
4410
+ response = await fetch(url, requestInit);
4411
+ } catch (error) {
4412
+ const message = error instanceof Error ? error.message : String(error);
4413
+ return rejectStorageError(
4414
+ {
4415
+ code: "NETWORK_ERROR",
4416
+ message: `Network error while calling Athena storage PUT ${endpoint}: ${message}`,
4417
+ status: 0,
4418
+ endpoint,
4419
+ method: "PUT",
4420
+ cause: error
4421
+ },
4422
+ options,
4423
+ runtimeOptions
4424
+ );
4425
+ }
4426
+ let rawText;
4427
+ try {
4428
+ rawText = await response.text();
4429
+ } catch (error) {
4430
+ return rejectStorageError(
4431
+ {
4432
+ code: "NETWORK_ERROR",
4433
+ message: `Athena storage PUT ${endpoint} response body could not be read`,
4434
+ status: response.status,
4435
+ endpoint,
4436
+ method: "PUT",
4437
+ requestId: headerValue(response.headers, ["x-athena-request-id", "x-request-id", "request-id"]),
4438
+ cause: error
4439
+ },
4440
+ options,
4441
+ runtimeOptions
4442
+ );
4443
+ }
4444
+ const parsedBody = parseResponseBody3(rawText ?? "", response.headers.get("content-type"));
4445
+ const requestId = headerValue(response.headers, ["x-athena-request-id", "x-request-id", "request-id"]);
4446
+ if (parsedBody.parseFailed) {
4447
+ return rejectStorageError(
4448
+ {
4449
+ code: "INVALID_JSON",
4450
+ message: `Athena storage PUT ${endpoint} returned malformed JSON`,
4451
+ status: response.status,
4452
+ endpoint,
4453
+ method: "PUT",
4454
+ requestId,
4455
+ raw: parsedBody.parsed
4456
+ },
4457
+ options,
4458
+ runtimeOptions
4459
+ );
4460
+ }
4461
+ if (!response.ok) {
4462
+ return rejectStorageError(
4463
+ {
4464
+ code: "HTTP_ERROR",
4465
+ message: resolveErrorMessage3(
4466
+ parsedBody.parsed,
4467
+ `Athena storage PUT ${endpoint} failed with status ${response.status}`
4468
+ ),
4469
+ status: response.status,
4470
+ endpoint,
4471
+ method: "PUT",
4472
+ requestId,
4473
+ hint: resolveErrorHint2(parsedBody.parsed),
4474
+ cause: resolveErrorCause(parsedBody.parsed),
4475
+ raw: parsedBody.parsed
4476
+ },
4477
+ options,
4478
+ runtimeOptions
4479
+ );
4480
+ }
4481
+ if (!isRecord6(parsedBody.parsed) || !("data" in parsedBody.parsed)) {
4482
+ return rejectStorageError(
4483
+ {
4484
+ code: "INVALID_ATHENA_ENVELOPE",
4485
+ message: `Athena storage PUT ${endpoint} returned an invalid Athena envelope`,
4486
+ status: response.status,
4487
+ endpoint,
4488
+ method: "PUT",
4489
+ requestId,
4490
+ raw: parsedBody.parsed
4491
+ },
4492
+ options,
4493
+ runtimeOptions
4494
+ );
4495
+ }
4496
+ return parsedBody.parsed.data;
4497
+ }
4498
+ function createStorageModule(gateway, runtimeOptions) {
4499
+ const resolvedRuntimeOptions = runtimeOptions;
4500
+ const callRaw = (path, method, payload, options) => callStorageEndpoint(
4501
+ gateway,
4502
+ storagePath(path),
4503
+ method,
4504
+ "raw",
4505
+ payload,
4506
+ options,
4507
+ resolvedRuntimeOptions
4508
+ );
4509
+ const callAthena2 = (path, method, payload, options) => callStorageEndpoint(
4510
+ gateway,
4511
+ storagePath(path),
4512
+ method,
4513
+ "athena",
4514
+ payload,
4515
+ options,
4516
+ resolvedRuntimeOptions
4517
+ );
4518
+ const base = {
3943
4519
  listStorageCatalogs(options) {
3944
- return callStorageEndpoint(gateway, storagePath("/storage/catalogs"), "GET", "raw", void 0, options, runtimeOptions);
4520
+ return callRaw("/storage/catalogs", "GET", void 0, options);
3945
4521
  },
3946
4522
  createStorageCatalog(input, options) {
3947
- return callStorageEndpoint(gateway, storagePath("/storage/catalogs"), "POST", "raw", input, options, runtimeOptions);
4523
+ return callRaw("/storage/catalogs", "POST", input, options);
3948
4524
  },
3949
4525
  updateStorageCatalog(id, input, options) {
3950
- return callStorageEndpoint(
3951
- gateway,
3952
- storagePath(withPathParam("/storage/catalogs/{id}", "id", id)),
3953
- "PATCH",
3954
- "raw",
3955
- input,
3956
- options,
3957
- runtimeOptions
3958
- );
4526
+ return callRaw(withPathParam("/storage/catalogs/{id}", "id", id), "PATCH", input, options);
3959
4527
  },
3960
4528
  deleteStorageCatalog(id, options) {
3961
- return callStorageEndpoint(
3962
- gateway,
3963
- storagePath(withPathParam("/storage/catalogs/{id}", "id", id)),
3964
- "DELETE",
3965
- "raw",
3966
- void 0,
3967
- options,
3968
- runtimeOptions
3969
- );
4529
+ return callRaw(withPathParam("/storage/catalogs/{id}", "id", id), "DELETE", void 0, options);
3970
4530
  },
3971
4531
  listStorageCredentials(options) {
3972
- return callStorageEndpoint(gateway, storagePath("/storage/credentials"), "GET", "raw", void 0, options, runtimeOptions);
4532
+ return callRaw("/storage/credentials", "GET", void 0, options);
3973
4533
  },
3974
4534
  createStorageUploadUrl(input, options) {
3975
- return callStorageEndpoint(
3976
- gateway,
3977
- storagePath("/storage/files/upload-url"),
3978
- "POST",
3979
- "athena",
3980
- input,
3981
- options,
3982
- runtimeOptions
3983
- );
4535
+ return callAthena2("/storage/files/upload-url", "POST", input, options);
3984
4536
  },
3985
4537
  createStorageUploadUrls(input, options) {
3986
- return callStorageEndpoint(
3987
- gateway,
3988
- storagePath("/storage/files/upload-urls"),
3989
- "POST",
3990
- "athena",
3991
- input,
3992
- options,
3993
- runtimeOptions
3994
- );
4538
+ return callAthena2("/storage/files/upload-urls", "POST", input, options);
3995
4539
  },
3996
4540
  listStorageFiles(input, options) {
3997
- return callStorageEndpoint(gateway, storagePath("/storage/files/list"), "POST", "athena", input, options, runtimeOptions);
4541
+ return callAthena2("/storage/files/list", "POST", input, options);
3998
4542
  },
3999
4543
  getStorageFile(fileId, options) {
4000
- return callStorageEndpoint(
4001
- gateway,
4002
- storagePath(withPathParam("/storage/files/{file_id}", "file_id", fileId)),
4003
- "GET",
4004
- "athena",
4005
- void 0,
4006
- options,
4007
- runtimeOptions
4008
- );
4544
+ return callAthena2(withPathParam("/storage/files/{file_id}", "file_id", fileId), "GET", void 0, options);
4009
4545
  },
4010
4546
  getStorageFileUrl(fileId, query, options) {
4011
4547
  const path = appendQuery(
4012
4548
  withPathParam("/storage/files/{file_id}/url", "file_id", fileId),
4013
4549
  query
4014
4550
  );
4015
- return callStorageEndpoint(gateway, storagePath(path), "GET", "athena", void 0, options, runtimeOptions);
4551
+ return callAthena2(path, "GET", void 0, options);
4016
4552
  },
4017
4553
  getStorageFileProxy(fileId, query, options) {
4018
4554
  const path = appendQuery(
4019
4555
  withPathParam("/storage/files/{file_id}/proxy", "file_id", fileId),
4020
4556
  query
4021
4557
  );
4022
- return callStorageBinaryEndpoint(gateway, storagePath(path), "GET", options, runtimeOptions);
4558
+ return callStorageBinaryEndpoint(gateway, storagePath(path), "GET", options, resolvedRuntimeOptions);
4023
4559
  },
4024
4560
  updateStorageFile(fileId, input, options) {
4025
- return callStorageEndpoint(
4026
- gateway,
4027
- storagePath(withPathParam("/storage/files/{file_id}", "file_id", fileId)),
4028
- "PATCH",
4029
- "athena",
4030
- input,
4031
- options,
4032
- runtimeOptions
4033
- );
4561
+ return callAthena2(withPathParam("/storage/files/{file_id}", "file_id", fileId), "PATCH", input, options);
4034
4562
  },
4035
4563
  deleteStorageFile(fileId, options) {
4036
- return callStorageEndpoint(
4037
- gateway,
4038
- storagePath(withPathParam("/storage/files/{file_id}", "file_id", fileId)),
4039
- "DELETE",
4040
- "athena",
4041
- void 0,
4042
- options,
4043
- runtimeOptions
4044
- );
4564
+ return callAthena2(withPathParam("/storage/files/{file_id}", "file_id", fileId), "DELETE", void 0, options);
4045
4565
  },
4046
4566
  setStorageFileVisibility(fileId, input, options) {
4047
- return callStorageEndpoint(
4567
+ return callAthena2(withPathParam("/storage/files/{file_id}/visibility", "file_id", fileId), "PATCH", input, options);
4568
+ },
4569
+ deleteStorageFolder(input, options) {
4570
+ return callAthena2("/storage/folders/delete", "POST", input, options);
4571
+ },
4572
+ moveStorageFolder(input, options) {
4573
+ return callAthena2("/storage/folders/move", "POST", input, options);
4574
+ }
4575
+ };
4576
+ const fileFacade = createStorageFileModule(base, runtimeOptions);
4577
+ const fileUpload = ((input, options) => {
4578
+ if (isRecord6(input) && "files" in input) {
4579
+ return fileFacade.upload(input, options);
4580
+ }
4581
+ return base.createStorageUploadUrl(
4582
+ normalizeUploadUrlRequest(input),
4583
+ options
4584
+ ).then(attachUploadHelper);
4585
+ });
4586
+ const fileDelete = ((input, options) => fileFacade.delete(input, options));
4587
+ const file = {
4588
+ ...fileFacade,
4589
+ upload: fileUpload,
4590
+ uploadMany(input, options) {
4591
+ return base.createStorageUploadUrls(
4592
+ { files: input.files.map(normalizeUploadUrlRequest) },
4593
+ options
4594
+ ).then(attachUploadHelpers);
4595
+ },
4596
+ confirmUpload(fileId, input, options) {
4597
+ return callAthena2(withPathParam("/storage/files/{file_id}/confirm-upload", "file_id", fileId), "POST", input ?? {}, options);
4598
+ },
4599
+ uploadBinary(fileId, body, options) {
4600
+ return callStorageUploadBinaryEndpoint(
4048
4601
  gateway,
4049
- storagePath(withPathParam("/storage/files/{file_id}/visibility", "file_id", fileId)),
4050
- "PATCH",
4051
- "athena",
4052
- input,
4602
+ storagePath(withPathParam("/storage/files/{file_id}/upload", "file_id", fileId)),
4603
+ body,
4053
4604
  options,
4054
- runtimeOptions
4605
+ resolvedRuntimeOptions
4055
4606
  );
4056
4607
  },
4057
- deleteStorageFolder(input, options) {
4058
- return callStorageEndpoint(gateway, storagePath("/storage/folders/delete"), "POST", "athena", input, options, runtimeOptions);
4608
+ search(input, options) {
4609
+ return callAthena2("/storage/files/search", "POST", input, options);
4059
4610
  },
4060
- moveStorageFolder(input, options) {
4061
- return callStorageEndpoint(gateway, storagePath("/storage/folders/move"), "POST", "athena", input, options, runtimeOptions);
4611
+ get(fileId, options) {
4612
+ return base.getStorageFile(fileId, options);
4613
+ },
4614
+ update(fileId, input, options) {
4615
+ return base.updateStorageFile(fileId, input, options);
4616
+ },
4617
+ delete: fileDelete,
4618
+ deleteMany(input, options) {
4619
+ return callAthena2("/storage/files/delete-many", "POST", input, options);
4620
+ },
4621
+ updateMany(input, options) {
4622
+ return callAthena2("/storage/files/update-many", "POST", input, options);
4623
+ },
4624
+ restore(fileId, options) {
4625
+ return callAthena2(withPathParam("/storage/files/{file_id}/restore", "file_id", fileId), "POST", {}, options);
4626
+ },
4627
+ purge(fileId, options) {
4628
+ return callAthena2(withPathParam("/storage/files/{file_id}/purge", "file_id", fileId), "DELETE", void 0, options);
4629
+ },
4630
+ copy(fileId, input, options) {
4631
+ return callAthena2(withPathParam("/storage/files/{file_id}/copy", "file_id", fileId), "POST", input, options);
4632
+ },
4633
+ url(fileId, query, options) {
4634
+ return base.getStorageFileUrl(fileId, query, options);
4635
+ },
4636
+ publicUrl(fileId, options) {
4637
+ return callAthena2(withPathParam("/storage/files/{file_id}/public-url", "file_id", fileId), "GET", void 0, options);
4638
+ },
4639
+ proxy(fileId, query, options) {
4640
+ return base.getStorageFileProxy(fileId, query, options);
4641
+ },
4642
+ visibility: {
4643
+ set(fileId, input, options) {
4644
+ return base.setStorageFileVisibility(fileId, input, options);
4645
+ },
4646
+ setMany(input, options) {
4647
+ return callAthena2("/storage/files/visibility-many", "POST", input, options);
4648
+ }
4649
+ }
4650
+ };
4651
+ const credentials = {
4652
+ list(options) {
4653
+ return base.listStorageCredentials(options);
4654
+ }
4655
+ };
4656
+ const catalog = {
4657
+ list(options) {
4658
+ return base.listStorageCatalogs(options);
4659
+ },
4660
+ create(input, options) {
4661
+ return base.createStorageCatalog(input, options);
4662
+ },
4663
+ update(id, input, options) {
4664
+ return base.updateStorageCatalog(id, input, options);
4665
+ },
4666
+ delete(id, options) {
4667
+ return base.deleteStorageCatalog(id, options);
4668
+ }
4669
+ };
4670
+ const folder = {
4671
+ list(input, options) {
4672
+ return callAthena2("/storage/folders/list", "POST", input, options);
4673
+ },
4674
+ tree(input, options) {
4675
+ return callAthena2("/storage/folders/tree", "POST", input, options);
4676
+ },
4677
+ delete(input, options) {
4678
+ return base.deleteStorageFolder(input, options);
4679
+ },
4680
+ move(input, options) {
4681
+ return base.moveStorageFolder(input, options);
4682
+ }
4683
+ };
4684
+ const permission = {
4685
+ list(input, options) {
4686
+ return callAthena2("/storage/permissions/list", "POST", input, options);
4687
+ },
4688
+ grant(input, options) {
4689
+ return callAthena2("/storage/permissions/grant", "POST", input, options);
4690
+ },
4691
+ revoke(input, options) {
4692
+ return callAthena2("/storage/permissions/revoke", "POST", input, options);
4693
+ },
4694
+ check(input, options) {
4695
+ return callAthena2("/storage/permissions/check", "POST", input, options);
4696
+ }
4697
+ };
4698
+ const objectFolder = {
4699
+ create(input, options) {
4700
+ return callAthena2("/storage/objects/folder", "POST", input, options);
4701
+ },
4702
+ delete(input, options) {
4703
+ return callAthena2("/storage/objects/folder/delete", "POST", input, options);
4704
+ },
4705
+ rename(input, options) {
4706
+ return callAthena2("/storage/objects/folder/rename", "POST", input, options);
4707
+ }
4708
+ };
4709
+ const object = {
4710
+ list(input, options) {
4711
+ return callAthena2("/storage/objects", "POST", input, options);
4712
+ },
4713
+ head(input, options) {
4714
+ return callAthena2("/storage/objects/head", "POST", input, options);
4715
+ },
4716
+ exists(input, options) {
4717
+ return callAthena2("/storage/objects/exists", "POST", input, options);
4718
+ },
4719
+ validate(input, options) {
4720
+ return callAthena2("/storage/objects/validate", "POST", input, options);
4721
+ },
4722
+ update(input, options) {
4723
+ return callAthena2("/storage/objects/update", "POST", input, options);
4724
+ },
4725
+ copy(input, options) {
4726
+ return callAthena2("/storage/objects/copy", "POST", input, options);
4727
+ },
4728
+ url(input, options) {
4729
+ return callAthena2("/storage/objects/url", "POST", input, options);
4730
+ },
4731
+ publicUrl(input, options) {
4732
+ return callAthena2("/storage/objects/public-url", "POST", input, options);
4733
+ },
4734
+ delete(input, options) {
4735
+ return callAthena2("/storage/objects/delete", "POST", input, options);
4736
+ },
4737
+ uploadUrl(input, options) {
4738
+ return callAthena2("/storage/objects/upload-url", "POST", input, options);
4739
+ },
4740
+ folder: objectFolder
4741
+ };
4742
+ const bucket = {
4743
+ list(input, options) {
4744
+ return callAthena2("/storage/buckets/list", "POST", input, options);
4745
+ },
4746
+ create(input, options) {
4747
+ return callAthena2("/storage/buckets/create", "POST", input, options);
4748
+ },
4749
+ delete(input, options) {
4750
+ return callAthena2("/storage/buckets/delete", "POST", input, options);
4751
+ },
4752
+ cors: {
4753
+ get(input, options) {
4754
+ return callAthena2("/storage/buckets/cors", "POST", input, options);
4755
+ },
4756
+ set(input, options) {
4757
+ return callAthena2("/storage/buckets/cors/set", "POST", input, options);
4758
+ },
4759
+ delete(input, options) {
4760
+ return callAthena2("/storage/buckets/cors/delete", "POST", input, options);
4761
+ }
4062
4762
  }
4063
4763
  };
4764
+ const multipart = {
4765
+ create(input, options) {
4766
+ return callAthena2("/storage/multipart/create", "POST", input, options);
4767
+ },
4768
+ signPart(input, options) {
4769
+ return callAthena2("/storage/multipart/sign-part", "POST", input, options);
4770
+ },
4771
+ complete(input, options) {
4772
+ return callAthena2("/storage/multipart/complete", "POST", input, options);
4773
+ },
4774
+ abort(input, options) {
4775
+ return callAthena2("/storage/multipart/abort", "POST", input, options);
4776
+ },
4777
+ listParts(input, options) {
4778
+ return callAthena2("/storage/multipart/list-parts", "POST", input, options);
4779
+ }
4780
+ };
4781
+ const audit = {
4782
+ list(input, options) {
4783
+ return callAthena2("/storage/audit/list", "POST", input, options);
4784
+ }
4785
+ };
4786
+ return {
4787
+ ...base,
4788
+ credentials,
4789
+ catalog,
4790
+ file,
4791
+ folder,
4792
+ permission,
4793
+ object,
4794
+ bucket,
4795
+ multipart,
4796
+ audit,
4797
+ delete: file.delete
4798
+ };
4799
+ }
4800
+
4801
+ // src/client-builder.ts
4802
+ var DEFAULT_BACKEND = { type: "athena" };
4803
+ function toBackendConfig(value) {
4804
+ if (!value) return DEFAULT_BACKEND;
4805
+ return typeof value === "string" ? { type: value } : value;
4806
+ }
4807
+ function mergeHeaders(current, next) {
4808
+ return {
4809
+ ...current ?? {},
4810
+ ...next
4811
+ };
4812
+ }
4813
+ function mergeAuthClientConfig(current, next) {
4814
+ const merged = {
4815
+ ...current ?? {},
4816
+ ...next
4817
+ };
4818
+ if (current?.headers || next.headers) {
4819
+ merged.headers = mergeHeaders(current?.headers, next.headers ?? {});
4820
+ }
4821
+ return merged;
4822
+ }
4823
+ function mergeExperimentalOptions(current, next) {
4824
+ const merged = {
4825
+ ...current ?? {},
4826
+ ...next
4827
+ };
4828
+ if (current?.traceQueries && typeof current.traceQueries === "object" && next.traceQueries && typeof next.traceQueries === "object") {
4829
+ merged.traceQueries = {
4830
+ ...current.traceQueries,
4831
+ ...next.traceQueries
4832
+ };
4833
+ }
4834
+ if (current?.storage || next.storage) {
4835
+ merged.storage = {
4836
+ ...current?.storage ?? {},
4837
+ ...next.storage ?? {}
4838
+ };
4839
+ }
4840
+ return merged;
4841
+ }
4842
+ function resolveBuilderReturn(builder, storageEnabled, strictEnabled) {
4843
+ return builder;
4844
+ }
4845
+ var AthenaClientBuilderImpl = class {
4846
+ constructor(buildClient) {
4847
+ this.buildClient = buildClient;
4848
+ }
4849
+ rootUrl;
4850
+ apiKey;
4851
+ backendConfig = DEFAULT_BACKEND;
4852
+ clientName;
4853
+ defaultHeaders;
4854
+ authConfig;
4855
+ dbUrlOverride;
4856
+ gatewayUrlOverride;
4857
+ authUrlOverride;
4858
+ storageUrlOverride;
4859
+ experimentalOptions;
4860
+ url(url) {
4861
+ this.rootUrl = url;
4862
+ return this;
4863
+ }
4864
+ key(apiKey) {
4865
+ this.apiKey = apiKey;
4866
+ return this;
4867
+ }
4868
+ backend(backend) {
4869
+ this.backendConfig = toBackendConfig(backend);
4870
+ return this;
4871
+ }
4872
+ client(clientName) {
4873
+ this.clientName = clientName;
4874
+ return this;
4875
+ }
4876
+ headers(headers) {
4877
+ this.defaultHeaders = headers;
4878
+ return this;
4879
+ }
4880
+ auth(config) {
4881
+ this.authConfig = mergeAuthClientConfig(this.authConfig, config);
4882
+ return this;
4883
+ }
4884
+ experimental(options) {
4885
+ this.experimentalOptions = mergeExperimentalOptions(this.experimentalOptions, options);
4886
+ if (options.athenaStorageBackend && options.typecheckColumns) {
4887
+ return resolveBuilderReturn(this);
4888
+ }
4889
+ if (options.athenaStorageBackend) {
4890
+ return resolveBuilderReturn(this);
4891
+ }
4892
+ if (options.typecheckColumns) {
4893
+ return resolveBuilderReturn(this);
4894
+ }
4895
+ return this;
4896
+ }
4897
+ options(options) {
4898
+ if (options.client !== void 0) {
4899
+ this.clientName = options.client;
4900
+ }
4901
+ if (options.backend !== void 0) {
4902
+ this.backendConfig = toBackendConfig(options.backend);
4903
+ }
4904
+ if (options.headers !== void 0) {
4905
+ this.defaultHeaders = mergeHeaders(this.defaultHeaders, options.headers);
4906
+ }
4907
+ if (options.auth !== void 0) {
4908
+ this.authConfig = mergeAuthClientConfig(this.authConfig, options.auth);
4909
+ }
4910
+ if (options.db?.url !== void 0 && options.db.url !== null) {
4911
+ this.dbUrlOverride = options.db.url;
4912
+ }
4913
+ if (options.gateway?.url !== void 0 && options.gateway.url !== null) {
4914
+ this.gatewayUrlOverride = options.gateway.url;
4915
+ }
4916
+ if (options.dbUrl !== void 0 && options.dbUrl !== null) {
4917
+ this.dbUrlOverride = options.dbUrl;
4918
+ }
4919
+ if (options.gatewayUrl !== void 0 && options.gatewayUrl !== null) {
4920
+ this.gatewayUrlOverride = options.gatewayUrl;
4921
+ }
4922
+ if (options.authUrl !== void 0 && options.authUrl !== null) {
4923
+ this.authUrlOverride = options.authUrl;
4924
+ }
4925
+ if (options.storage?.url !== void 0 && options.storage.url !== null) {
4926
+ this.storageUrlOverride = options.storage.url;
4927
+ }
4928
+ if (options.storageUrl !== void 0 && options.storageUrl !== null) {
4929
+ this.storageUrlOverride = options.storageUrl;
4930
+ }
4931
+ if (options.experimental !== void 0) {
4932
+ this.experimentalOptions = mergeExperimentalOptions(this.experimentalOptions, options.experimental);
4933
+ }
4934
+ if (options.experimental?.athenaStorageBackend && options.experimental.typecheckColumns) {
4935
+ return resolveBuilderReturn(this);
4936
+ }
4937
+ if (options.experimental?.athenaStorageBackend) {
4938
+ return resolveBuilderReturn(this);
4939
+ }
4940
+ if (options.experimental?.typecheckColumns) {
4941
+ return resolveBuilderReturn(this);
4942
+ }
4943
+ return this;
4944
+ }
4945
+ build() {
4946
+ if (!this.rootUrl && !this.dbUrlOverride && !this.gatewayUrlOverride || !this.apiKey) {
4947
+ throw new Error(
4948
+ "AthenaClient requires key plus either .url() or a db/gateway override before .build()"
4949
+ );
4950
+ }
4951
+ return this.buildClient({
4952
+ url: this.rootUrl,
4953
+ key: this.apiKey,
4954
+ client: this.clientName,
4955
+ backend: this.backendConfig,
4956
+ headers: this.defaultHeaders,
4957
+ db: this.dbUrlOverride ? { url: this.dbUrlOverride } : void 0,
4958
+ gateway: this.gatewayUrlOverride ? { url: this.gatewayUrlOverride } : void 0,
4959
+ auth: this.authConfig,
4960
+ authUrl: this.authUrlOverride,
4961
+ storage: this.storageUrlOverride ? { url: this.storageUrlOverride } : void 0,
4962
+ storageUrl: this.storageUrlOverride,
4963
+ experimental: this.experimentalOptions
4964
+ });
4965
+ }
4966
+ };
4967
+ function createAthenaClientBuilder(buildClient) {
4968
+ return new AthenaClientBuilderImpl(buildClient);
4064
4969
  }
4065
4970
 
4066
4971
  // src/query-ast.ts
@@ -4090,7 +4995,7 @@ var BOOLEAN_SAFE_OPERATORS = /* @__PURE__ */ new Set([
4090
4995
  "ilike",
4091
4996
  "is"
4092
4997
  ]);
4093
- function isRecord6(value) {
4998
+ function isRecord7(value) {
4094
4999
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
4095
5000
  }
4096
5001
  function isUuidString(value) {
@@ -4103,7 +5008,7 @@ function shouldUseUuidTextComparison(column, value) {
4103
5008
  return typeof value === "string" && isUuidString(value) && isUuidIdentifierColumn(column);
4104
5009
  }
4105
5010
  function isRelationSelectNode(value) {
4106
- return isRecord6(value) && isRecord6(value.select);
5011
+ return isRecord7(value) && isRecord7(value.select);
4107
5012
  }
4108
5013
  function normalizeIdentifier(value, label) {
4109
5014
  const normalized = value.trim();
@@ -4159,7 +5064,7 @@ function compileRelationToken(key, node) {
4159
5064
  return `${prefix}${relationToken}(${nested})`;
4160
5065
  }
4161
5066
  function compileSelectShape(select) {
4162
- if (!isRecord6(select)) {
5067
+ if (!isRecord7(select)) {
4163
5068
  throw new Error("findMany select must be an object");
4164
5069
  }
4165
5070
  const tokens = [];
@@ -4183,7 +5088,7 @@ function compileSelectShape(select) {
4183
5088
  return tokens.join(",");
4184
5089
  }
4185
5090
  function selectShapeUsesRelationSchema(select) {
4186
- if (!isRecord6(select)) {
5091
+ if (!isRecord7(select)) {
4187
5092
  return false;
4188
5093
  }
4189
5094
  for (const rawValue of Object.values(select)) {
@@ -4201,7 +5106,7 @@ function selectShapeUsesRelationSchema(select) {
4201
5106
  }
4202
5107
  function compileColumnWhere(column, input) {
4203
5108
  const normalizedColumn = normalizeIdentifier(column, "where column");
4204
- if (!isRecord6(input)) {
5109
+ if (!isRecord7(input)) {
4205
5110
  return [buildGatewayCondition("eq", normalizedColumn, input)];
4206
5111
  }
4207
5112
  const conditions = [];
@@ -4229,7 +5134,7 @@ function compileColumnWhere(column, input) {
4229
5134
  return conditions;
4230
5135
  }
4231
5136
  function compileBooleanExpressionTerms(clause, label) {
4232
- if (!isRecord6(clause)) {
5137
+ if (!isRecord7(clause)) {
4233
5138
  throw new Error(`findMany where.${label} clauses must be objects`);
4234
5139
  }
4235
5140
  const entries = Object.entries(clause).filter(([, value]) => value !== void 0);
@@ -4238,7 +5143,7 @@ function compileBooleanExpressionTerms(clause, label) {
4238
5143
  }
4239
5144
  const [rawColumn, rawValue] = entries[0];
4240
5145
  const column = normalizeIdentifier(rawColumn, `where.${label} column`);
4241
- if (!isRecord6(rawValue)) {
5146
+ if (!isRecord7(rawValue)) {
4242
5147
  return [`${column}.eq.${stringifyFilterValue(rawValue)}`];
4243
5148
  }
4244
5149
  const operatorEntries = Object.entries(rawValue).filter(([, value]) => value !== void 0);
@@ -4262,7 +5167,7 @@ function compileWhere(where) {
4262
5167
  if (where === void 0) {
4263
5168
  return void 0;
4264
5169
  }
4265
- if (!isRecord6(where)) {
5170
+ if (!isRecord7(where)) {
4266
5171
  throw new Error("findMany where must be an object");
4267
5172
  }
4268
5173
  const conditions = [];
@@ -4312,7 +5217,7 @@ function compileOrderBy(orderBy) {
4312
5217
  if (orderBy === void 0) {
4313
5218
  return void 0;
4314
5219
  }
4315
- if (!isRecord6(orderBy)) {
5220
+ if (!isRecord7(orderBy)) {
4316
5221
  throw new Error("findMany orderBy must be an object");
4317
5222
  }
4318
5223
  if ("column" in orderBy) {
@@ -4487,11 +5392,11 @@ function toFindManyAstOrder(order) {
4487
5392
  ascending: order.direction !== "descending"
4488
5393
  };
4489
5394
  }
4490
- function isRecord7(value) {
5395
+ function isRecord8(value) {
4491
5396
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
4492
5397
  }
4493
5398
  function normalizeFindManyAstColumnPredicate(value) {
4494
- if (!isRecord7(value)) {
5399
+ if (!isRecord8(value)) {
4495
5400
  return {
4496
5401
  eq: value
4497
5402
  };
@@ -4515,7 +5420,7 @@ function normalizeFindManyAstBooleanOperand(clause) {
4515
5420
  return normalized;
4516
5421
  }
4517
5422
  function normalizeFindManyAstWhere(where) {
4518
- if (!where || !isRecord7(where)) {
5423
+ if (!where || !isRecord8(where)) {
4519
5424
  return where;
4520
5425
  }
4521
5426
  const normalized = {};
@@ -4529,7 +5434,7 @@ function normalizeFindManyAstWhere(where) {
4529
5434
  );
4530
5435
  continue;
4531
5436
  }
4532
- if (key === "not" && isRecord7(value)) {
5437
+ if (key === "not" && isRecord8(value)) {
4533
5438
  normalized.not = normalizeFindManyAstBooleanOperand(
4534
5439
  value
4535
5440
  );
@@ -4540,7 +5445,7 @@ function normalizeFindManyAstWhere(where) {
4540
5445
  return normalized;
4541
5446
  }
4542
5447
  function predicateRequiresUuidQueryFallback(column, value) {
4543
- if (!isRecord7(value)) {
5448
+ if (!isRecord8(value)) {
4544
5449
  return shouldUseUuidTextComparison(column, value);
4545
5450
  }
4546
5451
  const eqValue = value.eq;
@@ -4558,7 +5463,7 @@ function booleanOperandRequiresUuidQueryFallback(clause) {
4558
5463
  return false;
4559
5464
  }
4560
5465
  function findManyAstWhereRequiresLegacyTransport(where) {
4561
- if (!where || !isRecord7(where)) {
5466
+ if (!where || !isRecord8(where)) {
4562
5467
  return false;
4563
5468
  }
4564
5469
  for (const [key, value] of Object.entries(where)) {
@@ -4573,7 +5478,7 @@ function findManyAstWhereRequiresLegacyTransport(where) {
4573
5478
  }
4574
5479
  continue;
4575
5480
  }
4576
- if (key === "not" && isRecord7(value)) {
5481
+ if (key === "not" && isRecord8(value)) {
4577
5482
  if (booleanOperandRequiresUuidQueryFallback(value)) {
4578
5483
  return true;
4579
5484
  }
@@ -4685,161 +5590,258 @@ function createSelectTransportPlan(input) {
4685
5590
  };
4686
5591
  }
4687
5592
 
4688
- // src/client.ts
4689
- var DEFAULT_COLUMNS = "*";
4690
- var SAFE_CAST_PATTERN = /^[a-z_][a-z0-9_]*(?:\[\])?$/i;
4691
- var ATHENA_NORMALIZED_ERROR_KEY = "__athenaNormalizedError";
4692
- var QUERY_TRACE_STACK_SKIP_PATTERNS = [
4693
- "src\\client.ts",
4694
- "src/client.ts",
4695
- "dist\\client.",
4696
- "dist/client.",
4697
- "node_modules\\@xylex-group\\athena",
4698
- "node_modules/@xylex-group/athena",
4699
- "node:internal",
4700
- "internal/process"
4701
- ];
4702
- function formatResult(response) {
4703
- const result = {
4704
- data: response.data ?? null,
4705
- error: null,
4706
- errorDetails: response.errorDetails ?? null,
4707
- status: response.status,
4708
- statusText: response.statusText ?? null,
4709
- raw: response.raw
5593
+ // src/query-debug-ast.ts
5594
+ var ATHENA_DEBUG_AST_KEY = "__athenaDebugAst";
5595
+ function cloneConditions(conditions) {
5596
+ return conditions.map((condition) => ({ ...condition }));
5597
+ }
5598
+ function cloneTableBuilderStateAst(state) {
5599
+ return {
5600
+ conditions: cloneConditions(state.conditions),
5601
+ limit: state.limit,
5602
+ offset: state.offset,
5603
+ order: state.order ? { ...state.order } : void 0,
5604
+ currentPage: state.currentPage,
5605
+ pageSize: state.pageSize,
5606
+ totalPages: state.totalPages
4710
5607
  };
4711
- if (response.count !== void 0) {
4712
- result.count = response.count;
5608
+ }
5609
+ function cloneRpcBuilderStateAst(state) {
5610
+ return {
5611
+ filters: state.filters.map((filter) => ({ ...filter })),
5612
+ limit: state.limit,
5613
+ offset: state.offset,
5614
+ order: state.order ? { ...state.order } : void 0
5615
+ };
5616
+ }
5617
+ function toSelectTransportAst(plan) {
5618
+ if (plan.kind === "query") {
5619
+ return {
5620
+ mode: "typed-query",
5621
+ endpoint: "/gateway/query",
5622
+ payload: plan.payload
5623
+ };
4713
5624
  }
4714
- return result;
5625
+ return {
5626
+ mode: plan.payload.select !== void 0 ? "structured-fetch" : "compiled-fetch",
5627
+ endpoint: "/gateway/fetch",
5628
+ payload: plan.payload
5629
+ };
4715
5630
  }
4716
- var EXPERIMENTAL_READ_RETRY_CONFIG = {
4717
- retries: 2,
4718
- baseDelayMs: 100,
4719
- maxDelayMs: 1e3,
4720
- backoff: "exponential",
4721
- jitter: true
4722
- };
4723
- function attachNormalizedError(result, normalizedError) {
4724
- Object.defineProperty(result, ATHENA_NORMALIZED_ERROR_KEY, {
4725
- value: normalizedError,
4726
- enumerable: false,
4727
- configurable: true,
4728
- writable: false
4729
- });
5631
+ function resolveDebugTableName(tableName) {
5632
+ return tableName ?? "__unknown_table__";
4730
5633
  }
4731
- function createResultFormatter(experimental) {
4732
- return (response, context) => {
4733
- const result = formatResult(response);
4734
- if (response.error == null && response.errorDetails == null) {
4735
- return result;
5634
+ function buildSelectDebugAst(input) {
5635
+ return {
5636
+ version: 1,
5637
+ kind: "select",
5638
+ tableName: input.tableName,
5639
+ input: {
5640
+ columns: input.columns,
5641
+ state: cloneTableBuilderStateAst(input.state)
5642
+ },
5643
+ transport: toSelectTransportAst(input.plan)
5644
+ };
5645
+ }
5646
+ function buildFindManyCompiledDebugAst(input) {
5647
+ return {
5648
+ version: 1,
5649
+ kind: "findMany",
5650
+ tableName: input.tableName,
5651
+ input: {
5652
+ select: input.options.select,
5653
+ where: input.options.where,
5654
+ orderBy: input.options.orderBy,
5655
+ limit: input.options.limit
5656
+ },
5657
+ compiled: {
5658
+ columns: input.compiledColumns,
5659
+ baseState: cloneTableBuilderStateAst(input.baseState),
5660
+ executionState: cloneTableBuilderStateAst(input.executionState)
5661
+ },
5662
+ transport: planToFindManyTransport(input.plan)
5663
+ };
5664
+ }
5665
+ function buildFindManyDirectDebugAst(input) {
5666
+ return {
5667
+ version: 1,
5668
+ kind: "findMany",
5669
+ tableName: input.tableName,
5670
+ input: {
5671
+ select: input.options.select,
5672
+ where: input.options.where,
5673
+ orderBy: input.options.orderBy,
5674
+ limit: input.options.limit
5675
+ },
5676
+ compiled: {
5677
+ columns: input.compiledColumns,
5678
+ baseState: cloneTableBuilderStateAst(input.baseState),
5679
+ executionState: cloneTableBuilderStateAst(input.executionState)
5680
+ },
5681
+ transport: {
5682
+ mode: "direct-ast-fetch",
5683
+ endpoint: "/gateway/fetch",
5684
+ payload: input.payload
4736
5685
  }
4737
- const normalizedError = normalizeAthenaError(
4738
- {
4739
- ...result,
4740
- error: response.error ?? response.errorDetails?.message ?? null
4741
- },
4742
- context
4743
- );
4744
- result.error = createResultError(response, result, normalizedError);
4745
- attachNormalizedError(result, normalizedError);
4746
- return result;
4747
5686
  };
4748
5687
  }
4749
- async function executeExperimentalRead(experimental, runner) {
4750
- if (!experimental?.retryReads) {
4751
- return runner();
5688
+ function planToFindManyTransport(plan) {
5689
+ if (plan.kind === "query") {
5690
+ return {
5691
+ mode: "compiled-query",
5692
+ endpoint: "/gateway/query",
5693
+ payload: plan.payload
5694
+ };
4752
5695
  }
4753
- let lastRetryableResult;
4754
- let lastRetrySignal = null;
4755
- try {
4756
- return await withRetry(
4757
- {
4758
- ...EXPERIMENTAL_READ_RETRY_CONFIG,
4759
- shouldRetry: (error) => error === lastRetrySignal || normalizeAthenaError(error).retryable
4760
- },
4761
- async () => {
4762
- const result = await runner();
4763
- if (result.error?.retryable) {
4764
- lastRetryableResult = result;
4765
- lastRetrySignal = result.error;
4766
- throw lastRetrySignal;
4767
- }
4768
- return result;
4769
- }
4770
- );
4771
- } catch (error) {
4772
- if (lastRetryableResult && error === lastRetrySignal) {
4773
- return lastRetryableResult;
5696
+ return {
5697
+ mode: plan.payload.select !== void 0 ? "structured-fetch" : "compiled-fetch",
5698
+ endpoint: "/gateway/fetch",
5699
+ payload: plan.payload
5700
+ };
5701
+ }
5702
+ function buildInsertDebugAst(payload) {
5703
+ return {
5704
+ version: 1,
5705
+ kind: "insert",
5706
+ tableName: payload.table_name,
5707
+ input: {
5708
+ values: payload.insert_body,
5709
+ returning: payload.columns,
5710
+ count: payload.count,
5711
+ head: payload.head,
5712
+ defaultToNull: payload.default_to_null
5713
+ },
5714
+ transport: {
5715
+ mode: "insert",
5716
+ endpoint: "/gateway/insert",
5717
+ payload
4774
5718
  }
4775
- throw error;
4776
- }
5719
+ };
4777
5720
  }
4778
- function isRecord8(value) {
4779
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
5721
+ function buildUpsertDebugAst(payload) {
5722
+ return {
5723
+ version: 1,
5724
+ kind: "upsert",
5725
+ tableName: payload.table_name,
5726
+ input: {
5727
+ values: payload.insert_body,
5728
+ updateBody: payload.update_body,
5729
+ onConflict: payload.on_conflict,
5730
+ returning: payload.columns,
5731
+ count: payload.count,
5732
+ head: payload.head,
5733
+ defaultToNull: payload.default_to_null
5734
+ },
5735
+ transport: {
5736
+ mode: "upsert",
5737
+ endpoint: "/gateway/insert",
5738
+ payload
5739
+ }
5740
+ };
4780
5741
  }
4781
- function firstNonEmptyString2(...values) {
4782
- for (const value of values) {
4783
- if (typeof value === "string" && value.trim().length > 0) {
4784
- return value.trim();
5742
+ function buildUpdateDebugAst(input) {
5743
+ return {
5744
+ version: 1,
5745
+ kind: "update",
5746
+ tableName: resolveDebugTableName(input.payload.table_name),
5747
+ input: {
5748
+ values: input.payload.set,
5749
+ state: cloneTableBuilderStateAst(input.state),
5750
+ returning: input.payload.columns
5751
+ },
5752
+ transport: {
5753
+ mode: "update",
5754
+ endpoint: "/gateway/update",
5755
+ payload: input.payload
4785
5756
  }
4786
- }
4787
- return void 0;
5757
+ };
4788
5758
  }
4789
- function resolveStructuredErrorPayload2(raw) {
4790
- if (!isRecord8(raw)) return null;
4791
- return isRecord8(raw.error) ? raw.error : raw;
5759
+ function buildDeleteDebugAst(input) {
5760
+ return {
5761
+ version: 1,
5762
+ kind: "delete",
5763
+ tableName: input.payload.table_name,
5764
+ input: {
5765
+ resourceId: input.payload.resource_id,
5766
+ state: cloneTableBuilderStateAst(input.state),
5767
+ returning: input.payload.columns
5768
+ },
5769
+ transport: {
5770
+ mode: "delete",
5771
+ endpoint: "/gateway/delete",
5772
+ payload: input.payload
5773
+ }
5774
+ };
4792
5775
  }
4793
- function resolveStructuredErrorDetails(payload, message) {
4794
- if (!payload || !("details" in payload)) {
4795
- return null;
5776
+ function buildRpcDebugAst(input) {
5777
+ return {
5778
+ version: 1,
5779
+ kind: "rpc",
5780
+ functionName: input.functionName,
5781
+ input: {
5782
+ args: input.args,
5783
+ select: input.selectedColumns,
5784
+ state: cloneRpcBuilderStateAst(input.state)
5785
+ },
5786
+ transport: {
5787
+ mode: input.endpoint === "/gateway/rpc" ? "rpc-post" : "rpc-get",
5788
+ endpoint: input.endpoint,
5789
+ payload: input.payload
5790
+ }
5791
+ };
5792
+ }
5793
+ function buildRawQueryDebugAst(query) {
5794
+ return {
5795
+ version: 1,
5796
+ kind: "query",
5797
+ input: {
5798
+ query
5799
+ },
5800
+ transport: {
5801
+ mode: "raw-query",
5802
+ endpoint: "/gateway/query",
5803
+ payload: {
5804
+ query
5805
+ }
5806
+ }
5807
+ };
5808
+ }
5809
+ function attachAthenaDebugAst(target, ast) {
5810
+ if (!ast) {
5811
+ return;
4796
5812
  }
4797
- const details = payload.details;
4798
- if (details == null) {
4799
- return null;
5813
+ if (!target || typeof target !== "object" && typeof target !== "function") {
5814
+ return;
4800
5815
  }
4801
- if (typeof details === "string" && details.trim() === message.trim()) {
5816
+ Object.defineProperty(target, ATHENA_DEBUG_AST_KEY, {
5817
+ value: ast,
5818
+ enumerable: false,
5819
+ configurable: true,
5820
+ writable: false
5821
+ });
5822
+ }
5823
+ function getAthenaDebugAst(value) {
5824
+ if (!value || typeof value !== "object" && typeof value !== "function") {
4802
5825
  return null;
4803
5826
  }
4804
- return details;
4805
- }
4806
- function createResultError(response, result, normalized) {
4807
- const rawRecord = isRecord8(response.raw) ? response.raw : null;
4808
- const payload = resolveStructuredErrorPayload2(response.raw);
4809
- const message = firstNonEmptyString2(
4810
- response.error,
4811
- payload?.message,
4812
- payload?.error,
4813
- payload?.details,
4814
- response.errorDetails?.message,
4815
- normalized.message
4816
- ) ?? normalized.message;
4817
- const statusText = firstNonEmptyString2(response.statusText, rawRecord?.statusText) ?? null;
4818
- const hint = firstNonEmptyString2(payload?.hint, response.errorDetails?.hint) ?? null;
4819
- const code = firstNonEmptyString2(payload?.code) ?? normalized.code;
4820
- const details = resolveStructuredErrorDetails(payload, message) ?? response.errorDetails?.cause ?? null;
4821
- return {
4822
- message,
4823
- code,
4824
- athenaCode: normalized.code,
4825
- gatewayCode: response.errorDetails?.code ?? null,
4826
- kind: normalized.kind,
4827
- category: normalized.category,
4828
- retryable: normalized.retryable,
4829
- details,
4830
- hint,
4831
- status: result.status,
4832
- statusText,
4833
- constraint: normalized.constraint,
4834
- table: normalized.table,
4835
- operation: normalized.operation,
4836
- endpoint: response.errorDetails?.endpoint,
4837
- method: response.errorDetails?.method,
4838
- requestId: response.errorDetails?.requestId,
4839
- cause: response.errorDetails?.cause,
4840
- raw: result.raw
4841
- };
5827
+ return value[ATHENA_DEBUG_AST_KEY] ?? null;
4842
5828
  }
5829
+
5830
+ // src/query-tracing.ts
5831
+ var QUERY_TRACE_STACK_SKIP_PATTERNS = [
5832
+ "src\\client.ts",
5833
+ "src/client.ts",
5834
+ "src\\query-tracing.ts",
5835
+ "src/query-tracing.ts",
5836
+ "dist\\client.",
5837
+ "dist/client.",
5838
+ "dist\\query-tracing.",
5839
+ "dist/query-tracing.",
5840
+ "node_modules\\@xylex-group\\athena",
5841
+ "node_modules/@xylex-group/athena",
5842
+ "node:internal",
5843
+ "internal/process"
5844
+ ];
4843
5845
  function parseQueryTraceCallsiteFrame(frame) {
4844
5846
  const trimmed = frame.trim();
4845
5847
  if (!trimmed) {
@@ -4944,6 +5946,7 @@ function createQueryTracer(experimental) {
4944
5946
  functionName: context.functionName,
4945
5947
  sql: context.sql,
4946
5948
  payload: context.payload,
5949
+ ast: context.ast,
4947
5950
  options: context.options,
4948
5951
  callsite,
4949
5952
  outcome: {
@@ -4966,6 +5969,7 @@ function createQueryTracer(experimental) {
4966
5969
  functionName: context.functionName,
4967
5970
  sql: context.sql,
4968
5971
  payload: context.payload,
5972
+ ast: context.ast,
4969
5973
  options: context.options,
4970
5974
  callsite,
4971
5975
  thrownError: error
@@ -4974,20 +5978,196 @@ function createQueryTracer(experimental) {
4974
5978
  };
4975
5979
  }
4976
5980
  async function executeWithQueryTrace(tracer, context, runner, callsiteOverride) {
4977
- if (!tracer) {
4978
- return runner();
4979
- }
4980
- const callsite = callsiteOverride ?? tracer.captureCallsite();
4981
- const startedAt = Date.now();
5981
+ const callsite = tracer ? callsiteOverride ?? tracer.captureCallsite() : null;
5982
+ const startedAt = tracer ? Date.now() : 0;
4982
5983
  try {
4983
5984
  const result = await runner();
4984
- tracer.publishSuccess(context, result, Date.now() - startedAt, callsite);
5985
+ attachAthenaDebugAst(result, context.ast);
5986
+ if (tracer) {
5987
+ tracer.publishSuccess(context, result, Date.now() - startedAt, callsite);
5988
+ }
5989
+ return result;
5990
+ } catch (error) {
5991
+ attachAthenaDebugAst(error, context.ast);
5992
+ if (tracer) {
5993
+ tracer.publishFailure(context, error, Date.now() - startedAt, callsite);
5994
+ }
5995
+ throw error;
5996
+ }
5997
+ }
5998
+
5999
+ // src/schema/model-target.ts
6000
+ function normalizeOptionalName(value) {
6001
+ const normalized = value?.trim();
6002
+ return normalized ? normalized : void 0;
6003
+ }
6004
+ function isAthenaModelTarget(value) {
6005
+ if (!value || typeof value !== "object") {
6006
+ return false;
6007
+ }
6008
+ const candidate = value;
6009
+ return Boolean(candidate.meta && Array.isArray(candidate.meta.primaryKey));
6010
+ }
6011
+ function resolveAthenaModelTargetTableName(target, options = {}) {
6012
+ const explicitTableName = normalizeOptionalName(target.meta.tableName);
6013
+ if (explicitTableName) {
6014
+ return explicitTableName;
6015
+ }
6016
+ const schemaName = normalizeOptionalName(target.meta.schema ?? options.fallbackSchema);
6017
+ const modelName = normalizeOptionalName(target.meta.model ?? options.fallbackModel);
6018
+ if (!modelName) {
6019
+ throw new Error(
6020
+ "Athena model target is missing meta.model or meta.tableName. Provide one of those before calling from(model)."
6021
+ );
6022
+ }
6023
+ return schemaName ? `${schemaName}.${modelName}` : modelName;
6024
+ }
6025
+
6026
+ // src/client.ts
6027
+ var DEFAULT_COLUMNS = "*";
6028
+ var SAFE_CAST_PATTERN = /^[a-z_][a-z0-9_]*(?:\[\])?$/i;
6029
+ var ATHENA_NORMALIZED_ERROR_KEY = "__athenaNormalizedError";
6030
+ function formatResult(response) {
6031
+ const result = {
6032
+ data: response.data ?? null,
6033
+ error: null,
6034
+ errorDetails: response.errorDetails ?? null,
6035
+ status: response.status,
6036
+ statusText: response.statusText ?? null,
6037
+ raw: response.raw
6038
+ };
6039
+ if (response.count !== void 0) {
6040
+ result.count = response.count;
6041
+ }
6042
+ return result;
6043
+ }
6044
+ var EXPERIMENTAL_READ_RETRY_CONFIG = {
6045
+ retries: 2,
6046
+ baseDelayMs: 100,
6047
+ maxDelayMs: 1e3,
6048
+ backoff: "exponential",
6049
+ jitter: true
6050
+ };
6051
+ function attachNormalizedError(result, normalizedError) {
6052
+ Object.defineProperty(result, ATHENA_NORMALIZED_ERROR_KEY, {
6053
+ value: normalizedError,
6054
+ enumerable: false,
6055
+ configurable: true,
6056
+ writable: false
6057
+ });
6058
+ }
6059
+ function createResultFormatter(experimental) {
6060
+ return (response, context) => {
6061
+ const result = formatResult(response);
6062
+ if (response.error == null && response.errorDetails == null) {
6063
+ return result;
6064
+ }
6065
+ const normalizedError = normalizeAthenaError(
6066
+ {
6067
+ ...result,
6068
+ error: response.error ?? response.errorDetails?.message ?? null
6069
+ },
6070
+ context
6071
+ );
6072
+ result.error = createResultError(response, result, normalizedError);
6073
+ attachNormalizedError(result, normalizedError);
4985
6074
  return result;
6075
+ };
6076
+ }
6077
+ async function executeExperimentalRead(experimental, runner) {
6078
+ if (!experimental?.retryReads) {
6079
+ return runner();
6080
+ }
6081
+ let lastRetryableResult;
6082
+ let lastRetrySignal = null;
6083
+ try {
6084
+ return await withRetry(
6085
+ {
6086
+ ...EXPERIMENTAL_READ_RETRY_CONFIG,
6087
+ shouldRetry: (error) => error === lastRetrySignal || normalizeAthenaError(error).retryable
6088
+ },
6089
+ async () => {
6090
+ const result = await runner();
6091
+ if (result.error?.retryable) {
6092
+ lastRetryableResult = result;
6093
+ lastRetrySignal = result.error;
6094
+ throw lastRetrySignal;
6095
+ }
6096
+ return result;
6097
+ }
6098
+ );
4986
6099
  } catch (error) {
4987
- tracer.publishFailure(context, error, Date.now() - startedAt, callsite);
6100
+ if (lastRetryableResult && error === lastRetrySignal) {
6101
+ return lastRetryableResult;
6102
+ }
4988
6103
  throw error;
4989
6104
  }
4990
6105
  }
6106
+ function isRecord9(value) {
6107
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
6108
+ }
6109
+ function firstNonEmptyString2(...values) {
6110
+ for (const value of values) {
6111
+ if (typeof value === "string" && value.trim().length > 0) {
6112
+ return value.trim();
6113
+ }
6114
+ }
6115
+ return void 0;
6116
+ }
6117
+ function resolveStructuredErrorPayload2(raw) {
6118
+ if (!isRecord9(raw)) return null;
6119
+ return isRecord9(raw.error) ? raw.error : raw;
6120
+ }
6121
+ function resolveStructuredErrorDetails(payload, message) {
6122
+ if (!payload || !("details" in payload)) {
6123
+ return null;
6124
+ }
6125
+ const details = payload.details;
6126
+ if (details == null) {
6127
+ return null;
6128
+ }
6129
+ if (typeof details === "string" && details.trim() === message.trim()) {
6130
+ return null;
6131
+ }
6132
+ return details;
6133
+ }
6134
+ function createResultError(response, result, normalized) {
6135
+ const rawRecord = isRecord9(response.raw) ? response.raw : null;
6136
+ const payload = resolveStructuredErrorPayload2(response.raw);
6137
+ const message = firstNonEmptyString2(
6138
+ response.error,
6139
+ payload?.message,
6140
+ payload?.error,
6141
+ payload?.details,
6142
+ response.errorDetails?.message,
6143
+ normalized.message
6144
+ ) ?? normalized.message;
6145
+ const statusText = firstNonEmptyString2(response.statusText, rawRecord?.statusText) ?? null;
6146
+ const hint = firstNonEmptyString2(payload?.hint, response.errorDetails?.hint) ?? null;
6147
+ const code = firstNonEmptyString2(payload?.code) ?? normalized.code;
6148
+ const details = resolveStructuredErrorDetails(payload, message) ?? response.errorDetails?.cause ?? null;
6149
+ return {
6150
+ message,
6151
+ code,
6152
+ athenaCode: normalized.code,
6153
+ gatewayCode: response.errorDetails?.code ?? null,
6154
+ kind: normalized.kind,
6155
+ category: normalized.category,
6156
+ retryable: normalized.retryable,
6157
+ details,
6158
+ hint,
6159
+ status: result.status,
6160
+ statusText,
6161
+ constraint: normalized.constraint,
6162
+ table: normalized.table,
6163
+ operation: normalized.operation,
6164
+ endpoint: response.errorDetails?.endpoint,
6165
+ method: response.errorDetails?.method,
6166
+ requestId: response.errorDetails?.requestId,
6167
+ cause: response.errorDetails?.cause,
6168
+ raw: result.raw
6169
+ };
6170
+ }
4991
6171
  function toSingleResult(response) {
4992
6172
  const payload = response.data;
4993
6173
  const singleData = Array.isArray(payload) ? payload.length ? payload[0] : null : payload ?? null;
@@ -5015,6 +6195,15 @@ function asAthenaJsonObject(value) {
5015
6195
  function asAthenaJsonObjectArray(values) {
5016
6196
  return values;
5017
6197
  }
6198
+ function normalizeSelectColumnsInput(columns) {
6199
+ if (columns === void 0) {
6200
+ return void 0;
6201
+ }
6202
+ if (typeof columns === "string") {
6203
+ return columns;
6204
+ }
6205
+ return [...columns];
6206
+ }
5018
6207
  function createMutationQuery(executor, defaultColumns = DEFAULT_COLUMNS, tracer, initialCallsite) {
5019
6208
  let selectedColumns = defaultColumns === null ? void 0 : defaultColumns;
5020
6209
  let selectedOptions;
@@ -5024,25 +6213,29 @@ function createMutationQuery(executor, defaultColumns = DEFAULT_COLUMNS, tracer,
5024
6213
  const payloadColumns = columns ?? selectedColumns;
5025
6214
  const payloadOptions = options ?? selectedOptions;
5026
6215
  if (!promise) {
5027
- promise = executor(payloadColumns, payloadOptions, callsiteStore.resolve(callsite));
6216
+ promise = executor(
6217
+ normalizeSelectColumnsInput(payloadColumns),
6218
+ payloadOptions,
6219
+ callsiteStore.resolve(callsite)
6220
+ );
5028
6221
  }
5029
6222
  return promise;
5030
6223
  };
5031
6224
  const mutationQuery = {
5032
- select(columns = selectedColumns, options) {
6225
+ select(columns, options) {
5033
6226
  selectedColumns = columns;
5034
6227
  selectedOptions = options ?? selectedOptions;
5035
6228
  return run(columns, options, captureTraceCallsite(tracer));
5036
6229
  },
5037
- returning(columns = selectedColumns, options) {
6230
+ returning(columns, options) {
5038
6231
  return mutationQuery.select(columns, options);
5039
6232
  },
5040
- single(columns = selectedColumns, options) {
6233
+ single(columns, options) {
5041
6234
  selectedColumns = columns;
5042
6235
  selectedOptions = options ?? selectedOptions;
5043
6236
  return run(columns, options, captureTraceCallsite(tracer)).then(toSingleResult);
5044
6237
  },
5045
- maybeSingle(columns = selectedColumns, options) {
6238
+ maybeSingle(columns, options) {
5046
6239
  return mutationQuery.single(columns, options);
5047
6240
  },
5048
6241
  then(onfulfilled, onrejected) {
@@ -5599,7 +6792,10 @@ function createFilterMethods(state, addCondition, self) {
5599
6792
  }
5600
6793
  function toRpcSelect(columns) {
5601
6794
  if (!columns) return void 0;
5602
- return Array.isArray(columns) ? columns.join(",") : columns;
6795
+ if (typeof columns === "string") {
6796
+ return columns;
6797
+ }
6798
+ return columns.join(",");
5603
6799
  }
5604
6800
  function createRpcFilterMethods(filters, self) {
5605
6801
  const addFilter = (operator, column, value) => {
@@ -5648,7 +6844,7 @@ function createRpcFilterMethods(filters, self) {
5648
6844
  }
5649
6845
  };
5650
6846
  }
5651
- function createRpcBuilder(functionName, args, baseOptions, client, formatGatewayResult, tracer, initialCallsite) {
6847
+ function createRpcBuilder(functionName, args, baseOptions, client, formatGatewayResult, tracer, initialCallsite, debugAstEnabled = false) {
5652
6848
  const state = {
5653
6849
  filters: []
5654
6850
  };
@@ -5658,6 +6854,7 @@ function createRpcBuilder(functionName, args, baseOptions, client, formatGateway
5658
6854
  const callsiteStore = createTraceCallsiteStore(tracer, initialCallsite);
5659
6855
  const executeRpc = async (columns, options, callsite) => {
5660
6856
  const mergedOptions = mergeOptions(baseOptions, options);
6857
+ const normalizedSelectedColumns = normalizeSelectColumnsInput(columns);
5661
6858
  const payload = {
5662
6859
  function: functionName,
5663
6860
  args,
@@ -5672,6 +6869,14 @@ function createRpcBuilder(functionName, args, baseOptions, client, formatGateway
5672
6869
  };
5673
6870
  const endpoint = mergedOptions?.get ? `/rpc/${functionName}` : "/gateway/rpc";
5674
6871
  const sql = buildRpcDebugSql(payload);
6872
+ const debugAst = debugAstEnabled ? buildRpcDebugAst({
6873
+ functionName,
6874
+ args,
6875
+ selectedColumns: normalizedSelectedColumns,
6876
+ state,
6877
+ payload,
6878
+ endpoint
6879
+ }) : void 0;
5675
6880
  return executeWithQueryTrace(
5676
6881
  tracer,
5677
6882
  {
@@ -5680,6 +6885,7 @@ function createRpcBuilder(functionName, args, baseOptions, client, formatGateway
5680
6885
  functionName,
5681
6886
  sql,
5682
6887
  payload,
6888
+ ast: debugAst,
5683
6889
  options: mergedOptions
5684
6890
  },
5685
6891
  async () => {
@@ -5700,7 +6906,7 @@ function createRpcBuilder(functionName, args, baseOptions, client, formatGateway
5700
6906
  const builder = {};
5701
6907
  const filterMethods = createRpcFilterMethods(state.filters, builder);
5702
6908
  Object.assign(builder, filterMethods, {
5703
- select(columns = selectedColumns, options) {
6909
+ select(columns, options) {
5704
6910
  selectedColumns = columns;
5705
6911
  selectedOptions = options ?? selectedOptions;
5706
6912
  return run(columns, options, captureTraceCallsite(tracer));
@@ -5745,6 +6951,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
5745
6951
  const state = {
5746
6952
  conditions: []
5747
6953
  };
6954
+ const debugAstEnabled = Boolean(experimental?.debugAst);
5748
6955
  const addCondition = (operator, column, value, hints) => {
5749
6956
  const condition = { operator };
5750
6957
  if (column) {
@@ -5788,15 +6995,27 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
5788
6995
  addCondition,
5789
6996
  builder
5790
6997
  );
5791
- const runSelect = async (columns = DEFAULT_COLUMNS, options, executionState = snapshotState(), callsite) => {
6998
+ const runSelect = async (columns = DEFAULT_COLUMNS, options, executionState = snapshotState(), callsite, debugAstFactory) => {
6999
+ const runtimeColumns = normalizeSelectColumnsInput(columns) ?? DEFAULT_COLUMNS;
5792
7000
  const resolvedTableName = resolveTableNameForCall(tableName, options?.schema);
5793
7001
  const plan = createSelectTransportPlan({
5794
7002
  tableName: resolvedTableName,
5795
- columns,
7003
+ columns: runtimeColumns,
5796
7004
  state: executionState,
5797
7005
  options,
5798
7006
  buildTypedSelectQuery
5799
7007
  });
7008
+ const debugAst = debugAstEnabled ? debugAstFactory?.({
7009
+ tableName: resolvedTableName,
7010
+ columns: runtimeColumns,
7011
+ executionState,
7012
+ plan
7013
+ }) ?? buildSelectDebugAst({
7014
+ tableName: resolvedTableName,
7015
+ columns: runtimeColumns,
7016
+ state: executionState,
7017
+ plan
7018
+ }) : void 0;
5800
7019
  if (plan.kind === "query") {
5801
7020
  return executeExperimentalRead(
5802
7021
  experimental,
@@ -5808,6 +7027,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
5808
7027
  table: resolvedTableName,
5809
7028
  sql: plan.query,
5810
7029
  payload: plan.payload,
7030
+ ast: debugAst,
5811
7031
  options
5812
7032
  },
5813
7033
  async () => {
@@ -5832,6 +7052,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
5832
7052
  table: resolvedTableName,
5833
7053
  sql,
5834
7054
  payload: plan.payload,
7055
+ ast: debugAst,
5835
7056
  options
5836
7057
  },
5837
7058
  async () => {
@@ -5845,7 +7066,11 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
5845
7066
  const createSelectChain = (columns, options, initialCallsite) => {
5846
7067
  const chain = {};
5847
7068
  const callsiteStore = createTraceCallsiteStore(tracer, initialCallsite);
5848
- const filterMethods2 = createFilterMethods(state, addCondition, chain);
7069
+ const filterMethods2 = createFilterMethods(
7070
+ state,
7071
+ addCondition,
7072
+ chain
7073
+ );
5849
7074
  Object.assign(chain, filterMethods2, {
5850
7075
  async single(cols, opts) {
5851
7076
  const r = await runSelect(
@@ -5932,6 +7157,14 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
5932
7157
  limit: executionState.limit,
5933
7158
  order: executionState.order
5934
7159
  });
7160
+ const debugAst = debugAstEnabled ? buildFindManyDirectDebugAst({
7161
+ tableName: resolvedTableName,
7162
+ options,
7163
+ compiledColumns: columns,
7164
+ baseState,
7165
+ executionState,
7166
+ payload
7167
+ }) : void 0;
5935
7168
  return executeExperimentalRead(
5936
7169
  experimental,
5937
7170
  () => executeWithQueryTrace(
@@ -5941,7 +7174,8 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
5941
7174
  endpoint: "/gateway/fetch",
5942
7175
  table: resolvedTableName,
5943
7176
  sql,
5944
- payload
7177
+ payload,
7178
+ ast: debugAst
5945
7179
  },
5946
7180
  async () => {
5947
7181
  const response = await client.fetchGateway(
@@ -5957,7 +7191,15 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
5957
7191
  columns,
5958
7192
  void 0,
5959
7193
  executionState,
5960
- callsite
7194
+ callsite,
7195
+ debugAstEnabled ? ({ tableName: resolvedTableName, executionState: tracedState, plan }) => buildFindManyCompiledDebugAst({
7196
+ tableName: resolvedTableName,
7197
+ options,
7198
+ compiledColumns: columns,
7199
+ baseState,
7200
+ executionState: tracedState,
7201
+ plan
7202
+ }) : void 0
5961
7203
  );
5962
7204
  },
5963
7205
  insert(values, options) {
@@ -5977,6 +7219,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
5977
7219
  payload.default_to_null = mergedOptions.defaultToNull;
5978
7220
  }
5979
7221
  const sql = buildInsertDebugSql(payload);
7222
+ const debugAst = debugAstEnabled ? buildInsertDebugAst(payload) : void 0;
5980
7223
  return executeWithQueryTrace(
5981
7224
  tracer,
5982
7225
  {
@@ -5985,6 +7228,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
5985
7228
  table: resolvedTableName,
5986
7229
  sql,
5987
7230
  payload,
7231
+ ast: debugAst,
5988
7232
  options: mergedOptions
5989
7233
  },
5990
7234
  async () => {
@@ -6010,6 +7254,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6010
7254
  payload.default_to_null = mergedOptions.defaultToNull;
6011
7255
  }
6012
7256
  const sql = buildInsertDebugSql(payload);
7257
+ const debugAst = debugAstEnabled ? buildInsertDebugAst(payload) : void 0;
6013
7258
  return executeWithQueryTrace(
6014
7259
  tracer,
6015
7260
  {
@@ -6018,6 +7263,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6018
7263
  table: resolvedTableName,
6019
7264
  sql,
6020
7265
  payload,
7266
+ ast: debugAst,
6021
7267
  options: mergedOptions
6022
7268
  },
6023
7269
  async () => {
@@ -6048,6 +7294,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6048
7294
  payload.default_to_null = mergedOptions.defaultToNull;
6049
7295
  }
6050
7296
  const sql = buildInsertDebugSql(payload);
7297
+ const debugAst = debugAstEnabled ? buildUpsertDebugAst(payload) : void 0;
6051
7298
  return executeWithQueryTrace(
6052
7299
  tracer,
6053
7300
  {
@@ -6056,6 +7303,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6056
7303
  table: resolvedTableName,
6057
7304
  sql,
6058
7305
  payload,
7306
+ ast: debugAst,
6059
7307
  options: mergedOptions
6060
7308
  },
6061
7309
  async () => {
@@ -6083,6 +7331,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6083
7331
  payload.default_to_null = mergedOptions.defaultToNull;
6084
7332
  }
6085
7333
  const sql = buildInsertDebugSql(payload);
7334
+ const debugAst = debugAstEnabled ? buildUpsertDebugAst(payload) : void 0;
6086
7335
  return executeWithQueryTrace(
6087
7336
  tracer,
6088
7337
  {
@@ -6091,6 +7340,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6091
7340
  table: resolvedTableName,
6092
7341
  sql,
6093
7342
  payload,
7343
+ ast: debugAst,
6094
7344
  options: mergedOptions
6095
7345
  },
6096
7346
  async () => {
@@ -6105,7 +7355,8 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6105
7355
  update(values, options) {
6106
7356
  const mutationCallsite = captureTraceCallsite(tracer);
6107
7357
  const executeUpdate = async (columns, selectOptions, callsite) => {
6108
- const filters = state.conditions.length ? [...state.conditions] : void 0;
7358
+ const executionState = snapshotState();
7359
+ const filters = executionState.conditions.length ? [...executionState.conditions] : void 0;
6109
7360
  const mergedOptions = mergeOptions(options, selectOptions);
6110
7361
  const resolvedTableName = resolveTableNameForCall(tableName, mergedOptions?.schema);
6111
7362
  const payload = {
@@ -6114,12 +7365,16 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6114
7365
  conditions: filters,
6115
7366
  strip_nulls: mergedOptions?.stripNulls ?? true
6116
7367
  };
6117
- if (state.order) payload.sort_by = state.order;
6118
- if (state.currentPage !== void 0) payload.current_page = state.currentPage;
6119
- if (state.pageSize !== void 0) payload.page_size = state.pageSize;
6120
- if (state.totalPages !== void 0) payload.total_pages = state.totalPages;
7368
+ if (executionState.order) payload.sort_by = executionState.order;
7369
+ if (executionState.currentPage !== void 0) payload.current_page = executionState.currentPage;
7370
+ if (executionState.pageSize !== void 0) payload.page_size = executionState.pageSize;
7371
+ if (executionState.totalPages !== void 0) payload.total_pages = executionState.totalPages;
6121
7372
  if (columns) payload.columns = columns;
6122
7373
  const sql = buildUpdateDebugSql(payload);
7374
+ const debugAst = debugAstEnabled ? buildUpdateDebugAst({
7375
+ state: executionState,
7376
+ payload
7377
+ }) : void 0;
6123
7378
  return executeWithQueryTrace(
6124
7379
  tracer,
6125
7380
  {
@@ -6128,6 +7383,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6128
7383
  table: resolvedTableName,
6129
7384
  sql,
6130
7385
  payload,
7386
+ ast: debugAst,
6131
7387
  options: mergedOptions
6132
7388
  },
6133
7389
  async () => {
@@ -6151,6 +7407,11 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6151
7407
  }
6152
7408
  const mutationCallsite = captureTraceCallsite(tracer);
6153
7409
  const executeDelete = async (columns, selectOptions, callsite) => {
7410
+ const executionState = snapshotState();
7411
+ const debugState = {
7412
+ ...executionState,
7413
+ conditions: filters ? filters.map((condition) => ({ ...condition })) : []
7414
+ };
6154
7415
  const mergedOptions = mergeOptions(options, selectOptions);
6155
7416
  const resolvedTableName = resolveTableNameForCall(tableName, mergedOptions?.schema);
6156
7417
  const payload = {
@@ -6158,12 +7419,16 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6158
7419
  resource_id: resourceId,
6159
7420
  conditions: filters
6160
7421
  };
6161
- if (state.order) payload.sort_by = state.order;
6162
- if (state.currentPage !== void 0) payload.current_page = state.currentPage;
6163
- if (state.pageSize !== void 0) payload.page_size = state.pageSize;
6164
- if (state.totalPages !== void 0) payload.total_pages = state.totalPages;
7422
+ if (executionState.order) payload.sort_by = executionState.order;
7423
+ if (executionState.currentPage !== void 0) payload.current_page = executionState.currentPage;
7424
+ if (executionState.pageSize !== void 0) payload.page_size = executionState.pageSize;
7425
+ if (executionState.totalPages !== void 0) payload.total_pages = executionState.totalPages;
6165
7426
  if (columns) payload.columns = columns;
6166
7427
  const sql = buildDeleteDebugSql(payload);
7428
+ const debugAst = debugAstEnabled ? buildDeleteDebugAst({
7429
+ state: debugState,
7430
+ payload
7431
+ }) : void 0;
6167
7432
  return executeWithQueryTrace(
6168
7433
  tracer,
6169
7434
  {
@@ -6172,6 +7437,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6172
7437
  table: resolvedTableName,
6173
7438
  sql,
6174
7439
  payload,
7440
+ ast: debugAst,
6175
7441
  options: mergedOptions
6176
7442
  },
6177
7443
  async () => {
@@ -6199,6 +7465,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6199
7465
  return builder;
6200
7466
  }
6201
7467
  function createQueryBuilder(client, formatGatewayResult, experimental, tracer) {
7468
+ const debugAstEnabled = Boolean(experimental?.debugAst);
6202
7469
  return async function query(query, options) {
6203
7470
  const normalizedQuery = query.trim();
6204
7471
  if (!normalizedQuery) {
@@ -6215,6 +7482,7 @@ function createQueryBuilder(client, formatGatewayResult, experimental, tracer) {
6215
7482
  endpoint: "/gateway/query",
6216
7483
  sql: normalizedQuery,
6217
7484
  payload,
7485
+ ast: debugAstEnabled ? buildRawQueryDebugAst(normalizedQuery) : void 0,
6218
7486
  options
6219
7487
  },
6220
7488
  async () => {
@@ -6226,6 +7494,63 @@ function createQueryBuilder(client, formatGatewayResult, experimental, tracer) {
6226
7494
  );
6227
7495
  };
6228
7496
  }
7497
+ function resolveClientServiceBaseUrl(value, label) {
7498
+ if (value === void 0 || value === null) {
7499
+ return void 0;
7500
+ }
7501
+ return normalizeAthenaGatewayBaseUrl(value, { label });
7502
+ }
7503
+ function appendServicePath(baseUrl, segment) {
7504
+ const normalizedBaseUrl = normalizeAthenaGatewayBaseUrl(baseUrl, { label: "Athena public base URL" });
7505
+ return `${normalizedBaseUrl}/${segment.replace(/^\/+/, "")}`;
7506
+ }
7507
+ function resolveServiceUrlOverride(value, label) {
7508
+ return resolveClientServiceBaseUrl(value, label);
7509
+ }
7510
+ function resolveServiceUrls(config) {
7511
+ const baseUrl = resolveClientServiceBaseUrl(config.url, "Athena public base URL");
7512
+ return {
7513
+ 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),
7514
+ 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),
7515
+ storageUrl: resolveServiceUrlOverride(config.storage?.url, "Athena storage base URL") ?? resolveServiceUrlOverride(config.storageUrl, "Athena storage base URL") ?? (baseUrl ? appendServicePath(baseUrl, "storage") : void 0)
7516
+ };
7517
+ }
7518
+ function normalizeAuthClientConfig(auth, defaultBaseUrl) {
7519
+ if (!auth && defaultBaseUrl === void 0) {
7520
+ return void 0;
7521
+ }
7522
+ const { url, ...rest } = auth ?? {};
7523
+ const normalized = {
7524
+ ...rest
7525
+ };
7526
+ const resolvedBaseUrl = resolveClientServiceBaseUrl(
7527
+ url ?? rest.baseUrl ?? defaultBaseUrl,
7528
+ "Athena auth base URL"
7529
+ );
7530
+ if (resolvedBaseUrl !== void 0) {
7531
+ normalized.baseUrl = resolvedBaseUrl;
7532
+ }
7533
+ return normalized;
7534
+ }
7535
+ function resolveCreateClientConfig(config) {
7536
+ const resolvedUrls = resolveServiceUrls(config);
7537
+ if (!resolvedUrls.dbUrl) {
7538
+ throw new Error(
7539
+ "Athena DB base URL is required. Pass createClient(url, key) for a unified root, or set db.url / gateway.url / gatewayUrl explicitly."
7540
+ );
7541
+ }
7542
+ return {
7543
+ baseUrl: resolvedUrls.dbUrl,
7544
+ apiKey: config.key,
7545
+ client: config.client,
7546
+ backend: toBackendConfig(config.backend),
7547
+ headers: config.headers,
7548
+ auth: config.auth,
7549
+ authUrl: resolvedUrls.authUrl,
7550
+ storageUrl: resolvedUrls.storageUrl,
7551
+ experimental: config.experimental
7552
+ };
7553
+ }
6229
7554
  function createClientFromConfig(config) {
6230
7555
  const gatewayHeaders = {
6231
7556
  ...config.headers ?? {}
@@ -6242,14 +7567,31 @@ function createClientFromConfig(config) {
6242
7567
  });
6243
7568
  const formatGatewayResult = createResultFormatter(config.experimental);
6244
7569
  const queryTracer = createQueryTracer(config.experimental);
6245
- const auth = createAuthClient(config.auth);
6246
- const from = (table, options) => createTableBuilder(
6247
- resolveTableNameForCall(table, options?.schema),
6248
- gateway,
6249
- formatGatewayResult,
6250
- queryTracer,
6251
- config.experimental
6252
- );
7570
+ const auth = createAuthClient(normalizeAuthClientConfig(config.auth, config.authUrl));
7571
+ function from(tableOrModel, options) {
7572
+ if (isAthenaModelTarget(tableOrModel)) {
7573
+ if (options?.schema !== void 0) {
7574
+ throw new Error(
7575
+ "from(model) does not accept a schema override because the model already defines its target."
7576
+ );
7577
+ }
7578
+ return createTableBuilder(
7579
+ resolveAthenaModelTargetTableName(tableOrModel),
7580
+ gateway,
7581
+ formatGatewayResult,
7582
+ queryTracer,
7583
+ config.experimental
7584
+ );
7585
+ }
7586
+ const resolvedTableName = resolveTableNameForCall(tableOrModel, options?.schema);
7587
+ return createTableBuilder(
7588
+ resolvedTableName,
7589
+ gateway,
7590
+ formatGatewayResult,
7591
+ queryTracer,
7592
+ config.experimental
7593
+ );
7594
+ }
6253
7595
  const rpc = (fn, args, options) => {
6254
7596
  const normalizedFn = fn.trim();
6255
7597
  if (!normalizedFn) {
@@ -6262,10 +7604,16 @@ function createClientFromConfig(config) {
6262
7604
  gateway,
6263
7605
  formatGatewayResult,
6264
7606
  queryTracer,
6265
- captureTraceCallsite(queryTracer)
7607
+ captureTraceCallsite(queryTracer),
7608
+ Boolean(config.experimental?.debugAst)
6266
7609
  );
6267
7610
  };
6268
- const query = createQueryBuilder(gateway, formatGatewayResult, config.experimental, queryTracer);
7611
+ const query = createQueryBuilder(
7612
+ gateway,
7613
+ formatGatewayResult,
7614
+ config.experimental,
7615
+ queryTracer
7616
+ );
6269
7617
  const db = createDbModule({ from, rpc, query });
6270
7618
  const sdkClient = {
6271
7619
  from,
@@ -6278,170 +7626,448 @@ function createClientFromConfig(config) {
6278
7626
  if (config.experimental?.athenaStorageBackend) {
6279
7627
  const storageClient = {
6280
7628
  ...sdkClient,
6281
- storage: createStorageModule(gateway, config.experimental.storage)
7629
+ storage: createStorageModule(gateway, {
7630
+ ...config.experimental.storage,
7631
+ ...config.storageUrl ? {
7632
+ baseUrl: config.storageUrl,
7633
+ stripBasePath: true
7634
+ } : {}
7635
+ })
6282
7636
  };
6283
7637
  return storageClient;
6284
7638
  }
6285
7639
  return sdkClient;
6286
7640
  }
6287
- var DEFAULT_BACKEND = { type: "athena" };
6288
- function toBackendConfig(b) {
6289
- if (!b) return DEFAULT_BACKEND;
6290
- return typeof b === "string" ? { type: b } : b;
6291
- }
6292
- function mergeAuthClientConfig(current, next) {
6293
- const merged = {
6294
- ...current ?? {},
6295
- ...next
6296
- };
6297
- if (current?.headers || next.headers) {
6298
- merged.headers = {
6299
- ...current?.headers ?? {},
6300
- ...next.headers ?? {}
6301
- };
7641
+ var AthenaClient = class {
7642
+ /** Create a fluent builder for a strongly-typed Athena SDK client. */
7643
+ static builder() {
7644
+ return createAthenaClientBuilder((config) => createClientFromConfig(resolveCreateClientConfig(config)));
6302
7645
  }
6303
- return merged;
6304
- }
6305
- function mergeExperimentalOptions(current, next) {
6306
- const merged = {
6307
- ...current ?? {},
6308
- ...next
6309
- };
6310
- if (current?.traceQueries && typeof current.traceQueries === "object" && next.traceQueries && typeof next.traceQueries === "object") {
6311
- merged.traceQueries = {
6312
- ...current.traceQueries,
6313
- ...next.traceQueries
6314
- };
7646
+ /** Build a client from process environment variables. */
7647
+ static fromEnvironment() {
7648
+ const url = process.env.ATHENA_URL;
7649
+ const gatewayUrl = process.env.ATHENA_DB_URL ?? process.env.ATHENA_GATEWAY_URL;
7650
+ const authUrl = process.env.ATHENA_AUTH_URL;
7651
+ const storageUrl = process.env.ATHENA_STORAGE_URL;
7652
+ const key = process.env.ATHENA_API_KEY ?? process.env.ATHENA_GATEWAY_API_KEY;
7653
+ if (!url && !gatewayUrl || !key) {
7654
+ throw new Error(
7655
+ "ATHENA_API_KEY plus ATHENA_URL or ATHENA_GATEWAY_URL (optionally ATHENA_DB_URL, ATHENA_AUTH_URL, ATHENA_STORAGE_URL) are required"
7656
+ );
7657
+ }
7658
+ return createClient({
7659
+ url,
7660
+ gatewayUrl,
7661
+ authUrl,
7662
+ storageUrl,
7663
+ key
7664
+ });
6315
7665
  }
6316
- if (current?.storage || next.storage) {
6317
- merged.storage = {
6318
- ...current?.storage ?? {},
6319
- ...next.storage ?? {}
6320
- };
7666
+ };
7667
+ function createClient(configOrUrl, apiKey, options) {
7668
+ if (typeof configOrUrl === "string") {
7669
+ return createClientFromConfig(resolveCreateClientConfig({
7670
+ url: configOrUrl,
7671
+ key: apiKey ?? "",
7672
+ ...options
7673
+ }));
6321
7674
  }
6322
- return merged;
7675
+ return createClientFromConfig(resolveCreateClientConfig(configOrUrl));
6323
7676
  }
6324
- var AthenaClientBuilderImpl = class {
6325
- baseUrl;
6326
- apiKey;
6327
- backendConfig = DEFAULT_BACKEND;
6328
- clientName;
6329
- defaultHeaders;
6330
- authConfig;
6331
- experimentalOptions;
6332
- url(url) {
6333
- this.baseUrl = url;
6334
- return this;
6335
- }
6336
- key(apiKey) {
6337
- this.apiKey = apiKey;
6338
- return this;
6339
- }
6340
- backend(backend) {
6341
- this.backendConfig = toBackendConfig(backend);
6342
- return this;
6343
- }
6344
- client(clientName) {
6345
- this.clientName = clientName;
6346
- return this;
6347
- }
6348
- headers(headers) {
6349
- this.defaultHeaders = headers;
6350
- return this;
6351
- }
6352
- auth(config) {
6353
- this.authConfig = mergeAuthClientConfig(this.authConfig, config);
6354
- return this;
7677
+
7678
+ // src/gateway/types.ts
7679
+ var Backend = {
7680
+ Athena: { type: "athena" },
7681
+ Postgrest: { type: "postgrest" },
7682
+ PostgreSQL: { type: "postgresql" },
7683
+ ScyllaDB: { type: "scylladb" }
7684
+ };
7685
+
7686
+ // src/schema/definitions.ts
7687
+ function defineModel(input) {
7688
+ return input;
7689
+ }
7690
+ function defineSchema(models) {
7691
+ return { models };
7692
+ }
7693
+ function defineDatabase(schemas) {
7694
+ return { schemas };
7695
+ }
7696
+ function defineRegistry(databases) {
7697
+ return databases;
7698
+ }
7699
+
7700
+ // src/schema/model-form.ts
7701
+ function resolveNullishValue(mode) {
7702
+ if (mode === "undefined") return void 0;
7703
+ if (mode === "null") return null;
7704
+ return "";
7705
+ }
7706
+ function isRecord10(value) {
7707
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
7708
+ }
7709
+ function isNullableColumn(model, key) {
7710
+ const nullable = model.meta.nullable;
7711
+ return nullable?.[key] === true;
7712
+ }
7713
+ function toModelFormDefaults(model, values, options) {
7714
+ const source = values;
7715
+ if (!isRecord10(source)) {
7716
+ return {};
6355
7717
  }
6356
- experimental(options) {
6357
- this.experimentalOptions = mergeExperimentalOptions(this.experimentalOptions, options);
6358
- return options.athenaStorageBackend ? this : this;
7718
+ const mode = options?.nullishMode ?? "empty-string";
7719
+ const nullishValue = resolveNullishValue(mode);
7720
+ const result = {};
7721
+ for (const [key, value] of Object.entries(source)) {
7722
+ if (value === null && isNullableColumn(model, key)) {
7723
+ result[key] = nullishValue;
7724
+ continue;
7725
+ }
7726
+ result[key] = value;
6359
7727
  }
6360
- options(options) {
6361
- if (options.client !== void 0) {
6362
- this.clientName = options.client;
7728
+ return result;
7729
+ }
7730
+ function toModelPayload(model, formValues, options) {
7731
+ const emptyStringAsNull = options?.emptyStringAsNull ?? true;
7732
+ const stripUndefined = options?.stripUndefined ?? true;
7733
+ const result = {};
7734
+ for (const [key, rawValue] of Object.entries(formValues)) {
7735
+ if (rawValue === void 0 && stripUndefined) {
7736
+ continue;
6363
7737
  }
6364
- if (options.backend !== void 0) {
6365
- this.backendConfig = toBackendConfig(options.backend);
7738
+ if (emptyStringAsNull && rawValue === "" && isNullableColumn(model, key)) {
7739
+ result[key] = null;
7740
+ continue;
6366
7741
  }
6367
- if (options.headers !== void 0) {
6368
- this.defaultHeaders = {
6369
- ...this.defaultHeaders ?? {},
6370
- ...options.headers
6371
- };
7742
+ result[key] = rawValue;
7743
+ }
7744
+ return result;
7745
+ }
7746
+ function createModelFormAdapter(model) {
7747
+ return {
7748
+ model,
7749
+ toDefaults(values, options) {
7750
+ return toModelFormDefaults(model, values, options);
7751
+ },
7752
+ toInsert(values, options) {
7753
+ return toModelPayload(model, values, options);
7754
+ },
7755
+ toUpdate(values, options) {
7756
+ return toModelPayload(model, values, options);
6372
7757
  }
6373
- if (options.auth !== void 0) {
6374
- this.authConfig = mergeAuthClientConfig(this.authConfig, options.auth);
7758
+ };
7759
+ }
7760
+
7761
+ // src/schema/table-columns.ts
7762
+ var COLUMN_CONFIG = /* @__PURE__ */ Symbol("athena.column.config");
7763
+ function createColumnBuilder(config) {
7764
+ return {
7765
+ [COLUMN_CONFIG]: config,
7766
+ optional() {
7767
+ return createColumnBuilder({
7768
+ ...config,
7769
+ nullable: true
7770
+ });
7771
+ },
7772
+ from(columnName) {
7773
+ return createColumnBuilder({
7774
+ ...config,
7775
+ columnName
7776
+ });
7777
+ },
7778
+ defaulted() {
7779
+ return createColumnBuilder({
7780
+ ...config,
7781
+ hasDefault: true
7782
+ });
7783
+ },
7784
+ generated() {
7785
+ return createColumnBuilder({
7786
+ ...config,
7787
+ isGenerated: true
7788
+ });
6375
7789
  }
6376
- if (options.experimental !== void 0) {
6377
- this.experimentalOptions = mergeExperimentalOptions(this.experimentalOptions, options.experimental);
7790
+ };
7791
+ }
7792
+ function isColumnBuilder(value) {
7793
+ return value !== null && typeof value === "object" && COLUMN_CONFIG in value;
7794
+ }
7795
+ function getColumnConfig(column) {
7796
+ return column[COLUMN_CONFIG];
7797
+ }
7798
+ function string() {
7799
+ return createColumnBuilder({
7800
+ kind: "string",
7801
+ nullable: false,
7802
+ hasDefault: false,
7803
+ isGenerated: false
7804
+ });
7805
+ }
7806
+ function number() {
7807
+ return createColumnBuilder({
7808
+ kind: "number",
7809
+ nullable: false,
7810
+ hasDefault: false,
7811
+ isGenerated: false
7812
+ });
7813
+ }
7814
+ function boolean() {
7815
+ return createColumnBuilder({
7816
+ kind: "boolean",
7817
+ nullable: false,
7818
+ hasDefault: false,
7819
+ isGenerated: false
7820
+ });
7821
+ }
7822
+ function json(schema) {
7823
+ return createColumnBuilder({
7824
+ kind: "json",
7825
+ nullable: false,
7826
+ hasDefault: false,
7827
+ isGenerated: false,
7828
+ jsonSchema: schema
7829
+ });
7830
+ }
7831
+ function enumeration(values) {
7832
+ if (values.length === 0) {
7833
+ throw new Error("enumeration() requires at least one value");
7834
+ }
7835
+ return createColumnBuilder({
7836
+ kind: "enumeration",
7837
+ nullable: false,
7838
+ hasDefault: false,
7839
+ isGenerated: false,
7840
+ enumValues: values
7841
+ });
7842
+ }
7843
+
7844
+ // src/schema/table-schemas.ts
7845
+ function isScalarFormKind(kind) {
7846
+ return kind === "string" || kind === "number" || kind === "boolean" || kind === "enumeration";
7847
+ }
7848
+ function createBaseSchema(column) {
7849
+ const config = getColumnConfig(column);
7850
+ switch (config.kind) {
7851
+ case "boolean":
7852
+ return z.boolean();
7853
+ case "number":
7854
+ return z.number();
7855
+ case "json":
7856
+ return config.jsonSchema ?? z.unknown();
7857
+ case "enumeration":
7858
+ if (!config.enumValues || config.enumValues.length === 0) {
7859
+ return z.string();
7860
+ }
7861
+ return z.enum(config.enumValues);
7862
+ case "string":
7863
+ default:
7864
+ return z.string();
7865
+ }
7866
+ }
7867
+ function applyNullable(schema, column) {
7868
+ const config = getColumnConfig(column);
7869
+ return config.nullable ? schema.nullable() : schema;
7870
+ }
7871
+ function applyInsertOptional(schema, column) {
7872
+ const config = getColumnConfig(column);
7873
+ return config.nullable || config.hasDefault ? schema.optional() : schema;
7874
+ }
7875
+ function createFormFieldSchema(column) {
7876
+ const config = getColumnConfig(column);
7877
+ const base = createBaseSchema(column);
7878
+ let schema;
7879
+ if (config.nullable && isScalarFormKind(config.kind)) {
7880
+ schema = z.union([base, z.literal("")]).transform((value) => value === "" ? null : value);
7881
+ } else {
7882
+ schema = applyNullable(base, column);
7883
+ }
7884
+ if (config.nullable || config.hasDefault) {
7885
+ schema = schema.optional();
7886
+ }
7887
+ return schema;
7888
+ }
7889
+ function buildTableSchemaBundle(model, columns) {
7890
+ const rowShape = {};
7891
+ const insertShape = {};
7892
+ const updateShape = {};
7893
+ const formShape = {};
7894
+ for (const [columnName, column] of Object.entries(columns)) {
7895
+ const config = getColumnConfig(column);
7896
+ const base = createBaseSchema(column);
7897
+ rowShape[columnName] = applyNullable(base, column);
7898
+ if (config.isGenerated) {
7899
+ continue;
6378
7900
  }
6379
- return options.experimental?.athenaStorageBackend ? this : this;
7901
+ insertShape[columnName] = applyInsertOptional(applyNullable(base, column), column);
7902
+ updateShape[columnName] = applyNullable(base, column).optional();
7903
+ formShape[columnName] = createFormFieldSchema(column);
6380
7904
  }
6381
- build() {
6382
- if (!this.baseUrl || !this.apiKey) {
6383
- throw new Error("AthenaClient requires url and key; call .url() and .key() before .build()");
7905
+ const rowSchema = z.object(rowShape);
7906
+ const insertSchema = z.object(insertShape);
7907
+ const updateSchema = z.object(updateShape);
7908
+ const formSchema = z.object(formShape).transform((value) => toModelPayload(model, value));
7909
+ return {
7910
+ row: rowSchema,
7911
+ insert: insertSchema,
7912
+ update: updateSchema,
7913
+ form: formSchema
7914
+ };
7915
+ }
7916
+
7917
+ // src/schema/table-builder.ts
7918
+ function assertColumnRecord(columns) {
7919
+ for (const [columnName, column] of Object.entries(columns)) {
7920
+ if (!isColumnBuilder(column)) {
7921
+ throw new Error(`Invalid column definition for "${columnName}"`);
6384
7922
  }
6385
- return createClientFromConfig({
6386
- baseUrl: this.baseUrl,
6387
- apiKey: this.apiKey,
6388
- client: this.clientName,
6389
- backend: this.backendConfig,
6390
- headers: this.defaultHeaders,
6391
- auth: this.authConfig,
6392
- experimental: this.experimentalOptions
6393
- });
6394
7923
  }
6395
- };
6396
- var AthenaClient = class _AthenaClient {
6397
- /** Create a fluent builder for a strongly-typed Athena SDK client. */
6398
- static builder() {
6399
- return new AthenaClientBuilderImpl();
7924
+ }
7925
+ function normalizeMappedNameInput(mappedName) {
7926
+ const normalized = mappedName.trim();
7927
+ if (!normalized) {
7928
+ throw new Error("table.from() requires a non-empty table name");
7929
+ }
7930
+ return normalized;
7931
+ }
7932
+ function normalizeSchemaNameInput(schemaName) {
7933
+ const normalized = schemaName.trim();
7934
+ if (!normalized) {
7935
+ throw new Error("table.schema() requires a non-empty schema name");
7936
+ }
7937
+ if (normalized.includes(".")) {
7938
+ throw new Error(
7939
+ 'table.schema() expects a schema name without dots. Use .schema("schema").from("table") or .from("schema.table").'
7940
+ );
7941
+ }
7942
+ return normalized;
7943
+ }
7944
+ function resolveTableTarget(logicalName, mappedName, explicitSchemaName) {
7945
+ const physicalName = (mappedName ?? logicalName).trim();
7946
+ if (!physicalName) {
7947
+ throw new Error("table() requires a non-empty name");
6400
7948
  }
6401
- /** Build a client from process environment variables. */
6402
- static fromEnvironment() {
6403
- const url = process.env.ATHENA_URL ?? process.env.ATHENA_GATEWAY_URL;
6404
- const key = process.env.ATHENA_API_KEY ?? process.env.ATHENA_GATEWAY_API_KEY;
6405
- if (!url || !key) {
7949
+ const firstDot = physicalName.indexOf(".");
7950
+ const lastDot = physicalName.lastIndexOf(".");
7951
+ if (firstDot > 0 && firstDot === lastDot) {
7952
+ const inlineSchema = physicalName.slice(0, firstDot).trim();
7953
+ const inlineModel = physicalName.slice(firstDot + 1).trim();
7954
+ if (!inlineSchema || !inlineModel) {
7955
+ throw new Error('table.from() schema-qualified names must look like "schema.table"');
7956
+ }
7957
+ if (explicitSchemaName && explicitSchemaName !== inlineSchema) {
6406
7958
  throw new Error(
6407
- "ATHENA_URL and ATHENA_API_KEY (or ATHENA_GATEWAY_URL and ATHENA_GATEWAY_API_KEY) are required"
7959
+ `table schema "${explicitSchemaName}" conflicts with mapped table "${physicalName}"`
6408
7960
  );
6409
7961
  }
6410
- return _AthenaClient.builder().url(url).key(key).build();
7962
+ return {
7963
+ schema: explicitSchemaName ?? inlineSchema,
7964
+ model: inlineModel,
7965
+ qualifiedName: `${explicitSchemaName ?? inlineSchema}.${inlineModel}`
7966
+ };
6411
7967
  }
6412
- };
6413
- function createClient(url, apiKey, options) {
6414
- return createClientFromConfig({
6415
- baseUrl: url,
6416
- apiKey,
6417
- client: options?.client,
6418
- backend: toBackendConfig(options?.backend),
6419
- headers: options?.headers,
6420
- auth: options?.auth,
6421
- experimental: options?.experimental
6422
- });
7968
+ if (explicitSchemaName) {
7969
+ return {
7970
+ schema: explicitSchemaName,
7971
+ model: physicalName,
7972
+ qualifiedName: `${explicitSchemaName}.${physicalName}`
7973
+ };
7974
+ }
7975
+ return {
7976
+ model: physicalName,
7977
+ qualifiedName: physicalName
7978
+ };
6423
7979
  }
6424
-
6425
- // src/gateway/types.ts
6426
- var Backend = {
6427
- Athena: { type: "athena" },
6428
- Postgrest: { type: "postgrest" },
6429
- PostgreSQL: { type: "postgresql" },
6430
- ScyllaDB: { type: "scylladb" }
6431
- };
6432
-
6433
- // src/schema/definitions.ts
6434
- function defineModel(input) {
6435
- return input;
7980
+ function toColumnMetadata(column) {
7981
+ const config = getColumnConfig(column);
7982
+ return {
7983
+ kind: config.kind,
7984
+ columnName: config.columnName,
7985
+ nullable: config.nullable,
7986
+ hasDefault: config.hasDefault,
7987
+ isGenerated: config.isGenerated,
7988
+ enumValues: config.enumValues
7989
+ };
6436
7990
  }
6437
- function defineSchema(models) {
6438
- return { models };
7991
+ function buildNullableMap(columns) {
7992
+ return Object.fromEntries(
7993
+ Object.entries(columns).map(([columnName, column]) => [columnName, getColumnConfig(column).nullable])
7994
+ );
6439
7995
  }
6440
- function defineDatabase(schemas) {
6441
- return { schemas };
7996
+ function buildColumnMetadataMap(columns) {
7997
+ return Object.fromEntries(
7998
+ Object.entries(columns).map(([columnName, column]) => [columnName, toColumnMetadata(column)])
7999
+ );
6442
8000
  }
6443
- function defineRegistry(databases) {
6444
- return databases;
8001
+ function finalizeTable(name, mappedName, schemaName, columns, primaryKey) {
8002
+ const target = resolveTableTarget(name, mappedName, schemaName);
8003
+ const model = defineModel({
8004
+ meta: {
8005
+ schema: target.schema,
8006
+ model: target.model,
8007
+ primaryKey: [...primaryKey],
8008
+ nullable: buildNullableMap(columns),
8009
+ columns: buildColumnMetadataMap(columns)
8010
+ }
8011
+ });
8012
+ const schemas = buildTableSchemaBundle(model, columns);
8013
+ return Object.assign(model, {
8014
+ kind: "table",
8015
+ name,
8016
+ mappedName,
8017
+ schemaName: target.schema,
8018
+ tableName: target.model,
8019
+ qualifiedName: target.qualifiedName,
8020
+ columns,
8021
+ schemas
8022
+ });
8023
+ }
8024
+ function createColumnsBuilder(name, mappedName, schemaName, columns) {
8025
+ assertColumnRecord(columns);
8026
+ return {
8027
+ name,
8028
+ mappedName,
8029
+ schemaName,
8030
+ columns,
8031
+ from(tableName) {
8032
+ const normalizedTableName = normalizeMappedNameInput(tableName);
8033
+ resolveTableTarget(name, normalizedTableName, schemaName);
8034
+ return createColumnsBuilder(name, normalizedTableName, schemaName, columns);
8035
+ },
8036
+ schema(nextSchemaName) {
8037
+ const normalizedSchemaName = normalizeSchemaNameInput(nextSchemaName);
8038
+ resolveTableTarget(name, mappedName, normalizedSchemaName);
8039
+ return createColumnsBuilder(name, mappedName, normalizedSchemaName, columns);
8040
+ },
8041
+ primaryKey(...keys) {
8042
+ return finalizeTable(name, mappedName, schemaName, columns, keys);
8043
+ }
8044
+ };
8045
+ }
8046
+ function createTableBuilder2(name, mappedName, schemaName) {
8047
+ return {
8048
+ name,
8049
+ mappedName,
8050
+ schemaName,
8051
+ from(tableName) {
8052
+ const normalizedTableName = normalizeMappedNameInput(tableName);
8053
+ resolveTableTarget(name, normalizedTableName, schemaName);
8054
+ return createTableBuilder2(name, normalizedTableName, schemaName);
8055
+ },
8056
+ schema(nextSchemaName) {
8057
+ const normalizedSchemaName = normalizeSchemaNameInput(nextSchemaName);
8058
+ resolveTableTarget(name, mappedName, normalizedSchemaName);
8059
+ return createTableBuilder2(name, mappedName, normalizedSchemaName);
8060
+ },
8061
+ columns(columns) {
8062
+ return createColumnsBuilder(name, mappedName, schemaName, columns);
8063
+ }
8064
+ };
8065
+ }
8066
+ function table(name) {
8067
+ if (!name.trim()) {
8068
+ throw new Error("table() requires a non-empty name");
8069
+ }
8070
+ return createTableBuilder2(name, void 0, void 0);
6445
8071
  }
6446
8072
 
6447
8073
  // src/schema/typed-client.ts
@@ -6483,12 +8109,10 @@ var RegistryNavigator = class {
6483
8109
  return modelDef;
6484
8110
  }
6485
8111
  resolveTableName(schema, model, modelDef) {
6486
- if (modelDef.meta.tableName) {
6487
- return modelDef.meta.tableName;
6488
- }
6489
- const schemaName = modelDef.meta.schema ?? schema;
6490
- const modelName = modelDef.meta.model ?? model;
6491
- return `${schemaName}.${modelName}`;
8112
+ return resolveAthenaModelTargetTableName(modelDef, {
8113
+ fallbackSchema: schema,
8114
+ fallbackModel: model
8115
+ });
6492
8116
  }
6493
8117
  };
6494
8118
  var TypedAthenaClientImpl = class _TypedAthenaClientImpl {
@@ -6515,17 +8139,20 @@ var TypedAthenaClientImpl = class _TypedAthenaClientImpl {
6515
8139
  this.clientOptions = {
6516
8140
  backend: input.options?.backend,
6517
8141
  client: input.options?.client,
6518
- headers: input.options?.headers
8142
+ headers: input.options?.headers,
8143
+ experimental: input.options?.experimental
6519
8144
  };
6520
8145
  this.baseClient = createClient(this.url, this.apiKey, {
6521
8146
  backend: this.clientOptions.backend,
6522
8147
  client: this.clientOptions.client,
6523
- headers: this.tenantHeaderMapper.apply(this.clientOptions.headers, tenantContext)
8148
+ headers: this.tenantHeaderMapper.apply(this.clientOptions.headers, tenantContext),
8149
+ experimental: this.clientOptions.experimental
6524
8150
  });
6525
8151
  this.db = this.baseClient.db;
6526
8152
  }
6527
- from(table, options) {
6528
- return this.baseClient.from(table, options);
8153
+ from(tableOrModel, options) {
8154
+ const from = this.baseClient.from;
8155
+ return from(tableOrModel, options);
6529
8156
  }
6530
8157
  rpc(fn, args, options) {
6531
8158
  return this.baseClient.rpc(fn, args, options);
@@ -6547,7 +8174,8 @@ var TypedAthenaClientImpl = class _TypedAthenaClientImpl {
6547
8174
  tenantContext: {
6548
8175
  ...this.tenantContext,
6549
8176
  ...context ?? {}
6550
- }
8177
+ },
8178
+ experimental: this.clientOptions.experimental
6551
8179
  }
6552
8180
  });
6553
8181
  }
@@ -6653,8 +8281,8 @@ var POSTGRES_CATALOG_SQL = {
6653
8281
  ORDER BY sn.nspname, sc.relname, con.conname;
6654
8282
  `
6655
8283
  };
6656
- function tableKey(schema, table) {
6657
- return `${schema}.${table}`;
8284
+ function tableKey(schema, table2) {
8285
+ return `${schema}.${table2}`;
6658
8286
  }
6659
8287
  function relationKey(...parts) {
6660
8288
  const base = parts.join("_").replace(/[^A-Za-z0-9_]+/g, "_").replace(/^_+|_+$/g, "");
@@ -6765,8 +8393,8 @@ var PostgresCatalogSnapshotAssembler = class {
6765
8393
  schemas = {};
6766
8394
  addColumnRows(columnRows, enumMap) {
6767
8395
  for (const row of columnRows) {
6768
- const table = this.ensureTable(row.schema_name, row.table_name);
6769
- table.columns[row.column_name] = {
8396
+ const table2 = this.ensureTable(row.schema_name, row.table_name);
8397
+ table2.columns[row.column_name] = {
6770
8398
  name: row.column_name,
6771
8399
  dataType: row.data_type,
6772
8400
  udtName: row.udt_name,
@@ -6782,12 +8410,12 @@ var PostgresCatalogSnapshotAssembler = class {
6782
8410
  }
6783
8411
  addPrimaryKeyRows(primaryKeyRows) {
6784
8412
  for (const row of primaryKeyRows) {
6785
- const table = this.ensureTable(row.schema_name, row.table_name);
8413
+ const table2 = this.ensureTable(row.schema_name, row.table_name);
6786
8414
  const primaryKeyColumns = coerceStringArray(row.columns);
6787
8415
  row.columns = primaryKeyColumns;
6788
- table.primaryKey = primaryKeyColumns;
8416
+ table2.primaryKey = primaryKeyColumns;
6789
8417
  for (const columnName of primaryKeyColumns) {
6790
- const column = table.columns[columnName];
8418
+ const column = table2.columns[columnName];
6791
8419
  if (column) {
6792
8420
  column.isPrimaryKey = true;
6793
8421
  }
@@ -6903,14 +8531,14 @@ var PostgresCatalogSnapshotAssembler = class {
6903
8531
  }
6904
8532
  return schema.tables[tableName];
6905
8533
  }
6906
- upsertRelation(table, baseKey, relation) {
8534
+ upsertRelation(table2, baseKey, relation) {
6907
8535
  let key = baseKey;
6908
8536
  let suffix = 2;
6909
- while (table.relations[key]) {
8537
+ while (table2.relations[key]) {
6910
8538
  key = `${baseKey}_${suffix}`;
6911
8539
  suffix += 1;
6912
8540
  }
6913
- table.relations[key] = relation;
8541
+ table2.relations[key] = relation;
6914
8542
  }
6915
8543
  };
6916
8544
 
@@ -7001,67 +8629,6 @@ function createPostgresIntrospectionProvider(options) {
7001
8629
  return new PostgresIntrospectionProvider(options);
7002
8630
  }
7003
8631
 
7004
- // src/schema/model-form.ts
7005
- function resolveNullishValue(mode) {
7006
- if (mode === "undefined") return void 0;
7007
- if (mode === "null") return null;
7008
- return "";
7009
- }
7010
- function isRecord9(value) {
7011
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
7012
- }
7013
- function isNullableColumn(model, key) {
7014
- const nullable = model.meta.nullable;
7015
- return nullable?.[key] === true;
7016
- }
7017
- function toModelFormDefaults(model, values, options) {
7018
- const source = values;
7019
- if (!isRecord9(source)) {
7020
- return {};
7021
- }
7022
- const mode = options?.nullishMode ?? "empty-string";
7023
- const nullishValue = resolveNullishValue(mode);
7024
- const result = {};
7025
- for (const [key, value] of Object.entries(source)) {
7026
- if (value === null && isNullableColumn(model, key)) {
7027
- result[key] = nullishValue;
7028
- continue;
7029
- }
7030
- result[key] = value;
7031
- }
7032
- return result;
7033
- }
7034
- function toModelPayload(model, formValues, options) {
7035
- const emptyStringAsNull = options?.emptyStringAsNull ?? true;
7036
- const stripUndefined = options?.stripUndefined ?? true;
7037
- const result = {};
7038
- for (const [key, rawValue] of Object.entries(formValues)) {
7039
- if (rawValue === void 0 && stripUndefined) {
7040
- continue;
7041
- }
7042
- if (emptyStringAsNull && rawValue === "" && isNullableColumn(model, key)) {
7043
- result[key] = null;
7044
- continue;
7045
- }
7046
- result[key] = rawValue;
7047
- }
7048
- return result;
7049
- }
7050
- function createModelFormAdapter(model) {
7051
- return {
7052
- model,
7053
- toDefaults(values, options) {
7054
- return toModelFormDefaults(model, values, options);
7055
- },
7056
- toInsert(values, options) {
7057
- return toModelPayload(model, values, options);
7058
- },
7059
- toUpdate(values, options) {
7060
- return toModelPayload(model, values, options);
7061
- }
7062
- };
7063
- }
7064
-
7065
8632
  // src/generator/schema-selection.ts
7066
8633
  var DEFAULT_POSTGRES_SCHEMAS = ["public"];
7067
8634
  function collectSchemaNames(input) {
@@ -7107,6 +8674,7 @@ var DEFAULT_TARGETS = {
7107
8674
  database: "athena/relations.ts",
7108
8675
  registry: "athena/config.ts"
7109
8676
  };
8677
+ var DEFAULT_OUTPUT_FORMAT = "define-model";
7110
8678
  var DEFAULT_NAMING = {
7111
8679
  modelType: "pascal",
7112
8680
  modelConst: "camel",
@@ -7122,6 +8690,9 @@ var DEFAULT_EXPERIMENTAL_FLAGS = {
7122
8690
  postgresGatewayIntrospection: false,
7123
8691
  scyllaProviderContracts: true
7124
8692
  };
8693
+ var DEFAULT_INTERNAL_CONFIG = {
8694
+ schemaVersion: 1
8695
+ };
7125
8696
  var PROJECT_ENV_FILENAMES = [".env", ".env.local"];
7126
8697
  var DIRECT_CONNECTION_STRING_ENV_KEYS = [
7127
8698
  "ATHENA_GENERATOR_PG_URL",
@@ -7138,6 +8709,27 @@ var GATEWAY_API_KEY_ENV_KEYS = [
7138
8709
  "ATHENA_GATEWAY_API_KEY",
7139
8710
  "ATHENA_GENERATOR_API_KEY"
7140
8711
  ];
8712
+ var GENERATOR_SCHEMA_ENV_KEYS = ["ATHENA_GENERATOR_SCHEMAS"];
8713
+ var OUTPUT_FORMAT_ENV_KEYS = ["ATHENA_GENERATOR_OUTPUT_FORMAT"];
8714
+ var MODEL_TARGET_ENV_KEYS = ["ATHENA_GENERATOR_MODEL_TARGET"];
8715
+ var SCHEMA_TARGET_ENV_KEYS = ["ATHENA_GENERATOR_SCHEMA_TARGET"];
8716
+ var DATABASE_TARGET_ENV_KEYS = ["ATHENA_GENERATOR_DATABASE_TARGET"];
8717
+ var REGISTRY_TARGET_ENV_KEYS = ["ATHENA_GENERATOR_REGISTRY_TARGET"];
8718
+ var PLACEHOLDER_MAP_ENV_KEYS = ["ATHENA_GENERATOR_PLACEHOLDER_MAP"];
8719
+ var MODEL_TYPE_ENV_KEYS = ["ATHENA_GENERATOR_MODEL_TYPE", "ATHENA_GENERATOR_MODEL_STYLE"];
8720
+ var MODEL_CONST_ENV_KEYS = ["ATHENA_GENERATOR_MODEL_CONST"];
8721
+ var SCHEMA_CONST_ENV_KEYS = ["ATHENA_GENERATOR_SCHEMA_CONST"];
8722
+ var DATABASE_CONST_ENV_KEYS = ["ATHENA_GENERATOR_DATABASE_CONST"];
8723
+ var REGISTRY_CONST_ENV_KEYS = ["ATHENA_GENERATOR_REGISTRY_CONST"];
8724
+ var EMIT_RELATIONS_ENV_KEYS = ["ATHENA_GENERATOR_EMIT_RELATIONS"];
8725
+ var EMIT_REGISTRY_ENV_KEYS = ["ATHENA_GENERATOR_EMIT_REGISTRY"];
8726
+ var GATEWAY_BACKEND_ENV_KEYS = ["ATHENA_GENERATOR_BACKEND"];
8727
+ var GATEWAY_EXPERIMENTAL_ENV_KEYS = ["ATHENA_GENERATOR_GATEWAY_EXPERIMENTAL"];
8728
+ var SCYLLA_PROVIDER_CONTRACTS_ENV_KEYS = ["ATHENA_GENERATOR_SCYLLA_PROVIDER_CONTRACTS"];
8729
+ var ENV_ONLY_CONFIG_PATH = "[environment defaults]";
8730
+ var NAMING_STYLE_VALUES = ["preserve", "camel", "pascal", "snake", "kebab"];
8731
+ var OUTPUT_FORMAT_VALUES = ["define-model", "table-builder"];
8732
+ var BACKEND_TYPE_VALUES = ["athena", "postgrest", "postgresql", "scylladb"];
7141
8733
  function normalizeRawEnvValue(rawValue) {
7142
8734
  if (rawValue.startsWith('"') && rawValue.endsWith('"') && rawValue.length >= 2) {
7143
8735
  const inner = rawValue.slice(1, -1);
@@ -7229,6 +8821,50 @@ function resolveFallbackValue(fallbackKeys) {
7229
8821
  }
7230
8822
  return void 0;
7231
8823
  }
8824
+ function normalizeOneOfValue(rawValue, allowedValues, envKeys) {
8825
+ if (!rawValue) {
8826
+ return void 0;
8827
+ }
8828
+ if (allowedValues.includes(rawValue)) {
8829
+ return rawValue;
8830
+ }
8831
+ throw new Error(
8832
+ `Generator config env vars ${envKeys.join(", ")} must resolve to one of: ${allowedValues.join(", ")}. Received: ${rawValue}.`
8833
+ );
8834
+ }
8835
+ function resolveOptionalOneOf(envKeys, allowedValues) {
8836
+ return normalizeOneOfValue(resolveFallbackValue(envKeys), allowedValues, envKeys);
8837
+ }
8838
+ function resolveOptionalBoolean(envKeys) {
8839
+ const rawValue = resolveFallbackValue(envKeys);
8840
+ return rawValue === void 0 ? void 0 : parseBooleanFlag2(rawValue, false);
8841
+ }
8842
+ function resolveOptionalJson(envKeys) {
8843
+ const rawValue = resolveFallbackValue(envKeys);
8844
+ if (rawValue === void 0) {
8845
+ return void 0;
8846
+ }
8847
+ try {
8848
+ return JSON.parse(rawValue);
8849
+ } catch (error) {
8850
+ const message = error instanceof Error ? error.message : String(error);
8851
+ throw new Error(
8852
+ `Generator config env vars ${envKeys.join(", ")} must contain valid JSON. ${message}`
8853
+ );
8854
+ }
8855
+ }
8856
+ function deriveDatabaseNameFromConnectionString(connectionString) {
8857
+ try {
8858
+ const parsedUrl = new URL(connectionString);
8859
+ if (!POSTGRES_PROTOCOLS.has(parsedUrl.protocol)) {
8860
+ return void 0;
8861
+ }
8862
+ const pathname = parsedUrl.pathname.replace(/^\/+/, "").trim();
8863
+ return pathname.length > 0 ? decodeURIComponent(pathname) : void 0;
8864
+ } catch {
8865
+ return void 0;
8866
+ }
8867
+ }
7232
8868
  function normalizeOptionalString(value, fallbackKeys) {
7233
8869
  if (typeof value === "string") {
7234
8870
  const trimmed = value.trim();
@@ -7302,12 +8938,13 @@ function normalizeExperimentalFlags(input) {
7302
8938
  }
7303
8939
  function normalizeOutputConfig(output) {
7304
8940
  return {
8941
+ format: output?.format ?? DEFAULT_OUTPUT_FORMAT,
7305
8942
  targets: {
7306
8943
  ...DEFAULT_TARGETS,
7307
- ...output.targets ?? {}
8944
+ ...output?.targets ?? {}
7308
8945
  },
7309
8946
  placeholderMap: {
7310
- ...output.placeholderMap ?? {}
8947
+ ...output?.placeholderMap ?? {}
7311
8948
  }
7312
8949
  };
7313
8950
  }
@@ -7318,7 +8955,7 @@ function normalizeProviderConfig(provider) {
7318
8955
  "provider.connectionString",
7319
8956
  DIRECT_CONNECTION_STRING_ENV_KEYS
7320
8957
  );
7321
- const database = normalizeOptionalString(provider.database, POSTGRES_DATABASE_ENV_KEYS);
8958
+ const database = normalizeOptionalString(provider.database, POSTGRES_DATABASE_ENV_KEYS) ?? deriveDatabaseNameFromConnectionString(connectionString);
7322
8959
  return {
7323
8960
  ...provider,
7324
8961
  connectionString: applyPostgresPasswordFallback(connectionString),
@@ -7337,11 +8974,7 @@ function normalizeProviderConfig(provider) {
7337
8974
  "provider.apiKey",
7338
8975
  GATEWAY_API_KEY_ENV_KEYS
7339
8976
  );
7340
- const database = normalizeRequiredString(
7341
- provider.database,
7342
- "provider.database",
7343
- POSTGRES_DATABASE_ENV_KEYS
7344
- );
8977
+ const database = normalizeOptionalString(provider.database, POSTGRES_DATABASE_ENV_KEYS) ?? "postgres";
7345
8978
  return {
7346
8979
  ...provider,
7347
8980
  gatewayUrl,
@@ -7350,6 +8983,26 @@ function normalizeProviderConfig(provider) {
7350
8983
  schemas: normalizeSchemaSelection(provider.schemas)
7351
8984
  };
7352
8985
  }
8986
+ if (provider.kind === "scylla" && provider.mode === "direct") {
8987
+ if (!provider.contactPoints?.length) {
8988
+ throw new Error(
8989
+ "Generator config is missing provider.contactPoints for scylla direct mode."
8990
+ );
8991
+ }
8992
+ const keyspace = normalizeOptionalString(provider.keyspace, []);
8993
+ if (!keyspace) {
8994
+ throw new Error(
8995
+ "Generator config is missing provider.keyspace for scylla direct mode."
8996
+ );
8997
+ }
8998
+ return {
8999
+ kind: "scylla",
9000
+ mode: "direct",
9001
+ contactPoints: provider.contactPoints.slice(),
9002
+ keyspace,
9003
+ datacenter: normalizeOptionalString(provider.datacenter, [])
9004
+ };
9005
+ }
7353
9006
  return provider;
7354
9007
  }
7355
9008
  function isAthenaGeneratorConfig(value) {
@@ -7357,7 +9010,7 @@ function isAthenaGeneratorConfig(value) {
7357
9010
  return false;
7358
9011
  }
7359
9012
  const record = value;
7360
- return Boolean(record.provider && typeof record.provider === "object") && Boolean(record.output && typeof record.output === "object");
9013
+ return Boolean(record.provider && typeof record.provider === "object") && (record.output === void 0 || typeof record.output === "object");
7361
9014
  }
7362
9015
  function normalizeGeneratorConfig(input) {
7363
9016
  return {
@@ -7368,7 +9021,10 @@ function normalizeGeneratorConfig(input) {
7368
9021
  ...input.naming ?? {}
7369
9022
  },
7370
9023
  features: normalizeFeatureFlags(input.features),
7371
- experimental: normalizeExperimentalFlags(input.experimental)
9024
+ experimental: normalizeExperimentalFlags(input.experimental),
9025
+ internal: {
9026
+ ...DEFAULT_INTERNAL_CONFIG
9027
+ }
7372
9028
  };
7373
9029
  }
7374
9030
  function defineGeneratorConfig(config) {
@@ -7425,16 +9081,123 @@ function importConfigModule(moduleSpecifier) {
7425
9081
  );
7426
9082
  return runtimeImport(moduleSpecifier);
7427
9083
  }
9084
+ function buildEnvironmentOutputConfig() {
9085
+ const format = resolveOptionalOneOf(OUTPUT_FORMAT_ENV_KEYS, OUTPUT_FORMAT_VALUES);
9086
+ const modelTarget = resolveFallbackValue(MODEL_TARGET_ENV_KEYS);
9087
+ const schemaTarget = resolveFallbackValue(SCHEMA_TARGET_ENV_KEYS);
9088
+ const databaseTarget = resolveFallbackValue(DATABASE_TARGET_ENV_KEYS);
9089
+ const registryTarget = resolveFallbackValue(REGISTRY_TARGET_ENV_KEYS);
9090
+ const placeholderMap = resolveOptionalJson(PLACEHOLDER_MAP_ENV_KEYS);
9091
+ if (format === void 0 && modelTarget === void 0 && schemaTarget === void 0 && databaseTarget === void 0 && registryTarget === void 0 && placeholderMap === void 0) {
9092
+ return void 0;
9093
+ }
9094
+ return {
9095
+ format,
9096
+ targets: {
9097
+ ...modelTarget ? { model: modelTarget } : {},
9098
+ ...schemaTarget ? { schema: schemaTarget } : {},
9099
+ ...databaseTarget ? { database: databaseTarget } : {},
9100
+ ...registryTarget ? { registry: registryTarget } : {}
9101
+ },
9102
+ placeholderMap
9103
+ };
9104
+ }
9105
+ function buildEnvironmentNamingConfig() {
9106
+ const modelType = resolveOptionalOneOf(MODEL_TYPE_ENV_KEYS, NAMING_STYLE_VALUES);
9107
+ const modelConst = resolveOptionalOneOf(MODEL_CONST_ENV_KEYS, NAMING_STYLE_VALUES);
9108
+ const schemaConst = resolveOptionalOneOf(SCHEMA_CONST_ENV_KEYS, NAMING_STYLE_VALUES);
9109
+ const databaseConst = resolveOptionalOneOf(DATABASE_CONST_ENV_KEYS, NAMING_STYLE_VALUES);
9110
+ const registryConst = resolveOptionalOneOf(REGISTRY_CONST_ENV_KEYS, NAMING_STYLE_VALUES);
9111
+ if (modelType === void 0 && modelConst === void 0 && schemaConst === void 0 && databaseConst === void 0 && registryConst === void 0) {
9112
+ return void 0;
9113
+ }
9114
+ return {
9115
+ ...modelType ? { modelType } : {},
9116
+ ...modelConst ? { modelConst } : {},
9117
+ ...schemaConst ? { schemaConst } : {},
9118
+ ...databaseConst ? { databaseConst } : {},
9119
+ ...registryConst ? { registryConst } : {}
9120
+ };
9121
+ }
9122
+ function buildEnvironmentFeatureFlags() {
9123
+ const emitRelations = resolveOptionalBoolean(EMIT_RELATIONS_ENV_KEYS);
9124
+ const emitRegistry = resolveOptionalBoolean(EMIT_REGISTRY_ENV_KEYS);
9125
+ if (emitRelations === void 0 && emitRegistry === void 0) {
9126
+ return void 0;
9127
+ }
9128
+ return {
9129
+ ...emitRelations !== void 0 ? { emitRelations } : {},
9130
+ ...emitRegistry !== void 0 ? { emitRegistry } : {}
9131
+ };
9132
+ }
9133
+ function buildEnvironmentExperimentalFlags() {
9134
+ const postgresGatewayIntrospection = resolveOptionalBoolean(GATEWAY_EXPERIMENTAL_ENV_KEYS);
9135
+ const scyllaProviderContracts = resolveOptionalBoolean(SCYLLA_PROVIDER_CONTRACTS_ENV_KEYS);
9136
+ if (postgresGatewayIntrospection === void 0 && scyllaProviderContracts === void 0) {
9137
+ return void 0;
9138
+ }
9139
+ return {
9140
+ ...postgresGatewayIntrospection !== void 0 ? { postgresGatewayIntrospection } : {},
9141
+ ...scyllaProviderContracts !== void 0 ? { scyllaProviderContracts } : {}
9142
+ };
9143
+ }
9144
+ function buildEnvironmentProviderConfig() {
9145
+ const directConnectionString = resolveFallbackValue(DIRECT_CONNECTION_STRING_ENV_KEYS);
9146
+ if (directConnectionString) {
9147
+ return {
9148
+ kind: "postgres",
9149
+ mode: "direct",
9150
+ connectionString: directConnectionString,
9151
+ database: normalizeOptionalString(void 0, POSTGRES_DATABASE_ENV_KEYS),
9152
+ schemas: normalizeSchemaSelection(resolveFallbackValue(GENERATOR_SCHEMA_ENV_KEYS))
9153
+ };
9154
+ }
9155
+ const gatewayUrl = resolveFallbackValue(GATEWAY_URL_ENV_KEYS);
9156
+ const apiKey = resolveFallbackValue(GATEWAY_API_KEY_ENV_KEYS);
9157
+ if (gatewayUrl && apiKey) {
9158
+ const backend = resolveOptionalOneOf(GATEWAY_BACKEND_ENV_KEYS, BACKEND_TYPE_VALUES);
9159
+ return {
9160
+ kind: "postgres",
9161
+ mode: "gateway",
9162
+ gatewayUrl,
9163
+ apiKey,
9164
+ database: normalizeOptionalString(void 0, POSTGRES_DATABASE_ENV_KEYS),
9165
+ schemas: normalizeSchemaSelection(resolveFallbackValue(GENERATOR_SCHEMA_ENV_KEYS)),
9166
+ backend
9167
+ };
9168
+ }
9169
+ return void 0;
9170
+ }
9171
+ function createEnvironmentGeneratorConfig() {
9172
+ const provider = buildEnvironmentProviderConfig();
9173
+ if (!provider) {
9174
+ return void 0;
9175
+ }
9176
+ return {
9177
+ provider,
9178
+ output: buildEnvironmentOutputConfig(),
9179
+ naming: buildEnvironmentNamingConfig(),
9180
+ features: buildEnvironmentFeatureFlags(),
9181
+ experimental: buildEnvironmentExperimentalFlags()
9182
+ };
9183
+ }
7428
9184
  async function loadGeneratorConfig(options = {}) {
7429
9185
  const cwd = options.cwd ?? process.cwd();
7430
9186
  const restoreProjectEnv = applyProjectEnv(cwd);
7431
- const resolvedPath = options.configPath ? resolve(cwd, options.configPath) : findGeneratorConfigPath(cwd);
7432
- if (!resolvedPath) {
7433
- throw new Error(
7434
- `No generator config found in ${cwd}. Expected one of: ${DEFAULT_CONFIG_CANDIDATES.join(", ")}`
7435
- );
7436
- }
7437
9187
  try {
9188
+ const resolvedPath = options.configPath ? resolve(cwd, options.configPath) : findGeneratorConfigPath(cwd);
9189
+ if (!resolvedPath) {
9190
+ const environmentConfig = createEnvironmentGeneratorConfig();
9191
+ if (environmentConfig) {
9192
+ return {
9193
+ configPath: ENV_ONLY_CONFIG_PATH,
9194
+ config: normalizeGeneratorConfig(environmentConfig)
9195
+ };
9196
+ }
9197
+ throw new Error(
9198
+ `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).`
9199
+ );
9200
+ }
7438
9201
  const moduleUrl = pathToFileURL(resolvedPath);
7439
9202
  const module = await importConfigModule(`${moduleUrl.href}?cacheBust=${Date.now()}`);
7440
9203
  const rawConfig = extractConfigExport(module);
@@ -7655,59 +9418,6 @@ function escapeStringLiteral(value) {
7655
9418
  return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
7656
9419
  }
7657
9420
 
7658
- // src/generator/placeholders.ts
7659
- function createStyleTokens(prefix, value) {
7660
- return {
7661
- [prefix]: value,
7662
- [`${prefix}_camel`]: applyNamingStyle(value, "camel"),
7663
- [`${prefix}_pascal`]: applyNamingStyle(value, "pascal"),
7664
- [`${prefix}_snake`]: applyNamingStyle(value, "snake"),
7665
- [`${prefix}_kebab`]: applyNamingStyle(value, "kebab")
7666
- };
7667
- }
7668
- function renderTemplate(template, tokenMap) {
7669
- return template.replace(/\{([A-Za-z0-9_]+)\}/g, (_match, token) => {
7670
- if (!(token in tokenMap)) {
7671
- throw new Error(`Unknown placeholder token "${token}" in template "${template}"`);
7672
- }
7673
- return tokenMap[token];
7674
- });
7675
- }
7676
- function resolvePlaceholderMap(baseTokens, outputConfig) {
7677
- const resolved = {
7678
- ...baseTokens
7679
- };
7680
- const reservedTokenKeys = new Set(Object.keys(baseTokens));
7681
- const entries = Object.entries(outputConfig.placeholderMap ?? {});
7682
- for (let index = 0; index < entries.length; index += 1) {
7683
- const [key, value] = entries[index];
7684
- if (reservedTokenKeys.has(key)) {
7685
- continue;
7686
- }
7687
- let current = value;
7688
- for (let depth = 0; depth < 8; depth += 1) {
7689
- const next = renderTemplate(current, resolved);
7690
- if (next === current) {
7691
- break;
7692
- }
7693
- current = next;
7694
- }
7695
- resolved[key] = current;
7696
- }
7697
- return resolved;
7698
- }
7699
- function renderOutputPath(template, context, outputConfig) {
7700
- const baseTokens = {
7701
- provider: context.provider,
7702
- kind: context.kind,
7703
- ...createStyleTokens("database", context.database),
7704
- ...createStyleTokens("schema", context.schema),
7705
- ...createStyleTokens("model", context.model)
7706
- };
7707
- const tokens = resolvePlaceholderMap(baseTokens, outputConfig);
7708
- return renderTemplate(template, tokens);
7709
- }
7710
-
7711
9421
  // src/generator/postgres-type-mapping.ts
7712
9422
  var NUMBER_TYPES = /* @__PURE__ */ new Set([
7713
9423
  "int2",
@@ -7824,7 +9534,60 @@ function resolvePostgresColumnType(column) {
7824
9534
  return wrapArrayType(baseType, column.arrayDimensions);
7825
9535
  }
7826
9536
 
7827
- // src/generator/renderer.ts
9537
+ // src/generator/placeholders.ts
9538
+ function createStyleTokens(prefix, value) {
9539
+ return {
9540
+ [prefix]: value,
9541
+ [`${prefix}_camel`]: applyNamingStyle(value, "camel"),
9542
+ [`${prefix}_pascal`]: applyNamingStyle(value, "pascal"),
9543
+ [`${prefix}_snake`]: applyNamingStyle(value, "snake"),
9544
+ [`${prefix}_kebab`]: applyNamingStyle(value, "kebab")
9545
+ };
9546
+ }
9547
+ function renderTemplate(template, tokenMap) {
9548
+ return template.replace(/\{([A-Za-z0-9_]+)\}/g, (_match, token) => {
9549
+ if (!(token in tokenMap)) {
9550
+ throw new Error(`Unknown placeholder token "${token}" in template "${template}"`);
9551
+ }
9552
+ return tokenMap[token];
9553
+ });
9554
+ }
9555
+ function resolvePlaceholderMap(baseTokens, outputConfig) {
9556
+ const resolved = {
9557
+ ...baseTokens
9558
+ };
9559
+ const reservedTokenKeys = new Set(Object.keys(baseTokens));
9560
+ const entries = Object.entries(outputConfig.placeholderMap ?? {});
9561
+ for (let index = 0; index < entries.length; index += 1) {
9562
+ const [key, value] = entries[index];
9563
+ if (reservedTokenKeys.has(key)) {
9564
+ continue;
9565
+ }
9566
+ let current = value;
9567
+ for (let depth = 0; depth < 8; depth += 1) {
9568
+ const next = renderTemplate(current, resolved);
9569
+ if (next === current) {
9570
+ break;
9571
+ }
9572
+ current = next;
9573
+ }
9574
+ resolved[key] = current;
9575
+ }
9576
+ return resolved;
9577
+ }
9578
+ function renderOutputPath(template, context, outputConfig) {
9579
+ const baseTokens = {
9580
+ provider: context.provider,
9581
+ kind: context.kind,
9582
+ ...createStyleTokens("database", context.database),
9583
+ ...createStyleTokens("schema", context.schema),
9584
+ ...createStyleTokens("model", context.model)
9585
+ };
9586
+ const tokens = resolvePlaceholderMap(baseTokens, outputConfig);
9587
+ return renderTemplate(template, tokens);
9588
+ }
9589
+
9590
+ // src/generator/render-shared.ts
7828
9591
  function normalizePath(pathValue) {
7829
9592
  return pathValue.replace(/\\/g, "/");
7830
9593
  }
@@ -7837,11 +9600,13 @@ function toModuleImportPath(fromFile, targetFile) {
7837
9600
  );
7838
9601
  return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
7839
9602
  }
9603
+ function resolveOutputPath(target, tokens, config) {
9604
+ return normalizePath(renderOutputPath(target, tokens, config.output));
9605
+ }
7840
9606
  function renderObjectKey(key) {
7841
- const escaped = escapeTypePropertyName(key);
7842
- return escaped.startsWith("'") ? escaped : escaped;
9607
+ return escapeTypePropertyName(key);
7843
9608
  }
7844
- function renderRelation(relation) {
9609
+ function renderRelationLiteral(relation) {
7845
9610
  const through = relation.through ? `,
7846
9611
  through: {
7847
9612
  schema: ${escapeStringLiteral(relation.through.schema)},
@@ -7857,54 +9622,12 @@ function renderRelation(relation) {
7857
9622
  targetColumns: [${relation.targetColumns.map((value) => escapeStringLiteral(value)).join(", ")}]${through}
7858
9623
  }`;
7859
9624
  }
7860
- function renderModelArtifact(snapshot, descriptor, config) {
7861
- const columnLines = Object.values(descriptor.table.columns).map((column) => {
7862
- const propertyName = escapeTypePropertyName(column.name);
7863
- const baseType = resolvePostgresColumnType(column);
7864
- const isOptional = column.isNullable;
7865
- const typeWithNullability = column.isNullable ? `${baseType} | null` : baseType;
7866
- return ` ${propertyName}${isOptional ? "?" : ""}: ${typeWithNullability}`;
7867
- }).join("\n");
7868
- const nullableLines = Object.values(descriptor.table.columns).map((column) => ` ${renderObjectKey(column.name)}: ${column.isNullable ? "true" : "false"}`).join(",\n");
7869
- const relationEntries = Object.entries(descriptor.table.relations);
7870
- const relationBlock = config.features.emitRelations && relationEntries.length > 0 ? `,
7871
- relations: {
7872
- ${relationEntries.map(([relationKey2, relationValue]) => ` ${renderObjectKey(relationKey2)}: ${renderRelation(relationValue)}`).join(",\n")}
7873
- }` : "";
7874
- const content = `import { defineModel } from '@xylex-group/athena'
7875
-
7876
- export interface ${descriptor.rowTypeName} {
7877
- ${columnLines}
7878
- }
7879
-
7880
- export type ${descriptor.insertTypeName} = Partial<${descriptor.rowTypeName}>
7881
- export type ${descriptor.updateTypeName} = Partial<${descriptor.insertTypeName}>
7882
-
7883
- export const ${descriptor.modelConstName} = defineModel<${descriptor.rowTypeName}, ${descriptor.insertTypeName}, ${descriptor.updateTypeName}>({
7884
- meta: {
7885
- database: ${escapeStringLiteral(snapshot.database)},
7886
- schema: ${escapeStringLiteral(descriptor.schemaName)},
7887
- model: ${escapeStringLiteral(descriptor.tableName)},
7888
- tableName: ${escapeStringLiteral(`${descriptor.schemaName}.${descriptor.tableName}`)},
7889
- primaryKey: [${descriptor.table.primaryKey.map((value) => escapeStringLiteral(value)).join(", ")}],
7890
- nullable: {
7891
- ${nullableLines}
7892
- }${relationBlock}
7893
- }
7894
- })
7895
- `;
7896
- return {
7897
- kind: "model",
7898
- path: descriptor.filePath,
7899
- content
7900
- };
7901
- }
7902
9625
  function renderSchemaArtifact(descriptor) {
7903
9626
  const importLines = descriptor.models.map((modelDescriptor) => {
7904
9627
  const importPath = toModuleImportPath(descriptor.filePath, modelDescriptor.filePath);
7905
- return `import { ${modelDescriptor.modelConstName} } from '${importPath}'`;
9628
+ return `import { ${modelDescriptor.exportConstName} } from '${importPath}'`;
7906
9629
  }).join("\n");
7907
- const modelEntries = descriptor.models.map((modelDescriptor) => ` ${renderObjectKey(modelDescriptor.tableName)}: ${modelDescriptor.modelConstName}`).join(",\n");
9630
+ const modelEntries = descriptor.models.map((modelDescriptor) => ` ${renderObjectKey(modelDescriptor.tableName)}: ${modelDescriptor.exportConstName}`).join(",\n");
7908
9631
  const content = `import { defineSchema } from '@xylex-group/athena'
7909
9632
  ${importLines ? `
7910
9633
  ${importLines}
@@ -7939,11 +9662,18 @@ ${schemaEntries}
7939
9662
  content
7940
9663
  };
7941
9664
  }
7942
- function renderRegistryArtifact(registryPath, databasePath, databaseConstName, registryConstName, databaseName) {
9665
+ function renderRegistryArtifact(registryPath, databasePath, databaseConstName, registryConstName, databaseName, generatedAt, outputFormat, schemaVersion) {
7943
9666
  const databaseImportPath = toModuleImportPath(registryPath, databasePath);
7944
9667
  const content = `import { defineRegistry } from '@xylex-group/athena'
7945
9668
  import { ${databaseConstName} } from '${databaseImportPath}'
7946
9669
 
9670
+ export const __athena_schema_meta = {
9671
+ schemaVersion: ${schemaVersion},
9672
+ generatedAt: ${escapeStringLiteral(generatedAt)},
9673
+ database: ${escapeStringLiteral(databaseName)},
9674
+ outputFormat: ${escapeStringLiteral(outputFormat)},
9675
+ } as const
9676
+
7947
9677
  export const ${registryConstName} = defineRegistry({
7948
9678
  ${renderObjectKey(databaseName)}: ${databaseConstName}
7949
9679
  })
@@ -8022,123 +9752,332 @@ function scopeDuplicateDescriptorPathsBySchema(descriptors) {
8022
9752
  }
8023
9753
  return nextDescriptors;
8024
9754
  }
8025
- var ArtifactComposer = class {
8026
- constructor(snapshot, config) {
8027
- this.snapshot = snapshot;
8028
- this.config = config;
8029
- }
8030
- compose() {
8031
- const providerName = this.snapshot.backend;
8032
- const databaseName = this.snapshot.database;
8033
- const modelDescriptors = [];
8034
- for (const schemaName of Object.keys(this.snapshot.schemas).sort()) {
8035
- const schema = this.snapshot.schemas[schemaName];
8036
- for (const tableName of Object.keys(schema.tables).sort()) {
8037
- const table = schema.tables[tableName];
8038
- const rowTypeName = `${toSafeIdentifier(`${schemaName} ${tableName}`, this.config.naming.modelType, "Model")}Row`;
8039
- const insertTypeName = `${toSafeIdentifier(`${schemaName} ${tableName}`, this.config.naming.modelType, "Model")}Insert`;
8040
- const updateTypeName = `${toSafeIdentifier(`${schemaName} ${tableName}`, this.config.naming.modelType, "Model")}Update`;
8041
- const modelConstName = `${toSafeIdentifier(`${schemaName} ${tableName} model`, this.config.naming.modelConst, "model")}`;
8042
- const modelPath = normalizePath(
8043
- renderOutputPath(this.config.output.targets.model, {
8044
- provider: providerName,
8045
- kind: "model",
8046
- database: databaseName,
8047
- schema: schemaName,
8048
- model: tableName
8049
- }, this.config.output)
8050
- );
8051
- modelDescriptors.push({
9755
+ function composeGeneratorArtifacts(input) {
9756
+ const { snapshot, config, createModelDescriptor, renderModelArtifact: renderModelArtifact3 } = input;
9757
+ const providerName = snapshot.backend;
9758
+ const databaseName = snapshot.database;
9759
+ const modelDescriptors = [];
9760
+ for (const schemaName of Object.keys(snapshot.schemas).sort()) {
9761
+ const schema = snapshot.schemas[schemaName];
9762
+ for (const tableName of Object.keys(schema.tables).sort()) {
9763
+ modelDescriptors.push(
9764
+ createModelDescriptor({
9765
+ providerName,
9766
+ databaseName,
8052
9767
  schemaName,
8053
9768
  tableName,
8054
- filePath: modelPath,
8055
- rowTypeName,
8056
- insertTypeName,
8057
- updateTypeName,
8058
- modelConstName,
8059
- table
8060
- });
8061
- }
8062
- }
8063
- const scopedModelDescriptors = scopeDuplicateDescriptorPathsBySchema(modelDescriptors);
8064
- let schemaDescriptors = Object.keys(this.snapshot.schemas).sort().map((schemaName) => {
8065
- const schemaPath = normalizePath(
8066
- renderOutputPath(this.config.output.targets.schema, {
8067
- provider: providerName,
8068
- kind: "schema",
8069
- database: databaseName,
8070
- schema: schemaName,
8071
- model: "index"
8072
- }, this.config.output)
9769
+ table: schema.tables[tableName]
9770
+ })
8073
9771
  );
8074
- return {
8075
- schemaName,
8076
- filePath: schemaPath,
8077
- schemaConstName: toSafeIdentifier(
8078
- `${schemaName} schema`,
8079
- this.config.naming.schemaConst,
8080
- "schema"
8081
- ),
8082
- models: scopedModelDescriptors.filter((model) => model.schemaName === schemaName)
8083
- };
8084
- });
8085
- schemaDescriptors = scopeDuplicateDescriptorPathsBySchema(schemaDescriptors);
8086
- const databasePath = normalizePath(
8087
- renderOutputPath(this.config.output.targets.database, {
9772
+ }
9773
+ }
9774
+ const scopedModelDescriptors = scopeDuplicateDescriptorPathsBySchema(modelDescriptors);
9775
+ let schemaDescriptors = Object.keys(snapshot.schemas).sort().map((schemaName) => ({
9776
+ schemaName,
9777
+ filePath: resolveOutputPath(
9778
+ config.output.targets.schema,
9779
+ {
9780
+ provider: providerName,
9781
+ kind: "schema",
9782
+ database: databaseName,
9783
+ schema: schemaName,
9784
+ model: "index"
9785
+ },
9786
+ config
9787
+ ),
9788
+ schemaConstName: toSafeIdentifier(
9789
+ `${schemaName} schema`,
9790
+ config.naming.schemaConst,
9791
+ "schema"
9792
+ ),
9793
+ models: scopedModelDescriptors.filter((model) => model.schemaName === schemaName)
9794
+ }));
9795
+ schemaDescriptors = scopeDuplicateDescriptorPathsBySchema(schemaDescriptors);
9796
+ const databaseDescriptor = {
9797
+ filePath: resolveOutputPath(
9798
+ config.output.targets.database,
9799
+ {
8088
9800
  provider: providerName,
8089
9801
  kind: "database",
8090
9802
  database: databaseName,
8091
9803
  schema: "index",
8092
9804
  model: "index"
8093
- }, this.config.output)
9805
+ },
9806
+ config
9807
+ ),
9808
+ databaseConstName: toSafeIdentifier(
9809
+ `${databaseName} database`,
9810
+ config.naming.databaseConst,
9811
+ "database"
9812
+ ),
9813
+ schemas: schemaDescriptors
9814
+ };
9815
+ const files = [];
9816
+ for (const modelDescriptor of scopedModelDescriptors) {
9817
+ files.push(renderModelArtifact3(modelDescriptor));
9818
+ }
9819
+ for (const schemaDescriptor of schemaDescriptors) {
9820
+ files.push(renderSchemaArtifact(schemaDescriptor));
9821
+ }
9822
+ files.push(renderDatabaseArtifact(databaseDescriptor));
9823
+ if (config.features.emitRegistry) {
9824
+ const registryPath = resolveOutputPath(
9825
+ config.output.targets.registry,
9826
+ {
9827
+ provider: providerName,
9828
+ kind: "registry",
9829
+ database: databaseName,
9830
+ schema: "index",
9831
+ model: "index"
9832
+ },
9833
+ config
9834
+ );
9835
+ files.push(
9836
+ renderRegistryArtifact(
9837
+ registryPath,
9838
+ databaseDescriptor.filePath,
9839
+ databaseDescriptor.databaseConstName,
9840
+ toSafeIdentifier("registry", config.naming.registryConst, "registry"),
9841
+ databaseName,
9842
+ snapshot.generatedAt,
9843
+ config.output.format,
9844
+ config.internal.schemaVersion
9845
+ )
8094
9846
  );
8095
- const databaseDescriptor = {
8096
- filePath: databasePath,
8097
- databaseConstName: toSafeIdentifier(
8098
- `${databaseName} database`,
8099
- this.config.naming.databaseConst,
8100
- "database"
8101
- ),
8102
- schemas: schemaDescriptors
8103
- };
8104
- const files = [];
8105
- for (const modelDescriptor of scopedModelDescriptors) {
8106
- files.push(renderModelArtifact(this.snapshot, modelDescriptor, this.config));
8107
- }
8108
- for (const schemaDescriptor of schemaDescriptors) {
8109
- files.push(renderSchemaArtifact(schemaDescriptor));
8110
- }
8111
- files.push(renderDatabaseArtifact(databaseDescriptor));
8112
- if (this.config.features.emitRegistry) {
8113
- const registryPath = normalizePath(
8114
- renderOutputPath(this.config.output.targets.registry, {
8115
- provider: providerName,
8116
- kind: "registry",
8117
- database: databaseName,
8118
- schema: "index",
8119
- model: "index"
8120
- }, this.config.output)
8121
- );
8122
- files.push(
8123
- renderRegistryArtifact(
8124
- registryPath,
8125
- databaseDescriptor.filePath,
8126
- databaseDescriptor.databaseConstName,
8127
- toSafeIdentifier("registry", this.config.naming.registryConst, "registry"),
8128
- databaseName
8129
- )
8130
- );
8131
- }
8132
- assertNoDuplicatePaths(files);
8133
- return {
8134
- snapshot: this.snapshot,
8135
- files
8136
- };
8137
9847
  }
8138
- };
9848
+ assertNoDuplicatePaths(files);
9849
+ return {
9850
+ snapshot,
9851
+ files
9852
+ };
9853
+ }
9854
+
9855
+ // src/generator/table-builder-renderer.ts
9856
+ var SAFE_NUMBER_TYPES = /* @__PURE__ */ new Set([
9857
+ "int2",
9858
+ "int4",
9859
+ "float4",
9860
+ "float8",
9861
+ "smallint",
9862
+ "integer",
9863
+ "real",
9864
+ "double precision"
9865
+ ]);
9866
+ var JSON_TYPES = /* @__PURE__ */ new Set(["json", "jsonb"]);
9867
+ var BOOLEAN_TYPES = /* @__PURE__ */ new Set(["bool", "boolean"]);
9868
+ var STRING_TYPES = /* @__PURE__ */ new Set([
9869
+ "int8",
9870
+ "bigint",
9871
+ "serial8",
9872
+ "bigserial",
9873
+ "numeric",
9874
+ "decimal",
9875
+ "money",
9876
+ "bytea"
9877
+ ]);
9878
+ function normalizeTypeLabel2(column) {
9879
+ const preferred = (column.udtName || column.dataType).toLowerCase().trim();
9880
+ if (column.arrayDimensions > 0 && preferred.startsWith("_")) {
9881
+ return preferred.slice(1);
9882
+ }
9883
+ return preferred;
9884
+ }
9885
+ function renderColumnBuilder(column) {
9886
+ const label = normalizeTypeLabel2(column);
9887
+ let helper;
9888
+ let expression;
9889
+ if (column.typeKind === "enum" && column.enumValues && column.enumValues.length > 0) {
9890
+ helper = "enumeration";
9891
+ expression = `enumeration([${column.enumValues.map((value) => escapeStringLiteral(value)).join(", ")}] as const)`;
9892
+ } else if (column.arrayDimensions > 0 || JSON_TYPES.has(label) || column.typeKind === "composite") {
9893
+ helper = "json";
9894
+ expression = `json<${resolvePostgresColumnType(column)}>()`;
9895
+ } else if (BOOLEAN_TYPES.has(label)) {
9896
+ helper = "boolean";
9897
+ expression = "boolean()";
9898
+ } else if (SAFE_NUMBER_TYPES.has(label)) {
9899
+ helper = "number";
9900
+ expression = "number()";
9901
+ } else if (STRING_TYPES.has(label)) {
9902
+ helper = "string";
9903
+ expression = "string()";
9904
+ } else {
9905
+ helper = "string";
9906
+ expression = "string()";
9907
+ }
9908
+ if (column.isNullable) {
9909
+ expression = `${expression}.optional()`;
9910
+ }
9911
+ if (column.hasDefault) {
9912
+ expression = `${expression}.defaulted()`;
9913
+ }
9914
+ if (column.isGenerated) {
9915
+ expression = `${expression}.generated()`;
9916
+ }
9917
+ return { helper, expression };
9918
+ }
9919
+ function renderModelArtifact(descriptor, config) {
9920
+ const helperImports = /* @__PURE__ */ new Set(["table"]);
9921
+ const columnLines = Object.entries(descriptor.table.columns).map(([columnName, column]) => {
9922
+ const propertyName = escapeTypePropertyName(columnName);
9923
+ const rendered = renderColumnBuilder(column);
9924
+ helperImports.add(rendered.helper);
9925
+ return ` ${propertyName}: ${rendered.expression}`;
9926
+ }).join(",\n");
9927
+ const helperImportLine = Array.from(helperImports).sort().join(", ");
9928
+ const rowSchemaConstName = `${descriptor.tableConstName}_row_schema`;
9929
+ const insertSchemaConstName = `${descriptor.tableConstName}_insert_schema`;
9930
+ const updateSchemaConstName = `${descriptor.tableConstName}_update_schema`;
9931
+ const formSchemaConstName = `${descriptor.tableConstName}_form_schema`;
9932
+ const relationEntries = Object.entries(descriptor.table.relations);
9933
+ const relationsAssignment = config.features.emitRelations && relationEntries.length > 0 ? `
9934
+ Object.assign(${descriptor.tableConstName}.meta, {
9935
+ relations: {
9936
+ ${relationEntries.map(([relationKey2, relationValue]) => ` ${renderObjectKey(relationKey2)}: ${renderRelationLiteral(relationValue)}`).join(",\n")}
9937
+ }
9938
+ })
9939
+ ` : "";
9940
+ const content = `import { ${helperImportLine} } from '@xylex-group/athena'
9941
+ import type { FormValuesOf, InsertOf, RowOf, UpdateOf } from '@xylex-group/athena'
9942
+
9943
+ export const ${descriptor.tableConstName} = table(${escapeStringLiteral(descriptor.tableName)})
9944
+ .schema(${escapeStringLiteral(descriptor.schemaName)})
9945
+ .columns({
9946
+ ${columnLines}
9947
+ })
9948
+ .primaryKey(${descriptor.table.primaryKey.map((value) => escapeStringLiteral(value)).join(", ")})
9949
+ ${relationsAssignment ? `${relationsAssignment}` : ""}
9950
+ export type ${descriptor.rowTypeName} = RowOf<typeof ${descriptor.tableConstName}>
9951
+ export type ${descriptor.insertTypeName} = InsertOf<typeof ${descriptor.tableConstName}>
9952
+ export type ${descriptor.updateTypeName} = UpdateOf<typeof ${descriptor.tableConstName}>
9953
+ export type ${descriptor.formValuesTypeName} = FormValuesOf<typeof ${descriptor.tableConstName}>
9954
+
9955
+ export const ${rowSchemaConstName} = ${descriptor.tableConstName}.schemas.row
9956
+ export const ${insertSchemaConstName} = ${descriptor.tableConstName}.schemas.insert
9957
+ export const ${updateSchemaConstName} = ${descriptor.tableConstName}.schemas.update
9958
+ export const ${formSchemaConstName} = ${descriptor.tableConstName}.schemas.form
9959
+ `;
9960
+ return {
9961
+ kind: "model",
9962
+ path: descriptor.filePath,
9963
+ content
9964
+ };
9965
+ }
9966
+ function generateTableBuilderArtifactsFromSnapshot(snapshot, config) {
9967
+ const normalizedConfig = "internal" in config ? config : normalizeGeneratorConfig(config);
9968
+ return composeGeneratorArtifacts({
9969
+ snapshot,
9970
+ config: normalizedConfig,
9971
+ createModelDescriptor({ providerName, databaseName, schemaName, tableName, table: table2 }) {
9972
+ const tableConstName = toSafeIdentifier(tableName, "preserve", "table");
9973
+ return {
9974
+ schemaName,
9975
+ tableName,
9976
+ filePath: resolveOutputPath(
9977
+ normalizedConfig.output.targets.model,
9978
+ {
9979
+ provider: providerName,
9980
+ kind: "model",
9981
+ database: databaseName,
9982
+ schema: schemaName,
9983
+ model: tableName
9984
+ },
9985
+ normalizedConfig
9986
+ ),
9987
+ rowTypeName: `${toSafeIdentifier(`${schemaName} ${tableName}`, normalizedConfig.naming.modelType, "Model")}Row`,
9988
+ insertTypeName: `${toSafeIdentifier(`${schemaName} ${tableName}`, normalizedConfig.naming.modelType, "Model")}Insert`,
9989
+ updateTypeName: `${toSafeIdentifier(`${schemaName} ${tableName}`, normalizedConfig.naming.modelType, "Model")}Update`,
9990
+ formValuesTypeName: `${toSafeIdentifier(`${schemaName} ${tableName}`, normalizedConfig.naming.modelType, "Model")}FormValues`,
9991
+ tableConstName,
9992
+ exportConstName: tableConstName,
9993
+ table: table2
9994
+ };
9995
+ },
9996
+ renderModelArtifact: (descriptor) => renderModelArtifact(descriptor, normalizedConfig)
9997
+ });
9998
+ }
9999
+
10000
+ // src/generator/renderer.ts
10001
+ function renderModelArtifact2(databaseName, descriptor, config) {
10002
+ const columnLines = Object.values(descriptor.table.columns).map((column) => {
10003
+ const propertyName = escapeTypePropertyName(column.name);
10004
+ const baseType = resolvePostgresColumnType(column);
10005
+ const isOptional = column.isNullable;
10006
+ const typeWithNullability = column.isNullable ? `${baseType} | null` : baseType;
10007
+ return ` ${propertyName}${isOptional ? "?" : ""}: ${typeWithNullability}`;
10008
+ }).join("\n");
10009
+ const nullableLines = Object.values(descriptor.table.columns).map((column) => ` ${renderObjectKey(column.name)}: ${column.isNullable ? "true" : "false"}`).join(",\n");
10010
+ const relationEntries = Object.entries(descriptor.table.relations);
10011
+ const relationBlock = config.features.emitRelations && relationEntries.length > 0 ? `,
10012
+ relations: {
10013
+ ${relationEntries.map(([relationKey2, relationValue]) => ` ${renderObjectKey(relationKey2)}: ${renderRelationLiteral(relationValue)}`).join(",\n")}
10014
+ }` : "";
10015
+ const content = `import { defineModel } from '@xylex-group/athena'
10016
+
10017
+ export interface ${descriptor.rowTypeName} {
10018
+ ${columnLines}
10019
+ }
10020
+
10021
+ export type ${descriptor.insertTypeName} = Partial<${descriptor.rowTypeName}>
10022
+ export type ${descriptor.updateTypeName} = Partial<${descriptor.insertTypeName}>
10023
+
10024
+ export const ${descriptor.modelConstName} = defineModel<${descriptor.rowTypeName}, ${descriptor.insertTypeName}, ${descriptor.updateTypeName}>({
10025
+ meta: {
10026
+ database: ${escapeStringLiteral(databaseName)},
10027
+ schema: ${escapeStringLiteral(descriptor.schemaName)},
10028
+ model: ${escapeStringLiteral(descriptor.tableName)},
10029
+ tableName: ${escapeStringLiteral(`${descriptor.schemaName}.${descriptor.tableName}`)},
10030
+ primaryKey: [${descriptor.table.primaryKey.map((value) => escapeStringLiteral(value)).join(", ")}],
10031
+ nullable: {
10032
+ ${nullableLines}
10033
+ }${relationBlock}
10034
+ }
10035
+ })
10036
+ `;
10037
+ return {
10038
+ kind: "model",
10039
+ path: descriptor.filePath,
10040
+ content
10041
+ };
10042
+ }
8139
10043
  function generateArtifactsFromSnapshot(snapshot, config) {
8140
- const normalizedConfig = "naming" in config && "features" in config && "experimental" in config ? config : normalizeGeneratorConfig(config);
8141
- return new ArtifactComposer(snapshot, normalizedConfig).compose();
10044
+ const normalizedConfig = "internal" in config ? config : normalizeGeneratorConfig(config);
10045
+ if (normalizedConfig.output.format === "table-builder") {
10046
+ return generateTableBuilderArtifactsFromSnapshot(snapshot, normalizedConfig);
10047
+ }
10048
+ return composeGeneratorArtifacts({
10049
+ snapshot,
10050
+ config: normalizedConfig,
10051
+ createModelDescriptor({ providerName, databaseName, schemaName, tableName, table: table2 }) {
10052
+ const modelConstName = toSafeIdentifier(
10053
+ `${schemaName} ${tableName} model`,
10054
+ normalizedConfig.naming.modelConst,
10055
+ "model"
10056
+ );
10057
+ return {
10058
+ schemaName,
10059
+ tableName,
10060
+ filePath: resolveOutputPath(
10061
+ normalizedConfig.output.targets.model,
10062
+ {
10063
+ provider: providerName,
10064
+ kind: "model",
10065
+ database: databaseName,
10066
+ schema: schemaName,
10067
+ model: tableName
10068
+ },
10069
+ normalizedConfig
10070
+ ),
10071
+ rowTypeName: `${toSafeIdentifier(`${schemaName} ${tableName}`, normalizedConfig.naming.modelType, "Model")}Row`,
10072
+ insertTypeName: `${toSafeIdentifier(`${schemaName} ${tableName}`, normalizedConfig.naming.modelType, "Model")}Insert`,
10073
+ updateTypeName: `${toSafeIdentifier(`${schemaName} ${tableName}`, normalizedConfig.naming.modelType, "Model")}Update`,
10074
+ modelConstName,
10075
+ exportConstName: modelConstName,
10076
+ table: table2
10077
+ };
10078
+ },
10079
+ renderModelArtifact: (descriptor) => renderModelArtifact2(snapshot.database, descriptor, normalizedConfig)
10080
+ });
8142
10081
  }
8143
10082
 
8144
10083
  // src/generator/providers.ts
@@ -8353,15 +10292,15 @@ function readCookieFromHeaders(headers, name) {
8353
10292
  }
8354
10293
  return parseCookies(cookieHeader).get(name);
8355
10294
  }
8356
- function isRecord10(value) {
10295
+ function isRecord11(value) {
8357
10296
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
8358
10297
  }
8359
10298
  function resolveSessionCandidate(value) {
8360
- if (!isRecord10(value)) {
10299
+ if (!isRecord11(value)) {
8361
10300
  return null;
8362
10301
  }
8363
- const session = isRecord10(value.session) ? value.session : void 0;
8364
- const user = isRecord10(value.user) ? value.user : void 0;
10302
+ const session = isRecord11(value.session) ? value.session : void 0;
10303
+ const user = isRecord11(value.user) ? value.user : void 0;
8365
10304
  if (session && typeof session.token === "string" && session.token.length > 0 && user) {
8366
10305
  return {
8367
10306
  session,
@@ -8371,7 +10310,7 @@ function resolveSessionCandidate(value) {
8371
10310
  return null;
8372
10311
  }
8373
10312
  function inferSessionPair(returned) {
8374
- return resolveSessionCandidate(returned) ?? (isRecord10(returned) ? resolveSessionCandidate(returned.data) : null) ?? (isRecord10(returned) ? resolveSessionCandidate(returned.session) : null);
10313
+ return resolveSessionCandidate(returned) ?? (isRecord11(returned) ? resolveSessionCandidate(returned.data) : null) ?? (isRecord11(returned) ? resolveSessionCandidate(returned.session) : null);
8375
10314
  }
8376
10315
  function resolveResponseHeaders(ctx) {
8377
10316
  if (ctx.context.responseHeaders instanceof Headers) {
@@ -8715,6 +10654,6 @@ function athenaAuth(config) {
8715
10654
  return auth;
8716
10655
  }
8717
10656
 
8718
- export { ATHENA_AUTH_BASE_ERROR_CODES, AthenaClient, AthenaError, AthenaErrorCategory, AthenaErrorCode, AthenaErrorKind, AthenaGatewayError, AthenaStorageError, AthenaStorageErrorCode, Backend, DEFAULT_POSTGRES_SCHEMAS, assertInt, athenaAuth, coerceInt, createAthenaStorageError, createAuthClient, createAuthReactEmailInput, createClient, createModelFormAdapter, createPostgresIntrospectionProvider, createTypedClient, defineAthenaAuthConfig, defineAuthEmailTemplate, defineDatabase, defineGeneratorConfig, defineModel, defineRegistry, defineSchema, findGeneratorConfigPath, generateArtifactsFromSnapshot, generatorEnv, identifier, isAthenaGatewayError, isOk, loadGeneratorConfig, normalizeAthenaError, normalizeAthenaGatewayBaseUrl, normalizeGeneratorConfig, normalizeSchemaSelection, parseBooleanFlag2 as parseBooleanFlag, renderAthenaReactEmail, requireAffected, requireSuccess, resolveGeneratorProvider, resolvePostgresColumnType, resolveProviderSchemas, runSchemaGenerator, storageSdkManifest, toModelFormDefaults, toModelPayload, unwrap, unwrapOne, unwrapRows, verifyAthenaGatewayUrl, withRetry };
10657
+ export { ATHENA_AUTH_BASE_ERROR_CODES, AthenaClient, AthenaError, AthenaErrorCategory, AthenaErrorCode, AthenaErrorKind, AthenaGatewayError, AthenaStorageError, AthenaStorageErrorCode, Backend, DEFAULT_POSTGRES_SCHEMAS, assertInt, athenaAuth, boolean, coerceInt, createAthenaStorageError, createAuthClient, createAuthReactEmailInput, createClient, createModelFormAdapter, createPostgresIntrospectionProvider, createTypedClient, defineAthenaAuthConfig, defineAuthEmailTemplate, defineDatabase, defineGeneratorConfig, defineModel, defineRegistry, defineSchema, enumeration, findGeneratorConfigPath, generateArtifactsFromSnapshot, generatorEnv, getAthenaDebugAst, identifier, isAthenaGatewayError, isOk, json, loadGeneratorConfig, normalizeAthenaError, normalizeAthenaGatewayBaseUrl, normalizeGeneratorConfig, normalizeSchemaSelection, number, parseBooleanFlag2 as parseBooleanFlag, renderAthenaReactEmail, requireAffected, requireSuccess, resolveGeneratorProvider, resolvePostgresColumnType, resolveProviderSchemas, runSchemaGenerator, storageSdkManifest, string, table, toModelFormDefaults, toModelPayload, unwrap, unwrapOne, unwrapRows, verifyAthenaGatewayUrl, withRetry };
8719
10658
  //# sourceMappingURL=index.js.map
8720
10659
  //# sourceMappingURL=index.js.map