@zharp/node 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +123 -3
- package/dist/index.d.mts +157 -0
- package/dist/index.d.ts +157 -0
- package/dist/index.js +802 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +788 -0
- package/dist/index.mjs.map +1 -0
- package/init.d.ts +2 -0
- package/init.js +4 -0
- package/init.mjs +5 -0
- package/package.json +83 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/zharp.ts","../../../internal/src/builtins.ts","../../../internal/src/env.ts","../src/context.ts","../src/console.ts","../../../internal/src/debug-ids.ts","../src/debug-ids.ts","../src/errors.ts","../src/version.ts","../src/index.ts"],"sourcesContent":["/**\r\n * @zharp/node: the OpenTelemetry Node SDK, configured for Zharp.\r\n *\r\n * Everything that makes spans is OpenTelemetry's — the Node SDK, the auto-instrumentations for\r\n * http, express, fastify, pg, redis, prisma's driver and the rest, the W3C propagators, the\r\n * pino/winston/bunyan log bridges. What is here is the configuration (where to send, with what\r\n * key, under which service), the two processors that put user and session on everything, a\r\n * console bridge, error capture, and a small API in the same shape as every other Zharp SDK.\r\n */\r\nimport { register as registerLoader } from 'node:module';\r\nimport {\r\n type Context,\r\n type DiagLogger,\r\n DiagLogLevel,\r\n diag,\r\n INVALID_SPAN_CONTEXT,\r\n logs,\r\n SeverityNumber,\r\n SpanStatusCode,\r\n trace,\r\n type Logger,\r\n type TextMapGetter,\r\n type TextMapPropagator,\r\n type Span,\r\n type SpanOptions,\r\n} from '@opentelemetry/api';\r\nimport { CompositePropagator, W3CBaggagePropagator, W3CTraceContextPropagator } from '@opentelemetry/core';\r\nimport { envDetector, hostDetector, resourceFromAttributes } from '@opentelemetry/resources';\r\nimport { NodeSDK } from '@opentelemetry/sdk-node';\r\nimport {\r\n BatchSpanProcessor,\r\n ParentBasedSampler,\r\n SamplingDecision,\r\n TraceIdRatioBasedSampler,\r\n type Sampler,\r\n type SamplingResult,\r\n type SpanProcessor,\r\n} from '@opentelemetry/sdk-trace';\r\nimport { BatchLogRecordProcessor, type LogRecordProcessor } from '@opentelemetry/sdk-logs';\r\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';\r\nimport { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-proto';\r\nimport { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';\r\nimport { announce, describeTarget, disabledByEnv, nodeEnv, packageName, pick, warn } from '@zharp/internal/env';\r\nimport { ContextLogProcessor, ContextSpanProcessor, ContextStore, userAttributes } from './context';\r\nimport { captureConsole } from './console';\r\nimport { DebugIdLogProcessor, DebugIdSpanProcessor } from './debug-ids';\r\nimport { asError, exceptionAttributes, SEVERITY, type Level } from './errors';\r\nimport type { Attributes, NodeOptions, ZharpUser } from './types';\r\nimport { VERSION } from './version';\r\n\r\nexport const DEFAULT_ENDPOINT = 'https://api.zharp.io/api/v1/otlp';\r\n\r\n/** How long a flush on the way out may hold the process up. */\r\nconst EXIT_FLUSH_MS = 2_000;\r\n\r\ntype LogFn = (message: unknown, attributes?: Attributes) => void;\r\n\r\nexport class ZharpNode {\r\n private sdk: NodeSDK | null = null;\r\n private spanProcessors: SpanProcessor[] = [];\r\n private logProcessors: LogRecordProcessor[] = [];\r\n private logger: Logger | null = null;\r\n private readonly store = new ContextStore();\r\n private teardowns: Array<() => void> = [];\r\n /** False in logs-only mode (`tracing: false` / `ZHARP_TRACING=false`). */\r\n private tracing = true;\r\n /** Errors already sent, so one that is both rejected and then thrown is reported once. */\r\n private readonly reported = new WeakSet<object>();\r\n\r\n /** `Zharp.log.info(\"Order placed\", { orderId })` — and debug, warn, error, fatal, trace. */\r\n readonly log: Record<Level, LogFn> = {\r\n trace: (m, a) => this.emit('trace', m, a),\r\n debug: (m, a) => this.emit('debug', m, a),\r\n info: (m, a) => this.emit('info', m, a),\r\n warn: (m, a) => this.emit('warn', m, a),\r\n error: (m, a) => this.emit('error', m, a),\r\n fatal: (m, a) => this.emit('fatal', m, a),\r\n };\r\n\r\n /** Whether `init()` started the SDK. */\r\n get isActive(): boolean {\r\n return this.sdk !== null;\r\n }\r\n\r\n /**\r\n * Start sending traces, logs and errors. Call it once, before the application's own modules\r\n * load — from a file preloaded with `node --import` (see the README) — so that http, the\r\n * database drivers and the frameworks are instrumented when they are first imported.\r\n */\r\n init(options: NodeOptions = {}): void {\r\n try {\r\n this.start(options);\r\n } catch (error) {\r\n warn(`Could not start: ${(error as Error)?.message ?? error}`);\r\n }\r\n }\r\n\r\n private start(options: NodeOptions): void {\r\n if (this.sdk) {\r\n warn('Zharp.init() was called again — the first call\\'s settings stay in effect.');\r\n return;\r\n }\r\n if (disabledByEnv()) {\r\n announce('Disabled by ZHARP_DISABLED — nothing will be sent');\r\n return;\r\n }\r\n const key = pick(options.key, nodeEnv('ZHARP_API_KEY'), nodeEnv('ZHARP_KEY'));\r\n if (!key) {\r\n warn('No key found — pass Zharp.init({ key }) or set ZHARP_API_KEY. Nothing will be sent.');\r\n return;\r\n }\r\n const service = pick(options.service, nodeEnv('ZHARP_SERVICE'), nodeEnv('OTEL_SERVICE_NAME'), packageName()) ?? 'node-app';\r\n const environment = pick(options.environment, nodeEnv('ZHARP_ENV'), nodeEnv('NODE_ENV'));\r\n const release = pick(options.release, nodeEnv('ZHARP_RELEASE'), nodeEnv('ZHARP_VERSION'));\r\n const endpoint = (pick(options.endpoint, nodeEnv('ZHARP_ENDPOINT')) ?? DEFAULT_ENDPOINT).replace(/\\/+$/, '');\r\n const tracing = tracingEnabled(options.tracing);\r\n this.tracing = tracing;\r\n\r\n if (options.debug) {\r\n // Bound to the console as it is now, before the bridge patches it: OpenTelemetry's own\r\n // messages about a failed export must not become log records that fail to export.\r\n const out = { error: console.error, warn: console.warn, info: console.info, debug: console.debug, verbose: console.debug };\r\n const prefixed = Object.fromEntries(\r\n Object.entries(out).map(([level, fn]) => [level, (message: string, ...args: unknown[]) => fn.call(console, `[Zharp][otel] ${message}`, ...args)]),\r\n ) as unknown as DiagLogger;\r\n diag.setLogger(prefixed, DiagLogLevel.DEBUG);\r\n }\r\n\r\n // ES modules can only be instrumented through a loader hook, and it has to be in place\r\n // before the application's first import — which is why init() belongs in a preloaded file.\r\n registerEsmHook();\r\n\r\n const headers = { Authorization: `Bearer ${key}` };\r\n const exporterOptions = { headers, compression: 'gzip' as any };\r\n // Logs only: no span exporter at all. The context processor stays, because it is what keeps\r\n // a user set with setUser() to its own request (see RecordOnlySampler).\r\n this.spanProcessors = tracing\r\n ? [\r\n new ContextSpanProcessor(this.store),\r\n new DebugIdSpanProcessor(),\r\n new BatchSpanProcessor({ exporter: new OTLPTraceExporter({ ...exporterOptions, url: `${endpoint}/v1/traces` }) }),\r\n ]\r\n : [new ContextSpanProcessor(this.store)];\r\n this.logProcessors = [\r\n new ContextLogProcessor(this.store),\r\n new DebugIdLogProcessor(),\r\n new BatchLogRecordProcessor({ exporter: new OTLPLogExporter({ ...exporterOptions, url: `${endpoint}/v1/logs` }) }),\r\n ];\r\n\r\n const resource = resourceFromAttributes({\r\n 'service.name': service,\r\n ...(release ? { 'service.version': release } : {}),\r\n ...(environment ? { 'deployment.environment.name': environment } : {}),\r\n 'telemetry.sdk.name': 'zharp',\r\n 'telemetry.sdk.language': 'nodejs',\r\n 'telemetry.sdk.version': VERSION,\r\n 'process.runtime.name': 'nodejs',\r\n 'process.runtime.version': process.versions.node,\r\n });\r\n\r\n const propagator = new CompositePropagator({\r\n propagators: [new W3CTraceContextPropagator(), new W3CBaggagePropagator()],\r\n });\r\n const rate = typeof options.sampleRate === 'number' ? Math.min(1, Math.max(0, options.sampleRate)) : 1;\r\n\r\n this.sdk = new NodeSDK({\r\n resource,\r\n // Host and OTEL_RESOURCE_ATTRIBUTES only. The process detector would send the command line,\r\n // which is where secrets passed as arguments live.\r\n resourceDetectors: [envDetector, hostDetector],\r\n sampler: tracing ? new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(rate) }) : new RecordOnlySampler(),\r\n textMapPropagator: tracing ? propagator : new ExtractOnlyPropagator(propagator),\r\n spanProcessors: this.spanProcessors,\r\n logRecordProcessors: this.logProcessors,\r\n // Without this the SDK would start an OTLP metrics exporter pointed at localhost:4318.\r\n metricReaders: [],\r\n instrumentations: [\r\n ...(tracing\r\n ? getNodeAutoInstrumentations({\r\n // A span per DNS lookup, socket and file read buries the requests that matter.\r\n '@opentelemetry/instrumentation-dns': { enabled: false },\r\n '@opentelemetry/instrumentation-net': { enabled: false },\r\n '@opentelemetry/instrumentation-fs': { enabled: false },\r\n ...options.instrumentations,\r\n })\r\n : logsOnlyInstrumentations(options)),\r\n ...(options.extraInstrumentations ?? []),\r\n ],\r\n });\r\n this.sdk.start();\r\n this.logger = logs.getLogger('@zharp/node', VERSION);\r\n\r\n if (options.captureConsole !== false) this.teardowns.push(captureConsole(this.logger));\r\n if (options.captureUncaught !== false) this.teardowns.push(this.captureProcessErrors());\r\n this.teardowns.push(this.flushOnExit());\r\n\r\n announce(`Application monitoring active${tracing ? '' : ' (logs only)'} — ${describeTarget(service, environment)}`);\r\n }\r\n\r\n /**\r\n * The user the current request is for: `enduser.id` (and `enduser.email`, `enduser.name`) on\r\n * every span and log of the request from here on, and on the request's own span. Outside a\r\n * request it applies to everything the process sends — for a script or a worker that runs as\r\n * one user.\r\n *\r\n * Requests from a page running @zharp/browser already carry the user in their baggage; this\r\n * is for servers that know the user themselves.\r\n */\r\n setUser(user: ZharpUser | null): void {\r\n try {\r\n this.store.setUser(user && user.id != null && user.id !== '' ? userAttributes(user) : null);\r\n } catch {\r\n // Never throw into the application.\r\n }\r\n }\r\n\r\n /** Forget the user — for the current request, or the process's when called outside one. */\r\n clearUser(): void {\r\n this.setUser(null);\r\n }\r\n\r\n /** An attribute on every span and log sent from now on, e.g. `setTag(\"region\", \"eu-west-1\")`. */\r\n setTag(key: string, value: string | number | boolean | null | undefined): void {\r\n if (value === null || value === undefined) delete this.store.tags[key];\r\n else this.store.tags[key] = value;\r\n }\r\n\r\n /**\r\n * Report an error you caught. It is sent as handled, in the trace of the request it happened\r\n * in, and grouped into an issue with every other occurrence.\r\n */\r\n captureError(error: unknown, attributes?: Attributes): void {\r\n this.report(error, true, 'error', attributes);\r\n }\r\n\r\n /**\r\n * Run `fn` inside a span named `name`, which ends when `fn` returns or its promise settles. A\r\n * throw or rejection marks the span as failed and is passed on unchanged.\r\n */\r\n startSpan<T>(name: string, fn: (span: Span) => T, options: SpanOptions = {}): T {\r\n // Logs only: no span — the callback runs as it is, handed a non-recording stand-in with the\r\n // current trace's ids (so ending or annotating it touches nothing).\r\n if (!this.tracing) return fn(trace.wrapSpanContext(trace.getActiveSpan()?.spanContext() ?? INVALID_SPAN_CONTEXT));\r\n const tracer = trace.getTracer('@zharp/node', VERSION);\r\n return tracer.startActiveSpan(name, options, (span) => {\r\n const fail = (error: unknown) => {\r\n span.setStatus({ code: SpanStatusCode.ERROR, message: asError(error).message });\r\n span.end();\r\n };\r\n let result: T;\r\n try {\r\n result = fn(span);\r\n } catch (error) {\r\n fail(error);\r\n throw error;\r\n }\r\n if (result && typeof (result as any).then === 'function') {\r\n return (result as any).then(\r\n (value: unknown) => {\r\n span.end();\r\n return value;\r\n },\r\n (error: unknown) => {\r\n fail(error);\r\n throw error;\r\n },\r\n ) as T;\r\n }\r\n span.end();\r\n return result;\r\n });\r\n }\r\n\r\n /** Send everything waiting now. Await it before a serverless function returns. */\r\n async flush(timeoutMs = 5_000): Promise<void> {\r\n const all = Promise.all([...this.spanProcessors, ...this.logProcessors].map((p) => p.forceFlush().catch(() => {})));\r\n await Promise.race([all, new Promise((resolve) => setTimeout(resolve, timeoutMs).unref())]);\r\n }\r\n\r\n /** Flush, stop, and put back everything that was patched. */\r\n async shutdown(): Promise<void> {\r\n const sdk = this.sdk;\r\n if (!sdk) return;\r\n this.sdk = null;\r\n for (const undo of this.teardowns.splice(0)) undo();\r\n await sdk.shutdown().catch(() => {});\r\n }\r\n\r\n // ── internals ─────────────────────────────────────────────────────────\r\n\r\n private emit(level: Level, message: unknown, attributes?: Attributes): void {\r\n try {\r\n if (!this.logger) return;\r\n const extra: Record<string, unknown> = {};\r\n // An Error among the attributes is the reason for the log: it is sent as the exception,\r\n // so `Zharp.log.error(\"Payment failed\", { error })` becomes an issue with its stack.\r\n for (const [key, value] of Object.entries(attributes ?? {})) {\r\n if (value instanceof Error && (level === 'error' || level === 'fatal') && !extra['exception.type']) {\r\n Object.assign(extra, exceptionAttributes(value, true));\r\n } else {\r\n extra[key] = value instanceof Error ? `${value.name}: ${value.message}` : value;\r\n }\r\n }\r\n this.logger.emit({\r\n severityNumber: SEVERITY[level] as SeverityNumber,\r\n severityText: level.toUpperCase(),\r\n body: typeof message === 'string' ? message : message instanceof Error ? message.message : safeJson(message),\r\n attributes: extra as any,\r\n });\r\n } catch {\r\n // Never throw into the application.\r\n }\r\n }\r\n\r\n private report(value: unknown, handled: boolean, level: Level, attributes?: Attributes): void {\r\n try {\r\n if (!this.logger) return;\r\n const error = asError(value);\r\n if (value && typeof value === 'object') {\r\n if (this.reported.has(value)) return;\r\n this.reported.add(value);\r\n }\r\n const exception = exceptionAttributes(error, handled);\r\n this.logger.emit({\r\n severityNumber: SEVERITY[level] as SeverityNumber,\r\n severityText: level.toUpperCase(),\r\n body: `${exception['exception.type']}: ${exception['exception.message']}`,\r\n attributes: { ...(attributes as any), ...exception },\r\n });\r\n // An error in a request fails that request's span, so the trace shows where it broke.\r\n if (!handled) trace.getActiveSpan()?.setStatus({ code: SpanStatusCode.ERROR, message: error.message });\r\n } catch {\r\n // As above.\r\n }\r\n }\r\n\r\n /**\r\n * Uncaught exceptions and unhandled rejections, reported as unhandled.\r\n *\r\n * Listening for either changes what Node does — it no longer exits — so when Zharp's listener\r\n * is the only one, it finishes the job the way Node would have: print the error, then exit\r\n * with code 1, after the error has been sent. When the application has listeners of its own,\r\n * they decide, and Zharp only reports.\r\n */\r\n private captureProcessErrors(): () => void {\r\n const onException = (error: unknown, origin?: string) => {\r\n this.report(error, false, 'fatal', origin ? { 'zharp.mechanism': origin } : undefined);\r\n if (process.listenerCount('uncaughtException') > 1) return;\r\n this.crash(error);\r\n };\r\n const onRejection = (reason: unknown) => {\r\n this.report(reason, false, 'error', { 'zharp.mechanism': 'unhandledRejection' });\r\n if (process.listenerCount('unhandledRejection') > 1) return;\r\n const mode = unhandledRejectionsMode();\r\n if (mode === 'warn' || mode === 'none') return;\r\n if (mode === 'warn-with-error-code') {\r\n process.exitCode = 1;\r\n return;\r\n }\r\n this.crash(reason);\r\n };\r\n process.on('uncaughtException', onException);\r\n process.on('unhandledRejection', onRejection);\r\n return () => {\r\n process.off('uncaughtException', onException);\r\n process.off('unhandledRejection', onRejection);\r\n };\r\n }\r\n\r\n private crashing = false;\r\n\r\n private crash(error: unknown): void {\r\n if (this.crashing) return;\r\n this.crashing = true;\r\n try {\r\n // Straight to stderr, not console.error: the console is captured, and this is already sent.\r\n const text = error instanceof Error ? error.stack || String(error) : `Uncaught ${safeJson(error)}`;\r\n process.stderr.write(`${text}\\n\\nNode.js ${process.version}\\n`);\r\n } catch {\r\n // Exit regardless.\r\n }\r\n this.flush(EXIT_FLUSH_MS).finally(() => process.exit(1));\r\n }\r\n\r\n /**\r\n * Send what is waiting when the process ends on its own (the event loop drains) or is told to\r\n * stop. A signal listener also replaces Node's default of exiting, so once the flush is done,\r\n * if no one else is listening, the signal is raised again with Zharp's listener gone.\r\n */\r\n private flushOnExit(): () => void {\r\n let flushing = false;\r\n const onBeforeExit = () => {\r\n if (flushing) return;\r\n flushing = true;\r\n this.flush(EXIT_FLUSH_MS).finally(() => (flushing = false));\r\n };\r\n process.on('beforeExit', onBeforeExit);\r\n\r\n const signals: NodeJS.Signals[] = ['SIGTERM', 'SIGINT'];\r\n const handlers = signals.map((signal) => {\r\n const handler = () => {\r\n this.flush(EXIT_FLUSH_MS).finally(() => {\r\n process.off(signal, handler);\r\n if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);\r\n });\r\n };\r\n process.on(signal, handler);\r\n return [signal, handler] as const;\r\n });\r\n\r\n return () => {\r\n process.off('beforeExit', onBeforeExit);\r\n for (const [signal, handler] of handlers) process.off(signal, handler);\r\n };\r\n }\r\n}\r\n\r\n/** `--unhandled-rejections=…` from the command line or NODE_OPTIONS; `throw` when unset. */\r\nfunction unhandledRejectionsMode(): string {\r\n const flags = [...process.execArgv, ...(process.env.NODE_OPTIONS ?? '').split(/\\s+/)];\r\n for (const flag of flags) {\r\n const match = /^--unhandled-rejections=(.+)$/.exec(flag);\r\n if (match) return match[1];\r\n }\r\n return 'throw';\r\n}\r\n\r\nfunction safeJson(value: unknown): string {\r\n try {\r\n return typeof value === 'string' ? value : JSON.stringify(value) ?? String(value);\r\n } catch {\r\n return String(value);\r\n }\r\n}\r\n\r\n/** Register OpenTelemetry's ES module loader hook, once per process. */\r\nfunction registerEsmHook(): void {\r\n const g = globalThis as any;\r\n if (g.__ZHARP_ESM_HOOK__) return;\r\n g.__ZHARP_ESM_HOOK__ = true;\r\n try {\r\n // Resolved from this package, which depends on @opentelemetry/instrumentation directly.\r\n registerLoader?.('@opentelemetry/instrumentation/hook.mjs', import.meta.url);\r\n } catch {\r\n // Older Node without module.register: CommonJS is still instrumented.\r\n }\r\n}\r\n\r\n/**\r\n * `tracing` from the option, else `ZHARP_TRACING` (`false`, `0`, `no`, `off` turn it off).\r\n * On unless one of them says otherwise.\r\n */\r\nfunction tracingEnabled(option: boolean | undefined): boolean {\r\n if (typeof option === 'boolean') return option;\r\n const value = nodeEnv('ZHARP_TRACING');\r\n return !(value && /^(false|0|no|off)$/i.test(value));\r\n}\r\n\r\n/**\r\n * Logs only: the log bridges (pino, winston, bunyan) and the http *server* instrumentation —\r\n * nothing else. The http server side is there only to give each incoming request a context: it\r\n * reads the caller's `traceparent` and `baggage`, so the request's logs carry the caller's trace\r\n * id, session and user (and a fresh trace id of their own when the caller sent none). Its one\r\n * span per request is never exported. Outgoing requests are not patched at all, and nothing is\r\n * injected into them.\r\n */\r\nfunction logsOnlyInstrumentations(options: NodeOptions) {\r\n // getNodeAutoInstrumentations has no \"only these\" option, but it honours this variable — set\r\n // for the duration of the call alone.\r\n const previous = process.env.OTEL_NODE_ENABLED_INSTRUMENTATIONS;\r\n process.env.OTEL_NODE_ENABLED_INSTRUMENTATIONS = 'http,pino,winston,bunyan';\r\n try {\r\n return getNodeAutoInstrumentations({\r\n ...options.instrumentations,\r\n '@opentelemetry/instrumentation-http': {\r\n ...options.instrumentations?.['@opentelemetry/instrumentation-http'],\r\n disableOutgoingRequestInstrumentation: true,\r\n },\r\n });\r\n } finally {\r\n if (previous === undefined) delete process.env.OTEL_NODE_ENABLED_INSTRUMENTATIONS;\r\n else process.env.OTEL_NODE_ENABLED_INSTRUMENTATIONS = previous;\r\n }\r\n}\r\n\r\n/**\r\n * Logs only: every span is recorded (so the context processor sees it start and end, which is\r\n * what scopes setUser() to a request) and none is sampled (so nothing could export it, and the\r\n * flags say so). Spans live in memory for the length of the request and are then dropped.\r\n */\r\nclass RecordOnlySampler implements Sampler {\r\n shouldSample(): SamplingResult {\r\n return { decision: SamplingDecision.RECORD };\r\n }\r\n\r\n toString(): string {\r\n return 'ZharpRecordOnlySampler';\r\n }\r\n}\r\n\r\n/** Reads `traceparent` and `baggage` from incoming requests; never writes them anywhere. */\r\nclass ExtractOnlyPropagator implements TextMapPropagator {\r\n constructor(private readonly inner: TextMapPropagator) {}\r\n\r\n inject(): void {}\r\n\r\n extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {\r\n return this.inner.extract(context, carrier, getter);\r\n }\r\n\r\n fields(): string[] {\r\n return [];\r\n }\r\n}\r\n","/**\n * Load a Node built-in module, or nothing at all outside Node.\n *\n * `process.getBuiltinModule` (Node 20.16+, 22.3+) is tried first because it is the only way in\n * that works from the ESM build: an ES module has no `require`, and the shim the bundler leaves\n * in its place throws. Without it, native-ESM applications silently lost HTTP tracing and kept\n * the active span in a single variable that every concurrent request overwrote.\n *\n * `require` remains the fallback for the CommonJS build on older Node. It is reached\n * indirectly so a bundler building for the browser does not try to resolve a Node built-in and\n * either fail or pull in a shim.\n *\n * @param name - Built-in name without the `node:` prefix, e.g. `http`\n */\nexport function loadBuiltin(name: string): any | null {\n try {\n const proc: any = typeof process !== 'undefined' ? process : undefined;\n if (proc && typeof proc.getBuiltinModule === 'function') {\n return proc.getBuiltinModule(`node:${name}`) ?? null;\n }\n const req = typeof module !== 'undefined' && typeof require === 'function' ? require : null;\n return req ? req(name) : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Make a patch to a built-in visible to ES-module named imports.\n *\n * `import { request } from 'node:http'` is a snapshot of the module's exports, so replacing\n * `http.request` is not seen there until Node is told to resynchronise. A no-op where the\n * function does not exist.\n */\nexport function syncBuiltinExports(): void {\n try {\n loadBuiltin('module')?.syncBuiltinESMExports?.();\n } catch {\n // Older Node; named imports keep the unpatched function, default imports still see it.\n }\n}\n","/**\n * Configuration from the environment, and the lines printed at startup.\n *\n * Both packages start the way dd-trace does: `init()` with no arguments reads the environment,\n * explicit options override it, and the result is announced in one line so it is obvious from\n * the first few lines of output whether — and as what — the application is reporting.\n */\n\nimport { loadBuiltin } from './builtins';\n\n/**\n * An environment variable, in Node only.\n *\n * Browser bundles often carry a `process` shim whose `env` was baked in at build time — reading\n * it there would tag a page with the build machine's NODE_ENV — so a browser reads nothing.\n */\nexport function nodeEnv(name: string): string | undefined {\n if (typeof window !== 'undefined' || typeof process === 'undefined' || !process.env) return undefined;\n const value = process.env[name];\n return value && value.trim() ? value.trim() : undefined;\n}\n\n/** What a deployment can set without touching code. Every field may be absent. */\nexport interface EnvConfig {\n apiKey?: string;\n service?: string;\n environment?: string;\n version?: string;\n source?: string;\n endpoint?: string;\n /** Raw `ZHARP_CAPTURE_CONSOLE`: `all`, or a list such as `warn,error`. */\n captureConsole?: string;\n}\n\n/**\n * Everything the environment says, in Node. Empty in a browser.\n *\n * | Setting | Variables |\n * |---------------|---------------------------------------------|\n * | `apiKey` | `ZHARP_API_KEY` |\n * | `service` | `ZHARP_SERVICE`, then `OTEL_SERVICE_NAME` |\n * | `environment` | `ZHARP_ENV`, then `NODE_ENV` |\n * | `version` | `ZHARP_VERSION` |\n * | `source` | `ZHARP_SOURCE` |\n * | `endpoint` | `ZHARP_ENDPOINT` |\n * | `captureConsole` | `ZHARP_CAPTURE_CONSOLE` (logs only) |\n */\nexport function readEnv(): EnvConfig {\n return {\n apiKey: nodeEnv('ZHARP_API_KEY'),\n service: nodeEnv('ZHARP_SERVICE') || nodeEnv('OTEL_SERVICE_NAME'),\n environment: nodeEnv('ZHARP_ENV') || nodeEnv('NODE_ENV'),\n version: nodeEnv('ZHARP_VERSION'),\n source: nodeEnv('ZHARP_SOURCE'),\n endpoint: nodeEnv('ZHARP_ENDPOINT'),\n captureConsole: nodeEnv('ZHARP_CAPTURE_CONSOLE'),\n };\n}\n\n/**\n * The app's own name, from the nearest package.json above the script Node was started with (or\n * the working directory) — the name a service gets when none is configured, as dd-trace does.\n * A scope is dropped: \"@acme/checkout-api\" is \"checkout-api\". Nothing in a browser.\n */\nexport function packageName(): string | undefined {\n if (typeof window !== 'undefined' || typeof process === 'undefined') return undefined;\n const fs = loadBuiltin('fs');\n const path = loadBuiltin('path');\n if (!fs || !path) return undefined;\n const starts = [process.argv?.[1] ? path.dirname(path.resolve(process.argv[1])) : '', process.cwd?.() ?? ''];\n for (const start of starts.filter(Boolean)) {\n let dir = start;\n for (let i = 0; i < 12; i++) {\n // A dependency's own package.json is not the app's.\n if (path.basename(dir) !== 'node_modules') {\n try {\n const name = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'))?.name;\n if (typeof name === 'string' && name.trim()) return name.trim().replace(/^@[^/]+\\//, '');\n } catch {\n // No package.json here, or not one we can read: keep looking further up.\n }\n }\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n }\n return undefined;\n}\n\n/** `ZHARP_DISABLED=true` (or `1`, `yes`): start nothing, whatever the code asks for. */\nexport function disabledByEnv(): boolean {\n const value = nodeEnv('ZHARP_DISABLED');\n return !!value && /^(true|1|yes|on)$/i.test(value);\n}\n\n/** The first argument that is a non-empty string — explicit option, then the next fallback. */\nexport function pick(...values: Array<string | undefined | null>): string | undefined {\n for (const value of values) {\n if (typeof value === 'string' && value.trim()) return value.trim();\n }\n return undefined;\n}\n\n/** `service \"checkout-api\", environment \"production\"` — the part both activation lines share. */\nexport function describeTarget(service: string, environment?: string): string {\n return `service \"${service}\", ${environment ? `environment \"${environment}\"` : 'no environment set'}`;\n}\n\n/** Startup output. One prefix, so it can be grepped for. */\nexport function announce(message: string): void {\n console.info(`[Zharp] ${message}`);\n}\n\nexport function warn(message: string): void {\n console.warn(`[Zharp] ${message}`);\n}\n","/**\r\n * Who a request is for, and the tags set on everything.\r\n *\r\n * Zharp joins a back end's spans and logs to the user and browser session that caused them\r\n * through two attributes, `enduser.id` and `session.id`. The browser SDK sends both in the W3C\r\n * `baggage` header next to `traceparent`; the processors here copy them from the baggage onto\r\n * every span and log written while handling that request, so nothing in the application has to\r\n * know about them.\r\n *\r\n * `Zharp.setUser()` covers the other case — a back end that knows the user itself (a session\r\n * cookie, an API token). OpenTelemetry's context is immutable, so the user cannot be put into\r\n * the request's context from inside a handler; it is kept per trace instead, and every span and\r\n * log in that trace picks it up from then on.\r\n */\r\nimport { context as otelContext, propagation, trace, type Context } from '@opentelemetry/api';\r\nimport type { ReadWriteLogRecord, LogRecordProcessor } from '@opentelemetry/sdk-logs';\r\nimport type { ReadableSpan, Span, SpanProcessor } from '@opentelemetry/sdk-trace';\r\nimport type { ZharpUser } from './types';\r\n\r\n/** Baggage entries copied onto spans and logs, unchanged in name. */\r\nconst BAGGAGE_KEYS = ['enduser.id', 'session.id'] as const;\r\n\r\n/** The user as attributes, ready to set. */\r\nexport type UserAttributes = Record<string, string>;\r\n\r\nexport function userAttributes(user: ZharpUser): UserAttributes {\r\n const out: UserAttributes = { 'enduser.id': String(user.id) };\r\n if (user.email) out['enduser.email'] = String(user.email);\r\n if (user.name) out['enduser.name'] = String(user.name);\r\n return out;\r\n}\r\n\r\n/**\r\n * Users and tags, and which trace each user belongs to.\r\n *\r\n * A trace's user is dropped when the span that began the trace in this process ends — its\r\n * SERVER span, for a request — so the map holds only requests in flight.\r\n */\r\nexport class ContextStore {\r\n /** Set outside any request: a script or worker that is one user's work throughout. */\r\n globalUser: UserAttributes | null = null;\r\n readonly tags: Record<string, string | number | boolean> = {};\r\n private readonly byTrace = new Map<string, UserAttributes>();\r\n /** The first span of each trace in this process, which the user is also written onto. */\r\n private readonly localRoots = new Map<string, { spanId: string; span: Span }>();\r\n\r\n /** Set the user for the request in progress, or for the whole process outside one. */\r\n setUser(user: UserAttributes | null): void {\r\n const span = trace.getActiveSpan();\r\n const traceId = span?.spanContext().traceId;\r\n if (!span || !traceId) {\r\n this.globalUser = user;\r\n return;\r\n }\r\n if (user) {\r\n this.byTrace.set(traceId, user);\r\n // The spans already open learn it too: the request's own span is the one the dashboard\r\n // lists, and it is still open while the handler runs.\r\n span.setAttributes(user);\r\n this.localRoots.get(traceId)?.span.setAttributes(user);\r\n } else {\r\n this.byTrace.delete(traceId);\r\n }\r\n }\r\n\r\n /** What every span and log in `traceId` should carry, before baggage. */\r\n attributesFor(traceId: string | undefined): Record<string, string | number | boolean> {\r\n const user = (traceId && this.byTrace.get(traceId)) || this.globalUser;\r\n return user ? { ...this.tags, ...user } : { ...this.tags };\r\n }\r\n\r\n noteStart(span: Span, parent: Context): void {\r\n const parentSpan = trace.getSpanContext(parent);\r\n // No parent, or one from another process: this span starts the trace here.\r\n if (!parentSpan || parentSpan.isRemote) {\r\n const { traceId, spanId } = span.spanContext();\r\n if (!this.localRoots.has(traceId)) this.localRoots.set(traceId, { spanId, span });\r\n }\r\n }\r\n\r\n noteEnd(span: ReadableSpan): void {\r\n const { traceId, spanId } = span.spanContext();\r\n if (this.localRoots.get(traceId)?.spanId !== spanId) return;\r\n this.localRoots.delete(traceId);\r\n this.byTrace.delete(traceId);\r\n }\r\n}\r\n\r\n/** `enduser.id` and `session.id` from the baggage in `ctx`, when the caller sent them. */\r\nfunction fromBaggage(ctx: Context): Record<string, string> {\r\n const out: Record<string, string> = {};\r\n const baggage = propagation.getBaggage(ctx);\r\n if (!baggage) return out;\r\n for (const key of BAGGAGE_KEYS) {\r\n const value = baggage.getEntry(key)?.value;\r\n if (value) out[key] = value;\r\n }\r\n return out;\r\n}\r\n\r\n/** Puts the user, session and tags on every span as it starts. Exports nothing itself. */\r\nexport class ContextSpanProcessor implements SpanProcessor {\r\n constructor(private readonly store: ContextStore) {}\r\n\r\n onStart(span: Span, parentContext: Context): void {\r\n try {\r\n this.store.noteStart(span, parentContext);\r\n // The store first, baggage over it: the browser's word on its own session is final, and\r\n // a user the server set itself is already in the store's entry for this trace.\r\n span.setAttributes({ ...this.store.attributesFor(span.spanContext().traceId), ...fromBaggage(parentContext) });\r\n } catch {\r\n // Never let telemetry break a request.\r\n }\r\n }\r\n\r\n onEnd(span: ReadableSpan): void {\r\n this.store.noteEnd(span);\r\n }\r\n\r\n forceFlush(): Promise<void> {\r\n return Promise.resolve();\r\n }\r\n\r\n shutdown(): Promise<void> {\r\n return Promise.resolve();\r\n }\r\n}\r\n\r\n/** The same for log records — those written through Zharp.log, the console, pino and winston alike. */\r\nexport class ContextLogProcessor implements LogRecordProcessor {\r\n constructor(private readonly store: ContextStore) {}\r\n\r\n onEmit(record: ReadWriteLogRecord, ctx?: Context): void {\r\n try {\r\n const active = ctx ?? otelContext.active();\r\n const traceId = record.spanContext?.traceId ?? trace.getSpanContext(active)?.traceId;\r\n const add = { ...this.store.attributesFor(traceId), ...fromBaggage(active) };\r\n // An attribute the call itself set (a log naming a different user, say) is kept.\r\n for (const [key, value] of Object.entries(add)) {\r\n if (record.attributes[key] === undefined) record.setAttribute(key, value);\r\n }\r\n } catch {\r\n // As above.\r\n }\r\n }\r\n\r\n forceFlush(): Promise<void> {\r\n return Promise.resolve();\r\n }\r\n\r\n shutdown(): Promise<void> {\r\n return Promise.resolve();\r\n }\r\n}\r\n","/**\r\n * `console.*` as OpenTelemetry log records.\r\n *\r\n * OpenTelemetry bridges pino, winston and bunyan but not the console, which is where most Node\r\n * code logs. Each call still prints exactly as before; a copy is emitted as a record in the\r\n * active context, so it carries the trace and span it was written in.\r\n */\r\nimport { format } from 'node:util';\r\nimport { SeverityNumber, type Logger } from '@opentelemetry/api';\r\n\r\nconst LEVELS: Array<[method: 'log' | 'info' | 'warn' | 'error' | 'debug' | 'trace', severity: SeverityNumber, text: string]> = [\r\n ['debug', SeverityNumber.DEBUG, 'DEBUG'],\r\n ['trace', SeverityNumber.TRACE, 'TRACE'],\r\n ['log', SeverityNumber.INFO, 'INFO'],\r\n ['info', SeverityNumber.INFO, 'INFO'],\r\n ['warn', SeverityNumber.WARN, 'WARN'],\r\n ['error', SeverityNumber.ERROR, 'ERROR'],\r\n];\r\n\r\n/** Set while a record is being emitted, so a console call made by the exporter is not sent too. */\r\nlet emitting = false;\r\n\r\n/**\r\n * Patch the console. Returns the undo.\r\n *\r\n * Lines the SDK prints about itself (`[Zharp] …`) are left out: they describe the reporting,\r\n * not the application.\r\n */\r\nexport function captureConsole(logger: Logger): () => void {\r\n const originals = new Map<string, (...args: unknown[]) => void>();\r\n for (const [method, severityNumber, severityText] of LEVELS) {\r\n const original = console[method];\r\n if (typeof original !== 'function' || (original as any).__zharp) continue;\r\n originals.set(method, original);\r\n const patched = function (this: unknown, ...args: unknown[]) {\r\n original.apply(this ?? console, args);\r\n if (emitting) return;\r\n emitting = true;\r\n try {\r\n const body = format(...args);\r\n if (!body.startsWith('[Zharp]')) {\r\n logger.emit({ severityNumber, severityText, body, attributes: { 'log.source': 'console' } });\r\n }\r\n } catch {\r\n // A log line that could not be copied is not worth an exception in the caller.\r\n } finally {\r\n emitting = false;\r\n }\r\n };\r\n (patched as any).__zharp = true;\r\n console[method] = patched;\r\n }\r\n return () => {\r\n for (const [method, original] of originals) (console as any)[method] = original;\r\n };\r\n}\r\n","/**\r\n * Debug IDs: which build of a file a stack frame came from, so Zharp can find its source map.\r\n *\r\n * `zharp sourcemaps inject` (and the bundler plugins) add a line to every emitted JS file that\r\n * registers it at load time:\r\n *\r\n * (globalThis.__zharpDebugIds ||= {})[new Error().stack] = \"<uuid>\"\r\n *\r\n * The key is a stack captured inside the file, so its top frame names the file exactly as this\r\n * runtime sees it — whatever the CDN, URL or path. Parsing those stacks gives file → debug ID;\r\n * an error then carries the IDs of the files in its own stack as `zharp.debug_ids`, a JSON\r\n * object `{ \"<file as it appears in the stack>\": \"<uuid>\" }`.\r\n */\r\n\r\n/** The attribute an error carries its files' debug IDs in. */\r\nexport const DEBUG_IDS_ATTRIBUTE = 'zharp.debug_ids';\r\n\r\n/** File → debug ID, from the registry entries parsed so far. */\r\nconst files = new Map<string, string>();\r\n/** Registry keys already parsed. The registry only grows, so each stack is parsed once. */\r\nconst parsed = new Set<string>();\r\n\r\nfunction registry(): Record<string, unknown> | undefined {\r\n const g = typeof globalThis !== 'undefined' ? (globalThis as any) : undefined;\r\n const value = g && g.__zharpDebugIds;\r\n return value && typeof value === 'object' ? value : undefined;\r\n}\r\n\r\n/**\r\n * The file a stack frame line points at, as written in the line: V8 (`at fn (file:1:2)`,\r\n * `at file:1:2`), and Gecko/WebKit (`fn@file:1:2`, `@file:1:2`). Undefined for anything else.\r\n */\r\nexport function frameFile(line: string): string | undefined {\r\n const text = line.trim();\r\n if (!text) return undefined;\r\n let match = /^at (?:async )?(?:.*? \\()?(.+?):\\d+:\\d+\\)?$/.exec(text);\r\n if (match) return clean(match[1]);\r\n if (text.startsWith('at ')) return undefined;\r\n match = /^(?:[^@]*@)?(.+?):\\d+:\\d+$/.exec(text);\r\n return match ? clean(match[1]) : undefined;\r\n}\r\n\r\nfunction clean(file: string): string | undefined {\r\n // `eval at fn (file:1:2), <anonymous>` and friends name no file of their own.\r\n if (!file || file.includes('eval at ') || file === '<anonymous>' || file === 'native') return undefined;\r\n return file;\r\n}\r\n\r\n/** Every file in a stack, in order, each once. */\r\nexport function stackFiles(stack: string): string[] {\r\n const out: string[] = [];\r\n for (const line of stack.split('\\n')) {\r\n const file = frameFile(line);\r\n if (file && !out.includes(file)) out.push(file);\r\n }\r\n return out;\r\n}\r\n\r\n/** Parse the registry entries not seen yet: each one's top frame is the file that registered it. */\r\nfunction refresh(): void {\r\n const entries = registry();\r\n if (!entries) return;\r\n for (const stack in entries) {\r\n if (parsed.has(stack)) continue;\r\n parsed.add(stack);\r\n const id = entries[stack];\r\n if (typeof id !== 'string') continue;\r\n for (const line of stack.split('\\n')) {\r\n const file = frameFile(line);\r\n if (file) {\r\n files.set(file, id);\r\n break;\r\n }\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * The debug IDs of the files in `stack` that registered one, or undefined when none did (no\r\n * injected build, or only third-party frames).\r\n */\r\nexport function debugIdsFor(stack: string | undefined): Record<string, string> | undefined {\r\n if (!stack) return undefined;\r\n try {\r\n refresh();\r\n if (files.size === 0) return undefined;\r\n let out: Record<string, string> | undefined;\r\n for (const file of stackFiles(stack)) {\r\n const id = files.get(file);\r\n if (id) (out ??= {})[file] = id;\r\n }\r\n return out;\r\n } catch {\r\n return undefined;\r\n }\r\n}\r\n\r\n/** `{ 'zharp.debug_ids': '<json>' }` for `stack`, or an empty object. Spread it into an error's attributes. */\r\nexport function debugIdAttributes(stack: string | undefined): Record<string, string> {\r\n const ids = debugIdsFor(stack);\r\n return ids ? { [DEBUG_IDS_ATTRIBUTE]: JSON.stringify(ids) } : {};\r\n}\r\n\r\n/** For tests: forget everything parsed. */\r\nexport function resetDebugIdCache(): void {\r\n files.clear();\r\n parsed.clear();\r\n}\r\n","/**\r\n * `zharp.debug_ids` on errors that do not come through Zharp's own API: exceptions recorded on\r\n * spans by the instrumentations (`span.recordException`), and error logs from the pino and\r\n * winston bridges. Zharp's own error logs already have it (see errors.ts); these processors only\r\n * fill it in where a stack is present and the attribute is not.\r\n */\r\nimport type { Context } from '@opentelemetry/api';\r\nimport type { ReadableSpan, Span, SpanProcessor } from '@opentelemetry/sdk-trace';\r\nimport type { LogRecordProcessor, ReadWriteLogRecord } from '@opentelemetry/sdk-logs';\r\nimport { DEBUG_IDS_ATTRIBUTE, debugIdsFor } from '@zharp/internal/debug-ids';\r\n\r\nconst STACK = 'exception.stacktrace';\r\n\r\nexport class DebugIdSpanProcessor implements SpanProcessor {\r\n onStart(_span: Span, _parentContext: Context): void {}\r\n\r\n /** Exception events are added while the span runs; by its end they are all there. */\r\n onEnd(span: ReadableSpan): void {\r\n try {\r\n for (const event of span.events) {\r\n const attributes = event.attributes as Record<string, unknown> | undefined;\r\n if (event.name !== 'exception' || !attributes || attributes[DEBUG_IDS_ATTRIBUTE] !== undefined) continue;\r\n const stack = attributes[STACK];\r\n const ids = typeof stack === 'string' ? debugIdsFor(stack) : undefined;\r\n if (ids) attributes[DEBUG_IDS_ATTRIBUTE] = JSON.stringify(ids);\r\n }\r\n } catch {\r\n // Never let telemetry break a request.\r\n }\r\n }\r\n\r\n forceFlush(): Promise<void> {\r\n return Promise.resolve();\r\n }\r\n\r\n shutdown(): Promise<void> {\r\n return Promise.resolve();\r\n }\r\n}\r\n\r\nexport class DebugIdLogProcessor implements LogRecordProcessor {\r\n onEmit(record: ReadWriteLogRecord, _ctx?: Context): void {\r\n try {\r\n const attributes = record.attributes as Record<string, unknown>;\r\n const stack = attributes[STACK];\r\n if (typeof stack !== 'string' || attributes[DEBUG_IDS_ATTRIBUTE] !== undefined) return;\r\n const ids = debugIdsFor(stack);\r\n if (ids) record.setAttribute(DEBUG_IDS_ATTRIBUTE, JSON.stringify(ids));\r\n } catch {\r\n // As above.\r\n }\r\n }\r\n\r\n forceFlush(): Promise<void> {\r\n return Promise.resolve();\r\n }\r\n\r\n shutdown(): Promise<void> {\r\n return Promise.resolve();\r\n }\r\n}\r\n","/**\r\n * Errors as Zharp reads them: a log record of severity ERROR or FATAL carrying\r\n * `exception.type`, `exception.message` and `exception.stacktrace`, plus `zharp.handled`.\r\n *\r\n * A log rather than a span event because an error does not always happen inside a span (a\r\n * crash at startup, a timer callback), and one shape for both keeps the count honest: the server\r\n * makes an error event from either, so sending both would count every error twice.\r\n */\r\nimport { inspect } from 'node:util';\r\nimport { debugIdAttributes } from '@zharp/internal/debug-ids';\r\n\r\n/** OTLP severity numbers. */\r\nexport const SEVERITY = { trace: 1, debug: 5, info: 9, warn: 13, error: 17, fatal: 21 } as const;\r\nexport type Level = keyof typeof SEVERITY;\r\n\r\n/** Whatever was thrown, as an Error — a rejection with a string or an object is still worth a stack. */\r\nexport function asError(value: unknown): Error {\r\n if (value instanceof Error) return value;\r\n if (value && typeof value === 'object' && typeof (value as any).message === 'string') {\r\n const error = new Error((value as any).message);\r\n error.name = typeof (value as any).name === 'string' ? (value as any).name : 'Error';\r\n if (typeof (value as any).stack === 'string') error.stack = (value as any).stack;\r\n return error;\r\n }\r\n const text = typeof value === 'string' ? value : inspect(value, { depth: 3, breakLength: Infinity });\r\n const error = new Error(`Non-Error thrown: ${text}`);\r\n // The stack points here, not at the throw — but it is the only one there is.\r\n return error;\r\n}\r\n\r\n/** The name an error is grouped under: `TypeError`, or a custom class's own name. */\r\nfunction typeOf(error: Error): string {\r\n const name = error.name && error.name !== 'Error' ? error.name : error.constructor?.name;\r\n return name || 'Error';\r\n}\r\n\r\n/** The `exception.*` attributes for `error`. The stack keeps its first `Type: message` line. */\r\nexport function exceptionAttributes(error: Error, handled: boolean): Record<string, string> {\r\n const type = typeOf(error);\r\n const message = error.message || '';\r\n let stack = typeof error.stack === 'string' && error.stack ? error.stack : `${type}: ${message}`;\r\n // A cause is part of what went wrong; Node prints it, so the stack shown in Zharp does too.\r\n const cause = (error as { cause?: unknown }).cause;\r\n if (cause instanceof Error && cause.stack) stack += `\\nCaused by: ${cause.stack}`;\r\n return {\r\n 'exception.type': type,\r\n 'exception.message': message,\r\n 'exception.stacktrace': stack,\r\n 'zharp.handled': handled ? 'true' : 'false',\r\n ...debugIdAttributes(stack),\r\n };\r\n}\r\n","/** Sent as `telemetry.sdk.version`. Bumped with package.json. */\r\nexport const VERSION = '0.1.0';\r\n","import { ZharpNode } from './zharp';\r\n\r\nexport { ZharpNode } from './zharp';\r\nexport { VERSION } from './version';\r\nexport type { NodeOptions, ZharpUser, Attributes, AttributeValue } from './types';\r\n\r\n// One instance per process, kept on globalThis: `instrument.mjs` imports the ES build and the\r\n// application may `require` the CommonJS one, and both must reach the SDK that was started.\r\nconst g = globalThis as any;\r\nexport const Zharp: ZharpNode = g.__ZHARP_NODE__ ?? (g.__ZHARP_NODE__ = new ZharpNode());\r\nexport default Zharp;\r\n"],"mappings":";;;;;;;;AASA,SAAS,YAAY,sBAAsB;AAC3C;AAAA,EAGE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA,SAAAA;AAAA,OAMK;AACP,SAAS,qBAAqB,sBAAsB,iCAAiC;AACrF,SAAS,aAAa,cAAc,8BAA8B;AAClE,SAAS,eAAe;AACxB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP,SAAS,+BAAwD;AACjE,SAAS,yBAAyB;AAClC,SAAS,uBAAuB;AAChC,SAAS,mCAAmC;;;AC3BrC,SAAS,YAAY,MAA0B;AACpD,MAAI;AACF,UAAM,OAAY,OAAO,YAAY,cAAc,UAAU;AAC7D,QAAI,QAAQ,OAAO,KAAK,qBAAqB,YAAY;AACvD,aAAO,KAAK,iBAAiB,QAAQ,IAAI,EAAE,KAAK;AAAA,IAClD;AACA,UAAM,MAAM,OAAO,WAAW,eAAe,OAAO,cAAY,aAAa,YAAU;AACvF,WAAO,MAAM,IAAI,IAAI,IAAI;AAAA,EAC3B,QAAQ;AACN,WAAO;AAAA,EACT;AACF;;;ACTO,SAAS,QAAQ,MAAkC;AACxD,MAAI,OAAO,WAAW,eAAe,OAAO,YAAY,eAAe,CAAC,QAAQ,IAAK,QAAO;AAC5F,QAAM,QAAQ,QAAQ,IAAI,IAAI;AAC9B,SAAO,SA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AAC7B,WAAO,EAAE,UAAU,iBAAiB,OAAO;AAAA,EAC7C;AAAA,EAEA,WAAmB;AACjB,WAAO;AAAA,EACT;AACF;AAGA,IAAM,wBAAN,MAAyD;AAAA,EACvD,YAA6B,OAA0B;AAA1B;AAAA,EAA2B;AAAA,EAA3B;AAAA,EAE7B,SAAe;AAAA,EAAC;AAAA,EAEhB,QAAQ,SAAkB,SAAkB,QAAgC;AAC1E,WAAO,KAAK,MAAM,QAAQ,SAAS,SAAS,MAAM;AAAA,EACpD;AAAA,EAEA,SAAmB;AACjB,WAAO,CAAC;AAAA,EACV;AACF;;;ASzfA,IAAM,IAAI;AACH,IAAM,QAAmB,EAAE,mBAAmB,EAAE,iBAAiB,IAAI,UAAU;AACtF,IAAO,gBAAQ;","names":["trace","g","error","trace","g"]}
|
package/init.d.ts
ADDED
package/init.js
ADDED
package/init.mjs
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,86 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zharp/node",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Zharp Application Monitoring for Node.js — traces, logs and errors, on OpenTelemetry",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"module": "dist/index.mjs",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"import": {
|
|
11
|
+
"types": "./dist/index.d.mts",
|
|
12
|
+
"default": "./dist/index.mjs"
|
|
13
|
+
},
|
|
14
|
+
"require": {
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"default": "./dist/index.js"
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"./init": {
|
|
20
|
+
"types": "./init.d.ts",
|
|
21
|
+
"import": "./init.mjs",
|
|
22
|
+
"require": "./init.js"
|
|
23
|
+
},
|
|
24
|
+
"./package.json": "./package.json"
|
|
25
|
+
},
|
|
26
|
+
"sideEffects": [
|
|
27
|
+
"./init.js",
|
|
28
|
+
"./init.mjs"
|
|
29
|
+
],
|
|
30
|
+
"files": [
|
|
31
|
+
"dist",
|
|
32
|
+
"init.js",
|
|
33
|
+
"init.mjs",
|
|
34
|
+
"init.d.ts"
|
|
35
|
+
],
|
|
36
|
+
"engines": {
|
|
37
|
+
"node": ">=22.15.0"
|
|
38
|
+
},
|
|
39
|
+
"keywords": [
|
|
40
|
+
"zharp",
|
|
41
|
+
"apm",
|
|
42
|
+
"opentelemetry",
|
|
43
|
+
"tracing",
|
|
44
|
+
"logging",
|
|
45
|
+
"error-tracking",
|
|
46
|
+
"monitoring",
|
|
47
|
+
"observability",
|
|
48
|
+
"nodejs",
|
|
49
|
+
"nextjs"
|
|
50
|
+
],
|
|
51
|
+
"license": "MIT",
|
|
52
|
+
"repository": {
|
|
53
|
+
"type": "git",
|
|
54
|
+
"url": "git+https://github.com/zharp-io/zharp-javascript-lib.git",
|
|
55
|
+
"directory": "packages/node"
|
|
56
|
+
},
|
|
57
|
+
"homepage": "https://zharp.io/docs/sdks/node",
|
|
58
|
+
"bugs": "https://github.com/zharp-io/zharp-javascript-lib/issues",
|
|
59
|
+
"publishConfig": {
|
|
60
|
+
"access": "public"
|
|
61
|
+
},
|
|
62
|
+
"dependencies": {
|
|
63
|
+
"@opentelemetry/api": "^1.10.0",
|
|
64
|
+
"@opentelemetry/auto-instrumentations-node": "^0.82.0",
|
|
65
|
+
"@opentelemetry/core": "^3.0.0",
|
|
66
|
+
"@opentelemetry/exporter-logs-otlp-proto": "^0.300.0",
|
|
67
|
+
"@opentelemetry/exporter-trace-otlp-proto": "^0.300.0",
|
|
68
|
+
"@opentelemetry/instrumentation": "^0.300.0",
|
|
69
|
+
"@opentelemetry/resources": "^3.0.0",
|
|
70
|
+
"@opentelemetry/sdk-logs": "^3.0.0",
|
|
71
|
+
"@opentelemetry/sdk-node": "^0.300.0",
|
|
72
|
+
"@opentelemetry/sdk-trace": "^3.0.0",
|
|
73
|
+
"@opentelemetry/winston-transport": "^0.35.0"
|
|
74
|
+
},
|
|
75
|
+
"devDependencies": {
|
|
76
|
+
"@types/node": "^25.9.3",
|
|
77
|
+
"tsup": "^8.5.1",
|
|
78
|
+
"typescript": "^5.9.3",
|
|
79
|
+
"@zharp/internal": "0.0.0"
|
|
80
|
+
},
|
|
81
|
+
"scripts": {
|
|
82
|
+
"build": "tsup",
|
|
83
|
+
"dev": "tsup --watch",
|
|
84
|
+
"typecheck": "tsc --noEmit"
|
|
85
|
+
}
|
|
6
86
|
}
|