@founderroute/analytics 0.1.0-beta.1

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 FounderRoute
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/index.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ export type Scalar = string | number | boolean | null;
2
+ export type AnalyticsOptions = { key: string; endpoint: string; verificationId?: string; autoPage?: boolean; allowedProperties?: string[]; allowedTraits?: string[]; storage?: Pick<Storage,"getItem"|"setItem"|"removeItem">; fetch?: typeof fetch };
3
+ export class FounderRouteAnalytics {
4
+ constructor(options: AnalyticsOptions);
5
+ setConsent(granted: boolean): void;
6
+ identify(userId: string, options?: {token?: string;traits?: Record<string,Scalar>}): void;
7
+ setAccount(accountId: string | null): void;
8
+ track(name: string, properties?: Record<string,Scalar>, options?: {outcomeId?: string}): string | null;
9
+ page(path?: string): string | null;
10
+ screen(name: string): string | null;
11
+ reset(): void;
12
+ flush(): Promise<void>;
13
+ decorateLink(url:string,destinationPropertyId:string):Promise<string>;
14
+ consumeHandoff(token:string):Promise<void>;
15
+ getDiagnostics(): {consent:boolean;queued:number;dropped:number;rejected:number;acknowledged:number;lastError:string|null;anonymousId:string|null};
16
+ destroy(): void;
17
+ }
18
+ export function init(options: AnalyticsOptions): FounderRouteAnalytics;
19
+ export function normalizePath(value:string):string;
package/index.js ADDED
@@ -0,0 +1,168 @@
1
+ const VERSION = "0.1.0-beta.1";
2
+ const MAX_BYTES = 1024 * 1024;
3
+ const MAX_EVENTS = 1000;
4
+ const TTL = 86400000;
5
+ const encoder = new TextEncoder();
6
+ const sensitive = /password|secret|token|email|phone|authorization|credit.?card|address|full.?name/i;
7
+ const uuid = () => globalThis.crypto.randomUUID();
8
+ const clean = (properties, allowed = []) => Object.fromEntries(Object.entries(properties ?? {}).filter(([k,v]) => allowed.includes(k) && !sensitive.test(k) && (v === null || ["string","boolean","number"].includes(typeof v))).map(([k,v]) => [k,typeof v === "string" ? v.slice(0,500) : v]));
9
+ export function normalizePath(value) {
10
+ return String(value ?? "/").split(/[?#]/)[0].split("/").map(s => /^\d+$/.test(s) || /@|%40/i.test(s) || /^[0-9a-f]{8}-[0-9a-f-]{27}$/i.test(s) ? "[id]" : s).join("/").slice(0,500);
11
+ }
12
+
13
+ export class FounderRouteAnalytics {
14
+ constructor(options) {
15
+ if (!options?.key || !options?.endpoint) throw new Error("FounderRoute requires a public key and collector origin.");
16
+ this.options = options; this.endpoint = options.endpoint.replace(/\/$/, "");
17
+ this.storageKey = `founderroute:${options.key}`; this.consent = false; this.queue = [];
18
+ this.identity = null; this.session = null; this.user = null; this.account = null; this.token = null; this.traits = {};
19
+ this.dropped = 0; this.rejected = 0; this.sent = 0; this.lastError = null; this.inFlight = null; this.retryAt = 0; this.failures = 0;
20
+ this.generation = 0; this.cleanups = []; this.timer = null; this.lastInteraction = 0; this.lastTick = 0; this.lastPage = null;
21
+ }
22
+ setConsent(granted) {
23
+ if (Boolean(granted) === this.consent) return;
24
+ this.consent = Boolean(granted); this.generation++;
25
+ if (!this.consent) {
26
+ this.controller?.abort(); clearInterval(this.timer); this.timer = null;
27
+ for (const remove of this.cleanups.splice(0)) remove();
28
+ this.queue = []; this.identity = null; this.session = null; this.user = null; this.token = null; this.account = null; this.traits = {}; this.lastPage = null;
29
+ try { this.options.storage?.removeItem(this.storageKey); if (!this.options.storage) globalThis.localStorage?.removeItem(this.storageKey); } catch { /* unavailable storage is not fatal */ }
30
+ return;
31
+ }
32
+ try {
33
+ const stored = (this.options.storage ?? globalThis.localStorage)?.getItem(this.storageKey);
34
+ if (stored) { const saved = JSON.parse(stored); this.queue = Array.isArray(saved.queue) ? saved.queue : []; this.identity = saved.identity; }
35
+ } catch { this.queue = []; }
36
+ this.identity ||= uuid(); this.lastInteraction = Date.now(); this.lastTick = Date.now();
37
+ this.prune(); this.persist(); this.attach();
38
+ this.timer = setInterval(() => { this.engagement(); void this.flush(); }, 15000);
39
+ this.timer?.unref?.();
40
+ if (this.options.autoPage !== false && globalThis.location) this.page();
41
+ void this.flush();
42
+ }
43
+ persist() {
44
+ if (!this.consent) return;
45
+ try { (this.options.storage ?? globalThis.localStorage)?.setItem(this.storageKey, JSON.stringify({ identity:this.identity,queue:this.queue })); }
46
+ catch { this.lastError = "storage_unavailable"; }
47
+ }
48
+ prune() {
49
+ const now = Date.now();
50
+ const keep = this.queue.filter(e => now-Date.parse(e.occurred_at) <= TTL);
51
+ this.dropped += this.queue.length-keep.length; this.queue = keep;
52
+ while (this.queue.length>MAX_EVENTS || encoder.encode(JSON.stringify(this.queue)).length>MAX_BYTES) { this.queue.shift(); this.dropped++; }
53
+ }
54
+ event(name, properties = {}, extra = {}) {
55
+ if (!this.consent) return null;
56
+ const now = Date.now();
57
+ if (!this.session || now-this.session.last >= 1800000) this.session = { id:uuid(),last:now };
58
+ this.session.last = now;
59
+ const event = {
60
+ event_id:uuid(),protocol:1,name,kind:extra.kind ?? "custom",occurred_at:new Date(now).toISOString(),anonymous_id:this.identity,
61
+ ...(this.user ? {user_id:this.user} : {}),...(this.token ? {identity_token:this.token} : {}),...(this.account ? {account_id:this.account} : {}),
62
+ session_id:this.session.id,consent:true,properties:clean(properties,this.options.allowedProperties),traits:clean(this.traits,this.options.allowedTraits),
63
+ context:{sdk:"browser",sdk_version:VERSION,...(this.options.verificationId?{verification_id:this.options.verificationId}:{}),...this.campaignContext(),...extra.context},...(extra.outcomeId ? {outcome_id:extra.outcomeId} : {}),
64
+ };
65
+ if (encoder.encode(JSON.stringify(event)).length>8192) { this.rejected++; this.lastError="event_too_large"; return null; }
66
+ this.queue.push(event); this.prune(); this.persist(); return event.event_id;
67
+ }
68
+ track(name, properties = {}, options = {}) { return this.event(name,properties,{outcomeId:options.outcomeId}); }
69
+ page(path) {
70
+ if (!this.consent) return null;
71
+ const route = normalizePath(path ?? globalThis.location?.pathname ?? "/");
72
+ if (route === this.lastPage) return null;
73
+ this.engagement(); this.lastPage=route;
74
+ return this.event("page_view",{},{kind:"page",context:{path:route}});
75
+ }
76
+ screen(name) { return this.event("screen_view",{},{kind:"screen",context:{screen:String(name).slice(0,150)}}); }
77
+ identify(userId, { token, traits = {} } = {}) {
78
+ if (!this.consent || !userId) return;
79
+ if (this.user && this.user !== String(userId)) this.reset();
80
+ this.user=String(userId); this.token=token; this.traits={...traits};
81
+ this.event("fr_identify",{},{kind:"identify"});
82
+ }
83
+ setAccount(accountId) { if (this.consent) this.account=accountId ? String(accountId) : null; }
84
+ reset() {
85
+ if (!this.consent) return;
86
+ this.engagement(); this.user=null; this.token=null; this.account=null; this.traits={}; this.identity=uuid(); this.session=null; this.lastPage=null; this.persist();
87
+ }
88
+ campaignContext() {
89
+ const result={};
90
+ if (!globalThis.location) return result;
91
+ const params=new URLSearchParams(globalThis.location.search);
92
+ for (const key of ["utm_source","utm_medium","utm_campaign","utm_content"]) if(params.get(key)) result[key]=params.get(key).slice(0,key==="utm_source"||key==="utm_medium"?100:150);
93
+ const link=params.get("fr_link"); if (link && /^[0-9a-f-]{36}$/i.test(link)) result.campaign_link=link;
94
+ try { if (globalThis.document?.referrer) result.referrer=new URL(globalThis.document.referrer).origin; } catch { /* ignore malformed referrers */ }
95
+ return result;
96
+ }
97
+ engagement() {
98
+ if (!this.consent) return;
99
+ const now=Date.now(); const elapsed=Math.min(15000,Math.max(0,now-this.lastTick)); this.lastTick=now;
100
+ if (globalThis.document?.visibilityState === "hidden" || now-this.lastInteraction>60000 || !elapsed) return;
101
+ this.event("fr_session",{},{kind:"session",context:{active_ms:elapsed,path:this.lastPage??"/"}});
102
+ }
103
+ attach() {
104
+ if (!globalThis.addEventListener) return;
105
+ const on=(target,name,callback)=>{target.addEventListener(name,callback);this.cleanups.push(()=>target.removeEventListener(name,callback));};
106
+ for (const name of ["pointerdown","keydown","scroll","touchstart"]) on(globalThis,name,()=>{this.lastInteraction=Date.now();});
107
+ on(globalThis,"online",()=>{this.retryAt=0;void this.flush();});
108
+ on(globalThis,"popstate",()=>this.page());
109
+ if (globalThis.document) on(document,"visibilitychange",()=>{
110
+ if(document.visibilityState==="hidden") { this.persist(); this.beacon(); }
111
+ else { this.lastTick=Date.now(); this.lastInteraction=Date.now(); void this.flush(); }
112
+ });
113
+ if (globalThis.history && this.options.autoPage!==false) {
114
+ for (const name of ["pushState","replaceState"]) {
115
+ const original=history[name];const client=this;
116
+ const wrapped=function(...args){ const result=original.apply(this,args);client.page();return result;};
117
+ history[name]=wrapped;this.cleanups.push(()=>{if(history[name]===wrapped)history[name]=original;});
118
+ }
119
+ }
120
+ }
121
+ batch() {
122
+ this.prune();const events=[];
123
+ for(const event of this.queue.slice(0,50)) { if(encoder.encode(JSON.stringify({key:this.options.key,events:[...events,event]})).length>65536)break;events.push(event); }
124
+ return events;
125
+ }
126
+ beacon() {
127
+ if(!this.consent||!globalThis.navigator?.sendBeacon) return;
128
+ const events=this.batch(); if(!events.length)return;
129
+ try { navigator.sendBeacon(`${this.endpoint}/api/analytics/v1/collect`,new Blob([JSON.stringify({key:this.options.key,events})],{type:"text/plain"})); }
130
+ catch { /* retained until acknowledged by fetch */ }
131
+ }
132
+ async flush() {
133
+ if(!this.consent||Date.now()<this.retryAt) return;
134
+ if(this.inFlight)return this.inFlight;
135
+ const generation=this.generation; const events=this.batch(); if(!events.length)return;
136
+ this.controller=new AbortController();
137
+ this.inFlight=(async()=>{
138
+ try {
139
+ const response=await (this.options.fetch??globalThis.fetch)(`${this.endpoint}/api/analytics/v1/collect`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:this.options.key,events}),signal:this.controller.signal});
140
+ if(!this.consent||this.generation!==generation)return;
141
+ if(response.status===429||response.status>=500){this.failures++;this.retryAt=Date.now()+Math.max(Number(response.headers.get("Retry-After")??0)*1000,Math.min(300000,1000*2**Math.min(this.failures,8)));this.lastError=`delivery_${response.status}`;return;}
142
+ const result=await response.json();
143
+ if(!response.ok){this.lastError=result.error??"delivery_rejected";this.retryAt=Date.now()+300000;if([400,401,403,413].includes(response.status)){const ids=new Set(events.map(e=>e.event_id));this.queue=this.queue.filter(e=>!ids.has(e.event_id));this.rejected+=ids.size;}return;}
144
+ const acknowledged=new Set();
145
+ for(const receipt of result.results??[]){if(["accepted","duplicate","rejected"].includes(receipt.status))acknowledged.add(receipt.event_id);if(receipt.status==="rejected"){this.rejected++;this.lastError=receipt.reason;}else this.sent++;}
146
+ this.queue=this.queue.filter(e=>!acknowledged.has(e.event_id));this.failures=0;this.retryAt=0;
147
+ }catch(error){if(error?.name!=="AbortError"){this.lastError="network_unavailable";this.failures++;this.retryAt=Date.now()+Math.min(300000,1000*2**Math.min(this.failures,8));}}
148
+ finally{if(this.consent&&this.generation===generation)this.persist();this.inFlight=null;}
149
+ })();
150
+ return this.inFlight;
151
+ }
152
+ async decorateLink(url,destinationPropertyId) {
153
+ if(!this.consent)return url;
154
+ const destination=new URL(url,globalThis.location?.href);if(!["http:","https:"].includes(destination.protocol)||destination.username||destination.password)return url;
155
+ const response=await (this.options.fetch??fetch)(`${this.endpoint}/api/analytics/v1/link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({consent:true,key:this.options.key,anonymousId:this.identity,destinationPropertyId,destinationUrl:destination.origin})});
156
+ if(!response.ok)return url;
157
+ const {token}=await response.json();destination.searchParams.set("fr_handoff",token);return destination.toString();
158
+ }
159
+ async consumeHandoff(token) {
160
+ if(!this.consent)return;
161
+ await (this.options.fetch??fetch)(`${this.endpoint}/api/analytics/v1/link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({consent:true,key:this.options.key,anonymousId:this.identity,token})});
162
+ }
163
+ getDiagnostics(){return {consent:this.consent,queued:this.queue.length,dropped:this.dropped,rejected:this.rejected,acknowledged:this.sent,lastError:this.lastError,anonymousId:this.consent?this.identity:null};}
164
+ destroy(){this.setConsent(false);}
165
+ }
166
+
167
+ const instances=new Map();
168
+ export function init(options){const existing=instances.get(options.key);if(existing)return existing;const client=new FounderRouteAnalytics(options);instances.set(options.key,client);return client;}
package/next.js ADDED
@@ -0,0 +1,4 @@
1
+ "use client";
2
+ import { useEffect } from "react";
3
+ import { usePathname } from "next/navigation";
4
+ export function FounderRoutePageViews({ client }) { const pathname=usePathname();useEffect(()=>{if(pathname)client.page(pathname);},[client,pathname]);return null; }
package/package.json ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "@founderroute/analytics",
3
+ "version": "0.1.0-beta.1",
4
+ "description": "Consent-first FounderRoute analytics for browsers, React, and Next.js",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "types": "index.d.ts",
8
+ "exports": { ".": { "types": "./index.d.ts", "default": "./index.js" }, "./react": "./react.js", "./next": "./next.js" },
9
+ "files": ["*.js", "*.d.ts", "LICENSE"],
10
+ "peerDependencies": { "react": ">=18 <20", "next": ">=15 <17" },
11
+ "peerDependenciesMeta": { "react": { "optional": true }, "next": { "optional": true } },
12
+ "license": "MIT",
13
+ "repository": { "type": "git", "url": "git+https://github.com/itsreed/founderroute-analytics.git", "directory": "packages/browser" },
14
+ "homepage": "https://github.com/itsreed/founderroute-analytics#readme",
15
+ "bugs": { "url": "https://github.com/itsreed/founderroute-analytics/issues" },
16
+ "publishConfig": { "access": "public", "provenance": true }
17
+ }
package/react.js ADDED
@@ -0,0 +1,3 @@
1
+ "use client";
2
+ import { useEffect } from "react";
3
+ export function FounderRouteConsent({ client, granted, children }) { useEffect(()=>{client.setConsent(granted);},[client,granted]);return children??null; }