@hot-updater/aws 1.2.0-rc.2 → 1.2.0-rc.21

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.
@@ -30,6 +30,7 @@ let _aws_sdk_client_cloudfront = require("@aws-sdk/client-cloudfront");
30
30
  let _aws_sdk_lib_dynamodb = require("@aws-sdk/lib-dynamodb");
31
31
  let _aws_sdk_client_s3 = require("@aws-sdk/client-s3");
32
32
  let _aws_sdk_lib_storage = require("@aws-sdk/lib-storage");
33
+ let _aws_sdk_s3_request_presigner = require("@aws-sdk/s3-request-presigner");
33
34
  const SHA256_FILE_HASH_RE = /^[0-9a-f]{64}$/;
34
35
  const isContentAddressedAssetFileHash = (value) => {
35
36
  return typeof value === "string" && SHA256_FILE_HASH_RE.test(value);
@@ -1437,6 +1438,10 @@ const semverSatisfies = (targetAppVersion, currentVersion) => {
1437
1438
  return satisfies(currentCoerce, targetAppVersion);
1438
1439
  };
1439
1440
  //#endregion
1441
+ //#region ../plugin-core/dist/types/index.mjs
1442
+ /** The value of a `Lazy`, calling its function. */
1443
+ const resolveLazy = async (value) => typeof value === "function" ? await value() : value;
1444
+ //#endregion
1440
1445
  //#region ../plugin-core/dist/serverPlugin/definePlugin.mjs
1441
1446
  /** Declares a plugin; Hot Updater's own plugins and third-party ones use the same contract. */
1442
1447
  const definePlugin = (plugin) => plugin;
@@ -2126,7 +2131,10 @@ const CHANNEL_ID = {
2126
2131
  * every database's migrator creates missing tables and then records the
2127
2132
  * version, and none of them changes an existing table, so changing one
2128
2133
  * needs a migration step of its own first. The schema fence answers 503 on
2129
- * a database whose row differs, until it runs.
2134
+ * a database whose row differs, until it runs. Before a version is released,
2135
+ * its tables change in place in its own migration, and a database one of its
2136
+ * prereleases migrated takes the same change by hand: the fence compares this
2137
+ * row, not columns, so nothing reports it.
2130
2138
  */
2131
2139
  const HOT_UPDATER_SCHEMA_VERSION = "1.2.0";
2132
2140
  const bundles = defineTable({
@@ -2390,6 +2398,10 @@ const channels = defineTable({
2390
2398
  * or `versionCode`. `submitted_to`, `submitted_at_ms` and
2391
2399
  * `submitted_version` record the store track a build went to, when, and
2392
2400
  * the store's label of the build; they stay null for a build no store took.
2401
+ * `store_build` is true on the build a person or a job says the store sells,
2402
+ * and null on every other: deploys patch from it over the scope's newest build.
2403
+ * It is never false, so `byStoreBuild` holds one entry per scope at most, on
2404
+ * every store, and an unmarked row, older than the column or not, holds none.
2393
2405
  */
2394
2406
  const nativeBuilds = defineTable({
2395
2407
  id: {
@@ -2466,6 +2478,10 @@ const nativeBuilds = defineTable({
2466
2478
  type: "string",
2467
2479
  maxLength: 255,
2468
2480
  required: false
2481
+ },
2482
+ store_build: {
2483
+ type: "boolean",
2484
+ required: false
2469
2485
  }
2470
2486
  }, {
2471
2487
  key: ["id"],
@@ -2478,6 +2494,11 @@ const nativeBuilds = defineTable({
2478
2494
  eq: ["scope_key", "build_key"],
2479
2495
  sort: ["id"]
2480
2496
  },
2497
+ byStoreBuild: {
2498
+ eq: ["scope_key", "store_build"],
2499
+ sort: [],
2500
+ unique: true
2501
+ },
2481
2502
  byChannel: {
2482
2503
  eq: ["channel_id"],
2483
2504
  sort: ["id"],
@@ -2698,15 +2719,8 @@ const LEASE_TABLE = "aggregate_lease";
2698
2719
  const LEASE = { id: "compaction" };
2699
2720
  /** How long a compaction holds the lease before another process may take it. */
2700
2721
  const LEASE_MS = 3e4;
2701
- /**
2702
- * Default windows: log mode compacts every 60 seconds, since reads compact
2703
- * first; memory mode flushes every 15, since its window is what a crash
2704
- * loses.
2705
- */
2706
- const WINDOW_MS$1 = {
2707
- log: 6e4,
2708
- memory: 15e3
2709
- };
2722
+ /** A commit compacts once this has passed since the last compaction. */
2723
+ const WINDOW_MS$1 = 6e4;
2710
2724
  /** Log rows a compaction reads from each log table for one group. */
2711
2725
  const LOG_PAGE = 200;
2712
2726
  /**
@@ -2720,8 +2734,6 @@ const GROUPS = {
2720
2734
  };
2721
2735
  /** Tries per write after a conflict or a transient error. */
2722
2736
  const ATTEMPTS = 5;
2723
- /** Aggregate rows a memory buffer holds before a commit waits for a flush. */
2724
- const MAX_BUFFERED = 1e4;
2725
2737
  const log = defineTable({
2726
2738
  id: {
2727
2739
  type: "string",
@@ -2771,7 +2783,7 @@ const valuesOf = ({ deltas, sketches }) => ({
2771
2783
  /**
2772
2784
  * Merges `values` into the change for `key`'s identity as `tx.aggregate`
2773
2785
  * does: deltas add up and sketches merge. One constant `shardBy` keys each
2774
- * identity to one entry; the write picks the shard.
2786
+ * identity to one entry; `compile` writes it to shard 0.
2775
2787
  */
2776
2788
  const merge = (into, model, key, values) => recordAggregate(into, model, Object.fromEntries(shapeOf(model).key.map((field, at) => [field, key[at]])), values, "");
2777
2789
  const mergeAll = (into, changes) => {
@@ -2805,7 +2817,7 @@ const increment = ({ model, deltas }, key) => Object.values(deltas).some((delta)
2805
2817
  /**
2806
2818
  * The guarded write that merges `change` into `current`: insert, patch, or
2807
2819
  * delete at zero. Unlike a transaction's, a gauge may go below zero here: a
2808
- * shard row holds one writer's net changes, and reads sum every shard.
2820
+ * group can hold a loss without the gain before it, and reads sum every shard.
2809
2821
  */
2810
2822
  const rewrite = (change, key, current) => {
2811
2823
  const { model } = change;
@@ -2843,12 +2855,12 @@ const rewrite = (change, key, current) => {
2843
2855
  };
2844
2856
  };
2845
2857
  /**
2846
- * The write for each change on its shard: a blind increment that creates
2847
- * the row for counters, and a guarded rewrite for gauges and sketches, whose
2848
- * rows are read in one batch per table.
2858
+ * The write for each change on shard 0, since one compaction runs at a time:
2859
+ * a blind increment that creates the row for counters, and a guarded rewrite
2860
+ * for gauges and sketches, whose rows are read in one batch per table.
2849
2861
  */
2850
- const compile = async (adapter, changes, shard) => {
2851
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
2862
+ const compile = async (adapter, changes) => {
2863
+ const keys = changes.map(({ key }) => [...key.slice(0, -1), 0]);
2852
2864
  const reads = /* @__PURE__ */ new Map();
2853
2865
  changes.forEach((change, at) => {
2854
2866
  if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
@@ -2902,14 +2914,13 @@ const encode = async (changes) => {
2902
2914
  return zipped !== void 0 && zipped.length < json.length ? `z${zipped}` : json;
2903
2915
  };
2904
2916
  /**
2905
- * Batches changes to aggregates declared `batched`. A transaction records
2906
- * them without writing their rows; once it commits, "memory" mode keeps
2907
- * them in this process until its timer flushes them, and "log" mode has
2908
- * written them as one log row in the same atomic write, which a compaction
2909
- * later merges into the aggregates and deletes, atomically again, so each
2910
- * applies exactly once. One lease row keeps compactions one at a time.
2917
+ * Batches changes to aggregates declared `batched`. A transaction writes
2918
+ * them as one log row in its own atomic write, in place of their rows; a
2919
+ * compaction later merges log rows into the aggregates and deletes them,
2920
+ * atomically again, so each applies exactly once. One lease row keeps
2921
+ * compactions one at a time.
2911
2922
  */
2912
- const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS$1[mode] }, now }) => {
2923
+ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs = WINDOW_MS$1 }, now }) => {
2913
2924
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
2914
2925
  const holder = crypto.randomUUID().replaceAll("-", "");
2915
2926
  const table = (name) => schema.models.get(name).table;
@@ -2937,68 +2948,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
2937
2948
  }
2938
2949
  return changes;
2939
2950
  };
2940
- /**
2941
- * Writes changes in atomic chunks within `fits`, and returns the ones it
2942
- * could not apply. A write whose outcome is unknown is dropped, never
2943
- * resent, so no change applies twice.
2944
- */
2945
- const apply = async (changes, shard) => {
2946
- let rest = changes;
2947
- let ops = [];
2948
- let read = true;
2949
- for (let failures = 0; rest.length > 0 && failures < ATTEMPTS;) try {
2950
- if (read) ops = await compile(adapter, rest, shard);
2951
- let size = rest.length;
2952
- const chunk = () => ops.slice(0, size).filter(isOp);
2953
- while (size > 1 && !adapter.fits(chunk())) size = Math.ceil(size / 2);
2954
- let result = { ok: true };
2955
- if (chunk().length > 0) result = await adapter.write(chunk()).catch((error) => {
2956
- warn("flush")(error);
2957
- return { ok: true };
2958
- });
2959
- read = !result.ok && !("retry" in result);
2960
- if (result.ok) {
2961
- rest = rest.slice(size);
2962
- ops = ops.slice(size);
2963
- failures = 0;
2964
- } else {
2965
- failures += 1;
2966
- if (!read) await sleep$2(failures);
2967
- }
2968
- } catch (error) {
2969
- warn("flush")(error);
2970
- return rest;
2971
- }
2972
- return rest;
2973
- };
2974
- let buffer = /* @__PURE__ */ new Map();
2975
- let timer;
2976
- let flushing;
2977
- const shards = /* @__PURE__ */ new Map();
2978
- /** Each process writes its own shard, so flushes of two processes rarely meet. */
2979
- const processShard = (model) => {
2980
- if (!shards.has(model)) shards.set(model, Math.floor(Math.random() * shapeOf(model).shards));
2981
- return shards.get(model);
2982
- };
2983
- const schedule = () => {
2984
- if (timer !== void 0 || buffer.size === 0) return;
2985
- timer = setTimeout(() => {
2986
- timer = void 0;
2987
- flushBuffer();
2988
- }, windowMs);
2989
- timer.unref?.();
2990
- };
2991
- /** Never rejects: what it cannot apply goes back into the buffer. */
2992
- const flushBuffer = () => flushing ??= (async () => {
2993
- clearTimeout(timer);
2994
- timer = void 0;
2995
- const pending = [...buffer.values()];
2996
- buffer = /* @__PURE__ */ new Map();
2997
- mergeAll(buffer, await apply(pending, processShard));
2998
- })().catch(warn("flush")).finally(() => {
2999
- flushing = void 0;
3000
- schedule();
3001
- });
3002
2951
  let nextDue = 0;
3003
2952
  let compacting;
3004
2953
  /** Log rows this process read, by `[log table's index, id]`, for the deletes after a group. */
@@ -3133,7 +3082,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3133
3082
  more
3134
3083
  };
3135
3084
  };
3136
- const rowsFor = async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp);
3085
+ const rowsFor = async (changes) => (await compile(adapter, changes)).filter(isOp);
3137
3086
  /**
3138
3087
  * Applies the oldest pending log rows whose merged changes fit in one
3139
3088
  * atomic write with the lease, which lists them as applied; the rows are
@@ -3227,20 +3176,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3227
3176
  }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
3228
3177
  checking = void 0;
3229
3178
  });
3230
- /** Takes a committed transaction's changes; never rejects, since the transaction already committed. */
3231
- const committed = async (changes) => {
3232
- if (mode === "log") {
3233
- if (now() >= nextDue) await compact(false, GROUPS.commit);
3234
- return;
3235
- }
3236
- mergeAll(buffer, changes.values());
3237
- schedule();
3238
- if (buffer.size >= MAX_BUFFERED) await flushBuffer();
3239
- };
3240
- const flush = async () => {
3241
- await flushBuffer();
3242
- if (mode === "log" && await hasPending()) await compact(true, GROUPS.flush);
3243
- };
3244
3179
  return {
3245
3180
  async transaction(fn) {
3246
3181
  let changes = /* @__PURE__ */ new Map();
@@ -3266,7 +3201,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3266
3201
  aggregate
3267
3202
  });
3268
3203
  if (failure) throw failure.error;
3269
- if (mode === "log" && attempt.size > 0) {
3204
+ if (attempt.size > 0) {
3270
3205
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
3271
3206
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
3272
3207
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -3280,24 +3215,18 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3280
3215
  open = false;
3281
3216
  }
3282
3217
  });
3283
- if (changes.size > 0) await committed(changes);
3218
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
3284
3219
  return result;
3285
3220
  },
3286
3221
  async beforeRead(name) {
3287
3222
  if (!isBatched(schema.models.get(name))) return;
3288
- if (buffer.size > 0 || flushing !== void 0) await flushBuffer();
3289
- if (mode === "log") {
3290
- if (await hasPending().catch((error) => {
3291
- warn("read")(error);
3292
- return false;
3293
- })) await compact(true, GROUPS.read);
3294
- }
3223
+ if (await hasPending().catch((error) => {
3224
+ warn("read")(error);
3225
+ return false;
3226
+ })) await compact(true, GROUPS.read);
3295
3227
  },
3296
- flush,
3297
- async dispose() {
3298
- clearTimeout(timer);
3299
- timer = void 0;
3300
- await flush();
3228
+ async flush() {
3229
+ if (await hasPending()) await compact(true, GROUPS.flush);
3301
3230
  }
3302
3231
  };
3303
3232
  };
@@ -4326,13 +4255,10 @@ const createDatabaseEngine = ({ batching, now = Date.now, meter, ...options }) =
4326
4255
  };
4327
4256
  return {
4328
4257
  ...engine,
4329
- /** Applies batched aggregate changes still pending: this process's buffer and the log. */
4258
+ /** Applies the batched aggregate changes still in the log. */
4330
4259
  flush: async () => {
4331
4260
  await batches?.flush();
4332
4261
  },
4333
- dispose: async () => {
4334
- await batches?.dispose();
4335
- },
4336
4262
  database(module) {
4337
4263
  const name = (model) => module.namespace ? `${module.namespace}_${model}` : model;
4338
4264
  return {
@@ -4413,8 +4339,7 @@ const createEngine = (database, { plugins = [], now = Date.now } = {}) => {
4413
4339
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
4414
4340
  return engine.database(module);
4415
4341
  },
4416
- flush: () => engine.flush(),
4417
- dispose: () => engine.dispose()
4342
+ flush: () => engine.flush()
4418
4343
  };
4419
4344
  };
4420
4345
  //#endregion
@@ -4707,7 +4632,7 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
4707
4632
  };
4708
4633
  //#endregion
4709
4634
  //#region ../../packages/server/dist/version.mjs
4710
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.2";
4635
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.21";
4711
4636
  //#endregion
4712
4637
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
4713
4638
  /**
@@ -5912,8 +5837,22 @@ const pick = (row) => ({
5912
5837
  build_number: row.build_number ?? null,
5913
5838
  submitted_to: row.submitted_to ?? null,
5914
5839
  submitted_at_ms: row.submitted_at_ms ?? null,
5915
- submitted_version: row.submitted_version ?? null
5840
+ submitted_version: row.submitted_version ?? null,
5841
+ store_build: row.store_build === true ? true : null
5916
5842
  });
5843
+ /**
5844
+ * The channels only sandbox builds register on, which no store sells: the
5845
+ * registry's convention, as `@hot-updater/protocol/native-artifact` checks it
5846
+ * for a build's artifact.
5847
+ */
5848
+ const SANDBOX_CHANNEL_PREFIX = "sandbox-";
5849
+ /**
5850
+ * How many older builds of a scope one read takes, looking for one older than
5851
+ * a bundle when a build made after the bundle is the newest.
5852
+ */
5853
+ const OLDER_BUILDS_PAGE = 20;
5854
+ /** How many times a mark runs again after losing its scope's mark to another. */
5855
+ const MARK_ATTEMPTS = 8;
5917
5856
  /** The store track each platform's builds are submitted to. */
5918
5857
  const SUBMISSION_DESTINATIONS = {
5919
5858
  android: "play-internal",
@@ -5990,7 +5929,8 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
5990
5929
  build_number: registration.buildNumber ?? null,
5991
5930
  submitted_to: null,
5992
5931
  submitted_at_ms: null,
5993
- submitted_version: null
5932
+ submitted_version: null,
5933
+ store_build: null
5994
5934
  };
5995
5935
  for (let attempt = 1;; attempt += 1) {
5996
5936
  await insertChannel(db, {
@@ -6028,21 +5968,45 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6028
5968
  const scopeKey = nativeBuildScopeKey(scope);
6029
5969
  const buildKey = options?.buildKey;
6030
5970
  if (buildKey !== void 0 && !BUILD_KEY.test(buildKey)) throw new NativeBuildInputError("Invalid native build key: it must be nbk1: and a SHA-256.");
6031
- const { rows } = buildKey === void 0 ? await db.findMany("native_builds", {
6032
- index: "byScope",
6033
- where: { scope_key: scopeKey },
6034
- order: "desc",
6035
- limit: 1
6036
- }) : await db.findMany("native_builds", {
6037
- index: "byBuildKey",
6038
- where: {
5971
+ if (options?.storeBuild) {
5972
+ const marked = await db.findOne("native_builds", {
6039
5973
  scope_key: scopeKey,
6040
- build_key: buildKey
6041
- },
6042
- order: "desc",
6043
- limit: 1
6044
- });
6045
- return rows[0] === void 0 ? null : pick(rows[0]);
5974
+ store_build: true
5975
+ });
5976
+ return marked === null ? null : pick(marked);
5977
+ }
5978
+ const read = (limit, before) => {
5979
+ const page = {
5980
+ order: "desc",
5981
+ limit,
5982
+ ...before === void 0 ? {} : { range: { lt: before } }
5983
+ };
5984
+ return buildKey === void 0 ? db.findMany("native_builds", {
5985
+ index: "byScope",
5986
+ where: { scope_key: scopeKey },
5987
+ ...page
5988
+ }) : db.findMany("native_builds", {
5989
+ index: "byBuildKey",
5990
+ where: {
5991
+ scope_key: scopeKey,
5992
+ build_key: buildKey
5993
+ },
5994
+ ...page
5995
+ });
5996
+ };
5997
+ const { rows } = await read(1);
5998
+ const newest = rows[0];
5999
+ if (newest === void 0) return null;
6000
+ const bundleId = options?.builtInOlderThan;
6001
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return pick(newest);
6002
+ for (let before = newest.id;;) {
6003
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
6004
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
6005
+ if (usable !== void 0) return pick(usable);
6006
+ const last = older.at(-1);
6007
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
6008
+ before = last.id;
6009
+ }
6046
6010
  },
6047
6011
  async recordNativeBuildSubmission(id, { destination, version }) {
6048
6012
  if (version.trim().length === 0 || version.length > SUBMITTED_VERSION_MAX_LENGTH) throw new NativeBuildInputError(`Invalid native build submission: version must be the store's label of the build, up to ${SUBMITTED_VERSION_MAX_LENGTH} characters.`);
@@ -6063,6 +6027,49 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6063
6027
  };
6064
6028
  });
6065
6029
  },
6030
+ async markNativeBuild(id, { storeBuild }) {
6031
+ for (let attempt = 1;; attempt += 1) try {
6032
+ return await db.transaction(async (tx) => {
6033
+ const row = await tx.findOne("native_builds", { id });
6034
+ if (row === null) return null;
6035
+ const build = pick(row);
6036
+ if (!storeBuild) {
6037
+ if (build.store_build !== null) tx.update("native_builds", row, { store_build: null });
6038
+ return {
6039
+ nativeBuild: {
6040
+ ...build,
6041
+ store_build: null
6042
+ },
6043
+ previous: null
6044
+ };
6045
+ }
6046
+ if (decodeChannelKey(build.channel_id.slice(8)).startsWith(SANDBOX_CHANNEL_PREFIX)) throw new NativeBuildInputError("A build on a sandbox channel can't be the store build.");
6047
+ if (build.store_build !== null) return {
6048
+ nativeBuild: build,
6049
+ previous: null
6050
+ };
6051
+ const holder = await tx.findOne("native_builds", {
6052
+ scope_key: build.scope_key,
6053
+ store_build: true
6054
+ });
6055
+ if (holder !== null) tx.update("native_builds", holder, { store_build: null });
6056
+ tx.update("native_builds", row, { store_build: true });
6057
+ return {
6058
+ nativeBuild: {
6059
+ ...build,
6060
+ store_build: true
6061
+ },
6062
+ previous: holder === null ? null : {
6063
+ ...pick(holder),
6064
+ store_build: null
6065
+ }
6066
+ };
6067
+ });
6068
+ } catch (error) {
6069
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
6070
+ throw error;
6071
+ }
6072
+ },
6066
6073
  async deleteNativeBuild(id) {
6067
6074
  return db.transaction(async (tx) => {
6068
6075
  const row = await tx.findOne("native_builds", { id });
@@ -7145,7 +7152,13 @@ const createAdminRouteHandlers = () => ({
7145
7152
  const url = new URL(request.url);
7146
7153
  const scope = nativeBuildScopeOf(url);
7147
7154
  const buildKey = url.searchParams.get("buildKey");
7148
- return json$2({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
7155
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
7156
+ const options = {
7157
+ ...buildKey === null ? {} : { buildKey },
7158
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
7159
+ ...builtInOlderThan === null ? {} : { builtInOlderThan }
7160
+ };
7161
+ return json$2({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
7149
7162
  }),
7150
7163
  getNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
7151
7164
  listNativeBuilds: onCore(async (core, request) => {
@@ -7166,6 +7179,12 @@ const createAdminRouteHandlers = () => ({
7166
7179
  };
7167
7180
  return json$2({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
7168
7181
  }),
7182
+ markNativeBuild: onCore(async (core, request, params) => {
7183
+ const input = await body(request);
7184
+ if (!isRecord$5(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
7185
+ const mark = { storeBuild: input.storeBuild };
7186
+ return json$2({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
7187
+ }),
7169
7188
  deleteNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
7170
7189
  deleteBundles: onCore(async (core, request) => {
7171
7190
  const { ids } = await body(request);
@@ -7311,6 +7330,11 @@ const ADMIN_ROUTES = [
7311
7330
  path: "/native-builds/:id/submission",
7312
7331
  handler: "recordNativeBuildSubmission"
7313
7332
  },
7333
+ {
7334
+ method: "POST",
7335
+ path: "/native-builds/:id/store-build",
7336
+ handler: "markNativeBuild"
7337
+ },
7314
7338
  {
7315
7339
  method: "DELETE",
7316
7340
  path: "/native-builds/:id",
@@ -14295,10 +14319,30 @@ async apply() {
14295
14319
  };
14296
14320
  };
14297
14321
  //#endregion
14322
+ //#region src/lazyCredentials.ts
14323
+ /**
14324
+ * `credentials` as the AWS SDK takes them: access keys with a lazy field
14325
+ * become a provider, which the SDK calls once, on its first request.
14326
+ */
14327
+ const toSdkCredentials$1 = (credentials) => {
14328
+ if (credentials === void 0 || typeof credentials === "function") return credentials;
14329
+ const { accessKeyId, secretAccessKey, sessionToken, ...rest } = credentials;
14330
+ if (typeof accessKeyId !== "function" && typeof secretAccessKey !== "function" && typeof sessionToken !== "function") return credentials;
14331
+ return async () => ({
14332
+ ...rest,
14333
+ accessKeyId: await resolveLazy(accessKeyId),
14334
+ secretAccessKey: await resolveLazy(secretAccessKey),
14335
+ ...sessionToken === void 0 ? {} : { sessionToken: await resolveLazy(sessionToken) }
14336
+ });
14337
+ };
14338
+ //#endregion
14298
14339
  //#region src/dynamoDB.ts
14299
14340
  /** The DynamoDB client ignores the CloudFront and batching settings. */
14300
- const adapterOf = ({ tableName, ...clientConfig }) => {
14301
- const client = new _aws_sdk_client_dynamodb.DynamoDBClient(clientConfig);
14341
+ const adapterOf = ({ tableName, credentials, ...clientConfig }) => {
14342
+ const client = new _aws_sdk_client_dynamodb.DynamoDBClient({
14343
+ ...clientConfig,
14344
+ credentials: toSdkCredentials$1(credentials)
14345
+ });
14302
14346
  const store = createDynamoDBStore({
14303
14347
  client,
14304
14348
  tableName
@@ -14323,7 +14367,10 @@ const marked = (target) => ({ [DATABASE_TARGET]: target });
14323
14367
  */
14324
14368
  const dynamoDB = (config) => {
14325
14369
  const { client, adapter } = adapterOf(config);
14326
- const cloudFront = createUpdateRouteInvalidation(config);
14370
+ const cloudFront = createUpdateRouteInvalidation({
14371
+ ...config,
14372
+ credentials: toSdkCredentials$1(config.credentials)
14373
+ });
14327
14374
  return {
14328
14375
  ...createEngineDatabase({
14329
14376
  name: "dynamoDB",
@@ -14340,18 +14387,49 @@ const dynamoDB = (config) => {
14340
14387
  };
14341
14388
  };
14342
14389
  //#endregion
14343
- //#region src/s3Storage.ts
14390
+ //#region ../storage-s3/dist/index.mjs
14391
+ /**
14392
+ * `credentials` as the AWS SDK takes them: access keys with a lazy field
14393
+ * become a provider, which the SDK calls once, on its first request.
14394
+ */
14395
+ const toSdkCredentials = (credentials) => {
14396
+ if (credentials === void 0 || typeof credentials === "function") return credentials;
14397
+ const { accessKeyId, secretAccessKey, sessionToken, ...rest } = credentials;
14398
+ if (typeof accessKeyId !== "function" && typeof secretAccessKey !== "function" && typeof sessionToken !== "function") return credentials;
14399
+ return async () => ({
14400
+ ...rest,
14401
+ accessKeyId: await resolveLazy(accessKeyId),
14402
+ secretAccessKey: await resolveLazy(secretAccessKey),
14403
+ ...sessionToken === void 0 ? {} : { sessionToken: await resolveLazy(sessionToken) }
14404
+ });
14405
+ };
14344
14406
  /** Devices download right after the update check that returns the URL. */
14345
- const PRESIGNED_URL_EXPIRES_IN_SECONDS = 3600;
14346
- const isObjectNotFoundError = (error) => error instanceof Error && (error.name === "NotFound" || error.name === "NoSuchKey");
14347
- function s3Storage(config) {
14348
- const { bucketName, basePath, getDownloadUrl, ...s3Config } = config;
14349
- const client = new _aws_sdk_client_s3.S3Client(applyS3RuntimeAwsConfig(s3Config));
14350
- const normalizedBasePath = basePath?.replace(/^\/+|\/+$/g, "") ?? "";
14407
+ const DEFAULT_SIGNED_LIFETIME_SECONDS = 3600;
14408
+ /** SigV4's limit on a presigned URL. */
14409
+ const MAX_SIGNED_LIFETIME_SECONDS = 604800;
14410
+ /** DeleteObjects takes at most 1000 keys a request. */
14411
+ const DELETE_BATCH_SIZE = 1e3;
14412
+ const isObjectNotFoundError = (error) => {
14413
+ if (error instanceof Error && (error.name === "NotFound" || error.name === "NoSuchKey")) return true;
14414
+ return typeof error === "object" && error !== null && "$metadata" in error && error.$metadata?.httpStatusCode === 404;
14415
+ };
14416
+ const trimSlashes = (value) => value.replace(/^\/+|\/+$/g, "");
14417
+ /**
14418
+ * A storage adapter over a bucket's S3 API, which AWS S3, Cloudflare R2, and
14419
+ * Neon Object Storage all serve. Each provider package passes its own name,
14420
+ * URI protocol, and client defaults.
14421
+ */
14422
+ const createS3Storage = ({ name, protocol }, config) => {
14423
+ const { bucketName, basePath, getDownloadUrl, signedUrlExpiresIn = DEFAULT_SIGNED_LIFETIME_SECONDS, credentials, ...clientConfig } = config;
14424
+ if (!Number.isFinite(signedUrlExpiresIn) || signedUrlExpiresIn <= 0 || signedUrlExpiresIn > MAX_SIGNED_LIFETIME_SECONDS) throw new Error(`${name} signedUrlExpiresIn must be between 1 and ${MAX_SIGNED_LIFETIME_SECONDS} seconds (seven days).`);
14425
+ const client = new _aws_sdk_client_s3.S3Client({
14426
+ ...clientConfig,
14427
+ credentials: toSdkCredentials(credentials)
14428
+ });
14429
+ const normalizedBasePath = trimSlashes(basePath ?? "");
14351
14430
  const getStorageKey = createStorageKeyBuilder(normalizedBasePath);
14352
14431
  const getListPrefix = (prefix = "") => {
14353
- const normalizedPrefix = prefix.replace(/^\/+|\/+$/g, "");
14354
- const value = [normalizedBasePath, normalizedPrefix].filter(Boolean).join("/");
14432
+ const value = [normalizedBasePath, trimSlashes(prefix)].filter(Boolean).join("/");
14355
14433
  return value ? `${value}/` : "";
14356
14434
  };
14357
14435
  /**
@@ -14363,7 +14441,7 @@ function s3Storage(config) {
14363
14441
  return createStorageUri({
14364
14442
  bucket: bucketName,
14365
14443
  key,
14366
- protocol: "s3"
14444
+ protocol
14367
14445
  });
14368
14446
  } catch {
14369
14447
  return null;
@@ -14375,55 +14453,16 @@ function s3Storage(config) {
14375
14453
  return key.startsWith(basePrefix) ? key.slice(basePrefix.length) : key;
14376
14454
  };
14377
14455
  const parseAndValidate = (storageUri) => {
14378
- const parsed = parseStorageUri(storageUri, "s3");
14456
+ const parsed = parseStorageUri(storageUri, protocol);
14379
14457
  if (parsed.bucket !== bucketName) throw new Error(`Bucket name mismatch: expected "${bucketName}", but found "${parsed.bucket}".`);
14380
14458
  return parsed;
14381
14459
  };
14382
14460
  return createStorageAdapter({
14383
- name: "s3Storage",
14384
- protocol: "s3",
14385
- async listObjects(prefix) {
14386
- const objects = [];
14387
- let continuationToken;
14388
- do {
14389
- const response = await client.send(new _aws_sdk_client_s3.ListObjectsV2Command({
14390
- Bucket: bucketName,
14391
- ContinuationToken: continuationToken,
14392
- Prefix: getListPrefix(prefix)
14393
- }));
14394
- for (const object of response.Contents ?? []) {
14395
- if (!object.Key) continue;
14396
- const storageUri = getListedStorageUri(object.Key);
14397
- if (storageUri === null) continue;
14398
- objects.push({
14399
- key: getRelativeKey(object.Key),
14400
- lastModifiedAt: object.LastModified,
14401
- size: object.Size ?? 0,
14402
- storageUri
14403
- });
14404
- }
14405
- continuationToken = response.NextContinuationToken;
14406
- } while (continuationToken);
14407
- return objects;
14408
- },
14409
- async deleteObjects(relativeKeys) {
14410
- const keys = relativeKeys.map((key) => getStorageKey(key));
14411
- for (let offset = 0; offset < keys.length; offset += 1e3) {
14412
- const batch = keys.slice(offset, offset + 1e3);
14413
- if (batch.length === 0) continue;
14414
- const response = await client.send(new _aws_sdk_client_s3.DeleteObjectsCommand({
14415
- Bucket: bucketName,
14416
- Delete: {
14417
- Objects: batch.map((Key) => ({ Key })),
14418
- Quiet: true
14419
- }
14420
- }));
14421
- if (response.Errors && response.Errors.length > 0) throw new Error(`Failed to delete ${response.Errors.length} S3 object(s).`);
14422
- }
14423
- },
14461
+ name,
14462
+ protocol,
14424
14463
  async put({ key, body, contentLength, contentType }) {
14425
14464
  const storageKey = getStorageKey(key);
14426
- const response = await new _aws_sdk_lib_storage.Upload({
14465
+ await new _aws_sdk_lib_storage.Upload({
14427
14466
  client,
14428
14467
  params: {
14429
14468
  Body: body,
@@ -14434,11 +14473,10 @@ function s3Storage(config) {
14434
14473
  Key: storageKey
14435
14474
  }
14436
14475
  }).done();
14437
- if (!response.Bucket || !response.Key) throw new Error("Upload failed");
14438
14476
  return { storageUri: createStorageUri({
14439
14477
  bucket: bucketName,
14440
14478
  key: storageKey,
14441
- protocol: "s3"
14479
+ protocol
14442
14480
  }) };
14443
14481
  },
14444
14482
  async get({ storageUri }) {
@@ -14461,11 +14499,10 @@ function s3Storage(config) {
14461
14499
  async getDownloadUrl({ storageUri }) {
14462
14500
  const { key } = parseAndValidate(storageUri);
14463
14501
  if (getDownloadUrl) return getDownloadUrl({ storageUri });
14464
- const { getSignedUrl } = await import("@aws-sdk/s3-request-presigner");
14465
- return { url: await getSignedUrl(client, new _aws_sdk_client_s3.GetObjectCommand({
14502
+ return { url: await (0, _aws_sdk_s3_request_presigner.getSignedUrl)(client, new _aws_sdk_client_s3.GetObjectCommand({
14466
14503
  Bucket: bucketName,
14467
14504
  Key: key
14468
- }), { expiresIn: PRESIGNED_URL_EXPIRES_IN_SECONDS }) };
14505
+ }), { expiresIn: signedUrlExpiresIn }) };
14469
14506
  },
14470
14507
  async exists({ storageUri }) {
14471
14508
  const { key } = parseAndValidate(storageUri);
@@ -14487,8 +14524,61 @@ function s3Storage(config) {
14487
14524
  Key: key
14488
14525
  }));
14489
14526
  return { deleted: true };
14527
+ },
14528
+ async listObjects(prefix) {
14529
+ const objects = [];
14530
+ let continuationToken;
14531
+ do {
14532
+ const response = await client.send(new _aws_sdk_client_s3.ListObjectsV2Command({
14533
+ Bucket: bucketName,
14534
+ ContinuationToken: continuationToken,
14535
+ Prefix: getListPrefix(prefix)
14536
+ }));
14537
+ for (const object of response.Contents ?? []) {
14538
+ if (!object.Key) continue;
14539
+ const storageUri = getListedStorageUri(object.Key);
14540
+ if (storageUri === null) continue;
14541
+ objects.push({
14542
+ key: getRelativeKey(object.Key),
14543
+ lastModifiedAt: object.LastModified,
14544
+ size: object.Size ?? 0,
14545
+ storageUri
14546
+ });
14547
+ }
14548
+ continuationToken = response.NextContinuationToken;
14549
+ } while (continuationToken);
14550
+ return objects;
14551
+ },
14552
+ async deleteObjects(relativeKeys) {
14553
+ const keys = relativeKeys.map((key) => getStorageKey(key));
14554
+ for (let offset = 0; offset < keys.length; offset += DELETE_BATCH_SIZE) {
14555
+ const batch = keys.slice(offset, offset + DELETE_BATCH_SIZE);
14556
+ const response = await client.send(new _aws_sdk_client_s3.DeleteObjectsCommand({
14557
+ Bucket: bucketName,
14558
+ Delete: {
14559
+ Objects: batch.map((Key) => ({ Key })),
14560
+ Quiet: true
14561
+ }
14562
+ }));
14563
+ if (response.Errors && response.Errors.length > 0) throw new Error(`Failed to delete ${response.Errors.length} S3 object(s) from bucket "${bucketName}".`);
14564
+ }
14490
14565
  }
14491
14566
  });
14567
+ };
14568
+ //#endregion
14569
+ //#region src/s3Storage.ts
14570
+ function s3Storage(config) {
14571
+ const { bucketName, basePath, getDownloadUrl, credentials, ...s3Config } = config;
14572
+ return createS3Storage({
14573
+ name: "s3Storage",
14574
+ protocol: "s3"
14575
+ }, {
14576
+ ...applyS3RuntimeAwsConfig(s3Config),
14577
+ credentials,
14578
+ bucketName,
14579
+ basePath,
14580
+ getDownloadUrl
14581
+ });
14492
14582
  }
14493
14583
  //#endregion
14494
14584
  //#region lambda/index.ts