npm package: @sions/firebase-admin-edge
Description: Cloudflare Workers compatible Firebase Admin SDK using REST APIs
Author: sions
Latest version: 0.1.0

# Firebase Admin Edge

Cloudflare Workers compatible Firebase Admin SDK using REST APIs and Web Standard APIs.

[![npm version](https://badge.fury.io/js/@sions%2Ffirebase-admin-edge.svg)](https://www.npmjs.com/package/@sions/firebase-admin-edge)
[![License: Apache-2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)

## Features

- ✅ **100% Cloudflare Workers Compatible** - Uses only Web Standard APIs
- ✅ **Firebase Authentication** - User management, token verification, email links
- ✅ **Firebase Realtime Database** - Read, write, queries, transactions
- ✅ **OAuth2 Token Generation** - Service account authentication
- ✅ **TypeScript First** - Full type definitions included
- ✅ **Zero Node.js Dependencies** - Works in any JavaScript runtime (Workers, Deno, Bun)
- ✅ **Firebase Emulator Support** - Local development ready

## Installation

```bash
npm install @sions/firebase-admin-edge
```

## Quick Start

### Environment Variables (Automatic)

Set these environment variables and the SDK will auto-configure:

```bash
FIREBASE_ADMIN_PROJECT_ID=your-project-id
FIREBASE_ADMIN_CLIENT_EMAIL=your-service-account@project.iam.gserviceaccount.com
FIREBASE_ADMIN_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n"
```

Then use the SDK directly:

```typescript
import { getAuth, verifyIdToken } from '@sions/firebase-admin-edge';

// Verify ID token
const decoded = await verifyIdToken(idToken);
console.log(decoded.uid);

// Get user info
const auth = getAuth();
const user = await auth.getUser(decoded.uid);
console.log(user.email);
```

### Explicit Initialization

```typescript
import { initializeApp, getAuth, getDatabase } from '@sions/firebase-admin-edge';

// Initialize once at app startup
initializeApp({
  projectId: 'your-project-id',
  clientEmail: 'your-service-account@project.iam.gserviceaccount.com',
  privateKey: process.env.FIREBASE_PRIVATE_KEY!
});

// Use Auth
const auth = getAuth();
const user = await auth.getUser('user-uid');

// Use Database
const db = getDatabase();
const snapshot = await db.ref('/users').get();
```

## Usage Examples

### Authentication

#### Verify ID Token

```typescript
import { verifyIdToken } from '@sions/firebase-admin-edge';

const decoded = await verifyIdToken(idToken);
console.log('User ID:', decoded.uid);
console.log('Email:', decoded.email);
```

#### User Management

```typescript
import { getAuth } from '@sions/firebase-admin-edge';

const auth = getAuth();

// Get user by UID
const user = await auth.getUser('user-uid');

// Get user by email
const userByEmail = await auth.getUserByEmail('user@example.com');

// Create new user
const newUser = await auth.createUser({
  email: 'new-user@example.com',
  password: 'SecurePassword123!',
  displayName: 'New User'
});

// Update user
await auth.updateUser('user-uid', {
  displayName: 'Updated Name',
  photoURL: 'https://example.com/photo.jpg'
});

// Delete user
await auth.deleteUser('user-uid');
```

#### Email Action Links

```typescript
import { generatePasswordResetLink, generateEmailVerificationLink } from '@sions/firebase-admin-edge';

// Generate password reset link
const resetLink = await generatePasswordResetLink('user@example.com');
console.log('Reset link:', resetLink);

// Generate email verification link
const verifyLink = await generateEmailVerificationLink('user@example.com');
console.log('Verification link:', verifyLink);
```

### Realtime Database

#### Basic Operations

```typescript
import { getDatabase } from '@sions/firebase-admin-edge';

const db = getDatabase();

// Read data
const snapshot = await db.ref('/users/user-id').get();
const data = snapshot.val();

// Write data
await db.ref('/users/user-id').set({
  name: 'John Doe',
  email: 'john@example.com'
});

// Update data
await db.ref('/users/user-id').update({
  lastLogin: Date.now()
});

// Delete data
await db.ref('/users/user-id/temp').remove();

// Push new child
const newRef = db.ref('/posts').push();
await newRef.set({
  title: 'New Post',
  content: 'Hello World'
});
```

#### Queries

```typescript
const db = getDatabase();

// Order by child
const byAge = await db.ref('/users')
  .orderByChild('age')
  .get();

// Limit results
const topUsers = await db.ref('/users')
  .orderByChild('score')
  .limitToLast(10)
  .get();

// Range queries
const adults = await db.ref('/users')
  .orderByChild('age')
  .startAt(18)
  .endAt(100)
  .get();

// Equal to
const admin = await db.ref('/users')
  .orderByChild('role')
  .equalTo('admin')
  .get();
```

#### Transactions

```typescript
const db = getDatabase();

// Atomic counter increment
const result = await db.ref('/counters/visits').transaction((current) => {
  return (current || 0) + 1;
});

console.log('New count:', result.snapshot.val());
console.log('Committed:', result.committed);
```

### Cloudflare Workers Example

```typescript
// worker.ts
import { initializeApp, verifyIdToken, getDatabase } from '@sions/firebase-admin-edge';

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    // Initialize with Workers environment variables
    initializeApp({
      projectId: env.FIREBASE_PROJECT_ID,
      clientEmail: env.FIREBASE_CLIENT_EMAIL,
      privateKey: env.FIREBASE_PRIVATE_KEY
    });

    // Verify authorization token
    const authHeader = request.headers.get('Authorization');
    if (!authHeader?.startsWith('Bearer ')) {
      return new Response('Unauthorized', { status: 401 });
    }

    const idToken = authHeader.substring(7);
    const decoded = await verifyIdToken(idToken);

    // Access database
    const db = getDatabase();
    const userData = await db.ref(`/users/${decoded.uid}`).get();

    return Response.json({
      user: decoded,
      data: userData.val()
    });
  }
};
```

## Firebase Emulator Support

```typescript
import { initializeApp } from '@sions/firebase-admin-edge';

initializeApp({
  projectId: 'demo-project',
  clientEmail: 'test@demo.com',
  privateKey: '-----BEGIN PRIVATE KEY-----\nfake-key\n-----END PRIVATE KEY-----\n',
  authEmulatorHost: '127.0.0.1:9099',
  databaseEmulatorHost: '127.0.0.1:9000'
});
```

Or use environment variables:

```bash
VITE_USE_FIREBASE_EMULATOR=true
VITE_FIREBASE_AUTH_EMULATOR_HOST=127.0.0.1:9099
VITE_FIREBASE_DATABASE_EMULATOR_HOST=127.0.0.1:9000
```

## API Reference

### Authentication

- `getAuth()` - Get Auth instance
- `verifyIdToken(token)` - Verify Firebase ID token
- `getUser(uid)` - Get user by UID
- `getUserByEmail(email)` - Get user by email
- `createUser(request)` - Create new user
- `updateUser(uid, request)` - Update user
- `deleteUser(uid)` - Delete user
- `generatePasswordResetLink(email)` - Generate password reset link
- `generateEmailVerificationLink(email)` - Generate email verification link

### Database

- `getDatabase()` - Get Database instance
- `ref(path)` - Get reference to path
- `get()` - Read data
- `set(value)` - Write data
- `update(values)` - Update data
- `remove()` - Delete data
- `push()` - Generate new child location
- `transaction(updateFn)` - Atomic transaction
- `orderByChild(path)` - Order query by child
- `orderByKey()` - Order query by key
- `orderByValue()` - Order query by value
- `limitToFirst(limit)` - Limit to first N
- `limitToLast(limit)` - Limit to last N
- `startAt(value)` - Range start
- `endAt(value)` - Range end
- `equalTo(value)` - Equal to value

### Configuration

- `initializeApp(config)` - Initialize SDK
- `getProjectId()` - Get project ID
- `isEmulatorMode()` - Check if using emulator
- `getEnvironmentMode()` - Get current mode

### Utilities

- `getAccessToken()` - Get OAuth2 access token
- `clearTokenCache()` - Clear token cache
- `isTokenExpired(token)` - Check if token expired
- `generatePushId()` - Generate Firebase push ID

## TypeScript Support

Full TypeScript definitions included:

```typescript
import type {
  UserRecord,
  DecodedIdToken,
  CreateUserRequest,
  UpdateUserRequest,
  DataSnapshot,
  TransactionResult
} from '@sions/firebase-admin-edge';
```

## Error Handling

```typescript
import {
  FirebaseError,
  FirebaseAuthError,
  FirebaseDatabaseError,
  isFirebaseError
} from '@sions/firebase-admin-edge';

try {
  await auth.getUser('invalid-uid');
} catch (error) {
  if (isFirebaseError(error)) {
    console.error('Firebase error:', error.code, error.message);
  }
}
```

## Compatibility

### ✅ Works In
- Cloudflare Workers
- Deno
- Bun
- Node.js 18+
- Any modern JavaScript runtime with Web Standard APIs

### ✅ Uses Only
- Web Standard APIs (fetch, Web Crypto API)
- `jose` library (Web Crypto-based JWT)
- Pure TypeScript/JavaScript

### ❌ No Dependencies On
- Node.js built-in modules (`fs`, `path`, `crypto`, `http`, etc.)
- Node.js-specific APIs (`Buffer`, `process.*`)
- Native binaries

## License

Apache-2.0

## Contributing

Contributions welcome! This project maintains 100% Cloudflare Workers compatibility.

### Development Guidelines

- Use only Web Standard APIs
- No Node.js built-in modules
- Test with Firebase Emulator
- Maintain TypeScript strict mode

## Links

- [npm package](https://www.npmjs.com/package/@sions/firebase-admin-edge)
- [GitHub Repository](https://github.com/sions/firebase-admin-edge)
- [Cloudflare Workers Docs](https://developers.cloudflare.com/workers/)
- [Firebase Documentation](https://firebase.google.com/docs)

## Support

- Create an issue on GitHub for bug reports
- Check existing issues before creating new ones
- Include error messages and runtime environment details