@watchtowerobservability/node 0.5.0 → 0.6.0

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.
Files changed (52) hide show
  1. package/README.md +39 -8
  2. package/dist/cjs/env.d.ts +12 -0
  3. package/dist/cjs/env.js +37 -0
  4. package/dist/cjs/errors.d.ts +8 -0
  5. package/dist/cjs/errors.js +23 -0
  6. package/dist/cjs/index.d.ts +29 -9
  7. package/dist/cjs/index.js +87 -49
  8. package/dist/cjs/instrument.d.ts +7 -0
  9. package/dist/cjs/instrument.js +51 -0
  10. package/dist/cjs/integrations/genai-agents.d.ts +4 -1
  11. package/dist/cjs/integrations/genai-agents.js +27 -24
  12. package/dist/cjs/integrations/genai-frameworks.d.ts +25 -0
  13. package/dist/cjs/integrations/genai-frameworks.js +211 -0
  14. package/dist/cjs/integrations/genai.d.ts +1 -0
  15. package/dist/cjs/integrations/genai.js +7 -2
  16. package/dist/cjs/integrations/next.d.ts +4 -1
  17. package/dist/cjs/integrations/next.js +13 -7
  18. package/dist/cjs/load.js +36 -5
  19. package/dist/cjs/origin.d.ts +9 -0
  20. package/dist/cjs/origin.js +43 -0
  21. package/dist/cjs/redact.d.ts +8 -0
  22. package/dist/cjs/redact.js +43 -0
  23. package/dist/cjs/register.d.ts +1 -0
  24. package/dist/cjs/register.js +29 -0
  25. package/dist/cjs/sampling.d.ts +53 -0
  26. package/dist/cjs/sampling.js +98 -0
  27. package/dist/esm/env.d.ts +12 -0
  28. package/dist/esm/env.js +33 -0
  29. package/dist/esm/errors.d.ts +8 -0
  30. package/dist/esm/errors.js +22 -0
  31. package/dist/esm/index.d.ts +29 -9
  32. package/dist/esm/index.js +87 -50
  33. package/dist/esm/instrument.d.ts +7 -0
  34. package/dist/esm/instrument.js +48 -0
  35. package/dist/esm/integrations/genai-agents.d.ts +4 -1
  36. package/dist/esm/integrations/genai-agents.js +4 -4
  37. package/dist/esm/integrations/genai-frameworks.d.ts +25 -0
  38. package/dist/esm/integrations/genai-frameworks.js +206 -0
  39. package/dist/esm/integrations/genai.d.ts +1 -0
  40. package/dist/esm/integrations/genai.js +3 -1
  41. package/dist/esm/integrations/next.d.ts +4 -1
  42. package/dist/esm/integrations/next.js +11 -6
  43. package/dist/esm/load.js +78 -2
  44. package/dist/esm/origin.d.ts +9 -0
  45. package/dist/esm/origin.js +39 -0
  46. package/dist/esm/redact.d.ts +8 -0
  47. package/dist/esm/redact.js +39 -0
  48. package/dist/esm/register.d.ts +1 -0
  49. package/dist/esm/register.js +27 -0
  50. package/dist/esm/sampling.d.ts +53 -0
  51. package/dist/esm/sampling.js +91 -0
  52. package/package.json +33 -2
@@ -4,12 +4,12 @@
4
4
  // argument text is recorded. Both take the framework's own object, so neither package is a dependency.
5
5
  import { context, SpanKind, SpanStatusCode, trace } from '@opentelemetry/api';
6
6
  import { applyExtract, extract } from './genai-stream.js';
7
- const obj = (v) => (v && typeof v === 'object' ? v : {});
8
- const s = (v) => (typeof v === 'string' ? v : '');
9
- function start(name, attrs, parent) {
7
+ export const obj = (v) => (v && typeof v === 'object' ? v : {});
8
+ export const s = (v) => (typeof v === 'string' ? v : '');
9
+ export function start(name, attrs, parent, startTime) {
10
10
  const ctx = parent ? trace.setSpan(context.active(), parent) : context.active();
11
11
  const clean = Object.fromEntries(Object.entries(attrs).filter(([, v]) => v !== undefined && v !== ''));
12
- return trace.getTracer('watchtower').startSpan(name, { kind: SpanKind.INTERNAL, attributes: clean }, ctx);
12
+ return trace.getTracer('watchtower').startSpan(name, { kind: SpanKind.INTERNAL, attributes: clean, ...(startTime !== undefined ? { startTime } : {}) }, ctx);
13
13
  }
14
14
  /** instrumentLlamaIndex(Settings) (from `llamaindex`): llm-start/stream/end and tool call events as spans. */
15
15
  export function instrumentLlamaIndex(settings) {
@@ -0,0 +1,25 @@
1
+ import type { Span } from '@opentelemetry/api';
2
+ type Fn = (...a: unknown[]) => unknown;
3
+ /**
4
+ * langchainCallbackHandler(): pass it as `callbacks: [handler]` to a LangChain.js model, chain or LangGraph.js graph
5
+ * (`graph.invoke(input, { callbacks: [handler] })`). LangGraph nodes (chains whose metadata names `langgraph_node`)
6
+ * and the graph itself become `invoke_agent` spans, tools `execute_tool`, model calls `chat`, nested as they run;
7
+ * plain LCEL chains get no span. Returns a plain handler object (LangChain wraps it) with the open spans for tests.
8
+ */
9
+ export declare function langchainCallbackHandler(): Record<string, unknown> & {
10
+ open: Map<string, Span>;
11
+ };
12
+ /**
13
+ * instrumentVercelAI({ generateText, streamText }) with the functions from `ai`: returns wrapped copies (ES module
14
+ * exports cannot be patched). Pass `agentName` to name the run (default: the `experimental_telemetry.functionId`, else `agent`).
15
+ * const { generateText } = instrumentVercelAI({ generateText: ai.generateText });
16
+ * A multi-step loop (`maxSteps` / `stopWhen`) gives one `invoke_agent` span with a `chat` span per step and an
17
+ * `execute_tool` span per tool call.
18
+ */
19
+ export declare function instrumentVercelAI<T extends {
20
+ generateText?: Fn;
21
+ streamText?: Fn;
22
+ }>(ai: T, agentName?: string): T;
23
+ /** instrumentMastra(agent): wraps `agent.generate` and `agent.stream` of a Mastra `Agent`; the run is named after the agent. Returns the agent. */
24
+ export declare function instrumentMastra<T>(agent: T): T;
25
+ export {};
@@ -0,0 +1,206 @@
1
+ // GenAI spans for the TypeScript agent frameworks: LangGraph.js (a LangChain.js callback handler), the Vercel AI SDK
2
+ // agent loop (generateText / streamText with several steps) and Mastra agents. Same shape as the Python
3
+ // instrumentors and `genai-agents.ts`: `invoke_agent` / `chat` / `execute_tool` spans, nested as the run nests,
4
+ // never any prompt, completion or tool argument text. CrewAI has no JavaScript port, so there is no CrewAI hook here.
5
+ // Nothing is imported from the frameworks: each function takes their object.
6
+ import { context, SpanStatusCode, trace } from '@opentelemetry/api';
7
+ import { obj, s, start } from './genai-agents.js';
8
+ const num = (v) => (typeof v === 'number' ? v : undefined);
9
+ const thenable = (v) => !!v && typeof v.then === 'function';
10
+ function fail(span, e) {
11
+ span.recordException(e);
12
+ span.setStatus({ code: SpanStatusCode.ERROR, message: e?.message });
13
+ }
14
+ /**
15
+ * langchainCallbackHandler(): pass it as `callbacks: [handler]` to a LangChain.js model, chain or LangGraph.js graph
16
+ * (`graph.invoke(input, { callbacks: [handler] })`). LangGraph nodes (chains whose metadata names `langgraph_node`)
17
+ * and the graph itself become `invoke_agent` spans, tools `execute_tool`, model calls `chat`, nested as they run;
18
+ * plain LCEL chains get no span. Returns a plain handler object (LangChain wraps it) with the open spans for tests.
19
+ */
20
+ export function langchainCallbackHandler() {
21
+ const open = new Map(), up = new Map();
22
+ const begin = (runId, parentId, name, attrs) => {
23
+ up.set(runId, parentId);
24
+ let p = parentId;
25
+ while (p !== undefined && !open.has(p))
26
+ p = up.get(p); // a parent without a span: skip to its own parent
27
+ open.set(runId, start(name, attrs, p === undefined ? undefined : open.get(p)));
28
+ };
29
+ const close = (runId, error) => {
30
+ up.delete(runId);
31
+ const span = open.get(runId);
32
+ open.delete(runId);
33
+ if (span && error !== undefined)
34
+ fail(span, error);
35
+ return span;
36
+ };
37
+ const llmStart = (extra, llm) => (runId, parentId) => {
38
+ const p = obj(obj(extra).invocation_params), k = obj(obj(llm).kwargs);
39
+ const model = s(p.model) || s(p.model_name) || s(k.model) || s(k.modelName);
40
+ begin(runId, parentId, `chat ${model}`.trim(), { 'gen_ai.operation.name': 'chat', 'gen_ai.system': 'langchain', 'gen_ai.request.model': model });
41
+ };
42
+ const ender = (runId, error) => { close(runId, error)?.end(); };
43
+ const h = {
44
+ open,
45
+ handleChatModelStart: (llm, _m, runId, parentId, extra) => llmStart(extra, llm)(runId, parentId),
46
+ handleLLMStart: (llm, _p, runId, parentId, extra) => llmStart(extra, llm)(runId, parentId),
47
+ handleLLMEnd: (output, runId) => {
48
+ const span = close(runId);
49
+ if (!span)
50
+ return;
51
+ const o = obj(output), tu = obj(obj(o.llmOutput).tokenUsage);
52
+ const first = Array.isArray(o.generations) && Array.isArray(o.generations[0]) ? obj(o.generations[0][0]) : {};
53
+ const msg = obj(first.message), um = obj(msg.usage_metadata), rm = obj(msg.response_metadata);
54
+ const input = num(tu.promptTokens) ?? num(um.input_tokens), out = num(tu.completionTokens) ?? num(um.output_tokens);
55
+ if (input !== undefined)
56
+ span.setAttribute('gen_ai.usage.input_tokens', input);
57
+ if (out !== undefined)
58
+ span.setAttribute('gen_ai.usage.output_tokens', out);
59
+ if (s(rm.model_name))
60
+ span.setAttribute('gen_ai.response.model', s(rm.model_name));
61
+ if (s(rm.finish_reason))
62
+ span.setAttribute('gen_ai.response.finish_reasons', [s(rm.finish_reason)]);
63
+ span.end();
64
+ },
65
+ handleLLMError: (e, runId) => ender(runId, e),
66
+ handleChainStart: (_c, _i, runId, parentId, _t, metadata, _rt, runName) => {
67
+ const m = obj(metadata), node = s(m.langgraph_node);
68
+ // only LangGraph runs get spans (the graph root and its nodes); plain LCEL chains are noise
69
+ if (!node && !(parentId === undefined && m.langgraph_step !== undefined)) {
70
+ up.set(runId, parentId);
71
+ return;
72
+ }
73
+ const who = node && runName === node ? node : runName || node || 'graph';
74
+ begin(runId, parentId, `invoke_agent ${who}`, { 'gen_ai.operation.name': 'invoke_agent', 'gen_ai.agent.name': who, 'gen_ai.system': 'langgraph' });
75
+ },
76
+ handleChainEnd: (_o, runId) => ender(runId),
77
+ handleChainError: (e, runId) => ender(runId, e),
78
+ handleToolStart: (tool, _i, runId, parentId, _t, _m, runName) => {
79
+ const name = runName || s(obj(tool).name) || s(obj(obj(tool).kwargs).name);
80
+ begin(runId, parentId, `execute_tool ${name}`.trim(), { 'gen_ai.operation.name': 'execute_tool', 'gen_ai.tool.name': name });
81
+ },
82
+ handleToolEnd: (_o, runId) => ender(runId),
83
+ handleToolError: (e, runId) => ender(runId, e),
84
+ };
85
+ return h;
86
+ }
87
+ /** Wraps every `execute` of an AI SDK / Mastra tool set so each call is an `execute_tool` span under the agent run. */
88
+ function wrapTools(tools, root) {
89
+ const out = {};
90
+ for (const [name, t] of Object.entries(obj(tools))) {
91
+ const tool = obj(t), exec = tool.execute;
92
+ if (typeof exec !== 'function') {
93
+ out[name] = t;
94
+ continue;
95
+ }
96
+ out[name] = {
97
+ ...tool,
98
+ execute: (...a) => {
99
+ const sp = start(`execute_tool ${name}`, { 'gen_ai.operation.name': 'execute_tool', 'gen_ai.tool.name': name }, root);
100
+ const done = (e) => { if (e !== undefined)
101
+ fail(sp, e); sp.end(); };
102
+ try {
103
+ const r = exec.apply(tool, a);
104
+ if (thenable(r))
105
+ r.then(() => done(), (e) => done(e ?? new Error('tool failed')));
106
+ else
107
+ done();
108
+ return r;
109
+ }
110
+ catch (e) {
111
+ done(e);
112
+ throw e;
113
+ }
114
+ },
115
+ };
116
+ }
117
+ return out;
118
+ }
119
+ /**
120
+ * One agent run as an `invoke_agent` span. `onStepFinish` (injected, the caller's own still runs) turns every model
121
+ * step into a `chat` span with usage, timed from the previous step's end; tool `execute` calls become
122
+ * `execute_tool` spans. `optsAt` is the position of the options argument. A stream ends the run in `onFinish` /
123
+ * `onError`; a promise ends it when it settles.
124
+ */
125
+ function agentRun(system, name, orig, self, args, optsAt, stream) {
126
+ const root = start(`invoke_agent ${name}`.trim(), { 'gen_ai.operation.name': 'invoke_agent', 'gen_ai.agent.name': name, 'gen_ai.system': system });
127
+ let ended = false, last = Date.now();
128
+ const end = (e) => { if (ended)
129
+ return; ended = true; if (e !== undefined)
130
+ fail(root, e); root.end(); };
131
+ const opts = { ...obj(args[optsAt]) };
132
+ const onStep = opts.onStepFinish, onFinish = opts.onFinish, onError = opts.onError;
133
+ opts.onStepFinish = (e) => {
134
+ const d = obj(e), u = obj(d.usage), r = obj(d.response);
135
+ const model = s(r.modelId) || s(r.model) || s(d.model);
136
+ const sp = start(`chat ${model}`.trim(), { 'gen_ai.operation.name': 'chat', 'gen_ai.system': system, 'gen_ai.response.model': model }, root, last);
137
+ const input = num(u.inputTokens) ?? num(u.promptTokens), out = num(u.outputTokens) ?? num(u.completionTokens);
138
+ if (input !== undefined)
139
+ sp.setAttribute('gen_ai.usage.input_tokens', input);
140
+ if (out !== undefined)
141
+ sp.setAttribute('gen_ai.usage.output_tokens', out);
142
+ if (s(d.finishReason))
143
+ sp.setAttribute('gen_ai.response.finish_reasons', [s(d.finishReason)]);
144
+ sp.end();
145
+ last = Date.now();
146
+ return onStep?.(e);
147
+ };
148
+ if (stream) {
149
+ opts.onFinish = (e) => { end(); return onFinish?.(e); };
150
+ opts.onError = (e) => { end(obj(e).error ?? e ?? new Error('stream failed')); return onError?.(e); };
151
+ }
152
+ if (opts.tools)
153
+ opts.tools = wrapTools(opts.tools, root);
154
+ const a = [...args];
155
+ a[optsAt] = opts;
156
+ let res;
157
+ try {
158
+ res = context.with(trace.setSpan(context.active(), root), () => orig.apply(self, a));
159
+ }
160
+ catch (e) {
161
+ end(e);
162
+ throw e;
163
+ }
164
+ if (!stream) {
165
+ // side branch only: the caller keeps the framework's own promise
166
+ if (thenable(res))
167
+ res.then(() => end(), (e) => end(e ?? new Error('run failed')));
168
+ else
169
+ end();
170
+ }
171
+ return res;
172
+ }
173
+ /**
174
+ * instrumentVercelAI({ generateText, streamText }) with the functions from `ai`: returns wrapped copies (ES module
175
+ * exports cannot be patched). Pass `agentName` to name the run (default: the `experimental_telemetry.functionId`, else `agent`).
176
+ * const { generateText } = instrumentVercelAI({ generateText: ai.generateText });
177
+ * A multi-step loop (`maxSteps` / `stopWhen`) gives one `invoke_agent` span with a `chat` span per step and an
178
+ * `execute_tool` span per tool call.
179
+ */
180
+ export function instrumentVercelAI(ai, agentName) {
181
+ const out = { ...ai };
182
+ const nameOf = (a) => agentName || s(obj(obj(a[0]).experimental_telemetry).functionId) || 'agent';
183
+ if (typeof ai.generateText === 'function') {
184
+ const f = ai.generateText;
185
+ out.generateText = function (...a) { return agentRun('vercel_ai', nameOf(a), f, this, a, 0, false); };
186
+ }
187
+ if (typeof ai.streamText === 'function') {
188
+ const f = ai.streamText;
189
+ out.streamText = function (...a) { return agentRun('vercel_ai', nameOf(a), f, this, a, 0, true); };
190
+ }
191
+ return out;
192
+ }
193
+ /** instrumentMastra(agent): wraps `agent.generate` and `agent.stream` of a Mastra `Agent`; the run is named after the agent. Returns the agent. */
194
+ export function instrumentMastra(agent) {
195
+ const a = agent;
196
+ const name = s(a.name) || 'agent';
197
+ for (const [method, stream] of [['generate', false], ['stream', true]]) {
198
+ const f = a[method];
199
+ if (typeof f !== 'function' || f.__wt)
200
+ continue;
201
+ const wrapped = function (...args) { return agentRun('mastra', name, f, this, args, 1, stream); };
202
+ wrapped.__wt = true;
203
+ a[method] = wrapped;
204
+ }
205
+ return agent;
206
+ }
@@ -1,4 +1,5 @@
1
1
  export { instrumentLlamaIndex, instrumentOpenAIAgents } from './genai-agents.js';
2
+ export { instrumentMastra, instrumentVercelAI, langchainCallbackHandler } from './genai-frameworks.js';
2
3
  /**
3
4
  * instrumentOpenAI(new OpenAI()): chat.completions.create and responses.create. Returns the client.
4
5
  * For an OpenAI-compatible gateway pass its name: instrumentOpenAI(new OpenAI({ baseURL: litellmUrl }), 'litellm').
@@ -1,10 +1,12 @@
1
1
  // GenAI spans (OTel GenAI semconv) for the openai, anthropic, AWS Bedrock, Google GenAI, Mistral and Ollama SDKs (and
2
- // LiteLLM through its OpenAI-compatible proxy), LlamaIndex and the OpenAI Agents SDK (genai-agents.ts), and a
2
+ // LiteLLM through its OpenAI-compatible proxy), LlamaIndex and the OpenAI Agents SDK (genai-agents.ts), LangGraph.js,
3
+ // Mastra and the Vercel AI SDK agent loop (genai-frameworks.ts), and a
3
4
  // telemetry option for the Vercel AI SDK. Streams record time to first chunk, usage and tool calls (genai-stream.ts).
4
5
  // Prompt and completion text is never recorded.
5
6
  import { context, SpanKind, SpanStatusCode, trace } from '@opentelemetry/api';
6
7
  import { applyExtract, extract, tapStream } from './genai-stream.js';
7
8
  export { instrumentLlamaIndex, instrumentOpenAIAgents } from './genai-agents.js';
9
+ export { instrumentMastra, instrumentVercelAI, langchainCallbackHandler } from './genai-frameworks.js';
8
10
  const DONE = Symbol('wt.instrumented');
9
11
  const plain = (b) => (b || {});
10
12
  function wrap(target, method, system, req = plain) {
@@ -1,5 +1,8 @@
1
+ import * as wt from '../index.js';
2
+ /** Build a Next.js instrumentation `register` that passes `options` to `init`; no-op off the Node.js runtime or without a key. */
3
+ export declare function makeRegister(options?: wt.InitOptions): () => Promise<void>;
1
4
  /** Next.js instrumentation hook: init from WT_* env on the Node.js runtime; no-op without WT_INGEST_KEY. */
2
- export declare function register(): Promise<void>;
5
+ export declare const register: () => Promise<void>;
3
6
  /** Next.js onRequestError: server render, route handler and server action errors. */
4
7
  export declare function onRequestError(err: unknown, request?: {
5
8
  path?: string;
@@ -1,12 +1,17 @@
1
1
  // instrumentation.js: module.exports = require('@watchtowerobservability/node/next');
2
+ // or, with options: export const register = makeRegister({ redact }); export { onRequestError } from '@watchtowerobservability/node/next';
2
3
  import * as wt from '../index.js';
3
- /** Next.js instrumentation hook: init from WT_* env on the Node.js runtime; no-op without WT_INGEST_KEY. */
4
- export async function register() {
5
- const rt = process.env.NEXT_RUNTIME;
6
- if ((rt && rt !== 'nodejs') || !process.env.WT_INGEST_KEY)
7
- return;
8
- wt.init({});
4
+ /** Build a Next.js instrumentation `register` that passes `options` to `init`; no-op off the Node.js runtime or without a key. */
5
+ export function makeRegister(options = {}) {
6
+ return async function register() {
7
+ const rt = process.env.NEXT_RUNTIME;
8
+ if ((rt && rt !== 'nodejs') || !(options.apiKey || process.env.WT_INGEST_KEY))
9
+ return;
10
+ wt.init(options);
11
+ };
9
12
  }
13
+ /** Next.js instrumentation hook: init from WT_* env on the Node.js runtime; no-op without WT_INGEST_KEY. */
14
+ export const register = makeRegister();
10
15
  /** Next.js onRequestError: server render, route handler and server action errors. */
11
16
  export async function onRequestError(err, request, context) {
12
17
  const c = context || {};
package/dist/esm/load.js CHANGED
@@ -1,5 +1,81 @@
1
+ // Optional-peer loader. Each peer is required by a LITERAL name inside a try block so bundlers (webpack, esbuild, Next's
2
+ // file tracer) can follow it; a computed `require(name)` is invisible to them. This is the CommonJS form;
3
+ // scripts/build.mjs prepends `const require = createRequire(import.meta.url)` for dist/esm (webpack follows that too).
4
+ // The cwd fallback only matters when `require` does not exist (test runners running the TS source as ESM).
1
5
  import { createRequire } from 'node:module';
2
- const req = createRequire(import.meta.url);
6
+ const pre = {};
7
+ try { pre["@opentelemetry/context-async-hooks"] = await import("@opentelemetry/context-async-hooks"); } catch (e) { pre["@opentelemetry/context-async-hooks"] = e; }
8
+ try { pre["@opentelemetry/core"] = await import("@opentelemetry/core"); } catch (e) { pre["@opentelemetry/core"] = e; }
9
+ try { pre["@opentelemetry/exporter-logs-otlp-http"] = await import("@opentelemetry/exporter-logs-otlp-http"); } catch (e) { pre["@opentelemetry/exporter-logs-otlp-http"] = e; }
10
+ try { pre["@opentelemetry/exporter-metrics-otlp-http"] = await import("@opentelemetry/exporter-metrics-otlp-http"); } catch (e) { pre["@opentelemetry/exporter-metrics-otlp-http"] = e; }
11
+ try { pre["@opentelemetry/exporter-trace-otlp-http"] = await import("@opentelemetry/exporter-trace-otlp-http"); } catch (e) { pre["@opentelemetry/exporter-trace-otlp-http"] = e; }
12
+ try { pre["@opentelemetry/otlp-transformer"] = await import("@opentelemetry/otlp-transformer"); } catch (e) { pre["@opentelemetry/otlp-transformer"] = e; }
13
+ try { pre["@opentelemetry/resources"] = await import("@opentelemetry/resources"); } catch (e) { pre["@opentelemetry/resources"] = e; }
14
+ try { pre["@opentelemetry/sdk-logs"] = await import("@opentelemetry/sdk-logs"); } catch (e) { pre["@opentelemetry/sdk-logs"] = e; }
15
+ try { pre["@opentelemetry/sdk-metrics"] = await import("@opentelemetry/sdk-metrics"); } catch (e) { pre["@opentelemetry/sdk-metrics"] = e; }
16
+ try { pre["@opentelemetry/sdk-trace"] = await import("@opentelemetry/sdk-trace"); } catch (e) { pre["@opentelemetry/sdk-trace"] = e; }
17
+ try { pre["@opentelemetry/instrumentation-runtime-node"] = await import("@opentelemetry/instrumentation-runtime-node"); } catch (e) { pre["@opentelemetry/instrumentation-runtime-node"] = e; }
18
+ try { pre["@opentelemetry/instrumentation"] = await import("@opentelemetry/instrumentation"); } catch (e) { pre["@opentelemetry/instrumentation"] = e; }
19
+ try { pre["@opentelemetry/instrumentation-http"] = await import("@opentelemetry/instrumentation-http"); } catch (e) { pre["@opentelemetry/instrumentation-http"] = e; }
20
+ try { pre["@opentelemetry/instrumentation-undici"] = await import("@opentelemetry/instrumentation-undici"); } catch (e) { pre["@opentelemetry/instrumentation-undici"] = e; }
21
+ try { pre["@opentelemetry/instrumentation-pg"] = await import("@opentelemetry/instrumentation-pg"); } catch (e) { pre["@opentelemetry/instrumentation-pg"] = e; }
22
+ try { pre["@opentelemetry/instrumentation-ioredis"] = await import("@opentelemetry/instrumentation-ioredis"); } catch (e) { pre["@opentelemetry/instrumentation-ioredis"] = e; }
23
+ try { pre["winston-transport"] = await import("winston-transport"); } catch (e) { pre["winston-transport"] = e; }
24
+ const nodeRequire = createRequire(import.meta.url);
25
+ const require = (id) => {
26
+ const m = pre[id];
27
+ if (m === undefined) return nodeRequire(id);
28
+ if (m instanceof Error) throw Object.assign(new Error(m.message), { code: m.code === 'ERR_MODULE_NOT_FOUND' ? 'MODULE_NOT_FOUND' : m.code });
29
+ return m.default && typeof m.default === 'object' ? { ...m.default, ...m } : m;
30
+ };
31
+ const NONE = Symbol('not a known peer');
32
+ function known(id) {
33
+ try { // bundlers only tolerate an optional require that is lexically inside try
34
+ switch (id) {
35
+ case '@opentelemetry/context-async-hooks': return require('@opentelemetry/context-async-hooks');
36
+ case '@opentelemetry/core': return require('@opentelemetry/core');
37
+ case '@opentelemetry/exporter-logs-otlp-http': return require('@opentelemetry/exporter-logs-otlp-http');
38
+ case '@opentelemetry/exporter-metrics-otlp-http': return require('@opentelemetry/exporter-metrics-otlp-http');
39
+ case '@opentelemetry/exporter-trace-otlp-http': return require('@opentelemetry/exporter-trace-otlp-http');
40
+ case '@opentelemetry/otlp-transformer': return require('@opentelemetry/otlp-transformer');
41
+ case '@opentelemetry/resources': return require('@opentelemetry/resources');
42
+ case '@opentelemetry/sdk-logs': return require('@opentelemetry/sdk-logs');
43
+ case '@opentelemetry/sdk-metrics': return require('@opentelemetry/sdk-metrics');
44
+ case '@opentelemetry/sdk-trace': return require('@opentelemetry/sdk-trace');
45
+ case '@opentelemetry/instrumentation-runtime-node': return require('@opentelemetry/instrumentation-runtime-node');
46
+ case '@opentelemetry/instrumentation': return require('@opentelemetry/instrumentation');
47
+ case '@opentelemetry/instrumentation-http': return require('@opentelemetry/instrumentation-http');
48
+ case '@opentelemetry/instrumentation-undici': return require('@opentelemetry/instrumentation-undici');
49
+ case '@opentelemetry/instrumentation-pg': return require('@opentelemetry/instrumentation-pg');
50
+ case '@opentelemetry/instrumentation-ioredis': return require('@opentelemetry/instrumentation-ioredis');
51
+ case 'winston-transport': return require('winston-transport');
52
+ default: return NONE;
53
+ }
54
+ }
55
+ catch (e) {
56
+ throw e;
57
+ }
58
+ }
3
59
  export function load(id) {
4
- return req(id);
60
+ if (typeof require !== 'function')
61
+ return createRequire(`${process.cwd()}/`)(id);
62
+ const m = known(id);
63
+ return m === NONE ? require(id) : m;
64
+ }
65
+ const SDK_PEERS = [
66
+ '@opentelemetry/context-async-hooks', '@opentelemetry/core', '@opentelemetry/exporter-logs-otlp-http',
67
+ '@opentelemetry/exporter-metrics-otlp-http', '@opentelemetry/exporter-trace-otlp-http', '@opentelemetry/otlp-transformer',
68
+ '@opentelemetry/resources', '@opentelemetry/sdk-logs', '@opentelemetry/sdk-metrics', '@opentelemetry/sdk-trace',
69
+ ];
70
+ /** Load an OpenTelemetry SDK package (an optional peer); a missing one throws an error naming what to install. */
71
+ export function need(id) {
72
+ try {
73
+ return load(id);
74
+ }
75
+ catch (e) {
76
+ if (e?.code === 'MODULE_NOT_FOUND' && String(e.message).includes(id)) {
77
+ throw new Error(`@watchtowerobservability/node needs the OpenTelemetry SDK, which is not installed (missing ${id}). Run: npm install ${SDK_PEERS.join(' ')}`);
78
+ }
79
+ throw e;
80
+ }
5
81
  }
@@ -0,0 +1,9 @@
1
+ import type { SpanProcessor } from '@opentelemetry/sdk-trace';
2
+ export interface Frame {
3
+ file: string;
4
+ line: number;
5
+ fn?: string;
6
+ }
7
+ /** The first application frame of a V8 stack, or undefined. */
8
+ export declare function firstAppFrame(stack: string): Frame | undefined;
9
+ export declare function codeOrigin(): SpanProcessor;
@@ -0,0 +1,39 @@
1
+ const FRAME = /^\s*at (?:(.+?) \()?(.+?):(\d+):\d+\)?$/;
2
+ const SKIP = /node_modules|^node:|[\\/]watchtower[\\/](?:dist|src)[\\/]|@watchtowerobservability[\\/]node/;
3
+ /** The first application frame of a V8 stack, or undefined. */
4
+ export function firstAppFrame(stack) {
5
+ for (const line of stack.split('\n').slice(1)) {
6
+ const m = FRAME.exec(line);
7
+ if (!m)
8
+ continue;
9
+ const file = m[2].replace(/^file:\/\//, '');
10
+ if (SKIP.test(file) || SKIP.test(line.trim().slice(3)))
11
+ continue;
12
+ return { file, line: Number(m[3]), fn: m[1] && m[1] !== '<anonymous>' ? m[1] : undefined };
13
+ }
14
+ return undefined;
15
+ }
16
+ export function codeOrigin() {
17
+ return {
18
+ onStart(span) {
19
+ const s = span;
20
+ if (s.attributes?.['code.filepath'] !== undefined)
21
+ return;
22
+ const holder = {};
23
+ const prev = Error.stackTraceLimit;
24
+ Error.stackTraceLimit = 30;
25
+ Error.captureStackTrace(holder);
26
+ Error.stackTraceLimit = prev;
27
+ const f = firstAppFrame(holder.stack ?? '');
28
+ if (!f)
29
+ return;
30
+ s.setAttribute('code.filepath', f.file);
31
+ s.setAttribute('code.lineno', f.line);
32
+ if (f.fn)
33
+ s.setAttribute('code.function', f.fn);
34
+ },
35
+ onEnd() { },
36
+ shutdown: () => Promise.resolve(),
37
+ forceFlush: () => Promise.resolve(),
38
+ };
39
+ }
@@ -0,0 +1,8 @@
1
+ import type { SpanProcessor } from '@opentelemetry/sdk-trace';
2
+ export type RedactHook = (key: string, value: unknown) => unknown;
3
+ /** Hook keys for the non-attribute fields. Event attributes (incl. exception.message / exception.stacktrace) use their own keys. */
4
+ export declare const SPAN_NAME_KEY = "span.name";
5
+ export declare const STATUS_MESSAGE_KEY = "status.message";
6
+ export declare const LOG_BODY_KEY = "log.body";
7
+ /** Span processor that redacts the name, status message, attributes, every event's and link's attributes before export. */
8
+ export declare function redactor(hook: RedactHook): SpanProcessor;
@@ -0,0 +1,39 @@
1
+ /** Hook keys for the non-attribute fields. Event attributes (incl. exception.message / exception.stacktrace) use their own keys. */
2
+ export const SPAN_NAME_KEY = 'span.name';
3
+ export const STATUS_MESSAGE_KEY = 'status.message';
4
+ export const LOG_BODY_KEY = 'log.body';
5
+ function attrs(a, hook) {
6
+ if (!a)
7
+ return;
8
+ for (const k of Object.keys(a))
9
+ a[k] = hook(k, a[k]);
10
+ }
11
+ /** Assign, falling back to defineProperty if the SDK exposes the field as a getter. */
12
+ function put(o, k, v) {
13
+ try {
14
+ o[k] = v;
15
+ }
16
+ catch { /* readonly accessor */ }
17
+ if (o[k] !== v)
18
+ Object.defineProperty(o, k, { value: v, configurable: true, enumerable: true, writable: true });
19
+ }
20
+ /** Span processor that redacts the name, status message, attributes, every event's and link's attributes before export. */
21
+ export function redactor(hook) {
22
+ return {
23
+ onStart() { },
24
+ onEnd(span) {
25
+ // ReadableSpan fields are readonly in the types but are plain mutable fields on the SDK span
26
+ const s = span;
27
+ put(s, 'name', String(hook(SPAN_NAME_KEY, s.name) ?? ''));
28
+ if (s.status?.message)
29
+ put(s.status, 'message', String(hook(STATUS_MESSAGE_KEY, s.status.message) ?? ''));
30
+ attrs(span.attributes, hook);
31
+ for (const e of s.events || [])
32
+ attrs(e.attributes, hook);
33
+ for (const l of s.links || [])
34
+ attrs(l.attributes, hook);
35
+ },
36
+ shutdown: () => Promise.resolve(),
37
+ forceFlush: () => Promise.resolve(),
38
+ };
39
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,27 @@
1
+ // Preload entry: `node --import @watchtowerobservability/node/register app.mjs` (ESM) or `node -r @watchtowerobservability/node/register app.js` (CommonJS).
2
+ // Starts the SDK from WT_*/OTEL_* env before the app loads, so http, fetch, pg and ioredis are patched in time.
3
+ // No-op without WT_INGEST_KEY.
4
+ import { pathToFileURL } from 'node:url';
5
+ import { register as registerHooks } from 'node:module';
6
+ import { init } from './index.js';
7
+ if (process.env.WT_INGEST_KEY || process.env.OTEL_EXPORTER_OTLP_HEADERS) {
8
+ try {
9
+ // ESM modules (node:http imported from an ES module) are only patched through OpenTelemetry's loader hook
10
+ // (import-in-the-middle). Resolve it from the app, once per process, and skip quietly when it is not installed.
11
+ const g = globalThis;
12
+ const key = Symbol.for('watchtower.node.esm-hook');
13
+ if (!g[key]) {
14
+ g[key] = true;
15
+ try {
16
+ registerHooks('@opentelemetry/instrumentation/hook.mjs', pathToFileURL(`${process.cwd()}/`));
17
+ }
18
+ catch {
19
+ // @opentelemetry/instrumentation not installed: CommonJS apps are still instrumented
20
+ }
21
+ }
22
+ init({});
23
+ }
24
+ catch (e) {
25
+ console.warn(`[watchtower] register: ${e.message}`);
26
+ }
27
+ }
@@ -0,0 +1,53 @@
1
+ import type { Attributes, Context, Link, SpanKind } from '@opentelemetry/api';
2
+ import type { Sampler, SamplingResult } from '@opentelemetry/sdk-trace';
3
+ export interface SamplingRule {
4
+ name?: string;
5
+ enabled?: boolean | null;
6
+ match?: {
7
+ service?: string;
8
+ env?: string;
9
+ span_name_prefix?: string;
10
+ span_name_glob?: string;
11
+ span_name_regex?: string;
12
+ attrs?: Record<string, string>;
13
+ min_duration_ms?: number | null;
14
+ status?: string;
15
+ };
16
+ action?: {
17
+ kind?: string;
18
+ ratio?: number | null;
19
+ };
20
+ }
21
+ export interface RemoteConfig {
22
+ strategyType?: string;
23
+ probabilisticSampling?: {
24
+ samplingRate: number;
25
+ };
26
+ rules?: SamplingRule[];
27
+ }
28
+ /** fnv64a of the trace id's bytes, as a fraction of 2^64; matches the gateway's `ratioKeeps`. */
29
+ export declare function traceFraction(traceIdHex: string): number;
30
+ export declare function globMatches(glob: string, text: string): boolean;
31
+ /** The keep ratio for a span under `cfg` (1 = keep). First matching ratio/drop rule wins. */
32
+ export declare function ratioFor(cfg: RemoteConfig, service: string, env: string, name: string, attrs: Attributes): number;
33
+ export interface RemoteSamplerOptions {
34
+ endpoint: string;
35
+ headers: Record<string, string>;
36
+ service: string;
37
+ env?: string;
38
+ intervalMs?: number;
39
+ fetch?: typeof fetch;
40
+ }
41
+ export declare class RemoteSampler implements Sampler {
42
+ private readonly o;
43
+ cfg: RemoteConfig;
44
+ private etag;
45
+ private timer?;
46
+ private readonly fetchFn;
47
+ constructor(o: RemoteSamplerOptions);
48
+ /** One poll; a failure or 304 keeps the current config. */
49
+ poll(): Promise<void>;
50
+ stop(): void;
51
+ shouldSample(_c: Context, traceId: string, name: string, _k: SpanKind, attributes: Attributes, _l: Link[]): SamplingResult;
52
+ toString(): string;
53
+ }