ZZZ Digital Lab

Back to HushBrief

src/firebase.ts

import { initializeApp } from 'firebase/app';
import { CustomProvider, initializeAppCheck, ReCaptchaEnterpriseProvider } from 'firebase/app-check';
import { getAI, getGenerativeModel, GoogleAIBackend, InferenceMode, InferenceSource } from 'firebase/ai';
import type { Ports, ModelResult } from './core.ts';

const e = import.meta.env;
const placeholder = (value: string | undefined) => !value || /YOUR_|REPLACE_/i.test(value);
// Local development with the App Check debug provider. `import.meta.env.DEV` is a
// compile-time constant: production builds drop this branch entirely, and
// scripts/check-dist.mjs fails the build if any debug-token assignment survives.
const devDebug = import.meta.env.DEV && e.VITE_APPCHECK_DEBUG === 'true' && ['localhost', '127.0.0.1'].includes(location.hostname);
const required = ['VITE_FIREBASE_API_KEY', 'VITE_FIREBASE_PROJECT_ID', 'VITE_FIREBASE_APP_ID', 'VITE_FIREBASE_AUTH_DOMAIN',
  // The reCAPTCHA Enterprise site key is mandatory everywhere except the local debug provider.
  ...(devDebug ? [] : ['VITE_RECAPTCHA_ENTERPRISE_SITE_KEY'])] as const;
export const firebaseMissing = required.filter(name => placeholder(e[name]));
export const firebaseConfigured = firebaseMissing.length === 0;
let live: ReturnType<typeof init> | undefined;
function appCheckProvider() {
  const siteKey = e.VITE_RECAPTCHA_ENTERPRISE_SITE_KEY;
  if (!placeholder(siteKey)) return new ReCaptchaEnterpriseProvider(siteKey);
  // Only reachable in local debug mode (see `required`): the debug token is exchanged
  // instead of an attestation, so this provider is never asked for a token.
  return new CustomProvider({ getToken: () => Promise.reject(new Error('reCAPTCHA Enterprise site key not configured')) });
}
function init() {
  if (!firebaseConfigured) throw new Error('Owner configuration is required. Use rehearsal mode.');
  const app = initializeApp({
    apiKey: e.VITE_FIREBASE_API_KEY, authDomain: e.VITE_FIREBASE_AUTH_DOMAIN, projectId: e.VITE_FIREBASE_PROJECT_ID, appId: e.VITE_FIREBASE_APP_ID,
    ...(placeholder(e.VITE_FIREBASE_STORAGE_BUCKET) ? {} : { storageBucket: e.VITE_FIREBASE_STORAGE_BUCKET }),
    ...(placeholder(e.VITE_FIREBASE_MESSAGING_SENDER_ID) ? {} : { messagingSenderId: e.VITE_FIREBASE_MESSAGING_SENDER_ID }),
  });
  if (import.meta.env.DEV && devDebug) {
    // Dev only. A token from the untracked .env.development.local is reused across fresh
    // browser profiles; otherwise the SDK generates one per profile. The SDK prints it in
    // the DevTools console as "Firebase App Check debug token: …" for the owner to register.
    const token = e.VITE_APPCHECK_DEBUG_TOKEN;
    (self as unknown as { FIREBASE_APPCHECK_DEBUG_TOKEN: string | boolean }).FIREBASE_APPCHECK_DEBUG_TOKEN = placeholder(token) ? true : token;
    console.info('[hushbrief:dev-appcheck-debug] App Check debug provider active (local development only).');
  }
  // App Check is initialised before any Firebase AI Logic object is created or called.
  initializeAppCheck(app, { provider: appCheckProvider(), isTokenAutoRefreshEnabled: true });
  const ai = getAI(app, { backend: new GoogleAIBackend() });
  const onDeviceParams = { createOptions: { expectedInputs: [{ type: 'text' as const, languages: ['en'] }], expectedOutputs: [{ type: 'text' as const, languages: ['en'] }] } };
  const inCloudParams = { model: e.VITE_CLOUD_MODEL || 'gemini-3.5-flash-lite', generationConfig: { temperature: 0.2, maxOutputTokens: 1600 } };
  return {
    device: getGenerativeModel(ai, { mode: InferenceMode.ONLY_ON_DEVICE, onDeviceParams }),
    hybrid: getGenerativeModel(ai, { mode: InferenceMode.PREFER_ON_DEVICE, onDeviceParams, inCloudParams }),
    cloud: getGenerativeModel(ai, { mode: InferenceMode.ONLY_IN_CLOUD, inCloudParams }),
  };
}
function models() { return live ??= init(); }
// Dev debug only: initialise App Check on page load so the SDK prints the debug token in the
// DevTools console straight away. Production keeps lazy initialisation (dropped at build time).
if (import.meta.env.DEV && devDebug && firebaseConfigured) models();
export function prepareDevice(progress: (value: number) => void): Promise<void> {
  // Must be called directly from the Prepare Nano click handler before any await.
  const m = models();
  return Promise.all([m.device.initializeDeviceModel(progress), m.hybrid.initializeDeviceModel()]).then(() => undefined);
}
async function generate(route: 'device' | 'hybrid' | 'cloud', prompt: string): Promise<ModelResult> {
  const r = await models()[route].generateContent(prompt);
  const source = r.response.inferenceSource;
  if (source !== InferenceSource.ON_DEVICE && source !== InferenceSource.IN_CLOUD) throw new Error('Unknown inference source');
  if (route === 'device' && source !== InferenceSource.ON_DEVICE) throw new Error('Unexpected cloud response');
  return { text: r.response.text(), source: source === InferenceSource.ON_DEVICE ? 'device' : 'cloud' };
}
export const firebasePorts: Ports = {
  device: prompt => generate('device', prompt), hybrid: prompt => generate('hybrid', prompt), cloud: prompt => generate('cloud', prompt),
};