@hot-updater/standalone 1.2.0-rc.6 → 1.2.0-rc.61

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.
package/dist/index.cjs CHANGED
@@ -12,11 +12,13 @@ var StandaloneDatabaseError = class extends Error {
12
12
  }
13
13
  };
14
14
  const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
15
+ /** `headers` with each lazy value resolved. */
16
+ const resolveHeaders = async (headers = {}) => Object.fromEntries(await Promise.all(Object.entries(headers).map(async ([name, value]) => [name, await (0, _hot_updater_plugin_core.resolveLazy)(value)])));
15
17
  const createStandaloneHttp = (config) => {
16
18
  const buildUrl = (path) => `${config.baseUrl.replace(/\/+$/, "")}${path}`;
17
- const headers = (routeHeaders) => ({
19
+ const headers = async (routeHeaders) => ({
18
20
  "Content-Type": "application/json",
19
- ...config.commonHeaders,
21
+ ...await resolveHeaders(config.commonHeaders),
20
22
  ...routeHeaders
21
23
  });
22
24
  const requestFailed = async (response) => {
@@ -59,6 +61,7 @@ const MANAGEMENT_CODES = /* @__PURE__ */ new Set([
59
61
  const CATALOG_CODES = /* @__PURE__ */ new Set([
60
62
  "CATALOG_GENERATION_EXHAUSTED",
61
63
  "CATALOG_IDENTITY_MISSING",
64
+ "CATALOG_FROM_LATER_RELEASE",
62
65
  "INVALID_SCOPE",
63
66
  "NON_MONOTONIC_RELEASE_ID"
64
67
  ]);
@@ -68,21 +71,31 @@ const refusal = (status, value, fallback) => {
68
71
  const message = isRecord(value) && typeof value.error === "string" ? value.error : fallback;
69
72
  if (typeof code === "string" && MANAGEMENT_CODES.has(code)) return new _hot_updater_plugin_core.ReleaseManagementError(code, message);
70
73
  if (typeof code === "string" && CATALOG_CODES.has(code)) return new _hot_updater_plugin_core.ReleaseCatalogMutationError(code, message);
74
+ if (code === "CATALOG_OVERSIZE") return new _hot_updater_plugin_core.ReleaseCatalogCompilationError(code, message);
71
75
  if (code === "BUNDLE_NOT_FOUND" && isRecord(value)) {
72
76
  const id = /"([^"]+)"/u.exec(message)?.[1] ?? "";
73
77
  return new _hot_updater_plugin_core.DatabaseBundleNotFoundError(id);
74
78
  }
75
79
  return new StandaloneDatabaseError("request-failed", message, status);
76
80
  };
77
- const nativeBuildScopeParams = ({ platform, channel, fingerprintHash, appVersion }) => ({
81
+ const nativeBuildScopeParams = ({ platform, channel, fingerprintHash, appVersion, sandbox }) => ({
78
82
  platform,
79
83
  channel,
80
- ...fingerprintHash === null ? { appVersion } : { fingerprintHash }
84
+ ...fingerprintHash === null ? { appVersion } : { fingerprintHash },
85
+ ...sandbox === void 0 || sandbox === null ? {} : {
86
+ sandboxAppId: sandbox.appId,
87
+ sandboxUrlScheme: sandbox.urlScheme,
88
+ artifactKind: sandbox.artifactKind,
89
+ distribution: sandbox.distribution
90
+ }
81
91
  });
82
- const keysetParams = ({ order, after, limit }) => ({
92
+ /** The most IDs the admin API takes in one request. */
93
+ const MAX_IDS = 100;
94
+ const keysetParams = ({ order, after, through, limit }) => ({
83
95
  limit: String(limit),
84
96
  ...order === void 0 ? {} : { order },
85
- ...after === void 0 ? {} : { cursor: after }
97
+ ...after === void 0 ? {} : { cursor: after },
98
+ ...through === void 0 ? {} : { through }
86
99
  });
87
100
  const filterParams = (filter) => {
88
101
  switch (filter.kind) {
@@ -108,7 +121,7 @@ const createStandaloneCoreApi = (config) => {
108
121
  const http = createStandaloneHttp(config);
109
122
  let checked;
110
123
  const checkProtocol = async () => {
111
- const response = await fetch(http.buildUrl("/version"), { headers: http.headers({ "Cache-Control": "no-cache" }) });
124
+ const response = await fetch(http.buildUrl("/version"), { headers: await http.headers({ "Cache-Control": "no-cache" }) });
112
125
  const body = response.status === 404 ? {} : await http.parseJson(response);
113
126
  const protocol = isRecord(body) ? body.adminProtocol : void 0;
114
127
  if (typeof protocol !== "number" || protocol < 2) throw new StandaloneDatabaseError("request-failed", `The server at ${config.baseUrl} does not report Hot Updater admin API protocol 2 at /version. Set baseUrl to the path where the server mounts handlers.admin, such as https://example.com/hot-updater/admin.`, response.status);
@@ -125,7 +138,7 @@ const createStandaloneCoreApi = (config) => {
125
138
  for (const [key, value] of Object.entries(query)) url.searchParams.set(key, value);
126
139
  const response = await fetch(url, {
127
140
  method,
128
- headers: http.headers(method === "GET" ? { "Cache-Control": "no-cache" } : void 0),
141
+ headers: await http.headers(method === "GET" ? { "Cache-Control": "no-cache" } : void 0),
129
142
  ...body === void 0 ? {} : { body: JSON.stringify(body) }
130
143
  });
131
144
  if (response.status === 204) return null;
@@ -174,26 +187,71 @@ const createStandaloneCoreApi = (config) => {
174
187
  limit: String(limit)
175
188
  }),
176
189
  getRelease: (id) => call("GET", `/releases/${encode(id)}`),
190
+ getReleaseByLabel: ({ channel, platform, label }) => call("GET", "/release-labels", {
191
+ query: {
192
+ channel,
193
+ platform,
194
+ label: String(label)
195
+ },
196
+ requiredRoute: "release label"
197
+ }),
177
198
  listReleases: ({ filter, ...input }) => list("/releases", {
178
199
  ...keysetParams(input),
179
200
  ...filterParams(filter)
180
201
  }),
181
202
  getReleaseCatalogRow: (scopeKey) => call("GET", `/release-catalogs/${encode(scopeKey)}`),
182
203
  listReleaseCatalogs: (input) => list("/release-catalogs", keysetParams(input)),
183
- listChannels: () => list("/channels", {}),
204
+ listReleaseScopeKeys: async ({ after, limit }) => await call("GET", "/release-scopes", {
205
+ query: {
206
+ limit: String(limit),
207
+ ...after === void 0 ? {} : { cursor: after }
208
+ },
209
+ requiredRoute: "release scope"
210
+ }) ?? [],
211
+ listChannels: async (input) => {
212
+ if (input === void 0) return list("/channels", {});
213
+ const rows = await list("/channels", keysetParams(input));
214
+ const desc = input.order === "desc";
215
+ const { after, through } = input;
216
+ const past = (name, bound) => desc ? (0, _hot_updater_plugin_core.compareUtf8)(name, bound) < 0 : (0, _hot_updater_plugin_core.compareUtf8)(name, bound) > 0;
217
+ return rows.filter(({ name }) => (after === void 0 || past(name, after)) && (through === void 0 || !past(name, through))).sort((left, right) => desc ? (0, _hot_updater_plugin_core.compareUtf8)(right.name, left.name) : (0, _hot_updater_plugin_core.compareUtf8)(left.name, right.name)).slice(0, input.limit);
218
+ },
219
+ getChannels: async (ids) => {
220
+ const unique = [...new Set(ids)];
221
+ const found = /* @__PURE__ */ new Map();
222
+ for (let start = 0; start < unique.length; start += MAX_IDS) {
223
+ const chunk = unique.slice(start, start + MAX_IDS);
224
+ const asked = new Set(chunk);
225
+ for (const row of await list("/channels", { ids: chunk.join(",") })) if (asked.has(row.id)) found.set(row.id, row);
226
+ }
227
+ return unique.flatMap((id) => {
228
+ const row = found.get(id);
229
+ return row === void 0 ? [] : [row];
230
+ });
231
+ },
184
232
  findChannelByName: (name) => call("GET", "/channels", { query: { name } }),
185
233
  getNativeBuild: (id) => call("GET", `/native-builds/${encode(id)}`, { requiredRoute: "native build" }),
234
+ findNativeBuildByBuiltInBundle: (bundleId) => call("GET", `/native-builds/built-in/${encode(bundleId)}`, { requiredRoute: "native build" }),
186
235
  findNativeBuild: async (scope, options) => {
187
236
  const buildKey = options?.buildKey;
188
237
  const row = await call("GET", "/native-builds/latest", {
189
238
  query: {
190
239
  ...nativeBuildScopeParams(scope),
191
- ...buildKey === void 0 ? {} : { buildKey }
240
+ ...buildKey === void 0 ? {} : { buildKey },
241
+ ...options?.storeBuild ? { storeBuild: "true" } : {},
242
+ ...options?.builtInOlderThan === void 0 ? {} : { builtInOlderThan: options.builtInOlderThan },
243
+ ...options?.artifactKind === void 0 ? {} : { kind: options.artifactKind }
192
244
  },
193
245
  requiredRoute: "native build"
194
246
  });
195
- return buildKey !== void 0 && row?.build_key !== buildKey ? null : row;
247
+ if (buildKey !== void 0 && row?.build_key !== buildKey) return null;
248
+ if (options?.artifactKind !== void 0 && row !== null && row.artifact_kind !== options.artifactKind) return null;
249
+ if (options?.storeBuild && row?.is_store_build !== true) return null;
250
+ const sandbox = scope.sandbox;
251
+ if (sandbox && row !== null && (row.is_sandbox !== true || row.artifact_kind !== sandbox.artifactKind || row.sandbox_url_scheme !== sandbox.urlScheme)) return null;
252
+ return row;
196
253
  },
254
+ findNativeBuildSibling: (build) => call("GET", `/native-builds/${encode(build.id)}/sibling`),
197
255
  listNativeBuilds: ({ channelId, ...input }) => list("/native-builds", {
198
256
  ...keysetParams(input),
199
257
  ...channelId === void 0 ? {} : { channelId }
@@ -207,6 +265,10 @@ const createStandaloneCoreApi = (config) => {
207
265
  } }),
208
266
  promoteRelease: async ({ releaseId, ...input }) => await call("POST", `/releases/${encode(releaseId)}/promote`, { body: input }),
209
267
  rebuildReleaseCatalog: async (scopeKey) => await call("POST", `/release-catalogs/${encode(scopeKey)}/rebuild`),
268
+ fillReleaseLabels: async (input = {}) => await call("POST", "/release-labels/fill", {
269
+ body: input,
270
+ requiredRoute: "release label"
271
+ }),
210
272
  preflightReleaseCatalogRebuild: async (scopeKey) => await call("POST", `/release-catalogs/${encode(scopeKey)}/preflight`),
211
273
  ensureChannel: async (name) => await call("POST", "/channels", { body: { name } }),
212
274
  deleteChannel: async (id) => {
@@ -236,6 +298,59 @@ const createStandaloneCoreApi = (config) => {
236
298
  body: submission,
237
299
  requiredRoute: "native build submission"
238
300
  }),
301
+ markNativeBuild: (id, mark) => call("POST", `/native-builds/${encode(id)}/store-build`, {
302
+ body: mark,
303
+ requiredRoute: "native build store mark"
304
+ }),
305
+ listIosDevices: async ({ status, ...input }) => await call("GET", "/ios-devices", {
306
+ query: {
307
+ ...keysetParams(input),
308
+ ...status === void 0 ? {} : { status }
309
+ },
310
+ requiredRoute: "iOS device registry"
311
+ }) ?? [],
312
+ findIosDevice: (udid) => call("GET", `/ios-devices/udid/${encode(udid)}`, { requiredRoute: "iOS device registry" }),
313
+ requestIosDevice: async (input) => await call("POST", "/ios-devices", {
314
+ body: input,
315
+ requiredRoute: "iOS device registry"
316
+ }),
317
+ approveIosDevice: (id, input) => call("POST", `/ios-devices/${encode(id)}/approval`, {
318
+ body: input,
319
+ requiredRoute: "iOS device registry"
320
+ }),
321
+ renameIosDevice: (id, name) => call("PATCH", `/ios-devices/${encode(id)}`, {
322
+ body: { name },
323
+ requiredRoute: "iOS device registry"
324
+ }),
325
+ recordIosDeviceOutcome: ({ id, ...input }) => call("POST", `/ios-devices/${encode(id)}/outcome`, {
326
+ body: input,
327
+ requiredRoute: "iOS device registry"
328
+ }),
329
+ markIosDevicesInBuild: async ({ buildId, ids }) => {
330
+ let start = 0;
331
+ do {
332
+ await request("POST", "/ios-devices/in-build", {
333
+ body: {
334
+ buildId,
335
+ ids: ids.slice(start, start + MAX_IDS)
336
+ },
337
+ requiredRoute: "iOS device registry"
338
+ });
339
+ start += MAX_IDS;
340
+ } while (start < ids.length);
341
+ },
342
+ findIosDeviceAccount: () => call("GET", "/ios-devices/account", { requiredRoute: "iOS device registry" }),
343
+ claimIosDeviceAccount: async (issuerId) => await call("POST", "/ios-devices/account", {
344
+ body: { issuerId },
345
+ requiredRoute: "iOS device registry"
346
+ }),
347
+ deleteIosDevice: (id, only) => call("DELETE", `/ios-devices/${encode(id)}`, {
348
+ query: {
349
+ ...only?.status === void 0 ? {} : { status: only.status },
350
+ ...only?.requestedBy === void 0 ? {} : { requestedBy: only.requestedBy }
351
+ },
352
+ requiredRoute: "iOS device registry"
353
+ }),
239
354
  deleteNativeBuild: async (id) => await call("DELETE", `/native-builds/${encode(id)}`, { requiredRoute: "native build deletion" })
240
355
  };
241
356
  };
@@ -252,8 +367,8 @@ const standaloneRepository = (config) => {
252
367
  return Object.freeze({
253
368
  name: "standalone-repository",
254
369
  core: createStandaloneCoreApi(config),
255
- fetchAdmin: (path, init = {}) => {
256
- const headers = new Headers(http.headers({ "Cache-Control": "no-cache" }));
370
+ fetchAdmin: async (path, init = {}) => {
371
+ const headers = new Headers(await http.headers({ "Cache-Control": "no-cache" }));
257
372
  new Headers(init.headers).forEach((value, name) => {
258
373
  headers.set(name, value);
259
374
  });
@@ -270,8 +385,12 @@ const defaultRoutes = {
270
385
  put: () => ({ path: "/upload" }),
271
386
  get: () => ({ path: "/get" }),
272
387
  exists: () => ({ path: "/exists" }),
273
- delete: () => ({ path: "/delete" })
388
+ delete: () => ({ path: "/delete" }),
389
+ listObjects: () => ({ path: "/list" }),
390
+ deleteObjects: () => ({ path: "/delete-objects" })
274
391
  };
392
+ /** Keys sent in one `deleteObjects` request. */
393
+ const DELETE_BATCH_SIZE = 1e3;
275
394
  const createRoute = (defaultRoute, customRoute) => ({
276
395
  path: customRoute?.path ?? defaultRoute.path,
277
396
  headers: {
@@ -280,8 +399,8 @@ const createRoute = (defaultRoute, customRoute) => ({
280
399
  }
281
400
  });
282
401
  const standaloneStorage = (config) => {
283
- const getHeaders = (routeHeaders) => ({
284
- ...config.commonHeaders,
402
+ const getHeaders = async (routeHeaders) => ({
403
+ ...await resolveHeaders(config.commonHeaders),
285
404
  ...routeHeaders
286
405
  });
287
406
  const resolveRoute = (name, args) => {
@@ -289,6 +408,14 @@ const standaloneStorage = (config) => {
289
408
  const custom = config.routes?.[name];
290
409
  return createRoute(fallback(...args), custom?.(...args));
291
410
  };
411
+ const postJson = async (path, headers, body) => fetch(`${config.baseUrl}${path}`, {
412
+ method: "POST",
413
+ headers: {
414
+ "content-type": "application/json",
415
+ ...await getHeaders(headers)
416
+ },
417
+ body: JSON.stringify(body)
418
+ });
292
419
  const requestStorageUri = async (routeName, storageUri) => {
293
420
  (0, _hot_updater_plugin_core.parseStorageUri)(storageUri, config.protocol);
294
421
  const { path, headers } = resolveRoute(routeName, [{ storageUri }]);
@@ -296,7 +423,7 @@ const standaloneStorage = (config) => {
296
423
  method: routeName === "delete" ? "DELETE" : "POST",
297
424
  headers: {
298
425
  "content-type": "application/json",
299
- ...getHeaders(headers)
426
+ ...await getHeaders(headers)
300
427
  },
301
428
  body: JSON.stringify({ storageUri })
302
429
  });
@@ -319,7 +446,7 @@ const standaloneStorage = (config) => {
319
446
  formData.append("key", key);
320
447
  const response = await fetch(`${config.baseUrl}${path}`, {
321
448
  method: "POST",
322
- headers: getHeaders(headers),
449
+ headers: await getHeaders(headers),
323
450
  body: formData
324
451
  });
325
452
  if (!response.ok) throw new Error(`Failed to upload bundle: ${response.statusText}`);
@@ -340,6 +467,39 @@ const standaloneStorage = (config) => {
340
467
  async delete({ storageUri }) {
341
468
  await requestStorageUri("delete", storageUri);
342
469
  return { deleted: true };
470
+ },
471
+ async listObjects(prefix) {
472
+ const { path, headers } = resolveRoute("listObjects", [{ prefix }]);
473
+ const objects = [];
474
+ let cursor;
475
+ do {
476
+ const response = await postJson(path, headers, {
477
+ prefix,
478
+ cursor
479
+ });
480
+ if (response.status === 404) throw new Error(`The storage service has no ${path} route, which storage prune needs.`);
481
+ if (!response.ok) throw new Error(`Failed to list storage objects: ${response.statusText}`);
482
+ const page = await response.json();
483
+ for (const object of page.objects) {
484
+ (0, _hot_updater_plugin_core.parseStorageUri)(object.storageUri, config.protocol);
485
+ objects.push({
486
+ key: object.key,
487
+ storageUri: object.storageUri,
488
+ size: object.size,
489
+ ...object.lastModifiedAt === void 0 ? {} : { lastModifiedAt: new Date(object.lastModifiedAt) }
490
+ });
491
+ }
492
+ cursor = page.cursor;
493
+ } while (cursor !== void 0);
494
+ return objects;
495
+ },
496
+ async deleteObjects(keys) {
497
+ for (let offset = 0; offset < keys.length; offset += DELETE_BATCH_SIZE) {
498
+ const batch = keys.slice(offset, offset + DELETE_BATCH_SIZE);
499
+ const { path, headers } = resolveRoute("deleteObjects", [{ keys: batch }]);
500
+ const response = await postJson(path, headers, { keys: batch });
501
+ if (!response.ok) throw new Error(`Failed to delete storage objects: ${response.statusText}`);
502
+ }
343
503
  }
344
504
  });
345
505
  };
package/dist/index.d.cts CHANGED
@@ -1,10 +1,14 @@
1
- import { HotUpdaterCoreApi, RemoteDatabase, StorageDeleteInput, StorageExistsInput, StorageGetInput, StoragePutInput } from "@hot-updater/plugin-core";
1
+ import { HotUpdaterCoreApi, Lazy, RemoteDatabase, StorageDeleteInput, StorageExistsInput, StorageGetInput, StorageObject, StoragePutInput } from "@hot-updater/plugin-core";
2
2
  //#region src/standaloneRoutes.d.ts
3
3
  interface StandaloneRepositoryConfig {
4
4
  /** Base URL of the Hot Updater admin handler. */
5
5
  readonly baseUrl: string;
6
- /** Headers sent with every admin request, such as its authorization. */
7
- readonly commonHeaders?: Readonly<Record<string, string>>;
6
+ /**
7
+ * Headers sent with every admin request, such as its authorization. A
8
+ * value may be a function that returns it, such as `secret("<name>")` in
9
+ * `hot-updater.config.ts`, called on the first request.
10
+ */
11
+ readonly commonHeaders?: Readonly<Record<string, Lazy<string>>>;
8
12
  }
9
13
  //#endregion
10
14
  //#region src/standaloneCore.d.ts
@@ -48,12 +52,25 @@ interface StorageRoutes {
48
52
  get: (input: StorageGetInput) => RouteConfig;
49
53
  exists: (input: StorageExistsInput) => RouteConfig;
50
54
  delete: (input: StorageDeleteInput) => RouteConfig;
55
+ /** Lists objects for `hot-updater storage prune`. */
56
+ listObjects: (input: {
57
+ readonly prefix?: string;
58
+ }) => RouteConfig;
59
+ /** Deletes exact keys for `hot-updater storage prune --yes`. */
60
+ deleteObjects: (input: {
61
+ readonly keys: readonly string[];
62
+ }) => RouteConfig;
51
63
  }
52
64
  interface StandaloneStorageConfig {
53
65
  baseUrl: string;
54
66
  /** Storage URI protocol owned by the remote implementation. */
55
67
  protocol: string;
56
- commonHeaders?: Record<string, string>;
68
+ /**
69
+ * Headers sent with every request. A value may be a function that returns
70
+ * it, such as `secret("<name>")` in `hot-updater.config.ts`, called on
71
+ * the first request.
72
+ */
73
+ commonHeaders?: Record<string, Lazy<string>>;
57
74
  routes?: Partial<StorageRoutes>;
58
75
  }
59
76
  declare const standaloneStorage: (config: StandaloneStorageConfig) => {
@@ -71,6 +88,8 @@ declare const standaloneStorage: (config: StandaloneStorageConfig) => {
71
88
  readonly delete: ({ storageUri }: StorageDeleteInput) => Promise<{
72
89
  deleted: true;
73
90
  }>;
91
+ readonly listObjects: (prefix?: string) => Promise<StorageObject[]>;
92
+ readonly deleteObjects: (keys: readonly string[]) => Promise<void>;
74
93
  };
75
94
  //#endregion
76
95
  export { RouteConfig, STANDALONE_ADMIN_PROTOCOL, StandaloneDatabaseError, StandaloneRepository, type StandaloneRepositoryConfig, StandaloneStorageConfig, StorageRoutes, createStandaloneCoreApi, standaloneRepository, standaloneStorage };
package/dist/index.d.mts CHANGED
@@ -1,10 +1,14 @@
1
- import { HotUpdaterCoreApi, RemoteDatabase, StorageDeleteInput, StorageExistsInput, StorageGetInput, StoragePutInput } from "@hot-updater/plugin-core";
1
+ import { HotUpdaterCoreApi, Lazy, RemoteDatabase, StorageDeleteInput, StorageExistsInput, StorageGetInput, StorageObject, StoragePutInput } from "@hot-updater/plugin-core";
2
2
  //#region src/standaloneRoutes.d.ts
3
3
  interface StandaloneRepositoryConfig {
4
4
  /** Base URL of the Hot Updater admin handler. */
5
5
  readonly baseUrl: string;
6
- /** Headers sent with every admin request, such as its authorization. */
7
- readonly commonHeaders?: Readonly<Record<string, string>>;
6
+ /**
7
+ * Headers sent with every admin request, such as its authorization. A
8
+ * value may be a function that returns it, such as `secret("<name>")` in
9
+ * `hot-updater.config.ts`, called on the first request.
10
+ */
11
+ readonly commonHeaders?: Readonly<Record<string, Lazy<string>>>;
8
12
  }
9
13
  //#endregion
10
14
  //#region src/standaloneCore.d.ts
@@ -48,12 +52,25 @@ interface StorageRoutes {
48
52
  get: (input: StorageGetInput) => RouteConfig;
49
53
  exists: (input: StorageExistsInput) => RouteConfig;
50
54
  delete: (input: StorageDeleteInput) => RouteConfig;
55
+ /** Lists objects for `hot-updater storage prune`. */
56
+ listObjects: (input: {
57
+ readonly prefix?: string;
58
+ }) => RouteConfig;
59
+ /** Deletes exact keys for `hot-updater storage prune --yes`. */
60
+ deleteObjects: (input: {
61
+ readonly keys: readonly string[];
62
+ }) => RouteConfig;
51
63
  }
52
64
  interface StandaloneStorageConfig {
53
65
  baseUrl: string;
54
66
  /** Storage URI protocol owned by the remote implementation. */
55
67
  protocol: string;
56
- commonHeaders?: Record<string, string>;
68
+ /**
69
+ * Headers sent with every request. A value may be a function that returns
70
+ * it, such as `secret("<name>")` in `hot-updater.config.ts`, called on
71
+ * the first request.
72
+ */
73
+ commonHeaders?: Record<string, Lazy<string>>;
57
74
  routes?: Partial<StorageRoutes>;
58
75
  }
59
76
  declare const standaloneStorage: (config: StandaloneStorageConfig) => {
@@ -71,6 +88,8 @@ declare const standaloneStorage: (config: StandaloneStorageConfig) => {
71
88
  readonly delete: ({ storageUri }: StorageDeleteInput) => Promise<{
72
89
  deleted: true;
73
90
  }>;
91
+ readonly listObjects: (prefix?: string) => Promise<StorageObject[]>;
92
+ readonly deleteObjects: (keys: readonly string[]) => Promise<void>;
74
93
  };
75
94
  //#endregion
76
95
  export { RouteConfig, STANDALONE_ADMIN_PROTOCOL, StandaloneDatabaseError, StandaloneRepository, type StandaloneRepositoryConfig, StandaloneStorageConfig, StorageRoutes, createStandaloneCoreApi, standaloneRepository, standaloneStorage };
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { DatabaseBundleNotFoundError, ReleaseCatalogMutationError, ReleaseManagementError, createStorageAdapter, parseStorageUri } from "@hot-updater/plugin-core";
1
+ import { DatabaseBundleNotFoundError, ReleaseCatalogCompilationError, ReleaseCatalogMutationError, ReleaseManagementError, compareUtf8, createStorageAdapter, parseStorageUri, resolveLazy } from "@hot-updater/plugin-core";
2
2
  //#region src/standaloneHttp.ts
3
3
  var StandaloneDatabaseError = class extends Error {
4
4
  code;
@@ -11,11 +11,13 @@ var StandaloneDatabaseError = class extends Error {
11
11
  }
12
12
  };
13
13
  const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
14
+ /** `headers` with each lazy value resolved. */
15
+ const resolveHeaders = async (headers = {}) => Object.fromEntries(await Promise.all(Object.entries(headers).map(async ([name, value]) => [name, await resolveLazy(value)])));
14
16
  const createStandaloneHttp = (config) => {
15
17
  const buildUrl = (path) => `${config.baseUrl.replace(/\/+$/, "")}${path}`;
16
- const headers = (routeHeaders) => ({
18
+ const headers = async (routeHeaders) => ({
17
19
  "Content-Type": "application/json",
18
- ...config.commonHeaders,
20
+ ...await resolveHeaders(config.commonHeaders),
19
21
  ...routeHeaders
20
22
  });
21
23
  const requestFailed = async (response) => {
@@ -58,6 +60,7 @@ const MANAGEMENT_CODES = /* @__PURE__ */ new Set([
58
60
  const CATALOG_CODES = /* @__PURE__ */ new Set([
59
61
  "CATALOG_GENERATION_EXHAUSTED",
60
62
  "CATALOG_IDENTITY_MISSING",
63
+ "CATALOG_FROM_LATER_RELEASE",
61
64
  "INVALID_SCOPE",
62
65
  "NON_MONOTONIC_RELEASE_ID"
63
66
  ]);
@@ -67,21 +70,31 @@ const refusal = (status, value, fallback) => {
67
70
  const message = isRecord(value) && typeof value.error === "string" ? value.error : fallback;
68
71
  if (typeof code === "string" && MANAGEMENT_CODES.has(code)) return new ReleaseManagementError(code, message);
69
72
  if (typeof code === "string" && CATALOG_CODES.has(code)) return new ReleaseCatalogMutationError(code, message);
73
+ if (code === "CATALOG_OVERSIZE") return new ReleaseCatalogCompilationError(code, message);
70
74
  if (code === "BUNDLE_NOT_FOUND" && isRecord(value)) {
71
75
  const id = /"([^"]+)"/u.exec(message)?.[1] ?? "";
72
76
  return new DatabaseBundleNotFoundError(id);
73
77
  }
74
78
  return new StandaloneDatabaseError("request-failed", message, status);
75
79
  };
76
- const nativeBuildScopeParams = ({ platform, channel, fingerprintHash, appVersion }) => ({
80
+ const nativeBuildScopeParams = ({ platform, channel, fingerprintHash, appVersion, sandbox }) => ({
77
81
  platform,
78
82
  channel,
79
- ...fingerprintHash === null ? { appVersion } : { fingerprintHash }
83
+ ...fingerprintHash === null ? { appVersion } : { fingerprintHash },
84
+ ...sandbox === void 0 || sandbox === null ? {} : {
85
+ sandboxAppId: sandbox.appId,
86
+ sandboxUrlScheme: sandbox.urlScheme,
87
+ artifactKind: sandbox.artifactKind,
88
+ distribution: sandbox.distribution
89
+ }
80
90
  });
81
- const keysetParams = ({ order, after, limit }) => ({
91
+ /** The most IDs the admin API takes in one request. */
92
+ const MAX_IDS = 100;
93
+ const keysetParams = ({ order, after, through, limit }) => ({
82
94
  limit: String(limit),
83
95
  ...order === void 0 ? {} : { order },
84
- ...after === void 0 ? {} : { cursor: after }
96
+ ...after === void 0 ? {} : { cursor: after },
97
+ ...through === void 0 ? {} : { through }
85
98
  });
86
99
  const filterParams = (filter) => {
87
100
  switch (filter.kind) {
@@ -107,7 +120,7 @@ const createStandaloneCoreApi = (config) => {
107
120
  const http = createStandaloneHttp(config);
108
121
  let checked;
109
122
  const checkProtocol = async () => {
110
- const response = await fetch(http.buildUrl("/version"), { headers: http.headers({ "Cache-Control": "no-cache" }) });
123
+ const response = await fetch(http.buildUrl("/version"), { headers: await http.headers({ "Cache-Control": "no-cache" }) });
111
124
  const body = response.status === 404 ? {} : await http.parseJson(response);
112
125
  const protocol = isRecord(body) ? body.adminProtocol : void 0;
113
126
  if (typeof protocol !== "number" || protocol < 2) throw new StandaloneDatabaseError("request-failed", `The server at ${config.baseUrl} does not report Hot Updater admin API protocol 2 at /version. Set baseUrl to the path where the server mounts handlers.admin, such as https://example.com/hot-updater/admin.`, response.status);
@@ -124,7 +137,7 @@ const createStandaloneCoreApi = (config) => {
124
137
  for (const [key, value] of Object.entries(query)) url.searchParams.set(key, value);
125
138
  const response = await fetch(url, {
126
139
  method,
127
- headers: http.headers(method === "GET" ? { "Cache-Control": "no-cache" } : void 0),
140
+ headers: await http.headers(method === "GET" ? { "Cache-Control": "no-cache" } : void 0),
128
141
  ...body === void 0 ? {} : { body: JSON.stringify(body) }
129
142
  });
130
143
  if (response.status === 204) return null;
@@ -173,26 +186,71 @@ const createStandaloneCoreApi = (config) => {
173
186
  limit: String(limit)
174
187
  }),
175
188
  getRelease: (id) => call("GET", `/releases/${encode(id)}`),
189
+ getReleaseByLabel: ({ channel, platform, label }) => call("GET", "/release-labels", {
190
+ query: {
191
+ channel,
192
+ platform,
193
+ label: String(label)
194
+ },
195
+ requiredRoute: "release label"
196
+ }),
176
197
  listReleases: ({ filter, ...input }) => list("/releases", {
177
198
  ...keysetParams(input),
178
199
  ...filterParams(filter)
179
200
  }),
180
201
  getReleaseCatalogRow: (scopeKey) => call("GET", `/release-catalogs/${encode(scopeKey)}`),
181
202
  listReleaseCatalogs: (input) => list("/release-catalogs", keysetParams(input)),
182
- listChannels: () => list("/channels", {}),
203
+ listReleaseScopeKeys: async ({ after, limit }) => await call("GET", "/release-scopes", {
204
+ query: {
205
+ limit: String(limit),
206
+ ...after === void 0 ? {} : { cursor: after }
207
+ },
208
+ requiredRoute: "release scope"
209
+ }) ?? [],
210
+ listChannels: async (input) => {
211
+ if (input === void 0) return list("/channels", {});
212
+ const rows = await list("/channels", keysetParams(input));
213
+ const desc = input.order === "desc";
214
+ const { after, through } = input;
215
+ const past = (name, bound) => desc ? compareUtf8(name, bound) < 0 : compareUtf8(name, bound) > 0;
216
+ return rows.filter(({ name }) => (after === void 0 || past(name, after)) && (through === void 0 || !past(name, through))).sort((left, right) => desc ? compareUtf8(right.name, left.name) : compareUtf8(left.name, right.name)).slice(0, input.limit);
217
+ },
218
+ getChannels: async (ids) => {
219
+ const unique = [...new Set(ids)];
220
+ const found = /* @__PURE__ */ new Map();
221
+ for (let start = 0; start < unique.length; start += MAX_IDS) {
222
+ const chunk = unique.slice(start, start + MAX_IDS);
223
+ const asked = new Set(chunk);
224
+ for (const row of await list("/channels", { ids: chunk.join(",") })) if (asked.has(row.id)) found.set(row.id, row);
225
+ }
226
+ return unique.flatMap((id) => {
227
+ const row = found.get(id);
228
+ return row === void 0 ? [] : [row];
229
+ });
230
+ },
183
231
  findChannelByName: (name) => call("GET", "/channels", { query: { name } }),
184
232
  getNativeBuild: (id) => call("GET", `/native-builds/${encode(id)}`, { requiredRoute: "native build" }),
233
+ findNativeBuildByBuiltInBundle: (bundleId) => call("GET", `/native-builds/built-in/${encode(bundleId)}`, { requiredRoute: "native build" }),
185
234
  findNativeBuild: async (scope, options) => {
186
235
  const buildKey = options?.buildKey;
187
236
  const row = await call("GET", "/native-builds/latest", {
188
237
  query: {
189
238
  ...nativeBuildScopeParams(scope),
190
- ...buildKey === void 0 ? {} : { buildKey }
239
+ ...buildKey === void 0 ? {} : { buildKey },
240
+ ...options?.storeBuild ? { storeBuild: "true" } : {},
241
+ ...options?.builtInOlderThan === void 0 ? {} : { builtInOlderThan: options.builtInOlderThan },
242
+ ...options?.artifactKind === void 0 ? {} : { kind: options.artifactKind }
191
243
  },
192
244
  requiredRoute: "native build"
193
245
  });
194
- return buildKey !== void 0 && row?.build_key !== buildKey ? null : row;
246
+ if (buildKey !== void 0 && row?.build_key !== buildKey) return null;
247
+ if (options?.artifactKind !== void 0 && row !== null && row.artifact_kind !== options.artifactKind) return null;
248
+ if (options?.storeBuild && row?.is_store_build !== true) return null;
249
+ const sandbox = scope.sandbox;
250
+ if (sandbox && row !== null && (row.is_sandbox !== true || row.artifact_kind !== sandbox.artifactKind || row.sandbox_url_scheme !== sandbox.urlScheme)) return null;
251
+ return row;
195
252
  },
253
+ findNativeBuildSibling: (build) => call("GET", `/native-builds/${encode(build.id)}/sibling`),
196
254
  listNativeBuilds: ({ channelId, ...input }) => list("/native-builds", {
197
255
  ...keysetParams(input),
198
256
  ...channelId === void 0 ? {} : { channelId }
@@ -206,6 +264,10 @@ const createStandaloneCoreApi = (config) => {
206
264
  } }),
207
265
  promoteRelease: async ({ releaseId, ...input }) => await call("POST", `/releases/${encode(releaseId)}/promote`, { body: input }),
208
266
  rebuildReleaseCatalog: async (scopeKey) => await call("POST", `/release-catalogs/${encode(scopeKey)}/rebuild`),
267
+ fillReleaseLabels: async (input = {}) => await call("POST", "/release-labels/fill", {
268
+ body: input,
269
+ requiredRoute: "release label"
270
+ }),
209
271
  preflightReleaseCatalogRebuild: async (scopeKey) => await call("POST", `/release-catalogs/${encode(scopeKey)}/preflight`),
210
272
  ensureChannel: async (name) => await call("POST", "/channels", { body: { name } }),
211
273
  deleteChannel: async (id) => {
@@ -235,6 +297,59 @@ const createStandaloneCoreApi = (config) => {
235
297
  body: submission,
236
298
  requiredRoute: "native build submission"
237
299
  }),
300
+ markNativeBuild: (id, mark) => call("POST", `/native-builds/${encode(id)}/store-build`, {
301
+ body: mark,
302
+ requiredRoute: "native build store mark"
303
+ }),
304
+ listIosDevices: async ({ status, ...input }) => await call("GET", "/ios-devices", {
305
+ query: {
306
+ ...keysetParams(input),
307
+ ...status === void 0 ? {} : { status }
308
+ },
309
+ requiredRoute: "iOS device registry"
310
+ }) ?? [],
311
+ findIosDevice: (udid) => call("GET", `/ios-devices/udid/${encode(udid)}`, { requiredRoute: "iOS device registry" }),
312
+ requestIosDevice: async (input) => await call("POST", "/ios-devices", {
313
+ body: input,
314
+ requiredRoute: "iOS device registry"
315
+ }),
316
+ approveIosDevice: (id, input) => call("POST", `/ios-devices/${encode(id)}/approval`, {
317
+ body: input,
318
+ requiredRoute: "iOS device registry"
319
+ }),
320
+ renameIosDevice: (id, name) => call("PATCH", `/ios-devices/${encode(id)}`, {
321
+ body: { name },
322
+ requiredRoute: "iOS device registry"
323
+ }),
324
+ recordIosDeviceOutcome: ({ id, ...input }) => call("POST", `/ios-devices/${encode(id)}/outcome`, {
325
+ body: input,
326
+ requiredRoute: "iOS device registry"
327
+ }),
328
+ markIosDevicesInBuild: async ({ buildId, ids }) => {
329
+ let start = 0;
330
+ do {
331
+ await request("POST", "/ios-devices/in-build", {
332
+ body: {
333
+ buildId,
334
+ ids: ids.slice(start, start + MAX_IDS)
335
+ },
336
+ requiredRoute: "iOS device registry"
337
+ });
338
+ start += MAX_IDS;
339
+ } while (start < ids.length);
340
+ },
341
+ findIosDeviceAccount: () => call("GET", "/ios-devices/account", { requiredRoute: "iOS device registry" }),
342
+ claimIosDeviceAccount: async (issuerId) => await call("POST", "/ios-devices/account", {
343
+ body: { issuerId },
344
+ requiredRoute: "iOS device registry"
345
+ }),
346
+ deleteIosDevice: (id, only) => call("DELETE", `/ios-devices/${encode(id)}`, {
347
+ query: {
348
+ ...only?.status === void 0 ? {} : { status: only.status },
349
+ ...only?.requestedBy === void 0 ? {} : { requestedBy: only.requestedBy }
350
+ },
351
+ requiredRoute: "iOS device registry"
352
+ }),
238
353
  deleteNativeBuild: async (id) => await call("DELETE", `/native-builds/${encode(id)}`, { requiredRoute: "native build deletion" })
239
354
  };
240
355
  };
@@ -251,8 +366,8 @@ const standaloneRepository = (config) => {
251
366
  return Object.freeze({
252
367
  name: "standalone-repository",
253
368
  core: createStandaloneCoreApi(config),
254
- fetchAdmin: (path, init = {}) => {
255
- const headers = new Headers(http.headers({ "Cache-Control": "no-cache" }));
369
+ fetchAdmin: async (path, init = {}) => {
370
+ const headers = new Headers(await http.headers({ "Cache-Control": "no-cache" }));
256
371
  new Headers(init.headers).forEach((value, name) => {
257
372
  headers.set(name, value);
258
373
  });
@@ -269,8 +384,12 @@ const defaultRoutes = {
269
384
  put: () => ({ path: "/upload" }),
270
385
  get: () => ({ path: "/get" }),
271
386
  exists: () => ({ path: "/exists" }),
272
- delete: () => ({ path: "/delete" })
387
+ delete: () => ({ path: "/delete" }),
388
+ listObjects: () => ({ path: "/list" }),
389
+ deleteObjects: () => ({ path: "/delete-objects" })
273
390
  };
391
+ /** Keys sent in one `deleteObjects` request. */
392
+ const DELETE_BATCH_SIZE = 1e3;
274
393
  const createRoute = (defaultRoute, customRoute) => ({
275
394
  path: customRoute?.path ?? defaultRoute.path,
276
395
  headers: {
@@ -279,8 +398,8 @@ const createRoute = (defaultRoute, customRoute) => ({
279
398
  }
280
399
  });
281
400
  const standaloneStorage = (config) => {
282
- const getHeaders = (routeHeaders) => ({
283
- ...config.commonHeaders,
401
+ const getHeaders = async (routeHeaders) => ({
402
+ ...await resolveHeaders(config.commonHeaders),
284
403
  ...routeHeaders
285
404
  });
286
405
  const resolveRoute = (name, args) => {
@@ -288,6 +407,14 @@ const standaloneStorage = (config) => {
288
407
  const custom = config.routes?.[name];
289
408
  return createRoute(fallback(...args), custom?.(...args));
290
409
  };
410
+ const postJson = async (path, headers, body) => fetch(`${config.baseUrl}${path}`, {
411
+ method: "POST",
412
+ headers: {
413
+ "content-type": "application/json",
414
+ ...await getHeaders(headers)
415
+ },
416
+ body: JSON.stringify(body)
417
+ });
291
418
  const requestStorageUri = async (routeName, storageUri) => {
292
419
  parseStorageUri(storageUri, config.protocol);
293
420
  const { path, headers } = resolveRoute(routeName, [{ storageUri }]);
@@ -295,7 +422,7 @@ const standaloneStorage = (config) => {
295
422
  method: routeName === "delete" ? "DELETE" : "POST",
296
423
  headers: {
297
424
  "content-type": "application/json",
298
- ...getHeaders(headers)
425
+ ...await getHeaders(headers)
299
426
  },
300
427
  body: JSON.stringify({ storageUri })
301
428
  });
@@ -318,7 +445,7 @@ const standaloneStorage = (config) => {
318
445
  formData.append("key", key);
319
446
  const response = await fetch(`${config.baseUrl}${path}`, {
320
447
  method: "POST",
321
- headers: getHeaders(headers),
448
+ headers: await getHeaders(headers),
322
449
  body: formData
323
450
  });
324
451
  if (!response.ok) throw new Error(`Failed to upload bundle: ${response.statusText}`);
@@ -339,6 +466,39 @@ const standaloneStorage = (config) => {
339
466
  async delete({ storageUri }) {
340
467
  await requestStorageUri("delete", storageUri);
341
468
  return { deleted: true };
469
+ },
470
+ async listObjects(prefix) {
471
+ const { path, headers } = resolveRoute("listObjects", [{ prefix }]);
472
+ const objects = [];
473
+ let cursor;
474
+ do {
475
+ const response = await postJson(path, headers, {
476
+ prefix,
477
+ cursor
478
+ });
479
+ if (response.status === 404) throw new Error(`The storage service has no ${path} route, which storage prune needs.`);
480
+ if (!response.ok) throw new Error(`Failed to list storage objects: ${response.statusText}`);
481
+ const page = await response.json();
482
+ for (const object of page.objects) {
483
+ parseStorageUri(object.storageUri, config.protocol);
484
+ objects.push({
485
+ key: object.key,
486
+ storageUri: object.storageUri,
487
+ size: object.size,
488
+ ...object.lastModifiedAt === void 0 ? {} : { lastModifiedAt: new Date(object.lastModifiedAt) }
489
+ });
490
+ }
491
+ cursor = page.cursor;
492
+ } while (cursor !== void 0);
493
+ return objects;
494
+ },
495
+ async deleteObjects(keys) {
496
+ for (let offset = 0; offset < keys.length; offset += DELETE_BATCH_SIZE) {
497
+ const batch = keys.slice(offset, offset + DELETE_BATCH_SIZE);
498
+ const { path, headers } = resolveRoute("deleteObjects", [{ keys: batch }]);
499
+ const response = await postJson(path, headers, { keys: batch });
500
+ if (!response.ok) throw new Error(`Failed to delete storage objects: ${response.statusText}`);
501
+ }
342
502
  }
343
503
  });
344
504
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hot-updater/standalone",
3
- "version": "1.2.0-rc.6",
3
+ "version": "1.2.0-rc.61",
4
4
  "type": "module",
5
5
  "description": "React Native OTA solution for self-hosted",
6
6
  "sideEffects": false,
@@ -42,8 +42,8 @@
42
42
  "access": "public"
43
43
  },
44
44
  "dependencies": {
45
- "@hot-updater/protocol": "1.2.0-rc.6",
46
- "@hot-updater/plugin-core": "1.2.0-rc.6"
45
+ "@hot-updater/plugin-core": "1.2.0-rc.61",
46
+ "@hot-updater/protocol": "1.2.0-rc.61"
47
47
  },
48
48
  "devDependencies": {
49
49
  "mime": "2.6.0",
@@ -52,12 +52,7 @@
52
52
  "msw": "^2.7.0",
53
53
  "verkit": "0.4.0",
54
54
  "vitest": "4.1.4",
55
- "@hot-updater/test-utils": "1.2.0-rc.6"
56
- },
57
- "nx": {
58
- "implicitDependencies": [
59
- "!@hot-updater/test-utils"
60
- ]
55
+ "@hot-updater/test-utils": "1.2.0-rc.61"
61
56
  },
62
57
  "scripts": {
63
58
  "build": "tsdown",