@hot-updater/vercel 1.2.0-rc.6 → 1.2.0-rc.61

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.
@@ -541,14 +541,14 @@ function modularInverse(value, modulus) {
541
541
  if (r > 1) throw new Error(`No modular inverse for ${value} mod ${modulus}`);
542
542
  return positiveMod(t, modulus);
543
543
  }
544
- function getRolloutShuffleParameters(bundleId) {
545
- let multiplier = positiveMod(hashString(`${bundleId}:multiplier`), 997);
544
+ function getRolloutShuffleParameters(releaseId) {
545
+ let multiplier = positiveMod(hashString(`${releaseId}:multiplier`), 997);
546
546
  if (multiplier === 0) multiplier = 1;
547
547
  while (gcd(multiplier, NUMERIC_COHORT_SIZE) !== 1) {
548
548
  multiplier = positiveMod(multiplier + 1, NUMERIC_COHORT_SIZE);
549
549
  if (multiplier === 0) multiplier = 1;
550
550
  }
551
- const offset = positiveMod(hashString(`${bundleId}:offset`), NUMERIC_COHORT_SIZE);
551
+ const offset = positiveMod(hashString(`${releaseId}:offset`), NUMERIC_COHORT_SIZE);
552
552
  return {
553
553
  multiplier,
554
554
  offset,
@@ -581,16 +581,16 @@ function isValidCohort(cohort) {
581
581
  const normalized = normalizeCohortValue(cohort);
582
582
  return isNumericCohort(normalized) || isCustomCohort(normalized);
583
583
  }
584
- function getNumericCohortRolloutPosition(bundleId, cohortValue) {
584
+ function getNumericCohortRolloutPosition(releaseId, cohortValue) {
585
585
  if (cohortValue < 1 || cohortValue > 1e3) throw new Error(`Invalid numeric cohort: ${cohortValue}`);
586
- const { offset, inverseMultiplier } = getRolloutShuffleParameters(bundleId);
586
+ const { offset, inverseMultiplier } = getRolloutShuffleParameters(releaseId);
587
587
  return positiveMod(inverseMultiplier * (cohortValue - 1 - offset), NUMERIC_COHORT_SIZE);
588
588
  }
589
- function getRolledOutNumericCohorts(bundleId, rolloutCohortCount) {
589
+ function getRolledOutNumericCohorts(releaseId, rolloutCohortCount) {
590
590
  const normalizedRolloutCount = normalizeRolloutCohortCount(rolloutCohortCount);
591
591
  if (normalizedRolloutCount <= 0) return [];
592
592
  if (normalizedRolloutCount >= 1e3) return Array.from({ length: NUMERIC_COHORT_SIZE }, (_, index) => index + 1);
593
- const { multiplier, offset } = getRolloutShuffleParameters(bundleId);
593
+ const { multiplier, offset } = getRolloutShuffleParameters(releaseId);
594
594
  return Array.from({ length: normalizedRolloutCount }, (_, position) => positiveMod(multiplier * position + offset, NUMERIC_COHORT_SIZE)).map((zeroBasedCohort) => zeroBasedCohort + 1).sort((left, right) => left - right);
595
595
  }
596
596
  const RELEASE_CATALOG_FALLBACK_POLICY = "BUILTIN_IF_ACTIVE_INELIGIBLE";
@@ -615,7 +615,8 @@ const releaseRowToRelease = (row) => ({
615
615
  operation: row.operation,
616
616
  sourceReleaseId: row.source_release_id,
617
617
  createdAtMs: row.created_at_ms,
618
- updatedAtMs: row.updated_at_ms
618
+ updatedAtMs: row.updated_at_ms,
619
+ label: row.label ?? null
619
620
  });
620
621
  const bundleToRow = (bundle) => {
621
622
  const metadata = bundleMetadataToRow(bundle.metadata);
@@ -1124,7 +1125,7 @@ function rangeToIntervals(range) {
1124
1125
  throw new ReleaseCatalogCompilationError("INVALID_TARGET_RANGE", `Invalid target app-version range: ${range}`);
1125
1126
  }
1126
1127
  }
1127
- function releaseDescriptor(release) {
1128
+ function releaseDescriptor(release, labels) {
1128
1129
  return {
1129
1130
  releaseId: release.id,
1130
1131
  kind: release.kind,
@@ -1132,7 +1133,8 @@ function releaseDescriptor(release) {
1132
1133
  rolloutCohortCount: release.rolloutCohortCount,
1133
1134
  targetCohorts: [...new Set(release.targetCohorts)].sort(),
1134
1135
  shouldForceUpdate: release.shouldForceUpdate,
1135
- message: release.message
1136
+ message: release.message,
1137
+ ...labels && typeof release.label === "number" ? { label: release.label } : {}
1136
1138
  };
1137
1139
  }
1138
1140
  function validateReleases(releases, strategy) {
@@ -1340,17 +1342,84 @@ function canonicalStringify(value) {
1340
1342
  const record = value;
1341
1343
  return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${canonicalStringify(record[key])}`).join(",")}}`;
1342
1344
  }
1345
+ const BOUND_SHAPE = {
1346
+ inclusive: null,
1347
+ version: null
1348
+ };
1349
+ const COMPILED_CATALOG_SHAPE = {
1350
+ fallbackPolicy: null,
1351
+ schemaVersion: null,
1352
+ strategy: null,
1353
+ releaseIndexes: null,
1354
+ rollbackReleaseIndexes: null,
1355
+ segments: {
1356
+ lower: BOUND_SHAPE,
1357
+ upper: BOUND_SHAPE,
1358
+ releaseIndexes: null,
1359
+ rollbackReleaseIndexes: null
1360
+ },
1361
+ releaseDescriptors: {
1362
+ releaseId: null,
1363
+ kind: null,
1364
+ bundleId: null,
1365
+ rolloutCohortCount: null,
1366
+ targetCohorts: null,
1367
+ shouldForceUpdate: null,
1368
+ message: null,
1369
+ label: null
1370
+ }
1371
+ };
1372
+ function readCompiledCatalogPayload(payload) {
1373
+ let fromLaterRelease = false;
1374
+ const known = (value, shape) => {
1375
+ if (Array.isArray(value)) return value.map((item) => known(item, shape));
1376
+ if (value === null || typeof value !== "object") return value;
1377
+ const entries = Object.entries(value).filter(([key]) => {
1378
+ if (Object.hasOwn(shape, key)) return true;
1379
+ fromLaterRelease = true;
1380
+ return false;
1381
+ });
1382
+ return Object.fromEntries(entries.map(([key, entry]) => {
1383
+ const inner = shape[key];
1384
+ return [key, inner === null ? entry : known(entry, inner)];
1385
+ }));
1386
+ };
1387
+ let parsed;
1388
+ try {
1389
+ parsed = JSON.parse(payload);
1390
+ } catch {
1391
+ parsed = null;
1392
+ }
1393
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return {
1394
+ canonicalPayload: payload,
1395
+ fromLaterRelease: false
1396
+ };
1397
+ if ("schemaVersion" in parsed && typeof parsed.schemaVersion === "number" && parsed.schemaVersion > 1) fromLaterRelease = true;
1398
+ return {
1399
+ canonicalPayload: canonicalStringify(known(parsed, COMPILED_CATALOG_SHAPE)),
1400
+ fromLaterRelease
1401
+ };
1402
+ }
1343
1403
  async function compileReleaseCatalog(input) {
1344
1404
  const releases = validateReleases(input.releases, input.strategy);
1345
1405
  const targetCohorts = new Set(releases.flatMap((release) => release.targetCohorts));
1346
1406
  if (targetCohorts.size > 512) throw new ReleaseCatalogCompilationError("DISTINCT_TARGET_COHORT_LIMIT", `Scope exceeds 512 distinct target cohorts`);
1347
1407
  const { envelope, retainedReleases } = input.strategy === "APP_VERSION" ? compileAppVersion(releases) : compileFingerprint(releases);
1348
- const payload = {
1349
- ...envelope,
1350
- releaseDescriptors: retainedReleases.map(releaseDescriptor)
1408
+ const compile = (labels) => {
1409
+ const payload = {
1410
+ ...envelope,
1411
+ releaseDescriptors: retainedReleases.map((release) => releaseDescriptor(release, labels))
1412
+ };
1413
+ const canonicalPayload = canonicalStringify(payload);
1414
+ return {
1415
+ payload,
1416
+ canonicalPayload,
1417
+ byteSize: new TextEncoder().encode(canonicalPayload).byteLength
1418
+ };
1351
1419
  };
1352
- const canonicalPayload = canonicalStringify(payload);
1353
- const byteSize = new TextEncoder().encode(canonicalPayload).byteLength;
1420
+ let compiled = compile(true);
1421
+ if (compiled.byteSize > 262144 && retainedReleases.some((release) => typeof release.label === "number")) compiled = compile(false);
1422
+ const { payload, canonicalPayload, byteSize } = compiled;
1354
1423
  if (byteSize > 262144) throw new ReleaseCatalogCompilationError("CATALOG_OVERSIZE", `Compiled Release catalog is ${byteSize} bytes; maximum is ${MAX_COMPILED_CATALOG_BYTES}`);
1355
1424
  return {
1356
1425
  byteSize,
@@ -1863,6 +1932,18 @@ const SETTINGS_TABLE = {
1863
1932
  };
1864
1933
  const ENGINE_SCHEMA_KEY = "schema.engine";
1865
1934
  const CORE_SCHEMA_KEY = "schema.core";
1935
+ const compareVersions = (left, right) => {
1936
+ const parse = (version) => /^\d+(?:\.\d+)*$/u.test(version) ? version.split(".").map(Number) : [NaN];
1937
+ const [a, b] = [parse(left), parse(right)];
1938
+ if ([...a, ...b].some(Number.isNaN)) return NaN;
1939
+ for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
1940
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
1941
+ if (difference !== 0) return difference;
1942
+ }
1943
+ return 0;
1944
+ };
1945
+ const newerCore = (settings) => settings.find(({ key, expected, found }) => key === CORE_SCHEMA_KEY && found !== null && compareVersions(found, expected) > 0);
1946
+ const newerMessage = (adapterName, { key, expected, found }) => `Hot Updater schema setting "${key}" for ${adapterName} is "${found}"; expected "${expected}". The database was migrated by Hot Updater ${found}: upgrade hot-updater and the @hot-updater packages to ${found} or later.`;
1866
1947
  const stored = ({ key, expected, found }) => `"${key}" is ${found === null ? "missing" : `"${found}"`}; expected "${expected}"`;
1867
1948
  const MIGRATE_SCHEMA_FIX = "Run `npx hot-updater doctor` in the project whose hot-updater.config.ts names this database: it names the command that migrates it. In a server project, `hot-updater db migrate` migrates the database its server file names.";
1868
1949
  const settingMessage = (adapterName, { key, expected, found }) => `Hot Updater schema setting "${key}" for ${adapterName} is ${found === null ? "missing" : `"${found}"`}; expected "${expected}". ${MIGRATE_SCHEMA_FIX}`;
@@ -1879,7 +1960,8 @@ var HotUpdaterSchemaMigrationRequiredError = class extends Error {
1879
1960
  constructor(adapterName, currentVersion, setting, options) {
1880
1961
  const settings = options?.settings ?? (setting === void 0 ? [] : [setting]);
1881
1962
  const plugins = settings.flatMap((mismatch) => pluginOf(mismatch) ?? []);
1882
- super(setting === void 0 ? currentVersion === void 0 ? `Hot Updater database schema is not initialized for ${adapterName}. ${MIGRATE_SCHEMA_FIX}` : `Hot Updater v1 cannot migrate schema ${currentVersion} in place. Create a new empty database and run \`hot-updater db migrate\`.` : plugins.length > 0 && plugins.length === settings.length ? pluginsMessage(adapterName, plugins, settings, options?.fix ?? MIGRATE_SCHEMA_FIX) : settings.length > 1 && !(setting.key === "schema.engine" && setting.found === null) ? settingsMessage(adapterName, settings) : settingMessage(adapterName, setting), options?.cause === void 0 ? void 0 : { cause: options.cause });
1963
+ const newer = newerCore(settings);
1964
+ super(newer !== void 0 ? newerMessage(adapterName, newer) : setting === void 0 ? currentVersion === void 0 ? `Hot Updater database schema is not initialized for ${adapterName}. ${MIGRATE_SCHEMA_FIX}` : `Hot Updater v1 cannot migrate schema ${currentVersion} in place. Create a new empty database and run \`hot-updater db migrate\`.` : plugins.length > 0 && plugins.length === settings.length ? pluginsMessage(adapterName, plugins, settings, options?.fix ?? MIGRATE_SCHEMA_FIX) : settings.length > 1 && !(setting.key === "schema.engine" && setting.found === null) ? settingsMessage(adapterName, settings) : settingMessage(adapterName, setting), options?.cause === void 0 ? void 0 : { cause: options.cause });
1883
1965
  this.adapterName = adapterName;
1884
1966
  this.currentVersion = currentVersion;
1885
1967
  this.setting = setting;
@@ -1969,43 +2051,6 @@ const withSchemaFence = (adapter, adapterName, expected, fix) => {
1969
2051
  const METER = Symbol.for("@hot-updater/plugin-core/read-meter");
1970
2052
  const readMeterOf = (database) => typeof database === "object" && database !== null ? database[METER] : void 0;
1971
2053
  //#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
2054
  //#region ../plugin-core/dist/engine/database/sql/sqlSchema.mjs
2010
2055
  const quoteSql = (dialect, name) => dialect === "mysql" ? `\`${name.replaceAll("`", "``")}\`` : `"${name.replaceAll("\"", "\"\"")}"`;
2011
2056
  const isMultiIndex = (table, index) => index.eq.some((column) => findPhysicalColumn(table, column).multi);
@@ -2049,6 +2094,7 @@ const sqlTableShapes = (dialect, tables, tablePrefix = "") => tables.map((table)
2049
2094
  const name = tablePrefix + table.name;
2050
2095
  const indexed = /* @__PURE__ */ new Set([...table.key, ...table.indexes.flatMap(({ eq, sort }) => [...eq, ...sort])]);
2051
2096
  if (dialect === "mysql") checkMysqlKey(table, "key", table.key);
2097
+ const covered = /* @__PURE__ */ new Set([JSON.stringify(table.key)]);
2052
2098
  const indexes = table.indexes.flatMap((index) => {
2053
2099
  const columns = [...index.eq, ...indexOrderColumns(table, index)];
2054
2100
  if (dialect === "mysql") checkMysqlKey(table, `index ${index.name}`, columns);
@@ -2064,11 +2110,19 @@ const sqlTableShapes = (dialect, tables, tablePrefix = "") => tables.map((table)
2064
2110
  name: `${name}__${index.name}`,
2065
2111
  columns: entries,
2066
2112
  key: columns,
2067
- indexes: []
2113
+ indexes: [{
2114
+ kind: "index",
2115
+ name: shortSqlName(`${name}__${index.name}__key`),
2116
+ unique: false,
2117
+ columns: table.key
2118
+ }]
2068
2119
  }
2069
2120
  }];
2070
2121
  }
2071
- if (!index.unique && columns.join() === table.key.join()) return [];
2122
+ if (!index.unique) {
2123
+ if (covered.has(JSON.stringify(columns))) return [];
2124
+ covered.add(JSON.stringify(columns));
2125
+ }
2072
2126
  return [{
2073
2127
  kind: "index",
2074
2128
  name: shortSqlName(`${name}_${index.name}`),
@@ -2134,9 +2188,17 @@ const pruneStatements = (dialect, table, tablePrefix, limit) => {
2134
2188
  const order = retentionOrder(table).columns.map(quote);
2135
2189
  const list = (alias, direction = "") => order.map((column) => `${alias}.${column}${direction}`).join(", ");
2136
2190
  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)`;
2191
+ 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
2192
  const entries = table.indexes.filter((index) => isMultiIndex(table, index)).map((index) => quote(`${tablePrefix}${table.name}__${index.name}`));
2139
2193
  const keyOf = (left, right) => table.key.map((column) => `${left}.${quote(column)} = ${right}.${quote(column)}`).join(" AND ");
2194
+ if (dialect === "sqlite") return [...table.indexes.filter((index) => isMultiIndex(table, index)).map((index) => {
2195
+ const columns = [...index.eq, ...indexOrderColumns(table, index)];
2196
+ const multi = columns.filter((column) => findPhysicalColumn(table, column).multi);
2197
+ const values = columns.map((column) => multi.includes(column) ? `j${multi.indexOf(column)}.${quote("value")}` : `b.${quote(column)}`);
2198
+ const each = multi.map((column, at) => `, json_each(b.${quote(column)}) j${at}`);
2199
+ const into = quote(`${tablePrefix}${table.name}__${index.name}`);
2200
+ return (before) => `DELETE FROM ${into} WHERE (${columns.map(quote).join(", ")}) IN (SELECT ${values.join(", ")} FROM ${name} b${each.join("")} WHERE ${doomed("b", before)})`;
2201
+ }), (before) => `DELETE FROM ${name} WHERE ${doomed(name, before)}`];
2140
2202
  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
2203
  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
2204
  };
@@ -2294,7 +2356,11 @@ const releases = defineTable({
2294
2356
  }
2295
2357
  },
2296
2358
  created_at_ms: { type: "integer" },
2297
- updated_at_ms: { type: "integer" }
2359
+ updated_at_ms: { type: "integer" },
2360
+ label: {
2361
+ type: "integer",
2362
+ required: false
2363
+ }
2298
2364
  }, {
2299
2365
  key: ["id"],
2300
2366
  indexes: {
@@ -2327,9 +2393,45 @@ const releases = defineTable({
2327
2393
  all: {
2328
2394
  eq: [],
2329
2395
  sort: ["id"]
2396
+ },
2397
+ scopes: {
2398
+ eq: [],
2399
+ sort: ["scope_key"]
2400
+ },
2401
+ byLabel: {
2402
+ eq: [
2403
+ "channel_id",
2404
+ "platform",
2405
+ "label"
2406
+ ],
2407
+ sort: [],
2408
+ unique: true
2330
2409
  }
2331
2410
  }
2332
2411
  });
2412
+ const LATE_INDEXES = [{
2413
+ table: "releases",
2414
+ index: "scopes"
2415
+ }];
2416
+ const LATE_COLUMNS = [{
2417
+ table: "releases",
2418
+ column: "label"
2419
+ }];
2420
+ const labelSequences = defineTable({
2421
+ id: {
2422
+ type: "string",
2423
+ maxLength: 1440,
2424
+ ascii: true
2425
+ },
2426
+ last_label: { type: "integer" },
2427
+ is_filled: { type: "boolean" }
2428
+ }, {
2429
+ key: ["id"],
2430
+ indexes: { all: {
2431
+ eq: [],
2432
+ sort: ["id"]
2433
+ } }
2434
+ });
2333
2435
  const releaseCatalogs = defineTable({
2334
2436
  scope_key: {
2335
2437
  type: "string",
@@ -2470,9 +2572,32 @@ const nativeBuilds = defineTable({
2470
2572
  type: "string",
2471
2573
  maxLength: 255,
2472
2574
  required: false
2575
+ },
2576
+ is_store_build: { type: "boolean" },
2577
+ is_sandbox: { type: "boolean" },
2578
+ sandbox_url_scheme: {
2579
+ type: "string",
2580
+ maxLength: 255,
2581
+ ascii: true,
2582
+ required: false
2583
+ },
2584
+ export_method: {
2585
+ type: "string",
2586
+ maxLength: 16,
2587
+ required: false
2588
+ },
2589
+ native_app_version: {
2590
+ type: "string",
2591
+ required: false
2473
2592
  }
2474
2593
  }, {
2475
2594
  key: ["id"],
2595
+ derived: { store_build_scope_key: {
2596
+ type: "string",
2597
+ maxLength: 2048,
2598
+ ascii: true,
2599
+ compute: (row) => row.is_store_build ? row.scope_key : null
2600
+ } },
2476
2601
  indexes: {
2477
2602
  byScope: {
2478
2603
  eq: ["scope_key"],
@@ -2482,6 +2607,15 @@ const nativeBuilds = defineTable({
2482
2607
  eq: ["scope_key", "build_key"],
2483
2608
  sort: ["id"]
2484
2609
  },
2610
+ byScopeKind: {
2611
+ eq: ["scope_key", "artifact_kind"],
2612
+ sort: ["id"]
2613
+ },
2614
+ byStoreBuild: {
2615
+ eq: ["store_build_scope_key"],
2616
+ sort: [],
2617
+ unique: true
2618
+ },
2485
2619
  byChannel: {
2486
2620
  eq: ["channel_id"],
2487
2621
  sort: ["id"],
@@ -2493,6 +2627,96 @@ const nativeBuilds = defineTable({
2493
2627
  }
2494
2628
  }
2495
2629
  });
2630
+ const iosDevices = defineTable({
2631
+ id: {
2632
+ type: "string",
2633
+ maxLength: 36
2634
+ },
2635
+ udid: {
2636
+ type: "string",
2637
+ maxLength: 40,
2638
+ ascii: true,
2639
+ unique: true
2640
+ },
2641
+ name: {
2642
+ type: "string",
2643
+ maxLength: 100
2644
+ },
2645
+ status: {
2646
+ type: "string",
2647
+ maxLength: 16
2648
+ },
2649
+ requested_by: {
2650
+ type: "string",
2651
+ maxLength: 320,
2652
+ required: false
2653
+ },
2654
+ created_at_ms: { type: "integer" },
2655
+ approved_by: {
2656
+ type: "string",
2657
+ maxLength: 320,
2658
+ required: false
2659
+ },
2660
+ approved_at_ms: {
2661
+ type: "integer",
2662
+ required: false
2663
+ },
2664
+ registered_at_ms: {
2665
+ type: "integer",
2666
+ required: false
2667
+ },
2668
+ apple_issuer_id: {
2669
+ type: "string",
2670
+ maxLength: 64,
2671
+ ascii: true,
2672
+ required: false
2673
+ },
2674
+ apple_error: {
2675
+ type: "string",
2676
+ maxLength: 512,
2677
+ required: false
2678
+ },
2679
+ build_id: {
2680
+ type: "string",
2681
+ maxLength: 36,
2682
+ required: false
2683
+ }
2684
+ }, {
2685
+ key: ["id"],
2686
+ indexes: {
2687
+ byStatus: {
2688
+ eq: ["status"],
2689
+ sort: ["id"]
2690
+ },
2691
+ byRegistration: {
2692
+ eq: [],
2693
+ sort: ["registered_at_ms"]
2694
+ },
2695
+ all: {
2696
+ eq: [],
2697
+ sort: ["id"]
2698
+ }
2699
+ }
2700
+ });
2701
+ const iosDeviceAccount = defineTable({
2702
+ id: {
2703
+ type: "string",
2704
+ maxLength: 16,
2705
+ ascii: true
2706
+ },
2707
+ apple_issuer_id: {
2708
+ type: "string",
2709
+ maxLength: 64,
2710
+ ascii: true
2711
+ },
2712
+ claimed_at_ms: { type: "integer" }
2713
+ }, {
2714
+ key: ["id"],
2715
+ indexes: { all: {
2716
+ eq: [],
2717
+ sort: ["id"]
2718
+ } }
2719
+ });
2496
2720
  const coreModule = {
2497
2721
  id: "core",
2498
2722
  schema: {
@@ -2512,7 +2736,10 @@ const coreModule = {
2512
2736
  sort: []
2513
2737
  } }
2514
2738
  }),
2515
- native_builds: nativeBuilds
2739
+ native_builds: nativeBuilds,
2740
+ ios_devices: iosDevices,
2741
+ ios_device_account: iosDeviceAccount,
2742
+ label_sequences: labelSequences
2516
2743
  }
2517
2744
  };
2518
2745
  //#endregion
@@ -2523,6 +2750,58 @@ const getEmptyMigrationResult = () => ({
2523
2750
  getSQL: () => ""
2524
2751
  });
2525
2752
  //#endregion
2753
+ //#region ../plugin-core/dist/engine/db/sqlSchemaState.mjs
2754
+ const POSTGRES_NAME_BYTES = 63;
2755
+ const postgresName = (name) => {
2756
+ const encoder = new TextEncoder();
2757
+ let bytes = 0;
2758
+ let cut = "";
2759
+ for (const character of name) {
2760
+ bytes += encoder.encode(character).length;
2761
+ if (bytes > POSTGRES_NAME_BYTES) break;
2762
+ cut += character;
2763
+ }
2764
+ return cut;
2765
+ };
2766
+ const fold = (dialect, name) => dialect === "mysql" ? String(name).toLowerCase() : dialect === "postgresql" ? postgresName(String(name)) : String(name);
2767
+ const CATALOG = {
2768
+ postgresql: {
2769
+ tables: "SELECT c.relname AS t FROM pg_class c WHERE c.relkind IN ('r', 'p') AND pg_table_is_visible(c.oid)",
2770
+ indexes: "SELECT t.relname AS t, c.relname AS i FROM pg_index x JOIN pg_class c ON c.oid = x.indexrelid JOIN pg_class t ON t.oid = x.indrelid WHERE pg_table_is_visible(t.oid)",
2771
+ columns: "SELECT c.relname AS t, a.attname AS c FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid WHERE c.relkind IN ('r', 'p') AND a.attnum > 0 AND NOT a.attisdropped AND pg_table_is_visible(c.oid)"
2772
+ },
2773
+ mysql: {
2774
+ tables: "SELECT TABLE_NAME AS t FROM information_schema.tables WHERE TABLE_SCHEMA = DATABASE()",
2775
+ indexes: "SELECT DISTINCT TABLE_NAME AS t, INDEX_NAME AS i FROM information_schema.statistics WHERE TABLE_SCHEMA = DATABASE()",
2776
+ columns: "SELECT TABLE_NAME AS t, COLUMN_NAME AS c FROM information_schema.columns WHERE TABLE_SCHEMA = DATABASE()"
2777
+ },
2778
+ sqlite: {
2779
+ tables: "SELECT name AS t FROM sqlite_master WHERE type = 'table'",
2780
+ indexes: "SELECT tbl_name AS t, name AS i FROM sqlite_master WHERE type = 'index'",
2781
+ columns: "SELECT m.name AS t, p.name AS c FROM sqlite_master m JOIN pragma_table_info(m.name) p WHERE m.type = 'table'"
2782
+ }
2783
+ };
2784
+ const readSqlSchemaState = async (executor) => {
2785
+ const { dialect } = executor;
2786
+ const read = (sql) => executor.execute({
2787
+ sql,
2788
+ params: []
2789
+ });
2790
+ const [tables, indexes, columns] = await Promise.all([
2791
+ read(CATALOG[dialect].tables),
2792
+ read(CATALOG[dialect].indexes),
2793
+ read(CATALOG[dialect].columns)
2794
+ ]);
2795
+ const columnNames = new Set(columns.rows.map(({ t, c }) => JSON.stringify([fold(dialect, t), fold(dialect, c)])));
2796
+ const tableNames = new Set(tables.rows.map(({ t }) => fold(dialect, t)));
2797
+ const indexNames = new Set(indexes.rows.map(({ t, i }) => JSON.stringify([fold(dialect, t), fold(dialect, i)])));
2798
+ return {
2799
+ hasTable: (table) => tableNames.has(fold(dialect, table)),
2800
+ hasIndex: (table, index) => indexNames.has(JSON.stringify([fold(dialect, table), fold(dialect, index)])),
2801
+ hasColumn: (table, column) => columnNames.has(JSON.stringify([fold(dialect, table), fold(dialect, column)]))
2802
+ };
2803
+ };
2804
+ //#endregion
2526
2805
  //#region ../plugin-core/dist/engine/db/settingsMigrator.mjs
2527
2806
  const storedSchemaVersion = (stored) => {
2528
2807
  const version = stored?.get("schema.core") ?? stored?.get("version");
@@ -2533,6 +2812,93 @@ const refuseV0Database = (adapterName, stored) => {
2533
2812
  if (typeof version !== "string" || stored.has("schema.engine")) return;
2534
2813
  throw new HotUpdaterSchemaMigrationRequiredError(adapterName, version);
2535
2814
  };
2815
+ const DEFAULT_ORDERED_SETTINGS = ["schema.core"];
2816
+ const refuseNewerSchema = (adapterName, stored, settings, ordered = DEFAULT_ORDERED_SETTINGS) => {
2817
+ const newer = ordered.flatMap((key) => {
2818
+ const found = stored.get(key);
2819
+ const expected = settings[key];
2820
+ return typeof found === "string" && expected !== void 0 && compareVersions(found, expected) > 0 ? [{
2821
+ key,
2822
+ found,
2823
+ expected
2824
+ }] : [];
2825
+ });
2826
+ const core = newer.find(({ key }) => key === "schema.core");
2827
+ if (core === void 0) return;
2828
+ 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.`);
2829
+ };
2830
+ const settingsOperation = (stored, changed) => ({
2831
+ type: "custom",
2832
+ description: `Record ${changed.map(([key, value]) => {
2833
+ const found = stored.get(key);
2834
+ return typeof found === "string" ? `${key} ${found} → ${value}` : `${key} ${value}`;
2835
+ }).join(", ")}`
2836
+ });
2837
+ //#endregion
2838
+ //#region ../plugin-core/dist/engine/db/schemaSettings.mjs
2839
+ const storedSettings = async (adapter, keys) => {
2840
+ const rows = await readSettings(adapter, keys);
2841
+ return new Map(keys.map((key, position) => [key, rows[position] ?? null]));
2842
+ };
2843
+ const writeSchemaSettings = async (adapter, adapterName, settings, ordered) => {
2844
+ const stored = await storedSettings(adapter, Object.keys(settings));
2845
+ refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
2846
+ const ops = Object.entries(settings).flatMap(([key, value]) => {
2847
+ const row = stored.get(key);
2848
+ if (row === null || row === void 0) return [{
2849
+ type: "insert",
2850
+ table: SETTINGS_TABLE,
2851
+ row: {
2852
+ key,
2853
+ value,
2854
+ _v: 0
2855
+ }
2856
+ }];
2857
+ if (row.value === value) return [];
2858
+ return [{
2859
+ type: "patch",
2860
+ table: SETTINGS_TABLE,
2861
+ key: [key],
2862
+ set: { value },
2863
+ guard: { v: Number(row._v) },
2864
+ previous: row
2865
+ }];
2866
+ });
2867
+ if (ops.length === 0) return;
2868
+ if (!(await adapter.write(ops)).ok) throw new Error(`${adapterName}: the schema settings changed during the migration; run it again.`);
2869
+ };
2870
+ const fillLateIndexes = async (adapter, tables, { dryRun = false } = {}) => {
2871
+ const fillIndex = adapter.migrations?.fillIndex;
2872
+ if (fillIndex === void 0) return [];
2873
+ const lacking = [];
2874
+ for (const { table: name, index } of LATE_INDEXES) {
2875
+ const table = tables.find((candidate) => candidate.name === name);
2876
+ if (table === void 0) continue;
2877
+ if (await fillIndex(table, index, { dryRun }) > 0) lacking.push(`${name}.${index}`);
2878
+ }
2879
+ return lacking;
2880
+ };
2881
+ const addLateColumns = async (adapter, tables, { dryRun = false } = {}) => {
2882
+ const addColumns = adapter.migrations?.addColumns;
2883
+ if (addColumns === void 0) return [];
2884
+ const lacking = [];
2885
+ for (const table of tables) {
2886
+ const columns = LATE_COLUMNS.filter(({ table: name }) => name === table.name).map(({ column }) => column);
2887
+ if (columns.length === 0) continue;
2888
+ const added = await addColumns(table, columns, { dryRun });
2889
+ lacking.push(...added.map((column) => `${table.name}.${column}`));
2890
+ }
2891
+ return lacking;
2892
+ };
2893
+ const migrateSchema = async (adapter, adapterName, tables, settings, ordered) => {
2894
+ if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
2895
+ const stored = await storedSettings(adapter, Object.keys(settings)).catch(() => void 0);
2896
+ if (stored !== void 0) refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
2897
+ await addLateColumns(adapter, tables);
2898
+ await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
2899
+ await fillLateIndexes(adapter, tables);
2900
+ await writeSchemaSettings(adapter, adapterName, settings, ordered);
2901
+ };
2536
2902
  //#endregion
2537
2903
  //#region ../plugin-core/dist/engine/database/cursor.mjs
2538
2904
  const encoder$1 = new TextEncoder();
@@ -2677,18 +3043,15 @@ const LOG_TABLES = [
2677
3043
  const LEASE_TABLE = "aggregate_lease";
2678
3044
  const LEASE = { id: "compaction" };
2679
3045
  const LEASE_MS = 3e4;
2680
- const WINDOW_MS$1 = {
2681
- log: 6e4,
2682
- memory: 15e3
2683
- };
3046
+ const WINDOW_MS$1 = 6e4;
2684
3047
  const LOG_PAGE = 200;
3048
+ const SKIP_AFTER_MS = 3e5;
2685
3049
  const GROUPS = {
2686
3050
  commit: 1,
2687
3051
  read: 8,
2688
3052
  flush: 256
2689
3053
  };
2690
3054
  const ATTEMPTS = 5;
2691
- const MAX_BUFFERED = 1e4;
2692
3055
  const log = defineTable({
2693
3056
  id: {
2694
3057
  type: "string",
@@ -2789,21 +3152,33 @@ const rewrite$1 = (change, key, current) => {
2789
3152
  previous: current
2790
3153
  };
2791
3154
  };
2792
- const compile = async (adapter, changes, shard) => {
2793
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
3155
+ const rowId = (model, key) => JSON.stringify([model.table.name, key]);
3156
+ const keysOf = (changes) => changes.map(({ key }) => [...key.slice(0, -1), 0]);
3157
+ const readCurrent = async (adapter, changes) => {
3158
+ const keys = keysOf(changes);
2794
3159
  const reads = /* @__PURE__ */ new Map();
2795
3160
  changes.forEach((change, at) => {
2796
- if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
3161
+ if (!rewrites(change)) return;
3162
+ const wanted = reads.get(change.model) ?? /* @__PURE__ */ new Map();
3163
+ wanted.set(rowId(change.model, keys[at]), keys[at]);
3164
+ reads.set(change.model, wanted);
2797
3165
  });
2798
3166
  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));
3167
+ await Promise.all([...reads].map(async ([model, wanted]) => {
3168
+ const keys = [...wanted.values()];
3169
+ const rows = await adapter.get(model.table, keys);
3170
+ keys.forEach((key, at) => {
3171
+ current.set(rowId(model, key), rows[at] ?? null);
3172
+ });
2802
3173
  }));
2803
- return changes.map((change, at) => current.has(at) ? rewrite$1(change, keys[at], current.get(at)) : increment(change, keys[at]));
3174
+ return current;
3175
+ };
3176
+ const build = (changes, current) => {
3177
+ const keys = keysOf(changes);
3178
+ 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
3179
  };
2805
3180
  const isOp = (op) => op !== void 0;
2806
- const sleep = (attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random()));
3181
+ const sleep$2 = (attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random()));
2807
3182
  const pack = (text) => {
2808
3183
  const runs = (text.match(/(.)\1*/gsu) ?? []).flatMap((run) => [run[0], run.length]);
2809
3184
  return JSON.stringify(runs).length < JSON.stringify(text).length ? runs : text;
@@ -2836,7 +3211,7 @@ const encode = async (changes) => {
2836
3211
  const zipped = await deflate(json);
2837
3212
  return zipped !== void 0 && zipped.length < json.length ? `z${zipped}` : json;
2838
3213
  };
2839
- const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS$1[mode] }, now }) => {
3214
+ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs = WINDOW_MS$1 }, now }) => {
2840
3215
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
2841
3216
  const holder = crypto.randomUUID().replaceAll("-", "");
2842
3217
  const table = (name) => schema.models.get(name).table;
@@ -2863,64 +3238,12 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
2863
3238
  }
2864
3239
  return changes;
2865
3240
  };
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
3241
  let nextDue = 0;
2922
3242
  let compacting;
2923
3243
  const known = /* @__PURE__ */ new Map();
3244
+ const skipped = LOG_TABLES.map(() => void 0);
3245
+ const past = (shard) => skipped[shard] === void 0 ? {} : { range: { gt: skipped[shard] } };
3246
+ const stampOf = (id) => Number.parseInt(id.slice(0, 9), 36);
2924
3247
  const idOf = (shard, id) => JSON.stringify([shard, id]);
2925
3248
  const leaseOp = (held, set) => {
2926
3249
  const next = {
@@ -2974,7 +3297,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
2974
3297
  const result = await adapter.write(ops);
2975
3298
  if (result.ok) return true;
2976
3299
  if (!("retry" in result)) return false;
2977
- await sleep(failures);
3300
+ await sleep$2(failures);
2978
3301
  }
2979
3302
  return false;
2980
3303
  };
@@ -3024,14 +3347,22 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3024
3347
  logs: (await Promise.all(LOG_TABLES.map(async (name, shard) => {
3025
3348
  const page = await engine.reads.findMany(name, {
3026
3349
  index: "oldest",
3027
- limit: LOG_PAGE
3350
+ limit: LOG_PAGE,
3351
+ ...past(shard)
3028
3352
  });
3029
3353
  more ||= page.next !== void 0;
3030
- return (await Promise.all(page.rows.map(async (row) => ({
3354
+ const decoded = await Promise.all(page.rows.map(async (row) => ({
3031
3355
  shard,
3032
3356
  row,
3033
3357
  changes: await decode(String(row.changes))
3034
- })))).flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
3358
+ })));
3359
+ const settled = now() - SKIP_AFTER_MS;
3360
+ for (const { row, changes } of decoded) {
3361
+ const id = String(row.id);
3362
+ if (changes !== void 0 || stampOf(id) >= settled) break;
3363
+ skipped[shard] = id;
3364
+ }
3365
+ return decoded.flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
3035
3366
  ...entry,
3036
3367
  changes
3037
3368
  }]);
@@ -3039,14 +3370,15 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3039
3370
  more
3040
3371
  };
3041
3372
  };
3042
- const rowsFor = async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp);
3043
3373
  const applyGroup = async (held, logs) => {
3374
+ const current = await readCurrent(adapter, logs.flatMap((entry) => [...entry.changes.values()]));
3375
+ const rowsFor = (changes) => build(changes, current).filter(isOp);
3044
3376
  for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
3045
3377
  const batch = logs.slice(0, count);
3046
3378
  const changes = mergeAll(/* @__PURE__ */ new Map(), batch.flatMap((entry) => [...entry.changes.values()]));
3047
3379
  const applied = batch.map(({ shard, row }) => [shard, row.id]);
3048
3380
  const lease = leaseOp(held, { applied: JSON.stringify(applied) });
3049
- const ops = [...await rowsFor([...changes.values()]), lease.op];
3381
+ const ops = [...rowsFor([...changes.values()]), lease.op];
3050
3382
  if (!adapter.fits(ops)) continue;
3051
3383
  for (const { shard, row } of batch) known.set(idOf(shard, row.id), row);
3052
3384
  return await commit(ops) ? {
@@ -3068,7 +3400,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3068
3400
  };
3069
3401
  const lease = leaseOp(held, {});
3070
3402
  const ops = [
3071
- ...await rowsFor(entries.slice(0, take)),
3403
+ ...rowsFor(entries.slice(0, take)),
3072
3404
  kept,
3073
3405
  lease.op
3074
3406
  ];
@@ -3084,11 +3416,12 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3084
3416
  if (held === void 0) return;
3085
3417
  let pending = true;
3086
3418
  let clear = false;
3419
+ let carried;
3087
3420
  try {
3088
3421
  for (let group = 0;; group += 1) {
3089
3422
  clear = await deleteApplied(held);
3090
3423
  if (!clear || !pending || group === groups) break;
3091
- const { logs, more } = await readLogs();
3424
+ const { logs, more } = carried ?? await readLogs();
3092
3425
  if (logs.length === 0) {
3093
3426
  pending = false;
3094
3427
  break;
@@ -3096,6 +3429,11 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3096
3429
  const applied = await applyGroup(held, logs);
3097
3430
  if (applied === void 0) break;
3098
3431
  [held, clear] = [applied.held, false];
3432
+ const rest = applied.count === 0 ? [] : logs.slice(applied.count);
3433
+ carried = rest.length > 0 ? {
3434
+ logs: rest,
3435
+ more
3436
+ } : void 0;
3099
3437
  pending = more || applied.count < logs.length;
3100
3438
  }
3101
3439
  } finally {
@@ -3113,25 +3451,13 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3113
3451
  compacting = void 0;
3114
3452
  });
3115
3453
  let checking;
3116
- const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name) => engine.reads.findMany(name, {
3454
+ const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name, shard) => engine.reads.findMany(name, {
3117
3455
  index: "oldest",
3118
- limit: 1
3456
+ limit: 1,
3457
+ ...past(shard)
3119
3458
  }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
3120
3459
  checking = void 0;
3121
3460
  });
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
3461
  return {
3136
3462
  async transaction(fn) {
3137
3463
  let changes = /* @__PURE__ */ new Map();
@@ -3157,7 +3483,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3157
3483
  aggregate
3158
3484
  });
3159
3485
  if (failure) throw failure.error;
3160
- if (mode === "log" && attempt.size > 0) {
3486
+ if (attempt.size > 0) {
3161
3487
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
3162
3488
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
3163
3489
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -3171,24 +3497,18 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3171
3497
  open = false;
3172
3498
  }
3173
3499
  });
3174
- if (changes.size > 0) await committed(changes);
3500
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
3175
3501
  return result;
3176
3502
  },
3177
3503
  async beforeRead(name) {
3178
3504
  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
- }
3505
+ if (await hasPending().catch((error) => {
3506
+ warn("read")(error);
3507
+ return false;
3508
+ })) await compact(true, GROUPS.read);
3186
3509
  },
3187
- flush,
3188
- async dispose() {
3189
- clearTimeout(timer);
3190
- timer = void 0;
3191
- await flush();
3510
+ async flush() {
3511
+ if (await hasPending()) await compact(true, GROUPS.flush);
3192
3512
  }
3193
3513
  };
3194
3514
  };
@@ -3307,7 +3627,8 @@ const fieldProblems = (definition, add) => {
3307
3627
  else if (field.required === false) add(`key field "${name}" is nullable`);
3308
3628
  else if (field.type === "json") add(`key field "${name}" is json`);
3309
3629
  }
3310
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
3630
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
3631
+ for (const [name, { type, maxLength, ascii }] of bounded) {
3311
3632
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
3312
3633
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
3313
3634
  }
@@ -3419,11 +3740,13 @@ const resolveSchema = (modules) => {
3419
3740
  ...maxLength === void 0 ? {} : { maxLength },
3420
3741
  ...ascii ? { ascii } : {}
3421
3742
  }));
3422
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
3743
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
3423
3744
  name: field,
3424
3745
  type,
3425
3746
  nullable: true,
3426
- ...multi ? { multi } : {}
3747
+ ...multi ? { multi } : {},
3748
+ ...maxLength === void 0 ? {} : { maxLength },
3749
+ ...ascii ? { ascii } : {}
3427
3750
  });
3428
3751
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
3429
3752
  name: metric,
@@ -3460,22 +3783,49 @@ const createEngineMigrator = (options) => {
3460
3783
  const makeResult = async (migrate = {}) => {
3461
3784
  const stored = await options.readSettings();
3462
3785
  refuseV0Database(options.adapterName, stored);
3463
- if (Object.entries(options.settings).every(([key, value]) => stored.get(key) === value)) return getEmptyMigrationResult();
3786
+ refuseNewerSchema(options.adapterName, stored, options.settings, options.ordered);
3787
+ const changed = Object.entries(options.settings).filter(([key, value]) => stored.get(key) !== value);
3788
+ if (changed.length === 0) {
3789
+ const columns = await addLateColumns(options.adapter, options.schema.tables, { dryRun: true });
3790
+ const lacking = await fillLateIndexes(options.adapter, options.schema.tables, { dryRun: true });
3791
+ if (columns.length === 0 && lacking.length === 0) return getEmptyMigrationResult();
3792
+ return {
3793
+ operations: [
3794
+ ...columns.map((column) => ({
3795
+ type: "custom",
3796
+ description: `Add column: ${column}`
3797
+ })),
3798
+ ...columns.length === 0 ? [] : [{
3799
+ type: "custom",
3800
+ description: "Create the tables and indexes the database lacks"
3801
+ }],
3802
+ ...lacking.length === 0 ? [] : [{
3803
+ type: "custom",
3804
+ description: `Write the index items rows lack: ${lacking.join(", ")}`
3805
+ }]
3806
+ ],
3807
+ execute: async () => {
3808
+ if (columns.length > 0) {
3809
+ await addLateColumns(options.adapter, options.schema.tables);
3810
+ await options.adapter.migrations.apply([...options.schema.tables, SETTINGS_TABLE]);
3811
+ }
3812
+ await fillLateIndexes(options.adapter, options.schema.tables);
3813
+ }
3814
+ };
3815
+ }
3464
3816
  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 ? [] : [{
3475
- 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)
3817
+ operations: [
3818
+ ...(await addLateColumns(options.adapter, options.schema.tables, { dryRun: true }).catch(() => [])).map((column) => ({
3819
+ type: "custom",
3820
+ description: `Add column: ${column}`
3821
+ })),
3822
+ {
3823
+ type: "custom",
3824
+ description: "Create the tables and indexes the database lacks"
3825
+ },
3826
+ ...migrate.updateSettings === false ? [] : [settingsOperation(stored, changed)]
3827
+ ],
3828
+ execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings, options.ordered)
3479
3829
  };
3480
3830
  };
3481
3831
  return {
@@ -3503,7 +3853,8 @@ const coreSettings = {
3503
3853
  };
3504
3854
  const coreTarget = {
3505
3855
  schema: coreSchema,
3506
- settings: coreSettings
3856
+ settings: coreSettings,
3857
+ ordered: ["schema.core"]
3507
3858
  };
3508
3859
  resolveSchema([aggregateBatchingModule]).tables;
3509
3860
  const pluginSettings = (plugins) => Object.fromEntries(plugins.map(({ id, schemaVersion }) => [`schema.${id}`, schemaVersion]));
@@ -3514,11 +3865,12 @@ const pluginModule = ({ id, schema, namespace }) => ({
3514
3865
  });
3515
3866
  const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBatching, retry, readSettings: readStored }) => {
3516
3867
  const fenced = withSchemaFence(adapter, name, coreSettings);
3517
- const createMigrator = ({ schema, settings } = coreTarget) => createEngineMigrator({
3868
+ const createMigrator = ({ schema, settings, ordered } = coreTarget) => createEngineMigrator({
3518
3869
  adapterName: name,
3519
3870
  adapter,
3520
3871
  schema,
3521
3872
  settings,
3873
+ ordered,
3522
3874
  readSettings: readStored ?? (async () => {
3523
3875
  const rows = await readSettings(adapter, Object.keys(settings)).catch((error) => {
3524
3876
  if (isMissingSchemaError(error)) return [];
@@ -3541,6 +3893,11 @@ const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBa
3541
3893
  //#region ../plugin-core/dist/engine/database/engineTransaction.mjs
3542
3894
  var StaleReadError = class extends Error {};
3543
3895
  const idOf = (table, key) => JSON.stringify([table, key]);
3896
+ const versionsOf = (ops) => JSON.stringify(ops.map((op) => op.type === "insert" ? [op.table.name, rowKey(op.table, op.row)] : [
3897
+ op.table.name,
3898
+ op.key,
3899
+ "guard" in op ? op.guard?.v : void 0
3900
+ ]));
3544
3901
  const versionOf = (row) => Number(row["_v"]);
3545
3902
  const isKeyed = (value) => value !== null && value !== void 0;
3546
3903
  const misuse = (table, message) => new DatabaseTransactionError(`${table}: ${message}`);
@@ -3872,7 +4229,10 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
3872
4229
  assertOutsideTransaction();
3873
4230
  let run;
3874
4231
  let negative;
3875
- for (let round = 0; round < attempts; round += 1) {
4232
+ let failures = 0;
4233
+ let lost;
4234
+ let busy = false;
4235
+ for (let round = 0;; round += 1) {
3876
4236
  const delay = round && Math.min(maxDelayMs, baseDelayMs * 2 ** (round - 1));
3877
4237
  if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay / 2 + Math.random() * (delay / 2)));
3878
4238
  run ??= await attempt(fn).catch((error) => {
@@ -3881,6 +4241,9 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
3881
4241
  });
3882
4242
  if (run === void 0) {
3883
4243
  onRetry?.("rerun", round + 1);
4244
+ lost = void 0;
4245
+ busy = false;
4246
+ if ((failures += 1) >= attempts) break;
3884
4247
  continue;
3885
4248
  }
3886
4249
  let aggregates;
@@ -3890,9 +4253,16 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
3890
4253
  if (!(error instanceof NegativeGaugeError)) throw error;
3891
4254
  negative = error;
3892
4255
  onRetry?.("rerun", round + 1);
4256
+ busy = false;
3893
4257
  run = void 0;
4258
+ lost = void 0;
4259
+ if ((failures += 1) >= attempts) break;
3894
4260
  continue;
3895
4261
  }
4262
+ const versions = versionsOf(aggregates);
4263
+ if (lost !== void 0 && versions !== lost) failures -= 1;
4264
+ lost = void 0;
4265
+ if (failures >= attempts) break;
3896
4266
  const ops = [...run.ops, ...aggregates];
3897
4267
  if (ops.length <= 1 && ops.every(({ type }) => type === "check")) return run.result;
3898
4268
  if (!adapter.fits(ops)) throw new DatabaseConstraintError("too_large", ops[0].table.name);
@@ -3904,16 +4274,21 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
3904
4274
  }
3905
4275
  if (outcome.ok) return run.result;
3906
4276
  const failed = "failedOp" in outcome ? outcome.failedOp : void 0;
4277
+ busy = failed === void 0;
3907
4278
  if (failed === void 0 || failed >= run.ops.length) {
3908
4279
  onRetry?.("resend", round + 1);
4280
+ failures += 1;
4281
+ if (failed !== void 0) lost = versions;
4282
+ else if (failures >= attempts) break;
3909
4283
  continue;
3910
4284
  }
3911
4285
  const reason = await classify(ops[failed], run.read);
3912
4286
  if (reason) throw new DatabaseConstraintError(reason, ops[failed].table.name);
3913
4287
  onRetry?.("rerun", round + 1);
3914
4288
  run = void 0;
4289
+ if ((failures += 1) >= attempts) break;
3915
4290
  }
3916
- throw negative ?? new DatabaseConflictError(`The transaction conflicted ${attempts} times.`);
4291
+ throw negative ?? new DatabaseConflictError(busy ? `The database stayed busy through ${attempts} attempts of the transaction, as a store does at its throughput limit.` : `The transaction conflicted ${attempts} times.`);
3917
4292
  } };
3918
4293
  };
3919
4294
  //#endregion
@@ -4147,9 +4522,6 @@ const createDatabaseEngine = ({ batching, now = Date.now, meter, ...options }) =
4147
4522
  flush: async () => {
4148
4523
  await batches?.flush();
4149
4524
  },
4150
- dispose: async () => {
4151
- await batches?.dispose();
4152
- },
4153
4525
  database(module) {
4154
4526
  const name = (model) => module.namespace ? `${module.namespace}_${model}` : model;
4155
4527
  return {
@@ -4217,8 +4589,7 @@ const createEngine = (database, { plugins = [], now = Date.now } = {}) => {
4217
4589
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
4218
4590
  return engine.database(module);
4219
4591
  },
4220
- flush: () => engine.flush(),
4221
- dispose: () => engine.dispose()
4592
+ flush: () => engine.flush()
4222
4593
  };
4223
4594
  };
4224
4595
  //#endregion
@@ -4306,19 +4677,19 @@ const createSqlAdapter = ({ executor, tablePrefix = "", maxOps = 1e3, maxParams
4306
4677
  const where = (bind, key, v) => `${keyMatch(bind, table, key)}${v === void 0 ? "" : ` AND ${version} = ${bind(v)}`}${when ? ` AND ${when(bind)}` : ""}`;
4307
4678
  const insert = (bind, into, columns, values) => `INSERT INTO ${into} (${columns.map(quote).join(", ")}) ${when ? `SELECT ${values.join(", ")} WHERE ${when(bind)}` : `VALUES (${values.join(", ")})`}`;
4308
4679
  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) => {
4680
+ const entries = (key, row, changed, stale = true) => table.indexes.flatMap((index) => {
4310
4681
  const columns = [...index.eq, ...indexOrderColumns(table, index)];
4311
4682
  if (!isMultiIndex(table, index) || changed && !columns.some((column) => changed.includes(column))) return [];
4312
4683
  const into = tableOf(table, index);
4313
4684
  const found = row ? indexEntries(table, index, row) : [];
4314
4685
  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) => {
4686
+ return [...stale ? [sql((bind) => `DELETE FROM ${into} WHERE ${where(bind, key)}`)] : [], ...found.map((eq) => sql((bind) => {
4316
4687
  const values = [...eq, ...order].map((value) => bind(value));
4317
4688
  return insert(bind, into, columns, values);
4318
4689
  }))];
4319
4690
  });
4320
4691
  switch (op.type) {
4321
- case "insert": return [sql((bind) => insertRow(bind, op.row)), ...entries(rowKey(table, op.row), op.row)];
4692
+ case "insert": return [sql((bind) => insertRow(bind, op.row)), ...entries(rowKey(table, op.row), op.row, void 0, false)];
4322
4693
  case "patch": return [sql((bind) => {
4323
4694
  const set = Object.entries(op.set).map(([column, value]) => `${quote(column)} = ${bind(value, findPhysicalColumn(table, column))}`);
4324
4695
  return `UPDATE ${name} SET ${[...set, `${version} = ${version} + 1`].join(", ")} WHERE ${where(bind, op.key, op.guard.v)}`;
@@ -4460,14 +4831,32 @@ const createSqlAdapter = ({ executor, tablePrefix = "", maxOps = 1e3, maxParams
4460
4831
  return done;
4461
4832
  })).at(-1)?.changes ?? 0;
4462
4833
  },
4463
- migrations: { async apply(tables) {
4464
- const created = executor.batch && !tables.includes(WRITE_GUARD_TABLE) ? [...tables, WRITE_GUARD_TABLE] : tables;
4465
- const statements = createTableStatements(dialect, created, tablePrefix);
4466
- for (const text of statements) await executor.execute({
4467
- sql: text,
4468
- params: []
4469
- });
4470
- } }
4834
+ migrations: {
4835
+ async apply(tables) {
4836
+ const created = executor.batch && !tables.includes(WRITE_GUARD_TABLE) ? [...tables, WRITE_GUARD_TABLE] : tables;
4837
+ const statements = createTableStatements(dialect, created, tablePrefix);
4838
+ for (const text of statements) await executor.execute({
4839
+ sql: text,
4840
+ params: []
4841
+ });
4842
+ },
4843
+ async addColumns(table, columns, { dryRun = false } = {}) {
4844
+ const [shape] = sqlTableShapes(dialect, [table], tablePrefix);
4845
+ const state = await readSqlSchemaState(executor);
4846
+ if (shape === void 0 || !state.hasTable(shape.name)) return [];
4847
+ const missing = columns.filter((column) => !state.hasColumn(shape.name, column));
4848
+ if (dryRun) return missing;
4849
+ for (const name of missing) {
4850
+ const column = shape.columns.find((candidate) => candidate.name === name);
4851
+ if (column === void 0 || column.notNull) throw new Error(`${table.name}.${name} can't be added to an existing table: only an optional column can.`);
4852
+ await executor.execute({
4853
+ sql: `ALTER TABLE ${quoteSql(dialect, shape.name)} ADD COLUMN ${quoteSql(dialect, name)} ${column.type}`,
4854
+ params: []
4855
+ });
4856
+ }
4857
+ return missing;
4858
+ }
4859
+ }
4471
4860
  };
4472
4861
  };
4473
4862
  //#endregion
@@ -17698,7 +18087,7 @@ const postgres = (config) => {
17698
18087
  };
17699
18088
  //#endregion
17700
18089
  //#region ../../packages/server/dist/version.mjs
17701
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.6";
18090
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.61";
17702
18091
  //#endregion
17703
18092
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
17704
18093
  const createVersionRouteHandlers = (plugins = []) => {
@@ -17824,9 +18213,14 @@ const releaseCatalogScopeKeyOf = (input) => input.strategy === "APP_VERSION" ? c
17824
18213
  platform: input.platform,
17825
18214
  strategy: "FINGERPRINT"
17826
18215
  });
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);
18216
+ const parseReleaseCatalogRow = ({ payload, ...row }) => ({
18217
+ row,
18218
+ compiled: parseCompiledCatalog(payload, row.strategy)
18219
+ });
18220
+ const projectParsedReleaseCatalogRow = (parsed, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
18221
+ if (parsed === null) return null;
18222
+ const { row, compiled } = parsed;
18223
+ 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
18224
  const appVersion = input.strategy === "APP_VERSION" ? input.appVersion : void 0;
17831
18225
  return {
17832
18226
  catalogId: row.catalog_id,
@@ -17839,6 +18233,7 @@ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyO
17839
18233
  scopeKey
17840
18234
  };
17841
18235
  };
18236
+ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => projectParsedReleaseCatalogRow(row === null ? null : parseReleaseCatalogRow(row), input, scopeKey);
17842
18237
  //#endregion
17843
18238
  //#region ../../packages/server/dist/db/updateArtifacts.mjs
17844
18239
  const HBC_ASSET_PATH_RE = /\.bundle$/;
@@ -18430,9 +18825,9 @@ const baseBundleIdsOf = (row, range, bundleId, limit) => {
18430
18825
  };
18431
18826
  //#endregion
18432
18827
  //#region ../../packages/server/dist/core/reads.mjs
18433
- const PAGE$3 = 500;
18434
- const pick$1 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
18435
- const toBundleRow = pick$1([
18828
+ const PAGE$5 = 500;
18829
+ const pick$2 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
18830
+ const toBundleRow = pick$2([
18436
18831
  "id",
18437
18832
  "platform",
18438
18833
  "git_commit_hash",
@@ -18441,7 +18836,7 @@ const toBundleRow = pick$1([
18441
18836
  "manifest_file_hash",
18442
18837
  "asset_base_storage_uri"
18443
18838
  ]);
18444
- const toPatchRow = pick$1([
18839
+ const toPatchRow = pick$2([
18445
18840
  "id",
18446
18841
  "bundle_id",
18447
18842
  "base_bundle_id",
@@ -18451,7 +18846,7 @@ const toPatchRow = pick$1([
18451
18846
  "byte_size",
18452
18847
  "order_index"
18453
18848
  ]);
18454
- const toReleaseRow = pick$1([
18849
+ const pickReleaseRow = pick$2([
18455
18850
  "id",
18456
18851
  "revision",
18457
18852
  "scope_key",
@@ -18472,7 +18867,13 @@ const toReleaseRow = pick$1([
18472
18867
  "created_at_ms",
18473
18868
  "updated_at_ms"
18474
18869
  ]);
18475
- const toCatalogRow = pick$1([
18870
+ const toReleaseRow = (row) => {
18871
+ return {
18872
+ ...pickReleaseRow(row),
18873
+ label: typeof row.label === "number" ? row.label : null
18874
+ };
18875
+ };
18876
+ const toCatalogRow = pick$2([
18476
18877
  "scope_key",
18477
18878
  "catalog_id",
18478
18879
  "strategy",
@@ -18487,7 +18888,7 @@ const toCatalogRow = pick$1([
18487
18888
  "is_tombstone",
18488
18889
  "updated_at_ms"
18489
18890
  ]);
18490
- const toChannelRow = pick$1(["id", "name"]);
18891
+ const toChannelRow = pick$2(["id", "name"]);
18491
18892
  const drain$1 = async (read) => {
18492
18893
  const rows = [];
18493
18894
  let cursor;
@@ -18498,7 +18899,14 @@ const drain$1 = async (read) => {
18498
18899
  } while (cursor !== void 0);
18499
18900
  return rows;
18500
18901
  };
18501
- const after = (input) => input.after === void 0 ? {} : { range: (input.order ?? "asc") === "asc" ? { gt: input.after } : { lt: input.after } };
18902
+ const after = (input) => {
18903
+ const asc = (input.order ?? "asc") === "asc";
18904
+ const range = {
18905
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
18906
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
18907
+ };
18908
+ return Object.keys(range).length === 0 ? {} : { range };
18909
+ };
18502
18910
  const createCoreReads = (db, storage) => {
18503
18911
  const detail = async (row) => {
18504
18912
  const count = row._refs_bundle_patches_bundle_id ?? 0;
@@ -18508,7 +18916,7 @@ const createCoreReads = (db, storage) => {
18508
18916
  const page = await db.findMany("bundle_patches", {
18509
18917
  index: "byBundle",
18510
18918
  where: { bundle_id: row.id },
18511
- limit: Math.min(count - patches.length, PAGE$3),
18919
+ limit: Math.min(count - patches.length, PAGE$5),
18512
18920
  ...cursor === void 0 ? {} : { cursor }
18513
18921
  });
18514
18922
  patches.push(...page.rows.map(toPatchRow));
@@ -18609,6 +19017,18 @@ const createCoreReads = (db, storage) => {
18609
19017
  const row = await db.findOne("releases", { id });
18610
19018
  return row === null ? null : toReleaseRow(row);
18611
19019
  },
19020
+ async getReleaseByLabel({ channel, platform, label }) {
19021
+ const found = await db.findOne("releases", {
19022
+ channel_id: `channel:${encodeChannelKey(channel)}`,
19023
+ platform,
19024
+ label
19025
+ });
19026
+ if (found === null) return null;
19027
+ const row = await db.findOne("releases", { id: found.id });
19028
+ if (row === null) return null;
19029
+ const release = toReleaseRow(row);
19030
+ return release.label === label && release.platform === platform ? release : null;
19031
+ },
18612
19032
  async listReleases(input) {
18613
19033
  const { filter } = input;
18614
19034
  const options = {
@@ -18674,14 +19094,41 @@ const createCoreReads = (db, storage) => {
18674
19094
  ...after(input)
18675
19095
  })).rows.map(toCatalogRow);
18676
19096
  },
18677
- async listChannels() {
19097
+ async listReleaseScopeKeys(input) {
19098
+ const scopeKeys = [];
19099
+ for (let last = input.after ?? ""; scopeKeys.length < input.limit;) {
19100
+ const { rows } = await db.findMany("releases", {
19101
+ index: "scopes",
19102
+ where: {},
19103
+ limit: 1,
19104
+ range: { gt: last }
19105
+ });
19106
+ if (rows[0] === void 0) break;
19107
+ last = rows[0].scope_key;
19108
+ scopeKeys.push(last);
19109
+ }
19110
+ return scopeKeys;
19111
+ },
19112
+ async listChannels(input) {
19113
+ if (input !== void 0) return (await db.findMany("channels", {
19114
+ index: "all",
19115
+ where: {},
19116
+ order: input.order ?? "asc",
19117
+ limit: input.limit,
19118
+ ...after(input)
19119
+ })).rows.map(toChannelRow);
18678
19120
  return (await drain$1((page) => db.findMany("channels", {
18679
19121
  index: "all",
18680
19122
  where: {},
18681
- limit: PAGE$3,
19123
+ limit: PAGE$5,
18682
19124
  ...page
18683
19125
  }))).map(toChannelRow);
18684
19126
  },
19127
+ async getChannels(ids) {
19128
+ const unique = [...new Set(ids)];
19129
+ if (unique.length === 0) return [];
19130
+ return (await db.findByKeys("channels", unique.map((id) => ({ id })))).flatMap((row) => row ? [toChannelRow(row)] : []);
19131
+ },
18685
19132
  async findChannelByName(name) {
18686
19133
  const row = await db.findOne("channels", { name });
18687
19134
  return row === null ? null : toChannelRow(row);
@@ -18689,8 +19136,562 @@ const createCoreReads = (db, storage) => {
18689
19136
  };
18690
19137
  };
18691
19138
  //#endregion
19139
+ //#region ../../packages/server/dist/core/iosDevices.mjs
19140
+ const UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
19141
+ const normalizeIosUdid = (value) => {
19142
+ const trimmed = value.trim();
19143
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
19144
+ };
19145
+ const NAME_MAX_LENGTH = 100;
19146
+ const EMAIL_MAX_LENGTH = 320;
19147
+ const ISSUER_MAX_LENGTH = 64;
19148
+ const ACCOUNT_ROW = "registry";
19149
+ const ERROR_MAX_LENGTH = 512;
19150
+ const STATUSES = [
19151
+ "pending",
19152
+ "approved",
19153
+ "registered"
19154
+ ];
19155
+ const OUTCOMES = [
19156
+ "registered",
19157
+ "refused",
19158
+ "disabled",
19159
+ "missing"
19160
+ ];
19161
+ const IOS_DEVICE_DISABLED_ERROR = "Disabled in the Apple account.";
19162
+ const IOS_DEVICE_MISSING_ERROR = "Gone from the Apple account. Approve it again to register it.";
19163
+ var IosDeviceInputError = class extends TypeError {
19164
+ name = "IosDeviceInputError";
19165
+ };
19166
+ const pick$1 = (row) => ({
19167
+ id: row.id,
19168
+ udid: row.udid,
19169
+ name: row.name,
19170
+ status: row.status,
19171
+ requested_by: row.requested_by ?? null,
19172
+ created_at_ms: row.created_at_ms,
19173
+ approved_by: row.approved_by ?? null,
19174
+ approved_at_ms: row.approved_at_ms ?? null,
19175
+ registered_at_ms: row.registered_at_ms ?? null,
19176
+ apple_issuer_id: row.apple_issuer_id ?? null,
19177
+ apple_error: row.apple_error ?? null,
19178
+ build_id: row.build_id ?? null
19179
+ });
19180
+ const udidOf = (udid) => {
19181
+ const key = typeof udid === "string" ? normalizeIosUdid(udid) : null;
19182
+ if (key === null) throw new IosDeviceInputError("Invalid iOS device: udid must be 40 hex digits, or 8 and 16 joined by a hyphen.");
19183
+ return key;
19184
+ };
19185
+ const nameOf = (name) => {
19186
+ const trimmed = typeof name === "string" ? name.trim() : "";
19187
+ if (trimmed.length === 0 || trimmed.length > NAME_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: name must be 1 to ${NAME_MAX_LENGTH} characters.`);
19188
+ return trimmed;
19189
+ };
19190
+ const personOf = (value, field) => {
19191
+ if (value === null) return null;
19192
+ const email = typeof value === "string" ? value.trim().toLowerCase() : "";
19193
+ 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.`);
19194
+ return email;
19195
+ };
19196
+ const errorText = (text) => {
19197
+ const line = text.replace(/\s+/gu, " ").trim();
19198
+ return line.length > ERROR_MAX_LENGTH ? `${line.slice(0, 511)}…` : line;
19199
+ };
19200
+ const createIosDeviceApi = (db, { now = Date.now } = {}) => {
19201
+ const findIosDevice = async (udid) => {
19202
+ const key = normalizeIosUdid(udid);
19203
+ if (key === null) return null;
19204
+ const row = await db.findOne("ios_devices", { udid: key });
19205
+ return row === null ? null : pick$1(row);
19206
+ };
19207
+ const accountOfRows = async () => {
19208
+ const { rows } = await db.findMany("ios_devices", {
19209
+ index: "byRegistration",
19210
+ where: {},
19211
+ order: "asc",
19212
+ limit: 1,
19213
+ range: { gte: 0 }
19214
+ });
19215
+ return (rows[0] === void 0 ? null : pick$1(rows[0]))?.apple_issuer_id ?? null;
19216
+ };
19217
+ return {
19218
+ async listIosDevices(input) {
19219
+ if (input.status !== void 0 && !STATUSES.includes(input.status)) throw new IosDeviceInputError(`Invalid iOS device status: ${String(input.status)}. Expected ${STATUSES.join(", ")}.`);
19220
+ const page = {
19221
+ order: input.order ?? "asc",
19222
+ limit: input.limit,
19223
+ ...after(input)
19224
+ };
19225
+ const { rows } = input.status === void 0 ? await db.findMany("ios_devices", {
19226
+ index: "all",
19227
+ where: {},
19228
+ ...page
19229
+ }) : await db.findMany("ios_devices", {
19230
+ index: "byStatus",
19231
+ where: { status: input.status },
19232
+ ...page
19233
+ });
19234
+ return rows.map(pick$1);
19235
+ },
19236
+ findIosDevice,
19237
+ async requestIosDevice(input) {
19238
+ const udid = udidOf(input.udid);
19239
+ const name = nameOf(input.name);
19240
+ const requestedBy = personOf(input.requestedBy, "requestedBy");
19241
+ const existing = await db.findOne("ios_devices", { udid });
19242
+ if (existing !== null) return {
19243
+ device: pick$1(existing),
19244
+ created: false
19245
+ };
19246
+ const device = {
19247
+ id: createUUIDv7(),
19248
+ udid,
19249
+ name,
19250
+ status: "pending",
19251
+ requested_by: requestedBy,
19252
+ created_at_ms: now(),
19253
+ approved_by: null,
19254
+ approved_at_ms: null,
19255
+ registered_at_ms: null,
19256
+ apple_issuer_id: null,
19257
+ apple_error: null,
19258
+ build_id: null
19259
+ };
19260
+ try {
19261
+ await db.transaction(async (tx) => {
19262
+ tx.create("ios_devices", device);
19263
+ });
19264
+ } catch (error) {
19265
+ if (error instanceof DatabaseConstraintError && error.reason === "unique") {
19266
+ const winner = await db.findOne("ios_devices", { udid });
19267
+ if (winner !== null) return {
19268
+ device: pick$1(winner),
19269
+ created: false
19270
+ };
19271
+ }
19272
+ throw error;
19273
+ }
19274
+ return {
19275
+ device,
19276
+ created: true
19277
+ };
19278
+ },
19279
+ async approveIosDevice(id, input) {
19280
+ const name = input.name === void 0 ? void 0 : nameOf(input.name);
19281
+ const approvedBy = personOf(input.approvedBy, "approvedBy");
19282
+ return db.transaction(async (tx) => {
19283
+ const row = await tx.findOne("ios_devices", { id });
19284
+ if (row === null) return null;
19285
+ const device = pick$1(row);
19286
+ const set = {
19287
+ ...name === void 0 || name === device.name ? {} : { name },
19288
+ ...device.status === "pending" ? {
19289
+ status: "approved",
19290
+ approved_by: approvedBy,
19291
+ approved_at_ms: now()
19292
+ } : {}
19293
+ };
19294
+ if (Object.keys(set).length === 0) return device;
19295
+ tx.update("ios_devices", row, set);
19296
+ return {
19297
+ ...device,
19298
+ ...set
19299
+ };
19300
+ });
19301
+ },
19302
+ async renameIosDevice(id, input) {
19303
+ const name = nameOf(input);
19304
+ return db.transaction(async (tx) => {
19305
+ const row = await tx.findOne("ios_devices", { id });
19306
+ if (row === null) return null;
19307
+ const device = pick$1(row);
19308
+ if (device.name === name) return device;
19309
+ tx.update("ios_devices", row, { name });
19310
+ return {
19311
+ ...device,
19312
+ name
19313
+ };
19314
+ });
19315
+ },
19316
+ async recordIosDeviceOutcome({ id, seen, issuerId, outcome, reason }) {
19317
+ if (!OUTCOMES.includes(outcome)) throw new IosDeviceInputError(`Invalid iOS device outcome: ${String(outcome)}. Expected ${OUTCOMES.join(", ")}.`);
19318
+ 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.`);
19319
+ return db.transaction(async (tx) => {
19320
+ const row = await tx.findOne("ios_devices", { id });
19321
+ if (row === null) return null;
19322
+ const device = pick$1(row);
19323
+ if (device.status !== seen.status || device.approved_at_ms !== seen.approvedAtMs || device.apple_issuer_id !== null && device.apple_issuer_id !== issuerId) return null;
19324
+ let set;
19325
+ switch (outcome) {
19326
+ case "registered":
19327
+ if (device.status === "pending") return null;
19328
+ set = {
19329
+ status: "registered",
19330
+ registered_at_ms: device.registered_at_ms ?? now(),
19331
+ apple_issuer_id: issuerId,
19332
+ apple_error: null
19333
+ };
19334
+ break;
19335
+ case "refused":
19336
+ if (device.status !== "approved") return null;
19337
+ set = { apple_error: errorText(reason === void 0 || reason.trim() === "" ? "Apple refused it." : reason) };
19338
+ break;
19339
+ case "disabled":
19340
+ if (device.status === "pending") return null;
19341
+ set = { apple_error: IOS_DEVICE_DISABLED_ERROR };
19342
+ break;
19343
+ case "missing":
19344
+ if (device.status !== "registered") return null;
19345
+ set = {
19346
+ status: "pending",
19347
+ approved_by: null,
19348
+ approved_at_ms: null,
19349
+ apple_error: IOS_DEVICE_MISSING_ERROR
19350
+ };
19351
+ }
19352
+ if (Object.entries(set).some(([column, value]) => device[column] !== (value ?? null))) tx.update("ios_devices", row, set);
19353
+ return {
19354
+ ...device,
19355
+ ...set
19356
+ };
19357
+ });
19358
+ },
19359
+ async markIosDevicesInBuild({ buildId, ids }) {
19360
+ for (const id of new Set(ids)) await db.transaction(async (tx) => {
19361
+ const row = await tx.findOne("ios_devices", { id });
19362
+ if (row === null || typeof row.build_id === "string" && row.build_id >= buildId) return;
19363
+ tx.update("ios_devices", row, { build_id: buildId });
19364
+ });
19365
+ },
19366
+ async findIosDeviceAccount() {
19367
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
19368
+ const issuerId = existing === null ? await accountOfRows() : existing.apple_issuer_id;
19369
+ return issuerId === null ? null : { issuerId };
19370
+ },
19371
+ async claimIosDeviceAccount(issuerId) {
19372
+ 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.`);
19373
+ const answer = (held) => ({
19374
+ issuerId: held,
19375
+ claimed: held === issuerId
19376
+ });
19377
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
19378
+ if (existing !== null) return answer(existing.apple_issuer_id);
19379
+ const holder = await accountOfRows() ?? issuerId;
19380
+ try {
19381
+ await db.transaction(async (tx) => {
19382
+ tx.create("ios_device_account", {
19383
+ id: ACCOUNT_ROW,
19384
+ apple_issuer_id: holder,
19385
+ claimed_at_ms: now()
19386
+ });
19387
+ });
19388
+ return answer(holder);
19389
+ } catch (error) {
19390
+ if (error instanceof DatabaseConstraintError && (error.reason === "exists" || error.reason === "unique")) {
19391
+ const winner = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
19392
+ if (winner !== null) return answer(winner.apple_issuer_id);
19393
+ }
19394
+ throw error;
19395
+ }
19396
+ },
19397
+ async deleteIosDevice(id, only) {
19398
+ const requestedBy = only?.requestedBy === void 0 ? void 0 : personOf(only.requestedBy, "requestedBy");
19399
+ return db.transaction(async (tx) => {
19400
+ const row = await tx.findOne("ios_devices", { id });
19401
+ if (row === null) return null;
19402
+ const device = pick$1(row);
19403
+ if (only?.status !== void 0 && device.status !== only.status || requestedBy !== void 0 && device.requested_by !== requestedBy) return null;
19404
+ await tx.delete("ios_devices", row);
19405
+ return device;
19406
+ });
19407
+ }
19408
+ };
19409
+ };
19410
+ //#endregion
19411
+ //#region ../../packages/server/dist/core/nativeBuildDestinations.mjs
19412
+ const NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
19413
+ android: [
19414
+ "play-internal",
19415
+ "play-closed",
19416
+ "play-open",
19417
+ "play-production"
19418
+ ],
19419
+ ios: ["testflight"]
19420
+ };
19421
+ //#endregion
19422
+ //#region ../../packages/server/dist/core/labels.mjs
19423
+ const labelSequenceId = (channelId, platform) => `releases/${platform}/${channelId}`;
19424
+ const LABEL_PLATFORMS = ["ios", "android"];
19425
+ var NeedsLabelFill = class extends Error {
19426
+ channelId;
19427
+ platform;
19428
+ constructor(channelId, platform) {
19429
+ super(`Release labels of ${platform} ${channelId} need a fill first.`);
19430
+ this.channelId = channelId;
19431
+ this.platform = platform;
19432
+ }
19433
+ };
19434
+ const createLabelAllocator = (tx, used, caughtUp) => {
19435
+ const sequences = /* @__PURE__ */ new Map();
19436
+ return {
19437
+ async next(channelId, platform) {
19438
+ const id = labelSequenceId(channelId, platform);
19439
+ let sequence = sequences.get(id);
19440
+ if (sequence === void 0) {
19441
+ const row = await tx.findOne("label_sequences", { id });
19442
+ if (row === null || !row.is_filled) {
19443
+ const channel = row === null ? await tx.findOne("channels", { id: channelId }) : null;
19444
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) throw new NeedsLabelFill(channelId, platform);
19445
+ }
19446
+ const read = row?.last_label ?? 0;
19447
+ sequence = {
19448
+ row,
19449
+ read,
19450
+ last: read
19451
+ };
19452
+ sequences.set(id, sequence);
19453
+ used.set(id, {
19454
+ channelId,
19455
+ platform,
19456
+ read
19457
+ });
19458
+ }
19459
+ sequence.last += 1;
19460
+ return sequence.last;
19461
+ },
19462
+ caughtUp(channelId, platform) {
19463
+ caughtUp.set(labelSequenceId(channelId, platform), {
19464
+ channelId,
19465
+ platform
19466
+ });
19467
+ },
19468
+ flush() {
19469
+ for (const [id, { row, read, last }] of sequences) if (row === null) tx.create("label_sequences", {
19470
+ id,
19471
+ last_label: last,
19472
+ is_filled: true
19473
+ });
19474
+ else if (last !== read) tx.update("label_sequences", row, { last_label: last });
19475
+ }
19476
+ };
19477
+ };
19478
+ const FILL_BATCH = 25;
19479
+ const PAGE$4 = 500;
19480
+ const PAUSE_MS$1 = 1e3;
19481
+ const MAX_PAUSE_MS$1 = 32e3;
19482
+ const sleep$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
19483
+ const fillLabels = async (db, { channelId, platform }, { dryRun = false } = {}) => {
19484
+ const id = labelSequenceId(channelId, platform);
19485
+ let labeled = 0;
19486
+ let batchSize = FILL_BATCH;
19487
+ let paused = 0;
19488
+ const label = async (ids) => {
19489
+ for (let at = 0; at < ids.length;) {
19490
+ const batch = ids.slice(at, at + batchSize);
19491
+ try {
19492
+ labeled += await db.transaction(async (tx) => {
19493
+ const counter = await tx.findOne("label_sequences", { id });
19494
+ let last = counter?.last_label ?? 0;
19495
+ let count = 0;
19496
+ for (const releaseId of batch) {
19497
+ const row = await tx.findOne("releases", { id: releaseId });
19498
+ if (row === null || typeof row.label === "number") continue;
19499
+ last += 1;
19500
+ count += 1;
19501
+ tx.update("releases", row, { label: last });
19502
+ }
19503
+ if (counter === null) tx.create("label_sequences", {
19504
+ id,
19505
+ last_label: last,
19506
+ is_filled: false
19507
+ });
19508
+ else if (last !== counter.last_label) tx.update("label_sequences", counter, { last_label: last });
19509
+ return count;
19510
+ });
19511
+ at += batch.length;
19512
+ paused = 0;
19513
+ } catch (error) {
19514
+ if (batchSize > 1 && error instanceof DatabaseConstraintError && error.reason === "too_large") {
19515
+ batchSize = Math.max(1, Math.floor(batchSize / 2));
19516
+ continue;
19517
+ }
19518
+ if (!isDatabaseBusyError(error) || paused >= MAX_PAUSE_MS$1) throw error;
19519
+ batchSize = Math.max(1, Math.floor(batchSize / 2));
19520
+ paused = paused === 0 ? PAUSE_MS$1 : paused * 2;
19521
+ await sleep$1(paused);
19522
+ }
19523
+ }
19524
+ };
19525
+ let cursor;
19526
+ do {
19527
+ const page = await db.findMany("releases", {
19528
+ index: "byChannelPlatform",
19529
+ where: {
19530
+ channel_id: channelId,
19531
+ platform
19532
+ },
19533
+ limit: PAGE$4,
19534
+ ...cursor === void 0 ? {} : { cursor }
19535
+ });
19536
+ const unlabeled = page.rows.filter((row) => typeof row.label !== "number").map((row) => row.id);
19537
+ if (dryRun) labeled += unlabeled.length;
19538
+ else await label(unlabeled);
19539
+ cursor = page.next;
19540
+ } while (cursor !== void 0);
19541
+ if (dryRun) return labeled;
19542
+ await db.transaction(async (tx) => {
19543
+ const counter = await tx.findOne("label_sequences", { id });
19544
+ if (counter === null) tx.create("label_sequences", {
19545
+ id,
19546
+ last_label: 0,
19547
+ is_filled: true
19548
+ });
19549
+ else if (!counter.is_filled) tx.update("label_sequences", counter, { is_filled: true });
19550
+ });
19551
+ return labeled;
19552
+ };
19553
+ const probeLabelSchema = async (db, { channelId, platform }) => {
19554
+ await db.findOne("label_sequences", { id: labelSequenceId(channelId, platform) });
19555
+ await db.findMany("releases", {
19556
+ index: "byLabel",
19557
+ where: {
19558
+ channel_id: channelId,
19559
+ platform,
19560
+ label: 0
19561
+ },
19562
+ limit: 1
19563
+ });
19564
+ };
19565
+ const REPAIRS = 4;
19566
+ const RACES = 32;
19567
+ const writeWithLabels = async (db, write) => {
19568
+ const filled = /* @__PURE__ */ new Set();
19569
+ const fill = async (pairs) => {
19570
+ for (const pair of pairs) {
19571
+ filled.add(labelSequenceId(pair.channelId, pair.platform));
19572
+ await fillLabels(db, pair);
19573
+ }
19574
+ };
19575
+ for (let repairs = 0, races = 0;;) {
19576
+ const used = /* @__PURE__ */ new Map();
19577
+ const caughtUp = /* @__PURE__ */ new Map();
19578
+ try {
19579
+ return await db.transaction(async (tx) => {
19580
+ used.clear();
19581
+ caughtUp.clear();
19582
+ const labels = createLabelAllocator(tx, used, caughtUp);
19583
+ const result = await write(tx, labels);
19584
+ labels.flush();
19585
+ return result;
19586
+ });
19587
+ } catch (error) {
19588
+ const needs = error instanceof NeedsLabelFill ? [error] : error instanceof DatabaseConstraintError && error.reason === "too_large" ? [...caughtUp.values()] : [];
19589
+ if (needs.length > 0) {
19590
+ const fresh = needs.some(({ channelId, platform }) => !filled.has(labelSequenceId(channelId, platform)));
19591
+ if (fresh || repairs < REPAIRS) {
19592
+ if (!fresh) repairs += 1;
19593
+ await fill(needs);
19594
+ continue;
19595
+ }
19596
+ }
19597
+ if (error instanceof DatabaseConstraintError && error.reason === "unique" && error.model === "releases" && used.size > 0) {
19598
+ if (await db.transaction(async (tx) => {
19599
+ const moves = [];
19600
+ for (const [id, { channelId, read }] of used) {
19601
+ const counter = await tx.findOne("label_sequences", { id });
19602
+ if (counter !== null) {
19603
+ if (counter.last_label !== read) return false;
19604
+ moves.push(() => tx.update("label_sequences", counter, { last_label: read + 1 }));
19605
+ continue;
19606
+ }
19607
+ const channel = await tx.findOne("channels", { id: channelId });
19608
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) return false;
19609
+ moves.push(() => tx.create("label_sequences", {
19610
+ id,
19611
+ last_label: read + 1,
19612
+ is_filled: true
19613
+ }));
19614
+ }
19615
+ for (const move of moves) move();
19616
+ return true;
19617
+ }) ? (repairs += 1) <= REPAIRS : (races += 1) <= RACES) continue;
19618
+ }
19619
+ throw error;
19620
+ }
19621
+ }
19622
+ };
19623
+ const catchUpLabels = async (tx, labels, latest) => {
19624
+ const given = /* @__PURE__ */ new Map();
19625
+ if (latest === null || typeof latest.label === "number") return given;
19626
+ const unlabeled = [];
19627
+ let cursor;
19628
+ scan: do {
19629
+ const page = await tx.findMany("releases", {
19630
+ index: "byScope",
19631
+ where: { scope_key: latest.scope_key },
19632
+ order: "desc",
19633
+ limit: FILL_BATCH,
19634
+ ...cursor === void 0 ? {} : { cursor }
19635
+ });
19636
+ for (const row of page.rows) {
19637
+ if (typeof row.label === "number") break scan;
19638
+ unlabeled.push(row);
19639
+ }
19640
+ cursor = page.next;
19641
+ } while (cursor !== void 0);
19642
+ labels.caughtUp(latest.channel_id, latest.platform);
19643
+ for (const row of unlabeled.reverse()) {
19644
+ const { id, channel_id, platform } = toReleaseRow(row);
19645
+ const label = await labels.next(channel_id, platform);
19646
+ tx.update("releases", row, { label });
19647
+ given.set(id, label);
19648
+ }
19649
+ return given;
19650
+ };
19651
+ const pendingLabelPairs = async (db) => {
19652
+ const pairs = /* @__PURE__ */ new Map();
19653
+ for (let last = "";;) {
19654
+ const { rows } = await db.findMany("releases", {
19655
+ index: "scopes",
19656
+ where: {},
19657
+ limit: 1,
19658
+ range: { gt: last }
19659
+ });
19660
+ if (rows[0] === void 0) break;
19661
+ last = rows[0].scope_key;
19662
+ const { rows: newest } = await db.findMany("releases", {
19663
+ index: "byScope",
19664
+ where: { scope_key: last },
19665
+ order: "desc",
19666
+ limit: 1
19667
+ });
19668
+ if (newest[0] === void 0) continue;
19669
+ const { channel_id: channelId, platform, label } = toReleaseRow(newest[0]);
19670
+ const id = labelSequenceId(channelId, platform);
19671
+ const pair = pairs.get(id) ?? {
19672
+ channelId,
19673
+ platform,
19674
+ pending: false
19675
+ };
19676
+ pair.pending ||= label === null;
19677
+ pairs.set(id, pair);
19678
+ }
19679
+ const pending = [];
19680
+ for (const [id, { channelId, platform, pending: unlabeled }] of pairs) {
19681
+ if (!unlabeled) {
19682
+ const counter = await db.findOne("label_sequences", { id });
19683
+ if (counter !== null && counter.is_filled) continue;
19684
+ }
19685
+ pending.push({
19686
+ channelId,
19687
+ platform
19688
+ });
19689
+ }
19690
+ return pending;
19691
+ };
19692
+ //#endregion
18692
19693
  //#region ../../packages/server/dist/core/writes.mjs
18693
- const PAGE$2 = 500;
19694
+ const PAGE$3 = 500;
18694
19695
  const countBundle = (tx, platform, delta) => {
18695
19696
  for (const key of [platform, "*"]) tx.aggregate("bundle_totals", { platform_key: key }, { bundles: delta });
18696
19697
  };
@@ -18709,7 +19710,7 @@ const deleteBundle = async (tx, current) => {
18709
19710
  await tx.delete("bundles", current);
18710
19711
  countBundle(tx, current.platform, -1);
18711
19712
  };
18712
- const replaceBundlePatches = async (tx, bundle, rows) => {
19713
+ const replaceBundlePatches = async (tx, bundle, rows, checkNew) => {
18713
19714
  const wanted = new Map(rows.map((row) => [row.id, row]));
18714
19715
  const count = bundle._refs_bundle_patches_bundle_id ?? 0;
18715
19716
  let cursor;
@@ -18717,7 +19718,7 @@ const replaceBundlePatches = async (tx, bundle, rows) => {
18717
19718
  const page = await tx.findMany("bundle_patches", {
18718
19719
  index: "byBundle",
18719
19720
  where: { bundle_id: bundle.id },
18720
- limit: Math.min(count - seen, PAGE$2),
19721
+ limit: Math.min(count - seen, PAGE$3),
18721
19722
  ...cursor === void 0 ? {} : { cursor }
18722
19723
  });
18723
19724
  for (const stored of page.rows) {
@@ -18734,6 +19735,7 @@ const replaceBundlePatches = async (tx, bundle, rows) => {
18734
19735
  if (page.next === void 0) break;
18735
19736
  cursor = page.next;
18736
19737
  }
19738
+ if (checkNew !== void 0) for (const row of wanted.values()) await checkNew(row);
18737
19739
  for (const row of wanted.values()) tx.create("bundle_patches", row);
18738
19740
  };
18739
19741
  const insertChannel = async (db, row) => {
@@ -18774,6 +19776,10 @@ const deleteChannel = (db, id) => db.transaction(async (tx) => {
18774
19776
  deleted: false,
18775
19777
  reason: "not_empty"
18776
19778
  };
19779
+ for (const platform of LABEL_PLATFORMS) {
19780
+ const counter = await tx.findOne("label_sequences", { id: labelSequenceId(id, platform) });
19781
+ if (counter !== null) await tx.delete("label_sequences", counter);
19782
+ }
18777
19783
  await tx.delete("channels", row);
18778
19784
  return { deleted: true };
18779
19785
  });
@@ -18786,6 +19792,16 @@ const ARTIFACT_KINDS = {
18786
19792
  const SCOPE_KEY_MAX_LENGTH = 2048;
18787
19793
  const GIT_COMMIT_HASH_MAX_LENGTH = 255;
18788
19794
  const BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
19795
+ const SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
19796
+ const URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
19797
+ const APP_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;
19798
+ const FINGERPRINT_HASH = /^[A-Za-z0-9._~-]{1,255}$/;
19799
+ const DISTRIBUTIONS = {
19800
+ apk: ["direct"],
19801
+ app: ["direct"],
19802
+ aab: ["store"],
19803
+ ipa: ["direct", "store"]
19804
+ };
18789
19805
  var NativeBuildInputError = class extends TypeError {
18790
19806
  name = "NativeBuildInputError";
18791
19807
  };
@@ -18806,15 +19822,42 @@ const pick = (row) => ({
18806
19822
  build_number: row.build_number ?? null,
18807
19823
  submitted_to: row.submitted_to ?? null,
18808
19824
  submitted_at_ms: row.submitted_at_ms ?? null,
18809
- submitted_version: row.submitted_version ?? null
19825
+ submitted_version: row.submitted_version ?? null,
19826
+ is_store_build: row.is_store_build === true,
19827
+ is_sandbox: row.is_sandbox === true,
19828
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
19829
+ export_method: row.export_method ?? null,
19830
+ native_app_version: row.native_app_version ?? null
18810
19831
  });
18811
- const SUBMISSION_DESTINATIONS = {
18812
- android: "play-internal",
18813
- ios: "testflight"
18814
- };
19832
+ const EXPORT_METHODS = /* @__PURE__ */ new Set([
19833
+ "app-store",
19834
+ "ad-hoc",
19835
+ "development",
19836
+ "enterprise"
19837
+ ]);
19838
+ const OLDER_BUILDS_PAGE = 20;
19839
+ const OLDER_BUILDS_PAGES = 5;
19840
+ const MARK_ATTEMPTS = 8;
18815
19841
  const BUILD_NUMBER_MAX_LENGTH = 64;
18816
19842
  const SUBMITTED_VERSION_MAX_LENGTH = 255;
19843
+ const checkedScopeKey = (scopeKey) => {
19844
+ 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.`);
19845
+ return scopeKey;
19846
+ };
19847
+ const registeredDistribution = (kind, exportMethod) => kind !== "ipa" ? DISTRIBUTIONS[kind][0] : exportMethod === void 0 || exportMethod === null ? "unknown" : exportMethod === "app-store" ? "store" : "direct";
19848
+ const sandboxScopeKey = (scope, sandbox) => {
19849
+ const { appId, urlScheme, artifactKind, distribution } = sandbox;
19850
+ 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;
19851
+ if (problem !== null) throw new NativeBuildInputError(`Invalid sandbox build scope: ${problem}.`);
19852
+ const target = scope.fingerprintHash === null ? `app-version:${encodeURIComponent(scope.appVersion)}` : `fingerprint:${scope.fingerprintHash}`;
19853
+ return checkedScopeKey(`v1:sandbox:${scope.platform}:${appId}:${urlScheme}:${artifactKind}:${distribution}:${target}`);
19854
+ };
18817
19855
  const nativeBuildScopeKey = (scope) => {
19856
+ const { sandbox } = scope;
19857
+ if (sandbox !== void 0 && sandbox !== null) {
19858
+ if (sandbox.distribution !== "direct" && sandbox.distribution !== "store") throw new NativeBuildInputError("Invalid sandbox build scope: its distribution must be direct or store.");
19859
+ return sandboxScopeKey(scope, sandbox);
19860
+ }
18818
19861
  let scopeKey;
18819
19862
  try {
18820
19863
  const channelKey = encodeChannelKey(scope.channel);
@@ -18831,30 +19874,102 @@ const nativeBuildScopeKey = (scope) => {
18831
19874
  } catch (error) {
18832
19875
  throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
18833
19876
  }
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;
19877
+ return checkedScopeKey(scopeKey);
19878
+ };
19879
+ const channelIdOf = (channel) => {
19880
+ try {
19881
+ return `channel:${encodeChannelKey(channel)}`;
19882
+ } catch (error) {
19883
+ throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
19884
+ }
19885
+ };
19886
+ const registrationScopeKey = (registration) => {
19887
+ channelIdOf(registration.channel);
19888
+ return registration.isSandbox === true ? sandboxScopeKey(registration, {
19889
+ appId: registration.sandboxAppId,
19890
+ urlScheme: registration.sandboxUrlScheme,
19891
+ artifactKind: registration.artifact.kind,
19892
+ distribution: registeredDistribution(registration.artifact.kind, registration.exportMethod)
19893
+ }) : nativeBuildScopeKey({
19894
+ ...registration,
19895
+ sandbox: null
19896
+ });
19897
+ };
19898
+ const refuseSandboxPatchBase = async (db, baseBundleId) => {
19899
+ 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
19900
  };
18837
19901
  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 }) => {
19902
+ const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, sandboxAppId, exportMethod, nativeAppVersion, artifact }) => {
18839
19903
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
18840
19904
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
18841
19905
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
18842
19906
  if (channel.trim().length === 0) return "channel is required";
19907
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
19908
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
19909
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
19910
+ 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`;
19911
+ }
19912
+ if (sandboxAppId !== void 0 && sandboxAppId !== null) {
19913
+ if (isSandbox !== true) return "sandboxAppId is a sandbox build's, and this isn't one";
19914
+ if (typeof sandboxAppId !== "string" || !APP_ID.test(sandboxAppId)) return "sandboxAppId must be the artifact's bundle identifier or application ID, up to 255 characters";
19915
+ }
19916
+ if (isSandbox === true) {
19917
+ if (sandboxUrlScheme === void 0 || sandboxUrlScheme === null) return "a sandbox build needs the sandboxUrlScheme its artifact registers";
19918
+ 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";
19919
+ }
18843
19920
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
18844
19921
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
18845
19922
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
18846
19923
  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`;
19924
+ 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
19925
  const kinds = ARTIFACT_KINDS[platform];
18848
19926
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
19927
+ if (exportMethod !== void 0 && exportMethod !== null) {
19928
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
19929
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
19930
+ }
18849
19931
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
18850
19932
  return null;
18851
19933
  };
19934
+ const SIBLING_KINDS = {
19935
+ app: "ipa",
19936
+ ipa: "app"
19937
+ };
19938
+ 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");
19939
+ const siblingSandboxScopeKey = (build, artifactKind) => {
19940
+ const [version, sandbox, platform, appId, urlScheme] = build.scope_key.split(":");
19941
+ if (version !== "v1" || sandbox !== "sandbox" || platform !== build.platform || appId === void 0 || urlScheme === void 0) return null;
19942
+ const target = build.fingerprint_hash === null ? {
19943
+ platform: build.platform,
19944
+ fingerprintHash: null,
19945
+ appVersion: build.app_version ?? ""
19946
+ } : {
19947
+ platform: build.platform,
19948
+ fingerprintHash: build.fingerprint_hash,
19949
+ appVersion: null
19950
+ };
19951
+ try {
19952
+ return sandboxScopeKey(target, {
19953
+ appId,
19954
+ urlScheme,
19955
+ artifactKind: build.artifact_kind,
19956
+ distribution: registeredDistribution(build.artifact_kind, build.export_method)
19957
+ }) === build.scope_key ? sandboxScopeKey(target, {
19958
+ appId,
19959
+ urlScheme,
19960
+ artifactKind,
19961
+ distribution: "direct"
19962
+ }) : null;
19963
+ } catch {
19964
+ return null;
19965
+ }
19966
+ };
18852
19967
  const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18853
19968
  async registerNativeBuild(registration) {
18854
19969
  const problem = problemOf(registration);
18855
19970
  if (problem !== null) throw new NativeBuildInputError(`Invalid native build: ${problem}.`);
18856
- const scopeKey = nativeBuildScopeKey(registration);
18857
- const channelId = `channel:${encodeChannelKey(registration.channel)}`;
19971
+ const scopeKey = registrationScopeKey(registration);
19972
+ const channelId = channelIdOf(registration.channel);
18858
19973
  const { embeddedBundle } = registration;
18859
19974
  const row = {
18860
19975
  id: registration.id,
@@ -18873,7 +19988,12 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18873
19988
  build_number: registration.buildNumber ?? null,
18874
19989
  submitted_to: null,
18875
19990
  submitted_at_ms: null,
18876
- submitted_version: null
19991
+ submitted_version: null,
19992
+ is_store_build: false,
19993
+ is_sandbox: registration.isSandbox === true,
19994
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
19995
+ export_method: registration.exportMethod ?? null,
19996
+ native_app_version: registration.nativeAppVersion ?? null
18877
19997
  };
18878
19998
  for (let attempt = 1;; attempt += 1) {
18879
19999
  await insertChannel(db, {
@@ -18907,25 +20027,82 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18907
20027
  const row = await db.findOne("native_builds", { id });
18908
20028
  return row === null ? null : pick(row);
18909
20029
  },
20030
+ async findNativeBuildByBuiltInBundle(bundleId) {
20031
+ const row = await db.findOne("native_builds", { min_bundle_id: bundleId });
20032
+ return row === null ? null : pick(row);
20033
+ },
18910
20034
  async findNativeBuild(scope, options) {
18911
20035
  const scopeKey = nativeBuildScopeKey(scope);
18912
20036
  const buildKey = options?.buildKey;
18913
20037
  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", {
20038
+ const artifactKind = options?.artifactKind;
20039
+ 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 ")}.`);
20040
+ const ofKind = (row) => artifactKind === void 0 || row.artifact_kind === artifactKind;
20041
+ if (options?.storeBuild) {
20042
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
20043
+ return marked === null || !ofKind(marked) ? null : pick(marked);
20044
+ }
20045
+ const read = (limit, before) => {
20046
+ const page = {
20047
+ order: "desc",
20048
+ limit,
20049
+ ...before === void 0 ? {} : { range: { lt: before } }
20050
+ };
20051
+ return buildKey !== void 0 ? db.findMany("native_builds", {
20052
+ index: "byBuildKey",
20053
+ where: {
20054
+ scope_key: scopeKey,
20055
+ build_key: buildKey
20056
+ },
20057
+ ...page
20058
+ }) : artifactKind !== void 0 ? db.findMany("native_builds", {
20059
+ index: "byScopeKind",
20060
+ where: {
20061
+ scope_key: scopeKey,
20062
+ artifact_kind: artifactKind
20063
+ },
20064
+ ...page
20065
+ }) : db.findMany("native_builds", {
20066
+ index: "byScope",
20067
+ where: { scope_key: scopeKey },
20068
+ ...page
20069
+ });
20070
+ };
20071
+ const bundleId = options?.builtInOlderThan;
20072
+ if (bundleId !== void 0 && scope.sandbox !== void 0 && scope.sandbox !== null) return null;
20073
+ const { rows } = await read(1);
20074
+ const newest = (rows[0] === void 0 ? void 0 : pick(rows[0])) ?? (artifactKind !== void 0 && buildKey === void 0 ? await db.findMany("native_builds", {
18915
20075
  index: "byScope",
18916
20076
  where: { scope_key: scopeKey },
18917
20077
  order: "desc",
18918
20078
  limit: 1
18919
- }) : await db.findMany("native_builds", {
18920
- index: "byBuildKey",
18921
- where: {
18922
- scope_key: scopeKey,
18923
- build_key: buildKey
18924
- },
20079
+ }).then(({ rows: [row] }) => row?.artifact_kind === artifactKind ? pick(row) : void 0) : void 0);
20080
+ if (newest === void 0 || !ofKind(newest)) return null;
20081
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return newest;
20082
+ let before = newest.id;
20083
+ for (let page = 0; page < OLDER_BUILDS_PAGES; page += 1) {
20084
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
20085
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
20086
+ if (usable !== void 0) return ofKind(usable) ? pick(usable) : null;
20087
+ const last = older.at(-1);
20088
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
20089
+ before = last.id;
20090
+ }
20091
+ return null;
20092
+ },
20093
+ async findNativeBuildSibling(build) {
20094
+ const artifactKind = SIBLING_KINDS[build.artifact_kind];
20095
+ if (build.platform !== "ios" || !build.is_sandbox || artifactKind === void 0 || !isInstallTarget(build)) return null;
20096
+ const scopeKey = siblingSandboxScopeKey(build, artifactKind);
20097
+ if (scopeKey === null) return null;
20098
+ const { rows } = await db.findMany("native_builds", {
20099
+ index: "byScope",
20100
+ where: { scope_key: scopeKey },
18925
20101
  order: "desc",
18926
20102
  limit: 1
18927
20103
  });
18928
- return rows[0] === void 0 ? null : pick(rows[0]);
20104
+ const sibling = rows[0] === void 0 ? null : pick(rows[0]);
20105
+ return sibling !== null && isInstallTarget(sibling) ? sibling : null;
18929
20106
  },
18930
20107
  async recordNativeBuildSubmission(id, { destination, version }) {
18931
20108
  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 +20110,8 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18933
20110
  const row = await tx.findOne("native_builds", { id });
18934
20111
  if (row === null) return null;
18935
20112
  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}.`);
20113
+ 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}.`);
20114
+ 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
20115
  const set = {
18938
20116
  submitted_to: destination,
18939
20117
  submitted_at_ms: now(),
@@ -18946,6 +20124,46 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18946
20124
  };
18947
20125
  });
18948
20126
  },
20127
+ async markNativeBuild(id, { storeBuild }) {
20128
+ for (let attempt = 1;; attempt += 1) try {
20129
+ return await db.transaction(async (tx) => {
20130
+ const row = await tx.findOne("native_builds", { id });
20131
+ if (row === null) return null;
20132
+ const build = pick(row);
20133
+ if (!storeBuild) {
20134
+ if (build.is_store_build) tx.update("native_builds", row, { is_store_build: false });
20135
+ return {
20136
+ nativeBuild: {
20137
+ ...build,
20138
+ is_store_build: false
20139
+ },
20140
+ previous: null
20141
+ };
20142
+ }
20143
+ if (build.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
20144
+ if (build.is_store_build) return {
20145
+ nativeBuild: build,
20146
+ previous: null
20147
+ };
20148
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build.scope_key });
20149
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
20150
+ tx.update("native_builds", row, { is_store_build: true });
20151
+ return {
20152
+ nativeBuild: {
20153
+ ...build,
20154
+ is_store_build: true
20155
+ },
20156
+ previous: holder === null ? null : {
20157
+ ...pick(holder),
20158
+ is_store_build: false
20159
+ }
20160
+ };
20161
+ });
20162
+ } catch (error) {
20163
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
20164
+ throw error;
20165
+ }
20166
+ },
18949
20167
  async deleteNativeBuild(id) {
18950
20168
  return db.transaction(async (tx) => {
18951
20169
  const row = await tx.findOne("native_builds", { id });
@@ -18983,7 +20201,7 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18983
20201
  });
18984
20202
  //#endregion
18985
20203
  //#region ../../packages/server/dist/core/releases.mjs
18986
- const PAGE$1 = 500;
20204
+ const PAGE$2 = 500;
18987
20205
  const fail$1 = (code, message) => {
18988
20206
  throw new ReleaseCatalogMutationError(code, message);
18989
20207
  };
@@ -19001,41 +20219,39 @@ const checkScope = (scope) => {
19001
20219
  });
19002
20220
  if (scope.strategy === "FINGERPRINT" !== (scope.fingerprintHash !== null) || scope.scopeKey !== expected) fail$1("INVALID_SCOPE", "Release catalog scope metadata is inconsistent");
19003
20221
  };
19004
- const enabledReleases = async (tx, scopeKey) => {
20222
+ const drainReleases = async (page) => {
19005
20223
  const rows = [];
19006
20224
  let cursor;
19007
20225
  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;
20226
+ const found = await page(cursor);
20227
+ rows.push(...found.rows.map((row) => toReleaseRow(row)));
20228
+ cursor = found.next;
19019
20229
  } while (cursor !== void 0);
19020
20230
  return rows;
19021
20231
  };
19022
- const latestReleaseId = async (tx, scopeKey) => {
20232
+ const enabledIn = (scopeKey, cursor) => ({
20233
+ index: "byScopeEnabled",
20234
+ where: {
20235
+ scope_key: scopeKey,
20236
+ enabled: true
20237
+ },
20238
+ limit: PAGE$2,
20239
+ ...cursor === void 0 ? {} : { cursor }
20240
+ });
20241
+ const enabledReleases = (tx, scopeKey) => drainReleases((cursor) => tx.findMany("releases", enabledIn(scopeKey, cursor)));
20242
+ const latestRelease = async (tx, scopeKey) => {
19023
20243
  const { rows } = await tx.findMany("releases", {
19024
20244
  index: "byScope",
19025
20245
  where: { scope_key: scopeKey },
19026
20246
  order: "desc",
19027
20247
  limit: 1
19028
20248
  });
19029
- return rows[0]?.id ?? null;
20249
+ return rows[0] === void 0 ? null : toReleaseRow(rows[0]);
19030
20250
  };
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;
20251
+ const nextCatalog = (scope, stored, compilation, updatedAtMs) => {
20252
+ const generation = (stored.catalog?.generation ?? 0) + 1;
19037
20253
  if (!Number.isSafeInteger(generation)) fail$1("CATALOG_GENERATION_EXHAUSTED", `Catalog "${scope.scopeKey}" exhausted its generation counter`);
19038
- const catalog = {
20254
+ return {
19039
20255
  scope_key: scope.scopeKey,
19040
20256
  catalog_id: stored.catalog?.catalog_id ?? createUUIDv7(),
19041
20257
  strategy: scope.strategy,
@@ -19050,6 +20266,21 @@ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
19050
20266
  is_tombstone: compilation.payload.releaseDescriptors.length === 0,
19051
20267
  updated_at_ms: updatedAtMs
19052
20268
  };
20269
+ };
20270
+ const compileScope = async (scope, enabled) => {
20271
+ try {
20272
+ return await compileReleaseCatalog({
20273
+ strategy: scope.strategy,
20274
+ releases: enabled.map(releaseRowToRelease)
20275
+ });
20276
+ } catch (error) {
20277
+ if (!(error instanceof ReleaseCatalogCompilationError) || error.code !== "CATALOG_OVERSIZE") throw error;
20278
+ 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.`);
20279
+ }
20280
+ };
20281
+ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
20282
+ const compilation = await compileScope(scope, enabled);
20283
+ const catalog = nextCatalog(scope, stored, compilation, updatedAtMs);
19053
20284
  const { scope_key: _scopeKey, ...set } = catalog;
19054
20285
  if (stored.row === null) tx.create("release_catalogs", catalog);
19055
20286
  else tx.update("release_catalogs", stored.row, set);
@@ -19066,13 +20297,17 @@ const readCatalog = async (tx, scopeKey) => {
19066
20297
  catalog: row === null ? null : toCatalogRow(row)
19067
20298
  };
19068
20299
  };
20300
+ const refuseLaterCatalog = (scope, catalog) => {
20301
+ if (catalog !== null && readCompiledCatalogPayload(catalog.payload).fromLaterRelease) fail$1("CATALOG_FROM_LATER_RELEASE", `The ${scope.platform} release catalog of channel "${scope.channelName}" was written by a later Hot Updater.\nUpgrade hot-updater, then try again.`);
20302
+ };
19069
20303
  const assertHistory = (stored, hasReleases) => {
19070
20304
  if (stored.catalog === null && hasReleases) fail$1("CATALOG_IDENTITY_MISSING", "Catalog history is missing. Restore its catalog row from backup before rebuilding or deploying.");
19071
20305
  };
19072
- const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
20306
+ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }, labels) => {
19073
20307
  checkScope(scope);
19074
20308
  const stored = await readCatalog(tx, scope.scopeKey);
19075
- const enabled = await enabledReleases(tx, scope.scopeKey);
20309
+ refuseLaterCatalog(scope, stored.catalog);
20310
+ let enabled = await enabledReleases(tx, scope.scopeKey);
19076
20311
  if (bundle !== void 0) {
19077
20312
  insertBundle(tx, bundle.row);
19078
20313
  for (const patch of bundle.patches) tx.create("bundle_patches", patch);
@@ -19080,14 +20315,22 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
19080
20315
  let before = null;
19081
20316
  let release;
19082
20317
  if (change.operation === "insert") {
19083
- const latest = await latestReleaseId(tx, scope.scopeKey);
20318
+ if (labels === void 0) throw new Error("A release insert takes its label from an allocator.");
20319
+ const newest = await latestRelease(tx, scope.scopeKey);
20320
+ const latest = newest?.id ?? null;
19084
20321
  assertHistory(stored, latest !== null);
19085
20322
  const floor = [latest, bundle && isUUIDv7(bundle.row.id) ? bundle.row.id : null].filter((id) => id !== null).sort().at(-1);
19086
20323
  const id = change.row.id ?? createUUIDv7After(floor ?? null);
19087
20324
  if (latest !== null && id <= latest) fail$1("NON_MONOTONIC_RELEASE_ID", `Release "${id}" must sort after "${latest}"`);
20325
+ const given = await catchUpLabels(tx, labels, newest);
20326
+ if (given.size > 0) enabled = enabled.map((row) => given.has(row.id) ? {
20327
+ ...row,
20328
+ label: given.get(row.id)
20329
+ } : row);
19088
20330
  release = {
19089
20331
  ...change.row,
19090
- id
20332
+ id,
20333
+ label: await labels.next(scope.channelId, scope.platform)
19091
20334
  };
19092
20335
  if (release.scope_key !== scope.scopeKey || release.channel_id !== scope.channelId || release.platform !== scope.platform || release.strategy !== scope.strategy || release.fingerprint_hash !== scope.fingerprintHash || release.revision !== 1) fail$1("INVALID_SCOPE", "Inserted Release does not match its catalog scope");
19093
20336
  tx.create("releases", release);
@@ -19100,8 +20343,9 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
19100
20343
  await tx.delete("releases", row);
19101
20344
  release = null;
19102
20345
  } else {
20346
+ const { label: _label, ...update } = change.update;
19103
20347
  const set = {
19104
- ...change.update,
20348
+ ...update,
19105
20349
  revision: before.revision + 1
19106
20350
  };
19107
20351
  tx.update("releases", row, set);
@@ -19122,28 +20366,66 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
19122
20366
  };
19123
20367
  const changeReleases = (db, inputs) => {
19124
20368
  if (new Set(inputs.map(({ scope }) => scope.scopeKey)).size !== inputs.length) fail$1("INVALID_SCOPE", "A batch cannot change one catalog scope twice");
19125
- return db.transaction(async (tx) => {
20369
+ return writeWithLabels(db, async (tx, labels) => {
19126
20370
  const results = [];
19127
- for (const input of inputs) results.push(await changeRelease(tx, input));
20371
+ for (const input of inputs) results.push(await changeRelease(tx, input, labels));
19128
20372
  return results;
19129
20373
  });
19130
20374
  };
20375
+ const isCurrent = (scope, current, compilation) => {
20376
+ if (current.strategy !== scope.strategy || current.channel_id !== scope.channelId || current.channel_key !== encodeChannelKey(scope.channelName) || current.platform !== scope.platform || current.fingerprint_hash !== scope.fingerprintHash) return false;
20377
+ if (current.catalog_hash === compilation.catalogHash) return true;
20378
+ const read = readCompiledCatalogPayload(current.payload);
20379
+ return read.fromLaterRelease && read.canonicalPayload === compilation.canonicalPayload;
20380
+ };
20381
+ const withoutLabels = (payload) => {
20382
+ const parsed = JSON.parse(payload);
20383
+ return JSON.stringify({
20384
+ ...parsed,
20385
+ releaseDescriptors: (parsed.releaseDescriptors ?? []).map(({ label: _label, ...descriptor }) => descriptor)
20386
+ });
20387
+ };
20388
+ const differsInLabelsOnly = (current, projected) => current.payload !== projected.payload && current.strategy === projected.strategy && current.channel_id === projected.channel_id && current.channel_key === projected.channel_key && current.platform === projected.platform && current.fingerprint_hash === projected.fingerprint_hash && withoutLabels(current.payload) === withoutLabels(projected.payload);
20389
+ const catalogRowScope = (row) => ({
20390
+ channelId: row.channel_id,
20391
+ channelName: decodeChannelKey(row.channel_key),
20392
+ fingerprintHash: row.fingerprint_hash,
20393
+ platform: row.platform,
20394
+ scopeKey: row.scope_key,
20395
+ strategy: row.strategy
20396
+ });
20397
+ const preflightRebuild = async (db, scopeKey, updatedAtMs) => {
20398
+ const row = await db.findOne("release_catalogs", { scope_key: scopeKey });
20399
+ if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
20400
+ const current = toCatalogRow(row);
20401
+ const scope = catalogRowScope(current);
20402
+ checkScope(scope);
20403
+ const enabled = await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor)));
20404
+ const compilation = await compileScope(scope, enabled);
20405
+ const changed = !isCurrent(scope, current, compilation);
20406
+ const projectedCatalog = changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current;
20407
+ return {
20408
+ changed,
20409
+ labelsOnly: changed && differsInLabelsOnly(current, projectedCatalog),
20410
+ currentCatalog: current,
20411
+ diagnostics: compilation.diagnostics,
20412
+ projectedCatalog
20413
+ };
20414
+ };
19131
20415
  const rebuildScope = async (tx, scope, updatedAtMs) => {
19132
20416
  checkScope(scope);
19133
20417
  const stored = await readCatalog(tx, scope.scopeKey);
19134
- assertHistory(stored, await latestReleaseId(tx, scope.scopeKey) !== null);
20418
+ assertHistory(stored, await latestRelease(tx, scope.scopeKey) !== null);
19135
20419
  const enabled = await enabledReleases(tx, scope.scopeKey);
19136
- const compilation = await compileReleaseCatalog({
19137
- strategy: scope.strategy,
19138
- releases: enabled.map(releaseRowToRelease)
19139
- });
20420
+ const compilation = await compileScope(scope, enabled);
19140
20421
  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 {
20422
+ if (current !== null && isCurrent(scope, current, compilation)) return {
19142
20423
  catalog: current,
19143
20424
  current,
19144
20425
  changed: false,
19145
20426
  diagnostics: compilation.diagnostics
19146
20427
  };
20428
+ refuseLaterCatalog(scope, current);
19147
20429
  const written = await writeCatalog(tx, scope, stored, enabled, updatedAtMs);
19148
20430
  return {
19149
20431
  catalog: written.catalog,
@@ -19154,6 +20436,7 @@ const rebuildScope = async (tx, scope, updatedAtMs) => {
19154
20436
  };
19155
20437
  //#endregion
19156
20438
  //#region ../../packages/server/dist/core/operations.mjs
20439
+ const CATALOG_PAGE = 100;
19157
20440
  var Preflight = class extends Error {
19158
20441
  result;
19159
20442
  constructor(result) {
@@ -19238,14 +20521,7 @@ const mutationResult = ({ catalog, release }) => ({
19238
20521
  const catalogScope = async (tx, scopeKey) => {
19239
20522
  const row = await tx.findOne("release_catalogs", { scope_key: scopeKey });
19240
20523
  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
- };
20524
+ return catalogRowScope(toCatalogRow(row));
19249
20525
  };
19250
20526
  const createCoreOperations = (db, { now = Date.now } = {}) => {
19251
20527
  const ensureChannel = async (name) => (await insertChannel(db, {
@@ -19265,7 +20541,11 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
19265
20541
  for (const { release } of deployments) if (!channels.has(release.channel)) channels.set(release.channel, await ensureChannel(release.channel));
19266
20542
  const platforms = /* @__PURE__ */ new Map();
19267
20543
  for (const deployment of deployments) {
19268
- if (!("bundleId" in deployment) || platforms.has(deployment.bundleId)) continue;
20544
+ if (!("bundleId" in deployment)) {
20545
+ for (const { baseBundleId } of deployment.bundle.patches ?? []) await refuseSandboxPatchBase(db, baseBundleId);
20546
+ continue;
20547
+ }
20548
+ if (platforms.has(deployment.bundleId)) continue;
19269
20549
  const row = await db.findOne("bundles", { id: deployment.bundleId });
19270
20550
  if (row === null) throw new DatabaseBundleNotFoundError(deployment.bundleId);
19271
20551
  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.`);
@@ -19375,7 +20655,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
19375
20655
  if (targetChannel.length === 0) throw new ReleaseManagementError("TARGET_RELEASE_INVALID", "Promotion requires a target channel.");
19376
20656
  const channel = await ensureChannel(targetChannel);
19377
20657
  const updatedAtMs = now();
19378
- return db.transaction(async (tx) => {
20658
+ return writeWithLabels(db, async (tx, labels) => {
19379
20659
  const { release: source, scope: sourceScope } = await loadTarget(tx, input);
19380
20660
  checkSource(source);
19381
20661
  const targetScope = scopeOf$1(channel, source.platform, source.fingerprint_hash);
@@ -19403,12 +20683,13 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
19403
20683
  },
19404
20684
  updatedAtMs
19405
20685
  }) : null;
20686
+ const { label: _label, ...copied } = source;
19406
20687
  const target = await changeRelease(tx, {
19407
20688
  scope: targetScope,
19408
20689
  change: {
19409
20690
  operation: "insert",
19410
20691
  row: {
19411
- ...source,
20692
+ ...copied,
19412
20693
  id: createUUIDv7After(floor ?? null, updatedAtMs),
19413
20694
  revision: 1,
19414
20695
  scope_key: targetScope.scopeKey,
@@ -19423,7 +20704,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
19423
20704
  }
19424
20705
  },
19425
20706
  updatedAtMs
19426
- });
20707
+ }, labels);
19427
20708
  return {
19428
20709
  source: moved === null ? null : mutationResult(moved),
19429
20710
  target: mutationResult(target)
@@ -19440,17 +20721,38 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
19440
20721
  };
19441
20722
  });
19442
20723
  },
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
- });
20724
+ preflightReleaseCatalogRebuild: (scopeKey) => preflightRebuild(db, scopeKey, now()),
20725
+ fillReleaseLabels: async ({ dryRun = false, catalogs = true } = {}) => {
20726
+ let releases = 0;
20727
+ const pairs = await pendingLabelPairs(db);
20728
+ if (dryRun && pairs[0] !== void 0) await probeLabelSchema(db, pairs[0]);
20729
+ for (const pair of pairs) releases += await fillLabels(db, pair, { dryRun });
20730
+ let rebuilt = 0;
20731
+ if (catalogs) {
20732
+ let cursor;
20733
+ do {
20734
+ const page = await db.findMany("release_catalogs", {
20735
+ index: "all",
20736
+ where: {},
20737
+ limit: CATALOG_PAGE,
20738
+ ...cursor === void 0 ? {} : { cursor }
20739
+ });
20740
+ for (const row of page.rows) {
20741
+ if (row.is_tombstone) continue;
20742
+ const preflight = await preflightRebuild(db, row.scope_key, now()).catch(() => null);
20743
+ if (preflight === null || !preflight.labelsOnly) continue;
20744
+ rebuilt += 1;
20745
+ if (dryRun) continue;
20746
+ const updatedAtMs = now();
20747
+ await db.transaction((tx) => rebuildScope(tx, catalogRowScope(toCatalogRow(row)), updatedAtMs));
20748
+ }
20749
+ cursor = page.next;
20750
+ } while (cursor !== void 0);
20751
+ }
20752
+ return {
20753
+ releases,
20754
+ catalogs: rebuilt
20755
+ };
19454
20756
  },
19455
20757
  ensureChannel,
19456
20758
  deleteChannel: (id) => deleteChannel(db, id),
@@ -19469,7 +20771,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
19469
20771
  if (patches !== void 0) await replaceBundlePatches(tx, current, bundleToPatchRows({
19470
20772
  ...next,
19471
20773
  patches
19472
- }));
20774
+ }), (row) => refuseSandboxPatchBase(tx, row.base_bundle_id));
19473
20775
  }),
19474
20776
  deleteBundles: async (ids) => {
19475
20777
  try {
@@ -19525,6 +20827,7 @@ const createCoreApi = (db, storage, options = {}) => {
19525
20827
  ...reads,
19526
20828
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
19527
20829
  ...createNativeBuildApi(db, options),
20830
+ ...createIosDeviceApi(db, options),
19528
20831
  ready: async () => {
19529
20832
  await reads.listReleaseCatalogs({ limit: 1 });
19530
20833
  }
@@ -19708,6 +21011,10 @@ const answer = async (operation) => {
19708
21011
  error: error.message
19709
21012
  }, status);
19710
21013
  }
21014
+ if (error instanceof ReleaseCatalogCompilationError && error.code === "CATALOG_OVERSIZE") return json$2({
21015
+ code: error.code,
21016
+ error: error.message
21017
+ }, 400);
19711
21018
  if (error instanceof DatabaseBundleNotFoundError) return json$2({
19712
21019
  code: "BUNDLE_NOT_FOUND",
19713
21020
  error: error.message
@@ -19727,17 +21034,20 @@ const LIMITS = {
19727
21034
  defaultValue: 50,
19728
21035
  maxValue: 500
19729
21036
  };
19730
- const keyset = (url, maxValue = LIMITS.maxValue) => {
19731
- const order = url.searchParams.get("order") ?? "desc";
21037
+ const MAX_IDS = 100;
21038
+ const keyset = (url, maxValue = LIMITS.maxValue, defaultOrder = "desc") => {
21039
+ const order = url.searchParams.get("order") ?? defaultOrder;
19732
21040
  if (order !== "asc" && order !== "desc") throw new HandlerBadRequestError("order must be 'asc' or 'desc'.");
19733
21041
  const limitParam = url.searchParams.get("limit");
19734
21042
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
19735
21043
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
19736
21044
  const cursor = url.searchParams.get("cursor");
21045
+ const through = url.searchParams.get("through");
19737
21046
  return {
19738
21047
  order,
19739
21048
  limit,
19740
- ...cursor === null ? {} : { after: cursor }
21049
+ ...cursor === null ? {} : { after: cursor },
21050
+ ...through === null ? {} : { through }
19741
21051
  };
19742
21052
  };
19743
21053
  const page = (rows, { limit }, keyOf, extra = {}) => json$2({
@@ -19828,7 +21138,8 @@ const nativeBuildScopeOf = (url) => {
19828
21138
  const fingerprintHash = params.get("fingerprintHash");
19829
21139
  const appVersion = params.get("appVersion");
19830
21140
  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 ? {
21141
+ const sandbox = sandboxScopeOf(params);
21142
+ const scope = fingerprintHash !== null ? {
19832
21143
  platform,
19833
21144
  channel,
19834
21145
  fingerprintHash,
@@ -19839,16 +21150,43 @@ const nativeBuildScopeOf = (url) => {
19839
21150
  fingerprintHash: null,
19840
21151
  appVersion
19841
21152
  };
21153
+ return sandbox === null ? scope : {
21154
+ ...scope,
21155
+ sandbox
21156
+ };
21157
+ };
21158
+ const SANDBOX_SCOPE_PARAMS = [
21159
+ "sandboxAppId",
21160
+ "sandboxUrlScheme",
21161
+ "artifactKind",
21162
+ "distribution"
21163
+ ];
21164
+ const sandboxScopeOf = (params) => {
21165
+ const [appId, urlScheme, artifactKind, distribution] = SANDBOX_SCOPE_PARAMS.map((name) => params.get(name));
21166
+ const named = [
21167
+ appId,
21168
+ urlScheme,
21169
+ artifactKind,
21170
+ distribution
21171
+ ].filter((value) => value !== null).length;
21172
+ if (named === 0) return null;
21173
+ if (named !== SANDBOX_SCOPE_PARAMS.length) throw new HandlerBadRequestError(`A sandbox build lookup needs ${SANDBOX_SCOPE_PARAMS.join(", ")}.`);
21174
+ return {
21175
+ appId,
21176
+ urlScheme,
21177
+ artifactKind,
21178
+ distribution
21179
+ };
19842
21180
  };
19843
21181
  const refusingInvalid = async (operation) => {
19844
21182
  try {
19845
21183
  return await operation();
19846
21184
  } catch (error) {
19847
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
21185
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
19848
21186
  throw error;
19849
21187
  }
19850
21188
  };
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));
21189
+ 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
21190
  const scopeKeyOf = (params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "";
19853
21191
  const createAdminRouteHandlers = () => ({
19854
21192
  listBundles: onCore(async (core, request) => {
@@ -19880,11 +21218,34 @@ const createAdminRouteHandlers = () => ({
19880
21218
  const rows = await core.listReleaseCatalogs(input);
19881
21219
  return page(rows, input, (row) => row.scope_key);
19882
21220
  }),
21221
+ listReleaseScopeKeys: onCore(async (core, request) => {
21222
+ const input = keyset(new URL(request.url), 100, "asc");
21223
+ if (input.order !== "asc" || input.through !== void 0) throw new HandlerBadRequestError("Release scopes are listed ascending, by limit and cursor only.");
21224
+ const rows = await core.listReleaseScopeKeys({
21225
+ limit: input.limit,
21226
+ ...input.after === void 0 ? {} : { after: input.after }
21227
+ });
21228
+ return page(rows, input, (scopeKey) => scopeKey);
21229
+ }),
19883
21230
  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 });
21231
+ const url = new URL(request.url);
21232
+ const name = url.searchParams.get("name");
21233
+ if (name !== null) {
21234
+ const channel = await core.findChannelByName(name);
21235
+ return channel === null ? notFound() : json$2({ data: channel });
21236
+ }
21237
+ const ids = url.searchParams.get("ids");
21238
+ if (ids !== null) {
21239
+ const list = ids.split(",").filter((id) => id.length > 0);
21240
+ if (list.length === 0 || list.length > MAX_IDS) throw new HandlerBadRequestError(`Channels by ID take ids=<channel id>,... with 1 to ${MAX_IDS} ids.`);
21241
+ return json$2({ data: await core.getChannels(list) });
21242
+ }
21243
+ if (url.searchParams.has("limit") || url.searchParams.has("cursor")) {
21244
+ const input = keyset(url, LIMITS.maxValue, "asc");
21245
+ const rows = await core.listChannels(input);
21246
+ return page(rows, input, (row) => row.name);
21247
+ }
21248
+ return json$2({ data: await core.listChannels() });
19888
21249
  }),
19889
21250
  createChannel: onCore(async (core, request) => {
19890
21251
  const { name } = await body(request);
@@ -19923,15 +21284,36 @@ const createAdminRouteHandlers = () => ({
19923
21284
  return row === null ? notFound() : json$2({ data: row });
19924
21285
  }),
19925
21286
  rebuildReleaseCatalog: onCore(async (core, _request, params) => json$2({ data: await core.rebuildReleaseCatalog(scopeKeyOf(params)) })),
21287
+ getReleaseByLabel: onCore(async (core, request) => {
21288
+ const url = new URL(request.url);
21289
+ const channel = url.searchParams.get("channel");
21290
+ const platform = platformOf(url);
21291
+ const label = Number(url.searchParams.get("label"));
21292
+ if (channel === null || channel.length === 0 || platform === void 0 || !Number.isSafeInteger(label) || label < 1) throw new HandlerBadRequestError("A release label lookup takes channel, platform, and a label of 1 or more.");
21293
+ return json$2({ data: await core.getReleaseByLabel({
21294
+ channel,
21295
+ platform,
21296
+ label
21297
+ }) });
21298
+ }),
21299
+ fillReleaseLabels: onCore(async (core, request) => {
21300
+ const body = await request.json().catch(() => ({}));
21301
+ const input = body !== null && typeof body === "object" ? body : {};
21302
+ return json$2({ data: await core.fillReleaseLabels({
21303
+ dryRun: input.dryRun === true,
21304
+ catalogs: input.catalogs !== false
21305
+ }) });
21306
+ }),
19926
21307
  updateBundle: onCore(async (core, request, params) => {
19927
21308
  const bundleId = requireRouteParam(params, "id");
19928
- await core.updateBundle(bundleId, bundleUpdateOf(await request.json(), bundleId));
21309
+ const update = bundleUpdateOf(await request.json(), bundleId);
21310
+ await refusingInvalid(() => core.updateBundle(bundleId, update));
19929
21311
  return noContent();
19930
21312
  }),
19931
21313
  countBundles: onCore(async (core, request) => json$2({ data: await core.countBundles(platformOf(new URL(request.url))) })),
19932
21314
  countBundleChildren: onCore(async (core, request) => {
19933
21315
  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.");
21316
+ 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
21317
  return json$2({ data: await core.countBundleChildren(ids) });
19936
21318
  }),
19937
21319
  listBundleChildren: onCore(async (core, request, params) => {
@@ -19949,7 +21331,7 @@ const createAdminRouteHandlers = () => ({
19949
21331
  deployReleases: onCore(async (core, request) => {
19950
21332
  const { deployments } = await body(request);
19951
21333
  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);
21334
+ return json$2({ data: await refusingInvalid(() => core.deploy(deployments)) }, 201);
19953
21335
  }),
19954
21336
  promoteRelease: onCore(async (core, request, params) => {
19955
21337
  const input = await body(request);
@@ -19972,9 +21354,22 @@ const createAdminRouteHandlers = () => ({
19972
21354
  const url = new URL(request.url);
19973
21355
  const scope = nativeBuildScopeOf(url);
19974
21356
  const buildKey = url.searchParams.get("buildKey");
19975
- return json$2({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
21357
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
21358
+ const kind = url.searchParams.get("kind");
21359
+ const options = {
21360
+ ...buildKey === null ? {} : { buildKey },
21361
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
21362
+ ...builtInOlderThan === null ? {} : { builtInOlderThan },
21363
+ ...kind === null ? {} : { artifactKind: kind }
21364
+ };
21365
+ return json$2({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
21366
+ }),
21367
+ findNativeBuildSibling: onCore(async (core, _request, params) => {
21368
+ const build = await core.getNativeBuild(requireRouteParam(params, "id"));
21369
+ return json$2({ data: build === null ? null : await core.findNativeBuildSibling(build) });
19976
21370
  }),
19977
21371
  getNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
21372
+ findNativeBuildByBuiltInBundle: onCore(async (core, _request, params) => json$2({ data: await core.findNativeBuildByBuiltInBundle(requireRouteParam(params, "bundleId")) })),
19978
21373
  listNativeBuilds: onCore(async (core, request) => {
19979
21374
  const url = new URL(request.url);
19980
21375
  const input = keyset(url);
@@ -19986,14 +21381,97 @@ const createAdminRouteHandlers = () => ({
19986
21381
  }),
19987
21382
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
19988
21383
  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.");
21384
+ 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
21385
  const submission = {
19991
21386
  destination: input.destination,
19992
21387
  version: input.version
19993
21388
  };
19994
21389
  return json$2({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
19995
21390
  }),
21391
+ markNativeBuild: onCore(async (core, request, params) => {
21392
+ const input = await body(request);
21393
+ if (!isRecord$5(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
21394
+ const mark = { storeBuild: input.storeBuild };
21395
+ return json$2({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
21396
+ }),
19996
21397
  deleteNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
21398
+ listIosDevices: onCore(async (core, request) => {
21399
+ const url = new URL(request.url);
21400
+ const input = keyset(url);
21401
+ const status = url.searchParams.get("status");
21402
+ return page(await refusingInvalid(() => core.listIosDevices({
21403
+ ...input,
21404
+ ...status === null ? {} : { status }
21405
+ })), input, ({ id }) => id);
21406
+ }),
21407
+ findIosDevice: onCore(async (core, _request, params) => json$2({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
21408
+ requestIosDevice: onCore(async (core, request) => {
21409
+ const input = await body(request);
21410
+ 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.");
21411
+ const device = {
21412
+ udid: input.udid,
21413
+ name: input.name,
21414
+ requestedBy: input.requestedBy
21415
+ };
21416
+ return json$2({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
21417
+ }),
21418
+ approveIosDevice: onCore(async (core, request, params) => {
21419
+ const input = await body(request);
21420
+ 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.");
21421
+ const approval = {
21422
+ approvedBy: input.approvedBy,
21423
+ ...input.name === void 0 ? {} : { name: input.name }
21424
+ };
21425
+ return json$2({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
21426
+ }),
21427
+ renameIosDevice: onCore(async (core, request, params) => {
21428
+ const input = await body(request);
21429
+ if (!isText$2(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
21430
+ const name = input.name;
21431
+ return json$2({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
21432
+ }),
21433
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
21434
+ const input = await body(request);
21435
+ const seen = input.seen;
21436
+ 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.");
21437
+ const outcome = {
21438
+ id: requireRouteParam(params, "id"),
21439
+ seen: {
21440
+ status: seen.status,
21441
+ approvedAtMs: seen.approvedAtMs
21442
+ },
21443
+ issuerId: input.issuerId,
21444
+ outcome: input.outcome,
21445
+ ...input.reason === void 0 ? {} : { reason: input.reason }
21446
+ };
21447
+ return json$2({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
21448
+ }),
21449
+ claimIosDeviceAccount: onCore(async (core, request) => {
21450
+ const { issuerId } = await body(request);
21451
+ if (!isText$2(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
21452
+ return json$2({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
21453
+ }),
21454
+ findIosDeviceAccount: onCore(async (core) => json$2({ data: await core.findIosDeviceAccount() })),
21455
+ markIosDevicesInBuild: onCore(async (core, request) => {
21456
+ const { buildId, ids } = await body(request);
21457
+ 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.");
21458
+ if (ids.length > MAX_IDS) throw new HandlerBadRequestError(`Marking iOS devices in a build takes at most ${MAX_IDS} ids a request.`);
21459
+ await core.markIosDevicesInBuild({
21460
+ buildId,
21461
+ ids
21462
+ });
21463
+ return noContent();
21464
+ }),
21465
+ deleteIosDevice: onCore(async (core, request, params) => {
21466
+ const url = new URL(request.url);
21467
+ const status = url.searchParams.get("status");
21468
+ const requestedBy = url.searchParams.get("requestedBy");
21469
+ const only = {
21470
+ ...status === null ? {} : { status },
21471
+ ...requestedBy === null ? {} : { requestedBy }
21472
+ };
21473
+ return json$2({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
21474
+ }),
19997
21475
  deleteBundles: onCore(async (core, request) => {
19998
21476
  const { ids } = await body(request);
19999
21477
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -20047,6 +21525,21 @@ const ADMIN_ROUTES = [
20047
21525
  path: "/release-catalogs",
20048
21526
  handler: "listReleaseCatalogs"
20049
21527
  },
21528
+ {
21529
+ method: "GET",
21530
+ path: "/release-scopes",
21531
+ handler: "listReleaseScopeKeys"
21532
+ },
21533
+ {
21534
+ method: "GET",
21535
+ path: "/release-labels",
21536
+ handler: "getReleaseByLabel"
21537
+ },
21538
+ {
21539
+ method: "POST",
21540
+ path: "/release-labels/fill",
21541
+ handler: "fillReleaseLabels"
21542
+ },
20050
21543
  {
20051
21544
  method: "POST",
20052
21545
  path: "/release-catalogs/:scopeKey/rebuild",
@@ -20122,6 +21615,16 @@ const ADMIN_ROUTES = [
20122
21615
  path: "/native-builds/latest",
20123
21616
  handler: "findNativeBuild"
20124
21617
  },
21618
+ {
21619
+ method: "GET",
21620
+ path: "/native-builds/built-in/:bundleId",
21621
+ handler: "findNativeBuildByBuiltInBundle"
21622
+ },
21623
+ {
21624
+ method: "GET",
21625
+ path: "/native-builds/:id/sibling",
21626
+ handler: "findNativeBuildSibling"
21627
+ },
20125
21628
  {
20126
21629
  method: "GET",
20127
21630
  path: "/native-builds/:id",
@@ -20137,10 +21640,65 @@ const ADMIN_ROUTES = [
20137
21640
  path: "/native-builds/:id/submission",
20138
21641
  handler: "recordNativeBuildSubmission"
20139
21642
  },
21643
+ {
21644
+ method: "POST",
21645
+ path: "/native-builds/:id/store-build",
21646
+ handler: "markNativeBuild"
21647
+ },
20140
21648
  {
20141
21649
  method: "DELETE",
20142
21650
  path: "/native-builds/:id",
20143
21651
  handler: "deleteNativeBuild"
21652
+ },
21653
+ {
21654
+ method: "GET",
21655
+ path: "/ios-devices",
21656
+ handler: "listIosDevices"
21657
+ },
21658
+ {
21659
+ method: "POST",
21660
+ path: "/ios-devices",
21661
+ handler: "requestIosDevice"
21662
+ },
21663
+ {
21664
+ method: "GET",
21665
+ path: "/ios-devices/udid/:udid",
21666
+ handler: "findIosDevice"
21667
+ },
21668
+ {
21669
+ method: "POST",
21670
+ path: "/ios-devices/in-build",
21671
+ handler: "markIosDevicesInBuild"
21672
+ },
21673
+ {
21674
+ method: "GET",
21675
+ path: "/ios-devices/account",
21676
+ handler: "findIosDeviceAccount"
21677
+ },
21678
+ {
21679
+ method: "POST",
21680
+ path: "/ios-devices/account",
21681
+ handler: "claimIosDeviceAccount"
21682
+ },
21683
+ {
21684
+ method: "POST",
21685
+ path: "/ios-devices/:id/approval",
21686
+ handler: "approveIosDevice"
21687
+ },
21688
+ {
21689
+ method: "POST",
21690
+ path: "/ios-devices/:id/outcome",
21691
+ handler: "recordIosDeviceOutcome"
21692
+ },
21693
+ {
21694
+ method: "PATCH",
21695
+ path: "/ios-devices/:id",
21696
+ handler: "renameIosDevice"
21697
+ },
21698
+ {
21699
+ method: "DELETE",
21700
+ path: "/ios-devices/:id",
21701
+ handler: "deleteIosDevice"
20144
21702
  }
20145
21703
  ];
20146
21704
  //#endregion
@@ -20215,38 +21773,53 @@ const catalogResponse = async (catalog, request) => {
20215
21773
  };
20216
21774
  const createReleaseCatalogRouteHandlers = () => {
20217
21775
  const cache = /* @__PURE__ */ new Map();
21776
+ const evict = (insertedHit) => {
21777
+ const now = Date.now();
21778
+ let oldestMiss;
21779
+ let oldest;
21780
+ for (const [key, entry] of cache) if (entry.expiresAt <= now) cache.delete(key);
21781
+ else {
21782
+ if (entry.row === null) oldestMiss ??= key;
21783
+ oldest ??= key;
21784
+ }
21785
+ if (cache.size <= ORIGIN_CACHE_MAX_ENTRIES) return;
21786
+ const victim = oldestMiss ?? (insertedHit ? oldest : void 0);
21787
+ if (victim !== void 0) cache.delete(victim);
21788
+ };
20218
21789
  const inFlight = /* @__PURE__ */ new Map();
20219
- const loadCatalog = async (key, load) => {
20220
- const cached = cache.get(key);
21790
+ const loadRow = async (scopeKey, load) => {
21791
+ const cached = cache.get(scopeKey);
20221
21792
  if (cached !== void 0 && cached.expiresAt > Date.now()) {
20222
- cache.delete(key);
20223
- cache.set(key, cached);
20224
- return cached.catalog;
21793
+ cache.delete(scopeKey);
21794
+ cache.set(scopeKey, cached);
21795
+ return cached.row;
20225
21796
  }
20226
- if (cached !== void 0) cache.delete(key);
20227
- const pending = inFlight.get(key);
21797
+ if (cached !== void 0) cache.delete(scopeKey);
21798
+ const pending = inFlight.get(scopeKey);
20228
21799
  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;
21800
+ const next = load().then((row) => {
21801
+ cache.set(scopeKey, {
21802
+ row,
21803
+ expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
21804
+ });
21805
+ if (cache.size > ORIGIN_CACHE_MAX_ENTRIES) evict(row !== null);
21806
+ return row;
20242
21807
  });
20243
- inFlight.set(key, next);
21808
+ inFlight.set(scopeKey, next);
20244
21809
  try {
20245
21810
  return await next;
20246
21811
  } finally {
20247
- inFlight.delete(key);
21812
+ inFlight.delete(scopeKey);
20248
21813
  }
20249
21814
  };
21815
+ const loadCatalog = async (core, input) => {
21816
+ const scopeKey = releaseCatalogScopeKeyOf(input);
21817
+ const parsed = await loadRow(scopeKey, async () => {
21818
+ const row = await core.getReleaseCatalogRow(scopeKey);
21819
+ return row === null ? null : parseReleaseCatalogRow(row);
21820
+ });
21821
+ return projectParsedReleaseCatalogRow(parsed, input, scopeKey);
21822
+ };
20250
21823
  return {
20251
21824
  appVersionReleaseCatalog: async (params, request, { core }) => {
20252
21825
  const rawAppVersion = requireRouteParam(params, "appVersion");
@@ -20260,7 +21833,7 @@ const createReleaseCatalogRouteHandlers = () => {
20260
21833
  };
20261
21834
  const invalid = invalidScope(input);
20262
21835
  if (invalid) return invalid;
20263
- return catalogResponse(await loadCatalog(`app-version:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
21836
+ return catalogResponse(await loadCatalog(core, input), request);
20264
21837
  },
20265
21838
  fingerprintReleaseCatalog: async (params, request, { core }) => {
20266
21839
  const input = {
@@ -20271,7 +21844,7 @@ const createReleaseCatalogRouteHandlers = () => {
20271
21844
  };
20272
21845
  const invalid = invalidScope(input);
20273
21846
  if (invalid) return invalid;
20274
- return catalogResponse(await loadCatalog(`fingerprint:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
21847
+ return catalogResponse(await loadCatalog(core, input), request);
20275
21848
  },
20276
21849
  artifactV2: async (params, _request, { core }) => {
20277
21850
  const info = await core.getArtifactInfo(requireRouteParam(params, "targetBundleId"), requireRouteParam(params, "currentBundleId"), 2);
@@ -20398,7 +21971,8 @@ const createRequestHandler = ({ api, clientPolicy, privateResponses = false, rou
20398
21971
  let authenticated;
20399
21972
  try {
20400
21973
  authenticated = await clientPolicy.authenticate(request);
20401
- } catch {
21974
+ } catch (error) {
21975
+ console.error("Hot Updater client authentication error:", error);
20402
21976
  return errorResponse("Service unavailable", 503);
20403
21977
  }
20404
21978
  if (!authenticated) return errorResponse("Unauthorized", 401);
@@ -20899,13 +22473,15 @@ const isLaunch = (row) => {
20899
22473
  const kinds = metadataOf(row).change?.kinds ?? [];
20900
22474
  return kinds.includes("bundle") && !kinds.includes("first_seen") && row.to_release_id !== null;
20901
22475
  };
20902
- const bundleRefsOf = (row) => {
22476
+ const sideRef = (key, releaseId, bundleId) => key === "release" ? releaseId ?? bundleId : bundleId;
22477
+ const bundleRefsOf = (row, key = "release") => {
20903
22478
  if (isFailedCheck(row) || isLateEvent(row)) return [];
20904
- if (row.type === "RECOVERED") return [`from:${row.from_bundle_id}`];
20905
- if (row.type === "UNCHANGED") return isLaunch(row) ? [`on:${row.to_bundle_id}`] : [];
20906
- return [`to:${row.to_bundle_id}`];
22479
+ if (row.type === "RECOVERED") return [`from:${sideRef(key, row.from_release_id, row.from_bundle_id)}`];
22480
+ if (row.type === "UNCHANGED") return isLaunch(row) ? [`on:${sideRef(key, row.to_release_id, row.to_bundle_id)}`] : [];
22481
+ return [`to:${sideRef(key, row.to_release_id, row.to_bundle_id)}`];
20907
22482
  };
20908
- const bundleRefOfFilter = (filter) => filter.type === "RECOVERED" ? `from:${filter.fromBundleId}` : filter.type === "UNCHANGED" ? `on:${filter.toBundleId}` : `to:${filter.toBundleId}`;
22483
+ const outcomeRefsOf = (row, key = "release") => [...bundleRefsOf(row, key).map((ref) => [row.type, ref]), ...metadataOf(row).implied_download === true ? [["UPDATE_DOWNLOADED", row.type === "RECOVERED" ? `to:${sideRef(key, row.from_release_id, row.from_bundle_id)}` : `to:${sideRef(key, row.to_release_id, row.to_bundle_id)}`]] : []];
22484
+ const bundleRefOfFilter = (filter) => filter.type === "RECOVERED" ? `from:${filter.fromReleaseId}` : filter.type === "UNCHANGED" ? `on:${filter.toReleaseId}` : `to:${filter.toReleaseId}`;
20909
22485
  const bundleEvents = (days) => defineTable({
20910
22486
  id: {
20911
22487
  type: "string",
@@ -21335,6 +22911,83 @@ const createInsightsSchema = ({ rawDays, dailyDays } = DEFAULT_INSIGHTS_RETENTIO
21335
22911
  };
21336
22912
  createInsightsSchema();
21337
22913
  //#endregion
22914
+ //#region ../insights/dist/server/backfill.mjs
22915
+ const PAGE$1 = 500;
22916
+ const BATCH = 25;
22917
+ const PAUSE_MS = 1e3;
22918
+ const MAX_PAUSE_MS = 32e3;
22919
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
22920
+ const sameRefs = (stored, refs) => {
22921
+ const values = Array.isArray(stored) ? stored : [];
22922
+ return values.length === refs.length && values.every((value) => refs.includes(value));
22923
+ };
22924
+ const namesArtifact = (row) => {
22925
+ const byKey = (key) => bundleRefsOf(row, key);
22926
+ return sameRefs(row.bundle_ref, byKey("artifact")) && !sameRefs(row.bundle_ref, byKey("release"));
22927
+ };
22928
+ const backfillReleaseRefs = async (db, now, { rawDays }, { dryRun = false } = {}) => {
22929
+ const today = now() - now() % DAY_MS$1;
22930
+ let events = 0;
22931
+ let size = BATCH;
22932
+ let paused = 0;
22933
+ const move = async (stale) => {
22934
+ if (dryRun) {
22935
+ events += stale.length;
22936
+ return;
22937
+ }
22938
+ for (let start = 0; start < stale.length;) {
22939
+ const candidates = stale.slice(start, start + size);
22940
+ try {
22941
+ events += await rewrite(candidates);
22942
+ start += candidates.length;
22943
+ paused = 0;
22944
+ } catch (error) {
22945
+ if (error instanceof DatabaseConstraintError && error.reason === "too_large" && candidates.length > 1) {
22946
+ size = Math.ceil(candidates.length / 2);
22947
+ continue;
22948
+ }
22949
+ if (!isDatabaseBusyError(error) || paused >= MAX_PAUSE_MS) throw error;
22950
+ size = Math.ceil(candidates.length / 2);
22951
+ paused = paused === 0 ? PAUSE_MS : paused * 2;
22952
+ await sleep(paused);
22953
+ }
22954
+ }
22955
+ };
22956
+ const rewrite = (candidates) => db.transaction(async (tx) => {
22957
+ const rows = await Promise.all(candidates.map(({ id }) => tx.findOne("bundle_events", { id })));
22958
+ let moved = 0;
22959
+ for (const row of rows) {
22960
+ if (row === null || !namesArtifact(row)) continue;
22961
+ tx.update("bundle_events", row, {});
22962
+ const outcome = (ref, delta) => tx.aggregate("insights_outcomes", {
22963
+ platform: row.platform,
22964
+ channel: row.channel,
22965
+ type: ref[0],
22966
+ bundle_ref: ref[1],
22967
+ bucket_start_ms: row.received_at_ms - row.received_at_ms % HOUR_MS$1
22968
+ }, { events: delta }, { shardBy: row.install_id });
22969
+ for (const ref of outcomeRefsOf(row, "artifact")) outcome(ref, -1);
22970
+ for (const ref of outcomeRefsOf(row, "release")) outcome(ref, 1);
22971
+ moved += 1;
22972
+ }
22973
+ return moved;
22974
+ });
22975
+ for (let day = today - rawDays * DAY_MS$1; day <= today; day += DAY_MS$1) {
22976
+ let cursor;
22977
+ do {
22978
+ const page = await db.findMany("bundle_events", {
22979
+ index: "byDay",
22980
+ where: { day },
22981
+ limit: PAGE$1,
22982
+ ...cursor === void 0 ? {} : { cursor }
22983
+ });
22984
+ await move(page.rows.filter(namesArtifact));
22985
+ cursor = page.next;
22986
+ } while (cursor !== void 0);
22987
+ }
22988
+ return { events };
22989
+ };
22990
+ //#endregion
21338
22991
  //#region ../insights/dist/server/eventRow.mjs
21339
22992
  const CHANGE_KINDS = /* @__PURE__ */ new Set([
21340
22993
  "first_seen",
@@ -21412,7 +23065,7 @@ const isBundleFilter = (value, withKind = false) => {
21412
23065
  "type",
21413
23066
  ...withKind ? ["kind"] : []
21414
23067
  ];
21415
- return value.type === "RECOVERED" ? isText$1(value.fromBundleId) && hasOnlyKeys(value, [...keys, "fromBundleId"]) : (value.type === "UPDATE_DOWNLOADED" || value.type === "UPDATE_APPLIED" || value.type === "UPDATE_FAILED" || value.type === "UNCHANGED") && isText$1(value.toBundleId) && hasOnlyKeys(value, [...keys, "toBundleId"]);
23068
+ return value.type === "RECOVERED" ? isText$1(value.fromReleaseId) && hasOnlyKeys(value, [...keys, "fromReleaseId"]) : (value.type === "UPDATE_DOWNLOADED" || value.type === "UPDATE_APPLIED" || value.type === "UPDATE_FAILED" || value.type === "UNCHANGED") && isText$1(value.toReleaseId) && hasOnlyKeys(value, [...keys, "toReleaseId"]);
21416
23069
  };
21417
23070
  const isEventFilter = (value) => {
21418
23071
  if (!isRecord$3(value)) return false;
@@ -21507,20 +23160,24 @@ const createValidatedInsightsModel = (model) => ({
21507
23160
  if (!isRecord$3(input) || !hasOnlyKeys(input, [
21508
23161
  "platform",
21509
23162
  "channel",
21510
- "sinceMs",
21511
- "bundle"
21512
- ]) || !hasScope(input) || !isTimestamp(input.sinceMs) || input.bundle !== void 0 && (!Array.isArray(input.bundle) || input.bundle.length < 1 || input.bundle.length > 2 || input.bundle.some((bundle) => !isRecord$3(bundle) || !hasOnlyKeys(bundle, [
21513
- "field",
21514
- "value",
21515
- "types"
21516
- ]) || bundle.field !== "from_bundle_id" && bundle.field !== "to_bundle_id" || !isText$1(bundle.value) || !Array.isArray(bundle.types) || bundle.types.length === 0 || bundle.types.some((type) => ![
21517
- "UNCHANGED",
21518
- "UPDATE_DOWNLOADED",
21519
- "UPDATE_APPLIED",
21520
- "RECOVERED"
21521
- ].includes(type))))) invalidQuery();
23163
+ "sinceMs"
23164
+ ]) || !hasScope(input) || !isTimestamp(input.sinceMs)) invalidQuery();
21522
23165
  return validateCount(await model.countLatestEvents(input));
21523
23166
  },
23167
+ async countReleaseInstallations(input) {
23168
+ if (!isRecord$3(input) || !hasOnlyKeys(input, [
23169
+ "platform",
23170
+ "channel",
23171
+ "sinceMs",
23172
+ "releaseId"
23173
+ ]) || !hasScope(input) || !isTimestamp(input.sinceMs) || !isText$1(input.releaseId)) invalidQuery();
23174
+ const counts = await model.countReleaseInstallations(input);
23175
+ if (!isRecord$3(counts) || !hasOnlyKeys(counts, ["installations", "release"])) invalidResult();
23176
+ return {
23177
+ installations: validateCount(counts.installations),
23178
+ release: validateCount(counts.release)
23179
+ };
23180
+ },
21524
23181
  async countEvents(input) {
21525
23182
  if (!isRecord$3(input) || !hasOnlyKeys(input, [
21526
23183
  "filter",
@@ -21573,6 +23230,7 @@ const createInsightsModel = (api) => createValidatedInsightsModel({
21573
23230
  listEvents: api.listEvents,
21574
23231
  findLatestEvents: api.findLatestEvents,
21575
23232
  countLatestEvents: api.countLatestEvents,
23233
+ countReleaseInstallations: api.countReleaseInstallations,
21576
23234
  countEvents: api.countEvents,
21577
23235
  countEventSeries: api.countEventSeries,
21578
23236
  getReleaseActivity: api.getReleaseActivity,
@@ -21941,27 +23599,27 @@ const readScope$1 = (input) => {
21941
23599
  };
21942
23600
  const bundleFilter = (input) => {
21943
23601
  const scope = readScope$1(input);
21944
- const bundleId = requireString(input.bundleId, "bundle ID", MAX_EVENT_ID_LENGTH);
23602
+ const releaseId = requireString(input.releaseId, "bundle ID", MAX_EVENT_ID_LENGTH);
21945
23603
  switch (input.outcome) {
21946
23604
  case "downloaded": return {
21947
23605
  ...scope,
21948
23606
  type: "UPDATE_DOWNLOADED",
21949
- toBundleId: bundleId
23607
+ toReleaseId: releaseId
21950
23608
  };
21951
23609
  case "applied": return {
21952
23610
  ...scope,
21953
23611
  type: "UPDATE_APPLIED",
21954
- toBundleId: bundleId
23612
+ toReleaseId: releaseId
21955
23613
  };
21956
23614
  case "recovered": return {
21957
23615
  ...scope,
21958
23616
  type: "RECOVERED",
21959
- fromBundleId: bundleId
23617
+ fromReleaseId: releaseId
21960
23618
  };
21961
23619
  case "failed": return {
21962
23620
  ...scope,
21963
23621
  type: "UPDATE_FAILED",
21964
- toBundleId: bundleId
23622
+ toReleaseId: releaseId
21965
23623
  };
21966
23624
  default: throw new InsightsBadRequestError("Invalid Insights outcome.");
21967
23625
  }
@@ -21971,7 +23629,7 @@ const sameFilter = (left, right) => {
21971
23629
  switch (right.kind) {
21972
23630
  case "all": return true;
21973
23631
  case "installationMovement": return left.installId === right.installId;
21974
- case "bundle": return left.platform === right.platform && left.channel === right.channel && left.type === right.type && (right.type === "RECOVERED" ? left.fromBundleId === right.fromBundleId : left.toBundleId === right.toBundleId);
23632
+ case "bundle": return left.platform === right.platform && left.channel === right.channel && left.type === right.type && (right.type === "RECOVERED" ? left.fromReleaseId === right.fromReleaseId : left.toReleaseId === right.toReleaseId);
21975
23633
  }
21976
23634
  };
21977
23635
  const readEventCursor = (value, filter) => {
@@ -22008,7 +23666,7 @@ const assertEventRows = (rows, input) => {
22008
23666
  for (let index = 0; index < rows.length; index += 1) {
22009
23667
  const row = rows[index];
22010
23668
  const previous = rows[index - 1];
22011
- if (!row || typeof row.id !== "string" || !isUUIDv7(row.id) || !Number.isSafeInteger(row.received_at_ms) || row.received_at_ms >= input.beforeReceivedAtMs || row.received_at_ms < input.sinceMs || previous !== void 0 && compareEventNewest(previous, row) >= 0 || input.after !== void 0 && !isAfterEventCursor(row, input.after) || input.filter.kind === "installationMovement" && (row.install_id !== input.filter.installId || !isInsightsMovementEvent(row)) || input.filter.kind === "bundle" && (row.platform !== input.filter.platform || row.channel !== input.filter.channel || row.type !== input.filter.type || (input.filter.type === "RECOVERED" ? row.from_bundle_id !== input.filter.fromBundleId : row.to_bundle_id !== input.filter.toBundleId))) throw new Error("Insights database returned invalid event rows.");
23669
+ if (!row || typeof row.id !== "string" || !isUUIDv7(row.id) || !Number.isSafeInteger(row.received_at_ms) || row.received_at_ms >= input.beforeReceivedAtMs || row.received_at_ms < input.sinceMs || previous !== void 0 && compareEventNewest(previous, row) >= 0 || input.after !== void 0 && !isAfterEventCursor(row, input.after) || input.filter.kind === "installationMovement" && (row.install_id !== input.filter.installId || !isInsightsMovementEvent(row)) || input.filter.kind === "bundle" && (row.platform !== input.filter.platform || row.channel !== input.filter.channel || row.type !== input.filter.type || (input.filter.type === "RECOVERED" ? (row.from_release_id ?? row.from_bundle_id) !== input.filter.fromReleaseId : (row.to_release_id ?? row.to_bundle_id) !== input.filter.toReleaseId))) throw new Error("Insights database returned invalid event rows.");
22012
23670
  }
22013
23671
  };
22014
23672
  const toFailure = (failure) => ({
@@ -22047,6 +23705,7 @@ const eventDetails = ({ type, metadata }) => ({
22047
23705
  ...metadata.implied_download === true ? { impliedDownload: true } : {}
22048
23706
  });
22049
23707
  const toEventHistoryRow = (row) => ({
23708
+ ...row.from_release_id == null ? {} : { fromReleaseId: row.from_release_id },
22050
23709
  ...row.to_release_id == null ? {} : { toReleaseId: row.to_release_id },
22051
23710
  ...row.metadata.sdk_version == null ? {} : { sdkVersion: row.metadata.sdk_version },
22052
23711
  ...row.metadata.min_bundle_id === void 0 ? {} : { minBundleId: row.metadata.min_bundle_id },
@@ -22071,6 +23730,7 @@ const toInstallationRow = (row) => ({
22071
23730
  cohort: row.metadata.cohort,
22072
23731
  installId: row.install_id,
22073
23732
  lastKnownBundleId: row.type === "UPDATE_DOWNLOADED" ? row.from_bundle_id : row.to_bundle_id,
23733
+ lastKnownReleaseId: row.type === "UPDATE_DOWNLOADED" ? row.from_release_id : row.to_release_id,
22074
23734
  pendingBundleId: row.type === "UPDATE_DOWNLOADED" ? row.to_bundle_id : null,
22075
23735
  pendingReleaseId: row.type === "UPDATE_DOWNLOADED" ? row.to_release_id : null,
22076
23736
  latestStatus: row.type,
@@ -22193,46 +23853,33 @@ const createInsightsProvider = (model) => Object.freeze({
22193
23853
  measuredAtMs: Date.now()
22194
23854
  };
22195
23855
  };
22196
- const bundleId = input.bundleId === void 0 ? void 0 : requireString(input.bundleId, "bundle ID", MAX_EVENT_ID_LENGTH);
22197
- const reporting = measure(model.countLatestEvents({
22198
- ...scope,
22199
- sinceMs
22200
- }));
22201
- if (bundleId === void 0) return {
23856
+ const releaseId = input.releaseId === void 0 ? void 0 : requireString(input.releaseId, "bundle ID", MAX_EVENT_ID_LENGTH);
23857
+ if (releaseId === void 0) return {
22202
23858
  ...scope,
22203
23859
  window,
22204
23860
  sinceMs,
22205
23861
  beforeReceivedAtMs,
22206
- reportingInstallations: await reporting
23862
+ reportingInstallations: await measure(model.countLatestEvents({
23863
+ ...scope,
23864
+ sinceMs
23865
+ }))
22207
23866
  };
23867
+ const installations = model.countReleaseInstallations({
23868
+ ...scope,
23869
+ sinceMs,
23870
+ releaseId
23871
+ }).then(async (counts) => [await measure(Promise.resolve(counts.installations)), await measure(Promise.resolve(counts.release))]);
22208
23872
  const countOutcome = (outcome) => measure(model.countEvents({
22209
23873
  filter: bundleFilter({
22210
23874
  ...scope,
22211
- bundleId,
23875
+ releaseId,
22212
23876
  outcome
22213
23877
  }),
22214
23878
  sinceMs,
22215
23879
  beforeReceivedAtMs
22216
23880
  }));
22217
- const [reportingInstallations, bundleInstallations, downloadedReports, appliedReports, recoveredReports, failedReports] = await Promise.all([
22218
- reporting,
22219
- measure(model.countLatestEvents({
22220
- ...scope,
22221
- sinceMs,
22222
- bundle: [{
22223
- field: "from_bundle_id",
22224
- value: bundleId,
22225
- types: ["UPDATE_DOWNLOADED"]
22226
- }, {
22227
- field: "to_bundle_id",
22228
- value: bundleId,
22229
- types: [
22230
- "UNCHANGED",
22231
- "UPDATE_APPLIED",
22232
- "RECOVERED"
22233
- ]
22234
- }]
22235
- })),
23881
+ const [[reportingInstallations, bundleInstallations], downloadedReports, appliedReports, recoveredReports, failedReports] = await Promise.all([
23882
+ installations,
22236
23883
  countOutcome("downloaded"),
22237
23884
  countOutcome("applied"),
22238
23885
  countOutcome("recovered"),
@@ -22245,7 +23892,7 @@ const createInsightsProvider = (model) => Object.freeze({
22245
23892
  beforeReceivedAtMs,
22246
23893
  reportingInstallations,
22247
23894
  bundle: {
22248
- bundleId,
23895
+ releaseId,
22249
23896
  reportingInstallations: bundleInstallations,
22250
23897
  downloadedReports,
22251
23898
  appliedReports,
@@ -22370,8 +24017,6 @@ const gaugeSlot = (head) => ({
22370
24017
  releaseId: head.type === "UPDATE_DOWNLOADED" ? head.from_release_id : head.to_release_id,
22371
24018
  builtinBundleId: runningBuiltinBundleId(head)
22372
24019
  });
22373
- const PAIR_FIELD = "from_to";
22374
- const bundlePairKey = (from, to) => insightsKey(`${from.length}:${from}${to.length}:${to}`);
22375
24020
  const countHead = (tx, head, delta) => {
22376
24021
  const { bucket, releaseId, builtinBundleId } = gaugeSlot(head);
22377
24022
  const shardBy = head.install_id;
@@ -22390,26 +24035,6 @@ const countHead = (tx, head, delta) => {
22390
24035
  builtin_bundle_id: builtinBundleId,
22391
24036
  bucket_start_ms: bucket
22392
24037
  }, { latest_installations: delta }, { shardBy });
22393
- for (const field of ["from_bundle_id", "to_bundle_id"]) {
22394
- const bundleId = head[field];
22395
- if (bundleId === null) continue;
22396
- tx.aggregate("insights_latest_by_bundle", {
22397
- platform: head.platform,
22398
- channel: head.channel,
22399
- bundle_field: field,
22400
- bundle_id: bundleId,
22401
- type: head.type,
22402
- bucket_start_ms: bucket
22403
- }, { installations: delta }, { shardBy });
22404
- }
22405
- if (head.from_bundle_id !== null) tx.aggregate("insights_latest_by_bundle", {
22406
- platform: head.platform,
22407
- channel: head.channel,
22408
- bundle_field: PAIR_FIELD,
22409
- bundle_id: bundlePairKey(head.from_bundle_id, head.to_bundle_id),
22410
- type: head.type,
22411
- bucket_start_ms: bucket
22412
- }, { installations: delta }, { shardBy });
22413
24038
  };
22414
24039
  const PERIOD_MODELS = {
22415
24040
  hour: {
@@ -22459,18 +24084,13 @@ const countEvent = (tx, event) => {
22459
24084
  };
22460
24085
  const countOutcome = (tx, event) => {
22461
24086
  const shardBy = event.install_id;
22462
- const hour = (type, bundleRef) => tx.aggregate("insights_outcomes", {
24087
+ for (const [type, bundleRef] of outcomeRefsOf(event)) tx.aggregate("insights_outcomes", {
22463
24088
  platform: event.platform,
22464
24089
  channel: event.channel,
22465
24090
  type,
22466
24091
  bundle_ref: bundleRef,
22467
24092
  bucket_start_ms: hourOf(event.received_at_ms)
22468
24093
  }, { events: 1 }, { shardBy });
22469
- for (const bundleRef of bundleRefsOf(event)) hour(event.type, bundleRef);
22470
- if (event.metadata.implied_download === true) hour("UPDATE_DOWNLOADED", bundleRefOfFilter({
22471
- type: "UPDATE_DOWNLOADED",
22472
- toBundleId: event.type === "RECOVERED" ? event.from_bundle_id : event.to_bundle_id
22473
- }));
22474
24094
  tx.aggregate("insights_outcomes", {
22475
24095
  ...DAILY_EVENTS,
22476
24096
  bucket_start_ms: dayOf(event.received_at_ms)
@@ -22856,25 +24476,34 @@ const countEventSeries = async (db, input) => {
22856
24476
  events: count
22857
24477
  }));
22858
24478
  };
22859
- const latestPredicates = (bundle) => {
22860
- if (bundle === void 0) return void 0;
22861
- return [...new Map(bundle.flatMap(({ field, value, types }) => types.map((type) => [JSON.stringify([
22862
- field,
22863
- value,
22864
- type
22865
- ]), {
22866
- field,
22867
- value,
22868
- type
22869
- }]))).values()];
22870
- };
22871
- const countLatestEvents = async (db, input) => {
22872
- const { platform, channel, sinceMs: start } = input;
24479
+ const distributionRows = (db, { platform, channel, sinceMs: start }) => {
22873
24480
  if (start % 864e5 !== 0) throw new DatabaseAdapterInputError("invalid-query");
22874
- const predicates = latestPredicates(input.bundle);
24481
+ return drain((page) => db.findAggregates("insights_distribution", {
24482
+ index: "byScope",
24483
+ where: {
24484
+ channel,
24485
+ platform
24486
+ },
24487
+ range: { gte: start },
24488
+ limit: PAGE,
24489
+ ...page
24490
+ }));
24491
+ };
24492
+ const installations = (count) => Math.max(0, count);
24493
+ const countLatestEvents = async (db, input) => installations((await distributionRows(db, input)).reduce((sum, row) => sum + row.latest_installations, 0));
24494
+ const countReleaseInstallations = async (db, input) => {
24495
+ const { platform, channel, sinceMs: start, releaseId } = input;
22875
24496
  let total = 0;
22876
- if (predicates === void 0) {
22877
- const rows = await drain((page) => db.findAggregates("insights_distribution", {
24497
+ let release = 0;
24498
+ let named = false;
24499
+ for (const row of await distributionRows(db, input)) {
24500
+ total += row.latest_installations;
24501
+ if (row.release_id !== releaseId) continue;
24502
+ named = true;
24503
+ release += row.latest_installations;
24504
+ }
24505
+ if (!named) {
24506
+ const builtin = await drain((page) => db.findAggregates("insights_builtin_distribution", {
22878
24507
  index: "byScope",
22879
24508
  where: {
22880
24509
  channel,
@@ -22884,33 +24513,12 @@ const countLatestEvents = async (db, input) => {
22884
24513
  limit: PAGE,
22885
24514
  ...page
22886
24515
  }));
22887
- total += rows.reduce((sum, row) => sum + row.latest_installations, 0);
22888
- } else {
22889
- const gauge = async (bundleField, bundleId, type) => {
22890
- return (await drain((page) => db.findAggregates("insights_latest_by_bundle", {
22891
- index: "byBundle",
22892
- where: {
22893
- platform,
22894
- channel,
22895
- bundle_field: bundleField,
22896
- bundle_id: bundleId,
22897
- type
22898
- },
22899
- range: { gte: start },
22900
- limit: PAGE,
22901
- ...page
22902
- }))).reduce((sum, row) => sum + row.installations, 0);
22903
- };
22904
- for (const { field, value, type } of predicates) total += await gauge(field, value, type);
22905
- for (const from of predicates) {
22906
- if (from.field !== "from_bundle_id") continue;
22907
- for (const to of predicates) {
22908
- if (to.field !== "to_bundle_id" || to.type !== from.type) continue;
22909
- total -= await gauge(PAIR_FIELD, bundlePairKey(from.value, to.value), from.type);
22910
- }
22911
- }
24516
+ for (const row of builtin) if (row.release_id === "" && row.builtin_bundle_id === releaseId) release += row.latest_installations;
22912
24517
  }
22913
- return Math.max(0, total);
24518
+ return {
24519
+ installations: installations(total),
24520
+ release: installations(release)
24521
+ };
22914
24522
  };
22915
24523
  const retained = (now, { rawDays, dailyDays }) => ({
22916
24524
  hour: hourCeil(now - rawDays * DAY_MS$1),
@@ -23185,6 +24793,53 @@ const breakdownOf = (rows) => {
23185
24793
  };
23186
24794
  });
23187
24795
  };
24796
+ const FAILURE_ROWS_PER_HOUR = 20;
24797
+ const FAILURE_QUERY_LIMIT = Math.min(PAGE, 168);
24798
+ const failureRowsByHour = async (db, platform, channel, timeRange) => {
24799
+ const read = (end, cursor) => db.findAggregates("insights_failures", {
24800
+ index: "byScope",
24801
+ where: {
24802
+ platform,
24803
+ channel
24804
+ },
24805
+ range: {
24806
+ gte: timeRange.start,
24807
+ lt: end
24808
+ },
24809
+ order: "desc",
24810
+ limit: FAILURE_QUERY_LIMIT,
24811
+ ...cursor === void 0 ? {} : { cursor }
24812
+ });
24813
+ const rows = [];
24814
+ const cappedHours = [];
24815
+ const perHour = /* @__PURE__ */ new Map();
24816
+ let end = timeRange.end;
24817
+ let cursor;
24818
+ while (end > timeRange.start) {
24819
+ const page = await read(end, cursor);
24820
+ let capped;
24821
+ for (const row of page.rows) {
24822
+ const hour = row.bucket_start_ms;
24823
+ const count = (perHour.get(hour) ?? 0) + 1;
24824
+ if (count > FAILURE_ROWS_PER_HOUR) {
24825
+ capped = hour;
24826
+ break;
24827
+ }
24828
+ perHour.set(hour, count);
24829
+ rows.push(row);
24830
+ }
24831
+ if (capped !== void 0) {
24832
+ cappedHours.unshift(capped);
24833
+ end = capped;
24834
+ cursor = void 0;
24835
+ } else if (page.next === void 0) break;
24836
+ else cursor = page.next;
24837
+ }
24838
+ return {
24839
+ rows,
24840
+ cappedHours
24841
+ };
24842
+ };
23188
24843
  const getUpdateFailures = async (db, input, now, retention) => {
23189
24844
  const { platform, channel, releaseId, timeRange } = input;
23190
24845
  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 +24900,7 @@ const getUpdateFailures = async (db, input, now, retention) => {
23245
24900
  days,
23246
24901
  kept.hour
23247
24902
  ];
23248
- const [counters, failures, checks, active, rows] = await Promise.all([
24903
+ const [counters, failures, checks, active, { rows, cappedHours }] = await Promise.all([
23249
24904
  counterRows(db, parts, ...window),
23250
24905
  sketchRows(db, failure, ...window),
23251
24906
  days ? sketchRows(db, {
@@ -23253,25 +24908,17 @@ const getUpdateFailures = async (db, input, now, retention) => {
23253
24908
  scopeKind: "check"
23254
24909
  }, ...window) : [],
23255
24910
  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
- }))
24911
+ failureRowsByHour(db, platform, channel, timeRange)
23269
24912
  ]);
23270
24913
  const total = (field) => counters.reduce((sum, row) => sum + row[field], 0);
23271
24914
  const scoped = rows.filter((row) => FAILURE_STAGES.has(row.stage) && (releaseId === void 0 || row.release_id === releaseId));
23272
24915
  const failuresAt = (counted) => scoped.reduce((sum, row) => sum + (counted(row.stage) ? Math.max(0, row.events) : 0), 0);
24916
+ const coverage = coverageOf(timeRange.start, kept.hour);
23273
24917
  return {
23274
- coverage: coverageOf(timeRange.start, kept.hour),
24918
+ coverage: cappedHours.length === 0 ? coverage : {
24919
+ kind: "partial",
24920
+ sinceMs: coverage.sinceMs
24921
+ },
23275
24922
  measuredAtMs: at,
23276
24923
  failedUpdates: failuresAt((stage) => stage !== "check"),
23277
24924
  failedInstallations: failed(failures),
@@ -23283,7 +24930,22 @@ const getUpdateFailures = async (db, input, now, retention) => {
23283
24930
  failedInstallations: failed(checks),
23284
24931
  activeInstallations: countDistinct(mergeDistinct(active.map((row) => row.activity_users)))
23285
24932
  } } : {},
23286
- breakdown: breakdownOf(scoped)
24933
+ breakdown: breakdownOf(scoped),
24934
+ ...cappedHours.length === 0 ? {} : { cappedHours }
24935
+ };
24936
+ };
24937
+ //#endregion
24938
+ //#region ../insights/dist/server/wire.mjs
24939
+ const RELEASE_ID_PARAM = "bundleId";
24940
+ const toWireOverview = ({ bundle, ...overview }) => {
24941
+ if (bundle === void 0) return overview;
24942
+ const { releaseId, ...counts } = bundle;
24943
+ return {
24944
+ ...overview,
24945
+ bundle: {
24946
+ ...counts,
24947
+ bundleId: releaseId
24948
+ }
23287
24949
  };
23288
24950
  };
23289
24951
  //#endregion
@@ -23331,7 +24993,7 @@ const readScope = (url) => {
23331
24993
  const parseEventPageInput = (request) => {
23332
24994
  const url = new URL(request.url);
23333
24995
  const bundleFields = [
23334
- "bundleId",
24996
+ RELEASE_ID_PARAM,
23335
24997
  "outcome",
23336
24998
  "platform",
23337
24999
  "channel"
@@ -23342,7 +25004,7 @@ const parseEventPageInput = (request) => {
23342
25004
  if (outcome !== "downloaded" && outcome !== "applied" && outcome !== "recovered" && outcome !== "failed") throw new InsightsBadRequestError("Invalid 'outcome' query parameter.");
23343
25005
  bundle = {
23344
25006
  ...readScope(url),
23345
- bundleId: readId(url, "bundleId", 1024),
25007
+ releaseId: readId(url, RELEASE_ID_PARAM, 1024),
23346
25008
  outcome
23347
25009
  };
23348
25010
  }
@@ -23368,11 +25030,10 @@ const parseReportingOverviewInput = (request) => {
23368
25030
  const url = new URL(request.url);
23369
25031
  const window = readSingle(url, "window") ?? "30d";
23370
25032
  if (window !== "24h" && window !== "7d" && window !== "30d") throw new InsightsBadRequestError("Invalid 'window' query parameter.");
23371
- const bundleId = readSingle(url, "bundleId");
23372
25033
  return {
23373
25034
  ...readScope(url),
23374
25035
  window,
23375
- ...bundleId === void 0 ? {} : { bundleId: readId(url, "bundleId", 1024) }
25036
+ ...readSingle(url, "bundleId") === void 0 ? {} : { releaseId: readId(url, RELEASE_ID_PARAM, 1024) }
23376
25037
  };
23377
25038
  };
23378
25039
  //#endregion
@@ -23451,7 +25112,7 @@ const createInsightsRouteHandlers = (provider) => ({
23451
25112
  await provider.appendBundleEvent(await parseBundleEventRequest(request));
23452
25113
  return new Response(null, { status: 204 });
23453
25114
  }),
23454
- getReportingOverview: (_params, request) => query(() => provider.getReportingOverview(parseReportingOverviewInput(request))),
25115
+ getReportingOverview: (_params, request) => query(async () => toWireOverview(await provider.getReportingOverview(parseReportingOverviewInput(request)))),
23455
25116
  getInstallation: (params) => run$1(async () => {
23456
25117
  const installation = await provider.getInstallation({ installId: requireParam(params, "installId") });
23457
25118
  return installation === null ? json$1({ error: "Installation not found" }, 404) : json$1(installation, 200);
@@ -23471,11 +25132,13 @@ const createInsightsApi = (db, now, retention) => ({
23471
25132
  listEvents: (input) => listEvents(db, input),
23472
25133
  findLatestEvents: (input) => findLatestEvents(db, input),
23473
25134
  countLatestEvents: (input) => countLatestEvents(db, input),
25135
+ countReleaseInstallations: (input) => countReleaseInstallations(db, input),
23474
25136
  countEvents: (input) => countEvents(db, input),
23475
25137
  countEventSeries: (input) => countEventSeries(db, input),
23476
25138
  getReleaseActivity: (input) => getReleaseActivity(db, input, now),
23477
25139
  getAppUsage: (input) => getAppUsage(db, input, now, retention),
23478
- getUpdateFailures: (input) => getUpdateFailures(db, input, now, retention)
25140
+ getUpdateFailures: (input) => getUpdateFailures(db, input, now, retention),
25141
+ backfillReleaseRefs: (options) => backfillReleaseRefs(db, now, retention, options)
23479
25142
  });
23480
25143
  const readFailuresQuery = (url) => {
23481
25144
  const query = url.searchParams;
@@ -54051,15 +55714,21 @@ const vercelBlobStorage = (config) => {
54051
55714
  bucket: storeId,
54052
55715
  key: storageKey
54053
55716
  });
54054
- await put(toPathname(storageKey), body, {
54055
- access,
54056
- token,
54057
- addRandomSuffix: false,
54058
- allowOverwrite: true,
54059
- cacheControlMaxAge: ONE_YEAR_IN_SECONDS,
54060
- contentType,
54061
- multipart: contentLength === void 0 || contentLength > MULTIPART_THRESHOLD_BYTES
54062
- });
55717
+ const multipart = contentLength === void 0 || contentLength > MULTIPART_THRESHOLD_BYTES;
55718
+ try {
55719
+ await put(toPathname(storageKey), body, {
55720
+ access,
55721
+ token,
55722
+ addRandomSuffix: false,
55723
+ allowOverwrite: true,
55724
+ cacheControlMaxAge: ONE_YEAR_IN_SECONDS,
55725
+ contentType,
55726
+ multipart
55727
+ });
55728
+ } catch (error) {
55729
+ if (!multipart && error instanceof TypeError && body.locked) throw new Error(`Vercel Blob failed while uploading ${storageKey}: it answered an error or the connection dropped`, { cause: error });
55730
+ throw error;
55731
+ }
54063
55732
  return { storageUri };
54064
55733
  },
54065
55734
  async get({ storageUri }) {