@faststats/web 0.2.13 → 0.3.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.
Files changed (51) hide show
  1. package/dist/chunks/api-urls-nKmJnyjD.js +1 -0
  2. package/dist/chunks/identifiers-wylBcW5K.js +1 -0
  3. package/dist/chunks/{replay-BuX3_0xs.d.ts → replay-Dpl1P6cw.d.ts} +17 -12
  4. package/dist/chunks/send-data-D6WdryL7.js +1 -0
  5. package/dist/error.d.ts +4 -12
  6. package/dist/error.js +2 -1
  7. package/dist/feature-flags.d.ts +19 -2
  8. package/dist/feature-flags.js +1 -1
  9. package/dist/index.d.ts +15 -37
  10. package/dist/index.js +1 -1
  11. package/dist/replay.d.ts +2 -2
  12. package/dist/replay.js +1 -1
  13. package/dist/web-vitals.d.ts +4 -7
  14. package/dist/web-vitals.js +1 -1
  15. package/package.json +9 -11
  16. package/CHANGELOG.md +0 -177
  17. package/dist/chunks/api-urls-DaeYkG0_.js +0 -1
  18. package/dist/chunks/error-CDVOMiI9.js +0 -2
  19. package/dist/chunks/feature-flags-BClx56v5.d.ts +0 -19
  20. package/dist/chunks/feature-flags-DSOCIZHK.js +0 -1
  21. package/dist/chunks/identifiers-CQeWm7wi.js +0 -1
  22. package/dist/chunks/replay-CHFW2q4E.js +0 -1
  23. package/dist/chunks/rolldown-runtime-MP-BAFHD.js +0 -1
  24. package/dist/chunks/send-data-DL_GlsQw.js +0 -1
  25. package/dist/chunks/types-CYzR5xtT.js +0 -1
  26. package/dist/chunks/web-vitals-GwPlL7Zy.js +0 -1
  27. package/scripts/check-bundle-size.mjs +0 -96
  28. package/src/analytics.ts +0 -776
  29. package/src/entries/error.ts +0 -6
  30. package/src/entries/feature-flags.ts +0 -5
  31. package/src/entries/main.ts +0 -21
  32. package/src/entries/replay.ts +0 -1
  33. package/src/entries/web-vitals.ts +0 -1
  34. package/src/env.d.ts +0 -2
  35. package/src/error.ts +0 -252
  36. package/src/feature-flags.ts +0 -84
  37. package/src/replay.ts +0 -469
  38. package/src/sdk.ts +0 -8
  39. package/src/utils/api-urls.ts +0 -24
  40. package/src/utils/identifiers.ts +0 -89
  41. package/src/utils/send-data.ts +0 -52
  42. package/src/utils/types.ts +0 -15
  43. package/src/web-vitals.ts +0 -159
  44. package/tests/analytics.test.ts +0 -450
  45. package/tests/identifiers.test.ts +0 -95
  46. package/tests/replay.test.ts +0 -412
  47. package/tests/web-vitals.test.ts +0 -208
  48. package/tsconfig.json +0 -30
  49. package/tsdown.config.ts +0 -27
  50. package/worker/index.ts +0 -22
  51. package/wrangler.toml +0 -8
@@ -1 +0,0 @@
1
- import{t as e}from"./rolldown-runtime-MP-BAFHD.js";import{n as t,t as n}from"./api-urls-DaeYkG0_.js";import{n as r,r as i,t as a}from"./identifiers-CQeWm7wi.js";import{t as o}from"./send-data-DL_GlsQw.js";import{t as s}from"./types-CYzR5xtT.js";import{EventType as c}from"@rrweb/types";import{record as l}from"rrweb";var u=e({default:()=>p});const d={mousemove:50,mouseInteraction:!0,scroll:150,media:800,input:`last`},f={script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0};var p=class{endpoint;compressionSupported=typeof window<`u`&&`CompressionStream`in window;sampled;events=[];pending=[];pendingSizeBytes=0;sessionId;started=!1;startTime=0;sequence=0;intervalId=null;flushTask=null;retryTask=null;minLengthFlushTask=null;stopRecording;sending=!1;constructor(e){this.options=e,this.endpoint=`${t(e.baseUrl)}${n.replay}`,this.sampled=Math.random()*100<s(e.samplingPercentage)}get debug(){return this.options.debug??!1}get flushInterval(){return this.options.flushInterval??1e4}get maxEvents(){return this.options.maxEvents??500}get maxPendingBatches(){return this.options.maxPendingBatches??30}get maxQueueSizeBytes(){return this.options.maxQueueSizeBytes??2097152}get minReplayLengthMs(){return this.options.minReplayLengthMs??3e3}get shouldCompress(){return this.options.compress??!0}log(...e){this.debug&&console.log(`[Replay]`,...e)}start(){this.started||typeof window>`u`||!this.sampled||(this.started=!0,this.sessionId=r(),this.startTime=i(),this.beginRecording(),this.intervalId=setInterval(this.requestFlush,this.flushInterval),window.addEventListener(`beforeunload`,this.onUnload),window.addEventListener(`pagehide`,this.onUnload),document.addEventListener(`visibilitychange`,this.onVisibilityChange),this.log(`Recording started`))}async beginRecording(){let e=this.options.recordConsole??!0,[{getRecordSequentialIdPlugin:t},n]=await Promise.all([import(`@rrweb/rrweb-plugin-sequential-id-record`),e?import(`@rrweb/rrweb-plugin-console-record`):Promise.resolve(null)]);if(!this.started)return;let r=[t({key:`_faststatsSeqId`})];n&&r.push(n.getRecordConsolePlugin()),this.stopRecording=l({emit:this.onEvent,sampling:this.options.sampling??d,slimDOMOptions:this.options.slimDOMOptions??f,maskAllInputs:this.options.maskAllInputs??!0,maskInputOptions:this.options.maskInputOptions??{password:!0,email:!0,tel:!0},blockClass:this.options.blockClass,blockSelector:this.options.blockSelector,maskTextClass:this.options.maskTextClass,maskTextSelector:this.options.maskTextSelector,checkoutEveryNms:this.options.checkoutEveryNms??6e4,checkoutEveryNth:this.options.checkoutEveryNth,plugins:r})}stop(){if(this.started){if(this.started=!1,this.stopRecording?.(),this.stopRecording=void 0,this.intervalId&&clearInterval(this.intervalId),this.flushTask&&clearTimeout(this.flushTask),this.retryTask&&clearTimeout(this.retryTask),this.minLengthFlushTask&&clearTimeout(this.minLengthFlushTask),this.intervalId=null,this.flushTask=null,this.retryTask=null,this.minLengthFlushTask=null,window.removeEventListener(`beforeunload`,this.onUnload),window.removeEventListener(`pagehide`,this.onUnload),document.removeEventListener(`visibilitychange`,this.onVisibilityChange),!this.hasReachedMinLength()){this.events.length=0,this.sessionId=void 0,this.log(`Session too short (${Date.now()-this.startTime}ms), discarding events`);return}this.flush(!0),this.sessionId=void 0,this.log(`Recording stopped`)}}getSessionId(){return this.sessionId??r()}onEvent=(e,t)=>{if(this.events.push(e),t||this.events.length>=this.maxEvents||e.type===c.FullSnapshot&&this.hasReachedMinLength()){this.requestFlush();return}this.scheduleMinLengthFlush()};onUnload=()=>{this.flush(!0)};onVisibilityChange=()=>{document.visibilityState===`hidden`&&this.flush(!0)};hasReachedMinLength(){return this.minReplayLengthMs<=0||Date.now()-this.startTime>=this.minReplayLengthMs}requestFlush=()=>{this.flushTask||this.sending||this.events.length===0||(this.minLengthFlushTask&&=(clearTimeout(this.minLengthFlushTask),null),this.flushTask=setTimeout(()=>{this.flushTask=null,this.flush(!1)},0))};scheduleMinLengthFlush(){if(this.minLengthFlushTask||this.events.length===0||this.hasReachedMinLength())return;let e=Math.max(0,this.minReplayLengthMs-(Date.now()-this.startTime)),t=Math.min(e,2147483647);this.minLengthFlushTask=setTimeout(()=>{this.minLengthFlushTask=null,this.requestFlush()},t)}createBatch(e){let t=a(),n=this.sequence++;return{token:this.options.siteKey,sessionId:this.getSessionId(),...t?{identifier:t}:{},batchId:this.createBatchId(n),sequence:n,timestamp:Date.now(),url:window.location.href,events:e}}createBatchId(e){let t=typeof crypto<`u`&&`randomUUID`in crypto?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;return`${this.getSessionId()??`unknown`}-${e}-${t}`}getBatchSizeBytes(e){return new TextEncoder().encode(JSON.stringify(e)).byteLength}dropOldestPendingBatch(e){let t=this.pending.shift();t&&(this.pendingSizeBytes=Math.max(0,this.pendingSizeBytes-this.getBatchSizeBytes(t)),this.log(`${e}, dropping batch ${t.sequence}`))}enqueueBatch(e){let t=this.getBatchSizeBytes(e);if(t>this.maxQueueSizeBytes){this.log(`Replay batch ${e.sequence} is ${t}B, exceeding ${this.maxQueueSizeBytes}B queue limit; dropping`);return}for(;this.pending.length>0&&this.pendingSizeBytes+t>this.maxQueueSizeBytes;)this.dropOldestPendingBatch(`Pending queue size limit reached`);for(;this.pending.length>=this.maxPendingBatches;)this.dropOldestPendingBatch(`Pending batch limit reached`);this.pending.push(e),this.pendingSizeBytes+=t}async encodeBatch(e){let t=JSON.stringify(e);if(!this.shouldCompress||!this.compressionSupported)return{data:t,isCompressed:!1};try{let e=await this.compress(t);return this.log(`Compressed ${t.length}B -> ${e.byteLength}B (${Math.round(e.byteLength/t.length*100)}%)`),{data:e,isCompressed:!0}}catch{return this.log(`Compression failed, using uncompressed`),{data:t,isCompressed:!1}}}async flush(e){if(!this.sending){if(this.events.length>0)if(!this.hasReachedMinLength())this.scheduleMinLengthFlush();else{let e=this.createBatch(this.events.splice(0));this.enqueueBatch(e)}if(this.pending.length!==0){this.sending=!0;try{for(;this.pending.length>0;){let t=this.pending[0];if(!t)break;let n=await this.encodeBatch(t);if(!await this.send(n.data,n.isCompressed,e)){this.log(`Failed to send replay batch ${t.sequence}, retrying`),this.scheduleRetry();break}this.dropOldestPendingBatch(`Sent replay batch`),e=!1}}finally{this.sending=!1}}}}scheduleRetry(){this.retryTask||=setTimeout(()=>{this.retryTask=null,this.flush(!1)},1e3)}async compress(e){let t=new Blob([e]).stream().pipeThrough(new CompressionStream(`gzip`)),n=await new Response(t).arrayBuffer();return new Uint8Array(n)}send(e,t,n){return o({url:t?`${this.endpoint}?encoding=gzip`:this.endpoint,data:e,contentType:t?`application/octet-stream`:`application/json`,debug:!1,useBeacon:!1,keepalive:n})??Promise.resolve(!1)}};export{u as n,p as t};
@@ -1 +0,0 @@
1
- var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r};export{t};
@@ -1 +0,0 @@
1
- async function e(e){let{url:t,data:n,contentType:r=`application/json`,headers:i={},debug:a=!1,debugPrefix:o=`[Analytics]`,useBeacon:s=!0,keepalive:c=!0}=e;if(s&&typeof globalThis.navigator?.sendBeacon==`function`)try{let e=n instanceof Blob?n:typeof Blob<`u`?new Blob([n],{type:r}):n;if(globalThis.navigator.sendBeacon(t,e))return a&&console.log(`${o} Sent via beacon`),!0}catch{}try{let e=await fetch(t,{method:`POST`,body:n,headers:{"Content-Type":r,...i},keepalive:c}),s=e.ok;if(a){let t=s?`${o} Sent via fetch`:`${o} Failed: ${e.status}`;console[s?`log`:`warn`](t)}return s}catch{return a&&console.warn(`${o} Failed to send`),!1}}export{e as t};
@@ -1 +0,0 @@
1
- function e(e){return typeof e!=`number`||!Number.isFinite(e)?100:Math.max(0,Math.min(100,e))}export{e as t};
@@ -1 +0,0 @@
1
- import{t as e}from"./rolldown-runtime-MP-BAFHD.js";import{n as t,t as n}from"./api-urls-DaeYkG0_.js";import{n as r}from"./identifiers-CQeWm7wi.js";import{t as i}from"./types-CYzR5xtT.js";var a=e({default:()=>o}),o=class{endpoint;sampled;metrics=new Map;started=!1;url=``;constructor(e){this.options=e,this.endpoint=`${t(e.baseUrl)}${n.vitals}`,this.sampled=Math.random()*100<i(e.samplingPercentage)}get debug(){return this.options.debug??!1}log(...e){this.debug&&console.log(`[WebVitals]`,...e)}async start(){if(this.started||typeof window>`u`)return;this.started=!0,this.url=window.location.href,document.addEventListener(`visibilitychange`,this.onHidden,{passive:!0}),window.addEventListener(`pagehide`,this.onPageHide,{passive:!0});let e=this.options.attribution?await import(`web-vitals/attribution`):await import(`web-vitals`);this.started&&(e.onCLS(this.capture,{reportAllChanges:!0}),e.onINP(this.capture,{reportAllChanges:!0}),e.onLCP(this.capture,{reportAllChanges:!0}),e.onFCP(this.capture),e.onTTFB(this.capture),this.log(`Tracking started`))}stop(){!this.started||typeof window>`u`||(this.started=!1,this.removeListeners(),this.flush())}trackPageChange(e){if(!this.started||typeof window>`u`)return;let t=e??window.location.href;t!==this.url&&(this.flush(),this.url=t)}onHidden=()=>{document.visibilityState===`hidden`&&this.flush()};onPageHide=()=>{this.flush()};capture=e=>{if(!this.started||!this.sampled)return;let t=e.name,n=e.attribution;this.metrics.set(t,{metric:t,value:e.value,attributes:{id:e.id,rating:e.rating,delta:e.delta,navigationType:e.navigationType,...n??{}}})};async flush(){if(typeof window>`u`||typeof fetch!=`function`||!this.metrics.size)return;let e=Array.from(this.metrics.values()),t=this.url;this.metrics.clear();try{let n=new AbortController,i=window.setTimeout(()=>n.abort(),3e3),a=await fetch(this.endpoint,{method:`POST`,body:JSON.stringify({sessionId:r(),vitals:e,metadata:{url:t}}),headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.options.siteKey}`},keepalive:!0,signal:n.signal});if(clearTimeout(i),!a.ok)throw Error(`HTTP ${a.status}`)}catch(e){this.log(`Failed to send metrics`,e)}}removeListeners(){document.removeEventListener(`visibilitychange`,this.onHidden),window.removeEventListener(`pagehide`,this.onPageHide)}};export{a as n,o as t};
@@ -1,96 +0,0 @@
1
- import { readdir, readFile, stat } from "node:fs/promises";
2
- import { join, resolve } from "node:path";
3
- import { gzipSync } from "node:zlib";
4
-
5
- const distDir = resolve(process.cwd(), "dist");
6
-
7
- const ENTRY_BUDGETS = {
8
- "index.js": { raw: 18 * 1024, gzip: 7 * 1024 },
9
- "feature-flags.js": { raw: 4 * 1024, gzip: 2 * 1024 },
10
- "replay.js": { raw: 8 * 1024, gzip: 4 * 1024 },
11
- "error.js": { raw: 5 * 1024, gzip: 3 * 1024 },
12
- "web-vitals.js": { raw: 4 * 1024, gzip: 2 * 1024 },
13
- };
14
-
15
- const TOTAL_BUDGET = { raw: 40 * 1024, gzip: 16 * 1024 };
16
-
17
- function formatBytes(bytes) {
18
- return `${(bytes / 1024).toFixed(2)} KB`;
19
- }
20
-
21
- async function listJs(dir) {
22
- const entries = await readdir(dir, { withFileTypes: true });
23
- const files = [];
24
- for (const entry of entries) {
25
- const full = join(dir, entry.name);
26
- if (entry.isDirectory()) {
27
- files.push(...(await listJs(full)));
28
- } else if (entry.isFile() && entry.name.endsWith(".js")) {
29
- files.push(full);
30
- }
31
- }
32
- return files;
33
- }
34
-
35
- const failures = [];
36
- let totalRaw = 0;
37
- let totalGzip = 0;
38
-
39
- for (const [name, budget] of Object.entries(ENTRY_BUDGETS)) {
40
- const path = join(distDir, name);
41
- let info;
42
- try {
43
- info = await stat(path);
44
- } catch {
45
- failures.push(`Missing entry: ${name}`);
46
- continue;
47
- }
48
- const buffer = await readFile(path);
49
- const gzipped = gzipSync(buffer).byteLength;
50
-
51
- const status = [];
52
- if (info.size > budget.raw) {
53
- status.push(`raw ${formatBytes(info.size)} > ${formatBytes(budget.raw)}`);
54
- }
55
- if (gzipped > budget.gzip) {
56
- status.push(`gzip ${formatBytes(gzipped)} > ${formatBytes(budget.gzip)}`);
57
- }
58
- if (status.length > 0) {
59
- failures.push(`${name}: ${status.join(", ")}`);
60
- }
61
- console.log(
62
- `${name.padEnd(20)} raw ${formatBytes(info.size).padStart(10)} gzip ${formatBytes(gzipped).padStart(10)}`,
63
- );
64
- }
65
-
66
- const allFiles = await listJs(distDir);
67
- for (const file of allFiles) {
68
- const buf = await readFile(file);
69
- totalRaw += buf.byteLength;
70
- totalGzip += gzipSync(buf).byteLength;
71
- }
72
-
73
- console.log(
74
- `${"total".padEnd(20)} raw ${formatBytes(totalRaw).padStart(10)} gzip ${formatBytes(totalGzip).padStart(10)}`,
75
- );
76
-
77
- if (totalRaw > TOTAL_BUDGET.raw) {
78
- failures.push(
79
- `total raw ${formatBytes(totalRaw)} > ${formatBytes(TOTAL_BUDGET.raw)}`,
80
- );
81
- }
82
- if (totalGzip > TOTAL_BUDGET.gzip) {
83
- failures.push(
84
- `total gzip ${formatBytes(totalGzip)} > ${formatBytes(TOTAL_BUDGET.gzip)}`,
85
- );
86
- }
87
-
88
- if (failures.length > 0) {
89
- console.error("\nBundle size check failed:");
90
- for (const failure of failures) {
91
- console.error(` - ${failure}`);
92
- }
93
- process.exit(1);
94
- }
95
-
96
- console.log("\nBundle size check passed.");