@hot-updater/cloudflare 1.0.0-rc.5 → 1.0.0

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