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