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

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.
@@ -603,7 +603,8 @@ const releaseRowToRelease = (row) => ({
603
603
  operation: row.operation,
604
604
  sourceReleaseId: row.source_release_id,
605
605
  createdAtMs: row.created_at_ms,
606
- updatedAtMs: row.updated_at_ms
606
+ updatedAtMs: row.updated_at_ms,
607
+ label: row.label ?? null
607
608
  });
608
609
  const bundleToRow = (bundle) => {
609
610
  const metadata = bundleMetadataToRow(bundle.metadata);
@@ -1112,7 +1113,8 @@ function rangeToIntervals(range) {
1112
1113
  throw new ReleaseCatalogCompilationError("INVALID_TARGET_RANGE", `Invalid target app-version range: ${range}`);
1113
1114
  }
1114
1115
  }
1115
- function releaseDescriptor(release) {
1116
+ /** A release's descriptor; its label only when it has one and `labels`. */
1117
+ function releaseDescriptor(release, labels) {
1116
1118
  return {
1117
1119
  releaseId: release.id,
1118
1120
  kind: release.kind,
@@ -1120,7 +1122,8 @@ function releaseDescriptor(release) {
1120
1122
  rolloutCohortCount: release.rolloutCohortCount,
1121
1123
  targetCohorts: [...new Set(release.targetCohorts)].sort(),
1122
1124
  shouldForceUpdate: release.shouldForceUpdate,
1123
- message: release.message
1125
+ message: release.message,
1126
+ ...labels && typeof release.label === "number" ? { label: release.label } : {}
1124
1127
  };
1125
1128
  }
1126
1129
  function validateReleases(releases, strategy) {
@@ -1333,12 +1336,21 @@ async function compileReleaseCatalog(input) {
1333
1336
  const targetCohorts = new Set(releases.flatMap((release) => release.targetCohorts));
1334
1337
  if (targetCohorts.size > 512) throw new ReleaseCatalogCompilationError("DISTINCT_TARGET_COHORT_LIMIT", `Scope exceeds 512 distinct target cohorts`);
1335
1338
  const { envelope, retainedReleases } = input.strategy === "APP_VERSION" ? compileAppVersion(releases) : compileFingerprint(releases);
1336
- const payload = {
1337
- ...envelope,
1338
- releaseDescriptors: retainedReleases.map(releaseDescriptor)
1339
+ const compile = (labels) => {
1340
+ const payload = {
1341
+ ...envelope,
1342
+ releaseDescriptors: retainedReleases.map((release) => releaseDescriptor(release, labels))
1343
+ };
1344
+ const canonicalPayload = canonicalStringify(payload);
1345
+ return {
1346
+ payload,
1347
+ canonicalPayload,
1348
+ byteSize: new TextEncoder().encode(canonicalPayload).byteLength
1349
+ };
1339
1350
  };
1340
- const canonicalPayload = canonicalStringify(payload);
1341
- const byteSize = new TextEncoder().encode(canonicalPayload).byteLength;
1351
+ let compiled = compile(true);
1352
+ if (compiled.byteSize > 262144 && retainedReleases.some((release) => typeof release.label === "number")) compiled = compile(false);
1353
+ const { payload, canonicalPayload, byteSize } = compiled;
1342
1354
  if (byteSize > 262144) throw new ReleaseCatalogCompilationError("CATALOG_OVERSIZE", `Compiled Release catalog is ${byteSize} bytes; maximum is ${MAX_COMPILED_CATALOG_BYTES}`);
1343
1355
  return {
1344
1356
  byteSize,
@@ -2046,45 +2058,6 @@ const METER = Symbol.for("@hot-updater/plugin-core/read-meter");
2046
2058
  /** The meter `meterReads` gave `database`, if it did. */
2047
2059
  const readMeterOf = (database) => typeof database === "object" && database !== null ? database[METER] : void 0;
2048
2060
  //#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
2061
  //#region ../plugin-core/dist/engine/core/schema.mjs
2089
2062
  /** A channel's id is `channel:` and its name's channel key, so ids share channel_key's bound. */
2090
2063
  const CHANNEL_ID = {
@@ -2100,9 +2073,13 @@ const CHANNEL_ID = {
2100
2073
  * applies it to managed databases an earlier release created. The official
2101
2074
  * plugins' `schemaVersion`s follow the same rule. A bump only adds tables:
2102
2075
  * 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.
2076
+ * version, and none of them changes an existing table's columns, so changing
2077
+ * one needs a migration step of its own first. An index added to an existing
2078
+ * table is listed in `LATE_INDEXES`, and a column in `LATE_COLUMNS`. The schema fence answers 503 on
2079
+ * a database whose row differs, until it runs. Before a version is released,
2080
+ * its tables change in place in its own migration, and a database one of its
2081
+ * prereleases migrated takes the same change by hand: the fence compares this
2082
+ * row, not columns, so nothing reports it.
2106
2083
  */
2107
2084
  const HOT_UPDATER_SCHEMA_VERSION = "1.2.0";
2108
2085
  const bundles = defineTable({
@@ -2251,7 +2228,11 @@ const releases = defineTable({
2251
2228
  }
2252
2229
  },
2253
2230
  created_at_ms: { type: "integer" },
2254
- updated_at_ms: { type: "integer" }
2231
+ updated_at_ms: { type: "integer" },
2232
+ label: {
2233
+ type: "integer",
2234
+ required: false
2235
+ }
2255
2236
  }, {
2256
2237
  key: ["id"],
2257
2238
  indexes: {
@@ -2284,9 +2265,72 @@ const releases = defineTable({
2284
2265
  all: {
2285
2266
  eq: [],
2286
2267
  sort: ["id"]
2268
+ },
2269
+ scopes: {
2270
+ eq: [],
2271
+ sort: ["scope_key"]
2272
+ },
2273
+ byLabel: {
2274
+ eq: [
2275
+ "channel_id",
2276
+ "platform",
2277
+ "label"
2278
+ ],
2279
+ sort: [],
2280
+ unique: true
2287
2281
  }
2288
2282
  }
2289
2283
  });
2284
+ /**
2285
+ * Indexes declared on a table that a released schema's servers write: a
2286
+ * store that keeps index items of its own (`migrations.fillIndex`) lacks
2287
+ * them for rows written before, and for rows such a server still writes
2288
+ * after the migration, since its schema fence keeps a check that passed.
2289
+ * Each migration writes the missing items, and `db migrate` on a database
2290
+ * whose settings match looks for them. `releases.scopes` arrived in 1.2.0;
2291
+ * 1.1.x servers write releases without it.
2292
+ */
2293
+ const LATE_INDEXES = [{
2294
+ table: "releases",
2295
+ index: "scopes"
2296
+ }];
2297
+ /**
2298
+ * Columns added to a table that a released schema created: a migrator whose
2299
+ * store has columns adds each one missing from an existing table, with
2300
+ * `ALTER TABLE … ADD COLUMN`, before it creates the table's indexes, and
2301
+ * `db migrate` on a database whose settings match still looks for them,
2302
+ * since a database a prerelease migrated records the same settings. Each
2303
+ * is optional, so rows written before it, and rows a server of the earlier
2304
+ * release still writes, read as null. `releases.label` arrived in 1.2.0.
2305
+ */
2306
+ const LATE_COLUMNS = [{
2307
+ table: "releases",
2308
+ column: "label"
2309
+ }];
2310
+ /**
2311
+ * One counter per sequence: `releases/<platform>/<channel ID>` holds the
2312
+ * last label that channel and platform's releases took. A deploy or a
2313
+ * promote reads it and writes the next value in the transaction that writes
2314
+ * the release, so two writers never take one label. `is_filled` is true once
2315
+ * every release of the sequence written before labels has one, in ID order;
2316
+ * until then a writer fills them first. Deleting a channel deletes its
2317
+ * counters, so a channel created again with the name starts at 1.
2318
+ */
2319
+ const labelSequences = defineTable({
2320
+ id: {
2321
+ type: "string",
2322
+ maxLength: 1440,
2323
+ ascii: true
2324
+ },
2325
+ last_label: { type: "integer" },
2326
+ is_filled: { type: "boolean" }
2327
+ }, {
2328
+ key: ["id"],
2329
+ indexes: { all: {
2330
+ eq: [],
2331
+ sort: ["id"]
2332
+ } }
2333
+ });
2290
2334
  /** One compiled catalog per scope; the update check reads exactly this row. */
2291
2335
  const releaseCatalogs = defineTable({
2292
2336
  scope_key: {
@@ -2356,7 +2400,10 @@ const channels = defineTable({
2356
2400
  /**
2357
2401
  * The native builds `native-build android` and `native-build ios` track, newest first
2358
2402
  * 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,
2403
+ * the build compiled in. A sandbox build's scope has no channel: its app ID,
2404
+ * URL scheme, artifact kind and distribution in its place, so pull requests
2405
+ * reuse it across channels, while `channel_id` still names the channel it
2406
+ * embeds. `min_bundle_id` names the build's built-in bundle,
2360
2407
  * a `bundles` row no release publishes. Its references keep no counters, so
2361
2408
  * adding this table changes no existing one; a channel with builds is
2362
2409
  * refused deletion through `byChannel`. `build_key` is the native build key
@@ -2366,6 +2413,27 @@ const channels = defineTable({
2366
2413
  * or `versionCode`. `submitted_to`, `submitted_at_ms` and
2367
2414
  * `submitted_version` record the store track a build went to, when, and
2368
2415
  * the store's label of the build; they stay null for a build no store took.
2416
+ * `is_store_build` is true on the build a person or a job says the store
2417
+ * sells, and false on every other: deploys patch from it over the scope's
2418
+ * newest build. The engine copies the scope key into `store_build_scope_key`
2419
+ * for that build alone, so `byStoreBuild` holds one entry per scope at most,
2420
+ * on every store, while any number of a scope's builds hold none.
2421
+ * `is_sandbox` is true on a sandbox build, set from its artifact when it
2422
+ * registers and never changed, and `sandbox_url_scheme` is the URL scheme its artifact registers,
2423
+ * which its preview links open; null on any other build, and on a sandbox
2424
+ * build registered before the column, which registered the derived one.
2425
+ * `export_method` is how an `.ipa` was exported, read from its profile when
2426
+ * it registers and never changed; null on any other artifact, on an `.ipa`
2427
+ * whose profile couldn't be read, and on one registered before the column.
2428
+ * `native_app_version` is the app version the artifact itself reports, its
2429
+ * `CFBundleShortVersionString` or `versionName`, read from the artifact when
2430
+ * it registers and never changed, whatever the update strategy; `app_version`
2431
+ * stays the version OTAs target, null on a fingerprint build. It is null
2432
+ * when the artifact's can't be read, and on a build registered before the
2433
+ * column.
2434
+ * Boolean columns follow one rule: `is_*` for a fact about the row or
2435
+ * `should_*` for an instruction to the client, never null; a unique index over
2436
+ * the rows where one is true keys a derived slot, not the boolean.
2369
2437
  */
2370
2438
  const nativeBuilds = defineTable({
2371
2439
  id: {
@@ -2442,9 +2510,34 @@ const nativeBuilds = defineTable({
2442
2510
  type: "string",
2443
2511
  maxLength: 255,
2444
2512
  required: false
2513
+ },
2514
+ is_store_build: { type: "boolean" },
2515
+ is_sandbox: { type: "boolean" },
2516
+ sandbox_url_scheme: {
2517
+ type: "string",
2518
+ maxLength: 255,
2519
+ ascii: true,
2520
+ required: false
2521
+ },
2522
+ export_method: {
2523
+ type: "string",
2524
+ maxLength: 16,
2525
+ required: false
2526
+ },
2527
+ native_app_version: {
2528
+ type: "string",
2529
+ required: false
2445
2530
  }
2446
2531
  }, {
2447
2532
  key: ["id"],
2533
+ derived: {
2534
+ /** The scope this build is the store build of; null on every other. */
2535
+ store_build_scope_key: {
2536
+ type: "string",
2537
+ maxLength: 2048,
2538
+ ascii: true,
2539
+ compute: (row) => row.is_store_build ? row.scope_key : null
2540
+ } },
2448
2541
  indexes: {
2449
2542
  byScope: {
2450
2543
  eq: ["scope_key"],
@@ -2454,6 +2547,15 @@ const nativeBuilds = defineTable({
2454
2547
  eq: ["scope_key", "build_key"],
2455
2548
  sort: ["id"]
2456
2549
  },
2550
+ byScopeKind: {
2551
+ eq: ["scope_key", "artifact_kind"],
2552
+ sort: ["id"]
2553
+ },
2554
+ byStoreBuild: {
2555
+ eq: ["store_build_scope_key"],
2556
+ sort: [],
2557
+ unique: true
2558
+ },
2457
2559
  byChannel: {
2458
2560
  eq: ["channel_id"],
2459
2561
  sort: ["id"],
@@ -2465,6 +2567,119 @@ const nativeBuilds = defineTable({
2465
2567
  }
2466
2568
  }
2467
2569
  });
2570
+ /**
2571
+ * The iPhones a team asks to install ad hoc builds on. A row decides what the
2572
+ * CLI registers with Apple, not what an export includes: Xcode's automatic ad
2573
+ * hoc profile lists every device the Apple account has enabled. `status` is
2574
+ * `pending` until someone approves it, `approved` until a build or
2575
+ * `native-build devices add` registers it with Apple, then `registered`;
2576
+ * declining or removing one deletes its row. `udid` is the UDID in lower case.
2577
+ * `apple_issuer_id` is the App Store Connect issuer whose key registered it,
2578
+ * set once: a build signed by another account never registers these rows.
2579
+ * `apple_error` is Apple's refusal of the device, or why it stopped counting
2580
+ * it, cleared by the next success. `build_id` is the newest native build whose
2581
+ * .ipa the CLI checked lists it; deleting that build never touches the row.
2582
+ * It holds personal data: a UDID, a name, and the emails of who asked and who
2583
+ * approved, null for the CLI.
2584
+ */
2585
+ const iosDevices = defineTable({
2586
+ id: {
2587
+ type: "string",
2588
+ maxLength: 36
2589
+ },
2590
+ udid: {
2591
+ type: "string",
2592
+ maxLength: 40,
2593
+ ascii: true,
2594
+ unique: true
2595
+ },
2596
+ name: {
2597
+ type: "string",
2598
+ maxLength: 100
2599
+ },
2600
+ status: {
2601
+ type: "string",
2602
+ maxLength: 16
2603
+ },
2604
+ requested_by: {
2605
+ type: "string",
2606
+ maxLength: 320,
2607
+ required: false
2608
+ },
2609
+ created_at_ms: { type: "integer" },
2610
+ approved_by: {
2611
+ type: "string",
2612
+ maxLength: 320,
2613
+ required: false
2614
+ },
2615
+ approved_at_ms: {
2616
+ type: "integer",
2617
+ required: false
2618
+ },
2619
+ registered_at_ms: {
2620
+ type: "integer",
2621
+ required: false
2622
+ },
2623
+ apple_issuer_id: {
2624
+ type: "string",
2625
+ maxLength: 64,
2626
+ ascii: true,
2627
+ required: false
2628
+ },
2629
+ apple_error: {
2630
+ type: "string",
2631
+ maxLength: 512,
2632
+ required: false
2633
+ },
2634
+ build_id: {
2635
+ type: "string",
2636
+ maxLength: 36,
2637
+ required: false
2638
+ }
2639
+ }, {
2640
+ key: ["id"],
2641
+ indexes: {
2642
+ byStatus: {
2643
+ eq: ["status"],
2644
+ sort: ["id"]
2645
+ },
2646
+ byRegistration: {
2647
+ eq: [],
2648
+ sort: ["registered_at_ms"]
2649
+ },
2650
+ all: {
2651
+ eq: [],
2652
+ sort: ["id"]
2653
+ }
2654
+ }
2655
+ });
2656
+ /**
2657
+ * The Apple account the iOS device registry belongs to: one row, keyed
2658
+ * `registry`, holding the App Store Connect issuer that first registered a
2659
+ * device. A build claims it before it sends Apple anything, and its key makes
2660
+ * the claim atomic on every store, so two builds of two accounts can't both
2661
+ * spend a slot; another account's build then registers nothing. Removing
2662
+ * devices never releases it.
2663
+ */
2664
+ const iosDeviceAccount = defineTable({
2665
+ id: {
2666
+ type: "string",
2667
+ maxLength: 16,
2668
+ ascii: true
2669
+ },
2670
+ apple_issuer_id: {
2671
+ type: "string",
2672
+ maxLength: 64,
2673
+ ascii: true
2674
+ },
2675
+ claimed_at_ms: { type: "integer" }
2676
+ }, {
2677
+ key: ["id"],
2678
+ indexes: { all: {
2679
+ eq: [],
2680
+ sort: ["id"]
2681
+ } }
2682
+ });
2468
2683
  /** Core's module: always installed, never a plugin. */
2469
2684
  const coreModule = {
2470
2685
  id: "core",
@@ -2485,7 +2700,10 @@ const coreModule = {
2485
2700
  sort: []
2486
2701
  } }
2487
2702
  }),
2488
- native_builds: nativeBuilds
2703
+ native_builds: nativeBuilds,
2704
+ ios_devices: iosDevices,
2705
+ ios_device_account: iosDeviceAccount,
2706
+ label_sequences: labelSequences
2489
2707
  }
2490
2708
  };
2491
2709
  //#endregion
@@ -2511,6 +2729,140 @@ const refuseV0Database = (adapterName, stored) => {
2511
2729
  if (typeof version !== "string" || stored.has("schema.engine")) return;
2512
2730
  throw new HotUpdaterSchemaMigrationRequiredError(adapterName, version);
2513
2731
  };
2732
+ /** Compares dotted numeric versions, such as "1" and "1.2.0"; NaN when either is not one. */
2733
+ const compareVersions = (left, right) => {
2734
+ const parse = (version) => /^\d+(?:\.\d+)*$/u.test(version) ? version.split(".").map(Number) : [NaN];
2735
+ const [a, b] = [parse(left), parse(right)];
2736
+ if ([...a, ...b].some(Number.isNaN)) return NaN;
2737
+ for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
2738
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
2739
+ if (difference !== 0) return difference;
2740
+ }
2741
+ return 0;
2742
+ };
2743
+ /**
2744
+ * The settings whose versions only move forward when a `ToolingTarget` names
2745
+ * none. `schema.engine` is a storage layout, not a release: a store refuses
2746
+ * another layout itself, and doctor reports it as not migratable.
2747
+ */
2748
+ const DEFAULT_ORDERED_SETTINGS = ["schema.core"];
2749
+ /**
2750
+ * Refuses a database a newer release migrated, one whose `schema.core` is
2751
+ * newer than this release's: writing this release's settings would move the
2752
+ * schema back, and every server of the newer release would answer 503. Only
2753
+ * `ordered` settings are compared, `schema.core` among them, and the message
2754
+ * lists each that is newer. An official plugin's
2755
+ * newer version alone is no newer release: Insights recorded "1.2.0" in
2756
+ * 1.0.0-rc.23 and rc.24, then went back to "1.0.0" with the same tables.
2757
+ */
2758
+ const refuseNewerSchema = (adapterName, stored, settings, ordered = DEFAULT_ORDERED_SETTINGS) => {
2759
+ const newer = ordered.flatMap((key) => {
2760
+ const found = stored.get(key);
2761
+ const expected = settings[key];
2762
+ return typeof found === "string" && expected !== void 0 && compareVersions(found, expected) > 0 ? [{
2763
+ key,
2764
+ found,
2765
+ expected
2766
+ }] : [];
2767
+ });
2768
+ const core = newer.find(({ key }) => key === "schema.core");
2769
+ if (core === void 0) return;
2770
+ 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.`);
2771
+ };
2772
+ /** The settings rows a migration changes, each with its stored value. */
2773
+ const settingsOperation = (stored, changed) => ({
2774
+ type: "custom",
2775
+ description: `Record ${changed.map(([key, value]) => {
2776
+ const found = stored.get(key);
2777
+ return typeof found === "string" ? `${key} ${found} → ${value}` : `${key} ${value}`;
2778
+ }).join(", ")}`
2779
+ });
2780
+ //#endregion
2781
+ //#region ../plugin-core/dist/engine/db/schemaSettings.mjs
2782
+ const storedSettings = async (adapter, keys) => {
2783
+ const rows = await readSettings(adapter, keys);
2784
+ return new Map(keys.map((key, position) => [key, rows[position] ?? null]));
2785
+ };
2786
+ /**
2787
+ * Writes the settings rows after every table exists, and refuses a database
2788
+ * whose `ordered` settings a newer release recorded.
2789
+ */
2790
+ const writeSchemaSettings = async (adapter, adapterName, settings, ordered) => {
2791
+ const stored = await storedSettings(adapter, Object.keys(settings));
2792
+ refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
2793
+ const ops = Object.entries(settings).flatMap(([key, value]) => {
2794
+ const row = stored.get(key);
2795
+ if (row === null || row === void 0) return [{
2796
+ type: "insert",
2797
+ table: SETTINGS_TABLE,
2798
+ row: {
2799
+ key,
2800
+ value,
2801
+ _v: 0
2802
+ }
2803
+ }];
2804
+ if (row.value === value) return [];
2805
+ return [{
2806
+ type: "patch",
2807
+ table: SETTINGS_TABLE,
2808
+ key: [key],
2809
+ set: { value },
2810
+ guard: { v: Number(row._v) },
2811
+ previous: row
2812
+ }];
2813
+ });
2814
+ if (ops.length === 0) return;
2815
+ if (!(await adapter.write(ops)).ok) throw new Error(`${adapterName}: the schema settings changed during the migration; run it again.`);
2816
+ };
2817
+ /**
2818
+ * The `LATE_INDEXES` among `tables` whose items some rows lack, as
2819
+ * `<table>.<index>`, written unless `dryRun`: none on a store without
2820
+ * `migrations.fillIndex`.
2821
+ */
2822
+ const fillLateIndexes = async (adapter, tables, { dryRun = false } = {}) => {
2823
+ const fillIndex = adapter.migrations?.fillIndex;
2824
+ if (fillIndex === void 0) return [];
2825
+ const lacking = [];
2826
+ for (const { table: name, index } of LATE_INDEXES) {
2827
+ const table = tables.find((candidate) => candidate.name === name);
2828
+ if (table === void 0) continue;
2829
+ if (await fillIndex(table, index, { dryRun }) > 0) lacking.push(`${name}.${index}`);
2830
+ }
2831
+ return lacking;
2832
+ };
2833
+ /**
2834
+ * The `LATE_COLUMNS` among `tables` that an existing table lacks, as
2835
+ * `<table>.<column>`, added unless `dryRun`: none on a store without
2836
+ * `migrations.addColumns`, or for a table not created yet.
2837
+ */
2838
+ const addLateColumns = async (adapter, tables, { dryRun = false } = {}) => {
2839
+ const addColumns = adapter.migrations?.addColumns;
2840
+ if (addColumns === void 0) return [];
2841
+ const lacking = [];
2842
+ for (const table of tables) {
2843
+ const columns = LATE_COLUMNS.filter(({ table: name }) => name === table.name).map(({ column }) => column);
2844
+ if (columns.length === 0) continue;
2845
+ const added = await addColumns(table, columns, { dryRun });
2846
+ lacking.push(...added.map((column) => `${table.name}.${column}`));
2847
+ }
2848
+ return lacking;
2849
+ };
2850
+ /**
2851
+ * Adds the late columns existing tables lack, creates or updates every
2852
+ * table, writes the late indexes' missing items, then writes the settings
2853
+ * rows last. A database a newer release migrated is
2854
+ * refused before anything is written: its settings are read first, and a
2855
+ * store without them yet, whose read fails, has none to refuse.
2856
+ */
2857
+ const migrateSchema = async (adapter, adapterName, tables, settings, ordered) => {
2858
+ if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
2859
+ const stored = await storedSettings(adapter, Object.keys(settings)).catch(() => void 0);
2860
+ if (stored !== void 0) refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
2861
+ await addLateColumns(adapter, tables);
2862
+ await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
2863
+ await fillLateIndexes(adapter, tables);
2864
+ await writeSchemaSettings(adapter, adapterName, settings, ordered);
2865
+ };
2514
2866
  //#endregion
2515
2867
  //#region ../plugin-core/dist/engine/database/cursor.mjs
2516
2868
  const encoder$1 = new TextEncoder();
@@ -2674,18 +3026,17 @@ const LEASE_TABLE = "aggregate_lease";
2674
3026
  const LEASE = { id: "compaction" };
2675
3027
  /** How long a compaction holds the lease before another process may take it. */
2676
3028
  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
- };
3029
+ /** A commit compacts once this has passed since the last compaction. */
3030
+ const WINDOW_MS$1 = 6e4;
2686
3031
  /** Log rows a compaction reads from each log table for one group. */
2687
3032
  const LOG_PAGE = 200;
2688
3033
  /**
3034
+ * How old a log row this process can't apply must be before its reads step
3035
+ * past it: older than any transaction still committing, between servers
3036
+ * whose clocks agree this closely.
3037
+ */
3038
+ const SKIP_AFTER_MS = 3e5;
3039
+ /**
2689
3040
  * Groups one compaction applies: after a commit, so the request that runs
2690
3041
  * it waits for one group; before a read; and on flush.
2691
3042
  */
@@ -2696,8 +3047,6 @@ const GROUPS = {
2696
3047
  };
2697
3048
  /** Tries per write after a conflict or a transient error. */
2698
3049
  const ATTEMPTS = 5;
2699
- /** Aggregate rows a memory buffer holds before a commit waits for a flush. */
2700
- const MAX_BUFFERED = 1e4;
2701
3050
  const log = defineTable({
2702
3051
  id: {
2703
3052
  type: "string",
@@ -2747,7 +3096,7 @@ const valuesOf = ({ deltas, sketches }) => ({
2747
3096
  /**
2748
3097
  * Merges `values` into the change for `key`'s identity as `tx.aggregate`
2749
3098
  * does: deltas add up and sketches merge. One constant `shardBy` keys each
2750
- * identity to one entry; the write picks the shard.
3099
+ * identity to one entry; `compile` writes it to shard 0.
2751
3100
  */
2752
3101
  const merge = (into, model, key, values) => recordAggregate(into, model, Object.fromEntries(shapeOf(model).key.map((field, at) => [field, key[at]])), values, "");
2753
3102
  const mergeAll = (into, changes) => {
@@ -2781,7 +3130,7 @@ const increment = ({ model, deltas }, key) => Object.values(deltas).some((delta)
2781
3130
  /**
2782
3131
  * The guarded write that merges `change` into `current`: insert, patch, or
2783
3132
  * 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.
3133
+ * group can hold a loss without the gain before it, and reads sum every shard.
2785
3134
  */
2786
3135
  const rewrite = (change, key, current) => {
2787
3136
  const { model } = change;
@@ -2818,23 +3167,41 @@ const rewrite = (change, key, current) => {
2818
3167
  previous: current
2819
3168
  };
2820
3169
  };
3170
+ /** A shard row's place in what `readCurrent` read. */
3171
+ const rowId = (model, key) => JSON.stringify([model.table.name, key]);
3172
+ /** The shard key each change writes: shard 0, since one compaction runs at a time. */
3173
+ const keysOf = (changes) => changes.map(({ key }) => [...key.slice(0, -1), 0]);
2821
3174
  /**
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.
3175
+ * The current rows of the changes that rewrite theirs (gauges and sketches),
3176
+ * each once, in one batch per table.
2825
3177
  */
2826
- const compile = async (adapter, changes, shard) => {
2827
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
3178
+ const readCurrent = async (adapter, changes) => {
3179
+ const keys = keysOf(changes);
2828
3180
  const reads = /* @__PURE__ */ new Map();
2829
3181
  changes.forEach((change, at) => {
2830
- if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
3182
+ if (!rewrites(change)) return;
3183
+ const wanted = reads.get(change.model) ?? /* @__PURE__ */ new Map();
3184
+ wanted.set(rowId(change.model, keys[at]), keys[at]);
3185
+ reads.set(change.model, wanted);
2831
3186
  });
2832
3187
  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));
3188
+ await Promise.all([...reads].map(async ([model, wanted]) => {
3189
+ const keys = [...wanted.values()];
3190
+ const rows = await adapter.get(model.table, keys);
3191
+ keys.forEach((key, at) => {
3192
+ current.set(rowId(model, key), rows[at] ?? null);
3193
+ });
2836
3194
  }));
2837
- return changes.map((change, at) => current.has(at) ? rewrite(change, keys[at], current.get(at)) : increment(change, keys[at]));
3195
+ return current;
3196
+ };
3197
+ /**
3198
+ * The write for each change: a blind increment that creates the row for
3199
+ * counters, and a guarded rewrite for gauges and sketches, over the rows
3200
+ * `current` read.
3201
+ */
3202
+ const build = (changes, current) => {
3203
+ const keys = keysOf(changes);
3204
+ return changes.map((change, at) => rewrites(change) ? rewrite(change, keys[at], current.get(rowId(change.model, keys[at])) ?? null) : increment(change, keys[at]));
2838
3205
  };
2839
3206
  const isOp = (op) => op !== void 0;
2840
3207
  const sleep = (attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random()));
@@ -2878,14 +3245,13 @@ const encode$1 = async (changes) => {
2878
3245
  return zipped !== void 0 && zipped.length < json.length ? `z${zipped}` : json;
2879
3246
  };
2880
3247
  /**
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.
3248
+ * Batches changes to aggregates declared `batched`. A transaction writes
3249
+ * them as one log row in its own atomic write, in place of their rows; a
3250
+ * compaction later merges log rows into the aggregates and deletes them,
3251
+ * atomically again, so each applies exactly once. One lease row keeps
3252
+ * compactions one at a time.
2887
3253
  */
2888
- const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS$1[mode] }, now }) => {
3254
+ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs = WINDOW_MS$1 }, now }) => {
2889
3255
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
2890
3256
  const holder = crypto.randomUUID().replaceAll("-", "");
2891
3257
  const table = (name) => schema.models.get(name).table;
@@ -2913,72 +3279,20 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
2913
3279
  }
2914
3280
  return changes;
2915
3281
  };
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
3282
  let nextDue = 0;
2979
3283
  let compacting;
2980
3284
  /** Log rows this process read, by `[log table's index, id]`, for the deletes after a group. */
2981
3285
  const known = /* @__PURE__ */ new Map();
3286
+ /**
3287
+ * Each log table's last row of a run at its head that this process can't
3288
+ * apply (it names an aggregate or metric this schema lacks), whose reads
3289
+ * start past it. The rows wait for a process that can apply them, and a
3290
+ * restart reads them again.
3291
+ */
3292
+ const skipped = LOG_TABLES.map(() => void 0);
3293
+ const past = (shard) => skipped[shard] === void 0 ? {} : { range: { gt: skipped[shard] } };
3294
+ /** When a log row's transaction stamped its ID. */
3295
+ const stampOf = (id) => Number.parseInt(id.slice(0, 9), 36);
2982
3296
  const idOf = (shard, id) => JSON.stringify([shard, id]);
2983
3297
  /** The lease row as stored once `set` is written over it. */
2984
3298
  const leaseOp = (held, set) => {
@@ -3094,14 +3408,22 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3094
3408
  logs: (await Promise.all(LOG_TABLES.map(async (name, shard) => {
3095
3409
  const page = await engine.reads.findMany(name, {
3096
3410
  index: "oldest",
3097
- limit: LOG_PAGE
3411
+ limit: LOG_PAGE,
3412
+ ...past(shard)
3098
3413
  });
3099
3414
  more ||= page.next !== void 0;
3100
- return (await Promise.all(page.rows.map(async (row) => ({
3415
+ const decoded = await Promise.all(page.rows.map(async (row) => ({
3101
3416
  shard,
3102
3417
  row,
3103
3418
  changes: await decode(String(row.changes))
3104
- })))).flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
3419
+ })));
3420
+ const settled = now() - SKIP_AFTER_MS;
3421
+ for (const { row, changes } of decoded) {
3422
+ const id = String(row.id);
3423
+ if (changes !== void 0 || stampOf(id) >= settled) break;
3424
+ skipped[shard] = id;
3425
+ }
3426
+ return decoded.flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
3105
3427
  ...entry,
3106
3428
  changes
3107
3429
  }]);
@@ -3109,7 +3431,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3109
3431
  more
3110
3432
  };
3111
3433
  };
3112
- const rowsFor = async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp);
3113
3434
  /**
3114
3435
  * Applies the oldest pending log rows whose merged changes fit in one
3115
3436
  * atomic write with the lease, which lists them as applied; the rows are
@@ -3118,12 +3439,14 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3118
3439
  * log rows it applied whole, or undefined when a conflict stopped it.
3119
3440
  */
3120
3441
  const applyGroup = async (held, logs) => {
3442
+ const current = await readCurrent(adapter, logs.flatMap((entry) => [...entry.changes.values()]));
3443
+ const rowsFor = (changes) => build(changes, current).filter(isOp);
3121
3444
  for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
3122
3445
  const batch = logs.slice(0, count);
3123
3446
  const changes = mergeAll(/* @__PURE__ */ new Map(), batch.flatMap((entry) => [...entry.changes.values()]));
3124
3447
  const applied = batch.map(({ shard, row }) => [shard, row.id]);
3125
3448
  const lease = leaseOp(held, { applied: JSON.stringify(applied) });
3126
- const ops = [...await rowsFor([...changes.values()]), lease.op];
3449
+ const ops = [...rowsFor([...changes.values()]), lease.op];
3127
3450
  if (!adapter.fits(ops)) continue;
3128
3451
  for (const { shard, row } of batch) known.set(idOf(shard, row.id), row);
3129
3452
  return await commit(ops) ? {
@@ -3145,7 +3468,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3145
3468
  };
3146
3469
  const lease = leaseOp(held, {});
3147
3470
  const ops = [
3148
- ...await rowsFor(entries.slice(0, take)),
3471
+ ...rowsFor(entries.slice(0, take)),
3149
3472
  kept,
3150
3473
  lease.op
3151
3474
  ];
@@ -3166,11 +3489,12 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3166
3489
  if (held === void 0) return;
3167
3490
  let pending = true;
3168
3491
  let clear = false;
3492
+ let carried;
3169
3493
  try {
3170
3494
  for (let group = 0;; group += 1) {
3171
3495
  clear = await deleteApplied(held);
3172
3496
  if (!clear || !pending || group === groups) break;
3173
- const { logs, more } = await readLogs();
3497
+ const { logs, more } = carried ?? await readLogs();
3174
3498
  if (logs.length === 0) {
3175
3499
  pending = false;
3176
3500
  break;
@@ -3178,6 +3502,11 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3178
3502
  const applied = await applyGroup(held, logs);
3179
3503
  if (applied === void 0) break;
3180
3504
  [held, clear] = [applied.held, false];
3505
+ const rest = applied.count === 0 ? [] : logs.slice(applied.count);
3506
+ carried = rest.length > 0 ? {
3507
+ logs: rest,
3508
+ more
3509
+ } : void 0;
3181
3510
  pending = more || applied.count < logs.length;
3182
3511
  }
3183
3512
  } finally {
@@ -3197,26 +3526,13 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3197
3526
  });
3198
3527
  let checking;
3199
3528
  /** 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, {
3529
+ const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name, shard) => engine.reads.findMany(name, {
3201
3530
  index: "oldest",
3202
- limit: 1
3531
+ limit: 1,
3532
+ ...past(shard)
3203
3533
  }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
3204
3534
  checking = void 0;
3205
3535
  });
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
3536
  return {
3221
3537
  async transaction(fn) {
3222
3538
  let changes = /* @__PURE__ */ new Map();
@@ -3242,7 +3558,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3242
3558
  aggregate
3243
3559
  });
3244
3560
  if (failure) throw failure.error;
3245
- if (mode === "log" && attempt.size > 0) {
3561
+ if (attempt.size > 0) {
3246
3562
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
3247
3563
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
3248
3564
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -3256,24 +3572,18 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3256
3572
  open = false;
3257
3573
  }
3258
3574
  });
3259
- if (changes.size > 0) await committed(changes);
3575
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
3260
3576
  return result;
3261
3577
  },
3262
3578
  async beforeRead(name) {
3263
3579
  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
- }
3580
+ if (await hasPending().catch((error) => {
3581
+ warn("read")(error);
3582
+ return false;
3583
+ })) await compact(true, GROUPS.read);
3271
3584
  },
3272
- flush,
3273
- async dispose() {
3274
- clearTimeout(timer);
3275
- timer = void 0;
3276
- await flush();
3585
+ async flush() {
3586
+ if (await hasPending()) await compact(true, GROUPS.flush);
3277
3587
  }
3278
3588
  };
3279
3589
  };
@@ -3415,7 +3725,8 @@ const fieldProblems = (definition, add) => {
3415
3725
  else if (field.required === false) add(`key field "${name}" is nullable`);
3416
3726
  else if (field.type === "json") add(`key field "${name}" is json`);
3417
3727
  }
3418
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
3728
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
3729
+ for (const [name, { type, maxLength, ascii }] of bounded) {
3419
3730
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
3420
3731
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
3421
3732
  }
@@ -3532,11 +3843,13 @@ const resolveSchema = (modules) => {
3532
3843
  ...maxLength === void 0 ? {} : { maxLength },
3533
3844
  ...ascii ? { ascii } : {}
3534
3845
  }));
3535
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
3846
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
3536
3847
  name: field,
3537
3848
  type,
3538
3849
  nullable: true,
3539
- ...multi ? { multi } : {}
3850
+ ...multi ? { multi } : {},
3851
+ ...maxLength === void 0 ? {} : { maxLength },
3852
+ ...ascii ? { ascii } : {}
3540
3853
  });
3541
3854
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
3542
3855
  name: metric,
@@ -3572,29 +3885,56 @@ const resolveSchema = (modules) => {
3572
3885
  * `hot-updater db migrate` for a store whose adapter creates its own tables
3573
3886
  * (MongoDB and the key-value stores): the tables and indexes, then the
3574
3887
  * settings rows, applied when a setting is missing or different, and refused
3575
- * on a v0 database.
3888
+ * on a v0 database or one a newer release migrated.
3576
3889
  */
3577
3890
  const createEngineMigrator = (options) => {
3578
3891
  const getVersion = async () => storedSchemaVersion(await options.readSettings());
3579
3892
  const makeResult = async (migrate = {}) => {
3580
3893
  const stored = await options.readSettings();
3581
3894
  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
- }]))
3895
+ refuseNewerSchema(options.adapterName, stored, options.settings, options.ordered);
3896
+ const changed = Object.entries(options.settings).filter(([key, value]) => stored.get(key) !== value);
3897
+ if (changed.length === 0) {
3898
+ const columns = await addLateColumns(options.adapter, options.schema.tables, { dryRun: true });
3899
+ const lacking = await fillLateIndexes(options.adapter, options.schema.tables, { dryRun: true });
3900
+ if (columns.length === 0 && lacking.length === 0) return getEmptyMigrationResult();
3901
+ return {
3902
+ operations: [
3903
+ ...columns.map((column) => ({
3904
+ type: "custom",
3905
+ description: `Add column: ${column}`
3906
+ })),
3907
+ ...columns.length === 0 ? [] : [{
3908
+ type: "custom",
3909
+ description: "Create the tables and indexes the database lacks"
3910
+ }],
3911
+ ...lacking.length === 0 ? [] : [{
3912
+ type: "custom",
3913
+ description: `Write the index items rows lack: ${lacking.join(", ")}`
3914
+ }]
3915
+ ],
3916
+ execute: async () => {
3917
+ if (columns.length > 0) {
3918
+ await addLateColumns(options.adapter, options.schema.tables);
3919
+ await options.adapter.migrations.apply([...options.schema.tables, SETTINGS_TABLE]);
3920
+ }
3921
+ await fillLateIndexes(options.adapter, options.schema.tables);
3592
3922
  }
3593
- })), ...migrate.updateSettings === false ? [] : [{
3594
- type: "custom",
3595
- description: `Write the schema settings: ${Object.keys(options.settings).join(", ")}`
3596
- }]],
3597
- execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings)
3923
+ };
3924
+ }
3925
+ return {
3926
+ operations: [
3927
+ ...(await addLateColumns(options.adapter, options.schema.tables, { dryRun: true }).catch(() => [])).map((column) => ({
3928
+ type: "custom",
3929
+ description: `Add column: ${column}`
3930
+ })),
3931
+ {
3932
+ type: "custom",
3933
+ description: "Create the tables and indexes the database lacks"
3934
+ },
3935
+ ...migrate.updateSettings === false ? [] : [settingsOperation(stored, changed)]
3936
+ ],
3937
+ execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings, options.ordered)
3598
3938
  };
3599
3939
  };
3600
3940
  return {
@@ -3625,7 +3965,8 @@ const coreSettings = {
3625
3965
  /** What `hot-updater db` creates for a server without plugins. */
3626
3966
  const coreTarget = {
3627
3967
  schema: coreSchema,
3628
- settings: coreSettings
3968
+ settings: coreSettings,
3969
+ ordered: ["schema.core"]
3629
3970
  };
3630
3971
  resolveSchema([aggregateBatchingModule]).tables;
3631
3972
  /** Each plugin's `schema.<id>` settings row. */
@@ -3645,11 +3986,12 @@ const pluginModule = ({ id, schema, namespace }) => ({
3645
3986
  */
3646
3987
  const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBatching, retry, readSettings: readStored }) => {
3647
3988
  const fenced = withSchemaFence(adapter, name, coreSettings);
3648
- const createMigrator = ({ schema, settings } = coreTarget) => createEngineMigrator({
3989
+ const createMigrator = ({ schema, settings, ordered } = coreTarget) => createEngineMigrator({
3649
3990
  adapterName: name,
3650
3991
  adapter,
3651
3992
  schema,
3652
3993
  settings,
3994
+ ordered,
3653
3995
  readSettings: readStored ?? (async () => {
3654
3996
  const rows = await readSettings(adapter, Object.keys(settings)).catch((error) => {
3655
3997
  if (isMissingSchemaError(error)) return [];
@@ -3673,6 +4015,12 @@ const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBa
3673
4015
  /** A row this attempt read changed while it ran; the attempt reruns. */
3674
4016
  var StaleReadError = class extends Error {};
3675
4017
  const idOf = (table, key) => JSON.stringify([table, key]);
4018
+ /** The aggregate rows a write changes, at the versions it read them. */
4019
+ const versionsOf = (ops) => JSON.stringify(ops.map((op) => op.type === "insert" ? [op.table.name, rowKey(op.table, op.row)] : [
4020
+ op.table.name,
4021
+ op.key,
4022
+ "guard" in op ? op.guard?.v : void 0
4023
+ ]));
3676
4024
  const versionOf = (row) => Number(row["_v"]);
3677
4025
  const isKeyed = (value) => value !== null && value !== void 0;
3678
4026
  const misuse = (table, message) => new DatabaseTransactionError(`${table}: ${message}`);
@@ -4017,7 +4365,9 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4017
4365
  assertOutsideTransaction();
4018
4366
  let run;
4019
4367
  let negative;
4020
- for (let round = 0; round < attempts; round += 1) {
4368
+ let failures = 0;
4369
+ let lost;
4370
+ for (let round = 0;; round += 1) {
4021
4371
  const delay = round && Math.min(maxDelayMs, baseDelayMs * 2 ** (round - 1));
4022
4372
  if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay / 2 + Math.random() * (delay / 2)));
4023
4373
  run ??= await attempt(fn).catch((error) => {
@@ -4026,6 +4376,8 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4026
4376
  });
4027
4377
  if (run === void 0) {
4028
4378
  onRetry?.("rerun", round + 1);
4379
+ lost = void 0;
4380
+ if ((failures += 1) >= attempts) break;
4029
4381
  continue;
4030
4382
  }
4031
4383
  let aggregates;
@@ -4036,8 +4388,14 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4036
4388
  negative = error;
4037
4389
  onRetry?.("rerun", round + 1);
4038
4390
  run = void 0;
4391
+ lost = void 0;
4392
+ if ((failures += 1) >= attempts) break;
4039
4393
  continue;
4040
4394
  }
4395
+ const versions = versionsOf(aggregates);
4396
+ if (lost !== void 0 && versions !== lost) failures -= 1;
4397
+ lost = void 0;
4398
+ if (failures >= attempts) break;
4041
4399
  const ops = [...run.ops, ...aggregates];
4042
4400
  if (ops.length <= 1 && ops.every(({ type }) => type === "check")) return run.result;
4043
4401
  if (!adapter.fits(ops)) throw new DatabaseConstraintError("too_large", ops[0].table.name);
@@ -4051,12 +4409,16 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4051
4409
  const failed = "failedOp" in outcome ? outcome.failedOp : void 0;
4052
4410
  if (failed === void 0 || failed >= run.ops.length) {
4053
4411
  onRetry?.("resend", round + 1);
4412
+ failures += 1;
4413
+ if (failed !== void 0) lost = versions;
4414
+ else if (failures >= attempts) break;
4054
4415
  continue;
4055
4416
  }
4056
4417
  const reason = await classify(ops[failed], run.read);
4057
4418
  if (reason) throw new DatabaseConstraintError(reason, ops[failed].table.name);
4058
4419
  onRetry?.("rerun", round + 1);
4059
4420
  run = void 0;
4421
+ if ((failures += 1) >= attempts) break;
4060
4422
  }
4061
4423
  throw negative ?? new DatabaseConflictError(`The transaction conflicted ${attempts} times.`);
4062
4424
  } };
@@ -4302,13 +4664,10 @@ const createDatabaseEngine = ({ batching, now = Date.now, meter, ...options }) =
4302
4664
  };
4303
4665
  return {
4304
4666
  ...engine,
4305
- /** Applies batched aggregate changes still pending: this process's buffer and the log. */
4667
+ /** Applies the batched aggregate changes still in the log. */
4306
4668
  flush: async () => {
4307
4669
  await batches?.flush();
4308
4670
  },
4309
- dispose: async () => {
4310
- await batches?.dispose();
4311
- },
4312
4671
  database(module) {
4313
4672
  const name = (model) => module.namespace ? `${module.namespace}_${model}` : model;
4314
4673
  return {
@@ -4389,8 +4748,7 @@ const createEngine = (database, { plugins = [], now = Date.now } = {}) => {
4389
4748
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
4390
4749
  return engine.database(module);
4391
4750
  },
4392
- flush: () => engine.flush(),
4393
- dispose: () => engine.dispose()
4751
+ flush: () => engine.flush()
4394
4752
  };
4395
4753
  };
4396
4754
  //#endregion
@@ -4460,10 +4818,10 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
4460
4818
  const at = row && expiresAt(table, row);
4461
4819
  return at === void 0 ? {} : { expiresAt: at };
4462
4820
  };
4463
- /** Every index and unique item a row has, by address. */
4464
- const itemsOf = (layout, row) => {
4821
+ /** Every index and unique item a row has, by address: in `indexes`, if given. */
4822
+ const itemsOf = (layout, row, indexes = layout.indexed) => {
4465
4823
  const items = /* @__PURE__ */ new Map();
4466
- for (const index of row === null ? [] : layout.indexed) for (const eq of indexEntries(layout.table, index, row)) {
4824
+ for (const index of row === null ? [] : indexes) for (const eq of indexEntries(layout.table, index, row)) {
4467
4825
  const pk = partition(layout, index, eq);
4468
4826
  const sk = index.unique ? ONLY : encodeKvKey(indexOrderTuple(layout.table, index, row)) || ONLY;
4469
4827
  items.set(JSON.stringify([pk, sk]), {
@@ -4618,19 +4976,92 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
4618
4976
  lte: lt.endsWith(SEPARATOR) ? lt.slice(0, -1) : lt
4619
4977
  };
4620
4978
  };
4621
- return {
4622
- id: store.id,
4623
- fits(ops) {
4624
- const { items } = compile(ops);
4625
- if (items === void 0) return true;
4626
- const { items: most, bytes, itemBytes = bytes, keyBytes } = store.limits;
4627
- const sizes = items.map(sizeOf);
4628
- const length = (text) => encoder.encode(text).length;
4629
- return items.length <= most && sizes.reduce((sum, size) => sum + size, 0) <= bytes && sizes.every((size) => size <= itemBytes) && (keyBytes === void 0 || items.every(({ op }) => length(op.key.pk) <= keyBytes.pk && length(op.key.sk) <= keyBytes.sk));
4630
- },
4631
- get: (table, keys) => store.get(keys.map((key) => rowItem(layoutOf(table), key))),
4632
- async query(table, request) {
4633
- const layout = layoutOf(table);
4979
+ /** One row's check and its item puts in `index`, copies of the row as it is. */
4980
+ const fillOps = (layout, index, row) => [{
4981
+ type: "check",
4982
+ key: rowItem(layout, rowKey(layout.table, row)),
4983
+ condition: { v: Number(row["_v"]) }
4984
+ }, ...[...itemsOf(layout, row, [index]).values()].map(({ key }) => ({
4985
+ type: "put",
4986
+ key,
4987
+ value: copyOf(layout, row),
4988
+ ...stamp(layout.table, row)
4989
+ }))];
4990
+ /**
4991
+ * Writes one row's items in `index`, checking the row's `_v` in the same
4992
+ * write: a row that changed is read again, and a deleted one needs none.
4993
+ */
4994
+ const fillRow = async (layout, index, first) => {
4995
+ const key = rowItem(layout, rowKey(layout.table, first));
4996
+ let row = first;
4997
+ for (let attempt = 0; row !== null; attempt += 1) {
4998
+ 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.`);
4999
+ if ((await store.write(fillOps(layout, index, row))).ok) return;
5000
+ [row] = await store.get([key]);
5001
+ }
5002
+ };
5003
+ /**
5004
+ * Finds the rows that lack an item in `index` and, unless `dryRun`, writes
5005
+ * them, as many rows per atomic write as the store takes. It reads every
5006
+ * row and its items, page by page.
5007
+ */
5008
+ const fillIndex = async (table, name, { dryRun = false } = {}) => {
5009
+ const layout = layoutOf(table);
5010
+ const index = layout.indexed.find((candidate) => candidate.name === name);
5011
+ if (index === void 0) return 0;
5012
+ 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.`);
5013
+ const { items: most, bytes } = store.limits;
5014
+ let lacking = 0;
5015
+ for (let after;;) {
5016
+ const page = await store.query({
5017
+ pk: layout.rows,
5018
+ order: "asc",
5019
+ limit: 100,
5020
+ after
5021
+ });
5022
+ const rows = page.items.map(({ value }) => value);
5023
+ const keys = rows.map((row) => [...itemsOf(layout, row, [index]).values()].map(({ key }) => key));
5024
+ const wanted = keys.flat();
5025
+ const found = wanted.length === 0 ? [] : await store.get(wanted);
5026
+ let at = 0;
5027
+ const missing = rows.filter((_, position) => {
5028
+ return found.slice(at, at += keys[position].length).some((item) => item === null);
5029
+ });
5030
+ lacking += missing.length;
5031
+ if (!dryRun) {
5032
+ let chunk = [];
5033
+ let ops = [];
5034
+ const flush = async () => {
5035
+ if (ops.length > 0 && !(await store.write(ops)).ok) for (const row of chunk) await fillRow(layout, index, row);
5036
+ chunk = [];
5037
+ ops = [];
5038
+ };
5039
+ for (const row of missing) {
5040
+ const next = fillOps(layout, index, row);
5041
+ 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);
5042
+ if (chunk.length > 0 && (ops.length + next.length > most || size(ops) + size(next) > bytes)) await flush();
5043
+ chunk.push(row);
5044
+ ops.push(...next);
5045
+ }
5046
+ await flush();
5047
+ }
5048
+ if (!page.more || page.items.length === 0) return lacking;
5049
+ after = page.items.at(-1).sk;
5050
+ }
5051
+ };
5052
+ return {
5053
+ id: store.id,
5054
+ fits(ops) {
5055
+ const { items } = compile(ops);
5056
+ if (items === void 0) return true;
5057
+ const { items: most, bytes, itemBytes = bytes, keyBytes } = store.limits;
5058
+ const sizes = items.map(sizeOf);
5059
+ const length = (text) => encoder.encode(text).length;
5060
+ return items.length <= most && sizes.reduce((sum, size) => sum + size, 0) <= bytes && sizes.every((size) => size <= itemBytes) && (keyBytes === void 0 || items.every(({ op }) => length(op.key.pk) <= keyBytes.pk && length(op.key.sk) <= keyBytes.sk));
5061
+ },
5062
+ get: (table, keys) => store.get(keys.map((key) => rowItem(layoutOf(table), key))),
5063
+ async query(table, request) {
5064
+ const layout = layoutOf(table);
4634
5065
  const index = findPhysicalIndex(table, request.index);
4635
5066
  if (index.unique) {
4636
5067
  const key = {
@@ -4677,13 +5108,16 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
4677
5108
  const layout = layoutOf(table);
4678
5109
  return store.deleteConsumed(rows.flatMap((row) => [rowItem(layout, rowKey(table, row)), ...[...itemsOf(layout, row).values()].map(({ key }) => key)]));
4679
5110
  } },
4680
- migrations: { apply: async () => store.migrations?.apply() },
5111
+ migrations: {
5112
+ apply: async () => store.migrations?.apply(),
5113
+ fillIndex
5114
+ },
4681
5115
  ...store.dispose === void 0 ? {} : { dispose: () => store.dispose() }
4682
5116
  };
4683
5117
  };
4684
5118
  //#endregion
4685
5119
  //#region ../../packages/server/dist/version.mjs
4686
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.5";
5120
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.51";
4687
5121
  //#endregion
4688
5122
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
4689
5123
  /**
@@ -4843,10 +5277,15 @@ const releaseCatalogScopeKeyOf = (input) => input.strategy === "APP_VERSION" ? c
4843
5277
  platform: input.platform,
4844
5278
  strategy: "FINGERPRINT"
4845
5279
  });
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);
5280
+ const parseReleaseCatalogRow = ({ payload, ...row }) => ({
5281
+ row,
5282
+ compiled: parseCompiledCatalog(payload, row.strategy)
5283
+ });
5284
+ /** Projects a parsed catalog row for one update check; null when the row is not this scope's. */
5285
+ const projectParsedReleaseCatalogRow = (parsed, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
5286
+ if (parsed === null) return null;
5287
+ const { row, compiled } = parsed;
5288
+ 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
5289
  const appVersion = input.strategy === "APP_VERSION" ? input.appVersion : void 0;
4851
5290
  return {
4852
5291
  catalogId: row.catalog_id,
@@ -4859,6 +5298,8 @@ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyO
4859
5298
  scopeKey
4860
5299
  };
4861
5300
  };
5301
+ /** Projects a stored catalog row for one update check; null when the row is not this scope's. */
5302
+ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => projectParsedReleaseCatalogRow(row === null ? null : parseReleaseCatalogRow(row), input, scopeKey);
4862
5303
  //#endregion
4863
5304
  //#region ../../packages/server/dist/db/updateArtifacts.mjs
4864
5305
  const HBC_ASSET_PATH_RE = /\.bundle$/;
@@ -5475,9 +5916,9 @@ const baseBundleIdsOf = (row, range, bundleId, limit) => {
5475
5916
  };
5476
5917
  //#endregion
5477
5918
  //#region ../../packages/server/dist/core/reads.mjs
5478
- const PAGE$3 = 500;
5479
- const pick$1 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
5480
- const toBundleRow = pick$1([
5919
+ const PAGE$4 = 500;
5920
+ const pick$2 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
5921
+ const toBundleRow = pick$2([
5481
5922
  "id",
5482
5923
  "platform",
5483
5924
  "git_commit_hash",
@@ -5486,7 +5927,7 @@ const toBundleRow = pick$1([
5486
5927
  "manifest_file_hash",
5487
5928
  "asset_base_storage_uri"
5488
5929
  ]);
5489
- const toPatchRow = pick$1([
5930
+ const toPatchRow = pick$2([
5490
5931
  "id",
5491
5932
  "bundle_id",
5492
5933
  "base_bundle_id",
@@ -5496,7 +5937,7 @@ const toPatchRow = pick$1([
5496
5937
  "byte_size",
5497
5938
  "order_index"
5498
5939
  ]);
5499
- const toReleaseRow = pick$1([
5940
+ const pickReleaseRow = pick$2([
5500
5941
  "id",
5501
5942
  "revision",
5502
5943
  "scope_key",
@@ -5517,7 +5958,14 @@ const toReleaseRow = pick$1([
5517
5958
  "created_at_ms",
5518
5959
  "updated_at_ms"
5519
5960
  ]);
5520
- const toCatalogRow = pick$1([
5961
+ /** A release row; `label` null where the store holds none, as before the column. */
5962
+ const toReleaseRow = (row) => {
5963
+ return {
5964
+ ...pickReleaseRow(row),
5965
+ label: typeof row.label === "number" ? row.label : null
5966
+ };
5967
+ };
5968
+ const toCatalogRow = pick$2([
5521
5969
  "scope_key",
5522
5970
  "catalog_id",
5523
5971
  "strategy",
@@ -5532,7 +5980,7 @@ const toCatalogRow = pick$1([
5532
5980
  "is_tombstone",
5533
5981
  "updated_at_ms"
5534
5982
  ]);
5535
- const toChannelRow = pick$1(["id", "name"]);
5983
+ const toChannelRow = pick$2(["id", "name"]);
5536
5984
  /** Every page of one read, in order. */
5537
5985
  const drain$1 = async (read) => {
5538
5986
  const rows = [];
@@ -5545,8 +5993,16 @@ const drain$1 = async (read) => {
5545
5993
  return rows;
5546
5994
  };
5547
5995
  /** 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. */
5996
+ /** A keyset read's range on its index's order: past `after`, up to `through`. */
5997
+ const after = (input) => {
5998
+ const asc = (input.order ?? "asc") === "asc";
5999
+ const range = {
6000
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
6001
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
6002
+ };
6003
+ return Object.keys(range).length === 0 ? {} : { range };
6004
+ };
6005
+ /** Core's reads, each through one declared index or key; plugins get `CoreReads`. */
5550
6006
  const createCoreReads = (db, storage) => {
5551
6007
  /** A bundle row's patches, exactly as many as its reference counter holds. */
5552
6008
  const detail = async (row) => {
@@ -5557,7 +6013,7 @@ const createCoreReads = (db, storage) => {
5557
6013
  const page = await db.findMany("bundle_patches", {
5558
6014
  index: "byBundle",
5559
6015
  where: { bundle_id: row.id },
5560
- limit: Math.min(count - patches.length, PAGE$3),
6016
+ limit: Math.min(count - patches.length, PAGE$4),
5561
6017
  ...cursor === void 0 ? {} : { cursor }
5562
6018
  });
5563
6019
  patches.push(...page.rows.map(toPatchRow));
@@ -5667,6 +6123,23 @@ const createCoreReads = (db, storage) => {
5667
6123
  const row = await db.findOne("releases", { id });
5668
6124
  return row === null ? null : toReleaseRow(row);
5669
6125
  },
6126
+ /**
6127
+ * The release a label names: its unique index, then the row itself,
6128
+ * since a key-value store keeps an index copy a server of an earlier
6129
+ * release may have left behind when it changed or deleted the row.
6130
+ */
6131
+ async getReleaseByLabel({ channel, platform, label }) {
6132
+ const found = await db.findOne("releases", {
6133
+ channel_id: `channel:${encodeChannelKey(channel)}`,
6134
+ platform,
6135
+ label
6136
+ });
6137
+ if (found === null) return null;
6138
+ const row = await db.findOne("releases", { id: found.id });
6139
+ if (row === null) return null;
6140
+ const release = toReleaseRow(row);
6141
+ return release.label === label && release.platform === platform ? release : null;
6142
+ },
5670
6143
  /** One page of releases through the index its filter names. */
5671
6144
  async listReleases(input) {
5672
6145
  const { filter } = input;
@@ -5734,15 +6207,47 @@ const createCoreReads = (db, storage) => {
5734
6207
  ...after(input)
5735
6208
  })).rows.map(toCatalogRow);
5736
6209
  },
5737
- /** Every channel, by name. */
5738
- async listChannels() {
6210
+ /**
6211
+ * Up to `limit` scope keys that have releases, ascending after `after`:
6212
+ * one limit-1 seek of the `scopes` index past each scope, so the reads
6213
+ * grow with the scopes, not with their releases.
6214
+ */
6215
+ async listReleaseScopeKeys(input) {
6216
+ const scopeKeys = [];
6217
+ for (let last = input.after ?? ""; scopeKeys.length < input.limit;) {
6218
+ const { rows } = await db.findMany("releases", {
6219
+ index: "scopes",
6220
+ where: {},
6221
+ limit: 1,
6222
+ range: { gt: last }
6223
+ });
6224
+ if (rows[0] === void 0) break;
6225
+ last = rows[0].scope_key;
6226
+ scopeKeys.push(last);
6227
+ }
6228
+ return scopeKeys;
6229
+ },
6230
+ /** Every channel by name; with `input`, one keyset page of them. */
6231
+ async listChannels(input) {
6232
+ if (input !== void 0) return (await db.findMany("channels", {
6233
+ index: "all",
6234
+ where: {},
6235
+ order: input.order ?? "asc",
6236
+ limit: input.limit,
6237
+ ...after(input)
6238
+ })).rows.map(toChannelRow);
5739
6239
  return (await drain$1((page) => db.findMany("channels", {
5740
6240
  index: "all",
5741
6241
  where: {},
5742
- limit: PAGE$3,
6242
+ limit: PAGE$4,
5743
6243
  ...page
5744
6244
  }))).map(toChannelRow);
5745
6245
  },
6246
+ async getChannels(ids) {
6247
+ const unique = [...new Set(ids)];
6248
+ if (unique.length === 0) return [];
6249
+ return (await db.findByKeys("channels", unique.map((id) => ({ id })))).flatMap((row) => row ? [toChannelRow(row)] : []);
6250
+ },
5746
6251
  async findChannelByName(name) {
5747
6252
  const row = await db.findOne("channels", { name });
5748
6253
  return row === null ? null : toChannelRow(row);
@@ -5750,6 +6255,625 @@ const createCoreReads = (db, storage) => {
5750
6255
  };
5751
6256
  };
5752
6257
  //#endregion
6258
+ //#region ../../packages/server/dist/core/iosDevices.mjs
6259
+ /**
6260
+ * A device's UDID: 40 hex digits, or 8 and 16 joined by a hyphen. The same
6261
+ * rule as `normalizeIosUdid` of `@hot-updater/protocol/native-artifact`,
6262
+ * implemented here so the server's runtime never loads the artifact readers.
6263
+ */
6264
+ const UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
6265
+ /** The form the registry stores and compares a UDID in, or null for text that isn't one. */
6266
+ const normalizeIosUdid = (value) => {
6267
+ const trimmed = value.trim();
6268
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
6269
+ };
6270
+ /** `ios_devices.name`'s bound in core's schema. */
6271
+ const NAME_MAX_LENGTH = 100;
6272
+ /** `ios_devices.requested_by` and `approved_by`'s bound: an email address. */
6273
+ const EMAIL_MAX_LENGTH = 320;
6274
+ /** `ios_devices.apple_issuer_id`'s bound. */
6275
+ const ISSUER_MAX_LENGTH = 64;
6276
+ /** The one row of `ios_device_account`. */
6277
+ const ACCOUNT_ROW = "registry";
6278
+ /** `ios_devices.apple_error`'s bound. */
6279
+ const ERROR_MAX_LENGTH = 512;
6280
+ const STATUSES = [
6281
+ "pending",
6282
+ "approved",
6283
+ "registered"
6284
+ ];
6285
+ const OUTCOMES = [
6286
+ "registered",
6287
+ "refused",
6288
+ "disabled",
6289
+ "missing"
6290
+ ];
6291
+ /** The `apple_error` of a device Apple has disabled. */
6292
+ const IOS_DEVICE_DISABLED_ERROR = "Disabled in the Apple account.";
6293
+ /** The `apple_error` of a registered device Apple no longer lists. */
6294
+ const IOS_DEVICE_MISSING_ERROR = "Gone from the Apple account. Approve it again to register it.";
6295
+ /** A device or registry request core cannot store: the caller's input. */
6296
+ var IosDeviceInputError = class extends TypeError {
6297
+ name = "IosDeviceInputError";
6298
+ };
6299
+ const pick$1 = (row) => ({
6300
+ id: row.id,
6301
+ udid: row.udid,
6302
+ name: row.name,
6303
+ status: row.status,
6304
+ requested_by: row.requested_by ?? null,
6305
+ created_at_ms: row.created_at_ms,
6306
+ approved_by: row.approved_by ?? null,
6307
+ approved_at_ms: row.approved_at_ms ?? null,
6308
+ registered_at_ms: row.registered_at_ms ?? null,
6309
+ apple_issuer_id: row.apple_issuer_id ?? null,
6310
+ apple_error: row.apple_error ?? null,
6311
+ build_id: row.build_id ?? null
6312
+ });
6313
+ const udidOf = (udid) => {
6314
+ const key = typeof udid === "string" ? normalizeIosUdid(udid) : null;
6315
+ if (key === null) throw new IosDeviceInputError("Invalid iOS device: udid must be 40 hex digits, or 8 and 16 joined by a hyphen.");
6316
+ return key;
6317
+ };
6318
+ const nameOf = (name) => {
6319
+ const trimmed = typeof name === "string" ? name.trim() : "";
6320
+ if (trimmed.length === 0 || trimmed.length > NAME_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: name must be 1 to ${NAME_MAX_LENGTH} characters.`);
6321
+ return trimmed;
6322
+ };
6323
+ /** An email, lower-cased, or null for the CLI. */
6324
+ const personOf = (value, field) => {
6325
+ if (value === null) return null;
6326
+ const email = typeof value === "string" ? value.trim().toLowerCase() : "";
6327
+ 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.`);
6328
+ return email;
6329
+ };
6330
+ /** Apple's words, on one line and within the column's bound. */
6331
+ const errorText = (text) => {
6332
+ const line = text.replace(/\s+/gu, " ").trim();
6333
+ return line.length > ERROR_MAX_LENGTH ? `${line.slice(0, 511)}…` : line;
6334
+ };
6335
+ /**
6336
+ * The iOS device registry: the iPhones and iPads a team asked to install ad hoc
6337
+ * builds on. The Console writes requests and approvals, and the CLI what Apple
6338
+ * said, each over the row it read.
6339
+ */
6340
+ const createIosDeviceApi = (db, { now = Date.now } = {}) => {
6341
+ const findIosDevice = async (udid) => {
6342
+ const key = normalizeIosUdid(udid);
6343
+ if (key === null) return null;
6344
+ const row = await db.findOne("ios_devices", { udid: key });
6345
+ return row === null ? null : pick$1(row);
6346
+ };
6347
+ /**
6348
+ * The issuer of the registry's earliest registration among its rows, by
6349
+ * when and then by ID, or null when no row names one: read only while the
6350
+ * registry has no account yet, in one read of its first registration. A
6351
+ * row names an issuer exactly when it has a registration time: both are
6352
+ * set by its first registration and never cleared.
6353
+ */
6354
+ const accountOfRows = async () => {
6355
+ const { rows } = await db.findMany("ios_devices", {
6356
+ index: "byRegistration",
6357
+ where: {},
6358
+ order: "asc",
6359
+ limit: 1,
6360
+ range: { gte: 0 }
6361
+ });
6362
+ return (rows[0] === void 0 ? null : pick$1(rows[0]))?.apple_issuer_id ?? null;
6363
+ };
6364
+ return {
6365
+ async listIosDevices(input) {
6366
+ if (input.status !== void 0 && !STATUSES.includes(input.status)) throw new IosDeviceInputError(`Invalid iOS device status: ${String(input.status)}. Expected ${STATUSES.join(", ")}.`);
6367
+ const page = {
6368
+ order: input.order ?? "asc",
6369
+ limit: input.limit,
6370
+ ...after(input)
6371
+ };
6372
+ const { rows } = input.status === void 0 ? await db.findMany("ios_devices", {
6373
+ index: "all",
6374
+ where: {},
6375
+ ...page
6376
+ }) : await db.findMany("ios_devices", {
6377
+ index: "byStatus",
6378
+ where: { status: input.status },
6379
+ ...page
6380
+ });
6381
+ return rows.map(pick$1);
6382
+ },
6383
+ findIosDevice,
6384
+ async requestIosDevice(input) {
6385
+ const udid = udidOf(input.udid);
6386
+ const name = nameOf(input.name);
6387
+ const requestedBy = personOf(input.requestedBy, "requestedBy");
6388
+ const existing = await db.findOne("ios_devices", { udid });
6389
+ if (existing !== null) return {
6390
+ device: pick$1(existing),
6391
+ created: false
6392
+ };
6393
+ const device = {
6394
+ id: createUUIDv7(),
6395
+ udid,
6396
+ name,
6397
+ status: "pending",
6398
+ requested_by: requestedBy,
6399
+ created_at_ms: now(),
6400
+ approved_by: null,
6401
+ approved_at_ms: null,
6402
+ registered_at_ms: null,
6403
+ apple_issuer_id: null,
6404
+ apple_error: null,
6405
+ build_id: null
6406
+ };
6407
+ try {
6408
+ await db.transaction(async (tx) => {
6409
+ tx.create("ios_devices", device);
6410
+ });
6411
+ } catch (error) {
6412
+ if (error instanceof DatabaseConstraintError && error.reason === "unique") {
6413
+ const winner = await db.findOne("ios_devices", { udid });
6414
+ if (winner !== null) return {
6415
+ device: pick$1(winner),
6416
+ created: false
6417
+ };
6418
+ }
6419
+ throw error;
6420
+ }
6421
+ return {
6422
+ device,
6423
+ created: true
6424
+ };
6425
+ },
6426
+ async approveIosDevice(id, input) {
6427
+ const name = input.name === void 0 ? void 0 : nameOf(input.name);
6428
+ const approvedBy = personOf(input.approvedBy, "approvedBy");
6429
+ return db.transaction(async (tx) => {
6430
+ const row = await tx.findOne("ios_devices", { id });
6431
+ if (row === null) return null;
6432
+ const device = pick$1(row);
6433
+ const set = {
6434
+ ...name === void 0 || name === device.name ? {} : { name },
6435
+ ...device.status === "pending" ? {
6436
+ status: "approved",
6437
+ approved_by: approvedBy,
6438
+ approved_at_ms: now()
6439
+ } : {}
6440
+ };
6441
+ if (Object.keys(set).length === 0) return device;
6442
+ tx.update("ios_devices", row, set);
6443
+ return {
6444
+ ...device,
6445
+ ...set
6446
+ };
6447
+ });
6448
+ },
6449
+ async renameIosDevice(id, input) {
6450
+ const name = nameOf(input);
6451
+ return db.transaction(async (tx) => {
6452
+ const row = await tx.findOne("ios_devices", { id });
6453
+ if (row === null) return null;
6454
+ const device = pick$1(row);
6455
+ if (device.name === name) return device;
6456
+ tx.update("ios_devices", row, { name });
6457
+ return {
6458
+ ...device,
6459
+ name
6460
+ };
6461
+ });
6462
+ },
6463
+ async recordIosDeviceOutcome({ id, seen, issuerId, outcome, reason }) {
6464
+ if (!OUTCOMES.includes(outcome)) throw new IosDeviceInputError(`Invalid iOS device outcome: ${String(outcome)}. Expected ${OUTCOMES.join(", ")}.`);
6465
+ 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.`);
6466
+ return db.transaction(async (tx) => {
6467
+ const row = await tx.findOne("ios_devices", { id });
6468
+ if (row === null) return null;
6469
+ const device = pick$1(row);
6470
+ if (device.status !== seen.status || device.approved_at_ms !== seen.approvedAtMs || device.apple_issuer_id !== null && device.apple_issuer_id !== issuerId) return null;
6471
+ let set;
6472
+ switch (outcome) {
6473
+ case "registered":
6474
+ if (device.status === "pending") return null;
6475
+ set = {
6476
+ status: "registered",
6477
+ registered_at_ms: device.registered_at_ms ?? now(),
6478
+ apple_issuer_id: issuerId,
6479
+ apple_error: null
6480
+ };
6481
+ break;
6482
+ case "refused":
6483
+ if (device.status !== "approved") return null;
6484
+ set = { apple_error: errorText(reason === void 0 || reason.trim() === "" ? "Apple refused it." : reason) };
6485
+ break;
6486
+ case "disabled":
6487
+ if (device.status === "pending") return null;
6488
+ set = { apple_error: IOS_DEVICE_DISABLED_ERROR };
6489
+ break;
6490
+ case "missing":
6491
+ if (device.status !== "registered") return null;
6492
+ set = {
6493
+ status: "pending",
6494
+ approved_by: null,
6495
+ approved_at_ms: null,
6496
+ apple_error: IOS_DEVICE_MISSING_ERROR
6497
+ };
6498
+ }
6499
+ if (Object.entries(set).some(([column, value]) => device[column] !== (value ?? null))) tx.update("ios_devices", row, set);
6500
+ return {
6501
+ ...device,
6502
+ ...set
6503
+ };
6504
+ });
6505
+ },
6506
+ async markIosDevicesInBuild({ buildId, ids }) {
6507
+ for (const id of new Set(ids)) await db.transaction(async (tx) => {
6508
+ const row = await tx.findOne("ios_devices", { id });
6509
+ if (row === null || typeof row.build_id === "string" && row.build_id >= buildId) return;
6510
+ tx.update("ios_devices", row, { build_id: buildId });
6511
+ });
6512
+ },
6513
+ async findIosDeviceAccount() {
6514
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6515
+ const issuerId = existing === null ? await accountOfRows() : existing.apple_issuer_id;
6516
+ return issuerId === null ? null : { issuerId };
6517
+ },
6518
+ async claimIosDeviceAccount(issuerId) {
6519
+ 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.`);
6520
+ const answer = (held) => ({
6521
+ issuerId: held,
6522
+ claimed: held === issuerId
6523
+ });
6524
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6525
+ if (existing !== null) return answer(existing.apple_issuer_id);
6526
+ const holder = await accountOfRows() ?? issuerId;
6527
+ try {
6528
+ await db.transaction(async (tx) => {
6529
+ tx.create("ios_device_account", {
6530
+ id: ACCOUNT_ROW,
6531
+ apple_issuer_id: holder,
6532
+ claimed_at_ms: now()
6533
+ });
6534
+ });
6535
+ return answer(holder);
6536
+ } catch (error) {
6537
+ if (error instanceof DatabaseConstraintError && (error.reason === "exists" || error.reason === "unique")) {
6538
+ const winner = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6539
+ if (winner !== null) return answer(winner.apple_issuer_id);
6540
+ }
6541
+ throw error;
6542
+ }
6543
+ },
6544
+ async deleteIosDevice(id, only) {
6545
+ const requestedBy = only?.requestedBy === void 0 ? void 0 : personOf(only.requestedBy, "requestedBy");
6546
+ return db.transaction(async (tx) => {
6547
+ const row = await tx.findOne("ios_devices", { id });
6548
+ if (row === null) return null;
6549
+ const device = pick$1(row);
6550
+ if (only?.status !== void 0 && device.status !== only.status || requestedBy !== void 0 && device.requested_by !== requestedBy) return null;
6551
+ await tx.delete("ios_devices", row);
6552
+ return device;
6553
+ });
6554
+ }
6555
+ };
6556
+ };
6557
+ //#endregion
6558
+ //#region ../../packages/server/dist/core/nativeBuildDestinations.mjs
6559
+ /** Store destinations accepted for each native platform. */
6560
+ const NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
6561
+ android: [
6562
+ "play-internal",
6563
+ "play-closed",
6564
+ "play-open",
6565
+ "play-production"
6566
+ ],
6567
+ ios: ["testflight"]
6568
+ };
6569
+ //#endregion
6570
+ //#region ../../packages/server/dist/core/labels.mjs
6571
+ /**
6572
+ * The counter of a channel and platform's release labels: one
6573
+ * `label_sequences` row, which every writer of the pair reads and bumps.
6574
+ */
6575
+ const labelSequenceId = (channelId, platform) => `releases/${platform}/${channelId}`;
6576
+ /** The pairs a channel's counters belong to, which deleting it removes. */
6577
+ const LABEL_PLATFORMS = ["ios", "android"];
6578
+ /**
6579
+ * A channel and platform whose releases written before labels have none
6580
+ * yet, or that has no counter: the write stops before taking a label, the
6581
+ * core labels the pair with `fillLabels`, and the write runs again.
6582
+ */
6583
+ var NeedsLabelFill = class extends Error {
6584
+ channelId;
6585
+ platform;
6586
+ constructor(channelId, platform) {
6587
+ super(`Release labels of ${platform} ${channelId} need a fill first.`);
6588
+ this.channelId = channelId;
6589
+ this.platform = platform;
6590
+ }
6591
+ };
6592
+ const createLabelAllocator = (tx, used, caughtUp) => {
6593
+ const sequences = /* @__PURE__ */ new Map();
6594
+ return {
6595
+ async next(channelId, platform) {
6596
+ const id = labelSequenceId(channelId, platform);
6597
+ let sequence = sequences.get(id);
6598
+ if (sequence === void 0) {
6599
+ const row = await tx.findOne("label_sequences", { id });
6600
+ if (row === null || !row.is_filled) {
6601
+ const channel = row === null ? await tx.findOne("channels", { id: channelId }) : null;
6602
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) throw new NeedsLabelFill(channelId, platform);
6603
+ }
6604
+ const read = row?.last_label ?? 0;
6605
+ sequence = {
6606
+ row,
6607
+ read,
6608
+ last: read
6609
+ };
6610
+ sequences.set(id, sequence);
6611
+ used.set(id, {
6612
+ channelId,
6613
+ platform,
6614
+ read
6615
+ });
6616
+ }
6617
+ sequence.last += 1;
6618
+ return sequence.last;
6619
+ },
6620
+ caughtUp(channelId, platform) {
6621
+ caughtUp.set(labelSequenceId(channelId, platform), {
6622
+ channelId,
6623
+ platform
6624
+ });
6625
+ },
6626
+ flush() {
6627
+ for (const [id, { row, read, last }] of sequences) if (row === null) tx.create("label_sequences", {
6628
+ id,
6629
+ last_label: last,
6630
+ is_filled: true
6631
+ });
6632
+ else if (last !== read) tx.update("label_sequences", row, { last_label: last });
6633
+ }
6634
+ };
6635
+ };
6636
+ const FILL_BATCH = 25;
6637
+ const PAGE$3 = 500;
6638
+ /**
6639
+ * Labels a channel and platform's releases that have none, in ID order,
6640
+ * which is the order they were created in, and marks its counter filled:
6641
+ * each batch reads the counter and its rows guarded, so a concurrent fill or
6642
+ * write serializes on the counter and skips what another labeled. With
6643
+ * `dryRun`, it only counts them. Answers how many it labeled.
6644
+ */
6645
+ const fillLabels = async (db, { channelId, platform }, { dryRun = false } = {}) => {
6646
+ const id = labelSequenceId(channelId, platform);
6647
+ let labeled = 0;
6648
+ let batchSize = FILL_BATCH;
6649
+ const label = async (ids) => {
6650
+ for (let at = 0; at < ids.length;) {
6651
+ const batch = ids.slice(at, at + batchSize);
6652
+ try {
6653
+ labeled += await db.transaction(async (tx) => {
6654
+ const counter = await tx.findOne("label_sequences", { id });
6655
+ let last = counter?.last_label ?? 0;
6656
+ let count = 0;
6657
+ for (const releaseId of batch) {
6658
+ const row = await tx.findOne("releases", { id: releaseId });
6659
+ if (row === null || typeof row.label === "number") continue;
6660
+ last += 1;
6661
+ count += 1;
6662
+ tx.update("releases", row, { label: last });
6663
+ }
6664
+ if (counter === null) tx.create("label_sequences", {
6665
+ id,
6666
+ last_label: last,
6667
+ is_filled: false
6668
+ });
6669
+ else if (last !== counter.last_label) tx.update("label_sequences", counter, { last_label: last });
6670
+ return count;
6671
+ });
6672
+ at += batch.length;
6673
+ } catch (error) {
6674
+ if (batchSize > 1 && error instanceof DatabaseConstraintError && error.reason === "too_large") {
6675
+ batchSize = Math.max(1, Math.floor(batchSize / 2));
6676
+ continue;
6677
+ }
6678
+ throw error;
6679
+ }
6680
+ }
6681
+ };
6682
+ let cursor;
6683
+ do {
6684
+ const page = await db.findMany("releases", {
6685
+ index: "byChannelPlatform",
6686
+ where: {
6687
+ channel_id: channelId,
6688
+ platform
6689
+ },
6690
+ limit: PAGE$3,
6691
+ ...cursor === void 0 ? {} : { cursor }
6692
+ });
6693
+ const unlabeled = page.rows.filter((row) => typeof row.label !== "number").map((row) => row.id);
6694
+ if (dryRun) labeled += unlabeled.length;
6695
+ else await label(unlabeled);
6696
+ cursor = page.next;
6697
+ } while (cursor !== void 0);
6698
+ if (dryRun) return labeled;
6699
+ await db.transaction(async (tx) => {
6700
+ const counter = await tx.findOne("label_sequences", { id });
6701
+ if (counter === null) tx.create("label_sequences", {
6702
+ id,
6703
+ last_label: 0,
6704
+ is_filled: true
6705
+ });
6706
+ else if (!counter.is_filled) tx.update("label_sequences", counter, { is_filled: true });
6707
+ });
6708
+ return labeled;
6709
+ };
6710
+ /**
6711
+ * Reads what a pair's fill writes, its counter and its label index, without
6712
+ * writing: a database without release labels' schema, such as one a 1.2
6713
+ * prerelease migrated, fails here as the fill would. The schema is the
6714
+ * database's, so one pair tells. Two reads.
6715
+ */
6716
+ const probeLabelSchema = async (db, { channelId, platform }) => {
6717
+ await db.findOne("label_sequences", { id: labelSequenceId(channelId, platform) });
6718
+ await db.findMany("releases", {
6719
+ index: "byLabel",
6720
+ where: {
6721
+ channel_id: channelId,
6722
+ platform,
6723
+ label: 0
6724
+ },
6725
+ limit: 1
6726
+ });
6727
+ };
6728
+ const REPAIRS = 4;
6729
+ const RACES = 32;
6730
+ /**
6731
+ * Runs a release write that takes labels, in one transaction with the
6732
+ * counters it bumps. A pair that still needs its fill is filled, and the
6733
+ * write runs again; so is a pair whose catch-up made the write too large for
6734
+ * the store. A label another row holds, such as an index item a release
6735
+ * deleted by a server of an earlier release left on a key-value store, is
6736
+ * skipped: its counters move past it and the write runs again.
6737
+ */
6738
+ const writeWithLabels = async (db, write) => {
6739
+ const filled = /* @__PURE__ */ new Set();
6740
+ const fill = async (pairs) => {
6741
+ for (const pair of pairs) {
6742
+ filled.add(labelSequenceId(pair.channelId, pair.platform));
6743
+ await fillLabels(db, pair);
6744
+ }
6745
+ };
6746
+ for (let repairs = 0, races = 0;;) {
6747
+ const used = /* @__PURE__ */ new Map();
6748
+ const caughtUp = /* @__PURE__ */ new Map();
6749
+ try {
6750
+ return await db.transaction(async (tx) => {
6751
+ used.clear();
6752
+ caughtUp.clear();
6753
+ const labels = createLabelAllocator(tx, used, caughtUp);
6754
+ const result = await write(tx, labels);
6755
+ labels.flush();
6756
+ return result;
6757
+ });
6758
+ } catch (error) {
6759
+ const needs = error instanceof NeedsLabelFill ? [error] : error instanceof DatabaseConstraintError && error.reason === "too_large" ? [...caughtUp.values()] : [];
6760
+ if (needs.length > 0) {
6761
+ const fresh = needs.some(({ channelId, platform }) => !filled.has(labelSequenceId(channelId, platform)));
6762
+ if (fresh || repairs < REPAIRS) {
6763
+ if (!fresh) repairs += 1;
6764
+ await fill(needs);
6765
+ continue;
6766
+ }
6767
+ }
6768
+ if (error instanceof DatabaseConstraintError && error.reason === "unique" && error.model === "releases" && used.size > 0) {
6769
+ if (await db.transaction(async (tx) => {
6770
+ const moves = [];
6771
+ for (const [id, { channelId, read }] of used) {
6772
+ const counter = await tx.findOne("label_sequences", { id });
6773
+ if (counter !== null) {
6774
+ if (counter.last_label !== read) return false;
6775
+ moves.push(() => tx.update("label_sequences", counter, { last_label: read + 1 }));
6776
+ continue;
6777
+ }
6778
+ const channel = await tx.findOne("channels", { id: channelId });
6779
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) return false;
6780
+ moves.push(() => tx.create("label_sequences", {
6781
+ id,
6782
+ last_label: read + 1,
6783
+ is_filled: true
6784
+ }));
6785
+ }
6786
+ for (const move of moves) move();
6787
+ return true;
6788
+ }) ? (repairs += 1) <= REPAIRS : (races += 1) <= RACES) continue;
6789
+ }
6790
+ throw error;
6791
+ }
6792
+ }
6793
+ };
6794
+ /**
6795
+ * Labels a scope's releases a server of an earlier release wrote after its
6796
+ * newest labeled one, oldest first, before the write takes its own label:
6797
+ * `latest` is the scope's newest release, so a labeled one costs no read.
6798
+ * Answers the labels it gave, by release ID.
6799
+ */
6800
+ const catchUpLabels = async (tx, labels, latest) => {
6801
+ const given = /* @__PURE__ */ new Map();
6802
+ if (latest === null || typeof latest.label === "number") return given;
6803
+ const unlabeled = [];
6804
+ let cursor;
6805
+ scan: do {
6806
+ const page = await tx.findMany("releases", {
6807
+ index: "byScope",
6808
+ where: { scope_key: latest.scope_key },
6809
+ order: "desc",
6810
+ limit: FILL_BATCH,
6811
+ ...cursor === void 0 ? {} : { cursor }
6812
+ });
6813
+ for (const row of page.rows) {
6814
+ if (typeof row.label === "number") break scan;
6815
+ unlabeled.push(row);
6816
+ }
6817
+ cursor = page.next;
6818
+ } while (cursor !== void 0);
6819
+ labels.caughtUp(latest.channel_id, latest.platform);
6820
+ for (const row of unlabeled.reverse()) {
6821
+ const { id, channel_id, platform } = toReleaseRow(row);
6822
+ const label = await labels.next(channel_id, platform);
6823
+ tx.update("releases", row, { label });
6824
+ given.set(id, label);
6825
+ }
6826
+ return given;
6827
+ };
6828
+ /**
6829
+ * The channels and platforms whose releases need labels: a scope whose
6830
+ * newest release has none, or a pair without a filled counter. Releases a
6831
+ * server of an earlier release wrote in a filled pair come after its
6832
+ * labeled ones in their scope, so the newest release of each scope tells.
6833
+ * Two reads per scope, one per pair.
6834
+ */
6835
+ const pendingLabelPairs = async (db) => {
6836
+ const pairs = /* @__PURE__ */ new Map();
6837
+ for (let last = "";;) {
6838
+ const { rows } = await db.findMany("releases", {
6839
+ index: "scopes",
6840
+ where: {},
6841
+ limit: 1,
6842
+ range: { gt: last }
6843
+ });
6844
+ if (rows[0] === void 0) break;
6845
+ last = rows[0].scope_key;
6846
+ const { rows: newest } = await db.findMany("releases", {
6847
+ index: "byScope",
6848
+ where: { scope_key: last },
6849
+ order: "desc",
6850
+ limit: 1
6851
+ });
6852
+ if (newest[0] === void 0) continue;
6853
+ const { channel_id: channelId, platform, label } = toReleaseRow(newest[0]);
6854
+ const id = labelSequenceId(channelId, platform);
6855
+ const pair = pairs.get(id) ?? {
6856
+ channelId,
6857
+ platform,
6858
+ pending: false
6859
+ };
6860
+ pair.pending ||= label === null;
6861
+ pairs.set(id, pair);
6862
+ }
6863
+ const pending = [];
6864
+ for (const [id, { channelId, platform, pending: unlabeled }] of pairs) {
6865
+ if (!unlabeled) {
6866
+ const counter = await db.findOne("label_sequences", { id });
6867
+ if (counter !== null && counter.is_filled) continue;
6868
+ }
6869
+ pending.push({
6870
+ channelId,
6871
+ platform
6872
+ });
6873
+ }
6874
+ return pending;
6875
+ };
6876
+ //#endregion
5753
6877
  //#region ../../packages/server/dist/core/writes.mjs
5754
6878
  const PAGE$2 = 500;
5755
6879
  /** Moves one bundle into or out of its platform's total and the overall total. */
@@ -5779,8 +6903,10 @@ const deleteBundle = async (tx, current) => {
5779
6903
  /**
5780
6904
  * Replaces a bundle's patches with `rows`: kept patches are updated where
5781
6905
  * they changed, others deleted or created, so no key is written twice.
6906
+ * `checkNew` sees each patch it is about to create, and refuses one by
6907
+ * throwing, which leaves the transaction's writes undone.
5782
6908
  */
5783
- const replaceBundlePatches = async (tx, bundle, rows) => {
6909
+ const replaceBundlePatches = async (tx, bundle, rows, checkNew) => {
5784
6910
  const wanted = new Map(rows.map((row) => [row.id, row]));
5785
6911
  const count = bundle._refs_bundle_patches_bundle_id ?? 0;
5786
6912
  let cursor;
@@ -5805,6 +6931,7 @@ const replaceBundlePatches = async (tx, bundle, rows) => {
5805
6931
  if (page.next === void 0) break;
5806
6932
  cursor = page.next;
5807
6933
  }
6934
+ if (checkNew !== void 0) for (const row of wanted.values()) await checkNew(row);
5808
6935
  for (const row of wanted.values()) tx.create("bundle_patches", row);
5809
6936
  };
5810
6937
  /** A channel by name, created when missing; a concurrent creator's row is returned instead. */
@@ -5827,7 +6954,11 @@ const insertChannel = async (db, row) => {
5827
6954
  throw error;
5828
6955
  }
5829
6956
  };
5830
- /** Deletes a channel no release or native build uses: 1 read, 1 query, 1 write. */
6957
+ /**
6958
+ * Deletes a channel no release or native build uses, with its label
6959
+ * counters, so one created again with its name starts at 1: 3 reads,
6960
+ * 1 query, 1 write.
6961
+ */
5831
6962
  const deleteChannel = (db, id) => db.transaction(async (tx) => {
5832
6963
  const row = await tx.findOne("channels", { id });
5833
6964
  if (row === null) return {
@@ -5847,6 +6978,10 @@ const deleteChannel = (db, id) => db.transaction(async (tx) => {
5847
6978
  deleted: false,
5848
6979
  reason: "not_empty"
5849
6980
  };
6981
+ for (const platform of LABEL_PLATFORMS) {
6982
+ const counter = await tx.findOne("label_sequences", { id: labelSequenceId(id, platform) });
6983
+ if (counter !== null) await tx.delete("label_sequences", counter);
6984
+ }
5850
6985
  await tx.delete("channels", row);
5851
6986
  return { deleted: true };
5852
6987
  });
@@ -5867,6 +7002,27 @@ const GIT_COMMIT_HASH_MAX_LENGTH = 255;
5867
7002
  * and looks up nothing else.
5868
7003
  */
5869
7004
  const BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
7005
+ /** `native_builds.sandbox_url_scheme`'s bound in core's schema. */
7006
+ const SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
7007
+ /**
7008
+ * A URL scheme as RFC 3986 spells it, in lower case: what a sandbox build's
7009
+ * artifact registers, as `@hot-updater/protocol/native-artifact` reads it.
7010
+ */
7011
+ const URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
7012
+ /**
7013
+ * A bundle identifier or application ID, as an artifact reports it: letters,
7014
+ * digits, dots, dashes and underscores, which a scope key holds as they are.
7015
+ */
7016
+ const APP_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;
7017
+ /** A fingerprint hash as a Release Catalog scope key holds it. */
7018
+ const FINGERPRINT_HASH = /^[A-Za-z0-9._~-]{1,255}$/;
7019
+ /** How each kind of artifact can install. */
7020
+ const DISTRIBUTIONS = {
7021
+ apk: ["direct"],
7022
+ app: ["direct"],
7023
+ aab: ["store"],
7024
+ ipa: ["direct", "store"]
7025
+ };
5870
7026
  /** A native build or scope core cannot store or look up: the caller's input. */
5871
7027
  var NativeBuildInputError = class extends TypeError {
5872
7028
  name = "NativeBuildInputError";
@@ -5888,24 +7044,73 @@ const pick = (row) => ({
5888
7044
  build_number: row.build_number ?? null,
5889
7045
  submitted_to: row.submitted_to ?? null,
5890
7046
  submitted_at_ms: row.submitted_at_ms ?? null,
5891
- submitted_version: row.submitted_version ?? null
7047
+ submitted_version: row.submitted_version ?? null,
7048
+ is_store_build: row.is_store_build === true,
7049
+ is_sandbox: row.is_sandbox === true,
7050
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
7051
+ export_method: row.export_method ?? null,
7052
+ native_app_version: row.native_app_version ?? null
5892
7053
  });
5893
- /** The store track each platform's builds are submitted to. */
5894
- const SUBMISSION_DESTINATIONS = {
5895
- android: "play-internal",
5896
- ios: "testflight"
5897
- };
7054
+ /** The export methods an `.ipa` registers with. */
7055
+ const EXPORT_METHODS = /* @__PURE__ */ new Set([
7056
+ "app-store",
7057
+ "ad-hoc",
7058
+ "development",
7059
+ "enterprise"
7060
+ ]);
7061
+ /**
7062
+ * How many older builds of a scope one read takes, looking for one older than
7063
+ * a bundle when a build made after the bundle is the newest.
7064
+ */
7065
+ const OLDER_BUILDS_PAGE = 20;
7066
+ /**
7067
+ * How many pages of older builds that look reads before it answers null: 100
7068
+ * builds made after the bundle in one scope, where a deploy's new bundle has
7069
+ * none or a few registered while it deploys.
7070
+ */
7071
+ const OLDER_BUILDS_PAGES = 5;
7072
+ /** How many times a mark runs again after losing its scope's mark to another. */
7073
+ const MARK_ATTEMPTS = 8;
5898
7074
  /** `native_builds.build_number`'s bound in core's schema. */
5899
7075
  const BUILD_NUMBER_MAX_LENGTH = 64;
5900
7076
  /** `native_builds.submitted_version`'s bound in core's schema. */
5901
7077
  const SUBMITTED_VERSION_MAX_LENGTH = 255;
7078
+ const checkedScopeKey = (scopeKey) => {
7079
+ 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.`);
7080
+ return scopeKey;
7081
+ };
7082
+ /**
7083
+ * How a registered artifact installs: an `.ipa` by its export method, and
7084
+ * `unknown` for one whose export no profile confirmed, which no lookup asks
7085
+ * for, so it is never reused as either.
7086
+ */
7087
+ const registeredDistribution = (kind, exportMethod) => kind !== "ipa" ? DISTRIBUTIONS[kind][0] : exportMethod === void 0 || exportMethod === null ? "unknown" : exportMethod === "app-store" ? "store" : "direct";
7088
+ /**
7089
+ * A sandbox build scope's key, which names no channel: the app ID, URL
7090
+ * scheme, artifact kind and distribution in its place, then the fingerprint,
7091
+ * or the app-version strategy and the exact app version. `v1:sandbox:` is no
7092
+ * Release Catalog strategy, so it never meets a normal build's key.
7093
+ */
7094
+ const sandboxScopeKey = (scope, sandbox) => {
7095
+ const { appId, urlScheme, artifactKind, distribution } = sandbox;
7096
+ 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;
7097
+ if (problem !== null) throw new NativeBuildInputError(`Invalid sandbox build scope: ${problem}.`);
7098
+ const target = scope.fingerprintHash === null ? `app-version:${encodeURIComponent(scope.appVersion)}` : `fingerprint:${scope.fingerprintHash}`;
7099
+ return checkedScopeKey(`v1:sandbox:${scope.platform}:${appId}:${urlScheme}:${artifactKind}:${distribution}:${target}`);
7100
+ };
5902
7101
  /**
5903
7102
  * A native build scope's key: the Release Catalog scope key of a
5904
7103
  * fingerprint, or of the app-version strategy followed by the exact app
5905
7104
  * version the build compiled in. One key serves both strategies, so one
5906
- * index finds the newest build of either.
7105
+ * index finds the newest build of either. A sandbox scope's key names no
7106
+ * channel, so pull requests find a sandbox build on any.
5907
7107
  */
5908
7108
  const nativeBuildScopeKey = (scope) => {
7109
+ const { sandbox } = scope;
7110
+ if (sandbox !== void 0 && sandbox !== null) {
7111
+ if (sandbox.distribution !== "direct" && sandbox.distribution !== "store") throw new NativeBuildInputError("Invalid sandbox build scope: its distribution must be direct or store.");
7112
+ return sandboxScopeKey(scope, sandbox);
7113
+ }
5909
7114
  let scopeKey;
5910
7115
  try {
5911
7116
  const channelKey = encodeChannelKey(scope.channel);
@@ -5922,32 +7127,126 @@ const nativeBuildScopeKey = (scope) => {
5922
7127
  } catch (error) {
5923
7128
  throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
5924
7129
  }
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;
7130
+ return checkedScopeKey(scopeKey);
7131
+ };
7132
+ /** The channel row a registration names, or the refusal of its channel. */
7133
+ const channelIdOf = (channel) => {
7134
+ try {
7135
+ return `channel:${encodeChannelKey(channel)}`;
7136
+ } catch (error) {
7137
+ throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
7138
+ }
7139
+ };
7140
+ /**
7141
+ * A registration's scope key, from the registration's own facts: a sandbox
7142
+ * build's from what its artifact says, whatever `sandbox` it names.
7143
+ */
7144
+ const registrationScopeKey = (registration) => {
7145
+ channelIdOf(registration.channel);
7146
+ return registration.isSandbox === true ? sandboxScopeKey(registration, {
7147
+ appId: registration.sandboxAppId,
7148
+ urlScheme: registration.sandboxUrlScheme,
7149
+ artifactKind: registration.artifact.kind,
7150
+ distribution: registeredDistribution(registration.artifact.kind, registration.exportMethod)
7151
+ }) : nativeBuildScopeKey({
7152
+ ...registration,
7153
+ sandbox: null
7154
+ });
7155
+ };
7156
+ /**
7157
+ * Refuses a patch from a sandbox build's built-in bundle: no deploy patches
7158
+ * from one, so no store or test install of the app gets a patch made for a
7159
+ * sandbox build. One unique read of the base.
7160
+ */
7161
+ const refuseSandboxPatchBase = async (db, baseBundleId) => {
7162
+ 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
7163
  };
5928
7164
  /** Whether `bundleId` is a native build's built-in bundle: one unique read. */
5929
7165
  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 }) => {
7166
+ const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, sandboxAppId, exportMethod, nativeAppVersion, artifact }) => {
5931
7167
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
5932
7168
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
5933
7169
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
5934
7170
  if (channel.trim().length === 0) return "channel is required";
7171
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
7172
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
7173
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
7174
+ 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`;
7175
+ }
7176
+ if (sandboxAppId !== void 0 && sandboxAppId !== null) {
7177
+ if (isSandbox !== true) return "sandboxAppId is a sandbox build's, and this isn't one";
7178
+ if (typeof sandboxAppId !== "string" || !APP_ID.test(sandboxAppId)) return "sandboxAppId must be the artifact's bundle identifier or application ID, up to 255 characters";
7179
+ }
7180
+ if (isSandbox === true) {
7181
+ if (sandboxUrlScheme === void 0 || sandboxUrlScheme === null) return "a sandbox build needs the sandboxUrlScheme its artifact registers";
7182
+ 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";
7183
+ }
5935
7184
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
5936
7185
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
5937
7186
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
5938
7187
  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`;
7188
+ 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
7189
  const kinds = ARTIFACT_KINDS[platform];
5940
7190
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
7191
+ if (exportMethod !== void 0 && exportMethod !== null) {
7192
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
7193
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
7194
+ }
5941
7195
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
5942
7196
  return null;
5943
7197
  };
7198
+ /** The other install target of an iOS sandbox build's native code. */
7199
+ const SIBLING_KINDS = {
7200
+ app: "ipa",
7201
+ ipa: "app"
7202
+ };
7203
+ /**
7204
+ * Whether a build is one a person installs from its file: a Simulator `.app`,
7205
+ * or an `.ipa` exported for direct install, that no store took and that isn't
7206
+ * the store build. One rule for a sibling and the build it is found from, so
7207
+ * a build that shows its sibling is shown by it.
7208
+ */
7209
+ 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");
7210
+ /**
7211
+ * The scope key of the other install target of a sandbox build, from its own
7212
+ * key's app ID and URL scheme, which hold no colon, and its row's fingerprint
7213
+ * or app version, through `sandboxScopeKey`; null for a key it didn't make.
7214
+ */
7215
+ const siblingSandboxScopeKey = (build, artifactKind) => {
7216
+ const [version, sandbox, platform, appId, urlScheme] = build.scope_key.split(":");
7217
+ if (version !== "v1" || sandbox !== "sandbox" || platform !== build.platform || appId === void 0 || urlScheme === void 0) return null;
7218
+ const target = build.fingerprint_hash === null ? {
7219
+ platform: build.platform,
7220
+ fingerprintHash: null,
7221
+ appVersion: build.app_version ?? ""
7222
+ } : {
7223
+ platform: build.platform,
7224
+ fingerprintHash: build.fingerprint_hash,
7225
+ appVersion: null
7226
+ };
7227
+ try {
7228
+ return sandboxScopeKey(target, {
7229
+ appId,
7230
+ urlScheme,
7231
+ artifactKind: build.artifact_kind,
7232
+ distribution: registeredDistribution(build.artifact_kind, build.export_method)
7233
+ }) === build.scope_key ? sandboxScopeKey(target, {
7234
+ appId,
7235
+ urlScheme,
7236
+ artifactKind,
7237
+ distribution: "direct"
7238
+ }) : null;
7239
+ } catch {
7240
+ return null;
7241
+ }
7242
+ };
5944
7243
  /** The native build registry: core's `native_builds` and the built-in bundle rows. */
5945
7244
  const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
5946
7245
  async registerNativeBuild(registration) {
5947
7246
  const problem = problemOf(registration);
5948
7247
  if (problem !== null) throw new NativeBuildInputError(`Invalid native build: ${problem}.`);
5949
- const scopeKey = nativeBuildScopeKey(registration);
5950
- const channelId = `channel:${encodeChannelKey(registration.channel)}`;
7248
+ const scopeKey = registrationScopeKey(registration);
7249
+ const channelId = channelIdOf(registration.channel);
5951
7250
  const { embeddedBundle } = registration;
5952
7251
  const row = {
5953
7252
  id: registration.id,
@@ -5966,7 +7265,12 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
5966
7265
  build_number: registration.buildNumber ?? null,
5967
7266
  submitted_to: null,
5968
7267
  submitted_at_ms: null,
5969
- submitted_version: null
7268
+ submitted_version: null,
7269
+ is_store_build: false,
7270
+ is_sandbox: registration.isSandbox === true,
7271
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
7272
+ export_method: registration.exportMethod ?? null,
7273
+ native_app_version: registration.nativeAppVersion ?? null
5970
7274
  };
5971
7275
  for (let attempt = 1;; attempt += 1) {
5972
7276
  await insertChannel(db, {
@@ -6000,25 +7304,82 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6000
7304
  const row = await db.findOne("native_builds", { id });
6001
7305
  return row === null ? null : pick(row);
6002
7306
  },
7307
+ async findNativeBuildByBuiltInBundle(bundleId) {
7308
+ const row = await db.findOne("native_builds", { min_bundle_id: bundleId });
7309
+ return row === null ? null : pick(row);
7310
+ },
6003
7311
  async findNativeBuild(scope, options) {
6004
7312
  const scopeKey = nativeBuildScopeKey(scope);
6005
7313
  const buildKey = options?.buildKey;
6006
7314
  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", {
7315
+ const artifactKind = options?.artifactKind;
7316
+ 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 ")}.`);
7317
+ const ofKind = (row) => artifactKind === void 0 || row.artifact_kind === artifactKind;
7318
+ if (options?.storeBuild) {
7319
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
7320
+ return marked === null || !ofKind(marked) ? null : pick(marked);
7321
+ }
7322
+ const read = (limit, before) => {
7323
+ const page = {
7324
+ order: "desc",
7325
+ limit,
7326
+ ...before === void 0 ? {} : { range: { lt: before } }
7327
+ };
7328
+ return buildKey !== void 0 ? db.findMany("native_builds", {
7329
+ index: "byBuildKey",
7330
+ where: {
7331
+ scope_key: scopeKey,
7332
+ build_key: buildKey
7333
+ },
7334
+ ...page
7335
+ }) : artifactKind !== void 0 ? db.findMany("native_builds", {
7336
+ index: "byScopeKind",
7337
+ where: {
7338
+ scope_key: scopeKey,
7339
+ artifact_kind: artifactKind
7340
+ },
7341
+ ...page
7342
+ }) : db.findMany("native_builds", {
7343
+ index: "byScope",
7344
+ where: { scope_key: scopeKey },
7345
+ ...page
7346
+ });
7347
+ };
7348
+ const bundleId = options?.builtInOlderThan;
7349
+ if (bundleId !== void 0 && scope.sandbox !== void 0 && scope.sandbox !== null) return null;
7350
+ const { rows } = await read(1);
7351
+ const newest = (rows[0] === void 0 ? void 0 : pick(rows[0])) ?? (artifactKind !== void 0 && buildKey === void 0 ? await db.findMany("native_builds", {
6008
7352
  index: "byScope",
6009
7353
  where: { scope_key: scopeKey },
6010
7354
  order: "desc",
6011
7355
  limit: 1
6012
- }) : await db.findMany("native_builds", {
6013
- index: "byBuildKey",
6014
- where: {
6015
- scope_key: scopeKey,
6016
- build_key: buildKey
6017
- },
7356
+ }).then(({ rows: [row] }) => row?.artifact_kind === artifactKind ? pick(row) : void 0) : void 0);
7357
+ if (newest === void 0 || !ofKind(newest)) return null;
7358
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return newest;
7359
+ let before = newest.id;
7360
+ for (let page = 0; page < OLDER_BUILDS_PAGES; page += 1) {
7361
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
7362
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
7363
+ if (usable !== void 0) return ofKind(usable) ? pick(usable) : null;
7364
+ const last = older.at(-1);
7365
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
7366
+ before = last.id;
7367
+ }
7368
+ return null;
7369
+ },
7370
+ async findNativeBuildSibling(build) {
7371
+ const artifactKind = SIBLING_KINDS[build.artifact_kind];
7372
+ if (build.platform !== "ios" || !build.is_sandbox || artifactKind === void 0 || !isInstallTarget(build)) return null;
7373
+ const scopeKey = siblingSandboxScopeKey(build, artifactKind);
7374
+ if (scopeKey === null) return null;
7375
+ const { rows } = await db.findMany("native_builds", {
7376
+ index: "byScope",
7377
+ where: { scope_key: scopeKey },
6018
7378
  order: "desc",
6019
7379
  limit: 1
6020
7380
  });
6021
- return rows[0] === void 0 ? null : pick(rows[0]);
7381
+ const sibling = rows[0] === void 0 ? null : pick(rows[0]);
7382
+ return sibling !== null && isInstallTarget(sibling) ? sibling : null;
6022
7383
  },
6023
7384
  async recordNativeBuildSubmission(id, { destination, version }) {
6024
7385
  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 +7387,8 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6026
7387
  const row = await tx.findOne("native_builds", { id });
6027
7388
  if (row === null) return null;
6028
7389
  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}.`);
7390
+ 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}.`);
7391
+ 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
7392
  const set = {
6031
7393
  submitted_to: destination,
6032
7394
  submitted_at_ms: now(),
@@ -6039,6 +7401,46 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6039
7401
  };
6040
7402
  });
6041
7403
  },
7404
+ async markNativeBuild(id, { storeBuild }) {
7405
+ for (let attempt = 1;; attempt += 1) try {
7406
+ return await db.transaction(async (tx) => {
7407
+ const row = await tx.findOne("native_builds", { id });
7408
+ if (row === null) return null;
7409
+ const build = pick(row);
7410
+ if (!storeBuild) {
7411
+ if (build.is_store_build) tx.update("native_builds", row, { is_store_build: false });
7412
+ return {
7413
+ nativeBuild: {
7414
+ ...build,
7415
+ is_store_build: false
7416
+ },
7417
+ previous: null
7418
+ };
7419
+ }
7420
+ if (build.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
7421
+ if (build.is_store_build) return {
7422
+ nativeBuild: build,
7423
+ previous: null
7424
+ };
7425
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build.scope_key });
7426
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
7427
+ tx.update("native_builds", row, { is_store_build: true });
7428
+ return {
7429
+ nativeBuild: {
7430
+ ...build,
7431
+ is_store_build: true
7432
+ },
7433
+ previous: holder === null ? null : {
7434
+ ...pick(holder),
7435
+ is_store_build: false
7436
+ }
7437
+ };
7438
+ });
7439
+ } catch (error) {
7440
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
7441
+ throw error;
7442
+ }
7443
+ },
6042
7444
  async deleteNativeBuild(id) {
6043
7445
  return db.transaction(async (tx) => {
6044
7446
  const row = await tx.findOne("native_builds", { id });
@@ -6094,44 +7496,43 @@ const checkScope = (scope) => {
6094
7496
  });
6095
7497
  if (scope.strategy === "FINGERPRINT" !== (scope.fingerprintHash !== null) || scope.scopeKey !== expected) fail$1("INVALID_SCOPE", "Release catalog scope metadata is inconsistent");
6096
7498
  };
6097
- /** A scope's enabled releases, all of them, under the catalog's guard. */
6098
- const enabledReleases = async (tx, scopeKey) => {
7499
+ /** Every row of a paged read, as release rows. */
7500
+ const drainReleases = async (page) => {
6099
7501
  const rows = [];
6100
7502
  let cursor;
6101
7503
  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;
7504
+ const found = await page(cursor);
7505
+ rows.push(...found.rows.map((row) => toReleaseRow(row)));
7506
+ cursor = found.next;
6113
7507
  } while (cursor !== void 0);
6114
7508
  return rows;
6115
7509
  };
6116
- /** The scope's newest release id: `byScope` descending, limit 1. */
6117
- const latestReleaseId = async (tx, scopeKey) => {
7510
+ const enabledIn = (scopeKey, cursor) => ({
7511
+ index: "byScopeEnabled",
7512
+ where: {
7513
+ scope_key: scopeKey,
7514
+ enabled: true
7515
+ },
7516
+ limit: PAGE$1,
7517
+ ...cursor === void 0 ? {} : { cursor }
7518
+ });
7519
+ /** A scope's enabled releases, all of them, under the catalog's guard. */
7520
+ const enabledReleases = (tx, scopeKey) => drainReleases((cursor) => tx.findMany("releases", enabledIn(scopeKey, cursor)));
7521
+ /** The scope's newest release: `byScope` descending, limit 1. */
7522
+ const latestRelease = async (tx, scopeKey) => {
6118
7523
  const { rows } = await tx.findMany("releases", {
6119
7524
  index: "byScope",
6120
7525
  where: { scope_key: scopeKey },
6121
7526
  order: "desc",
6122
7527
  limit: 1
6123
7528
  });
6124
- return rows[0]?.id ?? null;
7529
+ return rows[0] === void 0 ? null : toReleaseRow(rows[0]);
6125
7530
  };
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;
7531
+ /** The scope's next catalog generation, compiled as `compilation`. */
7532
+ const nextCatalog = (scope, stored, compilation, updatedAtMs) => {
7533
+ const generation = (stored.catalog?.generation ?? 0) + 1;
6133
7534
  if (!Number.isSafeInteger(generation)) fail$1("CATALOG_GENERATION_EXHAUSTED", `Catalog "${scope.scopeKey}" exhausted its generation counter`);
6134
- const catalog = {
7535
+ return {
6135
7536
  scope_key: scope.scopeKey,
6136
7537
  catalog_id: stored.catalog?.catalog_id ?? createUUIDv7(),
6137
7538
  strategy: scope.strategy,
@@ -6146,6 +7547,26 @@ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
6146
7547
  is_tombstone: compilation.payload.releaseDescriptors.length === 0,
6147
7548
  updated_at_ms: updatedAtMs
6148
7549
  };
7550
+ };
7551
+ /**
7552
+ * Compiles a scope's enabled releases. A catalog over the size limit is
7553
+ * refused naming its channel and platform, and what frees room in it.
7554
+ */
7555
+ const compileScope = async (scope, enabled) => {
7556
+ try {
7557
+ return await compileReleaseCatalog({
7558
+ strategy: scope.strategy,
7559
+ releases: enabled.map(releaseRowToRelease)
7560
+ });
7561
+ } catch (error) {
7562
+ if (!(error instanceof ReleaseCatalogCompilationError) || error.code !== "CATALOG_OVERSIZE") throw error;
7563
+ 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.`);
7564
+ }
7565
+ };
7566
+ /** Compiles `enabled` and writes it as the scope's next catalog generation. */
7567
+ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
7568
+ const compilation = await compileScope(scope, enabled);
7569
+ const catalog = nextCatalog(scope, stored, compilation, updatedAtMs);
6149
7570
  const { scope_key: _scopeKey, ...set } = catalog;
6150
7571
  if (stored.row === null) tx.create("release_catalogs", catalog);
6151
7572
  else tx.update("release_catalogs", stored.row, set);
@@ -6167,11 +7588,16 @@ const readCatalog = async (tx, scopeKey) => {
6167
7588
  const assertHistory = (stored, hasReleases) => {
6168
7589
  if (stored.catalog === null && hasReleases) fail$1("CATALOG_IDENTITY_MISSING", "Catalog history is missing. Restore its catalog row from backup before rebuilding or deploying.");
6169
7590
  };
6170
- /** One release change and its scope's next catalog, inside `tx`. */
6171
- const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
7591
+ /**
7592
+ * One release change and its scope's next catalog, inside `tx`. An insert
7593
+ * takes its channel and platform's next label from `labels`, after labeling
7594
+ * the releases a server of an earlier release wrote in the scope since its
7595
+ * last labeled one.
7596
+ */
7597
+ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }, labels) => {
6172
7598
  checkScope(scope);
6173
7599
  const stored = await readCatalog(tx, scope.scopeKey);
6174
- const enabled = await enabledReleases(tx, scope.scopeKey);
7600
+ let enabled = await enabledReleases(tx, scope.scopeKey);
6175
7601
  if (bundle !== void 0) {
6176
7602
  insertBundle(tx, bundle.row);
6177
7603
  for (const patch of bundle.patches) tx.create("bundle_patches", patch);
@@ -6179,14 +7605,22 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
6179
7605
  let before = null;
6180
7606
  let release;
6181
7607
  if (change.operation === "insert") {
6182
- const latest = await latestReleaseId(tx, scope.scopeKey);
7608
+ if (labels === void 0) throw new Error("A release insert takes its label from an allocator.");
7609
+ const newest = await latestRelease(tx, scope.scopeKey);
7610
+ const latest = newest?.id ?? null;
6183
7611
  assertHistory(stored, latest !== null);
6184
7612
  const floor = [latest, bundle && isUUIDv7(bundle.row.id) ? bundle.row.id : null].filter((id) => id !== null).sort().at(-1);
6185
7613
  const id = change.row.id ?? createUUIDv7After(floor ?? null);
6186
7614
  if (latest !== null && id <= latest) fail$1("NON_MONOTONIC_RELEASE_ID", `Release "${id}" must sort after "${latest}"`);
7615
+ const given = await catchUpLabels(tx, labels, newest);
7616
+ if (given.size > 0) enabled = enabled.map((row) => given.has(row.id) ? {
7617
+ ...row,
7618
+ label: given.get(row.id)
7619
+ } : row);
6187
7620
  release = {
6188
7621
  ...change.row,
6189
- id
7622
+ id,
7623
+ label: await labels.next(scope.channelId, scope.platform)
6190
7624
  };
6191
7625
  if (release.scope_key !== scope.scopeKey || release.channel_id !== scope.channelId || release.platform !== scope.platform || release.strategy !== scope.strategy || release.fingerprint_hash !== scope.fingerprintHash || release.revision !== 1) fail$1("INVALID_SCOPE", "Inserted Release does not match its catalog scope");
6192
7626
  tx.create("releases", release);
@@ -6199,8 +7633,9 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
6199
7633
  await tx.delete("releases", row);
6200
7634
  release = null;
6201
7635
  } else {
7636
+ const { label: _label, ...update } = change.update;
6202
7637
  const set = {
6203
- ...change.update,
7638
+ ...update,
6204
7639
  revision: before.revision + 1
6205
7640
  };
6206
7641
  tx.update("releases", row, set);
@@ -6228,24 +7663,70 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
6228
7663
  */
6229
7664
  const changeReleases = (db, inputs) => {
6230
7665
  if (new Set(inputs.map(({ scope }) => scope.scopeKey)).size !== inputs.length) fail$1("INVALID_SCOPE", "A batch cannot change one catalog scope twice");
6231
- return db.transaction(async (tx) => {
7666
+ return writeWithLabels(db, async (tx, labels) => {
6232
7667
  const results = [];
6233
- for (const input of inputs) results.push(await changeRelease(tx, input));
7668
+ for (const input of inputs) results.push(await changeRelease(tx, input, labels));
6234
7669
  return results;
6235
7670
  });
6236
7671
  };
7672
+ /** Whether `current` is what the scope's enabled releases compile to. */
7673
+ 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;
7674
+ /** A compiled payload with its descriptors' labels left out. */
7675
+ const withoutLabels = (payload) => {
7676
+ const parsed = JSON.parse(payload);
7677
+ return JSON.stringify({
7678
+ ...parsed,
7679
+ releaseDescriptors: (parsed.releaseDescriptors ?? []).map(({ label: _label, ...descriptor }) => descriptor)
7680
+ });
7681
+ };
7682
+ /**
7683
+ * Whether `projected` differs from `current` only by release labels, as a
7684
+ * catalog compiled before its releases had them does.
7685
+ */
7686
+ const differsInLabelsOnly = (current, projected) => current.payload !== projected.payload && current.strategy === projected.strategy && current.channel_id === projected.channel_id && current.channel_key === projected.channel_key && current.platform === projected.platform && current.fingerprint_hash === projected.fingerprint_hash && withoutLabels(current.payload) === withoutLabels(projected.payload);
7687
+ /** The scope a catalog row names. */
7688
+ const catalogRowScope = (row) => ({
7689
+ channelId: row.channel_id,
7690
+ channelName: decodeChannelKey(row.channel_key),
7691
+ fingerprintHash: row.fingerprint_hash,
7692
+ platform: row.platform,
7693
+ scopeKey: row.scope_key,
7694
+ strategy: row.strategy
7695
+ });
7696
+ /**
7697
+ * What a rebuild of the scope's catalog would write, without writing: one
7698
+ * read of the catalog row and one of the scope's enabled releases. It needs
7699
+ * no transaction, whose guards would read the catalog again for each read
7700
+ * beneath it, nor the scope's newest release, which matters only to a scope
7701
+ * without a catalog row; that one is not found.
7702
+ */
7703
+ const preflightRebuild = async (db, scopeKey, updatedAtMs) => {
7704
+ const row = await db.findOne("release_catalogs", { scope_key: scopeKey });
7705
+ if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
7706
+ const current = toCatalogRow(row);
7707
+ const scope = catalogRowScope(current);
7708
+ checkScope(scope);
7709
+ const enabled = await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor)));
7710
+ const compilation = await compileScope(scope, enabled);
7711
+ const changed = !isCurrent(scope, current, compilation);
7712
+ const projectedCatalog = changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current;
7713
+ return {
7714
+ changed,
7715
+ labelsOnly: changed && differsInLabelsOnly(current, projectedCatalog),
7716
+ currentCatalog: current,
7717
+ diagnostics: compilation.diagnostics,
7718
+ projectedCatalog
7719
+ };
7720
+ };
6237
7721
  /** Recompiles a scope's catalog from its enabled releases inside `tx`; an unchanged catalog is not rewritten. */
6238
7722
  const rebuildScope = async (tx, scope, updatedAtMs) => {
6239
7723
  checkScope(scope);
6240
7724
  const stored = await readCatalog(tx, scope.scopeKey);
6241
- assertHistory(stored, await latestReleaseId(tx, scope.scopeKey) !== null);
7725
+ assertHistory(stored, await latestRelease(tx, scope.scopeKey) !== null);
6242
7726
  const enabled = await enabledReleases(tx, scope.scopeKey);
6243
- const compilation = await compileReleaseCatalog({
6244
- strategy: scope.strategy,
6245
- releases: enabled.map(releaseRowToRelease)
6246
- });
7727
+ const compilation = await compileScope(scope, enabled);
6247
7728
  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 {
7729
+ if (current !== null && isCurrent(scope, current, compilation)) return {
6249
7730
  catalog: current,
6250
7731
  current,
6251
7732
  changed: false,
@@ -6261,6 +7742,7 @@ const rebuildScope = async (tx, scope, updatedAtMs) => {
6261
7742
  };
6262
7743
  //#endregion
6263
7744
  //#region ../../packages/server/dist/core/operations.mjs
7745
+ const CATALOG_PAGE = 100;
6264
7746
  /** Carries a preflight's result out of the transaction it stops, so nothing is written. */
6265
7747
  var Preflight = class extends Error {
6266
7748
  result;
@@ -6349,14 +7831,7 @@ const mutationResult = ({ catalog, release }) => ({
6349
7831
  const catalogScope = async (tx, scopeKey) => {
6350
7832
  const row = await tx.findOne("release_catalogs", { scope_key: scopeKey });
6351
7833
  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
- };
7834
+ return catalogRowScope(toCatalogRow(row));
6360
7835
  };
6361
7836
  /**
6362
7837
  * Core's typed writes: each runs in one engine transaction rooted at the
@@ -6385,7 +7860,11 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
6385
7860
  for (const { release } of deployments) if (!channels.has(release.channel)) channels.set(release.channel, await ensureChannel(release.channel));
6386
7861
  const platforms = /* @__PURE__ */ new Map();
6387
7862
  for (const deployment of deployments) {
6388
- if (!("bundleId" in deployment) || platforms.has(deployment.bundleId)) continue;
7863
+ if (!("bundleId" in deployment)) {
7864
+ for (const { baseBundleId } of deployment.bundle.patches ?? []) await refuseSandboxPatchBase(db, baseBundleId);
7865
+ continue;
7866
+ }
7867
+ if (platforms.has(deployment.bundleId)) continue;
6389
7868
  const row = await db.findOne("bundles", { id: deployment.bundleId });
6390
7869
  if (row === null) throw new DatabaseBundleNotFoundError(deployment.bundleId);
6391
7870
  if (await isBuiltInBundle(db, deployment.bundleId)) throw new ReleaseManagementError("TARGET_RELEASE_INVALID", `Bundle "${deployment.bundleId}" is a native build's built-in bundle, which no release publishes.`);
@@ -6495,7 +7974,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
6495
7974
  if (targetChannel.length === 0) throw new ReleaseManagementError("TARGET_RELEASE_INVALID", "Promotion requires a target channel.");
6496
7975
  const channel = await ensureChannel(targetChannel);
6497
7976
  const updatedAtMs = now();
6498
- return db.transaction(async (tx) => {
7977
+ return writeWithLabels(db, async (tx, labels) => {
6499
7978
  const { release: source, scope: sourceScope } = await loadTarget(tx, input);
6500
7979
  checkSource(source);
6501
7980
  const targetScope = scopeOf$1(channel, source.platform, source.fingerprint_hash);
@@ -6523,12 +8002,13 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
6523
8002
  },
6524
8003
  updatedAtMs
6525
8004
  }) : null;
8005
+ const { label: _label, ...copied } = source;
6526
8006
  const target = await changeRelease(tx, {
6527
8007
  scope: targetScope,
6528
8008
  change: {
6529
8009
  operation: "insert",
6530
8010
  row: {
6531
- ...source,
8011
+ ...copied,
6532
8012
  id: createUUIDv7After(floor ?? null, updatedAtMs),
6533
8013
  revision: 1,
6534
8014
  scope_key: targetScope.scopeKey,
@@ -6543,7 +8023,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
6543
8023
  }
6544
8024
  },
6545
8025
  updatedAtMs
6546
- });
8026
+ }, labels);
6547
8027
  return {
6548
8028
  source: moved === null ? null : mutationResult(moved),
6549
8029
  target: mutationResult(target)
@@ -6560,17 +8040,38 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
6560
8040
  };
6561
8041
  });
6562
8042
  },
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
- });
8043
+ preflightReleaseCatalogRebuild: (scopeKey) => preflightRebuild(db, scopeKey, now()),
8044
+ fillReleaseLabels: async ({ dryRun = false, catalogs = true } = {}) => {
8045
+ let releases = 0;
8046
+ const pairs = await pendingLabelPairs(db);
8047
+ if (dryRun && pairs[0] !== void 0) await probeLabelSchema(db, pairs[0]);
8048
+ for (const pair of pairs) releases += await fillLabels(db, pair, { dryRun });
8049
+ let rebuilt = 0;
8050
+ if (catalogs) {
8051
+ let cursor;
8052
+ do {
8053
+ const page = await db.findMany("release_catalogs", {
8054
+ index: "all",
8055
+ where: {},
8056
+ limit: CATALOG_PAGE,
8057
+ ...cursor === void 0 ? {} : { cursor }
8058
+ });
8059
+ for (const row of page.rows) {
8060
+ if (row.is_tombstone) continue;
8061
+ const preflight = await preflightRebuild(db, row.scope_key, now()).catch(() => null);
8062
+ if (preflight === null || !preflight.labelsOnly) continue;
8063
+ rebuilt += 1;
8064
+ if (dryRun) continue;
8065
+ const updatedAtMs = now();
8066
+ await db.transaction((tx) => rebuildScope(tx, catalogRowScope(toCatalogRow(row)), updatedAtMs));
8067
+ }
8068
+ cursor = page.next;
8069
+ } while (cursor !== void 0);
8070
+ }
8071
+ return {
8072
+ releases,
8073
+ catalogs: rebuilt
8074
+ };
6574
8075
  },
6575
8076
  ensureChannel,
6576
8077
  deleteChannel: (id) => deleteChannel(db, id),
@@ -6589,7 +8090,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
6589
8090
  if (patches !== void 0) await replaceBundlePatches(tx, current, bundleToPatchRows({
6590
8091
  ...next,
6591
8092
  patches
6592
- }));
8093
+ }), (row) => refuseSandboxPatchBase(tx, row.base_bundle_id));
6593
8094
  }),
6594
8095
  deleteBundles: async (ids) => {
6595
8096
  try {
@@ -6651,6 +8152,7 @@ const createCoreApi = (db, storage, options = {}) => {
6651
8152
  ...reads,
6652
8153
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
6653
8154
  ...createNativeBuildApi(db, options),
8155
+ ...createIosDeviceApi(db, options),
6654
8156
  /** One read, which checks the schema settings first. */
6655
8157
  ready: async () => {
6656
8158
  await reads.listReleaseCatalogs({ limit: 1 });
@@ -6843,6 +8345,10 @@ const answer = async (operation) => {
6843
8345
  error: error.message
6844
8346
  }, status);
6845
8347
  }
8348
+ if (error instanceof ReleaseCatalogCompilationError && error.code === "CATALOG_OVERSIZE") return json$2({
8349
+ code: error.code,
8350
+ error: error.message
8351
+ }, 400);
6846
8352
  if (error instanceof DatabaseBundleNotFoundError) return json$2({
6847
8353
  code: "BUNDLE_NOT_FOUND",
6848
8354
  error: error.message
@@ -6862,18 +8368,22 @@ const LIMITS = {
6862
8368
  defaultValue: 50,
6863
8369
  maxValue: 500
6864
8370
  };
8371
+ /** The most IDs one request names: a lookup's, or a write's. */
8372
+ const MAX_IDS = 100;
6865
8373
  /** `order`, `cursor`, and `limit`: one keyset page. */
6866
- const keyset = (url, maxValue = LIMITS.maxValue) => {
6867
- const order = url.searchParams.get("order") ?? "desc";
8374
+ const keyset = (url, maxValue = LIMITS.maxValue, defaultOrder = "desc") => {
8375
+ const order = url.searchParams.get("order") ?? defaultOrder;
6868
8376
  if (order !== "asc" && order !== "desc") throw new HandlerBadRequestError("order must be 'asc' or 'desc'.");
6869
8377
  const limitParam = url.searchParams.get("limit");
6870
8378
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
6871
8379
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
6872
8380
  const cursor = url.searchParams.get("cursor");
8381
+ const through = url.searchParams.get("through");
6873
8382
  return {
6874
8383
  order,
6875
8384
  limit,
6876
- ...cursor === null ? {} : { after: cursor }
8385
+ ...cursor === null ? {} : { after: cursor },
8386
+ ...through === null ? {} : { through }
6877
8387
  };
6878
8388
  };
6879
8389
  /** A page and the cursor of the next one, when the page is full. */
@@ -6971,7 +8481,8 @@ const nativeBuildScopeOf = (url) => {
6971
8481
  const fingerprintHash = params.get("fingerprintHash");
6972
8482
  const appVersion = params.get("appVersion");
6973
8483
  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 ? {
8484
+ const sandbox = sandboxScopeOf(params);
8485
+ const scope = fingerprintHash !== null ? {
6975
8486
  platform,
6976
8487
  channel,
6977
8488
  fingerprintHash,
@@ -6982,17 +8493,49 @@ const nativeBuildScopeOf = (url) => {
6982
8493
  fingerprintHash: null,
6983
8494
  appVersion
6984
8495
  };
8496
+ return sandbox === null ? scope : {
8497
+ ...scope,
8498
+ sandbox
8499
+ };
8500
+ };
8501
+ /** The query parameters a sandbox lookup names, all four or none. */
8502
+ const SANDBOX_SCOPE_PARAMS = [
8503
+ "sandboxAppId",
8504
+ "sandboxUrlScheme",
8505
+ "artifactKind",
8506
+ "distribution"
8507
+ ];
8508
+ /**
8509
+ * A lookup's sandbox scope: null without one, and a bad request for one
8510
+ * named in part. Core checks each value.
8511
+ */
8512
+ const sandboxScopeOf = (params) => {
8513
+ const [appId, urlScheme, artifactKind, distribution] = SANDBOX_SCOPE_PARAMS.map((name) => params.get(name));
8514
+ const named = [
8515
+ appId,
8516
+ urlScheme,
8517
+ artifactKind,
8518
+ distribution
8519
+ ].filter((value) => value !== null).length;
8520
+ if (named === 0) return null;
8521
+ if (named !== SANDBOX_SCOPE_PARAMS.length) throw new HandlerBadRequestError(`A sandbox build lookup needs ${SANDBOX_SCOPE_PARAMS.join(", ")}.`);
8522
+ return {
8523
+ appId,
8524
+ urlScheme,
8525
+ artifactKind,
8526
+ distribution
8527
+ };
6985
8528
  };
6986
8529
  /** A native build or scope core refuses: a bad request. */
6987
8530
  const refusingInvalid = async (operation) => {
6988
8531
  try {
6989
8532
  return await operation();
6990
8533
  } catch (error) {
6991
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
8534
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
6992
8535
  throw error;
6993
8536
  }
6994
8537
  };
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));
8538
+ 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
8539
  const scopeKeyOf = (params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "";
6997
8540
  /** Every admin route's handler, by the name `ADMIN_ROUTES` mounts it under. */
6998
8541
  const createAdminRouteHandlers = () => ({
@@ -7025,12 +8568,40 @@ const createAdminRouteHandlers = () => ({
7025
8568
  const rows = await core.listReleaseCatalogs(input);
7026
8569
  return page(rows, input, (row) => row.scope_key);
7027
8570
  }),
7028
- /** With `name`, the one channel of that name: 1 read. */
8571
+ /** Up to 100 scope keys that have releases, after `cursor`: one seek each. */
8572
+ listReleaseScopeKeys: onCore(async (core, request) => {
8573
+ const input = keyset(new URL(request.url), 100, "asc");
8574
+ if (input.order !== "asc" || input.through !== void 0) throw new HandlerBadRequestError("Release scopes are listed ascending, by limit and cursor only.");
8575
+ const rows = await core.listReleaseScopeKeys({
8576
+ limit: input.limit,
8577
+ ...input.after === void 0 ? {} : { after: input.after }
8578
+ });
8579
+ return page(rows, input, (scopeKey) => scopeKey);
8580
+ }),
8581
+ /**
8582
+ * With `name`, the one channel of that name: 1 read. With `ids`, the
8583
+ * channels of up to 100 IDs: 1 batch read. With `limit` or `cursor`, one
8584
+ * page by name. With none, every channel, as servers before pages answered.
8585
+ */
7029
8586
  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 });
8587
+ const url = new URL(request.url);
8588
+ const name = url.searchParams.get("name");
8589
+ if (name !== null) {
8590
+ const channel = await core.findChannelByName(name);
8591
+ return channel === null ? notFound() : json$2({ data: channel });
8592
+ }
8593
+ const ids = url.searchParams.get("ids");
8594
+ if (ids !== null) {
8595
+ const list = ids.split(",").filter((id) => id.length > 0);
8596
+ if (list.length === 0 || list.length > MAX_IDS) throw new HandlerBadRequestError(`Channels by ID take ids=<channel id>,... with 1 to ${MAX_IDS} ids.`);
8597
+ return json$2({ data: await core.getChannels(list) });
8598
+ }
8599
+ if (url.searchParams.has("limit") || url.searchParams.has("cursor")) {
8600
+ const input = keyset(url, LIMITS.maxValue, "asc");
8601
+ const rows = await core.listChannels(input);
8602
+ return page(rows, input, (row) => row.name);
8603
+ }
8604
+ return json$2({ data: await core.listChannels() });
7034
8605
  }),
7035
8606
  /** The channel named in the body, created when missing. */
7036
8607
  createChannel: onCore(async (core, request) => {
@@ -7072,15 +8643,40 @@ const createAdminRouteHandlers = () => ({
7072
8643
  return row === null ? notFound() : json$2({ data: row });
7073
8644
  }),
7074
8645
  rebuildReleaseCatalog: onCore(async (core, _request, params) => json$2({ data: await core.rebuildReleaseCatalog(scopeKeyOf(params)) })),
8646
+ /**
8647
+ * The release a label names, or `null`: never 404, which tells a client
8648
+ * the server has no such route.
8649
+ */
8650
+ getReleaseByLabel: onCore(async (core, request) => {
8651
+ const url = new URL(request.url);
8652
+ const channel = url.searchParams.get("channel");
8653
+ const platform = platformOf(url);
8654
+ const label = Number(url.searchParams.get("label"));
8655
+ if (channel === null || channel.length === 0 || platform === void 0 || !Number.isSafeInteger(label) || label < 1) throw new HandlerBadRequestError("A release label lookup takes channel, platform, and a label of 1 or more.");
8656
+ return json$2({ data: await core.getReleaseByLabel({
8657
+ channel,
8658
+ platform,
8659
+ label
8660
+ }) });
8661
+ }),
8662
+ fillReleaseLabels: onCore(async (core, request) => {
8663
+ const body = await request.json().catch(() => ({}));
8664
+ const input = body !== null && typeof body === "object" ? body : {};
8665
+ return json$2({ data: await core.fillReleaseLabels({
8666
+ dryRun: input.dryRun === true,
8667
+ catalogs: input.catalogs !== false
8668
+ }) });
8669
+ }),
7075
8670
  updateBundle: onCore(async (core, request, params) => {
7076
8671
  const bundleId = requireRouteParam(params, "id");
7077
- await core.updateBundle(bundleId, bundleUpdateOf(await request.json(), bundleId));
8672
+ const update = bundleUpdateOf(await request.json(), bundleId);
8673
+ await refusingInvalid(() => core.updateBundle(bundleId, update));
7078
8674
  return noContent();
7079
8675
  }),
7080
8676
  countBundles: onCore(async (core, request) => json$2({ data: await core.countBundles(platformOf(new URL(request.url))) })),
7081
8677
  countBundleChildren: onCore(async (core, request) => {
7082
8678
  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.");
8679
+ 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
8680
  return json$2({ data: await core.countBundleChildren(ids) });
7085
8681
  }),
7086
8682
  listBundleChildren: onCore(async (core, request, params) => {
@@ -7098,7 +8694,7 @@ const createAdminRouteHandlers = () => ({
7098
8694
  deployReleases: onCore(async (core, request) => {
7099
8695
  const { deployments } = await body(request);
7100
8696
  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);
8697
+ return json$2({ data: await refusingInvalid(() => core.deploy(deployments)) }, 201);
7102
8698
  }),
7103
8699
  promoteRelease: onCore(async (core, request, params) => {
7104
8700
  const input = await body(request);
@@ -7121,9 +8717,22 @@ const createAdminRouteHandlers = () => ({
7121
8717
  const url = new URL(request.url);
7122
8718
  const scope = nativeBuildScopeOf(url);
7123
8719
  const buildKey = url.searchParams.get("buildKey");
7124
- return json$2({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
8720
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
8721
+ const kind = url.searchParams.get("kind");
8722
+ const options = {
8723
+ ...buildKey === null ? {} : { buildKey },
8724
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
8725
+ ...builtInOlderThan === null ? {} : { builtInOlderThan },
8726
+ ...kind === null ? {} : { artifactKind: kind }
8727
+ };
8728
+ return json$2({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
8729
+ }),
8730
+ findNativeBuildSibling: onCore(async (core, _request, params) => {
8731
+ const build = await core.getNativeBuild(requireRouteParam(params, "id"));
8732
+ return json$2({ data: build === null ? null : await core.findNativeBuildSibling(build) });
7125
8733
  }),
7126
8734
  getNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
8735
+ findNativeBuildByBuiltInBundle: onCore(async (core, _request, params) => json$2({ data: await core.findNativeBuildByBuiltInBundle(requireRouteParam(params, "bundleId")) })),
7127
8736
  listNativeBuilds: onCore(async (core, request) => {
7128
8737
  const url = new URL(request.url);
7129
8738
  const input = keyset(url);
@@ -7135,14 +8744,97 @@ const createAdminRouteHandlers = () => ({
7135
8744
  }),
7136
8745
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
7137
8746
  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.");
8747
+ 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
8748
  const submission = {
7140
8749
  destination: input.destination,
7141
8750
  version: input.version
7142
8751
  };
7143
8752
  return json$2({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
7144
8753
  }),
8754
+ markNativeBuild: onCore(async (core, request, params) => {
8755
+ const input = await body(request);
8756
+ if (!isRecord$5(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
8757
+ const mark = { storeBuild: input.storeBuild };
8758
+ return json$2({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
8759
+ }),
7145
8760
  deleteNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
8761
+ listIosDevices: onCore(async (core, request) => {
8762
+ const url = new URL(request.url);
8763
+ const input = keyset(url);
8764
+ const status = url.searchParams.get("status");
8765
+ return page(await refusingInvalid(() => core.listIosDevices({
8766
+ ...input,
8767
+ ...status === null ? {} : { status }
8768
+ })), input, ({ id }) => id);
8769
+ }),
8770
+ findIosDevice: onCore(async (core, _request, params) => json$2({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
8771
+ requestIosDevice: onCore(async (core, request) => {
8772
+ const input = await body(request);
8773
+ 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.");
8774
+ const device = {
8775
+ udid: input.udid,
8776
+ name: input.name,
8777
+ requestedBy: input.requestedBy
8778
+ };
8779
+ return json$2({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
8780
+ }),
8781
+ approveIosDevice: onCore(async (core, request, params) => {
8782
+ const input = await body(request);
8783
+ 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.");
8784
+ const approval = {
8785
+ approvedBy: input.approvedBy,
8786
+ ...input.name === void 0 ? {} : { name: input.name }
8787
+ };
8788
+ return json$2({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
8789
+ }),
8790
+ renameIosDevice: onCore(async (core, request, params) => {
8791
+ const input = await body(request);
8792
+ if (!isText$2(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
8793
+ const name = input.name;
8794
+ return json$2({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
8795
+ }),
8796
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
8797
+ const input = await body(request);
8798
+ const seen = input.seen;
8799
+ 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.");
8800
+ const outcome = {
8801
+ id: requireRouteParam(params, "id"),
8802
+ seen: {
8803
+ status: seen.status,
8804
+ approvedAtMs: seen.approvedAtMs
8805
+ },
8806
+ issuerId: input.issuerId,
8807
+ outcome: input.outcome,
8808
+ ...input.reason === void 0 ? {} : { reason: input.reason }
8809
+ };
8810
+ return json$2({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
8811
+ }),
8812
+ claimIosDeviceAccount: onCore(async (core, request) => {
8813
+ const { issuerId } = await body(request);
8814
+ if (!isText$2(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
8815
+ return json$2({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
8816
+ }),
8817
+ findIosDeviceAccount: onCore(async (core) => json$2({ data: await core.findIosDeviceAccount() })),
8818
+ markIosDevicesInBuild: onCore(async (core, request) => {
8819
+ const { buildId, ids } = await body(request);
8820
+ 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.");
8821
+ if (ids.length > MAX_IDS) throw new HandlerBadRequestError(`Marking iOS devices in a build takes at most ${MAX_IDS} ids a request.`);
8822
+ await core.markIosDevicesInBuild({
8823
+ buildId,
8824
+ ids
8825
+ });
8826
+ return noContent();
8827
+ }),
8828
+ deleteIosDevice: onCore(async (core, request, params) => {
8829
+ const url = new URL(request.url);
8830
+ const status = url.searchParams.get("status");
8831
+ const requestedBy = url.searchParams.get("requestedBy");
8832
+ const only = {
8833
+ ...status === null ? {} : { status },
8834
+ ...requestedBy === null ? {} : { requestedBy }
8835
+ };
8836
+ return json$2({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
8837
+ }),
7146
8838
  deleteBundles: onCore(async (core, request) => {
7147
8839
  const { ids } = await body(request);
7148
8840
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -7197,6 +8889,21 @@ const ADMIN_ROUTES = [
7197
8889
  path: "/release-catalogs",
7198
8890
  handler: "listReleaseCatalogs"
7199
8891
  },
8892
+ {
8893
+ method: "GET",
8894
+ path: "/release-scopes",
8895
+ handler: "listReleaseScopeKeys"
8896
+ },
8897
+ {
8898
+ method: "GET",
8899
+ path: "/release-labels",
8900
+ handler: "getReleaseByLabel"
8901
+ },
8902
+ {
8903
+ method: "POST",
8904
+ path: "/release-labels/fill",
8905
+ handler: "fillReleaseLabels"
8906
+ },
7200
8907
  {
7201
8908
  method: "POST",
7202
8909
  path: "/release-catalogs/:scopeKey/rebuild",
@@ -7272,6 +8979,16 @@ const ADMIN_ROUTES = [
7272
8979
  path: "/native-builds/latest",
7273
8980
  handler: "findNativeBuild"
7274
8981
  },
8982
+ {
8983
+ method: "GET",
8984
+ path: "/native-builds/built-in/:bundleId",
8985
+ handler: "findNativeBuildByBuiltInBundle"
8986
+ },
8987
+ {
8988
+ method: "GET",
8989
+ path: "/native-builds/:id/sibling",
8990
+ handler: "findNativeBuildSibling"
8991
+ },
7275
8992
  {
7276
8993
  method: "GET",
7277
8994
  path: "/native-builds/:id",
@@ -7287,10 +9004,65 @@ const ADMIN_ROUTES = [
7287
9004
  path: "/native-builds/:id/submission",
7288
9005
  handler: "recordNativeBuildSubmission"
7289
9006
  },
9007
+ {
9008
+ method: "POST",
9009
+ path: "/native-builds/:id/store-build",
9010
+ handler: "markNativeBuild"
9011
+ },
7290
9012
  {
7291
9013
  method: "DELETE",
7292
9014
  path: "/native-builds/:id",
7293
9015
  handler: "deleteNativeBuild"
9016
+ },
9017
+ {
9018
+ method: "GET",
9019
+ path: "/ios-devices",
9020
+ handler: "listIosDevices"
9021
+ },
9022
+ {
9023
+ method: "POST",
9024
+ path: "/ios-devices",
9025
+ handler: "requestIosDevice"
9026
+ },
9027
+ {
9028
+ method: "GET",
9029
+ path: "/ios-devices/udid/:udid",
9030
+ handler: "findIosDevice"
9031
+ },
9032
+ {
9033
+ method: "POST",
9034
+ path: "/ios-devices/in-build",
9035
+ handler: "markIosDevicesInBuild"
9036
+ },
9037
+ {
9038
+ method: "GET",
9039
+ path: "/ios-devices/account",
9040
+ handler: "findIosDeviceAccount"
9041
+ },
9042
+ {
9043
+ method: "POST",
9044
+ path: "/ios-devices/account",
9045
+ handler: "claimIosDeviceAccount"
9046
+ },
9047
+ {
9048
+ method: "POST",
9049
+ path: "/ios-devices/:id/approval",
9050
+ handler: "approveIosDevice"
9051
+ },
9052
+ {
9053
+ method: "POST",
9054
+ path: "/ios-devices/:id/outcome",
9055
+ handler: "recordIosDeviceOutcome"
9056
+ },
9057
+ {
9058
+ method: "PATCH",
9059
+ path: "/ios-devices/:id",
9060
+ handler: "renameIosDevice"
9061
+ },
9062
+ {
9063
+ method: "DELETE",
9064
+ path: "/ios-devices/:id",
9065
+ handler: "deleteIosDevice"
7294
9066
  }
7295
9067
  ];
7296
9068
  //#endregion
@@ -7313,9 +9085,9 @@ const CATALOG_CACHE_CONTROL = "public, max-age=0, s-maxage=5";
7313
9085
  * background. `stale-if-error=0` keeps origin errors visible: without it,
7314
9086
  * Cloudflare serves a stale copy on error indefinitely.
7315
9087
  *
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
9088
+ * A device can see a catalog, or a scope's lack of one, up to 15 seconds
9089
+ * after a deploy or a Roll back replaced it: the origin's 5-second catalog
9090
+ * memo, then 5 seconds fresh and 5 stale at the CDN. A revoked API key can read a cached catalog up to
7319
9091
  * 10 seconds. Devices and caches that don't read the header keep
7320
9092
  * `Cache-Control`.
7321
9093
  */
@@ -7394,38 +9166,53 @@ const catalogResponse = async (catalog, request) => {
7394
9166
  };
7395
9167
  const createReleaseCatalogRouteHandlers = () => {
7396
9168
  const cache = /* @__PURE__ */ new Map();
9169
+ const evict = (insertedHit) => {
9170
+ const now = Date.now();
9171
+ let oldestMiss;
9172
+ let oldest;
9173
+ for (const [key, entry] of cache) if (entry.expiresAt <= now) cache.delete(key);
9174
+ else {
9175
+ if (entry.row === null) oldestMiss ??= key;
9176
+ oldest ??= key;
9177
+ }
9178
+ if (cache.size <= ORIGIN_CACHE_MAX_ENTRIES) return;
9179
+ const victim = oldestMiss ?? (insertedHit ? oldest : void 0);
9180
+ if (victim !== void 0) cache.delete(victim);
9181
+ };
7397
9182
  const inFlight = /* @__PURE__ */ new Map();
7398
- const loadCatalog = async (key, load) => {
7399
- const cached = cache.get(key);
9183
+ const loadRow = async (scopeKey, load) => {
9184
+ const cached = cache.get(scopeKey);
7400
9185
  if (cached !== void 0 && cached.expiresAt > Date.now()) {
7401
- cache.delete(key);
7402
- cache.set(key, cached);
7403
- return cached.catalog;
9186
+ cache.delete(scopeKey);
9187
+ cache.set(scopeKey, cached);
9188
+ return cached.row;
7404
9189
  }
7405
- if (cached !== void 0) cache.delete(key);
7406
- const pending = inFlight.get(key);
9190
+ if (cached !== void 0) cache.delete(scopeKey);
9191
+ const pending = inFlight.get(scopeKey);
7407
9192
  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;
9193
+ const next = load().then((row) => {
9194
+ cache.set(scopeKey, {
9195
+ row,
9196
+ expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
9197
+ });
9198
+ if (cache.size > ORIGIN_CACHE_MAX_ENTRIES) evict(row !== null);
9199
+ return row;
7421
9200
  });
7422
- inFlight.set(key, next);
9201
+ inFlight.set(scopeKey, next);
7423
9202
  try {
7424
9203
  return await next;
7425
9204
  } finally {
7426
- inFlight.delete(key);
9205
+ inFlight.delete(scopeKey);
7427
9206
  }
7428
9207
  };
9208
+ const loadCatalog = async (core, input) => {
9209
+ const scopeKey = releaseCatalogScopeKeyOf(input);
9210
+ const parsed = await loadRow(scopeKey, async () => {
9211
+ const row = await core.getReleaseCatalogRow(scopeKey);
9212
+ return row === null ? null : parseReleaseCatalogRow(row);
9213
+ });
9214
+ return projectParsedReleaseCatalogRow(parsed, input, scopeKey);
9215
+ };
7429
9216
  return {
7430
9217
  appVersionReleaseCatalog: async (params, request, { core }) => {
7431
9218
  const rawAppVersion = requireRouteParam(params, "appVersion");
@@ -7439,7 +9226,7 @@ const createReleaseCatalogRouteHandlers = () => {
7439
9226
  };
7440
9227
  const invalid = invalidScope(input);
7441
9228
  if (invalid) return invalid;
7442
- return catalogResponse(await loadCatalog(`app-version:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
9229
+ return catalogResponse(await loadCatalog(core, input), request);
7443
9230
  },
7444
9231
  fingerprintReleaseCatalog: async (params, request, { core }) => {
7445
9232
  const input = {
@@ -7450,7 +9237,7 @@ const createReleaseCatalogRouteHandlers = () => {
7450
9237
  };
7451
9238
  const invalid = invalidScope(input);
7452
9239
  if (invalid) return invalid;
7453
- return catalogResponse(await loadCatalog(`fingerprint:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
9240
+ return catalogResponse(await loadCatalog(core, input), request);
7454
9241
  },
7455
9242
  artifactV2: async (params, _request, { core }) => {
7456
9243
  const info = await core.getArtifactInfo(requireRouteParam(params, "targetBundleId"), requireRouteParam(params, "currentBundleId"), 2);
@@ -10733,13 +12520,80 @@ const breakdownOf = (rows) => {
10733
12520
  });
10734
12521
  };
10735
12522
  /**
12523
+ * The breakdown rows a failures read takes from one hour. An hour holds a
12524
+ * row per release, stage, reason, and detail that failed in it, a handful in
12525
+ * practice, and an incident across several releases and error codes still
12526
+ * fits; but a client with the app's API key can report any number of
12527
+ * details.
12528
+ */
12529
+ const FAILURE_ROWS_PER_HOUR = 20;
12530
+ /**
12531
+ * One query's stored rows: an hour's bound and one more row, on every shard,
12532
+ * so an hour past its bound costs at most one query's worth of rows more.
12533
+ */
12534
+ const FAILURE_QUERY_LIMIT = Math.min(PAGE, 168);
12535
+ /**
12536
+ * A channel's breakdown rows over a range, newest first, up to
12537
+ * {@link FAILURE_ROWS_PER_HOUR} an hour: 480 rows for a day, 14,400 for 30
12538
+ * days, however many details clients report. An hour that holds more is read
12539
+ * no further, and the read goes on from the hour before it with a new query;
12540
+ * the hour is listed in `cappedHours`, since its failures count only in part.
12541
+ * Every other hour counts every failure it holds.
12542
+ */
12543
+ const failureRowsByHour = async (db, platform, channel, timeRange) => {
12544
+ const read = (end, cursor) => db.findAggregates("insights_failures", {
12545
+ index: "byScope",
12546
+ where: {
12547
+ platform,
12548
+ channel
12549
+ },
12550
+ range: {
12551
+ gte: timeRange.start,
12552
+ lt: end
12553
+ },
12554
+ order: "desc",
12555
+ limit: FAILURE_QUERY_LIMIT,
12556
+ ...cursor === void 0 ? {} : { cursor }
12557
+ });
12558
+ const rows = [];
12559
+ const cappedHours = [];
12560
+ const perHour = /* @__PURE__ */ new Map();
12561
+ let end = timeRange.end;
12562
+ let cursor;
12563
+ while (end > timeRange.start) {
12564
+ const page = await read(end, cursor);
12565
+ let capped;
12566
+ for (const row of page.rows) {
12567
+ const hour = row.bucket_start_ms;
12568
+ const count = (perHour.get(hour) ?? 0) + 1;
12569
+ if (count > FAILURE_ROWS_PER_HOUR) {
12570
+ capped = hour;
12571
+ break;
12572
+ }
12573
+ perHour.set(hour, count);
12574
+ rows.push(row);
12575
+ }
12576
+ if (capped !== void 0) {
12577
+ cappedHours.unshift(capped);
12578
+ end = capped;
12579
+ cursor = void 0;
12580
+ } else if (page.next === void 0) break;
12581
+ else cursor = page.next;
12582
+ }
12583
+ return {
12584
+ rows,
12585
+ cappedHours
12586
+ };
12587
+ };
12588
+ /**
10736
12589
  * A release's or a channel's update failures. Since a release's first
10737
12590
  * report: its lifetime counters and failed installations. Over a time range
10738
12591
  * of at most 30 days: failures, failed checks, and the breakdown by stage,
10739
12592
  * reason, and detail, all summed from the breakdown's hourly rows; downloads
10740
12593
  * from the counters; failed installations from their sketches. A release reads hourly rows, a
10741
12594
  * channel daily rows past 48 hours like its activity; the breakdown's rows
10742
- * are hourly, so its coverage is the raw period's.
12595
+ * are hourly, so its coverage is the raw period's, and partial when an hour
12596
+ * held more breakdown rows than a read takes from it.
10743
12597
  */
10744
12598
  const getUpdateFailures = async (db, input, now, retention) => {
10745
12599
  const { platform, channel, releaseId, timeRange } = input;
@@ -10801,7 +12655,7 @@ const getUpdateFailures = async (db, input, now, retention) => {
10801
12655
  days,
10802
12656
  kept.hour
10803
12657
  ];
10804
- const [counters, failures, checks, active, rows] = await Promise.all([
12658
+ const [counters, failures, checks, active, { rows, cappedHours }] = await Promise.all([
10805
12659
  counterRows(db, parts, ...window),
10806
12660
  sketchRows(db, failure, ...window),
10807
12661
  days ? sketchRows(db, {
@@ -10809,25 +12663,17 @@ const getUpdateFailures = async (db, input, now, retention) => {
10809
12663
  scopeKind: "check"
10810
12664
  }, ...window) : [],
10811
12665
  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
- }))
12666
+ failureRowsByHour(db, platform, channel, timeRange)
10825
12667
  ]);
10826
12668
  const total = (field) => counters.reduce((sum, row) => sum + row[field], 0);
10827
12669
  const scoped = rows.filter((row) => FAILURE_STAGES.has(row.stage) && (releaseId === void 0 || row.release_id === releaseId));
10828
12670
  const failuresAt = (counted) => scoped.reduce((sum, row) => sum + (counted(row.stage) ? Math.max(0, row.events) : 0), 0);
12671
+ const coverage = coverageOf(timeRange.start, kept.hour);
10829
12672
  return {
10830
- coverage: coverageOf(timeRange.start, kept.hour),
12673
+ coverage: cappedHours.length === 0 ? coverage : {
12674
+ kind: "partial",
12675
+ sinceMs: coverage.sinceMs
12676
+ },
10831
12677
  measuredAtMs: at,
10832
12678
  failedUpdates: failuresAt((stage) => stage !== "check"),
10833
12679
  failedInstallations: failed(failures),
@@ -10839,7 +12685,8 @@ const getUpdateFailures = async (db, input, now, retention) => {
10839
12685
  failedInstallations: failed(checks),
10840
12686
  activeInstallations: countDistinct(mergeDistinct(active.map((row) => row.activity_users)))
10841
12687
  } } : {},
10842
- breakdown: breakdownOf(scoped)
12688
+ breakdown: breakdownOf(scoped),
12689
+ ...cappedHours.length === 0 ? {} : { cappedHours }
10843
12690
  };
10844
12691
  };
10845
12692
  //#endregion
@@ -12111,14 +13958,67 @@ const createFirestoreStore = ({ firestore, collection, nativePageSize }) => {
12111
13958
  };
12112
13959
  };
12113
13960
  //#endregion
13961
+ //#region src/googleCredential.ts
13962
+ const CLOUD_PLATFORM_SCOPE = "https://www.googleapis.com/auth/cloud-platform";
13963
+ /**
13964
+ * Resolves application default credentials as Firestore will, from
13965
+ * GOOGLE_APPLICATION_CREDENTIALS's file or the environment, for the app's
13966
+ * `projectId`, so it neither exchanges a token nor discovers a project
13967
+ * Firestore itself wouldn't. Only `applicationDefault()`'s credential: a
13968
+ * service account's or refresh token's was read from its file already.
13969
+ */
13970
+ const resolveApplicationDefault = async (credential, projectId) => {
13971
+ if (credential.constructor.name !== "ApplicationDefaultCredential") return;
13972
+ const { GoogleAuth } = await import("google-auth-library");
13973
+ await new GoogleAuth({
13974
+ scopes: [CLOUD_PLATFORM_SCOPE],
13975
+ ...projectId === void 0 ? {} : { projectId }
13976
+ }).getClient();
13977
+ };
13978
+ //#endregion
12114
13979
  //#region src/firebaseDatabase.ts
13980
+ /**
13981
+ * `store` that loads `credential` before its first call: one that cannot
13982
+ * load, such as GOOGLE_APPLICATION_CREDENTIALS naming a missing file, fails
13983
+ * that call with what is wrong. Firestore's own client would also reject a
13984
+ * promise nobody awaits, which ends a CLI process with a stack trace.
13985
+ */
13986
+ const withLoadedCredential = (store, credential, projectId) => {
13987
+ let loaded;
13988
+ const load = () => loaded ??= resolveApplicationDefault(credential, projectId).then(() => void 0, (error) => {
13989
+ loaded = void 0;
13990
+ throw new Error(`Could not load the Google credentials for Firestore: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
13991
+ });
13992
+ const { deleteConsumed } = store;
13993
+ return {
13994
+ ...store,
13995
+ get: async (keys) => {
13996
+ await load();
13997
+ return store.get(keys);
13998
+ },
13999
+ query: async (range) => {
14000
+ await load();
14001
+ return store.query(range);
14002
+ },
14003
+ write: async (ops) => {
14004
+ await load();
14005
+ return store.write(ops);
14006
+ },
14007
+ ...deleteConsumed && { deleteConsumed: async (keys) => {
14008
+ await load();
14009
+ return deleteConsumed.call(store, keys);
14010
+ } }
14011
+ };
14012
+ };
12115
14013
  const adapterOf = ({ databaseId, collection = FIREBASE_V1_COLLECTION, aggregateBatching: _, ...appOptions }) => {
12116
14014
  const app = (0, firebase_admin_app.getApps)().length ? (0, firebase_admin_app.getApp)() : (0, firebase_admin_app.initializeApp)(appOptions);
12117
14015
  const firestore = databaseId ? (0, firebase_admin_firestore.getFirestore)(app, databaseId) : (0, firebase_admin_firestore.getFirestore)(app);
12118
- return createKvAdapter({ store: createFirestoreStore({
14016
+ const store = createFirestoreStore({
12119
14017
  firestore,
12120
14018
  collection
12121
- }) });
14019
+ });
14020
+ const credential = app.options.credential;
14021
+ return createKvAdapter({ store: appOptions.credential === void 0 || credential === void 0 || process.env["FIRESTORE_EMULATOR_HOST"] ? store : withLoadedCredential(store, credential, app.options.projectId) });
12122
14022
  };
12123
14023
  /**
12124
14024
  * The resource this database reaches, without credentials, under the key
@@ -12139,11 +14039,14 @@ const firebaseDatabase = (config) => ({
12139
14039
  //#region src/firebaseStorage.ts
12140
14040
  /** Signed URLs kept per adapter, enough for a few Bundles' assets. */
12141
14041
  const MAX_CACHED_SIGNED_URLS = 1e4;
14042
+ /** Objects deleted at once: Cloud Storage deletes one object a request. */
14043
+ const DELETE_CONCURRENCY = 16;
12142
14044
  const firebaseStorage = (config) => {
12143
14045
  const app = (0, firebase_admin_app.getApps)().length ? (0, firebase_admin_app.getApp)() : (0, firebase_admin_app.initializeApp)(config);
12144
14046
  let opened;
12145
14047
  const bucket = () => opened ??= (0, firebase_admin_storage.getStorage)(app).bucket(config.storageBucket);
12146
14048
  const getStorageKey = createStorageKeyBuilder(config.basePath);
14049
+ const basePrefix = getStorageKey() ? `${getStorageKey()}/` : "";
12147
14050
  /**
12148
14051
  * Signed URLs by object. Without a private key, as in Cloud Functions, each
12149
14052
  * signature is an IAM signBlob request, and an update check returns a URL
@@ -12232,6 +14135,39 @@ const firebaseStorage = (config) => {
12232
14135
  const { key } = parseAndValidate(storageUri);
12233
14136
  await bucket().file(key).delete({ ignoreNotFound: true });
12234
14137
  return { deleted: true };
14138
+ },
14139
+ async listObjects(prefix) {
14140
+ const folder = getStorageKey(prefix ?? "");
14141
+ const [files] = await bucket().getFiles({
14142
+ autoPaginate: true,
14143
+ prefix: folder ? `${folder}/` : ""
14144
+ });
14145
+ const objects = [];
14146
+ for (const file of files) {
14147
+ if (!file.name.startsWith(basePrefix)) continue;
14148
+ let storageUri;
14149
+ try {
14150
+ storageUri = createStorageUri({
14151
+ bucket: config.storageBucket,
14152
+ key: file.name,
14153
+ protocol: "gs"
14154
+ });
14155
+ } catch {
14156
+ continue;
14157
+ }
14158
+ const { size, updated } = file.metadata;
14159
+ objects.push({
14160
+ key: file.name.slice(basePrefix.length),
14161
+ ...updated ? { lastModifiedAt: new Date(updated) } : {},
14162
+ size: Number(size ?? 0),
14163
+ storageUri
14164
+ });
14165
+ }
14166
+ return objects;
14167
+ },
14168
+ async deleteObjects(relativeKeys) {
14169
+ const keys = relativeKeys.map((key) => getStorageKey(key));
14170
+ 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
14171
  }
12236
14172
  });
12237
14173
  };
@@ -12242,9 +14178,10 @@ const adminOptions = ((0, firebase_admin_app.getApps)()[0] ?? (0, firebase_admin
12242
14178
  const storageBucket = adminOptions.storageBucket;
12243
14179
  const cdnUrl = process.env.HOT_UPDATER_CDN_URL;
12244
14180
  if (!storageBucket) throw new Error("Firebase runtime requires storageBucket to read bundle manifests.");
14181
+ const { credential: _runtimeCredential, ...databaseOptions } = adminOptions;
12245
14182
  const hotUpdater = createHotUpdater({
12246
14183
  database: firebaseDatabase({
12247
- ...adminOptions,
14184
+ ...databaseOptions,
12248
14185
  databaseId: HotUpdater.FIRESTORE_DATABASE_ID
12249
14186
  }),
12250
14187
  plugins: [