Clefbase SDK and CLI

raw JSON →
2.1.6 verified Thu Apr 23 auth: no javascript

clefbase is a Firebase-style SDK and CLI for building applications with the Cleforyx backend platform. It offers a comprehensive suite of services including a NoSQL database, authentication, file storage, serverless functions, AI capabilities, and hosting. The current stable version is 2.1.6, indicating active development. While a specific release cadence isn't published in the provided documentation, its versioning suggests regular updates. Key differentiators include its all-in-one backend-as-a-service model, providing a unified API for various backend needs, and its direct competitive positioning against Firebase, offering a similar developer experience. The package ships with TypeScript types and supports Node.js environments version 16.0.0 or higher, with peer dependencies on React and ReactDOM for front-end integration. It provides both an SDK for programmatic interaction and a CLI for project initialization and management.

error TypeError: initClefbase is not a function
cause Attempting to import `initClefbase` using CommonJS `require()` syntax in an ES Module context, or vice-versa.
fix
Ensure your project uses ES Modules (import ... from 'pkg') and is configured with 'type': 'module' in package.json for Node.js, or use a bundler that handles ESM correctly.
error ClefbaseError: PROJECT_ID_MISSING: Project ID is required for SDK initialization.
cause The `projectId` or `apiKey` is missing or invalid in the configuration object passed to `initClefbase`.
fix
Run npx clefbase init to generate a valid clefbase.json or ensure that projectId and apiKey are correctly provided via environment variables or a manually constructed config object.
error ClefbaseError: Permission denied (403): Invalid Admin Secret or insufficient permissions for operation.
cause Attempting to use an API requiring elevated privileges (e.g., `getHosting`, certain database operations) without a valid `adminSecret` in the configuration.
fix
Provide the correct adminSecret in your Clefbase configuration. Ensure it is loaded securely from environment variables and is never exposed in client-side code.
error TypeError: Cannot read properties of null (reading 'id')
cause Accessing properties on a document object returned by `db.collection(...).doc(...).get()` without checking if the document exists (i.e., if it's `null`).
fix
Always check if the document object is not null before attempting to access its properties: const user = await db.getDoc('users', 'uid-123'); if (user) { console.log(user.id); }.
breaking Clefbase v2 and later are primarily designed for ES Modules (ESM). Direct usage with CommonJS 'require()' will likely result in 'TypeError: initClefbase is not a function' or 'Cannot find module' errors.
fix Ensure your project is configured for ESM (e.g., 'type: module' in package.json) and use 'import' statements. If stuck with CommonJS, consider transpilation or using a bundler.
gotcha Services like 'getHosting' and certain database admin operations require an 'adminSecret' in your configuration. Exposing this secret client-side or using an invalid secret will lead to 'Permission denied' errors and severe security vulnerabilities.
fix Always load your 'adminSecret' securely, preferably from server-side environment variables (e.g., `process.env.CLEFBASE_ADMIN_SECRET`) and ensure it's never exposed in client-side code bundles. Use 'npx clefbase init' to generate a secure configuration.
gotcha Database `doc().get()` methods return `null` when a document is not found, rather than throwing an error. Developers expecting an error for non-existent documents might encounter `TypeError: Cannot read properties of null` if they don't perform null checks.
fix Always check for `null` when retrieving documents: `const doc = await db.collection('coll').doc('id').get(); if (doc) { /* use doc */ }`.
gotcha The `npx clefbase init` command is essential for project setup, generating the `clefbase.json` configuration file and `.env.example`. Skipping this step or manually creating an incorrectly formatted `clefbase.json` will lead to SDK initialization failures.
fix Always start by running `npx clefbase init` in your project root and follow the prompts. Ensure `clefbase.json` is correctly structured and contains valid credentials (Project ID, API Key, Admin Secret).
npm install clefbase
yarn add clefbase
pnpm add clefbase

Demonstrates initializing Clefbase, adding/getting documents, querying, and user authentication with basic error handling, using environment variable fallbacks for configuration.

import { initClefbase, getDatabase, getAuth } from "clefbase";
// Assume clefbase.json exists from 'npx clefbase init'
// For local development or CI, ensure these are available.
// In a real application, config would typically be loaded securely.
import config from "./clefbase.json";

// In a real application, avoid hardcoding sensitive data.
// Use process.env for API Key and Admin Secret, or a secure configuration management.
// For demonstration, we'll assume config has necessary values or use fallbacks.
const app = initClefbase({
  projectId: config.projectId ?? process.env.CLEFBASE_PROJECT_ID ?? 'YOUR_PROJECT_ID',
  apiKey: config.apiKey ?? process.env.CLEFBASE_API_KEY ?? 'YOUR_API_KEY',
  adminSecret: config.adminSecret ?? process.env.CLEFBASE_ADMIN_SECRET ?? '' // Optional, for admin functions
});

const db = getDatabase(app);
const auth = getAuth(app);

async function runExample() {
  console.log("Initializing Clefbase application...");

  // Example: Add a new document
  const newPost = await db.collection("demoPosts").add({
    title: "My First Clefbase Post",
    content: "This is a demonstration of adding a document to Clefbase.",
    authorId: "user-123",
    published: true,
    createdAt: new Date().toISOString()
  });
  console.log(`Added post with ID: ${newPost.id}`);

  // Example: Get the document back
  const fetchedPost = await db.collection("demoPosts").doc(newPost.id).get();
  console.log("Fetched post title:", fetchedPost?.title);

  // Example: Basic query for published posts
  const publishedPosts = await db.collection("demoPosts")
    .where({ published: true })
    .getDocs();
  console.log(`Found ${publishedPosts.length} published posts.`);

  // Example: Sign up a dummy user (handle existing user gracefully for repeated runs)
  try {
    const { user } = await auth.signUp("example@clefbase.com", "securePassword123", {
      displayName: "Demo User",
    });
    console.log(`Signed up user: ${user.displayName} (ID: ${user.uid})`);
  } catch (error: any) {
    if (error.message.includes("User already exists")) {
      console.log("User already exists, attempting to sign in.");
      const { user } = await auth.signIn("example@clefbase.com", "securePassword123");
      console.log(`Signed in user: ${user.displayName} (ID: ${user.uid})`);
    } else {
      console.error("Auth error:", error.message);
    }
  }
}

runExample().catch(console.error);