@rebasepro/firebase 0.0.1-canary.2 → 0.0.1-canary.eb08332

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 (47) hide show
  1. package/README.md +97 -3
  2. package/dist/components/FirebaseLoginView.d.ts +3 -3
  3. package/dist/components/RebaseFirebaseApp.d.ts +2 -1
  4. package/dist/components/RebaseFirebaseAppProps.d.ts +9 -13
  5. package/dist/components/social_icons.d.ts +6 -6
  6. package/dist/hooks/index.d.ts +3 -1
  7. package/dist/hooks/useAppCheck.d.ts +2 -2
  8. package/dist/hooks/useBuildUserManagement.d.ts +78 -0
  9. package/dist/hooks/useFirebaseAccessGate.d.ts +44 -0
  10. package/dist/hooks/useFirebaseAuthController.d.ts +2 -2
  11. package/dist/hooks/useFirebaseRealTimeDBDelegate.d.ts +2 -2
  12. package/dist/hooks/useFirebaseStorageSource.d.ts +1 -1
  13. package/dist/hooks/{useFirestoreDataSource.d.ts → useFirestoreDriver.d.ts} +9 -9
  14. package/dist/index.es.js +2598 -2663
  15. package/dist/index.es.js.map +1 -1
  16. package/dist/index.umd.js +2704 -2702
  17. package/dist/index.umd.js.map +1 -1
  18. package/dist/types/auth.d.ts +2 -2
  19. package/dist/types/text_search.d.ts +3 -3
  20. package/dist/utils/algolia.d.ts +7 -6
  21. package/dist/utils/collections_firestore.d.ts +4 -4
  22. package/package.json +75 -65
  23. package/src/components/FirebaseLoginView.tsx +53 -50
  24. package/src/components/RebaseFirebaseApp.tsx +82 -56
  25. package/src/components/RebaseFirebaseAppProps.tsx +10 -24
  26. package/src/components/social_icons.tsx +8 -8
  27. package/src/hooks/index.ts +3 -1
  28. package/src/hooks/useAppCheck.ts +5 -5
  29. package/src/hooks/useBuildUserManagement.tsx +366 -0
  30. package/src/hooks/useFirebaseAccessGate.tsx +145 -0
  31. package/src/hooks/useFirebaseAuthController.ts +6 -8
  32. package/src/hooks/useFirebaseRealTimeDBDelegate.ts +70 -79
  33. package/src/hooks/useFirebaseStorageSource.ts +23 -25
  34. package/src/hooks/useFirestoreDriver.ts +812 -0
  35. package/src/hooks/useInitialiseFirebase.ts +2 -2
  36. package/src/types/auth.tsx +2 -2
  37. package/src/types/text_search.ts +3 -3
  38. package/src/utils/algolia.ts +6 -9
  39. package/src/utils/collections_firestore.ts +25 -29
  40. package/src/utils/database.ts +2 -2
  41. package/src/utils/local_text_search_controller.ts +12 -12
  42. package/src/utils/pinecone.ts +3 -3
  43. package/src/utils/rebase_search_controller.ts +23 -22
  44. package/src/utils/text_search_controller.ts +2 -2
  45. package/dist/social_icons.d.ts +0 -6
  46. package/src/hooks/useFirestoreDataSource.ts +0 -796
  47. package/src/social_icons.tsx +0 -135
@@ -0,0 +1,812 @@
1
+ import { DataDriver, DeleteProps, CollectionConfig, EntityReference, FetchCollectionProps, FetchOneProps, FilterCombination, FilterValues, GeoPoint, ListenCollectionProps, ListenOneProps, SaveProps, WhereFilterOp } from "@rebasepro/types";
2
+ import { User } from "@firebase/auth";
3
+ import {
4
+ collection as collectionClause,
5
+ CollectionReference,
6
+ deleteDoc,
7
+ deleteField,
8
+ doc,
9
+ DocumentReference,
10
+ DocumentSnapshot,
11
+ Firestore,
12
+ GeoPoint as FirestoreGeoPoint,
13
+ getCountFromServer,
14
+ getDoc,
15
+ getDocs,
16
+ getFirestore,
17
+ limit as limitClause,
18
+ onSnapshot,
19
+ orderBy as orderByClause,
20
+ Query,
21
+ query,
22
+ QueryConstraint,
23
+ serverTimestamp,
24
+ setDoc,
25
+ startAfter as startAfterClause,
26
+ Timestamp,
27
+ VectorValue,
28
+ vector,
29
+ where as whereClause
30
+ } from "@firebase/firestore";
31
+ import type { FieldValue } from "@firebase/firestore";
32
+ import { FirebaseApp } from "@firebase/app";
33
+ import { FirestoreTextSearchController, FirestoreTextSearchControllerBuilder } from "../types/text_search";
34
+ import { useCallback, useEffect, useMemo, useRef } from "react";
35
+ import { localSearchControllerBuilder } from "../utils";
36
+ import { getAuth } from "@firebase/auth";
37
+
38
+ /**
39
+ * @group Firebase
40
+ */
41
+ export interface FirestoreDataDriverProps {
42
+ firebaseApp?: FirebaseApp,
43
+ /**
44
+ * You can use this controller to return a list of ids from a search index, given a
45
+ * `path` and a `searchString`.
46
+ */
47
+ textSearchControllerBuilder?: FirestoreTextSearchControllerBuilder,
48
+
49
+ /**
50
+ * Fallback to local text search if no text search controller is specified,
51
+ * or if the controller does not support the given path.
52
+ */
53
+ localTextSearchEnabled?: boolean,
54
+
55
+ /**
56
+ * Use this builder to indicate which indexes are available in your
57
+ * Firestore database. This is used to allow filtering and sorting
58
+ * for multiple fields in the CMS.
59
+ */
60
+ firestoreIndexesBuilder?: FirestoreIndexesBuilder;
61
+ }
62
+
63
+ export type FirestoreIndexesBuilder = (params: {
64
+ path: string,
65
+ collection: CollectionConfig<any>,
66
+ }) => FilterCombination<string>[] | undefined
67
+
68
+ export type FirestoreDataDriver = DataDriver & {
69
+
70
+ initTextSearch: (props: {
71
+ path: string,
72
+ databaseId?: string,
73
+ collection?: CollectionConfig
74
+ }) => Promise<boolean>,
75
+ }
76
+
77
+ /**
78
+ * Use this hook to build a {@link DataDriver} based on Firestore
79
+ * @param firebaseApp
80
+ * @param textSearchControllerBuilder
81
+ * @group Firebase
82
+ */
83
+ export function useFirestoreDriver({
84
+ firebaseApp,
85
+ textSearchControllerBuilder,
86
+ firestoreIndexesBuilder,
87
+ localTextSearchEnabled
88
+ }: FirestoreDataDriverProps): FirestoreDataDriver {
89
+
90
+ const searchControllerRef = useRef<FirestoreTextSearchController>(undefined);
91
+
92
+ useEffect(() => {
93
+ if (!searchControllerRef.current && firebaseApp) {
94
+ if ((textSearchControllerBuilder || localTextSearchEnabled) && !searchControllerRef.current) {
95
+ searchControllerRef.current = buildTextSearchControllerWithLocalSearch({
96
+ firebaseApp,
97
+ textSearchControllerBuilder,
98
+ localTextSearchEnabled: localTextSearchEnabled ?? false
99
+ });
100
+ }
101
+ }
102
+ }, [firebaseApp, localTextSearchEnabled, textSearchControllerBuilder]);
103
+
104
+ const buildQuery = useCallback(<M>(path: string,
105
+ filter: FilterValues<Extract<keyof M, string>> | undefined,
106
+ orderBy: string | undefined,
107
+ order: "desc" | "asc" | undefined,
108
+ startAfter: unknown[] | undefined,
109
+ limit: number | undefined,
110
+ databaseId?: string) => {
111
+
112
+ if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
113
+
114
+ const firestore = databaseId ? getFirestore(firebaseApp, databaseId) : getFirestore(firebaseApp);
115
+ const collectionReference: Query = collectionClause(firestore, path);
116
+
117
+ const queryParams: QueryConstraint[] = [];
118
+ if (filter) {
119
+ Object.entries(filter)
120
+ .filter(([_, entry]) => !!entry)
121
+ .forEach(([key, filterParameter]) => {
122
+ const [op, value] = filterParameter as [WhereFilterOp, any];
123
+
124
+ // Null-testing operators map to Firestore's == / != against null.
125
+ if (op === "is-null") {
126
+ queryParams.push(whereClause(key, "==", null));
127
+ return;
128
+ }
129
+ if (op === "is-not-null") {
130
+ queryParams.push(whereClause(key, "!=", null));
131
+ return;
132
+ }
133
+
134
+ // Firestore has no LIKE/ILIKE — fail loudly rather than silently
135
+ // returning wrong results. Use `searchString` / a search index instead.
136
+ if (op === "like" || op === "ilike" || op === "not-like" || op === "not-ilike") {
137
+ throw new Error(
138
+ `Firestore does not support the "${op}" operator (SQL pattern matching). ` +
139
+ "Use a full-text search index or the collection's searchString instead."
140
+ );
141
+ }
142
+
143
+ queryParams.push(whereClause(key, op, cmsToFirestoreModel(value, firestore)));
144
+ });
145
+ }
146
+
147
+ if (orderBy && order) {
148
+ queryParams.push(orderByClause(orderBy, order));
149
+ }
150
+
151
+ if (startAfter) {
152
+ queryParams.push(startAfterClause(startAfter));
153
+ }
154
+
155
+ if (limit) {
156
+ queryParams.push(limitClause(limit));
157
+ }
158
+
159
+ return query(collectionReference, ...queryParams);
160
+ }, [firebaseApp]);
161
+
162
+ const getAndBuildEntity = useCallback((path: string,
163
+ id: string | number,
164
+ databaseId?: string
165
+ ): Promise<Record<string, unknown> | undefined> => {
166
+ if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
167
+
168
+ const firestore = databaseId ? getFirestore(firebaseApp, databaseId) : getFirestore(firebaseApp);
169
+
170
+ return getDoc(doc(firestore, path, String(id)))
171
+ .then((docEntity) => {
172
+ if (!docEntity.exists()) {
173
+ return undefined;
174
+ }
175
+ return createRowFromDocument(docEntity);
176
+ });
177
+ }, [firebaseApp]);
178
+
179
+ const listenOne = useCallback(<M extends Record<string, any>>(
180
+ {
181
+ path,
182
+ id,
183
+ collection,
184
+ onUpdate,
185
+ onError
186
+ }: ListenOneProps<M>): () => void => {
187
+ if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
188
+
189
+ const databaseId = collection?.databaseId;
190
+ const firestore = databaseId ? getFirestore(firebaseApp, databaseId) : getFirestore(firebaseApp);
191
+ const resolvedPath = path;
192
+
193
+ return onSnapshot(
194
+ doc(firestore, resolvedPath, String(id)),
195
+ {
196
+ next: (docEntity) => {
197
+ onUpdate(docEntity.exists() ? createRowFromDocument(docEntity) : null);
198
+ },
199
+ error: onError
200
+ }
201
+ );
202
+ }, [firebaseApp]);
203
+
204
+ const performTextSearch = useCallback(<M extends Record<string, any>>({
205
+ path,
206
+ databaseId,
207
+ searchString,
208
+ onUpdate
209
+ }: {
210
+ path: string,
211
+ databaseId?: string,
212
+ searchString: string;
213
+ onUpdate: (rows: Record<string, unknown>[]) => void,
214
+ }): () => void => {
215
+
216
+ if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
217
+
218
+ const textSearchController = searchControllerRef.current;
219
+ if (!textSearchController)
220
+ throw Error("Trying to make text search without specifying a FirestoreTextSearchController");
221
+
222
+ let subscriptions: (() => void)[] = [];
223
+
224
+
225
+ const auth = getAuth(firebaseApp);
226
+ const currentUser = auth?.currentUser;
227
+
228
+ const search = textSearchController.search({
229
+ path,
230
+ searchString,
231
+ currentUser: currentUser ?? undefined,
232
+ databaseId
233
+ });
234
+
235
+ if (!search) {
236
+ throw Error("The current path is not supported by the specified FirestoreTextSearchController");
237
+ }
238
+
239
+ search.then((ids) => {
240
+ if (!ids || ids.length === 0) {
241
+ subscriptions = [];
242
+ onUpdate([]);
243
+ }
244
+
245
+ const rows: Record<string, unknown>[] = [];
246
+ const addedEntitiesSet = new Set<string | number>();
247
+ subscriptions = (ids ?? [])
248
+ .map((id) => {
249
+ return listenOne({
250
+ path,
251
+ id,
252
+ onUpdate: (row: Record<string, unknown> | null) => {
253
+ const incomingId = row?.id as string | number | undefined;
254
+ if (row && incomingId !== undefined) {
255
+ if (!addedEntitiesSet.has(incomingId)) {
256
+ addedEntitiesSet.add(incomingId);
257
+ rows.push(row);
258
+ onUpdate(rows);
259
+ }
260
+ } else {
261
+ addedEntitiesSet.delete(id);
262
+ onUpdate([...rows.filter(r => r.id !== id)])
263
+ }
264
+ }
265
+ })
266
+ }
267
+ );
268
+ });
269
+
270
+ return () => {
271
+ subscriptions.forEach((p) => p());
272
+ }
273
+
274
+ }, [firebaseApp, listenOne]);
275
+
276
+ const initTextSearch = useCallback(async (props: {
277
+ path: string,
278
+ databaseId?: string,
279
+ collection?: CollectionConfig
280
+ }) => {
281
+ console.debug("Init text search controller", searchControllerRef.current, props.path);
282
+ if (!searchControllerRef.current) {
283
+ console.warn("You are trying to use text search, but have not provided a text search controller in `useFirestoreDriver`. You can also set the flag `localTextSearchEnabled` to use local search in `useFirestoreDriver`. Local text search can incur in performance issues and higher costs for large datasets.");
284
+ return false;
285
+ }
286
+ try {
287
+ return searchControllerRef.current.init(props);
288
+ } catch (e) {
289
+ console.error("Error initializing text search controller", e);
290
+ return false;
291
+ }
292
+ }, []);
293
+
294
+ /**
295
+ * Fetch entities in a Firestore path
296
+ * @param path
297
+ * @param collection
298
+ * @param filter
299
+ * @param limit
300
+ * @param startAfter
301
+ * @param searchString
302
+ * @param orderBy
303
+ * @param order
304
+ * @return Function to cancel subscription
305
+ * @see useCollection if you need this functionality implemented as a hook
306
+ * @group Firestore
307
+ */
308
+ const fetchCollection = useCallback(async <M extends Record<string, any>>({
309
+ path,
310
+ filter,
311
+ limit,
312
+ startAfter,
313
+ searchString,
314
+ orderBy,
315
+ order,
316
+ collection
317
+ }: FetchCollectionProps<M>
318
+ ): Promise<Record<string, unknown>[]> => {
319
+
320
+ const databaseId = collection?.databaseId;
321
+
322
+ const resolvedPath = path;
323
+
324
+ console.debug("Fetching collection", {
325
+ path,
326
+ limit,
327
+ filter,
328
+ startAfter,
329
+ orderBy,
330
+ order
331
+ });
332
+ const query = buildQuery(resolvedPath, filter, orderBy, order, startAfter as unknown[] | undefined, limit, databaseId);
333
+
334
+ const entity = await getDocs(query);
335
+ return entity.docs.map((doc) => createRowFromDocument(doc));
336
+ }, [buildQuery]);
337
+
338
+ /**
339
+ * Listen to a entities in a given path
340
+ * @param path
341
+ * @param collection
342
+ * @param onError
343
+ * @param filter
344
+ * @param limit
345
+ * @param startAfter
346
+ * @param searchString
347
+ * @param orderBy
348
+ * @param order
349
+ * @param onUpdate
350
+ * @return Function to cancel subscription
351
+ * @see useCollection if you need this functionality implemented as a hook
352
+ * @group Firestore
353
+ */
354
+ const listenCollection = useCallback(<M extends Record<string, any>>(
355
+ {
356
+ path,
357
+ filter,
358
+ limit,
359
+ startAfter,
360
+ searchString,
361
+ orderBy,
362
+ order,
363
+ onUpdate,
364
+ onError,
365
+ collection
366
+ }: ListenCollectionProps<M>
367
+ ): () => void => {
368
+
369
+ console.debug("Listening collection", {
370
+ path,
371
+ searchString,
372
+ limit,
373
+ filter,
374
+ startAfter,
375
+ orderBy,
376
+ order,
377
+ collection
378
+ });
379
+
380
+ if (!firebaseApp) {
381
+ throw Error("useFirestoreDriver Firebase not initialised");
382
+ }
383
+
384
+ const databaseId = collection?.databaseId;
385
+
386
+ if (searchString) {
387
+ return performTextSearch<M>({
388
+ path,
389
+ searchString,
390
+ onUpdate,
391
+ databaseId
392
+ });
393
+ }
394
+
395
+ const resolvedPath = path;
396
+ console.debug("Resolved path for listening", {
397
+ path,
398
+ resolvedPath
399
+ });
400
+ const query = buildQuery(resolvedPath, filter, orderBy, order, startAfter as unknown[] | undefined, limit, databaseId);
401
+ return onSnapshot(query,
402
+ {
403
+ next: (entity) => {
404
+ if (!searchString)
405
+ onUpdate(entity.docs.map((doc) => createRowFromDocument(doc)));
406
+ },
407
+ error: onError
408
+ }
409
+ );
410
+
411
+ }, [buildQuery, firebaseApp, performTextSearch]);
412
+
413
+ /**
414
+ * Retrieve a entity given a path and a collection
415
+ * @param path
416
+ * @param id
417
+ * @param collection
418
+ * @group Firestore
419
+ */
420
+ const fetchOne = useCallback(<M extends Record<string, any>>({
421
+ path,
422
+ id,
423
+ collection
424
+ }: FetchOneProps<M>
425
+ ): Promise<Record<string, unknown> | undefined> => {
426
+ const resolvedPath = path;
427
+ return getAndBuildEntity(resolvedPath, id, collection?.databaseId);
428
+ }, [getAndBuildEntity]);
429
+
430
+ /**
431
+ * Save entity to the specified path. Note that Firestore does not allow
432
+ * undefined values.
433
+ * @param path
434
+ * @param id
435
+ * @param values
436
+ * @param schemaId
437
+ * @param collection
438
+ * @param status
439
+ * @group Firestore
440
+ */
441
+ const save = useCallback(<M extends Record<string, any>>(
442
+ {
443
+ path,
444
+ id,
445
+ values: valuesProp,
446
+ collection,
447
+ status
448
+ }: SaveProps<M>): Promise<Record<string, unknown>> => {
449
+
450
+ if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
451
+
452
+ console.debug("1", {
453
+ path,
454
+ id,
455
+ values: valuesProp,
456
+ collection
457
+ })
458
+ const values = cmsToFirestoreModel(valuesProp, getFirestore(firebaseApp));
459
+
460
+ console.debug("2", {
461
+ path,
462
+ id,
463
+ values: valuesProp,
464
+ collection
465
+ })
466
+ const databaseId = collection?.databaseId;
467
+ const firestore = databaseId ? getFirestore(firebaseApp, databaseId) : getFirestore(firebaseApp);
468
+ const resolvedPath = path;
469
+
470
+ const collectionReference: CollectionReference = collectionClause(firestore, path);
471
+ console.debug("Saving entity", {
472
+ path,
473
+ id,
474
+ values,
475
+ databaseId
476
+ });
477
+
478
+ let documentReference: DocumentReference;
479
+ if (id) {
480
+ documentReference = doc(collectionReference, String(id));
481
+ } else {
482
+ documentReference = doc(collectionReference);
483
+ }
484
+ return setDoc(documentReference, values as Record<string, unknown>, { merge: true })
485
+ .then(() => {
486
+ return {
487
+ ...(firestoreToCMSModel(values) as Record<string, unknown>),
488
+ id: documentReference.id
489
+ };
490
+ })
491
+ .catch((error) => {
492
+ console.error("Error saving entity", error);
493
+ throw error;
494
+
495
+ });
496
+ }, [firebaseApp]);
497
+
498
+ /**
499
+ * Delete a entity
500
+ * @param entity
501
+ * @param collection
502
+ * @group Firestore
503
+ */
504
+ const deleteOne = useCallback(<M extends Record<string, any>>(
505
+ {
506
+ row,
507
+ collection
508
+ }: DeleteProps<M>
509
+ ): Promise<void> => {
510
+ if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
511
+
512
+ const databaseId = collection?.databaseId;
513
+ const firestore = databaseId ? getFirestore(firebaseApp, databaseId) : getFirestore(firebaseApp);
514
+
515
+ return deleteDoc(doc(firestore, row.path, String(row.id)));
516
+ }, [firebaseApp]);
517
+
518
+ /**
519
+ * Check if the given property is unique in the given collection
520
+ * @param path Collection path
521
+ * @param name of the property
522
+ * @param value
523
+ * @param property
524
+ * @param id
525
+ * @return `true` if there are no other fields besides the given entity
526
+ * @group Firestore
527
+ */
528
+ const checkUniqueField = useCallback(async (
529
+ path: string,
530
+ name: string,
531
+ value: unknown,
532
+ id?: string | number,
533
+ collection?: CollectionConfig<any>
534
+ ): Promise<boolean> => {
535
+
536
+ if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
537
+
538
+ const databaseId = collection?.databaseId;
539
+ const firestore = databaseId ? getFirestore(firebaseApp, databaseId) : getFirestore(firebaseApp);
540
+
541
+ if (value === undefined || value === null) {
542
+ return Promise.resolve(true);
543
+ }
544
+ const q = query(collectionClause(firestore, path), whereClause(name, "==", cmsToFirestoreModel(value, firestore)));
545
+ const entity = await getDocs(q);
546
+ return entity.docs.filter(doc => doc.id !== id).length === 0;
547
+
548
+ }, [firebaseApp]);
549
+
550
+ const count = useCallback(async ({
551
+ path,
552
+ filter,
553
+ order,
554
+ orderBy,
555
+ collection
556
+ }: FetchCollectionProps<any>): Promise<number> => {
557
+ if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
558
+ const databaseId = collection?.databaseId;
559
+ const resolvedPath = path;
560
+ const query = buildQuery(resolvedPath, filter, orderBy, order, undefined, undefined, databaseId);
561
+ const entity = await getCountFromServer(query);
562
+ return entity.data().count;
563
+ }, [firebaseApp]);
564
+
565
+ const isFilterCombinationValid = useCallback(({
566
+ path,
567
+ collection,
568
+ filterValues,
569
+ sortBy
570
+ }: {
571
+ path: string,
572
+ collection: CollectionConfig<any>,
573
+ filterValues: FilterValues<any>,
574
+ sortBy?: [string, "asc" | "desc"],
575
+ }): boolean => {
576
+
577
+ if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
578
+
579
+ // If no indexes are defined, we assume the query is valid.
580
+ // If there is no index in Firestore, and error message will be shown
581
+ if (firestoreIndexesBuilder === undefined) return true;
582
+ const resolvedPath = path;
583
+
584
+ const indexes = firestoreIndexesBuilder?.({
585
+ path: resolvedPath,
586
+ collection
587
+ });
588
+
589
+ const sortKey = sortBy ? sortBy[0] : undefined;
590
+ const sortDirection = sortBy ? sortBy[1] : undefined;
591
+
592
+ // Order by clause cannot contain a field with an equality filter
593
+ const values: [WhereFilterOp, any][] = Object.values(filterValues) as [WhereFilterOp, any][];
594
+
595
+ const filterKeys = Object.keys(filterValues);
596
+ const filtersCount = filterKeys.length;
597
+
598
+ if (!sortKey && values.every((v) => v[0] === "==")) {
599
+ return true;
600
+ }
601
+
602
+ if (filtersCount === 1 && (!sortKey || sortKey === filterKeys[0])) {
603
+ return true;
604
+ }
605
+
606
+ if (!indexes && filtersCount > 1) {
607
+ return false;
608
+ }
609
+
610
+ return !!indexes && indexes
611
+ .filter((compositeIndex) => !sortKey || sortKey in compositeIndex)
612
+ .find((compositeIndex) =>
613
+ Object.entries(filterValues).every(([key, value]) => compositeIndex[key] !== undefined && (!sortDirection || compositeIndex[key] === sortDirection))
614
+ ) !== undefined;
615
+ }, [firebaseApp]);
616
+
617
+ return useMemo(() => ({
618
+ key: "firestore" as const,
619
+ currentTime,
620
+ initialised: Boolean(firebaseApp),
621
+ initTextSearch,
622
+ fetchCollection,
623
+ listenCollection,
624
+ fetchOne,
625
+ listenOne,
626
+ save,
627
+ delete: deleteOne,
628
+ checkUniqueField,
629
+ count,
630
+ isFilterCombinationValid
631
+ }), [
632
+ firebaseApp,
633
+ initTextSearch,
634
+ fetchCollection,
635
+ listenCollection,
636
+ fetchOne,
637
+ listenOne,
638
+ save,
639
+ deleteOne,
640
+ checkUniqueField,
641
+ count,
642
+ isFilterCombinationValid
643
+ ]);
644
+
645
+ }
646
+
647
+ const createRowFromDocument = (
648
+ docSnap: DocumentSnapshot
649
+ ): Record<string, unknown> => {
650
+ const values = firestoreToCMSModel(docSnap.data()) as Record<string, unknown>;
651
+ return {
652
+ ...values,
653
+ // Spread the canonical document id last so it wins over a literal `id` field
654
+ id: docSnap.id
655
+ };
656
+ };
657
+
658
+ /**
659
+ * Recursive function that converts Firestore data types into CMS or plain
660
+ * JS types.
661
+ * Rebase uses Javascript dates internally instead of Firestore timestamps.
662
+ * This makes it easier to interact with the rest of the libraries and
663
+ * bindings.
664
+ * Also, Firestore references are replaced with {@link EntityReference}
665
+ * @param data
666
+ * @group Firestore
667
+ */
668
+ export function firestoreToCMSModel(data: unknown): unknown {
669
+ if (data === null || data === undefined) return null;
670
+ if (typeof data === "object" && data !== null && "isEqual" in data && typeof (data as FieldValue).isEqual === "function" && deleteField().isEqual(data as FieldValue)) {
671
+ return undefined;
672
+ }
673
+ if (typeof data === "object" && data !== null && "isEqual" in data && typeof (data as FieldValue).isEqual === "function" && serverTimestamp().isEqual(data as FieldValue)) {
674
+ return null;
675
+ }
676
+ if (data instanceof Timestamp || (typeof data === "object" && data !== null && "toDate" in data && typeof (data as Record<string, unknown>).toDate === "function" && ((data as Record<string, unknown>).toDate as () => unknown)() instanceof Date)) {
677
+ return (data as { toDate: () => Date }).toDate();
678
+ }
679
+ if (data instanceof Date) {
680
+ return data;
681
+ }
682
+ if (typeof data === "object" && "__type__" in data && data.__type__ === "__vector__") {
683
+ return data; // already translated
684
+ }
685
+ if (data instanceof VectorValue || (typeof data === "object" && data !== null && "toArray" in data && typeof (data as Record<string, unknown>).toArray === "function" && (data as { constructor?: { name?: string } }).constructor?.name === "VectorValue")) {
686
+ return { __type__: "__vector__",
687
+ value: (data as { toArray: () => number[] }).toArray() };
688
+ }
689
+
690
+ if (data instanceof FirestoreGeoPoint) {
691
+ return new GeoPoint(data.latitude, data.longitude);
692
+ }
693
+ if (data instanceof DocumentReference) {
694
+ const databaseId = (data?.firestore as unknown as { _databaseId?: { database?: string } })?._databaseId?.database;
695
+ return new EntityReference({ id: data.id,
696
+ path: getCMSPathFromFirestorePath(data.path),
697
+ databaseId });
698
+ }
699
+ if (Array.isArray(data)) {
700
+ return data.map(firestoreToCMSModel).filter(v => v !== undefined);
701
+ }
702
+ if (typeof data === "object") {
703
+ const result: Record<string, unknown> = {};
704
+ for (const key of Object.keys(data)) {
705
+ const childValue = firestoreToCMSModel((data as Record<string, unknown>)[key]);
706
+ if (childValue !== undefined)
707
+ result[key] = childValue;
708
+ }
709
+ return result;
710
+ }
711
+ return data;
712
+ }
713
+
714
+ /**
715
+ * Remove id from Firestore path
716
+ * @param fsPath
717
+ */
718
+ function getCMSPathFromFirestorePath(fsPath: string): string {
719
+ let to = fsPath.lastIndexOf("/");
720
+ to = to === -1 ? fsPath.length : to;
721
+ return fsPath.substring(0, to);
722
+ }
723
+
724
+
725
+ export function cmsToFirestoreModel(data: unknown, firestore: Firestore, inArray = false): unknown {
726
+ if (data === undefined) {
727
+ return deleteField();
728
+ } else if (data === null) {
729
+ return null;
730
+ } else if (Array.isArray(data)) {
731
+ return (data as unknown[]).filter(v => v !== undefined).map(v => cmsToFirestoreModel(v, firestore, true));
732
+ } else if (typeof data === "object" && data !== null && "isEntityReference" in data && typeof (data as Record<string, unknown>).isEntityReference === "function" && (data as { isEntityReference: () => boolean }).isEntityReference()) {
733
+ const entityRef = data as EntityReference;
734
+ const targetFirestore = entityRef.databaseId ? getFirestore(firestore.app, entityRef.databaseId) : firestore;
735
+ return doc(targetFirestore, entityRef.path, entityRef.id);
736
+ } else if (data && typeof data === "object" && "__type" in data && (data as Record<string, unknown>).__type === "relation" && "path" in data && "id" in data) {
737
+ const rel = data as { path: string; id: string | number };
738
+ return doc(firestore, rel.path, String(rel.id));
739
+ } else if (data instanceof GeoPoint) {
740
+ return new FirestoreGeoPoint(data.latitude, data.longitude);
741
+ } else if (data instanceof Date) {
742
+ return Timestamp.fromDate(data);
743
+ } else if (data && typeof data === "object" && "__type__" in data && (data as Record<string, unknown>).__type__ === "__vector__") {
744
+ return vector((data as { value?: number[] }).value || []);
745
+ } else if (data && typeof data === "object") {
746
+ return Object.entries(data)
747
+ .map(([key, v]) => {
748
+ const firestoreModel = cmsToFirestoreModel(v, firestore);
749
+ if (firestoreModel !== undefined)
750
+ return ({ [key]: firestoreModel });
751
+ else
752
+ return {};
753
+ })
754
+ .reduce((a, b) => ({ ...a,
755
+ ...b }), {});
756
+ }
757
+ return data;
758
+ }
759
+
760
+ function currentTime(): unknown {
761
+ return serverTimestamp();
762
+ }
763
+
764
+ function buildTextSearchControllerWithLocalSearch({
765
+ textSearchControllerBuilder,
766
+ firebaseApp,
767
+ localTextSearchEnabled
768
+ }: {
769
+ textSearchControllerBuilder?: FirestoreTextSearchControllerBuilder,
770
+ firebaseApp: FirebaseApp,
771
+ localTextSearchEnabled: boolean
772
+ }): FirestoreTextSearchController | undefined {
773
+ if (!textSearchControllerBuilder && localTextSearchEnabled) {
774
+ console.debug("Using local search only");
775
+ return localSearchControllerBuilder({ firebaseApp });
776
+ }
777
+ if (!localTextSearchEnabled && textSearchControllerBuilder) {
778
+ console.debug("Using external text search only");
779
+ return textSearchControllerBuilder({ firebaseApp });
780
+ }
781
+ if (!textSearchControllerBuilder && !localTextSearchEnabled) {
782
+ return undefined;
783
+ }
784
+
785
+ const localSearchController = localSearchControllerBuilder({ firebaseApp })
786
+ const textSearchController = textSearchControllerBuilder!({ firebaseApp });
787
+ return {
788
+ init: async (props: {
789
+ path: string,
790
+ databaseId?: string,
791
+ collection?: CollectionConfig
792
+ }) => {
793
+ const b = await textSearchController.init(props);
794
+ if (b) {
795
+ console.debug("External Text search controller supports path", props.path);
796
+ return true;
797
+ }
798
+ if (localTextSearchEnabled)
799
+ return localSearchController.init(props);
800
+ return false;
801
+ },
802
+ search: async (props: {
803
+ searchString: string,
804
+ path: string,
805
+ currentUser?: User,
806
+ databaseId?: string
807
+ }) => {
808
+ const search = await textSearchController.search(props);
809
+ return search ?? await localSearchController.search(props);
810
+ }
811
+ }
812
+ }