@hot-updater/aws 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.
@@ -30,6 +30,7 @@ let _aws_sdk_client_cloudfront = require("@aws-sdk/client-cloudfront");
30
30
  let _aws_sdk_lib_dynamodb = require("@aws-sdk/lib-dynamodb");
31
31
  let _aws_sdk_client_s3 = require("@aws-sdk/client-s3");
32
32
  let _aws_sdk_lib_storage = require("@aws-sdk/lib-storage");
33
+ let _aws_sdk_s3_request_presigner = require("@aws-sdk/s3-request-presigner");
33
34
  const SHA256_FILE_HASH_RE = /^[0-9a-f]{64}$/;
34
35
  const isContentAddressedAssetFileHash = (value) => {
35
36
  return typeof value === "string" && SHA256_FILE_HASH_RE.test(value);
@@ -627,7 +628,8 @@ const releaseRowToRelease = (row) => ({
627
628
  operation: row.operation,
628
629
  sourceReleaseId: row.source_release_id,
629
630
  createdAtMs: row.created_at_ms,
630
- updatedAtMs: row.updated_at_ms
631
+ updatedAtMs: row.updated_at_ms,
632
+ label: row.label ?? null
631
633
  });
632
634
  const bundleToRow = (bundle) => {
633
635
  const metadata = bundleMetadataToRow(bundle.metadata);
@@ -1136,7 +1138,8 @@ function rangeToIntervals(range) {
1136
1138
  throw new ReleaseCatalogCompilationError("INVALID_TARGET_RANGE", `Invalid target app-version range: ${range}`);
1137
1139
  }
1138
1140
  }
1139
- function releaseDescriptor(release) {
1141
+ /** A release's descriptor; its label only when it has one and `labels`. */
1142
+ function releaseDescriptor(release, labels) {
1140
1143
  return {
1141
1144
  releaseId: release.id,
1142
1145
  kind: release.kind,
@@ -1144,7 +1147,8 @@ function releaseDescriptor(release) {
1144
1147
  rolloutCohortCount: release.rolloutCohortCount,
1145
1148
  targetCohorts: [...new Set(release.targetCohorts)].sort(),
1146
1149
  shouldForceUpdate: release.shouldForceUpdate,
1147
- message: release.message
1150
+ message: release.message,
1151
+ ...labels && typeof release.label === "number" ? { label: release.label } : {}
1148
1152
  };
1149
1153
  }
1150
1154
  function validateReleases(releases, strategy) {
@@ -1357,12 +1361,21 @@ async function compileReleaseCatalog(input) {
1357
1361
  const targetCohorts = new Set(releases.flatMap((release) => release.targetCohorts));
1358
1362
  if (targetCohorts.size > 512) throw new ReleaseCatalogCompilationError("DISTINCT_TARGET_COHORT_LIMIT", `Scope exceeds 512 distinct target cohorts`);
1359
1363
  const { envelope, retainedReleases } = input.strategy === "APP_VERSION" ? compileAppVersion(releases) : compileFingerprint(releases);
1360
- const payload = {
1361
- ...envelope,
1362
- releaseDescriptors: retainedReleases.map(releaseDescriptor)
1364
+ const compile = (labels) => {
1365
+ const payload = {
1366
+ ...envelope,
1367
+ releaseDescriptors: retainedReleases.map((release) => releaseDescriptor(release, labels))
1368
+ };
1369
+ const canonicalPayload = canonicalStringify(payload);
1370
+ return {
1371
+ payload,
1372
+ canonicalPayload,
1373
+ byteSize: new TextEncoder().encode(canonicalPayload).byteLength
1374
+ };
1363
1375
  };
1364
- const canonicalPayload = canonicalStringify(payload);
1365
- const byteSize = new TextEncoder().encode(canonicalPayload).byteLength;
1376
+ let compiled = compile(true);
1377
+ if (compiled.byteSize > 262144 && retainedReleases.some((release) => typeof release.label === "number")) compiled = compile(false);
1378
+ const { payload, canonicalPayload, byteSize } = compiled;
1366
1379
  if (byteSize > 262144) throw new ReleaseCatalogCompilationError("CATALOG_OVERSIZE", `Compiled Release catalog is ${byteSize} bytes; maximum is ${MAX_COMPILED_CATALOG_BYTES}`);
1367
1380
  return {
1368
1381
  byteSize,
@@ -1437,6 +1450,10 @@ const semverSatisfies = (targetAppVersion, currentVersion) => {
1437
1450
  return satisfies(currentCoerce, targetAppVersion);
1438
1451
  };
1439
1452
  //#endregion
1453
+ //#region ../plugin-core/dist/types/index.mjs
1454
+ /** The value of a `Lazy`, calling its function. */
1455
+ const resolveLazy = async (value) => typeof value === "function" ? await value() : value;
1456
+ //#endregion
1440
1457
  //#region ../plugin-core/dist/serverPlugin/definePlugin.mjs
1441
1458
  /** Declares a plugin; Hot Updater's own plugins and third-party ones use the same contract. */
1442
1459
  const definePlugin = (plugin) => plugin;
@@ -2070,45 +2087,6 @@ const METER = Symbol.for("@hot-updater/plugin-core/read-meter");
2070
2087
  /** The meter `meterReads` gave `database`, if it did. */
2071
2088
  const readMeterOf = (database) => typeof database === "object" && database !== null ? database[METER] : void 0;
2072
2089
  //#endregion
2073
- //#region ../plugin-core/dist/engine/db/schemaSettings.mjs
2074
- const storedSettings = async (adapter, keys) => {
2075
- const rows = await readSettings(adapter, keys);
2076
- return new Map(keys.map((key, position) => [key, rows[position] ?? null]));
2077
- };
2078
- /** Writes the settings rows after every table exists. */
2079
- const writeSchemaSettings = async (adapter, adapterName, settings) => {
2080
- const stored = await storedSettings(adapter, Object.keys(settings));
2081
- const ops = Object.entries(settings).flatMap(([key, value]) => {
2082
- const row = stored.get(key);
2083
- if (row === null || row === void 0) return [{
2084
- type: "insert",
2085
- table: SETTINGS_TABLE,
2086
- row: {
2087
- key,
2088
- value,
2089
- _v: 0
2090
- }
2091
- }];
2092
- if (row.value === value) return [];
2093
- return [{
2094
- type: "patch",
2095
- table: SETTINGS_TABLE,
2096
- key: [key],
2097
- set: { value },
2098
- guard: { v: Number(row._v) },
2099
- previous: row
2100
- }];
2101
- });
2102
- if (ops.length === 0) return;
2103
- if (!(await adapter.write(ops)).ok) throw new Error(`${adapterName}: the schema settings changed during the migration; run it again.`);
2104
- };
2105
- /** Creates or updates every table, then writes the settings rows last. */
2106
- const migrateSchema = async (adapter, adapterName, tables, settings) => {
2107
- if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
2108
- await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
2109
- await writeSchemaSettings(adapter, adapterName, settings);
2110
- };
2111
- //#endregion
2112
2090
  //#region ../plugin-core/dist/engine/core/schema.mjs
2113
2091
  /** A channel's id is `channel:` and its name's channel key, so ids share channel_key's bound. */
2114
2092
  const CHANNEL_ID = {
@@ -2124,9 +2102,13 @@ const CHANNEL_ID = {
2124
2102
  * applies it to managed databases an earlier release created. The official
2125
2103
  * plugins' `schemaVersion`s follow the same rule. A bump only adds tables:
2126
2104
  * every database's migrator creates missing tables and then records the
2127
- * version, and none of them changes an existing table, so changing one
2128
- * needs a migration step of its own first. The schema fence answers 503 on
2129
- * a database whose row differs, until it runs.
2105
+ * version, and none of them changes an existing table's columns, so changing
2106
+ * one needs a migration step of its own first. An index added to an existing
2107
+ * table is listed in `LATE_INDEXES`, and a column in `LATE_COLUMNS`. The schema fence answers 503 on
2108
+ * a database whose row differs, until it runs. Before a version is released,
2109
+ * its tables change in place in its own migration, and a database one of its
2110
+ * prereleases migrated takes the same change by hand: the fence compares this
2111
+ * row, not columns, so nothing reports it.
2130
2112
  */
2131
2113
  const HOT_UPDATER_SCHEMA_VERSION = "1.2.0";
2132
2114
  const bundles = defineTable({
@@ -2275,7 +2257,11 @@ const releases = defineTable({
2275
2257
  }
2276
2258
  },
2277
2259
  created_at_ms: { type: "integer" },
2278
- updated_at_ms: { type: "integer" }
2260
+ updated_at_ms: { type: "integer" },
2261
+ label: {
2262
+ type: "integer",
2263
+ required: false
2264
+ }
2279
2265
  }, {
2280
2266
  key: ["id"],
2281
2267
  indexes: {
@@ -2308,9 +2294,72 @@ const releases = defineTable({
2308
2294
  all: {
2309
2295
  eq: [],
2310
2296
  sort: ["id"]
2297
+ },
2298
+ scopes: {
2299
+ eq: [],
2300
+ sort: ["scope_key"]
2301
+ },
2302
+ byLabel: {
2303
+ eq: [
2304
+ "channel_id",
2305
+ "platform",
2306
+ "label"
2307
+ ],
2308
+ sort: [],
2309
+ unique: true
2311
2310
  }
2312
2311
  }
2313
2312
  });
2313
+ /**
2314
+ * Indexes declared on a table that a released schema's servers write: a
2315
+ * store that keeps index items of its own (`migrations.fillIndex`) lacks
2316
+ * them for rows written before, and for rows such a server still writes
2317
+ * after the migration, since its schema fence keeps a check that passed.
2318
+ * Each migration writes the missing items, and `db migrate` on a database
2319
+ * whose settings match looks for them. `releases.scopes` arrived in 1.2.0;
2320
+ * 1.1.x servers write releases without it.
2321
+ */
2322
+ const LATE_INDEXES = [{
2323
+ table: "releases",
2324
+ index: "scopes"
2325
+ }];
2326
+ /**
2327
+ * Columns added to a table that a released schema created: a migrator whose
2328
+ * store has columns adds each one missing from an existing table, with
2329
+ * `ALTER TABLE … ADD COLUMN`, before it creates the table's indexes, and
2330
+ * `db migrate` on a database whose settings match still looks for them,
2331
+ * since a database a prerelease migrated records the same settings. Each
2332
+ * is optional, so rows written before it, and rows a server of the earlier
2333
+ * release still writes, read as null. `releases.label` arrived in 1.2.0.
2334
+ */
2335
+ const LATE_COLUMNS = [{
2336
+ table: "releases",
2337
+ column: "label"
2338
+ }];
2339
+ /**
2340
+ * One counter per sequence: `releases/<platform>/<channel ID>` holds the
2341
+ * last label that channel and platform's releases took. A deploy or a
2342
+ * promote reads it and writes the next value in the transaction that writes
2343
+ * the release, so two writers never take one label. `is_filled` is true once
2344
+ * every release of the sequence written before labels has one, in ID order;
2345
+ * until then a writer fills them first. Deleting a channel deletes its
2346
+ * counters, so a channel created again with the name starts at 1.
2347
+ */
2348
+ const labelSequences = defineTable({
2349
+ id: {
2350
+ type: "string",
2351
+ maxLength: 1440,
2352
+ ascii: true
2353
+ },
2354
+ last_label: { type: "integer" },
2355
+ is_filled: { type: "boolean" }
2356
+ }, {
2357
+ key: ["id"],
2358
+ indexes: { all: {
2359
+ eq: [],
2360
+ sort: ["id"]
2361
+ } }
2362
+ });
2314
2363
  /** One compiled catalog per scope; the update check reads exactly this row. */
2315
2364
  const releaseCatalogs = defineTable({
2316
2365
  scope_key: {
@@ -2380,7 +2429,10 @@ const channels = defineTable({
2380
2429
  /**
2381
2430
  * The native builds `native-build android` and `native-build ios` track, newest first
2382
2431
  * in each scope: a platform, a channel, and the fingerprint or app version
2383
- * the build compiled in. `min_bundle_id` names the build's built-in bundle,
2432
+ * the build compiled in. A sandbox build's scope has no channel: its app ID,
2433
+ * URL scheme, artifact kind and distribution in its place, so pull requests
2434
+ * reuse it across channels, while `channel_id` still names the channel it
2435
+ * embeds. `min_bundle_id` names the build's built-in bundle,
2384
2436
  * a `bundles` row no release publishes. Its references keep no counters, so
2385
2437
  * adding this table changes no existing one; a channel with builds is
2386
2438
  * refused deletion through `byChannel`. `build_key` is the native build key
@@ -2390,6 +2442,27 @@ const channels = defineTable({
2390
2442
  * or `versionCode`. `submitted_to`, `submitted_at_ms` and
2391
2443
  * `submitted_version` record the store track a build went to, when, and
2392
2444
  * the store's label of the build; they stay null for a build no store took.
2445
+ * `is_store_build` is true on the build a person or a job says the store
2446
+ * sells, and false on every other: deploys patch from it over the scope's
2447
+ * newest build. The engine copies the scope key into `store_build_scope_key`
2448
+ * for that build alone, so `byStoreBuild` holds one entry per scope at most,
2449
+ * on every store, while any number of a scope's builds hold none.
2450
+ * `is_sandbox` is true on a sandbox build, set from its artifact when it
2451
+ * registers and never changed, and `sandbox_url_scheme` is the URL scheme its artifact registers,
2452
+ * which its preview links open; null on any other build, and on a sandbox
2453
+ * build registered before the column, which registered the derived one.
2454
+ * `export_method` is how an `.ipa` was exported, read from its profile when
2455
+ * it registers and never changed; null on any other artifact, on an `.ipa`
2456
+ * whose profile couldn't be read, and on one registered before the column.
2457
+ * `native_app_version` is the app version the artifact itself reports, its
2458
+ * `CFBundleShortVersionString` or `versionName`, read from the artifact when
2459
+ * it registers and never changed, whatever the update strategy; `app_version`
2460
+ * stays the version OTAs target, null on a fingerprint build. It is null
2461
+ * when the artifact's can't be read, and on a build registered before the
2462
+ * column.
2463
+ * Boolean columns follow one rule: `is_*` for a fact about the row or
2464
+ * `should_*` for an instruction to the client, never null; a unique index over
2465
+ * the rows where one is true keys a derived slot, not the boolean.
2393
2466
  */
2394
2467
  const nativeBuilds = defineTable({
2395
2468
  id: {
@@ -2466,9 +2539,34 @@ const nativeBuilds = defineTable({
2466
2539
  type: "string",
2467
2540
  maxLength: 255,
2468
2541
  required: false
2542
+ },
2543
+ is_store_build: { type: "boolean" },
2544
+ is_sandbox: { type: "boolean" },
2545
+ sandbox_url_scheme: {
2546
+ type: "string",
2547
+ maxLength: 255,
2548
+ ascii: true,
2549
+ required: false
2550
+ },
2551
+ export_method: {
2552
+ type: "string",
2553
+ maxLength: 16,
2554
+ required: false
2555
+ },
2556
+ native_app_version: {
2557
+ type: "string",
2558
+ required: false
2469
2559
  }
2470
2560
  }, {
2471
2561
  key: ["id"],
2562
+ derived: {
2563
+ /** The scope this build is the store build of; null on every other. */
2564
+ store_build_scope_key: {
2565
+ type: "string",
2566
+ maxLength: 2048,
2567
+ ascii: true,
2568
+ compute: (row) => row.is_store_build ? row.scope_key : null
2569
+ } },
2472
2570
  indexes: {
2473
2571
  byScope: {
2474
2572
  eq: ["scope_key"],
@@ -2478,6 +2576,15 @@ const nativeBuilds = defineTable({
2478
2576
  eq: ["scope_key", "build_key"],
2479
2577
  sort: ["id"]
2480
2578
  },
2579
+ byScopeKind: {
2580
+ eq: ["scope_key", "artifact_kind"],
2581
+ sort: ["id"]
2582
+ },
2583
+ byStoreBuild: {
2584
+ eq: ["store_build_scope_key"],
2585
+ sort: [],
2586
+ unique: true
2587
+ },
2481
2588
  byChannel: {
2482
2589
  eq: ["channel_id"],
2483
2590
  sort: ["id"],
@@ -2489,6 +2596,119 @@ const nativeBuilds = defineTable({
2489
2596
  }
2490
2597
  }
2491
2598
  });
2599
+ /**
2600
+ * The iPhones a team asks to install ad hoc builds on. A row decides what the
2601
+ * CLI registers with Apple, not what an export includes: Xcode's automatic ad
2602
+ * hoc profile lists every device the Apple account has enabled. `status` is
2603
+ * `pending` until someone approves it, `approved` until a build or
2604
+ * `native-build devices add` registers it with Apple, then `registered`;
2605
+ * declining or removing one deletes its row. `udid` is the UDID in lower case.
2606
+ * `apple_issuer_id` is the App Store Connect issuer whose key registered it,
2607
+ * set once: a build signed by another account never registers these rows.
2608
+ * `apple_error` is Apple's refusal of the device, or why it stopped counting
2609
+ * it, cleared by the next success. `build_id` is the newest native build whose
2610
+ * .ipa the CLI checked lists it; deleting that build never touches the row.
2611
+ * It holds personal data: a UDID, a name, and the emails of who asked and who
2612
+ * approved, null for the CLI.
2613
+ */
2614
+ const iosDevices = defineTable({
2615
+ id: {
2616
+ type: "string",
2617
+ maxLength: 36
2618
+ },
2619
+ udid: {
2620
+ type: "string",
2621
+ maxLength: 40,
2622
+ ascii: true,
2623
+ unique: true
2624
+ },
2625
+ name: {
2626
+ type: "string",
2627
+ maxLength: 100
2628
+ },
2629
+ status: {
2630
+ type: "string",
2631
+ maxLength: 16
2632
+ },
2633
+ requested_by: {
2634
+ type: "string",
2635
+ maxLength: 320,
2636
+ required: false
2637
+ },
2638
+ created_at_ms: { type: "integer" },
2639
+ approved_by: {
2640
+ type: "string",
2641
+ maxLength: 320,
2642
+ required: false
2643
+ },
2644
+ approved_at_ms: {
2645
+ type: "integer",
2646
+ required: false
2647
+ },
2648
+ registered_at_ms: {
2649
+ type: "integer",
2650
+ required: false
2651
+ },
2652
+ apple_issuer_id: {
2653
+ type: "string",
2654
+ maxLength: 64,
2655
+ ascii: true,
2656
+ required: false
2657
+ },
2658
+ apple_error: {
2659
+ type: "string",
2660
+ maxLength: 512,
2661
+ required: false
2662
+ },
2663
+ build_id: {
2664
+ type: "string",
2665
+ maxLength: 36,
2666
+ required: false
2667
+ }
2668
+ }, {
2669
+ key: ["id"],
2670
+ indexes: {
2671
+ byStatus: {
2672
+ eq: ["status"],
2673
+ sort: ["id"]
2674
+ },
2675
+ byRegistration: {
2676
+ eq: [],
2677
+ sort: ["registered_at_ms"]
2678
+ },
2679
+ all: {
2680
+ eq: [],
2681
+ sort: ["id"]
2682
+ }
2683
+ }
2684
+ });
2685
+ /**
2686
+ * The Apple account the iOS device registry belongs to: one row, keyed
2687
+ * `registry`, holding the App Store Connect issuer that first registered a
2688
+ * device. A build claims it before it sends Apple anything, and its key makes
2689
+ * the claim atomic on every store, so two builds of two accounts can't both
2690
+ * spend a slot; another account's build then registers nothing. Removing
2691
+ * devices never releases it.
2692
+ */
2693
+ const iosDeviceAccount = defineTable({
2694
+ id: {
2695
+ type: "string",
2696
+ maxLength: 16,
2697
+ ascii: true
2698
+ },
2699
+ apple_issuer_id: {
2700
+ type: "string",
2701
+ maxLength: 64,
2702
+ ascii: true
2703
+ },
2704
+ claimed_at_ms: { type: "integer" }
2705
+ }, {
2706
+ key: ["id"],
2707
+ indexes: { all: {
2708
+ eq: [],
2709
+ sort: ["id"]
2710
+ } }
2711
+ });
2492
2712
  /** Core's module: always installed, never a plugin. */
2493
2713
  const coreModule = {
2494
2714
  id: "core",
@@ -2509,7 +2729,10 @@ const coreModule = {
2509
2729
  sort: []
2510
2730
  } }
2511
2731
  }),
2512
- native_builds: nativeBuilds
2732
+ native_builds: nativeBuilds,
2733
+ ios_devices: iosDevices,
2734
+ ios_device_account: iosDeviceAccount,
2735
+ label_sequences: labelSequences
2513
2736
  }
2514
2737
  };
2515
2738
  //#endregion
@@ -2535,6 +2758,140 @@ const refuseV0Database = (adapterName, stored) => {
2535
2758
  if (typeof version !== "string" || stored.has("schema.engine")) return;
2536
2759
  throw new HotUpdaterSchemaMigrationRequiredError(adapterName, version);
2537
2760
  };
2761
+ /** Compares dotted numeric versions, such as "1" and "1.2.0"; NaN when either is not one. */
2762
+ const compareVersions = (left, right) => {
2763
+ const parse = (version) => /^\d+(?:\.\d+)*$/u.test(version) ? version.split(".").map(Number) : [NaN];
2764
+ const [a, b] = [parse(left), parse(right)];
2765
+ if ([...a, ...b].some(Number.isNaN)) return NaN;
2766
+ for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
2767
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
2768
+ if (difference !== 0) return difference;
2769
+ }
2770
+ return 0;
2771
+ };
2772
+ /**
2773
+ * The settings whose versions only move forward when a `ToolingTarget` names
2774
+ * none. `schema.engine` is a storage layout, not a release: a store refuses
2775
+ * another layout itself, and doctor reports it as not migratable.
2776
+ */
2777
+ const DEFAULT_ORDERED_SETTINGS = ["schema.core"];
2778
+ /**
2779
+ * Refuses a database a newer release migrated, one whose `schema.core` is
2780
+ * newer than this release's: writing this release's settings would move the
2781
+ * schema back, and every server of the newer release would answer 503. Only
2782
+ * `ordered` settings are compared, `schema.core` among them, and the message
2783
+ * lists each that is newer. An official plugin's
2784
+ * newer version alone is no newer release: Insights recorded "1.2.0" in
2785
+ * 1.0.0-rc.23 and rc.24, then went back to "1.0.0" with the same tables.
2786
+ */
2787
+ const refuseNewerSchema = (adapterName, stored, settings, ordered = DEFAULT_ORDERED_SETTINGS) => {
2788
+ const newer = ordered.flatMap((key) => {
2789
+ const found = stored.get(key);
2790
+ const expected = settings[key];
2791
+ return typeof found === "string" && expected !== void 0 && compareVersions(found, expected) > 0 ? [{
2792
+ key,
2793
+ found,
2794
+ expected
2795
+ }] : [];
2796
+ });
2797
+ const core = newer.find(({ key }) => key === "schema.core");
2798
+ if (core === void 0) return;
2799
+ 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.`);
2800
+ };
2801
+ /** The settings rows a migration changes, each with its stored value. */
2802
+ const settingsOperation = (stored, changed) => ({
2803
+ type: "custom",
2804
+ description: `Record ${changed.map(([key, value]) => {
2805
+ const found = stored.get(key);
2806
+ return typeof found === "string" ? `${key} ${found} → ${value}` : `${key} ${value}`;
2807
+ }).join(", ")}`
2808
+ });
2809
+ //#endregion
2810
+ //#region ../plugin-core/dist/engine/db/schemaSettings.mjs
2811
+ const storedSettings = async (adapter, keys) => {
2812
+ const rows = await readSettings(adapter, keys);
2813
+ return new Map(keys.map((key, position) => [key, rows[position] ?? null]));
2814
+ };
2815
+ /**
2816
+ * Writes the settings rows after every table exists, and refuses a database
2817
+ * whose `ordered` settings a newer release recorded.
2818
+ */
2819
+ const writeSchemaSettings = async (adapter, adapterName, settings, ordered) => {
2820
+ const stored = await storedSettings(adapter, Object.keys(settings));
2821
+ refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
2822
+ const ops = Object.entries(settings).flatMap(([key, value]) => {
2823
+ const row = stored.get(key);
2824
+ if (row === null || row === void 0) return [{
2825
+ type: "insert",
2826
+ table: SETTINGS_TABLE,
2827
+ row: {
2828
+ key,
2829
+ value,
2830
+ _v: 0
2831
+ }
2832
+ }];
2833
+ if (row.value === value) return [];
2834
+ return [{
2835
+ type: "patch",
2836
+ table: SETTINGS_TABLE,
2837
+ key: [key],
2838
+ set: { value },
2839
+ guard: { v: Number(row._v) },
2840
+ previous: row
2841
+ }];
2842
+ });
2843
+ if (ops.length === 0) return;
2844
+ if (!(await adapter.write(ops)).ok) throw new Error(`${adapterName}: the schema settings changed during the migration; run it again.`);
2845
+ };
2846
+ /**
2847
+ * The `LATE_INDEXES` among `tables` whose items some rows lack, as
2848
+ * `<table>.<index>`, written unless `dryRun`: none on a store without
2849
+ * `migrations.fillIndex`.
2850
+ */
2851
+ const fillLateIndexes = async (adapter, tables, { dryRun = false } = {}) => {
2852
+ const fillIndex = adapter.migrations?.fillIndex;
2853
+ if (fillIndex === void 0) return [];
2854
+ const lacking = [];
2855
+ for (const { table: name, index } of LATE_INDEXES) {
2856
+ const table = tables.find((candidate) => candidate.name === name);
2857
+ if (table === void 0) continue;
2858
+ if (await fillIndex(table, index, { dryRun }) > 0) lacking.push(`${name}.${index}`);
2859
+ }
2860
+ return lacking;
2861
+ };
2862
+ /**
2863
+ * The `LATE_COLUMNS` among `tables` that an existing table lacks, as
2864
+ * `<table>.<column>`, added unless `dryRun`: none on a store without
2865
+ * `migrations.addColumns`, or for a table not created yet.
2866
+ */
2867
+ const addLateColumns = async (adapter, tables, { dryRun = false } = {}) => {
2868
+ const addColumns = adapter.migrations?.addColumns;
2869
+ if (addColumns === void 0) return [];
2870
+ const lacking = [];
2871
+ for (const table of tables) {
2872
+ const columns = LATE_COLUMNS.filter(({ table: name }) => name === table.name).map(({ column }) => column);
2873
+ if (columns.length === 0) continue;
2874
+ const added = await addColumns(table, columns, { dryRun });
2875
+ lacking.push(...added.map((column) => `${table.name}.${column}`));
2876
+ }
2877
+ return lacking;
2878
+ };
2879
+ /**
2880
+ * Adds the late columns existing tables lack, creates or updates every
2881
+ * table, writes the late indexes' missing items, then writes the settings
2882
+ * rows last. A database a newer release migrated is
2883
+ * refused before anything is written: its settings are read first, and a
2884
+ * store without them yet, whose read fails, has none to refuse.
2885
+ */
2886
+ const migrateSchema = async (adapter, adapterName, tables, settings, ordered) => {
2887
+ if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
2888
+ const stored = await storedSettings(adapter, Object.keys(settings)).catch(() => void 0);
2889
+ if (stored !== void 0) refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
2890
+ await addLateColumns(adapter, tables);
2891
+ await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
2892
+ await fillLateIndexes(adapter, tables);
2893
+ await writeSchemaSettings(adapter, adapterName, settings, ordered);
2894
+ };
2538
2895
  //#endregion
2539
2896
  //#region ../plugin-core/dist/engine/database/cursor.mjs
2540
2897
  const encoder$1 = new TextEncoder();
@@ -2698,18 +3055,17 @@ const LEASE_TABLE = "aggregate_lease";
2698
3055
  const LEASE = { id: "compaction" };
2699
3056
  /** How long a compaction holds the lease before another process may take it. */
2700
3057
  const LEASE_MS = 3e4;
2701
- /**
2702
- * Default windows: log mode compacts every 60 seconds, since reads compact
2703
- * first; memory mode flushes every 15, since its window is what a crash
2704
- * loses.
2705
- */
2706
- const WINDOW_MS$1 = {
2707
- log: 6e4,
2708
- memory: 15e3
2709
- };
3058
+ /** A commit compacts once this has passed since the last compaction. */
3059
+ const WINDOW_MS$1 = 6e4;
2710
3060
  /** Log rows a compaction reads from each log table for one group. */
2711
3061
  const LOG_PAGE = 200;
2712
3062
  /**
3063
+ * How old a log row this process can't apply must be before its reads step
3064
+ * past it: older than any transaction still committing, between servers
3065
+ * whose clocks agree this closely.
3066
+ */
3067
+ const SKIP_AFTER_MS = 3e5;
3068
+ /**
2713
3069
  * Groups one compaction applies: after a commit, so the request that runs
2714
3070
  * it waits for one group; before a read; and on flush.
2715
3071
  */
@@ -2720,8 +3076,6 @@ const GROUPS = {
2720
3076
  };
2721
3077
  /** Tries per write after a conflict or a transient error. */
2722
3078
  const ATTEMPTS = 5;
2723
- /** Aggregate rows a memory buffer holds before a commit waits for a flush. */
2724
- const MAX_BUFFERED = 1e4;
2725
3079
  const log = defineTable({
2726
3080
  id: {
2727
3081
  type: "string",
@@ -2771,7 +3125,7 @@ const valuesOf = ({ deltas, sketches }) => ({
2771
3125
  /**
2772
3126
  * Merges `values` into the change for `key`'s identity as `tx.aggregate`
2773
3127
  * does: deltas add up and sketches merge. One constant `shardBy` keys each
2774
- * identity to one entry; the write picks the shard.
3128
+ * identity to one entry; `compile` writes it to shard 0.
2775
3129
  */
2776
3130
  const merge = (into, model, key, values) => recordAggregate(into, model, Object.fromEntries(shapeOf(model).key.map((field, at) => [field, key[at]])), values, "");
2777
3131
  const mergeAll = (into, changes) => {
@@ -2805,7 +3159,7 @@ const increment = ({ model, deltas }, key) => Object.values(deltas).some((delta)
2805
3159
  /**
2806
3160
  * The guarded write that merges `change` into `current`: insert, patch, or
2807
3161
  * delete at zero. Unlike a transaction's, a gauge may go below zero here: a
2808
- * shard row holds one writer's net changes, and reads sum every shard.
3162
+ * group can hold a loss without the gain before it, and reads sum every shard.
2809
3163
  */
2810
3164
  const rewrite = (change, key, current) => {
2811
3165
  const { model } = change;
@@ -2842,23 +3196,41 @@ const rewrite = (change, key, current) => {
2842
3196
  previous: current
2843
3197
  };
2844
3198
  };
3199
+ /** A shard row's place in what `readCurrent` read. */
3200
+ const rowId = (model, key) => JSON.stringify([model.table.name, key]);
3201
+ /** The shard key each change writes: shard 0, since one compaction runs at a time. */
3202
+ const keysOf = (changes) => changes.map(({ key }) => [...key.slice(0, -1), 0]);
2845
3203
  /**
2846
- * The write for each change on its shard: a blind increment that creates
2847
- * the row for counters, and a guarded rewrite for gauges and sketches, whose
2848
- * rows are read in one batch per table.
3204
+ * The current rows of the changes that rewrite theirs (gauges and sketches),
3205
+ * each once, in one batch per table.
2849
3206
  */
2850
- const compile = async (adapter, changes, shard) => {
2851
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
3207
+ const readCurrent = async (adapter, changes) => {
3208
+ const keys = keysOf(changes);
2852
3209
  const reads = /* @__PURE__ */ new Map();
2853
3210
  changes.forEach((change, at) => {
2854
- if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
3211
+ if (!rewrites(change)) return;
3212
+ const wanted = reads.get(change.model) ?? /* @__PURE__ */ new Map();
3213
+ wanted.set(rowId(change.model, keys[at]), keys[at]);
3214
+ reads.set(change.model, wanted);
2855
3215
  });
2856
3216
  const current = /* @__PURE__ */ new Map();
2857
- await Promise.all([...reads].map(async ([model, positions]) => {
2858
- const rows = await adapter.get(model.table, positions.map((at) => keys[at]));
2859
- positions.forEach((at, index) => current.set(at, rows[index] ?? null));
3217
+ await Promise.all([...reads].map(async ([model, wanted]) => {
3218
+ const keys = [...wanted.values()];
3219
+ const rows = await adapter.get(model.table, keys);
3220
+ keys.forEach((key, at) => {
3221
+ current.set(rowId(model, key), rows[at] ?? null);
3222
+ });
2860
3223
  }));
2861
- return changes.map((change, at) => current.has(at) ? rewrite(change, keys[at], current.get(at)) : increment(change, keys[at]));
3224
+ return current;
3225
+ };
3226
+ /**
3227
+ * The write for each change: a blind increment that creates the row for
3228
+ * counters, and a guarded rewrite for gauges and sketches, over the rows
3229
+ * `current` read.
3230
+ */
3231
+ const build = (changes, current) => {
3232
+ const keys = keysOf(changes);
3233
+ return changes.map((change, at) => rewrites(change) ? rewrite(change, keys[at], current.get(rowId(change.model, keys[at])) ?? null) : increment(change, keys[at]));
2862
3234
  };
2863
3235
  const isOp = (op) => op !== void 0;
2864
3236
  const sleep$2 = (attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random()));
@@ -2902,14 +3274,13 @@ const encode = async (changes) => {
2902
3274
  return zipped !== void 0 && zipped.length < json.length ? `z${zipped}` : json;
2903
3275
  };
2904
3276
  /**
2905
- * Batches changes to aggregates declared `batched`. A transaction records
2906
- * them without writing their rows; once it commits, "memory" mode keeps
2907
- * them in this process until its timer flushes them, and "log" mode has
2908
- * written them as one log row in the same atomic write, which a compaction
2909
- * later merges into the aggregates and deletes, atomically again, so each
2910
- * applies exactly once. One lease row keeps compactions one at a time.
3277
+ * Batches changes to aggregates declared `batched`. A transaction writes
3278
+ * them as one log row in its own atomic write, in place of their rows; a
3279
+ * compaction later merges log rows into the aggregates and deletes them,
3280
+ * atomically again, so each applies exactly once. One lease row keeps
3281
+ * compactions one at a time.
2911
3282
  */
2912
- const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS$1[mode] }, now }) => {
3283
+ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs = WINDOW_MS$1 }, now }) => {
2913
3284
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
2914
3285
  const holder = crypto.randomUUID().replaceAll("-", "");
2915
3286
  const table = (name) => schema.models.get(name).table;
@@ -2937,72 +3308,20 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
2937
3308
  }
2938
3309
  return changes;
2939
3310
  };
2940
- /**
2941
- * Writes changes in atomic chunks within `fits`, and returns the ones it
2942
- * could not apply. A write whose outcome is unknown is dropped, never
2943
- * resent, so no change applies twice.
2944
- */
2945
- const apply = async (changes, shard) => {
2946
- let rest = changes;
2947
- let ops = [];
2948
- let read = true;
2949
- for (let failures = 0; rest.length > 0 && failures < ATTEMPTS;) try {
2950
- if (read) ops = await compile(adapter, rest, shard);
2951
- let size = rest.length;
2952
- const chunk = () => ops.slice(0, size).filter(isOp);
2953
- while (size > 1 && !adapter.fits(chunk())) size = Math.ceil(size / 2);
2954
- let result = { ok: true };
2955
- if (chunk().length > 0) result = await adapter.write(chunk()).catch((error) => {
2956
- warn("flush")(error);
2957
- return { ok: true };
2958
- });
2959
- read = !result.ok && !("retry" in result);
2960
- if (result.ok) {
2961
- rest = rest.slice(size);
2962
- ops = ops.slice(size);
2963
- failures = 0;
2964
- } else {
2965
- failures += 1;
2966
- if (!read) await sleep$2(failures);
2967
- }
2968
- } catch (error) {
2969
- warn("flush")(error);
2970
- return rest;
2971
- }
2972
- return rest;
2973
- };
2974
- let buffer = /* @__PURE__ */ new Map();
2975
- let timer;
2976
- let flushing;
2977
- const shards = /* @__PURE__ */ new Map();
2978
- /** Each process writes its own shard, so flushes of two processes rarely meet. */
2979
- const processShard = (model) => {
2980
- if (!shards.has(model)) shards.set(model, Math.floor(Math.random() * shapeOf(model).shards));
2981
- return shards.get(model);
2982
- };
2983
- const schedule = () => {
2984
- if (timer !== void 0 || buffer.size === 0) return;
2985
- timer = setTimeout(() => {
2986
- timer = void 0;
2987
- flushBuffer();
2988
- }, windowMs);
2989
- timer.unref?.();
2990
- };
2991
- /** Never rejects: what it cannot apply goes back into the buffer. */
2992
- const flushBuffer = () => flushing ??= (async () => {
2993
- clearTimeout(timer);
2994
- timer = void 0;
2995
- const pending = [...buffer.values()];
2996
- buffer = /* @__PURE__ */ new Map();
2997
- mergeAll(buffer, await apply(pending, processShard));
2998
- })().catch(warn("flush")).finally(() => {
2999
- flushing = void 0;
3000
- schedule();
3001
- });
3002
3311
  let nextDue = 0;
3003
3312
  let compacting;
3004
3313
  /** Log rows this process read, by `[log table's index, id]`, for the deletes after a group. */
3005
3314
  const known = /* @__PURE__ */ new Map();
3315
+ /**
3316
+ * Each log table's last row of a run at its head that this process can't
3317
+ * apply (it names an aggregate or metric this schema lacks), whose reads
3318
+ * start past it. The rows wait for a process that can apply them, and a
3319
+ * restart reads them again.
3320
+ */
3321
+ const skipped = LOG_TABLES.map(() => void 0);
3322
+ const past = (shard) => skipped[shard] === void 0 ? {} : { range: { gt: skipped[shard] } };
3323
+ /** When a log row's transaction stamped its ID. */
3324
+ const stampOf = (id) => Number.parseInt(id.slice(0, 9), 36);
3006
3325
  const idOf = (shard, id) => JSON.stringify([shard, id]);
3007
3326
  /** The lease row as stored once `set` is written over it. */
3008
3327
  const leaseOp = (held, set) => {
@@ -3118,14 +3437,22 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3118
3437
  logs: (await Promise.all(LOG_TABLES.map(async (name, shard) => {
3119
3438
  const page = await engine.reads.findMany(name, {
3120
3439
  index: "oldest",
3121
- limit: LOG_PAGE
3440
+ limit: LOG_PAGE,
3441
+ ...past(shard)
3122
3442
  });
3123
3443
  more ||= page.next !== void 0;
3124
- return (await Promise.all(page.rows.map(async (row) => ({
3444
+ const decoded = await Promise.all(page.rows.map(async (row) => ({
3125
3445
  shard,
3126
3446
  row,
3127
3447
  changes: await decode(String(row.changes))
3128
- })))).flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
3448
+ })));
3449
+ const settled = now() - SKIP_AFTER_MS;
3450
+ for (const { row, changes } of decoded) {
3451
+ const id = String(row.id);
3452
+ if (changes !== void 0 || stampOf(id) >= settled) break;
3453
+ skipped[shard] = id;
3454
+ }
3455
+ return decoded.flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
3129
3456
  ...entry,
3130
3457
  changes
3131
3458
  }]);
@@ -3133,7 +3460,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3133
3460
  more
3134
3461
  };
3135
3462
  };
3136
- const rowsFor = async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp);
3137
3463
  /**
3138
3464
  * Applies the oldest pending log rows whose merged changes fit in one
3139
3465
  * atomic write with the lease, which lists them as applied; the rows are
@@ -3142,12 +3468,14 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3142
3468
  * log rows it applied whole, or undefined when a conflict stopped it.
3143
3469
  */
3144
3470
  const applyGroup = async (held, logs) => {
3471
+ const current = await readCurrent(adapter, logs.flatMap((entry) => [...entry.changes.values()]));
3472
+ const rowsFor = (changes) => build(changes, current).filter(isOp);
3145
3473
  for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
3146
3474
  const batch = logs.slice(0, count);
3147
3475
  const changes = mergeAll(/* @__PURE__ */ new Map(), batch.flatMap((entry) => [...entry.changes.values()]));
3148
3476
  const applied = batch.map(({ shard, row }) => [shard, row.id]);
3149
3477
  const lease = leaseOp(held, { applied: JSON.stringify(applied) });
3150
- const ops = [...await rowsFor([...changes.values()]), lease.op];
3478
+ const ops = [...rowsFor([...changes.values()]), lease.op];
3151
3479
  if (!adapter.fits(ops)) continue;
3152
3480
  for (const { shard, row } of batch) known.set(idOf(shard, row.id), row);
3153
3481
  return await commit(ops) ? {
@@ -3169,7 +3497,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3169
3497
  };
3170
3498
  const lease = leaseOp(held, {});
3171
3499
  const ops = [
3172
- ...await rowsFor(entries.slice(0, take)),
3500
+ ...rowsFor(entries.slice(0, take)),
3173
3501
  kept,
3174
3502
  lease.op
3175
3503
  ];
@@ -3190,11 +3518,12 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3190
3518
  if (held === void 0) return;
3191
3519
  let pending = true;
3192
3520
  let clear = false;
3521
+ let carried;
3193
3522
  try {
3194
3523
  for (let group = 0;; group += 1) {
3195
3524
  clear = await deleteApplied(held);
3196
3525
  if (!clear || !pending || group === groups) break;
3197
- const { logs, more } = await readLogs();
3526
+ const { logs, more } = carried ?? await readLogs();
3198
3527
  if (logs.length === 0) {
3199
3528
  pending = false;
3200
3529
  break;
@@ -3202,6 +3531,11 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3202
3531
  const applied = await applyGroup(held, logs);
3203
3532
  if (applied === void 0) break;
3204
3533
  [held, clear] = [applied.held, false];
3534
+ const rest = applied.count === 0 ? [] : logs.slice(applied.count);
3535
+ carried = rest.length > 0 ? {
3536
+ logs: rest,
3537
+ more
3538
+ } : void 0;
3205
3539
  pending = more || applied.count < logs.length;
3206
3540
  }
3207
3541
  } finally {
@@ -3221,26 +3555,13 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3221
3555
  });
3222
3556
  let checking;
3223
3557
  /** Whether any log row waits; reads at once share one check. */
3224
- const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name) => engine.reads.findMany(name, {
3558
+ const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name, shard) => engine.reads.findMany(name, {
3225
3559
  index: "oldest",
3226
- limit: 1
3560
+ limit: 1,
3561
+ ...past(shard)
3227
3562
  }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
3228
3563
  checking = void 0;
3229
3564
  });
3230
- /** Takes a committed transaction's changes; never rejects, since the transaction already committed. */
3231
- const committed = async (changes) => {
3232
- if (mode === "log") {
3233
- if (now() >= nextDue) await compact(false, GROUPS.commit);
3234
- return;
3235
- }
3236
- mergeAll(buffer, changes.values());
3237
- schedule();
3238
- if (buffer.size >= MAX_BUFFERED) await flushBuffer();
3239
- };
3240
- const flush = async () => {
3241
- await flushBuffer();
3242
- if (mode === "log" && await hasPending()) await compact(true, GROUPS.flush);
3243
- };
3244
3565
  return {
3245
3566
  async transaction(fn) {
3246
3567
  let changes = /* @__PURE__ */ new Map();
@@ -3266,7 +3587,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3266
3587
  aggregate
3267
3588
  });
3268
3589
  if (failure) throw failure.error;
3269
- if (mode === "log" && attempt.size > 0) {
3590
+ if (attempt.size > 0) {
3270
3591
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
3271
3592
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
3272
3593
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -3280,24 +3601,18 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3280
3601
  open = false;
3281
3602
  }
3282
3603
  });
3283
- if (changes.size > 0) await committed(changes);
3604
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
3284
3605
  return result;
3285
3606
  },
3286
3607
  async beforeRead(name) {
3287
3608
  if (!isBatched(schema.models.get(name))) return;
3288
- if (buffer.size > 0 || flushing !== void 0) await flushBuffer();
3289
- if (mode === "log") {
3290
- if (await hasPending().catch((error) => {
3291
- warn("read")(error);
3292
- return false;
3293
- })) await compact(true, GROUPS.read);
3294
- }
3609
+ if (await hasPending().catch((error) => {
3610
+ warn("read")(error);
3611
+ return false;
3612
+ })) await compact(true, GROUPS.read);
3295
3613
  },
3296
- flush,
3297
- async dispose() {
3298
- clearTimeout(timer);
3299
- timer = void 0;
3300
- await flush();
3614
+ async flush() {
3615
+ if (await hasPending()) await compact(true, GROUPS.flush);
3301
3616
  }
3302
3617
  };
3303
3618
  };
@@ -3439,7 +3754,8 @@ const fieldProblems = (definition, add) => {
3439
3754
  else if (field.required === false) add(`key field "${name}" is nullable`);
3440
3755
  else if (field.type === "json") add(`key field "${name}" is json`);
3441
3756
  }
3442
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
3757
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
3758
+ for (const [name, { type, maxLength, ascii }] of bounded) {
3443
3759
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
3444
3760
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
3445
3761
  }
@@ -3556,11 +3872,13 @@ const resolveSchema = (modules) => {
3556
3872
  ...maxLength === void 0 ? {} : { maxLength },
3557
3873
  ...ascii ? { ascii } : {}
3558
3874
  }));
3559
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
3875
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
3560
3876
  name: field,
3561
3877
  type,
3562
3878
  nullable: true,
3563
- ...multi ? { multi } : {}
3879
+ ...multi ? { multi } : {},
3880
+ ...maxLength === void 0 ? {} : { maxLength },
3881
+ ...ascii ? { ascii } : {}
3564
3882
  });
3565
3883
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
3566
3884
  name: metric,
@@ -3596,29 +3914,56 @@ const resolveSchema = (modules) => {
3596
3914
  * `hot-updater db migrate` for a store whose adapter creates its own tables
3597
3915
  * (MongoDB and the key-value stores): the tables and indexes, then the
3598
3916
  * settings rows, applied when a setting is missing or different, and refused
3599
- * on a v0 database.
3917
+ * on a v0 database or one a newer release migrated.
3600
3918
  */
3601
3919
  const createEngineMigrator = (options) => {
3602
3920
  const getVersion = async () => storedSchemaVersion(await options.readSettings());
3603
3921
  const makeResult = async (migrate = {}) => {
3604
3922
  const stored = await options.readSettings();
3605
3923
  refuseV0Database(options.adapterName, stored);
3606
- if (Object.entries(options.settings).every(([key, value]) => stored.get(key) === value)) return getEmptyMigrationResult();
3607
- return {
3608
- operations: [...options.schema.tables.map((table) => ({
3609
- type: "create-table",
3610
- value: {
3611
- ormName: table.name,
3612
- columns: Object.fromEntries(table.columns.map((column) => [column.name, {
3613
- ormName: column.name,
3614
- type: column.type
3615
- }]))
3924
+ refuseNewerSchema(options.adapterName, stored, options.settings, options.ordered);
3925
+ const changed = Object.entries(options.settings).filter(([key, value]) => stored.get(key) !== value);
3926
+ if (changed.length === 0) {
3927
+ const columns = await addLateColumns(options.adapter, options.schema.tables, { dryRun: true });
3928
+ const lacking = await fillLateIndexes(options.adapter, options.schema.tables, { dryRun: true });
3929
+ if (columns.length === 0 && lacking.length === 0) return getEmptyMigrationResult();
3930
+ return {
3931
+ operations: [
3932
+ ...columns.map((column) => ({
3933
+ type: "custom",
3934
+ description: `Add column: ${column}`
3935
+ })),
3936
+ ...columns.length === 0 ? [] : [{
3937
+ type: "custom",
3938
+ description: "Create the tables and indexes the database lacks"
3939
+ }],
3940
+ ...lacking.length === 0 ? [] : [{
3941
+ type: "custom",
3942
+ description: `Write the index items rows lack: ${lacking.join(", ")}`
3943
+ }]
3944
+ ],
3945
+ execute: async () => {
3946
+ if (columns.length > 0) {
3947
+ await addLateColumns(options.adapter, options.schema.tables);
3948
+ await options.adapter.migrations.apply([...options.schema.tables, SETTINGS_TABLE]);
3949
+ }
3950
+ await fillLateIndexes(options.adapter, options.schema.tables);
3616
3951
  }
3617
- })), ...migrate.updateSettings === false ? [] : [{
3618
- type: "custom",
3619
- description: `Write the schema settings: ${Object.keys(options.settings).join(", ")}`
3620
- }]],
3621
- execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings)
3952
+ };
3953
+ }
3954
+ return {
3955
+ operations: [
3956
+ ...(await addLateColumns(options.adapter, options.schema.tables, { dryRun: true }).catch(() => [])).map((column) => ({
3957
+ type: "custom",
3958
+ description: `Add column: ${column}`
3959
+ })),
3960
+ {
3961
+ type: "custom",
3962
+ description: "Create the tables and indexes the database lacks"
3963
+ },
3964
+ ...migrate.updateSettings === false ? [] : [settingsOperation(stored, changed)]
3965
+ ],
3966
+ execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings, options.ordered)
3622
3967
  };
3623
3968
  };
3624
3969
  return {
@@ -3649,7 +3994,8 @@ const coreSettings = {
3649
3994
  /** What `hot-updater db` creates for a server without plugins. */
3650
3995
  const coreTarget = {
3651
3996
  schema: coreSchema,
3652
- settings: coreSettings
3997
+ settings: coreSettings,
3998
+ ordered: ["schema.core"]
3653
3999
  };
3654
4000
  resolveSchema([aggregateBatchingModule]).tables;
3655
4001
  /** Each plugin's `schema.<id>` settings row. */
@@ -3669,11 +4015,12 @@ const pluginModule = ({ id, schema, namespace }) => ({
3669
4015
  */
3670
4016
  const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBatching, retry, readSettings: readStored }) => {
3671
4017
  const fenced = withSchemaFence(adapter, name, coreSettings);
3672
- const createMigrator = ({ schema, settings } = coreTarget) => createEngineMigrator({
4018
+ const createMigrator = ({ schema, settings, ordered } = coreTarget) => createEngineMigrator({
3673
4019
  adapterName: name,
3674
4020
  adapter,
3675
4021
  schema,
3676
4022
  settings,
4023
+ ordered,
3677
4024
  readSettings: readStored ?? (async () => {
3678
4025
  const rows = await readSettings(adapter, Object.keys(settings)).catch((error) => {
3679
4026
  if (isMissingSchemaError(error)) return [];
@@ -3697,6 +4044,12 @@ const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBa
3697
4044
  /** A row this attempt read changed while it ran; the attempt reruns. */
3698
4045
  var StaleReadError = class extends Error {};
3699
4046
  const idOf$1 = (table, key) => JSON.stringify([table, key]);
4047
+ /** The aggregate rows a write changes, at the versions it read them. */
4048
+ const versionsOf = (ops) => JSON.stringify(ops.map((op) => op.type === "insert" ? [op.table.name, rowKey(op.table, op.row)] : [
4049
+ op.table.name,
4050
+ op.key,
4051
+ "guard" in op ? op.guard?.v : void 0
4052
+ ]));
3700
4053
  const versionOf = (row) => Number(row["_v"]);
3701
4054
  const isKeyed = (value) => value !== null && value !== void 0;
3702
4055
  const misuse = (table, message) => new DatabaseTransactionError(`${table}: ${message}`);
@@ -4041,7 +4394,9 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4041
4394
  assertOutsideTransaction();
4042
4395
  let run;
4043
4396
  let negative;
4044
- for (let round = 0; round < attempts; round += 1) {
4397
+ let failures = 0;
4398
+ let lost;
4399
+ for (let round = 0;; round += 1) {
4045
4400
  const delay = round && Math.min(maxDelayMs, baseDelayMs * 2 ** (round - 1));
4046
4401
  if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay / 2 + Math.random() * (delay / 2)));
4047
4402
  run ??= await attempt(fn).catch((error) => {
@@ -4050,6 +4405,8 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4050
4405
  });
4051
4406
  if (run === void 0) {
4052
4407
  onRetry?.("rerun", round + 1);
4408
+ lost = void 0;
4409
+ if ((failures += 1) >= attempts) break;
4053
4410
  continue;
4054
4411
  }
4055
4412
  let aggregates;
@@ -4060,8 +4417,14 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4060
4417
  negative = error;
4061
4418
  onRetry?.("rerun", round + 1);
4062
4419
  run = void 0;
4420
+ lost = void 0;
4421
+ if ((failures += 1) >= attempts) break;
4063
4422
  continue;
4064
4423
  }
4424
+ const versions = versionsOf(aggregates);
4425
+ if (lost !== void 0 && versions !== lost) failures -= 1;
4426
+ lost = void 0;
4427
+ if (failures >= attempts) break;
4065
4428
  const ops = [...run.ops, ...aggregates];
4066
4429
  if (ops.length <= 1 && ops.every(({ type }) => type === "check")) return run.result;
4067
4430
  if (!adapter.fits(ops)) throw new DatabaseConstraintError("too_large", ops[0].table.name);
@@ -4075,12 +4438,16 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4075
4438
  const failed = "failedOp" in outcome ? outcome.failedOp : void 0;
4076
4439
  if (failed === void 0 || failed >= run.ops.length) {
4077
4440
  onRetry?.("resend", round + 1);
4441
+ failures += 1;
4442
+ if (failed !== void 0) lost = versions;
4443
+ else if (failures >= attempts) break;
4078
4444
  continue;
4079
4445
  }
4080
4446
  const reason = await classify(ops[failed], run.read);
4081
4447
  if (reason) throw new DatabaseConstraintError(reason, ops[failed].table.name);
4082
4448
  onRetry?.("rerun", round + 1);
4083
4449
  run = void 0;
4450
+ if ((failures += 1) >= attempts) break;
4084
4451
  }
4085
4452
  throw negative ?? new DatabaseConflictError(`The transaction conflicted ${attempts} times.`);
4086
4453
  } };
@@ -4326,13 +4693,10 @@ const createDatabaseEngine = ({ batching, now = Date.now, meter, ...options }) =
4326
4693
  };
4327
4694
  return {
4328
4695
  ...engine,
4329
- /** Applies batched aggregate changes still pending: this process's buffer and the log. */
4696
+ /** Applies the batched aggregate changes still in the log. */
4330
4697
  flush: async () => {
4331
4698
  await batches?.flush();
4332
4699
  },
4333
- dispose: async () => {
4334
- await batches?.dispose();
4335
- },
4336
4700
  database(module) {
4337
4701
  const name = (model) => module.namespace ? `${module.namespace}_${model}` : model;
4338
4702
  return {
@@ -4413,8 +4777,7 @@ const createEngine = (database, { plugins = [], now = Date.now } = {}) => {
4413
4777
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
4414
4778
  return engine.database(module);
4415
4779
  },
4416
- flush: () => engine.flush(),
4417
- dispose: () => engine.dispose()
4780
+ flush: () => engine.flush()
4418
4781
  };
4419
4782
  };
4420
4783
  //#endregion
@@ -4484,10 +4847,10 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
4484
4847
  const at = row && expiresAt(table, row);
4485
4848
  return at === void 0 ? {} : { expiresAt: at };
4486
4849
  };
4487
- /** Every index and unique item a row has, by address. */
4488
- const itemsOf = (layout, row) => {
4850
+ /** Every index and unique item a row has, by address: in `indexes`, if given. */
4851
+ const itemsOf = (layout, row, indexes = layout.indexed) => {
4489
4852
  const items = /* @__PURE__ */ new Map();
4490
- for (const index of row === null ? [] : layout.indexed) for (const eq of indexEntries(layout.table, index, row)) {
4853
+ for (const index of row === null ? [] : indexes) for (const eq of indexEntries(layout.table, index, row)) {
4491
4854
  const pk = partition(layout, index, eq);
4492
4855
  const sk = index.unique ? ONLY : encodeKvKey(indexOrderTuple(layout.table, index, row)) || ONLY;
4493
4856
  items.set(JSON.stringify([pk, sk]), {
@@ -4642,6 +5005,79 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
4642
5005
  lte: lt.endsWith(SEPARATOR) ? lt.slice(0, -1) : lt
4643
5006
  };
4644
5007
  };
5008
+ /** One row's check and its item puts in `index`, copies of the row as it is. */
5009
+ const fillOps = (layout, index, row) => [{
5010
+ type: "check",
5011
+ key: rowItem(layout, rowKey(layout.table, row)),
5012
+ condition: { v: Number(row["_v"]) }
5013
+ }, ...[...itemsOf(layout, row, [index]).values()].map(({ key }) => ({
5014
+ type: "put",
5015
+ key,
5016
+ value: copyOf(layout, row),
5017
+ ...stamp(layout.table, row)
5018
+ }))];
5019
+ /**
5020
+ * Writes one row's items in `index`, checking the row's `_v` in the same
5021
+ * write: a row that changed is read again, and a deleted one needs none.
5022
+ */
5023
+ const fillRow = async (layout, index, first) => {
5024
+ const key = rowItem(layout, rowKey(layout.table, first));
5025
+ let row = first;
5026
+ for (let attempt = 0; row !== null; attempt += 1) {
5027
+ 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.`);
5028
+ if ((await store.write(fillOps(layout, index, row))).ok) return;
5029
+ [row] = await store.get([key]);
5030
+ }
5031
+ };
5032
+ /**
5033
+ * Finds the rows that lack an item in `index` and, unless `dryRun`, writes
5034
+ * them, as many rows per atomic write as the store takes. It reads every
5035
+ * row and its items, page by page.
5036
+ */
5037
+ const fillIndex = async (table, name, { dryRun = false } = {}) => {
5038
+ const layout = layoutOf(table);
5039
+ const index = layout.indexed.find((candidate) => candidate.name === name);
5040
+ if (index === void 0) return 0;
5041
+ 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.`);
5042
+ const { items: most, bytes } = store.limits;
5043
+ let lacking = 0;
5044
+ for (let after;;) {
5045
+ const page = await store.query({
5046
+ pk: layout.rows,
5047
+ order: "asc",
5048
+ limit: 100,
5049
+ after
5050
+ });
5051
+ const rows = page.items.map(({ value }) => value);
5052
+ const keys = rows.map((row) => [...itemsOf(layout, row, [index]).values()].map(({ key }) => key));
5053
+ const wanted = keys.flat();
5054
+ const found = wanted.length === 0 ? [] : await store.get(wanted);
5055
+ let at = 0;
5056
+ const missing = rows.filter((_, position) => {
5057
+ return found.slice(at, at += keys[position].length).some((item) => item === null);
5058
+ });
5059
+ lacking += missing.length;
5060
+ if (!dryRun) {
5061
+ let chunk = [];
5062
+ let ops = [];
5063
+ const flush = async () => {
5064
+ if (ops.length > 0 && !(await store.write(ops)).ok) for (const row of chunk) await fillRow(layout, index, row);
5065
+ chunk = [];
5066
+ ops = [];
5067
+ };
5068
+ for (const row of missing) {
5069
+ const next = fillOps(layout, index, row);
5070
+ 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);
5071
+ if (chunk.length > 0 && (ops.length + next.length > most || size(ops) + size(next) > bytes)) await flush();
5072
+ chunk.push(row);
5073
+ ops.push(...next);
5074
+ }
5075
+ await flush();
5076
+ }
5077
+ if (!page.more || page.items.length === 0) return lacking;
5078
+ after = page.items.at(-1).sk;
5079
+ }
5080
+ };
4645
5081
  return {
4646
5082
  id: store.id,
4647
5083
  fits(ops) {
@@ -4701,13 +5137,16 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
4701
5137
  const layout = layoutOf(table);
4702
5138
  return store.deleteConsumed(rows.flatMap((row) => [rowItem(layout, rowKey(table, row)), ...[...itemsOf(layout, row).values()].map(({ key }) => key)]));
4703
5139
  } },
4704
- migrations: { apply: async () => store.migrations?.apply() },
5140
+ migrations: {
5141
+ apply: async () => store.migrations?.apply(),
5142
+ fillIndex
5143
+ },
4705
5144
  ...store.dispose === void 0 ? {} : { dispose: () => store.dispose() }
4706
5145
  };
4707
5146
  };
4708
5147
  //#endregion
4709
5148
  //#region ../../packages/server/dist/version.mjs
4710
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.5";
5149
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.51";
4711
5150
  //#endregion
4712
5151
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
4713
5152
  /**
@@ -4867,10 +5306,15 @@ const releaseCatalogScopeKeyOf = (input) => input.strategy === "APP_VERSION" ? c
4867
5306
  platform: input.platform,
4868
5307
  strategy: "FINGERPRINT"
4869
5308
  });
4870
- /** Projects a stored catalog row for one update check; null when the row is not this scope's. */
4871
- const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
4872
- 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;
4873
- const compiled = parseCompiledCatalog(row.payload, input.strategy);
5309
+ const parseReleaseCatalogRow = ({ payload, ...row }) => ({
5310
+ row,
5311
+ compiled: parseCompiledCatalog(payload, row.strategy)
5312
+ });
5313
+ /** Projects a parsed catalog row for one update check; null when the row is not this scope's. */
5314
+ const projectParsedReleaseCatalogRow = (parsed, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
5315
+ if (parsed === null) return null;
5316
+ const { row, compiled } = parsed;
5317
+ 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;
4874
5318
  const appVersion = input.strategy === "APP_VERSION" ? input.appVersion : void 0;
4875
5319
  return {
4876
5320
  catalogId: row.catalog_id,
@@ -4883,6 +5327,8 @@ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyO
4883
5327
  scopeKey
4884
5328
  };
4885
5329
  };
5330
+ /** Projects a stored catalog row for one update check; null when the row is not this scope's. */
5331
+ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => projectParsedReleaseCatalogRow(row === null ? null : parseReleaseCatalogRow(row), input, scopeKey);
4886
5332
  //#endregion
4887
5333
  //#region ../../packages/server/dist/db/updateArtifacts.mjs
4888
5334
  const HBC_ASSET_PATH_RE = /\.bundle$/;
@@ -5499,9 +5945,9 @@ const baseBundleIdsOf = (row, range, bundleId, limit) => {
5499
5945
  };
5500
5946
  //#endregion
5501
5947
  //#region ../../packages/server/dist/core/reads.mjs
5502
- const PAGE$3 = 500;
5503
- const pick$1 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
5504
- const toBundleRow = pick$1([
5948
+ const PAGE$4 = 500;
5949
+ const pick$2 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
5950
+ const toBundleRow = pick$2([
5505
5951
  "id",
5506
5952
  "platform",
5507
5953
  "git_commit_hash",
@@ -5510,7 +5956,7 @@ const toBundleRow = pick$1([
5510
5956
  "manifest_file_hash",
5511
5957
  "asset_base_storage_uri"
5512
5958
  ]);
5513
- const toPatchRow = pick$1([
5959
+ const toPatchRow = pick$2([
5514
5960
  "id",
5515
5961
  "bundle_id",
5516
5962
  "base_bundle_id",
@@ -5520,7 +5966,7 @@ const toPatchRow = pick$1([
5520
5966
  "byte_size",
5521
5967
  "order_index"
5522
5968
  ]);
5523
- const toReleaseRow = pick$1([
5969
+ const pickReleaseRow = pick$2([
5524
5970
  "id",
5525
5971
  "revision",
5526
5972
  "scope_key",
@@ -5541,7 +5987,14 @@ const toReleaseRow = pick$1([
5541
5987
  "created_at_ms",
5542
5988
  "updated_at_ms"
5543
5989
  ]);
5544
- const toCatalogRow = pick$1([
5990
+ /** A release row; `label` null where the store holds none, as before the column. */
5991
+ const toReleaseRow = (row) => {
5992
+ return {
5993
+ ...pickReleaseRow(row),
5994
+ label: typeof row.label === "number" ? row.label : null
5995
+ };
5996
+ };
5997
+ const toCatalogRow = pick$2([
5545
5998
  "scope_key",
5546
5999
  "catalog_id",
5547
6000
  "strategy",
@@ -5556,7 +6009,7 @@ const toCatalogRow = pick$1([
5556
6009
  "is_tombstone",
5557
6010
  "updated_at_ms"
5558
6011
  ]);
5559
- const toChannelRow = pick$1(["id", "name"]);
6012
+ const toChannelRow = pick$2(["id", "name"]);
5560
6013
  /** Every page of one read, in order. */
5561
6014
  const drain$1 = async (read) => {
5562
6015
  const rows = [];
@@ -5569,8 +6022,16 @@ const drain$1 = async (read) => {
5569
6022
  return rows;
5570
6023
  };
5571
6024
  /** A keyset page's range: the keys strictly after `after`, in `order`. */
5572
- const after = (input) => input.after === void 0 ? {} : { range: (input.order ?? "asc") === "asc" ? { gt: input.after } : { lt: input.after } };
5573
- /** Core's reads, each through one declared index or key. */
6025
+ /** A keyset read's range on its index's order: past `after`, up to `through`. */
6026
+ const after = (input) => {
6027
+ const asc = (input.order ?? "asc") === "asc";
6028
+ const range = {
6029
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
6030
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
6031
+ };
6032
+ return Object.keys(range).length === 0 ? {} : { range };
6033
+ };
6034
+ /** Core's reads, each through one declared index or key; plugins get `CoreReads`. */
5574
6035
  const createCoreReads = (db, storage) => {
5575
6036
  /** A bundle row's patches, exactly as many as its reference counter holds. */
5576
6037
  const detail = async (row) => {
@@ -5581,7 +6042,7 @@ const createCoreReads = (db, storage) => {
5581
6042
  const page = await db.findMany("bundle_patches", {
5582
6043
  index: "byBundle",
5583
6044
  where: { bundle_id: row.id },
5584
- limit: Math.min(count - patches.length, PAGE$3),
6045
+ limit: Math.min(count - patches.length, PAGE$4),
5585
6046
  ...cursor === void 0 ? {} : { cursor }
5586
6047
  });
5587
6048
  patches.push(...page.rows.map(toPatchRow));
@@ -5691,6 +6152,23 @@ const createCoreReads = (db, storage) => {
5691
6152
  const row = await db.findOne("releases", { id });
5692
6153
  return row === null ? null : toReleaseRow(row);
5693
6154
  },
6155
+ /**
6156
+ * The release a label names: its unique index, then the row itself,
6157
+ * since a key-value store keeps an index copy a server of an earlier
6158
+ * release may have left behind when it changed or deleted the row.
6159
+ */
6160
+ async getReleaseByLabel({ channel, platform, label }) {
6161
+ const found = await db.findOne("releases", {
6162
+ channel_id: `channel:${encodeChannelKey(channel)}`,
6163
+ platform,
6164
+ label
6165
+ });
6166
+ if (found === null) return null;
6167
+ const row = await db.findOne("releases", { id: found.id });
6168
+ if (row === null) return null;
6169
+ const release = toReleaseRow(row);
6170
+ return release.label === label && release.platform === platform ? release : null;
6171
+ },
5694
6172
  /** One page of releases through the index its filter names. */
5695
6173
  async listReleases(input) {
5696
6174
  const { filter } = input;
@@ -5758,15 +6236,47 @@ const createCoreReads = (db, storage) => {
5758
6236
  ...after(input)
5759
6237
  })).rows.map(toCatalogRow);
5760
6238
  },
5761
- /** Every channel, by name. */
5762
- async listChannels() {
6239
+ /**
6240
+ * Up to `limit` scope keys that have releases, ascending after `after`:
6241
+ * one limit-1 seek of the `scopes` index past each scope, so the reads
6242
+ * grow with the scopes, not with their releases.
6243
+ */
6244
+ async listReleaseScopeKeys(input) {
6245
+ const scopeKeys = [];
6246
+ for (let last = input.after ?? ""; scopeKeys.length < input.limit;) {
6247
+ const { rows } = await db.findMany("releases", {
6248
+ index: "scopes",
6249
+ where: {},
6250
+ limit: 1,
6251
+ range: { gt: last }
6252
+ });
6253
+ if (rows[0] === void 0) break;
6254
+ last = rows[0].scope_key;
6255
+ scopeKeys.push(last);
6256
+ }
6257
+ return scopeKeys;
6258
+ },
6259
+ /** Every channel by name; with `input`, one keyset page of them. */
6260
+ async listChannels(input) {
6261
+ if (input !== void 0) return (await db.findMany("channels", {
6262
+ index: "all",
6263
+ where: {},
6264
+ order: input.order ?? "asc",
6265
+ limit: input.limit,
6266
+ ...after(input)
6267
+ })).rows.map(toChannelRow);
5763
6268
  return (await drain$1((page) => db.findMany("channels", {
5764
6269
  index: "all",
5765
6270
  where: {},
5766
- limit: PAGE$3,
6271
+ limit: PAGE$4,
5767
6272
  ...page
5768
6273
  }))).map(toChannelRow);
5769
6274
  },
6275
+ async getChannels(ids) {
6276
+ const unique = [...new Set(ids)];
6277
+ if (unique.length === 0) return [];
6278
+ return (await db.findByKeys("channels", unique.map((id) => ({ id })))).flatMap((row) => row ? [toChannelRow(row)] : []);
6279
+ },
5770
6280
  async findChannelByName(name) {
5771
6281
  const row = await db.findOne("channels", { name });
5772
6282
  return row === null ? null : toChannelRow(row);
@@ -5774,6 +6284,625 @@ const createCoreReads = (db, storage) => {
5774
6284
  };
5775
6285
  };
5776
6286
  //#endregion
6287
+ //#region ../../packages/server/dist/core/iosDevices.mjs
6288
+ /**
6289
+ * A device's UDID: 40 hex digits, or 8 and 16 joined by a hyphen. The same
6290
+ * rule as `normalizeIosUdid` of `@hot-updater/protocol/native-artifact`,
6291
+ * implemented here so the server's runtime never loads the artifact readers.
6292
+ */
6293
+ const UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
6294
+ /** The form the registry stores and compares a UDID in, or null for text that isn't one. */
6295
+ const normalizeIosUdid = (value) => {
6296
+ const trimmed = value.trim();
6297
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
6298
+ };
6299
+ /** `ios_devices.name`'s bound in core's schema. */
6300
+ const NAME_MAX_LENGTH = 100;
6301
+ /** `ios_devices.requested_by` and `approved_by`'s bound: an email address. */
6302
+ const EMAIL_MAX_LENGTH = 320;
6303
+ /** `ios_devices.apple_issuer_id`'s bound. */
6304
+ const ISSUER_MAX_LENGTH = 64;
6305
+ /** The one row of `ios_device_account`. */
6306
+ const ACCOUNT_ROW = "registry";
6307
+ /** `ios_devices.apple_error`'s bound. */
6308
+ const ERROR_MAX_LENGTH = 512;
6309
+ const STATUSES = [
6310
+ "pending",
6311
+ "approved",
6312
+ "registered"
6313
+ ];
6314
+ const OUTCOMES = [
6315
+ "registered",
6316
+ "refused",
6317
+ "disabled",
6318
+ "missing"
6319
+ ];
6320
+ /** The `apple_error` of a device Apple has disabled. */
6321
+ const IOS_DEVICE_DISABLED_ERROR = "Disabled in the Apple account.";
6322
+ /** The `apple_error` of a registered device Apple no longer lists. */
6323
+ const IOS_DEVICE_MISSING_ERROR = "Gone from the Apple account. Approve it again to register it.";
6324
+ /** A device or registry request core cannot store: the caller's input. */
6325
+ var IosDeviceInputError = class extends TypeError {
6326
+ name = "IosDeviceInputError";
6327
+ };
6328
+ const pick$1 = (row) => ({
6329
+ id: row.id,
6330
+ udid: row.udid,
6331
+ name: row.name,
6332
+ status: row.status,
6333
+ requested_by: row.requested_by ?? null,
6334
+ created_at_ms: row.created_at_ms,
6335
+ approved_by: row.approved_by ?? null,
6336
+ approved_at_ms: row.approved_at_ms ?? null,
6337
+ registered_at_ms: row.registered_at_ms ?? null,
6338
+ apple_issuer_id: row.apple_issuer_id ?? null,
6339
+ apple_error: row.apple_error ?? null,
6340
+ build_id: row.build_id ?? null
6341
+ });
6342
+ const udidOf = (udid) => {
6343
+ const key = typeof udid === "string" ? normalizeIosUdid(udid) : null;
6344
+ if (key === null) throw new IosDeviceInputError("Invalid iOS device: udid must be 40 hex digits, or 8 and 16 joined by a hyphen.");
6345
+ return key;
6346
+ };
6347
+ const nameOf$1 = (name) => {
6348
+ const trimmed = typeof name === "string" ? name.trim() : "";
6349
+ if (trimmed.length === 0 || trimmed.length > NAME_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: name must be 1 to ${NAME_MAX_LENGTH} characters.`);
6350
+ return trimmed;
6351
+ };
6352
+ /** An email, lower-cased, or null for the CLI. */
6353
+ const personOf = (value, field) => {
6354
+ if (value === null) return null;
6355
+ const email = typeof value === "string" ? value.trim().toLowerCase() : "";
6356
+ 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.`);
6357
+ return email;
6358
+ };
6359
+ /** Apple's words, on one line and within the column's bound. */
6360
+ const errorText = (text) => {
6361
+ const line = text.replace(/\s+/gu, " ").trim();
6362
+ return line.length > ERROR_MAX_LENGTH ? `${line.slice(0, 511)}…` : line;
6363
+ };
6364
+ /**
6365
+ * The iOS device registry: the iPhones and iPads a team asked to install ad hoc
6366
+ * builds on. The Console writes requests and approvals, and the CLI what Apple
6367
+ * said, each over the row it read.
6368
+ */
6369
+ const createIosDeviceApi = (db, { now = Date.now } = {}) => {
6370
+ const findIosDevice = async (udid) => {
6371
+ const key = normalizeIosUdid(udid);
6372
+ if (key === null) return null;
6373
+ const row = await db.findOne("ios_devices", { udid: key });
6374
+ return row === null ? null : pick$1(row);
6375
+ };
6376
+ /**
6377
+ * The issuer of the registry's earliest registration among its rows, by
6378
+ * when and then by ID, or null when no row names one: read only while the
6379
+ * registry has no account yet, in one read of its first registration. A
6380
+ * row names an issuer exactly when it has a registration time: both are
6381
+ * set by its first registration and never cleared.
6382
+ */
6383
+ const accountOfRows = async () => {
6384
+ const { rows } = await db.findMany("ios_devices", {
6385
+ index: "byRegistration",
6386
+ where: {},
6387
+ order: "asc",
6388
+ limit: 1,
6389
+ range: { gte: 0 }
6390
+ });
6391
+ return (rows[0] === void 0 ? null : pick$1(rows[0]))?.apple_issuer_id ?? null;
6392
+ };
6393
+ return {
6394
+ async listIosDevices(input) {
6395
+ if (input.status !== void 0 && !STATUSES.includes(input.status)) throw new IosDeviceInputError(`Invalid iOS device status: ${String(input.status)}. Expected ${STATUSES.join(", ")}.`);
6396
+ const page = {
6397
+ order: input.order ?? "asc",
6398
+ limit: input.limit,
6399
+ ...after(input)
6400
+ };
6401
+ const { rows } = input.status === void 0 ? await db.findMany("ios_devices", {
6402
+ index: "all",
6403
+ where: {},
6404
+ ...page
6405
+ }) : await db.findMany("ios_devices", {
6406
+ index: "byStatus",
6407
+ where: { status: input.status },
6408
+ ...page
6409
+ });
6410
+ return rows.map(pick$1);
6411
+ },
6412
+ findIosDevice,
6413
+ async requestIosDevice(input) {
6414
+ const udid = udidOf(input.udid);
6415
+ const name = nameOf$1(input.name);
6416
+ const requestedBy = personOf(input.requestedBy, "requestedBy");
6417
+ const existing = await db.findOne("ios_devices", { udid });
6418
+ if (existing !== null) return {
6419
+ device: pick$1(existing),
6420
+ created: false
6421
+ };
6422
+ const device = {
6423
+ id: createUUIDv7(),
6424
+ udid,
6425
+ name,
6426
+ status: "pending",
6427
+ requested_by: requestedBy,
6428
+ created_at_ms: now(),
6429
+ approved_by: null,
6430
+ approved_at_ms: null,
6431
+ registered_at_ms: null,
6432
+ apple_issuer_id: null,
6433
+ apple_error: null,
6434
+ build_id: null
6435
+ };
6436
+ try {
6437
+ await db.transaction(async (tx) => {
6438
+ tx.create("ios_devices", device);
6439
+ });
6440
+ } catch (error) {
6441
+ if (error instanceof DatabaseConstraintError && error.reason === "unique") {
6442
+ const winner = await db.findOne("ios_devices", { udid });
6443
+ if (winner !== null) return {
6444
+ device: pick$1(winner),
6445
+ created: false
6446
+ };
6447
+ }
6448
+ throw error;
6449
+ }
6450
+ return {
6451
+ device,
6452
+ created: true
6453
+ };
6454
+ },
6455
+ async approveIosDevice(id, input) {
6456
+ const name = input.name === void 0 ? void 0 : nameOf$1(input.name);
6457
+ const approvedBy = personOf(input.approvedBy, "approvedBy");
6458
+ return db.transaction(async (tx) => {
6459
+ const row = await tx.findOne("ios_devices", { id });
6460
+ if (row === null) return null;
6461
+ const device = pick$1(row);
6462
+ const set = {
6463
+ ...name === void 0 || name === device.name ? {} : { name },
6464
+ ...device.status === "pending" ? {
6465
+ status: "approved",
6466
+ approved_by: approvedBy,
6467
+ approved_at_ms: now()
6468
+ } : {}
6469
+ };
6470
+ if (Object.keys(set).length === 0) return device;
6471
+ tx.update("ios_devices", row, set);
6472
+ return {
6473
+ ...device,
6474
+ ...set
6475
+ };
6476
+ });
6477
+ },
6478
+ async renameIosDevice(id, input) {
6479
+ const name = nameOf$1(input);
6480
+ return db.transaction(async (tx) => {
6481
+ const row = await tx.findOne("ios_devices", { id });
6482
+ if (row === null) return null;
6483
+ const device = pick$1(row);
6484
+ if (device.name === name) return device;
6485
+ tx.update("ios_devices", row, { name });
6486
+ return {
6487
+ ...device,
6488
+ name
6489
+ };
6490
+ });
6491
+ },
6492
+ async recordIosDeviceOutcome({ id, seen, issuerId, outcome, reason }) {
6493
+ if (!OUTCOMES.includes(outcome)) throw new IosDeviceInputError(`Invalid iOS device outcome: ${String(outcome)}. Expected ${OUTCOMES.join(", ")}.`);
6494
+ 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.`);
6495
+ return db.transaction(async (tx) => {
6496
+ const row = await tx.findOne("ios_devices", { id });
6497
+ if (row === null) return null;
6498
+ const device = pick$1(row);
6499
+ if (device.status !== seen.status || device.approved_at_ms !== seen.approvedAtMs || device.apple_issuer_id !== null && device.apple_issuer_id !== issuerId) return null;
6500
+ let set;
6501
+ switch (outcome) {
6502
+ case "registered":
6503
+ if (device.status === "pending") return null;
6504
+ set = {
6505
+ status: "registered",
6506
+ registered_at_ms: device.registered_at_ms ?? now(),
6507
+ apple_issuer_id: issuerId,
6508
+ apple_error: null
6509
+ };
6510
+ break;
6511
+ case "refused":
6512
+ if (device.status !== "approved") return null;
6513
+ set = { apple_error: errorText(reason === void 0 || reason.trim() === "" ? "Apple refused it." : reason) };
6514
+ break;
6515
+ case "disabled":
6516
+ if (device.status === "pending") return null;
6517
+ set = { apple_error: IOS_DEVICE_DISABLED_ERROR };
6518
+ break;
6519
+ case "missing":
6520
+ if (device.status !== "registered") return null;
6521
+ set = {
6522
+ status: "pending",
6523
+ approved_by: null,
6524
+ approved_at_ms: null,
6525
+ apple_error: IOS_DEVICE_MISSING_ERROR
6526
+ };
6527
+ }
6528
+ if (Object.entries(set).some(([column, value]) => device[column] !== (value ?? null))) tx.update("ios_devices", row, set);
6529
+ return {
6530
+ ...device,
6531
+ ...set
6532
+ };
6533
+ });
6534
+ },
6535
+ async markIosDevicesInBuild({ buildId, ids }) {
6536
+ for (const id of new Set(ids)) await db.transaction(async (tx) => {
6537
+ const row = await tx.findOne("ios_devices", { id });
6538
+ if (row === null || typeof row.build_id === "string" && row.build_id >= buildId) return;
6539
+ tx.update("ios_devices", row, { build_id: buildId });
6540
+ });
6541
+ },
6542
+ async findIosDeviceAccount() {
6543
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6544
+ const issuerId = existing === null ? await accountOfRows() : existing.apple_issuer_id;
6545
+ return issuerId === null ? null : { issuerId };
6546
+ },
6547
+ async claimIosDeviceAccount(issuerId) {
6548
+ 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.`);
6549
+ const answer = (held) => ({
6550
+ issuerId: held,
6551
+ claimed: held === issuerId
6552
+ });
6553
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6554
+ if (existing !== null) return answer(existing.apple_issuer_id);
6555
+ const holder = await accountOfRows() ?? issuerId;
6556
+ try {
6557
+ await db.transaction(async (tx) => {
6558
+ tx.create("ios_device_account", {
6559
+ id: ACCOUNT_ROW,
6560
+ apple_issuer_id: holder,
6561
+ claimed_at_ms: now()
6562
+ });
6563
+ });
6564
+ return answer(holder);
6565
+ } catch (error) {
6566
+ if (error instanceof DatabaseConstraintError && (error.reason === "exists" || error.reason === "unique")) {
6567
+ const winner = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6568
+ if (winner !== null) return answer(winner.apple_issuer_id);
6569
+ }
6570
+ throw error;
6571
+ }
6572
+ },
6573
+ async deleteIosDevice(id, only) {
6574
+ const requestedBy = only?.requestedBy === void 0 ? void 0 : personOf(only.requestedBy, "requestedBy");
6575
+ return db.transaction(async (tx) => {
6576
+ const row = await tx.findOne("ios_devices", { id });
6577
+ if (row === null) return null;
6578
+ const device = pick$1(row);
6579
+ if (only?.status !== void 0 && device.status !== only.status || requestedBy !== void 0 && device.requested_by !== requestedBy) return null;
6580
+ await tx.delete("ios_devices", row);
6581
+ return device;
6582
+ });
6583
+ }
6584
+ };
6585
+ };
6586
+ //#endregion
6587
+ //#region ../../packages/server/dist/core/nativeBuildDestinations.mjs
6588
+ /** Store destinations accepted for each native platform. */
6589
+ const NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
6590
+ android: [
6591
+ "play-internal",
6592
+ "play-closed",
6593
+ "play-open",
6594
+ "play-production"
6595
+ ],
6596
+ ios: ["testflight"]
6597
+ };
6598
+ //#endregion
6599
+ //#region ../../packages/server/dist/core/labels.mjs
6600
+ /**
6601
+ * The counter of a channel and platform's release labels: one
6602
+ * `label_sequences` row, which every writer of the pair reads and bumps.
6603
+ */
6604
+ const labelSequenceId = (channelId, platform) => `releases/${platform}/${channelId}`;
6605
+ /** The pairs a channel's counters belong to, which deleting it removes. */
6606
+ const LABEL_PLATFORMS = ["ios", "android"];
6607
+ /**
6608
+ * A channel and platform whose releases written before labels have none
6609
+ * yet, or that has no counter: the write stops before taking a label, the
6610
+ * core labels the pair with `fillLabels`, and the write runs again.
6611
+ */
6612
+ var NeedsLabelFill = class extends Error {
6613
+ channelId;
6614
+ platform;
6615
+ constructor(channelId, platform) {
6616
+ super(`Release labels of ${platform} ${channelId} need a fill first.`);
6617
+ this.channelId = channelId;
6618
+ this.platform = platform;
6619
+ }
6620
+ };
6621
+ const createLabelAllocator = (tx, used, caughtUp) => {
6622
+ const sequences = /* @__PURE__ */ new Map();
6623
+ return {
6624
+ async next(channelId, platform) {
6625
+ const id = labelSequenceId(channelId, platform);
6626
+ let sequence = sequences.get(id);
6627
+ if (sequence === void 0) {
6628
+ const row = await tx.findOne("label_sequences", { id });
6629
+ if (row === null || !row.is_filled) {
6630
+ const channel = row === null ? await tx.findOne("channels", { id: channelId }) : null;
6631
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) throw new NeedsLabelFill(channelId, platform);
6632
+ }
6633
+ const read = row?.last_label ?? 0;
6634
+ sequence = {
6635
+ row,
6636
+ read,
6637
+ last: read
6638
+ };
6639
+ sequences.set(id, sequence);
6640
+ used.set(id, {
6641
+ channelId,
6642
+ platform,
6643
+ read
6644
+ });
6645
+ }
6646
+ sequence.last += 1;
6647
+ return sequence.last;
6648
+ },
6649
+ caughtUp(channelId, platform) {
6650
+ caughtUp.set(labelSequenceId(channelId, platform), {
6651
+ channelId,
6652
+ platform
6653
+ });
6654
+ },
6655
+ flush() {
6656
+ for (const [id, { row, read, last }] of sequences) if (row === null) tx.create("label_sequences", {
6657
+ id,
6658
+ last_label: last,
6659
+ is_filled: true
6660
+ });
6661
+ else if (last !== read) tx.update("label_sequences", row, { last_label: last });
6662
+ }
6663
+ };
6664
+ };
6665
+ const FILL_BATCH = 25;
6666
+ const PAGE$3 = 500;
6667
+ /**
6668
+ * Labels a channel and platform's releases that have none, in ID order,
6669
+ * which is the order they were created in, and marks its counter filled:
6670
+ * each batch reads the counter and its rows guarded, so a concurrent fill or
6671
+ * write serializes on the counter and skips what another labeled. With
6672
+ * `dryRun`, it only counts them. Answers how many it labeled.
6673
+ */
6674
+ const fillLabels = async (db, { channelId, platform }, { dryRun = false } = {}) => {
6675
+ const id = labelSequenceId(channelId, platform);
6676
+ let labeled = 0;
6677
+ let batchSize = FILL_BATCH;
6678
+ const label = async (ids) => {
6679
+ for (let at = 0; at < ids.length;) {
6680
+ const batch = ids.slice(at, at + batchSize);
6681
+ try {
6682
+ labeled += await db.transaction(async (tx) => {
6683
+ const counter = await tx.findOne("label_sequences", { id });
6684
+ let last = counter?.last_label ?? 0;
6685
+ let count = 0;
6686
+ for (const releaseId of batch) {
6687
+ const row = await tx.findOne("releases", { id: releaseId });
6688
+ if (row === null || typeof row.label === "number") continue;
6689
+ last += 1;
6690
+ count += 1;
6691
+ tx.update("releases", row, { label: last });
6692
+ }
6693
+ if (counter === null) tx.create("label_sequences", {
6694
+ id,
6695
+ last_label: last,
6696
+ is_filled: false
6697
+ });
6698
+ else if (last !== counter.last_label) tx.update("label_sequences", counter, { last_label: last });
6699
+ return count;
6700
+ });
6701
+ at += batch.length;
6702
+ } catch (error) {
6703
+ if (batchSize > 1 && error instanceof DatabaseConstraintError && error.reason === "too_large") {
6704
+ batchSize = Math.max(1, Math.floor(batchSize / 2));
6705
+ continue;
6706
+ }
6707
+ throw error;
6708
+ }
6709
+ }
6710
+ };
6711
+ let cursor;
6712
+ do {
6713
+ const page = await db.findMany("releases", {
6714
+ index: "byChannelPlatform",
6715
+ where: {
6716
+ channel_id: channelId,
6717
+ platform
6718
+ },
6719
+ limit: PAGE$3,
6720
+ ...cursor === void 0 ? {} : { cursor }
6721
+ });
6722
+ const unlabeled = page.rows.filter((row) => typeof row.label !== "number").map((row) => row.id);
6723
+ if (dryRun) labeled += unlabeled.length;
6724
+ else await label(unlabeled);
6725
+ cursor = page.next;
6726
+ } while (cursor !== void 0);
6727
+ if (dryRun) return labeled;
6728
+ await db.transaction(async (tx) => {
6729
+ const counter = await tx.findOne("label_sequences", { id });
6730
+ if (counter === null) tx.create("label_sequences", {
6731
+ id,
6732
+ last_label: 0,
6733
+ is_filled: true
6734
+ });
6735
+ else if (!counter.is_filled) tx.update("label_sequences", counter, { is_filled: true });
6736
+ });
6737
+ return labeled;
6738
+ };
6739
+ /**
6740
+ * Reads what a pair's fill writes, its counter and its label index, without
6741
+ * writing: a database without release labels' schema, such as one a 1.2
6742
+ * prerelease migrated, fails here as the fill would. The schema is the
6743
+ * database's, so one pair tells. Two reads.
6744
+ */
6745
+ const probeLabelSchema = async (db, { channelId, platform }) => {
6746
+ await db.findOne("label_sequences", { id: labelSequenceId(channelId, platform) });
6747
+ await db.findMany("releases", {
6748
+ index: "byLabel",
6749
+ where: {
6750
+ channel_id: channelId,
6751
+ platform,
6752
+ label: 0
6753
+ },
6754
+ limit: 1
6755
+ });
6756
+ };
6757
+ const REPAIRS = 4;
6758
+ const RACES = 32;
6759
+ /**
6760
+ * Runs a release write that takes labels, in one transaction with the
6761
+ * counters it bumps. A pair that still needs its fill is filled, and the
6762
+ * write runs again; so is a pair whose catch-up made the write too large for
6763
+ * the store. A label another row holds, such as an index item a release
6764
+ * deleted by a server of an earlier release left on a key-value store, is
6765
+ * skipped: its counters move past it and the write runs again.
6766
+ */
6767
+ const writeWithLabels = async (db, write) => {
6768
+ const filled = /* @__PURE__ */ new Set();
6769
+ const fill = async (pairs) => {
6770
+ for (const pair of pairs) {
6771
+ filled.add(labelSequenceId(pair.channelId, pair.platform));
6772
+ await fillLabels(db, pair);
6773
+ }
6774
+ };
6775
+ for (let repairs = 0, races = 0;;) {
6776
+ const used = /* @__PURE__ */ new Map();
6777
+ const caughtUp = /* @__PURE__ */ new Map();
6778
+ try {
6779
+ return await db.transaction(async (tx) => {
6780
+ used.clear();
6781
+ caughtUp.clear();
6782
+ const labels = createLabelAllocator(tx, used, caughtUp);
6783
+ const result = await write(tx, labels);
6784
+ labels.flush();
6785
+ return result;
6786
+ });
6787
+ } catch (error) {
6788
+ const needs = error instanceof NeedsLabelFill ? [error] : error instanceof DatabaseConstraintError && error.reason === "too_large" ? [...caughtUp.values()] : [];
6789
+ if (needs.length > 0) {
6790
+ const fresh = needs.some(({ channelId, platform }) => !filled.has(labelSequenceId(channelId, platform)));
6791
+ if (fresh || repairs < REPAIRS) {
6792
+ if (!fresh) repairs += 1;
6793
+ await fill(needs);
6794
+ continue;
6795
+ }
6796
+ }
6797
+ if (error instanceof DatabaseConstraintError && error.reason === "unique" && error.model === "releases" && used.size > 0) {
6798
+ if (await db.transaction(async (tx) => {
6799
+ const moves = [];
6800
+ for (const [id, { channelId, read }] of used) {
6801
+ const counter = await tx.findOne("label_sequences", { id });
6802
+ if (counter !== null) {
6803
+ if (counter.last_label !== read) return false;
6804
+ moves.push(() => tx.update("label_sequences", counter, { last_label: read + 1 }));
6805
+ continue;
6806
+ }
6807
+ const channel = await tx.findOne("channels", { id: channelId });
6808
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) return false;
6809
+ moves.push(() => tx.create("label_sequences", {
6810
+ id,
6811
+ last_label: read + 1,
6812
+ is_filled: true
6813
+ }));
6814
+ }
6815
+ for (const move of moves) move();
6816
+ return true;
6817
+ }) ? (repairs += 1) <= REPAIRS : (races += 1) <= RACES) continue;
6818
+ }
6819
+ throw error;
6820
+ }
6821
+ }
6822
+ };
6823
+ /**
6824
+ * Labels a scope's releases a server of an earlier release wrote after its
6825
+ * newest labeled one, oldest first, before the write takes its own label:
6826
+ * `latest` is the scope's newest release, so a labeled one costs no read.
6827
+ * Answers the labels it gave, by release ID.
6828
+ */
6829
+ const catchUpLabels = async (tx, labels, latest) => {
6830
+ const given = /* @__PURE__ */ new Map();
6831
+ if (latest === null || typeof latest.label === "number") return given;
6832
+ const unlabeled = [];
6833
+ let cursor;
6834
+ scan: do {
6835
+ const page = await tx.findMany("releases", {
6836
+ index: "byScope",
6837
+ where: { scope_key: latest.scope_key },
6838
+ order: "desc",
6839
+ limit: FILL_BATCH,
6840
+ ...cursor === void 0 ? {} : { cursor }
6841
+ });
6842
+ for (const row of page.rows) {
6843
+ if (typeof row.label === "number") break scan;
6844
+ unlabeled.push(row);
6845
+ }
6846
+ cursor = page.next;
6847
+ } while (cursor !== void 0);
6848
+ labels.caughtUp(latest.channel_id, latest.platform);
6849
+ for (const row of unlabeled.reverse()) {
6850
+ const { id, channel_id, platform } = toReleaseRow(row);
6851
+ const label = await labels.next(channel_id, platform);
6852
+ tx.update("releases", row, { label });
6853
+ given.set(id, label);
6854
+ }
6855
+ return given;
6856
+ };
6857
+ /**
6858
+ * The channels and platforms whose releases need labels: a scope whose
6859
+ * newest release has none, or a pair without a filled counter. Releases a
6860
+ * server of an earlier release wrote in a filled pair come after its
6861
+ * labeled ones in their scope, so the newest release of each scope tells.
6862
+ * Two reads per scope, one per pair.
6863
+ */
6864
+ const pendingLabelPairs = async (db) => {
6865
+ const pairs = /* @__PURE__ */ new Map();
6866
+ for (let last = "";;) {
6867
+ const { rows } = await db.findMany("releases", {
6868
+ index: "scopes",
6869
+ where: {},
6870
+ limit: 1,
6871
+ range: { gt: last }
6872
+ });
6873
+ if (rows[0] === void 0) break;
6874
+ last = rows[0].scope_key;
6875
+ const { rows: newest } = await db.findMany("releases", {
6876
+ index: "byScope",
6877
+ where: { scope_key: last },
6878
+ order: "desc",
6879
+ limit: 1
6880
+ });
6881
+ if (newest[0] === void 0) continue;
6882
+ const { channel_id: channelId, platform, label } = toReleaseRow(newest[0]);
6883
+ const id = labelSequenceId(channelId, platform);
6884
+ const pair = pairs.get(id) ?? {
6885
+ channelId,
6886
+ platform,
6887
+ pending: false
6888
+ };
6889
+ pair.pending ||= label === null;
6890
+ pairs.set(id, pair);
6891
+ }
6892
+ const pending = [];
6893
+ for (const [id, { channelId, platform, pending: unlabeled }] of pairs) {
6894
+ if (!unlabeled) {
6895
+ const counter = await db.findOne("label_sequences", { id });
6896
+ if (counter !== null && counter.is_filled) continue;
6897
+ }
6898
+ pending.push({
6899
+ channelId,
6900
+ platform
6901
+ });
6902
+ }
6903
+ return pending;
6904
+ };
6905
+ //#endregion
5777
6906
  //#region ../../packages/server/dist/core/writes.mjs
5778
6907
  const PAGE$2 = 500;
5779
6908
  /** Moves one bundle into or out of its platform's total and the overall total. */
@@ -5803,8 +6932,10 @@ const deleteBundle = async (tx, current) => {
5803
6932
  /**
5804
6933
  * Replaces a bundle's patches with `rows`: kept patches are updated where
5805
6934
  * they changed, others deleted or created, so no key is written twice.
6935
+ * `checkNew` sees each patch it is about to create, and refuses one by
6936
+ * throwing, which leaves the transaction's writes undone.
5806
6937
  */
5807
- const replaceBundlePatches = async (tx, bundle, rows) => {
6938
+ const replaceBundlePatches = async (tx, bundle, rows, checkNew) => {
5808
6939
  const wanted = new Map(rows.map((row) => [row.id, row]));
5809
6940
  const count = bundle._refs_bundle_patches_bundle_id ?? 0;
5810
6941
  let cursor;
@@ -5829,6 +6960,7 @@ const replaceBundlePatches = async (tx, bundle, rows) => {
5829
6960
  if (page.next === void 0) break;
5830
6961
  cursor = page.next;
5831
6962
  }
6963
+ if (checkNew !== void 0) for (const row of wanted.values()) await checkNew(row);
5832
6964
  for (const row of wanted.values()) tx.create("bundle_patches", row);
5833
6965
  };
5834
6966
  /** A channel by name, created when missing; a concurrent creator's row is returned instead. */
@@ -5851,7 +6983,11 @@ const insertChannel = async (db, row) => {
5851
6983
  throw error;
5852
6984
  }
5853
6985
  };
5854
- /** Deletes a channel no release or native build uses: 1 read, 1 query, 1 write. */
6986
+ /**
6987
+ * Deletes a channel no release or native build uses, with its label
6988
+ * counters, so one created again with its name starts at 1: 3 reads,
6989
+ * 1 query, 1 write.
6990
+ */
5855
6991
  const deleteChannel = (db, id) => db.transaction(async (tx) => {
5856
6992
  const row = await tx.findOne("channels", { id });
5857
6993
  if (row === null) return {
@@ -5871,6 +7007,10 @@ const deleteChannel = (db, id) => db.transaction(async (tx) => {
5871
7007
  deleted: false,
5872
7008
  reason: "not_empty"
5873
7009
  };
7010
+ for (const platform of LABEL_PLATFORMS) {
7011
+ const counter = await tx.findOne("label_sequences", { id: labelSequenceId(id, platform) });
7012
+ if (counter !== null) await tx.delete("label_sequences", counter);
7013
+ }
5874
7014
  await tx.delete("channels", row);
5875
7015
  return { deleted: true };
5876
7016
  });
@@ -5891,6 +7031,27 @@ const GIT_COMMIT_HASH_MAX_LENGTH = 255;
5891
7031
  * and looks up nothing else.
5892
7032
  */
5893
7033
  const BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
7034
+ /** `native_builds.sandbox_url_scheme`'s bound in core's schema. */
7035
+ const SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
7036
+ /**
7037
+ * A URL scheme as RFC 3986 spells it, in lower case: what a sandbox build's
7038
+ * artifact registers, as `@hot-updater/protocol/native-artifact` reads it.
7039
+ */
7040
+ const URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
7041
+ /**
7042
+ * A bundle identifier or application ID, as an artifact reports it: letters,
7043
+ * digits, dots, dashes and underscores, which a scope key holds as they are.
7044
+ */
7045
+ const APP_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;
7046
+ /** A fingerprint hash as a Release Catalog scope key holds it. */
7047
+ const FINGERPRINT_HASH = /^[A-Za-z0-9._~-]{1,255}$/;
7048
+ /** How each kind of artifact can install. */
7049
+ const DISTRIBUTIONS = {
7050
+ apk: ["direct"],
7051
+ app: ["direct"],
7052
+ aab: ["store"],
7053
+ ipa: ["direct", "store"]
7054
+ };
5894
7055
  /** A native build or scope core cannot store or look up: the caller's input. */
5895
7056
  var NativeBuildInputError = class extends TypeError {
5896
7057
  name = "NativeBuildInputError";
@@ -5912,24 +7073,73 @@ const pick = (row) => ({
5912
7073
  build_number: row.build_number ?? null,
5913
7074
  submitted_to: row.submitted_to ?? null,
5914
7075
  submitted_at_ms: row.submitted_at_ms ?? null,
5915
- submitted_version: row.submitted_version ?? null
7076
+ submitted_version: row.submitted_version ?? null,
7077
+ is_store_build: row.is_store_build === true,
7078
+ is_sandbox: row.is_sandbox === true,
7079
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
7080
+ export_method: row.export_method ?? null,
7081
+ native_app_version: row.native_app_version ?? null
5916
7082
  });
5917
- /** The store track each platform's builds are submitted to. */
5918
- const SUBMISSION_DESTINATIONS = {
5919
- android: "play-internal",
5920
- ios: "testflight"
5921
- };
7083
+ /** The export methods an `.ipa` registers with. */
7084
+ const EXPORT_METHODS = /* @__PURE__ */ new Set([
7085
+ "app-store",
7086
+ "ad-hoc",
7087
+ "development",
7088
+ "enterprise"
7089
+ ]);
7090
+ /**
7091
+ * How many older builds of a scope one read takes, looking for one older than
7092
+ * a bundle when a build made after the bundle is the newest.
7093
+ */
7094
+ const OLDER_BUILDS_PAGE = 20;
7095
+ /**
7096
+ * How many pages of older builds that look reads before it answers null: 100
7097
+ * builds made after the bundle in one scope, where a deploy's new bundle has
7098
+ * none or a few registered while it deploys.
7099
+ */
7100
+ const OLDER_BUILDS_PAGES = 5;
7101
+ /** How many times a mark runs again after losing its scope's mark to another. */
7102
+ const MARK_ATTEMPTS = 8;
5922
7103
  /** `native_builds.build_number`'s bound in core's schema. */
5923
7104
  const BUILD_NUMBER_MAX_LENGTH = 64;
5924
7105
  /** `native_builds.submitted_version`'s bound in core's schema. */
5925
7106
  const SUBMITTED_VERSION_MAX_LENGTH = 255;
7107
+ const checkedScopeKey = (scopeKey) => {
7108
+ 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.`);
7109
+ return scopeKey;
7110
+ };
7111
+ /**
7112
+ * How a registered artifact installs: an `.ipa` by its export method, and
7113
+ * `unknown` for one whose export no profile confirmed, which no lookup asks
7114
+ * for, so it is never reused as either.
7115
+ */
7116
+ const registeredDistribution = (kind, exportMethod) => kind !== "ipa" ? DISTRIBUTIONS[kind][0] : exportMethod === void 0 || exportMethod === null ? "unknown" : exportMethod === "app-store" ? "store" : "direct";
7117
+ /**
7118
+ * A sandbox build scope's key, which names no channel: the app ID, URL
7119
+ * scheme, artifact kind and distribution in its place, then the fingerprint,
7120
+ * or the app-version strategy and the exact app version. `v1:sandbox:` is no
7121
+ * Release Catalog strategy, so it never meets a normal build's key.
7122
+ */
7123
+ const sandboxScopeKey = (scope, sandbox) => {
7124
+ const { appId, urlScheme, artifactKind, distribution } = sandbox;
7125
+ 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;
7126
+ if (problem !== null) throw new NativeBuildInputError(`Invalid sandbox build scope: ${problem}.`);
7127
+ const target = scope.fingerprintHash === null ? `app-version:${encodeURIComponent(scope.appVersion)}` : `fingerprint:${scope.fingerprintHash}`;
7128
+ return checkedScopeKey(`v1:sandbox:${scope.platform}:${appId}:${urlScheme}:${artifactKind}:${distribution}:${target}`);
7129
+ };
5926
7130
  /**
5927
7131
  * A native build scope's key: the Release Catalog scope key of a
5928
7132
  * fingerprint, or of the app-version strategy followed by the exact app
5929
7133
  * version the build compiled in. One key serves both strategies, so one
5930
- * index finds the newest build of either.
7134
+ * index finds the newest build of either. A sandbox scope's key names no
7135
+ * channel, so pull requests find a sandbox build on any.
5931
7136
  */
5932
7137
  const nativeBuildScopeKey = (scope) => {
7138
+ const { sandbox } = scope;
7139
+ if (sandbox !== void 0 && sandbox !== null) {
7140
+ if (sandbox.distribution !== "direct" && sandbox.distribution !== "store") throw new NativeBuildInputError("Invalid sandbox build scope: its distribution must be direct or store.");
7141
+ return sandboxScopeKey(scope, sandbox);
7142
+ }
5933
7143
  let scopeKey;
5934
7144
  try {
5935
7145
  const channelKey = encodeChannelKey(scope.channel);
@@ -5946,32 +7156,126 @@ const nativeBuildScopeKey = (scope) => {
5946
7156
  } catch (error) {
5947
7157
  throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
5948
7158
  }
5949
- 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.`);
5950
- return scopeKey;
7159
+ return checkedScopeKey(scopeKey);
7160
+ };
7161
+ /** The channel row a registration names, or the refusal of its channel. */
7162
+ const channelIdOf = (channel) => {
7163
+ try {
7164
+ return `channel:${encodeChannelKey(channel)}`;
7165
+ } catch (error) {
7166
+ throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
7167
+ }
7168
+ };
7169
+ /**
7170
+ * A registration's scope key, from the registration's own facts: a sandbox
7171
+ * build's from what its artifact says, whatever `sandbox` it names.
7172
+ */
7173
+ const registrationScopeKey = (registration) => {
7174
+ channelIdOf(registration.channel);
7175
+ return registration.isSandbox === true ? sandboxScopeKey(registration, {
7176
+ appId: registration.sandboxAppId,
7177
+ urlScheme: registration.sandboxUrlScheme,
7178
+ artifactKind: registration.artifact.kind,
7179
+ distribution: registeredDistribution(registration.artifact.kind, registration.exportMethod)
7180
+ }) : nativeBuildScopeKey({
7181
+ ...registration,
7182
+ sandbox: null
7183
+ });
7184
+ };
7185
+ /**
7186
+ * Refuses a patch from a sandbox build's built-in bundle: no deploy patches
7187
+ * from one, so no store or test install of the app gets a patch made for a
7188
+ * sandbox build. One unique read of the base.
7189
+ */
7190
+ const refuseSandboxPatchBase = async (db, baseBundleId) => {
7191
+ 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.");
5951
7192
  };
5952
7193
  /** Whether `bundleId` is a native build's built-in bundle: one unique read. */
5953
7194
  const isBuiltInBundle = async (db, bundleId) => await db.findOne("native_builds", { min_bundle_id: bundleId }) !== null;
5954
- const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, artifact }) => {
7195
+ const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, sandboxAppId, exportMethod, nativeAppVersion, artifact }) => {
5955
7196
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
5956
7197
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
5957
7198
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
5958
7199
  if (channel.trim().length === 0) return "channel is required";
7200
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
7201
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
7202
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
7203
+ 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`;
7204
+ }
7205
+ if (sandboxAppId !== void 0 && sandboxAppId !== null) {
7206
+ if (isSandbox !== true) return "sandboxAppId is a sandbox build's, and this isn't one";
7207
+ if (typeof sandboxAppId !== "string" || !APP_ID.test(sandboxAppId)) return "sandboxAppId must be the artifact's bundle identifier or application ID, up to 255 characters";
7208
+ }
7209
+ if (isSandbox === true) {
7210
+ if (sandboxUrlScheme === void 0 || sandboxUrlScheme === null) return "a sandbox build needs the sandboxUrlScheme its artifact registers";
7211
+ 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";
7212
+ }
5959
7213
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
5960
7214
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
5961
7215
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
5962
7216
  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`;
7217
+ if (nativeAppVersion !== void 0 && nativeAppVersion !== null && (typeof nativeAppVersion !== "string" || nativeAppVersion.trim().length === 0)) return "nativeAppVersion must be the artifact's app version, or null";
5963
7218
  const kinds = ARTIFACT_KINDS[platform];
5964
7219
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
7220
+ if (exportMethod !== void 0 && exportMethod !== null) {
7221
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
7222
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
7223
+ }
5965
7224
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
5966
7225
  return null;
5967
7226
  };
7227
+ /** The other install target of an iOS sandbox build's native code. */
7228
+ const SIBLING_KINDS = {
7229
+ app: "ipa",
7230
+ ipa: "app"
7231
+ };
7232
+ /**
7233
+ * Whether a build is one a person installs from its file: a Simulator `.app`,
7234
+ * or an `.ipa` exported for direct install, that no store took and that isn't
7235
+ * the store build. One rule for a sibling and the build it is found from, so
7236
+ * a build that shows its sibling is shown by it.
7237
+ */
7238
+ 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");
7239
+ /**
7240
+ * The scope key of the other install target of a sandbox build, from its own
7241
+ * key's app ID and URL scheme, which hold no colon, and its row's fingerprint
7242
+ * or app version, through `sandboxScopeKey`; null for a key it didn't make.
7243
+ */
7244
+ const siblingSandboxScopeKey = (build, artifactKind) => {
7245
+ const [version, sandbox, platform, appId, urlScheme] = build.scope_key.split(":");
7246
+ if (version !== "v1" || sandbox !== "sandbox" || platform !== build.platform || appId === void 0 || urlScheme === void 0) return null;
7247
+ const target = build.fingerprint_hash === null ? {
7248
+ platform: build.platform,
7249
+ fingerprintHash: null,
7250
+ appVersion: build.app_version ?? ""
7251
+ } : {
7252
+ platform: build.platform,
7253
+ fingerprintHash: build.fingerprint_hash,
7254
+ appVersion: null
7255
+ };
7256
+ try {
7257
+ return sandboxScopeKey(target, {
7258
+ appId,
7259
+ urlScheme,
7260
+ artifactKind: build.artifact_kind,
7261
+ distribution: registeredDistribution(build.artifact_kind, build.export_method)
7262
+ }) === build.scope_key ? sandboxScopeKey(target, {
7263
+ appId,
7264
+ urlScheme,
7265
+ artifactKind,
7266
+ distribution: "direct"
7267
+ }) : null;
7268
+ } catch {
7269
+ return null;
7270
+ }
7271
+ };
5968
7272
  /** The native build registry: core's `native_builds` and the built-in bundle rows. */
5969
7273
  const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
5970
7274
  async registerNativeBuild(registration) {
5971
7275
  const problem = problemOf(registration);
5972
7276
  if (problem !== null) throw new NativeBuildInputError(`Invalid native build: ${problem}.`);
5973
- const scopeKey = nativeBuildScopeKey(registration);
5974
- const channelId = `channel:${encodeChannelKey(registration.channel)}`;
7277
+ const scopeKey = registrationScopeKey(registration);
7278
+ const channelId = channelIdOf(registration.channel);
5975
7279
  const { embeddedBundle } = registration;
5976
7280
  const row = {
5977
7281
  id: registration.id,
@@ -5990,7 +7294,12 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
5990
7294
  build_number: registration.buildNumber ?? null,
5991
7295
  submitted_to: null,
5992
7296
  submitted_at_ms: null,
5993
- submitted_version: null
7297
+ submitted_version: null,
7298
+ is_store_build: false,
7299
+ is_sandbox: registration.isSandbox === true,
7300
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
7301
+ export_method: registration.exportMethod ?? null,
7302
+ native_app_version: registration.nativeAppVersion ?? null
5994
7303
  };
5995
7304
  for (let attempt = 1;; attempt += 1) {
5996
7305
  await insertChannel(db, {
@@ -6024,25 +7333,82 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6024
7333
  const row = await db.findOne("native_builds", { id });
6025
7334
  return row === null ? null : pick(row);
6026
7335
  },
7336
+ async findNativeBuildByBuiltInBundle(bundleId) {
7337
+ const row = await db.findOne("native_builds", { min_bundle_id: bundleId });
7338
+ return row === null ? null : pick(row);
7339
+ },
6027
7340
  async findNativeBuild(scope, options) {
6028
7341
  const scopeKey = nativeBuildScopeKey(scope);
6029
7342
  const buildKey = options?.buildKey;
6030
7343
  if (buildKey !== void 0 && !BUILD_KEY.test(buildKey)) throw new NativeBuildInputError("Invalid native build key: it must be nbk1: and a SHA-256.");
6031
- const { rows } = buildKey === void 0 ? await db.findMany("native_builds", {
7344
+ const artifactKind = options?.artifactKind;
7345
+ 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 ")}.`);
7346
+ const ofKind = (row) => artifactKind === void 0 || row.artifact_kind === artifactKind;
7347
+ if (options?.storeBuild) {
7348
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
7349
+ return marked === null || !ofKind(marked) ? null : pick(marked);
7350
+ }
7351
+ const read = (limit, before) => {
7352
+ const page = {
7353
+ order: "desc",
7354
+ limit,
7355
+ ...before === void 0 ? {} : { range: { lt: before } }
7356
+ };
7357
+ return buildKey !== void 0 ? db.findMany("native_builds", {
7358
+ index: "byBuildKey",
7359
+ where: {
7360
+ scope_key: scopeKey,
7361
+ build_key: buildKey
7362
+ },
7363
+ ...page
7364
+ }) : artifactKind !== void 0 ? db.findMany("native_builds", {
7365
+ index: "byScopeKind",
7366
+ where: {
7367
+ scope_key: scopeKey,
7368
+ artifact_kind: artifactKind
7369
+ },
7370
+ ...page
7371
+ }) : db.findMany("native_builds", {
7372
+ index: "byScope",
7373
+ where: { scope_key: scopeKey },
7374
+ ...page
7375
+ });
7376
+ };
7377
+ const bundleId = options?.builtInOlderThan;
7378
+ if (bundleId !== void 0 && scope.sandbox !== void 0 && scope.sandbox !== null) return null;
7379
+ const { rows } = await read(1);
7380
+ const newest = (rows[0] === void 0 ? void 0 : pick(rows[0])) ?? (artifactKind !== void 0 && buildKey === void 0 ? await db.findMany("native_builds", {
6032
7381
  index: "byScope",
6033
7382
  where: { scope_key: scopeKey },
6034
7383
  order: "desc",
6035
7384
  limit: 1
6036
- }) : await db.findMany("native_builds", {
6037
- index: "byBuildKey",
6038
- where: {
6039
- scope_key: scopeKey,
6040
- build_key: buildKey
6041
- },
7385
+ }).then(({ rows: [row] }) => row?.artifact_kind === artifactKind ? pick(row) : void 0) : void 0);
7386
+ if (newest === void 0 || !ofKind(newest)) return null;
7387
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return newest;
7388
+ let before = newest.id;
7389
+ for (let page = 0; page < OLDER_BUILDS_PAGES; page += 1) {
7390
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
7391
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
7392
+ if (usable !== void 0) return ofKind(usable) ? pick(usable) : null;
7393
+ const last = older.at(-1);
7394
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
7395
+ before = last.id;
7396
+ }
7397
+ return null;
7398
+ },
7399
+ async findNativeBuildSibling(build) {
7400
+ const artifactKind = SIBLING_KINDS[build.artifact_kind];
7401
+ if (build.platform !== "ios" || !build.is_sandbox || artifactKind === void 0 || !isInstallTarget(build)) return null;
7402
+ const scopeKey = siblingSandboxScopeKey(build, artifactKind);
7403
+ if (scopeKey === null) return null;
7404
+ const { rows } = await db.findMany("native_builds", {
7405
+ index: "byScope",
7406
+ where: { scope_key: scopeKey },
6042
7407
  order: "desc",
6043
7408
  limit: 1
6044
7409
  });
6045
- return rows[0] === void 0 ? null : pick(rows[0]);
7410
+ const sibling = rows[0] === void 0 ? null : pick(rows[0]);
7411
+ return sibling !== null && isInstallTarget(sibling) ? sibling : null;
6046
7412
  },
6047
7413
  async recordNativeBuildSubmission(id, { destination, version }) {
6048
7414
  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.`);
@@ -6050,7 +7416,8 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6050
7416
  const row = await tx.findOne("native_builds", { id });
6051
7417
  if (row === null) return null;
6052
7418
  const build = pick(row);
6053
- 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}.`);
7419
+ 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}.`);
7420
+ if (build.is_sandbox && destination !== "testflight" && destination !== "play-internal") throw new NativeBuildInputError("A sandbox build can submit only to TestFlight or Play internal testing.");
6054
7421
  const set = {
6055
7422
  submitted_to: destination,
6056
7423
  submitted_at_ms: now(),
@@ -6063,6 +7430,46 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6063
7430
  };
6064
7431
  });
6065
7432
  },
7433
+ async markNativeBuild(id, { storeBuild }) {
7434
+ for (let attempt = 1;; attempt += 1) try {
7435
+ return await db.transaction(async (tx) => {
7436
+ const row = await tx.findOne("native_builds", { id });
7437
+ if (row === null) return null;
7438
+ const build = pick(row);
7439
+ if (!storeBuild) {
7440
+ if (build.is_store_build) tx.update("native_builds", row, { is_store_build: false });
7441
+ return {
7442
+ nativeBuild: {
7443
+ ...build,
7444
+ is_store_build: false
7445
+ },
7446
+ previous: null
7447
+ };
7448
+ }
7449
+ if (build.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
7450
+ if (build.is_store_build) return {
7451
+ nativeBuild: build,
7452
+ previous: null
7453
+ };
7454
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build.scope_key });
7455
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
7456
+ tx.update("native_builds", row, { is_store_build: true });
7457
+ return {
7458
+ nativeBuild: {
7459
+ ...build,
7460
+ is_store_build: true
7461
+ },
7462
+ previous: holder === null ? null : {
7463
+ ...pick(holder),
7464
+ is_store_build: false
7465
+ }
7466
+ };
7467
+ });
7468
+ } catch (error) {
7469
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
7470
+ throw error;
7471
+ }
7472
+ },
6066
7473
  async deleteNativeBuild(id) {
6067
7474
  return db.transaction(async (tx) => {
6068
7475
  const row = await tx.findOne("native_builds", { id });
@@ -6118,44 +7525,43 @@ const checkScope = (scope) => {
6118
7525
  });
6119
7526
  if (scope.strategy === "FINGERPRINT" !== (scope.fingerprintHash !== null) || scope.scopeKey !== expected) fail$1("INVALID_SCOPE", "Release catalog scope metadata is inconsistent");
6120
7527
  };
6121
- /** A scope's enabled releases, all of them, under the catalog's guard. */
6122
- const enabledReleases = async (tx, scopeKey) => {
7528
+ /** Every row of a paged read, as release rows. */
7529
+ const drainReleases = async (page) => {
6123
7530
  const rows = [];
6124
7531
  let cursor;
6125
7532
  do {
6126
- const page = await tx.findMany("releases", {
6127
- index: "byScopeEnabled",
6128
- where: {
6129
- scope_key: scopeKey,
6130
- enabled: true
6131
- },
6132
- limit: PAGE$1,
6133
- ...cursor === void 0 ? {} : { cursor }
6134
- });
6135
- rows.push(...page.rows.map(toReleaseRow));
6136
- cursor = page.next;
7533
+ const found = await page(cursor);
7534
+ rows.push(...found.rows.map((row) => toReleaseRow(row)));
7535
+ cursor = found.next;
6137
7536
  } while (cursor !== void 0);
6138
7537
  return rows;
6139
7538
  };
6140
- /** The scope's newest release id: `byScope` descending, limit 1. */
6141
- const latestReleaseId = async (tx, scopeKey) => {
7539
+ const enabledIn = (scopeKey, cursor) => ({
7540
+ index: "byScopeEnabled",
7541
+ where: {
7542
+ scope_key: scopeKey,
7543
+ enabled: true
7544
+ },
7545
+ limit: PAGE$1,
7546
+ ...cursor === void 0 ? {} : { cursor }
7547
+ });
7548
+ /** A scope's enabled releases, all of them, under the catalog's guard. */
7549
+ const enabledReleases = (tx, scopeKey) => drainReleases((cursor) => tx.findMany("releases", enabledIn(scopeKey, cursor)));
7550
+ /** The scope's newest release: `byScope` descending, limit 1. */
7551
+ const latestRelease = async (tx, scopeKey) => {
6142
7552
  const { rows } = await tx.findMany("releases", {
6143
7553
  index: "byScope",
6144
7554
  where: { scope_key: scopeKey },
6145
7555
  order: "desc",
6146
7556
  limit: 1
6147
7557
  });
6148
- return rows[0]?.id ?? null;
7558
+ return rows[0] === void 0 ? null : toReleaseRow(rows[0]);
6149
7559
  };
6150
- /** Compiles `enabled` and writes it as the scope's next catalog generation. */
6151
- const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
6152
- const compilation = await compileReleaseCatalog({
6153
- strategy: scope.strategy,
6154
- releases: enabled.map(releaseRowToRelease)
6155
- });
6156
- const generation = (stored.generation ?? 0) + 1;
7560
+ /** The scope's next catalog generation, compiled as `compilation`. */
7561
+ const nextCatalog = (scope, stored, compilation, updatedAtMs) => {
7562
+ const generation = (stored.catalog?.generation ?? 0) + 1;
6157
7563
  if (!Number.isSafeInteger(generation)) fail$1("CATALOG_GENERATION_EXHAUSTED", `Catalog "${scope.scopeKey}" exhausted its generation counter`);
6158
- const catalog = {
7564
+ return {
6159
7565
  scope_key: scope.scopeKey,
6160
7566
  catalog_id: stored.catalog?.catalog_id ?? createUUIDv7(),
6161
7567
  strategy: scope.strategy,
@@ -6170,6 +7576,26 @@ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
6170
7576
  is_tombstone: compilation.payload.releaseDescriptors.length === 0,
6171
7577
  updated_at_ms: updatedAtMs
6172
7578
  };
7579
+ };
7580
+ /**
7581
+ * Compiles a scope's enabled releases. A catalog over the size limit is
7582
+ * refused naming its channel and platform, and what frees room in it.
7583
+ */
7584
+ const compileScope = async (scope, enabled) => {
7585
+ try {
7586
+ return await compileReleaseCatalog({
7587
+ strategy: scope.strategy,
7588
+ releases: enabled.map(releaseRowToRelease)
7589
+ });
7590
+ } catch (error) {
7591
+ if (!(error instanceof ReleaseCatalogCompilationError) || error.code !== "CATALOG_OVERSIZE") throw error;
7592
+ 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.`);
7593
+ }
7594
+ };
7595
+ /** Compiles `enabled` and writes it as the scope's next catalog generation. */
7596
+ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
7597
+ const compilation = await compileScope(scope, enabled);
7598
+ const catalog = nextCatalog(scope, stored, compilation, updatedAtMs);
6173
7599
  const { scope_key: _scopeKey, ...set } = catalog;
6174
7600
  if (stored.row === null) tx.create("release_catalogs", catalog);
6175
7601
  else tx.update("release_catalogs", stored.row, set);
@@ -6191,11 +7617,16 @@ const readCatalog = async (tx, scopeKey) => {
6191
7617
  const assertHistory = (stored, hasReleases) => {
6192
7618
  if (stored.catalog === null && hasReleases) fail$1("CATALOG_IDENTITY_MISSING", "Catalog history is missing. Restore its catalog row from backup before rebuilding or deploying.");
6193
7619
  };
6194
- /** One release change and its scope's next catalog, inside `tx`. */
6195
- const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
7620
+ /**
7621
+ * One release change and its scope's next catalog, inside `tx`. An insert
7622
+ * takes its channel and platform's next label from `labels`, after labeling
7623
+ * the releases a server of an earlier release wrote in the scope since its
7624
+ * last labeled one.
7625
+ */
7626
+ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }, labels) => {
6196
7627
  checkScope(scope);
6197
7628
  const stored = await readCatalog(tx, scope.scopeKey);
6198
- const enabled = await enabledReleases(tx, scope.scopeKey);
7629
+ let enabled = await enabledReleases(tx, scope.scopeKey);
6199
7630
  if (bundle !== void 0) {
6200
7631
  insertBundle(tx, bundle.row);
6201
7632
  for (const patch of bundle.patches) tx.create("bundle_patches", patch);
@@ -6203,14 +7634,22 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
6203
7634
  let before = null;
6204
7635
  let release;
6205
7636
  if (change.operation === "insert") {
6206
- const latest = await latestReleaseId(tx, scope.scopeKey);
7637
+ if (labels === void 0) throw new Error("A release insert takes its label from an allocator.");
7638
+ const newest = await latestRelease(tx, scope.scopeKey);
7639
+ const latest = newest?.id ?? null;
6207
7640
  assertHistory(stored, latest !== null);
6208
7641
  const floor = [latest, bundle && isUUIDv7(bundle.row.id) ? bundle.row.id : null].filter((id) => id !== null).sort().at(-1);
6209
7642
  const id = change.row.id ?? createUUIDv7After(floor ?? null);
6210
7643
  if (latest !== null && id <= latest) fail$1("NON_MONOTONIC_RELEASE_ID", `Release "${id}" must sort after "${latest}"`);
7644
+ const given = await catchUpLabels(tx, labels, newest);
7645
+ if (given.size > 0) enabled = enabled.map((row) => given.has(row.id) ? {
7646
+ ...row,
7647
+ label: given.get(row.id)
7648
+ } : row);
6211
7649
  release = {
6212
7650
  ...change.row,
6213
- id
7651
+ id,
7652
+ label: await labels.next(scope.channelId, scope.platform)
6214
7653
  };
6215
7654
  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");
6216
7655
  tx.create("releases", release);
@@ -6223,8 +7662,9 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
6223
7662
  await tx.delete("releases", row);
6224
7663
  release = null;
6225
7664
  } else {
7665
+ const { label: _label, ...update } = change.update;
6226
7666
  const set = {
6227
- ...change.update,
7667
+ ...update,
6228
7668
  revision: before.revision + 1
6229
7669
  };
6230
7670
  tx.update("releases", row, set);
@@ -6252,24 +7692,70 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
6252
7692
  */
6253
7693
  const changeReleases = (db, inputs) => {
6254
7694
  if (new Set(inputs.map(({ scope }) => scope.scopeKey)).size !== inputs.length) fail$1("INVALID_SCOPE", "A batch cannot change one catalog scope twice");
6255
- return db.transaction(async (tx) => {
7695
+ return writeWithLabels(db, async (tx, labels) => {
6256
7696
  const results = [];
6257
- for (const input of inputs) results.push(await changeRelease(tx, input));
7697
+ for (const input of inputs) results.push(await changeRelease(tx, input, labels));
6258
7698
  return results;
6259
7699
  });
6260
7700
  };
7701
+ /** Whether `current` is what the scope's enabled releases compile to. */
7702
+ 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;
7703
+ /** A compiled payload with its descriptors' labels left out. */
7704
+ const withoutLabels = (payload) => {
7705
+ const parsed = JSON.parse(payload);
7706
+ return JSON.stringify({
7707
+ ...parsed,
7708
+ releaseDescriptors: (parsed.releaseDescriptors ?? []).map(({ label: _label, ...descriptor }) => descriptor)
7709
+ });
7710
+ };
7711
+ /**
7712
+ * Whether `projected` differs from `current` only by release labels, as a
7713
+ * catalog compiled before its releases had them does.
7714
+ */
7715
+ 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);
7716
+ /** The scope a catalog row names. */
7717
+ const catalogRowScope = (row) => ({
7718
+ channelId: row.channel_id,
7719
+ channelName: decodeChannelKey(row.channel_key),
7720
+ fingerprintHash: row.fingerprint_hash,
7721
+ platform: row.platform,
7722
+ scopeKey: row.scope_key,
7723
+ strategy: row.strategy
7724
+ });
7725
+ /**
7726
+ * What a rebuild of the scope's catalog would write, without writing: one
7727
+ * read of the catalog row and one of the scope's enabled releases. It needs
7728
+ * no transaction, whose guards would read the catalog again for each read
7729
+ * beneath it, nor the scope's newest release, which matters only to a scope
7730
+ * without a catalog row; that one is not found.
7731
+ */
7732
+ const preflightRebuild = async (db, scopeKey, updatedAtMs) => {
7733
+ const row = await db.findOne("release_catalogs", { scope_key: scopeKey });
7734
+ if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
7735
+ const current = toCatalogRow(row);
7736
+ const scope = catalogRowScope(current);
7737
+ checkScope(scope);
7738
+ const enabled = await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor)));
7739
+ const compilation = await compileScope(scope, enabled);
7740
+ const changed = !isCurrent(scope, current, compilation);
7741
+ const projectedCatalog = changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current;
7742
+ return {
7743
+ changed,
7744
+ labelsOnly: changed && differsInLabelsOnly(current, projectedCatalog),
7745
+ currentCatalog: current,
7746
+ diagnostics: compilation.diagnostics,
7747
+ projectedCatalog
7748
+ };
7749
+ };
6261
7750
  /** Recompiles a scope's catalog from its enabled releases inside `tx`; an unchanged catalog is not rewritten. */
6262
7751
  const rebuildScope = async (tx, scope, updatedAtMs) => {
6263
7752
  checkScope(scope);
6264
7753
  const stored = await readCatalog(tx, scope.scopeKey);
6265
- assertHistory(stored, await latestReleaseId(tx, scope.scopeKey) !== null);
7754
+ assertHistory(stored, await latestRelease(tx, scope.scopeKey) !== null);
6266
7755
  const enabled = await enabledReleases(tx, scope.scopeKey);
6267
- const compilation = await compileReleaseCatalog({
6268
- strategy: scope.strategy,
6269
- releases: enabled.map(releaseRowToRelease)
6270
- });
7756
+ const compilation = await compileScope(scope, enabled);
6271
7757
  const current = stored.catalog;
6272
- 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 {
7758
+ if (current !== null && isCurrent(scope, current, compilation)) return {
6273
7759
  catalog: current,
6274
7760
  current,
6275
7761
  changed: false,
@@ -6285,6 +7771,7 @@ const rebuildScope = async (tx, scope, updatedAtMs) => {
6285
7771
  };
6286
7772
  //#endregion
6287
7773
  //#region ../../packages/server/dist/core/operations.mjs
7774
+ const CATALOG_PAGE = 100;
6288
7775
  /** Carries a preflight's result out of the transaction it stops, so nothing is written. */
6289
7776
  var Preflight = class extends Error {
6290
7777
  result;
@@ -6373,14 +7860,7 @@ const mutationResult = ({ catalog, release }) => ({
6373
7860
  const catalogScope = async (tx, scopeKey) => {
6374
7861
  const row = await tx.findOne("release_catalogs", { scope_key: scopeKey });
6375
7862
  if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
6376
- return {
6377
- channelId: row.channel_id,
6378
- channelName: decodeChannelKey(row.channel_key),
6379
- fingerprintHash: row.fingerprint_hash,
6380
- platform: row.platform,
6381
- scopeKey: row.scope_key,
6382
- strategy: row.strategy
6383
- };
7863
+ return catalogRowScope(toCatalogRow(row));
6384
7864
  };
6385
7865
  /**
6386
7866
  * Core's typed writes: each runs in one engine transaction rooted at the
@@ -6409,7 +7889,11 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
6409
7889
  for (const { release } of deployments) if (!channels.has(release.channel)) channels.set(release.channel, await ensureChannel(release.channel));
6410
7890
  const platforms = /* @__PURE__ */ new Map();
6411
7891
  for (const deployment of deployments) {
6412
- if (!("bundleId" in deployment) || platforms.has(deployment.bundleId)) continue;
7892
+ if (!("bundleId" in deployment)) {
7893
+ for (const { baseBundleId } of deployment.bundle.patches ?? []) await refuseSandboxPatchBase(db, baseBundleId);
7894
+ continue;
7895
+ }
7896
+ if (platforms.has(deployment.bundleId)) continue;
6413
7897
  const row = await db.findOne("bundles", { id: deployment.bundleId });
6414
7898
  if (row === null) throw new DatabaseBundleNotFoundError(deployment.bundleId);
6415
7899
  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.`);
@@ -6519,7 +8003,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
6519
8003
  if (targetChannel.length === 0) throw new ReleaseManagementError("TARGET_RELEASE_INVALID", "Promotion requires a target channel.");
6520
8004
  const channel = await ensureChannel(targetChannel);
6521
8005
  const updatedAtMs = now();
6522
- return db.transaction(async (tx) => {
8006
+ return writeWithLabels(db, async (tx, labels) => {
6523
8007
  const { release: source, scope: sourceScope } = await loadTarget(tx, input);
6524
8008
  checkSource(source);
6525
8009
  const targetScope = scopeOf$1(channel, source.platform, source.fingerprint_hash);
@@ -6547,12 +8031,13 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
6547
8031
  },
6548
8032
  updatedAtMs
6549
8033
  }) : null;
8034
+ const { label: _label, ...copied } = source;
6550
8035
  const target = await changeRelease(tx, {
6551
8036
  scope: targetScope,
6552
8037
  change: {
6553
8038
  operation: "insert",
6554
8039
  row: {
6555
- ...source,
8040
+ ...copied,
6556
8041
  id: createUUIDv7After(floor ?? null, updatedAtMs),
6557
8042
  revision: 1,
6558
8043
  scope_key: targetScope.scopeKey,
@@ -6567,7 +8052,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
6567
8052
  }
6568
8053
  },
6569
8054
  updatedAtMs
6570
- });
8055
+ }, labels);
6571
8056
  return {
6572
8057
  source: moved === null ? null : mutationResult(moved),
6573
8058
  target: mutationResult(target)
@@ -6584,18 +8069,39 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
6584
8069
  };
6585
8070
  });
6586
8071
  },
6587
- preflightReleaseCatalogRebuild: (scopeKey) => {
6588
- const updatedAtMs = now();
6589
- return dryRun(db, async (tx) => {
6590
- const rebuilt = await rebuildScope(tx, await catalogScope(tx, scopeKey), updatedAtMs);
6591
- return {
6592
- changed: rebuilt.changed,
6593
- currentCatalog: rebuilt.current,
6594
- diagnostics: rebuilt.diagnostics,
6595
- projectedCatalog: rebuilt.catalog
6596
- };
6597
- });
6598
- },
8072
+ preflightReleaseCatalogRebuild: (scopeKey) => preflightRebuild(db, scopeKey, now()),
8073
+ fillReleaseLabels: async ({ dryRun = false, catalogs = true } = {}) => {
8074
+ let releases = 0;
8075
+ const pairs = await pendingLabelPairs(db);
8076
+ if (dryRun && pairs[0] !== void 0) await probeLabelSchema(db, pairs[0]);
8077
+ for (const pair of pairs) releases += await fillLabels(db, pair, { dryRun });
8078
+ let rebuilt = 0;
8079
+ if (catalogs) {
8080
+ let cursor;
8081
+ do {
8082
+ const page = await db.findMany("release_catalogs", {
8083
+ index: "all",
8084
+ where: {},
8085
+ limit: CATALOG_PAGE,
8086
+ ...cursor === void 0 ? {} : { cursor }
8087
+ });
8088
+ for (const row of page.rows) {
8089
+ if (row.is_tombstone) continue;
8090
+ const preflight = await preflightRebuild(db, row.scope_key, now()).catch(() => null);
8091
+ if (preflight === null || !preflight.labelsOnly) continue;
8092
+ rebuilt += 1;
8093
+ if (dryRun) continue;
8094
+ const updatedAtMs = now();
8095
+ await db.transaction((tx) => rebuildScope(tx, catalogRowScope(toCatalogRow(row)), updatedAtMs));
8096
+ }
8097
+ cursor = page.next;
8098
+ } while (cursor !== void 0);
8099
+ }
8100
+ return {
8101
+ releases,
8102
+ catalogs: rebuilt
8103
+ };
8104
+ },
6599
8105
  ensureChannel,
6600
8106
  deleteChannel: (id) => deleteChannel(db, id),
6601
8107
  updateBundle: (id, update) => db.transaction(async (tx) => {
@@ -6613,7 +8119,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
6613
8119
  if (patches !== void 0) await replaceBundlePatches(tx, current, bundleToPatchRows({
6614
8120
  ...next,
6615
8121
  patches
6616
- }));
8122
+ }), (row) => refuseSandboxPatchBase(tx, row.base_bundle_id));
6617
8123
  }),
6618
8124
  deleteBundles: async (ids) => {
6619
8125
  try {
@@ -6675,6 +8181,7 @@ const createCoreApi = (db, storage, options = {}) => {
6675
8181
  ...reads,
6676
8182
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
6677
8183
  ...createNativeBuildApi(db, options),
8184
+ ...createIosDeviceApi(db, options),
6678
8185
  /** One read, which checks the schema settings first. */
6679
8186
  ready: async () => {
6680
8187
  await reads.listReleaseCatalogs({ limit: 1 });
@@ -6867,6 +8374,10 @@ const answer = async (operation) => {
6867
8374
  error: error.message
6868
8375
  }, status);
6869
8376
  }
8377
+ if (error instanceof ReleaseCatalogCompilationError && error.code === "CATALOG_OVERSIZE") return json$2({
8378
+ code: error.code,
8379
+ error: error.message
8380
+ }, 400);
6870
8381
  if (error instanceof DatabaseBundleNotFoundError) return json$2({
6871
8382
  code: "BUNDLE_NOT_FOUND",
6872
8383
  error: error.message
@@ -6886,18 +8397,22 @@ const LIMITS = {
6886
8397
  defaultValue: 50,
6887
8398
  maxValue: 500
6888
8399
  };
8400
+ /** The most IDs one request names: a lookup's, or a write's. */
8401
+ const MAX_IDS = 100;
6889
8402
  /** `order`, `cursor`, and `limit`: one keyset page. */
6890
- const keyset = (url, maxValue = LIMITS.maxValue) => {
6891
- const order = url.searchParams.get("order") ?? "desc";
8403
+ const keyset = (url, maxValue = LIMITS.maxValue, defaultOrder = "desc") => {
8404
+ const order = url.searchParams.get("order") ?? defaultOrder;
6892
8405
  if (order !== "asc" && order !== "desc") throw new HandlerBadRequestError("order must be 'asc' or 'desc'.");
6893
8406
  const limitParam = url.searchParams.get("limit");
6894
8407
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
6895
8408
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
6896
8409
  const cursor = url.searchParams.get("cursor");
8410
+ const through = url.searchParams.get("through");
6897
8411
  return {
6898
8412
  order,
6899
8413
  limit,
6900
- ...cursor === null ? {} : { after: cursor }
8414
+ ...cursor === null ? {} : { after: cursor },
8415
+ ...through === null ? {} : { through }
6901
8416
  };
6902
8417
  };
6903
8418
  /** A page and the cursor of the next one, when the page is full. */
@@ -6995,7 +8510,8 @@ const nativeBuildScopeOf = (url) => {
6995
8510
  const fingerprintHash = params.get("fingerprintHash");
6996
8511
  const appVersion = params.get("appVersion");
6997
8512
  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.");
6998
- return fingerprintHash !== null ? {
8513
+ const sandbox = sandboxScopeOf(params);
8514
+ const scope = fingerprintHash !== null ? {
6999
8515
  platform,
7000
8516
  channel,
7001
8517
  fingerprintHash,
@@ -7006,17 +8522,49 @@ const nativeBuildScopeOf = (url) => {
7006
8522
  fingerprintHash: null,
7007
8523
  appVersion
7008
8524
  };
8525
+ return sandbox === null ? scope : {
8526
+ ...scope,
8527
+ sandbox
8528
+ };
8529
+ };
8530
+ /** The query parameters a sandbox lookup names, all four or none. */
8531
+ const SANDBOX_SCOPE_PARAMS = [
8532
+ "sandboxAppId",
8533
+ "sandboxUrlScheme",
8534
+ "artifactKind",
8535
+ "distribution"
8536
+ ];
8537
+ /**
8538
+ * A lookup's sandbox scope: null without one, and a bad request for one
8539
+ * named in part. Core checks each value.
8540
+ */
8541
+ const sandboxScopeOf = (params) => {
8542
+ const [appId, urlScheme, artifactKind, distribution] = SANDBOX_SCOPE_PARAMS.map((name) => params.get(name));
8543
+ const named = [
8544
+ appId,
8545
+ urlScheme,
8546
+ artifactKind,
8547
+ distribution
8548
+ ].filter((value) => value !== null).length;
8549
+ if (named === 0) return null;
8550
+ if (named !== SANDBOX_SCOPE_PARAMS.length) throw new HandlerBadRequestError(`A sandbox build lookup needs ${SANDBOX_SCOPE_PARAMS.join(", ")}.`);
8551
+ return {
8552
+ appId,
8553
+ urlScheme,
8554
+ artifactKind,
8555
+ distribution
8556
+ };
7009
8557
  };
7010
8558
  /** A native build or scope core refuses: a bad request. */
7011
8559
  const refusingInvalid = async (operation) => {
7012
8560
  try {
7013
8561
  return await operation();
7014
8562
  } catch (error) {
7015
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
8563
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
7016
8564
  throw error;
7017
8565
  }
7018
8566
  };
7019
- 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));
8567
+ 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));
7020
8568
  const scopeKeyOf = (params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "";
7021
8569
  /** Every admin route's handler, by the name `ADMIN_ROUTES` mounts it under. */
7022
8570
  const createAdminRouteHandlers = () => ({
@@ -7049,12 +8597,40 @@ const createAdminRouteHandlers = () => ({
7049
8597
  const rows = await core.listReleaseCatalogs(input);
7050
8598
  return page(rows, input, (row) => row.scope_key);
7051
8599
  }),
7052
- /** With `name`, the one channel of that name: 1 read. */
8600
+ /** Up to 100 scope keys that have releases, after `cursor`: one seek each. */
8601
+ listReleaseScopeKeys: onCore(async (core, request) => {
8602
+ const input = keyset(new URL(request.url), 100, "asc");
8603
+ if (input.order !== "asc" || input.through !== void 0) throw new HandlerBadRequestError("Release scopes are listed ascending, by limit and cursor only.");
8604
+ const rows = await core.listReleaseScopeKeys({
8605
+ limit: input.limit,
8606
+ ...input.after === void 0 ? {} : { after: input.after }
8607
+ });
8608
+ return page(rows, input, (scopeKey) => scopeKey);
8609
+ }),
8610
+ /**
8611
+ * With `name`, the one channel of that name: 1 read. With `ids`, the
8612
+ * channels of up to 100 IDs: 1 batch read. With `limit` or `cursor`, one
8613
+ * page by name. With none, every channel, as servers before pages answered.
8614
+ */
7053
8615
  getChannels: onCore(async (core, request) => {
7054
- const name = new URL(request.url).searchParams.get("name");
7055
- if (name === null) return json$2({ data: await core.listChannels() });
7056
- const channel = await core.findChannelByName(name);
7057
- return channel === null ? notFound() : json$2({ data: channel });
8616
+ const url = new URL(request.url);
8617
+ const name = url.searchParams.get("name");
8618
+ if (name !== null) {
8619
+ const channel = await core.findChannelByName(name);
8620
+ return channel === null ? notFound() : json$2({ data: channel });
8621
+ }
8622
+ const ids = url.searchParams.get("ids");
8623
+ if (ids !== null) {
8624
+ const list = ids.split(",").filter((id) => id.length > 0);
8625
+ if (list.length === 0 || list.length > MAX_IDS) throw new HandlerBadRequestError(`Channels by ID take ids=<channel id>,... with 1 to ${MAX_IDS} ids.`);
8626
+ return json$2({ data: await core.getChannels(list) });
8627
+ }
8628
+ if (url.searchParams.has("limit") || url.searchParams.has("cursor")) {
8629
+ const input = keyset(url, LIMITS.maxValue, "asc");
8630
+ const rows = await core.listChannels(input);
8631
+ return page(rows, input, (row) => row.name);
8632
+ }
8633
+ return json$2({ data: await core.listChannels() });
7058
8634
  }),
7059
8635
  /** The channel named in the body, created when missing. */
7060
8636
  createChannel: onCore(async (core, request) => {
@@ -7096,15 +8672,40 @@ const createAdminRouteHandlers = () => ({
7096
8672
  return row === null ? notFound() : json$2({ data: row });
7097
8673
  }),
7098
8674
  rebuildReleaseCatalog: onCore(async (core, _request, params) => json$2({ data: await core.rebuildReleaseCatalog(scopeKeyOf(params)) })),
8675
+ /**
8676
+ * The release a label names, or `null`: never 404, which tells a client
8677
+ * the server has no such route.
8678
+ */
8679
+ getReleaseByLabel: onCore(async (core, request) => {
8680
+ const url = new URL(request.url);
8681
+ const channel = url.searchParams.get("channel");
8682
+ const platform = platformOf(url);
8683
+ const label = Number(url.searchParams.get("label"));
8684
+ 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.");
8685
+ return json$2({ data: await core.getReleaseByLabel({
8686
+ channel,
8687
+ platform,
8688
+ label
8689
+ }) });
8690
+ }),
8691
+ fillReleaseLabels: onCore(async (core, request) => {
8692
+ const body = await request.json().catch(() => ({}));
8693
+ const input = body !== null && typeof body === "object" ? body : {};
8694
+ return json$2({ data: await core.fillReleaseLabels({
8695
+ dryRun: input.dryRun === true,
8696
+ catalogs: input.catalogs !== false
8697
+ }) });
8698
+ }),
7099
8699
  updateBundle: onCore(async (core, request, params) => {
7100
8700
  const bundleId = requireRouteParam(params, "id");
7101
- await core.updateBundle(bundleId, bundleUpdateOf(await request.json(), bundleId));
8701
+ const update = bundleUpdateOf(await request.json(), bundleId);
8702
+ await refusingInvalid(() => core.updateBundle(bundleId, update));
7102
8703
  return noContent();
7103
8704
  }),
7104
8705
  countBundles: onCore(async (core, request) => json$2({ data: await core.countBundles(platformOf(new URL(request.url))) })),
7105
8706
  countBundleChildren: onCore(async (core, request) => {
7106
8707
  const ids = (new URL(request.url).searchParams.get("ids") ?? "").split(",").filter((id) => id.length > 0);
7107
- if (ids.length === 0 || ids.length > 100) throw new HandlerBadRequestError("Bundle child counts take ids=<bundle id>,... with 1 to 100 ids.");
8708
+ if (ids.length === 0 || ids.length > MAX_IDS) throw new HandlerBadRequestError(`Bundle child counts take ids=<bundle id>,... with 1 to ${MAX_IDS} ids.`);
7108
8709
  return json$2({ data: await core.countBundleChildren(ids) });
7109
8710
  }),
7110
8711
  listBundleChildren: onCore(async (core, request, params) => {
@@ -7122,7 +8723,7 @@ const createAdminRouteHandlers = () => ({
7122
8723
  deployReleases: onCore(async (core, request) => {
7123
8724
  const { deployments } = await body(request);
7124
8725
  if (!Array.isArray(deployments) || deployments.length === 0 || !deployments.every(isDeployment)) throw new HandlerBadRequestError("Deploy needs deployments, each a bundle and its release policy.");
7125
- return json$2({ data: await core.deploy(deployments) }, 201);
8726
+ return json$2({ data: await refusingInvalid(() => core.deploy(deployments)) }, 201);
7126
8727
  }),
7127
8728
  promoteRelease: onCore(async (core, request, params) => {
7128
8729
  const input = await body(request);
@@ -7145,9 +8746,22 @@ const createAdminRouteHandlers = () => ({
7145
8746
  const url = new URL(request.url);
7146
8747
  const scope = nativeBuildScopeOf(url);
7147
8748
  const buildKey = url.searchParams.get("buildKey");
7148
- return json$2({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
8749
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
8750
+ const kind = url.searchParams.get("kind");
8751
+ const options = {
8752
+ ...buildKey === null ? {} : { buildKey },
8753
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
8754
+ ...builtInOlderThan === null ? {} : { builtInOlderThan },
8755
+ ...kind === null ? {} : { artifactKind: kind }
8756
+ };
8757
+ return json$2({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
8758
+ }),
8759
+ findNativeBuildSibling: onCore(async (core, _request, params) => {
8760
+ const build = await core.getNativeBuild(requireRouteParam(params, "id"));
8761
+ return json$2({ data: build === null ? null : await core.findNativeBuildSibling(build) });
7149
8762
  }),
7150
8763
  getNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
8764
+ findNativeBuildByBuiltInBundle: onCore(async (core, _request, params) => json$2({ data: await core.findNativeBuildByBuiltInBundle(requireRouteParam(params, "bundleId")) })),
7151
8765
  listNativeBuilds: onCore(async (core, request) => {
7152
8766
  const url = new URL(request.url);
7153
8767
  const input = keyset(url);
@@ -7159,14 +8773,97 @@ const createAdminRouteHandlers = () => ({
7159
8773
  }),
7160
8774
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
7161
8775
  const input = await body(request);
7162
- 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.");
8776
+ 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.");
7163
8777
  const submission = {
7164
8778
  destination: input.destination,
7165
8779
  version: input.version
7166
8780
  };
7167
8781
  return json$2({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
7168
8782
  }),
8783
+ markNativeBuild: onCore(async (core, request, params) => {
8784
+ const input = await body(request);
8785
+ if (!isRecord$5(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
8786
+ const mark = { storeBuild: input.storeBuild };
8787
+ return json$2({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
8788
+ }),
7169
8789
  deleteNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
8790
+ listIosDevices: onCore(async (core, request) => {
8791
+ const url = new URL(request.url);
8792
+ const input = keyset(url);
8793
+ const status = url.searchParams.get("status");
8794
+ return page(await refusingInvalid(() => core.listIosDevices({
8795
+ ...input,
8796
+ ...status === null ? {} : { status }
8797
+ })), input, ({ id }) => id);
8798
+ }),
8799
+ findIosDevice: onCore(async (core, _request, params) => json$2({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
8800
+ requestIosDevice: onCore(async (core, request) => {
8801
+ const input = await body(request);
8802
+ 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.");
8803
+ const device = {
8804
+ udid: input.udid,
8805
+ name: input.name,
8806
+ requestedBy: input.requestedBy
8807
+ };
8808
+ return json$2({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
8809
+ }),
8810
+ approveIosDevice: onCore(async (core, request, params) => {
8811
+ const input = await body(request);
8812
+ 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.");
8813
+ const approval = {
8814
+ approvedBy: input.approvedBy,
8815
+ ...input.name === void 0 ? {} : { name: input.name }
8816
+ };
8817
+ return json$2({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
8818
+ }),
8819
+ renameIosDevice: onCore(async (core, request, params) => {
8820
+ const input = await body(request);
8821
+ if (!isText$2(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
8822
+ const name = input.name;
8823
+ return json$2({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
8824
+ }),
8825
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
8826
+ const input = await body(request);
8827
+ const seen = input.seen;
8828
+ 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.");
8829
+ const outcome = {
8830
+ id: requireRouteParam(params, "id"),
8831
+ seen: {
8832
+ status: seen.status,
8833
+ approvedAtMs: seen.approvedAtMs
8834
+ },
8835
+ issuerId: input.issuerId,
8836
+ outcome: input.outcome,
8837
+ ...input.reason === void 0 ? {} : { reason: input.reason }
8838
+ };
8839
+ return json$2({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
8840
+ }),
8841
+ claimIosDeviceAccount: onCore(async (core, request) => {
8842
+ const { issuerId } = await body(request);
8843
+ if (!isText$2(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
8844
+ return json$2({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
8845
+ }),
8846
+ findIosDeviceAccount: onCore(async (core) => json$2({ data: await core.findIosDeviceAccount() })),
8847
+ markIosDevicesInBuild: onCore(async (core, request) => {
8848
+ const { buildId, ids } = await body(request);
8849
+ 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.");
8850
+ if (ids.length > MAX_IDS) throw new HandlerBadRequestError(`Marking iOS devices in a build takes at most ${MAX_IDS} ids a request.`);
8851
+ await core.markIosDevicesInBuild({
8852
+ buildId,
8853
+ ids
8854
+ });
8855
+ return noContent();
8856
+ }),
8857
+ deleteIosDevice: onCore(async (core, request, params) => {
8858
+ const url = new URL(request.url);
8859
+ const status = url.searchParams.get("status");
8860
+ const requestedBy = url.searchParams.get("requestedBy");
8861
+ const only = {
8862
+ ...status === null ? {} : { status },
8863
+ ...requestedBy === null ? {} : { requestedBy }
8864
+ };
8865
+ return json$2({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
8866
+ }),
7170
8867
  deleteBundles: onCore(async (core, request) => {
7171
8868
  const { ids } = await body(request);
7172
8869
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -7221,6 +8918,21 @@ const ADMIN_ROUTES = [
7221
8918
  path: "/release-catalogs",
7222
8919
  handler: "listReleaseCatalogs"
7223
8920
  },
8921
+ {
8922
+ method: "GET",
8923
+ path: "/release-scopes",
8924
+ handler: "listReleaseScopeKeys"
8925
+ },
8926
+ {
8927
+ method: "GET",
8928
+ path: "/release-labels",
8929
+ handler: "getReleaseByLabel"
8930
+ },
8931
+ {
8932
+ method: "POST",
8933
+ path: "/release-labels/fill",
8934
+ handler: "fillReleaseLabels"
8935
+ },
7224
8936
  {
7225
8937
  method: "POST",
7226
8938
  path: "/release-catalogs/:scopeKey/rebuild",
@@ -7296,6 +9008,16 @@ const ADMIN_ROUTES = [
7296
9008
  path: "/native-builds/latest",
7297
9009
  handler: "findNativeBuild"
7298
9010
  },
9011
+ {
9012
+ method: "GET",
9013
+ path: "/native-builds/built-in/:bundleId",
9014
+ handler: "findNativeBuildByBuiltInBundle"
9015
+ },
9016
+ {
9017
+ method: "GET",
9018
+ path: "/native-builds/:id/sibling",
9019
+ handler: "findNativeBuildSibling"
9020
+ },
7299
9021
  {
7300
9022
  method: "GET",
7301
9023
  path: "/native-builds/:id",
@@ -7311,10 +9033,65 @@ const ADMIN_ROUTES = [
7311
9033
  path: "/native-builds/:id/submission",
7312
9034
  handler: "recordNativeBuildSubmission"
7313
9035
  },
9036
+ {
9037
+ method: "POST",
9038
+ path: "/native-builds/:id/store-build",
9039
+ handler: "markNativeBuild"
9040
+ },
7314
9041
  {
7315
9042
  method: "DELETE",
7316
9043
  path: "/native-builds/:id",
7317
9044
  handler: "deleteNativeBuild"
9045
+ },
9046
+ {
9047
+ method: "GET",
9048
+ path: "/ios-devices",
9049
+ handler: "listIosDevices"
9050
+ },
9051
+ {
9052
+ method: "POST",
9053
+ path: "/ios-devices",
9054
+ handler: "requestIosDevice"
9055
+ },
9056
+ {
9057
+ method: "GET",
9058
+ path: "/ios-devices/udid/:udid",
9059
+ handler: "findIosDevice"
9060
+ },
9061
+ {
9062
+ method: "POST",
9063
+ path: "/ios-devices/in-build",
9064
+ handler: "markIosDevicesInBuild"
9065
+ },
9066
+ {
9067
+ method: "GET",
9068
+ path: "/ios-devices/account",
9069
+ handler: "findIosDeviceAccount"
9070
+ },
9071
+ {
9072
+ method: "POST",
9073
+ path: "/ios-devices/account",
9074
+ handler: "claimIosDeviceAccount"
9075
+ },
9076
+ {
9077
+ method: "POST",
9078
+ path: "/ios-devices/:id/approval",
9079
+ handler: "approveIosDevice"
9080
+ },
9081
+ {
9082
+ method: "POST",
9083
+ path: "/ios-devices/:id/outcome",
9084
+ handler: "recordIosDeviceOutcome"
9085
+ },
9086
+ {
9087
+ method: "PATCH",
9088
+ path: "/ios-devices/:id",
9089
+ handler: "renameIosDevice"
9090
+ },
9091
+ {
9092
+ method: "DELETE",
9093
+ path: "/ios-devices/:id",
9094
+ handler: "deleteIosDevice"
7318
9095
  }
7319
9096
  ];
7320
9097
  //#endregion
@@ -7337,9 +9114,9 @@ const CATALOG_CACHE_CONTROL = "public, max-age=0, s-maxage=5";
7337
9114
  * background. `stale-if-error=0` keeps origin errors visible: without it,
7338
9115
  * Cloudflare serves a stale copy on error indefinitely.
7339
9116
  *
7340
- * A device can see a catalog up to 15 seconds after a deploy or a Roll back
7341
- * replaced it: the origin's 5-second catalog memo, then 5 seconds fresh and
7342
- * 5 stale at the CDN. A revoked API key can read a cached catalog up to
9117
+ * A device can see a catalog, or a scope's lack of one, up to 15 seconds
9118
+ * after a deploy or a Roll back replaced it: the origin's 5-second catalog
9119
+ * memo, then 5 seconds fresh and 5 stale at the CDN. A revoked API key can read a cached catalog up to
7343
9120
  * 10 seconds. Devices and caches that don't read the header keep
7344
9121
  * `Cache-Control`.
7345
9122
  */
@@ -7418,38 +9195,53 @@ const catalogResponse = async (catalog, request) => {
7418
9195
  };
7419
9196
  const createReleaseCatalogRouteHandlers = () => {
7420
9197
  const cache = /* @__PURE__ */ new Map();
9198
+ const evict = (insertedHit) => {
9199
+ const now = Date.now();
9200
+ let oldestMiss;
9201
+ let oldest;
9202
+ for (const [key, entry] of cache) if (entry.expiresAt <= now) cache.delete(key);
9203
+ else {
9204
+ if (entry.row === null) oldestMiss ??= key;
9205
+ oldest ??= key;
9206
+ }
9207
+ if (cache.size <= ORIGIN_CACHE_MAX_ENTRIES) return;
9208
+ const victim = oldestMiss ?? (insertedHit ? oldest : void 0);
9209
+ if (victim !== void 0) cache.delete(victim);
9210
+ };
7421
9211
  const inFlight = /* @__PURE__ */ new Map();
7422
- const loadCatalog = async (key, load) => {
7423
- const cached = cache.get(key);
9212
+ const loadRow = async (scopeKey, load) => {
9213
+ const cached = cache.get(scopeKey);
7424
9214
  if (cached !== void 0 && cached.expiresAt > Date.now()) {
7425
- cache.delete(key);
7426
- cache.set(key, cached);
7427
- return cached.catalog;
9215
+ cache.delete(scopeKey);
9216
+ cache.set(scopeKey, cached);
9217
+ return cached.row;
7428
9218
  }
7429
- if (cached !== void 0) cache.delete(key);
7430
- const pending = inFlight.get(key);
9219
+ if (cached !== void 0) cache.delete(scopeKey);
9220
+ const pending = inFlight.get(scopeKey);
7431
9221
  if (pending !== void 0) return pending;
7432
- const next = load().then((catalog) => {
7433
- if (catalog !== null) {
7434
- cache.set(key, {
7435
- catalog,
7436
- expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
7437
- });
7438
- while (cache.size > ORIGIN_CACHE_MAX_ENTRIES) {
7439
- const oldestKey = cache.keys().next().value;
7440
- if (oldestKey === void 0) break;
7441
- cache.delete(oldestKey);
7442
- }
7443
- }
7444
- return catalog;
9222
+ const next = load().then((row) => {
9223
+ cache.set(scopeKey, {
9224
+ row,
9225
+ expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
9226
+ });
9227
+ if (cache.size > ORIGIN_CACHE_MAX_ENTRIES) evict(row !== null);
9228
+ return row;
7445
9229
  });
7446
- inFlight.set(key, next);
9230
+ inFlight.set(scopeKey, next);
7447
9231
  try {
7448
9232
  return await next;
7449
9233
  } finally {
7450
- inFlight.delete(key);
9234
+ inFlight.delete(scopeKey);
7451
9235
  }
7452
9236
  };
9237
+ const loadCatalog = async (core, input) => {
9238
+ const scopeKey = releaseCatalogScopeKeyOf(input);
9239
+ const parsed = await loadRow(scopeKey, async () => {
9240
+ const row = await core.getReleaseCatalogRow(scopeKey);
9241
+ return row === null ? null : parseReleaseCatalogRow(row);
9242
+ });
9243
+ return projectParsedReleaseCatalogRow(parsed, input, scopeKey);
9244
+ };
7453
9245
  return {
7454
9246
  appVersionReleaseCatalog: async (params, request, { core }) => {
7455
9247
  const rawAppVersion = requireRouteParam(params, "appVersion");
@@ -7463,7 +9255,7 @@ const createReleaseCatalogRouteHandlers = () => {
7463
9255
  };
7464
9256
  const invalid = invalidScope(input);
7465
9257
  if (invalid) return invalid;
7466
- return catalogResponse(await loadCatalog(`app-version:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
9258
+ return catalogResponse(await loadCatalog(core, input), request);
7467
9259
  },
7468
9260
  fingerprintReleaseCatalog: async (params, request, { core }) => {
7469
9261
  const input = {
@@ -7474,7 +9266,7 @@ const createReleaseCatalogRouteHandlers = () => {
7474
9266
  };
7475
9267
  const invalid = invalidScope(input);
7476
9268
  if (invalid) return invalid;
7477
- return catalogResponse(await loadCatalog(`fingerprint:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
9269
+ return catalogResponse(await loadCatalog(core, input), request);
7478
9270
  },
7479
9271
  artifactV2: async (params, _request, { core }) => {
7480
9272
  const info = await core.getArtifactInfo(requireRouteParam(params, "targetBundleId"), requireRouteParam(params, "currentBundleId"), 2);
@@ -10757,13 +12549,80 @@ const breakdownOf = (rows) => {
10757
12549
  });
10758
12550
  };
10759
12551
  /**
12552
+ * The breakdown rows a failures read takes from one hour. An hour holds a
12553
+ * row per release, stage, reason, and detail that failed in it, a handful in
12554
+ * practice, and an incident across several releases and error codes still
12555
+ * fits; but a client with the app's API key can report any number of
12556
+ * details.
12557
+ */
12558
+ const FAILURE_ROWS_PER_HOUR = 20;
12559
+ /**
12560
+ * One query's stored rows: an hour's bound and one more row, on every shard,
12561
+ * so an hour past its bound costs at most one query's worth of rows more.
12562
+ */
12563
+ const FAILURE_QUERY_LIMIT = Math.min(PAGE, 168);
12564
+ /**
12565
+ * A channel's breakdown rows over a range, newest first, up to
12566
+ * {@link FAILURE_ROWS_PER_HOUR} an hour: 480 rows for a day, 14,400 for 30
12567
+ * days, however many details clients report. An hour that holds more is read
12568
+ * no further, and the read goes on from the hour before it with a new query;
12569
+ * the hour is listed in `cappedHours`, since its failures count only in part.
12570
+ * Every other hour counts every failure it holds.
12571
+ */
12572
+ const failureRowsByHour = async (db, platform, channel, timeRange) => {
12573
+ const read = (end, cursor) => db.findAggregates("insights_failures", {
12574
+ index: "byScope",
12575
+ where: {
12576
+ platform,
12577
+ channel
12578
+ },
12579
+ range: {
12580
+ gte: timeRange.start,
12581
+ lt: end
12582
+ },
12583
+ order: "desc",
12584
+ limit: FAILURE_QUERY_LIMIT,
12585
+ ...cursor === void 0 ? {} : { cursor }
12586
+ });
12587
+ const rows = [];
12588
+ const cappedHours = [];
12589
+ const perHour = /* @__PURE__ */ new Map();
12590
+ let end = timeRange.end;
12591
+ let cursor;
12592
+ while (end > timeRange.start) {
12593
+ const page = await read(end, cursor);
12594
+ let capped;
12595
+ for (const row of page.rows) {
12596
+ const hour = row.bucket_start_ms;
12597
+ const count = (perHour.get(hour) ?? 0) + 1;
12598
+ if (count > FAILURE_ROWS_PER_HOUR) {
12599
+ capped = hour;
12600
+ break;
12601
+ }
12602
+ perHour.set(hour, count);
12603
+ rows.push(row);
12604
+ }
12605
+ if (capped !== void 0) {
12606
+ cappedHours.unshift(capped);
12607
+ end = capped;
12608
+ cursor = void 0;
12609
+ } else if (page.next === void 0) break;
12610
+ else cursor = page.next;
12611
+ }
12612
+ return {
12613
+ rows,
12614
+ cappedHours
12615
+ };
12616
+ };
12617
+ /**
10760
12618
  * A release's or a channel's update failures. Since a release's first
10761
12619
  * report: its lifetime counters and failed installations. Over a time range
10762
12620
  * of at most 30 days: failures, failed checks, and the breakdown by stage,
10763
12621
  * reason, and detail, all summed from the breakdown's hourly rows; downloads
10764
12622
  * from the counters; failed installations from their sketches. A release reads hourly rows, a
10765
12623
  * channel daily rows past 48 hours like its activity; the breakdown's rows
10766
- * are hourly, so its coverage is the raw period's.
12624
+ * are hourly, so its coverage is the raw period's, and partial when an hour
12625
+ * held more breakdown rows than a read takes from it.
10767
12626
  */
10768
12627
  const getUpdateFailures = async (db, input, now, retention) => {
10769
12628
  const { platform, channel, releaseId, timeRange } = input;
@@ -10825,7 +12684,7 @@ const getUpdateFailures = async (db, input, now, retention) => {
10825
12684
  days,
10826
12685
  kept.hour
10827
12686
  ];
10828
- const [counters, failures, checks, active, rows] = await Promise.all([
12687
+ const [counters, failures, checks, active, { rows, cappedHours }] = await Promise.all([
10829
12688
  counterRows(db, parts, ...window),
10830
12689
  sketchRows(db, failure, ...window),
10831
12690
  days ? sketchRows(db, {
@@ -10833,25 +12692,17 @@ const getUpdateFailures = async (db, input, now, retention) => {
10833
12692
  scopeKind: "check"
10834
12693
  }, ...window) : [],
10835
12694
  days ? sketchRows(db, usageParts(channel, platform), ...window) : [],
10836
- drain((page) => db.findAggregates("insights_failures", {
10837
- index: "byScope",
10838
- where: {
10839
- platform,
10840
- channel
10841
- },
10842
- range: {
10843
- gte: timeRange.start,
10844
- lt: timeRange.end
10845
- },
10846
- limit: PAGE,
10847
- ...page
10848
- }))
12695
+ failureRowsByHour(db, platform, channel, timeRange)
10849
12696
  ]);
10850
12697
  const total = (field) => counters.reduce((sum, row) => sum + row[field], 0);
10851
12698
  const scoped = rows.filter((row) => FAILURE_STAGES.has(row.stage) && (releaseId === void 0 || row.release_id === releaseId));
10852
12699
  const failuresAt = (counted) => scoped.reduce((sum, row) => sum + (counted(row.stage) ? Math.max(0, row.events) : 0), 0);
12700
+ const coverage = coverageOf(timeRange.start, kept.hour);
10853
12701
  return {
10854
- coverage: coverageOf(timeRange.start, kept.hour),
12702
+ coverage: cappedHours.length === 0 ? coverage : {
12703
+ kind: "partial",
12704
+ sinceMs: coverage.sinceMs
12705
+ },
10855
12706
  measuredAtMs: at,
10856
12707
  failedUpdates: failuresAt((stage) => stage !== "check"),
10857
12708
  failedInstallations: failed(failures),
@@ -10863,7 +12714,8 @@ const getUpdateFailures = async (db, input, now, retention) => {
10863
12714
  failedInstallations: failed(checks),
10864
12715
  activeInstallations: countDistinct(mergeDistinct(active.map((row) => row.activity_users)))
10865
12716
  } } : {},
10866
- breakdown: breakdownOf(scoped)
12717
+ breakdown: breakdownOf(scoped),
12718
+ ...cappedHours.length === 0 ? {} : { cappedHours }
10867
12719
  };
10868
12720
  };
10869
12721
  //#endregion
@@ -14295,10 +16147,30 @@ async apply() {
14295
16147
  };
14296
16148
  };
14297
16149
  //#endregion
16150
+ //#region src/lazyCredentials.ts
16151
+ /**
16152
+ * `credentials` as the AWS SDK takes them: access keys with a lazy field
16153
+ * become a provider, which the SDK calls once, on its first request.
16154
+ */
16155
+ const toSdkCredentials$1 = (credentials) => {
16156
+ if (credentials === void 0 || typeof credentials === "function") return credentials;
16157
+ const { accessKeyId, secretAccessKey, sessionToken, ...rest } = credentials;
16158
+ if (typeof accessKeyId !== "function" && typeof secretAccessKey !== "function" && typeof sessionToken !== "function") return credentials;
16159
+ return async () => ({
16160
+ ...rest,
16161
+ accessKeyId: await resolveLazy(accessKeyId),
16162
+ secretAccessKey: await resolveLazy(secretAccessKey),
16163
+ ...sessionToken === void 0 ? {} : { sessionToken: await resolveLazy(sessionToken) }
16164
+ });
16165
+ };
16166
+ //#endregion
14298
16167
  //#region src/dynamoDB.ts
14299
16168
  /** The DynamoDB client ignores the CloudFront and batching settings. */
14300
- const adapterOf = ({ tableName, ...clientConfig }) => {
14301
- const client = new _aws_sdk_client_dynamodb.DynamoDBClient(clientConfig);
16169
+ const adapterOf = ({ tableName, credentials, ...clientConfig }) => {
16170
+ const client = new _aws_sdk_client_dynamodb.DynamoDBClient({
16171
+ ...clientConfig,
16172
+ credentials: toSdkCredentials$1(credentials)
16173
+ });
14302
16174
  const store = createDynamoDBStore({
14303
16175
  client,
14304
16176
  tableName
@@ -14323,7 +16195,10 @@ const marked = (target) => ({ [DATABASE_TARGET]: target });
14323
16195
  */
14324
16196
  const dynamoDB = (config) => {
14325
16197
  const { client, adapter } = adapterOf(config);
14326
- const cloudFront = createUpdateRouteInvalidation(config);
16198
+ const cloudFront = createUpdateRouteInvalidation({
16199
+ ...config,
16200
+ credentials: toSdkCredentials$1(config.credentials)
16201
+ });
14327
16202
  return {
14328
16203
  ...createEngineDatabase({
14329
16204
  name: "dynamoDB",
@@ -14340,18 +16215,49 @@ const dynamoDB = (config) => {
14340
16215
  };
14341
16216
  };
14342
16217
  //#endregion
14343
- //#region src/s3Storage.ts
16218
+ //#region ../storage-s3/dist/index.mjs
16219
+ /**
16220
+ * `credentials` as the AWS SDK takes them: access keys with a lazy field
16221
+ * become a provider, which the SDK calls once, on its first request.
16222
+ */
16223
+ const toSdkCredentials = (credentials) => {
16224
+ if (credentials === void 0 || typeof credentials === "function") return credentials;
16225
+ const { accessKeyId, secretAccessKey, sessionToken, ...rest } = credentials;
16226
+ if (typeof accessKeyId !== "function" && typeof secretAccessKey !== "function" && typeof sessionToken !== "function") return credentials;
16227
+ return async () => ({
16228
+ ...rest,
16229
+ accessKeyId: await resolveLazy(accessKeyId),
16230
+ secretAccessKey: await resolveLazy(secretAccessKey),
16231
+ ...sessionToken === void 0 ? {} : { sessionToken: await resolveLazy(sessionToken) }
16232
+ });
16233
+ };
14344
16234
  /** Devices download right after the update check that returns the URL. */
14345
- const PRESIGNED_URL_EXPIRES_IN_SECONDS = 3600;
14346
- const isObjectNotFoundError = (error) => error instanceof Error && (error.name === "NotFound" || error.name === "NoSuchKey");
14347
- function s3Storage(config) {
14348
- const { bucketName, basePath, getDownloadUrl, ...s3Config } = config;
14349
- const client = new _aws_sdk_client_s3.S3Client(applyS3RuntimeAwsConfig(s3Config));
14350
- const normalizedBasePath = basePath?.replace(/^\/+|\/+$/g, "") ?? "";
16235
+ const DEFAULT_SIGNED_LIFETIME_SECONDS = 3600;
16236
+ /** SigV4's limit on a presigned URL. */
16237
+ const MAX_SIGNED_LIFETIME_SECONDS = 604800;
16238
+ /** DeleteObjects takes at most 1000 keys a request. */
16239
+ const DELETE_BATCH_SIZE = 1e3;
16240
+ const isObjectNotFoundError = (error) => {
16241
+ if (error instanceof Error && (error.name === "NotFound" || error.name === "NoSuchKey")) return true;
16242
+ return typeof error === "object" && error !== null && "$metadata" in error && error.$metadata?.httpStatusCode === 404;
16243
+ };
16244
+ const trimSlashes = (value) => value.replace(/^\/+|\/+$/g, "");
16245
+ /**
16246
+ * A storage adapter over a bucket's S3 API, which AWS S3, Cloudflare R2, and
16247
+ * Neon Object Storage all serve. Each provider package passes its own name,
16248
+ * URI protocol, and client defaults.
16249
+ */
16250
+ const createS3Storage = ({ name, protocol }, config) => {
16251
+ const { bucketName, basePath, getDownloadUrl, signedUrlExpiresIn = DEFAULT_SIGNED_LIFETIME_SECONDS, credentials, ...clientConfig } = config;
16252
+ if (!Number.isFinite(signedUrlExpiresIn) || signedUrlExpiresIn <= 0 || signedUrlExpiresIn > MAX_SIGNED_LIFETIME_SECONDS) throw new Error(`${name} signedUrlExpiresIn must be between 1 and ${MAX_SIGNED_LIFETIME_SECONDS} seconds (seven days).`);
16253
+ const client = new _aws_sdk_client_s3.S3Client({
16254
+ ...clientConfig,
16255
+ credentials: toSdkCredentials(credentials)
16256
+ });
16257
+ const normalizedBasePath = trimSlashes(basePath ?? "");
14351
16258
  const getStorageKey = createStorageKeyBuilder(normalizedBasePath);
14352
16259
  const getListPrefix = (prefix = "") => {
14353
- const normalizedPrefix = prefix.replace(/^\/+|\/+$/g, "");
14354
- const value = [normalizedBasePath, normalizedPrefix].filter(Boolean).join("/");
16260
+ const value = [normalizedBasePath, trimSlashes(prefix)].filter(Boolean).join("/");
14355
16261
  return value ? `${value}/` : "";
14356
16262
  };
14357
16263
  /**
@@ -14363,7 +16269,7 @@ function s3Storage(config) {
14363
16269
  return createStorageUri({
14364
16270
  bucket: bucketName,
14365
16271
  key,
14366
- protocol: "s3"
16272
+ protocol
14367
16273
  });
14368
16274
  } catch {
14369
16275
  return null;
@@ -14375,55 +16281,16 @@ function s3Storage(config) {
14375
16281
  return key.startsWith(basePrefix) ? key.slice(basePrefix.length) : key;
14376
16282
  };
14377
16283
  const parseAndValidate = (storageUri) => {
14378
- const parsed = parseStorageUri(storageUri, "s3");
16284
+ const parsed = parseStorageUri(storageUri, protocol);
14379
16285
  if (parsed.bucket !== bucketName) throw new Error(`Bucket name mismatch: expected "${bucketName}", but found "${parsed.bucket}".`);
14380
16286
  return parsed;
14381
16287
  };
14382
16288
  return createStorageAdapter({
14383
- name: "s3Storage",
14384
- protocol: "s3",
14385
- async listObjects(prefix) {
14386
- const objects = [];
14387
- let continuationToken;
14388
- do {
14389
- const response = await client.send(new _aws_sdk_client_s3.ListObjectsV2Command({
14390
- Bucket: bucketName,
14391
- ContinuationToken: continuationToken,
14392
- Prefix: getListPrefix(prefix)
14393
- }));
14394
- for (const object of response.Contents ?? []) {
14395
- if (!object.Key) continue;
14396
- const storageUri = getListedStorageUri(object.Key);
14397
- if (storageUri === null) continue;
14398
- objects.push({
14399
- key: getRelativeKey(object.Key),
14400
- lastModifiedAt: object.LastModified,
14401
- size: object.Size ?? 0,
14402
- storageUri
14403
- });
14404
- }
14405
- continuationToken = response.NextContinuationToken;
14406
- } while (continuationToken);
14407
- return objects;
14408
- },
14409
- async deleteObjects(relativeKeys) {
14410
- const keys = relativeKeys.map((key) => getStorageKey(key));
14411
- for (let offset = 0; offset < keys.length; offset += 1e3) {
14412
- const batch = keys.slice(offset, offset + 1e3);
14413
- if (batch.length === 0) continue;
14414
- const response = await client.send(new _aws_sdk_client_s3.DeleteObjectsCommand({
14415
- Bucket: bucketName,
14416
- Delete: {
14417
- Objects: batch.map((Key) => ({ Key })),
14418
- Quiet: true
14419
- }
14420
- }));
14421
- if (response.Errors && response.Errors.length > 0) throw new Error(`Failed to delete ${response.Errors.length} S3 object(s).`);
14422
- }
14423
- },
16289
+ name,
16290
+ protocol,
14424
16291
  async put({ key, body, contentLength, contentType }) {
14425
16292
  const storageKey = getStorageKey(key);
14426
- const response = await new _aws_sdk_lib_storage.Upload({
16293
+ await new _aws_sdk_lib_storage.Upload({
14427
16294
  client,
14428
16295
  params: {
14429
16296
  Body: body,
@@ -14434,11 +16301,10 @@ function s3Storage(config) {
14434
16301
  Key: storageKey
14435
16302
  }
14436
16303
  }).done();
14437
- if (!response.Bucket || !response.Key) throw new Error("Upload failed");
14438
16304
  return { storageUri: createStorageUri({
14439
16305
  bucket: bucketName,
14440
16306
  key: storageKey,
14441
- protocol: "s3"
16307
+ protocol
14442
16308
  }) };
14443
16309
  },
14444
16310
  async get({ storageUri }) {
@@ -14461,11 +16327,10 @@ function s3Storage(config) {
14461
16327
  async getDownloadUrl({ storageUri }) {
14462
16328
  const { key } = parseAndValidate(storageUri);
14463
16329
  if (getDownloadUrl) return getDownloadUrl({ storageUri });
14464
- const { getSignedUrl } = await import("@aws-sdk/s3-request-presigner");
14465
- return { url: await getSignedUrl(client, new _aws_sdk_client_s3.GetObjectCommand({
16330
+ return { url: await (0, _aws_sdk_s3_request_presigner.getSignedUrl)(client, new _aws_sdk_client_s3.GetObjectCommand({
14466
16331
  Bucket: bucketName,
14467
16332
  Key: key
14468
- }), { expiresIn: PRESIGNED_URL_EXPIRES_IN_SECONDS }) };
16333
+ }), { expiresIn: signedUrlExpiresIn }) };
14469
16334
  },
14470
16335
  async exists({ storageUri }) {
14471
16336
  const { key } = parseAndValidate(storageUri);
@@ -14487,8 +16352,61 @@ function s3Storage(config) {
14487
16352
  Key: key
14488
16353
  }));
14489
16354
  return { deleted: true };
16355
+ },
16356
+ async listObjects(prefix) {
16357
+ const objects = [];
16358
+ let continuationToken;
16359
+ do {
16360
+ const response = await client.send(new _aws_sdk_client_s3.ListObjectsV2Command({
16361
+ Bucket: bucketName,
16362
+ ContinuationToken: continuationToken,
16363
+ Prefix: getListPrefix(prefix)
16364
+ }));
16365
+ for (const object of response.Contents ?? []) {
16366
+ if (!object.Key) continue;
16367
+ const storageUri = getListedStorageUri(object.Key);
16368
+ if (storageUri === null) continue;
16369
+ objects.push({
16370
+ key: getRelativeKey(object.Key),
16371
+ lastModifiedAt: object.LastModified,
16372
+ size: object.Size ?? 0,
16373
+ storageUri
16374
+ });
16375
+ }
16376
+ continuationToken = response.NextContinuationToken;
16377
+ } while (continuationToken);
16378
+ return objects;
16379
+ },
16380
+ async deleteObjects(relativeKeys) {
16381
+ const keys = relativeKeys.map((key) => getStorageKey(key));
16382
+ for (let offset = 0; offset < keys.length; offset += DELETE_BATCH_SIZE) {
16383
+ const batch = keys.slice(offset, offset + DELETE_BATCH_SIZE);
16384
+ const response = await client.send(new _aws_sdk_client_s3.DeleteObjectsCommand({
16385
+ Bucket: bucketName,
16386
+ Delete: {
16387
+ Objects: batch.map((Key) => ({ Key })),
16388
+ Quiet: true
16389
+ }
16390
+ }));
16391
+ if (response.Errors && response.Errors.length > 0) throw new Error(`Failed to delete ${response.Errors.length} S3 object(s) from bucket "${bucketName}".`);
16392
+ }
14490
16393
  }
14491
16394
  });
16395
+ };
16396
+ //#endregion
16397
+ //#region src/s3Storage.ts
16398
+ function s3Storage(config) {
16399
+ const { bucketName, basePath, getDownloadUrl, credentials, ...s3Config } = config;
16400
+ return createS3Storage({
16401
+ name: "s3Storage",
16402
+ protocol: "s3"
16403
+ }, {
16404
+ ...applyS3RuntimeAwsConfig(s3Config),
16405
+ credentials,
16406
+ bucketName,
16407
+ basePath,
16408
+ getDownloadUrl
16409
+ });
14492
16410
  }
14493
16411
  //#endregion
14494
16412
  //#region lambda/index.ts