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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,9 +2061,13 @@ 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
2105
- * a database whose row differs, until it runs.
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
2067
+ * a database whose row differs, until it runs. Before a version is released,
2068
+ * its tables change in place in its own migration, and a database one of its
2069
+ * prereleases migrated takes the same change by hand: the fence compares this
2070
+ * row, not columns, so nothing reports it.
2106
2071
  */
2107
2072
  const HOT_UPDATER_SCHEMA_VERSION = "1.2.0";
2108
2073
  const bundles = defineTable({
@@ -2284,9 +2249,26 @@ const releases = defineTable({
2284
2249
  all: {
2285
2250
  eq: [],
2286
2251
  sort: ["id"]
2252
+ },
2253
+ scopes: {
2254
+ eq: [],
2255
+ sort: ["scope_key"]
2287
2256
  }
2288
2257
  }
2289
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
+ }];
2290
2272
  /** One compiled catalog per scope; the update check reads exactly this row. */
2291
2273
  const releaseCatalogs = defineTable({
2292
2274
  scope_key: {
@@ -2356,7 +2338,10 @@ const channels = defineTable({
2356
2338
  /**
2357
2339
  * The native builds `native-build android` and `native-build ios` track, newest first
2358
2340
  * in each scope: a platform, a channel, and the fingerprint or app version
2359
- * the build compiled in. `min_bundle_id` names the build's built-in bundle,
2341
+ * the build compiled in. A sandbox build's scope has no channel: its app ID,
2342
+ * URL scheme, artifact kind and distribution in its place, so pull requests
2343
+ * reuse it across channels, while `channel_id` still names the channel it
2344
+ * embeds. `min_bundle_id` names the build's built-in bundle,
2360
2345
  * a `bundles` row no release publishes. Its references keep no counters, so
2361
2346
  * adding this table changes no existing one; a channel with builds is
2362
2347
  * refused deletion through `byChannel`. `build_key` is the native build key
@@ -2366,6 +2351,27 @@ const channels = defineTable({
2366
2351
  * or `versionCode`. `submitted_to`, `submitted_at_ms` and
2367
2352
  * `submitted_version` record the store track a build went to, when, and
2368
2353
  * the store's label of the build; they stay null for a build no store took.
2354
+ * `is_store_build` is true on the build a person or a job says the store
2355
+ * sells, and false on every other: deploys patch from it over the scope's
2356
+ * newest build. The engine copies the scope key into `store_build_scope_key`
2357
+ * for that build alone, so `byStoreBuild` holds one entry per scope at most,
2358
+ * on every store, while any number of a scope's builds hold none.
2359
+ * `is_sandbox` is true on a sandbox build, set from its artifact when it
2360
+ * registers and never changed, and `sandbox_url_scheme` is the URL scheme its artifact registers,
2361
+ * which its preview links open; null on any other build, and on a sandbox
2362
+ * build registered before the column, which registered the derived one.
2363
+ * `export_method` is how an `.ipa` was exported, read from its profile when
2364
+ * it registers and never changed; null on any other artifact, on an `.ipa`
2365
+ * whose profile couldn't be read, and on one registered before the column.
2366
+ * `native_app_version` is the app version the artifact itself reports, its
2367
+ * `CFBundleShortVersionString` or `versionName`, read from the artifact when
2368
+ * it registers and never changed, whatever the update strategy; `app_version`
2369
+ * stays the version OTAs target, null on a fingerprint build. It is null
2370
+ * when the artifact's can't be read, and on a build registered before the
2371
+ * column.
2372
+ * Boolean columns follow one rule: `is_*` for a fact about the row or
2373
+ * `should_*` for an instruction to the client, never null; a unique index over
2374
+ * the rows where one is true keys a derived slot, not the boolean.
2369
2375
  */
2370
2376
  const nativeBuilds = defineTable({
2371
2377
  id: {
@@ -2442,9 +2448,34 @@ const nativeBuilds = defineTable({
2442
2448
  type: "string",
2443
2449
  maxLength: 255,
2444
2450
  required: false
2451
+ },
2452
+ is_store_build: { type: "boolean" },
2453
+ is_sandbox: { type: "boolean" },
2454
+ sandbox_url_scheme: {
2455
+ type: "string",
2456
+ maxLength: 255,
2457
+ ascii: true,
2458
+ required: false
2459
+ },
2460
+ export_method: {
2461
+ type: "string",
2462
+ maxLength: 16,
2463
+ required: false
2464
+ },
2465
+ native_app_version: {
2466
+ type: "string",
2467
+ required: false
2445
2468
  }
2446
2469
  }, {
2447
2470
  key: ["id"],
2471
+ derived: {
2472
+ /** The scope this build is the store build of; null on every other. */
2473
+ store_build_scope_key: {
2474
+ type: "string",
2475
+ maxLength: 2048,
2476
+ ascii: true,
2477
+ compute: (row) => row.is_store_build ? row.scope_key : null
2478
+ } },
2448
2479
  indexes: {
2449
2480
  byScope: {
2450
2481
  eq: ["scope_key"],
@@ -2454,6 +2485,15 @@ const nativeBuilds = defineTable({
2454
2485
  eq: ["scope_key", "build_key"],
2455
2486
  sort: ["id"]
2456
2487
  },
2488
+ byScopeKind: {
2489
+ eq: ["scope_key", "artifact_kind"],
2490
+ sort: ["id"]
2491
+ },
2492
+ byStoreBuild: {
2493
+ eq: ["store_build_scope_key"],
2494
+ sort: [],
2495
+ unique: true
2496
+ },
2457
2497
  byChannel: {
2458
2498
  eq: ["channel_id"],
2459
2499
  sort: ["id"],
@@ -2465,6 +2505,119 @@ const nativeBuilds = defineTable({
2465
2505
  }
2466
2506
  }
2467
2507
  });
2508
+ /**
2509
+ * The iPhones a team asks to install ad hoc builds on. A row decides what the
2510
+ * CLI registers with Apple, not what an export includes: Xcode's automatic ad
2511
+ * hoc profile lists every device the Apple account has enabled. `status` is
2512
+ * `pending` until someone approves it, `approved` until a build or
2513
+ * `native-build devices add` registers it with Apple, then `registered`;
2514
+ * declining or removing one deletes its row. `udid` is the UDID in lower case.
2515
+ * `apple_issuer_id` is the App Store Connect issuer whose key registered it,
2516
+ * set once: a build signed by another account never registers these rows.
2517
+ * `apple_error` is Apple's refusal of the device, or why it stopped counting
2518
+ * it, cleared by the next success. `build_id` is the newest native build whose
2519
+ * .ipa the CLI checked lists it; deleting that build never touches the row.
2520
+ * It holds personal data: a UDID, a name, and the emails of who asked and who
2521
+ * approved, null for the CLI.
2522
+ */
2523
+ const iosDevices = defineTable({
2524
+ id: {
2525
+ type: "string",
2526
+ maxLength: 36
2527
+ },
2528
+ udid: {
2529
+ type: "string",
2530
+ maxLength: 40,
2531
+ ascii: true,
2532
+ unique: true
2533
+ },
2534
+ name: {
2535
+ type: "string",
2536
+ maxLength: 100
2537
+ },
2538
+ status: {
2539
+ type: "string",
2540
+ maxLength: 16
2541
+ },
2542
+ requested_by: {
2543
+ type: "string",
2544
+ maxLength: 320,
2545
+ required: false
2546
+ },
2547
+ created_at_ms: { type: "integer" },
2548
+ approved_by: {
2549
+ type: "string",
2550
+ maxLength: 320,
2551
+ required: false
2552
+ },
2553
+ approved_at_ms: {
2554
+ type: "integer",
2555
+ required: false
2556
+ },
2557
+ registered_at_ms: {
2558
+ type: "integer",
2559
+ required: false
2560
+ },
2561
+ apple_issuer_id: {
2562
+ type: "string",
2563
+ maxLength: 64,
2564
+ ascii: true,
2565
+ required: false
2566
+ },
2567
+ apple_error: {
2568
+ type: "string",
2569
+ maxLength: 512,
2570
+ required: false
2571
+ },
2572
+ build_id: {
2573
+ type: "string",
2574
+ maxLength: 36,
2575
+ required: false
2576
+ }
2577
+ }, {
2578
+ key: ["id"],
2579
+ indexes: {
2580
+ byStatus: {
2581
+ eq: ["status"],
2582
+ sort: ["id"]
2583
+ },
2584
+ byRegistration: {
2585
+ eq: [],
2586
+ sort: ["registered_at_ms"]
2587
+ },
2588
+ all: {
2589
+ eq: [],
2590
+ sort: ["id"]
2591
+ }
2592
+ }
2593
+ });
2594
+ /**
2595
+ * The Apple account the iOS device registry belongs to: one row, keyed
2596
+ * `registry`, holding the App Store Connect issuer that first registered a
2597
+ * device. A build claims it before it sends Apple anything, and its key makes
2598
+ * the claim atomic on every store, so two builds of two accounts can't both
2599
+ * spend a slot; another account's build then registers nothing. Removing
2600
+ * devices never releases it.
2601
+ */
2602
+ const iosDeviceAccount = defineTable({
2603
+ id: {
2604
+ type: "string",
2605
+ maxLength: 16,
2606
+ ascii: true
2607
+ },
2608
+ apple_issuer_id: {
2609
+ type: "string",
2610
+ maxLength: 64,
2611
+ ascii: true
2612
+ },
2613
+ claimed_at_ms: { type: "integer" }
2614
+ }, {
2615
+ key: ["id"],
2616
+ indexes: { all: {
2617
+ eq: [],
2618
+ sort: ["id"]
2619
+ } }
2620
+ });
2468
2621
  /** Core's module: always installed, never a plugin. */
2469
2622
  const coreModule = {
2470
2623
  id: "core",
@@ -2485,7 +2638,9 @@ const coreModule = {
2485
2638
  sort: []
2486
2639
  } }
2487
2640
  }),
2488
- native_builds: nativeBuilds
2641
+ native_builds: nativeBuilds,
2642
+ ios_devices: iosDevices,
2643
+ ios_device_account: iosDeviceAccount
2489
2644
  }
2490
2645
  };
2491
2646
  //#endregion
@@ -2511,6 +2666,121 @@ const refuseV0Database = (adapterName, stored) => {
2511
2666
  if (typeof version !== "string" || stored.has("schema.engine")) return;
2512
2667
  throw new HotUpdaterSchemaMigrationRequiredError(adapterName, version);
2513
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
+ };
2514
2784
  //#endregion
2515
2785
  //#region ../plugin-core/dist/engine/database/cursor.mjs
2516
2786
  const encoder$1 = new TextEncoder();
@@ -2674,18 +2944,17 @@ const LEASE_TABLE = "aggregate_lease";
2674
2944
  const LEASE = { id: "compaction" };
2675
2945
  /** How long a compaction holds the lease before another process may take it. */
2676
2946
  const LEASE_MS = 3e4;
2677
- /**
2678
- * Default windows: log mode compacts every 60 seconds, since reads compact
2679
- * first; memory mode flushes every 15, since its window is what a crash
2680
- * loses.
2681
- */
2682
- const WINDOW_MS$1 = {
2683
- log: 6e4,
2684
- memory: 15e3
2685
- };
2947
+ /** A commit compacts once this has passed since the last compaction. */
2948
+ const WINDOW_MS$1 = 6e4;
2686
2949
  /** Log rows a compaction reads from each log table for one group. */
2687
2950
  const LOG_PAGE = 200;
2688
2951
  /**
2952
+ * How old a log row this process can't apply must be before its reads step
2953
+ * past it: older than any transaction still committing, between servers
2954
+ * whose clocks agree this closely.
2955
+ */
2956
+ const SKIP_AFTER_MS = 3e5;
2957
+ /**
2689
2958
  * Groups one compaction applies: after a commit, so the request that runs
2690
2959
  * it waits for one group; before a read; and on flush.
2691
2960
  */
@@ -2696,8 +2965,6 @@ const GROUPS = {
2696
2965
  };
2697
2966
  /** Tries per write after a conflict or a transient error. */
2698
2967
  const ATTEMPTS = 5;
2699
- /** Aggregate rows a memory buffer holds before a commit waits for a flush. */
2700
- const MAX_BUFFERED = 1e4;
2701
2968
  const log = defineTable({
2702
2969
  id: {
2703
2970
  type: "string",
@@ -2747,7 +3014,7 @@ const valuesOf = ({ deltas, sketches }) => ({
2747
3014
  /**
2748
3015
  * Merges `values` into the change for `key`'s identity as `tx.aggregate`
2749
3016
  * does: deltas add up and sketches merge. One constant `shardBy` keys each
2750
- * identity to one entry; the write picks the shard.
3017
+ * identity to one entry; `compile` writes it to shard 0.
2751
3018
  */
2752
3019
  const merge = (into, model, key, values) => recordAggregate(into, model, Object.fromEntries(shapeOf(model).key.map((field, at) => [field, key[at]])), values, "");
2753
3020
  const mergeAll = (into, changes) => {
@@ -2781,7 +3048,7 @@ const increment = ({ model, deltas }, key) => Object.values(deltas).some((delta)
2781
3048
  /**
2782
3049
  * The guarded write that merges `change` into `current`: insert, patch, or
2783
3050
  * delete at zero. Unlike a transaction's, a gauge may go below zero here: a
2784
- * shard row holds one writer's net changes, and reads sum every shard.
3051
+ * group can hold a loss without the gain before it, and reads sum every shard.
2785
3052
  */
2786
3053
  const rewrite = (change, key, current) => {
2787
3054
  const { model } = change;
@@ -2818,23 +3085,41 @@ const rewrite = (change, key, current) => {
2818
3085
  previous: current
2819
3086
  };
2820
3087
  };
3088
+ /** A shard row's place in what `readCurrent` read. */
3089
+ const rowId = (model, key) => JSON.stringify([model.table.name, key]);
3090
+ /** The shard key each change writes: shard 0, since one compaction runs at a time. */
3091
+ const keysOf = (changes) => changes.map(({ key }) => [...key.slice(0, -1), 0]);
2821
3092
  /**
2822
- * The write for each change on its shard: a blind increment that creates
2823
- * the row for counters, and a guarded rewrite for gauges and sketches, whose
2824
- * rows are read in one batch per table.
3093
+ * The current rows of the changes that rewrite theirs (gauges and sketches),
3094
+ * each once, in one batch per table.
2825
3095
  */
2826
- const compile = async (adapter, changes, shard) => {
2827
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
3096
+ const readCurrent = async (adapter, changes) => {
3097
+ const keys = keysOf(changes);
2828
3098
  const reads = /* @__PURE__ */ new Map();
2829
3099
  changes.forEach((change, at) => {
2830
- if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
3100
+ if (!rewrites(change)) return;
3101
+ const wanted = reads.get(change.model) ?? /* @__PURE__ */ new Map();
3102
+ wanted.set(rowId(change.model, keys[at]), keys[at]);
3103
+ reads.set(change.model, wanted);
2831
3104
  });
2832
3105
  const current = /* @__PURE__ */ new Map();
2833
- await Promise.all([...reads].map(async ([model, positions]) => {
2834
- const rows = await adapter.get(model.table, positions.map((at) => keys[at]));
2835
- positions.forEach((at, index) => current.set(at, rows[index] ?? null));
3106
+ await Promise.all([...reads].map(async ([model, wanted]) => {
3107
+ const keys = [...wanted.values()];
3108
+ const rows = await adapter.get(model.table, keys);
3109
+ keys.forEach((key, at) => {
3110
+ current.set(rowId(model, key), rows[at] ?? null);
3111
+ });
2836
3112
  }));
2837
- return changes.map((change, at) => current.has(at) ? rewrite(change, keys[at], current.get(at)) : increment(change, keys[at]));
3113
+ return current;
3114
+ };
3115
+ /**
3116
+ * The write for each change: a blind increment that creates the row for
3117
+ * counters, and a guarded rewrite for gauges and sketches, over the rows
3118
+ * `current` read.
3119
+ */
3120
+ const build = (changes, current) => {
3121
+ const keys = keysOf(changes);
3122
+ return changes.map((change, at) => rewrites(change) ? rewrite(change, keys[at], current.get(rowId(change.model, keys[at])) ?? null) : increment(change, keys[at]));
2838
3123
  };
2839
3124
  const isOp = (op) => op !== void 0;
2840
3125
  const sleep = (attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random()));
@@ -2878,14 +3163,13 @@ const encode$1 = async (changes) => {
2878
3163
  return zipped !== void 0 && zipped.length < json.length ? `z${zipped}` : json;
2879
3164
  };
2880
3165
  /**
2881
- * Batches changes to aggregates declared `batched`. A transaction records
2882
- * them without writing their rows; once it commits, "memory" mode keeps
2883
- * them in this process until its timer flushes them, and "log" mode has
2884
- * written them as one log row in the same atomic write, which a compaction
2885
- * later merges into the aggregates and deletes, atomically again, so each
2886
- * applies exactly once. One lease row keeps compactions one at a time.
3166
+ * Batches changes to aggregates declared `batched`. A transaction writes
3167
+ * them as one log row in its own atomic write, in place of their rows; a
3168
+ * compaction later merges log rows into the aggregates and deletes them,
3169
+ * atomically again, so each applies exactly once. One lease row keeps
3170
+ * compactions one at a time.
2887
3171
  */
2888
- const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS$1[mode] }, now }) => {
3172
+ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs = WINDOW_MS$1 }, now }) => {
2889
3173
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
2890
3174
  const holder = crypto.randomUUID().replaceAll("-", "");
2891
3175
  const table = (name) => schema.models.get(name).table;
@@ -2913,72 +3197,20 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
2913
3197
  }
2914
3198
  return changes;
2915
3199
  };
2916
- /**
2917
- * Writes changes in atomic chunks within `fits`, and returns the ones it
2918
- * could not apply. A write whose outcome is unknown is dropped, never
2919
- * resent, so no change applies twice.
2920
- */
2921
- const apply = async (changes, shard) => {
2922
- let rest = changes;
2923
- let ops = [];
2924
- let read = true;
2925
- for (let failures = 0; rest.length > 0 && failures < ATTEMPTS;) try {
2926
- if (read) ops = await compile(adapter, rest, shard);
2927
- let size = rest.length;
2928
- const chunk = () => ops.slice(0, size).filter(isOp);
2929
- while (size > 1 && !adapter.fits(chunk())) size = Math.ceil(size / 2);
2930
- let result = { ok: true };
2931
- if (chunk().length > 0) result = await adapter.write(chunk()).catch((error) => {
2932
- warn("flush")(error);
2933
- return { ok: true };
2934
- });
2935
- read = !result.ok && !("retry" in result);
2936
- if (result.ok) {
2937
- rest = rest.slice(size);
2938
- ops = ops.slice(size);
2939
- failures = 0;
2940
- } else {
2941
- failures += 1;
2942
- if (!read) await sleep(failures);
2943
- }
2944
- } catch (error) {
2945
- warn("flush")(error);
2946
- return rest;
2947
- }
2948
- return rest;
2949
- };
2950
- let buffer = /* @__PURE__ */ new Map();
2951
- let timer;
2952
- let flushing;
2953
- const shards = /* @__PURE__ */ new Map();
2954
- /** Each process writes its own shard, so flushes of two processes rarely meet. */
2955
- const processShard = (model) => {
2956
- if (!shards.has(model)) shards.set(model, Math.floor(Math.random() * shapeOf(model).shards));
2957
- return shards.get(model);
2958
- };
2959
- const schedule = () => {
2960
- if (timer !== void 0 || buffer.size === 0) return;
2961
- timer = setTimeout(() => {
2962
- timer = void 0;
2963
- flushBuffer();
2964
- }, windowMs);
2965
- timer.unref?.();
2966
- };
2967
- /** Never rejects: what it cannot apply goes back into the buffer. */
2968
- const flushBuffer = () => flushing ??= (async () => {
2969
- clearTimeout(timer);
2970
- timer = void 0;
2971
- const pending = [...buffer.values()];
2972
- buffer = /* @__PURE__ */ new Map();
2973
- mergeAll(buffer, await apply(pending, processShard));
2974
- })().catch(warn("flush")).finally(() => {
2975
- flushing = void 0;
2976
- schedule();
2977
- });
2978
3200
  let nextDue = 0;
2979
3201
  let compacting;
2980
3202
  /** Log rows this process read, by `[log table's index, id]`, for the deletes after a group. */
2981
3203
  const known = /* @__PURE__ */ new Map();
3204
+ /**
3205
+ * Each log table's last row of a run at its head that this process can't
3206
+ * apply (it names an aggregate or metric this schema lacks), whose reads
3207
+ * start past it. The rows wait for a process that can apply them, and a
3208
+ * restart reads them again.
3209
+ */
3210
+ const skipped = LOG_TABLES.map(() => void 0);
3211
+ const past = (shard) => skipped[shard] === void 0 ? {} : { range: { gt: skipped[shard] } };
3212
+ /** When a log row's transaction stamped its ID. */
3213
+ const stampOf = (id) => Number.parseInt(id.slice(0, 9), 36);
2982
3214
  const idOf = (shard, id) => JSON.stringify([shard, id]);
2983
3215
  /** The lease row as stored once `set` is written over it. */
2984
3216
  const leaseOp = (held, set) => {
@@ -3094,14 +3326,22 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3094
3326
  logs: (await Promise.all(LOG_TABLES.map(async (name, shard) => {
3095
3327
  const page = await engine.reads.findMany(name, {
3096
3328
  index: "oldest",
3097
- limit: LOG_PAGE
3329
+ limit: LOG_PAGE,
3330
+ ...past(shard)
3098
3331
  });
3099
3332
  more ||= page.next !== void 0;
3100
- return (await Promise.all(page.rows.map(async (row) => ({
3333
+ const decoded = await Promise.all(page.rows.map(async (row) => ({
3101
3334
  shard,
3102
3335
  row,
3103
3336
  changes: await decode(String(row.changes))
3104
- })))).flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
3337
+ })));
3338
+ const settled = now() - SKIP_AFTER_MS;
3339
+ for (const { row, changes } of decoded) {
3340
+ const id = String(row.id);
3341
+ if (changes !== void 0 || stampOf(id) >= settled) break;
3342
+ skipped[shard] = id;
3343
+ }
3344
+ return decoded.flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
3105
3345
  ...entry,
3106
3346
  changes
3107
3347
  }]);
@@ -3109,7 +3349,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3109
3349
  more
3110
3350
  };
3111
3351
  };
3112
- const rowsFor = async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp);
3113
3352
  /**
3114
3353
  * Applies the oldest pending log rows whose merged changes fit in one
3115
3354
  * atomic write with the lease, which lists them as applied; the rows are
@@ -3118,12 +3357,14 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3118
3357
  * log rows it applied whole, or undefined when a conflict stopped it.
3119
3358
  */
3120
3359
  const applyGroup = async (held, logs) => {
3360
+ const current = await readCurrent(adapter, logs.flatMap((entry) => [...entry.changes.values()]));
3361
+ const rowsFor = (changes) => build(changes, current).filter(isOp);
3121
3362
  for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
3122
3363
  const batch = logs.slice(0, count);
3123
3364
  const changes = mergeAll(/* @__PURE__ */ new Map(), batch.flatMap((entry) => [...entry.changes.values()]));
3124
3365
  const applied = batch.map(({ shard, row }) => [shard, row.id]);
3125
3366
  const lease = leaseOp(held, { applied: JSON.stringify(applied) });
3126
- const ops = [...await rowsFor([...changes.values()]), lease.op];
3367
+ const ops = [...rowsFor([...changes.values()]), lease.op];
3127
3368
  if (!adapter.fits(ops)) continue;
3128
3369
  for (const { shard, row } of batch) known.set(idOf(shard, row.id), row);
3129
3370
  return await commit(ops) ? {
@@ -3145,7 +3386,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3145
3386
  };
3146
3387
  const lease = leaseOp(held, {});
3147
3388
  const ops = [
3148
- ...await rowsFor(entries.slice(0, take)),
3389
+ ...rowsFor(entries.slice(0, take)),
3149
3390
  kept,
3150
3391
  lease.op
3151
3392
  ];
@@ -3166,11 +3407,12 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3166
3407
  if (held === void 0) return;
3167
3408
  let pending = true;
3168
3409
  let clear = false;
3410
+ let carried;
3169
3411
  try {
3170
3412
  for (let group = 0;; group += 1) {
3171
3413
  clear = await deleteApplied(held);
3172
3414
  if (!clear || !pending || group === groups) break;
3173
- const { logs, more } = await readLogs();
3415
+ const { logs, more } = carried ?? await readLogs();
3174
3416
  if (logs.length === 0) {
3175
3417
  pending = false;
3176
3418
  break;
@@ -3178,6 +3420,11 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3178
3420
  const applied = await applyGroup(held, logs);
3179
3421
  if (applied === void 0) break;
3180
3422
  [held, clear] = [applied.held, false];
3423
+ const rest = applied.count === 0 ? [] : logs.slice(applied.count);
3424
+ carried = rest.length > 0 ? {
3425
+ logs: rest,
3426
+ more
3427
+ } : void 0;
3181
3428
  pending = more || applied.count < logs.length;
3182
3429
  }
3183
3430
  } finally {
@@ -3197,26 +3444,13 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3197
3444
  });
3198
3445
  let checking;
3199
3446
  /** Whether any log row waits; reads at once share one check. */
3200
- const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name) => engine.reads.findMany(name, {
3447
+ const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name, shard) => engine.reads.findMany(name, {
3201
3448
  index: "oldest",
3202
- limit: 1
3449
+ limit: 1,
3450
+ ...past(shard)
3203
3451
  }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
3204
3452
  checking = void 0;
3205
3453
  });
3206
- /** Takes a committed transaction's changes; never rejects, since the transaction already committed. */
3207
- const committed = async (changes) => {
3208
- if (mode === "log") {
3209
- if (now() >= nextDue) await compact(false, GROUPS.commit);
3210
- return;
3211
- }
3212
- mergeAll(buffer, changes.values());
3213
- schedule();
3214
- if (buffer.size >= MAX_BUFFERED) await flushBuffer();
3215
- };
3216
- const flush = async () => {
3217
- await flushBuffer();
3218
- if (mode === "log" && await hasPending()) await compact(true, GROUPS.flush);
3219
- };
3220
3454
  return {
3221
3455
  async transaction(fn) {
3222
3456
  let changes = /* @__PURE__ */ new Map();
@@ -3242,7 +3476,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3242
3476
  aggregate
3243
3477
  });
3244
3478
  if (failure) throw failure.error;
3245
- if (mode === "log" && attempt.size > 0) {
3479
+ if (attempt.size > 0) {
3246
3480
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
3247
3481
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
3248
3482
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -3256,24 +3490,18 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3256
3490
  open = false;
3257
3491
  }
3258
3492
  });
3259
- if (changes.size > 0) await committed(changes);
3493
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
3260
3494
  return result;
3261
3495
  },
3262
3496
  async beforeRead(name) {
3263
3497
  if (!isBatched(schema.models.get(name))) return;
3264
- if (buffer.size > 0 || flushing !== void 0) await flushBuffer();
3265
- if (mode === "log") {
3266
- if (await hasPending().catch((error) => {
3267
- warn("read")(error);
3268
- return false;
3269
- })) await compact(true, GROUPS.read);
3270
- }
3498
+ if (await hasPending().catch((error) => {
3499
+ warn("read")(error);
3500
+ return false;
3501
+ })) await compact(true, GROUPS.read);
3271
3502
  },
3272
- flush,
3273
- async dispose() {
3274
- clearTimeout(timer);
3275
- timer = void 0;
3276
- await flush();
3503
+ async flush() {
3504
+ if (await hasPending()) await compact(true, GROUPS.flush);
3277
3505
  }
3278
3506
  };
3279
3507
  };
@@ -3415,7 +3643,8 @@ const fieldProblems = (definition, add) => {
3415
3643
  else if (field.required === false) add(`key field "${name}" is nullable`);
3416
3644
  else if (field.type === "json") add(`key field "${name}" is json`);
3417
3645
  }
3418
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
3646
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
3647
+ for (const [name, { type, maxLength, ascii }] of bounded) {
3419
3648
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
3420
3649
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
3421
3650
  }
@@ -3532,11 +3761,13 @@ const resolveSchema = (modules) => {
3532
3761
  ...maxLength === void 0 ? {} : { maxLength },
3533
3762
  ...ascii ? { ascii } : {}
3534
3763
  }));
3535
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
3764
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
3536
3765
  name: field,
3537
3766
  type,
3538
3767
  nullable: true,
3539
- ...multi ? { multi } : {}
3768
+ ...multi ? { multi } : {},
3769
+ ...maxLength === void 0 ? {} : { maxLength },
3770
+ ...ascii ? { ascii } : {}
3540
3771
  });
3541
3772
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
3542
3773
  name: metric,
@@ -3572,29 +3803,34 @@ const resolveSchema = (modules) => {
3572
3803
  * `hot-updater db migrate` for a store whose adapter creates its own tables
3573
3804
  * (MongoDB and the key-value stores): the tables and indexes, then the
3574
3805
  * settings rows, applied when a setting is missing or different, and refused
3575
- * on a v0 database.
3806
+ * on a v0 database or one a newer release migrated.
3576
3807
  */
3577
3808
  const createEngineMigrator = (options) => {
3578
3809
  const getVersion = async () => storedSchemaVersion(await options.readSettings());
3579
3810
  const makeResult = async (migrate = {}) => {
3580
3811
  const stored = await options.readSettings();
3581
3812
  refuseV0Database(options.adapterName, stored);
3582
- if (Object.entries(options.settings).every(([key, value]) => stored.get(key) === value)) return getEmptyMigrationResult();
3583
- return {
3584
- operations: [...options.schema.tables.map((table) => ({
3585
- type: "create-table",
3586
- value: {
3587
- ormName: table.name,
3588
- columns: Object.fromEntries(table.columns.map((column) => [column.name, {
3589
- ormName: column.name,
3590
- type: column.type
3591
- }]))
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);
3592
3825
  }
3593
- })), ...migrate.updateSettings === false ? [] : [{
3826
+ };
3827
+ }
3828
+ return {
3829
+ operations: [{
3594
3830
  type: "custom",
3595
- description: `Write the schema settings: ${Object.keys(options.settings).join(", ")}`
3596
- }]],
3597
- execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings)
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)
3598
3834
  };
3599
3835
  };
3600
3836
  return {
@@ -3625,7 +3861,8 @@ const coreSettings = {
3625
3861
  /** What `hot-updater db` creates for a server without plugins. */
3626
3862
  const coreTarget = {
3627
3863
  schema: coreSchema,
3628
- settings: coreSettings
3864
+ settings: coreSettings,
3865
+ ordered: ["schema.core"]
3629
3866
  };
3630
3867
  resolveSchema([aggregateBatchingModule]).tables;
3631
3868
  /** Each plugin's `schema.<id>` settings row. */
@@ -3645,11 +3882,12 @@ const pluginModule = ({ id, schema, namespace }) => ({
3645
3882
  */
3646
3883
  const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBatching, retry, readSettings: readStored }) => {
3647
3884
  const fenced = withSchemaFence(adapter, name, coreSettings);
3648
- const createMigrator = ({ schema, settings } = coreTarget) => createEngineMigrator({
3885
+ const createMigrator = ({ schema, settings, ordered } = coreTarget) => createEngineMigrator({
3649
3886
  adapterName: name,
3650
3887
  adapter,
3651
3888
  schema,
3652
3889
  settings,
3890
+ ordered,
3653
3891
  readSettings: readStored ?? (async () => {
3654
3892
  const rows = await readSettings(adapter, Object.keys(settings)).catch((error) => {
3655
3893
  if (isMissingSchemaError(error)) return [];
@@ -3673,6 +3911,12 @@ const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBa
3673
3911
  /** A row this attempt read changed while it ran; the attempt reruns. */
3674
3912
  var StaleReadError = class extends Error {};
3675
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
+ ]));
3676
3920
  const versionOf = (row) => Number(row["_v"]);
3677
3921
  const isKeyed = (value) => value !== null && value !== void 0;
3678
3922
  const misuse = (table, message) => new DatabaseTransactionError(`${table}: ${message}`);
@@ -4017,7 +4261,9 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4017
4261
  assertOutsideTransaction();
4018
4262
  let run;
4019
4263
  let negative;
4020
- for (let round = 0; round < attempts; round += 1) {
4264
+ let failures = 0;
4265
+ let lost;
4266
+ for (let round = 0;; round += 1) {
4021
4267
  const delay = round && Math.min(maxDelayMs, baseDelayMs * 2 ** (round - 1));
4022
4268
  if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay / 2 + Math.random() * (delay / 2)));
4023
4269
  run ??= await attempt(fn).catch((error) => {
@@ -4026,6 +4272,8 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4026
4272
  });
4027
4273
  if (run === void 0) {
4028
4274
  onRetry?.("rerun", round + 1);
4275
+ lost = void 0;
4276
+ if ((failures += 1) >= attempts) break;
4029
4277
  continue;
4030
4278
  }
4031
4279
  let aggregates;
@@ -4036,8 +4284,14 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4036
4284
  negative = error;
4037
4285
  onRetry?.("rerun", round + 1);
4038
4286
  run = void 0;
4287
+ lost = void 0;
4288
+ if ((failures += 1) >= attempts) break;
4039
4289
  continue;
4040
4290
  }
4291
+ const versions = versionsOf(aggregates);
4292
+ if (lost !== void 0 && versions !== lost) failures -= 1;
4293
+ lost = void 0;
4294
+ if (failures >= attempts) break;
4041
4295
  const ops = [...run.ops, ...aggregates];
4042
4296
  if (ops.length <= 1 && ops.every(({ type }) => type === "check")) return run.result;
4043
4297
  if (!adapter.fits(ops)) throw new DatabaseConstraintError("too_large", ops[0].table.name);
@@ -4051,12 +4305,16 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4051
4305
  const failed = "failedOp" in outcome ? outcome.failedOp : void 0;
4052
4306
  if (failed === void 0 || failed >= run.ops.length) {
4053
4307
  onRetry?.("resend", round + 1);
4308
+ failures += 1;
4309
+ if (failed !== void 0) lost = versions;
4310
+ else if (failures >= attempts) break;
4054
4311
  continue;
4055
4312
  }
4056
4313
  const reason = await classify(ops[failed], run.read);
4057
4314
  if (reason) throw new DatabaseConstraintError(reason, ops[failed].table.name);
4058
4315
  onRetry?.("rerun", round + 1);
4059
4316
  run = void 0;
4317
+ if ((failures += 1) >= attempts) break;
4060
4318
  }
4061
4319
  throw negative ?? new DatabaseConflictError(`The transaction conflicted ${attempts} times.`);
4062
4320
  } };
@@ -4302,13 +4560,10 @@ const createDatabaseEngine = ({ batching, now = Date.now, meter, ...options }) =
4302
4560
  };
4303
4561
  return {
4304
4562
  ...engine,
4305
- /** Applies batched aggregate changes still pending: this process's buffer and the log. */
4563
+ /** Applies the batched aggregate changes still in the log. */
4306
4564
  flush: async () => {
4307
4565
  await batches?.flush();
4308
4566
  },
4309
- dispose: async () => {
4310
- await batches?.dispose();
4311
- },
4312
4567
  database(module) {
4313
4568
  const name = (model) => module.namespace ? `${module.namespace}_${model}` : model;
4314
4569
  return {
@@ -4389,8 +4644,7 @@ const createEngine = (database, { plugins = [], now = Date.now } = {}) => {
4389
4644
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
4390
4645
  return engine.database(module);
4391
4646
  },
4392
- flush: () => engine.flush(),
4393
- dispose: () => engine.dispose()
4647
+ flush: () => engine.flush()
4394
4648
  };
4395
4649
  };
4396
4650
  //#endregion
@@ -4460,10 +4714,10 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
4460
4714
  const at = row && expiresAt(table, row);
4461
4715
  return at === void 0 ? {} : { expiresAt: at };
4462
4716
  };
4463
- /** Every index and unique item a row has, by address. */
4464
- 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) => {
4465
4719
  const items = /* @__PURE__ */ new Map();
4466
- 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)) {
4467
4721
  const pk = partition(layout, index, eq);
4468
4722
  const sk = index.unique ? ONLY : encodeKvKey(indexOrderTuple(layout.table, index, row)) || ONLY;
4469
4723
  items.set(JSON.stringify([pk, sk]), {
@@ -4618,6 +4872,79 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
4618
4872
  lte: lt.endsWith(SEPARATOR) ? lt.slice(0, -1) : lt
4619
4873
  };
4620
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
+ };
4621
4948
  return {
4622
4949
  id: store.id,
4623
4950
  fits(ops) {
@@ -4677,13 +5004,16 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
4677
5004
  const layout = layoutOf(table);
4678
5005
  return store.deleteConsumed(rows.flatMap((row) => [rowItem(layout, rowKey(table, row)), ...[...itemsOf(layout, row).values()].map(({ key }) => key)]));
4679
5006
  } },
4680
- migrations: { apply: async () => store.migrations?.apply() },
5007
+ migrations: {
5008
+ apply: async () => store.migrations?.apply(),
5009
+ fillIndex
5010
+ },
4681
5011
  ...store.dispose === void 0 ? {} : { dispose: () => store.dispose() }
4682
5012
  };
4683
5013
  };
4684
5014
  //#endregion
4685
5015
  //#region ../../packages/server/dist/version.mjs
4686
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.5";
5016
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.50";
4687
5017
  //#endregion
4688
5018
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
4689
5019
  /**
@@ -4843,10 +5173,15 @@ const releaseCatalogScopeKeyOf = (input) => input.strategy === "APP_VERSION" ? c
4843
5173
  platform: input.platform,
4844
5174
  strategy: "FINGERPRINT"
4845
5175
  });
4846
- /** Projects a stored catalog row for one update check; null when the row is not this scope's. */
4847
- const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
4848
- if (row === null || row.platform !== input.platform || row.strategy !== input.strategy || row.channel_key !== input.channelKey || row.scope_key !== scopeKey || row.fingerprint_hash !== (input.strategy === "FINGERPRINT" ? input.fingerprintHash : null)) return null;
4849
- const compiled = parseCompiledCatalog(row.payload, input.strategy);
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;
4850
5185
  const appVersion = input.strategy === "APP_VERSION" ? input.appVersion : void 0;
4851
5186
  return {
4852
5187
  catalogId: row.catalog_id,
@@ -4859,6 +5194,8 @@ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyO
4859
5194
  scopeKey
4860
5195
  };
4861
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);
4862
5199
  //#endregion
4863
5200
  //#region ../../packages/server/dist/db/updateArtifacts.mjs
4864
5201
  const HBC_ASSET_PATH_RE = /\.bundle$/;
@@ -5476,8 +5813,8 @@ const baseBundleIdsOf = (row, range, bundleId, limit) => {
5476
5813
  //#endregion
5477
5814
  //#region ../../packages/server/dist/core/reads.mjs
5478
5815
  const PAGE$3 = 500;
5479
- const pick$1 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
5480
- const toBundleRow = pick$1([
5816
+ const pick$2 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
5817
+ const toBundleRow = pick$2([
5481
5818
  "id",
5482
5819
  "platform",
5483
5820
  "git_commit_hash",
@@ -5486,7 +5823,7 @@ const toBundleRow = pick$1([
5486
5823
  "manifest_file_hash",
5487
5824
  "asset_base_storage_uri"
5488
5825
  ]);
5489
- const toPatchRow = pick$1([
5826
+ const toPatchRow = pick$2([
5490
5827
  "id",
5491
5828
  "bundle_id",
5492
5829
  "base_bundle_id",
@@ -5496,7 +5833,7 @@ const toPatchRow = pick$1([
5496
5833
  "byte_size",
5497
5834
  "order_index"
5498
5835
  ]);
5499
- const toReleaseRow = pick$1([
5836
+ const toReleaseRow = pick$2([
5500
5837
  "id",
5501
5838
  "revision",
5502
5839
  "scope_key",
@@ -5517,7 +5854,7 @@ const toReleaseRow = pick$1([
5517
5854
  "created_at_ms",
5518
5855
  "updated_at_ms"
5519
5856
  ]);
5520
- const toCatalogRow = pick$1([
5857
+ const toCatalogRow = pick$2([
5521
5858
  "scope_key",
5522
5859
  "catalog_id",
5523
5860
  "strategy",
@@ -5532,7 +5869,7 @@ const toCatalogRow = pick$1([
5532
5869
  "is_tombstone",
5533
5870
  "updated_at_ms"
5534
5871
  ]);
5535
- const toChannelRow = pick$1(["id", "name"]);
5872
+ const toChannelRow = pick$2(["id", "name"]);
5536
5873
  /** Every page of one read, in order. */
5537
5874
  const drain$1 = async (read) => {
5538
5875
  const rows = [];
@@ -5545,8 +5882,16 @@ const drain$1 = async (read) => {
5545
5882
  return rows;
5546
5883
  };
5547
5884
  /** A keyset page's range: the keys strictly after `after`, in `order`. */
5548
- const after = (input) => input.after === void 0 ? {} : { range: (input.order ?? "asc") === "asc" ? { gt: input.after } : { lt: input.after } };
5549
- /** Core's reads, each through one declared index or key. */
5885
+ /** A keyset read's range on its index's order: past `after`, up to `through`. */
5886
+ const after = (input) => {
5887
+ const asc = (input.order ?? "asc") === "asc";
5888
+ const range = {
5889
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
5890
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
5891
+ };
5892
+ return Object.keys(range).length === 0 ? {} : { range };
5893
+ };
5894
+ /** Core's reads, each through one declared index or key; plugins get `CoreReads`. */
5550
5895
  const createCoreReads = (db, storage) => {
5551
5896
  /** A bundle row's patches, exactly as many as its reference counter holds. */
5552
5897
  const detail = async (row) => {
@@ -5734,8 +6079,35 @@ const createCoreReads = (db, storage) => {
5734
6079
  ...after(input)
5735
6080
  })).rows.map(toCatalogRow);
5736
6081
  },
5737
- /** Every channel, by name. */
5738
- 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);
5739
6111
  return (await drain$1((page) => db.findMany("channels", {
5740
6112
  index: "all",
5741
6113
  where: {},
@@ -5743,6 +6115,11 @@ const createCoreReads = (db, storage) => {
5743
6115
  ...page
5744
6116
  }))).map(toChannelRow);
5745
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
+ },
5746
6123
  async findChannelByName(name) {
5747
6124
  const row = await db.findOne("channels", { name });
5748
6125
  return row === null ? null : toChannelRow(row);
@@ -5750,6 +6127,318 @@ const createCoreReads = (db, storage) => {
5750
6127
  };
5751
6128
  };
5752
6129
  //#endregion
6130
+ //#region ../../packages/server/dist/core/iosDevices.mjs
6131
+ /**
6132
+ * A device's UDID: 40 hex digits, or 8 and 16 joined by a hyphen. The same
6133
+ * rule as `normalizeIosUdid` of `@hot-updater/protocol/native-artifact`,
6134
+ * implemented here so the server's runtime never loads the artifact readers.
6135
+ */
6136
+ const UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
6137
+ /** The form the registry stores and compares a UDID in, or null for text that isn't one. */
6138
+ const normalizeIosUdid = (value) => {
6139
+ const trimmed = value.trim();
6140
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
6141
+ };
6142
+ /** `ios_devices.name`'s bound in core's schema. */
6143
+ const NAME_MAX_LENGTH = 100;
6144
+ /** `ios_devices.requested_by` and `approved_by`'s bound: an email address. */
6145
+ const EMAIL_MAX_LENGTH = 320;
6146
+ /** `ios_devices.apple_issuer_id`'s bound. */
6147
+ const ISSUER_MAX_LENGTH = 64;
6148
+ /** The one row of `ios_device_account`. */
6149
+ const ACCOUNT_ROW = "registry";
6150
+ /** `ios_devices.apple_error`'s bound. */
6151
+ const ERROR_MAX_LENGTH = 512;
6152
+ const STATUSES = [
6153
+ "pending",
6154
+ "approved",
6155
+ "registered"
6156
+ ];
6157
+ const OUTCOMES = [
6158
+ "registered",
6159
+ "refused",
6160
+ "disabled",
6161
+ "missing"
6162
+ ];
6163
+ /** The `apple_error` of a device Apple has disabled. */
6164
+ const IOS_DEVICE_DISABLED_ERROR = "Disabled in the Apple account.";
6165
+ /** The `apple_error` of a registered device Apple no longer lists. */
6166
+ const IOS_DEVICE_MISSING_ERROR = "Gone from the Apple account. Approve it again to register it.";
6167
+ /** A device or registry request core cannot store: the caller's input. */
6168
+ var IosDeviceInputError = class extends TypeError {
6169
+ name = "IosDeviceInputError";
6170
+ };
6171
+ const pick$1 = (row) => ({
6172
+ id: row.id,
6173
+ udid: row.udid,
6174
+ name: row.name,
6175
+ status: row.status,
6176
+ requested_by: row.requested_by ?? null,
6177
+ created_at_ms: row.created_at_ms,
6178
+ approved_by: row.approved_by ?? null,
6179
+ approved_at_ms: row.approved_at_ms ?? null,
6180
+ registered_at_ms: row.registered_at_ms ?? null,
6181
+ apple_issuer_id: row.apple_issuer_id ?? null,
6182
+ apple_error: row.apple_error ?? null,
6183
+ build_id: row.build_id ?? null
6184
+ });
6185
+ const udidOf = (udid) => {
6186
+ const key = typeof udid === "string" ? normalizeIosUdid(udid) : null;
6187
+ if (key === null) throw new IosDeviceInputError("Invalid iOS device: udid must be 40 hex digits, or 8 and 16 joined by a hyphen.");
6188
+ return key;
6189
+ };
6190
+ const nameOf = (name) => {
6191
+ const trimmed = typeof name === "string" ? name.trim() : "";
6192
+ if (trimmed.length === 0 || trimmed.length > NAME_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: name must be 1 to ${NAME_MAX_LENGTH} characters.`);
6193
+ return trimmed;
6194
+ };
6195
+ /** An email, lower-cased, or null for the CLI. */
6196
+ const personOf = (value, field) => {
6197
+ if (value === null) return null;
6198
+ const email = typeof value === "string" ? value.trim().toLowerCase() : "";
6199
+ if (email.length === 0 || email.length > EMAIL_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: ${field} must be an email of at most ${EMAIL_MAX_LENGTH} characters, or null.`);
6200
+ return email;
6201
+ };
6202
+ /** Apple's words, on one line and within the column's bound. */
6203
+ const errorText = (text) => {
6204
+ const line = text.replace(/\s+/gu, " ").trim();
6205
+ return line.length > ERROR_MAX_LENGTH ? `${line.slice(0, 511)}…` : line;
6206
+ };
6207
+ /**
6208
+ * The iOS device registry: the iPhones and iPads a team asked to install ad hoc
6209
+ * builds on. The Console writes requests and approvals, and the CLI what Apple
6210
+ * said, each over the row it read.
6211
+ */
6212
+ const createIosDeviceApi = (db, { now = Date.now } = {}) => {
6213
+ const findIosDevice = async (udid) => {
6214
+ const key = normalizeIosUdid(udid);
6215
+ if (key === null) return null;
6216
+ const row = await db.findOne("ios_devices", { udid: key });
6217
+ return row === null ? null : pick$1(row);
6218
+ };
6219
+ /**
6220
+ * The issuer of the registry's earliest registration among its rows, by
6221
+ * when and then by ID, or null when no row names one: read only while the
6222
+ * registry has no account yet, in one read of its first registration. A
6223
+ * row names an issuer exactly when it has a registration time: both are
6224
+ * set by its first registration and never cleared.
6225
+ */
6226
+ const accountOfRows = async () => {
6227
+ const { rows } = await db.findMany("ios_devices", {
6228
+ index: "byRegistration",
6229
+ where: {},
6230
+ order: "asc",
6231
+ limit: 1,
6232
+ range: { gte: 0 }
6233
+ });
6234
+ return (rows[0] === void 0 ? null : pick$1(rows[0]))?.apple_issuer_id ?? null;
6235
+ };
6236
+ return {
6237
+ async listIosDevices(input) {
6238
+ if (input.status !== void 0 && !STATUSES.includes(input.status)) throw new IosDeviceInputError(`Invalid iOS device status: ${String(input.status)}. Expected ${STATUSES.join(", ")}.`);
6239
+ const page = {
6240
+ order: input.order ?? "asc",
6241
+ limit: input.limit,
6242
+ ...after(input)
6243
+ };
6244
+ const { rows } = input.status === void 0 ? await db.findMany("ios_devices", {
6245
+ index: "all",
6246
+ where: {},
6247
+ ...page
6248
+ }) : await db.findMany("ios_devices", {
6249
+ index: "byStatus",
6250
+ where: { status: input.status },
6251
+ ...page
6252
+ });
6253
+ return rows.map(pick$1);
6254
+ },
6255
+ findIosDevice,
6256
+ async requestIosDevice(input) {
6257
+ const udid = udidOf(input.udid);
6258
+ const name = nameOf(input.name);
6259
+ const requestedBy = personOf(input.requestedBy, "requestedBy");
6260
+ const existing = await db.findOne("ios_devices", { udid });
6261
+ if (existing !== null) return {
6262
+ device: pick$1(existing),
6263
+ created: false
6264
+ };
6265
+ const device = {
6266
+ id: createUUIDv7(),
6267
+ udid,
6268
+ name,
6269
+ status: "pending",
6270
+ requested_by: requestedBy,
6271
+ created_at_ms: now(),
6272
+ approved_by: null,
6273
+ approved_at_ms: null,
6274
+ registered_at_ms: null,
6275
+ apple_issuer_id: null,
6276
+ apple_error: null,
6277
+ build_id: null
6278
+ };
6279
+ try {
6280
+ await db.transaction(async (tx) => {
6281
+ tx.create("ios_devices", device);
6282
+ });
6283
+ } catch (error) {
6284
+ if (error instanceof DatabaseConstraintError && error.reason === "unique") {
6285
+ const winner = await db.findOne("ios_devices", { udid });
6286
+ if (winner !== null) return {
6287
+ device: pick$1(winner),
6288
+ created: false
6289
+ };
6290
+ }
6291
+ throw error;
6292
+ }
6293
+ return {
6294
+ device,
6295
+ created: true
6296
+ };
6297
+ },
6298
+ async approveIosDevice(id, input) {
6299
+ const name = input.name === void 0 ? void 0 : nameOf(input.name);
6300
+ const approvedBy = personOf(input.approvedBy, "approvedBy");
6301
+ return db.transaction(async (tx) => {
6302
+ const row = await tx.findOne("ios_devices", { id });
6303
+ if (row === null) return null;
6304
+ const device = pick$1(row);
6305
+ const set = {
6306
+ ...name === void 0 || name === device.name ? {} : { name },
6307
+ ...device.status === "pending" ? {
6308
+ status: "approved",
6309
+ approved_by: approvedBy,
6310
+ approved_at_ms: now()
6311
+ } : {}
6312
+ };
6313
+ if (Object.keys(set).length === 0) return device;
6314
+ tx.update("ios_devices", row, set);
6315
+ return {
6316
+ ...device,
6317
+ ...set
6318
+ };
6319
+ });
6320
+ },
6321
+ async renameIosDevice(id, input) {
6322
+ const name = nameOf(input);
6323
+ return db.transaction(async (tx) => {
6324
+ const row = await tx.findOne("ios_devices", { id });
6325
+ if (row === null) return null;
6326
+ const device = pick$1(row);
6327
+ if (device.name === name) return device;
6328
+ tx.update("ios_devices", row, { name });
6329
+ return {
6330
+ ...device,
6331
+ name
6332
+ };
6333
+ });
6334
+ },
6335
+ async recordIosDeviceOutcome({ id, seen, issuerId, outcome, reason }) {
6336
+ if (!OUTCOMES.includes(outcome)) throw new IosDeviceInputError(`Invalid iOS device outcome: ${String(outcome)}. Expected ${OUTCOMES.join(", ")}.`);
6337
+ if (typeof issuerId !== "string" || issuerId.trim().length === 0 || issuerId.length > ISSUER_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device outcome: issuerId must be an App Store Connect issuer of at most ${ISSUER_MAX_LENGTH} characters.`);
6338
+ return db.transaction(async (tx) => {
6339
+ const row = await tx.findOne("ios_devices", { id });
6340
+ if (row === null) return null;
6341
+ const device = pick$1(row);
6342
+ if (device.status !== seen.status || device.approved_at_ms !== seen.approvedAtMs || device.apple_issuer_id !== null && device.apple_issuer_id !== issuerId) return null;
6343
+ let set;
6344
+ switch (outcome) {
6345
+ case "registered":
6346
+ if (device.status === "pending") return null;
6347
+ set = {
6348
+ status: "registered",
6349
+ registered_at_ms: device.registered_at_ms ?? now(),
6350
+ apple_issuer_id: issuerId,
6351
+ apple_error: null
6352
+ };
6353
+ break;
6354
+ case "refused":
6355
+ if (device.status !== "approved") return null;
6356
+ set = { apple_error: errorText(reason === void 0 || reason.trim() === "" ? "Apple refused it." : reason) };
6357
+ break;
6358
+ case "disabled":
6359
+ if (device.status === "pending") return null;
6360
+ set = { apple_error: IOS_DEVICE_DISABLED_ERROR };
6361
+ break;
6362
+ case "missing":
6363
+ if (device.status !== "registered") return null;
6364
+ set = {
6365
+ status: "pending",
6366
+ approved_by: null,
6367
+ approved_at_ms: null,
6368
+ apple_error: IOS_DEVICE_MISSING_ERROR
6369
+ };
6370
+ }
6371
+ if (Object.entries(set).some(([column, value]) => device[column] !== (value ?? null))) tx.update("ios_devices", row, set);
6372
+ return {
6373
+ ...device,
6374
+ ...set
6375
+ };
6376
+ });
6377
+ },
6378
+ async markIosDevicesInBuild({ buildId, ids }) {
6379
+ for (const id of new Set(ids)) await db.transaction(async (tx) => {
6380
+ const row = await tx.findOne("ios_devices", { id });
6381
+ if (row === null || typeof row.build_id === "string" && row.build_id >= buildId) return;
6382
+ tx.update("ios_devices", row, { build_id: buildId });
6383
+ });
6384
+ },
6385
+ async findIosDeviceAccount() {
6386
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6387
+ const issuerId = existing === null ? await accountOfRows() : existing.apple_issuer_id;
6388
+ return issuerId === null ? null : { issuerId };
6389
+ },
6390
+ async claimIosDeviceAccount(issuerId) {
6391
+ if (typeof issuerId !== "string" || issuerId.trim().length === 0 || issuerId.length > ISSUER_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device account: issuerId must be an App Store Connect issuer of at most ${ISSUER_MAX_LENGTH} characters.`);
6392
+ const answer = (held) => ({
6393
+ issuerId: held,
6394
+ claimed: held === issuerId
6395
+ });
6396
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6397
+ if (existing !== null) return answer(existing.apple_issuer_id);
6398
+ const holder = await accountOfRows() ?? issuerId;
6399
+ try {
6400
+ await db.transaction(async (tx) => {
6401
+ tx.create("ios_device_account", {
6402
+ id: ACCOUNT_ROW,
6403
+ apple_issuer_id: holder,
6404
+ claimed_at_ms: now()
6405
+ });
6406
+ });
6407
+ return answer(holder);
6408
+ } catch (error) {
6409
+ if (error instanceof DatabaseConstraintError && (error.reason === "exists" || error.reason === "unique")) {
6410
+ const winner = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6411
+ if (winner !== null) return answer(winner.apple_issuer_id);
6412
+ }
6413
+ throw error;
6414
+ }
6415
+ },
6416
+ async deleteIosDevice(id, only) {
6417
+ const requestedBy = only?.requestedBy === void 0 ? void 0 : personOf(only.requestedBy, "requestedBy");
6418
+ return db.transaction(async (tx) => {
6419
+ const row = await tx.findOne("ios_devices", { id });
6420
+ if (row === null) return null;
6421
+ const device = pick$1(row);
6422
+ if (only?.status !== void 0 && device.status !== only.status || requestedBy !== void 0 && device.requested_by !== requestedBy) return null;
6423
+ await tx.delete("ios_devices", row);
6424
+ return device;
6425
+ });
6426
+ }
6427
+ };
6428
+ };
6429
+ //#endregion
6430
+ //#region ../../packages/server/dist/core/nativeBuildDestinations.mjs
6431
+ /** Store destinations accepted for each native platform. */
6432
+ const NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
6433
+ android: [
6434
+ "play-internal",
6435
+ "play-closed",
6436
+ "play-open",
6437
+ "play-production"
6438
+ ],
6439
+ ios: ["testflight"]
6440
+ };
6441
+ //#endregion
5753
6442
  //#region ../../packages/server/dist/core/writes.mjs
5754
6443
  const PAGE$2 = 500;
5755
6444
  /** Moves one bundle into or out of its platform's total and the overall total. */
@@ -5779,8 +6468,10 @@ const deleteBundle = async (tx, current) => {
5779
6468
  /**
5780
6469
  * Replaces a bundle's patches with `rows`: kept patches are updated where
5781
6470
  * they changed, others deleted or created, so no key is written twice.
6471
+ * `checkNew` sees each patch it is about to create, and refuses one by
6472
+ * throwing, which leaves the transaction's writes undone.
5782
6473
  */
5783
- const replaceBundlePatches = async (tx, bundle, rows) => {
6474
+ const replaceBundlePatches = async (tx, bundle, rows, checkNew) => {
5784
6475
  const wanted = new Map(rows.map((row) => [row.id, row]));
5785
6476
  const count = bundle._refs_bundle_patches_bundle_id ?? 0;
5786
6477
  let cursor;
@@ -5805,6 +6496,7 @@ const replaceBundlePatches = async (tx, bundle, rows) => {
5805
6496
  if (page.next === void 0) break;
5806
6497
  cursor = page.next;
5807
6498
  }
6499
+ if (checkNew !== void 0) for (const row of wanted.values()) await checkNew(row);
5808
6500
  for (const row of wanted.values()) tx.create("bundle_patches", row);
5809
6501
  };
5810
6502
  /** A channel by name, created when missing; a concurrent creator's row is returned instead. */
@@ -5867,6 +6559,27 @@ const GIT_COMMIT_HASH_MAX_LENGTH = 255;
5867
6559
  * and looks up nothing else.
5868
6560
  */
5869
6561
  const BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
6562
+ /** `native_builds.sandbox_url_scheme`'s bound in core's schema. */
6563
+ const SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
6564
+ /**
6565
+ * A URL scheme as RFC 3986 spells it, in lower case: what a sandbox build's
6566
+ * artifact registers, as `@hot-updater/protocol/native-artifact` reads it.
6567
+ */
6568
+ const URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
6569
+ /**
6570
+ * A bundle identifier or application ID, as an artifact reports it: letters,
6571
+ * digits, dots, dashes and underscores, which a scope key holds as they are.
6572
+ */
6573
+ const APP_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;
6574
+ /** A fingerprint hash as a Release Catalog scope key holds it. */
6575
+ const FINGERPRINT_HASH = /^[A-Za-z0-9._~-]{1,255}$/;
6576
+ /** How each kind of artifact can install. */
6577
+ const DISTRIBUTIONS = {
6578
+ apk: ["direct"],
6579
+ app: ["direct"],
6580
+ aab: ["store"],
6581
+ ipa: ["direct", "store"]
6582
+ };
5870
6583
  /** A native build or scope core cannot store or look up: the caller's input. */
5871
6584
  var NativeBuildInputError = class extends TypeError {
5872
6585
  name = "NativeBuildInputError";
@@ -5888,24 +6601,73 @@ const pick = (row) => ({
5888
6601
  build_number: row.build_number ?? null,
5889
6602
  submitted_to: row.submitted_to ?? null,
5890
6603
  submitted_at_ms: row.submitted_at_ms ?? null,
5891
- submitted_version: row.submitted_version ?? null
6604
+ submitted_version: row.submitted_version ?? null,
6605
+ is_store_build: row.is_store_build === true,
6606
+ is_sandbox: row.is_sandbox === true,
6607
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
6608
+ export_method: row.export_method ?? null,
6609
+ native_app_version: row.native_app_version ?? null
5892
6610
  });
5893
- /** The store track each platform's builds are submitted to. */
5894
- const SUBMISSION_DESTINATIONS = {
5895
- android: "play-internal",
5896
- ios: "testflight"
5897
- };
6611
+ /** The export methods an `.ipa` registers with. */
6612
+ const EXPORT_METHODS = /* @__PURE__ */ new Set([
6613
+ "app-store",
6614
+ "ad-hoc",
6615
+ "development",
6616
+ "enterprise"
6617
+ ]);
6618
+ /**
6619
+ * How many older builds of a scope one read takes, looking for one older than
6620
+ * a bundle when a build made after the bundle is the newest.
6621
+ */
6622
+ const OLDER_BUILDS_PAGE = 20;
6623
+ /**
6624
+ * How many pages of older builds that look reads before it answers null: 100
6625
+ * builds made after the bundle in one scope, where a deploy's new bundle has
6626
+ * none or a few registered while it deploys.
6627
+ */
6628
+ const OLDER_BUILDS_PAGES = 5;
6629
+ /** How many times a mark runs again after losing its scope's mark to another. */
6630
+ const MARK_ATTEMPTS = 8;
5898
6631
  /** `native_builds.build_number`'s bound in core's schema. */
5899
6632
  const BUILD_NUMBER_MAX_LENGTH = 64;
5900
6633
  /** `native_builds.submitted_version`'s bound in core's schema. */
5901
6634
  const SUBMITTED_VERSION_MAX_LENGTH = 255;
6635
+ const checkedScopeKey = (scopeKey) => {
6636
+ if (scopeKey.length > SCOPE_KEY_MAX_LENGTH) throw new NativeBuildInputError(`Invalid native build scope: its key is longer than ${SCOPE_KEY_MAX_LENGTH} characters; shorten the channel or app version.`);
6637
+ return scopeKey;
6638
+ };
6639
+ /**
6640
+ * How a registered artifact installs: an `.ipa` by its export method, and
6641
+ * `unknown` for one whose export no profile confirmed, which no lookup asks
6642
+ * for, so it is never reused as either.
6643
+ */
6644
+ const registeredDistribution = (kind, exportMethod) => kind !== "ipa" ? DISTRIBUTIONS[kind][0] : exportMethod === void 0 || exportMethod === null ? "unknown" : exportMethod === "app-store" ? "store" : "direct";
6645
+ /**
6646
+ * A sandbox build scope's key, which names no channel: the app ID, URL
6647
+ * scheme, artifact kind and distribution in its place, then the fingerprint,
6648
+ * or the app-version strategy and the exact app version. `v1:sandbox:` is no
6649
+ * Release Catalog strategy, so it never meets a normal build's key.
6650
+ */
6651
+ const sandboxScopeKey = (scope, sandbox) => {
6652
+ const { appId, urlScheme, artifactKind, distribution } = sandbox;
6653
+ const problem = typeof appId !== "string" || !APP_ID.test(appId) ? "its app ID must be a bundle identifier or application ID, up to 255 characters" : typeof urlScheme !== "string" || !URL_SCHEME.test(urlScheme) ? `its URL scheme must be a URL scheme in lower case, up to ${SANDBOX_URL_SCHEME_MAX_LENGTH} characters` : !ARTIFACT_KINDS[scope.platform]?.includes(artifactKind) ? `its artifact kind must be one an ${scope.platform} build makes` : distribution !== "unknown" && !DISTRIBUTIONS[artifactKind].includes(distribution) ? `an .${artifactKind} doesn't install as ${String(distribution)}` : scope.fingerprintHash !== null && !FINGERPRINT_HASH.test(scope.fingerprintHash) ? "its fingerprint hash must be 1-255 URL-safe ASCII characters" : null;
6654
+ if (problem !== null) throw new NativeBuildInputError(`Invalid sandbox build scope: ${problem}.`);
6655
+ const target = scope.fingerprintHash === null ? `app-version:${encodeURIComponent(scope.appVersion)}` : `fingerprint:${scope.fingerprintHash}`;
6656
+ return checkedScopeKey(`v1:sandbox:${scope.platform}:${appId}:${urlScheme}:${artifactKind}:${distribution}:${target}`);
6657
+ };
5902
6658
  /**
5903
6659
  * A native build scope's key: the Release Catalog scope key of a
5904
6660
  * fingerprint, or of the app-version strategy followed by the exact app
5905
6661
  * version the build compiled in. One key serves both strategies, so one
5906
- * index finds the newest build of either.
6662
+ * index finds the newest build of either. A sandbox scope's key names no
6663
+ * channel, so pull requests find a sandbox build on any.
5907
6664
  */
5908
6665
  const nativeBuildScopeKey = (scope) => {
6666
+ const { sandbox } = scope;
6667
+ if (sandbox !== void 0 && sandbox !== null) {
6668
+ if (sandbox.distribution !== "direct" && sandbox.distribution !== "store") throw new NativeBuildInputError("Invalid sandbox build scope: its distribution must be direct or store.");
6669
+ return sandboxScopeKey(scope, sandbox);
6670
+ }
5909
6671
  let scopeKey;
5910
6672
  try {
5911
6673
  const channelKey = encodeChannelKey(scope.channel);
@@ -5922,32 +6684,126 @@ const nativeBuildScopeKey = (scope) => {
5922
6684
  } catch (error) {
5923
6685
  throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
5924
6686
  }
5925
- if (scopeKey.length > SCOPE_KEY_MAX_LENGTH) throw new NativeBuildInputError(`Invalid native build scope: its key is longer than ${SCOPE_KEY_MAX_LENGTH} characters; shorten the channel or app version.`);
5926
- return scopeKey;
6687
+ return checkedScopeKey(scopeKey);
6688
+ };
6689
+ /** The channel row a registration names, or the refusal of its channel. */
6690
+ const channelIdOf = (channel) => {
6691
+ try {
6692
+ return `channel:${encodeChannelKey(channel)}`;
6693
+ } catch (error) {
6694
+ throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
6695
+ }
6696
+ };
6697
+ /**
6698
+ * A registration's scope key, from the registration's own facts: a sandbox
6699
+ * build's from what its artifact says, whatever `sandbox` it names.
6700
+ */
6701
+ const registrationScopeKey = (registration) => {
6702
+ channelIdOf(registration.channel);
6703
+ return registration.isSandbox === true ? sandboxScopeKey(registration, {
6704
+ appId: registration.sandboxAppId,
6705
+ urlScheme: registration.sandboxUrlScheme,
6706
+ artifactKind: registration.artifact.kind,
6707
+ distribution: registeredDistribution(registration.artifact.kind, registration.exportMethod)
6708
+ }) : nativeBuildScopeKey({
6709
+ ...registration,
6710
+ sandbox: null
6711
+ });
6712
+ };
6713
+ /**
6714
+ * Refuses a patch from a sandbox build's built-in bundle: no deploy patches
6715
+ * from one, so no store or test install of the app gets a patch made for a
6716
+ * sandbox build. One unique read of the base.
6717
+ */
6718
+ const refuseSandboxPatchBase = async (db, baseBundleId) => {
6719
+ if ((await db.findOne("native_builds", { min_bundle_id: baseBundleId }))?.is_sandbox === true) throw new NativeBuildInputError("A sandbox build's built-in bundle is no patch base.");
5927
6720
  };
5928
6721
  /** Whether `bundleId` is a native build's built-in bundle: one unique read. */
5929
6722
  const isBuiltInBundle = async (db, bundleId) => await db.findOne("native_builds", { min_bundle_id: bundleId }) !== null;
5930
- const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, artifact }) => {
6723
+ const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, sandboxAppId, exportMethod, nativeAppVersion, artifact }) => {
5931
6724
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
5932
6725
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
5933
6726
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
5934
6727
  if (channel.trim().length === 0) return "channel is required";
6728
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
6729
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
6730
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
6731
+ if (typeof sandboxUrlScheme !== "string" || !URL_SCHEME.test(sandboxUrlScheme)) return `sandboxUrlScheme must be a URL scheme in lower case, up to ${SANDBOX_URL_SCHEME_MAX_LENGTH} characters, or null`;
6732
+ }
6733
+ if (sandboxAppId !== void 0 && sandboxAppId !== null) {
6734
+ if (isSandbox !== true) return "sandboxAppId is a sandbox build's, and this isn't one";
6735
+ if (typeof sandboxAppId !== "string" || !APP_ID.test(sandboxAppId)) return "sandboxAppId must be the artifact's bundle identifier or application ID, up to 255 characters";
6736
+ }
6737
+ if (isSandbox === true) {
6738
+ if (sandboxUrlScheme === void 0 || sandboxUrlScheme === null) return "a sandbox build needs the sandboxUrlScheme its artifact registers";
6739
+ if (sandboxAppId === void 0 || sandboxAppId === null) return "a sandbox build needs the sandboxAppId its artifact reports, which an older hot-updater CLI doesn't send. Upgrade the hot-updater CLI to the version that matches this server, and build again";
6740
+ }
5935
6741
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
5936
6742
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
5937
6743
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
5938
6744
  if (buildNumber !== void 0 && buildNumber !== null && (buildNumber.trim().length === 0 || buildNumber.length > BUILD_NUMBER_MAX_LENGTH)) return `buildNumber must be the artifact's build number, up to ${BUILD_NUMBER_MAX_LENGTH} characters, or null`;
6745
+ if (nativeAppVersion !== void 0 && nativeAppVersion !== null && (typeof nativeAppVersion !== "string" || nativeAppVersion.trim().length === 0)) return "nativeAppVersion must be the artifact's app version, or null";
5939
6746
  const kinds = ARTIFACT_KINDS[platform];
5940
6747
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
6748
+ if (exportMethod !== void 0 && exportMethod !== null) {
6749
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
6750
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
6751
+ }
5941
6752
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
5942
6753
  return null;
5943
6754
  };
6755
+ /** The other install target of an iOS sandbox build's native code. */
6756
+ const SIBLING_KINDS = {
6757
+ app: "ipa",
6758
+ ipa: "app"
6759
+ };
6760
+ /**
6761
+ * Whether a build is one a person installs from its file: a Simulator `.app`,
6762
+ * or an `.ipa` exported for direct install, that no store took and that isn't
6763
+ * the store build. One rule for a sibling and the build it is found from, so
6764
+ * a build that shows its sibling is shown by it.
6765
+ */
6766
+ const isInstallTarget = (build) => !build.is_store_build && build.submitted_to === null && (build.artifact_kind === "app" || build.artifact_kind === "ipa" && build.export_method !== null && build.export_method !== "app-store");
6767
+ /**
6768
+ * The scope key of the other install target of a sandbox build, from its own
6769
+ * key's app ID and URL scheme, which hold no colon, and its row's fingerprint
6770
+ * or app version, through `sandboxScopeKey`; null for a key it didn't make.
6771
+ */
6772
+ const siblingSandboxScopeKey = (build, artifactKind) => {
6773
+ const [version, sandbox, platform, appId, urlScheme] = build.scope_key.split(":");
6774
+ if (version !== "v1" || sandbox !== "sandbox" || platform !== build.platform || appId === void 0 || urlScheme === void 0) return null;
6775
+ const target = build.fingerprint_hash === null ? {
6776
+ platform: build.platform,
6777
+ fingerprintHash: null,
6778
+ appVersion: build.app_version ?? ""
6779
+ } : {
6780
+ platform: build.platform,
6781
+ fingerprintHash: build.fingerprint_hash,
6782
+ appVersion: null
6783
+ };
6784
+ try {
6785
+ return sandboxScopeKey(target, {
6786
+ appId,
6787
+ urlScheme,
6788
+ artifactKind: build.artifact_kind,
6789
+ distribution: registeredDistribution(build.artifact_kind, build.export_method)
6790
+ }) === build.scope_key ? sandboxScopeKey(target, {
6791
+ appId,
6792
+ urlScheme,
6793
+ artifactKind,
6794
+ distribution: "direct"
6795
+ }) : null;
6796
+ } catch {
6797
+ return null;
6798
+ }
6799
+ };
5944
6800
  /** The native build registry: core's `native_builds` and the built-in bundle rows. */
5945
6801
  const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
5946
6802
  async registerNativeBuild(registration) {
5947
6803
  const problem = problemOf(registration);
5948
6804
  if (problem !== null) throw new NativeBuildInputError(`Invalid native build: ${problem}.`);
5949
- const scopeKey = nativeBuildScopeKey(registration);
5950
- const channelId = `channel:${encodeChannelKey(registration.channel)}`;
6805
+ const scopeKey = registrationScopeKey(registration);
6806
+ const channelId = channelIdOf(registration.channel);
5951
6807
  const { embeddedBundle } = registration;
5952
6808
  const row = {
5953
6809
  id: registration.id,
@@ -5966,7 +6822,12 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
5966
6822
  build_number: registration.buildNumber ?? null,
5967
6823
  submitted_to: null,
5968
6824
  submitted_at_ms: null,
5969
- submitted_version: null
6825
+ submitted_version: null,
6826
+ is_store_build: false,
6827
+ is_sandbox: registration.isSandbox === true,
6828
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
6829
+ export_method: registration.exportMethod ?? null,
6830
+ native_app_version: registration.nativeAppVersion ?? null
5970
6831
  };
5971
6832
  for (let attempt = 1;; attempt += 1) {
5972
6833
  await insertChannel(db, {
@@ -6000,25 +6861,82 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6000
6861
  const row = await db.findOne("native_builds", { id });
6001
6862
  return row === null ? null : pick(row);
6002
6863
  },
6864
+ async findNativeBuildByBuiltInBundle(bundleId) {
6865
+ const row = await db.findOne("native_builds", { min_bundle_id: bundleId });
6866
+ return row === null ? null : pick(row);
6867
+ },
6003
6868
  async findNativeBuild(scope, options) {
6004
6869
  const scopeKey = nativeBuildScopeKey(scope);
6005
6870
  const buildKey = options?.buildKey;
6006
6871
  if (buildKey !== void 0 && !BUILD_KEY.test(buildKey)) throw new NativeBuildInputError("Invalid native build key: it must be nbk1: and a SHA-256.");
6007
- const { rows } = buildKey === void 0 ? await db.findMany("native_builds", {
6872
+ const artifactKind = options?.artifactKind;
6873
+ if (artifactKind !== void 0 && !ARTIFACT_KINDS[scope.platform].includes(artifactKind)) throw new NativeBuildInputError(`Invalid native build kind: an ${scope.platform} build is ${ARTIFACT_KINDS[scope.platform].join(" or ")}.`);
6874
+ const ofKind = (row) => artifactKind === void 0 || row.artifact_kind === artifactKind;
6875
+ if (options?.storeBuild) {
6876
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
6877
+ return marked === null || !ofKind(marked) ? null : pick(marked);
6878
+ }
6879
+ const read = (limit, before) => {
6880
+ const page = {
6881
+ order: "desc",
6882
+ limit,
6883
+ ...before === void 0 ? {} : { range: { lt: before } }
6884
+ };
6885
+ return buildKey !== void 0 ? db.findMany("native_builds", {
6886
+ index: "byBuildKey",
6887
+ where: {
6888
+ scope_key: scopeKey,
6889
+ build_key: buildKey
6890
+ },
6891
+ ...page
6892
+ }) : artifactKind !== void 0 ? db.findMany("native_builds", {
6893
+ index: "byScopeKind",
6894
+ where: {
6895
+ scope_key: scopeKey,
6896
+ artifact_kind: artifactKind
6897
+ },
6898
+ ...page
6899
+ }) : db.findMany("native_builds", {
6900
+ index: "byScope",
6901
+ where: { scope_key: scopeKey },
6902
+ ...page
6903
+ });
6904
+ };
6905
+ const bundleId = options?.builtInOlderThan;
6906
+ if (bundleId !== void 0 && scope.sandbox !== void 0 && scope.sandbox !== null) return null;
6907
+ const { rows } = await read(1);
6908
+ const newest = (rows[0] === void 0 ? void 0 : pick(rows[0])) ?? (artifactKind !== void 0 && buildKey === void 0 ? await db.findMany("native_builds", {
6008
6909
  index: "byScope",
6009
6910
  where: { scope_key: scopeKey },
6010
6911
  order: "desc",
6011
6912
  limit: 1
6012
- }) : await db.findMany("native_builds", {
6013
- index: "byBuildKey",
6014
- where: {
6015
- scope_key: scopeKey,
6016
- build_key: buildKey
6017
- },
6913
+ }).then(({ rows: [row] }) => row?.artifact_kind === artifactKind ? pick(row) : void 0) : void 0);
6914
+ if (newest === void 0 || !ofKind(newest)) return null;
6915
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return newest;
6916
+ let before = newest.id;
6917
+ for (let page = 0; page < OLDER_BUILDS_PAGES; page += 1) {
6918
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
6919
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
6920
+ if (usable !== void 0) return ofKind(usable) ? pick(usable) : null;
6921
+ const last = older.at(-1);
6922
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
6923
+ before = last.id;
6924
+ }
6925
+ return null;
6926
+ },
6927
+ async findNativeBuildSibling(build) {
6928
+ const artifactKind = SIBLING_KINDS[build.artifact_kind];
6929
+ if (build.platform !== "ios" || !build.is_sandbox || artifactKind === void 0 || !isInstallTarget(build)) return null;
6930
+ const scopeKey = siblingSandboxScopeKey(build, artifactKind);
6931
+ if (scopeKey === null) return null;
6932
+ const { rows } = await db.findMany("native_builds", {
6933
+ index: "byScope",
6934
+ where: { scope_key: scopeKey },
6018
6935
  order: "desc",
6019
6936
  limit: 1
6020
6937
  });
6021
- return rows[0] === void 0 ? null : pick(rows[0]);
6938
+ const sibling = rows[0] === void 0 ? null : pick(rows[0]);
6939
+ return sibling !== null && isInstallTarget(sibling) ? sibling : null;
6022
6940
  },
6023
6941
  async recordNativeBuildSubmission(id, { destination, version }) {
6024
6942
  if (version.trim().length === 0 || version.length > SUBMITTED_VERSION_MAX_LENGTH) throw new NativeBuildInputError(`Invalid native build submission: version must be the store's label of the build, up to ${SUBMITTED_VERSION_MAX_LENGTH} characters.`);
@@ -6026,7 +6944,8 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6026
6944
  const row = await tx.findOne("native_builds", { id });
6027
6945
  if (row === null) return null;
6028
6946
  const build = pick(row);
6029
- if (SUBMISSION_DESTINATIONS[build.platform] !== destination) throw new NativeBuildInputError(`Invalid native build submission: an ${build.platform} build is submitted to ${SUBMISSION_DESTINATIONS[build.platform]}, not ${destination}.`);
6947
+ if (!NATIVE_BUILD_SUBMISSION_DESTINATIONS[build.platform].includes(destination)) throw new NativeBuildInputError(`Invalid native build submission: an ${build.platform} build is submitted to ${NATIVE_BUILD_SUBMISSION_DESTINATIONS[build.platform].join(" or ")}, not ${destination}.`);
6948
+ if (build.is_sandbox && destination !== "testflight" && destination !== "play-internal") throw new NativeBuildInputError("A sandbox build can submit only to TestFlight or Play internal testing.");
6030
6949
  const set = {
6031
6950
  submitted_to: destination,
6032
6951
  submitted_at_ms: now(),
@@ -6039,6 +6958,46 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6039
6958
  };
6040
6959
  });
6041
6960
  },
6961
+ async markNativeBuild(id, { storeBuild }) {
6962
+ for (let attempt = 1;; attempt += 1) try {
6963
+ return await db.transaction(async (tx) => {
6964
+ const row = await tx.findOne("native_builds", { id });
6965
+ if (row === null) return null;
6966
+ const build = pick(row);
6967
+ if (!storeBuild) {
6968
+ if (build.is_store_build) tx.update("native_builds", row, { is_store_build: false });
6969
+ return {
6970
+ nativeBuild: {
6971
+ ...build,
6972
+ is_store_build: false
6973
+ },
6974
+ previous: null
6975
+ };
6976
+ }
6977
+ if (build.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
6978
+ if (build.is_store_build) return {
6979
+ nativeBuild: build,
6980
+ previous: null
6981
+ };
6982
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build.scope_key });
6983
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
6984
+ tx.update("native_builds", row, { is_store_build: true });
6985
+ return {
6986
+ nativeBuild: {
6987
+ ...build,
6988
+ is_store_build: true
6989
+ },
6990
+ previous: holder === null ? null : {
6991
+ ...pick(holder),
6992
+ is_store_build: false
6993
+ }
6994
+ };
6995
+ });
6996
+ } catch (error) {
6997
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
6998
+ throw error;
6999
+ }
7000
+ },
6042
7001
  async deleteNativeBuild(id) {
6043
7002
  return db.transaction(async (tx) => {
6044
7003
  const row = await tx.findOne("native_builds", { id });
@@ -6094,25 +7053,28 @@ const checkScope = (scope) => {
6094
7053
  });
6095
7054
  if (scope.strategy === "FINGERPRINT" !== (scope.fingerprintHash !== null) || scope.scopeKey !== expected) fail$1("INVALID_SCOPE", "Release catalog scope metadata is inconsistent");
6096
7055
  };
6097
- /** A scope's enabled releases, all of them, under the catalog's guard. */
6098
- const enabledReleases = async (tx, scopeKey) => {
7056
+ /** Every row of a paged read, as release rows. */
7057
+ const drainReleases = async (page) => {
6099
7058
  const rows = [];
6100
7059
  let cursor;
6101
7060
  do {
6102
- const page = await tx.findMany("releases", {
6103
- index: "byScopeEnabled",
6104
- where: {
6105
- scope_key: scopeKey,
6106
- enabled: true
6107
- },
6108
- limit: PAGE$1,
6109
- ...cursor === void 0 ? {} : { cursor }
6110
- });
6111
- rows.push(...page.rows.map(toReleaseRow));
6112
- cursor = page.next;
7061
+ const found = await page(cursor);
7062
+ rows.push(...found.rows.map((row) => toReleaseRow(row)));
7063
+ cursor = found.next;
6113
7064
  } while (cursor !== void 0);
6114
7065
  return rows;
6115
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)));
6116
7078
  /** The scope's newest release id: `byScope` descending, limit 1. */
6117
7079
  const latestReleaseId = async (tx, scopeKey) => {
6118
7080
  const { rows } = await tx.findMany("releases", {
@@ -6123,15 +7085,11 @@ const latestReleaseId = async (tx, scopeKey) => {
6123
7085
  });
6124
7086
  return rows[0]?.id ?? null;
6125
7087
  };
6126
- /** Compiles `enabled` and writes it as the scope's next catalog generation. */
6127
- const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
6128
- const compilation = await compileReleaseCatalog({
6129
- strategy: scope.strategy,
6130
- releases: enabled.map(releaseRowToRelease)
6131
- });
6132
- const generation = (stored.generation ?? 0) + 1;
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;
6133
7091
  if (!Number.isSafeInteger(generation)) fail$1("CATALOG_GENERATION_EXHAUSTED", `Catalog "${scope.scopeKey}" exhausted its generation counter`);
6134
- const catalog = {
7092
+ return {
6135
7093
  scope_key: scope.scopeKey,
6136
7094
  catalog_id: stored.catalog?.catalog_id ?? createUUIDv7(),
6137
7095
  strategy: scope.strategy,
@@ -6146,6 +7104,26 @@ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
6146
7104
  is_tombstone: compilation.payload.releaseDescriptors.length === 0,
6147
7105
  updated_at_ms: updatedAtMs
6148
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);
6149
7127
  const { scope_key: _scopeKey, ...set } = catalog;
6150
7128
  if (stored.row === null) tx.create("release_catalogs", catalog);
6151
7129
  else tx.update("release_catalogs", stored.row, set);
@@ -6234,18 +7212,49 @@ const changeReleases = (db, inputs) => {
6234
7212
  return results;
6235
7213
  });
6236
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
+ };
6237
7249
  /** Recompiles a scope's catalog from its enabled releases inside `tx`; an unchanged catalog is not rewritten. */
6238
7250
  const rebuildScope = async (tx, scope, updatedAtMs) => {
6239
7251
  checkScope(scope);
6240
7252
  const stored = await readCatalog(tx, scope.scopeKey);
6241
7253
  assertHistory(stored, await latestReleaseId(tx, scope.scopeKey) !== null);
6242
7254
  const enabled = await enabledReleases(tx, scope.scopeKey);
6243
- const compilation = await compileReleaseCatalog({
6244
- strategy: scope.strategy,
6245
- releases: enabled.map(releaseRowToRelease)
6246
- });
7255
+ const compilation = await compileScope(scope, enabled);
6247
7256
  const current = stored.catalog;
6248
- if (current !== null && current.strategy === scope.strategy && current.channel_id === scope.channelId && current.channel_key === encodeChannelKey(scope.channelName) && current.platform === scope.platform && current.fingerprint_hash === scope.fingerprintHash && current.catalog_hash === compilation.catalogHash) return {
7257
+ if (current !== null && isCurrent(scope, current, compilation)) return {
6249
7258
  catalog: current,
6250
7259
  current,
6251
7260
  changed: false,
@@ -6349,14 +7358,7 @@ const mutationResult = ({ catalog, release }) => ({
6349
7358
  const catalogScope = async (tx, scopeKey) => {
6350
7359
  const row = await tx.findOne("release_catalogs", { scope_key: scopeKey });
6351
7360
  if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
6352
- return {
6353
- channelId: row.channel_id,
6354
- channelName: decodeChannelKey(row.channel_key),
6355
- fingerprintHash: row.fingerprint_hash,
6356
- platform: row.platform,
6357
- scopeKey: row.scope_key,
6358
- strategy: row.strategy
6359
- };
7361
+ return catalogRowScope(toCatalogRow(row));
6360
7362
  };
6361
7363
  /**
6362
7364
  * Core's typed writes: each runs in one engine transaction rooted at the
@@ -6385,7 +7387,11 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
6385
7387
  for (const { release } of deployments) if (!channels.has(release.channel)) channels.set(release.channel, await ensureChannel(release.channel));
6386
7388
  const platforms = /* @__PURE__ */ new Map();
6387
7389
  for (const deployment of deployments) {
6388
- if (!("bundleId" in deployment) || platforms.has(deployment.bundleId)) continue;
7390
+ if (!("bundleId" in deployment)) {
7391
+ for (const { baseBundleId } of deployment.bundle.patches ?? []) await refuseSandboxPatchBase(db, baseBundleId);
7392
+ continue;
7393
+ }
7394
+ if (platforms.has(deployment.bundleId)) continue;
6389
7395
  const row = await db.findOne("bundles", { id: deployment.bundleId });
6390
7396
  if (row === null) throw new DatabaseBundleNotFoundError(deployment.bundleId);
6391
7397
  if (await isBuiltInBundle(db, deployment.bundleId)) throw new ReleaseManagementError("TARGET_RELEASE_INVALID", `Bundle "${deployment.bundleId}" is a native build's built-in bundle, which no release publishes.`);
@@ -6560,18 +7566,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
6560
7566
  };
6561
7567
  });
6562
7568
  },
6563
- preflightReleaseCatalogRebuild: (scopeKey) => {
6564
- const updatedAtMs = now();
6565
- return dryRun(db, async (tx) => {
6566
- const rebuilt = await rebuildScope(tx, await catalogScope(tx, scopeKey), updatedAtMs);
6567
- return {
6568
- changed: rebuilt.changed,
6569
- currentCatalog: rebuilt.current,
6570
- diagnostics: rebuilt.diagnostics,
6571
- projectedCatalog: rebuilt.catalog
6572
- };
6573
- });
6574
- },
7569
+ preflightReleaseCatalogRebuild: (scopeKey) => preflightRebuild(db, scopeKey, now()),
6575
7570
  ensureChannel,
6576
7571
  deleteChannel: (id) => deleteChannel(db, id),
6577
7572
  updateBundle: (id, update) => db.transaction(async (tx) => {
@@ -6589,7 +7584,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
6589
7584
  if (patches !== void 0) await replaceBundlePatches(tx, current, bundleToPatchRows({
6590
7585
  ...next,
6591
7586
  patches
6592
- }));
7587
+ }), (row) => refuseSandboxPatchBase(tx, row.base_bundle_id));
6593
7588
  }),
6594
7589
  deleteBundles: async (ids) => {
6595
7590
  try {
@@ -6651,6 +7646,7 @@ const createCoreApi = (db, storage, options = {}) => {
6651
7646
  ...reads,
6652
7647
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
6653
7648
  ...createNativeBuildApi(db, options),
7649
+ ...createIosDeviceApi(db, options),
6654
7650
  /** One read, which checks the schema settings first. */
6655
7651
  ready: async () => {
6656
7652
  await reads.listReleaseCatalogs({ limit: 1 });
@@ -6843,6 +7839,10 @@ const answer = async (operation) => {
6843
7839
  error: error.message
6844
7840
  }, status);
6845
7841
  }
7842
+ if (error instanceof ReleaseCatalogCompilationError && error.code === "CATALOG_OVERSIZE") return json$2({
7843
+ code: error.code,
7844
+ error: error.message
7845
+ }, 400);
6846
7846
  if (error instanceof DatabaseBundleNotFoundError) return json$2({
6847
7847
  code: "BUNDLE_NOT_FOUND",
6848
7848
  error: error.message
@@ -6862,18 +7862,22 @@ const LIMITS = {
6862
7862
  defaultValue: 50,
6863
7863
  maxValue: 500
6864
7864
  };
7865
+ /** The most IDs one request names: a lookup's, or a write's. */
7866
+ const MAX_IDS = 100;
6865
7867
  /** `order`, `cursor`, and `limit`: one keyset page. */
6866
- const keyset = (url, maxValue = LIMITS.maxValue) => {
6867
- const order = url.searchParams.get("order") ?? "desc";
7868
+ const keyset = (url, maxValue = LIMITS.maxValue, defaultOrder = "desc") => {
7869
+ const order = url.searchParams.get("order") ?? defaultOrder;
6868
7870
  if (order !== "asc" && order !== "desc") throw new HandlerBadRequestError("order must be 'asc' or 'desc'.");
6869
7871
  const limitParam = url.searchParams.get("limit");
6870
7872
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
6871
7873
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
6872
7874
  const cursor = url.searchParams.get("cursor");
7875
+ const through = url.searchParams.get("through");
6873
7876
  return {
6874
7877
  order,
6875
7878
  limit,
6876
- ...cursor === null ? {} : { after: cursor }
7879
+ ...cursor === null ? {} : { after: cursor },
7880
+ ...through === null ? {} : { through }
6877
7881
  };
6878
7882
  };
6879
7883
  /** A page and the cursor of the next one, when the page is full. */
@@ -6971,7 +7975,8 @@ const nativeBuildScopeOf = (url) => {
6971
7975
  const fingerprintHash = params.get("fingerprintHash");
6972
7976
  const appVersion = params.get("appVersion");
6973
7977
  if (platform === void 0 || !isText$2(channel) || fingerprintHash === null === (appVersion === null) || fingerprintHash === "" || appVersion === "") throw new HandlerBadRequestError("A native build lookup needs platform, channel, and fingerprintHash or appVersion.");
6974
- return fingerprintHash !== null ? {
7978
+ const sandbox = sandboxScopeOf(params);
7979
+ const scope = fingerprintHash !== null ? {
6975
7980
  platform,
6976
7981
  channel,
6977
7982
  fingerprintHash,
@@ -6982,17 +7987,49 @@ const nativeBuildScopeOf = (url) => {
6982
7987
  fingerprintHash: null,
6983
7988
  appVersion
6984
7989
  };
7990
+ return sandbox === null ? scope : {
7991
+ ...scope,
7992
+ sandbox
7993
+ };
7994
+ };
7995
+ /** The query parameters a sandbox lookup names, all four or none. */
7996
+ const SANDBOX_SCOPE_PARAMS = [
7997
+ "sandboxAppId",
7998
+ "sandboxUrlScheme",
7999
+ "artifactKind",
8000
+ "distribution"
8001
+ ];
8002
+ /**
8003
+ * A lookup's sandbox scope: null without one, and a bad request for one
8004
+ * named in part. Core checks each value.
8005
+ */
8006
+ const sandboxScopeOf = (params) => {
8007
+ const [appId, urlScheme, artifactKind, distribution] = SANDBOX_SCOPE_PARAMS.map((name) => params.get(name));
8008
+ const named = [
8009
+ appId,
8010
+ urlScheme,
8011
+ artifactKind,
8012
+ distribution
8013
+ ].filter((value) => value !== null).length;
8014
+ if (named === 0) return null;
8015
+ if (named !== SANDBOX_SCOPE_PARAMS.length) throw new HandlerBadRequestError(`A sandbox build lookup needs ${SANDBOX_SCOPE_PARAMS.join(", ")}.`);
8016
+ return {
8017
+ appId,
8018
+ urlScheme,
8019
+ artifactKind,
8020
+ distribution
8021
+ };
6985
8022
  };
6986
8023
  /** A native build or scope core refuses: a bad request. */
6987
8024
  const refusingInvalid = async (operation) => {
6988
8025
  try {
6989
8026
  return await operation();
6990
8027
  } catch (error) {
6991
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
8028
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
6992
8029
  throw error;
6993
8030
  }
6994
8031
  };
6995
- const isNativeBuildRegistration = (value) => isRecord$5(value) && isText$2(value.id) && isText$2(value.minBundleId) && typeof value.platform === "string" && isPlatform(value.platform) && isText$2(value.channel) && isTextOrNull$1(value.fingerprintHash) && isTextOrNull$1(value.appVersion) && value.fingerprintHash === null !== (value.appVersion === null) && isTextOrNull$1(value.gitCommitHash) && isTextOrNull$1(value.buildKey) && (value.buildNumber === void 0 || isTextOrNull$1(value.buildNumber)) && isRecord$5(value.artifact) && typeof value.artifact.kind === "string" && NATIVE_BUILD_ARTIFACT_KINDS.has(value.artifact.kind) && isText$2(value.artifact.storageUri) && Number.isSafeInteger(value.artifact.byteSize) && value.artifact.byteSize >= 0 && isRecord$5(value.embeddedBundle) && isText$2(value.embeddedBundle.manifestStorageUri) && isText$2(value.embeddedBundle.manifestFileHash) && isText$2(value.embeddedBundle.assetBaseStorageUri) && (value.embeddedBundle.metadata === void 0 || isRecord$5(value.embeddedBundle.metadata));
8032
+ const isNativeBuildRegistration = (value) => isRecord$5(value) && isText$2(value.id) && isText$2(value.minBundleId) && typeof value.platform === "string" && isPlatform(value.platform) && isText$2(value.channel) && isTextOrNull$1(value.fingerprintHash) && isTextOrNull$1(value.appVersion) && value.fingerprintHash === null !== (value.appVersion === null) && isTextOrNull$1(value.gitCommitHash) && isTextOrNull$1(value.buildKey) && (value.buildNumber === void 0 || isTextOrNull$1(value.buildNumber)) && (value.isSandbox === void 0 || typeof value.isSandbox === "boolean") && (value.sandboxUrlScheme === void 0 || isTextOrNull$1(value.sandboxUrlScheme)) && (value.sandboxAppId === void 0 || isTextOrNull$1(value.sandboxAppId)) && (value.exportMethod === void 0 || isTextOrNull$1(value.exportMethod)) && (value.nativeAppVersion === void 0 || isTextOrNull$1(value.nativeAppVersion)) && isRecord$5(value.artifact) && typeof value.artifact.kind === "string" && NATIVE_BUILD_ARTIFACT_KINDS.has(value.artifact.kind) && isText$2(value.artifact.storageUri) && Number.isSafeInteger(value.artifact.byteSize) && value.artifact.byteSize >= 0 && isRecord$5(value.embeddedBundle) && isText$2(value.embeddedBundle.manifestStorageUri) && isText$2(value.embeddedBundle.manifestFileHash) && isText$2(value.embeddedBundle.assetBaseStorageUri) && (value.embeddedBundle.metadata === void 0 || isRecord$5(value.embeddedBundle.metadata));
6996
8033
  const scopeKeyOf = (params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "";
6997
8034
  /** Every admin route's handler, by the name `ADMIN_ROUTES` mounts it under. */
6998
8035
  const createAdminRouteHandlers = () => ({
@@ -7025,12 +8062,40 @@ const createAdminRouteHandlers = () => ({
7025
8062
  const rows = await core.listReleaseCatalogs(input);
7026
8063
  return page(rows, input, (row) => row.scope_key);
7027
8064
  }),
7028
- /** 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
+ */
7029
8080
  getChannels: onCore(async (core, request) => {
7030
- const name = new URL(request.url).searchParams.get("name");
7031
- if (name === null) return json$2({ data: await core.listChannels() });
7032
- const channel = await core.findChannelByName(name);
7033
- return channel === null ? notFound() : json$2({ data: channel });
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() });
7034
8099
  }),
7035
8100
  /** The channel named in the body, created when missing. */
7036
8101
  createChannel: onCore(async (core, request) => {
@@ -7074,13 +8139,14 @@ const createAdminRouteHandlers = () => ({
7074
8139
  rebuildReleaseCatalog: onCore(async (core, _request, params) => json$2({ data: await core.rebuildReleaseCatalog(scopeKeyOf(params)) })),
7075
8140
  updateBundle: onCore(async (core, request, params) => {
7076
8141
  const bundleId = requireRouteParam(params, "id");
7077
- await core.updateBundle(bundleId, bundleUpdateOf(await request.json(), bundleId));
8142
+ const update = bundleUpdateOf(await request.json(), bundleId);
8143
+ await refusingInvalid(() => core.updateBundle(bundleId, update));
7078
8144
  return noContent();
7079
8145
  }),
7080
8146
  countBundles: onCore(async (core, request) => json$2({ data: await core.countBundles(platformOf(new URL(request.url))) })),
7081
8147
  countBundleChildren: onCore(async (core, request) => {
7082
8148
  const ids = (new URL(request.url).searchParams.get("ids") ?? "").split(",").filter((id) => id.length > 0);
7083
- if (ids.length === 0 || ids.length > 100) throw new HandlerBadRequestError("Bundle child counts take ids=<bundle id>,... with 1 to 100 ids.");
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.`);
7084
8150
  return json$2({ data: await core.countBundleChildren(ids) });
7085
8151
  }),
7086
8152
  listBundleChildren: onCore(async (core, request, params) => {
@@ -7098,7 +8164,7 @@ const createAdminRouteHandlers = () => ({
7098
8164
  deployReleases: onCore(async (core, request) => {
7099
8165
  const { deployments } = await body(request);
7100
8166
  if (!Array.isArray(deployments) || deployments.length === 0 || !deployments.every(isDeployment)) throw new HandlerBadRequestError("Deploy needs deployments, each a bundle and its release policy.");
7101
- return json$2({ data: await core.deploy(deployments) }, 201);
8167
+ return json$2({ data: await refusingInvalid(() => core.deploy(deployments)) }, 201);
7102
8168
  }),
7103
8169
  promoteRelease: onCore(async (core, request, params) => {
7104
8170
  const input = await body(request);
@@ -7121,9 +8187,22 @@ const createAdminRouteHandlers = () => ({
7121
8187
  const url = new URL(request.url);
7122
8188
  const scope = nativeBuildScopeOf(url);
7123
8189
  const buildKey = url.searchParams.get("buildKey");
7124
- return json$2({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
8190
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
8191
+ const kind = url.searchParams.get("kind");
8192
+ const options = {
8193
+ ...buildKey === null ? {} : { buildKey },
8194
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
8195
+ ...builtInOlderThan === null ? {} : { builtInOlderThan },
8196
+ ...kind === null ? {} : { artifactKind: kind }
8197
+ };
8198
+ return json$2({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
8199
+ }),
8200
+ findNativeBuildSibling: onCore(async (core, _request, params) => {
8201
+ const build = await core.getNativeBuild(requireRouteParam(params, "id"));
8202
+ return json$2({ data: build === null ? null : await core.findNativeBuildSibling(build) });
7125
8203
  }),
7126
8204
  getNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
8205
+ findNativeBuildByBuiltInBundle: onCore(async (core, _request, params) => json$2({ data: await core.findNativeBuildByBuiltInBundle(requireRouteParam(params, "bundleId")) })),
7127
8206
  listNativeBuilds: onCore(async (core, request) => {
7128
8207
  const url = new URL(request.url);
7129
8208
  const input = keyset(url);
@@ -7135,14 +8214,97 @@ const createAdminRouteHandlers = () => ({
7135
8214
  }),
7136
8215
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
7137
8216
  const input = await body(request);
7138
- if (!isRecord$5(input) || input.destination !== "testflight" && input.destination !== "play-internal" || !isText$2(input.version)) throw new HandlerBadRequestError("A native build submission needs destination (testflight or play-internal) and version.");
8217
+ if (!isRecord$5(input) || !Object.values(NATIVE_BUILD_SUBMISSION_DESTINATIONS).flat().includes(input.destination) || !isText$2(input.version)) throw new HandlerBadRequestError("A native build submission needs a valid store destination and version.");
7139
8218
  const submission = {
7140
8219
  destination: input.destination,
7141
8220
  version: input.version
7142
8221
  };
7143
8222
  return json$2({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
7144
8223
  }),
8224
+ markNativeBuild: onCore(async (core, request, params) => {
8225
+ const input = await body(request);
8226
+ if (!isRecord$5(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
8227
+ const mark = { storeBuild: input.storeBuild };
8228
+ return json$2({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
8229
+ }),
7145
8230
  deleteNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
8231
+ listIosDevices: onCore(async (core, request) => {
8232
+ const url = new URL(request.url);
8233
+ const input = keyset(url);
8234
+ const status = url.searchParams.get("status");
8235
+ return page(await refusingInvalid(() => core.listIosDevices({
8236
+ ...input,
8237
+ ...status === null ? {} : { status }
8238
+ })), input, ({ id }) => id);
8239
+ }),
8240
+ findIosDevice: onCore(async (core, _request, params) => json$2({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
8241
+ requestIosDevice: onCore(async (core, request) => {
8242
+ const input = await body(request);
8243
+ if (!isText$2(input.udid) || !isText$2(input.name) || !isTextOrNull$1(input.requestedBy)) throw new HandlerBadRequestError("An iOS device request needs udid, name, and requestedBy, an email or null.");
8244
+ const device = {
8245
+ udid: input.udid,
8246
+ name: input.name,
8247
+ requestedBy: input.requestedBy
8248
+ };
8249
+ return json$2({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
8250
+ }),
8251
+ approveIosDevice: onCore(async (core, request, params) => {
8252
+ const input = await body(request);
8253
+ if (!isTextOrNull$1(input.approvedBy) || input.name !== void 0 && !isText$2(input.name)) throw new HandlerBadRequestError("An iOS device approval needs approvedBy, an email or null, and an optional name.");
8254
+ const approval = {
8255
+ approvedBy: input.approvedBy,
8256
+ ...input.name === void 0 ? {} : { name: input.name }
8257
+ };
8258
+ return json$2({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
8259
+ }),
8260
+ renameIosDevice: onCore(async (core, request, params) => {
8261
+ const input = await body(request);
8262
+ if (!isText$2(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
8263
+ const name = input.name;
8264
+ return json$2({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
8265
+ }),
8266
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
8267
+ const input = await body(request);
8268
+ const seen = input.seen;
8269
+ if (!isRecord$5(seen) || typeof seen.status !== "string" || !(seen.approvedAtMs === null || Number.isSafeInteger(seen.approvedAtMs)) || !isText$2(input.issuerId) || typeof input.outcome !== "string" || input.reason !== void 0 && typeof input.reason !== "string") throw new HandlerBadRequestError("An iOS device outcome needs seen { status, approvedAtMs }, issuerId, outcome, and an optional reason.");
8270
+ const outcome = {
8271
+ id: requireRouteParam(params, "id"),
8272
+ seen: {
8273
+ status: seen.status,
8274
+ approvedAtMs: seen.approvedAtMs
8275
+ },
8276
+ issuerId: input.issuerId,
8277
+ outcome: input.outcome,
8278
+ ...input.reason === void 0 ? {} : { reason: input.reason }
8279
+ };
8280
+ return json$2({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
8281
+ }),
8282
+ claimIosDeviceAccount: onCore(async (core, request) => {
8283
+ const { issuerId } = await body(request);
8284
+ if (!isText$2(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
8285
+ return json$2({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
8286
+ }),
8287
+ findIosDeviceAccount: onCore(async (core) => json$2({ data: await core.findIosDeviceAccount() })),
8288
+ markIosDevicesInBuild: onCore(async (core, request) => {
8289
+ const { buildId, ids } = await body(request);
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.`);
8292
+ await core.markIosDevicesInBuild({
8293
+ buildId,
8294
+ ids
8295
+ });
8296
+ return noContent();
8297
+ }),
8298
+ deleteIosDevice: onCore(async (core, request, params) => {
8299
+ const url = new URL(request.url);
8300
+ const status = url.searchParams.get("status");
8301
+ const requestedBy = url.searchParams.get("requestedBy");
8302
+ const only = {
8303
+ ...status === null ? {} : { status },
8304
+ ...requestedBy === null ? {} : { requestedBy }
8305
+ };
8306
+ return json$2({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
8307
+ }),
7146
8308
  deleteBundles: onCore(async (core, request) => {
7147
8309
  const { ids } = await body(request);
7148
8310
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -7197,6 +8359,11 @@ const ADMIN_ROUTES = [
7197
8359
  path: "/release-catalogs",
7198
8360
  handler: "listReleaseCatalogs"
7199
8361
  },
8362
+ {
8363
+ method: "GET",
8364
+ path: "/release-scopes",
8365
+ handler: "listReleaseScopeKeys"
8366
+ },
7200
8367
  {
7201
8368
  method: "POST",
7202
8369
  path: "/release-catalogs/:scopeKey/rebuild",
@@ -7272,6 +8439,16 @@ const ADMIN_ROUTES = [
7272
8439
  path: "/native-builds/latest",
7273
8440
  handler: "findNativeBuild"
7274
8441
  },
8442
+ {
8443
+ method: "GET",
8444
+ path: "/native-builds/built-in/:bundleId",
8445
+ handler: "findNativeBuildByBuiltInBundle"
8446
+ },
8447
+ {
8448
+ method: "GET",
8449
+ path: "/native-builds/:id/sibling",
8450
+ handler: "findNativeBuildSibling"
8451
+ },
7275
8452
  {
7276
8453
  method: "GET",
7277
8454
  path: "/native-builds/:id",
@@ -7287,10 +8464,65 @@ const ADMIN_ROUTES = [
7287
8464
  path: "/native-builds/:id/submission",
7288
8465
  handler: "recordNativeBuildSubmission"
7289
8466
  },
8467
+ {
8468
+ method: "POST",
8469
+ path: "/native-builds/:id/store-build",
8470
+ handler: "markNativeBuild"
8471
+ },
7290
8472
  {
7291
8473
  method: "DELETE",
7292
8474
  path: "/native-builds/:id",
7293
8475
  handler: "deleteNativeBuild"
8476
+ },
8477
+ {
8478
+ method: "GET",
8479
+ path: "/ios-devices",
8480
+ handler: "listIosDevices"
8481
+ },
8482
+ {
8483
+ method: "POST",
8484
+ path: "/ios-devices",
8485
+ handler: "requestIosDevice"
8486
+ },
8487
+ {
8488
+ method: "GET",
8489
+ path: "/ios-devices/udid/:udid",
8490
+ handler: "findIosDevice"
8491
+ },
8492
+ {
8493
+ method: "POST",
8494
+ path: "/ios-devices/in-build",
8495
+ handler: "markIosDevicesInBuild"
8496
+ },
8497
+ {
8498
+ method: "GET",
8499
+ path: "/ios-devices/account",
8500
+ handler: "findIosDeviceAccount"
8501
+ },
8502
+ {
8503
+ method: "POST",
8504
+ path: "/ios-devices/account",
8505
+ handler: "claimIosDeviceAccount"
8506
+ },
8507
+ {
8508
+ method: "POST",
8509
+ path: "/ios-devices/:id/approval",
8510
+ handler: "approveIosDevice"
8511
+ },
8512
+ {
8513
+ method: "POST",
8514
+ path: "/ios-devices/:id/outcome",
8515
+ handler: "recordIosDeviceOutcome"
8516
+ },
8517
+ {
8518
+ method: "PATCH",
8519
+ path: "/ios-devices/:id",
8520
+ handler: "renameIosDevice"
8521
+ },
8522
+ {
8523
+ method: "DELETE",
8524
+ path: "/ios-devices/:id",
8525
+ handler: "deleteIosDevice"
7294
8526
  }
7295
8527
  ];
7296
8528
  //#endregion
@@ -7313,9 +8545,9 @@ const CATALOG_CACHE_CONTROL = "public, max-age=0, s-maxage=5";
7313
8545
  * background. `stale-if-error=0` keeps origin errors visible: without it,
7314
8546
  * Cloudflare serves a stale copy on error indefinitely.
7315
8547
  *
7316
- * A device can see a catalog up to 15 seconds after a deploy or a Roll back
7317
- * replaced it: the origin's 5-second catalog memo, then 5 seconds fresh and
7318
- * 5 stale at the CDN. A revoked API key can read a cached catalog up to
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
7319
8551
  * 10 seconds. Devices and caches that don't read the header keep
7320
8552
  * `Cache-Control`.
7321
8553
  */
@@ -7394,38 +8626,53 @@ const catalogResponse = async (catalog, request) => {
7394
8626
  };
7395
8627
  const createReleaseCatalogRouteHandlers = () => {
7396
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
+ };
7397
8642
  const inFlight = /* @__PURE__ */ new Map();
7398
- const loadCatalog = async (key, load) => {
7399
- const cached = cache.get(key);
8643
+ const loadRow = async (scopeKey, load) => {
8644
+ const cached = cache.get(scopeKey);
7400
8645
  if (cached !== void 0 && cached.expiresAt > Date.now()) {
7401
- cache.delete(key);
7402
- cache.set(key, cached);
7403
- return cached.catalog;
8646
+ cache.delete(scopeKey);
8647
+ cache.set(scopeKey, cached);
8648
+ return cached.row;
7404
8649
  }
7405
- if (cached !== void 0) cache.delete(key);
7406
- const pending = inFlight.get(key);
8650
+ if (cached !== void 0) cache.delete(scopeKey);
8651
+ const pending = inFlight.get(scopeKey);
7407
8652
  if (pending !== void 0) return pending;
7408
- const next = load().then((catalog) => {
7409
- if (catalog !== null) {
7410
- cache.set(key, {
7411
- catalog,
7412
- expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
7413
- });
7414
- while (cache.size > ORIGIN_CACHE_MAX_ENTRIES) {
7415
- const oldestKey = cache.keys().next().value;
7416
- if (oldestKey === void 0) break;
7417
- cache.delete(oldestKey);
7418
- }
7419
- }
7420
- return catalog;
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;
7421
8660
  });
7422
- inFlight.set(key, next);
8661
+ inFlight.set(scopeKey, next);
7423
8662
  try {
7424
8663
  return await next;
7425
8664
  } finally {
7426
- inFlight.delete(key);
8665
+ inFlight.delete(scopeKey);
7427
8666
  }
7428
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
+ };
7429
8676
  return {
7430
8677
  appVersionReleaseCatalog: async (params, request, { core }) => {
7431
8678
  const rawAppVersion = requireRouteParam(params, "appVersion");
@@ -7439,7 +8686,7 @@ const createReleaseCatalogRouteHandlers = () => {
7439
8686
  };
7440
8687
  const invalid = invalidScope(input);
7441
8688
  if (invalid) return invalid;
7442
- return catalogResponse(await loadCatalog(`app-version:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
8689
+ return catalogResponse(await loadCatalog(core, input), request);
7443
8690
  },
7444
8691
  fingerprintReleaseCatalog: async (params, request, { core }) => {
7445
8692
  const input = {
@@ -7450,7 +8697,7 @@ const createReleaseCatalogRouteHandlers = () => {
7450
8697
  };
7451
8698
  const invalid = invalidScope(input);
7452
8699
  if (invalid) return invalid;
7453
- return catalogResponse(await loadCatalog(`fingerprint:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
8700
+ return catalogResponse(await loadCatalog(core, input), request);
7454
8701
  },
7455
8702
  artifactV2: async (params, _request, { core }) => {
7456
8703
  const info = await core.getArtifactInfo(requireRouteParam(params, "targetBundleId"), requireRouteParam(params, "currentBundleId"), 2);
@@ -10733,13 +11980,80 @@ const breakdownOf = (rows) => {
10733
11980
  });
10734
11981
  };
10735
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
+ /**
10736
12049
  * A release's or a channel's update failures. Since a release's first
10737
12050
  * report: its lifetime counters and failed installations. Over a time range
10738
12051
  * of at most 30 days: failures, failed checks, and the breakdown by stage,
10739
12052
  * reason, and detail, all summed from the breakdown's hourly rows; downloads
10740
12053
  * from the counters; failed installations from their sketches. A release reads hourly rows, a
10741
12054
  * channel daily rows past 48 hours like its activity; the breakdown's rows
10742
- * 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.
10743
12057
  */
10744
12058
  const getUpdateFailures = async (db, input, now, retention) => {
10745
12059
  const { platform, channel, releaseId, timeRange } = input;
@@ -10801,7 +12115,7 @@ const getUpdateFailures = async (db, input, now, retention) => {
10801
12115
  days,
10802
12116
  kept.hour
10803
12117
  ];
10804
- const [counters, failures, checks, active, rows] = await Promise.all([
12118
+ const [counters, failures, checks, active, { rows, cappedHours }] = await Promise.all([
10805
12119
  counterRows(db, parts, ...window),
10806
12120
  sketchRows(db, failure, ...window),
10807
12121
  days ? sketchRows(db, {
@@ -10809,25 +12123,17 @@ const getUpdateFailures = async (db, input, now, retention) => {
10809
12123
  scopeKind: "check"
10810
12124
  }, ...window) : [],
10811
12125
  days ? sketchRows(db, usageParts(channel, platform), ...window) : [],
10812
- drain((page) => db.findAggregates("insights_failures", {
10813
- index: "byScope",
10814
- where: {
10815
- platform,
10816
- channel
10817
- },
10818
- range: {
10819
- gte: timeRange.start,
10820
- lt: timeRange.end
10821
- },
10822
- limit: PAGE,
10823
- ...page
10824
- }))
12126
+ failureRowsByHour(db, platform, channel, timeRange)
10825
12127
  ]);
10826
12128
  const total = (field) => counters.reduce((sum, row) => sum + row[field], 0);
10827
12129
  const scoped = rows.filter((row) => FAILURE_STAGES.has(row.stage) && (releaseId === void 0 || row.release_id === releaseId));
10828
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);
10829
12132
  return {
10830
- coverage: coverageOf(timeRange.start, kept.hour),
12133
+ coverage: cappedHours.length === 0 ? coverage : {
12134
+ kind: "partial",
12135
+ sinceMs: coverage.sinceMs
12136
+ },
10831
12137
  measuredAtMs: at,
10832
12138
  failedUpdates: failuresAt((stage) => stage !== "check"),
10833
12139
  failedInstallations: failed(failures),
@@ -10839,7 +12145,8 @@ const getUpdateFailures = async (db, input, now, retention) => {
10839
12145
  failedInstallations: failed(checks),
10840
12146
  activeInstallations: countDistinct(mergeDistinct(active.map((row) => row.activity_users)))
10841
12147
  } } : {},
10842
- breakdown: breakdownOf(scoped)
12148
+ breakdown: breakdownOf(scoped),
12149
+ ...cappedHours.length === 0 ? {} : { cappedHours }
10843
12150
  };
10844
12151
  };
10845
12152
  //#endregion
@@ -12111,14 +13418,67 @@ const createFirestoreStore = ({ firestore, collection, nativePageSize }) => {
12111
13418
  };
12112
13419
  };
12113
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
12114
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
+ };
12115
13473
  const adapterOf = ({ databaseId, collection = FIREBASE_V1_COLLECTION, aggregateBatching: _, ...appOptions }) => {
12116
13474
  const app = (0, firebase_admin_app.getApps)().length ? (0, firebase_admin_app.getApp)() : (0, firebase_admin_app.initializeApp)(appOptions);
12117
13475
  const firestore = databaseId ? (0, firebase_admin_firestore.getFirestore)(app, databaseId) : (0, firebase_admin_firestore.getFirestore)(app);
12118
- return createKvAdapter({ store: createFirestoreStore({
13476
+ const store = createFirestoreStore({
12119
13477
  firestore,
12120
13478
  collection
12121
- }) });
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) });
12122
13482
  };
12123
13483
  /**
12124
13484
  * The resource this database reaches, without credentials, under the key
@@ -12139,11 +13499,14 @@ const firebaseDatabase = (config) => ({
12139
13499
  //#region src/firebaseStorage.ts
12140
13500
  /** Signed URLs kept per adapter, enough for a few Bundles' assets. */
12141
13501
  const MAX_CACHED_SIGNED_URLS = 1e4;
13502
+ /** Objects deleted at once: Cloud Storage deletes one object a request. */
13503
+ const DELETE_CONCURRENCY = 16;
12142
13504
  const firebaseStorage = (config) => {
12143
13505
  const app = (0, firebase_admin_app.getApps)().length ? (0, firebase_admin_app.getApp)() : (0, firebase_admin_app.initializeApp)(config);
12144
13506
  let opened;
12145
13507
  const bucket = () => opened ??= (0, firebase_admin_storage.getStorage)(app).bucket(config.storageBucket);
12146
13508
  const getStorageKey = createStorageKeyBuilder(config.basePath);
13509
+ const basePrefix = getStorageKey() ? `${getStorageKey()}/` : "";
12147
13510
  /**
12148
13511
  * Signed URLs by object. Without a private key, as in Cloud Functions, each
12149
13512
  * signature is an IAM signBlob request, and an update check returns a URL
@@ -12232,6 +13595,39 @@ const firebaseStorage = (config) => {
12232
13595
  const { key } = parseAndValidate(storageUri);
12233
13596
  await bucket().file(key).delete({ ignoreNotFound: true });
12234
13597
  return { deleted: true };
13598
+ },
13599
+ async listObjects(prefix) {
13600
+ const folder = getStorageKey(prefix ?? "");
13601
+ const [files] = await bucket().getFiles({
13602
+ autoPaginate: true,
13603
+ prefix: folder ? `${folder}/` : ""
13604
+ });
13605
+ const objects = [];
13606
+ for (const file of files) {
13607
+ if (!file.name.startsWith(basePrefix)) continue;
13608
+ let storageUri;
13609
+ try {
13610
+ storageUri = createStorageUri({
13611
+ bucket: config.storageBucket,
13612
+ key: file.name,
13613
+ protocol: "gs"
13614
+ });
13615
+ } catch {
13616
+ continue;
13617
+ }
13618
+ const { size, updated } = file.metadata;
13619
+ objects.push({
13620
+ key: file.name.slice(basePrefix.length),
13621
+ ...updated ? { lastModifiedAt: new Date(updated) } : {},
13622
+ size: Number(size ?? 0),
13623
+ storageUri
13624
+ });
13625
+ }
13626
+ return objects;
13627
+ },
13628
+ async deleteObjects(relativeKeys) {
13629
+ const keys = relativeKeys.map((key) => getStorageKey(key));
13630
+ for (let offset = 0; offset < keys.length; offset += DELETE_CONCURRENCY) await Promise.all(keys.slice(offset, offset + DELETE_CONCURRENCY).map((key) => bucket().file(key).delete({ ignoreNotFound: true })));
12235
13631
  }
12236
13632
  });
12237
13633
  };
@@ -12242,9 +13638,10 @@ const adminOptions = ((0, firebase_admin_app.getApps)()[0] ?? (0, firebase_admin
12242
13638
  const storageBucket = adminOptions.storageBucket;
12243
13639
  const cdnUrl = process.env.HOT_UPDATER_CDN_URL;
12244
13640
  if (!storageBucket) throw new Error("Firebase runtime requires storageBucket to read bundle manifests.");
13641
+ const { credential: _runtimeCredential, ...databaseOptions } = adminOptions;
12245
13642
  const hotUpdater = createHotUpdater({
12246
13643
  database: firebaseDatabase({
12247
- ...adminOptions,
13644
+ ...databaseOptions,
12248
13645
  databaseId: HotUpdater.FIRESTORE_DATABASE_ID
12249
13646
  }),
12250
13647
  plugins: [