@hot-updater/azure 1.2.0-rc.4 → 1.2.0-rc.40

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.
@@ -1,5 +1,6 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { EventEmitter } from "events";
3
+ import Stream, { Duplex, Readable, Transform } from "node:stream";
3
4
  import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes } from "node:crypto";
4
5
  import process$1 from "node:process";
5
6
  import os, { EOL } from "node:os";
@@ -7,7 +8,6 @@ import util, { inspect } from "node:util";
7
8
  import http from "node:http";
8
9
  import https from "node:https";
9
10
  import zlib from "node:zlib";
10
- import Stream, { Duplex, Readable, Transform } from "node:stream";
11
11
  import { Readable as Readable$1 } from "stream";
12
12
  import buffer from "node:buffer";
13
13
  import { Buffer as Buffer$1 } from "buffer";
@@ -6104,9 +6104,32 @@ const nativeBuilds = defineTable({
6104
6104
  type: "string",
6105
6105
  maxLength: 255,
6106
6106
  required: false
6107
+ },
6108
+ is_store_build: { type: "boolean" },
6109
+ is_sandbox: { type: "boolean" },
6110
+ sandbox_url_scheme: {
6111
+ type: "string",
6112
+ maxLength: 255,
6113
+ ascii: true,
6114
+ required: false
6115
+ },
6116
+ export_method: {
6117
+ type: "string",
6118
+ maxLength: 16,
6119
+ required: false
6120
+ },
6121
+ native_app_version: {
6122
+ type: "string",
6123
+ required: false
6107
6124
  }
6108
6125
  }, {
6109
6126
  key: ["id"],
6127
+ derived: { store_build_scope_key: {
6128
+ type: "string",
6129
+ maxLength: 2048,
6130
+ ascii: true,
6131
+ compute: (row) => row.is_store_build ? row.scope_key : null
6132
+ } },
6110
6133
  indexes: {
6111
6134
  byScope: {
6112
6135
  eq: ["scope_key"],
@@ -6116,6 +6139,11 @@ const nativeBuilds = defineTable({
6116
6139
  eq: ["scope_key", "build_key"],
6117
6140
  sort: ["id"]
6118
6141
  },
6142
+ byStoreBuild: {
6143
+ eq: ["store_build_scope_key"],
6144
+ sort: [],
6145
+ unique: true
6146
+ },
6119
6147
  byChannel: {
6120
6148
  eq: ["channel_id"],
6121
6149
  sort: ["id"],
@@ -6127,6 +6155,92 @@ const nativeBuilds = defineTable({
6127
6155
  }
6128
6156
  }
6129
6157
  });
6158
+ const iosDevices = defineTable({
6159
+ id: {
6160
+ type: "string",
6161
+ maxLength: 36
6162
+ },
6163
+ udid: {
6164
+ type: "string",
6165
+ maxLength: 40,
6166
+ ascii: true,
6167
+ unique: true
6168
+ },
6169
+ name: {
6170
+ type: "string",
6171
+ maxLength: 100
6172
+ },
6173
+ status: {
6174
+ type: "string",
6175
+ maxLength: 16
6176
+ },
6177
+ requested_by: {
6178
+ type: "string",
6179
+ maxLength: 320,
6180
+ required: false
6181
+ },
6182
+ created_at_ms: { type: "integer" },
6183
+ approved_by: {
6184
+ type: "string",
6185
+ maxLength: 320,
6186
+ required: false
6187
+ },
6188
+ approved_at_ms: {
6189
+ type: "integer",
6190
+ required: false
6191
+ },
6192
+ registered_at_ms: {
6193
+ type: "integer",
6194
+ required: false
6195
+ },
6196
+ apple_issuer_id: {
6197
+ type: "string",
6198
+ maxLength: 64,
6199
+ ascii: true,
6200
+ required: false
6201
+ },
6202
+ apple_error: {
6203
+ type: "string",
6204
+ maxLength: 512,
6205
+ required: false
6206
+ },
6207
+ build_id: {
6208
+ type: "string",
6209
+ maxLength: 36,
6210
+ required: false
6211
+ }
6212
+ }, {
6213
+ key: ["id"],
6214
+ indexes: {
6215
+ byStatus: {
6216
+ eq: ["status"],
6217
+ sort: ["id"]
6218
+ },
6219
+ all: {
6220
+ eq: [],
6221
+ sort: ["id"]
6222
+ }
6223
+ }
6224
+ });
6225
+ const iosDeviceAccount = defineTable({
6226
+ id: {
6227
+ type: "string",
6228
+ maxLength: 16,
6229
+ ascii: true
6230
+ },
6231
+ apple_issuer_id: {
6232
+ type: "string",
6233
+ maxLength: 64,
6234
+ ascii: true
6235
+ },
6236
+ claimed_at_ms: { type: "integer" }
6237
+ }, {
6238
+ key: ["id"],
6239
+ indexes: { all: {
6240
+ eq: [],
6241
+ sort: ["id"]
6242
+ } }
6243
+ });
6130
6244
  const coreModule = {
6131
6245
  id: "core",
6132
6246
  schema: {
@@ -6146,7 +6260,9 @@ const coreModule = {
6146
6260
  sort: []
6147
6261
  } }
6148
6262
  }),
6149
- native_builds: nativeBuilds
6263
+ native_builds: nativeBuilds,
6264
+ ios_devices: iosDevices,
6265
+ ios_device_account: iosDeviceAccount
6150
6266
  }
6151
6267
  };
6152
6268
  //#endregion
@@ -6311,10 +6427,7 @@ const LOG_TABLES = [
6311
6427
  const LEASE_TABLE = "aggregate_lease";
6312
6428
  const LEASE = { id: "compaction" };
6313
6429
  const LEASE_MS = 3e4;
6314
- const WINDOW_MS$1 = {
6315
- log: 6e4,
6316
- memory: 15e3
6317
- };
6430
+ const WINDOW_MS$1 = 6e4;
6318
6431
  const LOG_PAGE = 200;
6319
6432
  const GROUPS = {
6320
6433
  commit: 1,
@@ -6322,7 +6435,6 @@ const GROUPS = {
6322
6435
  flush: 256
6323
6436
  };
6324
6437
  const ATTEMPTS = 5;
6325
- const MAX_BUFFERED = 1e4;
6326
6438
  const log$1 = defineTable({
6327
6439
  id: {
6328
6440
  type: "string",
@@ -6423,8 +6535,8 @@ const rewrite = (change, key, current) => {
6423
6535
  previous: current
6424
6536
  };
6425
6537
  };
6426
- const compile = async (adapter, changes, shard) => {
6427
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
6538
+ const compile = async (adapter, changes) => {
6539
+ const keys = changes.map(({ key }) => [...key.slice(0, -1), 0]);
6428
6540
  const reads = /* @__PURE__ */ new Map();
6429
6541
  changes.forEach((change, at) => {
6430
6542
  if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
@@ -6470,7 +6582,7 @@ const encode$1 = async (changes) => {
6470
6582
  const zipped = await deflate(json);
6471
6583
  return zipped !== void 0 && zipped.length < json.length ? `z${zipped}` : json;
6472
6584
  };
6473
- const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS$1[mode] }, now }) => {
6585
+ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs = WINDOW_MS$1 }, now }) => {
6474
6586
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
6475
6587
  const holder = crypto.randomUUID().replaceAll("-", "");
6476
6588
  const table = (name) => schema.models.get(name).table;
@@ -6497,61 +6609,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6497
6609
  }
6498
6610
  return changes;
6499
6611
  };
6500
- const apply = async (changes, shard) => {
6501
- let rest = changes;
6502
- let ops = [];
6503
- let read = true;
6504
- for (let failures = 0; rest.length > 0 && failures < ATTEMPTS;) try {
6505
- if (read) ops = await compile(adapter, rest, shard);
6506
- let size = rest.length;
6507
- const chunk = () => ops.slice(0, size).filter(isOp);
6508
- while (size > 1 && !adapter.fits(chunk())) size = Math.ceil(size / 2);
6509
- let result = { ok: true };
6510
- if (chunk().length > 0) result = await adapter.write(chunk()).catch((error) => {
6511
- warn("flush")(error);
6512
- return { ok: true };
6513
- });
6514
- read = !result.ok && !("retry" in result);
6515
- if (result.ok) {
6516
- rest = rest.slice(size);
6517
- ops = ops.slice(size);
6518
- failures = 0;
6519
- } else {
6520
- failures += 1;
6521
- if (!read) await sleep$1(failures);
6522
- }
6523
- } catch (error) {
6524
- warn("flush")(error);
6525
- return rest;
6526
- }
6527
- return rest;
6528
- };
6529
- let buffer = /* @__PURE__ */ new Map();
6530
- let timer;
6531
- let flushing;
6532
- const shards = /* @__PURE__ */ new Map();
6533
- const processShard = (model) => {
6534
- if (!shards.has(model)) shards.set(model, Math.floor(Math.random() * shapeOf(model).shards));
6535
- return shards.get(model);
6536
- };
6537
- const schedule = () => {
6538
- if (timer !== void 0 || buffer.size === 0) return;
6539
- timer = setTimeout(() => {
6540
- timer = void 0;
6541
- flushBuffer();
6542
- }, windowMs);
6543
- timer.unref?.();
6544
- };
6545
- const flushBuffer = () => flushing ??= (async () => {
6546
- clearTimeout(timer);
6547
- timer = void 0;
6548
- const pending = [...buffer.values()];
6549
- buffer = /* @__PURE__ */ new Map();
6550
- mergeAll(buffer, await apply(pending, processShard));
6551
- })().catch(warn("flush")).finally(() => {
6552
- flushing = void 0;
6553
- schedule();
6554
- });
6555
6612
  let nextDue = 0;
6556
6613
  let compacting;
6557
6614
  const known = /* @__PURE__ */ new Map();
@@ -6673,7 +6730,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6673
6730
  more
6674
6731
  };
6675
6732
  };
6676
- const rowsFor = async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp);
6733
+ const rowsFor = async (changes) => (await compile(adapter, changes)).filter(isOp);
6677
6734
  const applyGroup = async (held, logs) => {
6678
6735
  for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
6679
6736
  const batch = logs.slice(0, count);
@@ -6753,19 +6810,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6753
6810
  }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
6754
6811
  checking = void 0;
6755
6812
  });
6756
- const committed = async (changes) => {
6757
- if (mode === "log") {
6758
- if (now() >= nextDue) await compact(false, GROUPS.commit);
6759
- return;
6760
- }
6761
- mergeAll(buffer, changes.values());
6762
- schedule();
6763
- if (buffer.size >= MAX_BUFFERED) await flushBuffer();
6764
- };
6765
- const flush = async () => {
6766
- await flushBuffer();
6767
- if (mode === "log" && await hasPending()) await compact(true, GROUPS.flush);
6768
- };
6769
6813
  return {
6770
6814
  async transaction(fn) {
6771
6815
  let changes = /* @__PURE__ */ new Map();
@@ -6791,7 +6835,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6791
6835
  aggregate
6792
6836
  });
6793
6837
  if (failure) throw failure.error;
6794
- if (mode === "log" && attempt.size > 0) {
6838
+ if (attempt.size > 0) {
6795
6839
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
6796
6840
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
6797
6841
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -6805,24 +6849,18 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6805
6849
  open = false;
6806
6850
  }
6807
6851
  });
6808
- if (changes.size > 0) await committed(changes);
6852
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
6809
6853
  return result;
6810
6854
  },
6811
6855
  async beforeRead(name) {
6812
6856
  if (!isBatched(schema.models.get(name))) return;
6813
- if (buffer.size > 0 || flushing !== void 0) await flushBuffer();
6814
- if (mode === "log") {
6815
- if (await hasPending().catch((error) => {
6816
- warn("read")(error);
6817
- return false;
6818
- })) await compact(true, GROUPS.read);
6819
- }
6857
+ if (await hasPending().catch((error) => {
6858
+ warn("read")(error);
6859
+ return false;
6860
+ })) await compact(true, GROUPS.read);
6820
6861
  },
6821
- flush,
6822
- async dispose() {
6823
- clearTimeout(timer);
6824
- timer = void 0;
6825
- await flush();
6862
+ async flush() {
6863
+ if (await hasPending()) await compact(true, GROUPS.flush);
6826
6864
  }
6827
6865
  };
6828
6866
  };
@@ -6941,7 +6979,8 @@ const fieldProblems = (definition, add) => {
6941
6979
  else if (field.required === false) add(`key field "${name}" is nullable`);
6942
6980
  else if (field.type === "json") add(`key field "${name}" is json`);
6943
6981
  }
6944
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
6982
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
6983
+ for (const [name, { type, maxLength, ascii }] of bounded) {
6945
6984
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
6946
6985
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
6947
6986
  }
@@ -7053,11 +7092,13 @@ const resolveSchema = (modules) => {
7053
7092
  ...maxLength === void 0 ? {} : { maxLength },
7054
7093
  ...ascii ? { ascii } : {}
7055
7094
  }));
7056
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
7095
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
7057
7096
  name: field,
7058
7097
  type,
7059
7098
  nullable: true,
7060
- ...multi ? { multi } : {}
7099
+ ...multi ? { multi } : {},
7100
+ ...maxLength === void 0 ? {} : { maxLength },
7101
+ ...ascii ? { ascii } : {}
7061
7102
  });
7062
7103
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
7063
7104
  name: metric,
@@ -7788,9 +7829,6 @@ const createDatabaseEngine = ({ batching, now = Date.now, meter, ...options }) =
7788
7829
  flush: async () => {
7789
7830
  await batches?.flush();
7790
7831
  },
7791
- dispose: async () => {
7792
- await batches?.dispose();
7793
- },
7794
7832
  database(module) {
7795
7833
  const name = (model) => module.namespace ? `${module.namespace}_${model}` : model;
7796
7834
  return {
@@ -7858,8 +7896,7 @@ const createEngine = (database, { plugins = [], now = Date.now } = {}) => {
7858
7896
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
7859
7897
  return engine.database(module);
7860
7898
  },
7861
- flush: () => engine.flush(),
7862
- dispose: () => engine.dispose()
7899
+ flush: () => engine.flush()
7863
7900
  };
7864
7901
  };
7865
7902
  //#endregion
@@ -8118,7 +8155,7 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
8118
8155
  };
8119
8156
  //#endregion
8120
8157
  //#region ../../packages/server/dist/version.mjs
8121
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.4";
8158
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.40";
8122
8159
  //#endregion
8123
8160
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
8124
8161
  const createVersionRouteHandlers = (plugins = []) => {
@@ -8851,8 +8888,8 @@ const baseBundleIdsOf = (row, range, bundleId, limit) => {
8851
8888
  //#endregion
8852
8889
  //#region ../../packages/server/dist/core/reads.mjs
8853
8890
  const PAGE$3 = 500;
8854
- const pick$1 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
8855
- const toBundleRow = pick$1([
8891
+ const pick$2 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
8892
+ const toBundleRow = pick$2([
8856
8893
  "id",
8857
8894
  "platform",
8858
8895
  "git_commit_hash",
@@ -8861,7 +8898,7 @@ const toBundleRow = pick$1([
8861
8898
  "manifest_file_hash",
8862
8899
  "asset_base_storage_uri"
8863
8900
  ]);
8864
- const toPatchRow = pick$1([
8901
+ const toPatchRow = pick$2([
8865
8902
  "id",
8866
8903
  "bundle_id",
8867
8904
  "base_bundle_id",
@@ -8871,7 +8908,7 @@ const toPatchRow = pick$1([
8871
8908
  "byte_size",
8872
8909
  "order_index"
8873
8910
  ]);
8874
- const toReleaseRow = pick$1([
8911
+ const toReleaseRow = pick$2([
8875
8912
  "id",
8876
8913
  "revision",
8877
8914
  "scope_key",
@@ -8892,7 +8929,7 @@ const toReleaseRow = pick$1([
8892
8929
  "created_at_ms",
8893
8930
  "updated_at_ms"
8894
8931
  ]);
8895
- const toCatalogRow = pick$1([
8932
+ const toCatalogRow = pick$2([
8896
8933
  "scope_key",
8897
8934
  "catalog_id",
8898
8935
  "strategy",
@@ -8907,7 +8944,7 @@ const toCatalogRow = pick$1([
8907
8944
  "is_tombstone",
8908
8945
  "updated_at_ms"
8909
8946
  ]);
8910
- const toChannelRow = pick$1(["id", "name"]);
8947
+ const toChannelRow = pick$2(["id", "name"]);
8911
8948
  const drain$1 = async (read) => {
8912
8949
  const rows = [];
8913
8950
  let cursor;
@@ -8918,7 +8955,14 @@ const drain$1 = async (read) => {
8918
8955
  } while (cursor !== void 0);
8919
8956
  return rows;
8920
8957
  };
8921
- const after = (input) => input.after === void 0 ? {} : { range: (input.order ?? "asc") === "asc" ? { gt: input.after } : { lt: input.after } };
8958
+ const after = (input) => {
8959
+ const asc = (input.order ?? "asc") === "asc";
8960
+ const range = {
8961
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
8962
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
8963
+ };
8964
+ return Object.keys(range).length === 0 ? {} : { range };
8965
+ };
8922
8966
  const createCoreReads = (db, storage) => {
8923
8967
  const detail = async (row) => {
8924
8968
  const count = row._refs_bundle_patches_bundle_id ?? 0;
@@ -9109,6 +9153,293 @@ const createCoreReads = (db, storage) => {
9109
9153
  };
9110
9154
  };
9111
9155
  //#endregion
9156
+ //#region ../../packages/server/dist/core/iosDevices.mjs
9157
+ const UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
9158
+ const normalizeIosUdid = (value) => {
9159
+ const trimmed = value.trim();
9160
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
9161
+ };
9162
+ const NAME_MAX_LENGTH = 100;
9163
+ const EMAIL_MAX_LENGTH = 320;
9164
+ const ISSUER_MAX_LENGTH = 64;
9165
+ const ACCOUNT_SCAN_PAGE = 200;
9166
+ const ACCOUNT_ROW = "registry";
9167
+ const ERROR_MAX_LENGTH = 512;
9168
+ const STATUSES = [
9169
+ "pending",
9170
+ "approved",
9171
+ "registered"
9172
+ ];
9173
+ const OUTCOMES = [
9174
+ "registered",
9175
+ "refused",
9176
+ "disabled",
9177
+ "missing"
9178
+ ];
9179
+ const IOS_DEVICE_DISABLED_ERROR = "Disabled in the Apple account.";
9180
+ const IOS_DEVICE_MISSING_ERROR = "Gone from the Apple account. Approve it again to register it.";
9181
+ var IosDeviceInputError = class extends TypeError {
9182
+ name = "IosDeviceInputError";
9183
+ };
9184
+ const pick$1 = (row) => ({
9185
+ id: row.id,
9186
+ udid: row.udid,
9187
+ name: row.name,
9188
+ status: row.status,
9189
+ requested_by: row.requested_by ?? null,
9190
+ created_at_ms: row.created_at_ms,
9191
+ approved_by: row.approved_by ?? null,
9192
+ approved_at_ms: row.approved_at_ms ?? null,
9193
+ registered_at_ms: row.registered_at_ms ?? null,
9194
+ apple_issuer_id: row.apple_issuer_id ?? null,
9195
+ apple_error: row.apple_error ?? null,
9196
+ build_id: row.build_id ?? null
9197
+ });
9198
+ const udidOf = (udid) => {
9199
+ const key = typeof udid === "string" ? normalizeIosUdid(udid) : null;
9200
+ if (key === null) throw new IosDeviceInputError("Invalid iOS device: udid must be 40 hex digits, or 8 and 16 joined by a hyphen.");
9201
+ return key;
9202
+ };
9203
+ const nameOf = (name) => {
9204
+ const trimmed = typeof name === "string" ? name.trim() : "";
9205
+ if (trimmed.length === 0 || trimmed.length > NAME_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: name must be 1 to ${NAME_MAX_LENGTH} characters.`);
9206
+ return trimmed;
9207
+ };
9208
+ const personOf = (value, field) => {
9209
+ if (value === null) return null;
9210
+ const email = typeof value === "string" ? value.trim().toLowerCase() : "";
9211
+ if (email.length === 0 || email.length > EMAIL_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: ${field} must be an email of at most ${EMAIL_MAX_LENGTH} characters, or null.`);
9212
+ return email;
9213
+ };
9214
+ const errorText = (text) => {
9215
+ const line = text.replace(/\s+/gu, " ").trim();
9216
+ return line.length > ERROR_MAX_LENGTH ? `${line.slice(0, 511)}…` : line;
9217
+ };
9218
+ const createIosDeviceApi = (db, { now = Date.now } = {}) => {
9219
+ const findIosDevice = async (udid) => {
9220
+ const key = normalizeIosUdid(udid);
9221
+ if (key === null) return null;
9222
+ const row = await db.findOne("ios_devices", { udid: key });
9223
+ return row === null ? null : pick$1(row);
9224
+ };
9225
+ const accountOfRows = async () => {
9226
+ let earliest = null;
9227
+ for (let after;;) {
9228
+ const { rows } = await db.findMany("ios_devices", {
9229
+ index: "all",
9230
+ where: {},
9231
+ order: "asc",
9232
+ limit: ACCOUNT_SCAN_PAGE,
9233
+ ...after === void 0 ? {} : { range: { gt: after } }
9234
+ });
9235
+ for (const row of rows.map(pick$1)) {
9236
+ if (row.apple_issuer_id === null) continue;
9237
+ if (earliest === null || (row.registered_at_ms ?? 0) < (earliest.registered_at_ms ?? 0)) earliest = row;
9238
+ }
9239
+ if (rows.length < ACCOUNT_SCAN_PAGE) return earliest?.apple_issuer_id ?? null;
9240
+ after = rows.at(-1).id;
9241
+ }
9242
+ };
9243
+ return {
9244
+ async listIosDevices(input) {
9245
+ if (input.status !== void 0 && !STATUSES.includes(input.status)) throw new IosDeviceInputError(`Invalid iOS device status: ${String(input.status)}. Expected ${STATUSES.join(", ")}.`);
9246
+ const page = {
9247
+ order: input.order ?? "asc",
9248
+ limit: input.limit,
9249
+ ...after(input)
9250
+ };
9251
+ const { rows } = input.status === void 0 ? await db.findMany("ios_devices", {
9252
+ index: "all",
9253
+ where: {},
9254
+ ...page
9255
+ }) : await db.findMany("ios_devices", {
9256
+ index: "byStatus",
9257
+ where: { status: input.status },
9258
+ ...page
9259
+ });
9260
+ return rows.map(pick$1);
9261
+ },
9262
+ findIosDevice,
9263
+ async requestIosDevice(input) {
9264
+ const udid = udidOf(input.udid);
9265
+ const name = nameOf(input.name);
9266
+ const requestedBy = personOf(input.requestedBy, "requestedBy");
9267
+ const existing = await db.findOne("ios_devices", { udid });
9268
+ if (existing !== null) return {
9269
+ device: pick$1(existing),
9270
+ created: false
9271
+ };
9272
+ const device = {
9273
+ id: createUUIDv7(),
9274
+ udid,
9275
+ name,
9276
+ status: "pending",
9277
+ requested_by: requestedBy,
9278
+ created_at_ms: now(),
9279
+ approved_by: null,
9280
+ approved_at_ms: null,
9281
+ registered_at_ms: null,
9282
+ apple_issuer_id: null,
9283
+ apple_error: null,
9284
+ build_id: null
9285
+ };
9286
+ try {
9287
+ await db.transaction(async (tx) => {
9288
+ tx.create("ios_devices", device);
9289
+ });
9290
+ } catch (error) {
9291
+ if (error instanceof DatabaseConstraintError && error.reason === "unique") {
9292
+ const winner = await db.findOne("ios_devices", { udid });
9293
+ if (winner !== null) return {
9294
+ device: pick$1(winner),
9295
+ created: false
9296
+ };
9297
+ }
9298
+ throw error;
9299
+ }
9300
+ return {
9301
+ device,
9302
+ created: true
9303
+ };
9304
+ },
9305
+ async approveIosDevice(id, input) {
9306
+ const name = input.name === void 0 ? void 0 : nameOf(input.name);
9307
+ const approvedBy = personOf(input.approvedBy, "approvedBy");
9308
+ return db.transaction(async (tx) => {
9309
+ const row = await tx.findOne("ios_devices", { id });
9310
+ if (row === null) return null;
9311
+ const device = pick$1(row);
9312
+ const set = {
9313
+ ...name === void 0 || name === device.name ? {} : { name },
9314
+ ...device.status === "pending" ? {
9315
+ status: "approved",
9316
+ approved_by: approvedBy,
9317
+ approved_at_ms: now()
9318
+ } : {}
9319
+ };
9320
+ if (Object.keys(set).length === 0) return device;
9321
+ tx.update("ios_devices", row, set);
9322
+ return {
9323
+ ...device,
9324
+ ...set
9325
+ };
9326
+ });
9327
+ },
9328
+ async renameIosDevice(id, input) {
9329
+ const name = nameOf(input);
9330
+ return db.transaction(async (tx) => {
9331
+ const row = await tx.findOne("ios_devices", { id });
9332
+ if (row === null) return null;
9333
+ const device = pick$1(row);
9334
+ if (device.name === name) return device;
9335
+ tx.update("ios_devices", row, { name });
9336
+ return {
9337
+ ...device,
9338
+ name
9339
+ };
9340
+ });
9341
+ },
9342
+ async recordIosDeviceOutcome({ id, seen, issuerId, outcome, reason }) {
9343
+ if (!OUTCOMES.includes(outcome)) throw new IosDeviceInputError(`Invalid iOS device outcome: ${String(outcome)}. Expected ${OUTCOMES.join(", ")}.`);
9344
+ if (typeof issuerId !== "string" || issuerId.trim().length === 0 || issuerId.length > ISSUER_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device outcome: issuerId must be an App Store Connect issuer of at most ${ISSUER_MAX_LENGTH} characters.`);
9345
+ return db.transaction(async (tx) => {
9346
+ const row = await tx.findOne("ios_devices", { id });
9347
+ if (row === null) return null;
9348
+ const device = pick$1(row);
9349
+ if (device.status !== seen.status || device.approved_at_ms !== seen.approvedAtMs || device.apple_issuer_id !== null && device.apple_issuer_id !== issuerId) return null;
9350
+ let set;
9351
+ switch (outcome) {
9352
+ case "registered":
9353
+ if (device.status === "pending") return null;
9354
+ set = {
9355
+ status: "registered",
9356
+ registered_at_ms: device.registered_at_ms ?? now(),
9357
+ apple_issuer_id: issuerId,
9358
+ apple_error: null
9359
+ };
9360
+ break;
9361
+ case "refused":
9362
+ if (device.status !== "approved") return null;
9363
+ set = { apple_error: errorText(reason === void 0 || reason.trim() === "" ? "Apple refused it." : reason) };
9364
+ break;
9365
+ case "disabled":
9366
+ if (device.status === "pending") return null;
9367
+ set = { apple_error: IOS_DEVICE_DISABLED_ERROR };
9368
+ break;
9369
+ case "missing":
9370
+ if (device.status !== "registered") return null;
9371
+ set = {
9372
+ status: "pending",
9373
+ approved_by: null,
9374
+ approved_at_ms: null,
9375
+ apple_error: IOS_DEVICE_MISSING_ERROR
9376
+ };
9377
+ }
9378
+ if (Object.entries(set).some(([column, value]) => device[column] !== (value ?? null))) tx.update("ios_devices", row, set);
9379
+ return {
9380
+ ...device,
9381
+ ...set
9382
+ };
9383
+ });
9384
+ },
9385
+ async markIosDevicesInBuild({ buildId, ids }) {
9386
+ for (const id of new Set(ids)) await db.transaction(async (tx) => {
9387
+ const row = await tx.findOne("ios_devices", { id });
9388
+ if (row === null || typeof row.build_id === "string" && row.build_id >= buildId) return;
9389
+ tx.update("ios_devices", row, { build_id: buildId });
9390
+ });
9391
+ },
9392
+ async claimIosDeviceAccount(issuerId) {
9393
+ if (typeof issuerId !== "string" || issuerId.trim().length === 0 || issuerId.length > ISSUER_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device account: issuerId must be an App Store Connect issuer of at most ${ISSUER_MAX_LENGTH} characters.`);
9394
+ const answer = (held) => ({
9395
+ issuerId: held,
9396
+ claimed: held === issuerId
9397
+ });
9398
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
9399
+ if (existing !== null) return answer(existing.apple_issuer_id);
9400
+ const holder = await accountOfRows() ?? issuerId;
9401
+ try {
9402
+ await db.transaction(async (tx) => {
9403
+ tx.create("ios_device_account", {
9404
+ id: ACCOUNT_ROW,
9405
+ apple_issuer_id: holder,
9406
+ claimed_at_ms: now()
9407
+ });
9408
+ });
9409
+ return answer(holder);
9410
+ } catch (error) {
9411
+ if (error instanceof DatabaseConstraintError && (error.reason === "exists" || error.reason === "unique")) {
9412
+ const winner = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
9413
+ if (winner !== null) return answer(winner.apple_issuer_id);
9414
+ }
9415
+ throw error;
9416
+ }
9417
+ },
9418
+ async deleteIosDevice(id, only) {
9419
+ const requestedBy = only?.requestedBy === void 0 ? void 0 : personOf(only.requestedBy, "requestedBy");
9420
+ return db.transaction(async (tx) => {
9421
+ const row = await tx.findOne("ios_devices", { id });
9422
+ if (row === null) return null;
9423
+ const device = pick$1(row);
9424
+ if (only?.status !== void 0 && device.status !== only.status || requestedBy !== void 0 && device.requested_by !== requestedBy) return null;
9425
+ await tx.delete("ios_devices", row);
9426
+ return device;
9427
+ });
9428
+ }
9429
+ };
9430
+ };
9431
+ //#endregion
9432
+ //#region ../../packages/server/dist/core/nativeBuildDestinations.mjs
9433
+ const NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
9434
+ android: [
9435
+ "play-internal",
9436
+ "play-closed",
9437
+ "play-open",
9438
+ "play-production"
9439
+ ],
9440
+ ios: ["testflight"]
9441
+ };
9442
+ //#endregion
9112
9443
  //#region ../../packages/server/dist/core/writes.mjs
9113
9444
  const PAGE$2 = 500;
9114
9445
  const countBundle = (tx, platform, delta) => {
@@ -9129,7 +9460,7 @@ const deleteBundle = async (tx, current) => {
9129
9460
  await tx.delete("bundles", current);
9130
9461
  countBundle(tx, current.platform, -1);
9131
9462
  };
9132
- const replaceBundlePatches = async (tx, bundle, rows) => {
9463
+ const replaceBundlePatches = async (tx, bundle, rows, checkNew) => {
9133
9464
  const wanted = new Map(rows.map((row) => [row.id, row]));
9134
9465
  const count = bundle._refs_bundle_patches_bundle_id ?? 0;
9135
9466
  let cursor;
@@ -9154,6 +9485,7 @@ const replaceBundlePatches = async (tx, bundle, rows) => {
9154
9485
  if (page.next === void 0) break;
9155
9486
  cursor = page.next;
9156
9487
  }
9488
+ if (checkNew !== void 0) for (const row of wanted.values()) await checkNew(row);
9157
9489
  for (const row of wanted.values()) tx.create("bundle_patches", row);
9158
9490
  };
9159
9491
  const insertChannel = async (db, row) => {
@@ -9206,6 +9538,8 @@ const ARTIFACT_KINDS = {
9206
9538
  const SCOPE_KEY_MAX_LENGTH = 2048;
9207
9539
  const GIT_COMMIT_HASH_MAX_LENGTH = 255;
9208
9540
  const BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
9541
+ const SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
9542
+ const URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
9209
9543
  var NativeBuildInputError = class extends TypeError {
9210
9544
  name = "NativeBuildInputError";
9211
9545
  };
@@ -9226,12 +9560,22 @@ const pick = (row) => ({
9226
9560
  build_number: row.build_number ?? null,
9227
9561
  submitted_to: row.submitted_to ?? null,
9228
9562
  submitted_at_ms: row.submitted_at_ms ?? null,
9229
- submitted_version: row.submitted_version ?? null
9563
+ submitted_version: row.submitted_version ?? null,
9564
+ is_store_build: row.is_store_build === true,
9565
+ is_sandbox: row.is_sandbox === true,
9566
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
9567
+ export_method: row.export_method ?? null,
9568
+ native_app_version: row.native_app_version ?? null
9230
9569
  });
9231
- const SUBMISSION_DESTINATIONS = {
9232
- android: "play-internal",
9233
- ios: "testflight"
9234
- };
9570
+ const EXPORT_METHODS = /* @__PURE__ */ new Set([
9571
+ "app-store",
9572
+ "ad-hoc",
9573
+ "development",
9574
+ "enterprise"
9575
+ ]);
9576
+ const SANDBOX_CHANNEL_PREFIX = "sandbox-";
9577
+ const OLDER_BUILDS_PAGE = 20;
9578
+ const MARK_ATTEMPTS = 8;
9235
9579
  const BUILD_NUMBER_MAX_LENGTH = 64;
9236
9580
  const SUBMITTED_VERSION_MAX_LENGTH = 255;
9237
9581
  const nativeBuildScopeKey = (scope) => {
@@ -9254,18 +9598,34 @@ const nativeBuildScopeKey = (scope) => {
9254
9598
  if (scopeKey.length > SCOPE_KEY_MAX_LENGTH) throw new NativeBuildInputError(`Invalid native build scope: its key is longer than ${SCOPE_KEY_MAX_LENGTH} characters; shorten the channel or app version.`);
9255
9599
  return scopeKey;
9256
9600
  };
9601
+ const refuseSandboxPatchBase = async (db, baseBundleId) => {
9602
+ if ((await db.findOne("native_builds", { min_bundle_id: baseBundleId }))?.is_sandbox === true) throw new NativeBuildInputError("A sandbox build's built-in bundle is no patch base.");
9603
+ };
9257
9604
  const isBuiltInBundle = async (db, bundleId) => await db.findOne("native_builds", { min_bundle_id: bundleId }) !== null;
9258
- const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, artifact }) => {
9605
+ const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, exportMethod, nativeAppVersion, artifact }) => {
9259
9606
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
9260
9607
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
9261
9608
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
9262
9609
  if (channel.trim().length === 0) return "channel is required";
9610
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
9611
+ const reserved = channel.startsWith(SANDBOX_CHANNEL_PREFIX);
9612
+ if (isSandbox === true && !reserved) return `a sandbox build registers on a ${SANDBOX_CHANNEL_PREFIX}* channel, not ${channel}`;
9613
+ if (isSandbox !== true && reserved) return `channel ${channel} is reserved for sandbox builds`;
9614
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
9615
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
9616
+ if (typeof sandboxUrlScheme !== "string" || !URL_SCHEME.test(sandboxUrlScheme)) return `sandboxUrlScheme must be a URL scheme in lower case, up to ${SANDBOX_URL_SCHEME_MAX_LENGTH} characters, or null`;
9617
+ }
9263
9618
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
9264
9619
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
9265
9620
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
9266
9621
  if (buildNumber !== void 0 && buildNumber !== null && (buildNumber.trim().length === 0 || buildNumber.length > BUILD_NUMBER_MAX_LENGTH)) return `buildNumber must be the artifact's build number, up to ${BUILD_NUMBER_MAX_LENGTH} characters, or null`;
9622
+ if (nativeAppVersion !== void 0 && nativeAppVersion !== null && (typeof nativeAppVersion !== "string" || nativeAppVersion.trim().length === 0)) return "nativeAppVersion must be the artifact's app version, or null";
9267
9623
  const kinds = ARTIFACT_KINDS[platform];
9268
9624
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
9625
+ if (exportMethod !== void 0 && exportMethod !== null) {
9626
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
9627
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
9628
+ }
9269
9629
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
9270
9630
  return null;
9271
9631
  };
@@ -9293,7 +9653,12 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9293
9653
  build_number: registration.buildNumber ?? null,
9294
9654
  submitted_to: null,
9295
9655
  submitted_at_ms: null,
9296
- submitted_version: null
9656
+ submitted_version: null,
9657
+ is_store_build: false,
9658
+ is_sandbox: registration.isSandbox === true,
9659
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
9660
+ export_method: registration.exportMethod ?? null,
9661
+ native_app_version: registration.nativeAppVersion ?? null
9297
9662
  };
9298
9663
  for (let attempt = 1;; attempt += 1) {
9299
9664
  await insertChannel(db, {
@@ -9331,21 +9696,43 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9331
9696
  const scopeKey = nativeBuildScopeKey(scope);
9332
9697
  const buildKey = options?.buildKey;
9333
9698
  if (buildKey !== void 0 && !BUILD_KEY.test(buildKey)) throw new NativeBuildInputError("Invalid native build key: it must be nbk1: and a SHA-256.");
9334
- const { rows } = buildKey === void 0 ? await db.findMany("native_builds", {
9335
- index: "byScope",
9336
- where: { scope_key: scopeKey },
9337
- order: "desc",
9338
- limit: 1
9339
- }) : await db.findMany("native_builds", {
9340
- index: "byBuildKey",
9341
- where: {
9342
- scope_key: scopeKey,
9343
- build_key: buildKey
9344
- },
9345
- order: "desc",
9346
- limit: 1
9347
- });
9348
- return rows[0] === void 0 ? null : pick(rows[0]);
9699
+ if (options?.storeBuild) {
9700
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
9701
+ return marked === null ? null : pick(marked);
9702
+ }
9703
+ const read = (limit, before) => {
9704
+ const page = {
9705
+ order: "desc",
9706
+ limit,
9707
+ ...before === void 0 ? {} : { range: { lt: before } }
9708
+ };
9709
+ return buildKey === void 0 ? db.findMany("native_builds", {
9710
+ index: "byScope",
9711
+ where: { scope_key: scopeKey },
9712
+ ...page
9713
+ }) : db.findMany("native_builds", {
9714
+ index: "byBuildKey",
9715
+ where: {
9716
+ scope_key: scopeKey,
9717
+ build_key: buildKey
9718
+ },
9719
+ ...page
9720
+ });
9721
+ };
9722
+ const bundleId = options?.builtInOlderThan;
9723
+ if (bundleId !== void 0 && scope.channel.startsWith(SANDBOX_CHANNEL_PREFIX)) return null;
9724
+ const { rows } = await read(1);
9725
+ const newest = rows[0];
9726
+ if (newest === void 0) return null;
9727
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return pick(newest);
9728
+ for (let before = newest.id;;) {
9729
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
9730
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
9731
+ if (usable !== void 0) return pick(usable);
9732
+ const last = older.at(-1);
9733
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
9734
+ before = last.id;
9735
+ }
9349
9736
  },
9350
9737
  async recordNativeBuildSubmission(id, { destination, version }) {
9351
9738
  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.`);
@@ -9353,7 +9740,8 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9353
9740
  const row = await tx.findOne("native_builds", { id });
9354
9741
  if (row === null) return null;
9355
9742
  const build = pick(row);
9356
- if (SUBMISSION_DESTINATIONS[build.platform] !== destination) throw new NativeBuildInputError(`Invalid native build submission: an ${build.platform} build is submitted to ${SUBMISSION_DESTINATIONS[build.platform]}, not ${destination}.`);
9743
+ if (!NATIVE_BUILD_SUBMISSION_DESTINATIONS[build.platform].includes(destination)) throw new NativeBuildInputError(`Invalid native build submission: an ${build.platform} build is submitted to ${NATIVE_BUILD_SUBMISSION_DESTINATIONS[build.platform].join(" or ")}, not ${destination}.`);
9744
+ if (build.is_sandbox && destination !== "testflight" && destination !== "play-internal") throw new NativeBuildInputError("A sandbox build can submit only to TestFlight or Play internal testing.");
9357
9745
  const set = {
9358
9746
  submitted_to: destination,
9359
9747
  submitted_at_ms: now(),
@@ -9366,6 +9754,46 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9366
9754
  };
9367
9755
  });
9368
9756
  },
9757
+ async markNativeBuild(id, { storeBuild }) {
9758
+ for (let attempt = 1;; attempt += 1) try {
9759
+ return await db.transaction(async (tx) => {
9760
+ const row = await tx.findOne("native_builds", { id });
9761
+ if (row === null) return null;
9762
+ const build = pick(row);
9763
+ if (!storeBuild) {
9764
+ if (build.is_store_build) tx.update("native_builds", row, { is_store_build: false });
9765
+ return {
9766
+ nativeBuild: {
9767
+ ...build,
9768
+ is_store_build: false
9769
+ },
9770
+ previous: null
9771
+ };
9772
+ }
9773
+ if (build.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
9774
+ if (build.is_store_build) return {
9775
+ nativeBuild: build,
9776
+ previous: null
9777
+ };
9778
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build.scope_key });
9779
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
9780
+ tx.update("native_builds", row, { is_store_build: true });
9781
+ return {
9782
+ nativeBuild: {
9783
+ ...build,
9784
+ is_store_build: true
9785
+ },
9786
+ previous: holder === null ? null : {
9787
+ ...pick(holder),
9788
+ is_store_build: false
9789
+ }
9790
+ };
9791
+ });
9792
+ } catch (error) {
9793
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
9794
+ throw error;
9795
+ }
9796
+ },
9369
9797
  async deleteNativeBuild(id) {
9370
9798
  return db.transaction(async (tx) => {
9371
9799
  const row = await tx.findOne("native_builds", { id });
@@ -9685,7 +10113,11 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
9685
10113
  for (const { release } of deployments) if (!channels.has(release.channel)) channels.set(release.channel, await ensureChannel(release.channel));
9686
10114
  const platforms = /* @__PURE__ */ new Map();
9687
10115
  for (const deployment of deployments) {
9688
- if (!("bundleId" in deployment) || platforms.has(deployment.bundleId)) continue;
10116
+ if (!("bundleId" in deployment)) {
10117
+ for (const { baseBundleId } of deployment.bundle.patches ?? []) await refuseSandboxPatchBase(db, baseBundleId);
10118
+ continue;
10119
+ }
10120
+ if (platforms.has(deployment.bundleId)) continue;
9689
10121
  const row = await db.findOne("bundles", { id: deployment.bundleId });
9690
10122
  if (row === null) throw new DatabaseBundleNotFoundError(deployment.bundleId);
9691
10123
  if (await isBuiltInBundle(db, deployment.bundleId)) throw new ReleaseManagementError("TARGET_RELEASE_INVALID", `Bundle "${deployment.bundleId}" is a native build's built-in bundle, which no release publishes.`);
@@ -9889,7 +10321,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
9889
10321
  if (patches !== void 0) await replaceBundlePatches(tx, current, bundleToPatchRows({
9890
10322
  ...next,
9891
10323
  patches
9892
- }));
10324
+ }), (row) => refuseSandboxPatchBase(tx, row.base_bundle_id));
9893
10325
  }),
9894
10326
  deleteBundles: async (ids) => {
9895
10327
  try {
@@ -9945,6 +10377,7 @@ const createCoreApi = (db, storage, options = {}) => {
9945
10377
  ...reads,
9946
10378
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
9947
10379
  ...createNativeBuildApi(db, options),
10380
+ ...createIosDeviceApi(db, options),
9948
10381
  ready: async () => {
9949
10382
  await reads.listReleaseCatalogs({ limit: 1 });
9950
10383
  }
@@ -10154,10 +10587,12 @@ const keyset = (url, maxValue = LIMITS.maxValue) => {
10154
10587
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
10155
10588
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
10156
10589
  const cursor = url.searchParams.get("cursor");
10590
+ const through = url.searchParams.get("through");
10157
10591
  return {
10158
10592
  order,
10159
10593
  limit,
10160
- ...cursor === null ? {} : { after: cursor }
10594
+ ...cursor === null ? {} : { after: cursor },
10595
+ ...through === null ? {} : { through }
10161
10596
  };
10162
10597
  };
10163
10598
  const page = (rows, { limit }, keyOf, extra = {}) => json$2({
@@ -10264,11 +10699,11 @@ const refusingInvalid = async (operation) => {
10264
10699
  try {
10265
10700
  return await operation();
10266
10701
  } catch (error) {
10267
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
10702
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
10268
10703
  throw error;
10269
10704
  }
10270
10705
  };
10271
- const isNativeBuildRegistration = (value) => isRecord$5(value) && isText$2(value.id) && isText$2(value.minBundleId) && typeof value.platform === "string" && isPlatform(value.platform) && isText$2(value.channel) && isTextOrNull$1(value.fingerprintHash) && isTextOrNull$1(value.appVersion) && value.fingerprintHash === null !== (value.appVersion === null) && isTextOrNull$1(value.gitCommitHash) && isTextOrNull$1(value.buildKey) && (value.buildNumber === void 0 || isTextOrNull$1(value.buildNumber)) && isRecord$5(value.artifact) && typeof value.artifact.kind === "string" && NATIVE_BUILD_ARTIFACT_KINDS.has(value.artifact.kind) && isText$2(value.artifact.storageUri) && Number.isSafeInteger(value.artifact.byteSize) && value.artifact.byteSize >= 0 && isRecord$5(value.embeddedBundle) && isText$2(value.embeddedBundle.manifestStorageUri) && isText$2(value.embeddedBundle.manifestFileHash) && isText$2(value.embeddedBundle.assetBaseStorageUri) && (value.embeddedBundle.metadata === void 0 || isRecord$5(value.embeddedBundle.metadata));
10706
+ const isNativeBuildRegistration = (value) => isRecord$5(value) && isText$2(value.id) && isText$2(value.minBundleId) && typeof value.platform === "string" && isPlatform(value.platform) && isText$2(value.channel) && isTextOrNull$1(value.fingerprintHash) && isTextOrNull$1(value.appVersion) && value.fingerprintHash === null !== (value.appVersion === null) && isTextOrNull$1(value.gitCommitHash) && isTextOrNull$1(value.buildKey) && (value.buildNumber === void 0 || isTextOrNull$1(value.buildNumber)) && (value.isSandbox === void 0 || typeof value.isSandbox === "boolean") && (value.sandboxUrlScheme === void 0 || isTextOrNull$1(value.sandboxUrlScheme)) && (value.exportMethod === void 0 || isTextOrNull$1(value.exportMethod)) && (value.nativeAppVersion === void 0 || isTextOrNull$1(value.nativeAppVersion)) && isRecord$5(value.artifact) && typeof value.artifact.kind === "string" && NATIVE_BUILD_ARTIFACT_KINDS.has(value.artifact.kind) && isText$2(value.artifact.storageUri) && Number.isSafeInteger(value.artifact.byteSize) && value.artifact.byteSize >= 0 && isRecord$5(value.embeddedBundle) && isText$2(value.embeddedBundle.manifestStorageUri) && isText$2(value.embeddedBundle.manifestFileHash) && isText$2(value.embeddedBundle.assetBaseStorageUri) && (value.embeddedBundle.metadata === void 0 || isRecord$5(value.embeddedBundle.metadata));
10272
10707
  const scopeKeyOf = (params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "";
10273
10708
  const createAdminRouteHandlers = () => ({
10274
10709
  listBundles: onCore(async (core, request) => {
@@ -10345,7 +10780,8 @@ const createAdminRouteHandlers = () => ({
10345
10780
  rebuildReleaseCatalog: onCore(async (core, _request, params) => json$2({ data: await core.rebuildReleaseCatalog(scopeKeyOf(params)) })),
10346
10781
  updateBundle: onCore(async (core, request, params) => {
10347
10782
  const bundleId = requireRouteParam(params, "id");
10348
- await core.updateBundle(bundleId, bundleUpdateOf(await request.json(), bundleId));
10783
+ const update = bundleUpdateOf(await request.json(), bundleId);
10784
+ await refusingInvalid(() => core.updateBundle(bundleId, update));
10349
10785
  return noContent();
10350
10786
  }),
10351
10787
  countBundles: onCore(async (core, request) => json$2({ data: await core.countBundles(platformOf(new URL(request.url))) })),
@@ -10369,7 +10805,7 @@ const createAdminRouteHandlers = () => ({
10369
10805
  deployReleases: onCore(async (core, request) => {
10370
10806
  const { deployments } = await body$1(request);
10371
10807
  if (!Array.isArray(deployments) || deployments.length === 0 || !deployments.every(isDeployment)) throw new HandlerBadRequestError("Deploy needs deployments, each a bundle and its release policy.");
10372
- return json$2({ data: await core.deploy(deployments) }, 201);
10808
+ return json$2({ data: await refusingInvalid(() => core.deploy(deployments)) }, 201);
10373
10809
  }),
10374
10810
  promoteRelease: onCore(async (core, request, params) => {
10375
10811
  const input = await body$1(request);
@@ -10392,7 +10828,13 @@ const createAdminRouteHandlers = () => ({
10392
10828
  const url = new URL(request.url);
10393
10829
  const scope = nativeBuildScopeOf(url);
10394
10830
  const buildKey = url.searchParams.get("buildKey");
10395
- return json$2({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
10831
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
10832
+ const options = {
10833
+ ...buildKey === null ? {} : { buildKey },
10834
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
10835
+ ...builtInOlderThan === null ? {} : { builtInOlderThan }
10836
+ };
10837
+ return json$2({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
10396
10838
  }),
10397
10839
  getNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
10398
10840
  listNativeBuilds: onCore(async (core, request) => {
@@ -10406,14 +10848,95 @@ const createAdminRouteHandlers = () => ({
10406
10848
  }),
10407
10849
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
10408
10850
  const input = await body$1(request);
10409
- if (!isRecord$5(input) || input.destination !== "testflight" && input.destination !== "play-internal" || !isText$2(input.version)) throw new HandlerBadRequestError("A native build submission needs destination (testflight or play-internal) and version.");
10851
+ if (!isRecord$5(input) || !Object.values(NATIVE_BUILD_SUBMISSION_DESTINATIONS).flat().includes(input.destination) || !isText$2(input.version)) throw new HandlerBadRequestError("A native build submission needs a valid store destination and version.");
10410
10852
  const submission = {
10411
10853
  destination: input.destination,
10412
10854
  version: input.version
10413
10855
  };
10414
10856
  return json$2({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
10415
10857
  }),
10858
+ markNativeBuild: onCore(async (core, request, params) => {
10859
+ const input = await body$1(request);
10860
+ if (!isRecord$5(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
10861
+ const mark = { storeBuild: input.storeBuild };
10862
+ return json$2({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
10863
+ }),
10416
10864
  deleteNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
10865
+ listIosDevices: onCore(async (core, request) => {
10866
+ const url = new URL(request.url);
10867
+ const input = keyset(url);
10868
+ const status = url.searchParams.get("status");
10869
+ return page(await refusingInvalid(() => core.listIosDevices({
10870
+ ...input,
10871
+ ...status === null ? {} : { status }
10872
+ })), input, ({ id }) => id);
10873
+ }),
10874
+ findIosDevice: onCore(async (core, _request, params) => json$2({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
10875
+ requestIosDevice: onCore(async (core, request) => {
10876
+ const input = await body$1(request);
10877
+ if (!isText$2(input.udid) || !isText$2(input.name) || !isTextOrNull$1(input.requestedBy)) throw new HandlerBadRequestError("An iOS device request needs udid, name, and requestedBy, an email or null.");
10878
+ const device = {
10879
+ udid: input.udid,
10880
+ name: input.name,
10881
+ requestedBy: input.requestedBy
10882
+ };
10883
+ return json$2({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
10884
+ }),
10885
+ approveIosDevice: onCore(async (core, request, params) => {
10886
+ const input = await body$1(request);
10887
+ if (!isTextOrNull$1(input.approvedBy) || input.name !== void 0 && !isText$2(input.name)) throw new HandlerBadRequestError("An iOS device approval needs approvedBy, an email or null, and an optional name.");
10888
+ const approval = {
10889
+ approvedBy: input.approvedBy,
10890
+ ...input.name === void 0 ? {} : { name: input.name }
10891
+ };
10892
+ return json$2({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
10893
+ }),
10894
+ renameIosDevice: onCore(async (core, request, params) => {
10895
+ const input = await body$1(request);
10896
+ if (!isText$2(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
10897
+ const name = input.name;
10898
+ return json$2({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
10899
+ }),
10900
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
10901
+ const input = await body$1(request);
10902
+ const seen = input.seen;
10903
+ if (!isRecord$5(seen) || typeof seen.status !== "string" || !(seen.approvedAtMs === null || Number.isSafeInteger(seen.approvedAtMs)) || !isText$2(input.issuerId) || typeof input.outcome !== "string" || input.reason !== void 0 && typeof input.reason !== "string") throw new HandlerBadRequestError("An iOS device outcome needs seen { status, approvedAtMs }, issuerId, outcome, and an optional reason.");
10904
+ const outcome = {
10905
+ id: requireRouteParam(params, "id"),
10906
+ seen: {
10907
+ status: seen.status,
10908
+ approvedAtMs: seen.approvedAtMs
10909
+ },
10910
+ issuerId: input.issuerId,
10911
+ outcome: input.outcome,
10912
+ ...input.reason === void 0 ? {} : { reason: input.reason }
10913
+ };
10914
+ return json$2({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
10915
+ }),
10916
+ claimIosDeviceAccount: onCore(async (core, request) => {
10917
+ const { issuerId } = await body$1(request);
10918
+ if (!isText$2(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
10919
+ return json$2({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
10920
+ }),
10921
+ markIosDevicesInBuild: onCore(async (core, request) => {
10922
+ const { buildId, ids } = await body$1(request);
10923
+ if (!isText$2(buildId) || !Array.isArray(ids) || !ids.every((id) => isText$2(id))) throw new HandlerBadRequestError("Marking iOS devices in a build needs buildId and ids.");
10924
+ await core.markIosDevicesInBuild({
10925
+ buildId,
10926
+ ids
10927
+ });
10928
+ return noContent();
10929
+ }),
10930
+ deleteIosDevice: onCore(async (core, request, params) => {
10931
+ const url = new URL(request.url);
10932
+ const status = url.searchParams.get("status");
10933
+ const requestedBy = url.searchParams.get("requestedBy");
10934
+ const only = {
10935
+ ...status === null ? {} : { status },
10936
+ ...requestedBy === null ? {} : { requestedBy }
10937
+ };
10938
+ return json$2({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
10939
+ }),
10417
10940
  deleteBundles: onCore(async (core, request) => {
10418
10941
  const { ids } = await body$1(request);
10419
10942
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -10557,10 +11080,60 @@ const ADMIN_ROUTES = [
10557
11080
  path: "/native-builds/:id/submission",
10558
11081
  handler: "recordNativeBuildSubmission"
10559
11082
  },
11083
+ {
11084
+ method: "POST",
11085
+ path: "/native-builds/:id/store-build",
11086
+ handler: "markNativeBuild"
11087
+ },
10560
11088
  {
10561
11089
  method: "DELETE",
10562
11090
  path: "/native-builds/:id",
10563
11091
  handler: "deleteNativeBuild"
11092
+ },
11093
+ {
11094
+ method: "GET",
11095
+ path: "/ios-devices",
11096
+ handler: "listIosDevices"
11097
+ },
11098
+ {
11099
+ method: "POST",
11100
+ path: "/ios-devices",
11101
+ handler: "requestIosDevice"
11102
+ },
11103
+ {
11104
+ method: "GET",
11105
+ path: "/ios-devices/udid/:udid",
11106
+ handler: "findIosDevice"
11107
+ },
11108
+ {
11109
+ method: "POST",
11110
+ path: "/ios-devices/in-build",
11111
+ handler: "markIosDevicesInBuild"
11112
+ },
11113
+ {
11114
+ method: "POST",
11115
+ path: "/ios-devices/account",
11116
+ handler: "claimIosDeviceAccount"
11117
+ },
11118
+ {
11119
+ method: "POST",
11120
+ path: "/ios-devices/:id/approval",
11121
+ handler: "approveIosDevice"
11122
+ },
11123
+ {
11124
+ method: "POST",
11125
+ path: "/ios-devices/:id/outcome",
11126
+ handler: "recordIosDeviceOutcome"
11127
+ },
11128
+ {
11129
+ method: "PATCH",
11130
+ path: "/ios-devices/:id",
11131
+ handler: "renameIosDevice"
11132
+ },
11133
+ {
11134
+ method: "DELETE",
11135
+ path: "/ios-devices/:id",
11136
+ handler: "deleteIosDevice"
10564
11137
  }
10565
11138
  ];
10566
11139
  //#endregion
@@ -57415,12 +57988,19 @@ const PROTOCOL = "azblob";
57415
57988
  const SAS_EXPIRES_IN_MS = 36e5;
57416
57989
  const DELEGATION_KEY_LIFETIME_MS = 864e5;
57417
57990
  const isNotFound = (error) => error instanceof RestError && error.statusCode === 404;
57418
- const serviceOf = (config) => "connectionString" in config ? BlobServiceClient.fromConnectionString(config.connectionString) : new BlobServiceClient(config.accountUrl, config.credential);
57991
+ const serviceOf = async (config) => {
57992
+ if (!("connectionString" in config)) return new BlobServiceClient(config.accountUrl, config.credential);
57993
+ const { connectionString } = config;
57994
+ return BlobServiceClient.fromConnectionString(typeof connectionString === "function" ? await connectionString() : connectionString);
57995
+ };
57419
57996
  function azureBlobStorage(config) {
57420
57997
  const { containerName, basePath, getDownloadUrl } = config;
57421
57998
  let client;
57422
- const service = () => client ??= serviceOf(config);
57423
- const container = () => service().getContainerClient(containerName);
57999
+ const service = () => client ??= serviceOf(config).catch((error) => {
58000
+ client = void 0;
58001
+ throw error;
58002
+ });
58003
+ const container = async () => (await service()).getContainerClient(containerName);
57424
58004
  const normalizedBasePath = basePath?.replace(/^\/+|\/+$/g, "") ?? "";
57425
58005
  const getStorageKey = createStorageKeyBuilder(normalizedBasePath);
57426
58006
  const getListPrefix = (prefix = "") => {
@@ -57451,7 +58031,7 @@ function azureBlobStorage(config) {
57451
58031
  const delegationKey = () => {
57452
58032
  const now = Date.now();
57453
58033
  if (delegation === void 0 || delegation.renewAt <= now) {
57454
- const key = service().getUserDelegationKey(/* @__PURE__ */ new Date(now - 3e5), new Date(now + DELEGATION_KEY_LIFETIME_MS));
58034
+ const key = service().then((blobService) => blobService.getUserDelegationKey(/* @__PURE__ */ new Date(now - 3e5), new Date(now + DELEGATION_KEY_LIFETIME_MS)));
57455
58035
  key.catch(() => {
57456
58036
  delegation = void 0;
57457
58037
  });
@@ -57463,7 +58043,7 @@ function azureBlobStorage(config) {
57463
58043
  return delegation.key;
57464
58044
  };
57465
58045
  const signedUrl = async (key) => {
57466
- const blob = container().getBlobClient(key);
58046
+ const blob = (await container()).getBlobClient(key);
57467
58047
  const expiresOn = new Date(Date.now() + SAS_EXPIRES_IN_MS);
57468
58048
  const permissions = BlobSASPermissions.parse("r");
57469
58049
  if (blob.credential instanceof StorageSharedKeyCredential) return blob.generateSasUrl({
@@ -57484,7 +58064,8 @@ function azureBlobStorage(config) {
57484
58064
  protocol: PROTOCOL,
57485
58065
  async listObjects(prefix) {
57486
58066
  const objects = [];
57487
- for await (const blob of container().listBlobsFlat({ prefix: getListPrefix(prefix) })) {
58067
+ const blobs = await container();
58068
+ for await (const blob of blobs.listBlobsFlat({ prefix: getListPrefix(prefix) })) {
57488
58069
  const storageUri = getListedStorageUri(blob.name);
57489
58070
  if (storageUri === null) continue;
57490
58071
  objects.push({
@@ -57501,7 +58082,8 @@ function azureBlobStorage(config) {
57501
58082
  for (let offset = 0; offset < keys.length; offset += 256) {
57502
58083
  const batch = keys.slice(offset, offset + 256);
57503
58084
  if (batch.length === 0) continue;
57504
- const failed = (await container().getBlobBatchClient().deleteBlobs(batch.map((key) => container().getBlobClient(key)))).subResponses.filter(({ status }) => status >= 300 && status !== 404);
58085
+ const blobs = await container();
58086
+ const failed = (await blobs.getBlobBatchClient().deleteBlobs(batch.map((key) => blobs.getBlobClient(key)))).subResponses.filter(({ status }) => status >= 300 && status !== 404);
57505
58087
  if (failed.length > 0) throw new Error(`Failed to delete ${failed.length} Azure blob(s).`);
57506
58088
  }
57507
58089
  },
@@ -57511,7 +58093,7 @@ function azureBlobStorage(config) {
57511
58093
  blobContentType: contentType,
57512
58094
  blobCacheControl: "max-age=31536000"
57513
58095
  } };
57514
- const blob = container().getBlockBlobClient(storageKey);
58096
+ const blob = (await container()).getBlockBlobClient(storageKey);
57515
58097
  if (contentLength === void 0) await blob.uploadData(new Uint8Array(await new Response(body).arrayBuffer()), options);
57516
58098
  else {
57517
58099
  const { Readable } = await import("node:stream");
@@ -57540,13 +58122,12 @@ function azureBlobStorage(config) {
57540
58122
  async get({ storageUri }) {
57541
58123
  const { key } = parseAndValidate(storageUri);
57542
58124
  try {
57543
- const download = await container().getBlobClient(key).download();
58125
+ const download = await (await container()).getBlobClient(key).download();
57544
58126
  const body = download.readableStreamBody;
57545
58127
  if (body === void 0) return { response: null };
57546
58128
  const headers = new Headers();
57547
58129
  if (download.contentType) headers.set("content-type", download.contentType);
57548
58130
  if (download.contentLength !== void 0) headers.set("content-length", String(download.contentLength));
57549
- const { Readable } = await import("node:stream");
57550
58131
  return { response: new Response(Readable.toWeb(body), { headers }) };
57551
58132
  } catch (error) {
57552
58133
  if (isNotFound(error)) return { response: null };
@@ -57560,11 +58141,11 @@ function azureBlobStorage(config) {
57560
58141
  },
57561
58142
  async exists({ storageUri }) {
57562
58143
  const { key } = parseAndValidate(storageUri);
57563
- return { exists: await container().getBlobClient(key).exists() };
58144
+ return { exists: await (await container()).getBlobClient(key).exists() };
57564
58145
  },
57565
58146
  async delete({ storageUri }) {
57566
58147
  const { key } = parseAndValidate(storageUri);
57567
- await container().getBlobClient(key).deleteIfExists();
58148
+ await (await container()).getBlobClient(key).deleteIfExists();
57568
58149
  return { deleted: true };
57569
58150
  }
57570
58151
  });
@@ -70857,18 +71438,21 @@ const isWideAdd = (op) => op.type === "add" && Object.keys(op.by).length + (op.e
70857
71438
  const emulatorAborted = (error) => statusOf(error) === 500 && /PostgresError\(SqlState\(E(25P02|40001|40P01)\)/.test(String(error instanceof Error ? error.message : error));
70858
71439
  const createCosmosStore = ({ client, databaseId, containerId, engine, nativePageSize }) => {
70859
71440
  let opened;
70860
- const open = () => opened ??= (() => {
70861
- const account = typeof client === "function" ? client() : client;
71441
+ const open = () => opened ??= (async () => {
71442
+ const account = typeof client === "function" ? await client() : client;
70862
71443
  return {
70863
71444
  client: account,
70864
71445
  container: account.database(databaseId).container(containerId)
70865
71446
  };
70866
- })();
70867
- const container = () => open().container;
71447
+ })().catch((error) => {
71448
+ opened = void 0;
71449
+ throw error;
71450
+ });
71451
+ const container = async () => (await open()).container;
70868
71452
  const readStates = async (ids, rowIds) => {
70869
71453
  const states = /* @__PURE__ */ new Map();
70870
71454
  for (const [group, projection] of [[ids.filter((id) => !rowIds.has(id)), ""], [ids.filter((id) => rowIds.has(id)), ", c.row"]]) for (let at = 0; at < group.length; at += GET_BATCH) {
70871
- const { resources } = await container().items.query(`SELECT c.id, c._etag AS etag, c.row._v AS v, c.expireAt${projection} FROM c WHERE c.id IN (${idList(group.slice(at, at + GET_BATCH))})`, { partitionKey: COSMOS_PARTITION }).fetchAll().catch(missingContainer);
71455
+ const { resources } = await (await container()).items.query(`SELECT c.id, c._etag AS etag, c.row._v AS v, c.expireAt${projection} FROM c WHERE c.id IN (${idList(group.slice(at, at + GET_BATCH))})`, { partitionKey: COSMOS_PARTITION }).fetchAll().catch(missingContainer);
70872
71456
  for (const { id, etag, v, expireAt, row } of resources) states.set(id, {
70873
71457
  etag,
70874
71458
  v,
@@ -71000,7 +71584,7 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
71000
71584
  const found = /* @__PURE__ */ new Map();
71001
71585
  const ids = [...new Set(keys.map(cosmosItemId))];
71002
71586
  for (let at = 0; at < ids.length; at += GET_BATCH) {
71003
- const { resources } = await container().items.query(`SELECT c.id, c.row FROM c WHERE c.id IN (${idList(ids.slice(at, at + GET_BATCH))})`, { partitionKey: COSMOS_PARTITION }).fetchAll().catch(missingContainer);
71587
+ const { resources } = await (await container()).items.query(`SELECT c.id, c.row FROM c WHERE c.id IN (${idList(ids.slice(at, at + GET_BATCH))})`, { partitionKey: COSMOS_PARTITION }).fetchAll().catch(missingContainer);
71004
71588
  for (const resource of resources) found.set(resource.id, toRow(resource.row));
71005
71589
  }
71006
71590
  return keys.map((key) => found.get(cosmosItemId(key)) ?? null);
@@ -71036,7 +71620,7 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
71036
71620
  value: after
71037
71621
  });
71038
71622
  }
71039
- const { resources } = await container().items.query({
71623
+ const { resources } = await (await container()).items.query({
71040
71624
  query: `SELECT TOP @size c.sk, c.row FROM c WHERE ${filters.join(" AND ")} ORDER BY c.pk ${order === "asc" ? "ASC" : "DESC"}, c.sk ${order === "asc" ? "ASC" : "DESC"}`,
71041
71625
  parameters
71042
71626
  }, {
@@ -71086,7 +71670,7 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
71086
71670
  if (planned.length > BATCH_OPERATIONS) throw new Error(`A Cosmos DB batch takes ${BATCH_OPERATIONS} operations; this write needs ${planned.length}.`);
71087
71671
  let results;
71088
71672
  try {
71089
- const response = await container().items.batch(planned.map(({ operation }) => operation), COSMOS_PARTITION);
71673
+ const response = await (await container()).items.batch(planned.map(({ operation }) => operation), COSMOS_PARTITION);
71090
71674
  if (response.result === void 0) throw Object.assign(/* @__PURE__ */ new Error(`Cosmos DB refused the batch with status ${response.code}`), { code: response.code });
71091
71675
  results = response.result;
71092
71676
  } catch (error) {
@@ -71119,7 +71703,7 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
71119
71703
  async deleteConsumed(keys) {
71120
71704
  let remaining = [...new Set(keys.map(cosmosItemId))];
71121
71705
  for (let attempt = 0; remaining.length > 0; attempt += 1) {
71122
- const failed = (await container().items.executeBulkOperations(remaining.map((id) => ({
71706
+ const failed = (await (await container()).items.executeBulkOperations(remaining.map((id) => ({
71123
71707
  operationType: "Delete",
71124
71708
  id,
71125
71709
  partitionKey: COSMOS_PARTITION
@@ -71138,8 +71722,8 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
71138
71722
  }
71139
71723
  },
71140
71724
  migrations: { async apply() {
71141
- if (engine !== void 0) await assertCosmosContainerReusable(container(), engine);
71142
- const { database } = await open().client.databases.createIfNotExists({ id: databaseId });
71725
+ if (engine !== void 0) await assertCosmosContainerReusable(await container(), engine);
71726
+ const { database } = await (await open()).client.databases.createIfNotExists({ id: databaseId });
71143
71727
  const { resource } = await database.containers.createIfNotExists({
71144
71728
  id: containerId,
71145
71729
  partitionKey: { paths: [COSMOS_PARTITION_KEY_PATH] },
@@ -71176,8 +71760,12 @@ const adapterOf = (config) => {
71176
71760
  const { databaseId = AZURE_COSMOS_V1_DATABASE, containerId = AZURE_COSMOS_V1_CONTAINER, aggregateBatching: _, ...connection } = config;
71177
71761
  if (connection.consistencyLevel !== void 0 && connection.consistencyLevel !== "Strong") throw new Error(`cosmosDatabase reads with strong consistency; consistencyLevel "${String(connection.consistencyLevel)}" is weaker.`);
71178
71762
  let client;
71763
+ const { connectionString } = connection;
71179
71764
  const store = createCosmosStore({
71180
- client: () => client ??= new CosmosClient(connection),
71765
+ client: async () => client ??= new CosmosClient({
71766
+ ...connection,
71767
+ connectionString: typeof connectionString === "function" ? await connectionString() : connectionString
71768
+ }),
71181
71769
  databaseId,
71182
71770
  containerId,
71183
71771
  engine: currentCosmosEngine()
@@ -71189,7 +71777,7 @@ const adapterOf = (config) => {
71189
71777
  };
71190
71778
  const DATABASE_TARGET = Symbol.for("@hot-updater/database-target");
71191
71779
  const accountHostOf = ({ endpoint, connectionString }) => {
71192
- const url = endpoint ?? connectionString?.match(/AccountEndpoint=([^;]+)/iu)?.[1];
71780
+ const url = endpoint ?? (typeof connectionString === "string" ? connectionString.match(/AccountEndpoint=([^;]+)/iu)?.[1] : void 0);
71193
71781
  try {
71194
71782
  return url === void 0 ? void 0 : new URL(url).hostname;
71195
71783
  } catch {