@hot-updater/vercel 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.
@@ -1969,43 +1969,6 @@ const withSchemaFence = (adapter, adapterName, expected, fix) => {
1969
1969
  const METER = Symbol.for("@hot-updater/plugin-core/read-meter");
1970
1970
  const readMeterOf = (database) => typeof database === "object" && database !== null ? database[METER] : void 0;
1971
1971
  //#endregion
1972
- //#region ../plugin-core/dist/engine/db/schemaSettings.mjs
1973
- const storedSettings = async (adapter, keys) => {
1974
- const rows = await readSettings(adapter, keys);
1975
- return new Map(keys.map((key, position) => [key, rows[position] ?? null]));
1976
- };
1977
- const writeSchemaSettings = async (adapter, adapterName, settings) => {
1978
- const stored = await storedSettings(adapter, Object.keys(settings));
1979
- const ops = Object.entries(settings).flatMap(([key, value]) => {
1980
- const row = stored.get(key);
1981
- if (row === null || row === void 0) return [{
1982
- type: "insert",
1983
- table: SETTINGS_TABLE,
1984
- row: {
1985
- key,
1986
- value,
1987
- _v: 0
1988
- }
1989
- }];
1990
- if (row.value === value) return [];
1991
- return [{
1992
- type: "patch",
1993
- table: SETTINGS_TABLE,
1994
- key: [key],
1995
- set: { value },
1996
- guard: { v: Number(row._v) },
1997
- previous: row
1998
- }];
1999
- });
2000
- if (ops.length === 0) return;
2001
- if (!(await adapter.write(ops)).ok) throw new Error(`${adapterName}: the schema settings changed during the migration; run it again.`);
2002
- };
2003
- const migrateSchema = async (adapter, adapterName, tables, settings) => {
2004
- if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
2005
- await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
2006
- await writeSchemaSettings(adapter, adapterName, settings);
2007
- };
2008
- //#endregion
2009
1972
  //#region ../plugin-core/dist/engine/database/sql/sqlSchema.mjs
2010
1973
  const quoteSql = (dialect, name) => dialect === "mysql" ? `\`${name.replaceAll("`", "``")}\`` : `"${name.replaceAll("\"", "\"\"")}"`;
2011
1974
  const isMultiIndex = (table, index) => index.eq.some((column) => findPhysicalColumn(table, column).multi);
@@ -2049,6 +2012,7 @@ const sqlTableShapes = (dialect, tables, tablePrefix = "") => tables.map((table)
2049
2012
  const name = tablePrefix + table.name;
2050
2013
  const indexed = /* @__PURE__ */ new Set([...table.key, ...table.indexes.flatMap(({ eq, sort }) => [...eq, ...sort])]);
2051
2014
  if (dialect === "mysql") checkMysqlKey(table, "key", table.key);
2015
+ const covered = /* @__PURE__ */ new Set([JSON.stringify(table.key)]);
2052
2016
  const indexes = table.indexes.flatMap((index) => {
2053
2017
  const columns = [...index.eq, ...indexOrderColumns(table, index)];
2054
2018
  if (dialect === "mysql") checkMysqlKey(table, `index ${index.name}`, columns);
@@ -2064,11 +2028,19 @@ const sqlTableShapes = (dialect, tables, tablePrefix = "") => tables.map((table)
2064
2028
  name: `${name}__${index.name}`,
2065
2029
  columns: entries,
2066
2030
  key: columns,
2067
- indexes: []
2031
+ indexes: [{
2032
+ kind: "index",
2033
+ name: shortSqlName(`${name}__${index.name}__key`),
2034
+ unique: false,
2035
+ columns: table.key
2036
+ }]
2068
2037
  }
2069
2038
  }];
2070
2039
  }
2071
- if (!index.unique && columns.join() === table.key.join()) return [];
2040
+ if (!index.unique) {
2041
+ if (covered.has(JSON.stringify(columns))) return [];
2042
+ covered.add(JSON.stringify(columns));
2043
+ }
2072
2044
  return [{
2073
2045
  kind: "index",
2074
2046
  name: shortSqlName(`${name}_${index.name}`),
@@ -2134,9 +2106,17 @@ const pruneStatements = (dialect, table, tablePrefix, limit) => {
2134
2106
  const order = retentionOrder(table).columns.map(quote);
2135
2107
  const list = (alias, direction = "") => order.map((column) => `${alias}.${column}${direction}`).join(", ");
2136
2108
  const oldest = (before) => `SELECT ${list("i")} FROM ${name} i WHERE i.${at} <= ${before()} ORDER BY ${list("i", " ASC")} LIMIT ${limit}`;
2137
- const doomed = (alias, before) => `${alias}.${at} <= ${before()} AND (${list(alias)}) <= (SELECT ${list("b")} FROM (${oldest(before)}) b ORDER BY ${list("b", " DESC")} LIMIT 1)`;
2109
+ const doomed = (alias, before) => `(${list(alias)}) <= (SELECT ${list("b")} FROM (${oldest(before)}) b ORDER BY ${list("b", " DESC")} LIMIT 1) AND ${alias}.${at} <= ${before()}`;
2138
2110
  const entries = table.indexes.filter((index) => isMultiIndex(table, index)).map((index) => quote(`${tablePrefix}${table.name}__${index.name}`));
2139
2111
  const keyOf = (left, right) => table.key.map((column) => `${left}.${quote(column)} = ${right}.${quote(column)}`).join(" AND ");
2112
+ if (dialect === "sqlite") return [...table.indexes.filter((index) => isMultiIndex(table, index)).map((index) => {
2113
+ const columns = [...index.eq, ...indexOrderColumns(table, index)];
2114
+ const multi = columns.filter((column) => findPhysicalColumn(table, column).multi);
2115
+ const values = columns.map((column) => multi.includes(column) ? `j${multi.indexOf(column)}.${quote("value")}` : `b.${quote(column)}`);
2116
+ const each = multi.map((column, at) => `, json_each(b.${quote(column)}) j${at}`);
2117
+ const into = quote(`${tablePrefix}${table.name}__${index.name}`);
2118
+ return (before) => `DELETE FROM ${into} WHERE (${columns.map(quote).join(", ")}) IN (SELECT ${values.join(", ")} FROM ${name} b${each.join("")} WHERE ${doomed("b", before)})`;
2119
+ }), (before) => `DELETE FROM ${name} WHERE ${doomed(name, before)}`];
2140
2120
  if (dialect === "mysql") return [...entries.map((index) => (before) => `DELETE e FROM ${index} e JOIN (${oldest(before)}) d ON ${keyOf("e", "d")}`), (before) => `DELETE FROM ${name} WHERE ${at} <= ${before()} ORDER BY ${order.join(", ")} LIMIT ${limit}`];
2141
2121
  return [...entries.map((index) => (before) => `DELETE FROM ${index} WHERE EXISTS (SELECT * FROM ${name} b WHERE ${keyOf("b", index)} AND ${doomed("b", before)})`), (before) => `DELETE FROM ${name} WHERE ${doomed(name, before)}`];
2142
2122
  };
@@ -2327,9 +2307,17 @@ const releases = defineTable({
2327
2307
  all: {
2328
2308
  eq: [],
2329
2309
  sort: ["id"]
2310
+ },
2311
+ scopes: {
2312
+ eq: [],
2313
+ sort: ["scope_key"]
2330
2314
  }
2331
2315
  }
2332
2316
  });
2317
+ const LATE_INDEXES = [{
2318
+ table: "releases",
2319
+ index: "scopes"
2320
+ }];
2333
2321
  const releaseCatalogs = defineTable({
2334
2322
  scope_key: {
2335
2323
  type: "string",
@@ -2470,9 +2458,32 @@ const nativeBuilds = defineTable({
2470
2458
  type: "string",
2471
2459
  maxLength: 255,
2472
2460
  required: false
2461
+ },
2462
+ is_store_build: { type: "boolean" },
2463
+ is_sandbox: { type: "boolean" },
2464
+ sandbox_url_scheme: {
2465
+ type: "string",
2466
+ maxLength: 255,
2467
+ ascii: true,
2468
+ required: false
2469
+ },
2470
+ export_method: {
2471
+ type: "string",
2472
+ maxLength: 16,
2473
+ required: false
2474
+ },
2475
+ native_app_version: {
2476
+ type: "string",
2477
+ required: false
2473
2478
  }
2474
2479
  }, {
2475
2480
  key: ["id"],
2481
+ derived: { store_build_scope_key: {
2482
+ type: "string",
2483
+ maxLength: 2048,
2484
+ ascii: true,
2485
+ compute: (row) => row.is_store_build ? row.scope_key : null
2486
+ } },
2476
2487
  indexes: {
2477
2488
  byScope: {
2478
2489
  eq: ["scope_key"],
@@ -2482,6 +2493,15 @@ const nativeBuilds = defineTable({
2482
2493
  eq: ["scope_key", "build_key"],
2483
2494
  sort: ["id"]
2484
2495
  },
2496
+ byScopeKind: {
2497
+ eq: ["scope_key", "artifact_kind"],
2498
+ sort: ["id"]
2499
+ },
2500
+ byStoreBuild: {
2501
+ eq: ["store_build_scope_key"],
2502
+ sort: [],
2503
+ unique: true
2504
+ },
2485
2505
  byChannel: {
2486
2506
  eq: ["channel_id"],
2487
2507
  sort: ["id"],
@@ -2493,6 +2513,96 @@ const nativeBuilds = defineTable({
2493
2513
  }
2494
2514
  }
2495
2515
  });
2516
+ const iosDevices = defineTable({
2517
+ id: {
2518
+ type: "string",
2519
+ maxLength: 36
2520
+ },
2521
+ udid: {
2522
+ type: "string",
2523
+ maxLength: 40,
2524
+ ascii: true,
2525
+ unique: true
2526
+ },
2527
+ name: {
2528
+ type: "string",
2529
+ maxLength: 100
2530
+ },
2531
+ status: {
2532
+ type: "string",
2533
+ maxLength: 16
2534
+ },
2535
+ requested_by: {
2536
+ type: "string",
2537
+ maxLength: 320,
2538
+ required: false
2539
+ },
2540
+ created_at_ms: { type: "integer" },
2541
+ approved_by: {
2542
+ type: "string",
2543
+ maxLength: 320,
2544
+ required: false
2545
+ },
2546
+ approved_at_ms: {
2547
+ type: "integer",
2548
+ required: false
2549
+ },
2550
+ registered_at_ms: {
2551
+ type: "integer",
2552
+ required: false
2553
+ },
2554
+ apple_issuer_id: {
2555
+ type: "string",
2556
+ maxLength: 64,
2557
+ ascii: true,
2558
+ required: false
2559
+ },
2560
+ apple_error: {
2561
+ type: "string",
2562
+ maxLength: 512,
2563
+ required: false
2564
+ },
2565
+ build_id: {
2566
+ type: "string",
2567
+ maxLength: 36,
2568
+ required: false
2569
+ }
2570
+ }, {
2571
+ key: ["id"],
2572
+ indexes: {
2573
+ byStatus: {
2574
+ eq: ["status"],
2575
+ sort: ["id"]
2576
+ },
2577
+ byRegistration: {
2578
+ eq: [],
2579
+ sort: ["registered_at_ms"]
2580
+ },
2581
+ all: {
2582
+ eq: [],
2583
+ sort: ["id"]
2584
+ }
2585
+ }
2586
+ });
2587
+ const iosDeviceAccount = defineTable({
2588
+ id: {
2589
+ type: "string",
2590
+ maxLength: 16,
2591
+ ascii: true
2592
+ },
2593
+ apple_issuer_id: {
2594
+ type: "string",
2595
+ maxLength: 64,
2596
+ ascii: true
2597
+ },
2598
+ claimed_at_ms: { type: "integer" }
2599
+ }, {
2600
+ key: ["id"],
2601
+ indexes: { all: {
2602
+ eq: [],
2603
+ sort: ["id"]
2604
+ } }
2605
+ });
2496
2606
  const coreModule = {
2497
2607
  id: "core",
2498
2608
  schema: {
@@ -2512,7 +2622,9 @@ const coreModule = {
2512
2622
  sort: []
2513
2623
  } }
2514
2624
  }),
2515
- native_builds: nativeBuilds
2625
+ native_builds: nativeBuilds,
2626
+ ios_devices: iosDevices,
2627
+ ios_device_account: iosDeviceAccount
2516
2628
  }
2517
2629
  };
2518
2630
  //#endregion
@@ -2533,6 +2645,90 @@ const refuseV0Database = (adapterName, stored) => {
2533
2645
  if (typeof version !== "string" || stored.has("schema.engine")) return;
2534
2646
  throw new HotUpdaterSchemaMigrationRequiredError(adapterName, version);
2535
2647
  };
2648
+ const compareVersions = (left, right) => {
2649
+ const parse = (version) => /^\d+(?:\.\d+)*$/u.test(version) ? version.split(".").map(Number) : [NaN];
2650
+ const [a, b] = [parse(left), parse(right)];
2651
+ if ([...a, ...b].some(Number.isNaN)) return NaN;
2652
+ for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
2653
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
2654
+ if (difference !== 0) return difference;
2655
+ }
2656
+ return 0;
2657
+ };
2658
+ const DEFAULT_ORDERED_SETTINGS = ["schema.core"];
2659
+ const refuseNewerSchema = (adapterName, stored, settings, ordered = DEFAULT_ORDERED_SETTINGS) => {
2660
+ const newer = ordered.flatMap((key) => {
2661
+ const found = stored.get(key);
2662
+ const expected = settings[key];
2663
+ return typeof found === "string" && expected !== void 0 && compareVersions(found, expected) > 0 ? [{
2664
+ key,
2665
+ found,
2666
+ expected
2667
+ }] : [];
2668
+ });
2669
+ const core = newer.find(({ key }) => key === "schema.core");
2670
+ if (core === void 0) return;
2671
+ 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.`);
2672
+ };
2673
+ const settingsOperation = (stored, changed) => ({
2674
+ type: "custom",
2675
+ description: `Record ${changed.map(([key, value]) => {
2676
+ const found = stored.get(key);
2677
+ return typeof found === "string" ? `${key} ${found} → ${value}` : `${key} ${value}`;
2678
+ }).join(", ")}`
2679
+ });
2680
+ //#endregion
2681
+ //#region ../plugin-core/dist/engine/db/schemaSettings.mjs
2682
+ const storedSettings = async (adapter, keys) => {
2683
+ const rows = await readSettings(adapter, keys);
2684
+ return new Map(keys.map((key, position) => [key, rows[position] ?? null]));
2685
+ };
2686
+ const writeSchemaSettings = async (adapter, adapterName, settings, ordered) => {
2687
+ const stored = await storedSettings(adapter, Object.keys(settings));
2688
+ refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
2689
+ const ops = Object.entries(settings).flatMap(([key, value]) => {
2690
+ const row = stored.get(key);
2691
+ if (row === null || row === void 0) return [{
2692
+ type: "insert",
2693
+ table: SETTINGS_TABLE,
2694
+ row: {
2695
+ key,
2696
+ value,
2697
+ _v: 0
2698
+ }
2699
+ }];
2700
+ if (row.value === value) return [];
2701
+ return [{
2702
+ type: "patch",
2703
+ table: SETTINGS_TABLE,
2704
+ key: [key],
2705
+ set: { value },
2706
+ guard: { v: Number(row._v) },
2707
+ previous: row
2708
+ }];
2709
+ });
2710
+ if (ops.length === 0) return;
2711
+ if (!(await adapter.write(ops)).ok) throw new Error(`${adapterName}: the schema settings changed during the migration; run it again.`);
2712
+ };
2713
+ const fillLateIndexes = async (adapter, tables, { dryRun = false } = {}) => {
2714
+ const fillIndex = adapter.migrations?.fillIndex;
2715
+ if (fillIndex === void 0) return [];
2716
+ const lacking = [];
2717
+ for (const { table: name, index } of LATE_INDEXES) {
2718
+ const table = tables.find((candidate) => candidate.name === name);
2719
+ if (table === void 0) continue;
2720
+ if (await fillIndex(table, index, { dryRun }) > 0) lacking.push(`${name}.${index}`);
2721
+ }
2722
+ return lacking;
2723
+ };
2724
+ const migrateSchema = async (adapter, adapterName, tables, settings, ordered) => {
2725
+ if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
2726
+ const stored = await storedSettings(adapter, Object.keys(settings)).catch(() => void 0);
2727
+ if (stored !== void 0) refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
2728
+ await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
2729
+ await fillLateIndexes(adapter, tables);
2730
+ await writeSchemaSettings(adapter, adapterName, settings, ordered);
2731
+ };
2536
2732
  //#endregion
2537
2733
  //#region ../plugin-core/dist/engine/database/cursor.mjs
2538
2734
  const encoder$1 = new TextEncoder();
@@ -2677,18 +2873,15 @@ const LOG_TABLES = [
2677
2873
  const LEASE_TABLE = "aggregate_lease";
2678
2874
  const LEASE = { id: "compaction" };
2679
2875
  const LEASE_MS = 3e4;
2680
- const WINDOW_MS$1 = {
2681
- log: 6e4,
2682
- memory: 15e3
2683
- };
2876
+ const WINDOW_MS$1 = 6e4;
2684
2877
  const LOG_PAGE = 200;
2878
+ const SKIP_AFTER_MS = 3e5;
2685
2879
  const GROUPS = {
2686
2880
  commit: 1,
2687
2881
  read: 8,
2688
2882
  flush: 256
2689
2883
  };
2690
2884
  const ATTEMPTS = 5;
2691
- const MAX_BUFFERED = 1e4;
2692
2885
  const log = defineTable({
2693
2886
  id: {
2694
2887
  type: "string",
@@ -2789,18 +2982,30 @@ const rewrite$1 = (change, key, current) => {
2789
2982
  previous: current
2790
2983
  };
2791
2984
  };
2792
- const compile = async (adapter, changes, shard) => {
2793
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
2985
+ const rowId = (model, key) => JSON.stringify([model.table.name, key]);
2986
+ const keysOf = (changes) => changes.map(({ key }) => [...key.slice(0, -1), 0]);
2987
+ const readCurrent = async (adapter, changes) => {
2988
+ const keys = keysOf(changes);
2794
2989
  const reads = /* @__PURE__ */ new Map();
2795
2990
  changes.forEach((change, at) => {
2796
- if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
2991
+ if (!rewrites(change)) return;
2992
+ const wanted = reads.get(change.model) ?? /* @__PURE__ */ new Map();
2993
+ wanted.set(rowId(change.model, keys[at]), keys[at]);
2994
+ reads.set(change.model, wanted);
2797
2995
  });
2798
2996
  const current = /* @__PURE__ */ new Map();
2799
- await Promise.all([...reads].map(async ([model, positions]) => {
2800
- const rows = await adapter.get(model.table, positions.map((at) => keys[at]));
2801
- positions.forEach((at, index) => current.set(at, rows[index] ?? null));
2997
+ await Promise.all([...reads].map(async ([model, wanted]) => {
2998
+ const keys = [...wanted.values()];
2999
+ const rows = await adapter.get(model.table, keys);
3000
+ keys.forEach((key, at) => {
3001
+ current.set(rowId(model, key), rows[at] ?? null);
3002
+ });
2802
3003
  }));
2803
- return changes.map((change, at) => current.has(at) ? rewrite$1(change, keys[at], current.get(at)) : increment(change, keys[at]));
3004
+ return current;
3005
+ };
3006
+ const build = (changes, current) => {
3007
+ const keys = keysOf(changes);
3008
+ return changes.map((change, at) => rewrites(change) ? rewrite$1(change, keys[at], current.get(rowId(change.model, keys[at])) ?? null) : increment(change, keys[at]));
2804
3009
  };
2805
3010
  const isOp = (op) => op !== void 0;
2806
3011
  const sleep = (attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random()));
@@ -2836,7 +3041,7 @@ const encode = async (changes) => {
2836
3041
  const zipped = await deflate(json);
2837
3042
  return zipped !== void 0 && zipped.length < json.length ? `z${zipped}` : json;
2838
3043
  };
2839
- const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS$1[mode] }, now }) => {
3044
+ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs = WINDOW_MS$1 }, now }) => {
2840
3045
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
2841
3046
  const holder = crypto.randomUUID().replaceAll("-", "");
2842
3047
  const table = (name) => schema.models.get(name).table;
@@ -2863,64 +3068,12 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
2863
3068
  }
2864
3069
  return changes;
2865
3070
  };
2866
- const apply = async (changes, shard) => {
2867
- let rest = changes;
2868
- let ops = [];
2869
- let read = true;
2870
- for (let failures = 0; rest.length > 0 && failures < ATTEMPTS;) try {
2871
- if (read) ops = await compile(adapter, rest, shard);
2872
- let size = rest.length;
2873
- const chunk = () => ops.slice(0, size).filter(isOp);
2874
- while (size > 1 && !adapter.fits(chunk())) size = Math.ceil(size / 2);
2875
- let result = { ok: true };
2876
- if (chunk().length > 0) result = await adapter.write(chunk()).catch((error) => {
2877
- warn("flush")(error);
2878
- return { ok: true };
2879
- });
2880
- read = !result.ok && !("retry" in result);
2881
- if (result.ok) {
2882
- rest = rest.slice(size);
2883
- ops = ops.slice(size);
2884
- failures = 0;
2885
- } else {
2886
- failures += 1;
2887
- if (!read) await sleep(failures);
2888
- }
2889
- } catch (error) {
2890
- warn("flush")(error);
2891
- return rest;
2892
- }
2893
- return rest;
2894
- };
2895
- let buffer = /* @__PURE__ */ new Map();
2896
- let timer;
2897
- let flushing;
2898
- const shards = /* @__PURE__ */ new Map();
2899
- const processShard = (model) => {
2900
- if (!shards.has(model)) shards.set(model, Math.floor(Math.random() * shapeOf(model).shards));
2901
- return shards.get(model);
2902
- };
2903
- const schedule = () => {
2904
- if (timer !== void 0 || buffer.size === 0) return;
2905
- timer = setTimeout(() => {
2906
- timer = void 0;
2907
- flushBuffer();
2908
- }, windowMs);
2909
- timer.unref?.();
2910
- };
2911
- const flushBuffer = () => flushing ??= (async () => {
2912
- clearTimeout(timer);
2913
- timer = void 0;
2914
- const pending = [...buffer.values()];
2915
- buffer = /* @__PURE__ */ new Map();
2916
- mergeAll(buffer, await apply(pending, processShard));
2917
- })().catch(warn("flush")).finally(() => {
2918
- flushing = void 0;
2919
- schedule();
2920
- });
2921
3071
  let nextDue = 0;
2922
3072
  let compacting;
2923
3073
  const known = /* @__PURE__ */ new Map();
3074
+ const skipped = LOG_TABLES.map(() => void 0);
3075
+ const past = (shard) => skipped[shard] === void 0 ? {} : { range: { gt: skipped[shard] } };
3076
+ const stampOf = (id) => Number.parseInt(id.slice(0, 9), 36);
2924
3077
  const idOf = (shard, id) => JSON.stringify([shard, id]);
2925
3078
  const leaseOp = (held, set) => {
2926
3079
  const next = {
@@ -3024,14 +3177,22 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3024
3177
  logs: (await Promise.all(LOG_TABLES.map(async (name, shard) => {
3025
3178
  const page = await engine.reads.findMany(name, {
3026
3179
  index: "oldest",
3027
- limit: LOG_PAGE
3180
+ limit: LOG_PAGE,
3181
+ ...past(shard)
3028
3182
  });
3029
3183
  more ||= page.next !== void 0;
3030
- return (await Promise.all(page.rows.map(async (row) => ({
3184
+ const decoded = await Promise.all(page.rows.map(async (row) => ({
3031
3185
  shard,
3032
3186
  row,
3033
3187
  changes: await decode(String(row.changes))
3034
- })))).flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
3188
+ })));
3189
+ const settled = now() - SKIP_AFTER_MS;
3190
+ for (const { row, changes } of decoded) {
3191
+ const id = String(row.id);
3192
+ if (changes !== void 0 || stampOf(id) >= settled) break;
3193
+ skipped[shard] = id;
3194
+ }
3195
+ return decoded.flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
3035
3196
  ...entry,
3036
3197
  changes
3037
3198
  }]);
@@ -3039,14 +3200,15 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3039
3200
  more
3040
3201
  };
3041
3202
  };
3042
- const rowsFor = async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp);
3043
3203
  const applyGroup = async (held, logs) => {
3204
+ const current = await readCurrent(adapter, logs.flatMap((entry) => [...entry.changes.values()]));
3205
+ const rowsFor = (changes) => build(changes, current).filter(isOp);
3044
3206
  for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
3045
3207
  const batch = logs.slice(0, count);
3046
3208
  const changes = mergeAll(/* @__PURE__ */ new Map(), batch.flatMap((entry) => [...entry.changes.values()]));
3047
3209
  const applied = batch.map(({ shard, row }) => [shard, row.id]);
3048
3210
  const lease = leaseOp(held, { applied: JSON.stringify(applied) });
3049
- const ops = [...await rowsFor([...changes.values()]), lease.op];
3211
+ const ops = [...rowsFor([...changes.values()]), lease.op];
3050
3212
  if (!adapter.fits(ops)) continue;
3051
3213
  for (const { shard, row } of batch) known.set(idOf(shard, row.id), row);
3052
3214
  return await commit(ops) ? {
@@ -3068,7 +3230,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3068
3230
  };
3069
3231
  const lease = leaseOp(held, {});
3070
3232
  const ops = [
3071
- ...await rowsFor(entries.slice(0, take)),
3233
+ ...rowsFor(entries.slice(0, take)),
3072
3234
  kept,
3073
3235
  lease.op
3074
3236
  ];
@@ -3084,11 +3246,12 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3084
3246
  if (held === void 0) return;
3085
3247
  let pending = true;
3086
3248
  let clear = false;
3249
+ let carried;
3087
3250
  try {
3088
3251
  for (let group = 0;; group += 1) {
3089
3252
  clear = await deleteApplied(held);
3090
3253
  if (!clear || !pending || group === groups) break;
3091
- const { logs, more } = await readLogs();
3254
+ const { logs, more } = carried ?? await readLogs();
3092
3255
  if (logs.length === 0) {
3093
3256
  pending = false;
3094
3257
  break;
@@ -3096,6 +3259,11 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3096
3259
  const applied = await applyGroup(held, logs);
3097
3260
  if (applied === void 0) break;
3098
3261
  [held, clear] = [applied.held, false];
3262
+ const rest = applied.count === 0 ? [] : logs.slice(applied.count);
3263
+ carried = rest.length > 0 ? {
3264
+ logs: rest,
3265
+ more
3266
+ } : void 0;
3099
3267
  pending = more || applied.count < logs.length;
3100
3268
  }
3101
3269
  } finally {
@@ -3113,25 +3281,13 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3113
3281
  compacting = void 0;
3114
3282
  });
3115
3283
  let checking;
3116
- const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name) => engine.reads.findMany(name, {
3284
+ const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name, shard) => engine.reads.findMany(name, {
3117
3285
  index: "oldest",
3118
- limit: 1
3286
+ limit: 1,
3287
+ ...past(shard)
3119
3288
  }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
3120
3289
  checking = void 0;
3121
3290
  });
3122
- const committed = async (changes) => {
3123
- if (mode === "log") {
3124
- if (now() >= nextDue) await compact(false, GROUPS.commit);
3125
- return;
3126
- }
3127
- mergeAll(buffer, changes.values());
3128
- schedule();
3129
- if (buffer.size >= MAX_BUFFERED) await flushBuffer();
3130
- };
3131
- const flush = async () => {
3132
- await flushBuffer();
3133
- if (mode === "log" && await hasPending()) await compact(true, GROUPS.flush);
3134
- };
3135
3291
  return {
3136
3292
  async transaction(fn) {
3137
3293
  let changes = /* @__PURE__ */ new Map();
@@ -3157,7 +3313,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3157
3313
  aggregate
3158
3314
  });
3159
3315
  if (failure) throw failure.error;
3160
- if (mode === "log" && attempt.size > 0) {
3316
+ if (attempt.size > 0) {
3161
3317
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
3162
3318
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
3163
3319
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -3171,24 +3327,18 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3171
3327
  open = false;
3172
3328
  }
3173
3329
  });
3174
- if (changes.size > 0) await committed(changes);
3330
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
3175
3331
  return result;
3176
3332
  },
3177
3333
  async beforeRead(name) {
3178
3334
  if (!isBatched(schema.models.get(name))) return;
3179
- if (buffer.size > 0 || flushing !== void 0) await flushBuffer();
3180
- if (mode === "log") {
3181
- if (await hasPending().catch((error) => {
3182
- warn("read")(error);
3183
- return false;
3184
- })) await compact(true, GROUPS.read);
3185
- }
3335
+ if (await hasPending().catch((error) => {
3336
+ warn("read")(error);
3337
+ return false;
3338
+ })) await compact(true, GROUPS.read);
3186
3339
  },
3187
- flush,
3188
- async dispose() {
3189
- clearTimeout(timer);
3190
- timer = void 0;
3191
- await flush();
3340
+ async flush() {
3341
+ if (await hasPending()) await compact(true, GROUPS.flush);
3192
3342
  }
3193
3343
  };
3194
3344
  };
@@ -3307,7 +3457,8 @@ const fieldProblems = (definition, add) => {
3307
3457
  else if (field.required === false) add(`key field "${name}" is nullable`);
3308
3458
  else if (field.type === "json") add(`key field "${name}" is json`);
3309
3459
  }
3310
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
3460
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
3461
+ for (const [name, { type, maxLength, ascii }] of bounded) {
3311
3462
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
3312
3463
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
3313
3464
  }
@@ -3419,11 +3570,13 @@ const resolveSchema = (modules) => {
3419
3570
  ...maxLength === void 0 ? {} : { maxLength },
3420
3571
  ...ascii ? { ascii } : {}
3421
3572
  }));
3422
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
3573
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
3423
3574
  name: field,
3424
3575
  type,
3425
3576
  nullable: true,
3426
- ...multi ? { multi } : {}
3577
+ ...multi ? { multi } : {},
3578
+ ...maxLength === void 0 ? {} : { maxLength },
3579
+ ...ascii ? { ascii } : {}
3427
3580
  });
3428
3581
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
3429
3582
  name: metric,
@@ -3460,22 +3613,27 @@ const createEngineMigrator = (options) => {
3460
3613
  const makeResult = async (migrate = {}) => {
3461
3614
  const stored = await options.readSettings();
3462
3615
  refuseV0Database(options.adapterName, stored);
3463
- if (Object.entries(options.settings).every(([key, value]) => stored.get(key) === value)) return getEmptyMigrationResult();
3616
+ refuseNewerSchema(options.adapterName, stored, options.settings, options.ordered);
3617
+ const changed = Object.entries(options.settings).filter(([key, value]) => stored.get(key) !== value);
3618
+ if (changed.length === 0) {
3619
+ const lacking = await fillLateIndexes(options.adapter, options.schema.tables, { dryRun: true });
3620
+ if (lacking.length === 0) return getEmptyMigrationResult();
3621
+ return {
3622
+ operations: [{
3623
+ type: "custom",
3624
+ description: `Write the index items rows lack: ${lacking.join(", ")}`
3625
+ }],
3626
+ execute: async () => {
3627
+ await fillLateIndexes(options.adapter, options.schema.tables);
3628
+ }
3629
+ };
3630
+ }
3464
3631
  return {
3465
- operations: [...options.schema.tables.map((table) => ({
3466
- type: "create-table",
3467
- value: {
3468
- ormName: table.name,
3469
- columns: Object.fromEntries(table.columns.map((column) => [column.name, {
3470
- ormName: column.name,
3471
- type: column.type
3472
- }]))
3473
- }
3474
- })), ...migrate.updateSettings === false ? [] : [{
3632
+ operations: [{
3475
3633
  type: "custom",
3476
- description: `Write the schema settings: ${Object.keys(options.settings).join(", ")}`
3477
- }]],
3478
- execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings)
3634
+ description: "Create the tables and indexes the database lacks"
3635
+ }, ...migrate.updateSettings === false ? [] : [settingsOperation(stored, changed)]],
3636
+ execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings, options.ordered)
3479
3637
  };
3480
3638
  };
3481
3639
  return {
@@ -3503,7 +3661,8 @@ const coreSettings = {
3503
3661
  };
3504
3662
  const coreTarget = {
3505
3663
  schema: coreSchema,
3506
- settings: coreSettings
3664
+ settings: coreSettings,
3665
+ ordered: ["schema.core"]
3507
3666
  };
3508
3667
  resolveSchema([aggregateBatchingModule]).tables;
3509
3668
  const pluginSettings = (plugins) => Object.fromEntries(plugins.map(({ id, schemaVersion }) => [`schema.${id}`, schemaVersion]));
@@ -3514,11 +3673,12 @@ const pluginModule = ({ id, schema, namespace }) => ({
3514
3673
  });
3515
3674
  const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBatching, retry, readSettings: readStored }) => {
3516
3675
  const fenced = withSchemaFence(adapter, name, coreSettings);
3517
- const createMigrator = ({ schema, settings } = coreTarget) => createEngineMigrator({
3676
+ const createMigrator = ({ schema, settings, ordered } = coreTarget) => createEngineMigrator({
3518
3677
  adapterName: name,
3519
3678
  adapter,
3520
3679
  schema,
3521
3680
  settings,
3681
+ ordered,
3522
3682
  readSettings: readStored ?? (async () => {
3523
3683
  const rows = await readSettings(adapter, Object.keys(settings)).catch((error) => {
3524
3684
  if (isMissingSchemaError(error)) return [];
@@ -3541,6 +3701,11 @@ const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBa
3541
3701
  //#region ../plugin-core/dist/engine/database/engineTransaction.mjs
3542
3702
  var StaleReadError = class extends Error {};
3543
3703
  const idOf = (table, key) => JSON.stringify([table, key]);
3704
+ const versionsOf = (ops) => JSON.stringify(ops.map((op) => op.type === "insert" ? [op.table.name, rowKey(op.table, op.row)] : [
3705
+ op.table.name,
3706
+ op.key,
3707
+ "guard" in op ? op.guard?.v : void 0
3708
+ ]));
3544
3709
  const versionOf = (row) => Number(row["_v"]);
3545
3710
  const isKeyed = (value) => value !== null && value !== void 0;
3546
3711
  const misuse = (table, message) => new DatabaseTransactionError(`${table}: ${message}`);
@@ -3872,7 +4037,9 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
3872
4037
  assertOutsideTransaction();
3873
4038
  let run;
3874
4039
  let negative;
3875
- for (let round = 0; round < attempts; round += 1) {
4040
+ let failures = 0;
4041
+ let lost;
4042
+ for (let round = 0;; round += 1) {
3876
4043
  const delay = round && Math.min(maxDelayMs, baseDelayMs * 2 ** (round - 1));
3877
4044
  if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay / 2 + Math.random() * (delay / 2)));
3878
4045
  run ??= await attempt(fn).catch((error) => {
@@ -3881,6 +4048,8 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
3881
4048
  });
3882
4049
  if (run === void 0) {
3883
4050
  onRetry?.("rerun", round + 1);
4051
+ lost = void 0;
4052
+ if ((failures += 1) >= attempts) break;
3884
4053
  continue;
3885
4054
  }
3886
4055
  let aggregates;
@@ -3891,8 +4060,14 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
3891
4060
  negative = error;
3892
4061
  onRetry?.("rerun", round + 1);
3893
4062
  run = void 0;
4063
+ lost = void 0;
4064
+ if ((failures += 1) >= attempts) break;
3894
4065
  continue;
3895
4066
  }
4067
+ const versions = versionsOf(aggregates);
4068
+ if (lost !== void 0 && versions !== lost) failures -= 1;
4069
+ lost = void 0;
4070
+ if (failures >= attempts) break;
3896
4071
  const ops = [...run.ops, ...aggregates];
3897
4072
  if (ops.length <= 1 && ops.every(({ type }) => type === "check")) return run.result;
3898
4073
  if (!adapter.fits(ops)) throw new DatabaseConstraintError("too_large", ops[0].table.name);
@@ -3906,12 +4081,16 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
3906
4081
  const failed = "failedOp" in outcome ? outcome.failedOp : void 0;
3907
4082
  if (failed === void 0 || failed >= run.ops.length) {
3908
4083
  onRetry?.("resend", round + 1);
4084
+ failures += 1;
4085
+ if (failed !== void 0) lost = versions;
4086
+ else if (failures >= attempts) break;
3909
4087
  continue;
3910
4088
  }
3911
4089
  const reason = await classify(ops[failed], run.read);
3912
4090
  if (reason) throw new DatabaseConstraintError(reason, ops[failed].table.name);
3913
4091
  onRetry?.("rerun", round + 1);
3914
4092
  run = void 0;
4093
+ if ((failures += 1) >= attempts) break;
3915
4094
  }
3916
4095
  throw negative ?? new DatabaseConflictError(`The transaction conflicted ${attempts} times.`);
3917
4096
  } };
@@ -4147,9 +4326,6 @@ const createDatabaseEngine = ({ batching, now = Date.now, meter, ...options }) =
4147
4326
  flush: async () => {
4148
4327
  await batches?.flush();
4149
4328
  },
4150
- dispose: async () => {
4151
- await batches?.dispose();
4152
- },
4153
4329
  database(module) {
4154
4330
  const name = (model) => module.namespace ? `${module.namespace}_${model}` : model;
4155
4331
  return {
@@ -4217,8 +4393,7 @@ const createEngine = (database, { plugins = [], now = Date.now } = {}) => {
4217
4393
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
4218
4394
  return engine.database(module);
4219
4395
  },
4220
- flush: () => engine.flush(),
4221
- dispose: () => engine.dispose()
4396
+ flush: () => engine.flush()
4222
4397
  };
4223
4398
  };
4224
4399
  //#endregion
@@ -4306,19 +4481,19 @@ const createSqlAdapter = ({ executor, tablePrefix = "", maxOps = 1e3, maxParams
4306
4481
  const where = (bind, key, v) => `${keyMatch(bind, table, key)}${v === void 0 ? "" : ` AND ${version} = ${bind(v)}`}${when ? ` AND ${when(bind)}` : ""}`;
4307
4482
  const insert = (bind, into, columns, values) => `INSERT INTO ${into} (${columns.map(quote).join(", ")}) ${when ? `SELECT ${values.join(", ")} WHERE ${when(bind)}` : `VALUES (${values.join(", ")})`}`;
4308
4483
  const insertRow = (bind, row) => insert(bind, name, table.columns.map((column) => column.name), table.columns.map((column) => bind(row[column.name], column)));
4309
- const entries = (key, row, changed) => table.indexes.flatMap((index) => {
4484
+ const entries = (key, row, changed, stale = true) => table.indexes.flatMap((index) => {
4310
4485
  const columns = [...index.eq, ...indexOrderColumns(table, index)];
4311
4486
  if (!isMultiIndex(table, index) || changed && !columns.some((column) => changed.includes(column))) return [];
4312
4487
  const into = tableOf(table, index);
4313
4488
  const found = row ? indexEntries(table, index, row) : [];
4314
4489
  const order = found.length > 0 ? indexOrderTuple(table, index, row) : [];
4315
- return [sql((bind) => `DELETE FROM ${into} WHERE ${where(bind, key)}`), ...found.map((eq) => sql((bind) => {
4490
+ return [...stale ? [sql((bind) => `DELETE FROM ${into} WHERE ${where(bind, key)}`)] : [], ...found.map((eq) => sql((bind) => {
4316
4491
  const values = [...eq, ...order].map((value) => bind(value));
4317
4492
  return insert(bind, into, columns, values);
4318
4493
  }))];
4319
4494
  });
4320
4495
  switch (op.type) {
4321
- case "insert": return [sql((bind) => insertRow(bind, op.row)), ...entries(rowKey(table, op.row), op.row)];
4496
+ case "insert": return [sql((bind) => insertRow(bind, op.row)), ...entries(rowKey(table, op.row), op.row, void 0, false)];
4322
4497
  case "patch": return [sql((bind) => {
4323
4498
  const set = Object.entries(op.set).map(([column, value]) => `${quote(column)} = ${bind(value, findPhysicalColumn(table, column))}`);
4324
4499
  return `UPDATE ${name} SET ${[...set, `${version} = ${version} + 1`].join(", ")} WHERE ${where(bind, op.key, op.guard.v)}`;
@@ -17698,7 +17873,7 @@ const postgres = (config) => {
17698
17873
  };
17699
17874
  //#endregion
17700
17875
  //#region ../../packages/server/dist/version.mjs
17701
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.5";
17876
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.50";
17702
17877
  //#endregion
17703
17878
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
17704
17879
  const createVersionRouteHandlers = (plugins = []) => {
@@ -17824,9 +17999,14 @@ const releaseCatalogScopeKeyOf = (input) => input.strategy === "APP_VERSION" ? c
17824
17999
  platform: input.platform,
17825
18000
  strategy: "FINGERPRINT"
17826
18001
  });
17827
- const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
17828
- 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;
17829
- const compiled = parseCompiledCatalog(row.payload, input.strategy);
18002
+ const parseReleaseCatalogRow = ({ payload, ...row }) => ({
18003
+ row,
18004
+ compiled: parseCompiledCatalog(payload, row.strategy)
18005
+ });
18006
+ const projectParsedReleaseCatalogRow = (parsed, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
18007
+ if (parsed === null) return null;
18008
+ const { row, compiled } = parsed;
18009
+ 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;
17830
18010
  const appVersion = input.strategy === "APP_VERSION" ? input.appVersion : void 0;
17831
18011
  return {
17832
18012
  catalogId: row.catalog_id,
@@ -17839,6 +18019,7 @@ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyO
17839
18019
  scopeKey
17840
18020
  };
17841
18021
  };
18022
+ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => projectParsedReleaseCatalogRow(row === null ? null : parseReleaseCatalogRow(row), input, scopeKey);
17842
18023
  //#endregion
17843
18024
  //#region ../../packages/server/dist/db/updateArtifacts.mjs
17844
18025
  const HBC_ASSET_PATH_RE = /\.bundle$/;
@@ -18431,8 +18612,8 @@ const baseBundleIdsOf = (row, range, bundleId, limit) => {
18431
18612
  //#endregion
18432
18613
  //#region ../../packages/server/dist/core/reads.mjs
18433
18614
  const PAGE$3 = 500;
18434
- const pick$1 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
18435
- const toBundleRow = pick$1([
18615
+ const pick$2 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
18616
+ const toBundleRow = pick$2([
18436
18617
  "id",
18437
18618
  "platform",
18438
18619
  "git_commit_hash",
@@ -18441,7 +18622,7 @@ const toBundleRow = pick$1([
18441
18622
  "manifest_file_hash",
18442
18623
  "asset_base_storage_uri"
18443
18624
  ]);
18444
- const toPatchRow = pick$1([
18625
+ const toPatchRow = pick$2([
18445
18626
  "id",
18446
18627
  "bundle_id",
18447
18628
  "base_bundle_id",
@@ -18451,7 +18632,7 @@ const toPatchRow = pick$1([
18451
18632
  "byte_size",
18452
18633
  "order_index"
18453
18634
  ]);
18454
- const toReleaseRow = pick$1([
18635
+ const toReleaseRow = pick$2([
18455
18636
  "id",
18456
18637
  "revision",
18457
18638
  "scope_key",
@@ -18472,7 +18653,7 @@ const toReleaseRow = pick$1([
18472
18653
  "created_at_ms",
18473
18654
  "updated_at_ms"
18474
18655
  ]);
18475
- const toCatalogRow = pick$1([
18656
+ const toCatalogRow = pick$2([
18476
18657
  "scope_key",
18477
18658
  "catalog_id",
18478
18659
  "strategy",
@@ -18487,7 +18668,7 @@ const toCatalogRow = pick$1([
18487
18668
  "is_tombstone",
18488
18669
  "updated_at_ms"
18489
18670
  ]);
18490
- const toChannelRow = pick$1(["id", "name"]);
18671
+ const toChannelRow = pick$2(["id", "name"]);
18491
18672
  const drain$1 = async (read) => {
18492
18673
  const rows = [];
18493
18674
  let cursor;
@@ -18498,7 +18679,14 @@ const drain$1 = async (read) => {
18498
18679
  } while (cursor !== void 0);
18499
18680
  return rows;
18500
18681
  };
18501
- const after = (input) => input.after === void 0 ? {} : { range: (input.order ?? "asc") === "asc" ? { gt: input.after } : { lt: input.after } };
18682
+ const after = (input) => {
18683
+ const asc = (input.order ?? "asc") === "asc";
18684
+ const range = {
18685
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
18686
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
18687
+ };
18688
+ return Object.keys(range).length === 0 ? {} : { range };
18689
+ };
18502
18690
  const createCoreReads = (db, storage) => {
18503
18691
  const detail = async (row) => {
18504
18692
  const count = row._refs_bundle_patches_bundle_id ?? 0;
@@ -18674,7 +18862,29 @@ const createCoreReads = (db, storage) => {
18674
18862
  ...after(input)
18675
18863
  })).rows.map(toCatalogRow);
18676
18864
  },
18677
- async listChannels() {
18865
+ async listReleaseScopeKeys(input) {
18866
+ const scopeKeys = [];
18867
+ for (let last = input.after ?? ""; scopeKeys.length < input.limit;) {
18868
+ const { rows } = await db.findMany("releases", {
18869
+ index: "scopes",
18870
+ where: {},
18871
+ limit: 1,
18872
+ range: { gt: last }
18873
+ });
18874
+ if (rows[0] === void 0) break;
18875
+ last = rows[0].scope_key;
18876
+ scopeKeys.push(last);
18877
+ }
18878
+ return scopeKeys;
18879
+ },
18880
+ async listChannels(input) {
18881
+ if (input !== void 0) return (await db.findMany("channels", {
18882
+ index: "all",
18883
+ where: {},
18884
+ order: input.order ?? "asc",
18885
+ limit: input.limit,
18886
+ ...after(input)
18887
+ })).rows.map(toChannelRow);
18678
18888
  return (await drain$1((page) => db.findMany("channels", {
18679
18889
  index: "all",
18680
18890
  where: {},
@@ -18682,6 +18892,11 @@ const createCoreReads = (db, storage) => {
18682
18892
  ...page
18683
18893
  }))).map(toChannelRow);
18684
18894
  },
18895
+ async getChannels(ids) {
18896
+ const unique = [...new Set(ids)];
18897
+ if (unique.length === 0) return [];
18898
+ return (await db.findByKeys("channels", unique.map((id) => ({ id })))).flatMap((row) => row ? [toChannelRow(row)] : []);
18899
+ },
18685
18900
  async findChannelByName(name) {
18686
18901
  const row = await db.findOne("channels", { name });
18687
18902
  return row === null ? null : toChannelRow(row);
@@ -18689,51 +18904,335 @@ const createCoreReads = (db, storage) => {
18689
18904
  };
18690
18905
  };
18691
18906
  //#endregion
18692
- //#region ../../packages/server/dist/core/writes.mjs
18693
- const PAGE$2 = 500;
18694
- const countBundle = (tx, platform, delta) => {
18695
- for (const key of [platform, "*"]) tx.aggregate("bundle_totals", { platform_key: key }, { bundles: delta });
18696
- };
18697
- const insertBundle = (tx, row) => {
18698
- tx.create("bundles", row);
18699
- countBundle(tx, row.platform, 1);
18700
- };
18701
- const updateBundle = (tx, current, set, { counted = true } = {}) => {
18702
- tx.update("bundles", current, set);
18703
- if (counted && set.platform !== void 0 && set.platform !== current.platform) {
18704
- countBundle(tx, current.platform, -1);
18705
- countBundle(tx, set.platform, 1);
18706
- }
18907
+ //#region ../../packages/server/dist/core/iosDevices.mjs
18908
+ const UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
18909
+ const normalizeIosUdid = (value) => {
18910
+ const trimmed = value.trim();
18911
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
18707
18912
  };
18708
- const deleteBundle = async (tx, current) => {
18709
- await tx.delete("bundles", current);
18710
- countBundle(tx, current.platform, -1);
18913
+ const NAME_MAX_LENGTH = 100;
18914
+ const EMAIL_MAX_LENGTH = 320;
18915
+ const ISSUER_MAX_LENGTH = 64;
18916
+ const ACCOUNT_ROW = "registry";
18917
+ const ERROR_MAX_LENGTH = 512;
18918
+ const STATUSES = [
18919
+ "pending",
18920
+ "approved",
18921
+ "registered"
18922
+ ];
18923
+ const OUTCOMES = [
18924
+ "registered",
18925
+ "refused",
18926
+ "disabled",
18927
+ "missing"
18928
+ ];
18929
+ const IOS_DEVICE_DISABLED_ERROR = "Disabled in the Apple account.";
18930
+ const IOS_DEVICE_MISSING_ERROR = "Gone from the Apple account. Approve it again to register it.";
18931
+ var IosDeviceInputError = class extends TypeError {
18932
+ name = "IosDeviceInputError";
18711
18933
  };
18712
- const replaceBundlePatches = async (tx, bundle, rows) => {
18713
- const wanted = new Map(rows.map((row) => [row.id, row]));
18714
- const count = bundle._refs_bundle_patches_bundle_id ?? 0;
18715
- let cursor;
18716
- for (let seen = 0; seen < count;) {
18717
- const page = await tx.findMany("bundle_patches", {
18718
- index: "byBundle",
18719
- where: { bundle_id: bundle.id },
18720
- limit: Math.min(count - seen, PAGE$2),
18721
- ...cursor === void 0 ? {} : { cursor }
18934
+ const pick$1 = (row) => ({
18935
+ id: row.id,
18936
+ udid: row.udid,
18937
+ name: row.name,
18938
+ status: row.status,
18939
+ requested_by: row.requested_by ?? null,
18940
+ created_at_ms: row.created_at_ms,
18941
+ approved_by: row.approved_by ?? null,
18942
+ approved_at_ms: row.approved_at_ms ?? null,
18943
+ registered_at_ms: row.registered_at_ms ?? null,
18944
+ apple_issuer_id: row.apple_issuer_id ?? null,
18945
+ apple_error: row.apple_error ?? null,
18946
+ build_id: row.build_id ?? null
18947
+ });
18948
+ const udidOf = (udid) => {
18949
+ const key = typeof udid === "string" ? normalizeIosUdid(udid) : null;
18950
+ if (key === null) throw new IosDeviceInputError("Invalid iOS device: udid must be 40 hex digits, or 8 and 16 joined by a hyphen.");
18951
+ return key;
18952
+ };
18953
+ const nameOf = (name) => {
18954
+ const trimmed = typeof name === "string" ? name.trim() : "";
18955
+ if (trimmed.length === 0 || trimmed.length > NAME_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: name must be 1 to ${NAME_MAX_LENGTH} characters.`);
18956
+ return trimmed;
18957
+ };
18958
+ const personOf = (value, field) => {
18959
+ if (value === null) return null;
18960
+ const email = typeof value === "string" ? value.trim().toLowerCase() : "";
18961
+ 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.`);
18962
+ return email;
18963
+ };
18964
+ const errorText = (text) => {
18965
+ const line = text.replace(/\s+/gu, " ").trim();
18966
+ return line.length > ERROR_MAX_LENGTH ? `${line.slice(0, 511)}…` : line;
18967
+ };
18968
+ const createIosDeviceApi = (db, { now = Date.now } = {}) => {
18969
+ const findIosDevice = async (udid) => {
18970
+ const key = normalizeIosUdid(udid);
18971
+ if (key === null) return null;
18972
+ const row = await db.findOne("ios_devices", { udid: key });
18973
+ return row === null ? null : pick$1(row);
18974
+ };
18975
+ const accountOfRows = async () => {
18976
+ const { rows } = await db.findMany("ios_devices", {
18977
+ index: "byRegistration",
18978
+ where: {},
18979
+ order: "asc",
18980
+ limit: 1,
18981
+ range: { gte: 0 }
18722
18982
  });
18723
- for (const stored of page.rows) {
18724
- const next = wanted.get(stored.id);
18725
- wanted.delete(stored.id);
18726
- if (next === void 0) {
18727
- await tx.delete("bundle_patches", stored);
18728
- continue;
18729
- }
18730
- const set = Object.fromEntries(Object.entries(next).filter(([field, value]) => field !== "id" && stored[field] !== value));
18731
- if (Object.keys(set).length > 0) tx.update("bundle_patches", stored, set);
18732
- }
18733
- seen += page.rows.length;
18734
- if (page.next === void 0) break;
18983
+ return (rows[0] === void 0 ? null : pick$1(rows[0]))?.apple_issuer_id ?? null;
18984
+ };
18985
+ return {
18986
+ async listIosDevices(input) {
18987
+ if (input.status !== void 0 && !STATUSES.includes(input.status)) throw new IosDeviceInputError(`Invalid iOS device status: ${String(input.status)}. Expected ${STATUSES.join(", ")}.`);
18988
+ const page = {
18989
+ order: input.order ?? "asc",
18990
+ limit: input.limit,
18991
+ ...after(input)
18992
+ };
18993
+ const { rows } = input.status === void 0 ? await db.findMany("ios_devices", {
18994
+ index: "all",
18995
+ where: {},
18996
+ ...page
18997
+ }) : await db.findMany("ios_devices", {
18998
+ index: "byStatus",
18999
+ where: { status: input.status },
19000
+ ...page
19001
+ });
19002
+ return rows.map(pick$1);
19003
+ },
19004
+ findIosDevice,
19005
+ async requestIosDevice(input) {
19006
+ const udid = udidOf(input.udid);
19007
+ const name = nameOf(input.name);
19008
+ const requestedBy = personOf(input.requestedBy, "requestedBy");
19009
+ const existing = await db.findOne("ios_devices", { udid });
19010
+ if (existing !== null) return {
19011
+ device: pick$1(existing),
19012
+ created: false
19013
+ };
19014
+ const device = {
19015
+ id: createUUIDv7(),
19016
+ udid,
19017
+ name,
19018
+ status: "pending",
19019
+ requested_by: requestedBy,
19020
+ created_at_ms: now(),
19021
+ approved_by: null,
19022
+ approved_at_ms: null,
19023
+ registered_at_ms: null,
19024
+ apple_issuer_id: null,
19025
+ apple_error: null,
19026
+ build_id: null
19027
+ };
19028
+ try {
19029
+ await db.transaction(async (tx) => {
19030
+ tx.create("ios_devices", device);
19031
+ });
19032
+ } catch (error) {
19033
+ if (error instanceof DatabaseConstraintError && error.reason === "unique") {
19034
+ const winner = await db.findOne("ios_devices", { udid });
19035
+ if (winner !== null) return {
19036
+ device: pick$1(winner),
19037
+ created: false
19038
+ };
19039
+ }
19040
+ throw error;
19041
+ }
19042
+ return {
19043
+ device,
19044
+ created: true
19045
+ };
19046
+ },
19047
+ async approveIosDevice(id, input) {
19048
+ const name = input.name === void 0 ? void 0 : nameOf(input.name);
19049
+ const approvedBy = personOf(input.approvedBy, "approvedBy");
19050
+ return db.transaction(async (tx) => {
19051
+ const row = await tx.findOne("ios_devices", { id });
19052
+ if (row === null) return null;
19053
+ const device = pick$1(row);
19054
+ const set = {
19055
+ ...name === void 0 || name === device.name ? {} : { name },
19056
+ ...device.status === "pending" ? {
19057
+ status: "approved",
19058
+ approved_by: approvedBy,
19059
+ approved_at_ms: now()
19060
+ } : {}
19061
+ };
19062
+ if (Object.keys(set).length === 0) return device;
19063
+ tx.update("ios_devices", row, set);
19064
+ return {
19065
+ ...device,
19066
+ ...set
19067
+ };
19068
+ });
19069
+ },
19070
+ async renameIosDevice(id, input) {
19071
+ const name = nameOf(input);
19072
+ return db.transaction(async (tx) => {
19073
+ const row = await tx.findOne("ios_devices", { id });
19074
+ if (row === null) return null;
19075
+ const device = pick$1(row);
19076
+ if (device.name === name) return device;
19077
+ tx.update("ios_devices", row, { name });
19078
+ return {
19079
+ ...device,
19080
+ name
19081
+ };
19082
+ });
19083
+ },
19084
+ async recordIosDeviceOutcome({ id, seen, issuerId, outcome, reason }) {
19085
+ if (!OUTCOMES.includes(outcome)) throw new IosDeviceInputError(`Invalid iOS device outcome: ${String(outcome)}. Expected ${OUTCOMES.join(", ")}.`);
19086
+ 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.`);
19087
+ return db.transaction(async (tx) => {
19088
+ const row = await tx.findOne("ios_devices", { id });
19089
+ if (row === null) return null;
19090
+ const device = pick$1(row);
19091
+ if (device.status !== seen.status || device.approved_at_ms !== seen.approvedAtMs || device.apple_issuer_id !== null && device.apple_issuer_id !== issuerId) return null;
19092
+ let set;
19093
+ switch (outcome) {
19094
+ case "registered":
19095
+ if (device.status === "pending") return null;
19096
+ set = {
19097
+ status: "registered",
19098
+ registered_at_ms: device.registered_at_ms ?? now(),
19099
+ apple_issuer_id: issuerId,
19100
+ apple_error: null
19101
+ };
19102
+ break;
19103
+ case "refused":
19104
+ if (device.status !== "approved") return null;
19105
+ set = { apple_error: errorText(reason === void 0 || reason.trim() === "" ? "Apple refused it." : reason) };
19106
+ break;
19107
+ case "disabled":
19108
+ if (device.status === "pending") return null;
19109
+ set = { apple_error: IOS_DEVICE_DISABLED_ERROR };
19110
+ break;
19111
+ case "missing":
19112
+ if (device.status !== "registered") return null;
19113
+ set = {
19114
+ status: "pending",
19115
+ approved_by: null,
19116
+ approved_at_ms: null,
19117
+ apple_error: IOS_DEVICE_MISSING_ERROR
19118
+ };
19119
+ }
19120
+ if (Object.entries(set).some(([column, value]) => device[column] !== (value ?? null))) tx.update("ios_devices", row, set);
19121
+ return {
19122
+ ...device,
19123
+ ...set
19124
+ };
19125
+ });
19126
+ },
19127
+ async markIosDevicesInBuild({ buildId, ids }) {
19128
+ for (const id of new Set(ids)) await db.transaction(async (tx) => {
19129
+ const row = await tx.findOne("ios_devices", { id });
19130
+ if (row === null || typeof row.build_id === "string" && row.build_id >= buildId) return;
19131
+ tx.update("ios_devices", row, { build_id: buildId });
19132
+ });
19133
+ },
19134
+ async findIosDeviceAccount() {
19135
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
19136
+ const issuerId = existing === null ? await accountOfRows() : existing.apple_issuer_id;
19137
+ return issuerId === null ? null : { issuerId };
19138
+ },
19139
+ async claimIosDeviceAccount(issuerId) {
19140
+ 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.`);
19141
+ const answer = (held) => ({
19142
+ issuerId: held,
19143
+ claimed: held === issuerId
19144
+ });
19145
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
19146
+ if (existing !== null) return answer(existing.apple_issuer_id);
19147
+ const holder = await accountOfRows() ?? issuerId;
19148
+ try {
19149
+ await db.transaction(async (tx) => {
19150
+ tx.create("ios_device_account", {
19151
+ id: ACCOUNT_ROW,
19152
+ apple_issuer_id: holder,
19153
+ claimed_at_ms: now()
19154
+ });
19155
+ });
19156
+ return answer(holder);
19157
+ } catch (error) {
19158
+ if (error instanceof DatabaseConstraintError && (error.reason === "exists" || error.reason === "unique")) {
19159
+ const winner = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
19160
+ if (winner !== null) return answer(winner.apple_issuer_id);
19161
+ }
19162
+ throw error;
19163
+ }
19164
+ },
19165
+ async deleteIosDevice(id, only) {
19166
+ const requestedBy = only?.requestedBy === void 0 ? void 0 : personOf(only.requestedBy, "requestedBy");
19167
+ return db.transaction(async (tx) => {
19168
+ const row = await tx.findOne("ios_devices", { id });
19169
+ if (row === null) return null;
19170
+ const device = pick$1(row);
19171
+ if (only?.status !== void 0 && device.status !== only.status || requestedBy !== void 0 && device.requested_by !== requestedBy) return null;
19172
+ await tx.delete("ios_devices", row);
19173
+ return device;
19174
+ });
19175
+ }
19176
+ };
19177
+ };
19178
+ //#endregion
19179
+ //#region ../../packages/server/dist/core/nativeBuildDestinations.mjs
19180
+ const NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
19181
+ android: [
19182
+ "play-internal",
19183
+ "play-closed",
19184
+ "play-open",
19185
+ "play-production"
19186
+ ],
19187
+ ios: ["testflight"]
19188
+ };
19189
+ //#endregion
19190
+ //#region ../../packages/server/dist/core/writes.mjs
19191
+ const PAGE$2 = 500;
19192
+ const countBundle = (tx, platform, delta) => {
19193
+ for (const key of [platform, "*"]) tx.aggregate("bundle_totals", { platform_key: key }, { bundles: delta });
19194
+ };
19195
+ const insertBundle = (tx, row) => {
19196
+ tx.create("bundles", row);
19197
+ countBundle(tx, row.platform, 1);
19198
+ };
19199
+ const updateBundle = (tx, current, set, { counted = true } = {}) => {
19200
+ tx.update("bundles", current, set);
19201
+ if (counted && set.platform !== void 0 && set.platform !== current.platform) {
19202
+ countBundle(tx, current.platform, -1);
19203
+ countBundle(tx, set.platform, 1);
19204
+ }
19205
+ };
19206
+ const deleteBundle = async (tx, current) => {
19207
+ await tx.delete("bundles", current);
19208
+ countBundle(tx, current.platform, -1);
19209
+ };
19210
+ const replaceBundlePatches = async (tx, bundle, rows, checkNew) => {
19211
+ const wanted = new Map(rows.map((row) => [row.id, row]));
19212
+ const count = bundle._refs_bundle_patches_bundle_id ?? 0;
19213
+ let cursor;
19214
+ for (let seen = 0; seen < count;) {
19215
+ const page = await tx.findMany("bundle_patches", {
19216
+ index: "byBundle",
19217
+ where: { bundle_id: bundle.id },
19218
+ limit: Math.min(count - seen, PAGE$2),
19219
+ ...cursor === void 0 ? {} : { cursor }
19220
+ });
19221
+ for (const stored of page.rows) {
19222
+ const next = wanted.get(stored.id);
19223
+ wanted.delete(stored.id);
19224
+ if (next === void 0) {
19225
+ await tx.delete("bundle_patches", stored);
19226
+ continue;
19227
+ }
19228
+ const set = Object.fromEntries(Object.entries(next).filter(([field, value]) => field !== "id" && stored[field] !== value));
19229
+ if (Object.keys(set).length > 0) tx.update("bundle_patches", stored, set);
19230
+ }
19231
+ seen += page.rows.length;
19232
+ if (page.next === void 0) break;
18735
19233
  cursor = page.next;
18736
19234
  }
19235
+ if (checkNew !== void 0) for (const row of wanted.values()) await checkNew(row);
18737
19236
  for (const row of wanted.values()) tx.create("bundle_patches", row);
18738
19237
  };
18739
19238
  const insertChannel = async (db, row) => {
@@ -18786,6 +19285,16 @@ const ARTIFACT_KINDS = {
18786
19285
  const SCOPE_KEY_MAX_LENGTH = 2048;
18787
19286
  const GIT_COMMIT_HASH_MAX_LENGTH = 255;
18788
19287
  const BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
19288
+ const SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
19289
+ const URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
19290
+ const APP_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;
19291
+ const FINGERPRINT_HASH = /^[A-Za-z0-9._~-]{1,255}$/;
19292
+ const DISTRIBUTIONS = {
19293
+ apk: ["direct"],
19294
+ app: ["direct"],
19295
+ aab: ["store"],
19296
+ ipa: ["direct", "store"]
19297
+ };
18789
19298
  var NativeBuildInputError = class extends TypeError {
18790
19299
  name = "NativeBuildInputError";
18791
19300
  };
@@ -18806,15 +19315,42 @@ const pick = (row) => ({
18806
19315
  build_number: row.build_number ?? null,
18807
19316
  submitted_to: row.submitted_to ?? null,
18808
19317
  submitted_at_ms: row.submitted_at_ms ?? null,
18809
- submitted_version: row.submitted_version ?? null
19318
+ submitted_version: row.submitted_version ?? null,
19319
+ is_store_build: row.is_store_build === true,
19320
+ is_sandbox: row.is_sandbox === true,
19321
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
19322
+ export_method: row.export_method ?? null,
19323
+ native_app_version: row.native_app_version ?? null
18810
19324
  });
18811
- const SUBMISSION_DESTINATIONS = {
18812
- android: "play-internal",
18813
- ios: "testflight"
18814
- };
19325
+ const EXPORT_METHODS = /* @__PURE__ */ new Set([
19326
+ "app-store",
19327
+ "ad-hoc",
19328
+ "development",
19329
+ "enterprise"
19330
+ ]);
19331
+ const OLDER_BUILDS_PAGE = 20;
19332
+ const OLDER_BUILDS_PAGES = 5;
19333
+ const MARK_ATTEMPTS = 8;
18815
19334
  const BUILD_NUMBER_MAX_LENGTH = 64;
18816
19335
  const SUBMITTED_VERSION_MAX_LENGTH = 255;
19336
+ const checkedScopeKey = (scopeKey) => {
19337
+ 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.`);
19338
+ return scopeKey;
19339
+ };
19340
+ const registeredDistribution = (kind, exportMethod) => kind !== "ipa" ? DISTRIBUTIONS[kind][0] : exportMethod === void 0 || exportMethod === null ? "unknown" : exportMethod === "app-store" ? "store" : "direct";
19341
+ const sandboxScopeKey = (scope, sandbox) => {
19342
+ const { appId, urlScheme, artifactKind, distribution } = sandbox;
19343
+ 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;
19344
+ if (problem !== null) throw new NativeBuildInputError(`Invalid sandbox build scope: ${problem}.`);
19345
+ const target = scope.fingerprintHash === null ? `app-version:${encodeURIComponent(scope.appVersion)}` : `fingerprint:${scope.fingerprintHash}`;
19346
+ return checkedScopeKey(`v1:sandbox:${scope.platform}:${appId}:${urlScheme}:${artifactKind}:${distribution}:${target}`);
19347
+ };
18817
19348
  const nativeBuildScopeKey = (scope) => {
19349
+ const { sandbox } = scope;
19350
+ if (sandbox !== void 0 && sandbox !== null) {
19351
+ if (sandbox.distribution !== "direct" && sandbox.distribution !== "store") throw new NativeBuildInputError("Invalid sandbox build scope: its distribution must be direct or store.");
19352
+ return sandboxScopeKey(scope, sandbox);
19353
+ }
18818
19354
  let scopeKey;
18819
19355
  try {
18820
19356
  const channelKey = encodeChannelKey(scope.channel);
@@ -18831,30 +19367,102 @@ const nativeBuildScopeKey = (scope) => {
18831
19367
  } catch (error) {
18832
19368
  throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
18833
19369
  }
18834
- 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.`);
18835
- return scopeKey;
19370
+ return checkedScopeKey(scopeKey);
19371
+ };
19372
+ const channelIdOf = (channel) => {
19373
+ try {
19374
+ return `channel:${encodeChannelKey(channel)}`;
19375
+ } catch (error) {
19376
+ throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
19377
+ }
19378
+ };
19379
+ const registrationScopeKey = (registration) => {
19380
+ channelIdOf(registration.channel);
19381
+ return registration.isSandbox === true ? sandboxScopeKey(registration, {
19382
+ appId: registration.sandboxAppId,
19383
+ urlScheme: registration.sandboxUrlScheme,
19384
+ artifactKind: registration.artifact.kind,
19385
+ distribution: registeredDistribution(registration.artifact.kind, registration.exportMethod)
19386
+ }) : nativeBuildScopeKey({
19387
+ ...registration,
19388
+ sandbox: null
19389
+ });
19390
+ };
19391
+ const refuseSandboxPatchBase = async (db, baseBundleId) => {
19392
+ 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.");
18836
19393
  };
18837
19394
  const isBuiltInBundle = async (db, bundleId) => await db.findOne("native_builds", { min_bundle_id: bundleId }) !== null;
18838
- const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, artifact }) => {
19395
+ const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, sandboxAppId, exportMethod, nativeAppVersion, artifact }) => {
18839
19396
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
18840
19397
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
18841
19398
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
18842
19399
  if (channel.trim().length === 0) return "channel is required";
19400
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
19401
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
19402
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
19403
+ 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`;
19404
+ }
19405
+ if (sandboxAppId !== void 0 && sandboxAppId !== null) {
19406
+ if (isSandbox !== true) return "sandboxAppId is a sandbox build's, and this isn't one";
19407
+ if (typeof sandboxAppId !== "string" || !APP_ID.test(sandboxAppId)) return "sandboxAppId must be the artifact's bundle identifier or application ID, up to 255 characters";
19408
+ }
19409
+ if (isSandbox === true) {
19410
+ if (sandboxUrlScheme === void 0 || sandboxUrlScheme === null) return "a sandbox build needs the sandboxUrlScheme its artifact registers";
19411
+ 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";
19412
+ }
18843
19413
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
18844
19414
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
18845
19415
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
18846
19416
  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`;
19417
+ if (nativeAppVersion !== void 0 && nativeAppVersion !== null && (typeof nativeAppVersion !== "string" || nativeAppVersion.trim().length === 0)) return "nativeAppVersion must be the artifact's app version, or null";
18847
19418
  const kinds = ARTIFACT_KINDS[platform];
18848
19419
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
19420
+ if (exportMethod !== void 0 && exportMethod !== null) {
19421
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
19422
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
19423
+ }
18849
19424
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
18850
19425
  return null;
18851
19426
  };
19427
+ const SIBLING_KINDS = {
19428
+ app: "ipa",
19429
+ ipa: "app"
19430
+ };
19431
+ 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");
19432
+ const siblingSandboxScopeKey = (build, artifactKind) => {
19433
+ const [version, sandbox, platform, appId, urlScheme] = build.scope_key.split(":");
19434
+ if (version !== "v1" || sandbox !== "sandbox" || platform !== build.platform || appId === void 0 || urlScheme === void 0) return null;
19435
+ const target = build.fingerprint_hash === null ? {
19436
+ platform: build.platform,
19437
+ fingerprintHash: null,
19438
+ appVersion: build.app_version ?? ""
19439
+ } : {
19440
+ platform: build.platform,
19441
+ fingerprintHash: build.fingerprint_hash,
19442
+ appVersion: null
19443
+ };
19444
+ try {
19445
+ return sandboxScopeKey(target, {
19446
+ appId,
19447
+ urlScheme,
19448
+ artifactKind: build.artifact_kind,
19449
+ distribution: registeredDistribution(build.artifact_kind, build.export_method)
19450
+ }) === build.scope_key ? sandboxScopeKey(target, {
19451
+ appId,
19452
+ urlScheme,
19453
+ artifactKind,
19454
+ distribution: "direct"
19455
+ }) : null;
19456
+ } catch {
19457
+ return null;
19458
+ }
19459
+ };
18852
19460
  const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18853
19461
  async registerNativeBuild(registration) {
18854
19462
  const problem = problemOf(registration);
18855
19463
  if (problem !== null) throw new NativeBuildInputError(`Invalid native build: ${problem}.`);
18856
- const scopeKey = nativeBuildScopeKey(registration);
18857
- const channelId = `channel:${encodeChannelKey(registration.channel)}`;
19464
+ const scopeKey = registrationScopeKey(registration);
19465
+ const channelId = channelIdOf(registration.channel);
18858
19466
  const { embeddedBundle } = registration;
18859
19467
  const row = {
18860
19468
  id: registration.id,
@@ -18873,7 +19481,12 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18873
19481
  build_number: registration.buildNumber ?? null,
18874
19482
  submitted_to: null,
18875
19483
  submitted_at_ms: null,
18876
- submitted_version: null
19484
+ submitted_version: null,
19485
+ is_store_build: false,
19486
+ is_sandbox: registration.isSandbox === true,
19487
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
19488
+ export_method: registration.exportMethod ?? null,
19489
+ native_app_version: registration.nativeAppVersion ?? null
18877
19490
  };
18878
19491
  for (let attempt = 1;; attempt += 1) {
18879
19492
  await insertChannel(db, {
@@ -18907,25 +19520,82 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18907
19520
  const row = await db.findOne("native_builds", { id });
18908
19521
  return row === null ? null : pick(row);
18909
19522
  },
19523
+ async findNativeBuildByBuiltInBundle(bundleId) {
19524
+ const row = await db.findOne("native_builds", { min_bundle_id: bundleId });
19525
+ return row === null ? null : pick(row);
19526
+ },
18910
19527
  async findNativeBuild(scope, options) {
18911
19528
  const scopeKey = nativeBuildScopeKey(scope);
18912
19529
  const buildKey = options?.buildKey;
18913
19530
  if (buildKey !== void 0 && !BUILD_KEY.test(buildKey)) throw new NativeBuildInputError("Invalid native build key: it must be nbk1: and a SHA-256.");
18914
- const { rows } = buildKey === void 0 ? await db.findMany("native_builds", {
19531
+ const artifactKind = options?.artifactKind;
19532
+ 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 ")}.`);
19533
+ const ofKind = (row) => artifactKind === void 0 || row.artifact_kind === artifactKind;
19534
+ if (options?.storeBuild) {
19535
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
19536
+ return marked === null || !ofKind(marked) ? null : pick(marked);
19537
+ }
19538
+ const read = (limit, before) => {
19539
+ const page = {
19540
+ order: "desc",
19541
+ limit,
19542
+ ...before === void 0 ? {} : { range: { lt: before } }
19543
+ };
19544
+ return buildKey !== void 0 ? db.findMany("native_builds", {
19545
+ index: "byBuildKey",
19546
+ where: {
19547
+ scope_key: scopeKey,
19548
+ build_key: buildKey
19549
+ },
19550
+ ...page
19551
+ }) : artifactKind !== void 0 ? db.findMany("native_builds", {
19552
+ index: "byScopeKind",
19553
+ where: {
19554
+ scope_key: scopeKey,
19555
+ artifact_kind: artifactKind
19556
+ },
19557
+ ...page
19558
+ }) : db.findMany("native_builds", {
19559
+ index: "byScope",
19560
+ where: { scope_key: scopeKey },
19561
+ ...page
19562
+ });
19563
+ };
19564
+ const bundleId = options?.builtInOlderThan;
19565
+ if (bundleId !== void 0 && scope.sandbox !== void 0 && scope.sandbox !== null) return null;
19566
+ const { rows } = await read(1);
19567
+ const newest = (rows[0] === void 0 ? void 0 : pick(rows[0])) ?? (artifactKind !== void 0 && buildKey === void 0 ? await db.findMany("native_builds", {
18915
19568
  index: "byScope",
18916
19569
  where: { scope_key: scopeKey },
18917
19570
  order: "desc",
18918
19571
  limit: 1
18919
- }) : await db.findMany("native_builds", {
18920
- index: "byBuildKey",
18921
- where: {
18922
- scope_key: scopeKey,
18923
- build_key: buildKey
18924
- },
19572
+ }).then(({ rows: [row] }) => row?.artifact_kind === artifactKind ? pick(row) : void 0) : void 0);
19573
+ if (newest === void 0 || !ofKind(newest)) return null;
19574
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return newest;
19575
+ let before = newest.id;
19576
+ for (let page = 0; page < OLDER_BUILDS_PAGES; page += 1) {
19577
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
19578
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
19579
+ if (usable !== void 0) return ofKind(usable) ? pick(usable) : null;
19580
+ const last = older.at(-1);
19581
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
19582
+ before = last.id;
19583
+ }
19584
+ return null;
19585
+ },
19586
+ async findNativeBuildSibling(build) {
19587
+ const artifactKind = SIBLING_KINDS[build.artifact_kind];
19588
+ if (build.platform !== "ios" || !build.is_sandbox || artifactKind === void 0 || !isInstallTarget(build)) return null;
19589
+ const scopeKey = siblingSandboxScopeKey(build, artifactKind);
19590
+ if (scopeKey === null) return null;
19591
+ const { rows } = await db.findMany("native_builds", {
19592
+ index: "byScope",
19593
+ where: { scope_key: scopeKey },
18925
19594
  order: "desc",
18926
19595
  limit: 1
18927
19596
  });
18928
- return rows[0] === void 0 ? null : pick(rows[0]);
19597
+ const sibling = rows[0] === void 0 ? null : pick(rows[0]);
19598
+ return sibling !== null && isInstallTarget(sibling) ? sibling : null;
18929
19599
  },
18930
19600
  async recordNativeBuildSubmission(id, { destination, version }) {
18931
19601
  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.`);
@@ -18933,7 +19603,8 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18933
19603
  const row = await tx.findOne("native_builds", { id });
18934
19604
  if (row === null) return null;
18935
19605
  const build = pick(row);
18936
- 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}.`);
19606
+ 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}.`);
19607
+ if (build.is_sandbox && destination !== "testflight" && destination !== "play-internal") throw new NativeBuildInputError("A sandbox build can submit only to TestFlight or Play internal testing.");
18937
19608
  const set = {
18938
19609
  submitted_to: destination,
18939
19610
  submitted_at_ms: now(),
@@ -18946,6 +19617,46 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18946
19617
  };
18947
19618
  });
18948
19619
  },
19620
+ async markNativeBuild(id, { storeBuild }) {
19621
+ for (let attempt = 1;; attempt += 1) try {
19622
+ return await db.transaction(async (tx) => {
19623
+ const row = await tx.findOne("native_builds", { id });
19624
+ if (row === null) return null;
19625
+ const build = pick(row);
19626
+ if (!storeBuild) {
19627
+ if (build.is_store_build) tx.update("native_builds", row, { is_store_build: false });
19628
+ return {
19629
+ nativeBuild: {
19630
+ ...build,
19631
+ is_store_build: false
19632
+ },
19633
+ previous: null
19634
+ };
19635
+ }
19636
+ if (build.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
19637
+ if (build.is_store_build) return {
19638
+ nativeBuild: build,
19639
+ previous: null
19640
+ };
19641
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build.scope_key });
19642
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
19643
+ tx.update("native_builds", row, { is_store_build: true });
19644
+ return {
19645
+ nativeBuild: {
19646
+ ...build,
19647
+ is_store_build: true
19648
+ },
19649
+ previous: holder === null ? null : {
19650
+ ...pick(holder),
19651
+ is_store_build: false
19652
+ }
19653
+ };
19654
+ });
19655
+ } catch (error) {
19656
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
19657
+ throw error;
19658
+ }
19659
+ },
18949
19660
  async deleteNativeBuild(id) {
18950
19661
  return db.transaction(async (tx) => {
18951
19662
  const row = await tx.findOne("native_builds", { id });
@@ -19001,24 +19712,26 @@ const checkScope = (scope) => {
19001
19712
  });
19002
19713
  if (scope.strategy === "FINGERPRINT" !== (scope.fingerprintHash !== null) || scope.scopeKey !== expected) fail$1("INVALID_SCOPE", "Release catalog scope metadata is inconsistent");
19003
19714
  };
19004
- const enabledReleases = async (tx, scopeKey) => {
19715
+ const drainReleases = async (page) => {
19005
19716
  const rows = [];
19006
19717
  let cursor;
19007
19718
  do {
19008
- const page = await tx.findMany("releases", {
19009
- index: "byScopeEnabled",
19010
- where: {
19011
- scope_key: scopeKey,
19012
- enabled: true
19013
- },
19014
- limit: PAGE$1,
19015
- ...cursor === void 0 ? {} : { cursor }
19016
- });
19017
- rows.push(...page.rows.map(toReleaseRow));
19018
- cursor = page.next;
19719
+ const found = await page(cursor);
19720
+ rows.push(...found.rows.map((row) => toReleaseRow(row)));
19721
+ cursor = found.next;
19019
19722
  } while (cursor !== void 0);
19020
19723
  return rows;
19021
19724
  };
19725
+ const enabledIn = (scopeKey, cursor) => ({
19726
+ index: "byScopeEnabled",
19727
+ where: {
19728
+ scope_key: scopeKey,
19729
+ enabled: true
19730
+ },
19731
+ limit: PAGE$1,
19732
+ ...cursor === void 0 ? {} : { cursor }
19733
+ });
19734
+ const enabledReleases = (tx, scopeKey) => drainReleases((cursor) => tx.findMany("releases", enabledIn(scopeKey, cursor)));
19022
19735
  const latestReleaseId = async (tx, scopeKey) => {
19023
19736
  const { rows } = await tx.findMany("releases", {
19024
19737
  index: "byScope",
@@ -19028,14 +19741,10 @@ const latestReleaseId = async (tx, scopeKey) => {
19028
19741
  });
19029
19742
  return rows[0]?.id ?? null;
19030
19743
  };
19031
- const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
19032
- const compilation = await compileReleaseCatalog({
19033
- strategy: scope.strategy,
19034
- releases: enabled.map(releaseRowToRelease)
19035
- });
19036
- const generation = (stored.generation ?? 0) + 1;
19744
+ const nextCatalog = (scope, stored, compilation, updatedAtMs) => {
19745
+ const generation = (stored.catalog?.generation ?? 0) + 1;
19037
19746
  if (!Number.isSafeInteger(generation)) fail$1("CATALOG_GENERATION_EXHAUSTED", `Catalog "${scope.scopeKey}" exhausted its generation counter`);
19038
- const catalog = {
19747
+ return {
19039
19748
  scope_key: scope.scopeKey,
19040
19749
  catalog_id: stored.catalog?.catalog_id ?? createUUIDv7(),
19041
19750
  strategy: scope.strategy,
@@ -19050,6 +19759,21 @@ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
19050
19759
  is_tombstone: compilation.payload.releaseDescriptors.length === 0,
19051
19760
  updated_at_ms: updatedAtMs
19052
19761
  };
19762
+ };
19763
+ const compileScope = async (scope, enabled) => {
19764
+ try {
19765
+ return await compileReleaseCatalog({
19766
+ strategy: scope.strategy,
19767
+ releases: enabled.map(releaseRowToRelease)
19768
+ });
19769
+ } catch (error) {
19770
+ if (!(error instanceof ReleaseCatalogCompilationError) || error.code !== "CATALOG_OVERSIZE") throw error;
19771
+ 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.`);
19772
+ }
19773
+ };
19774
+ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
19775
+ const compilation = await compileScope(scope, enabled);
19776
+ const catalog = nextCatalog(scope, stored, compilation, updatedAtMs);
19053
19777
  const { scope_key: _scopeKey, ...set } = catalog;
19054
19778
  if (stored.row === null) tx.create("release_catalogs", catalog);
19055
19779
  else tx.update("release_catalogs", stored.row, set);
@@ -19128,17 +19852,39 @@ const changeReleases = (db, inputs) => {
19128
19852
  return results;
19129
19853
  });
19130
19854
  };
19855
+ 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;
19856
+ const catalogRowScope = (row) => ({
19857
+ channelId: row.channel_id,
19858
+ channelName: decodeChannelKey(row.channel_key),
19859
+ fingerprintHash: row.fingerprint_hash,
19860
+ platform: row.platform,
19861
+ scopeKey: row.scope_key,
19862
+ strategy: row.strategy
19863
+ });
19864
+ const preflightRebuild = async (db, scopeKey, updatedAtMs) => {
19865
+ const row = await db.findOne("release_catalogs", { scope_key: scopeKey });
19866
+ if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
19867
+ const current = toCatalogRow(row);
19868
+ const scope = catalogRowScope(current);
19869
+ checkScope(scope);
19870
+ const enabled = await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor)));
19871
+ const compilation = await compileScope(scope, enabled);
19872
+ const changed = !isCurrent(scope, current, compilation);
19873
+ return {
19874
+ changed,
19875
+ currentCatalog: current,
19876
+ diagnostics: compilation.diagnostics,
19877
+ projectedCatalog: changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current
19878
+ };
19879
+ };
19131
19880
  const rebuildScope = async (tx, scope, updatedAtMs) => {
19132
19881
  checkScope(scope);
19133
19882
  const stored = await readCatalog(tx, scope.scopeKey);
19134
19883
  assertHistory(stored, await latestReleaseId(tx, scope.scopeKey) !== null);
19135
19884
  const enabled = await enabledReleases(tx, scope.scopeKey);
19136
- const compilation = await compileReleaseCatalog({
19137
- strategy: scope.strategy,
19138
- releases: enabled.map(releaseRowToRelease)
19139
- });
19885
+ const compilation = await compileScope(scope, enabled);
19140
19886
  const current = stored.catalog;
19141
- 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 {
19887
+ if (current !== null && isCurrent(scope, current, compilation)) return {
19142
19888
  catalog: current,
19143
19889
  current,
19144
19890
  changed: false,
@@ -19238,14 +19984,7 @@ const mutationResult = ({ catalog, release }) => ({
19238
19984
  const catalogScope = async (tx, scopeKey) => {
19239
19985
  const row = await tx.findOne("release_catalogs", { scope_key: scopeKey });
19240
19986
  if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
19241
- return {
19242
- channelId: row.channel_id,
19243
- channelName: decodeChannelKey(row.channel_key),
19244
- fingerprintHash: row.fingerprint_hash,
19245
- platform: row.platform,
19246
- scopeKey: row.scope_key,
19247
- strategy: row.strategy
19248
- };
19987
+ return catalogRowScope(toCatalogRow(row));
19249
19988
  };
19250
19989
  const createCoreOperations = (db, { now = Date.now } = {}) => {
19251
19990
  const ensureChannel = async (name) => (await insertChannel(db, {
@@ -19265,7 +20004,11 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
19265
20004
  for (const { release } of deployments) if (!channels.has(release.channel)) channels.set(release.channel, await ensureChannel(release.channel));
19266
20005
  const platforms = /* @__PURE__ */ new Map();
19267
20006
  for (const deployment of deployments) {
19268
- if (!("bundleId" in deployment) || platforms.has(deployment.bundleId)) continue;
20007
+ if (!("bundleId" in deployment)) {
20008
+ for (const { baseBundleId } of deployment.bundle.patches ?? []) await refuseSandboxPatchBase(db, baseBundleId);
20009
+ continue;
20010
+ }
20011
+ if (platforms.has(deployment.bundleId)) continue;
19269
20012
  const row = await db.findOne("bundles", { id: deployment.bundleId });
19270
20013
  if (row === null) throw new DatabaseBundleNotFoundError(deployment.bundleId);
19271
20014
  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.`);
@@ -19440,18 +20183,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
19440
20183
  };
19441
20184
  });
19442
20185
  },
19443
- preflightReleaseCatalogRebuild: (scopeKey) => {
19444
- const updatedAtMs = now();
19445
- return dryRun(db, async (tx) => {
19446
- const rebuilt = await rebuildScope(tx, await catalogScope(tx, scopeKey), updatedAtMs);
19447
- return {
19448
- changed: rebuilt.changed,
19449
- currentCatalog: rebuilt.current,
19450
- diagnostics: rebuilt.diagnostics,
19451
- projectedCatalog: rebuilt.catalog
19452
- };
19453
- });
19454
- },
20186
+ preflightReleaseCatalogRebuild: (scopeKey) => preflightRebuild(db, scopeKey, now()),
19455
20187
  ensureChannel,
19456
20188
  deleteChannel: (id) => deleteChannel(db, id),
19457
20189
  updateBundle: (id, update) => db.transaction(async (tx) => {
@@ -19469,7 +20201,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
19469
20201
  if (patches !== void 0) await replaceBundlePatches(tx, current, bundleToPatchRows({
19470
20202
  ...next,
19471
20203
  patches
19472
- }));
20204
+ }), (row) => refuseSandboxPatchBase(tx, row.base_bundle_id));
19473
20205
  }),
19474
20206
  deleteBundles: async (ids) => {
19475
20207
  try {
@@ -19525,6 +20257,7 @@ const createCoreApi = (db, storage, options = {}) => {
19525
20257
  ...reads,
19526
20258
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
19527
20259
  ...createNativeBuildApi(db, options),
20260
+ ...createIosDeviceApi(db, options),
19528
20261
  ready: async () => {
19529
20262
  await reads.listReleaseCatalogs({ limit: 1 });
19530
20263
  }
@@ -19708,6 +20441,10 @@ const answer = async (operation) => {
19708
20441
  error: error.message
19709
20442
  }, status);
19710
20443
  }
20444
+ if (error instanceof ReleaseCatalogCompilationError && error.code === "CATALOG_OVERSIZE") return json$2({
20445
+ code: error.code,
20446
+ error: error.message
20447
+ }, 400);
19711
20448
  if (error instanceof DatabaseBundleNotFoundError) return json$2({
19712
20449
  code: "BUNDLE_NOT_FOUND",
19713
20450
  error: error.message
@@ -19727,17 +20464,20 @@ const LIMITS = {
19727
20464
  defaultValue: 50,
19728
20465
  maxValue: 500
19729
20466
  };
19730
- const keyset = (url, maxValue = LIMITS.maxValue) => {
19731
- const order = url.searchParams.get("order") ?? "desc";
20467
+ const MAX_IDS = 100;
20468
+ const keyset = (url, maxValue = LIMITS.maxValue, defaultOrder = "desc") => {
20469
+ const order = url.searchParams.get("order") ?? defaultOrder;
19732
20470
  if (order !== "asc" && order !== "desc") throw new HandlerBadRequestError("order must be 'asc' or 'desc'.");
19733
20471
  const limitParam = url.searchParams.get("limit");
19734
20472
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
19735
20473
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
19736
20474
  const cursor = url.searchParams.get("cursor");
20475
+ const through = url.searchParams.get("through");
19737
20476
  return {
19738
20477
  order,
19739
20478
  limit,
19740
- ...cursor === null ? {} : { after: cursor }
20479
+ ...cursor === null ? {} : { after: cursor },
20480
+ ...through === null ? {} : { through }
19741
20481
  };
19742
20482
  };
19743
20483
  const page = (rows, { limit }, keyOf, extra = {}) => json$2({
@@ -19828,7 +20568,8 @@ const nativeBuildScopeOf = (url) => {
19828
20568
  const fingerprintHash = params.get("fingerprintHash");
19829
20569
  const appVersion = params.get("appVersion");
19830
20570
  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.");
19831
- return fingerprintHash !== null ? {
20571
+ const sandbox = sandboxScopeOf(params);
20572
+ const scope = fingerprintHash !== null ? {
19832
20573
  platform,
19833
20574
  channel,
19834
20575
  fingerprintHash,
@@ -19839,16 +20580,43 @@ const nativeBuildScopeOf = (url) => {
19839
20580
  fingerprintHash: null,
19840
20581
  appVersion
19841
20582
  };
20583
+ return sandbox === null ? scope : {
20584
+ ...scope,
20585
+ sandbox
20586
+ };
20587
+ };
20588
+ const SANDBOX_SCOPE_PARAMS = [
20589
+ "sandboxAppId",
20590
+ "sandboxUrlScheme",
20591
+ "artifactKind",
20592
+ "distribution"
20593
+ ];
20594
+ const sandboxScopeOf = (params) => {
20595
+ const [appId, urlScheme, artifactKind, distribution] = SANDBOX_SCOPE_PARAMS.map((name) => params.get(name));
20596
+ const named = [
20597
+ appId,
20598
+ urlScheme,
20599
+ artifactKind,
20600
+ distribution
20601
+ ].filter((value) => value !== null).length;
20602
+ if (named === 0) return null;
20603
+ if (named !== SANDBOX_SCOPE_PARAMS.length) throw new HandlerBadRequestError(`A sandbox build lookup needs ${SANDBOX_SCOPE_PARAMS.join(", ")}.`);
20604
+ return {
20605
+ appId,
20606
+ urlScheme,
20607
+ artifactKind,
20608
+ distribution
20609
+ };
19842
20610
  };
19843
20611
  const refusingInvalid = async (operation) => {
19844
20612
  try {
19845
20613
  return await operation();
19846
20614
  } catch (error) {
19847
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
20615
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
19848
20616
  throw error;
19849
20617
  }
19850
20618
  };
19851
- 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));
20619
+ 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));
19852
20620
  const scopeKeyOf = (params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "";
19853
20621
  const createAdminRouteHandlers = () => ({
19854
20622
  listBundles: onCore(async (core, request) => {
@@ -19880,11 +20648,34 @@ const createAdminRouteHandlers = () => ({
19880
20648
  const rows = await core.listReleaseCatalogs(input);
19881
20649
  return page(rows, input, (row) => row.scope_key);
19882
20650
  }),
20651
+ listReleaseScopeKeys: onCore(async (core, request) => {
20652
+ const input = keyset(new URL(request.url), 100, "asc");
20653
+ if (input.order !== "asc" || input.through !== void 0) throw new HandlerBadRequestError("Release scopes are listed ascending, by limit and cursor only.");
20654
+ const rows = await core.listReleaseScopeKeys({
20655
+ limit: input.limit,
20656
+ ...input.after === void 0 ? {} : { after: input.after }
20657
+ });
20658
+ return page(rows, input, (scopeKey) => scopeKey);
20659
+ }),
19883
20660
  getChannels: onCore(async (core, request) => {
19884
- const name = new URL(request.url).searchParams.get("name");
19885
- if (name === null) return json$2({ data: await core.listChannels() });
19886
- const channel = await core.findChannelByName(name);
19887
- return channel === null ? notFound() : json$2({ data: channel });
20661
+ const url = new URL(request.url);
20662
+ const name = url.searchParams.get("name");
20663
+ if (name !== null) {
20664
+ const channel = await core.findChannelByName(name);
20665
+ return channel === null ? notFound() : json$2({ data: channel });
20666
+ }
20667
+ const ids = url.searchParams.get("ids");
20668
+ if (ids !== null) {
20669
+ const list = ids.split(",").filter((id) => id.length > 0);
20670
+ if (list.length === 0 || list.length > MAX_IDS) throw new HandlerBadRequestError(`Channels by ID take ids=<channel id>,... with 1 to ${MAX_IDS} ids.`);
20671
+ return json$2({ data: await core.getChannels(list) });
20672
+ }
20673
+ if (url.searchParams.has("limit") || url.searchParams.has("cursor")) {
20674
+ const input = keyset(url, LIMITS.maxValue, "asc");
20675
+ const rows = await core.listChannels(input);
20676
+ return page(rows, input, (row) => row.name);
20677
+ }
20678
+ return json$2({ data: await core.listChannels() });
19888
20679
  }),
19889
20680
  createChannel: onCore(async (core, request) => {
19890
20681
  const { name } = await body(request);
@@ -19925,13 +20716,14 @@ const createAdminRouteHandlers = () => ({
19925
20716
  rebuildReleaseCatalog: onCore(async (core, _request, params) => json$2({ data: await core.rebuildReleaseCatalog(scopeKeyOf(params)) })),
19926
20717
  updateBundle: onCore(async (core, request, params) => {
19927
20718
  const bundleId = requireRouteParam(params, "id");
19928
- await core.updateBundle(bundleId, bundleUpdateOf(await request.json(), bundleId));
20719
+ const update = bundleUpdateOf(await request.json(), bundleId);
20720
+ await refusingInvalid(() => core.updateBundle(bundleId, update));
19929
20721
  return noContent();
19930
20722
  }),
19931
20723
  countBundles: onCore(async (core, request) => json$2({ data: await core.countBundles(platformOf(new URL(request.url))) })),
19932
20724
  countBundleChildren: onCore(async (core, request) => {
19933
20725
  const ids = (new URL(request.url).searchParams.get("ids") ?? "").split(",").filter((id) => id.length > 0);
19934
- if (ids.length === 0 || ids.length > 100) throw new HandlerBadRequestError("Bundle child counts take ids=<bundle id>,... with 1 to 100 ids.");
20726
+ if (ids.length === 0 || ids.length > MAX_IDS) throw new HandlerBadRequestError(`Bundle child counts take ids=<bundle id>,... with 1 to ${MAX_IDS} ids.`);
19935
20727
  return json$2({ data: await core.countBundleChildren(ids) });
19936
20728
  }),
19937
20729
  listBundleChildren: onCore(async (core, request, params) => {
@@ -19949,7 +20741,7 @@ const createAdminRouteHandlers = () => ({
19949
20741
  deployReleases: onCore(async (core, request) => {
19950
20742
  const { deployments } = await body(request);
19951
20743
  if (!Array.isArray(deployments) || deployments.length === 0 || !deployments.every(isDeployment)) throw new HandlerBadRequestError("Deploy needs deployments, each a bundle and its release policy.");
19952
- return json$2({ data: await core.deploy(deployments) }, 201);
20744
+ return json$2({ data: await refusingInvalid(() => core.deploy(deployments)) }, 201);
19953
20745
  }),
19954
20746
  promoteRelease: onCore(async (core, request, params) => {
19955
20747
  const input = await body(request);
@@ -19972,9 +20764,22 @@ const createAdminRouteHandlers = () => ({
19972
20764
  const url = new URL(request.url);
19973
20765
  const scope = nativeBuildScopeOf(url);
19974
20766
  const buildKey = url.searchParams.get("buildKey");
19975
- return json$2({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
20767
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
20768
+ const kind = url.searchParams.get("kind");
20769
+ const options = {
20770
+ ...buildKey === null ? {} : { buildKey },
20771
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
20772
+ ...builtInOlderThan === null ? {} : { builtInOlderThan },
20773
+ ...kind === null ? {} : { artifactKind: kind }
20774
+ };
20775
+ return json$2({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
20776
+ }),
20777
+ findNativeBuildSibling: onCore(async (core, _request, params) => {
20778
+ const build = await core.getNativeBuild(requireRouteParam(params, "id"));
20779
+ return json$2({ data: build === null ? null : await core.findNativeBuildSibling(build) });
19976
20780
  }),
19977
20781
  getNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
20782
+ findNativeBuildByBuiltInBundle: onCore(async (core, _request, params) => json$2({ data: await core.findNativeBuildByBuiltInBundle(requireRouteParam(params, "bundleId")) })),
19978
20783
  listNativeBuilds: onCore(async (core, request) => {
19979
20784
  const url = new URL(request.url);
19980
20785
  const input = keyset(url);
@@ -19986,14 +20791,97 @@ const createAdminRouteHandlers = () => ({
19986
20791
  }),
19987
20792
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
19988
20793
  const input = await body(request);
19989
- 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.");
20794
+ 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.");
19990
20795
  const submission = {
19991
20796
  destination: input.destination,
19992
20797
  version: input.version
19993
20798
  };
19994
20799
  return json$2({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
19995
20800
  }),
20801
+ markNativeBuild: onCore(async (core, request, params) => {
20802
+ const input = await body(request);
20803
+ if (!isRecord$5(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
20804
+ const mark = { storeBuild: input.storeBuild };
20805
+ return json$2({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
20806
+ }),
19996
20807
  deleteNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
20808
+ listIosDevices: onCore(async (core, request) => {
20809
+ const url = new URL(request.url);
20810
+ const input = keyset(url);
20811
+ const status = url.searchParams.get("status");
20812
+ return page(await refusingInvalid(() => core.listIosDevices({
20813
+ ...input,
20814
+ ...status === null ? {} : { status }
20815
+ })), input, ({ id }) => id);
20816
+ }),
20817
+ findIosDevice: onCore(async (core, _request, params) => json$2({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
20818
+ requestIosDevice: onCore(async (core, request) => {
20819
+ const input = await body(request);
20820
+ 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.");
20821
+ const device = {
20822
+ udid: input.udid,
20823
+ name: input.name,
20824
+ requestedBy: input.requestedBy
20825
+ };
20826
+ return json$2({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
20827
+ }),
20828
+ approveIosDevice: onCore(async (core, request, params) => {
20829
+ const input = await body(request);
20830
+ 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.");
20831
+ const approval = {
20832
+ approvedBy: input.approvedBy,
20833
+ ...input.name === void 0 ? {} : { name: input.name }
20834
+ };
20835
+ return json$2({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
20836
+ }),
20837
+ renameIosDevice: onCore(async (core, request, params) => {
20838
+ const input = await body(request);
20839
+ if (!isText$2(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
20840
+ const name = input.name;
20841
+ return json$2({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
20842
+ }),
20843
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
20844
+ const input = await body(request);
20845
+ const seen = input.seen;
20846
+ 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.");
20847
+ const outcome = {
20848
+ id: requireRouteParam(params, "id"),
20849
+ seen: {
20850
+ status: seen.status,
20851
+ approvedAtMs: seen.approvedAtMs
20852
+ },
20853
+ issuerId: input.issuerId,
20854
+ outcome: input.outcome,
20855
+ ...input.reason === void 0 ? {} : { reason: input.reason }
20856
+ };
20857
+ return json$2({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
20858
+ }),
20859
+ claimIosDeviceAccount: onCore(async (core, request) => {
20860
+ const { issuerId } = await body(request);
20861
+ if (!isText$2(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
20862
+ return json$2({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
20863
+ }),
20864
+ findIosDeviceAccount: onCore(async (core) => json$2({ data: await core.findIosDeviceAccount() })),
20865
+ markIosDevicesInBuild: onCore(async (core, request) => {
20866
+ const { buildId, ids } = await body(request);
20867
+ 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.");
20868
+ if (ids.length > MAX_IDS) throw new HandlerBadRequestError(`Marking iOS devices in a build takes at most ${MAX_IDS} ids a request.`);
20869
+ await core.markIosDevicesInBuild({
20870
+ buildId,
20871
+ ids
20872
+ });
20873
+ return noContent();
20874
+ }),
20875
+ deleteIosDevice: onCore(async (core, request, params) => {
20876
+ const url = new URL(request.url);
20877
+ const status = url.searchParams.get("status");
20878
+ const requestedBy = url.searchParams.get("requestedBy");
20879
+ const only = {
20880
+ ...status === null ? {} : { status },
20881
+ ...requestedBy === null ? {} : { requestedBy }
20882
+ };
20883
+ return json$2({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
20884
+ }),
19997
20885
  deleteBundles: onCore(async (core, request) => {
19998
20886
  const { ids } = await body(request);
19999
20887
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -20047,6 +20935,11 @@ const ADMIN_ROUTES = [
20047
20935
  path: "/release-catalogs",
20048
20936
  handler: "listReleaseCatalogs"
20049
20937
  },
20938
+ {
20939
+ method: "GET",
20940
+ path: "/release-scopes",
20941
+ handler: "listReleaseScopeKeys"
20942
+ },
20050
20943
  {
20051
20944
  method: "POST",
20052
20945
  path: "/release-catalogs/:scopeKey/rebuild",
@@ -20122,6 +21015,16 @@ const ADMIN_ROUTES = [
20122
21015
  path: "/native-builds/latest",
20123
21016
  handler: "findNativeBuild"
20124
21017
  },
21018
+ {
21019
+ method: "GET",
21020
+ path: "/native-builds/built-in/:bundleId",
21021
+ handler: "findNativeBuildByBuiltInBundle"
21022
+ },
21023
+ {
21024
+ method: "GET",
21025
+ path: "/native-builds/:id/sibling",
21026
+ handler: "findNativeBuildSibling"
21027
+ },
20125
21028
  {
20126
21029
  method: "GET",
20127
21030
  path: "/native-builds/:id",
@@ -20137,10 +21040,65 @@ const ADMIN_ROUTES = [
20137
21040
  path: "/native-builds/:id/submission",
20138
21041
  handler: "recordNativeBuildSubmission"
20139
21042
  },
21043
+ {
21044
+ method: "POST",
21045
+ path: "/native-builds/:id/store-build",
21046
+ handler: "markNativeBuild"
21047
+ },
20140
21048
  {
20141
21049
  method: "DELETE",
20142
21050
  path: "/native-builds/:id",
20143
21051
  handler: "deleteNativeBuild"
21052
+ },
21053
+ {
21054
+ method: "GET",
21055
+ path: "/ios-devices",
21056
+ handler: "listIosDevices"
21057
+ },
21058
+ {
21059
+ method: "POST",
21060
+ path: "/ios-devices",
21061
+ handler: "requestIosDevice"
21062
+ },
21063
+ {
21064
+ method: "GET",
21065
+ path: "/ios-devices/udid/:udid",
21066
+ handler: "findIosDevice"
21067
+ },
21068
+ {
21069
+ method: "POST",
21070
+ path: "/ios-devices/in-build",
21071
+ handler: "markIosDevicesInBuild"
21072
+ },
21073
+ {
21074
+ method: "GET",
21075
+ path: "/ios-devices/account",
21076
+ handler: "findIosDeviceAccount"
21077
+ },
21078
+ {
21079
+ method: "POST",
21080
+ path: "/ios-devices/account",
21081
+ handler: "claimIosDeviceAccount"
21082
+ },
21083
+ {
21084
+ method: "POST",
21085
+ path: "/ios-devices/:id/approval",
21086
+ handler: "approveIosDevice"
21087
+ },
21088
+ {
21089
+ method: "POST",
21090
+ path: "/ios-devices/:id/outcome",
21091
+ handler: "recordIosDeviceOutcome"
21092
+ },
21093
+ {
21094
+ method: "PATCH",
21095
+ path: "/ios-devices/:id",
21096
+ handler: "renameIosDevice"
21097
+ },
21098
+ {
21099
+ method: "DELETE",
21100
+ path: "/ios-devices/:id",
21101
+ handler: "deleteIosDevice"
20144
21102
  }
20145
21103
  ];
20146
21104
  //#endregion
@@ -20215,38 +21173,53 @@ const catalogResponse = async (catalog, request) => {
20215
21173
  };
20216
21174
  const createReleaseCatalogRouteHandlers = () => {
20217
21175
  const cache = /* @__PURE__ */ new Map();
21176
+ const evict = (insertedHit) => {
21177
+ const now = Date.now();
21178
+ let oldestMiss;
21179
+ let oldest;
21180
+ for (const [key, entry] of cache) if (entry.expiresAt <= now) cache.delete(key);
21181
+ else {
21182
+ if (entry.row === null) oldestMiss ??= key;
21183
+ oldest ??= key;
21184
+ }
21185
+ if (cache.size <= ORIGIN_CACHE_MAX_ENTRIES) return;
21186
+ const victim = oldestMiss ?? (insertedHit ? oldest : void 0);
21187
+ if (victim !== void 0) cache.delete(victim);
21188
+ };
20218
21189
  const inFlight = /* @__PURE__ */ new Map();
20219
- const loadCatalog = async (key, load) => {
20220
- const cached = cache.get(key);
21190
+ const loadRow = async (scopeKey, load) => {
21191
+ const cached = cache.get(scopeKey);
20221
21192
  if (cached !== void 0 && cached.expiresAt > Date.now()) {
20222
- cache.delete(key);
20223
- cache.set(key, cached);
20224
- return cached.catalog;
21193
+ cache.delete(scopeKey);
21194
+ cache.set(scopeKey, cached);
21195
+ return cached.row;
20225
21196
  }
20226
- if (cached !== void 0) cache.delete(key);
20227
- const pending = inFlight.get(key);
21197
+ if (cached !== void 0) cache.delete(scopeKey);
21198
+ const pending = inFlight.get(scopeKey);
20228
21199
  if (pending !== void 0) return pending;
20229
- const next = load().then((catalog) => {
20230
- if (catalog !== null) {
20231
- cache.set(key, {
20232
- catalog,
20233
- expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
20234
- });
20235
- while (cache.size > ORIGIN_CACHE_MAX_ENTRIES) {
20236
- const oldestKey = cache.keys().next().value;
20237
- if (oldestKey === void 0) break;
20238
- cache.delete(oldestKey);
20239
- }
20240
- }
20241
- return catalog;
21200
+ const next = load().then((row) => {
21201
+ cache.set(scopeKey, {
21202
+ row,
21203
+ expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
21204
+ });
21205
+ if (cache.size > ORIGIN_CACHE_MAX_ENTRIES) evict(row !== null);
21206
+ return row;
20242
21207
  });
20243
- inFlight.set(key, next);
21208
+ inFlight.set(scopeKey, next);
20244
21209
  try {
20245
21210
  return await next;
20246
21211
  } finally {
20247
- inFlight.delete(key);
21212
+ inFlight.delete(scopeKey);
20248
21213
  }
20249
21214
  };
21215
+ const loadCatalog = async (core, input) => {
21216
+ const scopeKey = releaseCatalogScopeKeyOf(input);
21217
+ const parsed = await loadRow(scopeKey, async () => {
21218
+ const row = await core.getReleaseCatalogRow(scopeKey);
21219
+ return row === null ? null : parseReleaseCatalogRow(row);
21220
+ });
21221
+ return projectParsedReleaseCatalogRow(parsed, input, scopeKey);
21222
+ };
20250
21223
  return {
20251
21224
  appVersionReleaseCatalog: async (params, request, { core }) => {
20252
21225
  const rawAppVersion = requireRouteParam(params, "appVersion");
@@ -20260,7 +21233,7 @@ const createReleaseCatalogRouteHandlers = () => {
20260
21233
  };
20261
21234
  const invalid = invalidScope(input);
20262
21235
  if (invalid) return invalid;
20263
- return catalogResponse(await loadCatalog(`app-version:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
21236
+ return catalogResponse(await loadCatalog(core, input), request);
20264
21237
  },
20265
21238
  fingerprintReleaseCatalog: async (params, request, { core }) => {
20266
21239
  const input = {
@@ -20271,7 +21244,7 @@ const createReleaseCatalogRouteHandlers = () => {
20271
21244
  };
20272
21245
  const invalid = invalidScope(input);
20273
21246
  if (invalid) return invalid;
20274
- return catalogResponse(await loadCatalog(`fingerprint:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
21247
+ return catalogResponse(await loadCatalog(core, input), request);
20275
21248
  },
20276
21249
  artifactV2: async (params, _request, { core }) => {
20277
21250
  const info = await core.getArtifactInfo(requireRouteParam(params, "targetBundleId"), requireRouteParam(params, "currentBundleId"), 2);
@@ -23185,6 +24158,53 @@ const breakdownOf = (rows) => {
23185
24158
  };
23186
24159
  });
23187
24160
  };
24161
+ const FAILURE_ROWS_PER_HOUR = 20;
24162
+ const FAILURE_QUERY_LIMIT = Math.min(PAGE, 168);
24163
+ const failureRowsByHour = async (db, platform, channel, timeRange) => {
24164
+ const read = (end, cursor) => db.findAggregates("insights_failures", {
24165
+ index: "byScope",
24166
+ where: {
24167
+ platform,
24168
+ channel
24169
+ },
24170
+ range: {
24171
+ gte: timeRange.start,
24172
+ lt: end
24173
+ },
24174
+ order: "desc",
24175
+ limit: FAILURE_QUERY_LIMIT,
24176
+ ...cursor === void 0 ? {} : { cursor }
24177
+ });
24178
+ const rows = [];
24179
+ const cappedHours = [];
24180
+ const perHour = /* @__PURE__ */ new Map();
24181
+ let end = timeRange.end;
24182
+ let cursor;
24183
+ while (end > timeRange.start) {
24184
+ const page = await read(end, cursor);
24185
+ let capped;
24186
+ for (const row of page.rows) {
24187
+ const hour = row.bucket_start_ms;
24188
+ const count = (perHour.get(hour) ?? 0) + 1;
24189
+ if (count > FAILURE_ROWS_PER_HOUR) {
24190
+ capped = hour;
24191
+ break;
24192
+ }
24193
+ perHour.set(hour, count);
24194
+ rows.push(row);
24195
+ }
24196
+ if (capped !== void 0) {
24197
+ cappedHours.unshift(capped);
24198
+ end = capped;
24199
+ cursor = void 0;
24200
+ } else if (page.next === void 0) break;
24201
+ else cursor = page.next;
24202
+ }
24203
+ return {
24204
+ rows,
24205
+ cappedHours
24206
+ };
24207
+ };
23188
24208
  const getUpdateFailures = async (db, input, now, retention) => {
23189
24209
  const { platform, channel, releaseId, timeRange } = input;
23190
24210
  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");
@@ -23245,7 +24265,7 @@ const getUpdateFailures = async (db, input, now, retention) => {
23245
24265
  days,
23246
24266
  kept.hour
23247
24267
  ];
23248
- const [counters, failures, checks, active, rows] = await Promise.all([
24268
+ const [counters, failures, checks, active, { rows, cappedHours }] = await Promise.all([
23249
24269
  counterRows(db, parts, ...window),
23250
24270
  sketchRows(db, failure, ...window),
23251
24271
  days ? sketchRows(db, {
@@ -23253,25 +24273,17 @@ const getUpdateFailures = async (db, input, now, retention) => {
23253
24273
  scopeKind: "check"
23254
24274
  }, ...window) : [],
23255
24275
  days ? sketchRows(db, usageParts(channel, platform), ...window) : [],
23256
- drain((page) => db.findAggregates("insights_failures", {
23257
- index: "byScope",
23258
- where: {
23259
- platform,
23260
- channel
23261
- },
23262
- range: {
23263
- gte: timeRange.start,
23264
- lt: timeRange.end
23265
- },
23266
- limit: PAGE,
23267
- ...page
23268
- }))
24276
+ failureRowsByHour(db, platform, channel, timeRange)
23269
24277
  ]);
23270
24278
  const total = (field) => counters.reduce((sum, row) => sum + row[field], 0);
23271
24279
  const scoped = rows.filter((row) => FAILURE_STAGES.has(row.stage) && (releaseId === void 0 || row.release_id === releaseId));
23272
24280
  const failuresAt = (counted) => scoped.reduce((sum, row) => sum + (counted(row.stage) ? Math.max(0, row.events) : 0), 0);
24281
+ const coverage = coverageOf(timeRange.start, kept.hour);
23273
24282
  return {
23274
- coverage: coverageOf(timeRange.start, kept.hour),
24283
+ coverage: cappedHours.length === 0 ? coverage : {
24284
+ kind: "partial",
24285
+ sinceMs: coverage.sinceMs
24286
+ },
23275
24287
  measuredAtMs: at,
23276
24288
  failedUpdates: failuresAt((stage) => stage !== "check"),
23277
24289
  failedInstallations: failed(failures),
@@ -23283,7 +24295,8 @@ const getUpdateFailures = async (db, input, now, retention) => {
23283
24295
  failedInstallations: failed(checks),
23284
24296
  activeInstallations: countDistinct(mergeDistinct(active.map((row) => row.activity_users)))
23285
24297
  } } : {},
23286
- breakdown: breakdownOf(scoped)
24298
+ breakdown: breakdownOf(scoped),
24299
+ ...cappedHours.length === 0 ? {} : { cappedHours }
23287
24300
  };
23288
24301
  };
23289
24302
  //#endregion