File size: 7,578 Bytes
e3fefe8
 
 
 
 
b9e5a76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3fefe8
 
 
 
 
 
 
 
 
b9e5a76
e3fefe8
 
 
 
 
 
 
 
b9e5a76
 
e3fefe8
 
b9e5a76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3fefe8
b9e5a76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3fefe8
 
b9e5a76
 
 
e3fefe8
 
b9e5a76
 
 
 
 
 
 
 
 
 
 
e3fefe8
 
b9e5a76
 
 
 
 
e3fefe8
b9e5a76
 
e3fefe8
b9e5a76
e3fefe8
b9e5a76
e3fefe8
 
b9e5a76
e3fefe8
 
 
 
b9e5a76
e3fefe8
b9e5a76
e3fefe8
 
b9e5a76
e3fefe8
 
 
 
b9e5a76
e3fefe8
b9e5a76
e3fefe8
 
b9e5a76
e3fefe8
 
 
 
b9e5a76
e3fefe8
b9e5a76
e3fefe8
 
 
b9e5a76
e3fefe8
 
 
 
b9e5a76
e3fefe8
b9e5a76
e3fefe8
 
b9e5a76
e3fefe8
 
 
 
b9e5a76
e3fefe8
b9e5a76
e3fefe8
 
 
 
b9e5a76
e3fefe8
 
b9e5a76
e3fefe8
 
 
 
b9e5a76
e3fefe8
b9e5a76
e3fefe8
 
b9e5a76
e3fefe8
 
b9e5a76
e3fefe8
 
 
 
b9e5a76
 
e3fefe8
 
 
b9e5a76
e3fefe8
 
b9e5a76
 
 
 
e3fefe8
b9e5a76
 
 
 
 
 
 
 
e3fefe8
b9e5a76
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
const admin = require('firebase-admin');
const path = require('path');
const fs = require('fs');

let db;
let firebaseReady = false;
let firebaseInitError = null;

function normalizePrivateKey(value) {
  if (!value) return value;
  return value.includes('\\n') ? value.replace(/\\n/g, '\n') : value;
}

function parseJson(value, label) {
  try {
    return JSON.parse(value);
  } catch (error) {
    throw new Error(`${label} is not valid JSON: ${error.message}`);
  }
}

function loadServiceAccount() {
  const jsonEnv = process.env.FIREBASE_SERVICE_ACCOUNT_JSON;
  if (jsonEnv && jsonEnv.trim()) {
    return parseJson(jsonEnv, 'FIREBASE_SERVICE_ACCOUNT_JSON');
  }

  const b64Env =
    process.env.FIREBASE_SERVICE_ACCOUNT_JSON_B64 ||
    process.env.FIREBASE_SERVICE_ACCOUNT_BASE64;
  if (b64Env && b64Env.trim()) {
    const decoded = Buffer.from(b64Env, 'base64').toString('utf8');
    return parseJson(decoded, 'FIREBASE_SERVICE_ACCOUNT_JSON_B64');
  }

  const projectId = process.env.FIREBASE_PROJECT_ID;
  const clientEmail = process.env.FIREBASE_CLIENT_EMAIL;
  const privateKey = normalizePrivateKey(process.env.FIREBASE_PRIVATE_KEY);
  if (projectId && clientEmail && privateKey) {
    return {
      project_id: projectId,
      client_email: clientEmail,
      private_key: privateKey,
    };
  }

  let serviceAccountPath = process.env.FIREBASE_SERVICE_ACCOUNT_PATH;
  if (!serviceAccountPath) {
    const possiblePaths = [
      path.resolve(__dirname, './serviceAccountKey.json'),
      path.resolve(__dirname, '../config/serviceAccountKey.json'),
      path.resolve(process.cwd(), './src/config/serviceAccountKey.json'),
      path.resolve(process.cwd(), './serviceAccountKey.json'),
    ];

    for (const possiblePath of possiblePaths) {
      if (fs.existsSync(possiblePath)) {
        serviceAccountPath = possiblePath;
        break;
      }
    }
  }

  if (serviceAccountPath && fs.existsSync(serviceAccountPath)) {
    return require(serviceAccountPath);
  }

  throw new Error(
    [
      'Firebase service account missing.',
      'Set one of these in Hugging Face Secrets:',
      '- FIREBASE_SERVICE_ACCOUNT_JSON',
      '- FIREBASE_SERVICE_ACCOUNT_JSON_B64',
      '- FIREBASE_PROJECT_ID + FIREBASE_CLIENT_EMAIL + FIREBASE_PRIVATE_KEY',
    ].join(' '),
  );
}

function createNoopSnapshot(value = null) {
  return {
    exists: () => Boolean(value),
    val: () => value,
    forEach: () => false,
  };
}

function createNoopQuery() {
  const query = {
    once: async () => createNoopSnapshot(null),
    get: async () => ({ empty: true, docs: [] }),
    set: async () => undefined,
    update: async () => undefined,
    remove: async () => undefined,
    on: () => undefined,
    off: () => undefined,
    orderByChild: () => query,
    equalTo: () => query,
    limitToLast: () => query,
    limit: () => query,
    where: () => query,
    doc: () => query,
    collection: () => query,
    push: () => ({
      key: `noop-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`,
      set: async () => undefined,
      update: async () => undefined,
    }),
  };

  return query;
}

function createNoopDb() {
  const root = createNoopQuery();
  return {
    ref: () => root,
    collection: () => root,
    doc: () => root,
  };
}

function createNoopAuth() {
  const unavailable = (method) => {
    const error = new Error(`Firebase Admin is not configured. Cannot call ${method}.`);
    error.code = 'auth/internal-error';
    throw error;
  };

  return {
    getUserByEmail: async () => unavailable('getUserByEmail'),
    getUser: async () => unavailable('getUser'),
    createUser: async () => unavailable('createUser'),
    createCustomToken: async () => unavailable('createCustomToken'),
    verifyIdToken: async () => unavailable('verifyIdToken'),
  };
}

function createNoopMessaging() {
  return {
    send: async () => {
      const error = new Error('Firebase messaging is not configured.');
      error.code = 'messaging/unavailable';
      throw error;
    },
    sendEachForMulticast: async () => {
      const error = new Error('Firebase messaging is not configured.');
      error.code = 'messaging/unavailable';
      throw error;
    },
  };
}

function initializeFirebase() {
  if (admin.apps.length) {
    firebaseReady = true;
    return true;
  }

  const serviceAccount = loadServiceAccount();
  admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL:
      process.env.FIREBASE_DATABASE_URL ||
      'https://serviceconnect-dea35-default-rtdb.firebaseio.com/',
  });

  firebaseReady = true;
  return true;
}

try {
  initializeFirebase();
  console.log('Firebase Admin initialized successfully');
} catch (error) {
  firebaseInitError = error;
  firebaseReady = false;
  console.error('Firebase initialization failed:', error.message);
}

if (firebaseReady) {
  db = admin.database();
} else {
  db = createNoopDb();
}

const auth = firebaseReady ? admin.auth() : createNoopAuth();
const messaging = firebaseReady ? admin.messaging() : createNoopMessaging();

async function dbGet(pathName) {
  try {
    const snap = await db.ref(pathName).once('value');
    return snap.exists() ? snap.val() : null;
  } catch (error) {
    console.error(`dbGet error at ${pathName}:`, error.message);
    return null;
  }
}

async function dbSet(pathName, data) {
  try {
    await db.ref(pathName).set({ ...data, _updatedAt: Date.now() });
    return true;
  } catch (error) {
    console.error(`dbSet error at ${pathName}:`, error.message);
    return false;
  }
}

async function dbUpdate(pathName, data) {
  try {
    await db.ref(pathName).update({ ...data, _updatedAt: Date.now() });
    return true;
  } catch (error) {
    console.error(`dbUpdate error at ${pathName}:`, error.message);
    return false;
  }
}

async function dbPush(pathName, data) {
  try {
    const ref = db.ref(pathName).push();
    await ref.set({ ...data, id: ref.key, _createdAt: Date.now() });
    return ref.key;
  } catch (error) {
    console.error(`dbPush error at ${pathName}:`, error.message);
    return null;
  }
}

async function dbDelete(pathName) {
  try {
    await db.ref(pathName).remove();
    return true;
  } catch (error) {
    console.error(`dbDelete error at ${pathName}:`, error.message);
    return false;
  }
}

async function dbQuery(pathName, orderBy, equalTo, limitToLast = null) {
  try {
    let ref = db.ref(pathName).orderByChild(orderBy).equalTo(equalTo);
    if (limitToLast) ref = ref.limitToLast(limitToLast);
    const snap = await ref.once('value');
    if (!snap.exists()) return [];
    const results = [];
    snap.forEach((child) => results.push({ _key: child.key, ...child.val() }));
    return results;
  } catch (error) {
    console.error(`dbQuery error at ${pathName}:`, error.message);
    return [];
  }
}

async function dbGetAll(pathName) {
  try {
    const snap = await db.ref(pathName).once('value');
    if (!snap.exists()) return [];
    const results = [];
    snap.forEach((child) => results.push({ _key: child.key, ...child.val() }));
    return results;
  } catch (error) {
    console.error(`dbGetAll error at ${pathName}:`, error.message);
    return [];
  }
}

function dbListen(pathName, callback) {
  const ref = db.ref(pathName);
  ref.on('value', (snapshot) => {
    callback(snapshot.exists() ? snapshot.val() : null);
  });
  return () => ref.off();
}

module.exports = {
  admin,
  db,
  auth,
  messaging,
  firebaseReady,
  firebaseInitError,
  dbGet,
  dbSet,
  dbUpdate,
  dbPush,
  dbDelete,
  dbQuery,
  dbGetAll,
  dbListen,
};