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

@prismacdp/sdk

v0.1.4

Published

SDK Node.js oficial do PrismaFlow para ingestao de eventos

Downloads

245

Readme

@prismacdp/sdk

SDK Node.js oficial do PrismaFlow para ingestão de eventos.

  • Node 22+ (usa fetch nativo)
  • Zero dependências de runtime
  • TypeScript-first, com tipagem completa
  • ESM + CJS (build dual)

Instalação

npm install @prismacdp/sdk
# ou
pnpm add @prismacdp/sdk
# ou
yarn add @prismacdp/sdk

Quickstart

import { PrismaFlow } from "@prismacdp/sdk";

const pf = new PrismaFlow({
  domain: process.env.PRISMAFLOW_DOMAIN!,
  apiKey: process.env.PRISMAFLOW_API_KEY!,
});

const result = await pf.track({
  name: "payment_created",
  version: 1,
  timestamp: event.createt_at,
  identifiers: { user_id: "usr_abc" },
  properties: { amount: 199.9, currency: "BRL" },
});

console.log(result.correlationId);

Configuração

| Opção | Tipo | Default | Descrição | | ------------- | -------- | ------- | ------------------------------------------- | | domain | string | — | Domínio público do PrismaFlow (obrigatório) | | apiKey | string | — | Chave de API do app (obrigatório) | | timeoutMs | number | 10000 | Timeout por tentativa em ms | | maxRetries | number | 3 | Número máximo de retentativas | | retryBaseMs | number | 250 | Delay base do backoff | | retryMaxMs | number | 5000 | Delay máximo do backoff |

API

track(event)

Envia um único evento.

const { correlationId, raw } = await pf.track({
  name: "user_signed_up",
  version: 1,
  timestamp: "2026-05-08T12:00:00.000Z",
  identifiers: { user_id: "usr_abc" },
  properties: { plan: "pro" },
  context: { source: "web", ip: "127.0.0.1" },
});

Retorno:

{
  "correlationId": "01985e2a-9f3c-7000-8000-abc123456789",
  "raw": {
    "ok": true,
    "args": { "correlation_id": "01985e2a-9f3c-7000-8000-abc123456789" },
    "timestamp": "2026-05-08T12:00:00.000Z"
  }
}

O correlationId identifica essa ingestão de ponta a ponta — guarde para troubleshooting.

trackBatch(events)

Envia múltiplos eventos em lote. Auto-chunk transparente: arrays acima do limite por requisição são divididos automaticamente em chunks sequenciais.

const { totalCount, chunks } = await pf.trackBatch([
  {
    name: "page_viewed",
    version: 1,
    timestamp: "2026-05-08T12:00:00.000Z",
    identifiers: { user_id: "usr_1" },
    properties: {
      path: "/checkout",
      referrer: "https://google.com",
      duration_ms: 1240,
    },
  },
  {
    name: "page_viewed",
    version: 1,
    timestamp: "2026-05-08T12:00:05.000Z",
    identifiers: { user_id: "usr_2" },
    properties: {
      path: "/pricing",
      referrer: "https://twitter.com",
      duration_ms: 820,
    },
  },
]);

Retorno:

{
  "totalCount": 2,
  "chunks": [
    {
      "correlationId": "01985e2a-9f3c-7000-8000-abc123456789",
      "count": 2,
      "raw": {
        "ok": true,
        "args": {
          "correlation_id": "01985e2a-9f3c-7000-8000-abc123456789",
          "count": 2
        },
        "timestamp": "2026-05-08T12:00:00.000Z"
      }
    }
  ]
}

Cada chunk traz seu próprio correlationId. Para batches grandes (acima do limite por requisição), o array chunks terá uma entrada por requisição enviada.

Tipos

TrackEvent

interface TrackEvent {
  name: string; // 1 a 50 chars: letra inicial + [letras, dígitos, _, -]
  version?: number; // inteiro >= 1 (default 1)
  timestamp: string; // ISO 8601 (ex: "2026-05-08T12:00:00.000Z")
  identifiers: Record<string, string | number>; // >= 1 chave
  properties: Record<string, unknown>;
  context?: Record<string, unknown>; // opcional (ip, source, etc)
}

A SDK valida o evento localmente antes de enviar — campos malformados falham instantaneamente sem round-trip.

Erros

Todos os erros estendem PrismaFlowError. Use instanceof ou os type guards estáticos .is():

import {
  PrismaFlowAuthError,
  PrismaFlowRateLimitError,
  PrismaFlowValidationError,
  PrismaFlowServerError,
  PrismaFlowNetworkError,
  PrismaFlowTimeoutError,
} from "@prismacdp/sdk";

try {
  await pf.track(event);
} catch (err) {
  if (PrismaFlowAuthError.is(err)) {
    // chave inválida ou ausente
  } else if (PrismaFlowRateLimitError.is(err)) {
    console.log(`tente novamente em ${err.retryAfterMs}ms`);
  } else if (PrismaFlowValidationError.is(err)) {
    console.log(err.issues); // detalhes campo a campo
  }
}

| Classe | Quando | Retentável? | | --------------------------- | ---------------------------------------------------- | ---------------- | | PrismaFlowAuthError | Chave inválida, ausente ou app desabilitado | Não | | PrismaFlowValidationError | Payload malformado | Não | | PrismaFlowServerError | Erro do servidor (5xx, pode carregar retryAfterMs) | Sim (automático) | | PrismaFlowNetworkError | Falha de rede (DNS, conexão) | Sim (automático) | | PrismaFlowTimeoutError | Timeout local da tentativa | Sim (automático) |

Cada erro carrega code, statusCode, correlationId e raw (resposta crua). O método toJSON() serializa de forma estável para logging.

Retry e idempotência

A SDK retenta automaticamente em 408, 425, 429, 5xx e erros de rede/timeout, com decorrelated jitter backoff. Quando a resposta inclui Retry-After, esse valor é respeitado (limitado por retryMaxMs).

Reenviar o mesmo evento é seguro. O servidor deduplica eventos idênticos por payload — duplicatas não geram processamento adicional. Isso significa que retentativas em caso de falha de rede não causam dupla contagem.

Licença

MIT