@hot-updater/firebase 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.
@@ -4,6 +4,8 @@ let firebase_functions_v2_https = require("firebase-functions/v2/https");
4
4
  let hono = require("hono");
5
5
  let firebase_admin_firestore = require("firebase-admin/firestore");
6
6
  let node_crypto = require("node:crypto");
7
+ let node_stream = require("node:stream");
8
+ let node_stream_promises = require("node:stream/promises");
7
9
  let firebase_admin_storage = require("firebase-admin/storage");
8
10
  //#region ../plugin-core/dist/contentAddressedAssets.mjs
9
11
  const SHA256_FILE_HASH_RE = /^[0-9a-f]{64}$/;
@@ -529,14 +531,14 @@ function modularInverse(value, modulus) {
529
531
  if (r > 1) throw new Error(`No modular inverse for ${value} mod ${modulus}`);
530
532
  return positiveMod(t, modulus);
531
533
  }
532
- function getRolloutShuffleParameters(bundleId) {
533
- let multiplier = positiveMod(hashString(`${bundleId}:multiplier`), 997);
534
+ function getRolloutShuffleParameters(releaseId) {
535
+ let multiplier = positiveMod(hashString(`${releaseId}:multiplier`), 997);
534
536
  if (multiplier === 0) multiplier = 1;
535
537
  while (gcd(multiplier, NUMERIC_COHORT_SIZE) !== 1) {
536
538
  multiplier = positiveMod(multiplier + 1, NUMERIC_COHORT_SIZE);
537
539
  if (multiplier === 0) multiplier = 1;
538
540
  }
539
- const offset = positiveMod(hashString(`${bundleId}:offset`), NUMERIC_COHORT_SIZE);
541
+ const offset = positiveMod(hashString(`${releaseId}:offset`), NUMERIC_COHORT_SIZE);
540
542
  return {
541
543
  multiplier,
542
544
  offset,
@@ -569,16 +571,16 @@ function isValidCohort(cohort) {
569
571
  const normalized = normalizeCohortValue(cohort);
570
572
  return isNumericCohort(normalized) || isCustomCohort(normalized);
571
573
  }
572
- function getNumericCohortRolloutPosition(bundleId, cohortValue) {
574
+ function getNumericCohortRolloutPosition(releaseId, cohortValue) {
573
575
  if (cohortValue < 1 || cohortValue > 1e3) throw new Error(`Invalid numeric cohort: ${cohortValue}`);
574
- const { offset, inverseMultiplier } = getRolloutShuffleParameters(bundleId);
576
+ const { offset, inverseMultiplier } = getRolloutShuffleParameters(releaseId);
575
577
  return positiveMod(inverseMultiplier * (cohortValue - 1 - offset), NUMERIC_COHORT_SIZE);
576
578
  }
577
- function getRolledOutNumericCohorts(bundleId, rolloutCohortCount) {
579
+ function getRolledOutNumericCohorts(releaseId, rolloutCohortCount) {
578
580
  const normalizedRolloutCount = normalizeRolloutCohortCount(rolloutCohortCount);
579
581
  if (normalizedRolloutCount <= 0) return [];
580
582
  if (normalizedRolloutCount >= 1e3) return Array.from({ length: NUMERIC_COHORT_SIZE }, (_, index) => index + 1);
581
- const { multiplier, offset } = getRolloutShuffleParameters(bundleId);
583
+ const { multiplier, offset } = getRolloutShuffleParameters(releaseId);
582
584
  return Array.from({ length: normalizedRolloutCount }, (_, position) => positiveMod(multiplier * position + offset, NUMERIC_COHORT_SIZE)).map((zeroBasedCohort) => zeroBasedCohort + 1).sort((left, right) => left - right);
583
585
  }
584
586
  const RELEASE_CATALOG_FALLBACK_POLICY = "BUILTIN_IF_ACTIVE_INELIGIBLE";
@@ -603,7 +605,8 @@ const releaseRowToRelease = (row) => ({
603
605
  operation: row.operation,
604
606
  sourceReleaseId: row.source_release_id,
605
607
  createdAtMs: row.created_at_ms,
606
- updatedAtMs: row.updated_at_ms
608
+ updatedAtMs: row.updated_at_ms,
609
+ label: row.label ?? null
607
610
  });
608
611
  const bundleToRow = (bundle) => {
609
612
  const metadata = bundleMetadataToRow(bundle.metadata);
@@ -1112,7 +1115,8 @@ function rangeToIntervals(range) {
1112
1115
  throw new ReleaseCatalogCompilationError("INVALID_TARGET_RANGE", `Invalid target app-version range: ${range}`);
1113
1116
  }
1114
1117
  }
1115
- function releaseDescriptor(release) {
1118
+ /** A release's descriptor; its label only when it has one and `labels`. */
1119
+ function releaseDescriptor(release, labels) {
1116
1120
  return {
1117
1121
  releaseId: release.id,
1118
1122
  kind: release.kind,
@@ -1120,7 +1124,8 @@ function releaseDescriptor(release) {
1120
1124
  rolloutCohortCount: release.rolloutCohortCount,
1121
1125
  targetCohorts: [...new Set(release.targetCohorts)].sort(),
1122
1126
  shouldForceUpdate: release.shouldForceUpdate,
1123
- message: release.message
1127
+ message: release.message,
1128
+ ...labels && typeof release.label === "number" ? { label: release.label } : {}
1124
1129
  };
1125
1130
  }
1126
1131
  function validateReleases(releases, strategy) {
@@ -1328,17 +1333,96 @@ function canonicalStringify(value) {
1328
1333
  const record = value;
1329
1334
  return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${canonicalStringify(record[key])}`).join(",")}}`;
1330
1335
  }
1336
+ const BOUND_SHAPE = {
1337
+ inclusive: null,
1338
+ version: null
1339
+ };
1340
+ /**
1341
+ * Every key this release's compiler writes in a catalog payload, where it
1342
+ * writes it: the envelope's, a segment's and its bounds', and a release
1343
+ * descriptor's. A key outside it was written by a later release.
1344
+ */
1345
+ const COMPILED_CATALOG_SHAPE = {
1346
+ fallbackPolicy: null,
1347
+ schemaVersion: null,
1348
+ strategy: null,
1349
+ releaseIndexes: null,
1350
+ rollbackReleaseIndexes: null,
1351
+ segments: {
1352
+ lower: BOUND_SHAPE,
1353
+ upper: BOUND_SHAPE,
1354
+ releaseIndexes: null,
1355
+ rollbackReleaseIndexes: null
1356
+ },
1357
+ releaseDescriptors: {
1358
+ releaseId: null,
1359
+ kind: null,
1360
+ bundleId: null,
1361
+ rolloutCohortCount: null,
1362
+ targetCohorts: null,
1363
+ shouldForceUpdate: null,
1364
+ message: null,
1365
+ label: null
1366
+ }
1367
+ };
1368
+ /**
1369
+ * A stored catalog payload as this release reads it: canonical, with the
1370
+ * keys a later release added left out, and whether it had any, a later
1371
+ * schema version included. Server core compares a catalog by the fields
1372
+ * its compiler writes, and refuses to rewrite one a later release wrote,
1373
+ * which would drop what that release added.
1374
+ */
1375
+ function readCompiledCatalogPayload(payload) {
1376
+ let fromLaterRelease = false;
1377
+ const known = (value, shape) => {
1378
+ if (Array.isArray(value)) return value.map((item) => known(item, shape));
1379
+ if (value === null || typeof value !== "object") return value;
1380
+ const entries = Object.entries(value).filter(([key]) => {
1381
+ if (Object.hasOwn(shape, key)) return true;
1382
+ fromLaterRelease = true;
1383
+ return false;
1384
+ });
1385
+ return Object.fromEntries(entries.map(([key, entry]) => {
1386
+ const inner = shape[key];
1387
+ return [key, inner === null ? entry : known(entry, inner)];
1388
+ }));
1389
+ };
1390
+ let parsed;
1391
+ try {
1392
+ parsed = JSON.parse(payload);
1393
+ } catch {
1394
+ parsed = null;
1395
+ }
1396
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return {
1397
+ canonicalPayload: payload,
1398
+ fromLaterRelease: false
1399
+ };
1400
+ if ("schemaVersion" in parsed && typeof parsed.schemaVersion === "number" && parsed.schemaVersion > 1) fromLaterRelease = true;
1401
+ return {
1402
+ canonicalPayload: canonicalStringify(known(parsed, COMPILED_CATALOG_SHAPE)),
1403
+ fromLaterRelease
1404
+ };
1405
+ }
1331
1406
  async function compileReleaseCatalog(input) {
1332
1407
  const releases = validateReleases(input.releases, input.strategy);
1333
1408
  const targetCohorts = new Set(releases.flatMap((release) => release.targetCohorts));
1334
1409
  if (targetCohorts.size > 512) throw new ReleaseCatalogCompilationError("DISTINCT_TARGET_COHORT_LIMIT", `Scope exceeds 512 distinct target cohorts`);
1335
1410
  const { envelope, retainedReleases } = input.strategy === "APP_VERSION" ? compileAppVersion(releases) : compileFingerprint(releases);
1336
- const payload = {
1337
- ...envelope,
1338
- releaseDescriptors: retainedReleases.map(releaseDescriptor)
1411
+ const compile = (labels) => {
1412
+ const payload = {
1413
+ ...envelope,
1414
+ releaseDescriptors: retainedReleases.map((release) => releaseDescriptor(release, labels))
1415
+ };
1416
+ const canonicalPayload = canonicalStringify(payload);
1417
+ return {
1418
+ payload,
1419
+ canonicalPayload,
1420
+ byteSize: new TextEncoder().encode(canonicalPayload).byteLength
1421
+ };
1339
1422
  };
1340
- const canonicalPayload = canonicalStringify(payload);
1341
- const byteSize = new TextEncoder().encode(canonicalPayload).byteLength;
1423
+ let compiled = compile(true);
1424
+ if (compiled.byteSize > 262144 && retainedReleases.some((release) => typeof release.label === "number")) compiled = compile(false);
1425
+ const { payload, canonicalPayload, byteSize } = compiled;
1342
1426
  if (byteSize > 262144) throw new ReleaseCatalogCompilationError("CATALOG_OVERSIZE", `Compiled Release catalog is ${byteSize} bytes; maximum is ${MAX_COMPILED_CATALOG_BYTES}`);
1343
1427
  return {
1344
1428
  byteSize,
@@ -1902,6 +1986,23 @@ const SETTINGS_TABLE = {
1902
1986
  /** The engine's storage-layout generation; it changes only with a migration. */
1903
1987
  const ENGINE_SCHEMA_KEY = "schema.engine";
1904
1988
  const CORE_SCHEMA_KEY = "schema.core";
1989
+ /** Compares dotted numeric versions, such as "1" and "1.2.0"; NaN when either is not one. */
1990
+ const compareVersions = (left, right) => {
1991
+ const parse = (version) => /^\d+(?:\.\d+)*$/u.test(version) ? version.split(".").map(Number) : [NaN];
1992
+ const [a, b] = [parse(left), parse(right)];
1993
+ if ([...a, ...b].some(Number.isNaN)) return NaN;
1994
+ for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
1995
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
1996
+ if (difference !== 0) return difference;
1997
+ }
1998
+ return 0;
1999
+ };
2000
+ /**
2001
+ * The `schema.core` a newer release recorded, which `hot-updater db migrate`
2002
+ * never moves back: the fix is to upgrade, not to migrate.
2003
+ */
2004
+ const newerCore = (settings) => settings.find(({ key, expected, found }) => key === CORE_SCHEMA_KEY && found !== null && compareVersions(found, expected) > 0);
2005
+ 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.`;
1905
2006
  const stored = ({ key, expected, found }) => `"${key}" is ${found === null ? "missing" : `"${found}"`}; expected "${expected}"`;
1906
2007
  /**
1907
2008
  * How to migrate a database the fence refused: doctor names the command for
@@ -1915,7 +2016,10 @@ const pluginOf = ({ key }) => key.startsWith("schema.") && key !== "schema.engin
1915
2016
  const listed = (items) => items.length < 2 ? items.join("") : `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`;
1916
2017
  const settingsMessage = (adapterName, settings) => `Hot Updater schema settings for ${adapterName} are not migrated: ${settings.map(stored).join(", and ")}. ${MIGRATE_SCHEMA_FIX}`;
1917
2018
  const pluginsMessage = (adapterName, plugins, settings, fix) => `The tables of ${plugins.length === 1 ? "plugin" : "plugins"} ${listed(plugins.map((id) => `"${id}"`))} are not migrated on ${adapterName}: schema ${settings.length === 1 ? "setting" : "settings"} ${settings.map(stored).join(", and ")}. ${fix}`;
1918
- /** The database needs `hot-updater db migrate`, or a new database; the handler answers 503. */
2019
+ /**
2020
+ * The database needs `hot-updater db migrate`, a new database, or a newer
2021
+ * Hot Updater; the handler answers 503.
2022
+ */
1919
2023
  var HotUpdaterSchemaMigrationRequiredError = class extends Error {
1920
2024
  adapterName;
1921
2025
  currentVersion;
@@ -1930,7 +2034,8 @@ var HotUpdaterSchemaMigrationRequiredError = class extends Error {
1930
2034
  constructor(adapterName, currentVersion, setting, options) {
1931
2035
  const settings = options?.settings ?? (setting === void 0 ? [] : [setting]);
1932
2036
  const plugins = settings.flatMap((mismatch) => pluginOf(mismatch) ?? []);
1933
- 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 });
2037
+ const newer = newerCore(settings);
2038
+ 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 });
1934
2039
  this.adapterName = adapterName;
1935
2040
  this.currentVersion = currentVersion;
1936
2041
  this.setting = setting;
@@ -2046,45 +2151,6 @@ const METER = Symbol.for("@hot-updater/plugin-core/read-meter");
2046
2151
  /** The meter `meterReads` gave `database`, if it did. */
2047
2152
  const readMeterOf = (database) => typeof database === "object" && database !== null ? database[METER] : void 0;
2048
2153
  //#endregion
2049
- //#region ../plugin-core/dist/engine/db/schemaSettings.mjs
2050
- const storedSettings = async (adapter, keys) => {
2051
- const rows = await readSettings(adapter, keys);
2052
- return new Map(keys.map((key, position) => [key, rows[position] ?? null]));
2053
- };
2054
- /** Writes the settings rows after every table exists. */
2055
- const writeSchemaSettings = async (adapter, adapterName, settings) => {
2056
- const stored = await storedSettings(adapter, Object.keys(settings));
2057
- const ops = Object.entries(settings).flatMap(([key, value]) => {
2058
- const row = stored.get(key);
2059
- if (row === null || row === void 0) return [{
2060
- type: "insert",
2061
- table: SETTINGS_TABLE,
2062
- row: {
2063
- key,
2064
- value,
2065
- _v: 0
2066
- }
2067
- }];
2068
- if (row.value === value) return [];
2069
- return [{
2070
- type: "patch",
2071
- table: SETTINGS_TABLE,
2072
- key: [key],
2073
- set: { value },
2074
- guard: { v: Number(row._v) },
2075
- previous: row
2076
- }];
2077
- });
2078
- if (ops.length === 0) return;
2079
- if (!(await adapter.write(ops)).ok) throw new Error(`${adapterName}: the schema settings changed during the migration; run it again.`);
2080
- };
2081
- /** Creates or updates every table, then writes the settings rows last. */
2082
- const migrateSchema = async (adapter, adapterName, tables, settings) => {
2083
- if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
2084
- await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
2085
- await writeSchemaSettings(adapter, adapterName, settings);
2086
- };
2087
- //#endregion
2088
2154
  //#region ../plugin-core/dist/engine/core/schema.mjs
2089
2155
  /** A channel's id is `channel:` and its name's channel key, so ids share channel_key's bound. */
2090
2156
  const CHANNEL_ID = {
@@ -2100,9 +2166,13 @@ const CHANNEL_ID = {
2100
2166
  * applies it to managed databases an earlier release created. The official
2101
2167
  * plugins' `schemaVersion`s follow the same rule. A bump only adds tables:
2102
2168
  * every database's migrator creates missing tables and then records the
2103
- * version, and none of them changes an existing table, so changing one
2104
- * needs a migration step of its own first. The schema fence answers 503 on
2105
- * a database whose row differs, until it runs.
2169
+ * version, and none of them changes an existing table's columns, so changing
2170
+ * one needs a migration step of its own first. An index added to an existing
2171
+ * table is listed in `LATE_INDEXES`, and a column in `LATE_COLUMNS`. The schema fence answers 503 on
2172
+ * a database whose row differs, until it runs. Before a version is released,
2173
+ * its tables change in place in its own migration, and a database one of its
2174
+ * prereleases migrated takes the same change by hand: the fence compares this
2175
+ * row, not columns, so nothing reports it.
2106
2176
  */
2107
2177
  const HOT_UPDATER_SCHEMA_VERSION = "1.2.0";
2108
2178
  const bundles = defineTable({
@@ -2251,7 +2321,11 @@ const releases = defineTable({
2251
2321
  }
2252
2322
  },
2253
2323
  created_at_ms: { type: "integer" },
2254
- updated_at_ms: { type: "integer" }
2324
+ updated_at_ms: { type: "integer" },
2325
+ label: {
2326
+ type: "integer",
2327
+ required: false
2328
+ }
2255
2329
  }, {
2256
2330
  key: ["id"],
2257
2331
  indexes: {
@@ -2284,9 +2358,72 @@ const releases = defineTable({
2284
2358
  all: {
2285
2359
  eq: [],
2286
2360
  sort: ["id"]
2361
+ },
2362
+ scopes: {
2363
+ eq: [],
2364
+ sort: ["scope_key"]
2365
+ },
2366
+ byLabel: {
2367
+ eq: [
2368
+ "channel_id",
2369
+ "platform",
2370
+ "label"
2371
+ ],
2372
+ sort: [],
2373
+ unique: true
2287
2374
  }
2288
2375
  }
2289
2376
  });
2377
+ /**
2378
+ * Indexes declared on a table that a released schema's servers write: a
2379
+ * store that keeps index items of its own (`migrations.fillIndex`) lacks
2380
+ * them for rows written before, and for rows such a server still writes
2381
+ * after the migration, since its schema fence keeps a check that passed.
2382
+ * Each migration writes the missing items, and `db migrate` on a database
2383
+ * whose settings match looks for them. `releases.scopes` arrived in 1.2.0;
2384
+ * 1.1.x servers write releases without it.
2385
+ */
2386
+ const LATE_INDEXES = [{
2387
+ table: "releases",
2388
+ index: "scopes"
2389
+ }];
2390
+ /**
2391
+ * Columns added to a table that a released schema created: a migrator whose
2392
+ * store has columns adds each one missing from an existing table, with
2393
+ * `ALTER TABLE … ADD COLUMN`, before it creates the table's indexes, and
2394
+ * `db migrate` on a database whose settings match still looks for them,
2395
+ * since a database a prerelease migrated records the same settings. Each
2396
+ * is optional, so rows written before it, and rows a server of the earlier
2397
+ * release still writes, read as null. `releases.label` arrived in 1.2.0.
2398
+ */
2399
+ const LATE_COLUMNS = [{
2400
+ table: "releases",
2401
+ column: "label"
2402
+ }];
2403
+ /**
2404
+ * One counter per sequence: `releases/<platform>/<channel ID>` holds the
2405
+ * last label that channel and platform's releases took. A deploy or a
2406
+ * promote reads it and writes the next value in the transaction that writes
2407
+ * the release, so two writers never take one label. `is_filled` is true once
2408
+ * every release of the sequence written before labels has one, in ID order;
2409
+ * until then a writer fills them first. Deleting a channel deletes its
2410
+ * counters, so a channel created again with the name starts at 1.
2411
+ */
2412
+ const labelSequences = defineTable({
2413
+ id: {
2414
+ type: "string",
2415
+ maxLength: 1440,
2416
+ ascii: true
2417
+ },
2418
+ last_label: { type: "integer" },
2419
+ is_filled: { type: "boolean" }
2420
+ }, {
2421
+ key: ["id"],
2422
+ indexes: { all: {
2423
+ eq: [],
2424
+ sort: ["id"]
2425
+ } }
2426
+ });
2290
2427
  /** One compiled catalog per scope; the update check reads exactly this row. */
2291
2428
  const releaseCatalogs = defineTable({
2292
2429
  scope_key: {
@@ -2356,7 +2493,10 @@ const channels = defineTable({
2356
2493
  /**
2357
2494
  * The native builds `native-build android` and `native-build ios` track, newest first
2358
2495
  * in each scope: a platform, a channel, and the fingerprint or app version
2359
- * the build compiled in. `min_bundle_id` names the build's built-in bundle,
2496
+ * the build compiled in. A sandbox build's scope has no channel: its app ID,
2497
+ * URL scheme, artifact kind and distribution in its place, so pull requests
2498
+ * reuse it across channels, while `channel_id` still names the channel it
2499
+ * embeds. `min_bundle_id` names the build's built-in bundle,
2360
2500
  * a `bundles` row no release publishes. Its references keep no counters, so
2361
2501
  * adding this table changes no existing one; a channel with builds is
2362
2502
  * refused deletion through `byChannel`. `build_key` is the native build key
@@ -2366,6 +2506,27 @@ const channels = defineTable({
2366
2506
  * or `versionCode`. `submitted_to`, `submitted_at_ms` and
2367
2507
  * `submitted_version` record the store track a build went to, when, and
2368
2508
  * the store's label of the build; they stay null for a build no store took.
2509
+ * `is_store_build` is true on the build a person or a job says the store
2510
+ * sells, and false on every other: deploys patch from it over the scope's
2511
+ * newest build. The engine copies the scope key into `store_build_scope_key`
2512
+ * for that build alone, so `byStoreBuild` holds one entry per scope at most,
2513
+ * on every store, while any number of a scope's builds hold none.
2514
+ * `is_sandbox` is true on a sandbox build, set from its artifact when it
2515
+ * registers and never changed, and `sandbox_url_scheme` is the URL scheme its artifact registers,
2516
+ * which its preview links open; null on any other build, and on a sandbox
2517
+ * build registered before the column, which registered the derived one.
2518
+ * `export_method` is how an `.ipa` was exported, read from its profile when
2519
+ * it registers and never changed; null on any other artifact, on an `.ipa`
2520
+ * whose profile couldn't be read, and on one registered before the column.
2521
+ * `native_app_version` is the app version the artifact itself reports, its
2522
+ * `CFBundleShortVersionString` or `versionName`, read from the artifact when
2523
+ * it registers and never changed, whatever the update strategy; `app_version`
2524
+ * stays the version OTAs target, null on a fingerprint build. It is null
2525
+ * when the artifact's can't be read, and on a build registered before the
2526
+ * column.
2527
+ * Boolean columns follow one rule: `is_*` for a fact about the row or
2528
+ * `should_*` for an instruction to the client, never null; a unique index over
2529
+ * the rows where one is true keys a derived slot, not the boolean.
2369
2530
  */
2370
2531
  const nativeBuilds = defineTable({
2371
2532
  id: {
@@ -2442,9 +2603,34 @@ const nativeBuilds = defineTable({
2442
2603
  type: "string",
2443
2604
  maxLength: 255,
2444
2605
  required: false
2606
+ },
2607
+ is_store_build: { type: "boolean" },
2608
+ is_sandbox: { type: "boolean" },
2609
+ sandbox_url_scheme: {
2610
+ type: "string",
2611
+ maxLength: 255,
2612
+ ascii: true,
2613
+ required: false
2614
+ },
2615
+ export_method: {
2616
+ type: "string",
2617
+ maxLength: 16,
2618
+ required: false
2619
+ },
2620
+ native_app_version: {
2621
+ type: "string",
2622
+ required: false
2445
2623
  }
2446
2624
  }, {
2447
2625
  key: ["id"],
2626
+ derived: {
2627
+ /** The scope this build is the store build of; null on every other. */
2628
+ store_build_scope_key: {
2629
+ type: "string",
2630
+ maxLength: 2048,
2631
+ ascii: true,
2632
+ compute: (row) => row.is_store_build ? row.scope_key : null
2633
+ } },
2448
2634
  indexes: {
2449
2635
  byScope: {
2450
2636
  eq: ["scope_key"],
@@ -2454,6 +2640,15 @@ const nativeBuilds = defineTable({
2454
2640
  eq: ["scope_key", "build_key"],
2455
2641
  sort: ["id"]
2456
2642
  },
2643
+ byScopeKind: {
2644
+ eq: ["scope_key", "artifact_kind"],
2645
+ sort: ["id"]
2646
+ },
2647
+ byStoreBuild: {
2648
+ eq: ["store_build_scope_key"],
2649
+ sort: [],
2650
+ unique: true
2651
+ },
2457
2652
  byChannel: {
2458
2653
  eq: ["channel_id"],
2459
2654
  sort: ["id"],
@@ -2465,6 +2660,119 @@ const nativeBuilds = defineTable({
2465
2660
  }
2466
2661
  }
2467
2662
  });
2663
+ /**
2664
+ * The iPhones a team asks to install ad hoc builds on. A row decides what the
2665
+ * CLI registers with Apple, not what an export includes: Xcode's automatic ad
2666
+ * hoc profile lists every device the Apple account has enabled. `status` is
2667
+ * `pending` until someone approves it, `approved` until a build or
2668
+ * `native-build devices add` registers it with Apple, then `registered`;
2669
+ * declining or removing one deletes its row. `udid` is the UDID in lower case.
2670
+ * `apple_issuer_id` is the App Store Connect issuer whose key registered it,
2671
+ * set once: a build signed by another account never registers these rows.
2672
+ * `apple_error` is Apple's refusal of the device, or why it stopped counting
2673
+ * it, cleared by the next success. `build_id` is the newest native build whose
2674
+ * .ipa the CLI checked lists it; deleting that build never touches the row.
2675
+ * It holds personal data: a UDID, a name, and the emails of who asked and who
2676
+ * approved, null for the CLI.
2677
+ */
2678
+ const iosDevices = defineTable({
2679
+ id: {
2680
+ type: "string",
2681
+ maxLength: 36
2682
+ },
2683
+ udid: {
2684
+ type: "string",
2685
+ maxLength: 40,
2686
+ ascii: true,
2687
+ unique: true
2688
+ },
2689
+ name: {
2690
+ type: "string",
2691
+ maxLength: 100
2692
+ },
2693
+ status: {
2694
+ type: "string",
2695
+ maxLength: 16
2696
+ },
2697
+ requested_by: {
2698
+ type: "string",
2699
+ maxLength: 320,
2700
+ required: false
2701
+ },
2702
+ created_at_ms: { type: "integer" },
2703
+ approved_by: {
2704
+ type: "string",
2705
+ maxLength: 320,
2706
+ required: false
2707
+ },
2708
+ approved_at_ms: {
2709
+ type: "integer",
2710
+ required: false
2711
+ },
2712
+ registered_at_ms: {
2713
+ type: "integer",
2714
+ required: false
2715
+ },
2716
+ apple_issuer_id: {
2717
+ type: "string",
2718
+ maxLength: 64,
2719
+ ascii: true,
2720
+ required: false
2721
+ },
2722
+ apple_error: {
2723
+ type: "string",
2724
+ maxLength: 512,
2725
+ required: false
2726
+ },
2727
+ build_id: {
2728
+ type: "string",
2729
+ maxLength: 36,
2730
+ required: false
2731
+ }
2732
+ }, {
2733
+ key: ["id"],
2734
+ indexes: {
2735
+ byStatus: {
2736
+ eq: ["status"],
2737
+ sort: ["id"]
2738
+ },
2739
+ byRegistration: {
2740
+ eq: [],
2741
+ sort: ["registered_at_ms"]
2742
+ },
2743
+ all: {
2744
+ eq: [],
2745
+ sort: ["id"]
2746
+ }
2747
+ }
2748
+ });
2749
+ /**
2750
+ * The Apple account the iOS device registry belongs to: one row, keyed
2751
+ * `registry`, holding the App Store Connect issuer that first registered a
2752
+ * device. A build claims it before it sends Apple anything, and its key makes
2753
+ * the claim atomic on every store, so two builds of two accounts can't both
2754
+ * spend a slot; another account's build then registers nothing. Removing
2755
+ * devices never releases it.
2756
+ */
2757
+ const iosDeviceAccount = defineTable({
2758
+ id: {
2759
+ type: "string",
2760
+ maxLength: 16,
2761
+ ascii: true
2762
+ },
2763
+ apple_issuer_id: {
2764
+ type: "string",
2765
+ maxLength: 64,
2766
+ ascii: true
2767
+ },
2768
+ claimed_at_ms: { type: "integer" }
2769
+ }, {
2770
+ key: ["id"],
2771
+ indexes: { all: {
2772
+ eq: [],
2773
+ sort: ["id"]
2774
+ } }
2775
+ });
2468
2776
  /** Core's module: always installed, never a plugin. */
2469
2777
  const coreModule = {
2470
2778
  id: "core",
@@ -2485,7 +2793,10 @@ const coreModule = {
2485
2793
  sort: []
2486
2794
  } }
2487
2795
  }),
2488
- native_builds: nativeBuilds
2796
+ native_builds: nativeBuilds,
2797
+ ios_devices: iosDevices,
2798
+ ios_device_account: iosDeviceAccount,
2799
+ label_sequences: labelSequences
2489
2800
  }
2490
2801
  };
2491
2802
  //#endregion
@@ -2511,6 +2822,129 @@ const refuseV0Database = (adapterName, stored) => {
2511
2822
  if (typeof version !== "string" || stored.has("schema.engine")) return;
2512
2823
  throw new HotUpdaterSchemaMigrationRequiredError(adapterName, version);
2513
2824
  };
2825
+ /**
2826
+ * The settings whose versions only move forward when a `ToolingTarget` names
2827
+ * none. `schema.engine` is a storage layout, not a release: a store refuses
2828
+ * another layout itself, and doctor reports it as not migratable.
2829
+ */
2830
+ const DEFAULT_ORDERED_SETTINGS = ["schema.core"];
2831
+ /**
2832
+ * Refuses a database a newer release migrated, one whose `schema.core` is
2833
+ * newer than this release's: writing this release's settings would move the
2834
+ * schema back, and every server of the newer release would answer 503. Only
2835
+ * `ordered` settings are compared, `schema.core` among them, and the message
2836
+ * lists each that is newer. An official plugin's
2837
+ * newer version alone is no newer release: Insights recorded "1.2.0" in
2838
+ * 1.0.0-rc.23 and rc.24, then went back to "1.0.0" with the same tables.
2839
+ */
2840
+ const refuseNewerSchema = (adapterName, stored, settings, ordered = DEFAULT_ORDERED_SETTINGS) => {
2841
+ const newer = ordered.flatMap((key) => {
2842
+ const found = stored.get(key);
2843
+ const expected = settings[key];
2844
+ return typeof found === "string" && expected !== void 0 && compareVersions(found, expected) > 0 ? [{
2845
+ key,
2846
+ found,
2847
+ expected
2848
+ }] : [];
2849
+ });
2850
+ const core = newer.find(({ key }) => key === "schema.core");
2851
+ if (core === void 0) return;
2852
+ 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.`);
2853
+ };
2854
+ /** The settings rows a migration changes, each with its stored value. */
2855
+ const settingsOperation = (stored, changed) => ({
2856
+ type: "custom",
2857
+ description: `Record ${changed.map(([key, value]) => {
2858
+ const found = stored.get(key);
2859
+ return typeof found === "string" ? `${key} ${found} → ${value}` : `${key} ${value}`;
2860
+ }).join(", ")}`
2861
+ });
2862
+ //#endregion
2863
+ //#region ../plugin-core/dist/engine/db/schemaSettings.mjs
2864
+ const storedSettings = async (adapter, keys) => {
2865
+ const rows = await readSettings(adapter, keys);
2866
+ return new Map(keys.map((key, position) => [key, rows[position] ?? null]));
2867
+ };
2868
+ /**
2869
+ * Writes the settings rows after every table exists, and refuses a database
2870
+ * whose `ordered` settings a newer release recorded.
2871
+ */
2872
+ const writeSchemaSettings = async (adapter, adapterName, settings, ordered) => {
2873
+ const stored = await storedSettings(adapter, Object.keys(settings));
2874
+ refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
2875
+ const ops = Object.entries(settings).flatMap(([key, value]) => {
2876
+ const row = stored.get(key);
2877
+ if (row === null || row === void 0) return [{
2878
+ type: "insert",
2879
+ table: SETTINGS_TABLE,
2880
+ row: {
2881
+ key,
2882
+ value,
2883
+ _v: 0
2884
+ }
2885
+ }];
2886
+ if (row.value === value) return [];
2887
+ return [{
2888
+ type: "patch",
2889
+ table: SETTINGS_TABLE,
2890
+ key: [key],
2891
+ set: { value },
2892
+ guard: { v: Number(row._v) },
2893
+ previous: row
2894
+ }];
2895
+ });
2896
+ if (ops.length === 0) return;
2897
+ if (!(await adapter.write(ops)).ok) throw new Error(`${adapterName}: the schema settings changed during the migration; run it again.`);
2898
+ };
2899
+ /**
2900
+ * The `LATE_INDEXES` among `tables` whose items some rows lack, as
2901
+ * `<table>.<index>`, written unless `dryRun`: none on a store without
2902
+ * `migrations.fillIndex`.
2903
+ */
2904
+ const fillLateIndexes = async (adapter, tables, { dryRun = false } = {}) => {
2905
+ const fillIndex = adapter.migrations?.fillIndex;
2906
+ if (fillIndex === void 0) return [];
2907
+ const lacking = [];
2908
+ for (const { table: name, index } of LATE_INDEXES) {
2909
+ const table = tables.find((candidate) => candidate.name === name);
2910
+ if (table === void 0) continue;
2911
+ if (await fillIndex(table, index, { dryRun }) > 0) lacking.push(`${name}.${index}`);
2912
+ }
2913
+ return lacking;
2914
+ };
2915
+ /**
2916
+ * The `LATE_COLUMNS` among `tables` that an existing table lacks, as
2917
+ * `<table>.<column>`, added unless `dryRun`: none on a store without
2918
+ * `migrations.addColumns`, or for a table not created yet.
2919
+ */
2920
+ const addLateColumns = async (adapter, tables, { dryRun = false } = {}) => {
2921
+ const addColumns = adapter.migrations?.addColumns;
2922
+ if (addColumns === void 0) return [];
2923
+ const lacking = [];
2924
+ for (const table of tables) {
2925
+ const columns = LATE_COLUMNS.filter(({ table: name }) => name === table.name).map(({ column }) => column);
2926
+ if (columns.length === 0) continue;
2927
+ const added = await addColumns(table, columns, { dryRun });
2928
+ lacking.push(...added.map((column) => `${table.name}.${column}`));
2929
+ }
2930
+ return lacking;
2931
+ };
2932
+ /**
2933
+ * Adds the late columns existing tables lack, creates or updates every
2934
+ * table, writes the late indexes' missing items, then writes the settings
2935
+ * rows last. A database a newer release migrated is
2936
+ * refused before anything is written: its settings are read first, and a
2937
+ * store without them yet, whose read fails, has none to refuse.
2938
+ */
2939
+ const migrateSchema = async (adapter, adapterName, tables, settings, ordered) => {
2940
+ if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
2941
+ const stored = await storedSettings(adapter, Object.keys(settings)).catch(() => void 0);
2942
+ if (stored !== void 0) refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
2943
+ await addLateColumns(adapter, tables);
2944
+ await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
2945
+ await fillLateIndexes(adapter, tables);
2946
+ await writeSchemaSettings(adapter, adapterName, settings, ordered);
2947
+ };
2514
2948
  //#endregion
2515
2949
  //#region ../plugin-core/dist/engine/database/cursor.mjs
2516
2950
  const encoder$1 = new TextEncoder();
@@ -2674,18 +3108,17 @@ const LEASE_TABLE = "aggregate_lease";
2674
3108
  const LEASE = { id: "compaction" };
2675
3109
  /** How long a compaction holds the lease before another process may take it. */
2676
3110
  const LEASE_MS = 3e4;
2677
- /**
2678
- * Default windows: log mode compacts every 60 seconds, since reads compact
2679
- * first; memory mode flushes every 15, since its window is what a crash
2680
- * loses.
2681
- */
2682
- const WINDOW_MS$1 = {
2683
- log: 6e4,
2684
- memory: 15e3
2685
- };
3111
+ /** A commit compacts once this has passed since the last compaction. */
3112
+ const WINDOW_MS$1 = 6e4;
2686
3113
  /** Log rows a compaction reads from each log table for one group. */
2687
3114
  const LOG_PAGE = 200;
2688
3115
  /**
3116
+ * How old a log row this process can't apply must be before its reads step
3117
+ * past it: older than any transaction still committing, between servers
3118
+ * whose clocks agree this closely.
3119
+ */
3120
+ const SKIP_AFTER_MS = 3e5;
3121
+ /**
2689
3122
  * Groups one compaction applies: after a commit, so the request that runs
2690
3123
  * it waits for one group; before a read; and on flush.
2691
3124
  */
@@ -2696,8 +3129,6 @@ const GROUPS = {
2696
3129
  };
2697
3130
  /** Tries per write after a conflict or a transient error. */
2698
3131
  const ATTEMPTS = 5;
2699
- /** Aggregate rows a memory buffer holds before a commit waits for a flush. */
2700
- const MAX_BUFFERED = 1e4;
2701
3132
  const log = defineTable({
2702
3133
  id: {
2703
3134
  type: "string",
@@ -2747,7 +3178,7 @@ const valuesOf = ({ deltas, sketches }) => ({
2747
3178
  /**
2748
3179
  * Merges `values` into the change for `key`'s identity as `tx.aggregate`
2749
3180
  * does: deltas add up and sketches merge. One constant `shardBy` keys each
2750
- * identity to one entry; the write picks the shard.
3181
+ * identity to one entry; `compile` writes it to shard 0.
2751
3182
  */
2752
3183
  const merge = (into, model, key, values) => recordAggregate(into, model, Object.fromEntries(shapeOf(model).key.map((field, at) => [field, key[at]])), values, "");
2753
3184
  const mergeAll = (into, changes) => {
@@ -2781,7 +3212,7 @@ const increment = ({ model, deltas }, key) => Object.values(deltas).some((delta)
2781
3212
  /**
2782
3213
  * The guarded write that merges `change` into `current`: insert, patch, or
2783
3214
  * delete at zero. Unlike a transaction's, a gauge may go below zero here: a
2784
- * shard row holds one writer's net changes, and reads sum every shard.
3215
+ * group can hold a loss without the gain before it, and reads sum every shard.
2785
3216
  */
2786
3217
  const rewrite = (change, key, current) => {
2787
3218
  const { model } = change;
@@ -2818,26 +3249,44 @@ const rewrite = (change, key, current) => {
2818
3249
  previous: current
2819
3250
  };
2820
3251
  };
3252
+ /** A shard row's place in what `readCurrent` read. */
3253
+ const rowId = (model, key) => JSON.stringify([model.table.name, key]);
3254
+ /** The shard key each change writes: shard 0, since one compaction runs at a time. */
3255
+ const keysOf = (changes) => changes.map(({ key }) => [...key.slice(0, -1), 0]);
2821
3256
  /**
2822
- * The write for each change on its shard: a blind increment that creates
2823
- * the row for counters, and a guarded rewrite for gauges and sketches, whose
2824
- * rows are read in one batch per table.
3257
+ * The current rows of the changes that rewrite theirs (gauges and sketches),
3258
+ * each once, in one batch per table.
2825
3259
  */
2826
- const compile = async (adapter, changes, shard) => {
2827
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
3260
+ const readCurrent = async (adapter, changes) => {
3261
+ const keys = keysOf(changes);
2828
3262
  const reads = /* @__PURE__ */ new Map();
2829
3263
  changes.forEach((change, at) => {
2830
- if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
3264
+ if (!rewrites(change)) return;
3265
+ const wanted = reads.get(change.model) ?? /* @__PURE__ */ new Map();
3266
+ wanted.set(rowId(change.model, keys[at]), keys[at]);
3267
+ reads.set(change.model, wanted);
2831
3268
  });
2832
3269
  const current = /* @__PURE__ */ new Map();
2833
- await Promise.all([...reads].map(async ([model, positions]) => {
2834
- const rows = await adapter.get(model.table, positions.map((at) => keys[at]));
2835
- positions.forEach((at, index) => current.set(at, rows[index] ?? null));
3270
+ await Promise.all([...reads].map(async ([model, wanted]) => {
3271
+ const keys = [...wanted.values()];
3272
+ const rows = await adapter.get(model.table, keys);
3273
+ keys.forEach((key, at) => {
3274
+ current.set(rowId(model, key), rows[at] ?? null);
3275
+ });
2836
3276
  }));
2837
- return changes.map((change, at) => current.has(at) ? rewrite(change, keys[at], current.get(at)) : increment(change, keys[at]));
3277
+ return current;
3278
+ };
3279
+ /**
3280
+ * The write for each change: a blind increment that creates the row for
3281
+ * counters, and a guarded rewrite for gauges and sketches, over the rows
3282
+ * `current` read.
3283
+ */
3284
+ const build = (changes, current) => {
3285
+ const keys = keysOf(changes);
3286
+ return changes.map((change, at) => rewrites(change) ? rewrite(change, keys[at], current.get(rowId(change.model, keys[at])) ?? null) : increment(change, keys[at]));
2838
3287
  };
2839
3288
  const isOp = (op) => op !== void 0;
2840
- const sleep = (attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random()));
3289
+ const sleep$2 = (attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random()));
2841
3290
  /** Runs of one character, where shorter: a sparse sketch packs into a few. */
2842
3291
  const pack = (text) => {
2843
3292
  const runs = (text.match(/(.)\1*/gsu) ?? []).flatMap((run) => [run[0], run.length]);
@@ -2878,14 +3327,13 @@ const encode$1 = async (changes) => {
2878
3327
  return zipped !== void 0 && zipped.length < json.length ? `z${zipped}` : json;
2879
3328
  };
2880
3329
  /**
2881
- * Batches changes to aggregates declared `batched`. A transaction records
2882
- * them without writing their rows; once it commits, "memory" mode keeps
2883
- * them in this process until its timer flushes them, and "log" mode has
2884
- * written them as one log row in the same atomic write, which a compaction
2885
- * later merges into the aggregates and deletes, atomically again, so each
2886
- * applies exactly once. One lease row keeps compactions one at a time.
3330
+ * Batches changes to aggregates declared `batched`. A transaction writes
3331
+ * them as one log row in its own atomic write, in place of their rows; a
3332
+ * compaction later merges log rows into the aggregates and deletes them,
3333
+ * atomically again, so each applies exactly once. One lease row keeps
3334
+ * compactions one at a time.
2887
3335
  */
2888
- const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS$1[mode] }, now }) => {
3336
+ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs = WINDOW_MS$1 }, now }) => {
2889
3337
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
2890
3338
  const holder = crypto.randomUUID().replaceAll("-", "");
2891
3339
  const table = (name) => schema.models.get(name).table;
@@ -2913,72 +3361,20 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
2913
3361
  }
2914
3362
  return changes;
2915
3363
  };
2916
- /**
2917
- * Writes changes in atomic chunks within `fits`, and returns the ones it
2918
- * could not apply. A write whose outcome is unknown is dropped, never
2919
- * resent, so no change applies twice.
2920
- */
2921
- const apply = async (changes, shard) => {
2922
- let rest = changes;
2923
- let ops = [];
2924
- let read = true;
2925
- for (let failures = 0; rest.length > 0 && failures < ATTEMPTS;) try {
2926
- if (read) ops = await compile(adapter, rest, shard);
2927
- let size = rest.length;
2928
- const chunk = () => ops.slice(0, size).filter(isOp);
2929
- while (size > 1 && !adapter.fits(chunk())) size = Math.ceil(size / 2);
2930
- let result = { ok: true };
2931
- if (chunk().length > 0) result = await adapter.write(chunk()).catch((error) => {
2932
- warn("flush")(error);
2933
- return { ok: true };
2934
- });
2935
- read = !result.ok && !("retry" in result);
2936
- if (result.ok) {
2937
- rest = rest.slice(size);
2938
- ops = ops.slice(size);
2939
- failures = 0;
2940
- } else {
2941
- failures += 1;
2942
- if (!read) await sleep(failures);
2943
- }
2944
- } catch (error) {
2945
- warn("flush")(error);
2946
- return rest;
2947
- }
2948
- return rest;
2949
- };
2950
- let buffer = /* @__PURE__ */ new Map();
2951
- let timer;
2952
- let flushing;
2953
- const shards = /* @__PURE__ */ new Map();
2954
- /** Each process writes its own shard, so flushes of two processes rarely meet. */
2955
- const processShard = (model) => {
2956
- if (!shards.has(model)) shards.set(model, Math.floor(Math.random() * shapeOf(model).shards));
2957
- return shards.get(model);
2958
- };
2959
- const schedule = () => {
2960
- if (timer !== void 0 || buffer.size === 0) return;
2961
- timer = setTimeout(() => {
2962
- timer = void 0;
2963
- flushBuffer();
2964
- }, windowMs);
2965
- timer.unref?.();
2966
- };
2967
- /** Never rejects: what it cannot apply goes back into the buffer. */
2968
- const flushBuffer = () => flushing ??= (async () => {
2969
- clearTimeout(timer);
2970
- timer = void 0;
2971
- const pending = [...buffer.values()];
2972
- buffer = /* @__PURE__ */ new Map();
2973
- mergeAll(buffer, await apply(pending, processShard));
2974
- })().catch(warn("flush")).finally(() => {
2975
- flushing = void 0;
2976
- schedule();
2977
- });
2978
3364
  let nextDue = 0;
2979
3365
  let compacting;
2980
3366
  /** Log rows this process read, by `[log table's index, id]`, for the deletes after a group. */
2981
3367
  const known = /* @__PURE__ */ new Map();
3368
+ /**
3369
+ * Each log table's last row of a run at its head that this process can't
3370
+ * apply (it names an aggregate or metric this schema lacks), whose reads
3371
+ * start past it. The rows wait for a process that can apply them, and a
3372
+ * restart reads them again.
3373
+ */
3374
+ const skipped = LOG_TABLES.map(() => void 0);
3375
+ const past = (shard) => skipped[shard] === void 0 ? {} : { range: { gt: skipped[shard] } };
3376
+ /** When a log row's transaction stamped its ID. */
3377
+ const stampOf = (id) => Number.parseInt(id.slice(0, 9), 36);
2982
3378
  const idOf = (shard, id) => JSON.stringify([shard, id]);
2983
3379
  /** The lease row as stored once `set` is written over it. */
2984
3380
  const leaseOp = (held, set) => {
@@ -3039,7 +3435,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3039
3435
  const result = await adapter.write(ops);
3040
3436
  if (result.ok) return true;
3041
3437
  if (!("retry" in result)) return false;
3042
- await sleep(failures);
3438
+ await sleep$2(failures);
3043
3439
  }
3044
3440
  return false;
3045
3441
  };
@@ -3094,14 +3490,22 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3094
3490
  logs: (await Promise.all(LOG_TABLES.map(async (name, shard) => {
3095
3491
  const page = await engine.reads.findMany(name, {
3096
3492
  index: "oldest",
3097
- limit: LOG_PAGE
3493
+ limit: LOG_PAGE,
3494
+ ...past(shard)
3098
3495
  });
3099
3496
  more ||= page.next !== void 0;
3100
- return (await Promise.all(page.rows.map(async (row) => ({
3497
+ const decoded = await Promise.all(page.rows.map(async (row) => ({
3101
3498
  shard,
3102
3499
  row,
3103
3500
  changes: await decode(String(row.changes))
3104
- })))).flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
3501
+ })));
3502
+ const settled = now() - SKIP_AFTER_MS;
3503
+ for (const { row, changes } of decoded) {
3504
+ const id = String(row.id);
3505
+ if (changes !== void 0 || stampOf(id) >= settled) break;
3506
+ skipped[shard] = id;
3507
+ }
3508
+ return decoded.flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
3105
3509
  ...entry,
3106
3510
  changes
3107
3511
  }]);
@@ -3109,7 +3513,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3109
3513
  more
3110
3514
  };
3111
3515
  };
3112
- const rowsFor = async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp);
3113
3516
  /**
3114
3517
  * Applies the oldest pending log rows whose merged changes fit in one
3115
3518
  * atomic write with the lease, which lists them as applied; the rows are
@@ -3118,12 +3521,14 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3118
3521
  * log rows it applied whole, or undefined when a conflict stopped it.
3119
3522
  */
3120
3523
  const applyGroup = async (held, logs) => {
3524
+ const current = await readCurrent(adapter, logs.flatMap((entry) => [...entry.changes.values()]));
3525
+ const rowsFor = (changes) => build(changes, current).filter(isOp);
3121
3526
  for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
3122
3527
  const batch = logs.slice(0, count);
3123
3528
  const changes = mergeAll(/* @__PURE__ */ new Map(), batch.flatMap((entry) => [...entry.changes.values()]));
3124
3529
  const applied = batch.map(({ shard, row }) => [shard, row.id]);
3125
3530
  const lease = leaseOp(held, { applied: JSON.stringify(applied) });
3126
- const ops = [...await rowsFor([...changes.values()]), lease.op];
3531
+ const ops = [...rowsFor([...changes.values()]), lease.op];
3127
3532
  if (!adapter.fits(ops)) continue;
3128
3533
  for (const { shard, row } of batch) known.set(idOf(shard, row.id), row);
3129
3534
  return await commit(ops) ? {
@@ -3145,7 +3550,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3145
3550
  };
3146
3551
  const lease = leaseOp(held, {});
3147
3552
  const ops = [
3148
- ...await rowsFor(entries.slice(0, take)),
3553
+ ...rowsFor(entries.slice(0, take)),
3149
3554
  kept,
3150
3555
  lease.op
3151
3556
  ];
@@ -3166,11 +3571,12 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3166
3571
  if (held === void 0) return;
3167
3572
  let pending = true;
3168
3573
  let clear = false;
3574
+ let carried;
3169
3575
  try {
3170
3576
  for (let group = 0;; group += 1) {
3171
3577
  clear = await deleteApplied(held);
3172
3578
  if (!clear || !pending || group === groups) break;
3173
- const { logs, more } = await readLogs();
3579
+ const { logs, more } = carried ?? await readLogs();
3174
3580
  if (logs.length === 0) {
3175
3581
  pending = false;
3176
3582
  break;
@@ -3178,6 +3584,11 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3178
3584
  const applied = await applyGroup(held, logs);
3179
3585
  if (applied === void 0) break;
3180
3586
  [held, clear] = [applied.held, false];
3587
+ const rest = applied.count === 0 ? [] : logs.slice(applied.count);
3588
+ carried = rest.length > 0 ? {
3589
+ logs: rest,
3590
+ more
3591
+ } : void 0;
3181
3592
  pending = more || applied.count < logs.length;
3182
3593
  }
3183
3594
  } finally {
@@ -3197,26 +3608,13 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3197
3608
  });
3198
3609
  let checking;
3199
3610
  /** Whether any log row waits; reads at once share one check. */
3200
- const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name) => engine.reads.findMany(name, {
3611
+ const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name, shard) => engine.reads.findMany(name, {
3201
3612
  index: "oldest",
3202
- limit: 1
3613
+ limit: 1,
3614
+ ...past(shard)
3203
3615
  }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
3204
3616
  checking = void 0;
3205
3617
  });
3206
- /** Takes a committed transaction's changes; never rejects, since the transaction already committed. */
3207
- const committed = async (changes) => {
3208
- if (mode === "log") {
3209
- if (now() >= nextDue) await compact(false, GROUPS.commit);
3210
- return;
3211
- }
3212
- mergeAll(buffer, changes.values());
3213
- schedule();
3214
- if (buffer.size >= MAX_BUFFERED) await flushBuffer();
3215
- };
3216
- const flush = async () => {
3217
- await flushBuffer();
3218
- if (mode === "log" && await hasPending()) await compact(true, GROUPS.flush);
3219
- };
3220
3618
  return {
3221
3619
  async transaction(fn) {
3222
3620
  let changes = /* @__PURE__ */ new Map();
@@ -3242,7 +3640,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3242
3640
  aggregate
3243
3641
  });
3244
3642
  if (failure) throw failure.error;
3245
- if (mode === "log" && attempt.size > 0) {
3643
+ if (attempt.size > 0) {
3246
3644
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
3247
3645
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
3248
3646
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -3256,24 +3654,18 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3256
3654
  open = false;
3257
3655
  }
3258
3656
  });
3259
- if (changes.size > 0) await committed(changes);
3657
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
3260
3658
  return result;
3261
3659
  },
3262
3660
  async beforeRead(name) {
3263
3661
  if (!isBatched(schema.models.get(name))) return;
3264
- if (buffer.size > 0 || flushing !== void 0) await flushBuffer();
3265
- if (mode === "log") {
3266
- if (await hasPending().catch((error) => {
3267
- warn("read")(error);
3268
- return false;
3269
- })) await compact(true, GROUPS.read);
3270
- }
3662
+ if (await hasPending().catch((error) => {
3663
+ warn("read")(error);
3664
+ return false;
3665
+ })) await compact(true, GROUPS.read);
3271
3666
  },
3272
- flush,
3273
- async dispose() {
3274
- clearTimeout(timer);
3275
- timer = void 0;
3276
- await flush();
3667
+ async flush() {
3668
+ if (await hasPending()) await compact(true, GROUPS.flush);
3277
3669
  }
3278
3670
  };
3279
3671
  };
@@ -3415,7 +3807,8 @@ const fieldProblems = (definition, add) => {
3415
3807
  else if (field.required === false) add(`key field "${name}" is nullable`);
3416
3808
  else if (field.type === "json") add(`key field "${name}" is json`);
3417
3809
  }
3418
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
3810
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
3811
+ for (const [name, { type, maxLength, ascii }] of bounded) {
3419
3812
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
3420
3813
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
3421
3814
  }
@@ -3532,11 +3925,13 @@ const resolveSchema = (modules) => {
3532
3925
  ...maxLength === void 0 ? {} : { maxLength },
3533
3926
  ...ascii ? { ascii } : {}
3534
3927
  }));
3535
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
3928
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
3536
3929
  name: field,
3537
3930
  type,
3538
3931
  nullable: true,
3539
- ...multi ? { multi } : {}
3932
+ ...multi ? { multi } : {},
3933
+ ...maxLength === void 0 ? {} : { maxLength },
3934
+ ...ascii ? { ascii } : {}
3540
3935
  });
3541
3936
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
3542
3937
  name: metric,
@@ -3572,30 +3967,57 @@ const resolveSchema = (modules) => {
3572
3967
  * `hot-updater db migrate` for a store whose adapter creates its own tables
3573
3968
  * (MongoDB and the key-value stores): the tables and indexes, then the
3574
3969
  * settings rows, applied when a setting is missing or different, and refused
3575
- * on a v0 database.
3970
+ * on a v0 database or one a newer release migrated.
3576
3971
  */
3577
3972
  const createEngineMigrator = (options) => {
3578
3973
  const getVersion = async () => storedSchemaVersion(await options.readSettings());
3579
3974
  const makeResult = async (migrate = {}) => {
3580
3975
  const stored = await options.readSettings();
3581
3976
  refuseV0Database(options.adapterName, stored);
3582
- if (Object.entries(options.settings).every(([key, value]) => stored.get(key) === value)) return getEmptyMigrationResult();
3583
- return {
3584
- operations: [...options.schema.tables.map((table) => ({
3585
- type: "create-table",
3586
- value: {
3587
- ormName: table.name,
3588
- columns: Object.fromEntries(table.columns.map((column) => [column.name, {
3589
- ormName: column.name,
3590
- type: column.type
3591
- }]))
3977
+ refuseNewerSchema(options.adapterName, stored, options.settings, options.ordered);
3978
+ const changed = Object.entries(options.settings).filter(([key, value]) => stored.get(key) !== value);
3979
+ if (changed.length === 0) {
3980
+ const columns = await addLateColumns(options.adapter, options.schema.tables, { dryRun: true });
3981
+ const lacking = await fillLateIndexes(options.adapter, options.schema.tables, { dryRun: true });
3982
+ if (columns.length === 0 && lacking.length === 0) return getEmptyMigrationResult();
3983
+ return {
3984
+ operations: [
3985
+ ...columns.map((column) => ({
3986
+ type: "custom",
3987
+ description: `Add column: ${column}`
3988
+ })),
3989
+ ...columns.length === 0 ? [] : [{
3990
+ type: "custom",
3991
+ description: "Create the tables and indexes the database lacks"
3992
+ }],
3993
+ ...lacking.length === 0 ? [] : [{
3994
+ type: "custom",
3995
+ description: `Write the index items rows lack: ${lacking.join(", ")}`
3996
+ }]
3997
+ ],
3998
+ execute: async () => {
3999
+ if (columns.length > 0) {
4000
+ await addLateColumns(options.adapter, options.schema.tables);
4001
+ await options.adapter.migrations.apply([...options.schema.tables, SETTINGS_TABLE]);
4002
+ }
4003
+ await fillLateIndexes(options.adapter, options.schema.tables);
3592
4004
  }
3593
- })), ...migrate.updateSettings === false ? [] : [{
3594
- type: "custom",
3595
- description: `Write the schema settings: ${Object.keys(options.settings).join(", ")}`
3596
- }]],
3597
- execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings)
3598
- };
4005
+ };
4006
+ }
4007
+ return {
4008
+ operations: [
4009
+ ...(await addLateColumns(options.adapter, options.schema.tables, { dryRun: true }).catch(() => [])).map((column) => ({
4010
+ type: "custom",
4011
+ description: `Add column: ${column}`
4012
+ })),
4013
+ {
4014
+ type: "custom",
4015
+ description: "Create the tables and indexes the database lacks"
4016
+ },
4017
+ ...migrate.updateSettings === false ? [] : [settingsOperation(stored, changed)]
4018
+ ],
4019
+ execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings, options.ordered)
4020
+ };
3599
4021
  };
3600
4022
  return {
3601
4023
  getVersion,
@@ -3625,7 +4047,8 @@ const coreSettings = {
3625
4047
  /** What `hot-updater db` creates for a server without plugins. */
3626
4048
  const coreTarget = {
3627
4049
  schema: coreSchema,
3628
- settings: coreSettings
4050
+ settings: coreSettings,
4051
+ ordered: ["schema.core"]
3629
4052
  };
3630
4053
  resolveSchema([aggregateBatchingModule]).tables;
3631
4054
  /** Each plugin's `schema.<id>` settings row. */
@@ -3645,11 +4068,12 @@ const pluginModule = ({ id, schema, namespace }) => ({
3645
4068
  */
3646
4069
  const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBatching, retry, readSettings: readStored }) => {
3647
4070
  const fenced = withSchemaFence(adapter, name, coreSettings);
3648
- const createMigrator = ({ schema, settings } = coreTarget) => createEngineMigrator({
4071
+ const createMigrator = ({ schema, settings, ordered } = coreTarget) => createEngineMigrator({
3649
4072
  adapterName: name,
3650
4073
  adapter,
3651
4074
  schema,
3652
4075
  settings,
4076
+ ordered,
3653
4077
  readSettings: readStored ?? (async () => {
3654
4078
  const rows = await readSettings(adapter, Object.keys(settings)).catch((error) => {
3655
4079
  if (isMissingSchemaError(error)) return [];
@@ -3673,6 +4097,12 @@ const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBa
3673
4097
  /** A row this attempt read changed while it ran; the attempt reruns. */
3674
4098
  var StaleReadError = class extends Error {};
3675
4099
  const idOf = (table, key) => JSON.stringify([table, key]);
4100
+ /** The aggregate rows a write changes, at the versions it read them. */
4101
+ const versionsOf = (ops) => JSON.stringify(ops.map((op) => op.type === "insert" ? [op.table.name, rowKey(op.table, op.row)] : [
4102
+ op.table.name,
4103
+ op.key,
4104
+ "guard" in op ? op.guard?.v : void 0
4105
+ ]));
3676
4106
  const versionOf = (row) => Number(row["_v"]);
3677
4107
  const isKeyed = (value) => value !== null && value !== void 0;
3678
4108
  const misuse = (table, message) => new DatabaseTransactionError(`${table}: ${message}`);
@@ -4017,7 +4447,10 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4017
4447
  assertOutsideTransaction();
4018
4448
  let run;
4019
4449
  let negative;
4020
- for (let round = 0; round < attempts; round += 1) {
4450
+ let failures = 0;
4451
+ let lost;
4452
+ let busy = false;
4453
+ for (let round = 0;; round += 1) {
4021
4454
  const delay = round && Math.min(maxDelayMs, baseDelayMs * 2 ** (round - 1));
4022
4455
  if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay / 2 + Math.random() * (delay / 2)));
4023
4456
  run ??= await attempt(fn).catch((error) => {
@@ -4026,6 +4459,9 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4026
4459
  });
4027
4460
  if (run === void 0) {
4028
4461
  onRetry?.("rerun", round + 1);
4462
+ lost = void 0;
4463
+ busy = false;
4464
+ if ((failures += 1) >= attempts) break;
4029
4465
  continue;
4030
4466
  }
4031
4467
  let aggregates;
@@ -4035,9 +4471,16 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4035
4471
  if (!(error instanceof NegativeGaugeError)) throw error;
4036
4472
  negative = error;
4037
4473
  onRetry?.("rerun", round + 1);
4474
+ busy = false;
4038
4475
  run = void 0;
4476
+ lost = void 0;
4477
+ if ((failures += 1) >= attempts) break;
4039
4478
  continue;
4040
4479
  }
4480
+ const versions = versionsOf(aggregates);
4481
+ if (lost !== void 0 && versions !== lost) failures -= 1;
4482
+ lost = void 0;
4483
+ if (failures >= attempts) break;
4041
4484
  const ops = [...run.ops, ...aggregates];
4042
4485
  if (ops.length <= 1 && ops.every(({ type }) => type === "check")) return run.result;
4043
4486
  if (!adapter.fits(ops)) throw new DatabaseConstraintError("too_large", ops[0].table.name);
@@ -4049,16 +4492,21 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4049
4492
  }
4050
4493
  if (outcome.ok) return run.result;
4051
4494
  const failed = "failedOp" in outcome ? outcome.failedOp : void 0;
4495
+ busy = failed === void 0;
4052
4496
  if (failed === void 0 || failed >= run.ops.length) {
4053
4497
  onRetry?.("resend", round + 1);
4498
+ failures += 1;
4499
+ if (failed !== void 0) lost = versions;
4500
+ else if (failures >= attempts) break;
4054
4501
  continue;
4055
4502
  }
4056
4503
  const reason = await classify(ops[failed], run.read);
4057
4504
  if (reason) throw new DatabaseConstraintError(reason, ops[failed].table.name);
4058
4505
  onRetry?.("rerun", round + 1);
4059
4506
  run = void 0;
4507
+ if ((failures += 1) >= attempts) break;
4060
4508
  }
4061
- throw negative ?? new DatabaseConflictError(`The transaction conflicted ${attempts} times.`);
4509
+ 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.`);
4062
4510
  } };
4063
4511
  };
4064
4512
  //#endregion
@@ -4302,13 +4750,10 @@ const createDatabaseEngine = ({ batching, now = Date.now, meter, ...options }) =
4302
4750
  };
4303
4751
  return {
4304
4752
  ...engine,
4305
- /** Applies batched aggregate changes still pending: this process's buffer and the log. */
4753
+ /** Applies the batched aggregate changes still in the log. */
4306
4754
  flush: async () => {
4307
4755
  await batches?.flush();
4308
4756
  },
4309
- dispose: async () => {
4310
- await batches?.dispose();
4311
- },
4312
4757
  database(module) {
4313
4758
  const name = (model) => module.namespace ? `${module.namespace}_${model}` : model;
4314
4759
  return {
@@ -4389,8 +4834,7 @@ const createEngine = (database, { plugins = [], now = Date.now } = {}) => {
4389
4834
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
4390
4835
  return engine.database(module);
4391
4836
  },
4392
- flush: () => engine.flush(),
4393
- dispose: () => engine.dispose()
4837
+ flush: () => engine.flush()
4394
4838
  };
4395
4839
  };
4396
4840
  //#endregion
@@ -4460,10 +4904,10 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
4460
4904
  const at = row && expiresAt(table, row);
4461
4905
  return at === void 0 ? {} : { expiresAt: at };
4462
4906
  };
4463
- /** Every index and unique item a row has, by address. */
4464
- const itemsOf = (layout, row) => {
4907
+ /** Every index and unique item a row has, by address: in `indexes`, if given. */
4908
+ const itemsOf = (layout, row, indexes = layout.indexed) => {
4465
4909
  const items = /* @__PURE__ */ new Map();
4466
- for (const index of row === null ? [] : layout.indexed) for (const eq of indexEntries(layout.table, index, row)) {
4910
+ for (const index of row === null ? [] : indexes) for (const eq of indexEntries(layout.table, index, row)) {
4467
4911
  const pk = partition(layout, index, eq);
4468
4912
  const sk = index.unique ? ONLY : encodeKvKey(indexOrderTuple(layout.table, index, row)) || ONLY;
4469
4913
  items.set(JSON.stringify([pk, sk]), {
@@ -4618,6 +5062,79 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
4618
5062
  lte: lt.endsWith(SEPARATOR) ? lt.slice(0, -1) : lt
4619
5063
  };
4620
5064
  };
5065
+ /** One row's check and its item puts in `index`, copies of the row as it is. */
5066
+ const fillOps = (layout, index, row) => [{
5067
+ type: "check",
5068
+ key: rowItem(layout, rowKey(layout.table, row)),
5069
+ condition: { v: Number(row["_v"]) }
5070
+ }, ...[...itemsOf(layout, row, [index]).values()].map(({ key }) => ({
5071
+ type: "put",
5072
+ key,
5073
+ value: copyOf(layout, row),
5074
+ ...stamp(layout.table, row)
5075
+ }))];
5076
+ /**
5077
+ * Writes one row's items in `index`, checking the row's `_v` in the same
5078
+ * write: a row that changed is read again, and a deleted one needs none.
5079
+ */
5080
+ const fillRow = async (layout, index, first) => {
5081
+ const key = rowItem(layout, rowKey(layout.table, first));
5082
+ let row = first;
5083
+ for (let attempt = 0; row !== null; attempt += 1) {
5084
+ if (attempt === 8) throw new Error(`${layout.table.name}.${index.name}: a row kept changing while its index items were written; run the migration again.`);
5085
+ if ((await store.write(fillOps(layout, index, row))).ok) return;
5086
+ [row] = await store.get([key]);
5087
+ }
5088
+ };
5089
+ /**
5090
+ * Finds the rows that lack an item in `index` and, unless `dryRun`, writes
5091
+ * them, as many rows per atomic write as the store takes. It reads every
5092
+ * row and its items, page by page.
5093
+ */
5094
+ const fillIndex = async (table, name, { dryRun = false } = {}) => {
5095
+ const layout = layoutOf(table);
5096
+ const index = layout.indexed.find((candidate) => candidate.name === name);
5097
+ if (index === void 0) return 0;
5098
+ if (index.unique) throw new DatabaseAdapterContractError(`${table.name}.${name} is unique: its items can't be written for rows stored before it, since two of them may hold one value.`);
5099
+ const { items: most, bytes } = store.limits;
5100
+ let lacking = 0;
5101
+ for (let after;;) {
5102
+ const page = await store.query({
5103
+ pk: layout.rows,
5104
+ order: "asc",
5105
+ limit: 100,
5106
+ after
5107
+ });
5108
+ const rows = page.items.map(({ value }) => value);
5109
+ const keys = rows.map((row) => [...itemsOf(layout, row, [index]).values()].map(({ key }) => key));
5110
+ const wanted = keys.flat();
5111
+ const found = wanted.length === 0 ? [] : await store.get(wanted);
5112
+ let at = 0;
5113
+ const missing = rows.filter((_, position) => {
5114
+ return found.slice(at, at += keys[position].length).some((item) => item === null);
5115
+ });
5116
+ lacking += missing.length;
5117
+ if (!dryRun) {
5118
+ let chunk = [];
5119
+ let ops = [];
5120
+ const flush = async () => {
5121
+ if (ops.length > 0 && !(await store.write(ops)).ok) for (const row of chunk) await fillRow(layout, index, row);
5122
+ chunk = [];
5123
+ ops = [];
5124
+ };
5125
+ for (const row of missing) {
5126
+ const next = fillOps(layout, index, row);
5127
+ const size = (list) => list.reduce((sum, op) => sum + encoder.encode(op.key.pk + op.key.sk + JSON.stringify(op.type === "put" ? op.value : null)).length, 0);
5128
+ if (chunk.length > 0 && (ops.length + next.length > most || size(ops) + size(next) > bytes)) await flush();
5129
+ chunk.push(row);
5130
+ ops.push(...next);
5131
+ }
5132
+ await flush();
5133
+ }
5134
+ if (!page.more || page.items.length === 0) return lacking;
5135
+ after = page.items.at(-1).sk;
5136
+ }
5137
+ };
4621
5138
  return {
4622
5139
  id: store.id,
4623
5140
  fits(ops) {
@@ -4677,13 +5194,16 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
4677
5194
  const layout = layoutOf(table);
4678
5195
  return store.deleteConsumed(rows.flatMap((row) => [rowItem(layout, rowKey(table, row)), ...[...itemsOf(layout, row).values()].map(({ key }) => key)]));
4679
5196
  } },
4680
- migrations: { apply: async () => store.migrations?.apply() },
5197
+ migrations: {
5198
+ apply: async () => store.migrations?.apply(),
5199
+ fillIndex
5200
+ },
4681
5201
  ...store.dispose === void 0 ? {} : { dispose: () => store.dispose() }
4682
5202
  };
4683
5203
  };
4684
5204
  //#endregion
4685
5205
  //#region ../../packages/server/dist/version.mjs
4686
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.6";
5206
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.61";
4687
5207
  //#endregion
4688
5208
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
4689
5209
  /**
@@ -4843,10 +5363,15 @@ const releaseCatalogScopeKeyOf = (input) => input.strategy === "APP_VERSION" ? c
4843
5363
  platform: input.platform,
4844
5364
  strategy: "FINGERPRINT"
4845
5365
  });
4846
- /** Projects a stored catalog row for one update check; null when the row is not this scope's. */
4847
- const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
4848
- 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;
4849
- const compiled = parseCompiledCatalog(row.payload, input.strategy);
5366
+ const parseReleaseCatalogRow = ({ payload, ...row }) => ({
5367
+ row,
5368
+ compiled: parseCompiledCatalog(payload, row.strategy)
5369
+ });
5370
+ /** Projects a parsed catalog row for one update check; null when the row is not this scope's. */
5371
+ const projectParsedReleaseCatalogRow = (parsed, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
5372
+ if (parsed === null) return null;
5373
+ const { row, compiled } = parsed;
5374
+ 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;
4850
5375
  const appVersion = input.strategy === "APP_VERSION" ? input.appVersion : void 0;
4851
5376
  return {
4852
5377
  catalogId: row.catalog_id,
@@ -4859,6 +5384,8 @@ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyO
4859
5384
  scopeKey
4860
5385
  };
4861
5386
  };
5387
+ /** Projects a stored catalog row for one update check; null when the row is not this scope's. */
5388
+ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => projectParsedReleaseCatalogRow(row === null ? null : parseReleaseCatalogRow(row), input, scopeKey);
4862
5389
  //#endregion
4863
5390
  //#region ../../packages/server/dist/db/updateArtifacts.mjs
4864
5391
  const HBC_ASSET_PATH_RE = /\.bundle$/;
@@ -5475,9 +6002,9 @@ const baseBundleIdsOf = (row, range, bundleId, limit) => {
5475
6002
  };
5476
6003
  //#endregion
5477
6004
  //#region ../../packages/server/dist/core/reads.mjs
5478
- const PAGE$3 = 500;
5479
- const pick$1 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
5480
- const toBundleRow = pick$1([
6005
+ const PAGE$5 = 500;
6006
+ const pick$2 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
6007
+ const toBundleRow = pick$2([
5481
6008
  "id",
5482
6009
  "platform",
5483
6010
  "git_commit_hash",
@@ -5486,7 +6013,7 @@ const toBundleRow = pick$1([
5486
6013
  "manifest_file_hash",
5487
6014
  "asset_base_storage_uri"
5488
6015
  ]);
5489
- const toPatchRow = pick$1([
6016
+ const toPatchRow = pick$2([
5490
6017
  "id",
5491
6018
  "bundle_id",
5492
6019
  "base_bundle_id",
@@ -5496,7 +6023,7 @@ const toPatchRow = pick$1([
5496
6023
  "byte_size",
5497
6024
  "order_index"
5498
6025
  ]);
5499
- const toReleaseRow = pick$1([
6026
+ const pickReleaseRow = pick$2([
5500
6027
  "id",
5501
6028
  "revision",
5502
6029
  "scope_key",
@@ -5517,7 +6044,14 @@ const toReleaseRow = pick$1([
5517
6044
  "created_at_ms",
5518
6045
  "updated_at_ms"
5519
6046
  ]);
5520
- const toCatalogRow = pick$1([
6047
+ /** A release row; `label` null where the store holds none, as before the column. */
6048
+ const toReleaseRow = (row) => {
6049
+ return {
6050
+ ...pickReleaseRow(row),
6051
+ label: typeof row.label === "number" ? row.label : null
6052
+ };
6053
+ };
6054
+ const toCatalogRow = pick$2([
5521
6055
  "scope_key",
5522
6056
  "catalog_id",
5523
6057
  "strategy",
@@ -5532,7 +6066,7 @@ const toCatalogRow = pick$1([
5532
6066
  "is_tombstone",
5533
6067
  "updated_at_ms"
5534
6068
  ]);
5535
- const toChannelRow = pick$1(["id", "name"]);
6069
+ const toChannelRow = pick$2(["id", "name"]);
5536
6070
  /** Every page of one read, in order. */
5537
6071
  const drain$1 = async (read) => {
5538
6072
  const rows = [];
@@ -5545,8 +6079,16 @@ const drain$1 = async (read) => {
5545
6079
  return rows;
5546
6080
  };
5547
6081
  /** A keyset page's range: the keys strictly after `after`, in `order`. */
5548
- const after = (input) => input.after === void 0 ? {} : { range: (input.order ?? "asc") === "asc" ? { gt: input.after } : { lt: input.after } };
5549
- /** Core's reads, each through one declared index or key. */
6082
+ /** A keyset read's range on its index's order: past `after`, up to `through`. */
6083
+ const after = (input) => {
6084
+ const asc = (input.order ?? "asc") === "asc";
6085
+ const range = {
6086
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
6087
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
6088
+ };
6089
+ return Object.keys(range).length === 0 ? {} : { range };
6090
+ };
6091
+ /** Core's reads, each through one declared index or key; plugins get `CoreReads`. */
5550
6092
  const createCoreReads = (db, storage) => {
5551
6093
  /** A bundle row's patches, exactly as many as its reference counter holds. */
5552
6094
  const detail = async (row) => {
@@ -5557,7 +6099,7 @@ const createCoreReads = (db, storage) => {
5557
6099
  const page = await db.findMany("bundle_patches", {
5558
6100
  index: "byBundle",
5559
6101
  where: { bundle_id: row.id },
5560
- limit: Math.min(count - patches.length, PAGE$3),
6102
+ limit: Math.min(count - patches.length, PAGE$5),
5561
6103
  ...cursor === void 0 ? {} : { cursor }
5562
6104
  });
5563
6105
  patches.push(...page.rows.map(toPatchRow));
@@ -5667,6 +6209,23 @@ const createCoreReads = (db, storage) => {
5667
6209
  const row = await db.findOne("releases", { id });
5668
6210
  return row === null ? null : toReleaseRow(row);
5669
6211
  },
6212
+ /**
6213
+ * The release a label names: its unique index, then the row itself,
6214
+ * since a key-value store keeps an index copy a server of an earlier
6215
+ * release may have left behind when it changed or deleted the row.
6216
+ */
6217
+ async getReleaseByLabel({ channel, platform, label }) {
6218
+ const found = await db.findOne("releases", {
6219
+ channel_id: `channel:${encodeChannelKey(channel)}`,
6220
+ platform,
6221
+ label
6222
+ });
6223
+ if (found === null) return null;
6224
+ const row = await db.findOne("releases", { id: found.id });
6225
+ if (row === null) return null;
6226
+ const release = toReleaseRow(row);
6227
+ return release.label === label && release.platform === platform ? release : null;
6228
+ },
5670
6229
  /** One page of releases through the index its filter names. */
5671
6230
  async listReleases(input) {
5672
6231
  const { filter } = input;
@@ -5734,15 +6293,47 @@ const createCoreReads = (db, storage) => {
5734
6293
  ...after(input)
5735
6294
  })).rows.map(toCatalogRow);
5736
6295
  },
5737
- /** Every channel, by name. */
5738
- async listChannels() {
6296
+ /**
6297
+ * Up to `limit` scope keys that have releases, ascending after `after`:
6298
+ * one limit-1 seek of the `scopes` index past each scope, so the reads
6299
+ * grow with the scopes, not with their releases.
6300
+ */
6301
+ async listReleaseScopeKeys(input) {
6302
+ const scopeKeys = [];
6303
+ for (let last = input.after ?? ""; scopeKeys.length < input.limit;) {
6304
+ const { rows } = await db.findMany("releases", {
6305
+ index: "scopes",
6306
+ where: {},
6307
+ limit: 1,
6308
+ range: { gt: last }
6309
+ });
6310
+ if (rows[0] === void 0) break;
6311
+ last = rows[0].scope_key;
6312
+ scopeKeys.push(last);
6313
+ }
6314
+ return scopeKeys;
6315
+ },
6316
+ /** Every channel by name; with `input`, one keyset page of them. */
6317
+ async listChannels(input) {
6318
+ if (input !== void 0) return (await db.findMany("channels", {
6319
+ index: "all",
6320
+ where: {},
6321
+ order: input.order ?? "asc",
6322
+ limit: input.limit,
6323
+ ...after(input)
6324
+ })).rows.map(toChannelRow);
5739
6325
  return (await drain$1((page) => db.findMany("channels", {
5740
6326
  index: "all",
5741
6327
  where: {},
5742
- limit: PAGE$3,
6328
+ limit: PAGE$5,
5743
6329
  ...page
5744
6330
  }))).map(toChannelRow);
5745
6331
  },
6332
+ async getChannels(ids) {
6333
+ const unique = [...new Set(ids)];
6334
+ if (unique.length === 0) return [];
6335
+ return (await db.findByKeys("channels", unique.map((id) => ({ id })))).flatMap((row) => row ? [toChannelRow(row)] : []);
6336
+ },
5746
6337
  async findChannelByName(name) {
5747
6338
  const row = await db.findOne("channels", { name });
5748
6339
  return row === null ? null : toChannelRow(row);
@@ -5750,8 +6341,635 @@ const createCoreReads = (db, storage) => {
5750
6341
  };
5751
6342
  };
5752
6343
  //#endregion
6344
+ //#region ../../packages/server/dist/core/iosDevices.mjs
6345
+ /**
6346
+ * A device's UDID: 40 hex digits, or 8 and 16 joined by a hyphen. The same
6347
+ * rule as `normalizeIosUdid` of `@hot-updater/protocol/native-artifact`,
6348
+ * implemented here so the server's runtime never loads the artifact readers.
6349
+ */
6350
+ const UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
6351
+ /** The form the registry stores and compares a UDID in, or null for text that isn't one. */
6352
+ const normalizeIosUdid = (value) => {
6353
+ const trimmed = value.trim();
6354
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
6355
+ };
6356
+ /** `ios_devices.name`'s bound in core's schema. */
6357
+ const NAME_MAX_LENGTH = 100;
6358
+ /** `ios_devices.requested_by` and `approved_by`'s bound: an email address. */
6359
+ const EMAIL_MAX_LENGTH = 320;
6360
+ /** `ios_devices.apple_issuer_id`'s bound. */
6361
+ const ISSUER_MAX_LENGTH = 64;
6362
+ /** The one row of `ios_device_account`. */
6363
+ const ACCOUNT_ROW = "registry";
6364
+ /** `ios_devices.apple_error`'s bound. */
6365
+ const ERROR_MAX_LENGTH = 512;
6366
+ const STATUSES = [
6367
+ "pending",
6368
+ "approved",
6369
+ "registered"
6370
+ ];
6371
+ const OUTCOMES = [
6372
+ "registered",
6373
+ "refused",
6374
+ "disabled",
6375
+ "missing"
6376
+ ];
6377
+ /** The `apple_error` of a device Apple has disabled. */
6378
+ const IOS_DEVICE_DISABLED_ERROR = "Disabled in the Apple account.";
6379
+ /** The `apple_error` of a registered device Apple no longer lists. */
6380
+ const IOS_DEVICE_MISSING_ERROR = "Gone from the Apple account. Approve it again to register it.";
6381
+ /** A device or registry request core cannot store: the caller's input. */
6382
+ var IosDeviceInputError = class extends TypeError {
6383
+ name = "IosDeviceInputError";
6384
+ };
6385
+ const pick$1 = (row) => ({
6386
+ id: row.id,
6387
+ udid: row.udid,
6388
+ name: row.name,
6389
+ status: row.status,
6390
+ requested_by: row.requested_by ?? null,
6391
+ created_at_ms: row.created_at_ms,
6392
+ approved_by: row.approved_by ?? null,
6393
+ approved_at_ms: row.approved_at_ms ?? null,
6394
+ registered_at_ms: row.registered_at_ms ?? null,
6395
+ apple_issuer_id: row.apple_issuer_id ?? null,
6396
+ apple_error: row.apple_error ?? null,
6397
+ build_id: row.build_id ?? null
6398
+ });
6399
+ const udidOf = (udid) => {
6400
+ const key = typeof udid === "string" ? normalizeIosUdid(udid) : null;
6401
+ if (key === null) throw new IosDeviceInputError("Invalid iOS device: udid must be 40 hex digits, or 8 and 16 joined by a hyphen.");
6402
+ return key;
6403
+ };
6404
+ const nameOf = (name) => {
6405
+ const trimmed = typeof name === "string" ? name.trim() : "";
6406
+ if (trimmed.length === 0 || trimmed.length > NAME_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: name must be 1 to ${NAME_MAX_LENGTH} characters.`);
6407
+ return trimmed;
6408
+ };
6409
+ /** An email, lower-cased, or null for the CLI. */
6410
+ const personOf = (value, field) => {
6411
+ if (value === null) return null;
6412
+ const email = typeof value === "string" ? value.trim().toLowerCase() : "";
6413
+ 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.`);
6414
+ return email;
6415
+ };
6416
+ /** Apple's words, on one line and within the column's bound. */
6417
+ const errorText = (text) => {
6418
+ const line = text.replace(/\s+/gu, " ").trim();
6419
+ return line.length > ERROR_MAX_LENGTH ? `${line.slice(0, 511)}…` : line;
6420
+ };
6421
+ /**
6422
+ * The iOS device registry: the iPhones and iPads a team asked to install ad hoc
6423
+ * builds on. The Console writes requests and approvals, and the CLI what Apple
6424
+ * said, each over the row it read.
6425
+ */
6426
+ const createIosDeviceApi = (db, { now = Date.now } = {}) => {
6427
+ const findIosDevice = async (udid) => {
6428
+ const key = normalizeIosUdid(udid);
6429
+ if (key === null) return null;
6430
+ const row = await db.findOne("ios_devices", { udid: key });
6431
+ return row === null ? null : pick$1(row);
6432
+ };
6433
+ /**
6434
+ * The issuer of the registry's earliest registration among its rows, by
6435
+ * when and then by ID, or null when no row names one: read only while the
6436
+ * registry has no account yet, in one read of its first registration. A
6437
+ * row names an issuer exactly when it has a registration time: both are
6438
+ * set by its first registration and never cleared.
6439
+ */
6440
+ const accountOfRows = async () => {
6441
+ const { rows } = await db.findMany("ios_devices", {
6442
+ index: "byRegistration",
6443
+ where: {},
6444
+ order: "asc",
6445
+ limit: 1,
6446
+ range: { gte: 0 }
6447
+ });
6448
+ return (rows[0] === void 0 ? null : pick$1(rows[0]))?.apple_issuer_id ?? null;
6449
+ };
6450
+ return {
6451
+ async listIosDevices(input) {
6452
+ if (input.status !== void 0 && !STATUSES.includes(input.status)) throw new IosDeviceInputError(`Invalid iOS device status: ${String(input.status)}. Expected ${STATUSES.join(", ")}.`);
6453
+ const page = {
6454
+ order: input.order ?? "asc",
6455
+ limit: input.limit,
6456
+ ...after(input)
6457
+ };
6458
+ const { rows } = input.status === void 0 ? await db.findMany("ios_devices", {
6459
+ index: "all",
6460
+ where: {},
6461
+ ...page
6462
+ }) : await db.findMany("ios_devices", {
6463
+ index: "byStatus",
6464
+ where: { status: input.status },
6465
+ ...page
6466
+ });
6467
+ return rows.map(pick$1);
6468
+ },
6469
+ findIosDevice,
6470
+ async requestIosDevice(input) {
6471
+ const udid = udidOf(input.udid);
6472
+ const name = nameOf(input.name);
6473
+ const requestedBy = personOf(input.requestedBy, "requestedBy");
6474
+ const existing = await db.findOne("ios_devices", { udid });
6475
+ if (existing !== null) return {
6476
+ device: pick$1(existing),
6477
+ created: false
6478
+ };
6479
+ const device = {
6480
+ id: createUUIDv7(),
6481
+ udid,
6482
+ name,
6483
+ status: "pending",
6484
+ requested_by: requestedBy,
6485
+ created_at_ms: now(),
6486
+ approved_by: null,
6487
+ approved_at_ms: null,
6488
+ registered_at_ms: null,
6489
+ apple_issuer_id: null,
6490
+ apple_error: null,
6491
+ build_id: null
6492
+ };
6493
+ try {
6494
+ await db.transaction(async (tx) => {
6495
+ tx.create("ios_devices", device);
6496
+ });
6497
+ } catch (error) {
6498
+ if (error instanceof DatabaseConstraintError && error.reason === "unique") {
6499
+ const winner = await db.findOne("ios_devices", { udid });
6500
+ if (winner !== null) return {
6501
+ device: pick$1(winner),
6502
+ created: false
6503
+ };
6504
+ }
6505
+ throw error;
6506
+ }
6507
+ return {
6508
+ device,
6509
+ created: true
6510
+ };
6511
+ },
6512
+ async approveIosDevice(id, input) {
6513
+ const name = input.name === void 0 ? void 0 : nameOf(input.name);
6514
+ const approvedBy = personOf(input.approvedBy, "approvedBy");
6515
+ return db.transaction(async (tx) => {
6516
+ const row = await tx.findOne("ios_devices", { id });
6517
+ if (row === null) return null;
6518
+ const device = pick$1(row);
6519
+ const set = {
6520
+ ...name === void 0 || name === device.name ? {} : { name },
6521
+ ...device.status === "pending" ? {
6522
+ status: "approved",
6523
+ approved_by: approvedBy,
6524
+ approved_at_ms: now()
6525
+ } : {}
6526
+ };
6527
+ if (Object.keys(set).length === 0) return device;
6528
+ tx.update("ios_devices", row, set);
6529
+ return {
6530
+ ...device,
6531
+ ...set
6532
+ };
6533
+ });
6534
+ },
6535
+ async renameIosDevice(id, input) {
6536
+ const name = nameOf(input);
6537
+ return db.transaction(async (tx) => {
6538
+ const row = await tx.findOne("ios_devices", { id });
6539
+ if (row === null) return null;
6540
+ const device = pick$1(row);
6541
+ if (device.name === name) return device;
6542
+ tx.update("ios_devices", row, { name });
6543
+ return {
6544
+ ...device,
6545
+ name
6546
+ };
6547
+ });
6548
+ },
6549
+ async recordIosDeviceOutcome({ id, seen, issuerId, outcome, reason }) {
6550
+ if (!OUTCOMES.includes(outcome)) throw new IosDeviceInputError(`Invalid iOS device outcome: ${String(outcome)}. Expected ${OUTCOMES.join(", ")}.`);
6551
+ 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.`);
6552
+ return db.transaction(async (tx) => {
6553
+ const row = await tx.findOne("ios_devices", { id });
6554
+ if (row === null) return null;
6555
+ const device = pick$1(row);
6556
+ if (device.status !== seen.status || device.approved_at_ms !== seen.approvedAtMs || device.apple_issuer_id !== null && device.apple_issuer_id !== issuerId) return null;
6557
+ let set;
6558
+ switch (outcome) {
6559
+ case "registered":
6560
+ if (device.status === "pending") return null;
6561
+ set = {
6562
+ status: "registered",
6563
+ registered_at_ms: device.registered_at_ms ?? now(),
6564
+ apple_issuer_id: issuerId,
6565
+ apple_error: null
6566
+ };
6567
+ break;
6568
+ case "refused":
6569
+ if (device.status !== "approved") return null;
6570
+ set = { apple_error: errorText(reason === void 0 || reason.trim() === "" ? "Apple refused it." : reason) };
6571
+ break;
6572
+ case "disabled":
6573
+ if (device.status === "pending") return null;
6574
+ set = { apple_error: IOS_DEVICE_DISABLED_ERROR };
6575
+ break;
6576
+ case "missing":
6577
+ if (device.status !== "registered") return null;
6578
+ set = {
6579
+ status: "pending",
6580
+ approved_by: null,
6581
+ approved_at_ms: null,
6582
+ apple_error: IOS_DEVICE_MISSING_ERROR
6583
+ };
6584
+ }
6585
+ if (Object.entries(set).some(([column, value]) => device[column] !== (value ?? null))) tx.update("ios_devices", row, set);
6586
+ return {
6587
+ ...device,
6588
+ ...set
6589
+ };
6590
+ });
6591
+ },
6592
+ async markIosDevicesInBuild({ buildId, ids }) {
6593
+ for (const id of new Set(ids)) await db.transaction(async (tx) => {
6594
+ const row = await tx.findOne("ios_devices", { id });
6595
+ if (row === null || typeof row.build_id === "string" && row.build_id >= buildId) return;
6596
+ tx.update("ios_devices", row, { build_id: buildId });
6597
+ });
6598
+ },
6599
+ async findIosDeviceAccount() {
6600
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6601
+ const issuerId = existing === null ? await accountOfRows() : existing.apple_issuer_id;
6602
+ return issuerId === null ? null : { issuerId };
6603
+ },
6604
+ async claimIosDeviceAccount(issuerId) {
6605
+ 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.`);
6606
+ const answer = (held) => ({
6607
+ issuerId: held,
6608
+ claimed: held === issuerId
6609
+ });
6610
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6611
+ if (existing !== null) return answer(existing.apple_issuer_id);
6612
+ const holder = await accountOfRows() ?? issuerId;
6613
+ try {
6614
+ await db.transaction(async (tx) => {
6615
+ tx.create("ios_device_account", {
6616
+ id: ACCOUNT_ROW,
6617
+ apple_issuer_id: holder,
6618
+ claimed_at_ms: now()
6619
+ });
6620
+ });
6621
+ return answer(holder);
6622
+ } catch (error) {
6623
+ if (error instanceof DatabaseConstraintError && (error.reason === "exists" || error.reason === "unique")) {
6624
+ const winner = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6625
+ if (winner !== null) return answer(winner.apple_issuer_id);
6626
+ }
6627
+ throw error;
6628
+ }
6629
+ },
6630
+ async deleteIosDevice(id, only) {
6631
+ const requestedBy = only?.requestedBy === void 0 ? void 0 : personOf(only.requestedBy, "requestedBy");
6632
+ return db.transaction(async (tx) => {
6633
+ const row = await tx.findOne("ios_devices", { id });
6634
+ if (row === null) return null;
6635
+ const device = pick$1(row);
6636
+ if (only?.status !== void 0 && device.status !== only.status || requestedBy !== void 0 && device.requested_by !== requestedBy) return null;
6637
+ await tx.delete("ios_devices", row);
6638
+ return device;
6639
+ });
6640
+ }
6641
+ };
6642
+ };
6643
+ //#endregion
6644
+ //#region ../../packages/server/dist/core/nativeBuildDestinations.mjs
6645
+ /** Store destinations accepted for each native platform. */
6646
+ const NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
6647
+ android: [
6648
+ "play-internal",
6649
+ "play-closed",
6650
+ "play-open",
6651
+ "play-production"
6652
+ ],
6653
+ ios: ["testflight"]
6654
+ };
6655
+ //#endregion
6656
+ //#region ../../packages/server/dist/core/labels.mjs
6657
+ /**
6658
+ * The counter of a channel and platform's release labels: one
6659
+ * `label_sequences` row, which every writer of the pair reads and bumps.
6660
+ */
6661
+ const labelSequenceId = (channelId, platform) => `releases/${platform}/${channelId}`;
6662
+ /** The pairs a channel's counters belong to, which deleting it removes. */
6663
+ const LABEL_PLATFORMS = ["ios", "android"];
6664
+ /**
6665
+ * A channel and platform whose releases written before labels have none
6666
+ * yet, or that has no counter: the write stops before taking a label, the
6667
+ * core labels the pair with `fillLabels`, and the write runs again.
6668
+ */
6669
+ var NeedsLabelFill = class extends Error {
6670
+ channelId;
6671
+ platform;
6672
+ constructor(channelId, platform) {
6673
+ super(`Release labels of ${platform} ${channelId} need a fill first.`);
6674
+ this.channelId = channelId;
6675
+ this.platform = platform;
6676
+ }
6677
+ };
6678
+ const createLabelAllocator = (tx, used, caughtUp) => {
6679
+ const sequences = /* @__PURE__ */ new Map();
6680
+ return {
6681
+ async next(channelId, platform) {
6682
+ const id = labelSequenceId(channelId, platform);
6683
+ let sequence = sequences.get(id);
6684
+ if (sequence === void 0) {
6685
+ const row = await tx.findOne("label_sequences", { id });
6686
+ if (row === null || !row.is_filled) {
6687
+ const channel = row === null ? await tx.findOne("channels", { id: channelId }) : null;
6688
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) throw new NeedsLabelFill(channelId, platform);
6689
+ }
6690
+ const read = row?.last_label ?? 0;
6691
+ sequence = {
6692
+ row,
6693
+ read,
6694
+ last: read
6695
+ };
6696
+ sequences.set(id, sequence);
6697
+ used.set(id, {
6698
+ channelId,
6699
+ platform,
6700
+ read
6701
+ });
6702
+ }
6703
+ sequence.last += 1;
6704
+ return sequence.last;
6705
+ },
6706
+ caughtUp(channelId, platform) {
6707
+ caughtUp.set(labelSequenceId(channelId, platform), {
6708
+ channelId,
6709
+ platform
6710
+ });
6711
+ },
6712
+ flush() {
6713
+ for (const [id, { row, read, last }] of sequences) if (row === null) tx.create("label_sequences", {
6714
+ id,
6715
+ last_label: last,
6716
+ is_filled: true
6717
+ });
6718
+ else if (last !== read) tx.update("label_sequences", row, { last_label: last });
6719
+ }
6720
+ };
6721
+ };
6722
+ const FILL_BATCH = 25;
6723
+ const PAGE$4 = 500;
6724
+ const PAUSE_MS$1 = 1e3;
6725
+ const MAX_PAUSE_MS$1 = 32e3;
6726
+ const sleep$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
6727
+ /**
6728
+ * Labels a channel and platform's releases that have none, in ID order,
6729
+ * which is the order they were created in, and marks its counter filled:
6730
+ * each batch reads the counter and its rows guarded, so a concurrent fill or
6731
+ * write serializes on the counter and skips what another labeled. With
6732
+ * `dryRun`, it only counts them. Answers how many it labeled.
6733
+ */
6734
+ const fillLabels = async (db, { channelId, platform }, { dryRun = false } = {}) => {
6735
+ const id = labelSequenceId(channelId, platform);
6736
+ let labeled = 0;
6737
+ let batchSize = FILL_BATCH;
6738
+ let paused = 0;
6739
+ const label = async (ids) => {
6740
+ for (let at = 0; at < ids.length;) {
6741
+ const batch = ids.slice(at, at + batchSize);
6742
+ try {
6743
+ labeled += await db.transaction(async (tx) => {
6744
+ const counter = await tx.findOne("label_sequences", { id });
6745
+ let last = counter?.last_label ?? 0;
6746
+ let count = 0;
6747
+ for (const releaseId of batch) {
6748
+ const row = await tx.findOne("releases", { id: releaseId });
6749
+ if (row === null || typeof row.label === "number") continue;
6750
+ last += 1;
6751
+ count += 1;
6752
+ tx.update("releases", row, { label: last });
6753
+ }
6754
+ if (counter === null) tx.create("label_sequences", {
6755
+ id,
6756
+ last_label: last,
6757
+ is_filled: false
6758
+ });
6759
+ else if (last !== counter.last_label) tx.update("label_sequences", counter, { last_label: last });
6760
+ return count;
6761
+ });
6762
+ at += batch.length;
6763
+ paused = 0;
6764
+ } catch (error) {
6765
+ if (batchSize > 1 && error instanceof DatabaseConstraintError && error.reason === "too_large") {
6766
+ batchSize = Math.max(1, Math.floor(batchSize / 2));
6767
+ continue;
6768
+ }
6769
+ if (!isDatabaseBusyError(error) || paused >= MAX_PAUSE_MS$1) throw error;
6770
+ batchSize = Math.max(1, Math.floor(batchSize / 2));
6771
+ paused = paused === 0 ? PAUSE_MS$1 : paused * 2;
6772
+ await sleep$1(paused);
6773
+ }
6774
+ }
6775
+ };
6776
+ let cursor;
6777
+ do {
6778
+ const page = await db.findMany("releases", {
6779
+ index: "byChannelPlatform",
6780
+ where: {
6781
+ channel_id: channelId,
6782
+ platform
6783
+ },
6784
+ limit: PAGE$4,
6785
+ ...cursor === void 0 ? {} : { cursor }
6786
+ });
6787
+ const unlabeled = page.rows.filter((row) => typeof row.label !== "number").map((row) => row.id);
6788
+ if (dryRun) labeled += unlabeled.length;
6789
+ else await label(unlabeled);
6790
+ cursor = page.next;
6791
+ } while (cursor !== void 0);
6792
+ if (dryRun) return labeled;
6793
+ await db.transaction(async (tx) => {
6794
+ const counter = await tx.findOne("label_sequences", { id });
6795
+ if (counter === null) tx.create("label_sequences", {
6796
+ id,
6797
+ last_label: 0,
6798
+ is_filled: true
6799
+ });
6800
+ else if (!counter.is_filled) tx.update("label_sequences", counter, { is_filled: true });
6801
+ });
6802
+ return labeled;
6803
+ };
6804
+ /**
6805
+ * Reads what a pair's fill writes, its counter and its label index, without
6806
+ * writing: a database without release labels' schema, such as one a 1.2
6807
+ * prerelease migrated, fails here as the fill would. The schema is the
6808
+ * database's, so one pair tells. Two reads.
6809
+ */
6810
+ const probeLabelSchema = async (db, { channelId, platform }) => {
6811
+ await db.findOne("label_sequences", { id: labelSequenceId(channelId, platform) });
6812
+ await db.findMany("releases", {
6813
+ index: "byLabel",
6814
+ where: {
6815
+ channel_id: channelId,
6816
+ platform,
6817
+ label: 0
6818
+ },
6819
+ limit: 1
6820
+ });
6821
+ };
6822
+ const REPAIRS = 4;
6823
+ const RACES = 32;
6824
+ /**
6825
+ * Runs a release write that takes labels, in one transaction with the
6826
+ * counters it bumps. A pair that still needs its fill is filled, and the
6827
+ * write runs again; so is a pair whose catch-up made the write too large for
6828
+ * the store. A label another row holds, such as an index item a release
6829
+ * deleted by a server of an earlier release left on a key-value store, is
6830
+ * skipped: its counters move past it and the write runs again.
6831
+ */
6832
+ const writeWithLabels = async (db, write) => {
6833
+ const filled = /* @__PURE__ */ new Set();
6834
+ const fill = async (pairs) => {
6835
+ for (const pair of pairs) {
6836
+ filled.add(labelSequenceId(pair.channelId, pair.platform));
6837
+ await fillLabels(db, pair);
6838
+ }
6839
+ };
6840
+ for (let repairs = 0, races = 0;;) {
6841
+ const used = /* @__PURE__ */ new Map();
6842
+ const caughtUp = /* @__PURE__ */ new Map();
6843
+ try {
6844
+ return await db.transaction(async (tx) => {
6845
+ used.clear();
6846
+ caughtUp.clear();
6847
+ const labels = createLabelAllocator(tx, used, caughtUp);
6848
+ const result = await write(tx, labels);
6849
+ labels.flush();
6850
+ return result;
6851
+ });
6852
+ } catch (error) {
6853
+ const needs = error instanceof NeedsLabelFill ? [error] : error instanceof DatabaseConstraintError && error.reason === "too_large" ? [...caughtUp.values()] : [];
6854
+ if (needs.length > 0) {
6855
+ const fresh = needs.some(({ channelId, platform }) => !filled.has(labelSequenceId(channelId, platform)));
6856
+ if (fresh || repairs < REPAIRS) {
6857
+ if (!fresh) repairs += 1;
6858
+ await fill(needs);
6859
+ continue;
6860
+ }
6861
+ }
6862
+ if (error instanceof DatabaseConstraintError && error.reason === "unique" && error.model === "releases" && used.size > 0) {
6863
+ if (await db.transaction(async (tx) => {
6864
+ const moves = [];
6865
+ for (const [id, { channelId, read }] of used) {
6866
+ const counter = await tx.findOne("label_sequences", { id });
6867
+ if (counter !== null) {
6868
+ if (counter.last_label !== read) return false;
6869
+ moves.push(() => tx.update("label_sequences", counter, { last_label: read + 1 }));
6870
+ continue;
6871
+ }
6872
+ const channel = await tx.findOne("channels", { id: channelId });
6873
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) return false;
6874
+ moves.push(() => tx.create("label_sequences", {
6875
+ id,
6876
+ last_label: read + 1,
6877
+ is_filled: true
6878
+ }));
6879
+ }
6880
+ for (const move of moves) move();
6881
+ return true;
6882
+ }) ? (repairs += 1) <= REPAIRS : (races += 1) <= RACES) continue;
6883
+ }
6884
+ throw error;
6885
+ }
6886
+ }
6887
+ };
6888
+ /**
6889
+ * Labels a scope's releases a server of an earlier release wrote after its
6890
+ * newest labeled one, oldest first, before the write takes its own label:
6891
+ * `latest` is the scope's newest release, so a labeled one costs no read.
6892
+ * Answers the labels it gave, by release ID.
6893
+ */
6894
+ const catchUpLabels = async (tx, labels, latest) => {
6895
+ const given = /* @__PURE__ */ new Map();
6896
+ if (latest === null || typeof latest.label === "number") return given;
6897
+ const unlabeled = [];
6898
+ let cursor;
6899
+ scan: do {
6900
+ const page = await tx.findMany("releases", {
6901
+ index: "byScope",
6902
+ where: { scope_key: latest.scope_key },
6903
+ order: "desc",
6904
+ limit: FILL_BATCH,
6905
+ ...cursor === void 0 ? {} : { cursor }
6906
+ });
6907
+ for (const row of page.rows) {
6908
+ if (typeof row.label === "number") break scan;
6909
+ unlabeled.push(row);
6910
+ }
6911
+ cursor = page.next;
6912
+ } while (cursor !== void 0);
6913
+ labels.caughtUp(latest.channel_id, latest.platform);
6914
+ for (const row of unlabeled.reverse()) {
6915
+ const { id, channel_id, platform } = toReleaseRow(row);
6916
+ const label = await labels.next(channel_id, platform);
6917
+ tx.update("releases", row, { label });
6918
+ given.set(id, label);
6919
+ }
6920
+ return given;
6921
+ };
6922
+ /**
6923
+ * The channels and platforms whose releases need labels: a scope whose
6924
+ * newest release has none, or a pair without a filled counter. Releases a
6925
+ * server of an earlier release wrote in a filled pair come after its
6926
+ * labeled ones in their scope, so the newest release of each scope tells.
6927
+ * Two reads per scope, one per pair.
6928
+ */
6929
+ const pendingLabelPairs = async (db) => {
6930
+ const pairs = /* @__PURE__ */ new Map();
6931
+ for (let last = "";;) {
6932
+ const { rows } = await db.findMany("releases", {
6933
+ index: "scopes",
6934
+ where: {},
6935
+ limit: 1,
6936
+ range: { gt: last }
6937
+ });
6938
+ if (rows[0] === void 0) break;
6939
+ last = rows[0].scope_key;
6940
+ const { rows: newest } = await db.findMany("releases", {
6941
+ index: "byScope",
6942
+ where: { scope_key: last },
6943
+ order: "desc",
6944
+ limit: 1
6945
+ });
6946
+ if (newest[0] === void 0) continue;
6947
+ const { channel_id: channelId, platform, label } = toReleaseRow(newest[0]);
6948
+ const id = labelSequenceId(channelId, platform);
6949
+ const pair = pairs.get(id) ?? {
6950
+ channelId,
6951
+ platform,
6952
+ pending: false
6953
+ };
6954
+ pair.pending ||= label === null;
6955
+ pairs.set(id, pair);
6956
+ }
6957
+ const pending = [];
6958
+ for (const [id, { channelId, platform, pending: unlabeled }] of pairs) {
6959
+ if (!unlabeled) {
6960
+ const counter = await db.findOne("label_sequences", { id });
6961
+ if (counter !== null && counter.is_filled) continue;
6962
+ }
6963
+ pending.push({
6964
+ channelId,
6965
+ platform
6966
+ });
6967
+ }
6968
+ return pending;
6969
+ };
6970
+ //#endregion
5753
6971
  //#region ../../packages/server/dist/core/writes.mjs
5754
- const PAGE$2 = 500;
6972
+ const PAGE$3 = 500;
5755
6973
  /** Moves one bundle into or out of its platform's total and the overall total. */
5756
6974
  const countBundle = (tx, platform, delta) => {
5757
6975
  for (const key of [platform, "*"]) tx.aggregate("bundle_totals", { platform_key: key }, { bundles: delta });
@@ -5779,8 +6997,10 @@ const deleteBundle = async (tx, current) => {
5779
6997
  /**
5780
6998
  * Replaces a bundle's patches with `rows`: kept patches are updated where
5781
6999
  * they changed, others deleted or created, so no key is written twice.
7000
+ * `checkNew` sees each patch it is about to create, and refuses one by
7001
+ * throwing, which leaves the transaction's writes undone.
5782
7002
  */
5783
- const replaceBundlePatches = async (tx, bundle, rows) => {
7003
+ const replaceBundlePatches = async (tx, bundle, rows, checkNew) => {
5784
7004
  const wanted = new Map(rows.map((row) => [row.id, row]));
5785
7005
  const count = bundle._refs_bundle_patches_bundle_id ?? 0;
5786
7006
  let cursor;
@@ -5788,7 +7008,7 @@ const replaceBundlePatches = async (tx, bundle, rows) => {
5788
7008
  const page = await tx.findMany("bundle_patches", {
5789
7009
  index: "byBundle",
5790
7010
  where: { bundle_id: bundle.id },
5791
- limit: Math.min(count - seen, PAGE$2),
7011
+ limit: Math.min(count - seen, PAGE$3),
5792
7012
  ...cursor === void 0 ? {} : { cursor }
5793
7013
  });
5794
7014
  for (const stored of page.rows) {
@@ -5805,6 +7025,7 @@ const replaceBundlePatches = async (tx, bundle, rows) => {
5805
7025
  if (page.next === void 0) break;
5806
7026
  cursor = page.next;
5807
7027
  }
7028
+ if (checkNew !== void 0) for (const row of wanted.values()) await checkNew(row);
5808
7029
  for (const row of wanted.values()) tx.create("bundle_patches", row);
5809
7030
  };
5810
7031
  /** A channel by name, created when missing; a concurrent creator's row is returned instead. */
@@ -5827,7 +7048,11 @@ const insertChannel = async (db, row) => {
5827
7048
  throw error;
5828
7049
  }
5829
7050
  };
5830
- /** Deletes a channel no release or native build uses: 1 read, 1 query, 1 write. */
7051
+ /**
7052
+ * Deletes a channel no release or native build uses, with its label
7053
+ * counters, so one created again with its name starts at 1: 3 reads,
7054
+ * 1 query, 1 write.
7055
+ */
5831
7056
  const deleteChannel = (db, id) => db.transaction(async (tx) => {
5832
7057
  const row = await tx.findOne("channels", { id });
5833
7058
  if (row === null) return {
@@ -5847,6 +7072,10 @@ const deleteChannel = (db, id) => db.transaction(async (tx) => {
5847
7072
  deleted: false,
5848
7073
  reason: "not_empty"
5849
7074
  };
7075
+ for (const platform of LABEL_PLATFORMS) {
7076
+ const counter = await tx.findOne("label_sequences", { id: labelSequenceId(id, platform) });
7077
+ if (counter !== null) await tx.delete("label_sequences", counter);
7078
+ }
5850
7079
  await tx.delete("channels", row);
5851
7080
  return { deleted: true };
5852
7081
  });
@@ -5867,6 +7096,27 @@ const GIT_COMMIT_HASH_MAX_LENGTH = 255;
5867
7096
  * and looks up nothing else.
5868
7097
  */
5869
7098
  const BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
7099
+ /** `native_builds.sandbox_url_scheme`'s bound in core's schema. */
7100
+ const SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
7101
+ /**
7102
+ * A URL scheme as RFC 3986 spells it, in lower case: what a sandbox build's
7103
+ * artifact registers, as `@hot-updater/protocol/native-artifact` reads it.
7104
+ */
7105
+ const URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
7106
+ /**
7107
+ * A bundle identifier or application ID, as an artifact reports it: letters,
7108
+ * digits, dots, dashes and underscores, which a scope key holds as they are.
7109
+ */
7110
+ const APP_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;
7111
+ /** A fingerprint hash as a Release Catalog scope key holds it. */
7112
+ const FINGERPRINT_HASH = /^[A-Za-z0-9._~-]{1,255}$/;
7113
+ /** How each kind of artifact can install. */
7114
+ const DISTRIBUTIONS = {
7115
+ apk: ["direct"],
7116
+ app: ["direct"],
7117
+ aab: ["store"],
7118
+ ipa: ["direct", "store"]
7119
+ };
5870
7120
  /** A native build or scope core cannot store or look up: the caller's input. */
5871
7121
  var NativeBuildInputError = class extends TypeError {
5872
7122
  name = "NativeBuildInputError";
@@ -5888,24 +7138,73 @@ const pick = (row) => ({
5888
7138
  build_number: row.build_number ?? null,
5889
7139
  submitted_to: row.submitted_to ?? null,
5890
7140
  submitted_at_ms: row.submitted_at_ms ?? null,
5891
- submitted_version: row.submitted_version ?? null
7141
+ submitted_version: row.submitted_version ?? null,
7142
+ is_store_build: row.is_store_build === true,
7143
+ is_sandbox: row.is_sandbox === true,
7144
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
7145
+ export_method: row.export_method ?? null,
7146
+ native_app_version: row.native_app_version ?? null
5892
7147
  });
5893
- /** The store track each platform's builds are submitted to. */
5894
- const SUBMISSION_DESTINATIONS = {
5895
- android: "play-internal",
5896
- ios: "testflight"
5897
- };
7148
+ /** The export methods an `.ipa` registers with. */
7149
+ const EXPORT_METHODS = /* @__PURE__ */ new Set([
7150
+ "app-store",
7151
+ "ad-hoc",
7152
+ "development",
7153
+ "enterprise"
7154
+ ]);
7155
+ /**
7156
+ * How many older builds of a scope one read takes, looking for one older than
7157
+ * a bundle when a build made after the bundle is the newest.
7158
+ */
7159
+ const OLDER_BUILDS_PAGE = 20;
7160
+ /**
7161
+ * How many pages of older builds that look reads before it answers null: 100
7162
+ * builds made after the bundle in one scope, where a deploy's new bundle has
7163
+ * none or a few registered while it deploys.
7164
+ */
7165
+ const OLDER_BUILDS_PAGES = 5;
7166
+ /** How many times a mark runs again after losing its scope's mark to another. */
7167
+ const MARK_ATTEMPTS = 8;
5898
7168
  /** `native_builds.build_number`'s bound in core's schema. */
5899
7169
  const BUILD_NUMBER_MAX_LENGTH = 64;
5900
7170
  /** `native_builds.submitted_version`'s bound in core's schema. */
5901
7171
  const SUBMITTED_VERSION_MAX_LENGTH = 255;
7172
+ const checkedScopeKey = (scopeKey) => {
7173
+ 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.`);
7174
+ return scopeKey;
7175
+ };
7176
+ /**
7177
+ * How a registered artifact installs: an `.ipa` by its export method, and
7178
+ * `unknown` for one whose export no profile confirmed, which no lookup asks
7179
+ * for, so it is never reused as either.
7180
+ */
7181
+ const registeredDistribution = (kind, exportMethod) => kind !== "ipa" ? DISTRIBUTIONS[kind][0] : exportMethod === void 0 || exportMethod === null ? "unknown" : exportMethod === "app-store" ? "store" : "direct";
7182
+ /**
7183
+ * A sandbox build scope's key, which names no channel: the app ID, URL
7184
+ * scheme, artifact kind and distribution in its place, then the fingerprint,
7185
+ * or the app-version strategy and the exact app version. `v1:sandbox:` is no
7186
+ * Release Catalog strategy, so it never meets a normal build's key.
7187
+ */
7188
+ const sandboxScopeKey = (scope, sandbox) => {
7189
+ const { appId, urlScheme, artifactKind, distribution } = sandbox;
7190
+ 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;
7191
+ if (problem !== null) throw new NativeBuildInputError(`Invalid sandbox build scope: ${problem}.`);
7192
+ const target = scope.fingerprintHash === null ? `app-version:${encodeURIComponent(scope.appVersion)}` : `fingerprint:${scope.fingerprintHash}`;
7193
+ return checkedScopeKey(`v1:sandbox:${scope.platform}:${appId}:${urlScheme}:${artifactKind}:${distribution}:${target}`);
7194
+ };
5902
7195
  /**
5903
7196
  * A native build scope's key: the Release Catalog scope key of a
5904
7197
  * fingerprint, or of the app-version strategy followed by the exact app
5905
7198
  * version the build compiled in. One key serves both strategies, so one
5906
- * index finds the newest build of either.
7199
+ * index finds the newest build of either. A sandbox scope's key names no
7200
+ * channel, so pull requests find a sandbox build on any.
5907
7201
  */
5908
7202
  const nativeBuildScopeKey = (scope) => {
7203
+ const { sandbox } = scope;
7204
+ if (sandbox !== void 0 && sandbox !== null) {
7205
+ if (sandbox.distribution !== "direct" && sandbox.distribution !== "store") throw new NativeBuildInputError("Invalid sandbox build scope: its distribution must be direct or store.");
7206
+ return sandboxScopeKey(scope, sandbox);
7207
+ }
5909
7208
  let scopeKey;
5910
7209
  try {
5911
7210
  const channelKey = encodeChannelKey(scope.channel);
@@ -5922,32 +7221,126 @@ const nativeBuildScopeKey = (scope) => {
5922
7221
  } catch (error) {
5923
7222
  throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
5924
7223
  }
5925
- 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.`);
5926
- return scopeKey;
7224
+ return checkedScopeKey(scopeKey);
7225
+ };
7226
+ /** The channel row a registration names, or the refusal of its channel. */
7227
+ const channelIdOf = (channel) => {
7228
+ try {
7229
+ return `channel:${encodeChannelKey(channel)}`;
7230
+ } catch (error) {
7231
+ throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
7232
+ }
7233
+ };
7234
+ /**
7235
+ * A registration's scope key, from the registration's own facts: a sandbox
7236
+ * build's from what its artifact says, whatever `sandbox` it names.
7237
+ */
7238
+ const registrationScopeKey = (registration) => {
7239
+ channelIdOf(registration.channel);
7240
+ return registration.isSandbox === true ? sandboxScopeKey(registration, {
7241
+ appId: registration.sandboxAppId,
7242
+ urlScheme: registration.sandboxUrlScheme,
7243
+ artifactKind: registration.artifact.kind,
7244
+ distribution: registeredDistribution(registration.artifact.kind, registration.exportMethod)
7245
+ }) : nativeBuildScopeKey({
7246
+ ...registration,
7247
+ sandbox: null
7248
+ });
7249
+ };
7250
+ /**
7251
+ * Refuses a patch from a sandbox build's built-in bundle: no deploy patches
7252
+ * from one, so no store or test install of the app gets a patch made for a
7253
+ * sandbox build. One unique read of the base.
7254
+ */
7255
+ const refuseSandboxPatchBase = async (db, baseBundleId) => {
7256
+ 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.");
5927
7257
  };
5928
7258
  /** Whether `bundleId` is a native build's built-in bundle: one unique read. */
5929
7259
  const isBuiltInBundle = async (db, bundleId) => await db.findOne("native_builds", { min_bundle_id: bundleId }) !== null;
5930
- const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, artifact }) => {
7260
+ const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, sandboxAppId, exportMethod, nativeAppVersion, artifact }) => {
5931
7261
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
5932
7262
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
5933
7263
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
5934
7264
  if (channel.trim().length === 0) return "channel is required";
7265
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
7266
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
7267
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
7268
+ 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`;
7269
+ }
7270
+ if (sandboxAppId !== void 0 && sandboxAppId !== null) {
7271
+ if (isSandbox !== true) return "sandboxAppId is a sandbox build's, and this isn't one";
7272
+ if (typeof sandboxAppId !== "string" || !APP_ID.test(sandboxAppId)) return "sandboxAppId must be the artifact's bundle identifier or application ID, up to 255 characters";
7273
+ }
7274
+ if (isSandbox === true) {
7275
+ if (sandboxUrlScheme === void 0 || sandboxUrlScheme === null) return "a sandbox build needs the sandboxUrlScheme its artifact registers";
7276
+ 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";
7277
+ }
5935
7278
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
5936
7279
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
5937
7280
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
5938
7281
  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`;
7282
+ if (nativeAppVersion !== void 0 && nativeAppVersion !== null && (typeof nativeAppVersion !== "string" || nativeAppVersion.trim().length === 0)) return "nativeAppVersion must be the artifact's app version, or null";
5939
7283
  const kinds = ARTIFACT_KINDS[platform];
5940
7284
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
7285
+ if (exportMethod !== void 0 && exportMethod !== null) {
7286
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
7287
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
7288
+ }
5941
7289
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
5942
7290
  return null;
5943
7291
  };
7292
+ /** The other install target of an iOS sandbox build's native code. */
7293
+ const SIBLING_KINDS = {
7294
+ app: "ipa",
7295
+ ipa: "app"
7296
+ };
7297
+ /**
7298
+ * Whether a build is one a person installs from its file: a Simulator `.app`,
7299
+ * or an `.ipa` exported for direct install, that no store took and that isn't
7300
+ * the store build. One rule for a sibling and the build it is found from, so
7301
+ * a build that shows its sibling is shown by it.
7302
+ */
7303
+ 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");
7304
+ /**
7305
+ * The scope key of the other install target of a sandbox build, from its own
7306
+ * key's app ID and URL scheme, which hold no colon, and its row's fingerprint
7307
+ * or app version, through `sandboxScopeKey`; null for a key it didn't make.
7308
+ */
7309
+ const siblingSandboxScopeKey = (build, artifactKind) => {
7310
+ const [version, sandbox, platform, appId, urlScheme] = build.scope_key.split(":");
7311
+ if (version !== "v1" || sandbox !== "sandbox" || platform !== build.platform || appId === void 0 || urlScheme === void 0) return null;
7312
+ const target = build.fingerprint_hash === null ? {
7313
+ platform: build.platform,
7314
+ fingerprintHash: null,
7315
+ appVersion: build.app_version ?? ""
7316
+ } : {
7317
+ platform: build.platform,
7318
+ fingerprintHash: build.fingerprint_hash,
7319
+ appVersion: null
7320
+ };
7321
+ try {
7322
+ return sandboxScopeKey(target, {
7323
+ appId,
7324
+ urlScheme,
7325
+ artifactKind: build.artifact_kind,
7326
+ distribution: registeredDistribution(build.artifact_kind, build.export_method)
7327
+ }) === build.scope_key ? sandboxScopeKey(target, {
7328
+ appId,
7329
+ urlScheme,
7330
+ artifactKind,
7331
+ distribution: "direct"
7332
+ }) : null;
7333
+ } catch {
7334
+ return null;
7335
+ }
7336
+ };
5944
7337
  /** The native build registry: core's `native_builds` and the built-in bundle rows. */
5945
7338
  const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
5946
7339
  async registerNativeBuild(registration) {
5947
7340
  const problem = problemOf(registration);
5948
7341
  if (problem !== null) throw new NativeBuildInputError(`Invalid native build: ${problem}.`);
5949
- const scopeKey = nativeBuildScopeKey(registration);
5950
- const channelId = `channel:${encodeChannelKey(registration.channel)}`;
7342
+ const scopeKey = registrationScopeKey(registration);
7343
+ const channelId = channelIdOf(registration.channel);
5951
7344
  const { embeddedBundle } = registration;
5952
7345
  const row = {
5953
7346
  id: registration.id,
@@ -5966,7 +7359,12 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
5966
7359
  build_number: registration.buildNumber ?? null,
5967
7360
  submitted_to: null,
5968
7361
  submitted_at_ms: null,
5969
- submitted_version: null
7362
+ submitted_version: null,
7363
+ is_store_build: false,
7364
+ is_sandbox: registration.isSandbox === true,
7365
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
7366
+ export_method: registration.exportMethod ?? null,
7367
+ native_app_version: registration.nativeAppVersion ?? null
5970
7368
  };
5971
7369
  for (let attempt = 1;; attempt += 1) {
5972
7370
  await insertChannel(db, {
@@ -6000,25 +7398,82 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6000
7398
  const row = await db.findOne("native_builds", { id });
6001
7399
  return row === null ? null : pick(row);
6002
7400
  },
7401
+ async findNativeBuildByBuiltInBundle(bundleId) {
7402
+ const row = await db.findOne("native_builds", { min_bundle_id: bundleId });
7403
+ return row === null ? null : pick(row);
7404
+ },
6003
7405
  async findNativeBuild(scope, options) {
6004
7406
  const scopeKey = nativeBuildScopeKey(scope);
6005
7407
  const buildKey = options?.buildKey;
6006
7408
  if (buildKey !== void 0 && !BUILD_KEY.test(buildKey)) throw new NativeBuildInputError("Invalid native build key: it must be nbk1: and a SHA-256.");
6007
- const { rows } = buildKey === void 0 ? await db.findMany("native_builds", {
7409
+ const artifactKind = options?.artifactKind;
7410
+ 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 ")}.`);
7411
+ const ofKind = (row) => artifactKind === void 0 || row.artifact_kind === artifactKind;
7412
+ if (options?.storeBuild) {
7413
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
7414
+ return marked === null || !ofKind(marked) ? null : pick(marked);
7415
+ }
7416
+ const read = (limit, before) => {
7417
+ const page = {
7418
+ order: "desc",
7419
+ limit,
7420
+ ...before === void 0 ? {} : { range: { lt: before } }
7421
+ };
7422
+ return buildKey !== void 0 ? db.findMany("native_builds", {
7423
+ index: "byBuildKey",
7424
+ where: {
7425
+ scope_key: scopeKey,
7426
+ build_key: buildKey
7427
+ },
7428
+ ...page
7429
+ }) : artifactKind !== void 0 ? db.findMany("native_builds", {
7430
+ index: "byScopeKind",
7431
+ where: {
7432
+ scope_key: scopeKey,
7433
+ artifact_kind: artifactKind
7434
+ },
7435
+ ...page
7436
+ }) : db.findMany("native_builds", {
7437
+ index: "byScope",
7438
+ where: { scope_key: scopeKey },
7439
+ ...page
7440
+ });
7441
+ };
7442
+ const bundleId = options?.builtInOlderThan;
7443
+ if (bundleId !== void 0 && scope.sandbox !== void 0 && scope.sandbox !== null) return null;
7444
+ const { rows } = await read(1);
7445
+ const newest = (rows[0] === void 0 ? void 0 : pick(rows[0])) ?? (artifactKind !== void 0 && buildKey === void 0 ? await db.findMany("native_builds", {
6008
7446
  index: "byScope",
6009
7447
  where: { scope_key: scopeKey },
6010
7448
  order: "desc",
6011
7449
  limit: 1
6012
- }) : await db.findMany("native_builds", {
6013
- index: "byBuildKey",
6014
- where: {
6015
- scope_key: scopeKey,
6016
- build_key: buildKey
6017
- },
7450
+ }).then(({ rows: [row] }) => row?.artifact_kind === artifactKind ? pick(row) : void 0) : void 0);
7451
+ if (newest === void 0 || !ofKind(newest)) return null;
7452
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return newest;
7453
+ let before = newest.id;
7454
+ for (let page = 0; page < OLDER_BUILDS_PAGES; page += 1) {
7455
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
7456
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
7457
+ if (usable !== void 0) return ofKind(usable) ? pick(usable) : null;
7458
+ const last = older.at(-1);
7459
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
7460
+ before = last.id;
7461
+ }
7462
+ return null;
7463
+ },
7464
+ async findNativeBuildSibling(build) {
7465
+ const artifactKind = SIBLING_KINDS[build.artifact_kind];
7466
+ if (build.platform !== "ios" || !build.is_sandbox || artifactKind === void 0 || !isInstallTarget(build)) return null;
7467
+ const scopeKey = siblingSandboxScopeKey(build, artifactKind);
7468
+ if (scopeKey === null) return null;
7469
+ const { rows } = await db.findMany("native_builds", {
7470
+ index: "byScope",
7471
+ where: { scope_key: scopeKey },
6018
7472
  order: "desc",
6019
7473
  limit: 1
6020
7474
  });
6021
- return rows[0] === void 0 ? null : pick(rows[0]);
7475
+ const sibling = rows[0] === void 0 ? null : pick(rows[0]);
7476
+ return sibling !== null && isInstallTarget(sibling) ? sibling : null;
6022
7477
  },
6023
7478
  async recordNativeBuildSubmission(id, { destination, version }) {
6024
7479
  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.`);
@@ -6026,7 +7481,8 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6026
7481
  const row = await tx.findOne("native_builds", { id });
6027
7482
  if (row === null) return null;
6028
7483
  const build = pick(row);
6029
- 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}.`);
7484
+ 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}.`);
7485
+ if (build.is_sandbox && destination !== "testflight" && destination !== "play-internal") throw new NativeBuildInputError("A sandbox build can submit only to TestFlight or Play internal testing.");
6030
7486
  const set = {
6031
7487
  submitted_to: destination,
6032
7488
  submitted_at_ms: now(),
@@ -6039,6 +7495,46 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6039
7495
  };
6040
7496
  });
6041
7497
  },
7498
+ async markNativeBuild(id, { storeBuild }) {
7499
+ for (let attempt = 1;; attempt += 1) try {
7500
+ return await db.transaction(async (tx) => {
7501
+ const row = await tx.findOne("native_builds", { id });
7502
+ if (row === null) return null;
7503
+ const build = pick(row);
7504
+ if (!storeBuild) {
7505
+ if (build.is_store_build) tx.update("native_builds", row, { is_store_build: false });
7506
+ return {
7507
+ nativeBuild: {
7508
+ ...build,
7509
+ is_store_build: false
7510
+ },
7511
+ previous: null
7512
+ };
7513
+ }
7514
+ if (build.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
7515
+ if (build.is_store_build) return {
7516
+ nativeBuild: build,
7517
+ previous: null
7518
+ };
7519
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build.scope_key });
7520
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
7521
+ tx.update("native_builds", row, { is_store_build: true });
7522
+ return {
7523
+ nativeBuild: {
7524
+ ...build,
7525
+ is_store_build: true
7526
+ },
7527
+ previous: holder === null ? null : {
7528
+ ...pick(holder),
7529
+ is_store_build: false
7530
+ }
7531
+ };
7532
+ });
7533
+ } catch (error) {
7534
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
7535
+ throw error;
7536
+ }
7537
+ },
6042
7538
  async deleteNativeBuild(id) {
6043
7539
  return db.transaction(async (tx) => {
6044
7540
  const row = await tx.findOne("native_builds", { id });
@@ -6076,7 +7572,7 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6076
7572
  });
6077
7573
  //#endregion
6078
7574
  //#region ../../packages/server/dist/core/releases.mjs
6079
- const PAGE$1 = 500;
7575
+ const PAGE$2 = 500;
6080
7576
  const fail$1 = (code, message) => {
6081
7577
  throw new ReleaseCatalogMutationError(code, message);
6082
7578
  };
@@ -6094,44 +7590,43 @@ const checkScope = (scope) => {
6094
7590
  });
6095
7591
  if (scope.strategy === "FINGERPRINT" !== (scope.fingerprintHash !== null) || scope.scopeKey !== expected) fail$1("INVALID_SCOPE", "Release catalog scope metadata is inconsistent");
6096
7592
  };
6097
- /** A scope's enabled releases, all of them, under the catalog's guard. */
6098
- const enabledReleases = async (tx, scopeKey) => {
7593
+ /** Every row of a paged read, as release rows. */
7594
+ const drainReleases = async (page) => {
6099
7595
  const rows = [];
6100
7596
  let cursor;
6101
7597
  do {
6102
- const page = await tx.findMany("releases", {
6103
- index: "byScopeEnabled",
6104
- where: {
6105
- scope_key: scopeKey,
6106
- enabled: true
6107
- },
6108
- limit: PAGE$1,
6109
- ...cursor === void 0 ? {} : { cursor }
6110
- });
6111
- rows.push(...page.rows.map(toReleaseRow));
6112
- cursor = page.next;
7598
+ const found = await page(cursor);
7599
+ rows.push(...found.rows.map((row) => toReleaseRow(row)));
7600
+ cursor = found.next;
6113
7601
  } while (cursor !== void 0);
6114
7602
  return rows;
6115
7603
  };
6116
- /** The scope's newest release id: `byScope` descending, limit 1. */
6117
- const latestReleaseId = async (tx, scopeKey) => {
7604
+ const enabledIn = (scopeKey, cursor) => ({
7605
+ index: "byScopeEnabled",
7606
+ where: {
7607
+ scope_key: scopeKey,
7608
+ enabled: true
7609
+ },
7610
+ limit: PAGE$2,
7611
+ ...cursor === void 0 ? {} : { cursor }
7612
+ });
7613
+ /** A scope's enabled releases, all of them, under the catalog's guard. */
7614
+ const enabledReleases = (tx, scopeKey) => drainReleases((cursor) => tx.findMany("releases", enabledIn(scopeKey, cursor)));
7615
+ /** The scope's newest release: `byScope` descending, limit 1. */
7616
+ const latestRelease = async (tx, scopeKey) => {
6118
7617
  const { rows } = await tx.findMany("releases", {
6119
7618
  index: "byScope",
6120
7619
  where: { scope_key: scopeKey },
6121
7620
  order: "desc",
6122
7621
  limit: 1
6123
7622
  });
6124
- return rows[0]?.id ?? null;
7623
+ return rows[0] === void 0 ? null : toReleaseRow(rows[0]);
6125
7624
  };
6126
- /** Compiles `enabled` and writes it as the scope's next catalog generation. */
6127
- const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
6128
- const compilation = await compileReleaseCatalog({
6129
- strategy: scope.strategy,
6130
- releases: enabled.map(releaseRowToRelease)
6131
- });
6132
- const generation = (stored.generation ?? 0) + 1;
7625
+ /** The scope's next catalog generation, compiled as `compilation`. */
7626
+ const nextCatalog = (scope, stored, compilation, updatedAtMs) => {
7627
+ const generation = (stored.catalog?.generation ?? 0) + 1;
6133
7628
  if (!Number.isSafeInteger(generation)) fail$1("CATALOG_GENERATION_EXHAUSTED", `Catalog "${scope.scopeKey}" exhausted its generation counter`);
6134
- const catalog = {
7629
+ return {
6135
7630
  scope_key: scope.scopeKey,
6136
7631
  catalog_id: stored.catalog?.catalog_id ?? createUUIDv7(),
6137
7632
  strategy: scope.strategy,
@@ -6146,6 +7641,26 @@ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
6146
7641
  is_tombstone: compilation.payload.releaseDescriptors.length === 0,
6147
7642
  updated_at_ms: updatedAtMs
6148
7643
  };
7644
+ };
7645
+ /**
7646
+ * Compiles a scope's enabled releases. A catalog over the size limit is
7647
+ * refused naming its channel and platform, and what frees room in it.
7648
+ */
7649
+ const compileScope = async (scope, enabled) => {
7650
+ try {
7651
+ return await compileReleaseCatalog({
7652
+ strategy: scope.strategy,
7653
+ releases: enabled.map(releaseRowToRelease)
7654
+ });
7655
+ } catch (error) {
7656
+ if (!(error instanceof ReleaseCatalogCompilationError) || error.code !== "CATALOG_OVERSIZE") throw error;
7657
+ 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.`);
7658
+ }
7659
+ };
7660
+ /** Compiles `enabled` and writes it as the scope's next catalog generation. */
7661
+ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
7662
+ const compilation = await compileScope(scope, enabled);
7663
+ const catalog = nextCatalog(scope, stored, compilation, updatedAtMs);
6149
7664
  const { scope_key: _scopeKey, ...set } = catalog;
6150
7665
  if (stored.row === null) tx.create("release_catalogs", catalog);
6151
7666
  else tx.update("release_catalogs", stored.row, set);
@@ -6163,15 +7678,28 @@ const readCatalog = async (tx, scopeKey) => {
6163
7678
  catalog: row === null ? null : toCatalogRow(row)
6164
7679
  };
6165
7680
  };
7681
+ /**
7682
+ * Refuses to rewrite a catalog a later release compiled: this release's
7683
+ * compiler would drop the fields that release added.
7684
+ */
7685
+ const refuseLaterCatalog = (scope, catalog) => {
7686
+ 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.`);
7687
+ };
6166
7688
  /** A scope with releases and no compiled catalog lost its history. */
6167
7689
  const assertHistory = (stored, hasReleases) => {
6168
7690
  if (stored.catalog === null && hasReleases) fail$1("CATALOG_IDENTITY_MISSING", "Catalog history is missing. Restore its catalog row from backup before rebuilding or deploying.");
6169
7691
  };
6170
- /** One release change and its scope's next catalog, inside `tx`. */
6171
- const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
7692
+ /**
7693
+ * One release change and its scope's next catalog, inside `tx`. An insert
7694
+ * takes its channel and platform's next label from `labels`, after labeling
7695
+ * the releases a server of an earlier release wrote in the scope since its
7696
+ * last labeled one.
7697
+ */
7698
+ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }, labels) => {
6172
7699
  checkScope(scope);
6173
7700
  const stored = await readCatalog(tx, scope.scopeKey);
6174
- const enabled = await enabledReleases(tx, scope.scopeKey);
7701
+ refuseLaterCatalog(scope, stored.catalog);
7702
+ let enabled = await enabledReleases(tx, scope.scopeKey);
6175
7703
  if (bundle !== void 0) {
6176
7704
  insertBundle(tx, bundle.row);
6177
7705
  for (const patch of bundle.patches) tx.create("bundle_patches", patch);
@@ -6179,14 +7707,22 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
6179
7707
  let before = null;
6180
7708
  let release;
6181
7709
  if (change.operation === "insert") {
6182
- const latest = await latestReleaseId(tx, scope.scopeKey);
7710
+ if (labels === void 0) throw new Error("A release insert takes its label from an allocator.");
7711
+ const newest = await latestRelease(tx, scope.scopeKey);
7712
+ const latest = newest?.id ?? null;
6183
7713
  assertHistory(stored, latest !== null);
6184
7714
  const floor = [latest, bundle && isUUIDv7(bundle.row.id) ? bundle.row.id : null].filter((id) => id !== null).sort().at(-1);
6185
7715
  const id = change.row.id ?? createUUIDv7After(floor ?? null);
6186
7716
  if (latest !== null && id <= latest) fail$1("NON_MONOTONIC_RELEASE_ID", `Release "${id}" must sort after "${latest}"`);
7717
+ const given = await catchUpLabels(tx, labels, newest);
7718
+ if (given.size > 0) enabled = enabled.map((row) => given.has(row.id) ? {
7719
+ ...row,
7720
+ label: given.get(row.id)
7721
+ } : row);
6187
7722
  release = {
6188
7723
  ...change.row,
6189
- id
7724
+ id,
7725
+ label: await labels.next(scope.channelId, scope.platform)
6190
7726
  };
6191
7727
  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");
6192
7728
  tx.create("releases", release);
@@ -6199,8 +7735,9 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
6199
7735
  await tx.delete("releases", row);
6200
7736
  release = null;
6201
7737
  } else {
7738
+ const { label: _label, ...update } = change.update;
6202
7739
  const set = {
6203
- ...change.update,
7740
+ ...update,
6204
7741
  revision: before.revision + 1
6205
7742
  };
6206
7743
  tx.update("releases", row, set);
@@ -6228,29 +7765,84 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
6228
7765
  */
6229
7766
  const changeReleases = (db, inputs) => {
6230
7767
  if (new Set(inputs.map(({ scope }) => scope.scopeKey)).size !== inputs.length) fail$1("INVALID_SCOPE", "A batch cannot change one catalog scope twice");
6231
- return db.transaction(async (tx) => {
7768
+ return writeWithLabels(db, async (tx, labels) => {
6232
7769
  const results = [];
6233
- for (const input of inputs) results.push(await changeRelease(tx, input));
7770
+ for (const input of inputs) results.push(await changeRelease(tx, input, labels));
6234
7771
  return results;
6235
7772
  });
6236
7773
  };
7774
+ /**
7775
+ * Whether `current` is what the scope's enabled releases compile to, in the
7776
+ * fields this release compiles: a later release's catalog may add others.
7777
+ */
7778
+ const isCurrent = (scope, current, compilation) => {
7779
+ 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;
7780
+ if (current.catalog_hash === compilation.catalogHash) return true;
7781
+ const read = readCompiledCatalogPayload(current.payload);
7782
+ return read.fromLaterRelease && read.canonicalPayload === compilation.canonicalPayload;
7783
+ };
7784
+ /** A compiled payload with its descriptors' labels left out. */
7785
+ const withoutLabels = (payload) => {
7786
+ const parsed = JSON.parse(payload);
7787
+ return JSON.stringify({
7788
+ ...parsed,
7789
+ releaseDescriptors: (parsed.releaseDescriptors ?? []).map(({ label: _label, ...descriptor }) => descriptor)
7790
+ });
7791
+ };
7792
+ /**
7793
+ * Whether `projected` differs from `current` only by release labels, as a
7794
+ * catalog compiled before its releases had them does.
7795
+ */
7796
+ 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);
7797
+ /** The scope a catalog row names. */
7798
+ const catalogRowScope = (row) => ({
7799
+ channelId: row.channel_id,
7800
+ channelName: decodeChannelKey(row.channel_key),
7801
+ fingerprintHash: row.fingerprint_hash,
7802
+ platform: row.platform,
7803
+ scopeKey: row.scope_key,
7804
+ strategy: row.strategy
7805
+ });
7806
+ /**
7807
+ * What a rebuild of the scope's catalog would write, without writing: one
7808
+ * read of the catalog row and one of the scope's enabled releases. It needs
7809
+ * no transaction, whose guards would read the catalog again for each read
7810
+ * beneath it, nor the scope's newest release, which matters only to a scope
7811
+ * without a catalog row; that one is not found.
7812
+ */
7813
+ const preflightRebuild = async (db, scopeKey, updatedAtMs) => {
7814
+ const row = await db.findOne("release_catalogs", { scope_key: scopeKey });
7815
+ if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
7816
+ const current = toCatalogRow(row);
7817
+ const scope = catalogRowScope(current);
7818
+ checkScope(scope);
7819
+ const enabled = await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor)));
7820
+ const compilation = await compileScope(scope, enabled);
7821
+ const changed = !isCurrent(scope, current, compilation);
7822
+ const projectedCatalog = changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current;
7823
+ return {
7824
+ changed,
7825
+ labelsOnly: changed && differsInLabelsOnly(current, projectedCatalog),
7826
+ currentCatalog: current,
7827
+ diagnostics: compilation.diagnostics,
7828
+ projectedCatalog
7829
+ };
7830
+ };
6237
7831
  /** Recompiles a scope's catalog from its enabled releases inside `tx`; an unchanged catalog is not rewritten. */
6238
7832
  const rebuildScope = async (tx, scope, updatedAtMs) => {
6239
7833
  checkScope(scope);
6240
7834
  const stored = await readCatalog(tx, scope.scopeKey);
6241
- assertHistory(stored, await latestReleaseId(tx, scope.scopeKey) !== null);
7835
+ assertHistory(stored, await latestRelease(tx, scope.scopeKey) !== null);
6242
7836
  const enabled = await enabledReleases(tx, scope.scopeKey);
6243
- const compilation = await compileReleaseCatalog({
6244
- strategy: scope.strategy,
6245
- releases: enabled.map(releaseRowToRelease)
6246
- });
7837
+ const compilation = await compileScope(scope, enabled);
6247
7838
  const current = stored.catalog;
6248
- 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 {
7839
+ if (current !== null && isCurrent(scope, current, compilation)) return {
6249
7840
  catalog: current,
6250
7841
  current,
6251
7842
  changed: false,
6252
7843
  diagnostics: compilation.diagnostics
6253
7844
  };
7845
+ refuseLaterCatalog(scope, current);
6254
7846
  const written = await writeCatalog(tx, scope, stored, enabled, updatedAtMs);
6255
7847
  return {
6256
7848
  catalog: written.catalog,
@@ -6261,6 +7853,7 @@ const rebuildScope = async (tx, scope, updatedAtMs) => {
6261
7853
  };
6262
7854
  //#endregion
6263
7855
  //#region ../../packages/server/dist/core/operations.mjs
7856
+ const CATALOG_PAGE = 100;
6264
7857
  /** Carries a preflight's result out of the transaction it stops, so nothing is written. */
6265
7858
  var Preflight = class extends Error {
6266
7859
  result;
@@ -6349,14 +7942,7 @@ const mutationResult = ({ catalog, release }) => ({
6349
7942
  const catalogScope = async (tx, scopeKey) => {
6350
7943
  const row = await tx.findOne("release_catalogs", { scope_key: scopeKey });
6351
7944
  if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
6352
- return {
6353
- channelId: row.channel_id,
6354
- channelName: decodeChannelKey(row.channel_key),
6355
- fingerprintHash: row.fingerprint_hash,
6356
- platform: row.platform,
6357
- scopeKey: row.scope_key,
6358
- strategy: row.strategy
6359
- };
7945
+ return catalogRowScope(toCatalogRow(row));
6360
7946
  };
6361
7947
  /**
6362
7948
  * Core's typed writes: each runs in one engine transaction rooted at the
@@ -6385,7 +7971,11 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
6385
7971
  for (const { release } of deployments) if (!channels.has(release.channel)) channels.set(release.channel, await ensureChannel(release.channel));
6386
7972
  const platforms = /* @__PURE__ */ new Map();
6387
7973
  for (const deployment of deployments) {
6388
- if (!("bundleId" in deployment) || platforms.has(deployment.bundleId)) continue;
7974
+ if (!("bundleId" in deployment)) {
7975
+ for (const { baseBundleId } of deployment.bundle.patches ?? []) await refuseSandboxPatchBase(db, baseBundleId);
7976
+ continue;
7977
+ }
7978
+ if (platforms.has(deployment.bundleId)) continue;
6389
7979
  const row = await db.findOne("bundles", { id: deployment.bundleId });
6390
7980
  if (row === null) throw new DatabaseBundleNotFoundError(deployment.bundleId);
6391
7981
  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.`);
@@ -6495,7 +8085,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
6495
8085
  if (targetChannel.length === 0) throw new ReleaseManagementError("TARGET_RELEASE_INVALID", "Promotion requires a target channel.");
6496
8086
  const channel = await ensureChannel(targetChannel);
6497
8087
  const updatedAtMs = now();
6498
- return db.transaction(async (tx) => {
8088
+ return writeWithLabels(db, async (tx, labels) => {
6499
8089
  const { release: source, scope: sourceScope } = await loadTarget(tx, input);
6500
8090
  checkSource(source);
6501
8091
  const targetScope = scopeOf$1(channel, source.platform, source.fingerprint_hash);
@@ -6523,12 +8113,13 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
6523
8113
  },
6524
8114
  updatedAtMs
6525
8115
  }) : null;
8116
+ const { label: _label, ...copied } = source;
6526
8117
  const target = await changeRelease(tx, {
6527
8118
  scope: targetScope,
6528
8119
  change: {
6529
8120
  operation: "insert",
6530
8121
  row: {
6531
- ...source,
8122
+ ...copied,
6532
8123
  id: createUUIDv7After(floor ?? null, updatedAtMs),
6533
8124
  revision: 1,
6534
8125
  scope_key: targetScope.scopeKey,
@@ -6543,7 +8134,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
6543
8134
  }
6544
8135
  },
6545
8136
  updatedAtMs
6546
- });
8137
+ }, labels);
6547
8138
  return {
6548
8139
  source: moved === null ? null : mutationResult(moved),
6549
8140
  target: mutationResult(target)
@@ -6560,17 +8151,38 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
6560
8151
  };
6561
8152
  });
6562
8153
  },
6563
- preflightReleaseCatalogRebuild: (scopeKey) => {
6564
- const updatedAtMs = now();
6565
- return dryRun(db, async (tx) => {
6566
- const rebuilt = await rebuildScope(tx, await catalogScope(tx, scopeKey), updatedAtMs);
6567
- return {
6568
- changed: rebuilt.changed,
6569
- currentCatalog: rebuilt.current,
6570
- diagnostics: rebuilt.diagnostics,
6571
- projectedCatalog: rebuilt.catalog
6572
- };
6573
- });
8154
+ preflightReleaseCatalogRebuild: (scopeKey) => preflightRebuild(db, scopeKey, now()),
8155
+ fillReleaseLabels: async ({ dryRun = false, catalogs = true } = {}) => {
8156
+ let releases = 0;
8157
+ const pairs = await pendingLabelPairs(db);
8158
+ if (dryRun && pairs[0] !== void 0) await probeLabelSchema(db, pairs[0]);
8159
+ for (const pair of pairs) releases += await fillLabels(db, pair, { dryRun });
8160
+ let rebuilt = 0;
8161
+ if (catalogs) {
8162
+ let cursor;
8163
+ do {
8164
+ const page = await db.findMany("release_catalogs", {
8165
+ index: "all",
8166
+ where: {},
8167
+ limit: CATALOG_PAGE,
8168
+ ...cursor === void 0 ? {} : { cursor }
8169
+ });
8170
+ for (const row of page.rows) {
8171
+ if (row.is_tombstone) continue;
8172
+ const preflight = await preflightRebuild(db, row.scope_key, now()).catch(() => null);
8173
+ if (preflight === null || !preflight.labelsOnly) continue;
8174
+ rebuilt += 1;
8175
+ if (dryRun) continue;
8176
+ const updatedAtMs = now();
8177
+ await db.transaction((tx) => rebuildScope(tx, catalogRowScope(toCatalogRow(row)), updatedAtMs));
8178
+ }
8179
+ cursor = page.next;
8180
+ } while (cursor !== void 0);
8181
+ }
8182
+ return {
8183
+ releases,
8184
+ catalogs: rebuilt
8185
+ };
6574
8186
  },
6575
8187
  ensureChannel,
6576
8188
  deleteChannel: (id) => deleteChannel(db, id),
@@ -6589,7 +8201,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
6589
8201
  if (patches !== void 0) await replaceBundlePatches(tx, current, bundleToPatchRows({
6590
8202
  ...next,
6591
8203
  patches
6592
- }));
8204
+ }), (row) => refuseSandboxPatchBase(tx, row.base_bundle_id));
6593
8205
  }),
6594
8206
  deleteBundles: async (ids) => {
6595
8207
  try {
@@ -6651,6 +8263,7 @@ const createCoreApi = (db, storage, options = {}) => {
6651
8263
  ...reads,
6652
8264
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
6653
8265
  ...createNativeBuildApi(db, options),
8266
+ ...createIosDeviceApi(db, options),
6654
8267
  /** One read, which checks the schema settings first. */
6655
8268
  ready: async () => {
6656
8269
  await reads.listReleaseCatalogs({ limit: 1 });
@@ -6843,6 +8456,10 @@ const answer = async (operation) => {
6843
8456
  error: error.message
6844
8457
  }, status);
6845
8458
  }
8459
+ if (error instanceof ReleaseCatalogCompilationError && error.code === "CATALOG_OVERSIZE") return json$2({
8460
+ code: error.code,
8461
+ error: error.message
8462
+ }, 400);
6846
8463
  if (error instanceof DatabaseBundleNotFoundError) return json$2({
6847
8464
  code: "BUNDLE_NOT_FOUND",
6848
8465
  error: error.message
@@ -6862,18 +8479,22 @@ const LIMITS = {
6862
8479
  defaultValue: 50,
6863
8480
  maxValue: 500
6864
8481
  };
8482
+ /** The most IDs one request names: a lookup's, or a write's. */
8483
+ const MAX_IDS = 100;
6865
8484
  /** `order`, `cursor`, and `limit`: one keyset page. */
6866
- const keyset = (url, maxValue = LIMITS.maxValue) => {
6867
- const order = url.searchParams.get("order") ?? "desc";
8485
+ const keyset = (url, maxValue = LIMITS.maxValue, defaultOrder = "desc") => {
8486
+ const order = url.searchParams.get("order") ?? defaultOrder;
6868
8487
  if (order !== "asc" && order !== "desc") throw new HandlerBadRequestError("order must be 'asc' or 'desc'.");
6869
8488
  const limitParam = url.searchParams.get("limit");
6870
8489
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
6871
8490
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
6872
8491
  const cursor = url.searchParams.get("cursor");
8492
+ const through = url.searchParams.get("through");
6873
8493
  return {
6874
8494
  order,
6875
8495
  limit,
6876
- ...cursor === null ? {} : { after: cursor }
8496
+ ...cursor === null ? {} : { after: cursor },
8497
+ ...through === null ? {} : { through }
6877
8498
  };
6878
8499
  };
6879
8500
  /** A page and the cursor of the next one, when the page is full. */
@@ -6971,7 +8592,8 @@ const nativeBuildScopeOf = (url) => {
6971
8592
  const fingerprintHash = params.get("fingerprintHash");
6972
8593
  const appVersion = params.get("appVersion");
6973
8594
  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.");
6974
- return fingerprintHash !== null ? {
8595
+ const sandbox = sandboxScopeOf(params);
8596
+ const scope = fingerprintHash !== null ? {
6975
8597
  platform,
6976
8598
  channel,
6977
8599
  fingerprintHash,
@@ -6982,17 +8604,49 @@ const nativeBuildScopeOf = (url) => {
6982
8604
  fingerprintHash: null,
6983
8605
  appVersion
6984
8606
  };
8607
+ return sandbox === null ? scope : {
8608
+ ...scope,
8609
+ sandbox
8610
+ };
8611
+ };
8612
+ /** The query parameters a sandbox lookup names, all four or none. */
8613
+ const SANDBOX_SCOPE_PARAMS = [
8614
+ "sandboxAppId",
8615
+ "sandboxUrlScheme",
8616
+ "artifactKind",
8617
+ "distribution"
8618
+ ];
8619
+ /**
8620
+ * A lookup's sandbox scope: null without one, and a bad request for one
8621
+ * named in part. Core checks each value.
8622
+ */
8623
+ const sandboxScopeOf = (params) => {
8624
+ const [appId, urlScheme, artifactKind, distribution] = SANDBOX_SCOPE_PARAMS.map((name) => params.get(name));
8625
+ const named = [
8626
+ appId,
8627
+ urlScheme,
8628
+ artifactKind,
8629
+ distribution
8630
+ ].filter((value) => value !== null).length;
8631
+ if (named === 0) return null;
8632
+ if (named !== SANDBOX_SCOPE_PARAMS.length) throw new HandlerBadRequestError(`A sandbox build lookup needs ${SANDBOX_SCOPE_PARAMS.join(", ")}.`);
8633
+ return {
8634
+ appId,
8635
+ urlScheme,
8636
+ artifactKind,
8637
+ distribution
8638
+ };
6985
8639
  };
6986
8640
  /** A native build or scope core refuses: a bad request. */
6987
8641
  const refusingInvalid = async (operation) => {
6988
8642
  try {
6989
8643
  return await operation();
6990
8644
  } catch (error) {
6991
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
8645
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
6992
8646
  throw error;
6993
8647
  }
6994
8648
  };
6995
- 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));
8649
+ 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));
6996
8650
  const scopeKeyOf = (params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "";
6997
8651
  /** Every admin route's handler, by the name `ADMIN_ROUTES` mounts it under. */
6998
8652
  const createAdminRouteHandlers = () => ({
@@ -7025,12 +8679,40 @@ const createAdminRouteHandlers = () => ({
7025
8679
  const rows = await core.listReleaseCatalogs(input);
7026
8680
  return page(rows, input, (row) => row.scope_key);
7027
8681
  }),
7028
- /** With `name`, the one channel of that name: 1 read. */
8682
+ /** Up to 100 scope keys that have releases, after `cursor`: one seek each. */
8683
+ listReleaseScopeKeys: onCore(async (core, request) => {
8684
+ const input = keyset(new URL(request.url), 100, "asc");
8685
+ if (input.order !== "asc" || input.through !== void 0) throw new HandlerBadRequestError("Release scopes are listed ascending, by limit and cursor only.");
8686
+ const rows = await core.listReleaseScopeKeys({
8687
+ limit: input.limit,
8688
+ ...input.after === void 0 ? {} : { after: input.after }
8689
+ });
8690
+ return page(rows, input, (scopeKey) => scopeKey);
8691
+ }),
8692
+ /**
8693
+ * With `name`, the one channel of that name: 1 read. With `ids`, the
8694
+ * channels of up to 100 IDs: 1 batch read. With `limit` or `cursor`, one
8695
+ * page by name. With none, every channel, as servers before pages answered.
8696
+ */
7029
8697
  getChannels: onCore(async (core, request) => {
7030
- const name = new URL(request.url).searchParams.get("name");
7031
- if (name === null) return json$2({ data: await core.listChannels() });
7032
- const channel = await core.findChannelByName(name);
7033
- return channel === null ? notFound() : json$2({ data: channel });
8698
+ const url = new URL(request.url);
8699
+ const name = url.searchParams.get("name");
8700
+ if (name !== null) {
8701
+ const channel = await core.findChannelByName(name);
8702
+ return channel === null ? notFound() : json$2({ data: channel });
8703
+ }
8704
+ const ids = url.searchParams.get("ids");
8705
+ if (ids !== null) {
8706
+ const list = ids.split(",").filter((id) => id.length > 0);
8707
+ if (list.length === 0 || list.length > MAX_IDS) throw new HandlerBadRequestError(`Channels by ID take ids=<channel id>,... with 1 to ${MAX_IDS} ids.`);
8708
+ return json$2({ data: await core.getChannels(list) });
8709
+ }
8710
+ if (url.searchParams.has("limit") || url.searchParams.has("cursor")) {
8711
+ const input = keyset(url, LIMITS.maxValue, "asc");
8712
+ const rows = await core.listChannels(input);
8713
+ return page(rows, input, (row) => row.name);
8714
+ }
8715
+ return json$2({ data: await core.listChannels() });
7034
8716
  }),
7035
8717
  /** The channel named in the body, created when missing. */
7036
8718
  createChannel: onCore(async (core, request) => {
@@ -7072,15 +8754,40 @@ const createAdminRouteHandlers = () => ({
7072
8754
  return row === null ? notFound() : json$2({ data: row });
7073
8755
  }),
7074
8756
  rebuildReleaseCatalog: onCore(async (core, _request, params) => json$2({ data: await core.rebuildReleaseCatalog(scopeKeyOf(params)) })),
8757
+ /**
8758
+ * The release a label names, or `null`: never 404, which tells a client
8759
+ * the server has no such route.
8760
+ */
8761
+ getReleaseByLabel: onCore(async (core, request) => {
8762
+ const url = new URL(request.url);
8763
+ const channel = url.searchParams.get("channel");
8764
+ const platform = platformOf(url);
8765
+ const label = Number(url.searchParams.get("label"));
8766
+ 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.");
8767
+ return json$2({ data: await core.getReleaseByLabel({
8768
+ channel,
8769
+ platform,
8770
+ label
8771
+ }) });
8772
+ }),
8773
+ fillReleaseLabels: onCore(async (core, request) => {
8774
+ const body = await request.json().catch(() => ({}));
8775
+ const input = body !== null && typeof body === "object" ? body : {};
8776
+ return json$2({ data: await core.fillReleaseLabels({
8777
+ dryRun: input.dryRun === true,
8778
+ catalogs: input.catalogs !== false
8779
+ }) });
8780
+ }),
7075
8781
  updateBundle: onCore(async (core, request, params) => {
7076
8782
  const bundleId = requireRouteParam(params, "id");
7077
- await core.updateBundle(bundleId, bundleUpdateOf(await request.json(), bundleId));
8783
+ const update = bundleUpdateOf(await request.json(), bundleId);
8784
+ await refusingInvalid(() => core.updateBundle(bundleId, update));
7078
8785
  return noContent();
7079
8786
  }),
7080
8787
  countBundles: onCore(async (core, request) => json$2({ data: await core.countBundles(platformOf(new URL(request.url))) })),
7081
8788
  countBundleChildren: onCore(async (core, request) => {
7082
8789
  const ids = (new URL(request.url).searchParams.get("ids") ?? "").split(",").filter((id) => id.length > 0);
7083
- if (ids.length === 0 || ids.length > 100) throw new HandlerBadRequestError("Bundle child counts take ids=<bundle id>,... with 1 to 100 ids.");
8790
+ if (ids.length === 0 || ids.length > MAX_IDS) throw new HandlerBadRequestError(`Bundle child counts take ids=<bundle id>,... with 1 to ${MAX_IDS} ids.`);
7084
8791
  return json$2({ data: await core.countBundleChildren(ids) });
7085
8792
  }),
7086
8793
  listBundleChildren: onCore(async (core, request, params) => {
@@ -7098,7 +8805,7 @@ const createAdminRouteHandlers = () => ({
7098
8805
  deployReleases: onCore(async (core, request) => {
7099
8806
  const { deployments } = await body(request);
7100
8807
  if (!Array.isArray(deployments) || deployments.length === 0 || !deployments.every(isDeployment)) throw new HandlerBadRequestError("Deploy needs deployments, each a bundle and its release policy.");
7101
- return json$2({ data: await core.deploy(deployments) }, 201);
8808
+ return json$2({ data: await refusingInvalid(() => core.deploy(deployments)) }, 201);
7102
8809
  }),
7103
8810
  promoteRelease: onCore(async (core, request, params) => {
7104
8811
  const input = await body(request);
@@ -7121,9 +8828,22 @@ const createAdminRouteHandlers = () => ({
7121
8828
  const url = new URL(request.url);
7122
8829
  const scope = nativeBuildScopeOf(url);
7123
8830
  const buildKey = url.searchParams.get("buildKey");
7124
- return json$2({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
8831
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
8832
+ const kind = url.searchParams.get("kind");
8833
+ const options = {
8834
+ ...buildKey === null ? {} : { buildKey },
8835
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
8836
+ ...builtInOlderThan === null ? {} : { builtInOlderThan },
8837
+ ...kind === null ? {} : { artifactKind: kind }
8838
+ };
8839
+ return json$2({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
8840
+ }),
8841
+ findNativeBuildSibling: onCore(async (core, _request, params) => {
8842
+ const build = await core.getNativeBuild(requireRouteParam(params, "id"));
8843
+ return json$2({ data: build === null ? null : await core.findNativeBuildSibling(build) });
7125
8844
  }),
7126
8845
  getNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
8846
+ findNativeBuildByBuiltInBundle: onCore(async (core, _request, params) => json$2({ data: await core.findNativeBuildByBuiltInBundle(requireRouteParam(params, "bundleId")) })),
7127
8847
  listNativeBuilds: onCore(async (core, request) => {
7128
8848
  const url = new URL(request.url);
7129
8849
  const input = keyset(url);
@@ -7135,14 +8855,97 @@ const createAdminRouteHandlers = () => ({
7135
8855
  }),
7136
8856
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
7137
8857
  const input = await body(request);
7138
- 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.");
8858
+ 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.");
7139
8859
  const submission = {
7140
8860
  destination: input.destination,
7141
8861
  version: input.version
7142
8862
  };
7143
8863
  return json$2({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
7144
8864
  }),
8865
+ markNativeBuild: onCore(async (core, request, params) => {
8866
+ const input = await body(request);
8867
+ if (!isRecord$5(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
8868
+ const mark = { storeBuild: input.storeBuild };
8869
+ return json$2({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
8870
+ }),
7145
8871
  deleteNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
8872
+ listIosDevices: onCore(async (core, request) => {
8873
+ const url = new URL(request.url);
8874
+ const input = keyset(url);
8875
+ const status = url.searchParams.get("status");
8876
+ return page(await refusingInvalid(() => core.listIosDevices({
8877
+ ...input,
8878
+ ...status === null ? {} : { status }
8879
+ })), input, ({ id }) => id);
8880
+ }),
8881
+ findIosDevice: onCore(async (core, _request, params) => json$2({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
8882
+ requestIosDevice: onCore(async (core, request) => {
8883
+ const input = await body(request);
8884
+ 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.");
8885
+ const device = {
8886
+ udid: input.udid,
8887
+ name: input.name,
8888
+ requestedBy: input.requestedBy
8889
+ };
8890
+ return json$2({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
8891
+ }),
8892
+ approveIosDevice: onCore(async (core, request, params) => {
8893
+ const input = await body(request);
8894
+ 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.");
8895
+ const approval = {
8896
+ approvedBy: input.approvedBy,
8897
+ ...input.name === void 0 ? {} : { name: input.name }
8898
+ };
8899
+ return json$2({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
8900
+ }),
8901
+ renameIosDevice: onCore(async (core, request, params) => {
8902
+ const input = await body(request);
8903
+ if (!isText$2(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
8904
+ const name = input.name;
8905
+ return json$2({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
8906
+ }),
8907
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
8908
+ const input = await body(request);
8909
+ const seen = input.seen;
8910
+ 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.");
8911
+ const outcome = {
8912
+ id: requireRouteParam(params, "id"),
8913
+ seen: {
8914
+ status: seen.status,
8915
+ approvedAtMs: seen.approvedAtMs
8916
+ },
8917
+ issuerId: input.issuerId,
8918
+ outcome: input.outcome,
8919
+ ...input.reason === void 0 ? {} : { reason: input.reason }
8920
+ };
8921
+ return json$2({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
8922
+ }),
8923
+ claimIosDeviceAccount: onCore(async (core, request) => {
8924
+ const { issuerId } = await body(request);
8925
+ if (!isText$2(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
8926
+ return json$2({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
8927
+ }),
8928
+ findIosDeviceAccount: onCore(async (core) => json$2({ data: await core.findIosDeviceAccount() })),
8929
+ markIosDevicesInBuild: onCore(async (core, request) => {
8930
+ const { buildId, ids } = await body(request);
8931
+ 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.");
8932
+ if (ids.length > MAX_IDS) throw new HandlerBadRequestError(`Marking iOS devices in a build takes at most ${MAX_IDS} ids a request.`);
8933
+ await core.markIosDevicesInBuild({
8934
+ buildId,
8935
+ ids
8936
+ });
8937
+ return noContent();
8938
+ }),
8939
+ deleteIosDevice: onCore(async (core, request, params) => {
8940
+ const url = new URL(request.url);
8941
+ const status = url.searchParams.get("status");
8942
+ const requestedBy = url.searchParams.get("requestedBy");
8943
+ const only = {
8944
+ ...status === null ? {} : { status },
8945
+ ...requestedBy === null ? {} : { requestedBy }
8946
+ };
8947
+ return json$2({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
8948
+ }),
7146
8949
  deleteBundles: onCore(async (core, request) => {
7147
8950
  const { ids } = await body(request);
7148
8951
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -7197,6 +9000,21 @@ const ADMIN_ROUTES = [
7197
9000
  path: "/release-catalogs",
7198
9001
  handler: "listReleaseCatalogs"
7199
9002
  },
9003
+ {
9004
+ method: "GET",
9005
+ path: "/release-scopes",
9006
+ handler: "listReleaseScopeKeys"
9007
+ },
9008
+ {
9009
+ method: "GET",
9010
+ path: "/release-labels",
9011
+ handler: "getReleaseByLabel"
9012
+ },
9013
+ {
9014
+ method: "POST",
9015
+ path: "/release-labels/fill",
9016
+ handler: "fillReleaseLabels"
9017
+ },
7200
9018
  {
7201
9019
  method: "POST",
7202
9020
  path: "/release-catalogs/:scopeKey/rebuild",
@@ -7272,6 +9090,16 @@ const ADMIN_ROUTES = [
7272
9090
  path: "/native-builds/latest",
7273
9091
  handler: "findNativeBuild"
7274
9092
  },
9093
+ {
9094
+ method: "GET",
9095
+ path: "/native-builds/built-in/:bundleId",
9096
+ handler: "findNativeBuildByBuiltInBundle"
9097
+ },
9098
+ {
9099
+ method: "GET",
9100
+ path: "/native-builds/:id/sibling",
9101
+ handler: "findNativeBuildSibling"
9102
+ },
7275
9103
  {
7276
9104
  method: "GET",
7277
9105
  path: "/native-builds/:id",
@@ -7287,10 +9115,65 @@ const ADMIN_ROUTES = [
7287
9115
  path: "/native-builds/:id/submission",
7288
9116
  handler: "recordNativeBuildSubmission"
7289
9117
  },
9118
+ {
9119
+ method: "POST",
9120
+ path: "/native-builds/:id/store-build",
9121
+ handler: "markNativeBuild"
9122
+ },
7290
9123
  {
7291
9124
  method: "DELETE",
7292
9125
  path: "/native-builds/:id",
7293
9126
  handler: "deleteNativeBuild"
9127
+ },
9128
+ {
9129
+ method: "GET",
9130
+ path: "/ios-devices",
9131
+ handler: "listIosDevices"
9132
+ },
9133
+ {
9134
+ method: "POST",
9135
+ path: "/ios-devices",
9136
+ handler: "requestIosDevice"
9137
+ },
9138
+ {
9139
+ method: "GET",
9140
+ path: "/ios-devices/udid/:udid",
9141
+ handler: "findIosDevice"
9142
+ },
9143
+ {
9144
+ method: "POST",
9145
+ path: "/ios-devices/in-build",
9146
+ handler: "markIosDevicesInBuild"
9147
+ },
9148
+ {
9149
+ method: "GET",
9150
+ path: "/ios-devices/account",
9151
+ handler: "findIosDeviceAccount"
9152
+ },
9153
+ {
9154
+ method: "POST",
9155
+ path: "/ios-devices/account",
9156
+ handler: "claimIosDeviceAccount"
9157
+ },
9158
+ {
9159
+ method: "POST",
9160
+ path: "/ios-devices/:id/approval",
9161
+ handler: "approveIosDevice"
9162
+ },
9163
+ {
9164
+ method: "POST",
9165
+ path: "/ios-devices/:id/outcome",
9166
+ handler: "recordIosDeviceOutcome"
9167
+ },
9168
+ {
9169
+ method: "PATCH",
9170
+ path: "/ios-devices/:id",
9171
+ handler: "renameIosDevice"
9172
+ },
9173
+ {
9174
+ method: "DELETE",
9175
+ path: "/ios-devices/:id",
9176
+ handler: "deleteIosDevice"
7294
9177
  }
7295
9178
  ];
7296
9179
  //#endregion
@@ -7313,9 +9196,9 @@ const CATALOG_CACHE_CONTROL = "public, max-age=0, s-maxage=5";
7313
9196
  * background. `stale-if-error=0` keeps origin errors visible: without it,
7314
9197
  * Cloudflare serves a stale copy on error indefinitely.
7315
9198
  *
7316
- * A device can see a catalog up to 15 seconds after a deploy or a Roll back
7317
- * replaced it: the origin's 5-second catalog memo, then 5 seconds fresh and
7318
- * 5 stale at the CDN. A revoked API key can read a cached catalog up to
9199
+ * A device can see a catalog, or a scope's lack of one, up to 15 seconds
9200
+ * after a deploy or a Roll back replaced it: the origin's 5-second catalog
9201
+ * memo, then 5 seconds fresh and 5 stale at the CDN. A revoked API key can read a cached catalog up to
7319
9202
  * 10 seconds. Devices and caches that don't read the header keep
7320
9203
  * `Cache-Control`.
7321
9204
  */
@@ -7394,38 +9277,53 @@ const catalogResponse = async (catalog, request) => {
7394
9277
  };
7395
9278
  const createReleaseCatalogRouteHandlers = () => {
7396
9279
  const cache = /* @__PURE__ */ new Map();
9280
+ const evict = (insertedHit) => {
9281
+ const now = Date.now();
9282
+ let oldestMiss;
9283
+ let oldest;
9284
+ for (const [key, entry] of cache) if (entry.expiresAt <= now) cache.delete(key);
9285
+ else {
9286
+ if (entry.row === null) oldestMiss ??= key;
9287
+ oldest ??= key;
9288
+ }
9289
+ if (cache.size <= ORIGIN_CACHE_MAX_ENTRIES) return;
9290
+ const victim = oldestMiss ?? (insertedHit ? oldest : void 0);
9291
+ if (victim !== void 0) cache.delete(victim);
9292
+ };
7397
9293
  const inFlight = /* @__PURE__ */ new Map();
7398
- const loadCatalog = async (key, load) => {
7399
- const cached = cache.get(key);
9294
+ const loadRow = async (scopeKey, load) => {
9295
+ const cached = cache.get(scopeKey);
7400
9296
  if (cached !== void 0 && cached.expiresAt > Date.now()) {
7401
- cache.delete(key);
7402
- cache.set(key, cached);
7403
- return cached.catalog;
9297
+ cache.delete(scopeKey);
9298
+ cache.set(scopeKey, cached);
9299
+ return cached.row;
7404
9300
  }
7405
- if (cached !== void 0) cache.delete(key);
7406
- const pending = inFlight.get(key);
9301
+ if (cached !== void 0) cache.delete(scopeKey);
9302
+ const pending = inFlight.get(scopeKey);
7407
9303
  if (pending !== void 0) return pending;
7408
- const next = load().then((catalog) => {
7409
- if (catalog !== null) {
7410
- cache.set(key, {
7411
- catalog,
7412
- expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
7413
- });
7414
- while (cache.size > ORIGIN_CACHE_MAX_ENTRIES) {
7415
- const oldestKey = cache.keys().next().value;
7416
- if (oldestKey === void 0) break;
7417
- cache.delete(oldestKey);
7418
- }
7419
- }
7420
- return catalog;
9304
+ const next = load().then((row) => {
9305
+ cache.set(scopeKey, {
9306
+ row,
9307
+ expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
9308
+ });
9309
+ if (cache.size > ORIGIN_CACHE_MAX_ENTRIES) evict(row !== null);
9310
+ return row;
7421
9311
  });
7422
- inFlight.set(key, next);
9312
+ inFlight.set(scopeKey, next);
7423
9313
  try {
7424
9314
  return await next;
7425
9315
  } finally {
7426
- inFlight.delete(key);
9316
+ inFlight.delete(scopeKey);
7427
9317
  }
7428
9318
  };
9319
+ const loadCatalog = async (core, input) => {
9320
+ const scopeKey = releaseCatalogScopeKeyOf(input);
9321
+ const parsed = await loadRow(scopeKey, async () => {
9322
+ const row = await core.getReleaseCatalogRow(scopeKey);
9323
+ return row === null ? null : parseReleaseCatalogRow(row);
9324
+ });
9325
+ return projectParsedReleaseCatalogRow(parsed, input, scopeKey);
9326
+ };
7429
9327
  return {
7430
9328
  appVersionReleaseCatalog: async (params, request, { core }) => {
7431
9329
  const rawAppVersion = requireRouteParam(params, "appVersion");
@@ -7439,7 +9337,7 @@ const createReleaseCatalogRouteHandlers = () => {
7439
9337
  };
7440
9338
  const invalid = invalidScope(input);
7441
9339
  if (invalid) return invalid;
7442
- return catalogResponse(await loadCatalog(`app-version:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
9340
+ return catalogResponse(await loadCatalog(core, input), request);
7443
9341
  },
7444
9342
  fingerprintReleaseCatalog: async (params, request, { core }) => {
7445
9343
  const input = {
@@ -7450,7 +9348,7 @@ const createReleaseCatalogRouteHandlers = () => {
7450
9348
  };
7451
9349
  const invalid = invalidScope(input);
7452
9350
  if (invalid) return invalid;
7453
- return catalogResponse(await loadCatalog(`fingerprint:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
9351
+ return catalogResponse(await loadCatalog(core, input), request);
7454
9352
  },
7455
9353
  artifactV2: async (params, _request, { core }) => {
7456
9354
  const info = await core.getArtifactInfo(requireRouteParam(params, "targetBundleId"), requireRouteParam(params, "currentBundleId"), 2);
@@ -7578,7 +9476,8 @@ const createRequestHandler = ({ api, clientPolicy, privateResponses = false, rou
7578
9476
  let authenticated;
7579
9477
  try {
7580
9478
  authenticated = await clientPolicy.authenticate(request);
7581
- } catch {
9479
+ } catch (error) {
9480
+ console.error("Hot Updater client authentication error:", error);
7582
9481
  return errorResponse("Service unavailable", 503);
7583
9482
  }
7584
9483
  if (!authenticated) return errorResponse("Unauthorized", 401);
@@ -8123,21 +10022,29 @@ const isLaunch = (row) => {
8123
10022
  const kinds = metadataOf(row).change?.kinds ?? [];
8124
10023
  return kinds.includes("bundle") && !kinds.includes("first_seen") && row.to_release_id !== null;
8125
10024
  };
10025
+ const sideRef = (key, releaseId, bundleId) => key === "release" ? releaseId ?? bundleId : bundleId;
8126
10026
  /**
8127
10027
  * The bundle a stored row's bundle filter matches: `from:<bundle>` for a
8128
10028
  * recovery; `to:<bundle>` for a download, an apply, and an update failure;
8129
10029
  * `on:<bundle>` for an UNCHANGED row that launched a bundle (`isLaunch`), a
8130
10030
  * key no other row uses. None for a failed check, which targets no bundle, a
8131
- * late row, or any other UNCHANGED row.
10031
+ * late row, or any other UNCHANGED row. Each names its bundle by `key`.
8132
10032
  */
8133
- const bundleRefsOf = (row) => {
10033
+ const bundleRefsOf = (row, key = "release") => {
8134
10034
  if (isFailedCheck(row) || isLateEvent(row)) return [];
8135
- if (row.type === "RECOVERED") return [`from:${row.from_bundle_id}`];
8136
- if (row.type === "UNCHANGED") return isLaunch(row) ? [`on:${row.to_bundle_id}`] : [];
8137
- return [`to:${row.to_bundle_id}`];
10035
+ if (row.type === "RECOVERED") return [`from:${sideRef(key, row.from_release_id, row.from_bundle_id)}`];
10036
+ if (row.type === "UNCHANGED") return isLaunch(row) ? [`on:${sideRef(key, row.to_release_id, row.to_bundle_id)}`] : [];
10037
+ return [`to:${sideRef(key, row.to_release_id, row.to_bundle_id)}`];
8138
10038
  };
10039
+ /**
10040
+ * The hourly outcome rows a stored row counts in, as `[type, bundle ref]`:
10041
+ * its bundle filter's (`bundleRefsOf`), and a download that a launch or
10042
+ * crash implied, in its bundle's download hour, so the download series
10043
+ * covers what the release's downloads count.
10044
+ */
10045
+ 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)}`]] : []];
8139
10046
  /** The key a bundle filter reads, as `bundleRefsOf` writes it. */
8140
- const bundleRefOfFilter = (filter) => filter.type === "RECOVERED" ? `from:${filter.fromBundleId}` : filter.type === "UNCHANGED" ? `on:${filter.toBundleId}` : `to:${filter.toBundleId}`;
10047
+ const bundleRefOfFilter = (filter) => filter.type === "RECOVERED" ? `from:${filter.fromReleaseId}` : filter.type === "UNCHANGED" ? `on:${filter.toReleaseId}` : `to:${filter.toReleaseId}`;
8141
10048
  /**
8142
10049
  * Downloads, applies, recoveries, update failures, and the UNCHANGED
8143
10050
  * reports that changed what their installation runs, whole. An UNCHANGED
@@ -8202,7 +10109,11 @@ const bundleEvents = (days) => defineTable({
8202
10109
  type: "string",
8203
10110
  compute: (row) => MOVEMENTS.has(row.type) ? row.install_id : null
8204
10111
  },
8205
- /** The bundle a bundle filter matches (`bundleRefsOf`). */
10112
+ /**
10113
+ * The bundle a bundle filter matches (`bundleRefsOf`), by release.
10114
+ * Rows a 1.1 server wrote name the artifact until
10115
+ * `backfillReleaseRefs` rewrites them.
10116
+ */
8206
10117
  bundle_ref: {
8207
10118
  type: "string",
8208
10119
  multi: true,
@@ -8521,7 +10432,13 @@ const insightsBuiltinDistribution = (retention) => defineAggregate({
8521
10432
  },
8522
10433
  retention
8523
10434
  });
8524
- /** Latest events by the bundle they came from or went to, bucketed like the distribution. */
10435
+ /**
10436
+ * Latest events by the artifact they came from or went to, bucketed like
10437
+ * the distribution, as 1.1 servers wrote them. Nothing writes or reads it
10438
+ * since a bundle's installations come from `insights_distribution`, which
10439
+ * names the release; it stays declared so retention still empties the rows
10440
+ * a 1.1 server wrote.
10441
+ */
8525
10442
  const insightsLatestByBundle = (retention) => defineAggregate({
8526
10443
  platform: {
8527
10444
  type: "string",
@@ -8569,7 +10486,9 @@ const insightsLatestByBundle = (retention) => defineAggregate({
8569
10486
  * Stored events by outcome and the bundle a bundle filter matches, a row an
8570
10487
  * hour, which a failed check has none of; and every stored event, a row a UTC
8571
10488
  * day (`DAILY_EVENTS`). Bundle counts sum the hourly rows, and event lists
8572
- * read either to skip days without events.
10489
+ * read either to skip days without events. `bundle_ref` names the release
10490
+ * (`outcomeRefsOf`); a 1.1 server's rows name the artifact until
10491
+ * `backfillReleaseRefs` moves their counts.
8573
10492
  */
8574
10493
  const insightsOutcomes = (retention) => defineAggregate({
8575
10494
  platform: {
@@ -8648,6 +10567,120 @@ const createInsightsSchema = ({ rawDays, dailyDays } = DEFAULT_INSIGHTS_RETENTIO
8648
10567
  };
8649
10568
  createInsightsSchema();
8650
10569
  //#endregion
10570
+ //#region ../insights/dist/server/backfill.mjs
10571
+ /**
10572
+ * Stored events read a page, and rewritten up to `BATCH` a transaction. A
10573
+ * run keeps one batch size, which only shrinks, halving whenever a store
10574
+ * refuses a batch:
10575
+ * - as too large, before writing anything: DynamoDB's 100 items hold fewer
10576
+ * than 25 rewrites with their index copies and counts;
10577
+ * - as busy through the transaction's retries: a write-capacity cap, such as
10578
+ * the 100 write units a second `hot-updater init` gives a DynamoDB table,
10579
+ * throttles a transaction that costs more than the cap admits, about 13
10580
+ * rewrites of 2 KB events there, and refuses every write for seconds once
10581
+ * the run has spent it.
10582
+ * After a busy refusal the run also waits before it writes again, `PAUSE_MS`
10583
+ * and twice as long after each further one, so the cap refills; a commit
10584
+ * starts the waits over. A batch the store still refuses after the
10585
+ * `MAX_PAUSE_MS` wait, or a one-event batch too large to write, fails the
10586
+ * run, which a rerun resumes.
10587
+ */
10588
+ const PAGE$1 = 500;
10589
+ const BATCH = 25;
10590
+ const PAUSE_MS = 1e3;
10591
+ const MAX_PAUSE_MS = 32e3;
10592
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
10593
+ const sameRefs = (stored, refs) => {
10594
+ const values = Array.isArray(stored) ? stored : [];
10595
+ return values.length === refs.length && values.every((value) => refs.includes(value));
10596
+ };
10597
+ /**
10598
+ * Whether a stored event still names its artifact, as a 1.1 server wrote
10599
+ * it: its stored refs are the artifact's and differ from the release's. Its
10600
+ * stored refs are how its outcome rows counted it, so they are what a
10601
+ * rewrite moves, and a rewritten event reads as done.
10602
+ */
10603
+ const namesArtifact = (row) => {
10604
+ const byKey = (key) => bundleRefsOf(row, key);
10605
+ return sameRefs(row.bundle_ref, byKey("artifact")) && !sameRefs(row.bundle_ref, byKey("release"));
10606
+ };
10607
+ /**
10608
+ * Rewrites the stored events in the raw period whose refs name their
10609
+ * artifact, as 1.1 servers wrote them, to name their release, and moves
10610
+ * their hourly outcome counts with them, each event in the transaction that
10611
+ * rewrites it. Each event carries its own release IDs, so two releases of
10612
+ * one artifact in one scope come apart; an event without a release ID keeps
10613
+ * the bundle ID it reports, as new events do.
10614
+ *
10615
+ * It reads every stored event once and writes only those still to move, so
10616
+ * an interrupted run can run again. `hot-updater db migrate` and `hot-updater
10617
+ * init` run it once a database: when it completes they record the settings
10618
+ * row `insights.releaseRefs`, and later runs read no event. Installation
10619
+ * gauges need nothing: they name releases already.
10620
+ */
10621
+ const backfillReleaseRefs = async (db, now, { rawDays }, { dryRun = false } = {}) => {
10622
+ const today = now() - now() % DAY_MS$1;
10623
+ let events = 0;
10624
+ let size = BATCH;
10625
+ let paused = 0;
10626
+ const move = async (stale) => {
10627
+ if (dryRun) {
10628
+ events += stale.length;
10629
+ return;
10630
+ }
10631
+ for (let start = 0; start < stale.length;) {
10632
+ const candidates = stale.slice(start, start + size);
10633
+ try {
10634
+ events += await rewrite(candidates);
10635
+ start += candidates.length;
10636
+ paused = 0;
10637
+ } catch (error) {
10638
+ if (error instanceof DatabaseConstraintError && error.reason === "too_large" && candidates.length > 1) {
10639
+ size = Math.ceil(candidates.length / 2);
10640
+ continue;
10641
+ }
10642
+ if (!isDatabaseBusyError(error) || paused >= MAX_PAUSE_MS) throw error;
10643
+ size = Math.ceil(candidates.length / 2);
10644
+ paused = paused === 0 ? PAUSE_MS : paused * 2;
10645
+ await sleep(paused);
10646
+ }
10647
+ }
10648
+ };
10649
+ const rewrite = (candidates) => db.transaction(async (tx) => {
10650
+ const rows = await Promise.all(candidates.map(({ id }) => tx.findOne("bundle_events", { id })));
10651
+ let moved = 0;
10652
+ for (const row of rows) {
10653
+ if (row === null || !namesArtifact(row)) continue;
10654
+ tx.update("bundle_events", row, {});
10655
+ const outcome = (ref, delta) => tx.aggregate("insights_outcomes", {
10656
+ platform: row.platform,
10657
+ channel: row.channel,
10658
+ type: ref[0],
10659
+ bundle_ref: ref[1],
10660
+ bucket_start_ms: row.received_at_ms - row.received_at_ms % HOUR_MS$1
10661
+ }, { events: delta }, { shardBy: row.install_id });
10662
+ for (const ref of outcomeRefsOf(row, "artifact")) outcome(ref, -1);
10663
+ for (const ref of outcomeRefsOf(row, "release")) outcome(ref, 1);
10664
+ moved += 1;
10665
+ }
10666
+ return moved;
10667
+ });
10668
+ for (let day = today - rawDays * DAY_MS$1; day <= today; day += DAY_MS$1) {
10669
+ let cursor;
10670
+ do {
10671
+ const page = await db.findMany("bundle_events", {
10672
+ index: "byDay",
10673
+ where: { day },
10674
+ limit: PAGE$1,
10675
+ ...cursor === void 0 ? {} : { cursor }
10676
+ });
10677
+ await move(page.rows.filter(namesArtifact));
10678
+ cursor = page.next;
10679
+ } while (cursor !== void 0);
10680
+ }
10681
+ return { events };
10682
+ };
10683
+ //#endregion
8651
10684
  //#region ../insights/dist/server/eventRow.mjs
8652
10685
  const CHANGE_KINDS = /* @__PURE__ */ new Set([
8653
10686
  "first_seen",
@@ -8744,7 +10777,7 @@ const isBundleFilter = (value, withKind = false) => {
8744
10777
  "type",
8745
10778
  ...withKind ? ["kind"] : []
8746
10779
  ];
8747
- 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"]);
10780
+ 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"]);
8748
10781
  };
8749
10782
  const isEventFilter = (value) => {
8750
10783
  if (!isRecord$3(value)) return false;
@@ -8845,20 +10878,24 @@ const createValidatedInsightsModel = (model) => ({
8845
10878
  if (!isRecord$3(input) || !hasOnlyKeys(input, [
8846
10879
  "platform",
8847
10880
  "channel",
8848
- "sinceMs",
8849
- "bundle"
8850
- ]) || !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, [
8851
- "field",
8852
- "value",
8853
- "types"
8854
- ]) || 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) => ![
8855
- "UNCHANGED",
8856
- "UPDATE_DOWNLOADED",
8857
- "UPDATE_APPLIED",
8858
- "RECOVERED"
8859
- ].includes(type))))) invalidQuery();
10881
+ "sinceMs"
10882
+ ]) || !hasScope(input) || !isTimestamp(input.sinceMs)) invalidQuery();
8860
10883
  return validateCount(await model.countLatestEvents(input));
8861
10884
  },
10885
+ async countReleaseInstallations(input) {
10886
+ if (!isRecord$3(input) || !hasOnlyKeys(input, [
10887
+ "platform",
10888
+ "channel",
10889
+ "sinceMs",
10890
+ "releaseId"
10891
+ ]) || !hasScope(input) || !isTimestamp(input.sinceMs) || !isText$1(input.releaseId)) invalidQuery();
10892
+ const counts = await model.countReleaseInstallations(input);
10893
+ if (!isRecord$3(counts) || !hasOnlyKeys(counts, ["installations", "release"])) invalidResult();
10894
+ return {
10895
+ installations: validateCount(counts.installations),
10896
+ release: validateCount(counts.release)
10897
+ };
10898
+ },
8862
10899
  async countEvents(input) {
8863
10900
  if (!isRecord$3(input) || !hasOnlyKeys(input, [
8864
10901
  "filter",
@@ -8915,6 +10952,7 @@ const createInsightsModel = (api) => createValidatedInsightsModel({
8915
10952
  listEvents: api.listEvents,
8916
10953
  findLatestEvents: api.findLatestEvents,
8917
10954
  countLatestEvents: api.countLatestEvents,
10955
+ countReleaseInstallations: api.countReleaseInstallations,
8918
10956
  countEvents: api.countEvents,
8919
10957
  countEventSeries: api.countEventSeries,
8920
10958
  getReleaseActivity: api.getReleaseActivity,
@@ -9317,27 +11355,27 @@ const readScope$1 = (input) => {
9317
11355
  };
9318
11356
  const bundleFilter = (input) => {
9319
11357
  const scope = readScope$1(input);
9320
- const bundleId = requireString(input.bundleId, "bundle ID", MAX_EVENT_ID_LENGTH);
11358
+ const releaseId = requireString(input.releaseId, "bundle ID", MAX_EVENT_ID_LENGTH);
9321
11359
  switch (input.outcome) {
9322
11360
  case "downloaded": return {
9323
11361
  ...scope,
9324
11362
  type: "UPDATE_DOWNLOADED",
9325
- toBundleId: bundleId
11363
+ toReleaseId: releaseId
9326
11364
  };
9327
11365
  case "applied": return {
9328
11366
  ...scope,
9329
11367
  type: "UPDATE_APPLIED",
9330
- toBundleId: bundleId
11368
+ toReleaseId: releaseId
9331
11369
  };
9332
11370
  case "recovered": return {
9333
11371
  ...scope,
9334
11372
  type: "RECOVERED",
9335
- fromBundleId: bundleId
11373
+ fromReleaseId: releaseId
9336
11374
  };
9337
11375
  case "failed": return {
9338
11376
  ...scope,
9339
11377
  type: "UPDATE_FAILED",
9340
- toBundleId: bundleId
11378
+ toReleaseId: releaseId
9341
11379
  };
9342
11380
  default: throw new InsightsBadRequestError("Invalid Insights outcome.");
9343
11381
  }
@@ -9347,7 +11385,7 @@ const sameFilter = (left, right) => {
9347
11385
  switch (right.kind) {
9348
11386
  case "all": return true;
9349
11387
  case "installationMovement": return left.installId === right.installId;
9350
- 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);
11388
+ 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);
9351
11389
  }
9352
11390
  };
9353
11391
  const readEventCursor = (value, filter) => {
@@ -9384,7 +11422,7 @@ const assertEventRows = (rows, input) => {
9384
11422
  for (let index = 0; index < rows.length; index += 1) {
9385
11423
  const row = rows[index];
9386
11424
  const previous = rows[index - 1];
9387
- 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.");
11425
+ 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.");
9388
11426
  }
9389
11427
  };
9390
11428
  /** An `UPDATE_FAILED` row's failure, as the event lists show it. */
@@ -9425,6 +11463,7 @@ const eventDetails = ({ type, metadata }) => ({
9425
11463
  ...metadata.implied_download === true ? { impliedDownload: true } : {}
9426
11464
  });
9427
11465
  const toEventHistoryRow = (row) => ({
11466
+ ...row.from_release_id == null ? {} : { fromReleaseId: row.from_release_id },
9428
11467
  ...row.to_release_id == null ? {} : { toReleaseId: row.to_release_id },
9429
11468
  ...row.metadata.sdk_version == null ? {} : { sdkVersion: row.metadata.sdk_version },
9430
11469
  ...row.metadata.min_bundle_id === void 0 ? {} : { minBundleId: row.metadata.min_bundle_id },
@@ -9449,6 +11488,7 @@ const toInstallationRow = (row) => ({
9449
11488
  cohort: row.metadata.cohort,
9450
11489
  installId: row.install_id,
9451
11490
  lastKnownBundleId: row.type === "UPDATE_DOWNLOADED" ? row.from_bundle_id : row.to_bundle_id,
11491
+ lastKnownReleaseId: row.type === "UPDATE_DOWNLOADED" ? row.from_release_id : row.to_release_id,
9452
11492
  pendingBundleId: row.type === "UPDATE_DOWNLOADED" ? row.to_bundle_id : null,
9453
11493
  pendingReleaseId: row.type === "UPDATE_DOWNLOADED" ? row.to_release_id : null,
9454
11494
  latestStatus: row.type,
@@ -9577,46 +11617,33 @@ const createInsightsProvider = (model) => Object.freeze({
9577
11617
  measuredAtMs: Date.now()
9578
11618
  };
9579
11619
  };
9580
- const bundleId = input.bundleId === void 0 ? void 0 : requireString(input.bundleId, "bundle ID", MAX_EVENT_ID_LENGTH);
9581
- const reporting = measure(model.countLatestEvents({
9582
- ...scope,
9583
- sinceMs
9584
- }));
9585
- if (bundleId === void 0) return {
11620
+ const releaseId = input.releaseId === void 0 ? void 0 : requireString(input.releaseId, "bundle ID", MAX_EVENT_ID_LENGTH);
11621
+ if (releaseId === void 0) return {
9586
11622
  ...scope,
9587
11623
  window,
9588
11624
  sinceMs,
9589
11625
  beforeReceivedAtMs,
9590
- reportingInstallations: await reporting
11626
+ reportingInstallations: await measure(model.countLatestEvents({
11627
+ ...scope,
11628
+ sinceMs
11629
+ }))
9591
11630
  };
11631
+ const installations = model.countReleaseInstallations({
11632
+ ...scope,
11633
+ sinceMs,
11634
+ releaseId
11635
+ }).then(async (counts) => [await measure(Promise.resolve(counts.installations)), await measure(Promise.resolve(counts.release))]);
9592
11636
  const countOutcome = (outcome) => measure(model.countEvents({
9593
11637
  filter: bundleFilter({
9594
11638
  ...scope,
9595
- bundleId,
11639
+ releaseId,
9596
11640
  outcome
9597
11641
  }),
9598
11642
  sinceMs,
9599
11643
  beforeReceivedAtMs
9600
11644
  }));
9601
- const [reportingInstallations, bundleInstallations, downloadedReports, appliedReports, recoveredReports, failedReports] = await Promise.all([
9602
- reporting,
9603
- measure(model.countLatestEvents({
9604
- ...scope,
9605
- sinceMs,
9606
- bundle: [{
9607
- field: "from_bundle_id",
9608
- value: bundleId,
9609
- types: ["UPDATE_DOWNLOADED"]
9610
- }, {
9611
- field: "to_bundle_id",
9612
- value: bundleId,
9613
- types: [
9614
- "UNCHANGED",
9615
- "UPDATE_APPLIED",
9616
- "RECOVERED"
9617
- ]
9618
- }]
9619
- })),
11645
+ const [[reportingInstallations, bundleInstallations], downloadedReports, appliedReports, recoveredReports, failedReports] = await Promise.all([
11646
+ installations,
9620
11647
  countOutcome("downloaded"),
9621
11648
  countOutcome("applied"),
9622
11649
  countOutcome("recovered"),
@@ -9629,7 +11656,7 @@ const createInsightsProvider = (model) => Object.freeze({
9629
11656
  beforeReceivedAtMs,
9630
11657
  reportingInstallations,
9631
11658
  bundle: {
9632
- bundleId,
11659
+ releaseId,
9633
11660
  reportingInstallations: bundleInstallations,
9634
11661
  downloadedReports,
9635
11662
  appliedReports,
@@ -9764,17 +11791,10 @@ const gaugeSlot = (head) => ({
9764
11791
  builtinBundleId: runningBuiltinBundleId(head)
9765
11792
  });
9766
11793
  /**
9767
- * The `insights_latest_by_bundle` field of a head's (from, to) pair. A head
9768
- * matches a `from` and a `to` predicate of one type at once only through its
9769
- * pair, so this gauge is what a count subtracts to count it once.
9770
- */
9771
- const PAIR_FIELD = "from_to";
9772
- /** The pair gauge's `bundle_id`: a hash of the two bundle ids, which fit no single 36-character column. */
9773
- const bundlePairKey = (from, to) => insightsKey(`${from.length}:${from}${to.length}:${to}`);
9774
- /**
9775
11794
  * Moves a head's gauges: the distribution row, and the built-in one when it
9776
- * runs its build's built-in bundle, one row per bundle it references, and
9777
- * its pair; -1 takes back the head an event replaces.
11795
+ * runs its build's built-in bundle; -1 takes back the head an event
11796
+ * replaces. The distribution row names the release the head runs, so it is
11797
+ * also each release's installation gauge.
9778
11798
  */
9779
11799
  const countHead = (tx, head, delta) => {
9780
11800
  const { bucket, releaseId, builtinBundleId } = gaugeSlot(head);
@@ -9794,26 +11814,6 @@ const countHead = (tx, head, delta) => {
9794
11814
  builtin_bundle_id: builtinBundleId,
9795
11815
  bucket_start_ms: bucket
9796
11816
  }, { latest_installations: delta }, { shardBy });
9797
- for (const field of ["from_bundle_id", "to_bundle_id"]) {
9798
- const bundleId = head[field];
9799
- if (bundleId === null) continue;
9800
- tx.aggregate("insights_latest_by_bundle", {
9801
- platform: head.platform,
9802
- channel: head.channel,
9803
- bundle_field: field,
9804
- bundle_id: bundleId,
9805
- type: head.type,
9806
- bucket_start_ms: bucket
9807
- }, { installations: delta }, { shardBy });
9808
- }
9809
- if (head.from_bundle_id !== null) tx.aggregate("insights_latest_by_bundle", {
9810
- platform: head.platform,
9811
- channel: head.channel,
9812
- bundle_field: PAIR_FIELD,
9813
- bundle_id: bundlePairKey(head.from_bundle_id, head.to_bundle_id),
9814
- type: head.type,
9815
- bucket_start_ms: bucket
9816
- }, { installations: delta }, { shardBy });
9817
11817
  };
9818
11818
  /**
9819
11819
  * Where each period's rows go, each with its retention: hours for 90 days,
@@ -9874,26 +11874,19 @@ const countEvent = (tx, event) => {
9874
11874
  }
9875
11875
  };
9876
11876
  /**
9877
- * A stored event's outcome rows: its bundle filter's hour, when it has one
9878
- * (`bundleRefsOf`), and every stored event's UTC day. A download that a
9879
- * launch or crash implied counts in its bundle's download hour too, in the
9880
- * hour of that launch or crash, so the download series covers what the
9881
- * release's downloads count; the launch or crash is its row.
11877
+ * A stored event's outcome rows: its bundle filter's hour, and the download
11878
+ * hour of a download its launch or crash implied, each by release
11879
+ * (`outcomeRefsOf`); and every stored event's UTC day.
9882
11880
  */
9883
11881
  const countOutcome = (tx, event) => {
9884
11882
  const shardBy = event.install_id;
9885
- const hour = (type, bundleRef) => tx.aggregate("insights_outcomes", {
11883
+ for (const [type, bundleRef] of outcomeRefsOf(event)) tx.aggregate("insights_outcomes", {
9886
11884
  platform: event.platform,
9887
11885
  channel: event.channel,
9888
11886
  type,
9889
11887
  bundle_ref: bundleRef,
9890
11888
  bucket_start_ms: hourOf(event.received_at_ms)
9891
11889
  }, { events: 1 }, { shardBy });
9892
- for (const bundleRef of bundleRefsOf(event)) hour(event.type, bundleRef);
9893
- if (event.metadata.implied_download === true) hour("UPDATE_DOWNLOADED", bundleRefOfFilter({
9894
- type: "UPDATE_DOWNLOADED",
9895
- toBundleId: event.type === "RECOVERED" ? event.from_bundle_id : event.to_bundle_id
9896
- }));
9897
11890
  tx.aggregate("insights_outcomes", {
9898
11891
  ...DAILY_EVENTS,
9899
11892
  bucket_start_ms: dayOf(event.received_at_ms)
@@ -10373,31 +12366,48 @@ const countEventSeries = async (db, input) => {
10373
12366
  events: count
10374
12367
  }));
10375
12368
  };
10376
- /** A bundle filter's distinct (field, value, type) predicates. */
10377
- const latestPredicates = (bundle) => {
10378
- if (bundle === void 0) return void 0;
10379
- return [...new Map(bundle.flatMap(({ field, value, types }) => types.map((type) => [JSON.stringify([
10380
- field,
10381
- value,
10382
- type
10383
- ]), {
10384
- field,
10385
- value,
10386
- type
10387
- }]))).values()];
12369
+ /** The distribution rows at or after `start`, a UTC day's start. */
12370
+ const distributionRows = (db, { platform, channel, sinceMs: start }) => {
12371
+ if (start % 864e5 !== 0) throw new DatabaseAdapterInputError("invalid-query");
12372
+ return drain((page) => db.findAggregates("insights_distribution", {
12373
+ index: "byScope",
12374
+ where: {
12375
+ channel,
12376
+ platform
12377
+ },
12378
+ range: { gte: start },
12379
+ limit: PAGE,
12380
+ ...page
12381
+ }));
10388
12382
  };
12383
+ const installations = (count) => Math.max(0, count);
10389
12384
  /**
10390
12385
  * Latest events at or after `sinceMs`, a UTC day's start: the gauges count
10391
12386
  * each installation in the UTC day of its latest event, so they answer whole
10392
12387
  * days only, and a later start is rejected rather than rounded.
10393
12388
  */
10394
- const countLatestEvents = async (db, input) => {
10395
- const { platform, channel, sinceMs: start } = input;
10396
- if (start % 864e5 !== 0) throw new DatabaseAdapterInputError("invalid-query");
10397
- const predicates = latestPredicates(input.bundle);
12389
+ const countLatestEvents = async (db, input) => installations((await distributionRows(db, input)).reduce((sum, row) => sum + row.latest_installations, 0));
12390
+ /**
12391
+ * `countLatestEvents`, and of those the installations it leaves running
12392
+ * `releaseId`, from the same distribution rows in one read: each names the
12393
+ * release its installations run. An ID no row names as a release may be a
12394
+ * built-in bundle's, which a report without a release names, as event
12395
+ * counts match it: its installations outside any release are in the
12396
+ * built-in rows, read only then. Release and bundle IDs never coincide.
12397
+ */
12398
+ const countReleaseInstallations = async (db, input) => {
12399
+ const { platform, channel, sinceMs: start, releaseId } = input;
10398
12400
  let total = 0;
10399
- if (predicates === void 0) {
10400
- const rows = await drain((page) => db.findAggregates("insights_distribution", {
12401
+ let release = 0;
12402
+ let named = false;
12403
+ for (const row of await distributionRows(db, input)) {
12404
+ total += row.latest_installations;
12405
+ if (row.release_id !== releaseId) continue;
12406
+ named = true;
12407
+ release += row.latest_installations;
12408
+ }
12409
+ if (!named) {
12410
+ const builtin = await drain((page) => db.findAggregates("insights_builtin_distribution", {
10401
12411
  index: "byScope",
10402
12412
  where: {
10403
12413
  channel,
@@ -10407,33 +12417,12 @@ const countLatestEvents = async (db, input) => {
10407
12417
  limit: PAGE,
10408
12418
  ...page
10409
12419
  }));
10410
- total += rows.reduce((sum, row) => sum + row.latest_installations, 0);
10411
- } else {
10412
- const gauge = async (bundleField, bundleId, type) => {
10413
- return (await drain((page) => db.findAggregates("insights_latest_by_bundle", {
10414
- index: "byBundle",
10415
- where: {
10416
- platform,
10417
- channel,
10418
- bundle_field: bundleField,
10419
- bundle_id: bundleId,
10420
- type
10421
- },
10422
- range: { gte: start },
10423
- limit: PAGE,
10424
- ...page
10425
- }))).reduce((sum, row) => sum + row.installations, 0);
10426
- };
10427
- for (const { field, value, type } of predicates) total += await gauge(field, value, type);
10428
- for (const from of predicates) {
10429
- if (from.field !== "from_bundle_id") continue;
10430
- for (const to of predicates) {
10431
- if (to.field !== "to_bundle_id" || to.type !== from.type) continue;
10432
- total -= await gauge(PAIR_FIELD, bundlePairKey(from.value, to.value), from.type);
10433
- }
10434
- }
12420
+ for (const row of builtin) if (row.release_id === "" && row.builtin_bundle_id === releaseId) release += row.latest_installations;
10435
12421
  }
10436
- return Math.max(0, total);
12422
+ return {
12423
+ installations: installations(total),
12424
+ release: installations(release)
12425
+ };
10437
12426
  };
10438
12427
  /** The oldest whole hour and UTC day that hourly and daily rows still hold. */
10439
12428
  const retained = (now, { rawDays, dailyDays }) => ({
@@ -10733,13 +12722,80 @@ const breakdownOf = (rows) => {
10733
12722
  });
10734
12723
  };
10735
12724
  /**
12725
+ * The breakdown rows a failures read takes from one hour. An hour holds a
12726
+ * row per release, stage, reason, and detail that failed in it, a handful in
12727
+ * practice, and an incident across several releases and error codes still
12728
+ * fits; but a client with the app's API key can report any number of
12729
+ * details.
12730
+ */
12731
+ const FAILURE_ROWS_PER_HOUR = 20;
12732
+ /**
12733
+ * One query's stored rows: an hour's bound and one more row, on every shard,
12734
+ * so an hour past its bound costs at most one query's worth of rows more.
12735
+ */
12736
+ const FAILURE_QUERY_LIMIT = Math.min(PAGE, 168);
12737
+ /**
12738
+ * A channel's breakdown rows over a range, newest first, up to
12739
+ * {@link FAILURE_ROWS_PER_HOUR} an hour: 480 rows for a day, 14,400 for 30
12740
+ * days, however many details clients report. An hour that holds more is read
12741
+ * no further, and the read goes on from the hour before it with a new query;
12742
+ * the hour is listed in `cappedHours`, since its failures count only in part.
12743
+ * Every other hour counts every failure it holds.
12744
+ */
12745
+ const failureRowsByHour = async (db, platform, channel, timeRange) => {
12746
+ const read = (end, cursor) => db.findAggregates("insights_failures", {
12747
+ index: "byScope",
12748
+ where: {
12749
+ platform,
12750
+ channel
12751
+ },
12752
+ range: {
12753
+ gte: timeRange.start,
12754
+ lt: end
12755
+ },
12756
+ order: "desc",
12757
+ limit: FAILURE_QUERY_LIMIT,
12758
+ ...cursor === void 0 ? {} : { cursor }
12759
+ });
12760
+ const rows = [];
12761
+ const cappedHours = [];
12762
+ const perHour = /* @__PURE__ */ new Map();
12763
+ let end = timeRange.end;
12764
+ let cursor;
12765
+ while (end > timeRange.start) {
12766
+ const page = await read(end, cursor);
12767
+ let capped;
12768
+ for (const row of page.rows) {
12769
+ const hour = row.bucket_start_ms;
12770
+ const count = (perHour.get(hour) ?? 0) + 1;
12771
+ if (count > FAILURE_ROWS_PER_HOUR) {
12772
+ capped = hour;
12773
+ break;
12774
+ }
12775
+ perHour.set(hour, count);
12776
+ rows.push(row);
12777
+ }
12778
+ if (capped !== void 0) {
12779
+ cappedHours.unshift(capped);
12780
+ end = capped;
12781
+ cursor = void 0;
12782
+ } else if (page.next === void 0) break;
12783
+ else cursor = page.next;
12784
+ }
12785
+ return {
12786
+ rows,
12787
+ cappedHours
12788
+ };
12789
+ };
12790
+ /**
10736
12791
  * A release's or a channel's update failures. Since a release's first
10737
12792
  * report: its lifetime counters and failed installations. Over a time range
10738
12793
  * of at most 30 days: failures, failed checks, and the breakdown by stage,
10739
12794
  * reason, and detail, all summed from the breakdown's hourly rows; downloads
10740
12795
  * from the counters; failed installations from their sketches. A release reads hourly rows, a
10741
12796
  * channel daily rows past 48 hours like its activity; the breakdown's rows
10742
- * are hourly, so its coverage is the raw period's.
12797
+ * are hourly, so its coverage is the raw period's, and partial when an hour
12798
+ * held more breakdown rows than a read takes from it.
10743
12799
  */
10744
12800
  const getUpdateFailures = async (db, input, now, retention) => {
10745
12801
  const { platform, channel, releaseId, timeRange } = input;
@@ -10801,7 +12857,7 @@ const getUpdateFailures = async (db, input, now, retention) => {
10801
12857
  days,
10802
12858
  kept.hour
10803
12859
  ];
10804
- const [counters, failures, checks, active, rows] = await Promise.all([
12860
+ const [counters, failures, checks, active, { rows, cappedHours }] = await Promise.all([
10805
12861
  counterRows(db, parts, ...window),
10806
12862
  sketchRows(db, failure, ...window),
10807
12863
  days ? sketchRows(db, {
@@ -10809,25 +12865,17 @@ const getUpdateFailures = async (db, input, now, retention) => {
10809
12865
  scopeKind: "check"
10810
12866
  }, ...window) : [],
10811
12867
  days ? sketchRows(db, usageParts(channel, platform), ...window) : [],
10812
- drain((page) => db.findAggregates("insights_failures", {
10813
- index: "byScope",
10814
- where: {
10815
- platform,
10816
- channel
10817
- },
10818
- range: {
10819
- gte: timeRange.start,
10820
- lt: timeRange.end
10821
- },
10822
- limit: PAGE,
10823
- ...page
10824
- }))
12868
+ failureRowsByHour(db, platform, channel, timeRange)
10825
12869
  ]);
10826
12870
  const total = (field) => counters.reduce((sum, row) => sum + row[field], 0);
10827
12871
  const scoped = rows.filter((row) => FAILURE_STAGES.has(row.stage) && (releaseId === void 0 || row.release_id === releaseId));
10828
12872
  const failuresAt = (counted) => scoped.reduce((sum, row) => sum + (counted(row.stage) ? Math.max(0, row.events) : 0), 0);
12873
+ const coverage = coverageOf(timeRange.start, kept.hour);
10829
12874
  return {
10830
- coverage: coverageOf(timeRange.start, kept.hour),
12875
+ coverage: cappedHours.length === 0 ? coverage : {
12876
+ kind: "partial",
12877
+ sinceMs: coverage.sinceMs
12878
+ },
10831
12879
  measuredAtMs: at,
10832
12880
  failedUpdates: failuresAt((stage) => stage !== "check"),
10833
12881
  failedInstallations: failed(failures),
@@ -10839,7 +12887,28 @@ const getUpdateFailures = async (db, input, now, retention) => {
10839
12887
  failedInstallations: failed(checks),
10840
12888
  activeInstallations: countDistinct(mergeDistinct(active.map((row) => row.activity_users)))
10841
12889
  } } : {},
10842
- breakdown: breakdownOf(scoped)
12890
+ breakdown: breakdownOf(scoped),
12891
+ ...cappedHours.length === 0 ? {} : { cappedHours }
12892
+ };
12893
+ };
12894
+ //#endregion
12895
+ //#region ../insights/dist/server/wire.mjs
12896
+ /**
12897
+ * The HTTP API calls a release ID `bundleId`, the word users have for it, in
12898
+ * its query parameters and its overview's JSON. The code calls it
12899
+ * `releaseId`; only this module maps between the two names.
12900
+ */
12901
+ const RELEASE_ID_PARAM = "bundleId";
12902
+ /** An overview as the HTTP API and the CLI's `--json` send it. */
12903
+ const toWireOverview = ({ bundle, ...overview }) => {
12904
+ if (bundle === void 0) return overview;
12905
+ const { releaseId, ...counts } = bundle;
12906
+ return {
12907
+ ...overview,
12908
+ bundle: {
12909
+ ...counts,
12910
+ bundleId: releaseId
12911
+ }
10843
12912
  };
10844
12913
  };
10845
12914
  //#endregion
@@ -10887,7 +12956,7 @@ const readScope = (url) => {
10887
12956
  const parseEventPageInput = (request) => {
10888
12957
  const url = new URL(request.url);
10889
12958
  const bundleFields = [
10890
- "bundleId",
12959
+ RELEASE_ID_PARAM,
10891
12960
  "outcome",
10892
12961
  "platform",
10893
12962
  "channel"
@@ -10898,7 +12967,7 @@ const parseEventPageInput = (request) => {
10898
12967
  if (outcome !== "downloaded" && outcome !== "applied" && outcome !== "recovered" && outcome !== "failed") throw new InsightsBadRequestError("Invalid 'outcome' query parameter.");
10899
12968
  bundle = {
10900
12969
  ...readScope(url),
10901
- bundleId: readId(url, "bundleId", 1024),
12970
+ releaseId: readId(url, RELEASE_ID_PARAM, 1024),
10902
12971
  outcome
10903
12972
  };
10904
12973
  }
@@ -10924,11 +12993,10 @@ const parseReportingOverviewInput = (request) => {
10924
12993
  const url = new URL(request.url);
10925
12994
  const window = readSingle(url, "window") ?? "30d";
10926
12995
  if (window !== "24h" && window !== "7d" && window !== "30d") throw new InsightsBadRequestError("Invalid 'window' query parameter.");
10927
- const bundleId = readSingle(url, "bundleId");
10928
12996
  return {
10929
12997
  ...readScope(url),
10930
12998
  window,
10931
- ...bundleId === void 0 ? {} : { bundleId: readId(url, "bundleId", 1024) }
12999
+ ...readSingle(url, "bundleId") === void 0 ? {} : { releaseId: readId(url, RELEASE_ID_PARAM, 1024) }
10932
13000
  };
10933
13001
  };
10934
13002
  //#endregion
@@ -11009,7 +13077,7 @@ const createInsightsRouteHandlers = (provider) => ({
11009
13077
  await provider.appendBundleEvent(await parseBundleEventRequest(request));
11010
13078
  return new Response(null, { status: 204 });
11011
13079
  }),
11012
- getReportingOverview: (_params, request) => query(() => provider.getReportingOverview(parseReportingOverviewInput(request))),
13080
+ getReportingOverview: (_params, request) => query(async () => toWireOverview(await provider.getReportingOverview(parseReportingOverviewInput(request)))),
11013
13081
  getInstallation: (params) => run$1(async () => {
11014
13082
  const installation = await provider.getInstallation({ installId: requireParam(params, "installId") });
11015
13083
  return installation === null ? json$1({ error: "Installation not found" }, 404) : json$1(installation, 200);
@@ -11031,12 +13099,20 @@ const createInsightsApi = (db, now, retention) => ({
11031
13099
  listEvents: (input) => listEvents(db, input),
11032
13100
  findLatestEvents: (input) => findLatestEvents(db, input),
11033
13101
  countLatestEvents: (input) => countLatestEvents(db, input),
13102
+ countReleaseInstallations: (input) => countReleaseInstallations(db, input),
11034
13103
  countEvents: (input) => countEvents(db, input),
11035
13104
  countEventSeries: (input) => countEventSeries(db, input),
11036
13105
  getReleaseActivity: (input) => getReleaseActivity(db, input, now),
11037
13106
  getAppUsage: (input) => getAppUsage(db, input, now, retention),
11038
13107
  /** A release's or a channel's update failures, and their breakdown over a time range. */
11039
- getUpdateFailures: (input) => getUpdateFailures(db, input, now, retention)
13108
+ getUpdateFailures: (input) => getUpdateFailures(db, input, now, retention),
13109
+ /**
13110
+ * Moves the stored events a 1.1 server keyed by artifact, and their
13111
+ * outcome counts, to their release, reading every stored event of the
13112
+ * raw period: `hot-updater db migrate` and `hot-updater init` run it once
13113
+ * a database, and an interrupted run can run again.
13114
+ */
13115
+ backfillReleaseRefs: (options) => backfillReleaseRefs(db, now, retention, options)
11040
13116
  });
11041
13117
  /** `GET /failures`'s query: a scope, an optional release, and a time range or none. */
11042
13118
  const readFailuresQuery = (url) => {
@@ -12111,14 +14187,67 @@ const createFirestoreStore = ({ firestore, collection, nativePageSize }) => {
12111
14187
  };
12112
14188
  };
12113
14189
  //#endregion
14190
+ //#region src/googleCredential.ts
14191
+ const CLOUD_PLATFORM_SCOPE = "https://www.googleapis.com/auth/cloud-platform";
14192
+ /**
14193
+ * Resolves application default credentials as Firestore will, from
14194
+ * GOOGLE_APPLICATION_CREDENTIALS's file or the environment, for the app's
14195
+ * `projectId`, so it neither exchanges a token nor discovers a project
14196
+ * Firestore itself wouldn't. Only `applicationDefault()`'s credential: a
14197
+ * service account's or refresh token's was read from its file already.
14198
+ */
14199
+ const resolveApplicationDefault = async (credential, projectId) => {
14200
+ if (credential.constructor.name !== "ApplicationDefaultCredential") return;
14201
+ const { GoogleAuth } = await import("google-auth-library");
14202
+ await new GoogleAuth({
14203
+ scopes: [CLOUD_PLATFORM_SCOPE],
14204
+ ...projectId === void 0 ? {} : { projectId }
14205
+ }).getClient();
14206
+ };
14207
+ //#endregion
12114
14208
  //#region src/firebaseDatabase.ts
14209
+ /**
14210
+ * `store` that loads `credential` before its first call: one that cannot
14211
+ * load, such as GOOGLE_APPLICATION_CREDENTIALS naming a missing file, fails
14212
+ * that call with what is wrong. Firestore's own client would also reject a
14213
+ * promise nobody awaits, which ends a CLI process with a stack trace.
14214
+ */
14215
+ const withLoadedCredential = (store, credential, projectId) => {
14216
+ let loaded;
14217
+ const load = () => loaded ??= resolveApplicationDefault(credential, projectId).then(() => void 0, (error) => {
14218
+ loaded = void 0;
14219
+ throw new Error(`Could not load the Google credentials for Firestore: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
14220
+ });
14221
+ const { deleteConsumed } = store;
14222
+ return {
14223
+ ...store,
14224
+ get: async (keys) => {
14225
+ await load();
14226
+ return store.get(keys);
14227
+ },
14228
+ query: async (range) => {
14229
+ await load();
14230
+ return store.query(range);
14231
+ },
14232
+ write: async (ops) => {
14233
+ await load();
14234
+ return store.write(ops);
14235
+ },
14236
+ ...deleteConsumed && { deleteConsumed: async (keys) => {
14237
+ await load();
14238
+ return deleteConsumed.call(store, keys);
14239
+ } }
14240
+ };
14241
+ };
12115
14242
  const adapterOf = ({ databaseId, collection = FIREBASE_V1_COLLECTION, aggregateBatching: _, ...appOptions }) => {
12116
14243
  const app = (0, firebase_admin_app.getApps)().length ? (0, firebase_admin_app.getApp)() : (0, firebase_admin_app.initializeApp)(appOptions);
12117
14244
  const firestore = databaseId ? (0, firebase_admin_firestore.getFirestore)(app, databaseId) : (0, firebase_admin_firestore.getFirestore)(app);
12118
- return createKvAdapter({ store: createFirestoreStore({
14245
+ const store = createFirestoreStore({
12119
14246
  firestore,
12120
14247
  collection
12121
- }) });
14248
+ });
14249
+ const credential = app.options.credential;
14250
+ return createKvAdapter({ store: appOptions.credential === void 0 || credential === void 0 || process.env["FIRESTORE_EMULATOR_HOST"] ? store : withLoadedCredential(store, credential, app.options.projectId) });
12122
14251
  };
12123
14252
  /**
12124
14253
  * The resource this database reaches, without credentials, under the key
@@ -12139,11 +14268,14 @@ const firebaseDatabase = (config) => ({
12139
14268
  //#region src/firebaseStorage.ts
12140
14269
  /** Signed URLs kept per adapter, enough for a few Bundles' assets. */
12141
14270
  const MAX_CACHED_SIGNED_URLS = 1e4;
14271
+ /** Objects deleted at once: Cloud Storage deletes one object a request. */
14272
+ const DELETE_CONCURRENCY = 16;
12142
14273
  const firebaseStorage = (config) => {
12143
14274
  const app = (0, firebase_admin_app.getApps)().length ? (0, firebase_admin_app.getApp)() : (0, firebase_admin_app.initializeApp)(config);
12144
14275
  let opened;
12145
14276
  const bucket = () => opened ??= (0, firebase_admin_storage.getStorage)(app).bucket(config.storageBucket);
12146
14277
  const getStorageKey = createStorageKeyBuilder(config.basePath);
14278
+ const basePrefix = getStorageKey() ? `${getStorageKey()}/` : "";
12147
14279
  /**
12148
14280
  * Signed URLs by object. Without a private key, as in Cloud Functions, each
12149
14281
  * signature is an IAM signBlob request, and an update check returns a URL
@@ -12186,11 +14318,21 @@ const firebaseStorage = (config) => {
12186
14318
  protocol: "gs",
12187
14319
  async put({ key, body, contentType }) {
12188
14320
  const storageKey = getStorageKey(key);
12189
- const [{ Readable }, { pipeline }] = await Promise.all([import("node:stream"), import("node:stream/promises")]);
12190
- await pipeline(Readable.fromWeb(body), bucket().file(storageKey).createWriteStream({ metadata: {
12191
- contentType,
12192
- cacheControl: "public, max-age=31536000, immutable"
12193
- } }));
14321
+ try {
14322
+ await (0, node_stream_promises.pipeline)(node_stream.Readable.fromWeb(body), bucket().file(storageKey).createWriteStream({
14323
+ resumable: false,
14324
+ metadata: {
14325
+ contentType,
14326
+ cacheControl: "public, max-age=31536000, immutable"
14327
+ }
14328
+ }));
14329
+ } catch (error) {
14330
+ const status = Reflect.get(Object(error), "code");
14331
+ if (typeof status !== "number") throw error;
14332
+ const message = error.message;
14333
+ const detail = /<html|<!doctype/i.test(message) ? "" : `: ${message}`;
14334
+ throw new Error(`Firebase Storage answered HTTP ${status} while uploading ${storageKey}${detail}`, { cause: error });
14335
+ }
12194
14336
  return { storageUri: createStorageUri({
12195
14337
  bucket: config.storageBucket,
12196
14338
  key: storageKey,
@@ -12232,6 +14374,39 @@ const firebaseStorage = (config) => {
12232
14374
  const { key } = parseAndValidate(storageUri);
12233
14375
  await bucket().file(key).delete({ ignoreNotFound: true });
12234
14376
  return { deleted: true };
14377
+ },
14378
+ async listObjects(prefix) {
14379
+ const folder = getStorageKey(prefix ?? "");
14380
+ const [files] = await bucket().getFiles({
14381
+ autoPaginate: true,
14382
+ prefix: folder ? `${folder}/` : ""
14383
+ });
14384
+ const objects = [];
14385
+ for (const file of files) {
14386
+ if (!file.name.startsWith(basePrefix)) continue;
14387
+ let storageUri;
14388
+ try {
14389
+ storageUri = createStorageUri({
14390
+ bucket: config.storageBucket,
14391
+ key: file.name,
14392
+ protocol: "gs"
14393
+ });
14394
+ } catch {
14395
+ continue;
14396
+ }
14397
+ const { size, updated } = file.metadata;
14398
+ objects.push({
14399
+ key: file.name.slice(basePrefix.length),
14400
+ ...updated ? { lastModifiedAt: new Date(updated) } : {},
14401
+ size: Number(size ?? 0),
14402
+ storageUri
14403
+ });
14404
+ }
14405
+ return objects;
14406
+ },
14407
+ async deleteObjects(relativeKeys) {
14408
+ const keys = relativeKeys.map((key) => getStorageKey(key));
14409
+ for (let offset = 0; offset < keys.length; offset += DELETE_CONCURRENCY) await Promise.all(keys.slice(offset, offset + DELETE_CONCURRENCY).map((key) => bucket().file(key).delete({ ignoreNotFound: true })));
12235
14410
  }
12236
14411
  });
12237
14412
  };
@@ -12242,9 +14417,10 @@ const adminOptions = ((0, firebase_admin_app.getApps)()[0] ?? (0, firebase_admin
12242
14417
  const storageBucket = adminOptions.storageBucket;
12243
14418
  const cdnUrl = process.env.HOT_UPDATER_CDN_URL;
12244
14419
  if (!storageBucket) throw new Error("Firebase runtime requires storageBucket to read bundle manifests.");
14420
+ const { credential: _runtimeCredential, ...databaseOptions } = adminOptions;
12245
14421
  const hotUpdater = createHotUpdater({
12246
14422
  database: firebaseDatabase({
12247
- ...adminOptions,
14423
+ ...databaseOptions,
12248
14424
  databaseId: HotUpdater.FIRESTORE_DATABASE_ID
12249
14425
  }),
12250
14426
  plugins: [