@xylex-group/athena 3.1.0 → 3.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -1
- package/dist/admin.cjs +55 -1
- package/dist/admin.cjs.map +1 -1
- package/dist/admin.d.cts +32 -8
- package/dist/admin.d.ts +32 -8
- package/dist/admin.js +54 -2
- package/dist/admin.js.map +1 -1
- package/dist/athena-auth-url-C1FbVmN6.d.cts +200 -0
- package/dist/athena-auth-url-C1FbVmN6.d.ts +200 -0
- package/dist/{athena-request-headers-C7Jy-c_D.d.ts → athena-request-headers-BnFN2mbd.d.cts} +49 -201
- package/dist/{athena-request-headers-DujFFyMU.d.cts → athena-request-headers-Dwdkq2WR.d.ts} +49 -201
- package/dist/billing.cjs +1 -1
- package/dist/billing.cjs.map +1 -1
- package/dist/billing.js +1 -1
- package/dist/billing.js.map +1 -1
- package/dist/browser.cjs +3735 -248
- package/dist/browser.cjs.map +1 -1
- package/dist/browser.d.cts +11 -10
- package/dist/browser.d.ts +11 -10
- package/dist/browser.js +3726 -249
- package/dist/browser.js.map +1 -1
- package/dist/cli/index.cjs +3232 -190
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.d.cts +4 -4
- package/dist/cli/index.d.ts +4 -4
- package/dist/cli/index.js +3232 -190
- package/dist/cli/index.js.map +1 -1
- package/dist/cloudflare.cjs +12914 -0
- package/dist/cloudflare.cjs.map +1 -0
- package/dist/cloudflare.d.cts +368 -0
- package/dist/cloudflare.d.ts +368 -0
- package/dist/cloudflare.js +12885 -0
- package/dist/cloudflare.js.map +1 -0
- package/dist/cookies.cjs +4 -3
- package/dist/cookies.cjs.map +1 -1
- package/dist/cookies.js +4 -3
- package/dist/cookies.js.map +1 -1
- package/dist/env.cjs +130 -0
- package/dist/env.cjs.map +1 -0
- package/dist/env.d.cts +70 -0
- package/dist/env.d.ts +70 -0
- package/dist/env.js +122 -0
- package/dist/env.js.map +1 -0
- package/dist/index.cjs +3749 -241
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +11 -10
- package/dist/index.d.ts +11 -10
- package/dist/index.js +3739 -242
- package/dist/index.js.map +1 -1
- package/dist/{model-form-BhWWsA-7.d.cts → model-form-D0ykVVOs.d.cts} +26 -4
- package/dist/{model-form-BbdzJ9Uh.d.ts → model-form-U8NVtfSA.d.ts} +26 -4
- package/dist/{module-xFd7_Igv.d.cts → module-CMWlJ1z3.d.cts} +5 -5
- package/dist/{module-DKkJKOuJ.d.ts → module-CZ-wPcf2.d.ts} +5 -5
- package/dist/next/client.cjs +3212 -196
- package/dist/next/client.cjs.map +1 -1
- package/dist/next/client.d.cts +6 -5
- package/dist/next/client.d.ts +6 -5
- package/dist/next/client.js +3212 -196
- package/dist/next/client.js.map +1 -1
- package/dist/next/server.cjs +4461 -781
- package/dist/next/server.cjs.map +1 -1
- package/dist/next/server.d.cts +139 -13
- package/dist/next/server.d.ts +139 -13
- package/dist/next/server.js +4451 -782
- package/dist/next/server.js.map +1 -1
- package/dist/{pipeline-DuKzYGia.d.cts → pipeline-BCpb4BX1.d.cts} +1 -1
- package/dist/{pipeline-wer2G9xW.d.ts → pipeline-CgmXwMeX.d.ts} +1 -1
- package/dist/{proxy-request-headers-m4D2Tduy.d.ts → proxy-request-headers-CttlcuRb.d.ts} +1 -1
- package/dist/{proxy-request-headers-DGxdoyA0.d.cts → proxy-request-headers-pIBSn1Fw.d.cts} +1 -1
- package/dist/react.cjs +290 -31
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +62 -12
- package/dist/react.d.ts +62 -12
- package/dist/react.js +290 -32
- package/dist/react.js.map +1 -1
- package/dist/schema-handlers-CvWqF-dW.d.ts +138 -0
- package/dist/schema-handlers-Dr8h9Jg-.d.cts +138 -0
- package/dist/social-providers.cjs +1 -1
- package/dist/social-providers.cjs.map +1 -1
- package/dist/social-providers.d.cts +1 -1
- package/dist/social-providers.d.ts +1 -1
- package/dist/social-providers.js +1 -1
- package/dist/social-providers.js.map +1 -1
- package/dist/{types-Bltx6iL6.d.ts → types-B2RZPivM.d.cts} +8 -1
- package/dist/{types-Bltx6iL6.d.cts → types-B2RZPivM.d.ts} +8 -1
- package/dist/{types-1ztXDgPa.d.cts → types-BKklrX4J.d.ts} +14 -2
- package/dist/{types-AOY-GLu8.d.cts → types-BVKpQmfY.d.cts} +11 -0
- package/dist/{types-AOY-GLu8.d.ts → types-BVKpQmfY.d.ts} +11 -0
- package/dist/{types-CgCv5o6R.d.cts → types-D5dj1v5Z.d.cts} +1 -1
- package/dist/{types-CccOiXPo.d.ts → types-DqBFwfhn.d.cts} +14 -2
- package/dist/{types-B75PdABb.d.ts → types-S-bTMPiM.d.ts} +1 -1
- package/dist/utils.cjs +30 -0
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.cts +4 -3
- package/dist/utils.d.ts +4 -3
- package/dist/utils.js +30 -1
- package/dist/utils.js.map +1 -1
- package/dist/{v3-client-CWfZHcKL.d.cts → v3-client-DP-qg82X.d.cts} +323 -5
- package/dist/{v3-client-DZp2NEhK.d.ts → v3-client-OAai_JNs.d.ts} +323 -5
- package/package.json +25 -4
package/dist/next/client.js
CHANGED
|
@@ -1617,6 +1617,8 @@ function buildUpdateDebugSql(payload) {
|
|
|
1617
1617
|
sqlParts.push(`WHERE ${whereClauses.join(" AND ")}`);
|
|
1618
1618
|
}
|
|
1619
1619
|
const pagination = resolvePagination({
|
|
1620
|
+
limit: payload.limit,
|
|
1621
|
+
offset: payload.offset,
|
|
1620
1622
|
currentPage: payload.current_page,
|
|
1621
1623
|
pageSize: payload.page_size
|
|
1622
1624
|
});
|
|
@@ -1639,6 +1641,8 @@ function buildDeleteDebugSql(payload) {
|
|
|
1639
1641
|
sqlParts.push(`WHERE ${whereClauses.join(" AND ")}`);
|
|
1640
1642
|
}
|
|
1641
1643
|
const pagination = resolvePagination({
|
|
1644
|
+
limit: payload.limit,
|
|
1645
|
+
offset: payload.offset,
|
|
1642
1646
|
currentPage: payload.current_page,
|
|
1643
1647
|
pageSize: payload.page_size
|
|
1644
1648
|
});
|
|
@@ -1782,7 +1786,7 @@ function buildAthenaGatewayUrl(baseUrl, path) {
|
|
|
1782
1786
|
|
|
1783
1787
|
// package.json
|
|
1784
1788
|
var package_default = {
|
|
1785
|
-
version: "3.1
|
|
1789
|
+
version: "3.5.1"
|
|
1786
1790
|
};
|
|
1787
1791
|
|
|
1788
1792
|
// src/sdk-version.ts
|
|
@@ -3868,6 +3872,14 @@ function createAuthModule(config = {}, runtimeOptions = {}) {
|
|
|
3868
3872
|
changeEmailVerify: (input, options) => getWithQuery("/change-email/verify", input, options),
|
|
3869
3873
|
deleteUserVerify: (input, options) => getWithQuery("/delete-user/verify", input, options),
|
|
3870
3874
|
changePassword: (input, options) => postGeneric("/change-password", input, options),
|
|
3875
|
+
// Better Auth UI flat method aliases (also nested under session/account/social/user).
|
|
3876
|
+
listSessions: (input, options) => getGeneric("/list-sessions", input, options),
|
|
3877
|
+
revokeSession: sessionRevokeBinding,
|
|
3878
|
+
revokeOtherSessions,
|
|
3879
|
+
listAccounts: (input, options) => getGeneric("/list-accounts", input, options),
|
|
3880
|
+
unlinkAccount: (input, options) => postGeneric("/unlink-account", input, options),
|
|
3881
|
+
linkSocial: (input, options) => postGeneric("/link-social", input, options),
|
|
3882
|
+
updateUser: (input, options) => postGeneric("/update-user", input, options),
|
|
3871
3883
|
user: {
|
|
3872
3884
|
update: (input, options) => postGeneric("/update-user", input, options),
|
|
3873
3885
|
delete: (input, options) => postGeneric("/delete-user", input, options),
|
|
@@ -4973,9 +4985,9 @@ function readHeadersField(value) {
|
|
|
4973
4985
|
const headers = value.headers;
|
|
4974
4986
|
if (!isRecord8(headers)) return {};
|
|
4975
4987
|
const result = {};
|
|
4976
|
-
for (const [key,
|
|
4977
|
-
if (typeof
|
|
4978
|
-
result[key] =
|
|
4988
|
+
for (const [key, headerValue3] of Object.entries(headers)) {
|
|
4989
|
+
if (typeof headerValue3 === "string") {
|
|
4990
|
+
result[key] = headerValue3;
|
|
4979
4991
|
}
|
|
4980
4992
|
}
|
|
4981
4993
|
return result;
|
|
@@ -8600,6 +8612,8 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, beha
|
|
|
8600
8612
|
strip_nulls: mergedOptions?.stripNulls ?? true
|
|
8601
8613
|
};
|
|
8602
8614
|
if (executionState.order) payload.sort_by = executionState.order;
|
|
8615
|
+
if (executionState.limit !== void 0) payload.limit = executionState.limit;
|
|
8616
|
+
if (executionState.offset !== void 0) payload.offset = executionState.offset;
|
|
8603
8617
|
if (executionState.currentPage !== void 0) payload.current_page = executionState.currentPage;
|
|
8604
8618
|
if (executionState.pageSize !== void 0) payload.page_size = executionState.pageSize;
|
|
8605
8619
|
if (executionState.totalPages !== void 0) payload.total_pages = executionState.totalPages;
|
|
@@ -8654,6 +8668,8 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, beha
|
|
|
8654
8668
|
conditions: filters
|
|
8655
8669
|
};
|
|
8656
8670
|
if (executionState.order) payload.sort_by = executionState.order;
|
|
8671
|
+
if (executionState.limit !== void 0) payload.limit = executionState.limit;
|
|
8672
|
+
if (executionState.offset !== void 0) payload.offset = executionState.offset;
|
|
8657
8673
|
if (executionState.currentPage !== void 0) payload.current_page = executionState.currentPage;
|
|
8658
8674
|
if (executionState.pageSize !== void 0) payload.page_size = executionState.pageSize;
|
|
8659
8675
|
if (executionState.totalPages !== void 0) payload.total_pages = executionState.totalPages;
|
|
@@ -8705,7 +8721,11 @@ function createQueryBuilder(client, formatGatewayResult, behavior, tracer) {
|
|
|
8705
8721
|
if (!normalizedQuery) {
|
|
8706
8722
|
throw new Error("query requires a non-empty string");
|
|
8707
8723
|
}
|
|
8708
|
-
const
|
|
8724
|
+
const params = options?.params;
|
|
8725
|
+
const payload = {
|
|
8726
|
+
query: normalizedQuery,
|
|
8727
|
+
...Array.isArray(params) ? { params } : {}
|
|
8728
|
+
};
|
|
8709
8729
|
const callsite = captureTraceCallsite(tracer);
|
|
8710
8730
|
return executeRead(
|
|
8711
8731
|
behavior,
|
|
@@ -8754,7 +8774,7 @@ function normalizeAuthClientConfig(auth, defaultBaseUrl) {
|
|
|
8754
8774
|
}
|
|
8755
8775
|
function createInternalClientCore(config) {
|
|
8756
8776
|
const normalizedAuthConfig = normalizeAuthClientConfig(config.auth, config.authUrl);
|
|
8757
|
-
const gatewayTransport = createAthenaGatewayClient({
|
|
8777
|
+
const gatewayTransport = config.gatewayTransport ?? createAthenaGatewayClient({
|
|
8758
8778
|
baseUrl: config.baseUrl,
|
|
8759
8779
|
apiKey: config.apiKey,
|
|
8760
8780
|
client: config.client ?? void 0,
|
|
@@ -8909,178 +8929,2816 @@ function createInternalClientView(core, resolveContext) {
|
|
|
8909
8929
|
};
|
|
8910
8930
|
}
|
|
8911
8931
|
|
|
8912
|
-
// src/
|
|
8913
|
-
var
|
|
8914
|
-
var
|
|
8915
|
-
|
|
8916
|
-
|
|
8917
|
-
|
|
8918
|
-
|
|
8919
|
-
|
|
8920
|
-
|
|
8921
|
-
|
|
8922
|
-
|
|
8923
|
-
|
|
8924
|
-
|
|
8925
|
-
|
|
8926
|
-
|
|
8927
|
-
|
|
8928
|
-
|
|
8929
|
-
|
|
8930
|
-
|
|
8931
|
-
}
|
|
8932
|
-
|
|
8933
|
-
|
|
8934
|
-
|
|
8935
|
-
|
|
8936
|
-
|
|
8937
|
-
|
|
8938
|
-
|
|
8939
|
-
|
|
8940
|
-
|
|
8932
|
+
// src/cloudflare/types.ts
|
|
8933
|
+
var CLOUDFLARE_EDGE_BASE_URL = "https://athena.local/cloudflare-edge";
|
|
8934
|
+
var CLOUDFLARE_EDGE_API_KEY = "cloudflare-edge-local";
|
|
8935
|
+
|
|
8936
|
+
// src/cloudflare/capabilities.ts
|
|
8937
|
+
function createGatewayCapabilities(options) {
|
|
8938
|
+
const storageConfigured = options?.storageConfigured ?? true;
|
|
8939
|
+
return {
|
|
8940
|
+
mode: "gateway",
|
|
8941
|
+
db: {
|
|
8942
|
+
engine: options?.engine ?? "postgresql",
|
|
8943
|
+
local: false,
|
|
8944
|
+
layers: {
|
|
8945
|
+
query: true,
|
|
8946
|
+
flatCrud: true,
|
|
8947
|
+
findManyAst: true,
|
|
8948
|
+
rpc: true,
|
|
8949
|
+
relations: true
|
|
8950
|
+
}
|
|
8951
|
+
},
|
|
8952
|
+
storage: {
|
|
8953
|
+
local: false,
|
|
8954
|
+
objects: storageConfigured,
|
|
8955
|
+
catalogs: storageConfigured ? options?.storageCatalogs ?? true : false,
|
|
8956
|
+
backups: storageConfigured ? options?.storageBackups ?? true : false
|
|
8957
|
+
},
|
|
8958
|
+
auth: {
|
|
8959
|
+
remote: options?.authRemote ?? true
|
|
8960
|
+
}
|
|
8961
|
+
};
|
|
8941
8962
|
}
|
|
8942
|
-
function
|
|
8943
|
-
const
|
|
8944
|
-
|
|
8963
|
+
function createCloudflareEdgeCapabilities(options) {
|
|
8964
|
+
const hasObjects = options.hasR2 || Boolean(options.hasRemoteStorage);
|
|
8965
|
+
return {
|
|
8966
|
+
mode: "cloudflare-edge",
|
|
8967
|
+
db: {
|
|
8968
|
+
engine: "cloudflare-d1",
|
|
8969
|
+
local: true,
|
|
8970
|
+
layers: {
|
|
8971
|
+
query: true,
|
|
8972
|
+
flatCrud: true,
|
|
8973
|
+
findManyAst: options.findManyAst ?? false,
|
|
8974
|
+
rpc: false,
|
|
8975
|
+
relations: false
|
|
8976
|
+
}
|
|
8977
|
+
},
|
|
8978
|
+
storage: {
|
|
8979
|
+
// Local objects only when an R2 binding is present.
|
|
8980
|
+
local: options.hasR2,
|
|
8981
|
+
// Remote hybrid root can still expose storage.objects via the HTTP API.
|
|
8982
|
+
objects: hasObjects,
|
|
8983
|
+
catalogs: false,
|
|
8984
|
+
backups: false
|
|
8985
|
+
},
|
|
8986
|
+
auth: {
|
|
8987
|
+
remote: options.authRemote
|
|
8988
|
+
}
|
|
8945
8989
|
};
|
|
8946
|
-
if (input.clientName) query.clientName = input.clientName;
|
|
8947
|
-
if ("cursor" in input && input.cursor) query.cursor = input.cursor;
|
|
8948
|
-
if ("source" in input && input.source) query.source = input.source;
|
|
8949
|
-
if ("limit" in input && input.limit !== void 0) query.limit = String(input.limit);
|
|
8950
|
-
if ("offset" in input && input.offset !== void 0) query.offset = String(input.offset);
|
|
8951
|
-
return query;
|
|
8952
8990
|
}
|
|
8953
|
-
|
|
8954
|
-
|
|
8955
|
-
|
|
8991
|
+
|
|
8992
|
+
// src/cloudflare/d1/runner.ts
|
|
8993
|
+
function resultColumns(rows) {
|
|
8994
|
+
const first = rows.find((value) => value && typeof value === "object" && !Array.isArray(value));
|
|
8995
|
+
if (!first) return [];
|
|
8996
|
+
return Object.keys(first);
|
|
8997
|
+
}
|
|
8998
|
+
function isIdentChar(ch) {
|
|
8999
|
+
if (!ch) return false;
|
|
9000
|
+
return /[A-Za-z0-9_]/.test(ch);
|
|
9001
|
+
}
|
|
9002
|
+
function scanSqlKeywordsOutsideLiterals(sql, onKeyword) {
|
|
9003
|
+
let inSingle = false;
|
|
9004
|
+
let inDouble = false;
|
|
9005
|
+
let inBacktick = false;
|
|
9006
|
+
let inBracket = false;
|
|
9007
|
+
let inLineComment = false;
|
|
9008
|
+
let inBlockComment = false;
|
|
9009
|
+
for (let i = 0; i < sql.length; i += 1) {
|
|
9010
|
+
const ch = sql[i];
|
|
9011
|
+
const next = sql[i + 1];
|
|
9012
|
+
if (inLineComment) {
|
|
9013
|
+
if (ch === "\n" || ch === "\r") inLineComment = false;
|
|
9014
|
+
continue;
|
|
9015
|
+
}
|
|
9016
|
+
if (inBlockComment) {
|
|
9017
|
+
if (ch === "*" && next === "/") {
|
|
9018
|
+
i += 1;
|
|
9019
|
+
inBlockComment = false;
|
|
9020
|
+
}
|
|
9021
|
+
continue;
|
|
9022
|
+
}
|
|
9023
|
+
if (inSingle) {
|
|
9024
|
+
if (ch === "'" && next === "'") {
|
|
9025
|
+
i += 1;
|
|
9026
|
+
continue;
|
|
9027
|
+
}
|
|
9028
|
+
if (ch === "'") inSingle = false;
|
|
9029
|
+
continue;
|
|
9030
|
+
}
|
|
9031
|
+
if (inDouble) {
|
|
9032
|
+
if (ch === '"' && next === '"') {
|
|
9033
|
+
i += 1;
|
|
9034
|
+
continue;
|
|
9035
|
+
}
|
|
9036
|
+
if (ch === '"') inDouble = false;
|
|
9037
|
+
continue;
|
|
9038
|
+
}
|
|
9039
|
+
if (inBacktick) {
|
|
9040
|
+
if (ch === "`" && next === "`") {
|
|
9041
|
+
i += 1;
|
|
9042
|
+
continue;
|
|
9043
|
+
}
|
|
9044
|
+
if (ch === "`") inBacktick = false;
|
|
9045
|
+
continue;
|
|
9046
|
+
}
|
|
9047
|
+
if (inBracket) {
|
|
9048
|
+
if (ch === "]") inBracket = false;
|
|
9049
|
+
continue;
|
|
9050
|
+
}
|
|
9051
|
+
if (ch === "-" && next === "-") {
|
|
9052
|
+
inLineComment = true;
|
|
9053
|
+
i += 1;
|
|
9054
|
+
continue;
|
|
9055
|
+
}
|
|
9056
|
+
if (ch === "/" && next === "*") {
|
|
9057
|
+
inBlockComment = true;
|
|
9058
|
+
i += 1;
|
|
9059
|
+
continue;
|
|
9060
|
+
}
|
|
9061
|
+
if (ch === "'") {
|
|
9062
|
+
inSingle = true;
|
|
9063
|
+
continue;
|
|
9064
|
+
}
|
|
9065
|
+
if (ch === '"') {
|
|
9066
|
+
inDouble = true;
|
|
9067
|
+
continue;
|
|
9068
|
+
}
|
|
9069
|
+
if (ch === "`") {
|
|
9070
|
+
inBacktick = true;
|
|
9071
|
+
continue;
|
|
9072
|
+
}
|
|
9073
|
+
if (ch === "[") {
|
|
9074
|
+
inBracket = true;
|
|
9075
|
+
continue;
|
|
9076
|
+
}
|
|
9077
|
+
if (!isIdentChar(ch) || isIdentChar(sql[i - 1])) {
|
|
9078
|
+
continue;
|
|
9079
|
+
}
|
|
9080
|
+
let end = i + 1;
|
|
9081
|
+
while (end < sql.length && isIdentChar(sql[end])) {
|
|
9082
|
+
end += 1;
|
|
9083
|
+
}
|
|
9084
|
+
const keyword = sql.slice(i, end);
|
|
9085
|
+
if (onKeyword(keyword, i)) {
|
|
9086
|
+
return;
|
|
9087
|
+
}
|
|
9088
|
+
i = end - 1;
|
|
8956
9089
|
}
|
|
8957
|
-
return body;
|
|
8958
9090
|
}
|
|
8959
|
-
function
|
|
8960
|
-
const
|
|
8961
|
-
|
|
9091
|
+
function sqlContainsKeywordOutsideLiterals(sql, keyword) {
|
|
9092
|
+
const target = keyword.toUpperCase();
|
|
9093
|
+
let found = false;
|
|
9094
|
+
scanSqlKeywordsOutsideLiterals(sql, (token) => {
|
|
9095
|
+
if (token.toUpperCase() === target) {
|
|
9096
|
+
found = true;
|
|
9097
|
+
return true;
|
|
9098
|
+
}
|
|
9099
|
+
return false;
|
|
8962
9100
|
});
|
|
8963
|
-
|
|
8964
|
-
|
|
8965
|
-
|
|
8966
|
-
|
|
8967
|
-
|
|
8968
|
-
|
|
8969
|
-
|
|
8970
|
-
|
|
8971
|
-
|
|
8972
|
-
|
|
8973
|
-
|
|
8974
|
-
|
|
8975
|
-
|
|
8976
|
-
|
|
8977
|
-
|
|
8978
|
-
|
|
8979
|
-
|
|
8980
|
-
|
|
8981
|
-
|
|
8982
|
-
|
|
8983
|
-
|
|
8984
|
-
|
|
9101
|
+
return found;
|
|
9102
|
+
}
|
|
9103
|
+
function sqlFirstKeywordOutsideLiterals(sql) {
|
|
9104
|
+
let first = null;
|
|
9105
|
+
scanSqlKeywordsOutsideLiterals(sql, (token) => {
|
|
9106
|
+
first = token;
|
|
9107
|
+
return true;
|
|
9108
|
+
});
|
|
9109
|
+
return first;
|
|
9110
|
+
}
|
|
9111
|
+
var ROW_PRODUCING_LEAD_KEYWORDS = /* @__PURE__ */ new Set(["SELECT", "PRAGMA", "EXPLAIN", "VALUES"]);
|
|
9112
|
+
var MUTATION_LEAD_KEYWORDS = /* @__PURE__ */ new Set(["INSERT", "UPDATE", "DELETE", "REPLACE"]);
|
|
9113
|
+
var WITH_TERMINAL_KEYWORDS = /* @__PURE__ */ new Set([
|
|
9114
|
+
"SELECT",
|
|
9115
|
+
"INSERT",
|
|
9116
|
+
"UPDATE",
|
|
9117
|
+
"DELETE",
|
|
9118
|
+
"REPLACE",
|
|
9119
|
+
"VALUES",
|
|
9120
|
+
"PRAGMA",
|
|
9121
|
+
"EXPLAIN"
|
|
9122
|
+
]);
|
|
9123
|
+
function sqlTerminalKeywordAfterWith(sql) {
|
|
9124
|
+
let inSingle = false;
|
|
9125
|
+
let inDouble = false;
|
|
9126
|
+
let inBacktick = false;
|
|
9127
|
+
let inBracket = false;
|
|
9128
|
+
let inLineComment = false;
|
|
9129
|
+
let inBlockComment = false;
|
|
9130
|
+
let depth = 0;
|
|
9131
|
+
let sawWith = false;
|
|
9132
|
+
for (let i = 0; i < sql.length; i += 1) {
|
|
9133
|
+
const ch = sql[i];
|
|
9134
|
+
const next = sql[i + 1];
|
|
9135
|
+
if (inLineComment) {
|
|
9136
|
+
if (ch === "\n" || ch === "\r") inLineComment = false;
|
|
9137
|
+
continue;
|
|
9138
|
+
}
|
|
9139
|
+
if (inBlockComment) {
|
|
9140
|
+
if (ch === "*" && next === "/") {
|
|
9141
|
+
i += 1;
|
|
9142
|
+
inBlockComment = false;
|
|
8985
9143
|
}
|
|
9144
|
+
continue;
|
|
8986
9145
|
}
|
|
8987
|
-
|
|
8988
|
-
|
|
8989
|
-
|
|
8990
|
-
|
|
8991
|
-
body: requestBody,
|
|
8992
|
-
signal: options?.signal
|
|
8993
|
-
});
|
|
8994
|
-
if (responseType === "text") {
|
|
8995
|
-
const text = await response.text();
|
|
8996
|
-
if (!response.ok) {
|
|
8997
|
-
throw new AthenaBillingError({
|
|
8998
|
-
message: `Billing request failed (${response.status})`,
|
|
8999
|
-
status: response.status,
|
|
9000
|
-
endpoint: path,
|
|
9001
|
-
method,
|
|
9002
|
-
body: text
|
|
9003
|
-
});
|
|
9146
|
+
if (inSingle) {
|
|
9147
|
+
if (ch === "'" && next === "'") {
|
|
9148
|
+
i += 1;
|
|
9149
|
+
continue;
|
|
9004
9150
|
}
|
|
9005
|
-
|
|
9151
|
+
if (ch === "'") inSingle = false;
|
|
9152
|
+
continue;
|
|
9006
9153
|
}
|
|
9007
|
-
|
|
9008
|
-
|
|
9009
|
-
|
|
9010
|
-
|
|
9011
|
-
parsed = JSON.parse(rawText);
|
|
9012
|
-
} catch {
|
|
9013
|
-
parsed = rawText;
|
|
9154
|
+
if (inDouble) {
|
|
9155
|
+
if (ch === '"' && next === '"') {
|
|
9156
|
+
i += 1;
|
|
9157
|
+
continue;
|
|
9014
9158
|
}
|
|
9015
|
-
|
|
9016
|
-
|
|
9159
|
+
if (ch === '"') inDouble = false;
|
|
9160
|
+
continue;
|
|
9017
9161
|
}
|
|
9018
|
-
if (
|
|
9019
|
-
|
|
9020
|
-
|
|
9021
|
-
|
|
9022
|
-
|
|
9023
|
-
|
|
9024
|
-
|
|
9025
|
-
body: parsed
|
|
9026
|
-
});
|
|
9162
|
+
if (inBacktick) {
|
|
9163
|
+
if (ch === "`" && next === "`") {
|
|
9164
|
+
i += 1;
|
|
9165
|
+
continue;
|
|
9166
|
+
}
|
|
9167
|
+
if (ch === "`") inBacktick = false;
|
|
9168
|
+
continue;
|
|
9027
9169
|
}
|
|
9028
|
-
|
|
9170
|
+
if (inBracket) {
|
|
9171
|
+
if (ch === "]") inBracket = false;
|
|
9172
|
+
continue;
|
|
9173
|
+
}
|
|
9174
|
+
if (ch === "-" && next === "-") {
|
|
9175
|
+
inLineComment = true;
|
|
9176
|
+
i += 1;
|
|
9177
|
+
continue;
|
|
9178
|
+
}
|
|
9179
|
+
if (ch === "/" && next === "*") {
|
|
9180
|
+
inBlockComment = true;
|
|
9181
|
+
i += 1;
|
|
9182
|
+
continue;
|
|
9183
|
+
}
|
|
9184
|
+
if (ch === "'") {
|
|
9185
|
+
inSingle = true;
|
|
9186
|
+
continue;
|
|
9187
|
+
}
|
|
9188
|
+
if (ch === '"') {
|
|
9189
|
+
inDouble = true;
|
|
9190
|
+
continue;
|
|
9191
|
+
}
|
|
9192
|
+
if (ch === "`") {
|
|
9193
|
+
inBacktick = true;
|
|
9194
|
+
continue;
|
|
9195
|
+
}
|
|
9196
|
+
if (ch === "[") {
|
|
9197
|
+
inBracket = true;
|
|
9198
|
+
continue;
|
|
9199
|
+
}
|
|
9200
|
+
if (ch === "(") {
|
|
9201
|
+
depth += 1;
|
|
9202
|
+
continue;
|
|
9203
|
+
}
|
|
9204
|
+
if (ch === ")") {
|
|
9205
|
+
if (depth > 0) depth -= 1;
|
|
9206
|
+
continue;
|
|
9207
|
+
}
|
|
9208
|
+
if (depth !== 0 || !isIdentChar(ch) || isIdentChar(sql[i - 1])) {
|
|
9209
|
+
continue;
|
|
9210
|
+
}
|
|
9211
|
+
let end = i + 1;
|
|
9212
|
+
while (end < sql.length && isIdentChar(sql[end])) {
|
|
9213
|
+
end += 1;
|
|
9214
|
+
}
|
|
9215
|
+
const keyword = sql.slice(i, end);
|
|
9216
|
+
const upper = keyword.toUpperCase();
|
|
9217
|
+
if (!sawWith) {
|
|
9218
|
+
if (upper === "WITH") {
|
|
9219
|
+
sawWith = true;
|
|
9220
|
+
}
|
|
9221
|
+
i = end - 1;
|
|
9222
|
+
continue;
|
|
9223
|
+
}
|
|
9224
|
+
if (WITH_TERMINAL_KEYWORDS.has(upper)) {
|
|
9225
|
+
return keyword;
|
|
9226
|
+
}
|
|
9227
|
+
i = end - 1;
|
|
9029
9228
|
}
|
|
9030
|
-
return
|
|
9031
|
-
|
|
9032
|
-
|
|
9033
|
-
|
|
9034
|
-
|
|
9035
|
-
|
|
9036
|
-
|
|
9037
|
-
|
|
9038
|
-
|
|
9039
|
-
|
|
9040
|
-
|
|
9041
|
-
|
|
9042
|
-
|
|
9043
|
-
return
|
|
9044
|
-
|
|
9045
|
-
|
|
9046
|
-
|
|
9047
|
-
|
|
9048
|
-
|
|
9049
|
-
|
|
9050
|
-
|
|
9051
|
-
|
|
9052
|
-
|
|
9053
|
-
|
|
9054
|
-
|
|
9055
|
-
|
|
9056
|
-
|
|
9057
|
-
|
|
9058
|
-
|
|
9059
|
-
|
|
9060
|
-
|
|
9061
|
-
|
|
9062
|
-
|
|
9063
|
-
|
|
9064
|
-
|
|
9065
|
-
|
|
9066
|
-
|
|
9067
|
-
|
|
9068
|
-
}
|
|
9069
|
-
|
|
9070
|
-
|
|
9071
|
-
|
|
9072
|
-
|
|
9073
|
-
|
|
9074
|
-
|
|
9075
|
-
|
|
9076
|
-
|
|
9077
|
-
|
|
9078
|
-
|
|
9079
|
-
|
|
9080
|
-
|
|
9081
|
-
|
|
9082
|
-
|
|
9083
|
-
|
|
9229
|
+
return null;
|
|
9230
|
+
}
|
|
9231
|
+
function sqlLeadStatementKeyword(sql) {
|
|
9232
|
+
const first = sqlFirstKeywordOutsideLiterals(sql);
|
|
9233
|
+
if (!first) return null;
|
|
9234
|
+
if (first.toUpperCase() !== "WITH") return first;
|
|
9235
|
+
return sqlTerminalKeywordAfterWith(sql) ?? first;
|
|
9236
|
+
}
|
|
9237
|
+
function statementExpectsResultRows(sql) {
|
|
9238
|
+
const lead = sqlLeadStatementKeyword(sql);
|
|
9239
|
+
if (lead) {
|
|
9240
|
+
const upper = lead.toUpperCase();
|
|
9241
|
+
if (ROW_PRODUCING_LEAD_KEYWORDS.has(upper)) {
|
|
9242
|
+
return true;
|
|
9243
|
+
}
|
|
9244
|
+
if (MUTATION_LEAD_KEYWORDS.has(upper)) {
|
|
9245
|
+
return sqlContainsKeywordOutsideLiterals(sql, "RETURNING");
|
|
9246
|
+
}
|
|
9247
|
+
}
|
|
9248
|
+
return sqlContainsKeywordOutsideLiterals(sql, "RETURNING");
|
|
9249
|
+
}
|
|
9250
|
+
function collectRowsFromBatchResults(results) {
|
|
9251
|
+
const rows = [];
|
|
9252
|
+
for (const item of results) {
|
|
9253
|
+
if (Array.isArray(item.results) && item.results.length > 0) {
|
|
9254
|
+
rows.push(...item.results);
|
|
9255
|
+
}
|
|
9256
|
+
}
|
|
9257
|
+
return rows;
|
|
9258
|
+
}
|
|
9259
|
+
function sumBatchAffectedRows(results, statementCount) {
|
|
9260
|
+
let sum2 = 0;
|
|
9261
|
+
let sawChanges = false;
|
|
9262
|
+
for (const item of results) {
|
|
9263
|
+
const changes = item.meta?.changes;
|
|
9264
|
+
if (typeof changes === "number") {
|
|
9265
|
+
sum2 += changes;
|
|
9266
|
+
sawChanges = true;
|
|
9267
|
+
}
|
|
9268
|
+
}
|
|
9269
|
+
return sawChanges ? sum2 : statementCount;
|
|
9270
|
+
}
|
|
9271
|
+
function matchSqlKeywordAt(query, index, keyword) {
|
|
9272
|
+
const len = keyword.length;
|
|
9273
|
+
if (index + len > query.length) {
|
|
9274
|
+
return null;
|
|
9275
|
+
}
|
|
9276
|
+
const slice = query.slice(index, index + len);
|
|
9277
|
+
if (slice.toLowerCase() !== keyword.toLowerCase()) {
|
|
9278
|
+
return null;
|
|
9279
|
+
}
|
|
9280
|
+
const before = index === 0 ? "" : query[index - 1];
|
|
9281
|
+
const after = index + len >= query.length ? "" : query[index + len];
|
|
9282
|
+
const isIdent = (c) => /[A-Za-z0-9_]/.test(c);
|
|
9283
|
+
if (before && isIdent(before)) {
|
|
9284
|
+
return null;
|
|
9285
|
+
}
|
|
9286
|
+
if (after && isIdent(after)) {
|
|
9287
|
+
return null;
|
|
9288
|
+
}
|
|
9289
|
+
return len;
|
|
9290
|
+
}
|
|
9291
|
+
function splitSqlStatements(query) {
|
|
9292
|
+
const statements = [];
|
|
9293
|
+
let inSingle = false;
|
|
9294
|
+
let inDouble = false;
|
|
9295
|
+
let inBacktick = false;
|
|
9296
|
+
let inBracket = false;
|
|
9297
|
+
let inLineComment = false;
|
|
9298
|
+
let inBlockComment = false;
|
|
9299
|
+
let segmentStart = 0;
|
|
9300
|
+
let segmentHasContent = false;
|
|
9301
|
+
let awaitTriggerBegin = false;
|
|
9302
|
+
let triggerBodyDepth = 0;
|
|
9303
|
+
let caseDepth = 0;
|
|
9304
|
+
const flushSegment = (end) => {
|
|
9305
|
+
if (!segmentHasContent) {
|
|
9306
|
+
segmentStart = end + 1;
|
|
9307
|
+
return;
|
|
9308
|
+
}
|
|
9309
|
+
const sql = query.slice(segmentStart, end).trim();
|
|
9310
|
+
if (sql) {
|
|
9311
|
+
statements.push(sql);
|
|
9312
|
+
}
|
|
9313
|
+
segmentHasContent = false;
|
|
9314
|
+
segmentStart = end + 1;
|
|
9315
|
+
awaitTriggerBegin = false;
|
|
9316
|
+
triggerBodyDepth = 0;
|
|
9317
|
+
caseDepth = 0;
|
|
9318
|
+
};
|
|
9319
|
+
for (let i = 0; i < query.length; i += 1) {
|
|
9320
|
+
const ch = query[i];
|
|
9321
|
+
const next = query[i + 1];
|
|
9322
|
+
if (inLineComment) {
|
|
9323
|
+
if (ch === "\n" || ch === "\r") {
|
|
9324
|
+
inLineComment = false;
|
|
9325
|
+
}
|
|
9326
|
+
continue;
|
|
9327
|
+
}
|
|
9328
|
+
if (inBlockComment) {
|
|
9329
|
+
if (ch === "*" && next === "/") {
|
|
9330
|
+
inBlockComment = false;
|
|
9331
|
+
i += 1;
|
|
9332
|
+
}
|
|
9333
|
+
continue;
|
|
9334
|
+
}
|
|
9335
|
+
if (inSingle) {
|
|
9336
|
+
if (ch === "'" && next === "'") {
|
|
9337
|
+
i += 1;
|
|
9338
|
+
continue;
|
|
9339
|
+
}
|
|
9340
|
+
if (ch === "'") {
|
|
9341
|
+
inSingle = false;
|
|
9342
|
+
}
|
|
9343
|
+
continue;
|
|
9344
|
+
}
|
|
9345
|
+
if (inDouble) {
|
|
9346
|
+
if (ch === '"' && next === '"') {
|
|
9347
|
+
i += 1;
|
|
9348
|
+
continue;
|
|
9349
|
+
}
|
|
9350
|
+
if (ch === '"') {
|
|
9351
|
+
inDouble = false;
|
|
9352
|
+
}
|
|
9353
|
+
continue;
|
|
9354
|
+
}
|
|
9355
|
+
if (inBacktick) {
|
|
9356
|
+
if (ch === "`" && next === "`") {
|
|
9357
|
+
i += 1;
|
|
9358
|
+
continue;
|
|
9359
|
+
}
|
|
9360
|
+
if (ch === "`") {
|
|
9361
|
+
inBacktick = false;
|
|
9362
|
+
}
|
|
9363
|
+
continue;
|
|
9364
|
+
}
|
|
9365
|
+
if (inBracket) {
|
|
9366
|
+
if (ch === "]") {
|
|
9367
|
+
inBracket = false;
|
|
9368
|
+
}
|
|
9369
|
+
continue;
|
|
9370
|
+
}
|
|
9371
|
+
if (ch === "-" && next === "-") {
|
|
9372
|
+
inLineComment = true;
|
|
9373
|
+
i += 1;
|
|
9374
|
+
continue;
|
|
9375
|
+
}
|
|
9376
|
+
if (ch === "/" && next === "*") {
|
|
9377
|
+
inBlockComment = true;
|
|
9378
|
+
i += 1;
|
|
9379
|
+
continue;
|
|
9380
|
+
}
|
|
9381
|
+
if (ch === "'") {
|
|
9382
|
+
inSingle = true;
|
|
9383
|
+
segmentHasContent = true;
|
|
9384
|
+
continue;
|
|
9385
|
+
}
|
|
9386
|
+
if (ch === '"') {
|
|
9387
|
+
inDouble = true;
|
|
9388
|
+
segmentHasContent = true;
|
|
9389
|
+
continue;
|
|
9390
|
+
}
|
|
9391
|
+
if (ch === "`") {
|
|
9392
|
+
inBacktick = true;
|
|
9393
|
+
segmentHasContent = true;
|
|
9394
|
+
continue;
|
|
9395
|
+
}
|
|
9396
|
+
if (ch === "[") {
|
|
9397
|
+
inBracket = true;
|
|
9398
|
+
segmentHasContent = true;
|
|
9399
|
+
continue;
|
|
9400
|
+
}
|
|
9401
|
+
if (/[A-Za-z_]/.test(ch)) {
|
|
9402
|
+
const createLen = matchSqlKeywordAt(query, i, "CREATE");
|
|
9403
|
+
if (createLen != null) {
|
|
9404
|
+
let j2 = i + createLen;
|
|
9405
|
+
const skipWsAndComments = () => {
|
|
9406
|
+
while (j2 < query.length) {
|
|
9407
|
+
const c = query[j2];
|
|
9408
|
+
const n = query[j2 + 1];
|
|
9409
|
+
if (/\s/.test(c)) {
|
|
9410
|
+
j2 += 1;
|
|
9411
|
+
continue;
|
|
9412
|
+
}
|
|
9413
|
+
if (c === "-" && n === "-") {
|
|
9414
|
+
j2 += 2;
|
|
9415
|
+
while (j2 < query.length && query[j2] !== "\n" && query[j2] !== "\r") {
|
|
9416
|
+
j2 += 1;
|
|
9417
|
+
}
|
|
9418
|
+
continue;
|
|
9419
|
+
}
|
|
9420
|
+
if (c === "/" && n === "*") {
|
|
9421
|
+
j2 += 2;
|
|
9422
|
+
while (j2 < query.length) {
|
|
9423
|
+
if (query[j2] === "*" && query[j2 + 1] === "/") {
|
|
9424
|
+
j2 += 2;
|
|
9425
|
+
break;
|
|
9426
|
+
}
|
|
9427
|
+
j2 += 1;
|
|
9428
|
+
}
|
|
9429
|
+
continue;
|
|
9430
|
+
}
|
|
9431
|
+
break;
|
|
9432
|
+
}
|
|
9433
|
+
};
|
|
9434
|
+
skipWsAndComments();
|
|
9435
|
+
const tempLen = matchSqlKeywordAt(query, j2, "TEMPORARY") ?? matchSqlKeywordAt(query, j2, "TEMP");
|
|
9436
|
+
if (tempLen != null) {
|
|
9437
|
+
j2 += tempLen;
|
|
9438
|
+
skipWsAndComments();
|
|
9439
|
+
}
|
|
9440
|
+
const triggerLen = matchSqlKeywordAt(query, j2, "TRIGGER");
|
|
9441
|
+
if (triggerLen != null) {
|
|
9442
|
+
awaitTriggerBegin = true;
|
|
9443
|
+
segmentHasContent = true;
|
|
9444
|
+
i += createLen - 1;
|
|
9445
|
+
continue;
|
|
9446
|
+
}
|
|
9447
|
+
segmentHasContent = true;
|
|
9448
|
+
i += createLen - 1;
|
|
9449
|
+
continue;
|
|
9450
|
+
}
|
|
9451
|
+
const caseLen = matchSqlKeywordAt(query, i, "CASE");
|
|
9452
|
+
if (caseLen != null) {
|
|
9453
|
+
caseDepth += 1;
|
|
9454
|
+
segmentHasContent = true;
|
|
9455
|
+
i += caseLen - 1;
|
|
9456
|
+
continue;
|
|
9457
|
+
}
|
|
9458
|
+
const beginLen = matchSqlKeywordAt(query, i, "BEGIN");
|
|
9459
|
+
if (beginLen != null) {
|
|
9460
|
+
if (awaitTriggerBegin) {
|
|
9461
|
+
triggerBodyDepth += 1;
|
|
9462
|
+
awaitTriggerBegin = false;
|
|
9463
|
+
}
|
|
9464
|
+
segmentHasContent = true;
|
|
9465
|
+
i += beginLen - 1;
|
|
9466
|
+
continue;
|
|
9467
|
+
}
|
|
9468
|
+
const endLen = matchSqlKeywordAt(query, i, "END");
|
|
9469
|
+
if (endLen != null) {
|
|
9470
|
+
if (caseDepth > 0) {
|
|
9471
|
+
caseDepth -= 1;
|
|
9472
|
+
} else if (triggerBodyDepth > 0) {
|
|
9473
|
+
triggerBodyDepth -= 1;
|
|
9474
|
+
}
|
|
9475
|
+
segmentHasContent = true;
|
|
9476
|
+
i += endLen - 1;
|
|
9477
|
+
continue;
|
|
9478
|
+
}
|
|
9479
|
+
let j = i + 1;
|
|
9480
|
+
while (j < query.length && /[A-Za-z0-9_]/.test(query[j])) {
|
|
9481
|
+
j += 1;
|
|
9482
|
+
}
|
|
9483
|
+
segmentHasContent = true;
|
|
9484
|
+
i = j - 1;
|
|
9485
|
+
continue;
|
|
9486
|
+
}
|
|
9487
|
+
if (ch === ";") {
|
|
9488
|
+
if (triggerBodyDepth > 0 || caseDepth > 0) {
|
|
9489
|
+
segmentHasContent = true;
|
|
9490
|
+
continue;
|
|
9491
|
+
}
|
|
9492
|
+
flushSegment(i);
|
|
9493
|
+
continue;
|
|
9494
|
+
}
|
|
9495
|
+
if (!/\s/.test(ch)) {
|
|
9496
|
+
segmentHasContent = true;
|
|
9497
|
+
}
|
|
9498
|
+
}
|
|
9499
|
+
flushSegment(query.length);
|
|
9500
|
+
return statements;
|
|
9501
|
+
}
|
|
9502
|
+
function isMultiStatement(query) {
|
|
9503
|
+
return splitSqlStatements(query).length > 1;
|
|
9504
|
+
}
|
|
9505
|
+
function resolveSessionTarget(db, input) {
|
|
9506
|
+
const sessionValue = input.bookmark?.trim() || input.sessionMode?.trim();
|
|
9507
|
+
if (!sessionValue) {
|
|
9508
|
+
return { target: db, session: null };
|
|
9509
|
+
}
|
|
9510
|
+
if (typeof db.withSession !== "function") {
|
|
9511
|
+
throw new Error("D1 session mode/bookmark requested but withSession is not available");
|
|
9512
|
+
}
|
|
9513
|
+
const session = db.withSession(sessionValue);
|
|
9514
|
+
return { target: session, session };
|
|
9515
|
+
}
|
|
9516
|
+
function normalizeD1BindParams(params) {
|
|
9517
|
+
return params.map((value) => {
|
|
9518
|
+
if (typeof value === "boolean") {
|
|
9519
|
+
return value ? 1 : 0;
|
|
9520
|
+
}
|
|
9521
|
+
return value;
|
|
9522
|
+
});
|
|
9523
|
+
}
|
|
9524
|
+
async function executeD1Query(db, input) {
|
|
9525
|
+
const query = input.query?.trim();
|
|
9526
|
+
if (!query) {
|
|
9527
|
+
return { ok: false, error: "invalid_query", message: "query is required" };
|
|
9528
|
+
}
|
|
9529
|
+
const params = normalizeD1BindParams(Array.isArray(input.params) ? input.params : []);
|
|
9530
|
+
const { target, session } = resolveSessionTarget(db, input);
|
|
9531
|
+
if (isMultiStatement(query)) {
|
|
9532
|
+
if (params.length > 0) {
|
|
9533
|
+
return {
|
|
9534
|
+
ok: false,
|
|
9535
|
+
error: "invalid_query",
|
|
9536
|
+
message: "params are only supported for single prepared statements"
|
|
9537
|
+
};
|
|
9538
|
+
}
|
|
9539
|
+
const resolveBookmark = () => session?.getBookmark() ?? null;
|
|
9540
|
+
const parts = splitSqlStatements(query);
|
|
9541
|
+
if (typeof target.batch === "function") {
|
|
9542
|
+
const prepared = parts.map((part) => target.prepare(part));
|
|
9543
|
+
const results = await target.batch(prepared);
|
|
9544
|
+
const rows2 = collectRowsFromBatchResults(results);
|
|
9545
|
+
return {
|
|
9546
|
+
ok: true,
|
|
9547
|
+
rows: rows2,
|
|
9548
|
+
columns: resultColumns(rows2),
|
|
9549
|
+
// Prefer returned rows; otherwise sum mutation meta.changes (not statement count).
|
|
9550
|
+
count: rows2.length > 0 ? rows2.length : sumBatchAffectedRows(results, parts.length),
|
|
9551
|
+
bookmark: resolveBookmark(),
|
|
9552
|
+
meta: { statementCount: parts.length, results },
|
|
9553
|
+
statementCount: parts.length
|
|
9554
|
+
};
|
|
9555
|
+
}
|
|
9556
|
+
const canExec = typeof target.exec === "function" && !session;
|
|
9557
|
+
if (canExec) {
|
|
9558
|
+
const execResult = await target.exec(query);
|
|
9559
|
+
return {
|
|
9560
|
+
ok: true,
|
|
9561
|
+
rows: [],
|
|
9562
|
+
columns: [],
|
|
9563
|
+
durationMs: execResult.duration,
|
|
9564
|
+
count: execResult.count,
|
|
9565
|
+
bookmark: resolveBookmark(),
|
|
9566
|
+
meta: { statementCount: execResult.count },
|
|
9567
|
+
statementCount: execResult.count
|
|
9568
|
+
};
|
|
9569
|
+
}
|
|
9570
|
+
return {
|
|
9571
|
+
ok: false,
|
|
9572
|
+
error: "invalid_query",
|
|
9573
|
+
message: "multi-statement query requires D1 batch() or exec() support"
|
|
9574
|
+
};
|
|
9575
|
+
}
|
|
9576
|
+
let statement = target.prepare(query);
|
|
9577
|
+
if (params.length > 0) {
|
|
9578
|
+
statement = statement.bind(...params);
|
|
9579
|
+
}
|
|
9580
|
+
const expectsRows = statementExpectsResultRows(query);
|
|
9581
|
+
const result = expectsRows ? await statement.all() : await statement.run();
|
|
9582
|
+
if (result.success === false) {
|
|
9583
|
+
const errorField = result.error;
|
|
9584
|
+
const message = typeof errorField === "string" && errorField.trim() ? errorField : "D1 query failed";
|
|
9585
|
+
return {
|
|
9586
|
+
ok: false,
|
|
9587
|
+
error: "query_failed",
|
|
9588
|
+
message
|
|
9589
|
+
};
|
|
9590
|
+
}
|
|
9591
|
+
const rows = Array.isArray(result.results) ? result.results : [];
|
|
9592
|
+
const bookmark = session?.getBookmark() ?? null;
|
|
9593
|
+
const meta = result.meta ?? {};
|
|
9594
|
+
const changes = typeof meta.changes === "number" ? meta.changes : typeof result.meta?.changes === "number" ? result.meta.changes : void 0;
|
|
9595
|
+
return {
|
|
9596
|
+
ok: true,
|
|
9597
|
+
rows,
|
|
9598
|
+
columns: resultColumns(rows),
|
|
9599
|
+
durationMs: typeof result.meta?.duration === "number" ? result.meta.duration : void 0,
|
|
9600
|
+
count: expectsRows ? rows.length : changes ?? rows.length,
|
|
9601
|
+
bookmark,
|
|
9602
|
+
meta
|
|
9603
|
+
};
|
|
9604
|
+
}
|
|
9605
|
+
async function executeD1Batch(db, input) {
|
|
9606
|
+
const statements = Array.isArray(input.statements) ? input.statements : [];
|
|
9607
|
+
if (statements.length === 0) {
|
|
9608
|
+
return {
|
|
9609
|
+
ok: false,
|
|
9610
|
+
error: "invalid_batch",
|
|
9611
|
+
message: "statements must contain at least one item"
|
|
9612
|
+
};
|
|
9613
|
+
}
|
|
9614
|
+
const { target, session } = resolveSessionTarget(db, input);
|
|
9615
|
+
const prepared = statements.map((item) => {
|
|
9616
|
+
const query = item.query?.trim();
|
|
9617
|
+
if (!query) {
|
|
9618
|
+
throw new Error("statements[].query is required");
|
|
9619
|
+
}
|
|
9620
|
+
const params = normalizeD1BindParams(Array.isArray(item.params) ? item.params : []);
|
|
9621
|
+
let statement = target.prepare(query);
|
|
9622
|
+
if (params.length > 0) {
|
|
9623
|
+
statement = statement.bind(...params);
|
|
9624
|
+
}
|
|
9625
|
+
return statement;
|
|
9626
|
+
});
|
|
9627
|
+
const results = await target.batch(prepared);
|
|
9628
|
+
const bookmark = session?.getBookmark() ?? null;
|
|
9629
|
+
return {
|
|
9630
|
+
ok: true,
|
|
9631
|
+
results,
|
|
9632
|
+
bookmark
|
|
9633
|
+
};
|
|
9634
|
+
}
|
|
9635
|
+
|
|
9636
|
+
// src/cloudflare/d1/sql.ts
|
|
9637
|
+
function asSingle(sql, params) {
|
|
9638
|
+
return { sql, params };
|
|
9639
|
+
}
|
|
9640
|
+
function asBatch(statements) {
|
|
9641
|
+
if (statements.length === 0) {
|
|
9642
|
+
throw new D1SqlCompileError("empty_insert", "batch requires at least one statement");
|
|
9643
|
+
}
|
|
9644
|
+
return {
|
|
9645
|
+
sql: statements[0].sql,
|
|
9646
|
+
params: statements[0].params,
|
|
9647
|
+
statements
|
|
9648
|
+
};
|
|
9649
|
+
}
|
|
9650
|
+
function hasPaginationBounds(payload) {
|
|
9651
|
+
return payload.limit !== void 0 || payload.offset !== void 0 || payload.page_size !== void 0 || payload.current_page !== void 0;
|
|
9652
|
+
}
|
|
9653
|
+
function assertEffectiveMutationBounds(payload) {
|
|
9654
|
+
if (payload.current_page !== void 0 && payload.page_size === void 0 && payload.limit === void 0) {
|
|
9655
|
+
throw new D1SqlCompileError(
|
|
9656
|
+
"page_without_size",
|
|
9657
|
+
"current_page requires page_size (or limit) for bounded update/delete on D1 edge-local"
|
|
9658
|
+
);
|
|
9659
|
+
}
|
|
9660
|
+
const clause = limitOffsetClause(payload);
|
|
9661
|
+
if (!clause.trim()) {
|
|
9662
|
+
throw new D1SqlCompileError(
|
|
9663
|
+
"invalid_pagination_bounds",
|
|
9664
|
+
"Bounded update/delete requires limit, offset, and/or page_size on D1 edge-local"
|
|
9665
|
+
);
|
|
9666
|
+
}
|
|
9667
|
+
}
|
|
9668
|
+
var SQLITE_ROWID_ALIASES = /* @__PURE__ */ new Set(["rowid", "oid", "_rowid_"]);
|
|
9669
|
+
function referencedMutationColumns(payload) {
|
|
9670
|
+
const names = [];
|
|
9671
|
+
for (const condition of payload.conditions ?? []) {
|
|
9672
|
+
const column = (condition.column ?? condition.eq_column ?? "").trim();
|
|
9673
|
+
if (column) names.push(column);
|
|
9674
|
+
}
|
|
9675
|
+
if (payload.sort_by?.field?.trim()) {
|
|
9676
|
+
names.push(payload.sort_by.field.trim());
|
|
9677
|
+
}
|
|
9678
|
+
return names;
|
|
9679
|
+
}
|
|
9680
|
+
function resolveBoundedIdentityColumn(payload, options) {
|
|
9681
|
+
const refs = referencedMutationColumns(payload);
|
|
9682
|
+
const lower = refs.map((name) => name.toLowerCase());
|
|
9683
|
+
if (lower.some((name) => SQLITE_ROWID_ALIASES.has(name))) {
|
|
9684
|
+
throw new D1SqlCompileError(
|
|
9685
|
+
"bounded_mutation_unsafe_identity",
|
|
9686
|
+
"Bounded update/delete cannot use rowid/oid/_rowid_ in filters or order \u2014 those names may be user columns that shadow SQLite row identity. Resolve the table primary key (or a single-column unique index) instead."
|
|
9687
|
+
);
|
|
9688
|
+
}
|
|
9689
|
+
const identity = options?.identityColumn?.trim();
|
|
9690
|
+
if (!identity) {
|
|
9691
|
+
throw new D1SqlCompileError(
|
|
9692
|
+
"bounded_mutation_no_unique_identity",
|
|
9693
|
+
"Bounded update/delete requires a proven unique identity column from the table schema (single-column PRIMARY KEY or UNIQUE index). Cannot assume a column named id."
|
|
9694
|
+
);
|
|
9695
|
+
}
|
|
9696
|
+
if (SQLITE_ROWID_ALIASES.has(identity.toLowerCase())) {
|
|
9697
|
+
throw new D1SqlCompileError(
|
|
9698
|
+
"bounded_mutation_unsafe_identity",
|
|
9699
|
+
`Bounded update/delete cannot use identity column "${identity}" \u2014 it may shadow SQLite row identity.`
|
|
9700
|
+
);
|
|
9701
|
+
}
|
|
9702
|
+
return identity;
|
|
9703
|
+
}
|
|
9704
|
+
function boundedRowidInClause(table, whereSql, whereParams, payload, options) {
|
|
9705
|
+
assertEffectiveMutationBounds(payload);
|
|
9706
|
+
const identity = resolveBoundedIdentityColumn(payload, options);
|
|
9707
|
+
const identitySql = quoteIdent(identity);
|
|
9708
|
+
const innerWhere = whereSql.replace(/^WHERE\s+/i, "");
|
|
9709
|
+
const parts = [
|
|
9710
|
+
`SELECT ${identitySql} FROM ${quoteIdent(table)}`,
|
|
9711
|
+
innerWhere ? `WHERE ${innerWhere}` : "",
|
|
9712
|
+
orderClause(payload.sort_by),
|
|
9713
|
+
limitOffsetClause(payload)
|
|
9714
|
+
].filter(Boolean);
|
|
9715
|
+
return {
|
|
9716
|
+
sql: `${identitySql} IN (${parts.join(" ")})`,
|
|
9717
|
+
params: [...whereParams]
|
|
9718
|
+
};
|
|
9719
|
+
}
|
|
9720
|
+
var D1SqlCompileError = class extends Error {
|
|
9721
|
+
code;
|
|
9722
|
+
constructor(code, message) {
|
|
9723
|
+
super(message);
|
|
9724
|
+
this.name = "D1SqlCompileError";
|
|
9725
|
+
this.code = code;
|
|
9726
|
+
}
|
|
9727
|
+
};
|
|
9728
|
+
var SAFE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
9729
|
+
function quoteIdent(name) {
|
|
9730
|
+
const trimmed = name.trim();
|
|
9731
|
+
if (!trimmed) {
|
|
9732
|
+
throw new D1SqlCompileError("invalid_identifier", "Identifier is required");
|
|
9733
|
+
}
|
|
9734
|
+
if (trimmed.includes(".")) {
|
|
9735
|
+
throw new D1SqlCompileError(
|
|
9736
|
+
"schema_qualified_name",
|
|
9737
|
+
`Schema-qualified names are unsupported on D1 edge-local: ${trimmed}`
|
|
9738
|
+
);
|
|
9739
|
+
}
|
|
9740
|
+
if (!SAFE_IDENTIFIER.test(trimmed)) {
|
|
9741
|
+
throw new D1SqlCompileError(
|
|
9742
|
+
"invalid_identifier",
|
|
9743
|
+
`Invalid SQL identifier for D1 edge-local: ${trimmed}`
|
|
9744
|
+
);
|
|
9745
|
+
}
|
|
9746
|
+
return quoteQualifiedIdentifier(trimmed);
|
|
9747
|
+
}
|
|
9748
|
+
var RESPONSE_ALIAS_PATTERN2 = /^([A-Za-z_][A-Za-z0-9_]*)\s*:\s*([A-Za-z_][A-Za-z0-9_]*)$/;
|
|
9749
|
+
var SQL_ALIAS_PATTERN2 = /^([A-Za-z_][A-Za-z0-9_]*)\s+(?:as\s+)?([A-Za-z_][A-Za-z0-9_]*)$/i;
|
|
9750
|
+
function quoteSelectTokenStrict(token) {
|
|
9751
|
+
const trimmed = token.trim();
|
|
9752
|
+
if (!trimmed || trimmed === "*") return trimmed || "*";
|
|
9753
|
+
if (SAFE_IDENTIFIER.test(trimmed)) {
|
|
9754
|
+
return quoteQualifiedIdentifier(trimmed);
|
|
9755
|
+
}
|
|
9756
|
+
const responseAlias = RESPONSE_ALIAS_PATTERN2.exec(trimmed);
|
|
9757
|
+
if (responseAlias) {
|
|
9758
|
+
const [, aliasIdentifier, baseIdentifier] = responseAlias;
|
|
9759
|
+
return `${quoteQualifiedIdentifier(baseIdentifier)} AS ${quoteQualifiedIdentifier(aliasIdentifier)}`;
|
|
9760
|
+
}
|
|
9761
|
+
const sqlAlias = SQL_ALIAS_PATTERN2.exec(trimmed);
|
|
9762
|
+
if (sqlAlias) {
|
|
9763
|
+
const [, baseIdentifier, aliasIdentifier] = sqlAlias;
|
|
9764
|
+
return `${quoteQualifiedIdentifier(baseIdentifier)} AS ${quoteQualifiedIdentifier(aliasIdentifier)}`;
|
|
9765
|
+
}
|
|
9766
|
+
throw new D1SqlCompileError(
|
|
9767
|
+
"unsafe_select",
|
|
9768
|
+
`SELECT/RETURNING expressions are not supported on D1 edge-local; use column names or aliases only: ${token}`
|
|
9769
|
+
);
|
|
9770
|
+
}
|
|
9771
|
+
function selectClause(columns) {
|
|
9772
|
+
if (columns === void 0 || columns === "*" || columns === "") return "*";
|
|
9773
|
+
if (typeof columns === "string") {
|
|
9774
|
+
const trimmed = columns.trim();
|
|
9775
|
+
if (!trimmed || trimmed === "*") return "*";
|
|
9776
|
+
return trimmed.split(",").map((part) => quoteSelectTokenStrict(part)).join(", ");
|
|
9777
|
+
}
|
|
9778
|
+
if (columns.length === 0) return "*";
|
|
9779
|
+
return columns.map((column) => quoteSelectTokenStrict(column)).join(", ");
|
|
9780
|
+
}
|
|
9781
|
+
function wantsReturning(payload) {
|
|
9782
|
+
return Boolean(payload.columns) && payload.head !== true;
|
|
9783
|
+
}
|
|
9784
|
+
function conditionToWhere(condition) {
|
|
9785
|
+
const column = condition.column?.trim() || condition.eq_column?.trim() || "";
|
|
9786
|
+
if (!column) {
|
|
9787
|
+
throw new D1SqlCompileError("invalid_condition", "Condition requires a column");
|
|
9788
|
+
}
|
|
9789
|
+
const col = quoteIdent(column);
|
|
9790
|
+
const operator = (condition.operator || "eq").toLowerCase();
|
|
9791
|
+
const value = condition.value !== void 0 ? condition.value : condition.eq_value;
|
|
9792
|
+
switch (operator) {
|
|
9793
|
+
case "eq": {
|
|
9794
|
+
if (Array.isArray(value)) {
|
|
9795
|
+
if (value.length === 0) {
|
|
9796
|
+
return { sql: "1 = 0", params: [] };
|
|
9797
|
+
}
|
|
9798
|
+
const placeholders = value.map(() => "?").join(", ");
|
|
9799
|
+
return { sql: `${col} IN (${placeholders})`, params: [...value] };
|
|
9800
|
+
}
|
|
9801
|
+
if (value === null) {
|
|
9802
|
+
return { sql: `${col} IS NULL`, params: [] };
|
|
9803
|
+
}
|
|
9804
|
+
return { sql: `${col} = ?`, params: [value ?? null] };
|
|
9805
|
+
}
|
|
9806
|
+
case "neq":
|
|
9807
|
+
if (value === null) {
|
|
9808
|
+
return { sql: `${col} IS NOT NULL`, params: [] };
|
|
9809
|
+
}
|
|
9810
|
+
return { sql: `${col} != ?`, params: [value ?? null] };
|
|
9811
|
+
case "gt":
|
|
9812
|
+
return { sql: `${col} > ?`, params: [value ?? null] };
|
|
9813
|
+
case "gte":
|
|
9814
|
+
return { sql: `${col} >= ?`, params: [value ?? null] };
|
|
9815
|
+
case "lt":
|
|
9816
|
+
return { sql: `${col} < ?`, params: [value ?? null] };
|
|
9817
|
+
case "lte":
|
|
9818
|
+
return { sql: `${col} <= ?`, params: [value ?? null] };
|
|
9819
|
+
case "like":
|
|
9820
|
+
return { sql: `${col} LIKE ?`, params: [value ?? null] };
|
|
9821
|
+
case "ilike":
|
|
9822
|
+
return { sql: `${col} LIKE ? COLLATE NOCASE`, params: [value ?? null] };
|
|
9823
|
+
case "in": {
|
|
9824
|
+
const items = Array.isArray(value) ? value : value === void 0 ? [] : [value];
|
|
9825
|
+
if (items.length === 0) {
|
|
9826
|
+
return { sql: "1 = 0", params: [] };
|
|
9827
|
+
}
|
|
9828
|
+
const placeholders = items.map(() => "?").join(", ");
|
|
9829
|
+
return { sql: `${col} IN (${placeholders})`, params: [...items] };
|
|
9830
|
+
}
|
|
9831
|
+
case "is": {
|
|
9832
|
+
if (value === null || value === "null") {
|
|
9833
|
+
return { sql: `${col} IS NULL`, params: [] };
|
|
9834
|
+
}
|
|
9835
|
+
if (value === true || value === "true") {
|
|
9836
|
+
return { sql: `${col} IS TRUE`, params: [] };
|
|
9837
|
+
}
|
|
9838
|
+
if (value === false || value === "false") {
|
|
9839
|
+
return { sql: `${col} IS FALSE`, params: [] };
|
|
9840
|
+
}
|
|
9841
|
+
return { sql: `${col} IS ?`, params: [value] };
|
|
9842
|
+
}
|
|
9843
|
+
case "not":
|
|
9844
|
+
case "or":
|
|
9845
|
+
case "contains":
|
|
9846
|
+
case "containedby":
|
|
9847
|
+
throw new D1SqlCompileError(
|
|
9848
|
+
"unsupported_operator",
|
|
9849
|
+
`Condition operator "${operator}" is not supported on D1 edge-local L1`
|
|
9850
|
+
);
|
|
9851
|
+
default:
|
|
9852
|
+
throw new D1SqlCompileError(
|
|
9853
|
+
"unsupported_operator",
|
|
9854
|
+
`Unknown condition operator "${operator}"`
|
|
9855
|
+
);
|
|
9856
|
+
}
|
|
9857
|
+
}
|
|
9858
|
+
function buildWhere(conditions) {
|
|
9859
|
+
if (!conditions?.length) {
|
|
9860
|
+
return { sql: "", params: [] };
|
|
9861
|
+
}
|
|
9862
|
+
const parts = [];
|
|
9863
|
+
const params = [];
|
|
9864
|
+
for (const condition of conditions) {
|
|
9865
|
+
if (!condition.operator && condition.eq_column) {
|
|
9866
|
+
const clause2 = conditionToWhere({
|
|
9867
|
+
...condition,
|
|
9868
|
+
operator: "eq",
|
|
9869
|
+
column: condition.eq_column,
|
|
9870
|
+
value: condition.eq_value
|
|
9871
|
+
});
|
|
9872
|
+
parts.push(clause2.sql);
|
|
9873
|
+
params.push(...clause2.params);
|
|
9874
|
+
continue;
|
|
9875
|
+
}
|
|
9876
|
+
const clause = conditionToWhere(condition);
|
|
9877
|
+
parts.push(clause.sql);
|
|
9878
|
+
params.push(...clause.params);
|
|
9879
|
+
}
|
|
9880
|
+
return {
|
|
9881
|
+
sql: parts.length ? `WHERE ${parts.join(" AND ")}` : "",
|
|
9882
|
+
params
|
|
9883
|
+
};
|
|
9884
|
+
}
|
|
9885
|
+
function orderClause(order) {
|
|
9886
|
+
if (!order?.field?.trim()) return "";
|
|
9887
|
+
const direction = order.direction === "descending" ? "DESC" : "ASC";
|
|
9888
|
+
return `ORDER BY ${quoteIdent(order.field)} ${direction}`;
|
|
9889
|
+
}
|
|
9890
|
+
function limitOffsetClause(payload) {
|
|
9891
|
+
let limit = payload.limit;
|
|
9892
|
+
let offset = payload.offset;
|
|
9893
|
+
if (limit === void 0 && payload.page_size !== void 0) {
|
|
9894
|
+
limit = payload.page_size;
|
|
9895
|
+
}
|
|
9896
|
+
if (payload.current_page !== void 0 && offset === void 0) {
|
|
9897
|
+
const pageSize = payload.page_size ?? payload.limit;
|
|
9898
|
+
if (pageSize !== void 0) {
|
|
9899
|
+
offset = Math.max(0, (payload.current_page - 1) * pageSize);
|
|
9900
|
+
}
|
|
9901
|
+
}
|
|
9902
|
+
const parts = [];
|
|
9903
|
+
if (offset !== void 0 && limit === void 0) {
|
|
9904
|
+
parts.push("LIMIT -1");
|
|
9905
|
+
parts.push(`OFFSET ${Math.max(0, Math.trunc(offset))}`);
|
|
9906
|
+
} else {
|
|
9907
|
+
if (limit !== void 0) {
|
|
9908
|
+
parts.push(`LIMIT ${Math.max(0, Math.trunc(limit))}`);
|
|
9909
|
+
}
|
|
9910
|
+
if (offset !== void 0) {
|
|
9911
|
+
parts.push(`OFFSET ${Math.max(0, Math.trunc(offset))}`);
|
|
9912
|
+
}
|
|
9913
|
+
}
|
|
9914
|
+
return parts.join(" ");
|
|
9915
|
+
}
|
|
9916
|
+
function rejectStructuredRelations(payload) {
|
|
9917
|
+
const select = payload.select;
|
|
9918
|
+
if (select && typeof select === "object" && !Array.isArray(select)) {
|
|
9919
|
+
for (const value of Object.values(select)) {
|
|
9920
|
+
if (value && typeof value === "object") {
|
|
9921
|
+
throw new D1SqlCompileError(
|
|
9922
|
+
"relations_unsupported",
|
|
9923
|
+
"Nested relation selects are unsupported on D1 edge-local"
|
|
9924
|
+
);
|
|
9925
|
+
}
|
|
9926
|
+
}
|
|
9927
|
+
}
|
|
9928
|
+
if (payload.view_name) {
|
|
9929
|
+
throw new D1SqlCompileError(
|
|
9930
|
+
"view_unsupported",
|
|
9931
|
+
"view_name is unsupported on D1 edge-local L1"
|
|
9932
|
+
);
|
|
9933
|
+
}
|
|
9934
|
+
}
|
|
9935
|
+
function jsonValue(value) {
|
|
9936
|
+
if (value === void 0) return null;
|
|
9937
|
+
if (value !== null && typeof value === "object") {
|
|
9938
|
+
return JSON.stringify(value);
|
|
9939
|
+
}
|
|
9940
|
+
return value;
|
|
9941
|
+
}
|
|
9942
|
+
function compileD1Fetch(payload) {
|
|
9943
|
+
rejectStructuredRelations(payload);
|
|
9944
|
+
const table = payload.table_name?.trim();
|
|
9945
|
+
if (!table) {
|
|
9946
|
+
throw new D1SqlCompileError("missing_table", "table_name is required for fetch");
|
|
9947
|
+
}
|
|
9948
|
+
let columns = payload.columns;
|
|
9949
|
+
if (payload.select && typeof payload.select === "object" && !Array.isArray(payload.select)) {
|
|
9950
|
+
const keys = Object.entries(payload.select).filter(([, enabled]) => enabled === true || enabled === 1).map(([key]) => key);
|
|
9951
|
+
if (keys.length > 0) {
|
|
9952
|
+
columns = keys;
|
|
9953
|
+
}
|
|
9954
|
+
} else if (typeof payload.select === "string" && payload.select.trim()) {
|
|
9955
|
+
columns = payload.select;
|
|
9956
|
+
}
|
|
9957
|
+
let where = buildWhere(payload.conditions);
|
|
9958
|
+
if (!where.sql && payload.where && typeof payload.where === "object") {
|
|
9959
|
+
const eqConditions = Object.entries(
|
|
9960
|
+
payload.where
|
|
9961
|
+
).map(([column, value]) => ({
|
|
9962
|
+
column,
|
|
9963
|
+
operator: "eq",
|
|
9964
|
+
value
|
|
9965
|
+
}));
|
|
9966
|
+
where = buildWhere(eqConditions);
|
|
9967
|
+
}
|
|
9968
|
+
if (payload.head === true) {
|
|
9969
|
+
return compileD1CountFromWhere(table, where);
|
|
9970
|
+
}
|
|
9971
|
+
const parts = [
|
|
9972
|
+
`SELECT ${selectClause(columns)} FROM ${quoteIdent(table)}`,
|
|
9973
|
+
where.sql,
|
|
9974
|
+
orderClause(payload.sort_by),
|
|
9975
|
+
limitOffsetClause(payload)
|
|
9976
|
+
].filter(Boolean);
|
|
9977
|
+
return asSingle(parts.join(" "), where.params);
|
|
9978
|
+
}
|
|
9979
|
+
function compileD1Count(payload) {
|
|
9980
|
+
rejectStructuredRelations(payload);
|
|
9981
|
+
const table = payload.table_name?.trim();
|
|
9982
|
+
if (!table) {
|
|
9983
|
+
throw new D1SqlCompileError("missing_table", "table_name is required for count");
|
|
9984
|
+
}
|
|
9985
|
+
let where = buildWhere(payload.conditions);
|
|
9986
|
+
if (!where.sql && payload.where && typeof payload.where === "object") {
|
|
9987
|
+
const eqConditions = Object.entries(
|
|
9988
|
+
payload.where
|
|
9989
|
+
).map(([column, value]) => ({
|
|
9990
|
+
column,
|
|
9991
|
+
operator: "eq",
|
|
9992
|
+
value
|
|
9993
|
+
}));
|
|
9994
|
+
where = buildWhere(eqConditions);
|
|
9995
|
+
}
|
|
9996
|
+
return compileD1CountFromWhere(table, where);
|
|
9997
|
+
}
|
|
9998
|
+
function compileD1CountFromWhere(table, where) {
|
|
9999
|
+
const parts = [
|
|
10000
|
+
`SELECT COUNT(*) AS __athena_count FROM ${quoteIdent(table)}`,
|
|
10001
|
+
where.sql
|
|
10002
|
+
].filter(Boolean);
|
|
10003
|
+
return asSingle(parts.join(" "), where.params);
|
|
10004
|
+
}
|
|
10005
|
+
function extractAthenaCount(rows) {
|
|
10006
|
+
const first = rows[0];
|
|
10007
|
+
const rawCount = first && typeof first === "object" && !Array.isArray(first) ? first.__athena_count : void 0;
|
|
10008
|
+
const count = typeof rawCount === "number" ? rawCount : typeof rawCount === "bigint" ? Number(rawCount) : Number(rawCount ?? 0);
|
|
10009
|
+
return Number.isFinite(count) ? count : 0;
|
|
10010
|
+
}
|
|
10011
|
+
function compileSingleRowInsert(table, row, payload) {
|
|
10012
|
+
const columns = Object.keys(row);
|
|
10013
|
+
if (columns.length === 0) {
|
|
10014
|
+
if (payload.on_conflict) {
|
|
10015
|
+
throw new D1SqlCompileError(
|
|
10016
|
+
"default_values_upsert_unsupported",
|
|
10017
|
+
"DEFAULT VALUES upsert is unsupported on D1 edge-local; provide insert columns or omit onConflict"
|
|
10018
|
+
);
|
|
10019
|
+
}
|
|
10020
|
+
const parts2 = [`INSERT INTO ${quoteIdent(table)} DEFAULT VALUES`];
|
|
10021
|
+
if (wantsReturning(payload)) {
|
|
10022
|
+
parts2.push(`RETURNING ${selectClause(payload.columns)}`);
|
|
10023
|
+
}
|
|
10024
|
+
return { sql: parts2.join(" "), params: [] };
|
|
10025
|
+
}
|
|
10026
|
+
const params = columns.map((column) => jsonValue(row[column]));
|
|
10027
|
+
const parts = [
|
|
10028
|
+
`INSERT INTO ${quoteIdent(table)} (${columns.map(quoteIdent).join(", ")})`,
|
|
10029
|
+
`VALUES (${columns.map(() => "?").join(", ")})`
|
|
10030
|
+
];
|
|
10031
|
+
appendOnConflict(parts, params, payload, columns);
|
|
10032
|
+
if (wantsReturning(payload)) {
|
|
10033
|
+
parts.push(`RETURNING ${selectClause(payload.columns)}`);
|
|
10034
|
+
}
|
|
10035
|
+
return { sql: parts.join(" "), params };
|
|
10036
|
+
}
|
|
10037
|
+
function parseOnConflictColumns(onConflict) {
|
|
10038
|
+
const raw = Array.isArray(onConflict) ? onConflict : [onConflict];
|
|
10039
|
+
const columns = [];
|
|
10040
|
+
for (const item of raw) {
|
|
10041
|
+
for (const part of String(item).split(",")) {
|
|
10042
|
+
const trimmed = part.trim();
|
|
10043
|
+
if (trimmed) columns.push(trimmed);
|
|
10044
|
+
}
|
|
10045
|
+
}
|
|
10046
|
+
if (columns.length === 0) {
|
|
10047
|
+
throw new D1SqlCompileError(
|
|
10048
|
+
"invalid_on_conflict",
|
|
10049
|
+
"on_conflict requires at least one column"
|
|
10050
|
+
);
|
|
10051
|
+
}
|
|
10052
|
+
return columns;
|
|
10053
|
+
}
|
|
10054
|
+
function appendOnConflict(parts, params, payload, insertColumns) {
|
|
10055
|
+
if (!payload.on_conflict) return;
|
|
10056
|
+
const conflictCols = parseOnConflictColumns(payload.on_conflict);
|
|
10057
|
+
const conflictSql = conflictCols.map(quoteIdent).join(", ");
|
|
10058
|
+
if (payload.update_body !== void 0 && payload.update_body !== null) {
|
|
10059
|
+
const entries = Object.entries(payload.update_body);
|
|
10060
|
+
if (entries.length === 0) {
|
|
10061
|
+
parts.push(`ON CONFLICT (${conflictSql}) DO NOTHING`);
|
|
10062
|
+
return;
|
|
10063
|
+
}
|
|
10064
|
+
const assignments2 = entries.map(([column, value]) => {
|
|
10065
|
+
params.push(jsonValue(value));
|
|
10066
|
+
return `${quoteIdent(column)} = ?`;
|
|
10067
|
+
});
|
|
10068
|
+
parts.push(`ON CONFLICT (${conflictSql}) DO UPDATE SET ${assignments2.join(", ")}`);
|
|
10069
|
+
return;
|
|
10070
|
+
}
|
|
10071
|
+
const conflictSet = new Set(conflictCols);
|
|
10072
|
+
const assignments = insertColumns.filter((column) => !conflictSet.has(column)).map((column) => {
|
|
10073
|
+
const quoted = quoteIdent(column);
|
|
10074
|
+
return `${quoted} = excluded.${quoted}`;
|
|
10075
|
+
});
|
|
10076
|
+
if (assignments.length === 0) {
|
|
10077
|
+
parts.push(`ON CONFLICT (${conflictSql}) DO NOTHING`);
|
|
10078
|
+
} else {
|
|
10079
|
+
parts.push(`ON CONFLICT (${conflictSql}) DO UPDATE SET ${assignments.join(", ")}`);
|
|
10080
|
+
}
|
|
10081
|
+
}
|
|
10082
|
+
function compileD1Insert(payload) {
|
|
10083
|
+
const table = payload.table_name?.trim();
|
|
10084
|
+
if (!table) {
|
|
10085
|
+
throw new D1SqlCompileError("missing_table", "table_name is required for insert");
|
|
10086
|
+
}
|
|
10087
|
+
const rows = Array.isArray(payload.insert_body) ? payload.insert_body : [payload.insert_body];
|
|
10088
|
+
if (rows.length === 0) {
|
|
10089
|
+
throw new D1SqlCompileError("empty_insert", "insert_body must not be empty");
|
|
10090
|
+
}
|
|
10091
|
+
const columns = [];
|
|
10092
|
+
const seen = /* @__PURE__ */ new Set();
|
|
10093
|
+
for (const row of rows) {
|
|
10094
|
+
for (const key of Object.keys(row ?? {})) {
|
|
10095
|
+
if (seen.has(key)) continue;
|
|
10096
|
+
seen.add(key);
|
|
10097
|
+
columns.push(key);
|
|
10098
|
+
}
|
|
10099
|
+
}
|
|
10100
|
+
if (columns.length === 0) {
|
|
10101
|
+
if (rows.length === 1) {
|
|
10102
|
+
const compiled = compileSingleRowInsert(table, {}, payload);
|
|
10103
|
+
return asSingle(compiled.sql, compiled.params);
|
|
10104
|
+
}
|
|
10105
|
+
throw new D1SqlCompileError(
|
|
10106
|
+
"empty_insert",
|
|
10107
|
+
"Multi-row insert_body cannot be empty objects; use a single {} for DEFAULT VALUES"
|
|
10108
|
+
);
|
|
10109
|
+
}
|
|
10110
|
+
const forceNullForMissing = payload.default_to_null === true;
|
|
10111
|
+
const isSparse = rows.some(
|
|
10112
|
+
(row) => columns.some((column) => !Object.prototype.hasOwnProperty.call(row, column))
|
|
10113
|
+
);
|
|
10114
|
+
if (isSparse && !forceNullForMissing && rows.length > 1) {
|
|
10115
|
+
return asBatch(
|
|
10116
|
+
rows.map((row) => compileSingleRowInsert(table, row, payload))
|
|
10117
|
+
);
|
|
10118
|
+
}
|
|
10119
|
+
if (isSparse && !forceNullForMissing && rows.length === 1) {
|
|
10120
|
+
const compiled = compileSingleRowInsert(table, rows[0], payload);
|
|
10121
|
+
return asSingle(compiled.sql, compiled.params);
|
|
10122
|
+
}
|
|
10123
|
+
const params = [];
|
|
10124
|
+
const valueGroups = rows.map((row) => {
|
|
10125
|
+
const placeholders = columns.map((column) => {
|
|
10126
|
+
const has = Object.prototype.hasOwnProperty.call(row, column);
|
|
10127
|
+
if (!has) {
|
|
10128
|
+
params.push(null);
|
|
10129
|
+
return "?";
|
|
10130
|
+
}
|
|
10131
|
+
params.push(jsonValue(row[column]));
|
|
10132
|
+
return "?";
|
|
10133
|
+
});
|
|
10134
|
+
return `(${placeholders.join(", ")})`;
|
|
10135
|
+
});
|
|
10136
|
+
const parts = [
|
|
10137
|
+
`INSERT INTO ${quoteIdent(table)} (${columns.map(quoteIdent).join(", ")})`,
|
|
10138
|
+
`VALUES ${valueGroups.join(", ")}`
|
|
10139
|
+
];
|
|
10140
|
+
appendOnConflict(parts, params, payload, columns);
|
|
10141
|
+
if (wantsReturning(payload)) {
|
|
10142
|
+
parts.push(`RETURNING ${selectClause(payload.columns)}`);
|
|
10143
|
+
}
|
|
10144
|
+
return asSingle(parts.join(" "), params);
|
|
10145
|
+
}
|
|
10146
|
+
function compileD1Update(payload, options) {
|
|
10147
|
+
const table = payload.table_name?.trim();
|
|
10148
|
+
if (!table) {
|
|
10149
|
+
throw new D1SqlCompileError("missing_table", "table_name is required for update");
|
|
10150
|
+
}
|
|
10151
|
+
const entries = Object.entries(payload.update_body ?? {});
|
|
10152
|
+
if (entries.length === 0) {
|
|
10153
|
+
throw new D1SqlCompileError("empty_update", "update_body must not be empty");
|
|
10154
|
+
}
|
|
10155
|
+
const params = [];
|
|
10156
|
+
const assignments = entries.map(([column, value]) => {
|
|
10157
|
+
params.push(jsonValue(value));
|
|
10158
|
+
return `${quoteIdent(column)} = ?`;
|
|
10159
|
+
});
|
|
10160
|
+
const where = buildWhere(payload.conditions);
|
|
10161
|
+
if (!where.sql) {
|
|
10162
|
+
throw new D1SqlCompileError(
|
|
10163
|
+
"unfiltered_update",
|
|
10164
|
+
"UPDATE requires at least one condition on D1 edge-local"
|
|
10165
|
+
);
|
|
10166
|
+
}
|
|
10167
|
+
if (hasPaginationBounds(payload) || payload.sort_by) {
|
|
10168
|
+
if (!hasPaginationBounds(payload)) {
|
|
10169
|
+
throw new D1SqlCompileError(
|
|
10170
|
+
"order_without_bounds",
|
|
10171
|
+
"UPDATE with sort_by requires limit/offset or page_size/current_page on D1 edge-local"
|
|
10172
|
+
);
|
|
10173
|
+
}
|
|
10174
|
+
const bounded = boundedRowidInClause(
|
|
10175
|
+
table,
|
|
10176
|
+
where.sql,
|
|
10177
|
+
where.params,
|
|
10178
|
+
{
|
|
10179
|
+
...payload,
|
|
10180
|
+
conditions: payload.conditions
|
|
10181
|
+
},
|
|
10182
|
+
options
|
|
10183
|
+
);
|
|
10184
|
+
params.push(...bounded.params);
|
|
10185
|
+
const parts2 = [
|
|
10186
|
+
`UPDATE ${quoteIdent(table)} SET ${assignments.join(", ")}`,
|
|
10187
|
+
`WHERE ${bounded.sql}`
|
|
10188
|
+
];
|
|
10189
|
+
if (wantsReturning(payload)) {
|
|
10190
|
+
parts2.push(`RETURNING ${selectClause(payload.columns)}`);
|
|
10191
|
+
}
|
|
10192
|
+
return asSingle(parts2.join(" "), params);
|
|
10193
|
+
}
|
|
10194
|
+
params.push(...where.params);
|
|
10195
|
+
const parts = [
|
|
10196
|
+
`UPDATE ${quoteIdent(table)} SET ${assignments.join(", ")}`,
|
|
10197
|
+
where.sql
|
|
10198
|
+
];
|
|
10199
|
+
if (wantsReturning(payload)) {
|
|
10200
|
+
parts.push(`RETURNING ${selectClause(payload.columns)}`);
|
|
10201
|
+
}
|
|
10202
|
+
return asSingle(parts.join(" "), params);
|
|
10203
|
+
}
|
|
10204
|
+
function compileD1Delete(payload, options) {
|
|
10205
|
+
const table = payload.table_name?.trim();
|
|
10206
|
+
if (!table) {
|
|
10207
|
+
throw new D1SqlCompileError("missing_table", "table_name is required for delete");
|
|
10208
|
+
}
|
|
10209
|
+
const conditions = [...payload.conditions ?? []];
|
|
10210
|
+
if (payload.resource_id !== void 0 && payload.resource_id !== null) {
|
|
10211
|
+
const hasResourceIdFilter = conditions.some((condition) => {
|
|
10212
|
+
const column = (condition.column ?? condition.eq_column ?? "").trim();
|
|
10213
|
+
return column === "resource_id";
|
|
10214
|
+
});
|
|
10215
|
+
const hasIdFilter = conditions.some((condition) => {
|
|
10216
|
+
const column = (condition.column ?? condition.eq_column ?? "").trim();
|
|
10217
|
+
return column === "id";
|
|
10218
|
+
});
|
|
10219
|
+
if (!hasResourceIdFilter && !hasIdFilter) {
|
|
10220
|
+
conditions.unshift({
|
|
10221
|
+
column: "id",
|
|
10222
|
+
operator: "eq",
|
|
10223
|
+
value: payload.resource_id
|
|
10224
|
+
});
|
|
10225
|
+
}
|
|
10226
|
+
}
|
|
10227
|
+
const where = buildWhere(conditions);
|
|
10228
|
+
if (!where.sql) {
|
|
10229
|
+
throw new D1SqlCompileError(
|
|
10230
|
+
"unfiltered_delete",
|
|
10231
|
+
"DELETE requires at least one condition or resource_id on D1 edge-local"
|
|
10232
|
+
);
|
|
10233
|
+
}
|
|
10234
|
+
if (hasPaginationBounds(payload) || payload.sort_by) {
|
|
10235
|
+
if (!hasPaginationBounds(payload)) {
|
|
10236
|
+
throw new D1SqlCompileError(
|
|
10237
|
+
"order_without_bounds",
|
|
10238
|
+
"DELETE with sort_by requires limit/offset or page_size/current_page on D1 edge-local"
|
|
10239
|
+
);
|
|
10240
|
+
}
|
|
10241
|
+
const bounded = boundedRowidInClause(
|
|
10242
|
+
table,
|
|
10243
|
+
where.sql,
|
|
10244
|
+
where.params,
|
|
10245
|
+
{
|
|
10246
|
+
...payload,
|
|
10247
|
+
conditions
|
|
10248
|
+
},
|
|
10249
|
+
options
|
|
10250
|
+
);
|
|
10251
|
+
const parts2 = [`DELETE FROM ${quoteIdent(table)}`, `WHERE ${bounded.sql}`];
|
|
10252
|
+
if (wantsReturning(payload)) {
|
|
10253
|
+
parts2.push(`RETURNING ${selectClause(payload.columns)}`);
|
|
10254
|
+
}
|
|
10255
|
+
return asSingle(parts2.join(" "), bounded.params);
|
|
10256
|
+
}
|
|
10257
|
+
const parts = [`DELETE FROM ${quoteIdent(table)}`, where.sql];
|
|
10258
|
+
if (wantsReturning(payload)) {
|
|
10259
|
+
parts.push(`RETURNING ${selectClause(payload.columns)}`);
|
|
10260
|
+
}
|
|
10261
|
+
return asSingle(parts.join(" "), where.params);
|
|
10262
|
+
}
|
|
10263
|
+
|
|
10264
|
+
// src/cloudflare/d1/sql-rewrite.ts
|
|
10265
|
+
var PG_CAST_TYPES = "text|uuid|citext|varchar|bpchar|char|integer|int4|int8|bigint|smallint|boolean|bool|jsonb|json|numeric|decimal|real|float|double precision|timestamptz|timestamp|date|bytea";
|
|
10266
|
+
function mapSqlOutsideLiterals(sql, transform) {
|
|
10267
|
+
let out = "";
|
|
10268
|
+
let buffer = "";
|
|
10269
|
+
let inSingle = false;
|
|
10270
|
+
let inDouble = false;
|
|
10271
|
+
let inBacktick = false;
|
|
10272
|
+
let inBracket = false;
|
|
10273
|
+
let inLineComment = false;
|
|
10274
|
+
let inBlockComment = false;
|
|
10275
|
+
const flushCode = () => {
|
|
10276
|
+
if (buffer) {
|
|
10277
|
+
out += transform(buffer);
|
|
10278
|
+
buffer = "";
|
|
10279
|
+
}
|
|
10280
|
+
};
|
|
10281
|
+
for (let i = 0; i < sql.length; i += 1) {
|
|
10282
|
+
const ch = sql[i];
|
|
10283
|
+
const next = sql[i + 1];
|
|
10284
|
+
if (inLineComment) {
|
|
10285
|
+
out += ch;
|
|
10286
|
+
if (ch === "\n" || ch === "\r") inLineComment = false;
|
|
10287
|
+
continue;
|
|
10288
|
+
}
|
|
10289
|
+
if (inBlockComment) {
|
|
10290
|
+
out += ch;
|
|
10291
|
+
if (ch === "*" && next === "/") {
|
|
10292
|
+
out += next;
|
|
10293
|
+
i += 1;
|
|
10294
|
+
inBlockComment = false;
|
|
10295
|
+
}
|
|
10296
|
+
continue;
|
|
10297
|
+
}
|
|
10298
|
+
if (inSingle) {
|
|
10299
|
+
out += ch;
|
|
10300
|
+
if (ch === "'" && next === "'") {
|
|
10301
|
+
out += next;
|
|
10302
|
+
i += 1;
|
|
10303
|
+
continue;
|
|
10304
|
+
}
|
|
10305
|
+
if (ch === "'") inSingle = false;
|
|
10306
|
+
continue;
|
|
10307
|
+
}
|
|
10308
|
+
if (inDouble) {
|
|
10309
|
+
out += ch;
|
|
10310
|
+
if (ch === '"' && next === '"') {
|
|
10311
|
+
out += next;
|
|
10312
|
+
i += 1;
|
|
10313
|
+
continue;
|
|
10314
|
+
}
|
|
10315
|
+
if (ch === '"') inDouble = false;
|
|
10316
|
+
continue;
|
|
10317
|
+
}
|
|
10318
|
+
if (inBacktick) {
|
|
10319
|
+
out += ch;
|
|
10320
|
+
if (ch === "`" && next === "`") {
|
|
10321
|
+
out += next;
|
|
10322
|
+
i += 1;
|
|
10323
|
+
continue;
|
|
10324
|
+
}
|
|
10325
|
+
if (ch === "`") inBacktick = false;
|
|
10326
|
+
continue;
|
|
10327
|
+
}
|
|
10328
|
+
if (inBracket) {
|
|
10329
|
+
out += ch;
|
|
10330
|
+
if (ch === "]") inBracket = false;
|
|
10331
|
+
continue;
|
|
10332
|
+
}
|
|
10333
|
+
if (ch === "-" && next === "-") {
|
|
10334
|
+
flushCode();
|
|
10335
|
+
out += ch;
|
|
10336
|
+
out += next;
|
|
10337
|
+
i += 1;
|
|
10338
|
+
inLineComment = true;
|
|
10339
|
+
continue;
|
|
10340
|
+
}
|
|
10341
|
+
if (ch === "/" && next === "*") {
|
|
10342
|
+
flushCode();
|
|
10343
|
+
out += ch;
|
|
10344
|
+
out += next;
|
|
10345
|
+
i += 1;
|
|
10346
|
+
inBlockComment = true;
|
|
10347
|
+
continue;
|
|
10348
|
+
}
|
|
10349
|
+
if (ch === "'") {
|
|
10350
|
+
flushCode();
|
|
10351
|
+
out += ch;
|
|
10352
|
+
inSingle = true;
|
|
10353
|
+
continue;
|
|
10354
|
+
}
|
|
10355
|
+
if (ch === '"') {
|
|
10356
|
+
flushCode();
|
|
10357
|
+
out += ch;
|
|
10358
|
+
inDouble = true;
|
|
10359
|
+
continue;
|
|
10360
|
+
}
|
|
10361
|
+
if (ch === "`") {
|
|
10362
|
+
flushCode();
|
|
10363
|
+
out += ch;
|
|
10364
|
+
inBacktick = true;
|
|
10365
|
+
continue;
|
|
10366
|
+
}
|
|
10367
|
+
if (ch === "[") {
|
|
10368
|
+
flushCode();
|
|
10369
|
+
out += ch;
|
|
10370
|
+
inBracket = true;
|
|
10371
|
+
continue;
|
|
10372
|
+
}
|
|
10373
|
+
buffer += ch;
|
|
10374
|
+
}
|
|
10375
|
+
flushCode();
|
|
10376
|
+
return out;
|
|
10377
|
+
}
|
|
10378
|
+
function isIdentChar2(ch) {
|
|
10379
|
+
if (!ch) return false;
|
|
10380
|
+
return /[A-Za-z0-9_]/.test(ch);
|
|
10381
|
+
}
|
|
10382
|
+
function collectLimitOffsetKeywords(sql) {
|
|
10383
|
+
const hits = [];
|
|
10384
|
+
let depth = 0;
|
|
10385
|
+
let statement = 0;
|
|
10386
|
+
let inSingle = false;
|
|
10387
|
+
let inDouble = false;
|
|
10388
|
+
let inBacktick = false;
|
|
10389
|
+
let inBracket = false;
|
|
10390
|
+
let inLineComment = false;
|
|
10391
|
+
let inBlockComment = false;
|
|
10392
|
+
for (let i = 0; i < sql.length; i += 1) {
|
|
10393
|
+
const ch = sql[i];
|
|
10394
|
+
const next = sql[i + 1];
|
|
10395
|
+
if (inLineComment) {
|
|
10396
|
+
if (ch === "\n" || ch === "\r") inLineComment = false;
|
|
10397
|
+
continue;
|
|
10398
|
+
}
|
|
10399
|
+
if (inBlockComment) {
|
|
10400
|
+
if (ch === "*" && next === "/") {
|
|
10401
|
+
i += 1;
|
|
10402
|
+
inBlockComment = false;
|
|
10403
|
+
}
|
|
10404
|
+
continue;
|
|
10405
|
+
}
|
|
10406
|
+
if (inSingle) {
|
|
10407
|
+
if (ch === "'" && next === "'") {
|
|
10408
|
+
i += 1;
|
|
10409
|
+
continue;
|
|
10410
|
+
}
|
|
10411
|
+
if (ch === "'") inSingle = false;
|
|
10412
|
+
continue;
|
|
10413
|
+
}
|
|
10414
|
+
if (inDouble) {
|
|
10415
|
+
if (ch === '"' && next === '"') {
|
|
10416
|
+
i += 1;
|
|
10417
|
+
continue;
|
|
10418
|
+
}
|
|
10419
|
+
if (ch === '"') inDouble = false;
|
|
10420
|
+
continue;
|
|
10421
|
+
}
|
|
10422
|
+
if (inBacktick) {
|
|
10423
|
+
if (ch === "`" && next === "`") {
|
|
10424
|
+
i += 1;
|
|
10425
|
+
continue;
|
|
10426
|
+
}
|
|
10427
|
+
if (ch === "`") inBacktick = false;
|
|
10428
|
+
continue;
|
|
10429
|
+
}
|
|
10430
|
+
if (inBracket) {
|
|
10431
|
+
if (ch === "]") inBracket = false;
|
|
10432
|
+
continue;
|
|
10433
|
+
}
|
|
10434
|
+
if (ch === "-" && next === "-") {
|
|
10435
|
+
inLineComment = true;
|
|
10436
|
+
i += 1;
|
|
10437
|
+
continue;
|
|
10438
|
+
}
|
|
10439
|
+
if (ch === "/" && next === "*") {
|
|
10440
|
+
inBlockComment = true;
|
|
10441
|
+
i += 1;
|
|
10442
|
+
continue;
|
|
10443
|
+
}
|
|
10444
|
+
if (ch === "'") {
|
|
10445
|
+
inSingle = true;
|
|
10446
|
+
continue;
|
|
10447
|
+
}
|
|
10448
|
+
if (ch === '"') {
|
|
10449
|
+
inDouble = true;
|
|
10450
|
+
continue;
|
|
10451
|
+
}
|
|
10452
|
+
if (ch === "`") {
|
|
10453
|
+
inBacktick = true;
|
|
10454
|
+
continue;
|
|
10455
|
+
}
|
|
10456
|
+
if (ch === "[") {
|
|
10457
|
+
inBracket = true;
|
|
10458
|
+
continue;
|
|
10459
|
+
}
|
|
10460
|
+
if (ch === "(") {
|
|
10461
|
+
depth += 1;
|
|
10462
|
+
continue;
|
|
10463
|
+
}
|
|
10464
|
+
if (ch === ")") {
|
|
10465
|
+
depth = Math.max(0, depth - 1);
|
|
10466
|
+
continue;
|
|
10467
|
+
}
|
|
10468
|
+
if (ch === ";" && depth === 0) {
|
|
10469
|
+
statement += 1;
|
|
10470
|
+
continue;
|
|
10471
|
+
}
|
|
10472
|
+
if (!isIdentChar2(ch) || isIdentChar2(sql[i - 1])) {
|
|
10473
|
+
continue;
|
|
10474
|
+
}
|
|
10475
|
+
const rest = sql.slice(i);
|
|
10476
|
+
if (/^LIMIT\b/i.test(rest)) {
|
|
10477
|
+
hits.push({ kind: "limit", start: i, depth, statement });
|
|
10478
|
+
i += 4;
|
|
10479
|
+
continue;
|
|
10480
|
+
}
|
|
10481
|
+
if (/^OFFSET\b/i.test(rest)) {
|
|
10482
|
+
hits.push({ kind: "offset", start: i, depth, statement });
|
|
10483
|
+
i += 5;
|
|
10484
|
+
}
|
|
10485
|
+
}
|
|
10486
|
+
return hits;
|
|
10487
|
+
}
|
|
10488
|
+
function injectLimitBeforeBareOffsets(sql) {
|
|
10489
|
+
const hits = collectLimitOffsetKeywords(sql);
|
|
10490
|
+
if (hits.length === 0) return sql;
|
|
10491
|
+
const injectAt = [];
|
|
10492
|
+
for (const hit of hits) {
|
|
10493
|
+
if (hit.kind !== "offset") continue;
|
|
10494
|
+
let hasLimit = false;
|
|
10495
|
+
for (let i = hits.length - 1; i >= 0; i -= 1) {
|
|
10496
|
+
const prev = hits[i];
|
|
10497
|
+
if (prev.start >= hit.start) continue;
|
|
10498
|
+
if (prev.statement !== hit.statement) continue;
|
|
10499
|
+
if (prev.depth !== hit.depth) continue;
|
|
10500
|
+
if (prev.kind === "limit") {
|
|
10501
|
+
hasLimit = true;
|
|
10502
|
+
break;
|
|
10503
|
+
}
|
|
10504
|
+
if (prev.kind === "offset") {
|
|
10505
|
+
break;
|
|
10506
|
+
}
|
|
10507
|
+
}
|
|
10508
|
+
if (!hasLimit) {
|
|
10509
|
+
injectAt.push(hit.start);
|
|
10510
|
+
}
|
|
10511
|
+
}
|
|
10512
|
+
if (injectAt.length === 0) return sql;
|
|
10513
|
+
let out = sql;
|
|
10514
|
+
for (let i = injectAt.length - 1; i >= 0; i -= 1) {
|
|
10515
|
+
const at = injectAt[i];
|
|
10516
|
+
out = `${out.slice(0, at)}LIMIT -1 ${out.slice(at)}`;
|
|
10517
|
+
}
|
|
10518
|
+
return out;
|
|
10519
|
+
}
|
|
10520
|
+
function rewritePostgresSqlForSqlite(sql) {
|
|
10521
|
+
const castPattern = new RegExp(`::(?:${PG_CAST_TYPES})\\b`, "gi");
|
|
10522
|
+
const withoutCastsAndIlike = mapSqlOutsideLiterals(sql, (chunk) => {
|
|
10523
|
+
let rewritten = chunk.replace(castPattern, "");
|
|
10524
|
+
rewritten = rewritten.replace(/\bILIKE\b/gi, "LIKE");
|
|
10525
|
+
return rewritten;
|
|
10526
|
+
});
|
|
10527
|
+
return injectLimitBeforeBareOffsets(withoutCastsAndIlike);
|
|
10528
|
+
}
|
|
10529
|
+
|
|
10530
|
+
// src/cloudflare/d1/transport.ts
|
|
10531
|
+
function hasPaginationBounds2(payload) {
|
|
10532
|
+
return payload.limit !== void 0 || payload.offset !== void 0 || payload.page_size !== void 0 || payload.current_page !== void 0;
|
|
10533
|
+
}
|
|
10534
|
+
function normalizeSqliteCollation(name) {
|
|
10535
|
+
const raw = String(name ?? "").trim().replace(/^["'`[]|["'`\]]$/g, "");
|
|
10536
|
+
if (!raw) return "BINARY";
|
|
10537
|
+
return raw.toUpperCase();
|
|
10538
|
+
}
|
|
10539
|
+
function findCreateTableColumnListOpen(createSql) {
|
|
10540
|
+
const m = /\bCREATE\s+(?:(?:TEMP|TEMPORARY|VIRTUAL)\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?/i.exec(
|
|
10541
|
+
createSql
|
|
10542
|
+
);
|
|
10543
|
+
if (!m) return -1;
|
|
10544
|
+
let i = m.index + m[0].length;
|
|
10545
|
+
let inSingle = false;
|
|
10546
|
+
let inDouble = false;
|
|
10547
|
+
let inBacktick = false;
|
|
10548
|
+
let inBracket = false;
|
|
10549
|
+
while (i < createSql.length) {
|
|
10550
|
+
const ch = createSql[i];
|
|
10551
|
+
if (inSingle) {
|
|
10552
|
+
if (ch === "'" && createSql[i + 1] === "'") {
|
|
10553
|
+
i += 2;
|
|
10554
|
+
continue;
|
|
10555
|
+
}
|
|
10556
|
+
if (ch === "'") inSingle = false;
|
|
10557
|
+
i++;
|
|
10558
|
+
continue;
|
|
10559
|
+
}
|
|
10560
|
+
if (inDouble) {
|
|
10561
|
+
if (ch === '"') inDouble = false;
|
|
10562
|
+
i++;
|
|
10563
|
+
continue;
|
|
10564
|
+
}
|
|
10565
|
+
if (inBacktick) {
|
|
10566
|
+
if (ch === "`") inBacktick = false;
|
|
10567
|
+
i++;
|
|
10568
|
+
continue;
|
|
10569
|
+
}
|
|
10570
|
+
if (inBracket) {
|
|
10571
|
+
if (ch === "]") inBracket = false;
|
|
10572
|
+
i++;
|
|
10573
|
+
continue;
|
|
10574
|
+
}
|
|
10575
|
+
if (ch === "'") {
|
|
10576
|
+
inSingle = true;
|
|
10577
|
+
i++;
|
|
10578
|
+
continue;
|
|
10579
|
+
}
|
|
10580
|
+
if (ch === '"') {
|
|
10581
|
+
inDouble = true;
|
|
10582
|
+
i++;
|
|
10583
|
+
continue;
|
|
10584
|
+
}
|
|
10585
|
+
if (ch === "`") {
|
|
10586
|
+
inBacktick = true;
|
|
10587
|
+
i++;
|
|
10588
|
+
continue;
|
|
10589
|
+
}
|
|
10590
|
+
if (ch === "[") {
|
|
10591
|
+
inBracket = true;
|
|
10592
|
+
i++;
|
|
10593
|
+
continue;
|
|
10594
|
+
}
|
|
10595
|
+
if (ch === "(") return i;
|
|
10596
|
+
i++;
|
|
10597
|
+
}
|
|
10598
|
+
return -1;
|
|
10599
|
+
}
|
|
10600
|
+
function parseColumnCollationFromCreateSql(createSql, columnName) {
|
|
10601
|
+
if (!createSql || !columnName) return null;
|
|
10602
|
+
const listOpen = findCreateTableColumnListOpen(createSql);
|
|
10603
|
+
if (listOpen < 0) return null;
|
|
10604
|
+
const listStart = listOpen + 1;
|
|
10605
|
+
const escaped = columnName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
10606
|
+
const nameRe = new RegExp(
|
|
10607
|
+
`(?:^|[^\\w])(?:"${escaped}"|\`${escaped}\`|\\[${escaped}\\]|${escaped})\\s+`,
|
|
10608
|
+
"i"
|
|
10609
|
+
);
|
|
10610
|
+
const listSlice = createSql.slice(listStart);
|
|
10611
|
+
let nameMatchAbs = -1;
|
|
10612
|
+
let nameMatchLen = 0;
|
|
10613
|
+
{
|
|
10614
|
+
let i2 = 0;
|
|
10615
|
+
let depth2 = 1;
|
|
10616
|
+
let inSingle2 = false;
|
|
10617
|
+
let inDouble2 = false;
|
|
10618
|
+
let inBacktick2 = false;
|
|
10619
|
+
let inBracket2 = false;
|
|
10620
|
+
let segmentStart = 0;
|
|
10621
|
+
const trySegment = (from, to) => {
|
|
10622
|
+
if (nameMatchAbs >= 0) return;
|
|
10623
|
+
const segment = listSlice.slice(from, to);
|
|
10624
|
+
const m = nameRe.exec(segment);
|
|
10625
|
+
if (!m) return;
|
|
10626
|
+
const leading = segment.slice(0, m.index).trim();
|
|
10627
|
+
if (leading.length > 0) return;
|
|
10628
|
+
nameMatchAbs = listStart + from + m.index;
|
|
10629
|
+
nameMatchLen = m[0].length;
|
|
10630
|
+
};
|
|
10631
|
+
while (i2 < listSlice.length && depth2 > 0) {
|
|
10632
|
+
const ch = listSlice[i2];
|
|
10633
|
+
if (inSingle2) {
|
|
10634
|
+
if (ch === "'" && listSlice[i2 + 1] === "'") {
|
|
10635
|
+
i2 += 2;
|
|
10636
|
+
continue;
|
|
10637
|
+
}
|
|
10638
|
+
if (ch === "'") inSingle2 = false;
|
|
10639
|
+
i2++;
|
|
10640
|
+
continue;
|
|
10641
|
+
}
|
|
10642
|
+
if (inDouble2) {
|
|
10643
|
+
if (ch === '"') inDouble2 = false;
|
|
10644
|
+
i2++;
|
|
10645
|
+
continue;
|
|
10646
|
+
}
|
|
10647
|
+
if (inBacktick2) {
|
|
10648
|
+
if (ch === "`") inBacktick2 = false;
|
|
10649
|
+
i2++;
|
|
10650
|
+
continue;
|
|
10651
|
+
}
|
|
10652
|
+
if (inBracket2) {
|
|
10653
|
+
if (ch === "]") inBracket2 = false;
|
|
10654
|
+
i2++;
|
|
10655
|
+
continue;
|
|
10656
|
+
}
|
|
10657
|
+
if (ch === "'") {
|
|
10658
|
+
inSingle2 = true;
|
|
10659
|
+
i2++;
|
|
10660
|
+
continue;
|
|
10661
|
+
}
|
|
10662
|
+
if (ch === '"') {
|
|
10663
|
+
inDouble2 = true;
|
|
10664
|
+
i2++;
|
|
10665
|
+
continue;
|
|
10666
|
+
}
|
|
10667
|
+
if (ch === "`") {
|
|
10668
|
+
inBacktick2 = true;
|
|
10669
|
+
i2++;
|
|
10670
|
+
continue;
|
|
10671
|
+
}
|
|
10672
|
+
if (ch === "[") {
|
|
10673
|
+
inBracket2 = true;
|
|
10674
|
+
i2++;
|
|
10675
|
+
continue;
|
|
10676
|
+
}
|
|
10677
|
+
if (ch === "(") {
|
|
10678
|
+
depth2++;
|
|
10679
|
+
i2++;
|
|
10680
|
+
continue;
|
|
10681
|
+
}
|
|
10682
|
+
if (ch === ")") {
|
|
10683
|
+
depth2--;
|
|
10684
|
+
if (depth2 === 0) {
|
|
10685
|
+
trySegment(segmentStart, i2);
|
|
10686
|
+
break;
|
|
10687
|
+
}
|
|
10688
|
+
i2++;
|
|
10689
|
+
continue;
|
|
10690
|
+
}
|
|
10691
|
+
if (ch === "," && depth2 === 1) {
|
|
10692
|
+
trySegment(segmentStart, i2);
|
|
10693
|
+
segmentStart = i2 + 1;
|
|
10694
|
+
i2++;
|
|
10695
|
+
continue;
|
|
10696
|
+
}
|
|
10697
|
+
i2++;
|
|
10698
|
+
}
|
|
10699
|
+
}
|
|
10700
|
+
if (nameMatchAbs < 0 || nameMatchLen <= 0) return null;
|
|
10701
|
+
const start = nameMatchAbs + nameMatchLen;
|
|
10702
|
+
let i = start;
|
|
10703
|
+
let depth = 0;
|
|
10704
|
+
let inSingle = false;
|
|
10705
|
+
let inDouble = false;
|
|
10706
|
+
let inBacktick = false;
|
|
10707
|
+
let inBracket = false;
|
|
10708
|
+
while (i < createSql.length) {
|
|
10709
|
+
const ch = createSql[i];
|
|
10710
|
+
if (inSingle) {
|
|
10711
|
+
if (ch === "'" && createSql[i + 1] === "'") {
|
|
10712
|
+
i += 2;
|
|
10713
|
+
continue;
|
|
10714
|
+
}
|
|
10715
|
+
if (ch === "'") inSingle = false;
|
|
10716
|
+
i++;
|
|
10717
|
+
continue;
|
|
10718
|
+
}
|
|
10719
|
+
if (inDouble) {
|
|
10720
|
+
if (ch === '"') inDouble = false;
|
|
10721
|
+
i++;
|
|
10722
|
+
continue;
|
|
10723
|
+
}
|
|
10724
|
+
if (inBacktick) {
|
|
10725
|
+
if (ch === "`") inBacktick = false;
|
|
10726
|
+
i++;
|
|
10727
|
+
continue;
|
|
10728
|
+
}
|
|
10729
|
+
if (inBracket) {
|
|
10730
|
+
if (ch === "]") inBracket = false;
|
|
10731
|
+
i++;
|
|
10732
|
+
continue;
|
|
10733
|
+
}
|
|
10734
|
+
if (ch === "'") {
|
|
10735
|
+
inSingle = true;
|
|
10736
|
+
i++;
|
|
10737
|
+
continue;
|
|
10738
|
+
}
|
|
10739
|
+
if (ch === '"') {
|
|
10740
|
+
inDouble = true;
|
|
10741
|
+
i++;
|
|
10742
|
+
continue;
|
|
10743
|
+
}
|
|
10744
|
+
if (ch === "`") {
|
|
10745
|
+
inBacktick = true;
|
|
10746
|
+
i++;
|
|
10747
|
+
continue;
|
|
10748
|
+
}
|
|
10749
|
+
if (ch === "[") {
|
|
10750
|
+
inBracket = true;
|
|
10751
|
+
i++;
|
|
10752
|
+
continue;
|
|
10753
|
+
}
|
|
10754
|
+
if (ch === "(") {
|
|
10755
|
+
depth++;
|
|
10756
|
+
i++;
|
|
10757
|
+
continue;
|
|
10758
|
+
}
|
|
10759
|
+
if (ch === ")") {
|
|
10760
|
+
if (depth === 0) {
|
|
10761
|
+
break;
|
|
10762
|
+
}
|
|
10763
|
+
depth--;
|
|
10764
|
+
i++;
|
|
10765
|
+
continue;
|
|
10766
|
+
}
|
|
10767
|
+
if (ch === "," && depth === 0) {
|
|
10768
|
+
break;
|
|
10769
|
+
}
|
|
10770
|
+
i++;
|
|
10771
|
+
}
|
|
10772
|
+
const colDef = createSql.slice(start, i);
|
|
10773
|
+
const collRe = /\bCOLLATE\s+("([^"]+)"|'([^']+)'|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][\w$]*))/i;
|
|
10774
|
+
const match = collRe.exec(colDef);
|
|
10775
|
+
if (!match) return null;
|
|
10776
|
+
return match[2] ?? match[3] ?? match[4] ?? match[5] ?? match[6] ?? match[1] ?? null;
|
|
10777
|
+
}
|
|
10778
|
+
async function indexCollationMatchesColumn(d1, table, tableSafe, indexSafe, columnName, session) {
|
|
10779
|
+
const xinfo = await executeD1Query(d1, {
|
|
10780
|
+
query: `PRAGMA index_xinfo("${indexSafe}")`,
|
|
10781
|
+
params: [],
|
|
10782
|
+
...session
|
|
10783
|
+
});
|
|
10784
|
+
if (!xinfo.ok) {
|
|
10785
|
+
return false;
|
|
10786
|
+
}
|
|
10787
|
+
const xRows = xinfo.rows ?? [];
|
|
10788
|
+
const keyRows = xRows.filter((row) => {
|
|
10789
|
+
const isKey = row.key === 1 || row.key === true || Number(row.key) === 1;
|
|
10790
|
+
if (!isKey) return false;
|
|
10791
|
+
return typeof row.name === "string" && row.name === columnName;
|
|
10792
|
+
});
|
|
10793
|
+
if (keyRows.length === 0) {
|
|
10794
|
+
const byName = xRows.find(
|
|
10795
|
+
(row) => typeof row.name === "string" && row.name === columnName
|
|
10796
|
+
);
|
|
10797
|
+
if (!byName) return false;
|
|
10798
|
+
keyRows.push(byName);
|
|
10799
|
+
}
|
|
10800
|
+
const indexColl = normalizeSqliteCollation(keyRows[0]?.coll);
|
|
10801
|
+
const master = await executeD1Query(d1, {
|
|
10802
|
+
query: `SELECT sql AS create_sql FROM sqlite_master WHERE type = 'table' AND name = ?`,
|
|
10803
|
+
params: [table],
|
|
10804
|
+
...session
|
|
10805
|
+
});
|
|
10806
|
+
let createSql = "";
|
|
10807
|
+
if (master.ok && Array.isArray(master.rows) && master.rows.length > 0) {
|
|
10808
|
+
createSql = String(
|
|
10809
|
+
master.rows[0]?.create_sql ?? ""
|
|
10810
|
+
);
|
|
10811
|
+
}
|
|
10812
|
+
const columnCollRaw = parseColumnCollationFromCreateSql(createSql, columnName);
|
|
10813
|
+
const columnColl = normalizeSqliteCollation(columnCollRaw);
|
|
10814
|
+
return indexColl === columnColl;
|
|
10815
|
+
}
|
|
10816
|
+
async function resolveD1BoundedIdentityColumn(d1, tableName, session) {
|
|
10817
|
+
const table = tableName.trim();
|
|
10818
|
+
if (!table) {
|
|
10819
|
+
throw new D1SqlCompileError("missing_table", "table_name is required for bounded mutation");
|
|
10820
|
+
}
|
|
10821
|
+
const safe = table.replace(/"/g, '""');
|
|
10822
|
+
const info = await executeD1Query(d1, {
|
|
10823
|
+
query: `PRAGMA table_info("${safe}")`,
|
|
10824
|
+
params: [],
|
|
10825
|
+
...session
|
|
10826
|
+
});
|
|
10827
|
+
if (!info.ok) {
|
|
10828
|
+
throw new D1SqlCompileError(
|
|
10829
|
+
"bounded_mutation_no_unique_identity",
|
|
10830
|
+
`Unable to introspect table "${table}" for bounded mutation identity: ${info.message}`
|
|
10831
|
+
);
|
|
10832
|
+
}
|
|
10833
|
+
const cols = info.rows.filter(
|
|
10834
|
+
(row) => typeof row?.name === "string" && row.name.length > 0
|
|
10835
|
+
);
|
|
10836
|
+
const colByName = new Map(cols.map((col) => [col.name, col]));
|
|
10837
|
+
const isNotNullColumn = (name) => {
|
|
10838
|
+
const col = colByName.get(name);
|
|
10839
|
+
if (!col) return false;
|
|
10840
|
+
return col.notnull === 1 || col.notnull === true || Number(col.notnull) === 1;
|
|
10841
|
+
};
|
|
10842
|
+
const isIntegerPrimaryKeyType = (col) => {
|
|
10843
|
+
if (typeof col.pk !== "number" || col.pk <= 0) return false;
|
|
10844
|
+
const declared = String(col.type ?? "").trim().toUpperCase();
|
|
10845
|
+
return declared === "INTEGER";
|
|
10846
|
+
};
|
|
10847
|
+
const loadIndexList = async () => {
|
|
10848
|
+
const indexList = await executeD1Query(d1, {
|
|
10849
|
+
query: `PRAGMA index_list("${safe}")`,
|
|
10850
|
+
params: [],
|
|
10851
|
+
...session
|
|
10852
|
+
});
|
|
10853
|
+
if (!indexList.ok) return null;
|
|
10854
|
+
return indexList.rows;
|
|
10855
|
+
};
|
|
10856
|
+
const isDescendingIntegerPrimaryKeyException = async (colName, indexes) => {
|
|
10857
|
+
if (indexes) {
|
|
10858
|
+
const hasPkOrigin = indexes.some(
|
|
10859
|
+
(index) => String(index.origin ?? "").toLowerCase() === "pk"
|
|
10860
|
+
);
|
|
10861
|
+
if (hasPkOrigin) return true;
|
|
10862
|
+
const originReported = indexes.some(
|
|
10863
|
+
(index) => index.origin !== void 0 && index.origin !== null && String(index.origin).length > 0
|
|
10864
|
+
);
|
|
10865
|
+
if (indexes.length === 0 || originReported) {
|
|
10866
|
+
return false;
|
|
10867
|
+
}
|
|
10868
|
+
}
|
|
10869
|
+
const master = await executeD1Query(d1, {
|
|
10870
|
+
query: `SELECT sql AS create_sql FROM sqlite_master WHERE type = 'table' AND name = ?`,
|
|
10871
|
+
params: [table],
|
|
10872
|
+
...session
|
|
10873
|
+
});
|
|
10874
|
+
if (!master.ok || !Array.isArray(master.rows) || master.rows.length === 0) {
|
|
10875
|
+
return false;
|
|
10876
|
+
}
|
|
10877
|
+
const createSql = String(
|
|
10878
|
+
master.rows[0]?.create_sql ?? ""
|
|
10879
|
+
);
|
|
10880
|
+
if (!createSql) return false;
|
|
10881
|
+
const escaped = colName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
10882
|
+
const inlineDesc = new RegExp(
|
|
10883
|
+
`(?:^|[^\\w])(?:"${escaped}"|${escaped})\\s+INTEGER\\s+PRIMARY\\s+KEY\\s+DESC\\b`,
|
|
10884
|
+
"i"
|
|
10885
|
+
);
|
|
10886
|
+
const tableDesc = new RegExp(
|
|
10887
|
+
`PRIMARY\\s+KEY\\s*\\(\\s*(?:"${escaped}"|${escaped})\\s+DESC\\b`,
|
|
10888
|
+
"i"
|
|
10889
|
+
);
|
|
10890
|
+
return inlineDesc.test(createSql) || tableDesc.test(createSql);
|
|
10891
|
+
};
|
|
10892
|
+
const pkCols = cols.filter((row) => typeof row.pk === "number" && row.pk > 0).sort((a, b) => (a.pk ?? 0) - (b.pk ?? 0));
|
|
10893
|
+
let indexRows;
|
|
10894
|
+
if (pkCols.length === 1 && pkCols[0]?.name) {
|
|
10895
|
+
if (isIntegerPrimaryKeyType(pkCols[0])) {
|
|
10896
|
+
indexRows = await loadIndexList();
|
|
10897
|
+
const isDescException = await isDescendingIntegerPrimaryKeyException(
|
|
10898
|
+
pkCols[0].name,
|
|
10899
|
+
indexRows
|
|
10900
|
+
);
|
|
10901
|
+
if (!isDescException) {
|
|
10902
|
+
return pkCols[0].name;
|
|
10903
|
+
}
|
|
10904
|
+
} else if (isNotNullColumn(pkCols[0].name)) {
|
|
10905
|
+
indexRows = await loadIndexList();
|
|
10906
|
+
const pkIndex = (indexRows ?? []).find(
|
|
10907
|
+
(index) => String(index.origin ?? "").toLowerCase() === "pk"
|
|
10908
|
+
);
|
|
10909
|
+
if (pkIndex && typeof pkIndex.name === "string" && pkIndex.name) {
|
|
10910
|
+
const indexSafe = pkIndex.name.replace(/"/g, '""');
|
|
10911
|
+
const collMatch = await indexCollationMatchesColumn(
|
|
10912
|
+
d1,
|
|
10913
|
+
table,
|
|
10914
|
+
safe,
|
|
10915
|
+
indexSafe,
|
|
10916
|
+
pkCols[0].name,
|
|
10917
|
+
session
|
|
10918
|
+
);
|
|
10919
|
+
if (collMatch) {
|
|
10920
|
+
return pkCols[0].name;
|
|
10921
|
+
}
|
|
10922
|
+
}
|
|
10923
|
+
}
|
|
10924
|
+
}
|
|
10925
|
+
if (indexRows === void 0) {
|
|
10926
|
+
indexRows = await loadIndexList();
|
|
10927
|
+
}
|
|
10928
|
+
if (indexRows) {
|
|
10929
|
+
for (const index of indexRows) {
|
|
10930
|
+
const unique = index.unique === 1 || index.unique === true || Number(index.unique) === 1;
|
|
10931
|
+
if (!unique || typeof index.name !== "string" || !index.name) continue;
|
|
10932
|
+
const isPartial = index.partial === 1 || index.partial === true || Number(index.partial) === 1;
|
|
10933
|
+
if (isPartial) {
|
|
10934
|
+
continue;
|
|
10935
|
+
}
|
|
10936
|
+
const indexSafe = index.name.replace(/"/g, '""');
|
|
10937
|
+
const indexInfo = await executeD1Query(d1, {
|
|
10938
|
+
query: `PRAGMA index_info("${indexSafe}")`,
|
|
10939
|
+
params: [],
|
|
10940
|
+
...session
|
|
10941
|
+
});
|
|
10942
|
+
if (!indexInfo.ok) continue;
|
|
10943
|
+
const rawIndexCols = indexInfo.rows ?? [];
|
|
10944
|
+
const hasExpressionTerm = rawIndexCols.some((row) => {
|
|
10945
|
+
const nameOk = typeof row?.name === "string" && row.name.length > 0;
|
|
10946
|
+
if (!nameOk) return true;
|
|
10947
|
+
if (typeof row.cid === "number" && row.cid < 0) return true;
|
|
10948
|
+
return false;
|
|
10949
|
+
});
|
|
10950
|
+
if (hasExpressionTerm || rawIndexCols.length === 0) {
|
|
10951
|
+
continue;
|
|
10952
|
+
}
|
|
10953
|
+
const indexCols = rawIndexCols.filter(
|
|
10954
|
+
(row) => typeof row?.name === "string" && row.name.length > 0
|
|
10955
|
+
);
|
|
10956
|
+
if (indexCols.length === 1 && indexCols[0]?.name) {
|
|
10957
|
+
const identity = indexCols[0].name;
|
|
10958
|
+
if (!isNotNullColumn(identity)) {
|
|
10959
|
+
continue;
|
|
10960
|
+
}
|
|
10961
|
+
const collMatch = await indexCollationMatchesColumn(
|
|
10962
|
+
d1,
|
|
10963
|
+
table,
|
|
10964
|
+
safe,
|
|
10965
|
+
indexSafe,
|
|
10966
|
+
identity,
|
|
10967
|
+
session
|
|
10968
|
+
);
|
|
10969
|
+
if (!collMatch) {
|
|
10970
|
+
continue;
|
|
10971
|
+
}
|
|
10972
|
+
return identity;
|
|
10973
|
+
}
|
|
10974
|
+
}
|
|
10975
|
+
}
|
|
10976
|
+
throw new D1SqlCompileError(
|
|
10977
|
+
"bounded_mutation_no_unique_identity",
|
|
10978
|
+
`Bounded update/delete on "${table}" requires a proven single-column PRIMARY KEY or UNIQUE index`
|
|
10979
|
+
);
|
|
10980
|
+
}
|
|
10981
|
+
async function compileOptionsForBoundedMutation(d1, payload, session) {
|
|
10982
|
+
if (!hasPaginationBounds2(payload) && !payload.sort_by) {
|
|
10983
|
+
return void 0;
|
|
10984
|
+
}
|
|
10985
|
+
if (!hasPaginationBounds2(payload)) {
|
|
10986
|
+
return void 0;
|
|
10987
|
+
}
|
|
10988
|
+
const identityColumn = await resolveD1BoundedIdentityColumn(
|
|
10989
|
+
d1,
|
|
10990
|
+
payload.table_name ?? "",
|
|
10991
|
+
session
|
|
10992
|
+
);
|
|
10993
|
+
return { identityColumn };
|
|
10994
|
+
}
|
|
10995
|
+
function headerValue2(options, name) {
|
|
10996
|
+
const headers = options?.headers;
|
|
10997
|
+
if (!headers) return void 0;
|
|
10998
|
+
const lower = name.toLowerCase();
|
|
10999
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
11000
|
+
if (key.toLowerCase() === lower && value?.trim()) {
|
|
11001
|
+
return value.trim();
|
|
11002
|
+
}
|
|
11003
|
+
}
|
|
11004
|
+
return void 0;
|
|
11005
|
+
}
|
|
11006
|
+
function sessionFromOptions(options, defaults) {
|
|
11007
|
+
return {
|
|
11008
|
+
bookmark: headerValue2(options, "x-athena-d1-bookmark") ?? null,
|
|
11009
|
+
sessionMode: headerValue2(options, "x-athena-d1-session-mode") ?? defaults.defaultSessionMode ?? null
|
|
11010
|
+
};
|
|
11011
|
+
}
|
|
11012
|
+
function resolveStripNulls(payloadStrip, callOptions, defaultValue = true) {
|
|
11013
|
+
if (typeof payloadStrip === "boolean") return payloadStrip;
|
|
11014
|
+
if (typeof callOptions?.stripNulls === "boolean") return callOptions.stripNulls;
|
|
11015
|
+
return defaultValue;
|
|
11016
|
+
}
|
|
11017
|
+
function stripNullPropertiesFromRows(rows) {
|
|
11018
|
+
return rows.map((row) => {
|
|
11019
|
+
if (row == null || typeof row !== "object" || Array.isArray(row)) {
|
|
11020
|
+
return row;
|
|
11021
|
+
}
|
|
11022
|
+
const out = {};
|
|
11023
|
+
for (const [key, value] of Object.entries(row)) {
|
|
11024
|
+
if (value !== null) {
|
|
11025
|
+
out[key] = value;
|
|
11026
|
+
}
|
|
11027
|
+
}
|
|
11028
|
+
return out;
|
|
11029
|
+
});
|
|
11030
|
+
}
|
|
11031
|
+
function maybeStripNullRows(rows, strip) {
|
|
11032
|
+
return strip ? stripNullPropertiesFromRows(rows) : rows;
|
|
11033
|
+
}
|
|
11034
|
+
function successResponse(data, count, raw, bookmark) {
|
|
11035
|
+
const response = {
|
|
11036
|
+
ok: true,
|
|
11037
|
+
status: 200,
|
|
11038
|
+
statusText: "OK",
|
|
11039
|
+
data,
|
|
11040
|
+
count: count ?? null,
|
|
11041
|
+
error: void 0,
|
|
11042
|
+
errorDetails: null,
|
|
11043
|
+
raw
|
|
11044
|
+
};
|
|
11045
|
+
if (bookmark) {
|
|
11046
|
+
if (raw && typeof raw === "object" && !Array.isArray(raw)) {
|
|
11047
|
+
const rawRecord = raw;
|
|
11048
|
+
rawRecord.bookmark = bookmark;
|
|
11049
|
+
}
|
|
11050
|
+
}
|
|
11051
|
+
return response;
|
|
11052
|
+
}
|
|
11053
|
+
function errorResponse(status, code, message, endpoint, method, hint) {
|
|
11054
|
+
const error = new AthenaGatewayError({
|
|
11055
|
+
code,
|
|
11056
|
+
message,
|
|
11057
|
+
status,
|
|
11058
|
+
endpoint,
|
|
11059
|
+
method,
|
|
11060
|
+
hint
|
|
11061
|
+
});
|
|
11062
|
+
return {
|
|
11063
|
+
ok: false,
|
|
11064
|
+
status,
|
|
11065
|
+
statusText: null,
|
|
11066
|
+
data: null,
|
|
11067
|
+
error: error.message,
|
|
11068
|
+
errorDetails: error.toDetails(),
|
|
11069
|
+
raw: { error: message, code }
|
|
11070
|
+
};
|
|
11071
|
+
}
|
|
11072
|
+
function compileErrorResponse(error, endpoint, method) {
|
|
11073
|
+
if (error instanceof D1SqlCompileError) {
|
|
11074
|
+
return errorResponse(
|
|
11075
|
+
400,
|
|
11076
|
+
"HTTP_ERROR",
|
|
11077
|
+
error.message,
|
|
11078
|
+
endpoint,
|
|
11079
|
+
method,
|
|
11080
|
+
`D1 SQL compile failed (${error.code})`
|
|
11081
|
+
);
|
|
11082
|
+
}
|
|
11083
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
11084
|
+
return errorResponse(500, "UNKNOWN_ERROR", message, endpoint, method);
|
|
11085
|
+
}
|
|
11086
|
+
function createCloudflareD1GatewayTransport(options) {
|
|
11087
|
+
const { d1 } = options;
|
|
11088
|
+
async function runCompiled(compiled, callOptions, endpoint, method, mapResult, stripNulls = true) {
|
|
11089
|
+
try {
|
|
11090
|
+
const session = sessionFromOptions(callOptions, options);
|
|
11091
|
+
if (compiled.statements && compiled.statements.length > 1) {
|
|
11092
|
+
const batch = await executeD1Batch(d1, {
|
|
11093
|
+
statements: compiled.statements.map((statement) => ({
|
|
11094
|
+
query: statement.sql,
|
|
11095
|
+
params: statement.params
|
|
11096
|
+
})),
|
|
11097
|
+
...session
|
|
11098
|
+
});
|
|
11099
|
+
if (!batch.ok) {
|
|
11100
|
+
return errorResponse(400, "HTTP_ERROR", batch.message, endpoint, method);
|
|
11101
|
+
}
|
|
11102
|
+
const rows2 = maybeStripNullRows(
|
|
11103
|
+
batch.results.flatMap(
|
|
11104
|
+
(item) => Array.isArray(item.results) ? item.results : []
|
|
11105
|
+
),
|
|
11106
|
+
stripNulls
|
|
11107
|
+
);
|
|
11108
|
+
const changes = batch.results.reduce((sum2, item) => {
|
|
11109
|
+
const meta = item?.meta;
|
|
11110
|
+
const n = meta && typeof meta === "object" && typeof meta.changes === "number" ? meta.changes : 0;
|
|
11111
|
+
return sum2 + n;
|
|
11112
|
+
}, 0);
|
|
11113
|
+
const count = rows2.length > 0 ? rows2.length : changes;
|
|
11114
|
+
const mapped2 = mapResult?.(rows2, count) ?? {
|
|
11115
|
+
data: rows2,
|
|
11116
|
+
count
|
|
11117
|
+
};
|
|
11118
|
+
return successResponse(mapped2.data, mapped2.count, batch, batch.bookmark);
|
|
11119
|
+
}
|
|
11120
|
+
const result = await executeD1Query(d1, {
|
|
11121
|
+
query: compiled.sql,
|
|
11122
|
+
params: compiled.params,
|
|
11123
|
+
...session
|
|
11124
|
+
});
|
|
11125
|
+
if (!result.ok) {
|
|
11126
|
+
return errorResponse(400, "HTTP_ERROR", result.message, endpoint, method);
|
|
11127
|
+
}
|
|
11128
|
+
const rows = maybeStripNullRows(result.rows, stripNulls);
|
|
11129
|
+
const mapped = mapResult?.(rows, result.count) ?? {
|
|
11130
|
+
data: rows,
|
|
11131
|
+
count: result.count
|
|
11132
|
+
};
|
|
11133
|
+
return successResponse(mapped.data, mapped.count, result, result.bookmark);
|
|
11134
|
+
} catch (error) {
|
|
11135
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
11136
|
+
return errorResponse(500, "UNKNOWN_ERROR", message, endpoint, method);
|
|
11137
|
+
}
|
|
11138
|
+
}
|
|
11139
|
+
return {
|
|
11140
|
+
baseUrl: CLOUDFLARE_EDGE_BASE_URL,
|
|
11141
|
+
buildHeaders(callOptions) {
|
|
11142
|
+
return { ...callOptions?.headers ?? {} };
|
|
11143
|
+
},
|
|
11144
|
+
async resolveCallOptions(callOptions) {
|
|
11145
|
+
return callOptions;
|
|
11146
|
+
},
|
|
11147
|
+
async verifyConnection(connectionOptions) {
|
|
11148
|
+
const baseUrl = CLOUDFLARE_EDGE_BASE_URL;
|
|
11149
|
+
try {
|
|
11150
|
+
const result = await executeD1Query(d1, { query: "SELECT 1 AS ok" });
|
|
11151
|
+
if (!result.ok) {
|
|
11152
|
+
return {
|
|
11153
|
+
ok: false,
|
|
11154
|
+
reachable: false,
|
|
11155
|
+
status: 500,
|
|
11156
|
+
statusText: null,
|
|
11157
|
+
baseUrl,
|
|
11158
|
+
url: `${baseUrl}/d1`,
|
|
11159
|
+
error: result.message,
|
|
11160
|
+
errorDetails: null,
|
|
11161
|
+
raw: result
|
|
11162
|
+
};
|
|
11163
|
+
}
|
|
11164
|
+
return {
|
|
11165
|
+
ok: true,
|
|
11166
|
+
reachable: true,
|
|
11167
|
+
status: 200,
|
|
11168
|
+
statusText: "OK",
|
|
11169
|
+
baseUrl,
|
|
11170
|
+
url: `${baseUrl}/d1`,
|
|
11171
|
+
error: void 0,
|
|
11172
|
+
errorDetails: null,
|
|
11173
|
+
raw: result
|
|
11174
|
+
};
|
|
11175
|
+
} catch (error) {
|
|
11176
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
11177
|
+
return {
|
|
11178
|
+
ok: false,
|
|
11179
|
+
reachable: false,
|
|
11180
|
+
status: 0,
|
|
11181
|
+
statusText: null,
|
|
11182
|
+
baseUrl,
|
|
11183
|
+
url: `${baseUrl}/d1`,
|
|
11184
|
+
error: message,
|
|
11185
|
+
errorDetails: null,
|
|
11186
|
+
raw: null
|
|
11187
|
+
};
|
|
11188
|
+
}
|
|
11189
|
+
},
|
|
11190
|
+
async fetchGateway(payload, callOptions) {
|
|
11191
|
+
try {
|
|
11192
|
+
if (payload && typeof payload === "object" && "operation" in payload) {
|
|
11193
|
+
return errorResponse(
|
|
11194
|
+
400,
|
|
11195
|
+
"HTTP_ERROR",
|
|
11196
|
+
"Direct AST operation payloads are unsupported on D1 edge-local",
|
|
11197
|
+
"/gateway/fetch",
|
|
11198
|
+
"POST"
|
|
11199
|
+
);
|
|
11200
|
+
}
|
|
11201
|
+
const compiled = compileD1Fetch(payload);
|
|
11202
|
+
const stripNulls = resolveStripNulls(payload.strip_nulls, callOptions, true);
|
|
11203
|
+
if (payload.head === true) {
|
|
11204
|
+
return runCompiled(
|
|
11205
|
+
compiled,
|
|
11206
|
+
callOptions,
|
|
11207
|
+
"/gateway/fetch",
|
|
11208
|
+
"POST",
|
|
11209
|
+
(rows) => ({ data: [], count: extractAthenaCount(rows) }),
|
|
11210
|
+
// COUNT rows are meta, not user-facing object rows
|
|
11211
|
+
false
|
|
11212
|
+
);
|
|
11213
|
+
}
|
|
11214
|
+
const wantsTotalCount = payload.count === "exact" || payload.count === "planned" || payload.count === "estimated";
|
|
11215
|
+
if (wantsTotalCount) {
|
|
11216
|
+
const session = sessionFromOptions(callOptions, options);
|
|
11217
|
+
const countCompiled = compileD1Count(payload);
|
|
11218
|
+
const batch = await executeD1Batch(d1, {
|
|
11219
|
+
statements: [
|
|
11220
|
+
{
|
|
11221
|
+
query: compiled.sql,
|
|
11222
|
+
params: compiled.params
|
|
11223
|
+
},
|
|
11224
|
+
{
|
|
11225
|
+
query: countCompiled.sql,
|
|
11226
|
+
params: countCompiled.params
|
|
11227
|
+
}
|
|
11228
|
+
],
|
|
11229
|
+
...session
|
|
11230
|
+
});
|
|
11231
|
+
if (!batch.ok) {
|
|
11232
|
+
return errorResponse(400, "HTTP_ERROR", batch.message, "/gateway/fetch", "POST");
|
|
11233
|
+
}
|
|
11234
|
+
const dataItem = batch.results[0];
|
|
11235
|
+
const countItem = batch.results[1];
|
|
11236
|
+
if (!dataItem || dataItem.success === false) {
|
|
11237
|
+
const message = dataItem && typeof dataItem.error === "string" && dataItem.error.trim() ? dataItem.error : "D1 page query failed";
|
|
11238
|
+
return errorResponse(400, "HTTP_ERROR", message, "/gateway/fetch", "POST");
|
|
11239
|
+
}
|
|
11240
|
+
if (!countItem || countItem.success === false) {
|
|
11241
|
+
const message = countItem && typeof countItem.error === "string" && countItem.error.trim() ? countItem.error : "D1 count query failed";
|
|
11242
|
+
return errorResponse(400, "HTTP_ERROR", message, "/gateway/fetch", "POST");
|
|
11243
|
+
}
|
|
11244
|
+
const dataRows = Array.isArray(dataItem.results) ? dataItem.results : [];
|
|
11245
|
+
const countRows = Array.isArray(countItem.results) ? countItem.results : [];
|
|
11246
|
+
const total = extractAthenaCount(countRows);
|
|
11247
|
+
const rows = maybeStripNullRows(dataRows, stripNulls);
|
|
11248
|
+
return successResponse(
|
|
11249
|
+
rows,
|
|
11250
|
+
total,
|
|
11251
|
+
{ data: dataItem, count: countItem, batch },
|
|
11252
|
+
batch.bookmark
|
|
11253
|
+
);
|
|
11254
|
+
}
|
|
11255
|
+
return runCompiled(compiled, callOptions, "/gateway/fetch", "POST", void 0, stripNulls);
|
|
11256
|
+
} catch (error) {
|
|
11257
|
+
return compileErrorResponse(error, "/gateway/fetch", "POST");
|
|
11258
|
+
}
|
|
11259
|
+
},
|
|
11260
|
+
async insertGateway(payload, callOptions) {
|
|
11261
|
+
try {
|
|
11262
|
+
const compiled = compileD1Insert(payload);
|
|
11263
|
+
const stripNulls = resolveStripNulls(void 0, callOptions, true);
|
|
11264
|
+
return runCompiled(compiled, callOptions, "/gateway/insert", "PUT", void 0, stripNulls);
|
|
11265
|
+
} catch (error) {
|
|
11266
|
+
return compileErrorResponse(error, "/gateway/insert", "PUT");
|
|
11267
|
+
}
|
|
11268
|
+
},
|
|
11269
|
+
async updateGateway(payload, callOptions) {
|
|
11270
|
+
try {
|
|
11271
|
+
const session = sessionFromOptions(callOptions, options);
|
|
11272
|
+
const compileOptions = await compileOptionsForBoundedMutation(d1, payload, session);
|
|
11273
|
+
const compiled = compileD1Update(payload, compileOptions);
|
|
11274
|
+
const stripNulls = resolveStripNulls(payload.strip_nulls, callOptions, true);
|
|
11275
|
+
return runCompiled(compiled, callOptions, "/gateway/update", "POST", void 0, stripNulls);
|
|
11276
|
+
} catch (error) {
|
|
11277
|
+
return compileErrorResponse(error, "/gateway/update", "POST");
|
|
11278
|
+
}
|
|
11279
|
+
},
|
|
11280
|
+
async deleteGateway(payload, callOptions) {
|
|
11281
|
+
try {
|
|
11282
|
+
const session = sessionFromOptions(callOptions, options);
|
|
11283
|
+
const compileOptions = await compileOptionsForBoundedMutation(d1, payload, session);
|
|
11284
|
+
const compiled = compileD1Delete(payload, compileOptions);
|
|
11285
|
+
const stripNulls = resolveStripNulls(void 0, callOptions, true);
|
|
11286
|
+
return runCompiled(compiled, callOptions, "/gateway/delete", "DELETE", void 0, stripNulls);
|
|
11287
|
+
} catch (error) {
|
|
11288
|
+
return compileErrorResponse(error, "/gateway/delete", "DELETE");
|
|
11289
|
+
}
|
|
11290
|
+
},
|
|
11291
|
+
async rpcGateway(payload, callOptions) {
|
|
11292
|
+
return errorResponse(
|
|
11293
|
+
400,
|
|
11294
|
+
"HTTP_ERROR",
|
|
11295
|
+
"RPC is unsupported on D1 edge-local mode",
|
|
11296
|
+
"/gateway/rpc",
|
|
11297
|
+
"POST",
|
|
11298
|
+
"Use flat CRUD or raw query SQL instead"
|
|
11299
|
+
);
|
|
11300
|
+
},
|
|
11301
|
+
async queryGateway(payload, callOptions) {
|
|
11302
|
+
try {
|
|
11303
|
+
const params = payload.params ?? callOptions?.params;
|
|
11304
|
+
const session = sessionFromOptions(callOptions, options);
|
|
11305
|
+
const query = rewritePostgresSqlForSqlite(payload.query);
|
|
11306
|
+
const result = await executeD1Query(d1, {
|
|
11307
|
+
query,
|
|
11308
|
+
params: Array.isArray(params) ? params : [],
|
|
11309
|
+
...session
|
|
11310
|
+
});
|
|
11311
|
+
if (!result.ok) {
|
|
11312
|
+
return errorResponse(400, "HTTP_ERROR", result.message, "/gateway/query", "POST");
|
|
11313
|
+
}
|
|
11314
|
+
const stripNulls = resolveStripNulls(void 0, callOptions, true);
|
|
11315
|
+
const rows = maybeStripNullRows(result.rows, stripNulls);
|
|
11316
|
+
return successResponse(
|
|
11317
|
+
rows,
|
|
11318
|
+
result.count,
|
|
11319
|
+
{ ...result, query },
|
|
11320
|
+
result.bookmark
|
|
11321
|
+
);
|
|
11322
|
+
} catch (error) {
|
|
11323
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
11324
|
+
return errorResponse(500, "UNKNOWN_ERROR", message, "/gateway/query", "POST");
|
|
11325
|
+
}
|
|
11326
|
+
}
|
|
11327
|
+
};
|
|
11328
|
+
}
|
|
11329
|
+
|
|
11330
|
+
// src/config/errors.ts
|
|
11331
|
+
var AthenaConfigurationError = class extends Error {
|
|
11332
|
+
code;
|
|
11333
|
+
service;
|
|
11334
|
+
constructor(code, message, service) {
|
|
11335
|
+
super(message);
|
|
11336
|
+
this.name = "AthenaConfigurationError";
|
|
11337
|
+
this.code = code;
|
|
11338
|
+
this.service = service;
|
|
11339
|
+
}
|
|
11340
|
+
};
|
|
11341
|
+
|
|
11342
|
+
// src/cloudflare/execution-mode.ts
|
|
11343
|
+
var ATHENA_EXECUTION_MODE_ENV_KEY = "ATHENA_EXECUTION_MODE";
|
|
11344
|
+
var ATHENA_EXECUTION_PREFER_ENV_KEY = "ATHENA_EXECUTION_PREFER";
|
|
11345
|
+
var MODE_ALIASES = {
|
|
11346
|
+
gateway: "gateway",
|
|
11347
|
+
server: "gateway",
|
|
11348
|
+
remote: "gateway",
|
|
11349
|
+
http: "gateway",
|
|
11350
|
+
edge: "edge",
|
|
11351
|
+
cloudflare: "edge",
|
|
11352
|
+
"cloudflare-edge": "edge",
|
|
11353
|
+
d1: "edge",
|
|
11354
|
+
local: "edge",
|
|
11355
|
+
auto: "auto"
|
|
11356
|
+
};
|
|
11357
|
+
function normalizeOptional(value) {
|
|
11358
|
+
const trimmed = value?.trim();
|
|
11359
|
+
return trimmed || void 0;
|
|
11360
|
+
}
|
|
11361
|
+
function normalizeModeString(value) {
|
|
11362
|
+
if (value == null) return void 0;
|
|
11363
|
+
const key = value.trim().toLowerCase();
|
|
11364
|
+
if (!key) return void 0;
|
|
11365
|
+
const mapped = MODE_ALIASES[key];
|
|
11366
|
+
if (!mapped) {
|
|
11367
|
+
throw new AthenaConfigurationError(
|
|
11368
|
+
"ATHENA_NO_SERVICE_CONFIGURED",
|
|
11369
|
+
`Unknown Athena execution mode "${value}". Use gateway | edge | auto (aliases: server, remote, cloudflare, d1).`,
|
|
11370
|
+
"db"
|
|
11371
|
+
);
|
|
11372
|
+
}
|
|
11373
|
+
return mapped;
|
|
11374
|
+
}
|
|
11375
|
+
function isD1Binding(value) {
|
|
11376
|
+
return Boolean(
|
|
11377
|
+
value && typeof value === "object" && typeof value.prepare === "function"
|
|
11378
|
+
);
|
|
11379
|
+
}
|
|
11380
|
+
var GATEWAY_URL_ENV_KEYS = [
|
|
11381
|
+
"ATHENA_URL",
|
|
11382
|
+
"NEXT_PUBLIC_ATHENA_URL",
|
|
11383
|
+
"ATHENA_DB_URL",
|
|
11384
|
+
"ATHENA_GATEWAY_URL",
|
|
11385
|
+
"NEXT_PUBLIC_ATHENA_DB_API_URL"
|
|
11386
|
+
];
|
|
11387
|
+
function resolveGatewayUrl(url, env) {
|
|
11388
|
+
if (normalizeOptional(url)) {
|
|
11389
|
+
return normalizeOptional(url);
|
|
11390
|
+
}
|
|
11391
|
+
for (const key of GATEWAY_URL_ENV_KEYS) {
|
|
11392
|
+
const value = normalizeOptional(env[key]);
|
|
11393
|
+
if (value) return value;
|
|
11394
|
+
}
|
|
11395
|
+
return void 0;
|
|
11396
|
+
}
|
|
11397
|
+
function resolvePrefer(prefer, env) {
|
|
11398
|
+
const raw = normalizeOptional(typeof prefer === "string" ? prefer : prefer ?? void 0) ?? normalizeOptional(env[ATHENA_EXECUTION_PREFER_ENV_KEY]) ?? "edge";
|
|
11399
|
+
const key = raw.toLowerCase();
|
|
11400
|
+
if (key === "gateway" || key === "server" || key === "remote" || key === "http") {
|
|
11401
|
+
return "gateway";
|
|
11402
|
+
}
|
|
11403
|
+
if (key === "edge" || key === "d1" || key === "cloudflare" || key === "local") {
|
|
11404
|
+
return "edge";
|
|
11405
|
+
}
|
|
11406
|
+
throw new AthenaConfigurationError(
|
|
11407
|
+
"ATHENA_NO_SERVICE_CONFIGURED",
|
|
11408
|
+
`Unknown Athena execution prefer "${raw}". Use edge | gateway.`,
|
|
11409
|
+
"db"
|
|
11410
|
+
);
|
|
11411
|
+
}
|
|
11412
|
+
function resolveAthenaExecutionMode(input = {}) {
|
|
11413
|
+
const env = input.env ?? {};
|
|
11414
|
+
const fromEnv = normalizeModeString(env[ATHENA_EXECUTION_MODE_ENV_KEY]);
|
|
11415
|
+
const requested = normalizeModeString(input.mode) ?? fromEnv ?? "auto";
|
|
11416
|
+
const url = resolveGatewayUrl(input.url, env);
|
|
11417
|
+
const hasD1 = isD1Binding(input.d1);
|
|
11418
|
+
const hasGateway = Boolean(url);
|
|
11419
|
+
if (requested === "gateway") {
|
|
11420
|
+
if (!hasGateway) {
|
|
11421
|
+
throw new AthenaConfigurationError(
|
|
11422
|
+
"ATHENA_NO_SERVICE_CONFIGURED",
|
|
11423
|
+
'Athena execution mode is "gateway" but no url / ATHENA_URL / ATHENA_DB_URL / ATHENA_GATEWAY_URL was provided.',
|
|
11424
|
+
"db"
|
|
11425
|
+
);
|
|
11426
|
+
}
|
|
11427
|
+
return "gateway";
|
|
11428
|
+
}
|
|
11429
|
+
if (requested === "edge") {
|
|
11430
|
+
if (!hasD1) {
|
|
11431
|
+
throw new AthenaConfigurationError(
|
|
11432
|
+
"ATHENA_NO_SERVICE_CONFIGURED",
|
|
11433
|
+
'Athena execution mode is "edge" but no D1 binding was provided (db.d1 / config.d1 / env.DB).',
|
|
11434
|
+
"db"
|
|
11435
|
+
);
|
|
11436
|
+
}
|
|
11437
|
+
return "edge";
|
|
11438
|
+
}
|
|
11439
|
+
if (hasD1 && hasGateway) {
|
|
11440
|
+
return resolvePrefer(input.prefer, env);
|
|
11441
|
+
}
|
|
11442
|
+
if (hasD1) return "edge";
|
|
11443
|
+
if (hasGateway) return "gateway";
|
|
11444
|
+
throw new AthenaConfigurationError(
|
|
11445
|
+
"ATHENA_NO_SERVICE_CONFIGURED",
|
|
11446
|
+
'Cannot resolve Athena execution mode: provide mode "gateway" with url/key, mode "edge" with d1, or mode "auto" with either a D1 binding or a gateway URL (ATHENA_URL / ATHENA_DB_URL / ATHENA_GATEWAY_URL).',
|
|
11447
|
+
"db"
|
|
11448
|
+
);
|
|
11449
|
+
}
|
|
11450
|
+
|
|
11451
|
+
// src/cloudflare/r2/storage.ts
|
|
11452
|
+
function normalizePrefix(prefix) {
|
|
11453
|
+
if (!prefix?.trim()) return "";
|
|
11454
|
+
const normalized = prefix.replace(/^\/+/, "").replace(/\/?$/, "/");
|
|
11455
|
+
if (normalized.includes("\0")) {
|
|
11456
|
+
throw new Error("storage prefix must not contain null bytes");
|
|
11457
|
+
}
|
|
11458
|
+
if (normalized.split("/").some((segment) => segment === "..")) {
|
|
11459
|
+
throw new Error('storage prefix must not contain ".." path segments');
|
|
11460
|
+
}
|
|
11461
|
+
return normalized;
|
|
11462
|
+
}
|
|
11463
|
+
function assertSafeObjectKey(key) {
|
|
11464
|
+
if (typeof key !== "string" || !key.trim()) {
|
|
11465
|
+
throw new Error("Object key is required");
|
|
11466
|
+
}
|
|
11467
|
+
if (key.includes("\0")) {
|
|
11468
|
+
throw new Error("Object key must not contain null bytes");
|
|
11469
|
+
}
|
|
11470
|
+
const cleaned = key.replace(/^\/+/, "");
|
|
11471
|
+
if (!cleaned) {
|
|
11472
|
+
throw new Error("Object key is required");
|
|
11473
|
+
}
|
|
11474
|
+
const segments = cleaned.split("/");
|
|
11475
|
+
if (segments.some((segment) => segment === "..")) {
|
|
11476
|
+
throw new Error('Object key must not contain ".." path segments');
|
|
11477
|
+
}
|
|
11478
|
+
return cleaned;
|
|
11479
|
+
}
|
|
11480
|
+
function joinKey(prefix, key) {
|
|
11481
|
+
return `${prefix}${assertSafeObjectKey(key)}`;
|
|
11482
|
+
}
|
|
11483
|
+
function toLogicalKey(prefix, physicalKey) {
|
|
11484
|
+
if (!prefix) return physicalKey;
|
|
11485
|
+
if (physicalKey.startsWith(prefix)) {
|
|
11486
|
+
return physicalKey.slice(prefix.length);
|
|
11487
|
+
}
|
|
11488
|
+
return physicalKey;
|
|
11489
|
+
}
|
|
11490
|
+
function toPhysicalKey(prefix, key) {
|
|
11491
|
+
return joinKey(prefix, key);
|
|
11492
|
+
}
|
|
11493
|
+
function unsupported(method) {
|
|
11494
|
+
throw new Error(
|
|
11495
|
+
`storage.${method} is not available in Cloudflare edge-local R2 object mode. Only putObject / getObject / deleteObject / listObjects are supported (L3a).`
|
|
11496
|
+
);
|
|
11497
|
+
}
|
|
11498
|
+
function createCloudflareR2StorageModule(options) {
|
|
11499
|
+
const prefix = normalizePrefix(options.prefix);
|
|
11500
|
+
const { r2 } = options;
|
|
11501
|
+
const putObject = async (input) => {
|
|
11502
|
+
const logical = assertSafeObjectKey(input.key);
|
|
11503
|
+
const physical = toPhysicalKey(prefix, logical);
|
|
11504
|
+
await r2.put(physical, input.body, {
|
|
11505
|
+
httpMetadata: input.contentType ? { contentType: input.contentType } : void 0,
|
|
11506
|
+
customMetadata: input.metadata
|
|
11507
|
+
});
|
|
11508
|
+
return { key: logical };
|
|
11509
|
+
};
|
|
11510
|
+
const getObject = async (input) => {
|
|
11511
|
+
const logical = assertSafeObjectKey(input.key);
|
|
11512
|
+
const physical = toPhysicalKey(prefix, logical);
|
|
11513
|
+
const object = await r2.get(physical);
|
|
11514
|
+
if (!object) return null;
|
|
11515
|
+
return {
|
|
11516
|
+
key: toLogicalKey(prefix, object.key),
|
|
11517
|
+
size: object.size,
|
|
11518
|
+
contentType: object.httpMetadata?.contentType,
|
|
11519
|
+
body: object
|
|
11520
|
+
};
|
|
11521
|
+
};
|
|
11522
|
+
const deleteObject = async (input) => {
|
|
11523
|
+
const logicalKeys = (Array.isArray(input.key) ? input.key : [input.key]).map(
|
|
11524
|
+
(key) => assertSafeObjectKey(key)
|
|
11525
|
+
);
|
|
11526
|
+
const physicalKeys = logicalKeys.map((key) => toPhysicalKey(prefix, key));
|
|
11527
|
+
await r2.delete(physicalKeys.length === 1 ? physicalKeys[0] : physicalKeys);
|
|
11528
|
+
return { deleted: logicalKeys };
|
|
11529
|
+
};
|
|
11530
|
+
const listObjects = async (input) => {
|
|
11531
|
+
const relative = input?.prefix?.trim() ? assertSafeObjectKey(input.prefix) : "";
|
|
11532
|
+
const listPrefix = `${prefix}${relative}`;
|
|
11533
|
+
const listed = await r2.list({
|
|
11534
|
+
prefix: listPrefix || void 0,
|
|
11535
|
+
limit: input?.limit,
|
|
11536
|
+
cursor: input?.cursor
|
|
11537
|
+
});
|
|
11538
|
+
return {
|
|
11539
|
+
objects: listed.objects.map((object) => ({
|
|
11540
|
+
key: toLogicalKey(prefix, object.key),
|
|
11541
|
+
size: object.size,
|
|
11542
|
+
etag: object.etag,
|
|
11543
|
+
uploaded: object.uploaded
|
|
11544
|
+
})),
|
|
11545
|
+
truncated: listed.truncated,
|
|
11546
|
+
cursor: listed.cursor
|
|
11547
|
+
};
|
|
11548
|
+
};
|
|
11549
|
+
const base = {
|
|
11550
|
+
putObject,
|
|
11551
|
+
getObject,
|
|
11552
|
+
deleteObject,
|
|
11553
|
+
listObjects
|
|
11554
|
+
};
|
|
11555
|
+
return new Proxy(base, {
|
|
11556
|
+
get(target, property, receiver) {
|
|
11557
|
+
if (property in target) {
|
|
11558
|
+
return Reflect.get(target, property, receiver);
|
|
11559
|
+
}
|
|
11560
|
+
if (typeof property === "string") {
|
|
11561
|
+
return (...args) => {
|
|
11562
|
+
return unsupported(property);
|
|
11563
|
+
};
|
|
11564
|
+
}
|
|
11565
|
+
return void 0;
|
|
11566
|
+
}
|
|
11567
|
+
});
|
|
11568
|
+
}
|
|
11569
|
+
|
|
11570
|
+
// src/billing/module.ts
|
|
11571
|
+
var SDK_NAME5 = "xylex-group/athena-billing";
|
|
11572
|
+
var SDK_HEADER_VALUE4 = buildSdkHeaderValue(SDK_NAME5);
|
|
11573
|
+
var AthenaBillingError = class extends Error {
|
|
11574
|
+
status;
|
|
11575
|
+
endpoint;
|
|
11576
|
+
method;
|
|
11577
|
+
body;
|
|
11578
|
+
constructor(input) {
|
|
11579
|
+
super(input.message);
|
|
11580
|
+
this.name = "AthenaBillingError";
|
|
11581
|
+
this.status = input.status;
|
|
11582
|
+
this.endpoint = input.endpoint;
|
|
11583
|
+
this.method = input.method;
|
|
11584
|
+
this.body = input.body;
|
|
11585
|
+
}
|
|
11586
|
+
};
|
|
11587
|
+
function withPathParam2(path, name, value) {
|
|
11588
|
+
return path.replace(`{${name}}`, encodeURIComponent(value));
|
|
11589
|
+
}
|
|
11590
|
+
function appendQuery3(path, query) {
|
|
11591
|
+
if (!query) return path;
|
|
11592
|
+
const params = new URLSearchParams();
|
|
11593
|
+
for (const [key, value] of Object.entries(query)) {
|
|
11594
|
+
if (value === void 0 || value === null) continue;
|
|
11595
|
+
params.set(key, String(value));
|
|
11596
|
+
}
|
|
11597
|
+
const serialized = params.toString();
|
|
11598
|
+
return serialized ? `${path}?${serialized}` : path;
|
|
11599
|
+
}
|
|
11600
|
+
function connectionQuery(input) {
|
|
11601
|
+
const query = {
|
|
11602
|
+
connectionId: input.connectionId
|
|
11603
|
+
};
|
|
11604
|
+
if (input.clientName) query.clientName = input.clientName;
|
|
11605
|
+
if ("cursor" in input && input.cursor) query.cursor = input.cursor;
|
|
11606
|
+
if ("source" in input && input.source) query.source = input.source;
|
|
11607
|
+
if ("limit" in input && input.limit !== void 0) query.limit = String(input.limit);
|
|
11608
|
+
if ("offset" in input && input.offset !== void 0) query.offset = String(input.offset);
|
|
11609
|
+
return query;
|
|
11610
|
+
}
|
|
11611
|
+
function parseEnvelopeData(body) {
|
|
11612
|
+
if (body && typeof body === "object" && "data" in body) {
|
|
11613
|
+
return body.data;
|
|
11614
|
+
}
|
|
11615
|
+
return body;
|
|
11616
|
+
}
|
|
11617
|
+
function createBillingModule(config) {
|
|
11618
|
+
const baseUrl = normalizeAthenaGatewayBaseUrl(config.baseUrl, {
|
|
11619
|
+
label: "Athena billing base URL"
|
|
11620
|
+
});
|
|
11621
|
+
const fetchImpl = config.fetchImpl ?? globalThis.fetch.bind(globalThis);
|
|
11622
|
+
async function call(method, path, body, options, responseType = "json") {
|
|
11623
|
+
const headers = buildAthenaRequestHeaders({
|
|
11624
|
+
profile: "gateway",
|
|
11625
|
+
sdkHeaderValue: SDK_HEADER_VALUE4,
|
|
11626
|
+
apiKey: options?.apiKey ?? config.apiKey,
|
|
11627
|
+
client: config.client,
|
|
11628
|
+
configHeaders: {
|
|
11629
|
+
...config.headers ?? {}
|
|
11630
|
+
},
|
|
11631
|
+
callHeaders: options?.headers,
|
|
11632
|
+
contentType: "application/json"
|
|
11633
|
+
});
|
|
11634
|
+
let requestBody;
|
|
11635
|
+
if (body !== void 0 && body !== null) {
|
|
11636
|
+
if (typeof body === "string" || body instanceof Blob || body instanceof ArrayBuffer || ArrayBuffer.isView(body) || body instanceof FormData || body instanceof URLSearchParams) {
|
|
11637
|
+
requestBody = body;
|
|
11638
|
+
} else {
|
|
11639
|
+
requestBody = JSON.stringify(body);
|
|
11640
|
+
if (!hasHeaderIgnoreCase(headers, "Content-Type")) {
|
|
11641
|
+
headers["Content-Type"] = "application/json";
|
|
11642
|
+
}
|
|
11643
|
+
}
|
|
11644
|
+
}
|
|
11645
|
+
const targetUrl = `${baseUrl}${path.startsWith("/") ? path : `/${path}`}`;
|
|
11646
|
+
const response = await fetchImpl(targetUrl, {
|
|
11647
|
+
method,
|
|
11648
|
+
headers,
|
|
11649
|
+
body: requestBody,
|
|
11650
|
+
signal: options?.signal
|
|
11651
|
+
});
|
|
11652
|
+
if (responseType === "text") {
|
|
11653
|
+
const text = await response.text();
|
|
11654
|
+
if (!response.ok) {
|
|
11655
|
+
throw new AthenaBillingError({
|
|
11656
|
+
message: `Billing request failed (${response.status})`,
|
|
11657
|
+
status: response.status,
|
|
11658
|
+
endpoint: path,
|
|
11659
|
+
method,
|
|
11660
|
+
body: text
|
|
11661
|
+
});
|
|
11662
|
+
}
|
|
11663
|
+
return text;
|
|
11664
|
+
}
|
|
11665
|
+
const rawText = await response.text();
|
|
11666
|
+
let parsed = rawText;
|
|
11667
|
+
if (rawText) {
|
|
11668
|
+
try {
|
|
11669
|
+
parsed = JSON.parse(rawText);
|
|
11670
|
+
} catch {
|
|
11671
|
+
parsed = rawText;
|
|
11672
|
+
}
|
|
11673
|
+
} else {
|
|
11674
|
+
parsed = null;
|
|
11675
|
+
}
|
|
11676
|
+
if (!response.ok) {
|
|
11677
|
+
const message = parsed && typeof parsed === "object" && "message" in parsed && typeof parsed.message === "string" ? parsed.message : `Billing request failed (${response.status})`;
|
|
11678
|
+
throw new AthenaBillingError({
|
|
11679
|
+
message,
|
|
11680
|
+
status: response.status,
|
|
11681
|
+
endpoint: path,
|
|
11682
|
+
method,
|
|
11683
|
+
body: parsed
|
|
11684
|
+
});
|
|
11685
|
+
}
|
|
11686
|
+
return parseEnvelopeData(parsed);
|
|
11687
|
+
}
|
|
11688
|
+
return {
|
|
11689
|
+
getCapabilities(input, options) {
|
|
11690
|
+
return call(
|
|
11691
|
+
"GET",
|
|
11692
|
+
appendQuery3("/billing/v1/capabilities", connectionQuery(input)),
|
|
11693
|
+
void 0,
|
|
11694
|
+
options
|
|
11695
|
+
);
|
|
11696
|
+
},
|
|
11697
|
+
createCheckout(body, options) {
|
|
11698
|
+
return call("POST", "/billing/v1/checkouts", body, options);
|
|
11699
|
+
},
|
|
11700
|
+
listProducts(input, options) {
|
|
11701
|
+
return call(
|
|
11702
|
+
"GET",
|
|
11703
|
+
appendQuery3("/billing/v1/products", connectionQuery(input)),
|
|
11704
|
+
void 0,
|
|
11705
|
+
options
|
|
11706
|
+
);
|
|
11707
|
+
},
|
|
11708
|
+
listPrices(input, options) {
|
|
11709
|
+
return call(
|
|
11710
|
+
"GET",
|
|
11711
|
+
appendQuery3("/billing/v1/prices", {
|
|
11712
|
+
...connectionQuery(input),
|
|
11713
|
+
...input.productId ? { productId: input.productId } : {}
|
|
11714
|
+
}),
|
|
11715
|
+
void 0,
|
|
11716
|
+
options
|
|
11717
|
+
);
|
|
11718
|
+
},
|
|
11719
|
+
listCustomers(input, options) {
|
|
11720
|
+
return call(
|
|
11721
|
+
"GET",
|
|
11722
|
+
appendQuery3("/billing/v1/customers", connectionQuery(input)),
|
|
11723
|
+
void 0,
|
|
11724
|
+
options
|
|
11725
|
+
);
|
|
11726
|
+
},
|
|
11727
|
+
createCustomer(input, options) {
|
|
11728
|
+
return call(
|
|
11729
|
+
"POST",
|
|
11730
|
+
"/billing/v1/customers",
|
|
11731
|
+
{
|
|
11732
|
+
connectionId: input.connectionId,
|
|
11733
|
+
clientName: input.clientName,
|
|
11734
|
+
email: input.email,
|
|
11735
|
+
name: input.name,
|
|
11736
|
+
metadata: input.metadata ?? {},
|
|
11737
|
+
idempotencyKey: input.idempotencyKey
|
|
11738
|
+
},
|
|
11739
|
+
options
|
|
11740
|
+
);
|
|
11741
|
+
},
|
|
9084
11742
|
getCustomer(id, input, options) {
|
|
9085
11743
|
return call(
|
|
9086
11744
|
"GET",
|
|
@@ -9505,18 +12163,6 @@ function createBillingModule(config) {
|
|
|
9505
12163
|
};
|
|
9506
12164
|
}
|
|
9507
12165
|
|
|
9508
|
-
// src/config/errors.ts
|
|
9509
|
-
var AthenaConfigurationError = class extends Error {
|
|
9510
|
-
code;
|
|
9511
|
-
service;
|
|
9512
|
-
constructor(code, message, service) {
|
|
9513
|
-
super(message);
|
|
9514
|
-
this.name = "AthenaConfigurationError";
|
|
9515
|
-
this.code = code;
|
|
9516
|
-
this.service = service;
|
|
9517
|
-
}
|
|
9518
|
-
};
|
|
9519
|
-
|
|
9520
12166
|
// src/context/merge.ts
|
|
9521
12167
|
function mergeAthenaRequestContexts(base, override) {
|
|
9522
12168
|
if (!base && !override) return void 0;
|
|
@@ -9530,6 +12176,82 @@ function mergeAthenaRequestContexts(base, override) {
|
|
|
9530
12176
|
};
|
|
9531
12177
|
}
|
|
9532
12178
|
|
|
12179
|
+
// src/diagnostics.ts
|
|
12180
|
+
function readProcessEnv2() {
|
|
12181
|
+
try {
|
|
12182
|
+
return globalThis.process?.env ?? {};
|
|
12183
|
+
} catch {
|
|
12184
|
+
return {};
|
|
12185
|
+
}
|
|
12186
|
+
}
|
|
12187
|
+
function isTruthyEnv(value) {
|
|
12188
|
+
if (!value) return false;
|
|
12189
|
+
const normalized = value.trim().toLowerCase();
|
|
12190
|
+
return normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on";
|
|
12191
|
+
}
|
|
12192
|
+
function isQuietAthenaDiagnosticsEnvironment(env = readProcessEnv2()) {
|
|
12193
|
+
const nodeEnv = env.NODE_ENV?.trim().toLowerCase();
|
|
12194
|
+
if (nodeEnv === "production") {
|
|
12195
|
+
return true;
|
|
12196
|
+
}
|
|
12197
|
+
if (isTruthyEnv(env.OPENNEXT_BUILD)) {
|
|
12198
|
+
return true;
|
|
12199
|
+
}
|
|
12200
|
+
const nextPhase = env.NEXT_PHASE?.trim();
|
|
12201
|
+
if (nextPhase === "phase-production-build") {
|
|
12202
|
+
return true;
|
|
12203
|
+
}
|
|
12204
|
+
if (isTruthyEnv(env.CI) && nodeEnv !== "test") {
|
|
12205
|
+
if (nodeEnv === "production" || isTruthyEnv(env.OPENNEXT_BUILD)) {
|
|
12206
|
+
return true;
|
|
12207
|
+
}
|
|
12208
|
+
}
|
|
12209
|
+
return false;
|
|
12210
|
+
}
|
|
12211
|
+
function resolveBooleanFlag(explicit, mode, quiet) {
|
|
12212
|
+
if (typeof explicit === "boolean") {
|
|
12213
|
+
return explicit;
|
|
12214
|
+
}
|
|
12215
|
+
if (mode === true) {
|
|
12216
|
+
return true;
|
|
12217
|
+
}
|
|
12218
|
+
if (mode === false) {
|
|
12219
|
+
return false;
|
|
12220
|
+
}
|
|
12221
|
+
if (mode === "auto") {
|
|
12222
|
+
return false;
|
|
12223
|
+
}
|
|
12224
|
+
return false;
|
|
12225
|
+
}
|
|
12226
|
+
function resolveAthenaClientDiagnostics(input) {
|
|
12227
|
+
const env = input.env ?? readProcessEnv2();
|
|
12228
|
+
const quiet = isQuietAthenaDiagnosticsEnvironment(env);
|
|
12229
|
+
const mode = input.diagnostics;
|
|
12230
|
+
const effectiveMode = mode === "auto" && quiet ? false : mode;
|
|
12231
|
+
const debugAst = resolveBooleanFlag(input.debugAst, effectiveMode);
|
|
12232
|
+
const findManyAst = resolveBooleanFlag(input.findManyAst, effectiveMode);
|
|
12233
|
+
let traceQueries;
|
|
12234
|
+
if (input.traceQueries !== void 0) {
|
|
12235
|
+
if (typeof input.traceQueries === "boolean") {
|
|
12236
|
+
traceQueries = input.traceQueries;
|
|
12237
|
+
} else if (effectiveMode === false || mode === "auto" && quiet) {
|
|
12238
|
+
const enabled = input.traceQueries.enabled;
|
|
12239
|
+
traceQueries = typeof enabled === "boolean" ? enabled ? input.traceQueries : false : false;
|
|
12240
|
+
} else {
|
|
12241
|
+
traceQueries = input.traceQueries;
|
|
12242
|
+
}
|
|
12243
|
+
} else if (effectiveMode === true) {
|
|
12244
|
+
traceQueries = true;
|
|
12245
|
+
} else {
|
|
12246
|
+
traceQueries = false;
|
|
12247
|
+
}
|
|
12248
|
+
return {
|
|
12249
|
+
debugAst,
|
|
12250
|
+
findManyAst,
|
|
12251
|
+
traceQueries
|
|
12252
|
+
};
|
|
12253
|
+
}
|
|
12254
|
+
|
|
9533
12255
|
// src/v3-client.ts
|
|
9534
12256
|
var ENV_URL_KEYS = ["ATHENA_URL", "NEXT_PUBLIC_ATHENA_URL"];
|
|
9535
12257
|
var ENV_DB_URL_KEYS = ["ATHENA_DB_URL", "ATHENA_GATEWAY_URL", "NEXT_PUBLIC_ATHENA_DB_API_URL"];
|
|
@@ -9538,7 +12260,13 @@ var ENV_CHAT_URL_KEYS = ["ATHENA_CHAT_URL", "NEXT_PUBLIC_ATHENA_CHAT_URL"];
|
|
|
9538
12260
|
var ENV_CHAT_WS_URL_KEYS = ["ATHENA_CHAT_WS_URL", "NEXT_PUBLIC_ATHENA_CHAT_WS_URL"];
|
|
9539
12261
|
var ENV_STORAGE_URL_KEYS = ["ATHENA_STORAGE_URL", "NEXT_PUBLIC_ATHENA_STORAGE_URL"];
|
|
9540
12262
|
var ENV_KEY_KEYS = ["ATHENA_API_KEY", "NEXT_PUBLIC_ATHENA_API_KEY", "ATHENA_GATEWAY_API_KEY", "X_API_KEY"];
|
|
9541
|
-
var ENV_CLIENT_KEYS = [
|
|
12263
|
+
var ENV_CLIENT_KEYS = [
|
|
12264
|
+
"ATHENA_CLIENT",
|
|
12265
|
+
"ATHENA_GATEWAY_CLIENT",
|
|
12266
|
+
"ATHENA_GENERATOR_CLIENT",
|
|
12267
|
+
"NEXT_PUBLIC_ATHENA_CLIENT",
|
|
12268
|
+
"NEXT_PUBLIC_ATHENA_GATEWAY_CLIENT"
|
|
12269
|
+
];
|
|
9542
12270
|
var MISSING_DB_SENTINEL = "https://athena.invalid/db";
|
|
9543
12271
|
function readFirstEnv(env, keys) {
|
|
9544
12272
|
for (const key of keys) {
|
|
@@ -9547,14 +12275,30 @@ function readFirstEnv(env, keys) {
|
|
|
9547
12275
|
}
|
|
9548
12276
|
return void 0;
|
|
9549
12277
|
}
|
|
9550
|
-
function
|
|
12278
|
+
function readFirstEnvHttpUrl(env, keys) {
|
|
12279
|
+
for (const key of keys) {
|
|
12280
|
+
const value = env?.[key]?.trim();
|
|
12281
|
+
if (value && isAbsoluteHttpUrl(value)) return value;
|
|
12282
|
+
}
|
|
12283
|
+
return void 0;
|
|
12284
|
+
}
|
|
12285
|
+
function normalizeOptional2(value) {
|
|
9551
12286
|
const normalized = value?.trim();
|
|
9552
12287
|
return normalized || void 0;
|
|
9553
12288
|
}
|
|
12289
|
+
function isAbsoluteHttpUrl(value) {
|
|
12290
|
+
try {
|
|
12291
|
+
const url = new URL(value);
|
|
12292
|
+
return url.protocol === "http:" || url.protocol === "https:";
|
|
12293
|
+
} catch {
|
|
12294
|
+
return false;
|
|
12295
|
+
}
|
|
12296
|
+
}
|
|
9554
12297
|
function appendPath(baseUrl, path) {
|
|
9555
12298
|
return `${baseUrl.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
|
|
9556
12299
|
}
|
|
9557
12300
|
function toWebSocketUrl(baseUrl) {
|
|
12301
|
+
if (!isAbsoluteHttpUrl(baseUrl)) return void 0;
|
|
9558
12302
|
const url = new URL(baseUrl);
|
|
9559
12303
|
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
9560
12304
|
url.pathname = `${url.pathname.replace(/\/+$/, "")}/wss/gateway`;
|
|
@@ -9564,11 +12308,11 @@ function toWebSocketUrl(baseUrl) {
|
|
|
9564
12308
|
}
|
|
9565
12309
|
function resolveCore(config) {
|
|
9566
12310
|
const env = config.env;
|
|
9567
|
-
const explicitRoot =
|
|
9568
|
-
const envRoot =
|
|
9569
|
-
const root = explicitRoot
|
|
9570
|
-
const explicitRootWinsOverEnvServices = explicitRoot
|
|
9571
|
-
const resolveService = (explicit, envKeys, path) =>
|
|
12311
|
+
const explicitRoot = normalizeOptional2(config.url);
|
|
12312
|
+
const envRoot = readFirstEnvHttpUrl(env, ENV_URL_KEYS);
|
|
12313
|
+
const root = explicitRoot && isAbsoluteHttpUrl(explicitRoot) ? explicitRoot : explicitRoot ? void 0 : envRoot;
|
|
12314
|
+
const explicitRootWinsOverEnvServices = Boolean(root && explicitRoot && isAbsoluteHttpUrl(explicitRoot));
|
|
12315
|
+
const resolveService = (explicit, envKeys, path) => normalizeOptional2(explicit) ?? (explicitRootWinsOverEnvServices && root ? appendPath(root, path) : void 0) ?? readFirstEnvHttpUrl(env, envKeys) ?? (root ? appendPath(root, path) : void 0);
|
|
9572
12316
|
const dbUrl = resolveService(config.db?.url, ENV_DB_URL_KEYS, "db");
|
|
9573
12317
|
const urls = {
|
|
9574
12318
|
db: dbUrl,
|
|
@@ -9576,8 +12320,8 @@ function resolveCore(config) {
|
|
|
9576
12320
|
chat: resolveService(config.chat?.url, ENV_CHAT_URL_KEYS, "chat"),
|
|
9577
12321
|
storage: resolveService(config.storage?.url, ENV_STORAGE_URL_KEYS, "storage"),
|
|
9578
12322
|
// Billing lives on the main Athena HTTP surface (same host as gateway/db).
|
|
9579
|
-
billing:
|
|
9580
|
-
chatWs:
|
|
12323
|
+
billing: normalizeOptional2(config.billing?.url) ?? dbUrl ?? root ?? void 0,
|
|
12324
|
+
chatWs: normalizeOptional2(config.chat?.wsUrl) ?? (explicitRootWinsOverEnvServices && root ? toWebSocketUrl(root) : void 0) ?? readFirstEnvHttpUrl(env, ENV_CHAT_WS_URL_KEYS) ?? (root ? toWebSocketUrl(root) : void 0)
|
|
9581
12325
|
};
|
|
9582
12326
|
if (!urls.db && !urls.auth && !urls.chat && !urls.storage && !urls.billing) {
|
|
9583
12327
|
throw new AthenaConfigurationError(
|
|
@@ -9586,7 +12330,7 @@ function resolveCore(config) {
|
|
|
9586
12330
|
"db"
|
|
9587
12331
|
);
|
|
9588
12332
|
}
|
|
9589
|
-
const key =
|
|
12333
|
+
const key = normalizeOptional2(config.key) ?? readFirstEnv(env, ENV_KEY_KEYS);
|
|
9590
12334
|
if (!key) {
|
|
9591
12335
|
throw new AthenaConfigurationError(
|
|
9592
12336
|
"ATHENA_API_KEY_REQUIRED",
|
|
@@ -9597,7 +12341,7 @@ function resolveCore(config) {
|
|
|
9597
12341
|
config,
|
|
9598
12342
|
urls,
|
|
9599
12343
|
key,
|
|
9600
|
-
client:
|
|
12344
|
+
client: normalizeOptional2(config.client) ?? readFirstEnv(env, ENV_CLIENT_KEYS)
|
|
9601
12345
|
};
|
|
9602
12346
|
return {
|
|
9603
12347
|
...base,
|
|
@@ -9612,7 +12356,20 @@ async function resolveConfiguredContext(core, viewContext) {
|
|
|
9612
12356
|
function createInternalConfig(core) {
|
|
9613
12357
|
const { config, urls } = core;
|
|
9614
12358
|
const { url: _authUrl, ...authOptions } = config.auth ?? {};
|
|
9615
|
-
const {
|
|
12359
|
+
const {
|
|
12360
|
+
url: _storageUrl,
|
|
12361
|
+
directUpload,
|
|
12362
|
+
r2: _r2,
|
|
12363
|
+
prefix: _r2Prefix,
|
|
12364
|
+
...storageOptions
|
|
12365
|
+
} = config.storage ?? {};
|
|
12366
|
+
const diagnostics = resolveAthenaClientDiagnostics({
|
|
12367
|
+
diagnostics: config.diagnostics,
|
|
12368
|
+
debugAst: config.debugAst,
|
|
12369
|
+
findManyAst: config.findManyAst,
|
|
12370
|
+
traceQueries: config.traceQueries,
|
|
12371
|
+
env: config.env
|
|
12372
|
+
});
|
|
9616
12373
|
return {
|
|
9617
12374
|
baseUrl: urls.db ?? MISSING_DB_SENTINEL,
|
|
9618
12375
|
apiKey: core.key,
|
|
@@ -9629,14 +12386,15 @@ function createInternalConfig(core) {
|
|
|
9629
12386
|
models: config.models,
|
|
9630
12387
|
behavior: {
|
|
9631
12388
|
retryReads: config.retryReads,
|
|
9632
|
-
traceQueries:
|
|
9633
|
-
debugAst:
|
|
9634
|
-
findManyAst:
|
|
12389
|
+
traceQueries: diagnostics.traceQueries,
|
|
12390
|
+
debugAst: diagnostics.debugAst,
|
|
12391
|
+
findManyAst: diagnostics.findManyAst
|
|
9635
12392
|
},
|
|
9636
12393
|
storage: {
|
|
9637
12394
|
...storageOptions,
|
|
9638
12395
|
...directUpload ? { directUpload } : {}
|
|
9639
|
-
}
|
|
12396
|
+
},
|
|
12397
|
+
gatewayTransport: config.gatewayTransport
|
|
9640
12398
|
};
|
|
9641
12399
|
}
|
|
9642
12400
|
function serviceGuard(urls, service) {
|
|
@@ -9659,6 +12417,232 @@ function createUnavailableNamespace(service, urls, path = []) {
|
|
|
9659
12417
|
}
|
|
9660
12418
|
});
|
|
9661
12419
|
}
|
|
12420
|
+
function isD1Binding2(value) {
|
|
12421
|
+
return Boolean(
|
|
12422
|
+
value && typeof value === "object" && typeof value.prepare === "function"
|
|
12423
|
+
);
|
|
12424
|
+
}
|
|
12425
|
+
function isR2Binding(value) {
|
|
12426
|
+
return Boolean(
|
|
12427
|
+
value && typeof value === "object" && typeof value.put === "function" && typeof value.get === "function"
|
|
12428
|
+
);
|
|
12429
|
+
}
|
|
12430
|
+
function foldBindingAliases(config) {
|
|
12431
|
+
const d1 = config.db?.d1 ?? config.d1;
|
|
12432
|
+
const r2 = config.storage?.r2 ?? config.r2;
|
|
12433
|
+
const sessionMode = config.db?.sessionMode ?? config.sessionMode;
|
|
12434
|
+
const prefix = config.storage?.prefix ?? config.storagePrefix;
|
|
12435
|
+
let next = { ...config };
|
|
12436
|
+
if (d1 !== void 0 || sessionMode !== void 0) {
|
|
12437
|
+
next = {
|
|
12438
|
+
...next,
|
|
12439
|
+
db: {
|
|
12440
|
+
...next.db,
|
|
12441
|
+
...d1 !== void 0 ? { d1 } : {},
|
|
12442
|
+
...sessionMode !== void 0 ? { sessionMode } : {}
|
|
12443
|
+
}
|
|
12444
|
+
};
|
|
12445
|
+
}
|
|
12446
|
+
if (r2 !== void 0 || prefix !== void 0) {
|
|
12447
|
+
next = {
|
|
12448
|
+
...next,
|
|
12449
|
+
storage: {
|
|
12450
|
+
...next.storage,
|
|
12451
|
+
...r2 !== void 0 ? { r2 } : {},
|
|
12452
|
+
...prefix !== void 0 ? { prefix } : {}
|
|
12453
|
+
}
|
|
12454
|
+
};
|
|
12455
|
+
}
|
|
12456
|
+
const {
|
|
12457
|
+
d1: _d1,
|
|
12458
|
+
r2: _r2,
|
|
12459
|
+
storagePrefix: _storagePrefix,
|
|
12460
|
+
sessionMode: _sessionMode,
|
|
12461
|
+
...rest
|
|
12462
|
+
} = next;
|
|
12463
|
+
return rest;
|
|
12464
|
+
}
|
|
12465
|
+
function applyExecutionMode(config) {
|
|
12466
|
+
const d1 = config.db?.d1;
|
|
12467
|
+
const hasD1 = isD1Binding2(d1);
|
|
12468
|
+
const hasUrl = Boolean(
|
|
12469
|
+
normalizeOptional2(config.url) ?? normalizeOptional2(config.db?.url) ?? (config.env ? normalizeOptional2(config.env.ATHENA_URL) ?? normalizeOptional2(config.env.NEXT_PUBLIC_ATHENA_URL) : void 0)
|
|
12470
|
+
);
|
|
12471
|
+
const hasModeHint = config.mode != null || config.prefer != null || Boolean(config.env?.ATHENA_EXECUTION_MODE) || Boolean(config.env?.ATHENA_EXECUTION_PREFER);
|
|
12472
|
+
if (!hasD1 && !hasModeHint) {
|
|
12473
|
+
return config;
|
|
12474
|
+
}
|
|
12475
|
+
if (hasD1 && !hasUrl && !hasModeHint) {
|
|
12476
|
+
return config;
|
|
12477
|
+
}
|
|
12478
|
+
let resolved;
|
|
12479
|
+
try {
|
|
12480
|
+
resolved = resolveAthenaExecutionMode({
|
|
12481
|
+
mode: config.mode,
|
|
12482
|
+
prefer: config.prefer,
|
|
12483
|
+
d1: hasD1 ? d1 : null,
|
|
12484
|
+
url: config.url ?? config.db?.url,
|
|
12485
|
+
env: config.env
|
|
12486
|
+
});
|
|
12487
|
+
} catch (error) {
|
|
12488
|
+
if (!hasModeHint) return config;
|
|
12489
|
+
throw error;
|
|
12490
|
+
}
|
|
12491
|
+
if (resolved === "gateway" && hasD1) {
|
|
12492
|
+
const { d1: _drop, sessionMode: _sm, ...dbRest } = config.db ?? {};
|
|
12493
|
+
return {
|
|
12494
|
+
...config,
|
|
12495
|
+
db: Object.keys(dbRest).length > 0 ? dbRest : void 0,
|
|
12496
|
+
gatewayTransport: void 0
|
|
12497
|
+
};
|
|
12498
|
+
}
|
|
12499
|
+
return config;
|
|
12500
|
+
}
|
|
12501
|
+
function resolveUnifiedRemoteRoot(config) {
|
|
12502
|
+
return normalizeOptional2(config.url) ?? readFirstEnv(config.env, ENV_URL_KEYS);
|
|
12503
|
+
}
|
|
12504
|
+
function isEdgeLocalSentinelUrl(url) {
|
|
12505
|
+
if (!url) return false;
|
|
12506
|
+
return url === CLOUDFLARE_EDGE_BASE_URL || url.startsWith("https://athena.local/") || url.startsWith("http://athena.local/");
|
|
12507
|
+
}
|
|
12508
|
+
function hasRemoteDbGatewayUrl(config) {
|
|
12509
|
+
const dbUrl = normalizeOptional2(config.db?.url) ?? readFirstEnv(config.env, ENV_DB_URL_KEYS);
|
|
12510
|
+
return Boolean(dbUrl && !isEdgeLocalSentinelUrl(dbUrl));
|
|
12511
|
+
}
|
|
12512
|
+
function hasRemoteHttpServices(config) {
|
|
12513
|
+
return Boolean(
|
|
12514
|
+
resolveUnifiedRemoteRoot(config) || hasRemoteDbGatewayUrl(config) || normalizeOptional2(config.auth?.url) || readFirstEnv(config.env, ENV_AUTH_URL_KEYS) || normalizeOptional2(config.storage?.url) || readFirstEnv(config.env, ENV_STORAGE_URL_KEYS) || normalizeOptional2(config.chat?.url) || readFirstEnv(config.env, ENV_CHAT_URL_KEYS) || normalizeOptional2(config.billing?.url)
|
|
12515
|
+
);
|
|
12516
|
+
}
|
|
12517
|
+
function hasRemoteHttpStorage(config) {
|
|
12518
|
+
return Boolean(
|
|
12519
|
+
normalizeOptional2(config.storage?.url) || readFirstEnv(config.env, ENV_STORAGE_URL_KEYS) || resolveUnifiedRemoteRoot(config)
|
|
12520
|
+
);
|
|
12521
|
+
}
|
|
12522
|
+
function hasRemoteAuthService(config) {
|
|
12523
|
+
return Boolean(
|
|
12524
|
+
normalizeOptional2(config.auth?.url) || readFirstEnv(config.env, ENV_AUTH_URL_KEYS) || resolveUnifiedRemoteRoot(config)
|
|
12525
|
+
);
|
|
12526
|
+
}
|
|
12527
|
+
function materializeEdgeBindings(config) {
|
|
12528
|
+
const d1 = config.db?.d1;
|
|
12529
|
+
const r2 = config.storage?.r2;
|
|
12530
|
+
const hasD1 = isD1Binding2(d1);
|
|
12531
|
+
const hasR2 = isR2Binding(r2);
|
|
12532
|
+
if (!hasD1 && !hasR2) {
|
|
12533
|
+
return config;
|
|
12534
|
+
}
|
|
12535
|
+
if (hasD1 && d1 && typeof d1.prepare !== "function") {
|
|
12536
|
+
throw new AthenaConfigurationError(
|
|
12537
|
+
"ATHENA_NO_SERVICE_CONFIGURED",
|
|
12538
|
+
"db.d1 must be a D1 binding with prepare().",
|
|
12539
|
+
"db"
|
|
12540
|
+
);
|
|
12541
|
+
}
|
|
12542
|
+
const remoteRoot = resolveUnifiedRemoteRoot(config);
|
|
12543
|
+
const remoteServices = hasRemoteHttpServices(config);
|
|
12544
|
+
const remoteStorage = hasRemoteHttpStorage(config);
|
|
12545
|
+
const remoteAuth = hasRemoteAuthService(config);
|
|
12546
|
+
const next = { ...config };
|
|
12547
|
+
if (hasD1 && d1) {
|
|
12548
|
+
if (!config.gatewayTransport) {
|
|
12549
|
+
next.gatewayTransport = createCloudflareD1GatewayTransport({
|
|
12550
|
+
d1,
|
|
12551
|
+
defaultSessionMode: config.db?.sessionMode
|
|
12552
|
+
});
|
|
12553
|
+
}
|
|
12554
|
+
const explicitDbUrl = normalizeOptional2(config.db?.url);
|
|
12555
|
+
const remoteDbGateway = hasRemoteDbGatewayUrl(config);
|
|
12556
|
+
next.db = {
|
|
12557
|
+
...config.db,
|
|
12558
|
+
d1,
|
|
12559
|
+
url: explicitDbUrl ?? (remoteDbGateway ? void 0 : CLOUDFLARE_EDGE_BASE_URL)
|
|
12560
|
+
};
|
|
12561
|
+
const explicitKey = normalizeOptional2(config.key);
|
|
12562
|
+
if (explicitKey) {
|
|
12563
|
+
next.key = explicitKey;
|
|
12564
|
+
} else if (!remoteServices) {
|
|
12565
|
+
next.key = CLOUDFLARE_EDGE_API_KEY;
|
|
12566
|
+
} else {
|
|
12567
|
+
next.key = void 0;
|
|
12568
|
+
}
|
|
12569
|
+
if (remoteRoot) {
|
|
12570
|
+
next.billing = {
|
|
12571
|
+
...config.billing ?? {},
|
|
12572
|
+
url: normalizeOptional2(config.billing?.url) ?? remoteRoot
|
|
12573
|
+
};
|
|
12574
|
+
}
|
|
12575
|
+
if (!config.capabilities) {
|
|
12576
|
+
next.capabilities = createCloudflareEdgeCapabilities({
|
|
12577
|
+
hasR2,
|
|
12578
|
+
// Explicit storage.url / env storage URL / unified remote root all count.
|
|
12579
|
+
hasRemoteStorage: remoteStorage,
|
|
12580
|
+
authRemote: remoteAuth,
|
|
12581
|
+
findManyAst: false
|
|
12582
|
+
});
|
|
12583
|
+
}
|
|
12584
|
+
} else if (hasR2 && r2) {
|
|
12585
|
+
if (!remoteRoot && !normalizeOptional2(config.db?.url) && !normalizeOptional2(config.storage?.url) && !readFirstEnv(config.env, ENV_STORAGE_URL_KEYS)) {
|
|
12586
|
+
next.storage = {
|
|
12587
|
+
...config.storage,
|
|
12588
|
+
r2,
|
|
12589
|
+
// Local sentinel so resolveCore accepts a storage-only binding client.
|
|
12590
|
+
url: CLOUDFLARE_EDGE_BASE_URL
|
|
12591
|
+
};
|
|
12592
|
+
if (!remoteServices) {
|
|
12593
|
+
next.key = normalizeOptional2(config.key) ?? CLOUDFLARE_EDGE_API_KEY;
|
|
12594
|
+
} else if (normalizeOptional2(config.key)) {
|
|
12595
|
+
next.key = normalizeOptional2(config.key);
|
|
12596
|
+
} else {
|
|
12597
|
+
next.key = void 0;
|
|
12598
|
+
}
|
|
12599
|
+
}
|
|
12600
|
+
if (!config.capabilities) {
|
|
12601
|
+
if (remoteRoot || normalizeOptional2(config.db?.url) || readFirstEnv(config.env, ENV_DB_URL_KEYS)) {
|
|
12602
|
+
const base = createGatewayCapabilities({
|
|
12603
|
+
authRemote: remoteAuth,
|
|
12604
|
+
storageConfigured: true
|
|
12605
|
+
});
|
|
12606
|
+
next.capabilities = {
|
|
12607
|
+
...base,
|
|
12608
|
+
storage: {
|
|
12609
|
+
...base.storage,
|
|
12610
|
+
local: true,
|
|
12611
|
+
objects: true
|
|
12612
|
+
}
|
|
12613
|
+
};
|
|
12614
|
+
} else {
|
|
12615
|
+
next.capabilities = {
|
|
12616
|
+
mode: "cloudflare-edge",
|
|
12617
|
+
db: {
|
|
12618
|
+
engine: "unknown",
|
|
12619
|
+
local: false,
|
|
12620
|
+
layers: {
|
|
12621
|
+
query: false,
|
|
12622
|
+
flatCrud: false,
|
|
12623
|
+
findManyAst: false,
|
|
12624
|
+
rpc: false,
|
|
12625
|
+
relations: false
|
|
12626
|
+
}
|
|
12627
|
+
},
|
|
12628
|
+
storage: {
|
|
12629
|
+
local: true,
|
|
12630
|
+
objects: true,
|
|
12631
|
+
catalogs: false,
|
|
12632
|
+
backups: false
|
|
12633
|
+
},
|
|
12634
|
+
auth: {
|
|
12635
|
+
remote: remoteAuth
|
|
12636
|
+
}
|
|
12637
|
+
};
|
|
12638
|
+
}
|
|
12639
|
+
}
|
|
12640
|
+
}
|
|
12641
|
+
return next;
|
|
12642
|
+
}
|
|
12643
|
+
function normalizeCreateClientConfig(config) {
|
|
12644
|
+
return materializeEdgeBindings(applyExecutionMode(foldBindingAliases(config)));
|
|
12645
|
+
}
|
|
9662
12646
|
function createClientView(core, viewContext) {
|
|
9663
12647
|
const resolved = createInternalClientView(
|
|
9664
12648
|
core.internalCore,
|
|
@@ -9676,12 +12660,23 @@ function createClientView(core, viewContext) {
|
|
|
9676
12660
|
},
|
|
9677
12661
|
...billingOptions
|
|
9678
12662
|
}) : createUnavailableNamespace("billing", core.urls);
|
|
12663
|
+
const capabilities = core.config.capabilities ?? createGatewayCapabilities({
|
|
12664
|
+
authRemote: Boolean(core.urls.auth),
|
|
12665
|
+
// Match unavailable storage proxy when no storage URL was resolved.
|
|
12666
|
+
storageConfigured: Boolean(core.urls.storage)
|
|
12667
|
+
});
|
|
12668
|
+
const r2 = core.config.storage?.r2;
|
|
12669
|
+
const storageModule = isR2Binding(r2) ? createCloudflareR2StorageModule({
|
|
12670
|
+
r2,
|
|
12671
|
+
prefix: core.config.storage?.prefix ?? void 0
|
|
12672
|
+
}) : core.urls.storage ? resolved.storage : createUnavailableNamespace("storage", core.urls);
|
|
9679
12673
|
const client = {
|
|
9680
12674
|
db: core.urls.db ? resolved.db : createUnavailableNamespace("db", core.urls),
|
|
9681
12675
|
auth: core.urls.auth ? resolved.auth : createUnavailableNamespace("auth", core.urls),
|
|
9682
12676
|
chat: core.urls.chat ? resolved.chat : createUnavailableNamespace("chat", core.urls),
|
|
9683
|
-
storage:
|
|
12677
|
+
storage: storageModule,
|
|
9684
12678
|
billing: billingModule,
|
|
12679
|
+
capabilities,
|
|
9685
12680
|
from: ((...args) => {
|
|
9686
12681
|
requireDb();
|
|
9687
12682
|
return Reflect.apply(resolved.from, resolved, args);
|
|
@@ -9705,13 +12700,34 @@ function createClientView(core, viewContext) {
|
|
|
9705
12700
|
return resolved.verifyConnection(options);
|
|
9706
12701
|
},
|
|
9707
12702
|
withContext(context) {
|
|
12703
|
+
warnIfEmptyRequestContext(context);
|
|
9708
12704
|
return createClientView(core, mergeAthenaRequestContexts(viewContext, context));
|
|
9709
12705
|
}
|
|
9710
12706
|
};
|
|
9711
12707
|
return Object.freeze(client);
|
|
9712
12708
|
}
|
|
12709
|
+
function isEmptyAthenaRequestContext(context) {
|
|
12710
|
+
if (!context) return true;
|
|
12711
|
+
const hasHeaders = context.headers != null && Object.keys(context.headers).length > 0;
|
|
12712
|
+
return context.userId == null && context.organizationId == null && !normalizeOptionalContextString(context.cookie) && !normalizeOptionalContextString(context.bearerToken) && !normalizeOptionalContextString(context.sessionToken) && !context.forceNoCache && !hasHeaders;
|
|
12713
|
+
}
|
|
12714
|
+
function normalizeOptionalContextString(value) {
|
|
12715
|
+
const trimmed = value?.trim();
|
|
12716
|
+
return trimmed || void 0;
|
|
12717
|
+
}
|
|
12718
|
+
function warnIfEmptyRequestContext(context) {
|
|
12719
|
+
if (!isEmptyAthenaRequestContext(context)) return;
|
|
12720
|
+
const nodeEnv = globalThis.process?.env?.NODE_ENV;
|
|
12721
|
+
if (nodeEnv === "production") {
|
|
12722
|
+
return;
|
|
12723
|
+
}
|
|
12724
|
+
console.warn(
|
|
12725
|
+
"[athena] withContext({}) has no userId, organizationId, cookie, bearerToken, sessionToken, headers, or forceNoCache. Gateway scope headers will not change. Pass identity fields, or use createAthenaServerClient({ session, scope })."
|
|
12726
|
+
);
|
|
12727
|
+
}
|
|
9713
12728
|
function createClient(config) {
|
|
9714
|
-
|
|
12729
|
+
const normalized = normalizeCreateClientConfig(config);
|
|
12730
|
+
return createClientView(resolveCore(normalized));
|
|
9715
12731
|
}
|
|
9716
12732
|
|
|
9717
12733
|
// src/next/session-bridge/constants.ts
|
|
@@ -10002,7 +13018,7 @@ function stripAthenaAuthPath(pathname) {
|
|
|
10002
13018
|
}
|
|
10003
13019
|
return normalizedPath;
|
|
10004
13020
|
}
|
|
10005
|
-
function
|
|
13021
|
+
function readProcessEnv3() {
|
|
10006
13022
|
try {
|
|
10007
13023
|
const maybeProcess = globalThis.process;
|
|
10008
13024
|
return maybeProcess?.env;
|
|
@@ -10039,7 +13055,7 @@ function resolveConfiguredAthenaAuthUpstreamUrl(rawUpstreamUrl) {
|
|
|
10039
13055
|
if (rawUpstreamUrl) {
|
|
10040
13056
|
return readAthenaAuthUpstreamUrlFromEnv(rawUpstreamUrl);
|
|
10041
13057
|
}
|
|
10042
|
-
const processEnv =
|
|
13058
|
+
const processEnv = readProcessEnv3();
|
|
10043
13059
|
return processEnv ? readAthenaAuthUpstreamUrlFromEnv(processEnv) : void 0;
|
|
10044
13060
|
}
|
|
10045
13061
|
function normalizeAthenaAuthBaseUrl(urlOrPath) {
|