Files
errors.bitreport.pt/clients/node/errorReporter.mjs
T
Peter Spark a51b3e987a feat(clients): optional project_slug and gitea_repo on ingest context
PHP + Node reporters read ERROR_REPORTING_* env; ingest-api tests run contract on clients/.

Paperclip-Agent: 11179220-3cec-4f0f-880d-2771ff64fce8
Paperclip-Issue: BIT-1310
Paperclip-Run: 35ce1c21-9862-4c60-8b58-441d53b4b3bd
2026-04-07 02:12:55 +00:00

154 lines
5.1 KiB
JavaScript

/**
* BitReport Error Reporter — lightweight Node.js client for errors.bitreport.pt
*
* Zero dependencies (uses native fetch). Drop this file into any Node.js 18+ project.
*
* Usage:
* import { initReporter, reportError, reportMessage } from './errorReporter.mjs';
* initReporter({ token: process.env.ERROR_REPORTING_TOKEN, endpoint: 'https://errors.bitreport.pt' });
* reportError(err, { url: '/api/foo', method: 'POST' });
*
* Environment variables (alternative to initReporter options):
* ERROR_REPORTING_TOKEN — ingest API key (Bearer token)
* ERROR_REPORTING_ENDPOINT — base URL (default: https://errors.bitreport.pt)
* ERROR_REPORTING_DISABLED — set to "1" to disable
* ERROR_REPORTING_PROJECT_NAME — display name in ingest context (optional)
* ERROR_REPORTING_PROJECT_SLUG — stable product slug (optional)
* ERROR_REPORTING_GITEA_REPO — canonical owner/repo on Gitea (optional)
*/
let _token = '';
let _endpoint = 'https://errors.bitreport.pt';
let _disabled = false;
let _projectName = process.env.ERROR_REPORTING_PROJECT_NAME || '';
let _projectSlug = process.env.ERROR_REPORTING_PROJECT_SLUG || '';
let _giteaRepo = process.env.ERROR_REPORTING_GITEA_REPO || '';
const _queue = [];
let _flushTimer = null;
const BATCH_SIZE = 25;
const FLUSH_MS = 5000;
const TIMEOUT_MS = 8000;
/**
* Initialise the reporter. Call once at startup.
* @param {{ token?: string, endpoint?: string, disabled?: boolean, projectName?: string, projectSlug?: string, giteaRepo?: string }} opts
*/
export function initReporter(opts = {}) {
_token = opts.token || process.env.ERROR_REPORTING_TOKEN || '';
_endpoint = (opts.endpoint || process.env.ERROR_REPORTING_ENDPOINT || 'https://errors.bitreport.pt').replace(/\/$/, '');
_disabled = opts.disabled ?? process.env.ERROR_REPORTING_DISABLED === '1';
_projectName = opts.projectName || process.env.ERROR_REPORTING_PROJECT_NAME || _projectName;
_projectSlug = opts.projectSlug || process.env.ERROR_REPORTING_PROJECT_SLUG || _projectSlug;
_giteaRepo = opts.giteaRepo || process.env.ERROR_REPORTING_GITEA_REPO || _giteaRepo;
if (!_disabled && _token) {
process.on('uncaughtException', (err) => {
reportError(err, { uncaught: true });
// Re-throw after reporting so the process still crashes
setTimeout(() => { throw err; }, 200);
});
process.on('unhandledRejection', (reason) => {
const err = reason instanceof Error ? reason : new Error(String(reason));
reportError(err, { unhandledRejection: true });
});
}
}
/**
* Report an Error object.
* @param {Error} err
* @param {Record<string, unknown>} [context]
*/
export function reportError(err, context = {}) {
if (_disabled || !_token) return;
const msg = err?.message || String(err);
const stack = err?.stack || '';
const fileMatch = stack.match(/at\s+.+?\((.+?):(\d+):\d+\)|at\s+(.+?):(\d+):\d+/);
const filePath = fileMatch?.[1] || fileMatch?.[3] || '';
const lineNumber = parseInt(fileMatch?.[2] || fileMatch?.[4] || '0', 10);
_enqueue({
schema_version: 1,
occurred_at: new Date().toISOString(),
level: 'error',
message: msg,
stacktrace: stack,
context: {
file_path: filePath,
line_number: lineNumber || undefined,
error_type: err?.constructor?.name || 'Error',
error_code: err?.code || undefined,
project_name: _projectName || undefined,
project_slug: _projectSlug || undefined,
gitea_repo: _giteaRepo || undefined,
...context,
},
});
}
/**
* Report a plain message (warning, info, etc.).
* @param {string} message
* @param {'error'|'warning'|'info'|'critical'} [level]
* @param {Record<string, unknown>} [context]
*/
export function reportMessage(message, level = 'error', context = {}) {
if (_disabled || !_token) return;
_enqueue({
schema_version: 1,
occurred_at: new Date().toISOString(),
level,
message,
context: {
project_name: _projectName || undefined,
project_slug: _projectSlug || undefined,
gitea_repo: _giteaRepo || undefined,
...context,
},
});
}
/**
* Flush queued events immediately. Call before process exit.
* @returns {Promise<void>}
*/
export async function flush() {
if (_flushTimer) { clearTimeout(_flushTimer); _flushTimer = null; }
while (_queue.length > 0) {
const batch = _queue.splice(0, BATCH_SIZE);
await _send(batch);
}
}
// --- internals ---
function _enqueue(event) {
_queue.push(event);
if (_queue.length >= BATCH_SIZE) {
flush().catch(() => {});
} else if (!_flushTimer) {
_flushTimer = setTimeout(() => { _flushTimer = null; flush().catch(() => {}); }, FLUSH_MS);
if (_flushTimer.unref) _flushTimer.unref();
}
}
async function _send(events) {
if (!events.length) return;
try {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), TIMEOUT_MS);
await fetch(`${_endpoint}/v1/ingest/events`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${_token}`,
},
body: JSON.stringify({ events }),
signal: ctrl.signal,
});
clearTimeout(timer);
} catch {
// Fire-and-forget: never crash the host app
}
}