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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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.41";
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,298 @@ 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 findIosDeviceAccount() {
9393
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
9394
+ const issuerId = existing === null ? await accountOfRows() : existing.apple_issuer_id;
9395
+ return issuerId === null ? null : { issuerId };
9396
+ },
9397
+ async claimIosDeviceAccount(issuerId) {
9398
+ 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.`);
9399
+ const answer = (held) => ({
9400
+ issuerId: held,
9401
+ claimed: held === issuerId
9402
+ });
9403
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
9404
+ if (existing !== null) return answer(existing.apple_issuer_id);
9405
+ const holder = await accountOfRows() ?? issuerId;
9406
+ try {
9407
+ await db.transaction(async (tx) => {
9408
+ tx.create("ios_device_account", {
9409
+ id: ACCOUNT_ROW,
9410
+ apple_issuer_id: holder,
9411
+ claimed_at_ms: now()
9412
+ });
9413
+ });
9414
+ return answer(holder);
9415
+ } catch (error) {
9416
+ if (error instanceof DatabaseConstraintError && (error.reason === "exists" || error.reason === "unique")) {
9417
+ const winner = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
9418
+ if (winner !== null) return answer(winner.apple_issuer_id);
9419
+ }
9420
+ throw error;
9421
+ }
9422
+ },
9423
+ async deleteIosDevice(id, only) {
9424
+ const requestedBy = only?.requestedBy === void 0 ? void 0 : personOf(only.requestedBy, "requestedBy");
9425
+ return db.transaction(async (tx) => {
9426
+ const row = await tx.findOne("ios_devices", { id });
9427
+ if (row === null) return null;
9428
+ const device = pick$1(row);
9429
+ if (only?.status !== void 0 && device.status !== only.status || requestedBy !== void 0 && device.requested_by !== requestedBy) return null;
9430
+ await tx.delete("ios_devices", row);
9431
+ return device;
9432
+ });
9433
+ }
9434
+ };
9435
+ };
9436
+ //#endregion
9437
+ //#region ../../packages/server/dist/core/nativeBuildDestinations.mjs
9438
+ const NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
9439
+ android: [
9440
+ "play-internal",
9441
+ "play-closed",
9442
+ "play-open",
9443
+ "play-production"
9444
+ ],
9445
+ ios: ["testflight"]
9446
+ };
9447
+ //#endregion
9112
9448
  //#region ../../packages/server/dist/core/writes.mjs
9113
9449
  const PAGE$2 = 500;
9114
9450
  const countBundle = (tx, platform, delta) => {
@@ -9129,7 +9465,7 @@ const deleteBundle = async (tx, current) => {
9129
9465
  await tx.delete("bundles", current);
9130
9466
  countBundle(tx, current.platform, -1);
9131
9467
  };
9132
- const replaceBundlePatches = async (tx, bundle, rows) => {
9468
+ const replaceBundlePatches = async (tx, bundle, rows, checkNew) => {
9133
9469
  const wanted = new Map(rows.map((row) => [row.id, row]));
9134
9470
  const count = bundle._refs_bundle_patches_bundle_id ?? 0;
9135
9471
  let cursor;
@@ -9154,6 +9490,7 @@ const replaceBundlePatches = async (tx, bundle, rows) => {
9154
9490
  if (page.next === void 0) break;
9155
9491
  cursor = page.next;
9156
9492
  }
9493
+ if (checkNew !== void 0) for (const row of wanted.values()) await checkNew(row);
9157
9494
  for (const row of wanted.values()) tx.create("bundle_patches", row);
9158
9495
  };
9159
9496
  const insertChannel = async (db, row) => {
@@ -9206,6 +9543,16 @@ const ARTIFACT_KINDS = {
9206
9543
  const SCOPE_KEY_MAX_LENGTH = 2048;
9207
9544
  const GIT_COMMIT_HASH_MAX_LENGTH = 255;
9208
9545
  const BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
9546
+ const SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
9547
+ const URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
9548
+ const APP_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;
9549
+ const FINGERPRINT_HASH = /^[A-Za-z0-9._~-]{1,255}$/;
9550
+ const DISTRIBUTIONS = {
9551
+ apk: ["direct"],
9552
+ app: ["direct"],
9553
+ aab: ["store"],
9554
+ ipa: ["direct", "store"]
9555
+ };
9209
9556
  var NativeBuildInputError = class extends TypeError {
9210
9557
  name = "NativeBuildInputError";
9211
9558
  };
@@ -9226,15 +9573,41 @@ const pick = (row) => ({
9226
9573
  build_number: row.build_number ?? null,
9227
9574
  submitted_to: row.submitted_to ?? null,
9228
9575
  submitted_at_ms: row.submitted_at_ms ?? null,
9229
- submitted_version: row.submitted_version ?? null
9576
+ submitted_version: row.submitted_version ?? null,
9577
+ is_store_build: row.is_store_build === true,
9578
+ is_sandbox: row.is_sandbox === true,
9579
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
9580
+ export_method: row.export_method ?? null,
9581
+ native_app_version: row.native_app_version ?? null
9230
9582
  });
9231
- const SUBMISSION_DESTINATIONS = {
9232
- android: "play-internal",
9233
- ios: "testflight"
9234
- };
9583
+ const EXPORT_METHODS = /* @__PURE__ */ new Set([
9584
+ "app-store",
9585
+ "ad-hoc",
9586
+ "development",
9587
+ "enterprise"
9588
+ ]);
9589
+ const OLDER_BUILDS_PAGE = 20;
9590
+ const MARK_ATTEMPTS = 8;
9235
9591
  const BUILD_NUMBER_MAX_LENGTH = 64;
9236
9592
  const SUBMITTED_VERSION_MAX_LENGTH = 255;
9593
+ const checkedScopeKey = (scopeKey) => {
9594
+ 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.`);
9595
+ return scopeKey;
9596
+ };
9597
+ const registeredDistribution = (kind, exportMethod) => kind !== "ipa" ? DISTRIBUTIONS[kind][0] : exportMethod === void 0 || exportMethod === null ? "unknown" : exportMethod === "app-store" ? "store" : "direct";
9598
+ const sandboxScopeKey = (scope, sandbox) => {
9599
+ const { appId, urlScheme, artifactKind, distribution } = sandbox;
9600
+ const problem = typeof appId !== "string" || !APP_ID.test(appId) ? "its app ID must be a bundle identifier or application ID, up to 255 characters" : typeof urlScheme !== "string" || !URL_SCHEME.test(urlScheme) ? `its URL scheme must be a URL scheme in lower case, up to ${SANDBOX_URL_SCHEME_MAX_LENGTH} characters` : !ARTIFACT_KINDS[scope.platform]?.includes(artifactKind) ? `its artifact kind must be one an ${scope.platform} build makes` : distribution !== "unknown" && !DISTRIBUTIONS[artifactKind].includes(distribution) ? `an .${artifactKind} doesn't install as ${String(distribution)}` : scope.fingerprintHash !== null && !FINGERPRINT_HASH.test(scope.fingerprintHash) ? "its fingerprint hash must be 1-255 URL-safe ASCII characters" : null;
9601
+ if (problem !== null) throw new NativeBuildInputError(`Invalid sandbox build scope: ${problem}.`);
9602
+ const target = scope.fingerprintHash === null ? `app-version:${encodeURIComponent(scope.appVersion)}` : `fingerprint:${scope.fingerprintHash}`;
9603
+ return checkedScopeKey(`v1:sandbox:${scope.platform}:${appId}:${urlScheme}:${artifactKind}:${distribution}:${target}`);
9604
+ };
9237
9605
  const nativeBuildScopeKey = (scope) => {
9606
+ const { sandbox } = scope;
9607
+ if (sandbox !== void 0 && sandbox !== null) {
9608
+ if (sandbox.distribution !== "direct" && sandbox.distribution !== "store") throw new NativeBuildInputError("Invalid sandbox build scope: its distribution must be direct or store.");
9609
+ return sandboxScopeKey(scope, sandbox);
9610
+ }
9238
9611
  let scopeKey;
9239
9612
  try {
9240
9613
  const channelKey = encodeChannelKey(scope.channel);
@@ -9251,21 +9624,60 @@ const nativeBuildScopeKey = (scope) => {
9251
9624
  } catch (error) {
9252
9625
  throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
9253
9626
  }
9254
- 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
- return scopeKey;
9627
+ return checkedScopeKey(scopeKey);
9628
+ };
9629
+ const channelIdOf = (channel) => {
9630
+ try {
9631
+ return `channel:${encodeChannelKey(channel)}`;
9632
+ } catch (error) {
9633
+ throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
9634
+ }
9635
+ };
9636
+ const registrationScopeKey = (registration) => {
9637
+ channelIdOf(registration.channel);
9638
+ return registration.isSandbox === true ? sandboxScopeKey(registration, {
9639
+ appId: registration.sandboxAppId,
9640
+ urlScheme: registration.sandboxUrlScheme,
9641
+ artifactKind: registration.artifact.kind,
9642
+ distribution: registeredDistribution(registration.artifact.kind, registration.exportMethod)
9643
+ }) : nativeBuildScopeKey({
9644
+ ...registration,
9645
+ sandbox: null
9646
+ });
9647
+ };
9648
+ const refuseSandboxPatchBase = async (db, baseBundleId) => {
9649
+ 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.");
9256
9650
  };
9257
9651
  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 }) => {
9652
+ const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, sandboxAppId, exportMethod, nativeAppVersion, artifact }) => {
9259
9653
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
9260
9654
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
9261
9655
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
9262
9656
  if (channel.trim().length === 0) return "channel is required";
9657
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
9658
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
9659
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
9660
+ 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`;
9661
+ }
9662
+ if (sandboxAppId !== void 0 && sandboxAppId !== null) {
9663
+ if (isSandbox !== true) return "sandboxAppId is a sandbox build's, and this isn't one";
9664
+ if (typeof sandboxAppId !== "string" || !APP_ID.test(sandboxAppId)) return "sandboxAppId must be the artifact's bundle identifier or application ID, up to 255 characters";
9665
+ }
9666
+ if (isSandbox === true) {
9667
+ if (sandboxUrlScheme === void 0 || sandboxUrlScheme === null) return "a sandbox build needs the sandboxUrlScheme its artifact registers";
9668
+ if (sandboxAppId === void 0 || sandboxAppId === null) return "a sandbox build needs the sandboxAppId its artifact reports, which an older hot-updater CLI doesn't send. Upgrade the hot-updater CLI to the version that matches this server, and build again";
9669
+ }
9263
9670
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
9264
9671
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
9265
9672
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
9266
9673
  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`;
9674
+ 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
9675
  const kinds = ARTIFACT_KINDS[platform];
9268
9676
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
9677
+ if (exportMethod !== void 0 && exportMethod !== null) {
9678
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
9679
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
9680
+ }
9269
9681
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
9270
9682
  return null;
9271
9683
  };
@@ -9273,8 +9685,8 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9273
9685
  async registerNativeBuild(registration) {
9274
9686
  const problem = problemOf(registration);
9275
9687
  if (problem !== null) throw new NativeBuildInputError(`Invalid native build: ${problem}.`);
9276
- const scopeKey = nativeBuildScopeKey(registration);
9277
- const channelId = `channel:${encodeChannelKey(registration.channel)}`;
9688
+ const scopeKey = registrationScopeKey(registration);
9689
+ const channelId = channelIdOf(registration.channel);
9278
9690
  const { embeddedBundle } = registration;
9279
9691
  const row = {
9280
9692
  id: registration.id,
@@ -9293,7 +9705,12 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9293
9705
  build_number: registration.buildNumber ?? null,
9294
9706
  submitted_to: null,
9295
9707
  submitted_at_ms: null,
9296
- submitted_version: null
9708
+ submitted_version: null,
9709
+ is_store_build: false,
9710
+ is_sandbox: registration.isSandbox === true,
9711
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
9712
+ export_method: registration.exportMethod ?? null,
9713
+ native_app_version: registration.nativeAppVersion ?? null
9297
9714
  };
9298
9715
  for (let attempt = 1;; attempt += 1) {
9299
9716
  await insertChannel(db, {
@@ -9331,21 +9748,43 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9331
9748
  const scopeKey = nativeBuildScopeKey(scope);
9332
9749
  const buildKey = options?.buildKey;
9333
9750
  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]);
9751
+ if (options?.storeBuild) {
9752
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
9753
+ return marked === null ? null : pick(marked);
9754
+ }
9755
+ const read = (limit, before) => {
9756
+ const page = {
9757
+ order: "desc",
9758
+ limit,
9759
+ ...before === void 0 ? {} : { range: { lt: before } }
9760
+ };
9761
+ return buildKey === void 0 ? db.findMany("native_builds", {
9762
+ index: "byScope",
9763
+ where: { scope_key: scopeKey },
9764
+ ...page
9765
+ }) : db.findMany("native_builds", {
9766
+ index: "byBuildKey",
9767
+ where: {
9768
+ scope_key: scopeKey,
9769
+ build_key: buildKey
9770
+ },
9771
+ ...page
9772
+ });
9773
+ };
9774
+ const bundleId = options?.builtInOlderThan;
9775
+ if (bundleId !== void 0 && scope.sandbox !== void 0 && scope.sandbox !== null) return null;
9776
+ const { rows } = await read(1);
9777
+ const newest = rows[0];
9778
+ if (newest === void 0) return null;
9779
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return pick(newest);
9780
+ for (let before = newest.id;;) {
9781
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
9782
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
9783
+ if (usable !== void 0) return pick(usable);
9784
+ const last = older.at(-1);
9785
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
9786
+ before = last.id;
9787
+ }
9349
9788
  },
9350
9789
  async recordNativeBuildSubmission(id, { destination, version }) {
9351
9790
  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 +9792,8 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9353
9792
  const row = await tx.findOne("native_builds", { id });
9354
9793
  if (row === null) return null;
9355
9794
  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}.`);
9795
+ 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}.`);
9796
+ 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
9797
  const set = {
9358
9798
  submitted_to: destination,
9359
9799
  submitted_at_ms: now(),
@@ -9366,6 +9806,46 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9366
9806
  };
9367
9807
  });
9368
9808
  },
9809
+ async markNativeBuild(id, { storeBuild }) {
9810
+ for (let attempt = 1;; attempt += 1) try {
9811
+ return await db.transaction(async (tx) => {
9812
+ const row = await tx.findOne("native_builds", { id });
9813
+ if (row === null) return null;
9814
+ const build = pick(row);
9815
+ if (!storeBuild) {
9816
+ if (build.is_store_build) tx.update("native_builds", row, { is_store_build: false });
9817
+ return {
9818
+ nativeBuild: {
9819
+ ...build,
9820
+ is_store_build: false
9821
+ },
9822
+ previous: null
9823
+ };
9824
+ }
9825
+ if (build.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
9826
+ if (build.is_store_build) return {
9827
+ nativeBuild: build,
9828
+ previous: null
9829
+ };
9830
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build.scope_key });
9831
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
9832
+ tx.update("native_builds", row, { is_store_build: true });
9833
+ return {
9834
+ nativeBuild: {
9835
+ ...build,
9836
+ is_store_build: true
9837
+ },
9838
+ previous: holder === null ? null : {
9839
+ ...pick(holder),
9840
+ is_store_build: false
9841
+ }
9842
+ };
9843
+ });
9844
+ } catch (error) {
9845
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
9846
+ throw error;
9847
+ }
9848
+ },
9369
9849
  async deleteNativeBuild(id) {
9370
9850
  return db.transaction(async (tx) => {
9371
9851
  const row = await tx.findOne("native_builds", { id });
@@ -9685,7 +10165,11 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
9685
10165
  for (const { release } of deployments) if (!channels.has(release.channel)) channels.set(release.channel, await ensureChannel(release.channel));
9686
10166
  const platforms = /* @__PURE__ */ new Map();
9687
10167
  for (const deployment of deployments) {
9688
- if (!("bundleId" in deployment) || platforms.has(deployment.bundleId)) continue;
10168
+ if (!("bundleId" in deployment)) {
10169
+ for (const { baseBundleId } of deployment.bundle.patches ?? []) await refuseSandboxPatchBase(db, baseBundleId);
10170
+ continue;
10171
+ }
10172
+ if (platforms.has(deployment.bundleId)) continue;
9689
10173
  const row = await db.findOne("bundles", { id: deployment.bundleId });
9690
10174
  if (row === null) throw new DatabaseBundleNotFoundError(deployment.bundleId);
9691
10175
  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 +10373,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
9889
10373
  if (patches !== void 0) await replaceBundlePatches(tx, current, bundleToPatchRows({
9890
10374
  ...next,
9891
10375
  patches
9892
- }));
10376
+ }), (row) => refuseSandboxPatchBase(tx, row.base_bundle_id));
9893
10377
  }),
9894
10378
  deleteBundles: async (ids) => {
9895
10379
  try {
@@ -9945,6 +10429,7 @@ const createCoreApi = (db, storage, options = {}) => {
9945
10429
  ...reads,
9946
10430
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
9947
10431
  ...createNativeBuildApi(db, options),
10432
+ ...createIosDeviceApi(db, options),
9948
10433
  ready: async () => {
9949
10434
  await reads.listReleaseCatalogs({ limit: 1 });
9950
10435
  }
@@ -10154,10 +10639,12 @@ const keyset = (url, maxValue = LIMITS.maxValue) => {
10154
10639
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
10155
10640
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
10156
10641
  const cursor = url.searchParams.get("cursor");
10642
+ const through = url.searchParams.get("through");
10157
10643
  return {
10158
10644
  order,
10159
10645
  limit,
10160
- ...cursor === null ? {} : { after: cursor }
10646
+ ...cursor === null ? {} : { after: cursor },
10647
+ ...through === null ? {} : { through }
10161
10648
  };
10162
10649
  };
10163
10650
  const page = (rows, { limit }, keyOf, extra = {}) => json$2({
@@ -10248,7 +10735,8 @@ const nativeBuildScopeOf = (url) => {
10248
10735
  const fingerprintHash = params.get("fingerprintHash");
10249
10736
  const appVersion = params.get("appVersion");
10250
10737
  if (platform === void 0 || !isText$2(channel) || fingerprintHash === null === (appVersion === null) || fingerprintHash === "" || appVersion === "") throw new HandlerBadRequestError("A native build lookup needs platform, channel, and fingerprintHash or appVersion.");
10251
- return fingerprintHash !== null ? {
10738
+ const sandbox = sandboxScopeOf(params);
10739
+ const scope = fingerprintHash !== null ? {
10252
10740
  platform,
10253
10741
  channel,
10254
10742
  fingerprintHash,
@@ -10259,16 +10747,43 @@ const nativeBuildScopeOf = (url) => {
10259
10747
  fingerprintHash: null,
10260
10748
  appVersion
10261
10749
  };
10750
+ return sandbox === null ? scope : {
10751
+ ...scope,
10752
+ sandbox
10753
+ };
10754
+ };
10755
+ const SANDBOX_SCOPE_PARAMS = [
10756
+ "sandboxAppId",
10757
+ "sandboxUrlScheme",
10758
+ "artifactKind",
10759
+ "distribution"
10760
+ ];
10761
+ const sandboxScopeOf = (params) => {
10762
+ const [appId, urlScheme, artifactKind, distribution] = SANDBOX_SCOPE_PARAMS.map((name) => params.get(name));
10763
+ const named = [
10764
+ appId,
10765
+ urlScheme,
10766
+ artifactKind,
10767
+ distribution
10768
+ ].filter((value) => value !== null).length;
10769
+ if (named === 0) return null;
10770
+ if (named !== SANDBOX_SCOPE_PARAMS.length) throw new HandlerBadRequestError(`A sandbox build lookup needs ${SANDBOX_SCOPE_PARAMS.join(", ")}.`);
10771
+ return {
10772
+ appId,
10773
+ urlScheme,
10774
+ artifactKind,
10775
+ distribution
10776
+ };
10262
10777
  };
10263
10778
  const refusingInvalid = async (operation) => {
10264
10779
  try {
10265
10780
  return await operation();
10266
10781
  } catch (error) {
10267
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
10782
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
10268
10783
  throw error;
10269
10784
  }
10270
10785
  };
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));
10786
+ 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.sandboxAppId === void 0 || isTextOrNull$1(value.sandboxAppId)) && (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
10787
  const scopeKeyOf = (params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "";
10273
10788
  const createAdminRouteHandlers = () => ({
10274
10789
  listBundles: onCore(async (core, request) => {
@@ -10345,7 +10860,8 @@ const createAdminRouteHandlers = () => ({
10345
10860
  rebuildReleaseCatalog: onCore(async (core, _request, params) => json$2({ data: await core.rebuildReleaseCatalog(scopeKeyOf(params)) })),
10346
10861
  updateBundle: onCore(async (core, request, params) => {
10347
10862
  const bundleId = requireRouteParam(params, "id");
10348
- await core.updateBundle(bundleId, bundleUpdateOf(await request.json(), bundleId));
10863
+ const update = bundleUpdateOf(await request.json(), bundleId);
10864
+ await refusingInvalid(() => core.updateBundle(bundleId, update));
10349
10865
  return noContent();
10350
10866
  }),
10351
10867
  countBundles: onCore(async (core, request) => json$2({ data: await core.countBundles(platformOf(new URL(request.url))) })),
@@ -10369,7 +10885,7 @@ const createAdminRouteHandlers = () => ({
10369
10885
  deployReleases: onCore(async (core, request) => {
10370
10886
  const { deployments } = await body$1(request);
10371
10887
  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);
10888
+ return json$2({ data: await refusingInvalid(() => core.deploy(deployments)) }, 201);
10373
10889
  }),
10374
10890
  promoteRelease: onCore(async (core, request, params) => {
10375
10891
  const input = await body$1(request);
@@ -10392,7 +10908,13 @@ const createAdminRouteHandlers = () => ({
10392
10908
  const url = new URL(request.url);
10393
10909
  const scope = nativeBuildScopeOf(url);
10394
10910
  const buildKey = url.searchParams.get("buildKey");
10395
- return json$2({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
10911
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
10912
+ const options = {
10913
+ ...buildKey === null ? {} : { buildKey },
10914
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
10915
+ ...builtInOlderThan === null ? {} : { builtInOlderThan }
10916
+ };
10917
+ return json$2({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
10396
10918
  }),
10397
10919
  getNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
10398
10920
  listNativeBuilds: onCore(async (core, request) => {
@@ -10406,14 +10928,96 @@ const createAdminRouteHandlers = () => ({
10406
10928
  }),
10407
10929
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
10408
10930
  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.");
10931
+ 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
10932
  const submission = {
10411
10933
  destination: input.destination,
10412
10934
  version: input.version
10413
10935
  };
10414
10936
  return json$2({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
10415
10937
  }),
10938
+ markNativeBuild: onCore(async (core, request, params) => {
10939
+ const input = await body$1(request);
10940
+ if (!isRecord$5(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
10941
+ const mark = { storeBuild: input.storeBuild };
10942
+ return json$2({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
10943
+ }),
10416
10944
  deleteNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
10945
+ listIosDevices: onCore(async (core, request) => {
10946
+ const url = new URL(request.url);
10947
+ const input = keyset(url);
10948
+ const status = url.searchParams.get("status");
10949
+ return page(await refusingInvalid(() => core.listIosDevices({
10950
+ ...input,
10951
+ ...status === null ? {} : { status }
10952
+ })), input, ({ id }) => id);
10953
+ }),
10954
+ findIosDevice: onCore(async (core, _request, params) => json$2({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
10955
+ requestIosDevice: onCore(async (core, request) => {
10956
+ const input = await body$1(request);
10957
+ 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.");
10958
+ const device = {
10959
+ udid: input.udid,
10960
+ name: input.name,
10961
+ requestedBy: input.requestedBy
10962
+ };
10963
+ return json$2({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
10964
+ }),
10965
+ approveIosDevice: onCore(async (core, request, params) => {
10966
+ const input = await body$1(request);
10967
+ 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.");
10968
+ const approval = {
10969
+ approvedBy: input.approvedBy,
10970
+ ...input.name === void 0 ? {} : { name: input.name }
10971
+ };
10972
+ return json$2({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
10973
+ }),
10974
+ renameIosDevice: onCore(async (core, request, params) => {
10975
+ const input = await body$1(request);
10976
+ if (!isText$2(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
10977
+ const name = input.name;
10978
+ return json$2({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
10979
+ }),
10980
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
10981
+ const input = await body$1(request);
10982
+ const seen = input.seen;
10983
+ 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.");
10984
+ const outcome = {
10985
+ id: requireRouteParam(params, "id"),
10986
+ seen: {
10987
+ status: seen.status,
10988
+ approvedAtMs: seen.approvedAtMs
10989
+ },
10990
+ issuerId: input.issuerId,
10991
+ outcome: input.outcome,
10992
+ ...input.reason === void 0 ? {} : { reason: input.reason }
10993
+ };
10994
+ return json$2({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
10995
+ }),
10996
+ claimIosDeviceAccount: onCore(async (core, request) => {
10997
+ const { issuerId } = await body$1(request);
10998
+ if (!isText$2(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
10999
+ return json$2({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
11000
+ }),
11001
+ findIosDeviceAccount: onCore(async (core) => json$2({ data: await core.findIosDeviceAccount() })),
11002
+ markIosDevicesInBuild: onCore(async (core, request) => {
11003
+ const { buildId, ids } = await body$1(request);
11004
+ 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.");
11005
+ await core.markIosDevicesInBuild({
11006
+ buildId,
11007
+ ids
11008
+ });
11009
+ return noContent();
11010
+ }),
11011
+ deleteIosDevice: onCore(async (core, request, params) => {
11012
+ const url = new URL(request.url);
11013
+ const status = url.searchParams.get("status");
11014
+ const requestedBy = url.searchParams.get("requestedBy");
11015
+ const only = {
11016
+ ...status === null ? {} : { status },
11017
+ ...requestedBy === null ? {} : { requestedBy }
11018
+ };
11019
+ return json$2({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
11020
+ }),
10417
11021
  deleteBundles: onCore(async (core, request) => {
10418
11022
  const { ids } = await body$1(request);
10419
11023
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -10557,10 +11161,65 @@ const ADMIN_ROUTES = [
10557
11161
  path: "/native-builds/:id/submission",
10558
11162
  handler: "recordNativeBuildSubmission"
10559
11163
  },
11164
+ {
11165
+ method: "POST",
11166
+ path: "/native-builds/:id/store-build",
11167
+ handler: "markNativeBuild"
11168
+ },
10560
11169
  {
10561
11170
  method: "DELETE",
10562
11171
  path: "/native-builds/:id",
10563
11172
  handler: "deleteNativeBuild"
11173
+ },
11174
+ {
11175
+ method: "GET",
11176
+ path: "/ios-devices",
11177
+ handler: "listIosDevices"
11178
+ },
11179
+ {
11180
+ method: "POST",
11181
+ path: "/ios-devices",
11182
+ handler: "requestIosDevice"
11183
+ },
11184
+ {
11185
+ method: "GET",
11186
+ path: "/ios-devices/udid/:udid",
11187
+ handler: "findIosDevice"
11188
+ },
11189
+ {
11190
+ method: "POST",
11191
+ path: "/ios-devices/in-build",
11192
+ handler: "markIosDevicesInBuild"
11193
+ },
11194
+ {
11195
+ method: "GET",
11196
+ path: "/ios-devices/account",
11197
+ handler: "findIosDeviceAccount"
11198
+ },
11199
+ {
11200
+ method: "POST",
11201
+ path: "/ios-devices/account",
11202
+ handler: "claimIosDeviceAccount"
11203
+ },
11204
+ {
11205
+ method: "POST",
11206
+ path: "/ios-devices/:id/approval",
11207
+ handler: "approveIosDevice"
11208
+ },
11209
+ {
11210
+ method: "POST",
11211
+ path: "/ios-devices/:id/outcome",
11212
+ handler: "recordIosDeviceOutcome"
11213
+ },
11214
+ {
11215
+ method: "PATCH",
11216
+ path: "/ios-devices/:id",
11217
+ handler: "renameIosDevice"
11218
+ },
11219
+ {
11220
+ method: "DELETE",
11221
+ path: "/ios-devices/:id",
11222
+ handler: "deleteIosDevice"
10564
11223
  }
10565
11224
  ];
10566
11225
  //#endregion
@@ -57415,12 +58074,19 @@ const PROTOCOL = "azblob";
57415
58074
  const SAS_EXPIRES_IN_MS = 36e5;
57416
58075
  const DELEGATION_KEY_LIFETIME_MS = 864e5;
57417
58076
  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);
58077
+ const serviceOf = async (config) => {
58078
+ if (!("connectionString" in config)) return new BlobServiceClient(config.accountUrl, config.credential);
58079
+ const { connectionString } = config;
58080
+ return BlobServiceClient.fromConnectionString(typeof connectionString === "function" ? await connectionString() : connectionString);
58081
+ };
57419
58082
  function azureBlobStorage(config) {
57420
58083
  const { containerName, basePath, getDownloadUrl } = config;
57421
58084
  let client;
57422
- const service = () => client ??= serviceOf(config);
57423
- const container = () => service().getContainerClient(containerName);
58085
+ const service = () => client ??= serviceOf(config).catch((error) => {
58086
+ client = void 0;
58087
+ throw error;
58088
+ });
58089
+ const container = async () => (await service()).getContainerClient(containerName);
57424
58090
  const normalizedBasePath = basePath?.replace(/^\/+|\/+$/g, "") ?? "";
57425
58091
  const getStorageKey = createStorageKeyBuilder(normalizedBasePath);
57426
58092
  const getListPrefix = (prefix = "") => {
@@ -57451,7 +58117,7 @@ function azureBlobStorage(config) {
57451
58117
  const delegationKey = () => {
57452
58118
  const now = Date.now();
57453
58119
  if (delegation === void 0 || delegation.renewAt <= now) {
57454
- const key = service().getUserDelegationKey(/* @__PURE__ */ new Date(now - 3e5), new Date(now + DELEGATION_KEY_LIFETIME_MS));
58120
+ const key = service().then((blobService) => blobService.getUserDelegationKey(/* @__PURE__ */ new Date(now - 3e5), new Date(now + DELEGATION_KEY_LIFETIME_MS)));
57455
58121
  key.catch(() => {
57456
58122
  delegation = void 0;
57457
58123
  });
@@ -57463,7 +58129,7 @@ function azureBlobStorage(config) {
57463
58129
  return delegation.key;
57464
58130
  };
57465
58131
  const signedUrl = async (key) => {
57466
- const blob = container().getBlobClient(key);
58132
+ const blob = (await container()).getBlobClient(key);
57467
58133
  const expiresOn = new Date(Date.now() + SAS_EXPIRES_IN_MS);
57468
58134
  const permissions = BlobSASPermissions.parse("r");
57469
58135
  if (blob.credential instanceof StorageSharedKeyCredential) return blob.generateSasUrl({
@@ -57484,7 +58150,8 @@ function azureBlobStorage(config) {
57484
58150
  protocol: PROTOCOL,
57485
58151
  async listObjects(prefix) {
57486
58152
  const objects = [];
57487
- for await (const blob of container().listBlobsFlat({ prefix: getListPrefix(prefix) })) {
58153
+ const blobs = await container();
58154
+ for await (const blob of blobs.listBlobsFlat({ prefix: getListPrefix(prefix) })) {
57488
58155
  const storageUri = getListedStorageUri(blob.name);
57489
58156
  if (storageUri === null) continue;
57490
58157
  objects.push({
@@ -57501,7 +58168,8 @@ function azureBlobStorage(config) {
57501
58168
  for (let offset = 0; offset < keys.length; offset += 256) {
57502
58169
  const batch = keys.slice(offset, offset + 256);
57503
58170
  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);
58171
+ const blobs = await container();
58172
+ const failed = (await blobs.getBlobBatchClient().deleteBlobs(batch.map((key) => blobs.getBlobClient(key)))).subResponses.filter(({ status }) => status >= 300 && status !== 404);
57505
58173
  if (failed.length > 0) throw new Error(`Failed to delete ${failed.length} Azure blob(s).`);
57506
58174
  }
57507
58175
  },
@@ -57511,7 +58179,7 @@ function azureBlobStorage(config) {
57511
58179
  blobContentType: contentType,
57512
58180
  blobCacheControl: "max-age=31536000"
57513
58181
  } };
57514
- const blob = container().getBlockBlobClient(storageKey);
58182
+ const blob = (await container()).getBlockBlobClient(storageKey);
57515
58183
  if (contentLength === void 0) await blob.uploadData(new Uint8Array(await new Response(body).arrayBuffer()), options);
57516
58184
  else {
57517
58185
  const { Readable } = await import("node:stream");
@@ -57540,13 +58208,12 @@ function azureBlobStorage(config) {
57540
58208
  async get({ storageUri }) {
57541
58209
  const { key } = parseAndValidate(storageUri);
57542
58210
  try {
57543
- const download = await container().getBlobClient(key).download();
58211
+ const download = await (await container()).getBlobClient(key).download();
57544
58212
  const body = download.readableStreamBody;
57545
58213
  if (body === void 0) return { response: null };
57546
58214
  const headers = new Headers();
57547
58215
  if (download.contentType) headers.set("content-type", download.contentType);
57548
58216
  if (download.contentLength !== void 0) headers.set("content-length", String(download.contentLength));
57549
- const { Readable } = await import("node:stream");
57550
58217
  return { response: new Response(Readable.toWeb(body), { headers }) };
57551
58218
  } catch (error) {
57552
58219
  if (isNotFound(error)) return { response: null };
@@ -57560,11 +58227,11 @@ function azureBlobStorage(config) {
57560
58227
  },
57561
58228
  async exists({ storageUri }) {
57562
58229
  const { key } = parseAndValidate(storageUri);
57563
- return { exists: await container().getBlobClient(key).exists() };
58230
+ return { exists: await (await container()).getBlobClient(key).exists() };
57564
58231
  },
57565
58232
  async delete({ storageUri }) {
57566
58233
  const { key } = parseAndValidate(storageUri);
57567
- await container().getBlobClient(key).deleteIfExists();
58234
+ await (await container()).getBlobClient(key).deleteIfExists();
57568
58235
  return { deleted: true };
57569
58236
  }
57570
58237
  });
@@ -70857,18 +71524,21 @@ const isWideAdd = (op) => op.type === "add" && Object.keys(op.by).length + (op.e
70857
71524
  const emulatorAborted = (error) => statusOf(error) === 500 && /PostgresError\(SqlState\(E(25P02|40001|40P01)\)/.test(String(error instanceof Error ? error.message : error));
70858
71525
  const createCosmosStore = ({ client, databaseId, containerId, engine, nativePageSize }) => {
70859
71526
  let opened;
70860
- const open = () => opened ??= (() => {
70861
- const account = typeof client === "function" ? client() : client;
71527
+ const open = () => opened ??= (async () => {
71528
+ const account = typeof client === "function" ? await client() : client;
70862
71529
  return {
70863
71530
  client: account,
70864
71531
  container: account.database(databaseId).container(containerId)
70865
71532
  };
70866
- })();
70867
- const container = () => open().container;
71533
+ })().catch((error) => {
71534
+ opened = void 0;
71535
+ throw error;
71536
+ });
71537
+ const container = async () => (await open()).container;
70868
71538
  const readStates = async (ids, rowIds) => {
70869
71539
  const states = /* @__PURE__ */ new Map();
70870
71540
  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);
71541
+ 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
71542
  for (const { id, etag, v, expireAt, row } of resources) states.set(id, {
70873
71543
  etag,
70874
71544
  v,
@@ -71000,7 +71670,7 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
71000
71670
  const found = /* @__PURE__ */ new Map();
71001
71671
  const ids = [...new Set(keys.map(cosmosItemId))];
71002
71672
  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);
71673
+ 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
71674
  for (const resource of resources) found.set(resource.id, toRow(resource.row));
71005
71675
  }
71006
71676
  return keys.map((key) => found.get(cosmosItemId(key)) ?? null);
@@ -71036,7 +71706,7 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
71036
71706
  value: after
71037
71707
  });
71038
71708
  }
71039
- const { resources } = await container().items.query({
71709
+ const { resources } = await (await container()).items.query({
71040
71710
  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
71711
  parameters
71042
71712
  }, {
@@ -71086,7 +71756,7 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
71086
71756
  if (planned.length > BATCH_OPERATIONS) throw new Error(`A Cosmos DB batch takes ${BATCH_OPERATIONS} operations; this write needs ${planned.length}.`);
71087
71757
  let results;
71088
71758
  try {
71089
- const response = await container().items.batch(planned.map(({ operation }) => operation), COSMOS_PARTITION);
71759
+ const response = await (await container()).items.batch(planned.map(({ operation }) => operation), COSMOS_PARTITION);
71090
71760
  if (response.result === void 0) throw Object.assign(/* @__PURE__ */ new Error(`Cosmos DB refused the batch with status ${response.code}`), { code: response.code });
71091
71761
  results = response.result;
71092
71762
  } catch (error) {
@@ -71119,7 +71789,7 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
71119
71789
  async deleteConsumed(keys) {
71120
71790
  let remaining = [...new Set(keys.map(cosmosItemId))];
71121
71791
  for (let attempt = 0; remaining.length > 0; attempt += 1) {
71122
- const failed = (await container().items.executeBulkOperations(remaining.map((id) => ({
71792
+ const failed = (await (await container()).items.executeBulkOperations(remaining.map((id) => ({
71123
71793
  operationType: "Delete",
71124
71794
  id,
71125
71795
  partitionKey: COSMOS_PARTITION
@@ -71138,8 +71808,8 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
71138
71808
  }
71139
71809
  },
71140
71810
  migrations: { async apply() {
71141
- if (engine !== void 0) await assertCosmosContainerReusable(container(), engine);
71142
- const { database } = await open().client.databases.createIfNotExists({ id: databaseId });
71811
+ if (engine !== void 0) await assertCosmosContainerReusable(await container(), engine);
71812
+ const { database } = await (await open()).client.databases.createIfNotExists({ id: databaseId });
71143
71813
  const { resource } = await database.containers.createIfNotExists({
71144
71814
  id: containerId,
71145
71815
  partitionKey: { paths: [COSMOS_PARTITION_KEY_PATH] },
@@ -71176,8 +71846,12 @@ const adapterOf = (config) => {
71176
71846
  const { databaseId = AZURE_COSMOS_V1_DATABASE, containerId = AZURE_COSMOS_V1_CONTAINER, aggregateBatching: _, ...connection } = config;
71177
71847
  if (connection.consistencyLevel !== void 0 && connection.consistencyLevel !== "Strong") throw new Error(`cosmosDatabase reads with strong consistency; consistencyLevel "${String(connection.consistencyLevel)}" is weaker.`);
71178
71848
  let client;
71849
+ const { connectionString } = connection;
71179
71850
  const store = createCosmosStore({
71180
- client: () => client ??= new CosmosClient(connection),
71851
+ client: async () => client ??= new CosmosClient({
71852
+ ...connection,
71853
+ connectionString: typeof connectionString === "function" ? await connectionString() : connectionString
71854
+ }),
71181
71855
  databaseId,
71182
71856
  containerId,
71183
71857
  engine: currentCosmosEngine()
@@ -71189,7 +71863,7 @@ const adapterOf = (config) => {
71189
71863
  };
71190
71864
  const DATABASE_TARGET = Symbol.for("@hot-updater/database-target");
71191
71865
  const accountHostOf = ({ endpoint, connectionString }) => {
71192
- const url = endpoint ?? connectionString?.match(/AccountEndpoint=([^;]+)/iu)?.[1];
71866
+ const url = endpoint ?? (typeof connectionString === "string" ? connectionString.match(/AccountEndpoint=([^;]+)/iu)?.[1] : void 0);
71193
71867
  try {
71194
71868
  return url === void 0 ? void 0 : new URL(url).hostname;
71195
71869
  } catch {