@seaverse/data-service-sdk 0.4.0 → 0.5.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/README.md CHANGED
@@ -85,16 +85,14 @@ import { DataServiceClient } from '@seaverse/data-service-sdk';
85
85
 
86
86
  ## Quick Start
87
87
 
88
- ### For Authenticated Users
88
+ ### 🚀 Easiest Way (Recommended - Auto Firebase Setup)
89
89
 
90
90
  ```typescript
91
- import { DataServiceClient } from '@seaverse/data-service-sdk';
91
+ import { DataServiceClient, initializeWithToken } from '@seaverse/data-service-sdk';
92
92
  import { AuthClient } from '@seaverse/auth-sdk';
93
- import { initializeApp } from 'firebase/app';
94
- import { getAuth, signInWithCustomToken } from 'firebase/auth';
95
- import { getFirestore, collection, addDoc, getDocs, serverTimestamp } from 'firebase/firestore';
93
+ import { collection, addDoc, getDocs, serverTimestamp } from 'firebase/firestore';
96
94
 
97
- // Step 1: Login user with Auth SDK
95
+ // Step 1: Login user
98
96
  const authClient = new AuthClient({ appId: 'my-app-123' });
99
97
  const loginResponse = await authClient.loginWithEmail({
100
98
  email: 'user@example.com',
@@ -103,20 +101,15 @@ const loginResponse = await authClient.loginWithEmail({
103
101
 
104
102
  // Step 2: Get Firestore token
105
103
  const dataClient = new DataServiceClient();
106
- const firestoreToken = await dataClient.generateFirestoreToken({
107
- token: loginResponse.token, // JWT from auth
104
+ const tokenResponse = await dataClient.generateFirestoreToken({
105
+ token: loginResponse.token,
108
106
  app_id: 'my-app-123'
109
107
  });
110
108
 
111
- // Step 3: Initialize Firebase
112
- const app = initializeApp({ projectId: firestoreToken.project_id });
113
- const auth = getAuth(app);
114
- await signInWithCustomToken(auth, firestoreToken.custom_token);
115
- const db = getFirestore(app);
109
+ // Step 3: Auto-initialize Firebase (ONE LINE!)
110
+ const { db, appId, userId } = await initializeWithToken(tokenResponse);
116
111
 
117
- // Step 4: Use Firestore with proper paths
118
- const appId = firestoreToken.app_id;
119
- const userId = firestoreToken.user_id;
112
+ // Step 4: Use Firestore directly!
120
113
 
121
114
  // Write to publicData (everyone can write)
122
115
  await addDoc(collection(db, `appData/${appId}/publicData/posts`), {
@@ -143,31 +136,26 @@ await addDoc(collection(db, `appData/${appId}/userData/${userId}/notes`), {
143
136
  });
144
137
  ```
145
138
 
146
- ### For Guest Users
139
+ ### 👤 For Guest Users (Even Simpler!)
147
140
 
148
141
  ```typescript
149
- import { DataServiceClient } from '@seaverse/data-service-sdk';
150
- import { initializeApp } from 'firebase/app';
151
- import { getAuth, signInWithCustomToken } from 'firebase/auth';
152
- import { getFirestore, collection, addDoc, serverTimestamp } from 'firebase/firestore';
142
+ import { DataServiceClient, initializeWithToken } from '@seaverse/data-service-sdk';
143
+ import { collection, addDoc, serverTimestamp } from 'firebase/firestore';
153
144
 
154
145
  // Step 1: Get guest token (no authentication needed!)
155
146
  const dataClient = new DataServiceClient();
156
- const guestToken = await dataClient.generateGuestFirestoreToken({
147
+ const tokenResponse = await dataClient.generateGuestFirestoreToken({
157
148
  app_id: 'my-app-123'
158
149
  });
159
150
 
160
- // Step 2: Initialize Firebase
161
- const app = initializeApp({ projectId: guestToken.project_id });
162
- const auth = getAuth(app);
163
- await signInWithCustomToken(auth, guestToken.custom_token);
164
- const db = getFirestore(app);
151
+ // Step 2: Auto-initialize Firebase (ONE LINE!)
152
+ const { db, appId, userId } = await initializeWithToken(tokenResponse);
165
153
 
166
154
  // Step 3: Guest can write to publicData
167
- await addDoc(collection(db, `appData/${guestToken.app_id}/publicData/comments`), {
168
- _appId: guestToken.app_id,
155
+ await addDoc(collection(db, `appData/${appId}/publicData/comments`), {
156
+ _appId: appId,
169
157
  _createdAt: serverTimestamp(),
170
- _createdBy: guestToken.user_id, // Guest user ID (e.g., 'guest-abc123')
158
+ _createdBy: userId, // Guest user ID (e.g., 'guest-abc123')
171
159
  comment: 'Great app!',
172
160
  rating: 5
173
161
  });
@@ -175,6 +163,36 @@ await addDoc(collection(db, `appData/${guestToken.app_id}/publicData/comments`),
175
163
  // Note: Guests CANNOT access userData
176
164
  ```
177
165
 
166
+ ### 🔧 Manual Way (If you need more control)
167
+
168
+ If you prefer to initialize Firebase manually:
169
+
170
+ ```typescript
171
+ import { DataServiceClient, getFirebaseConfig } from '@seaverse/data-service-sdk';
172
+ import { initializeApp } from 'firebase/app';
173
+ import { getAuth, signInWithCustomToken } from 'firebase/auth';
174
+ import { getFirestore } from 'firebase/firestore';
175
+
176
+ const dataClient = new DataServiceClient();
177
+ const tokenResponse = await dataClient.generateGuestFirestoreToken({
178
+ app_id: 'my-app-123'
179
+ });
180
+
181
+ // Option 1: Use getFirebaseConfig helper
182
+ const firebaseConfig = getFirebaseConfig(tokenResponse);
183
+ const app = initializeApp(firebaseConfig);
184
+
185
+ // Option 2: Manual config
186
+ const app = initializeApp({
187
+ apiKey: tokenResponse.web_api_key, // ✅ Provided automatically!
188
+ projectId: tokenResponse.project_id
189
+ });
190
+
191
+ const auth = getAuth(app);
192
+ await signInWithCustomToken(auth, tokenResponse.custom_token);
193
+ const db = getFirestore(app);
194
+ ```
195
+
178
196
  ## API Reference
179
197
 
180
198
  ### DataServiceClient
@@ -232,11 +250,12 @@ interface GenerateFirestoreTokenRequest {
232
250
  ```typescript
233
251
  interface FirestoreTokenResponse {
234
252
  custom_token: string; // Firebase Custom Token - use with signInWithCustomToken()
253
+ web_api_key: string; // Firebase Web API Key - use with initializeApp()
235
254
  project_id: string; // Firebase Project ID for initializeApp()
236
255
  database_id: string; // Firestore Database ID
237
256
  app_id?: string; // Application ID (use in Firestore paths)
238
257
  user_id: string; // User ID (use in Firestore paths)
239
- role?: string; // User role ('guest', 'user', 'admin')
258
+ user_type: string; // User type ('guest', 'user', 'admin', 'appadmin')
240
259
  expires_in: number; // Token expiration in seconds (typically 3600)
241
260
  }
242
261
  ```
@@ -286,7 +305,63 @@ const guestToken = await client.generateGuestFirestoreToken({
286
305
 
287
306
  console.log('Guest Custom Token:', guestToken.custom_token);
288
307
  console.log('Guest User ID:', guestToken.user_id);
289
- console.log('Role:', guestToken.role); // 'guest'
308
+ console.log('User Type:', guestToken.user_type); // 'guest'
309
+ ```
310
+
311
+ ### Helper Functions
312
+
313
+ #### getFirebaseConfig
314
+
315
+ Extract Firebase configuration from token response.
316
+
317
+ ```typescript
318
+ getFirebaseConfig(tokenResponse: FirestoreTokenResponse): FirebaseConfig
319
+ ```
320
+
321
+ **Example:**
322
+
323
+ ```typescript
324
+ import { getFirebaseConfig } from '@seaverse/data-service-sdk';
325
+ import { initializeApp } from 'firebase/app';
326
+
327
+ const tokenResponse = await client.generateGuestFirestoreToken({ app_id: 'my-app' });
328
+ const firebaseConfig = getFirebaseConfig(tokenResponse);
329
+ // Returns: { apiKey: '...', projectId: '...' }
330
+
331
+ const app = initializeApp(firebaseConfig);
332
+ ```
333
+
334
+ #### initializeWithToken
335
+
336
+ Automatically initialize Firebase and sign in with token (one-line setup).
337
+
338
+ ```typescript
339
+ initializeWithToken(tokenResponse: FirestoreTokenResponse): Promise<{
340
+ app: FirebaseApp;
341
+ auth: Auth;
342
+ db: Firestore;
343
+ userId: string;
344
+ appId: string;
345
+ }>
346
+ ```
347
+
348
+ **Example:**
349
+
350
+ ```typescript
351
+ import { initializeWithToken } from '@seaverse/data-service-sdk';
352
+
353
+ const tokenResponse = await client.generateGuestFirestoreToken({ app_id: 'my-app' });
354
+
355
+ // One line to get everything!
356
+ const { db, appId, userId } = await initializeWithToken(tokenResponse);
357
+
358
+ // Ready to use Firestore
359
+ await addDoc(collection(db, `appData/${appId}/publicData/posts`), { ... });
360
+ ```
361
+
362
+ **Note:** This function requires Firebase SDK to be installed separately:
363
+ ```bash
364
+ npm install firebase
290
365
  ```
291
366
 
292
367
  ## Common Use Cases
package/dist/browser.js CHANGED
@@ -4173,5 +4173,94 @@ class DataServiceClient {
4173
4173
  }
4174
4174
  }
4175
4175
 
4176
- export { DEFAULT_BASE_URL, DEFAULT_TIMEOUT, DataServiceClient, ENDPOINTS };
4176
+ /**
4177
+ * Create Firebase configuration from Firestore token response
4178
+ *
4179
+ * This helper function extracts the Firebase config from the token response,
4180
+ * making it easy to initialize Firebase app.
4181
+ *
4182
+ * @param tokenResponse - The Firestore token response from SDK
4183
+ * @returns Firebase configuration object ready for initializeApp()
4184
+ *
4185
+ * @example
4186
+ * ```typescript
4187
+ * import { initializeApp } from 'firebase/app';
4188
+ * import { getFirebaseConfig } from '@seaverse/data-service-sdk';
4189
+ *
4190
+ * const tokenResponse = await client.generateGuestFirestoreToken({ app_id: 'my-app' });
4191
+ * const firebaseConfig = getFirebaseConfig(tokenResponse);
4192
+ *
4193
+ * const app = initializeApp(firebaseConfig);
4194
+ * ```
4195
+ */
4196
+ function getFirebaseConfig(tokenResponse) {
4197
+ return {
4198
+ apiKey: tokenResponse.web_api_key,
4199
+ projectId: tokenResponse.project_id,
4200
+ };
4201
+ }
4202
+ /**
4203
+ * Initialize Firebase with Firestore token response (browser only)
4204
+ *
4205
+ * This is a convenience function that automatically:
4206
+ * 1. Creates Firebase config from token response
4207
+ * 2. Initializes Firebase app
4208
+ * 3. Signs in with the custom token
4209
+ * 4. Returns authenticated Firebase instances
4210
+ *
4211
+ * IMPORTANT: This function requires Firebase SDK to be installed separately:
4212
+ * npm install firebase
4213
+ *
4214
+ * @param tokenResponse - The Firestore token response from SDK
4215
+ * @returns Object containing initialized Firebase app, auth, and db instances
4216
+ *
4217
+ * @example
4218
+ * ```typescript
4219
+ * import { initializeWithToken } from '@seaverse/data-service-sdk';
4220
+ *
4221
+ * const tokenResponse = await client.generateGuestFirestoreToken({ app_id: 'my-app' });
4222
+ * const { app, auth, db, userId, appId } = await initializeWithToken(tokenResponse);
4223
+ *
4224
+ * // Ready to use Firestore!
4225
+ * const snapshot = await getDocs(collection(db, `appData/${appId}/publicData/posts`));
4226
+ * ```
4227
+ */
4228
+ async function initializeWithToken(tokenResponse) {
4229
+ // Check if Firebase SDK is available
4230
+ let initializeApp;
4231
+ let getAuth;
4232
+ let signInWithCustomToken;
4233
+ let getFirestore;
4234
+ try {
4235
+ // Try to import Firebase modules
4236
+ const firebaseApp = await import('firebase/app');
4237
+ const firebaseAuth = await import('firebase/auth');
4238
+ const firebaseFirestore = await import('firebase/firestore');
4239
+ initializeApp = firebaseApp.initializeApp;
4240
+ getAuth = firebaseAuth.getAuth;
4241
+ signInWithCustomToken = firebaseAuth.signInWithCustomToken;
4242
+ getFirestore = firebaseFirestore.getFirestore;
4243
+ }
4244
+ catch (error) {
4245
+ throw new Error('Firebase SDK not found. Please install it: npm install firebase\n' +
4246
+ 'Or import manually and use getFirebaseConfig() helper instead.');
4247
+ }
4248
+ // Initialize Firebase
4249
+ const config = getFirebaseConfig(tokenResponse);
4250
+ const app = initializeApp(config);
4251
+ // Sign in with custom token
4252
+ const auth = getAuth(app);
4253
+ await signInWithCustomToken(auth, tokenResponse.custom_token);
4254
+ // Get Firestore instance
4255
+ const db = getFirestore(app);
4256
+ return {
4257
+ app,
4258
+ auth,
4259
+ db,
4260
+ userId: tokenResponse.user_id,
4261
+ appId: tokenResponse.app_id || '',
4262
+ };
4263
+ }
4264
+
4265
+ export { DEFAULT_BASE_URL, DEFAULT_TIMEOUT, DataServiceClient, ENDPOINTS, getFirebaseConfig, initializeWithToken };
4177
4266
  //# sourceMappingURL=browser.js.map