@xovris/node 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ /** The wizard's own variables from `<dir>/.env`, set where the process lacks them; returns the names it set. */
2
+ export declare function wizardEnv(dir?: string, env?: NodeJS.ProcessEnv): string[];
@@ -0,0 +1,26 @@
1
+ // D01.01.06.01 (the clean room's first Express run, 13 Nov 2026: the wizard wrote its address and key to the project's .env, the app was
2
+ // started as `npm start` starts it, and no event ever left it - nothing in a Node app reads a .env by itself): Xovris reads its OWN
3
+ // variables from the project's .env when the process was not given them, as the Go and Python setups read theirs. Only XOVRIS_
4
+ // variables are taken, never one the process already has, and nothing else of the file is loaded - the app's own environment is
5
+ // exactly as it was.
6
+ import { readFileSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+ import { parseEnv } from 'node:util';
9
+ /** The wizard's own variables from `<dir>/.env`, set where the process lacks them; returns the names it set. */
10
+ export function wizardEnv(dir = process.cwd(), env = process.env) {
11
+ let text;
12
+ try {
13
+ text = readFileSync(join(dir, '.env'), 'utf8');
14
+ }
15
+ catch {
16
+ return [];
17
+ }
18
+ const set = [];
19
+ for (const [k, v] of Object.entries(parseEnv(text))) {
20
+ if (!k.startsWith('XOVRIS_') || env[k] !== undefined)
21
+ continue;
22
+ env[k] = v;
23
+ set.push(k);
24
+ }
25
+ return set;
26
+ }
@@ -0,0 +1,16 @@
1
+ import { type Client, type Send } from '@xovris/core';
2
+ export interface NodeOptions {
3
+ url?: string | undefined;
4
+ key?: string | undefined;
5
+ release?: string | undefined;
6
+ environment?: string | undefined;
7
+ send?: Send;
8
+ }
9
+ export declare function init(o?: NodeOptions, proc?: NodeJS.Process): Client;
10
+ export declare function installProcessHandlers(c: Client, proc?: NodeJS.Process): void;
11
+ export declare function captureException(err: unknown, o?: Parameters<Client['captureException']>[1]): string | null;
12
+ /** Sends every pending error and finished span; resolves false if errors were still in flight at the timeout. */
13
+ export declare function flush(timeoutMs?: number): Promise<boolean>;
14
+ /** Tests only: forget the process-wide client. */
15
+ export declare function resetForTests(): void;
16
+ export { startTracing, tracingState, xovrisSpanProcessor, type TracingState } from './otel.ts';
package/dist/index.js ADDED
@@ -0,0 +1,80 @@
1
+ // @xovris/node (ADR 0011): errors from a Node.js server sent to Xovris, configured from the two variables the wizard
2
+ // writes. Process handlers keep Node's own behaviour: an uncaught error or rejection still ends the process (after the
3
+ // event is flushed) unless the app has its own handler - Xovris observes, it never changes how the app fails.
4
+ // The client is process-wide, shared by every copy of this package, so loading Xovris twice never sends twice.
5
+ import { createClient, environmentFrom } from '@xovris/core';
6
+ import { wizardEnv } from './env-file.js';
7
+ import { releaseOf } from './release.js';
8
+ import { activeTraceContext, flushTraces, withoutTracing } from './otel.js';
9
+ import { captureServerErrors } from './server-errors.js';
10
+ const SHARED = Symbol.for('xovris.node.v1');
11
+ function shared() {
12
+ const g = globalThis;
13
+ return (g[SHARED] ??= { client: null, handlers: new WeakSet() });
14
+ }
15
+ const fetchSend = (url, init) => withoutTracing(() => fetch(url, init)).then((r) => {
16
+ const ra = Number(r.headers.get('retry-after'));
17
+ return { status: r.status, ...(Number.isFinite(ra) && ra > 0 ? { retryAfterSeconds: ra } : {}) };
18
+ });
19
+ // the edge runtime's process has no working directory: its events carry only the release the host names
20
+ const cwdOf = (proc) => { try {
21
+ return typeof proc.cwd === 'function' ? proc.cwd() : undefined;
22
+ }
23
+ catch {
24
+ return undefined;
25
+ } };
26
+ export function init(o = {}, proc = process) {
27
+ const s = shared();
28
+ if (s.client)
29
+ return s.client;
30
+ // An app whose run reads no .env (SvelteKit 3's preview and built server, a built Nuxt server - the clean room, 14 Nov: the server half
31
+ // sent nothing) gets Xovris's own two variables from the .env the wizard wrote, never another line of it nor over one it was given.
32
+ if ((!(o.url || proc.env.XOVRIS_INGEST_URL) || !(o.key || proc.env.XOVRIS_INGEST_KEY)) && typeof proc.cwd === 'function')
33
+ wizardEnv(proc.cwd(), proc.env);
34
+ const client = createClient({
35
+ url: o.url || proc.env.XOVRIS_INGEST_URL, key: o.key || proc.env.XOVRIS_INGEST_KEY,
36
+ release: o.release ?? releaseOf(proc.env, cwdOf(proc)), environment: o.environment ?? environmentFrom(proc.env), platform: 'node',
37
+ send: o.send ?? fetchSend, traceContext: activeTraceContext,
38
+ });
39
+ s.client = client;
40
+ // The edge runtime has no process events; there the client reports what it is handed and nothing more.
41
+ if (client.enabled && typeof proc?.on === 'function') {
42
+ installProcessHandlers(client, proc);
43
+ s.stopServerErrors = captureServerErrors(client);
44
+ }
45
+ return client;
46
+ }
47
+ export function installProcessHandlers(c, proc = process) {
48
+ // One set of handlers per process object, whoever calls this.
49
+ const s = shared();
50
+ if (s.handlers.has(proc))
51
+ return;
52
+ s.handlers.add(proc);
53
+ proc.on('uncaughtException', (err) => {
54
+ c.captureException(err, { handled: false, mechanism: 'onuncaughtexception', level: 'fatal' });
55
+ if (proc.listenerCount('uncaughtException') <= 1) {
56
+ console.error(err);
57
+ void Promise.all([c.flush(2000), flushTraces()]).finally(() => proc.exit(1));
58
+ }
59
+ });
60
+ proc.on('unhandledRejection', (reason) => {
61
+ c.captureException(reason, { handled: false, mechanism: 'onunhandledrejection' });
62
+ // Node's default for an unhandled rejection is to crash; adding a listener would silently stop that, so keep it.
63
+ if (proc.listenerCount('unhandledRejection') <= 1) {
64
+ console.error(reason);
65
+ void Promise.all([c.flush(2000), flushTraces()]).finally(() => proc.exit(1));
66
+ }
67
+ });
68
+ }
69
+ export function captureException(err, o) {
70
+ return init().captureException(err, o);
71
+ }
72
+ /** Sends every pending error and finished span; resolves false if errors were still in flight at the timeout. */
73
+ export async function flush(timeoutMs) {
74
+ const c = shared().client;
75
+ const [ok] = await Promise.all([c ? c.flush(timeoutMs) : Promise.resolve(true), flushTraces()]);
76
+ return ok;
77
+ }
78
+ /** Tests only: forget the process-wide client. */
79
+ export function resetForTests() { const s = shared(); s.stopServerErrors?.(); s.stopServerErrors = undefined; s.client = null; s.handlers = new WeakSet(); }
80
+ export { startTracing, tracingState, xovrisSpanProcessor } from './otel.js';
package/dist/otel.d.ts ADDED
@@ -0,0 +1,109 @@
1
+ import { type Context } from '@opentelemetry/api';
2
+ import { defaultResource } from '@opentelemetry/resources';
3
+ import { type ReadableSpan, type Span, type SpanExporter, type SpanProcessor } from '@opentelemetry/sdk-trace-base';
4
+ type Env = Record<string, string | undefined>;
5
+ export interface TraceOptions {
6
+ url?: string | undefined;
7
+ key?: string | undefined;
8
+ /** Where this processor was added, named in the duplicate warning ("registerOTel in instrumentation.ts"). */
9
+ source?: string;
10
+ env?: Env;
11
+ /** Tests and custom pipelines: export somewhere other than Xovris's OTLP endpoint. */
12
+ exporter?: SpanExporter;
13
+ warn?: (message: string) => void;
14
+ }
15
+ export type TracingState = {
16
+ mode: 'own';
17
+ source: string;
18
+ } | {
19
+ mode: 'adopted';
20
+ via: 'configuration' | 'runtime' | 'environment' | 'sentry';
21
+ source: string;
22
+ } | {
23
+ mode: 'stood_down';
24
+ reason: string;
25
+ next: string;
26
+ } | {
27
+ mode: 'off';
28
+ reason: string;
29
+ };
30
+ /** True when the app's own OTLP exporter variables already point at the Xovris ingest host - adding Xovris again
31
+ * would send every span twice. */
32
+ export declare function envExportsToXovris(env: Env, ingestUrl: string | undefined): boolean;
33
+ /** One more span processor for an existing OpenTelemetry setup: batches spans to Xovris's OTLP endpoint with the
34
+ * ingestion key in a header (never the URL). Two of them on one provider send each span once, and say so. */
35
+ export declare class XovrisSpanProcessor implements SpanProcessor {
36
+ readonly source: string;
37
+ readonly enabled: boolean;
38
+ readonly reason: string | null;
39
+ private readonly inner;
40
+ private readonly warn;
41
+ constructor(o?: TraceOptions);
42
+ onStart(span: Span, parentContext: Context): void;
43
+ onEnd(span: ReadableSpan): void;
44
+ forceFlush(): Promise<void>;
45
+ shutdown(): Promise<void>;
46
+ }
47
+ /** The processor the wizard writes into an existing setup: `spanProcessors: ['auto', xovrisSpanProcessor()]`. */
48
+ export declare function xovrisSpanProcessor(o?: TraceOptions): XovrisSpanProcessor;
49
+ /** NodeSDK configured with a `traceExporter` only: the wizard keeps that exporter exactly and adds Xovris beside it. */
50
+ export declare function batchFor(exporter: SpanExporter): SpanProcessor;
51
+ interface LiveProvider {
52
+ constructor?: {
53
+ name?: string;
54
+ };
55
+ addSpanProcessor?: (p: SpanProcessor) => void;
56
+ _activeSpanProcessor?: {
57
+ _spanProcessors?: SpanProcessor[];
58
+ };
59
+ }
60
+ export declare function liveTracerProvider(): LiveProvider | null;
61
+ /** Joins a provider that is already running: the SDK 1.x public method, or the SDK 2.x processor list (the 2.x
62
+ * provider takes processors only in its constructor). Returns false when the provider has neither - it is not an
63
+ * OpenTelemetry SDK provider (Sentry's own, for one), so Xovris stands down rather than start a rival. */
64
+ export declare function joinLiveProvider(provider: LiveProvider, p: SpanProcessor): boolean;
65
+ /** Sentry's client as the app runs it, read from Sentry's own global carrier (version 8 and later) - Xovris never imports Sentry. */
66
+ export interface SentryClientLike {
67
+ on: (hook: 'spanEnd', cb: (span: unknown) => void) => unknown;
68
+ }
69
+ export declare function liveSentryClient(): SentryClientLike | null;
70
+ /** A finished Sentry span as Sentry itself writes it (spanToJSON / getSpanJSON). */
71
+ export interface SentrySpanJson {
72
+ name?: string;
73
+ description?: string;
74
+ op?: string;
75
+ span_id: string;
76
+ trace_id: string;
77
+ parent_span_id?: string;
78
+ start_timestamp: number;
79
+ timestamp?: number;
80
+ end_timestamp?: number;
81
+ status?: string;
82
+ data?: Record<string, unknown>;
83
+ attributes?: Record<string, unknown>;
84
+ }
85
+ /** One Sentry span as the OpenTelemetry span the OTLP exporter sends: the same trace and span ids, parent, times, status and attributes. */
86
+ export declare function sentrySpanToReadable(j: SentrySpanJson, resource: ReturnType<typeof defaultResource>): ReadableSpan;
87
+ /** G105.01.C191 (#248): Sentry stays the app's tracer and keeps its spans; Xovris reads each one as it ends (the client's own spanEnd
88
+ * hook, Sentry 8 and later) and sends it over OTLP - nothing to change in the app, no second SDK. Once per process. */
89
+ export declare function rideSentry(client: SentryClientLike, o: TraceOptions, resource: ReturnType<typeof defaultResource>): boolean;
90
+ /** Decides, once per process, how this app's traces reach Xovris. Never registers a provider when one is live. */
91
+ export declare function decideTracing(o?: TraceOptions): TracingState;
92
+ /** Starts tracing after the code that loaded Xovris has finished its own start-up, so a setup registered on the same
93
+ * start-up path (registerOTel after this import, a NodeSDK started next) always wins and Xovris joins it. */
94
+ export declare function startTracing(o?: TraceOptions & {
95
+ defer?: boolean;
96
+ }): Promise<TracingState>;
97
+ export declare function tracingState(): TracingState | null;
98
+ /** Sends every finished span now (before a serverless function freezes, or at shutdown). */
99
+ export declare function flushTraces(): Promise<void>;
100
+ /** The active span, so an error event names the trace it happened in. */
101
+ export declare function activeTraceContext(): {
102
+ trace_id: string;
103
+ span_id: string;
104
+ } | undefined;
105
+ /** Runs Xovris's own network calls with tracing suppressed, so sending an error never creates a span to send. */
106
+ export declare function withoutTracing<T>(work: () => T): T;
107
+ /** Tests only: forget the process-wide decision and any provider Xovris registered. */
108
+ export declare function resetTracingForTests(): Promise<void>;
109
+ export {};
package/dist/otel.js ADDED
@@ -0,0 +1,263 @@
1
+ // @xovris/node/otel (D01.02.01): traces reach Xovris over OTLP without ever starting a second tracing SDK. If the app
2
+ // already runs OpenTelemetry (@vercel/otel, NodeSDK, its own provider), Xovris joins it as one more span processor -
3
+ // written into that setup by the wizard as a reviewable change, or joined at start-up - and only when nothing is
4
+ // running does Xovris register a provider of its own. Every span is sent once, however many times Xovris is added.
5
+ import { SpanKind, SpanStatusCode, TraceFlags, context, diag, trace } from '@opentelemetry/api';
6
+ import { suppressTracing } from '@opentelemetry/core';
7
+ import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
8
+ import { defaultResource, resourceFromAttributes } from '@opentelemetry/resources';
9
+ import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';
10
+ import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
11
+ import { ERRORS_VIA_ENVELOPE, environmentFrom, otlpTracesUrl, projectIdFrom } from '@xovris/core';
12
+ import { releaseOf } from './release.js';
13
+ const REGISTRY = Symbol.for('xovris.otel.v1');
14
+ function registry() {
15
+ const g = globalThis;
16
+ return (g[REGISTRY] ??= { processors: [], claimed: new WeakSet(), state: null, warned: new Set(), own: null });
17
+ }
18
+ const defaultWarn = (m) => console.warn(`[xovris] ${m}`);
19
+ function warnOnce(key, message, warn = defaultWarn) {
20
+ const r = registry();
21
+ if (r.warned.has(key))
22
+ return;
23
+ r.warned.add(key);
24
+ warn(message);
25
+ }
26
+ /** True when the app's own OTLP exporter variables already point at the Xovris ingest host - adding Xovris again
27
+ * would send every span twice. */
28
+ export function envExportsToXovris(env, ingestUrl) {
29
+ if (!ingestUrl)
30
+ return false;
31
+ const target = env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT ?? env.OTEL_EXPORTER_OTLP_ENDPOINT;
32
+ if (!target)
33
+ return false;
34
+ try {
35
+ return new URL(target).host === new URL(ingestUrl).host;
36
+ }
37
+ catch {
38
+ return false;
39
+ }
40
+ }
41
+ /** One more span processor for an existing OpenTelemetry setup: batches spans to Xovris's OTLP endpoint with the
42
+ * ingestion key in a header (never the URL). Two of them on one provider send each span once, and say so. */
43
+ export class XovrisSpanProcessor {
44
+ source;
45
+ enabled;
46
+ reason;
47
+ inner;
48
+ warn;
49
+ constructor(o = {}) {
50
+ const env = o.env ?? process.env;
51
+ const url = o.url ?? env.XOVRIS_INGEST_URL;
52
+ const key = o.key ?? env.XOVRIS_INGEST_KEY;
53
+ const endpoint = url ? otlpTracesUrl(url) : null;
54
+ this.source = o.source ?? 'your OpenTelemetry setup';
55
+ this.warn = o.warn ?? defaultWarn;
56
+ if (!endpoint || !key) {
57
+ this.inner = null;
58
+ this.reason = 'No ingest address or key is set, so traces are not sent. Run the wizard: it writes both.';
59
+ }
60
+ else if (envExportsToXovris(env, url)) {
61
+ this.inner = null;
62
+ this.reason = 'Your OpenTelemetry exporter variables already send traces to Xovris, so this processor stays idle and each span arrives once.';
63
+ warnOnce('env-duplicate', this.reason, this.warn);
64
+ }
65
+ else {
66
+ this.reason = null;
67
+ this.inner = new BatchSpanProcessor(o.exporter ?? new OTLPTraceExporter({ url: endpoint, headers: { 'x-xovris-key': key, ...ERRORS_VIA_ENVELOPE }, timeoutMillis: 10_000 }));
68
+ }
69
+ this.enabled = this.inner !== null;
70
+ registry().processors.push(this);
71
+ }
72
+ onStart(span, parentContext) { this.inner?.onStart(span, parentContext); }
73
+ onEnd(span) {
74
+ if (!this.inner)
75
+ return;
76
+ const r = registry();
77
+ if (r.claimed.has(span)) {
78
+ const first = r.processors.find((p) => p.enabled && p !== this);
79
+ warnOnce('processor-duplicate', `Xovris is added to this app's OpenTelemetry setup twice (${first?.source ?? 'another place'} and ${this.source}). Each span is sent once; remove one of them - npx xovris remove undoes the one the wizard added.`, this.warn);
80
+ return;
81
+ }
82
+ r.claimed.add(span);
83
+ this.inner.onEnd(span);
84
+ }
85
+ forceFlush() { return this.inner?.forceFlush() ?? Promise.resolve(); }
86
+ shutdown() { return this.inner?.shutdown() ?? Promise.resolve(); }
87
+ }
88
+ /** The processor the wizard writes into an existing setup: `spanProcessors: ['auto', xovrisSpanProcessor()]`. */
89
+ export function xovrisSpanProcessor(o = {}) {
90
+ return new XovrisSpanProcessor(o);
91
+ }
92
+ /** NodeSDK configured with a `traceExporter` only: the wizard keeps that exporter exactly and adds Xovris beside it. */
93
+ export function batchFor(exporter) {
94
+ return new BatchSpanProcessor(exporter);
95
+ }
96
+ // The API keeps one registry per major version on the global object, shared by every copy of @opentelemetry/api in the
97
+ // process - the only reliable way to ask "is a tracer provider already registered?" across bundled copies.
98
+ const OTEL_API_GLOBAL = Symbol.for('opentelemetry.js.api.1');
99
+ export function liveTracerProvider() {
100
+ const api = globalThis[OTEL_API_GLOBAL];
101
+ if (!api?.trace)
102
+ return null;
103
+ const p = api.trace;
104
+ return (typeof p.getDelegate === 'function' ? p.getDelegate() : p);
105
+ }
106
+ /** Joins a provider that is already running: the SDK 1.x public method, or the SDK 2.x processor list (the 2.x
107
+ * provider takes processors only in its constructor). Returns false when the provider has neither - it is not an
108
+ * OpenTelemetry SDK provider (Sentry's own, for one), so Xovris stands down rather than start a rival. */
109
+ export function joinLiveProvider(provider, p) {
110
+ if (typeof provider.addSpanProcessor === 'function') {
111
+ provider.addSpanProcessor(p);
112
+ return true;
113
+ }
114
+ const list = provider._activeSpanProcessor?._spanProcessors;
115
+ if (Array.isArray(list)) {
116
+ list.push(p);
117
+ return true;
118
+ }
119
+ return false;
120
+ }
121
+ export function liveSentryClient() {
122
+ const carrier = globalThis.__SENTRY__;
123
+ if (!carrier)
124
+ return null;
125
+ const box = (typeof carrier.version === 'string' ? carrier[carrier.version] : carrier);
126
+ const scope = (box?.defaultCurrentScope ?? box?.stack?.getStackTop?.()?.scope);
127
+ const client = scope?.getClient?.();
128
+ return client && typeof client.on === 'function' ? client : null;
129
+ }
130
+ const SENTRY_KIND = { 'http.server': SpanKind.SERVER, 'http.client': SpanKind.CLIENT, 'queue.publish': SpanKind.PRODUCER, 'queue.process': SpanKind.CONSUMER };
131
+ const hrOf = (sec) => { const whole = Math.floor(sec); return [whole, Math.round((sec - whole) * 1e9)]; };
132
+ const plainAttrs = (o) => Object.fromEntries(Object.entries(o ?? {}).filter(([, v]) => ['string', 'number', 'boolean'].includes(typeof v) || (Array.isArray(v) && v.every((x) => ['string', 'number', 'boolean'].includes(typeof x)))));
133
+ /** One Sentry span as the OpenTelemetry span the OTLP exporter sends: the same trace and span ids, parent, times, status and attributes. */
134
+ export function sentrySpanToReadable(j, resource) {
135
+ const end = j.end_timestamp ?? j.timestamp ?? j.start_timestamp;
136
+ const ctx = { traceId: j.trace_id, spanId: j.span_id, traceFlags: TraceFlags.SAMPLED };
137
+ const parent = j.parent_span_id ? { traceId: j.trace_id, spanId: j.parent_span_id, traceFlags: TraceFlags.SAMPLED } : undefined;
138
+ const op = j.op ?? (typeof j.attributes?.['sentry.op'] === 'string' ? j.attributes['sentry.op'] : undefined);
139
+ const ms = Math.max(0, end - j.start_timestamp);
140
+ return {
141
+ name: j.description ?? j.name ?? op ?? 'span', kind: (op && SENTRY_KIND[op]) ?? SpanKind.INTERNAL, spanContext: () => ctx, parentSpanContext: parent, parentSpanId: parent?.spanId,
142
+ startTime: hrOf(j.start_timestamp), endTime: hrOf(end), duration: hrOf(ms), ended: true,
143
+ status: { code: !j.status || j.status === 'ok' ? SpanStatusCode.UNSET : SpanStatusCode.ERROR, ...(j.status && j.status !== 'ok' ? { message: j.status } : {}) },
144
+ attributes: { ...plainAttrs(j.data), ...plainAttrs(j.attributes), ...(op ? { 'sentry.op': op } : {}) }, links: [], events: [], resource,
145
+ instrumentationScope: { name: '@xovris/node (Sentry spans)' }, instrumentationLibrary: { name: '@xovris/node (Sentry spans)' }, droppedAttributesCount: 0, droppedEventsCount: 0, droppedLinksCount: 0,
146
+ };
147
+ }
148
+ function resourceOf(env, url) {
149
+ const release = releaseOf(env, typeof process.cwd === 'function' ? process.cwd() : undefined);
150
+ const environment = environmentFrom(env);
151
+ const projectId = projectIdFrom(url);
152
+ return defaultResource().merge(resourceFromAttributes({
153
+ 'service.name': env.OTEL_SERVICE_NAME ?? env.npm_package_name ?? 'app',
154
+ ...(release ? { 'service.version': release } : {}),
155
+ ...(environment ? { 'deployment.environment.name': environment } : {}),
156
+ ...(projectId ? { 'xovris.project_id': projectId } : {}),
157
+ }));
158
+ }
159
+ /** G105.01.C191 (#248): Sentry stays the app's tracer and keeps its spans; Xovris reads each one as it ends (the client's own spanEnd
160
+ * hook, Sentry 8 and later) and sends it over OTLP - nothing to change in the app, no second SDK. Once per process. */
161
+ export function rideSentry(client, o, resource) {
162
+ const r = registry();
163
+ if (r.sentry)
164
+ return true;
165
+ const p = new XovrisSpanProcessor({ ...o, source: "Sentry's own spans" });
166
+ if (!p.enabled)
167
+ return false;
168
+ client.on('spanEnd', (span) => {
169
+ const j = span.getSpanJSON?.();
170
+ if (j?.trace_id && j.span_id && typeof j.start_timestamp === 'number')
171
+ p.onEnd(sentrySpanToReadable(j, resource));
172
+ });
173
+ r.sentry = true;
174
+ return true;
175
+ }
176
+ /** Decides, once per process, how this app's traces reach Xovris. Never registers a provider when one is live. */
177
+ export function decideTracing(o = {}) {
178
+ const r = registry();
179
+ if (r.state)
180
+ return r.state;
181
+ const env = o.env ?? process.env;
182
+ const url = o.url ?? env.XOVRIS_INGEST_URL;
183
+ const key = o.key ?? env.XOVRIS_INGEST_KEY;
184
+ const set = (s) => (r.state = s);
185
+ if ((env.XOVRIS_TRACES ?? '').toLowerCase() === 'off')
186
+ return set({ mode: 'off', reason: 'XOVRIS_TRACES=off is set, so only errors are sent.' }); // own setting: the customer's SDK variable
187
+ if (!url || !key || !otlpTracesUrl(url))
188
+ return set({ mode: 'off', reason: 'No ingest address or key is set, so traces are not sent. Run the wizard: it writes both.' });
189
+ if (envExportsToXovris(env, url))
190
+ return set({ mode: 'adopted', via: 'environment', source: 'OTEL_EXPORTER_OTLP_ENDPOINT' });
191
+ const live = liveTracerProvider();
192
+ if (live) {
193
+ const configured = r.processors.find((p) => p.enabled);
194
+ if (configured)
195
+ return set({ mode: 'adopted', via: 'configuration', source: configured.source });
196
+ if (joinLiveProvider(live, new XovrisSpanProcessor({ ...o, source: 'joined at start-up' })))
197
+ return set({ mode: 'adopted', via: 'runtime', source: 'joined at start-up' });
198
+ const sentry = /sentry/i.test(live.constructor?.name ?? '');
199
+ const client = liveSentryClient();
200
+ if (client && rideSentry(client, o, resourceOf(env, url)))
201
+ return set({ mode: 'adopted', via: 'sentry', source: "Sentry's own spans, read as each one ends" });
202
+ const state = sentry
203
+ ? { mode: 'stood_down', reason: "Sentry's SDK is this app's tracer, and this version (before 8) lets nothing else read its spans.", next: 'Errors still reach Xovris. npx xovris init brings the traces too - Xovris writes the change to point your Sentry DSN at Xovris, and no second SDK is installed. Do it yourself instead: upgrade Sentry to version 8 or later and Xovris reads its spans by itself.' }
204
+ : { mode: 'stood_down', reason: `Another tracer (${live.constructor?.name ?? 'unknown'}) is already running and does not accept another processor.`, next: 'Errors still reach Xovris. Run npx xovris init in this project to add Xovris to that tracer as a reviewable change.' };
205
+ warnOnce('stood-down', `${state.reason} ${state.next}`, o.warn);
206
+ return set(state);
207
+ }
208
+ const release = releaseOf(env, typeof process.cwd === 'function' ? process.cwd() : undefined);
209
+ const environment = environmentFrom(env);
210
+ const projectId = projectIdFrom(url);
211
+ const provider = new NodeTracerProvider({
212
+ resource: defaultResource().merge(resourceFromAttributes({
213
+ 'service.name': env.OTEL_SERVICE_NAME ?? env.npm_package_name ?? 'app',
214
+ ...(release ? { 'service.version': release } : {}),
215
+ ...(environment ? { 'deployment.environment.name': environment } : {}),
216
+ ...(projectId ? { 'xovris.project_id': projectId } : {}),
217
+ })),
218
+ spanProcessors: [new XovrisSpanProcessor({ ...o, source: 'Xovris (no other tracer was running)' })],
219
+ });
220
+ provider.register();
221
+ r.own = provider;
222
+ // Sentry 10+ traces without OpenTelemetry: its spans are read too, so the app's own instrumentation reaches Xovris as well
223
+ const sentryClient = liveSentryClient();
224
+ if (sentryClient && rideSentry(sentryClient, o, resourceOf(env, url)))
225
+ return set({ mode: 'own', source: "Xovris (no other tracer was running), with Sentry's own spans read as each one ends" });
226
+ return set({ mode: 'own', source: 'Xovris (no other tracer was running)' });
227
+ }
228
+ /** Starts tracing after the code that loaded Xovris has finished its own start-up, so a setup registered on the same
229
+ * start-up path (registerOTel after this import, a NodeSDK started next) always wins and Xovris joins it. */
230
+ export function startTracing(o = {}) {
231
+ if (o.defer === false)
232
+ return Promise.resolve(decideTracing(o));
233
+ return new Promise((resolve) => setImmediate(() => resolve(decideTracing(o))));
234
+ }
235
+ export function tracingState() { return registry().state; }
236
+ /** Sends every finished span now (before a serverless function freezes, or at shutdown). */
237
+ export async function flushTraces() {
238
+ await Promise.all(registry().processors.map((p) => p.forceFlush().catch(() => undefined)));
239
+ }
240
+ /** The active span, so an error event names the trace it happened in. */
241
+ export function activeTraceContext() {
242
+ const c = trace.getActiveSpan()?.spanContext();
243
+ return c && /^[0-9a-f]{32}$/.test(c.traceId) && !/^0+$/.test(c.traceId) ? { trace_id: c.traceId, span_id: c.spanId } : undefined;
244
+ }
245
+ /** Runs Xovris's own network calls with tracing suppressed, so sending an error never creates a span to send. */
246
+ export function withoutTracing(work) {
247
+ return context.with(suppressTracing(context.active()), work);
248
+ }
249
+ /** Tests only: forget the process-wide decision and any provider Xovris registered. */
250
+ export async function resetTracingForTests() {
251
+ const r = registry();
252
+ const own = r.own;
253
+ r.processors.length = 0;
254
+ r.claimed = new WeakSet();
255
+ r.state = null;
256
+ r.warned.clear();
257
+ r.own = null;
258
+ if (own)
259
+ await own.shutdown().catch(() => undefined);
260
+ trace.disable();
261
+ context.disable();
262
+ diag.disable();
263
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,9 @@
1
+ // Loaded first (node --import / --require, or Next.js's register()): starts Xovris from the wizard's variables - errors
2
+ // at once, traces after this start-up step so an OpenTelemetry setup registered next is joined, never replaced. The variables
3
+ // come from the process, else from the .env the wizard wrote (env-file.ts) - a Node app reads no .env by itself.
4
+ import { wizardEnv } from './env-file.js';
5
+ import { init } from './index.js';
6
+ import { startTracing } from './otel.js';
7
+ wizardEnv();
8
+ init();
9
+ void startTracing();
@@ -0,0 +1,5 @@
1
+ /** The commit the code at `dir` is checked out at, from the nearest .git above it (a worktree's or submodule's gitdir file, a loose or a
2
+ * packed ref, a detached head); undefined where there is none or it names no commit yet. */
3
+ export declare function gitCommitAt(dir: string): string | undefined;
4
+ /** The release a Node app's events carry: what it or its host says, else the commit of the code it runs from. */
5
+ export declare function releaseOf(env: Record<string, string | undefined>, cwd: string | undefined): string | undefined;
@@ -0,0 +1,72 @@
1
+ // D01.03 (the open setup race, 14 Nov: the wizard waited 15 minutes for a first real event that had already arrived, because it carried no
2
+ // release): a Node app's events name the code they came from on any host. The explicit XOVRIS_RELEASE first, then what the host already says
3
+ // (releaseFrom), then the code itself - the commit its own .git names - so an app run from a clone, a container built with its history or a
4
+ // person's own machine is never release-less. Read once, synchronously, never a process spawned and never a network call.
5
+ import { existsSync, readFileSync, statSync } from 'node:fs';
6
+ import { dirname, join, resolve } from 'node:path';
7
+ import { releaseFrom } from '@xovris/core';
8
+ const SHA = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/i;
9
+ /** The commit the code at `dir` is checked out at, from the nearest .git above it (a worktree's or submodule's gitdir file, a loose or a
10
+ * packed ref, a detached head); undefined where there is none or it names no commit yet. */
11
+ export function gitCommitAt(dir) {
12
+ try {
13
+ for (let d = resolve(dir);;) {
14
+ const dot = join(d, '.git');
15
+ if (existsSync(dot))
16
+ return commitOf(dot, d);
17
+ const up = dirname(d);
18
+ if (up === d)
19
+ return undefined;
20
+ d = up;
21
+ }
22
+ }
23
+ catch {
24
+ // a runtime with no file system (the edge) names no release from git
25
+ return undefined;
26
+ }
27
+ }
28
+ function commitOf(dot, top) {
29
+ try {
30
+ let git = dot;
31
+ if (statSync(dot).isFile()) {
32
+ const to = /^gitdir:\s*(.+)$/m.exec(readFileSync(dot, 'utf8'))?.[1]?.trim();
33
+ if (!to)
34
+ return undefined;
35
+ git = resolve(top, to);
36
+ }
37
+ const head = readFileSync(join(git, 'HEAD'), 'utf8').trim();
38
+ if (SHA.test(head))
39
+ return head.toLowerCase();
40
+ const ref = /^ref:\s*(\S+)$/.exec(head)?.[1];
41
+ if (!ref)
42
+ return undefined;
43
+ // a linked worktree keeps its HEAD here and its branches in the common directory it names
44
+ const common = existsSync(join(git, 'commondir')) ? resolve(git, readFileSync(join(git, 'commondir'), 'utf8').trim()) : git;
45
+ for (const base of [git, common]) {
46
+ const loose = join(base, ref);
47
+ if (existsSync(loose)) {
48
+ const s = readFileSync(loose, 'utf8').trim();
49
+ if (SHA.test(s))
50
+ return s.toLowerCase();
51
+ }
52
+ }
53
+ for (const base of [git, common]) {
54
+ const packed = join(base, 'packed-refs');
55
+ if (!existsSync(packed))
56
+ continue;
57
+ for (const line of readFileSync(packed, 'utf8').split(/\r?\n/)) {
58
+ const [sha, name] = line.split(' ');
59
+ if (name === ref && sha && SHA.test(sha))
60
+ return sha.toLowerCase();
61
+ }
62
+ }
63
+ }
64
+ catch {
65
+ // an unreadable .git names no release; the event is still sent
66
+ }
67
+ return undefined;
68
+ }
69
+ /** The release a Node app's events carry: what it or its host says, else the commit of the code it runs from. */
70
+ export function releaseOf(env, cwd) {
71
+ return releaseFrom(env) ?? (cwd ? gitCommitAt(cwd) : undefined);
72
+ }
@@ -0,0 +1,34 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+ import type { Client } from '@xovris/core';
3
+ /** The event a 5xx answer becomes: the method, the path without its query, and the status - never the query, a header or a body. */
4
+ export declare function serverErrorOf(request: Pick<IncomingMessage, 'method' | 'url'>, status: number): {
5
+ error: Error;
6
+ request: {
7
+ method: string;
8
+ url: string;
9
+ };
10
+ };
11
+ /**
12
+ * Subscribes the client to every 5xx answer of every HTTP server in this process; returns how to stop. B311s's clean room (14 Nov): a route
13
+ * whose own exception was captured while its request ran (Next.js's onRequestError, a framework's error handler) was then reported a
14
+ * second time by this floor as "GET /x answered 500" - two events for one failure. Each request now runs in its own async context, an
15
+ * exception captured inside it marks the request reported, and the floor speaks only for a 5xx nothing else reported.
16
+ */
17
+ export declare function captureServerErrors(c: Client): () => void;
18
+ type BunHandler = (this: unknown, ...a: unknown[]) => unknown;
19
+ type BunServeOptions = {
20
+ fetch?: BunHandler;
21
+ routes?: Record<string, unknown>;
22
+ } & Record<string, unknown>;
23
+ type BunGlobal = {
24
+ serve: (this: unknown, o: BunServeOptions) => unknown;
25
+ };
26
+ /**
27
+ * D01.05.01 (the setup race's Bun probe, 14 Nov: a route's thrown error never reaches a Node channel): Bun's own server answers a thrown
28
+ * error with a 500 by itself, so each fetch and route handler Bun.serve is given is wrapped - the thrown error reaches Xovris with the
29
+ * method and the path (never the query) and is thrown on unchanged, to the app's and Bun's own error handling. Returns how to stop.
30
+ */
31
+ export declare function captureBunServe(c: Client, g?: {
32
+ Bun?: BunGlobal;
33
+ }): () => void;
34
+ export {};
@@ -0,0 +1,83 @@
1
+ // D01.01.06.01 (the clean room's Express run, 14 Nov 2026: the app answered 500 and nothing reached Xovris - Express, like Fastify, Koa,
2
+ // Hono and Nest, handles a route's error itself, so neither an uncaught exception nor an unhandled rejection ever fires): every request
3
+ // a Node server answers with a 5xx reaches Xovris, whatever framework answered it - read from Node's own HTTP diagnostics channel
4
+ // (http.server.response.finish), so nothing is patched, no dependency is added, and an ES module app is covered as a CommonJS one.
5
+ // The route's own exception, where a framework hands it over, is the next layer; this is the floor every server stands on.
6
+ import { AsyncLocalStorage } from 'node:async_hooks';
7
+ import { subscribe, unsubscribe } from 'node:diagnostics_channel';
8
+ const CHANNEL = 'http.server.response.finish'; // KEEP: machine format - Node's own HTTP server channel (nodejs.org/api/diagnostics_channel.html)
9
+ /** The event a 5xx answer becomes: the method, the path without its query, and the status - never the query, a header or a body. */
10
+ export function serverErrorOf(request, status) {
11
+ const method = request.method ?? 'GET';
12
+ const url = (request.url ?? '/').split('?')[0] ?? '/';
13
+ const error = new Error(`${method} ${url} answered ${status}`);
14
+ error.name = 'ServerError';
15
+ // no frames: the stack would be Xovris's own, never the app's
16
+ error.stack = `${error.name}: ${error.message}`;
17
+ return { error, request: { method, url } };
18
+ }
19
+ const START = 'http.server.request.start'; // KEEP: machine format - Node's own HTTP server channel
20
+ /**
21
+ * Subscribes the client to every 5xx answer of every HTTP server in this process; returns how to stop. B311s's clean room (14 Nov): a route
22
+ * whose own exception was captured while its request ran (Next.js's onRequestError, a framework's error handler) was then reported a
23
+ * second time by this floor as "GET /x answered 500" - two events for one failure. Each request now runs in its own async context, an
24
+ * exception captured inside it marks the request reported, and the floor speaks only for a 5xx nothing else reported.
25
+ */
26
+ export function captureServerErrors(c) {
27
+ const reported = new WeakSet();
28
+ const running = new AsyncLocalStorage();
29
+ // the request's own context from its first line of handling - the channel is published just before the server emits 'request'
30
+ const start = (m) => { const { request } = (m ?? {}); if (request)
31
+ running.enterWith(request); };
32
+ const capture = c.captureException.bind(c);
33
+ c.captureException = (err, o) => { const r = running.getStore(); if (r && o?.mechanism !== 'http.server')
34
+ reported.add(r); return capture(err, o); };
35
+ const on = (m) => {
36
+ const { request, response } = (m ?? {});
37
+ const status = response?.statusCode ?? 0;
38
+ if (!request || status < 500 || reported.has(request))
39
+ return;
40
+ const e = serverErrorOf(request, status);
41
+ c.captureException(e.error, { handled: true, mechanism: 'http.server', request: e.request, level: 'error' });
42
+ };
43
+ subscribe(START, start);
44
+ subscribe(CHANNEL, on);
45
+ const stopBun = captureBunServe(c);
46
+ return () => { unsubscribe(START, start); unsubscribe(CHANNEL, on); stopBun(); c.captureException = capture; };
47
+ }
48
+ /**
49
+ * D01.05.01 (the setup race's Bun probe, 14 Nov: a route's thrown error never reaches a Node channel): Bun's own server answers a thrown
50
+ * error with a 500 by itself, so each fetch and route handler Bun.serve is given is wrapped - the thrown error reaches Xovris with the
51
+ * method and the path (never the query) and is thrown on unchanged, to the app's and Bun's own error handling. Returns how to stop.
52
+ */
53
+ export function captureBunServe(c, g = globalThis) {
54
+ const bun = g.Bun;
55
+ if (!bun || typeof bun.serve !== 'function')
56
+ return () => { };
57
+ const serve = bun.serve;
58
+ const report = (e, r) => {
59
+ const req = r;
60
+ const ok = !!req && typeof req.method === 'string' && typeof req.url === 'string';
61
+ c.captureException(e, { handled: false, mechanism: 'bun.serve', level: 'error', ...(ok ? { request: { method: req.method, url: new URL(req.url).pathname } } : {}) });
62
+ };
63
+ const wrap = (f) => function (...a) {
64
+ try {
65
+ const out = f.apply(this, a);
66
+ return out instanceof Promise ? out.catch((e) => { report(e, a[0]); throw e; }) : out;
67
+ }
68
+ catch (e) {
69
+ report(e, a[0]);
70
+ throw e;
71
+ }
72
+ };
73
+ // a route is a handler, a plain object of one handler per method, or a value Bun serves as it is (a Response, an HTML import) - kept
74
+ const plain = (v) => !!v && typeof v === 'object' && Object.getPrototypeOf(v) === Object.prototype;
75
+ const routes = (r) => Object.fromEntries(Object.entries(r).map(([path, h]) => [path,
76
+ typeof h === 'function' ? wrap(h) : plain(h) ? Object.fromEntries(Object.entries(h).map(([m, f]) => [m, typeof f === 'function' ? wrap(f) : f])) : h]));
77
+ bun.serve = function (o) {
78
+ if (!plain(o))
79
+ return serve.call(this, o);
80
+ return serve.call(this, { ...o, ...(typeof o.fetch === 'function' ? { fetch: wrap(o.fetch) } : {}), ...(plain(o.routes) ? { routes: routes(o.routes) } : {}) });
81
+ };
82
+ return () => { bun.serve = serve; };
83
+ }
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "@xovris/node",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "gitHead": "8c4ea16632dacbd3d42aa498287016ff8445a668",
4
+ "description": "Xovris for Node.js servers: errors from the wizard-written variables, process handlers that keep Node's own failure behaviour, and OTLP traces that join an existing OpenTelemetry setup instead of starting a second one (ADR 0011, D01.02.01).",
5
+ "version": "0.1.1",
6
+ "license": "Apache-2.0",
7
+ "type": "module",
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js",
15
+ "default": "./dist/index.js"
16
+ },
17
+ "./register": {
18
+ "types": "./dist/register.d.ts",
19
+ "import": "./dist/register.js",
20
+ "default": "./dist/register.js"
21
+ },
22
+ "./otel": {
23
+ "types": "./dist/otel.d.ts",
24
+ "import": "./dist/otel.js",
25
+ "default": "./dist/otel.js"
26
+ }
27
+ },
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
31
+ "dependencies": {
32
+ "@opentelemetry/api": "^1.9.1",
33
+ "@opentelemetry/core": "^2.12.0",
34
+ "@opentelemetry/exporter-trace-otlp-http": "^0.222.0",
35
+ "@opentelemetry/resources": "^2.12.0",
36
+ "@opentelemetry/sdk-trace-base": "^2.12.0",
37
+ "@opentelemetry/sdk-trace-node": "^2.12.0",
38
+ "@xovris/core": "0.1.1"
39
+ },
40
+ "devDependencies": {
41
+ "@opentelemetry/sdk-node": "^0.222.0",
42
+ "@sentry/node": "^11.6.0",
43
+ "@vercel/otel": "^2.1.3"
44
+ },
45
+ "homepage": "https://xovris.ai/developers/",
46
+ "engines": {
47
+ "node": ">=20"
48
+ },
49
+ "scripts": {
50
+ "build": "tsc -p tsconfig.build.json",
51
+ "typecheck": "tsc --noEmit -p .",
52
+ "test": "vitest run"
53
+ }
6
54
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.