@daybook/analytics 0.0.0-stage → 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.
@@ -0,0 +1,217 @@
1
+ /**
2
+ * The browser, OS and kind of device, from the user agent. Deliberately small: these are the values a
3
+ * breakdown is useful by, and a full parser would be most of the bundle. Chromium freezes parts of the
4
+ * string (macOS stays 10.15.7, Windows 11 says 10), so those versions are what the browser claims.
5
+ */
6
+ export function parseUserAgent(ua, maxTouchPoints = 0) {
7
+ const match = (re) => re.exec(ua)?.[1] ?? '';
8
+ let browser = '';
9
+ let browserVersion = '';
10
+ const pick = (name, re) => {
11
+ const v = re.exec(ua);
12
+ if (!v)
13
+ return false;
14
+ browser = name;
15
+ browserVersion = v[1] ?? '';
16
+ return true;
17
+ };
18
+ // Order matters: Edge, Opera and Samsung say "Chrome" too, and every iOS browser says "Safari".
19
+ void (pick('Edge', /Edg(?:e|A|iOS)?\/([\d.]+)/)
20
+ || pick('Opera', /(?:OPR|OPT)\/([\d.]+)/)
21
+ || pick('Samsung Internet', /SamsungBrowser\/([\d.]+)/)
22
+ || pick('Firefox', /(?:Firefox|FxiOS)\/([\d.]+)/)
23
+ || pick('Chrome', /(?:Chrome|CriOS)\/([\d.]+)/)
24
+ || pick('Safari', /Version\/([\d.]+).*Safari/));
25
+ let os = '';
26
+ let osVersion = '';
27
+ // An iPad asks for the desktop site and says "Macintosh"; touch is what gives it away.
28
+ const iPadAsMac = /Macintosh/.test(ua) && maxTouchPoints > 1;
29
+ if (/iPhone|iPad|iPod/.test(ua) || iPadAsMac) {
30
+ os = 'iOS';
31
+ osVersion = match(/OS (\d+[_.]\d+(?:[_.]\d+)?)/).replace(/_/g, '.');
32
+ }
33
+ else if (/Android/.test(ua)) {
34
+ os = 'Android';
35
+ osVersion = match(/Android (\d+(?:\.\d+)*)/);
36
+ }
37
+ else if (/Windows/.test(ua)) {
38
+ os = 'Windows';
39
+ osVersion = match(/Windows NT (\d+\.\d+)/);
40
+ }
41
+ else if (/CrOS/.test(ua)) {
42
+ os = 'Chrome OS';
43
+ }
44
+ else if (/Mac OS X|Macintosh/.test(ua)) {
45
+ os = 'macOS';
46
+ osVersion = match(/Mac OS X (\d+[_.]\d+(?:[_.]\d+)?)/).replace(/_/g, '.');
47
+ }
48
+ else if (/Linux/.test(ua)) {
49
+ os = 'Linux';
50
+ }
51
+ const deviceType = /iPad|Tablet/.test(ua) || iPadAsMac || (/Android/.test(ua) && !/Mobile/.test(ua))
52
+ ? 'tablet'
53
+ : /Mobi|iPhone|iPod/.test(ua)
54
+ ? 'mobile'
55
+ : 'desktop';
56
+ return { browser, browserVersion, os, osVersion, deviceType };
57
+ }
58
+ /**
59
+ * Crawlers, link previews and uptime checks: what `ignoreBots` leaves out. Named rather than matched on
60
+ * "bot" anywhere, because phones such as Cubot carry those letters in a real browser's user agent.
61
+ */
62
+ export function isBot(ua) {
63
+ return /\bbot\b|crawler|spider|\b(?:googlebot|bingbot|yandexbot|duckduckbot|applebot|petalbot|ahrefsbot|semrushbot|mj12bot|gptbot|claudebot|ccbot|bytespider|twitterbot|linkedinbot|slackbot|discordbot|telegrambot|slurp|facebookexternalhit|whatsapp|embedly|headlesschrome|lighthouse|pingdom|uptimerobot)\b/i.test(ua);
64
+ }
65
+ export function browserContext(appVersion) {
66
+ const nav = globalThis.navigator;
67
+ const parsed = parseUserAgent(nav?.userAgent ?? '', nav?.maxTouchPoints ?? 0);
68
+ const context = {
69
+ browser: parsed.browser,
70
+ os: parsed.os,
71
+ os_version: parsed.osVersion,
72
+ device_type: parsed.deviceType,
73
+ locale: nav?.language ?? '',
74
+ };
75
+ if (appVersion)
76
+ context.app_version = appVersion;
77
+ return { context: { ...context, ...deviceContext() }, browserVersion: parsed.browserVersion };
78
+ }
79
+ /**
80
+ * The person's settings and what they look at (PM-T-0613): their time zone, languages, calendar, digits
81
+ * and clock; the screen, its pixel ratio, light or dark, and the connection. Each only where the
82
+ * browser says, and only what describes the device to a question — nothing that would single one out
83
+ * (no canvas, fonts, graphics card, audio or hardware counts).
84
+ */
85
+ export function deviceContext() {
86
+ const out = {};
87
+ try {
88
+ const options = Intl.DateTimeFormat().resolvedOptions();
89
+ if (options.timeZone)
90
+ out.timezone = options.timeZone;
91
+ if (options.calendar)
92
+ out.calendar = options.calendar;
93
+ if (options.numberingSystem)
94
+ out.numbering_system = options.numberingSystem;
95
+ // hourCycle is not in every TypeScript lib's types yet, though every current browser answers it.
96
+ const cycle = new Intl.DateTimeFormat(undefined, { hour: 'numeric' }).resolvedOptions().hourCycle;
97
+ if (cycle)
98
+ out.hour_cycle = cycle;
99
+ }
100
+ catch {
101
+ // No Intl: none of these.
102
+ }
103
+ const nav = globalThis.navigator;
104
+ const languages = (nav?.languages ?? []).filter(Boolean);
105
+ if (languages.length)
106
+ out.languages = languages.join(',');
107
+ if (nav?.connection?.effectiveType)
108
+ out.network = nav.connection.effectiveType;
109
+ const screen = globalThis.screen;
110
+ if (screen?.width)
111
+ out.screen_width = screen.width;
112
+ if (screen?.height)
113
+ out.screen_height = screen.height;
114
+ const win = globalThis;
115
+ if (win.devicePixelRatio)
116
+ out.pixel_ratio = Math.round(win.devicePixelRatio * 1000) / 1000;
117
+ if (typeof win.matchMedia === 'function') {
118
+ try {
119
+ out.color_scheme = win.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
120
+ }
121
+ catch {
122
+ // A matchMedia that throws: no preference known.
123
+ }
124
+ }
125
+ return out;
126
+ }
127
+ /**
128
+ * What Chromium tells a page that asks (User-Agent Client Hints): an Android phone's model, and the real
129
+ * OS version where the user agent string is frozen (Windows 11 still says 10, macOS 10.15.7). Safari and
130
+ * Firefox do not answer, and an iPhone's model is never given; then this is empty.
131
+ */
132
+ export async function clientHints() {
133
+ const data = globalThis.navigator
134
+ ?.userAgentData;
135
+ if (typeof data?.getHighEntropyValues !== 'function')
136
+ return {};
137
+ try {
138
+ const v = await data.getHighEntropyValues(['model', 'platformVersion']);
139
+ const out = {};
140
+ if (typeof v.model === 'string' && v.model.trim())
141
+ out.device_model = v.model.trim();
142
+ const version = osVersionOf(String(v.platform ?? ''), String(v.platformVersion ?? ''));
143
+ if (version)
144
+ out.os_version = version;
145
+ return out;
146
+ }
147
+ catch {
148
+ return {};
149
+ }
150
+ }
151
+ /** A platform's version as people name it: Windows 13.x and later is 11, macOS and the rest major.minor. */
152
+ export function osVersionOf(platform, version) {
153
+ const [major = '', minor = ''] = version.split('.');
154
+ const n = Number(major);
155
+ if (!major || Number.isNaN(n))
156
+ return null;
157
+ if (platform === 'Windows')
158
+ return n >= 13 ? '11' : n > 0 ? '10' : null;
159
+ if (n === 0)
160
+ return null;
161
+ return minor && minor !== '0' ? `${n}.${minor}` : String(n);
162
+ }
163
+ /** True when the browser asks not to be tracked: Do Not Track, or Global Privacy Control. */
164
+ export function doNotTrack() {
165
+ const nav = globalThis.navigator;
166
+ const win = globalThis;
167
+ const dnt = nav?.doNotTrack ?? win.doNotTrack ?? nav?.msDoNotTrack;
168
+ return dnt === '1' || dnt === 'yes' || nav?.globalPrivacyControl === true;
169
+ }
170
+ /** The campaign parameters kept from a landing URL. */
171
+ const CAMPAIGN = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'gclid', 'fbclid'];
172
+ /** The campaign parameters in a URL, named `$utm_source` and so on. */
173
+ export function campaign(href) {
174
+ const found = {};
175
+ try {
176
+ const params = new URL(href).searchParams;
177
+ for (const name of CAMPAIGN) {
178
+ const value = params.get(name);
179
+ if (value)
180
+ found[`$${name}`] = value.slice(0, 200);
181
+ }
182
+ }
183
+ catch { /* not a URL */ }
184
+ return found;
185
+ }
186
+ /** The host a referrer came from, or `$direct` for none. */
187
+ export function referringDomain(referrer) {
188
+ if (!referrer)
189
+ return '$direct';
190
+ try {
191
+ return new URL(referrer).hostname;
192
+ }
193
+ catch {
194
+ return '$direct';
195
+ }
196
+ }
197
+ /**
198
+ * Where this browser first came from, kept for good on its first page (PM-R-0062 criterion 3), so a
199
+ * signup weeks later can still be broken down by the campaign that brought the visitor.
200
+ */
201
+ export function initialAttribution(href, referrer) {
202
+ const initial = {
203
+ $initial_referrer: referrer || '$direct',
204
+ $initial_referring_domain: referringDomain(referrer),
205
+ };
206
+ for (const [name, value] of Object.entries(campaign(href)))
207
+ initial[`$initial_${name.slice(1)}`] = value;
208
+ return initial;
209
+ }
210
+ /**
211
+ * A page's route, for telling a navigation from a page that only changed its query string: the path,
212
+ * plus the hash when a router keeps its routes there (`#/settings`, `#!/settings`).
213
+ */
214
+ export function routeOf(location) {
215
+ const hash = location.hash ?? '';
216
+ return location.pathname + (hash.startsWith('#/') || hash.startsWith('#!') ? hash.split('?')[0] : '');
217
+ }
@@ -0,0 +1 @@
1
+ "use strict";(()=>{function J(n,t=0){let e=u=>{var p,y;return(y=(p=u.exec(n))==null?void 0:p[1])!=null?y:""},i="",s="",r=(u,p)=>{var N;let y=p.exec(n);return y?(i=u,s=(N=y[1])!=null?N:"",!0):!1};r("Edge",/Edg(?:e|A|iOS)?\/([\d.]+)/)||r("Opera",/(?:OPR|OPT)\/([\d.]+)/)||r("Samsung Internet",/SamsungBrowser\/([\d.]+)/)||r("Firefox",/(?:Firefox|FxiOS)\/([\d.]+)/)||r("Chrome",/(?:Chrome|CriOS)\/([\d.]+)/)||r("Safari",/Version\/([\d.]+).*Safari/);let a="",o="",l=/Macintosh/.test(n)&&t>1;/iPhone|iPad|iPod/.test(n)||l?(a="iOS",o=e(/OS (\d+[_.]\d+(?:[_.]\d+)?)/).replace(/_/g,".")):/Android/.test(n)?(a="Android",o=e(/Android (\d+(?:\.\d+)*)/)):/Windows/.test(n)?(a="Windows",o=e(/Windows NT (\d+\.\d+)/)):/CrOS/.test(n)?a="Chrome OS":/Mac OS X|Macintosh/.test(n)?(a="macOS",o=e(/Mac OS X (\d+[_.]\d+(?:[_.]\d+)?)/).replace(/_/g,".")):/Linux/.test(n)&&(a="Linux");let h=/iPad|Tablet/.test(n)||l||/Android/.test(n)&&!/Mobile/.test(n)?"tablet":/Mobi|iPhone|iPod/.test(n)?"mobile":"desktop";return{browser:i,browserVersion:s,os:a,osVersion:o,deviceType:h}}function D(n){return/\bbot\b|crawler|spider|\b(?:googlebot|bingbot|yandexbot|duckduckbot|applebot|petalbot|ahrefsbot|semrushbot|mj12bot|gptbot|claudebot|ccbot|bytespider|twitterbot|linkedinbot|slackbot|discordbot|telegrambot|slurp|facebookexternalhit|whatsapp|embedly|headlesschrome|lighthouse|pingdom|uptimerobot)\b/i.test(n)}function j(n){var s,r,a;let t=globalThis.navigator,e=J((s=t==null?void 0:t.userAgent)!=null?s:"",(r=t==null?void 0:t.maxTouchPoints)!=null?r:0),i={browser:e.browser,os:e.os,os_version:e.osVersion,device_type:e.deviceType,locale:(a=t==null?void 0:t.language)!=null?a:""};return n&&(i.app_version=n),{context:{...i,...z()},browserVersion:e.browserVersion}}function z(){var r,a;let n={};try{let o=Intl.DateTimeFormat().resolvedOptions();o.timeZone&&(n.timezone=o.timeZone),o.calendar&&(n.calendar=o.calendar),o.numberingSystem&&(n.numbering_system=o.numberingSystem);let l=new Intl.DateTimeFormat(void 0,{hour:"numeric"}).resolvedOptions().hourCycle;l&&(n.hour_cycle=l)}catch{}let t=globalThis.navigator,e=((r=t==null?void 0:t.languages)!=null?r:[]).filter(Boolean);e.length&&(n.languages=e.join(",")),(a=t==null?void 0:t.connection)!=null&&a.effectiveType&&(n.network=t.connection.effectiveType);let i=globalThis.screen;i!=null&&i.width&&(n.screen_width=i.width),i!=null&&i.height&&(n.screen_height=i.height);let s=globalThis;if(s.devicePixelRatio&&(n.pixel_ratio=Math.round(s.devicePixelRatio*1e3)/1e3),typeof s.matchMedia=="function")try{n.color_scheme=s.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}catch{}return n}async function M(){var t,e,i;let n=(t=globalThis.navigator)==null?void 0:t.userAgentData;if(typeof(n==null?void 0:n.getHighEntropyValues)!="function")return{};try{let s=await n.getHighEntropyValues(["model","platformVersion"]),r={};typeof s.model=="string"&&s.model.trim()&&(r.device_model=s.model.trim());let a=H(String((e=s.platform)!=null?e:""),String((i=s.platformVersion)!=null?i:""));return a&&(r.os_version=a),r}catch{return{}}}function H(n,t){let[e="",i=""]=t.split("."),s=Number(e);return!e||Number.isNaN(s)?null:n==="Windows"?s>=13?"11":s>0?"10":null:s===0?null:i&&i!=="0"?`${s}.${i}`:String(s)}function R(){var i,s;let n=globalThis.navigator,t=globalThis,e=(s=(i=n==null?void 0:n.doNotTrack)!=null?i:t.doNotTrack)!=null?s:n==null?void 0:n.msDoNotTrack;return e==="1"||e==="yes"||(n==null?void 0:n.globalPrivacyControl)===!0}var W=["utm_source","utm_medium","utm_campaign","utm_term","utm_content","gclid","fbclid"];function w(n){let t={};try{let e=new URL(n).searchParams;for(let i of W){let s=e.get(i);s&&(t[`$${i}`]=s.slice(0,200))}}catch{}return t}function S(n){if(!n)return"$direct";try{return new URL(n).hostname}catch{return"$direct"}}function I(n,t){let e={$initial_referrer:t||"$direct",$initial_referring_domain:S(t)};for(let[i,s]of Object.entries(w(n)))e[`$initial_${i.slice(1)}`]=s;return e}function $(n){var e;let t=(e=n.hash)!=null?e:"";return n.pathname+(t.startsWith("#/")||t.startsWith("#!")?t.split("?")[0]:"")}var x=class{constructor(t){this.enabled=t;this.said=new Set}debug(t,...e){this.enabled&&console.log(`[daybook] ${t}`,...e)}warn(t){this.said.has(t)||(this.said.add(t),console.warn(`[daybook] ${t}`))}};function b(){let n=new Map;return{get:t=>{var e;return(e=n.get(t))!=null?e:null},set:(t,e)=>{n.set(t,e)},remove:t=>{n.delete(t)}}}function A(n){let t;try{t=globalThis[n];let e="__daybook_probe__";t.setItem(e,"1"),t.removeItem(e)}catch{return null}return{get:e=>{try{return t.getItem(e)}catch{return null}},set:(e,i)=>{try{t.setItem(e,i)}catch{}},remove:e=>{try{t.removeItem(e)}catch{}}}}function q(n){var i;if(typeof document=="undefined")return null;let t=((i=globalThis.location)==null?void 0:i.protocol)==="https:"?"; Secure":"",e=`; path=/${n?`; domain=${n}`:""}; SameSite=Lax${t}`;return{get:s=>{try{let r=`${s}=`,a=document.cookie.split("; ").find(o=>o.startsWith(r));return a?decodeURIComponent(a.slice(r.length)):null}catch{return null}},set:(s,r)=>{try{document.cookie=`${s}=${encodeURIComponent(r)}; max-age=31536000${e}`}catch{}},remove:s=>{try{document.cookie=`${s}=; max-age=0${e}`}catch{}}}}function C(n,t){var e,i;return n==="memory"?b():n==="cookie"||t?(e=q(t))!=null?e:b():(i=A("localStorage"))!=null?i:b()}function O(n,t){let e=n.get(t);if(!e)return null;try{let i=JSON.parse(e);return i&&typeof i=="object"?i:null}catch{return null}}var v="0.3.0";var K=512*1024,V=60*1024,P=1e3,k=class{constructor(t,e){this.apiUrl=t;this.key=e}url(t){return`${this.apiUrl.replace(/\/+$/,"")}/analytics/v1/${t}?key=${encodeURIComponent(this.key)}&sdk=${"js"}`}async post(t,e){var r,a;let i;try{i=await fetch(this.url(t),{method:"POST",body:e,headers:{"Content-Type":"text/plain"},credentials:"omit",keepalive:e.length<V})}catch{return{kind:"retry"}}if(i.ok)return{kind:"ok",body:await i.json().catch(()=>null)};if(i.status===413)return{kind:"too_large"};if(i.status===408||i.status===429||i.status>=500){let o=Number(i.headers.get("Retry-After"));return{kind:"retry",afterMs:Number.isFinite(o)&&o>0?o*1e3:void 0}}let s=await i.json().catch(()=>null);return{kind:"drop",status:i.status,detail:(a=(r=s==null?void 0:s.message)!=null?r:s==null?void 0:s.code)!=null?a:""}}beacon(t,e){let i=this.url(t);try{return typeof navigator!="undefined"&&typeof navigator.sendBeacon=="function"?navigator.sendBeacon(i,new Blob([e],{type:"text/plain"})):(fetch(i,{method:"POST",body:e,headers:{"Content-Type":"text/plain"},credentials:"omit",keepalive:!0}).catch(()=>{}),!0)}catch{return!1}}},_=class{constructor(t,e,i,s,r){this.transport=t;this.store=e;this.name=i;this.options=s;this.log=r;this.timer=null;this.sending=null;this.failures=0;this.retrySize=null;this.inFlight=0;this.stopped=!1;this.jobs=this.load(),this.jobs.length>0&&this.schedule(0)}get size(){return this.jobs.length}push(t){this.jobs.push(t),this.jobs.length>P&&(this.jobs.splice(0,this.jobs.length-P),this.log.warn(`more than ${P} events are waiting to be sent; the oldest were dropped`)),this.save(),this.schedule(this.options.flushIntervalMs)}flush(){var t;return this.timer!==null&&(clearTimeout(this.timer),this.timer=null),(t=this.sending)!=null||(this.sending=this.drain().finally(()=>{this.sending=null})),this.sending}beaconAll(){for(;this.jobs.length>this.inFlight;){let{path:t,text:e,count:i}=this.next(V,this.inFlight);if(!this.transport.beacon(t,e))break;this.jobs.splice(this.inFlight,i)}this.inFlight===0&&(this.retrySize=null),this.save()}clear(){this.jobs=[],this.retrySize=null,this.save()}stop(){this.stopped=!0,this.timer!==null&&clearTimeout(this.timer),this.timer=null}resume(){this.jobs.length>0&&!this.sending&&this.flush()}schedule(t){this.stopped||this.timer!==null||(this.timer=setTimeout(()=>{this.timer=null,this.flush()},t))}async drain(){var t,e;for(;this.jobs.length>0&&!this.stopped;){let{path:i,text:s,count:r,events:a}=this.next(K);this.inFlight=r;let o=await this.transport.post(i,s).finally(()=>{this.inFlight=0});if(o.kind==="retry"){this.retrySize=r,this.failures++;let l=Math.min(3e5,1e3*2**Math.min(this.failures-1,9))*(.75+Math.random()/2);this.log.debug(`could not reach the API; trying again in ${Math.round(((t=o.afterMs)!=null?t:l)/1e3)} s`),this.schedule((e=o.afterMs)!=null?e:l);return}if(o.kind==="too_large"&&r>1){this.retrySize=Math.ceil(r/2);continue}this.jobs.splice(0,r),this.retrySize=null,this.failures=0,this.save(),o.kind==="ok"?this.report(i,o.body,a,r):o.kind==="too_large"?this.log.warn("an event was too large for the API and was dropped"):this.refused(o.status,o.detail,i,r)}}next(t,e=0){let i=this.jobs[e];if(i.t==="i")return{path:"identify",text:JSON.stringify(i.b),count:1,events:[]};if(i.t==="p")return{path:"people",text:JSON.stringify(i.b),count:1,events:[]};let s=e===0&&this.retrySize!==null?this.retrySize:this.options.batchSize,r=[],a=16;for(let o of this.jobs.slice(e)){if(o.t!=="e"||r.length>=s)break;let l=JSON.stringify(o.e).length+1;if(r.length>0&&a+l>t)break;r.push(o.e),a+=l}return{path:"batch",text:JSON.stringify({sent_at:new Date().toISOString(),events:r}),count:r.length,events:r}}report(t,e,i,s){var a,o,l,h;if(t!=="batch"){this.log.debug(`${t} sent`);return}let r=(a=e==null?void 0:e.refused)!=null?a:[];this.log.debug(`${s-r.length} of ${s} events stored`);for(let u of r)this.log.warn(`"${(l=(o=i[u.index])==null?void 0:o.event)!=null?l:"?"}" was refused (${u.reason}): ${(h=u.message)!=null?h:""}`)}refused(t,e,i,s){if(t===401){this.log.warn("the ingest key was refused; check the key in Analytics \u2192 Settings. Nothing more is sent from this page."),this.clear(),this.stop();return}if(t===409&&i==="identify"){this.log.warn(`identify was refused: ${e}`);return}this.log.warn(`${s} ${i==="batch"?"events were":i+" request was"} refused (${t}): ${e}`)}load(){var e;let t=(e=this.store)==null?void 0:e.get(this.name);if(!t)return[];try{let i=JSON.parse(t);return Array.isArray(i)?i.filter(s=>s&&(s.t==="e"||s.t==="i"||s.t==="p")):[]}catch{return[]}}save(){this.store&&(this.jobs.length===0?this.store.remove(this.name):this.store.set(this.name,JSON.stringify(this.jobs)))}};function f(){let n=globalThis.crypto;if(typeof(n==null?void 0:n.randomUUID)=="function")return n.randomUUID();let t=new Uint8Array(16);if(typeof(n==null?void 0:n.getRandomValues)=="function")n.getRandomValues(t);else for(let i=0;i<16;i++)t[i]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e=Array.from(t,i=>i.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}var U="https://api.daybook.team",X="$pageview",G="$pageleave",Y="$session_start",Z=1440*6e4,d=class{constructor(t){this.options=t;this.context={};this.browserVersion="";this.outbox=null;this.cleanup=[];this.current=null;this.referrer=null;this.ignored=!1;var s,r,a,o,l,h,u;if(!t||typeof t.key!="string"||t.key.trim()==="")throw new Error("@daybook/analytics: `key` is required \u2014 the ingest key from Analytics \u2192 Settings.");if(this.log=new x(t.debug===!0),this.browser=typeof window!="undefined"&&typeof document!="undefined",this.stateName=`dbk_${t.key.trim().replace(/^dak_/,"").slice(0,8)}`,this.store=this.browser?C((s=t.persistence)!=null?s:"localStorage",t.cookieDomain):b(),this.state={anon:f(),props:{}},!this.browser)return;let e=(r=navigator.userAgent)!=null?r:"";t.ignoreBots!==!1&&D(e)&&(this.ignored=!0,this.log.debug("this browser says it is a crawler; nothing is sent from it"));let i=j(t.appVersion);this.context=i.context,this.browserVersion=i.browserVersion,M().then(p=>Object.assign(this.context,p)),this.state=this.load(),(o=(a=this.state).initial)!=null||(a.initial=I(location.href,document.referrer)),t.properties&&Object.assign(this.state.props,g(t.properties)),this.save(),this.outbox=new _(new k((l=t.apiUrl)!=null?l:U,t.key.trim()),A("sessionStorage"),`${this.stateName}_queue`,{batchSize:Math.max(1,Math.min(1e3,(h=t.batchSize)!=null?h:50)),flushIntervalMs:Math.max(0,(u=t.flushIntervalMs)!=null?u:2e3)},this.log),this.listen(),t.autoPageviews!==!1&&this.watchHistory()}get distinctId(){return this.state.anon}get userId(){var t;return(t=this.state.user)!=null?t:null}get sessionId(){var t,e;return(e=(t=this.state.session)==null?void 0:t.id)!=null?e:null}get optedOut(){return!this.sending}get registered(){return{...this.state.props}}track(t,e){let i=typeof t=="string"?t.trim():"";if(i===""||i.length>200){this.log.warn(`an event needs a name of 1 to 200 characters; got ${JSON.stringify(t)}`);return}if(i.startsWith("$")){this.log.warn(`"${i}": names starting with $ are Daybook's own. For a page view call page().`);return}this.capture(i,e)}page(t){var a,o;if(!this.browser)return;let e=Date.now(),i=$(location),s=this.current;s&&s.route!==i&&this.leave(e);let r=s?s.url:document.referrer;this.referrer=r,this.current={route:i,url:location.href,path:location.pathname,at:e},this.capture(X,{$title:document.title,$referrer:r||"$direct",$referring_domain:S(r),$screen_width:(a=globalThis.screen)==null?void 0:a.width,$screen_height:(o=globalThis.screen)==null?void 0:o.height,$viewport_width:window.innerWidth,$viewport_height:window.innerHeight,...w(location.href),...t})}identify(t,e){var s;let i=typeof t=="string"||typeof t=="number"?String(t).trim():"";if(i===""||i.length>200){this.log.warn(`identify needs a user id of 1 to 200 characters; got ${JSON.stringify(t)}`);return}if(this.browser){if(this.sync(),this.state.user===i){e&&this.setPersonProperties(e);return}this.state.user&&this.reset(),this.state.user=i,this.save(),this.sending&&((s=this.outbox)==null||s.push({t:"i",b:{distinct_id:this.state.anon,user_id:i,properties:e?g(e):void 0}}))}}reset(){this.browser&&(this.sync(),this.state={anon:f(),props:{},initial:this.state.initial,consent:this.state.consent},this.save())}setPersonProperties(t,e){var i;!this.browser||!this.sending||(this.sync(),(i=this.outbox)==null||i.push({t:"p",b:{...this.who(),set:g(t!=null?t:{}),unset:e==null?void 0:e.filter(s=>typeof s=="string")}}))}setPersonPropertiesOnce(t){var e;!this.browser||!this.sending||(this.sync(),(e=this.outbox)==null||e.push({t:"p",b:{...this.who(),set_once:g(t!=null?t:{})}}))}who(){return this.state.user?{user_id:this.state.user}:{distinct_id:this.state.anon}}register(t){this.browser&&(this.sync(),Object.assign(this.state.props,g(t)),this.save())}unregister(t){this.browser&&(this.sync(),delete this.state.props[t],this.save())}optIn(){if(!this.browser)return;let t=this.sending;this.state.consent="in",this.save(),!t&&this.options.autoPageviews!==!1&&this.page()}optOut(){var t;this.browser&&(this.state.consent="out",(t=this.outbox)==null||t.clear(),this.save())}flush(){var t,e;return(e=(t=this.outbox)==null?void 0:t.flush())!=null?e:Promise.resolve()}destroy(){var t;for(let e of this.cleanup.splice(0))e();(t=this.outbox)==null||t.stop()}get sending(){return this.ignored?!1:this.state.consent?this.state.consent==="in":!(this.options.optOutByDefault||this.options.respectDoNotTrack&&R())}capture(t,e){if(!this.browser||!this.sending||!this.outbox)return;this.sync();let i=Date.now(),s=this.session(i);s.fresh&&this.emit(Y,this.entry(),i,s.id),this.emit(t,e,i,s.id)}entry(){var e;let t=(e=this.referrer)!=null?e:document.referrer;return{$referrer:t||"$direct",$referring_domain:S(t),...w(location.href)}}emit(t,e,i,s){if(!this.outbox)return;let r={event:t,event_id:f(),distinct_id:this.state.anon,timestamp:new Date(i).toISOString(),session_id:s,properties:{$url:location.href,$path:location.pathname,$host:location.host,$browser_version:this.browserVersion,$lib_version:v,...this.state.initial,...this.state.props,...g(e!=null?e:{})},context:{...this.context}};this.state.user&&(r.user_id=this.state.user);let a=!this.state.initialSent&&this.state.initial!==void 0;a&&(r.properties.$set_once={...this.state.initial});let o=r;if(this.options.beforeSend){try{o=this.options.beforeSend(r)}catch(l){this.log.warn(`beforeSend threw, so "${t}" was dropped: ${String(l)}`);return}if(!o){this.log.debug(`beforeSend dropped "${t}"`);return}}try{JSON.stringify(o)}catch{this.log.warn(`"${t}" has properties that cannot be sent as JSON (a circular object?); it was dropped`);return}this.log.debug(`queued "${t}"`,o),this.outbox.push({t:"e",e:o}),a&&(this.state.initialSent=!0),this.save()}session(t){var s,r;let e=Math.max(1,(s=this.options.sessionTimeoutMinutes)!=null?s:30)*6e4,i=this.state.session;return!i||t-i.last>e||t-((r=i.start)!=null?r:i.last)>Z?(this.state.session={id:f(),start:t,last:t},{id:this.state.session.id,fresh:!0}):(i.last=t,{id:i.id,fresh:!1})}leave(t){let e=this.current;this.current=null,!(!e||this.options.pageleave===!1)&&this.capture(G,{$url:e.url,$path:e.path,$duration_ms:Math.max(0,t-e.at)})}watchHistory(){let t=()=>setTimeout(()=>{!this.current||this.current.route!==$(location)?this.page():this.current.url=location.href},0),e=i=>{let s=history[i],r=function(...a){let o=s.apply(this,a);return t(),o};history[i]=r,this.cleanup.push(()=>{history[i]===r&&(history[i]=s)})};e("pushState"),e("replaceState"),this.on(window,"popstate",t),this.on(window,"hashchange",t),document.readyState==="loading"?this.on(document,"DOMContentLoaded",()=>this.page(),{once:!0}):this.page()}listen(){this.on(document,"visibilitychange",()=>{var t;document.visibilityState==="hidden"&&((t=this.outbox)==null||t.beaconAll())}),this.on(window,"pagehide",()=>{var t;this.leave(Date.now()),(t=this.outbox)==null||t.beaconAll()}),this.on(window,"online",()=>{var t;return(t=this.outbox)==null?void 0:t.resume()}),this.on(window,"pageshow",t=>{t.persisted&&this.options.autoPageviews!==!1&&this.page()})}on(t,e,i,s){t.addEventListener(e,i,s),this.cleanup.push(()=>t.removeEventListener(e,i,s))}load(t=O(this.store,this.stateName)){return{anon:typeof(t==null?void 0:t.anon)=="string"&&t.anon?t.anon:f(),user:typeof(t==null?void 0:t.user)=="string"&&t.user?t.user:void 0,props:t!=null&&t.props&&typeof t.props=="object"?t.props:{},initial:t!=null&&t.initial&&typeof t.initial=="object"?t.initial:void 0,initialSent:(t==null?void 0:t.initialSent)===!0?!0:void 0,session:t!=null&&t.session&&typeof t.session.id=="string"?t.session:void 0,consent:(t==null?void 0:t.consent)==="in"||(t==null?void 0:t.consent)==="out"?t.consent:void 0}}sync(){if(!this.sending)return;let t=O(this.store,this.stateName);typeof(t==null?void 0:t.anon)=="string"&&t.anon!==""&&(this.state=this.load(t))}save(){this.browser&&(this.sending?this.store.set(this.stateName,JSON.stringify(this.state)):this.state.consent==="out"&&this.store.set(this.stateName,JSON.stringify({consent:"out"})))}};function g(n){let t={};if(!n||typeof n!="object")return t;for(let[e,i]of Object.entries(n))i===void 0||typeof i=="function"||(t[e]=i instanceof Date?i.toISOString():i);return t}var m=null;function B(n){return m?(n!=null&&n.key&&n.key.trim()!==m.options.key.trim()&&console.warn("[daybook] init was called again with another key; the first instance is kept. Use new DaybookAnalytics() for a second project."),m):(m=new d(n),m)}function L(){return m}var E=globalThis,T=typeof document!="undefined"?document.currentScript:null;function F(n){let t=E.daybook,e=B(n);E.daybook=e;for(let[i,s]of Array.isArray(t==null?void 0:t.q)?t.q:[]){let r=e[i];typeof r=="function"&&r.apply(e,s)}return e}E.DaybookAnalytics={init:F,getAnalytics:L,DaybookAnalytics:d,version:v};var c=T==null?void 0:T.dataset;c!=null&&c.key&&F({key:c.key,apiUrl:c.apiUrl,appVersion:c.appVersion,autoPageviews:c.pageviews!=="false",pageleave:c.pageleave!=="false",persistence:c.persistence,cookieDomain:c.cookieDomain,optOutByDefault:c.optOutByDefault!==void 0&&c.optOutByDefault!=="false",respectDoNotTrack:c.respectDnt!==void 0&&c.respectDnt!=="false",debug:c.debug!==void 0&&c.debug!=="false"});})();
@@ -0,0 +1,19 @@
1
+ import { DaybookAnalytics } from './client.js';
2
+ import type { AnalyticsOptions } from './types.js';
3
+ export { DaybookAnalytics, DEFAULT_API_URL } from './client.js';
4
+ export { SDK_VERSION } from './version.js';
5
+ export type { AnalyticsEvent, AnalyticsOptions, EventContext, Persistence, Properties, PropertyValue, } from './types.js';
6
+ /**
7
+ * Starts analytics for this site, once:
8
+ *
9
+ * import { init } from '@daybook/analytics'
10
+ *
11
+ * const analytics = init({ key: 'dak_…' })
12
+ * analytics.track('signed_up', { plan: 'pro' })
13
+ *
14
+ * A second call returns the same instance, so a component that re-renders, a hot reload or a provider
15
+ * mounted twice cannot start a second one that sends every page view again.
16
+ */
17
+ export declare function init(options: AnalyticsOptions): DaybookAnalytics;
18
+ /** The instance `init` started, or null before it. */
19
+ export declare function getAnalytics(): DaybookAnalytics | null;
package/dist/index.js ADDED
@@ -0,0 +1,28 @@
1
+ import { DaybookAnalytics } from './client.js';
2
+ export { DaybookAnalytics, DEFAULT_API_URL } from './client.js';
3
+ export { SDK_VERSION } from './version.js';
4
+ let shared = null;
5
+ /**
6
+ * Starts analytics for this site, once:
7
+ *
8
+ * import { init } from '@daybook/analytics'
9
+ *
10
+ * const analytics = init({ key: 'dak_…' })
11
+ * analytics.track('signed_up', { plan: 'pro' })
12
+ *
13
+ * A second call returns the same instance, so a component that re-renders, a hot reload or a provider
14
+ * mounted twice cannot start a second one that sends every page view again.
15
+ */
16
+ export function init(options) {
17
+ if (shared) {
18
+ if (options?.key && options.key.trim() !== shared.options.key.trim())
19
+ console.warn('[daybook] init was called again with another key; the first instance is kept. Use new DaybookAnalytics() for a second project.');
20
+ return shared;
21
+ }
22
+ shared = new DaybookAnalytics(options);
23
+ return shared;
24
+ }
25
+ /** The instance `init` started, or null before it. */
26
+ export function getAnalytics() {
27
+ return shared;
28
+ }
package/dist/log.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The SDK's console. Warnings always show, because each one is a tracking mistake a developer can fix
3
+ * — a refused event, a wrong key — and is said once per page; the rest shows only with `debug`.
4
+ */
5
+ export declare class Log {
6
+ enabled: boolean;
7
+ private readonly said;
8
+ constructor(enabled: boolean);
9
+ debug(message: string, ...details: unknown[]): void;
10
+ warn(message: string): void;
11
+ }
package/dist/log.js ADDED
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The SDK's console. Warnings always show, because each one is a tracking mistake a developer can fix
3
+ * — a refused event, a wrong key — and is said once per page; the rest shows only with `debug`.
4
+ */
5
+ export class Log {
6
+ constructor(enabled) {
7
+ this.enabled = enabled;
8
+ this.said = new Set();
9
+ }
10
+ debug(message, ...details) {
11
+ if (this.enabled)
12
+ console.log(`[daybook] ${message}`, ...details);
13
+ }
14
+ warn(message) {
15
+ if (this.said.has(message))
16
+ return;
17
+ this.said.add(message);
18
+ console.warn(`[daybook] ${message}`);
19
+ }
20
+ }
@@ -0,0 +1,27 @@
1
+ import { type ReactNode } from 'react';
2
+ import { DaybookAnalytics } from './index.js';
3
+ import type { AnalyticsOptions } from './types.js';
4
+ export { DaybookAnalytics } from './index.js';
5
+ export type { AnalyticsEvent, AnalyticsOptions, Properties } from './index.js';
6
+ export interface DaybookProviderProps {
7
+ /** Options for the site's instance, started once with `init`. */
8
+ options?: AnalyticsOptions;
9
+ /** Or an instance you started yourself. */
10
+ client?: DaybookAnalytics;
11
+ children?: ReactNode;
12
+ }
13
+ /**
14
+ * Analytics for a React app (PM-R-0062 criterion 6):
15
+ *
16
+ * <DaybookProvider options={{ key: 'dak_…' }}>
17
+ * <App />
18
+ * </DaybookProvider>
19
+ *
20
+ * Started once, while rendering, so the first page view is not a render late. `init` returns the same
21
+ * instance every time, which keeps StrictMode's double render and a remounted provider from starting
22
+ * a second one. Marked 'use client', so Next.js's App Router renders it as a client component; on the
23
+ * server the instance does nothing.
24
+ */
25
+ export declare function DaybookProvider({ options, client, children }: DaybookProviderProps): import("react").FunctionComponentElement<import("react").ProviderProps<DaybookAnalytics | null>>;
26
+ /** The site's analytics, inside a `DaybookProvider`: `const analytics = useAnalytics(); analytics.track('…')`. */
27
+ export declare function useAnalytics(): DaybookAnalytics;
package/dist/react.js ADDED
@@ -0,0 +1,36 @@
1
+ 'use client';
2
+ import { createContext, createElement, useContext, useRef } from 'react';
3
+ import { DaybookAnalytics, init } from './index.js';
4
+ export { DaybookAnalytics } from './index.js';
5
+ const AnalyticsContext = createContext(null);
6
+ /**
7
+ * Analytics for a React app (PM-R-0062 criterion 6):
8
+ *
9
+ * <DaybookProvider options={{ key: 'dak_…' }}>
10
+ * <App />
11
+ * </DaybookProvider>
12
+ *
13
+ * Started once, while rendering, so the first page view is not a render late. `init` returns the same
14
+ * instance every time, which keeps StrictMode's double render and a remounted provider from starting
15
+ * a second one. Marked 'use client', so Next.js's App Router renders it as a client component; on the
16
+ * server the instance does nothing.
17
+ */
18
+ export function DaybookProvider({ options, client, children }) {
19
+ const instance = useRef(null);
20
+ if (instance.current === null) {
21
+ if (client)
22
+ instance.current = client;
23
+ else if (options)
24
+ instance.current = init(options);
25
+ else
26
+ throw new Error('@daybook/analytics/react: DaybookProvider needs `options` (with your key) or a `client`.');
27
+ }
28
+ return createElement(AnalyticsContext.Provider, { value: instance.current }, children);
29
+ }
30
+ /** The site's analytics, inside a `DaybookProvider`: `const analytics = useAnalytics(); analytics.track('…')`. */
31
+ export function useAnalytics() {
32
+ const instance = useContext(AnalyticsContext);
33
+ if (!instance)
34
+ throw new Error('@daybook/analytics/react: useAnalytics is used outside a DaybookProvider.');
35
+ return instance;
36
+ }
@@ -0,0 +1,44 @@
1
+ import type { Persistence } from './types.js';
2
+ /** A place to keep a string by name. Every method swallows the browser's refusals: storage is a nicety, never a reason to lose an event. */
3
+ export interface Store {
4
+ get(name: string): string | null;
5
+ set(name: string, value: string): void;
6
+ remove(name: string): void;
7
+ }
8
+ /** What the SDK remembers about this browser between page loads. */
9
+ export interface State {
10
+ /** The anonymous id: the event's `distinct_id`. */
11
+ anon: string;
12
+ /** The signed-in user, after `identify()`. */
13
+ user?: string;
14
+ /** Registered properties, sent with every event. */
15
+ props: Record<string, unknown>;
16
+ /** Where this browser first came from: `$initial_referrer`, `$initial_utm_source` and the rest. */
17
+ initial?: Record<string, string>;
18
+ /** Whether `initial` has gone to this anonymous id's person as set_once properties (PM-T-0540). */
19
+ initialSent?: boolean;
20
+ /** The current session: when it started and when it last saw an event (ms). */
21
+ session?: {
22
+ id: string;
23
+ start?: number;
24
+ last: number;
25
+ };
26
+ /** The visitor's choice, once they have made one. */
27
+ consent?: 'in' | 'out';
28
+ }
29
+ export declare function memoryStore(): Store;
30
+ /**
31
+ * localStorage or sessionStorage, if the browser lets this page use it. Safari's private mode, a
32
+ * sandboxed iframe and a storage-blocking setting all throw on access rather than saying no, so the
33
+ * only reliable test is to try.
34
+ */
35
+ export declare function webStore(kind: 'localStorage' | 'sessionStorage'): Store | null;
36
+ /**
37
+ * A first-party cookie, so one visitor on `www.example.com` and `app.example.com` is one anonymous id
38
+ * when `domain` is `.example.com`. Never sent to Daybook: the SDK's requests carry no credentials.
39
+ */
40
+ export declare function cookieStore(domain?: string): Store | null;
41
+ /** The store a persistence choice gets, falling back to memory where the browser refuses it. */
42
+ export declare function storeFor(persistence: Persistence, cookieDomain?: string): Store;
43
+ /** A stored state, or null when there is none or it is not one. */
44
+ export declare function readState(store: Store, name: string): Partial<State> | null;
@@ -0,0 +1,102 @@
1
+ export function memoryStore() {
2
+ const values = new Map();
3
+ return {
4
+ get: (name) => values.get(name) ?? null,
5
+ set: (name, value) => void values.set(name, value),
6
+ remove: (name) => void values.delete(name),
7
+ };
8
+ }
9
+ /**
10
+ * localStorage or sessionStorage, if the browser lets this page use it. Safari's private mode, a
11
+ * sandboxed iframe and a storage-blocking setting all throw on access rather than saying no, so the
12
+ * only reliable test is to try.
13
+ */
14
+ export function webStore(kind) {
15
+ let storage;
16
+ try {
17
+ storage = globalThis[kind];
18
+ const probe = '__daybook_probe__';
19
+ storage.setItem(probe, '1');
20
+ storage.removeItem(probe);
21
+ }
22
+ catch {
23
+ return null;
24
+ }
25
+ return {
26
+ get: (name) => {
27
+ try {
28
+ return storage.getItem(name);
29
+ }
30
+ catch {
31
+ return null;
32
+ }
33
+ },
34
+ set: (name, value) => {
35
+ try {
36
+ storage.setItem(name, value);
37
+ }
38
+ catch { /* full or blocked */ }
39
+ },
40
+ remove: (name) => {
41
+ try {
42
+ storage.removeItem(name);
43
+ }
44
+ catch { /* blocked */ }
45
+ },
46
+ };
47
+ }
48
+ /**
49
+ * A first-party cookie, so one visitor on `www.example.com` and `app.example.com` is one anonymous id
50
+ * when `domain` is `.example.com`. Never sent to Daybook: the SDK's requests carry no credentials.
51
+ */
52
+ export function cookieStore(domain) {
53
+ if (typeof document === 'undefined')
54
+ return null;
55
+ const secure = globalThis.location?.protocol === 'https:' ? '; Secure' : '';
56
+ const scope = `; path=/${domain ? `; domain=${domain}` : ''}; SameSite=Lax${secure}`;
57
+ return {
58
+ get: (name) => {
59
+ try {
60
+ const prefix = `${name}=`;
61
+ const found = document.cookie.split('; ').find((c) => c.startsWith(prefix));
62
+ return found ? decodeURIComponent(found.slice(prefix.length)) : null;
63
+ }
64
+ catch {
65
+ return null;
66
+ }
67
+ },
68
+ set: (name, value) => {
69
+ try {
70
+ document.cookie = `${name}=${encodeURIComponent(value)}; max-age=31536000${scope}`;
71
+ }
72
+ catch { /* blocked */ }
73
+ },
74
+ remove: (name) => {
75
+ try {
76
+ document.cookie = `${name}=; max-age=0${scope}`;
77
+ }
78
+ catch { /* blocked */ }
79
+ },
80
+ };
81
+ }
82
+ /** The store a persistence choice gets, falling back to memory where the browser refuses it. */
83
+ export function storeFor(persistence, cookieDomain) {
84
+ if (persistence === 'memory')
85
+ return memoryStore();
86
+ if (persistence === 'cookie' || cookieDomain)
87
+ return cookieStore(cookieDomain) ?? memoryStore();
88
+ return webStore('localStorage') ?? memoryStore();
89
+ }
90
+ /** A stored state, or null when there is none or it is not one. */
91
+ export function readState(store, name) {
92
+ const text = store.get(name);
93
+ if (!text)
94
+ return null;
95
+ try {
96
+ const value = JSON.parse(text);
97
+ return value && typeof value === 'object' ? value : null;
98
+ }
99
+ catch {
100
+ return null;
101
+ }
102
+ }