@davidilie/telemetry-next 0.0.0-bootstrap.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 ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,174 @@
1
+ # `@davidilie/telemetry-next`
2
+
3
+ Next.js 16 server instrumentation backed by `@vercel/otel` and the shared
4
+ DavidApps client. It has a strict runtime boundary:
5
+
6
+ - `@davidilie/telemetry-next` is runtime-neutral and contains request-error
7
+ reporting types/helpers.
8
+ - `@davidilie/telemetry-next/node` registers the Node provider and must be
9
+ dynamically imported only from the Node branch of `instrumentation.ts`.
10
+
11
+ Node.js 20.9 or newer, Next.js 16, and OpenTelemetry API 1.x are supported.
12
+
13
+ ```sh
14
+ pnpm add @davidilie/telemetry-next @opentelemetry/api
15
+ ```
16
+
17
+ ## Server setup
18
+
19
+ ```ts
20
+ // instrumentation.ts
21
+ import type { Instrumentation } from "next";
22
+ import {
23
+ createNextRequestErrorHandler,
24
+ type NextRequestErrorHandler,
25
+ } from "@davidilie/telemetry-next";
26
+
27
+ let reportRequestError: NextRequestErrorHandler | undefined;
28
+
29
+ export async function register() {
30
+ if (process.env.NEXT_RUNTIME !== "nodejs") return;
31
+
32
+ const { registerNextTelemetry } = await import(
33
+ "@davidilie/telemetry-next/node"
34
+ );
35
+
36
+ const deployedSha = process.env.GIT_SHA!;
37
+ const telemetry = registerNextTelemetry({
38
+ resource: {
39
+ serviceName: "storefront",
40
+ serviceVersion: deployedSha,
41
+ environment: process.env.DEPLOYMENT_ENV ?? "production",
42
+ namespace: "storefront",
43
+ repositoryUrl: "https://github.com/example/storefront",
44
+ commitSha: deployedSha,
45
+ attributes: {
46
+ "davidapps.project.id": "storefront",
47
+ },
48
+ },
49
+ });
50
+
51
+ reportRequestError = createNextRequestErrorHandler({ telemetry });
52
+ }
53
+
54
+ export const onRequestError: Instrumentation.onRequestError = async (
55
+ error,
56
+ request,
57
+ context,
58
+ ) => reportRequestError?.(error, request, context);
59
+ ```
60
+
61
+ `serviceVersion` and `commitSha` must be the exact immutable SHA deployed in
62
+ the running image. `davidapps.project.id` must be nested in
63
+ `resource.attributes`.
64
+
65
+ Configure the private Alloy receiver through standard OTel variables:
66
+
67
+ ```sh
68
+ OTEL_EXPORTER_OTLP_ENDPOINT=http://alloy.observability.svc.cluster.local:4318
69
+ OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
70
+ ```
71
+
72
+ `registerNextTelemetry` calls `registerOTel` once per JavaScript global and
73
+ returns the same client on repeated calls. Its optional `otel` object accepts
74
+ `@vercel/otel` configuration other than `serviceName` and `attributes`, which
75
+ are derived from the shared resource contract. Unless `otel.traceSampler` is
76
+ provided, registration builds a parent-based ratio sampler from `sampleRate`.
77
+ Only a concrete OpenTelemetry `Sampler` is accepted, not `@vercel/otel`'s named
78
+ sampler strings. Either sampler is wrapped in a mutable provider-wide gate, so
79
+ `telemetry.setEnabled(...)` and `telemetry.setConsent(...)` immediately control
80
+ new automatic and client-created spans, including children of sampled parents.
81
+ Already queued/exported work is not recalled.
82
+
83
+ Provider registration owns trace sampling and the Node adapter applies
84
+ `sampleRate` once to logs; core does not make a second decision for those
85
+ signals. OTel histogram measurements remain aggregated instead of randomly
86
+ sampling points.
87
+
88
+ Measurements default to short trace spans because `@vercel/otel` does not
89
+ configure a metrics reader by default. If `otel.metricReaders` is non-empty,
90
+ the default becomes OTel metrics. Set `measurementMode: "spans"`, `"metrics"`,
91
+ or `"both"` explicitly when the representation must not depend on provider
92
+ configuration; metric attributes require `metricAttributeAllowlist`.
93
+
94
+ Do not import `@davidilie/telemetry-node/register` in a Next.js app. This
95
+ package deliberately makes `@vercel/otel` the only provider registration.
96
+
97
+ ## Request errors
98
+
99
+ `createNextRequestErrorHandler` maps Next's request/context data to bounded
100
+ attributes, captures the exception, then awaits the client's core flush as
101
+ required by the `onRequestError` lifecycle.
102
+
103
+ It records:
104
+
105
+ - `http.request.method` and `url.path`
106
+ - `next.router.kind`, `next.route.path`, and `next.route.type`
107
+ - Optional render source/type, revalidation reason, and Next error digest
108
+ - Static attributes passed to the helper
109
+
110
+ Request headers are deliberately not captured. Avoid putting path parameters,
111
+ queries, or personal identifiers into custom attributes.
112
+
113
+ ```ts
114
+ const reportRequestError = createNextRequestErrorHandler({
115
+ telemetry,
116
+ attributes: { "app.surface": "storefront" },
117
+ beforeCapture: async (error, request, context) => {
118
+ // Returning false drops this report. Keep this predicate cheap.
119
+ return context.routeType !== "action" || shouldReport(error);
120
+ },
121
+ onError: (error, stage) => diagnostics.report(stage, error),
122
+ });
123
+ ```
124
+
125
+ `beforeCapture` may be asynchronous. Hook, capture, flush, and diagnostic-hook
126
+ failures are contained so request error reporting never breaks the request.
127
+ `onError` receives `beforeCapture`, `capture`, or `flush` as its stage. Let Next
128
+ await the returned promise so the reporting attempt reaches its boundary.
129
+
130
+ The root helper is Edge-import-safe and can accept any reporter implementing
131
+ `captureException` plus optional `flush`. Provider registration in this package
132
+ is Node-only; an Edge runtime needs an explicitly Edge-safe reporter.
133
+
134
+ ## Browser setup
135
+
136
+ Server instrumentation does not initialize browser telemetry. Use
137
+ `@davidilie/telemetry-web` from `instrumentation-client.ts`:
138
+
139
+ ```ts
140
+ // instrumentation-client.ts
141
+ import { initializeWebTelemetry } from "@davidilie/telemetry-web";
142
+
143
+ const deployedSha = process.env.NEXT_PUBLIC_GIT_SHA!;
144
+
145
+ export const { client: browserTelemetry } = initializeWebTelemetry({
146
+ url: `${process.env.NEXT_PUBLIC_TELEMETRY_URL}/collect`,
147
+ publicKey: process.env.NEXT_PUBLIC_TELEMETRY_KEY,
148
+ resource: {
149
+ serviceName: "storefront-web",
150
+ serviceVersion: deployedSha,
151
+ environment: process.env.NODE_ENV,
152
+ commitSha: deployedSha,
153
+ platform: "web",
154
+ attributes: { "davidapps.project.id": "storefront" },
155
+ },
156
+ });
157
+ ```
158
+
159
+ Values prefixed `NEXT_PUBLIC_` are visible to every browser user. The endpoint
160
+ and public key are routing identifiers, not secrets.
161
+
162
+ ## Logs and shutdown
163
+
164
+ `@vercel/otel` registers tracing but does not configure an OTLP Logs provider
165
+ by default. The returned Node client therefore keeps structured JSON console
166
+ logging enabled unless `structuredConsole: false` is set. Kubernetes stdout
167
+ reaches VictoriaLogs with active `trace_id`, `span_id`, service, and release.
168
+
169
+ In long-running Next server processes the framework owns the provider
170
+ lifecycle. Do not call `shutdown()` during an ordinary request. Use `flush()`
171
+ only at a real lifecycle boundary; it drains core sends, not every private
172
+ batch inside `@vercel/otel`.
173
+
174
+ See the [web adapter](https://www.npmjs.com/package/@davidilie/telemetry-web), [Node adapter](https://www.npmjs.com/package/@davidilie/telemetry-node), [project onboarding](https://github.com/DavidIlie/davidapps-telemetry/blob/main/docs/adding-a-project.md), and [troubleshooting](https://github.com/DavidIlie/davidapps-telemetry/blob/main/docs/troubleshooting.md).
@@ -0,0 +1,11 @@
1
+ # Third-party notices
2
+
3
+ DavidApps Telemetry depends on permissively licensed open-source projects and used other SDKs as API and implementation references. Exact source commits and usage classifications are tracked in `UPSTREAM.yml`.
4
+
5
+ - Grafana Faro Web SDK — Apache License 2.0 — Copyright Grafana Labs.
6
+ - OpenTelemetry JS API 1.9.0/1.9.1, stable SDK 2.10.0, and experimental SDK 0.221.0 — Apache License 2.0 — Copyright The OpenTelemetry Authors.
7
+ - Vercel Analytics and Vercel OTEL — MIT License — Copyright Vercel, Inc.
8
+ - PostHog JavaScript SDKs — Apache-2.0/MIT — API reference only; no source is vendored.
9
+ - Honeycomb OpenTelemetry React Native — MIT License — Copyright Honeycomb.io.
10
+
11
+ Reference license texts are retained in `licenses/` so future adaptations cannot accidentally lose their attribution obligations. The current source tree does not vendor code from PostHog, Vercel, Honeycomb, or the OpenTelemetry demo.
package/UPSTREAM.yml ADDED
@@ -0,0 +1,56 @@
1
+ version: 1
2
+ sources:
3
+ - name: grafana-faro-web-sdk
4
+ repository: https://github.com/grafana/faro-web-sdk
5
+ license: Apache-2.0
6
+ commit: fafe843c8b21efe98a64250a11b48828604381fb
7
+ use: dependency
8
+ - name: vercel-otel
9
+ repository: https://github.com/vercel/otel
10
+ license: MIT
11
+ commit: 4745daa7559cd41d2fceedeadb56aeec7724735a
12
+ use: dependency
13
+ - name: vercel-analytics
14
+ repository: https://github.com/vercel/analytics
15
+ license: MIT
16
+ commit: d5df714080cbfdc7ee5e84b9aa6918e291a8e979
17
+ use: api-reference
18
+ - name: posthog-js
19
+ repository: https://github.com/PostHog/posthog-js
20
+ license: mixed-apache-2.0-and-mit
21
+ commit: 9a58462065dbe612ee4f6728d28c6275358643ad
22
+ use: api-reference
23
+ - name: opentelemetry-js-stable-2.10.0
24
+ repository: https://github.com/open-telemetry/opentelemetry-js
25
+ license: Apache-2.0
26
+ release: v2.10.0
27
+ commit: 76fa6b509e2b48d9cbee31cb37a2efc61dc4d384
28
+ use: dependency
29
+ - name: opentelemetry-js-experimental-0.221.0
30
+ repository: https://github.com/open-telemetry/opentelemetry-js
31
+ license: Apache-2.0
32
+ release: experimental/v0.221.0
33
+ commit: 76fa6b509e2b48d9cbee31cb37a2efc61dc4d384
34
+ use: dependency
35
+ - name: opentelemetry-js-api-1.9.0
36
+ repository: https://github.com/open-telemetry/opentelemetry-js
37
+ license: Apache-2.0
38
+ release: v1.9.0
39
+ commit: 08f597f3a3d71a4852b0afbba120af15ca038121
40
+ use: dependency
41
+ - name: opentelemetry-js-api-1.9.1
42
+ repository: https://github.com/open-telemetry/opentelemetry-js
43
+ license: Apache-2.0
44
+ release: v1.9.1
45
+ commit: 279458e7ddf16f7ddca5fe60c78672e05fafce66
46
+ use: dependency
47
+ - name: opentelemetry-demo-react-native
48
+ repository: https://github.com/open-telemetry/opentelemetry-demo
49
+ license: Apache-2.0
50
+ commit: 2e05c45b85b985a691cc75082c234e8d6ac0b2e9
51
+ use: api-reference
52
+ - name: honeycomb-opentelemetry-react-native
53
+ repository: https://github.com/honeycombio/honeycomb-opentelemetry-react-native
54
+ license: MIT
55
+ commit: 07d144459177a58a347e18be762cf8f04e63cb1d
56
+ use: api-reference
package/dist/index.cjs ADDED
@@ -0,0 +1,3 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_request_error = require("./request-error-CtYIz296.cjs");
3
+ exports.createNextRequestErrorHandler = require_request_error.createNextRequestErrorHandler;
@@ -0,0 +1,2 @@
1
+ import { a as NextRequestErrorReporter, i as NextRequestErrorHandlerConfig, n as NextRequestErrorDetails, o as createNextRequestErrorHandler, r as NextRequestErrorHandler, t as NextRequestErrorContext } from "./request-error-CANVaAVM.cjs";
2
+ export { type NextRequestErrorContext, type NextRequestErrorDetails, type NextRequestErrorHandler, type NextRequestErrorHandlerConfig, type NextRequestErrorReporter, createNextRequestErrorHandler };
@@ -0,0 +1,2 @@
1
+ import { a as NextRequestErrorReporter, i as NextRequestErrorHandlerConfig, n as NextRequestErrorDetails, o as createNextRequestErrorHandler, r as NextRequestErrorHandler, t as NextRequestErrorContext } from "./request-error-CANVaAVM.mjs";
2
+ export { type NextRequestErrorContext, type NextRequestErrorDetails, type NextRequestErrorHandler, type NextRequestErrorHandlerConfig, type NextRequestErrorReporter, createNextRequestErrorHandler };
package/dist/index.mjs ADDED
@@ -0,0 +1,2 @@
1
+ import { t as createNextRequestErrorHandler } from "./request-error-6cvJ4jpq.mjs";
2
+ export { createNextRequestErrorHandler };
package/dist/node.cjs ADDED
@@ -0,0 +1,48 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_request_error = require("./request-error-CtYIz296.cjs");
3
+ let _vercel_otel = require("@vercel/otel");
4
+ let _davidilie_telemetry_core = require("@davidilie/telemetry-core");
5
+ let _davidilie_telemetry_node = require("@davidilie/telemetry-node");
6
+ let _opentelemetry_sdk_trace_base = require("@opentelemetry/sdk-trace-base");
7
+ //#region src/node.ts
8
+ const REGISTRATION = Symbol.for("@davidilie/telemetry-next/registration");
9
+ function traceSampler(config) {
10
+ const configuredRate = Number.isFinite(config.sampleRate) ? config.sampleRate ?? 1 : 1;
11
+ return new _opentelemetry_sdk_trace_base.ParentBasedSampler({ root: new _opentelemetry_sdk_trace_base.TraceIdRatioBasedSampler(Math.min(1, Math.max(0, configuredRate))) });
12
+ }
13
+ /**
14
+ * Register the one OpenTelemetry provider used by the Next.js Node runtime.
15
+ * Import this entry point dynamically behind `NEXT_RUNTIME === "nodejs"`.
16
+ */
17
+ function registerNextTelemetry(config) {
18
+ if (process.env.NEXT_RUNTIME !== void 0 && process.env.NEXT_RUNTIME !== "nodejs") throw new Error("@davidilie/telemetry-next/node can only register in the Next.js Node runtime");
19
+ const sharedGlobal = globalThis;
20
+ const existing = sharedGlobal[REGISTRATION];
21
+ if (existing) return existing;
22
+ const resource = (0, _davidilie_telemetry_core.sanitizeResource)(config.resource);
23
+ const sampler = new _davidilie_telemetry_node.DynamicTelemetrySampler(config.otel?.traceSampler ?? traceSampler(config), {
24
+ enabled: config.enabled ?? true,
25
+ consent: config.consent ?? "granted"
26
+ });
27
+ (0, _vercel_otel.registerOTel)({
28
+ ...config.otel,
29
+ traceSampler: sampler,
30
+ serviceName: resource.serviceName,
31
+ attributes: (0, _davidilie_telemetry_node.telemetryResourceAttributes)(resource)
32
+ });
33
+ const client = new _davidilie_telemetry_node.NodeTelemetryClient({
34
+ ...config,
35
+ resource,
36
+ providerManagedSampling: true,
37
+ onCollectionStateChange: (state) => {
38
+ sampler.setEnabled(state.enabled);
39
+ sampler.setConsent(state.consent);
40
+ },
41
+ measurementMode: config.measurementMode ?? (config.otel?.metricReaders?.length ? "metrics" : "spans")
42
+ });
43
+ sharedGlobal[REGISTRATION] = client;
44
+ return client;
45
+ }
46
+ //#endregion
47
+ exports.createNextRequestErrorHandler = require_request_error.createNextRequestErrorHandler;
48
+ exports.registerNextTelemetry = registerNextTelemetry;
@@ -0,0 +1,18 @@
1
+ import { i as NextRequestErrorHandlerConfig, o as createNextRequestErrorHandler, r as NextRequestErrorHandler } from "./request-error-CANVaAVM.cjs";
2
+ import { Configuration } from "@vercel/otel";
3
+ import { NodeTelemetryClient, NodeTelemetryConfig } from "@davidilie/telemetry-node";
4
+ import { Sampler } from "@opentelemetry/sdk-trace-base";
5
+ //#region src/node.d.ts
6
+ interface RegisterNextTelemetryConfig extends NodeTelemetryConfig {
7
+ otel?: Omit<Configuration, "attributes" | "serviceName" | "traceSampler"> & {
8
+ /** A concrete sampler so dynamic consent can wrap it safely. */
9
+ traceSampler?: Sampler;
10
+ };
11
+ }
12
+ /**
13
+ * Register the one OpenTelemetry provider used by the Next.js Node runtime.
14
+ * Import this entry point dynamically behind `NEXT_RUNTIME === "nodejs"`.
15
+ */
16
+ declare function registerNextTelemetry(config: RegisterNextTelemetryConfig): NodeTelemetryClient;
17
+ //#endregion
18
+ export { type NextRequestErrorHandler, type NextRequestErrorHandlerConfig, RegisterNextTelemetryConfig, createNextRequestErrorHandler, registerNextTelemetry };
@@ -0,0 +1,18 @@
1
+ import { i as NextRequestErrorHandlerConfig, o as createNextRequestErrorHandler, r as NextRequestErrorHandler } from "./request-error-CANVaAVM.mjs";
2
+ import { Configuration } from "@vercel/otel";
3
+ import { NodeTelemetryClient, NodeTelemetryConfig } from "@davidilie/telemetry-node";
4
+ import { Sampler } from "@opentelemetry/sdk-trace-base";
5
+ //#region src/node.d.ts
6
+ interface RegisterNextTelemetryConfig extends NodeTelemetryConfig {
7
+ otel?: Omit<Configuration, "attributes" | "serviceName" | "traceSampler"> & {
8
+ /** A concrete sampler so dynamic consent can wrap it safely. */
9
+ traceSampler?: Sampler;
10
+ };
11
+ }
12
+ /**
13
+ * Register the one OpenTelemetry provider used by the Next.js Node runtime.
14
+ * Import this entry point dynamically behind `NEXT_RUNTIME === "nodejs"`.
15
+ */
16
+ declare function registerNextTelemetry(config: RegisterNextTelemetryConfig): NodeTelemetryClient;
17
+ //#endregion
18
+ export { type NextRequestErrorHandler, type NextRequestErrorHandlerConfig, RegisterNextTelemetryConfig, createNextRequestErrorHandler, registerNextTelemetry };
package/dist/node.mjs ADDED
@@ -0,0 +1,46 @@
1
+ import { t as createNextRequestErrorHandler } from "./request-error-6cvJ4jpq.mjs";
2
+ import { registerOTel } from "@vercel/otel";
3
+ import { sanitizeResource } from "@davidilie/telemetry-core";
4
+ import { DynamicTelemetrySampler, NodeTelemetryClient, telemetryResourceAttributes } from "@davidilie/telemetry-node";
5
+ import { ParentBasedSampler, TraceIdRatioBasedSampler } from "@opentelemetry/sdk-trace-base";
6
+ //#region src/node.ts
7
+ const REGISTRATION = Symbol.for("@davidilie/telemetry-next/registration");
8
+ function traceSampler(config) {
9
+ const configuredRate = Number.isFinite(config.sampleRate) ? config.sampleRate ?? 1 : 1;
10
+ return new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(Math.min(1, Math.max(0, configuredRate))) });
11
+ }
12
+ /**
13
+ * Register the one OpenTelemetry provider used by the Next.js Node runtime.
14
+ * Import this entry point dynamically behind `NEXT_RUNTIME === "nodejs"`.
15
+ */
16
+ function registerNextTelemetry(config) {
17
+ if (process.env.NEXT_RUNTIME !== void 0 && process.env.NEXT_RUNTIME !== "nodejs") throw new Error("@davidilie/telemetry-next/node can only register in the Next.js Node runtime");
18
+ const sharedGlobal = globalThis;
19
+ const existing = sharedGlobal[REGISTRATION];
20
+ if (existing) return existing;
21
+ const resource = sanitizeResource(config.resource);
22
+ const sampler = new DynamicTelemetrySampler(config.otel?.traceSampler ?? traceSampler(config), {
23
+ enabled: config.enabled ?? true,
24
+ consent: config.consent ?? "granted"
25
+ });
26
+ registerOTel({
27
+ ...config.otel,
28
+ traceSampler: sampler,
29
+ serviceName: resource.serviceName,
30
+ attributes: telemetryResourceAttributes(resource)
31
+ });
32
+ const client = new NodeTelemetryClient({
33
+ ...config,
34
+ resource,
35
+ providerManagedSampling: true,
36
+ onCollectionStateChange: (state) => {
37
+ sampler.setEnabled(state.enabled);
38
+ sampler.setConsent(state.consent);
39
+ },
40
+ measurementMode: config.measurementMode ?? (config.otel?.metricReaders?.length ? "metrics" : "spans")
41
+ });
42
+ sharedGlobal[REGISTRATION] = client;
43
+ return client;
44
+ }
45
+ //#endregion
46
+ export { createNextRequestErrorHandler, registerNextTelemetry };
@@ -0,0 +1,44 @@
1
+ //#region src/request-error.ts
2
+ async function reportFailure(config, error, stage) {
3
+ try {
4
+ await config.onError?.(error, stage);
5
+ } catch {}
6
+ }
7
+ function errorDigest(error) {
8
+ if (typeof error === "object" && error !== null && "digest" in error && typeof error.digest === "string") return error.digest;
9
+ }
10
+ function createNextRequestErrorHandler(config) {
11
+ return async (error, request, context) => {
12
+ if (config.beforeCapture) try {
13
+ if (!await config.beforeCapture(error, request, context)) return;
14
+ } catch (hookError) {
15
+ await reportFailure(config, hookError, "beforeCapture");
16
+ return;
17
+ }
18
+ const digest = errorDigest(error);
19
+ try {
20
+ config.telemetry.captureException(error, {
21
+ ...config.attributes,
22
+ "http.request.method": request.method,
23
+ "url.path": request.path,
24
+ "next.router.kind": context.routerKind,
25
+ "next.route.path": context.routePath,
26
+ "next.route.type": context.routeType,
27
+ ...context.renderSource ? { "next.render.source": context.renderSource } : {},
28
+ ...context.revalidateReason ? { "next.revalidate.reason": context.revalidateReason } : {},
29
+ ...context.renderType ? { "next.render.type": context.renderType } : {},
30
+ ...digest ? { "next.error.digest": digest } : {}
31
+ });
32
+ } catch (captureError) {
33
+ await reportFailure(config, captureError, "capture");
34
+ return;
35
+ }
36
+ try {
37
+ await config.telemetry.flush?.();
38
+ } catch (flushError) {
39
+ await reportFailure(config, flushError, "flush");
40
+ }
41
+ };
42
+ }
43
+ //#endregion
44
+ export { createNextRequestErrorHandler as t };
@@ -0,0 +1,30 @@
1
+ import { Attributes } from "@davidilie/telemetry-core";
2
+ //#region src/request-error.d.ts
3
+ interface NextRequestErrorDetails {
4
+ path: string;
5
+ method: string;
6
+ headers?: Readonly<Record<string, string | string[] | undefined>>;
7
+ }
8
+ interface NextRequestErrorContext {
9
+ routerKind: string;
10
+ routePath: string;
11
+ routeType: string;
12
+ renderSource?: string;
13
+ revalidateReason?: string;
14
+ renderType?: string;
15
+ }
16
+ type NextRequestErrorHandler = (error: unknown, request: NextRequestErrorDetails, context: NextRequestErrorContext) => void | Promise<void>;
17
+ interface NextRequestErrorReporter {
18
+ captureException(error: unknown, attributes?: Attributes): void;
19
+ flush?(): void | Promise<void>;
20
+ }
21
+ interface NextRequestErrorHandlerConfig {
22
+ telemetry: NextRequestErrorReporter;
23
+ attributes?: Attributes;
24
+ beforeCapture?: (error: unknown, request: NextRequestErrorDetails, context: NextRequestErrorContext) => boolean | Promise<boolean>;
25
+ /** Optional fail-open diagnostics for hook, capture, or flush failures. */
26
+ onError?: (error: unknown, stage: "beforeCapture" | "capture" | "flush") => void | Promise<void>;
27
+ }
28
+ declare function createNextRequestErrorHandler(config: NextRequestErrorHandlerConfig): NextRequestErrorHandler;
29
+ //#endregion
30
+ export { NextRequestErrorReporter as a, NextRequestErrorHandlerConfig as i, NextRequestErrorDetails as n, createNextRequestErrorHandler as o, NextRequestErrorHandler as r, NextRequestErrorContext as t };
@@ -0,0 +1,30 @@
1
+ import { Attributes } from "@davidilie/telemetry-core";
2
+ //#region src/request-error.d.ts
3
+ interface NextRequestErrorDetails {
4
+ path: string;
5
+ method: string;
6
+ headers?: Readonly<Record<string, string | string[] | undefined>>;
7
+ }
8
+ interface NextRequestErrorContext {
9
+ routerKind: string;
10
+ routePath: string;
11
+ routeType: string;
12
+ renderSource?: string;
13
+ revalidateReason?: string;
14
+ renderType?: string;
15
+ }
16
+ type NextRequestErrorHandler = (error: unknown, request: NextRequestErrorDetails, context: NextRequestErrorContext) => void | Promise<void>;
17
+ interface NextRequestErrorReporter {
18
+ captureException(error: unknown, attributes?: Attributes): void;
19
+ flush?(): void | Promise<void>;
20
+ }
21
+ interface NextRequestErrorHandlerConfig {
22
+ telemetry: NextRequestErrorReporter;
23
+ attributes?: Attributes;
24
+ beforeCapture?: (error: unknown, request: NextRequestErrorDetails, context: NextRequestErrorContext) => boolean | Promise<boolean>;
25
+ /** Optional fail-open diagnostics for hook, capture, or flush failures. */
26
+ onError?: (error: unknown, stage: "beforeCapture" | "capture" | "flush") => void | Promise<void>;
27
+ }
28
+ declare function createNextRequestErrorHandler(config: NextRequestErrorHandlerConfig): NextRequestErrorHandler;
29
+ //#endregion
30
+ export { NextRequestErrorReporter as a, NextRequestErrorHandlerConfig as i, NextRequestErrorDetails as n, createNextRequestErrorHandler as o, NextRequestErrorHandler as r, NextRequestErrorContext as t };
@@ -0,0 +1,49 @@
1
+ //#region src/request-error.ts
2
+ async function reportFailure(config, error, stage) {
3
+ try {
4
+ await config.onError?.(error, stage);
5
+ } catch {}
6
+ }
7
+ function errorDigest(error) {
8
+ if (typeof error === "object" && error !== null && "digest" in error && typeof error.digest === "string") return error.digest;
9
+ }
10
+ function createNextRequestErrorHandler(config) {
11
+ return async (error, request, context) => {
12
+ if (config.beforeCapture) try {
13
+ if (!await config.beforeCapture(error, request, context)) return;
14
+ } catch (hookError) {
15
+ await reportFailure(config, hookError, "beforeCapture");
16
+ return;
17
+ }
18
+ const digest = errorDigest(error);
19
+ try {
20
+ config.telemetry.captureException(error, {
21
+ ...config.attributes,
22
+ "http.request.method": request.method,
23
+ "url.path": request.path,
24
+ "next.router.kind": context.routerKind,
25
+ "next.route.path": context.routePath,
26
+ "next.route.type": context.routeType,
27
+ ...context.renderSource ? { "next.render.source": context.renderSource } : {},
28
+ ...context.revalidateReason ? { "next.revalidate.reason": context.revalidateReason } : {},
29
+ ...context.renderType ? { "next.render.type": context.renderType } : {},
30
+ ...digest ? { "next.error.digest": digest } : {}
31
+ });
32
+ } catch (captureError) {
33
+ await reportFailure(config, captureError, "capture");
34
+ return;
35
+ }
36
+ try {
37
+ await config.telemetry.flush?.();
38
+ } catch (flushError) {
39
+ await reportFailure(config, flushError, "flush");
40
+ }
41
+ };
42
+ }
43
+ //#endregion
44
+ Object.defineProperty(exports, "createNextRequestErrorHandler", {
45
+ enumerable: true,
46
+ get: function() {
47
+ return createNextRequestErrorHandler;
48
+ }
49
+ });
package/package.json ADDED
@@ -0,0 +1,93 @@
1
+ {
2
+ "name": "@davidilie/telemetry-next",
3
+ "version": "0.0.0-bootstrap.0",
4
+ "description": "Runtime-safe Next.js telemetry backed by @vercel/otel.",
5
+ "keywords": [
6
+ "analytics",
7
+ "nextjs",
8
+ "observability",
9
+ "opentelemetry",
10
+ "telemetry",
11
+ "vercel"
12
+ ],
13
+ "author": "David Ilie <david@davidilie.com> (https://davidilie.com)",
14
+ "license": "Apache-2.0",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/DavidIlie/davidapps-telemetry.git",
18
+ "directory": "packages/next"
19
+ },
20
+ "homepage": "https://github.com/DavidIlie/davidapps-telemetry#readme",
21
+ "bugs": {
22
+ "url": "https://github.com/DavidIlie/davidapps-telemetry/issues"
23
+ },
24
+ "engines": {
25
+ "node": ">=20.9.0"
26
+ },
27
+ "type": "module",
28
+ "sideEffects": false,
29
+ "files": [
30
+ "dist",
31
+ "README.md",
32
+ "LICENSE",
33
+ "THIRD_PARTY_NOTICES.md",
34
+ "UPSTREAM.yml"
35
+ ],
36
+ "main": "./dist/index.cjs",
37
+ "module": "./dist/index.mjs",
38
+ "types": "./dist/index.d.mts",
39
+ "exports": {
40
+ ".": {
41
+ "import": {
42
+ "types": "./dist/index.d.mts",
43
+ "default": "./dist/index.mjs"
44
+ },
45
+ "require": {
46
+ "types": "./dist/index.d.cts",
47
+ "default": "./dist/index.cjs"
48
+ }
49
+ },
50
+ "./node": {
51
+ "import": {
52
+ "types": "./dist/node.d.mts",
53
+ "default": "./dist/node.mjs"
54
+ },
55
+ "require": {
56
+ "types": "./dist/node.d.cts",
57
+ "default": "./dist/node.cjs"
58
+ }
59
+ }
60
+ },
61
+ "scripts": {
62
+ "build": "tsdown src/index.ts src/node.ts --format esm,cjs --dts --tsconfig tsconfig.build.json",
63
+ "check": "tsc -p tsconfig.json",
64
+ "test": "vitest run",
65
+ "lint": "tsc -p tsconfig.json",
66
+ "clean": "rm -rf dist coverage"
67
+ },
68
+ "dependencies": {
69
+ "@davidilie/telemetry-core": "0.0.0-bootstrap.0",
70
+ "@davidilie/telemetry-node": "0.0.0-bootstrap.0",
71
+ "@opentelemetry/sdk-trace-base": "2.10.0",
72
+ "@vercel/otel": "2.1.3"
73
+ },
74
+ "peerDependencies": {
75
+ "@opentelemetry/api": ">=1.9.0 <2.0.0",
76
+ "next": ">=16.0.0 <17.0.0"
77
+ },
78
+ "peerDependenciesMeta": {
79
+ "next": {
80
+ "optional": true
81
+ }
82
+ },
83
+ "devDependencies": {
84
+ "@opentelemetry/api": "1.9.0",
85
+ "@types/node": "25.0.10",
86
+ "next": "16.3.1"
87
+ },
88
+ "publishConfig": {
89
+ "access": "public",
90
+ "registry": "https://registry.npmjs.org/",
91
+ "provenance": true
92
+ }
93
+ }