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 🙏

© 2026 – Pkg Stats / Ryan Hefner

triqai

v0.4.0

Published

Official TypeScript SDK for the Triqai Transaction Enrichment API

Readme

Triqai Node.js SDK

The official Node.js / TypeScript SDK for the Triqai Transaction Enrichment API.

Enrich raw bank transaction descriptions into structured data: merchants, categories, locations, intermediaries, and more.

Installation

npm install triqai
yarn add triqai
pnpm add triqai

Quick Start

import Triqai from "triqai";

const triqai = new Triqai("triq_your_api_key");

const result = await triqai.transactions.enrich({
  title: "STARBUCKS SEATTLE WA",
  country: "US",
  type: "expense",
});

console.log(result.data.transaction.category.primary.name);
// => "Cafes" (the most specific category; secondary and tertiary are its parents)

console.log(result.data.entities);
// => [{ type: "merchant", data: { name: "Starbucks", ... } }, ...]

Requirements

  • Node.js 18+ (uses native fetch)
  • Also works in Bun, Deno, and Cloudflare Workers

Configuration

const triqai = new Triqai("triq_your_api_key", {
  // Base URL (default: https://api.triqai.com)
  baseUrl: "https://api.triqai.com",

  // Retry configuration
  maxRetries: 3, // default: 3
  retryDelay: 500, // base delay in ms (default: 500)
  maxRetryDelay: 30_000, // max delay in ms (default: 30000)

  // Total call budget, including attempts and retry waits (default: 300000)
  maxRetryTime: 300_000,

  // Per-attempt timeout, including response body, in ms (default: 60000)
  timeout: 60_000,

  // Pacing within your rate limits (default: on in Node.js and Bun). See "Pacing" below.
  pacing: true,

  // Extra headers for every request
  defaultHeaders: {
    "X-Custom-Header": "value",
  },

  // Debug hooks
  onRequest: (info) => console.log(`${info.method} ${info.url}`),
  onResponse: (info) => console.log(`${info.status} in ${info.durationMs}ms`),
});

API Reference

Transactions

Enrich a transaction

const result = await triqai.transactions.enrich({
  title: "AMAZON MKTPLACE PMTS AMZN.COM/BILL WA",
  country: "US",
  type: "expense",
  options: {
    // Skip specific entity extraction
    filters: {
      noLocation: true,
      noIntermediary: true,
    },
    // Pre-fill known data to improve accuracy
    merchant: {
      name: "Amazon",
    },
  },
});

// When your payment rail already tells you who was paid, pass `p2p`:
// `true` for a person-to-person transfer, `false` for a payment to a business.
await triqai.transactions.enrich({
  title: "BILL PAYMENT TO J D MORGAN REF RENT",
  country: "GB",
  type: "expense",
  options: { p2p: true },
});

// API v1.1.11+: `data.transaction.channel` is no longer returned.
// Confidence reasons are dynamic and may include tags like:
// `venue_or_attraction`, `merchant_location_crosscheck_corrected`,
// `merchant_location_crosscheck_recovered`, `merchant_location_mismatch`, `geo_mismatch`.

Enrich with idempotency

const result = await triqai.transactions.enrich(
  { title: "STARBUCKS", country: "US", type: "expense" },
  // One key per bank transaction (e.g. your own transaction ID), so a retry
  // replays the original result without a second charge.
  { idempotencyKey: "txn_8f14e45f" },
);

The force option is deprecated and has no effect. The API has no cache bypass, so the SDK no longer sends it.

Cancel a call

Every method accepts a signal in its last options argument:

const controller = new AbortController();
const result = await triqai.transactions.enrich(
  { title: "STARBUCKS", country: "US", type: "expense" },
  { signal: controller.signal },
);

const page = await triqai.transactions.list({ size: 50 }, { signal: AbortSignal.timeout(30_000) });
const merchant = await triqai.merchants.get("merchant-uuid", { signal: controller.signal });
const raw = await triqai.rawGet("/v1/categories", undefined, { signal: controller.signal });

Aborting rejects the call with the signal's reason (an AbortError by default), including while it waits its turn, between retries, or in flight.

List transactions

// Get a single page
const page = await triqai.transactions.list({
  page: 1,
  size: 50,
  startDate: "2026-01-01T00:00:00Z",
  endDate: "2026-03-01T00:00:00Z",
});

console.log(page.data); // EnrichedTransaction[]
console.log(page.pageInfo); // { page, size, total, totalPages }

// Navigate pages
if (page.hasNextPage) {
  const nextPage = await page.nextPage();
}

Auto-paginate

const page = await triqai.transactions.list();

for await (const tx of page) {
  console.log(tx.id, tx.raw, tx.status);
}

Count transactions

const { count } = await triqai.transactions.count();

// Only transactions created on or after a date (ISO 8601 string or Date)
const { count: recent } = await triqai.transactions.count({
  afterDate: "2026-01-01T00:00:00Z",
});

Get a transaction

const tx = await triqai.transactions.get("550e8400-e29b-41d4-a716-446655440000");

Delete a transaction

const { deleted, transactionId } = await triqai.transactions.delete(
  "550e8400-e29b-41d4-a716-446655440000",
);

Delete transactions in bulk

Pass exactly one of ids (at most 1000 UUIDs), afterDate, or all: true:

// Specific transactions
const { count } = await triqai.transactions.batchDelete({
  ids: ["550e8400-e29b-41d4-a716-446655440000", "a1b2c3d4-e5f6-7890-abcd-ef1234567890"],
});

// Everything created on or after a date (ISO 8601 string or Date)
await triqai.transactions.batchDelete({ afterDate: "2026-01-01T00:00:00Z" });

// Every transaction in your organization
await triqai.transactions.batchDelete({ all: true });

Any other combination throws a ValidationError. A 503 means cleanup is incomplete. The SDK retries it automatically. If it still fails, call again with the same request. After a retry, count covers only the final attempt.

Categories

const { categories, total, categoryVersion } = await triqai.categories.list();

for (const cat of categories) {
  console.log(`${cat.name} (level ${cat.level}, type: ${cat.type})`);
}

Merchants

const merchant = await triqai.merchants.get("merchant-uuid");
console.log(merchant.name, merchant.website, merchant.icon);

Locations

const location = await triqai.locations.get("location-uuid");
console.log(location.formatted, location.structured.city);

Intermediaries

const intermediary = await triqai.intermediaries.get("intermediary-uuid");
console.log(intermediary.name); // "PayPal", "Square", etc.

Issue Reports

Report an enrichment issue

const report = await triqai.issueReports.create({
  transactionId: "tx-uuid",
  description: "Merchant was identified incorrectly",
  fields: ["entities.merchant.data.name"],
});

List issue reports

const page = await triqai.issueReports.list({
  status: "pending",
  transactionId: "tx-uuid",
});

// Auto-paginate
for await (const report of page) {
  console.log(report.id, report.status);
}

Get an issue report

const report = await triqai.issueReports.get("report-uuid");

Error Handling

All API errors are thrown as TriqaiError. Common HTTP statuses are mapped to typed subclasses:

import Triqai, {
  TriqaiError,
  AuthenticationError,
  ValidationError,
  RateLimitError,
  InsufficientCreditsError,
  NotFoundError,
} from "triqai";

try {
  await triqai.transactions.enrich({ title: "", country: "US", type: "expense" });
} catch (err) {
  if (err instanceof ValidationError) {
    console.log("Field errors:", err.fieldErrors);
    // { title: ["Title cannot be empty"] }
  } else if (err instanceof RateLimitError) {
    console.log("Retry after:", err.rateLimitInfo.retryAfter, "seconds");
  } else if (err instanceof AuthenticationError) {
    console.log("Check your API key");
  } else if (err instanceof InsufficientCreditsError) {
    console.log("Top up credits at https://triqai.com/dashboard");
  } else if (err instanceof NotFoundError) {
    console.log("Resource not found");
  } else if (err instanceof TriqaiError) {
    console.log(`API error ${err.statusCode}: ${err.message} [${err.code}]`);
    console.log("Request ID:", err.requestId);
  }
}

Error Classes

| Class | Status | When | | --- | --- | --- | | AuthenticationError | 401 | Invalid or missing API key | | InsufficientCreditsError | 402 | No credits remaining | | AuthorizationError | 403 | Key valid but not authorized | | NotFoundError | 404 | Resource does not exist | | ClientDisconnectedError | 499 | Client disconnected before completion | | DuplicateRequestError | 409 | Idempotency key used for a different request (reason: "payload_mismatch"), or the same request is still in progress (retried automatically) | | GoneError | 410 | Transaction data erased or organization inactive (never retried) | | ValidationError | 422 | Request body validation failed | | RateLimitError | 429 | Rate limit exceeded | | InternalServerError | 500 | Server error (retried automatically) | | ServiceUnavailableError | 503 | Service temporarily down (retried automatically) | | GatewayTimeoutError | 504 | Upstream timeout | | ConnectionError | - | Network/DNS failure | | TimeoutError | - | Request exceeded timeout | | PacingTimeoutError | - | A call waited longer than pacing.maxWait for its turn; it was never sent (a TimeoutError with code pacing_timeout) |

Automatic Retries

The SDK automatically retries on transient errors (429, 500, 503, 504, and network errors) with exponential backoff:

  • GET and DELETE requests are always retried
  • Enrichment calls generate an idempotency key and reuse it across automatic retries. Supply your own idempotencyKey to safely retry across separate calls
  • A 409 for the same enrichment that is still in progress is retried after Retry-After and returns the stored result. A 409 with reason: "payload_mismatch" is not retried
  • The Retry-After header is a minimum delay; the SDK never retries early to fit a limit
  • With pacing, after a 429 other calls on the same client wait too (see Pacing)
  • Calls have a 5-minute total budget (maxRetryTime), including attempts, response bodies, and retry waits. If a retry delay cannot fit, the SDK throws the last error with its retry information so you can schedule a later call using the same idempotency key. With pacing, the budget starts when the first attempt is sent, and a retry is only sent with at least min(1s, timeout / 2) of it left
  • Default: 3 retries, 500ms base delay, 30s max delay

Disable retries:

const triqai = new Triqai("triq_your_api_key", { maxRetries: 0 });

Pacing

Pacing keeps a client's requests within your organization's rate limits, so a burst of calls, such as Promise.all over a batch, waits its turn on the client instead of being refused with 429. It is on by default in Node.js and Bun, and off by default elsewhere (see Cloudflare Workers and other runtimes).

  • Concurrency. Enrichments in flight stay within X-RateLimit-Concurrency-Limit. Only enrichments wait for one of these slots, so reads are not held behind a queued batch.
  • Rate. All requests are spaced to the per-second rate in X-RateLimit-Limit on responses whose X-RateLimit-Scope is rps or absent. When X-RateLimit-Remaining shows fewer requests left than the client expects, for example while another process uses the same organization, the client slows down to match.
  • Before the limits are known. Until a response reports them, at most 5 requests are in flight, enrichments included. A proxy that strips the X-RateLimit-* headers keeps a client at this limit; set pacing: false or explicit limits in that case.
  • After a 429. Every call on the client waits for the limit it names: X-RateLimit-Scope: rps, or no scope, pauses all requests; concurrency pauses enrichments, and enrichments that hold a slot but have not been sent give it back. The pause lasts the Retry-After time plus up to 20% (at most 1 second) of jitter. Without Retry-After, it lasts until X-RateLimit-Reset, measured against the response's Date header, when that is at most 10 seconds away; otherwise the normal backoff applies. Other calls wait at most 60 seconds before trying again.
  • Fewer enrichments after a concurrency 429. The client keeps fewer enrichments in flight than were running when it was refused, then adds one back after as many successful enrichments as its current limit, counting only enrichments sent after the decrease. Refusals of enrichments sent before the limit was known do not lower it.
  • Retries first. A call that is retried keeps its place, and its enrichment slot while the limit allows, and goes ahead of calls that have not been sent yet.
  • Budgets. Waiting for a turn before the first attempt is limited by pacing.maxWait (default: maxRetryTime), not by timeout or maxRetryTime. A call that waits longer rejects with PacingTimeoutError and is never sent or charged. maxRetryTime starts when the first attempt is sent. Pass a signal to cancel a call at any point.

Pacing is per client, so share one client across a batch. Processes that share an organization also share its limits: give each one lower limits. Your limits apply when they are lower than the API's:

const triqai = new Triqai("triq_your_api_key", {
  pacing: {
    maxConcurrency: 5, // enrichments in flight
    requestsPerSecond: 3, // all requests, retries included
    maxWait: 600_000, // wait up to 10 minutes for a turn
  },
});

To send every request as soon as it is made, as before pacing, disable it:

const triqai = new Triqai("triq_your_api_key", { pacing: false });

Cloudflare Workers and other runtimes

Pacing is off by default in Cloudflare Workers, Deno, edge runtimes and browsers. Workers bind the work of each request to that request, so one request cannot reliably wait for another's call to finish. In Workers, create the client inside each request handler, or keep pacing off. Within one request, pacing: true still paces a batch of calls on that request's client. If you opt in with a client shared across requests, a slot granted to a request that no longer runs returns to the pool within a second; pass { signal: request.signal } to each call, so a call whose client has gone is not sent.

Tests with fake timers

Pacing uses Date.now() and setTimeout. In tests that fake timers, fake both and advance the clock, or set pacing: false.

Rate Limiting

Rate limit information is available on responses from rate-limited endpoints. The SDK paces requests and handles 429 responses automatically, but you can monitor usage via the onResponse hook or rawGet/rawPost/rawDelete methods:

// Option 1: Debug hook
const triqai = new Triqai("triq_your_api_key", {
  onResponse: (info) => {
    // info.headers contains X-RateLimit-* values
  },
});

// Option 2: Raw request with full response
const resp = await triqai.rawGet("/v1/categories");
console.log(resp.rateLimitInfo.remaining); // tokens left
console.log(resp.rateLimitInfo.limit); // max tokens
console.log(resp.rateLimitInfo.concurrencyRemaining); // concurrent slots left

Health & API Info

// Check API health
const health = await triqai.health();
console.log(health.data.status); // "healthy"

// Get API version and endpoint directory
const info = await triqai.apiInfo();
console.log(info.data.version); // "v1"
console.log(info.data.endpoints);

Raw Requests

For endpoints not yet covered by a resource class, or when you need the full HTTP response (headers, rate limit info):

import type { HttpResponse } from "triqai";

// Full response with headers and rate limit info
const resp: HttpResponse<any> = await triqai.rawGet("/v1/categories");
console.log(resp.data); // response body
console.log(resp.rateLimitInfo); // { limit, remaining, ... }

Banks

Search stored banks by exact name (case-insensitive), optionally filtered by country of origin:

const result = await triqai.banks.search({ name: "ING", country: "NL" });
for (const bank of result.banks) {
  console.log(bank.id, bank.name, bank.country, bank.icon);
}

if (result.pagination.hasMore) {
  const nextPage = await triqai.banks.search({ name: "ING", country: "NL", page: 2 });
  console.log(nextPage.banks);
}

const bank = await triqai.banks.get("550e8400-e29b-41d4-a716-446655440000");

name is required (1–200 characters after trimming). country is an optional ISO 3166-1 alpha-2 code for the bank's origin, not where it operates. Both lowercase and uppercase country codes are accepted. Search returns candidates because multiple banks can share a name; it does not select one arbitrarily. No match returns an empty banks array. A missing bank ID returns 404.

page defaults to 1 (maximum 10,000), and size defaults to 20 (maximum 100). Results are ordered by country (unknown last), then ID. Keep filters and size the same on subsequent pages; results may change between requests during a backfill.

Profiles include foundedYear, foundedOn (an exact date when known), description, icon (logo URL), color, website, and domain. Unknown values are null. Bank reads require an API key, are rate limited, and cost zero credits. The catalog starts empty until populated administratively. Lookups only read stored data, with no fuzzy matching, enrichment, or automatic bank creation.

Pricing

The Triqai API uses a credit-based pricing model. See triqai.com/pricing for details.

TypeScript

This package is written in TypeScript and ships with full type definitions. All request/response types are exported:

import type {
  EnrichRequest,
  EnrichSuccessResponse,
  EnrichedTransaction,
  MerchantData,
  LocationData,
  CategoryInfo,
  EntityResult,
  TransactionType,
  EnrichmentFieldPath,
} from "triqai";

Contributing

See CONTRIBUTING.md for development setup and guidelines.

License

MIT - see LICENSE for details.

The Triqai API itself is a commercial product. This SDK is open source, but API usage requires an API key and is subject to Triqai's terms of service.