@hot-updater/firebase 1.2.0-rc.3 → 1.2.0-rc.30

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({
@@ -2366,6 +2369,21 @@ const channels = defineTable({
2366
2369
  * or `versionCode`. `submitted_to`, `submitted_at_ms` and
2367
2370
  * `submitted_version` record the store track a build went to, when, and
2368
2371
  * the store's label of the build; they stay null for a build no store took.
2372
+ * `is_store_build` is true on the build a person or a job says the store
2373
+ * sells, and false on every other: deploys patch from it over the scope's
2374
+ * newest build. The engine copies the scope key into `store_build_scope_key`
2375
+ * for that build alone, so `byStoreBuild` holds one entry per scope at most,
2376
+ * on every store, while any number of a scope's builds hold none.
2377
+ * `is_sandbox` is true on a sandbox build, set when it registers and never
2378
+ * changed, and `sandbox_url_scheme` is the URL scheme its artifact registers,
2379
+ * which its preview links open; null on any other build, and on a sandbox
2380
+ * build registered before the column, which registered the derived one.
2381
+ * `export_method` is how an `.ipa` was exported, read from its profile when
2382
+ * it registers and never changed; null on any other artifact, on an `.ipa`
2383
+ * whose profile couldn't be read, and on one registered before the column.
2384
+ * Boolean columns follow one rule: `is_*` for a fact about the row or
2385
+ * `should_*` for an instruction to the client, never null; a unique index over
2386
+ * the rows where one is true keys a derived slot, not the boolean.
2369
2387
  */
2370
2388
  const nativeBuilds = defineTable({
2371
2389
  id: {
@@ -2442,9 +2460,30 @@ const nativeBuilds = defineTable({
2442
2460
  type: "string",
2443
2461
  maxLength: 255,
2444
2462
  required: false
2463
+ },
2464
+ is_store_build: { type: "boolean" },
2465
+ is_sandbox: { type: "boolean" },
2466
+ sandbox_url_scheme: {
2467
+ type: "string",
2468
+ maxLength: 255,
2469
+ ascii: true,
2470
+ required: false
2471
+ },
2472
+ export_method: {
2473
+ type: "string",
2474
+ maxLength: 16,
2475
+ required: false
2445
2476
  }
2446
2477
  }, {
2447
2478
  key: ["id"],
2479
+ derived: {
2480
+ /** The scope this build is the store build of; null on every other. */
2481
+ store_build_scope_key: {
2482
+ type: "string",
2483
+ maxLength: 2048,
2484
+ ascii: true,
2485
+ compute: (row) => row.is_store_build ? row.scope_key : null
2486
+ } },
2448
2487
  indexes: {
2449
2488
  byScope: {
2450
2489
  eq: ["scope_key"],
@@ -2454,6 +2493,11 @@ const nativeBuilds = defineTable({
2454
2493
  eq: ["scope_key", "build_key"],
2455
2494
  sort: ["id"]
2456
2495
  },
2496
+ byStoreBuild: {
2497
+ eq: ["store_build_scope_key"],
2498
+ sort: [],
2499
+ unique: true
2500
+ },
2457
2501
  byChannel: {
2458
2502
  eq: ["channel_id"],
2459
2503
  sort: ["id"],
@@ -2465,6 +2509,115 @@ const nativeBuilds = defineTable({
2465
2509
  }
2466
2510
  }
2467
2511
  });
2512
+ /**
2513
+ * The iPhones a team asks to install ad hoc builds on. A row decides what the
2514
+ * CLI registers with Apple, not what an export includes: Xcode's automatic ad
2515
+ * hoc profile lists every device the Apple account has enabled. `status` is
2516
+ * `pending` until someone approves it, `approved` until a build or
2517
+ * `native-build devices add` registers it with Apple, then `registered`;
2518
+ * declining or removing one deletes its row. `udid` is the UDID in lower case.
2519
+ * `apple_issuer_id` is the App Store Connect issuer whose key registered it,
2520
+ * set once: a build signed by another account never registers these rows.
2521
+ * `apple_error` is Apple's refusal of the device, or why it stopped counting
2522
+ * it, cleared by the next success. `build_id` is the newest native build whose
2523
+ * .ipa the CLI checked lists it; deleting that build never touches the row.
2524
+ * It holds personal data: a UDID, a name, and the emails of who asked and who
2525
+ * approved, null for the CLI.
2526
+ */
2527
+ const iosDevices = defineTable({
2528
+ id: {
2529
+ type: "string",
2530
+ maxLength: 36
2531
+ },
2532
+ udid: {
2533
+ type: "string",
2534
+ maxLength: 40,
2535
+ ascii: true,
2536
+ unique: true
2537
+ },
2538
+ name: {
2539
+ type: "string",
2540
+ maxLength: 100
2541
+ },
2542
+ status: {
2543
+ type: "string",
2544
+ maxLength: 16
2545
+ },
2546
+ requested_by: {
2547
+ type: "string",
2548
+ maxLength: 320,
2549
+ required: false
2550
+ },
2551
+ created_at_ms: { type: "integer" },
2552
+ approved_by: {
2553
+ type: "string",
2554
+ maxLength: 320,
2555
+ required: false
2556
+ },
2557
+ approved_at_ms: {
2558
+ type: "integer",
2559
+ required: false
2560
+ },
2561
+ registered_at_ms: {
2562
+ type: "integer",
2563
+ required: false
2564
+ },
2565
+ apple_issuer_id: {
2566
+ type: "string",
2567
+ maxLength: 64,
2568
+ ascii: true,
2569
+ required: false
2570
+ },
2571
+ apple_error: {
2572
+ type: "string",
2573
+ maxLength: 512,
2574
+ required: false
2575
+ },
2576
+ build_id: {
2577
+ type: "string",
2578
+ maxLength: 36,
2579
+ required: false
2580
+ }
2581
+ }, {
2582
+ key: ["id"],
2583
+ indexes: {
2584
+ byStatus: {
2585
+ eq: ["status"],
2586
+ sort: ["id"]
2587
+ },
2588
+ all: {
2589
+ eq: [],
2590
+ sort: ["id"]
2591
+ }
2592
+ }
2593
+ });
2594
+ /**
2595
+ * The Apple account the iOS device registry belongs to: one row, keyed
2596
+ * `registry`, holding the App Store Connect issuer that first registered a
2597
+ * device. A build claims it before it sends Apple anything, and its key makes
2598
+ * the claim atomic on every store, so two builds of two accounts can't both
2599
+ * spend a slot; another account's build then registers nothing. Removing
2600
+ * devices never releases it.
2601
+ */
2602
+ const iosDeviceAccount = defineTable({
2603
+ id: {
2604
+ type: "string",
2605
+ maxLength: 16,
2606
+ ascii: true
2607
+ },
2608
+ apple_issuer_id: {
2609
+ type: "string",
2610
+ maxLength: 64,
2611
+ ascii: true
2612
+ },
2613
+ claimed_at_ms: { type: "integer" }
2614
+ }, {
2615
+ key: ["id"],
2616
+ indexes: { all: {
2617
+ eq: [],
2618
+ sort: ["id"]
2619
+ } }
2620
+ });
2468
2621
  /** Core's module: always installed, never a plugin. */
2469
2622
  const coreModule = {
2470
2623
  id: "core",
@@ -2485,7 +2638,9 @@ const coreModule = {
2485
2638
  sort: []
2486
2639
  } }
2487
2640
  }),
2488
- native_builds: nativeBuilds
2641
+ native_builds: nativeBuilds,
2642
+ ios_devices: iosDevices,
2643
+ ios_device_account: iosDeviceAccount
2489
2644
  }
2490
2645
  };
2491
2646
  //#endregion
@@ -2674,15 +2829,8 @@ const LEASE_TABLE = "aggregate_lease";
2674
2829
  const LEASE = { id: "compaction" };
2675
2830
  /** How long a compaction holds the lease before another process may take it. */
2676
2831
  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
- };
2832
+ /** A commit compacts once this has passed since the last compaction. */
2833
+ const WINDOW_MS$1 = 6e4;
2686
2834
  /** Log rows a compaction reads from each log table for one group. */
2687
2835
  const LOG_PAGE = 200;
2688
2836
  /**
@@ -2696,8 +2844,6 @@ const GROUPS = {
2696
2844
  };
2697
2845
  /** Tries per write after a conflict or a transient error. */
2698
2846
  const ATTEMPTS = 5;
2699
- /** Aggregate rows a memory buffer holds before a commit waits for a flush. */
2700
- const MAX_BUFFERED = 1e4;
2701
2847
  const log = defineTable({
2702
2848
  id: {
2703
2849
  type: "string",
@@ -2747,7 +2893,7 @@ const valuesOf = ({ deltas, sketches }) => ({
2747
2893
  /**
2748
2894
  * Merges `values` into the change for `key`'s identity as `tx.aggregate`
2749
2895
  * does: deltas add up and sketches merge. One constant `shardBy` keys each
2750
- * identity to one entry; the write picks the shard.
2896
+ * identity to one entry; `compile` writes it to shard 0.
2751
2897
  */
2752
2898
  const merge = (into, model, key, values) => recordAggregate(into, model, Object.fromEntries(shapeOf(model).key.map((field, at) => [field, key[at]])), values, "");
2753
2899
  const mergeAll = (into, changes) => {
@@ -2781,7 +2927,7 @@ const increment = ({ model, deltas }, key) => Object.values(deltas).some((delta)
2781
2927
  /**
2782
2928
  * The guarded write that merges `change` into `current`: insert, patch, or
2783
2929
  * 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.
2930
+ * group can hold a loss without the gain before it, and reads sum every shard.
2785
2931
  */
2786
2932
  const rewrite = (change, key, current) => {
2787
2933
  const { model } = change;
@@ -2819,12 +2965,12 @@ const rewrite = (change, key, current) => {
2819
2965
  };
2820
2966
  };
2821
2967
  /**
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.
2968
+ * The write for each change on shard 0, since one compaction runs at a time:
2969
+ * a blind increment that creates the row for counters, and a guarded rewrite
2970
+ * for gauges and sketches, whose rows are read in one batch per table.
2825
2971
  */
2826
- const compile = async (adapter, changes, shard) => {
2827
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
2972
+ const compile = async (adapter, changes) => {
2973
+ const keys = changes.map(({ key }) => [...key.slice(0, -1), 0]);
2828
2974
  const reads = /* @__PURE__ */ new Map();
2829
2975
  changes.forEach((change, at) => {
2830
2976
  if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
@@ -2878,14 +3024,13 @@ const encode$1 = async (changes) => {
2878
3024
  return zipped !== void 0 && zipped.length < json.length ? `z${zipped}` : json;
2879
3025
  };
2880
3026
  /**
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.
3027
+ * Batches changes to aggregates declared `batched`. A transaction writes
3028
+ * them as one log row in its own atomic write, in place of their rows; a
3029
+ * compaction later merges log rows into the aggregates and deletes them,
3030
+ * atomically again, so each applies exactly once. One lease row keeps
3031
+ * compactions one at a time.
2887
3032
  */
2888
- const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS$1[mode] }, now }) => {
3033
+ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs = WINDOW_MS$1 }, now }) => {
2889
3034
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
2890
3035
  const holder = crypto.randomUUID().replaceAll("-", "");
2891
3036
  const table = (name) => schema.models.get(name).table;
@@ -2913,68 +3058,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
2913
3058
  }
2914
3059
  return changes;
2915
3060
  };
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
3061
  let nextDue = 0;
2979
3062
  let compacting;
2980
3063
  /** Log rows this process read, by `[log table's index, id]`, for the deletes after a group. */
@@ -3109,7 +3192,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3109
3192
  more
3110
3193
  };
3111
3194
  };
3112
- const rowsFor = async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp);
3195
+ const rowsFor = async (changes) => (await compile(adapter, changes)).filter(isOp);
3113
3196
  /**
3114
3197
  * Applies the oldest pending log rows whose merged changes fit in one
3115
3198
  * atomic write with the lease, which lists them as applied; the rows are
@@ -3203,20 +3286,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3203
3286
  }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
3204
3287
  checking = void 0;
3205
3288
  });
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
3289
  return {
3221
3290
  async transaction(fn) {
3222
3291
  let changes = /* @__PURE__ */ new Map();
@@ -3242,7 +3311,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3242
3311
  aggregate
3243
3312
  });
3244
3313
  if (failure) throw failure.error;
3245
- if (mode === "log" && attempt.size > 0) {
3314
+ if (attempt.size > 0) {
3246
3315
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
3247
3316
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
3248
3317
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -3256,24 +3325,18 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3256
3325
  open = false;
3257
3326
  }
3258
3327
  });
3259
- if (changes.size > 0) await committed(changes);
3328
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
3260
3329
  return result;
3261
3330
  },
3262
3331
  async beforeRead(name) {
3263
3332
  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
- }
3333
+ if (await hasPending().catch((error) => {
3334
+ warn("read")(error);
3335
+ return false;
3336
+ })) await compact(true, GROUPS.read);
3271
3337
  },
3272
- flush,
3273
- async dispose() {
3274
- clearTimeout(timer);
3275
- timer = void 0;
3276
- await flush();
3338
+ async flush() {
3339
+ if (await hasPending()) await compact(true, GROUPS.flush);
3277
3340
  }
3278
3341
  };
3279
3342
  };
@@ -3415,7 +3478,8 @@ const fieldProblems = (definition, add) => {
3415
3478
  else if (field.required === false) add(`key field "${name}" is nullable`);
3416
3479
  else if (field.type === "json") add(`key field "${name}" is json`);
3417
3480
  }
3418
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
3481
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
3482
+ for (const [name, { type, maxLength, ascii }] of bounded) {
3419
3483
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
3420
3484
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
3421
3485
  }
@@ -3532,11 +3596,13 @@ const resolveSchema = (modules) => {
3532
3596
  ...maxLength === void 0 ? {} : { maxLength },
3533
3597
  ...ascii ? { ascii } : {}
3534
3598
  }));
3535
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
3599
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
3536
3600
  name: field,
3537
3601
  type,
3538
3602
  nullable: true,
3539
- ...multi ? { multi } : {}
3603
+ ...multi ? { multi } : {},
3604
+ ...maxLength === void 0 ? {} : { maxLength },
3605
+ ...ascii ? { ascii } : {}
3540
3606
  });
3541
3607
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
3542
3608
  name: metric,
@@ -4302,13 +4368,10 @@ const createDatabaseEngine = ({ batching, now = Date.now, meter, ...options }) =
4302
4368
  };
4303
4369
  return {
4304
4370
  ...engine,
4305
- /** Applies batched aggregate changes still pending: this process's buffer and the log. */
4371
+ /** Applies the batched aggregate changes still in the log. */
4306
4372
  flush: async () => {
4307
4373
  await batches?.flush();
4308
4374
  },
4309
- dispose: async () => {
4310
- await batches?.dispose();
4311
- },
4312
4375
  database(module) {
4313
4376
  const name = (model) => module.namespace ? `${module.namespace}_${model}` : model;
4314
4377
  return {
@@ -4389,8 +4452,7 @@ const createEngine = (database, { plugins = [], now = Date.now } = {}) => {
4389
4452
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
4390
4453
  return engine.database(module);
4391
4454
  },
4392
- flush: () => engine.flush(),
4393
- dispose: () => engine.dispose()
4455
+ flush: () => engine.flush()
4394
4456
  };
4395
4457
  };
4396
4458
  //#endregion
@@ -4683,7 +4745,7 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
4683
4745
  };
4684
4746
  //#endregion
4685
4747
  //#region ../../packages/server/dist/version.mjs
4686
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.3";
4748
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.30";
4687
4749
  //#endregion
4688
4750
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
4689
4751
  /**
@@ -5476,8 +5538,8 @@ const baseBundleIdsOf = (row, range, bundleId, limit) => {
5476
5538
  //#endregion
5477
5539
  //#region ../../packages/server/dist/core/reads.mjs
5478
5540
  const PAGE$3 = 500;
5479
- const pick$1 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
5480
- const toBundleRow = pick$1([
5541
+ const pick$2 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
5542
+ const toBundleRow = pick$2([
5481
5543
  "id",
5482
5544
  "platform",
5483
5545
  "git_commit_hash",
@@ -5486,7 +5548,7 @@ const toBundleRow = pick$1([
5486
5548
  "manifest_file_hash",
5487
5549
  "asset_base_storage_uri"
5488
5550
  ]);
5489
- const toPatchRow = pick$1([
5551
+ const toPatchRow = pick$2([
5490
5552
  "id",
5491
5553
  "bundle_id",
5492
5554
  "base_bundle_id",
@@ -5496,7 +5558,7 @@ const toPatchRow = pick$1([
5496
5558
  "byte_size",
5497
5559
  "order_index"
5498
5560
  ]);
5499
- const toReleaseRow = pick$1([
5561
+ const toReleaseRow = pick$2([
5500
5562
  "id",
5501
5563
  "revision",
5502
5564
  "scope_key",
@@ -5517,7 +5579,7 @@ const toReleaseRow = pick$1([
5517
5579
  "created_at_ms",
5518
5580
  "updated_at_ms"
5519
5581
  ]);
5520
- const toCatalogRow = pick$1([
5582
+ const toCatalogRow = pick$2([
5521
5583
  "scope_key",
5522
5584
  "catalog_id",
5523
5585
  "strategy",
@@ -5532,7 +5594,7 @@ const toCatalogRow = pick$1([
5532
5594
  "is_tombstone",
5533
5595
  "updated_at_ms"
5534
5596
  ]);
5535
- const toChannelRow = pick$1(["id", "name"]);
5597
+ const toChannelRow = pick$2(["id", "name"]);
5536
5598
  /** Every page of one read, in order. */
5537
5599
  const drain$1 = async (read) => {
5538
5600
  const rows = [];
@@ -5545,7 +5607,15 @@ const drain$1 = async (read) => {
5545
5607
  return rows;
5546
5608
  };
5547
5609
  /** 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 } };
5610
+ /** A keyset read's range on its index's order: past `after`, up to `through`. */
5611
+ const after = (input) => {
5612
+ const asc = (input.order ?? "asc") === "asc";
5613
+ const range = {
5614
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
5615
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
5616
+ };
5617
+ return Object.keys(range).length === 0 ? {} : { range };
5618
+ };
5549
5619
  /** Core's reads, each through one declared index or key. */
5550
5620
  const createCoreReads = (db, storage) => {
5551
5621
  /** A bundle row's patches, exactly as many as its reference counter holds. */
@@ -5750,6 +5820,321 @@ const createCoreReads = (db, storage) => {
5750
5820
  };
5751
5821
  };
5752
5822
  //#endregion
5823
+ //#region ../../packages/server/dist/core/iosDevices.mjs
5824
+ /**
5825
+ * A device's UDID: 40 hex digits, or 8 and 16 joined by a hyphen. The same
5826
+ * rule as `normalizeIosUdid` of `@hot-updater/protocol/native-artifact`,
5827
+ * implemented here so the server's runtime never loads the artifact readers.
5828
+ */
5829
+ const UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
5830
+ /** The form the registry stores and compares a UDID in, or null for text that isn't one. */
5831
+ const normalizeIosUdid = (value) => {
5832
+ const trimmed = value.trim();
5833
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
5834
+ };
5835
+ /** `ios_devices.name`'s bound in core's schema. */
5836
+ const NAME_MAX_LENGTH = 100;
5837
+ /** `ios_devices.requested_by` and `approved_by`'s bound: an email address. */
5838
+ const EMAIL_MAX_LENGTH = 320;
5839
+ /** `ios_devices.apple_issuer_id`'s bound. */
5840
+ const ISSUER_MAX_LENGTH = 64;
5841
+ /** How many registry rows one read takes while finding its account. */
5842
+ const ACCOUNT_SCAN_PAGE = 200;
5843
+ /** The one row of `ios_device_account`. */
5844
+ const ACCOUNT_ROW = "registry";
5845
+ /** `ios_devices.apple_error`'s bound. */
5846
+ const ERROR_MAX_LENGTH = 512;
5847
+ const STATUSES = [
5848
+ "pending",
5849
+ "approved",
5850
+ "registered"
5851
+ ];
5852
+ const OUTCOMES = [
5853
+ "registered",
5854
+ "refused",
5855
+ "disabled",
5856
+ "missing"
5857
+ ];
5858
+ /** The `apple_error` of a device Apple has disabled. */
5859
+ const IOS_DEVICE_DISABLED_ERROR = "Disabled in the Apple account.";
5860
+ /** The `apple_error` of a registered device Apple no longer lists. */
5861
+ const IOS_DEVICE_MISSING_ERROR = "Gone from the Apple account. Approve it again to register it.";
5862
+ /** A device or registry request core cannot store: the caller's input. */
5863
+ var IosDeviceInputError = class extends TypeError {
5864
+ name = "IosDeviceInputError";
5865
+ };
5866
+ const pick$1 = (row) => ({
5867
+ id: row.id,
5868
+ udid: row.udid,
5869
+ name: row.name,
5870
+ status: row.status,
5871
+ requested_by: row.requested_by ?? null,
5872
+ created_at_ms: row.created_at_ms,
5873
+ approved_by: row.approved_by ?? null,
5874
+ approved_at_ms: row.approved_at_ms ?? null,
5875
+ registered_at_ms: row.registered_at_ms ?? null,
5876
+ apple_issuer_id: row.apple_issuer_id ?? null,
5877
+ apple_error: row.apple_error ?? null,
5878
+ build_id: row.build_id ?? null
5879
+ });
5880
+ const udidOf = (udid) => {
5881
+ const key = typeof udid === "string" ? normalizeIosUdid(udid) : null;
5882
+ if (key === null) throw new IosDeviceInputError("Invalid iOS device: udid must be 40 hex digits, or 8 and 16 joined by a hyphen.");
5883
+ return key;
5884
+ };
5885
+ const nameOf = (name) => {
5886
+ const trimmed = typeof name === "string" ? name.trim() : "";
5887
+ if (trimmed.length === 0 || trimmed.length > NAME_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: name must be 1 to ${NAME_MAX_LENGTH} characters.`);
5888
+ return trimmed;
5889
+ };
5890
+ /** An email, lower-cased, or null for the CLI. */
5891
+ const personOf = (value, field) => {
5892
+ if (value === null) return null;
5893
+ const email = typeof value === "string" ? value.trim().toLowerCase() : "";
5894
+ 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.`);
5895
+ return email;
5896
+ };
5897
+ /** Apple's words, on one line and within the column's bound. */
5898
+ const errorText = (text) => {
5899
+ const line = text.replace(/\s+/gu, " ").trim();
5900
+ return line.length > ERROR_MAX_LENGTH ? `${line.slice(0, 511)}…` : line;
5901
+ };
5902
+ /**
5903
+ * The iOS device registry: the iPhones and iPads a team asked to install ad hoc
5904
+ * builds on. The Console writes requests and approvals, and the CLI what Apple
5905
+ * said, each over the row it read.
5906
+ */
5907
+ const createIosDeviceApi = (db, { now = Date.now } = {}) => {
5908
+ const findIosDevice = async (udid) => {
5909
+ const key = normalizeIosUdid(udid);
5910
+ if (key === null) return null;
5911
+ const row = await db.findOne("ios_devices", { udid: key });
5912
+ return row === null ? null : pick$1(row);
5913
+ };
5914
+ /**
5915
+ * The issuer of the registry's earliest registration among its rows, by
5916
+ * when and then by ID, or null when no row names one: read only while the
5917
+ * registry has no account yet, a page at a time.
5918
+ */
5919
+ const accountOfRows = async () => {
5920
+ let earliest = null;
5921
+ for (let after;;) {
5922
+ const { rows } = await db.findMany("ios_devices", {
5923
+ index: "all",
5924
+ where: {},
5925
+ order: "asc",
5926
+ limit: ACCOUNT_SCAN_PAGE,
5927
+ ...after === void 0 ? {} : { range: { gt: after } }
5928
+ });
5929
+ for (const row of rows.map(pick$1)) {
5930
+ if (row.apple_issuer_id === null) continue;
5931
+ if (earliest === null || (row.registered_at_ms ?? 0) < (earliest.registered_at_ms ?? 0)) earliest = row;
5932
+ }
5933
+ if (rows.length < ACCOUNT_SCAN_PAGE) return earliest?.apple_issuer_id ?? null;
5934
+ after = rows.at(-1).id;
5935
+ }
5936
+ };
5937
+ return {
5938
+ async listIosDevices(input) {
5939
+ if (input.status !== void 0 && !STATUSES.includes(input.status)) throw new IosDeviceInputError(`Invalid iOS device status: ${String(input.status)}. Expected ${STATUSES.join(", ")}.`);
5940
+ const page = {
5941
+ order: input.order ?? "asc",
5942
+ limit: input.limit,
5943
+ ...after(input)
5944
+ };
5945
+ const { rows } = input.status === void 0 ? await db.findMany("ios_devices", {
5946
+ index: "all",
5947
+ where: {},
5948
+ ...page
5949
+ }) : await db.findMany("ios_devices", {
5950
+ index: "byStatus",
5951
+ where: { status: input.status },
5952
+ ...page
5953
+ });
5954
+ return rows.map(pick$1);
5955
+ },
5956
+ findIosDevice,
5957
+ async requestIosDevice(input) {
5958
+ const udid = udidOf(input.udid);
5959
+ const name = nameOf(input.name);
5960
+ const requestedBy = personOf(input.requestedBy, "requestedBy");
5961
+ const existing = await db.findOne("ios_devices", { udid });
5962
+ if (existing !== null) return {
5963
+ device: pick$1(existing),
5964
+ created: false
5965
+ };
5966
+ const device = {
5967
+ id: createUUIDv7(),
5968
+ udid,
5969
+ name,
5970
+ status: "pending",
5971
+ requested_by: requestedBy,
5972
+ created_at_ms: now(),
5973
+ approved_by: null,
5974
+ approved_at_ms: null,
5975
+ registered_at_ms: null,
5976
+ apple_issuer_id: null,
5977
+ apple_error: null,
5978
+ build_id: null
5979
+ };
5980
+ try {
5981
+ await db.transaction(async (tx) => {
5982
+ tx.create("ios_devices", device);
5983
+ });
5984
+ } catch (error) {
5985
+ if (error instanceof DatabaseConstraintError && error.reason === "unique") {
5986
+ const winner = await db.findOne("ios_devices", { udid });
5987
+ if (winner !== null) return {
5988
+ device: pick$1(winner),
5989
+ created: false
5990
+ };
5991
+ }
5992
+ throw error;
5993
+ }
5994
+ return {
5995
+ device,
5996
+ created: true
5997
+ };
5998
+ },
5999
+ async approveIosDevice(id, input) {
6000
+ const name = input.name === void 0 ? void 0 : nameOf(input.name);
6001
+ const approvedBy = personOf(input.approvedBy, "approvedBy");
6002
+ return db.transaction(async (tx) => {
6003
+ const row = await tx.findOne("ios_devices", { id });
6004
+ if (row === null) return null;
6005
+ const device = pick$1(row);
6006
+ const set = {
6007
+ ...name === void 0 || name === device.name ? {} : { name },
6008
+ ...device.status === "pending" ? {
6009
+ status: "approved",
6010
+ approved_by: approvedBy,
6011
+ approved_at_ms: now()
6012
+ } : {}
6013
+ };
6014
+ if (Object.keys(set).length === 0) return device;
6015
+ tx.update("ios_devices", row, set);
6016
+ return {
6017
+ ...device,
6018
+ ...set
6019
+ };
6020
+ });
6021
+ },
6022
+ async renameIosDevice(id, input) {
6023
+ const name = nameOf(input);
6024
+ return db.transaction(async (tx) => {
6025
+ const row = await tx.findOne("ios_devices", { id });
6026
+ if (row === null) return null;
6027
+ const device = pick$1(row);
6028
+ if (device.name === name) return device;
6029
+ tx.update("ios_devices", row, { name });
6030
+ return {
6031
+ ...device,
6032
+ name
6033
+ };
6034
+ });
6035
+ },
6036
+ async recordIosDeviceOutcome({ id, seen, issuerId, outcome, reason }) {
6037
+ if (!OUTCOMES.includes(outcome)) throw new IosDeviceInputError(`Invalid iOS device outcome: ${String(outcome)}. Expected ${OUTCOMES.join(", ")}.`);
6038
+ 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.`);
6039
+ return db.transaction(async (tx) => {
6040
+ const row = await tx.findOne("ios_devices", { id });
6041
+ if (row === null) return null;
6042
+ const device = pick$1(row);
6043
+ if (device.status !== seen.status || device.approved_at_ms !== seen.approvedAtMs || device.apple_issuer_id !== null && device.apple_issuer_id !== issuerId) return null;
6044
+ let set;
6045
+ switch (outcome) {
6046
+ case "registered":
6047
+ if (device.status === "pending") return null;
6048
+ set = {
6049
+ status: "registered",
6050
+ registered_at_ms: device.registered_at_ms ?? now(),
6051
+ apple_issuer_id: issuerId,
6052
+ apple_error: null
6053
+ };
6054
+ break;
6055
+ case "refused":
6056
+ if (device.status !== "approved") return null;
6057
+ set = { apple_error: errorText(reason === void 0 || reason.trim() === "" ? "Apple refused it." : reason) };
6058
+ break;
6059
+ case "disabled":
6060
+ if (device.status === "pending") return null;
6061
+ set = { apple_error: IOS_DEVICE_DISABLED_ERROR };
6062
+ break;
6063
+ case "missing":
6064
+ if (device.status !== "registered") return null;
6065
+ set = {
6066
+ status: "pending",
6067
+ approved_by: null,
6068
+ approved_at_ms: null,
6069
+ apple_error: IOS_DEVICE_MISSING_ERROR
6070
+ };
6071
+ }
6072
+ if (Object.entries(set).some(([column, value]) => device[column] !== (value ?? null))) tx.update("ios_devices", row, set);
6073
+ return {
6074
+ ...device,
6075
+ ...set
6076
+ };
6077
+ });
6078
+ },
6079
+ async markIosDevicesInBuild({ buildId, ids }) {
6080
+ for (const id of new Set(ids)) await db.transaction(async (tx) => {
6081
+ const row = await tx.findOne("ios_devices", { id });
6082
+ if (row === null || typeof row.build_id === "string" && row.build_id >= buildId) return;
6083
+ tx.update("ios_devices", row, { build_id: buildId });
6084
+ });
6085
+ },
6086
+ async claimIosDeviceAccount(issuerId) {
6087
+ 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.`);
6088
+ const answer = (held) => ({
6089
+ issuerId: held,
6090
+ claimed: held === issuerId
6091
+ });
6092
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6093
+ if (existing !== null) return answer(existing.apple_issuer_id);
6094
+ const holder = await accountOfRows() ?? issuerId;
6095
+ try {
6096
+ await db.transaction(async (tx) => {
6097
+ tx.create("ios_device_account", {
6098
+ id: ACCOUNT_ROW,
6099
+ apple_issuer_id: holder,
6100
+ claimed_at_ms: now()
6101
+ });
6102
+ });
6103
+ return answer(holder);
6104
+ } catch (error) {
6105
+ if (error instanceof DatabaseConstraintError && (error.reason === "exists" || error.reason === "unique")) {
6106
+ const winner = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
6107
+ if (winner !== null) return answer(winner.apple_issuer_id);
6108
+ }
6109
+ throw error;
6110
+ }
6111
+ },
6112
+ async deleteIosDevice(id, only) {
6113
+ const requestedBy = only?.requestedBy === void 0 ? void 0 : personOf(only.requestedBy, "requestedBy");
6114
+ return db.transaction(async (tx) => {
6115
+ const row = await tx.findOne("ios_devices", { id });
6116
+ if (row === null) return null;
6117
+ const device = pick$1(row);
6118
+ if (only?.status !== void 0 && device.status !== only.status || requestedBy !== void 0 && device.requested_by !== requestedBy) return null;
6119
+ await tx.delete("ios_devices", row);
6120
+ return device;
6121
+ });
6122
+ }
6123
+ };
6124
+ };
6125
+ //#endregion
6126
+ //#region ../../packages/server/dist/core/nativeBuildDestinations.mjs
6127
+ /** Store destinations accepted for each native platform. */
6128
+ const NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
6129
+ android: [
6130
+ "play-internal",
6131
+ "play-closed",
6132
+ "play-open",
6133
+ "play-production"
6134
+ ],
6135
+ ios: ["testflight"]
6136
+ };
6137
+ //#endregion
5753
6138
  //#region ../../packages/server/dist/core/writes.mjs
5754
6139
  const PAGE$2 = 500;
5755
6140
  /** Moves one bundle into or out of its platform's total and the overall total. */
@@ -5867,6 +6252,13 @@ const GIT_COMMIT_HASH_MAX_LENGTH = 255;
5867
6252
  * and looks up nothing else.
5868
6253
  */
5869
6254
  const BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
6255
+ /** `native_builds.sandbox_url_scheme`'s bound in core's schema. */
6256
+ const SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
6257
+ /**
6258
+ * A URL scheme as RFC 3986 spells it, in lower case: what a sandbox build's
6259
+ * artifact registers, as `@hot-updater/protocol/native-artifact` reads it.
6260
+ */
6261
+ const URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
5870
6262
  /** A native build or scope core cannot store or look up: the caller's input. */
5871
6263
  var NativeBuildInputError = class extends TypeError {
5872
6264
  name = "NativeBuildInputError";
@@ -5888,13 +6280,32 @@ const pick = (row) => ({
5888
6280
  build_number: row.build_number ?? null,
5889
6281
  submitted_to: row.submitted_to ?? null,
5890
6282
  submitted_at_ms: row.submitted_at_ms ?? null,
5891
- submitted_version: row.submitted_version ?? null
6283
+ submitted_version: row.submitted_version ?? null,
6284
+ is_store_build: row.is_store_build === true,
6285
+ is_sandbox: row.is_sandbox === true,
6286
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
6287
+ export_method: row.export_method ?? null
5892
6288
  });
5893
- /** The store track each platform's builds are submitted to. */
5894
- const SUBMISSION_DESTINATIONS = {
5895
- android: "play-internal",
5896
- ios: "testflight"
5897
- };
6289
+ /** The export methods an `.ipa` registers with. */
6290
+ const EXPORT_METHODS = /* @__PURE__ */ new Set([
6291
+ "app-store",
6292
+ "ad-hoc",
6293
+ "development",
6294
+ "enterprise"
6295
+ ]);
6296
+ /**
6297
+ * The channels only sandbox builds register on: a registration's `sandbox`
6298
+ * must agree with it. The registry's convention, as
6299
+ * `@hot-updater/protocol/native-artifact` checks it for a build's artifact.
6300
+ */
6301
+ const SANDBOX_CHANNEL_PREFIX = "sandbox-";
6302
+ /**
6303
+ * How many older builds of a scope one read takes, looking for one older than
6304
+ * a bundle when a build made after the bundle is the newest.
6305
+ */
6306
+ const OLDER_BUILDS_PAGE = 20;
6307
+ /** How many times a mark runs again after losing its scope's mark to another. */
6308
+ const MARK_ATTEMPTS = 8;
5898
6309
  /** `native_builds.build_number`'s bound in core's schema. */
5899
6310
  const BUILD_NUMBER_MAX_LENGTH = 64;
5900
6311
  /** `native_builds.submitted_version`'s bound in core's schema. */
@@ -5927,17 +6338,29 @@ const nativeBuildScopeKey = (scope) => {
5927
6338
  };
5928
6339
  /** Whether `bundleId` is a native build's built-in bundle: one unique read. */
5929
6340
  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 }) => {
6341
+ const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, exportMethod, artifact }) => {
5931
6342
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
5932
6343
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
5933
6344
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
5934
6345
  if (channel.trim().length === 0) return "channel is required";
6346
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
6347
+ const reserved = channel.startsWith(SANDBOX_CHANNEL_PREFIX);
6348
+ if (isSandbox === true && !reserved) return `a sandbox build registers on a ${SANDBOX_CHANNEL_PREFIX}* channel, not ${channel}`;
6349
+ if (isSandbox !== true && reserved) return `channel ${channel} is reserved for sandbox builds`;
6350
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
6351
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
6352
+ 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`;
6353
+ }
5935
6354
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
5936
6355
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
5937
6356
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
5938
6357
  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`;
5939
6358
  const kinds = ARTIFACT_KINDS[platform];
5940
6359
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
6360
+ if (exportMethod !== void 0 && exportMethod !== null) {
6361
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
6362
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
6363
+ }
5941
6364
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
5942
6365
  return null;
5943
6366
  };
@@ -5966,7 +6389,11 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
5966
6389
  build_number: registration.buildNumber ?? null,
5967
6390
  submitted_to: null,
5968
6391
  submitted_at_ms: null,
5969
- submitted_version: null
6392
+ submitted_version: null,
6393
+ is_store_build: false,
6394
+ is_sandbox: registration.isSandbox === true,
6395
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
6396
+ export_method: registration.exportMethod ?? null
5970
6397
  };
5971
6398
  for (let attempt = 1;; attempt += 1) {
5972
6399
  await insertChannel(db, {
@@ -6004,21 +6431,42 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6004
6431
  const scopeKey = nativeBuildScopeKey(scope);
6005
6432
  const buildKey = options?.buildKey;
6006
6433
  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]);
6434
+ if (options?.storeBuild) {
6435
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
6436
+ return marked === null ? null : pick(marked);
6437
+ }
6438
+ const read = (limit, before) => {
6439
+ const page = {
6440
+ order: "desc",
6441
+ limit,
6442
+ ...before === void 0 ? {} : { range: { lt: before } }
6443
+ };
6444
+ return buildKey === void 0 ? db.findMany("native_builds", {
6445
+ index: "byScope",
6446
+ where: { scope_key: scopeKey },
6447
+ ...page
6448
+ }) : db.findMany("native_builds", {
6449
+ index: "byBuildKey",
6450
+ where: {
6451
+ scope_key: scopeKey,
6452
+ build_key: buildKey
6453
+ },
6454
+ ...page
6455
+ });
6456
+ };
6457
+ const { rows } = await read(1);
6458
+ const newest = rows[0];
6459
+ if (newest === void 0) return null;
6460
+ const bundleId = options?.builtInOlderThan;
6461
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return pick(newest);
6462
+ for (let before = newest.id;;) {
6463
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
6464
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
6465
+ if (usable !== void 0) return pick(usable);
6466
+ const last = older.at(-1);
6467
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
6468
+ before = last.id;
6469
+ }
6022
6470
  },
6023
6471
  async recordNativeBuildSubmission(id, { destination, version }) {
6024
6472
  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 +6474,8 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6026
6474
  const row = await tx.findOne("native_builds", { id });
6027
6475
  if (row === null) return null;
6028
6476
  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}.`);
6477
+ 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}.`);
6478
+ 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
6479
  const set = {
6031
6480
  submitted_to: destination,
6032
6481
  submitted_at_ms: now(),
@@ -6039,6 +6488,46 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
6039
6488
  };
6040
6489
  });
6041
6490
  },
6491
+ async markNativeBuild(id, { storeBuild }) {
6492
+ for (let attempt = 1;; attempt += 1) try {
6493
+ return await db.transaction(async (tx) => {
6494
+ const row = await tx.findOne("native_builds", { id });
6495
+ if (row === null) return null;
6496
+ const build = pick(row);
6497
+ if (!storeBuild) {
6498
+ if (build.is_store_build) tx.update("native_builds", row, { is_store_build: false });
6499
+ return {
6500
+ nativeBuild: {
6501
+ ...build,
6502
+ is_store_build: false
6503
+ },
6504
+ previous: null
6505
+ };
6506
+ }
6507
+ if (build.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
6508
+ if (build.is_store_build) return {
6509
+ nativeBuild: build,
6510
+ previous: null
6511
+ };
6512
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build.scope_key });
6513
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
6514
+ tx.update("native_builds", row, { is_store_build: true });
6515
+ return {
6516
+ nativeBuild: {
6517
+ ...build,
6518
+ is_store_build: true
6519
+ },
6520
+ previous: holder === null ? null : {
6521
+ ...pick(holder),
6522
+ is_store_build: false
6523
+ }
6524
+ };
6525
+ });
6526
+ } catch (error) {
6527
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
6528
+ throw error;
6529
+ }
6530
+ },
6042
6531
  async deleteNativeBuild(id) {
6043
6532
  return db.transaction(async (tx) => {
6044
6533
  const row = await tx.findOne("native_builds", { id });
@@ -6651,6 +7140,7 @@ const createCoreApi = (db, storage, options = {}) => {
6651
7140
  ...reads,
6652
7141
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
6653
7142
  ...createNativeBuildApi(db, options),
7143
+ ...createIosDeviceApi(db, options),
6654
7144
  /** One read, which checks the schema settings first. */
6655
7145
  ready: async () => {
6656
7146
  await reads.listReleaseCatalogs({ limit: 1 });
@@ -6870,10 +7360,12 @@ const keyset = (url, maxValue = LIMITS.maxValue) => {
6870
7360
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
6871
7361
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
6872
7362
  const cursor = url.searchParams.get("cursor");
7363
+ const through = url.searchParams.get("through");
6873
7364
  return {
6874
7365
  order,
6875
7366
  limit,
6876
- ...cursor === null ? {} : { after: cursor }
7367
+ ...cursor === null ? {} : { after: cursor },
7368
+ ...through === null ? {} : { through }
6877
7369
  };
6878
7370
  };
6879
7371
  /** A page and the cursor of the next one, when the page is full. */
@@ -6988,11 +7480,11 @@ const refusingInvalid = async (operation) => {
6988
7480
  try {
6989
7481
  return await operation();
6990
7482
  } catch (error) {
6991
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
7483
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
6992
7484
  throw error;
6993
7485
  }
6994
7486
  };
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));
7487
+ 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.exportMethod === void 0 || isTextOrNull$1(value.exportMethod)) && 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
7488
  const scopeKeyOf = (params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "";
6997
7489
  /** Every admin route's handler, by the name `ADMIN_ROUTES` mounts it under. */
6998
7490
  const createAdminRouteHandlers = () => ({
@@ -7121,7 +7613,13 @@ const createAdminRouteHandlers = () => ({
7121
7613
  const url = new URL(request.url);
7122
7614
  const scope = nativeBuildScopeOf(url);
7123
7615
  const buildKey = url.searchParams.get("buildKey");
7124
- return json$2({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
7616
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
7617
+ const options = {
7618
+ ...buildKey === null ? {} : { buildKey },
7619
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
7620
+ ...builtInOlderThan === null ? {} : { builtInOlderThan }
7621
+ };
7622
+ return json$2({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
7125
7623
  }),
7126
7624
  getNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
7127
7625
  listNativeBuilds: onCore(async (core, request) => {
@@ -7135,14 +7633,95 @@ const createAdminRouteHandlers = () => ({
7135
7633
  }),
7136
7634
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
7137
7635
  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.");
7636
+ 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
7637
  const submission = {
7140
7638
  destination: input.destination,
7141
7639
  version: input.version
7142
7640
  };
7143
7641
  return json$2({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
7144
7642
  }),
7643
+ markNativeBuild: onCore(async (core, request, params) => {
7644
+ const input = await body(request);
7645
+ if (!isRecord$5(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
7646
+ const mark = { storeBuild: input.storeBuild };
7647
+ return json$2({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
7648
+ }),
7145
7649
  deleteNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
7650
+ listIosDevices: onCore(async (core, request) => {
7651
+ const url = new URL(request.url);
7652
+ const input = keyset(url);
7653
+ const status = url.searchParams.get("status");
7654
+ return page(await refusingInvalid(() => core.listIosDevices({
7655
+ ...input,
7656
+ ...status === null ? {} : { status }
7657
+ })), input, ({ id }) => id);
7658
+ }),
7659
+ findIosDevice: onCore(async (core, _request, params) => json$2({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
7660
+ requestIosDevice: onCore(async (core, request) => {
7661
+ const input = await body(request);
7662
+ 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.");
7663
+ const device = {
7664
+ udid: input.udid,
7665
+ name: input.name,
7666
+ requestedBy: input.requestedBy
7667
+ };
7668
+ return json$2({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
7669
+ }),
7670
+ approveIosDevice: onCore(async (core, request, params) => {
7671
+ const input = await body(request);
7672
+ 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.");
7673
+ const approval = {
7674
+ approvedBy: input.approvedBy,
7675
+ ...input.name === void 0 ? {} : { name: input.name }
7676
+ };
7677
+ return json$2({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
7678
+ }),
7679
+ renameIosDevice: onCore(async (core, request, params) => {
7680
+ const input = await body(request);
7681
+ if (!isText$2(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
7682
+ const name = input.name;
7683
+ return json$2({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
7684
+ }),
7685
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
7686
+ const input = await body(request);
7687
+ const seen = input.seen;
7688
+ 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.");
7689
+ const outcome = {
7690
+ id: requireRouteParam(params, "id"),
7691
+ seen: {
7692
+ status: seen.status,
7693
+ approvedAtMs: seen.approvedAtMs
7694
+ },
7695
+ issuerId: input.issuerId,
7696
+ outcome: input.outcome,
7697
+ ...input.reason === void 0 ? {} : { reason: input.reason }
7698
+ };
7699
+ return json$2({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
7700
+ }),
7701
+ claimIosDeviceAccount: onCore(async (core, request) => {
7702
+ const { issuerId } = await body(request);
7703
+ if (!isText$2(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
7704
+ return json$2({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
7705
+ }),
7706
+ markIosDevicesInBuild: onCore(async (core, request) => {
7707
+ const { buildId, ids } = await body(request);
7708
+ 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.");
7709
+ await core.markIosDevicesInBuild({
7710
+ buildId,
7711
+ ids
7712
+ });
7713
+ return noContent();
7714
+ }),
7715
+ deleteIosDevice: onCore(async (core, request, params) => {
7716
+ const url = new URL(request.url);
7717
+ const status = url.searchParams.get("status");
7718
+ const requestedBy = url.searchParams.get("requestedBy");
7719
+ const only = {
7720
+ ...status === null ? {} : { status },
7721
+ ...requestedBy === null ? {} : { requestedBy }
7722
+ };
7723
+ return json$2({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
7724
+ }),
7146
7725
  deleteBundles: onCore(async (core, request) => {
7147
7726
  const { ids } = await body(request);
7148
7727
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -7287,10 +7866,60 @@ const ADMIN_ROUTES = [
7287
7866
  path: "/native-builds/:id/submission",
7288
7867
  handler: "recordNativeBuildSubmission"
7289
7868
  },
7869
+ {
7870
+ method: "POST",
7871
+ path: "/native-builds/:id/store-build",
7872
+ handler: "markNativeBuild"
7873
+ },
7290
7874
  {
7291
7875
  method: "DELETE",
7292
7876
  path: "/native-builds/:id",
7293
7877
  handler: "deleteNativeBuild"
7878
+ },
7879
+ {
7880
+ method: "GET",
7881
+ path: "/ios-devices",
7882
+ handler: "listIosDevices"
7883
+ },
7884
+ {
7885
+ method: "POST",
7886
+ path: "/ios-devices",
7887
+ handler: "requestIosDevice"
7888
+ },
7889
+ {
7890
+ method: "GET",
7891
+ path: "/ios-devices/udid/:udid",
7892
+ handler: "findIosDevice"
7893
+ },
7894
+ {
7895
+ method: "POST",
7896
+ path: "/ios-devices/in-build",
7897
+ handler: "markIosDevicesInBuild"
7898
+ },
7899
+ {
7900
+ method: "POST",
7901
+ path: "/ios-devices/account",
7902
+ handler: "claimIosDeviceAccount"
7903
+ },
7904
+ {
7905
+ method: "POST",
7906
+ path: "/ios-devices/:id/approval",
7907
+ handler: "approveIosDevice"
7908
+ },
7909
+ {
7910
+ method: "POST",
7911
+ path: "/ios-devices/:id/outcome",
7912
+ handler: "recordIosDeviceOutcome"
7913
+ },
7914
+ {
7915
+ method: "PATCH",
7916
+ path: "/ios-devices/:id",
7917
+ handler: "renameIosDevice"
7918
+ },
7919
+ {
7920
+ method: "DELETE",
7921
+ path: "/ios-devices/:id",
7922
+ handler: "deleteIosDevice"
7294
7923
  }
7295
7924
  ];
7296
7925
  //#endregion
@@ -12139,11 +12768,14 @@ const firebaseDatabase = (config) => ({
12139
12768
  //#region src/firebaseStorage.ts
12140
12769
  /** Signed URLs kept per adapter, enough for a few Bundles' assets. */
12141
12770
  const MAX_CACHED_SIGNED_URLS = 1e4;
12771
+ /** Objects deleted at once: Cloud Storage deletes one object a request. */
12772
+ const DELETE_CONCURRENCY = 16;
12142
12773
  const firebaseStorage = (config) => {
12143
12774
  const app = (0, firebase_admin_app.getApps)().length ? (0, firebase_admin_app.getApp)() : (0, firebase_admin_app.initializeApp)(config);
12144
12775
  let opened;
12145
12776
  const bucket = () => opened ??= (0, firebase_admin_storage.getStorage)(app).bucket(config.storageBucket);
12146
12777
  const getStorageKey = createStorageKeyBuilder(config.basePath);
12778
+ const basePrefix = getStorageKey() ? `${getStorageKey()}/` : "";
12147
12779
  /**
12148
12780
  * Signed URLs by object. Without a private key, as in Cloud Functions, each
12149
12781
  * signature is an IAM signBlob request, and an update check returns a URL
@@ -12232,6 +12864,39 @@ const firebaseStorage = (config) => {
12232
12864
  const { key } = parseAndValidate(storageUri);
12233
12865
  await bucket().file(key).delete({ ignoreNotFound: true });
12234
12866
  return { deleted: true };
12867
+ },
12868
+ async listObjects(prefix) {
12869
+ const folder = getStorageKey(prefix ?? "");
12870
+ const [files] = await bucket().getFiles({
12871
+ autoPaginate: true,
12872
+ prefix: folder ? `${folder}/` : ""
12873
+ });
12874
+ const objects = [];
12875
+ for (const file of files) {
12876
+ if (!file.name.startsWith(basePrefix)) continue;
12877
+ let storageUri;
12878
+ try {
12879
+ storageUri = createStorageUri({
12880
+ bucket: config.storageBucket,
12881
+ key: file.name,
12882
+ protocol: "gs"
12883
+ });
12884
+ } catch {
12885
+ continue;
12886
+ }
12887
+ const { size, updated } = file.metadata;
12888
+ objects.push({
12889
+ key: file.name.slice(basePrefix.length),
12890
+ ...updated ? { lastModifiedAt: new Date(updated) } : {},
12891
+ size: Number(size ?? 0),
12892
+ storageUri
12893
+ });
12894
+ }
12895
+ return objects;
12896
+ },
12897
+ async deleteObjects(relativeKeys) {
12898
+ const keys = relativeKeys.map((key) => getStorageKey(key));
12899
+ 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
12900
  }
12236
12901
  });
12237
12902
  };