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

@unhandled/agent-adonisjs

v0.7.6

Published

Unhandled for AdonisJS: first-party layer on @unhandled/node for routes, auth users, the exception handler, Ace commands, mail and queues

Readme

@unhandled/agent-adonisjs

Sends traces, logs, metrics, exceptions and analytics events from an AdonisJS 6.2+ or 7 app to Unhandled over OTLP/HTTP. It is the AdonisJS layer on top of @unhandled/node, which owns the OpenTelemetry Node SDK. This package adds route names, the signed-in user, the exception handler hook, Ace command spans, mail spans and @adonisjs/queue spans. Every @unhandled/node option works in config/unhandled.ts.

Install

node ace add @unhandled/agent-adonisjs

node ace add installs the package with your package manager and runs its configure hook. AdonisJS 6.2 has no add command (it arrived in 6.3), so install the package and run node ace configure @unhandled/agent-adonisjs there.

The configure hook:

  • creates config/unhandled.ts and otel.ts
  • adds import '../otel.js' as the first import of bin/server.ts and bin/console.ts (skipped when already there)
  • registers the provider in adonisrc.ts and the middleware as the first router middleware
  • adds APP_ENV and UNHANDLED_DSN to .env and start/env.ts, leaving an existing DSN alone

otel.ts must stay the first import. Anything imported before it loads unpatched and produces no spans.

The hook stops without changing anything when otel.ts starts @adonisjs/otel, and the provider refuses to boot beside the @adonisjs/otel provider. Pick one package: see Migrate from @adonisjs/otel.

Paste the DSN from the service settings page:

UNHANDLED_DSN=https://[email protected]/0b4f6c2e-8a1d-4c3e-9f7a-1234567890ab

Staying on @adonisjs/otel

Apps that keep @adonisjs/otel don't need this package. Install @unhandled/otel-lean instead: it has the same preset and installs neither the agent nor the @unhandled/node SDK. In config/otel.ts:

import { unhandledDestinations } from '@unhandled/otel-lean/otel_preset'

export default defineConfig({
  // ...
  destinations: unhandledDestinations({ dsn: env.get('UNHANDLED_DSN'), environment: env.get('APP_ENV') }),
})

Passing destinations switches export away from the OTEL_* variables: the OpenTelemetry Node SDK builds no exporter from OTEL_EXPORTER_OTLP_* once a destination supplies its own. If your .env has both UNHANDLED_DSN and OTEL_* variables, everything goes to the DSN and the OTEL_* endpoint receives nothing.

This covers export only; exception capture, mail and Ace spans and job sampling need the agent.

@unhandled/agent-adonisjs/otel_preset, /execution_context and /knex_pool_wait re-export the @unhandled/otel-lean subpaths, so imports from 0.4.0 keep working. They load without the SDK, but installing this package still installs it. See the @unhandled/otel-lean README for the connection pool wait, the web or background context and the @opentelemetry/instrumentation pin.

Configuration

// config/unhandled.ts
import { defineConfig } from '@unhandled/agent-adonisjs'

export default defineConfig({})

otel.ts loads this file before the app boots, and defineConfig() reads UNHANDLED_DSN, APP_ENV and UNHANDLED_ENV from the process environment and the .env files on its own. Don't import #start/env here: Env.create copies .env into process.env that early, and node ace test then passes those values to the test process ahead of .env.test. Running node ace configure @unhandled/agent-adonisjs replaces the config that versions up to 0.7.4 generated.

| Option | Default | Effect | | --------------------------------------------------- | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | dsn | none | Endpoint, API key and service id. Without it (and without extra destinations) nothing is exported. An invalid DSN disables export with a warning. | | dev | false | Ignores the DSN. Exports only when endpoint points at a local collector. | | apiKey, endpoint, serviceName | none | Legacy setup: sends x-api-key and x-unhandled-env to endpoint. dsn wins when both are set. endpoint also overrides the DSN host. | | environment | UNHANDLED_ENV, then APP_ENV or NODE_ENV if it is production, staging or development, else development | Aliases such as prod are read with a warning; any other value in the option or UNHANDLED_ENV turns export off with a warning. | | serviceVersion | detected | See version detection below. | | enabled | true, false when NODE_ENV=test | Turns the SDK off. | | debug | false | Also prints every span to the console. | | samplingRatio | 1 | Head sampling ratio in [0, 1]. Forced to 1 when sampling is set. Below 1, kept spans carry unhandled.sampling.ratio. | | sampling(ctx) | none | Per-job sampling, see below. | | compression | true | gzip on every signal. 'gzip' and 'none' still work. | | batch | 512 items, 5 s delay, 30 s timeout, queue of 2048 | Span and log batch processors. | | shutdownTimeoutMillis | 5000 | Deadline for flush() and shutdown(). Neither rejects; unsent telemetry is dropped at the deadline. | | hostMetrics | { enabled: true } | CPU, memory and network metrics. false also works. | | destinations | [] | Extra OTLP endpoints, each receiving traces, metrics and logs next to the DSN destination. | | integrations | [] | Integration packages such as @unhandled/instrumentation-bullmq. Names must be unique. | | mail | { enabled: true } | Mail spans. false turns them off. | | queue | { enabled: true, executionSpanLinkMode: 'link' } | Job spans for @adonisjs/queue. 'parent' makes executions children of the dispatch span. | | cli | include *, exclude make:*, generate:*, queue:work, queue:listen | Ace command spans. Long-running commands are never traced. | | ignoreOptionsRequests | true | Drops CORS preflight spans. | | http | see below | Ignored URLs, URL sanitizing and body capture. | | ignoreExceptions, ignoreStatuses, ignoreCodes | [] | Error classes, HTTP statuses and error codes the exception handler hook does not report. | | userContext | reads id and role from ctx.auth.user | email: true also sends the email (personal data), resolver(ctx) returns the user (extra keys become user.<key>), false turns it off. | | instrumentations | net, dns, socket.io, pg, mysql and mysql2 off | Per auto-instrumentation config, { enabled: false }, or an Instrumentation instance. | | processHandlers | true | Reports uncaught exceptions and unhandled rejections, then keeps Node's crash behavior. |

The keys ai, mastra, bullmq and cache are not agent options. Passing them logs a warning that names the package to install instead, and they are ignored.

import { defineConfig, destinations } from '@unhandled/agent-adonisjs'

export default defineConfig({
  destinations: [
    destinations.otlp({
      name: 'grafana',
      url: 'https://otlp-gateway.grafana.net/otlp',
      headers: { Authorization: `Basic ${btoa('id:key')}` },
    }),
  ],
})

Service name and version

With a DSN the ingest server takes the service from the DSN. For other destinations the name comes from serviceName, OTEL_SERVICE_NAME, APP_NAME, the package.json name without its npm scope, then unknown_service.

The version comes from the first usable value of serviceVersion, UNHANDLED_VERSION, APP_VERSION, the platform revision (Vercel, Render, Railway, Heroku, Coolify, Dokku, Cloud Run), the CI commit (GitHub Actions, GitLab CI, CircleCI, Bitbucket Pipelines, Buildkite, Cloudflare Workers Builds), then the local .git HEAD. Placeholders (0.0.0, 0.0.1, 1.0.0, unknown, dev, latest, empty) are skipped. The resource gets service.version, unhandled.service.version.source (config, env:UNHANDLED_VERSION, platform:render, ci:github_actions, git, ...) and vcs.ref.head.revision when a commit SHA is known.

HTTP

defineConfig({
  http: {
    ignoredUrls: ['/internal/*'],
    sanitizeUrls: { queryParams: ['invite'], censor: 'REDACTED' },
    captureBodies: {
      incoming: { request: { enabled: true }, response: { enabled: true } },
      outgoing: { request: { enabled: true, maxBodySize: 16_384 } },
      redact: { bodyKeys: ['pin'], headers: ['x-tenant'] },
      transform: (record) => {
        record.http.body = { ...record.http.body, trimmed: true }
      },
    },
  },
})
  • ignoredUrls add to the built-in list of health checks, metrics endpoints, static files and Vite dev assets. /admin and /admin/* cover the path and everything below it, other * are globs.
  • sanitizeUrls is on by default. It rewrites http.url, url.full, url.path, http.target and url.query on server and client spans: secret query values (token, code, state, signature, api_key and the body redaction names) and secret path segments (JWTs, email addresses, keys with a known secret prefix such as sk_live_ or ghp_, random tokens of 32 or more mixed-case characters with a digit, ids of 8 or more characters with a digit in the 2 segments after a reset, verify, invite, token, session, share, oauth, key, hook or download segment, Slack webhook secrets, and ;jsessionid= values) become REDACTED. Ids such as UUIDs and hashes stay; strict: true keeps these rules and also replaces UUIDs and opaque ids. queryParams adds names, sanitize(url) replaces the whole URL instead, and sanitizeUrls: false turns it off. Before this release it was opt-in and queryParams replaced the built-in names.
  • Body capture is off until enabled or a per-side enabled is set. Only application/json and application/x-www-form-urlencoded bodies are kept. Built-in keys (password, token, code, access_token, refresh_token, authorization, secret, api_key, client_secret, cookie, session, otp, cvv, card_number, ssn and more, matched case and separator insensitively) are always redacted and your lists add to them. Redaction runs before transform; returning null from transform skips the capture. Bodies are cut to maxBodySize bytes (default 10 000) and stored as unhandled.http.request.body and unhandled.http.response.body. Raw text longer than 64 KiB, or than maxBodySize when that is larger, is not parsed. The span gets unhandled.http.request.body_omitted or unhandled.http.response.body_omitted set to too_large.
  • Incoming bodies are read from the Adonis request and response in the middleware. Outgoing capture hooks node:http and node:https only, not fetch or undici.
  • Options you set under instrumentations['@opentelemetry/instrumentation-http'] merge with these. Your ignoreIncomingRequestHook, requestHook and responseHook run in addition to the built-in ones.

Job sampling

import { defineConfig, Sample } from '@unhandled/agent-adonisjs'

defineConfig({
  sampling: (job) => {
    if (job.name === 'HeartbeatJob') return Sample.never()
    if (job.name === 'SendNewsletterEmail') return Sample.rate(0).keepErrors({ maxSpans: 500 })
    return Sample.default()
  },
})

The callback gets { kind: 'job', system, name, queue?, jobId?, attempt? }. Jobs from @adonisjs/queue are recognised from their consumer span; integrations such as BullMQ ask before the worker body runs, so a dropped job creates no spans at all. keepErrors() buffers the job's spans until the root ends and exports them only if something failed, root first. It buffers at most maxSpans spans, by default one less than batch.maxQueueSize (2047). Later spans are dropped, and the root gets unhandled.sampling.truncated=true and unhandled.sampling.dropped_spans=<n>.

What gets recorded

  • HTTP server spans named GET /users/:id with http.route, adonis.route.name, the status and the signed-in user.
  • Database, Redis, outgoing HTTP and the other Node auto-instrumentations.
  • Mail sends (including queued ones) as CLIENT spans named email send <mailer> with email.system=adonisjs-mail, email.operation=send, email.transport, email.message.subject, email.message.from, email.message.to (JSON array), email.recipient_count and email.message.id. Failures record the exception and set ERROR status.
  • Queue dispatch and execution spans from @adonisjs/queue.
  • Ace commands as cli <name> spans with entry_point.type=cli, cli.command.name, cli.command.description, cli.args.* and cli.flags.*.
  • Exceptions reported by the Adonis exception handler or failed Ace commands (an app report() override must still call await super.report(error, ctx)), as log records with unhandled.log.source=exception_reporter, the cause tree and source lines for in-app frames. Source lines come only from .js/.ts source files under the app root (sourceContext.root), never from paths named in an error message, dotfiles such as .env, or node_modules unless sourceContext.includeNodeModules is true.
  • Pino logs and runtime and host metrics.

API

import { Unhandled } from '@unhandled/agent-adonisjs'

Unhandled.setUser({ id: user.id, email: user.email, name: user.fullName })
Unhandled.captureException(error, {
  user: { id: 7 },
  tags: { area: 'billing' },
  extra: { orderId },
})
Unhandled.captureMessage('quota almost used', 'warning')
Unhandled.captureMessage('import finished', { level: 'info', tags: { source: 'csv' } })
Unhandled.track('subscription_started', { plan: 'pro', seats: 3 })
Unhandled.trackRevenue({ amount: 1999, currency: 'usd', product: 'pro', subscription: { id: 'sub_1', interval: 'month' } })
Unhandled.identify(user.id, { plan: 'pro' })
Unhandled.setUserProperties({ seats: 3 })

setUser writes user.id, user.email and user.name on the active span and on the request's SERVER span. The SERVER span is found through the OpenTelemetry RPC metadata the HTTP instrumentation attaches to the request context, so the call works from nested spans in controllers and services. Never put secrets in user fields.

identify is the opt-in that links analytics events to a user. It binds the id to the current request only: later track() calls in that request carry user.id, and the request span gets user.id like setUser({ id }). Nothing is taken from the auth user automatically. setUserProperties updates the bound user's profile (no_user without one) and reset unbinds. They are also exported from @unhandled/agent-adonisjs/helpers.

trackRevenue({ amount, currency, id?, product?, subscription?, properties? }) records a purchase, renewal or refund. amount is an integer in the currency's minor unit (1999 is $19.99), negative for a refund. subscription is { id, interval: 'day' | 'week' | 'month' | 'year', intervalCount? } and feeds MRR. Like track, it returns { ok: true, eventId } or { ok: false, error } and carries the bound user.id. Pass the payment provider's charge id as id so a retried call counts once. The event name revenue is reserved for it, so track('revenue') returns reserved_name.

getVariant(experiment, variants, { userId? }) returns the variant of the request's identified user (or userId) and records an experiment_exposure event; every SDK picks the same variant for the same user. Without a user it returns the first variant and records nothing. trackExposure(experiment, variant, { userId? }) records a variant you assigned yourself.

captureMessage levels are debug, info (default), log, warning, error and fatal, sent as unhandled.message.level. It never throws. captureException sends unhandled.message.level=error.

Custom spans

import { record, setAttributes } from '@unhandled/agent-adonisjs/helpers'
import { span, spanAll } from '@unhandled/agent-adonisjs/decorators'

await record('report.generate', async (active) => {
  active.setAttribute('report.type', 'monthly')
  return buildReport()
})

@spanAll({ prefix: 'user' })
class UserService {
  findById(id: number) {}
}

./helpers re-exports getCurrentSpan, setAttributes, recordEvent, injectTraceContext, extractTraceContext, setUser, identify, setUserProperties, trackRevenue, getVariant, trackExposure and reset. Its record and handleError, and the @span / @spanAll decorators, add an exception event with unhandled.exception.frames (source lines around in-app frames) and unhandled.exception.cause_chain (every cause, including AggregateError children), set ERROR status, end the span and rethrow.

Background spans

A query or outgoing call that runs outside a request, job or Ace command becomes the root of its own trace and shows up as a background span. To fix it:

  • Wrap polling loops, timers and hand-rolled workers in record('sync.tick', async () => { ... }) so their queries get a parent.
  • Keep work inside the span's async callback. When a library loses context (emitters, pools, callbacks), run the callback with context.with(savedContext, fn) from @opentelemetry/api.
  • Keep import '../otel.js' the first import of bin/server.ts and bin/console.ts. Modules loaded before it are not instrumented.
  • Silence intentional noise (health probes, tight polling) with context.with(suppressTracing(context.active()), fn) using suppressTracing from @opentelemetry/core.

For AI agents

A coding agent can install this package, check that its data arrives and fix the errors it reports through the Unhandled MCP server at https://unhandled.net/mcp. In Claude Code, the Unhandled plugin adds that server plus skills for instrumenting a service, fixing a production error with a failing test first and verifying a deploy:

claude plugin marketplace add treboryx/unhandled
claude plugin install unhandled@unhandled

Codex, Cursor, Gemini CLI and other agents connect to the same URL. Coding agents has the setup for each one and an AGENTS.md section to add to your repository.