@clickhouse/clickstack-node 0.0.0-stage → 1.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,203 @@
1
+ Copyright 2016-2026 ClickHouse, Inc.
2
+
3
+ Apache License
4
+ Version 2.0, January 2004
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "Licensor" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "control" means (i) the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
+ outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ "You" (or "Your") shall mean an individual or Legal Entity
26
+ exercising permissions granted by this License.
27
+
28
+ "Source" form shall mean the preferred form for making modifications,
29
+ including but not limited to software source code, documentation
30
+ source, and configuration files.
31
+
32
+ "Object" form shall mean any form resulting from mechanical
33
+ transformation or translation of a Source form, including but
34
+ not limited to compiled object code, generated documentation,
35
+ and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or
38
+ Object form, made available under the License, as indicated by a
39
+ copyright notice that is included in or attached to the work
40
+ (an example is provided in the Appendix below).
41
+
42
+ "Derivative Works" shall mean any work, whether in Source or Object
43
+ form, that is based on (or derived from) the Work and for which the
44
+ editorial revisions, annotations, elaborations, or other modifications
45
+ represent, as a whole, an original work of authorship. For the purposes
46
+ of this License, Derivative Works shall not include works that remain
47
+ separable from, or merely link (or bind by name) to the interfaces of,
48
+ the Work and Derivative Works thereof.
49
+
50
+ "Contribution" shall mean any work of authorship, including
51
+ the original version of the Work and any modifications or additions
52
+ to that Work or Derivative Works thereof, that is intentionally
53
+ submitted to Licensor for inclusion in the Work by the copyright owner
54
+ or by an individual or Legal Entity authorized to submit on behalf of
55
+ the copyright owner. For the purposes of this definition, "submitted"
56
+ means any form of electronic, verbal, or written communication sent
57
+ to the Licensor or its representatives, including but not limited to
58
+ communication on electronic mailing lists, source code control systems,
59
+ and issue tracking systems that are managed by, or on behalf of, the
60
+ Licensor for the purpose of discussing and improving the Work, but
61
+ excluding communication that is conspicuously marked or otherwise
62
+ designated in writing by the copyright owner as "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, and in Source or Object form, provided that You
94
+ meet the following conditions:
95
+
96
+ (a) You must give any other recipients of the Work or
97
+ Derivative Works a copy of this License; and
98
+
99
+ (b) You must cause any modified files to carry prominent notices
100
+ stating that You changed the files; and
101
+
102
+ (c) You must retain, in the Source form of any Derivative Works
103
+ that You distribute, all copyright, patent, trademark, and
104
+ attribution notices from the Source form of the Work,
105
+ excluding those notices that do not pertain to any part of
106
+ the Derivative Works; and
107
+
108
+ (d) If the Work includes a "NOTICE" text file as part of its
109
+ distribution, then any Derivative Works that You distribute must
110
+ include a readable copy of the attribution notices contained
111
+ within such NOTICE file, excluding those notices that do not
112
+ pertain to any part of the Derivative Works, in at least one
113
+ of the following places: within a NOTICE text file distributed
114
+ as part of the Derivative Works; within the Source form or
115
+ documentation, if provided along with the Derivative Works; or,
116
+ within a display generated by the Derivative Works, if and
117
+ wherever such third-party notices normally appear. The contents
118
+ of the NOTICE file are for informational purposes only and
119
+ do not modify the License. You may add Your own attribution
120
+ notices within Derivative Works that You distribute, alongside
121
+ or as an addendum to the NOTICE text from the Work, provided
122
+ that such additional attribution notices cannot be construed
123
+ as modifying the License.
124
+
125
+ You may add Your own copyright statement to Your modifications and
126
+ may provide additional or different license terms and conditions
127
+ for use, reproduction, or distribution of Your modifications, or
128
+ for any such Derivative Works as a whole, provided Your use,
129
+ reproduction, and distribution of the Work otherwise complies with
130
+ the conditions stated in this License.
131
+
132
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
133
+ any Contribution intentionally submitted for inclusion in the Work
134
+ by You to the Licensor shall be under the terms and conditions of
135
+ this License, without any additional terms or conditions.
136
+ Notwithstanding the above, nothing herein shall supersede or modify
137
+ the terms of any separate license agreement you may have executed
138
+ with Licensor regarding such Contributions.
139
+
140
+ 6. Trademarks. This License does not grant permission to use the trade
141
+ names, trademarks, service marks, or product names of the Licensor,
142
+ except as required for reasonable and customary use in describing the
143
+ origin of the Work and reproducing the content of the NOTICE file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this License.
154
+
155
+ 8. Limitation of Liability. In no event and under no legal theory,
156
+ whether in tort (including negligence), contract, or otherwise,
157
+ unless required by applicable law (such as deliberate and grossly
158
+ negligent acts) or agreed to in writing, shall any Contributor be
159
+ liable to You for damages, including any direct, indirect, special,
160
+ incidental, or consequential damages of any character arising as a
161
+ result of this License or out of the use or inability to use the
162
+ Work (including but not limited to damages for loss of goodwill,
163
+ work stoppage, computer failure or malfunction, or any and all
164
+ other commercial damages or losses), even if such Contributor
165
+ has been advised of the possibility of such damages.
166
+
167
+ 9. Accepting Warranty or Additional Liability. While redistributing
168
+ the Work or Derivative Works thereof, You may choose to offer,
169
+ and charge a fee for, acceptance of support, warranty, indemnity,
170
+ or other liability obligations and/or rights consistent with this
171
+ License. However, in accepting such obligations, You may act only
172
+ on Your own behalf and on Your sole responsibility, not on behalf
173
+ of any other Contributor, and only if You agree to indemnify,
174
+ defend, and hold each Contributor harmless for any liability
175
+ incurred by, or claims asserted against, such Contributor by reason
176
+ of your accepting any such warranty or additional liability.
177
+
178
+ END OF TERMS AND CONDITIONS
179
+
180
+ APPENDIX: How to apply the Apache License to your work.
181
+
182
+ To apply the Apache License to your work, attach the following
183
+ boilerplate notice, with the fields enclosed by brackets "[]"
184
+ replaced with your own identifying information. (Don't include
185
+ the brackets!) The text should be enclosed in the appropriate
186
+ comment syntax for the file format. We also recommend that a
187
+ file or class name and description of purpose be included on the
188
+ same "printed page" as the copyright notice for easier
189
+ identification within third-party archives.
190
+
191
+ Copyright 2026 ClickHouse, Inc.
192
+
193
+ Licensed under the Apache License, Version 2.0 (the "License");
194
+ you may not use this file except in compliance with the License.
195
+ You may obtain a copy of the License at
196
+
197
+ http://www.apache.org/licenses/LICENSE-2.0
198
+
199
+ Unless required by applicable law or agreed to in writing, software
200
+ distributed under the License is distributed on an "AS IS" BASIS,
201
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202
+ See the License for the specific language governing permissions and
203
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,283 @@
1
- # Temporary Holding Version
1
+ # @clickhouse/clickstack-node
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Traces, metrics and logs from Node.js apps to ClickStack, built on the upstream OpenTelemetry
4
+ Node.js SDK. One flag or one `init` call starts the SDK with the upstream auto-instrumentations,
5
+ records `console` output and crashes, and flushes telemetry on exit, termination signals and AWS
6
+ Lambda invocations. Exporters, batching, sampling and every `OTEL_*` variable stay upstream. Apps
7
+ that set up the SDK themselves do not need this package
8
+ ([Using the upstream SDK directly](#using-the-upstream-sdk-directly)).
9
+
10
+ If you're migrating from `@hyperdx/node-opentelemetry` please follow the
11
+ [migration guide](docs/migration.md).
12
+
13
+ ## Install
14
+
15
+ ```sh
16
+ npm install @clickhouse/clickstack-node
17
+ ```
18
+
19
+ The package needs Node.js 22.15 or later and ships ES module and CommonJS builds.
20
+ `@opentelemetry/api` is a peer dependency, which npm installs automatically, so the app and the
21
+ SDK share one copy.
22
+
23
+ ## Quick start
24
+
25
+ ```sh
26
+ export OTEL_EXPORTER_OTLP_ENDPOINT=https://example-collector.clickhouse.com:4318
27
+ export OTEL_EXPORTER_OTLP_HEADERS="authorization=<YOUR_INGESTION_API_KEY>"
28
+ export OTEL_SERVICE_NAME=example-app
29
+ node --import @clickhouse/clickstack-node/register server.js
30
+ ```
31
+
32
+ The endpoint is the OTLP HTTP address of your OpenTelemetry collector (port 4318), without
33
+ `/v1/traces`. With ClickStack, it is your service's collector URL.
34
+
35
+ The flag works for CommonJS and ES module apps, and `--require` works too. In `NODE_OPTIONS`, set
36
+ it only on the command that runs the app, because build tools and every other Node.js process
37
+ inherit it.
38
+
39
+ Or call `init` in code, at the top of a CommonJS entry file before anything else is required:
40
+
41
+ ```js
42
+ const { init } = require("@clickhouse/clickstack-node");
43
+
44
+ init({
45
+ endpoint: "https://example-collector.clickhouse.com:4318",
46
+ apiKey: "<YOUR_INGESTION_API_KEY>",
47
+ serviceName: "example-app",
48
+ });
49
+ ```
50
+
51
+ Static imports run before any code in an ES module, so an ES module app calls `init` in a file of
52
+ its own and preloads it: `node --import ./instrumentation.mjs server.mjs`.
53
+
54
+ | Option | Environment variable (wins) | Default | Meaning |
55
+ | ---------------------------- | -------------------------------------------------------------------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
56
+ | `endpoint` | `OTEL_EXPORTER_OTLP_ENDPOINT` | `http://localhost:4318` | OTLP/HTTP base URL of the collector. `/v1/traces`, `/v1/metrics` and `/v1/logs` are appended. |
57
+ | `serviceName` | `OTEL_SERVICE_NAME`, or `service.name` in `OTEL_RESOURCE_ATTRIBUTES` | `unknown_service:` and the executable name | `service.name` of all telemetry. |
58
+ | `environment` | `OTEL_RESOURCE_ATTRIBUTES` (`deployment.environment.name=<env>`) | None | `deployment.environment.name`, such as `production` or `staging`. |
59
+ | `apiKey` | `OTEL_EXPORTER_OTLP_HEADERS` (`authorization=<key>`) | None | Ingestion key, sent as the `authorization` header. Send the bare key; `Bearer <key>` works only on ClickStack 2.38.0 or later. |
60
+ | `httpBodyCapture` | `CLICKSTACK_CAPTURE_HTTP_BODY` | `false` | Records request and response bodies ([Privacy](#privacy)). |
61
+ | `instrumentations` | None | Upstream defaults | The `getNodeAutoInstrumentations()` config map. An `enabled` value here beats `OTEL_NODE_ENABLED_INSTRUMENTATIONS` and `OTEL_NODE_DISABLED_INSTRUMENTATIONS`. |
62
+ | `additionalInstrumentations` | None | `[]` | Instrumentation instances to add to the bundle's, for libraries the bundle does not cover. |
63
+
64
+ `init` writes `serviceName`, `endpoint`, `apiKey` and `httpBodyCapture` to their variables only
65
+ when those are unset or blank, so an operator's value wins and child processes inherit it;
66
+ `environment` goes on the resource only. When `OTEL_EXPORTER_OTLP_HEADERS` already holds other
67
+ headers, `apiKey` is ignored with a warning. Use either the flag or `init`: a second
68
+ start logs a warning and does nothing. The rest is fixed:
69
+
70
+ - Instrumentations: the upstream auto-instrumentations bundle with its defaults, plus `console`
71
+ capture (`@opentelemetry/instrumentation-console`) and crash capture. To turn `console` capture
72
+ off, add `console` to `OTEL_NODE_DISABLED_INSTRUMENTATIONS`. It is also off while
73
+ `OTEL_TRACES_EXPORTER`, `OTEL_METRICS_EXPORTER` or `OTEL_LOGS_EXPORTER` includes `console`,
74
+ because those exporters print with `console`.
75
+ - The router instrumentation is off. Express 5 is built on the `router` package, so with it every
76
+ Express middleware gets a second span and every route error three exception events. To turn it
77
+ on, list `router` in `OTEL_NODE_ENABLED_INSTRUMENTATIONS`, or set `enabled: true` for
78
+ `@opentelemetry/instrumentation-router` in `instrumentations`.
79
+ - Resource detectors: `container,host,os,process,serviceinstance,env`, so nothing probes cloud
80
+ metadata endpoints at startup. To add a cloud detector, set `OTEL_NODE_RESOURCE_DETECTORS` to the
81
+ whole list, without spaces and with `env` last, for example
82
+ `container,host,os,process,serviceinstance,aws,env`.
83
+ - Diagnostics go to stderr at WARN level (`OTEL_LOG_LEVEL`), unless the app registered its own
84
+ `diag` logger first. They include unknown names in `OTEL_NODE_ENABLED_INSTRUMENTATIONS`,
85
+ `OTEL_NODE_DISABLED_INSTRUMENTATIONS` and `OTEL_NODE_RESOURCE_DETECTORS`. Messages from this
86
+ package start with `clickstack-node:`.
87
+ - Every other OpenTelemetry variable keeps its upstream meaning, for example
88
+ `OTEL_EXPORTER_OTLP_PROTOCOL` (`http/protobuf`; `grpc` goes to port 4317),
89
+ `OTEL_TRACES_SAMPLER`, `OTEL_PROPAGATORS` and `OTEL_METRIC_EXPORT_INTERVAL`. Boolean variables
90
+ are true only for `true`. `OTEL_SDK_DISABLED=true` makes the flag and `init` do nothing.
91
+
92
+ Other functions:
93
+
94
+ - `flush(timeoutMillis)` exports what is buffered. It waits at most 5000 ms by default and never
95
+ rejects.
96
+ - `shutdown(timeoutMillis)` flushes and stops the SDK, with the same bound. Await it before your
97
+ own code exits the process ([Lifecycle](#lifecycle)).
98
+ - `withFlush(handler)` wraps an async AWS Lambda handler, so telemetry is exported before each
99
+ invocation returns.
100
+
101
+ ## Privacy
102
+
103
+ `console` output and crash stack traces are exported by default. Headers and bodies are recorded
104
+ only when you turn them on; they can hold personal data and credentials.
105
+
106
+ - Headers: `OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_{SERVER,CLIENT}_{REQUEST,RESPONSE}` each list
107
+ exact header names, comma-separated, such as `user-agent,x-request-id`. They are recorded as
108
+ `http.request.header.<name>` and `http.response.header.<name>`. Names on
109
+ `OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS` (by default
110
+ `authorization,cookie,set-cookie,proxy-authorization,x-api-key`) are never recorded.
111
+ - Bodies: `httpBodyCapture` records `node:http` server and client bodies and `fetch` bodies (on
112
+ Node.js 24.4 or later). Only textual UTF-8 bodies without a `Content-Encoding` are recorded, from
113
+ the first 8192 bytes of each body; others get a size only. Values of keys that contain
114
+ `password`, `passwd`, `secret`, `token`, `api_key`, `apikey`, `api-key`, `authorization`,
115
+ `cookie` or `session` become `[REDACTED]` in JSON-looking text (also one level of JSON escaped
116
+ inside a string) and in form fields. This is a best effort, so keep a redaction step in your
117
+ collector.
118
+ - The app's streams are never read, paused or resumed, and the bytes it sends and receives are
119
+ unchanged.
120
+
121
+ ## Using the upstream SDK directly
122
+
123
+ This file sets up the upstream SDK with the same instrumentations and defaults. Start the app with
124
+ `node --require ./telemetry.cjs app.js` and the variables from the quick start, plus
125
+ `OTEL_NODE_RESOURCE_DETECTORS=container,host,os,process,serviceinstance,env`.
126
+
127
+ ```js
128
+ // telemetry.cjs
129
+ const {
130
+ getNodeAutoInstrumentations,
131
+ getResourceDetectors,
132
+ } = require("@opentelemetry/auto-instrumentations-node");
133
+ const {
134
+ ConsoleInstrumentation,
135
+ } = require("@opentelemetry/instrumentation-console");
136
+ const { NodeSDK } = require("@opentelemetry/sdk-node");
137
+
138
+ // Without a log level, NodeSDK prints nothing, not even export errors.
139
+ process.env.OTEL_LOG_LEVEL ??= "warn";
140
+
141
+ const sdk = new NodeSDK({
142
+ // Reads OTEL_NODE_RESOURCE_DETECTORS; the default list includes the cloud detectors.
143
+ resourceDetectors: getResourceDetectors(),
144
+ instrumentations: [
145
+ getNodeAutoInstrumentations({
146
+ "@opentelemetry/instrumentation-runtime-node": {
147
+ captureUncaughtException: true,
148
+ },
149
+ // Express 5 is already covered by the express instrumentation.
150
+ "@opentelemetry/instrumentation-router": { enabled: false },
151
+ }),
152
+ new ConsoleInstrumentation(),
153
+ ],
154
+ });
155
+ sdk.start();
156
+
157
+ process.once("SIGTERM", () => {
158
+ sdk.shutdown().finally(() => process.kill(process.pid, "SIGTERM"));
159
+ });
160
+ ```
161
+
162
+ What the package adds to this:
163
+
164
+ - ES modules: upstream registers no ES module loader hook on the 2.x line. Add
165
+ `--experimental-loader=@opentelemetry/instrumentation/hook.mjs`, which prints an
166
+ `ExperimentalWarning` on every start.
167
+ - Crashes: the record of an uncaught exception is exported before Node.js exits, and the process
168
+ still exits with code 1. Upstream drops it.
169
+ - Signals: SIGINT as well as SIGTERM, a bounded shutdown, and the exit status when the app runs as
170
+ PID 1, where a re-raised signal is ignored.
171
+ - AWS Lambda: `withFlush`, and the flush after each invocation by
172
+ `@opentelemetry/instrumentation-aws-lambda`, which `NodeSDK` leaves bound to a no-op provider. It
173
+ now also flushes logs, and ends before the invocation's deadline.
174
+ - Header capture from the variables above, and body capture. Upstream reads no header variables
175
+ and has no body option.
176
+
177
+ ## What is emitted
178
+
179
+ - Resource: `service.name`, `deployment.environment.name` when set, `telemetry.sdk.*`,
180
+ `telemetry.distro.name` (`clickstack-node`), `telemetry.distro.version`, and the detector
181
+ attributes (`host.*`, `os.*`, `process.*`, `container.id`, `service.instance.id`).
182
+ - Spans, metrics and log records from the upstream instrumentations, unchanged.
183
+ - `console` log records: the formatted message as the body, a severity number per method (`debug`
184
+ 5, `log` and `info` 9, `warn` 13, `error` 17) and the active trace context.
185
+ - A FATAL log record (severity number 21, body `exception`) with `exception.type`,
186
+ `exception.message` and `exception.stacktrace` for an uncaught exception
187
+ ([Errors](#errors)).
188
+ - With capture on: `http.request.header.<name>` and `http.response.header.<name>` (string arrays),
189
+ `http.request.body.content` and `http.response.body.content`, and `http.request.body.size` and
190
+ `http.response.body.size` (bytes). The body keys are in development in the semantic conventions.
191
+
192
+ ## Errors
193
+
194
+ - Uncaught exceptions, and unhandled rejections under Node's default
195
+ `--unhandled-rejections=throw`, become the FATAL log record, exported before the process exits
196
+ ([Lifecycle](#lifecycle)). It carries the active trace when the error comes from an asynchronous
197
+ callback, such as a timer or a rejected promise. A request still open at the crash exports no
198
+ span.
199
+ - `exception.stacktrace` is the raw stack, with the error's `cause` chain, up to five deep,
200
+ appended as `Caused by: Name: message` sections. A thrown value that is not an error, such as
201
+ `throw { code: 1 }`, is recorded as JSON text in `exception.message`; Node.js itself wraps a
202
+ rejection reason that is not an error in an `ERR_UNHANDLED_REJECTION` error.
203
+ - Start TypeScript and bundled apps with `--enable-source-maps`, for example in `NODE_OPTIONS`, so
204
+ that stack traces point to your sources when the error happens. ClickStack maps only browser
205
+ stack traces.
206
+ - An app `uncaughtException` listener takes over the exit: the FATAL record is still recorded, but
207
+ the package neither prints the error nor exits, so await `flush()` before your listener ends the
208
+ process. An app `unhandledRejection` listener turns crash capture off for rejections, because
209
+ Node.js then no longer treats them as crashes.
210
+ - Errors thrown in route handlers of instrumented frameworks, such as Express, Koa, Hapi and
211
+ NestJS, are recorded as `exception` events on the handler's span.
212
+ - Errors that your code catches are not recorded. Record them on the active span:
213
+
214
+ ```js
215
+ import { SpanStatusCode, trace } from "@opentelemetry/api";
216
+
217
+ const span = trace.getActiveSpan();
218
+ span?.recordException(err);
219
+ span?.setStatus({ code: SpanStatusCode.ERROR });
220
+ ```
221
+
222
+ - `console.error(err)` sends a log record whose body is the formatted error with its stack trace.
223
+ It has no `exception.*` attributes, so it does not count as an exception.
224
+ - Telemetry still buffered when the app calls `process.exit()` is lost unless the app awaits
225
+ `shutdown()` first.
226
+
227
+ ## Lifecycle
228
+
229
+ - SIGTERM and SIGINT: the SDK shuts down (at most 5 seconds) and the signal is raised again, so the
230
+ process exits with 143 or 130. If the app has its own listener for the signal, the SDK only
231
+ flushes and the app owns the exit; await `shutdown()` in that listener before it exits.
232
+ - Uncaught exceptions, and unhandled rejections under the default `--unhandled-rejections=throw`:
233
+ the error goes to stderr as Node.js prints it, the SDK shuts down, and the process exits with
234
+ code 1, after 2 seconds when `@sentry/node` is installed so that Sentry can send its event. An app
235
+ `uncaughtException` listener takes over the exit ([Errors](#errors)).
236
+ - When the event loop empties, the SDK shuts down. `process.exit()` skips this, so scripts call
237
+ `await shutdown()` first.
238
+ - When the collector cannot be reached, these shutdowns wait the full 5 seconds. A second Ctrl-C,
239
+ more than a second after the first, exits at once. Set `OTEL_SDK_DISABLED=true` where no
240
+ collector runs.
241
+ - In Docker, use the exec form of `CMD` (a JSON array), or `docker run --init`. In the shell form,
242
+ `/bin/sh` is PID 1 and does not forward signals, so `docker stop` kills the app after 10 seconds
243
+ without a flush.
244
+ - On AWS Lambda, set `NODE_OPTIONS=--import @clickhouse/clickstack-node/register` and wrap the
245
+ handler. Only async handlers are supported. Flushes end 500 ms before the invocation's deadline,
246
+ so an unreachable collector does not make invocations time out.
247
+
248
+ ```js
249
+ import { withFlush } from "@clickhouse/clickstack-node";
250
+
251
+ export const handler = withFlush(async (event) => {
252
+ console.log("order received", event.id);
253
+ return { statusCode: 200 };
254
+ });
255
+ ```
256
+
257
+ - The flag does nothing in worker threads. `init` in a worker starts an SDK for that worker only.
258
+
259
+ ## Compatibility
260
+
261
+ - Node.js 22.15 or later. CI runs the latest 22, 24 and 26. Windows is not tested.
262
+ - OpenTelemetry JS 2.x: `@opentelemetry/sdk-node` `^0.223.0`, `@opentelemetry/core` `^2.12.0` and
263
+ `@opentelemetry/auto-instrumentations-node` `^0.81.0`, with `@opentelemetry/api`
264
+ `>=1.9.1 <1.10.0`.
265
+ - ES modules: the flag uses synchronous loader hooks on Node.js 22.22.3 or later, 24.11.1 or later
266
+ and 26, and `module.register()` on earlier versions and where `require()` of ES modules is off,
267
+ such as AWS Lambda. With `module.register()`, a named import from `node:http` after the import of
268
+ a package that loads `node:http` itself stays uninstrumented (import `node:http` first), and an ES
269
+ module entry file needs a file extension.
270
+ - Default imports of CommonJS packages: the default export does not see functions that an
271
+ instrumentation replaces on the package's exports. With `import grpc from "@grpc/grpc-js"`, gRPC
272
+ client calls get no spans; use `import * as grpc from "@grpc/grpc-js"` or named imports.
273
+ - TypeScript: CommonJS TypeScript fails under any ES module loader hook on Node.js 22 and on 24.0
274
+ to 24.11, so use `--require` there.
275
+ - Bundlers: code that a bundler inlined cannot be instrumented, and nothing warns. Keep this
276
+ package and the instrumented libraries external (esbuild `--packages=external`, webpack
277
+ `externals`, Next.js `serverExternalPackages`). In Next.js, call `init` from `register()` in
278
+ `instrumentation.ts` when `process.env.NEXT_RUNTIME === "nodejs"`.
279
+ - ClickStack: any version that accepts the ingestion key as a bare `authorization` header.
280
+
281
+ ## License
282
+
283
+ [Apache-2.0](LICENSE)
@@ -0,0 +1,22 @@
1
+ // \0rolldown/runtime.js
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
22
+ exports.__toESM = __toESM;
@@ -0,0 +1,115 @@
1
+ const require_rules = require("./rules.cjs");
2
+ let node_events = require("node:events");
3
+ // src/body/http.ts
4
+ function isIncoming(message) {
5
+ return !("getHeader" in message);
6
+ }
7
+ function observe(message) {
8
+ const capture = new require_rules.BodyCapture();
9
+ const copy = (chunk, encoding) => {
10
+ try {
11
+ capture.add(chunk, encoding);
12
+ } catch (err) {
13
+ require_rules.reportFailure(err);
14
+ }
15
+ };
16
+ if (isIncoming(message)) {
17
+ const { headers } = message;
18
+ const meta = {
19
+ contentType: headers["content-type"],
20
+ contentEncoding: headers["content-encoding"],
21
+ contentLength: headers["content-length"]
22
+ };
23
+ const emit = message.emit.bind(message);
24
+ message.emit = (event, ...args) => {
25
+ if (event === "data") copy(args[0], message.readableEncoding);
26
+ return emit(event, ...args);
27
+ };
28
+ return {
29
+ capture,
30
+ meta: () => ({
31
+ ...meta,
32
+ complete: message.complete
33
+ })
34
+ };
35
+ }
36
+ const wrap = (original) => (...args) => {
37
+ const ended = message.writableEnded;
38
+ const result = Reflect.apply(original, message, args);
39
+ if (!ended && typeof args[0] !== "function") copy(args[0], args[1]);
40
+ return result;
41
+ };
42
+ message.write = wrap(message.write.bind(message));
43
+ message.end = wrap(message.end.bind(message));
44
+ let written = /* @__PURE__ */ new Map();
45
+ if ("writeHead" in message) {
46
+ const response = message;
47
+ const writeHead = response.writeHead.bind(response);
48
+ response.writeHead = ((...args) => {
49
+ const result = writeHead(...args);
50
+ try {
51
+ const raw = args.slice(1).find((a) => typeof a === "object" && a !== null);
52
+ const list = Array.isArray(raw) ? raw.flat() : Object.entries(raw ?? {}).flat();
53
+ if (list.length > 0) written = require_rules.headerMap(list);
54
+ } catch (err) {
55
+ require_rules.reportFailure(err);
56
+ }
57
+ return result;
58
+ });
59
+ }
60
+ const header = (name) => message.getHeader(name) ?? written.get(name);
61
+ return {
62
+ capture,
63
+ meta: () => ({
64
+ contentType: header("content-type"),
65
+ contentEncoding: header("content-encoding"),
66
+ contentLength: header("content-length"),
67
+ complete: message.writableEnded
68
+ })
69
+ };
70
+ }
71
+ /**
72
+ * Creates the `node:http` body hooks.
73
+ *
74
+ * @returns Hooks for `instrumentation-http`.
75
+ */
76
+ function createHttpBodyHooks() {
77
+ const exchanges = /* @__PURE__ */ new WeakMap();
78
+ const finalize = (span) => {
79
+ try {
80
+ const ex = exchanges.get(span);
81
+ exchanges.delete(span);
82
+ if (ex === void 0 || !span.isRecording()) return;
83
+ span.setAttributes(ex.request.capture.attributes("request", ex.request.meta()));
84
+ if (ex.response !== void 0 && !require_rules.responseHasNoBody(ex.method, ex.status?.())) span.setAttributes(ex.response.capture.attributes("response", ex.response.meta()));
85
+ } catch (err) {
86
+ require_rules.reportFailure(err);
87
+ }
88
+ };
89
+ return {
90
+ requestHook(span, request) {
91
+ if (!span.isRecording()) return;
92
+ exchanges.set(span, {
93
+ method: request.method,
94
+ request: observe(request)
95
+ });
96
+ if (!isIncoming(request)) {
97
+ const done = () => {
98
+ finalize(span);
99
+ };
100
+ request.on(node_events.errorMonitor, done).on("close", done);
101
+ }
102
+ },
103
+ responseHook(span, response) {
104
+ const ex = exchanges.get(span);
105
+ if (ex === void 0) return;
106
+ ex.response = observe(response);
107
+ ex.status = () => response.statusCode;
108
+ if (!isIncoming(response)) response.on(node_events.errorMonitor, () => {
109
+ finalize(span);
110
+ });
111
+ },
112
+ finalize
113
+ };
114
+ }
115
+ exports.createHttpBodyHooks = createHttpBodyHooks;