@hot-updater/cloudflare 1.2.0-rc.3 → 1.2.0-rc.31

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.3";
4675
+ var version = "1.2.0-rc.31";
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) => {
@@ -5784,13 +6121,15 @@ var ARTIFACT_KINDS = {
5784
6121
  var SCOPE_KEY_MAX_LENGTH = 2048;
5785
6122
  var GIT_COMMIT_HASH_MAX_LENGTH = 255;
5786
6123
  var BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
6124
+ var SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
6125
+ var URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
5787
6126
  var NativeBuildInputError = class extends TypeError {
5788
6127
  static {
5789
6128
  __name(this, "NativeBuildInputError");
5790
6129
  }
5791
6130
  name = "NativeBuildInputError";
5792
6131
  };
5793
- var pick2 = /* @__PURE__ */ __name((row) => ({
6132
+ var pick3 = /* @__PURE__ */ __name((row) => ({
5794
6133
  id: row.id,
5795
6134
  scope_key: row.scope_key,
5796
6135
  platform: row.platform,
@@ -5807,12 +6146,22 @@ var pick2 = /* @__PURE__ */ __name((row) => ({
5807
6146
  build_number: row.build_number ?? null,
5808
6147
  submitted_to: row.submitted_to ?? null,
5809
6148
  submitted_at_ms: row.submitted_at_ms ?? null,
5810
- submitted_version: row.submitted_version ?? null
6149
+ submitted_version: row.submitted_version ?? null,
6150
+ is_store_build: row.is_store_build === true,
6151
+ is_sandbox: row.is_sandbox === true,
6152
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
6153
+ export_method: row.export_method ?? null,
6154
+ native_app_version: row.native_app_version ?? null
5811
6155
  }), "pick");
5812
- var SUBMISSION_DESTINATIONS = {
5813
- android: "play-internal",
5814
- ios: "testflight"
5815
- };
6156
+ var EXPORT_METHODS = /* @__PURE__ */ new Set([
6157
+ "app-store",
6158
+ "ad-hoc",
6159
+ "development",
6160
+ "enterprise"
6161
+ ]);
6162
+ var SANDBOX_CHANNEL_PREFIX = "sandbox-";
6163
+ var OLDER_BUILDS_PAGE = 20;
6164
+ var MARK_ATTEMPTS = 8;
5816
6165
  var BUILD_NUMBER_MAX_LENGTH = 64;
5817
6166
  var SUBMITTED_VERSION_MAX_LENGTH = 255;
5818
6167
  var nativeBuildScopeKey = /* @__PURE__ */ __name((scope) => {
@@ -5836,17 +6185,30 @@ var nativeBuildScopeKey = /* @__PURE__ */ __name((scope) => {
5836
6185
  return scopeKey;
5837
6186
  }, "nativeBuildScopeKey");
5838
6187
  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 }) => {
6188
+ var problemOf = /* @__PURE__ */ __name(({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, exportMethod, nativeAppVersion, artifact }) => {
5840
6189
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
5841
6190
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
5842
6191
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
5843
6192
  if (channel.trim().length === 0) return "channel is required";
6193
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
6194
+ const reserved = channel.startsWith(SANDBOX_CHANNEL_PREFIX);
6195
+ if (isSandbox === true && !reserved) return `a sandbox build registers on a ${SANDBOX_CHANNEL_PREFIX}* channel, not ${channel}`;
6196
+ if (isSandbox !== true && reserved) return `channel ${channel} is reserved for sandbox builds`;
6197
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
6198
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
6199
+ 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`;
6200
+ }
5844
6201
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
5845
6202
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
5846
6203
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
5847
6204
  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`;
6205
+ 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
6206
  const kinds = ARTIFACT_KINDS[platform];
5849
6207
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
6208
+ if (exportMethod !== void 0 && exportMethod !== null) {
6209
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
6210
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
6211
+ }
5850
6212
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
5851
6213
  return null;
5852
6214
  }, "problemOf");
@@ -5874,7 +6236,12 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5874
6236
  build_number: registration.buildNumber ?? null,
5875
6237
  submitted_to: null,
5876
6238
  submitted_at_ms: null,
5877
- submitted_version: null
6239
+ submitted_version: null,
6240
+ is_store_build: false,
6241
+ is_sandbox: registration.isSandbox === true,
6242
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
6243
+ export_method: registration.exportMethod ?? null,
6244
+ native_app_version: registration.nativeAppVersion ?? null
5878
6245
  };
5879
6246
  for (let attempt = 1; ; attempt += 1) {
5880
6247
  await insertChannel(db, {
@@ -5906,35 +6273,57 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5906
6273
  },
5907
6274
  async getNativeBuild(id) {
5908
6275
  const row = await db.findOne("native_builds", { id });
5909
- return row === null ? null : pick2(row);
6276
+ return row === null ? null : pick3(row);
5910
6277
  },
5911
6278
  async findNativeBuild(scope, options) {
5912
6279
  const scopeKey = nativeBuildScopeKey(scope);
5913
6280
  const buildKey = options?.buildKey;
5914
6281
  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]);
6282
+ if (options?.storeBuild) {
6283
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
6284
+ return marked === null ? null : pick3(marked);
6285
+ }
6286
+ const read = /* @__PURE__ */ __name((limit, before) => {
6287
+ const page2 = {
6288
+ order: "desc",
6289
+ limit,
6290
+ ...before === void 0 ? {} : { range: { lt: before } }
6291
+ };
6292
+ return buildKey === void 0 ? db.findMany("native_builds", {
6293
+ index: "byScope",
6294
+ where: { scope_key: scopeKey },
6295
+ ...page2
6296
+ }) : db.findMany("native_builds", {
6297
+ index: "byBuildKey",
6298
+ where: {
6299
+ scope_key: scopeKey,
6300
+ build_key: buildKey
6301
+ },
6302
+ ...page2
6303
+ });
6304
+ }, "read");
6305
+ const { rows } = await read(1);
6306
+ const newest = rows[0];
6307
+ if (newest === void 0) return null;
6308
+ const bundleId = options?.builtInOlderThan;
6309
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return pick3(newest);
6310
+ for (let before = newest.id; ; ) {
6311
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
6312
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
6313
+ if (usable !== void 0) return pick3(usable);
6314
+ const last = older.at(-1);
6315
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
6316
+ before = last.id;
6317
+ }
5930
6318
  },
5931
6319
  async recordNativeBuildSubmission(id, { destination, version: version2 }) {
5932
6320
  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
6321
  return db.transaction(async (tx) => {
5934
6322
  const row = await tx.findOne("native_builds", { id });
5935
6323
  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}.`);
6324
+ const build = pick3(row);
6325
+ 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}.`);
6326
+ 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
6327
  const set = {
5939
6328
  submitted_to: destination,
5940
6329
  submitted_at_ms: now(),
@@ -5947,6 +6336,46 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5947
6336
  };
5948
6337
  });
5949
6338
  },
6339
+ async markNativeBuild(id, { storeBuild }) {
6340
+ for (let attempt = 1; ; attempt += 1) try {
6341
+ return await db.transaction(async (tx) => {
6342
+ const row = await tx.findOne("native_builds", { id });
6343
+ if (row === null) return null;
6344
+ const build = pick3(row);
6345
+ if (!storeBuild) {
6346
+ if (build.is_store_build) tx.update("native_builds", row, { is_store_build: false });
6347
+ return {
6348
+ nativeBuild: {
6349
+ ...build,
6350
+ is_store_build: false
6351
+ },
6352
+ previous: null
6353
+ };
6354
+ }
6355
+ if (build.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
6356
+ if (build.is_store_build) return {
6357
+ nativeBuild: build,
6358
+ previous: null
6359
+ };
6360
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build.scope_key });
6361
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
6362
+ tx.update("native_builds", row, { is_store_build: true });
6363
+ return {
6364
+ nativeBuild: {
6365
+ ...build,
6366
+ is_store_build: true
6367
+ },
6368
+ previous: holder === null ? null : {
6369
+ ...pick3(holder),
6370
+ is_store_build: false
6371
+ }
6372
+ };
6373
+ });
6374
+ } catch (error) {
6375
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
6376
+ throw error;
6377
+ }
6378
+ },
5950
6379
  async deleteNativeBuild(id) {
5951
6380
  return db.transaction(async (tx) => {
5952
6381
  const row = await tx.findOne("native_builds", { id });
@@ -5959,7 +6388,7 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5959
6388
  if (bundle !== null) await tx.delete("bundles", bundle);
5960
6389
  return {
5961
6390
  deleted: true,
5962
- nativeBuild: pick2(row)
6391
+ nativeBuild: pick3(row)
5963
6392
  };
5964
6393
  });
5965
6394
  },
@@ -5979,7 +6408,7 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5979
6408
  ...page2,
5980
6409
  ...after(input)
5981
6410
  });
5982
- return rows.map(pick2);
6411
+ return rows.map(pick3);
5983
6412
  }
5984
6413
  }), "createNativeBuildApi");
5985
6414
 
@@ -6529,6 +6958,7 @@ var createCoreApi = /* @__PURE__ */ __name((db, storage, options = {}) => {
6529
6958
  ...reads,
6530
6959
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
6531
6960
  ...createNativeBuildApi(db, options),
6961
+ ...createIosDeviceApi(db, options),
6532
6962
  /** One read, which checks the schema settings first. */
6533
6963
  ready: /* @__PURE__ */ __name(async () => {
6534
6964
  await reads.listReleaseCatalogs({ limit: 1 });
@@ -6742,10 +7172,12 @@ var keyset = /* @__PURE__ */ __name((url, maxValue = LIMITS.maxValue) => {
6742
7172
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
6743
7173
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
6744
7174
  const cursor = url.searchParams.get("cursor");
7175
+ const through = url.searchParams.get("through");
6745
7176
  return {
6746
7177
  order,
6747
7178
  limit,
6748
- ...cursor === null ? {} : { after: cursor }
7179
+ ...cursor === null ? {} : { after: cursor },
7180
+ ...through === null ? {} : { through }
6749
7181
  };
6750
7182
  }, "keyset");
6751
7183
  var page = /* @__PURE__ */ __name((rows, { limit }, keyOf, extra = {}) => json({
@@ -6852,11 +7284,11 @@ var refusingInvalid = /* @__PURE__ */ __name(async (operation) => {
6852
7284
  try {
6853
7285
  return await operation();
6854
7286
  } catch (error) {
6855
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
7287
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
6856
7288
  throw error;
6857
7289
  }
6858
7290
  }, "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");
7291
+ 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
7292
  var scopeKeyOf = /* @__PURE__ */ __name((params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "", "scopeKeyOf");
6861
7293
  var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
6862
7294
  listBundles: onCore(async (core, request) => {
@@ -6984,7 +7416,13 @@ var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
6984
7416
  const url = new URL(request.url);
6985
7417
  const scope = nativeBuildScopeOf(url);
6986
7418
  const buildKey = url.searchParams.get("buildKey");
6987
- return json({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
7419
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
7420
+ const options = {
7421
+ ...buildKey === null ? {} : { buildKey },
7422
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
7423
+ ...builtInOlderThan === null ? {} : { builtInOlderThan }
7424
+ };
7425
+ return json({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
6988
7426
  }),
6989
7427
  getNativeBuild: onCore(async (core, _request, params) => json({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
6990
7428
  listNativeBuilds: onCore(async (core, request) => {
@@ -6998,14 +7436,95 @@ var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
6998
7436
  }),
6999
7437
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
7000
7438
  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.");
7439
+ 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
7440
  const submission = {
7003
7441
  destination: input.destination,
7004
7442
  version: input.version
7005
7443
  };
7006
7444
  return json({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
7007
7445
  }),
7446
+ markNativeBuild: onCore(async (core, request, params) => {
7447
+ const input = await body(request);
7448
+ if (!isRecord3(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
7449
+ const mark = { storeBuild: input.storeBuild };
7450
+ return json({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
7451
+ }),
7008
7452
  deleteNativeBuild: onCore(async (core, _request, params) => json({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
7453
+ listIosDevices: onCore(async (core, request) => {
7454
+ const url = new URL(request.url);
7455
+ const input = keyset(url);
7456
+ const status = url.searchParams.get("status");
7457
+ return page(await refusingInvalid(() => core.listIosDevices({
7458
+ ...input,
7459
+ ...status === null ? {} : { status }
7460
+ })), input, ({ id }) => id);
7461
+ }),
7462
+ findIosDevice: onCore(async (core, _request, params) => json({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
7463
+ requestIosDevice: onCore(async (core, request) => {
7464
+ const input = await body(request);
7465
+ 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.");
7466
+ const device = {
7467
+ udid: input.udid,
7468
+ name: input.name,
7469
+ requestedBy: input.requestedBy
7470
+ };
7471
+ return json({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
7472
+ }),
7473
+ approveIosDevice: onCore(async (core, request, params) => {
7474
+ const input = await body(request);
7475
+ 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.");
7476
+ const approval = {
7477
+ approvedBy: input.approvedBy,
7478
+ ...input.name === void 0 ? {} : { name: input.name }
7479
+ };
7480
+ return json({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
7481
+ }),
7482
+ renameIosDevice: onCore(async (core, request, params) => {
7483
+ const input = await body(request);
7484
+ if (!isText(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
7485
+ const name = input.name;
7486
+ return json({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
7487
+ }),
7488
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
7489
+ const input = await body(request);
7490
+ const seen = input.seen;
7491
+ 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.");
7492
+ const outcome = {
7493
+ id: requireRouteParam(params, "id"),
7494
+ seen: {
7495
+ status: seen.status,
7496
+ approvedAtMs: seen.approvedAtMs
7497
+ },
7498
+ issuerId: input.issuerId,
7499
+ outcome: input.outcome,
7500
+ ...input.reason === void 0 ? {} : { reason: input.reason }
7501
+ };
7502
+ return json({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
7503
+ }),
7504
+ claimIosDeviceAccount: onCore(async (core, request) => {
7505
+ const { issuerId } = await body(request);
7506
+ if (!isText(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
7507
+ return json({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
7508
+ }),
7509
+ markIosDevicesInBuild: onCore(async (core, request) => {
7510
+ const { buildId, ids } = await body(request);
7511
+ if (!isText(buildId) || !Array.isArray(ids) || !ids.every((id) => isText(id))) throw new HandlerBadRequestError("Marking iOS devices in a build needs buildId and ids.");
7512
+ await core.markIosDevicesInBuild({
7513
+ buildId,
7514
+ ids
7515
+ });
7516
+ return noContent();
7517
+ }),
7518
+ deleteIosDevice: onCore(async (core, request, params) => {
7519
+ const url = new URL(request.url);
7520
+ const status = url.searchParams.get("status");
7521
+ const requestedBy = url.searchParams.get("requestedBy");
7522
+ const only = {
7523
+ ...status === null ? {} : { status },
7524
+ ...requestedBy === null ? {} : { requestedBy }
7525
+ };
7526
+ return json({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
7527
+ }),
7009
7528
  deleteBundles: onCore(async (core, request) => {
7010
7529
  const { ids } = await body(request);
7011
7530
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -7149,10 +7668,60 @@ var ADMIN_ROUTES = [
7149
7668
  path: "/native-builds/:id/submission",
7150
7669
  handler: "recordNativeBuildSubmission"
7151
7670
  },
7671
+ {
7672
+ method: "POST",
7673
+ path: "/native-builds/:id/store-build",
7674
+ handler: "markNativeBuild"
7675
+ },
7152
7676
  {
7153
7677
  method: "DELETE",
7154
7678
  path: "/native-builds/:id",
7155
7679
  handler: "deleteNativeBuild"
7680
+ },
7681
+ {
7682
+ method: "GET",
7683
+ path: "/ios-devices",
7684
+ handler: "listIosDevices"
7685
+ },
7686
+ {
7687
+ method: "POST",
7688
+ path: "/ios-devices",
7689
+ handler: "requestIosDevice"
7690
+ },
7691
+ {
7692
+ method: "GET",
7693
+ path: "/ios-devices/udid/:udid",
7694
+ handler: "findIosDevice"
7695
+ },
7696
+ {
7697
+ method: "POST",
7698
+ path: "/ios-devices/in-build",
7699
+ handler: "markIosDevicesInBuild"
7700
+ },
7701
+ {
7702
+ method: "POST",
7703
+ path: "/ios-devices/account",
7704
+ handler: "claimIosDeviceAccount"
7705
+ },
7706
+ {
7707
+ method: "POST",
7708
+ path: "/ios-devices/:id/approval",
7709
+ handler: "approveIosDevice"
7710
+ },
7711
+ {
7712
+ method: "POST",
7713
+ path: "/ios-devices/:id/outcome",
7714
+ handler: "recordIosDeviceOutcome"
7715
+ },
7716
+ {
7717
+ method: "PATCH",
7718
+ path: "/ios-devices/:id",
7719
+ handler: "renameIosDevice"
7720
+ },
7721
+ {
7722
+ method: "DELETE",
7723
+ path: "/ios-devices/:id",
7724
+ handler: "deleteIosDevice"
7156
7725
  }
7157
7726
  ];
7158
7727
 
@@ -13683,8 +14252,10 @@ var presignR2GetUrl = /* @__PURE__ */ __name(async ({
13683
14252
 
13684
14253
  // src/r2WorkerStorage.ts
13685
14254
  var PRESIGNED_URL_EXPIRES_IN_SECONDS = 3600;
14255
+ var DELETE_BATCH_SIZE = 1e3;
13686
14256
  function r2WorkerStorage(config) {
13687
14257
  const getStorageKey = createStorageKeyBuilder(config.basePath);
14258
+ const basePrefix = getStorageKey() ? `${getStorageKey()}/` : "";
13688
14259
  const parseAndValidate = /* @__PURE__ */ __name((storageUri) => {
13689
14260
  const parsed = parseStorageUri(storageUri, "r2");
13690
14261
  if (parsed.bucket !== config.bucketName) {
@@ -13761,6 +14332,46 @@ function r2WorkerStorage(config) {
13761
14332
  const { key } = parseAndValidate(storageUri);
13762
14333
  await config.bucket.delete(key);
13763
14334
  return { deleted: true };
14335
+ },
14336
+ async listObjects(prefix) {
14337
+ const folder = getStorageKey(prefix ?? "");
14338
+ const objects = [];
14339
+ let cursor;
14340
+ do {
14341
+ const listed2 = await config.bucket.list({
14342
+ prefix: folder ? `${folder}/` : "",
14343
+ ...cursor === void 0 ? {} : { cursor }
14344
+ });
14345
+ for (const object of listed2.objects) {
14346
+ if (!object.key.startsWith(basePrefix)) continue;
14347
+ let storageUri;
14348
+ try {
14349
+ storageUri = createStorageUri({
14350
+ protocol: "r2",
14351
+ bucket: config.bucketName,
14352
+ key: object.key
14353
+ });
14354
+ } catch {
14355
+ continue;
14356
+ }
14357
+ objects.push({
14358
+ key: object.key.slice(basePrefix.length),
14359
+ lastModifiedAt: object.uploaded,
14360
+ size: object.size,
14361
+ storageUri
14362
+ });
14363
+ }
14364
+ cursor = listed2.truncated ? listed2.cursor : void 0;
14365
+ } while (cursor !== void 0);
14366
+ return objects;
14367
+ },
14368
+ async deleteObjects(relativeKeys) {
14369
+ const keys = relativeKeys.map((key) => getStorageKey(key));
14370
+ for (let offset = 0; offset < keys.length; offset += DELETE_BATCH_SIZE) {
14371
+ await config.bucket.delete(
14372
+ keys.slice(offset, offset + DELETE_BATCH_SIZE)
14373
+ );
14374
+ }
13764
14375
  }
13765
14376
  });
13766
14377
  }