@mark1russell7/otel-ts 0.0.0-bootstrap.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/README.md +417 -2
  2. package/dist/.tsbuildinfo +1 -0
  3. package/dist/before-flush.d.ts +21 -0
  4. package/dist/before-flush.d.ts.map +1 -0
  5. package/dist/before-flush.js +46 -0
  6. package/dist/before-flush.js.map +1 -0
  7. package/dist/common.d.ts +11 -0
  8. package/dist/common.d.ts.map +1 -0
  9. package/dist/common.js +22 -0
  10. package/dist/common.js.map +1 -0
  11. package/dist/constants.d.ts +12 -0
  12. package/dist/constants.d.ts.map +1 -0
  13. package/dist/constants.js +12 -0
  14. package/dist/constants.js.map +1 -0
  15. package/dist/context-manager.d.ts +36 -0
  16. package/dist/context-manager.d.ts.map +1 -0
  17. package/dist/context-manager.js +60 -0
  18. package/dist/context-manager.js.map +1 -0
  19. package/dist/core.d.ts +14 -0
  20. package/dist/core.d.ts.map +1 -0
  21. package/dist/core.js +26 -0
  22. package/dist/core.js.map +1 -0
  23. package/dist/env.d.ts +6 -0
  24. package/dist/env.d.ts.map +1 -0
  25. package/dist/env.js +8 -0
  26. package/dist/env.js.map +1 -0
  27. package/dist/faro.d.ts +8 -0
  28. package/dist/faro.d.ts.map +1 -0
  29. package/dist/faro.js +24 -0
  30. package/dist/faro.js.map +1 -0
  31. package/dist/id.d.ts +22 -0
  32. package/dist/id.d.ts.map +1 -0
  33. package/dist/id.js +54 -0
  34. package/dist/id.js.map +1 -0
  35. package/dist/index.d.ts +14 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +33 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/init.d.ts +8 -0
  40. package/dist/init.d.ts.map +1 -0
  41. package/dist/init.js +135 -0
  42. package/dist/init.js.map +1 -0
  43. package/dist/lifecycle.d.ts +33 -0
  44. package/dist/lifecycle.d.ts.map +1 -0
  45. package/dist/lifecycle.js +39 -0
  46. package/dist/lifecycle.js.map +1 -0
  47. package/dist/logs.d.ts +6 -0
  48. package/dist/logs.d.ts.map +1 -0
  49. package/dist/logs.js +17 -0
  50. package/dist/logs.js.map +1 -0
  51. package/dist/metrics.d.ts +5 -0
  52. package/dist/metrics.d.ts.map +1 -0
  53. package/dist/metrics.js +37 -0
  54. package/dist/metrics.js.map +1 -0
  55. package/dist/node-testing.d.ts +23 -0
  56. package/dist/node-testing.d.ts.map +1 -0
  57. package/dist/node-testing.js +71 -0
  58. package/dist/node-testing.js.map +1 -0
  59. package/dist/node.d.ts +37 -0
  60. package/dist/node.d.ts.map +1 -0
  61. package/dist/node.js +54 -0
  62. package/dist/node.js.map +1 -0
  63. package/dist/resource.d.ts +38 -0
  64. package/dist/resource.d.ts.map +1 -0
  65. package/dist/resource.js +54 -0
  66. package/dist/resource.js.map +1 -0
  67. package/dist/session-processors.d.ts +9 -0
  68. package/dist/session-processors.d.ts.map +1 -0
  69. package/dist/session-processors.js +37 -0
  70. package/dist/session-processors.js.map +1 -0
  71. package/dist/session.d.ts +21 -0
  72. package/dist/session.d.ts.map +1 -0
  73. package/dist/session.js +76 -0
  74. package/dist/session.js.map +1 -0
  75. package/dist/trace-echo.d.ts +60 -0
  76. package/dist/trace-echo.d.ts.map +1 -0
  77. package/dist/trace-echo.js +118 -0
  78. package/dist/trace-echo.js.map +1 -0
  79. package/dist/tracing.d.ts +7 -0
  80. package/dist/tracing.d.ts.map +1 -0
  81. package/dist/tracing.js +48 -0
  82. package/dist/tracing.js.map +1 -0
  83. package/dist/types.d.ts +210 -0
  84. package/dist/types.d.ts.map +1 -0
  85. package/dist/types.js +2 -0
  86. package/dist/types.js.map +1 -0
  87. package/dist/zone.d.ts +14 -0
  88. package/dist/zone.d.ts.map +1 -0
  89. package/dist/zone.js +40 -0
  90. package/dist/zone.js.map +1 -0
  91. package/package.json +84 -5
  92. package/src/before-flush.ts +64 -0
  93. package/src/common.ts +46 -0
  94. package/src/constants.ts +12 -0
  95. package/src/context-manager.ts +82 -0
  96. package/src/core.ts +38 -0
  97. package/src/env.ts +7 -0
  98. package/src/faro.ts +29 -0
  99. package/src/id.ts +59 -0
  100. package/src/index.ts +45 -0
  101. package/src/init.ts +177 -0
  102. package/src/lifecycle.ts +52 -0
  103. package/src/logs.ts +30 -0
  104. package/src/metrics.ts +63 -0
  105. package/src/node-testing.ts +88 -0
  106. package/src/node.ts +89 -0
  107. package/src/resource.ts +73 -0
  108. package/src/session-processors.ts +48 -0
  109. package/src/session.ts +86 -0
  110. package/src/trace-echo.ts +137 -0
  111. package/src/tracing.ts +64 -0
  112. package/src/types.ts +261 -0
  113. package/src/zone.ts +52 -0
package/README.md CHANGED
@@ -1,3 +1,418 @@
1
- # @mark1russell7/otel-ts
1
+ # otel-ts
2
2
 
3
- This version is a placeholder. The release workflow of https://github.com/mark1russell7/otel-ts publishes the real versions. Use a later version.
3
+ OpenTelemetry and Grafana Faro for TypeScript web apps, with one `init()` call.
4
+
5
+ ## Install
6
+
7
+ Install the package from GitHub:
8
+
9
+ ```bash
10
+ pnpm add github:mark1russell7/otel-ts
11
+ ```
12
+
13
+ The repository contains the compiled `dist/` folder. You do not need a build step.
14
+
15
+ ## Quick start
16
+
17
+ ```ts
18
+ import { init } from "@mark1russell7/otel-ts";
19
+
20
+ const otel = init({
21
+ serviceName: "checkout-web",
22
+ serviceVersion: "1.4.0",
23
+ endpoint: "https://otel.example.com",
24
+ });
25
+
26
+ const meter = otel.getMeter("checkout");
27
+ meter.createHistogram("checkout.duration", { unit: "ms" }).record(120);
28
+ ```
29
+
30
+ `init()` starts traces, metrics and logs. It sends them to `endpoint` with OTLP over HTTP. The paths are `/v1/traces`, `/v1/metrics` and `/v1/logs`.
31
+
32
+ `init()` also does these steps:
33
+
34
+ - It makes one resource for traces, metrics and logs.
35
+ - It sets a new `service.instance.id` for each `init()` call.
36
+ - It adds the `session.id` attribute to each log record and to each span.
37
+ - It exports metrics every 15 seconds.
38
+ - It flushes all telemetry each time the page becomes hidden.
39
+ - It stops all providers when the browser discards the page.
40
+ - It starts Grafana Faro only when you set `faroCollectorUrl`.
41
+ - It keeps the active span with async-browser-context. To use zone.js or no context library, import `init` from another entry. Refer to [Context manager](#context-manager).
42
+
43
+ `init()` also runs in Web Workers. There, it does not start the parts that need a DOM.
44
+
45
+ ## Options
46
+
47
+ | Option | Type | Default | Description |
48
+ | --- | --- | --- | --- |
49
+ | `endpoint` | `string` | `"http://localhost:4318"` | The OTLP HTTP endpoint. |
50
+ | `serviceName` | `string` | `"frontend-app"` | The `service.name` resource attribute. |
51
+ | `serviceVersion` | `string` | `"0.0.0"` | The `service.version` resource attribute. |
52
+ | `serviceInstanceId` | `string` | A new random UUID v4 for each `init()` call | The `service.instance.id` resource attribute. Refer to [Writer identity](#writer-identity). |
53
+ | `contextManager` | `"async" \| "stack" \| ContextManager` | `"async"` | The context manager of the tracer provider. The zone and core entries have other values. Refer to [Context manager](#context-manager). |
54
+ | `browserAttributes` | `boolean` | `true` | Puts `browser.brands`, `browser.platform`, `browser.mobile`, `browser.language` and `user_agent.original` (semantic conventions) on the resource, from `navigator`. The attributes of `resourceAttributes` replace them when the key is the same. |
55
+ | `resourceAttributes` | `Record<string, string>` | `{}` | More resource attributes. They replace the attributes above when the key is the same. |
56
+ | `tracing` | `boolean` | `true` | Starts the trace provider. |
57
+ | `propagateTraceHeaderCorsUrls` | `Array<string \| RegExp>` | All origins | The origins that get trace context headers. |
58
+ | `metrics` | `boolean` | `true` | Starts the meter provider. |
59
+ | `metricsExportIntervalMs` | `number` | `15000` | The time between two metric exports, in milliseconds. Refer to [Metric export](#metric-export). |
60
+ | `metricsTemporality` | `"cumulative" \| "delta"` | `"cumulative"` | The aggregation temporality that the OTLP metric exporter requests. |
61
+ | `histogramAggregation` | `"explicit" \| "exponential"` | `"explicit"` | The aggregation for histogram instruments. Refer to [Histograms](#histograms). |
62
+ | `logs` | `boolean` | `true` | Starts the logger provider. |
63
+ | `instrumentDocumentLoad` | `boolean` | `true` | Records document-load spans. This instrumentation needs a DOM. |
64
+ | `instrumentFetch` | `boolean` | `true` | Records a span for each `fetch()` request. |
65
+ | `instrumentXhr` | `boolean` | `true` | Records a span for each `XMLHttpRequest` request. |
66
+ | `instrumentUserInteraction` | `boolean` | `true` | Records user-interaction spans. This instrumentation needs a DOM. |
67
+ | `instrumentLongTask` | `boolean` | `true` | Records long-task spans. |
68
+ | `faro` | `boolean` | `true` | Starts Grafana Faro. Faro also needs `faroCollectorUrl` and a DOM. Refer to [Grafana Faro](#grafana-faro). |
69
+ | `faroCollectorUrl` | `string` | Not set | The Faro collector URL. Without this URL, Faro does not start. |
70
+ | `faroAppName` | `string` | The `serviceName` value | The Faro app name. |
71
+ | `sessionTracking` | `boolean` | `true` | Keeps the session ID in `sessionStorage`. Refer to [Sessions](#sessions). |
72
+ | `debug` | `boolean` | `false` | Writes the configuration to the console when `init()` runs. |
73
+
74
+ ## The returned object
75
+
76
+ | Member | Description |
77
+ | --- | --- |
78
+ | `forceFlush(): Promise<void>` | Exports all pending telemetry now. The providers continue to run. |
79
+ | `shutdown(): Promise<void>` | Exports all pending telemetry and stops all providers. A second call returns the same promise. |
80
+ | `onBeforeFlush(listener: (cause: FlushCause) => void): () => void` | Adds a function that runs before each flush. It gets the lifecycle transition that started the flush, if any. Refer to [Record values before a flush](#record-values-before-a-flush). |
81
+ | `getSessionId(): string` | Returns the current session ID. |
82
+ | `getMeter(name: string): Meter` | Returns a `Meter` for counters, histograms and gauges. |
83
+ | `getLogger(name: string): Logger` | Returns a `Logger` for log records. |
84
+
85
+ ## Context manager
86
+
87
+ The context manager keeps the active span. A span that starts while a span is active gets the active span as its parent. Set the manager with the `contextManager` option.
88
+
89
+ zone.js and async-browser-context patch the same functions with different rules. Thus, they cannot share a page. The package has three entries, and each entry loads one context library or none:
90
+
91
+ | Entry | Context library | `contextManager` values | Default |
92
+ | --- | --- | --- | --- |
93
+ | `@mark1russell7/otel-ts` | [async-browser-context](https://github.com/mark1russell7/AsyncBrowserContext) | `"async"`, `"stack"`, a `ContextManager` | `"async"` |
94
+ | `@mark1russell7/otel-ts/zone` | zone.js | `"zone"`, `"stack"`, a `ContextManager` | `"zone"` |
95
+ | `@mark1russell7/otel-ts/core` | None | `"stack"`, a `ContextManager` | `"stack"` |
96
+
97
+ Each entry exports the same API. Only `init()` and the types `OtelTsConfig` and `ContextManagerOption` are different. Import from one entry in an app.
98
+
99
+ If you give a name that the entry does not have, `init()` throws an error before it starts. The error tells you which entry has the name. For example, `"zone"` in `@mark1russell7/otel-ts` gives this error:
100
+
101
+ ```text
102
+ [otel-ts] contextManager: "zone" is not available in "@mark1russell7/otel-ts". This entry loads async-browser-context, and zone.js and async-browser-context cannot share a page: they patch the same functions with different rules. Import init from "@mark1russell7/otel-ts/zone" in place of "@mark1russell7/otel-ts".
103
+ ```
104
+
105
+ | Manager | Where the active span stays |
106
+ | --- | --- |
107
+ | `"async"` | In synchronous code and in the callbacks of the patched APIs. With the transform, also after `await`. |
108
+ | `"zone"` | In synchronous code and in the callbacks of the patched APIs. Not after a native `await`. |
109
+ | `"stack"` | Only in synchronous code. A timer callback, a `then` callback and an event listener get no active span. |
110
+ | A `ContextManager` | As your manager operates. |
111
+
112
+ ### The default: async-browser-context
113
+
114
+ `@mark1russell7/otel-ts` imports async-browser-context. When it loads, its runtime patches `Promise.prototype.then`, the timers, the event listeners, the observers and other callback APIs. Thus, a callback gets the active span of the code that registered it:
115
+
116
+ - A timer callback, for example of `setTimeout` or `requestAnimationFrame`.
117
+ - A `then`, `catch` or `finally` callback.
118
+ - An event listener. If the code that dispatches the event has no active span, the listener gets the span of the `addEventListener()` call. This is also true for a click of the user.
119
+
120
+ Import `@mark1russell7/otel-ts` before the other modules of the entry file. Code that keeps a reference to `setTimeout` or to another patched function before the runtime loads does not get the active span.
121
+
122
+ The runtime patches the page also when you set `"stack"` in this entry. For a page without patches, use `@mark1russell7/otel-ts/core`.
123
+
124
+ Profilers and the Long Animation Frames API of Chromium show the wrapper `asyncBrowserContextWrapper` of the runtime in place of the callback. With zone.js, they show the wrapper functions of zone.js.
125
+
126
+ On Node.js, the `node` export condition of async-browser-context selects the native `AsyncLocalStorage`. Nothing is patched, and the active span stays also after `await`. Server-side rendering and tests in Node.js get this entry. A bundler gives a Web Worker the browser runtime, which does not need a DOM.
127
+
128
+ ### Keep the span after `await`
129
+
130
+ A native `await` does not use code that a library can patch. Thus, without a transform, the code after an `await` gets no active span. The Vite plugin and the Babel preset of async-browser-context change each async function. Then the runtime sets the active span again after each `await`.
131
+
132
+ 1. Add async-browser-context to the dependencies of the app. The transformed code imports `async-browser-context/runtime`, and with pnpm, a module can import only the dependencies of its own package. Use the version range of otel-ts, so that the package manager installs one copy:
133
+
134
+ ```bash
135
+ pnpm add async-browser-context@^0.2.2
136
+ ```
137
+
138
+ 2. Add the Vite plugin to `vite.config.ts`:
139
+
140
+ ```ts
141
+ import { defineConfig } from "vite";
142
+ import { asyncContext } from "async-browser-context/vite";
143
+
144
+ export default defineConfig({
145
+ plugins: [asyncContext()],
146
+ });
147
+ ```
148
+
149
+ For other build tools, put the Babel preset `async-browser-context/babel-preset` last in the `presets` list. The [build tools guide](https://mark1russell7.github.io/AsyncBrowserContext/docs/guides/build-tools) gives the setup for webpack, Rollup, esbuild and Next.js.
150
+
151
+ The transform adds a small cost to each `await` step. The plugin has the options `include` and `exclude`. Use them to transform only the code that needs the active span after `await`. Code without the transform does not get the span of a different operation: after its own `await`, it gets no active span.
152
+
153
+ Firefox has a fast path for an `await` of a promise. A patch of `Promise.prototype.then` stops this fast path. Thus, with the runtime, each `await` of a promise takes approximately 0.8 µs more in Firefox, also in code without the transform. The patch of zone.js has the same cost. An `await` of a value that is not a promise does not change. If your app awaits many promises in hot code, measure it in Firefox.
154
+
155
+ Lag's experiment E8 compared the runtime without the transform with zone.js in Chromium, Firefox and WebKit. The runtime kept the active span in each case where zone.js kept it. It used less main-thread time, and it is smaller (5.7 KiB against 12.9 KiB with gzip). The [E8 results](https://mark1russell7.github.io/lag/research/local-experiments) give all the numbers.
156
+
157
+ ### Use zone.js
158
+
159
+ Import `init` from the zone entry:
160
+
161
+ ```ts
162
+ import { init } from "@mark1russell7/otel-ts/zone";
163
+
164
+ const otel = init();
165
+ ```
166
+
167
+ The zone entry loads zone.js through `@opentelemetry/context-zone`. zone.js patches `Promise`, the timers and the event listeners of the page when it loads. The zone entry does not import async-browser-context.
168
+
169
+ `@opentelemetry/context-zone` is a dependency of otel-ts, not a peer dependency. Thus, the zone entry needs no other install, and its version agrees with the OpenTelemetry SDK of otel-ts. The package uses only disk space: a bundle gets zone.js only through the zone entry.
170
+
171
+ ### Use no context library
172
+
173
+ Import `init` from the core entry:
174
+
175
+ ```ts
176
+ import { init } from "@mark1russell7/otel-ts/core";
177
+
178
+ const otel = init();
179
+ ```
180
+
181
+ The core entry imports no context library, and it patches nothing. Its default is `"stack"`: the `StackContextManager` of OpenTelemetry. You can also give your own `ContextManager`.
182
+
183
+ ## Writer identity
184
+
185
+ Prometheus and Mimir make the `instance` label from the `service.instance.id` resource attribute. Each SDK instance writes its own metric series. Two SDK instances with the same identity write to the same series. Then Mimir rejects samples, and `rate()` gives incorrect values.
186
+
187
+ For this reason, `init()` sets a new random UUID v4 for each call. The metrics, logs and traces resources get the same value. The library does not store the value. It does not make the value from the session ID. Each page load and each Web Worker gets a different value.
188
+
189
+ To set your own value, use the `serviceInstanceId` option. Give each `init()` call a different value. The library replaces an empty string with a random value.
190
+
191
+ To know the value before `init()` runs, call `createInstanceId()`:
192
+
193
+ ```ts
194
+ import { createInstanceId, init } from "@mark1russell7/otel-ts";
195
+
196
+ const serviceInstanceId = createInstanceId();
197
+ const otel = init({ serviceInstanceId });
198
+ ```
199
+
200
+ `createInstanceId()` returns a random UUID v4. It uses `crypto.randomUUID()` when that function exists. Browsers supply `crypto.randomUUID()` only in secure contexts: HTTPS pages and `http://localhost`. On other `http://` pages, `createInstanceId()` uses `crypto.getRandomValues()`. Without Web Crypto, it uses `Math.random()`. The session IDs use the same method.
201
+
202
+ ## Sessions
203
+
204
+ The library adds the `session.id` attribute to each log record and to each span. It reads the current session ID when the log record or the span starts. Thus, the next record shows a new session immediately.
205
+
206
+ The resources do not get `session.id`. A resource does not change, so it keeps an old session ID after the session changes. On the metrics resource, `session.id` also adds one `target_info` series for each session.
207
+
208
+ The library keeps the session ID and the time of the last activity in `sessionStorage`. A session ends after 30 minutes without activity. Activity is a log record, a span, a `getSessionId()` call or an `init()` call. The next activity then starts a new session with a new ID.
209
+
210
+ Some contexts have no usable `sessionStorage`. Examples are Web Workers, sandboxed iframes and a full storage quota. In these contexts, the library keeps the session in memory, with the same 30-minute limit.
211
+
212
+ If you set `session.id` on a log record or a span, the library keeps your value. Use this for a `session.end` event of the previous session.
213
+
214
+ When `sessionTracking` is `false`, each `init()` call gets one new random session ID. The library does not store this ID, and the ID does not change.
215
+
216
+ In Loki, find the attribute as the `session_id` structured metadata. In TraceQL, use `span.session.id` instead of `resource.session.id`.
217
+
218
+ ## Histograms
219
+
220
+ By default, histogram instruments use explicit-bucket histograms. All OTLP backends can store them. The bucket boundaries come from the `advice` of the instrument, or from the SDK defaults.
221
+
222
+ To use base-2 exponential histograms, set `histogramAggregation` to `"exponential"`:
223
+
224
+ ```ts
225
+ const otel = init({ histogramAggregation: "exponential" });
226
+ ```
227
+
228
+ This setting applies to all histogram instruments. The library then ignores `advice.explicitBucketBoundaries`. Counters and gauges do not change. The library sets the aggregation through the `aggregationPreference` option of the OTLP metric exporter.
229
+
230
+ Mimir stores each exponential histogram as one native-histogram series. An explicit-bucket histogram uses one series for each bucket, and one series each for `_sum` and `_count`.
231
+
232
+ Mimir must accept native histograms. Make sure that the limits of the tenant set `native_histograms_ingestion_enabled` to `true`:
233
+
234
+ ```yaml
235
+ limits:
236
+ native_histograms_ingestion_enabled: true
237
+ ```
238
+
239
+ Without this setting, you lose the histogram data. If your backend cannot store native histograms, keep the default `"explicit"`.
240
+
241
+ To query a native histogram, use the series name without the `_bucket` suffix:
242
+
243
+ ```promql
244
+ histogram_quantile(0.95, sum(rate(checkout_duration[5m])))
245
+ ```
246
+
247
+ The Mimir OTLP settings can add a unit suffix to the series name.
248
+
249
+ ## Metric export
250
+
251
+ The library exports metrics every 15 seconds. To change the interval, set `metricsExportIntervalMs`. The default was `60000` before this version.
252
+
253
+ The library also flushes all telemetry each time the page becomes hidden. Thus, you do not lose the data of the last interval of a page.
254
+
255
+ A shorter interval sends more samples. Each series then costs more in Mimir and in Grafana Cloud. Use an interval of 15 to 30 seconds.
256
+
257
+ By default, the exporter requests cumulative temporality. In its default configuration, Mimir rejects delta sums and delta histograms. Keep `metricsTemporality` at `"cumulative"` for Mimir and Prometheus.
258
+
259
+ ## Page lifecycle
260
+
261
+ The library follows the state of the page with [`page-lifecycle-tracker`](https://github.com/mark1russell7/page-lifecycle-tracker). It uses the tracker that the page shares (`getPageLifecycle()`), and it subscribes in the `export` phase:
262
+
263
+ - To `hidden`: The library flushes all telemetry. This transition occurs at each tab switch. The providers continue to run.
264
+ - To `frozen`: The browser freezes the page, or the page goes into the back/forward cache (`pagehide` with `persisted`). The library flushes all telemetry.
265
+ - To `terminated`: The browser discards the page (`pagehide` without `persisted`). The library stops all providers.
266
+
267
+ The tracker does not listen to `beforeunload` or `unload`. These events can prevent the back/forward cache.
268
+
269
+ ### Record values before a flush
270
+
271
+ Some monitors record their values at the end of the page. An example is the final Web Vitals of a page. The order of `pagehide` listeners is not the same in all browsers. Chromium calls `window` listeners in registration order. Thus, a library that stops in its own `pagehide` listener can stop before a monitor records its values.
272
+
273
+ This library flushes in the `export` phase of the shared lifecycle tracker. A monitor that subscribes to the same tracker in the `observe` phase records its values first, whatever the order of the scripts. `@lag/core` does this by default.
274
+
275
+ Values that a monitor keeps until a checkpoint can go out in each flush. Record them in an `onBeforeFlush()` listener:
276
+
277
+ ```ts
278
+ import { init } from "@mark1russell7/otel-ts";
279
+ import { createBrowserDeps, setupAllMonitors } from "@lag/core";
280
+
281
+ const otel = init({ serviceName: "checkout-web" });
282
+ const monitors = setupAllMonitors(createBrowserDeps(window, { /* options */ }));
283
+ otel.onBeforeFlush(() => monitors.flush());
284
+ ```
285
+
286
+ The listener gets the cause of the flush. For a page hide, `cause.transition` is the transition of the lifecycle state. For a call of `forceFlush()` or `shutdown()`, `cause.transition` is undefined.
287
+
288
+ The library calls each listener synchronously before each flush. These flushes include each page hide and the stop at `pagehide`. They also include each `forceFlush()` call and the first `shutdown()` call.
289
+
290
+ - The listeners run in registration order.
291
+ - An error in one listener does not stop the other listeners or the flush.
292
+ - The library writes only the first listener error to the console.
293
+ - The library does not wait for a promise that a listener returns.
294
+ - The listeners do not run after the providers stop.
295
+
296
+ `onBeforeFlush()` returns a function. Call this function to remove the listener.
297
+
298
+ ## Grafana Faro
299
+
300
+ Faro starts only if `faro` is `true`, you set `faroCollectorUrl`, and a DOM exists. Without a collector URL, Faro has no destination for its data. Faro then also writes an error to the console. For this reason, the library does not start Faro without `faroCollectorUrl`.
301
+
302
+ To use Faro, set the collector URL:
303
+
304
+ ```ts
305
+ const otel = init({ faroCollectorUrl: "https://faro.example.com/collect" });
306
+ ```
307
+
308
+ ## Web Workers
309
+
310
+ You can call `init()` in a Web Worker. The library does not use `window` or `document` there. It does not start Faro, document-load spans or user-interaction spans. It does not add page listeners. Call `forceFlush()` or `shutdown()` yourself before the worker stops.
311
+
312
+ The context managers also operate in a worker. In `@mark1russell7/otel-ts`, the runtime of async-browser-context patches the timers and the promises of the worker.
313
+
314
+ ## Node.js services
315
+
316
+ The entry `@mark1russell7/otel-ts/node` starts OpenTelemetry in a Node.js service. It is separate from the browser entries and imports no browser library.
317
+
318
+ Install the SDK and the instrumentations in the service. The SDK is a peer dependency, so the service keeps one version line of the OpenTelemetry packages:
319
+
320
+ ```bash
321
+ pnpm add @opentelemetry/sdk-node @opentelemetry/instrumentation @opentelemetry/instrumentation-http
322
+ ```
323
+
324
+ Put the start in its own module:
325
+
326
+ ```ts
327
+ // instrumentation.ts
328
+ import { startNodeTelemetry } from "@mark1russell7/otel-ts/node";
329
+ import { HttpInstrumentation } from "@opentelemetry/instrumentation-http";
330
+
331
+ export const telemetry = startNodeTelemetry({
332
+ serviceName: "my-service",
333
+ importMetaUrl: import.meta.url,
334
+ instrumentations: [new HttpInstrumentation()],
335
+ });
336
+ ```
337
+
338
+ Start the service with this module first:
339
+
340
+ ```bash
341
+ node --import ./dist/instrumentation.js dist/server.js
342
+ ```
343
+
344
+ The instrumentations patch a module when it loads, so this module must load before the modules of the service. In an ES module service, the CommonJS hook does not see a package that an ES module imports. When you give `importMetaUrl`, `startNodeTelemetry()` registers the loader hook of OpenTelemetry (`@opentelemetry/instrumentation/hook.mjs`) before the SDK starts. The hook then patches those imports too.
345
+
346
+ `startNodeTelemetry()` starts nothing when `OTEL_EXPORTER_OTLP_ENDPOINT` has no value. Set `enabled` to change this. By default, it stops the SDK and sends the last spans at `SIGTERM` and `SIGINT`.
347
+
348
+ ### The trace of a write, in its echo
349
+
350
+ A change stream or a queue reports a write after its request ends, without the trace of the request. `createTraceEcho()` keeps the trace of each write for some seconds, and the handler of the echo takes it:
351
+
352
+ ```ts
353
+ import { createTraceEcho, outgoingTraceparent } from "@mark1russell7/otel-ts/node";
354
+
355
+ const echoes = createTraceEcho();
356
+
357
+ // in the write handler
358
+ echoes.remember("orders", order.id, outgoingTraceparent(req.headers.traceparent));
359
+
360
+ // in the change-stream handler
361
+ const traceparent = echoes.take("orders", change.documentKey._id);
362
+ ```
363
+
364
+ `outgoingTraceparent()` gives the context of the active span when the SDK operates. Otherwise it gives the `traceparent` header of the request.
365
+
366
+ ### Apply a remote change in its trace
367
+
368
+ A client gets the change with the `traceparent` of the write. `runInRemoteTrace()` runs the apply in a consumer span whose parent is that trace. Thus one trace shows the click, the write, the server and each client that applies the change:
369
+
370
+ ```ts
371
+ import { runInRemoteTrace } from "@mark1russell7/otel-ts";
372
+
373
+ socket.onChange((msg) =>
374
+ runInRemoteTrace(msg.traceparent, () => store.apply(msg), {
375
+ name: "realtime.echo",
376
+ attributes: { "app.collection": msg.collection },
377
+ }),
378
+ );
379
+ ```
380
+
381
+ - Without a valid `traceparent`, it only runs the function.
382
+ - The span ends when the function returns, or when its promise settles. An error sets the status `ERROR` and passes through.
383
+ - Each entry exports it: the browser entries and `@mark1russell7/otel-ts/node`.
384
+
385
+ ### Make sure that the spans arrive
386
+
387
+ A change of the load order breaks the instrumentations without an error: the service operates, and some spans are not there. The entry `@mark1russell7/otel-ts/node/testing` has a stand-in collector for a CI check:
388
+
389
+ ```ts
390
+ import { startStubCollector } from "@mark1russell7/otel-ts/node/testing";
391
+
392
+ const collector = await startStubCollector();
393
+ // start the service with OTEL_EXPORTER_OTLP_ENDPOINT=collector.endpoint, then:
394
+ const missing = await collector.waitFor(
395
+ ["@opentelemetry/instrumentation-http", "@opentelemetry/instrumentation-express"],
396
+ { poke: () => fetch("http://127.0.0.1:8080/health") },
397
+ );
398
+ await collector.close();
399
+ if (missing.length > 0) throw new Error(`no spans from ${missing.join(", ")}`);
400
+ ```
401
+
402
+ The collector reads OTLP/HTTP JSON, the format of `@opentelemetry/exporter-trace-otlp-http`.
403
+
404
+ ## Development
405
+
406
+ ```bash
407
+ pnpm install
408
+ pnpm run build
409
+ pnpm run typecheck
410
+ pnpm test
411
+ ```
412
+
413
+ `pnpm test` starts two Vitest projects:
414
+
415
+ - `browser runtime`: The tests in happy-dom. The project gives async-browser-context the browser runtime, as a browser does.
416
+ - `node`: The tests in `test/node/`. Node.js gives async-browser-context the native `AsyncLocalStorage`.
417
+
418
+ Consumers install the package from GitHub. Thus, rebuild `dist/` after each change to `src/`. Then commit `dist/`.