@plasius/nfr 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,203 @@
1
+ Copyright 2025 Plasius LTD
2
+
3
+ Apache License
4
+ Version 2.0, January 2004
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "Licensor" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "control" means (i) the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
+ outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ "You" (or "Your") shall mean an individual or Legal Entity
26
+ exercising permissions granted by this License.
27
+
28
+ "Source" form shall mean the preferred form for making modifications,
29
+ including but not limited to software source code, documentation
30
+ source, and configuration files.
31
+
32
+ "Object" form shall mean any form resulting from mechanical
33
+ transformation or translation of a Source form, including but
34
+ not limited to compiled object code, generated documentation,
35
+ and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or
38
+ Object form, made available under the License, as indicated by a
39
+ copyright notice that is included in or attached to the work
40
+ (an example is provided in the Appendix below).
41
+
42
+ "Derivative Works" shall mean any work, whether in Source or Object
43
+ form, that is based on (or derived from) the Work and for which the
44
+ editorial revisions, annotations, elaborations, or other modifications
45
+ represent, as a whole, an original work of authorship. For the purposes
46
+ of this License, Derivative Works shall not include works that remain
47
+ separable from, or merely link (or bind by name) to the interfaces of,
48
+ the Work and Derivative Works thereof.
49
+
50
+ "Contribution" shall mean any work of authorship, including
51
+ the original version of the Work and any modifications or additions
52
+ to that Work or Derivative Works thereof, that is intentionally
53
+ submitted to Licensor for inclusion in the Work by the copyright owner
54
+ or by an individual or Legal Entity authorized to submit on behalf of
55
+ the copyright owner. For the purposes of this definition, "submitted"
56
+ means any form of electronic, verbal, or written communication sent
57
+ to the Licensor or its representatives, including but not limited to
58
+ communication on electronic mailing lists, source code control systems,
59
+ and issue tracking systems that are managed by, or on behalf of, the
60
+ Licensor for the purpose of discussing and improving the Work, but
61
+ excluding communication that is conspicuously marked or otherwise
62
+ designated in writing by the copyright owner as "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, and in Source or Object form, provided that You
94
+ meet the following conditions:
95
+
96
+ (a) You must give any other recipients of the Work or
97
+ Derivative Works a copy of this License; and
98
+
99
+ (b) You must cause any modified files to carry prominent notices
100
+ stating that You changed the files; and
101
+
102
+ (c) You must retain, in the Source form of any Derivative Works
103
+ that You distribute, all copyright, patent, trademark, and
104
+ attribution notices from the Source form of the Work,
105
+ excluding those notices that do not pertain to any part of
106
+ the Derivative Works; and
107
+
108
+ (d) If the Work includes a "NOTICE" text file as part of its
109
+ distribution, then any Derivative Works that You distribute must
110
+ include a readable copy of the attribution notices contained
111
+ within such NOTICE file, excluding those notices that do not
112
+ pertain to any part of the Derivative Works, in at least one
113
+ of the following places: within a NOTICE text file distributed
114
+ as part of the Derivative Works; within the Source form or
115
+ documentation, if provided along with the Derivative Works; or,
116
+ within a display generated by the Derivative Works, if and
117
+ wherever such third-party notices normally appear. The contents
118
+ of the NOTICE file are for informational purposes only and
119
+ do not modify the License. You may add Your own attribution
120
+ notices within Derivative Works that You distribute, alongside
121
+ or as an addendum to the NOTICE text from the Work, provided
122
+ that such additional attribution notices cannot be construed
123
+ as modifying the License.
124
+
125
+ You may add Your own copyright statement to Your modifications and
126
+ may provide additional or different license terms and conditions
127
+ for use, reproduction, or distribution of Your modifications, or
128
+ for any such Derivative Works as a whole, provided Your use,
129
+ reproduction, and distribution of the Work otherwise complies with
130
+ the conditions stated in this License.
131
+
132
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
133
+ any Contribution intentionally submitted for inclusion in the Work
134
+ by You to the Licensor shall be under the terms and conditions of
135
+ this License, without any additional terms or conditions.
136
+ Notwithstanding the above, nothing herein shall supersede or modify
137
+ the terms of any separate license agreement you may have executed
138
+ with Licensor regarding such Contributions.
139
+
140
+ 6. Trademarks. This License does not grant permission to use the trade
141
+ names, trademarks, service marks, or product names of the Licensor,
142
+ except as required for reasonable and customary use in describing the
143
+ origin of the Work and reproducing the content of the NOTICE file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this License.
154
+
155
+ 8. Limitation of Liability. In no event and under no legal theory,
156
+ whether in tort (including negligence), contract, or otherwise,
157
+ unless required by applicable law (such as deliberate and grossly
158
+ negligent acts) or agreed to in writing, shall any Contributor be
159
+ liable to You for damages, including any direct, indirect, special,
160
+ incidental, or consequential damages of any character arising as a
161
+ result of this License or out of the use or inability to use the
162
+ Work (including but not limited to damages for loss of goodwill,
163
+ work stoppage, computer failure or malfunction, or any and all
164
+ other commercial damages or losses), even if such Contributor
165
+ has been advised of the possibility of such damages.
166
+
167
+ 9. Accepting Warranty or Additional Liability. While redistributing
168
+ the Work or Derivative Works thereof, You may choose to offer,
169
+ and charge a fee for, acceptance of support, warranty, indemnity,
170
+ or other liability obligations and/or rights consistent with this
171
+ License. However, in accepting such obligations, You may act only
172
+ on Your own behalf and on Your sole responsibility, not on behalf
173
+ of any other Contributor, and only if You agree to indemnify,
174
+ defend, and hold each Contributor harmless for any liability
175
+ incurred by, or claims asserted against, such Contributor by reason
176
+ of your accepting any such warranty or additional liability.
177
+
178
+ END OF TERMS AND CONDITIONS
179
+
180
+ APPENDIX: How to apply the Apache License to your work.
181
+
182
+ To apply the Apache License to your work, attach the following
183
+ boilerplate notice, with the fields enclosed by brackets "[]"
184
+ replaced with your own identifying information. (Don't include
185
+ the brackets!) The text should be enclosed in the appropriate
186
+ comment syntax for the file format. We also recommend that a
187
+ file or class name and description of purpose be included on the
188
+ same "printed page" as the copyright notice for easier
189
+ identification within third-party archives.
190
+
191
+ Copyright [yyyy] [name of copyright owner]
192
+
193
+ Licensed under the Apache License, Version 2.0 (the "License");
194
+ you may not use this file except in compliance with the License.
195
+ You may obtain a copy of the License at
196
+
197
+ http://www.apache.org/licenses/LICENSE-2.0
198
+
199
+ Unless required by applicable law or agreed to in writing, software
200
+ distributed under the License is distributed on an "AS IS" BASIS,
201
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202
+ See the License for the specific language governing permissions and
203
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,71 @@
1
+ # @plasius/nfr
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@plasius/nfr.svg)](https://www.npmjs.com/package/@plasius/nfr)
4
+ [![Build Status](https://img.shields.io/github/actions/workflow/status/Plasius-LTD/nfr/ci.yml?branch=main&label=build&style=flat)](https://github.com/plasius/nfr/actions/workflows/ci.yml)
5
+ [![coverage](https://img.shields.io/codecov/c/github/Plasius-LTD/nfr)](https://codecov.io/gh/Plasius-LTD/nfr)
6
+ [![License](https://img.shields.io/github/license/Plasius-LTD/nfr)](./LICENSE)
7
+ [![Code of Conduct](https://img.shields.io/badge/code%20of%20conduct-yes-blue.svg)](./CODE_OF_CONDUCT.md)
8
+ [![Security Policy](https://img.shields.io/badge/security%20policy-yes-orange.svg)](./SECURITY.md)
9
+ [![Changelog](https://img.shields.io/badge/changelog-md-blue.svg)](./CHANGELOG.md)
10
+
11
+ ---
12
+
13
+ ## Overview
14
+
15
+ `@plasius/nfr` provides a scoped state management solution for React applications. It allows developers to create isolated, testable, and composable stores without introducing heavy dependencies.
16
+
17
+ ---
18
+
19
+ ## Installation
20
+
21
+ ```bash
22
+ npm install @plasius/nfr
23
+ ```
24
+
25
+ ---
26
+
27
+ ## Usage Example
28
+
29
+ ### Analytics
30
+
31
+ ```ts
32
+ import { withInteractionTracking, trackPerf, initPerformanceTracking } from "@plasius/nfr";
33
+
34
+ // Example: wrap a component with interaction tracking
35
+ const TrackedButton = withInteractionTracking("Button", (props) => {
36
+ return <button {...props}>Click me</button>;
37
+ });
38
+
39
+ // Example: initialize performance tracking
40
+
41
+ const teardown = initPerformanceTracking({
42
+ track: trackPerf, // re-use our analytics pipeline
43
+ resourceSampleRate: 0.25, // optional (default 0.25)
44
+ resourceFilter: (r) => r.initiatorType !== "img", // optional
45
+ includeNetworkInfo: true, // optional (default true)
46
+ includeMemorySnapshot: false, // optional (default false)
47
+ });
48
+
49
+ // Example: manual event
50
+ trackPerf({
51
+ category: "custom",
52
+ name: "user-action",
53
+ ts: Date.now(),
54
+ details: { action: "something-happened" },
55
+ });
56
+ ```
57
+
58
+ ---
59
+
60
+ ## Contributing
61
+
62
+ We welcome contributions! Please see [CONTRIBUTING.md](./CONTRIBUTING.md) for guidelines.
63
+
64
+ - [Code of Conduct](./CODE_OF_CONDUCT.md)
65
+ - [Contributor License Agreement](./legal/CLA.md)
66
+
67
+ ---
68
+
69
+ ## License
70
+
71
+ This project is licensed under the terms of the [Apache 2.0 license](./LICENSE).
package/dist/index.cjs ADDED
@@ -0,0 +1,362 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ initPerformanceTracking: () => initPerformanceTracking,
34
+ page: () => page,
35
+ setAnalyticsSink: () => setAnalyticsSink,
36
+ track: () => track,
37
+ trackPerf: () => trackPerf,
38
+ withInteractionTracking: () => withInteractionTracking
39
+ });
40
+ module.exports = __toCommonJS(index_exports);
41
+
42
+ // src/telemetry/analytics.ts
43
+ var import_meta = {};
44
+ var trackPerf = (e) => {
45
+ const { ts, ...rest } = e;
46
+ activeSink.track({
47
+ name: "perf",
48
+ props: rest,
49
+ ts: ts ?? Date.now()
50
+ });
51
+ };
52
+ var isProd = typeof import_meta !== "undefined" && import_meta.env?.MODE === "production" || process.env.NODE_ENV === "production";
53
+ var consoleSink = {
54
+ track: (event) => console.info("[analytics:track]", event),
55
+ page: (name, props) => console.info("[analytics:page]", { name, props })
56
+ };
57
+ var dataLayerSink = {
58
+ track: (event) => {
59
+ window.dataLayer = window.dataLayer || [];
60
+ window.dataLayer.push({
61
+ event: event.name,
62
+ ...event.props,
63
+ ts: event.ts ?? Date.now()
64
+ });
65
+ },
66
+ page: (name, props) => {
67
+ window.dataLayer = window.dataLayer || [];
68
+ window.dataLayer.push({
69
+ event: "page_view",
70
+ page: name,
71
+ ...props
72
+ });
73
+ }
74
+ };
75
+ var activeSink = isProd ? dataLayerSink : consoleSink;
76
+ var setAnalyticsSink = (sink) => {
77
+ activeSink = sink;
78
+ };
79
+ var track = (name, props) => activeSink.track({ name, props, ts: Date.now() });
80
+ var page = (name, props) => activeSink.page?.(name, props);
81
+
82
+ // src/telemetry/withInteractionTracking.tsx
83
+ var import_react = __toESM(require("react"), 1);
84
+ var import_jsx_runtime = require("react/jsx-runtime");
85
+ function withInteractionTracking(Component, { origin } = {}) {
86
+ const Wrapped = import_react.default.forwardRef(function Wrapped2(props, ref) {
87
+ const onInteractionCapture = (e) => {
88
+ const isKey = e.key !== void 0;
89
+ const isPointer = e.pointerType !== void 0;
90
+ const type = isKey ? "keydown" : isPointer ? "pointerup" : e.type;
91
+ let key;
92
+ if (isKey) {
93
+ key = e.key;
94
+ if (key !== "Enter" && key !== " ") return;
95
+ }
96
+ if (isPointer) {
97
+ const pe = e;
98
+ if (type === "pointerup" && pe.button !== 0) return;
99
+ }
100
+ const target = e.target;
101
+ const label = target?.getAttribute?.("aria-label") || target?.getAttribute?.("data-analytics-label") || target?.textContent?.trim() || target?.tagName;
102
+ track("ui.interaction", {
103
+ origin,
104
+ label,
105
+ type,
106
+ key,
107
+ pointerType: isPointer ? e.pointerType : void 0
108
+ });
109
+ };
110
+ const Comp = Component;
111
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
112
+ "div",
113
+ {
114
+ onPointerUpCapture: onInteractionCapture,
115
+ onKeyDownCapture: onInteractionCapture,
116
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Comp, { ref, ...props })
117
+ }
118
+ );
119
+ });
120
+ Wrapped.displayName = `WithInteractionTracking(${Component.displayName || Component.name || "Component"})`;
121
+ return Wrapped;
122
+ }
123
+
124
+ // src/performance/webVitals.ts
125
+ var now = () => Date.now();
126
+ var pageURL = () => typeof location !== "undefined" ? location.href : void 0;
127
+ var navType = () => {
128
+ try {
129
+ const nav = performance.getEntriesByType("navigation")[0];
130
+ return nav?.type ?? performance.navigation?.type;
131
+ } catch {
132
+ return void 0;
133
+ }
134
+ };
135
+ async function wireWebVitals(track2) {
136
+ try {
137
+ const mod = await import(
138
+ /* webpackChunkName: "web-vitals" */
139
+ "web-vitals"
140
+ );
141
+ const handlers = [
142
+ ["LCP", mod.onLCP],
143
+ ["INP", mod.onINP],
144
+ ["CLS", mod.onCLS],
145
+ ["FCP", mod.onFCP],
146
+ ["TTFB", mod.onTTFB]
147
+ ];
148
+ handlers.forEach(([name, fn]) => {
149
+ if (typeof fn === "function") {
150
+ fn((metric) => {
151
+ const { value, rating, delta, id, navigationType: nt, attribution } = metric;
152
+ track2({
153
+ category: "web-vitals",
154
+ name,
155
+ value,
156
+ rating,
157
+ delta,
158
+ id,
159
+ url: pageURL(),
160
+ navigationType: nt ?? navType(),
161
+ ts: now(),
162
+ details: attribution ? { attribution } : void 0
163
+ });
164
+ }, { reportAllChanges: true });
165
+ }
166
+ });
167
+ } catch {
168
+ }
169
+ }
170
+ function reportNavigationTiming(track2) {
171
+ try {
172
+ const nav = performance.getEntriesByType("navigation")[0];
173
+ if (!nav) return;
174
+ const base = {
175
+ category: "nav-timing",
176
+ url: pageURL(),
177
+ navigationType: nav.type,
178
+ ts: now()
179
+ };
180
+ const push = (name, value, details) => {
181
+ if (value == null || Number.isNaN(value)) return;
182
+ track2({ ...base, name, value, details });
183
+ };
184
+ push("TTFB", nav.responseStart);
185
+ push("DNS", nav.domainLookupEnd - nav.domainLookupStart);
186
+ push("TCP", nav.connectEnd - nav.connectStart);
187
+ push("TLS", nav.secureConnectionStart > 0 ? nav.connectEnd - nav.secureConnectionStart : 0);
188
+ push("Request", nav.responseStart - nav.requestStart);
189
+ push("Response", nav.responseEnd - nav.responseStart);
190
+ push("DOMInteractive", nav.domInteractive);
191
+ push("DOMComplete", nav.domComplete);
192
+ push("DOMContentLoaded", nav.domContentLoadedEventEnd);
193
+ push("LoadEvent", nav.loadEventEnd - nav.loadEventStart);
194
+ push("FirstByteToInteractive", nav.domInteractive - nav.responseStart);
195
+ } catch {
196
+ }
197
+ }
198
+ function reportPaintTimings(track2) {
199
+ try {
200
+ const paints = performance.getEntriesByType("paint");
201
+ const base = { category: "paint", url: pageURL(), navigationType: navType(), ts: now() };
202
+ for (const p of paints) {
203
+ track2({ ...base, name: p.name, value: p.startTime });
204
+ }
205
+ } catch {
206
+ }
207
+ }
208
+ function observeLongTasks(track2) {
209
+ if (!("PerformanceObserver" in window)) return () => {
210
+ };
211
+ let obs;
212
+ try {
213
+ obs = new PerformanceObserver((list) => {
214
+ for (const entry of list.getEntries()) {
215
+ const anyEntry = entry;
216
+ track2({
217
+ category: "longtask",
218
+ name: "longtask",
219
+ value: entry.duration,
220
+ ts: now(),
221
+ url: pageURL(),
222
+ details: {
223
+ startTime: entry.startTime,
224
+ duration: entry.duration,
225
+ attribution: anyEntry.attribution ?? anyEntry.attribution ?? void 0
226
+ }
227
+ });
228
+ }
229
+ });
230
+ obs.observe({ type: "longtask", buffered: true });
231
+ } catch {
232
+ }
233
+ return () => {
234
+ try {
235
+ obs?.disconnect();
236
+ } catch {
237
+ }
238
+ };
239
+ }
240
+ function observeResources(track2, sampleRate, filter) {
241
+ if (!("PerformanceObserver" in window)) return () => {
242
+ };
243
+ const shouldSample = Math.max(0, Math.min(1, sampleRate)) || 0.25;
244
+ const take = () => Math.random() < shouldSample;
245
+ let obs;
246
+ const toEvent = (e) => ({
247
+ category: "resource",
248
+ name: `resource:${e.initiatorType || "other"}`,
249
+ url: e.name,
250
+ ts: now(),
251
+ value: e.duration,
252
+ details: {
253
+ startTime: e.startTime,
254
+ transferSize: e.transferSize,
255
+ encodedBodySize: e.encodedBodySize,
256
+ decodedBodySize: e.decodedBodySize,
257
+ nextHopProtocol: e.nextHopProtocol,
258
+ initiatorType: e.initiatorType
259
+ }
260
+ });
261
+ try {
262
+ obs = new PerformanceObserver((list) => {
263
+ for (const entry of list.getEntries()) {
264
+ if (filter && !filter(entry)) continue;
265
+ if (!take()) continue;
266
+ track2(toEvent(entry));
267
+ }
268
+ });
269
+ obs.observe({ type: "resource", buffered: true });
270
+ } catch {
271
+ }
272
+ return () => {
273
+ try {
274
+ obs?.disconnect();
275
+ } catch {
276
+ }
277
+ };
278
+ }
279
+ function wireVisibility(track2) {
280
+ const onHidden = (type) => () => {
281
+ track2({ category: "visibility", name: type, ts: now(), url: pageURL() });
282
+ };
283
+ document.addEventListener("visibilitychange", () => {
284
+ if (document.visibilityState === "hidden") onHidden("hidden")();
285
+ });
286
+ window.addEventListener("pagehide", onHidden("pagehide"));
287
+ return () => {
288
+ document.removeEventListener("visibilitychange", onHidden("hidden"));
289
+ window.removeEventListener("pagehide", onHidden("pagehide"));
290
+ };
291
+ }
292
+ function snapshotNetwork(track2) {
293
+ const nav = navigator;
294
+ const c = nav?.connection || nav?.mozConnection || nav?.webkitConnection;
295
+ if (!c) return;
296
+ track2({
297
+ category: "snapshot",
298
+ name: "network-info",
299
+ ts: now(),
300
+ url: pageURL(),
301
+ details: {
302
+ effectiveType: c.effectiveType,
303
+ downlink: c.downlink,
304
+ rtt: c.rtt,
305
+ saveData: c.saveData
306
+ }
307
+ });
308
+ }
309
+ function snapshotMemory(track2) {
310
+ const mem = performance.memory;
311
+ if (!mem) return;
312
+ track2({
313
+ category: "snapshot",
314
+ name: "js-heap",
315
+ ts: now(),
316
+ url: pageURL(),
317
+ details: {
318
+ jsHeapSizeLimit: mem.jsHeapSizeLimit,
319
+ totalJSHeapSize: mem.totalJSHeapSize,
320
+ usedJSHeapSize: mem.usedJSHeapSize
321
+ }
322
+ });
323
+ }
324
+ function initPerformanceTracking(opts) {
325
+ const {
326
+ track: track2,
327
+ resourceSampleRate = 0.25,
328
+ resourceFilter,
329
+ includeNetworkInfo = true,
330
+ includeMemorySnapshot = false
331
+ } = opts;
332
+ void wireWebVitals(track2);
333
+ if (document.readyState === "complete") {
334
+ reportNavigationTiming(track2);
335
+ reportPaintTimings(track2);
336
+ } else {
337
+ window.addEventListener("load", () => {
338
+ reportNavigationTiming(track2);
339
+ reportPaintTimings(track2);
340
+ }, { once: true });
341
+ }
342
+ const offLong = observeLongTasks(track2);
343
+ const offRes = observeResources(track2, resourceSampleRate, resourceFilter);
344
+ const offVis = wireVisibility(track2);
345
+ if (includeNetworkInfo) snapshotNetwork(track2);
346
+ if (includeMemorySnapshot) snapshotMemory(track2);
347
+ return () => {
348
+ offLong();
349
+ offRes();
350
+ offVis();
351
+ };
352
+ }
353
+ // Annotate the CommonJS export names for ESM import in node:
354
+ 0 && (module.exports = {
355
+ initPerformanceTracking,
356
+ page,
357
+ setAnalyticsSink,
358
+ track,
359
+ trackPerf,
360
+ withInteractionTracking
361
+ });
362
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/telemetry/analytics.ts","../src/telemetry/withInteractionTracking.tsx","../src/performance/webVitals.ts"],"sourcesContent":["export * from \"./telemetry/index.js\";\nexport * from \"./performance/index.js\";\n","import { PerfEvent } from \"../performance/index.js\";\n\nexport type AnalyticsEvent = {\n name: string;\n props?: Record<string, unknown>;\n ts?: number;\n};\n\nexport interface AnalyticsSink {\n track: (event: AnalyticsEvent) => void;\n page?: (name: string, props?: Record<string, unknown>) => void;\n}\n\n/**\n * Send a performance event through the active analytics sink.\n * We flatten the payload so `dataLayer`-style sinks can consume it directly.\n */\nexport const trackPerf = (e: PerfEvent) => {\n // Preserve provided timestamp if present; otherwise add one in the sink (or here)\n const { ts, ...rest } = e;\n activeSink.track({\n name: \"perf\",\n props: rest,\n ts: ts ?? Date.now(),\n });\n};\n\nconst isProd =\n (typeof import.meta !== \"undefined\" &&\n (import.meta as any).env?.MODE === \"production\") ||\n process.env.NODE_ENV === \"production\";\n\n// Example sinks\nconst consoleSink: AnalyticsSink = {\n track: (event) => console.info(\"[analytics:track]\", event),\n page: (name, props) => console.info(\"[analytics:page]\", { name, props }),\n};\n\n// Replace with your real one later:\nconst dataLayerSink: AnalyticsSink = {\n track: (event) => {\n // Example: Google Tag Manager dataLayer\n (window as any).dataLayer = (window as any).dataLayer || [];\n (window as any).dataLayer.push({\n event: event.name,\n ...event.props,\n ts: event.ts ?? Date.now(),\n });\n },\n page: (name, props) => {\n (window as any).dataLayer = (window as any).dataLayer || [];\n (window as any).dataLayer.push({\n event: \"page_view\",\n page: name,\n ...props,\n });\n },\n};\n\nlet activeSink: AnalyticsSink = isProd ? dataLayerSink : consoleSink;\n\nexport const setAnalyticsSink = (sink: AnalyticsSink) => {\n activeSink = sink;\n};\n\nexport const track = (name: string, props?: Record<string, unknown>) =>\n activeSink.track({ name, props, ts: Date.now() });\n\nexport const page = (name: string, props?: Record<string, unknown>) =>\n activeSink.page?.(name, props);\n","import React from \"react\";\nimport { track } from \"./analytics.js\";\n\ntype WithInteractionOpts = {\n origin?: string; // e.g. story name\n};\n\nexport function withInteractionTracking<P extends object, R = unknown>(\n Component: React.ForwardRefExoticComponent<\n React.PropsWithoutRef<P> & React.RefAttributes<R>\n >,\n opts?: WithInteractionOpts\n): React.ForwardRefExoticComponent<\n React.PropsWithoutRef<P> & React.RefAttributes<R>\n>;\n\nexport function withInteractionTracking<P extends object>(\n Component: React.ComponentType<P>,\n opts?: WithInteractionOpts\n): React.FC<P>;\n\nexport function withInteractionTracking<P extends object, R = unknown>(\n Component:\n | React.ForwardRefExoticComponent<\n React.PropsWithoutRef<P> & React.RefAttributes<R>\n >\n | React.ComponentType<P>,\n { origin }: WithInteractionOpts = {}\n): any {\n const Wrapped = React.forwardRef<R, P>(function Wrapped(props, ref) {\n const onInteractionCapture = (\n e: React.PointerEvent<HTMLDivElement> | React.KeyboardEvent<HTMLDivElement>\n ) => {\n // Normalize event type\n const isKey = (e as React.KeyboardEvent).key !== undefined;\n const isPointer = (e as React.PointerEvent).pointerType !== undefined;\n const type = isKey ? \"keydown\" : isPointer ? \"pointerup\" : e.type;\n\n // Only track meaningful keyboard activations (Enter/Space)\n let key: string | undefined;\n if (isKey) {\n key = (e as React.KeyboardEvent).key;\n if (key !== \"Enter\" && key !== \" \") return; // ignore other keys\n }\n\n // For pointers: only primary button releases\n if (isPointer) {\n const pe = e as React.PointerEvent;\n if (type === \"pointerup\" && pe.button !== 0) return;\n }\n\n const target = e.target as HTMLElement | null;\n const label =\n target?.getAttribute?.(\"aria-label\") ||\n target?.getAttribute?.(\"data-analytics-label\") ||\n target?.textContent?.trim() ||\n target?.tagName;\n\n track(\"ui.interaction\", {\n origin,\n label,\n type,\n key,\n pointerType: isPointer ? (e as React.PointerEvent).pointerType : undefined,\n });\n };\n\n const Comp = Component as any; // Allow ref passing for both ref-aware and plain components\n return (\n <div\n onPointerUpCapture={onInteractionCapture}\n onKeyDownCapture={onInteractionCapture}\n >\n <Comp ref={ref} {...(props as any)} />\n </div>\n );\n });\n\n Wrapped.displayName = `WithInteractionTracking(${Component.displayName || Component.name || \"Component\"})`;\n return Wrapped;\n}\n","/*\n * Performance & Web Vitals tracking\n * ---------------------------------\n * A lightweight collector that wires up:\n * - Core Web Vitals (LCP, INP, CLS, FCP, TTFB) via optional dynamic import of `web-vitals`\n * - Long tasks via PerformanceObserver('longtask')\n * - Navigation timing (TTFB, DOMContentLoaded, load, etc.)\n * - Paint timings (FP, FCP fallback)\n * - Resource timings (optionally sampled)\n * - Visibility lifecycle (hidden, pagehide)\n * - Network info (downlink, rtt, effectiveType) when available\n * - Memory snapshot (JS heap) when available (Chromium only)\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport type VitalName = \"LCP\" | \"INP\" | \"CLS\" | \"FCP\" | \"TTFB\";\nexport type PerfCategory =\n | \"web-vitals\"\n | \"nav-timing\"\n | \"paint\"\n | \"resource\"\n | \"longtask\"\n | \"visibility\"\n | \"snapshot\";\n\nexport type PerfEvent = {\n category: PerfCategory;\n name: string; // e.g., \"LCP\", \"DOMContentLoaded\", \"resource:script\"\n value?: number; // ms for most; CLS is unitless\n rating?: \"good\" | \"needs-improvement\" | \"poor\";\n delta?: number; // for web-vitals deltas\n id?: string; // web-vitals id\n url?: string; // current page\n navigationType?: string; // navigate, reload, back_forward, prerender\n ts?: number; // epoch ms when measured\n details?: Record<string, any>;\n};\n\nexport type PerfTracker = (event: PerfEvent) => void;\n\nexport type InitOptions = {\n track: PerfTracker;\n /** Sample a subset of resource entries to avoid high-volume beacons */\n resourceSampleRate?: number; // 0..1, default 0.25\n /** Predicate to include a resource entry */\n resourceFilter?: (e: PerformanceResourceTiming) => boolean;\n /** Include network information (effectiveType/downlink/rtt) snapshots */\n includeNetworkInfo?: boolean;\n /** Include JS heap memory snapshot where supported */\n includeMemorySnapshot?: boolean;\n};\n\nconst now = () => Date.now();\nconst pageURL = () => (typeof location !== \"undefined\" ? location.href : undefined);\nconst navType = () => {\n try {\n const nav = performance.getEntriesByType(\"navigation\")[0] as PerformanceNavigationTiming | undefined;\n return nav?.type ?? (performance as any).navigation?.type;\n } catch {\n return undefined;\n }\n};\n\n// ---------------------------------------------------------------------------\n// Web Vitals (via optional dynamic import of `web-vitals`)\n// ---------------------------------------------------------------------------\nasync function wireWebVitals(track: PerfTracker) {\n try {\n // @ts-ignore - optional dependency; we ignore TS resolution and rely on runtime try/catch\n const mod: any = await import(/* webpackChunkName: \"web-vitals\" */ \"web-vitals\");\n const handlers: [string, (onReport: any, opts?: any) => void, any?][] = [\n [\"LCP\", mod.onLCP],\n [\"INP\", mod.onINP],\n [\"CLS\", mod.onCLS],\n [\"FCP\", mod.onFCP],\n [\"TTFB\", mod.onTTFB],\n ];\n\n handlers.forEach(([name, fn]) => {\n if (typeof fn === \"function\") {\n fn((metric: any) => {\n const { value, rating, delta, id, navigationType: nt, attribution } = metric;\n track({\n category: \"web-vitals\",\n name,\n value,\n rating,\n delta,\n id,\n url: pageURL(),\n navigationType: nt ?? navType(),\n ts: now(),\n details: attribution ? { attribution } : undefined,\n });\n }, { reportAllChanges: true });\n }\n });\n } catch {\n // `web-vitals` not available — silently skip.\n }\n}\n\n// ---------------------------------------------------------------------------\n// Navigation timing & paint timings\n// ---------------------------------------------------------------------------\nfunction reportNavigationTiming(track: PerfTracker) {\n try {\n const nav = performance.getEntriesByType(\"navigation\")[0] as PerformanceNavigationTiming | undefined;\n if (!nav) return;\n const base = {\n category: \"nav-timing\" as const,\n url: pageURL(),\n navigationType: nav.type,\n ts: now(),\n };\n const push = (name: string, value: number | undefined, details?: any) => {\n if (value == null || Number.isNaN(value)) return;\n track({ ...base, name, value, details });\n };\n\n // Common derived timings (ms)\n push(\"TTFB\", nav.responseStart);\n push(\"DNS\", nav.domainLookupEnd - nav.domainLookupStart);\n push(\"TCP\", nav.connectEnd - nav.connectStart);\n push(\"TLS\", nav.secureConnectionStart > 0 ? nav.connectEnd - nav.secureConnectionStart : 0);\n push(\"Request\", nav.responseStart - nav.requestStart);\n push(\"Response\", nav.responseEnd - nav.responseStart);\n push(\"DOMInteractive\", nav.domInteractive);\n push(\"DOMComplete\", nav.domComplete);\n push(\"DOMContentLoaded\", nav.domContentLoadedEventEnd);\n push(\"LoadEvent\", nav.loadEventEnd - nav.loadEventStart);\n push(\"FirstByteToInteractive\", nav.domInteractive - nav.responseStart);\n } catch {\n // ignore\n }\n}\n\nfunction reportPaintTimings(track: PerfTracker) {\n try {\n const paints = performance.getEntriesByType(\"paint\") as PerformanceEntry[];\n const base = { category: \"paint\" as const, url: pageURL(), navigationType: navType(), ts: now() };\n for (const p of paints) {\n track({ ...base, name: p.name, value: p.startTime });\n }\n } catch {\n // ignore\n }\n}\n\n// ---------------------------------------------------------------------------\n// Long tasks\n// ---------------------------------------------------------------------------\nfunction observeLongTasks(track: PerfTracker): () => void {\n if (!(\"PerformanceObserver\" in window)) return () => {};\n let obs: PerformanceObserver | undefined;\n try {\n obs = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n const anyEntry: any = entry as any;\n track({\n category: \"longtask\",\n name: \"longtask\",\n value: entry.duration,\n ts: now(),\n url: pageURL(),\n details: {\n startTime: entry.startTime,\n duration: entry.duration,\n attribution: anyEntry.attribution ?? anyEntry.attribution ?? undefined,\n },\n });\n }\n });\n obs.observe({ type: \"longtask\", buffered: true as any });\n } catch {\n // ignore\n }\n return () => {\n try { obs?.disconnect(); } catch {}\n };\n}\n\n// ---------------------------------------------------------------------------\n// Resource timings (sampled)\n// ---------------------------------------------------------------------------\nfunction observeResources(track: PerfTracker, sampleRate: number, filter?: (e: PerformanceResourceTiming) => boolean): () => void {\n if (!(\"PerformanceObserver\" in window)) return () => {};\n const shouldSample = (Math.max(0, Math.min(1, sampleRate)) || 0.25);\n const take = () => Math.random() < shouldSample;\n let obs: PerformanceObserver | undefined;\n\n const toEvent = (e: PerformanceResourceTiming): PerfEvent => ({\n category: \"resource\",\n name: `resource:${e.initiatorType || \"other\"}`,\n url: e.name,\n ts: now(),\n value: e.duration,\n details: {\n startTime: e.startTime,\n transferSize: (e as any).transferSize,\n encodedBodySize: (e as any).encodedBodySize,\n decodedBodySize: (e as any).decodedBodySize,\n nextHopProtocol: (e as any).nextHopProtocol,\n initiatorType: e.initiatorType,\n },\n });\n\n try {\n obs = new PerformanceObserver((list) => {\n for (const entry of list.getEntries() as PerformanceResourceTiming[]) {\n if (filter && !filter(entry)) continue;\n if (!take()) continue;\n track(toEvent(entry));\n }\n });\n obs.observe({ type: \"resource\", buffered: true as any });\n } catch {\n // ignore\n }\n return () => { try { obs?.disconnect(); } catch {} };\n}\n\n// ---------------------------------------------------------------------------\n// Visibility & lifecycle\n// ---------------------------------------------------------------------------\nfunction wireVisibility(track: PerfTracker): () => void {\n const onHidden = (type: string) => () => {\n track({ category: \"visibility\", name: type, ts: now(), url: pageURL() });\n };\n document.addEventListener(\"visibilitychange\", () => {\n if (document.visibilityState === \"hidden\") onHidden(\"hidden\")();\n });\n window.addEventListener(\"pagehide\", onHidden(\"pagehide\"));\n return () => {\n document.removeEventListener(\"visibilitychange\", onHidden(\"hidden\"));\n window.removeEventListener(\"pagehide\", onHidden(\"pagehide\"));\n };\n}\n\n// ---------------------------------------------------------------------------\n// Snapshots: Network / Memory\n// ---------------------------------------------------------------------------\nfunction snapshotNetwork(track: PerfTracker) {\n const nav: any = (navigator as any);\n const c = nav?.connection || nav?.mozConnection || nav?.webkitConnection;\n if (!c) return;\n track({\n category: \"snapshot\",\n name: \"network-info\",\n ts: now(),\n url: pageURL(),\n details: {\n effectiveType: c.effectiveType,\n downlink: c.downlink,\n rtt: c.rtt,\n saveData: c.saveData,\n },\n });\n}\n\nfunction snapshotMemory(track: PerfTracker) {\n const mem: any = (performance as any).memory;\n if (!mem) return;\n track({\n category: \"snapshot\",\n name: \"js-heap\",\n ts: now(),\n url: pageURL(),\n details: {\n jsHeapSizeLimit: mem.jsHeapSizeLimit,\n totalJSHeapSize: mem.totalJSHeapSize,\n usedJSHeapSize: mem.usedJSHeapSize,\n },\n });\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\nexport function initPerformanceTracking(opts: InitOptions): () => void {\n const {\n track,\n resourceSampleRate = 0.25,\n resourceFilter,\n includeNetworkInfo = true,\n includeMemorySnapshot = false,\n } = opts;\n\n // Web Vitals (async)\n void wireWebVitals(track);\n\n // Navigation & paints (buffered entries are available after DOM ready)\n if (document.readyState === \"complete\") {\n reportNavigationTiming(track);\n reportPaintTimings(track);\n } else {\n window.addEventListener(\"load\", () => {\n reportNavigationTiming(track);\n reportPaintTimings(track);\n }, { once: true });\n }\n\n // Observers\n const offLong = observeLongTasks(track);\n const offRes = observeResources(track, resourceSampleRate, resourceFilter);\n const offVis = wireVisibility(track);\n\n // Snapshots\n if (includeNetworkInfo) snapshotNetwork(track);\n if (includeMemorySnapshot) snapshotMemory(track);\n\n // Teardown\n return () => {\n offLong();\n offRes();\n offVis();\n };\n}\n\nexport default {\n initPerformanceTracking,\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAiBO,IAAM,YAAY,CAAC,MAAiB;AAEzC,QAAM,EAAE,IAAI,GAAG,KAAK,IAAI;AACxB,aAAW,MAAM;AAAA,IACf,MAAM;AAAA,IACN,OAAO;AAAA,IACP,IAAI,MAAM,KAAK,IAAI;AAAA,EACrB,CAAC;AACH;AAEA,IAAM,SACH,OAAO,gBAAgB,eACrB,YAAoB,KAAK,SAAS,gBACrC,QAAQ,IAAI,aAAa;AAG3B,IAAM,cAA6B;AAAA,EACjC,OAAO,CAAC,UAAU,QAAQ,KAA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MAAI,mBAAoB,iBAAgBA,MAAK;AAC7C,MAAI,sBAAuB,gBAAeA,MAAK;AAG/C,SAAO,MAAM;AACX,YAAQ;AACR,WAAO;AACP,WAAO;AAAA,EACT;AACF;","names":["React","Wrapped","track"]}
@@ -0,0 +1,55 @@
1
+ import React from 'react';
2
+
3
+ type VitalName = "LCP" | "INP" | "CLS" | "FCP" | "TTFB";
4
+ type PerfCategory = "web-vitals" | "nav-timing" | "paint" | "resource" | "longtask" | "visibility" | "snapshot";
5
+ type PerfEvent = {
6
+ category: PerfCategory;
7
+ name: string;
8
+ value?: number;
9
+ rating?: "good" | "needs-improvement" | "poor";
10
+ delta?: number;
11
+ id?: string;
12
+ url?: string;
13
+ navigationType?: string;
14
+ ts?: number;
15
+ details?: Record<string, any>;
16
+ };
17
+ type PerfTracker = (event: PerfEvent) => void;
18
+ type InitOptions = {
19
+ track: PerfTracker;
20
+ /** Sample a subset of resource entries to avoid high-volume beacons */
21
+ resourceSampleRate?: number;
22
+ /** Predicate to include a resource entry */
23
+ resourceFilter?: (e: PerformanceResourceTiming) => boolean;
24
+ /** Include network information (effectiveType/downlink/rtt) snapshots */
25
+ includeNetworkInfo?: boolean;
26
+ /** Include JS heap memory snapshot where supported */
27
+ includeMemorySnapshot?: boolean;
28
+ };
29
+ declare function initPerformanceTracking(opts: InitOptions): () => void;
30
+
31
+ type AnalyticsEvent = {
32
+ name: string;
33
+ props?: Record<string, unknown>;
34
+ ts?: number;
35
+ };
36
+ interface AnalyticsSink {
37
+ track: (event: AnalyticsEvent) => void;
38
+ page?: (name: string, props?: Record<string, unknown>) => void;
39
+ }
40
+ /**
41
+ * Send a performance event through the active analytics sink.
42
+ * We flatten the payload so `dataLayer`-style sinks can consume it directly.
43
+ */
44
+ declare const trackPerf: (e: PerfEvent) => void;
45
+ declare const setAnalyticsSink: (sink: AnalyticsSink) => void;
46
+ declare const track: (name: string, props?: Record<string, unknown>) => void;
47
+ declare const page: (name: string, props?: Record<string, unknown>) => void | undefined;
48
+
49
+ type WithInteractionOpts = {
50
+ origin?: string;
51
+ };
52
+ declare function withInteractionTracking<P extends object, R = unknown>(Component: React.ForwardRefExoticComponent<React.PropsWithoutRef<P> & React.RefAttributes<R>>, opts?: WithInteractionOpts): React.ForwardRefExoticComponent<React.PropsWithoutRef<P> & React.RefAttributes<R>>;
53
+ declare function withInteractionTracking<P extends object>(Component: React.ComponentType<P>, opts?: WithInteractionOpts): React.FC<P>;
54
+
55
+ export { type AnalyticsEvent, type AnalyticsSink, type InitOptions, type PerfCategory, type PerfEvent, type PerfTracker, type VitalName, initPerformanceTracking, page, setAnalyticsSink, track, trackPerf, withInteractionTracking };
@@ -0,0 +1,55 @@
1
+ import React from 'react';
2
+
3
+ type VitalName = "LCP" | "INP" | "CLS" | "FCP" | "TTFB";
4
+ type PerfCategory = "web-vitals" | "nav-timing" | "paint" | "resource" | "longtask" | "visibility" | "snapshot";
5
+ type PerfEvent = {
6
+ category: PerfCategory;
7
+ name: string;
8
+ value?: number;
9
+ rating?: "good" | "needs-improvement" | "poor";
10
+ delta?: number;
11
+ id?: string;
12
+ url?: string;
13
+ navigationType?: string;
14
+ ts?: number;
15
+ details?: Record<string, any>;
16
+ };
17
+ type PerfTracker = (event: PerfEvent) => void;
18
+ type InitOptions = {
19
+ track: PerfTracker;
20
+ /** Sample a subset of resource entries to avoid high-volume beacons */
21
+ resourceSampleRate?: number;
22
+ /** Predicate to include a resource entry */
23
+ resourceFilter?: (e: PerformanceResourceTiming) => boolean;
24
+ /** Include network information (effectiveType/downlink/rtt) snapshots */
25
+ includeNetworkInfo?: boolean;
26
+ /** Include JS heap memory snapshot where supported */
27
+ includeMemorySnapshot?: boolean;
28
+ };
29
+ declare function initPerformanceTracking(opts: InitOptions): () => void;
30
+
31
+ type AnalyticsEvent = {
32
+ name: string;
33
+ props?: Record<string, unknown>;
34
+ ts?: number;
35
+ };
36
+ interface AnalyticsSink {
37
+ track: (event: AnalyticsEvent) => void;
38
+ page?: (name: string, props?: Record<string, unknown>) => void;
39
+ }
40
+ /**
41
+ * Send a performance event through the active analytics sink.
42
+ * We flatten the payload so `dataLayer`-style sinks can consume it directly.
43
+ */
44
+ declare const trackPerf: (e: PerfEvent) => void;
45
+ declare const setAnalyticsSink: (sink: AnalyticsSink) => void;
46
+ declare const track: (name: string, props?: Record<string, unknown>) => void;
47
+ declare const page: (name: string, props?: Record<string, unknown>) => void | undefined;
48
+
49
+ type WithInteractionOpts = {
50
+ origin?: string;
51
+ };
52
+ declare function withInteractionTracking<P extends object, R = unknown>(Component: React.ForwardRefExoticComponent<React.PropsWithoutRef<P> & React.RefAttributes<R>>, opts?: WithInteractionOpts): React.ForwardRefExoticComponent<React.PropsWithoutRef<P> & React.RefAttributes<R>>;
53
+ declare function withInteractionTracking<P extends object>(Component: React.ComponentType<P>, opts?: WithInteractionOpts): React.FC<P>;
54
+
55
+ export { type AnalyticsEvent, type AnalyticsSink, type InitOptions, type PerfCategory, type PerfEvent, type PerfTracker, type VitalName, initPerformanceTracking, page, setAnalyticsSink, track, trackPerf, withInteractionTracking };
package/dist/index.js ADDED
@@ -0,0 +1,319 @@
1
+ // src/telemetry/analytics.ts
2
+ var trackPerf = (e) => {
3
+ const { ts, ...rest } = e;
4
+ activeSink.track({
5
+ name: "perf",
6
+ props: rest,
7
+ ts: ts ?? Date.now()
8
+ });
9
+ };
10
+ var isProd = typeof import.meta !== "undefined" && import.meta.env?.MODE === "production" || process.env.NODE_ENV === "production";
11
+ var consoleSink = {
12
+ track: (event) => console.info("[analytics:track]", event),
13
+ page: (name, props) => console.info("[analytics:page]", { name, props })
14
+ };
15
+ var dataLayerSink = {
16
+ track: (event) => {
17
+ window.dataLayer = window.dataLayer || [];
18
+ window.dataLayer.push({
19
+ event: event.name,
20
+ ...event.props,
21
+ ts: event.ts ?? Date.now()
22
+ });
23
+ },
24
+ page: (name, props) => {
25
+ window.dataLayer = window.dataLayer || [];
26
+ window.dataLayer.push({
27
+ event: "page_view",
28
+ page: name,
29
+ ...props
30
+ });
31
+ }
32
+ };
33
+ var activeSink = isProd ? dataLayerSink : consoleSink;
34
+ var setAnalyticsSink = (sink) => {
35
+ activeSink = sink;
36
+ };
37
+ var track = (name, props) => activeSink.track({ name, props, ts: Date.now() });
38
+ var page = (name, props) => activeSink.page?.(name, props);
39
+
40
+ // src/telemetry/withInteractionTracking.tsx
41
+ import React from "react";
42
+ import { jsx } from "react/jsx-runtime";
43
+ function withInteractionTracking(Component, { origin } = {}) {
44
+ const Wrapped = React.forwardRef(function Wrapped2(props, ref) {
45
+ const onInteractionCapture = (e) => {
46
+ const isKey = e.key !== void 0;
47
+ const isPointer = e.pointerType !== void 0;
48
+ const type = isKey ? "keydown" : isPointer ? "pointerup" : e.type;
49
+ let key;
50
+ if (isKey) {
51
+ key = e.key;
52
+ if (key !== "Enter" && key !== " ") return;
53
+ }
54
+ if (isPointer) {
55
+ const pe = e;
56
+ if (type === "pointerup" && pe.button !== 0) return;
57
+ }
58
+ const target = e.target;
59
+ const label = target?.getAttribute?.("aria-label") || target?.getAttribute?.("data-analytics-label") || target?.textContent?.trim() || target?.tagName;
60
+ track("ui.interaction", {
61
+ origin,
62
+ label,
63
+ type,
64
+ key,
65
+ pointerType: isPointer ? e.pointerType : void 0
66
+ });
67
+ };
68
+ const Comp = Component;
69
+ return /* @__PURE__ */ jsx(
70
+ "div",
71
+ {
72
+ onPointerUpCapture: onInteractionCapture,
73
+ onKeyDownCapture: onInteractionCapture,
74
+ children: /* @__PURE__ */ jsx(Comp, { ref, ...props })
75
+ }
76
+ );
77
+ });
78
+ Wrapped.displayName = `WithInteractionTracking(${Component.displayName || Component.name || "Component"})`;
79
+ return Wrapped;
80
+ }
81
+
82
+ // src/performance/webVitals.ts
83
+ var now = () => Date.now();
84
+ var pageURL = () => typeof location !== "undefined" ? location.href : void 0;
85
+ var navType = () => {
86
+ try {
87
+ const nav = performance.getEntriesByType("navigation")[0];
88
+ return nav?.type ?? performance.navigation?.type;
89
+ } catch {
90
+ return void 0;
91
+ }
92
+ };
93
+ async function wireWebVitals(track2) {
94
+ try {
95
+ const mod = await import(
96
+ /* webpackChunkName: "web-vitals" */
97
+ "web-vitals"
98
+ );
99
+ const handlers = [
100
+ ["LCP", mod.onLCP],
101
+ ["INP", mod.onINP],
102
+ ["CLS", mod.onCLS],
103
+ ["FCP", mod.onFCP],
104
+ ["TTFB", mod.onTTFB]
105
+ ];
106
+ handlers.forEach(([name, fn]) => {
107
+ if (typeof fn === "function") {
108
+ fn((metric) => {
109
+ const { value, rating, delta, id, navigationType: nt, attribution } = metric;
110
+ track2({
111
+ category: "web-vitals",
112
+ name,
113
+ value,
114
+ rating,
115
+ delta,
116
+ id,
117
+ url: pageURL(),
118
+ navigationType: nt ?? navType(),
119
+ ts: now(),
120
+ details: attribution ? { attribution } : void 0
121
+ });
122
+ }, { reportAllChanges: true });
123
+ }
124
+ });
125
+ } catch {
126
+ }
127
+ }
128
+ function reportNavigationTiming(track2) {
129
+ try {
130
+ const nav = performance.getEntriesByType("navigation")[0];
131
+ if (!nav) return;
132
+ const base = {
133
+ category: "nav-timing",
134
+ url: pageURL(),
135
+ navigationType: nav.type,
136
+ ts: now()
137
+ };
138
+ const push = (name, value, details) => {
139
+ if (value == null || Number.isNaN(value)) return;
140
+ track2({ ...base, name, value, details });
141
+ };
142
+ push("TTFB", nav.responseStart);
143
+ push("DNS", nav.domainLookupEnd - nav.domainLookupStart);
144
+ push("TCP", nav.connectEnd - nav.connectStart);
145
+ push("TLS", nav.secureConnectionStart > 0 ? nav.connectEnd - nav.secureConnectionStart : 0);
146
+ push("Request", nav.responseStart - nav.requestStart);
147
+ push("Response", nav.responseEnd - nav.responseStart);
148
+ push("DOMInteractive", nav.domInteractive);
149
+ push("DOMComplete", nav.domComplete);
150
+ push("DOMContentLoaded", nav.domContentLoadedEventEnd);
151
+ push("LoadEvent", nav.loadEventEnd - nav.loadEventStart);
152
+ push("FirstByteToInteractive", nav.domInteractive - nav.responseStart);
153
+ } catch {
154
+ }
155
+ }
156
+ function reportPaintTimings(track2) {
157
+ try {
158
+ const paints = performance.getEntriesByType("paint");
159
+ const base = { category: "paint", url: pageURL(), navigationType: navType(), ts: now() };
160
+ for (const p of paints) {
161
+ track2({ ...base, name: p.name, value: p.startTime });
162
+ }
163
+ } catch {
164
+ }
165
+ }
166
+ function observeLongTasks(track2) {
167
+ if (!("PerformanceObserver" in window)) return () => {
168
+ };
169
+ let obs;
170
+ try {
171
+ obs = new PerformanceObserver((list) => {
172
+ for (const entry of list.getEntries()) {
173
+ const anyEntry = entry;
174
+ track2({
175
+ category: "longtask",
176
+ name: "longtask",
177
+ value: entry.duration,
178
+ ts: now(),
179
+ url: pageURL(),
180
+ details: {
181
+ startTime: entry.startTime,
182
+ duration: entry.duration,
183
+ attribution: anyEntry.attribution ?? anyEntry.attribution ?? void 0
184
+ }
185
+ });
186
+ }
187
+ });
188
+ obs.observe({ type: "longtask", buffered: true });
189
+ } catch {
190
+ }
191
+ return () => {
192
+ try {
193
+ obs?.disconnect();
194
+ } catch {
195
+ }
196
+ };
197
+ }
198
+ function observeResources(track2, sampleRate, filter) {
199
+ if (!("PerformanceObserver" in window)) return () => {
200
+ };
201
+ const shouldSample = Math.max(0, Math.min(1, sampleRate)) || 0.25;
202
+ const take = () => Math.random() < shouldSample;
203
+ let obs;
204
+ const toEvent = (e) => ({
205
+ category: "resource",
206
+ name: `resource:${e.initiatorType || "other"}`,
207
+ url: e.name,
208
+ ts: now(),
209
+ value: e.duration,
210
+ details: {
211
+ startTime: e.startTime,
212
+ transferSize: e.transferSize,
213
+ encodedBodySize: e.encodedBodySize,
214
+ decodedBodySize: e.decodedBodySize,
215
+ nextHopProtocol: e.nextHopProtocol,
216
+ initiatorType: e.initiatorType
217
+ }
218
+ });
219
+ try {
220
+ obs = new PerformanceObserver((list) => {
221
+ for (const entry of list.getEntries()) {
222
+ if (filter && !filter(entry)) continue;
223
+ if (!take()) continue;
224
+ track2(toEvent(entry));
225
+ }
226
+ });
227
+ obs.observe({ type: "resource", buffered: true });
228
+ } catch {
229
+ }
230
+ return () => {
231
+ try {
232
+ obs?.disconnect();
233
+ } catch {
234
+ }
235
+ };
236
+ }
237
+ function wireVisibility(track2) {
238
+ const onHidden = (type) => () => {
239
+ track2({ category: "visibility", name: type, ts: now(), url: pageURL() });
240
+ };
241
+ document.addEventListener("visibilitychange", () => {
242
+ if (document.visibilityState === "hidden") onHidden("hidden")();
243
+ });
244
+ window.addEventListener("pagehide", onHidden("pagehide"));
245
+ return () => {
246
+ document.removeEventListener("visibilitychange", onHidden("hidden"));
247
+ window.removeEventListener("pagehide", onHidden("pagehide"));
248
+ };
249
+ }
250
+ function snapshotNetwork(track2) {
251
+ const nav = navigator;
252
+ const c = nav?.connection || nav?.mozConnection || nav?.webkitConnection;
253
+ if (!c) return;
254
+ track2({
255
+ category: "snapshot",
256
+ name: "network-info",
257
+ ts: now(),
258
+ url: pageURL(),
259
+ details: {
260
+ effectiveType: c.effectiveType,
261
+ downlink: c.downlink,
262
+ rtt: c.rtt,
263
+ saveData: c.saveData
264
+ }
265
+ });
266
+ }
267
+ function snapshotMemory(track2) {
268
+ const mem = performance.memory;
269
+ if (!mem) return;
270
+ track2({
271
+ category: "snapshot",
272
+ name: "js-heap",
273
+ ts: now(),
274
+ url: pageURL(),
275
+ details: {
276
+ jsHeapSizeLimit: mem.jsHeapSizeLimit,
277
+ totalJSHeapSize: mem.totalJSHeapSize,
278
+ usedJSHeapSize: mem.usedJSHeapSize
279
+ }
280
+ });
281
+ }
282
+ function initPerformanceTracking(opts) {
283
+ const {
284
+ track: track2,
285
+ resourceSampleRate = 0.25,
286
+ resourceFilter,
287
+ includeNetworkInfo = true,
288
+ includeMemorySnapshot = false
289
+ } = opts;
290
+ void wireWebVitals(track2);
291
+ if (document.readyState === "complete") {
292
+ reportNavigationTiming(track2);
293
+ reportPaintTimings(track2);
294
+ } else {
295
+ window.addEventListener("load", () => {
296
+ reportNavigationTiming(track2);
297
+ reportPaintTimings(track2);
298
+ }, { once: true });
299
+ }
300
+ const offLong = observeLongTasks(track2);
301
+ const offRes = observeResources(track2, resourceSampleRate, resourceFilter);
302
+ const offVis = wireVisibility(track2);
303
+ if (includeNetworkInfo) snapshotNetwork(track2);
304
+ if (includeMemorySnapshot) snapshotMemory(track2);
305
+ return () => {
306
+ offLong();
307
+ offRes();
308
+ offVis();
309
+ };
310
+ }
311
+ export {
312
+ initPerformanceTracking,
313
+ page,
314
+ setAnalyticsSink,
315
+ track,
316
+ trackPerf,
317
+ withInteractionTracking
318
+ };
319
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/telemetry/analytics.ts","../src/telemetry/withInteractionTracking.tsx","../src/performance/webVitals.ts"],"sourcesContent":["import { PerfEvent } from \"../performance/index.js\";\n\nexport type AnalyticsEvent = {\n name: string;\n props?: Record<string, unknown>;\n ts?: number;\n};\n\nexport interface AnalyticsSink {\n track: (event: AnalyticsEvent) => void;\n page?: (name: string, props?: Record<string, unknown>) => void;\n}\n\n/**\n * Send a performance event through the active analytics sink.\n * We flatten the payload so `dataLayer`-style sinks can consume it directly.\n */\nexport const trackPerf = (e: PerfEvent) => {\n // Preserve provided timestamp if present; otherwise add one in the sink (or here)\n const { ts, ...rest } = e;\n activeSink.track({\n name: \"perf\",\n props: rest,\n ts: ts ?? Date.now(),\n });\n};\n\nconst isProd =\n (typeof import.meta !== \"undefined\" &&\n (import.meta as any).env?.MODE === \"production\") ||\n process.env.NODE_ENV === \"production\";\n\n// Example sinks\nconst consoleSink: AnalyticsSink = {\n track: (event) => console.info(\"[analytics:track]\", event),\n page: (name, props) => console.info(\"[analytics:page]\", { name, props }),\n};\n\n// Replace with your real one later:\nconst dataLayerSink: AnalyticsSink = {\n track: (event) => {\n // Example: Google Tag Manager dataLayer\n (window as any).dataLayer = (window as any).dataLayer || [];\n (window as any).dataLayer.push({\n event: event.name,\n ...event.props,\n ts: event.ts ?? Date.now(),\n });\n },\n page: (name, props) => {\n (window as any).dataLayer = (window as any).dataLayer || [];\n (window as any).dataLayer.push({\n event: \"page_view\",\n page: name,\n ...props,\n });\n },\n};\n\nlet activeSink: AnalyticsSink = isProd ? dataLayerSink : consoleSink;\n\nexport const setAnalyticsSink = (sink: AnalyticsSink) => {\n activeSink = sink;\n};\n\nexport const track = (name: string, props?: Record<string, unknown>) =>\n activeSink.track({ name, props, ts: Date.now() });\n\nexport const page = (name: string, props?: Record<string, unknown>) =>\n activeSink.page?.(name, props);\n","import React from \"react\";\nimport { track } from \"./analytics.js\";\n\ntype WithInteractionOpts = {\n origin?: string; // e.g. story name\n};\n\nexport function withInteractionTracking<P extends object, R = unknown>(\n Component: React.ForwardRefExoticComponent<\n React.PropsWithoutRef<P> & React.RefAttributes<R>\n >,\n opts?: WithInteractionOpts\n): React.ForwardRefExoticComponent<\n React.PropsWithoutRef<P> & React.RefAttributes<R>\n>;\n\nexport function withInteractionTracking<P extends object>(\n Component: React.ComponentType<P>,\n opts?: WithInteractionOpts\n): React.FC<P>;\n\nexport function withInteractionTracking<P extends object, R = unknown>(\n Component:\n | React.ForwardRefExoticComponent<\n React.PropsWithoutRef<P> & React.RefAttributes<R>\n >\n | React.ComponentType<P>,\n { origin }: WithInteractionOpts = {}\n): any {\n const Wrapped = React.forwardRef<R, P>(function Wrapped(props, ref) {\n const onInteractionCapture = (\n e: React.PointerEvent<HTMLDivElement> | React.KeyboardEvent<HTMLDivElement>\n ) => {\n // Normalize event type\n const isKey = (e as React.KeyboardEvent).key !== undefined;\n const isPointer = (e as React.PointerEvent).pointerType !== undefined;\n const type = isKey ? \"keydown\" : isPointer ? \"pointerup\" : e.type;\n\n // Only track meaningful keyboard activations (Enter/Space)\n let key: string | undefined;\n if (isKey) {\n key = (e as React.KeyboardEvent).key;\n if (key !== \"Enter\" && key !== \" \") return; // ignore other keys\n }\n\n // For pointers: only primary button releases\n if (isPointer) {\n const pe = e as React.PointerEvent;\n if (type === \"pointerup\" && pe.button !== 0) return;\n }\n\n const target = e.target as HTMLElement | null;\n const label =\n target?.getAttribute?.(\"aria-label\") ||\n target?.getAttribute?.(\"data-analytics-label\") ||\n target?.textContent?.trim() ||\n target?.tagName;\n\n track(\"ui.interaction\", {\n origin,\n label,\n type,\n key,\n pointerType: isPointer ? (e as React.PointerEvent).pointerType : undefined,\n });\n };\n\n const Comp = Component as any; // Allow ref passing for both ref-aware and plain components\n return (\n <div\n onPointerUpCapture={onInteractionCapture}\n onKeyDownCapture={onInteractionCapture}\n >\n <Comp ref={ref} {...(props as any)} />\n </div>\n );\n });\n\n Wrapped.displayName = `WithInteractionTracking(${Component.displayName || Component.name || \"Component\"})`;\n return Wrapped;\n}\n","/*\n * Performance & Web Vitals tracking\n * ---------------------------------\n * A lightweight collector that wires up:\n * - Core Web Vitals (LCP, INP, CLS, FCP, TTFB) via optional dynamic import of `web-vitals`\n * - Long tasks via PerformanceObserver('longtask')\n * - Navigation timing (TTFB, DOMContentLoaded, load, etc.)\n * - Paint timings (FP, FCP fallback)\n * - Resource timings (optionally sampled)\n * - Visibility lifecycle (hidden, pagehide)\n * - Network info (downlink, rtt, effectiveType) when available\n * - Memory snapshot (JS heap) when available (Chromium only)\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport type VitalName = \"LCP\" | \"INP\" | \"CLS\" | \"FCP\" | \"TTFB\";\nexport type PerfCategory =\n | \"web-vitals\"\n | \"nav-timing\"\n | \"paint\"\n | \"resource\"\n | \"longtask\"\n | \"visibility\"\n | \"snapshot\";\n\nexport type PerfEvent = {\n category: PerfCategory;\n name: string; // e.g., \"LCP\", \"DOMContentLoaded\", \"resource:script\"\n value?: number; // ms for most; CLS is unitless\n rating?: \"good\" | \"needs-improvement\" | \"poor\";\n delta?: number; // for web-vitals deltas\n id?: string; // web-vitals id\n url?: string; // current page\n navigationType?: string; // navigate, reload, back_forward, prerender\n ts?: number; // epoch ms when measured\n details?: Record<string, any>;\n};\n\nexport type PerfTracker = (event: PerfEvent) => void;\n\nexport type InitOptions = {\n track: PerfTracker;\n /** Sample a subset of resource entries to avoid high-volume beacons */\n resourceSampleRate?: number; // 0..1, default 0.25\n /** Predicate to include a resource entry */\n resourceFilter?: (e: PerformanceResourceTiming) => boolean;\n /** Include network information (effectiveType/downlink/rtt) snapshots */\n includeNetworkInfo?: boolean;\n /** Include JS heap memory snapshot where supported */\n includeMemorySnapshot?: boolean;\n};\n\nconst now = () => Date.now();\nconst pageURL = () => (typeof location !== \"undefined\" ? location.href : undefined);\nconst navType = () => {\n try {\n const nav = performance.getEntriesByType(\"navigation\")[0] as PerformanceNavigationTiming | undefined;\n return nav?.type ?? (performance as any).navigation?.type;\n } catch {\n return undefined;\n }\n};\n\n// ---------------------------------------------------------------------------\n// Web Vitals (via optional dynamic import of `web-vitals`)\n// ---------------------------------------------------------------------------\nasync function wireWebVitals(track: PerfTracker) {\n try {\n // @ts-ignore - optional dependency; we ignore TS resolution and rely on runtime try/catch\n const mod: any = await import(/* webpackChunkName: \"web-vitals\" */ \"web-vitals\");\n const handlers: [string, (onReport: any, opts?: any) => void, any?][] = [\n [\"LCP\", mod.onLCP],\n [\"INP\", mod.onINP],\n [\"CLS\", mod.onCLS],\n [\"FCP\", mod.onFCP],\n [\"TTFB\", mod.onTTFB],\n ];\n\n handlers.forEach(([name, fn]) => {\n if (typeof fn === \"function\") {\n fn((metric: any) => {\n const { value, rating, delta, id, navigationType: nt, attribution } = metric;\n track({\n category: \"web-vitals\",\n name,\n value,\n rating,\n delta,\n id,\n url: pageURL(),\n navigationType: nt ?? navType(),\n ts: now(),\n details: attribution ? { attribution } : undefined,\n });\n }, { reportAllChanges: true });\n }\n });\n } catch {\n // `web-vitals` not available — silently skip.\n }\n}\n\n// ---------------------------------------------------------------------------\n// Navigation timing & paint timings\n// ---------------------------------------------------------------------------\nfunction reportNavigationTiming(track: PerfTracker) {\n try {\n const nav = performance.getEntriesByType(\"navigation\")[0] as PerformanceNavigationTiming | undefined;\n if (!nav) return;\n const base = {\n category: \"nav-timing\" as const,\n url: pageURL(),\n navigationType: nav.type,\n ts: now(),\n };\n const push = (name: string, value: number | undefined, details?: any) => {\n if (value == null || Number.isNaN(value)) return;\n track({ ...base, name, value, details });\n };\n\n // Common derived timings (ms)\n push(\"TTFB\", nav.responseStart);\n push(\"DNS\", nav.domainLookupEnd - nav.domainLookupStart);\n push(\"TCP\", nav.connectEnd - nav.connectStart);\n push(\"TLS\", nav.secureConnectionStart > 0 ? nav.connectEnd - nav.secureConnectionStart : 0);\n push(\"Request\", nav.responseStart - nav.requestStart);\n push(\"Response\", nav.responseEnd - nav.responseStart);\n push(\"DOMInteractive\", nav.domInteractive);\n push(\"DOMComplete\", nav.domComplete);\n push(\"DOMContentLoaded\", nav.domContentLoadedEventEnd);\n push(\"LoadEvent\", nav.loadEventEnd - nav.loadEventStart);\n push(\"FirstByteToInteractive\", nav.domInteractive - nav.responseStart);\n } catch {\n // ignore\n }\n}\n\nfunction reportPaintTimings(track: PerfTracker) {\n try {\n const paints = performance.getEntriesByType(\"paint\") as PerformanceEntry[];\n const base = { category: \"paint\" as const, url: pageURL(), navigationType: navType(), ts: now() };\n for (const p of paints) {\n track({ ...base, name: p.name, value: p.startTime });\n }\n } catch {\n // ignore\n }\n}\n\n// ---------------------------------------------------------------------------\n// Long tasks\n// ---------------------------------------------------------------------------\nfunction observeLongTasks(track: PerfTracker): () => void {\n if (!(\"PerformanceObserver\" in window)) return () => {};\n let obs: PerformanceObserver | undefined;\n try {\n obs = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n const anyEntry: any = entry as any;\n track({\n category: \"longtask\",\n name: \"longtask\",\n value: entry.duration,\n ts: now(),\n url: pageURL(),\n details: {\n startTime: entry.startTime,\n duration: entry.duration,\n attribution: anyEntry.attribution ?? anyEntry.attribution ?? undefined,\n },\n });\n }\n });\n obs.observe({ type: \"longtask\", buffered: true as any });\n } catch {\n // ignore\n }\n return () => {\n try { obs?.disconnect(); } catch {}\n };\n}\n\n// ---------------------------------------------------------------------------\n// Resource timings (sampled)\n// ---------------------------------------------------------------------------\nfunction observeResources(track: PerfTracker, sampleRate: number, filter?: (e: PerformanceResourceTiming) => boolean): () => void {\n if (!(\"PerformanceObserver\" in window)) return () => {};\n const shouldSample = (Math.max(0, Math.min(1, sampleRate)) || 0.25);\n const take = () => Math.random() < shouldSample;\n let obs: PerformanceObserver | undefined;\n\n const toEvent = (e: PerformanceResourceTiming): PerfEvent => ({\n category: \"resource\",\n name: `resource:${e.initiatorType || \"other\"}`,\n url: e.name,\n ts: now(),\n value: e.duration,\n details: {\n startTime: e.startTime,\n transferSize: (e as any).transferSize,\n encodedBodySize: (e as any).encodedBodySize,\n decodedBodySize: (e as any).decodedBodySize,\n nextHopProtocol: (e as any).nextHopProtocol,\n initiatorType: e.initiatorType,\n },\n });\n\n try {\n obs = new PerformanceObserver((list) => {\n for (const entry of list.getEntries() as PerformanceResourceTiming[]) {\n if (filter && !filter(entry)) continue;\n if (!take()) continue;\n track(toEvent(entry));\n }\n });\n obs.observe({ type: \"resource\", buffered: true as any });\n } catch {\n // ignore\n }\n return () => { try { obs?.disconnect(); } catch {} };\n}\n\n// ---------------------------------------------------------------------------\n// Visibility & lifecycle\n// ---------------------------------------------------------------------------\nfunction wireVisibility(track: PerfTracker): () => void {\n const onHidden = (type: string) => () => {\n track({ category: \"visibility\", name: type, ts: now(), url: pageURL() });\n };\n document.addEventListener(\"visibilitychange\", () => {\n if (document.visibilityState === \"hidden\") onHidden(\"hidden\")();\n });\n window.addEventListener(\"pagehide\", onHidden(\"pagehide\"));\n return () => {\n document.removeEventListener(\"visibilitychange\", onHidden(\"hidden\"));\n window.removeEventListener(\"pagehide\", onHidden(\"pagehide\"));\n };\n}\n\n// ---------------------------------------------------------------------------\n// Snapshots: Network / Memory\n// ---------------------------------------------------------------------------\nfunction snapshotNetwork(track: PerfTracker) {\n const nav: any = (navigator as any);\n const c = nav?.connection || nav?.mozConnection || nav?.webkitConnection;\n if (!c) return;\n track({\n category: \"snapshot\",\n name: \"network-info\",\n ts: now(),\n url: pageURL(),\n details: {\n effectiveType: c.effectiveType,\n downlink: c.downlink,\n rtt: c.rtt,\n saveData: c.saveData,\n },\n });\n}\n\nfunction snapshotMemory(track: PerfTracker) {\n const mem: any = (performance as any).memory;\n if (!mem) return;\n track({\n category: \"snapshot\",\n name: \"js-heap\",\n ts: now(),\n url: pageURL(),\n details: {\n jsHeapSizeLimit: mem.jsHeapSizeLimit,\n totalJSHeapSize: mem.totalJSHeapSize,\n usedJSHeapSize: mem.usedJSHeapSize,\n },\n });\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\nexport function initPerformanceTracking(opts: InitOptions): () => void {\n const {\n track,\n resourceSampleRate = 0.25,\n resourceFilter,\n includeNetworkInfo = true,\n includeMemorySnapshot = false,\n } = opts;\n\n // Web Vitals (async)\n void wireWebVitals(track);\n\n // Navigation & paints (buffered entries are available after DOM ready)\n if (document.readyState === \"complete\") {\n reportNavigationTiming(track);\n reportPaintTimings(track);\n } else {\n window.addEventListener(\"load\", () => {\n reportNavigationTiming(track);\n reportPaintTimings(track);\n }, { once: true });\n }\n\n // Observers\n const offLong = observeLongTasks(track);\n const offRes = observeResources(track, resourceSampleRate, resourceFilter);\n const offVis = wireVisibility(track);\n\n // Snapshots\n if (includeNetworkInfo) snapshotNetwork(track);\n if (includeMemorySnapshot) snapshotMemory(track);\n\n // Teardown\n return () => {\n offLong();\n offRes();\n offVis();\n };\n}\n\nexport default {\n initPerformanceTracking,\n};\n"],"mappings":";AAiBO,IAAM,YAAY,CAAC,MAAiB;AAEzC,QAAM,EAAE,IAAI,GAAG,KAAK,IAAI;AACxB,aAAW,MAAM;AAAA,IACf,MAAM;AAAA,IACN,OAAO;AAAA,IACP,IAAI,MAAM,KAAK,IAAI;AAAA,EACrB,CAAC;AACH;AAEA,IAAM,SACH,OAAO,gBAAgB,eACrB,YAAoB,KAAK,SAAS,gBACrC,QAAQ,IAAI,aAAa;AAG3B,IAAM,cAA6B;AAAA,EACjC,OAAO,CAAC,UAA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K;AAGnC,MAAI,mBAAoB,iBAAgBA,MAAK;AAC7C,MAAI,sBAAuB,gBAAeA,MAAK;AAG/C,SAAO,MAAM;AACX,YAAQ;AACR,WAAO;AACP,WAAO;AAAA,EACT;AACF;","names":["Wrapped","track"]}
package/package.json ADDED
@@ -0,0 +1,65 @@
1
+ {
2
+ "name": "@plasius/nfr",
3
+ "version": "1.0.0",
4
+ "description": "a small, typed Non-Functional-Requirement (NFR) framework that cleanly adapts to different cloud vendors (GA4, PostHog, Azure Application Insights, etc.) and different concerns (analytics/events, metrics, tracing, logs, feature flags, performance).",
5
+ "homepage": "https://github.com/Plasius-LTD/nfr#readme",
6
+ "bugs": {
7
+ "url": "https://github.com/Plasius-LTD/nfr/issues"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/Plasius-LTD/nfr.git"
12
+ },
13
+ "license": "Apache-2.0",
14
+ "author": "Plasius LTD",
15
+ "type": "module",
16
+ "sideEffects": false,
17
+ "private": false,
18
+ "files": [
19
+ "dist"
20
+ ],
21
+ "exports": {
22
+ ".": {
23
+ "types": "./dist/index.d.ts",
24
+ "import": "./dist/index.js",
25
+ "require": "./dist/index.cjs"
26
+ }
27
+ },
28
+ "scripts": {
29
+ "build": "tsup",
30
+ "test:watch": "vitest",
31
+ "lint": "eslint .",
32
+ "prepare": "npm run build",
33
+ "clean": "rimraf dist",
34
+ "test": "vitest run --environment jsdom"
35
+ },
36
+ "devDependencies": {
37
+ "@testing-library/jest-dom": "^6.8.0",
38
+ "@testing-library/react": "^16.3.0",
39
+ "@types/node": "^24.5.2",
40
+ "@types/react": "^19.1.13",
41
+ "@typescript-eslint/eslint-plugin": "^8.44.0",
42
+ "@typescript-eslint/parser": "^8.44.0",
43
+ "@vitest/coverage-v8": "^3.2.4",
44
+ "eslint": "^9.36.0",
45
+ "eslint-config-prettier": "^10.1.8",
46
+ "eslint-plugin-react": "^7.37.5",
47
+ "eslint-plugin-react-hooks": "^5.2.0",
48
+ "jsdom": "^27.0.0",
49
+ "prettier": "^3.6.2",
50
+ "react": "^19",
51
+ "tsup": "^8.5.0",
52
+ "tsx": "^4.20.5",
53
+ "typescript": "^5.9.2",
54
+ "vitest": "^3.2.4"
55
+ },
56
+ "peerDependencies": {
57
+ "react": "^19",
58
+ "web-vitals": "^5.1.0"
59
+ },
60
+ "peerDependenciesMeta": {
61
+ "web-vitals": {
62
+ "optional": true
63
+ }
64
+ }
65
+ }