managarten/packages/shared-error-tracking/src/index.ts
Till JS f422fd6779 fix(shared-error-tracking): point main at src/, strip dashes from Glitchtip DSN
Two real-world fixes from wiring mana-auth to Glitchtip:

1. The compiled dist/ folder was excluded from Docker builds via
   .dockerignore's '**/dist' rule, so any container that pnpm-installed
   the package found node_modules/@mana/shared-error-tracking but no
   loadable entry point ('Cannot find module' at startup). Match the
   pattern shared-hono uses — point main + types + exports straight at
   src/*.ts. Bun runs TS natively and the type-only consumers don't
   care.

2. Glitchtip projects expose UUID-format public keys (`556fbd2e-a720-…`)
   in their generated DSNs. @sentry/node v9 tightened its DSN regex to
   alphanumeric-only, so it silently rejects the DSN with "Invalid
   Sentry Dsn" and never sends events. Strip the dashes from the
   user/key portion before handing it to Sentry — the Glitchtip ingest
   endpoint accepts both forms over the wire, so no server change.

Plus the missing Dockerfile COPY lines for shared-error-tracking and
eslint-config (root package.json devDeps reference the latter, which
breaks pnpm-filter installs that don't include it in the build context).

Verified end-to-end: 4 issues now in Glitchtip from mana-auth
(2 manual probes + 1 captureException + 1 401 from a
real /api/v1/me/data request without auth).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 02:34:54 +02:00

126 lines
3.4 KiB
TypeScript

/**
* Shared Error Tracking for Mana Apps
*
* Uses Sentry SDK with GlitchTip as the self-hosted backend.
* Compatible with any Sentry-compatible error tracking service.
*
* @example
* ```typescript
* // In instrument.ts (must be imported BEFORE app bootstrap)
* import { initErrorTracking } from '@mana/shared-error-tracking';
*
* initErrorTracking({
* serviceName: 'calendar-backend',
* dsn: process.env.GLITCHTIP_DSN,
* environment: process.env.NODE_ENV,
* release: process.env.APP_VERSION,
* });
* ```
*/
import * as Sentry from '@sentry/node';
export interface ErrorTrackingOptions {
/** Service/app name (e.g. 'calendar-backend', 'contacts-web') */
serviceName: string;
/** GlitchTip/Sentry DSN. If not set, error tracking is disabled. */
dsn?: string;
/** Environment (development, staging, production) */
environment?: string;
/** Release/version string */
release?: string;
/** Sample rate for error events (0.0 to 1.0, default: 1.0) */
sampleRate?: number;
/** Sample rate for performance traces (0.0 to 1.0, default: 0.1) */
tracesSampleRate?: number;
/** Enable debug mode (default: false) */
debug?: boolean;
}
let initialized = false;
/**
* Initialize error tracking. Call this BEFORE bootstrapping your app.
* If no DSN is provided, error tracking is silently disabled.
*/
export function initErrorTracking(options: ErrorTrackingOptions): void {
if (initialized) return;
const rawDsn = options.dsn || process.env.GLITCHTIP_DSN || process.env.SENTRY_DSN;
if (!rawDsn) {
if (options.debug) {
console.log(`[ErrorTracking] No DSN configured for ${options.serviceName} - disabled`);
}
return;
}
// Glitchtip projects use UUID-format public_keys (`556fbd2e-a720-...`)
// but @sentry/node v9's DSN parser only accepts alphanumeric — dashes
// trip "Invalid Sentry Dsn" and silently disable transport. Strip them
// from the user/key portion only; the wire format accepts both.
const dsn = rawDsn.replace(/^(https?:\/\/)([\w-]+)(@.+)$/, (_, proto, key, rest) => {
return proto + key.replace(/-/g, '') + rest;
});
Sentry.init({
dsn,
environment: options.environment || process.env.NODE_ENV || 'development',
release: options.release || process.env.APP_VERSION,
serverName: options.serviceName,
sampleRate: options.sampleRate ?? 1.0,
tracesSampleRate: options.tracesSampleRate ?? 0.1,
debug: options.debug ?? false,
});
initialized = true;
console.log(
`[ErrorTracking] Initialized for ${options.serviceName} (${options.environment || 'development'})`
);
}
/**
* Capture an exception manually
*/
export function captureException(error: unknown, context?: Record<string, unknown>): void {
if (!initialized) return;
Sentry.captureException(error, { extra: context });
}
/**
* Capture a message
*/
export function captureMessage(
message: string,
level: 'fatal' | 'error' | 'warning' | 'info' | 'debug' = 'info'
): void {
if (!initialized) return;
Sentry.captureMessage(message, level);
}
/**
* Set user context for error reports
*/
export function setUser(user: { id: string; email?: string } | null): void {
if (!initialized) return;
Sentry.setUser(user);
}
/**
* Set extra context tags
*/
export function setTag(key: string, value: string): void {
if (!initialized) return;
Sentry.setTag(key, value);
}
/**
* Flush pending events (call before process exit)
*/
export async function flush(timeout = 2000): Promise<void> {
if (!initialized) return;
await Sentry.flush(timeout);
}
export { Sentry };