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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2470,9 +2470,32 @@ const nativeBuilds = defineTable({
2470
2470
  type: "string",
2471
2471
  maxLength: 255,
2472
2472
  required: false
2473
+ },
2474
+ is_store_build: { type: "boolean" },
2475
+ is_sandbox: { type: "boolean" },
2476
+ sandbox_url_scheme: {
2477
+ type: "string",
2478
+ maxLength: 255,
2479
+ ascii: true,
2480
+ required: false
2481
+ },
2482
+ export_method: {
2483
+ type: "string",
2484
+ maxLength: 16,
2485
+ required: false
2486
+ },
2487
+ native_app_version: {
2488
+ type: "string",
2489
+ required: false
2473
2490
  }
2474
2491
  }, {
2475
2492
  key: ["id"],
2493
+ derived: { store_build_scope_key: {
2494
+ type: "string",
2495
+ maxLength: 2048,
2496
+ ascii: true,
2497
+ compute: (row) => row.is_store_build ? row.scope_key : null
2498
+ } },
2476
2499
  indexes: {
2477
2500
  byScope: {
2478
2501
  eq: ["scope_key"],
@@ -2482,6 +2505,11 @@ const nativeBuilds = defineTable({
2482
2505
  eq: ["scope_key", "build_key"],
2483
2506
  sort: ["id"]
2484
2507
  },
2508
+ byStoreBuild: {
2509
+ eq: ["store_build_scope_key"],
2510
+ sort: [],
2511
+ unique: true
2512
+ },
2485
2513
  byChannel: {
2486
2514
  eq: ["channel_id"],
2487
2515
  sort: ["id"],
@@ -2493,6 +2521,92 @@ const nativeBuilds = defineTable({
2493
2521
  }
2494
2522
  }
2495
2523
  });
2524
+ const iosDevices = defineTable({
2525
+ id: {
2526
+ type: "string",
2527
+ maxLength: 36
2528
+ },
2529
+ udid: {
2530
+ type: "string",
2531
+ maxLength: 40,
2532
+ ascii: true,
2533
+ unique: true
2534
+ },
2535
+ name: {
2536
+ type: "string",
2537
+ maxLength: 100
2538
+ },
2539
+ status: {
2540
+ type: "string",
2541
+ maxLength: 16
2542
+ },
2543
+ requested_by: {
2544
+ type: "string",
2545
+ maxLength: 320,
2546
+ required: false
2547
+ },
2548
+ created_at_ms: { type: "integer" },
2549
+ approved_by: {
2550
+ type: "string",
2551
+ maxLength: 320,
2552
+ required: false
2553
+ },
2554
+ approved_at_ms: {
2555
+ type: "integer",
2556
+ required: false
2557
+ },
2558
+ registered_at_ms: {
2559
+ type: "integer",
2560
+ required: false
2561
+ },
2562
+ apple_issuer_id: {
2563
+ type: "string",
2564
+ maxLength: 64,
2565
+ ascii: true,
2566
+ required: false
2567
+ },
2568
+ apple_error: {
2569
+ type: "string",
2570
+ maxLength: 512,
2571
+ required: false
2572
+ },
2573
+ build_id: {
2574
+ type: "string",
2575
+ maxLength: 36,
2576
+ required: false
2577
+ }
2578
+ }, {
2579
+ key: ["id"],
2580
+ indexes: {
2581
+ byStatus: {
2582
+ eq: ["status"],
2583
+ sort: ["id"]
2584
+ },
2585
+ all: {
2586
+ eq: [],
2587
+ sort: ["id"]
2588
+ }
2589
+ }
2590
+ });
2591
+ const iosDeviceAccount = defineTable({
2592
+ id: {
2593
+ type: "string",
2594
+ maxLength: 16,
2595
+ ascii: true
2596
+ },
2597
+ apple_issuer_id: {
2598
+ type: "string",
2599
+ maxLength: 64,
2600
+ ascii: true
2601
+ },
2602
+ claimed_at_ms: { type: "integer" }
2603
+ }, {
2604
+ key: ["id"],
2605
+ indexes: { all: {
2606
+ eq: [],
2607
+ sort: ["id"]
2608
+ } }
2609
+ });
2496
2610
  const coreModule = {
2497
2611
  id: "core",
2498
2612
  schema: {
@@ -2512,7 +2626,9 @@ const coreModule = {
2512
2626
  sort: []
2513
2627
  } }
2514
2628
  }),
2515
- native_builds: nativeBuilds
2629
+ native_builds: nativeBuilds,
2630
+ ios_devices: iosDevices,
2631
+ ios_device_account: iosDeviceAccount
2516
2632
  }
2517
2633
  };
2518
2634
  //#endregion
@@ -2677,10 +2793,7 @@ const LOG_TABLES = [
2677
2793
  const LEASE_TABLE = "aggregate_lease";
2678
2794
  const LEASE = { id: "compaction" };
2679
2795
  const LEASE_MS = 3e4;
2680
- const WINDOW_MS$1 = {
2681
- log: 6e4,
2682
- memory: 15e3
2683
- };
2796
+ const WINDOW_MS$1 = 6e4;
2684
2797
  const LOG_PAGE = 200;
2685
2798
  const GROUPS = {
2686
2799
  commit: 1,
@@ -2688,7 +2801,6 @@ const GROUPS = {
2688
2801
  flush: 256
2689
2802
  };
2690
2803
  const ATTEMPTS = 5;
2691
- const MAX_BUFFERED = 1e4;
2692
2804
  const log = defineTable({
2693
2805
  id: {
2694
2806
  type: "string",
@@ -2789,8 +2901,8 @@ const rewrite$1 = (change, key, current) => {
2789
2901
  previous: current
2790
2902
  };
2791
2903
  };
2792
- const compile = async (adapter, changes, shard) => {
2793
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
2904
+ const compile = async (adapter, changes) => {
2905
+ const keys = changes.map(({ key }) => [...key.slice(0, -1), 0]);
2794
2906
  const reads = /* @__PURE__ */ new Map();
2795
2907
  changes.forEach((change, at) => {
2796
2908
  if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
@@ -2836,7 +2948,7 @@ const encode = async (changes) => {
2836
2948
  const zipped = await deflate(json);
2837
2949
  return zipped !== void 0 && zipped.length < json.length ? `z${zipped}` : json;
2838
2950
  };
2839
- const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS$1[mode] }, now }) => {
2951
+ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs = WINDOW_MS$1 }, now }) => {
2840
2952
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
2841
2953
  const holder = crypto.randomUUID().replaceAll("-", "");
2842
2954
  const table = (name) => schema.models.get(name).table;
@@ -2863,61 +2975,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
2863
2975
  }
2864
2976
  return changes;
2865
2977
  };
2866
- const apply = async (changes, shard) => {
2867
- let rest = changes;
2868
- let ops = [];
2869
- let read = true;
2870
- for (let failures = 0; rest.length > 0 && failures < ATTEMPTS;) try {
2871
- if (read) ops = await compile(adapter, rest, shard);
2872
- let size = rest.length;
2873
- const chunk = () => ops.slice(0, size).filter(isOp);
2874
- while (size > 1 && !adapter.fits(chunk())) size = Math.ceil(size / 2);
2875
- let result = { ok: true };
2876
- if (chunk().length > 0) result = await adapter.write(chunk()).catch((error) => {
2877
- warn("flush")(error);
2878
- return { ok: true };
2879
- });
2880
- read = !result.ok && !("retry" in result);
2881
- if (result.ok) {
2882
- rest = rest.slice(size);
2883
- ops = ops.slice(size);
2884
- failures = 0;
2885
- } else {
2886
- failures += 1;
2887
- if (!read) await sleep(failures);
2888
- }
2889
- } catch (error) {
2890
- warn("flush")(error);
2891
- return rest;
2892
- }
2893
- return rest;
2894
- };
2895
- let buffer = /* @__PURE__ */ new Map();
2896
- let timer;
2897
- let flushing;
2898
- const shards = /* @__PURE__ */ new Map();
2899
- const processShard = (model) => {
2900
- if (!shards.has(model)) shards.set(model, Math.floor(Math.random() * shapeOf(model).shards));
2901
- return shards.get(model);
2902
- };
2903
- const schedule = () => {
2904
- if (timer !== void 0 || buffer.size === 0) return;
2905
- timer = setTimeout(() => {
2906
- timer = void 0;
2907
- flushBuffer();
2908
- }, windowMs);
2909
- timer.unref?.();
2910
- };
2911
- const flushBuffer = () => flushing ??= (async () => {
2912
- clearTimeout(timer);
2913
- timer = void 0;
2914
- const pending = [...buffer.values()];
2915
- buffer = /* @__PURE__ */ new Map();
2916
- mergeAll(buffer, await apply(pending, processShard));
2917
- })().catch(warn("flush")).finally(() => {
2918
- flushing = void 0;
2919
- schedule();
2920
- });
2921
2978
  let nextDue = 0;
2922
2979
  let compacting;
2923
2980
  const known = /* @__PURE__ */ new Map();
@@ -3039,7 +3096,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3039
3096
  more
3040
3097
  };
3041
3098
  };
3042
- const rowsFor = async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp);
3099
+ const rowsFor = async (changes) => (await compile(adapter, changes)).filter(isOp);
3043
3100
  const applyGroup = async (held, logs) => {
3044
3101
  for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
3045
3102
  const batch = logs.slice(0, count);
@@ -3119,19 +3176,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3119
3176
  }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
3120
3177
  checking = void 0;
3121
3178
  });
3122
- const committed = async (changes) => {
3123
- if (mode === "log") {
3124
- if (now() >= nextDue) await compact(false, GROUPS.commit);
3125
- return;
3126
- }
3127
- mergeAll(buffer, changes.values());
3128
- schedule();
3129
- if (buffer.size >= MAX_BUFFERED) await flushBuffer();
3130
- };
3131
- const flush = async () => {
3132
- await flushBuffer();
3133
- if (mode === "log" && await hasPending()) await compact(true, GROUPS.flush);
3134
- };
3135
3179
  return {
3136
3180
  async transaction(fn) {
3137
3181
  let changes = /* @__PURE__ */ new Map();
@@ -3157,7 +3201,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3157
3201
  aggregate
3158
3202
  });
3159
3203
  if (failure) throw failure.error;
3160
- if (mode === "log" && attempt.size > 0) {
3204
+ if (attempt.size > 0) {
3161
3205
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
3162
3206
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
3163
3207
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -3171,24 +3215,18 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
3171
3215
  open = false;
3172
3216
  }
3173
3217
  });
3174
- if (changes.size > 0) await committed(changes);
3218
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
3175
3219
  return result;
3176
3220
  },
3177
3221
  async beforeRead(name) {
3178
3222
  if (!isBatched(schema.models.get(name))) return;
3179
- if (buffer.size > 0 || flushing !== void 0) await flushBuffer();
3180
- if (mode === "log") {
3181
- if (await hasPending().catch((error) => {
3182
- warn("read")(error);
3183
- return false;
3184
- })) await compact(true, GROUPS.read);
3185
- }
3223
+ if (await hasPending().catch((error) => {
3224
+ warn("read")(error);
3225
+ return false;
3226
+ })) await compact(true, GROUPS.read);
3186
3227
  },
3187
- flush,
3188
- async dispose() {
3189
- clearTimeout(timer);
3190
- timer = void 0;
3191
- await flush();
3228
+ async flush() {
3229
+ if (await hasPending()) await compact(true, GROUPS.flush);
3192
3230
  }
3193
3231
  };
3194
3232
  };
@@ -3307,7 +3345,8 @@ const fieldProblems = (definition, add) => {
3307
3345
  else if (field.required === false) add(`key field "${name}" is nullable`);
3308
3346
  else if (field.type === "json") add(`key field "${name}" is json`);
3309
3347
  }
3310
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
3348
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
3349
+ for (const [name, { type, maxLength, ascii }] of bounded) {
3311
3350
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
3312
3351
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
3313
3352
  }
@@ -3419,11 +3458,13 @@ const resolveSchema = (modules) => {
3419
3458
  ...maxLength === void 0 ? {} : { maxLength },
3420
3459
  ...ascii ? { ascii } : {}
3421
3460
  }));
3422
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
3461
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
3423
3462
  name: field,
3424
3463
  type,
3425
3464
  nullable: true,
3426
- ...multi ? { multi } : {}
3465
+ ...multi ? { multi } : {},
3466
+ ...maxLength === void 0 ? {} : { maxLength },
3467
+ ...ascii ? { ascii } : {}
3427
3468
  });
3428
3469
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
3429
3470
  name: metric,
@@ -4147,9 +4188,6 @@ const createDatabaseEngine = ({ batching, now = Date.now, meter, ...options }) =
4147
4188
  flush: async () => {
4148
4189
  await batches?.flush();
4149
4190
  },
4150
- dispose: async () => {
4151
- await batches?.dispose();
4152
- },
4153
4191
  database(module) {
4154
4192
  const name = (model) => module.namespace ? `${module.namespace}_${model}` : model;
4155
4193
  return {
@@ -4217,8 +4255,7 @@ const createEngine = (database, { plugins = [], now = Date.now } = {}) => {
4217
4255
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
4218
4256
  return engine.database(module);
4219
4257
  },
4220
- flush: () => engine.flush(),
4221
- dispose: () => engine.dispose()
4258
+ flush: () => engine.flush()
4222
4259
  };
4223
4260
  };
4224
4261
  //#endregion
@@ -17667,6 +17704,7 @@ var import_lib$1 = /* @__PURE__ */ __toESM(require_lib$2(), 1);
17667
17704
  const { Pool } = import_lib$1.default;
17668
17705
  const DATABASE_TARGET = Symbol.for("@hot-updater/database-target");
17669
17706
  const targetOf = ({ connectionString, host, port, database }) => {
17707
+ if (typeof connectionString === "function") return void 0;
17670
17708
  if (connectionString !== void 0) try {
17671
17709
  const url = new URL(connectionString);
17672
17710
  return `postgres/${url.hostname}:${url.port || "5432"}/${decodeURIComponent(url.pathname.slice(1))}`;
@@ -17678,7 +17716,14 @@ const targetOf = ({ connectionString, host, port, database }) => {
17678
17716
  const postgres = (config) => {
17679
17717
  const { dialect, ...poolConfig } = config;
17680
17718
  const target = targetOf(poolConfig);
17681
- const db = new Kysely({ dialect: dialect ?? new PostgresDialect({ pool: new Pool(poolConfig) }) });
17719
+ const { connectionString } = poolConfig;
17720
+ const db = new Kysely({ dialect: dialect ?? new PostgresDialect({ pool: typeof connectionString === "function" ? async () => new Pool({
17721
+ ...poolConfig,
17722
+ connectionString: await connectionString()
17723
+ }) : new Pool({
17724
+ ...poolConfig,
17725
+ connectionString
17726
+ }) }) });
17682
17727
  return {
17683
17728
  ...createEngineDatabase({
17684
17729
  name: "postgres",
@@ -17690,7 +17735,7 @@ const postgres = (config) => {
17690
17735
  };
17691
17736
  //#endregion
17692
17737
  //#region ../../packages/server/dist/version.mjs
17693
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.4";
17738
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.40";
17694
17739
  //#endregion
17695
17740
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
17696
17741
  const createVersionRouteHandlers = (plugins = []) => {
@@ -18423,8 +18468,8 @@ const baseBundleIdsOf = (row, range, bundleId, limit) => {
18423
18468
  //#endregion
18424
18469
  //#region ../../packages/server/dist/core/reads.mjs
18425
18470
  const PAGE$3 = 500;
18426
- const pick$1 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
18427
- const toBundleRow = pick$1([
18471
+ const pick$2 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
18472
+ const toBundleRow = pick$2([
18428
18473
  "id",
18429
18474
  "platform",
18430
18475
  "git_commit_hash",
@@ -18433,7 +18478,7 @@ const toBundleRow = pick$1([
18433
18478
  "manifest_file_hash",
18434
18479
  "asset_base_storage_uri"
18435
18480
  ]);
18436
- const toPatchRow = pick$1([
18481
+ const toPatchRow = pick$2([
18437
18482
  "id",
18438
18483
  "bundle_id",
18439
18484
  "base_bundle_id",
@@ -18443,7 +18488,7 @@ const toPatchRow = pick$1([
18443
18488
  "byte_size",
18444
18489
  "order_index"
18445
18490
  ]);
18446
- const toReleaseRow = pick$1([
18491
+ const toReleaseRow = pick$2([
18447
18492
  "id",
18448
18493
  "revision",
18449
18494
  "scope_key",
@@ -18464,7 +18509,7 @@ const toReleaseRow = pick$1([
18464
18509
  "created_at_ms",
18465
18510
  "updated_at_ms"
18466
18511
  ]);
18467
- const toCatalogRow = pick$1([
18512
+ const toCatalogRow = pick$2([
18468
18513
  "scope_key",
18469
18514
  "catalog_id",
18470
18515
  "strategy",
@@ -18479,7 +18524,7 @@ const toCatalogRow = pick$1([
18479
18524
  "is_tombstone",
18480
18525
  "updated_at_ms"
18481
18526
  ]);
18482
- const toChannelRow = pick$1(["id", "name"]);
18527
+ const toChannelRow = pick$2(["id", "name"]);
18483
18528
  const drain$1 = async (read) => {
18484
18529
  const rows = [];
18485
18530
  let cursor;
@@ -18490,7 +18535,14 @@ const drain$1 = async (read) => {
18490
18535
  } while (cursor !== void 0);
18491
18536
  return rows;
18492
18537
  };
18493
- const after = (input) => input.after === void 0 ? {} : { range: (input.order ?? "asc") === "asc" ? { gt: input.after } : { lt: input.after } };
18538
+ const after = (input) => {
18539
+ const asc = (input.order ?? "asc") === "asc";
18540
+ const range = {
18541
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
18542
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
18543
+ };
18544
+ return Object.keys(range).length === 0 ? {} : { range };
18545
+ };
18494
18546
  const createCoreReads = (db, storage) => {
18495
18547
  const detail = async (row) => {
18496
18548
  const count = row._refs_bundle_patches_bundle_id ?? 0;
@@ -18681,6 +18733,293 @@ const createCoreReads = (db, storage) => {
18681
18733
  };
18682
18734
  };
18683
18735
  //#endregion
18736
+ //#region ../../packages/server/dist/core/iosDevices.mjs
18737
+ const UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
18738
+ const normalizeIosUdid = (value) => {
18739
+ const trimmed = value.trim();
18740
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
18741
+ };
18742
+ const NAME_MAX_LENGTH = 100;
18743
+ const EMAIL_MAX_LENGTH = 320;
18744
+ const ISSUER_MAX_LENGTH = 64;
18745
+ const ACCOUNT_SCAN_PAGE = 200;
18746
+ const ACCOUNT_ROW = "registry";
18747
+ const ERROR_MAX_LENGTH = 512;
18748
+ const STATUSES = [
18749
+ "pending",
18750
+ "approved",
18751
+ "registered"
18752
+ ];
18753
+ const OUTCOMES = [
18754
+ "registered",
18755
+ "refused",
18756
+ "disabled",
18757
+ "missing"
18758
+ ];
18759
+ const IOS_DEVICE_DISABLED_ERROR = "Disabled in the Apple account.";
18760
+ const IOS_DEVICE_MISSING_ERROR = "Gone from the Apple account. Approve it again to register it.";
18761
+ var IosDeviceInputError = class extends TypeError {
18762
+ name = "IosDeviceInputError";
18763
+ };
18764
+ const pick$1 = (row) => ({
18765
+ id: row.id,
18766
+ udid: row.udid,
18767
+ name: row.name,
18768
+ status: row.status,
18769
+ requested_by: row.requested_by ?? null,
18770
+ created_at_ms: row.created_at_ms,
18771
+ approved_by: row.approved_by ?? null,
18772
+ approved_at_ms: row.approved_at_ms ?? null,
18773
+ registered_at_ms: row.registered_at_ms ?? null,
18774
+ apple_issuer_id: row.apple_issuer_id ?? null,
18775
+ apple_error: row.apple_error ?? null,
18776
+ build_id: row.build_id ?? null
18777
+ });
18778
+ const udidOf = (udid) => {
18779
+ const key = typeof udid === "string" ? normalizeIosUdid(udid) : null;
18780
+ if (key === null) throw new IosDeviceInputError("Invalid iOS device: udid must be 40 hex digits, or 8 and 16 joined by a hyphen.");
18781
+ return key;
18782
+ };
18783
+ const nameOf = (name) => {
18784
+ const trimmed = typeof name === "string" ? name.trim() : "";
18785
+ if (trimmed.length === 0 || trimmed.length > NAME_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: name must be 1 to ${NAME_MAX_LENGTH} characters.`);
18786
+ return trimmed;
18787
+ };
18788
+ const personOf = (value, field) => {
18789
+ if (value === null) return null;
18790
+ const email = typeof value === "string" ? value.trim().toLowerCase() : "";
18791
+ 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.`);
18792
+ return email;
18793
+ };
18794
+ const errorText = (text) => {
18795
+ const line = text.replace(/\s+/gu, " ").trim();
18796
+ return line.length > ERROR_MAX_LENGTH ? `${line.slice(0, 511)}…` : line;
18797
+ };
18798
+ const createIosDeviceApi = (db, { now = Date.now } = {}) => {
18799
+ const findIosDevice = async (udid) => {
18800
+ const key = normalizeIosUdid(udid);
18801
+ if (key === null) return null;
18802
+ const row = await db.findOne("ios_devices", { udid: key });
18803
+ return row === null ? null : pick$1(row);
18804
+ };
18805
+ const accountOfRows = async () => {
18806
+ let earliest = null;
18807
+ for (let after;;) {
18808
+ const { rows } = await db.findMany("ios_devices", {
18809
+ index: "all",
18810
+ where: {},
18811
+ order: "asc",
18812
+ limit: ACCOUNT_SCAN_PAGE,
18813
+ ...after === void 0 ? {} : { range: { gt: after } }
18814
+ });
18815
+ for (const row of rows.map(pick$1)) {
18816
+ if (row.apple_issuer_id === null) continue;
18817
+ if (earliest === null || (row.registered_at_ms ?? 0) < (earliest.registered_at_ms ?? 0)) earliest = row;
18818
+ }
18819
+ if (rows.length < ACCOUNT_SCAN_PAGE) return earliest?.apple_issuer_id ?? null;
18820
+ after = rows.at(-1).id;
18821
+ }
18822
+ };
18823
+ return {
18824
+ async listIosDevices(input) {
18825
+ if (input.status !== void 0 && !STATUSES.includes(input.status)) throw new IosDeviceInputError(`Invalid iOS device status: ${String(input.status)}. Expected ${STATUSES.join(", ")}.`);
18826
+ const page = {
18827
+ order: input.order ?? "asc",
18828
+ limit: input.limit,
18829
+ ...after(input)
18830
+ };
18831
+ const { rows } = input.status === void 0 ? await db.findMany("ios_devices", {
18832
+ index: "all",
18833
+ where: {},
18834
+ ...page
18835
+ }) : await db.findMany("ios_devices", {
18836
+ index: "byStatus",
18837
+ where: { status: input.status },
18838
+ ...page
18839
+ });
18840
+ return rows.map(pick$1);
18841
+ },
18842
+ findIosDevice,
18843
+ async requestIosDevice(input) {
18844
+ const udid = udidOf(input.udid);
18845
+ const name = nameOf(input.name);
18846
+ const requestedBy = personOf(input.requestedBy, "requestedBy");
18847
+ const existing = await db.findOne("ios_devices", { udid });
18848
+ if (existing !== null) return {
18849
+ device: pick$1(existing),
18850
+ created: false
18851
+ };
18852
+ const device = {
18853
+ id: createUUIDv7(),
18854
+ udid,
18855
+ name,
18856
+ status: "pending",
18857
+ requested_by: requestedBy,
18858
+ created_at_ms: now(),
18859
+ approved_by: null,
18860
+ approved_at_ms: null,
18861
+ registered_at_ms: null,
18862
+ apple_issuer_id: null,
18863
+ apple_error: null,
18864
+ build_id: null
18865
+ };
18866
+ try {
18867
+ await db.transaction(async (tx) => {
18868
+ tx.create("ios_devices", device);
18869
+ });
18870
+ } catch (error) {
18871
+ if (error instanceof DatabaseConstraintError && error.reason === "unique") {
18872
+ const winner = await db.findOne("ios_devices", { udid });
18873
+ if (winner !== null) return {
18874
+ device: pick$1(winner),
18875
+ created: false
18876
+ };
18877
+ }
18878
+ throw error;
18879
+ }
18880
+ return {
18881
+ device,
18882
+ created: true
18883
+ };
18884
+ },
18885
+ async approveIosDevice(id, input) {
18886
+ const name = input.name === void 0 ? void 0 : nameOf(input.name);
18887
+ const approvedBy = personOf(input.approvedBy, "approvedBy");
18888
+ return db.transaction(async (tx) => {
18889
+ const row = await tx.findOne("ios_devices", { id });
18890
+ if (row === null) return null;
18891
+ const device = pick$1(row);
18892
+ const set = {
18893
+ ...name === void 0 || name === device.name ? {} : { name },
18894
+ ...device.status === "pending" ? {
18895
+ status: "approved",
18896
+ approved_by: approvedBy,
18897
+ approved_at_ms: now()
18898
+ } : {}
18899
+ };
18900
+ if (Object.keys(set).length === 0) return device;
18901
+ tx.update("ios_devices", row, set);
18902
+ return {
18903
+ ...device,
18904
+ ...set
18905
+ };
18906
+ });
18907
+ },
18908
+ async renameIosDevice(id, input) {
18909
+ const name = nameOf(input);
18910
+ return db.transaction(async (tx) => {
18911
+ const row = await tx.findOne("ios_devices", { id });
18912
+ if (row === null) return null;
18913
+ const device = pick$1(row);
18914
+ if (device.name === name) return device;
18915
+ tx.update("ios_devices", row, { name });
18916
+ return {
18917
+ ...device,
18918
+ name
18919
+ };
18920
+ });
18921
+ },
18922
+ async recordIosDeviceOutcome({ id, seen, issuerId, outcome, reason }) {
18923
+ if (!OUTCOMES.includes(outcome)) throw new IosDeviceInputError(`Invalid iOS device outcome: ${String(outcome)}. Expected ${OUTCOMES.join(", ")}.`);
18924
+ 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.`);
18925
+ return db.transaction(async (tx) => {
18926
+ const row = await tx.findOne("ios_devices", { id });
18927
+ if (row === null) return null;
18928
+ const device = pick$1(row);
18929
+ if (device.status !== seen.status || device.approved_at_ms !== seen.approvedAtMs || device.apple_issuer_id !== null && device.apple_issuer_id !== issuerId) return null;
18930
+ let set;
18931
+ switch (outcome) {
18932
+ case "registered":
18933
+ if (device.status === "pending") return null;
18934
+ set = {
18935
+ status: "registered",
18936
+ registered_at_ms: device.registered_at_ms ?? now(),
18937
+ apple_issuer_id: issuerId,
18938
+ apple_error: null
18939
+ };
18940
+ break;
18941
+ case "refused":
18942
+ if (device.status !== "approved") return null;
18943
+ set = { apple_error: errorText(reason === void 0 || reason.trim() === "" ? "Apple refused it." : reason) };
18944
+ break;
18945
+ case "disabled":
18946
+ if (device.status === "pending") return null;
18947
+ set = { apple_error: IOS_DEVICE_DISABLED_ERROR };
18948
+ break;
18949
+ case "missing":
18950
+ if (device.status !== "registered") return null;
18951
+ set = {
18952
+ status: "pending",
18953
+ approved_by: null,
18954
+ approved_at_ms: null,
18955
+ apple_error: IOS_DEVICE_MISSING_ERROR
18956
+ };
18957
+ }
18958
+ if (Object.entries(set).some(([column, value]) => device[column] !== (value ?? null))) tx.update("ios_devices", row, set);
18959
+ return {
18960
+ ...device,
18961
+ ...set
18962
+ };
18963
+ });
18964
+ },
18965
+ async markIosDevicesInBuild({ buildId, ids }) {
18966
+ for (const id of new Set(ids)) await db.transaction(async (tx) => {
18967
+ const row = await tx.findOne("ios_devices", { id });
18968
+ if (row === null || typeof row.build_id === "string" && row.build_id >= buildId) return;
18969
+ tx.update("ios_devices", row, { build_id: buildId });
18970
+ });
18971
+ },
18972
+ async claimIosDeviceAccount(issuerId) {
18973
+ 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.`);
18974
+ const answer = (held) => ({
18975
+ issuerId: held,
18976
+ claimed: held === issuerId
18977
+ });
18978
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
18979
+ if (existing !== null) return answer(existing.apple_issuer_id);
18980
+ const holder = await accountOfRows() ?? issuerId;
18981
+ try {
18982
+ await db.transaction(async (tx) => {
18983
+ tx.create("ios_device_account", {
18984
+ id: ACCOUNT_ROW,
18985
+ apple_issuer_id: holder,
18986
+ claimed_at_ms: now()
18987
+ });
18988
+ });
18989
+ return answer(holder);
18990
+ } catch (error) {
18991
+ if (error instanceof DatabaseConstraintError && (error.reason === "exists" || error.reason === "unique")) {
18992
+ const winner = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
18993
+ if (winner !== null) return answer(winner.apple_issuer_id);
18994
+ }
18995
+ throw error;
18996
+ }
18997
+ },
18998
+ async deleteIosDevice(id, only) {
18999
+ const requestedBy = only?.requestedBy === void 0 ? void 0 : personOf(only.requestedBy, "requestedBy");
19000
+ return db.transaction(async (tx) => {
19001
+ const row = await tx.findOne("ios_devices", { id });
19002
+ if (row === null) return null;
19003
+ const device = pick$1(row);
19004
+ if (only?.status !== void 0 && device.status !== only.status || requestedBy !== void 0 && device.requested_by !== requestedBy) return null;
19005
+ await tx.delete("ios_devices", row);
19006
+ return device;
19007
+ });
19008
+ }
19009
+ };
19010
+ };
19011
+ //#endregion
19012
+ //#region ../../packages/server/dist/core/nativeBuildDestinations.mjs
19013
+ const NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
19014
+ android: [
19015
+ "play-internal",
19016
+ "play-closed",
19017
+ "play-open",
19018
+ "play-production"
19019
+ ],
19020
+ ios: ["testflight"]
19021
+ };
19022
+ //#endregion
18684
19023
  //#region ../../packages/server/dist/core/writes.mjs
18685
19024
  const PAGE$2 = 500;
18686
19025
  const countBundle = (tx, platform, delta) => {
@@ -18701,7 +19040,7 @@ const deleteBundle = async (tx, current) => {
18701
19040
  await tx.delete("bundles", current);
18702
19041
  countBundle(tx, current.platform, -1);
18703
19042
  };
18704
- const replaceBundlePatches = async (tx, bundle, rows) => {
19043
+ const replaceBundlePatches = async (tx, bundle, rows, checkNew) => {
18705
19044
  const wanted = new Map(rows.map((row) => [row.id, row]));
18706
19045
  const count = bundle._refs_bundle_patches_bundle_id ?? 0;
18707
19046
  let cursor;
@@ -18726,6 +19065,7 @@ const replaceBundlePatches = async (tx, bundle, rows) => {
18726
19065
  if (page.next === void 0) break;
18727
19066
  cursor = page.next;
18728
19067
  }
19068
+ if (checkNew !== void 0) for (const row of wanted.values()) await checkNew(row);
18729
19069
  for (const row of wanted.values()) tx.create("bundle_patches", row);
18730
19070
  };
18731
19071
  const insertChannel = async (db, row) => {
@@ -18778,6 +19118,8 @@ const ARTIFACT_KINDS = {
18778
19118
  const SCOPE_KEY_MAX_LENGTH = 2048;
18779
19119
  const GIT_COMMIT_HASH_MAX_LENGTH = 255;
18780
19120
  const BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
19121
+ const SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
19122
+ const URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
18781
19123
  var NativeBuildInputError = class extends TypeError {
18782
19124
  name = "NativeBuildInputError";
18783
19125
  };
@@ -18798,12 +19140,22 @@ const pick = (row) => ({
18798
19140
  build_number: row.build_number ?? null,
18799
19141
  submitted_to: row.submitted_to ?? null,
18800
19142
  submitted_at_ms: row.submitted_at_ms ?? null,
18801
- submitted_version: row.submitted_version ?? null
19143
+ submitted_version: row.submitted_version ?? null,
19144
+ is_store_build: row.is_store_build === true,
19145
+ is_sandbox: row.is_sandbox === true,
19146
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
19147
+ export_method: row.export_method ?? null,
19148
+ native_app_version: row.native_app_version ?? null
18802
19149
  });
18803
- const SUBMISSION_DESTINATIONS = {
18804
- android: "play-internal",
18805
- ios: "testflight"
18806
- };
19150
+ const EXPORT_METHODS = /* @__PURE__ */ new Set([
19151
+ "app-store",
19152
+ "ad-hoc",
19153
+ "development",
19154
+ "enterprise"
19155
+ ]);
19156
+ const SANDBOX_CHANNEL_PREFIX = "sandbox-";
19157
+ const OLDER_BUILDS_PAGE = 20;
19158
+ const MARK_ATTEMPTS = 8;
18807
19159
  const BUILD_NUMBER_MAX_LENGTH = 64;
18808
19160
  const SUBMITTED_VERSION_MAX_LENGTH = 255;
18809
19161
  const nativeBuildScopeKey = (scope) => {
@@ -18826,18 +19178,34 @@ const nativeBuildScopeKey = (scope) => {
18826
19178
  if (scopeKey.length > SCOPE_KEY_MAX_LENGTH) throw new NativeBuildInputError(`Invalid native build scope: its key is longer than ${SCOPE_KEY_MAX_LENGTH} characters; shorten the channel or app version.`);
18827
19179
  return scopeKey;
18828
19180
  };
19181
+ const refuseSandboxPatchBase = async (db, baseBundleId) => {
19182
+ if ((await db.findOne("native_builds", { min_bundle_id: baseBundleId }))?.is_sandbox === true) throw new NativeBuildInputError("A sandbox build's built-in bundle is no patch base.");
19183
+ };
18829
19184
  const isBuiltInBundle = async (db, bundleId) => await db.findOne("native_builds", { min_bundle_id: bundleId }) !== null;
18830
- const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, artifact }) => {
19185
+ const problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, exportMethod, nativeAppVersion, artifact }) => {
18831
19186
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
18832
19187
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
18833
19188
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
18834
19189
  if (channel.trim().length === 0) return "channel is required";
19190
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
19191
+ const reserved = channel.startsWith(SANDBOX_CHANNEL_PREFIX);
19192
+ if (isSandbox === true && !reserved) return `a sandbox build registers on a ${SANDBOX_CHANNEL_PREFIX}* channel, not ${channel}`;
19193
+ if (isSandbox !== true && reserved) return `channel ${channel} is reserved for sandbox builds`;
19194
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
19195
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
19196
+ 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`;
19197
+ }
18835
19198
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
18836
19199
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
18837
19200
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
18838
19201
  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`;
19202
+ if (nativeAppVersion !== void 0 && nativeAppVersion !== null && (typeof nativeAppVersion !== "string" || nativeAppVersion.trim().length === 0)) return "nativeAppVersion must be the artifact's app version, or null";
18839
19203
  const kinds = ARTIFACT_KINDS[platform];
18840
19204
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
19205
+ if (exportMethod !== void 0 && exportMethod !== null) {
19206
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
19207
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
19208
+ }
18841
19209
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
18842
19210
  return null;
18843
19211
  };
@@ -18865,7 +19233,12 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18865
19233
  build_number: registration.buildNumber ?? null,
18866
19234
  submitted_to: null,
18867
19235
  submitted_at_ms: null,
18868
- submitted_version: null
19236
+ submitted_version: null,
19237
+ is_store_build: false,
19238
+ is_sandbox: registration.isSandbox === true,
19239
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
19240
+ export_method: registration.exportMethod ?? null,
19241
+ native_app_version: registration.nativeAppVersion ?? null
18869
19242
  };
18870
19243
  for (let attempt = 1;; attempt += 1) {
18871
19244
  await insertChannel(db, {
@@ -18903,21 +19276,43 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18903
19276
  const scopeKey = nativeBuildScopeKey(scope);
18904
19277
  const buildKey = options?.buildKey;
18905
19278
  if (buildKey !== void 0 && !BUILD_KEY.test(buildKey)) throw new NativeBuildInputError("Invalid native build key: it must be nbk1: and a SHA-256.");
18906
- const { rows } = buildKey === void 0 ? await db.findMany("native_builds", {
18907
- index: "byScope",
18908
- where: { scope_key: scopeKey },
18909
- order: "desc",
18910
- limit: 1
18911
- }) : await db.findMany("native_builds", {
18912
- index: "byBuildKey",
18913
- where: {
18914
- scope_key: scopeKey,
18915
- build_key: buildKey
18916
- },
18917
- order: "desc",
18918
- limit: 1
18919
- });
18920
- return rows[0] === void 0 ? null : pick(rows[0]);
19279
+ if (options?.storeBuild) {
19280
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
19281
+ return marked === null ? null : pick(marked);
19282
+ }
19283
+ const read = (limit, before) => {
19284
+ const page = {
19285
+ order: "desc",
19286
+ limit,
19287
+ ...before === void 0 ? {} : { range: { lt: before } }
19288
+ };
19289
+ return buildKey === void 0 ? db.findMany("native_builds", {
19290
+ index: "byScope",
19291
+ where: { scope_key: scopeKey },
19292
+ ...page
19293
+ }) : db.findMany("native_builds", {
19294
+ index: "byBuildKey",
19295
+ where: {
19296
+ scope_key: scopeKey,
19297
+ build_key: buildKey
19298
+ },
19299
+ ...page
19300
+ });
19301
+ };
19302
+ const bundleId = options?.builtInOlderThan;
19303
+ if (bundleId !== void 0 && scope.channel.startsWith(SANDBOX_CHANNEL_PREFIX)) return null;
19304
+ const { rows } = await read(1);
19305
+ const newest = rows[0];
19306
+ if (newest === void 0) return null;
19307
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return pick(newest);
19308
+ for (let before = newest.id;;) {
19309
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
19310
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
19311
+ if (usable !== void 0) return pick(usable);
19312
+ const last = older.at(-1);
19313
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
19314
+ before = last.id;
19315
+ }
18921
19316
  },
18922
19317
  async recordNativeBuildSubmission(id, { destination, version }) {
18923
19318
  if (version.trim().length === 0 || version.length > SUBMITTED_VERSION_MAX_LENGTH) throw new NativeBuildInputError(`Invalid native build submission: version must be the store's label of the build, up to ${SUBMITTED_VERSION_MAX_LENGTH} characters.`);
@@ -18925,7 +19320,8 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18925
19320
  const row = await tx.findOne("native_builds", { id });
18926
19321
  if (row === null) return null;
18927
19322
  const build = pick(row);
18928
- 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}.`);
19323
+ 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}.`);
19324
+ if (build.is_sandbox && destination !== "testflight" && destination !== "play-internal") throw new NativeBuildInputError("A sandbox build can submit only to TestFlight or Play internal testing.");
18929
19325
  const set = {
18930
19326
  submitted_to: destination,
18931
19327
  submitted_at_ms: now(),
@@ -18938,6 +19334,46 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
18938
19334
  };
18939
19335
  });
18940
19336
  },
19337
+ async markNativeBuild(id, { storeBuild }) {
19338
+ for (let attempt = 1;; attempt += 1) try {
19339
+ return await db.transaction(async (tx) => {
19340
+ const row = await tx.findOne("native_builds", { id });
19341
+ if (row === null) return null;
19342
+ const build = pick(row);
19343
+ if (!storeBuild) {
19344
+ if (build.is_store_build) tx.update("native_builds", row, { is_store_build: false });
19345
+ return {
19346
+ nativeBuild: {
19347
+ ...build,
19348
+ is_store_build: false
19349
+ },
19350
+ previous: null
19351
+ };
19352
+ }
19353
+ if (build.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
19354
+ if (build.is_store_build) return {
19355
+ nativeBuild: build,
19356
+ previous: null
19357
+ };
19358
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build.scope_key });
19359
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
19360
+ tx.update("native_builds", row, { is_store_build: true });
19361
+ return {
19362
+ nativeBuild: {
19363
+ ...build,
19364
+ is_store_build: true
19365
+ },
19366
+ previous: holder === null ? null : {
19367
+ ...pick(holder),
19368
+ is_store_build: false
19369
+ }
19370
+ };
19371
+ });
19372
+ } catch (error) {
19373
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
19374
+ throw error;
19375
+ }
19376
+ },
18941
19377
  async deleteNativeBuild(id) {
18942
19378
  return db.transaction(async (tx) => {
18943
19379
  const row = await tx.findOne("native_builds", { id });
@@ -19257,7 +19693,11 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
19257
19693
  for (const { release } of deployments) if (!channels.has(release.channel)) channels.set(release.channel, await ensureChannel(release.channel));
19258
19694
  const platforms = /* @__PURE__ */ new Map();
19259
19695
  for (const deployment of deployments) {
19260
- if (!("bundleId" in deployment) || platforms.has(deployment.bundleId)) continue;
19696
+ if (!("bundleId" in deployment)) {
19697
+ for (const { baseBundleId } of deployment.bundle.patches ?? []) await refuseSandboxPatchBase(db, baseBundleId);
19698
+ continue;
19699
+ }
19700
+ if (platforms.has(deployment.bundleId)) continue;
19261
19701
  const row = await db.findOne("bundles", { id: deployment.bundleId });
19262
19702
  if (row === null) throw new DatabaseBundleNotFoundError(deployment.bundleId);
19263
19703
  if (await isBuiltInBundle(db, deployment.bundleId)) throw new ReleaseManagementError("TARGET_RELEASE_INVALID", `Bundle "${deployment.bundleId}" is a native build's built-in bundle, which no release publishes.`);
@@ -19461,7 +19901,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
19461
19901
  if (patches !== void 0) await replaceBundlePatches(tx, current, bundleToPatchRows({
19462
19902
  ...next,
19463
19903
  patches
19464
- }));
19904
+ }), (row) => refuseSandboxPatchBase(tx, row.base_bundle_id));
19465
19905
  }),
19466
19906
  deleteBundles: async (ids) => {
19467
19907
  try {
@@ -19517,6 +19957,7 @@ const createCoreApi = (db, storage, options = {}) => {
19517
19957
  ...reads,
19518
19958
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
19519
19959
  ...createNativeBuildApi(db, options),
19960
+ ...createIosDeviceApi(db, options),
19520
19961
  ready: async () => {
19521
19962
  await reads.listReleaseCatalogs({ limit: 1 });
19522
19963
  }
@@ -19726,10 +20167,12 @@ const keyset = (url, maxValue = LIMITS.maxValue) => {
19726
20167
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
19727
20168
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
19728
20169
  const cursor = url.searchParams.get("cursor");
20170
+ const through = url.searchParams.get("through");
19729
20171
  return {
19730
20172
  order,
19731
20173
  limit,
19732
- ...cursor === null ? {} : { after: cursor }
20174
+ ...cursor === null ? {} : { after: cursor },
20175
+ ...through === null ? {} : { through }
19733
20176
  };
19734
20177
  };
19735
20178
  const page = (rows, { limit }, keyOf, extra = {}) => json$2({
@@ -19836,11 +20279,11 @@ const refusingInvalid = async (operation) => {
19836
20279
  try {
19837
20280
  return await operation();
19838
20281
  } catch (error) {
19839
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
20282
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
19840
20283
  throw error;
19841
20284
  }
19842
20285
  };
19843
- const isNativeBuildRegistration = (value) => isRecord$5(value) && isText$2(value.id) && isText$2(value.minBundleId) && typeof value.platform === "string" && isPlatform(value.platform) && isText$2(value.channel) && isTextOrNull$1(value.fingerprintHash) && isTextOrNull$1(value.appVersion) && value.fingerprintHash === null !== (value.appVersion === null) && isTextOrNull$1(value.gitCommitHash) && isTextOrNull$1(value.buildKey) && (value.buildNumber === void 0 || isTextOrNull$1(value.buildNumber)) && isRecord$5(value.artifact) && typeof value.artifact.kind === "string" && NATIVE_BUILD_ARTIFACT_KINDS.has(value.artifact.kind) && isText$2(value.artifact.storageUri) && Number.isSafeInteger(value.artifact.byteSize) && value.artifact.byteSize >= 0 && isRecord$5(value.embeddedBundle) && isText$2(value.embeddedBundle.manifestStorageUri) && isText$2(value.embeddedBundle.manifestFileHash) && isText$2(value.embeddedBundle.assetBaseStorageUri) && (value.embeddedBundle.metadata === void 0 || isRecord$5(value.embeddedBundle.metadata));
20286
+ const isNativeBuildRegistration = (value) => isRecord$5(value) && isText$2(value.id) && isText$2(value.minBundleId) && typeof value.platform === "string" && isPlatform(value.platform) && isText$2(value.channel) && isTextOrNull$1(value.fingerprintHash) && isTextOrNull$1(value.appVersion) && value.fingerprintHash === null !== (value.appVersion === null) && isTextOrNull$1(value.gitCommitHash) && isTextOrNull$1(value.buildKey) && (value.buildNumber === void 0 || isTextOrNull$1(value.buildNumber)) && (value.isSandbox === void 0 || typeof value.isSandbox === "boolean") && (value.sandboxUrlScheme === void 0 || isTextOrNull$1(value.sandboxUrlScheme)) && (value.exportMethod === void 0 || isTextOrNull$1(value.exportMethod)) && (value.nativeAppVersion === void 0 || isTextOrNull$1(value.nativeAppVersion)) && isRecord$5(value.artifact) && typeof value.artifact.kind === "string" && NATIVE_BUILD_ARTIFACT_KINDS.has(value.artifact.kind) && isText$2(value.artifact.storageUri) && Number.isSafeInteger(value.artifact.byteSize) && value.artifact.byteSize >= 0 && isRecord$5(value.embeddedBundle) && isText$2(value.embeddedBundle.manifestStorageUri) && isText$2(value.embeddedBundle.manifestFileHash) && isText$2(value.embeddedBundle.assetBaseStorageUri) && (value.embeddedBundle.metadata === void 0 || isRecord$5(value.embeddedBundle.metadata));
19844
20287
  const scopeKeyOf = (params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "";
19845
20288
  const createAdminRouteHandlers = () => ({
19846
20289
  listBundles: onCore(async (core, request) => {
@@ -19917,7 +20360,8 @@ const createAdminRouteHandlers = () => ({
19917
20360
  rebuildReleaseCatalog: onCore(async (core, _request, params) => json$2({ data: await core.rebuildReleaseCatalog(scopeKeyOf(params)) })),
19918
20361
  updateBundle: onCore(async (core, request, params) => {
19919
20362
  const bundleId = requireRouteParam(params, "id");
19920
- await core.updateBundle(bundleId, bundleUpdateOf(await request.json(), bundleId));
20363
+ const update = bundleUpdateOf(await request.json(), bundleId);
20364
+ await refusingInvalid(() => core.updateBundle(bundleId, update));
19921
20365
  return noContent();
19922
20366
  }),
19923
20367
  countBundles: onCore(async (core, request) => json$2({ data: await core.countBundles(platformOf(new URL(request.url))) })),
@@ -19941,7 +20385,7 @@ const createAdminRouteHandlers = () => ({
19941
20385
  deployReleases: onCore(async (core, request) => {
19942
20386
  const { deployments } = await body(request);
19943
20387
  if (!Array.isArray(deployments) || deployments.length === 0 || !deployments.every(isDeployment)) throw new HandlerBadRequestError("Deploy needs deployments, each a bundle and its release policy.");
19944
- return json$2({ data: await core.deploy(deployments) }, 201);
20388
+ return json$2({ data: await refusingInvalid(() => core.deploy(deployments)) }, 201);
19945
20389
  }),
19946
20390
  promoteRelease: onCore(async (core, request, params) => {
19947
20391
  const input = await body(request);
@@ -19964,7 +20408,13 @@ const createAdminRouteHandlers = () => ({
19964
20408
  const url = new URL(request.url);
19965
20409
  const scope = nativeBuildScopeOf(url);
19966
20410
  const buildKey = url.searchParams.get("buildKey");
19967
- return json$2({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
20411
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
20412
+ const options = {
20413
+ ...buildKey === null ? {} : { buildKey },
20414
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
20415
+ ...builtInOlderThan === null ? {} : { builtInOlderThan }
20416
+ };
20417
+ return json$2({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
19968
20418
  }),
19969
20419
  getNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
19970
20420
  listNativeBuilds: onCore(async (core, request) => {
@@ -19978,14 +20428,95 @@ const createAdminRouteHandlers = () => ({
19978
20428
  }),
19979
20429
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
19980
20430
  const input = await body(request);
19981
- if (!isRecord$5(input) || input.destination !== "testflight" && input.destination !== "play-internal" || !isText$2(input.version)) throw new HandlerBadRequestError("A native build submission needs destination (testflight or play-internal) and version.");
20431
+ if (!isRecord$5(input) || !Object.values(NATIVE_BUILD_SUBMISSION_DESTINATIONS).flat().includes(input.destination) || !isText$2(input.version)) throw new HandlerBadRequestError("A native build submission needs a valid store destination and version.");
19982
20432
  const submission = {
19983
20433
  destination: input.destination,
19984
20434
  version: input.version
19985
20435
  };
19986
20436
  return json$2({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
19987
20437
  }),
20438
+ markNativeBuild: onCore(async (core, request, params) => {
20439
+ const input = await body(request);
20440
+ if (!isRecord$5(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
20441
+ const mark = { storeBuild: input.storeBuild };
20442
+ return json$2({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
20443
+ }),
19988
20444
  deleteNativeBuild: onCore(async (core, _request, params) => json$2({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
20445
+ listIosDevices: onCore(async (core, request) => {
20446
+ const url = new URL(request.url);
20447
+ const input = keyset(url);
20448
+ const status = url.searchParams.get("status");
20449
+ return page(await refusingInvalid(() => core.listIosDevices({
20450
+ ...input,
20451
+ ...status === null ? {} : { status }
20452
+ })), input, ({ id }) => id);
20453
+ }),
20454
+ findIosDevice: onCore(async (core, _request, params) => json$2({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
20455
+ requestIosDevice: onCore(async (core, request) => {
20456
+ const input = await body(request);
20457
+ if (!isText$2(input.udid) || !isText$2(input.name) || !isTextOrNull$1(input.requestedBy)) throw new HandlerBadRequestError("An iOS device request needs udid, name, and requestedBy, an email or null.");
20458
+ const device = {
20459
+ udid: input.udid,
20460
+ name: input.name,
20461
+ requestedBy: input.requestedBy
20462
+ };
20463
+ return json$2({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
20464
+ }),
20465
+ approveIosDevice: onCore(async (core, request, params) => {
20466
+ const input = await body(request);
20467
+ if (!isTextOrNull$1(input.approvedBy) || input.name !== void 0 && !isText$2(input.name)) throw new HandlerBadRequestError("An iOS device approval needs approvedBy, an email or null, and an optional name.");
20468
+ const approval = {
20469
+ approvedBy: input.approvedBy,
20470
+ ...input.name === void 0 ? {} : { name: input.name }
20471
+ };
20472
+ return json$2({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
20473
+ }),
20474
+ renameIosDevice: onCore(async (core, request, params) => {
20475
+ const input = await body(request);
20476
+ if (!isText$2(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
20477
+ const name = input.name;
20478
+ return json$2({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
20479
+ }),
20480
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
20481
+ const input = await body(request);
20482
+ const seen = input.seen;
20483
+ if (!isRecord$5(seen) || typeof seen.status !== "string" || !(seen.approvedAtMs === null || Number.isSafeInteger(seen.approvedAtMs)) || !isText$2(input.issuerId) || typeof input.outcome !== "string" || input.reason !== void 0 && typeof input.reason !== "string") throw new HandlerBadRequestError("An iOS device outcome needs seen { status, approvedAtMs }, issuerId, outcome, and an optional reason.");
20484
+ const outcome = {
20485
+ id: requireRouteParam(params, "id"),
20486
+ seen: {
20487
+ status: seen.status,
20488
+ approvedAtMs: seen.approvedAtMs
20489
+ },
20490
+ issuerId: input.issuerId,
20491
+ outcome: input.outcome,
20492
+ ...input.reason === void 0 ? {} : { reason: input.reason }
20493
+ };
20494
+ return json$2({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
20495
+ }),
20496
+ claimIosDeviceAccount: onCore(async (core, request) => {
20497
+ const { issuerId } = await body(request);
20498
+ if (!isText$2(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
20499
+ return json$2({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
20500
+ }),
20501
+ markIosDevicesInBuild: onCore(async (core, request) => {
20502
+ const { buildId, ids } = await body(request);
20503
+ if (!isText$2(buildId) || !Array.isArray(ids) || !ids.every((id) => isText$2(id))) throw new HandlerBadRequestError("Marking iOS devices in a build needs buildId and ids.");
20504
+ await core.markIosDevicesInBuild({
20505
+ buildId,
20506
+ ids
20507
+ });
20508
+ return noContent();
20509
+ }),
20510
+ deleteIosDevice: onCore(async (core, request, params) => {
20511
+ const url = new URL(request.url);
20512
+ const status = url.searchParams.get("status");
20513
+ const requestedBy = url.searchParams.get("requestedBy");
20514
+ const only = {
20515
+ ...status === null ? {} : { status },
20516
+ ...requestedBy === null ? {} : { requestedBy }
20517
+ };
20518
+ return json$2({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
20519
+ }),
19989
20520
  deleteBundles: onCore(async (core, request) => {
19990
20521
  const { ids } = await body(request);
19991
20522
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -20129,10 +20660,60 @@ const ADMIN_ROUTES = [
20129
20660
  path: "/native-builds/:id/submission",
20130
20661
  handler: "recordNativeBuildSubmission"
20131
20662
  },
20663
+ {
20664
+ method: "POST",
20665
+ path: "/native-builds/:id/store-build",
20666
+ handler: "markNativeBuild"
20667
+ },
20132
20668
  {
20133
20669
  method: "DELETE",
20134
20670
  path: "/native-builds/:id",
20135
20671
  handler: "deleteNativeBuild"
20672
+ },
20673
+ {
20674
+ method: "GET",
20675
+ path: "/ios-devices",
20676
+ handler: "listIosDevices"
20677
+ },
20678
+ {
20679
+ method: "POST",
20680
+ path: "/ios-devices",
20681
+ handler: "requestIosDevice"
20682
+ },
20683
+ {
20684
+ method: "GET",
20685
+ path: "/ios-devices/udid/:udid",
20686
+ handler: "findIosDevice"
20687
+ },
20688
+ {
20689
+ method: "POST",
20690
+ path: "/ios-devices/in-build",
20691
+ handler: "markIosDevicesInBuild"
20692
+ },
20693
+ {
20694
+ method: "POST",
20695
+ path: "/ios-devices/account",
20696
+ handler: "claimIosDeviceAccount"
20697
+ },
20698
+ {
20699
+ method: "POST",
20700
+ path: "/ios-devices/:id/approval",
20701
+ handler: "approveIosDevice"
20702
+ },
20703
+ {
20704
+ method: "POST",
20705
+ path: "/ios-devices/:id/outcome",
20706
+ handler: "recordIosDeviceOutcome"
20707
+ },
20708
+ {
20709
+ method: "PATCH",
20710
+ path: "/ios-devices/:id",
20711
+ handler: "renameIosDevice"
20712
+ },
20713
+ {
20714
+ method: "DELETE",
20715
+ path: "/ios-devices/:id",
20716
+ handler: "deleteIosDevice"
20136
20717
  }
20137
20718
  ];
20138
20719
  //#endregion
@@ -53985,9 +54566,17 @@ const storeIdOf = (token) => {
53985
54566
  };
53986
54567
  const access = "private";
53987
54568
  const vercelBlobStorage = (config) => {
53988
- const { token } = config;
53989
- let store;
53990
- const storeId = () => store ??= storeIdOf(token);
54569
+ let resolved;
54570
+ const store = () => resolved ??= (async () => {
54571
+ const token = typeof config.token === "function" ? await config.token() : config.token;
54572
+ return {
54573
+ token,
54574
+ storeId: storeIdOf(token)
54575
+ };
54576
+ })().catch((error) => {
54577
+ resolved = void 0;
54578
+ throw error;
54579
+ });
53991
54580
  const normalizedBasePath = config.basePath?.replace(/^\/+|\/+$/g, "") ?? "";
53992
54581
  const getStorageKey = createStorageKeyBuilder(normalizedBasePath);
53993
54582
  const expiresIn = config.signedUrlExpiresIn ?? 3600;
@@ -53997,6 +54586,7 @@ const vercelBlobStorage = (config) => {
53997
54586
  const delegationUntil = async (validUntil) => {
53998
54587
  const current = await delegation?.catch(() => void 0);
53999
54588
  if (current !== void 0 && current.validUntil >= validUntil) return current;
54589
+ const { token } = await store();
54000
54590
  const issued = issueSignedToken({
54001
54591
  token,
54002
54592
  operations: ["get"],
@@ -54005,10 +54595,14 @@ const vercelBlobStorage = (config) => {
54005
54595
  delegation = issued;
54006
54596
  return issued;
54007
54597
  };
54008
- const parseAndValidate = (storageUri) => {
54598
+ const parseAndValidate = async (storageUri) => {
54009
54599
  const parsed = parseStorageUri(storageUri, PROTOCOL);
54010
- if (parsed.bucket !== storeId()) throw new Error(`Blob store mismatch: expected "${storeId()}", but found "${parsed.bucket}".`);
54011
- return parsed;
54600
+ const { token, storeId } = await store();
54601
+ if (parsed.bucket !== storeId) throw new Error(`Blob store mismatch: expected "${storeId}", but found "${parsed.bucket}".`);
54602
+ return {
54603
+ ...parsed,
54604
+ token
54605
+ };
54012
54606
  };
54013
54607
  const getListPrefix = (prefix = "") => {
54014
54608
  const value = [normalizedBasePath, prefix.replace(/^\/+|\/+$/g, "")].filter(Boolean).join("/");
@@ -54024,9 +54618,10 @@ const vercelBlobStorage = (config) => {
54024
54618
  protocol: PROTOCOL,
54025
54619
  async put({ key, body, contentLength, contentType }) {
54026
54620
  const storageKey = getStorageKey(key);
54621
+ const { token, storeId } = await store();
54027
54622
  const storageUri = createStorageUri({
54028
54623
  protocol: PROTOCOL,
54029
- bucket: storeId(),
54624
+ bucket: storeId,
54030
54625
  key: storageKey
54031
54626
  });
54032
54627
  await put(toPathname(storageKey), body, {
@@ -54041,7 +54636,7 @@ const vercelBlobStorage = (config) => {
54041
54636
  return { storageUri };
54042
54637
  },
54043
54638
  async get({ storageUri }) {
54044
- const { key } = parseAndValidate(storageUri);
54639
+ const { key, token } = await parseAndValidate(storageUri);
54045
54640
  const result = await get(toPathname(key), {
54046
54641
  access,
54047
54642
  token,
@@ -54055,7 +54650,7 @@ const vercelBlobStorage = (config) => {
54055
54650
  } }) };
54056
54651
  },
54057
54652
  async getDownloadUrl({ storageUri }) {
54058
- const { key } = parseAndValidate(storageUri);
54653
+ const { key } = await parseAndValidate(storageUri);
54059
54654
  const pathname = toPathname(key);
54060
54655
  const validUntil = Date.now() + expiresInMs;
54061
54656
  const { presignedUrl } = await presignUrl(await delegationUntil(validUntil), {
@@ -54067,7 +54662,7 @@ const vercelBlobStorage = (config) => {
54067
54662
  return { url: presignedUrl };
54068
54663
  },
54069
54664
  async exists({ storageUri }) {
54070
- const { key } = parseAndValidate(storageUri);
54665
+ const { key, token } = await parseAndValidate(storageUri);
54071
54666
  try {
54072
54667
  await head(toPathname(key), { token });
54073
54668
  return { exists: true };
@@ -54077,11 +54672,12 @@ const vercelBlobStorage = (config) => {
54077
54672
  }
54078
54673
  },
54079
54674
  async delete({ storageUri }) {
54080
- const { key } = parseAndValidate(storageUri);
54675
+ const { key, token } = await parseAndValidate(storageUri);
54081
54676
  await del(toPathname(key), { token });
54082
54677
  return { deleted: true };
54083
54678
  },
54084
54679
  async listObjects(prefix) {
54680
+ const { token, storeId } = await store();
54085
54681
  const objects = [];
54086
54682
  let cursor;
54087
54683
  do {
@@ -54098,7 +54694,7 @@ const vercelBlobStorage = (config) => {
54098
54694
  try {
54099
54695
  storageUri = createStorageUri({
54100
54696
  protocol: PROTOCOL,
54101
- bucket: storeId(),
54697
+ bucket: storeId,
54102
54698
  key
54103
54699
  });
54104
54700
  } catch {
@@ -54116,6 +54712,7 @@ const vercelBlobStorage = (config) => {
54116
54712
  return objects;
54117
54713
  },
54118
54714
  async deleteObjects(relativeKeys) {
54715
+ const { token } = await store();
54119
54716
  const pathnames = relativeKeys.map((key) => toPathname(getStorageKey(key)));
54120
54717
  for (let offset = 0; offset < pathnames.length; offset += DELETE_BATCH_SIZE) await del(pathnames.slice(offset, offset + DELETE_BATCH_SIZE), { token });
54121
54718
  }