@chrom-ar/collector 0.4.0 → 0.5.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/CHANGELOG.md +28 -0
- package/README.md +97 -26
- package/dist/{chunk-YN5N3X7X.js → chunk-42XODVHT.js} +8 -1
- package/dist/collector.esm.js +7 -0
- package/dist/index.cjs +128 -38
- package/dist/index.d.cts +11 -4
- package/dist/index.d.ts +11 -4
- package/dist/index.js +122 -39
- package/dist/rum.cjs +40 -10
- package/dist/rum.d.cts +10 -4
- package/dist/rum.d.ts +10 -4
- package/dist/rum.esm.js +2 -0
- package/dist/rum.js +34 -11
- package/dist/{types-CTnanJxh.d.cts → types-ml-o_-mr.d.cts} +9 -4
- package/dist/{types-CTnanJxh.d.ts → types-ml-o_-mr.d.ts} +9 -4
- package/package.json +9 -5
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { B as Breadcrumb, C as CaptureContext, L as Level, a as CollectorOptions, T as TestResult } from './types-
|
|
2
|
-
export { b as BreadcrumbKind, c as CollectorEvent, F as Frame, R as RequestTiming, d as RumContext, e as RumHandle, f as RumPlugin } from './types-
|
|
1
|
+
import { B as Breadcrumb, C as CaptureContext, L as Level, a as CollectorOptions, T as TestResult } from './types-ml-o_-mr.js';
|
|
2
|
+
export { b as BreadcrumbKind, c as CollectorEvent, F as Frame, R as RequestTiming, d as RumContext, e as RumHandle, f as RumPlugin } from './types-ml-o_-mr.js';
|
|
3
3
|
|
|
4
4
|
/** The version of this SDK, as sent in every event's `sdk.version`. */
|
|
5
5
|
declare const SDK_VERSION: string;
|
|
@@ -13,10 +13,14 @@ declare const SDK_VERSION: string;
|
|
|
13
13
|
* Collector.init({ dsn: "https://clt_…@app.clt.chrom.ar" });
|
|
14
14
|
* ```
|
|
15
15
|
*
|
|
16
|
+
* Without options, it reads them from the page's meta tags:
|
|
17
|
+
* `<meta name="collector-dsn">`, `collector-environment` and
|
|
18
|
+
* `collector-release`. Options you pass win over the tags.
|
|
19
|
+
*
|
|
16
20
|
* Without a `dsn`, nothing is captured or sent. Calling it again replaces the
|
|
17
21
|
* options. Safe to import during server-side rendering: it does nothing there.
|
|
18
22
|
*/
|
|
19
|
-
declare function init(options
|
|
23
|
+
declare function init(options?: CollectorOptions): void;
|
|
20
24
|
/**
|
|
21
25
|
* Sends one test error, to check your setup end to end. Resolves to
|
|
22
26
|
* `{ ok: true, id }` once Collector accepts it, or `{ ok: false, reason }`,
|
|
@@ -31,7 +35,10 @@ declare function test(): Promise<TestResult>;
|
|
|
31
35
|
declare function captureException(error: unknown, context?: CaptureContext): string | undefined;
|
|
32
36
|
/** Reports something that isn't an error: `captureMessage("Payment slow", "warning")`. */
|
|
33
37
|
declare function captureMessage(message: string, context?: CaptureContext | Level): string | undefined;
|
|
34
|
-
/**
|
|
38
|
+
/**
|
|
39
|
+
* Attaches your user's id to the following events. An id, not personal data. `null` clears it.
|
|
40
|
+
* From then on, the `collector-user` meta tag is ignored.
|
|
41
|
+
*/
|
|
35
42
|
declare function setUser(user: {
|
|
36
43
|
id: string | number;
|
|
37
44
|
} | null): void;
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { truncate, safeStringify, stripUrl, uuid4, rumUrl } from './chunk-
|
|
1
|
+
import { readMeta, truncate, safeStringify, stripUrl, uuid4, rumUrl } from './chunk-42XODVHT.js';
|
|
2
2
|
|
|
3
3
|
// src/dsn.ts
|
|
4
4
|
function parseDsn(dsn) {
|
|
@@ -14,6 +14,10 @@ function parseDsn(dsn) {
|
|
|
14
14
|
return { url: `${base}/api/events?key=${key}`, heartbeatUrl: `${base}/api/heartbeats?key=${key}`, pageviewsUrl: `${base}/api/pageviews?key=${key}`, base, key };
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
+
// src/self.ts
|
|
18
|
+
var file;
|
|
19
|
+
var sdkFile = () => file;
|
|
20
|
+
|
|
17
21
|
// src/stacktrace.ts
|
|
18
22
|
var MAX_FRAMES = 250;
|
|
19
23
|
var V8 = /^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?$/;
|
|
@@ -99,7 +103,7 @@ function toFrames(raw, opts) {
|
|
|
99
103
|
}
|
|
100
104
|
return frames;
|
|
101
105
|
}
|
|
102
|
-
function toFrame(raw, { origin, inAppUrls }) {
|
|
106
|
+
function toFrame(raw, { origin, inAppUrls, classify, sdkFile: sdkFile2 }) {
|
|
103
107
|
let url;
|
|
104
108
|
try {
|
|
105
109
|
url = new URL(raw.url, origin);
|
|
@@ -108,10 +112,16 @@ function toFrame(raw, { origin, inAppUrls }) {
|
|
|
108
112
|
}
|
|
109
113
|
const webpackInternal = raw.url.startsWith("webpack-internal://");
|
|
110
114
|
const sameOrigin = url?.origin === origin || webpackInternal;
|
|
111
|
-
let
|
|
112
|
-
if (url && !webpackInternal)
|
|
113
|
-
const inApp =
|
|
114
|
-
|
|
115
|
+
let file2 = stripUrl(raw.url);
|
|
116
|
+
if (url && !webpackInternal) file2 = sameOrigin ? url.pathname : stripUrl(url.href);
|
|
117
|
+
const inApp = isInApp();
|
|
118
|
+
function isInApp() {
|
|
119
|
+
if (inAppUrls) return inAppUrls.some((p) => typeof p === "string" ? raw.url.includes(p) : p.test(raw.url));
|
|
120
|
+
const verdict = url === void 0 ? void 0 : classify?.(url.href);
|
|
121
|
+
if (verdict !== void 0) return verdict === "app";
|
|
122
|
+
return sameOrigin && !isExtensionUrl(raw.url) && !VENDOR_PATTERNS.some((p) => p.test(file2));
|
|
123
|
+
}
|
|
124
|
+
const frame = { module: normalizeModule(file2), function: raw.function ?? "?", file: file2, in_app: inApp };
|
|
115
125
|
if (raw.line !== void 0) frame.line = raw.line;
|
|
116
126
|
if (raw.column !== void 0) frame.column = raw.column;
|
|
117
127
|
return frame;
|
|
@@ -140,7 +150,7 @@ function errorType(error) {
|
|
|
140
150
|
function eventFromException(error, env, ctx, mechanism = "manual") {
|
|
141
151
|
const event = baseEvent(env, ctx);
|
|
142
152
|
if (isErrorLike(error)) {
|
|
143
|
-
const frames = typeof error.stack === "string" ? toFrames(parseStack(error.stack), { origin: env.origin, inAppUrls: env.options.inAppUrls }) : [];
|
|
153
|
+
const frames = typeof error.stack === "string" ? toFrames(parseStack(error.stack), { origin: env.origin, inAppUrls: env.options.inAppUrls, classify: env.classify, sdkFile: sdkFile() }) : [];
|
|
144
154
|
event.exception = { type: errorType(error), message: truncate(String(error.message), MAX_MESSAGE) };
|
|
145
155
|
if (frames.length > 0) event.exception.frames = frames;
|
|
146
156
|
} else {
|
|
@@ -174,7 +184,7 @@ function baseEvent({ options, scope: scope2, href, userAgent, session }, ctx = {
|
|
|
174
184
|
platform: "javascript",
|
|
175
185
|
level: toLevel(ctx.level),
|
|
176
186
|
request: { url: options.stripQuery === false ? href : stripUrl(href), headers: { "user-agent": userAgent } },
|
|
177
|
-
sdk: { name: SDK_NAME, version: "0.
|
|
187
|
+
sdk: { name: SDK_NAME, version: "0.5.0" }
|
|
178
188
|
};
|
|
179
189
|
const environment = environmentOf(options);
|
|
180
190
|
if (environment !== void 0) event.environment = environment;
|
|
@@ -271,6 +281,45 @@ function errorFromLocation(e) {
|
|
|
271
281
|
return error;
|
|
272
282
|
}
|
|
273
283
|
|
|
284
|
+
// src/importmap.ts
|
|
285
|
+
var isBare = (specifier) => !/^(?:\.{0,2}\/|[a-z][a-z\d+.-]*:)/i.test(specifier);
|
|
286
|
+
function pinsOf(doc) {
|
|
287
|
+
const script = doc.querySelector('script[type="importmap"]');
|
|
288
|
+
const text = script?.textContent;
|
|
289
|
+
if (text === void 0 || text === "") return void 0;
|
|
290
|
+
let map;
|
|
291
|
+
try {
|
|
292
|
+
map = JSON.parse(text);
|
|
293
|
+
} catch {
|
|
294
|
+
return void 0;
|
|
295
|
+
}
|
|
296
|
+
const imports = typeof map === "object" && map !== null && "imports" in map ? map.imports : void 0;
|
|
297
|
+
if (typeof imports !== "object" || imports === null) return void 0;
|
|
298
|
+
const pins = [];
|
|
299
|
+
for (const [specifier, target] of Object.entries(imports)) {
|
|
300
|
+
if (typeof target !== "string" || !isBare(specifier)) continue;
|
|
301
|
+
try {
|
|
302
|
+
pins.push({ specifier, url: stripUrl(new URL(target, doc.baseURI).href), prefix: specifier.endsWith("/") });
|
|
303
|
+
} catch {
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
return pins.sort((a, b) => a.prefix === b.prefix ? b.url.length - a.url.length : Number(a.prefix) - Number(b.prefix));
|
|
307
|
+
}
|
|
308
|
+
var listed = (list, specifier) => list.some((entry) => entry === specifier || entry.endsWith("/") && specifier.startsWith(entry));
|
|
309
|
+
function importMapClassifier(doc, origin) {
|
|
310
|
+
const pins = pinsOf(doc);
|
|
311
|
+
if (!pins || pins.length === 0) return void 0;
|
|
312
|
+
const own = readMeta("collector-in-app")?.split(/[\s,]+/).filter((entry) => entry !== "");
|
|
313
|
+
return (url) => {
|
|
314
|
+
const clean = stripUrl(url);
|
|
315
|
+
const pin = pins.find((p) => p.prefix ? clean.startsWith(p.url) : clean === p.url);
|
|
316
|
+
if (!pin) return void 0;
|
|
317
|
+
const specifier = pin.prefix ? pin.specifier + clean.slice(pin.url.length) : pin.specifier;
|
|
318
|
+
if (own) return listed(own, specifier) ? "app" : "dependency";
|
|
319
|
+
return specifier.startsWith("@") || !pin.url.startsWith(`${origin}/`) ? "dependency" : void 0;
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
|
|
274
323
|
// src/heartbeat.ts
|
|
275
324
|
var HEARTBEAT_DELAY_MS = 5e3;
|
|
276
325
|
var STORAGE_PREFIX = "collector:heartbeat:";
|
|
@@ -304,7 +353,7 @@ async function beat({ url, key, fetch, options, logger }) {
|
|
|
304
353
|
if (storedMark(storageKey) === mark || sentThisPage.has(storageKey + mark)) return;
|
|
305
354
|
let status;
|
|
306
355
|
try {
|
|
307
|
-
const body = JSON.stringify({ v: 1, sdk: { name: SDK_NAME, version: "0.
|
|
356
|
+
const body = JSON.stringify({ v: 1, sdk: { name: SDK_NAME, version: "0.5.0" }, environment, release });
|
|
308
357
|
const response = await fetch(url, { method: "POST", body, headers: { "Content-Type": "text/plain;charset=UTF-8" }, keepalive: true, credentials: "omit" });
|
|
309
358
|
({ status } = response);
|
|
310
359
|
} catch (error) {
|
|
@@ -319,6 +368,33 @@ async function beat({ url, key, fetch, options, logger }) {
|
|
|
319
368
|
}
|
|
320
369
|
}
|
|
321
370
|
|
|
371
|
+
// src/describe.ts
|
|
372
|
+
var MAX_KEYS = 10;
|
|
373
|
+
var MAX_STRING = 100;
|
|
374
|
+
function describeValue(value, nested = false) {
|
|
375
|
+
if (typeof value === "string") return nested ? JSON.stringify(truncate(value, MAX_STRING)) : value;
|
|
376
|
+
if (value === null || typeof value !== "object") {
|
|
377
|
+
return typeof value === "function" ? `[Function ${value.name !== "" ? value.name : "anonymous"}]` : String(value);
|
|
378
|
+
}
|
|
379
|
+
const v = value;
|
|
380
|
+
if (value instanceof Error || typeof v.message === "string" && typeof v.name === "string") {
|
|
381
|
+
return `${String(v.name)}: ${String(v.message)}`;
|
|
382
|
+
}
|
|
383
|
+
if (typeof v.nodeType === "number") return typeof v.tagName === "string" ? `<${v.tagName.toLowerCase()}>` : "[Node]";
|
|
384
|
+
if (nested) return Array.isArray(value) ? `[Array(${String(value.length)})]` : "{\u2026}";
|
|
385
|
+
if (Array.isArray(value)) {
|
|
386
|
+
const items = value.slice(0, MAX_KEYS).map((x) => describeValue(x, true));
|
|
387
|
+
return `[${items.join(", ")}${value.length > MAX_KEYS ? ", \u2026" : ""}]`;
|
|
388
|
+
}
|
|
389
|
+
try {
|
|
390
|
+
const keys = Object.keys(value);
|
|
391
|
+
const shown = keys.slice(0, MAX_KEYS).map((k) => `${k}: ${describeValue(value[k], true)}`);
|
|
392
|
+
return `{${shown.join(", ")}${keys.length > MAX_KEYS ? ", \u2026" : ""}}`;
|
|
393
|
+
} catch {
|
|
394
|
+
return "{\u2026}";
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
322
398
|
// src/instrument/common.ts
|
|
323
399
|
var ORIGINAL = "__collector_original__";
|
|
324
400
|
function wrap(obj, name, make) {
|
|
@@ -376,31 +452,6 @@ function requestMessage(method, url, status) {
|
|
|
376
452
|
|
|
377
453
|
// src/instrument/console.ts
|
|
378
454
|
var LEVELS2 = { error: "error", warn: "warning", log: "info", info: "info" };
|
|
379
|
-
var MAX_KEYS = 10;
|
|
380
|
-
var MAX_STRING = 100;
|
|
381
|
-
function describeValue(value, nested = false) {
|
|
382
|
-
if (typeof value === "string") return nested ? JSON.stringify(truncate(value, MAX_STRING)) : value;
|
|
383
|
-
if (value === null || typeof value !== "object") {
|
|
384
|
-
return typeof value === "function" ? `[Function ${value.name !== "" ? value.name : "anonymous"}]` : String(value);
|
|
385
|
-
}
|
|
386
|
-
const v = value;
|
|
387
|
-
if (value instanceof Error || typeof v.message === "string" && typeof v.name === "string") {
|
|
388
|
-
return `${String(v.name)}: ${String(v.message)}`;
|
|
389
|
-
}
|
|
390
|
-
if (typeof v.nodeType === "number") return typeof v.tagName === "string" ? `<${v.tagName.toLowerCase()}>` : "[Node]";
|
|
391
|
-
if (nested) return Array.isArray(value) ? `[Array(${String(value.length)})]` : "{\u2026}";
|
|
392
|
-
if (Array.isArray(value)) {
|
|
393
|
-
const items = value.slice(0, MAX_KEYS).map((x) => describeValue(x, true));
|
|
394
|
-
return `[${items.join(", ")}${value.length > MAX_KEYS ? ", \u2026" : ""}]`;
|
|
395
|
-
}
|
|
396
|
-
try {
|
|
397
|
-
const keys = Object.keys(value);
|
|
398
|
-
const shown = keys.slice(0, MAX_KEYS).map((k) => `${k}: ${describeValue(value[k], true)}`);
|
|
399
|
-
return `{${shown.join(", ")}${keys.length > MAX_KEYS ? ", \u2026" : ""}}`;
|
|
400
|
-
} catch {
|
|
401
|
-
return "{\u2026}";
|
|
402
|
-
}
|
|
403
|
-
}
|
|
404
455
|
function instrumentConsole(win, record, _opts) {
|
|
405
456
|
const target = win.console;
|
|
406
457
|
const restores = Object.keys(LEVELS2).map(
|
|
@@ -936,7 +987,7 @@ var Client = class {
|
|
|
936
987
|
}
|
|
937
988
|
if (options.rum && !this.transport.disabled) {
|
|
938
989
|
try {
|
|
939
|
-
this.rum = options.rum.start({ win, url: endpoint.pageviewsUrl, fetch: fetchFn, logger: this.logger, options, sdk: { name: SDK_NAME, version: "0.
|
|
990
|
+
this.rum = options.rum.start({ win, url: endpoint.pageviewsUrl, fetch: fetchFn, logger: this.logger, options, sdk: { name: SDK_NAME, version: "0.5.0" }, environment: environmentOf(options), release: releaseOf(options) });
|
|
940
991
|
} catch (error) {
|
|
941
992
|
this.logger.debug("RUM didn't start", error);
|
|
942
993
|
}
|
|
@@ -1053,13 +1104,15 @@ var Client = class {
|
|
|
1053
1104
|
}
|
|
1054
1105
|
env() {
|
|
1055
1106
|
const { win } = this;
|
|
1107
|
+
this.classify ?? (this.classify = { fn: importMapClassifier(win.document, win.location.origin) });
|
|
1056
1108
|
return {
|
|
1057
1109
|
options: this.options,
|
|
1058
1110
|
scope: this.scope,
|
|
1059
1111
|
origin: win.location.origin,
|
|
1060
1112
|
href: win.location.href,
|
|
1061
1113
|
userAgent: win.navigator.userAgent,
|
|
1062
|
-
session: this.rum?.session
|
|
1114
|
+
session: this.rum?.session,
|
|
1115
|
+
classify: this.classify.fn
|
|
1063
1116
|
};
|
|
1064
1117
|
}
|
|
1065
1118
|
capture(build) {
|
|
@@ -1105,10 +1158,12 @@ var Client = class {
|
|
|
1105
1158
|
};
|
|
1106
1159
|
|
|
1107
1160
|
// src/index.ts
|
|
1108
|
-
var SDK_VERSION = "0.
|
|
1161
|
+
var SDK_VERSION = "0.5.0";
|
|
1109
1162
|
var client;
|
|
1110
1163
|
var pendingRoute;
|
|
1111
1164
|
var pendingScope = new Scope();
|
|
1165
|
+
var userFromApp = false;
|
|
1166
|
+
var stopPageListener;
|
|
1112
1167
|
function scope() {
|
|
1113
1168
|
return client?.scope ?? pendingScope;
|
|
1114
1169
|
}
|
|
@@ -1120,12 +1175,21 @@ function safely(fn, fallback) {
|
|
|
1120
1175
|
return fallback;
|
|
1121
1176
|
}
|
|
1122
1177
|
}
|
|
1123
|
-
function init(options) {
|
|
1178
|
+
function init(options = {}) {
|
|
1124
1179
|
safely(() => {
|
|
1125
1180
|
if (typeof window === "undefined") return;
|
|
1126
1181
|
const kept = scope();
|
|
1127
1182
|
client?.close();
|
|
1128
|
-
|
|
1183
|
+
stopPageListener?.();
|
|
1184
|
+
client = new Client(withMeta(options), window, kept);
|
|
1185
|
+
userFromMeta();
|
|
1186
|
+
const onPageLoad = () => {
|
|
1187
|
+
safely(userFromMeta, void 0);
|
|
1188
|
+
};
|
|
1189
|
+
document.addEventListener("turbo:load", onPageLoad);
|
|
1190
|
+
stopPageListener = () => {
|
|
1191
|
+
document.removeEventListener("turbo:load", onPageLoad);
|
|
1192
|
+
};
|
|
1129
1193
|
if (pendingRoute) client.setRoute(pendingRoute.name);
|
|
1130
1194
|
pendingRoute = void 0;
|
|
1131
1195
|
if (options.debug === true) Object.defineProperty(window, CONSOLE_HANDLE, { value: { test }, configurable: true, writable: true });
|
|
@@ -1133,6 +1197,21 @@ function init(options) {
|
|
|
1133
1197
|
}, void 0);
|
|
1134
1198
|
}
|
|
1135
1199
|
var CONSOLE_HANDLE = "__collector";
|
|
1200
|
+
function withMeta(options) {
|
|
1201
|
+
const resolved = { ...options };
|
|
1202
|
+
const dsn = options.dsn ?? readMeta("collector-dsn");
|
|
1203
|
+
const environment = options.environment ?? readMeta("collector-environment");
|
|
1204
|
+
const release = options.release ?? readMeta("collector-release");
|
|
1205
|
+
if (dsn !== void 0) resolved.dsn = dsn;
|
|
1206
|
+
if (environment !== void 0) resolved.environment = environment;
|
|
1207
|
+
if (release !== void 0) resolved.release = release;
|
|
1208
|
+
return resolved;
|
|
1209
|
+
}
|
|
1210
|
+
function userFromMeta() {
|
|
1211
|
+
if (userFromApp) return;
|
|
1212
|
+
const id = readMeta("collector-user");
|
|
1213
|
+
scope().setUser(id === void 0 ? null : { id });
|
|
1214
|
+
}
|
|
1136
1215
|
async function test() {
|
|
1137
1216
|
const notInitialized = () => {
|
|
1138
1217
|
const reason = "init() hasn't run on this page (or this isn't a browser).";
|
|
@@ -1149,6 +1228,7 @@ function captureMessage(message, context) {
|
|
|
1149
1228
|
}
|
|
1150
1229
|
function setUser(user) {
|
|
1151
1230
|
safely(() => {
|
|
1231
|
+
userFromApp = true;
|
|
1152
1232
|
scope().setUser(user);
|
|
1153
1233
|
}, void 0);
|
|
1154
1234
|
}
|
|
@@ -1181,8 +1261,11 @@ function close() {
|
|
|
1181
1261
|
safely(() => {
|
|
1182
1262
|
client?.close();
|
|
1183
1263
|
client = void 0;
|
|
1264
|
+
stopPageListener?.();
|
|
1265
|
+
stopPageListener = void 0;
|
|
1184
1266
|
pendingScope = new Scope();
|
|
1185
1267
|
pendingRoute = void 0;
|
|
1268
|
+
userFromApp = false;
|
|
1186
1269
|
if (typeof window !== "undefined") Reflect.deleteProperty(window, CONSOLE_HANDLE);
|
|
1187
1270
|
}, void 0);
|
|
1188
1271
|
}
|
package/dist/rum.cjs
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
// src/meta.ts
|
|
4
|
+
function readMeta(name) {
|
|
5
|
+
if (typeof document === "undefined") return void 0;
|
|
6
|
+
const content = document.querySelector(`meta[name="${name}"]`)?.content.trim();
|
|
7
|
+
return content === void 0 || content === "" ? void 0 : content;
|
|
8
|
+
}
|
|
9
|
+
|
|
3
10
|
// src/util.ts
|
|
4
11
|
function uuid4() {
|
|
5
12
|
if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
|
|
@@ -97,7 +104,15 @@ var Tracker = class {
|
|
|
97
104
|
if (owner === this.current) this.settle?.();
|
|
98
105
|
}
|
|
99
106
|
setRoute(name) {
|
|
100
|
-
if (this.current)
|
|
107
|
+
if (!this.current) return;
|
|
108
|
+
this.current.route = name === void 0 ? void 0 : stripUrl(name);
|
|
109
|
+
this.current.named = true;
|
|
110
|
+
}
|
|
111
|
+
/** The page rendered (turbo:load): names the current page view again, unless the app named it. */
|
|
112
|
+
pageLoaded() {
|
|
113
|
+
if (this.closed) return;
|
|
114
|
+
this.navigate();
|
|
115
|
+
if (this.current && this.current.named !== true) this.current.route = this.routeFor(true);
|
|
101
116
|
}
|
|
102
117
|
/** The id of the page view in progress, if any. */
|
|
103
118
|
currentId() {
|
|
@@ -134,12 +149,17 @@ var Tracker = class {
|
|
|
134
149
|
}
|
|
135
150
|
begin(navigation, start2) {
|
|
136
151
|
this.lastKey = keyOf();
|
|
152
|
+
return { id: uuid4(), key: this.lastKey, path: location.pathname, navigation, start: start2, route: this.routeFor(navigation === "hard"), requests: [], pending: 0 };
|
|
153
|
+
}
|
|
154
|
+
/** The `route` option's name for this URL, else (when `fromPage`) the page's own. */
|
|
155
|
+
routeFor(fromPage) {
|
|
137
156
|
let route;
|
|
138
157
|
try {
|
|
139
158
|
route = this.options.route?.(location);
|
|
140
159
|
} catch {
|
|
141
160
|
}
|
|
142
|
-
|
|
161
|
+
if (route === void 0 && fromPage) route = this.options.pageRoute?.();
|
|
162
|
+
return route === void 0 ? void 0 : stripUrl(route);
|
|
143
163
|
}
|
|
144
164
|
/** Measures how long an in-app navigation takes to settle. */
|
|
145
165
|
watch(live) {
|
|
@@ -517,11 +537,12 @@ function observeVitals() {
|
|
|
517
537
|
var SEND_EVERY = 10;
|
|
518
538
|
var SEND_INTERVAL_MS = 5 * 6e4;
|
|
519
539
|
var load;
|
|
520
|
-
function rum(options) {
|
|
540
|
+
function rum(options = {}) {
|
|
521
541
|
return { start: (ctx) => start(ctx, options) };
|
|
522
542
|
}
|
|
523
543
|
function start(ctx, options) {
|
|
524
|
-
const
|
|
544
|
+
const sampleRate = options.sampleRate ?? Number(readMeta("collector-rum-sample-rate"));
|
|
545
|
+
const { id, sampled } = sessionFor(sampleRate);
|
|
525
546
|
if (!sampled) {
|
|
526
547
|
ctx.logger.debug("RUM: this tab wasn't sampled");
|
|
527
548
|
const nothing = () => void 0;
|
|
@@ -529,7 +550,7 @@ function start(ctx, options) {
|
|
|
529
550
|
}
|
|
530
551
|
const base = ctx.url.slice(0, ctx.url.indexOf("/api/pageviews"));
|
|
531
552
|
const vitals = observeVitals();
|
|
532
|
-
const tracker = new Tracker({ vitals: () => vitals, route: options.route, own: (url) => url.startsWith(`${base}/`), first: load?.open ?? true, hardId: load?.id });
|
|
553
|
+
const tracker = new Tracker({ vitals: () => vitals, route: options.route, pageRoute: () => readMeta("collector-route"), own: (url) => url.startsWith(`${base}/`), first: load?.open ?? true, hardId: load?.id });
|
|
533
554
|
const opened = tracker.currentId();
|
|
534
555
|
load ?? (load = { id: opened ?? "", open: opened !== void 0 });
|
|
535
556
|
const sender = new Sender({
|
|
@@ -538,7 +559,7 @@ function start(ctx, options) {
|
|
|
538
559
|
logger: ctx.logger,
|
|
539
560
|
sdk: ctx.sdk,
|
|
540
561
|
session: id,
|
|
541
|
-
sampleRate
|
|
562
|
+
sampleRate,
|
|
542
563
|
environment: ctx.environment,
|
|
543
564
|
release: ctx.release,
|
|
544
565
|
beforeSendPageview: options.beforeSendPageview
|
|
@@ -551,6 +572,7 @@ function start(ctx, options) {
|
|
|
551
572
|
tracker.close();
|
|
552
573
|
vitals.stop();
|
|
553
574
|
document.removeEventListener("visibilitychange", onVisibility);
|
|
575
|
+
document.removeEventListener("turbo:load", onPageLoad);
|
|
554
576
|
window.removeEventListener("pagehide", onPageHide);
|
|
555
577
|
};
|
|
556
578
|
const send = (pageviews, how) => {
|
|
@@ -579,6 +601,12 @@ function start(ctx, options) {
|
|
|
579
601
|
};
|
|
580
602
|
document.addEventListener("visibilitychange", onVisibility);
|
|
581
603
|
window.addEventListener("pagehide", onPageHide);
|
|
604
|
+
const queue = () => {
|
|
605
|
+
if (load && tracker.currentId() !== load.id) load.open = false;
|
|
606
|
+
const waiting = tracker.finishedCount();
|
|
607
|
+
if (waiting >= SEND_EVERY) sendFinished();
|
|
608
|
+
else if (waiting > 0) timer ?? (timer = setTimeout(sendFinished, SEND_INTERVAL_MS));
|
|
609
|
+
};
|
|
582
610
|
const guard = (fn) => (...args) => {
|
|
583
611
|
if (closed) return;
|
|
584
612
|
try {
|
|
@@ -587,6 +615,11 @@ function start(ctx, options) {
|
|
|
587
615
|
ctx.logger.debug("RUM error", error);
|
|
588
616
|
}
|
|
589
617
|
};
|
|
618
|
+
const onPageLoad = guard(() => {
|
|
619
|
+
tracker.pageLoaded();
|
|
620
|
+
queue();
|
|
621
|
+
});
|
|
622
|
+
document.addEventListener("turbo:load", onPageLoad);
|
|
590
623
|
return {
|
|
591
624
|
session: id,
|
|
592
625
|
requestStart: guard(() => {
|
|
@@ -597,10 +630,7 @@ function start(ctx, options) {
|
|
|
597
630
|
}),
|
|
598
631
|
navigate: guard(() => {
|
|
599
632
|
tracker.navigate();
|
|
600
|
-
|
|
601
|
-
const waiting = tracker.finishedCount();
|
|
602
|
-
if (waiting >= SEND_EVERY) sendFinished();
|
|
603
|
-
else if (waiting > 0) timer ?? (timer = setTimeout(sendFinished, SEND_INTERVAL_MS));
|
|
633
|
+
queue();
|
|
604
634
|
}),
|
|
605
635
|
setRoute: guard((name) => {
|
|
606
636
|
tracker.setRoute(name);
|
package/dist/rum.d.cts
CHANGED
|
@@ -34,9 +34,15 @@ interface PageView {
|
|
|
34
34
|
}
|
|
35
35
|
|
|
36
36
|
interface RumOptions {
|
|
37
|
-
/**
|
|
38
|
-
|
|
39
|
-
|
|
37
|
+
/**
|
|
38
|
+
* Share of tabs to measure, `0 < sampleRate ≤ 1`, decided once per tab. `0.1` is a good start.
|
|
39
|
+
* Default: the page's `<meta name="collector-rum-sample-rate">`; without either, nothing is measured.
|
|
40
|
+
*/
|
|
41
|
+
sampleRate?: number;
|
|
42
|
+
/**
|
|
43
|
+
* Your app's route name for a URL, e.g. `/products/:id`. `setRoute()` wins over it, and it wins
|
|
44
|
+
* over the page's `<meta name="collector-route">`.
|
|
45
|
+
*/
|
|
40
46
|
route?: (location: Location) => string | undefined;
|
|
41
47
|
/** Last chance to edit or drop a page view: return it, changed or not, or `null`. */
|
|
42
48
|
beforeSendPageview?: (pageview: PageView) => PageView | null;
|
|
@@ -51,7 +57,7 @@ interface RumOptions {
|
|
|
51
57
|
* Collector.init({ dsn: "…", rum: rum({ sampleRate: 0.1 }) });
|
|
52
58
|
* ```
|
|
53
59
|
*/
|
|
54
|
-
declare function rum(options
|
|
60
|
+
declare function rum(options?: RumOptions): RumPlugin;
|
|
55
61
|
|
|
56
62
|
export { rum };
|
|
57
63
|
export type { PageView, RumOptions };
|
package/dist/rum.d.ts
CHANGED
|
@@ -34,9 +34,15 @@ interface PageView {
|
|
|
34
34
|
}
|
|
35
35
|
|
|
36
36
|
interface RumOptions {
|
|
37
|
-
/**
|
|
38
|
-
|
|
39
|
-
|
|
37
|
+
/**
|
|
38
|
+
* Share of tabs to measure, `0 < sampleRate ≤ 1`, decided once per tab. `0.1` is a good start.
|
|
39
|
+
* Default: the page's `<meta name="collector-rum-sample-rate">`; without either, nothing is measured.
|
|
40
|
+
*/
|
|
41
|
+
sampleRate?: number;
|
|
42
|
+
/**
|
|
43
|
+
* Your app's route name for a URL, e.g. `/products/:id`. `setRoute()` wins over it, and it wins
|
|
44
|
+
* over the page's `<meta name="collector-route">`.
|
|
45
|
+
*/
|
|
40
46
|
route?: (location: Location) => string | undefined;
|
|
41
47
|
/** Last chance to edit or drop a page view: return it, changed or not, or `null`. */
|
|
42
48
|
beforeSendPageview?: (pageview: PageView) => PageView | null;
|
|
@@ -51,7 +57,7 @@ interface RumOptions {
|
|
|
51
57
|
* Collector.init({ dsn: "…", rum: rum({ sampleRate: 0.1 }) });
|
|
52
58
|
* ```
|
|
53
59
|
*/
|
|
54
|
-
declare function rum(options
|
|
60
|
+
declare function rum(options?: RumOptions): RumPlugin;
|
|
55
61
|
|
|
56
62
|
export { rum };
|
|
57
63
|
export type { PageView, RumOptions };
|
package/dist/rum.esm.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! @chrom-ar/collector v0.5.0 | MIT */
|
|
2
|
+
function _(r){if(typeof document>"u")return;let e=document.querySelector(`meta[name="${r}"]`)?.content.trim();return e===void 0||e===""?void 0:e}function L(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let r=crypto.getRandomValues(new Uint8Array(16));r[6]=(r[6]??0)&15|64,r[8]=(r[8]??0)&63|128;let e=Array.from(r,t=>t.toString(16).padStart(2,"0")).join("");return `${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function A(r){let e=r.search(/[?#]/);return e===-1?r:r.slice(0,e)}var K=500;function B(r,e){try{let t=new URL(e,r);return t.protocol!=="http:"&&t.protocol!=="https:"?void 0:(t.origin+t.pathname).slice(0,K)}catch{return}}var D=500,F=1e4,G=1e3,Q=50,Y=30,H=300,C={lcp:4e3,inp:500,nav:2500},U=()=>location.pathname,V=class{constructor(e){this.options=e;this.finished=[];this.lastKey=U();this.lastClick=-1/0;this.closed=false;this.resources=[];this.cleanups=[];e.first&&(this.current=this.begin("hard",0),e.hardId!==void 0&&(this.current.id=e.hardId));let t=()=>{this.lastClick=performance.now();},o=n=>{n.persisted&&this.next(performance.now());};document.addEventListener("click",t,true),window.addEventListener("pageshow",o),this.cleanups.push(()=>{document.removeEventListener("click",t,true),window.removeEventListener("pageshow",o);});try{if(typeof PerformanceObserver<"u"&&PerformanceObserver.supportedEntryTypes.includes("resource")){let n=new PerformanceObserver(i=>{for(let l of i.getEntries())this.resources.push({name:l.name,type:l.initiatorType,start:l.startTime,duration:l.duration,size:l.transferSize});this.resources.length>H&&this.resources.splice(0,this.resources.length-H);});n.observe({type:"resource",buffered:!0}),this.cleanups.push(()=>{n.disconnect();});}}catch{}}navigate(){if(this.closed||U()===this.lastKey)return;let e=performance.now(),t=this.lastClick>=(this.current?.start??-1/0)&&e-this.lastClick<=G?this.lastClick:e;this.lastClick=-1/0,this.next(t);}requestStart(){return this.current&&(this.current.pending+=1),this.current}request(e,t){let o=[this.current,...this.finished].filter(i=>i!==void 0),n=t===void 0?o.filter(i=>i.start<=e.start).sort((i,l)=>l.start-i.start)[0]:o.find(i=>i===t);n&&(n.pending=Math.max(0,n.pending-1),n.requests.length<Q&&n.requests.push(e),n===this.current&&this.settle?.());}setRoute(e){this.current&&(this.current.route=e===void 0?void 0:A(e),this.current.named=true);}pageLoaded(){this.closed||(this.navigate(),this.current&&this.current.named!==true&&(this.current.route=this.routeFor(true)));}currentId(){return this.current?.id}finishedCount(){return this.finished.length}takeFinished(){let e=this.finished.splice(0).map(t=>this.toPageView(t));return e.length>0&&this.current&&this.options.vitals()?.prune(this.current.start),e}snapshot(){return [...this.finished,...this.current?[this.current]:[]].map(t=>this.toPageView(t))}close(){this.closed=true,this.settle=void 0;for(let e of this.cleanups.splice(0))e();}next(e){this.closed||(this.current&&(this.current.end=e,this.finished.push(this.current)),this.current=this.begin("soft",e),this.watch(this.current));}begin(e,t){return this.lastKey=U(),{id:L(),key:this.lastKey,path:location.pathname,navigation:e,start:t,route:this.routeFor(e==="hard"),requests:[],pending:0}}routeFor(e){let t;try{t=this.options.route?.(location);}catch{}return t===void 0&&e&&(t=this.options.pageRoute?.()),t===void 0?void 0:A(t)}watch(e){this.settle?.();let t=e.start,o,n,i=s=>{clearTimeout(o),clearTimeout(h),n?.disconnect(),this.settle===a&&(this.settle=void 0),e.nav=Math.round(s);},l=()=>{e.pending===0&&i(t-e.start);},a=()=>{t=performance.now(),clearTimeout(o),o=setTimeout(l,D);},h=setTimeout(()=>{i(F);},F);try{n=new MutationObserver(a),n.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,characterData:!0});}catch{}this.settle=()=>{if(e!==this.current||this.closed){clearTimeout(o),clearTimeout(h),n?.disconnect();return}a();},o=setTimeout(l,D);}toPageView(e){let t=this.options.vitals(),o=e.end??performance.now(),n={...e.navigation==="hard"?t?.hard():{},...t?.span(e.start,o),...e.nav===void 0?{}:{nav:e.nav}},i={id:e.id,at:new Date(performance.timeOrigin+e.start).toISOString(),path:e.path,navigation:e.navigation};if(e.route!==void 0&&e.route!==""&&(i.route=e.route),Object.keys(n).length>0&&(i.vitals=n),e.requests.length>0&&(i.requests=e.requests.map(a=>({method:a.method,url:a.url,status:a.status,start:Math.max(0,Math.round(a.start-e.start)),duration:Math.round(a.end-a.start)}))),(n.lcp??0)>C.lcp||(n.inp??0)>C.inp||(n.nav??0)>C.nav){let h=this.resources.flatMap(s=>{let f=B(location.href,s.name),g=s.start>=e.start&&(e.end===void 0||s.start<e.end);return f!==void 0&&g&&!this.options.own(s.name)?[{...s,name:f}]:[]}).sort((s,f)=>f.duration-s.duration).slice(0,Y);h.length>0&&(i.waterfall=h.map(s=>({name:s.name,type:s.type,start:Math.round(s.start-e.start),duration:Math.round(s.duration),...s.size>0?{size:s.size}:{}})));}return i}};var q="text/plain;charset=UTF-8",Z=new TextEncoder,ee=r=>Z.encode(r).length,k=class{constructor(e){this.options=e;this.stopped=false;this.pausedUntil=0;this.compressing=new Set;this.sent=new Map;}undispatched(){return [...this.compressing].flatMap(e=>e.pageviews)}async send(e,t){if(this.stopped||Date.now()<this.pausedUntil)return;let o=e.flatMap(i=>this.prepare(i)).filter(i=>this.sent.get(i.id)!==JSON.stringify(i)),n=this.batches(o);if(t!=="visible"&&(n=te(n,48e3,this.options.logger)),t==="pagehide"){for(let i of n)this.unload(i);return}if(t==="hidden"){await Promise.all(n.map(async i=>this.post(i,t)));return}for(let i of n)await this.post(i,t);}prepare(e){let t=this.options.beforeSendPageview;if(!t)return [e];let o;try{o=t(e);}catch(n){return this.options.logger.debug("beforeSendPageview threw; sending the page view unchanged",n),[e]}return o===null?[]:typeof o=="object"&&"then"in o?(this.options.logger.warnOnce("beforeSendPageview returned a Promise, so the page view was dropped. It must return the page view (or null) right away, not async."),[]):[o]}batches(e){let{sdk:t,environment:o,release:n,session:i,sampleRate:l}=this.options,a=f=>{let g=JSON.stringify({v:1,sdk:t,environment:o,release:n,session:i,sample_rate:l,pageviews:f});return {body:g,pageviews:f,bytes:ee(g)}},h=[],s=[];for(let f of e){if(a([...s,f]).bytes<=32e3){s.push(f);continue}s.length>0&&h.push(a(s)),s=[f],a(s).bytes>32e3&&(this.options.logger.debug("dropped a page view that is too big to send",f.id),s=[]);}return s.length>0&&h.push(a(s)),h}dispatched(e){for(let t of e.pageviews)this.sent.delete(t.id),this.sent.set(t.id,JSON.stringify(t));for(let t of [...this.sent.keys()].slice(0,Math.max(0,this.sent.size-200)))this.sent.delete(t);}unload(e){this.dispatched(e);let t=false;try{t=navigator.sendBeacon(this.options.url,new Blob([e.body],{type:q}));}catch{}if(!t)try{this.options.fetch(this.options.url,{method:"POST",body:e.body,headers:{"Content-Type":q},keepalive:!0,credentials:"omit"}).catch(()=>{});}catch{}}async post(e,t){let{url:o,fetch:n,logger:i}=this.options,l={"Content-Type":q},a=e.body;if(e.bytes>1024&&typeof CompressionStream=="function"){this.compressing.add(e);try{a=await ne(e.body),l["Content-Encoding"]="gzip";}catch{a=e.body;}finally{this.compressing.delete(e);}}this.dispatched(e);let h;try{h=await n(o,{method:"POST",body:a,headers:l,keepalive:!0,credentials:"omit"});}catch(f){t==="hidden"?this.unload(e):i.debug("page views not sent",f);return}let{status:s}=h;if(s===401||s===403||s===404)this.stopped=true,i.debug(`Collector turned RUM down (HTTP ${String(s)}): no more page views from this page`);else if(s===429){let f=Number.parseInt(h.headers.get("Retry-After")??"",10);this.pausedUntil=Date.now()+(f>=0?f:60)*1e3;}else (s<200||s>=300)&&i.debug(`page views dropped (HTTP ${String(s)})`);}};function te(r,e,t){let o=[],n=0;for(let i of [...r].reverse()){if(n+i.bytes>e){t.debug("an unloading page can't send this much; dropped the oldest page views");break}n+=i.bytes,o.unshift(i);}return o}async function ne(r){let e=new Response(r).body;if(!e)throw new Error("no stream");return new Response(e.pipeThrough(new CompressionStream("gzip"))).arrayBuffer()}var z="collector:rum",$;function re(){let r;try{r=sessionStorage.getItem(z);}catch{return $}if(r!==null)try{let e=JSON.parse(r);if(typeof e=="object"&&e!==null&&"session"in e&&"rate"in e&&"sampled"in e){let{session:t,rate:o,sampled:n}=e;if(typeof t=="string"&&typeof o=="number"&&typeof n=="boolean")return {session:t,rate:o,sampled:n}}}catch{}}function W(r,e=Math.random){let t=re();if(t?.rate===r)return {id:t.session,sampled:t.sampled};let o=r>0&&r<=1,n={session:L(),rate:r,sampled:o&&e()<r};$=n;try{sessionStorage.setItem(z,JSON.stringify(n));}catch{}return {id:n.session,sampled:n.sampled}}function I(r,e){let t=r===void 0?void 0:Reflect.get(r,e);return typeof t=="number"?t:void 0}var ie=1e3,se=5e3;function X(){let r=performance.getEntriesByType("navigation")[0],e=I(r,"activationStart")??0,t=I(r,"responseStart"),o=t===void 0?void 0:Math.max(0,t-e),n=document.visibilityState==="hidden"&&Reflect.get(document,"prerendering")!==true?0:1/0,i=1/0,l,a,h=[],s=[],f=()=>{document.visibilityState==="hidden"&&(n=Math.min(n,performance.now()));};document.addEventListener("visibilitychange",f,true);let g=[],w=(d,u,p)=>{try{if(typeof PerformanceObserver>"u"||!PerformanceObserver.supportedEntryTypes.includes(d))return;let m=new PerformanceObserver(b=>{try{u(b.getEntries());}catch{}});m.observe({type:d,buffered:!0,...p}),g.push(m);}catch{}},T=d=>{for(let u of d){let p=I(u,"interactionId")??0;p>0&&s.length<5e3&&s.push({id:p,t:u.startTime,d:u.duration});}};w("first-input",d=>{for(let u of d)i=Math.min(i,u.startTime);T(d);}),w("paint",d=>{for(let u of d)u.name==="first-contentful-paint"&&u.startTime<n&&(a=u.startTime);}),w("largest-contentful-paint",d=>{for(let u of d)u.startTime<Math.min(n,i)&&(l=u.startTime);}),w("layout-shift",d=>{for(let u of d){let p=I(u,"value");p!==void 0&&Reflect.get(u,"hadRecentInput")!==!0&&h.length<5e3&&h.push({t:u.startTime,v:p});}}),w("event",T,{durationThreshold:16});let M=d=>d===void 0?void 0:Math.round(Math.max(0,d-e)),P=(d,u)=>p=>p.t>=d&&p.t<u;return {hard(){let d={},u=M(l),p=M(a);return u!==void 0&&(d.lcp=u),p!==void 0&&(d.fcp=p),o!==void 0&&(d.ttfb=Math.round(o)),d},span(d,u){let p={},m=0,b=0,c=-1/0,v=-1/0,E=false;for(let{t:y,v:R}of h.filter(P(d,u)).sort((j,J)=>j.t-J.t))E=true,(y-v>ie||y-c>=se)&&(c=y,b=0),b+=R,v=y,m=Math.max(m,b);E&&(p.cls=m);let O=new Map;for(let{id:y,d:R}of s.filter(P(d,u)))O.set(y,Math.max(O.get(y)??0,R));let x=[...O.values()].sort((y,R)=>R-y),N=x[Math.min(x.length-1,Math.floor(x.length/50))];return N!==void 0&&(p.inp=Math.round(N)),p},prune(d){let u=p=>{let m=p.filter(b=>b.t>=d);p.splice(0,p.length,...m);};u(h),u(s);},stop(){for(let d of g)d.disconnect();document.removeEventListener("visibilitychange",f,true);}}}var oe=10,ae=5*6e4,S;function Te(r={}){return {start:e=>de(e,r)}}function de(r,e){let t=e.sampleRate??Number(_("collector-rum-sample-rate")),{id:o,sampled:n}=W(t);if(!n){r.logger.debug("RUM: this tab wasn't sampled");let c=()=>{};return {session:void 0,requestStart:c,request:c,navigate:c,setRoute:c,close:c}}let i=r.url.slice(0,r.url.indexOf("/api/pageviews")),l=X(),a=new V({vitals:()=>l,route:e.route,pageRoute:()=>_("collector-route"),own:c=>c.startsWith(`${i}/`),first:S?.open??true,hardId:S?.id}),h=a.currentId();S??(S={id:h??"",open:h!==void 0});let s=new k({url:r.url,fetch:r.fetch,logger:r.logger,sdk:r.sdk,session:o,sampleRate:t,environment:r.environment,release:r.release,beforeSendPageview:e.beforeSendPageview}),f=false,g,w=()=>{f=true,clearTimeout(g),a.close(),l.stop(),document.removeEventListener("visibilitychange",d),document.removeEventListener("turbo:load",b),window.removeEventListener("pagehide",u);},T=(c,v)=>{c.length!==0&&s.send(c,v).then(()=>{s.stopped&&!f&&w();},()=>{});},M=c=>{T([...a.takeFinished(),...a.snapshot()],c);},P=()=>{clearTimeout(g),g=void 0,T(a.takeFinished(),"visible");},d=()=>{document.visibilityState==="hidden"&&M("hidden");},u=()=>{let c=[...s.undispatched(),...a.takeFinished(),...a.snapshot()];T([...new Map(c.map(v=>[v.id,v])).values()],"pagehide");};document.addEventListener("visibilitychange",d),window.addEventListener("pagehide",u);let p=()=>{S&&a.currentId()!==S.id&&(S.open=false);let c=a.finishedCount();c>=oe?P():c>0&&(g??(g=setTimeout(P,ae)));},m=c=>(...v)=>{if(!f)try{c(...v);}catch(E){r.logger.debug("RUM error",E);}},b=m(()=>{a.pageLoaded(),p();});return document.addEventListener("turbo:load",b),{session:o,requestStart:m(()=>{a.requestStart();}),request:m(c=>{a.request(c);}),navigate:m(()=>{a.navigate(),p();}),setRoute:m(c=>{a.setRoute(c);}),close:m(()=>{M("visible"),w();})}}export{Te as rum};
|
package/dist/rum.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { uuid4, stripUrl, rumUrl } from './chunk-
|
|
1
|
+
import { readMeta, uuid4, stripUrl, rumUrl } from './chunk-42XODVHT.js';
|
|
2
2
|
|
|
3
3
|
// src/rum/pageviews.ts
|
|
4
4
|
var QUIET_MS = 500;
|
|
@@ -73,7 +73,15 @@ var Tracker = class {
|
|
|
73
73
|
if (owner === this.current) this.settle?.();
|
|
74
74
|
}
|
|
75
75
|
setRoute(name) {
|
|
76
|
-
if (this.current)
|
|
76
|
+
if (!this.current) return;
|
|
77
|
+
this.current.route = name === void 0 ? void 0 : stripUrl(name);
|
|
78
|
+
this.current.named = true;
|
|
79
|
+
}
|
|
80
|
+
/** The page rendered (turbo:load): names the current page view again, unless the app named it. */
|
|
81
|
+
pageLoaded() {
|
|
82
|
+
if (this.closed) return;
|
|
83
|
+
this.navigate();
|
|
84
|
+
if (this.current && this.current.named !== true) this.current.route = this.routeFor(true);
|
|
77
85
|
}
|
|
78
86
|
/** The id of the page view in progress, if any. */
|
|
79
87
|
currentId() {
|
|
@@ -110,12 +118,17 @@ var Tracker = class {
|
|
|
110
118
|
}
|
|
111
119
|
begin(navigation, start2) {
|
|
112
120
|
this.lastKey = keyOf();
|
|
121
|
+
return { id: uuid4(), key: this.lastKey, path: location.pathname, navigation, start: start2, route: this.routeFor(navigation === "hard"), requests: [], pending: 0 };
|
|
122
|
+
}
|
|
123
|
+
/** The `route` option's name for this URL, else (when `fromPage`) the page's own. */
|
|
124
|
+
routeFor(fromPage) {
|
|
113
125
|
let route;
|
|
114
126
|
try {
|
|
115
127
|
route = this.options.route?.(location);
|
|
116
128
|
} catch {
|
|
117
129
|
}
|
|
118
|
-
|
|
130
|
+
if (route === void 0 && fromPage) route = this.options.pageRoute?.();
|
|
131
|
+
return route === void 0 ? void 0 : stripUrl(route);
|
|
119
132
|
}
|
|
120
133
|
/** Measures how long an in-app navigation takes to settle. */
|
|
121
134
|
watch(live) {
|
|
@@ -493,11 +506,12 @@ function observeVitals() {
|
|
|
493
506
|
var SEND_EVERY = 10;
|
|
494
507
|
var SEND_INTERVAL_MS = 5 * 6e4;
|
|
495
508
|
var load;
|
|
496
|
-
function rum(options) {
|
|
509
|
+
function rum(options = {}) {
|
|
497
510
|
return { start: (ctx) => start(ctx, options) };
|
|
498
511
|
}
|
|
499
512
|
function start(ctx, options) {
|
|
500
|
-
const
|
|
513
|
+
const sampleRate = options.sampleRate ?? Number(readMeta("collector-rum-sample-rate"));
|
|
514
|
+
const { id, sampled } = sessionFor(sampleRate);
|
|
501
515
|
if (!sampled) {
|
|
502
516
|
ctx.logger.debug("RUM: this tab wasn't sampled");
|
|
503
517
|
const nothing = () => void 0;
|
|
@@ -505,7 +519,7 @@ function start(ctx, options) {
|
|
|
505
519
|
}
|
|
506
520
|
const base = ctx.url.slice(0, ctx.url.indexOf("/api/pageviews"));
|
|
507
521
|
const vitals = observeVitals();
|
|
508
|
-
const tracker = new Tracker({ vitals: () => vitals, route: options.route, own: (url) => url.startsWith(`${base}/`), first: load?.open ?? true, hardId: load?.id });
|
|
522
|
+
const tracker = new Tracker({ vitals: () => vitals, route: options.route, pageRoute: () => readMeta("collector-route"), own: (url) => url.startsWith(`${base}/`), first: load?.open ?? true, hardId: load?.id });
|
|
509
523
|
const opened = tracker.currentId();
|
|
510
524
|
load ?? (load = { id: opened ?? "", open: opened !== void 0 });
|
|
511
525
|
const sender = new Sender({
|
|
@@ -514,7 +528,7 @@ function start(ctx, options) {
|
|
|
514
528
|
logger: ctx.logger,
|
|
515
529
|
sdk: ctx.sdk,
|
|
516
530
|
session: id,
|
|
517
|
-
sampleRate
|
|
531
|
+
sampleRate,
|
|
518
532
|
environment: ctx.environment,
|
|
519
533
|
release: ctx.release,
|
|
520
534
|
beforeSendPageview: options.beforeSendPageview
|
|
@@ -527,6 +541,7 @@ function start(ctx, options) {
|
|
|
527
541
|
tracker.close();
|
|
528
542
|
vitals.stop();
|
|
529
543
|
document.removeEventListener("visibilitychange", onVisibility);
|
|
544
|
+
document.removeEventListener("turbo:load", onPageLoad);
|
|
530
545
|
window.removeEventListener("pagehide", onPageHide);
|
|
531
546
|
};
|
|
532
547
|
const send = (pageviews, how) => {
|
|
@@ -555,6 +570,12 @@ function start(ctx, options) {
|
|
|
555
570
|
};
|
|
556
571
|
document.addEventListener("visibilitychange", onVisibility);
|
|
557
572
|
window.addEventListener("pagehide", onPageHide);
|
|
573
|
+
const queue = () => {
|
|
574
|
+
if (load && tracker.currentId() !== load.id) load.open = false;
|
|
575
|
+
const waiting = tracker.finishedCount();
|
|
576
|
+
if (waiting >= SEND_EVERY) sendFinished();
|
|
577
|
+
else if (waiting > 0) timer ?? (timer = setTimeout(sendFinished, SEND_INTERVAL_MS));
|
|
578
|
+
};
|
|
558
579
|
const guard = (fn) => (...args) => {
|
|
559
580
|
if (closed) return;
|
|
560
581
|
try {
|
|
@@ -563,6 +584,11 @@ function start(ctx, options) {
|
|
|
563
584
|
ctx.logger.debug("RUM error", error);
|
|
564
585
|
}
|
|
565
586
|
};
|
|
587
|
+
const onPageLoad = guard(() => {
|
|
588
|
+
tracker.pageLoaded();
|
|
589
|
+
queue();
|
|
590
|
+
});
|
|
591
|
+
document.addEventListener("turbo:load", onPageLoad);
|
|
566
592
|
return {
|
|
567
593
|
session: id,
|
|
568
594
|
requestStart: guard(() => {
|
|
@@ -573,10 +599,7 @@ function start(ctx, options) {
|
|
|
573
599
|
}),
|
|
574
600
|
navigate: guard(() => {
|
|
575
601
|
tracker.navigate();
|
|
576
|
-
|
|
577
|
-
const waiting = tracker.finishedCount();
|
|
578
|
-
if (waiting >= SEND_EVERY) sendFinished();
|
|
579
|
-
else if (waiting > 0) timer ?? (timer = setTimeout(sendFinished, SEND_INTERVAL_MS));
|
|
602
|
+
queue();
|
|
580
603
|
}),
|
|
581
604
|
setRoute: guard((name) => {
|
|
582
605
|
tracker.setRoute(name);
|