@hot-updater/azure 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.
@@ -5738,43 +5738,6 @@ const withSchemaFence = (adapter, adapterName, expected, fix) => {
5738
5738
  const METER = Symbol.for("@hot-updater/plugin-core/read-meter");
5739
5739
  const readMeterOf = (database) => typeof database === "object" && database !== null ? database[METER] : void 0;
5740
5740
  //#endregion
5741
- //#region ../plugin-core/dist/engine/db/schemaSettings.mjs
5742
- const storedSettings = async (adapter, keys) => {
5743
- const rows = await readSettings(adapter, keys);
5744
- return new Map(keys.map((key, position) => [key, rows[position] ?? null]));
5745
- };
5746
- const writeSchemaSettings = async (adapter, adapterName, settings) => {
5747
- const stored = await storedSettings(adapter, Object.keys(settings));
5748
- const ops = Object.entries(settings).flatMap(([key, value]) => {
5749
- const row = stored.get(key);
5750
- if (row === null || row === void 0) return [{
5751
- type: "insert",
5752
- table: SETTINGS_TABLE,
5753
- row: {
5754
- key,
5755
- value,
5756
- _v: 0
5757
- }
5758
- }];
5759
- if (row.value === value) return [];
5760
- return [{
5761
- type: "patch",
5762
- table: SETTINGS_TABLE,
5763
- key: [key],
5764
- set: { value },
5765
- guard: { v: Number(row._v) },
5766
- previous: row
5767
- }];
5768
- });
5769
- if (ops.length === 0) return;
5770
- if (!(await adapter.write(ops)).ok) throw new Error(`${adapterName}: the schema settings changed during the migration; run it again.`);
5771
- };
5772
- const migrateSchema = async (adapter, adapterName, tables, settings) => {
5773
- if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
5774
- await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
5775
- await writeSchemaSettings(adapter, adapterName, settings);
5776
- };
5777
- //#endregion
5778
5741
  //#region ../plugin-core/dist/engine/core/schema.mjs
5779
5742
  const CHANNEL_ID = {
5780
5743
  type: "string",
@@ -5961,9 +5924,17 @@ const releases = defineTable({
5961
5924
  all: {
5962
5925
  eq: [],
5963
5926
  sort: ["id"]
5927
+ },
5928
+ scopes: {
5929
+ eq: [],
5930
+ sort: ["scope_key"]
5964
5931
  }
5965
5932
  }
5966
5933
  });
5934
+ const LATE_INDEXES = [{
5935
+ table: "releases",
5936
+ index: "scopes"
5937
+ }];
5967
5938
  const releaseCatalogs = defineTable({
5968
5939
  scope_key: {
5969
5940
  type: "string",
@@ -6291,6 +6262,90 @@ const refuseV0Database = (adapterName, stored) => {
6291
6262
  if (typeof version !== "string" || stored.has("schema.engine")) return;
6292
6263
  throw new HotUpdaterSchemaMigrationRequiredError(adapterName, version);
6293
6264
  };
6265
+ const compareVersions = (left, right) => {
6266
+ const parse = (version) => /^\d+(?:\.\d+)*$/u.test(version) ? version.split(".").map(Number) : [NaN];
6267
+ const [a, b] = [parse(left), parse(right)];
6268
+ if ([...a, ...b].some(Number.isNaN)) return NaN;
6269
+ for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
6270
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
6271
+ if (difference !== 0) return difference;
6272
+ }
6273
+ return 0;
6274
+ };
6275
+ const DEFAULT_ORDERED_SETTINGS = ["schema.core"];
6276
+ const refuseNewerSchema = (adapterName, stored, settings, ordered = DEFAULT_ORDERED_SETTINGS) => {
6277
+ const newer = ordered.flatMap((key) => {
6278
+ const found = stored.get(key);
6279
+ const expected = settings[key];
6280
+ return typeof found === "string" && expected !== void 0 && compareVersions(found, expected) > 0 ? [{
6281
+ key,
6282
+ found,
6283
+ expected
6284
+ }] : [];
6285
+ });
6286
+ const core = newer.find(({ key }) => key === "schema.core");
6287
+ if (core === void 0) return;
6288
+ throw new Error(`${adapterName}: the database was migrated by Hot Updater ${core.found} (${newer.map(({ key, found, expected }) => `${key} "${found}", this CLI's "${expected}"`).join("; ")}). Upgrade hot-updater to ${core.found} or later; nothing was written.`);
6289
+ };
6290
+ const settingsOperation = (stored, changed) => ({
6291
+ type: "custom",
6292
+ description: `Record ${changed.map(([key, value]) => {
6293
+ const found = stored.get(key);
6294
+ return typeof found === "string" ? `${key} ${found} → ${value}` : `${key} ${value}`;
6295
+ }).join(", ")}`
6296
+ });
6297
+ //#endregion
6298
+ //#region ../plugin-core/dist/engine/db/schemaSettings.mjs
6299
+ const storedSettings = async (adapter, keys) => {
6300
+ const rows = await readSettings(adapter, keys);
6301
+ return new Map(keys.map((key, position) => [key, rows[position] ?? null]));
6302
+ };
6303
+ const writeSchemaSettings = async (adapter, adapterName, settings, ordered) => {
6304
+ const stored = await storedSettings(adapter, Object.keys(settings));
6305
+ refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
6306
+ const ops = Object.entries(settings).flatMap(([key, value]) => {
6307
+ const row = stored.get(key);
6308
+ if (row === null || row === void 0) return [{
6309
+ type: "insert",
6310
+ table: SETTINGS_TABLE,
6311
+ row: {
6312
+ key,
6313
+ value,
6314
+ _v: 0
6315
+ }
6316
+ }];
6317
+ if (row.value === value) return [];
6318
+ return [{
6319
+ type: "patch",
6320
+ table: SETTINGS_TABLE,
6321
+ key: [key],
6322
+ set: { value },
6323
+ guard: { v: Number(row._v) },
6324
+ previous: row
6325
+ }];
6326
+ });
6327
+ if (ops.length === 0) return;
6328
+ if (!(await adapter.write(ops)).ok) throw new Error(`${adapterName}: the schema settings changed during the migration; run it again.`);
6329
+ };
6330
+ const fillLateIndexes = async (adapter, tables, { dryRun = false } = {}) => {
6331
+ const fillIndex = adapter.migrations?.fillIndex;
6332
+ if (fillIndex === void 0) return [];
6333
+ const lacking = [];
6334
+ for (const { table: name, index } of LATE_INDEXES) {
6335
+ const table = tables.find((candidate) => candidate.name === name);
6336
+ if (table === void 0) continue;
6337
+ if (await fillIndex(table, index, { dryRun }) > 0) lacking.push(`${name}.${index}`);
6338
+ }
6339
+ return lacking;
6340
+ };
6341
+ const migrateSchema = async (adapter, adapterName, tables, settings, ordered) => {
6342
+ if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
6343
+ const stored = await storedSettings(adapter, Object.keys(settings)).catch(() => void 0);
6344
+ if (stored !== void 0) refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
6345
+ await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
6346
+ await fillLateIndexes(adapter, tables);
6347
+ await writeSchemaSettings(adapter, adapterName, settings, ordered);
6348
+ };
6294
6349
  //#endregion
6295
6350
  //#region ../plugin-core/dist/engine/database/cursor.mjs
6296
6351
  const encoder$3 = new TextEncoder();
@@ -7175,22 +7230,27 @@ const createEngineMigrator = (options) => {
7175
7230
  const makeResult = async (migrate = {}) => {
7176
7231
  const stored = await options.readSettings();
7177
7232
  refuseV0Database(options.adapterName, stored);
7178
- if (Object.entries(options.settings).every(([key, value]) => stored.get(key) === value)) return getEmptyMigrationResult();
7179
- return {
7180
- operations: [...options.schema.tables.map((table) => ({
7181
- type: "create-table",
7182
- value: {
7183
- ormName: table.name,
7184
- columns: Object.fromEntries(table.columns.map((column) => [column.name, {
7185
- ormName: column.name,
7186
- type: column.type
7187
- }]))
7233
+ refuseNewerSchema(options.adapterName, stored, options.settings, options.ordered);
7234
+ const changed = Object.entries(options.settings).filter(([key, value]) => stored.get(key) !== value);
7235
+ if (changed.length === 0) {
7236
+ const lacking = await fillLateIndexes(options.adapter, options.schema.tables, { dryRun: true });
7237
+ if (lacking.length === 0) return getEmptyMigrationResult();
7238
+ return {
7239
+ operations: [{
7240
+ type: "custom",
7241
+ description: `Write the index items rows lack: ${lacking.join(", ")}`
7242
+ }],
7243
+ execute: async () => {
7244
+ await fillLateIndexes(options.adapter, options.schema.tables);
7188
7245
  }
7189
- })), ...migrate.updateSettings === false ? [] : [{
7246
+ };
7247
+ }
7248
+ return {
7249
+ operations: [{
7190
7250
  type: "custom",
7191
- description: `Write the schema settings: ${Object.keys(options.settings).join(", ")}`
7192
- }]],
7193
- execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings)
7251
+ description: "Create the tables and indexes the database lacks"
7252
+ }, ...migrate.updateSettings === false ? [] : [settingsOperation(stored, changed)]],
7253
+ execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings, options.ordered)
7194
7254
  };
7195
7255
  };
7196
7256
  return {
@@ -7218,8 +7278,10 @@ const coreSettings = {
7218
7278
  };
7219
7279
  const coreTarget = {
7220
7280
  schema: coreSchema,
7221
- settings: coreSettings
7281
+ settings: coreSettings,
7282
+ ordered: ["schema.core"]
7222
7283
  };
7284
+ const isOfficialPlugin$1 = (plugin) => Reflect.get(plugin, Symbol.for("@hot-updater/server/official-plugin")) === true;
7223
7285
  resolveSchema([aggregateBatchingModule]).tables;
7224
7286
  const pluginSettings = (plugins) => Object.fromEntries(plugins.map(({ id, schemaVersion }) => [`schema.${id}`, schemaVersion]));
7225
7287
  const pluginModule = ({ id, schema, namespace }) => ({
@@ -7232,15 +7294,17 @@ const toolingTargetOf = (plugins) => plugins.length === 0 ? coreTarget : {
7232
7294
  settings: {
7233
7295
  ...coreSettings,
7234
7296
  ...pluginSettings(plugins)
7235
- }
7297
+ },
7298
+ ordered: [...coreTarget.ordered, ...plugins.flatMap((plugin) => isOfficialPlugin$1(plugin) ? [`schema.${plugin.id}`] : [])]
7236
7299
  };
7237
7300
  const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBatching, retry, readSettings: readStored }) => {
7238
7301
  const fenced = withSchemaFence(adapter, name, coreSettings);
7239
- const createMigrator = ({ schema, settings } = coreTarget) => createEngineMigrator({
7302
+ const createMigrator = ({ schema, settings, ordered } = coreTarget) => createEngineMigrator({
7240
7303
  adapterName: name,
7241
7304
  adapter,
7242
7305
  schema,
7243
7306
  settings,
7307
+ ordered,
7244
7308
  readSettings: readStored ?? (async () => {
7245
7309
  const rows = await readSettings(adapter, Object.keys(settings)).catch((error) => {
7246
7310
  if (isMissingSchemaError(error)) return [];
@@ -7263,6 +7327,11 @@ const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBa
7263
7327
  //#region ../plugin-core/dist/engine/database/engineTransaction.mjs
7264
7328
  var StaleReadError = class extends Error {};
7265
7329
  const idOf = (table, key) => JSON.stringify([table, key]);
7330
+ const versionsOf = (ops) => JSON.stringify(ops.map((op) => op.type === "insert" ? [op.table.name, rowKey(op.table, op.row)] : [
7331
+ op.table.name,
7332
+ op.key,
7333
+ "guard" in op ? op.guard?.v : void 0
7334
+ ]));
7266
7335
  const versionOf = (row) => Number(row["_v"]);
7267
7336
  const isKeyed = (value) => value !== null && value !== void 0;
7268
7337
  const misuse = (table, message) => new DatabaseTransactionError(`${table}: ${message}`);
@@ -7594,7 +7663,9 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
7594
7663
  assertOutsideTransaction();
7595
7664
  let run;
7596
7665
  let negative;
7597
- for (let round = 0; round < attempts; round += 1) {
7666
+ let failures = 0;
7667
+ let lost;
7668
+ for (let round = 0;; round += 1) {
7598
7669
  const delay = round && Math.min(maxDelayMs, baseDelayMs * 2 ** (round - 1));
7599
7670
  if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay / 2 + Math.random() * (delay / 2)));
7600
7671
  run ??= await attempt(fn).catch((error) => {
@@ -7603,6 +7674,8 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
7603
7674
  });
7604
7675
  if (run === void 0) {
7605
7676
  onRetry?.("rerun", round + 1);
7677
+ lost = void 0;
7678
+ if ((failures += 1) >= attempts) break;
7606
7679
  continue;
7607
7680
  }
7608
7681
  let aggregates;
@@ -7613,8 +7686,14 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
7613
7686
  negative = error;
7614
7687
  onRetry?.("rerun", round + 1);
7615
7688
  run = void 0;
7689
+ lost = void 0;
7690
+ if ((failures += 1) >= attempts) break;
7616
7691
  continue;
7617
7692
  }
7693
+ const versions = versionsOf(aggregates);
7694
+ if (lost !== void 0 && versions !== lost) failures -= 1;
7695
+ lost = void 0;
7696
+ if (failures >= attempts) break;
7618
7697
  const ops = [...run.ops, ...aggregates];
7619
7698
  if (ops.length <= 1 && ops.every(({ type }) => type === "check")) return run.result;
7620
7699
  if (!adapter.fits(ops)) throw new DatabaseConstraintError("too_large", ops[0].table.name);
@@ -7628,12 +7707,16 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
7628
7707
  const failed = "failedOp" in outcome ? outcome.failedOp : void 0;
7629
7708
  if (failed === void 0 || failed >= run.ops.length) {
7630
7709
  onRetry?.("resend", round + 1);
7710
+ failures += 1;
7711
+ if (failed !== void 0) lost = versions;
7712
+ else if (failures >= attempts) break;
7631
7713
  continue;
7632
7714
  }
7633
7715
  const reason = await classify(ops[failed], run.read);
7634
7716
  if (reason) throw new DatabaseConstraintError(reason, ops[failed].table.name);
7635
7717
  onRetry?.("rerun", round + 1);
7636
7718
  run = void 0;
7719
+ if ((failures += 1) >= attempts) break;
7637
7720
  }
7638
7721
  throw negative ?? new DatabaseConflictError(`The transaction conflicted ${attempts} times.`);
7639
7722
  } };
@@ -7987,9 +8070,9 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
7987
8070
  const at = row && expiresAt(table, row);
7988
8071
  return at === void 0 ? {} : { expiresAt: at };
7989
8072
  };
7990
- const itemsOf = (layout, row) => {
8073
+ const itemsOf = (layout, row, indexes = layout.indexed) => {
7991
8074
  const items = /* @__PURE__ */ new Map();
7992
- for (const index of row === null ? [] : layout.indexed) for (const eq of indexEntries(layout.table, index, row)) {
8075
+ for (const index of row === null ? [] : indexes) for (const eq of indexEntries(layout.table, index, row)) {
7993
8076
  const pk = partition(layout, index, eq);
7994
8077
  const sk = index.unique ? ONLY : encodeKvKey(indexOrderTuple(layout.table, index, row)) || ONLY;
7995
8078
  items.set(JSON.stringify([pk, sk]), {
@@ -8130,6 +8213,69 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
8130
8213
  lte: lt.endsWith(SEPARATOR) ? lt.slice(0, -1) : lt
8131
8214
  };
8132
8215
  };
8216
+ const fillOps = (layout, index, row) => [{
8217
+ type: "check",
8218
+ key: rowItem(layout, rowKey(layout.table, row)),
8219
+ condition: { v: Number(row["_v"]) }
8220
+ }, ...[...itemsOf(layout, row, [index]).values()].map(({ key }) => ({
8221
+ type: "put",
8222
+ key,
8223
+ value: copyOf(layout, row),
8224
+ ...stamp(layout.table, row)
8225
+ }))];
8226
+ const fillRow = async (layout, index, first) => {
8227
+ const key = rowItem(layout, rowKey(layout.table, first));
8228
+ let row = first;
8229
+ for (let attempt = 0; row !== null; attempt += 1) {
8230
+ if (attempt === 8) throw new Error(`${layout.table.name}.${index.name}: a row kept changing while its index items were written; run the migration again.`);
8231
+ if ((await store.write(fillOps(layout, index, row))).ok) return;
8232
+ [row] = await store.get([key]);
8233
+ }
8234
+ };
8235
+ const fillIndex = async (table, name, { dryRun = false } = {}) => {
8236
+ const layout = layoutOf(table);
8237
+ const index = layout.indexed.find((candidate) => candidate.name === name);
8238
+ if (index === void 0) return 0;
8239
+ if (index.unique) throw new DatabaseAdapterContractError(`${table.name}.${name} is unique: its items can't be written for rows stored before it, since two of them may hold one value.`);
8240
+ const { items: most, bytes } = store.limits;
8241
+ let lacking = 0;
8242
+ for (let after;;) {
8243
+ const page = await store.query({
8244
+ pk: layout.rows,
8245
+ order: "asc",
8246
+ limit: 100,
8247
+ after
8248
+ });
8249
+ const rows = page.items.map(({ value }) => value);
8250
+ const keys = rows.map((row) => [...itemsOf(layout, row, [index]).values()].map(({ key }) => key));
8251
+ const wanted = keys.flat();
8252
+ const found = wanted.length === 0 ? [] : await store.get(wanted);
8253
+ let at = 0;
8254
+ const missing = rows.filter((_, position) => {
8255
+ return found.slice(at, at += keys[position].length).some((item) => item === null);
8256
+ });
8257
+ lacking += missing.length;
8258
+ if (!dryRun) {
8259
+ let chunk = [];
8260
+ let ops = [];
8261
+ const flush = async () => {
8262
+ if (ops.length > 0 && !(await store.write(ops)).ok) for (const row of chunk) await fillRow(layout, index, row);
8263
+ chunk = [];
8264
+ ops = [];
8265
+ };
8266
+ for (const row of missing) {
8267
+ const next = fillOps(layout, index, row);
8268
+ const size = (list) => list.reduce((sum, op) => sum + encoder.encode(op.key.pk + op.key.sk + JSON.stringify(op.type === "put" ? op.value : null)).length, 0);
8269
+ if (chunk.length > 0 && (ops.length + next.length > most || size(ops) + size(next) > bytes)) await flush();
8270
+ chunk.push(row);
8271
+ ops.push(...next);
8272
+ }
8273
+ await flush();
8274
+ }
8275
+ if (!page.more || page.items.length === 0) return lacking;
8276
+ after = page.items.at(-1).sk;
8277
+ }
8278
+ };
8133
8279
  return {
8134
8280
  id: store.id,
8135
8281
  fits(ops) {
@@ -8189,13 +8335,16 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
8189
8335
  const layout = layoutOf(table);
8190
8336
  return store.deleteConsumed(rows.flatMap((row) => [rowItem(layout, rowKey(table, row)), ...[...itemsOf(layout, row).values()].map(({ key }) => key)]));
8191
8337
  } },
8192
- migrations: { apply: async () => store.migrations?.apply() },
8338
+ migrations: {
8339
+ apply: async () => store.migrations?.apply(),
8340
+ fillIndex
8341
+ },
8193
8342
  ...store.dispose === void 0 ? {} : { dispose: () => store.dispose() }
8194
8343
  };
8195
8344
  };
8196
8345
  //#endregion
8197
8346
  //#region ../../packages/server/dist/version.mjs
8198
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.49";
8347
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.50";
8199
8348
  //#endregion
8200
8349
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
8201
8350
  const createVersionRouteHandlers = (plugins = []) => {
@@ -8321,9 +8470,14 @@ const releaseCatalogScopeKeyOf = (input) => input.strategy === "APP_VERSION" ? c
8321
8470
  platform: input.platform,
8322
8471
  strategy: "FINGERPRINT"
8323
8472
  });
8324
- const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
8325
- 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;
8326
- const compiled = parseCompiledCatalog(row.payload, input.strategy);
8473
+ const parseReleaseCatalogRow = ({ payload, ...row }) => ({
8474
+ row,
8475
+ compiled: parseCompiledCatalog(payload, row.strategy)
8476
+ });
8477
+ const projectParsedReleaseCatalogRow = (parsed, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
8478
+ if (parsed === null) return null;
8479
+ const { row, compiled } = parsed;
8480
+ if (row.platform !== input.platform || row.strategy !== input.strategy || row.channel_key !== input.channelKey || row.scope_key !== scopeKey || row.fingerprint_hash !== (input.strategy === "FINGERPRINT" ? input.fingerprintHash : null)) return null;
8327
8481
  const appVersion = input.strategy === "APP_VERSION" ? input.appVersion : void 0;
8328
8482
  return {
8329
8483
  catalogId: row.catalog_id,
@@ -8336,6 +8490,7 @@ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyO
8336
8490
  scopeKey
8337
8491
  };
8338
8492
  };
8493
+ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => projectParsedReleaseCatalogRow(row === null ? null : parseReleaseCatalogRow(row), input, scopeKey);
8339
8494
  //#endregion
8340
8495
  //#region ../../packages/server/dist/db/updateArtifacts.mjs
8341
8496
  const HBC_ASSET_PATH_RE = /\.bundle$/;
@@ -9178,7 +9333,29 @@ const createCoreReads = (db, storage) => {
9178
9333
  ...after(input)
9179
9334
  })).rows.map(toCatalogRow);
9180
9335
  },
9181
- async listChannels() {
9336
+ async listReleaseScopeKeys(input) {
9337
+ const scopeKeys = [];
9338
+ for (let last = input.after ?? ""; scopeKeys.length < input.limit;) {
9339
+ const { rows } = await db.findMany("releases", {
9340
+ index: "scopes",
9341
+ where: {},
9342
+ limit: 1,
9343
+ range: { gt: last }
9344
+ });
9345
+ if (rows[0] === void 0) break;
9346
+ last = rows[0].scope_key;
9347
+ scopeKeys.push(last);
9348
+ }
9349
+ return scopeKeys;
9350
+ },
9351
+ async listChannels(input) {
9352
+ if (input !== void 0) return (await db.findMany("channels", {
9353
+ index: "all",
9354
+ where: {},
9355
+ order: input.order ?? "asc",
9356
+ limit: input.limit,
9357
+ ...after(input)
9358
+ })).rows.map(toChannelRow);
9182
9359
  return (await drain$1((page) => db.findMany("channels", {
9183
9360
  index: "all",
9184
9361
  where: {},
@@ -9186,6 +9363,11 @@ const createCoreReads = (db, storage) => {
9186
9363
  ...page
9187
9364
  }))).map(toChannelRow);
9188
9365
  },
9366
+ async getChannels(ids) {
9367
+ const unique = [...new Set(ids)];
9368
+ if (unique.length === 0) return [];
9369
+ return (await db.findByKeys("channels", unique.map((id) => ({ id })))).flatMap((row) => row ? [toChannelRow(row)] : []);
9370
+ },
9189
9371
  async findChannelByName(name) {
9190
9372
  const row = await db.findOne("channels", { name });
9191
9373
  return row === null ? null : toChannelRow(row);
@@ -10001,24 +10183,26 @@ const checkScope = (scope) => {
10001
10183
  });
10002
10184
  if (scope.strategy === "FINGERPRINT" !== (scope.fingerprintHash !== null) || scope.scopeKey !== expected) fail$1("INVALID_SCOPE", "Release catalog scope metadata is inconsistent");
10003
10185
  };
10004
- const enabledReleases = async (tx, scopeKey) => {
10186
+ const drainReleases = async (page) => {
10005
10187
  const rows = [];
10006
10188
  let cursor;
10007
10189
  do {
10008
- const page = await tx.findMany("releases", {
10009
- index: "byScopeEnabled",
10010
- where: {
10011
- scope_key: scopeKey,
10012
- enabled: true
10013
- },
10014
- limit: PAGE$1,
10015
- ...cursor === void 0 ? {} : { cursor }
10016
- });
10017
- rows.push(...page.rows.map(toReleaseRow));
10018
- cursor = page.next;
10190
+ const found = await page(cursor);
10191
+ rows.push(...found.rows.map((row) => toReleaseRow(row)));
10192
+ cursor = found.next;
10019
10193
  } while (cursor !== void 0);
10020
10194
  return rows;
10021
10195
  };
10196
+ const enabledIn = (scopeKey, cursor) => ({
10197
+ index: "byScopeEnabled",
10198
+ where: {
10199
+ scope_key: scopeKey,
10200
+ enabled: true
10201
+ },
10202
+ limit: PAGE$1,
10203
+ ...cursor === void 0 ? {} : { cursor }
10204
+ });
10205
+ const enabledReleases = (tx, scopeKey) => drainReleases((cursor) => tx.findMany("releases", enabledIn(scopeKey, cursor)));
10022
10206
  const latestReleaseId = async (tx, scopeKey) => {
10023
10207
  const { rows } = await tx.findMany("releases", {
10024
10208
  index: "byScope",
@@ -10028,14 +10212,10 @@ const latestReleaseId = async (tx, scopeKey) => {
10028
10212
  });
10029
10213
  return rows[0]?.id ?? null;
10030
10214
  };
10031
- const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
10032
- const compilation = await compileReleaseCatalog({
10033
- strategy: scope.strategy,
10034
- releases: enabled.map(releaseRowToRelease)
10035
- });
10036
- const generation = (stored.generation ?? 0) + 1;
10215
+ const nextCatalog = (scope, stored, compilation, updatedAtMs) => {
10216
+ const generation = (stored.catalog?.generation ?? 0) + 1;
10037
10217
  if (!Number.isSafeInteger(generation)) fail$1("CATALOG_GENERATION_EXHAUSTED", `Catalog "${scope.scopeKey}" exhausted its generation counter`);
10038
- const catalog = {
10218
+ return {
10039
10219
  scope_key: scope.scopeKey,
10040
10220
  catalog_id: stored.catalog?.catalog_id ?? createUUIDv7(),
10041
10221
  strategy: scope.strategy,
@@ -10050,6 +10230,21 @@ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
10050
10230
  is_tombstone: compilation.payload.releaseDescriptors.length === 0,
10051
10231
  updated_at_ms: updatedAtMs
10052
10232
  };
10233
+ };
10234
+ const compileScope = async (scope, enabled) => {
10235
+ try {
10236
+ return await compileReleaseCatalog({
10237
+ strategy: scope.strategy,
10238
+ releases: enabled.map(releaseRowToRelease)
10239
+ });
10240
+ } catch (error) {
10241
+ if (!(error instanceof ReleaseCatalogCompilationError) || error.code !== "CATALOG_OVERSIZE") throw error;
10242
+ throw new ReleaseCatalogCompilationError("CATALOG_OVERSIZE", `The ${scope.platform} release catalog of channel "${scope.channelName}" would be over its ${MAX_COMPILED_CATALOG_BYTES / 1024} KiB limit.\nDisable or delete old bundles on that channel, then try again.`);
10243
+ }
10244
+ };
10245
+ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
10246
+ const compilation = await compileScope(scope, enabled);
10247
+ const catalog = nextCatalog(scope, stored, compilation, updatedAtMs);
10053
10248
  const { scope_key: _scopeKey, ...set } = catalog;
10054
10249
  if (stored.row === null) tx.create("release_catalogs", catalog);
10055
10250
  else tx.update("release_catalogs", stored.row, set);
@@ -10128,17 +10323,39 @@ const changeReleases = (db, inputs) => {
10128
10323
  return results;
10129
10324
  });
10130
10325
  };
10326
+ const isCurrent = (scope, current, compilation) => current.strategy === scope.strategy && current.channel_id === scope.channelId && current.channel_key === encodeChannelKey(scope.channelName) && current.platform === scope.platform && current.fingerprint_hash === scope.fingerprintHash && current.catalog_hash === compilation.catalogHash;
10327
+ const catalogRowScope = (row) => ({
10328
+ channelId: row.channel_id,
10329
+ channelName: decodeChannelKey(row.channel_key),
10330
+ fingerprintHash: row.fingerprint_hash,
10331
+ platform: row.platform,
10332
+ scopeKey: row.scope_key,
10333
+ strategy: row.strategy
10334
+ });
10335
+ const preflightRebuild = async (db, scopeKey, updatedAtMs) => {
10336
+ const row = await db.findOne("release_catalogs", { scope_key: scopeKey });
10337
+ if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
10338
+ const current = toCatalogRow(row);
10339
+ const scope = catalogRowScope(current);
10340
+ checkScope(scope);
10341
+ const enabled = await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor)));
10342
+ const compilation = await compileScope(scope, enabled);
10343
+ const changed = !isCurrent(scope, current, compilation);
10344
+ return {
10345
+ changed,
10346
+ currentCatalog: current,
10347
+ diagnostics: compilation.diagnostics,
10348
+ projectedCatalog: changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current
10349
+ };
10350
+ };
10131
10351
  const rebuildScope = async (tx, scope, updatedAtMs) => {
10132
10352
  checkScope(scope);
10133
10353
  const stored = await readCatalog(tx, scope.scopeKey);
10134
10354
  assertHistory(stored, await latestReleaseId(tx, scope.scopeKey) !== null);
10135
10355
  const enabled = await enabledReleases(tx, scope.scopeKey);
10136
- const compilation = await compileReleaseCatalog({
10137
- strategy: scope.strategy,
10138
- releases: enabled.map(releaseRowToRelease)
10139
- });
10356
+ const compilation = await compileScope(scope, enabled);
10140
10357
  const current = stored.catalog;
10141
- if (current !== null && current.strategy === scope.strategy && current.channel_id === scope.channelId && current.channel_key === encodeChannelKey(scope.channelName) && current.platform === scope.platform && current.fingerprint_hash === scope.fingerprintHash && current.catalog_hash === compilation.catalogHash) return {
10358
+ if (current !== null && isCurrent(scope, current, compilation)) return {
10142
10359
  catalog: current,
10143
10360
  current,
10144
10361
  changed: false,
@@ -10238,14 +10455,7 @@ const mutationResult = ({ catalog, release }) => ({
10238
10455
  const catalogScope = async (tx, scopeKey) => {
10239
10456
  const row = await tx.findOne("release_catalogs", { scope_key: scopeKey });
10240
10457
  if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
10241
- return {
10242
- channelId: row.channel_id,
10243
- channelName: decodeChannelKey(row.channel_key),
10244
- fingerprintHash: row.fingerprint_hash,
10245
- platform: row.platform,
10246
- scopeKey: row.scope_key,
10247
- strategy: row.strategy
10248
- };
10458
+ return catalogRowScope(toCatalogRow(row));
10249
10459
  };
10250
10460
  const createCoreOperations = (db, { now = Date.now } = {}) => {
10251
10461
  const ensureChannel = async (name) => (await insertChannel(db, {
@@ -10444,18 +10654,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
10444
10654
  };
10445
10655
  });
10446
10656
  },
10447
- preflightReleaseCatalogRebuild: (scopeKey) => {
10448
- const updatedAtMs = now();
10449
- return dryRun(db, async (tx) => {
10450
- const rebuilt = await rebuildScope(tx, await catalogScope(tx, scopeKey), updatedAtMs);
10451
- return {
10452
- changed: rebuilt.changed,
10453
- currentCatalog: rebuilt.current,
10454
- diagnostics: rebuilt.diagnostics,
10455
- projectedCatalog: rebuilt.catalog
10456
- };
10457
- });
10458
- },
10657
+ preflightReleaseCatalogRebuild: (scopeKey) => preflightRebuild(db, scopeKey, now()),
10459
10658
  ensureChannel,
10460
10659
  deleteChannel: (id) => deleteChannel(db, id),
10461
10660
  updateBundle: (id, update) => db.transaction(async (tx) => {
@@ -10713,6 +10912,10 @@ const answer = async (operation) => {
10713
10912
  error: error.message
10714
10913
  }, status);
10715
10914
  }
10915
+ if (error instanceof ReleaseCatalogCompilationError && error.code === "CATALOG_OVERSIZE") return json$2({
10916
+ code: error.code,
10917
+ error: error.message
10918
+ }, 400);
10716
10919
  if (error instanceof DatabaseBundleNotFoundError) return json$2({
10717
10920
  code: "BUNDLE_NOT_FOUND",
10718
10921
  error: error.message
@@ -10732,8 +10935,9 @@ const LIMITS = {
10732
10935
  defaultValue: 50,
10733
10936
  maxValue: 500
10734
10937
  };
10735
- const keyset = (url, maxValue = LIMITS.maxValue) => {
10736
- const order = url.searchParams.get("order") ?? "desc";
10938
+ const MAX_IDS = 100;
10939
+ const keyset = (url, maxValue = LIMITS.maxValue, defaultOrder = "desc") => {
10940
+ const order = url.searchParams.get("order") ?? defaultOrder;
10737
10941
  if (order !== "asc" && order !== "desc") throw new HandlerBadRequestError("order must be 'asc' or 'desc'.");
10738
10942
  const limitParam = url.searchParams.get("limit");
10739
10943
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
@@ -10915,11 +11119,34 @@ const createAdminRouteHandlers = () => ({
10915
11119
  const rows = await core.listReleaseCatalogs(input);
10916
11120
  return page(rows, input, (row) => row.scope_key);
10917
11121
  }),
11122
+ listReleaseScopeKeys: onCore(async (core, request) => {
11123
+ const input = keyset(new URL(request.url), 100, "asc");
11124
+ if (input.order !== "asc" || input.through !== void 0) throw new HandlerBadRequestError("Release scopes are listed ascending, by limit and cursor only.");
11125
+ const rows = await core.listReleaseScopeKeys({
11126
+ limit: input.limit,
11127
+ ...input.after === void 0 ? {} : { after: input.after }
11128
+ });
11129
+ return page(rows, input, (scopeKey) => scopeKey);
11130
+ }),
10918
11131
  getChannels: onCore(async (core, request) => {
10919
- const name = new URL(request.url).searchParams.get("name");
10920
- if (name === null) return json$2({ data: await core.listChannels() });
10921
- const channel = await core.findChannelByName(name);
10922
- return channel === null ? notFound() : json$2({ data: channel });
11132
+ const url = new URL(request.url);
11133
+ const name = url.searchParams.get("name");
11134
+ if (name !== null) {
11135
+ const channel = await core.findChannelByName(name);
11136
+ return channel === null ? notFound() : json$2({ data: channel });
11137
+ }
11138
+ const ids = url.searchParams.get("ids");
11139
+ if (ids !== null) {
11140
+ const list = ids.split(",").filter((id) => id.length > 0);
11141
+ if (list.length === 0 || list.length > MAX_IDS) throw new HandlerBadRequestError(`Channels by ID take ids=<channel id>,... with 1 to ${MAX_IDS} ids.`);
11142
+ return json$2({ data: await core.getChannels(list) });
11143
+ }
11144
+ if (url.searchParams.has("limit") || url.searchParams.has("cursor")) {
11145
+ const input = keyset(url, LIMITS.maxValue, "asc");
11146
+ const rows = await core.listChannels(input);
11147
+ return page(rows, input, (row) => row.name);
11148
+ }
11149
+ return json$2({ data: await core.listChannels() });
10923
11150
  }),
10924
11151
  createChannel: onCore(async (core, request) => {
10925
11152
  const { name } = await body$1(request);
@@ -10967,7 +11194,7 @@ const createAdminRouteHandlers = () => ({
10967
11194
  countBundles: onCore(async (core, request) => json$2({ data: await core.countBundles(platformOf(new URL(request.url))) })),
10968
11195
  countBundleChildren: onCore(async (core, request) => {
10969
11196
  const ids = (new URL(request.url).searchParams.get("ids") ?? "").split(",").filter((id) => id.length > 0);
10970
- if (ids.length === 0 || ids.length > 100) throw new HandlerBadRequestError("Bundle child counts take ids=<bundle id>,... with 1 to 100 ids.");
11197
+ if (ids.length === 0 || ids.length > MAX_IDS) throw new HandlerBadRequestError(`Bundle child counts take ids=<bundle id>,... with 1 to ${MAX_IDS} ids.`);
10971
11198
  return json$2({ data: await core.countBundleChildren(ids) });
10972
11199
  }),
10973
11200
  listBundleChildren: onCore(async (core, request, params) => {
@@ -11109,6 +11336,7 @@ const createAdminRouteHandlers = () => ({
11109
11336
  markIosDevicesInBuild: onCore(async (core, request) => {
11110
11337
  const { buildId, ids } = await body$1(request);
11111
11338
  if (!isText$2(buildId) || !Array.isArray(ids) || !ids.every((id) => isText$2(id))) throw new HandlerBadRequestError("Marking iOS devices in a build needs buildId and ids.");
11339
+ if (ids.length > MAX_IDS) throw new HandlerBadRequestError(`Marking iOS devices in a build takes at most ${MAX_IDS} ids a request.`);
11112
11340
  await core.markIosDevicesInBuild({
11113
11341
  buildId,
11114
11342
  ids
@@ -11178,6 +11406,11 @@ const ADMIN_ROUTES = [
11178
11406
  path: "/release-catalogs",
11179
11407
  handler: "listReleaseCatalogs"
11180
11408
  },
11409
+ {
11410
+ method: "GET",
11411
+ path: "/release-scopes",
11412
+ handler: "listReleaseScopeKeys"
11413
+ },
11181
11414
  {
11182
11415
  method: "POST",
11183
11416
  path: "/release-catalogs/:scopeKey/rebuild",
@@ -11411,38 +11644,53 @@ const catalogResponse = async (catalog, request) => {
11411
11644
  };
11412
11645
  const createReleaseCatalogRouteHandlers = () => {
11413
11646
  const cache = /* @__PURE__ */ new Map();
11647
+ const evict = (insertedHit) => {
11648
+ const now = Date.now();
11649
+ let oldestMiss;
11650
+ let oldest;
11651
+ for (const [key, entry] of cache) if (entry.expiresAt <= now) cache.delete(key);
11652
+ else {
11653
+ if (entry.row === null) oldestMiss ??= key;
11654
+ oldest ??= key;
11655
+ }
11656
+ if (cache.size <= ORIGIN_CACHE_MAX_ENTRIES) return;
11657
+ const victim = oldestMiss ?? (insertedHit ? oldest : void 0);
11658
+ if (victim !== void 0) cache.delete(victim);
11659
+ };
11414
11660
  const inFlight = /* @__PURE__ */ new Map();
11415
- const loadCatalog = async (key, load) => {
11416
- const cached = cache.get(key);
11661
+ const loadRow = async (scopeKey, load) => {
11662
+ const cached = cache.get(scopeKey);
11417
11663
  if (cached !== void 0 && cached.expiresAt > Date.now()) {
11418
- cache.delete(key);
11419
- cache.set(key, cached);
11420
- return cached.catalog;
11664
+ cache.delete(scopeKey);
11665
+ cache.set(scopeKey, cached);
11666
+ return cached.row;
11421
11667
  }
11422
- if (cached !== void 0) cache.delete(key);
11423
- const pending = inFlight.get(key);
11668
+ if (cached !== void 0) cache.delete(scopeKey);
11669
+ const pending = inFlight.get(scopeKey);
11424
11670
  if (pending !== void 0) return pending;
11425
- const next = load().then((catalog) => {
11426
- if (catalog !== null) {
11427
- cache.set(key, {
11428
- catalog,
11429
- expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
11430
- });
11431
- while (cache.size > ORIGIN_CACHE_MAX_ENTRIES) {
11432
- const oldestKey = cache.keys().next().value;
11433
- if (oldestKey === void 0) break;
11434
- cache.delete(oldestKey);
11435
- }
11436
- }
11437
- return catalog;
11671
+ const next = load().then((row) => {
11672
+ cache.set(scopeKey, {
11673
+ row,
11674
+ expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
11675
+ });
11676
+ if (cache.size > ORIGIN_CACHE_MAX_ENTRIES) evict(row !== null);
11677
+ return row;
11438
11678
  });
11439
- inFlight.set(key, next);
11679
+ inFlight.set(scopeKey, next);
11440
11680
  try {
11441
11681
  return await next;
11442
11682
  } finally {
11443
- inFlight.delete(key);
11683
+ inFlight.delete(scopeKey);
11444
11684
  }
11445
11685
  };
11686
+ const loadCatalog = async (core, input) => {
11687
+ const scopeKey = releaseCatalogScopeKeyOf(input);
11688
+ const parsed = await loadRow(scopeKey, async () => {
11689
+ const row = await core.getReleaseCatalogRow(scopeKey);
11690
+ return row === null ? null : parseReleaseCatalogRow(row);
11691
+ });
11692
+ return projectParsedReleaseCatalogRow(parsed, input, scopeKey);
11693
+ };
11446
11694
  return {
11447
11695
  appVersionReleaseCatalog: async (params, request, { core }) => {
11448
11696
  const rawAppVersion = requireRouteParam(params, "appVersion");
@@ -11456,7 +11704,7 @@ const createReleaseCatalogRouteHandlers = () => {
11456
11704
  };
11457
11705
  const invalid = invalidScope(input);
11458
11706
  if (invalid) return invalid;
11459
- return catalogResponse(await loadCatalog(`app-version:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
11707
+ return catalogResponse(await loadCatalog(core, input), request);
11460
11708
  },
11461
11709
  fingerprintReleaseCatalog: async (params, request, { core }) => {
11462
11710
  const input = {
@@ -11467,7 +11715,7 @@ const createReleaseCatalogRouteHandlers = () => {
11467
11715
  };
11468
11716
  const invalid = invalidScope(input);
11469
11717
  if (invalid) return invalid;
11470
- return catalogResponse(await loadCatalog(`fingerprint:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
11718
+ return catalogResponse(await loadCatalog(core, input), request);
11471
11719
  },
11472
11720
  artifactV2: async (params, _request, { core }) => {
11473
11721
  const info = await core.getArtifactInfo(requireRouteParam(params, "targetBundleId"), requireRouteParam(params, "currentBundleId"), 2);
@@ -14381,6 +14629,53 @@ const breakdownOf = (rows) => {
14381
14629
  };
14382
14630
  });
14383
14631
  };
14632
+ const FAILURE_ROWS_PER_HOUR = 20;
14633
+ const FAILURE_QUERY_LIMIT = Math.min(PAGE, 168);
14634
+ const failureRowsByHour = async (db, platform, channel, timeRange) => {
14635
+ const read = (end, cursor) => db.findAggregates("insights_failures", {
14636
+ index: "byScope",
14637
+ where: {
14638
+ platform,
14639
+ channel
14640
+ },
14641
+ range: {
14642
+ gte: timeRange.start,
14643
+ lt: end
14644
+ },
14645
+ order: "desc",
14646
+ limit: FAILURE_QUERY_LIMIT,
14647
+ ...cursor === void 0 ? {} : { cursor }
14648
+ });
14649
+ const rows = [];
14650
+ const cappedHours = [];
14651
+ const perHour = /* @__PURE__ */ new Map();
14652
+ let end = timeRange.end;
14653
+ let cursor;
14654
+ while (end > timeRange.start) {
14655
+ const page = await read(end, cursor);
14656
+ let capped;
14657
+ for (const row of page.rows) {
14658
+ const hour = row.bucket_start_ms;
14659
+ const count = (perHour.get(hour) ?? 0) + 1;
14660
+ if (count > FAILURE_ROWS_PER_HOUR) {
14661
+ capped = hour;
14662
+ break;
14663
+ }
14664
+ perHour.set(hour, count);
14665
+ rows.push(row);
14666
+ }
14667
+ if (capped !== void 0) {
14668
+ cappedHours.unshift(capped);
14669
+ end = capped;
14670
+ cursor = void 0;
14671
+ } else if (page.next === void 0) break;
14672
+ else cursor = page.next;
14673
+ }
14674
+ return {
14675
+ rows,
14676
+ cappedHours
14677
+ };
14678
+ };
14384
14679
  const getUpdateFailures = async (db, input, now, retention) => {
14385
14680
  const { platform, channel, releaseId, timeRange } = input;
14386
14681
  if (platform !== "ios" && platform !== "android" || !isText(channel, 1024) || releaseId !== void 0 && !isText(releaseId, 36) || !isRange(timeRange) || releaseId === void 0 && timeRange === void 0) throw new DatabaseAdapterInputError("invalid-query");
@@ -14441,7 +14736,7 @@ const getUpdateFailures = async (db, input, now, retention) => {
14441
14736
  days,
14442
14737
  kept.hour
14443
14738
  ];
14444
- const [counters, failures, checks, active, rows] = await Promise.all([
14739
+ const [counters, failures, checks, active, { rows, cappedHours }] = await Promise.all([
14445
14740
  counterRows(db, parts, ...window),
14446
14741
  sketchRows(db, failure, ...window),
14447
14742
  days ? sketchRows(db, {
@@ -14449,25 +14744,17 @@ const getUpdateFailures = async (db, input, now, retention) => {
14449
14744
  scopeKind: "check"
14450
14745
  }, ...window) : [],
14451
14746
  days ? sketchRows(db, usageParts(channel, platform), ...window) : [],
14452
- drain((page) => db.findAggregates("insights_failures", {
14453
- index: "byScope",
14454
- where: {
14455
- platform,
14456
- channel
14457
- },
14458
- range: {
14459
- gte: timeRange.start,
14460
- lt: timeRange.end
14461
- },
14462
- limit: PAGE,
14463
- ...page
14464
- }))
14747
+ failureRowsByHour(db, platform, channel, timeRange)
14465
14748
  ]);
14466
14749
  const total = (field) => counters.reduce((sum, row) => sum + row[field], 0);
14467
14750
  const scoped = rows.filter((row) => FAILURE_STAGES.has(row.stage) && (releaseId === void 0 || row.release_id === releaseId));
14468
14751
  const failuresAt = (counted) => scoped.reduce((sum, row) => sum + (counted(row.stage) ? Math.max(0, row.events) : 0), 0);
14752
+ const coverage = coverageOf(timeRange.start, kept.hour);
14469
14753
  return {
14470
- coverage: coverageOf(timeRange.start, kept.hour),
14754
+ coverage: cappedHours.length === 0 ? coverage : {
14755
+ kind: "partial",
14756
+ sinceMs: coverage.sinceMs
14757
+ },
14471
14758
  measuredAtMs: at,
14472
14759
  failedUpdates: failuresAt((stage) => stage !== "check"),
14473
14760
  failedInstallations: failed(failures),
@@ -14479,7 +14766,8 @@ const getUpdateFailures = async (db, input, now, retention) => {
14479
14766
  failedInstallations: failed(checks),
14480
14767
  activeInstallations: countDistinct(mergeDistinct(active.map((row) => row.activity_users)))
14481
14768
  } } : {},
14482
- breakdown: breakdownOf(scoped)
14769
+ breakdown: breakdownOf(scoped),
14770
+ ...cappedHours.length === 0 ? {} : { cappedHours }
14483
14771
  };
14484
14772
  };
14485
14773
  //#endregion
@@ -7687,7 +7687,7 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
7687
7687
  const nonInteractive = envFile !== void 0;
7688
7688
  const initEnvSources = await (0, _hot_updater_cli_tools.readHotUpdaterInitEnv)(cwd, envFile, secretsEnv);
7689
7689
  const initInputEnv = (0, _hot_updater_cli_tools.getHotUpdaterInitInputEnv)(initEnvSources, nonInteractive);
7690
- const saved = Object.fromEntries(Object.entries(inputs).map(([name, input]) => [name, initInputEnv[input.envKey]?.trim() || void 0]));
7690
+ const saved = (0, _hot_updater_cli_tools.resolveInitProviderInputs)(initInputEnv, initProvider);
7691
7691
  const cliVersion = await azureCliVersion();
7692
7692
  if (cliVersion === null) {
7693
7693
  _hot_updater_cli_tools.p.log.error("The Azure CLI (az) is not installed.");
@@ -1,7 +1,7 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { createHash } from "crypto";
3
3
  import path from "path";
4
- import { ConfigBuilder, InitError, assembleServer, createHotUpdaterConfigScaffoldFromBuilder, createZip, getCwd, getHotUpdaterInitInputEnv, getInitProviderEnvVars, getInitProviderTextPromptValues, link, makeEnv, p, printAppSetup, provisionClientCredential, readHotUpdaterInitEnv, shouldAutoSelectOnlyInitResource, writeHotUpdaterFiles } from "@hot-updater/cli-tools";
4
+ import { ConfigBuilder, InitError, assembleServer, createHotUpdaterConfigScaffoldFromBuilder, createZip, getCwd, getHotUpdaterInitInputEnv, getInitProviderEnvVars, getInitProviderTextPromptValues, link, makeEnv, p, printAppSetup, provisionClientCredential, readHotUpdaterInitEnv, resolveInitProviderInputs, shouldAutoSelectOnlyInitResource, writeHotUpdaterFiles } from "@hot-updater/cli-tools";
5
5
  import { apiKeys, insights, remoteConfig } from "@hot-updater/server/plugins";
6
6
  import { CosmosClient } from "@azure/cosmos";
7
7
  import { SETTINGS_TABLE, createEngineDatabase, createKvAdapter, encodeKvKey, migrateCoreSchema, toolingTargetOf } from "@hot-updater/plugin-core";
@@ -7682,7 +7682,7 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
7682
7682
  const nonInteractive = envFile !== void 0;
7683
7683
  const initEnvSources = await readHotUpdaterInitEnv(cwd, envFile, secretsEnv);
7684
7684
  const initInputEnv = getHotUpdaterInitInputEnv(initEnvSources, nonInteractive);
7685
- const saved = Object.fromEntries(Object.entries(inputs).map(([name, input]) => [name, initInputEnv[input.envKey]?.trim() || void 0]));
7685
+ const saved = resolveInitProviderInputs(initInputEnv, initProvider);
7686
7686
  const cliVersion = await azureCliVersion();
7687
7687
  if (cliVersion === null) {
7688
7688
  p.log.error("The Azure CLI (az) is not installed.");
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hot-updater/azure",
3
3
  "type": "module",
4
- "version": "1.2.0-rc.49",
4
+ "version": "1.2.0-rc.50",
5
5
  "description": "React Native OTA solution for self-hosted",
6
6
  "engines": {
7
7
  "node": "^22.23.4 || ^24.22.1 || >=26.12.1"
@@ -44,10 +44,10 @@
44
44
  "@azure/identity": "4.14.0",
45
45
  "@azure/keyvault-secrets": "4.11.2",
46
46
  "@azure/storage-blob": "12.34.0",
47
- "@hot-updater/cli-tools": "1.2.0-rc.49",
48
- "@hot-updater/plugin-core": "1.2.0-rc.49",
49
- "@hot-updater/protocol": "1.2.0-rc.49",
50
- "@hot-updater/server": "1.2.0-rc.49"
47
+ "@hot-updater/cli-tools": "1.2.0-rc.50",
48
+ "@hot-updater/plugin-core": "1.2.0-rc.50",
49
+ "@hot-updater/protocol": "1.2.0-rc.50",
50
+ "@hot-updater/server": "1.2.0-rc.50"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@azure/functions": "4.16.5",
@@ -55,7 +55,7 @@
55
55
  "execa": "9.5.2",
56
56
  "jszip": "^3.10.1",
57
57
  "vitest": "4.1.4",
58
- "@hot-updater/test-utils": "1.2.0-rc.49"
58
+ "@hot-updater/test-utils": "1.2.0-rc.50"
59
59
  },
60
60
  "scripts": {
61
61
  "build": "tsdown",