@dalgo/firestore 0.1.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Strongo Team
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,117 @@
1
+ # DALgo adapter for Firestore Web
2
+
3
+ `@dalgo/firestore` implements the
4
+ [`@dalgo/core`](https://www.npmjs.com/package/@dalgo/core) database contracts with
5
+ Firebase's modular Cloud Firestore Web SDK. It is intended for browser apps,
6
+ including apps that query an OpenVaultDB Firestore database directly.
7
+
8
+ ## Install
9
+
10
+ ```sh
11
+ pnpm add @dalgo/core @dalgo/firestore firebase
12
+ ```
13
+
14
+ The adapter uses the separately published `@dalgo/core` contracts.
15
+
16
+ ## Browser setup
17
+
18
+ ```ts
19
+ import { initializeApp } from "firebase/app";
20
+ import { getFirestore } from "firebase/firestore";
21
+ import { collection, key } from "@dalgo/core";
22
+ import { FirestoreDatabase } from "@dalgo/firestore";
23
+
24
+ interface Item {
25
+ title: string;
26
+ done: boolean;
27
+ rank: number;
28
+ }
29
+
30
+ const app = initializeApp({
31
+ apiKey: import.meta.env.VITE_FIREBASE_API_KEY,
32
+ authDomain: import.meta.env.VITE_FIREBASE_AUTH_DOMAIN,
33
+ projectId: import.meta.env.VITE_FIREBASE_PROJECT_ID,
34
+ });
35
+
36
+ const db = new FirestoreDatabase(getFirestore(app));
37
+ const spaceKey = key("spaces", "my-space");
38
+ const items = collection<Item>("items").in(spaceKey);
39
+
40
+ const firstPage = await db.query(
41
+ items.query()
42
+ .where("done", "==", false)
43
+ .orderBy("rank")
44
+ .limit(25)
45
+ .build(),
46
+ );
47
+
48
+ const secondPage = firstPage.nextCursor === undefined
49
+ ? undefined
50
+ : await db.query(
51
+ items.query()
52
+ .where("done", "==", false)
53
+ .orderBy("rank")
54
+ .startAfter(...firstPage.nextCursor.values)
55
+ .limit(25)
56
+ .build(),
57
+ );
58
+ ```
59
+
60
+ For a named Firestore database, pass its database ID to `getFirestore`:
61
+
62
+ ```ts
63
+ const db = new FirestoreDatabase(getFirestore(app, openVaultDatabaseId));
64
+ ```
65
+
66
+ The adapter appends document ID as a deterministic final ordering field. Use
67
+ the returned `nextCursor` rather than constructing pagination values manually.
68
+
69
+ ## Point reads and transactions
70
+
71
+ ```ts
72
+ const item = await db.get(items.key("milk"));
73
+ if (item.exists) {
74
+ console.log(item.data.title);
75
+ }
76
+
77
+ await db.runReadwriteTransaction(async (tx) => {
78
+ const current = await tx.get<Item>(items.key("milk"));
79
+ if (current.exists) {
80
+ await tx.update(current.key, { done: true });
81
+ }
82
+ });
83
+ ```
84
+
85
+ Firestore may retry a transaction callback. Keep it idempotent and do not
86
+ perform UI or other external side effects inside it. Firestore also requires
87
+ all reads before writes; the adapter reports a DALgo `UnsupportedError` when a
88
+ callback tries to read after writing.
89
+
90
+ ## OpenVaultDB and browser security
91
+
92
+ The Firebase Web configuration identifies a project; it is not an admin
93
+ credential. Browser access must be authorized with Firebase Authentication and
94
+ least-privilege Firestore Security Rules. Every mobile/web SDK request is
95
+ checked by those rules. Consider Firebase App Check as an additional abuse
96
+ signal. Never ship service-account credentials or server SDK credentials to a
97
+ browser.
98
+
99
+ This package deliberately uses the Web SDK, not `firebase-admin`, so it cannot
100
+ bypass Firestore Security Rules.
101
+
102
+ ## Supported query surface
103
+
104
+ - nested collections and collection-group queries
105
+ - Firestore comparison, membership, and array filters
106
+ - multiple `where` clauses combined with AND
107
+ - ascending and descending ordering
108
+ - deterministic value-cursor pagination
109
+ - limits
110
+
111
+ Offset is rejected explicitly because the Firestore Web SDK does not expose an
112
+ offset constraint. Firestore index and operator-combination requirements remain
113
+ native Firestore behavior and errors.
114
+
115
+ ## License
116
+
117
+ MIT
@@ -0,0 +1,11 @@
1
+ import { Key, type Codec, type Database, type QueryPage, type ReadwriteTransaction, type RecordSnapshot, type StructuredQuery } from "@dalgo/core";
2
+ import { type Firestore } from "firebase/firestore";
3
+ export declare class FirestoreDatabase implements Database {
4
+ readonly firestore: Firestore;
5
+ constructor(firestore: Firestore);
6
+ get<T>(key: Key, codec?: Codec<T>): Promise<RecordSnapshot<T>>;
7
+ getMany<T>(keys: readonly Key[], codec?: Codec<T>): Promise<readonly RecordSnapshot<T>[]>;
8
+ query<T>(dalQuery: StructuredQuery<T>): Promise<QueryPage<T>>;
9
+ runReadwriteTransaction<Result>(callback: (transaction: ReadwriteTransaction) => Promise<Result>): Promise<Result>;
10
+ }
11
+ //# sourceMappingURL=database.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"database.d.ts","sourceRoot":"","sources":["../src/database.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,GAAG,EAGH,KAAK,KAAK,EACV,KAAK,QAAQ,EAEb,KAAK,SAAS,EACd,KAAK,oBAAoB,EACzB,KAAK,cAAc,EACnB,KAAK,eAAe,EAErB,MAAM,aAAa,CAAC;AACrB,OAAO,EAQL,KAAK,SAAS,EAIf,MAAM,oBAAoB,CAAC;AAuG5B,qBAAa,iBAAkB,YAAW,QAAQ;IAChD,SAAgB,SAAS,EAAE,SAAS,CAAC;gBAElB,SAAS,EAAE,SAAS;IAI1B,GAAG,CAAC,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,KAAK,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC;IAK9D,OAAO,CAAC,CAAC,EACpB,IAAI,EAAE,SAAS,GAAG,EAAE,EACpB,KAAK,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,GACf,OAAO,CAAC,SAAS,cAAc,CAAC,CAAC,CAAC,EAAE,CAAC;IAI3B,KAAK,CAAC,CAAC,EAAE,QAAQ,EAAE,eAAe,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;IAoBnE,uBAAuB,CAAC,MAAM,EACnC,QAAQ,EAAE,CAAC,WAAW,EAAE,oBAAoB,KAAK,OAAO,CAAC,MAAM,CAAC,GAC/D,OAAO,CAAC,MAAM,CAAC;CAKnB"}
@@ -0,0 +1,111 @@
1
+ import { AlreadyExistsError, Key, UnsupportedError, identityCodec, } from "@dalgo/core";
2
+ import { doc, getDoc, getDocs, runTransaction, } from "firebase/firestore";
3
+ import { keyFromDocumentPath } from "./path.js";
4
+ import { compileFirestoreQuery, cursorFromSnapshot } from "./query.js";
5
+ function codecOrIdentity(codec) {
6
+ return (codec ?? identityCodec);
7
+ }
8
+ function documentReference(firestore, key) {
9
+ return doc(firestore, key.path);
10
+ }
11
+ function recordFromSnapshot(snapshot, requestedKey, codec) {
12
+ const key = requestedKey ?? keyFromDocumentPath(snapshot.ref.path);
13
+ const metadata = {
14
+ fromCache: snapshot.metadata.fromCache,
15
+ hasPendingWrites: snapshot.metadata.hasPendingWrites,
16
+ };
17
+ if (!snapshot.exists()) {
18
+ return { key, exists: false, metadata };
19
+ }
20
+ return {
21
+ key,
22
+ exists: true,
23
+ data: codecOrIdentity(codec).decode(snapshot.data()),
24
+ metadata,
25
+ };
26
+ }
27
+ class FirestoreReadwriteTransaction {
28
+ #firestore;
29
+ #transaction;
30
+ #hasWrites = false;
31
+ constructor(firestore, transaction) {
32
+ this.#firestore = firestore;
33
+ this.#transaction = transaction;
34
+ }
35
+ async get(key, codec) {
36
+ this.assertCanRead();
37
+ const snapshot = await this.#transaction.get(documentReference(this.#firestore, key));
38
+ return recordFromSnapshot(snapshot, key, codec);
39
+ }
40
+ async getMany(keys, codec) {
41
+ const records = [];
42
+ for (const key of keys) {
43
+ records.push(await this.get(key, codec));
44
+ }
45
+ return records;
46
+ }
47
+ async insert(key, data, codec) {
48
+ const existing = await this.get(key);
49
+ if (existing.exists) {
50
+ throw new AlreadyExistsError(key);
51
+ }
52
+ this.#transaction.set(documentReference(this.#firestore, key), codecOrIdentity(codec).encode(data));
53
+ this.#hasWrites = true;
54
+ }
55
+ set(key, data, codec) {
56
+ this.#transaction.set(documentReference(this.#firestore, key), codecOrIdentity(codec).encode(data));
57
+ this.#hasWrites = true;
58
+ return Promise.resolve();
59
+ }
60
+ update(key, data) {
61
+ this.#transaction.update(documentReference(this.#firestore, key), data);
62
+ this.#hasWrites = true;
63
+ return Promise.resolve();
64
+ }
65
+ delete(key) {
66
+ this.#transaction.delete(documentReference(this.#firestore, key));
67
+ this.#hasWrites = true;
68
+ return Promise.resolve();
69
+ }
70
+ assertCanRead() {
71
+ if (this.#hasWrites) {
72
+ throw new UnsupportedError("Firestore transaction reads after writes");
73
+ }
74
+ }
75
+ }
76
+ export class FirestoreDatabase {
77
+ firestore;
78
+ constructor(firestore) {
79
+ this.firestore = firestore;
80
+ }
81
+ async get(key, codec) {
82
+ const snapshot = await getDoc(documentReference(this.firestore, key));
83
+ return recordFromSnapshot(snapshot, key, codec);
84
+ }
85
+ async getMany(keys, codec) {
86
+ return Promise.all(keys.map(async (key) => this.get(key, codec)));
87
+ }
88
+ async query(dalQuery) {
89
+ const compiled = compileFirestoreQuery(this.firestore, dalQuery);
90
+ const snapshot = await getDocs(compiled.query);
91
+ const records = snapshot.docs.map((document) => {
92
+ const record = recordFromSnapshot(document, undefined, dalQuery.source.codec);
93
+ if (!record.exists) {
94
+ throw new Error(`query returned a missing Firestore document: ${document.ref.path}`);
95
+ }
96
+ return record;
97
+ });
98
+ const last = snapshot.docs.at(-1);
99
+ const nextCursor = dalQuery.limit !== undefined && snapshot.size === dalQuery.limit && last !== undefined
100
+ ? cursorFromSnapshot(last, compiled.orders)
101
+ : undefined;
102
+ return {
103
+ records,
104
+ ...(nextCursor === undefined ? {} : { nextCursor }),
105
+ };
106
+ }
107
+ runReadwriteTransaction(callback) {
108
+ return runTransaction(this.firestore, async (transaction) => callback(new FirestoreReadwriteTransaction(this.firestore, transaction)));
109
+ }
110
+ }
111
+ //# sourceMappingURL=database.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"database.js","sourceRoot":"","sources":["../src/database.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,GAAG,EACH,gBAAgB,EAChB,aAAa,GASd,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,GAAG,EACH,MAAM,EACN,OAAO,EACP,cAAc,GAQf,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAChD,OAAO,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAEvE,SAAS,eAAe,CAAI,KAAgB;IAC1C,OAAO,CAAC,KAAK,IAAI,aAAa,CAAa,CAAC;AAC9C,CAAC;AAED,SAAS,iBAAiB,CAAC,SAAoB,EAAE,GAAQ;IACvD,OAAO,GAAG,CAAC,SAAS,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;AAClC,CAAC;AAED,SAAS,kBAAkB,CACzB,QAA0B,EAC1B,YAA6B,EAC7B,KAA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AAC,KAAK,CAAC,CAAC;YAC9E,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;gBACnB,MAAM,IAAI,KAAK,CAAC,gDAAgD,QAAQ,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;YACvF,CAAC;YACD,OAAO,MAAM,CAAC;QAChB,CAAC,CAAC,CAAC;QACH,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QAClC,MAAM,UAAU,GAAG,QAAQ,CAAC,KAAK,KAAK,SAAS,IAAI,QAAQ,CAAC,IAAI,KAAK,QAAQ,CAAC,KAAK,IAAI,IAAI,KAAK,SAAS;YACvG,CAAC,CAAC,kBAAkB,CAAC,IAAI,EAAE,QAAQ,CAAC,MAAM,CAAC;YAC3C,CAAC,CAAC,SAAS,CAAC;QACd,OAAO;YACL,OAAO;YACP,GAAG,CAAC,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC;SACpD,CAAC;IACJ,CAAC;IAEM,uBAAuB,CAC5B,QAAgE;QAEhE,OAAO,cAAc,CAAC,IAAI,CAAC,SAAS,EAAE,KAAK,EAAE,WAAW,EAAE,EAAE,CAAC,QAAQ,CACnE,IAAI,6BAA6B,CAAC,IAAI,CAAC,SAAS,EAAE,WAAW,CAAC,CAC/D,CAAC,CAAC;IACL,CAAC;CACF"}
@@ -0,0 +1,4 @@
1
+ export * from "./database.js";
2
+ export * from "./path.js";
3
+ export * from "./query.js";
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,eAAe,CAAC;AAC9B,cAAc,WAAW,CAAC;AAC1B,cAAc,YAAY,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from "./database.js";
2
+ export * from "./path.js";
3
+ export * from "./query.js";
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,eAAe,CAAC;AAC9B,cAAc,WAAW,CAAC;AAC1B,cAAc,YAAY,CAAC"}
package/dist/path.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import { Key, type CollectionSource } from "@dalgo/core";
2
+ export declare function firestoreCollectionPath<T>(source: CollectionSource<T>): string;
3
+ export declare function keyFromDocumentPath(path: string): Key<string>;
4
+ //# sourceMappingURL=path.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"path.d.ts","sourceRoot":"","sources":["../src/path.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,KAAK,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAEzD,wBAAgB,uBAAuB,CAAC,CAAC,EAAE,MAAM,EAAE,gBAAgB,CAAC,CAAC,CAAC,GAAG,MAAM,CAI9E;AAED,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC,CAoB7D"}
package/dist/path.js ADDED
@@ -0,0 +1,26 @@
1
+ import { Key } from "@dalgo/core";
2
+ export function firestoreCollectionPath(source) {
3
+ return source.parent === undefined
4
+ ? source.name
5
+ : `${source.parent.path}/${source.name}`;
6
+ }
7
+ export function keyFromDocumentPath(path) {
8
+ const segments = path.split("/");
9
+ if (segments.length === 0 || segments.length % 2 !== 0 || segments.some((part) => part === "")) {
10
+ throw new TypeError(`invalid Firestore document path: ${path}`);
11
+ }
12
+ let current;
13
+ for (let index = 0; index < segments.length; index += 2) {
14
+ const collection = segments[index];
15
+ const id = segments[index + 1];
16
+ if (collection === undefined || id === undefined) {
17
+ throw new TypeError(`invalid Firestore document path: ${path}`);
18
+ }
19
+ current = new Key(collection, id, current);
20
+ }
21
+ if (current === undefined) {
22
+ throw new TypeError(`invalid Firestore document path: ${path}`);
23
+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AC,CAAC;IAC7C,CAAC;IAED,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;QAC1B,MAAM,IAAI,SAAS,CAAC,oCAAoC,IAAI,EAAE,CAAC,CAAC;IAClE,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC"}
@@ -0,0 +1,10 @@
1
+ import { type QueryCursor, type QueryOrder, type QuerySource, type StructuredQuery } from "@dalgo/core";
2
+ import { type DocumentSnapshot, type Firestore, type Query } from "firebase/firestore";
3
+ export interface CompiledFirestoreQuery<T> {
4
+ readonly query: Query;
5
+ readonly orders: readonly QueryOrder<T>[];
6
+ }
7
+ export declare function toFirestoreDocumentIdValue<T>(value: unknown, source: QuerySource<T>): unknown;
8
+ export declare function compileFirestoreQuery<T>(firestore: Firestore, dalQuery: StructuredQuery<T>): CompiledFirestoreQuery<T>;
9
+ export declare function cursorFromSnapshot<T>(snapshot: DocumentSnapshot, orders: readonly QueryOrder<T>[]): QueryCursor;
10
+ //# sourceMappingURL=query.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query.d.ts","sourceRoot":"","sources":["../src/query.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,KAAK,WAAW,EAChB,KAAK,UAAU,EACf,KAAK,WAAW,EAChB,KAAK,eAAe,EACrB,MAAM,aAAa,CAAC;AACrB,OAAO,EAYL,KAAK,gBAAgB,EACrB,KAAK,SAAS,EACd,KAAK,KAAK,EAEX,MAAM,oBAAoB,CAAC;AAG5B,MAAM,WAAW,sBAAsB,CAAC,CAAC;IACvC,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC;IACtB,QAAQ,CAAC,MAAM,EAAE,SAAS,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC;CAC3C;AAMD,wBAAgB,0BAA0B,CAAC,CAAC,EAC1C,KAAK,EAAE,OAAO,EACd,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,GACrB,OAAO,CAsBT;AA2BD,wBAAgB,qBAAqB,CAAC,CAAC,EACrC,SAAS,EAAE,SAAS,EACpB,QAAQ,EAAE,eAAe,CAAC,CAAC,CAAC,GAC3B,sBAAsB,CAAC,CAAC,CAAC,CAmC3B;AAED,wBAAgB,kBAAkB,CAAC,CAAC,EAClC,QAAQ,EAAE,gBAAgB,EAC1B,MAAM,EAAE,SAAS,UAAU,CAAC,CAAC,CAAC,EAAE,GAC/B,WAAW,CAMb"}
package/dist/query.js ADDED
@@ -0,0 +1,73 @@
1
+ import { DOCUMENT_ID, Key, UnsupportedError, } from "@dalgo/core";
2
+ import { collection, collectionGroup, documentId, endAt, endBefore, limit, orderBy, query as createQuery, startAfter, startAt, where, } from "firebase/firestore";
3
+ import { firestoreCollectionPath } from "./path.js";
4
+ function firestoreField(field) {
5
+ return field === DOCUMENT_ID ? documentId() : field;
6
+ }
7
+ export function toFirestoreDocumentIdValue(value, source) {
8
+ if (value instanceof Key) {
9
+ if (source.kind === "collection") {
10
+ const collectionPath = firestoreCollectionPath(source);
11
+ if (value.collectionPath !== collectionPath) {
12
+ throw new TypeError(`document key belongs to ${value.collectionPath}, expected ${collectionPath}`);
13
+ }
14
+ return value.path.slice(collectionPath.length + 1);
15
+ }
16
+ if (value.collection !== source.name) {
17
+ throw new TypeError(`document key belongs to ${value.collection}, expected collection group ${source.name}`);
18
+ }
19
+ return value.path;
20
+ }
21
+ if (Array.isArray(value)) {
22
+ return value.map((item) => toFirestoreDocumentIdValue(item, source));
23
+ }
24
+ return value;
25
+ }
26
+ function queryOrders(dalQuery) {
27
+ if (dalQuery.orders.some(({ field }) => field === DOCUMENT_ID)) {
28
+ return dalQuery.orders;
29
+ }
30
+ const direction = dalQuery.orders.at(-1)?.direction ?? "asc";
31
+ return [...dalQuery.orders, { field: DOCUMENT_ID, direction }];
32
+ }
33
+ function addCursor(constraints, value, orderCount, createConstraint) {
34
+ if (value === undefined) {
35
+ return;
36
+ }
37
+ if (value.values.length !== orderCount) {
38
+ throw new TypeError(`cursor has ${value.values.length.toString()} values but the compiled query has ${orderCount.toString()} order fields`);
39
+ }
40
+ constraints.push(createConstraint(...value.values));
41
+ }
42
+ export function compileFirestoreQuery(firestore, dalQuery) {
43
+ if ((dalQuery.offset ?? 0) !== 0) {
44
+ throw new UnsupportedError("Firestore Web SDK query offsets");
45
+ }
46
+ const source = dalQuery.source.kind === "collection"
47
+ ? collection(firestore, firestoreCollectionPath(dalQuery.source))
48
+ : collectionGroup(firestore, dalQuery.source.name);
49
+ const constraints = [];
50
+ for (const filter of dalQuery.filters) {
51
+ constraints.push(where(firestoreField(filter.field), filter.operator, filter.field === DOCUMENT_ID
52
+ ? toFirestoreDocumentIdValue(filter.value, dalQuery.source)
53
+ : filter.value));
54
+ }
55
+ const orders = queryOrders(dalQuery);
56
+ for (const order of orders) {
57
+ constraints.push(orderBy(firestoreField(order.field), order.direction));
58
+ }
59
+ addCursor(constraints, dalQuery.startAt, orders.length, startAt);
60
+ addCursor(constraints, dalQuery.startAfter, orders.length, startAfter);
61
+ addCursor(constraints, dalQuery.endAt, orders.length, endAt);
62
+ addCursor(constraints, dalQuery.endBefore, orders.length, endBefore);
63
+ if (dalQuery.limit !== undefined) {
64
+ constraints.push(limit(dalQuery.limit));
65
+ }
66
+ return { query: createQuery(source, ...constraints), orders };
67
+ }
68
+ export function cursorFromSnapshot(snapshot, orders) {
69
+ return {
70
+ values: orders.map(({ field }) => (field === DOCUMENT_ID ? snapshot.id : snapshot.get(field))),
71
+ };
72
+ }
73
+ //# sourceMappingURL=query.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query.js","sourceRoot":"","sources":["../src/query.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EACX,GAAG,EACH,gBAAgB,GAMjB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,UAAU,EACV,eAAe,EACf,UAAU,EACV,KAAK,EACL,SAAS,EACT,KAAK,EACL,OAAO,EACP,KAAK,IAAI,WAAW,EACpB,UAAU,EACV,OAAO,EACP,KAAK,GAKN,MAAM,oBAAoB,CAAC;AA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AAU,kBAAkB,CAChC,QAA0B,EAC1B,MAAgC;IAEhC,OAAO;QACL,MAAM,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,EAAW,EAAE,CAAC,CACzC,KAAK,KAAK,WAAW,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAY,CACrE,CAAC;KACH,CAAC;AACJ,CAAC"}
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@dalgo/firestore",
3
+ "version": "0.1.0",
4
+ "description": "Firestore Web SDK adapter for DALgo TypeScript",
5
+ "type": "module",
6
+ "packageManager": "pnpm@11.20.0",
7
+ "sideEffects": false,
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "LICENSE",
17
+ "README.md"
18
+ ],
19
+ "scripts": {
20
+ "build": "tsc -p tsconfig.build.json",
21
+ "check": "eslint . && vitest run --exclude test/firestore.integration.test.ts && tsc -p tsconfig.build.json",
22
+ "lint": "eslint .",
23
+ "prepack": "npm run build",
24
+ "test": "vitest run --exclude test/firestore.integration.test.ts",
25
+ "test:emulator": "pnpm --package firebase-tools@15.30.2 dlx firebase emulators:exec --only firestore --project demo-dalgo-js-e2e \"vitest run test/firestore.integration.test.ts\"",
26
+ "test:watch": "vitest"
27
+ },
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/dal-go/dalgo-http-adapters.git",
31
+ "directory": "packages/firestore"
32
+ },
33
+ "bugs": {
34
+ "url": "https://github.com/dal-go/dalgo-http-adapters/issues"
35
+ },
36
+ "homepage": "https://github.com/dal-go/dalgo-http-adapters/tree/main/packages/firestore#readme",
37
+ "license": "MIT",
38
+ "publishConfig": {
39
+ "access": "public"
40
+ },
41
+ "engines": {
42
+ "node": ">=20"
43
+ },
44
+ "peerDependencies": {
45
+ "@dalgo/core": "^0.1.0",
46
+ "firebase": "^12.19.0"
47
+ },
48
+ "devDependencies": {
49
+ "@dalgo/core": "^0.1.0",
50
+ "@eslint/js": "10.0.1",
51
+ "eslint": "10.11.0",
52
+ "firebase": "12.19.0",
53
+ "typescript": "6.0.3",
54
+ "typescript-eslint": "8.70.0",
55
+ "vitest": "5.0.1"
56
+ }
57
+ }