@watchtowerobservability/node 0.7.4 → 0.7.5

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 (89) hide show
  1. package/CHANGELOG.md +36 -1
  2. package/README.md +96 -12
  3. package/dist/cjs/attach.d.ts +7 -0
  4. package/dist/cjs/attach.js +29 -0
  5. package/dist/cjs/checkin.js +4 -13
  6. package/dist/cjs/cron/monitor.d.ts +47 -0
  7. package/dist/cjs/cron/monitor.js +95 -0
  8. package/dist/cjs/cron/schedulers.d.ts +36 -0
  9. package/dist/cjs/cron/schedulers.js +65 -0
  10. package/dist/cjs/env.d.ts +10 -0
  11. package/dist/cjs/env.js +98 -1
  12. package/dist/cjs/index.d.ts +50 -6
  13. package/dist/cjs/index.js +114 -37
  14. package/dist/cjs/instrument-for.d.ts +17 -0
  15. package/dist/cjs/instrument-for.js +44 -0
  16. package/dist/cjs/instrument.d.ts +4 -0
  17. package/dist/cjs/instrument.js +32 -1
  18. package/dist/cjs/integrations/bullmq.d.ts +8 -2
  19. package/dist/cjs/integrations/bullmq.js +32 -5
  20. package/dist/cjs/integrations/db.d.ts +7 -2
  21. package/dist/cjs/integrations/db.js +32 -4
  22. package/dist/cjs/integrations/fastify.d.ts +1 -1
  23. package/dist/cjs/integrations/fastify.js +3 -2
  24. package/dist/cjs/integrations/logs.js +16 -5
  25. package/dist/cjs/integrations/next-build.d.ts +25 -8
  26. package/dist/cjs/integrations/next-build.js +159 -34
  27. package/dist/cjs/integrations/next-tunnel.d.ts +6 -1
  28. package/dist/cjs/integrations/next-tunnel.js +13 -2
  29. package/dist/cjs/integrations/postgres.d.ts +2 -0
  30. package/dist/cjs/integrations/postgres.js +43 -1
  31. package/dist/cjs/integrations/temporal.d.ts +97 -0
  32. package/dist/cjs/integrations/temporal.js +144 -0
  33. package/dist/cjs/integrations/util.d.ts +17 -0
  34. package/dist/cjs/integrations/util.js +38 -0
  35. package/dist/cjs/load.d.ts +6 -0
  36. package/dist/cjs/load.js +28 -4
  37. package/dist/cjs/next-doctor-cli.d.ts +2 -0
  38. package/dist/cjs/next-doctor-cli.js +15 -0
  39. package/dist/cjs/next-doctor.d.ts +2 -0
  40. package/dist/cjs/next-doctor.js +50 -0
  41. package/dist/cjs/redact-presets.d.ts +16 -0
  42. package/dist/cjs/redact-presets.js +66 -0
  43. package/dist/cjs/register.js +19 -6
  44. package/dist/cjs/version.d.ts +1 -1
  45. package/dist/cjs/version.js +1 -1
  46. package/dist/esm/attach.d.ts +7 -0
  47. package/dist/esm/attach.js +25 -0
  48. package/dist/esm/checkin.js +4 -13
  49. package/dist/esm/cron/monitor.d.ts +47 -0
  50. package/dist/esm/cron/monitor.js +85 -0
  51. package/dist/esm/cron/schedulers.d.ts +36 -0
  52. package/dist/esm/cron/schedulers.js +61 -0
  53. package/dist/esm/env.d.ts +10 -0
  54. package/dist/esm/env.js +62 -0
  55. package/dist/esm/index.d.ts +50 -6
  56. package/dist/esm/index.js +109 -39
  57. package/dist/esm/instrument-for.d.ts +17 -0
  58. package/dist/esm/instrument-for.js +41 -0
  59. package/dist/esm/instrument.d.ts +4 -0
  60. package/dist/esm/instrument.js +30 -1
  61. package/dist/esm/integrations/bullmq.d.ts +8 -2
  62. package/dist/esm/integrations/bullmq.js +32 -5
  63. package/dist/esm/integrations/db.d.ts +7 -2
  64. package/dist/esm/integrations/db.js +29 -4
  65. package/dist/esm/integrations/fastify.d.ts +1 -1
  66. package/dist/esm/integrations/fastify.js +4 -3
  67. package/dist/esm/integrations/logs.js +16 -5
  68. package/dist/esm/integrations/next-build.d.ts +25 -8
  69. package/dist/esm/integrations/next-build.js +158 -34
  70. package/dist/esm/integrations/next-tunnel.d.ts +6 -1
  71. package/dist/esm/integrations/next-tunnel.js +13 -2
  72. package/dist/esm/integrations/postgres.d.ts +2 -0
  73. package/dist/esm/integrations/postgres.js +43 -2
  74. package/dist/esm/integrations/temporal.d.ts +97 -0
  75. package/dist/esm/integrations/temporal.js +139 -0
  76. package/dist/esm/integrations/util.d.ts +17 -0
  77. package/dist/esm/integrations/util.js +35 -0
  78. package/dist/esm/load.d.ts +6 -0
  79. package/dist/esm/load.js +21 -3
  80. package/dist/esm/next-doctor-cli.d.ts +2 -0
  81. package/dist/esm/next-doctor-cli.js +13 -0
  82. package/dist/esm/next-doctor.d.ts +2 -0
  83. package/dist/esm/next-doctor.js +14 -0
  84. package/dist/esm/redact-presets.d.ts +16 -0
  85. package/dist/esm/redact-presets.js +58 -0
  86. package/dist/esm/register.js +20 -7
  87. package/dist/esm/version.d.ts +1 -1
  88. package/dist/esm/version.js +1 -1
  89. package/package.json +42 -1
@@ -1,2 +1,2 @@
1
1
  /** This package's version (test/distro.test.ts checks it against package.json); sent as `telemetry.distro.version`. */
2
- export declare const VERSION = "0.7.4";
2
+ export declare const VERSION = "0.7.5";
@@ -2,4 +2,4 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.VERSION = void 0;
4
4
  /** This package's version (test/distro.test.ts checks it against package.json); sent as `telemetry.distro.version`. */
5
- exports.VERSION = '0.7.4';
5
+ exports.VERSION = '0.7.5';
@@ -0,0 +1,7 @@
1
+ /** The real provider behind the global proxy, or undefined when none (or only the no-op one) is registered. */
2
+ export declare function foreignProvider(): any;
3
+ /**
4
+ * Add processors to `provider`: `addSpanProcessor` (sdk-trace v1) or the v2 `_activeSpanProcessor._spanProcessors` list.
5
+ * shortcut: v2+ has no public hook, so this reaches into a private field; replace when the SDK adds one.
6
+ */
7
+ export declare function attachProcessors(provider: any, procs: unknown[]): boolean;
@@ -0,0 +1,25 @@
1
+ // Coexistence with another OpenTelemetry setup (Sentry, a vendor agent): find the tracer provider already registered
2
+ // globally and add our span processors to it instead of replacing it.
3
+ import { trace } from '@opentelemetry/api';
4
+ /** The real provider behind the global proxy, or undefined when none (or only the no-op one) is registered. */
5
+ export function foreignProvider() {
6
+ const g = trace.getTracerProvider();
7
+ const d = typeof g?.getDelegate === 'function' ? g.getDelegate() : g;
8
+ return !d || d.constructor?.name === 'NoopTracerProvider' || d.constructor?.name === 'ProxyTracerProvider' ? undefined : d;
9
+ }
10
+ /**
11
+ * Add processors to `provider`: `addSpanProcessor` (sdk-trace v1) or the v2 `_activeSpanProcessor._spanProcessors` list.
12
+ * shortcut: v2+ has no public hook, so this reaches into a private field; replace when the SDK adds one.
13
+ */
14
+ export function attachProcessors(provider, procs) {
15
+ if (typeof provider.addSpanProcessor === 'function') {
16
+ for (const p of procs)
17
+ provider.addSpanProcessor(p);
18
+ return true;
19
+ }
20
+ const list = provider._activeSpanProcessor?._spanProcessors;
21
+ if (!Array.isArray(list))
22
+ return false;
23
+ list.push(...procs);
24
+ return true;
25
+ }
@@ -1,15 +1,6 @@
1
+ // Cron / scheduler check-ins: POST /v1/checkins/{slug} (key scope `ingest:checkins`; the edge accepts 6 a minute per monitor).
2
+ import { withMonitor } from './cron/monitor.js';
1
3
  /** Send `in_progress`, run `fn`, then send `ok` or `error` with its duration. Check-in failures never affect `fn`; its result or error is passed through. */
2
- export async function checkin(c, slug, fn) {
3
- const send = (status, ms) => c.fetch(`${c.endpoint}/v1/checkins/${encodeURIComponent(slug)}?status=${status}${ms === undefined ? '' : `&duration_ms=${Math.min(ms, 86_400_000)}`}`, { method: 'POST', headers: c.headers }).catch(() => undefined);
4
- await send('in_progress');
5
- const t = Date.now();
6
- try {
7
- const r = await fn();
8
- await send('ok', Date.now() - t);
9
- return r;
10
- }
11
- catch (e) {
12
- await send('error', Date.now() - t);
13
- throw e;
14
- }
4
+ export function checkin(c, slug, fn) {
5
+ return withMonitor(c, slug, fn, { wait: true });
15
6
  }
@@ -0,0 +1,47 @@
1
+ import type { CheckinTarget } from '../checkin.js';
2
+ export type CheckInStatus = 'in_progress' | 'ok' | 'error';
3
+ /** Sent in the check-in body so the server can create or update the monitor on first contact (Sentry's `monitor_config` shape, minutes). */
4
+ export interface MonitorConfig {
5
+ schedule: {
6
+ type: 'crontab';
7
+ value: string;
8
+ };
9
+ timezone?: string;
10
+ checkin_margin_m?: number;
11
+ max_runtime_m?: number;
12
+ failure_threshold?: number;
13
+ }
14
+ export interface MonitorOptions {
15
+ /** Crontab, 5 fields (or 6 with leading seconds, which are dropped when they are `0`). */
16
+ schedule?: string;
17
+ timezone?: string;
18
+ /** Minutes a check-in may be late before it counts as missed. */
19
+ checkinMargin?: number;
20
+ /** Minutes a run may stay `in_progress` before it counts as failed. */
21
+ maxRuntime?: number;
22
+ /** Consecutive failures before an issue opens. */
23
+ failureThreshold?: number;
24
+ /** Await the check-in requests (default false: fire and forget, capped at 5 s). Use it in short-lived processes. */
25
+ wait?: boolean;
26
+ }
27
+ export interface CheckInOptions {
28
+ wait?: boolean;
29
+ durationMs?: number;
30
+ monitorConfig?: MonitorConfig;
31
+ /** Default 5000. */
32
+ timeoutMs?: number;
33
+ }
34
+ /** The client `init()` made (the one per-process state `index.ts` keeps), without importing it. */
35
+ export declare function currentTarget(): CheckinTarget | undefined;
36
+ /** Check-ins are served by the edge host, not the OTLP gateway: `ingest.x` becomes `edge.x`. `WT_CHECKIN_URL` overrides. */
37
+ export declare function checkinBase(endpoint: string): string;
38
+ export declare function normalizeCron(expr: string): string;
39
+ export declare function toConfig(o: MonitorOptions): MonitorConfig | undefined;
40
+ /** Send one check-in. Never throws or rejects; without `wait` it returns at once and the request is capped at 5 s. */
41
+ export declare function checkIn(c: CheckinTarget, slug: string, status: CheckInStatus, o?: CheckInOptions): Promise<void>;
42
+ /** Run `fn` as a monitored job: `in_progress`, then `ok` or `error` with the duration. Returns fn's result or rethrows its error; check-in failures never reach it. */
43
+ export declare function withMonitor<T>(c: CheckinTarget, slug: string, fn: () => T | Promise<T>, o?: MonitorOptions): Promise<T>;
44
+ /** Lowercase kebab slug of a job or method name (`MyService.nightlyReport` -> `my-service-nightly-report`). Empty for a uuid. */
45
+ export declare function slugify(name: string): string;
46
+ /** `withMonitor` against the client `init()` made; just runs `fn` when there is none. */
47
+ export declare function monitorJob<T>(slug: string, fn: () => T | Promise<T>, o?: MonitorOptions): Promise<T>;
@@ -0,0 +1,85 @@
1
+ // Cron monitor check-ins: POST {edge}/v1/checkins/{slug} (key scope `ingest:checkins`; the edge accepts 6 a minute per monitor).
2
+ import { context } from '@opentelemetry/api';
3
+ /** The client `init()` made (the one per-process state `index.ts` keeps), without importing it. */
4
+ export function currentTarget() {
5
+ const s = globalThis[Symbol.for('watchtower.node.state')];
6
+ return s?.current;
7
+ }
8
+ /** Check-ins are served by the edge host, not the OTLP gateway: `ingest.x` becomes `edge.x`. `WT_CHECKIN_URL` overrides. */
9
+ export function checkinBase(endpoint) {
10
+ const env = process.env.WT_CHECKIN_URL;
11
+ if (env)
12
+ return env.replace(/\/+$/, '');
13
+ return endpoint.replace(/^(https?:\/\/)ingest\./i, '$1edge.');
14
+ }
15
+ // `0 */5 * * * *` -> `*/5 * * * *`; a 6-field expression with another seconds value stays as it is.
16
+ export function normalizeCron(expr) {
17
+ const f = expr.trim().split(/\s+/);
18
+ return f.length === 6 && /^0+$/.test(f[0]) ? f.slice(1).join(' ') : f.join(' ');
19
+ }
20
+ export function toConfig(o) {
21
+ if (typeof o.schedule !== 'string' || !o.schedule.trim())
22
+ return undefined;
23
+ const c = { schedule: { type: 'crontab', value: normalizeCron(o.schedule) } };
24
+ if (o.timezone)
25
+ c.timezone = o.timezone;
26
+ if (o.checkinMargin !== undefined)
27
+ c.checkin_margin_m = o.checkinMargin;
28
+ if (o.maxRuntime !== undefined)
29
+ c.max_runtime_m = o.maxRuntime;
30
+ if (o.failureThreshold !== undefined)
31
+ c.failure_threshold = o.failureThreshold;
32
+ return c;
33
+ }
34
+ // The OTel SDK's own key (`@opentelemetry/core` suppressTracing), so our HTTP call makes no span.
35
+ const SUPPRESS = Symbol.for('OpenTelemetry SDK Context Key SUPPRESS_TRACING');
36
+ /** Send one check-in. Never throws or rejects; without `wait` it returns at once and the request is capped at 5 s. */
37
+ export function checkIn(c, slug, status, o = {}) {
38
+ const ms = o.durationMs === undefined ? undefined : Math.min(Math.max(Math.round(o.durationMs), 0), 86_400_000);
39
+ const url = `${checkinBase(c.endpoint)}/v1/checkins/${encodeURIComponent(slug)}?status=${status}${ms === undefined ? '' : `&duration_ms=${ms}`}`;
40
+ const body = { status };
41
+ if (ms !== undefined)
42
+ body.duration_ms = ms;
43
+ if (o.monitorConfig)
44
+ body.monitor_config = o.monitorConfig;
45
+ const ac = new AbortController();
46
+ const timer = setTimeout(() => ac.abort(), o.timeoutMs ?? 5000);
47
+ timer.unref?.();
48
+ let p;
49
+ try {
50
+ p = context.with(context.active().setValue(SUPPRESS, true), () => c.fetch(url, { method: 'POST', headers: { ...c.headers, 'Content-Type': 'application/json' }, body: JSON.stringify(body), signal: ac.signal }))
51
+ .then(() => undefined, () => undefined);
52
+ }
53
+ catch {
54
+ p = Promise.resolve();
55
+ }
56
+ p = p.finally(() => clearTimeout(timer));
57
+ return o.wait ? p : Promise.resolve();
58
+ }
59
+ /** Run `fn` as a monitored job: `in_progress`, then `ok` or `error` with the duration. Returns fn's result or rethrows its error; check-in failures never reach it. */
60
+ export async function withMonitor(c, slug, fn, o = {}) {
61
+ const monitorConfig = toConfig(o);
62
+ const send = (status, durationMs) => checkIn(c, slug, status, { wait: o.wait, durationMs, monitorConfig });
63
+ await send('in_progress');
64
+ const t = Date.now();
65
+ try {
66
+ const r = await fn();
67
+ await send('ok', Date.now() - t);
68
+ return r;
69
+ }
70
+ catch (e) {
71
+ await send('error', Date.now() - t);
72
+ throw e;
73
+ }
74
+ }
75
+ /** Lowercase kebab slug of a job or method name (`MyService.nightlyReport` -> `my-service-nightly-report`). Empty for a uuid. */
76
+ export function slugify(name) {
77
+ if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(name))
78
+ return '';
79
+ return name.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 64);
80
+ }
81
+ /** `withMonitor` against the client `init()` made; just runs `fn` when there is none. */
82
+ export function monitorJob(slug, fn, o = {}) {
83
+ const c = currentTarget();
84
+ return c ? withMonitor(c, slug, fn, o) : Promise.resolve().then(fn);
85
+ }
@@ -0,0 +1,36 @@
1
+ type Fn = (...a: any[]) => unknown;
2
+ declare const DONE: unique symbol;
3
+ interface CronJobLike {
4
+ cronTime?: {
5
+ source?: unknown;
6
+ zone?: unknown;
7
+ timeZone?: unknown;
8
+ };
9
+ _callbacks?: Fn[];
10
+ [DONE]?: boolean;
11
+ }
12
+ interface SchedulerRegistryLike {
13
+ addCronJob: (name: string, job: CronJobLike) => unknown;
14
+ getCronJobs: () => Map<string, CronJobLike>;
15
+ [DONE]?: boolean;
16
+ }
17
+ /**
18
+ * `instrumentNestSchedule(app.get(SchedulerRegistry))` after `app.init()` (or in `onApplicationBootstrap`): every `@Cron`
19
+ * job, already registered or added later, runs as a monitor named after its `@Cron(expr, { name })` (kebab-cased) with its
20
+ * cron expression and timezone as the schedule. Give jobs a name; unnamed ones (uuid) are skipped. Returns how many were wrapped now.
21
+ * shortcut: reads the `cron` package's private `_callbacks` (cron 3 and 4); a version that moves it wraps nothing.
22
+ */
23
+ export declare function instrumentNestSchedule(registry: SchedulerRegistryLike): number;
24
+ interface NodeCronLike {
25
+ schedule: (expr: string, fn: Fn, opts?: {
26
+ name?: string;
27
+ timezone?: string;
28
+ }) => unknown;
29
+ }
30
+ /**
31
+ * `import cron from 'node-cron'; instrumentNodeCron(cron)`: tasks scheduled afterwards with `cron.schedule(expr, fn, { name })`
32
+ * run as monitors (a function's own name is not used: bundlers rename them). Pass the default export (a CommonJS object), not an ESM namespace.
33
+ * Returns false when it cannot patch it.
34
+ */
35
+ export declare function instrumentNodeCron(cron: NodeCronLike): boolean;
36
+ export {};
@@ -0,0 +1,61 @@
1
+ // Cron monitors for `@nestjs/schedule` (`@Cron`) and `node-cron`: each job becomes a monitor via `withMonitor`.
2
+ import { monitorJob, slugify } from './monitor.js';
3
+ const DONE = Symbol.for('watchtower.cron.wrapped');
4
+ /** Wrap one `cron` CronJob's callbacks. False when this `cron` version keeps them elsewhere than `_callbacks`. */
5
+ function wrapJob(name, job) {
6
+ const slug = slugify(name); // a Nest job without `{ name }` gets a uuid: nothing stable to monitor
7
+ if (!slug || job[DONE] || !Array.isArray(job._callbacks))
8
+ return false;
9
+ job[DONE] = true;
10
+ const src = job.cronTime?.source;
11
+ const tz = job.cronTime?.zone ?? job.cronTime?.timeZone;
12
+ const o = { schedule: typeof src === 'string' ? src : undefined, timezone: typeof tz === 'string' ? tz : undefined };
13
+ job._callbacks = job._callbacks.map((cb) => function (...a) { return monitorJob(slug, () => cb.apply(this, a), o); });
14
+ return true;
15
+ }
16
+ /**
17
+ * `instrumentNestSchedule(app.get(SchedulerRegistry))` after `app.init()` (or in `onApplicationBootstrap`): every `@Cron`
18
+ * job, already registered or added later, runs as a monitor named after its `@Cron(expr, { name })` (kebab-cased) with its
19
+ * cron expression and timezone as the schedule. Give jobs a name; unnamed ones (uuid) are skipped. Returns how many were wrapped now.
20
+ * shortcut: reads the `cron` package's private `_callbacks` (cron 3 and 4); a version that moves it wraps nothing.
21
+ */
22
+ export function instrumentNestSchedule(registry) {
23
+ let n = 0;
24
+ for (const [name, job] of registry.getCronJobs())
25
+ if (wrapJob(name, job))
26
+ n++;
27
+ if (!registry[DONE]) {
28
+ registry[DONE] = true;
29
+ const add = registry.addCronJob;
30
+ registry.addCronJob = function (name, job) {
31
+ wrapJob(name, job);
32
+ return add.call(this, name, job);
33
+ };
34
+ }
35
+ return n;
36
+ }
37
+ /**
38
+ * `import cron from 'node-cron'; instrumentNodeCron(cron)`: tasks scheduled afterwards with `cron.schedule(expr, fn, { name })`
39
+ * run as monitors (a function's own name is not used: bundlers rename them). Pass the default export (a CommonJS object), not an ESM namespace.
40
+ * Returns false when it cannot patch it.
41
+ */
42
+ export function instrumentNodeCron(cron) {
43
+ const orig = cron.schedule;
44
+ if (typeof orig !== 'function' || orig[DONE])
45
+ return false;
46
+ const wrapped = function (expr, fn, opts, ...rest) {
47
+ const slug = typeof fn === 'function' ? slugify(opts?.name || '') : '';
48
+ if (!slug)
49
+ return orig.call(this, expr, fn, opts, ...rest);
50
+ const o = { schedule: expr, timezone: opts?.timezone };
51
+ return orig.call(this, expr, function (...a) { return monitorJob(slug, () => fn.apply(this, a), o); }, opts, ...rest);
52
+ };
53
+ wrapped[DONE] = true;
54
+ try {
55
+ cron.schedule = wrapped;
56
+ }
57
+ catch {
58
+ return false;
59
+ }
60
+ return cron.schedule === wrapped;
61
+ }
package/dist/esm/env.d.ts CHANGED
@@ -10,3 +10,13 @@ export interface OtelEnv {
10
10
  resource: Record<string, string>;
11
11
  }
12
12
  export declare function otelEnv(env?: NodeJS.ProcessEnv): OtelEnv;
13
+ /**
14
+ * The commit `HEAD` points at, found by walking up from `from` to a `.git` directory (a `.git` file of a worktree or submodule is
15
+ * followed through its `gitdir:` line). Reads `HEAD`, then the ref file or `packed-refs`; no child process. undefined when not found.
16
+ */
17
+ export declare function gitHeadSha(from: string): string | undefined;
18
+ /**
19
+ * service.version: explicit option, WT_RELEASE, OTEL_RESOURCE_ATTRIBUTES, the first CI commit-sha variable, the build stamp
20
+ * (`WT_BUILD_STAMP`, `BUILD_STAMP`), then the `.git` HEAD found upward from `gitFrom` (skipped when not given). Empty and `unknown` count as absent.
21
+ */
22
+ export declare function resolveRelease(opt: string | undefined, env: NodeJS.ProcessEnv, otelResource: Record<string, string>, gitFrom?: string): string | undefined;
package/dist/esm/env.js CHANGED
@@ -1,3 +1,5 @@
1
+ import * as fs from 'node:fs';
2
+ import * as nodePath from 'node:path';
1
3
  // Standard OTEL_* environment variables, used as fallbacks after the WT_* ones.
2
4
  /** Parse `k=v,k2=v2` (OTEL_RESOURCE_ATTRIBUTES / OTEL_EXPORTER_OTLP_HEADERS); values are percent-decoded. */
3
5
  export function parseKv(s) {
@@ -31,3 +33,63 @@ export function otelEnv(env = process.env) {
31
33
  resource,
32
34
  };
33
35
  }
36
+ const CI_SHA_VARS = ['GITHUB_SHA', 'CI_COMMIT_SHA', 'VERCEL_GIT_COMMIT_SHA', 'SOURCE_VERSION', 'BUILD_SHA', 'RENDER_GIT_COMMIT', 'HEROKU_SLUG_COMMIT'];
37
+ const present = (v) => { const t = (v || '').trim(); return t && t.toLowerCase() !== 'unknown' ? t : undefined; };
38
+ /**
39
+ * The commit `HEAD` points at, found by walking up from `from` to a `.git` directory (a `.git` file of a worktree or submodule is
40
+ * followed through its `gitdir:` line). Reads `HEAD`, then the ref file or `packed-refs`; no child process. undefined when not found.
41
+ */
42
+ export function gitHeadSha(from) {
43
+ const sha = /^[0-9a-f]{40,64}$/i;
44
+ try {
45
+ for (let dir = nodePath.resolve(from);; dir = nodePath.dirname(dir)) {
46
+ let git = nodePath.join(dir, '.git');
47
+ if (fs.existsSync(git)) {
48
+ if (fs.statSync(git).isFile())
49
+ git = nodePath.resolve(dir, /^gitdir:\s*(.+)$/m.exec(fs.readFileSync(git, 'utf8'))?.[1]?.trim() ?? '');
50
+ const head = fs.readFileSync(nodePath.join(git, 'HEAD'), 'utf8').trim();
51
+ if (sha.test(head))
52
+ return head; // detached
53
+ const ref = /^ref:\s*(\S+)/.exec(head)?.[1];
54
+ if (!ref)
55
+ return undefined;
56
+ // a worktree keeps its branch refs in the common dir
57
+ const cd = nodePath.join(git, 'commondir');
58
+ const common = fs.existsSync(cd) ? nodePath.resolve(git, fs.readFileSync(cd, 'utf8').trim()) : git;
59
+ for (const d of [git, common]) {
60
+ try {
61
+ const v = fs.readFileSync(nodePath.join(d, ref), 'utf8').trim();
62
+ if (sha.test(v))
63
+ return v;
64
+ }
65
+ catch { /* not a loose ref */ }
66
+ try {
67
+ const line = fs.readFileSync(nodePath.join(d, 'packed-refs'), 'utf8').split('\n').find((l) => l.endsWith(` ${ref}`));
68
+ const v = line?.split(' ')[0];
69
+ if (v && sha.test(v))
70
+ return v;
71
+ }
72
+ catch { /* no packed-refs */ }
73
+ }
74
+ return undefined;
75
+ }
76
+ if (nodePath.dirname(dir) === dir)
77
+ return undefined;
78
+ }
79
+ }
80
+ catch {
81
+ return undefined;
82
+ }
83
+ }
84
+ /**
85
+ * service.version: explicit option, WT_RELEASE, OTEL_RESOURCE_ATTRIBUTES, the first CI commit-sha variable, the build stamp
86
+ * (`WT_BUILD_STAMP`, `BUILD_STAMP`), then the `.git` HEAD found upward from `gitFrom` (skipped when not given). Empty and `unknown` count as absent.
87
+ */
88
+ export function resolveRelease(opt, env, otelResource, gitFrom) {
89
+ for (const v of [opt, env.WT_RELEASE, otelResource['service.version'], ...CI_SHA_VARS.map((k) => env[k]), env.WT_BUILD_STAMP, env.BUILD_STAMP]) {
90
+ const r = present(v);
91
+ if (r)
92
+ return r;
93
+ }
94
+ return gitFrom ? gitHeadSha(gitFrom) : undefined;
95
+ }
@@ -9,12 +9,20 @@ import type { ReadableSpan, TracerProvider } from '@opentelemetry/sdk-trace';
9
9
  import type { LoggerProvider } from '@opentelemetry/sdk-logs';
10
10
  // @ts-ignore optional peer: absent -> any (keeps skipLibCheck:false consumers compiling)
11
11
  import type { MeterProvider } from '@opentelemetry/sdk-metrics';
12
+ import type { RedactHook } from './redact.js';
13
+ import type { RedactPreset } from './redact-presets.js';
14
+ import type { CheckInOptions, CheckInStatus, MonitorOptions } from './cron/monitor.js';
12
15
  import { captureException } from './errors.js';
13
16
  import type { CaptureContext } from './errors.js';
14
17
  import { RemoteSampler } from './sampling.js';
15
18
  import type { Profiler } from './profiling.js';
16
19
  export { captureException, metrics, trace };
20
+ export { instrument } from './instrument-for.js';
21
+ export type { Framework, InstrumentOptions } from './instrument-for.js';
22
+ export { droppedDbSpans } from './integrations/db.js';
17
23
  export { setCaptureRules, capturePayload } from './payload.js';
24
+ export type { MonitorOptions, MonitorConfig, CheckInOptions, CheckInStatus } from './cron/monitor.js';
25
+ export { instrumentNestSchedule, instrumentNodeCron } from './cron/schedulers.js';
18
26
  export type { CaptureRule } from './payload.js';
19
27
  export type { CaptureContext };
20
28
  export declare const DEFAULT_ENDPOINT = "http://localhost:4318";
@@ -26,7 +34,7 @@ export interface InitOptions {
26
34
  apiKey?: string;
27
35
  /** Defaults to WT_ENVIRONMENT. */
28
36
  environment?: string;
29
- /** Sent as `service.version`; the server links an issue's first release by matching it to an existing release's version. Defaults to WT_RELEASE, then `service.version` in OTEL_RESOURCE_ATTRIBUTES. */
37
+ /** Sent as `service.version`; the server links an issue's first release by matching it to an existing release's version. Defaults to WT_RELEASE, then `service.version` in OTEL_RESOURCE_ATTRIBUTES, then the first set of GITHUB_SHA, CI_COMMIT_SHA, VERCEL_GIT_COMMIT_SHA, SOURCE_VERSION, BUILD_SHA, RENDER_GIT_COMMIT, HEROKU_SLUG_COMMIT, then WT_BUILD_STAMP / BUILD_STAMP, then the commit `.git/HEAD` points at (searched upward from the working directory). */
30
38
  release?: string;
31
39
  /** Hook uncaughtException / unhandledRejection (default true). */
32
40
  captureProcessErrors?: boolean;
@@ -50,11 +58,15 @@ export interface InitOptions {
50
58
  /** Resource attributes (on top of OTEL_RESOURCE_ATTRIBUTES); keys starting with `wt.` are dropped. */
51
59
  resource?: Record<string, string | number | boolean>;
52
60
  /**
53
- * Called before export for every span attribute, every span event's and link's attributes (so `exception.message`
61
+ * Built-in redaction: `'strict'` (default) replaces string values of secret-shaped keys (authorization, cookie, set-cookie,
62
+ * password, secret, token, api_key, session, ...) with `[redacted]` on spans, span events, logs and errors, and URLs lose their
63
+ * query string and token-shaped path segments (`urlScrubbing`); `'pii'` also masks emails, phone numbers, Luhn-valid card numbers
64
+ * and IP addresses in every string; `'off'` disables the presets and URL scrubbing. The gateway applies the same rules again as
65
+ * a backstop. A function is a hook run after the `'strict'` preset. The hook is called before export for every span attribute, every span event's and link's attributes (so `exception.message`
54
66
  * and `exception.stacktrace`), the span name (key `span.name`), the status message (`status.message`) and each log
55
67
  * body (`log.body`) and log attribute; return the value to keep.
56
68
  */
57
- redact?: (key: string, value: unknown) => unknown;
69
+ redact?: RedactHook | RedactPreset;
58
70
  /** Directory for the offline buffer. */
59
71
  bufferDir?: string;
60
72
  /** Apply the project's head sampling rules in the SDK, polled from /v1/sampling; defaults to WT_REMOTE_SAMPLING=1. Spans dropped here never reach the gateway, so its exact request counts see only what is kept. */
@@ -71,9 +83,17 @@ export interface InitOptions {
71
83
  * Scrub URLs on every span, including spans other libraries create (Next.js, node:http, fetch): the query string is dropped
72
84
  * (`url.query` removed) and path segments that look like secrets (UUIDs, hex runs, JWTs, long digit runs, random tokens of >= 16 chars;
73
85
  * hosts, readable words, slugs and short ids stay) become `:redacted`, in `http.target`, `url.full`, `url.path`, `http.url` and URLs in span names.
74
- * `http.route` is kept. Default true; `false` records URLs as the instrumentation produced them.
86
+ * `http.route` is kept. Default true (false when `redact: 'off'`); `false` records URLs as the instrumentation produced them.
75
87
  */
76
88
  urlScrubbing?: boolean;
89
+ /**
90
+ * What to do when another library (Sentry, ...) already registered the global TracerProvider. `'auto'` (default): attach the
91
+ * Watchtower exporter to that provider as a span processor and leave its context manager and propagator alone; `'own'`: build and
92
+ * register our own provider (the old behaviour; the other one is kept as the global and a warning says so); `'attach'`: like
93
+ * `'auto'`, with a warning when there is no provider to attach to. Attached spans carry the other provider's resource
94
+ * (set `OTEL_SERVICE_NAME`), and `remoteSampling` is not applied.
95
+ */
96
+ otel?: 'auto' | 'own' | 'attach';
77
97
  /** Return false to drop a finished span before export (the `/next` entry uses it for `nextInternals`). */
78
98
  spanFilter?: (span: ReadableSpan) => boolean;
79
99
  /**
@@ -116,7 +136,15 @@ export interface ScoreOptions {
116
136
  }
117
137
  /** Drop caller-supplied wt.* keys: tenant identity comes only from the key. */
118
138
  export declare function safeResource(attrs?: Record<string, unknown>): Record<string, unknown>;
119
- export declare class Client {
139
+ /** What `init()` reports (also fields of the returned Client): per signal `ok`, `disabled` (switched off) or `blocked` (an OTel global was already registered and kept). */
140
+ export interface InitStatus {
141
+ traces: 'ok' | 'disabled' | 'blocked';
142
+ metrics: 'ok' | 'disabled' | 'blocked';
143
+ logs: 'ok' | 'disabled' | 'blocked';
144
+ blocked: string[];
145
+ warnings: string[];
146
+ }
147
+ export declare class Client implements InitStatus {
120
148
  readonly endpoint: string;
121
149
  readonly apiUrl: string;
122
150
  readonly project: string | undefined;
@@ -124,7 +152,17 @@ export declare class Client {
124
152
  Authorization: string;
125
153
  } & Record<string, string>;
126
154
  readonly fetch: typeof fetch;
127
- readonly redact: InitOptions['redact'];
155
+ readonly redact: RedactHook | undefined;
156
+ private readonly scrubUrls;
157
+ /** What `init` found: `blocked` lists the OTel globals that were already registered and kept. */
158
+ traces: 'ok' | 'disabled' | 'blocked';
159
+ metrics: 'ok' | 'disabled' | 'blocked';
160
+ logs: 'ok' | 'disabled' | 'blocked';
161
+ blocked: string[];
162
+ warnings: string[];
163
+ /** True when the exporter was attached to another provider's pipeline (`otel`). */
164
+ readonly attached: boolean;
165
+ private readonly spanProcessors;
128
166
  private readonly logCaller;
129
167
  readonly provider: TracerProvider;
130
168
  readonly resource: Resource;
@@ -165,6 +203,12 @@ export declare class Client {
165
203
  shutdown(): Promise<void>;
166
204
  }
167
205
  export declare function init(opts: InitOptions): Client;
206
+ /** Why telemetry is off (set by the preload when it cannot start); shown on the first dropped helper call. */
207
+ export declare const setOffReason: (r: string) => void;
208
+ /** One check-in for the monitor `slug`. Fire and forget by default (5 s cap, never throws); `{ wait: true }` awaits it. */
209
+ export declare const checkIn: (slug: string, status: CheckInStatus, o?: CheckInOptions) => Promise<void>;
210
+ /** `withMonitor(slug, fn, { schedule, timezone, checkinMargin, maxRuntime, failureThreshold, wait })`: `fn` as a monitored job; the monitor is created or updated from `schedule`. */
211
+ export declare const withMonitor: <T>(slug: string, fn: () => T | Promise<T>, o?: MonitorOptions) => Promise<T>;
168
212
  export declare const checkin: <T>(slug: string, fn: () => T | Promise<T>) => Promise<T>;
169
213
  export declare const flush: () => Promise<unknown>;
170
214
  export declare const log: (l: LogLevel, b: string, a?: Record<string, unknown>) => void;