@hot-updater/vercel 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.
@@ -615,7 +615,8 @@ const releaseRowToRelease = (row) => ({
615
615
  operation: row.operation,
616
616
  sourceReleaseId: row.source_release_id,
617
617
  createdAtMs: row.created_at_ms,
618
- updatedAtMs: row.updated_at_ms
618
+ updatedAtMs: row.updated_at_ms,
619
+ label: row.label ?? null
619
620
  });
620
621
  const bundleToRow = (bundle) => {
621
622
  const metadata = bundleMetadataToRow(bundle.metadata);
@@ -1124,7 +1125,7 @@ function rangeToIntervals(range) {
1124
1125
  throw new ReleaseCatalogCompilationError("INVALID_TARGET_RANGE", `Invalid target app-version range: ${range}`);
1125
1126
  }
1126
1127
  }
1127
- function releaseDescriptor(release) {
1128
+ function releaseDescriptor(release, labels) {
1128
1129
  return {
1129
1130
  releaseId: release.id,
1130
1131
  kind: release.kind,
@@ -1132,7 +1133,8 @@ function releaseDescriptor(release) {
1132
1133
  rolloutCohortCount: release.rolloutCohortCount,
1133
1134
  targetCohorts: [...new Set(release.targetCohorts)].sort(),
1134
1135
  shouldForceUpdate: release.shouldForceUpdate,
1135
- message: release.message
1136
+ message: release.message,
1137
+ ...labels && typeof release.label === "number" ? { label: release.label } : {}
1136
1138
  };
1137
1139
  }
1138
1140
  function validateReleases(releases, strategy) {
@@ -1345,12 +1347,21 @@ async function compileReleaseCatalog(input) {
1345
1347
  const targetCohorts = new Set(releases.flatMap((release) => release.targetCohorts));
1346
1348
  if (targetCohorts.size > 512) throw new ReleaseCatalogCompilationError("DISTINCT_TARGET_COHORT_LIMIT", `Scope exceeds 512 distinct target cohorts`);
1347
1349
  const { envelope, retainedReleases } = input.strategy === "APP_VERSION" ? compileAppVersion(releases) : compileFingerprint(releases);
1348
- const payload = {
1349
- ...envelope,
1350
- releaseDescriptors: retainedReleases.map(releaseDescriptor)
1350
+ const compile = (labels) => {
1351
+ const payload = {
1352
+ ...envelope,
1353
+ releaseDescriptors: retainedReleases.map((release) => releaseDescriptor(release, labels))
1354
+ };
1355
+ const canonicalPayload = canonicalStringify(payload);
1356
+ return {
1357
+ payload,
1358
+ canonicalPayload,
1359
+ byteSize: new TextEncoder().encode(canonicalPayload).byteLength
1360
+ };
1351
1361
  };
1352
- const canonicalPayload = canonicalStringify(payload);
1353
- const byteSize = new TextEncoder().encode(canonicalPayload).byteLength;
1362
+ let compiled = compile(true);
1363
+ if (compiled.byteSize > 262144 && retainedReleases.some((release) => typeof release.label === "number")) compiled = compile(false);
1364
+ const { payload, canonicalPayload, byteSize } = compiled;
1354
1365
  if (byteSize > 262144) throw new ReleaseCatalogCompilationError("CATALOG_OVERSIZE", `Compiled Release catalog is ${byteSize} bytes; maximum is ${MAX_COMPILED_CATALOG_BYTES}`);
1355
1366
  return {
1356
1367
  byteSize,
@@ -1969,43 +1980,6 @@ const withSchemaFence = (adapter, adapterName, expected, fix) => {
1969
1980
  const METER = Symbol.for("@hot-updater/plugin-core/read-meter");
1970
1981
  const readMeterOf = (database) => typeof database === "object" && database !== null ? database[METER] : void 0;
1971
1982
  //#endregion
1972
- //#region ../plugin-core/dist/engine/db/schemaSettings.mjs
1973
- const storedSettings = async (adapter, keys) => {
1974
- const rows = await readSettings(adapter, keys);
1975
- return new Map(keys.map((key, position) => [key, rows[position] ?? null]));
1976
- };
1977
- const writeSchemaSettings = async (adapter, adapterName, settings) => {
1978
- const stored = await storedSettings(adapter, Object.keys(settings));
1979
- const ops = Object.entries(settings).flatMap(([key, value]) => {
1980
- const row = stored.get(key);
1981
- if (row === null || row === void 0) return [{
1982
- type: "insert",
1983
- table: SETTINGS_TABLE,
1984
- row: {
1985
- key,
1986
- value,
1987
- _v: 0
1988
- }
1989
- }];
1990
- if (row.value === value) return [];
1991
- return [{
1992
- type: "patch",
1993
- table: SETTINGS_TABLE,
1994
- key: [key],
1995
- set: { value },
1996
- guard: { v: Number(row._v) },
1997
- previous: row
1998
- }];
1999
- });
2000
- if (ops.length === 0) return;
2001
- if (!(await adapter.write(ops)).ok) throw new Error(`${adapterName}: the schema settings changed during the migration; run it again.`);
2002
- };
2003
- const migrateSchema = async (adapter, adapterName, tables, settings) => {
2004
- if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
2005
- await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
2006
- await writeSchemaSettings(adapter, adapterName, settings);
2007
- };
2008
- //#endregion
2009
1983
  //#region ../plugin-core/dist/engine/database/sql/sqlSchema.mjs
2010
1984
  const quoteSql = (dialect, name) => dialect === "mysql" ? `\`${name.replaceAll("`", "``")}\`` : `"${name.replaceAll("\"", "\"\"")}"`;
2011
1985
  const isMultiIndex = (table, index) => index.eq.some((column) => findPhysicalColumn(table, column).multi);
@@ -2049,6 +2023,7 @@ const sqlTableShapes = (dialect, tables, tablePrefix = "") => tables.map((table)
2049
2023
  const name = tablePrefix + table.name;
2050
2024
  const indexed = /* @__PURE__ */ new Set([...table.key, ...table.indexes.flatMap(({ eq, sort }) => [...eq, ...sort])]);
2051
2025
  if (dialect === "mysql") checkMysqlKey(table, "key", table.key);
2026
+ const covered = /* @__PURE__ */ new Set([JSON.stringify(table.key)]);
2052
2027
  const indexes = table.indexes.flatMap((index) => {
2053
2028
  const columns = [...index.eq, ...indexOrderColumns(table, index)];
2054
2029
  if (dialect === "mysql") checkMysqlKey(table, `index ${index.name}`, columns);
@@ -2064,11 +2039,19 @@ const sqlTableShapes = (dialect, tables, tablePrefix = "") => tables.map((table)
2064
2039
  name: `${name}__${index.name}`,
2065
2040
  columns: entries,
2066
2041
  key: columns,
2067
- indexes: []
2042
+ indexes: [{
2043
+ kind: "index",
2044
+ name: shortSqlName(`${name}__${index.name}__key`),
2045
+ unique: false,
2046
+ columns: table.key
2047
+ }]
2068
2048
  }
2069
2049
  }];
2070
2050
  }
2071
- if (!index.unique && columns.join() === table.key.join()) return [];
2051
+ if (!index.unique) {
2052
+ if (covered.has(JSON.stringify(columns))) return [];
2053
+ covered.add(JSON.stringify(columns));
2054
+ }
2072
2055
  return [{
2073
2056
  kind: "index",
2074
2057
  name: shortSqlName(`${name}_${index.name}`),
@@ -2134,9 +2117,17 @@ const pruneStatements = (dialect, table, tablePrefix, limit) => {
2134
2117
  const order = retentionOrder(table).columns.map(quote);
2135
2118
  const list = (alias, direction = "") => order.map((column) => `${alias}.${column}${direction}`).join(", ");
2136
2119
  const oldest = (before) => `SELECT ${list("i")} FROM ${name} i WHERE i.${at} <= ${before()} ORDER BY ${list("i", " ASC")} LIMIT ${limit}`;
2137
- const doomed = (alias, before) => `${alias}.${at} <= ${before()} AND (${list(alias)}) <= (SELECT ${list("b")} FROM (${oldest(before)}) b ORDER BY ${list("b", " DESC")} LIMIT 1)`;
2120
+ const doomed = (alias, before) => `(${list(alias)}) <= (SELECT ${list("b")} FROM (${oldest(before)}) b ORDER BY ${list("b", " DESC")} LIMIT 1) AND ${alias}.${at} <= ${before()}`;
2138
2121
  const entries = table.indexes.filter((index) => isMultiIndex(table, index)).map((index) => quote(`${tablePrefix}${table.name}__${index.name}`));
2139
2122
  const keyOf = (left, right) => table.key.map((column) => `${left}.${quote(column)} = ${right}.${quote(column)}`).join(" AND ");
2123
+ if (dialect === "sqlite") return [...table.indexes.filter((index) => isMultiIndex(table, index)).map((index) => {
2124
+ const columns = [...index.eq, ...indexOrderColumns(table, index)];
2125
+ const multi = columns.filter((column) => findPhysicalColumn(table, column).multi);
2126
+ const values = columns.map((column) => multi.includes(column) ? `j${multi.indexOf(column)}.${quote("value")}` : `b.${quote(column)}`);
2127
+ const each = multi.map((column, at) => `, json_each(b.${quote(column)}) j${at}`);
2128
+ const into = quote(`${tablePrefix}${table.name}__${index.name}`);
2129
+ return (before) => `DELETE FROM ${into} WHERE (${columns.map(quote).join(", ")}) IN (SELECT ${values.join(", ")} FROM ${name} b${each.join("")} WHERE ${doomed("b", before)})`;
2130
+ }), (before) => `DELETE FROM ${name} WHERE ${doomed(name, before)}`];
2140
2131
  if (dialect === "mysql") return [...entries.map((index) => (before) => `DELETE e FROM ${index} e JOIN (${oldest(before)}) d ON ${keyOf("e", "d")}`), (before) => `DELETE FROM ${name} WHERE ${at} <= ${before()} ORDER BY ${order.join(", ")} LIMIT ${limit}`];
2141
2132
  return [...entries.map((index) => (before) => `DELETE FROM ${index} WHERE EXISTS (SELECT * FROM ${name} b WHERE ${keyOf("b", index)} AND ${doomed("b", before)})`), (before) => `DELETE FROM ${name} WHERE ${doomed(name, before)}`];
2142
2133
  };
@@ -2294,7 +2285,11 @@ const releases = defineTable({
2294
2285
  }
2295
2286
  },
2296
2287
  created_at_ms: { type: "integer" },
2297
- updated_at_ms: { type: "integer" }
2288
+ updated_at_ms: { type: "integer" },
2289
+ label: {
2290
+ type: "integer",
2291
+ required: false
2292
+ }
2298
2293
  }, {
2299
2294
  key: ["id"],
2300
2295
  indexes: {
@@ -2327,9 +2322,45 @@ const releases = defineTable({
2327
2322
  all: {
2328
2323
  eq: [],
2329
2324
  sort: ["id"]
2325
+ },
2326
+ scopes: {
2327
+ eq: [],
2328
+ sort: ["scope_key"]
2329
+ },
2330
+ byLabel: {
2331
+ eq: [
2332
+ "channel_id",
2333
+ "platform",
2334
+ "label"
2335
+ ],
2336
+ sort: [],
2337
+ unique: true
2330
2338
  }
2331
2339
  }
2332
2340
  });
2341
+ const LATE_INDEXES = [{
2342
+ table: "releases",
2343
+ index: "scopes"
2344
+ }];
2345
+ const LATE_COLUMNS = [{
2346
+ table: "releases",
2347
+ column: "label"
2348
+ }];
2349
+ const labelSequences = defineTable({
2350
+ id: {
2351
+ type: "string",
2352
+ maxLength: 1440,
2353
+ ascii: true
2354
+ },
2355
+ last_label: { type: "integer" },
2356
+ is_filled: { type: "boolean" }
2357
+ }, {
2358
+ key: ["id"],
2359
+ indexes: { all: {
2360
+ eq: [],
2361
+ sort: ["id"]
2362
+ } }
2363
+ });
2333
2364
  const releaseCatalogs = defineTable({
2334
2365
  scope_key: {
2335
2366
  type: "string",
@@ -2470,9 +2501,32 @@ const nativeBuilds = defineTable({
2470
2501
  type: "string",
2471
2502
  maxLength: 255,
2472
2503
  required: false
2504
+ },
2505
+ is_store_build: { type: "boolean" },
2506
+ is_sandbox: { type: "boolean" },
2507
+ sandbox_url_scheme: {
2508
+ type: "string",
2509
+ maxLength: 255,
2510
+ ascii: true,
2511
+ required: false
2512
+ },
2513
+ export_method: {
2514
+ type: "string",
2515
+ maxLength: 16,
2516
+ required: false
2517
+ },
2518
+ native_app_version: {
2519
+ type: "string",
2520
+ required: false
2473
2521
  }
2474
2522
  }, {
2475
2523
  key: ["id"],
2524
+ derived: { store_build_scope_key: {
2525
+ type: "string",
2526
+ maxLength: 2048,
2527
+ ascii: true,
2528
+ compute: (row) => row.is_store_build ? row.scope_key : null
2529
+ } },
2476
2530
  indexes: {
2477
2531
  byScope: {
2478
2532
  eq: ["scope_key"],
@@ -2482,6 +2536,15 @@ const nativeBuilds = defineTable({
2482
2536
  eq: ["scope_key", "build_key"],
2483
2537
  sort: ["id"]
2484
2538
  },
2539
+ byScopeKind: {
2540
+ eq: ["scope_key", "artifact_kind"],
2541
+ sort: ["id"]
2542
+ },
2543
+ byStoreBuild: {
2544
+ eq: ["store_build_scope_key"],
2545
+ sort: [],
2546
+ unique: true
2547
+ },
2485
2548
  byChannel: {
2486
2549
  eq: ["channel_id"],
2487
2550
  sort: ["id"],
@@ -2493,6 +2556,96 @@ const nativeBuilds = defineTable({
2493
2556
  }
2494
2557
  }
2495
2558
  });
2559
+ const iosDevices = defineTable({
2560
+ id: {
2561
+ type: "string",
2562
+ maxLength: 36
2563
+ },
2564
+ udid: {
2565
+ type: "string",
2566
+ maxLength: 40,
2567
+ ascii: true,
2568
+ unique: true
2569
+ },
2570
+ name: {
2571
+ type: "string",
2572
+ maxLength: 100
2573
+ },
2574
+ status: {
2575
+ type: "string",
2576
+ maxLength: 16
2577
+ },
2578
+ requested_by: {
2579
+ type: "string",
2580
+ maxLength: 320,
2581
+ required: false
2582
+ },
2583
+ created_at_ms: { type: "integer" },
2584
+ approved_by: {
2585
+ type: "string",
2586
+ maxLength: 320,
2587
+ required: false
2588
+ },
2589
+ approved_at_ms: {
2590
+ type: "integer",
2591
+ required: false
2592
+ },
2593
+ registered_at_ms: {
2594
+ type: "integer",
2595
+ required: false
2596
+ },
2597
+ apple_issuer_id: {
2598
+ type: "string",
2599
+ maxLength: 64,
2600
+ ascii: true,
2601
+ required: false
2602
+ },
2603
+ apple_error: {
2604
+ type: "string",
2605
+ maxLength: 512,
2606
+ required: false
2607
+ },
2608
+ build_id: {
2609
+ type: "string",
2610
+ maxLength: 36,
2611
+ required: false
2612
+ }
2613
+ }, {
2614
+ key: ["id"],
2615
+ indexes: {
2616
+ byStatus: {
2617
+ eq: ["status"],
2618
+ sort: ["id"]
2619
+ },
2620
+ byRegistration: {
2621
+ eq: [],
2622
+ sort: ["registered_at_ms"]
2623
+ },
2624
+ all: {
2625
+ eq: [],
2626
+ sort: ["id"]
2627
+ }
2628
+ }
2629
+ });
2630
+ const iosDeviceAccount = defineTable({
2631
+ id: {
2632
+ type: "string",
2633
+ maxLength: 16,
2634
+ ascii: true
2635
+ },
2636
+ apple_issuer_id: {
2637
+ type: "string",
2638
+ maxLength: 64,
2639
+ ascii: true
2640
+ },
2641
+ claimed_at_ms: { type: "integer" }
2642
+ }, {
2643
+ key: ["id"],
2644
+ indexes: { all: {
2645
+ eq: [],
2646
+ sort: ["id"]
2647
+ } }
2648
+ });
2496
2649
  const coreModule = {
2497
2650
  id: "core",
2498
2651
  schema: {
@@ -2512,7 +2665,10 @@ const coreModule = {
2512
2665
  sort: []
2513
2666
  } }
2514
2667
  }),
2515
- native_builds: nativeBuilds
2668
+ native_builds: nativeBuilds,
2669
+ ios_devices: iosDevices,
2670
+ ios_device_account: iosDeviceAccount,
2671
+ label_sequences: labelSequences
2516
2672
  }
2517
2673
  };
2518
2674
  //#endregion
@@ -2523,6 +2679,58 @@ const getEmptyMigrationResult = () => ({
2523
2679
  getSQL: () => ""
2524
2680
  });
2525
2681
  //#endregion
2682
+ //#region ../plugin-core/dist/engine/db/sqlSchemaState.mjs
2683
+ const POSTGRES_NAME_BYTES = 63;
2684
+ const postgresName = (name) => {
2685
+ const encoder = new TextEncoder();
2686
+ let bytes = 0;
2687
+ let cut = "";
2688
+ for (const character of name) {
2689
+ bytes += encoder.encode(character).length;
2690
+ if (bytes > POSTGRES_NAME_BYTES) break;
2691
+ cut += character;
2692
+ }
2693
+ return cut;
2694
+ };
2695
+ const fold = (dialect, name) => dialect === "mysql" ? String(name).toLowerCase() : dialect === "postgresql" ? postgresName(String(name)) : String(name);
2696
+ const CATALOG = {
2697
+ postgresql: {
2698
+ tables: "SELECT c.relname AS t FROM pg_class c WHERE c.relkind IN ('r', 'p') AND pg_table_is_visible(c.oid)",
2699
+ indexes: "SELECT t.relname AS t, c.relname AS i FROM pg_index x JOIN pg_class c ON c.oid = x.indexrelid JOIN pg_class t ON t.oid = x.indrelid WHERE pg_table_is_visible(t.oid)",
2700
+ columns: "SELECT c.relname AS t, a.attname AS c FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid WHERE c.relkind IN ('r', 'p') AND a.attnum > 0 AND NOT a.attisdropped AND pg_table_is_visible(c.oid)"
2701
+ },
2702
+ mysql: {
2703
+ tables: "SELECT TABLE_NAME AS t FROM information_schema.tables WHERE TABLE_SCHEMA = DATABASE()",
2704
+ indexes: "SELECT DISTINCT TABLE_NAME AS t, INDEX_NAME AS i FROM information_schema.statistics WHERE TABLE_SCHEMA = DATABASE()",
2705
+ columns: "SELECT TABLE_NAME AS t, COLUMN_NAME AS c FROM information_schema.columns WHERE TABLE_SCHEMA = DATABASE()"
2706
+ },
2707
+ sqlite: {
2708
+ tables: "SELECT name AS t FROM sqlite_master WHERE type = 'table'",
2709
+ indexes: "SELECT tbl_name AS t, name AS i FROM sqlite_master WHERE type = 'index'",
2710
+ columns: "SELECT m.name AS t, p.name AS c FROM sqlite_master m JOIN pragma_table_info(m.name) p WHERE m.type = 'table'"
2711
+ }
2712
+ };
2713
+ const readSqlSchemaState = async (executor) => {
2714
+ const { dialect } = executor;
2715
+ const read = (sql) => executor.execute({
2716
+ sql,
2717
+ params: []
2718
+ });
2719
+ const [tables, indexes, columns] = await Promise.all([
2720
+ read(CATALOG[dialect].tables),
2721
+ read(CATALOG[dialect].indexes),
2722
+ read(CATALOG[dialect].columns)
2723
+ ]);
2724
+ const columnNames = new Set(columns.rows.map(({ t, c }) => JSON.stringify([fold(dialect, t), fold(dialect, c)])));
2725
+ const tableNames = new Set(tables.rows.map(({ t }) => fold(dialect, t)));
2726
+ const indexNames = new Set(indexes.rows.map(({ t, i }) => JSON.stringify([fold(dialect, t), fold(dialect, i)])));
2727
+ return {
2728
+ hasTable: (table) => tableNames.has(fold(dialect, table)),
2729
+ hasIndex: (table, index) => indexNames.has(JSON.stringify([fold(dialect, table), fold(dialect, index)])),
2730
+ hasColumn: (table, column) => columnNames.has(JSON.stringify([fold(dialect, table), fold(dialect, column)]))
2731
+ };
2732
+ };
2733
+ //#endregion
2526
2734
  //#region ../plugin-core/dist/engine/db/settingsMigrator.mjs
2527
2735
  const storedSchemaVersion = (stored) => {
2528
2736
  const version = stored?.get("schema.core") ?? stored?.get("version");
@@ -2533,6 +2741,103 @@ const refuseV0Database = (adapterName, stored) => {
2533
2741
  if (typeof version !== "string" || stored.has("schema.engine")) return;
2534
2742
  throw new HotUpdaterSchemaMigrationRequiredError(adapterName, version);
2535
2743
  };
2744
+ const compareVersions = (left, right) => {
2745
+ const parse = (version) => /^\d+(?:\.\d+)*$/u.test(version) ? version.split(".").map(Number) : [NaN];
2746
+ const [a, b] = [parse(left), parse(right)];
2747
+ if ([...a, ...b].some(Number.isNaN)) return NaN;
2748
+ for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
2749
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
2750
+ if (difference !== 0) return difference;
2751
+ }
2752
+ return 0;
2753
+ };
2754
+ const DEFAULT_ORDERED_SETTINGS = ["schema.core"];
2755
+ const refuseNewerSchema = (adapterName, stored, settings, ordered = DEFAULT_ORDERED_SETTINGS) => {
2756
+ const newer = ordered.flatMap((key) => {
2757
+ const found = stored.get(key);
2758
+ const expected = settings[key];
2759
+ return typeof found === "string" && expected !== void 0 && compareVersions(found, expected) > 0 ? [{
2760
+ key,
2761
+ found,
2762
+ expected
2763
+ }] : [];
2764
+ });
2765
+ const core = newer.find(({ key }) => key === "schema.core");
2766
+ if (core === void 0) return;
2767
+ 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.`);
2768
+ };
2769
+ const settingsOperation = (stored, changed) => ({
2770
+ type: "custom",
2771
+ description: `Record ${changed.map(([key, value]) => {
2772
+ const found = stored.get(key);
2773
+ return typeof found === "string" ? `${key} ${found} → ${value}` : `${key} ${value}`;
2774
+ }).join(", ")}`
2775
+ });
2776
+ //#endregion
2777
+ //#region ../plugin-core/dist/engine/db/schemaSettings.mjs
2778
+ const storedSettings = async (adapter, keys) => {
2779
+ const rows = await readSettings(adapter, keys);
2780
+ return new Map(keys.map((key, position) => [key, rows[position] ?? null]));
2781
+ };
2782
+ const writeSchemaSettings = async (adapter, adapterName, settings, ordered) => {
2783
+ const stored = await storedSettings(adapter, Object.keys(settings));
2784
+ refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
2785
+ const ops = Object.entries(settings).flatMap(([key, value]) => {
2786
+ const row = stored.get(key);
2787
+ if (row === null || row === void 0) return [{
2788
+ type: "insert",
2789
+ table: SETTINGS_TABLE,
2790
+ row: {
2791
+ key,
2792
+ value,
2793
+ _v: 0
2794
+ }
2795
+ }];
2796
+ if (row.value === value) return [];
2797
+ return [{
2798
+ type: "patch",
2799
+ table: SETTINGS_TABLE,
2800
+ key: [key],
2801
+ set: { value },
2802
+ guard: { v: Number(row._v) },
2803
+ previous: row
2804
+ }];
2805
+ });
2806
+ if (ops.length === 0) return;
2807
+ if (!(await adapter.write(ops)).ok) throw new Error(`${adapterName}: the schema settings changed during the migration; run it again.`);
2808
+ };
2809
+ const fillLateIndexes = async (adapter, tables, { dryRun = false } = {}) => {
2810
+ const fillIndex = adapter.migrations?.fillIndex;
2811
+ if (fillIndex === void 0) return [];
2812
+ const lacking = [];
2813
+ for (const { table: name, index } of LATE_INDEXES) {
2814
+ const table = tables.find((candidate) => candidate.name === name);
2815
+ if (table === void 0) continue;
2816
+ if (await fillIndex(table, index, { dryRun }) > 0) lacking.push(`${name}.${index}`);
2817
+ }
2818
+ return lacking;
2819
+ };
2820
+ const addLateColumns = async (adapter, tables, { dryRun = false } = {}) => {
2821
+ const addColumns = adapter.migrations?.addColumns;
2822
+ if (addColumns === void 0) return [];
2823
+ const lacking = [];
2824
+ for (const table of tables) {
2825
+ const columns = LATE_COLUMNS.filter(({ table: name }) => name === table.name).map(({ column }) => column);
2826
+ if (columns.length === 0) continue;
2827
+ const added = await addColumns(table, columns, { dryRun });
2828
+ lacking.push(...added.map((column) => `${table.name}.${column}`));
2829
+ }
2830
+ return lacking;
2831
+ };
2832
+ const migrateSchema = async (adapter, adapterName, tables, settings, ordered) => {
2833
+ if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
2834
+ const stored = await storedSettings(adapter, Object.keys(settings)).catch(() => void 0);
2835
+ if (stored !== void 0) refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
2836
+ await addLateColumns(adapter, tables);
2837
+ await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
2838
+ await fillLateIndexes(adapter, tables);
2839
+ await writeSchemaSettings(adapter, adapterName, settings, ordered);
2840
+ };
2536
2841
  //#endregion
2537
2842
  //#region ../plugin-core/dist/engine/database/cursor.mjs
2538
2843
  const encoder$1 = new TextEncoder();
@@ -2677,18 +2982,15 @@ const LOG_TABLES = [
2677
2982
  const LEASE_TABLE = "aggregate_lease";
2678
2983
  const LEASE = { id: "compaction" };
2679
2984
  const LEASE_MS = 3e4;
2680
- const WINDOW_MS$1 = {
2681
- log: 6e4,
2682
- memory: 15e3
2683
- };
2985
+ const WINDOW_MS$1 = 6e4;
2684
2986
  const LOG_PAGE = 200;
2987
+ const SKIP_AFTER_MS = 3e5;
2685
2988
  const GROUPS = {
2686
2989
  commit: 1,
2687
2990
  read: 8,
2688
2991
  flush: 256
2689
2992
  };
2690
2993
  const ATTEMPTS = 5;
2691
- const MAX_BUFFERED = 1e4;
2692
2994
  const log = defineTable({
2693
2995
  id: {
2694
2996
  type: "string",
@@ -2789,18 +3091,30 @@ const rewrite$1 = (change, key, current) => {
2789
3091
  previous: current
2790
3092
  };
2791
3093
  };
2792
- const compile = async (adapter, changes, shard) => {
2793
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
3094
+ const rowId = (model, key) => JSON.stringify([model.table.name, key]);
3095
+ const keysOf = (changes) => changes.map(({ key }) => [...key.slice(0, -1), 0]);
3096
+ const readCurrent = async (adapter, changes) => {
3097
+ const keys = keysOf(changes);
2794
3098
  const reads = /* @__PURE__ */ new Map();
2795
3099
  changes.forEach((change, at) => {
2796
- if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
3100
+ if (!rewrites(change)) return;
3101
+ const wanted = reads.get(change.model) ?? /* @__PURE__ */ new Map();
3102
+ wanted.set(rowId(change.model, keys[at]), keys[at]);
3103
+ reads.set(change.model, wanted);
2797
3104
  });
2798
3105
  const current = /* @__PURE__ */ new Map();
2799
- await Promise.all([...reads].map(async ([model, positions]) => {
2800
- const rows = await adapter.get(model.table, positions.map((at) => keys[at]));
2801
- positions.forEach((at, index) => current.set(at, rows[index] ?? null));
3106
+ await Promise.all([...reads].map(async ([model, wanted]) => {
3107
+ const keys = [...wanted.values()];
3108
+ const rows = await adapter.get(model.table, keys);
3109
+ keys.forEach((key, at) => {
3110
+ current.set(rowId(model, key), rows[at] ?? null);
3111
+ });
2802
3112
  }));
2803
- return changes.map((change, at) => current.has(at) ? rewrite$1(change, keys[at], current.get(at)) : increment(change, keys[at]));
3113
+ return current;
3114
+ };
3115
+ const build = (changes, current) => {
3116
+ const keys = keysOf(changes);
3117
+ return changes.map((change, at) => rewrites(change) ? rewrite$1(change, keys[at], current.get(rowId(change.model, keys[at])) ?? null) : increment(change, keys[at]));
2804
3118
  };
2805
3119
  const isOp = (op) => op !== void 0;
2806
3120
  const sleep = (attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random()));
@@ -2836,7 +3150,7 @@ const encode = async (changes) => {
2836
3150
  const zipped = await deflate(json);
2837
3151
  return zipped !== void 0 && zipped.length < json.length ? `z${zipped}` : json;
2838
3152
  };
2839
- const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS$1[mode] }, now }) => {
3153
+ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs = WINDOW_MS$1 }, now }) => {
2840
3154
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
2841
3155
  const holder = crypto.randomUUID().replaceAll("-", "");
2842
3156
  const table = (name) => schema.models.get(name).table;
@@ -2863,64 +3177,12 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
2863
3177
  }
2864
3178
  return changes;
2865
3179
  };
2866
- const apply = async (changes, shard) => {
2867
- let rest = changes;
2868
- let ops = [];
2869
- let read = true;
2870
- for (let failures = 0; rest.length > 0 && failures < ATTEMPTS;) try {
2871
- if (read) ops = await compile(adapter, rest, shard);
2872
- let size = rest.length;
2873
- const chunk = () => ops.slice(0, size).filter(isOp);
2874
- while (size > 1 && !adapter.fits(chunk())) size = Math.ceil(size / 2);
2875
- let result = { ok: true };
2876
- if (chunk().length > 0) result = await adapter.write(chunk()).catch((error) => {
2877
- warn("flush")(error);
2878
- return { ok: true };
2879
- });
2880
- read = !result.ok && !("retry" in result);
2881
- if (result.ok) {
2882
- rest = rest.slice(size);
2883
- ops = ops.slice(size);
2884
- failures = 0;
2885
- } else {
2886
- failures += 1;
2887
- if (!read) await sleep(failures);
2888
- }
2889
- } catch (error) {
2890
- warn("flush")(error);
2891
- return rest;
2892
- }
2893
- return rest;
2894
- };
2895
- let buffer = /* @__PURE__ */ new Map();
2896
- let timer;
2897
- let flushing;
2898
- const shards = /* @__PURE__ */ new Map();
2899
- const processShard = (model) => {
2900
- if (!shards.has(model)) shards.set(model, Math.floor(Math.random() * shapeOf(model).shards));
2901
- return shards.get(model);
2902
- };
2903
- const schedule = () => {
2904
- if (timer !== void 0 || buffer.size === 0) return;
2905
- timer = setTimeout(() => {
2906
- timer = void 0;
2907
- flushBuffer();
2908
- }, windowMs);
2909
- timer.unref?.();
2910
- };
2911
- const flushBuffer = () => flushing ??= (async () => {
2912
- clearTimeout(timer);
2913
- timer = void 0;
2914
- const pending = [...buffer.values()];
2915
- buffer = /* @__PURE__ */ new Map();
2916
- mergeAll(buffer, await apply(pending, processShard));
2917
- })().catch(warn("flush")).finally(() => {
2918
- flushing = void 0;
2919
- schedule();
2920
- });
2921
3180
  let nextDue = 0;
2922
3181
  let compacting;
2923
3182
  const known = /* @__PURE__ */ new Map();
3183
+ const skipped = LOG_TABLES.map(() => void 0);
3184
+ const past = (shard) => skipped[shard] === void 0 ? {} : { range: { gt: skipped[shard] } };
3185
+ const stampOf = (id) => Number.parseInt(id.slice(0, 9), 36);
2924
3186
  const idOf = (shard, id) => JSON.stringify([shard, id]);
2925
3187
  const leaseOp = (held, set) => {
2926
3188
  const next = {
@@ -3024,14 +3286,22 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3024
3286
  logs: (await Promise.all(LOG_TABLES.map(async (name, shard) => {
3025
3287
  const page = await engine.reads.findMany(name, {
3026
3288
  index: "oldest",
3027
- limit: LOG_PAGE
3289
+ limit: LOG_PAGE,
3290
+ ...past(shard)
3028
3291
  });
3029
3292
  more ||= page.next !== void 0;
3030
- return (await Promise.all(page.rows.map(async (row) => ({
3293
+ const decoded = await Promise.all(page.rows.map(async (row) => ({
3031
3294
  shard,
3032
3295
  row,
3033
3296
  changes: await decode(String(row.changes))
3034
- })))).flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
3297
+ })));
3298
+ const settled = now() - SKIP_AFTER_MS;
3299
+ for (const { row, changes } of decoded) {
3300
+ const id = String(row.id);
3301
+ if (changes !== void 0 || stampOf(id) >= settled) break;
3302
+ skipped[shard] = id;
3303
+ }
3304
+ return decoded.flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
3035
3305
  ...entry,
3036
3306
  changes
3037
3307
  }]);
@@ -3039,14 +3309,15 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3039
3309
  more
3040
3310
  };
3041
3311
  };
3042
- const rowsFor = async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp);
3043
3312
  const applyGroup = async (held, logs) => {
3313
+ const current = await readCurrent(adapter, logs.flatMap((entry) => [...entry.changes.values()]));
3314
+ const rowsFor = (changes) => build(changes, current).filter(isOp);
3044
3315
  for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
3045
3316
  const batch = logs.slice(0, count);
3046
3317
  const changes = mergeAll(/* @__PURE__ */ new Map(), batch.flatMap((entry) => [...entry.changes.values()]));
3047
3318
  const applied = batch.map(({ shard, row }) => [shard, row.id]);
3048
3319
  const lease = leaseOp(held, { applied: JSON.stringify(applied) });
3049
- const ops = [...await rowsFor([...changes.values()]), lease.op];
3320
+ const ops = [...rowsFor([...changes.values()]), lease.op];
3050
3321
  if (!adapter.fits(ops)) continue;
3051
3322
  for (const { shard, row } of batch) known.set(idOf(shard, row.id), row);
3052
3323
  return await commit(ops) ? {
@@ -3068,7 +3339,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3068
3339
  };
3069
3340
  const lease = leaseOp(held, {});
3070
3341
  const ops = [
3071
- ...await rowsFor(entries.slice(0, take)),
3342
+ ...rowsFor(entries.slice(0, take)),
3072
3343
  kept,
3073
3344
  lease.op
3074
3345
  ];
@@ -3084,11 +3355,12 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3084
3355
  if (held === void 0) return;
3085
3356
  let pending = true;
3086
3357
  let clear = false;
3358
+ let carried;
3087
3359
  try {
3088
3360
  for (let group = 0;; group += 1) {
3089
3361
  clear = await deleteApplied(held);
3090
3362
  if (!clear || !pending || group === groups) break;
3091
- const { logs, more } = await readLogs();
3363
+ const { logs, more } = carried ?? await readLogs();
3092
3364
  if (logs.length === 0) {
3093
3365
  pending = false;
3094
3366
  break;
@@ -3096,6 +3368,11 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3096
3368
  const applied = await applyGroup(held, logs);
3097
3369
  if (applied === void 0) break;
3098
3370
  [held, clear] = [applied.held, false];
3371
+ const rest = applied.count === 0 ? [] : logs.slice(applied.count);
3372
+ carried = rest.length > 0 ? {
3373
+ logs: rest,
3374
+ more
3375
+ } : void 0;
3099
3376
  pending = more || applied.count < logs.length;
3100
3377
  }
3101
3378
  } finally {
@@ -3113,25 +3390,13 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3113
3390
  compacting = void 0;
3114
3391
  });
3115
3392
  let checking;
3116
- const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name) => engine.reads.findMany(name, {
3393
+ const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name, shard) => engine.reads.findMany(name, {
3117
3394
  index: "oldest",
3118
- limit: 1
3395
+ limit: 1,
3396
+ ...past(shard)
3119
3397
  }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
3120
3398
  checking = void 0;
3121
3399
  });
3122
- const committed = async (changes) => {
3123
- if (mode === "log") {
3124
- if (now() >= nextDue) await compact(false, GROUPS.commit);
3125
- return;
3126
- }
3127
- mergeAll(buffer, changes.values());
3128
- schedule();
3129
- if (buffer.size >= MAX_BUFFERED) await flushBuffer();
3130
- };
3131
- const flush = async () => {
3132
- await flushBuffer();
3133
- if (mode === "log" && await hasPending()) await compact(true, GROUPS.flush);
3134
- };
3135
3400
  return {
3136
3401
  async transaction(fn) {
3137
3402
  let changes = /* @__PURE__ */ new Map();
@@ -3157,7 +3422,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3157
3422
  aggregate
3158
3423
  });
3159
3424
  if (failure) throw failure.error;
3160
- if (mode === "log" && attempt.size > 0) {
3425
+ if (attempt.size > 0) {
3161
3426
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
3162
3427
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
3163
3428
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -3171,24 +3436,18 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3171
3436
  open = false;
3172
3437
  }
3173
3438
  });
3174
- if (changes.size > 0) await committed(changes);
3439
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
3175
3440
  return result;
3176
3441
  },
3177
3442
  async beforeRead(name) {
3178
3443
  if (!isBatched(schema.models.get(name))) return;
3179
- if (buffer.size > 0 || flushing !== void 0) await flushBuffer();
3180
- if (mode === "log") {
3181
- if (await hasPending().catch((error) => {
3182
- warn("read")(error);
3183
- return false;
3184
- })) await compact(true, GROUPS.read);
3185
- }
3444
+ if (await hasPending().catch((error) => {
3445
+ warn("read")(error);
3446
+ return false;
3447
+ })) await compact(true, GROUPS.read);
3186
3448
  },
3187
- flush,
3188
- async dispose() {
3189
- clearTimeout(timer);
3190
- timer = void 0;
3191
- await flush();
3449
+ async flush() {
3450
+ if (await hasPending()) await compact(true, GROUPS.flush);
3192
3451
  }
3193
3452
  };
3194
3453
  };
@@ -3307,7 +3566,8 @@ const fieldProblems = (definition, add) => {
3307
3566
  else if (field.required === false) add(`key field "${name}" is nullable`);
3308
3567
  else if (field.type === "json") add(`key field "${name}" is json`);
3309
3568
  }
3310
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
3569
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
3570
+ for (const [name, { type, maxLength, ascii }] of bounded) {
3311
3571
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
3312
3572
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
3313
3573
  }
@@ -3419,11 +3679,13 @@ const resolveSchema = (modules) => {
3419
3679
  ...maxLength === void 0 ? {} : { maxLength },
3420
3680
  ...ascii ? { ascii } : {}
3421
3681
  }));
3422
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
3682
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
3423
3683
  name: field,
3424
3684
  type,
3425
3685
  nullable: true,
3426
- ...multi ? { multi } : {}
3686
+ ...multi ? { multi } : {},
3687
+ ...maxLength === void 0 ? {} : { maxLength },
3688
+ ...ascii ? { ascii } : {}
3427
3689
  });
3428
3690
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
3429
3691
  name: metric,
@@ -3460,22 +3722,49 @@ const createEngineMigrator = (options) => {
3460
3722
  const makeResult = async (migrate = {}) => {
3461
3723
  const stored = await options.readSettings();
3462
3724
  refuseV0Database(options.adapterName, stored);
3463
- if (Object.entries(options.settings).every(([key, value]) => stored.get(key) === value)) return getEmptyMigrationResult();
3725
+ refuseNewerSchema(options.adapterName, stored, options.settings, options.ordered);
3726
+ const changed = Object.entries(options.settings).filter(([key, value]) => stored.get(key) !== value);
3727
+ if (changed.length === 0) {
3728
+ const columns = await addLateColumns(options.adapter, options.schema.tables, { dryRun: true });
3729
+ const lacking = await fillLateIndexes(options.adapter, options.schema.tables, { dryRun: true });
3730
+ if (columns.length === 0 && lacking.length === 0) return getEmptyMigrationResult();
3731
+ return {
3732
+ operations: [
3733
+ ...columns.map((column) => ({
3734
+ type: "custom",
3735
+ description: `Add column: ${column}`
3736
+ })),
3737
+ ...columns.length === 0 ? [] : [{
3738
+ type: "custom",
3739
+ description: "Create the tables and indexes the database lacks"
3740
+ }],
3741
+ ...lacking.length === 0 ? [] : [{
3742
+ type: "custom",
3743
+ description: `Write the index items rows lack: ${lacking.join(", ")}`
3744
+ }]
3745
+ ],
3746
+ execute: async () => {
3747
+ if (columns.length > 0) {
3748
+ await addLateColumns(options.adapter, options.schema.tables);
3749
+ await options.adapter.migrations.apply([...options.schema.tables, SETTINGS_TABLE]);
3750
+ }
3751
+ await fillLateIndexes(options.adapter, options.schema.tables);
3752
+ }
3753
+ };
3754
+ }
3464
3755
  return {
3465
- operations: [...options.schema.tables.map((table) => ({
3466
- type: "create-table",
3467
- value: {
3468
- ormName: table.name,
3469
- columns: Object.fromEntries(table.columns.map((column) => [column.name, {
3470
- ormName: column.name,
3471
- type: column.type
3472
- }]))
3473
- }
3474
- })), ...migrate.updateSettings === false ? [] : [{
3475
- type: "custom",
3476
- description: `Write the schema settings: ${Object.keys(options.settings).join(", ")}`
3477
- }]],
3478
- execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings)
3756
+ operations: [
3757
+ ...(await addLateColumns(options.adapter, options.schema.tables, { dryRun: true }).catch(() => [])).map((column) => ({
3758
+ type: "custom",
3759
+ description: `Add column: ${column}`
3760
+ })),
3761
+ {
3762
+ type: "custom",
3763
+ description: "Create the tables and indexes the database lacks"
3764
+ },
3765
+ ...migrate.updateSettings === false ? [] : [settingsOperation(stored, changed)]
3766
+ ],
3767
+ execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings, options.ordered)
3479
3768
  };
3480
3769
  };
3481
3770
  return {
@@ -3503,7 +3792,8 @@ const coreSettings = {
3503
3792
  };
3504
3793
  const coreTarget = {
3505
3794
  schema: coreSchema,
3506
- settings: coreSettings
3795
+ settings: coreSettings,
3796
+ ordered: ["schema.core"]
3507
3797
  };
3508
3798
  resolveSchema([aggregateBatchingModule]).tables;
3509
3799
  const pluginSettings = (plugins) => Object.fromEntries(plugins.map(({ id, schemaVersion }) => [`schema.${id}`, schemaVersion]));
@@ -3514,11 +3804,12 @@ const pluginModule = ({ id, schema, namespace }) => ({
3514
3804
  });
3515
3805
  const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBatching, retry, readSettings: readStored }) => {
3516
3806
  const fenced = withSchemaFence(adapter, name, coreSettings);
3517
- const createMigrator = ({ schema, settings } = coreTarget) => createEngineMigrator({
3807
+ const createMigrator = ({ schema, settings, ordered } = coreTarget) => createEngineMigrator({
3518
3808
  adapterName: name,
3519
3809
  adapter,
3520
3810
  schema,
3521
3811
  settings,
3812
+ ordered,
3522
3813
  readSettings: readStored ?? (async () => {
3523
3814
  const rows = await readSettings(adapter, Object.keys(settings)).catch((error) => {
3524
3815
  if (isMissingSchemaError(error)) return [];
@@ -3541,6 +3832,11 @@ const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBa
3541
3832
  //#region ../plugin-core/dist/engine/database/engineTransaction.mjs
3542
3833
  var StaleReadError = class extends Error {};
3543
3834
  const idOf = (table, key) => JSON.stringify([table, key]);
3835
+ const versionsOf = (ops) => JSON.stringify(ops.map((op) => op.type === "insert" ? [op.table.name, rowKey(op.table, op.row)] : [
3836
+ op.table.name,
3837
+ op.key,
3838
+ "guard" in op ? op.guard?.v : void 0
3839
+ ]));
3544
3840
  const versionOf = (row) => Number(row["_v"]);
3545
3841
  const isKeyed = (value) => value !== null && value !== void 0;
3546
3842
  const misuse = (table, message) => new DatabaseTransactionError(`${table}: ${message}`);
@@ -3872,7 +4168,9 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
3872
4168
  assertOutsideTransaction();
3873
4169
  let run;
3874
4170
  let negative;
3875
- for (let round = 0; round < attempts; round += 1) {
4171
+ let failures = 0;
4172
+ let lost;
4173
+ for (let round = 0;; round += 1) {
3876
4174
  const delay = round && Math.min(maxDelayMs, baseDelayMs * 2 ** (round - 1));
3877
4175
  if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay / 2 + Math.random() * (delay / 2)));
3878
4176
  run ??= await attempt(fn).catch((error) => {
@@ -3881,6 +4179,8 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
3881
4179
  });
3882
4180
  if (run === void 0) {
3883
4181
  onRetry?.("rerun", round + 1);
4182
+ lost = void 0;
4183
+ if ((failures += 1) >= attempts) break;
3884
4184
  continue;
3885
4185
  }
3886
4186
  let aggregates;
@@ -3891,8 +4191,14 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
3891
4191
  negative = error;
3892
4192
  onRetry?.("rerun", round + 1);
3893
4193
  run = void 0;
4194
+ lost = void 0;
4195
+ if ((failures += 1) >= attempts) break;
3894
4196
  continue;
3895
4197
  }
4198
+ const versions = versionsOf(aggregates);
4199
+ if (lost !== void 0 && versions !== lost) failures -= 1;
4200
+ lost = void 0;
4201
+ if (failures >= attempts) break;
3896
4202
  const ops = [...run.ops, ...aggregates];
3897
4203
  if (ops.length <= 1 && ops.every(({ type }) => type === "check")) return run.result;
3898
4204
  if (!adapter.fits(ops)) throw new DatabaseConstraintError("too_large", ops[0].table.name);
@@ -3906,12 +4212,16 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
3906
4212
  const failed = "failedOp" in outcome ? outcome.failedOp : void 0;
3907
4213
  if (failed === void 0 || failed >= run.ops.length) {
3908
4214
  onRetry?.("resend", round + 1);
4215
+ failures += 1;
4216
+ if (failed !== void 0) lost = versions;
4217
+ else if (failures >= attempts) break;
3909
4218
  continue;
3910
4219
  }
3911
4220
  const reason = await classify(ops[failed], run.read);
3912
4221
  if (reason) throw new DatabaseConstraintError(reason, ops[failed].table.name);
3913
4222
  onRetry?.("rerun", round + 1);
3914
4223
  run = void 0;
4224
+ if ((failures += 1) >= attempts) break;
3915
4225
  }
3916
4226
  throw negative ?? new DatabaseConflictError(`The transaction conflicted ${attempts} times.`);
3917
4227
  } };
@@ -4147,9 +4457,6 @@ const createDatabaseEngine = ({ batching, now = Date.now, meter, ...options }) =
4147
4457
  flush: async () => {
4148
4458
  await batches?.flush();
4149
4459
  },
4150
- dispose: async () => {
4151
- await batches?.dispose();
4152
- },
4153
4460
  database(module) {
4154
4461
  const name = (model) => module.namespace ? `${module.namespace}_${model}` : model;
4155
4462
  return {
@@ -4217,8 +4524,7 @@ const createEngine = (database, { plugins = [], now = Date.now } = {}) => {
4217
4524
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
4218
4525
  return engine.database(module);
4219
4526
  },
4220
- flush: () => engine.flush(),
4221
- dispose: () => engine.dispose()
4527
+ flush: () => engine.flush()
4222
4528
  };
4223
4529
  };
4224
4530
  //#endregion
@@ -4306,19 +4612,19 @@ const createSqlAdapter = ({ executor, tablePrefix = "", maxOps = 1e3, maxParams
4306
4612
  const where = (bind, key, v) => `${keyMatch(bind, table, key)}${v === void 0 ? "" : ` AND ${version} = ${bind(v)}`}${when ? ` AND ${when(bind)}` : ""}`;
4307
4613
  const insert = (bind, into, columns, values) => `INSERT INTO ${into} (${columns.map(quote).join(", ")}) ${when ? `SELECT ${values.join(", ")} WHERE ${when(bind)}` : `VALUES (${values.join(", ")})`}`;
4308
4614
  const insertRow = (bind, row) => insert(bind, name, table.columns.map((column) => column.name), table.columns.map((column) => bind(row[column.name], column)));
4309
- const entries = (key, row, changed) => table.indexes.flatMap((index) => {
4615
+ const entries = (key, row, changed, stale = true) => table.indexes.flatMap((index) => {
4310
4616
  const columns = [...index.eq, ...indexOrderColumns(table, index)];
4311
4617
  if (!isMultiIndex(table, index) || changed && !columns.some((column) => changed.includes(column))) return [];
4312
4618
  const into = tableOf(table, index);
4313
4619
  const found = row ? indexEntries(table, index, row) : [];
4314
4620
  const order = found.length > 0 ? indexOrderTuple(table, index, row) : [];
4315
- return [sql((bind) => `DELETE FROM ${into} WHERE ${where(bind, key)}`), ...found.map((eq) => sql((bind) => {
4621
+ return [...stale ? [sql((bind) => `DELETE FROM ${into} WHERE ${where(bind, key)}`)] : [], ...found.map((eq) => sql((bind) => {
4316
4622
  const values = [...eq, ...order].map((value) => bind(value));
4317
4623
  return insert(bind, into, columns, values);
4318
4624
  }))];
4319
4625
  });
4320
4626
  switch (op.type) {
4321
- case "insert": return [sql((bind) => insertRow(bind, op.row)), ...entries(rowKey(table, op.row), op.row)];
4627
+ case "insert": return [sql((bind) => insertRow(bind, op.row)), ...entries(rowKey(table, op.row), op.row, void 0, false)];
4322
4628
  case "patch": return [sql((bind) => {
4323
4629
  const set = Object.entries(op.set).map(([column, value]) => `${quote(column)} = ${bind(value, findPhysicalColumn(table, column))}`);
4324
4630
  return `UPDATE ${name} SET ${[...set, `${version} = ${version} + 1`].join(", ")} WHERE ${where(bind, op.key, op.guard.v)}`;
@@ -4460,14 +4766,32 @@ const createSqlAdapter = ({ executor, tablePrefix = "", maxOps = 1e3, maxParams
4460
4766
  return done;
4461
4767
  })).at(-1)?.changes ?? 0;
4462
4768
  },
4463
- migrations: { async apply(tables) {
4464
- const created = executor.batch && !tables.includes(WRITE_GUARD_TABLE) ? [...tables, WRITE_GUARD_TABLE] : tables;
4465
- const statements = createTableStatements(dialect, created, tablePrefix);
4466
- for (const text of statements) await executor.execute({
4467
- sql: text,
4468
- params: []
4469
- });
4470
- } }
4769
+ migrations: {
4770
+ async apply(tables) {
4771
+ const created = executor.batch && !tables.includes(WRITE_GUARD_TABLE) ? [...tables, WRITE_GUARD_TABLE] : tables;
4772
+ const statements = createTableStatements(dialect, created, tablePrefix);
4773
+ for (const text of statements) await executor.execute({
4774
+ sql: text,
4775
+ params: []
4776
+ });
4777
+ },
4778
+ async addColumns(table, columns, { dryRun = false } = {}) {
4779
+ const [shape] = sqlTableShapes(dialect, [table], tablePrefix);
4780
+ const state = await readSqlSchemaState(executor);
4781
+ if (shape === void 0 || !state.hasTable(shape.name)) return [];
4782
+ const missing = columns.filter((column) => !state.hasColumn(shape.name, column));
4783
+ if (dryRun) return missing;
4784
+ for (const name of missing) {
4785
+ const column = shape.columns.find((candidate) => candidate.name === name);
4786
+ if (column === void 0 || column.notNull) throw new Error(`${table.name}.${name} can't be added to an existing table: only an optional column can.`);
4787
+ await executor.execute({
4788
+ sql: `ALTER TABLE ${quoteSql(dialect, shape.name)} ADD COLUMN ${quoteSql(dialect, name)} ${column.type}`,
4789
+ params: []
4790
+ });
4791
+ }
4792
+ return missing;
4793
+ }
4794
+ }
4471
4795
  };
4472
4796
  };
4473
4797
  //#endregion
@@ -17698,7 +18022,7 @@ const postgres = (config) => {
17698
18022
  };
17699
18023
  //#endregion
17700
18024
  //#region ../../packages/server/dist/version.mjs
17701
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.5";
18025
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.51";
17702
18026
  //#endregion
17703
18027
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
17704
18028
  const createVersionRouteHandlers = (plugins = []) => {
@@ -17824,9 +18148,14 @@ const releaseCatalogScopeKeyOf = (input) => input.strategy === "APP_VERSION" ? c
17824
18148
  platform: input.platform,
17825
18149
  strategy: "FINGERPRINT"
17826
18150
  });
17827
- const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
17828
- 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;
17829
- const compiled = parseCompiledCatalog(row.payload, input.strategy);
18151
+ const parseReleaseCatalogRow = ({ payload, ...row }) => ({
18152
+ row,
18153
+ compiled: parseCompiledCatalog(payload, row.strategy)
18154
+ });
18155
+ const projectParsedReleaseCatalogRow = (parsed, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
18156
+ if (parsed === null) return null;
18157
+ const { row, compiled } = parsed;
18158
+ 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;
17830
18159
  const appVersion = input.strategy === "APP_VERSION" ? input.appVersion : void 0;
17831
18160
  return {
17832
18161
  catalogId: row.catalog_id,
@@ -17839,6 +18168,7 @@ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyO
17839
18168
  scopeKey
17840
18169
  };
17841
18170
  };
18171
+ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => projectParsedReleaseCatalogRow(row === null ? null : parseReleaseCatalogRow(row), input, scopeKey);
17842
18172
  //#endregion
17843
18173
  //#region ../../packages/server/dist/db/updateArtifacts.mjs
17844
18174
  const HBC_ASSET_PATH_RE = /\.bundle$/;
@@ -18430,9 +18760,9 @@ const baseBundleIdsOf = (row, range, bundleId, limit) => {
18430
18760
  };
18431
18761
  //#endregion
18432
18762
  //#region ../../packages/server/dist/core/reads.mjs
18433
- const PAGE$3 = 500;
18434
- const pick$1 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
18435
- const toBundleRow = pick$1([
18763
+ const PAGE$4 = 500;
18764
+ const pick$2 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
18765
+ const toBundleRow = pick$2([
18436
18766
  "id",
18437
18767
  "platform",
18438
18768
  "git_commit_hash",
@@ -18441,7 +18771,7 @@ const toBundleRow = pick$1([
18441
18771
  "manifest_file_hash",
18442
18772
  "asset_base_storage_uri"
18443
18773
  ]);
18444
- const toPatchRow = pick$1([
18774
+ const toPatchRow = pick$2([
18445
18775
  "id",
18446
18776
  "bundle_id",
18447
18777
  "base_bundle_id",
@@ -18451,7 +18781,7 @@ const toPatchRow = pick$1([
18451
18781
  "byte_size",
18452
18782
  "order_index"
18453
18783
  ]);
18454
- const toReleaseRow = pick$1([
18784
+ const pickReleaseRow = pick$2([
18455
18785
  "id",
18456
18786
  "revision",
18457
18787
  "scope_key",
@@ -18472,7 +18802,13 @@ const toReleaseRow = pick$1([
18472
18802
  "created_at_ms",
18473
18803
  "updated_at_ms"
18474
18804
  ]);
18475
- const toCatalogRow = pick$1([
18805
+ const toReleaseRow = (row) => {
18806
+ return {
18807
+ ...pickReleaseRow(row),
18808
+ label: typeof row.label === "number" ? row.label : null
18809
+ };
18810
+ };
18811
+ const toCatalogRow = pick$2([
18476
18812
  "scope_key",
18477
18813
  "catalog_id",
18478
18814
  "strategy",
@@ -18487,7 +18823,7 @@ const toCatalogRow = pick$1([
18487
18823
  "is_tombstone",
18488
18824
  "updated_at_ms"
18489
18825
  ]);
18490
- const toChannelRow = pick$1(["id", "name"]);
18826
+ const toChannelRow = pick$2(["id", "name"]);
18491
18827
  const drain$1 = async (read) => {
18492
18828
  const rows = [];
18493
18829
  let cursor;
@@ -18498,7 +18834,14 @@ const drain$1 = async (read) => {
18498
18834
  } while (cursor !== void 0);
18499
18835
  return rows;
18500
18836
  };
18501
- const after = (input) => input.after === void 0 ? {} : { range: (input.order ?? "asc") === "asc" ? { gt: input.after } : { lt: input.after } };
18837
+ const after = (input) => {
18838
+ const asc = (input.order ?? "asc") === "asc";
18839
+ const range = {
18840
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
18841
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
18842
+ };
18843
+ return Object.keys(range).length === 0 ? {} : { range };
18844
+ };
18502
18845
  const createCoreReads = (db, storage) => {
18503
18846
  const detail = async (row) => {
18504
18847
  const count = row._refs_bundle_patches_bundle_id ?? 0;
@@ -18508,7 +18851,7 @@ const createCoreReads = (db, storage) => {
18508
18851
  const page = await db.findMany("bundle_patches", {
18509
18852
  index: "byBundle",
18510
18853
  where: { bundle_id: row.id },
18511
- limit: Math.min(count - patches.length, PAGE$3),
18854
+ limit: Math.min(count - patches.length, PAGE$4),
18512
18855
  ...cursor === void 0 ? {} : { cursor }
18513
18856
  });
18514
18857
  patches.push(...page.rows.map(toPatchRow));
@@ -18609,6 +18952,18 @@ const createCoreReads = (db, storage) => {
18609
18952
  const row = await db.findOne("releases", { id });
18610
18953
  return row === null ? null : toReleaseRow(row);
18611
18954
  },
18955
+ async getReleaseByLabel({ channel, platform, label }) {
18956
+ const found = await db.findOne("releases", {
18957
+ channel_id: `channel:${encodeChannelKey(channel)}`,
18958
+ platform,
18959
+ label
18960
+ });
18961
+ if (found === null) return null;
18962
+ const row = await db.findOne("releases", { id: found.id });
18963
+ if (row === null) return null;
18964
+ const release = toReleaseRow(row);
18965
+ return release.label === label && release.platform === platform ? release : null;
18966
+ },
18612
18967
  async listReleases(input) {
18613
18968
  const { filter } = input;
18614
18969
  const options = {
@@ -18674,14 +19029,41 @@ const createCoreReads = (db, storage) => {
18674
19029
  ...after(input)
18675
19030
  })).rows.map(toCatalogRow);
18676
19031
  },
18677
- async listChannels() {
18678
- return (await drain$1((page) => db.findMany("channels", {
19032
+ async listReleaseScopeKeys(input) {
19033
+ const scopeKeys = [];
19034
+ for (let last = input.after ?? ""; scopeKeys.length < input.limit;) {
19035
+ const { rows } = await db.findMany("releases", {
19036
+ index: "scopes",
19037
+ where: {},
19038
+ limit: 1,
19039
+ range: { gt: last }
19040
+ });
19041
+ if (rows[0] === void 0) break;
19042
+ last = rows[0].scope_key;
19043
+ scopeKeys.push(last);
19044
+ }
19045
+ return scopeKeys;
19046
+ },
19047
+ async listChannels(input) {
19048
+ if (input !== void 0) return (await db.findMany("channels", {
18679
19049
  index: "all",
18680
19050
  where: {},
18681
- limit: PAGE$3,
19051
+ order: input.order ?? "asc",
19052
+ limit: input.limit,
19053
+ ...after(input)
19054
+ })).rows.map(toChannelRow);
19055
+ return (await drain$1((page) => db.findMany("channels", {
19056
+ index: "all",
19057
+ where: {},
19058
+ limit: PAGE$4,
18682
19059
  ...page
18683
19060
  }))).map(toChannelRow);
18684
19061
  },
19062
+ async getChannels(ids) {
19063
+ const unique = [...new Set(ids)];
19064
+ if (unique.length === 0) return [];
19065
+ return (await db.findByKeys("channels", unique.map((id) => ({ id })))).flatMap((row) => row ? [toChannelRow(row)] : []);
19066
+ },
18685
19067
  async findChannelByName(name) {
18686
19068
  const row = await db.findOne("channels", { name });
18687
19069
  return row === null ? null : toChannelRow(row);
@@ -18689,6 +19071,552 @@ const createCoreReads = (db, storage) => {
18689
19071
  };
18690
19072
  };
18691
19073
  //#endregion
19074
+ //#region ../../packages/server/dist/core/iosDevices.mjs
19075
+ const UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
19076
+ const normalizeIosUdid = (value) => {
19077
+ const trimmed = value.trim();
19078
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
19079
+ };
19080
+ const NAME_MAX_LENGTH = 100;
19081
+ const EMAIL_MAX_LENGTH = 320;
19082
+ const ISSUER_MAX_LENGTH = 64;
19083
+ const ACCOUNT_ROW = "registry";
19084
+ const ERROR_MAX_LENGTH = 512;
19085
+ const STATUSES = [
19086
+ "pending",
19087
+ "approved",
19088
+ "registered"
19089
+ ];
19090
+ const OUTCOMES = [
19091
+ "registered",
19092
+ "refused",
19093
+ "disabled",
19094
+ "missing"
19095
+ ];
19096
+ const IOS_DEVICE_DISABLED_ERROR = "Disabled in the Apple account.";
19097
+ const IOS_DEVICE_MISSING_ERROR = "Gone from the Apple account. Approve it again to register it.";
19098
+ var IosDeviceInputError = class extends TypeError {
19099
+ name = "IosDeviceInputError";
19100
+ };
19101
+ const pick$1 = (row) => ({
19102
+ id: row.id,
19103
+ udid: row.udid,
19104
+ name: row.name,
19105
+ status: row.status,
19106
+ requested_by: row.requested_by ?? null,
19107
+ created_at_ms: row.created_at_ms,
19108
+ approved_by: row.approved_by ?? null,
19109
+ approved_at_ms: row.approved_at_ms ?? null,
19110
+ registered_at_ms: row.registered_at_ms ?? null,
19111
+ apple_issuer_id: row.apple_issuer_id ?? null,
19112
+ apple_error: row.apple_error ?? null,
19113
+ build_id: row.build_id ?? null
19114
+ });
19115
+ const udidOf = (udid) => {
19116
+ const key = typeof udid === "string" ? normalizeIosUdid(udid) : null;
19117
+ if (key === null) throw new IosDeviceInputError("Invalid iOS device: udid must be 40 hex digits, or 8 and 16 joined by a hyphen.");
19118
+ return key;
19119
+ };
19120
+ const nameOf = (name) => {
19121
+ const trimmed = typeof name === "string" ? name.trim() : "";
19122
+ if (trimmed.length === 0 || trimmed.length > NAME_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: name must be 1 to ${NAME_MAX_LENGTH} characters.`);
19123
+ return trimmed;
19124
+ };
19125
+ const personOf = (value, field) => {
19126
+ if (value === null) return null;
19127
+ const email = typeof value === "string" ? value.trim().toLowerCase() : "";
19128
+ 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.`);
19129
+ return email;
19130
+ };
19131
+ const errorText = (text) => {
19132
+ const line = text.replace(/\s+/gu, " ").trim();
19133
+ return line.length > ERROR_MAX_LENGTH ? `${line.slice(0, 511)}…` : line;
19134
+ };
19135
+ const createIosDeviceApi = (db, { now = Date.now } = {}) => {
19136
+ const findIosDevice = async (udid) => {
19137
+ const key = normalizeIosUdid(udid);
19138
+ if (key === null) return null;
19139
+ const row = await db.findOne("ios_devices", { udid: key });
19140
+ return row === null ? null : pick$1(row);
19141
+ };
19142
+ const accountOfRows = async () => {
19143
+ const { rows } = await db.findMany("ios_devices", {
19144
+ index: "byRegistration",
19145
+ where: {},
19146
+ order: "asc",
19147
+ limit: 1,
19148
+ range: { gte: 0 }
19149
+ });
19150
+ return (rows[0] === void 0 ? null : pick$1(rows[0]))?.apple_issuer_id ?? null;
19151
+ };
19152
+ return {
19153
+ async listIosDevices(input) {
19154
+ if (input.status !== void 0 && !STATUSES.includes(input.status)) throw new IosDeviceInputError(`Invalid iOS device status: ${String(input.status)}. Expected ${STATUSES.join(", ")}.`);
19155
+ const page = {
19156
+ order: input.order ?? "asc",
19157
+ limit: input.limit,
19158
+ ...after(input)
19159
+ };
19160
+ const { rows } = input.status === void 0 ? await db.findMany("ios_devices", {
19161
+ index: "all",
19162
+ where: {},
19163
+ ...page
19164
+ }) : await db.findMany("ios_devices", {
19165
+ index: "byStatus",
19166
+ where: { status: input.status },
19167
+ ...page
19168
+ });
19169
+ return rows.map(pick$1);
19170
+ },
19171
+ findIosDevice,
19172
+ async requestIosDevice(input) {
19173
+ const udid = udidOf(input.udid);
19174
+ const name = nameOf(input.name);
19175
+ const requestedBy = personOf(input.requestedBy, "requestedBy");
19176
+ const existing = await db.findOne("ios_devices", { udid });
19177
+ if (existing !== null) return {
19178
+ device: pick$1(existing),
19179
+ created: false
19180
+ };
19181
+ const device = {
19182
+ id: createUUIDv7(),
19183
+ udid,
19184
+ name,
19185
+ status: "pending",
19186
+ requested_by: requestedBy,
19187
+ created_at_ms: now(),
19188
+ approved_by: null,
19189
+ approved_at_ms: null,
19190
+ registered_at_ms: null,
19191
+ apple_issuer_id: null,
19192
+ apple_error: null,
19193
+ build_id: null
19194
+ };
19195
+ try {
19196
+ await db.transaction(async (tx) => {
19197
+ tx.create("ios_devices", device);
19198
+ });
19199
+ } catch (error) {
19200
+ if (error instanceof DatabaseConstraintError && error.reason === "unique") {
19201
+ const winner = await db.findOne("ios_devices", { udid });
19202
+ if (winner !== null) return {
19203
+ device: pick$1(winner),
19204
+ created: false
19205
+ };
19206
+ }
19207
+ throw error;
19208
+ }
19209
+ return {
19210
+ device,
19211
+ created: true
19212
+ };
19213
+ },
19214
+ async approveIosDevice(id, input) {
19215
+ const name = input.name === void 0 ? void 0 : nameOf(input.name);
19216
+ const approvedBy = personOf(input.approvedBy, "approvedBy");
19217
+ return db.transaction(async (tx) => {
19218
+ const row = await tx.findOne("ios_devices", { id });
19219
+ if (row === null) return null;
19220
+ const device = pick$1(row);
19221
+ const set = {
19222
+ ...name === void 0 || name === device.name ? {} : { name },
19223
+ ...device.status === "pending" ? {
19224
+ status: "approved",
19225
+ approved_by: approvedBy,
19226
+ approved_at_ms: now()
19227
+ } : {}
19228
+ };
19229
+ if (Object.keys(set).length === 0) return device;
19230
+ tx.update("ios_devices", row, set);
19231
+ return {
19232
+ ...device,
19233
+ ...set
19234
+ };
19235
+ });
19236
+ },
19237
+ async renameIosDevice(id, input) {
19238
+ const name = nameOf(input);
19239
+ return db.transaction(async (tx) => {
19240
+ const row = await tx.findOne("ios_devices", { id });
19241
+ if (row === null) return null;
19242
+ const device = pick$1(row);
19243
+ if (device.name === name) return device;
19244
+ tx.update("ios_devices", row, { name });
19245
+ return {
19246
+ ...device,
19247
+ name
19248
+ };
19249
+ });
19250
+ },
19251
+ async recordIosDeviceOutcome({ id, seen, issuerId, outcome, reason }) {
19252
+ if (!OUTCOMES.includes(outcome)) throw new IosDeviceInputError(`Invalid iOS device outcome: ${String(outcome)}. Expected ${OUTCOMES.join(", ")}.`);
19253
+ 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.`);
19254
+ return db.transaction(async (tx) => {
19255
+ const row = await tx.findOne("ios_devices", { id });
19256
+ if (row === null) return null;
19257
+ const device = pick$1(row);
19258
+ if (device.status !== seen.status || device.approved_at_ms !== seen.approvedAtMs || device.apple_issuer_id !== null && device.apple_issuer_id !== issuerId) return null;
19259
+ let set;
19260
+ switch (outcome) {
19261
+ case "registered":
19262
+ if (device.status === "pending") return null;
19263
+ set = {
19264
+ status: "registered",
19265
+ registered_at_ms: device.registered_at_ms ?? now(),
19266
+ apple_issuer_id: issuerId,
19267
+ apple_error: null
19268
+ };
19269
+ break;
19270
+ case "refused":
19271
+ if (device.status !== "approved") return null;
19272
+ set = { apple_error: errorText(reason === void 0 || reason.trim() === "" ? "Apple refused it." : reason) };
19273
+ break;
19274
+ case "disabled":
19275
+ if (device.status === "pending") return null;
19276
+ set = { apple_error: IOS_DEVICE_DISABLED_ERROR };
19277
+ break;
19278
+ case "missing":
19279
+ if (device.status !== "registered") return null;
19280
+ set = {
19281
+ status: "pending",
19282
+ approved_by: null,
19283
+ approved_at_ms: null,
19284
+ apple_error: IOS_DEVICE_MISSING_ERROR
19285
+ };
19286
+ }
19287
+ if (Object.entries(set).some(([column, value]) => device[column] !== (value ?? null))) tx.update("ios_devices", row, set);
19288
+ return {
19289
+ ...device,
19290
+ ...set
19291
+ };
19292
+ });
19293
+ },
19294
+ async markIosDevicesInBuild({ buildId, ids }) {
19295
+ for (const id of new Set(ids)) await db.transaction(async (tx) => {
19296
+ const row = await tx.findOne("ios_devices", { id });
19297
+ if (row === null || typeof row.build_id === "string" && row.build_id >= buildId) return;
19298
+ tx.update("ios_devices", row, { build_id: buildId });
19299
+ });
19300
+ },
19301
+ async findIosDeviceAccount() {
19302
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
19303
+ const issuerId = existing === null ? await accountOfRows() : existing.apple_issuer_id;
19304
+ return issuerId === null ? null : { issuerId };
19305
+ },
19306
+ async claimIosDeviceAccount(issuerId) {
19307
+ 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.`);
19308
+ const answer = (held) => ({
19309
+ issuerId: held,
19310
+ claimed: held === issuerId
19311
+ });
19312
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
19313
+ if (existing !== null) return answer(existing.apple_issuer_id);
19314
+ const holder = await accountOfRows() ?? issuerId;
19315
+ try {
19316
+ await db.transaction(async (tx) => {
19317
+ tx.create("ios_device_account", {
19318
+ id: ACCOUNT_ROW,
19319
+ apple_issuer_id: holder,
19320
+ claimed_at_ms: now()
19321
+ });
19322
+ });
19323
+ return answer(holder);
19324
+ } catch (error) {
19325
+ if (error instanceof DatabaseConstraintError && (error.reason === "exists" || error.reason === "unique")) {
19326
+ const winner = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
19327
+ if (winner !== null) return answer(winner.apple_issuer_id);
19328
+ }
19329
+ throw error;
19330
+ }
19331
+ },
19332
+ async deleteIosDevice(id, only) {
19333
+ const requestedBy = only?.requestedBy === void 0 ? void 0 : personOf(only.requestedBy, "requestedBy");
19334
+ return db.transaction(async (tx) => {
19335
+ const row = await tx.findOne("ios_devices", { id });
19336
+ if (row === null) return null;
19337
+ const device = pick$1(row);
19338
+ if (only?.status !== void 0 && device.status !== only.status || requestedBy !== void 0 && device.requested_by !== requestedBy) return null;
19339
+ await tx.delete("ios_devices", row);
19340
+ return device;
19341
+ });
19342
+ }
19343
+ };
19344
+ };
19345
+ //#endregion
19346
+ //#region ../../packages/server/dist/core/nativeBuildDestinations.mjs
19347
+ const NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
19348
+ android: [
19349
+ "play-internal",
19350
+ "play-closed",
19351
+ "play-open",
19352
+ "play-production"
19353
+ ],
19354
+ ios: ["testflight"]
19355
+ };
19356
+ //#endregion
19357
+ //#region ../../packages/server/dist/core/labels.mjs
19358
+ const labelSequenceId = (channelId, platform) => `releases/${platform}/${channelId}`;
19359
+ const LABEL_PLATFORMS = ["ios", "android"];
19360
+ var NeedsLabelFill = class extends Error {
19361
+ channelId;
19362
+ platform;
19363
+ constructor(channelId, platform) {
19364
+ super(`Release labels of ${platform} ${channelId} need a fill first.`);
19365
+ this.channelId = channelId;
19366
+ this.platform = platform;
19367
+ }
19368
+ };
19369
+ const createLabelAllocator = (tx, used, caughtUp) => {
19370
+ const sequences = /* @__PURE__ */ new Map();
19371
+ return {
19372
+ async next(channelId, platform) {
19373
+ const id = labelSequenceId(channelId, platform);
19374
+ let sequence = sequences.get(id);
19375
+ if (sequence === void 0) {
19376
+ const row = await tx.findOne("label_sequences", { id });
19377
+ if (row === null || !row.is_filled) {
19378
+ const channel = row === null ? await tx.findOne("channels", { id: channelId }) : null;
19379
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) throw new NeedsLabelFill(channelId, platform);
19380
+ }
19381
+ const read = row?.last_label ?? 0;
19382
+ sequence = {
19383
+ row,
19384
+ read,
19385
+ last: read
19386
+ };
19387
+ sequences.set(id, sequence);
19388
+ used.set(id, {
19389
+ channelId,
19390
+ platform,
19391
+ read
19392
+ });
19393
+ }
19394
+ sequence.last += 1;
19395
+ return sequence.last;
19396
+ },
19397
+ caughtUp(channelId, platform) {
19398
+ caughtUp.set(labelSequenceId(channelId, platform), {
19399
+ channelId,
19400
+ platform
19401
+ });
19402
+ },
19403
+ flush() {
19404
+ for (const [id, { row, read, last }] of sequences) if (row === null) tx.create("label_sequences", {
19405
+ id,
19406
+ last_label: last,
19407
+ is_filled: true
19408
+ });
19409
+ else if (last !== read) tx.update("label_sequences", row, { last_label: last });
19410
+ }
19411
+ };
19412
+ };
19413
+ const FILL_BATCH = 25;
19414
+ const PAGE$3 = 500;
19415
+ const fillLabels = async (db, { channelId, platform }, { dryRun = false } = {}) => {
19416
+ const id = labelSequenceId(channelId, platform);
19417
+ let labeled = 0;
19418
+ let batchSize = FILL_BATCH;
19419
+ const label = async (ids) => {
19420
+ for (let at = 0; at < ids.length;) {
19421
+ const batch = ids.slice(at, at + batchSize);
19422
+ try {
19423
+ labeled += await db.transaction(async (tx) => {
19424
+ const counter = await tx.findOne("label_sequences", { id });
19425
+ let last = counter?.last_label ?? 0;
19426
+ let count = 0;
19427
+ for (const releaseId of batch) {
19428
+ const row = await tx.findOne("releases", { id: releaseId });
19429
+ if (row === null || typeof row.label === "number") continue;
19430
+ last += 1;
19431
+ count += 1;
19432
+ tx.update("releases", row, { label: last });
19433
+ }
19434
+ if (counter === null) tx.create("label_sequences", {
19435
+ id,
19436
+ last_label: last,
19437
+ is_filled: false
19438
+ });
19439
+ else if (last !== counter.last_label) tx.update("label_sequences", counter, { last_label: last });
19440
+ return count;
19441
+ });
19442
+ at += batch.length;
19443
+ } catch (error) {
19444
+ if (batchSize > 1 && error instanceof DatabaseConstraintError && error.reason === "too_large") {
19445
+ batchSize = Math.max(1, Math.floor(batchSize / 2));
19446
+ continue;
19447
+ }
19448
+ throw error;
19449
+ }
19450
+ }
19451
+ };
19452
+ let cursor;
19453
+ do {
19454
+ const page = await db.findMany("releases", {
19455
+ index: "byChannelPlatform",
19456
+ where: {
19457
+ channel_id: channelId,
19458
+ platform
19459
+ },
19460
+ limit: PAGE$3,
19461
+ ...cursor === void 0 ? {} : { cursor }
19462
+ });
19463
+ const unlabeled = page.rows.filter((row) => typeof row.label !== "number").map((row) => row.id);
19464
+ if (dryRun) labeled += unlabeled.length;
19465
+ else await label(unlabeled);
19466
+ cursor = page.next;
19467
+ } while (cursor !== void 0);
19468
+ if (dryRun) return labeled;
19469
+ await db.transaction(async (tx) => {
19470
+ const counter = await tx.findOne("label_sequences", { id });
19471
+ if (counter === null) tx.create("label_sequences", {
19472
+ id,
19473
+ last_label: 0,
19474
+ is_filled: true
19475
+ });
19476
+ else if (!counter.is_filled) tx.update("label_sequences", counter, { is_filled: true });
19477
+ });
19478
+ return labeled;
19479
+ };
19480
+ const probeLabelSchema = async (db, { channelId, platform }) => {
19481
+ await db.findOne("label_sequences", { id: labelSequenceId(channelId, platform) });
19482
+ await db.findMany("releases", {
19483
+ index: "byLabel",
19484
+ where: {
19485
+ channel_id: channelId,
19486
+ platform,
19487
+ label: 0
19488
+ },
19489
+ limit: 1
19490
+ });
19491
+ };
19492
+ const REPAIRS = 4;
19493
+ const RACES = 32;
19494
+ const writeWithLabels = async (db, write) => {
19495
+ const filled = /* @__PURE__ */ new Set();
19496
+ const fill = async (pairs) => {
19497
+ for (const pair of pairs) {
19498
+ filled.add(labelSequenceId(pair.channelId, pair.platform));
19499
+ await fillLabels(db, pair);
19500
+ }
19501
+ };
19502
+ for (let repairs = 0, races = 0;;) {
19503
+ const used = /* @__PURE__ */ new Map();
19504
+ const caughtUp = /* @__PURE__ */ new Map();
19505
+ try {
19506
+ return await db.transaction(async (tx) => {
19507
+ used.clear();
19508
+ caughtUp.clear();
19509
+ const labels = createLabelAllocator(tx, used, caughtUp);
19510
+ const result = await write(tx, labels);
19511
+ labels.flush();
19512
+ return result;
19513
+ });
19514
+ } catch (error) {
19515
+ const needs = error instanceof NeedsLabelFill ? [error] : error instanceof DatabaseConstraintError && error.reason === "too_large" ? [...caughtUp.values()] : [];
19516
+ if (needs.length > 0) {
19517
+ const fresh = needs.some(({ channelId, platform }) => !filled.has(labelSequenceId(channelId, platform)));
19518
+ if (fresh || repairs < REPAIRS) {
19519
+ if (!fresh) repairs += 1;
19520
+ await fill(needs);
19521
+ continue;
19522
+ }
19523
+ }
19524
+ if (error instanceof DatabaseConstraintError && error.reason === "unique" && error.model === "releases" && used.size > 0) {
19525
+ if (await db.transaction(async (tx) => {
19526
+ const moves = [];
19527
+ for (const [id, { channelId, read }] of used) {
19528
+ const counter = await tx.findOne("label_sequences", { id });
19529
+ if (counter !== null) {
19530
+ if (counter.last_label !== read) return false;
19531
+ moves.push(() => tx.update("label_sequences", counter, { last_label: read + 1 }));
19532
+ continue;
19533
+ }
19534
+ const channel = await tx.findOne("channels", { id: channelId });
19535
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) return false;
19536
+ moves.push(() => tx.create("label_sequences", {
19537
+ id,
19538
+ last_label: read + 1,
19539
+ is_filled: true
19540
+ }));
19541
+ }
19542
+ for (const move of moves) move();
19543
+ return true;
19544
+ }) ? (repairs += 1) <= REPAIRS : (races += 1) <= RACES) continue;
19545
+ }
19546
+ throw error;
19547
+ }
19548
+ }
19549
+ };
19550
+ const catchUpLabels = async (tx, labels, latest) => {
19551
+ const given = /* @__PURE__ */ new Map();
19552
+ if (latest === null || typeof latest.label === "number") return given;
19553
+ const unlabeled = [];
19554
+ let cursor;
19555
+ scan: do {
19556
+ const page = await tx.findMany("releases", {
19557
+ index: "byScope",
19558
+ where: { scope_key: latest.scope_key },
19559
+ order: "desc",
19560
+ limit: FILL_BATCH,
19561
+ ...cursor === void 0 ? {} : { cursor }
19562
+ });
19563
+ for (const row of page.rows) {
19564
+ if (typeof row.label === "number") break scan;
19565
+ unlabeled.push(row);
19566
+ }
19567
+ cursor = page.next;
19568
+ } while (cursor !== void 0);
19569
+ labels.caughtUp(latest.channel_id, latest.platform);
19570
+ for (const row of unlabeled.reverse()) {
19571
+ const { id, channel_id, platform } = toReleaseRow(row);
19572
+ const label = await labels.next(channel_id, platform);
19573
+ tx.update("releases", row, { label });
19574
+ given.set(id, label);
19575
+ }
19576
+ return given;
19577
+ };
19578
+ const pendingLabelPairs = async (db) => {
19579
+ const pairs = /* @__PURE__ */ new Map();
19580
+ for (let last = "";;) {
19581
+ const { rows } = await db.findMany("releases", {
19582
+ index: "scopes",
19583
+ where: {},
19584
+ limit: 1,
19585
+ range: { gt: last }
19586
+ });
19587
+ if (rows[0] === void 0) break;
19588
+ last = rows[0].scope_key;
19589
+ const { rows: newest } = await db.findMany("releases", {
19590
+ index: "byScope",
19591
+ where: { scope_key: last },
19592
+ order: "desc",
19593
+ limit: 1
19594
+ });
19595
+ if (newest[0] === void 0) continue;
19596
+ const { channel_id: channelId, platform, label } = toReleaseRow(newest[0]);
19597
+ const id = labelSequenceId(channelId, platform);
19598
+ const pair = pairs.get(id) ?? {
19599
+ channelId,
19600
+ platform,
19601
+ pending: false
19602
+ };
19603
+ pair.pending ||= label === null;
19604
+ pairs.set(id, pair);
19605
+ }
19606
+ const pending = [];
19607
+ for (const [id, { channelId, platform, pending: unlabeled }] of pairs) {
19608
+ if (!unlabeled) {
19609
+ const counter = await db.findOne("label_sequences", { id });
19610
+ if (counter !== null && counter.is_filled) continue;
19611
+ }
19612
+ pending.push({
19613
+ channelId,
19614
+ platform
19615
+ });
19616
+ }
19617
+ return pending;
19618
+ };
19619
+ //#endregion
18692
19620
  //#region ../../packages/server/dist/core/writes.mjs
18693
19621
  const PAGE$2 = 500;
18694
19622
  const countBundle = (tx, platform, delta) => {
@@ -18709,7 +19637,7 @@ const deleteBundle = async (tx, current) => {
18709
19637
  await tx.delete("bundles", current);
18710
19638
  countBundle(tx, current.platform, -1);
18711
19639
  };
18712
- const replaceBundlePatches = async (tx, bundle, rows) => {
19640
+ const replaceBundlePatches = async (tx, bundle, rows, checkNew) => {
18713
19641
  const wanted = new Map(rows.map((row) => [row.id, row]));
18714
19642
  const count = bundle._refs_bundle_patches_bundle_id ?? 0;
18715
19643
  let cursor;
@@ -18734,6 +19662,7 @@ const replaceBundlePatches = async (tx, bundle, rows) => {
18734
19662
  if (page.next === void 0) break;
18735
19663
  cursor = page.next;
18736
19664
  }
19665
+ if (checkNew !== void 0) for (const row of wanted.values()) await checkNew(row);
18737
19666
  for (const row of wanted.values()) tx.create("bundle_patches", row);
18738
19667
  };
18739
19668
  const insertChannel = async (db, row) => {
@@ -18774,6 +19703,10 @@ const deleteChannel = (db, id) => db.transaction(async (tx) => {
18774
19703
  deleted: false,
18775
19704
  reason: "not_empty"
18776
19705
  };
19706
+ for (const platform of LABEL_PLATFORMS) {
19707
+ const counter = await tx.findOne("label_sequences", { id: labelSequenceId(id, platform) });
19708
+ if (counter !== null) await tx.delete("label_sequences", counter);
19709
+ }
18777
19710
  await tx.delete("channels", row);
18778
19711
  return { deleted: true };
18779
19712
  });
@@ -18786,6 +19719,16 @@ const ARTIFACT_KINDS = {
18786
19719
  const SCOPE_KEY_MAX_LENGTH = 2048;
18787
19720
  const GIT_COMMIT_HASH_MAX_LENGTH = 255;
18788
19721
  const BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
19722
+ const SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
19723
+ const URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
19724
+ const APP_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;
19725
+ const FINGERPRINT_HASH = /^[A-Za-z0-9._~-]{1,255}$/;
19726
+ const DISTRIBUTIONS = {
19727
+ apk: ["direct"],
19728
+ app: ["direct"],
19729
+ aab: ["store"],
19730
+ ipa: ["direct", "store"]
19731
+ };
18789
19732
  var NativeBuildInputError = class extends TypeError {
18790
19733
  name = "NativeBuildInputError";
18791
19734
  };
@@ -18806,15 +19749,42 @@ const pick = (row) => ({
18806
19749
  build_number: row.build_number ?? null,
18807
19750
  submitted_to: row.submitted_to ?? null,
18808
19751
  submitted_at_ms: row.submitted_at_ms ?? null,
18809
- submitted_version: row.submitted_version ?? null
19752
+ submitted_version: row.submitted_version ?? null,
19753
+ is_store_build: row.is_store_build === true,
19754
+ is_sandbox: row.is_sandbox === true,
19755
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
19756
+ export_method: row.export_method ?? null,
19757
+ native_app_version: row.native_app_version ?? null
18810
19758
  });
18811
- const SUBMISSION_DESTINATIONS = {
18812
- android: "play-internal",
18813
- ios: "testflight"
18814
- };
19759
+ const EXPORT_METHODS = /* @__PURE__ */ new Set([
19760
+ "app-store",
19761
+ "ad-hoc",
19762
+ "development",
19763
+ "enterprise"
19764
+ ]);
19765
+ const OLDER_BUILDS_PAGE = 20;
19766
+ const OLDER_BUILDS_PAGES = 5;
19767
+ const MARK_ATTEMPTS = 8;
18815
19768
  const BUILD_NUMBER_MAX_LENGTH = 64;
18816
19769
  const SUBMITTED_VERSION_MAX_LENGTH = 255;
19770
+ const checkedScopeKey = (scopeKey) => {
19771
+ 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.`);
19772
+ return scopeKey;
19773
+ };
19774
+ const registeredDistribution = (kind, exportMethod) => kind !== "ipa" ? DISTRIBUTIONS[kind][0] : exportMethod === void 0 || exportMethod === null ? "unknown" : exportMethod === "app-store" ? "store" : "direct";
19775
+ const sandboxScopeKey = (scope, sandbox) => {
19776
+ const { appId, urlScheme, artifactKind, distribution } = sandbox;
19777
+ 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;
19778
+ if (problem !== null) throw new NativeBuildInputError(`Invalid sandbox build scope: ${problem}.`);
19779
+ const target = scope.fingerprintHash === null ? `app-version:${encodeURIComponent(scope.appVersion)}` : `fingerprint:${scope.fingerprintHash}`;
19780
+ return checkedScopeKey(`v1:sandbox:${scope.platform}:${appId}:${urlScheme}:${artifactKind}:${distribution}:${target}`);
19781
+ };
18817
19782
  const nativeBuildScopeKey = (scope) => {
19783
+ const { sandbox } = scope;
19784
+ if (sandbox !== void 0 && sandbox !== null) {
19785
+ if (sandbox.distribution !== "direct" && sandbox.distribution !== "store") throw new NativeBuildInputError("Invalid sandbox build scope: its distribution must be direct or store.");
19786
+ return sandboxScopeKey(scope, sandbox);
19787
+ }
18818
19788
  let scopeKey;
18819
19789
  try {
18820
19790
  const channelKey = encodeChannelKey(scope.channel);
@@ -18831,30 +19801,102 @@ const nativeBuildScopeKey = (scope) => {
18831
19801
  } catch (error) {
18832
19802
  throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
18833
19803
  }
18834
- 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.`);
18835
- return scopeKey;
19804
+ return checkedScopeKey(scopeKey);
19805
+ };
19806
+ const channelIdOf = (channel) => {
19807
+ try {
19808
+ return `channel:${encodeChannelKey(channel)}`;
19809
+ } catch (error) {
19810
+ throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
19811
+ }
19812
+ };
19813
+ const registrationScopeKey = (registration) => {
19814
+ channelIdOf(registration.channel);
19815
+ return registration.isSandbox === true ? sandboxScopeKey(registration, {
19816
+ appId: registration.sandboxAppId,
19817
+ urlScheme: registration.sandboxUrlScheme,
19818
+ artifactKind: registration.artifact.kind,
19819
+ distribution: registeredDistribution(registration.artifact.kind, registration.exportMethod)
19820
+ }) : nativeBuildScopeKey({
19821
+ ...registration,
19822
+ sandbox: null
19823
+ });
19824
+ };
19825
+ const refuseSandboxPatchBase = async (db, baseBundleId) => {
19826
+ 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.");
18836
19827
  };
18837
19828
  const isBuiltInBundle = async (db, bundleId) => await db.findOne("native_builds", { min_bundle_id: bundleId }) !== null;
18838
- const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, artifact }) => {
19829
+ const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, sandboxAppId, exportMethod, nativeAppVersion, artifact }) => {
18839
19830
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
18840
19831
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
18841
19832
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
18842
19833
  if (channel.trim().length === 0) return "channel is required";
19834
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
19835
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
19836
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
19837
+ 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`;
19838
+ }
19839
+ if (sandboxAppId !== void 0 && sandboxAppId !== null) {
19840
+ if (isSandbox !== true) return "sandboxAppId is a sandbox build's, and this isn't one";
19841
+ if (typeof sandboxAppId !== "string" || !APP_ID.test(sandboxAppId)) return "sandboxAppId must be the artifact's bundle identifier or application ID, up to 255 characters";
19842
+ }
19843
+ if (isSandbox === true) {
19844
+ if (sandboxUrlScheme === void 0 || sandboxUrlScheme === null) return "a sandbox build needs the sandboxUrlScheme its artifact registers";
19845
+ 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";
19846
+ }
18843
19847
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
18844
19848
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
18845
19849
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
18846
19850
  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`;
19851
+ if (nativeAppVersion !== void 0 && nativeAppVersion !== null && (typeof nativeAppVersion !== "string" || nativeAppVersion.trim().length === 0)) return "nativeAppVersion must be the artifact's app version, or null";
18847
19852
  const kinds = ARTIFACT_KINDS[platform];
18848
19853
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
19854
+ if (exportMethod !== void 0 && exportMethod !== null) {
19855
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
19856
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
19857
+ }
18849
19858
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
18850
19859
  return null;
18851
19860
  };
19861
+ const SIBLING_KINDS = {
19862
+ app: "ipa",
19863
+ ipa: "app"
19864
+ };
19865
+ 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");
19866
+ const siblingSandboxScopeKey = (build, artifactKind) => {
19867
+ const [version, sandbox, platform, appId, urlScheme] = build.scope_key.split(":");
19868
+ if (version !== "v1" || sandbox !== "sandbox" || platform !== build.platform || appId === void 0 || urlScheme === void 0) return null;
19869
+ const target = build.fingerprint_hash === null ? {
19870
+ platform: build.platform,
19871
+ fingerprintHash: null,
19872
+ appVersion: build.app_version ?? ""
19873
+ } : {
19874
+ platform: build.platform,
19875
+ fingerprintHash: build.fingerprint_hash,
19876
+ appVersion: null
19877
+ };
19878
+ try {
19879
+ return sandboxScopeKey(target, {
19880
+ appId,
19881
+ urlScheme,
19882
+ artifactKind: build.artifact_kind,
19883
+ distribution: registeredDistribution(build.artifact_kind, build.export_method)
19884
+ }) === build.scope_key ? sandboxScopeKey(target, {
19885
+ appId,
19886
+ urlScheme,
19887
+ artifactKind,
19888
+ distribution: "direct"
19889
+ }) : null;
19890
+ } catch {
19891
+ return null;
19892
+ }
19893
+ };
18852
19894
  const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18853
19895
  async registerNativeBuild(registration) {
18854
19896
  const problem = problemOf(registration);
18855
19897
  if (problem !== null) throw new NativeBuildInputError(`Invalid native build: ${problem}.`);
18856
- const scopeKey = nativeBuildScopeKey(registration);
18857
- const channelId = `channel:${encodeChannelKey(registration.channel)}`;
19898
+ const scopeKey = registrationScopeKey(registration);
19899
+ const channelId = channelIdOf(registration.channel);
18858
19900
  const { embeddedBundle } = registration;
18859
19901
  const row = {
18860
19902
  id: registration.id,
@@ -18873,7 +19915,12 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18873
19915
  build_number: registration.buildNumber ?? null,
18874
19916
  submitted_to: null,
18875
19917
  submitted_at_ms: null,
18876
- submitted_version: null
19918
+ submitted_version: null,
19919
+ is_store_build: false,
19920
+ is_sandbox: registration.isSandbox === true,
19921
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
19922
+ export_method: registration.exportMethod ?? null,
19923
+ native_app_version: registration.nativeAppVersion ?? null
18877
19924
  };
18878
19925
  for (let attempt = 1;; attempt += 1) {
18879
19926
  await insertChannel(db, {
@@ -18907,25 +19954,82 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18907
19954
  const row = await db.findOne("native_builds", { id });
18908
19955
  return row === null ? null : pick(row);
18909
19956
  },
19957
+ async findNativeBuildByBuiltInBundle(bundleId) {
19958
+ const row = await db.findOne("native_builds", { min_bundle_id: bundleId });
19959
+ return row === null ? null : pick(row);
19960
+ },
18910
19961
  async findNativeBuild(scope, options) {
18911
19962
  const scopeKey = nativeBuildScopeKey(scope);
18912
19963
  const buildKey = options?.buildKey;
18913
19964
  if (buildKey !== void 0 && !BUILD_KEY.test(buildKey)) throw new NativeBuildInputError("Invalid native build key: it must be nbk1: and a SHA-256.");
18914
- const { rows } = buildKey === void 0 ? await db.findMany("native_builds", {
19965
+ const artifactKind = options?.artifactKind;
19966
+ 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 ")}.`);
19967
+ const ofKind = (row) => artifactKind === void 0 || row.artifact_kind === artifactKind;
19968
+ if (options?.storeBuild) {
19969
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
19970
+ return marked === null || !ofKind(marked) ? null : pick(marked);
19971
+ }
19972
+ const read = (limit, before) => {
19973
+ const page = {
19974
+ order: "desc",
19975
+ limit,
19976
+ ...before === void 0 ? {} : { range: { lt: before } }
19977
+ };
19978
+ return buildKey !== void 0 ? db.findMany("native_builds", {
19979
+ index: "byBuildKey",
19980
+ where: {
19981
+ scope_key: scopeKey,
19982
+ build_key: buildKey
19983
+ },
19984
+ ...page
19985
+ }) : artifactKind !== void 0 ? db.findMany("native_builds", {
19986
+ index: "byScopeKind",
19987
+ where: {
19988
+ scope_key: scopeKey,
19989
+ artifact_kind: artifactKind
19990
+ },
19991
+ ...page
19992
+ }) : db.findMany("native_builds", {
19993
+ index: "byScope",
19994
+ where: { scope_key: scopeKey },
19995
+ ...page
19996
+ });
19997
+ };
19998
+ const bundleId = options?.builtInOlderThan;
19999
+ if (bundleId !== void 0 && scope.sandbox !== void 0 && scope.sandbox !== null) return null;
20000
+ const { rows } = await read(1);
20001
+ const newest = (rows[0] === void 0 ? void 0 : pick(rows[0])) ?? (artifactKind !== void 0 && buildKey === void 0 ? await db.findMany("native_builds", {
18915
20002
  index: "byScope",
18916
20003
  where: { scope_key: scopeKey },
18917
20004
  order: "desc",
18918
20005
  limit: 1
18919
- }) : await db.findMany("native_builds", {
18920
- index: "byBuildKey",
18921
- where: {
18922
- scope_key: scopeKey,
18923
- build_key: buildKey
18924
- },
20006
+ }).then(({ rows: [row] }) => row?.artifact_kind === artifactKind ? pick(row) : void 0) : void 0);
20007
+ if (newest === void 0 || !ofKind(newest)) return null;
20008
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return newest;
20009
+ let before = newest.id;
20010
+ for (let page = 0; page < OLDER_BUILDS_PAGES; page += 1) {
20011
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
20012
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
20013
+ if (usable !== void 0) return ofKind(usable) ? pick(usable) : null;
20014
+ const last = older.at(-1);
20015
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
20016
+ before = last.id;
20017
+ }
20018
+ return null;
20019
+ },
20020
+ async findNativeBuildSibling(build) {
20021
+ const artifactKind = SIBLING_KINDS[build.artifact_kind];
20022
+ if (build.platform !== "ios" || !build.is_sandbox || artifactKind === void 0 || !isInstallTarget(build)) return null;
20023
+ const scopeKey = siblingSandboxScopeKey(build, artifactKind);
20024
+ if (scopeKey === null) return null;
20025
+ const { rows } = await db.findMany("native_builds", {
20026
+ index: "byScope",
20027
+ where: { scope_key: scopeKey },
18925
20028
  order: "desc",
18926
20029
  limit: 1
18927
20030
  });
18928
- return rows[0] === void 0 ? null : pick(rows[0]);
20031
+ const sibling = rows[0] === void 0 ? null : pick(rows[0]);
20032
+ return sibling !== null && isInstallTarget(sibling) ? sibling : null;
18929
20033
  },
18930
20034
  async recordNativeBuildSubmission(id, { destination, version }) {
18931
20035
  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.`);
@@ -18933,7 +20037,8 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18933
20037
  const row = await tx.findOne("native_builds", { id });
18934
20038
  if (row === null) return null;
18935
20039
  const build = pick(row);
18936
- 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}.`);
20040
+ 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}.`);
20041
+ if (build.is_sandbox && destination !== "testflight" && destination !== "play-internal") throw new NativeBuildInputError("A sandbox build can submit only to TestFlight or Play internal testing.");
18937
20042
  const set = {
18938
20043
  submitted_to: destination,
18939
20044
  submitted_at_ms: now(),
@@ -18946,6 +20051,46 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18946
20051
  };
18947
20052
  });
18948
20053
  },
20054
+ async markNativeBuild(id, { storeBuild }) {
20055
+ for (let attempt = 1;; attempt += 1) try {
20056
+ return await db.transaction(async (tx) => {
20057
+ const row = await tx.findOne("native_builds", { id });
20058
+ if (row === null) return null;
20059
+ const build = pick(row);
20060
+ if (!storeBuild) {
20061
+ if (build.is_store_build) tx.update("native_builds", row, { is_store_build: false });
20062
+ return {
20063
+ nativeBuild: {
20064
+ ...build,
20065
+ is_store_build: false
20066
+ },
20067
+ previous: null
20068
+ };
20069
+ }
20070
+ if (build.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
20071
+ if (build.is_store_build) return {
20072
+ nativeBuild: build,
20073
+ previous: null
20074
+ };
20075
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build.scope_key });
20076
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
20077
+ tx.update("native_builds", row, { is_store_build: true });
20078
+ return {
20079
+ nativeBuild: {
20080
+ ...build,
20081
+ is_store_build: true
20082
+ },
20083
+ previous: holder === null ? null : {
20084
+ ...pick(holder),
20085
+ is_store_build: false
20086
+ }
20087
+ };
20088
+ });
20089
+ } catch (error) {
20090
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
20091
+ throw error;
20092
+ }
20093
+ },
18949
20094
  async deleteNativeBuild(id) {
18950
20095
  return db.transaction(async (tx) => {
18951
20096
  const row = await tx.findOne("native_builds", { id });
@@ -19001,41 +20146,39 @@ const checkScope = (scope) => {
19001
20146
  });
19002
20147
  if (scope.strategy === "FINGERPRINT" !== (scope.fingerprintHash !== null) || scope.scopeKey !== expected) fail$1("INVALID_SCOPE", "Release catalog scope metadata is inconsistent");
19003
20148
  };
19004
- const enabledReleases = async (tx, scopeKey) => {
20149
+ const drainReleases = async (page) => {
19005
20150
  const rows = [];
19006
20151
  let cursor;
19007
20152
  do {
19008
- const page = await tx.findMany("releases", {
19009
- index: "byScopeEnabled",
19010
- where: {
19011
- scope_key: scopeKey,
19012
- enabled: true
19013
- },
19014
- limit: PAGE$1,
19015
- ...cursor === void 0 ? {} : { cursor }
19016
- });
19017
- rows.push(...page.rows.map(toReleaseRow));
19018
- cursor = page.next;
20153
+ const found = await page(cursor);
20154
+ rows.push(...found.rows.map((row) => toReleaseRow(row)));
20155
+ cursor = found.next;
19019
20156
  } while (cursor !== void 0);
19020
20157
  return rows;
19021
20158
  };
19022
- const latestReleaseId = async (tx, scopeKey) => {
20159
+ const enabledIn = (scopeKey, cursor) => ({
20160
+ index: "byScopeEnabled",
20161
+ where: {
20162
+ scope_key: scopeKey,
20163
+ enabled: true
20164
+ },
20165
+ limit: PAGE$1,
20166
+ ...cursor === void 0 ? {} : { cursor }
20167
+ });
20168
+ const enabledReleases = (tx, scopeKey) => drainReleases((cursor) => tx.findMany("releases", enabledIn(scopeKey, cursor)));
20169
+ const latestRelease = async (tx, scopeKey) => {
19023
20170
  const { rows } = await tx.findMany("releases", {
19024
20171
  index: "byScope",
19025
20172
  where: { scope_key: scopeKey },
19026
20173
  order: "desc",
19027
20174
  limit: 1
19028
20175
  });
19029
- return rows[0]?.id ?? null;
20176
+ return rows[0] === void 0 ? null : toReleaseRow(rows[0]);
19030
20177
  };
19031
- const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
19032
- const compilation = await compileReleaseCatalog({
19033
- strategy: scope.strategy,
19034
- releases: enabled.map(releaseRowToRelease)
19035
- });
19036
- const generation = (stored.generation ?? 0) + 1;
20178
+ const nextCatalog = (scope, stored, compilation, updatedAtMs) => {
20179
+ const generation = (stored.catalog?.generation ?? 0) + 1;
19037
20180
  if (!Number.isSafeInteger(generation)) fail$1("CATALOG_GENERATION_EXHAUSTED", `Catalog "${scope.scopeKey}" exhausted its generation counter`);
19038
- const catalog = {
20181
+ return {
19039
20182
  scope_key: scope.scopeKey,
19040
20183
  catalog_id: stored.catalog?.catalog_id ?? createUUIDv7(),
19041
20184
  strategy: scope.strategy,
@@ -19050,6 +20193,21 @@ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
19050
20193
  is_tombstone: compilation.payload.releaseDescriptors.length === 0,
19051
20194
  updated_at_ms: updatedAtMs
19052
20195
  };
20196
+ };
20197
+ const compileScope = async (scope, enabled) => {
20198
+ try {
20199
+ return await compileReleaseCatalog({
20200
+ strategy: scope.strategy,
20201
+ releases: enabled.map(releaseRowToRelease)
20202
+ });
20203
+ } catch (error) {
20204
+ if (!(error instanceof ReleaseCatalogCompilationError) || error.code !== "CATALOG_OVERSIZE") throw error;
20205
+ 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.`);
20206
+ }
20207
+ };
20208
+ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
20209
+ const compilation = await compileScope(scope, enabled);
20210
+ const catalog = nextCatalog(scope, stored, compilation, updatedAtMs);
19053
20211
  const { scope_key: _scopeKey, ...set } = catalog;
19054
20212
  if (stored.row === null) tx.create("release_catalogs", catalog);
19055
20213
  else tx.update("release_catalogs", stored.row, set);
@@ -19069,10 +20227,10 @@ const readCatalog = async (tx, scopeKey) => {
19069
20227
  const assertHistory = (stored, hasReleases) => {
19070
20228
  if (stored.catalog === null && hasReleases) fail$1("CATALOG_IDENTITY_MISSING", "Catalog history is missing. Restore its catalog row from backup before rebuilding or deploying.");
19071
20229
  };
19072
- const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
20230
+ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }, labels) => {
19073
20231
  checkScope(scope);
19074
20232
  const stored = await readCatalog(tx, scope.scopeKey);
19075
- const enabled = await enabledReleases(tx, scope.scopeKey);
20233
+ let enabled = await enabledReleases(tx, scope.scopeKey);
19076
20234
  if (bundle !== void 0) {
19077
20235
  insertBundle(tx, bundle.row);
19078
20236
  for (const patch of bundle.patches) tx.create("bundle_patches", patch);
@@ -19080,14 +20238,22 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
19080
20238
  let before = null;
19081
20239
  let release;
19082
20240
  if (change.operation === "insert") {
19083
- const latest = await latestReleaseId(tx, scope.scopeKey);
20241
+ if (labels === void 0) throw new Error("A release insert takes its label from an allocator.");
20242
+ const newest = await latestRelease(tx, scope.scopeKey);
20243
+ const latest = newest?.id ?? null;
19084
20244
  assertHistory(stored, latest !== null);
19085
20245
  const floor = [latest, bundle && isUUIDv7(bundle.row.id) ? bundle.row.id : null].filter((id) => id !== null).sort().at(-1);
19086
20246
  const id = change.row.id ?? createUUIDv7After(floor ?? null);
19087
20247
  if (latest !== null && id <= latest) fail$1("NON_MONOTONIC_RELEASE_ID", `Release "${id}" must sort after "${latest}"`);
20248
+ const given = await catchUpLabels(tx, labels, newest);
20249
+ if (given.size > 0) enabled = enabled.map((row) => given.has(row.id) ? {
20250
+ ...row,
20251
+ label: given.get(row.id)
20252
+ } : row);
19088
20253
  release = {
19089
20254
  ...change.row,
19090
- id
20255
+ id,
20256
+ label: await labels.next(scope.channelId, scope.platform)
19091
20257
  };
19092
20258
  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");
19093
20259
  tx.create("releases", release);
@@ -19100,8 +20266,9 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
19100
20266
  await tx.delete("releases", row);
19101
20267
  release = null;
19102
20268
  } else {
20269
+ const { label: _label, ...update } = change.update;
19103
20270
  const set = {
19104
- ...change.update,
20271
+ ...update,
19105
20272
  revision: before.revision + 1
19106
20273
  };
19107
20274
  tx.update("releases", row, set);
@@ -19122,23 +20289,55 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
19122
20289
  };
19123
20290
  const changeReleases = (db, inputs) => {
19124
20291
  if (new Set(inputs.map(({ scope }) => scope.scopeKey)).size !== inputs.length) fail$1("INVALID_SCOPE", "A batch cannot change one catalog scope twice");
19125
- return db.transaction(async (tx) => {
20292
+ return writeWithLabels(db, async (tx, labels) => {
19126
20293
  const results = [];
19127
- for (const input of inputs) results.push(await changeRelease(tx, input));
20294
+ for (const input of inputs) results.push(await changeRelease(tx, input, labels));
19128
20295
  return results;
19129
20296
  });
19130
20297
  };
20298
+ 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;
20299
+ const withoutLabels = (payload) => {
20300
+ const parsed = JSON.parse(payload);
20301
+ return JSON.stringify({
20302
+ ...parsed,
20303
+ releaseDescriptors: (parsed.releaseDescriptors ?? []).map(({ label: _label, ...descriptor }) => descriptor)
20304
+ });
20305
+ };
20306
+ 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);
20307
+ const catalogRowScope = (row) => ({
20308
+ channelId: row.channel_id,
20309
+ channelName: decodeChannelKey(row.channel_key),
20310
+ fingerprintHash: row.fingerprint_hash,
20311
+ platform: row.platform,
20312
+ scopeKey: row.scope_key,
20313
+ strategy: row.strategy
20314
+ });
20315
+ const preflightRebuild = async (db, scopeKey, updatedAtMs) => {
20316
+ const row = await db.findOne("release_catalogs", { scope_key: scopeKey });
20317
+ if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
20318
+ const current = toCatalogRow(row);
20319
+ const scope = catalogRowScope(current);
20320
+ checkScope(scope);
20321
+ const enabled = await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor)));
20322
+ const compilation = await compileScope(scope, enabled);
20323
+ const changed = !isCurrent(scope, current, compilation);
20324
+ const projectedCatalog = changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current;
20325
+ return {
20326
+ changed,
20327
+ labelsOnly: changed && differsInLabelsOnly(current, projectedCatalog),
20328
+ currentCatalog: current,
20329
+ diagnostics: compilation.diagnostics,
20330
+ projectedCatalog
20331
+ };
20332
+ };
19131
20333
  const rebuildScope = async (tx, scope, updatedAtMs) => {
19132
20334
  checkScope(scope);
19133
20335
  const stored = await readCatalog(tx, scope.scopeKey);
19134
- assertHistory(stored, await latestReleaseId(tx, scope.scopeKey) !== null);
20336
+ assertHistory(stored, await latestRelease(tx, scope.scopeKey) !== null);
19135
20337
  const enabled = await enabledReleases(tx, scope.scopeKey);
19136
- const compilation = await compileReleaseCatalog({
19137
- strategy: scope.strategy,
19138
- releases: enabled.map(releaseRowToRelease)
19139
- });
20338
+ const compilation = await compileScope(scope, enabled);
19140
20339
  const current = stored.catalog;
19141
- 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 {
20340
+ if (current !== null && isCurrent(scope, current, compilation)) return {
19142
20341
  catalog: current,
19143
20342
  current,
19144
20343
  changed: false,
@@ -19154,6 +20353,7 @@ const rebuildScope = async (tx, scope, updatedAtMs) => {
19154
20353
  };
19155
20354
  //#endregion
19156
20355
  //#region ../../packages/server/dist/core/operations.mjs
20356
+ const CATALOG_PAGE = 100;
19157
20357
  var Preflight = class extends Error {
19158
20358
  result;
19159
20359
  constructor(result) {
@@ -19238,14 +20438,7 @@ const mutationResult = ({ catalog, release }) => ({
19238
20438
  const catalogScope = async (tx, scopeKey) => {
19239
20439
  const row = await tx.findOne("release_catalogs", { scope_key: scopeKey });
19240
20440
  if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
19241
- return {
19242
- channelId: row.channel_id,
19243
- channelName: decodeChannelKey(row.channel_key),
19244
- fingerprintHash: row.fingerprint_hash,
19245
- platform: row.platform,
19246
- scopeKey: row.scope_key,
19247
- strategy: row.strategy
19248
- };
20441
+ return catalogRowScope(toCatalogRow(row));
19249
20442
  };
19250
20443
  const createCoreOperations = (db, { now = Date.now } = {}) => {
19251
20444
  const ensureChannel = async (name) => (await insertChannel(db, {
@@ -19265,7 +20458,11 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
19265
20458
  for (const { release } of deployments) if (!channels.has(release.channel)) channels.set(release.channel, await ensureChannel(release.channel));
19266
20459
  const platforms = /* @__PURE__ */ new Map();
19267
20460
  for (const deployment of deployments) {
19268
- if (!("bundleId" in deployment) || platforms.has(deployment.bundleId)) continue;
20461
+ if (!("bundleId" in deployment)) {
20462
+ for (const { baseBundleId } of deployment.bundle.patches ?? []) await refuseSandboxPatchBase(db, baseBundleId);
20463
+ continue;
20464
+ }
20465
+ if (platforms.has(deployment.bundleId)) continue;
19269
20466
  const row = await db.findOne("bundles", { id: deployment.bundleId });
19270
20467
  if (row === null) throw new DatabaseBundleNotFoundError(deployment.bundleId);
19271
20468
  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.`);
@@ -19375,7 +20572,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
19375
20572
  if (targetChannel.length === 0) throw new ReleaseManagementError("TARGET_RELEASE_INVALID", "Promotion requires a target channel.");
19376
20573
  const channel = await ensureChannel(targetChannel);
19377
20574
  const updatedAtMs = now();
19378
- return db.transaction(async (tx) => {
20575
+ return writeWithLabels(db, async (tx, labels) => {
19379
20576
  const { release: source, scope: sourceScope } = await loadTarget(tx, input);
19380
20577
  checkSource(source);
19381
20578
  const targetScope = scopeOf$1(channel, source.platform, source.fingerprint_hash);
@@ -19403,12 +20600,13 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
19403
20600
  },
19404
20601
  updatedAtMs
19405
20602
  }) : null;
20603
+ const { label: _label, ...copied } = source;
19406
20604
  const target = await changeRelease(tx, {
19407
20605
  scope: targetScope,
19408
20606
  change: {
19409
20607
  operation: "insert",
19410
20608
  row: {
19411
- ...source,
20609
+ ...copied,
19412
20610
  id: createUUIDv7After(floor ?? null, updatedAtMs),
19413
20611
  revision: 1,
19414
20612
  scope_key: targetScope.scopeKey,
@@ -19423,7 +20621,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
19423
20621
  }
19424
20622
  },
19425
20623
  updatedAtMs
19426
- });
20624
+ }, labels);
19427
20625
  return {
19428
20626
  source: moved === null ? null : mutationResult(moved),
19429
20627
  target: mutationResult(target)
@@ -19440,17 +20638,38 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
19440
20638
  };
19441
20639
  });
19442
20640
  },
19443
- preflightReleaseCatalogRebuild: (scopeKey) => {
19444
- const updatedAtMs = now();
19445
- return dryRun(db, async (tx) => {
19446
- const rebuilt = await rebuildScope(tx, await catalogScope(tx, scopeKey), updatedAtMs);
19447
- return {
19448
- changed: rebuilt.changed,
19449
- currentCatalog: rebuilt.current,
19450
- diagnostics: rebuilt.diagnostics,
19451
- projectedCatalog: rebuilt.catalog
19452
- };
19453
- });
20641
+ preflightReleaseCatalogRebuild: (scopeKey) => preflightRebuild(db, scopeKey, now()),
20642
+ fillReleaseLabels: async ({ dryRun = false, catalogs = true } = {}) => {
20643
+ let releases = 0;
20644
+ const pairs = await pendingLabelPairs(db);
20645
+ if (dryRun && pairs[0] !== void 0) await probeLabelSchema(db, pairs[0]);
20646
+ for (const pair of pairs) releases += await fillLabels(db, pair, { dryRun });
20647
+ let rebuilt = 0;
20648
+ if (catalogs) {
20649
+ let cursor;
20650
+ do {
20651
+ const page = await db.findMany("release_catalogs", {
20652
+ index: "all",
20653
+ where: {},
20654
+ limit: CATALOG_PAGE,
20655
+ ...cursor === void 0 ? {} : { cursor }
20656
+ });
20657
+ for (const row of page.rows) {
20658
+ if (row.is_tombstone) continue;
20659
+ const preflight = await preflightRebuild(db, row.scope_key, now()).catch(() => null);
20660
+ if (preflight === null || !preflight.labelsOnly) continue;
20661
+ rebuilt += 1;
20662
+ if (dryRun) continue;
20663
+ const updatedAtMs = now();
20664
+ await db.transaction((tx) => rebuildScope(tx, catalogRowScope(toCatalogRow(row)), updatedAtMs));
20665
+ }
20666
+ cursor = page.next;
20667
+ } while (cursor !== void 0);
20668
+ }
20669
+ return {
20670
+ releases,
20671
+ catalogs: rebuilt
20672
+ };
19454
20673
  },
19455
20674
  ensureChannel,
19456
20675
  deleteChannel: (id) => deleteChannel(db, id),
@@ -19469,7 +20688,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
19469
20688
  if (patches !== void 0) await replaceBundlePatches(tx, current, bundleToPatchRows({
19470
20689
  ...next,
19471
20690
  patches
19472
- }));
20691
+ }), (row) => refuseSandboxPatchBase(tx, row.base_bundle_id));
19473
20692
  }),
19474
20693
  deleteBundles: async (ids) => {
19475
20694
  try {
@@ -19525,6 +20744,7 @@ const createCoreApi = (db, storage, options = {}) => {
19525
20744
  ...reads,
19526
20745
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
19527
20746
  ...createNativeBuildApi(db, options),
20747
+ ...createIosDeviceApi(db, options),
19528
20748
  ready: async () => {
19529
20749
  await reads.listReleaseCatalogs({ limit: 1 });
19530
20750
  }
@@ -19708,6 +20928,10 @@ const answer = async (operation) => {
19708
20928
  error: error.message
19709
20929
  }, status);
19710
20930
  }
20931
+ if (error instanceof ReleaseCatalogCompilationError && error.code === "CATALOG_OVERSIZE") return json$2({
20932
+ code: error.code,
20933
+ error: error.message
20934
+ }, 400);
19711
20935
  if (error instanceof DatabaseBundleNotFoundError) return json$2({
19712
20936
  code: "BUNDLE_NOT_FOUND",
19713
20937
  error: error.message
@@ -19727,17 +20951,20 @@ const LIMITS = {
19727
20951
  defaultValue: 50,
19728
20952
  maxValue: 500
19729
20953
  };
19730
- const keyset = (url, maxValue = LIMITS.maxValue) => {
19731
- const order = url.searchParams.get("order") ?? "desc";
20954
+ const MAX_IDS = 100;
20955
+ const keyset = (url, maxValue = LIMITS.maxValue, defaultOrder = "desc") => {
20956
+ const order = url.searchParams.get("order") ?? defaultOrder;
19732
20957
  if (order !== "asc" && order !== "desc") throw new HandlerBadRequestError("order must be 'asc' or 'desc'.");
19733
20958
  const limitParam = url.searchParams.get("limit");
19734
20959
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
19735
20960
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
19736
20961
  const cursor = url.searchParams.get("cursor");
20962
+ const through = url.searchParams.get("through");
19737
20963
  return {
19738
20964
  order,
19739
20965
  limit,
19740
- ...cursor === null ? {} : { after: cursor }
20966
+ ...cursor === null ? {} : { after: cursor },
20967
+ ...through === null ? {} : { through }
19741
20968
  };
19742
20969
  };
19743
20970
  const page = (rows, { limit }, keyOf, extra = {}) => json$2({
@@ -19828,7 +21055,8 @@ const nativeBuildScopeOf = (url) => {
19828
21055
  const fingerprintHash = params.get("fingerprintHash");
19829
21056
  const appVersion = params.get("appVersion");
19830
21057
  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.");
19831
- return fingerprintHash !== null ? {
21058
+ const sandbox = sandboxScopeOf(params);
21059
+ const scope = fingerprintHash !== null ? {
19832
21060
  platform,
19833
21061
  channel,
19834
21062
  fingerprintHash,
@@ -19839,16 +21067,43 @@ const nativeBuildScopeOf = (url) => {
19839
21067
  fingerprintHash: null,
19840
21068
  appVersion
19841
21069
  };
21070
+ return sandbox === null ? scope : {
21071
+ ...scope,
21072
+ sandbox
21073
+ };
21074
+ };
21075
+ const SANDBOX_SCOPE_PARAMS = [
21076
+ "sandboxAppId",
21077
+ "sandboxUrlScheme",
21078
+ "artifactKind",
21079
+ "distribution"
21080
+ ];
21081
+ const sandboxScopeOf = (params) => {
21082
+ const [appId, urlScheme, artifactKind, distribution] = SANDBOX_SCOPE_PARAMS.map((name) => params.get(name));
21083
+ const named = [
21084
+ appId,
21085
+ urlScheme,
21086
+ artifactKind,
21087
+ distribution
21088
+ ].filter((value) => value !== null).length;
21089
+ if (named === 0) return null;
21090
+ if (named !== SANDBOX_SCOPE_PARAMS.length) throw new HandlerBadRequestError(`A sandbox build lookup needs ${SANDBOX_SCOPE_PARAMS.join(", ")}.`);
21091
+ return {
21092
+ appId,
21093
+ urlScheme,
21094
+ artifactKind,
21095
+ distribution
21096
+ };
19842
21097
  };
19843
21098
  const refusingInvalid = async (operation) => {
19844
21099
  try {
19845
21100
  return await operation();
19846
21101
  } catch (error) {
19847
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
21102
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
19848
21103
  throw error;
19849
21104
  }
19850
21105
  };
19851
- 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));
21106
+ 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));
19852
21107
  const scopeKeyOf = (params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "";
19853
21108
  const createAdminRouteHandlers = () => ({
19854
21109
  listBundles: onCore(async (core, request) => {
@@ -19880,11 +21135,34 @@ const createAdminRouteHandlers = () => ({
19880
21135
  const rows = await core.listReleaseCatalogs(input);
19881
21136
  return page(rows, input, (row) => row.scope_key);
19882
21137
  }),
21138
+ listReleaseScopeKeys: onCore(async (core, request) => {
21139
+ const input = keyset(new URL(request.url), 100, "asc");
21140
+ if (input.order !== "asc" || input.through !== void 0) throw new HandlerBadRequestError("Release scopes are listed ascending, by limit and cursor only.");
21141
+ const rows = await core.listReleaseScopeKeys({
21142
+ limit: input.limit,
21143
+ ...input.after === void 0 ? {} : { after: input.after }
21144
+ });
21145
+ return page(rows, input, (scopeKey) => scopeKey);
21146
+ }),
19883
21147
  getChannels: onCore(async (core, request) => {
19884
- const name = new URL(request.url).searchParams.get("name");
19885
- if (name === null) return json$2({ data: await core.listChannels() });
19886
- const channel = await core.findChannelByName(name);
19887
- return channel === null ? notFound() : json$2({ data: channel });
21148
+ const url = new URL(request.url);
21149
+ const name = url.searchParams.get("name");
21150
+ if (name !== null) {
21151
+ const channel = await core.findChannelByName(name);
21152
+ return channel === null ? notFound() : json$2({ data: channel });
21153
+ }
21154
+ const ids = url.searchParams.get("ids");
21155
+ if (ids !== null) {
21156
+ const list = ids.split(",").filter((id) => id.length > 0);
21157
+ if (list.length === 0 || list.length > MAX_IDS) throw new HandlerBadRequestError(`Channels by ID take ids=<channel id>,... with 1 to ${MAX_IDS} ids.`);
21158
+ return json$2({ data: await core.getChannels(list) });
21159
+ }
21160
+ if (url.searchParams.has("limit") || url.searchParams.has("cursor")) {
21161
+ const input = keyset(url, LIMITS.maxValue, "asc");
21162
+ const rows = await core.listChannels(input);
21163
+ return page(rows, input, (row) => row.name);
21164
+ }
21165
+ return json$2({ data: await core.listChannels() });
19888
21166
  }),
19889
21167
  createChannel: onCore(async (core, request) => {
19890
21168
  const { name } = await body(request);
@@ -19923,15 +21201,36 @@ const createAdminRouteHandlers = () => ({
19923
21201
  return row === null ? notFound() : json$2({ data: row });
19924
21202
  }),
19925
21203
  rebuildReleaseCatalog: onCore(async (core, _request, params) => json$2({ data: await core.rebuildReleaseCatalog(scopeKeyOf(params)) })),
21204
+ getReleaseByLabel: onCore(async (core, request) => {
21205
+ const url = new URL(request.url);
21206
+ const channel = url.searchParams.get("channel");
21207
+ const platform = platformOf(url);
21208
+ const label = Number(url.searchParams.get("label"));
21209
+ 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.");
21210
+ return json$2({ data: await core.getReleaseByLabel({
21211
+ channel,
21212
+ platform,
21213
+ label
21214
+ }) });
21215
+ }),
21216
+ fillReleaseLabels: onCore(async (core, request) => {
21217
+ const body = await request.json().catch(() => ({}));
21218
+ const input = body !== null && typeof body === "object" ? body : {};
21219
+ return json$2({ data: await core.fillReleaseLabels({
21220
+ dryRun: input.dryRun === true,
21221
+ catalogs: input.catalogs !== false
21222
+ }) });
21223
+ }),
19926
21224
  updateBundle: onCore(async (core, request, params) => {
19927
21225
  const bundleId = requireRouteParam(params, "id");
19928
- await core.updateBundle(bundleId, bundleUpdateOf(await request.json(), bundleId));
21226
+ const update = bundleUpdateOf(await request.json(), bundleId);
21227
+ await refusingInvalid(() => core.updateBundle(bundleId, update));
19929
21228
  return noContent();
19930
21229
  }),
19931
21230
  countBundles: onCore(async (core, request) => json$2({ data: await core.countBundles(platformOf(new URL(request.url))) })),
19932
21231
  countBundleChildren: onCore(async (core, request) => {
19933
21232
  const ids = (new URL(request.url).searchParams.get("ids") ?? "").split(",").filter((id) => id.length > 0);
19934
- if (ids.length === 0 || ids.length > 100) throw new HandlerBadRequestError("Bundle child counts take ids=<bundle id>,... with 1 to 100 ids.");
21233
+ if (ids.length === 0 || ids.length > MAX_IDS) throw new HandlerBadRequestError(`Bundle child counts take ids=<bundle id>,... with 1 to ${MAX_IDS} ids.`);
19935
21234
  return json$2({ data: await core.countBundleChildren(ids) });
19936
21235
  }),
19937
21236
  listBundleChildren: onCore(async (core, request, params) => {
@@ -19949,7 +21248,7 @@ const createAdminRouteHandlers = () => ({
19949
21248
  deployReleases: onCore(async (core, request) => {
19950
21249
  const { deployments } = await body(request);
19951
21250
  if (!Array.isArray(deployments) || deployments.length === 0 || !deployments.every(isDeployment)) throw new HandlerBadRequestError("Deploy needs deployments, each a bundle and its release policy.");
19952
- return json$2({ data: await core.deploy(deployments) }, 201);
21251
+ return json$2({ data: await refusingInvalid(() => core.deploy(deployments)) }, 201);
19953
21252
  }),
19954
21253
  promoteRelease: onCore(async (core, request, params) => {
19955
21254
  const input = await body(request);
@@ -19972,9 +21271,22 @@ const createAdminRouteHandlers = () => ({
19972
21271
  const url = new URL(request.url);
19973
21272
  const scope = nativeBuildScopeOf(url);
19974
21273
  const buildKey = url.searchParams.get("buildKey");
19975
- return json$2({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
21274
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
21275
+ const kind = url.searchParams.get("kind");
21276
+ const options = {
21277
+ ...buildKey === null ? {} : { buildKey },
21278
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
21279
+ ...builtInOlderThan === null ? {} : { builtInOlderThan },
21280
+ ...kind === null ? {} : { artifactKind: kind }
21281
+ };
21282
+ return json$2({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
21283
+ }),
21284
+ findNativeBuildSibling: onCore(async (core, _request, params) => {
21285
+ const build = await core.getNativeBuild(requireRouteParam(params, "id"));
21286
+ return json$2({ data: build === null ? null : await core.findNativeBuildSibling(build) });
19976
21287
  }),
19977
21288
  getNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
21289
+ findNativeBuildByBuiltInBundle: onCore(async (core, _request, params) => json$2({ data: await core.findNativeBuildByBuiltInBundle(requireRouteParam(params, "bundleId")) })),
19978
21290
  listNativeBuilds: onCore(async (core, request) => {
19979
21291
  const url = new URL(request.url);
19980
21292
  const input = keyset(url);
@@ -19986,14 +21298,97 @@ const createAdminRouteHandlers = () => ({
19986
21298
  }),
19987
21299
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
19988
21300
  const input = await body(request);
19989
- 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.");
21301
+ 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.");
19990
21302
  const submission = {
19991
21303
  destination: input.destination,
19992
21304
  version: input.version
19993
21305
  };
19994
21306
  return json$2({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
19995
21307
  }),
21308
+ markNativeBuild: onCore(async (core, request, params) => {
21309
+ const input = await body(request);
21310
+ if (!isRecord$5(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
21311
+ const mark = { storeBuild: input.storeBuild };
21312
+ return json$2({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
21313
+ }),
19996
21314
  deleteNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
21315
+ listIosDevices: onCore(async (core, request) => {
21316
+ const url = new URL(request.url);
21317
+ const input = keyset(url);
21318
+ const status = url.searchParams.get("status");
21319
+ return page(await refusingInvalid(() => core.listIosDevices({
21320
+ ...input,
21321
+ ...status === null ? {} : { status }
21322
+ })), input, ({ id }) => id);
21323
+ }),
21324
+ findIosDevice: onCore(async (core, _request, params) => json$2({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
21325
+ requestIosDevice: onCore(async (core, request) => {
21326
+ const input = await body(request);
21327
+ 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.");
21328
+ const device = {
21329
+ udid: input.udid,
21330
+ name: input.name,
21331
+ requestedBy: input.requestedBy
21332
+ };
21333
+ return json$2({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
21334
+ }),
21335
+ approveIosDevice: onCore(async (core, request, params) => {
21336
+ const input = await body(request);
21337
+ 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.");
21338
+ const approval = {
21339
+ approvedBy: input.approvedBy,
21340
+ ...input.name === void 0 ? {} : { name: input.name }
21341
+ };
21342
+ return json$2({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
21343
+ }),
21344
+ renameIosDevice: onCore(async (core, request, params) => {
21345
+ const input = await body(request);
21346
+ if (!isText$2(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
21347
+ const name = input.name;
21348
+ return json$2({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
21349
+ }),
21350
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
21351
+ const input = await body(request);
21352
+ const seen = input.seen;
21353
+ 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.");
21354
+ const outcome = {
21355
+ id: requireRouteParam(params, "id"),
21356
+ seen: {
21357
+ status: seen.status,
21358
+ approvedAtMs: seen.approvedAtMs
21359
+ },
21360
+ issuerId: input.issuerId,
21361
+ outcome: input.outcome,
21362
+ ...input.reason === void 0 ? {} : { reason: input.reason }
21363
+ };
21364
+ return json$2({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
21365
+ }),
21366
+ claimIosDeviceAccount: onCore(async (core, request) => {
21367
+ const { issuerId } = await body(request);
21368
+ if (!isText$2(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
21369
+ return json$2({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
21370
+ }),
21371
+ findIosDeviceAccount: onCore(async (core) => json$2({ data: await core.findIosDeviceAccount() })),
21372
+ markIosDevicesInBuild: onCore(async (core, request) => {
21373
+ const { buildId, ids } = await body(request);
21374
+ 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.");
21375
+ if (ids.length > MAX_IDS) throw new HandlerBadRequestError(`Marking iOS devices in a build takes at most ${MAX_IDS} ids a request.`);
21376
+ await core.markIosDevicesInBuild({
21377
+ buildId,
21378
+ ids
21379
+ });
21380
+ return noContent();
21381
+ }),
21382
+ deleteIosDevice: onCore(async (core, request, params) => {
21383
+ const url = new URL(request.url);
21384
+ const status = url.searchParams.get("status");
21385
+ const requestedBy = url.searchParams.get("requestedBy");
21386
+ const only = {
21387
+ ...status === null ? {} : { status },
21388
+ ...requestedBy === null ? {} : { requestedBy }
21389
+ };
21390
+ return json$2({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
21391
+ }),
19997
21392
  deleteBundles: onCore(async (core, request) => {
19998
21393
  const { ids } = await body(request);
19999
21394
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -20047,6 +21442,21 @@ const ADMIN_ROUTES = [
20047
21442
  path: "/release-catalogs",
20048
21443
  handler: "listReleaseCatalogs"
20049
21444
  },
21445
+ {
21446
+ method: "GET",
21447
+ path: "/release-scopes",
21448
+ handler: "listReleaseScopeKeys"
21449
+ },
21450
+ {
21451
+ method: "GET",
21452
+ path: "/release-labels",
21453
+ handler: "getReleaseByLabel"
21454
+ },
21455
+ {
21456
+ method: "POST",
21457
+ path: "/release-labels/fill",
21458
+ handler: "fillReleaseLabels"
21459
+ },
20050
21460
  {
20051
21461
  method: "POST",
20052
21462
  path: "/release-catalogs/:scopeKey/rebuild",
@@ -20122,6 +21532,16 @@ const ADMIN_ROUTES = [
20122
21532
  path: "/native-builds/latest",
20123
21533
  handler: "findNativeBuild"
20124
21534
  },
21535
+ {
21536
+ method: "GET",
21537
+ path: "/native-builds/built-in/:bundleId",
21538
+ handler: "findNativeBuildByBuiltInBundle"
21539
+ },
21540
+ {
21541
+ method: "GET",
21542
+ path: "/native-builds/:id/sibling",
21543
+ handler: "findNativeBuildSibling"
21544
+ },
20125
21545
  {
20126
21546
  method: "GET",
20127
21547
  path: "/native-builds/:id",
@@ -20137,10 +21557,65 @@ const ADMIN_ROUTES = [
20137
21557
  path: "/native-builds/:id/submission",
20138
21558
  handler: "recordNativeBuildSubmission"
20139
21559
  },
21560
+ {
21561
+ method: "POST",
21562
+ path: "/native-builds/:id/store-build",
21563
+ handler: "markNativeBuild"
21564
+ },
20140
21565
  {
20141
21566
  method: "DELETE",
20142
21567
  path: "/native-builds/:id",
20143
21568
  handler: "deleteNativeBuild"
21569
+ },
21570
+ {
21571
+ method: "GET",
21572
+ path: "/ios-devices",
21573
+ handler: "listIosDevices"
21574
+ },
21575
+ {
21576
+ method: "POST",
21577
+ path: "/ios-devices",
21578
+ handler: "requestIosDevice"
21579
+ },
21580
+ {
21581
+ method: "GET",
21582
+ path: "/ios-devices/udid/:udid",
21583
+ handler: "findIosDevice"
21584
+ },
21585
+ {
21586
+ method: "POST",
21587
+ path: "/ios-devices/in-build",
21588
+ handler: "markIosDevicesInBuild"
21589
+ },
21590
+ {
21591
+ method: "GET",
21592
+ path: "/ios-devices/account",
21593
+ handler: "findIosDeviceAccount"
21594
+ },
21595
+ {
21596
+ method: "POST",
21597
+ path: "/ios-devices/account",
21598
+ handler: "claimIosDeviceAccount"
21599
+ },
21600
+ {
21601
+ method: "POST",
21602
+ path: "/ios-devices/:id/approval",
21603
+ handler: "approveIosDevice"
21604
+ },
21605
+ {
21606
+ method: "POST",
21607
+ path: "/ios-devices/:id/outcome",
21608
+ handler: "recordIosDeviceOutcome"
21609
+ },
21610
+ {
21611
+ method: "PATCH",
21612
+ path: "/ios-devices/:id",
21613
+ handler: "renameIosDevice"
21614
+ },
21615
+ {
21616
+ method: "DELETE",
21617
+ path: "/ios-devices/:id",
21618
+ handler: "deleteIosDevice"
20144
21619
  }
20145
21620
  ];
20146
21621
  //#endregion
@@ -20215,38 +21690,53 @@ const catalogResponse = async (catalog, request) => {
20215
21690
  };
20216
21691
  const createReleaseCatalogRouteHandlers = () => {
20217
21692
  const cache = /* @__PURE__ */ new Map();
21693
+ const evict = (insertedHit) => {
21694
+ const now = Date.now();
21695
+ let oldestMiss;
21696
+ let oldest;
21697
+ for (const [key, entry] of cache) if (entry.expiresAt <= now) cache.delete(key);
21698
+ else {
21699
+ if (entry.row === null) oldestMiss ??= key;
21700
+ oldest ??= key;
21701
+ }
21702
+ if (cache.size <= ORIGIN_CACHE_MAX_ENTRIES) return;
21703
+ const victim = oldestMiss ?? (insertedHit ? oldest : void 0);
21704
+ if (victim !== void 0) cache.delete(victim);
21705
+ };
20218
21706
  const inFlight = /* @__PURE__ */ new Map();
20219
- const loadCatalog = async (key, load) => {
20220
- const cached = cache.get(key);
21707
+ const loadRow = async (scopeKey, load) => {
21708
+ const cached = cache.get(scopeKey);
20221
21709
  if (cached !== void 0 && cached.expiresAt > Date.now()) {
20222
- cache.delete(key);
20223
- cache.set(key, cached);
20224
- return cached.catalog;
21710
+ cache.delete(scopeKey);
21711
+ cache.set(scopeKey, cached);
21712
+ return cached.row;
20225
21713
  }
20226
- if (cached !== void 0) cache.delete(key);
20227
- const pending = inFlight.get(key);
21714
+ if (cached !== void 0) cache.delete(scopeKey);
21715
+ const pending = inFlight.get(scopeKey);
20228
21716
  if (pending !== void 0) return pending;
20229
- const next = load().then((catalog) => {
20230
- if (catalog !== null) {
20231
- cache.set(key, {
20232
- catalog,
20233
- expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
20234
- });
20235
- while (cache.size > ORIGIN_CACHE_MAX_ENTRIES) {
20236
- const oldestKey = cache.keys().next().value;
20237
- if (oldestKey === void 0) break;
20238
- cache.delete(oldestKey);
20239
- }
20240
- }
20241
- return catalog;
21717
+ const next = load().then((row) => {
21718
+ cache.set(scopeKey, {
21719
+ row,
21720
+ expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
21721
+ });
21722
+ if (cache.size > ORIGIN_CACHE_MAX_ENTRIES) evict(row !== null);
21723
+ return row;
20242
21724
  });
20243
- inFlight.set(key, next);
21725
+ inFlight.set(scopeKey, next);
20244
21726
  try {
20245
21727
  return await next;
20246
21728
  } finally {
20247
- inFlight.delete(key);
21729
+ inFlight.delete(scopeKey);
20248
21730
  }
20249
21731
  };
21732
+ const loadCatalog = async (core, input) => {
21733
+ const scopeKey = releaseCatalogScopeKeyOf(input);
21734
+ const parsed = await loadRow(scopeKey, async () => {
21735
+ const row = await core.getReleaseCatalogRow(scopeKey);
21736
+ return row === null ? null : parseReleaseCatalogRow(row);
21737
+ });
21738
+ return projectParsedReleaseCatalogRow(parsed, input, scopeKey);
21739
+ };
20250
21740
  return {
20251
21741
  appVersionReleaseCatalog: async (params, request, { core }) => {
20252
21742
  const rawAppVersion = requireRouteParam(params, "appVersion");
@@ -20260,7 +21750,7 @@ const createReleaseCatalogRouteHandlers = () => {
20260
21750
  };
20261
21751
  const invalid = invalidScope(input);
20262
21752
  if (invalid) return invalid;
20263
- return catalogResponse(await loadCatalog(`app-version:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
21753
+ return catalogResponse(await loadCatalog(core, input), request);
20264
21754
  },
20265
21755
  fingerprintReleaseCatalog: async (params, request, { core }) => {
20266
21756
  const input = {
@@ -20271,7 +21761,7 @@ const createReleaseCatalogRouteHandlers = () => {
20271
21761
  };
20272
21762
  const invalid = invalidScope(input);
20273
21763
  if (invalid) return invalid;
20274
- return catalogResponse(await loadCatalog(`fingerprint:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
21764
+ return catalogResponse(await loadCatalog(core, input), request);
20275
21765
  },
20276
21766
  artifactV2: async (params, _request, { core }) => {
20277
21767
  const info = await core.getArtifactInfo(requireRouteParam(params, "targetBundleId"), requireRouteParam(params, "currentBundleId"), 2);
@@ -23185,6 +24675,53 @@ const breakdownOf = (rows) => {
23185
24675
  };
23186
24676
  });
23187
24677
  };
24678
+ const FAILURE_ROWS_PER_HOUR = 20;
24679
+ const FAILURE_QUERY_LIMIT = Math.min(PAGE, 168);
24680
+ const failureRowsByHour = async (db, platform, channel, timeRange) => {
24681
+ const read = (end, cursor) => db.findAggregates("insights_failures", {
24682
+ index: "byScope",
24683
+ where: {
24684
+ platform,
24685
+ channel
24686
+ },
24687
+ range: {
24688
+ gte: timeRange.start,
24689
+ lt: end
24690
+ },
24691
+ order: "desc",
24692
+ limit: FAILURE_QUERY_LIMIT,
24693
+ ...cursor === void 0 ? {} : { cursor }
24694
+ });
24695
+ const rows = [];
24696
+ const cappedHours = [];
24697
+ const perHour = /* @__PURE__ */ new Map();
24698
+ let end = timeRange.end;
24699
+ let cursor;
24700
+ while (end > timeRange.start) {
24701
+ const page = await read(end, cursor);
24702
+ let capped;
24703
+ for (const row of page.rows) {
24704
+ const hour = row.bucket_start_ms;
24705
+ const count = (perHour.get(hour) ?? 0) + 1;
24706
+ if (count > FAILURE_ROWS_PER_HOUR) {
24707
+ capped = hour;
24708
+ break;
24709
+ }
24710
+ perHour.set(hour, count);
24711
+ rows.push(row);
24712
+ }
24713
+ if (capped !== void 0) {
24714
+ cappedHours.unshift(capped);
24715
+ end = capped;
24716
+ cursor = void 0;
24717
+ } else if (page.next === void 0) break;
24718
+ else cursor = page.next;
24719
+ }
24720
+ return {
24721
+ rows,
24722
+ cappedHours
24723
+ };
24724
+ };
23188
24725
  const getUpdateFailures = async (db, input, now, retention) => {
23189
24726
  const { platform, channel, releaseId, timeRange } = input;
23190
24727
  if (platform !== "ios" && platform !== "android" || !isText(channel, 1024) || releaseId !== void 0 && !isText(releaseId, 36) || !isRange(timeRange) || releaseId === void 0 && timeRange === void 0) throw new DatabaseAdapterInputError("invalid-query");
@@ -23245,7 +24782,7 @@ const getUpdateFailures = async (db, input, now, retention) => {
23245
24782
  days,
23246
24783
  kept.hour
23247
24784
  ];
23248
- const [counters, failures, checks, active, rows] = await Promise.all([
24785
+ const [counters, failures, checks, active, { rows, cappedHours }] = await Promise.all([
23249
24786
  counterRows(db, parts, ...window),
23250
24787
  sketchRows(db, failure, ...window),
23251
24788
  days ? sketchRows(db, {
@@ -23253,25 +24790,17 @@ const getUpdateFailures = async (db, input, now, retention) => {
23253
24790
  scopeKind: "check"
23254
24791
  }, ...window) : [],
23255
24792
  days ? sketchRows(db, usageParts(channel, platform), ...window) : [],
23256
- drain((page) => db.findAggregates("insights_failures", {
23257
- index: "byScope",
23258
- where: {
23259
- platform,
23260
- channel
23261
- },
23262
- range: {
23263
- gte: timeRange.start,
23264
- lt: timeRange.end
23265
- },
23266
- limit: PAGE,
23267
- ...page
23268
- }))
24793
+ failureRowsByHour(db, platform, channel, timeRange)
23269
24794
  ]);
23270
24795
  const total = (field) => counters.reduce((sum, row) => sum + row[field], 0);
23271
24796
  const scoped = rows.filter((row) => FAILURE_STAGES.has(row.stage) && (releaseId === void 0 || row.release_id === releaseId));
23272
24797
  const failuresAt = (counted) => scoped.reduce((sum, row) => sum + (counted(row.stage) ? Math.max(0, row.events) : 0), 0);
24798
+ const coverage = coverageOf(timeRange.start, kept.hour);
23273
24799
  return {
23274
- coverage: coverageOf(timeRange.start, kept.hour),
24800
+ coverage: cappedHours.length === 0 ? coverage : {
24801
+ kind: "partial",
24802
+ sinceMs: coverage.sinceMs
24803
+ },
23275
24804
  measuredAtMs: at,
23276
24805
  failedUpdates: failuresAt((stage) => stage !== "check"),
23277
24806
  failedInstallations: failed(failures),
@@ -23283,7 +24812,8 @@ const getUpdateFailures = async (db, input, now, retention) => {
23283
24812
  failedInstallations: failed(checks),
23284
24813
  activeInstallations: countDistinct(mergeDistinct(active.map((row) => row.activity_users)))
23285
24814
  } } : {},
23286
- breakdown: breakdownOf(scoped)
24815
+ breakdown: breakdownOf(scoped),
24816
+ ...cappedHours.length === 0 ? {} : { cappedHours }
23287
24817
  };
23288
24818
  };
23289
24819
  //#endregion