@hot-updater/cloudflare 1.0.0-rc.4 → 1.0.0-rc.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/index.cjs +93 -918
  2. package/dist/index.d.cts +1030 -4
  3. package/dist/index.d.mts +1030 -4
  4. package/dist/index.mjs +93 -920
  5. package/dist/init/index.cjs +11773 -0
  6. package/dist/init/index.d.cts +5 -1
  7. package/dist/init/index.d.mts +5 -1
  8. package/dist/init/index.mjs +11766 -1
  9. package/dist/worker/index.cjs +60 -911
  10. package/dist/worker/index.d.cts +1030 -9
  11. package/dist/worker/index.d.mts +1030 -9
  12. package/dist/worker/index.mjs +61 -913
  13. package/package.json +8 -12
  14. package/sql/bundles.sql +121 -212
  15. package/src/d1Database.ts +58 -43
  16. package/src/d1Executor.ts +84 -0
  17. package/src/d1Schema.ts +26 -0
  18. package/src/index.ts +1 -0
  19. package/src/plugins.ts +9 -0
  20. package/src/r2S3Storage.ts +4 -4
  21. package/src/r2Storage.ts +2 -2
  22. package/src/r2WorkerStorage.ts +4 -4
  23. package/src/worker/d1Database.ts +21 -35
  24. package/src/worker/index.ts +1 -0
  25. package/worker/dist/README.md +1 -1
  26. package/worker/dist/index.js +10252 -6054
  27. package/worker/dist/index.js.map +4 -4
  28. package/worker/migrations/0001_hot-updater_1.0.0.sql +121 -222
  29. package/worker/src/index.ts +2 -2
  30. package/dist/iac/index.cjs +0 -12688
  31. package/dist/iac/index.d.cts +0 -5
  32. package/dist/iac/index.d.mts +0 -5
  33. package/dist/iac/index.mjs +0 -12680
  34. package/src/d1Database.spec.ts +0 -277
  35. package/src/d1Implementation.spec.ts +0 -342
  36. package/src/d1Implementation.ts +0 -781
  37. package/src/d1Query.spec.ts +0 -46
  38. package/src/d1Query.ts +0 -92
  39. package/src/d1Rows.spec.ts +0 -143
  40. package/src/d1Rows.ts +0 -361
  41. package/src/d1Sql.spec.ts +0 -30
  42. package/src/d1Sql.ts +0 -175
  43. package/src/r2Storage.spec.ts +0 -346
  44. package/src/r2WorkerStorage.spec.ts +0 -184
  45. package/src/utils/createWrangler.spec.ts +0 -75
  46. package/src/worker/d1Database.spec.ts +0 -69
  47. package/worker/src/databaseMigration.integration.spec.ts +0 -191
  48. package/worker/src/databasePlugins.integration.spec.ts +0 -326
  49. package/worker/src/index.integration.spec.ts +0 -190
  50. package/worker/src/insightsMovement.integration.spec.ts +0 -73
  51. package/worker/src/storagePlugin.integration.spec.ts +0 -59
  52. package/worker/src/testWorker.ts +0 -5
package/dist/index.mjs CHANGED
@@ -1,950 +1,112 @@
1
- import { createDatabasePlugin, createStorageDownloadUrl, createStorageKeyBuilder, createStoragePlugin, createStorageUri, isDatabaseMetadataObject, parseStorageUri } from "@hot-updater/plugin-core";
2
- import { createDatabasePluginAdapter } from "@hot-updater/plugin-core/internal";
1
+ import { WRITE_GUARD_TABLE, coreSettings, coreTarget, createEngineDatabase, createSqlAdapter, createStorageAdapter, createStorageDownloadUrl, createStorageKeyBuilder, createStorageUri, createTableStatements, generateEngineSql, parseStorageUri } from "@hot-updater/plugin-core";
3
2
  import Cloudflare from "cloudflare";
4
3
  import { DeleteObjectCommand, GetObjectCommand, HeadObjectCommand, S3Client } from "@aws-sdk/client-s3";
5
4
  import { Upload } from "@aws-sdk/lib-storage";
6
- //#region src/d1Rows.ts
7
- var InvalidD1RowError = class extends Error {
8
- name = "InvalidD1RowError";
9
- model;
10
- constructor(model) {
11
- super(`D1 returned an invalid ${model} row`);
12
- this.model = model;
13
- }
14
- };
15
- const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
16
- const stringValue = (row, field, model) => {
17
- const value = row[field];
18
- if (typeof value !== "string") throw new InvalidD1RowError(model);
19
- return value;
20
- };
21
- const nullableString = (row, field, model) => {
22
- const value = row[field];
23
- if (value === null) return null;
24
- if (typeof value !== "string") throw new InvalidD1RowError(model);
25
- return value;
26
- };
27
- const numberValue = (row, field, model) => {
28
- const value = row[field];
29
- if (typeof value !== "number") throw new InvalidD1RowError(model);
30
- return value;
31
- };
32
- const byteSizeValue = (row, field, model) => {
33
- const value = row[field];
34
- if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new InvalidD1RowError(model);
35
- return value;
36
- };
37
- const booleanValue = (row, field, model) => {
38
- const value = row[field];
39
- if (value === true || value === 1) return true;
40
- if (value === false || value === 0) return false;
41
- throw new InvalidD1RowError(model);
42
- };
43
- const jsonValue = (value, model) => {
44
- if (typeof value !== "string") throw new InvalidD1RowError(model);
45
- try {
46
- return JSON.parse(value);
47
- } catch (error) {
48
- if (error instanceof SyntaxError) throw new InvalidD1RowError(model);
49
- throw error;
50
- }
51
- };
52
- const metadata = (row) => {
53
- const value = jsonValue(row["metadata"], "bundles");
54
- if (!isDatabaseMetadataObject(value)) throw new InvalidD1RowError("bundles");
55
- return value;
56
- };
57
- const bundleRow = (row) => {
58
- const platform = stringValue(row, "platform", "bundles");
59
- if (platform !== "ios" && platform !== "android") throw new InvalidD1RowError("bundles");
60
- return {
61
- id: stringValue(row, "id", "bundles"),
62
- platform,
63
- file_hash: stringValue(row, "file_hash", "bundles"),
64
- git_commit_hash: nullableString(row, "git_commit_hash", "bundles"),
65
- storage_uri: stringValue(row, "storage_uri", "bundles"),
66
- archive_byte_size: row["archive_byte_size"] === void 0 ? 0 : byteSizeValue(row, "archive_byte_size", "bundles"),
67
- metadata: metadata(row),
68
- manifest_storage_uri: nullableString(row, "manifest_storage_uri", "bundles"),
69
- manifest_file_hash: nullableString(row, "manifest_file_hash", "bundles"),
70
- asset_base_storage_uri: nullableString(row, "asset_base_storage_uri", "bundles")
71
- };
72
- };
73
- const patchRow = (row) => ({
74
- id: stringValue(row, "id", "bundle_patches"),
75
- bundle_id: stringValue(row, "bundle_id", "bundle_patches"),
76
- base_bundle_id: stringValue(row, "base_bundle_id", "bundle_patches"),
77
- base_file_hash: stringValue(row, "base_file_hash", "bundle_patches"),
78
- patch_file_hash: stringValue(row, "patch_file_hash", "bundle_patches"),
79
- patch_storage_uri: stringValue(row, "patch_storage_uri", "bundle_patches"),
80
- byte_size: byteSizeValue(row, "byte_size", "bundle_patches"),
81
- order_index: numberValue(row, "order_index", "bundle_patches")
82
- });
83
- const channelRow = (row) => ({
84
- id: stringValue(row, "id", "channels"),
85
- name: stringValue(row, "name", "channels")
86
- });
87
- const eventRow = (row) => {
88
- const type = stringValue(row, "type", "bundle_events");
89
- const platform = stringValue(row, "platform", "bundle_events");
90
- const fromBundleId = nullableString(row, "from_bundle_id", "bundle_events");
91
- const updateStrategy = nullableString(row, "update_strategy", "bundle_events");
92
- if (platform !== "ios" && platform !== "android" || !((type === "UPDATE_APPLIED" || type === "RECOVERED" || type === "RELEASE_ADOPTED") && typeof fromBundleId === "string" && (updateStrategy === "fingerprint" || updateStrategy === "appVersion") || type === "UNCHANGED" && fromBundleId === null && updateStrategy === null)) throw new InvalidD1RowError("bundle_events");
93
- return {
94
- id: stringValue(row, "id", "bundle_events"),
95
- type,
96
- install_id: stringValue(row, "install_id", "bundle_events"),
97
- user_id: nullableString(row, "user_id", "bundle_events"),
98
- username: nullableString(row, "username", "bundle_events"),
99
- from_release_id: nullableString(row, "from_release_id", "bundle_events"),
100
- from_bundle_id: fromBundleId,
101
- to_release_id: nullableString(row, "to_release_id", "bundle_events"),
102
- to_bundle_id: stringValue(row, "to_bundle_id", "bundle_events"),
103
- platform,
104
- app_version: stringValue(row, "app_version", "bundle_events"),
105
- channel: stringValue(row, "channel", "bundle_events"),
106
- cohort: stringValue(row, "cohort", "bundle_events"),
107
- update_strategy: updateStrategy,
108
- fingerprint_hash: nullableString(row, "fingerprint_hash", "bundle_events"),
109
- sdk_version: nullableString(row, "sdk_version", "bundle_events"),
110
- received_at_ms: numberValue(row, "received_at_ms", "bundle_events")
111
- };
112
- };
113
- const installationRow = (row) => {
114
- const type = stringValue(row, "type", "bundle_installations");
115
- const platform = stringValue(row, "platform", "bundle_installations");
116
- if (![
117
- "UPDATE_APPLIED",
118
- "RECOVERED",
119
- "RELEASE_ADOPTED",
120
- "UNCHANGED"
121
- ].includes(type) || platform !== "ios" && platform !== "android") throw new InvalidD1RowError("bundle_installations");
122
- return {
123
- id: stringValue(row, "id", "bundle_installations"),
124
- install_id: stringValue(row, "install_id", "bundle_installations"),
125
- user_id: nullableString(row, "user_id", "bundle_installations"),
126
- username: nullableString(row, "username", "bundle_installations"),
127
- to_bundle_id: stringValue(row, "to_bundle_id", "bundle_installations"),
128
- type,
129
- platform,
130
- app_version: stringValue(row, "app_version", "bundle_installations"),
131
- channel: stringValue(row, "channel", "bundle_installations"),
132
- cohort: stringValue(row, "cohort", "bundle_installations"),
133
- received_at_ms: numberValue(row, "received_at_ms", "bundle_installations")
134
- };
135
- };
136
- const apiKeyRow = (row) => {
137
- const role = stringValue(row, "role", "api_keys");
138
- if (role !== "client") throw new InvalidD1RowError("api_keys");
139
- const revokedAt = row["revoked_at_ms"];
140
- return {
141
- id: stringValue(row, "id", "api_keys"),
142
- hash: stringValue(row, "hash", "api_keys"),
143
- name: stringValue(row, "name", "api_keys"),
144
- prefix: stringValue(row, "prefix", "api_keys"),
145
- role,
146
- created_at_ms: numberValue(row, "created_at_ms", "api_keys"),
147
- revoked_at_ms: revokedAt === null ? null : numberValue(row, "revoked_at_ms", "api_keys")
148
- };
149
- };
150
- const releaseTargetCohorts = (row) => {
151
- const value = jsonValue(row["target_cohorts"], "releases");
152
- if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) throw new InvalidD1RowError("releases");
153
- return value.filter((item) => typeof item === "string");
154
- };
155
- const releaseRow = (row) => {
156
- const platform = stringValue(row, "platform", "releases");
157
- const kind = stringValue(row, "kind", "releases");
158
- const strategy = stringValue(row, "strategy", "releases");
159
- const operation = stringValue(row, "operation", "releases");
160
- if (platform !== "ios" && platform !== "android" || kind !== "BUNDLE" && kind !== "EMBEDDED" || strategy !== "APP_VERSION" && strategy !== "FINGERPRINT" || operation !== "DEPLOY" && operation !== "PROMOTE" && operation !== "ROLLBACK") throw new InvalidD1RowError("releases");
161
- return {
162
- id: stringValue(row, "id", "releases"),
163
- revision: numberValue(row, "revision", "releases"),
164
- scope_key: stringValue(row, "scope_key", "releases"),
165
- channel_id: stringValue(row, "channel_id", "releases"),
166
- platform,
167
- kind,
168
- bundle_id: nullableString(row, "bundle_id", "releases"),
169
- strategy,
170
- target_app_version: nullableString(row, "target_app_version", "releases"),
171
- fingerprint_hash: nullableString(row, "fingerprint_hash", "releases"),
172
- enabled: booleanValue(row, "enabled", "releases"),
173
- should_force_update: booleanValue(row, "should_force_update", "releases"),
174
- message: nullableString(row, "message", "releases"),
175
- rollout_cohort_count: numberValue(row, "rollout_cohort_count", "releases"),
176
- target_cohorts: releaseTargetCohorts(row),
177
- operation,
178
- source_release_id: nullableString(row, "source_release_id", "releases"),
179
- created_at_ms: numberValue(row, "created_at_ms", "releases"),
180
- updated_at_ms: numberValue(row, "updated_at_ms", "releases")
181
- };
182
- };
183
- const releaseCatalogRow = (row) => {
184
- const platform = stringValue(row, "platform", "release_catalogs");
185
- const strategy = stringValue(row, "strategy", "release_catalogs");
186
- if (platform !== "ios" && platform !== "android" || strategy !== "APP_VERSION" && strategy !== "FINGERPRINT") throw new InvalidD1RowError("release_catalogs");
187
- return {
188
- scope_key: stringValue(row, "scope_key", "release_catalogs"),
189
- catalog_id: stringValue(row, "catalog_id", "release_catalogs"),
190
- strategy,
191
- channel_id: stringValue(row, "channel_id", "release_catalogs"),
192
- channel_key: stringValue(row, "channel_key", "release_catalogs"),
193
- platform,
194
- fingerprint_hash: nullableString(row, "fingerprint_hash", "release_catalogs"),
195
- generation: numberValue(row, "generation", "release_catalogs"),
196
- payload: stringValue(row, "payload", "release_catalogs"),
197
- catalog_hash: stringValue(row, "catalog_hash", "release_catalogs"),
198
- byte_size: numberValue(row, "byte_size", "release_catalogs"),
199
- is_tombstone: booleanValue(row, "is_tombstone", "release_catalogs"),
200
- updated_at_ms: numberValue(row, "updated_at_ms", "release_catalogs")
201
- };
202
- };
203
- function parseD1Row(model, value) {
204
- if (!isRecord(value)) throw new InvalidD1RowError(model);
205
- switch (model) {
206
- case "bundles": return bundleRow(value);
207
- case "bundle_patches": return patchRow(value);
208
- case "channels": return channelRow(value);
209
- case "bundle_events": return eventRow(value);
210
- case "bundle_installations": return installationRow(value);
211
- case "api_keys": return apiKeyRow(value);
212
- case "releases": return releaseRow(value);
213
- case "release_catalogs": return releaseCatalogRow(value);
214
- }
215
- }
216
- //#endregion
217
- //#region src/d1Sql.ts
218
- var InvalidD1PredicateError = class extends Error {
219
- name = "InvalidD1PredicateError";
220
- };
221
- const encodeD1Value = (value) => {
222
- const encoded = JSON.stringify(value);
223
- if (encoded === void 0) throw new TypeError("D1 values must be JSON-serializable.");
224
- return encoded;
225
- };
226
- const bind = (value) => ({
227
- sql: "json_extract(?, '$')",
228
- params: [encodeD1Value(value)]
229
- });
230
- const escapeLikePattern = (value) => value.replaceAll("\\", "\\\\").replaceAll("%", "\\%").replaceAll("_", "\\_");
231
- const stringPredicate = (condition, operator) => {
232
- if (typeof condition.value !== "string") throw new InvalidD1PredicateError();
233
- if (condition.mode !== "insensitive") {
234
- const parameter = bind(condition.value);
235
- const column = `${condition.field} COLLATE BINARY`;
236
- const value = `${parameter.sql} COLLATE BINARY`;
237
- if (operator === "contains" || operator === "starts_with") return {
238
- sql: `instr(${column}, ${value}) ${operator === "contains" ? "> 0" : "= 1"}`,
239
- params: parameter.params
240
- };
241
- return {
242
- sql: `substr(${column}, length(${condition.field}) - length(${parameter.sql}) + 1) = ${value}`,
243
- params: [...parameter.params, ...parameter.params]
244
- };
245
- }
246
- const literal = escapeLikePattern(condition.value);
247
- const pattern = operator === "contains" ? `%${literal}%` : operator === "starts_with" ? `${literal}%` : `%${literal}`;
248
- const parameter = bind(pattern);
249
- return {
250
- sql: `lower(${condition.field}) LIKE lower(${parameter.sql}) ESCAPE '\\'`,
251
- params: parameter.params
252
- };
253
- };
254
- const predicate = (condition) => {
255
- const operator = condition.operator ?? "eq";
256
- switch (operator) {
257
- case "eq":
258
- case "ne": {
259
- if (condition.value === null) return {
260
- sql: `${condition.field} IS ${operator === "ne" ? "NOT " : ""}NULL`,
261
- params: []
262
- };
263
- const parameter = bind(condition.value);
264
- const insensitive = "mode" in condition && condition.mode === "insensitive";
265
- const column = insensitive ? `lower(${condition.field})` : condition.field;
266
- const value = insensitive ? `lower(${parameter.sql})` : parameter.sql;
267
- return {
268
- sql: `${column} ${operator === "eq" ? "=" : "<>"} ${value}`,
269
- params: parameter.params
270
- };
271
- }
272
- case "gt":
273
- case "gte":
274
- case "lt":
275
- case "lte": {
276
- const sqlOperator = {
277
- gt: ">",
278
- gte: ">=",
279
- lt: "<",
280
- lte: "<="
281
- }[operator];
282
- const parameter = bind(condition.value);
283
- return {
284
- sql: `${condition.field} ${sqlOperator} ${parameter.sql}`,
285
- params: parameter.params
286
- };
287
- }
288
- case "in":
289
- case "not_in":
290
- if (!Array.isArray(condition.value)) throw new InvalidD1PredicateError();
291
- if (condition.value.length === 0) return {
292
- sql: operator === "not_in" ? "1 = 1" : "1 = 0",
293
- params: []
294
- };
295
- return {
296
- sql: `${condition.field} ${operator === "not_in" ? "NOT " : ""}IN (SELECT value FROM json_each(?))`,
297
- params: [encodeD1Value(condition.value)]
298
- };
299
- case "contains":
300
- case "starts_with":
301
- case "ends_with": return stringPredicate(condition, operator);
302
- }
303
- };
304
- const buildD1Where = (where) => {
305
- const [first, ...rest] = where ?? [];
306
- if (first === void 0) return {
307
- sql: "",
308
- params: []
309
- };
310
- const initial = predicate(first);
311
- let sql = initial.sql;
312
- const params = [...initial.params];
313
- for (const condition of rest) {
314
- const next = predicate(condition);
315
- sql = `(${sql} ${condition.connector === "OR" ? "OR" : "AND"} ${next.sql})`;
316
- params.push(...next.params);
317
- }
318
- return {
319
- sql: ` WHERE ${sql}`,
320
- params
321
- };
322
- };
323
- const buildD1Order = (orderBy) => orderBy === void 0 ? "" : ` ORDER BY ${orderBy.map((clause) => `${clause.field} ${clause.direction.toUpperCase()}${clause.nulls ? ` NULLS ${clause.nulls.toUpperCase()}` : ""}`).join(", ")}`;
324
- const d1Placeholders = (count) => Array.from({ length: count }, () => "json_extract(?, '$')").join(", ");
325
- const encodeD1Values = (values) => values.map(encodeD1Value);
326
- //#endregion
327
- //#region src/d1Query.ts
328
- const d1TableNames = {
329
- bundles: "bundles",
330
- bundle_patches: "bundle_patches",
331
- channels: "channels",
332
- bundle_events: "bundle_events",
333
- bundle_installations: "bundle_installations",
334
- api_keys: "api_keys",
335
- release_catalogs: "release_catalogs",
336
- releases: "releases"
337
- };
338
- var D1QueryResultError = class extends Error {
339
- result;
340
- name = "D1QueryResultError";
341
- operation = "count";
342
- constructor(result) {
343
- super("D1 count query returned a malformed first row");
344
- this.result = result;
345
- }
346
- };
347
- const countD1Rows = async (executor, input) => {
348
- const where = buildD1Where(input.where);
349
- const table = d1TableNames[input.model];
350
- const source = input.distinct === void 0 ? `${table}${where.sql}` : `(SELECT DISTINCT ${input.distinct.join(", ")} FROM ${table}${where.sql}) AS distinct_rows`;
351
- const row = (await executor.query(`SELECT COUNT(*) AS count FROM ${source}`, where.params))[0];
352
- if (typeof row !== "object" || row === null || Array.isArray(row)) throw new D1QueryResultError(row);
353
- const count = Reflect.get(row, "count");
354
- if (typeof count !== "number" || !Number.isFinite(count)) throw new D1QueryResultError(row);
355
- return count;
356
- };
357
- const findManyD1Rows = async (executor, input) => {
358
- const where = buildD1Where(input.where);
359
- const orderBy = input.orderBy;
360
- const order = buildD1Order(orderBy);
361
- const table = d1TableNames[input.model];
362
- const source = input.distinctOn === void 0 ? `SELECT * FROM ${table}${where.sql}${order}` : `SELECT * FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY ${input.distinctOn.fields.join(", ")}${order}) AS __hot_updater_rank FROM ${table}${where.sql}) AS distinct_rows WHERE __hot_updater_rank = 1${order}`;
363
- const pageParams = encodeD1Values([input.limit, input.offset]);
364
- const rows = await executor.query(`${source} LIMIT json_extract(?, '$') OFFSET json_extract(?, '$')`, [...where.params, ...pageParams]);
365
- switch (input.model) {
366
- case "bundles": return rows.map((row) => parseD1Row("bundles", row));
367
- case "bundle_patches": return rows.map((row) => parseD1Row("bundle_patches", row));
368
- case "channels": return rows.map((row) => parseD1Row("channels", row));
369
- case "bundle_events": return rows.map((row) => parseD1Row("bundle_events", row));
370
- case "bundle_installations": return rows.map((row) => parseD1Row("bundle_installations", row));
371
- case "api_keys": return rows.map((row) => parseD1Row("api_keys", row));
372
- case "releases": return rows.map((row) => parseD1Row("releases", row));
373
- case "release_catalogs": return rows.map((row) => parseD1Row("release_catalogs", row));
374
- }
375
- };
376
- //#endregion
377
- //#region src/d1Implementation.ts
5
+ import { apiKeys } from "@hot-updater/server/plugins/api-keys";
6
+ import { insights } from "@hot-updater/server/plugins/insights";
7
+ import { remoteConfig } from "@hot-updater/server/plugins/remote-config";
8
+ //#region src/d1Executor.ts
378
9
  var D1ExecutionError = class extends Error {
379
10
  name = "D1ExecutionError";
380
11
  constructor() {
381
12
  super("D1 did not successfully execute every requested statement");
382
13
  }
383
14
  };
384
- const EXPECTATION_CONFLICT_MARKER = "HOT_UPDATER_COMMIT_EXPECTATION_CONFLICT";
385
- const expectationGuard = (expectations) => {
386
- const clauses = [];
387
- const params = [];
388
- for (const expectation of expectations) {
389
- const isRelease = expectation.model === "releases";
390
- const table = isRelease ? "releases" : "release_catalogs";
391
- const keyField = isRelease ? "id" : "scope_key";
392
- const versionField = isRelease ? "revision" : "generation";
393
- const key = isRelease ? expectation.id : expectation.scopeKey;
394
- const version = isRelease ? expectation.revision : expectation.generation;
395
- if (version === null) {
396
- clauses.push(`NOT EXISTS (SELECT 1 FROM ${table} WHERE ${keyField} = json_extract(?, '$'))`);
397
- params.push(...encodeD1Values([key]));
398
- } else {
399
- clauses.push(`EXISTS (SELECT 1 FROM ${table} WHERE ${keyField} = json_extract(?, '$') AND ${versionField} = json_extract(?, '$'))`);
400
- params.push(...encodeD1Values([key, version]));
401
- }
402
- }
15
+ const toSqlResult = (result) => {
16
+ if (result.success === false) throw new D1ExecutionError();
403
17
  return {
404
- sql: clauses.join(" AND ") || "1",
405
- params
18
+ rows: result.results ?? [],
19
+ changes: result.meta?.changes ?? 0
406
20
  };
407
21
  };
408
- const readVersion = (row, field) => {
409
- if (typeof row !== "object" || row === null) return null;
410
- const value = Reflect.get(row, field);
411
- return typeof value === "number" ? value : null;
412
- };
413
- const expectationConflict = async (executor, expectations) => {
414
- for (const expectation of expectations) {
415
- const isRelease = expectation.model === "releases";
416
- const table = isRelease ? "releases" : "release_catalogs";
417
- const keyField = isRelease ? "id" : "scope_key";
418
- const versionField = isRelease ? "revision" : "generation";
419
- const key = isRelease ? expectation.id : expectation.scopeKey;
420
- const expectedVersion = isRelease ? expectation.revision : expectation.generation;
421
- const rows = await executor.query(`SELECT ${versionField} FROM ${table} WHERE ${keyField} = json_extract(?, '$') LIMIT 1`, encodeD1Values([key]));
422
- const actualVersion = readVersion(rows[0], versionField);
423
- if (actualVersion !== expectedVersion) return {
424
- committed: false,
425
- conflict: {
426
- actualVersion,
427
- changeIndex: -1,
428
- expectedVersion,
429
- key,
430
- model: expectation.model,
431
- reason: "version_conflict"
432
- }
433
- };
434
- }
435
- return null;
436
- };
437
- const isExpectationConflictError = (error) => {
22
+ /** D1 reports SQLite errors in the message; the SQL core classifies codes. */
23
+ const withSqliteCode = (error) => {
438
24
  const message = error instanceof Error ? error.message : String(error);
439
- return message.includes(EXPECTATION_CONFLICT_MARKER) || message.toLowerCase().includes("malformed json");
440
- };
441
- const bundleValues = (row) => [
442
- row.id,
443
- row.platform,
444
- row.file_hash,
445
- row.git_commit_hash,
446
- row.storage_uri,
447
- row.archive_byte_size,
448
- row.metadata,
449
- row.manifest_storage_uri,
450
- row.manifest_file_hash,
451
- row.asset_base_storage_uri
452
- ];
453
- const patchValues = (row) => [
454
- row.id,
455
- row.bundle_id,
456
- row.base_bundle_id,
457
- row.base_file_hash,
458
- row.patch_file_hash,
459
- row.patch_storage_uri,
460
- row.byte_size,
461
- row.order_index
462
- ];
463
- const channelValues = (row) => [row.id, row.name];
464
- const insertQuery = (input, guard, conflictMode = "returnExisting") => {
465
- let columns;
466
- let values;
467
- switch (input.model) {
468
- case "bundles":
469
- columns = [
470
- "id",
471
- "platform",
472
- "file_hash",
473
- "git_commit_hash",
474
- "storage_uri",
475
- "archive_byte_size",
476
- "metadata",
477
- "manifest_storage_uri",
478
- "manifest_file_hash",
479
- "asset_base_storage_uri"
480
- ];
481
- values = bundleValues(input.data);
482
- break;
483
- case "bundle_patches":
484
- columns = [
485
- "id",
486
- "bundle_id",
487
- "base_bundle_id",
488
- "base_file_hash",
489
- "patch_file_hash",
490
- "patch_storage_uri",
491
- "byte_size",
492
- "order_index"
493
- ];
494
- values = patchValues(input.data);
495
- break;
496
- case "channels":
497
- columns = ["id", "name"];
498
- values = channelValues(input.data);
499
- break;
500
- case "bundle_events":
501
- case "bundle_installations":
502
- case "api_keys":
503
- case "release_catalogs":
504
- case "releases":
505
- columns = Object.keys(input.data);
506
- values = Object.values(input.data);
507
- }
508
- const conflict = input.onConflict !== "ignore" ? "" : input.model === "channels" ? conflictMode === "ignore" ? " ON CONFLICT(name) DO NOTHING" : " ON CONFLICT(name) DO UPDATE SET name = excluded.name" : input.model === "api_keys" ? conflictMode === "ignore" ? " ON CONFLICT(hash) DO NOTHING" : " ON CONFLICT(hash) DO UPDATE SET hash = excluded.hash" : " ON CONFLICT(install_id) DO UPDATE SET install_id = excluded.install_id";
509
- return {
510
- sql: `INSERT INTO ${d1TableNames[input.model]} (${columns.join(", ")}) ${guard === void 0 ? `VALUES (${d1Placeholders(values.length)})` : `SELECT ${d1Placeholders(values.length)} WHERE ${guard.sql}`}${conflict} RETURNING *`,
511
- params: [...encodeD1Values(values), ...guard?.params ?? []]
512
- };
513
- };
514
- const updateEntries = (update) => Object.entries(update);
515
- const updateQuery = (input, guard) => {
516
- const entries = updateEntries(input.update);
517
- const where = buildD1Where(input.where);
518
- if (entries.length === 0) return {
519
- sql: `SELECT * FROM ${d1TableNames[input.model]}${where.sql}${guard ? ` AND ${guard.sql}` : ""} LIMIT 1`,
520
- params: [...where.params, ...guard?.params ?? []]
521
- };
522
- const assignments = entries.map(([field]) => `${field} = json_extract(?, '$')`).join(", ");
523
- return {
524
- sql: `UPDATE ${d1TableNames[input.model]} SET ${assignments}${where.sql}${guard ? ` AND ${guard.sql}` : ""} RETURNING *`,
525
- params: [
526
- ...encodeD1Values(entries.map(([, value]) => value)),
527
- ...where.params,
528
- ...guard?.params ?? []
529
- ]
530
- };
531
- };
532
- const deleteQuery = (input, guard) => {
533
- const where = buildD1Where(input.where);
534
- return {
535
- sql: `DELETE FROM ${d1TableNames[input.model]}${where.sql}${guard ? ` AND ${guard.sql}` : ""}`,
536
- params: [...where.params, ...guard?.params ?? []]
537
- };
538
- };
539
- const insertedKey = (change) => {
540
- if (change.operation !== "insert") return void 0;
541
- if (change.model === "bundles") return `bundles:${change.row.id}`;
542
- if (change.model === "apiKeys") return `api_keys:${change.row.id}`;
543
- if (change.model === "releases") return `releases:${change.row.id}`;
544
- };
545
- const requiredRow = (change, changeIndex) => {
546
- if (change.operation !== "update") return void 0;
547
- if (change.model === "bundles") return {
548
- model: "bundles",
549
- id: change.where.id,
550
- changeIndex
551
- };
552
- if (change.model === "apiKeys") return {
553
- model: "api_keys",
554
- id: change.where.id,
555
- changeIndex
556
- };
557
- if (change.model === "releases") return {
558
- model: "releases",
559
- id: change.where.id,
560
- changeIndex
561
- };
562
- };
563
- const channelDeletePrecondition = (changes, changeIndex, channelId) => {
564
- const releaseEffects = /* @__PURE__ */ new Map();
565
- for (const change of changes.slice(0, changeIndex)) {
566
- if (change.model !== "releases") continue;
567
- switch (change.operation) {
568
- case "insert":
569
- releaseEffects.set(change.row.id, change.row.channel_id);
570
- break;
571
- case "update": break;
572
- case "delete": releaseEffects.set(change.where.id, null);
573
- }
574
- }
575
- return {
576
- id: channelId,
577
- excludedReleaseIds: [...releaseEffects.keys()],
578
- addedReferenceReleaseIds: [...releaseEffects].filter(([, finalChannelId]) => finalChannelId === channelId).map(([releaseId]) => releaseId)
579
- };
580
- };
581
- const changeQuery = (change, guard) => {
582
- switch (change.model) {
583
- case "bundles": switch (change.operation) {
584
- case "insert": return insertQuery({
585
- model: "bundles",
586
- data: change.row
587
- }, guard);
588
- case "update": return updateQuery({
589
- model: "bundles",
590
- where: [{
591
- field: "id",
592
- value: change.where.id
593
- }],
594
- update: change.update
595
- }, guard);
596
- case "delete": return deleteQuery({
597
- model: "bundles",
598
- where: [{
599
- field: "id",
600
- value: change.where.id
601
- }]
602
- }, guard);
603
- }
604
- case "bundlePatches": return change.operation === "insert" ? insertQuery({
605
- model: "bundle_patches",
606
- data: change.row
607
- }, guard) : deleteQuery({
608
- model: "bundle_patches",
609
- where: [{
610
- field: "bundle_id",
611
- value: change.where.bundleId
612
- }]
613
- }, guard);
614
- case "releases": switch (change.operation) {
615
- case "insert": return insertQuery({
616
- model: "releases",
617
- data: change.row
618
- }, guard);
619
- case "update": return updateQuery({
620
- model: "releases",
621
- where: [{
622
- field: "id",
623
- value: change.where.id
624
- }],
625
- update: change.update
626
- }, guard);
627
- case "delete": return deleteQuery({
628
- model: "releases",
629
- where: [{
630
- field: "id",
631
- value: change.where.id
632
- }]
633
- }, guard);
634
- }
635
- case "releaseCatalogs": return {
636
- sql: `INSERT INTO release_catalogs (${Object.keys(change.row).join(", ")}) SELECT ${d1Placeholders(Object.keys(change.row).length)} WHERE ${guard.sql} ON CONFLICT(scope_key) DO UPDATE SET ${Object.keys(change.row).filter((field) => field !== "scope_key").map((field) => `${field} = excluded.${field}`).join(", ")} RETURNING *`,
637
- params: [...encodeD1Values(Object.values(change.row)), ...guard.params]
638
- };
639
- case "channels": return change.operation === "insert" ? insertQuery({
640
- model: "channels",
641
- data: change.row,
642
- onConflict: change.onConflict
643
- }, guard, "ignore") : {
644
- sql: `DELETE FROM channels WHERE id = json_extract(?, '$') AND NOT EXISTS (SELECT 1 FROM releases WHERE channel_id = json_extract(?, '$')) AND ${guard.sql}`,
645
- params: [...encodeD1Values([change.where.id, change.where.id]), ...guard.params]
646
- };
647
- case "apiKeys": return change.operation === "insert" ? insertQuery({
648
- model: "api_keys",
649
- data: change.row,
650
- onConflict: change.onConflict
651
- }, guard, "ignore") : updateQuery({
652
- model: "api_keys",
653
- where: [{
654
- field: "id",
655
- value: change.where.id
656
- }],
657
- update: { revoked_at_ms: change.update.revokedAtMs }
658
- }, guard);
659
- }
660
- };
661
- const createCommitPlan = (input) => {
662
- const checks = [];
663
- const statements = [];
664
- const expectations = input.expectations ?? [];
665
- if (expectations.length > 0) {
666
- const guard = expectationGuard(expectations);
667
- statements.push({
668
- sql: `SELECT CASE WHEN ${guard.sql} THEN 1 ELSE json_extract('${EXPECTATION_CONFLICT_MARKER}', '$') END AS expectation_guard`,
669
- params: guard.params
670
- });
671
- }
672
- const requiredRows = [];
673
- const channelDeletes = [];
674
- const inserted = /* @__PURE__ */ new Set();
675
- for (const [changeIndex, change] of input.changes.entries()) {
676
- const required = requiredRow(change, changeIndex);
677
- if (required !== void 0) {
678
- if (!inserted.has(`${required.model}:${required.id}`)) {
679
- requiredRows.push(required);
680
- checks.push({
681
- changeIndex,
682
- resultIndex: statements.length,
683
- conflictWhen: "empty",
684
- reason: "not_found"
685
- });
686
- statements.push({
687
- sql: `SELECT id FROM ${d1TableNames[required.model]} WHERE id = json_extract(?, '$') LIMIT 1`,
688
- params: encodeD1Values([required.id])
689
- });
690
- }
691
- }
692
- if (change.model === "channels" && change.operation === "delete") {
693
- const precondition = channelDeletePrecondition(input.changes, changeIndex, change.where.id);
694
- channelDeletes.push(precondition);
695
- checks.push({
696
- changeIndex,
697
- resultIndex: statements.length,
698
- conflictWhen: "nonempty",
699
- reason: "referenced"
700
- });
701
- statements.push({
702
- sql: "SELECT id FROM releases WHERE channel_id = json_extract(?, '$') AND id NOT IN (SELECT value FROM json_each(?)) UNION ALL SELECT value AS id FROM json_each(?) LIMIT 1",
703
- params: encodeD1Values([
704
- precondition.id,
705
- precondition.excludedReleaseIds,
706
- precondition.addedReferenceReleaseIds
707
- ])
708
- });
709
- }
710
- const key = insertedKey(change);
711
- if (key !== void 0) inserted.add(key);
712
- }
713
- const guard = {
714
- sql: `NOT EXISTS (
715
- SELECT 1 FROM json_each(?) AS required
716
- WHERE NOT EXISTS (
717
- SELECT 1 FROM bundles
718
- WHERE json_extract(required.value, '$.model') = 'bundles'
719
- AND bundles.id = json_extract(required.value, '$.id')
720
- UNION ALL
721
- SELECT 1 FROM api_keys
722
- WHERE json_extract(required.value, '$.model') = 'api_keys'
723
- AND api_keys.id = json_extract(required.value, '$.id')
724
- UNION ALL
725
- SELECT 1 FROM channels
726
- WHERE json_extract(required.value, '$.model') = 'channels'
727
- AND channels.id = json_extract(required.value, '$.id')
728
- UNION ALL
729
- SELECT 1 FROM releases
730
- WHERE json_extract(required.value, '$.model') = 'releases'
731
- AND releases.id = json_extract(required.value, '$.id')
732
- )
733
- ) AND NOT EXISTS (
734
- SELECT 1 FROM json_each(?) AS channel_delete
735
- WHERE EXISTS (
736
- SELECT 1 FROM releases
737
- WHERE releases.channel_id = json_extract(channel_delete.value, '$.id')
738
- AND releases.id NOT IN (
739
- SELECT value FROM json_each(
740
- json_extract(channel_delete.value, '$.excludedReleaseIds')
741
- )
742
- )
743
- UNION ALL
744
- SELECT value FROM json_each(
745
- json_extract(channel_delete.value, '$.addedReferenceReleaseIds')
746
- )
747
- )
748
- )`,
749
- params: encodeD1Values([requiredRows.map(({ model, id }) => ({
750
- model,
751
- id
752
- })), channelDeletes])
753
- };
754
- statements.push(...input.changes.map((change) => changeQuery(change, guard)));
755
- return {
756
- checks,
757
- statements
758
- };
759
- };
760
- const resultForPlan = (plan, results) => {
761
- const missing = plan.checks.find(({ conflictWhen, resultIndex }) => conflictWhen === "empty" ? (results[resultIndex]?.length ?? 0) === 0 : (results[resultIndex]?.length ?? 0) > 0);
762
- return missing === void 0 ? { committed: true } : {
763
- committed: false,
764
- conflict: {
765
- changeIndex: missing.changeIndex,
766
- reason: missing.reason
767
- }
768
- };
769
- };
770
- const insertChannel = async (executor, input) => {
771
- const insert = insertQuery({
772
- model: "channels",
773
- data: input.row,
774
- onConflict: "ignore"
775
- }, void 0, "ignore");
776
- const select = {
777
- sql: "SELECT id, name FROM channels WHERE name = json_extract(?, '$') LIMIT 1",
778
- params: encodeD1Values([input.row.name])
779
- };
780
- const [insertedRows = [], canonicalRows = []] = await executor.batch([insert, select]);
781
- return {
782
- row: parseD1Row("channels", canonicalRows[0]),
783
- inserted: insertedRows.length > 0
784
- };
785
- };
786
- const deleteChannel = async (executor, input) => {
787
- const [channelRows = [], referenceRows = [], deletedRows = []] = await executor.batch([
788
- {
789
- sql: "SELECT id FROM channels WHERE id = json_extract(?, '$') LIMIT 1",
790
- params: encodeD1Values([input.id])
791
- },
792
- {
793
- sql: "SELECT id FROM releases WHERE channel_id = json_extract(?, '$') LIMIT 1",
794
- params: encodeD1Values([input.id])
795
- },
796
- {
797
- sql: "DELETE FROM channels WHERE id = json_extract(?, '$') AND NOT EXISTS (SELECT 1 FROM releases WHERE channel_id = json_extract(?, '$')) RETURNING id",
798
- params: encodeD1Values([input.id, input.id])
799
- }
800
- ]);
801
- if (channelRows.length === 0) return {
802
- deleted: false,
803
- reason: "not_found"
804
- };
805
- if (referenceRows.length > 0) return {
806
- deleted: false,
807
- reason: "not_empty"
808
- };
809
- return deletedRows.length > 0 ? { deleted: true } : {
810
- deleted: false,
811
- reason: "not_empty"
812
- };
813
- };
814
- const createD1Implementation = (executor) => ({
815
- async recordInsights({ event, installation }) {
816
- const columns = Object.keys(installation);
817
- const eventInsert = insertQuery({
818
- model: "bundle_events",
819
- data: event
820
- });
821
- await executor.batch([{
822
- sql: `INSERT INTO bundle_installations (${columns.join(", ")})
823
- SELECT ${d1Placeholders(columns.length)}
824
- WHERE NOT EXISTS (SELECT 1 FROM bundle_events WHERE id = json_extract(?, '$'))
825
- ON CONFLICT(install_id) DO UPDATE SET ${columns.filter((column) => column !== "install_id").map((column) => `${column} = excluded.${column}`).join(", ")}
826
- WHERE (excluded.received_at_ms, excluded.id) >
827
- (bundle_installations.received_at_ms, bundle_installations.id)`,
828
- params: encodeD1Values([...Object.values(installation), event.id])
829
- }, {
830
- ...eventInsert,
831
- sql: eventInsert.sql.replace(" RETURNING *", " ON CONFLICT(id) DO NOTHING")
832
- }]);
833
- },
834
- async create(input) {
835
- const query = insertQuery(input);
836
- const rows = await executor.query(query.sql, query.params);
837
- switch (input.model) {
838
- case "bundles": return parseD1Row("bundles", rows[0]);
839
- case "bundle_patches": return parseD1Row("bundle_patches", rows[0]);
840
- case "channels": return parseD1Row("channels", rows[0]);
841
- case "bundle_events": return parseD1Row("bundle_events", rows[0]);
842
- case "bundle_installations": return parseD1Row("bundle_installations", rows[0]);
843
- case "api_keys": return parseD1Row("api_keys", rows[0]);
844
- case "releases": return parseD1Row("releases", rows[0]);
845
- case "release_catalogs": return parseD1Row("release_catalogs", rows[0]);
846
- }
847
- },
848
- async update(input) {
849
- const query = updateQuery(input);
850
- const rows = await executor.query(query.sql, query.params);
851
- if (rows[0] === void 0) return null;
852
- switch (input.model) {
853
- case "bundles": return parseD1Row("bundles", rows[0]);
854
- case "api_keys": return parseD1Row("api_keys", rows[0]);
855
- case "releases": return parseD1Row("releases", rows[0]);
856
- case "release_catalogs": return parseD1Row("release_catalogs", rows[0]);
857
- case "bundle_installations": return parseD1Row("bundle_installations", rows[0]);
858
- }
859
- },
860
- async delete(input) {
861
- const query = deleteQuery(input);
862
- await executor.query(query.sql, query.params);
863
- },
864
- count: (input) => countD1Rows(executor, input),
865
- async findOne(input) {
866
- const where = buildD1Where(input.where);
867
- const rows = await executor.query(`SELECT * FROM ${d1TableNames[input.model]}${where.sql} LIMIT 1`, where.params);
868
- if (rows[0] === void 0) return null;
869
- switch (input.model) {
870
- case "bundles": return parseD1Row("bundles", rows[0]);
871
- case "bundle_patches": return parseD1Row("bundle_patches", rows[0]);
872
- case "channels": return parseD1Row("channels", rows[0]);
873
- case "api_keys": return parseD1Row("api_keys", rows[0]);
874
- case "releases": return parseD1Row("releases", rows[0]);
875
- case "release_catalogs": return parseD1Row("release_catalogs", rows[0]);
876
- case "bundle_installations": return parseD1Row("bundle_installations", rows[0]);
877
- }
878
- },
879
- findMany: (input) => findManyD1Rows(executor, input),
880
- insertChannel: (input) => insertChannel(executor, input),
881
- deleteChannel: (input) => deleteChannel(executor, input),
882
- async commit(input) {
883
- if (input.changes.length === 0) return { committed: true };
884
- const expectations = input.expectations ?? [];
885
- const conflict = await expectationConflict(executor, expectations);
886
- if (conflict !== null) return conflict;
887
- const plan = createCommitPlan(input);
888
- try {
889
- return resultForPlan(plan, await executor.batch(plan.statements));
890
- } catch (error) {
891
- if (expectations.length === 0 || !isExpectationConflictError(error)) throw error;
892
- return await expectationConflict(executor, expectations) ?? {
893
- committed: false,
894
- conflict: {
895
- actualVersion: expectations[0].model === "releases" ? expectations[0].revision : expectations[0].generation,
896
- changeIndex: -1,
897
- expectedVersion: expectations[0].model === "releases" ? expectations[0].revision : expectations[0].generation,
898
- key: expectations[0].model === "releases" ? expectations[0].id : expectations[0].scopeKey,
899
- model: expectations[0].model,
900
- reason: "version_conflict"
25
+ const code = /UNIQUE constraint failed|constraint failed: .*PRIMARY/iu.test(message) ? "SQLITE_CONSTRAINT_UNIQUE" : /SQLITE_BUSY|database is locked/iu.test(message) ? "SQLITE_BUSY" : void 0;
26
+ return code === void 0 ? error : Object.assign(new Error(message, { cause: error }), { code });
27
+ };
28
+ /**
29
+ * Hot Updater's database on D1: the storage engine through the shared SQL
30
+ * core, fenced by the schema settings. D1 has no interactive transactions,
31
+ * so each write is one atomic batch that evaluates its guards first
32
+ * (`_hu_write`).
33
+ */
34
+ const createD1Database = (runner) => {
35
+ return createEngineDatabase({
36
+ name: "d1Database",
37
+ adapter: createSqlAdapter({
38
+ executor: {
39
+ dialect: "sqlite",
40
+ execute: (statement) => runner.query(statement).catch((error) => {
41
+ throw withSqliteCode(error);
42
+ }),
43
+ batch: (statements) => runner.batch(statements).catch((error) => {
44
+ throw withSqliteCode(error);
45
+ }),
46
+ transaction: () => {
47
+ throw new Error("D1 has no interactive transactions; writes are batches.");
901
48
  }
902
- };
903
- }
904
- }
905
- });
49
+ },
50
+ maxOps: 450,
51
+ maxParams: 100
52
+ })
53
+ });
54
+ };
55
+ //#endregion
56
+ //#region src/d1Schema.ts
57
+ /**
58
+ * D1's schema: the guard table batch writes need, then the shared SQL
59
+ * schema of core and the target's plugins, settings last. Every statement can
60
+ * run again, so a migration for a server's plugin tables repeats core's.
61
+ */
62
+ const d1SchemaStatements = ({ schema, settings } = coreTarget) => [...createTableStatements("sqlite", [WRITE_GUARD_TABLE]), ...generateEngineSql("sqlite", schema, settings)];
63
+ /** The schema as a D1 migration, which `wrangler d1 migrations apply` runs. */
64
+ const d1SchemaSql = (target) => `-- HotUpdater.schema\n\n${d1SchemaStatements(target).map((statement) => `${statement};`).join("\n\n")}\n`;
906
65
  //#endregion
907
66
  //#region src/d1Database.ts
67
+ /** The REST API binds text: each value goes as JSON and is read back with `json_extract`. */
68
+ const encode = ({ sql, params }) => ({
69
+ sql: sql.replaceAll("?", () => "json_extract(?, '$')"),
70
+ params: params.map((value) => JSON.stringify(value ?? null))
71
+ });
72
+ /**
73
+ * Hot Updater's database on D1 through the Cloudflare REST API, for the CLI
74
+ * and console. `hot-updater db generate` writes a D1 migration of the built-in
75
+ * tables and the server's plugin tables to `migrations`, and
76
+ * `hot-updater db migrate` applies them through the API.
77
+ */
908
78
  const d1Database = (config) => {
909
79
  const cloudflare = new Cloudflare({ apiToken: config.cloudflareApiToken });
910
80
  const execute = async (statements) => {
911
- const first = statements[0];
81
+ const [first] = statements;
912
82
  if (first === void 0) return [];
913
83
  const body = statements.length === 1 ? {
914
84
  account_id: config.accountId,
915
- sql: first.sql,
916
- params: [...first.params]
85
+ ...encode(first)
917
86
  } : {
918
87
  account_id: config.accountId,
919
- batch: statements.map(({ sql, params }) => ({
920
- sql,
921
- params: [...params]
922
- }))
88
+ batch: statements.map(encode)
923
89
  };
924
- const page = await cloudflare.d1.database.query(config.databaseId, { ...body });
90
+ const page = await cloudflare.d1.database.query(config.databaseId, body);
925
91
  const results = [];
926
- for await (const resultPage of page.iterPages()) for (const result of resultPage.result) {
927
- if (result.success === false) throw new D1ExecutionError();
928
- results.push(result.results ?? []);
929
- }
92
+ for await (const resultPage of page.iterPages()) for (const result of resultPage.result) results.push(toSqlResult(result));
930
93
  if (results.length !== statements.length) throw new D1ExecutionError();
931
94
  return results;
932
95
  };
933
- const adapter = createDatabasePluginAdapter("d1Database", createD1Implementation({
934
- async query(sql, params) {
935
- return (await execute([{
936
- sql,
937
- params
938
- }])).flat();
939
- },
940
- batch: execute
941
- }));
942
- return createDatabasePlugin({
943
- name: "d1Database",
944
- models: adapter.models,
945
- commit: adapter.commit,
946
- ...adapter.dispose ? { dispose: adapter.dispose } : {}
947
- });
96
+ return {
97
+ ...createD1Database({
98
+ query: async (statement) => (await execute([statement]))[0],
99
+ batch: execute
100
+ }),
101
+ generateSchema: ((version, _name, target = coreTarget) => {
102
+ if (version !== "latest" && version !== coreSettings["schema.core"]) throw new Error(`Invalid version ${version}`);
103
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/\D/g, "").slice(0, 14);
104
+ return {
105
+ code: d1SchemaSql(target),
106
+ path: `migrations/${timestamp}_hot-updater.sql`
107
+ };
108
+ })
109
+ };
948
110
  };
949
111
  //#endregion
950
112
  //#region src/r2S3Storage.ts
@@ -967,7 +129,7 @@ const createR2S3Storage = (config) => {
967
129
  if (parsed.bucket !== bucketName) throw new Error(`Bucket name mismatch: expected "${bucketName}", but found "${parsed.bucket}".`);
968
130
  return parsed;
969
131
  };
970
- return createStoragePlugin({
132
+ return createStorageAdapter({
971
133
  name: "r2Storage",
972
134
  protocol: "r2",
973
135
  async put({ key, body, contentLength, contentType }) {
@@ -1040,4 +202,15 @@ const r2Storage = (config) => {
1040
202
  return createR2S3Storage(config);
1041
203
  };
1042
204
  //#endregion
1043
- export { d1Database, r2Storage };
205
+ //#region src/plugins.ts
206
+ /**
207
+ * The plugins the managed Cloudflare server runs: Insights, API keys on every
208
+ * client route, and Remote Config. Its Worker imports this list.
209
+ */
210
+ const plugins = [
211
+ insights(),
212
+ apiKeys(),
213
+ remoteConfig()
214
+ ];
215
+ //#endregion
216
+ export { D1ExecutionError, d1Database, plugins, r2Storage };