npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@zssz-soft/firebase-functions-shared

v1.2.6

Published

Shared Firebase Cloud Functions modules for LodgeFlow applications

Readme

LodgeFlow Shared Firebase Functions

A shared library of Firebase Cloud Functions modules for LodgeFlow applications. This library provides common functionality for user management, email services, file storage, and system bootstrap across multiple Firebase projects.

Features

  • Bootstrap Module: System initialization with default admin user and roles
  • Email Module: Templated email service (welcome, password reset, notifications)
  • Storage Module: Image/document processing with thumbnail generation and HEIC conversion
  • User Module: User management with Firebase Auth and Firestore integration
  • Configuration Management: Centralized configuration for multi-tenant deployments

Installation

cd firebase/shared/functions
npm install
npm run build

Usage

1. Initialize Configuration

Before using any shared functions, you must initialize the application configuration in your main index.ts file:

import { initializeApp } from 'firebase-admin/app';
import { setGlobalOptions } from 'firebase-functions/v2';
import { initializeConfig, AppConfig } from '@lodgeflow/firebase-functions-shared';

// Initialize Firebase Admin SDK
initializeApp({
  projectId: process.env.GCLOUD_PROJECT || 'your-project-id',
});

// Configure shared library
const config: AppConfig = {
  projectId: process.env.GCLOUD_PROJECT || 'your-project-id',
  region: process.env.FUNCTION_REGION || 'europe-west1',
  firestoreDatabaseId: process.env.FIRESTORE_DATABASE_ID, // Optional
  appName: 'Your App Name',
  defaultAdminPassword: process.env.DEFAULT_ADMIN_PASSWORD || 'AdminBootstrap2024!',
  defaultUserPassword: process.env.DEFAULT_USER_PASSWORD || 'User2024!',
  defaultAdminRoleId: '66000',
  defaultUserRoleId: '66001',
  defaultLoginUrl: process.env.DEFAULT_LOGIN_URL || 'https://yourapp.web.app/login',
  maxInstances: 10,
};

initializeConfig(config);

// Set global function options
setGlobalOptions({
  maxInstances: config.maxInstances,
  region: config.region,
});

// Export functions
export * from '@lodgeflow/firebase-functions-shared';

2. Environment Variables

Create a .env file in your functions directory:

# Firebase Configuration
GCLOUD_PROJECT=your-project-id
FUNCTION_REGION=europe-west1
FIRESTORE_DATABASE_ID=default  # Optional

# Email Configuration (SMTP)
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_SECURE=false
[email protected]
EMAIL_PASS=your-app-password
EMAIL_FROM_NAME=Your App Name
[email protected]

# Application Configuration
DEFAULT_ADMIN_PASSWORD=AdminBootstrap2024!
DEFAULT_USER_PASSWORD=User2024!
DEFAULT_LOGIN_URL=https://yourapp.web.app/login

3. Using Shared Modules

Bootstrap Module

Initialize your system with default admin user and roles:

// Client-side usage
import { getFunctions, httpsCallable } from 'firebase/functions';

const functions = getFunctions();
const systemBootstrap = httpsCallable(functions, 'systemBootstrap');

const result = await systemBootstrap({
  adminEmail: '[email protected]',
  adminDisplayName: 'Admin User',
  adminPassword: 'SecurePassword123!',
});

console.log(result.data.message);

Check bootstrap status:

const checkStatus = httpsCallable(functions, 'checkBootstrapStatus');
const status = await checkStatus();
console.log(status.data); // { isBootstrapped: true, userCount: 1 }

Email Module

Send templated emails:

const sendEmail = httpsCallable(functions, 'sendEmail');

// Welcome email
await sendEmail({
  to: '[email protected]',
  subject: 'Welcome!',
  type: 'welcome',
  userName: 'John Doe',
  loginLink: 'https://yourapp.web.app/login',
});

// Password reset email
await sendEmail({
  to: '[email protected]',
  subject: 'Reset Password',
  type: 'password-reset',
  userName: 'John Doe',
  resetLink: 'https://yourapp.web.app/reset?token=abc123',
});

// Notification email
await sendEmail({
  to: '[email protected]',
  subject: 'Important Update',
  type: 'notification',
  message: 'Your account has been updated.',
});

Storage Module

Generate thumbnails for images and documents:

const generateThumbnail = httpsCallable(functions, 'generateThumbnail');

const result = await generateThumbnail({
  path: 'gs://your-bucket/path/to/image.jpg',
  maxWidth: 512,
  maxHeight: 512,
  force: false, // Set to true to regenerate existing thumbnails
  documentId: 'optional-document-id', // Updates Firestore document with thumbnail URL
});

console.log(result.data);
// {
//   success: true,
//   path: 'path/to/image.jpg',
//   thumbPath: 'https://.../_thumb.webp',
//   webImagePath: 'https://.../_web.jpg', // For HEIC files only
//   created: true
// }

User Module

Create users with automatic email notification:

const createUser = httpsCallable(functions, 'createUserWithEmail');

const result = await createUser({
  email: '[email protected]',
  firstName: 'John',
  lastName: 'Doe',
  password: 'SecurePassword123!',
  phoneNumber: '+1234567890',
  roleIds: ['66001'], // USER role
  sendWelcomeEmail: true,
  loginUrl: 'https://yourapp.web.app/login',
});

console.log(result.data);
// { success: true, uid: '...', email: '...', emailSent: true }

Module Details

Bootstrap Module

Functions:

  • systemBootstrap(data) - Creates initial admin user and default roles
  • checkBootstrapStatus() - Checks if system has been initialized

Default Roles:

  • ADMIN (ID: 66000): Full administrative access
  • USER (ID: 66001): Standard user access

Email Module

Supported Email Types:

  • welcome - Welcome email with login link
  • password-reset - Password reset email with reset link
  • notification - Generic notification email
  • custom - Custom HTML email

Configuration: All emails use the application name from the configuration and support both HTML and plain text formats.

Storage Module

Supported File Types:

  • Images: jpg, jpeg, png, webp, avif, gif, bmp, tiff, heic, heif
  • Documents: pdf, doc, docx, xls, xlsx, ppt, pptx, txt, rtf, odt, ods, odp

Features:

  • Automatic HEIC to JPEG conversion (web-optimized)
  • WebP thumbnail generation (512x512 default)
  • Empty placeholder thumbnails for non-image files
  • Automatic Firestore document updates with thumbnail URLs
  • Efficient caching (1 year max-age)

User Module

Features:

  • Creates users in both Firebase Auth and Firestore
  • Automatic welcome email sending
  • Default role assignment (USER role)
  • Transaction-safe with automatic cleanup on errors
  • Supports custom passwords or generates secure defaults

Configuration Reference

AppConfig Interface

interface AppConfig {
  projectId: string; // Firebase project ID
  region: string; // Cloud Functions region
  firestoreDatabaseId?: string; // Optional Firestore database ID
  appName: string; // Application name for branding
  defaultAdminPassword: string; // Bootstrap admin password
  defaultUserPassword: string; // Default password for new users
  defaultAdminRoleId: string; // Admin role ID in Firestore
  defaultUserRoleId: string; // User role ID in Firestore
  defaultLoginUrl: string; // Default login URL for emails
  maxInstances?: number; // Max Cloud Function instances
}

EmailConfig Interface

interface EmailConfig {
  host: string; // SMTP server hostname
  port: number; // SMTP port (587 or 465)
  secure: boolean; // TLS/SSL enabled
  user: string; // SMTP username
  pass: string; // SMTP password
  fromName: string; // Sender display name
  fromEmail: string; // Sender email address
}

Security Best Practices

  1. Environment Variables: Store sensitive data in environment variables, not in code
  2. Firebase Secrets: Use Firebase Secrets Manager for production:
    firebase functions:secrets:set EMAIL_PASS
  3. Authentication: All functions require authentication except bootstrap status check
  4. Role-Based Access: Implement proper role checks in your application
  5. Password Policies: Enforce strong passwords (min 6 characters)
  6. Email Verification: Users should verify their email addresses

Development

Build

npm run build

Watch Mode

npm run build:watch

Testing

npm test

Linting

npm run lint

Migration Guide

From Standalone to Shared Library

  1. Install the shared library in your Firebase functions project
  2. Update your index.ts to initialize configuration
  3. Remove duplicate code from your project (bootstrap, email, storage, user modules)
  4. Update imports to use the shared library
  5. Configure environment variables according to the template above
  6. Test thoroughly in emulator before deploying

Example migration:

// Before
import { systemBootstrap } from './modules/bootstrap/bootstrap';
export { systemBootstrap };

// After
import { initializeConfig, AppConfig } from '@lodgeflow/firebase-functions-shared';

const config: AppConfig = {
  /* your config */
};
initializeConfig(config);

export * from '@lodgeflow/firebase-functions-shared';

Contributing

This is a private shared library for LodgeFlow applications. To contribute:

  1. Make changes in the firebase/shared/functions directory
  2. Test changes in emulator with one of the consumer projects
  3. Update version in package.json
  4. Build and deploy

Troubleshooting

Configuration Not Initialized Error

Error: Application configuration not initialized. Call initializeConfig() first.

Solution: Ensure you call initializeConfig(config) before exporting any functions.

Email Sending Fails

Error: Email configuration incomplete

Solution: Check that all required environment variables are set (EMAIL_HOST, EMAIL_USER, EMAIL_PASS).

Firestore Database Not Found

Error: Firestore database "default" not found

Solution: Either create the database in Firebase Console or set firestoreDatabaseId to undefined to use the default database.

HEIC Conversion Fails

Error: Failed to convert HEIC to JPEG

Solution: Ensure heic-convert and sharp are installed. Check that the file is a valid HEIC image.

License

UNLICENSED - Private library for ZS-Soft/LodgeFlow applications.

Support

For issues or questions, contact the development team or create an issue in the project repository.