svelte-firekit 0.0.22 → 0.0.24

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/README.md CHANGED
@@ -1,221 +1,213 @@
1
- ---
2
- slug: docs
3
- title: Welcome to Svelte Firekit
4
- description: a comprehensive library integrating SvelteKit and Firebase for building robust micro SaaS applications.
5
- ---
6
-
7
- ## Introduction to Svelte Firekit
8
-
9
- Svelte Firekit is a powerful Firebase toolkit for SvelteKit applications, providing a comprehensive set of utilities, stores, and components for seamless Firebase integration. Whether you're building a micro SaaS, web application, or any Firebase-powered project, Svelte Firekit streamlines your development process.
10
-
11
- ## Installation
12
-
13
- ```bash
14
- npm install firebase svelte-firekit
15
- ```
16
-
17
- ## Configuration
18
-
19
- Svelte Firekit automatically manages your Firebase configuration through environment variables. Create a `.env` file in your project root with the following variables:
20
-
21
- ```env
22
- PUBLIC_FIREBASE_API_KEY=your_api_key
23
- PUBLIC_FIREBASE_AUTH_DOMAIN=your_auth_domain
24
- PUBLIC_FIREBASE_PROJECT_ID=your_project_id
25
- PUBLIC_FIREBASE_STORAGE_BUCKET=your_storage_bucket
26
- PUBLIC_FIREBASE_MESSAGING_SENDER_ID=your_messaging_sender_id
27
- PUBLIC_FIREBASE_APP_ID=your_app_id
28
- PUBLIC_FIREBASE_MEASUREMENT_ID=your_measurement_id
29
- ```
30
-
31
- The configuration is automatically handled by Firekit - no manual setup required. If any required environment variables are missing, Firekit will throw a helpful error indicating which variables need to be set.
32
-
33
- ## Usage Example
34
-
35
- Here's a simple example showing how to display the current user's name:
36
-
37
- ```svelte
38
- <script>
39
- import { firekitUser } from 'svelte-firekit';
40
- </script>
41
-
42
- Hello {firekitUser.displayName}
43
- ```
44
-
45
- The `firekitUser` store provides access to the current user's information and authentication state.
46
-
47
- ## Core Features
48
-
49
- ### 🔥 Firebase Integration
50
- - Zero-config Firebase setup through environment variables
51
- - Automatic initialization and app management
52
- - Built-in error handling and connection state management
53
- - Type-safe configuration management
54
-
55
- ### 🔐 Authentication
56
- - Complete authentication system with built-in components
57
- - Support for multiple authentication providers:
58
- - Email/Password
59
- - Google
60
- - GitHub
61
- - Custom providers
62
- - User state management and persistence through `firekitUser` store
63
-
64
- ### 📚 Firestore Integration
65
- - Reactive data stores for real-time updates
66
- - Simplified CRUD operations
67
- - Batch operations and transactions
68
- - Type-safe document references
69
- - Automatic data serialization/deserialization
70
-
71
- ### 📦 Storage Management
72
- - File upload and download utilities
73
- - Progress tracking and status updates
74
- - Storage security rules helpers
75
- - Image optimization utilities
76
-
77
- ### Server-Side Rendering
78
- - Full SSR compatibility
79
- - Hydration support
80
- - Server-side data fetching
81
- - SEO-friendly rendering
82
-
83
- ### 🎯 Type Safety
84
- - Built with TypeScript
85
- - Complete type definitions
86
- - Intelligent autocomplete
87
- - Runtime type checking
88
- - Type-safe Firestore operations
89
-
90
- ## Why Svelte Firekit?
91
-
92
- - **Zero Configuration**: Automatic Firebase setup through environment variables
93
- - **Type Safety**: Full TypeScript support with built-in type checking
94
- - **Rapid Development**: Get your Firebase-powered SvelteKit application up and running in minutes
95
- - **Best Practices**: Built following Firebase and SvelteKit best practices
96
- - **Production Ready**: Battle-tested in production environments
97
- - **Active Community**: Regular updates and active community support
98
- - **Extensible**: Easy to customize and extend for your specific needs
99
-
100
- ## Next Steps
101
-
102
- - Check out our [Getting Started](/getting-started) guide
103
- - Explore the [API Reference](/api)
104
- - View [Examples](/examples)
105
- - Join our [Community](/community)
106
-
107
- ## Contributing
108
-
109
- We welcome contributions! Please see our [Contributing Guide](/contributing) for more details.
110
-
111
- ## License
112
-
113
- Svelte Firekit is released under the MIT License. See the [LICENSE](/license) file for more details.
114
-
115
- # Authentication
116
-
117
- Svelte Firekit provides a comprehensive authentication system through the `firekitAuth` singleton, offering various authentication methods and user management features.
118
-
119
- ## Basic Usage
120
-
121
- ```typescript
122
- import { firekitAuth } from 'svelte-firekit';
123
- ```
124
-
125
- ## Authentication Methods
126
-
127
- ### Google Authentication
128
-
129
- ```typescript
130
- await firekitAuth.signInWithGoogle();
131
- ```
132
-
133
- ### Email/Password Authentication
134
-
135
- ```typescript
136
- // Sign in
137
- await firekitAuth.signInWithEmail(email, password);
138
-
139
- // Register
140
- await firekitAuth.registerWithEmail(email, password, displayName);
141
-
142
- // Sign out
143
- await firekitAuth.logOut();
144
- ```
145
-
146
- ## User Management
147
-
148
- ### Password Management
149
-
150
- ```typescript
151
- // Send password reset email
152
- await firekitAuth.sendPasswordReset(email);
153
-
154
- // Update password (requires reauthentication)
155
- await firekitAuth.updateUserPassword(newPassword, currentPassword);
156
- ```
157
-
158
- ### Profile Management
159
-
160
- ```typescript
161
- // Update user profile
162
- await firekitAuth.updateUserProfile({
163
- displayName: "New Name",
164
- photoURL: "https://example.com/photo.jpg"
165
- });
166
- ```
167
-
168
- ### Email Verification
169
-
170
- ```typescript
171
- // Send verification email
172
- await firekitAuth.sendEmailVerificationToUser();
173
- ```
174
-
175
- ### Account Deletion
176
-
177
- ```typescript
178
- // Delete user account
179
- await firekitAuth.deleteUserAccount();
180
- ```
181
-
182
- ## Automatic Firestore Integration
183
-
184
- The authentication system automatically maintains a user document in Firestore with the following information:
185
- - User ID
186
- - Email
187
- - Email verification status
188
- - Display name
189
- - Photo URL
190
- - Authentication provider information
191
- - Anonymous status
192
-
193
- ## Error Handling
194
-
195
- All methods include proper error handling and return appropriate error messages. For example, password updates will return:
196
-
197
- ```typescript
198
- {
199
- success: boolean;
200
- message: string;
201
- code?: string; // In case of errors
202
- }
203
- ```
204
-
205
- ## Features
206
-
207
- - 🔐 Multiple authentication providers
208
- - 📝 Automatic user profile management
209
- - 🔄 Password reset and update functionality
210
- - ✉️ Email verification
211
- - 🗑️ Account deletion
212
- - 🔄 Reauthentication support
213
- - 📚 Automatic Firestore user document management
214
- - ⚡ Type-safe operations
215
-
216
- ## Important Notes
217
-
218
- 1. User data is automatically synchronized with Firestore
219
- 2. Password updates require current password verification
220
- 3. Account deletion removes both authentication and Firestore data
1
+ Svelte Firekit is a powerful Firebase toolkit for SvelteKit applications, providing a comprehensive set of utilities, stores, and components for seamless Firebase integration. Whether you're building a micro SaaS, web application, or any Firebase-powered project, Svelte Firekit streamlines your development process.
2
+
3
+ ## Installation
4
+
5
+ ```bash
6
+ npm install firebase svelte-firekit
7
+ ```
8
+
9
+ ## Configuration
10
+
11
+ Svelte Firekit automatically manages your Firebase configuration through environment variables. Create a `.env` file in your project root with the following variables:
12
+
13
+ ```env
14
+ PUBLIC_FIREBASE_API_KEY=your_api_key
15
+ PUBLIC_FIREBASE_AUTH_DOMAIN=your_auth_domain
16
+ PUBLIC_FIREBASE_PROJECT_ID=your_project_id
17
+ PUBLIC_FIREBASE_STORAGE_BUCKET=your_storage_bucket
18
+ PUBLIC_FIREBASE_MESSAGING_SENDER_ID=your_messaging_sender_id
19
+ PUBLIC_FIREBASE_APP_ID=your_app_id
20
+ PUBLIC_FIREBASE_MEASUREMENT_ID=your_measurement_id
21
+ ```
22
+
23
+ The configuration is automatically handled by Firekit - no manual setup required. If any required environment variables are missing, Firekit will throw a helpful error indicating which variables need to be set.
24
+
25
+ ## Usage Example
26
+
27
+ Here's a simple example showing how to display the current user's name:
28
+
29
+ ```svelte
30
+ <script>
31
+ import { firekitUser } from 'svelte-firekit';
32
+ </script>
33
+
34
+ Hello {firekitUser.displayName}
35
+ ```
36
+
37
+ The `firekitUser` store provides access to the current user's information and authentication state.
38
+
39
+ ## Core Features
40
+
41
+ ### 🔥 Firebase Integration
42
+ - Zero-config Firebase setup through environment variables
43
+ - Automatic initialization and app management
44
+ - Built-in error handling and connection state management
45
+ - Type-safe configuration management
46
+
47
+ ### 🔐 Authentication
48
+ - Complete authentication system with built-in components
49
+ - Support for multiple authentication providers:
50
+ - Email/Password
51
+ - Google
52
+ - GitHub
53
+ - Custom providers
54
+ - User state management and persistence through `firekitUser` store
55
+
56
+ ### 📚 Firestore Integration
57
+ - Reactive data stores for real-time updates
58
+ - Simplified CRUD operations
59
+ - Batch operations and transactions
60
+ - Type-safe document references
61
+ - Automatic data serialization/deserialization
62
+
63
+ ### 📦 Storage Management
64
+ - File upload and download utilities
65
+ - Progress tracking and status updates
66
+ - Storage security rules helpers
67
+ - Image optimization utilities
68
+
69
+ ### Server-Side Rendering
70
+ - Full SSR compatibility
71
+ - Hydration support
72
+ - Server-side data fetching
73
+ - SEO-friendly rendering
74
+
75
+ ### 🎯 Type Safety
76
+ - Built with TypeScript
77
+ - Complete type definitions
78
+ - Intelligent autocomplete
79
+ - Runtime type checking
80
+ - Type-safe Firestore operations
81
+
82
+ ## Why Svelte Firekit?
83
+
84
+ - **Zero Configuration**: Automatic Firebase setup through environment variables
85
+ - **Type Safety**: Full TypeScript support with built-in type checking
86
+ - **Rapid Development**: Get your Firebase-powered SvelteKit application up and running in minutes
87
+ - **Best Practices**: Built following Firebase and SvelteKit best practices
88
+ - **Production Ready**: Battle-tested in production environments
89
+ - **Active Community**: Regular updates and active community support
90
+ - **Extensible**: Easy to customize and extend for your specific needs
91
+
92
+ ## Next Steps
93
+
94
+ - Check out our [Getting Started](/getting-started) guide
95
+ - Explore the [API Reference](/api)
96
+ - View [Examples](/examples)
97
+ - Join our [Community](/community)
98
+
99
+ ## Contributing
100
+
101
+ We welcome contributions! Please see our [Contributing Guide](/contributing) for more details.
102
+
103
+ ## License
104
+
105
+ Svelte Firekit is released under the MIT License. See the [LICENSE](/license) file for more details.
106
+
107
+ # Authentication
108
+
109
+ Svelte Firekit provides a comprehensive authentication system through the `firekitAuth` singleton, offering various authentication methods and user management features.
110
+
111
+ ## Basic Usage
112
+
113
+ ```typescript
114
+ import { firekitAuth } from 'svelte-firekit';
115
+ ```
116
+
117
+ ## Authentication Methods
118
+
119
+ ### Google Authentication
120
+
121
+ ```typescript
122
+ await firekitAuth.signInWithGoogle();
123
+ ```
124
+
125
+ ### Email/Password Authentication
126
+
127
+ ```typescript
128
+ // Sign in
129
+ await firekitAuth.signInWithEmail(email, password);
130
+
131
+ // Register
132
+ await firekitAuth.registerWithEmail(email, password, displayName);
133
+
134
+ // Sign out
135
+ await firekitAuth.logOut();
136
+ ```
137
+
138
+ ## User Management
139
+
140
+ ### Password Management
141
+
142
+ ```typescript
143
+ // Send password reset email
144
+ await firekitAuth.sendPasswordReset(email);
145
+
146
+ // Update password (requires reauthentication)
147
+ await firekitAuth.updateUserPassword(newPassword, currentPassword);
148
+ ```
149
+
150
+ ### Profile Management
151
+
152
+ ```typescript
153
+ // Update user profile
154
+ await firekitAuth.updateUserProfile({
155
+ displayName: "New Name",
156
+ photoURL: "https://example.com/photo.jpg"
157
+ });
158
+ ```
159
+
160
+ ### Email Verification
161
+
162
+ ```typescript
163
+ // Send verification email
164
+ await firekitAuth.sendEmailVerificationToUser();
165
+ ```
166
+
167
+ ### Account Deletion
168
+
169
+ ```typescript
170
+ // Delete user account
171
+ await firekitAuth.deleteUserAccount();
172
+ ```
173
+
174
+ ## Automatic Firestore Integration
175
+
176
+ The authentication system automatically maintains a user document in Firestore with the following information:
177
+ - User ID
178
+ - Email
179
+ - Email verification status
180
+ - Display name
181
+ - Photo URL
182
+ - Authentication provider information
183
+ - Anonymous status
184
+
185
+ ## Error Handling
186
+
187
+ All methods include proper error handling and return appropriate error messages. For example, password updates will return:
188
+
189
+ ```typescript
190
+ {
191
+ success: boolean;
192
+ message: string;
193
+ code?: string; // In case of errors
194
+ }
195
+ ```
196
+
197
+ ## Features
198
+
199
+ - 🔐 Multiple authentication providers
200
+ - 📝 Automatic user profile management
201
+ - 🔄 Password reset and update functionality
202
+ - ✉️ Email verification
203
+ - 🗑️ Account deletion
204
+ - 🔄 Reauthentication support
205
+ - 📚 Automatic Firestore user document management
206
+ - ⚡ Type-safe operations
207
+
208
+ ## Important Notes
209
+
210
+ 1. User data is automatically synchronized with Firestore
211
+ 2. Password updates require current password verification
212
+ 3. Account deletion removes both authentication and Firestore data
221
213
  4. All operations are fully typed for TypeScript support
@@ -0,0 +1,140 @@
1
+ /**
2
+ * @module FirekitBatchMutations
3
+ */
4
+ import { type DocumentData, type WithFieldValue } from 'firebase/firestore';
5
+ /**
6
+ * Response structure for batch operations
7
+ * @interface BatchResponse
8
+ */
9
+ interface BatchResponse {
10
+ /** Operation success status */
11
+ success: boolean;
12
+ /** Number of processed items */
13
+ processedItems?: number;
14
+ /** Error details if operation failed */
15
+ error?: {
16
+ code: string;
17
+ message: string;
18
+ };
19
+ }
20
+ /**
21
+ * Options for batch mutations
22
+ * @interface BatchMutationOptions
23
+ */
24
+ interface BatchMutationOptions {
25
+ /** Whether to include timestamp fields */
26
+ timestamps?: boolean;
27
+ /** Whether to merge data in set operations */
28
+ merge?: boolean;
29
+ /** Batch size limit (default: 500) */
30
+ batchSize?: number;
31
+ /** Delay between batches in milliseconds (default: 3000) */
32
+ delayBetweenBatches?: number;
33
+ }
34
+ /**
35
+ * Batch operation type
36
+ * @type BatchOperation
37
+ */
38
+ type BatchOperation<T> = {
39
+ /** Operation type */
40
+ type: 'set' | 'update' | 'delete';
41
+ /** Document path */
42
+ path: string;
43
+ /** Document data */
44
+ data?: WithFieldValue<T>;
45
+ /** Operation options */
46
+ options?: BatchMutationOptions;
47
+ };
48
+ /**
49
+ * Manages Firestore batch operations with automatic timestamps and error handling
50
+ * @class
51
+ */
52
+ declare class FirekitBatchMutations {
53
+ /** Default batch size limit */
54
+ private readonly DEFAULT_BATCH_LIMIT;
55
+ /** Default delay between batches in milliseconds */
56
+ private readonly DEFAULT_BATCH_DELAY;
57
+ /**
58
+ * Generates timestamp data for document mutations
59
+ * @private
60
+ * @param {boolean} [isNew=true] Whether this is a new document
61
+ * @returns {Record<string, any>} Timestamp data
62
+ */
63
+ private getTimestampData;
64
+ /**
65
+ * Creates a delay between batch operations
66
+ * @private
67
+ * @param {number} ms Milliseconds to delay
68
+ * @returns {Promise<void>}
69
+ */
70
+ private delay;
71
+ /**
72
+ * Handles and formats batch operation errors
73
+ * @private
74
+ * @param {any} error Error object
75
+ * @returns {BatchResponse} Formatted error response
76
+ */
77
+ private handleError;
78
+ /**
79
+ * Executes multiple write operations as batches
80
+ * @template T Document data type
81
+ * @param {BatchOperation<T>[]} operations Array of batch operations
82
+ * @param {BatchMutationOptions} [options] Batch options
83
+ * @returns {Promise<BatchResponse>} Batch operation response
84
+ *
85
+ * @example
86
+ * ```typescript
87
+ * const operations = [
88
+ * {
89
+ * type: 'set',
90
+ * path: 'cities/NYC',
91
+ * data: { name: 'New York City' }
92
+ * },
93
+ * {
94
+ * type: 'update',
95
+ * path: 'cities/SF',
96
+ * data: { population: 1000000 }
97
+ * },
98
+ * {
99
+ * type: 'delete',
100
+ * path: 'cities/LA'
101
+ * }
102
+ * ];
103
+ *
104
+ * const result = await firekitBatchMutations.batch(operations);
105
+ * ```
106
+ */
107
+ batch<T extends DocumentData>(operations: BatchOperation<T>[], options?: BatchMutationOptions): Promise<BatchResponse>;
108
+ /**
109
+ * Inserts multiple items into a collection using batched writes
110
+ * @template T Document data type
111
+ * @param {string} collectionPath Collection path
112
+ * @param {T[]} items Array of items to insert
113
+ * @param {BatchMutationOptions} [options] Batch options
114
+ * @param {string} [idKey] Optional key to use as document ID from items
115
+ * @returns {Promise<BatchResponse>} Batch operation response
116
+ *
117
+ * @example
118
+ * ```typescript
119
+ * const items = [
120
+ * { id: 'nyc', name: 'New York City' },
121
+ * { id: 'sf', name: 'San Francisco' }
122
+ * ];
123
+ *
124
+ * const result = await firekitBatchMutations.batchInsert(
125
+ * 'cities',
126
+ * items,
127
+ * { timestamps: true },
128
+ * 'id'
129
+ * );
130
+ * ```
131
+ */
132
+ batchInsert<T extends DocumentData>(collectionPath: string, items: T[], options?: BatchMutationOptions, idKey?: string): Promise<BatchResponse>;
133
+ }
134
+ /**
135
+ * Pre-initialized instance of FirekitBatchMutations
136
+ * @const
137
+ * @type {FirekitBatchMutations}
138
+ */
139
+ export declare const firekitBatchMutations: FirekitBatchMutations;
140
+ export {};
@@ -0,0 +1,218 @@
1
+ /**
2
+ * @module FirekitBatchMutations
3
+ */
4
+ import { doc, setDoc, updateDoc, deleteDoc, getDoc, collection, writeBatch, serverTimestamp } from 'firebase/firestore';
5
+ import { firebaseService } from '../firebase.js';
6
+ import { firekitUser } from '../auth/user.svelte.js';
7
+ /**
8
+ * Manages Firestore batch operations with automatic timestamps and error handling
9
+ * @class
10
+ */
11
+ class FirekitBatchMutations {
12
+ /** Default batch size limit */
13
+ DEFAULT_BATCH_LIMIT = 500;
14
+ /** Default delay between batches in milliseconds */
15
+ DEFAULT_BATCH_DELAY = 3000;
16
+ /**
17
+ * Generates timestamp data for document mutations
18
+ * @private
19
+ * @param {boolean} [isNew=true] Whether this is a new document
20
+ * @returns {Record<string, any>} Timestamp data
21
+ */
22
+ getTimestampData(isNew = true) {
23
+ const timestamps = {
24
+ updatedAt: serverTimestamp(),
25
+ updatedBy: firekitUser.uid
26
+ };
27
+ if (isNew) {
28
+ timestamps.createdAt = serverTimestamp();
29
+ timestamps.createdBy = firekitUser.uid;
30
+ }
31
+ return timestamps;
32
+ }
33
+ /**
34
+ * Creates a delay between batch operations
35
+ * @private
36
+ * @param {number} ms Milliseconds to delay
37
+ * @returns {Promise<void>}
38
+ */
39
+ async delay(ms) {
40
+ return new Promise((resolve) => setTimeout(resolve, ms));
41
+ }
42
+ /**
43
+ * Handles and formats batch operation errors
44
+ * @private
45
+ * @param {any} error Error object
46
+ * @returns {BatchResponse} Formatted error response
47
+ */
48
+ handleError(error) {
49
+ console.error('Firestore batch operation error:', error);
50
+ return {
51
+ success: false,
52
+ error: {
53
+ code: error.code || 'unknown_error',
54
+ message: error.message || 'An unknown error occurred'
55
+ }
56
+ };
57
+ }
58
+ /**
59
+ * Executes multiple write operations as batches
60
+ * @template T Document data type
61
+ * @param {BatchOperation<T>[]} operations Array of batch operations
62
+ * @param {BatchMutationOptions} [options] Batch options
63
+ * @returns {Promise<BatchResponse>} Batch operation response
64
+ *
65
+ * @example
66
+ * ```typescript
67
+ * const operations = [
68
+ * {
69
+ * type: 'set',
70
+ * path: 'cities/NYC',
71
+ * data: { name: 'New York City' }
72
+ * },
73
+ * {
74
+ * type: 'update',
75
+ * path: 'cities/SF',
76
+ * data: { population: 1000000 }
77
+ * },
78
+ * {
79
+ * type: 'delete',
80
+ * path: 'cities/LA'
81
+ * }
82
+ * ];
83
+ *
84
+ * const result = await firekitBatchMutations.batch(operations);
85
+ * ```
86
+ */
87
+ async batch(operations, options = {}) {
88
+ try {
89
+ const firestore = firebaseService.getDbInstance();
90
+ let batch = writeBatch(firestore);
91
+ let batchCounter = 0;
92
+ const batchLimit = options.batchSize || this.DEFAULT_BATCH_LIMIT;
93
+ const batchDelay = options.delayBetweenBatches || this.DEFAULT_BATCH_DELAY;
94
+ for (const [index, operation] of operations.entries()) {
95
+ const docRef = doc(firestore, operation.path);
96
+ switch (operation.type) {
97
+ case 'set': {
98
+ if (!operation.data) {
99
+ throw new Error('Data is required for set operation');
100
+ }
101
+ const dataToSet = {
102
+ ...operation.data,
103
+ ...(operation.options?.timestamps && this.getTimestampData()),
104
+ id: docRef.id
105
+ };
106
+ batch.set(docRef, dataToSet, {
107
+ merge: operation.options?.merge
108
+ });
109
+ break;
110
+ }
111
+ case 'update': {
112
+ if (!operation.data) {
113
+ throw new Error('Data is required for update operation');
114
+ }
115
+ const dataToUpdate = {
116
+ ...operation.data,
117
+ ...(operation.options?.timestamps && this.getTimestampData(false))
118
+ };
119
+ batch.update(docRef, dataToUpdate);
120
+ break;
121
+ }
122
+ case 'delete': {
123
+ batch.delete(docRef);
124
+ break;
125
+ }
126
+ default:
127
+ throw new Error(`Invalid operation type: ${operation.type}`);
128
+ }
129
+ batchCounter++;
130
+ // If batch limit reached or last item, commit and create new batch
131
+ if (batchCounter === batchLimit || index === operations.length - 1) {
132
+ await batch.commit();
133
+ console.log(`Batch committed at index ${index} of ${operations.length} operations.`);
134
+ if (index < operations.length - 1) {
135
+ batch = writeBatch(firestore);
136
+ batchCounter = 0;
137
+ await this.delay(batchDelay);
138
+ }
139
+ }
140
+ }
141
+ return {
142
+ success: true,
143
+ processedItems: operations.length
144
+ };
145
+ }
146
+ catch (error) {
147
+ return this.handleError(error);
148
+ }
149
+ }
150
+ /**
151
+ * Inserts multiple items into a collection using batched writes
152
+ * @template T Document data type
153
+ * @param {string} collectionPath Collection path
154
+ * @param {T[]} items Array of items to insert
155
+ * @param {BatchMutationOptions} [options] Batch options
156
+ * @param {string} [idKey] Optional key to use as document ID from items
157
+ * @returns {Promise<BatchResponse>} Batch operation response
158
+ *
159
+ * @example
160
+ * ```typescript
161
+ * const items = [
162
+ * { id: 'nyc', name: 'New York City' },
163
+ * { id: 'sf', name: 'San Francisco' }
164
+ * ];
165
+ *
166
+ * const result = await firekitBatchMutations.batchInsert(
167
+ * 'cities',
168
+ * items,
169
+ * { timestamps: true },
170
+ * 'id'
171
+ * );
172
+ * ```
173
+ */
174
+ async batchInsert(collectionPath, items, options = { timestamps: true }, idKey) {
175
+ try {
176
+ const firestore = firebaseService.getDbInstance();
177
+ let batch = writeBatch(firestore);
178
+ let batchCounter = 0;
179
+ const batchLimit = options.batchSize || this.DEFAULT_BATCH_LIMIT;
180
+ const batchDelay = options.delayBetweenBatches || this.DEFAULT_BATCH_DELAY;
181
+ for (const [index, item] of items.entries()) {
182
+ const docRef = idKey && item[idKey]
183
+ ? doc(firestore, collectionPath, item[idKey])
184
+ : doc(collection(firestore, collectionPath));
185
+ const dataToSet = {
186
+ ...item,
187
+ ...(options.timestamps && this.getTimestampData()),
188
+ id: docRef.id
189
+ };
190
+ batch.set(docRef, dataToSet, { merge: options.merge });
191
+ batchCounter++;
192
+ // If batch limit reached or last item, commit and create new batch
193
+ if (batchCounter === batchLimit || index === items.length - 1) {
194
+ await batch.commit();
195
+ console.log(`Batch committed at index ${index} of ${items.length} items.`);
196
+ if (index < items.length - 1) {
197
+ batch = writeBatch(firestore);
198
+ batchCounter = 0;
199
+ await this.delay(batchDelay);
200
+ }
201
+ }
202
+ }
203
+ return {
204
+ success: true,
205
+ processedItems: items.length
206
+ };
207
+ }
208
+ catch (error) {
209
+ return this.handleError(error);
210
+ }
211
+ }
212
+ }
213
+ /**
214
+ * Pre-initialized instance of FirekitBatchMutations
215
+ * @const
216
+ * @type {FirekitBatchMutations}
217
+ */
218
+ export const firekitBatchMutations = new FirekitBatchMutations();
@@ -0,0 +1,78 @@
1
+ /**
2
+ * @module FirekitCollectionGroup
3
+ */
4
+ import { type Query, type DocumentData, type QueryConstraint } from "firebase/firestore";
5
+ /**
6
+ * Manages real-time Firestore collection group subscriptions with reactive state
7
+ * @class
8
+ * @template T Collection document type
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * interface Task {
13
+ * id: string;
14
+ * title: string;
15
+ * status: string;
16
+ * }
17
+ *
18
+ * // Create collection group subscription
19
+ * const allTasks = firekitCollectionGroup<Task>('tasks',
20
+ * where('status', '==', 'active'),
21
+ * orderBy('title')
22
+ * );
23
+ * ```
24
+ */
25
+ declare class FirekitCollectionGroup<T> {
26
+ /** Current collection group data */
27
+ private _data;
28
+ /** Loading state */
29
+ private _loading;
30
+ /** Error state */
31
+ private _error;
32
+ /** Query reference */
33
+ private queryRef;
34
+ /**
35
+ * Creates a collection group subscription
36
+ * @param {string} collectionId Collection ID to query across all documents
37
+ * @param {...QueryConstraint[]} queryConstraints Query constraints (where, orderBy, limit, etc.)
38
+ */
39
+ constructor(collectionId: string, ...queryConstraints: QueryConstraint[]);
40
+ /** Gets current collection group data */
41
+ get data(): T[];
42
+ /** Gets loading state */
43
+ get loading(): boolean;
44
+ /** Gets error state */
45
+ get error(): Error | null;
46
+ /** Checks if collection group is empty */
47
+ get empty(): boolean;
48
+ /** Gets number of documents in collection group */
49
+ get size(): number;
50
+ /**
51
+ * Gets query reference
52
+ * @throws {Error} If query reference is not available
53
+ */
54
+ get ref(): Query<T>;
55
+ }
56
+ /**
57
+ * Creates a collection group subscription
58
+ * @template T Collection document type
59
+ * @param {string} collectionId Collection ID to query across all documents
60
+ * @param {...QueryConstraint[]} queryConstraints Query constraints
61
+ * @returns {FirekitCollectionGroup<T>} Collection group subscription instance
62
+ *
63
+ * @example
64
+ * ```typescript
65
+ * interface Comment {
66
+ * id: string;
67
+ * text: string;
68
+ * userId: string;
69
+ * }
70
+ *
71
+ * const allComments = firekitCollectionGroup<Comment>('comments',
72
+ * where('userId', '==', currentUserId),
73
+ * orderBy('createdAt', 'desc')
74
+ * );
75
+ * ```
76
+ */
77
+ export declare function firekitCollectionGroup<T extends DocumentData>(collectionId: string, ...queryConstraints: QueryConstraint[]): FirekitCollectionGroup<T>;
78
+ export {};
@@ -0,0 +1,120 @@
1
+ /**
2
+ * @module FirekitCollectionGroup
3
+ */
4
+ import { collectionGroup, query, onSnapshot } from "firebase/firestore";
5
+ import { firebaseService } from "../firebase.js";
6
+ import { browser } from "$app/environment";
7
+ /**
8
+ * Manages real-time Firestore collection group subscriptions with reactive state
9
+ * @class
10
+ * @template T Collection document type
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * interface Task {
15
+ * id: string;
16
+ * title: string;
17
+ * status: string;
18
+ * }
19
+ *
20
+ * // Create collection group subscription
21
+ * const allTasks = firekitCollectionGroup<Task>('tasks',
22
+ * where('status', '==', 'active'),
23
+ * orderBy('title')
24
+ * );
25
+ * ```
26
+ */
27
+ class FirekitCollectionGroup {
28
+ /** Current collection group data */
29
+ _data = $state([]);
30
+ /** Loading state */
31
+ _loading = $state(true);
32
+ /** Error state */
33
+ _error = $state(null);
34
+ /** Query reference */
35
+ queryRef = null;
36
+ /**
37
+ * Creates a collection group subscription
38
+ * @param {string} collectionId Collection ID to query across all documents
39
+ * @param {...QueryConstraint[]} queryConstraints Query constraints (where, orderBy, limit, etc.)
40
+ */
41
+ constructor(collectionId, ...queryConstraints) {
42
+ if (browser) {
43
+ try {
44
+ const firestore = firebaseService.getDbInstance();
45
+ const groupRef = collectionGroup(firestore, collectionId);
46
+ this.queryRef = query(groupRef, ...queryConstraints);
47
+ onSnapshot(this.queryRef, (snapshot) => {
48
+ this._data = snapshot.docs.map(doc => ({
49
+ id: doc.id,
50
+ path: doc.ref.path,
51
+ ...doc.data()
52
+ }));
53
+ this._loading = false;
54
+ this._error = null;
55
+ }, (error) => {
56
+ this._error = error;
57
+ this._loading = false;
58
+ });
59
+ }
60
+ catch (error) {
61
+ this._error = error;
62
+ this._loading = false;
63
+ }
64
+ }
65
+ }
66
+ /** Gets current collection group data */
67
+ get data() {
68
+ return this._data;
69
+ }
70
+ /** Gets loading state */
71
+ get loading() {
72
+ return this._loading;
73
+ }
74
+ /** Gets error state */
75
+ get error() {
76
+ return this._error;
77
+ }
78
+ /** Checks if collection group is empty */
79
+ get empty() {
80
+ return this._data.length === 0;
81
+ }
82
+ /** Gets number of documents in collection group */
83
+ get size() {
84
+ return this._data.length;
85
+ }
86
+ /**
87
+ * Gets query reference
88
+ * @throws {Error} If query reference is not available
89
+ */
90
+ get ref() {
91
+ if (!this.queryRef) {
92
+ throw new Error("Query reference is not available");
93
+ }
94
+ return this.queryRef;
95
+ }
96
+ }
97
+ /**
98
+ * Creates a collection group subscription
99
+ * @template T Collection document type
100
+ * @param {string} collectionId Collection ID to query across all documents
101
+ * @param {...QueryConstraint[]} queryConstraints Query constraints
102
+ * @returns {FirekitCollectionGroup<T>} Collection group subscription instance
103
+ *
104
+ * @example
105
+ * ```typescript
106
+ * interface Comment {
107
+ * id: string;
108
+ * text: string;
109
+ * userId: string;
110
+ * }
111
+ *
112
+ * const allComments = firekitCollectionGroup<Comment>('comments',
113
+ * where('userId', '==', currentUserId),
114
+ * orderBy('createdAt', 'desc')
115
+ * );
116
+ * ```
117
+ */
118
+ export function firekitCollectionGroup(collectionId, ...queryConstraints) {
119
+ return new FirekitCollectionGroup(collectionId, ...queryConstraints);
120
+ }
package/dist/index.d.ts CHANGED
@@ -7,6 +7,7 @@ export { firekitAwaitableDoc } from './firestore/awaitable-doc.svelte.js';
7
7
  export { firekitDocMutations } from './firestore/document-mutations.svelte.js';
8
8
  export { firekitCollection } from './firestore/collection.svelte.js';
9
9
  export { firekitDoc } from './firestore/doc.svelte.js';
10
+ export { firekitCollectionGroup } from './firestore/collection-group.svelte.js';
10
11
  export { firekitRealtimeDB } from './realtime/realtime.svelte.js';
11
12
  export { firekitDownloadUrl } from './storage/download-url.svelte.js';
12
13
  export { firekitStorageList } from './storage/storage-list.svelte.js';
package/dist/index.js CHANGED
@@ -10,6 +10,7 @@ export { firekitAwaitableDoc } from './firestore/awaitable-doc.svelte.js';
10
10
  export { firekitDocMutations } from './firestore/document-mutations.svelte.js';
11
11
  export { firekitCollection } from './firestore/collection.svelte.js';
12
12
  export { firekitDoc } from './firestore/doc.svelte.js';
13
+ export { firekitCollectionGroup } from './firestore/collection-group.svelte.js';
13
14
  // realtime services
14
15
  export { firekitRealtimeDB } from './realtime/realtime.svelte.js';
15
16
  // Storage services
package/package.json CHANGED
@@ -1,65 +1,65 @@
1
- {
2
- "name": "svelte-firekit",
3
- "version": "0.0.22",
4
- "license": "MIT",
5
- "scripts": {
6
- "dev": "vite dev",
7
- "build": "vite build && npm run package",
8
- "preview": "vite preview",
9
- "package": "svelte-kit sync && svelte-package && publint",
10
- "prepublishOnly": "npm run package",
11
- "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
12
- "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
13
- "format": "prettier --write .",
14
- "lint": "prettier --check ."
15
- },
16
- "repository": {
17
- "type": "git",
18
- "url": "https://github.com/code-gio/svelte-firekit.git"
19
- },
20
- "description": "A Svelte library for Firebase integration",
21
- "keywords": [
22
- "svelte",
23
- "firebase",
24
- "library",
25
- "frontend"
26
- ],
27
- "author": "Giovani Rodriguez",
28
- "files": [
29
- "dist",
30
- "!dist/**/*.test.*",
31
- "!dist/**/*.spec.*"
32
- ],
33
- "sideEffects": [
34
- "**/*.css"
35
- ],
36
- "svelte": "./dist/index.js",
37
- "types": "./dist/index.d.ts",
38
- "type": "module",
39
- "exports": {
40
- ".": {
41
- "types": "./dist/index.d.ts",
42
- "svelte": "./dist/index.js"
43
- }
44
- },
45
- "peerDependencies": {
46
- "firebase": "^11.0.1",
47
- "svelte": "^5.0.0"
48
- },
49
- "devDependencies": {
50
- "@sveltejs/adapter-auto": "^3.0.0",
51
- "@sveltejs/kit": "^2.9.0",
52
- "@sveltejs/package": "^2.0.0",
53
- "@sveltejs/vite-plugin-svelte": "^5.0.0",
54
- "prettier": "^3.3.2",
55
- "prettier-plugin-svelte": "^3.2.6",
56
- "publint": "^0.2.0",
57
- "svelte": "^5.0.0",
58
- "svelte-check": "^4.0.0",
59
- "typescript": "^5.0.0",
60
- "vite": "^6.0.0"
61
- },
62
- "dependencies": {
63
- "firebase": "^11.0.2"
64
- }
1
+ {
2
+ "name": "svelte-firekit",
3
+ "version": "0.0.24",
4
+ "license": "MIT",
5
+ "scripts": {
6
+ "dev": "vite dev",
7
+ "build": "vite build && npm run package",
8
+ "preview": "vite preview",
9
+ "package": "svelte-kit sync && svelte-package && publint",
10
+ "prepublishOnly": "npm run package",
11
+ "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
12
+ "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
13
+ "format": "prettier --write .",
14
+ "lint": "prettier --check ."
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "https://github.com/code-gio/svelte-firekit.git"
19
+ },
20
+ "description": "A Svelte library for Firebase integration",
21
+ "keywords": [
22
+ "svelte",
23
+ "firebase",
24
+ "library",
25
+ "frontend"
26
+ ],
27
+ "author": "Giovani Rodriguez",
28
+ "files": [
29
+ "dist",
30
+ "!dist/**/*.test.*",
31
+ "!dist/**/*.spec.*"
32
+ ],
33
+ "sideEffects": [
34
+ "**/*.css"
35
+ ],
36
+ "svelte": "./dist/index.js",
37
+ "types": "./dist/index.d.ts",
38
+ "type": "module",
39
+ "exports": {
40
+ ".": {
41
+ "types": "./dist/index.d.ts",
42
+ "svelte": "./dist/index.js"
43
+ }
44
+ },
45
+ "peerDependencies": {
46
+ "firebase": "^11.0.1",
47
+ "svelte": "^5.0.0"
48
+ },
49
+ "devDependencies": {
50
+ "@sveltejs/adapter-auto": "^3.0.0",
51
+ "@sveltejs/kit": "^2.9.0",
52
+ "@sveltejs/package": "^2.0.0",
53
+ "@sveltejs/vite-plugin-svelte": "^5.0.0",
54
+ "prettier": "^3.3.2",
55
+ "prettier-plugin-svelte": "^3.2.6",
56
+ "publint": "^0.2.0",
57
+ "svelte": "^5.0.0",
58
+ "svelte-check": "^4.0.0",
59
+ "typescript": "^5.0.0",
60
+ "vite": "^6.0.0"
61
+ },
62
+ "dependencies": {
63
+ "firebase": "^11.0.2"
64
+ }
65
65
  }