@hot-updater/firebase 1.2.0-rc.49 → 1.2.0-rc.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2046,45 +2046,6 @@ const METER = Symbol.for("@hot-updater/plugin-core/read-meter");
2046
2046
  /** The meter `meterReads` gave `database`, if it did. */
2047
2047
  const readMeterOf = (database) => typeof database === "object" && database !== null ? database[METER] : void 0;
2048
2048
  //#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
2049
  //#region ../plugin-core/dist/engine/core/schema.mjs
2089
2050
  /** A channel's id is `channel:` and its name's channel key, so ids share channel_key's bound. */
2090
2051
  const CHANNEL_ID = {
@@ -2100,8 +2061,9 @@ const CHANNEL_ID = {
2100
2061
  * applies it to managed databases an earlier release created. The official
2101
2062
  * plugins' `schemaVersion`s follow the same rule. A bump only adds tables:
2102
2063
  * 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
2064
+ * version, and none of them changes an existing table's columns, so changing
2065
+ * one needs a migration step of its own first. An index added to an existing
2066
+ * table is listed in `LATE_INDEXES`. The schema fence answers 503 on
2105
2067
  * a database whose row differs, until it runs. Before a version is released,
2106
2068
  * its tables change in place in its own migration, and a database one of its
2107
2069
  * prereleases migrated takes the same change by hand: the fence compares this
@@ -2287,9 +2249,26 @@ const releases = defineTable({
2287
2249
  all: {
2288
2250
  eq: [],
2289
2251
  sort: ["id"]
2252
+ },
2253
+ scopes: {
2254
+ eq: [],
2255
+ sort: ["scope_key"]
2290
2256
  }
2291
2257
  }
2292
2258
  });
2259
+ /**
2260
+ * Indexes declared on a table that a released schema's servers write: a
2261
+ * store that keeps index items of its own (`migrations.fillIndex`) lacks
2262
+ * them for rows written before, and for rows such a server still writes
2263
+ * after the migration, since its schema fence keeps a check that passed.
2264
+ * Each migration writes the missing items, and `db migrate` on a database
2265
+ * whose settings match looks for them. `releases.scopes` arrived in 1.2.0;
2266
+ * 1.1.x servers write releases without it.
2267
+ */
2268
+ const LATE_INDEXES = [{
2269
+ table: "releases",
2270
+ index: "scopes"
2271
+ }];
2293
2272
  /** One compiled catalog per scope; the update check reads exactly this row. */
2294
2273
  const releaseCatalogs = defineTable({
2295
2274
  scope_key: {
@@ -2687,6 +2666,121 @@ const refuseV0Database = (adapterName, stored) => {
2687
2666
  if (typeof version !== "string" || stored.has("schema.engine")) return;
2688
2667
  throw new HotUpdaterSchemaMigrationRequiredError(adapterName, version);
2689
2668
  };
2669
+ /** Compares dotted numeric versions, such as "1" and "1.2.0"; NaN when either is not one. */
2670
+ const compareVersions = (left, right) => {
2671
+ const parse = (version) => /^\d+(?:\.\d+)*$/u.test(version) ? version.split(".").map(Number) : [NaN];
2672
+ const [a, b] = [parse(left), parse(right)];
2673
+ if ([...a, ...b].some(Number.isNaN)) return NaN;
2674
+ for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
2675
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
2676
+ if (difference !== 0) return difference;
2677
+ }
2678
+ return 0;
2679
+ };
2680
+ /**
2681
+ * The settings whose versions only move forward when a `ToolingTarget` names
2682
+ * none. `schema.engine` is a storage layout, not a release: a store refuses
2683
+ * another layout itself, and doctor reports it as not migratable.
2684
+ */
2685
+ const DEFAULT_ORDERED_SETTINGS = ["schema.core"];
2686
+ /**
2687
+ * Refuses a database a newer release migrated, one whose `schema.core` is
2688
+ * newer than this release's: writing this release's settings would move the
2689
+ * schema back, and every server of the newer release would answer 503. Only
2690
+ * `ordered` settings are compared, `schema.core` among them, and the message
2691
+ * lists each that is newer. An official plugin's
2692
+ * newer version alone is no newer release: Insights recorded "1.2.0" in
2693
+ * 1.0.0-rc.23 and rc.24, then went back to "1.0.0" with the same tables.
2694
+ */
2695
+ const refuseNewerSchema = (adapterName, stored, settings, ordered = DEFAULT_ORDERED_SETTINGS) => {
2696
+ const newer = ordered.flatMap((key) => {
2697
+ const found = stored.get(key);
2698
+ const expected = settings[key];
2699
+ return typeof found === "string" && expected !== void 0 && compareVersions(found, expected) > 0 ? [{
2700
+ key,
2701
+ found,
2702
+ expected
2703
+ }] : [];
2704
+ });
2705
+ const core = newer.find(({ key }) => key === "schema.core");
2706
+ if (core === void 0) return;
2707
+ 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.`);
2708
+ };
2709
+ /** The settings rows a migration changes, each with its stored value. */
2710
+ const settingsOperation = (stored, changed) => ({
2711
+ type: "custom",
2712
+ description: `Record ${changed.map(([key, value]) => {
2713
+ const found = stored.get(key);
2714
+ return typeof found === "string" ? `${key} ${found} → ${value}` : `${key} ${value}`;
2715
+ }).join(", ")}`
2716
+ });
2717
+ //#endregion
2718
+ //#region ../plugin-core/dist/engine/db/schemaSettings.mjs
2719
+ const storedSettings = async (adapter, keys) => {
2720
+ const rows = await readSettings(adapter, keys);
2721
+ return new Map(keys.map((key, position) => [key, rows[position] ?? null]));
2722
+ };
2723
+ /**
2724
+ * Writes the settings rows after every table exists, and refuses a database
2725
+ * whose `ordered` settings a newer release recorded.
2726
+ */
2727
+ const writeSchemaSettings = async (adapter, adapterName, settings, ordered) => {
2728
+ const stored = await storedSettings(adapter, Object.keys(settings));
2729
+ refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
2730
+ const ops = Object.entries(settings).flatMap(([key, value]) => {
2731
+ const row = stored.get(key);
2732
+ if (row === null || row === void 0) return [{
2733
+ type: "insert",
2734
+ table: SETTINGS_TABLE,
2735
+ row: {
2736
+ key,
2737
+ value,
2738
+ _v: 0
2739
+ }
2740
+ }];
2741
+ if (row.value === value) return [];
2742
+ return [{
2743
+ type: "patch",
2744
+ table: SETTINGS_TABLE,
2745
+ key: [key],
2746
+ set: { value },
2747
+ guard: { v: Number(row._v) },
2748
+ previous: row
2749
+ }];
2750
+ });
2751
+ if (ops.length === 0) return;
2752
+ if (!(await adapter.write(ops)).ok) throw new Error(`${adapterName}: the schema settings changed during the migration; run it again.`);
2753
+ };
2754
+ /**
2755
+ * The `LATE_INDEXES` among `tables` whose items some rows lack, as
2756
+ * `<table>.<index>`, written unless `dryRun`: none on a store without
2757
+ * `migrations.fillIndex`.
2758
+ */
2759
+ const fillLateIndexes = async (adapter, tables, { dryRun = false } = {}) => {
2760
+ const fillIndex = adapter.migrations?.fillIndex;
2761
+ if (fillIndex === void 0) return [];
2762
+ const lacking = [];
2763
+ for (const { table: name, index } of LATE_INDEXES) {
2764
+ const table = tables.find((candidate) => candidate.name === name);
2765
+ if (table === void 0) continue;
2766
+ if (await fillIndex(table, index, { dryRun }) > 0) lacking.push(`${name}.${index}`);
2767
+ }
2768
+ return lacking;
2769
+ };
2770
+ /**
2771
+ * Creates or updates every table, writes the late indexes' missing items,
2772
+ * then writes the settings rows last. A database a newer release migrated is
2773
+ * refused before anything is written: its settings are read first, and a
2774
+ * store without them yet, whose read fails, has none to refuse.
2775
+ */
2776
+ const migrateSchema = async (adapter, adapterName, tables, settings, ordered) => {
2777
+ if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
2778
+ const stored = await storedSettings(adapter, Object.keys(settings)).catch(() => void 0);
2779
+ if (stored !== void 0) refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
2780
+ await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
2781
+ await fillLateIndexes(adapter, tables);
2782
+ await writeSchemaSettings(adapter, adapterName, settings, ordered);
2783
+ };
2690
2784
  //#endregion
2691
2785
  //#region ../plugin-core/dist/engine/database/cursor.mjs
2692
2786
  const encoder$1 = new TextEncoder();
@@ -3709,29 +3803,34 @@ const resolveSchema = (modules) => {
3709
3803
  * `hot-updater db migrate` for a store whose adapter creates its own tables
3710
3804
  * (MongoDB and the key-value stores): the tables and indexes, then the
3711
3805
  * settings rows, applied when a setting is missing or different, and refused
3712
- * on a v0 database.
3806
+ * on a v0 database or one a newer release migrated.
3713
3807
  */
3714
3808
  const createEngineMigrator = (options) => {
3715
3809
  const getVersion = async () => storedSchemaVersion(await options.readSettings());
3716
3810
  const makeResult = async (migrate = {}) => {
3717
3811
  const stored = await options.readSettings();
3718
3812
  refuseV0Database(options.adapterName, stored);
3719
- if (Object.entries(options.settings).every(([key, value]) => stored.get(key) === value)) return getEmptyMigrationResult();
3720
- return {
3721
- operations: [...options.schema.tables.map((table) => ({
3722
- type: "create-table",
3723
- value: {
3724
- ormName: table.name,
3725
- columns: Object.fromEntries(table.columns.map((column) => [column.name, {
3726
- ormName: column.name,
3727
- type: column.type
3728
- }]))
3813
+ refuseNewerSchema(options.adapterName, stored, options.settings, options.ordered);
3814
+ const changed = Object.entries(options.settings).filter(([key, value]) => stored.get(key) !== value);
3815
+ if (changed.length === 0) {
3816
+ const lacking = await fillLateIndexes(options.adapter, options.schema.tables, { dryRun: true });
3817
+ if (lacking.length === 0) return getEmptyMigrationResult();
3818
+ return {
3819
+ operations: [{
3820
+ type: "custom",
3821
+ description: `Write the index items rows lack: ${lacking.join(", ")}`
3822
+ }],
3823
+ execute: async () => {
3824
+ await fillLateIndexes(options.adapter, options.schema.tables);
3729
3825
  }
3730
- })), ...migrate.updateSettings === false ? [] : [{
3826
+ };
3827
+ }
3828
+ return {
3829
+ operations: [{
3731
3830
  type: "custom",
3732
- description: `Write the schema settings: ${Object.keys(options.settings).join(", ")}`
3733
- }]],
3734
- execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings)
3831
+ description: "Create the tables and indexes the database lacks"
3832
+ }, ...migrate.updateSettings === false ? [] : [settingsOperation(stored, changed)]],
3833
+ execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings, options.ordered)
3735
3834
  };
3736
3835
  };
3737
3836
  return {
@@ -3762,7 +3861,8 @@ const coreSettings = {
3762
3861
  /** What `hot-updater db` creates for a server without plugins. */
3763
3862
  const coreTarget = {
3764
3863
  schema: coreSchema,
3765
- settings: coreSettings
3864
+ settings: coreSettings,
3865
+ ordered: ["schema.core"]
3766
3866
  };
3767
3867
  resolveSchema([aggregateBatchingModule]).tables;
3768
3868
  /** Each plugin's `schema.<id>` settings row. */
@@ -3782,11 +3882,12 @@ const pluginModule = ({ id, schema, namespace }) => ({
3782
3882
  */
3783
3883
  const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBatching, retry, readSettings: readStored }) => {
3784
3884
  const fenced = withSchemaFence(adapter, name, coreSettings);
3785
- const createMigrator = ({ schema, settings } = coreTarget) => createEngineMigrator({
3885
+ const createMigrator = ({ schema, settings, ordered } = coreTarget) => createEngineMigrator({
3786
3886
  adapterName: name,
3787
3887
  adapter,
3788
3888
  schema,
3789
3889
  settings,
3890
+ ordered,
3790
3891
  readSettings: readStored ?? (async () => {
3791
3892
  const rows = await readSettings(adapter, Object.keys(settings)).catch((error) => {
3792
3893
  if (isMissingSchemaError(error)) return [];
@@ -3810,6 +3911,12 @@ const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBa
3810
3911
  /** A row this attempt read changed while it ran; the attempt reruns. */
3811
3912
  var StaleReadError = class extends Error {};
3812
3913
  const idOf = (table, key) => JSON.stringify([table, key]);
3914
+ /** The aggregate rows a write changes, at the versions it read them. */
3915
+ const versionsOf = (ops) => JSON.stringify(ops.map((op) => op.type === "insert" ? [op.table.name, rowKey(op.table, op.row)] : [
3916
+ op.table.name,
3917
+ op.key,
3918
+ "guard" in op ? op.guard?.v : void 0
3919
+ ]));
3813
3920
  const versionOf = (row) => Number(row["_v"]);
3814
3921
  const isKeyed = (value) => value !== null && value !== void 0;
3815
3922
  const misuse = (table, message) => new DatabaseTransactionError(`${table}: ${message}`);
@@ -4154,7 +4261,9 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4154
4261
  assertOutsideTransaction();
4155
4262
  let run;
4156
4263
  let negative;
4157
- for (let round = 0; round < attempts; round += 1) {
4264
+ let failures = 0;
4265
+ let lost;
4266
+ for (let round = 0;; round += 1) {
4158
4267
  const delay = round && Math.min(maxDelayMs, baseDelayMs * 2 ** (round - 1));
4159
4268
  if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay / 2 + Math.random() * (delay / 2)));
4160
4269
  run ??= await attempt(fn).catch((error) => {
@@ -4163,6 +4272,8 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4163
4272
  });
4164
4273
  if (run === void 0) {
4165
4274
  onRetry?.("rerun", round + 1);
4275
+ lost = void 0;
4276
+ if ((failures += 1) >= attempts) break;
4166
4277
  continue;
4167
4278
  }
4168
4279
  let aggregates;
@@ -4173,8 +4284,14 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4173
4284
  negative = error;
4174
4285
  onRetry?.("rerun", round + 1);
4175
4286
  run = void 0;
4287
+ lost = void 0;
4288
+ if ((failures += 1) >= attempts) break;
4176
4289
  continue;
4177
4290
  }
4291
+ const versions = versionsOf(aggregates);
4292
+ if (lost !== void 0 && versions !== lost) failures -= 1;
4293
+ lost = void 0;
4294
+ if (failures >= attempts) break;
4178
4295
  const ops = [...run.ops, ...aggregates];
4179
4296
  if (ops.length <= 1 && ops.every(({ type }) => type === "check")) return run.result;
4180
4297
  if (!adapter.fits(ops)) throw new DatabaseConstraintError("too_large", ops[0].table.name);
@@ -4188,12 +4305,16 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4188
4305
  const failed = "failedOp" in outcome ? outcome.failedOp : void 0;
4189
4306
  if (failed === void 0 || failed >= run.ops.length) {
4190
4307
  onRetry?.("resend", round + 1);
4308
+ failures += 1;
4309
+ if (failed !== void 0) lost = versions;
4310
+ else if (failures >= attempts) break;
4191
4311
  continue;
4192
4312
  }
4193
4313
  const reason = await classify(ops[failed], run.read);
4194
4314
  if (reason) throw new DatabaseConstraintError(reason, ops[failed].table.name);
4195
4315
  onRetry?.("rerun", round + 1);
4196
4316
  run = void 0;
4317
+ if ((failures += 1) >= attempts) break;
4197
4318
  }
4198
4319
  throw negative ?? new DatabaseConflictError(`The transaction conflicted ${attempts} times.`);
4199
4320
  } };
@@ -4593,10 +4714,10 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
4593
4714
  const at = row && expiresAt(table, row);
4594
4715
  return at === void 0 ? {} : { expiresAt: at };
4595
4716
  };
4596
- /** Every index and unique item a row has, by address. */
4597
- const itemsOf = (layout, row) => {
4717
+ /** Every index and unique item a row has, by address: in `indexes`, if given. */
4718
+ const itemsOf = (layout, row, indexes = layout.indexed) => {
4598
4719
  const items = /* @__PURE__ */ new Map();
4599
- for (const index of row === null ? [] : layout.indexed) for (const eq of indexEntries(layout.table, index, row)) {
4720
+ for (const index of row === null ? [] : indexes) for (const eq of indexEntries(layout.table, index, row)) {
4600
4721
  const pk = partition(layout, index, eq);
4601
4722
  const sk = index.unique ? ONLY : encodeKvKey(indexOrderTuple(layout.table, index, row)) || ONLY;
4602
4723
  items.set(JSON.stringify([pk, sk]), {
@@ -4751,6 +4872,79 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
4751
4872
  lte: lt.endsWith(SEPARATOR) ? lt.slice(0, -1) : lt
4752
4873
  };
4753
4874
  };
4875
+ /** One row's check and its item puts in `index`, copies of the row as it is. */
4876
+ const fillOps = (layout, index, row) => [{
4877
+ type: "check",
4878
+ key: rowItem(layout, rowKey(layout.table, row)),
4879
+ condition: { v: Number(row["_v"]) }
4880
+ }, ...[...itemsOf(layout, row, [index]).values()].map(({ key }) => ({
4881
+ type: "put",
4882
+ key,
4883
+ value: copyOf(layout, row),
4884
+ ...stamp(layout.table, row)
4885
+ }))];
4886
+ /**
4887
+ * Writes one row's items in `index`, checking the row's `_v` in the same
4888
+ * write: a row that changed is read again, and a deleted one needs none.
4889
+ */
4890
+ const fillRow = async (layout, index, first) => {
4891
+ const key = rowItem(layout, rowKey(layout.table, first));
4892
+ let row = first;
4893
+ for (let attempt = 0; row !== null; attempt += 1) {
4894
+ 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.`);
4895
+ if ((await store.write(fillOps(layout, index, row))).ok) return;
4896
+ [row] = await store.get([key]);
4897
+ }
4898
+ };
4899
+ /**
4900
+ * Finds the rows that lack an item in `index` and, unless `dryRun`, writes
4901
+ * them, as many rows per atomic write as the store takes. It reads every
4902
+ * row and its items, page by page.
4903
+ */
4904
+ const fillIndex = async (table, name, { dryRun = false } = {}) => {
4905
+ const layout = layoutOf(table);
4906
+ const index = layout.indexed.find((candidate) => candidate.name === name);
4907
+ if (index === void 0) return 0;
4908
+ 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.`);
4909
+ const { items: most, bytes } = store.limits;
4910
+ let lacking = 0;
4911
+ for (let after;;) {
4912
+ const page = await store.query({
4913
+ pk: layout.rows,
4914
+ order: "asc",
4915
+ limit: 100,
4916
+ after
4917
+ });
4918
+ const rows = page.items.map(({ value }) => value);
4919
+ const keys = rows.map((row) => [...itemsOf(layout, row, [index]).values()].map(({ key }) => key));
4920
+ const wanted = keys.flat();
4921
+ const found = wanted.length === 0 ? [] : await store.get(wanted);
4922
+ let at = 0;
4923
+ const missing = rows.filter((_, position) => {
4924
+ return found.slice(at, at += keys[position].length).some((item) => item === null);
4925
+ });
4926
+ lacking += missing.length;
4927
+ if (!dryRun) {
4928
+ let chunk = [];
4929
+ let ops = [];
4930
+ const flush = async () => {
4931
+ if (ops.length > 0 && !(await store.write(ops)).ok) for (const row of chunk) await fillRow(layout, index, row);
4932
+ chunk = [];
4933
+ ops = [];
4934
+ };
4935
+ for (const row of missing) {
4936
+ const next = fillOps(layout, index, row);
4937
+ 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);
4938
+ if (chunk.length > 0 && (ops.length + next.length > most || size(ops) + size(next) > bytes)) await flush();
4939
+ chunk.push(row);
4940
+ ops.push(...next);
4941
+ }
4942
+ await flush();
4943
+ }
4944
+ if (!page.more || page.items.length === 0) return lacking;
4945
+ after = page.items.at(-1).sk;
4946
+ }
4947
+ };
4754
4948
  return {
4755
4949
  id: store.id,
4756
4950
  fits(ops) {
@@ -4810,13 +5004,16 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
4810
5004
  const layout = layoutOf(table);
4811
5005
  return store.deleteConsumed(rows.flatMap((row) => [rowItem(layout, rowKey(table, row)), ...[...itemsOf(layout, row).values()].map(({ key }) => key)]));
4812
5006
  } },
4813
- migrations: { apply: async () => store.migrations?.apply() },
5007
+ migrations: {
5008
+ apply: async () => store.migrations?.apply(),
5009
+ fillIndex
5010
+ },
4814
5011
  ...store.dispose === void 0 ? {} : { dispose: () => store.dispose() }
4815
5012
  };
4816
5013
  };
4817
5014
  //#endregion
4818
5015
  //#region ../../packages/server/dist/version.mjs
4819
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.49";
5016
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.50";
4820
5017
  //#endregion
4821
5018
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
4822
5019
  /**
@@ -4976,10 +5173,15 @@ const releaseCatalogScopeKeyOf = (input) => input.strategy === "APP_VERSION" ? c
4976
5173
  platform: input.platform,
4977
5174
  strategy: "FINGERPRINT"
4978
5175
  });
4979
- /** Projects a stored catalog row for one update check; null when the row is not this scope's. */
4980
- const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
4981
- 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;
4982
- const compiled = parseCompiledCatalog(row.payload, input.strategy);
5176
+ const parseReleaseCatalogRow = ({ payload, ...row }) => ({
5177
+ row,
5178
+ compiled: parseCompiledCatalog(payload, row.strategy)
5179
+ });
5180
+ /** Projects a parsed catalog row for one update check; null when the row is not this scope's. */
5181
+ const projectParsedReleaseCatalogRow = (parsed, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
5182
+ if (parsed === null) return null;
5183
+ const { row, compiled } = parsed;
5184
+ 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;
4983
5185
  const appVersion = input.strategy === "APP_VERSION" ? input.appVersion : void 0;
4984
5186
  return {
4985
5187
  catalogId: row.catalog_id,
@@ -4992,6 +5194,8 @@ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyO
4992
5194
  scopeKey
4993
5195
  };
4994
5196
  };
5197
+ /** Projects a stored catalog row for one update check; null when the row is not this scope's. */
5198
+ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => projectParsedReleaseCatalogRow(row === null ? null : parseReleaseCatalogRow(row), input, scopeKey);
4995
5199
  //#endregion
4996
5200
  //#region ../../packages/server/dist/db/updateArtifacts.mjs
4997
5201
  const HBC_ASSET_PATH_RE = /\.bundle$/;
@@ -5687,7 +5891,7 @@ const after = (input) => {
5687
5891
  };
5688
5892
  return Object.keys(range).length === 0 ? {} : { range };
5689
5893
  };
5690
- /** Core's reads, each through one declared index or key. */
5894
+ /** Core's reads, each through one declared index or key; plugins get `CoreReads`. */
5691
5895
  const createCoreReads = (db, storage) => {
5692
5896
  /** A bundle row's patches, exactly as many as its reference counter holds. */
5693
5897
  const detail = async (row) => {
@@ -5875,8 +6079,35 @@ const createCoreReads = (db, storage) => {
5875
6079
  ...after(input)
5876
6080
  })).rows.map(toCatalogRow);
5877
6081
  },
5878
- /** Every channel, by name. */
5879
- async listChannels() {
6082
+ /**
6083
+ * Up to `limit` scope keys that have releases, ascending after `after`:
6084
+ * one limit-1 seek of the `scopes` index past each scope, so the reads
6085
+ * grow with the scopes, not with their releases.
6086
+ */
6087
+ async listReleaseScopeKeys(input) {
6088
+ const scopeKeys = [];
6089
+ for (let last = input.after ?? ""; scopeKeys.length < input.limit;) {
6090
+ const { rows } = await db.findMany("releases", {
6091
+ index: "scopes",
6092
+ where: {},
6093
+ limit: 1,
6094
+ range: { gt: last }
6095
+ });
6096
+ if (rows[0] === void 0) break;
6097
+ last = rows[0].scope_key;
6098
+ scopeKeys.push(last);
6099
+ }
6100
+ return scopeKeys;
6101
+ },
6102
+ /** Every channel by name; with `input`, one keyset page of them. */
6103
+ async listChannels(input) {
6104
+ if (input !== void 0) return (await db.findMany("channels", {
6105
+ index: "all",
6106
+ where: {},
6107
+ order: input.order ?? "asc",
6108
+ limit: input.limit,
6109
+ ...after(input)
6110
+ })).rows.map(toChannelRow);
5880
6111
  return (await drain$1((page) => db.findMany("channels", {
5881
6112
  index: "all",
5882
6113
  where: {},
@@ -5884,6 +6115,11 @@ const createCoreReads = (db, storage) => {
5884
6115
  ...page
5885
6116
  }))).map(toChannelRow);
5886
6117
  },
6118
+ async getChannels(ids) {
6119
+ const unique = [...new Set(ids)];
6120
+ if (unique.length === 0) return [];
6121
+ return (await db.findByKeys("channels", unique.map((id) => ({ id })))).flatMap((row) => row ? [toChannelRow(row)] : []);
6122
+ },
5887
6123
  async findChannelByName(name) {
5888
6124
  const row = await db.findOne("channels", { name });
5889
6125
  return row === null ? null : toChannelRow(row);
@@ -6817,25 +7053,28 @@ const checkScope = (scope) => {
6817
7053
  });
6818
7054
  if (scope.strategy === "FINGERPRINT" !== (scope.fingerprintHash !== null) || scope.scopeKey !== expected) fail$1("INVALID_SCOPE", "Release catalog scope metadata is inconsistent");
6819
7055
  };
6820
- /** A scope's enabled releases, all of them, under the catalog's guard. */
6821
- const enabledReleases = async (tx, scopeKey) => {
7056
+ /** Every row of a paged read, as release rows. */
7057
+ const drainReleases = async (page) => {
6822
7058
  const rows = [];
6823
7059
  let cursor;
6824
7060
  do {
6825
- const page = await tx.findMany("releases", {
6826
- index: "byScopeEnabled",
6827
- where: {
6828
- scope_key: scopeKey,
6829
- enabled: true
6830
- },
6831
- limit: PAGE$1,
6832
- ...cursor === void 0 ? {} : { cursor }
6833
- });
6834
- rows.push(...page.rows.map(toReleaseRow));
6835
- cursor = page.next;
7061
+ const found = await page(cursor);
7062
+ rows.push(...found.rows.map((row) => toReleaseRow(row)));
7063
+ cursor = found.next;
6836
7064
  } while (cursor !== void 0);
6837
7065
  return rows;
6838
7066
  };
7067
+ const enabledIn = (scopeKey, cursor) => ({
7068
+ index: "byScopeEnabled",
7069
+ where: {
7070
+ scope_key: scopeKey,
7071
+ enabled: true
7072
+ },
7073
+ limit: PAGE$1,
7074
+ ...cursor === void 0 ? {} : { cursor }
7075
+ });
7076
+ /** A scope's enabled releases, all of them, under the catalog's guard. */
7077
+ const enabledReleases = (tx, scopeKey) => drainReleases((cursor) => tx.findMany("releases", enabledIn(scopeKey, cursor)));
6839
7078
  /** The scope's newest release id: `byScope` descending, limit 1. */
6840
7079
  const latestReleaseId = async (tx, scopeKey) => {
6841
7080
  const { rows } = await tx.findMany("releases", {
@@ -6846,15 +7085,11 @@ const latestReleaseId = async (tx, scopeKey) => {
6846
7085
  });
6847
7086
  return rows[0]?.id ?? null;
6848
7087
  };
6849
- /** Compiles `enabled` and writes it as the scope's next catalog generation. */
6850
- const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
6851
- const compilation = await compileReleaseCatalog({
6852
- strategy: scope.strategy,
6853
- releases: enabled.map(releaseRowToRelease)
6854
- });
6855
- const generation = (stored.generation ?? 0) + 1;
7088
+ /** The scope's next catalog generation, compiled as `compilation`. */
7089
+ const nextCatalog = (scope, stored, compilation, updatedAtMs) => {
7090
+ const generation = (stored.catalog?.generation ?? 0) + 1;
6856
7091
  if (!Number.isSafeInteger(generation)) fail$1("CATALOG_GENERATION_EXHAUSTED", `Catalog "${scope.scopeKey}" exhausted its generation counter`);
6857
- const catalog = {
7092
+ return {
6858
7093
  scope_key: scope.scopeKey,
6859
7094
  catalog_id: stored.catalog?.catalog_id ?? createUUIDv7(),
6860
7095
  strategy: scope.strategy,
@@ -6869,6 +7104,26 @@ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
6869
7104
  is_tombstone: compilation.payload.releaseDescriptors.length === 0,
6870
7105
  updated_at_ms: updatedAtMs
6871
7106
  };
7107
+ };
7108
+ /**
7109
+ * Compiles a scope's enabled releases. A catalog over the size limit is
7110
+ * refused naming its channel and platform, and what frees room in it.
7111
+ */
7112
+ const compileScope = async (scope, enabled) => {
7113
+ try {
7114
+ return await compileReleaseCatalog({
7115
+ strategy: scope.strategy,
7116
+ releases: enabled.map(releaseRowToRelease)
7117
+ });
7118
+ } catch (error) {
7119
+ if (!(error instanceof ReleaseCatalogCompilationError) || error.code !== "CATALOG_OVERSIZE") throw error;
7120
+ 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.`);
7121
+ }
7122
+ };
7123
+ /** Compiles `enabled` and writes it as the scope's next catalog generation. */
7124
+ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
7125
+ const compilation = await compileScope(scope, enabled);
7126
+ const catalog = nextCatalog(scope, stored, compilation, updatedAtMs);
6872
7127
  const { scope_key: _scopeKey, ...set } = catalog;
6873
7128
  if (stored.row === null) tx.create("release_catalogs", catalog);
6874
7129
  else tx.update("release_catalogs", stored.row, set);
@@ -6957,18 +7212,49 @@ const changeReleases = (db, inputs) => {
6957
7212
  return results;
6958
7213
  });
6959
7214
  };
7215
+ /** Whether `current` is what the scope's enabled releases compile to. */
7216
+ const isCurrent = (scope, current, compilation) => current.strategy === scope.strategy && current.channel_id === scope.channelId && current.channel_key === encodeChannelKey(scope.channelName) && current.platform === scope.platform && current.fingerprint_hash === scope.fingerprintHash && current.catalog_hash === compilation.catalogHash;
7217
+ /** The scope a catalog row names. */
7218
+ const catalogRowScope = (row) => ({
7219
+ channelId: row.channel_id,
7220
+ channelName: decodeChannelKey(row.channel_key),
7221
+ fingerprintHash: row.fingerprint_hash,
7222
+ platform: row.platform,
7223
+ scopeKey: row.scope_key,
7224
+ strategy: row.strategy
7225
+ });
7226
+ /**
7227
+ * What a rebuild of the scope's catalog would write, without writing: one
7228
+ * read of the catalog row and one of the scope's enabled releases. It needs
7229
+ * no transaction, whose guards would read the catalog again for each read
7230
+ * beneath it, nor the scope's newest release, which matters only to a scope
7231
+ * without a catalog row; that one is not found.
7232
+ */
7233
+ const preflightRebuild = async (db, scopeKey, updatedAtMs) => {
7234
+ const row = await db.findOne("release_catalogs", { scope_key: scopeKey });
7235
+ if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
7236
+ const current = toCatalogRow(row);
7237
+ const scope = catalogRowScope(current);
7238
+ checkScope(scope);
7239
+ const enabled = await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor)));
7240
+ const compilation = await compileScope(scope, enabled);
7241
+ const changed = !isCurrent(scope, current, compilation);
7242
+ return {
7243
+ changed,
7244
+ currentCatalog: current,
7245
+ diagnostics: compilation.diagnostics,
7246
+ projectedCatalog: changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current
7247
+ };
7248
+ };
6960
7249
  /** Recompiles a scope's catalog from its enabled releases inside `tx`; an unchanged catalog is not rewritten. */
6961
7250
  const rebuildScope = async (tx, scope, updatedAtMs) => {
6962
7251
  checkScope(scope);
6963
7252
  const stored = await readCatalog(tx, scope.scopeKey);
6964
7253
  assertHistory(stored, await latestReleaseId(tx, scope.scopeKey) !== null);
6965
7254
  const enabled = await enabledReleases(tx, scope.scopeKey);
6966
- const compilation = await compileReleaseCatalog({
6967
- strategy: scope.strategy,
6968
- releases: enabled.map(releaseRowToRelease)
6969
- });
7255
+ const compilation = await compileScope(scope, enabled);
6970
7256
  const current = stored.catalog;
6971
- 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 {
7257
+ if (current !== null && isCurrent(scope, current, compilation)) return {
6972
7258
  catalog: current,
6973
7259
  current,
6974
7260
  changed: false,
@@ -7072,14 +7358,7 @@ const mutationResult = ({ catalog, release }) => ({
7072
7358
  const catalogScope = async (tx, scopeKey) => {
7073
7359
  const row = await tx.findOne("release_catalogs", { scope_key: scopeKey });
7074
7360
  if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
7075
- return {
7076
- channelId: row.channel_id,
7077
- channelName: decodeChannelKey(row.channel_key),
7078
- fingerprintHash: row.fingerprint_hash,
7079
- platform: row.platform,
7080
- scopeKey: row.scope_key,
7081
- strategy: row.strategy
7082
- };
7361
+ return catalogRowScope(toCatalogRow(row));
7083
7362
  };
7084
7363
  /**
7085
7364
  * Core's typed writes: each runs in one engine transaction rooted at the
@@ -7287,18 +7566,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
7287
7566
  };
7288
7567
  });
7289
7568
  },
7290
- preflightReleaseCatalogRebuild: (scopeKey) => {
7291
- const updatedAtMs = now();
7292
- return dryRun(db, async (tx) => {
7293
- const rebuilt = await rebuildScope(tx, await catalogScope(tx, scopeKey), updatedAtMs);
7294
- return {
7295
- changed: rebuilt.changed,
7296
- currentCatalog: rebuilt.current,
7297
- diagnostics: rebuilt.diagnostics,
7298
- projectedCatalog: rebuilt.catalog
7299
- };
7300
- });
7301
- },
7569
+ preflightReleaseCatalogRebuild: (scopeKey) => preflightRebuild(db, scopeKey, now()),
7302
7570
  ensureChannel,
7303
7571
  deleteChannel: (id) => deleteChannel(db, id),
7304
7572
  updateBundle: (id, update) => db.transaction(async (tx) => {
@@ -7571,6 +7839,10 @@ const answer = async (operation) => {
7571
7839
  error: error.message
7572
7840
  }, status);
7573
7841
  }
7842
+ if (error instanceof ReleaseCatalogCompilationError && error.code === "CATALOG_OVERSIZE") return json$2({
7843
+ code: error.code,
7844
+ error: error.message
7845
+ }, 400);
7574
7846
  if (error instanceof DatabaseBundleNotFoundError) return json$2({
7575
7847
  code: "BUNDLE_NOT_FOUND",
7576
7848
  error: error.message
@@ -7590,9 +7862,11 @@ const LIMITS = {
7590
7862
  defaultValue: 50,
7591
7863
  maxValue: 500
7592
7864
  };
7865
+ /** The most IDs one request names: a lookup's, or a write's. */
7866
+ const MAX_IDS = 100;
7593
7867
  /** `order`, `cursor`, and `limit`: one keyset page. */
7594
- const keyset = (url, maxValue = LIMITS.maxValue) => {
7595
- const order = url.searchParams.get("order") ?? "desc";
7868
+ const keyset = (url, maxValue = LIMITS.maxValue, defaultOrder = "desc") => {
7869
+ const order = url.searchParams.get("order") ?? defaultOrder;
7596
7870
  if (order !== "asc" && order !== "desc") throw new HandlerBadRequestError("order must be 'asc' or 'desc'.");
7597
7871
  const limitParam = url.searchParams.get("limit");
7598
7872
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
@@ -7788,12 +8062,40 @@ const createAdminRouteHandlers = () => ({
7788
8062
  const rows = await core.listReleaseCatalogs(input);
7789
8063
  return page(rows, input, (row) => row.scope_key);
7790
8064
  }),
7791
- /** With `name`, the one channel of that name: 1 read. */
8065
+ /** Up to 100 scope keys that have releases, after `cursor`: one seek each. */
8066
+ listReleaseScopeKeys: onCore(async (core, request) => {
8067
+ const input = keyset(new URL(request.url), 100, "asc");
8068
+ if (input.order !== "asc" || input.through !== void 0) throw new HandlerBadRequestError("Release scopes are listed ascending, by limit and cursor only.");
8069
+ const rows = await core.listReleaseScopeKeys({
8070
+ limit: input.limit,
8071
+ ...input.after === void 0 ? {} : { after: input.after }
8072
+ });
8073
+ return page(rows, input, (scopeKey) => scopeKey);
8074
+ }),
8075
+ /**
8076
+ * With `name`, the one channel of that name: 1 read. With `ids`, the
8077
+ * channels of up to 100 IDs: 1 batch read. With `limit` or `cursor`, one
8078
+ * page by name. With none, every channel, as servers before pages answered.
8079
+ */
7792
8080
  getChannels: onCore(async (core, request) => {
7793
- const name = new URL(request.url).searchParams.get("name");
7794
- if (name === null) return json$2({ data: await core.listChannels() });
7795
- const channel = await core.findChannelByName(name);
7796
- return channel === null ? notFound() : json$2({ data: channel });
8081
+ const url = new URL(request.url);
8082
+ const name = url.searchParams.get("name");
8083
+ if (name !== null) {
8084
+ const channel = await core.findChannelByName(name);
8085
+ return channel === null ? notFound() : json$2({ data: channel });
8086
+ }
8087
+ const ids = url.searchParams.get("ids");
8088
+ if (ids !== null) {
8089
+ const list = ids.split(",").filter((id) => id.length > 0);
8090
+ if (list.length === 0 || list.length > MAX_IDS) throw new HandlerBadRequestError(`Channels by ID take ids=<channel id>,... with 1 to ${MAX_IDS} ids.`);
8091
+ return json$2({ data: await core.getChannels(list) });
8092
+ }
8093
+ if (url.searchParams.has("limit") || url.searchParams.has("cursor")) {
8094
+ const input = keyset(url, LIMITS.maxValue, "asc");
8095
+ const rows = await core.listChannels(input);
8096
+ return page(rows, input, (row) => row.name);
8097
+ }
8098
+ return json$2({ data: await core.listChannels() });
7797
8099
  }),
7798
8100
  /** The channel named in the body, created when missing. */
7799
8101
  createChannel: onCore(async (core, request) => {
@@ -7844,7 +8146,7 @@ const createAdminRouteHandlers = () => ({
7844
8146
  countBundles: onCore(async (core, request) => json$2({ data: await core.countBundles(platformOf(new URL(request.url))) })),
7845
8147
  countBundleChildren: onCore(async (core, request) => {
7846
8148
  const ids = (new URL(request.url).searchParams.get("ids") ?? "").split(",").filter((id) => id.length > 0);
7847
- if (ids.length === 0 || ids.length > 100) throw new HandlerBadRequestError("Bundle child counts take ids=<bundle id>,... with 1 to 100 ids.");
8149
+ if (ids.length === 0 || ids.length > MAX_IDS) throw new HandlerBadRequestError(`Bundle child counts take ids=<bundle id>,... with 1 to ${MAX_IDS} ids.`);
7848
8150
  return json$2({ data: await core.countBundleChildren(ids) });
7849
8151
  }),
7850
8152
  listBundleChildren: onCore(async (core, request, params) => {
@@ -7986,6 +8288,7 @@ const createAdminRouteHandlers = () => ({
7986
8288
  markIosDevicesInBuild: onCore(async (core, request) => {
7987
8289
  const { buildId, ids } = await body(request);
7988
8290
  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.");
8291
+ if (ids.length > MAX_IDS) throw new HandlerBadRequestError(`Marking iOS devices in a build takes at most ${MAX_IDS} ids a request.`);
7989
8292
  await core.markIosDevicesInBuild({
7990
8293
  buildId,
7991
8294
  ids
@@ -8056,6 +8359,11 @@ const ADMIN_ROUTES = [
8056
8359
  path: "/release-catalogs",
8057
8360
  handler: "listReleaseCatalogs"
8058
8361
  },
8362
+ {
8363
+ method: "GET",
8364
+ path: "/release-scopes",
8365
+ handler: "listReleaseScopeKeys"
8366
+ },
8059
8367
  {
8060
8368
  method: "POST",
8061
8369
  path: "/release-catalogs/:scopeKey/rebuild",
@@ -8237,9 +8545,9 @@ const CATALOG_CACHE_CONTROL = "public, max-age=0, s-maxage=5";
8237
8545
  * background. `stale-if-error=0` keeps origin errors visible: without it,
8238
8546
  * Cloudflare serves a stale copy on error indefinitely.
8239
8547
  *
8240
- * A device can see a catalog up to 15 seconds after a deploy or a Roll back
8241
- * replaced it: the origin's 5-second catalog memo, then 5 seconds fresh and
8242
- * 5 stale at the CDN. A revoked API key can read a cached catalog up to
8548
+ * A device can see a catalog, or a scope's lack of one, up to 15 seconds
8549
+ * after a deploy or a Roll back replaced it: the origin's 5-second catalog
8550
+ * memo, then 5 seconds fresh and 5 stale at the CDN. A revoked API key can read a cached catalog up to
8243
8551
  * 10 seconds. Devices and caches that don't read the header keep
8244
8552
  * `Cache-Control`.
8245
8553
  */
@@ -8318,38 +8626,53 @@ const catalogResponse = async (catalog, request) => {
8318
8626
  };
8319
8627
  const createReleaseCatalogRouteHandlers = () => {
8320
8628
  const cache = /* @__PURE__ */ new Map();
8629
+ const evict = (insertedHit) => {
8630
+ const now = Date.now();
8631
+ let oldestMiss;
8632
+ let oldest;
8633
+ for (const [key, entry] of cache) if (entry.expiresAt <= now) cache.delete(key);
8634
+ else {
8635
+ if (entry.row === null) oldestMiss ??= key;
8636
+ oldest ??= key;
8637
+ }
8638
+ if (cache.size <= ORIGIN_CACHE_MAX_ENTRIES) return;
8639
+ const victim = oldestMiss ?? (insertedHit ? oldest : void 0);
8640
+ if (victim !== void 0) cache.delete(victim);
8641
+ };
8321
8642
  const inFlight = /* @__PURE__ */ new Map();
8322
- const loadCatalog = async (key, load) => {
8323
- const cached = cache.get(key);
8643
+ const loadRow = async (scopeKey, load) => {
8644
+ const cached = cache.get(scopeKey);
8324
8645
  if (cached !== void 0 && cached.expiresAt > Date.now()) {
8325
- cache.delete(key);
8326
- cache.set(key, cached);
8327
- return cached.catalog;
8646
+ cache.delete(scopeKey);
8647
+ cache.set(scopeKey, cached);
8648
+ return cached.row;
8328
8649
  }
8329
- if (cached !== void 0) cache.delete(key);
8330
- const pending = inFlight.get(key);
8650
+ if (cached !== void 0) cache.delete(scopeKey);
8651
+ const pending = inFlight.get(scopeKey);
8331
8652
  if (pending !== void 0) return pending;
8332
- const next = load().then((catalog) => {
8333
- if (catalog !== null) {
8334
- cache.set(key, {
8335
- catalog,
8336
- expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
8337
- });
8338
- while (cache.size > ORIGIN_CACHE_MAX_ENTRIES) {
8339
- const oldestKey = cache.keys().next().value;
8340
- if (oldestKey === void 0) break;
8341
- cache.delete(oldestKey);
8342
- }
8343
- }
8344
- return catalog;
8653
+ const next = load().then((row) => {
8654
+ cache.set(scopeKey, {
8655
+ row,
8656
+ expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
8657
+ });
8658
+ if (cache.size > ORIGIN_CACHE_MAX_ENTRIES) evict(row !== null);
8659
+ return row;
8345
8660
  });
8346
- inFlight.set(key, next);
8661
+ inFlight.set(scopeKey, next);
8347
8662
  try {
8348
8663
  return await next;
8349
8664
  } finally {
8350
- inFlight.delete(key);
8665
+ inFlight.delete(scopeKey);
8351
8666
  }
8352
8667
  };
8668
+ const loadCatalog = async (core, input) => {
8669
+ const scopeKey = releaseCatalogScopeKeyOf(input);
8670
+ const parsed = await loadRow(scopeKey, async () => {
8671
+ const row = await core.getReleaseCatalogRow(scopeKey);
8672
+ return row === null ? null : parseReleaseCatalogRow(row);
8673
+ });
8674
+ return projectParsedReleaseCatalogRow(parsed, input, scopeKey);
8675
+ };
8353
8676
  return {
8354
8677
  appVersionReleaseCatalog: async (params, request, { core }) => {
8355
8678
  const rawAppVersion = requireRouteParam(params, "appVersion");
@@ -8363,7 +8686,7 @@ const createReleaseCatalogRouteHandlers = () => {
8363
8686
  };
8364
8687
  const invalid = invalidScope(input);
8365
8688
  if (invalid) return invalid;
8366
- return catalogResponse(await loadCatalog(`app-version:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
8689
+ return catalogResponse(await loadCatalog(core, input), request);
8367
8690
  },
8368
8691
  fingerprintReleaseCatalog: async (params, request, { core }) => {
8369
8692
  const input = {
@@ -8374,7 +8697,7 @@ const createReleaseCatalogRouteHandlers = () => {
8374
8697
  };
8375
8698
  const invalid = invalidScope(input);
8376
8699
  if (invalid) return invalid;
8377
- return catalogResponse(await loadCatalog(`fingerprint:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
8700
+ return catalogResponse(await loadCatalog(core, input), request);
8378
8701
  },
8379
8702
  artifactV2: async (params, _request, { core }) => {
8380
8703
  const info = await core.getArtifactInfo(requireRouteParam(params, "targetBundleId"), requireRouteParam(params, "currentBundleId"), 2);
@@ -11657,13 +11980,80 @@ const breakdownOf = (rows) => {
11657
11980
  });
11658
11981
  };
11659
11982
  /**
11983
+ * The breakdown rows a failures read takes from one hour. An hour holds a
11984
+ * row per release, stage, reason, and detail that failed in it, a handful in
11985
+ * practice, and an incident across several releases and error codes still
11986
+ * fits; but a client with the app's API key can report any number of
11987
+ * details.
11988
+ */
11989
+ const FAILURE_ROWS_PER_HOUR = 20;
11990
+ /**
11991
+ * One query's stored rows: an hour's bound and one more row, on every shard,
11992
+ * so an hour past its bound costs at most one query's worth of rows more.
11993
+ */
11994
+ const FAILURE_QUERY_LIMIT = Math.min(PAGE, 168);
11995
+ /**
11996
+ * A channel's breakdown rows over a range, newest first, up to
11997
+ * {@link FAILURE_ROWS_PER_HOUR} an hour: 480 rows for a day, 14,400 for 30
11998
+ * days, however many details clients report. An hour that holds more is read
11999
+ * no further, and the read goes on from the hour before it with a new query;
12000
+ * the hour is listed in `cappedHours`, since its failures count only in part.
12001
+ * Every other hour counts every failure it holds.
12002
+ */
12003
+ const failureRowsByHour = async (db, platform, channel, timeRange) => {
12004
+ const read = (end, cursor) => db.findAggregates("insights_failures", {
12005
+ index: "byScope",
12006
+ where: {
12007
+ platform,
12008
+ channel
12009
+ },
12010
+ range: {
12011
+ gte: timeRange.start,
12012
+ lt: end
12013
+ },
12014
+ order: "desc",
12015
+ limit: FAILURE_QUERY_LIMIT,
12016
+ ...cursor === void 0 ? {} : { cursor }
12017
+ });
12018
+ const rows = [];
12019
+ const cappedHours = [];
12020
+ const perHour = /* @__PURE__ */ new Map();
12021
+ let end = timeRange.end;
12022
+ let cursor;
12023
+ while (end > timeRange.start) {
12024
+ const page = await read(end, cursor);
12025
+ let capped;
12026
+ for (const row of page.rows) {
12027
+ const hour = row.bucket_start_ms;
12028
+ const count = (perHour.get(hour) ?? 0) + 1;
12029
+ if (count > FAILURE_ROWS_PER_HOUR) {
12030
+ capped = hour;
12031
+ break;
12032
+ }
12033
+ perHour.set(hour, count);
12034
+ rows.push(row);
12035
+ }
12036
+ if (capped !== void 0) {
12037
+ cappedHours.unshift(capped);
12038
+ end = capped;
12039
+ cursor = void 0;
12040
+ } else if (page.next === void 0) break;
12041
+ else cursor = page.next;
12042
+ }
12043
+ return {
12044
+ rows,
12045
+ cappedHours
12046
+ };
12047
+ };
12048
+ /**
11660
12049
  * A release's or a channel's update failures. Since a release's first
11661
12050
  * report: its lifetime counters and failed installations. Over a time range
11662
12051
  * of at most 30 days: failures, failed checks, and the breakdown by stage,
11663
12052
  * reason, and detail, all summed from the breakdown's hourly rows; downloads
11664
12053
  * from the counters; failed installations from their sketches. A release reads hourly rows, a
11665
12054
  * channel daily rows past 48 hours like its activity; the breakdown's rows
11666
- * are hourly, so its coverage is the raw period's.
12055
+ * are hourly, so its coverage is the raw period's, and partial when an hour
12056
+ * held more breakdown rows than a read takes from it.
11667
12057
  */
11668
12058
  const getUpdateFailures = async (db, input, now, retention) => {
11669
12059
  const { platform, channel, releaseId, timeRange } = input;
@@ -11725,7 +12115,7 @@ const getUpdateFailures = async (db, input, now, retention) => {
11725
12115
  days,
11726
12116
  kept.hour
11727
12117
  ];
11728
- const [counters, failures, checks, active, rows] = await Promise.all([
12118
+ const [counters, failures, checks, active, { rows, cappedHours }] = await Promise.all([
11729
12119
  counterRows(db, parts, ...window),
11730
12120
  sketchRows(db, failure, ...window),
11731
12121
  days ? sketchRows(db, {
@@ -11733,25 +12123,17 @@ const getUpdateFailures = async (db, input, now, retention) => {
11733
12123
  scopeKind: "check"
11734
12124
  }, ...window) : [],
11735
12125
  days ? sketchRows(db, usageParts(channel, platform), ...window) : [],
11736
- drain((page) => db.findAggregates("insights_failures", {
11737
- index: "byScope",
11738
- where: {
11739
- platform,
11740
- channel
11741
- },
11742
- range: {
11743
- gte: timeRange.start,
11744
- lt: timeRange.end
11745
- },
11746
- limit: PAGE,
11747
- ...page
11748
- }))
12126
+ failureRowsByHour(db, platform, channel, timeRange)
11749
12127
  ]);
11750
12128
  const total = (field) => counters.reduce((sum, row) => sum + row[field], 0);
11751
12129
  const scoped = rows.filter((row) => FAILURE_STAGES.has(row.stage) && (releaseId === void 0 || row.release_id === releaseId));
11752
12130
  const failuresAt = (counted) => scoped.reduce((sum, row) => sum + (counted(row.stage) ? Math.max(0, row.events) : 0), 0);
12131
+ const coverage = coverageOf(timeRange.start, kept.hour);
11753
12132
  return {
11754
- coverage: coverageOf(timeRange.start, kept.hour),
12133
+ coverage: cappedHours.length === 0 ? coverage : {
12134
+ kind: "partial",
12135
+ sinceMs: coverage.sinceMs
12136
+ },
11755
12137
  measuredAtMs: at,
11756
12138
  failedUpdates: failuresAt((stage) => stage !== "check"),
11757
12139
  failedInstallations: failed(failures),
@@ -11763,7 +12145,8 @@ const getUpdateFailures = async (db, input, now, retention) => {
11763
12145
  failedInstallations: failed(checks),
11764
12146
  activeInstallations: countDistinct(mergeDistinct(active.map((row) => row.activity_users)))
11765
12147
  } } : {},
11766
- breakdown: breakdownOf(scoped)
12148
+ breakdown: breakdownOf(scoped),
12149
+ ...cappedHours.length === 0 ? {} : { cappedHours }
11767
12150
  };
11768
12151
  };
11769
12152
  //#endregion
@@ -13035,14 +13418,67 @@ const createFirestoreStore = ({ firestore, collection, nativePageSize }) => {
13035
13418
  };
13036
13419
  };
13037
13420
  //#endregion
13421
+ //#region src/googleCredential.ts
13422
+ const CLOUD_PLATFORM_SCOPE = "https://www.googleapis.com/auth/cloud-platform";
13423
+ /**
13424
+ * Resolves application default credentials as Firestore will, from
13425
+ * GOOGLE_APPLICATION_CREDENTIALS's file or the environment, for the app's
13426
+ * `projectId`, so it neither exchanges a token nor discovers a project
13427
+ * Firestore itself wouldn't. Only `applicationDefault()`'s credential: a
13428
+ * service account's or refresh token's was read from its file already.
13429
+ */
13430
+ const resolveApplicationDefault = async (credential, projectId) => {
13431
+ if (credential.constructor.name !== "ApplicationDefaultCredential") return;
13432
+ const { GoogleAuth } = await import("google-auth-library");
13433
+ await new GoogleAuth({
13434
+ scopes: [CLOUD_PLATFORM_SCOPE],
13435
+ ...projectId === void 0 ? {} : { projectId }
13436
+ }).getClient();
13437
+ };
13438
+ //#endregion
13038
13439
  //#region src/firebaseDatabase.ts
13440
+ /**
13441
+ * `store` that loads `credential` before its first call: one that cannot
13442
+ * load, such as GOOGLE_APPLICATION_CREDENTIALS naming a missing file, fails
13443
+ * that call with what is wrong. Firestore's own client would also reject a
13444
+ * promise nobody awaits, which ends a CLI process with a stack trace.
13445
+ */
13446
+ const withLoadedCredential = (store, credential, projectId) => {
13447
+ let loaded;
13448
+ const load = () => loaded ??= resolveApplicationDefault(credential, projectId).then(() => void 0, (error) => {
13449
+ loaded = void 0;
13450
+ throw new Error(`Could not load the Google credentials for Firestore: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
13451
+ });
13452
+ const { deleteConsumed } = store;
13453
+ return {
13454
+ ...store,
13455
+ get: async (keys) => {
13456
+ await load();
13457
+ return store.get(keys);
13458
+ },
13459
+ query: async (range) => {
13460
+ await load();
13461
+ return store.query(range);
13462
+ },
13463
+ write: async (ops) => {
13464
+ await load();
13465
+ return store.write(ops);
13466
+ },
13467
+ ...deleteConsumed && { deleteConsumed: async (keys) => {
13468
+ await load();
13469
+ return deleteConsumed.call(store, keys);
13470
+ } }
13471
+ };
13472
+ };
13039
13473
  const adapterOf = ({ databaseId, collection = FIREBASE_V1_COLLECTION, aggregateBatching: _, ...appOptions }) => {
13040
13474
  const app = (0, firebase_admin_app.getApps)().length ? (0, firebase_admin_app.getApp)() : (0, firebase_admin_app.initializeApp)(appOptions);
13041
13475
  const firestore = databaseId ? (0, firebase_admin_firestore.getFirestore)(app, databaseId) : (0, firebase_admin_firestore.getFirestore)(app);
13042
- return createKvAdapter({ store: createFirestoreStore({
13476
+ const store = createFirestoreStore({
13043
13477
  firestore,
13044
13478
  collection
13045
- }) });
13479
+ });
13480
+ const credential = app.options.credential;
13481
+ return createKvAdapter({ store: appOptions.credential === void 0 || credential === void 0 || process.env["FIRESTORE_EMULATOR_HOST"] ? store : withLoadedCredential(store, credential, app.options.projectId) });
13046
13482
  };
13047
13483
  /**
13048
13484
  * The resource this database reaches, without credentials, under the key
@@ -13202,9 +13638,10 @@ const adminOptions = ((0, firebase_admin_app.getApps)()[0] ?? (0, firebase_admin
13202
13638
  const storageBucket = adminOptions.storageBucket;
13203
13639
  const cdnUrl = process.env.HOT_UPDATER_CDN_URL;
13204
13640
  if (!storageBucket) throw new Error("Firebase runtime requires storageBucket to read bundle manifests.");
13641
+ const { credential: _runtimeCredential, ...databaseOptions } = adminOptions;
13205
13642
  const hotUpdater = createHotUpdater({
13206
13643
  database: firebaseDatabase({
13207
- ...adminOptions,
13644
+ ...databaseOptions,
13208
13645
  databaseId: HotUpdater.FIRESTORE_DATABASE_ID
13209
13646
  }),
13210
13647
  plugins: [