@hot-updater/firebase 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.mjs CHANGED
@@ -2,6 +2,8 @@ import { createEngineDatabase, createKvAdapter, createStorageAdapter, createStor
2
2
  import { getApp, getApps, initializeApp } from "firebase-admin/app";
3
3
  import { FieldPath, FieldValue, Timestamp, getFirestore } from "firebase-admin/firestore";
4
4
  import { createHash } from "node:crypto";
5
+ import { Readable } from "node:stream";
6
+ import { pipeline } from "node:stream/promises";
5
7
  import { getStorage } from "firebase-admin/storage";
6
8
  //#region src/firebaseInfrastructureNames.ts
7
9
  /**
@@ -166,14 +168,67 @@ const createFirestoreStore = ({ firestore, collection, nativePageSize }) => {
166
168
  };
167
169
  };
168
170
  //#endregion
171
+ //#region src/googleCredential.ts
172
+ const CLOUD_PLATFORM_SCOPE$1 = "https://www.googleapis.com/auth/cloud-platform";
173
+ /**
174
+ * Resolves application default credentials as Firestore will, from
175
+ * GOOGLE_APPLICATION_CREDENTIALS's file or the environment, for the app's
176
+ * `projectId`, so it neither exchanges a token nor discovers a project
177
+ * Firestore itself wouldn't. Only `applicationDefault()`'s credential: a
178
+ * service account's or refresh token's was read from its file already.
179
+ */
180
+ const resolveApplicationDefault = async (credential, projectId) => {
181
+ if (credential.constructor.name !== "ApplicationDefaultCredential") return;
182
+ const { GoogleAuth } = await import("google-auth-library");
183
+ await new GoogleAuth({
184
+ scopes: [CLOUD_PLATFORM_SCOPE$1],
185
+ ...projectId === void 0 ? {} : { projectId }
186
+ }).getClient();
187
+ };
188
+ //#endregion
169
189
  //#region src/firebaseDatabase.ts
190
+ /**
191
+ * `store` that loads `credential` before its first call: one that cannot
192
+ * load, such as GOOGLE_APPLICATION_CREDENTIALS naming a missing file, fails
193
+ * that call with what is wrong. Firestore's own client would also reject a
194
+ * promise nobody awaits, which ends a CLI process with a stack trace.
195
+ */
196
+ const withLoadedCredential = (store, credential, projectId) => {
197
+ let loaded;
198
+ const load = () => loaded ??= resolveApplicationDefault(credential, projectId).then(() => void 0, (error) => {
199
+ loaded = void 0;
200
+ throw new Error(`Could not load the Google credentials for Firestore: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
201
+ });
202
+ const { deleteConsumed } = store;
203
+ return {
204
+ ...store,
205
+ get: async (keys) => {
206
+ await load();
207
+ return store.get(keys);
208
+ },
209
+ query: async (range) => {
210
+ await load();
211
+ return store.query(range);
212
+ },
213
+ write: async (ops) => {
214
+ await load();
215
+ return store.write(ops);
216
+ },
217
+ ...deleteConsumed && { deleteConsumed: async (keys) => {
218
+ await load();
219
+ return deleteConsumed.call(store, keys);
220
+ } }
221
+ };
222
+ };
170
223
  const adapterOf = ({ databaseId, collection = FIREBASE_V1_COLLECTION, aggregateBatching: _, ...appOptions }) => {
171
224
  const app = getApps().length ? getApp() : initializeApp(appOptions);
172
225
  const firestore = databaseId ? getFirestore(app, databaseId) : getFirestore(app);
173
- return createKvAdapter({ store: createFirestoreStore({
226
+ const store = createFirestoreStore({
174
227
  firestore,
175
228
  collection
176
- }) });
229
+ });
230
+ const credential = app.options.credential;
231
+ return createKvAdapter({ store: appOptions.credential === void 0 || credential === void 0 || process.env["FIRESTORE_EMULATOR_HOST"] ? store : withLoadedCredential(store, credential, app.options.projectId) });
177
232
  };
178
233
  /**
179
234
  * Writes the schema settings of core and `plugins`, the plugins the server
@@ -201,11 +256,14 @@ const firebaseDatabase = (config) => ({
201
256
  //#region src/firebaseStorage.ts
202
257
  /** Signed URLs kept per adapter, enough for a few Bundles' assets. */
203
258
  const MAX_CACHED_SIGNED_URLS = 1e4;
259
+ /** Objects deleted at once: Cloud Storage deletes one object a request. */
260
+ const DELETE_CONCURRENCY = 16;
204
261
  const firebaseStorage = (config) => {
205
262
  const app = getApps().length ? getApp() : initializeApp(config);
206
263
  let opened;
207
264
  const bucket = () => opened ??= getStorage(app).bucket(config.storageBucket);
208
265
  const getStorageKey = createStorageKeyBuilder(config.basePath);
266
+ const basePrefix = getStorageKey() ? `${getStorageKey()}/` : "";
209
267
  /**
210
268
  * Signed URLs by object. Without a private key, as in Cloud Functions, each
211
269
  * signature is an IAM signBlob request, and an update check returns a URL
@@ -248,11 +306,21 @@ const firebaseStorage = (config) => {
248
306
  protocol: "gs",
249
307
  async put({ key, body, contentType }) {
250
308
  const storageKey = getStorageKey(key);
251
- const [{ Readable }, { pipeline }] = await Promise.all([import("node:stream"), import("node:stream/promises")]);
252
- await pipeline(Readable.fromWeb(body), bucket().file(storageKey).createWriteStream({ metadata: {
253
- contentType,
254
- cacheControl: "public, max-age=31536000, immutable"
255
- } }));
309
+ try {
310
+ await pipeline(Readable.fromWeb(body), bucket().file(storageKey).createWriteStream({
311
+ resumable: false,
312
+ metadata: {
313
+ contentType,
314
+ cacheControl: "public, max-age=31536000, immutable"
315
+ }
316
+ }));
317
+ } catch (error) {
318
+ const status = Reflect.get(Object(error), "code");
319
+ if (typeof status !== "number") throw error;
320
+ const message = error.message;
321
+ const detail = /<html|<!doctype/i.test(message) ? "" : `: ${message}`;
322
+ throw new Error(`Firebase Storage answered HTTP ${status} while uploading ${storageKey}${detail}`, { cause: error });
323
+ }
256
324
  return { storageUri: createStorageUri({
257
325
  bucket: config.storageBucket,
258
326
  key: storageKey,
@@ -294,6 +362,39 @@ const firebaseStorage = (config) => {
294
362
  const { key } = parseAndValidate(storageUri);
295
363
  await bucket().file(key).delete({ ignoreNotFound: true });
296
364
  return { deleted: true };
365
+ },
366
+ async listObjects(prefix) {
367
+ const folder = getStorageKey(prefix ?? "");
368
+ const [files] = await bucket().getFiles({
369
+ autoPaginate: true,
370
+ prefix: folder ? `${folder}/` : ""
371
+ });
372
+ const objects = [];
373
+ for (const file of files) {
374
+ if (!file.name.startsWith(basePrefix)) continue;
375
+ let storageUri;
376
+ try {
377
+ storageUri = createStorageUri({
378
+ bucket: config.storageBucket,
379
+ key: file.name,
380
+ protocol: "gs"
381
+ });
382
+ } catch {
383
+ continue;
384
+ }
385
+ const { size, updated } = file.metadata;
386
+ objects.push({
387
+ key: file.name.slice(basePrefix.length),
388
+ ...updated ? { lastModifiedAt: new Date(updated) } : {},
389
+ size: Number(size ?? 0),
390
+ storageUri
391
+ });
392
+ }
393
+ return objects;
394
+ },
395
+ async deleteObjects(relativeKeys) {
396
+ const keys = relativeKeys.map((key) => getStorageKey(key));
397
+ for (let offset = 0; offset < keys.length; offset += DELETE_CONCURRENCY) await Promise.all(keys.slice(offset, offset + DELETE_CONCURRENCY).map((key) => bucket().file(key).delete({ ignoreNotFound: true })));
297
398
  }
298
399
  });
299
400
  };
@@ -355,22 +456,61 @@ const crc32c = (bytes) => {
355
456
  /** The version IDs the secret's annotation lists. */
356
457
  const trackedVersions = (secret) => (secret.annotations?.[VERSIONS_ANNOTATION] ?? "").split(",").map((entry) => entry.trim()).filter((entry) => VERSION_ID_PATTERN.test(entry));
357
458
  const versionOf = (name) => typeof name === "string" ? name.slice(name.lastIndexOf("/") + 1) : "";
358
- const hint = (response, permission) => {
459
+ /** An error of one line each, for a terminal. */
460
+ const failure = (lines, cause) => new Error(lines.join("\n"), cause === void 0 ? void 0 : { cause });
461
+ /**
462
+ * The one step that can fix the credentials in use, by the order they're
463
+ * tried: signing in with gcloud changes nothing while a variable comes first.
464
+ */
465
+ const signInHint = (credentials) => {
466
+ if (credentials) return [`Check the credentials passed to ${ADAPTER_NAME}().`];
467
+ const variable = ACCESS_TOKEN_ENV_NAMES.find((name) => process.env[name]?.trim()) ?? (process.env["GOOGLE_APPLICATION_CREDENTIALS"]?.trim() ? "GOOGLE_APPLICATION_CREDENTIALS" : void 0);
468
+ if (variable) return [`Fix or unset ${variable}.`];
469
+ return process.env["CI"] ? ["Use google-github-actions/auth."] : ["Sign in:", "gcloud auth application-default login"];
470
+ };
471
+ const hint = (response, permission, signIn, projectId) => {
359
472
  const { status, error } = response;
360
- if (error.details?.some((detail) => detail.reason === "SERVICE_DISABLED")) return " Enable the Secret Manager API (secretmanager.googleapis.com) in the project: gcloud services enable secretmanager.googleapis.com --project <project>.";
361
- if (status === 401) return " Google rejected the access token: sign in again with `gcloud auth application-default login`, or check the job's Workload Identity Federation.";
362
- if (status === 403) return ` The Google identity needs ${permission}.`;
363
- if (status === 429) return " Secret Manager's quota is exhausted: try again later.";
364
- return "";
473
+ if (error.details?.some((detail) => detail.reason === "SERVICE_DISABLED")) return ["Enable the Secret Manager API in the project:", `gcloud services enable secretmanager.googleapis.com --project ${projectId}`];
474
+ if (status === 401) return ["Google rejected the access token.", ...signIn];
475
+ if (status === 403) return [`The identity needs ${permission}.`];
476
+ if (status === 429) return ["Secret Manager's quota is exhausted: try again later."];
477
+ return [];
365
478
  };
366
479
  /**
367
- * An error for a failed request: the HTTP status, Google's status and
368
- * message, which name resources but never a value, and what to fix.
480
+ * An error for a failed request on `resource`, a line each: the HTTP status,
481
+ * the resource, `notes`, and what to fix, or Google's own status and message,
482
+ * which name resources but never a value, when nothing here says what to fix.
369
483
  */
370
- const requestError = (action, response, permission) => {
484
+ const requestErrorOf = (signIn, projectId, action, resource, response, permission, notes = []) => {
371
485
  const { status, message } = response.error;
372
- const detail = [status, message?.slice(0, 300)].filter(Boolean).join(": ");
373
- return /* @__PURE__ */ new Error(`${ADAPTER_NAME} could not ${action} (${response.status}${detail ? ` ${detail}` : ""}).${hint(response, permission)}`);
486
+ const fix = hint(response, permission, signIn, projectId);
487
+ if (response.status === 401 && notes.length === 0) return failure(fix);
488
+ return failure([
489
+ `${ADAPTER_NAME} couldn't ${action} (${response.status}).`,
490
+ resourceLine(resource),
491
+ ...notes,
492
+ ...fix.length > 0 ? fix : [[status, message?.slice(0, 300)].filter(Boolean).join(": ")]
493
+ ]);
494
+ };
495
+ /** The line that names a secret: its resource name is a line's worth. */
496
+ const resourceLine = (secret) => `Secret: ${secret}`;
497
+ let metadataWarningFiltered = false;
498
+ /**
499
+ * Drops the one warning `gcp-metadata` emits when its probe for a Google
500
+ * runtime fails oddly: credentials are about to be reported as missing, and
501
+ * the warning has nothing to act on. It stays filtered for the process, as
502
+ * the library caches the probe; every other warning passes through.
503
+ * `METADATA_SERVER_DETECTION=none` would also silence it, but skips the probe,
504
+ * and with it the credentials of a Google runtime.
505
+ */
506
+ const filterMetadataWarning = () => {
507
+ if (metadataWarningFiltered) return;
508
+ metadataWarningFiltered = true;
509
+ const emitWarning = process.emitWarning;
510
+ process.emitWarning = ((warning, ...rest) => {
511
+ if (rest[0] === "MetadataLookupWarning") return;
512
+ Reflect.apply(emitWarning, process, [warning, ...rest]);
513
+ });
374
514
  };
375
515
  /** Masks a value in the CLI's output, which loads `@hot-updater/cli-tools`. */
376
516
  const mask = async (value) => {
@@ -407,10 +547,11 @@ const createAccessToken = (credentials, projectId) => {
407
547
  throw error;
408
548
  });
409
549
  const client = await auth;
550
+ filterMetadataWarning();
410
551
  try {
411
552
  return await client.getAccessToken() ?? void 0;
412
553
  } catch (error) {
413
- throw new Error(`${ADAPTER_NAME} found no Google credentials (${error instanceof Error ? error.message.split("\n")[0] : String(error)}). Sign in with \`gcloud auth application-default login\`, use google-github-actions/auth in CI, set GOOGLE_APPLICATION_CREDENTIALS, or set ${ACCESS_TOKEN_ENV_NAMES.join(" or ")} to an access token.`, { cause: error });
554
+ throw failure([`${ADAPTER_NAME} found no Google credentials.`, ...signInHint(void 0)], error);
414
555
  }
415
556
  };
416
557
  return async () => {
@@ -432,14 +573,19 @@ const createAccessToken = (credentials, projectId) => {
432
573
  */
433
574
  const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
434
575
  const accessToken = createAccessToken(credentials, projectId);
576
+ const requestError = (action, resource, response, permission, notes) => requestErrorOf(signInHint(credentials), projectId, action, resource, response, permission, notes);
435
577
  const projectPath = () => {
436
- if (typeof projectId !== "string" || !PROJECT_PATTERN.test(projectId)) throw new Error(`${ADAPTER_NAME} needs the Google Cloud project ID or number as projectId, and ${JSON.stringify(projectId)} is not one.`);
437
- if (!PREFIX_PATTERN.test(prefix)) throw new Error(`${ADAPTER_NAME}'s prefix takes letters, digits, "-", and "_", and ${JSON.stringify(prefix)} has others.`);
578
+ if (typeof projectId !== "string" || !PROJECT_PATTERN.test(projectId)) throw failure([`${ADAPTER_NAME} can't use the projectId ${JSON.stringify(projectId)}.`, "Set the Google Cloud project's ID or number."]);
579
+ if (!PREFIX_PATTERN.test(prefix)) throw failure([`${ADAPTER_NAME} can't use the prefix ${JSON.stringify(prefix)}.`, "It takes letters, digits, \"-\", and \"_\"."]);
438
580
  return `projects/${projectId}`;
439
581
  };
440
582
  const secretId = (name) => {
441
583
  const id = `${prefix}${name}`;
442
- if (!SECRET_ID_PATTERN.test(id)) throw new Error(`${ADAPTER_NAME} keeps ${JSON.stringify(name)} as the secret ID ${JSON.stringify(id)}, and Secret Manager's IDs take only letters, digits, "-", and "_", up to 255 characters.`);
584
+ if (!SECRET_ID_PATTERN.test(id)) throw failure([
585
+ `${ADAPTER_NAME} can't name a secret ${JSON.stringify(name)}.`,
586
+ `Secret: ${id}`,
587
+ "Secret Manager's IDs take up to 255 letters, digits, \"-\", and \"_\"."
588
+ ]);
443
589
  return id;
444
590
  };
445
591
  const request = async (token, method, path, body) => {
@@ -474,14 +620,18 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
474
620
  const accessLatest = async (token, secret) => {
475
621
  const response = await request(token, "GET", `${secret}/versions/latest:access`);
476
622
  if (response.status === 404) return void 0;
477
- if (!response.ok) throw requestError(`read ${secret}`, response, "roles/secretmanager.secretAccessor on the secret");
623
+ if (!response.ok) throw requestError("read", secret, response, "roles/secretmanager.secretAccessor on the secret");
478
624
  const body = isRecord(response.body) ? response.body : void 0;
479
625
  const payload = body?.payload;
480
626
  const data = isRecord(payload) ? payload.data : void 0;
481
- if (typeof data !== "string") throw new Error(`${ADAPTER_NAME} read no payload for ${secret}.`);
627
+ if (typeof data !== "string") throw failure([`${ADAPTER_NAME} read no payload.`, resourceLine(secret)]);
482
628
  const bytes = Buffer.from(data, "base64");
483
629
  const checksum = isRecord(payload) ? payload.dataCrc32c : void 0;
484
- if (checksum !== void 0 && Number(checksum) !== crc32c(bytes)) throw new Error(`${ADAPTER_NAME} read ${secret} with a checksum that does not match its payload.`);
630
+ if (checksum !== void 0 && Number(checksum) !== crc32c(bytes)) throw failure([
631
+ `${ADAPTER_NAME} can't trust what it read.`,
632
+ resourceLine(secret),
633
+ "Its checksum doesn't match its payload."
634
+ ]);
485
635
  const value = bytes.toString("utf8");
486
636
  await mask(value);
487
637
  return {
@@ -514,7 +664,7 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
514
664
  const readSecret = async (token, secret) => {
515
665
  const response = await request(token, "GET", secret);
516
666
  if (response.status === 404) return void 0;
517
- if (!response.ok) throw requestError(`read ${secret}`, response, "secretmanager.secrets.get on the secret");
667
+ if (!response.ok) throw requestError("read", secret, response, "secretmanager.secrets.get on the secret");
518
668
  return response.body;
519
669
  };
520
670
  const getOrCreateSecret = async (token, parent, id) => {
@@ -527,14 +677,19 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
527
677
  const raced = await readSecret(token, secret);
528
678
  if (raced) return raced;
529
679
  }
530
- throw requestError(`create ${secret}`, created, `secretmanager.secrets.create on ${parent}`);
680
+ throw requestError("create", secret, created, `secretmanager.secrets.create on ${parent}`);
531
681
  };
532
682
  const assertCanSet = async (token, secret) => {
533
683
  const response = await request(token, "POST", `${secret}:testIamPermissions`, { permissions: SET_PERMISSIONS });
534
- if (!response.ok) throw requestError(`check its permissions on ${secret}`, response, SET_PERMISSIONS.join(", "));
684
+ if (!response.ok) throw requestError("check its permissions", secret, response, SET_PERMISSIONS.join(", "));
535
685
  const held = isRecord(response.body) && Array.isArray(response.body.permissions) ? response.body.permissions : [];
536
686
  const missing = SET_PERMISSIONS.filter((name) => !held.includes(name));
537
- if (missing.length > 0) throw new Error(`${ADAPTER_NAME} stores a value as a new version of ${secret} and destroys the versions it added before, and the Google identity lacks ${missing.join(", ")} on it: grant a custom role with secretmanager.secrets.get, secretmanager.secrets.update, secretmanager.versions.add, secretmanager.versions.destroy, and secretmanager.versions.access on it, or roles/secretmanager.admin.`);
687
+ if (missing.length > 0) throw failure([
688
+ `${ADAPTER_NAME} can't store a value.`,
689
+ resourceLine(secret),
690
+ `The identity lacks ${missing.join(", ")} on it.`,
691
+ "Grant roles/secretmanager.admin."
692
+ ]);
538
693
  };
539
694
  /**
540
695
  * Destroys `version` of `secret`: true once it is destroyed, or already
@@ -567,10 +722,11 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
567
722
  /**
568
723
  * Adds `value` as the secret's newest version, creating the secret when
569
724
  * it is missing, and waits until the `latest` alias resolves to it. Then
570
- * it destroys the older versions this adapter added, which the secret's
571
- * `hot-updater-versions` annotation lists: versions added any other way
572
- * are never touched. The permissions this needs are checked before
573
- * anything is written. A version that could not be destroyed stays
725
+ * it destroys the versions this adapter added before the previous one,
726
+ * which the secret's `hot-updater-versions` annotation lists, keeping
727
+ * the previous value: versions added any other way are never touched.
728
+ * The permissions this needs are checked on the secret, once it exists,
729
+ * before any version is added. A version that could not be destroyed stays
574
730
  * listed for the next `set`. The annotation is updated against the
575
731
  * secret's etag, so a concurrent `set` loses no listed version. When
576
732
  * `latest` does not resolve to the new version in time, or the
@@ -581,7 +737,7 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
581
737
  const parent = projectPath();
582
738
  const id = secretId(name);
583
739
  const secret = `${parent}/secrets/${id}`;
584
- if (typeof value !== "string" || value === "") throw new Error(`${ADAPTER_NAME} cannot store an empty ${secret}.`);
740
+ if (typeof value !== "string" || value === "") throw failure([`${ADAPTER_NAME} can't store an empty value.`, resourceLine(secret)]);
585
741
  await mask(value);
586
742
  const token = await accessToken();
587
743
  const current = await getOrCreateSecret(token, parent, id);
@@ -592,17 +748,20 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
592
748
  dataCrc32c: String(crc32c(data))
593
749
  } });
594
750
  const version = versionOf(isRecord(added.body) ? added.body.name : void 0);
595
- if (!added.ok || !VERSION_ID_PATTERN.test(version)) throw requestError(`add a version to ${secret}`, added, "secretmanager.versions.add on the secret");
751
+ if (!added.ok || !VERSION_ID_PATTERN.test(version)) throw requestError("add a version", secret, added, "secretmanager.versions.add on the secret");
752
+ const own = trackedVersions(current).filter((entry) => Number(entry) < Number(version));
753
+ const previous = own.reduce((newest, entry) => newest === void 0 || Number(entry) > Number(newest) ? entry : newest, void 0);
596
754
  const visible = await waitForLatest(token, secret, version);
597
755
  const destroyed = /* @__PURE__ */ new Set();
598
756
  if (visible) {
599
- const older = trackedVersions(current).filter((entry) => Number(entry) < Number(version));
757
+ const older = own.filter((entry) => entry !== previous);
600
758
  const results = await Promise.all(older.map((entry) => destroy(token, secret, entry)));
601
759
  older.forEach((entry, index) => {
602
760
  if (results[index]) destroyed.add(entry);
603
761
  });
604
762
  }
605
- const notListed = `list version ${version}, which it stored, in ${secret}'s ${VERSIONS_ANNOTATION} annotation, so the next set will not destroy it`;
763
+ const notListed = `record version ${version}, which it stored`;
764
+ const notDestroyed = `The next set won't destroy it: ${VERSIONS_ANNOTATION} misses it.`;
606
765
  let base = current;
607
766
  let updated;
608
767
  try {
@@ -611,7 +770,11 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
611
770
  await delay(LATEST_RETRY_DELAYS_MS[attempt - 1] ?? 0);
612
771
  base = await readSecret(token, secret) ?? {};
613
772
  }
614
- const listed = [.../* @__PURE__ */ new Set([version, ...trackedVersions(base)])].filter((entry) => !destroyed.has(entry));
773
+ const listed = [.../* @__PURE__ */ new Set([
774
+ version,
775
+ ...previous === void 0 ? [] : [previous],
776
+ ...trackedVersions(base)
777
+ ])].filter((entry) => !destroyed.has(entry));
615
778
  updated = await request(token, "PATCH", `${secret}?updateMask=annotations`, {
616
779
  ...base.etag === void 0 ? {} : { etag: base.etag },
617
780
  annotations: {
@@ -622,14 +785,24 @@ const secretManager = ({ projectId, prefix = "hot-updater-", credentials }) => {
622
785
  if (updated.error.status !== "FAILED_PRECONDITION") break;
623
786
  }
624
787
  } catch (error) {
625
- throw new Error(`${ADAPTER_NAME} could not ${notListed} (${error instanceof Error ? error.message : String(error)}).`, { cause: error });
788
+ throw failure([
789
+ `${ADAPTER_NAME} couldn't ${notListed}.`,
790
+ resourceLine(secret),
791
+ error instanceof Error ? error.message : String(error),
792
+ notDestroyed
793
+ ], error);
626
794
  }
627
- if (!updated?.ok) throw requestError(notListed, updated, "secretmanager.secrets.update on the secret");
628
- if (!visible) throw new Error(`${ADAPTER_NAME} stored ${secret} as version ${version}, and its latest alias does not resolve to that version yet, so it kept the versions it added before; the next set destroys them.`);
795
+ if (!updated?.ok) throw requestError(notListed, secret, updated, "secretmanager.secrets.update on the secret", [notDestroyed]);
796
+ if (!visible) throw failure([
797
+ `${ADAPTER_NAME} stored version ${version}.`,
798
+ resourceLine(secret),
799
+ "Its latest alias doesn't resolve to that version yet.",
800
+ "It kept the versions it added before: the next set destroys them."
801
+ ]);
629
802
  },
630
803
  describe: (name) => {
631
804
  const id = `${prefix}${name}`;
632
- return `projects/${projectId}/secrets/${id} (https://console.cloud.google.com/security/secret-manager/secret/${encodeURIComponent(id)}/versions?project=${encodeURIComponent(projectId)})`;
805
+ return `the secret ${JSON.stringify(id)} in Google Secret Manager (https://console.cloud.google.com/security/secret-manager/secret/${encodeURIComponent(id)}/versions?project=${encodeURIComponent(projectId)})`;
633
806
  }
634
807
  };
635
808
  };
@@ -6863,14 +6863,67 @@ const createFirestoreStore = ({ firestore, collection, nativePageSize }) => {
6863
6863
  };
6864
6864
  };
6865
6865
  //#endregion
6866
+ //#region src/googleCredential.ts
6867
+ const CLOUD_PLATFORM_SCOPE = "https://www.googleapis.com/auth/cloud-platform";
6868
+ /**
6869
+ * Resolves application default credentials as Firestore will, from
6870
+ * GOOGLE_APPLICATION_CREDENTIALS's file or the environment, for the app's
6871
+ * `projectId`, so it neither exchanges a token nor discovers a project
6872
+ * Firestore itself wouldn't. Only `applicationDefault()`'s credential: a
6873
+ * service account's or refresh token's was read from its file already.
6874
+ */
6875
+ const resolveApplicationDefault = async (credential, projectId) => {
6876
+ if (credential.constructor.name !== "ApplicationDefaultCredential") return;
6877
+ const { GoogleAuth } = await import("google-auth-library");
6878
+ await new GoogleAuth({
6879
+ scopes: [CLOUD_PLATFORM_SCOPE],
6880
+ ...projectId === void 0 ? {} : { projectId }
6881
+ }).getClient();
6882
+ };
6883
+ //#endregion
6866
6884
  //#region src/firebaseDatabase.ts
6885
+ /**
6886
+ * `store` that loads `credential` before its first call: one that cannot
6887
+ * load, such as GOOGLE_APPLICATION_CREDENTIALS naming a missing file, fails
6888
+ * that call with what is wrong. Firestore's own client would also reject a
6889
+ * promise nobody awaits, which ends a CLI process with a stack trace.
6890
+ */
6891
+ const withLoadedCredential = (store, credential, projectId) => {
6892
+ let loaded;
6893
+ const load = () => loaded ??= resolveApplicationDefault(credential, projectId).then(() => void 0, (error) => {
6894
+ loaded = void 0;
6895
+ throw new Error(`Could not load the Google credentials for Firestore: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
6896
+ });
6897
+ const { deleteConsumed } = store;
6898
+ return {
6899
+ ...store,
6900
+ get: async (keys) => {
6901
+ await load();
6902
+ return store.get(keys);
6903
+ },
6904
+ query: async (range) => {
6905
+ await load();
6906
+ return store.query(range);
6907
+ },
6908
+ write: async (ops) => {
6909
+ await load();
6910
+ return store.write(ops);
6911
+ },
6912
+ ...deleteConsumed && { deleteConsumed: async (keys) => {
6913
+ await load();
6914
+ return deleteConsumed.call(store, keys);
6915
+ } }
6916
+ };
6917
+ };
6867
6918
  const adapterOf = ({ databaseId, collection = FIREBASE_V1_COLLECTION, aggregateBatching: _, ...appOptions }) => {
6868
6919
  const app = (0, firebase_admin_app.getApps)().length ? (0, firebase_admin_app.getApp)() : (0, firebase_admin_app.initializeApp)(appOptions);
6869
6920
  const firestore = databaseId ? (0, firebase_admin_firestore.getFirestore)(app, databaseId) : (0, firebase_admin_firestore.getFirestore)(app);
6870
- return (0, _hot_updater_plugin_core.createKvAdapter)({ store: createFirestoreStore({
6921
+ const store = createFirestoreStore({
6871
6922
  firestore,
6872
6923
  collection
6873
- }) });
6924
+ });
6925
+ const credential = app.options.credential;
6926
+ return (0, _hot_updater_plugin_core.createKvAdapter)({ store: appOptions.credential === void 0 || credential === void 0 || process.env["FIRESTORE_EMULATOR_HOST"] ? store : withLoadedCredential(store, credential, app.options.projectId) });
6874
6927
  };
6875
6928
  /**
6876
6929
  * Writes the schema settings of core and `plugins`, the plugins the server
@@ -6976,8 +7029,32 @@ const firebaseEngineSettingDocumentId = () => firestoreDocumentId({
6976
7029
  pk: _hot_updater_plugin_core.SETTINGS_TABLE.name,
6977
7030
  sk: (0, _hot_updater_plugin_core.encodeKvKey)([ENGINE_SETTING])
6978
7031
  });
7032
+ /**
7033
+ * The Google credential init reads Firestore with, once it loads: the
7034
+ * service account key file `applicationCredentials` names, or the
7035
+ * application default credentials. Before any change, an InitError says
7036
+ * what is wrong with one that does not load, where Firestore's client would
7037
+ * end init with a stack trace.
7038
+ */
7039
+ const loadGoogleCredential = async (applicationCredentials, projectId) => {
7040
+ const next = "Set GOOGLE_APPLICATION_CREDENTIALS to a service account key file, then rerun init.";
7041
+ let credential;
7042
+ try {
7043
+ credential = applicationCredentials ? (0, firebase_admin_app.cert)(JSON.parse(await fs_promises.default.readFile(applicationCredentials, "utf8"))) : (0, firebase_admin_app.applicationDefault)();
7044
+ } catch {
7045
+ throw new _hot_updater_cli_tools.InitError(`GOOGLE_APPLICATION_CREDENTIALS names ${applicationCredentials}, which is not a readable service account key file. ${next}`);
7046
+ }
7047
+ if (process.env["FIRESTORE_EMULATOR_HOST"]) return credential;
7048
+ try {
7049
+ await resolveApplicationDefault(credential, projectId);
7050
+ } catch (error) {
7051
+ const reason = (error instanceof Error ? error.message : String(error)).split(/(?<=\.)\s/u)[0].replace(/\.$/u, "");
7052
+ throw new _hot_updater_cli_tools.InitError(`Could not load Google credentials: ${reason}. ${next}`);
7053
+ }
7054
+ return credential;
7055
+ };
6979
7056
  const assertFirebaseInfrastructureCanInitialize = async ({ applicationCredentials, databaseId, projectId }) => {
6980
- const credential = applicationCredentials ? (0, firebase_admin_app.cert)(JSON.parse(await fs_promises.default.readFile(applicationCredentials, "utf8"))) : (0, firebase_admin_app.applicationDefault)();
7057
+ const credential = await loadGoogleCredential(applicationCredentials, projectId);
6981
7058
  const app = (0, firebase_admin_app.initializeApp)({
6982
7059
  credential,
6983
7060
  projectId
@@ -7823,7 +7900,7 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
7823
7900
  });
7824
7901
  await (0, _hot_updater_cli_tools.makeEnv)(persistedInputs);
7825
7902
  await removeTmpDir();
7826
- return;
7903
+ return null;
7827
7904
  }
7828
7905
  const functionsCode = (0, _hot_updater_cli_tools.transformEnv)(functionsIndexPath, {
7829
7906
  REGION: currentRegion,
@@ -7853,8 +7930,8 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
7853
7930
  }
7854
7931
  }]);
7855
7932
  await deployFirestore(tmpDir, initializeVariable.databaseId, nonInteractive, cliEnv);
7856
- const credential = applicationCredentials ? (0, firebase_admin_app.cert)(JSON.parse(await fs.default.promises.readFile(applicationCredentials, "utf-8"))) : (0, firebase_admin_app.applicationDefault)();
7857
- const existingApps = new Set((0, firebase_admin_app.getApps)());
7933
+ const credential = await loadGoogleCredential(applicationCredentials, initializeVariable.projectId);
7934
+ await Promise.all((0, firebase_admin_app.getApps)().map((app) => (0, firebase_admin_app.deleteApp)(app)));
7858
7935
  const databaseConfig = {
7859
7936
  credential,
7860
7937
  databaseId: initializeVariable.databaseId,
@@ -7872,6 +7949,7 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
7872
7949
  let clientCredential;
7873
7950
  try {
7874
7951
  await migrateFirebaseDatabase(databaseConfig, server.plugins);
7952
+ await (0, _hot_updater_cli_tools.fillReleaseLabels)(server);
7875
7953
  clientCredential = await (0, _hot_updater_cli_tools.provisionClientCredential)(server, {
7876
7954
  env: initInputEnv,
7877
7955
  name: "Firebase init"
@@ -7879,7 +7957,7 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
7879
7957
  if (clientCredential !== void 0) await (0, _hot_updater_cli_tools.makeEnv)({ [clientCredential.env]: clientCredential.value });
7880
7958
  } finally {
7881
7959
  await database.dispose?.();
7882
- await Promise.all((0, firebase_admin_app.getApps)().filter((app) => !existingApps.has(app)).map((app) => (0, firebase_admin_app.deleteApp)(app)));
7960
+ await Promise.all((0, firebase_admin_app.getApps)().map((app) => (0, firebase_admin_app.deleteApp)(app)));
7883
7961
  }
7884
7962
  await deployFunctions(tmpDir, nonInteractive, cliEnv);
7885
7963
  await _hot_updater_cli_tools.p.tasks([{
@@ -7924,11 +8002,19 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
7924
8002
  await removeTmpDir();
7925
8003
  process.exit(1);
7926
8004
  }
8005
+ const backfillDatabase = firebaseDatabase(databaseConfig);
8006
+ try {
8007
+ await (0, _hot_updater_cli_tools.backfillInsightsReleaseRefs)((0, _hot_updater_cli_tools.assembleServer)({
8008
+ database: backfillDatabase,
8009
+ plugins: server.plugins
8010
+ }));
8011
+ } finally {
8012
+ await backfillDatabase.dispose?.();
8013
+ await Promise.all((0, firebase_admin_app.getApps)().map((app) => (0, firebase_admin_app.deleteApp)(app)));
8014
+ }
7927
8015
  await printTemplate(clientCredential, initializeVariable.projectId, currentRegion, server.clientPlugins, cliEnv);
7928
8016
  await removeTmpDir();
7929
- _hot_updater_cli_tools.p.log.message(`Next step: ${(0, _hot_updater_cli_tools.link)("https://hot-updater.dev/docs/managed/firebase#step-3-add-hotupdater-to-your-project")}`);
7930
- if (!applicationCredentials) _hot_updater_cli_tools.p.log.message("Next step: Change GOOGLE_APPLICATION_CREDENTIALS=your-credentials.json in .env.hotupdater");
7931
- _hot_updater_cli_tools.p.log.success("Done! 🎉");
8017
+ return { nextSteps: [(0, _hot_updater_cli_tools.link)("https://hot-updater.dev/docs/managed/firebase#step-3-add-hotupdater-to-your-project"), ...applicationCredentials ? [] : ["Change GOOGLE_APPLICATION_CREDENTIALS=your-credentials.json in .env.hotupdater"]] };
7932
8018
  };
7933
8019
  //#endregion
7934
8020
  exports.initProvider = initProvider;
@@ -1,4 +1,4 @@
1
- import { RunInitOptions } from "@hot-updater/cli-tools";
1
+ import { RunInitOptions, RunInitResult } from "@hot-updater/cli-tools";
2
2
  //#region iac/init/index.d.ts
3
3
  declare const initProvider: {
4
4
  readonly label: "Firebase";
@@ -86,6 +86,6 @@ declare const mergeIndexes: (originalIndexes: {
86
86
  };
87
87
  /** Points the template's `firebase.json` at the database init sets up. */
88
88
  declare const setFirestoreDatabase: (cwd: string, databaseId: string) => Promise<void>;
89
- declare const runInit: ({ build, envFile, secretsEnv }: RunInitOptions) => Promise<void>;
89
+ declare const runInit: ({ build, envFile, secretsEnv }: RunInitOptions) => Promise<RunInitResult>;
90
90
  //#endregion
91
91
  export { initProvider, mergeIndexes, runInit, setFirestoreDatabase };
@@ -1,4 +1,4 @@
1
- import { RunInitOptions } from "@hot-updater/cli-tools";
1
+ import { RunInitOptions, RunInitResult } from "@hot-updater/cli-tools";
2
2
  //#region iac/init/index.d.ts
3
3
  declare const initProvider: {
4
4
  readonly label: "Firebase";
@@ -86,6 +86,6 @@ declare const mergeIndexes: (originalIndexes: {
86
86
  };
87
87
  /** Points the template's `firebase.json` at the database init sets up. */
88
88
  declare const setFirestoreDatabase: (cwd: string, databaseId: string) => Promise<void>;
89
- declare const runInit: ({ build, envFile, secretsEnv }: RunInitOptions) => Promise<void>;
89
+ declare const runInit: ({ build, envFile, secretsEnv }: RunInitOptions) => Promise<RunInitResult>;
90
90
  //#endregion
91
91
  export { initProvider, mergeIndexes, runInit, setFirestoreDatabase };