@xovris/core 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.
- package/dist/index.d.ts +178 -0
- package/dist/index.js +293 -0
- package/package.json +27 -3
- package/README.md +0 -3
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
export interface Frame {
|
|
2
|
+
function?: string;
|
|
3
|
+
filename?: string;
|
|
4
|
+
lineno?: number;
|
|
5
|
+
colno?: number;
|
|
6
|
+
in_app?: boolean;
|
|
7
|
+
}
|
|
8
|
+
export interface Breadcrumb {
|
|
9
|
+
timestamp: number;
|
|
10
|
+
category: string;
|
|
11
|
+
message: string;
|
|
12
|
+
level?: 'info' | 'warning' | 'error';
|
|
13
|
+
}
|
|
14
|
+
export interface TraceContext {
|
|
15
|
+
trace_id: string;
|
|
16
|
+
span_id: string;
|
|
17
|
+
}
|
|
18
|
+
export interface XovrisEvent {
|
|
19
|
+
event_id: string;
|
|
20
|
+
timestamp: number;
|
|
21
|
+
platform: 'javascript' | 'node';
|
|
22
|
+
level: 'fatal' | 'error' | 'warning' | 'info';
|
|
23
|
+
release?: string;
|
|
24
|
+
environment?: string;
|
|
25
|
+
tags: Record<string, string>;
|
|
26
|
+
exception?: {
|
|
27
|
+
values: {
|
|
28
|
+
type: string;
|
|
29
|
+
value: string;
|
|
30
|
+
stacktrace?: {
|
|
31
|
+
frames: Frame[];
|
|
32
|
+
};
|
|
33
|
+
mechanism: {
|
|
34
|
+
type: string;
|
|
35
|
+
handled: boolean;
|
|
36
|
+
};
|
|
37
|
+
}[];
|
|
38
|
+
};
|
|
39
|
+
message?: {
|
|
40
|
+
formatted: string;
|
|
41
|
+
};
|
|
42
|
+
breadcrumbs?: {
|
|
43
|
+
values: Breadcrumb[];
|
|
44
|
+
};
|
|
45
|
+
request?: {
|
|
46
|
+
url?: string;
|
|
47
|
+
method?: string;
|
|
48
|
+
};
|
|
49
|
+
/** The active span when the error was captured, so ingestion links the error to its trace instead of storing it twice. */
|
|
50
|
+
contexts?: {
|
|
51
|
+
trace?: TraceContext;
|
|
52
|
+
};
|
|
53
|
+
/** D01.02.02: the built files this error's frames name, each with the debug ID the build step registered for it. */
|
|
54
|
+
debug_meta?: {
|
|
55
|
+
images: {
|
|
56
|
+
type: 'sourcemap';
|
|
57
|
+
code_file: string;
|
|
58
|
+
debug_id: string;
|
|
59
|
+
}[];
|
|
60
|
+
};
|
|
61
|
+
sdk: {
|
|
62
|
+
name: string;
|
|
63
|
+
version: string;
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
export declare const SDK_VERSION = "0.1.0";
|
|
67
|
+
/** V8 ("at fn (file:1:2)") and Gecko/WebKit ("fn@file:1:2") stacks, oldest frame first as the protocol expects. */
|
|
68
|
+
export declare function parseStack(stack: string | undefined): Frame[];
|
|
69
|
+
type DebugRegistry = Record<string, string>;
|
|
70
|
+
/**
|
|
71
|
+
* D01.02.02: the build step (xovris sourcemaps; Sentry's bundler plugins write the same shape) registers each built file's debug
|
|
72
|
+
* ID under a stack captured inside that file. The files an error's frames name are sent with their IDs, so ingestion finds the
|
|
73
|
+
* exact map - or knows it never arrived and says the build ran without its token.
|
|
74
|
+
*/
|
|
75
|
+
export declare function debugImages(frames: readonly Frame[], registry?: DebugRegistry | undefined): NonNullable<XovrisEvent['debug_meta']>['images'];
|
|
76
|
+
export declare function eventFromError(err: unknown, o: {
|
|
77
|
+
platform: XovrisEvent['platform'];
|
|
78
|
+
handled: boolean;
|
|
79
|
+
mechanism: string;
|
|
80
|
+
level?: XovrisEvent['level'];
|
|
81
|
+
}): XovrisEvent;
|
|
82
|
+
/** One envelope: header, item header, item - the protocol the Xovris envelope endpoint and every Sentry SDK speak.
|
|
83
|
+
* The envelope header never carries a DSN, so the key cannot travel in the body. */
|
|
84
|
+
export declare function envelope(event: XovrisEvent, report?: ClientReport): string;
|
|
85
|
+
/** Sentry's client report item: what the SDK did NOT send, by reason, so ingestion counts every occurrence exactly. */
|
|
86
|
+
export interface ClientReport {
|
|
87
|
+
timestamp: number;
|
|
88
|
+
discarded_events: {
|
|
89
|
+
reason: 'queue_overflow' | 'ratelimit_backoff';
|
|
90
|
+
category: 'error';
|
|
91
|
+
quantity: number;
|
|
92
|
+
}[];
|
|
93
|
+
}
|
|
94
|
+
/** An error's identity on the client: its type and the frame it was thrown from (never the message, which varies). */
|
|
95
|
+
export declare function signatureOf(ev: XovrisEvent): string;
|
|
96
|
+
/** The wizard writes the project's own ingest address (https://<ingest host>/api/<project>); events go to its /envelope/. */
|
|
97
|
+
export declare function envelopeUrl(ingestUrl: string): string | null;
|
|
98
|
+
/** The project id inside the wizard-written ingest address, or null when the address has no project path. */
|
|
99
|
+
export declare function projectIdFrom(ingestUrl: string): string | null;
|
|
100
|
+
/** OTLP/HTTP traces go to the ingest origin's /v1/otlp/v1/traces; the project is resolved from the key header. */
|
|
101
|
+
export declare function otlpTracesUrl(ingestUrl: string): string | null;
|
|
102
|
+
/** The header that tells ingestion this SDK reports errors as envelopes, so a span's exception event is linked to the
|
|
103
|
+
* envelope event by its trace rather than stored as a second error (D01.02.01, D01-AT-08). */
|
|
104
|
+
export declare const ERRORS_VIA_ENVELOPE: {
|
|
105
|
+
readonly 'x-xovris-errors': 'envelope';
|
|
106
|
+
};
|
|
107
|
+
export type Send = (url: string, init: {
|
|
108
|
+
method: 'POST';
|
|
109
|
+
headers: Record<string, string>;
|
|
110
|
+
body: string;
|
|
111
|
+
keepalive?: boolean;
|
|
112
|
+
}) => Promise<{
|
|
113
|
+
status: number;
|
|
114
|
+
retryAfterSeconds?: number;
|
|
115
|
+
}>;
|
|
116
|
+
export interface ClientOptions {
|
|
117
|
+
url: string | undefined;
|
|
118
|
+
key: string | undefined;
|
|
119
|
+
release?: string | undefined;
|
|
120
|
+
environment?: string | undefined;
|
|
121
|
+
platform: XovrisEvent['platform'];
|
|
122
|
+
send?: Send;
|
|
123
|
+
/** At most this many events a minute leave the process; the rest are counted and dropped (no runaway loop). */
|
|
124
|
+
maxPerMinute?: number;
|
|
125
|
+
/**
|
|
126
|
+
* D03.01.01: an error this process has not sent before still leaves when the cap is spent or ingestion asked for a
|
|
127
|
+
* pause - at most this many a minute - so a flood of one fault never hides the first occurrence of another.
|
|
128
|
+
*/
|
|
129
|
+
maxFirstPerMinute?: number;
|
|
130
|
+
warn?: (message: string) => void;
|
|
131
|
+
/** The active span, when the runtime has one (the Node SDK reads it from OpenTelemetry). */
|
|
132
|
+
traceContext?: () => TraceContext | undefined;
|
|
133
|
+
now?: () => number;
|
|
134
|
+
/**
|
|
135
|
+
* A same-origin path (e.g. /xovris) that forwards envelopes to the ingest address (D01.02.02): used when a browser
|
|
136
|
+
* extension blocks the ingest host, so browser errors still arrive. Only a path, never another host.
|
|
137
|
+
*/
|
|
138
|
+
tunnel?: string | undefined;
|
|
139
|
+
/** Whether the device is online; a failed send while offline is not a block. */
|
|
140
|
+
isOnline?: () => boolean;
|
|
141
|
+
/** The pause before the one retry of an envelope an ingest instance lost (502-504 or a dropped connection). */
|
|
142
|
+
retryDelayMs?: number;
|
|
143
|
+
}
|
|
144
|
+
export interface Client {
|
|
145
|
+
enabled: boolean;
|
|
146
|
+
captureException(err: unknown, o?: {
|
|
147
|
+
handled?: boolean;
|
|
148
|
+
mechanism?: string;
|
|
149
|
+
tags?: Record<string, string>;
|
|
150
|
+
request?: XovrisEvent['request'];
|
|
151
|
+
level?: XovrisEvent['level'];
|
|
152
|
+
}): string | null;
|
|
153
|
+
addBreadcrumb(b: Omit<Breadcrumb, 'timestamp'>): void;
|
|
154
|
+
flush(timeoutMs?: number): Promise<boolean>;
|
|
155
|
+
readonly dropped: number;
|
|
156
|
+
/** Sends the ingest host refused at the network while the device was online - an ad blocker's signature. */
|
|
157
|
+
readonly blocked: number;
|
|
158
|
+
/** True once events go through the tunnel. */
|
|
159
|
+
readonly viaTunnel: boolean;
|
|
160
|
+
/** Envelopes sent a second time because ingestion lost the first attempt (one copy is kept per event id). */
|
|
161
|
+
readonly retried: number;
|
|
162
|
+
}
|
|
163
|
+
interface Shared {
|
|
164
|
+
seen: WeakSet<object>;
|
|
165
|
+
recent: Map<string, number>;
|
|
166
|
+
}
|
|
167
|
+
export declare function shared(): Shared;
|
|
168
|
+
/** True the first time this error is offered anywhere in the process. Objects are remembered for their lifetime;
|
|
169
|
+
* a thrown string or number is remembered for one second (two handlers seeing one rejection, not two real failures). */
|
|
170
|
+
export declare function firstSighting(err: unknown, now: number): boolean;
|
|
171
|
+
export declare function createClient(o: ClientOptions): Client;
|
|
172
|
+
/** Release and environment from what the platform already knows: XOVRIS_RELEASE, then the commit each host or build service names for the
|
|
173
|
+
* code it deployed (D01.03, 14 Nov - Vercel and GitHub alone left an app on Netlify, Render, Railway, Heroku, Cloudflare Pages, Amplify or
|
|
174
|
+
* a CI build with no release, so its first real event was never verified). A Node app falls back to its own git commit (@xovris/node). */
|
|
175
|
+
export declare const HOST_COMMIT: string[];
|
|
176
|
+
export declare function releaseFrom(env: Record<string, string | undefined>): string | undefined;
|
|
177
|
+
export declare function environmentFrom(env: Record<string, string | undefined>): string | undefined;
|
|
178
|
+
export {};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
// @xovris/core (ADR 0011): the part OpenTelemetry does not yet give - error capture with stack frames and breadcrumbs,
|
|
2
|
+
// release and environment tagging - sent as Sentry-protocol envelopes to Xovris's envelope endpoint. No model, no
|
|
3
|
+
// third-party call: one POST per event to the address the wizard wrote, and the key never inside the body or the URL.
|
|
4
|
+
export const SDK_VERSION = '0.1.0';
|
|
5
|
+
const V8 = /^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?\s*$/;
|
|
6
|
+
const GECKO = /^\s*(.*?)@(.+?):(\d+):(\d+)\s*$/;
|
|
7
|
+
/** V8 ("at fn (file:1:2)") and Gecko/WebKit ("fn@file:1:2") stacks, oldest frame first as the protocol expects. */
|
|
8
|
+
export function parseStack(stack) {
|
|
9
|
+
if (!stack)
|
|
10
|
+
return [];
|
|
11
|
+
const frames = [];
|
|
12
|
+
for (const line of stack.split('\n')) {
|
|
13
|
+
const m = V8.exec(line) ?? GECKO.exec(line);
|
|
14
|
+
if (!m)
|
|
15
|
+
continue;
|
|
16
|
+
const filename = m[2];
|
|
17
|
+
const fn = m[1]?.trim().replace(/^async /, '');
|
|
18
|
+
frames.push({
|
|
19
|
+
...(fn ? { function: fn } : {}), filename, lineno: Number(m[3]), colno: Number(m[4]),
|
|
20
|
+
in_app: !/node_modules|^node:|^internal\/|^native$/.test(filename),
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
return frames.reverse();
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* D01.02.02: the build step (xovris sourcemaps; Sentry's bundler plugins write the same shape) registers each built file's debug
|
|
27
|
+
* ID under a stack captured inside that file. The files an error's frames name are sent with their IDs, so ingestion finds the
|
|
28
|
+
* exact map - or knows it never arrived and says the build ran without its token.
|
|
29
|
+
*/
|
|
30
|
+
export function debugImages(frames, registry = globalThis._xovrisDebugIds ?? globalThis._sentryDebugIds) {
|
|
31
|
+
if (!registry)
|
|
32
|
+
return [];
|
|
33
|
+
const byFile = new Map();
|
|
34
|
+
for (const [stack, id] of Object.entries(registry)) {
|
|
35
|
+
const file = parseStack(stack).at(-1)?.filename;
|
|
36
|
+
if (file && typeof id === 'string')
|
|
37
|
+
byFile.set(file, id);
|
|
38
|
+
}
|
|
39
|
+
const seen = new Set();
|
|
40
|
+
const out = [];
|
|
41
|
+
for (const f of frames) {
|
|
42
|
+
const id = f.filename ? byFile.get(f.filename) : undefined;
|
|
43
|
+
if (!id || seen.has(f.filename))
|
|
44
|
+
continue;
|
|
45
|
+
seen.add(f.filename);
|
|
46
|
+
out.push({ type: 'sourcemap', code_file: f.filename, debug_id: id });
|
|
47
|
+
}
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
const hex = (n) => Array.from(crypto.getRandomValues(new Uint8Array(n)), (b) => b.toString(16).padStart(2, '0')).join('');
|
|
51
|
+
export function eventFromError(err, o) {
|
|
52
|
+
const e = err instanceof Error ? err : new Error(typeof err === 'string' ? err : safeString(err));
|
|
53
|
+
const frames = parseStack(e.stack);
|
|
54
|
+
const images = debugImages(frames);
|
|
55
|
+
return {
|
|
56
|
+
event_id: hex(16), timestamp: Date.now() / 1000, platform: o.platform, level: o.level ?? 'error', tags: {},
|
|
57
|
+
exception: { values: [{ type: e.name || 'Error', value: e.message, stacktrace: { frames }, mechanism: { type: o.mechanism, handled: o.handled } }] },
|
|
58
|
+
...(images.length ? { debug_meta: { images } } : {}),
|
|
59
|
+
sdk: { name: 'xovris.javascript', version: SDK_VERSION },
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
function safeString(v) {
|
|
63
|
+
try {
|
|
64
|
+
return JSON.stringify(v) ?? String(v);
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return String(v);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/** One envelope: header, item header, item - the protocol the Xovris envelope endpoint and every Sentry SDK speak.
|
|
71
|
+
* The envelope header never carries a DSN, so the key cannot travel in the body. */
|
|
72
|
+
export function envelope(event, report) {
|
|
73
|
+
const body = JSON.stringify(event);
|
|
74
|
+
const head = `${JSON.stringify({ event_id: event.event_id, sent_at: new Date().toISOString(), sdk: event.sdk })}\n${JSON.stringify({ type: 'event', length: new TextEncoder().encode(body).length })}\n${body}\n`;
|
|
75
|
+
if (!report || report.discarded_events.length === 0)
|
|
76
|
+
return head;
|
|
77
|
+
const r = JSON.stringify(report);
|
|
78
|
+
return `${head}${JSON.stringify({ type: 'client_report', length: new TextEncoder().encode(r).length })}\n${r}\n`;
|
|
79
|
+
}
|
|
80
|
+
/** An error's identity on the client: its type and the frame it was thrown from (never the message, which varies). */
|
|
81
|
+
export function signatureOf(ev) {
|
|
82
|
+
const ex = ev.exception?.values?.at(-1);
|
|
83
|
+
const top = (ex?.stacktrace?.frames ?? []).filter((f) => f.in_app !== false).at(-1);
|
|
84
|
+
return `${ex?.type ?? 'Error'}|${top?.filename ?? ''}:${top?.function ?? ''}`;
|
|
85
|
+
}
|
|
86
|
+
/** The wizard writes the project's own ingest address (https://<ingest host>/api/<project>); events go to its /envelope/. */
|
|
87
|
+
export function envelopeUrl(ingestUrl) {
|
|
88
|
+
let u;
|
|
89
|
+
try {
|
|
90
|
+
u = new URL(ingestUrl);
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
if (!/^\/api\/[^/]+\/?$/.test(u.pathname) || u.username || u.password || u.search)
|
|
96
|
+
return null;
|
|
97
|
+
return `${u.origin}${u.pathname.replace(/\/$/, '')}/envelope/`;
|
|
98
|
+
}
|
|
99
|
+
/** The project id inside the wizard-written ingest address, or null when the address has no project path. */
|
|
100
|
+
export function projectIdFrom(ingestUrl) {
|
|
101
|
+
try {
|
|
102
|
+
return decodeURIComponent(/^\/api\/([^/]+)\/?$/.exec(new URL(ingestUrl).pathname)?.[1] ?? '') || null;
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
/** OTLP/HTTP traces go to the ingest origin's /v1/otlp/v1/traces; the project is resolved from the key header. */
|
|
109
|
+
export function otlpTracesUrl(ingestUrl) {
|
|
110
|
+
if (!envelopeUrl(ingestUrl))
|
|
111
|
+
return null;
|
|
112
|
+
return `${new URL(ingestUrl).origin}/v1/otlp/v1/traces`;
|
|
113
|
+
}
|
|
114
|
+
/** The header that tells ingestion this SDK reports errors as envelopes, so a span's exception event is linked to the
|
|
115
|
+
* envelope event by its trace rather than stored as a second error (D01.02.01, D01-AT-08). */
|
|
116
|
+
export const ERRORS_VIA_ENVELOPE = { 'x-xovris-errors': 'envelope' };
|
|
117
|
+
const SHARED = Symbol.for('xovris.sdk.shared.v1');
|
|
118
|
+
export function shared() {
|
|
119
|
+
const g = globalThis;
|
|
120
|
+
return (g[SHARED] ??= { seen: new WeakSet(), recent: new Map() });
|
|
121
|
+
}
|
|
122
|
+
/** True the first time this error is offered anywhere in the process. Objects are remembered for their lifetime;
|
|
123
|
+
* a thrown string or number is remembered for one second (two handlers seeing one rejection, not two real failures). */
|
|
124
|
+
export function firstSighting(err, now) {
|
|
125
|
+
const s = shared();
|
|
126
|
+
if (typeof err === 'object' && err !== null) {
|
|
127
|
+
if (s.seen.has(err))
|
|
128
|
+
return false;
|
|
129
|
+
s.seen.add(err);
|
|
130
|
+
return true;
|
|
131
|
+
}
|
|
132
|
+
const k = `${typeof err}:${String(err)}`;
|
|
133
|
+
const at = s.recent.get(k);
|
|
134
|
+
if (at !== undefined && now - at < 1000)
|
|
135
|
+
return false;
|
|
136
|
+
s.recent.set(k, now);
|
|
137
|
+
if (s.recent.size > 100)
|
|
138
|
+
s.recent.delete(s.recent.keys().next().value);
|
|
139
|
+
return true;
|
|
140
|
+
}
|
|
141
|
+
export function createClient(o) {
|
|
142
|
+
const endpoint = o.url ? envelopeUrl(o.url) : null;
|
|
143
|
+
const warn = o.warn ?? ((m) => console.warn(`[xovris] ${m}`));
|
|
144
|
+
const now = o.now ?? (() => Date.now());
|
|
145
|
+
const enabled = !!(endpoint && o.key);
|
|
146
|
+
if (!enabled)
|
|
147
|
+
warn(!o.url || !o.key ? 'No ingest address or key is set, so errors are not sent. Run the wizard: it writes both.' : `The ingest address ${o.url} has no project path, so errors are not sent. Run the wizard again to rewrite it.`);
|
|
148
|
+
const send = o.send ?? ((url, init) => fetch(url, init).then((r) => {
|
|
149
|
+
const ra = Number(r.headers.get('retry-after'));
|
|
150
|
+
return { status: r.status, ...(Number.isFinite(ra) && ra > 0 ? { retryAfterSeconds: ra } : {}) };
|
|
151
|
+
}));
|
|
152
|
+
const crumbs = [];
|
|
153
|
+
const pending = new Set();
|
|
154
|
+
let windowStart = now();
|
|
155
|
+
let inWindow = 0;
|
|
156
|
+
let dropped = 0;
|
|
157
|
+
let pausedUntil = 0;
|
|
158
|
+
const limit = o.maxPerMinute ?? 60;
|
|
159
|
+
const tunnel = o.tunnel && /^\/(?!\/)/.test(o.tunnel) ? o.tunnel : null;
|
|
160
|
+
let viaTunnel = false;
|
|
161
|
+
let blocked = 0;
|
|
162
|
+
let retried = 0;
|
|
163
|
+
const attempt = (url, body, headers) => send(url, { method: 'POST', keepalive: o.platform === 'javascript', body, headers }).catch(() => ({ status: 0 }));
|
|
164
|
+
const firstLimit = o.maxFirstPerMinute ?? 10;
|
|
165
|
+
let firstInWindow = 0;
|
|
166
|
+
const signatures = new Set();
|
|
167
|
+
const discarded = { queue_overflow: 0, ratelimit_backoff: 0 };
|
|
168
|
+
const takeReport = () => {
|
|
169
|
+
const d = ['queue_overflow', 'ratelimit_backoff'].filter((k) => discarded[k] > 0).map((reason) => ({ reason, category: 'error', quantity: discarded[reason] }));
|
|
170
|
+
if (d.length === 0)
|
|
171
|
+
return undefined;
|
|
172
|
+
discarded.queue_overflow = 0;
|
|
173
|
+
discarded.ratelimit_backoff = 0;
|
|
174
|
+
return { timestamp: now() / 1000, discarded_events: d };
|
|
175
|
+
};
|
|
176
|
+
return {
|
|
177
|
+
enabled,
|
|
178
|
+
get dropped() { return dropped; },
|
|
179
|
+
get blocked() { return blocked; },
|
|
180
|
+
get retried() { return retried; },
|
|
181
|
+
get viaTunnel() { return viaTunnel; },
|
|
182
|
+
addBreadcrumb(b) { crumbs.push({ ...b, timestamp: now() / 1000 }); if (crumbs.length > 50)
|
|
183
|
+
crumbs.shift(); },
|
|
184
|
+
captureException(err, c = {}) {
|
|
185
|
+
if (!enabled)
|
|
186
|
+
return null;
|
|
187
|
+
if (!firstSighting(err, now()))
|
|
188
|
+
return null;
|
|
189
|
+
const t = now();
|
|
190
|
+
const ev = eventFromError(err, { platform: o.platform, handled: c.handled ?? true, mechanism: c.mechanism ?? 'generic', ...(c.level ? { level: c.level } : {}) });
|
|
191
|
+
const sig = signatureOf(ev);
|
|
192
|
+
if (t - windowStart > 60_000) {
|
|
193
|
+
windowStart = t;
|
|
194
|
+
inWindow = 0;
|
|
195
|
+
firstInWindow = 0;
|
|
196
|
+
}
|
|
197
|
+
// A pause (429 with Retry-After) or a spent cap drops repeats - counted and reported - but a fault this process
|
|
198
|
+
// has never sent still leaves, within its own small budget: the rare error is never the one sampled away.
|
|
199
|
+
const firstSeen = !signatures.has(sig) && firstInWindow < firstLimit;
|
|
200
|
+
if (t < pausedUntil && !firstSeen) {
|
|
201
|
+
dropped++;
|
|
202
|
+
discarded.ratelimit_backoff++;
|
|
203
|
+
return null;
|
|
204
|
+
}
|
|
205
|
+
if (inWindow >= limit && !firstSeen) {
|
|
206
|
+
dropped++;
|
|
207
|
+
discarded.queue_overflow++;
|
|
208
|
+
return null;
|
|
209
|
+
}
|
|
210
|
+
if (inWindow >= limit || t < pausedUntil)
|
|
211
|
+
firstInWindow++;
|
|
212
|
+
inWindow++;
|
|
213
|
+
signatures.add(sig);
|
|
214
|
+
if (signatures.size > 1000)
|
|
215
|
+
signatures.delete(signatures.values().next().value);
|
|
216
|
+
if (o.release)
|
|
217
|
+
ev.release = o.release;
|
|
218
|
+
if (o.environment)
|
|
219
|
+
ev.environment = o.environment;
|
|
220
|
+
if (c.tags)
|
|
221
|
+
ev.tags = { ...c.tags };
|
|
222
|
+
if (c.request)
|
|
223
|
+
ev.request = c.request;
|
|
224
|
+
const trace = o.traceContext?.();
|
|
225
|
+
if (trace)
|
|
226
|
+
ev.contexts = { trace };
|
|
227
|
+
if (crumbs.length)
|
|
228
|
+
ev.breadcrumbs = { values: [...crumbs] };
|
|
229
|
+
const body = envelope(ev, takeReport());
|
|
230
|
+
const headers = { 'content-type': 'application/x-sentry-envelope', 'x-sentry-auth': `Sentry sentry_version=7, sentry_key=${o.key}, sentry_client=xovris-js/${SDK_VERSION}` };
|
|
231
|
+
const go = () => attempt(viaTunnel && tunnel ? tunnel : endpoint, body, viaTunnel ? { ...headers, 'x-xovris-tunnel': 'blocked' } : headers);
|
|
232
|
+
const p = go().then(async (r) => {
|
|
233
|
+
// No answer at all while online: something on the device blocked the ingest host - go through the site's own domain.
|
|
234
|
+
if (r.status === 0 && !viaTunnel && (o.isOnline?.() ?? true)) {
|
|
235
|
+
blocked++;
|
|
236
|
+
if (tunnel) {
|
|
237
|
+
viaTunnel = true;
|
|
238
|
+
return go();
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return r;
|
|
242
|
+
}).then(async (r) => {
|
|
243
|
+
// G86.06: an ingest instance lost mid-request answers 502-504 or drops the connection. The same envelope goes once
|
|
244
|
+
// more after a short pause; ingestion keeps one copy per event id, so the retry can never double an error.
|
|
245
|
+
if ((r.status >= 502 && r.status <= 504) || (r.status === 0 && (o.isOnline?.() ?? true))) {
|
|
246
|
+
retried++;
|
|
247
|
+
await new Promise((res) => setTimeout(res, (o.retryDelayMs ?? 250) + Math.floor(Math.random() * 250)));
|
|
248
|
+
return go();
|
|
249
|
+
}
|
|
250
|
+
return r;
|
|
251
|
+
}).then((r) => { if (r.status === 429)
|
|
252
|
+
pausedUntil = now() + 1000 * (r.retryAfterSeconds ?? 60); return r; });
|
|
253
|
+
pending.add(p);
|
|
254
|
+
void p.finally(() => pending.delete(p));
|
|
255
|
+
return ev.event_id;
|
|
256
|
+
},
|
|
257
|
+
async flush(timeoutMs = 2000) {
|
|
258
|
+
if (pending.size === 0)
|
|
259
|
+
return true;
|
|
260
|
+
let timer;
|
|
261
|
+
const timeout = new Promise((r) => { timer = setTimeout(() => r(pending.size === 0), timeoutMs); });
|
|
262
|
+
// The timer never holds a short-lived process open after the sends have finished.
|
|
263
|
+
try {
|
|
264
|
+
return await Promise.race([Promise.all([...pending]).then(() => true), timeout]);
|
|
265
|
+
}
|
|
266
|
+
finally {
|
|
267
|
+
clearTimeout(timer);
|
|
268
|
+
}
|
|
269
|
+
},
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
/** Release and environment from what the platform already knows: XOVRIS_RELEASE, then the commit each host or build service names for the
|
|
273
|
+
* code it deployed (D01.03, 14 Nov - Vercel and GitHub alone left an app on Netlify, Render, Railway, Heroku, Cloudflare Pages, Amplify or
|
|
274
|
+
* a CI build with no release, so its first real event was never verified). A Node app falls back to its own git commit (@xovris/node). */
|
|
275
|
+
// KEEP: machine format - each host's own name for the deployed commit; the code's own .git is the open reading behind it (release.ts)
|
|
276
|
+
// G105.01.C132: the same list @xovris/stacks HOST_COMMIT holds for the OpenTelemetry stacks - a lane keeps the two equal
|
|
277
|
+
export const HOST_COMMIT = ['VERCEL_GIT_COMMIT_SHA', 'NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA', 'GITHUB_SHA', 'COMMIT_REF', 'CF_PAGES_COMMIT_SHA', 'RENDER_GIT_COMMIT',
|
|
278
|
+
'RAILWAY_GIT_COMMIT_SHA', 'HEROKU_SLUG_COMMIT', 'SOURCE_VERSION', 'AWS_COMMIT_ID', 'CODEBUILD_RESOLVED_SOURCE_VERSION', 'CI_COMMIT_SHA', 'BITBUCKET_COMMIT',
|
|
279
|
+
'CIRCLE_SHA1', 'BUILD_SOURCEVERSION', 'BUILDKITE_COMMIT', 'DRONE_COMMIT_SHA', 'GIT_COMMIT', 'SOURCE_COMMIT'];
|
|
280
|
+
export function releaseFrom(env) {
|
|
281
|
+
const own = env.XOVRIS_RELEASE?.trim();
|
|
282
|
+
if (own)
|
|
283
|
+
return own;
|
|
284
|
+
for (const k of HOST_COMMIT) {
|
|
285
|
+
const v = env[k]?.trim();
|
|
286
|
+
if (v)
|
|
287
|
+
return v;
|
|
288
|
+
}
|
|
289
|
+
return undefined;
|
|
290
|
+
}
|
|
291
|
+
export function environmentFrom(env) {
|
|
292
|
+
return env.XOVRIS_ENVIRONMENT ?? env.VERCEL_ENV ?? env.NEXT_PUBLIC_VERCEL_ENV ?? env.NODE_ENV ?? undefined;
|
|
293
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,30 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xovris/core",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"gitHead": "8c4ea16632dacbd3d42aa498287016ff8445a668",
|
|
4
|
+
"description": "Error capture, stack frames, breadcrumbs and Sentry-protocol envelopes for the Xovris SDK layer (ADR 0011).",
|
|
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
|
+
},
|
|
18
|
+
"publishConfig": {
|
|
19
|
+
"access": "public"
|
|
20
|
+
},
|
|
21
|
+
"homepage": "https://xovris.ai/developers/",
|
|
22
|
+
"engines": {
|
|
23
|
+
"node": ">=20"
|
|
24
|
+
},
|
|
25
|
+
"scripts": {
|
|
26
|
+
"build": "tsc -p tsconfig.build.json",
|
|
27
|
+
"typecheck": "tsc --noEmit -p .",
|
|
28
|
+
"test": "vitest run"
|
|
29
|
+
}
|
|
6
30
|
}
|
package/README.md
DELETED