@hot-updater/azure 1.2.0-rc.5 → 1.2.0-rc.50

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";
@@ -5738,43 +5738,6 @@ const withSchemaFence = (adapter, adapterName, expected, fix) => {
5738
5738
  const METER = Symbol.for("@hot-updater/plugin-core/read-meter");
5739
5739
  const readMeterOf = (database) => typeof database === "object" && database !== null ? database[METER] : void 0;
5740
5740
  //#endregion
5741
- //#region ../plugin-core/dist/engine/db/schemaSettings.mjs
5742
- const storedSettings = async (adapter, keys) => {
5743
- const rows = await readSettings(adapter, keys);
5744
- return new Map(keys.map((key, position) => [key, rows[position] ?? null]));
5745
- };
5746
- const writeSchemaSettings = async (adapter, adapterName, settings) => {
5747
- const stored = await storedSettings(adapter, Object.keys(settings));
5748
- const ops = Object.entries(settings).flatMap(([key, value]) => {
5749
- const row = stored.get(key);
5750
- if (row === null || row === void 0) return [{
5751
- type: "insert",
5752
- table: SETTINGS_TABLE,
5753
- row: {
5754
- key,
5755
- value,
5756
- _v: 0
5757
- }
5758
- }];
5759
- if (row.value === value) return [];
5760
- return [{
5761
- type: "patch",
5762
- table: SETTINGS_TABLE,
5763
- key: [key],
5764
- set: { value },
5765
- guard: { v: Number(row._v) },
5766
- previous: row
5767
- }];
5768
- });
5769
- if (ops.length === 0) return;
5770
- if (!(await adapter.write(ops)).ok) throw new Error(`${adapterName}: the schema settings changed during the migration; run it again.`);
5771
- };
5772
- const migrateSchema = async (adapter, adapterName, tables, settings) => {
5773
- if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
5774
- await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
5775
- await writeSchemaSettings(adapter, adapterName, settings);
5776
- };
5777
- //#endregion
5778
5741
  //#region ../plugin-core/dist/engine/core/schema.mjs
5779
5742
  const CHANNEL_ID = {
5780
5743
  type: "string",
@@ -5961,9 +5924,17 @@ const releases = defineTable({
5961
5924
  all: {
5962
5925
  eq: [],
5963
5926
  sort: ["id"]
5927
+ },
5928
+ scopes: {
5929
+ eq: [],
5930
+ sort: ["scope_key"]
5964
5931
  }
5965
5932
  }
5966
5933
  });
5934
+ const LATE_INDEXES = [{
5935
+ table: "releases",
5936
+ index: "scopes"
5937
+ }];
5967
5938
  const releaseCatalogs = defineTable({
5968
5939
  scope_key: {
5969
5940
  type: "string",
@@ -6104,9 +6075,32 @@ const nativeBuilds = defineTable({
6104
6075
  type: "string",
6105
6076
  maxLength: 255,
6106
6077
  required: false
6078
+ },
6079
+ is_store_build: { type: "boolean" },
6080
+ is_sandbox: { type: "boolean" },
6081
+ sandbox_url_scheme: {
6082
+ type: "string",
6083
+ maxLength: 255,
6084
+ ascii: true,
6085
+ required: false
6086
+ },
6087
+ export_method: {
6088
+ type: "string",
6089
+ maxLength: 16,
6090
+ required: false
6091
+ },
6092
+ native_app_version: {
6093
+ type: "string",
6094
+ required: false
6107
6095
  }
6108
6096
  }, {
6109
6097
  key: ["id"],
6098
+ derived: { store_build_scope_key: {
6099
+ type: "string",
6100
+ maxLength: 2048,
6101
+ ascii: true,
6102
+ compute: (row) => row.is_store_build ? row.scope_key : null
6103
+ } },
6110
6104
  indexes: {
6111
6105
  byScope: {
6112
6106
  eq: ["scope_key"],
@@ -6116,6 +6110,15 @@ const nativeBuilds = defineTable({
6116
6110
  eq: ["scope_key", "build_key"],
6117
6111
  sort: ["id"]
6118
6112
  },
6113
+ byScopeKind: {
6114
+ eq: ["scope_key", "artifact_kind"],
6115
+ sort: ["id"]
6116
+ },
6117
+ byStoreBuild: {
6118
+ eq: ["store_build_scope_key"],
6119
+ sort: [],
6120
+ unique: true
6121
+ },
6119
6122
  byChannel: {
6120
6123
  eq: ["channel_id"],
6121
6124
  sort: ["id"],
@@ -6127,6 +6130,96 @@ const nativeBuilds = defineTable({
6127
6130
  }
6128
6131
  }
6129
6132
  });
6133
+ const iosDevices = defineTable({
6134
+ id: {
6135
+ type: "string",
6136
+ maxLength: 36
6137
+ },
6138
+ udid: {
6139
+ type: "string",
6140
+ maxLength: 40,
6141
+ ascii: true,
6142
+ unique: true
6143
+ },
6144
+ name: {
6145
+ type: "string",
6146
+ maxLength: 100
6147
+ },
6148
+ status: {
6149
+ type: "string",
6150
+ maxLength: 16
6151
+ },
6152
+ requested_by: {
6153
+ type: "string",
6154
+ maxLength: 320,
6155
+ required: false
6156
+ },
6157
+ created_at_ms: { type: "integer" },
6158
+ approved_by: {
6159
+ type: "string",
6160
+ maxLength: 320,
6161
+ required: false
6162
+ },
6163
+ approved_at_ms: {
6164
+ type: "integer",
6165
+ required: false
6166
+ },
6167
+ registered_at_ms: {
6168
+ type: "integer",
6169
+ required: false
6170
+ },
6171
+ apple_issuer_id: {
6172
+ type: "string",
6173
+ maxLength: 64,
6174
+ ascii: true,
6175
+ required: false
6176
+ },
6177
+ apple_error: {
6178
+ type: "string",
6179
+ maxLength: 512,
6180
+ required: false
6181
+ },
6182
+ build_id: {
6183
+ type: "string",
6184
+ maxLength: 36,
6185
+ required: false
6186
+ }
6187
+ }, {
6188
+ key: ["id"],
6189
+ indexes: {
6190
+ byStatus: {
6191
+ eq: ["status"],
6192
+ sort: ["id"]
6193
+ },
6194
+ byRegistration: {
6195
+ eq: [],
6196
+ sort: ["registered_at_ms"]
6197
+ },
6198
+ all: {
6199
+ eq: [],
6200
+ sort: ["id"]
6201
+ }
6202
+ }
6203
+ });
6204
+ const iosDeviceAccount = defineTable({
6205
+ id: {
6206
+ type: "string",
6207
+ maxLength: 16,
6208
+ ascii: true
6209
+ },
6210
+ apple_issuer_id: {
6211
+ type: "string",
6212
+ maxLength: 64,
6213
+ ascii: true
6214
+ },
6215
+ claimed_at_ms: { type: "integer" }
6216
+ }, {
6217
+ key: ["id"],
6218
+ indexes: { all: {
6219
+ eq: [],
6220
+ sort: ["id"]
6221
+ } }
6222
+ });
6130
6223
  const coreModule = {
6131
6224
  id: "core",
6132
6225
  schema: {
@@ -6146,7 +6239,9 @@ const coreModule = {
6146
6239
  sort: []
6147
6240
  } }
6148
6241
  }),
6149
- native_builds: nativeBuilds
6242
+ native_builds: nativeBuilds,
6243
+ ios_devices: iosDevices,
6244
+ ios_device_account: iosDeviceAccount
6150
6245
  }
6151
6246
  };
6152
6247
  //#endregion
@@ -6167,6 +6262,90 @@ const refuseV0Database = (adapterName, stored) => {
6167
6262
  if (typeof version !== "string" || stored.has("schema.engine")) return;
6168
6263
  throw new HotUpdaterSchemaMigrationRequiredError(adapterName, version);
6169
6264
  };
6265
+ const compareVersions = (left, right) => {
6266
+ const parse = (version) => /^\d+(?:\.\d+)*$/u.test(version) ? version.split(".").map(Number) : [NaN];
6267
+ const [a, b] = [parse(left), parse(right)];
6268
+ if ([...a, ...b].some(Number.isNaN)) return NaN;
6269
+ for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
6270
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
6271
+ if (difference !== 0) return difference;
6272
+ }
6273
+ return 0;
6274
+ };
6275
+ const DEFAULT_ORDERED_SETTINGS = ["schema.core"];
6276
+ const refuseNewerSchema = (adapterName, stored, settings, ordered = DEFAULT_ORDERED_SETTINGS) => {
6277
+ const newer = ordered.flatMap((key) => {
6278
+ const found = stored.get(key);
6279
+ const expected = settings[key];
6280
+ return typeof found === "string" && expected !== void 0 && compareVersions(found, expected) > 0 ? [{
6281
+ key,
6282
+ found,
6283
+ expected
6284
+ }] : [];
6285
+ });
6286
+ const core = newer.find(({ key }) => key === "schema.core");
6287
+ if (core === void 0) return;
6288
+ throw new Error(`${adapterName}: the database was migrated by Hot Updater ${core.found} (${newer.map(({ key, found, expected }) => `${key} "${found}", this CLI's "${expected}"`).join("; ")}). Upgrade hot-updater to ${core.found} or later; nothing was written.`);
6289
+ };
6290
+ const settingsOperation = (stored, changed) => ({
6291
+ type: "custom",
6292
+ description: `Record ${changed.map(([key, value]) => {
6293
+ const found = stored.get(key);
6294
+ return typeof found === "string" ? `${key} ${found} → ${value}` : `${key} ${value}`;
6295
+ }).join(", ")}`
6296
+ });
6297
+ //#endregion
6298
+ //#region ../plugin-core/dist/engine/db/schemaSettings.mjs
6299
+ const storedSettings = async (adapter, keys) => {
6300
+ const rows = await readSettings(adapter, keys);
6301
+ return new Map(keys.map((key, position) => [key, rows[position] ?? null]));
6302
+ };
6303
+ const writeSchemaSettings = async (adapter, adapterName, settings, ordered) => {
6304
+ const stored = await storedSettings(adapter, Object.keys(settings));
6305
+ refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
6306
+ const ops = Object.entries(settings).flatMap(([key, value]) => {
6307
+ const row = stored.get(key);
6308
+ if (row === null || row === void 0) return [{
6309
+ type: "insert",
6310
+ table: SETTINGS_TABLE,
6311
+ row: {
6312
+ key,
6313
+ value,
6314
+ _v: 0
6315
+ }
6316
+ }];
6317
+ if (row.value === value) return [];
6318
+ return [{
6319
+ type: "patch",
6320
+ table: SETTINGS_TABLE,
6321
+ key: [key],
6322
+ set: { value },
6323
+ guard: { v: Number(row._v) },
6324
+ previous: row
6325
+ }];
6326
+ });
6327
+ if (ops.length === 0) return;
6328
+ if (!(await adapter.write(ops)).ok) throw new Error(`${adapterName}: the schema settings changed during the migration; run it again.`);
6329
+ };
6330
+ const fillLateIndexes = async (adapter, tables, { dryRun = false } = {}) => {
6331
+ const fillIndex = adapter.migrations?.fillIndex;
6332
+ if (fillIndex === void 0) return [];
6333
+ const lacking = [];
6334
+ for (const { table: name, index } of LATE_INDEXES) {
6335
+ const table = tables.find((candidate) => candidate.name === name);
6336
+ if (table === void 0) continue;
6337
+ if (await fillIndex(table, index, { dryRun }) > 0) lacking.push(`${name}.${index}`);
6338
+ }
6339
+ return lacking;
6340
+ };
6341
+ const migrateSchema = async (adapter, adapterName, tables, settings, ordered) => {
6342
+ if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
6343
+ const stored = await storedSettings(adapter, Object.keys(settings)).catch(() => void 0);
6344
+ if (stored !== void 0) refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
6345
+ await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
6346
+ await fillLateIndexes(adapter, tables);
6347
+ await writeSchemaSettings(adapter, adapterName, settings, ordered);
6348
+ };
6170
6349
  //#endregion
6171
6350
  //#region ../plugin-core/dist/engine/database/cursor.mjs
6172
6351
  const encoder$3 = new TextEncoder();
@@ -6311,18 +6490,15 @@ const LOG_TABLES = [
6311
6490
  const LEASE_TABLE = "aggregate_lease";
6312
6491
  const LEASE = { id: "compaction" };
6313
6492
  const LEASE_MS = 3e4;
6314
- const WINDOW_MS$1 = {
6315
- log: 6e4,
6316
- memory: 15e3
6317
- };
6493
+ const WINDOW_MS$1 = 6e4;
6318
6494
  const LOG_PAGE = 200;
6495
+ const SKIP_AFTER_MS = 3e5;
6319
6496
  const GROUPS = {
6320
6497
  commit: 1,
6321
6498
  read: 8,
6322
6499
  flush: 256
6323
6500
  };
6324
6501
  const ATTEMPTS = 5;
6325
- const MAX_BUFFERED = 1e4;
6326
6502
  const log$1 = defineTable({
6327
6503
  id: {
6328
6504
  type: "string",
@@ -6423,18 +6599,30 @@ const rewrite = (change, key, current) => {
6423
6599
  previous: current
6424
6600
  };
6425
6601
  };
6426
- const compile = async (adapter, changes, shard) => {
6427
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
6602
+ const rowId = (model, key) => JSON.stringify([model.table.name, key]);
6603
+ const keysOf = (changes) => changes.map(({ key }) => [...key.slice(0, -1), 0]);
6604
+ const readCurrent = async (adapter, changes) => {
6605
+ const keys = keysOf(changes);
6428
6606
  const reads = /* @__PURE__ */ new Map();
6429
6607
  changes.forEach((change, at) => {
6430
- if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
6608
+ if (!rewrites(change)) return;
6609
+ const wanted = reads.get(change.model) ?? /* @__PURE__ */ new Map();
6610
+ wanted.set(rowId(change.model, keys[at]), keys[at]);
6611
+ reads.set(change.model, wanted);
6431
6612
  });
6432
6613
  const current = /* @__PURE__ */ new Map();
6433
- await Promise.all([...reads].map(async ([model, positions]) => {
6434
- const rows = await adapter.get(model.table, positions.map((at) => keys[at]));
6435
- positions.forEach((at, index) => current.set(at, rows[index] ?? null));
6614
+ await Promise.all([...reads].map(async ([model, wanted]) => {
6615
+ const keys = [...wanted.values()];
6616
+ const rows = await adapter.get(model.table, keys);
6617
+ keys.forEach((key, at) => {
6618
+ current.set(rowId(model, key), rows[at] ?? null);
6619
+ });
6436
6620
  }));
6437
- return changes.map((change, at) => current.has(at) ? rewrite(change, keys[at], current.get(at)) : increment(change, keys[at]));
6621
+ return current;
6622
+ };
6623
+ const build = (changes, current) => {
6624
+ const keys = keysOf(changes);
6625
+ return changes.map((change, at) => rewrites(change) ? rewrite(change, keys[at], current.get(rowId(change.model, keys[at])) ?? null) : increment(change, keys[at]));
6438
6626
  };
6439
6627
  const isOp = (op) => op !== void 0;
6440
6628
  const sleep$1 = (attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random()));
@@ -6470,7 +6658,7 @@ const encode$1 = async (changes) => {
6470
6658
  const zipped = await deflate(json);
6471
6659
  return zipped !== void 0 && zipped.length < json.length ? `z${zipped}` : json;
6472
6660
  };
6473
- const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS$1[mode] }, now }) => {
6661
+ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs = WINDOW_MS$1 }, now }) => {
6474
6662
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
6475
6663
  const holder = crypto.randomUUID().replaceAll("-", "");
6476
6664
  const table = (name) => schema.models.get(name).table;
@@ -6497,64 +6685,12 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6497
6685
  }
6498
6686
  return changes;
6499
6687
  };
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
6688
  let nextDue = 0;
6556
6689
  let compacting;
6557
6690
  const known = /* @__PURE__ */ new Map();
6691
+ const skipped = LOG_TABLES.map(() => void 0);
6692
+ const past = (shard) => skipped[shard] === void 0 ? {} : { range: { gt: skipped[shard] } };
6693
+ const stampOf = (id) => Number.parseInt(id.slice(0, 9), 36);
6558
6694
  const idOf = (shard, id) => JSON.stringify([shard, id]);
6559
6695
  const leaseOp = (held, set) => {
6560
6696
  const next = {
@@ -6658,14 +6794,22 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6658
6794
  logs: (await Promise.all(LOG_TABLES.map(async (name, shard) => {
6659
6795
  const page = await engine.reads.findMany(name, {
6660
6796
  index: "oldest",
6661
- limit: LOG_PAGE
6797
+ limit: LOG_PAGE,
6798
+ ...past(shard)
6662
6799
  });
6663
6800
  more ||= page.next !== void 0;
6664
- return (await Promise.all(page.rows.map(async (row) => ({
6801
+ const decoded = await Promise.all(page.rows.map(async (row) => ({
6665
6802
  shard,
6666
6803
  row,
6667
6804
  changes: await decode(String(row.changes))
6668
- })))).flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
6805
+ })));
6806
+ const settled = now() - SKIP_AFTER_MS;
6807
+ for (const { row, changes } of decoded) {
6808
+ const id = String(row.id);
6809
+ if (changes !== void 0 || stampOf(id) >= settled) break;
6810
+ skipped[shard] = id;
6811
+ }
6812
+ return decoded.flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
6669
6813
  ...entry,
6670
6814
  changes
6671
6815
  }]);
@@ -6673,14 +6817,15 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6673
6817
  more
6674
6818
  };
6675
6819
  };
6676
- const rowsFor = async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp);
6677
6820
  const applyGroup = async (held, logs) => {
6821
+ const current = await readCurrent(adapter, logs.flatMap((entry) => [...entry.changes.values()]));
6822
+ const rowsFor = (changes) => build(changes, current).filter(isOp);
6678
6823
  for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
6679
6824
  const batch = logs.slice(0, count);
6680
6825
  const changes = mergeAll(/* @__PURE__ */ new Map(), batch.flatMap((entry) => [...entry.changes.values()]));
6681
6826
  const applied = batch.map(({ shard, row }) => [shard, row.id]);
6682
6827
  const lease = leaseOp(held, { applied: JSON.stringify(applied) });
6683
- const ops = [...await rowsFor([...changes.values()]), lease.op];
6828
+ const ops = [...rowsFor([...changes.values()]), lease.op];
6684
6829
  if (!adapter.fits(ops)) continue;
6685
6830
  for (const { shard, row } of batch) known.set(idOf(shard, row.id), row);
6686
6831
  return await commit(ops) ? {
@@ -6702,7 +6847,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6702
6847
  };
6703
6848
  const lease = leaseOp(held, {});
6704
6849
  const ops = [
6705
- ...await rowsFor(entries.slice(0, take)),
6850
+ ...rowsFor(entries.slice(0, take)),
6706
6851
  kept,
6707
6852
  lease.op
6708
6853
  ];
@@ -6718,11 +6863,12 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6718
6863
  if (held === void 0) return;
6719
6864
  let pending = true;
6720
6865
  let clear = false;
6866
+ let carried;
6721
6867
  try {
6722
6868
  for (let group = 0;; group += 1) {
6723
6869
  clear = await deleteApplied(held);
6724
6870
  if (!clear || !pending || group === groups) break;
6725
- const { logs, more } = await readLogs();
6871
+ const { logs, more } = carried ?? await readLogs();
6726
6872
  if (logs.length === 0) {
6727
6873
  pending = false;
6728
6874
  break;
@@ -6730,6 +6876,11 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6730
6876
  const applied = await applyGroup(held, logs);
6731
6877
  if (applied === void 0) break;
6732
6878
  [held, clear] = [applied.held, false];
6879
+ const rest = applied.count === 0 ? [] : logs.slice(applied.count);
6880
+ carried = rest.length > 0 ? {
6881
+ logs: rest,
6882
+ more
6883
+ } : void 0;
6733
6884
  pending = more || applied.count < logs.length;
6734
6885
  }
6735
6886
  } finally {
@@ -6747,25 +6898,13 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6747
6898
  compacting = void 0;
6748
6899
  });
6749
6900
  let checking;
6750
- const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name) => engine.reads.findMany(name, {
6901
+ const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name, shard) => engine.reads.findMany(name, {
6751
6902
  index: "oldest",
6752
- limit: 1
6903
+ limit: 1,
6904
+ ...past(shard)
6753
6905
  }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
6754
6906
  checking = void 0;
6755
6907
  });
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
6908
  return {
6770
6909
  async transaction(fn) {
6771
6910
  let changes = /* @__PURE__ */ new Map();
@@ -6791,7 +6930,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6791
6930
  aggregate
6792
6931
  });
6793
6932
  if (failure) throw failure.error;
6794
- if (mode === "log" && attempt.size > 0) {
6933
+ if (attempt.size > 0) {
6795
6934
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
6796
6935
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
6797
6936
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -6805,24 +6944,18 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
6805
6944
  open = false;
6806
6945
  }
6807
6946
  });
6808
- if (changes.size > 0) await committed(changes);
6947
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
6809
6948
  return result;
6810
6949
  },
6811
6950
  async beforeRead(name) {
6812
6951
  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
- }
6952
+ if (await hasPending().catch((error) => {
6953
+ warn("read")(error);
6954
+ return false;
6955
+ })) await compact(true, GROUPS.read);
6820
6956
  },
6821
- flush,
6822
- async dispose() {
6823
- clearTimeout(timer);
6824
- timer = void 0;
6825
- await flush();
6957
+ async flush() {
6958
+ if (await hasPending()) await compact(true, GROUPS.flush);
6826
6959
  }
6827
6960
  };
6828
6961
  };
@@ -6941,7 +7074,8 @@ const fieldProblems = (definition, add) => {
6941
7074
  else if (field.required === false) add(`key field "${name}" is nullable`);
6942
7075
  else if (field.type === "json") add(`key field "${name}" is json`);
6943
7076
  }
6944
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
7077
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
7078
+ for (const [name, { type, maxLength, ascii }] of bounded) {
6945
7079
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
6946
7080
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
6947
7081
  }
@@ -7053,11 +7187,13 @@ const resolveSchema = (modules) => {
7053
7187
  ...maxLength === void 0 ? {} : { maxLength },
7054
7188
  ...ascii ? { ascii } : {}
7055
7189
  }));
7056
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
7190
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
7057
7191
  name: field,
7058
7192
  type,
7059
7193
  nullable: true,
7060
- ...multi ? { multi } : {}
7194
+ ...multi ? { multi } : {},
7195
+ ...maxLength === void 0 ? {} : { maxLength },
7196
+ ...ascii ? { ascii } : {}
7061
7197
  });
7062
7198
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
7063
7199
  name: metric,
@@ -7094,22 +7230,27 @@ const createEngineMigrator = (options) => {
7094
7230
  const makeResult = async (migrate = {}) => {
7095
7231
  const stored = await options.readSettings();
7096
7232
  refuseV0Database(options.adapterName, stored);
7097
- if (Object.entries(options.settings).every(([key, value]) => stored.get(key) === value)) return getEmptyMigrationResult();
7098
- return {
7099
- operations: [...options.schema.tables.map((table) => ({
7100
- type: "create-table",
7101
- value: {
7102
- ormName: table.name,
7103
- columns: Object.fromEntries(table.columns.map((column) => [column.name, {
7104
- ormName: column.name,
7105
- type: column.type
7106
- }]))
7233
+ refuseNewerSchema(options.adapterName, stored, options.settings, options.ordered);
7234
+ const changed = Object.entries(options.settings).filter(([key, value]) => stored.get(key) !== value);
7235
+ if (changed.length === 0) {
7236
+ const lacking = await fillLateIndexes(options.adapter, options.schema.tables, { dryRun: true });
7237
+ if (lacking.length === 0) return getEmptyMigrationResult();
7238
+ return {
7239
+ operations: [{
7240
+ type: "custom",
7241
+ description: `Write the index items rows lack: ${lacking.join(", ")}`
7242
+ }],
7243
+ execute: async () => {
7244
+ await fillLateIndexes(options.adapter, options.schema.tables);
7107
7245
  }
7108
- })), ...migrate.updateSettings === false ? [] : [{
7246
+ };
7247
+ }
7248
+ return {
7249
+ operations: [{
7109
7250
  type: "custom",
7110
- description: `Write the schema settings: ${Object.keys(options.settings).join(", ")}`
7111
- }]],
7112
- execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings)
7251
+ description: "Create the tables and indexes the database lacks"
7252
+ }, ...migrate.updateSettings === false ? [] : [settingsOperation(stored, changed)]],
7253
+ execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings, options.ordered)
7113
7254
  };
7114
7255
  };
7115
7256
  return {
@@ -7137,8 +7278,10 @@ const coreSettings = {
7137
7278
  };
7138
7279
  const coreTarget = {
7139
7280
  schema: coreSchema,
7140
- settings: coreSettings
7281
+ settings: coreSettings,
7282
+ ordered: ["schema.core"]
7141
7283
  };
7284
+ const isOfficialPlugin$1 = (plugin) => Reflect.get(plugin, Symbol.for("@hot-updater/server/official-plugin")) === true;
7142
7285
  resolveSchema([aggregateBatchingModule]).tables;
7143
7286
  const pluginSettings = (plugins) => Object.fromEntries(plugins.map(({ id, schemaVersion }) => [`schema.${id}`, schemaVersion]));
7144
7287
  const pluginModule = ({ id, schema, namespace }) => ({
@@ -7151,15 +7294,17 @@ const toolingTargetOf = (plugins) => plugins.length === 0 ? coreTarget : {
7151
7294
  settings: {
7152
7295
  ...coreSettings,
7153
7296
  ...pluginSettings(plugins)
7154
- }
7297
+ },
7298
+ ordered: [...coreTarget.ordered, ...plugins.flatMap((plugin) => isOfficialPlugin$1(plugin) ? [`schema.${plugin.id}`] : [])]
7155
7299
  };
7156
7300
  const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBatching, retry, readSettings: readStored }) => {
7157
7301
  const fenced = withSchemaFence(adapter, name, coreSettings);
7158
- const createMigrator = ({ schema, settings } = coreTarget) => createEngineMigrator({
7302
+ const createMigrator = ({ schema, settings, ordered } = coreTarget) => createEngineMigrator({
7159
7303
  adapterName: name,
7160
7304
  adapter,
7161
7305
  schema,
7162
7306
  settings,
7307
+ ordered,
7163
7308
  readSettings: readStored ?? (async () => {
7164
7309
  const rows = await readSettings(adapter, Object.keys(settings)).catch((error) => {
7165
7310
  if (isMissingSchemaError(error)) return [];
@@ -7182,6 +7327,11 @@ const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBa
7182
7327
  //#region ../plugin-core/dist/engine/database/engineTransaction.mjs
7183
7328
  var StaleReadError = class extends Error {};
7184
7329
  const idOf = (table, key) => JSON.stringify([table, key]);
7330
+ const versionsOf = (ops) => JSON.stringify(ops.map((op) => op.type === "insert" ? [op.table.name, rowKey(op.table, op.row)] : [
7331
+ op.table.name,
7332
+ op.key,
7333
+ "guard" in op ? op.guard?.v : void 0
7334
+ ]));
7185
7335
  const versionOf = (row) => Number(row["_v"]);
7186
7336
  const isKeyed = (value) => value !== null && value !== void 0;
7187
7337
  const misuse = (table, message) => new DatabaseTransactionError(`${table}: ${message}`);
@@ -7513,7 +7663,9 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
7513
7663
  assertOutsideTransaction();
7514
7664
  let run;
7515
7665
  let negative;
7516
- for (let round = 0; round < attempts; round += 1) {
7666
+ let failures = 0;
7667
+ let lost;
7668
+ for (let round = 0;; round += 1) {
7517
7669
  const delay = round && Math.min(maxDelayMs, baseDelayMs * 2 ** (round - 1));
7518
7670
  if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay / 2 + Math.random() * (delay / 2)));
7519
7671
  run ??= await attempt(fn).catch((error) => {
@@ -7522,6 +7674,8 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
7522
7674
  });
7523
7675
  if (run === void 0) {
7524
7676
  onRetry?.("rerun", round + 1);
7677
+ lost = void 0;
7678
+ if ((failures += 1) >= attempts) break;
7525
7679
  continue;
7526
7680
  }
7527
7681
  let aggregates;
@@ -7532,8 +7686,14 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
7532
7686
  negative = error;
7533
7687
  onRetry?.("rerun", round + 1);
7534
7688
  run = void 0;
7689
+ lost = void 0;
7690
+ if ((failures += 1) >= attempts) break;
7535
7691
  continue;
7536
7692
  }
7693
+ const versions = versionsOf(aggregates);
7694
+ if (lost !== void 0 && versions !== lost) failures -= 1;
7695
+ lost = void 0;
7696
+ if (failures >= attempts) break;
7537
7697
  const ops = [...run.ops, ...aggregates];
7538
7698
  if (ops.length <= 1 && ops.every(({ type }) => type === "check")) return run.result;
7539
7699
  if (!adapter.fits(ops)) throw new DatabaseConstraintError("too_large", ops[0].table.name);
@@ -7547,12 +7707,16 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
7547
7707
  const failed = "failedOp" in outcome ? outcome.failedOp : void 0;
7548
7708
  if (failed === void 0 || failed >= run.ops.length) {
7549
7709
  onRetry?.("resend", round + 1);
7710
+ failures += 1;
7711
+ if (failed !== void 0) lost = versions;
7712
+ else if (failures >= attempts) break;
7550
7713
  continue;
7551
7714
  }
7552
7715
  const reason = await classify(ops[failed], run.read);
7553
7716
  if (reason) throw new DatabaseConstraintError(reason, ops[failed].table.name);
7554
7717
  onRetry?.("rerun", round + 1);
7555
7718
  run = void 0;
7719
+ if ((failures += 1) >= attempts) break;
7556
7720
  }
7557
7721
  throw negative ?? new DatabaseConflictError(`The transaction conflicted ${attempts} times.`);
7558
7722
  } };
@@ -7788,9 +7952,6 @@ const createDatabaseEngine = ({ batching, now = Date.now, meter, ...options }) =
7788
7952
  flush: async () => {
7789
7953
  await batches?.flush();
7790
7954
  },
7791
- dispose: async () => {
7792
- await batches?.dispose();
7793
- },
7794
7955
  database(module) {
7795
7956
  const name = (model) => module.namespace ? `${module.namespace}_${model}` : model;
7796
7957
  return {
@@ -7858,8 +8019,7 @@ const createEngine = (database, { plugins = [], now = Date.now } = {}) => {
7858
8019
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
7859
8020
  return engine.database(module);
7860
8021
  },
7861
- flush: () => engine.flush(),
7862
- dispose: () => engine.dispose()
8022
+ flush: () => engine.flush()
7863
8023
  };
7864
8024
  };
7865
8025
  //#endregion
@@ -7910,9 +8070,9 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
7910
8070
  const at = row && expiresAt(table, row);
7911
8071
  return at === void 0 ? {} : { expiresAt: at };
7912
8072
  };
7913
- const itemsOf = (layout, row) => {
8073
+ const itemsOf = (layout, row, indexes = layout.indexed) => {
7914
8074
  const items = /* @__PURE__ */ new Map();
7915
- for (const index of row === null ? [] : layout.indexed) for (const eq of indexEntries(layout.table, index, row)) {
8075
+ for (const index of row === null ? [] : indexes) for (const eq of indexEntries(layout.table, index, row)) {
7916
8076
  const pk = partition(layout, index, eq);
7917
8077
  const sk = index.unique ? ONLY : encodeKvKey(indexOrderTuple(layout.table, index, row)) || ONLY;
7918
8078
  items.set(JSON.stringify([pk, sk]), {
@@ -8053,6 +8213,69 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
8053
8213
  lte: lt.endsWith(SEPARATOR) ? lt.slice(0, -1) : lt
8054
8214
  };
8055
8215
  };
8216
+ const fillOps = (layout, index, row) => [{
8217
+ type: "check",
8218
+ key: rowItem(layout, rowKey(layout.table, row)),
8219
+ condition: { v: Number(row["_v"]) }
8220
+ }, ...[...itemsOf(layout, row, [index]).values()].map(({ key }) => ({
8221
+ type: "put",
8222
+ key,
8223
+ value: copyOf(layout, row),
8224
+ ...stamp(layout.table, row)
8225
+ }))];
8226
+ const fillRow = async (layout, index, first) => {
8227
+ const key = rowItem(layout, rowKey(layout.table, first));
8228
+ let row = first;
8229
+ for (let attempt = 0; row !== null; attempt += 1) {
8230
+ if (attempt === 8) throw new Error(`${layout.table.name}.${index.name}: a row kept changing while its index items were written; run the migration again.`);
8231
+ if ((await store.write(fillOps(layout, index, row))).ok) return;
8232
+ [row] = await store.get([key]);
8233
+ }
8234
+ };
8235
+ const fillIndex = async (table, name, { dryRun = false } = {}) => {
8236
+ const layout = layoutOf(table);
8237
+ const index = layout.indexed.find((candidate) => candidate.name === name);
8238
+ if (index === void 0) return 0;
8239
+ if (index.unique) throw new DatabaseAdapterContractError(`${table.name}.${name} is unique: its items can't be written for rows stored before it, since two of them may hold one value.`);
8240
+ const { items: most, bytes } = store.limits;
8241
+ let lacking = 0;
8242
+ for (let after;;) {
8243
+ const page = await store.query({
8244
+ pk: layout.rows,
8245
+ order: "asc",
8246
+ limit: 100,
8247
+ after
8248
+ });
8249
+ const rows = page.items.map(({ value }) => value);
8250
+ const keys = rows.map((row) => [...itemsOf(layout, row, [index]).values()].map(({ key }) => key));
8251
+ const wanted = keys.flat();
8252
+ const found = wanted.length === 0 ? [] : await store.get(wanted);
8253
+ let at = 0;
8254
+ const missing = rows.filter((_, position) => {
8255
+ return found.slice(at, at += keys[position].length).some((item) => item === null);
8256
+ });
8257
+ lacking += missing.length;
8258
+ if (!dryRun) {
8259
+ let chunk = [];
8260
+ let ops = [];
8261
+ const flush = async () => {
8262
+ if (ops.length > 0 && !(await store.write(ops)).ok) for (const row of chunk) await fillRow(layout, index, row);
8263
+ chunk = [];
8264
+ ops = [];
8265
+ };
8266
+ for (const row of missing) {
8267
+ const next = fillOps(layout, index, row);
8268
+ const size = (list) => list.reduce((sum, op) => sum + encoder.encode(op.key.pk + op.key.sk + JSON.stringify(op.type === "put" ? op.value : null)).length, 0);
8269
+ if (chunk.length > 0 && (ops.length + next.length > most || size(ops) + size(next) > bytes)) await flush();
8270
+ chunk.push(row);
8271
+ ops.push(...next);
8272
+ }
8273
+ await flush();
8274
+ }
8275
+ if (!page.more || page.items.length === 0) return lacking;
8276
+ after = page.items.at(-1).sk;
8277
+ }
8278
+ };
8056
8279
  return {
8057
8280
  id: store.id,
8058
8281
  fits(ops) {
@@ -8112,13 +8335,16 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
8112
8335
  const layout = layoutOf(table);
8113
8336
  return store.deleteConsumed(rows.flatMap((row) => [rowItem(layout, rowKey(table, row)), ...[...itemsOf(layout, row).values()].map(({ key }) => key)]));
8114
8337
  } },
8115
- migrations: { apply: async () => store.migrations?.apply() },
8338
+ migrations: {
8339
+ apply: async () => store.migrations?.apply(),
8340
+ fillIndex
8341
+ },
8116
8342
  ...store.dispose === void 0 ? {} : { dispose: () => store.dispose() }
8117
8343
  };
8118
8344
  };
8119
8345
  //#endregion
8120
8346
  //#region ../../packages/server/dist/version.mjs
8121
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.5";
8347
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.50";
8122
8348
  //#endregion
8123
8349
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
8124
8350
  const createVersionRouteHandlers = (plugins = []) => {
@@ -8244,9 +8470,14 @@ const releaseCatalogScopeKeyOf = (input) => input.strategy === "APP_VERSION" ? c
8244
8470
  platform: input.platform,
8245
8471
  strategy: "FINGERPRINT"
8246
8472
  });
8247
- const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
8248
- if (row === null || row.platform !== input.platform || row.strategy !== input.strategy || row.channel_key !== input.channelKey || row.scope_key !== scopeKey || row.fingerprint_hash !== (input.strategy === "FINGERPRINT" ? input.fingerprintHash : null)) return null;
8249
- const compiled = parseCompiledCatalog(row.payload, input.strategy);
8473
+ const parseReleaseCatalogRow = ({ payload, ...row }) => ({
8474
+ row,
8475
+ compiled: parseCompiledCatalog(payload, row.strategy)
8476
+ });
8477
+ const projectParsedReleaseCatalogRow = (parsed, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
8478
+ if (parsed === null) return null;
8479
+ const { row, compiled } = parsed;
8480
+ if (row.platform !== input.platform || row.strategy !== input.strategy || row.channel_key !== input.channelKey || row.scope_key !== scopeKey || row.fingerprint_hash !== (input.strategy === "FINGERPRINT" ? input.fingerprintHash : null)) return null;
8250
8481
  const appVersion = input.strategy === "APP_VERSION" ? input.appVersion : void 0;
8251
8482
  return {
8252
8483
  catalogId: row.catalog_id,
@@ -8259,6 +8490,7 @@ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyO
8259
8490
  scopeKey
8260
8491
  };
8261
8492
  };
8493
+ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => projectParsedReleaseCatalogRow(row === null ? null : parseReleaseCatalogRow(row), input, scopeKey);
8262
8494
  //#endregion
8263
8495
  //#region ../../packages/server/dist/db/updateArtifacts.mjs
8264
8496
  const HBC_ASSET_PATH_RE = /\.bundle$/;
@@ -8851,8 +9083,8 @@ const baseBundleIdsOf = (row, range, bundleId, limit) => {
8851
9083
  //#endregion
8852
9084
  //#region ../../packages/server/dist/core/reads.mjs
8853
9085
  const PAGE$3 = 500;
8854
- const pick$1 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
8855
- const toBundleRow = pick$1([
9086
+ const pick$2 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
9087
+ const toBundleRow = pick$2([
8856
9088
  "id",
8857
9089
  "platform",
8858
9090
  "git_commit_hash",
@@ -8861,7 +9093,7 @@ const toBundleRow = pick$1([
8861
9093
  "manifest_file_hash",
8862
9094
  "asset_base_storage_uri"
8863
9095
  ]);
8864
- const toPatchRow = pick$1([
9096
+ const toPatchRow = pick$2([
8865
9097
  "id",
8866
9098
  "bundle_id",
8867
9099
  "base_bundle_id",
@@ -8871,7 +9103,7 @@ const toPatchRow = pick$1([
8871
9103
  "byte_size",
8872
9104
  "order_index"
8873
9105
  ]);
8874
- const toReleaseRow = pick$1([
9106
+ const toReleaseRow = pick$2([
8875
9107
  "id",
8876
9108
  "revision",
8877
9109
  "scope_key",
@@ -8892,7 +9124,7 @@ const toReleaseRow = pick$1([
8892
9124
  "created_at_ms",
8893
9125
  "updated_at_ms"
8894
9126
  ]);
8895
- const toCatalogRow = pick$1([
9127
+ const toCatalogRow = pick$2([
8896
9128
  "scope_key",
8897
9129
  "catalog_id",
8898
9130
  "strategy",
@@ -8907,7 +9139,7 @@ const toCatalogRow = pick$1([
8907
9139
  "is_tombstone",
8908
9140
  "updated_at_ms"
8909
9141
  ]);
8910
- const toChannelRow = pick$1(["id", "name"]);
9142
+ const toChannelRow = pick$2(["id", "name"]);
8911
9143
  const drain$1 = async (read) => {
8912
9144
  const rows = [];
8913
9145
  let cursor;
@@ -8918,7 +9150,14 @@ const drain$1 = async (read) => {
8918
9150
  } while (cursor !== void 0);
8919
9151
  return rows;
8920
9152
  };
8921
- const after = (input) => input.after === void 0 ? {} : { range: (input.order ?? "asc") === "asc" ? { gt: input.after } : { lt: input.after } };
9153
+ const after = (input) => {
9154
+ const asc = (input.order ?? "asc") === "asc";
9155
+ const range = {
9156
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
9157
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
9158
+ };
9159
+ return Object.keys(range).length === 0 ? {} : { range };
9160
+ };
8922
9161
  const createCoreReads = (db, storage) => {
8923
9162
  const detail = async (row) => {
8924
9163
  const count = row._refs_bundle_patches_bundle_id ?? 0;
@@ -9094,7 +9333,29 @@ const createCoreReads = (db, storage) => {
9094
9333
  ...after(input)
9095
9334
  })).rows.map(toCatalogRow);
9096
9335
  },
9097
- async listChannels() {
9336
+ async listReleaseScopeKeys(input) {
9337
+ const scopeKeys = [];
9338
+ for (let last = input.after ?? ""; scopeKeys.length < input.limit;) {
9339
+ const { rows } = await db.findMany("releases", {
9340
+ index: "scopes",
9341
+ where: {},
9342
+ limit: 1,
9343
+ range: { gt: last }
9344
+ });
9345
+ if (rows[0] === void 0) break;
9346
+ last = rows[0].scope_key;
9347
+ scopeKeys.push(last);
9348
+ }
9349
+ return scopeKeys;
9350
+ },
9351
+ async listChannels(input) {
9352
+ if (input !== void 0) return (await db.findMany("channels", {
9353
+ index: "all",
9354
+ where: {},
9355
+ order: input.order ?? "asc",
9356
+ limit: input.limit,
9357
+ ...after(input)
9358
+ })).rows.map(toChannelRow);
9098
9359
  return (await drain$1((page) => db.findMany("channels", {
9099
9360
  index: "all",
9100
9361
  where: {},
@@ -9102,6 +9363,11 @@ const createCoreReads = (db, storage) => {
9102
9363
  ...page
9103
9364
  }))).map(toChannelRow);
9104
9365
  },
9366
+ async getChannels(ids) {
9367
+ const unique = [...new Set(ids)];
9368
+ if (unique.length === 0) return [];
9369
+ return (await db.findByKeys("channels", unique.map((id) => ({ id })))).flatMap((row) => row ? [toChannelRow(row)] : []);
9370
+ },
9105
9371
  async findChannelByName(name) {
9106
9372
  const row = await db.findOne("channels", { name });
9107
9373
  return row === null ? null : toChannelRow(row);
@@ -9109,6 +9375,289 @@ const createCoreReads = (db, storage) => {
9109
9375
  };
9110
9376
  };
9111
9377
  //#endregion
9378
+ //#region ../../packages/server/dist/core/iosDevices.mjs
9379
+ const UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
9380
+ const normalizeIosUdid = (value) => {
9381
+ const trimmed = value.trim();
9382
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
9383
+ };
9384
+ const NAME_MAX_LENGTH = 100;
9385
+ const EMAIL_MAX_LENGTH = 320;
9386
+ const ISSUER_MAX_LENGTH = 64;
9387
+ const ACCOUNT_ROW = "registry";
9388
+ const ERROR_MAX_LENGTH = 512;
9389
+ const STATUSES = [
9390
+ "pending",
9391
+ "approved",
9392
+ "registered"
9393
+ ];
9394
+ const OUTCOMES = [
9395
+ "registered",
9396
+ "refused",
9397
+ "disabled",
9398
+ "missing"
9399
+ ];
9400
+ const IOS_DEVICE_DISABLED_ERROR = "Disabled in the Apple account.";
9401
+ const IOS_DEVICE_MISSING_ERROR = "Gone from the Apple account. Approve it again to register it.";
9402
+ var IosDeviceInputError = class extends TypeError {
9403
+ name = "IosDeviceInputError";
9404
+ };
9405
+ const pick$1 = (row) => ({
9406
+ id: row.id,
9407
+ udid: row.udid,
9408
+ name: row.name,
9409
+ status: row.status,
9410
+ requested_by: row.requested_by ?? null,
9411
+ created_at_ms: row.created_at_ms,
9412
+ approved_by: row.approved_by ?? null,
9413
+ approved_at_ms: row.approved_at_ms ?? null,
9414
+ registered_at_ms: row.registered_at_ms ?? null,
9415
+ apple_issuer_id: row.apple_issuer_id ?? null,
9416
+ apple_error: row.apple_error ?? null,
9417
+ build_id: row.build_id ?? null
9418
+ });
9419
+ const udidOf = (udid) => {
9420
+ const key = typeof udid === "string" ? normalizeIosUdid(udid) : null;
9421
+ if (key === null) throw new IosDeviceInputError("Invalid iOS device: udid must be 40 hex digits, or 8 and 16 joined by a hyphen.");
9422
+ return key;
9423
+ };
9424
+ const nameOf = (name) => {
9425
+ const trimmed = typeof name === "string" ? name.trim() : "";
9426
+ if (trimmed.length === 0 || trimmed.length > NAME_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: name must be 1 to ${NAME_MAX_LENGTH} characters.`);
9427
+ return trimmed;
9428
+ };
9429
+ const personOf = (value, field) => {
9430
+ if (value === null) return null;
9431
+ const email = typeof value === "string" ? value.trim().toLowerCase() : "";
9432
+ 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.`);
9433
+ return email;
9434
+ };
9435
+ const errorText = (text) => {
9436
+ const line = text.replace(/\s+/gu, " ").trim();
9437
+ return line.length > ERROR_MAX_LENGTH ? `${line.slice(0, 511)}…` : line;
9438
+ };
9439
+ const createIosDeviceApi = (db, { now = Date.now } = {}) => {
9440
+ const findIosDevice = async (udid) => {
9441
+ const key = normalizeIosUdid(udid);
9442
+ if (key === null) return null;
9443
+ const row = await db.findOne("ios_devices", { udid: key });
9444
+ return row === null ? null : pick$1(row);
9445
+ };
9446
+ const accountOfRows = async () => {
9447
+ const { rows } = await db.findMany("ios_devices", {
9448
+ index: "byRegistration",
9449
+ where: {},
9450
+ order: "asc",
9451
+ limit: 1,
9452
+ range: { gte: 0 }
9453
+ });
9454
+ return (rows[0] === void 0 ? null : pick$1(rows[0]))?.apple_issuer_id ?? null;
9455
+ };
9456
+ return {
9457
+ async listIosDevices(input) {
9458
+ if (input.status !== void 0 && !STATUSES.includes(input.status)) throw new IosDeviceInputError(`Invalid iOS device status: ${String(input.status)}. Expected ${STATUSES.join(", ")}.`);
9459
+ const page = {
9460
+ order: input.order ?? "asc",
9461
+ limit: input.limit,
9462
+ ...after(input)
9463
+ };
9464
+ const { rows } = input.status === void 0 ? await db.findMany("ios_devices", {
9465
+ index: "all",
9466
+ where: {},
9467
+ ...page
9468
+ }) : await db.findMany("ios_devices", {
9469
+ index: "byStatus",
9470
+ where: { status: input.status },
9471
+ ...page
9472
+ });
9473
+ return rows.map(pick$1);
9474
+ },
9475
+ findIosDevice,
9476
+ async requestIosDevice(input) {
9477
+ const udid = udidOf(input.udid);
9478
+ const name = nameOf(input.name);
9479
+ const requestedBy = personOf(input.requestedBy, "requestedBy");
9480
+ const existing = await db.findOne("ios_devices", { udid });
9481
+ if (existing !== null) return {
9482
+ device: pick$1(existing),
9483
+ created: false
9484
+ };
9485
+ const device = {
9486
+ id: createUUIDv7(),
9487
+ udid,
9488
+ name,
9489
+ status: "pending",
9490
+ requested_by: requestedBy,
9491
+ created_at_ms: now(),
9492
+ approved_by: null,
9493
+ approved_at_ms: null,
9494
+ registered_at_ms: null,
9495
+ apple_issuer_id: null,
9496
+ apple_error: null,
9497
+ build_id: null
9498
+ };
9499
+ try {
9500
+ await db.transaction(async (tx) => {
9501
+ tx.create("ios_devices", device);
9502
+ });
9503
+ } catch (error) {
9504
+ if (error instanceof DatabaseConstraintError && error.reason === "unique") {
9505
+ const winner = await db.findOne("ios_devices", { udid });
9506
+ if (winner !== null) return {
9507
+ device: pick$1(winner),
9508
+ created: false
9509
+ };
9510
+ }
9511
+ throw error;
9512
+ }
9513
+ return {
9514
+ device,
9515
+ created: true
9516
+ };
9517
+ },
9518
+ async approveIosDevice(id, input) {
9519
+ const name = input.name === void 0 ? void 0 : nameOf(input.name);
9520
+ const approvedBy = personOf(input.approvedBy, "approvedBy");
9521
+ return db.transaction(async (tx) => {
9522
+ const row = await tx.findOne("ios_devices", { id });
9523
+ if (row === null) return null;
9524
+ const device = pick$1(row);
9525
+ const set = {
9526
+ ...name === void 0 || name === device.name ? {} : { name },
9527
+ ...device.status === "pending" ? {
9528
+ status: "approved",
9529
+ approved_by: approvedBy,
9530
+ approved_at_ms: now()
9531
+ } : {}
9532
+ };
9533
+ if (Object.keys(set).length === 0) return device;
9534
+ tx.update("ios_devices", row, set);
9535
+ return {
9536
+ ...device,
9537
+ ...set
9538
+ };
9539
+ });
9540
+ },
9541
+ async renameIosDevice(id, input) {
9542
+ const name = nameOf(input);
9543
+ return db.transaction(async (tx) => {
9544
+ const row = await tx.findOne("ios_devices", { id });
9545
+ if (row === null) return null;
9546
+ const device = pick$1(row);
9547
+ if (device.name === name) return device;
9548
+ tx.update("ios_devices", row, { name });
9549
+ return {
9550
+ ...device,
9551
+ name
9552
+ };
9553
+ });
9554
+ },
9555
+ async recordIosDeviceOutcome({ id, seen, issuerId, outcome, reason }) {
9556
+ if (!OUTCOMES.includes(outcome)) throw new IosDeviceInputError(`Invalid iOS device outcome: ${String(outcome)}. Expected ${OUTCOMES.join(", ")}.`);
9557
+ 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.`);
9558
+ return db.transaction(async (tx) => {
9559
+ const row = await tx.findOne("ios_devices", { id });
9560
+ if (row === null) return null;
9561
+ const device = pick$1(row);
9562
+ if (device.status !== seen.status || device.approved_at_ms !== seen.approvedAtMs || device.apple_issuer_id !== null && device.apple_issuer_id !== issuerId) return null;
9563
+ let set;
9564
+ switch (outcome) {
9565
+ case "registered":
9566
+ if (device.status === "pending") return null;
9567
+ set = {
9568
+ status: "registered",
9569
+ registered_at_ms: device.registered_at_ms ?? now(),
9570
+ apple_issuer_id: issuerId,
9571
+ apple_error: null
9572
+ };
9573
+ break;
9574
+ case "refused":
9575
+ if (device.status !== "approved") return null;
9576
+ set = { apple_error: errorText(reason === void 0 || reason.trim() === "" ? "Apple refused it." : reason) };
9577
+ break;
9578
+ case "disabled":
9579
+ if (device.status === "pending") return null;
9580
+ set = { apple_error: IOS_DEVICE_DISABLED_ERROR };
9581
+ break;
9582
+ case "missing":
9583
+ if (device.status !== "registered") return null;
9584
+ set = {
9585
+ status: "pending",
9586
+ approved_by: null,
9587
+ approved_at_ms: null,
9588
+ apple_error: IOS_DEVICE_MISSING_ERROR
9589
+ };
9590
+ }
9591
+ if (Object.entries(set).some(([column, value]) => device[column] !== (value ?? null))) tx.update("ios_devices", row, set);
9592
+ return {
9593
+ ...device,
9594
+ ...set
9595
+ };
9596
+ });
9597
+ },
9598
+ async markIosDevicesInBuild({ buildId, ids }) {
9599
+ for (const id of new Set(ids)) await db.transaction(async (tx) => {
9600
+ const row = await tx.findOne("ios_devices", { id });
9601
+ if (row === null || typeof row.build_id === "string" && row.build_id >= buildId) return;
9602
+ tx.update("ios_devices", row, { build_id: buildId });
9603
+ });
9604
+ },
9605
+ async findIosDeviceAccount() {
9606
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
9607
+ const issuerId = existing === null ? await accountOfRows() : existing.apple_issuer_id;
9608
+ return issuerId === null ? null : { issuerId };
9609
+ },
9610
+ async claimIosDeviceAccount(issuerId) {
9611
+ 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.`);
9612
+ const answer = (held) => ({
9613
+ issuerId: held,
9614
+ claimed: held === issuerId
9615
+ });
9616
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
9617
+ if (existing !== null) return answer(existing.apple_issuer_id);
9618
+ const holder = await accountOfRows() ?? issuerId;
9619
+ try {
9620
+ await db.transaction(async (tx) => {
9621
+ tx.create("ios_device_account", {
9622
+ id: ACCOUNT_ROW,
9623
+ apple_issuer_id: holder,
9624
+ claimed_at_ms: now()
9625
+ });
9626
+ });
9627
+ return answer(holder);
9628
+ } catch (error) {
9629
+ if (error instanceof DatabaseConstraintError && (error.reason === "exists" || error.reason === "unique")) {
9630
+ const winner = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
9631
+ if (winner !== null) return answer(winner.apple_issuer_id);
9632
+ }
9633
+ throw error;
9634
+ }
9635
+ },
9636
+ async deleteIosDevice(id, only) {
9637
+ const requestedBy = only?.requestedBy === void 0 ? void 0 : personOf(only.requestedBy, "requestedBy");
9638
+ return db.transaction(async (tx) => {
9639
+ const row = await tx.findOne("ios_devices", { id });
9640
+ if (row === null) return null;
9641
+ const device = pick$1(row);
9642
+ if (only?.status !== void 0 && device.status !== only.status || requestedBy !== void 0 && device.requested_by !== requestedBy) return null;
9643
+ await tx.delete("ios_devices", row);
9644
+ return device;
9645
+ });
9646
+ }
9647
+ };
9648
+ };
9649
+ //#endregion
9650
+ //#region ../../packages/server/dist/core/nativeBuildDestinations.mjs
9651
+ const NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
9652
+ android: [
9653
+ "play-internal",
9654
+ "play-closed",
9655
+ "play-open",
9656
+ "play-production"
9657
+ ],
9658
+ ios: ["testflight"]
9659
+ };
9660
+ //#endregion
9112
9661
  //#region ../../packages/server/dist/core/writes.mjs
9113
9662
  const PAGE$2 = 500;
9114
9663
  const countBundle = (tx, platform, delta) => {
@@ -9129,7 +9678,7 @@ const deleteBundle = async (tx, current) => {
9129
9678
  await tx.delete("bundles", current);
9130
9679
  countBundle(tx, current.platform, -1);
9131
9680
  };
9132
- const replaceBundlePatches = async (tx, bundle, rows) => {
9681
+ const replaceBundlePatches = async (tx, bundle, rows, checkNew) => {
9133
9682
  const wanted = new Map(rows.map((row) => [row.id, row]));
9134
9683
  const count = bundle._refs_bundle_patches_bundle_id ?? 0;
9135
9684
  let cursor;
@@ -9154,6 +9703,7 @@ const replaceBundlePatches = async (tx, bundle, rows) => {
9154
9703
  if (page.next === void 0) break;
9155
9704
  cursor = page.next;
9156
9705
  }
9706
+ if (checkNew !== void 0) for (const row of wanted.values()) await checkNew(row);
9157
9707
  for (const row of wanted.values()) tx.create("bundle_patches", row);
9158
9708
  };
9159
9709
  const insertChannel = async (db, row) => {
@@ -9206,6 +9756,16 @@ const ARTIFACT_KINDS = {
9206
9756
  const SCOPE_KEY_MAX_LENGTH = 2048;
9207
9757
  const GIT_COMMIT_HASH_MAX_LENGTH = 255;
9208
9758
  const BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
9759
+ const SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
9760
+ const URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
9761
+ const APP_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;
9762
+ const FINGERPRINT_HASH = /^[A-Za-z0-9._~-]{1,255}$/;
9763
+ const DISTRIBUTIONS = {
9764
+ apk: ["direct"],
9765
+ app: ["direct"],
9766
+ aab: ["store"],
9767
+ ipa: ["direct", "store"]
9768
+ };
9209
9769
  var NativeBuildInputError = class extends TypeError {
9210
9770
  name = "NativeBuildInputError";
9211
9771
  };
@@ -9226,15 +9786,42 @@ const pick = (row) => ({
9226
9786
  build_number: row.build_number ?? null,
9227
9787
  submitted_to: row.submitted_to ?? null,
9228
9788
  submitted_at_ms: row.submitted_at_ms ?? null,
9229
- submitted_version: row.submitted_version ?? null
9789
+ submitted_version: row.submitted_version ?? null,
9790
+ is_store_build: row.is_store_build === true,
9791
+ is_sandbox: row.is_sandbox === true,
9792
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
9793
+ export_method: row.export_method ?? null,
9794
+ native_app_version: row.native_app_version ?? null
9230
9795
  });
9231
- const SUBMISSION_DESTINATIONS = {
9232
- android: "play-internal",
9233
- ios: "testflight"
9234
- };
9796
+ const EXPORT_METHODS = /* @__PURE__ */ new Set([
9797
+ "app-store",
9798
+ "ad-hoc",
9799
+ "development",
9800
+ "enterprise"
9801
+ ]);
9802
+ const OLDER_BUILDS_PAGE = 20;
9803
+ const OLDER_BUILDS_PAGES = 5;
9804
+ const MARK_ATTEMPTS = 8;
9235
9805
  const BUILD_NUMBER_MAX_LENGTH = 64;
9236
9806
  const SUBMITTED_VERSION_MAX_LENGTH = 255;
9807
+ const checkedScopeKey = (scopeKey) => {
9808
+ 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.`);
9809
+ return scopeKey;
9810
+ };
9811
+ const registeredDistribution = (kind, exportMethod) => kind !== "ipa" ? DISTRIBUTIONS[kind][0] : exportMethod === void 0 || exportMethod === null ? "unknown" : exportMethod === "app-store" ? "store" : "direct";
9812
+ const sandboxScopeKey = (scope, sandbox) => {
9813
+ const { appId, urlScheme, artifactKind, distribution } = sandbox;
9814
+ 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;
9815
+ if (problem !== null) throw new NativeBuildInputError(`Invalid sandbox build scope: ${problem}.`);
9816
+ const target = scope.fingerprintHash === null ? `app-version:${encodeURIComponent(scope.appVersion)}` : `fingerprint:${scope.fingerprintHash}`;
9817
+ return checkedScopeKey(`v1:sandbox:${scope.platform}:${appId}:${urlScheme}:${artifactKind}:${distribution}:${target}`);
9818
+ };
9237
9819
  const nativeBuildScopeKey = (scope) => {
9820
+ const { sandbox } = scope;
9821
+ if (sandbox !== void 0 && sandbox !== null) {
9822
+ if (sandbox.distribution !== "direct" && sandbox.distribution !== "store") throw new NativeBuildInputError("Invalid sandbox build scope: its distribution must be direct or store.");
9823
+ return sandboxScopeKey(scope, sandbox);
9824
+ }
9238
9825
  let scopeKey;
9239
9826
  try {
9240
9827
  const channelKey = encodeChannelKey(scope.channel);
@@ -9251,30 +9838,102 @@ const nativeBuildScopeKey = (scope) => {
9251
9838
  } catch (error) {
9252
9839
  throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
9253
9840
  }
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;
9841
+ return checkedScopeKey(scopeKey);
9842
+ };
9843
+ const channelIdOf = (channel) => {
9844
+ try {
9845
+ return `channel:${encodeChannelKey(channel)}`;
9846
+ } catch (error) {
9847
+ throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
9848
+ }
9849
+ };
9850
+ const registrationScopeKey = (registration) => {
9851
+ channelIdOf(registration.channel);
9852
+ return registration.isSandbox === true ? sandboxScopeKey(registration, {
9853
+ appId: registration.sandboxAppId,
9854
+ urlScheme: registration.sandboxUrlScheme,
9855
+ artifactKind: registration.artifact.kind,
9856
+ distribution: registeredDistribution(registration.artifact.kind, registration.exportMethod)
9857
+ }) : nativeBuildScopeKey({
9858
+ ...registration,
9859
+ sandbox: null
9860
+ });
9861
+ };
9862
+ const refuseSandboxPatchBase = async (db, baseBundleId) => {
9863
+ 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
9864
  };
9257
9865
  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 }) => {
9866
+ const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, sandboxAppId, exportMethod, nativeAppVersion, artifact }) => {
9259
9867
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
9260
9868
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
9261
9869
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
9262
9870
  if (channel.trim().length === 0) return "channel is required";
9871
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
9872
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
9873
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
9874
+ 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`;
9875
+ }
9876
+ if (sandboxAppId !== void 0 && sandboxAppId !== null) {
9877
+ if (isSandbox !== true) return "sandboxAppId is a sandbox build's, and this isn't one";
9878
+ if (typeof sandboxAppId !== "string" || !APP_ID.test(sandboxAppId)) return "sandboxAppId must be the artifact's bundle identifier or application ID, up to 255 characters";
9879
+ }
9880
+ if (isSandbox === true) {
9881
+ if (sandboxUrlScheme === void 0 || sandboxUrlScheme === null) return "a sandbox build needs the sandboxUrlScheme its artifact registers";
9882
+ 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";
9883
+ }
9263
9884
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
9264
9885
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
9265
9886
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
9266
9887
  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`;
9888
+ 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
9889
  const kinds = ARTIFACT_KINDS[platform];
9268
9890
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
9891
+ if (exportMethod !== void 0 && exportMethod !== null) {
9892
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
9893
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
9894
+ }
9269
9895
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
9270
9896
  return null;
9271
9897
  };
9898
+ const SIBLING_KINDS = {
9899
+ app: "ipa",
9900
+ ipa: "app"
9901
+ };
9902
+ const isInstallTarget = (build) => !build.is_store_build && build.submitted_to === null && (build.artifact_kind === "app" || build.artifact_kind === "ipa" && build.export_method !== null && build.export_method !== "app-store");
9903
+ const siblingSandboxScopeKey = (build, artifactKind) => {
9904
+ const [version, sandbox, platform, appId, urlScheme] = build.scope_key.split(":");
9905
+ if (version !== "v1" || sandbox !== "sandbox" || platform !== build.platform || appId === void 0 || urlScheme === void 0) return null;
9906
+ const target = build.fingerprint_hash === null ? {
9907
+ platform: build.platform,
9908
+ fingerprintHash: null,
9909
+ appVersion: build.app_version ?? ""
9910
+ } : {
9911
+ platform: build.platform,
9912
+ fingerprintHash: build.fingerprint_hash,
9913
+ appVersion: null
9914
+ };
9915
+ try {
9916
+ return sandboxScopeKey(target, {
9917
+ appId,
9918
+ urlScheme,
9919
+ artifactKind: build.artifact_kind,
9920
+ distribution: registeredDistribution(build.artifact_kind, build.export_method)
9921
+ }) === build.scope_key ? sandboxScopeKey(target, {
9922
+ appId,
9923
+ urlScheme,
9924
+ artifactKind,
9925
+ distribution: "direct"
9926
+ }) : null;
9927
+ } catch {
9928
+ return null;
9929
+ }
9930
+ };
9272
9931
  const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9273
9932
  async registerNativeBuild(registration) {
9274
9933
  const problem = problemOf(registration);
9275
9934
  if (problem !== null) throw new NativeBuildInputError(`Invalid native build: ${problem}.`);
9276
- const scopeKey = nativeBuildScopeKey(registration);
9277
- const channelId = `channel:${encodeChannelKey(registration.channel)}`;
9935
+ const scopeKey = registrationScopeKey(registration);
9936
+ const channelId = channelIdOf(registration.channel);
9278
9937
  const { embeddedBundle } = registration;
9279
9938
  const row = {
9280
9939
  id: registration.id,
@@ -9293,7 +9952,12 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9293
9952
  build_number: registration.buildNumber ?? null,
9294
9953
  submitted_to: null,
9295
9954
  submitted_at_ms: null,
9296
- submitted_version: null
9955
+ submitted_version: null,
9956
+ is_store_build: false,
9957
+ is_sandbox: registration.isSandbox === true,
9958
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
9959
+ export_method: registration.exportMethod ?? null,
9960
+ native_app_version: registration.nativeAppVersion ?? null
9297
9961
  };
9298
9962
  for (let attempt = 1;; attempt += 1) {
9299
9963
  await insertChannel(db, {
@@ -9327,25 +9991,82 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9327
9991
  const row = await db.findOne("native_builds", { id });
9328
9992
  return row === null ? null : pick(row);
9329
9993
  },
9994
+ async findNativeBuildByBuiltInBundle(bundleId) {
9995
+ const row = await db.findOne("native_builds", { min_bundle_id: bundleId });
9996
+ return row === null ? null : pick(row);
9997
+ },
9330
9998
  async findNativeBuild(scope, options) {
9331
9999
  const scopeKey = nativeBuildScopeKey(scope);
9332
10000
  const buildKey = options?.buildKey;
9333
10001
  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", {
10002
+ const artifactKind = options?.artifactKind;
10003
+ if (artifactKind !== void 0 && !ARTIFACT_KINDS[scope.platform].includes(artifactKind)) throw new NativeBuildInputError(`Invalid native build kind: an ${scope.platform} build is ${ARTIFACT_KINDS[scope.platform].join(" or ")}.`);
10004
+ const ofKind = (row) => artifactKind === void 0 || row.artifact_kind === artifactKind;
10005
+ if (options?.storeBuild) {
10006
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
10007
+ return marked === null || !ofKind(marked) ? null : pick(marked);
10008
+ }
10009
+ const read = (limit, before) => {
10010
+ const page = {
10011
+ order: "desc",
10012
+ limit,
10013
+ ...before === void 0 ? {} : { range: { lt: before } }
10014
+ };
10015
+ return buildKey !== void 0 ? db.findMany("native_builds", {
10016
+ index: "byBuildKey",
10017
+ where: {
10018
+ scope_key: scopeKey,
10019
+ build_key: buildKey
10020
+ },
10021
+ ...page
10022
+ }) : artifactKind !== void 0 ? db.findMany("native_builds", {
10023
+ index: "byScopeKind",
10024
+ where: {
10025
+ scope_key: scopeKey,
10026
+ artifact_kind: artifactKind
10027
+ },
10028
+ ...page
10029
+ }) : db.findMany("native_builds", {
10030
+ index: "byScope",
10031
+ where: { scope_key: scopeKey },
10032
+ ...page
10033
+ });
10034
+ };
10035
+ const bundleId = options?.builtInOlderThan;
10036
+ if (bundleId !== void 0 && scope.sandbox !== void 0 && scope.sandbox !== null) return null;
10037
+ const { rows } = await read(1);
10038
+ const newest = (rows[0] === void 0 ? void 0 : pick(rows[0])) ?? (artifactKind !== void 0 && buildKey === void 0 ? await db.findMany("native_builds", {
9335
10039
  index: "byScope",
9336
10040
  where: { scope_key: scopeKey },
9337
10041
  order: "desc",
9338
10042
  limit: 1
9339
- }) : await db.findMany("native_builds", {
9340
- index: "byBuildKey",
9341
- where: {
9342
- scope_key: scopeKey,
9343
- build_key: buildKey
9344
- },
10043
+ }).then(({ rows: [row] }) => row?.artifact_kind === artifactKind ? pick(row) : void 0) : void 0);
10044
+ if (newest === void 0 || !ofKind(newest)) return null;
10045
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return newest;
10046
+ let before = newest.id;
10047
+ for (let page = 0; page < OLDER_BUILDS_PAGES; page += 1) {
10048
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
10049
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
10050
+ if (usable !== void 0) return ofKind(usable) ? pick(usable) : null;
10051
+ const last = older.at(-1);
10052
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
10053
+ before = last.id;
10054
+ }
10055
+ return null;
10056
+ },
10057
+ async findNativeBuildSibling(build) {
10058
+ const artifactKind = SIBLING_KINDS[build.artifact_kind];
10059
+ if (build.platform !== "ios" || !build.is_sandbox || artifactKind === void 0 || !isInstallTarget(build)) return null;
10060
+ const scopeKey = siblingSandboxScopeKey(build, artifactKind);
10061
+ if (scopeKey === null) return null;
10062
+ const { rows } = await db.findMany("native_builds", {
10063
+ index: "byScope",
10064
+ where: { scope_key: scopeKey },
9345
10065
  order: "desc",
9346
10066
  limit: 1
9347
10067
  });
9348
- return rows[0] === void 0 ? null : pick(rows[0]);
10068
+ const sibling = rows[0] === void 0 ? null : pick(rows[0]);
10069
+ return sibling !== null && isInstallTarget(sibling) ? sibling : null;
9349
10070
  },
9350
10071
  async recordNativeBuildSubmission(id, { destination, version }) {
9351
10072
  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 +10074,8 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9353
10074
  const row = await tx.findOne("native_builds", { id });
9354
10075
  if (row === null) return null;
9355
10076
  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}.`);
10077
+ 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}.`);
10078
+ 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
10079
  const set = {
9358
10080
  submitted_to: destination,
9359
10081
  submitted_at_ms: now(),
@@ -9366,6 +10088,46 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
9366
10088
  };
9367
10089
  });
9368
10090
  },
10091
+ async markNativeBuild(id, { storeBuild }) {
10092
+ for (let attempt = 1;; attempt += 1) try {
10093
+ return await db.transaction(async (tx) => {
10094
+ const row = await tx.findOne("native_builds", { id });
10095
+ if (row === null) return null;
10096
+ const build = pick(row);
10097
+ if (!storeBuild) {
10098
+ if (build.is_store_build) tx.update("native_builds", row, { is_store_build: false });
10099
+ return {
10100
+ nativeBuild: {
10101
+ ...build,
10102
+ is_store_build: false
10103
+ },
10104
+ previous: null
10105
+ };
10106
+ }
10107
+ if (build.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
10108
+ if (build.is_store_build) return {
10109
+ nativeBuild: build,
10110
+ previous: null
10111
+ };
10112
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build.scope_key });
10113
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
10114
+ tx.update("native_builds", row, { is_store_build: true });
10115
+ return {
10116
+ nativeBuild: {
10117
+ ...build,
10118
+ is_store_build: true
10119
+ },
10120
+ previous: holder === null ? null : {
10121
+ ...pick(holder),
10122
+ is_store_build: false
10123
+ }
10124
+ };
10125
+ });
10126
+ } catch (error) {
10127
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
10128
+ throw error;
10129
+ }
10130
+ },
9369
10131
  async deleteNativeBuild(id) {
9370
10132
  return db.transaction(async (tx) => {
9371
10133
  const row = await tx.findOne("native_builds", { id });
@@ -9421,24 +10183,26 @@ const checkScope = (scope) => {
9421
10183
  });
9422
10184
  if (scope.strategy === "FINGERPRINT" !== (scope.fingerprintHash !== null) || scope.scopeKey !== expected) fail$1("INVALID_SCOPE", "Release catalog scope metadata is inconsistent");
9423
10185
  };
9424
- const enabledReleases = async (tx, scopeKey) => {
10186
+ const drainReleases = async (page) => {
9425
10187
  const rows = [];
9426
10188
  let cursor;
9427
10189
  do {
9428
- const page = await tx.findMany("releases", {
9429
- index: "byScopeEnabled",
9430
- where: {
9431
- scope_key: scopeKey,
9432
- enabled: true
9433
- },
9434
- limit: PAGE$1,
9435
- ...cursor === void 0 ? {} : { cursor }
9436
- });
9437
- rows.push(...page.rows.map(toReleaseRow));
9438
- cursor = page.next;
10190
+ const found = await page(cursor);
10191
+ rows.push(...found.rows.map((row) => toReleaseRow(row)));
10192
+ cursor = found.next;
9439
10193
  } while (cursor !== void 0);
9440
10194
  return rows;
9441
10195
  };
10196
+ const enabledIn = (scopeKey, cursor) => ({
10197
+ index: "byScopeEnabled",
10198
+ where: {
10199
+ scope_key: scopeKey,
10200
+ enabled: true
10201
+ },
10202
+ limit: PAGE$1,
10203
+ ...cursor === void 0 ? {} : { cursor }
10204
+ });
10205
+ const enabledReleases = (tx, scopeKey) => drainReleases((cursor) => tx.findMany("releases", enabledIn(scopeKey, cursor)));
9442
10206
  const latestReleaseId = async (tx, scopeKey) => {
9443
10207
  const { rows } = await tx.findMany("releases", {
9444
10208
  index: "byScope",
@@ -9448,14 +10212,10 @@ const latestReleaseId = async (tx, scopeKey) => {
9448
10212
  });
9449
10213
  return rows[0]?.id ?? null;
9450
10214
  };
9451
- const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
9452
- const compilation = await compileReleaseCatalog({
9453
- strategy: scope.strategy,
9454
- releases: enabled.map(releaseRowToRelease)
9455
- });
9456
- const generation = (stored.generation ?? 0) + 1;
10215
+ const nextCatalog = (scope, stored, compilation, updatedAtMs) => {
10216
+ const generation = (stored.catalog?.generation ?? 0) + 1;
9457
10217
  if (!Number.isSafeInteger(generation)) fail$1("CATALOG_GENERATION_EXHAUSTED", `Catalog "${scope.scopeKey}" exhausted its generation counter`);
9458
- const catalog = {
10218
+ return {
9459
10219
  scope_key: scope.scopeKey,
9460
10220
  catalog_id: stored.catalog?.catalog_id ?? createUUIDv7(),
9461
10221
  strategy: scope.strategy,
@@ -9470,6 +10230,21 @@ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
9470
10230
  is_tombstone: compilation.payload.releaseDescriptors.length === 0,
9471
10231
  updated_at_ms: updatedAtMs
9472
10232
  };
10233
+ };
10234
+ const compileScope = async (scope, enabled) => {
10235
+ try {
10236
+ return await compileReleaseCatalog({
10237
+ strategy: scope.strategy,
10238
+ releases: enabled.map(releaseRowToRelease)
10239
+ });
10240
+ } catch (error) {
10241
+ if (!(error instanceof ReleaseCatalogCompilationError) || error.code !== "CATALOG_OVERSIZE") throw error;
10242
+ throw new ReleaseCatalogCompilationError("CATALOG_OVERSIZE", `The ${scope.platform} release catalog of channel "${scope.channelName}" would be over its ${MAX_COMPILED_CATALOG_BYTES / 1024} KiB limit.\nDisable or delete old bundles on that channel, then try again.`);
10243
+ }
10244
+ };
10245
+ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
10246
+ const compilation = await compileScope(scope, enabled);
10247
+ const catalog = nextCatalog(scope, stored, compilation, updatedAtMs);
9473
10248
  const { scope_key: _scopeKey, ...set } = catalog;
9474
10249
  if (stored.row === null) tx.create("release_catalogs", catalog);
9475
10250
  else tx.update("release_catalogs", stored.row, set);
@@ -9548,17 +10323,39 @@ const changeReleases = (db, inputs) => {
9548
10323
  return results;
9549
10324
  });
9550
10325
  };
10326
+ const isCurrent = (scope, current, compilation) => current.strategy === scope.strategy && current.channel_id === scope.channelId && current.channel_key === encodeChannelKey(scope.channelName) && current.platform === scope.platform && current.fingerprint_hash === scope.fingerprintHash && current.catalog_hash === compilation.catalogHash;
10327
+ const catalogRowScope = (row) => ({
10328
+ channelId: row.channel_id,
10329
+ channelName: decodeChannelKey(row.channel_key),
10330
+ fingerprintHash: row.fingerprint_hash,
10331
+ platform: row.platform,
10332
+ scopeKey: row.scope_key,
10333
+ strategy: row.strategy
10334
+ });
10335
+ const preflightRebuild = async (db, scopeKey, updatedAtMs) => {
10336
+ const row = await db.findOne("release_catalogs", { scope_key: scopeKey });
10337
+ if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
10338
+ const current = toCatalogRow(row);
10339
+ const scope = catalogRowScope(current);
10340
+ checkScope(scope);
10341
+ const enabled = await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor)));
10342
+ const compilation = await compileScope(scope, enabled);
10343
+ const changed = !isCurrent(scope, current, compilation);
10344
+ return {
10345
+ changed,
10346
+ currentCatalog: current,
10347
+ diagnostics: compilation.diagnostics,
10348
+ projectedCatalog: changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current
10349
+ };
10350
+ };
9551
10351
  const rebuildScope = async (tx, scope, updatedAtMs) => {
9552
10352
  checkScope(scope);
9553
10353
  const stored = await readCatalog(tx, scope.scopeKey);
9554
10354
  assertHistory(stored, await latestReleaseId(tx, scope.scopeKey) !== null);
9555
10355
  const enabled = await enabledReleases(tx, scope.scopeKey);
9556
- const compilation = await compileReleaseCatalog({
9557
- strategy: scope.strategy,
9558
- releases: enabled.map(releaseRowToRelease)
9559
- });
10356
+ const compilation = await compileScope(scope, enabled);
9560
10357
  const current = stored.catalog;
9561
- if (current !== null && current.strategy === scope.strategy && current.channel_id === scope.channelId && current.channel_key === encodeChannelKey(scope.channelName) && current.platform === scope.platform && current.fingerprint_hash === scope.fingerprintHash && current.catalog_hash === compilation.catalogHash) return {
10358
+ if (current !== null && isCurrent(scope, current, compilation)) return {
9562
10359
  catalog: current,
9563
10360
  current,
9564
10361
  changed: false,
@@ -9658,14 +10455,7 @@ const mutationResult = ({ catalog, release }) => ({
9658
10455
  const catalogScope = async (tx, scopeKey) => {
9659
10456
  const row = await tx.findOne("release_catalogs", { scope_key: scopeKey });
9660
10457
  if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
9661
- return {
9662
- channelId: row.channel_id,
9663
- channelName: decodeChannelKey(row.channel_key),
9664
- fingerprintHash: row.fingerprint_hash,
9665
- platform: row.platform,
9666
- scopeKey: row.scope_key,
9667
- strategy: row.strategy
9668
- };
10458
+ return catalogRowScope(toCatalogRow(row));
9669
10459
  };
9670
10460
  const createCoreOperations = (db, { now = Date.now } = {}) => {
9671
10461
  const ensureChannel = async (name) => (await insertChannel(db, {
@@ -9685,7 +10475,11 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
9685
10475
  for (const { release } of deployments) if (!channels.has(release.channel)) channels.set(release.channel, await ensureChannel(release.channel));
9686
10476
  const platforms = /* @__PURE__ */ new Map();
9687
10477
  for (const deployment of deployments) {
9688
- if (!("bundleId" in deployment) || platforms.has(deployment.bundleId)) continue;
10478
+ if (!("bundleId" in deployment)) {
10479
+ for (const { baseBundleId } of deployment.bundle.patches ?? []) await refuseSandboxPatchBase(db, baseBundleId);
10480
+ continue;
10481
+ }
10482
+ if (platforms.has(deployment.bundleId)) continue;
9689
10483
  const row = await db.findOne("bundles", { id: deployment.bundleId });
9690
10484
  if (row === null) throw new DatabaseBundleNotFoundError(deployment.bundleId);
9691
10485
  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.`);
@@ -9860,18 +10654,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
9860
10654
  };
9861
10655
  });
9862
10656
  },
9863
- preflightReleaseCatalogRebuild: (scopeKey) => {
9864
- const updatedAtMs = now();
9865
- return dryRun(db, async (tx) => {
9866
- const rebuilt = await rebuildScope(tx, await catalogScope(tx, scopeKey), updatedAtMs);
9867
- return {
9868
- changed: rebuilt.changed,
9869
- currentCatalog: rebuilt.current,
9870
- diagnostics: rebuilt.diagnostics,
9871
- projectedCatalog: rebuilt.catalog
9872
- };
9873
- });
9874
- },
10657
+ preflightReleaseCatalogRebuild: (scopeKey) => preflightRebuild(db, scopeKey, now()),
9875
10658
  ensureChannel,
9876
10659
  deleteChannel: (id) => deleteChannel(db, id),
9877
10660
  updateBundle: (id, update) => db.transaction(async (tx) => {
@@ -9889,7 +10672,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
9889
10672
  if (patches !== void 0) await replaceBundlePatches(tx, current, bundleToPatchRows({
9890
10673
  ...next,
9891
10674
  patches
9892
- }));
10675
+ }), (row) => refuseSandboxPatchBase(tx, row.base_bundle_id));
9893
10676
  }),
9894
10677
  deleteBundles: async (ids) => {
9895
10678
  try {
@@ -9945,6 +10728,7 @@ const createCoreApi = (db, storage, options = {}) => {
9945
10728
  ...reads,
9946
10729
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
9947
10730
  ...createNativeBuildApi(db, options),
10731
+ ...createIosDeviceApi(db, options),
9948
10732
  ready: async () => {
9949
10733
  await reads.listReleaseCatalogs({ limit: 1 });
9950
10734
  }
@@ -10128,6 +10912,10 @@ const answer = async (operation) => {
10128
10912
  error: error.message
10129
10913
  }, status);
10130
10914
  }
10915
+ if (error instanceof ReleaseCatalogCompilationError && error.code === "CATALOG_OVERSIZE") return json$2({
10916
+ code: error.code,
10917
+ error: error.message
10918
+ }, 400);
10131
10919
  if (error instanceof DatabaseBundleNotFoundError) return json$2({
10132
10920
  code: "BUNDLE_NOT_FOUND",
10133
10921
  error: error.message
@@ -10147,17 +10935,20 @@ const LIMITS = {
10147
10935
  defaultValue: 50,
10148
10936
  maxValue: 500
10149
10937
  };
10150
- const keyset = (url, maxValue = LIMITS.maxValue) => {
10151
- const order = url.searchParams.get("order") ?? "desc";
10938
+ const MAX_IDS = 100;
10939
+ const keyset = (url, maxValue = LIMITS.maxValue, defaultOrder = "desc") => {
10940
+ const order = url.searchParams.get("order") ?? defaultOrder;
10152
10941
  if (order !== "asc" && order !== "desc") throw new HandlerBadRequestError("order must be 'asc' or 'desc'.");
10153
10942
  const limitParam = url.searchParams.get("limit");
10154
10943
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
10155
10944
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
10156
10945
  const cursor = url.searchParams.get("cursor");
10946
+ const through = url.searchParams.get("through");
10157
10947
  return {
10158
10948
  order,
10159
10949
  limit,
10160
- ...cursor === null ? {} : { after: cursor }
10950
+ ...cursor === null ? {} : { after: cursor },
10951
+ ...through === null ? {} : { through }
10161
10952
  };
10162
10953
  };
10163
10954
  const page = (rows, { limit }, keyOf, extra = {}) => json$2({
@@ -10248,7 +11039,8 @@ const nativeBuildScopeOf = (url) => {
10248
11039
  const fingerprintHash = params.get("fingerprintHash");
10249
11040
  const appVersion = params.get("appVersion");
10250
11041
  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 ? {
11042
+ const sandbox = sandboxScopeOf(params);
11043
+ const scope = fingerprintHash !== null ? {
10252
11044
  platform,
10253
11045
  channel,
10254
11046
  fingerprintHash,
@@ -10259,16 +11051,43 @@ const nativeBuildScopeOf = (url) => {
10259
11051
  fingerprintHash: null,
10260
11052
  appVersion
10261
11053
  };
11054
+ return sandbox === null ? scope : {
11055
+ ...scope,
11056
+ sandbox
11057
+ };
11058
+ };
11059
+ const SANDBOX_SCOPE_PARAMS = [
11060
+ "sandboxAppId",
11061
+ "sandboxUrlScheme",
11062
+ "artifactKind",
11063
+ "distribution"
11064
+ ];
11065
+ const sandboxScopeOf = (params) => {
11066
+ const [appId, urlScheme, artifactKind, distribution] = SANDBOX_SCOPE_PARAMS.map((name) => params.get(name));
11067
+ const named = [
11068
+ appId,
11069
+ urlScheme,
11070
+ artifactKind,
11071
+ distribution
11072
+ ].filter((value) => value !== null).length;
11073
+ if (named === 0) return null;
11074
+ if (named !== SANDBOX_SCOPE_PARAMS.length) throw new HandlerBadRequestError(`A sandbox build lookup needs ${SANDBOX_SCOPE_PARAMS.join(", ")}.`);
11075
+ return {
11076
+ appId,
11077
+ urlScheme,
11078
+ artifactKind,
11079
+ distribution
11080
+ };
10262
11081
  };
10263
11082
  const refusingInvalid = async (operation) => {
10264
11083
  try {
10265
11084
  return await operation();
10266
11085
  } catch (error) {
10267
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
11086
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
10268
11087
  throw error;
10269
11088
  }
10270
11089
  };
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));
11090
+ 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
11091
  const scopeKeyOf = (params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "";
10273
11092
  const createAdminRouteHandlers = () => ({
10274
11093
  listBundles: onCore(async (core, request) => {
@@ -10300,11 +11119,34 @@ const createAdminRouteHandlers = () => ({
10300
11119
  const rows = await core.listReleaseCatalogs(input);
10301
11120
  return page(rows, input, (row) => row.scope_key);
10302
11121
  }),
11122
+ listReleaseScopeKeys: onCore(async (core, request) => {
11123
+ const input = keyset(new URL(request.url), 100, "asc");
11124
+ if (input.order !== "asc" || input.through !== void 0) throw new HandlerBadRequestError("Release scopes are listed ascending, by limit and cursor only.");
11125
+ const rows = await core.listReleaseScopeKeys({
11126
+ limit: input.limit,
11127
+ ...input.after === void 0 ? {} : { after: input.after }
11128
+ });
11129
+ return page(rows, input, (scopeKey) => scopeKey);
11130
+ }),
10303
11131
  getChannels: onCore(async (core, request) => {
10304
- const name = new URL(request.url).searchParams.get("name");
10305
- if (name === null) return json$2({ data: await core.listChannels() });
10306
- const channel = await core.findChannelByName(name);
10307
- return channel === null ? notFound() : json$2({ data: channel });
11132
+ const url = new URL(request.url);
11133
+ const name = url.searchParams.get("name");
11134
+ if (name !== null) {
11135
+ const channel = await core.findChannelByName(name);
11136
+ return channel === null ? notFound() : json$2({ data: channel });
11137
+ }
11138
+ const ids = url.searchParams.get("ids");
11139
+ if (ids !== null) {
11140
+ const list = ids.split(",").filter((id) => id.length > 0);
11141
+ if (list.length === 0 || list.length > MAX_IDS) throw new HandlerBadRequestError(`Channels by ID take ids=<channel id>,... with 1 to ${MAX_IDS} ids.`);
11142
+ return json$2({ data: await core.getChannels(list) });
11143
+ }
11144
+ if (url.searchParams.has("limit") || url.searchParams.has("cursor")) {
11145
+ const input = keyset(url, LIMITS.maxValue, "asc");
11146
+ const rows = await core.listChannels(input);
11147
+ return page(rows, input, (row) => row.name);
11148
+ }
11149
+ return json$2({ data: await core.listChannels() });
10308
11150
  }),
10309
11151
  createChannel: onCore(async (core, request) => {
10310
11152
  const { name } = await body$1(request);
@@ -10345,13 +11187,14 @@ const createAdminRouteHandlers = () => ({
10345
11187
  rebuildReleaseCatalog: onCore(async (core, _request, params) => json$2({ data: await core.rebuildReleaseCatalog(scopeKeyOf(params)) })),
10346
11188
  updateBundle: onCore(async (core, request, params) => {
10347
11189
  const bundleId = requireRouteParam(params, "id");
10348
- await core.updateBundle(bundleId, bundleUpdateOf(await request.json(), bundleId));
11190
+ const update = bundleUpdateOf(await request.json(), bundleId);
11191
+ await refusingInvalid(() => core.updateBundle(bundleId, update));
10349
11192
  return noContent();
10350
11193
  }),
10351
11194
  countBundles: onCore(async (core, request) => json$2({ data: await core.countBundles(platformOf(new URL(request.url))) })),
10352
11195
  countBundleChildren: onCore(async (core, request) => {
10353
11196
  const ids = (new URL(request.url).searchParams.get("ids") ?? "").split(",").filter((id) => id.length > 0);
10354
- if (ids.length === 0 || ids.length > 100) throw new HandlerBadRequestError("Bundle child counts take ids=<bundle id>,... with 1 to 100 ids.");
11197
+ if (ids.length === 0 || ids.length > MAX_IDS) throw new HandlerBadRequestError(`Bundle child counts take ids=<bundle id>,... with 1 to ${MAX_IDS} ids.`);
10355
11198
  return json$2({ data: await core.countBundleChildren(ids) });
10356
11199
  }),
10357
11200
  listBundleChildren: onCore(async (core, request, params) => {
@@ -10369,7 +11212,7 @@ const createAdminRouteHandlers = () => ({
10369
11212
  deployReleases: onCore(async (core, request) => {
10370
11213
  const { deployments } = await body$1(request);
10371
11214
  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);
11215
+ return json$2({ data: await refusingInvalid(() => core.deploy(deployments)) }, 201);
10373
11216
  }),
10374
11217
  promoteRelease: onCore(async (core, request, params) => {
10375
11218
  const input = await body$1(request);
@@ -10392,9 +11235,22 @@ const createAdminRouteHandlers = () => ({
10392
11235
  const url = new URL(request.url);
10393
11236
  const scope = nativeBuildScopeOf(url);
10394
11237
  const buildKey = url.searchParams.get("buildKey");
10395
- return json$2({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
11238
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
11239
+ const kind = url.searchParams.get("kind");
11240
+ const options = {
11241
+ ...buildKey === null ? {} : { buildKey },
11242
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
11243
+ ...builtInOlderThan === null ? {} : { builtInOlderThan },
11244
+ ...kind === null ? {} : { artifactKind: kind }
11245
+ };
11246
+ return json$2({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
11247
+ }),
11248
+ findNativeBuildSibling: onCore(async (core, _request, params) => {
11249
+ const build = await core.getNativeBuild(requireRouteParam(params, "id"));
11250
+ return json$2({ data: build === null ? null : await core.findNativeBuildSibling(build) });
10396
11251
  }),
10397
11252
  getNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
11253
+ findNativeBuildByBuiltInBundle: onCore(async (core, _request, params) => json$2({ data: await core.findNativeBuildByBuiltInBundle(requireRouteParam(params, "bundleId")) })),
10398
11254
  listNativeBuilds: onCore(async (core, request) => {
10399
11255
  const url = new URL(request.url);
10400
11256
  const input = keyset(url);
@@ -10406,14 +11262,97 @@ const createAdminRouteHandlers = () => ({
10406
11262
  }),
10407
11263
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
10408
11264
  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.");
11265
+ 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
11266
  const submission = {
10411
11267
  destination: input.destination,
10412
11268
  version: input.version
10413
11269
  };
10414
11270
  return json$2({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
10415
11271
  }),
11272
+ markNativeBuild: onCore(async (core, request, params) => {
11273
+ const input = await body$1(request);
11274
+ if (!isRecord$5(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
11275
+ const mark = { storeBuild: input.storeBuild };
11276
+ return json$2({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
11277
+ }),
10416
11278
  deleteNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
11279
+ listIosDevices: onCore(async (core, request) => {
11280
+ const url = new URL(request.url);
11281
+ const input = keyset(url);
11282
+ const status = url.searchParams.get("status");
11283
+ return page(await refusingInvalid(() => core.listIosDevices({
11284
+ ...input,
11285
+ ...status === null ? {} : { status }
11286
+ })), input, ({ id }) => id);
11287
+ }),
11288
+ findIosDevice: onCore(async (core, _request, params) => json$2({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
11289
+ requestIosDevice: onCore(async (core, request) => {
11290
+ const input = await body$1(request);
11291
+ 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.");
11292
+ const device = {
11293
+ udid: input.udid,
11294
+ name: input.name,
11295
+ requestedBy: input.requestedBy
11296
+ };
11297
+ return json$2({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
11298
+ }),
11299
+ approveIosDevice: onCore(async (core, request, params) => {
11300
+ const input = await body$1(request);
11301
+ 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.");
11302
+ const approval = {
11303
+ approvedBy: input.approvedBy,
11304
+ ...input.name === void 0 ? {} : { name: input.name }
11305
+ };
11306
+ return json$2({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
11307
+ }),
11308
+ renameIosDevice: onCore(async (core, request, params) => {
11309
+ const input = await body$1(request);
11310
+ if (!isText$2(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
11311
+ const name = input.name;
11312
+ return json$2({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
11313
+ }),
11314
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
11315
+ const input = await body$1(request);
11316
+ const seen = input.seen;
11317
+ 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.");
11318
+ const outcome = {
11319
+ id: requireRouteParam(params, "id"),
11320
+ seen: {
11321
+ status: seen.status,
11322
+ approvedAtMs: seen.approvedAtMs
11323
+ },
11324
+ issuerId: input.issuerId,
11325
+ outcome: input.outcome,
11326
+ ...input.reason === void 0 ? {} : { reason: input.reason }
11327
+ };
11328
+ return json$2({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
11329
+ }),
11330
+ claimIosDeviceAccount: onCore(async (core, request) => {
11331
+ const { issuerId } = await body$1(request);
11332
+ if (!isText$2(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
11333
+ return json$2({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
11334
+ }),
11335
+ findIosDeviceAccount: onCore(async (core) => json$2({ data: await core.findIosDeviceAccount() })),
11336
+ markIosDevicesInBuild: onCore(async (core, request) => {
11337
+ const { buildId, ids } = await body$1(request);
11338
+ 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.");
11339
+ if (ids.length > MAX_IDS) throw new HandlerBadRequestError(`Marking iOS devices in a build takes at most ${MAX_IDS} ids a request.`);
11340
+ await core.markIosDevicesInBuild({
11341
+ buildId,
11342
+ ids
11343
+ });
11344
+ return noContent();
11345
+ }),
11346
+ deleteIosDevice: onCore(async (core, request, params) => {
11347
+ const url = new URL(request.url);
11348
+ const status = url.searchParams.get("status");
11349
+ const requestedBy = url.searchParams.get("requestedBy");
11350
+ const only = {
11351
+ ...status === null ? {} : { status },
11352
+ ...requestedBy === null ? {} : { requestedBy }
11353
+ };
11354
+ return json$2({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
11355
+ }),
10417
11356
  deleteBundles: onCore(async (core, request) => {
10418
11357
  const { ids } = await body$1(request);
10419
11358
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -10467,6 +11406,11 @@ const ADMIN_ROUTES = [
10467
11406
  path: "/release-catalogs",
10468
11407
  handler: "listReleaseCatalogs"
10469
11408
  },
11409
+ {
11410
+ method: "GET",
11411
+ path: "/release-scopes",
11412
+ handler: "listReleaseScopeKeys"
11413
+ },
10470
11414
  {
10471
11415
  method: "POST",
10472
11416
  path: "/release-catalogs/:scopeKey/rebuild",
@@ -10542,6 +11486,16 @@ const ADMIN_ROUTES = [
10542
11486
  path: "/native-builds/latest",
10543
11487
  handler: "findNativeBuild"
10544
11488
  },
11489
+ {
11490
+ method: "GET",
11491
+ path: "/native-builds/built-in/:bundleId",
11492
+ handler: "findNativeBuildByBuiltInBundle"
11493
+ },
11494
+ {
11495
+ method: "GET",
11496
+ path: "/native-builds/:id/sibling",
11497
+ handler: "findNativeBuildSibling"
11498
+ },
10545
11499
  {
10546
11500
  method: "GET",
10547
11501
  path: "/native-builds/:id",
@@ -10557,10 +11511,65 @@ const ADMIN_ROUTES = [
10557
11511
  path: "/native-builds/:id/submission",
10558
11512
  handler: "recordNativeBuildSubmission"
10559
11513
  },
11514
+ {
11515
+ method: "POST",
11516
+ path: "/native-builds/:id/store-build",
11517
+ handler: "markNativeBuild"
11518
+ },
10560
11519
  {
10561
11520
  method: "DELETE",
10562
11521
  path: "/native-builds/:id",
10563
11522
  handler: "deleteNativeBuild"
11523
+ },
11524
+ {
11525
+ method: "GET",
11526
+ path: "/ios-devices",
11527
+ handler: "listIosDevices"
11528
+ },
11529
+ {
11530
+ method: "POST",
11531
+ path: "/ios-devices",
11532
+ handler: "requestIosDevice"
11533
+ },
11534
+ {
11535
+ method: "GET",
11536
+ path: "/ios-devices/udid/:udid",
11537
+ handler: "findIosDevice"
11538
+ },
11539
+ {
11540
+ method: "POST",
11541
+ path: "/ios-devices/in-build",
11542
+ handler: "markIosDevicesInBuild"
11543
+ },
11544
+ {
11545
+ method: "GET",
11546
+ path: "/ios-devices/account",
11547
+ handler: "findIosDeviceAccount"
11548
+ },
11549
+ {
11550
+ method: "POST",
11551
+ path: "/ios-devices/account",
11552
+ handler: "claimIosDeviceAccount"
11553
+ },
11554
+ {
11555
+ method: "POST",
11556
+ path: "/ios-devices/:id/approval",
11557
+ handler: "approveIosDevice"
11558
+ },
11559
+ {
11560
+ method: "POST",
11561
+ path: "/ios-devices/:id/outcome",
11562
+ handler: "recordIosDeviceOutcome"
11563
+ },
11564
+ {
11565
+ method: "PATCH",
11566
+ path: "/ios-devices/:id",
11567
+ handler: "renameIosDevice"
11568
+ },
11569
+ {
11570
+ method: "DELETE",
11571
+ path: "/ios-devices/:id",
11572
+ handler: "deleteIosDevice"
10564
11573
  }
10565
11574
  ];
10566
11575
  //#endregion
@@ -10635,38 +11644,53 @@ const catalogResponse = async (catalog, request) => {
10635
11644
  };
10636
11645
  const createReleaseCatalogRouteHandlers = () => {
10637
11646
  const cache = /* @__PURE__ */ new Map();
11647
+ const evict = (insertedHit) => {
11648
+ const now = Date.now();
11649
+ let oldestMiss;
11650
+ let oldest;
11651
+ for (const [key, entry] of cache) if (entry.expiresAt <= now) cache.delete(key);
11652
+ else {
11653
+ if (entry.row === null) oldestMiss ??= key;
11654
+ oldest ??= key;
11655
+ }
11656
+ if (cache.size <= ORIGIN_CACHE_MAX_ENTRIES) return;
11657
+ const victim = oldestMiss ?? (insertedHit ? oldest : void 0);
11658
+ if (victim !== void 0) cache.delete(victim);
11659
+ };
10638
11660
  const inFlight = /* @__PURE__ */ new Map();
10639
- const loadCatalog = async (key, load) => {
10640
- const cached = cache.get(key);
11661
+ const loadRow = async (scopeKey, load) => {
11662
+ const cached = cache.get(scopeKey);
10641
11663
  if (cached !== void 0 && cached.expiresAt > Date.now()) {
10642
- cache.delete(key);
10643
- cache.set(key, cached);
10644
- return cached.catalog;
11664
+ cache.delete(scopeKey);
11665
+ cache.set(scopeKey, cached);
11666
+ return cached.row;
10645
11667
  }
10646
- if (cached !== void 0) cache.delete(key);
10647
- const pending = inFlight.get(key);
11668
+ if (cached !== void 0) cache.delete(scopeKey);
11669
+ const pending = inFlight.get(scopeKey);
10648
11670
  if (pending !== void 0) return pending;
10649
- const next = load().then((catalog) => {
10650
- if (catalog !== null) {
10651
- cache.set(key, {
10652
- catalog,
10653
- expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
10654
- });
10655
- while (cache.size > ORIGIN_CACHE_MAX_ENTRIES) {
10656
- const oldestKey = cache.keys().next().value;
10657
- if (oldestKey === void 0) break;
10658
- cache.delete(oldestKey);
10659
- }
10660
- }
10661
- return catalog;
11671
+ const next = load().then((row) => {
11672
+ cache.set(scopeKey, {
11673
+ row,
11674
+ expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
11675
+ });
11676
+ if (cache.size > ORIGIN_CACHE_MAX_ENTRIES) evict(row !== null);
11677
+ return row;
10662
11678
  });
10663
- inFlight.set(key, next);
11679
+ inFlight.set(scopeKey, next);
10664
11680
  try {
10665
11681
  return await next;
10666
11682
  } finally {
10667
- inFlight.delete(key);
11683
+ inFlight.delete(scopeKey);
10668
11684
  }
10669
11685
  };
11686
+ const loadCatalog = async (core, input) => {
11687
+ const scopeKey = releaseCatalogScopeKeyOf(input);
11688
+ const parsed = await loadRow(scopeKey, async () => {
11689
+ const row = await core.getReleaseCatalogRow(scopeKey);
11690
+ return row === null ? null : parseReleaseCatalogRow(row);
11691
+ });
11692
+ return projectParsedReleaseCatalogRow(parsed, input, scopeKey);
11693
+ };
10670
11694
  return {
10671
11695
  appVersionReleaseCatalog: async (params, request, { core }) => {
10672
11696
  const rawAppVersion = requireRouteParam(params, "appVersion");
@@ -10680,7 +11704,7 @@ const createReleaseCatalogRouteHandlers = () => {
10680
11704
  };
10681
11705
  const invalid = invalidScope(input);
10682
11706
  if (invalid) return invalid;
10683
- return catalogResponse(await loadCatalog(`app-version:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
11707
+ return catalogResponse(await loadCatalog(core, input), request);
10684
11708
  },
10685
11709
  fingerprintReleaseCatalog: async (params, request, { core }) => {
10686
11710
  const input = {
@@ -10691,7 +11715,7 @@ const createReleaseCatalogRouteHandlers = () => {
10691
11715
  };
10692
11716
  const invalid = invalidScope(input);
10693
11717
  if (invalid) return invalid;
10694
- return catalogResponse(await loadCatalog(`fingerprint:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
11718
+ return catalogResponse(await loadCatalog(core, input), request);
10695
11719
  },
10696
11720
  artifactV2: async (params, _request, { core }) => {
10697
11721
  const info = await core.getArtifactInfo(requireRouteParam(params, "targetBundleId"), requireRouteParam(params, "currentBundleId"), 2);
@@ -13605,6 +14629,53 @@ const breakdownOf = (rows) => {
13605
14629
  };
13606
14630
  });
13607
14631
  };
14632
+ const FAILURE_ROWS_PER_HOUR = 20;
14633
+ const FAILURE_QUERY_LIMIT = Math.min(PAGE, 168);
14634
+ const failureRowsByHour = async (db, platform, channel, timeRange) => {
14635
+ const read = (end, cursor) => db.findAggregates("insights_failures", {
14636
+ index: "byScope",
14637
+ where: {
14638
+ platform,
14639
+ channel
14640
+ },
14641
+ range: {
14642
+ gte: timeRange.start,
14643
+ lt: end
14644
+ },
14645
+ order: "desc",
14646
+ limit: FAILURE_QUERY_LIMIT,
14647
+ ...cursor === void 0 ? {} : { cursor }
14648
+ });
14649
+ const rows = [];
14650
+ const cappedHours = [];
14651
+ const perHour = /* @__PURE__ */ new Map();
14652
+ let end = timeRange.end;
14653
+ let cursor;
14654
+ while (end > timeRange.start) {
14655
+ const page = await read(end, cursor);
14656
+ let capped;
14657
+ for (const row of page.rows) {
14658
+ const hour = row.bucket_start_ms;
14659
+ const count = (perHour.get(hour) ?? 0) + 1;
14660
+ if (count > FAILURE_ROWS_PER_HOUR) {
14661
+ capped = hour;
14662
+ break;
14663
+ }
14664
+ perHour.set(hour, count);
14665
+ rows.push(row);
14666
+ }
14667
+ if (capped !== void 0) {
14668
+ cappedHours.unshift(capped);
14669
+ end = capped;
14670
+ cursor = void 0;
14671
+ } else if (page.next === void 0) break;
14672
+ else cursor = page.next;
14673
+ }
14674
+ return {
14675
+ rows,
14676
+ cappedHours
14677
+ };
14678
+ };
13608
14679
  const getUpdateFailures = async (db, input, now, retention) => {
13609
14680
  const { platform, channel, releaseId, timeRange } = input;
13610
14681
  if (platform !== "ios" && platform !== "android" || !isText(channel, 1024) || releaseId !== void 0 && !isText(releaseId, 36) || !isRange(timeRange) || releaseId === void 0 && timeRange === void 0) throw new DatabaseAdapterInputError("invalid-query");
@@ -13665,7 +14736,7 @@ const getUpdateFailures = async (db, input, now, retention) => {
13665
14736
  days,
13666
14737
  kept.hour
13667
14738
  ];
13668
- const [counters, failures, checks, active, rows] = await Promise.all([
14739
+ const [counters, failures, checks, active, { rows, cappedHours }] = await Promise.all([
13669
14740
  counterRows(db, parts, ...window),
13670
14741
  sketchRows(db, failure, ...window),
13671
14742
  days ? sketchRows(db, {
@@ -13673,25 +14744,17 @@ const getUpdateFailures = async (db, input, now, retention) => {
13673
14744
  scopeKind: "check"
13674
14745
  }, ...window) : [],
13675
14746
  days ? sketchRows(db, usageParts(channel, platform), ...window) : [],
13676
- drain((page) => db.findAggregates("insights_failures", {
13677
- index: "byScope",
13678
- where: {
13679
- platform,
13680
- channel
13681
- },
13682
- range: {
13683
- gte: timeRange.start,
13684
- lt: timeRange.end
13685
- },
13686
- limit: PAGE,
13687
- ...page
13688
- }))
14747
+ failureRowsByHour(db, platform, channel, timeRange)
13689
14748
  ]);
13690
14749
  const total = (field) => counters.reduce((sum, row) => sum + row[field], 0);
13691
14750
  const scoped = rows.filter((row) => FAILURE_STAGES.has(row.stage) && (releaseId === void 0 || row.release_id === releaseId));
13692
14751
  const failuresAt = (counted) => scoped.reduce((sum, row) => sum + (counted(row.stage) ? Math.max(0, row.events) : 0), 0);
14752
+ const coverage = coverageOf(timeRange.start, kept.hour);
13693
14753
  return {
13694
- coverage: coverageOf(timeRange.start, kept.hour),
14754
+ coverage: cappedHours.length === 0 ? coverage : {
14755
+ kind: "partial",
14756
+ sinceMs: coverage.sinceMs
14757
+ },
13695
14758
  measuredAtMs: at,
13696
14759
  failedUpdates: failuresAt((stage) => stage !== "check"),
13697
14760
  failedInstallations: failed(failures),
@@ -13703,7 +14766,8 @@ const getUpdateFailures = async (db, input, now, retention) => {
13703
14766
  failedInstallations: failed(checks),
13704
14767
  activeInstallations: countDistinct(mergeDistinct(active.map((row) => row.activity_users)))
13705
14768
  } } : {},
13706
- breakdown: breakdownOf(scoped)
14769
+ breakdown: breakdownOf(scoped),
14770
+ ...cappedHours.length === 0 ? {} : { cappedHours }
13707
14771
  };
13708
14772
  };
13709
14773
  //#endregion
@@ -57555,7 +58619,6 @@ function azureBlobStorage(config) {
57555
58619
  const headers = new Headers();
57556
58620
  if (download.contentType) headers.set("content-type", download.contentType);
57557
58621
  if (download.contentLength !== void 0) headers.set("content-length", String(download.contentLength));
57558
- const { Readable } = await import("node:stream");
57559
58622
  return { response: new Response(Readable.toWeb(body), { headers }) };
57560
58623
  } catch (error) {
57561
58624
  if (isNotFound(error)) return { response: null };
@@ -70815,6 +71878,7 @@ const statusOf = (error) => {
70815
71878
  if (typeof status === "number") return status;
70816
71879
  }
70817
71880
  };
71881
+ const POINT_READS = 2;
70818
71882
  const missingContainer = (error) => {
70819
71883
  throw statusOf(error) === 404 ? Object.assign(new Error(error.message, { cause: error }), { code: "42P01" }) : error;
70820
71884
  };
@@ -70877,16 +71941,36 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
70877
71941
  throw error;
70878
71942
  });
70879
71943
  const container = async () => (await open()).container;
71944
+ const pointRead = async (id) => {
71945
+ const response = await (await container()).item(id, COSMOS_PARTITION).read().catch(missingContainer);
71946
+ if (response.statusCode !== 404) return response.resource;
71947
+ const headers = response.headers;
71948
+ if (headers["x-ms-documentdb-partitionkeyrangeid"] === void 0 && headers["x-ms-substatus"] !== void 0) missingContainer(Object.assign(/* @__PURE__ */ new Error(`Cosmos DB container ${containerId} is missing.`), { code: 404 }));
71949
+ };
70880
71950
  const readStates = async (ids, rowIds) => {
70881
71951
  const states = /* @__PURE__ */ new Map();
70882
- 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) {
70883
- 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);
70884
- for (const { id, etag, v, expireAt, row } of resources) states.set(id, {
70885
- etag,
70886
- v,
70887
- expireAt: expireAt ?? null,
70888
- row
70889
- });
71952
+ for (const [group, projection] of [[ids.filter((id) => !rowIds.has(id)), ""], [ids.filter((id) => rowIds.has(id)), ", c.row"]]) {
71953
+ if (group.length <= POINT_READS) {
71954
+ for (const item of await Promise.all(group.map(pointRead))) {
71955
+ if (item === void 0) continue;
71956
+ states.set(item.id, {
71957
+ etag: item._etag,
71958
+ v: item.row?._v,
71959
+ expireAt: item.expireAt ?? null,
71960
+ row: projection === "" ? void 0 : item.row
71961
+ });
71962
+ }
71963
+ continue;
71964
+ }
71965
+ for (let at = 0; at < group.length; at += GET_BATCH) {
71966
+ 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);
71967
+ for (const { id, etag, v, expireAt, row } of resources) states.set(id, {
71968
+ etag,
71969
+ v,
71970
+ expireAt: expireAt ?? null,
71971
+ row
71972
+ });
71973
+ }
70890
71974
  }
70891
71975
  return states;
70892
71976
  };
@@ -71011,6 +72095,10 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
71011
72095
  async get(keys) {
71012
72096
  const found = /* @__PURE__ */ new Map();
71013
72097
  const ids = [...new Set(keys.map(cosmosItemId))];
72098
+ if (ids.length <= POINT_READS) {
72099
+ for (const item of await Promise.all(ids.map(pointRead))) if (item !== void 0) found.set(item.id, toRow(item.row));
72100
+ return keys.map((key) => found.get(cosmosItemId(key)) ?? null);
72101
+ }
71014
72102
  for (let at = 0; at < ids.length; at += GET_BATCH) {
71015
72103
  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);
71016
72104
  for (const resource of resources) found.set(resource.id, toRow(resource.row));