svelte-firekit 0.0.23 → 0.0.25

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,213 +1,213 @@
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
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
213
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, 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();
package/dist/index.d.ts CHANGED
@@ -8,6 +8,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
10
  export { firekitCollectionGroup } from './firestore/collection-group.svelte.js';
11
+ export { firekitBatchMutations } from './firestore/batch-mutations.svelte.js';
11
12
  export { firekitRealtimeDB } from './realtime/realtime.svelte.js';
12
13
  export { firekitDownloadUrl } from './storage/download-url.svelte.js';
13
14
  export { firekitStorageList } from './storage/storage-list.svelte.js';
package/dist/index.js CHANGED
@@ -11,6 +11,7 @@ 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
13
  export { firekitCollectionGroup } from './firestore/collection-group.svelte.js';
14
+ export { firekitBatchMutations } from './firestore/batch-mutations.svelte.js';
14
15
  // realtime services
15
16
  export { firekitRealtimeDB } from './realtime/realtime.svelte.js';
16
17
  // Storage services
package/package.json CHANGED
@@ -1,65 +1,65 @@
1
- {
2
- "name": "svelte-firekit",
3
- "version": "0.0.23",
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.25",
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
  }