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

@yarlisai/triggers-core

v0.1.0-alpha.1

Published

Generic primitives for poll-based triggers: cadence math, exponential backoff with jitter, and a provider-agnostic OAuth state machine.

Downloads

56

Readme

@yarlisai/triggers-core

Generic primitives for poll-based triggers — cadence math, exponential backoff with jitter, and a provider-agnostic OAuth resolver state machine. Built on the Port/Adapter pattern (ADR 0007). Wire your own state store via the TriggerProvider port; ship in-memory + Postgres adapters out of the box.

What this package does

If you're building any kind of polled integration — IMAP mailbox, Google Tasks, RSS feed, Atlassian Jira, GitHub issues, etc. — the same three problems show up every time:

  1. Cadence math — converting a tier label like 5m / 15m / 30m / 60m into a wall-clock next_poll_at after a successful tick.
  2. Backoff on failure — when the upstream is angry (rate limit, OAuth expiry, DNS), don't hammer it. Exponential 2× per failure past a threshold, capped at 4 hours, with ±20% jitter so parallel pollers don't retry in lockstep.
  3. OAuth resolution — a credential id stored on the trigger row → an access token, with a typed result discriminating "credential missing" / "row not found" / "refresh failed" / "token null" instead of throwing.

This package handles all three. Provider-specific code (the actual API call, payload shape, dedupe key) stays in your app.

Install

bun add @yarlisai/triggers-core@alpha

Zero runtime deps beyond @yarlisai/core (used only for typings). Pure TS — works in Node, Bun, edge, Workers.

Quick start

import {
  computeNextPollAt,
  computeNextPollAtWithBackoff,
  createOAuthResolver,
  createTriggersClient,
  describeOAuthFailure,
  memoryProvider,
} from '@yarlisai/triggers-core'

// 1. Backoff math (pure, no client needed)
const next = computeNextPollAtWithBackoff('5m', failureCount, new Date())

// 2. OAuth resolver bound to YOUR credential store + refresh helper
const resolveOAuth = createOAuthResolver({
  lookupCredential: async (id) => myDb.findCredential(id), // returns { userId } | null
  refreshAccessToken: async (id, userId, reqId) => myAuth.refresh(id, userId, reqId),
})

const result = await resolveOAuth({ credentialId, requestId: 'req-77' })
if (!result.ok) {
  await persistLastError(describeOAuthFailure(result))
  return
}
// use result.accessToken …

// 3. Optional client over a state store
const triggers = createTriggersClient({ provider: memoryProvider() })
const due = await triggers.getDueStates(new Date(), 100)

Backoff policy

export interface BackoffPolicy {
  startAfterFailures: number  // default 3 — first 3 failures stay on cadence
  multiplier: number          // default 2
  capMinutes: number          // default 240 (4h)
  jitterMin: number           // default 0.8 (-20%)
  jitterRange: number         // default 0.4 (+20% range)
}

All fields are overridable per-call:

computeNextPollAtWithBackoff('5m', 2, new Date(), Math.random, {
  startAfterFailures: 1,
  multiplier: 3,
})

OAuth resolver result

type ResolveOAuthResult =
  | { ok: true; accessToken: string }
  | {
      ok: false
      reason: 'credential_missing' | 'credential_not_found' | 'refresh_failed' | 'token_null'
      error?: string
    }

describeOAuthFailure(result) formats the failure into a oauth: <detail> string suitable for a last_error column, so DB inspection stays grep-friendly across providers.

TriggerProvider port

interface TriggerProvider {
  readonly name: string
  readonly isConfigured: boolean
  getState(id: string): Promise<TriggerPollerState | null>
  saveState(state: TriggerPollerState): Promise<void>
  getDueStates(now: Date, limit?: number): Promise<TriggerPollerState[]>
}

Built-in adapters

| Adapter | Factory | Notes | |---|---|---| | in-memory | memoryProvider() | Tests + single-process dev | | Postgres | postgresProvider({ query }) | Driver-agnostic — pass any (sql, params) => rows function |

The Postgres adapter expects a poller_state table by default — column names and the table name are overridable via the tableName + columns options.

import { postgresProvider } from '@yarlisai/triggers-core'

// Wraps `pg` Pool
import { Pool } from 'pg'
const pool = new Pool({ connectionString: process.env.DATABASE_URL })
const provider = postgresProvider({
  query: async (sql, params) => (await pool.query(sql, [...params])).rows,
})

Writing a custom adapter

import type { TriggerProvider } from '@yarlisai/triggers-core'

export function dynamoProvider(config: { tableName: string }): TriggerProvider {
  return {
    name: 'dynamo',
    isConfigured: true,
    async getState(id) { /* … */ return null },
    async saveState(state) { /* … */ },
    async getDueStates(now, limit) { /* … */ return [] },
  }
}

Drop it into createTriggersClient({ provider: dynamoProvider({...}) }) — done.

Build

bun install
cd packages/triggers-core
bun run build

Related

License

MIT