@algolia/firestore-search 0.0.0-stage → 2.0.0-rc.0

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,97 @@
1
- # Temporary Holding Version
1
+ # @algolia/firestore-search
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Index a Cloud Firestore collection into [Algolia](https://algolia.com) using
4
+ 2nd Gen Cloud Functions. This is the Function Kit version of the
5
+ `firestore-algolia-search` Firebase Extension.
6
+
7
+ ## Installation
8
+
9
+ Requires `firebase-tools` 15.32.0 or later.
10
+
11
+ ```bash
12
+ firebase functions:kits:install --package @algolia/firestore-search --project <project-id>
13
+ ```
14
+
15
+ The CLI asks for a kit instance ID and prompts for the
16
+ [configuration](#configuration) values. Then deploy the kit:
17
+
18
+ ```bash
19
+ firebase deploy --only functions:<kit-instance-id> --project <project-id>
20
+ ```
21
+
22
+ The IAM roles `roles/datastore.user`, `roles/eventarc.eventReceiver`,
23
+ `roles/run.invoker` and `roles/cloudtasks.enqueuer` are declared in code and
24
+ granted at deploy time. A full indexing run is triggered automatically after the first deploy and
25
+ after every redeploy if you set `DO_FULL_INDEXING` to `true` (default `false`).
26
+
27
+ > [!NOTE]
28
+ > On the first deploy, the roles above are granted at the same moment the full
29
+ > indexing task is queued. IAM changes can take a few minutes to propagate, so the
30
+ > task may be rejected with a `403`:
31
+ > ```
32
+ > The request was not authenticated [...] The IAM principal lacks {run.routes.invoke} permission.
33
+ > ```
34
+ > If you see this in the `executeFullIndexOperation` logs, wait a few minutes and run the
35
+ > lifecycle hook again:
36
+ >
37
+ > ```bash
38
+ > firebase functions:lifecycle:run afterFirstDeploy <kit-instance-id> # or: afterRedeploy
39
+ > ```
40
+
41
+ ## Exported functions
42
+
43
+ | Function | Trigger | Purpose |
44
+ | :-------------------------- | :---------------------------------------- | :--------------------------------------------------- |
45
+ | `executeIndexOperation` | Firestore `onDocumentWritten` | Creates, updates or deletes the record in Algolia |
46
+ | `executeFullIndexOperation` | Cloud Tasks `onTaskDispatched` | Indexes all existing documents, in batches of 250 |
47
+
48
+ ## Configuration
49
+ ### `.env` values
50
+
51
+ | Param | Type | Default | Description |
52
+ | :------------------- | :------ | :------------ | :------------------------------------------------------------------------------------|
53
+ | `LOCATION` | string | `us-central1` | Functions region. |
54
+ | `DATABASE_ID` | string | `(default)` | Firestore database to monitor. |
55
+ | `COLLECTION_PATH` | string | _required_ | Collection to monitor, e.g. `movies` or `users/{userId}/posts` (collection group). |
56
+ | `FIELDS` | string | _all_ | Comma separated list of fields to index. |
57
+ | `FORCE_DATA_SYNC` | string | `false` | `true` / `false` (`yes` / `no` also accepted). Re-read the document before indexing. |
58
+ | `ALGOLIA_APP_ID` | string | _required_ | Algolia application ID. |
59
+ | `ALGOLIA_INDEX_NAME` | string | _required_ | Target Algolia index. |
60
+ | `ALT_OBJECT_ID` | string | _doc id_ | Document field used as `objectID`; `(path)` uses the document path. |
61
+ | `TRANSFORM_FUNCTION` | string | _none_ | Name of an HTTPS function that transforms records before indexing (experimental). |
62
+ | `DO_FULL_INDEXING` | boolean | `false` | Index existing documents after each deployment. |
63
+
64
+ ### Secrets
65
+
66
+ - `ALGOLIA_API_KEY`: An Algolia API Key with the following ACLs: `addObject`, `deleteObject`.
67
+
68
+ ## Migrating from the extension
69
+
70
+ Follow [Migrate from an extension to a function kit](https://firebase.google.com/docs/extensions/users/migrate) guide.
71
+
72
+ - Until the extension is uninstalled, it and the kit both index every write.
73
+ - Keep `DO_FULL_INDEXING=false` if the Algolia index is already up to date:
74
+ records keep the same `objectID` as long as `ALT_OBJECT_ID` doesn't change.
75
+ Set it to `true` for one deploy if you need a full resync.
76
+
77
+ ### What changed (Extension vs Package)
78
+
79
+ | Area | Extension | Package |
80
+ | :------------------ | :----------------------------------------------- | :--------------------------------------------------------------- |
81
+ | Triggers | 1st Gen `firestore.document().onWrite`, `taskQueue` | 2nd Gen `onDocumentWritten`, `onTaskDispatched` |
82
+ | Handler signature | `(change, context)` | `({ change, context })` via the V1 destructuring shim |
83
+ | Configuration | `extension.yaml` params / `process.env` | `defineString` / `defineBoolean` / `defineSecret` params |
84
+ | API key | `secret` param | `defineSecret("ALGOLIA_API_KEY")`, bound to both functions |
85
+ | IAM | `roles` in `extension.yaml` | four `requiresRole(...)` calls (see above) |
86
+ | Lifecycle | `onInstall` / `onUpdate` / `onConfigure` | `afterFirstDeploy` / `afterRedeploy` |
87
+ | Processing state | `runtime.setProcessingState` | Logged to Cloud Logging |
88
+ | Task enqueue | Needs `EXT_INSTANCE_ID` | Plain function name |
89
+ | `DO_FULL_INDEXING` | Required choice (Yes/No) | Default `false`; runs after every redeploy when `true` |
90
+ | Concurrency/cost | 1 request per instance | `cpu: "gcf_gen1"` keeps the single concurrency |
91
+
92
+ ## Development
93
+
94
+ ```bash
95
+ npm test # jest
96
+ npm run compile # tsc -> lib/
97
+ ```
@@ -0,0 +1,11 @@
1
+ export declare const databaseId: import("firebase-functions/params").StringParam;
2
+ export declare const collectionPath: import("firebase-functions/params").StringParam;
3
+ export declare const fields: import("firebase-functions/params").StringParam;
4
+ export declare const forceDataSync: import("firebase-functions/params").StringParam;
5
+ export declare const algoliaIndexName: import("firebase-functions/params").StringParam;
6
+ export declare const algoliaAppId: import("firebase-functions/params").StringParam;
7
+ export declare const algoliaApiKey: import("firebase-functions/params").SecretParam;
8
+ export declare const altObjectId: import("firebase-functions/params").StringParam;
9
+ export declare const transformFunction: import("firebase-functions/params").StringParam;
10
+ export declare const doFullIndexing: import("firebase-functions/params").BooleanParam;
11
+ export declare const location: import("firebase-functions/params").StringParam;
package/lib/config.js ADDED
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright 2021 Algolia
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * https://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.location = exports.doFullIndexing = exports.transformFunction = exports.altObjectId = exports.algoliaApiKey = exports.algoliaAppId = exports.algoliaIndexName = exports.forceDataSync = exports.fields = exports.collectionPath = exports.databaseId = void 0;
19
+ const params_1 = require("firebase-functions/params");
20
+ /*
21
+ * Parameterized configuration (replaces the extension `params`).
22
+ * Values are provided through `.env` files / CLI prompts at deploy time.
23
+ */
24
+ exports.databaseId = (0, params_1.defineString)('DATABASE_ID', {
25
+ default: '(default)',
26
+ description: 'Firestore database that contains the collection to monitor.',
27
+ });
28
+ exports.collectionPath = (0, params_1.defineString)('COLLECTION_PATH', {
29
+ description: 'Path of the Cloud Firestore collection to monitor, e.g. "movies" or "movies/{id}/actors".',
30
+ input: { text: { validationRegex: '^[^/]+(/[^/]+/[^/]+)*$', validationErrorMessage: 'Firestore collection paths must be an odd number of segments separated by slashes.' } },
31
+ });
32
+ exports.fields = (0, params_1.defineString)('FIELDS', {
33
+ default: '',
34
+ description: 'Comma separated list of fields to index. Leave blank to index all fields.',
35
+ });
36
+ // Declared as string so existing extension configs (`yes` / `no`) continue to work (a boolean param would turn `yes` into false).
37
+ exports.forceDataSync = (0, params_1.defineString)('FORCE_DATA_SYNC', {
38
+ default: 'false',
39
+ description: 'Re-read the document from Firestore before indexing to mitigate race conditions. "yes" is also accepted as "true".',
40
+ input: { select: { options: [{ value: 'false' }, { value: 'true' }] } },
41
+ });
42
+ exports.algoliaIndexName = (0, params_1.defineString)('ALGOLIA_INDEX_NAME', {
43
+ description: 'Name of the Algolia index where records are persisted.',
44
+ input: { text: { nonEmpty: true } },
45
+ });
46
+ exports.algoliaAppId = (0, params_1.defineString)('ALGOLIA_APP_ID', {
47
+ description: 'Algolia application ID.',
48
+ input: { text: { nonEmpty: true } },
49
+ });
50
+ exports.algoliaApiKey = (0, params_1.defineSecret)('ALGOLIA_API_KEY');
51
+ exports.altObjectId = (0, params_1.defineString)('ALT_OBJECT_ID', {
52
+ default: '',
53
+ description: 'Alternative Firestore document property to use as the Algolia objectID. Use "(path)" for the document path.',
54
+ });
55
+ exports.transformFunction = (0, params_1.defineString)('TRANSFORM_FUNCTION', {
56
+ default: '',
57
+ description: 'Name of an HTTPS callable function used to transform data before it is saved to Algolia (experimental).',
58
+ });
59
+ exports.doFullIndexing = (0, params_1.defineBoolean)('DO_FULL_INDEXING', {
60
+ default: false,
61
+ description: 'Index existing documents of the collection after each deployment.',
62
+ });
63
+ exports.location = (0, params_1.defineString)('LOCATION', {
64
+ default: 'us-central1',
65
+ description: 'Cloud Functions region.',
66
+ });
@@ -0,0 +1,2 @@
1
+ import { DocumentSnapshot } from 'firebase-admin/firestore';
2
+ export default function extract(snapshot: DocumentSnapshot, timestamp: Number): Promise<any>;
package/lib/extract.js ADDED
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright 2021 Algolia
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * https://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.default = extract;
19
+ const config_1 = require("./config");
20
+ const logs = require("./logs");
21
+ const processors_1 = require("./processors");
22
+ const transform_1 = require("./transform");
23
+ const util_1 = require("./util");
24
+ const PAYLOAD_MAX_SIZE = 102400;
25
+ const PAYLOAD_TOO_LARGE_ERR_MSG = 'Record is too large.';
26
+ const trim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
27
+ const getPayload = async (snapshot) => {
28
+ let payload = {
29
+ objectID: (0, util_1.getObjectID)(snapshot),
30
+ path: snapshot.ref.path,
31
+ };
32
+ const fields = (0, util_1.getFields)(config_1.fields.value());
33
+ if (fields.length === 0) {
34
+ payload = {
35
+ ...(0, processors_1.dataProcessor)(snapshot.data()),
36
+ ...payload,
37
+ };
38
+ }
39
+ else {
40
+ // Fields have been defined by user. Start pulling data from the document to create payload
41
+ // to send to Algolia.
42
+ fields.forEach(item => {
43
+ const firebaseField = item.replace(trim, '');
44
+ const [field, value] = (0, processors_1.valueProcessor)(firebaseField, snapshot.get(firebaseField));
45
+ if ((0, util_1.isValidValue)(value)) {
46
+ payload[field] = value;
47
+ }
48
+ else {
49
+ logs.fieldNotExist(firebaseField);
50
+ }
51
+ });
52
+ }
53
+ // adding the objectId in the return to make sure to restore to original if changed in the post processing.
54
+ return (0, transform_1.default)(payload);
55
+ };
56
+ async function extract(snapshot, timestamp) {
57
+ // Check payload size and make sure its within limits before sending for indexing
58
+ const payload = await getPayload(snapshot);
59
+ if ((0, util_1.getObjectSizeInBytes)(payload) < PAYLOAD_MAX_SIZE) {
60
+ if (timestamp === 0) {
61
+ return {
62
+ ...payload,
63
+ };
64
+ }
65
+ else {
66
+ return {
67
+ ...payload,
68
+ lastmodified: {
69
+ _operation: 'IncrementSet',
70
+ value: timestamp,
71
+ },
72
+ };
73
+ }
74
+ }
75
+ else {
76
+ throw new Error(PAYLOAD_TOO_LARGE_ERR_MSG);
77
+ }
78
+ }
package/lib/index.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import { SearchIndex } from 'algoliasearch';
2
+ export declare const getIndex: () => SearchIndex;
3
+ export declare const executeIndexOperation: import("firebase-functions/core").CloudFunction<import("firebase-functions/v2/firestore").FirestoreEvent<import("firebase-functions/v2").Change<import("firebase-functions/v2/firestore").DocumentSnapshot>, Record<string, string>>>;
4
+ export declare const executeFullIndexOperation: import("firebase-functions/v2/tasks").TaskQueueFunction<any>;
package/lib/index.js ADDED
@@ -0,0 +1,243 @@
1
+ "use strict";
2
+ /* eslint-disable import/no-unresolved */
3
+ /*
4
+ * Copyright 2021 Algolia
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * https://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.executeFullIndexOperation = exports.executeIndexOperation = exports.getIndex = void 0;
20
+ const algoliasearch_1 = require("algoliasearch");
21
+ const firestore_1 = require("firebase-functions/v2/firestore");
22
+ const tasks_1 = require("firebase-functions/v2/tasks");
23
+ const v2_1 = require("firebase-functions/v2");
24
+ const lifecycle_1 = require("firebase-functions/lifecycle");
25
+ const params_1 = require("firebase-functions/params");
26
+ const firestore_2 = require("firebase-admin/firestore");
27
+ const functions_1 = require("firebase-admin/functions");
28
+ const app_1 = require("firebase-admin/app");
29
+ const config_1 = require("./config");
30
+ const extract_1 = require("./extract");
31
+ const util_1 = require("./util");
32
+ const version_1 = require("./version");
33
+ const logs = require("./logs");
34
+ const DOCS_PER_INDEXING = 250;
35
+ // Required IAM roles.
36
+ (0, v2_1.requiresRole)('roles/datastore.user'); // read/write Firestore
37
+ (0, v2_1.requiresRole)('roles/eventarc.eventReceiver'); // create and receive the Firestore trigger
38
+ (0, v2_1.requiresRole)('roles/run.invoker'); // allow Firebase to call the functions (on document changes and for full indexing)
39
+ (0, v2_1.requiresRole)('roles/cloudtasks.enqueuer'); // needed when full indexing enqueues its next batch
40
+ // Algolia client and Firebase Admin are created lazily: parameter values are
41
+ // not available at module load time.
42
+ let algoliaIndex;
43
+ const getIndex = () => {
44
+ if (!algoliaIndex) {
45
+ logs.init();
46
+ const client = (0, algoliasearch_1.default)(config_1.algoliaAppId.value(), config_1.algoliaApiKey.value());
47
+ client.addAlgoliaAgent('firestore_integration', version_1.version);
48
+ algoliaIndex = client.initIndex(config_1.algoliaIndexName.value());
49
+ }
50
+ return algoliaIndex;
51
+ };
52
+ exports.getIndex = getIndex;
53
+ const getDb = () => {
54
+ if ((0, app_1.getApps)().length === 0) {
55
+ (0, app_1.initializeApp)();
56
+ }
57
+ return (0, firestore_2.getFirestore)(config_1.databaseId.value());
58
+ };
59
+ const handleCreateDocument = async (snapshot, timestamp) => {
60
+ try {
61
+ const shouldForceSync = (0, util_1.isEnabled)(config_1.forceDataSync.value());
62
+ if (shouldForceSync) {
63
+ const updatedSnapshot = await snapshot.ref.get();
64
+ const data = await (0, extract_1.default)(updatedSnapshot, 0);
65
+ logs.createIndex(updatedSnapshot.id, data);
66
+ logs.info('force sync data: execute saveObject');
67
+ await (0, exports.getIndex)().saveObject(data);
68
+ }
69
+ else {
70
+ const data = await (0, extract_1.default)(snapshot, timestamp);
71
+ logs.debug({
72
+ ...data,
73
+ });
74
+ logs.createIndex(snapshot.id, data);
75
+ await (0, exports.getIndex)().partialUpdateObject(data, { createIfNotExists: true });
76
+ }
77
+ }
78
+ catch (e) {
79
+ logs.error(e);
80
+ }
81
+ };
82
+ const handleUpdateDocument = async (before, after, timestamp) => {
83
+ try {
84
+ const shouldForceSync = (0, util_1.isEnabled)(config_1.forceDataSync.value());
85
+ if (shouldForceSync) {
86
+ const updatedSnapshot = await after.ref.get();
87
+ const data = await (0, extract_1.default)(updatedSnapshot, 0);
88
+ logs.updateIndex(updatedSnapshot.id, data);
89
+ logs.info('force sync data: execute saveObject');
90
+ await (0, exports.getIndex)().saveObject(data);
91
+ }
92
+ else {
93
+ if ((0, util_1.areFieldsUpdated)(before, after)) {
94
+ logs.debug('Detected a change, execute indexing');
95
+ const beforeData = await before.data();
96
+ // loop through the after data snapshot to see if any properties were removed
97
+ const undefinedAttrs = Object.keys(beforeData).filter(key => after.get(key) === undefined || after.get(key) === null);
98
+ logs.debug('undefinedAttrs', undefinedAttrs);
99
+ // if no attributes were removed, then use partial update of the record.
100
+ if (undefinedAttrs.length === 0) {
101
+ const data = await (0, extract_1.default)(after, timestamp);
102
+ logs.updateIndex(after.id, data);
103
+ logs.debug('execute partialUpdateObject');
104
+ await (0, exports.getIndex)().partialUpdateObject(data, { createIfNotExists: true });
105
+ }
106
+ // if an attribute was removed, then use save object of the record.
107
+ else {
108
+ const data = await (0, extract_1.default)(after, 0);
109
+ // delete null value attributes before saving.
110
+ undefinedAttrs.forEach(attr => delete data[attr]);
111
+ logs.updateIndex(after.id, data);
112
+ logs.debug('execute saveObject');
113
+ await (0, exports.getIndex)().saveObject(data);
114
+ }
115
+ }
116
+ }
117
+ }
118
+ catch (e) {
119
+ logs.error(e);
120
+ }
121
+ };
122
+ const handleDeleteDocument = async (deleted) => {
123
+ try {
124
+ logs.deleteIndex((0, util_1.getObjectID)(deleted));
125
+ await (0, exports.getIndex)().deleteObject((0, util_1.getObjectID)(deleted));
126
+ }
127
+ catch (e) {
128
+ logs.error(e);
129
+ }
130
+ };
131
+ exports.executeIndexOperation = (0, firestore_1.onDocumentWritten)({
132
+ document: (0, params_1.expr) `${config_1.collectionPath}/{documentID}`,
133
+ database: config_1.databaseId,
134
+ region: config_1.location,
135
+ secrets: [config_1.algoliaApiKey],
136
+ cpu: 'gcf_gen1',
137
+ }, async ({ change, context }) => {
138
+ logs.start();
139
+ const eventTimestamp = Date.parse(context.timestamp);
140
+ const changeType = (0, util_1.getChangeType)(change);
141
+ switch (changeType) {
142
+ case util_1.ChangeType.CREATE:
143
+ await handleCreateDocument(change.after, eventTimestamp);
144
+ break;
145
+ case util_1.ChangeType.DELETE:
146
+ await handleDeleteDocument(change.before);
147
+ break;
148
+ case util_1.ChangeType.UPDATE:
149
+ await handleUpdateDocument(change.before, change.after, eventTimestamp);
150
+ break;
151
+ default: {
152
+ throw new Error(`Invalid change type: ${changeType}`);
153
+ }
154
+ }
155
+ });
156
+ exports.executeFullIndexOperation = (0, tasks_1.onTaskDispatched)({
157
+ region: config_1.location,
158
+ secrets: [config_1.algoliaApiKey],
159
+ memory: '1GiB',
160
+ timeoutSeconds: 540,
161
+ cpu: 'gcf_gen1',
162
+ retryConfig: {
163
+ maxAttempts: 5,
164
+ minBackoffSeconds: 10, // To let the time for permissions to propagate on first deploy.
165
+ },
166
+ }, async ({ data }) => {
167
+ logs.init();
168
+ logs.info('doFullIndexing', config_1.doFullIndexing.value());
169
+ if (!config_1.doFullIndexing.value()) {
170
+ logs.info('Existing documents were not indexed because DO_FULL_INDEXING is false. ' +
171
+ 'Set it to true and redeploy to run a full reindex.');
172
+ return;
173
+ }
174
+ const collection = config_1.collectionPath.value();
175
+ logs.info('collectionPath', collection);
176
+ const docId = (data ?? {})['docId'] ?? null;
177
+ const pastSuccessCount = (data ?? {})['successCount'] ?? 0;
178
+ const pastErrorCount = (data ?? {})['errorCount'] ?? 0;
179
+ // We also track the start time of the first invocation, so that we can report the full length at the end.
180
+ const startTime = (data ?? {})['startTime'] ?? Date.now();
181
+ let query;
182
+ const isCollectionGroup = (0, util_1.isCollectionGroupPath)(collection);
183
+ logs.info('Is Collection Group?', isCollectionGroup);
184
+ if (isCollectionGroup) {
185
+ query = getDb()
186
+ .collectionGroup(collection.split('/').pop());
187
+ }
188
+ else {
189
+ query = getDb()
190
+ .collection(collection);
191
+ }
192
+ query = query.limit(DOCS_PER_INDEXING);
193
+ logs.debug('docId?', docId);
194
+ if (docId) {
195
+ const queryCursor = query.where(firestore_2.FieldPath.documentId(), '==', docId);
196
+ logs.debug('queryCursor?', queryCursor);
197
+ const querySnapshot = await queryCursor.get();
198
+ logs.debug('querySnapshot?', querySnapshot);
199
+ logs.debug('querySnapshot.docs?', querySnapshot.docs);
200
+ querySnapshot.docs.forEach(doc => query = query.startAfter(doc));
201
+ }
202
+ logs.debug('query', query);
203
+ const snapshot = await query.get();
204
+ const promises = await Promise.allSettled(snapshot.docs.map((doc) => (0, extract_1.default)(doc, startTime)));
205
+ logs.debug('promises.length', promises.length);
206
+ promises.forEach(v => logs.info('v', v));
207
+ const records = promises
208
+ .filter(v => v.status === "fulfilled")
209
+ .map(v => v.value);
210
+ logs.info('records.length', records.length);
211
+ const responses = await (0, exports.getIndex)().saveObjects(records, {
212
+ autoGenerateObjectIDIfNotExist: true,
213
+ });
214
+ logs.debug('responses.objectIDs', responses.objectIDs);
215
+ logs.info('responses.taskIDs', responses.taskIDs);
216
+ const newSuccessCount = pastSuccessCount + records.length;
217
+ const newErrorCount = pastErrorCount;
218
+ if (snapshot.size === DOCS_PER_INDEXING) {
219
+ const newCursor = snapshot.docs[snapshot.size - 1];
220
+ const queue = (0, functions_1.getFunctions)().taskQueue(`locations/${config_1.location.value()}/functions/executeFullIndexOperation`);
221
+ await queue.enqueue({
222
+ docId: isCollectionGroup ? newCursor.ref.path : newCursor.id,
223
+ successCount: newSuccessCount,
224
+ errorCount: newErrorCount,
225
+ startTime: startTime,
226
+ });
227
+ }
228
+ else {
229
+ // No more documents to index, time to set the processing state.
230
+ logs.fullIndexingComplete(newSuccessCount, newErrorCount);
231
+ const elapsed = Date.now() - startTime;
232
+ if (newErrorCount === 0) {
233
+ logs.info(`Successfully indexed ${newSuccessCount} documents in ${elapsed}ms.`);
234
+ }
235
+ else {
236
+ logs.warn(`Indexed ${newSuccessCount} documents, ${newErrorCount} errors in ${elapsed}ms.`);
237
+ }
238
+ }
239
+ });
240
+ // Run a full indexing after the first deployment and after every redeploy
241
+ // (replaces `lifecycleEvents` in extension.yaml).
242
+ (0, lifecycle_1.afterFirstDeploy)({ task: { function: 'executeFullIndexOperation', body: { data: {} } } });
243
+ (0, lifecycle_1.afterRedeploy)({ task: { function: 'executeFullIndexOperation', body: { data: {} } } });
package/lib/logs.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ export declare const obfuscatedConfig: () => {
2
+ location: string;
3
+ algoliaAppId: string;
4
+ algoliaAPIKey: string;
5
+ algoliaIndexName: string;
6
+ databaseId: string;
7
+ collectionPath: string;
8
+ fields: string;
9
+ forceDataSync: string;
10
+ transformFunction: string;
11
+ projectId: string;
12
+ doFullIndexing: boolean;
13
+ altObjectId: string;
14
+ };
15
+ export declare const init: () => void;
16
+ export declare const start: () => void;
17
+ export declare const warn: (...args: any) => void;
18
+ export declare const error: (err: Error) => void;
19
+ export declare const info: (...args: any) => void;
20
+ export declare const debug: (...args: any) => void;
21
+ export declare const createIndex: (id: string, data: object) => void;
22
+ export declare const updateIndex: (id: string, data: object) => void;
23
+ export declare const deleteIndex: (id: string) => void;
24
+ export declare const fieldNotExist: (field: string) => void;
25
+ export declare const fullIndexingComplete: (successCount: number, errorCount: number) => void;
26
+ export declare const enqueueNext: (offset: number) => void;
package/lib/logs.js ADDED
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright 2021 Algolia
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * https://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.enqueueNext = exports.fullIndexingComplete = exports.fieldNotExist = exports.deleteIndex = exports.updateIndex = exports.createIndex = exports.debug = exports.info = exports.error = exports.warn = exports.start = exports.init = exports.obfuscatedConfig = void 0;
19
+ const firebase_functions_1 = require("firebase-functions");
20
+ const params_1 = require("firebase-functions/params");
21
+ const config_1 = require("./config");
22
+ const obfuscatedConfig = () => ({
23
+ location: config_1.location.value(),
24
+ algoliaAppId: config_1.algoliaAppId.value(),
25
+ algoliaAPIKey: '********',
26
+ algoliaIndexName: config_1.algoliaIndexName.value(),
27
+ databaseId: config_1.databaseId.value(),
28
+ collectionPath: config_1.collectionPath.value(),
29
+ fields: config_1.fields.value(),
30
+ forceDataSync: config_1.forceDataSync.value(),
31
+ transformFunction: config_1.transformFunction.value(),
32
+ projectId: params_1.projectID.value(),
33
+ doFullIndexing: config_1.doFullIndexing.value(),
34
+ altObjectId: config_1.altObjectId.value(),
35
+ });
36
+ exports.obfuscatedConfig = obfuscatedConfig;
37
+ const init = () => {
38
+ firebase_functions_1.logger.info('Initializing function kit with configuration', (0, exports.obfuscatedConfig)());
39
+ };
40
+ exports.init = init;
41
+ const start = () => {
42
+ firebase_functions_1.logger.info('Started function execution with configuration', (0, exports.obfuscatedConfig)());
43
+ };
44
+ exports.start = start;
45
+ const warn = (...args) => {
46
+ firebase_functions_1.logger.warn(args);
47
+ };
48
+ exports.warn = warn;
49
+ const error = (err) => {
50
+ firebase_functions_1.logger.error('Error when performing Algolia index', err);
51
+ };
52
+ exports.error = error;
53
+ const info = (...args) => {
54
+ firebase_functions_1.logger.info(args);
55
+ };
56
+ exports.info = info;
57
+ const debug = (...args) => {
58
+ firebase_functions_1.logger.debug(args);
59
+ };
60
+ exports.debug = debug;
61
+ const createIndex = (id, data) => {
62
+ firebase_functions_1.logger.info(`Creating new Algolia index for document ${id}`, data);
63
+ };
64
+ exports.createIndex = createIndex;
65
+ const updateIndex = (id, data) => {
66
+ firebase_functions_1.logger.info(`Updating existing Algolia index for document ${id}`, data);
67
+ };
68
+ exports.updateIndex = updateIndex;
69
+ const deleteIndex = (id) => {
70
+ firebase_functions_1.logger.info(`Deleting existing Algolia index for document ${id}`);
71
+ };
72
+ exports.deleteIndex = deleteIndex;
73
+ const fieldNotExist = (field) => {
74
+ firebase_functions_1.logger.warn(`The field "${field}" was specified in the FIELDS config but was not found on collection data.`);
75
+ };
76
+ exports.fieldNotExist = fieldNotExist;
77
+ const fullIndexingComplete = (successCount, errorCount) => {
78
+ firebase_functions_1.logger.info(`Finished full indexing data. ${successCount} translations succeeded, ${errorCount} errors.`);
79
+ };
80
+ exports.fullIndexingComplete = fullIndexingComplete;
81
+ const enqueueNext = (offset) => {
82
+ firebase_functions_1.logger.info(`About to enqueue next task, starting at offset ${offset}`);
83
+ };
84
+ exports.enqueueNext = enqueueNext;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The data processor will process the Firestore document. It will loop through the fields and process the values.
3
+ * The value can be simple or complex types that are supported by Firestore.
4
+ *
5
+ * @param data
6
+ */
7
+ export declare const dataProcessor: (data: any) => {};
8
+ /**
9
+ * The field processor will process the Firestore document field value.
10
+ *
11
+ * @param field
12
+ * @param value
13
+ */
14
+ export declare const valueProcessor: (field: any, value: any) => any;
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.valueProcessor = exports.dataProcessor = void 0;
4
+ /*
5
+ * Copyright 2021 Algolia
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * https://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+ // eslint-disable-next-line import/no-unresolved
20
+ const firestore_1 = require("firebase-admin/firestore");
21
+ const util_1 = require("./util");
22
+ const processObject = objectVal => {
23
+ const payload = {};
24
+ for (const [key, val] of Object.entries(objectVal)) {
25
+ const [field, value] = processValue(key, val);
26
+ if ((0, util_1.isValidValue)(value)) {
27
+ payload[field] = value;
28
+ }
29
+ }
30
+ return payload;
31
+ };
32
+ const processValue = (field, value) => {
33
+ if (value instanceof firestore_1.DocumentReference) {
34
+ return [field, processDocumentReference(value)];
35
+ }
36
+ else if (value instanceof firestore_1.GeoPoint) {
37
+ // Algolia has a prescribed field name for Geo data.
38
+ return ['_geoloc', processGeoPoint(value)];
39
+ }
40
+ else if (value instanceof firestore_1.Timestamp) {
41
+ return [field, processTimestamp(value)];
42
+ }
43
+ else if (value instanceof Array) {
44
+ return [field, processArray(value)];
45
+ }
46
+ else if (value instanceof Object) {
47
+ return [field, processObject(value)];
48
+ }
49
+ return [field, value];
50
+ };
51
+ const processArray = (arrayVal) => {
52
+ return arrayVal.map((val, index) => {
53
+ if (val instanceof Object) {
54
+ const [_, value] = processValue(index, val);
55
+ return value;
56
+ }
57
+ return val;
58
+ });
59
+ };
60
+ const processTimestamp = (timestampVal) => {
61
+ return timestampVal.toDate().getTime();
62
+ };
63
+ const processDocumentReference = (referenceVal) => {
64
+ return referenceVal.path;
65
+ };
66
+ const processGeoPoint = (geoPointVal) => {
67
+ return {
68
+ lat: geoPointVal.latitude,
69
+ lng: geoPointVal.longitude,
70
+ };
71
+ };
72
+ /**
73
+ * The data processor will process the Firestore document. It will loop through the fields and process the values.
74
+ * The value can be simple or complex types that are supported by Firestore.
75
+ *
76
+ * @param data
77
+ */
78
+ const dataProcessor = data => {
79
+ return processObject(data);
80
+ };
81
+ exports.dataProcessor = dataProcessor;
82
+ /**
83
+ * The field processor will process the Firestore document field value.
84
+ *
85
+ * @param field
86
+ * @param value
87
+ */
88
+ const valueProcessor = (field, value) => {
89
+ return processValue(field, value);
90
+ };
91
+ exports.valueProcessor = valueProcessor;
@@ -0,0 +1,2 @@
1
+ declare const _default: (payload: any) => Promise<any>;
2
+ export default _default;
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright 2021 Algolia
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * https://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ const node_fetch_1 = require("node-fetch");
19
+ const config_1 = require("./config");
20
+ const params_1 = require("firebase-functions/params");
21
+ const logs = require("./logs");
22
+ exports.default = async (payload) => {
23
+ const functionName = config_1.transformFunction.value();
24
+ if (functionName) {
25
+ try {
26
+ const response = await (0, node_fetch_1.default)(`https://${config_1.location.value()}-${params_1.projectID.value()}.cloudfunctions.net/${functionName}`, {
27
+ method: 'post',
28
+ body: JSON.stringify({ data: payload }),
29
+ headers: { 'Content-Type': 'application/json' },
30
+ });
31
+ const data = await response?.json();
32
+ return data.result;
33
+ }
34
+ catch (e) {
35
+ logs.error(e);
36
+ }
37
+ }
38
+ return payload;
39
+ };
package/lib/util.d.ts ADDED
@@ -0,0 +1,31 @@
1
+ import { Change } from 'firebase-functions';
2
+ import { DocumentSnapshot } from 'firebase-admin/firestore';
3
+ export declare enum ChangeType {
4
+ CREATE = 0,
5
+ DELETE = 1,
6
+ UPDATE = 2
7
+ }
8
+ export declare const getChangeType: (change: Change<DocumentSnapshot>) => ChangeType;
9
+ export declare const getObjectID: (snapshot: DocumentSnapshot) => string;
10
+ export declare const getObjectSizeInBytes: (object: [] | {}) => number;
11
+ export declare const getFields: (fields: string) => string[];
12
+ export declare const areFieldsUpdated: (before: DocumentSnapshot, after: DocumentSnapshot) => boolean;
13
+ /** Accepts `true` and `yes` (extension value), so old configs keep working. */
14
+ export declare const isEnabled: (value: string | undefined) => boolean;
15
+ export declare const isValidValue: (value: any) => boolean;
16
+ /**
17
+ * Determines if a collection path represents a collection group query by checking for wildcard patterns.
18
+ *
19
+ * Collection group queries use wildcard syntax like "users/{userId}/posts" to query
20
+ * all subcollections with a given name across the database:
21
+ * - "users/{userId}/posts" → queries all "posts" subcollections across all users
22
+ * - "organizations/{orgId}/members" → queries all "members" subcollections
23
+ *
24
+ * Specific paths like "organizations/acme/members" should NOT be treated as collection groups:
25
+ * - "posts" → top-level collection
26
+ * - "organizations/acme/members" → specific subcollection under a specific document
27
+ *
28
+ * @param collectionPath - The configured collection path
29
+ * @returns true if the path contains wildcard patterns (e.g., {userId}), false otherwise
30
+ */
31
+ export declare const isCollectionGroupPath: (collectionPath: string) => boolean;
package/lib/util.js ADDED
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright 2021 Algolia
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * https://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.isCollectionGroupPath = exports.isValidValue = exports.isEnabled = exports.areFieldsUpdated = exports.getFields = exports.getObjectSizeInBytes = exports.getObjectID = exports.getChangeType = exports.ChangeType = void 0;
19
+ const config_1 = require("./config");
20
+ const logs = require("./logs");
21
+ const processors_1 = require("./processors");
22
+ var ChangeType;
23
+ (function (ChangeType) {
24
+ ChangeType[ChangeType["CREATE"] = 0] = "CREATE";
25
+ ChangeType[ChangeType["DELETE"] = 1] = "DELETE";
26
+ ChangeType[ChangeType["UPDATE"] = 2] = "UPDATE";
27
+ })(ChangeType || (exports.ChangeType = ChangeType = {}));
28
+ const getChangeType = (change) => {
29
+ if (!change.after.exists) {
30
+ return ChangeType.DELETE;
31
+ }
32
+ if (!change.before.exists) {
33
+ return ChangeType.CREATE;
34
+ }
35
+ return ChangeType.UPDATE;
36
+ };
37
+ exports.getChangeType = getChangeType;
38
+ const getObjectID = (snapshot) => {
39
+ const altId = config_1.altObjectId.value();
40
+ return altId ? altId === '(path)' ? snapshot.ref.path : snapshot.get(altId) : snapshot.id;
41
+ };
42
+ exports.getObjectID = getObjectID;
43
+ const getObjectSizeInBytes = (object) => {
44
+ const recordBuffer = Buffer.from(JSON.stringify(object));
45
+ return recordBuffer.byteLength;
46
+ };
47
+ exports.getObjectSizeInBytes = getObjectSizeInBytes;
48
+ const getFields = (fields) => fields ? fields.split(/[ ,]+/) : [];
49
+ exports.getFields = getFields;
50
+ const areFieldsUpdated = (before, after) => {
51
+ const fields = (0, exports.getFields)(config_1.fields.value());
52
+ logs.debug(`fields: ${fields}`);
53
+ // If fields are not configured, then execute update record.
54
+ if (fields.length === 0) {
55
+ return true;
56
+ }
57
+ // If fields are configured, then check the before and after data for the specified fields.
58
+ // If any changes detected, then execute update record.
59
+ for (const field of fields) {
60
+ const [, beforeFieldValue] = (0, processors_1.valueProcessor)(field, before.get(field));
61
+ const [, afterFieldValue] = (0, processors_1.valueProcessor)(field, after.get(field));
62
+ if (JSON.stringify(beforeFieldValue) !== JSON.stringify(afterFieldValue)) {
63
+ return true;
64
+ }
65
+ }
66
+ return false;
67
+ };
68
+ exports.areFieldsUpdated = areFieldsUpdated;
69
+ /** Accepts `true` and `yes` (extension value), so old configs keep working. */
70
+ const isEnabled = (value) => ['true', 'yes'].includes((value ?? '').trim().toLowerCase());
71
+ exports.isEnabled = isEnabled;
72
+ const isValidValue = (value) => {
73
+ return typeof value !== undefined && value !== null;
74
+ };
75
+ exports.isValidValue = isValidValue;
76
+ /**
77
+ * Determines if a collection path represents a collection group query by checking for wildcard patterns.
78
+ *
79
+ * Collection group queries use wildcard syntax like "users/{userId}/posts" to query
80
+ * all subcollections with a given name across the database:
81
+ * - "users/{userId}/posts" → queries all "posts" subcollections across all users
82
+ * - "organizations/{orgId}/members" → queries all "members" subcollections
83
+ *
84
+ * Specific paths like "organizations/acme/members" should NOT be treated as collection groups:
85
+ * - "posts" → top-level collection
86
+ * - "organizations/acme/members" → specific subcollection under a specific document
87
+ *
88
+ * @param collectionPath - The configured collection path
89
+ * @returns true if the path contains wildcard patterns (e.g., {userId}), false otherwise
90
+ */
91
+ const isCollectionGroupPath = (collectionPath) => {
92
+ // Check for wildcard patterns like {userId}, {docId}, etc.
93
+ return /\{[^}]+\}/.test(collectionPath);
94
+ };
95
+ exports.isCollectionGroupPath = isCollectionGroupPath;
@@ -0,0 +1 @@
1
+ export declare const version = "1.3.0";
package/lib/version.js ADDED
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.version = void 0;
4
+ exports.version = '1.3.0';
package/package.json CHANGED
@@ -1,6 +1,64 @@
1
1
  {
2
2
  "name": "@algolia/firestore-search",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.0.0-rc.0",
4
+ "description": "Index Cloud Firestore collection to Algolia (2nd Gen Cloud Functions kit)",
5
+ "scripts": {
6
+ "build": "npm run clean && npm test && npm run compile",
7
+ "clean": "rimraf lib",
8
+ "compile": "tsc",
9
+ "lint": "pretty-quick --staged && lint-staged",
10
+ "test": "jest --coverage",
11
+ "prepublishOnly": "npm run build",
12
+ "prepack": "npm run clean && npm run compile"
13
+ },
14
+ "main": "lib/index.js",
15
+ "license": "Apache-2.0",
16
+ "types": "lib/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./lib/index.d.ts",
20
+ "default": "./lib/index.js"
21
+ }
22
+ },
23
+ "files": [
24
+ "lib",
25
+ "README.md",
26
+ "LICENSE"
27
+ ],
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
31
+ "engines": {
32
+ "node": ">=22"
33
+ },
34
+ "dependencies": {
35
+ "algoliasearch": "^4.23.3",
36
+ "firebase-admin": "^14.2.0",
37
+ "firebase-functions": "^7.4.0",
38
+ "node-fetch": "^2.7.0"
39
+ },
40
+ "devDependencies": {
41
+ "@babel/preset-typescript": "^7.24.1",
42
+ "@types/jest": "^27.5.2",
43
+ "@types/js-yaml": "^4.0.8",
44
+ "@types/node": "^24.0.0",
45
+ "@typescript-eslint/eslint-plugin": "^5.62.0",
46
+ "@typescript-eslint/parser": "^5.62.0",
47
+ "eslint": "^8.57.0",
48
+ "eslint-config-prettier": "^8.10.0",
49
+ "eslint-plugin-import": "^2.29.1",
50
+ "eslint-plugin-prettier": "^4.2.1",
51
+ "firebase-admin": "^13.0.0",
52
+ "firebase-functions-test": "^3.5.0",
53
+ "jest": "^29.7.0",
54
+ "jest-mock": "^29.7.0",
55
+ "lint-staged": "^13.3.0",
56
+ "mocked-env": "^1.3.5",
57
+ "prettier": "^2.8.8",
58
+ "pretty-quick": "^3.3.1",
59
+ "rimraf": "^4.4.1",
60
+ "ts-jest": "^29.1.2",
61
+ "ts-node": "^10.9.2",
62
+ "typescript": "^5.4.0"
63
+ }
64
+ }