@hot-updater/firebase 1.2.0-rc.4 → 1.2.0-rc.41

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.
@@ -2102,7 +2102,10 @@ const CHANNEL_ID = {
2102
2102
  * every database's migrator creates missing tables and then records the
2103
2103
  * version, and none of them changes an existing table, so changing one
2104
2104
  * needs a migration step of its own first. The schema fence answers 503 on
2105
- * a database whose row differs, until it runs.
2105
+ * a database whose row differs, until it runs. Before a version is released,
2106
+ * its tables change in place in its own migration, and a database one of its
2107
+ * prereleases migrated takes the same change by hand: the fence compares this
2108
+ * row, not columns, so nothing reports it.
2106
2109
  */
2107
2110
  const HOT_UPDATER_SCHEMA_VERSION = "1.2.0";
2108
2111
  const bundles = defineTable({
@@ -2356,7 +2359,10 @@ const channels = defineTable({
2356
2359
  /**
2357
2360
  * The native builds `native-build android` and `native-build ios` track, newest first
2358
2361
  * in each scope: a platform, a channel, and the fingerprint or app version
2359
- * the build compiled in. `min_bundle_id` names the build's built-in bundle,
2362
+ * the build compiled in. A sandbox build's scope has no channel: its app ID,
2363
+ * URL scheme, artifact kind and distribution in its place, so pull requests
2364
+ * reuse it across channels, while `channel_id` still names the channel it
2365
+ * embeds. `min_bundle_id` names the build's built-in bundle,
2360
2366
  * a `bundles` row no release publishes. Its references keep no counters, so
2361
2367
  * adding this table changes no existing one; a channel with builds is
2362
2368
  * refused deletion through `byChannel`. `build_key` is the native build key
@@ -2366,6 +2372,27 @@ const channels = defineTable({
2366
2372
  * or `versionCode`. `submitted_to`, `submitted_at_ms` and
2367
2373
  * `submitted_version` record the store track a build went to, when, and
2368
2374
  * the store's label of the build; they stay null for a build no store took.
2375
+ * `is_store_build` is true on the build a person or a job says the store
2376
+ * sells, and false on every other: deploys patch from it over the scope's
2377
+ * newest build. The engine copies the scope key into `store_build_scope_key`
2378
+ * for that build alone, so `byStoreBuild` holds one entry per scope at most,
2379
+ * on every store, while any number of a scope's builds hold none.
2380
+ * `is_sandbox` is true on a sandbox build, set from its artifact when it
2381
+ * registers and never changed, and `sandbox_url_scheme` is the URL scheme its artifact registers,
2382
+ * which its preview links open; null on any other build, and on a sandbox
2383
+ * build registered before the column, which registered the derived one.
2384
+ * `export_method` is how an `.ipa` was exported, read from its profile when
2385
+ * it registers and never changed; null on any other artifact, on an `.ipa`
2386
+ * whose profile couldn't be read, and on one registered before the column.
2387
+ * `native_app_version` is the app version the artifact itself reports, its
2388
+ * `CFBundleShortVersionString` or `versionName`, read from the artifact when
2389
+ * it registers and never changed, whatever the update strategy; `app_version`
2390
+ * stays the version OTAs target, null on a fingerprint build. It is null
2391
+ * when the artifact's can't be read, and on a build registered before the
2392
+ * column.
2393
+ * Boolean columns follow one rule: `is_*` for a fact about the row or
2394
+ * `should_*` for an instruction to the client, never null; a unique index over
2395
+ * the rows where one is true keys a derived slot, not the boolean.
2369
2396
  */
2370
2397
  const nativeBuilds = defineTable({
2371
2398
  id: {
@@ -2442,9 +2469,34 @@ const nativeBuilds = defineTable({
2442
2469
  type: "string",
2443
2470
  maxLength: 255,
2444
2471
  required: false
2472
+ },
2473
+ is_store_build: { type: "boolean" },
2474
+ is_sandbox: { type: "boolean" },
2475
+ sandbox_url_scheme: {
2476
+ type: "string",
2477
+ maxLength: 255,
2478
+ ascii: true,
2479
+ required: false
2480
+ },
2481
+ export_method: {
2482
+ type: "string",
2483
+ maxLength: 16,
2484
+ required: false
2485
+ },
2486
+ native_app_version: {
2487
+ type: "string",
2488
+ required: false
2445
2489
  }
2446
2490
  }, {
2447
2491
  key: ["id"],
2492
+ derived: {
2493
+ /** The scope this build is the store build of; null on every other. */
2494
+ store_build_scope_key: {
2495
+ type: "string",
2496
+ maxLength: 2048,
2497
+ ascii: true,
2498
+ compute: (row) => row.is_store_build ? row.scope_key : null
2499
+ } },
2448
2500
  indexes: {
2449
2501
  byScope: {
2450
2502
  eq: ["scope_key"],
@@ -2454,6 +2506,11 @@ const nativeBuilds = defineTable({
2454
2506
  eq: ["scope_key", "build_key"],
2455
2507
  sort: ["id"]
2456
2508
  },
2509
+ byStoreBuild: {
2510
+ eq: ["store_build_scope_key"],
2511
+ sort: [],
2512
+ unique: true
2513
+ },
2457
2514
  byChannel: {
2458
2515
  eq: ["channel_id"],
2459
2516
  sort: ["id"],
@@ -2465,6 +2522,115 @@ const nativeBuilds = defineTable({
2465
2522
  }
2466
2523
  }
2467
2524
  });
2525
+ /**
2526
+ * The iPhones a team asks to install ad hoc builds on. A row decides what the
2527
+ * CLI registers with Apple, not what an export includes: Xcode's automatic ad
2528
+ * hoc profile lists every device the Apple account has enabled. `status` is
2529
+ * `pending` until someone approves it, `approved` until a build or
2530
+ * `native-build devices add` registers it with Apple, then `registered`;
2531
+ * declining or removing one deletes its row. `udid` is the UDID in lower case.
2532
+ * `apple_issuer_id` is the App Store Connect issuer whose key registered it,
2533
+ * set once: a build signed by another account never registers these rows.
2534
+ * `apple_error` is Apple's refusal of the device, or why it stopped counting
2535
+ * it, cleared by the next success. `build_id` is the newest native build whose
2536
+ * .ipa the CLI checked lists it; deleting that build never touches the row.
2537
+ * It holds personal data: a UDID, a name, and the emails of who asked and who
2538
+ * approved, null for the CLI.
2539
+ */
2540
+ const iosDevices = defineTable({
2541
+ id: {
2542
+ type: "string",
2543
+ maxLength: 36
2544
+ },
2545
+ udid: {
2546
+ type: "string",
2547
+ maxLength: 40,
2548
+ ascii: true,
2549
+ unique: true
2550
+ },
2551
+ name: {
2552
+ type: "string",
2553
+ maxLength: 100
2554
+ },
2555
+ status: {
2556
+ type: "string",
2557
+ maxLength: 16
2558
+ },
2559
+ requested_by: {
2560
+ type: "string",
2561
+ maxLength: 320,
2562
+ required: false
2563
+ },
2564
+ created_at_ms: { type: "integer" },
2565
+ approved_by: {
2566
+ type: "string",
2567
+ maxLength: 320,
2568
+ required: false
2569
+ },
2570
+ approved_at_ms: {
2571
+ type: "integer",
2572
+ required: false
2573
+ },
2574
+ registered_at_ms: {
2575
+ type: "integer",
2576
+ required: false
2577
+ },
2578
+ apple_issuer_id: {
2579
+ type: "string",
2580
+ maxLength: 64,
2581
+ ascii: true,
2582
+ required: false
2583
+ },
2584
+ apple_error: {
2585
+ type: "string",
2586
+ maxLength: 512,
2587
+ required: false
2588
+ },
2589
+ build_id: {
2590
+ type: "string",
2591
+ maxLength: 36,
2592
+ required: false
2593
+ }
2594
+ }, {
2595
+ key: ["id"],
2596
+ indexes: {
2597
+ byStatus: {
2598
+ eq: ["status"],
2599
+ sort: ["id"]
2600
+ },
2601
+ all: {
2602
+ eq: [],
2603
+ sort: ["id"]
2604
+ }
2605
+ }
2606
+ });
2607
+ /**
2608
+ * The Apple account the iOS device registry belongs to: one row, keyed
2609
+ * `registry`, holding the App Store Connect issuer that first registered a
2610
+ * device. A build claims it before it sends Apple anything, and its key makes
2611
+ * the claim atomic on every store, so two builds of two accounts can't both
2612
+ * spend a slot; another account's build then registers nothing. Removing
2613
+ * devices never releases it.
2614
+ */
2615
+ const iosDeviceAccount = defineTable({
2616
+ id: {
2617
+ type: "string",
2618
+ maxLength: 16,
2619
+ ascii: true
2620
+ },
2621
+ apple_issuer_id: {
2622
+ type: "string",
2623
+ maxLength: 64,
2624
+ ascii: true
2625
+ },
2626
+ claimed_at_ms: { type: "integer" }
2627
+ }, {
2628
+ key: ["id"],
2629
+ indexes: { all: {
2630
+ eq: [],
2631
+ sort: ["id"]
2632
+ } }
2633
+ });
2468
2634
  /** Core's module: always installed, never a plugin. */
2469
2635
  const coreModule = {
2470
2636
  id: "core",
@@ -2485,7 +2651,9 @@ const coreModule = {
2485
2651
  sort: []
2486
2652
  } }
2487
2653
  }),
2488
- native_builds: nativeBuilds
2654
+ native_builds: nativeBuilds,
2655
+ ios_devices: iosDevices,
2656
+ ios_device_account: iosDeviceAccount
2489
2657
  }
2490
2658
  };
2491
2659
  //#endregion
@@ -2674,15 +2842,8 @@ const LEASE_TABLE = "aggregate_lease";
2674
2842
  const LEASE = { id: "compaction" };
2675
2843
  /** How long a compaction holds the lease before another process may take it. */
2676
2844
  const LEASE_MS = 3e4;
2677
- /**
2678
- * Default windows: log mode compacts every 60 seconds, since reads compact
2679
- * first; memory mode flushes every 15, since its window is what a crash
2680
- * loses.
2681
- */
2682
- const WINDOW_MS$1 = {
2683
- log: 6e4,
2684
- memory: 15e3
2685
- };
2845
+ /** A commit compacts once this has passed since the last compaction. */
2846
+ const WINDOW_MS$1 = 6e4;
2686
2847
  /** Log rows a compaction reads from each log table for one group. */
2687
2848
  const LOG_PAGE = 200;
2688
2849
  /**
@@ -2696,8 +2857,6 @@ const GROUPS = {
2696
2857
  };
2697
2858
  /** Tries per write after a conflict or a transient error. */
2698
2859
  const ATTEMPTS = 5;
2699
- /** Aggregate rows a memory buffer holds before a commit waits for a flush. */
2700
- const MAX_BUFFERED = 1e4;
2701
2860
  const log = defineTable({
2702
2861
  id: {
2703
2862
  type: "string",
@@ -2747,7 +2906,7 @@ const valuesOf = ({ deltas, sketches }) => ({
2747
2906
  /**
2748
2907
  * Merges `values` into the change for `key`'s identity as `tx.aggregate`
2749
2908
  * does: deltas add up and sketches merge. One constant `shardBy` keys each
2750
- * identity to one entry; the write picks the shard.
2909
+ * identity to one entry; `compile` writes it to shard 0.
2751
2910
  */
2752
2911
  const merge = (into, model, key, values) => recordAggregate(into, model, Object.fromEntries(shapeOf(model).key.map((field, at) => [field, key[at]])), values, "");
2753
2912
  const mergeAll = (into, changes) => {
@@ -2781,7 +2940,7 @@ const increment = ({ model, deltas }, key) => Object.values(deltas).some((delta)
2781
2940
  /**
2782
2941
  * The guarded write that merges `change` into `current`: insert, patch, or
2783
2942
  * delete at zero. Unlike a transaction's, a gauge may go below zero here: a
2784
- * shard row holds one writer's net changes, and reads sum every shard.
2943
+ * group can hold a loss without the gain before it, and reads sum every shard.
2785
2944
  */
2786
2945
  const rewrite = (change, key, current) => {
2787
2946
  const { model } = change;
@@ -2819,12 +2978,12 @@ const rewrite = (change, key, current) => {
2819
2978
  };
2820
2979
  };
2821
2980
  /**
2822
- * The write for each change on its shard: a blind increment that creates
2823
- * the row for counters, and a guarded rewrite for gauges and sketches, whose
2824
- * rows are read in one batch per table.
2981
+ * The write for each change on shard 0, since one compaction runs at a time:
2982
+ * a blind increment that creates the row for counters, and a guarded rewrite
2983
+ * for gauges and sketches, whose rows are read in one batch per table.
2825
2984
  */
2826
- const compile = async (adapter, changes, shard) => {
2827
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
2985
+ const compile = async (adapter, changes) => {
2986
+ const keys = changes.map(({ key }) => [...key.slice(0, -1), 0]);
2828
2987
  const reads = /* @__PURE__ */ new Map();
2829
2988
  changes.forEach((change, at) => {
2830
2989
  if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
@@ -2878,14 +3037,13 @@ const encode$1 = async (changes) => {
2878
3037
  return zipped !== void 0 && zipped.length < json.length ? `z${zipped}` : json;
2879
3038
  };
2880
3039
  /**
2881
- * Batches changes to aggregates declared `batched`. A transaction records
2882
- * them without writing their rows; once it commits, "memory" mode keeps
2883
- * them in this process until its timer flushes them, and "log" mode has
2884
- * written them as one log row in the same atomic write, which a compaction
2885
- * later merges into the aggregates and deletes, atomically again, so each
2886
- * applies exactly once. One lease row keeps compactions one at a time.
3040
+ * Batches changes to aggregates declared `batched`. A transaction writes
3041
+ * them as one log row in its own atomic write, in place of their rows; a
3042
+ * compaction later merges log rows into the aggregates and deletes them,
3043
+ * atomically again, so each applies exactly once. One lease row keeps
3044
+ * compactions one at a time.
2887
3045
  */
2888
- const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS$1[mode] }, now }) => {
3046
+ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs = WINDOW_MS$1 }, now }) => {
2889
3047
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
2890
3048
  const holder = crypto.randomUUID().replaceAll("-", "");
2891
3049
  const table = (name) => schema.models.get(name).table;
@@ -2913,68 +3071,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
2913
3071
  }
2914
3072
  return changes;
2915
3073
  };
2916
- /**
2917
- * Writes changes in atomic chunks within `fits`, and returns the ones it
2918
- * could not apply. A write whose outcome is unknown is dropped, never
2919
- * resent, so no change applies twice.
2920
- */
2921
- const apply = async (changes, shard) => {
2922
- let rest = changes;
2923
- let ops = [];
2924
- let read = true;
2925
- for (let failures = 0; rest.length > 0 && failures < ATTEMPTS;) try {
2926
- if (read) ops = await compile(adapter, rest, shard);
2927
- let size = rest.length;
2928
- const chunk = () => ops.slice(0, size).filter(isOp);
2929
- while (size > 1 && !adapter.fits(chunk())) size = Math.ceil(size / 2);
2930
- let result = { ok: true };
2931
- if (chunk().length > 0) result = await adapter.write(chunk()).catch((error) => {
2932
- warn("flush")(error);
2933
- return { ok: true };
2934
- });
2935
- read = !result.ok && !("retry" in result);
2936
- if (result.ok) {
2937
- rest = rest.slice(size);
2938
- ops = ops.slice(size);
2939
- failures = 0;
2940
- } else {
2941
- failures += 1;
2942
- if (!read) await sleep(failures);
2943
- }
2944
- } catch (error) {
2945
- warn("flush")(error);
2946
- return rest;
2947
- }
2948
- return rest;
2949
- };
2950
- let buffer = /* @__PURE__ */ new Map();
2951
- let timer;
2952
- let flushing;
2953
- const shards = /* @__PURE__ */ new Map();
2954
- /** Each process writes its own shard, so flushes of two processes rarely meet. */
2955
- const processShard = (model) => {
2956
- if (!shards.has(model)) shards.set(model, Math.floor(Math.random() * shapeOf(model).shards));
2957
- return shards.get(model);
2958
- };
2959
- const schedule = () => {
2960
- if (timer !== void 0 || buffer.size === 0) return;
2961
- timer = setTimeout(() => {
2962
- timer = void 0;
2963
- flushBuffer();
2964
- }, windowMs);
2965
- timer.unref?.();
2966
- };
2967
- /** Never rejects: what it cannot apply goes back into the buffer. */
2968
- const flushBuffer = () => flushing ??= (async () => {
2969
- clearTimeout(timer);
2970
- timer = void 0;
2971
- const pending = [...buffer.values()];
2972
- buffer = /* @__PURE__ */ new Map();
2973
- mergeAll(buffer, await apply(pending, processShard));
2974
- })().catch(warn("flush")).finally(() => {
2975
- flushing = void 0;
2976
- schedule();
2977
- });
2978
3074
  let nextDue = 0;
2979
3075
  let compacting;
2980
3076
  /** Log rows this process read, by `[log table's index, id]`, for the deletes after a group. */
@@ -3109,7 +3205,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3109
3205
  more
3110
3206
  };
3111
3207
  };
3112
- const rowsFor = async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp);
3208
+ const rowsFor = async (changes) => (await compile(adapter, changes)).filter(isOp);
3113
3209
  /**
3114
3210
  * Applies the oldest pending log rows whose merged changes fit in one
3115
3211
  * atomic write with the lease, which lists them as applied; the rows are
@@ -3203,20 +3299,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3203
3299
  }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
3204
3300
  checking = void 0;
3205
3301
  });
3206
- /** Takes a committed transaction's changes; never rejects, since the transaction already committed. */
3207
- const committed = async (changes) => {
3208
- if (mode === "log") {
3209
- if (now() >= nextDue) await compact(false, GROUPS.commit);
3210
- return;
3211
- }
3212
- mergeAll(buffer, changes.values());
3213
- schedule();
3214
- if (buffer.size >= MAX_BUFFERED) await flushBuffer();
3215
- };
3216
- const flush = async () => {
3217
- await flushBuffer();
3218
- if (mode === "log" && await hasPending()) await compact(true, GROUPS.flush);
3219
- };
3220
3302
  return {
3221
3303
  async transaction(fn) {
3222
3304
  let changes = /* @__PURE__ */ new Map();
@@ -3242,7 +3324,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3242
3324
  aggregate
3243
3325
  });
3244
3326
  if (failure) throw failure.error;
3245
- if (mode === "log" && attempt.size > 0) {
3327
+ if (attempt.size > 0) {
3246
3328
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
3247
3329
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
3248
3330
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -3256,24 +3338,18 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3256
3338
  open = false;
3257
3339
  }
3258
3340
  });
3259
- if (changes.size > 0) await committed(changes);
3341
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
3260
3342
  return result;
3261
3343
  },
3262
3344
  async beforeRead(name) {
3263
3345
  if (!isBatched(schema.models.get(name))) return;
3264
- if (buffer.size > 0 || flushing !== void 0) await flushBuffer();
3265
- if (mode === "log") {
3266
- if (await hasPending().catch((error) => {
3267
- warn("read")(error);
3268
- return false;
3269
- })) await compact(true, GROUPS.read);
3270
- }
3346
+ if (await hasPending().catch((error) => {
3347
+ warn("read")(error);
3348
+ return false;
3349
+ })) await compact(true, GROUPS.read);
3271
3350
  },
3272
- flush,
3273
- async dispose() {
3274
- clearTimeout(timer);
3275
- timer = void 0;
3276
- await flush();
3351
+ async flush() {
3352
+ if (await hasPending()) await compact(true, GROUPS.flush);
3277
3353
  }
3278
3354
  };
3279
3355
  };
@@ -3415,7 +3491,8 @@ const fieldProblems = (definition, add) => {
3415
3491
  else if (field.required === false) add(`key field "${name}" is nullable`);
3416
3492
  else if (field.type === "json") add(`key field "${name}" is json`);
3417
3493
  }
3418
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
3494
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
3495
+ for (const [name, { type, maxLength, ascii }] of bounded) {
3419
3496
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
3420
3497
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
3421
3498
  }
@@ -3532,11 +3609,13 @@ const resolveSchema = (modules) => {
3532
3609
  ...maxLength === void 0 ? {} : { maxLength },
3533
3610
  ...ascii ? { ascii } : {}
3534
3611
  }));
3535
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
3612
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
3536
3613
  name: field,
3537
3614
  type,
3538
3615
  nullable: true,
3539
- ...multi ? { multi } : {}
3616
+ ...multi ? { multi } : {},
3617
+ ...maxLength === void 0 ? {} : { maxLength },
3618
+ ...ascii ? { ascii } : {}
3540
3619
  });
3541
3620
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
3542
3621
  name: metric,
@@ -4302,13 +4381,10 @@ const createDatabaseEngine = ({ batching, now = Date.now, meter, ...options }) =
4302
4381
  };
4303
4382
  return {
4304
4383
  ...engine,
4305
- /** Applies batched aggregate changes still pending: this process's buffer and the log. */
4384
+ /** Applies the batched aggregate changes still in the log. */
4306
4385
  flush: async () => {
4307
4386
  await batches?.flush();
4308
4387
  },
4309
- dispose: async () => {
4310
- await batches?.dispose();
4311
- },
4312
4388
  database(module) {
4313
4389
  const name = (model) => module.namespace ? `${module.namespace}_${model}` : model;
4314
4390
  return {
@@ -4389,8 +4465,7 @@ const createEngine = (database, { plugins = [], now = Date.now } = {}) => {
4389
4465
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
4390
4466
  return engine.database(module);
4391
4467
  },
4392
- flush: () => engine.flush(),
4393
- dispose: () => engine.dispose()
4468
+ flush: () => engine.flush()
4394
4469
  };
4395
4470
  };
4396
4471
  //#endregion
@@ -4683,7 +4758,7 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
4683
4758
  };
4684
4759
  //#endregion
4685
4760
  //#region ../../packages/server/dist/version.mjs
4686
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.4";
4761
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.41";
4687
4762
  //#endregion
4688
4763
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
4689
4764
  /**
@@ -5476,8 +5551,8 @@ const baseBundleIdsOf = (row, range, bundleId, limit) => {
5476
5551
  //#endregion
5477
5552
  //#region ../../packages/server/dist/core/reads.mjs
5478
5553
  const PAGE$3 = 500;
5479
- const pick$1 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
5480
- const toBundleRow = pick$1([
5554
+ const pick$2 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
5555
+ const toBundleRow = pick$2([
5481
5556
  "id",
5482
5557
  "platform",
5483
5558
  "git_commit_hash",
@@ -5486,7 +5561,7 @@ const toBundleRow = pick$1([
5486
5561
  "manifest_file_hash",
5487
5562
  "asset_base_storage_uri"
5488
5563
  ]);
5489
- const toPatchRow = pick$1([
5564
+ const toPatchRow = pick$2([
5490
5565
  "id",
5491
5566
  "bundle_id",
5492
5567
  "base_bundle_id",
@@ -5496,7 +5571,7 @@ const toPatchRow = pick$1([
5496
5571
  "byte_size",
5497
5572
  "order_index"
5498
5573
  ]);
5499
- const toReleaseRow = pick$1([
5574
+ const toReleaseRow = pick$2([
5500
5575
  "id",
5501
5576
  "revision",
5502
5577
  "scope_key",
@@ -5517,7 +5592,7 @@ const toReleaseRow = pick$1([
5517
5592
  "created_at_ms",
5518
5593
  "updated_at_ms"
5519
5594
  ]);
5520
- const toCatalogRow = pick$1([
5595
+ const toCatalogRow = pick$2([
5521
5596
  "scope_key",
5522
5597
  "catalog_id",
5523
5598
  "strategy",
@@ -5532,7 +5607,7 @@ const toCatalogRow = pick$1([
5532
5607
  "is_tombstone",
5533
5608
  "updated_at_ms"
5534
5609
  ]);
5535
- const toChannelRow = pick$1(["id", "name"]);
5610
+ const toChannelRow = pick$2(["id", "name"]);
5536
5611
  /** Every page of one read, in order. */
5537
5612
  const drain$1 = async (read) => {
5538
5613
  const rows = [];
@@ -5545,7 +5620,15 @@ const drain$1 = async (read) => {
5545
5620
  return rows;
5546
5621
  };
5547
5622
  /** A keyset page's range: the keys strictly after `after`, in `order`. */
5548
- const after = (input) => input.after === void 0 ? {} : { range: (input.order ?? "asc") === "asc" ? { gt: input.after } : { lt: input.after } };
5623
+ /** A keyset read's range on its index's order: past `after`, up to `through`. */
5624
+ const after = (input) => {
5625
+ const asc = (input.order ?? "asc") === "asc";
5626
+ const range = {
5627
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
5628
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
5629
+ };
5630
+ return Object.keys(range).length === 0 ? {} : { range };
5631
+ };
5549
5632
  /** Core's reads, each through one declared index or key. */
5550
5633
  const createCoreReads = (db, storage) => {
5551
5634
  /** A bundle row's patches, exactly as many as its reference counter holds. */
@@ -5750,6 +5833,326 @@ const createCoreReads = (db, storage) => {
5750
5833
  };
5751
5834
  };
5752
5835
  //#endregion
5836
+ //#region ../../packages/server/dist/core/iosDevices.mjs
5837
+ /**
5838
+ * A device's UDID: 40 hex digits, or 8 and 16 joined by a hyphen. The same
5839
+ * rule as `normalizeIosUdid` of `@hot-updater/protocol/native-artifact`,
5840
+ * implemented here so the server's runtime never loads the artifact readers.
5841
+ */
5842
+ const UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
5843
+ /** The form the registry stores and compares a UDID in, or null for text that isn't one. */
5844
+ const normalizeIosUdid = (value) => {
5845
+ const trimmed = value.trim();
5846
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
5847
+ };
5848
+ /** `ios_devices.name`'s bound in core's schema. */
5849
+ const NAME_MAX_LENGTH = 100;
5850
+ /** `ios_devices.requested_by` and `approved_by`'s bound: an email address. */
5851
+ const EMAIL_MAX_LENGTH = 320;
5852
+ /** `ios_devices.apple_issuer_id`'s bound. */
5853
+ const ISSUER_MAX_LENGTH = 64;
5854
+ /** How many registry rows one read takes while finding its account. */
5855
+ const ACCOUNT_SCAN_PAGE = 200;
5856
+ /** The one row of `ios_device_account`. */
5857
+ const ACCOUNT_ROW = "registry";
5858
+ /** `ios_devices.apple_error`'s bound. */
5859
+ const ERROR_MAX_LENGTH = 512;
5860
+ const STATUSES = [
5861
+ "pending",
5862
+ "approved",
5863
+ "registered"
5864
+ ];
5865
+ const OUTCOMES = [
5866
+ "registered",
5867
+ "refused",
5868
+ "disabled",
5869
+ "missing"
5870
+ ];
5871
+ /** The `apple_error` of a device Apple has disabled. */
5872
+ const IOS_DEVICE_DISABLED_ERROR = "Disabled in the Apple account.";
5873
+ /** The `apple_error` of a registered device Apple no longer lists. */
5874
+ const IOS_DEVICE_MISSING_ERROR = "Gone from the Apple account. Approve it again to register it.";
5875
+ /** A device or registry request core cannot store: the caller's input. */
5876
+ var IosDeviceInputError = class extends TypeError {
5877
+ name = "IosDeviceInputError";
5878
+ };
5879
+ const pick$1 = (row) => ({
5880
+ id: row.id,
5881
+ udid: row.udid,
5882
+ name: row.name,
5883
+ status: row.status,
5884
+ requested_by: row.requested_by ?? null,
5885
+ created_at_ms: row.created_at_ms,
5886
+ approved_by: row.approved_by ?? null,
5887
+ approved_at_ms: row.approved_at_ms ?? null,
5888
+ registered_at_ms: row.registered_at_ms ?? null,
5889
+ apple_issuer_id: row.apple_issuer_id ?? null,
5890
+ apple_error: row.apple_error ?? null,
5891
+ build_id: row.build_id ?? null
5892
+ });
5893
+ const udidOf = (udid) => {
5894
+ const key = typeof udid === "string" ? normalizeIosUdid(udid) : null;
5895
+ if (key === null) throw new IosDeviceInputError("Invalid iOS device: udid must be 40 hex digits, or 8 and 16 joined by a hyphen.");
5896
+ return key;
5897
+ };
5898
+ const nameOf = (name) => {
5899
+ const trimmed = typeof name === "string" ? name.trim() : "";
5900
+ if (trimmed.length === 0 || trimmed.length > NAME_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: name must be 1 to ${NAME_MAX_LENGTH} characters.`);
5901
+ return trimmed;
5902
+ };
5903
+ /** An email, lower-cased, or null for the CLI. */
5904
+ const personOf = (value, field) => {
5905
+ if (value === null) return null;
5906
+ const email = typeof value === "string" ? value.trim().toLowerCase() : "";
5907
+ 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.`);
5908
+ return email;
5909
+ };
5910
+ /** Apple's words, on one line and within the column's bound. */
5911
+ const errorText = (text) => {
5912
+ const line = text.replace(/\s+/gu, " ").trim();
5913
+ return line.length > ERROR_MAX_LENGTH ? `${line.slice(0, 511)}…` : line;
5914
+ };
5915
+ /**
5916
+ * The iOS device registry: the iPhones and iPads a team asked to install ad hoc
5917
+ * builds on. The Console writes requests and approvals, and the CLI what Apple
5918
+ * said, each over the row it read.
5919
+ */
5920
+ const createIosDeviceApi = (db, { now = Date.now } = {}) => {
5921
+ const findIosDevice = async (udid) => {
5922
+ const key = normalizeIosUdid(udid);
5923
+ if (key === null) return null;
5924
+ const row = await db.findOne("ios_devices", { udid: key });
5925
+ return row === null ? null : pick$1(row);
5926
+ };
5927
+ /**
5928
+ * The issuer of the registry's earliest registration among its rows, by
5929
+ * when and then by ID, or null when no row names one: read only while the
5930
+ * registry has no account yet, a page at a time.
5931
+ */
5932
+ const accountOfRows = async () => {
5933
+ let earliest = null;
5934
+ for (let after;;) {
5935
+ const { rows } = await db.findMany("ios_devices", {
5936
+ index: "all",
5937
+ where: {},
5938
+ order: "asc",
5939
+ limit: ACCOUNT_SCAN_PAGE,
5940
+ ...after === void 0 ? {} : { range: { gt: after } }
5941
+ });
5942
+ for (const row of rows.map(pick$1)) {
5943
+ if (row.apple_issuer_id === null) continue;
5944
+ if (earliest === null || (row.registered_at_ms ?? 0) < (earliest.registered_at_ms ?? 0)) earliest = row;
5945
+ }
5946
+ if (rows.length < ACCOUNT_SCAN_PAGE) return earliest?.apple_issuer_id ?? null;
5947
+ after = rows.at(-1).id;
5948
+ }
5949
+ };
5950
+ return {
5951
+ async listIosDevices(input) {
5952
+ if (input.status !== void 0 && !STATUSES.includes(input.status)) throw new IosDeviceInputError(`Invalid iOS device status: ${String(input.status)}. Expected ${STATUSES.join(", ")}.`);
5953
+ const page = {
5954
+ order: input.order ?? "asc",
5955
+ limit: input.limit,
5956
+ ...after(input)
5957
+ };
5958
+ const { rows } = input.status === void 0 ? await db.findMany("ios_devices", {
5959
+ index: "all",
5960
+ where: {},
5961
+ ...page
5962
+ }) : await db.findMany("ios_devices", {
5963
+ index: "byStatus",
5964
+ where: { status: input.status },
5965
+ ...page
5966
+ });
5967
+ return rows.map(pick$1);
5968
+ },
5969
+ findIosDevice,
5970
+ async requestIosDevice(input) {
5971
+ const udid = udidOf(input.udid);
5972
+ const name = nameOf(input.name);
5973
+ const requestedBy = personOf(input.requestedBy, "requestedBy");
5974
+ const existing = await db.findOne("ios_devices", { udid });
5975
+ if (existing !== null) return {
5976
+ device: pick$1(existing),
5977
+ created: false
5978
+ };
5979
+ const device = {
5980
+ id: createUUIDv7(),
5981
+ udid,
5982
+ name,
5983
+ status: "pending",
5984
+ requested_by: requestedBy,
5985
+ created_at_ms: now(),
5986
+ approved_by: null,
5987
+ approved_at_ms: null,
5988
+ registered_at_ms: null,
5989
+ apple_issuer_id: null,
5990
+ apple_error: null,
5991
+ build_id: null
5992
+ };
5993
+ try {
5994
+ await db.transaction(async (tx) => {
5995
+ tx.create("ios_devices", device);
5996
+ });
5997
+ } catch (error) {
5998
+ if (error instanceof DatabaseConstraintError && error.reason === "unique") {
5999
+ const winner = await db.findOne("ios_devices", { udid });
6000
+ if (winner !== null) return {
6001
+ device: pick$1(winner),
6002
+ created: false
6003
+ };
6004
+ }
6005
+ throw error;
6006
+ }
6007
+ return {
6008
+ device,
6009
+ created: true
6010
+ };
6011
+ },
6012
+ async approveIosDevice(id, input) {
6013
+ const name = input.name === void 0 ? void 0 : nameOf(input.name);
6014
+ const approvedBy = personOf(input.approvedBy, "approvedBy");
6015
+ return db.transaction(async (tx) => {
6016
+ const row = await tx.findOne("ios_devices", { id });
6017
+ if (row === null) return null;
6018
+ const device = pick$1(row);
6019
+ const set = {
6020
+ ...name === void 0 || name === device.name ? {} : { name },
6021
+ ...device.status === "pending" ? {
6022
+ status: "approved",
6023
+ approved_by: approvedBy,
6024
+ approved_at_ms: now()
6025
+ } : {}
6026
+ };
6027
+ if (Object.keys(set).length === 0) return device;
6028
+ tx.update("ios_devices", row, set);
6029
+ return {
6030
+ ...device,
6031
+ ...set
6032
+ };
6033
+ });
6034
+ },
6035
+ async renameIosDevice(id, input) {
6036
+ const name = nameOf(input);
6037
+ return db.transaction(async (tx) => {
6038
+ const row = await tx.findOne("ios_devices", { id });
6039
+ if (row === null) return null;
6040
+ const device = pick$1(row);
6041
+ if (device.name === name) return device;
6042
+ tx.update("ios_devices", row, { name });
6043
+ return {
6044
+ ...device,
6045
+ name
6046
+ };
6047
+ });
6048
+ },
6049
+ async recordIosDeviceOutcome({ id, seen, issuerId, outcome, reason }) {
6050
+ if (!OUTCOMES.includes(outcome)) throw new IosDeviceInputError(`Invalid iOS device outcome: ${String(outcome)}. Expected ${OUTCOMES.join(", ")}.`);
6051
+ 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.`);
6052
+ return db.transaction(async (tx) => {
6053
+ const row = await tx.findOne("ios_devices", { id });
6054
+ if (row === null) return null;
6055
+ const device = pick$1(row);
6056
+ if (device.status !== seen.status || device.approved_at_ms !== seen.approvedAtMs || device.apple_issuer_id !== null && device.apple_issuer_id !== issuerId) return null;
6057
+ let set;
6058
+ switch (outcome) {
6059
+ case "registered":
6060
+ if (device.status === "pending") return null;
6061
+ set = {
6062
+ status: "registered",
6063
+ registered_at_ms: device.registered_at_ms ?? now(),
6064
+ apple_issuer_id: issuerId,
6065
+ apple_error: null
6066
+ };
6067
+ break;
6068
+ case "refused":
6069
+ if (device.status !== "approved") return null;
6070
+ set = { apple_error: errorText(reason === void 0 || reason.trim() === "" ? "Apple refused it." : reason) };
6071
+ break;
6072
+ case "disabled":
6073
+ if (device.status === "pending") return null;
6074
+ set = { apple_error: IOS_DEVICE_DISABLED_ERROR };
6075
+ break;
6076
+ case "missing":
6077
+ if (device.status !== "registered") return null;
6078
+ set = {
6079
+ status: "pending",
6080
+ approved_by: null,
6081
+ approved_at_ms: null,
6082
+ apple_error: IOS_DEVICE_MISSING_ERROR
6083
+ };
6084
+ }
6085
+ if (Object.entries(set).some(([column, value]) => device[column] !== (value ?? null))) tx.update("ios_devices", row, set);
6086
+ return {
6087
+ ...device,
6088
+ ...set
6089
+ };
6090
+ });
6091
+ },
6092
+ async markIosDevicesInBuild({ buildId, ids }) {
6093
+ for (const id of new Set(ids)) await db.transaction(async (tx) => {
6094
+ const row = await tx.findOne("ios_devices", { id });
6095
+ if (row === null || typeof row.build_id === "string" && row.build_id >= buildId) return;
6096
+ tx.update("ios_devices", row, { build_id: buildId });
6097
+ });
6098
+ },
6099
+ async findIosDeviceAccount() {
6100
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6101
+ const issuerId = existing === null ? await accountOfRows() : existing.apple_issuer_id;
6102
+ return issuerId === null ? null : { issuerId };
6103
+ },
6104
+ async claimIosDeviceAccount(issuerId) {
6105
+ 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.`);
6106
+ const answer = (held) => ({
6107
+ issuerId: held,
6108
+ claimed: held === issuerId
6109
+ });
6110
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6111
+ if (existing !== null) return answer(existing.apple_issuer_id);
6112
+ const holder = await accountOfRows() ?? issuerId;
6113
+ try {
6114
+ await db.transaction(async (tx) => {
6115
+ tx.create("ios_device_account", {
6116
+ id: ACCOUNT_ROW,
6117
+ apple_issuer_id: holder,
6118
+ claimed_at_ms: now()
6119
+ });
6120
+ });
6121
+ return answer(holder);
6122
+ } catch (error) {
6123
+ if (error instanceof DatabaseConstraintError && (error.reason === "exists" || error.reason === "unique")) {
6124
+ const winner = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6125
+ if (winner !== null) return answer(winner.apple_issuer_id);
6126
+ }
6127
+ throw error;
6128
+ }
6129
+ },
6130
+ async deleteIosDevice(id, only) {
6131
+ const requestedBy = only?.requestedBy === void 0 ? void 0 : personOf(only.requestedBy, "requestedBy");
6132
+ return db.transaction(async (tx) => {
6133
+ const row = await tx.findOne("ios_devices", { id });
6134
+ if (row === null) return null;
6135
+ const device = pick$1(row);
6136
+ if (only?.status !== void 0 && device.status !== only.status || requestedBy !== void 0 && device.requested_by !== requestedBy) return null;
6137
+ await tx.delete("ios_devices", row);
6138
+ return device;
6139
+ });
6140
+ }
6141
+ };
6142
+ };
6143
+ //#endregion
6144
+ //#region ../../packages/server/dist/core/nativeBuildDestinations.mjs
6145
+ /** Store destinations accepted for each native platform. */
6146
+ const NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
6147
+ android: [
6148
+ "play-internal",
6149
+ "play-closed",
6150
+ "play-open",
6151
+ "play-production"
6152
+ ],
6153
+ ios: ["testflight"]
6154
+ };
6155
+ //#endregion
5753
6156
  //#region ../../packages/server/dist/core/writes.mjs
5754
6157
  const PAGE$2 = 500;
5755
6158
  /** Moves one bundle into or out of its platform's total and the overall total. */
@@ -5779,8 +6182,10 @@ const deleteBundle = async (tx, current) => {
5779
6182
  /**
5780
6183
  * Replaces a bundle's patches with `rows`: kept patches are updated where
5781
6184
  * they changed, others deleted or created, so no key is written twice.
6185
+ * `checkNew` sees each patch it is about to create, and refuses one by
6186
+ * throwing, which leaves the transaction's writes undone.
5782
6187
  */
5783
- const replaceBundlePatches = async (tx, bundle, rows) => {
6188
+ const replaceBundlePatches = async (tx, bundle, rows, checkNew) => {
5784
6189
  const wanted = new Map(rows.map((row) => [row.id, row]));
5785
6190
  const count = bundle._refs_bundle_patches_bundle_id ?? 0;
5786
6191
  let cursor;
@@ -5805,6 +6210,7 @@ const replaceBundlePatches = async (tx, bundle, rows) => {
5805
6210
  if (page.next === void 0) break;
5806
6211
  cursor = page.next;
5807
6212
  }
6213
+ if (checkNew !== void 0) for (const row of wanted.values()) await checkNew(row);
5808
6214
  for (const row of wanted.values()) tx.create("bundle_patches", row);
5809
6215
  };
5810
6216
  /** A channel by name, created when missing; a concurrent creator's row is returned instead. */
@@ -5867,6 +6273,27 @@ const GIT_COMMIT_HASH_MAX_LENGTH = 255;
5867
6273
  * and looks up nothing else.
5868
6274
  */
5869
6275
  const BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
6276
+ /** `native_builds.sandbox_url_scheme`'s bound in core's schema. */
6277
+ const SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
6278
+ /**
6279
+ * A URL scheme as RFC 3986 spells it, in lower case: what a sandbox build's
6280
+ * artifact registers, as `@hot-updater/protocol/native-artifact` reads it.
6281
+ */
6282
+ const URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
6283
+ /**
6284
+ * A bundle identifier or application ID, as an artifact reports it: letters,
6285
+ * digits, dots, dashes and underscores, which a scope key holds as they are.
6286
+ */
6287
+ const APP_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;
6288
+ /** A fingerprint hash as a Release Catalog scope key holds it. */
6289
+ const FINGERPRINT_HASH = /^[A-Za-z0-9._~-]{1,255}$/;
6290
+ /** How each kind of artifact can install. */
6291
+ const DISTRIBUTIONS = {
6292
+ apk: ["direct"],
6293
+ app: ["direct"],
6294
+ aab: ["store"],
6295
+ ipa: ["direct", "store"]
6296
+ };
5870
6297
  /** A native build or scope core cannot store or look up: the caller's input. */
5871
6298
  var NativeBuildInputError = class extends TypeError {
5872
6299
  name = "NativeBuildInputError";
@@ -5888,24 +6315,67 @@ const pick = (row) => ({
5888
6315
  build_number: row.build_number ?? null,
5889
6316
  submitted_to: row.submitted_to ?? null,
5890
6317
  submitted_at_ms: row.submitted_at_ms ?? null,
5891
- submitted_version: row.submitted_version ?? null
6318
+ submitted_version: row.submitted_version ?? null,
6319
+ is_store_build: row.is_store_build === true,
6320
+ is_sandbox: row.is_sandbox === true,
6321
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
6322
+ export_method: row.export_method ?? null,
6323
+ native_app_version: row.native_app_version ?? null
5892
6324
  });
5893
- /** The store track each platform's builds are submitted to. */
5894
- const SUBMISSION_DESTINATIONS = {
5895
- android: "play-internal",
5896
- ios: "testflight"
5897
- };
6325
+ /** The export methods an `.ipa` registers with. */
6326
+ const EXPORT_METHODS = /* @__PURE__ */ new Set([
6327
+ "app-store",
6328
+ "ad-hoc",
6329
+ "development",
6330
+ "enterprise"
6331
+ ]);
6332
+ /**
6333
+ * How many older builds of a scope one read takes, looking for one older than
6334
+ * a bundle when a build made after the bundle is the newest.
6335
+ */
6336
+ const OLDER_BUILDS_PAGE = 20;
6337
+ /** How many times a mark runs again after losing its scope's mark to another. */
6338
+ const MARK_ATTEMPTS = 8;
5898
6339
  /** `native_builds.build_number`'s bound in core's schema. */
5899
6340
  const BUILD_NUMBER_MAX_LENGTH = 64;
5900
6341
  /** `native_builds.submitted_version`'s bound in core's schema. */
5901
6342
  const SUBMITTED_VERSION_MAX_LENGTH = 255;
6343
+ const checkedScopeKey = (scopeKey) => {
6344
+ 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.`);
6345
+ return scopeKey;
6346
+ };
6347
+ /**
6348
+ * How a registered artifact installs: an `.ipa` by its export method, and
6349
+ * `unknown` for one whose export no profile confirmed, which no lookup asks
6350
+ * for, so it is never reused as either.
6351
+ */
6352
+ const registeredDistribution = (kind, exportMethod) => kind !== "ipa" ? DISTRIBUTIONS[kind][0] : exportMethod === void 0 || exportMethod === null ? "unknown" : exportMethod === "app-store" ? "store" : "direct";
6353
+ /**
6354
+ * A sandbox build scope's key, which names no channel: the app ID, URL
6355
+ * scheme, artifact kind and distribution in its place, then the fingerprint,
6356
+ * or the app-version strategy and the exact app version. `v1:sandbox:` is no
6357
+ * Release Catalog strategy, so it never meets a normal build's key.
6358
+ */
6359
+ const sandboxScopeKey = (scope, sandbox) => {
6360
+ const { appId, urlScheme, artifactKind, distribution } = sandbox;
6361
+ 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;
6362
+ if (problem !== null) throw new NativeBuildInputError(`Invalid sandbox build scope: ${problem}.`);
6363
+ const target = scope.fingerprintHash === null ? `app-version:${encodeURIComponent(scope.appVersion)}` : `fingerprint:${scope.fingerprintHash}`;
6364
+ return checkedScopeKey(`v1:sandbox:${scope.platform}:${appId}:${urlScheme}:${artifactKind}:${distribution}:${target}`);
6365
+ };
5902
6366
  /**
5903
6367
  * A native build scope's key: the Release Catalog scope key of a
5904
6368
  * fingerprint, or of the app-version strategy followed by the exact app
5905
6369
  * version the build compiled in. One key serves both strategies, so one
5906
- * index finds the newest build of either.
6370
+ * index finds the newest build of either. A sandbox scope's key names no
6371
+ * channel, so pull requests find a sandbox build on any.
5907
6372
  */
5908
6373
  const nativeBuildScopeKey = (scope) => {
6374
+ const { sandbox } = scope;
6375
+ if (sandbox !== void 0 && sandbox !== null) {
6376
+ if (sandbox.distribution !== "direct" && sandbox.distribution !== "store") throw new NativeBuildInputError("Invalid sandbox build scope: its distribution must be direct or store.");
6377
+ return sandboxScopeKey(scope, sandbox);
6378
+ }
5909
6379
  let scopeKey;
5910
6380
  try {
5911
6381
  const channelKey = encodeChannelKey(scope.channel);
@@ -5922,22 +6392,71 @@ const nativeBuildScopeKey = (scope) => {
5922
6392
  } catch (error) {
5923
6393
  throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
5924
6394
  }
5925
- if (scopeKey.length > SCOPE_KEY_MAX_LENGTH) throw new NativeBuildInputError(`Invalid native build scope: its key is longer than ${SCOPE_KEY_MAX_LENGTH} characters; shorten the channel or app version.`);
5926
- return scopeKey;
6395
+ return checkedScopeKey(scopeKey);
6396
+ };
6397
+ /** The channel row a registration names, or the refusal of its channel. */
6398
+ const channelIdOf = (channel) => {
6399
+ try {
6400
+ return `channel:${encodeChannelKey(channel)}`;
6401
+ } catch (error) {
6402
+ throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
6403
+ }
6404
+ };
6405
+ /**
6406
+ * A registration's scope key, from the registration's own facts: a sandbox
6407
+ * build's from what its artifact says, whatever `sandbox` it names.
6408
+ */
6409
+ const registrationScopeKey = (registration) => {
6410
+ channelIdOf(registration.channel);
6411
+ return registration.isSandbox === true ? sandboxScopeKey(registration, {
6412
+ appId: registration.sandboxAppId,
6413
+ urlScheme: registration.sandboxUrlScheme,
6414
+ artifactKind: registration.artifact.kind,
6415
+ distribution: registeredDistribution(registration.artifact.kind, registration.exportMethod)
6416
+ }) : nativeBuildScopeKey({
6417
+ ...registration,
6418
+ sandbox: null
6419
+ });
6420
+ };
6421
+ /**
6422
+ * Refuses a patch from a sandbox build's built-in bundle: no deploy patches
6423
+ * from one, so no store or test install of the app gets a patch made for a
6424
+ * sandbox build. One unique read of the base.
6425
+ */
6426
+ const refuseSandboxPatchBase = async (db, baseBundleId) => {
6427
+ if ((await db.findOne("native_builds", { min_bundle_id: baseBundleId }))?.is_sandbox === true) throw new NativeBuildInputError("A sandbox build's built-in bundle is no patch base.");
5927
6428
  };
5928
6429
  /** Whether `bundleId` is a native build's built-in bundle: one unique read. */
5929
6430
  const isBuiltInBundle = async (db, bundleId) => await db.findOne("native_builds", { min_bundle_id: bundleId }) !== null;
5930
- const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, artifact }) => {
6431
+ const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, sandboxAppId, exportMethod, nativeAppVersion, artifact }) => {
5931
6432
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
5932
6433
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
5933
6434
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
5934
6435
  if (channel.trim().length === 0) return "channel is required";
6436
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
6437
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
6438
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
6439
+ 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`;
6440
+ }
6441
+ if (sandboxAppId !== void 0 && sandboxAppId !== null) {
6442
+ if (isSandbox !== true) return "sandboxAppId is a sandbox build's, and this isn't one";
6443
+ if (typeof sandboxAppId !== "string" || !APP_ID.test(sandboxAppId)) return "sandboxAppId must be the artifact's bundle identifier or application ID, up to 255 characters";
6444
+ }
6445
+ if (isSandbox === true) {
6446
+ if (sandboxUrlScheme === void 0 || sandboxUrlScheme === null) return "a sandbox build needs the sandboxUrlScheme its artifact registers";
6447
+ 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";
6448
+ }
5935
6449
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
5936
6450
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
5937
6451
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
5938
6452
  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`;
6453
+ if (nativeAppVersion !== void 0 && nativeAppVersion !== null && (typeof nativeAppVersion !== "string" || nativeAppVersion.trim().length === 0)) return "nativeAppVersion must be the artifact's app version, or null";
5939
6454
  const kinds = ARTIFACT_KINDS[platform];
5940
6455
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
6456
+ if (exportMethod !== void 0 && exportMethod !== null) {
6457
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
6458
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
6459
+ }
5941
6460
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
5942
6461
  return null;
5943
6462
  };
@@ -5946,8 +6465,8 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
5946
6465
  async registerNativeBuild(registration) {
5947
6466
  const problem = problemOf(registration);
5948
6467
  if (problem !== null) throw new NativeBuildInputError(`Invalid native build: ${problem}.`);
5949
- const scopeKey = nativeBuildScopeKey(registration);
5950
- const channelId = `channel:${encodeChannelKey(registration.channel)}`;
6468
+ const scopeKey = registrationScopeKey(registration);
6469
+ const channelId = channelIdOf(registration.channel);
5951
6470
  const { embeddedBundle } = registration;
5952
6471
  const row = {
5953
6472
  id: registration.id,
@@ -5966,7 +6485,12 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
5966
6485
  build_number: registration.buildNumber ?? null,
5967
6486
  submitted_to: null,
5968
6487
  submitted_at_ms: null,
5969
- submitted_version: null
6488
+ submitted_version: null,
6489
+ is_store_build: false,
6490
+ is_sandbox: registration.isSandbox === true,
6491
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
6492
+ export_method: registration.exportMethod ?? null,
6493
+ native_app_version: registration.nativeAppVersion ?? null
5970
6494
  };
5971
6495
  for (let attempt = 1;; attempt += 1) {
5972
6496
  await insertChannel(db, {
@@ -6004,21 +6528,43 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6004
6528
  const scopeKey = nativeBuildScopeKey(scope);
6005
6529
  const buildKey = options?.buildKey;
6006
6530
  if (buildKey !== void 0 && !BUILD_KEY.test(buildKey)) throw new NativeBuildInputError("Invalid native build key: it must be nbk1: and a SHA-256.");
6007
- const { rows } = buildKey === void 0 ? await db.findMany("native_builds", {
6008
- index: "byScope",
6009
- where: { scope_key: scopeKey },
6010
- order: "desc",
6011
- limit: 1
6012
- }) : await db.findMany("native_builds", {
6013
- index: "byBuildKey",
6014
- where: {
6015
- scope_key: scopeKey,
6016
- build_key: buildKey
6017
- },
6018
- order: "desc",
6019
- limit: 1
6020
- });
6021
- return rows[0] === void 0 ? null : pick(rows[0]);
6531
+ if (options?.storeBuild) {
6532
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
6533
+ return marked === null ? null : pick(marked);
6534
+ }
6535
+ const read = (limit, before) => {
6536
+ const page = {
6537
+ order: "desc",
6538
+ limit,
6539
+ ...before === void 0 ? {} : { range: { lt: before } }
6540
+ };
6541
+ return buildKey === void 0 ? db.findMany("native_builds", {
6542
+ index: "byScope",
6543
+ where: { scope_key: scopeKey },
6544
+ ...page
6545
+ }) : db.findMany("native_builds", {
6546
+ index: "byBuildKey",
6547
+ where: {
6548
+ scope_key: scopeKey,
6549
+ build_key: buildKey
6550
+ },
6551
+ ...page
6552
+ });
6553
+ };
6554
+ const bundleId = options?.builtInOlderThan;
6555
+ if (bundleId !== void 0 && scope.sandbox !== void 0 && scope.sandbox !== null) return null;
6556
+ const { rows } = await read(1);
6557
+ const newest = rows[0];
6558
+ if (newest === void 0) return null;
6559
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return pick(newest);
6560
+ for (let before = newest.id;;) {
6561
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
6562
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
6563
+ if (usable !== void 0) return pick(usable);
6564
+ const last = older.at(-1);
6565
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
6566
+ before = last.id;
6567
+ }
6022
6568
  },
6023
6569
  async recordNativeBuildSubmission(id, { destination, version }) {
6024
6570
  if (version.trim().length === 0 || version.length > SUBMITTED_VERSION_MAX_LENGTH) throw new NativeBuildInputError(`Invalid native build submission: version must be the store's label of the build, up to ${SUBMITTED_VERSION_MAX_LENGTH} characters.`);
@@ -6026,7 +6572,8 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6026
6572
  const row = await tx.findOne("native_builds", { id });
6027
6573
  if (row === null) return null;
6028
6574
  const build = pick(row);
6029
- if (SUBMISSION_DESTINATIONS[build.platform] !== destination) throw new NativeBuildInputError(`Invalid native build submission: an ${build.platform} build is submitted to ${SUBMISSION_DESTINATIONS[build.platform]}, not ${destination}.`);
6575
+ 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}.`);
6576
+ if (build.is_sandbox && destination !== "testflight" && destination !== "play-internal") throw new NativeBuildInputError("A sandbox build can submit only to TestFlight or Play internal testing.");
6030
6577
  const set = {
6031
6578
  submitted_to: destination,
6032
6579
  submitted_at_ms: now(),
@@ -6039,6 +6586,46 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6039
6586
  };
6040
6587
  });
6041
6588
  },
6589
+ async markNativeBuild(id, { storeBuild }) {
6590
+ for (let attempt = 1;; attempt += 1) try {
6591
+ return await db.transaction(async (tx) => {
6592
+ const row = await tx.findOne("native_builds", { id });
6593
+ if (row === null) return null;
6594
+ const build = pick(row);
6595
+ if (!storeBuild) {
6596
+ if (build.is_store_build) tx.update("native_builds", row, { is_store_build: false });
6597
+ return {
6598
+ nativeBuild: {
6599
+ ...build,
6600
+ is_store_build: false
6601
+ },
6602
+ previous: null
6603
+ };
6604
+ }
6605
+ if (build.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
6606
+ if (build.is_store_build) return {
6607
+ nativeBuild: build,
6608
+ previous: null
6609
+ };
6610
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build.scope_key });
6611
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
6612
+ tx.update("native_builds", row, { is_store_build: true });
6613
+ return {
6614
+ nativeBuild: {
6615
+ ...build,
6616
+ is_store_build: true
6617
+ },
6618
+ previous: holder === null ? null : {
6619
+ ...pick(holder),
6620
+ is_store_build: false
6621
+ }
6622
+ };
6623
+ });
6624
+ } catch (error) {
6625
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
6626
+ throw error;
6627
+ }
6628
+ },
6042
6629
  async deleteNativeBuild(id) {
6043
6630
  return db.transaction(async (tx) => {
6044
6631
  const row = await tx.findOne("native_builds", { id });
@@ -6385,7 +6972,11 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
6385
6972
  for (const { release } of deployments) if (!channels.has(release.channel)) channels.set(release.channel, await ensureChannel(release.channel));
6386
6973
  const platforms = /* @__PURE__ */ new Map();
6387
6974
  for (const deployment of deployments) {
6388
- if (!("bundleId" in deployment) || platforms.has(deployment.bundleId)) continue;
6975
+ if (!("bundleId" in deployment)) {
6976
+ for (const { baseBundleId } of deployment.bundle.patches ?? []) await refuseSandboxPatchBase(db, baseBundleId);
6977
+ continue;
6978
+ }
6979
+ if (platforms.has(deployment.bundleId)) continue;
6389
6980
  const row = await db.findOne("bundles", { id: deployment.bundleId });
6390
6981
  if (row === null) throw new DatabaseBundleNotFoundError(deployment.bundleId);
6391
6982
  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.`);
@@ -6589,7 +7180,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
6589
7180
  if (patches !== void 0) await replaceBundlePatches(tx, current, bundleToPatchRows({
6590
7181
  ...next,
6591
7182
  patches
6592
- }));
7183
+ }), (row) => refuseSandboxPatchBase(tx, row.base_bundle_id));
6593
7184
  }),
6594
7185
  deleteBundles: async (ids) => {
6595
7186
  try {
@@ -6651,6 +7242,7 @@ const createCoreApi = (db, storage, options = {}) => {
6651
7242
  ...reads,
6652
7243
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
6653
7244
  ...createNativeBuildApi(db, options),
7245
+ ...createIosDeviceApi(db, options),
6654
7246
  /** One read, which checks the schema settings first. */
6655
7247
  ready: async () => {
6656
7248
  await reads.listReleaseCatalogs({ limit: 1 });
@@ -6870,10 +7462,12 @@ const keyset = (url, maxValue = LIMITS.maxValue) => {
6870
7462
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
6871
7463
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
6872
7464
  const cursor = url.searchParams.get("cursor");
7465
+ const through = url.searchParams.get("through");
6873
7466
  return {
6874
7467
  order,
6875
7468
  limit,
6876
- ...cursor === null ? {} : { after: cursor }
7469
+ ...cursor === null ? {} : { after: cursor },
7470
+ ...through === null ? {} : { through }
6877
7471
  };
6878
7472
  };
6879
7473
  /** A page and the cursor of the next one, when the page is full. */
@@ -6971,7 +7565,8 @@ const nativeBuildScopeOf = (url) => {
6971
7565
  const fingerprintHash = params.get("fingerprintHash");
6972
7566
  const appVersion = params.get("appVersion");
6973
7567
  if (platform === void 0 || !isText$2(channel) || fingerprintHash === null === (appVersion === null) || fingerprintHash === "" || appVersion === "") throw new HandlerBadRequestError("A native build lookup needs platform, channel, and fingerprintHash or appVersion.");
6974
- return fingerprintHash !== null ? {
7568
+ const sandbox = sandboxScopeOf(params);
7569
+ const scope = fingerprintHash !== null ? {
6975
7570
  platform,
6976
7571
  channel,
6977
7572
  fingerprintHash,
@@ -6982,17 +7577,49 @@ const nativeBuildScopeOf = (url) => {
6982
7577
  fingerprintHash: null,
6983
7578
  appVersion
6984
7579
  };
7580
+ return sandbox === null ? scope : {
7581
+ ...scope,
7582
+ sandbox
7583
+ };
7584
+ };
7585
+ /** The query parameters a sandbox lookup names, all four or none. */
7586
+ const SANDBOX_SCOPE_PARAMS = [
7587
+ "sandboxAppId",
7588
+ "sandboxUrlScheme",
7589
+ "artifactKind",
7590
+ "distribution"
7591
+ ];
7592
+ /**
7593
+ * A lookup's sandbox scope: null without one, and a bad request for one
7594
+ * named in part. Core checks each value.
7595
+ */
7596
+ const sandboxScopeOf = (params) => {
7597
+ const [appId, urlScheme, artifactKind, distribution] = SANDBOX_SCOPE_PARAMS.map((name) => params.get(name));
7598
+ const named = [
7599
+ appId,
7600
+ urlScheme,
7601
+ artifactKind,
7602
+ distribution
7603
+ ].filter((value) => value !== null).length;
7604
+ if (named === 0) return null;
7605
+ if (named !== SANDBOX_SCOPE_PARAMS.length) throw new HandlerBadRequestError(`A sandbox build lookup needs ${SANDBOX_SCOPE_PARAMS.join(", ")}.`);
7606
+ return {
7607
+ appId,
7608
+ urlScheme,
7609
+ artifactKind,
7610
+ distribution
7611
+ };
6985
7612
  };
6986
7613
  /** A native build or scope core refuses: a bad request. */
6987
7614
  const refusingInvalid = async (operation) => {
6988
7615
  try {
6989
7616
  return await operation();
6990
7617
  } catch (error) {
6991
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
7618
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
6992
7619
  throw error;
6993
7620
  }
6994
7621
  };
6995
- const isNativeBuildRegistration = (value) => isRecord$5(value) && isText$2(value.id) && isText$2(value.minBundleId) && typeof value.platform === "string" && isPlatform(value.platform) && isText$2(value.channel) && isTextOrNull$1(value.fingerprintHash) && isTextOrNull$1(value.appVersion) && value.fingerprintHash === null !== (value.appVersion === null) && isTextOrNull$1(value.gitCommitHash) && isTextOrNull$1(value.buildKey) && (value.buildNumber === void 0 || isTextOrNull$1(value.buildNumber)) && isRecord$5(value.artifact) && typeof value.artifact.kind === "string" && NATIVE_BUILD_ARTIFACT_KINDS.has(value.artifact.kind) && isText$2(value.artifact.storageUri) && Number.isSafeInteger(value.artifact.byteSize) && value.artifact.byteSize >= 0 && isRecord$5(value.embeddedBundle) && isText$2(value.embeddedBundle.manifestStorageUri) && isText$2(value.embeddedBundle.manifestFileHash) && isText$2(value.embeddedBundle.assetBaseStorageUri) && (value.embeddedBundle.metadata === void 0 || isRecord$5(value.embeddedBundle.metadata));
7622
+ const isNativeBuildRegistration = (value) => isRecord$5(value) && isText$2(value.id) && isText$2(value.minBundleId) && typeof value.platform === "string" && isPlatform(value.platform) && isText$2(value.channel) && isTextOrNull$1(value.fingerprintHash) && isTextOrNull$1(value.appVersion) && value.fingerprintHash === null !== (value.appVersion === null) && isTextOrNull$1(value.gitCommitHash) && isTextOrNull$1(value.buildKey) && (value.buildNumber === void 0 || isTextOrNull$1(value.buildNumber)) && (value.isSandbox === void 0 || typeof value.isSandbox === "boolean") && (value.sandboxUrlScheme === void 0 || isTextOrNull$1(value.sandboxUrlScheme)) && (value.sandboxAppId === void 0 || isTextOrNull$1(value.sandboxAppId)) && (value.exportMethod === void 0 || isTextOrNull$1(value.exportMethod)) && (value.nativeAppVersion === void 0 || isTextOrNull$1(value.nativeAppVersion)) && isRecord$5(value.artifact) && typeof value.artifact.kind === "string" && NATIVE_BUILD_ARTIFACT_KINDS.has(value.artifact.kind) && isText$2(value.artifact.storageUri) && Number.isSafeInteger(value.artifact.byteSize) && value.artifact.byteSize >= 0 && isRecord$5(value.embeddedBundle) && isText$2(value.embeddedBundle.manifestStorageUri) && isText$2(value.embeddedBundle.manifestFileHash) && isText$2(value.embeddedBundle.assetBaseStorageUri) && (value.embeddedBundle.metadata === void 0 || isRecord$5(value.embeddedBundle.metadata));
6996
7623
  const scopeKeyOf = (params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "";
6997
7624
  /** Every admin route's handler, by the name `ADMIN_ROUTES` mounts it under. */
6998
7625
  const createAdminRouteHandlers = () => ({
@@ -7074,7 +7701,8 @@ const createAdminRouteHandlers = () => ({
7074
7701
  rebuildReleaseCatalog: onCore(async (core, _request, params) => json$2({ data: await core.rebuildReleaseCatalog(scopeKeyOf(params)) })),
7075
7702
  updateBundle: onCore(async (core, request, params) => {
7076
7703
  const bundleId = requireRouteParam(params, "id");
7077
- await core.updateBundle(bundleId, bundleUpdateOf(await request.json(), bundleId));
7704
+ const update = bundleUpdateOf(await request.json(), bundleId);
7705
+ await refusingInvalid(() => core.updateBundle(bundleId, update));
7078
7706
  return noContent();
7079
7707
  }),
7080
7708
  countBundles: onCore(async (core, request) => json$2({ data: await core.countBundles(platformOf(new URL(request.url))) })),
@@ -7098,7 +7726,7 @@ const createAdminRouteHandlers = () => ({
7098
7726
  deployReleases: onCore(async (core, request) => {
7099
7727
  const { deployments } = await body(request);
7100
7728
  if (!Array.isArray(deployments) || deployments.length === 0 || !deployments.every(isDeployment)) throw new HandlerBadRequestError("Deploy needs deployments, each a bundle and its release policy.");
7101
- return json$2({ data: await core.deploy(deployments) }, 201);
7729
+ return json$2({ data: await refusingInvalid(() => core.deploy(deployments)) }, 201);
7102
7730
  }),
7103
7731
  promoteRelease: onCore(async (core, request, params) => {
7104
7732
  const input = await body(request);
@@ -7121,7 +7749,13 @@ const createAdminRouteHandlers = () => ({
7121
7749
  const url = new URL(request.url);
7122
7750
  const scope = nativeBuildScopeOf(url);
7123
7751
  const buildKey = url.searchParams.get("buildKey");
7124
- return json$2({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
7752
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
7753
+ const options = {
7754
+ ...buildKey === null ? {} : { buildKey },
7755
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
7756
+ ...builtInOlderThan === null ? {} : { builtInOlderThan }
7757
+ };
7758
+ return json$2({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
7125
7759
  }),
7126
7760
  getNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
7127
7761
  listNativeBuilds: onCore(async (core, request) => {
@@ -7135,14 +7769,96 @@ const createAdminRouteHandlers = () => ({
7135
7769
  }),
7136
7770
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
7137
7771
  const input = await body(request);
7138
- if (!isRecord$5(input) || input.destination !== "testflight" && input.destination !== "play-internal" || !isText$2(input.version)) throw new HandlerBadRequestError("A native build submission needs destination (testflight or play-internal) and version.");
7772
+ if (!isRecord$5(input) || !Object.values(NATIVE_BUILD_SUBMISSION_DESTINATIONS).flat().includes(input.destination) || !isText$2(input.version)) throw new HandlerBadRequestError("A native build submission needs a valid store destination and version.");
7139
7773
  const submission = {
7140
7774
  destination: input.destination,
7141
7775
  version: input.version
7142
7776
  };
7143
7777
  return json$2({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
7144
7778
  }),
7779
+ markNativeBuild: onCore(async (core, request, params) => {
7780
+ const input = await body(request);
7781
+ if (!isRecord$5(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
7782
+ const mark = { storeBuild: input.storeBuild };
7783
+ return json$2({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
7784
+ }),
7145
7785
  deleteNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
7786
+ listIosDevices: onCore(async (core, request) => {
7787
+ const url = new URL(request.url);
7788
+ const input = keyset(url);
7789
+ const status = url.searchParams.get("status");
7790
+ return page(await refusingInvalid(() => core.listIosDevices({
7791
+ ...input,
7792
+ ...status === null ? {} : { status }
7793
+ })), input, ({ id }) => id);
7794
+ }),
7795
+ findIosDevice: onCore(async (core, _request, params) => json$2({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
7796
+ requestIosDevice: onCore(async (core, request) => {
7797
+ const input = await body(request);
7798
+ 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.");
7799
+ const device = {
7800
+ udid: input.udid,
7801
+ name: input.name,
7802
+ requestedBy: input.requestedBy
7803
+ };
7804
+ return json$2({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
7805
+ }),
7806
+ approveIosDevice: onCore(async (core, request, params) => {
7807
+ const input = await body(request);
7808
+ 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.");
7809
+ const approval = {
7810
+ approvedBy: input.approvedBy,
7811
+ ...input.name === void 0 ? {} : { name: input.name }
7812
+ };
7813
+ return json$2({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
7814
+ }),
7815
+ renameIosDevice: onCore(async (core, request, params) => {
7816
+ const input = await body(request);
7817
+ if (!isText$2(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
7818
+ const name = input.name;
7819
+ return json$2({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
7820
+ }),
7821
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
7822
+ const input = await body(request);
7823
+ const seen = input.seen;
7824
+ 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.");
7825
+ const outcome = {
7826
+ id: requireRouteParam(params, "id"),
7827
+ seen: {
7828
+ status: seen.status,
7829
+ approvedAtMs: seen.approvedAtMs
7830
+ },
7831
+ issuerId: input.issuerId,
7832
+ outcome: input.outcome,
7833
+ ...input.reason === void 0 ? {} : { reason: input.reason }
7834
+ };
7835
+ return json$2({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
7836
+ }),
7837
+ claimIosDeviceAccount: onCore(async (core, request) => {
7838
+ const { issuerId } = await body(request);
7839
+ if (!isText$2(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
7840
+ return json$2({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
7841
+ }),
7842
+ findIosDeviceAccount: onCore(async (core) => json$2({ data: await core.findIosDeviceAccount() })),
7843
+ markIosDevicesInBuild: onCore(async (core, request) => {
7844
+ const { buildId, ids } = await body(request);
7845
+ 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.");
7846
+ await core.markIosDevicesInBuild({
7847
+ buildId,
7848
+ ids
7849
+ });
7850
+ return noContent();
7851
+ }),
7852
+ deleteIosDevice: onCore(async (core, request, params) => {
7853
+ const url = new URL(request.url);
7854
+ const status = url.searchParams.get("status");
7855
+ const requestedBy = url.searchParams.get("requestedBy");
7856
+ const only = {
7857
+ ...status === null ? {} : { status },
7858
+ ...requestedBy === null ? {} : { requestedBy }
7859
+ };
7860
+ return json$2({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
7861
+ }),
7146
7862
  deleteBundles: onCore(async (core, request) => {
7147
7863
  const { ids } = await body(request);
7148
7864
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -7287,10 +8003,65 @@ const ADMIN_ROUTES = [
7287
8003
  path: "/native-builds/:id/submission",
7288
8004
  handler: "recordNativeBuildSubmission"
7289
8005
  },
8006
+ {
8007
+ method: "POST",
8008
+ path: "/native-builds/:id/store-build",
8009
+ handler: "markNativeBuild"
8010
+ },
7290
8011
  {
7291
8012
  method: "DELETE",
7292
8013
  path: "/native-builds/:id",
7293
8014
  handler: "deleteNativeBuild"
8015
+ },
8016
+ {
8017
+ method: "GET",
8018
+ path: "/ios-devices",
8019
+ handler: "listIosDevices"
8020
+ },
8021
+ {
8022
+ method: "POST",
8023
+ path: "/ios-devices",
8024
+ handler: "requestIosDevice"
8025
+ },
8026
+ {
8027
+ method: "GET",
8028
+ path: "/ios-devices/udid/:udid",
8029
+ handler: "findIosDevice"
8030
+ },
8031
+ {
8032
+ method: "POST",
8033
+ path: "/ios-devices/in-build",
8034
+ handler: "markIosDevicesInBuild"
8035
+ },
8036
+ {
8037
+ method: "GET",
8038
+ path: "/ios-devices/account",
8039
+ handler: "findIosDeviceAccount"
8040
+ },
8041
+ {
8042
+ method: "POST",
8043
+ path: "/ios-devices/account",
8044
+ handler: "claimIosDeviceAccount"
8045
+ },
8046
+ {
8047
+ method: "POST",
8048
+ path: "/ios-devices/:id/approval",
8049
+ handler: "approveIosDevice"
8050
+ },
8051
+ {
8052
+ method: "POST",
8053
+ path: "/ios-devices/:id/outcome",
8054
+ handler: "recordIosDeviceOutcome"
8055
+ },
8056
+ {
8057
+ method: "PATCH",
8058
+ path: "/ios-devices/:id",
8059
+ handler: "renameIosDevice"
8060
+ },
8061
+ {
8062
+ method: "DELETE",
8063
+ path: "/ios-devices/:id",
8064
+ handler: "deleteIosDevice"
7294
8065
  }
7295
8066
  ];
7296
8067
  //#endregion
@@ -12139,11 +12910,14 @@ const firebaseDatabase = (config) => ({
12139
12910
  //#region src/firebaseStorage.ts
12140
12911
  /** Signed URLs kept per adapter, enough for a few Bundles' assets. */
12141
12912
  const MAX_CACHED_SIGNED_URLS = 1e4;
12913
+ /** Objects deleted at once: Cloud Storage deletes one object a request. */
12914
+ const DELETE_CONCURRENCY = 16;
12142
12915
  const firebaseStorage = (config) => {
12143
12916
  const app = (0, firebase_admin_app.getApps)().length ? (0, firebase_admin_app.getApp)() : (0, firebase_admin_app.initializeApp)(config);
12144
12917
  let opened;
12145
12918
  const bucket = () => opened ??= (0, firebase_admin_storage.getStorage)(app).bucket(config.storageBucket);
12146
12919
  const getStorageKey = createStorageKeyBuilder(config.basePath);
12920
+ const basePrefix = getStorageKey() ? `${getStorageKey()}/` : "";
12147
12921
  /**
12148
12922
  * Signed URLs by object. Without a private key, as in Cloud Functions, each
12149
12923
  * signature is an IAM signBlob request, and an update check returns a URL
@@ -12232,6 +13006,39 @@ const firebaseStorage = (config) => {
12232
13006
  const { key } = parseAndValidate(storageUri);
12233
13007
  await bucket().file(key).delete({ ignoreNotFound: true });
12234
13008
  return { deleted: true };
13009
+ },
13010
+ async listObjects(prefix) {
13011
+ const folder = getStorageKey(prefix ?? "");
13012
+ const [files] = await bucket().getFiles({
13013
+ autoPaginate: true,
13014
+ prefix: folder ? `${folder}/` : ""
13015
+ });
13016
+ const objects = [];
13017
+ for (const file of files) {
13018
+ if (!file.name.startsWith(basePrefix)) continue;
13019
+ let storageUri;
13020
+ try {
13021
+ storageUri = createStorageUri({
13022
+ bucket: config.storageBucket,
13023
+ key: file.name,
13024
+ protocol: "gs"
13025
+ });
13026
+ } catch {
13027
+ continue;
13028
+ }
13029
+ const { size, updated } = file.metadata;
13030
+ objects.push({
13031
+ key: file.name.slice(basePrefix.length),
13032
+ ...updated ? { lastModifiedAt: new Date(updated) } : {},
13033
+ size: Number(size ?? 0),
13034
+ storageUri
13035
+ });
13036
+ }
13037
+ return objects;
13038
+ },
13039
+ async deleteObjects(relativeKeys) {
13040
+ const keys = relativeKeys.map((key) => getStorageKey(key));
13041
+ for (let offset = 0; offset < keys.length; offset += DELETE_CONCURRENCY) await Promise.all(keys.slice(offset, offset + DELETE_CONCURRENCY).map((key) => bucket().file(key).delete({ ignoreNotFound: true })));
12235
13042
  }
12236
13043
  });
12237
13044
  };