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

@anysoftinc/anydb-sdk

v0.5.1

Published

AnyDB TypeScript SDK for querying and transacting with Datomic databases

Downloads

742

Readme

AnyDB TypeScript SDK

TypeScript SDK for querying and transacting with Datomic databases via the AnyDB server.

Installation

npm install @anysoftinc/anydb-sdk

Quick Start

import {
  DatomicClient,
  createAnyDBClient,
  kw,
  sym,
  uuid,
} from "@anysoftinc/anydb-sdk";

// Create a client
const client = new DatomicClient({
  baseUrl: "http://localhost:4000",
  getAuthToken: () => process.env.ANYDB_TOKEN!,
});

// Create a database wrapper for convenience
const db = createAnyDBClient(client, "sql", "db-name");

// Symbolic query
const query = {
  find: [[sym("pull"), sym("?e"), [kw("db/id"), kw("person/name")]]],
  where: [[sym("?e"), kw("person/name"), "John Doe"]],
};
const rows = await db.query(query);

// Execute a transaction (keywordized keys, kw()/uuid() for values)
await db.transact([
  {
    ["person/id"]: uuid("550e8400-e29b-41d4-a716-446655440000"),
    ["person/name"]: "John Doe",
  },
]);

Core Features

Database Operations

  • Database Management - Create, list, and delete databases
  • Transactions - Execute database transactions
  • Queries - Execute Datalog queries with full EDN support
  • Entity Lookup - Retrieve individual entities
  • Datom Access - Raw datom queries with indexing

Query Types

Traditional array-based queries are not supported in v2.

Symbolic Queries (Type-safe)

import { sym, kw } from "@anysoftinc/anydb-sdk";

const query = {
  find: [sym("?e"), sym("?name")],
  where: [[sym("?e"), kw("person/name"), sym("?name")]],
};
const results = await db.query(query);

QueryBuilder has been removed in v2.

QueryBuilder Benefits:

  • Type Safety: All attributes use proper Keyword objects with kw()
  • IntelliSense: Full autocomplete for methods and parameters
  • Structured Queries: No string concatenation or EDN parsing errors
  • Fluent API: Chain methods for readable query construction
  • Aggregations: Built-in support for count, sum, avg, min, max
  • Direct Execution: Execute queries directly from the builder

Temporal Queries

// As-of queries
const pastResults = await client.query(query, [
  {
    "db/alias": "storage/db",
    "as-of": 1000,
  },
]);

// Since queries
const recentResults = await client.query(query, [
  {
    "db/alias": "storage/db",
    since: 1000,
  },
]);

// History queries
const allHistory = await client.query(query, [
  {
    "db/alias": "storage/db",
    history: true,
  },
]);

SchemaBuilder and DatomicUtils have been removed in v2. Use plain tx maps with keywordized keys and kw()/uuid() for values.

Utility Functions

Utility helpers for tempids and entity builders were removed in v2.

Idempotent Schema Install

Use ensureAttributes(db, schemaEntities) to install attribute idents exactly once per database alias. It checks which idents already exist and only transacts the missing ones.

import { ensureAttributes, kw } from "@anysoftinc/anydb-sdk";

await ensureAttributes(db, [
  { "db/ident": kw("person/name"), "db/valueType": kw("db.type/string"), "db/cardinality": kw("db.cardinality/one") },
  { "db/ident": kw("person/age"),  "db/valueType": kw("db.type/long"),   "db/cardinality": kw("db.cardinality/one") },
]);

Advanced Features

EDN Data Types

The SDK provides full support for Datomic's EDN data types:

import { sym, kw, uuid } from "@anysoftinc/anydb-sdk";

// Symbols for query variables
const entityVar = sym("?e");

// Keywords for attributes
const nameAttr = kw("person/name");

// UUIDs
const entityId = uuid("550e8400-e29b-41d4-a716-446655440000");

Event Streaming

Subscribe to transaction reports via Server-Sent Events:

const eventSource = db.subscribeToEvents(
  (event) => {
    const txData = JSON.parse(event.data);
    console.log("Transaction:", txData);
  },
  (error) => {
    console.error("Connection error:", error);
  }
);

// Close the connection when done
eventSource.close();

Raw Datom Queries

Access the raw datom index for high-performance queries:

// Query EAVT index
const datoms = await db.datoms("eavt", "-", {
  e: 12345,
  limit: 100,
});

// Query AVET index for attribute values
const attributeValues = await db.datoms("avet", "-", {
  a: ":person/name",
  start: "A",
  end: "B",
});

Custom HTTP Configuration

const client = new DatomicClient({
  baseUrl: "https://api.example.com",
  timeout: 30000,
  headers: {
    Authorization: "Bearer token",
    "X-Custom-Header": "value",
  },
});

NextAuth.js Integration

The SDK includes a NextAuth.js adapter for authentication:

import { AnyDBAdapter } from "@anysoftinc/anydb-sdk/nextauth-adapter";
import NextAuth from "next-auth";

export default NextAuth({
  adapter: AnyDBAdapter(db),
  providers: [
    // Your providers
  ],
});

Cookie names per app (avoid collisions)

If multiple apps share a domain, configure distinct cookie names so sessions don’t collide.

```ts
import NextAuth from "next-auth";
import { AnyDBAdapter, createNextAuthCookies } from "@anysoftinc/anydb-sdk/nextauth-adapter";

// ai-pm-suite
export default NextAuth({
  adapter: AnyDBAdapter(db),
  cookies: createNextAuthCookies("ai-pm-suite", { style: "cookie" }),
  // ... other config
});

// dashboard
export default NextAuth({
  adapter: AnyDBAdapter(db),
  cookies: createNextAuthCookies("dashboard", { style: "cookie" }),
  // ... other config
});

This produces names like ai-pm-suite.session.cookie, ai-pm-suite.callback.cookie, and ai-pm-suite.csrf.cookie (prefixed with __Host- in production). Clear existing cookies after changing names.

SSO across apps (shared DB)

If multiple apps use the same AnyDB auth database and you want single sign-on across them, derive cookie names from the database name so they all share the same cookie namespace:

import NextAuth from "next-auth";
import { AnyDBAdapter, createNextAuthCookiesFromDb } from "@anysoftinc/anydb-sdk/nextauth-adapter";

export default NextAuth({
  adapter: AnyDBAdapter(db),
  // Use DB name for cookie namespace to share sessions across apps
  cookies: createNextAuthCookiesFromDb(db, { style: "cookie" }),
  // ... other config
});

Auth Helpers (Server-side)

Issue AnyDB-compatible HS256 tokens and normalize subjects consistently across apps:

import { createServiceTokenProvider, signFromSessionClaims } from "@anysoftinc/anydb-sdk/auth";

// 1) Service token provider (e.g., for adapters/bootstrap)
const getServiceToken = createServiceTokenProvider({
  secret: process.env.JWT_SECRET!,
  storageAlias: "dev",
  dbName: "app",
  iss: "my-app-service",
  ttlSeconds: 3600,
});

// Use with DatomicClient
// new DatomicClient({ baseUrl, getAuthToken: getServiceToken })

// 2) Per-user token from NextAuth claims (re-signs JWS for AnyDB)
const token = signFromSessionClaims({
  claims: nextAuthClaims, // from next-auth/jwt getToken()
  secret: process.env.JWT_SECRET!,
  storageAlias: "dev",
  dbName: "app",
  iss: "my-app-auth",
  ttlSeconds: 900,
});

Error Handling

The SDK provides detailed error information:

try {
  const results = await db.query(invalidQuery);
} catch (error) {
  if (error.message.includes("Datomic API error")) {
    console.error("Server error:", error.message);
  } else {
    console.error("Client error:", error);
  }
}

TypeScript Support

Full TypeScript definitions are included:

import type {
  QueryResult,
  Transaction,
  Entity,
  Datom,
  DatabaseDescriptor,
} from "@anysoftinc/anydb-sdk";

const processResults = (results: QueryResult): void => {
  results.forEach((row) => {
    console.log("Row:", row);
  });
};

Examples

See the examples directory for complete working examples:

API Reference

DatomicClient

The main client class for interacting with the AnyDB server.

AnyDBClient

Convenience wrapper for working with a specific database.

Related