@watchtowerobservability/node 0.0.0-stage → 0.2.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 (105) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +121 -2
  3. package/dist/cjs/buffer.d.ts +49 -0
  4. package/dist/cjs/buffer.js +134 -0
  5. package/dist/cjs/errors.d.ts +17 -0
  6. package/dist/cjs/errors.js +55 -0
  7. package/dist/cjs/index.d.ts +120 -0
  8. package/dist/cjs/index.js +302 -0
  9. package/dist/cjs/integrations/azure-functions.d.ts +18 -0
  10. package/dist/cjs/integrations/azure-functions.js +97 -0
  11. package/dist/cjs/integrations/express.d.ts +25 -0
  12. package/dist/cjs/integrations/express.js +58 -0
  13. package/dist/cjs/integrations/fastify.d.ts +6 -0
  14. package/dist/cjs/integrations/fastify.js +44 -0
  15. package/dist/cjs/integrations/genai-agents.d.ts +36 -0
  16. package/dist/cjs/integrations/genai-agents.js +124 -0
  17. package/dist/cjs/integrations/genai-stream.d.ts +19 -0
  18. package/dist/cjs/integrations/genai-stream.js +135 -0
  19. package/dist/cjs/integrations/genai.d.ts +18 -0
  20. package/dist/cjs/integrations/genai.js +150 -0
  21. package/dist/cjs/integrations/koa.d.ts +19 -0
  22. package/dist/cjs/integrations/koa.js +34 -0
  23. package/dist/cjs/integrations/lambda.d.ts +11 -0
  24. package/dist/cjs/integrations/lambda.js +68 -0
  25. package/dist/cjs/integrations/logs.d.ts +10 -0
  26. package/dist/cjs/integrations/logs.js +77 -0
  27. package/dist/cjs/integrations/nestjs.d.ts +16 -0
  28. package/dist/cjs/integrations/nestjs.js +30 -0
  29. package/dist/cjs/integrations/next.d.ts +11 -0
  30. package/dist/cjs/integrations/next.js +59 -0
  31. package/dist/cjs/integrations/prisma.d.ts +3 -0
  32. package/dist/cjs/integrations/prisma.js +33 -0
  33. package/dist/cjs/integrations/util.d.ts +9 -0
  34. package/dist/cjs/integrations/util.js +37 -0
  35. package/dist/cjs/jest.d.ts +21 -0
  36. package/dist/cjs/jest.js +45 -0
  37. package/dist/cjs/load.d.ts +1 -0
  38. package/dist/cjs/load.js +11 -0
  39. package/dist/cjs/metrics.d.ts +10 -0
  40. package/dist/cjs/metrics.js +81 -0
  41. package/dist/cjs/package.json +1 -0
  42. package/dist/cjs/payload.d.ts +42 -0
  43. package/dist/cjs/payload.js +145 -0
  44. package/dist/cjs/probes.d.ts +97 -0
  45. package/dist/cjs/probes.js +422 -0
  46. package/dist/cjs/profiling.d.ts +81 -0
  47. package/dist/cjs/profiling.js +253 -0
  48. package/dist/cjs/reporter-core.d.ts +32 -0
  49. package/dist/cjs/reporter-core.js +102 -0
  50. package/dist/cjs/test-plan.d.ts +93 -0
  51. package/dist/cjs/test-plan.js +262 -0
  52. package/dist/cjs/vitest.d.ts +27 -0
  53. package/dist/cjs/vitest.js +52 -0
  54. package/dist/esm/buffer.d.ts +49 -0
  55. package/dist/esm/buffer.js +92 -0
  56. package/dist/esm/errors.d.ts +17 -0
  57. package/dist/esm/errors.js +50 -0
  58. package/dist/esm/index.d.ts +120 -0
  59. package/dist/esm/index.js +251 -0
  60. package/dist/esm/integrations/azure-functions.d.ts +18 -0
  61. package/dist/esm/integrations/azure-functions.js +60 -0
  62. package/dist/esm/integrations/express.d.ts +25 -0
  63. package/dist/esm/integrations/express.js +54 -0
  64. package/dist/esm/integrations/fastify.d.ts +6 -0
  65. package/dist/esm/integrations/fastify.js +41 -0
  66. package/dist/esm/integrations/genai-agents.d.ts +36 -0
  67. package/dist/esm/integrations/genai-agents.js +118 -0
  68. package/dist/esm/integrations/genai-stream.d.ts +19 -0
  69. package/dist/esm/integrations/genai-stream.js +130 -0
  70. package/dist/esm/integrations/genai.d.ts +18 -0
  71. package/dist/esm/integrations/genai.js +138 -0
  72. package/dist/esm/integrations/koa.d.ts +19 -0
  73. package/dist/esm/integrations/koa.js +31 -0
  74. package/dist/esm/integrations/lambda.d.ts +11 -0
  75. package/dist/esm/integrations/lambda.js +32 -0
  76. package/dist/esm/integrations/logs.d.ts +10 -0
  77. package/dist/esm/integrations/logs.js +40 -0
  78. package/dist/esm/integrations/nestjs.d.ts +16 -0
  79. package/dist/esm/integrations/nestjs.js +26 -0
  80. package/dist/esm/integrations/next.d.ts +11 -0
  81. package/dist/esm/integrations/next.js +22 -0
  82. package/dist/esm/integrations/prisma.d.ts +3 -0
  83. package/dist/esm/integrations/prisma.js +30 -0
  84. package/dist/esm/integrations/util.d.ts +9 -0
  85. package/dist/esm/integrations/util.js +32 -0
  86. package/dist/esm/jest.d.ts +21 -0
  87. package/dist/esm/jest.js +41 -0
  88. package/dist/esm/load.d.ts +1 -0
  89. package/dist/esm/load.js +5 -0
  90. package/dist/esm/metrics.d.ts +10 -0
  91. package/dist/esm/metrics.js +44 -0
  92. package/dist/esm/package.json +1 -0
  93. package/dist/esm/payload.d.ts +42 -0
  94. package/dist/esm/payload.js +131 -0
  95. package/dist/esm/probes.d.ts +97 -0
  96. package/dist/esm/probes.js +412 -0
  97. package/dist/esm/profiling.d.ts +81 -0
  98. package/dist/esm/profiling.js +242 -0
  99. package/dist/esm/reporter-core.d.ts +32 -0
  100. package/dist/esm/reporter-core.js +63 -0
  101. package/dist/esm/test-plan.d.ts +93 -0
  102. package/dist/esm/test-plan.js +248 -0
  103. package/dist/esm/vitest.d.ts +27 -0
  104. package/dist/esm/vitest.js +48 -0
  105. package/package.json +219 -4
@@ -0,0 +1,130 @@
1
+ // Response, chunk and stream reading shared by every GenAI wrapper: tokens, finish reasons and tool calls
2
+ // from OpenAI, Anthropic, Mistral (camelCase) and Ollama shapes. Tool calls become `gen_ai.tool.call` span
3
+ // events with the tool name and call id only; prompt, completion and argument text is never recorded.
4
+ import { SpanStatusCode } from '@opentelemetry/api';
5
+ const obj = (v) => (v && typeof v === 'object' ? v : undefined);
6
+ const num = (...v) => v.find((x) => typeof x === 'number');
7
+ const str = (...v) => v.find((x) => typeof x === 'string' && x !== '');
8
+ const list = (v) => (Array.isArray(v) ? v : []);
9
+ function toolsOf(calls, out) {
10
+ for (const tc of list(calls)) {
11
+ const t = obj(tc);
12
+ const name = str(obj(t?.function)?.name);
13
+ if (name)
14
+ out.push([name, str(t?.id)]);
15
+ }
16
+ }
17
+ /** Reads a full response, a stream chunk or a stream event (`{ data }` for Mistral, typed events for Anthropic). */
18
+ export function extract(raw) {
19
+ let o = obj(raw) ?? {};
20
+ if (o.choices === undefined && o.type === undefined && obj(o.data))
21
+ o = obj(o.data);
22
+ const start = o.type === 'message_start' ? obj(o.message) : undefined;
23
+ const u = obj(o.usage) ?? obj(start?.usage) ?? {};
24
+ const g = obj(o.usageMetadata) ?? {};
25
+ const x = {
26
+ id: str(o.id, start?.id, o.responseId),
27
+ model: str(o.model, start?.model, o.modelVersion),
28
+ input: num(u.input_tokens, u.prompt_tokens, u.promptTokens, u.inputTokens, o.prompt_eval_count, g.promptTokenCount),
29
+ output: num(u.output_tokens, u.completion_tokens, u.completionTokens, u.outputTokens, o.eval_count, g.candidatesTokenCount),
30
+ reasons: [],
31
+ tools: [],
32
+ };
33
+ for (const ch of list(o.choices)) {
34
+ const c = obj(ch);
35
+ const r = str(c?.finish_reason, c?.finishReason);
36
+ if (r)
37
+ x.reasons.push(r);
38
+ const m = obj(c?.message) ?? obj(c?.delta);
39
+ toolsOf(m?.tool_calls ?? m?.toolCalls, x.tools);
40
+ }
41
+ for (const r of [o.stop_reason, obj(o.delta)?.stop_reason, o.done_reason, o.stopReason])
42
+ if (str(r))
43
+ x.reasons.push(r);
44
+ for (const b of list(o.content))
45
+ if (obj(b)?.type === 'tool_use')
46
+ x.tools.push([String(obj(b).name), str(obj(b).id)]);
47
+ const cb = obj(o.content_block);
48
+ if (cb?.type === 'tool_use')
49
+ x.tools.push([String(cb.name), str(cb.id)]);
50
+ if (o.choices === undefined)
51
+ toolsOf(obj(o.message)?.tool_calls, x.tools);
52
+ return x;
53
+ }
54
+ /** Sets what `x` holds; `seen` keeps a stream's tool calls from repeating. */
55
+ export function applyExtract(span, x, seen = new Set()) {
56
+ if (x.id)
57
+ span.setAttribute('gen_ai.response.id', x.id);
58
+ if (x.model)
59
+ span.setAttribute('gen_ai.response.model', x.model);
60
+ if (x.input != null)
61
+ span.setAttribute('gen_ai.usage.input_tokens', x.input);
62
+ if (x.output != null)
63
+ span.setAttribute('gen_ai.usage.output_tokens', x.output);
64
+ if (x.reasons.length)
65
+ span.setAttribute('gen_ai.response.finish_reasons', x.reasons);
66
+ for (const [name, id] of x.tools) {
67
+ const k = `${name}\u0000${id ?? ''}`;
68
+ if (seen.has(k))
69
+ continue;
70
+ seen.add(k);
71
+ span.addEvent('gen_ai.tool.call', { 'gen_ai.tool.name': name, ...(id ? { 'gen_ai.tool.call.id': id } : {}) });
72
+ }
73
+ }
74
+ /**
75
+ * Hooks the async iterator of a stream object in place (the caller keeps the SDK's own object): the span records
76
+ * time to first chunk, usage, finish reasons and tool calls, and ends when the stream ends, fails or is closed.
77
+ * False when `res` is not async iterable.
78
+ */
79
+ export function tapStream(span, res, startedMs) {
80
+ const s = obj(res);
81
+ const orig = s?.[Symbol.asyncIterator];
82
+ if (!s || typeof orig !== 'function')
83
+ return false;
84
+ let first = true, done = false;
85
+ const reasons = [], seen = new Set();
86
+ const end = (e) => {
87
+ if (done)
88
+ return;
89
+ done = true;
90
+ if (e !== undefined) {
91
+ span.recordException(e);
92
+ span.setStatus({ code: SpanStatusCode.ERROR, message: e?.message });
93
+ }
94
+ span.end();
95
+ };
96
+ s[Symbol.asyncIterator] = function () {
97
+ const inner = orig.call(s);
98
+ return {
99
+ async next() {
100
+ let r;
101
+ try {
102
+ r = await inner.next();
103
+ }
104
+ catch (e) {
105
+ end(e);
106
+ throw e;
107
+ }
108
+ if (r.done) {
109
+ end();
110
+ return r;
111
+ }
112
+ if (first) {
113
+ first = false;
114
+ span.setAttribute('gen_ai.response.time_to_first_chunk', (Date.now() - startedMs) / 1000);
115
+ }
116
+ const x = extract(r.value);
117
+ for (const q of x.reasons)
118
+ if (!reasons.includes(q))
119
+ reasons.push(q);
120
+ applyExtract(span, { ...x, reasons }, seen);
121
+ return r;
122
+ },
123
+ async return(v) {
124
+ end();
125
+ return inner.return ? inner.return(v) : { done: true, value: v };
126
+ },
127
+ };
128
+ };
129
+ return true;
130
+ }
@@ -0,0 +1,18 @@
1
+ export { instrumentLlamaIndex, instrumentOpenAIAgents } from './genai-agents.js';
2
+ /**
3
+ * instrumentOpenAI(new OpenAI()): chat.completions.create and responses.create. Returns the client.
4
+ * For an OpenAI-compatible gateway pass its name: instrumentOpenAI(new OpenAI({ baseURL: litellmUrl }), 'litellm').
5
+ */
6
+ export declare function instrumentOpenAI<T>(client: T, system?: string): T;
7
+ /** instrumentBedrock(new BedrockRuntimeClient()): `send` of Converse and InvokeModel commands; others pass through untraced. */
8
+ export declare function instrumentBedrock<T>(client: T): T;
9
+ /** instrumentGoogleGenAI(new GoogleGenAI({...})): models.generateContent (Gemini API or Vertex AI). */
10
+ export declare function instrumentGoogleGenAI<T>(client: T): T;
11
+ /** instrumentAnthropic(new Anthropic()): messages.create. Returns the client. */
12
+ export declare function instrumentAnthropic<T>(client: T): T;
13
+ /** instrumentMistral(new Mistral()): chat.complete and chat.stream (the stream span ends with the stream). */
14
+ export declare function instrumentMistral<T>(client: T): T;
15
+ /** instrumentOllama(new Ollama()) or instrumentOllama(ollama): chat and generate, with `stream: true` too. */
16
+ export declare function instrumentOllama<T>(client: T): T;
17
+ /** generateText({ ..., experimental_telemetry: vercelAiTelemetry() }); inputs/outputs off unless overridden. */
18
+ export declare function vercelAiTelemetry(o?: Record<string, unknown>): Record<string, unknown>;
@@ -0,0 +1,138 @@
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
3
+ // telemetry option for the Vercel AI SDK. Streams record time to first chunk, usage and tool calls (genai-stream.ts).
4
+ // Prompt and completion text is never recorded.
5
+ import { context, SpanKind, SpanStatusCode, trace } from '@opentelemetry/api';
6
+ import { applyExtract, extract, tapStream } from './genai-stream.js';
7
+ export { instrumentLlamaIndex, instrumentOpenAIAgents } from './genai-agents.js';
8
+ const DONE = Symbol('wt.instrumented');
9
+ const plain = (b) => (b || {});
10
+ function wrap(target, method, system, req = plain) {
11
+ if (!target || typeof target[method] !== 'function' || target[method][DONE])
12
+ return;
13
+ const orig = target[method];
14
+ const wrapped = function (body, ...rest) {
15
+ const b = req(body);
16
+ const started = Date.now();
17
+ const span = trace.getTracer('watchtower').startSpan(`chat ${b.model || ''}`.trim(), {
18
+ kind: SpanKind.CLIENT,
19
+ attributes: {
20
+ 'gen_ai.operation.name': 'chat',
21
+ 'gen_ai.system': system,
22
+ ...(b.model ? { 'gen_ai.request.model': b.model } : {}),
23
+ ...(b.max_tokens != null ? { 'gen_ai.request.max_tokens': b.max_tokens } : {}),
24
+ ...(b.temperature != null ? { 'gen_ai.request.temperature': b.temperature } : {}),
25
+ },
26
+ });
27
+ const p = context.with(trace.setSpan(context.active(), span), () => orig.call(this, body, ...rest));
28
+ // side branch only: the caller keeps the SDK's own promise (APIPromise helpers stay intact)
29
+ Promise.resolve(p).then((res) => {
30
+ // a stream keeps the span open until it ends (this runs before the caller's own continuation)
31
+ if (b.stream && tapStream(span, res, started))
32
+ return;
33
+ // the shared reader adds camelCase usage (Mistral), Ollama counts and tool calls
34
+ if (!b.stream && res) {
35
+ record(span, res);
36
+ applyExtract(span, extract(res));
37
+ }
38
+ span.end();
39
+ }, (e) => {
40
+ span.recordException(e);
41
+ span.setStatus({ code: SpanStatusCode.ERROR, message: e?.message });
42
+ span.end();
43
+ });
44
+ return p;
45
+ };
46
+ wrapped[DONE] = true;
47
+ target[method] = wrapped;
48
+ }
49
+ function record(span, res) {
50
+ const u = res.usage || {};
51
+ const g = res.usageMetadata || {};
52
+ const input = u.prompt_tokens ?? u.input_tokens ?? u.inputTokens ?? g.promptTokenCount;
53
+ const output = u.completion_tokens ?? u.output_tokens ?? u.outputTokens ?? g.candidatesTokenCount;
54
+ const one = res.stop_reason ?? res.stopReason;
55
+ const finish = Array.isArray(res.choices) ? res.choices.map((c) => c.finish_reason)
56
+ : Array.isArray(res.candidates) ? res.candidates.map((c) => c.finishReason) : one ? [one] : [];
57
+ const id = res.id ?? res.responseId ?? res.$metadata?.requestId;
58
+ const model = res.model ?? res.modelVersion;
59
+ if (id)
60
+ span.setAttribute('gen_ai.response.id', id);
61
+ if (model)
62
+ span.setAttribute('gen_ai.response.model', model);
63
+ if (finish.length)
64
+ span.setAttribute('gen_ai.response.finish_reasons', finish.filter((f) => Boolean(f)));
65
+ if (input != null)
66
+ span.setAttribute('gen_ai.usage.input_tokens', input);
67
+ if (output != null)
68
+ span.setAttribute('gen_ai.usage.output_tokens', output);
69
+ }
70
+ /**
71
+ * instrumentOpenAI(new OpenAI()): chat.completions.create and responses.create. Returns the client.
72
+ * For an OpenAI-compatible gateway pass its name: instrumentOpenAI(new OpenAI({ baseURL: litellmUrl }), 'litellm').
73
+ */
74
+ export function instrumentOpenAI(client, system = 'openai') {
75
+ const c = client;
76
+ wrap(c.chat && c.chat.completions, 'create', system);
77
+ wrap(c.responses, 'create', system);
78
+ return client;
79
+ }
80
+ /** instrumentBedrock(new BedrockRuntimeClient()): `send` of Converse and InvokeModel commands; others pass through untraced. */
81
+ export function instrumentBedrock(client) {
82
+ const c = client;
83
+ const send = c.send;
84
+ if (typeof send !== 'function' || send[DONE])
85
+ return client;
86
+ const traced = { send };
87
+ wrap(traced, 'send', 'aws.bedrock', (cmd) => {
88
+ const x = (cmd || {});
89
+ const name = (x.constructor && x.constructor.name) || '';
90
+ return { model: x.input?.modelId, max_tokens: x.input?.inferenceConfig?.maxTokens, temperature: x.input?.inferenceConfig?.temperature, stream: name.includes('Stream') };
91
+ });
92
+ const wrapped = function (cmd, ...rest) {
93
+ const name = (cmd?.constructor?.name) || '';
94
+ return /^(Converse|InvokeModel)/.test(name) ? traced.send.call(this, cmd, ...rest) : send.call(this, cmd, ...rest);
95
+ };
96
+ wrapped[DONE] = true;
97
+ c.send = wrapped;
98
+ return client;
99
+ }
100
+ /** instrumentGoogleGenAI(new GoogleGenAI({...})): models.generateContent (Gemini API or Vertex AI). */
101
+ export function instrumentGoogleGenAI(client) {
102
+ const c = client;
103
+ wrap(c.models, 'generateContent', c.vertexai ? 'vertex_ai' : 'gemini', (b) => {
104
+ const x = (b || {});
105
+ return { model: x.model, max_tokens: x.config?.maxOutputTokens, temperature: x.config?.temperature };
106
+ });
107
+ return client;
108
+ }
109
+ /** instrumentAnthropic(new Anthropic()): messages.create. Returns the client. */
110
+ export function instrumentAnthropic(client) {
111
+ wrap(client.messages, 'create', 'anthropic');
112
+ return client;
113
+ }
114
+ /** instrumentMistral(new Mistral()): chat.complete and chat.stream (the stream span ends with the stream). */
115
+ export function instrumentMistral(client) {
116
+ const c = client.chat;
117
+ wrap(c, 'complete', 'mistral_ai', mistralReq);
118
+ wrap(c, 'stream', 'mistral_ai', (b) => ({ ...mistralReq(b), stream: true }));
119
+ return client;
120
+ }
121
+ const mistralReq = (b) => {
122
+ const x = (b || {});
123
+ return { model: x.model, max_tokens: x.maxTokens, temperature: x.temperature };
124
+ };
125
+ /** instrumentOllama(new Ollama()) or instrumentOllama(ollama): chat and generate, with `stream: true` too. */
126
+ export function instrumentOllama(client) {
127
+ const ollamaReq = (b) => {
128
+ const x = (b || {});
129
+ return { model: x.model, stream: x.stream, max_tokens: x.options?.num_predict, temperature: x.options?.temperature };
130
+ };
131
+ wrap(client, 'chat', 'ollama', ollamaReq);
132
+ wrap(client, 'generate', 'ollama', ollamaReq);
133
+ return client;
134
+ }
135
+ /** generateText({ ..., experimental_telemetry: vercelAiTelemetry() }); inputs/outputs off unless overridden. */
136
+ export function vercelAiTelemetry(o) {
137
+ return { isEnabled: true, recordInputs: false, recordOutputs: false, tracer: trace.getTracer('watchtower'), ...o };
138
+ }
@@ -0,0 +1,19 @@
1
+ /** The slice of a Koa context this integration reads. */
2
+ export interface KoaContext {
3
+ method: string;
4
+ path: string;
5
+ status: number;
6
+ _matchedRoute?: string;
7
+ /** `body` is set by a body parser (koa-bodyparser, koa-body) for payload capture. */
8
+ request?: {
9
+ body?: unknown;
10
+ type?: string;
11
+ };
12
+ /** The response body the handler set (payload capture; streams are skipped). */
13
+ body?: unknown;
14
+ response?: {
15
+ type?: string;
16
+ };
17
+ }
18
+ /** app.use(middleware()) first: server span per request, errors captured then rethrown. */
19
+ export declare function middleware(): (ctx: KoaContext, next: () => Promise<unknown>) => Promise<void>;
@@ -0,0 +1,31 @@
1
+ import { context } from '@opentelemetry/api';
2
+ import { captureException } from '../errors.js';
3
+ import { capturePayload, captureActive } from '../payload.js';
4
+ import { serverSpan, statusOf } from './util.js';
5
+ /** app.use(middleware()) first: server span per request, errors captured then rethrown. */
6
+ export function middleware() {
7
+ return async (ctx, next) => {
8
+ const s = serverSpan(ctx.method, ctx.path);
9
+ let status;
10
+ try {
11
+ await context.with(s.ctx, next);
12
+ status = ctx.status;
13
+ }
14
+ catch (e) {
15
+ status = statusOf(e);
16
+ if (status >= 500)
17
+ context.with(s.ctx, () => captureException(e));
18
+ throw e;
19
+ }
20
+ finally {
21
+ if (captureActive()) {
22
+ capturePayload(s.span, {
23
+ route: ctx._matchedRoute || ctx.path,
24
+ reqType: ctx.request?.type, reqBody: ctx.request?.body,
25
+ resType: ctx.response?.type, resBody: ctx.body,
26
+ });
27
+ }
28
+ s.finish(status, ctx._matchedRoute);
29
+ }
30
+ };
31
+ }
@@ -0,0 +1,11 @@
1
+ /** The slice of the Lambda context this wrapper reads. */
2
+ export interface LambdaContextLike {
3
+ functionName?: string;
4
+ awsRequestId?: string;
5
+ invokedFunctionArn?: string;
6
+ }
7
+ /** exports.handler = wrapHandler(async (event, context) => ...). Async handlers only. Flushes before the
8
+ * runtime freezes, otherwise buffered spans are lost. */
9
+ export declare function wrapHandler<E, R, C extends LambdaContextLike = LambdaContextLike>(handler: (event: E, context: C) => Promise<R>, o?: {
10
+ name?: string;
11
+ }): (event: E, context: C) => Promise<R>;
@@ -0,0 +1,32 @@
1
+ import { SpanKind, trace } from '@opentelemetry/api';
2
+ import { captureException } from '../errors.js';
3
+ import * as wt from '../index.js';
4
+ /** exports.handler = wrapHandler(async (event, context) => ...). Async handlers only. Flushes before the
5
+ * runtime freezes, otherwise buffered spans are lost. */
6
+ export function wrapHandler(handler, o) {
7
+ const x = o || {};
8
+ return async (event, context) => {
9
+ const c = context || {};
10
+ return trace.getTracer('watchtower').startActiveSpan(x.name || c.functionName || 'lambda', {
11
+ kind: SpanKind.SERVER,
12
+ attributes: {
13
+ 'cloud.provider': 'aws',
14
+ 'faas.name': c.functionName,
15
+ 'faas.invocation_id': c.awsRequestId,
16
+ 'cloud.resource_id': c.invokedFunctionArn,
17
+ },
18
+ }, async (span) => {
19
+ try {
20
+ return await handler(event, context);
21
+ }
22
+ catch (e) {
23
+ captureException(e, { handled: false, attributes: { 'error.mechanism': 'lambda' } });
24
+ throw e;
25
+ }
26
+ finally {
27
+ span.end();
28
+ await wt.flush().catch(() => { });
29
+ }
30
+ });
31
+ };
32
+ }
@@ -0,0 +1,10 @@
1
+ /** Anything with a `log` method, e.g. a `Client`. */
2
+ export interface LogSink {
3
+ log(level: string, body: string, attrs?: Record<string, unknown>): void;
4
+ }
5
+ /** pino(opts, pinoStream()) or pino.multistream([{ stream: pinoStream() }, { stream: process.stdout }]). */
6
+ export declare function pinoStream(client?: LogSink): {
7
+ write(line: string): void;
8
+ };
9
+ /** logger.add(watchtowerTransport()). Needs `winston-transport`, which winston always installs. */
10
+ export declare function watchtowerTransport(client?: LogSink): object;
@@ -0,0 +1,40 @@
1
+ // Logs bridges: pino and winston records become OTLP logs carrying the active trace and span ids.
2
+ import * as wt from '../index.js';
3
+ import { load } from '../load.js';
4
+ const defaultSink = { log: (level, body, attrs) => wt.log(level, body, attrs) };
5
+ const PINO = { 10: 'trace', 20: 'debug', 30: 'info', 40: 'warn', 50: 'error', 60: 'fatal' };
6
+ const CORE = new Set(['level', 'time', 'msg', 'pid', 'hostname', 'v']);
7
+ const flat = (o, skip) => {
8
+ const attrs = {};
9
+ for (const [k, v] of Object.entries(o))
10
+ if (!skip || !skip.has(k))
11
+ attrs[k] = typeof v === 'object' ? JSON.stringify(v) : v;
12
+ return attrs;
13
+ };
14
+ /** pino(opts, pinoStream()) or pino.multistream([{ stream: pinoStream() }, { stream: process.stdout }]). */
15
+ export function pinoStream(client) {
16
+ return {
17
+ write(line) {
18
+ let r;
19
+ try {
20
+ r = JSON.parse(line);
21
+ }
22
+ catch (_) {
23
+ return;
24
+ }
25
+ (client || defaultSink).log(PINO[r.level] || 'info', r.msg || '', flat(r, CORE));
26
+ },
27
+ };
28
+ }
29
+ const WINSTON = { silly: 'trace', debug: 'debug', verbose: 'debug', http: 'info', info: 'info', warn: 'warn', error: 'error' };
30
+ /** logger.add(watchtowerTransport()). Needs `winston-transport`, which winston always installs. */
31
+ export function watchtowerTransport(client) {
32
+ const Transport = load('winston-transport');
33
+ return new (class extends Transport {
34
+ log(info, cb) {
35
+ const { level, message, ...rest } = info;
36
+ (client || defaultSink).log(WINSTON[level] || 'info', String(message), flat(rest));
37
+ cb();
38
+ }
39
+ })();
40
+ }
@@ -0,0 +1,16 @@
1
+ /** The slice of Nest's ExecutionContext this interceptor reads. */
2
+ export interface NestExecutionContext {
3
+ getClass(): {
4
+ name: string;
5
+ };
6
+ getHandler(): {
7
+ name: string;
8
+ };
9
+ }
10
+ /** app.useGlobalInterceptors(new WatchtowerInterceptor()): captures 5xx errors with controller and handler names.
11
+ * Duck-typed over the rxjs Observable (no rxjs import); pair with the express or fastify integration for spans. */
12
+ export declare class WatchtowerInterceptor {
13
+ intercept(execCtx: NestExecutionContext, next: {
14
+ handle(): any;
15
+ }): any;
16
+ }
@@ -0,0 +1,26 @@
1
+ import { captureException } from '../errors.js';
2
+ import { statusOf } from './util.js';
3
+ /** app.useGlobalInterceptors(new WatchtowerInterceptor()): captures 5xx errors with controller and handler names.
4
+ * Duck-typed over the rxjs Observable (no rxjs import); pair with the express or fastify integration for spans. */
5
+ export class WatchtowerInterceptor {
6
+ // `any`: the Observable is rxjs's, which this package deliberately does not import.
7
+ intercept(execCtx, next) {
8
+ const where = {};
9
+ try {
10
+ where['code.namespace'] = execCtx.getClass().name;
11
+ where['code.function'] = execCtx.getHandler().name;
12
+ }
13
+ catch (_) { /* non-http context */ }
14
+ const source = next.handle();
15
+ return source.pipe((src) => new src.constructor((sub) => src.subscribe({
16
+ next: (v) => sub.next(v),
17
+ error: (e) => {
18
+ const status = typeof e.getStatus === 'function' ? e.getStatus() : statusOf(e);
19
+ if (status >= 500)
20
+ captureException(e, { attributes: where });
21
+ sub.error(e);
22
+ },
23
+ complete: () => sub.complete(),
24
+ })));
25
+ }
26
+ }
@@ -0,0 +1,11 @@
1
+ /** 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>;
3
+ /** Next.js onRequestError: server render, route handler and server action errors. */
4
+ export declare function onRequestError(err: unknown, request?: {
5
+ path?: string;
6
+ method?: string;
7
+ }, context?: {
8
+ routerKind?: string;
9
+ routePath?: string;
10
+ routeType?: string;
11
+ }): Promise<void>;
@@ -0,0 +1,22 @@
1
+ // instrumentation.js: module.exports = require('@watchtowerobservability/node/next');
2
+ 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({});
9
+ }
10
+ /** Next.js onRequestError: server render, route handler and server action errors. */
11
+ export async function onRequestError(err, request, context) {
12
+ const c = context || {};
13
+ wt.captureException(err, {
14
+ attributes: {
15
+ 'http.request.method': request && request.method,
16
+ 'url.path': request && request.path && String(request.path).split('?')[0],
17
+ 'http.route': c.routePath,
18
+ 'next.router_kind': c.routerKind,
19
+ 'next.route_type': c.routeType,
20
+ },
21
+ });
22
+ }
@@ -0,0 +1,3 @@
1
+ /** prisma.$extends(watchtowerExtension()): a CLIENT span per model operation (no query args recorded: they hold data).
2
+ * shortcut: $queryRaw/$executeRaw are not wrapped; add query.$queryRaw hooks if raw SQL spans are needed. */
3
+ export declare function watchtowerExtension(): object;
@@ -0,0 +1,30 @@
1
+ import { SpanKind, SpanStatusCode, trace } from '@opentelemetry/api';
2
+ /** prisma.$extends(watchtowerExtension()): a CLIENT span per model operation (no query args recorded: they hold data).
3
+ * shortcut: $queryRaw/$executeRaw are not wrapped; add query.$queryRaw hooks if raw SQL spans are needed. */
4
+ export function watchtowerExtension() {
5
+ return {
6
+ name: 'watchtower',
7
+ query: {
8
+ $allModels: {
9
+ $allOperations({ model, operation, query, args }) {
10
+ return trace.getTracer('watchtower').startActiveSpan(`prisma ${model}.${operation}`, {
11
+ kind: SpanKind.CLIENT,
12
+ attributes: { 'db.system.name': 'prisma', 'db.collection.name': model, 'db.operation.name': operation },
13
+ }, async (span) => {
14
+ try {
15
+ return await query(args);
16
+ }
17
+ catch (e) {
18
+ span.recordException(e);
19
+ span.setStatus({ code: SpanStatusCode.ERROR, message: e.message });
20
+ throw e;
21
+ }
22
+ finally {
23
+ span.end();
24
+ }
25
+ });
26
+ },
27
+ },
28
+ },
29
+ };
30
+ }
@@ -0,0 +1,9 @@
1
+ import type { Context, Span } from '@opentelemetry/api';
2
+ export interface ServerSpan {
3
+ span: Span;
4
+ ctx: Context;
5
+ finish(status?: number, route?: string): void;
6
+ }
7
+ /** Start a server span; finish(status, route) names it `METHOD route` and ends it once. */
8
+ export declare function serverSpan(method: string, path?: string): ServerSpan;
9
+ export declare const statusOf: (e: unknown) => number;
@@ -0,0 +1,32 @@
1
+ import { context, trace, SpanKind, SpanStatusCode } from '@opentelemetry/api';
2
+ /** Start a server span; finish(status, route) names it `METHOD route` and ends it once. */
3
+ export function serverSpan(method, path) {
4
+ // url.path only: query strings can carry secrets
5
+ const span = trace.getTracer('watchtower').startSpan(method, {
6
+ kind: SpanKind.SERVER,
7
+ attributes: { 'http.request.method': method, 'url.path': String(path || '').split('?')[0] },
8
+ });
9
+ let done = false;
10
+ return {
11
+ span,
12
+ ctx: trace.setSpan(context.active(), span),
13
+ finish(status, route) {
14
+ if (done)
15
+ return;
16
+ done = true;
17
+ if (route) {
18
+ span.updateName(`${method} ${route}`);
19
+ span.setAttribute('http.route', route);
20
+ }
21
+ if (status)
22
+ span.setAttribute('http.response.status_code', status);
23
+ if (status !== undefined && status >= 500)
24
+ span.setStatus({ code: SpanStatusCode.ERROR });
25
+ span.end();
26
+ },
27
+ };
28
+ }
29
+ export const statusOf = (e) => {
30
+ const x = e;
31
+ return (x && (x.status || x.statusCode)) || 500;
32
+ };
@@ -0,0 +1,21 @@
1
+ import type { ReporterOptions } from './reporter-core.js';
2
+ /** The slice of Jest's `TestResult` this reporter reads. */
3
+ export interface JestTestResult {
4
+ testFilePath?: string;
5
+ testResults?: {
6
+ fullName?: string;
7
+ ancestorTitles?: string[];
8
+ title: string;
9
+ status?: string;
10
+ duration?: number | null;
11
+ failureMessages?: string[];
12
+ invocations?: number;
13
+ }[];
14
+ }
15
+ export default class WatchtowerJestReporter {
16
+ private readonly client;
17
+ private readonly tests;
18
+ constructor(_globalConfig?: unknown, options?: ReporterOptions);
19
+ onTestResult(_test: unknown, result: JestTestResult): void;
20
+ onRunComplete(): Promise<void>;
21
+ }
@@ -0,0 +1,41 @@
1
+ // Jest reporter: `reporters: ['default', ['@watchtowerobservability/node/jest', { /* apiKey, client, ... */ }]]`.
2
+ // With the test-plan environment (test-plan.ts) a quarantined failure arrives as a pending test that
3
+ // still carries its failure message; it is reported as a quarantined failure. Uploads JUnit when
4
+ // WT_CI_RUN_ID is set.
5
+ import { clientFor, reportTests, outcome } from './reporter-core.js';
6
+ import { decider, loadPlan, suiteName, testId, uploadResults } from './test-plan.js';
7
+ export default class WatchtowerJestReporter {
8
+ client;
9
+ tests = [];
10
+ constructor(_globalConfig, options) {
11
+ this.client = clientFor(options);
12
+ }
13
+ onTestResult(_test, result) {
14
+ const end = Date.now();
15
+ const decide = decider(loadPlan());
16
+ for (const t of result.testResults || []) {
17
+ const names = (t.ancestorTitles || []).concat(t.title);
18
+ const id = testId(suiteName('jest'), result.testFilePath, names);
19
+ const d = decide(id);
20
+ const failures = t.failureMessages || [];
21
+ const qFail = d.quarantined !== undefined && t.status === 'pending' && failures.length > 0;
22
+ this.tests.push({
23
+ name: t.fullName || names.join(' '),
24
+ id,
25
+ outcome: qFail ? 'failed' : outcome(t.status),
26
+ durationMs: t.duration || 0,
27
+ message: failures[0],
28
+ endMs: end,
29
+ quarantined: qFail ? d.quarantined : undefined,
30
+ isNew: d.isNew,
31
+ attempts: Math.max(0, (t.invocations || 1) - 1),
32
+ });
33
+ }
34
+ }
35
+ async onRunComplete() {
36
+ await reportTests(this.client, this.tests, 'jest');
37
+ await uploadResults(this.client, suiteName('jest'), this.tests);
38
+ if (this.client)
39
+ await this.client.shutdown().catch(() => { });
40
+ }
41
+ }