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