@seaverse/data-service-sdk 0.10.1 → 0.10.2

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.
@@ -5153,7 +5153,7 @@
5153
5153
  *
5154
5154
  * This is a convenience function that automatically:
5155
5155
  * 1. Creates Firebase config from token response
5156
- * 2. Initializes Firebase app
5156
+ * 2. Initializes Firebase app (or reuses existing one)
5157
5157
  * 3. Signs in with the custom token
5158
5158
  * 4. Creates FirestoreHelper for LLM-friendly operations
5159
5159
  * 5. Returns authenticated Firebase instances
@@ -5161,11 +5161,20 @@
5161
5161
  * IMPORTANT: This function requires Firebase SDK to be installed separately:
5162
5162
  * npm install firebase
5163
5163
  *
5164
+ * ⚠️ IMPORTANT: This function can be called multiple times safely. It will:
5165
+ * - Reuse existing Firebase app if already initialized
5166
+ * - Re-authenticate with new token if needed
5167
+ * - Handle token refresh scenarios
5168
+ *
5164
5169
  * 🎯 LLM RECOMMENDED: Use the `helper` object for simplified operations
5165
5170
  *
5166
5171
  * @param tokenResponse - The Firestore token response from SDK
5167
5172
  * @returns Object containing initialized Firebase instances and LLM-friendly helper
5168
5173
  *
5174
+ * @throws {Error} If app_id is missing from token response
5175
+ * @throws {Error} If Firebase SDK is not installed
5176
+ * @throws {Error} If authentication fails
5177
+ *
5169
5178
  * @example
5170
5179
  * ```typescript
5171
5180
  * import { initializeWithToken } from '@seaverse/data-service-sdk';
@@ -5184,17 +5193,25 @@
5184
5193
  * ```
5185
5194
  */
5186
5195
  async function initializeWithToken(tokenResponse) {
5196
+ // ✅ FIX #3: Validate appId FIRST before any initialization
5197
+ const appId = tokenResponse.app_id;
5198
+ if (!appId) {
5199
+ throw new Error('app_id is required in token response. ' +
5200
+ 'Make sure your token response includes a valid app_id field.');
5201
+ }
5187
5202
  // Check if Firebase SDK is available
5188
5203
  let initializeApp;
5189
5204
  let getAuth;
5190
5205
  let signInWithCustomToken;
5191
5206
  let getFirestore;
5207
+ let getApps;
5192
5208
  try {
5193
5209
  // Try to import Firebase modules
5194
5210
  const firebaseApp = await import('firebase/app');
5195
5211
  const firebaseAuth = await import('firebase/auth');
5196
5212
  const firebaseFirestore = await import('firebase/firestore');
5197
5213
  initializeApp = firebaseApp.initializeApp;
5214
+ getApps = firebaseApp.getApps;
5198
5215
  getAuth = firebaseAuth.getAuth;
5199
5216
  signInWithCustomToken = firebaseAuth.signInWithCustomToken;
5200
5217
  getFirestore = firebaseFirestore.getFirestore;
@@ -5203,17 +5220,57 @@
5203
5220
  throw new Error('Firebase SDK not found. Please install it: npm install firebase\n' +
5204
5221
  'Or import manually and use getFirebaseConfig() helper instead.');
5205
5222
  }
5206
- // Initialize Firebase
5207
- const config = getFirebaseConfig(tokenResponse);
5208
- const app = initializeApp(config);
5209
- // Sign in with custom token
5210
- const auth = getAuth(app);
5211
- await signInWithCustomToken(auth, tokenResponse.custom_token);
5212
- // Get Firestore instance with correct database ID
5213
- // IMPORTANT: Must specify database_id, not just use default!
5214
- const db = getFirestore(app, tokenResponse.database_id);
5223
+ // FIX #1: Check if Firebase app already exists
5224
+ const existingApps = getApps();
5225
+ const existingApp = existingApps.find((app) => app.name === '[DEFAULT]');
5226
+ let app;
5227
+ let auth;
5228
+ let db;
5229
+ if (existingApp) {
5230
+ // ✅ FIX #2: Reuse existing app instead of creating new one
5231
+ console.log('[SeaVerse SDK] Reusing existing Firebase app');
5232
+ app = existingApp;
5233
+ auth = getAuth(app);
5234
+ db = getFirestore(app, tokenResponse.database_id);
5235
+ // ✅ FIX #4: Re-authenticate with new token (for token refresh scenarios)
5236
+ try {
5237
+ await signInWithCustomToken(auth, tokenResponse.custom_token);
5238
+ console.log('[SeaVerse SDK] Re-authenticated with new token');
5239
+ }
5240
+ catch (error) {
5241
+ // If already signed in with same token, ignore error
5242
+ // Only throw if it's a real authentication failure
5243
+ if (error?.code !== 'auth/invalid-credential' && error?.code !== 'auth/network-request-failed') {
5244
+ console.warn('[SeaVerse SDK] Re-authentication warning:', error?.message || error);
5245
+ }
5246
+ }
5247
+ }
5248
+ else {
5249
+ // ✅ FIX #4: First-time initialization with proper error handling
5250
+ console.log('[SeaVerse SDK] Initializing new Firebase app');
5251
+ try {
5252
+ const config = getFirebaseConfig(tokenResponse);
5253
+ app = initializeApp(config);
5254
+ auth = getAuth(app);
5255
+ await signInWithCustomToken(auth, tokenResponse.custom_token);
5256
+ // IMPORTANT: Must specify database_id, not just use default!
5257
+ db = getFirestore(app, tokenResponse.database_id);
5258
+ }
5259
+ catch (error) {
5260
+ // ✅ FIX #4: Cleanup on failure to prevent half-initialized state
5261
+ if (app) {
5262
+ try {
5263
+ await app.delete();
5264
+ console.log('[SeaVerse SDK] Cleaned up failed Firebase app initialization');
5265
+ }
5266
+ catch (cleanupError) {
5267
+ console.warn('[SeaVerse SDK] Failed to cleanup app:', cleanupError);
5268
+ }
5269
+ }
5270
+ throw new Error(`Failed to initialize Firebase: ${error instanceof Error ? error.message : String(error)}`);
5271
+ }
5272
+ }
5215
5273
  const userId = tokenResponse.user_id;
5216
- const appId = tokenResponse.app_id || '';
5217
5274
  // Create LLM-friendly helper
5218
5275
  const helper = new FirestoreHelper(db, appId, userId);
5219
5276
  return {