@dash0/sdk-web 0.18.2 → 0.18.4

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.
@@ -1,11 +1,17 @@
1
1
  import { vars } from "../vars";
2
2
  import { noop, warn, fetch, debug } from "../utils";
3
+ // The bacon api enforces a size limit across all pending beacon requests per fetch group
4
+ // There also seems to be a limit of 15 pending requests at the same time
5
+ // See: https://fetch.spec.whatwg.org/#concept-http-network-or-cache-fetch subpoint 10
6
+ // See: https://github.com/getsentry/sentry-javascript/pull/7553
3
7
  const BEACON_BODY_SIZE_LIMIT = 60000;
8
+ let pendingBodySize = 0;
9
+ let pendingRequestCount = 0;
4
10
  export async function send(path, body) {
5
11
  debug("Transmitting telemetry to endpoints", body);
6
12
  const jsonString = JSON.stringify(body);
7
13
  let requestBody = jsonString;
8
- let byteLength = jsonString.length;
14
+ let byteLength = new Blob([jsonString]).size;
9
15
  let isCompressed = false;
10
16
  // Try to compress if supported
11
17
  if (typeof CompressionStream !== "undefined" && vars.enableTransportCompression) {
@@ -33,12 +39,14 @@ export async function send(path, body) {
33
39
  warn("Unable to send telemetry, fetch is not defined");
34
40
  return;
35
41
  }
42
+ pendingBodySize += byteLength;
43
+ pendingRequestCount++;
36
44
  const response = await fetch(url, {
37
45
  method: "POST",
38
46
  headers,
39
47
  body: requestBody,
40
48
  // The keepalive flag is related to the window.sendBeacon API. This in turn has size limitations.
41
- keepalive: byteLength <= BEACON_BODY_SIZE_LIMIT,
49
+ keepalive: pendingBodySize <= BEACON_BODY_SIZE_LIMIT && pendingRequestCount <= 15,
42
50
  });
43
51
  // read the body so the connection can be closed
44
52
  response.text().catch(noop);
@@ -49,6 +57,10 @@ export async function send(path, body) {
49
57
  catch (error) {
50
58
  warn(`Error sending telemetry to ${endpoint.url}${path}:`, error);
51
59
  }
60
+ finally {
61
+ pendingBodySize -= byteLength;
62
+ pendingRequestCount--;
63
+ }
52
64
  }));
53
65
  }
54
66
  async function compressWithGzip(data) {
@@ -0,0 +1,267 @@
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
2
+ import { send } from "./fetch";
3
+ import { vars } from "../vars";
4
+ import * as utils from "../utils";
5
+ describe("fetch transport keepalive handling", () => {
6
+ let fetchMock;
7
+ let consoleWarnSpy;
8
+ beforeEach(() => {
9
+ // Reset vars
10
+ vars.endpoints = [
11
+ {
12
+ url: "https://api.example.com/",
13
+ authToken: "test-token",
14
+ },
15
+ ];
16
+ vars.enableTransportCompression = false;
17
+ // Mock fetch with proper response
18
+ fetchMock = vi.fn().mockResolvedValue({
19
+ ok: true,
20
+ status: 200,
21
+ statusText: "OK",
22
+ text: vi.fn().mockResolvedValue(""),
23
+ });
24
+ vi.spyOn(utils, "fetch").mockImplementation(fetchMock);
25
+ // Spy on warn to verify error handling
26
+ consoleWarnSpy = vi.spyOn(utils, "warn").mockImplementation(() => { });
27
+ });
28
+ afterEach(() => {
29
+ vi.restoreAllMocks();
30
+ });
31
+ it("should set keepalive=true for small single request", async () => {
32
+ const smallBody = { data: "test" };
33
+ await send("/v1/traces", smallBody);
34
+ expect(fetchMock).toHaveBeenCalledOnce();
35
+ const fetchOptions = fetchMock.mock.calls[0][1];
36
+ expect(fetchOptions.keepalive).toBe(true);
37
+ });
38
+ it("should set keepalive=false when body size exceeds BEACON_BODY_SIZE_LIMIT", async () => {
39
+ // Create a large body that exceeds 60KB
40
+ const largeBody = { data: "x".repeat(65000) };
41
+ await send("/v1/traces", largeBody);
42
+ expect(fetchMock).toHaveBeenCalledOnce();
43
+ const fetchOptions = fetchMock.mock.calls[0][1];
44
+ expect(fetchOptions.keepalive).toBe(false);
45
+ });
46
+ it("should handle multiple parallel requests within limits", async () => {
47
+ const smallBody = { data: "test" };
48
+ // Send 3 requests in parallel
49
+ await Promise.all([send("/v1/traces", smallBody), send("/v1/traces", smallBody), send("/v1/traces", smallBody)]);
50
+ expect(fetchMock).toHaveBeenCalledTimes(3);
51
+ fetchMock.mock.calls.forEach((call) => {
52
+ expect(call[1].keepalive).toBe(true);
53
+ });
54
+ });
55
+ it("should set keepalive=false when pending request count exceeds 15", async () => {
56
+ // Create 16 endpoints to trigger the limit
57
+ vars.endpoints = Array.from({ length: 16 }, (_, i) => ({
58
+ url: `https://api${i}.example.com/`,
59
+ authToken: `token-${i}`,
60
+ }));
61
+ const smallBody = { data: "test" };
62
+ // Mock fetch to delay response to keep requests pending
63
+ let resolvers = [];
64
+ fetchMock.mockImplementation(() => new Promise((resolve) => {
65
+ resolvers.push(() => resolve({
66
+ ok: true,
67
+ status: 200,
68
+ statusText: "OK",
69
+ text: vi.fn().mockResolvedValue(""),
70
+ }));
71
+ }));
72
+ const sendPromise = send("/v1/traces", smallBody);
73
+ // Wait a bit for all requests to be initiated
74
+ await new Promise((resolve) => setTimeout(resolve, 10));
75
+ // Check that at least one request has keepalive=false
76
+ const keepaliveValues = fetchMock.mock.calls.map((call) => call[1].keepalive);
77
+ expect(keepaliveValues.some((v) => v === false)).toBe(true);
78
+ // Resolve all requests
79
+ resolvers.forEach((resolve) => resolve());
80
+ await sendPromise;
81
+ });
82
+ it("should correctly adjust pendingBodySize when request succeeds", async () => {
83
+ // Create bodies that are ~35KB each, so two together would exceed the 60KB limit
84
+ const mediumBody1 = { data: "x".repeat(35000) };
85
+ const mediumBody2 = { data: "y".repeat(35000) };
86
+ // First request: pendingBodySize starts at 0, so keepalive should be true
87
+ await send("/v1/traces", mediumBody1);
88
+ expect(fetchMock.mock.calls[0][1].keepalive).toBe(true);
89
+ // After first request completes, pendingBodySize should be back to 0
90
+ // Second request: pendingBodySize starts at 0 again, so keepalive should be true
91
+ await send("/v1/traces", mediumBody2);
92
+ expect(fetchMock.mock.calls[1][1].keepalive).toBe(true);
93
+ // This verifies that the pendingBodySize is properly decremented in the finally block
94
+ expect(fetchMock).toHaveBeenCalledTimes(2);
95
+ });
96
+ it("should correctly adjust pendingBodySize when request fails with network error", async () => {
97
+ // Create bodies that are ~35KB each, so two together would exceed the 60KB limit
98
+ const mediumBody = { data: "x".repeat(35000) };
99
+ // First request fails
100
+ fetchMock.mockRejectedValueOnce(new Error("Network error"));
101
+ // Second request succeeds
102
+ fetchMock.mockResolvedValueOnce({
103
+ ok: true,
104
+ status: 200,
105
+ statusText: "OK",
106
+ text: vi.fn().mockResolvedValue(""),
107
+ });
108
+ // First request: should have keepalive=true (pendingBodySize is 0)
109
+ await send("/v1/traces", mediumBody);
110
+ expect(fetchMock.mock.calls[0][1].keepalive).toBe(true);
111
+ // Even though first request failed, pendingBodySize should be decremented in finally block
112
+ // Second request: should also have keepalive=true (pendingBodySize is back to 0)
113
+ await send("/v1/traces", mediumBody);
114
+ expect(fetchMock.mock.calls[1][1].keepalive).toBe(true);
115
+ expect(fetchMock).toHaveBeenCalledTimes(2);
116
+ expect(consoleWarnSpy).toHaveBeenCalledWith(expect.stringContaining("Error sending telemetry"), expect.any(Error));
117
+ });
118
+ it("should correctly adjust pendingBodySize when response.text() fails", async () => {
119
+ // Create bodies that are ~35KB each, so two together would exceed the 60KB limit
120
+ const mediumBody = { data: "x".repeat(35000) };
121
+ // Mock response.text() to fail
122
+ fetchMock.mockResolvedValueOnce({
123
+ ok: true,
124
+ status: 200,
125
+ statusText: "OK",
126
+ text: vi.fn().mockRejectedValue(new Error("Failed to read body")),
127
+ });
128
+ // First request: should have keepalive=true (pendingBodySize is 0)
129
+ await send("/v1/traces", mediumBody);
130
+ expect(fetchMock.mock.calls[0][1].keepalive).toBe(true);
131
+ // Should still complete successfully and adjust pendingBodySize even though text() failed
132
+ expect(fetchMock).toHaveBeenCalledOnce();
133
+ // Next request should still work with keepalive=true (verifying pendingBodySize is 0)
134
+ fetchMock.mockResolvedValueOnce({
135
+ ok: true,
136
+ status: 200,
137
+ statusText: "OK",
138
+ text: vi.fn().mockResolvedValue(""),
139
+ });
140
+ await send("/v1/traces", mediumBody);
141
+ expect(fetchMock).toHaveBeenCalledTimes(2);
142
+ expect(fetchMock.mock.calls[1][1].keepalive).toBe(true);
143
+ });
144
+ it("should handle multiple parallel requests with failures", async () => {
145
+ vars.endpoints = [
146
+ { url: "https://api1.example.com/", authToken: "token1" },
147
+ { url: "https://api2.example.com/", authToken: "token2" },
148
+ { url: "https://api3.example.com/", authToken: "token3" },
149
+ ];
150
+ const body = { data: "test" };
151
+ // First endpoint fails, others succeed
152
+ fetchMock
153
+ .mockRejectedValueOnce(new Error("Network error"))
154
+ .mockResolvedValueOnce({
155
+ ok: true,
156
+ status: 200,
157
+ statusText: "OK",
158
+ text: vi.fn().mockResolvedValue(""),
159
+ })
160
+ .mockResolvedValueOnce({
161
+ ok: true,
162
+ status: 200,
163
+ statusText: "OK",
164
+ text: vi.fn().mockResolvedValue(""),
165
+ });
166
+ await send("/v1/traces", body);
167
+ expect(fetchMock).toHaveBeenCalledTimes(3);
168
+ expect(consoleWarnSpy).toHaveBeenCalledWith(expect.stringContaining("Error sending telemetry"), expect.any(Error));
169
+ // After all complete, counters should be reset
170
+ // Reset endpoints back to 1
171
+ vars.endpoints = [
172
+ {
173
+ url: "https://api.example.com/",
174
+ authToken: "test-token",
175
+ },
176
+ ];
177
+ fetchMock.mockResolvedValueOnce({
178
+ ok: true,
179
+ status: 200,
180
+ statusText: "OK",
181
+ text: vi.fn().mockResolvedValue(""),
182
+ });
183
+ await send("/v1/traces", body);
184
+ expect(fetchMock).toHaveBeenCalledTimes(4);
185
+ expect(fetchMock.mock.calls[3][1].keepalive).toBe(true);
186
+ });
187
+ it("should correctly handle mixed success and failure in parallel with size tracking", async () => {
188
+ vars.endpoints = [
189
+ { url: "https://api1.example.com/", authToken: "token1" },
190
+ { url: "https://api2.example.com/", authToken: "token2" },
191
+ ];
192
+ // Create a body that's about 30KB
193
+ const mediumBody = { data: "x".repeat(30000) };
194
+ // First endpoint fails, second succeeds
195
+ fetchMock.mockRejectedValueOnce(new Error("Network error")).mockResolvedValueOnce({
196
+ ok: true,
197
+ status: 200,
198
+ statusText: "OK",
199
+ text: vi.fn().mockResolvedValue(""),
200
+ });
201
+ await send("/v1/traces", mediumBody);
202
+ // Both requests should have been made
203
+ expect(fetchMock).toHaveBeenCalledTimes(2);
204
+ expect(consoleWarnSpy).toHaveBeenCalledWith(expect.stringContaining("Error sending telemetry"), expect.any(Error));
205
+ // After completion, pendingBodySize should be back to 0
206
+ // Reset to single endpoint for simpler test
207
+ vars.endpoints = [
208
+ {
209
+ url: "https://api.example.com/",
210
+ authToken: "test-token",
211
+ },
212
+ ];
213
+ fetchMock.mockResolvedValueOnce({
214
+ ok: true,
215
+ status: 200,
216
+ statusText: "OK",
217
+ text: vi.fn().mockResolvedValue(""),
218
+ });
219
+ await send("/v1/traces", { data: "test" });
220
+ expect(fetchMock.mock.calls[2][1].keepalive).toBe(true);
221
+ });
222
+ it("should handle requests with non-ok response status", async () => {
223
+ // Create bodies that are ~35KB each, so two together would exceed the 60KB limit
224
+ const mediumBody = { data: "x".repeat(35000) };
225
+ fetchMock.mockResolvedValueOnce({
226
+ ok: false,
227
+ status: 500,
228
+ statusText: "Internal Server Error",
229
+ text: vi.fn().mockResolvedValue(""),
230
+ });
231
+ // First request with error response
232
+ await send("/v1/traces", mediumBody);
233
+ expect(fetchMock).toHaveBeenCalledOnce();
234
+ expect(consoleWarnSpy).toHaveBeenCalledWith(expect.stringContaining("Failed to send telemetry"));
235
+ // Verify pendingBodySize was adjusted correctly by sending another request
236
+ fetchMock.mockResolvedValueOnce({
237
+ ok: true,
238
+ status: 200,
239
+ statusText: "OK",
240
+ text: vi.fn().mockResolvedValue(""),
241
+ });
242
+ // Second request should have keepalive=true (verifying pendingBodySize was decremented)
243
+ await send("/v1/traces", mediumBody);
244
+ expect(fetchMock.mock.calls[1][1].keepalive).toBe(true);
245
+ });
246
+ it("should handle the exact boundary of BEACON_BODY_SIZE_LIMIT", async () => {
247
+ // Create a body that's just under 60000 bytes
248
+ const nearBoundaryBody = { data: "x".repeat(59970) }; // Accounting for JSON overhead
249
+ await send("/v1/traces", nearBoundaryBody);
250
+ expect(fetchMock).toHaveBeenCalledOnce();
251
+ const fetchOptions = fetchMock.mock.calls[0][1];
252
+ // Should be true since we're under the limit
253
+ expect(fetchOptions.keepalive).toBe(true);
254
+ });
255
+ it("should handle exactly 15 parallel requests", async () => {
256
+ vars.endpoints = Array.from({ length: 15 }, (_, i) => ({
257
+ url: `https://api${i}.example.com/`,
258
+ authToken: `token-${i}`,
259
+ }));
260
+ const smallBody = { data: "test" };
261
+ await send("/v1/traces", smallBody);
262
+ expect(fetchMock).toHaveBeenCalledTimes(15);
263
+ fetchMock.mock.calls.forEach((call) => {
264
+ expect(call[1].keepalive).toBe(true);
265
+ });
266
+ });
267
+ });
@@ -4,10 +4,19 @@ export function now() {
4
4
  }
5
5
  export function nowNanos() {
6
6
  const timeOrigin = getTimeOrigin();
7
+ const currentDate = new Date();
7
8
  if (timeOrigin) {
8
- return String((perf.now() + timeOrigin) * 1000000);
9
+ const perfTime = perf.now() + timeOrigin;
10
+ const dateTime = currentDate.getTime();
11
+ // Only return perf time measurement if it hasn't significantly drifted (60s).
12
+ // Some browsers violate the performance api spec and do not tick the monotonic time while the OS sleeps or the browser hangs
13
+ // See https://bugzil.la/1709767
14
+ // See https://webkit.org/b/225610
15
+ if (Math.abs(perfTime - dateTime) < 60000) {
16
+ return String(perfTime * 1000000);
17
+ }
9
18
  }
10
- return toNanosTs(new Date());
19
+ return toNanosTs(currentDate);
11
20
  }
12
21
  export function toNanosTs(time) {
13
22
  if (typeof time === "object") {
@@ -0,0 +1,232 @@
1
+ import { expect, describe, it, vi, beforeEach, afterEach } from "vitest";
2
+ import { now, nowNanos, toNanosTs, getTimeOrigin, domHRTimestampToNanos } from "./time";
3
+ import * as globals from "./globals";
4
+ describe("now", () => {
5
+ it("returns the current time in milliseconds", () => {
6
+ const before = new Date().getTime();
7
+ const result = now();
8
+ const after = new Date().getTime();
9
+ expect(result).toBeGreaterThanOrEqual(before);
10
+ expect(result).toBeLessThanOrEqual(after);
11
+ });
12
+ });
13
+ describe("toNanosTs", () => {
14
+ it("converts milliseconds to nanoseconds as string", () => {
15
+ const ms = 1609459200000; // 2021-01-01 00:00:00 UTC
16
+ const result = toNanosTs(ms);
17
+ expect(result).toBe("1609459200000000000");
18
+ });
19
+ it("converts Date object to nanoseconds as string", () => {
20
+ const date = new Date(1609459200000);
21
+ const result = toNanosTs(date);
22
+ expect(result).toBe("1609459200000000000");
23
+ });
24
+ it("handles zero timestamp", () => {
25
+ const result = toNanosTs(0);
26
+ expect(result).toBe("0000000");
27
+ });
28
+ it("preserves precision", () => {
29
+ const ms = 1234567890123;
30
+ const result = toNanosTs(ms);
31
+ expect(result).toBe("1234567890123000000");
32
+ });
33
+ });
34
+ describe("getTimeOrigin", () => {
35
+ afterEach(() => {
36
+ vi.restoreAllMocks();
37
+ });
38
+ it("returns timeOrigin when available", () => {
39
+ const mockPerf = {
40
+ timeOrigin: 1609459200000,
41
+ now: vi.fn(),
42
+ };
43
+ vi.spyOn(globals, "perf", "get").mockReturnValue(mockPerf);
44
+ const result = getTimeOrigin();
45
+ expect(result).toBe(1609459200000);
46
+ });
47
+ it("falls back to timing.fetchStart when timeOrigin is not a number", () => {
48
+ const mockPerf = {
49
+ timing: {
50
+ fetchStart: 1609459200000,
51
+ },
52
+ now: vi.fn(),
53
+ };
54
+ vi.spyOn(globals, "perf", "get").mockReturnValue(mockPerf);
55
+ const result = getTimeOrigin();
56
+ expect(result).toBe(1609459200000);
57
+ });
58
+ it("returns undefined when perf is not available", () => {
59
+ vi.spyOn(globals, "perf", "get").mockReturnValue(undefined);
60
+ const result = getTimeOrigin();
61
+ expect(result).toBeUndefined();
62
+ });
63
+ it("returns undefined when both timeOrigin and fetchStart are unavailable", () => {
64
+ const mockPerf = {
65
+ now: vi.fn(),
66
+ };
67
+ vi.spyOn(globals, "perf", "get").mockReturnValue(mockPerf);
68
+ const result = getTimeOrigin();
69
+ expect(result).toBeUndefined();
70
+ });
71
+ });
72
+ describe("nowNanos", () => {
73
+ let dateNowSpy;
74
+ beforeEach(() => {
75
+ dateNowSpy = vi.spyOn(Date.prototype, "getTime");
76
+ });
77
+ afterEach(() => {
78
+ vi.restoreAllMocks();
79
+ });
80
+ it("uses performance time when available and not drifted", () => {
81
+ const timeOrigin = 1609459200000;
82
+ const perfNow = 5000; // 5 seconds after time origin
83
+ const expectedTime = timeOrigin + perfNow; // 1609459205000
84
+ const mockPerf = {
85
+ timeOrigin,
86
+ now: vi.fn().mockReturnValue(perfNow),
87
+ };
88
+ vi.spyOn(globals, "perf", "get").mockReturnValue(mockPerf);
89
+ dateNowSpy.mockReturnValue(expectedTime);
90
+ const result = nowNanos();
91
+ const expected = String(expectedTime * 1000000);
92
+ expect(result).toBe(expected);
93
+ });
94
+ it("falls back to Date when drift is exactly 60000ms (60 seconds)", () => {
95
+ const timeOrigin = 1609459200000;
96
+ const perfNow = 5000;
97
+ const perfTime = timeOrigin + perfNow; // 1609459205000
98
+ const dateTime = perfTime + 60000; // 60000ms drift
99
+ const mockPerf = {
100
+ timeOrigin,
101
+ now: vi.fn().mockReturnValue(perfNow),
102
+ };
103
+ vi.spyOn(globals, "perf", "get").mockReturnValue(mockPerf);
104
+ dateNowSpy.mockReturnValue(dateTime);
105
+ const result = nowNanos();
106
+ const expected = String(dateTime) + "000000";
107
+ expect(result).toBe(expected);
108
+ });
109
+ it("falls back to Date when drift exceeds 60000ms (positive)", () => {
110
+ const timeOrigin = 1609459200000;
111
+ const perfNow = 5000;
112
+ const perfTime = timeOrigin + perfNow;
113
+ const dateTime = perfTime + 65000; // 65000ms drift (browser slept)
114
+ const mockPerf = {
115
+ timeOrigin,
116
+ now: vi.fn().mockReturnValue(perfNow),
117
+ };
118
+ vi.spyOn(globals, "perf", "get").mockReturnValue(mockPerf);
119
+ dateNowSpy.mockReturnValue(dateTime);
120
+ const result = nowNanos();
121
+ const expected = String(dateTime) + "000000";
122
+ expect(result).toBe(expected);
123
+ });
124
+ it("falls back to Date when drift exceeds 60000ms (negative)", () => {
125
+ const timeOrigin = 1609459200000;
126
+ const perfNow = 5000;
127
+ const perfTime = timeOrigin + perfNow;
128
+ const dateTime = perfTime - 65000; // -65000ms drift (clock adjustment)
129
+ const mockPerf = {
130
+ timeOrigin,
131
+ now: vi.fn().mockReturnValue(perfNow),
132
+ };
133
+ vi.spyOn(globals, "perf", "get").mockReturnValue(mockPerf);
134
+ dateNowSpy.mockReturnValue(dateTime);
135
+ const result = nowNanos();
136
+ const expected = String(dateTime) + "000000";
137
+ expect(result).toBe(expected);
138
+ });
139
+ it("uses performance time when drift is just under 60000ms (59999ms)", () => {
140
+ const timeOrigin = 1609459200000;
141
+ const perfNow = 5000;
142
+ const perfTime = timeOrigin + perfNow;
143
+ const dateTime = perfTime + 59999; // 59999ms drift (still acceptable)
144
+ const mockPerf = {
145
+ timeOrigin,
146
+ now: vi.fn().mockReturnValue(perfNow),
147
+ };
148
+ vi.spyOn(globals, "perf", "get").mockReturnValue(mockPerf);
149
+ dateNowSpy.mockReturnValue(dateTime);
150
+ const result = nowNanos();
151
+ const expected = String(perfTime * 1000000);
152
+ expect(result).toBe(expected);
153
+ });
154
+ it("uses performance time when drift is just under -60000ms (-59999ms)", () => {
155
+ const timeOrigin = 1609459200000;
156
+ const perfNow = 5000;
157
+ const perfTime = timeOrigin + perfNow;
158
+ const dateTime = perfTime - 59999; // -59999ms drift (still acceptable)
159
+ const mockPerf = {
160
+ timeOrigin,
161
+ now: vi.fn().mockReturnValue(perfNow),
162
+ };
163
+ vi.spyOn(globals, "perf", "get").mockReturnValue(mockPerf);
164
+ dateNowSpy.mockReturnValue(dateTime);
165
+ const result = nowNanos();
166
+ const expected = String(perfTime * 1000000);
167
+ expect(result).toBe(expected);
168
+ });
169
+ it("falls back to Date when timeOrigin is not available", () => {
170
+ vi.spyOn(globals, "perf", "get").mockReturnValue(undefined);
171
+ const dateTime = 1609459205000;
172
+ dateNowSpy.mockReturnValue(dateTime);
173
+ const result = nowNanos();
174
+ const expected = String(dateTime) + "000000";
175
+ expect(result).toBe(expected);
176
+ });
177
+ it("falls back to Date when timeOrigin is not a number", () => {
178
+ const mockPerf = {
179
+ timeOrigin: undefined,
180
+ now: vi.fn().mockReturnValue(5000),
181
+ timing: {}, // no fetchStart either
182
+ };
183
+ vi.spyOn(globals, "perf", "get").mockReturnValue(mockPerf);
184
+ const dateTime = 1609459205000;
185
+ dateNowSpy.mockReturnValue(dateTime);
186
+ const result = nowNanos();
187
+ const expected = String(dateTime) + "000000";
188
+ expect(result).toBe(expected);
189
+ });
190
+ });
191
+ describe("domHRTimestampToNanos", () => {
192
+ afterEach(() => {
193
+ vi.restoreAllMocks();
194
+ });
195
+ it("converts DOM high resolution timestamp to nanoseconds", () => {
196
+ const timeOrigin = 1609459200000;
197
+ const hrTimestamp = 5000.123; // 5.000123 seconds after time origin
198
+ const mockPerf = {
199
+ timeOrigin,
200
+ now: vi.fn(),
201
+ };
202
+ vi.spyOn(globals, "perf", "get").mockReturnValue(mockPerf);
203
+ const result = domHRTimestampToNanos(hrTimestamp);
204
+ const expectedMs = timeOrigin + hrTimestamp;
205
+ const expectedNanos = String(Math.round(expectedMs * 1000000));
206
+ expect(result).toBe(expectedNanos);
207
+ });
208
+ it("rounds to nearest nanosecond", () => {
209
+ const timeOrigin = 1000;
210
+ const hrTimestamp = 0.0000001; // Very small fraction
211
+ const mockPerf = {
212
+ timeOrigin,
213
+ now: vi.fn(),
214
+ };
215
+ vi.spyOn(globals, "perf", "get").mockReturnValue(mockPerf);
216
+ const result = domHRTimestampToNanos(hrTimestamp);
217
+ const expectedMs = timeOrigin + hrTimestamp;
218
+ const expectedNanos = String(Math.round(expectedMs * 1000000));
219
+ expect(result).toBe(expectedNanos);
220
+ });
221
+ it("handles zero timestamp", () => {
222
+ const timeOrigin = 1609459200000;
223
+ const mockPerf = {
224
+ timeOrigin,
225
+ now: vi.fn(),
226
+ };
227
+ vi.spyOn(globals, "perf", "get").mockReturnValue(mockPerf);
228
+ const result = domHRTimestampToNanos(0);
229
+ const expectedNanos = String(Math.round(timeOrigin * 1000000));
230
+ expect(result).toBe(expectedNanos);
231
+ });
232
+ });