@rebasepro/firebase 0.27.0 → 0.28.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.
@@ -1,6 +1,6 @@
1
- import { DataDriver, CollectionConfig } from "@rebasepro/types";
1
+ import { DataDriver, CollectionConfig, LogicalCondition } from "@rebasepro/types";
2
2
  import { FilterCombination } from "@rebasepro/cms-types";
3
- import { Firestore } from "firebase/firestore";
3
+ import { Firestore, QueryFilterConstraint } from "firebase/firestore";
4
4
  import { FirebaseApp } from "firebase/app";
5
5
  import { FirestoreTextSearchControllerBuilder } from "../types/text_search.js";
6
6
  /**
@@ -83,6 +83,16 @@ export declare function listenToSearchResults({ ids, limit, offset, listenOne, o
83
83
  onUpdate: (rows: Record<string, unknown>[]) => void;
84
84
  onError?: (error: Error) => void;
85
85
  }): () => void;
86
+ /**
87
+ * An `or(...)` / `and(...)` group as a Firestore composite filter, nesting
88
+ * included, or `undefined` for a group with no conditions in it.
89
+ *
90
+ * A group the driver does not translate is refused, never dropped: a dropped
91
+ * `or(...)` does not fail, it answers with the whole collection. `not(...)` is
92
+ * one — Firestore has no negation of a conjunction, and `!=` on each leaf
93
+ * matches a different set of documents.
94
+ */
95
+ export declare function firestoreLogicalCondition(logical: LogicalCondition | undefined, firestore: Firestore): QueryFilterConstraint | undefined;
86
96
  /**
87
97
  * Use this hook to build a {@link DataDriver} based on Firestore
88
98
  * @param firebaseApp
package/dist/index.es.js CHANGED
@@ -5,8 +5,8 @@ import { deleteObject, getDownloadURL, getMetadata, getStorage, list, ref, uploa
5
5
  import { deleteApp, getApps, initializeApp } from "firebase/app";
6
6
  import { getToken, initializeAppCheck } from "firebase/app-check";
7
7
  import { DEFAULT_DATA_SOURCE_KEY, EntityReference, GeoPoint } from "@rebasepro/types";
8
- import { COLLECTION_PATH_SEPARATOR, buildRebaseData, normalizeDriverOrderBy, sortProperties, stripCollectionPath } from "@rebasepro/common";
9
- import { DocumentReference, GeoPoint as GeoPoint$1, Timestamp, VectorValue, collection, deleteDoc, deleteField, doc, getCountFromServer, getDoc, getDocs, getFirestore, limit, onSnapshot, orderBy, query, serverTimestamp, setDoc, startAfter, vector, where } from "firebase/firestore";
8
+ import { COLLECTION_PATH_SEPARATOR, buildRebaseData, normalizeDriverOrderBy, sortProperties, stripCollectionPath, toFilterTuples } from "@rebasepro/common";
9
+ import { DocumentReference, GeoPoint as GeoPoint$1, Timestamp, VectorValue, and, collection, deleteDoc, deleteField, doc, getCountFromServer, getDoc, getDocs, getFirestore, limit, onSnapshot, or, orderBy, query, serverTimestamp, setDoc, startAfter, vector, where } from "firebase/firestore";
10
10
  import Fuse from "fuse.js";
11
11
  import { getFunctions, httpsCallable } from "firebase/functions";
12
12
  import { endAt, equalTo, get, getDatabase, limitToFirst, onValue, orderByChild, orderByKey, push, query as query$1, ref as ref$1, remove, set, startAfter as startAfter$1, startAt, update } from "firebase/database";
@@ -1034,6 +1034,43 @@ function listenToSearchResults({ ids, limit, offset, listenOne, onUpdate, onErro
1034
1034
  };
1035
1035
  }
1036
1036
  /**
1037
+ * One condition, as the Firestore filter it means.
1038
+ *
1039
+ * Null-testing operators map to `==` / `!=` against null. Firestore has no
1040
+ * LIKE/ILIKE, so those fail loudly rather than return wrong results.
1041
+ */
1042
+ function firestoreCondition(key, op, value, firestore) {
1043
+ if (op === "is-null") return where(key, "==", null);
1044
+ if (op === "is-not-null") return where(key, "!=", null);
1045
+ if (op === "like" || op === "ilike" || op === "not-like" || op === "not-ilike") throw new Error(`Firestore does not support the "${op}" operator (SQL pattern matching). Use a full-text search index or the collection's searchString instead.`);
1046
+ return where(key, op, rebaseToFirestoreModel(value, firestore));
1047
+ }
1048
+ /**
1049
+ * An `or(...)` / `and(...)` group as a Firestore composite filter, nesting
1050
+ * included, or `undefined` for a group with no conditions in it.
1051
+ *
1052
+ * A group the driver does not translate is refused, never dropped: a dropped
1053
+ * `or(...)` does not fail, it answers with the whole collection. `not(...)` is
1054
+ * one — Firestore has no negation of a conjunction, and `!=` on each leaf
1055
+ * matches a different set of documents.
1056
+ */
1057
+ function firestoreLogicalCondition(logical, firestore) {
1058
+ if (!logical || !Array.isArray(logical.conditions)) return void 0;
1059
+ if (logical.type === "not") throw new Error("Firestore does not support a not(...) filter group. Write the condition without the negation.");
1060
+ const parts = [];
1061
+ for (const entry of logical.conditions) {
1062
+ if (!entry) continue;
1063
+ if ("conditions" in entry) {
1064
+ const nested = firestoreLogicalCondition(entry, firestore);
1065
+ if (nested) parts.push(nested);
1066
+ continue;
1067
+ }
1068
+ parts.push(firestoreCondition(entry.column, entry.operator, entry.value, firestore));
1069
+ }
1070
+ if (parts.length === 0) return void 0;
1071
+ return logical.type === "or" ? or(...parts) : and(...parts);
1072
+ }
1073
+ /**
1037
1074
  * Use this hook to build a {@link DataDriver} based on Firestore
1038
1075
  * @param firebaseApp
1039
1076
  * @param textSearchControllerBuilder
@@ -1054,28 +1091,19 @@ function useFirestoreDriver({ firebaseApp, textSearchControllerBuilder, firestor
1054
1091
  localTextSearchEnabled,
1055
1092
  textSearchControllerBuilder
1056
1093
  ]);
1057
- const buildQuery = useCallback((path, filter, orderBy$1, order, startAfter$2, limit$1, databaseId) => {
1094
+ const buildQuery = useCallback((path, filter, orderBy$1, order, startAfter$2, limit$1, databaseId, logical) => {
1058
1095
  if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
1059
1096
  const firestore = databaseId ? getFirestore(firebaseApp, databaseId) : getFirestore(firebaseApp);
1060
1097
  const collectionReference = collection(firestore, path);
1098
+ const filters = [];
1099
+ for (const [key, filterParameter] of Object.entries(filter ?? {})) for (const [op, value] of toFilterTuples(filterParameter)) filters.push(firestoreCondition(key, op, value, firestore));
1100
+ const group = firestoreLogicalCondition(logical, firestore);
1061
1101
  const queryParams = [];
1062
- if (filter) Object.entries(filter).filter(([_, entry]) => !!entry).forEach(([key, filterParameter]) => {
1063
- const [op, value] = filterParameter;
1064
- if (op === "is-null") {
1065
- queryParams.push(where(key, "==", null));
1066
- return;
1067
- }
1068
- if (op === "is-not-null") {
1069
- queryParams.push(where(key, "!=", null));
1070
- return;
1071
- }
1072
- if (op === "like" || op === "ilike" || op === "not-like" || op === "not-ilike") throw new Error(`Firestore does not support the "${op}" operator (SQL pattern matching). Use a full-text search index or the collection's searchString instead.`);
1073
- queryParams.push(where(key, op, rebaseToFirestoreModel(value, firestore)));
1074
- });
1075
1102
  for (const [field, direction] of normalizeDriverOrderBy(orderBy$1, order) ?? []) queryParams.push(orderBy(field, direction));
1076
1103
  if (startAfter$2) queryParams.push(startAfter(startAfter$2));
1077
1104
  if (limit$1) queryParams.push(limit(limit$1));
1078
- return query(collectionReference, ...queryParams);
1105
+ if (group) return query(collectionReference, and(...filters, group), ...queryParams);
1106
+ return query(collectionReference, ...filters, ...queryParams);
1079
1107
  }, [firebaseApp]);
1080
1108
  const getAndBuildEntity = useCallback((path, id, databaseId) => {
1081
1109
  if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
@@ -1153,7 +1181,7 @@ function useFirestoreDriver({ firebaseApp, textSearchControllerBuilder, firestor
1153
1181
  * @see useCollection if you need this functionality implemented as a hook
1154
1182
  * @group Firestore
1155
1183
  */
1156
- const fetchCollection = useCallback(async ({ path, filter, limit, offset, startAfter, searchString, orderBy, order, collection }) => {
1184
+ const fetchCollection = useCallback(async ({ path, filter, logical, limit, offset, startAfter, searchString, orderBy, order, collection }) => {
1157
1185
  const databaseId = collection?.databaseId;
1158
1186
  const resolvedPath = path;
1159
1187
  console.debug("Fetching collection", {
@@ -1172,7 +1200,7 @@ function useFirestoreDriver({ firebaseApp, textSearchControllerBuilder, firestor
1172
1200
  readOne: (id) => getAndBuildEntity(resolvedPath, id, databaseId)
1173
1201
  });
1174
1202
  const { fetchLimit, skip } = resolveOffsetWindow(limit, offset);
1175
- return (await getDocs(buildQuery(resolvedPath, filter, orderBy, order, startAfter, fetchLimit, databaseId))).docs.slice(skip).map((doc) => createRowFromDocument(doc));
1203
+ return (await getDocs(buildQuery(resolvedPath, filter, orderBy, order, startAfter, fetchLimit, databaseId, logical))).docs.slice(skip).map((doc) => createRowFromDocument(doc));
1176
1204
  }, [
1177
1205
  buildQuery,
1178
1206
  searchIds,
@@ -1194,7 +1222,7 @@ function useFirestoreDriver({ firebaseApp, textSearchControllerBuilder, firestor
1194
1222
  * @see useCollection if you need this functionality implemented as a hook
1195
1223
  * @group Firestore
1196
1224
  */
1197
- const listenCollection = useCallback(({ path, filter, limit, offset, startAfter, searchString, orderBy, order, onUpdate, onError, collection }) => {
1225
+ const listenCollection = useCallback(({ path, filter, logical, limit, offset, startAfter, searchString, orderBy, order, onUpdate, onError, collection }) => {
1198
1226
  console.debug("Listening collection", {
1199
1227
  path,
1200
1228
  searchString,
@@ -1222,7 +1250,7 @@ function useFirestoreDriver({ firebaseApp, textSearchControllerBuilder, firestor
1222
1250
  resolvedPath
1223
1251
  });
1224
1252
  const { fetchLimit, skip } = resolveOffsetWindow(limit, offset);
1225
- return onSnapshot(buildQuery(resolvedPath, filter, orderBy, order, startAfter, fetchLimit, databaseId), {
1253
+ return onSnapshot(buildQuery(resolvedPath, filter, orderBy, order, startAfter, fetchLimit, databaseId, logical), {
1226
1254
  next: (entity) => {
1227
1255
  onUpdate(entity.docs.slice(skip).map((doc) => createRowFromDocument(doc)));
1228
1256
  },
@@ -1318,12 +1346,12 @@ function useFirestoreDriver({ firebaseApp, textSearchControllerBuilder, firestor
1318
1346
  if (value === void 0 || value === null) return Promise.resolve(true);
1319
1347
  return (await getDocs(query(collection(firestore, path), where(name, "==", rebaseToFirestoreModel(value, firestore))))).docs.filter((doc) => doc.id !== id).length === 0;
1320
1348
  }, [firebaseApp]);
1321
- const count = useCallback(async ({ path, filter, order, orderBy, searchString, collection }) => {
1349
+ const count = useCallback(async ({ path, filter, logical, order, orderBy, searchString, collection }) => {
1322
1350
  if (!firebaseApp) throw Error("useFirestoreDriver Firebase not initialised");
1323
1351
  const databaseId = collection?.databaseId;
1324
1352
  const resolvedPath = path;
1325
1353
  if (searchString) return (await searchIds(resolvedPath, searchString, databaseId) ?? []).length;
1326
- return (await getCountFromServer(buildQuery(resolvedPath, filter, orderBy, order, void 0, void 0, databaseId))).data().count;
1354
+ return (await getCountFromServer(buildQuery(resolvedPath, filter, orderBy, order, void 0, void 0, databaseId, logical))).data().count;
1327
1355
  }, [
1328
1356
  firebaseApp,
1329
1357
  buildQuery,
@@ -2861,6 +2889,6 @@ function RebaseFirebaseApp({ name, logo, logoDark, accessGate, collections, view
2861
2889
  }) });
2862
2890
  }
2863
2891
  //#endregion
2864
- export { FirebaseLoginView, LoginButton, RECAPTCHA_CONTAINER_ID, RebaseFirebaseApp, buildCollectionId, buildExternalSearchController, buildPineconeSearchController, buildRebaseSearchController, docToCollection, docsToCollectionTree, firestoreToRebaseModel, getFirestoreDataInPath, listenToSearchResults, localSearchControllerBuilder, performAlgoliaTextSearch, performPineconeTextSearch, planRTDBQuery, readSearchResults, rebaseToFirestoreModel, resolveAccessDecision, resolveOffsetWindow, resolveRoleRefresh, useAppCheck, useBuildUserManagement, useFirebaseAccessGate, useFirebaseAuthController, useFirebaseRTDBDelegate, useFirebaseStorageSource, useFirestoreDriver, useInitialiseFirebase, useRecaptcha };
2892
+ export { FirebaseLoginView, LoginButton, RECAPTCHA_CONTAINER_ID, RebaseFirebaseApp, buildCollectionId, buildExternalSearchController, buildPineconeSearchController, buildRebaseSearchController, docToCollection, docsToCollectionTree, firestoreLogicalCondition, firestoreToRebaseModel, getFirestoreDataInPath, listenToSearchResults, localSearchControllerBuilder, performAlgoliaTextSearch, performPineconeTextSearch, planRTDBQuery, readSearchResults, rebaseToFirestoreModel, resolveAccessDecision, resolveOffsetWindow, resolveRoleRefresh, useAppCheck, useBuildUserManagement, useFirebaseAccessGate, useFirebaseAuthController, useFirebaseRTDBDelegate, useFirebaseStorageSource, useFirestoreDriver, useInitialiseFirebase, useRecaptcha };
2865
2893
 
2866
2894
  //# sourceMappingURL=index.es.js.map