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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2600,9 +2600,31 @@ 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
2603
2616
  }
2604
2617
  }, {
2605
2618
  key: ["id"],
2619
+ derived: {
2620
+ /** The scope this build is the store build of; null on every other. */
2621
+ store_build_scope_key: {
2622
+ type: "string",
2623
+ maxLength: 2048,
2624
+ ascii: true,
2625
+ compute: /* @__PURE__ */ __name((row) => row.is_store_build ? row.scope_key : null, "compute")
2626
+ }
2627
+ },
2606
2628
  indexes: {
2607
2629
  byScope: {
2608
2630
  eq: ["scope_key"],
@@ -2612,6 +2634,11 @@ var nativeBuilds = defineTable({
2612
2634
  eq: ["scope_key", "build_key"],
2613
2635
  sort: ["id"]
2614
2636
  },
2637
+ byStoreBuild: {
2638
+ eq: ["store_build_scope_key"],
2639
+ sort: [],
2640
+ unique: true
2641
+ },
2615
2642
  byChannel: {
2616
2643
  eq: ["channel_id"],
2617
2644
  sort: ["id"],
@@ -2623,6 +2650,92 @@ var nativeBuilds = defineTable({
2623
2650
  }
2624
2651
  }
2625
2652
  });
2653
+ var iosDevices = defineTable({
2654
+ id: {
2655
+ type: "string",
2656
+ maxLength: 36
2657
+ },
2658
+ udid: {
2659
+ type: "string",
2660
+ maxLength: 40,
2661
+ ascii: true,
2662
+ unique: true
2663
+ },
2664
+ name: {
2665
+ type: "string",
2666
+ maxLength: 100
2667
+ },
2668
+ status: {
2669
+ type: "string",
2670
+ maxLength: 16
2671
+ },
2672
+ requested_by: {
2673
+ type: "string",
2674
+ maxLength: 320,
2675
+ required: false
2676
+ },
2677
+ created_at_ms: { type: "integer" },
2678
+ approved_by: {
2679
+ type: "string",
2680
+ maxLength: 320,
2681
+ required: false
2682
+ },
2683
+ approved_at_ms: {
2684
+ type: "integer",
2685
+ required: false
2686
+ },
2687
+ registered_at_ms: {
2688
+ type: "integer",
2689
+ required: false
2690
+ },
2691
+ apple_issuer_id: {
2692
+ type: "string",
2693
+ maxLength: 64,
2694
+ ascii: true,
2695
+ required: false
2696
+ },
2697
+ apple_error: {
2698
+ type: "string",
2699
+ maxLength: 512,
2700
+ required: false
2701
+ },
2702
+ build_id: {
2703
+ type: "string",
2704
+ maxLength: 36,
2705
+ required: false
2706
+ }
2707
+ }, {
2708
+ key: ["id"],
2709
+ indexes: {
2710
+ byStatus: {
2711
+ eq: ["status"],
2712
+ sort: ["id"]
2713
+ },
2714
+ all: {
2715
+ eq: [],
2716
+ sort: ["id"]
2717
+ }
2718
+ }
2719
+ });
2720
+ var iosDeviceAccount = defineTable({
2721
+ id: {
2722
+ type: "string",
2723
+ maxLength: 16,
2724
+ ascii: true
2725
+ },
2726
+ apple_issuer_id: {
2727
+ type: "string",
2728
+ maxLength: 64,
2729
+ ascii: true
2730
+ },
2731
+ claimed_at_ms: { type: "integer" }
2732
+ }, {
2733
+ key: ["id"],
2734
+ indexes: { all: {
2735
+ eq: [],
2736
+ sort: ["id"]
2737
+ } }
2738
+ });
2626
2739
  var coreSchema = {
2627
2740
  bundles,
2628
2741
  bundle_patches: bundlePatches,
@@ -2640,7 +2753,9 @@ var coreSchema = {
2640
2753
  sort: []
2641
2754
  } }
2642
2755
  }),
2643
- native_builds: nativeBuilds
2756
+ native_builds: nativeBuilds,
2757
+ ios_devices: iosDevices,
2758
+ ios_device_account: iosDeviceAccount
2644
2759
  };
2645
2760
  var coreModule = {
2646
2761
  id: "core",
@@ -2813,10 +2928,7 @@ var LOG_TABLES = [
2813
2928
  var LEASE_TABLE = "aggregate_lease";
2814
2929
  var LEASE = { id: "compaction" };
2815
2930
  var LEASE_MS = 3e4;
2816
- var WINDOW_MS = {
2817
- log: 6e4,
2818
- memory: 15e3
2819
- };
2931
+ var WINDOW_MS = 6e4;
2820
2932
  var LOG_PAGE = 200;
2821
2933
  var GROUPS = {
2822
2934
  commit: 1,
@@ -2824,7 +2936,6 @@ var GROUPS = {
2824
2936
  flush: 256
2825
2937
  };
2826
2938
  var ATTEMPTS = 5;
2827
- var MAX_BUFFERED = 1e4;
2828
2939
  var log = defineTable({
2829
2940
  id: {
2830
2941
  type: "string",
@@ -2926,8 +3037,8 @@ var rewrite2 = /* @__PURE__ */ __name((change, key, current) => {
2926
3037
  previous: current
2927
3038
  };
2928
3039
  }, "rewrite");
2929
- var compile = /* @__PURE__ */ __name(async (adapter, changes, shard) => {
2930
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
3040
+ var compile = /* @__PURE__ */ __name(async (adapter, changes) => {
3041
+ const keys = changes.map(({ key }) => [...key.slice(0, -1), 0]);
2931
3042
  const reads = /* @__PURE__ */ new Map();
2932
3043
  changes.forEach((change, at) => {
2933
3044
  if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
@@ -2973,7 +3084,7 @@ var encode2 = /* @__PURE__ */ __name(async (changes) => {
2973
3084
  const zipped = await deflate(json4);
2974
3085
  return zipped !== void 0 && zipped.length < json4.length ? `z${zipped}` : json4;
2975
3086
  }, "encode");
2976
- var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS[mode] }, now }) => {
3087
+ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema, batching: { windowMs = WINDOW_MS }, now }) => {
2977
3088
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
2978
3089
  const holder = crypto.randomUUID().replaceAll("-", "");
2979
3090
  const table = /* @__PURE__ */ __name((name) => schema.models.get(name).table, "table");
@@ -3000,61 +3111,6 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3000
3111
  }
3001
3112
  return changes;
3002
3113
  }, "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
3114
  let nextDue = 0;
3059
3115
  let compacting;
3060
3116
  const known = /* @__PURE__ */ new Map();
@@ -3176,7 +3232,7 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3176
3232
  more
3177
3233
  };
3178
3234
  }, "readLogs");
3179
- const rowsFor = /* @__PURE__ */ __name(async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp), "rowsFor");
3235
+ const rowsFor = /* @__PURE__ */ __name(async (changes) => (await compile(adapter, changes)).filter(isOp), "rowsFor");
3180
3236
  const applyGroup = /* @__PURE__ */ __name(async (held, logs) => {
3181
3237
  for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
3182
3238
  const batch = logs.slice(0, count);
@@ -3256,19 +3312,6 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3256
3312
  }))).then((pages) => pages.some((page2) => page2.rows.length > 0)).finally(() => {
3257
3313
  checking = void 0;
3258
3314
  }), "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
3315
  return {
3273
3316
  async transaction(fn) {
3274
3317
  let changes = /* @__PURE__ */ new Map();
@@ -3294,7 +3337,7 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3294
3337
  aggregate
3295
3338
  });
3296
3339
  if (failure) throw failure.error;
3297
- if (mode === "log" && attempt.size > 0) {
3340
+ if (attempt.size > 0) {
3298
3341
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
3299
3342
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
3300
3343
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -3308,24 +3351,18 @@ var createAggregateBatches = /* @__PURE__ */ __name(({ engine, adapter, schema,
3308
3351
  open = false;
3309
3352
  }
3310
3353
  });
3311
- if (changes.size > 0) await committed(changes);
3354
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
3312
3355
  return result;
3313
3356
  },
3314
3357
  async beforeRead(name) {
3315
3358
  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
- }
3359
+ if (await hasPending().catch((error) => {
3360
+ warn("read")(error);
3361
+ return false;
3362
+ })) await compact(true, GROUPS.read);
3323
3363
  },
3324
- flush,
3325
- async dispose() {
3326
- clearTimeout(timer);
3327
- timer = void 0;
3328
- await flush();
3364
+ async flush() {
3365
+ if (await hasPending()) await compact(true, GROUPS.flush);
3329
3366
  }
3330
3367
  };
3331
3368
  }, "createAggregateBatches");
@@ -3444,7 +3481,8 @@ var fieldProblems = /* @__PURE__ */ __name((definition, add) => {
3444
3481
  else if (field.required === false) add(`key field "${name}" is nullable`);
3445
3482
  else if (field.type === "json") add(`key field "${name}" is json`);
3446
3483
  }
3447
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
3484
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
3485
+ for (const [name, { type, maxLength, ascii }] of bounded) {
3448
3486
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
3449
3487
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
3450
3488
  }
@@ -3557,11 +3595,13 @@ var resolveSchema = /* @__PURE__ */ __name((modules) => {
3557
3595
  ...maxLength === void 0 ? {} : { maxLength },
3558
3596
  ...ascii ? { ascii } : {}
3559
3597
  }));
3560
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
3598
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
3561
3599
  name: field,
3562
3600
  type,
3563
3601
  nullable: true,
3564
- ...multi ? { multi } : {}
3602
+ ...multi ? { multi } : {},
3603
+ ...maxLength === void 0 ? {} : { maxLength },
3604
+ ...ascii ? { ascii } : {}
3565
3605
  });
3566
3606
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
3567
3607
  name: metric,
@@ -4294,13 +4334,10 @@ var createDatabaseEngine = /* @__PURE__ */ __name(({ batching, now = Date.now, m
4294
4334
  }, "barePage");
4295
4335
  return {
4296
4336
  ...engine,
4297
- /** Applies batched aggregate changes still pending: this process's buffer and the log. */
4337
+ /** Applies the batched aggregate changes still in the log. */
4298
4338
  flush: /* @__PURE__ */ __name(async () => {
4299
4339
  await batches?.flush();
4300
4340
  }, "flush"),
4301
- dispose: /* @__PURE__ */ __name(async () => {
4302
- await batches?.dispose();
4303
- }, "dispose"),
4304
4341
  database(module) {
4305
4342
  const name = /* @__PURE__ */ __name((model) => module.namespace ? `${module.namespace}_${model}` : model, "name");
4306
4343
  return {
@@ -4368,8 +4405,7 @@ var createEngine = /* @__PURE__ */ __name((database, { plugins = [], now = Date.
4368
4405
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
4369
4406
  return engine.database(module);
4370
4407
  }, "database"),
4371
- flush: /* @__PURE__ */ __name(() => engine.flush(), "flush"),
4372
- dispose: /* @__PURE__ */ __name(() => engine.dispose(), "dispose")
4408
+ flush: /* @__PURE__ */ __name(() => engine.flush(), "flush")
4373
4409
  };
4374
4410
  }, "createEngine");
4375
4411
 
@@ -4632,7 +4668,7 @@ var createSqlAdapter = /* @__PURE__ */ __name(({ executor, tablePrefix = "", max
4632
4668
  }, "createSqlAdapter");
4633
4669
 
4634
4670
  // ../../packages/server/dist/package.mjs
4635
- var version = "1.2.0-rc.3";
4671
+ var version = "1.2.0-rc.30";
4636
4672
 
4637
4673
  // ../../packages/server/dist/version.mjs
4638
4674
  var HOT_UPDATER_SERVER_VERSION = version;
@@ -5484,7 +5520,14 @@ var drain = /* @__PURE__ */ __name(async (read) => {
5484
5520
  } while (cursor !== void 0);
5485
5521
  return rows;
5486
5522
  }, "drain");
5487
- var after = /* @__PURE__ */ __name((input) => input.after === void 0 ? {} : { range: (input.order ?? "asc") === "asc" ? { gt: input.after } : { lt: input.after } }, "after");
5523
+ var after = /* @__PURE__ */ __name((input) => {
5524
+ const asc = (input.order ?? "asc") === "asc";
5525
+ const range = {
5526
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
5527
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
5528
+ };
5529
+ return Object.keys(range).length === 0 ? {} : { range };
5530
+ }, "after");
5488
5531
  var createCoreReads = /* @__PURE__ */ __name((db, storage) => {
5489
5532
  const detail = /* @__PURE__ */ __name(async (row) => {
5490
5533
  const count = row._refs_bundle_patches_bundle_id ?? 0;
@@ -5687,6 +5730,296 @@ var createCoreReads = /* @__PURE__ */ __name((db, storage) => {
5687
5730
  };
5688
5731
  }, "createCoreReads");
5689
5732
 
5733
+ // ../../packages/server/dist/core/iosDevices.mjs
5734
+ var UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
5735
+ var normalizeIosUdid = /* @__PURE__ */ __name((value) => {
5736
+ const trimmed = value.trim();
5737
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
5738
+ }, "normalizeIosUdid");
5739
+ var NAME_MAX_LENGTH = 100;
5740
+ var EMAIL_MAX_LENGTH = 320;
5741
+ var ISSUER_MAX_LENGTH = 64;
5742
+ var ACCOUNT_SCAN_PAGE = 200;
5743
+ var ACCOUNT_ROW = "registry";
5744
+ var ERROR_MAX_LENGTH = 512;
5745
+ var STATUSES = [
5746
+ "pending",
5747
+ "approved",
5748
+ "registered"
5749
+ ];
5750
+ var OUTCOMES = [
5751
+ "registered",
5752
+ "refused",
5753
+ "disabled",
5754
+ "missing"
5755
+ ];
5756
+ var IOS_DEVICE_DISABLED_ERROR = "Disabled in the Apple account.";
5757
+ var IOS_DEVICE_MISSING_ERROR = "Gone from the Apple account. Approve it again to register it.";
5758
+ var IosDeviceInputError = class extends TypeError {
5759
+ static {
5760
+ __name(this, "IosDeviceInputError");
5761
+ }
5762
+ name = "IosDeviceInputError";
5763
+ };
5764
+ var pick2 = /* @__PURE__ */ __name((row) => ({
5765
+ id: row.id,
5766
+ udid: row.udid,
5767
+ name: row.name,
5768
+ status: row.status,
5769
+ requested_by: row.requested_by ?? null,
5770
+ created_at_ms: row.created_at_ms,
5771
+ approved_by: row.approved_by ?? null,
5772
+ approved_at_ms: row.approved_at_ms ?? null,
5773
+ registered_at_ms: row.registered_at_ms ?? null,
5774
+ apple_issuer_id: row.apple_issuer_id ?? null,
5775
+ apple_error: row.apple_error ?? null,
5776
+ build_id: row.build_id ?? null
5777
+ }), "pick");
5778
+ var udidOf = /* @__PURE__ */ __name((udid) => {
5779
+ const key = typeof udid === "string" ? normalizeIosUdid(udid) : null;
5780
+ if (key === null) throw new IosDeviceInputError("Invalid iOS device: udid must be 40 hex digits, or 8 and 16 joined by a hyphen.");
5781
+ return key;
5782
+ }, "udidOf");
5783
+ var nameOf = /* @__PURE__ */ __name((name) => {
5784
+ const trimmed = typeof name === "string" ? name.trim() : "";
5785
+ if (trimmed.length === 0 || trimmed.length > NAME_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: name must be 1 to ${NAME_MAX_LENGTH} characters.`);
5786
+ return trimmed;
5787
+ }, "nameOf");
5788
+ var personOf = /* @__PURE__ */ __name((value, field) => {
5789
+ if (value === null) return null;
5790
+ const email = typeof value === "string" ? value.trim().toLowerCase() : "";
5791
+ 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.`);
5792
+ return email;
5793
+ }, "personOf");
5794
+ var errorText = /* @__PURE__ */ __name((text) => {
5795
+ const line = text.replace(/\s+/gu, " ").trim();
5796
+ return line.length > ERROR_MAX_LENGTH ? `${line.slice(0, 511)}\u2026` : line;
5797
+ }, "errorText");
5798
+ var createIosDeviceApi = /* @__PURE__ */ __name((db, { now = Date.now } = {}) => {
5799
+ const findIosDevice = /* @__PURE__ */ __name(async (udid) => {
5800
+ const key = normalizeIosUdid(udid);
5801
+ if (key === null) return null;
5802
+ const row = await db.findOne("ios_devices", { udid: key });
5803
+ return row === null ? null : pick2(row);
5804
+ }, "findIosDevice");
5805
+ const accountOfRows = /* @__PURE__ */ __name(async () => {
5806
+ let earliest = null;
5807
+ for (let after2; ; ) {
5808
+ const { rows } = await db.findMany("ios_devices", {
5809
+ index: "all",
5810
+ where: {},
5811
+ order: "asc",
5812
+ limit: ACCOUNT_SCAN_PAGE,
5813
+ ...after2 === void 0 ? {} : { range: { gt: after2 } }
5814
+ });
5815
+ for (const row of rows.map(pick2)) {
5816
+ if (row.apple_issuer_id === null) continue;
5817
+ if (earliest === null || (row.registered_at_ms ?? 0) < (earliest.registered_at_ms ?? 0)) earliest = row;
5818
+ }
5819
+ if (rows.length < ACCOUNT_SCAN_PAGE) return earliest?.apple_issuer_id ?? null;
5820
+ after2 = rows.at(-1).id;
5821
+ }
5822
+ }, "accountOfRows");
5823
+ return {
5824
+ async listIosDevices(input) {
5825
+ if (input.status !== void 0 && !STATUSES.includes(input.status)) throw new IosDeviceInputError(`Invalid iOS device status: ${String(input.status)}. Expected ${STATUSES.join(", ")}.`);
5826
+ const page2 = {
5827
+ order: input.order ?? "asc",
5828
+ limit: input.limit,
5829
+ ...after(input)
5830
+ };
5831
+ const { rows } = input.status === void 0 ? await db.findMany("ios_devices", {
5832
+ index: "all",
5833
+ where: {},
5834
+ ...page2
5835
+ }) : await db.findMany("ios_devices", {
5836
+ index: "byStatus",
5837
+ where: { status: input.status },
5838
+ ...page2
5839
+ });
5840
+ return rows.map(pick2);
5841
+ },
5842
+ findIosDevice,
5843
+ async requestIosDevice(input) {
5844
+ const udid = udidOf(input.udid);
5845
+ const name = nameOf(input.name);
5846
+ const requestedBy = personOf(input.requestedBy, "requestedBy");
5847
+ const existing = await db.findOne("ios_devices", { udid });
5848
+ if (existing !== null) return {
5849
+ device: pick2(existing),
5850
+ created: false
5851
+ };
5852
+ const device = {
5853
+ id: createUUIDv7(),
5854
+ udid,
5855
+ name,
5856
+ status: "pending",
5857
+ requested_by: requestedBy,
5858
+ created_at_ms: now(),
5859
+ approved_by: null,
5860
+ approved_at_ms: null,
5861
+ registered_at_ms: null,
5862
+ apple_issuer_id: null,
5863
+ apple_error: null,
5864
+ build_id: null
5865
+ };
5866
+ try {
5867
+ await db.transaction(async (tx) => {
5868
+ tx.create("ios_devices", device);
5869
+ });
5870
+ } catch (error) {
5871
+ if (error instanceof DatabaseConstraintError && error.reason === "unique") {
5872
+ const winner = await db.findOne("ios_devices", { udid });
5873
+ if (winner !== null) return {
5874
+ device: pick2(winner),
5875
+ created: false
5876
+ };
5877
+ }
5878
+ throw error;
5879
+ }
5880
+ return {
5881
+ device,
5882
+ created: true
5883
+ };
5884
+ },
5885
+ async approveIosDevice(id, input) {
5886
+ const name = input.name === void 0 ? void 0 : nameOf(input.name);
5887
+ const approvedBy = personOf(input.approvedBy, "approvedBy");
5888
+ return db.transaction(async (tx) => {
5889
+ const row = await tx.findOne("ios_devices", { id });
5890
+ if (row === null) return null;
5891
+ const device = pick2(row);
5892
+ const set = {
5893
+ ...name === void 0 || name === device.name ? {} : { name },
5894
+ ...device.status === "pending" ? {
5895
+ status: "approved",
5896
+ approved_by: approvedBy,
5897
+ approved_at_ms: now()
5898
+ } : {}
5899
+ };
5900
+ if (Object.keys(set).length === 0) return device;
5901
+ tx.update("ios_devices", row, set);
5902
+ return {
5903
+ ...device,
5904
+ ...set
5905
+ };
5906
+ });
5907
+ },
5908
+ async renameIosDevice(id, input) {
5909
+ const name = nameOf(input);
5910
+ return db.transaction(async (tx) => {
5911
+ const row = await tx.findOne("ios_devices", { id });
5912
+ if (row === null) return null;
5913
+ const device = pick2(row);
5914
+ if (device.name === name) return device;
5915
+ tx.update("ios_devices", row, { name });
5916
+ return {
5917
+ ...device,
5918
+ name
5919
+ };
5920
+ });
5921
+ },
5922
+ async recordIosDeviceOutcome({ id, seen, issuerId, outcome, reason }) {
5923
+ if (!OUTCOMES.includes(outcome)) throw new IosDeviceInputError(`Invalid iOS device outcome: ${String(outcome)}. Expected ${OUTCOMES.join(", ")}.`);
5924
+ 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.`);
5925
+ return db.transaction(async (tx) => {
5926
+ const row = await tx.findOne("ios_devices", { id });
5927
+ if (row === null) return null;
5928
+ const device = pick2(row);
5929
+ if (device.status !== seen.status || device.approved_at_ms !== seen.approvedAtMs || device.apple_issuer_id !== null && device.apple_issuer_id !== issuerId) return null;
5930
+ let set;
5931
+ switch (outcome) {
5932
+ case "registered":
5933
+ if (device.status === "pending") return null;
5934
+ set = {
5935
+ status: "registered",
5936
+ registered_at_ms: device.registered_at_ms ?? now(),
5937
+ apple_issuer_id: issuerId,
5938
+ apple_error: null
5939
+ };
5940
+ break;
5941
+ case "refused":
5942
+ if (device.status !== "approved") return null;
5943
+ set = { apple_error: errorText(reason === void 0 || reason.trim() === "" ? "Apple refused it." : reason) };
5944
+ break;
5945
+ case "disabled":
5946
+ if (device.status === "pending") return null;
5947
+ set = { apple_error: IOS_DEVICE_DISABLED_ERROR };
5948
+ break;
5949
+ case "missing":
5950
+ if (device.status !== "registered") return null;
5951
+ set = {
5952
+ status: "pending",
5953
+ approved_by: null,
5954
+ approved_at_ms: null,
5955
+ apple_error: IOS_DEVICE_MISSING_ERROR
5956
+ };
5957
+ }
5958
+ if (Object.entries(set).some(([column, value]) => device[column] !== (value ?? null))) tx.update("ios_devices", row, set);
5959
+ return {
5960
+ ...device,
5961
+ ...set
5962
+ };
5963
+ });
5964
+ },
5965
+ async markIosDevicesInBuild({ buildId, ids }) {
5966
+ for (const id of new Set(ids)) await db.transaction(async (tx) => {
5967
+ const row = await tx.findOne("ios_devices", { id });
5968
+ if (row === null || typeof row.build_id === "string" && row.build_id >= buildId) return;
5969
+ tx.update("ios_devices", row, { build_id: buildId });
5970
+ });
5971
+ },
5972
+ async claimIosDeviceAccount(issuerId) {
5973
+ 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.`);
5974
+ const answer2 = /* @__PURE__ */ __name((held) => ({
5975
+ issuerId: held,
5976
+ claimed: held === issuerId
5977
+ }), "answer");
5978
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
5979
+ if (existing !== null) return answer2(existing.apple_issuer_id);
5980
+ const holder = await accountOfRows() ?? issuerId;
5981
+ try {
5982
+ await db.transaction(async (tx) => {
5983
+ tx.create("ios_device_account", {
5984
+ id: ACCOUNT_ROW,
5985
+ apple_issuer_id: holder,
5986
+ claimed_at_ms: now()
5987
+ });
5988
+ });
5989
+ return answer2(holder);
5990
+ } catch (error) {
5991
+ if (error instanceof DatabaseConstraintError && (error.reason === "exists" || error.reason === "unique")) {
5992
+ const winner = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
5993
+ if (winner !== null) return answer2(winner.apple_issuer_id);
5994
+ }
5995
+ throw error;
5996
+ }
5997
+ },
5998
+ async deleteIosDevice(id, only) {
5999
+ const requestedBy = only?.requestedBy === void 0 ? void 0 : personOf(only.requestedBy, "requestedBy");
6000
+ return db.transaction(async (tx) => {
6001
+ const row = await tx.findOne("ios_devices", { id });
6002
+ if (row === null) return null;
6003
+ const device = pick2(row);
6004
+ if (only?.status !== void 0 && device.status !== only.status || requestedBy !== void 0 && device.requested_by !== requestedBy) return null;
6005
+ await tx.delete("ios_devices", row);
6006
+ return device;
6007
+ });
6008
+ }
6009
+ };
6010
+ }, "createIosDeviceApi");
6011
+
6012
+ // ../../packages/server/dist/core/nativeBuildDestinations.mjs
6013
+ var NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
6014
+ android: [
6015
+ "play-internal",
6016
+ "play-closed",
6017
+ "play-open",
6018
+ "play-production"
6019
+ ],
6020
+ ios: ["testflight"]
6021
+ };
6022
+
5690
6023
  // ../../packages/server/dist/core/writes.mjs
5691
6024
  var PAGE2 = 500;
5692
6025
  var countBundle = /* @__PURE__ */ __name((tx, platform, delta) => {
@@ -5784,13 +6117,15 @@ var ARTIFACT_KINDS = {
5784
6117
  var SCOPE_KEY_MAX_LENGTH = 2048;
5785
6118
  var GIT_COMMIT_HASH_MAX_LENGTH = 255;
5786
6119
  var BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
6120
+ var SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
6121
+ var URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
5787
6122
  var NativeBuildInputError = class extends TypeError {
5788
6123
  static {
5789
6124
  __name(this, "NativeBuildInputError");
5790
6125
  }
5791
6126
  name = "NativeBuildInputError";
5792
6127
  };
5793
- var pick2 = /* @__PURE__ */ __name((row) => ({
6128
+ var pick3 = /* @__PURE__ */ __name((row) => ({
5794
6129
  id: row.id,
5795
6130
  scope_key: row.scope_key,
5796
6131
  platform: row.platform,
@@ -5807,12 +6142,21 @@ var pick2 = /* @__PURE__ */ __name((row) => ({
5807
6142
  build_number: row.build_number ?? null,
5808
6143
  submitted_to: row.submitted_to ?? null,
5809
6144
  submitted_at_ms: row.submitted_at_ms ?? null,
5810
- submitted_version: row.submitted_version ?? null
6145
+ submitted_version: row.submitted_version ?? null,
6146
+ is_store_build: row.is_store_build === true,
6147
+ is_sandbox: row.is_sandbox === true,
6148
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
6149
+ export_method: row.export_method ?? null
5811
6150
  }), "pick");
5812
- var SUBMISSION_DESTINATIONS = {
5813
- android: "play-internal",
5814
- ios: "testflight"
5815
- };
6151
+ var EXPORT_METHODS = /* @__PURE__ */ new Set([
6152
+ "app-store",
6153
+ "ad-hoc",
6154
+ "development",
6155
+ "enterprise"
6156
+ ]);
6157
+ var SANDBOX_CHANNEL_PREFIX = "sandbox-";
6158
+ var OLDER_BUILDS_PAGE = 20;
6159
+ var MARK_ATTEMPTS = 8;
5816
6160
  var BUILD_NUMBER_MAX_LENGTH = 64;
5817
6161
  var SUBMITTED_VERSION_MAX_LENGTH = 255;
5818
6162
  var nativeBuildScopeKey = /* @__PURE__ */ __name((scope) => {
@@ -5836,17 +6180,29 @@ var nativeBuildScopeKey = /* @__PURE__ */ __name((scope) => {
5836
6180
  return scopeKey;
5837
6181
  }, "nativeBuildScopeKey");
5838
6182
  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 }) => {
6183
+ var problemOf = /* @__PURE__ */ __name(({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, exportMethod, artifact }) => {
5840
6184
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
5841
6185
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
5842
6186
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
5843
6187
  if (channel.trim().length === 0) return "channel is required";
6188
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
6189
+ const reserved = channel.startsWith(SANDBOX_CHANNEL_PREFIX);
6190
+ if (isSandbox === true && !reserved) return `a sandbox build registers on a ${SANDBOX_CHANNEL_PREFIX}* channel, not ${channel}`;
6191
+ if (isSandbox !== true && reserved) return `channel ${channel} is reserved for sandbox builds`;
6192
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
6193
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
6194
+ 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`;
6195
+ }
5844
6196
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
5845
6197
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
5846
6198
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
5847
6199
  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`;
5848
6200
  const kinds = ARTIFACT_KINDS[platform];
5849
6201
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
6202
+ if (exportMethod !== void 0 && exportMethod !== null) {
6203
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
6204
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
6205
+ }
5850
6206
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
5851
6207
  return null;
5852
6208
  }, "problemOf");
@@ -5874,7 +6230,11 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5874
6230
  build_number: registration.buildNumber ?? null,
5875
6231
  submitted_to: null,
5876
6232
  submitted_at_ms: null,
5877
- submitted_version: null
6233
+ submitted_version: null,
6234
+ is_store_build: false,
6235
+ is_sandbox: registration.isSandbox === true,
6236
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
6237
+ export_method: registration.exportMethod ?? null
5878
6238
  };
5879
6239
  for (let attempt = 1; ; attempt += 1) {
5880
6240
  await insertChannel(db, {
@@ -5906,35 +6266,57 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5906
6266
  },
5907
6267
  async getNativeBuild(id) {
5908
6268
  const row = await db.findOne("native_builds", { id });
5909
- return row === null ? null : pick2(row);
6269
+ return row === null ? null : pick3(row);
5910
6270
  },
5911
6271
  async findNativeBuild(scope, options) {
5912
6272
  const scopeKey = nativeBuildScopeKey(scope);
5913
6273
  const buildKey = options?.buildKey;
5914
6274
  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]);
6275
+ if (options?.storeBuild) {
6276
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
6277
+ return marked === null ? null : pick3(marked);
6278
+ }
6279
+ const read = /* @__PURE__ */ __name((limit, before) => {
6280
+ const page2 = {
6281
+ order: "desc",
6282
+ limit,
6283
+ ...before === void 0 ? {} : { range: { lt: before } }
6284
+ };
6285
+ return buildKey === void 0 ? db.findMany("native_builds", {
6286
+ index: "byScope",
6287
+ where: { scope_key: scopeKey },
6288
+ ...page2
6289
+ }) : db.findMany("native_builds", {
6290
+ index: "byBuildKey",
6291
+ where: {
6292
+ scope_key: scopeKey,
6293
+ build_key: buildKey
6294
+ },
6295
+ ...page2
6296
+ });
6297
+ }, "read");
6298
+ const { rows } = await read(1);
6299
+ const newest = rows[0];
6300
+ if (newest === void 0) return null;
6301
+ const bundleId = options?.builtInOlderThan;
6302
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return pick3(newest);
6303
+ for (let before = newest.id; ; ) {
6304
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
6305
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
6306
+ if (usable !== void 0) return pick3(usable);
6307
+ const last = older.at(-1);
6308
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
6309
+ before = last.id;
6310
+ }
5930
6311
  },
5931
6312
  async recordNativeBuildSubmission(id, { destination, version: version2 }) {
5932
6313
  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
6314
  return db.transaction(async (tx) => {
5934
6315
  const row = await tx.findOne("native_builds", { id });
5935
6316
  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}.`);
6317
+ const build = pick3(row);
6318
+ 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}.`);
6319
+ 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
6320
  const set = {
5939
6321
  submitted_to: destination,
5940
6322
  submitted_at_ms: now(),
@@ -5947,6 +6329,46 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5947
6329
  };
5948
6330
  });
5949
6331
  },
6332
+ async markNativeBuild(id, { storeBuild }) {
6333
+ for (let attempt = 1; ; attempt += 1) try {
6334
+ return await db.transaction(async (tx) => {
6335
+ const row = await tx.findOne("native_builds", { id });
6336
+ if (row === null) return null;
6337
+ const build = pick3(row);
6338
+ if (!storeBuild) {
6339
+ if (build.is_store_build) tx.update("native_builds", row, { is_store_build: false });
6340
+ return {
6341
+ nativeBuild: {
6342
+ ...build,
6343
+ is_store_build: false
6344
+ },
6345
+ previous: null
6346
+ };
6347
+ }
6348
+ if (build.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
6349
+ if (build.is_store_build) return {
6350
+ nativeBuild: build,
6351
+ previous: null
6352
+ };
6353
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build.scope_key });
6354
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
6355
+ tx.update("native_builds", row, { is_store_build: true });
6356
+ return {
6357
+ nativeBuild: {
6358
+ ...build,
6359
+ is_store_build: true
6360
+ },
6361
+ previous: holder === null ? null : {
6362
+ ...pick3(holder),
6363
+ is_store_build: false
6364
+ }
6365
+ };
6366
+ });
6367
+ } catch (error) {
6368
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
6369
+ throw error;
6370
+ }
6371
+ },
5950
6372
  async deleteNativeBuild(id) {
5951
6373
  return db.transaction(async (tx) => {
5952
6374
  const row = await tx.findOne("native_builds", { id });
@@ -5959,7 +6381,7 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5959
6381
  if (bundle !== null) await tx.delete("bundles", bundle);
5960
6382
  return {
5961
6383
  deleted: true,
5962
- nativeBuild: pick2(row)
6384
+ nativeBuild: pick3(row)
5963
6385
  };
5964
6386
  });
5965
6387
  },
@@ -5979,7 +6401,7 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
5979
6401
  ...page2,
5980
6402
  ...after(input)
5981
6403
  });
5982
- return rows.map(pick2);
6404
+ return rows.map(pick3);
5983
6405
  }
5984
6406
  }), "createNativeBuildApi");
5985
6407
 
@@ -6529,6 +6951,7 @@ var createCoreApi = /* @__PURE__ */ __name((db, storage, options = {}) => {
6529
6951
  ...reads,
6530
6952
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
6531
6953
  ...createNativeBuildApi(db, options),
6954
+ ...createIosDeviceApi(db, options),
6532
6955
  /** One read, which checks the schema settings first. */
6533
6956
  ready: /* @__PURE__ */ __name(async () => {
6534
6957
  await reads.listReleaseCatalogs({ limit: 1 });
@@ -6742,10 +7165,12 @@ var keyset = /* @__PURE__ */ __name((url, maxValue = LIMITS.maxValue) => {
6742
7165
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
6743
7166
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
6744
7167
  const cursor = url.searchParams.get("cursor");
7168
+ const through = url.searchParams.get("through");
6745
7169
  return {
6746
7170
  order,
6747
7171
  limit,
6748
- ...cursor === null ? {} : { after: cursor }
7172
+ ...cursor === null ? {} : { after: cursor },
7173
+ ...through === null ? {} : { through }
6749
7174
  };
6750
7175
  }, "keyset");
6751
7176
  var page = /* @__PURE__ */ __name((rows, { limit }, keyOf, extra = {}) => json({
@@ -6852,11 +7277,11 @@ var refusingInvalid = /* @__PURE__ */ __name(async (operation) => {
6852
7277
  try {
6853
7278
  return await operation();
6854
7279
  } catch (error) {
6855
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
7280
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
6856
7281
  throw error;
6857
7282
  }
6858
7283
  }, "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");
7284
+ 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)) && 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
7285
  var scopeKeyOf = /* @__PURE__ */ __name((params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "", "scopeKeyOf");
6861
7286
  var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
6862
7287
  listBundles: onCore(async (core, request) => {
@@ -6984,7 +7409,13 @@ var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
6984
7409
  const url = new URL(request.url);
6985
7410
  const scope = nativeBuildScopeOf(url);
6986
7411
  const buildKey = url.searchParams.get("buildKey");
6987
- return json({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
7412
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
7413
+ const options = {
7414
+ ...buildKey === null ? {} : { buildKey },
7415
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
7416
+ ...builtInOlderThan === null ? {} : { builtInOlderThan }
7417
+ };
7418
+ return json({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
6988
7419
  }),
6989
7420
  getNativeBuild: onCore(async (core, _request, params) => json({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
6990
7421
  listNativeBuilds: onCore(async (core, request) => {
@@ -6998,14 +7429,95 @@ var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
6998
7429
  }),
6999
7430
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
7000
7431
  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.");
7432
+ 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
7433
  const submission = {
7003
7434
  destination: input.destination,
7004
7435
  version: input.version
7005
7436
  };
7006
7437
  return json({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
7007
7438
  }),
7439
+ markNativeBuild: onCore(async (core, request, params) => {
7440
+ const input = await body(request);
7441
+ if (!isRecord3(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
7442
+ const mark = { storeBuild: input.storeBuild };
7443
+ return json({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
7444
+ }),
7008
7445
  deleteNativeBuild: onCore(async (core, _request, params) => json({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
7446
+ listIosDevices: onCore(async (core, request) => {
7447
+ const url = new URL(request.url);
7448
+ const input = keyset(url);
7449
+ const status = url.searchParams.get("status");
7450
+ return page(await refusingInvalid(() => core.listIosDevices({
7451
+ ...input,
7452
+ ...status === null ? {} : { status }
7453
+ })), input, ({ id }) => id);
7454
+ }),
7455
+ findIosDevice: onCore(async (core, _request, params) => json({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
7456
+ requestIosDevice: onCore(async (core, request) => {
7457
+ const input = await body(request);
7458
+ 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.");
7459
+ const device = {
7460
+ udid: input.udid,
7461
+ name: input.name,
7462
+ requestedBy: input.requestedBy
7463
+ };
7464
+ return json({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
7465
+ }),
7466
+ approveIosDevice: onCore(async (core, request, params) => {
7467
+ const input = await body(request);
7468
+ 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.");
7469
+ const approval = {
7470
+ approvedBy: input.approvedBy,
7471
+ ...input.name === void 0 ? {} : { name: input.name }
7472
+ };
7473
+ return json({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
7474
+ }),
7475
+ renameIosDevice: onCore(async (core, request, params) => {
7476
+ const input = await body(request);
7477
+ if (!isText(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
7478
+ const name = input.name;
7479
+ return json({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
7480
+ }),
7481
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
7482
+ const input = await body(request);
7483
+ const seen = input.seen;
7484
+ 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.");
7485
+ const outcome = {
7486
+ id: requireRouteParam(params, "id"),
7487
+ seen: {
7488
+ status: seen.status,
7489
+ approvedAtMs: seen.approvedAtMs
7490
+ },
7491
+ issuerId: input.issuerId,
7492
+ outcome: input.outcome,
7493
+ ...input.reason === void 0 ? {} : { reason: input.reason }
7494
+ };
7495
+ return json({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
7496
+ }),
7497
+ claimIosDeviceAccount: onCore(async (core, request) => {
7498
+ const { issuerId } = await body(request);
7499
+ if (!isText(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
7500
+ return json({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
7501
+ }),
7502
+ markIosDevicesInBuild: onCore(async (core, request) => {
7503
+ const { buildId, ids } = await body(request);
7504
+ if (!isText(buildId) || !Array.isArray(ids) || !ids.every((id) => isText(id))) throw new HandlerBadRequestError("Marking iOS devices in a build needs buildId and ids.");
7505
+ await core.markIosDevicesInBuild({
7506
+ buildId,
7507
+ ids
7508
+ });
7509
+ return noContent();
7510
+ }),
7511
+ deleteIosDevice: onCore(async (core, request, params) => {
7512
+ const url = new URL(request.url);
7513
+ const status = url.searchParams.get("status");
7514
+ const requestedBy = url.searchParams.get("requestedBy");
7515
+ const only = {
7516
+ ...status === null ? {} : { status },
7517
+ ...requestedBy === null ? {} : { requestedBy }
7518
+ };
7519
+ return json({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
7520
+ }),
7009
7521
  deleteBundles: onCore(async (core, request) => {
7010
7522
  const { ids } = await body(request);
7011
7523
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -7149,10 +7661,60 @@ var ADMIN_ROUTES = [
7149
7661
  path: "/native-builds/:id/submission",
7150
7662
  handler: "recordNativeBuildSubmission"
7151
7663
  },
7664
+ {
7665
+ method: "POST",
7666
+ path: "/native-builds/:id/store-build",
7667
+ handler: "markNativeBuild"
7668
+ },
7152
7669
  {
7153
7670
  method: "DELETE",
7154
7671
  path: "/native-builds/:id",
7155
7672
  handler: "deleteNativeBuild"
7673
+ },
7674
+ {
7675
+ method: "GET",
7676
+ path: "/ios-devices",
7677
+ handler: "listIosDevices"
7678
+ },
7679
+ {
7680
+ method: "POST",
7681
+ path: "/ios-devices",
7682
+ handler: "requestIosDevice"
7683
+ },
7684
+ {
7685
+ method: "GET",
7686
+ path: "/ios-devices/udid/:udid",
7687
+ handler: "findIosDevice"
7688
+ },
7689
+ {
7690
+ method: "POST",
7691
+ path: "/ios-devices/in-build",
7692
+ handler: "markIosDevicesInBuild"
7693
+ },
7694
+ {
7695
+ method: "POST",
7696
+ path: "/ios-devices/account",
7697
+ handler: "claimIosDeviceAccount"
7698
+ },
7699
+ {
7700
+ method: "POST",
7701
+ path: "/ios-devices/:id/approval",
7702
+ handler: "approveIosDevice"
7703
+ },
7704
+ {
7705
+ method: "POST",
7706
+ path: "/ios-devices/:id/outcome",
7707
+ handler: "recordIosDeviceOutcome"
7708
+ },
7709
+ {
7710
+ method: "PATCH",
7711
+ path: "/ios-devices/:id",
7712
+ handler: "renameIosDevice"
7713
+ },
7714
+ {
7715
+ method: "DELETE",
7716
+ path: "/ios-devices/:id",
7717
+ handler: "deleteIosDevice"
7156
7718
  }
7157
7719
  ];
7158
7720
 
@@ -13683,8 +14245,10 @@ var presignR2GetUrl = /* @__PURE__ */ __name(async ({
13683
14245
 
13684
14246
  // src/r2WorkerStorage.ts
13685
14247
  var PRESIGNED_URL_EXPIRES_IN_SECONDS = 3600;
14248
+ var DELETE_BATCH_SIZE = 1e3;
13686
14249
  function r2WorkerStorage(config) {
13687
14250
  const getStorageKey = createStorageKeyBuilder(config.basePath);
14251
+ const basePrefix = getStorageKey() ? `${getStorageKey()}/` : "";
13688
14252
  const parseAndValidate = /* @__PURE__ */ __name((storageUri) => {
13689
14253
  const parsed = parseStorageUri(storageUri, "r2");
13690
14254
  if (parsed.bucket !== config.bucketName) {
@@ -13761,6 +14325,46 @@ function r2WorkerStorage(config) {
13761
14325
  const { key } = parseAndValidate(storageUri);
13762
14326
  await config.bucket.delete(key);
13763
14327
  return { deleted: true };
14328
+ },
14329
+ async listObjects(prefix) {
14330
+ const folder = getStorageKey(prefix ?? "");
14331
+ const objects = [];
14332
+ let cursor;
14333
+ do {
14334
+ const listed2 = await config.bucket.list({
14335
+ prefix: folder ? `${folder}/` : "",
14336
+ ...cursor === void 0 ? {} : { cursor }
14337
+ });
14338
+ for (const object of listed2.objects) {
14339
+ if (!object.key.startsWith(basePrefix)) continue;
14340
+ let storageUri;
14341
+ try {
14342
+ storageUri = createStorageUri({
14343
+ protocol: "r2",
14344
+ bucket: config.bucketName,
14345
+ key: object.key
14346
+ });
14347
+ } catch {
14348
+ continue;
14349
+ }
14350
+ objects.push({
14351
+ key: object.key.slice(basePrefix.length),
14352
+ lastModifiedAt: object.uploaded,
14353
+ size: object.size,
14354
+ storageUri
14355
+ });
14356
+ }
14357
+ cursor = listed2.truncated ? listed2.cursor : void 0;
14358
+ } while (cursor !== void 0);
14359
+ return objects;
14360
+ },
14361
+ async deleteObjects(relativeKeys) {
14362
+ const keys = relativeKeys.map((key) => getStorageKey(key));
14363
+ for (let offset = 0; offset < keys.length; offset += DELETE_BATCH_SIZE) {
14364
+ await config.bucket.delete(
14365
+ keys.slice(offset, offset + DELETE_BATCH_SIZE)
14366
+ );
14367
+ }
13764
14368
  }
13765
14369
  });
13766
14370
  }