@hot-updater/cloudflare 1.2.0-rc.4 → 1.2.0-rc.40

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.
@@ -2600,9 +2600,35 @@ var nativeBuilds = defineTable({
2600
2600
  type: "string",
2601
2601
  maxLength: 255,
2602
2602
  required: false
2603
+ },
2604
+ is_store_build: { type: "boolean" },
2605
+ is_sandbox: { type: "boolean" },
2606
+ sandbox_url_scheme: {
2607
+ type: "string",
2608
+ maxLength: 255,
2609
+ ascii: true,
2610
+ required: false
2611
+ },
2612
+ export_method: {
2613
+ type: "string",
2614
+ maxLength: 16,
2615
+ required: false
2616
+ },
2617
+ native_app_version: {
2618
+ type: "string",
2619
+ required: false
2603
2620
  }
2604
2621
  }, {
2605
2622
  key: ["id"],
2623
+ derived: {
2624
+ /** The scope this build is the store build of; null on every other. */
2625
+ store_build_scope_key: {
2626
+ type: "string",
2627
+ maxLength: 2048,
2628
+ ascii: true,
2629
+ compute: /* @__PURE__ */ __name((row) => row.is_store_build ? row.scope_key : null, "compute")
2630
+ }
2631
+ },
2606
2632
  indexes: {
2607
2633
  byScope: {
2608
2634
  eq: ["scope_key"],
@@ -2612,6 +2638,11 @@ var nativeBuilds = defineTable({
2612
2638
  eq: ["scope_key", "build_key"],
2613
2639
  sort: ["id"]
2614
2640
  },
2641
+ byStoreBuild: {
2642
+ eq: ["store_build_scope_key"],
2643
+ sort: [],
2644
+ unique: true
2645
+ },
2615
2646
  byChannel: {
2616
2647
  eq: ["channel_id"],
2617
2648
  sort: ["id"],
@@ -2623,6 +2654,92 @@ var nativeBuilds = defineTable({
2623
2654
  }
2624
2655
  }
2625
2656
  });
2657
+ var iosDevices = defineTable({
2658
+ id: {
2659
+ type: "string",
2660
+ maxLength: 36
2661
+ },
2662
+ udid: {
2663
+ type: "string",
2664
+ maxLength: 40,
2665
+ ascii: true,
2666
+ unique: true
2667
+ },
2668
+ name: {
2669
+ type: "string",
2670
+ maxLength: 100
2671
+ },
2672
+ status: {
2673
+ type: "string",
2674
+ maxLength: 16
2675
+ },
2676
+ requested_by: {
2677
+ type: "string",
2678
+ maxLength: 320,
2679
+ required: false
2680
+ },
2681
+ created_at_ms: { type: "integer" },
2682
+ approved_by: {
2683
+ type: "string",
2684
+ maxLength: 320,
2685
+ required: false
2686
+ },
2687
+ approved_at_ms: {
2688
+ type: "integer",
2689
+ required: false
2690
+ },
2691
+ registered_at_ms: {
2692
+ type: "integer",
2693
+ required: false
2694
+ },
2695
+ apple_issuer_id: {
2696
+ type: "string",
2697
+ maxLength: 64,
2698
+ ascii: true,
2699
+ required: false
2700
+ },
2701
+ apple_error: {
2702
+ type: "string",
2703
+ maxLength: 512,
2704
+ required: false
2705
+ },
2706
+ build_id: {
2707
+ type: "string",
2708
+ maxLength: 36,
2709
+ required: false
2710
+ }
2711
+ }, {
2712
+ key: ["id"],
2713
+ indexes: {
2714
+ byStatus: {
2715
+ eq: ["status"],
2716
+ sort: ["id"]
2717
+ },
2718
+ all: {
2719
+ eq: [],
2720
+ sort: ["id"]
2721
+ }
2722
+ }
2723
+ });
2724
+ var iosDeviceAccount = defineTable({
2725
+ id: {
2726
+ type: "string",
2727
+ maxLength: 16,
2728
+ ascii: true
2729
+ },
2730
+ apple_issuer_id: {
2731
+ type: "string",
2732
+ maxLength: 64,
2733
+ ascii: true
2734
+ },
2735
+ claimed_at_ms: { type: "integer" }
2736
+ }, {
2737
+ key: ["id"],
2738
+ indexes: { all: {
2739
+ eq: [],
2740
+ sort: ["id"]
2741
+ } }
2742
+ });
2626
2743
  var coreSchema = {
2627
2744
  bundles,
2628
2745
  bundle_patches: bundlePatches,
@@ -2640,7 +2757,9 @@ var coreSchema = {
2640
2757
  sort: []
2641
2758
  } }
2642
2759
  }),
2643
- native_builds: nativeBuilds
2760
+ native_builds: nativeBuilds,
2761
+ ios_devices: iosDevices,
2762
+ ios_device_account: iosDeviceAccount
2644
2763
  };
2645
2764
  var coreModule = {
2646
2765
  id: "core",
@@ -2813,10 +2932,7 @@ var LOG_TABLES = [
2813
2932
  var LEASE_TABLE = "aggregate_lease";
2814
2933
  var LEASE = { id: "compaction" };
2815
2934
  var LEASE_MS = 3e4;
2816
- var WINDOW_MS = {
2817
- log: 6e4,
2818
- memory: 15e3
2819
- };
2935
+ var WINDOW_MS = 6e4;
2820
2936
  var LOG_PAGE = 200;
2821
2937
  var GROUPS = {
2822
2938
  commit: 1,
@@ -2824,7 +2940,6 @@ var GROUPS = {
2824
2940
  flush: 256
2825
2941
  };
2826
2942
  var ATTEMPTS = 5;
2827
- var MAX_BUFFERED = 1e4;
2828
2943
  var log = defineTable({
2829
2944
  id: {
2830
2945
  type: "string",
@@ -2926,8 +3041,8 @@ var rewrite2 = /* @__PURE__ */ __name((change, key, current) => {
2926
3041
  previous: current
2927
3042
  };
2928
3043
  }, "rewrite");
2929
- var compile = /* @__PURE__ */ __name(async (adapter, changes, shard) => {
2930
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
3044
+ var compile = /* @__PURE__ */ __name(async (adapter, changes) => {
3045
+ const keys = changes.map(({ key }) => [...key.slice(0, -1), 0]);
2931
3046
  const reads = /* @__PURE__ */ new Map();
2932
3047
  changes.forEach((change, at) => {
2933
3048
  if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
@@ -2973,7 +3088,7 @@ var encode2 = /* @__PURE__ */ __name(async (changes) => {
2973
3088
  const zipped = await deflate(json4);
2974
3089
  return zipped !== void 0 && zipped.length < json4.length ? `z${zipped}` : json4;
2975
3090
  }, "encode");
2976
- var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS[mode] }, now }) => {
3091
+ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema, batching: { windowMs = WINDOW_MS }, now }) => {
2977
3092
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
2978
3093
  const holder = crypto.randomUUID().replaceAll("-", "");
2979
3094
  const table = /* @__PURE__ */ __name((name) => schema.models.get(name).table, "table");
@@ -3000,61 +3115,6 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3000
3115
  }
3001
3116
  return changes;
3002
3117
  }, "decode");
3003
- const apply = /* @__PURE__ */ __name(async (changes, shard) => {
3004
- let rest = changes;
3005
- let ops = [];
3006
- let read = true;
3007
- for (let failures = 0; rest.length > 0 && failures < ATTEMPTS; ) try {
3008
- if (read) ops = await compile(adapter, rest, shard);
3009
- let size = rest.length;
3010
- const chunk = /* @__PURE__ */ __name(() => ops.slice(0, size).filter(isOp), "chunk");
3011
- while (size > 1 && !adapter.fits(chunk())) size = Math.ceil(size / 2);
3012
- let result = { ok: true };
3013
- if (chunk().length > 0) result = await adapter.write(chunk()).catch((error) => {
3014
- warn("flush")(error);
3015
- return { ok: true };
3016
- });
3017
- read = !result.ok && !("retry" in result);
3018
- if (result.ok) {
3019
- rest = rest.slice(size);
3020
- ops = ops.slice(size);
3021
- failures = 0;
3022
- } else {
3023
- failures += 1;
3024
- if (!read) await sleep(failures);
3025
- }
3026
- } catch (error) {
3027
- warn("flush")(error);
3028
- return rest;
3029
- }
3030
- return rest;
3031
- }, "apply");
3032
- let buffer = /* @__PURE__ */ new Map();
3033
- let timer;
3034
- let flushing;
3035
- const shards = /* @__PURE__ */ new Map();
3036
- const processShard = /* @__PURE__ */ __name((model) => {
3037
- if (!shards.has(model)) shards.set(model, Math.floor(Math.random() * shapeOf(model).shards));
3038
- return shards.get(model);
3039
- }, "processShard");
3040
- const schedule = /* @__PURE__ */ __name(() => {
3041
- if (timer !== void 0 || buffer.size === 0) return;
3042
- timer = setTimeout(() => {
3043
- timer = void 0;
3044
- flushBuffer();
3045
- }, windowMs);
3046
- timer.unref?.();
3047
- }, "schedule");
3048
- const flushBuffer = /* @__PURE__ */ __name(() => flushing ??= (async () => {
3049
- clearTimeout(timer);
3050
- timer = void 0;
3051
- const pending = [...buffer.values()];
3052
- buffer = /* @__PURE__ */ new Map();
3053
- mergeAll(buffer, await apply(pending, processShard));
3054
- })().catch(warn("flush")).finally(() => {
3055
- flushing = void 0;
3056
- schedule();
3057
- }), "flushBuffer");
3058
3118
  let nextDue = 0;
3059
3119
  let compacting;
3060
3120
  const known = /* @__PURE__ */ new Map();
@@ -3176,7 +3236,7 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3176
3236
  more
3177
3237
  };
3178
3238
  }, "readLogs");
3179
- const rowsFor = /* @__PURE__ */ __name(async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp), "rowsFor");
3239
+ const rowsFor = /* @__PURE__ */ __name(async (changes) => (await compile(adapter, changes)).filter(isOp), "rowsFor");
3180
3240
  const applyGroup = /* @__PURE__ */ __name(async (held, logs) => {
3181
3241
  for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
3182
3242
  const batch = logs.slice(0, count);
@@ -3256,19 +3316,6 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3256
3316
  }))).then((pages) => pages.some((page2) => page2.rows.length > 0)).finally(() => {
3257
3317
  checking = void 0;
3258
3318
  }), "hasPending");
3259
- const committed = /* @__PURE__ */ __name(async (changes) => {
3260
- if (mode === "log") {
3261
- if (now() >= nextDue) await compact(false, GROUPS.commit);
3262
- return;
3263
- }
3264
- mergeAll(buffer, changes.values());
3265
- schedule();
3266
- if (buffer.size >= MAX_BUFFERED) await flushBuffer();
3267
- }, "committed");
3268
- const flush = /* @__PURE__ */ __name(async () => {
3269
- await flushBuffer();
3270
- if (mode === "log" && await hasPending()) await compact(true, GROUPS.flush);
3271
- }, "flush");
3272
3319
  return {
3273
3320
  async transaction(fn) {
3274
3321
  let changes = /* @__PURE__ */ new Map();
@@ -3294,7 +3341,7 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3294
3341
  aggregate
3295
3342
  });
3296
3343
  if (failure) throw failure.error;
3297
- if (mode === "log" && attempt.size > 0) {
3344
+ if (attempt.size > 0) {
3298
3345
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
3299
3346
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
3300
3347
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -3308,24 +3355,18 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3308
3355
  open = false;
3309
3356
  }
3310
3357
  });
3311
- if (changes.size > 0) await committed(changes);
3358
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
3312
3359
  return result;
3313
3360
  },
3314
3361
  async beforeRead(name) {
3315
3362
  if (!isBatched(schema.models.get(name))) return;
3316
- if (buffer.size > 0 || flushing !== void 0) await flushBuffer();
3317
- if (mode === "log") {
3318
- if (await hasPending().catch((error) => {
3319
- warn("read")(error);
3320
- return false;
3321
- })) await compact(true, GROUPS.read);
3322
- }
3363
+ if (await hasPending().catch((error) => {
3364
+ warn("read")(error);
3365
+ return false;
3366
+ })) await compact(true, GROUPS.read);
3323
3367
  },
3324
- flush,
3325
- async dispose() {
3326
- clearTimeout(timer);
3327
- timer = void 0;
3328
- await flush();
3368
+ async flush() {
3369
+ if (await hasPending()) await compact(true, GROUPS.flush);
3329
3370
  }
3330
3371
  };
3331
3372
  }, "createAggregateBatches");
@@ -3444,7 +3485,8 @@ var fieldProblems = /* @__PURE__ */ __name((definition, add) => {
3444
3485
  else if (field.required === false) add(`key field "${name}" is nullable`);
3445
3486
  else if (field.type === "json") add(`key field "${name}" is json`);
3446
3487
  }
3447
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
3488
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
3489
+ for (const [name, { type, maxLength, ascii }] of bounded) {
3448
3490
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
3449
3491
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
3450
3492
  }
@@ -3557,11 +3599,13 @@ var resolveSchema = /* @__PURE__ */ __name((modules) => {
3557
3599
  ...maxLength === void 0 ? {} : { maxLength },
3558
3600
  ...ascii ? { ascii } : {}
3559
3601
  }));
3560
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
3602
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
3561
3603
  name: field,
3562
3604
  type,
3563
3605
  nullable: true,
3564
- ...multi ? { multi } : {}
3606
+ ...multi ? { multi } : {},
3607
+ ...maxLength === void 0 ? {} : { maxLength },
3608
+ ...ascii ? { ascii } : {}
3565
3609
  });
3566
3610
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
3567
3611
  name: metric,
@@ -4294,13 +4338,10 @@ var createDatabaseEngine = /* @__PURE__ */ __name(({ batching, now = Date.now, m
4294
4338
  }, "barePage");
4295
4339
  return {
4296
4340
  ...engine,
4297
- /** Applies batched aggregate changes still pending: this process's buffer and the log. */
4341
+ /** Applies the batched aggregate changes still in the log. */
4298
4342
  flush: /* @__PURE__ */ __name(async () => {
4299
4343
  await batches?.flush();
4300
4344
  }, "flush"),
4301
- dispose: /* @__PURE__ */ __name(async () => {
4302
- await batches?.dispose();
4303
- }, "dispose"),
4304
4345
  database(module) {
4305
4346
  const name = /* @__PURE__ */ __name((model) => module.namespace ? `${module.namespace}_${model}` : model, "name");
4306
4347
  return {
@@ -4368,8 +4409,7 @@ var createEngine = /* @__PURE__ */ __name((database, { plugins = [], now = Date.
4368
4409
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
4369
4410
  return engine.database(module);
4370
4411
  }, "database"),
4371
- flush: /* @__PURE__ */ __name(() => engine.flush(), "flush"),
4372
- dispose: /* @__PURE__ */ __name(() => engine.dispose(), "dispose")
4412
+ flush: /* @__PURE__ */ __name(() => engine.flush(), "flush")
4373
4413
  };
4374
4414
  }, "createEngine");
4375
4415
 
@@ -4632,7 +4672,7 @@ var createSqlAdapter = /* @__PURE__ */ __name(({ executor, tablePrefix = "", max
4632
4672
  }, "createSqlAdapter");
4633
4673
 
4634
4674
  // ../../packages/server/dist/package.mjs
4635
- var version = "1.2.0-rc.4";
4675
+ var version = "1.2.0-rc.40";
4636
4676
 
4637
4677
  // ../../packages/server/dist/version.mjs
4638
4678
  var HOT_UPDATER_SERVER_VERSION = version;
@@ -5484,7 +5524,14 @@ var drain = /* @__PURE__ */ __name(async (read) => {
5484
5524
  } while (cursor !== void 0);
5485
5525
  return rows;
5486
5526
  }, "drain");
5487
- var after = /* @__PURE__ */ __name((input) => input.after === void 0 ? {} : { range: (input.order ?? "asc") === "asc" ? { gt: input.after } : { lt: input.after } }, "after");
5527
+ var after = /* @__PURE__ */ __name((input) => {
5528
+ const asc = (input.order ?? "asc") === "asc";
5529
+ const range = {
5530
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
5531
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
5532
+ };
5533
+ return Object.keys(range).length === 0 ? {} : { range };
5534
+ }, "after");
5488
5535
  var createCoreReads = /* @__PURE__ */ __name((db, storage) => {
5489
5536
  const detail = /* @__PURE__ */ __name(async (row) => {
5490
5537
  const count = row._refs_bundle_patches_bundle_id ?? 0;
@@ -5687,6 +5734,296 @@ var createCoreReads = /* @__PURE__ */ __name((db, storage) => {
5687
5734
  };
5688
5735
  }, "createCoreReads");
5689
5736
 
5737
+ // ../../packages/server/dist/core/iosDevices.mjs
5738
+ var UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
5739
+ var normalizeIosUdid = /* @__PURE__ */ __name((value) => {
5740
+ const trimmed = value.trim();
5741
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
5742
+ }, "normalizeIosUdid");
5743
+ var NAME_MAX_LENGTH = 100;
5744
+ var EMAIL_MAX_LENGTH = 320;
5745
+ var ISSUER_MAX_LENGTH = 64;
5746
+ var ACCOUNT_SCAN_PAGE = 200;
5747
+ var ACCOUNT_ROW = "registry";
5748
+ var ERROR_MAX_LENGTH = 512;
5749
+ var STATUSES = [
5750
+ "pending",
5751
+ "approved",
5752
+ "registered"
5753
+ ];
5754
+ var OUTCOMES = [
5755
+ "registered",
5756
+ "refused",
5757
+ "disabled",
5758
+ "missing"
5759
+ ];
5760
+ var IOS_DEVICE_DISABLED_ERROR = "Disabled in the Apple account.";
5761
+ var IOS_DEVICE_MISSING_ERROR = "Gone from the Apple account. Approve it again to register it.";
5762
+ var IosDeviceInputError = class extends TypeError {
5763
+ static {
5764
+ __name(this, "IosDeviceInputError");
5765
+ }
5766
+ name = "IosDeviceInputError";
5767
+ };
5768
+ var pick2 = /* @__PURE__ */ __name((row) => ({
5769
+ id: row.id,
5770
+ udid: row.udid,
5771
+ name: row.name,
5772
+ status: row.status,
5773
+ requested_by: row.requested_by ?? null,
5774
+ created_at_ms: row.created_at_ms,
5775
+ approved_by: row.approved_by ?? null,
5776
+ approved_at_ms: row.approved_at_ms ?? null,
5777
+ registered_at_ms: row.registered_at_ms ?? null,
5778
+ apple_issuer_id: row.apple_issuer_id ?? null,
5779
+ apple_error: row.apple_error ?? null,
5780
+ build_id: row.build_id ?? null
5781
+ }), "pick");
5782
+ var udidOf = /* @__PURE__ */ __name((udid) => {
5783
+ const key = typeof udid === "string" ? normalizeIosUdid(udid) : null;
5784
+ if (key === null) throw new IosDeviceInputError("Invalid iOS device: udid must be 40 hex digits, or 8 and 16 joined by a hyphen.");
5785
+ return key;
5786
+ }, "udidOf");
5787
+ var nameOf = /* @__PURE__ */ __name((name) => {
5788
+ const trimmed = typeof name === "string" ? name.trim() : "";
5789
+ if (trimmed.length === 0 || trimmed.length > NAME_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: name must be 1 to ${NAME_MAX_LENGTH} characters.`);
5790
+ return trimmed;
5791
+ }, "nameOf");
5792
+ var personOf = /* @__PURE__ */ __name((value, field) => {
5793
+ if (value === null) return null;
5794
+ const email = typeof value === "string" ? value.trim().toLowerCase() : "";
5795
+ 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.`);
5796
+ return email;
5797
+ }, "personOf");
5798
+ var errorText = /* @__PURE__ */ __name((text) => {
5799
+ const line = text.replace(/\s+/gu, " ").trim();
5800
+ return line.length > ERROR_MAX_LENGTH ? `${line.slice(0, 511)}\u2026` : line;
5801
+ }, "errorText");
5802
+ var createIosDeviceApi = /* @__PURE__ */ __name((db, { now = Date.now } = {}) => {
5803
+ const findIosDevice = /* @__PURE__ */ __name(async (udid) => {
5804
+ const key = normalizeIosUdid(udid);
5805
+ if (key === null) return null;
5806
+ const row = await db.findOne("ios_devices", { udid: key });
5807
+ return row === null ? null : pick2(row);
5808
+ }, "findIosDevice");
5809
+ const accountOfRows = /* @__PURE__ */ __name(async () => {
5810
+ let earliest = null;
5811
+ for (let after2; ; ) {
5812
+ const { rows } = await db.findMany("ios_devices", {
5813
+ index: "all",
5814
+ where: {},
5815
+ order: "asc",
5816
+ limit: ACCOUNT_SCAN_PAGE,
5817
+ ...after2 === void 0 ? {} : { range: { gt: after2 } }
5818
+ });
5819
+ for (const row of rows.map(pick2)) {
5820
+ if (row.apple_issuer_id === null) continue;
5821
+ if (earliest === null || (row.registered_at_ms ?? 0) < (earliest.registered_at_ms ?? 0)) earliest = row;
5822
+ }
5823
+ if (rows.length < ACCOUNT_SCAN_PAGE) return earliest?.apple_issuer_id ?? null;
5824
+ after2 = rows.at(-1).id;
5825
+ }
5826
+ }, "accountOfRows");
5827
+ return {
5828
+ async listIosDevices(input) {
5829
+ if (input.status !== void 0 && !STATUSES.includes(input.status)) throw new IosDeviceInputError(`Invalid iOS device status: ${String(input.status)}. Expected ${STATUSES.join(", ")}.`);
5830
+ const page2 = {
5831
+ order: input.order ?? "asc",
5832
+ limit: input.limit,
5833
+ ...after(input)
5834
+ };
5835
+ const { rows } = input.status === void 0 ? await db.findMany("ios_devices", {
5836
+ index: "all",
5837
+ where: {},
5838
+ ...page2
5839
+ }) : await db.findMany("ios_devices", {
5840
+ index: "byStatus",
5841
+ where: { status: input.status },
5842
+ ...page2
5843
+ });
5844
+ return rows.map(pick2);
5845
+ },
5846
+ findIosDevice,
5847
+ async requestIosDevice(input) {
5848
+ const udid = udidOf(input.udid);
5849
+ const name = nameOf(input.name);
5850
+ const requestedBy = personOf(input.requestedBy, "requestedBy");
5851
+ const existing = await db.findOne("ios_devices", { udid });
5852
+ if (existing !== null) return {
5853
+ device: pick2(existing),
5854
+ created: false
5855
+ };
5856
+ const device = {
5857
+ id: createUUIDv7(),
5858
+ udid,
5859
+ name,
5860
+ status: "pending",
5861
+ requested_by: requestedBy,
5862
+ created_at_ms: now(),
5863
+ approved_by: null,
5864
+ approved_at_ms: null,
5865
+ registered_at_ms: null,
5866
+ apple_issuer_id: null,
5867
+ apple_error: null,
5868
+ build_id: null
5869
+ };
5870
+ try {
5871
+ await db.transaction(async (tx) => {
5872
+ tx.create("ios_devices", device);
5873
+ });
5874
+ } catch (error) {
5875
+ if (error instanceof DatabaseConstraintError && error.reason === "unique") {
5876
+ const winner = await db.findOne("ios_devices", { udid });
5877
+ if (winner !== null) return {
5878
+ device: pick2(winner),
5879
+ created: false
5880
+ };
5881
+ }
5882
+ throw error;
5883
+ }
5884
+ return {
5885
+ device,
5886
+ created: true
5887
+ };
5888
+ },
5889
+ async approveIosDevice(id, input) {
5890
+ const name = input.name === void 0 ? void 0 : nameOf(input.name);
5891
+ const approvedBy = personOf(input.approvedBy, "approvedBy");
5892
+ return db.transaction(async (tx) => {
5893
+ const row = await tx.findOne("ios_devices", { id });
5894
+ if (row === null) return null;
5895
+ const device = pick2(row);
5896
+ const set = {
5897
+ ...name === void 0 || name === device.name ? {} : { name },
5898
+ ...device.status === "pending" ? {
5899
+ status: "approved",
5900
+ approved_by: approvedBy,
5901
+ approved_at_ms: now()
5902
+ } : {}
5903
+ };
5904
+ if (Object.keys(set).length === 0) return device;
5905
+ tx.update("ios_devices", row, set);
5906
+ return {
5907
+ ...device,
5908
+ ...set
5909
+ };
5910
+ });
5911
+ },
5912
+ async renameIosDevice(id, input) {
5913
+ const name = nameOf(input);
5914
+ return db.transaction(async (tx) => {
5915
+ const row = await tx.findOne("ios_devices", { id });
5916
+ if (row === null) return null;
5917
+ const device = pick2(row);
5918
+ if (device.name === name) return device;
5919
+ tx.update("ios_devices", row, { name });
5920
+ return {
5921
+ ...device,
5922
+ name
5923
+ };
5924
+ });
5925
+ },
5926
+ async recordIosDeviceOutcome({ id, seen, issuerId, outcome, reason }) {
5927
+ if (!OUTCOMES.includes(outcome)) throw new IosDeviceInputError(`Invalid iOS device outcome: ${String(outcome)}. Expected ${OUTCOMES.join(", ")}.`);
5928
+ 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.`);
5929
+ return db.transaction(async (tx) => {
5930
+ const row = await tx.findOne("ios_devices", { id });
5931
+ if (row === null) return null;
5932
+ const device = pick2(row);
5933
+ if (device.status !== seen.status || device.approved_at_ms !== seen.approvedAtMs || device.apple_issuer_id !== null && device.apple_issuer_id !== issuerId) return null;
5934
+ let set;
5935
+ switch (outcome) {
5936
+ case "registered":
5937
+ if (device.status === "pending") return null;
5938
+ set = {
5939
+ status: "registered",
5940
+ registered_at_ms: device.registered_at_ms ?? now(),
5941
+ apple_issuer_id: issuerId,
5942
+ apple_error: null
5943
+ };
5944
+ break;
5945
+ case "refused":
5946
+ if (device.status !== "approved") return null;
5947
+ set = { apple_error: errorText(reason === void 0 || reason.trim() === "" ? "Apple refused it." : reason) };
5948
+ break;
5949
+ case "disabled":
5950
+ if (device.status === "pending") return null;
5951
+ set = { apple_error: IOS_DEVICE_DISABLED_ERROR };
5952
+ break;
5953
+ case "missing":
5954
+ if (device.status !== "registered") return null;
5955
+ set = {
5956
+ status: "pending",
5957
+ approved_by: null,
5958
+ approved_at_ms: null,
5959
+ apple_error: IOS_DEVICE_MISSING_ERROR
5960
+ };
5961
+ }
5962
+ if (Object.entries(set).some(([column, value]) => device[column] !== (value ?? null))) tx.update("ios_devices", row, set);
5963
+ return {
5964
+ ...device,
5965
+ ...set
5966
+ };
5967
+ });
5968
+ },
5969
+ async markIosDevicesInBuild({ buildId, ids }) {
5970
+ for (const id of new Set(ids)) await db.transaction(async (tx) => {
5971
+ const row = await tx.findOne("ios_devices", { id });
5972
+ if (row === null || typeof row.build_id === "string" && row.build_id >= buildId) return;
5973
+ tx.update("ios_devices", row, { build_id: buildId });
5974
+ });
5975
+ },
5976
+ async claimIosDeviceAccount(issuerId) {
5977
+ 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.`);
5978
+ const answer2 = /* @__PURE__ */ __name((held) => ({
5979
+ issuerId: held,
5980
+ claimed: held === issuerId
5981
+ }), "answer");
5982
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
5983
+ if (existing !== null) return answer2(existing.apple_issuer_id);
5984
+ const holder = await accountOfRows() ?? issuerId;
5985
+ try {
5986
+ await db.transaction(async (tx) => {
5987
+ tx.create("ios_device_account", {
5988
+ id: ACCOUNT_ROW,
5989
+ apple_issuer_id: holder,
5990
+ claimed_at_ms: now()
5991
+ });
5992
+ });
5993
+ return answer2(holder);
5994
+ } catch (error) {
5995
+ if (error instanceof DatabaseConstraintError && (error.reason === "exists" || error.reason === "unique")) {
5996
+ const winner = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
5997
+ if (winner !== null) return answer2(winner.apple_issuer_id);
5998
+ }
5999
+ throw error;
6000
+ }
6001
+ },
6002
+ async deleteIosDevice(id, only) {
6003
+ const requestedBy = only?.requestedBy === void 0 ? void 0 : personOf(only.requestedBy, "requestedBy");
6004
+ return db.transaction(async (tx) => {
6005
+ const row = await tx.findOne("ios_devices", { id });
6006
+ if (row === null) return null;
6007
+ const device = pick2(row);
6008
+ if (only?.status !== void 0 && device.status !== only.status || requestedBy !== void 0 && device.requested_by !== requestedBy) return null;
6009
+ await tx.delete("ios_devices", row);
6010
+ return device;
6011
+ });
6012
+ }
6013
+ };
6014
+ }, "createIosDeviceApi");
6015
+
6016
+ // ../../packages/server/dist/core/nativeBuildDestinations.mjs
6017
+ var NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
6018
+ android: [
6019
+ "play-internal",
6020
+ "play-closed",
6021
+ "play-open",
6022
+ "play-production"
6023
+ ],
6024
+ ios: ["testflight"]
6025
+ };
6026
+
5690
6027
  // ../../packages/server/dist/core/writes.mjs
5691
6028
  var PAGE2 = 500;
5692
6029
  var countBundle = /* @__PURE__ */ __name((tx, platform, delta) => {
@@ -5707,7 +6044,7 @@ var deleteBundle = /* @__PURE__ */ __name(async (tx, current) => {
5707
6044
  await tx.delete("bundles", current);
5708
6045
  countBundle(tx, current.platform, -1);
5709
6046
  }, "deleteBundle");
5710
- var replaceBundlePatches = /* @__PURE__ */ __name(async (tx, bundle, rows) => {
6047
+ var replaceBundlePatches = /* @__PURE__ */ __name(async (tx, bundle, rows, checkNew) => {
5711
6048
  const wanted = new Map(rows.map((row) => [row.id, row]));
5712
6049
  const count = bundle._refs_bundle_patches_bundle_id ?? 0;
5713
6050
  let cursor;
@@ -5732,6 +6069,7 @@ var replaceBundlePatches = /* @__PURE__ */ __name(async (tx, bundle, rows) => {
5732
6069
  if (page2.next === void 0) break;
5733
6070
  cursor = page2.next;
5734
6071
  }
6072
+ if (checkNew !== void 0) for (const row of wanted.values()) await checkNew(row);
5735
6073
  for (const row of wanted.values()) tx.create("bundle_patches", row);
5736
6074
  }, "replaceBundlePatches");
5737
6075
  var insertChannel = /* @__PURE__ */ __name(async (db, row) => {
@@ -5784,13 +6122,15 @@ var ARTIFACT_KINDS = {
5784
6122
  var SCOPE_KEY_MAX_LENGTH = 2048;
5785
6123
  var GIT_COMMIT_HASH_MAX_LENGTH = 255;
5786
6124
  var BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
6125
+ var SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
6126
+ var URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
5787
6127
  var NativeBuildInputError = class extends TypeError {
5788
6128
  static {
5789
6129
  __name(this, "NativeBuildInputError");
5790
6130
  }
5791
6131
  name = "NativeBuildInputError";
5792
6132
  };
5793
- var pick2 = /* @__PURE__ */ __name((row) => ({
6133
+ var pick3 = /* @__PURE__ */ __name((row) => ({
5794
6134
  id: row.id,
5795
6135
  scope_key: row.scope_key,
5796
6136
  platform: row.platform,
@@ -5807,12 +6147,22 @@ var pick2 = /* @__PURE__ */ __name((row) => ({
5807
6147
  build_number: row.build_number ?? null,
5808
6148
  submitted_to: row.submitted_to ?? null,
5809
6149
  submitted_at_ms: row.submitted_at_ms ?? null,
5810
- submitted_version: row.submitted_version ?? null
6150
+ submitted_version: row.submitted_version ?? null,
6151
+ is_store_build: row.is_store_build === true,
6152
+ is_sandbox: row.is_sandbox === true,
6153
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
6154
+ export_method: row.export_method ?? null,
6155
+ native_app_version: row.native_app_version ?? null
5811
6156
  }), "pick");
5812
- var SUBMISSION_DESTINATIONS = {
5813
- android: "play-internal",
5814
- ios: "testflight"
5815
- };
6157
+ var EXPORT_METHODS = /* @__PURE__ */ new Set([
6158
+ "app-store",
6159
+ "ad-hoc",
6160
+ "development",
6161
+ "enterprise"
6162
+ ]);
6163
+ var SANDBOX_CHANNEL_PREFIX = "sandbox-";
6164
+ var OLDER_BUILDS_PAGE = 20;
6165
+ var MARK_ATTEMPTS = 8;
5816
6166
  var BUILD_NUMBER_MAX_LENGTH = 64;
5817
6167
  var SUBMITTED_VERSION_MAX_LENGTH = 255;
5818
6168
  var nativeBuildScopeKey = /* @__PURE__ */ __name((scope) => {
@@ -5835,18 +6185,34 @@ var nativeBuildScopeKey = /* @__PURE__ */ __name((scope) => {
5835
6185
  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.`);
5836
6186
  return scopeKey;
5837
6187
  }, "nativeBuildScopeKey");
6188
+ var refuseSandboxPatchBase = /* @__PURE__ */ __name(async (db, baseBundleId) => {
6189
+ 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.");
6190
+ }, "refuseSandboxPatchBase");
5838
6191
  var isBuiltInBundle = /* @__PURE__ */ __name(async (db, bundleId) => await db.findOne("native_builds", { min_bundle_id: bundleId }) !== null, "isBuiltInBundle");
5839
- var problemOf = /* @__PURE__ */ __name(({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, artifact }) => {
6192
+ var problemOf = /* @__PURE__ */ __name(({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, exportMethod, nativeAppVersion, artifact }) => {
5840
6193
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
5841
6194
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
5842
6195
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
5843
6196
  if (channel.trim().length === 0) return "channel is required";
6197
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
6198
+ const reserved = channel.startsWith(SANDBOX_CHANNEL_PREFIX);
6199
+ if (isSandbox === true && !reserved) return `a sandbox build registers on a ${SANDBOX_CHANNEL_PREFIX}* channel, not ${channel}`;
6200
+ if (isSandbox !== true && reserved) return `channel ${channel} is reserved for sandbox builds`;
6201
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
6202
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
6203
+ 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`;
6204
+ }
5844
6205
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
5845
6206
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
5846
6207
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
5847
6208
  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`;
6209
+ if (nativeAppVersion !== void 0 && nativeAppVersion !== null && (typeof nativeAppVersion !== "string" || nativeAppVersion.trim().length === 0)) return "nativeAppVersion must be the artifact's app version, or null";
5848
6210
  const kinds = ARTIFACT_KINDS[platform];
5849
6211
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
6212
+ if (exportMethod !== void 0 && exportMethod !== null) {
6213
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
6214
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
6215
+ }
5850
6216
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
5851
6217
  return null;
5852
6218
  }, "problemOf");
@@ -5874,7 +6240,12 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5874
6240
  build_number: registration.buildNumber ?? null,
5875
6241
  submitted_to: null,
5876
6242
  submitted_at_ms: null,
5877
- submitted_version: null
6243
+ submitted_version: null,
6244
+ is_store_build: false,
6245
+ is_sandbox: registration.isSandbox === true,
6246
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
6247
+ export_method: registration.exportMethod ?? null,
6248
+ native_app_version: registration.nativeAppVersion ?? null
5878
6249
  };
5879
6250
  for (let attempt = 1; ; attempt += 1) {
5880
6251
  await insertChannel(db, {
@@ -5906,35 +6277,58 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5906
6277
  },
5907
6278
  async getNativeBuild(id) {
5908
6279
  const row = await db.findOne("native_builds", { id });
5909
- return row === null ? null : pick2(row);
6280
+ return row === null ? null : pick3(row);
5910
6281
  },
5911
6282
  async findNativeBuild(scope, options) {
5912
6283
  const scopeKey = nativeBuildScopeKey(scope);
5913
6284
  const buildKey = options?.buildKey;
5914
6285
  if (buildKey !== void 0 && !BUILD_KEY.test(buildKey)) throw new NativeBuildInputError("Invalid native build key: it must be nbk1: and a SHA-256.");
5915
- const { rows } = buildKey === void 0 ? await db.findMany("native_builds", {
5916
- index: "byScope",
5917
- where: { scope_key: scopeKey },
5918
- order: "desc",
5919
- limit: 1
5920
- }) : await db.findMany("native_builds", {
5921
- index: "byBuildKey",
5922
- where: {
5923
- scope_key: scopeKey,
5924
- build_key: buildKey
5925
- },
5926
- order: "desc",
5927
- limit: 1
5928
- });
5929
- return rows[0] === void 0 ? null : pick2(rows[0]);
6286
+ if (options?.storeBuild) {
6287
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
6288
+ return marked === null ? null : pick3(marked);
6289
+ }
6290
+ const read = /* @__PURE__ */ __name((limit, before) => {
6291
+ const page2 = {
6292
+ order: "desc",
6293
+ limit,
6294
+ ...before === void 0 ? {} : { range: { lt: before } }
6295
+ };
6296
+ return buildKey === void 0 ? db.findMany("native_builds", {
6297
+ index: "byScope",
6298
+ where: { scope_key: scopeKey },
6299
+ ...page2
6300
+ }) : db.findMany("native_builds", {
6301
+ index: "byBuildKey",
6302
+ where: {
6303
+ scope_key: scopeKey,
6304
+ build_key: buildKey
6305
+ },
6306
+ ...page2
6307
+ });
6308
+ }, "read");
6309
+ const bundleId = options?.builtInOlderThan;
6310
+ if (bundleId !== void 0 && scope.channel.startsWith(SANDBOX_CHANNEL_PREFIX)) return null;
6311
+ const { rows } = await read(1);
6312
+ const newest = rows[0];
6313
+ if (newest === void 0) return null;
6314
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return pick3(newest);
6315
+ for (let before = newest.id; ; ) {
6316
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
6317
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
6318
+ if (usable !== void 0) return pick3(usable);
6319
+ const last = older.at(-1);
6320
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
6321
+ before = last.id;
6322
+ }
5930
6323
  },
5931
6324
  async recordNativeBuildSubmission(id, { destination, version: version2 }) {
5932
6325
  if (version2.trim().length === 0 || version2.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.`);
5933
6326
  return db.transaction(async (tx) => {
5934
6327
  const row = await tx.findOne("native_builds", { id });
5935
6328
  if (row === null) return null;
5936
- const build = pick2(row);
5937
- 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}.`);
6329
+ const build = pick3(row);
6330
+ 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}.`);
6331
+ if (build.is_sandbox && destination !== "testflight" && destination !== "play-internal") throw new NativeBuildInputError("A sandbox build can submit only to TestFlight or Play internal testing.");
5938
6332
  const set = {
5939
6333
  submitted_to: destination,
5940
6334
  submitted_at_ms: now(),
@@ -5947,6 +6341,46 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5947
6341
  };
5948
6342
  });
5949
6343
  },
6344
+ async markNativeBuild(id, { storeBuild }) {
6345
+ for (let attempt = 1; ; attempt += 1) try {
6346
+ return await db.transaction(async (tx) => {
6347
+ const row = await tx.findOne("native_builds", { id });
6348
+ if (row === null) return null;
6349
+ const build = pick3(row);
6350
+ if (!storeBuild) {
6351
+ if (build.is_store_build) tx.update("native_builds", row, { is_store_build: false });
6352
+ return {
6353
+ nativeBuild: {
6354
+ ...build,
6355
+ is_store_build: false
6356
+ },
6357
+ previous: null
6358
+ };
6359
+ }
6360
+ if (build.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
6361
+ if (build.is_store_build) return {
6362
+ nativeBuild: build,
6363
+ previous: null
6364
+ };
6365
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build.scope_key });
6366
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
6367
+ tx.update("native_builds", row, { is_store_build: true });
6368
+ return {
6369
+ nativeBuild: {
6370
+ ...build,
6371
+ is_store_build: true
6372
+ },
6373
+ previous: holder === null ? null : {
6374
+ ...pick3(holder),
6375
+ is_store_build: false
6376
+ }
6377
+ };
6378
+ });
6379
+ } catch (error) {
6380
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
6381
+ throw error;
6382
+ }
6383
+ },
5950
6384
  async deleteNativeBuild(id) {
5951
6385
  return db.transaction(async (tx) => {
5952
6386
  const row = await tx.findOne("native_builds", { id });
@@ -5959,7 +6393,7 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5959
6393
  if (bundle !== null) await tx.delete("bundles", bundle);
5960
6394
  return {
5961
6395
  deleted: true,
5962
- nativeBuild: pick2(row)
6396
+ nativeBuild: pick3(row)
5963
6397
  };
5964
6398
  });
5965
6399
  },
@@ -5979,7 +6413,7 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5979
6413
  ...page2,
5980
6414
  ...after(input)
5981
6415
  });
5982
- return rows.map(pick2);
6416
+ return rows.map(pick3);
5983
6417
  }
5984
6418
  }), "createNativeBuildApi");
5985
6419
 
@@ -6269,7 +6703,11 @@ var createCoreOperations = /* @__PURE__ */ __name((db, { now = Date.now } = {})
6269
6703
  for (const { release } of deployments) if (!channels2.has(release.channel)) channels2.set(release.channel, await ensureChannel(release.channel));
6270
6704
  const platforms = /* @__PURE__ */ new Map();
6271
6705
  for (const deployment of deployments) {
6272
- if (!("bundleId" in deployment) || platforms.has(deployment.bundleId)) continue;
6706
+ if (!("bundleId" in deployment)) {
6707
+ for (const { baseBundleId } of deployment.bundle.patches ?? []) await refuseSandboxPatchBase(db, baseBundleId);
6708
+ continue;
6709
+ }
6710
+ if (platforms.has(deployment.bundleId)) continue;
6273
6711
  const row = await db.findOne("bundles", { id: deployment.bundleId });
6274
6712
  if (row === null) throw new DatabaseBundleNotFoundError(deployment.bundleId);
6275
6713
  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.`);
@@ -6473,7 +6911,7 @@ var createCoreOperations = /* @__PURE__ */ __name((db, { now = Date.now } = {})
6473
6911
  if (patches !== void 0) await replaceBundlePatches(tx, current, bundleToPatchRows({
6474
6912
  ...next,
6475
6913
  patches
6476
- }));
6914
+ }), (row) => refuseSandboxPatchBase(tx, row.base_bundle_id));
6477
6915
  }), "updateBundle"),
6478
6916
  deleteBundles: /* @__PURE__ */ __name(async (ids) => {
6479
6917
  try {
@@ -6529,6 +6967,7 @@ var createCoreApi = /* @__PURE__ */ __name((db, storage, options = {}) => {
6529
6967
  ...reads,
6530
6968
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
6531
6969
  ...createNativeBuildApi(db, options),
6970
+ ...createIosDeviceApi(db, options),
6532
6971
  /** One read, which checks the schema settings first. */
6533
6972
  ready: /* @__PURE__ */ __name(async () => {
6534
6973
  await reads.listReleaseCatalogs({ limit: 1 });
@@ -6742,10 +7181,12 @@ var keyset = /* @__PURE__ */ __name((url, maxValue = LIMITS.maxValue) => {
6742
7181
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
6743
7182
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
6744
7183
  const cursor = url.searchParams.get("cursor");
7184
+ const through = url.searchParams.get("through");
6745
7185
  return {
6746
7186
  order,
6747
7187
  limit,
6748
- ...cursor === null ? {} : { after: cursor }
7188
+ ...cursor === null ? {} : { after: cursor },
7189
+ ...through === null ? {} : { through }
6749
7190
  };
6750
7191
  }, "keyset");
6751
7192
  var page = /* @__PURE__ */ __name((rows, { limit }, keyOf, extra = {}) => json({
@@ -6852,11 +7293,11 @@ var refusingInvalid = /* @__PURE__ */ __name(async (operation) => {
6852
7293
  try {
6853
7294
  return await operation();
6854
7295
  } catch (error) {
6855
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
7296
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
6856
7297
  throw error;
6857
7298
  }
6858
7299
  }, "refusingInvalid");
6859
- var isNativeBuildRegistration = /* @__PURE__ */ __name((value) => isRecord3(value) && isText(value.id) && isText(value.minBundleId) && typeof value.platform === "string" && isPlatform(value.platform) && isText(value.channel) && isTextOrNull(value.fingerprintHash) && isTextOrNull(value.appVersion) && value.fingerprintHash === null !== (value.appVersion === null) && isTextOrNull(value.gitCommitHash) && isTextOrNull(value.buildKey) && (value.buildNumber === void 0 || isTextOrNull(value.buildNumber)) && isRecord3(value.artifact) && typeof value.artifact.kind === "string" && NATIVE_BUILD_ARTIFACT_KINDS.has(value.artifact.kind) && isText(value.artifact.storageUri) && Number.isSafeInteger(value.artifact.byteSize) && value.artifact.byteSize >= 0 && isRecord3(value.embeddedBundle) && isText(value.embeddedBundle.manifestStorageUri) && isText(value.embeddedBundle.manifestFileHash) && isText(value.embeddedBundle.assetBaseStorageUri) && (value.embeddedBundle.metadata === void 0 || isRecord3(value.embeddedBundle.metadata)), "isNativeBuildRegistration");
7300
+ var isNativeBuildRegistration = /* @__PURE__ */ __name((value) => isRecord3(value) && isText(value.id) && isText(value.minBundleId) && typeof value.platform === "string" && isPlatform(value.platform) && isText(value.channel) && isTextOrNull(value.fingerprintHash) && isTextOrNull(value.appVersion) && value.fingerprintHash === null !== (value.appVersion === null) && isTextOrNull(value.gitCommitHash) && isTextOrNull(value.buildKey) && (value.buildNumber === void 0 || isTextOrNull(value.buildNumber)) && (value.isSandbox === void 0 || typeof value.isSandbox === "boolean") && (value.sandboxUrlScheme === void 0 || isTextOrNull(value.sandboxUrlScheme)) && (value.exportMethod === void 0 || isTextOrNull(value.exportMethod)) && (value.nativeAppVersion === void 0 || isTextOrNull(value.nativeAppVersion)) && isRecord3(value.artifact) && typeof value.artifact.kind === "string" && NATIVE_BUILD_ARTIFACT_KINDS.has(value.artifact.kind) && isText(value.artifact.storageUri) && Number.isSafeInteger(value.artifact.byteSize) && value.artifact.byteSize >= 0 && isRecord3(value.embeddedBundle) && isText(value.embeddedBundle.manifestStorageUri) && isText(value.embeddedBundle.manifestFileHash) && isText(value.embeddedBundle.assetBaseStorageUri) && (value.embeddedBundle.metadata === void 0 || isRecord3(value.embeddedBundle.metadata)), "isNativeBuildRegistration");
6860
7301
  var scopeKeyOf = /* @__PURE__ */ __name((params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "", "scopeKeyOf");
6861
7302
  var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
6862
7303
  listBundles: onCore(async (core, request) => {
@@ -6937,7 +7378,8 @@ var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
6937
7378
  rebuildReleaseCatalog: onCore(async (core, _request, params) => json({ data: await core.rebuildReleaseCatalog(scopeKeyOf(params)) })),
6938
7379
  updateBundle: onCore(async (core, request, params) => {
6939
7380
  const bundleId = requireRouteParam(params, "id");
6940
- await core.updateBundle(bundleId, bundleUpdateOf(await request.json(), bundleId));
7381
+ const update = bundleUpdateOf(await request.json(), bundleId);
7382
+ await refusingInvalid(() => core.updateBundle(bundleId, update));
6941
7383
  return noContent();
6942
7384
  }),
6943
7385
  countBundles: onCore(async (core, request) => json({ data: await core.countBundles(platformOf(new URL(request.url))) })),
@@ -6961,7 +7403,7 @@ var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
6961
7403
  deployReleases: onCore(async (core, request) => {
6962
7404
  const { deployments } = await body(request);
6963
7405
  if (!Array.isArray(deployments) || deployments.length === 0 || !deployments.every(isDeployment)) throw new HandlerBadRequestError("Deploy needs deployments, each a bundle and its release policy.");
6964
- return json({ data: await core.deploy(deployments) }, 201);
7406
+ return json({ data: await refusingInvalid(() => core.deploy(deployments)) }, 201);
6965
7407
  }),
6966
7408
  promoteRelease: onCore(async (core, request, params) => {
6967
7409
  const input = await body(request);
@@ -6984,7 +7426,13 @@ var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
6984
7426
  const url = new URL(request.url);
6985
7427
  const scope = nativeBuildScopeOf(url);
6986
7428
  const buildKey = url.searchParams.get("buildKey");
6987
- return json({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
7429
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
7430
+ const options = {
7431
+ ...buildKey === null ? {} : { buildKey },
7432
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
7433
+ ...builtInOlderThan === null ? {} : { builtInOlderThan }
7434
+ };
7435
+ return json({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
6988
7436
  }),
6989
7437
  getNativeBuild: onCore(async (core, _request, params) => json({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
6990
7438
  listNativeBuilds: onCore(async (core, request) => {
@@ -6998,14 +7446,95 @@ var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
6998
7446
  }),
6999
7447
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
7000
7448
  const input = await body(request);
7001
- if (!isRecord3(input) || input.destination !== "testflight" && input.destination !== "play-internal" || !isText(input.version)) throw new HandlerBadRequestError("A native build submission needs destination (testflight or play-internal) and version.");
7449
+ if (!isRecord3(input) || !Object.values(NATIVE_BUILD_SUBMISSION_DESTINATIONS).flat().includes(input.destination) || !isText(input.version)) throw new HandlerBadRequestError("A native build submission needs a valid store destination and version.");
7002
7450
  const submission = {
7003
7451
  destination: input.destination,
7004
7452
  version: input.version
7005
7453
  };
7006
7454
  return json({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
7007
7455
  }),
7456
+ markNativeBuild: onCore(async (core, request, params) => {
7457
+ const input = await body(request);
7458
+ if (!isRecord3(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
7459
+ const mark = { storeBuild: input.storeBuild };
7460
+ return json({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
7461
+ }),
7008
7462
  deleteNativeBuild: onCore(async (core, _request, params) => json({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
7463
+ listIosDevices: onCore(async (core, request) => {
7464
+ const url = new URL(request.url);
7465
+ const input = keyset(url);
7466
+ const status = url.searchParams.get("status");
7467
+ return page(await refusingInvalid(() => core.listIosDevices({
7468
+ ...input,
7469
+ ...status === null ? {} : { status }
7470
+ })), input, ({ id }) => id);
7471
+ }),
7472
+ findIosDevice: onCore(async (core, _request, params) => json({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
7473
+ requestIosDevice: onCore(async (core, request) => {
7474
+ const input = await body(request);
7475
+ if (!isText(input.udid) || !isText(input.name) || !isTextOrNull(input.requestedBy)) throw new HandlerBadRequestError("An iOS device request needs udid, name, and requestedBy, an email or null.");
7476
+ const device = {
7477
+ udid: input.udid,
7478
+ name: input.name,
7479
+ requestedBy: input.requestedBy
7480
+ };
7481
+ return json({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
7482
+ }),
7483
+ approveIosDevice: onCore(async (core, request, params) => {
7484
+ const input = await body(request);
7485
+ if (!isTextOrNull(input.approvedBy) || input.name !== void 0 && !isText(input.name)) throw new HandlerBadRequestError("An iOS device approval needs approvedBy, an email or null, and an optional name.");
7486
+ const approval = {
7487
+ approvedBy: input.approvedBy,
7488
+ ...input.name === void 0 ? {} : { name: input.name }
7489
+ };
7490
+ return json({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
7491
+ }),
7492
+ renameIosDevice: onCore(async (core, request, params) => {
7493
+ const input = await body(request);
7494
+ if (!isText(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
7495
+ const name = input.name;
7496
+ return json({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
7497
+ }),
7498
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
7499
+ const input = await body(request);
7500
+ const seen = input.seen;
7501
+ if (!isRecord3(seen) || typeof seen.status !== "string" || !(seen.approvedAtMs === null || Number.isSafeInteger(seen.approvedAtMs)) || !isText(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.");
7502
+ const outcome = {
7503
+ id: requireRouteParam(params, "id"),
7504
+ seen: {
7505
+ status: seen.status,
7506
+ approvedAtMs: seen.approvedAtMs
7507
+ },
7508
+ issuerId: input.issuerId,
7509
+ outcome: input.outcome,
7510
+ ...input.reason === void 0 ? {} : { reason: input.reason }
7511
+ };
7512
+ return json({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
7513
+ }),
7514
+ claimIosDeviceAccount: onCore(async (core, request) => {
7515
+ const { issuerId } = await body(request);
7516
+ if (!isText(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
7517
+ return json({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
7518
+ }),
7519
+ markIosDevicesInBuild: onCore(async (core, request) => {
7520
+ const { buildId, ids } = await body(request);
7521
+ if (!isText(buildId) || !Array.isArray(ids) || !ids.every((id) => isText(id))) throw new HandlerBadRequestError("Marking iOS devices in a build needs buildId and ids.");
7522
+ await core.markIosDevicesInBuild({
7523
+ buildId,
7524
+ ids
7525
+ });
7526
+ return noContent();
7527
+ }),
7528
+ deleteIosDevice: onCore(async (core, request, params) => {
7529
+ const url = new URL(request.url);
7530
+ const status = url.searchParams.get("status");
7531
+ const requestedBy = url.searchParams.get("requestedBy");
7532
+ const only = {
7533
+ ...status === null ? {} : { status },
7534
+ ...requestedBy === null ? {} : { requestedBy }
7535
+ };
7536
+ return json({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
7537
+ }),
7009
7538
  deleteBundles: onCore(async (core, request) => {
7010
7539
  const { ids } = await body(request);
7011
7540
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -7149,10 +7678,60 @@ var ADMIN_ROUTES = [
7149
7678
  path: "/native-builds/:id/submission",
7150
7679
  handler: "recordNativeBuildSubmission"
7151
7680
  },
7681
+ {
7682
+ method: "POST",
7683
+ path: "/native-builds/:id/store-build",
7684
+ handler: "markNativeBuild"
7685
+ },
7152
7686
  {
7153
7687
  method: "DELETE",
7154
7688
  path: "/native-builds/:id",
7155
7689
  handler: "deleteNativeBuild"
7690
+ },
7691
+ {
7692
+ method: "GET",
7693
+ path: "/ios-devices",
7694
+ handler: "listIosDevices"
7695
+ },
7696
+ {
7697
+ method: "POST",
7698
+ path: "/ios-devices",
7699
+ handler: "requestIosDevice"
7700
+ },
7701
+ {
7702
+ method: "GET",
7703
+ path: "/ios-devices/udid/:udid",
7704
+ handler: "findIosDevice"
7705
+ },
7706
+ {
7707
+ method: "POST",
7708
+ path: "/ios-devices/in-build",
7709
+ handler: "markIosDevicesInBuild"
7710
+ },
7711
+ {
7712
+ method: "POST",
7713
+ path: "/ios-devices/account",
7714
+ handler: "claimIosDeviceAccount"
7715
+ },
7716
+ {
7717
+ method: "POST",
7718
+ path: "/ios-devices/:id/approval",
7719
+ handler: "approveIosDevice"
7720
+ },
7721
+ {
7722
+ method: "POST",
7723
+ path: "/ios-devices/:id/outcome",
7724
+ handler: "recordIosDeviceOutcome"
7725
+ },
7726
+ {
7727
+ method: "PATCH",
7728
+ path: "/ios-devices/:id",
7729
+ handler: "renameIosDevice"
7730
+ },
7731
+ {
7732
+ method: "DELETE",
7733
+ path: "/ios-devices/:id",
7734
+ handler: "deleteIosDevice"
7156
7735
  }
7157
7736
  ];
7158
7737
 
@@ -13683,8 +14262,10 @@ var presignR2GetUrl = /* @__PURE__ */ __name(async ({
13683
14262
 
13684
14263
  // src/r2WorkerStorage.ts
13685
14264
  var PRESIGNED_URL_EXPIRES_IN_SECONDS = 3600;
14265
+ var DELETE_BATCH_SIZE = 1e3;
13686
14266
  function r2WorkerStorage(config) {
13687
14267
  const getStorageKey = createStorageKeyBuilder(config.basePath);
14268
+ const basePrefix = getStorageKey() ? `${getStorageKey()}/` : "";
13688
14269
  const parseAndValidate = /* @__PURE__ */ __name((storageUri) => {
13689
14270
  const parsed = parseStorageUri(storageUri, "r2");
13690
14271
  if (parsed.bucket !== config.bucketName) {
@@ -13761,6 +14342,46 @@ function r2WorkerStorage(config) {
13761
14342
  const { key } = parseAndValidate(storageUri);
13762
14343
  await config.bucket.delete(key);
13763
14344
  return { deleted: true };
14345
+ },
14346
+ async listObjects(prefix) {
14347
+ const folder = getStorageKey(prefix ?? "");
14348
+ const objects = [];
14349
+ let cursor;
14350
+ do {
14351
+ const listed2 = await config.bucket.list({
14352
+ prefix: folder ? `${folder}/` : "",
14353
+ ...cursor === void 0 ? {} : { cursor }
14354
+ });
14355
+ for (const object of listed2.objects) {
14356
+ if (!object.key.startsWith(basePrefix)) continue;
14357
+ let storageUri;
14358
+ try {
14359
+ storageUri = createStorageUri({
14360
+ protocol: "r2",
14361
+ bucket: config.bucketName,
14362
+ key: object.key
14363
+ });
14364
+ } catch {
14365
+ continue;
14366
+ }
14367
+ objects.push({
14368
+ key: object.key.slice(basePrefix.length),
14369
+ lastModifiedAt: object.uploaded,
14370
+ size: object.size,
14371
+ storageUri
14372
+ });
14373
+ }
14374
+ cursor = listed2.truncated ? listed2.cursor : void 0;
14375
+ } while (cursor !== void 0);
14376
+ return objects;
14377
+ },
14378
+ async deleteObjects(relativeKeys) {
14379
+ const keys = relativeKeys.map((key) => getStorageKey(key));
14380
+ for (let offset = 0; offset < keys.length; offset += DELETE_BATCH_SIZE) {
14381
+ await config.bucket.delete(
14382
+ keys.slice(offset, offset + DELETE_BATCH_SIZE)
14383
+ );
14384
+ }
13764
14385
  }
13765
14386
  });
13766
14387
  }