@firebase-function-kits/delete-user-data 0.0.1 → 0.0.2-rc.1

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.
Files changed (77) hide show
  1. package/CHANGELOG.md +1 -0
  2. package/README.md +220 -0
  3. package/lib/config.d.ts +22 -0
  4. package/lib/config.d.ts.map +1 -0
  5. package/lib/config.js +153 -0
  6. package/lib/config.js.map +1 -0
  7. package/lib/events.d.ts +18 -0
  8. package/lib/events.d.ts.map +1 -0
  9. package/lib/events.js +71 -0
  10. package/lib/events.js.map +1 -0
  11. package/lib/export-config.d.ts +55 -0
  12. package/lib/export-config.d.ts.map +1 -0
  13. package/lib/export-config.js +56 -0
  14. package/lib/export-config.js.map +1 -0
  15. package/lib/handlers.d.ts +35 -0
  16. package/lib/handlers.d.ts.map +1 -0
  17. package/lib/handlers.js +243 -0
  18. package/lib/handlers.js.map +1 -0
  19. package/lib/helpers.d.ts +19 -0
  20. package/lib/helpers.d.ts.map +1 -0
  21. package/lib/helpers.js +39 -0
  22. package/lib/helpers.js.map +1 -0
  23. package/lib/index.d.ts +6 -0
  24. package/lib/index.d.ts.map +1 -0
  25. package/lib/index.js +112 -0
  26. package/lib/index.js.map +1 -0
  27. package/lib/lib.d.ts +23 -0
  28. package/lib/lib.d.ts.map +1 -0
  29. package/lib/lib.js +38 -0
  30. package/lib/lib.js.map +1 -0
  31. package/lib/logs.d.ts +26 -0
  32. package/lib/logs.d.ts.map +1 -0
  33. package/lib/logs.js +116 -0
  34. package/lib/logs.js.map +1 -0
  35. package/lib/recursiveDelete.d.ts +18 -0
  36. package/lib/recursiveDelete.d.ts.map +1 -0
  37. package/lib/recursiveDelete.js +37 -0
  38. package/lib/recursiveDelete.js.map +1 -0
  39. package/lib/runBatchPubSubDeletions.d.ts +27 -0
  40. package/lib/runBatchPubSubDeletions.d.ts.map +1 -0
  41. package/lib/runBatchPubSubDeletions.js +47 -0
  42. package/lib/runBatchPubSubDeletions.js.map +1 -0
  43. package/lib/runCustomSearchFunction.d.ts +18 -0
  44. package/lib/runCustomSearchFunction.d.ts.map +1 -0
  45. package/lib/runCustomSearchFunction.js +78 -0
  46. package/lib/runCustomSearchFunction.js.map +1 -0
  47. package/lib/search.d.ts +19 -0
  48. package/lib/search.d.ts.map +1 -0
  49. package/lib/search.js +29 -0
  50. package/lib/search.js.map +1 -0
  51. package/npm-shrinkwrap.json +4167 -0
  52. package/package.json +37 -4
  53. package/src/config.ts +188 -0
  54. package/src/events.ts +38 -0
  55. package/src/export-config.ts +112 -0
  56. package/src/handlers.ts +271 -0
  57. package/src/helpers.ts +42 -0
  58. package/src/index.ts +100 -0
  59. package/src/lib.ts +41 -0
  60. package/src/logs.ts +127 -0
  61. package/src/recursiveDelete.ts +42 -0
  62. package/src/runBatchPubSubDeletions.ts +66 -0
  63. package/src/runCustomSearchFunction.ts +50 -0
  64. package/src/search.ts +37 -0
  65. package/tests/config.test.ts +180 -0
  66. package/tests/export-config.test.ts +117 -0
  67. package/tests/fakes.ts +325 -0
  68. package/tests/handlers.test.ts +517 -0
  69. package/tests/helpers.test.ts +126 -0
  70. package/tests/lib.test.ts +40 -0
  71. package/tests/recursiveDelete.test.ts +102 -0
  72. package/tests/runBatchPubSubDeletions.test.ts +164 -0
  73. package/tests/runCustomSearchFunction.test.ts +125 -0
  74. package/tests/search.test.ts +127 -0
  75. package/tsconfig.json +18 -0
  76. package/tsconfig.tsbuildinfo +1 -0
  77. package/index.js +0 -0
package/src/index.ts ADDED
@@ -0,0 +1,100 @@
1
+ /*
2
+ * Copyright 2019 Google LLC
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * https://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import { PubSub } from "@google-cloud/pubsub";
18
+ import * as admin from "firebase-admin";
19
+ import { getFirestore } from "firebase-admin/firestore";
20
+ import * as functionsV1 from "firebase-functions/v1";
21
+ import type { Role } from "firebase-functions/v2";
22
+ import { requiresRole } from "firebase-functions/v2";
23
+ import { onMessagePublished } from "firebase-functions/v2/pubsub";
24
+ import { CONFIG_EXPRESSIONS, configFromEnv } from "./config";
25
+ import * as events from "./events";
26
+ import { getDatabaseUrl, resolveDeleteUserDataConfig } from "./export-config";
27
+ import {
28
+ type HandlerContext,
29
+ handleClear,
30
+ handleDeletion as runDeletion,
31
+ handleSearch as runSearch,
32
+ } from "./handlers";
33
+ import * as logs from "./logs";
34
+
35
+ export * from "./lib";
36
+
37
+ const REQUIRED_ROLES: ReadonlyArray<Role> = [
38
+ "roles/datastore.owner",
39
+ "roles/firebasedatabase.admin",
40
+ "roles/storage.admin",
41
+ "roles/pubsub.admin",
42
+ // Gen2 event triggers need Eventarc receive and run.invoker on the function SA.
43
+ "roles/eventarc.eventReceiver",
44
+ "roles/run.invoker",
45
+ ];
46
+
47
+ for (const role of REQUIRED_ROLES) {
48
+ requiresRole(role);
49
+ }
50
+
51
+ let ctx: HandlerContext | undefined;
52
+
53
+ function getContext(): HandlerContext {
54
+ if (ctx) {
55
+ return ctx;
56
+ }
57
+
58
+ const resolved = resolveDeleteUserDataConfig(configFromEnv());
59
+ const databaseURL = getDatabaseUrl(
60
+ resolved.rtdbInstance,
61
+ resolved.rtdbLocation
62
+ );
63
+
64
+ if (admin.apps.length === 0) {
65
+ admin.initializeApp({
66
+ credential: admin.credential.applicationDefault(),
67
+ ...(databaseURL ? { databaseURL } : {}),
68
+ });
69
+ }
70
+
71
+ events.setupEventChannel();
72
+ logs.init(resolved);
73
+
74
+ ctx = {
75
+ firestore: getFirestore(resolved.firestoreDatabaseId),
76
+ storage: admin.storage(),
77
+ database: admin.database(),
78
+ pubsub: new PubSub({ projectId: resolved.projectId }),
79
+ config: resolved,
80
+ };
81
+ return ctx;
82
+ }
83
+
84
+ export const clearData = functionsV1.auth.user().onDelete((user) => {
85
+ return handleClear(user.uid, getContext());
86
+ });
87
+
88
+ export const handleSearch = onMessagePublished(
89
+ {
90
+ topic: CONFIG_EXPRESSIONS.discoveryTopicName,
91
+ },
92
+ (event) => runSearch(event.data.message.json, getContext())
93
+ );
94
+
95
+ export const handleDeletion = onMessagePublished(
96
+ {
97
+ topic: CONFIG_EXPRESSIONS.deletionTopicName,
98
+ },
99
+ (event) => runDeletion(event.data.message.json, getContext())
100
+ );
package/src/lib.ts ADDED
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Copyright 2026 Google LLC
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * https://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ export {
18
+ type DeleteUserDataConfig,
19
+ type FirestoreDeleteMode,
20
+ getDatabaseUrl,
21
+ type ResolvedDeleteUserDataConfig,
22
+ resolveDeleteUserDataConfig,
23
+ } from "./export-config";
24
+ export {
25
+ type DeleteMessageData,
26
+ type HandlerContext,
27
+ handleClear,
28
+ handleDeletion,
29
+ handleSearch,
30
+ type SearchMessageData,
31
+ } from "./handlers";
32
+ export { extractUserPaths, hasValidUserPath } from "./helpers";
33
+ export { recursiveDelete } from "./recursiveDelete";
34
+ export {
35
+ type DeletionPaths,
36
+ type PublisherContext,
37
+ publishSearch,
38
+ runBatchPubSubDeletions,
39
+ } from "./runBatchPubSubDeletions";
40
+ export { runCustomSearchFunction } from "./runCustomSearchFunction";
41
+ export { search } from "./search";
package/src/logs.ts ADDED
@@ -0,0 +1,127 @@
1
+ /*
2
+ * Copyright 2019 Google LLC
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * https://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import { logger } from "firebase-functions";
18
+ import type { ResolvedDeleteUserDataConfig } from "./export-config";
19
+
20
+ export const complete = (uid: string) => {
21
+ logger.log(`Successfully removed data for user: ${uid}`);
22
+ };
23
+
24
+ export const firestoreDeleted = () => {
25
+ logger.log("Finished deleting user data from Cloud Firestore");
26
+ };
27
+
28
+ export const firestoreDeleting = () => {
29
+ logger.log("Deleting user data from Cloud Firestore");
30
+ };
31
+
32
+ export const firestoreNotConfigured = () => {
33
+ logger.log("Cloud Firestore paths are not configured, skipping");
34
+ };
35
+
36
+ export const firestorePathDeleted = (path: string, recursive: boolean) => {
37
+ logger.log(
38
+ `Deleted: '${path}' from Cloud Firestore ${
39
+ recursive ? "with recursive delete" : ""
40
+ }`
41
+ );
42
+ };
43
+
44
+ export const firestorePathDeleting = (path: string, recursive: boolean) => {
45
+ logger.log(
46
+ `Deleting: '${path}' from Cloud Firestore ${
47
+ recursive ? "with recursive delete" : ""
48
+ }`
49
+ );
50
+ };
51
+
52
+ export const firestorePathError = (path: string, err: Error) => {
53
+ logger.error(`Error when deleting: '${path}' from Cloud Firestore`, err);
54
+ };
55
+
56
+ export const init = (config: ResolvedDeleteUserDataConfig) => {
57
+ logger.log("Initializing extension with configuration", config);
58
+ };
59
+
60
+ export const rtdbDeleted = () => {
61
+ logger.log("Finished deleting user data from the Realtime Database");
62
+ };
63
+
64
+ export const rtdbDeleting = () => {
65
+ logger.log("Deleting user data from the Realtime Database");
66
+ };
67
+
68
+ export const rtdbPathDeleted = (path: string) => {
69
+ logger.log(`Deleted: '${path}' from the Realtime Database`);
70
+ };
71
+
72
+ export const rtdbNotConfigured = () => {
73
+ logger.log("Realtime Database paths are not configured, skipping");
74
+ };
75
+
76
+ export const rtdbPathDeleting = (path: string) => {
77
+ logger.log(`Deleting: '${path}' from the Realtime Database`);
78
+ };
79
+
80
+ export const rtdbPathError = (path: string, err: Error) => {
81
+ logger.error(
82
+ `Error when deleting: '${path}' from the Realtime Database`,
83
+ err
84
+ );
85
+ };
86
+
87
+ export const start = (config: ResolvedDeleteUserDataConfig) => {
88
+ logger.log("Started extension execution with configuration", config);
89
+ };
90
+
91
+ export const storageDeleted = () => {
92
+ logger.log("Finished deleting user data from Cloud Storage");
93
+ };
94
+
95
+ export const storageDeleting = () => {
96
+ logger.log("Deleting user data from Cloud Storage");
97
+ };
98
+
99
+ export const storageNotConfigured = () => {
100
+ logger.log("Cloud Storage paths are not configured, skipping");
101
+ };
102
+
103
+ export const storagePathDeleted = (path: string) => {
104
+ logger.log(`Deleted: '${path}' from Cloud Storage`);
105
+ };
106
+
107
+ export const storagePathDeleting = (path: string) => {
108
+ logger.log(`Deleting: '${path}' from Cloud Storage`);
109
+ };
110
+
111
+ export const storagePath404 = (path: string) => {
112
+ logger.log(`File: '${path}' does not exist in Cloud Storage, skipping`);
113
+ };
114
+
115
+ export const storagePathError = (path: string, err: Error) => {
116
+ logger.error(`Error deleting: '${path}' from Cloud Storage`, err);
117
+ };
118
+
119
+ export const customFunctionError = (err: Error) => {
120
+ logger.error(`Call to custom hook function threw an error`, err);
121
+ };
122
+
123
+ export function warnInvalidPaths(invalidPathCount: number, uid: string) {
124
+ logger.warn(
125
+ `Attempted to delete ${invalidPathCount} invalid paths for deleted user ${uid}`
126
+ );
127
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Copyright 2026 Google LLC
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * https://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import type * as admin from "firebase-admin";
18
+
19
+ const MAX_RETRY_ATTEMPTS = 3;
20
+
21
+ export const recursiveDelete = async (
22
+ path: string,
23
+ db: admin.firestore.Firestore
24
+ ) => {
25
+ // Recursively delete a reference and log the references of failures.
26
+ const bulkWriter = db.bulkWriter();
27
+
28
+ bulkWriter.onWriteError((error) => {
29
+ if (error.failedAttempts < MAX_RETRY_ATTEMPTS) {
30
+ return true;
31
+ } else {
32
+ console.warn("Failed to delete document: ", error.documentRef.path);
33
+ return false;
34
+ }
35
+ });
36
+
37
+ const isDocument = path.split("/").length % 2 === 0;
38
+
39
+ const reference = isDocument ? db.doc(path) : db.collection(path);
40
+
41
+ await db.recursiveDelete(reference, bulkWriter);
42
+ };
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Copyright 2026 Google LLC
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * https://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import type { PubSub } from "@google-cloud/pubsub";
18
+ import chunk from "lodash.chunk";
19
+ import type { ResolvedDeleteUserDataConfig } from "./export-config";
20
+
21
+ export interface DeletionPaths {
22
+ firestorePaths: string[];
23
+ }
24
+
25
+ export interface PublisherContext {
26
+ pubsub: PubSub;
27
+ config: ResolvedDeleteUserDataConfig;
28
+ }
29
+
30
+ function topicPath(
31
+ config: ResolvedDeleteUserDataConfig,
32
+ topicName: string
33
+ ): string {
34
+ const projectId =
35
+ config.projectId ??
36
+ process.env.GOOGLE_CLOUD_PROJECT ??
37
+ process.env.PROJECT_ID;
38
+ return projectId ? `projects/${projectId}/topics/${topicName}` : topicName;
39
+ }
40
+
41
+ export async function publishSearch(
42
+ uid: string,
43
+ depth: number,
44
+ path: string,
45
+ ctx: PublisherContext
46
+ ): Promise<void> {
47
+ await ctx.pubsub
48
+ .topic(topicPath(ctx.config, ctx.config.discoveryTopicName))
49
+ .publishMessage({ json: { path, uid, depth } });
50
+ }
51
+
52
+ export async function runBatchPubSubDeletions(
53
+ paths: DeletionPaths,
54
+ uid: string,
55
+ ctx: PublisherContext
56
+ ): Promise<void> {
57
+ const { firestorePaths } = paths;
58
+ if (!firestorePaths || !Array.isArray(firestorePaths)) return;
59
+ if (firestorePaths.length === 0) return;
60
+
61
+ for (const chunkedPaths of chunk<string>(firestorePaths, 450)) {
62
+ await ctx.pubsub
63
+ .topic(topicPath(ctx.config, ctx.config.deletionTopicName))
64
+ .publishMessage({ json: { paths: chunkedPaths, uid } });
65
+ }
66
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Copyright 2026 Google LLC
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * https://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import fetch from "node-fetch";
18
+ import * as logs from "./logs";
19
+ import type { PublisherContext } from "./runBatchPubSubDeletions";
20
+ import { runBatchPubSubDeletions } from "./runBatchPubSubDeletions";
21
+
22
+ export const runCustomSearchFunction = async (
23
+ uid: string,
24
+ ctx: PublisherContext
25
+ ): Promise<void> => {
26
+ if (!ctx.config.searchFunction) return;
27
+
28
+ const response = await fetch(ctx.config.searchFunction, {
29
+ method: "POST",
30
+ body: JSON.stringify({ uid }),
31
+ headers: { "Content-Type": "application/json" },
32
+ });
33
+
34
+ if (!response.ok) {
35
+ const body = await response.text();
36
+ logs.customFunctionError(new Error(body));
37
+ return;
38
+ }
39
+
40
+ const json = await response.json();
41
+ if (Array.isArray(json)) {
42
+ return runBatchPubSubDeletions({ firestorePaths: json }, uid, ctx);
43
+ }
44
+
45
+ return runBatchPubSubDeletions(
46
+ json as { firestorePaths: string[] },
47
+ uid,
48
+ ctx
49
+ );
50
+ };
package/src/search.ts ADDED
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Copyright 2026 Google LLC
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * https://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import type * as admin from "firebase-admin";
18
+ import {
19
+ type PublisherContext,
20
+ publishSearch,
21
+ } from "./runBatchPubSubDeletions";
22
+
23
+ export const search = async (
24
+ uid: string,
25
+ depth: number,
26
+ db: admin.firestore.Firestore,
27
+ ctx: PublisherContext,
28
+ document?: admin.firestore.DocumentReference<admin.firestore.DocumentData>
29
+ ): Promise<void> => {
30
+ const collections = !document
31
+ ? await db.listCollections()
32
+ : await document.listCollections();
33
+
34
+ for (const collection of collections) {
35
+ await publishSearch(uid, depth, collection.path, ctx);
36
+ }
37
+ };
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Copyright 2026 Google LLC
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * https://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import { afterEach, describe, expect, test, vi } from "vitest";
18
+
19
+ class FakeExpression<_T = string> {
20
+ constructor(private readonly cel: string) {}
21
+
22
+ toCEL(): string {
23
+ return this.cel;
24
+ }
25
+ }
26
+
27
+ class FakeStringParam extends FakeExpression<string> {
28
+ constructor(
29
+ private readonly name: string,
30
+ private readonly defaultValue?: string | FakeExpression
31
+ ) {
32
+ super(`{{ params.${name} }}`);
33
+ }
34
+
35
+ value(): string {
36
+ if (this.defaultValue instanceof FakeStringParam) {
37
+ return this.defaultValue.value();
38
+ }
39
+ if (this.defaultValue instanceof FakeExpression) {
40
+ return this.defaultValue.toCEL();
41
+ }
42
+ return this.defaultValue ?? `${this.name.toLowerCase()}-value`;
43
+ }
44
+ }
45
+
46
+ const defineString = vi.fn(
47
+ (name: string, opts?: { default?: string | FakeExpression }) =>
48
+ new FakeStringParam(name, opts?.default)
49
+ );
50
+
51
+ const defineInt = vi.fn((_name: string, opts?: { default?: number }) => ({
52
+ value: () => opts?.default ?? 0,
53
+ }));
54
+
55
+ const defineBoolean = vi.fn((_name: string, opts?: { default?: boolean }) => ({
56
+ value: () => opts?.default ?? false,
57
+ }));
58
+
59
+ const expr = vi.fn(
60
+ (strings: TemplateStringsArray, ...values: unknown[]) =>
61
+ new FakeExpression(
62
+ strings.reduce(
63
+ (result, part, index) =>
64
+ result + part + (index < values.length ? cel(values[index]) : ""),
65
+ ""
66
+ )
67
+ )
68
+ );
69
+
70
+ function cel(value: unknown): string {
71
+ return value instanceof FakeExpression ? value.toCEL() : String(value);
72
+ }
73
+
74
+ vi.mock("firebase-functions/params", () => ({
75
+ Expression: FakeExpression,
76
+ defineBoolean,
77
+ defineInt,
78
+ defineString,
79
+ expr,
80
+ projectID: { value: () => "demo-test" },
81
+ select: vi.fn((options: string[]) => ({ options })),
82
+ storageBucket: new FakeStringParam("STORAGE_BUCKET", "demo-test.appspot.com"),
83
+ }));
84
+
85
+ async function importConfig() {
86
+ vi.resetModules();
87
+ defineString.mockClear();
88
+ defineInt.mockClear();
89
+ defineBoolean.mockClear();
90
+ expr.mockClear();
91
+
92
+ return import("../src/config");
93
+ }
94
+
95
+ afterEach(() => {
96
+ vi.unstubAllEnvs();
97
+ });
98
+
99
+ describe("configFromEnv", () => {
100
+ test("reads the extension.yaml defaults", async () => {
101
+ const { configFromEnv } = await importConfig();
102
+
103
+ expect(configFromEnv()).toMatchObject({
104
+ firestoreDatabaseId: "(default)",
105
+ firestoreDeleteMode: "shallow",
106
+ rtdbLocation: "us-central1",
107
+ enableAutoDiscovery: false,
108
+ searchDepth: 3,
109
+ searchFields: "id,uid,userId",
110
+ projectId: "demo-test",
111
+ });
112
+ });
113
+
114
+ test("maps empty params to undefined", async () => {
115
+ const { configFromEnv } = await importConfig();
116
+ const config = configFromEnv();
117
+
118
+ expect(config.firestorePaths).toBeUndefined();
119
+ expect(config.rtdbPaths).toBeUndefined();
120
+ expect(config.storagePaths).toBeUndefined();
121
+ expect(config.searchFunction).toBeUndefined();
122
+ expect(config.rtdbInstance).toBeUndefined();
123
+ });
124
+
125
+ test("declares the params the extension exposes", async () => {
126
+ await importConfig();
127
+
128
+ const declared = defineString.mock.calls.map(([name]) => name);
129
+ expect(declared).toEqual(
130
+ expect.arrayContaining([
131
+ "INSTANCE_ID",
132
+ "FIRESTORE_PATHS",
133
+ "FIRESTORE_DATABASE_ID",
134
+ "FIRESTORE_DELETE_MODE",
135
+ "SELECTED_DATABASE_INSTANCE",
136
+ "SELECTED_DATABASE_LOCATION",
137
+ "RTDB_PATHS",
138
+ "CLOUD_STORAGE_BUCKET",
139
+ "STORAGE_PATHS",
140
+ "AUTO_DISCOVERY_SEARCH_FIELDS",
141
+ "SEARCH_FUNCTION",
142
+ "DISCOVERY_TOPIC_NAME",
143
+ "DELETION_TOPIC_NAME",
144
+ ])
145
+ );
146
+ expect(defineInt.mock.calls).toContainEqual([
147
+ "AUTO_DISCOVERY_SEARCH_DEPTH",
148
+ expect.objectContaining({ default: 3 }),
149
+ ]);
150
+ expect(defineBoolean.mock.calls).toContainEqual([
151
+ "ENABLE_AUTO_DISCOVERY",
152
+ expect.objectContaining({ default: false }),
153
+ ]);
154
+ });
155
+
156
+ test("defaults the topic names to kit-{instanceId}-* expressions", async () => {
157
+ const { CONFIG_EXPRESSIONS } = await importConfig();
158
+
159
+ expect(cel(CONFIG_EXPRESSIONS.discoveryTopicName)).toBe(
160
+ "{{ params.DISCOVERY_TOPIC_NAME }}"
161
+ );
162
+ expect(cel(CONFIG_EXPRESSIONS.deletionTopicName)).toBe(
163
+ "{{ params.DELETION_TOPIC_NAME }}"
164
+ );
165
+ expect(expr.mock.results.map((result) => cel(result.value))).toEqual([
166
+ "kit-{{ params.INSTANCE_ID }}-discovery",
167
+ "kit-{{ params.INSTANCE_ID }}-deletion",
168
+ ]);
169
+ expect(defineString.mock.calls).toContainEqual([
170
+ "DISCOVERY_TOPIC_NAME",
171
+ { default: expect.anything() },
172
+ ]);
173
+ });
174
+
175
+ test("defaults the storage bucket to the project bucket param", async () => {
176
+ const { configFromEnv } = await importConfig();
177
+
178
+ expect(configFromEnv().storageBucket).toBe("demo-test.appspot.com");
179
+ });
180
+ });