@daybook/analytics 0.2.0 → 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.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,20 @@
3
3
  Every published version of `@daybook/analytics`. `npm run release` (`devops/publish-sdk.sh analytics`) refuses a version
4
4
  that has no entry here: a release nobody wrote down is a release nobody hears of.
5
5
 
6
+ ## 0.3.0
7
+
8
+ More of where and on what an event happened, as context columns a question can filter and break down by
9
+ (PM-T-0613).
10
+
11
+ - The person's settings: `timezone` (IANA), `languages` (every preferred one, in order), `calendar`,
12
+ `numbering_system`, `hour_cycle`.
13
+ - The screen: `screen_width`, `screen_height`, `pixel_ratio`; `color_scheme` (light or dark); `network`
14
+ (the connection as the browser rates it, where it says).
15
+ - Chromium's client hints, where the browser gives them: an Android phone's `device_model`, and the real
16
+ `os_version` where the user agent is frozen (Windows 11, macOS).
17
+ - Nothing that singles a device out rather than describing it: no canvas, fonts, graphics card, audio or
18
+ hardware counts.
19
+
6
20
  ## 0.2.0
7
21
 
8
22
  Events at their true time, first touch on the person, and sessions as every Daybook SDK keeps them.
package/README.md CHANGED
@@ -62,8 +62,8 @@ Without `data-key`, start it yourself: `DaybookAnalytics.init({ key: 'dak_…',
62
62
  `window.daybook`.
63
63
 
64
64
  **A pinned version.** `daybook.team/sdk/v1/daybook.js` is always the newest build that speaks the v1 API.
65
- To pin one, load it from npm through a public CDN: `https://cdn.jsdelivr.net/npm/@daybook/analytics@0.2.0`
66
- or `https://unpkg.com/@daybook/analytics@0.2.0` serve the same file.
65
+ To pin one, load it from npm through a public CDN: `https://cdn.jsdelivr.net/npm/@daybook/analytics@0.3.0`
66
+ or `https://unpkg.com/@daybook/analytics@0.3.0` serve the same file.
67
67
 
68
68
  ### npm
69
69
 
@@ -407,8 +407,16 @@ Properties the SDK adds, all starting with `$`:
407
407
  | `$session_start` | a session's first event: `$referrer`, `$referring_domain` (`$direct` for none), `$utm_source` … `$utm_content` |
408
408
  | the browser's first event | `$set_once`: the `$initial_*` values, which Daybook sets once on the person and keeps off the event |
409
409
 
410
- The `context` fields are columns of their own in Daybook — `browser`, `os`, `os_version`, `device_type`,
411
- `locale`, `app_version` — so a breakdown by them is fast. `country` is added by Daybook from the request.
410
+ The `context` fields are columns of their own in Daybook, so a breakdown by them is fast:
411
+
412
+ - From the user agent: `browser`, `os`, `os_version`, `device_type`, `locale`, `app_version`. Where Chromium
413
+ answers its client hints, `device_model` (an Android phone's) and the real `os_version`.
414
+ - The person's settings: `timezone`, `languages`, `calendar`, `numbering_system`, `hour_cycle`.
415
+ - The screen and connection: `screen_width`, `screen_height`, `pixel_ratio`, `color_scheme`, `network`.
416
+
417
+ Daybook adds where the request came from, as its edge resolved it: `country`, and with location headers on,
418
+ `continent`, `region`, `region_code`, `city`, `postal_code`, `latitude`, `longitude` (and `timezone` when the
419
+ device sent none). The address itself is never stored — only a keyed hash of it, `ip_hash`.
412
420
 
413
421
  `identify` goes to `/analytics/v1/identify` and person properties to `/analytics/v1/people`. A server can
414
422
  call the same three endpoints with the key in an `X-Daybook-Key` header.
package/dist/client.js CHANGED
@@ -1,4 +1,4 @@
1
- import { browserContext, campaign, doNotTrack, initialAttribution, isBot, referringDomain, routeOf } from './context.js';
1
+ import { browserContext, campaign, clientHints, doNotTrack, initialAttribution, isBot, referringDomain, routeOf } from './context.js';
2
2
  import { Log } from './log.js';
3
3
  import { memoryStore, readState, storeFor, webStore } from './storage.js';
4
4
  import { Outbox, Transport } from './transport.js';
@@ -55,6 +55,9 @@ export class DaybookAnalytics {
55
55
  const browser = browserContext(options.appVersion);
56
56
  this.context = browser.context;
57
57
  this.browserVersion = browser.browserVersion;
58
+ // A phone's model and the real OS version arrive a moment later, where the browser gives them;
59
+ // every event from then on carries them.
60
+ void clientHints().then((hints) => Object.assign(this.context, hints));
58
61
  this.state = this.load();
59
62
  (_a = this.state).initial ?? (_a.initial = initialAttribution(location.href, document.referrer));
60
63
  if (options.properties)
package/dist/context.d.ts CHANGED
@@ -22,6 +22,21 @@ export declare function parseUserAgent(ua: string, maxTouchPoints?: number): {
22
22
  */
23
23
  export declare function isBot(ua: string): boolean;
24
24
  export declare function browserContext(appVersion?: string): Browser;
25
+ /**
26
+ * The person's settings and what they look at (PM-T-0613): their time zone, languages, calendar, digits
27
+ * and clock; the screen, its pixel ratio, light or dark, and the connection. Each only where the
28
+ * browser says, and only what describes the device to a question — nothing that would single one out
29
+ * (no canvas, fonts, graphics card, audio or hardware counts).
30
+ */
31
+ export declare function deviceContext(): EventContext;
32
+ /**
33
+ * What Chromium tells a page that asks (User-Agent Client Hints): an Android phone's model, and the real
34
+ * OS version where the user agent string is frozen (Windows 11 still says 10, macOS 10.15.7). Safari and
35
+ * Firefox do not answer, and an iPhone's model is never given; then this is empty.
36
+ */
37
+ export declare function clientHints(): Promise<EventContext>;
38
+ /** A platform's version as people name it: Windows 13.x and later is 11, macOS and the rest major.minor. */
39
+ export declare function osVersionOf(platform: string, version: string): string | null;
25
40
  /** True when the browser asks not to be tracked: Do Not Track, or Global Privacy Control. */
26
41
  export declare function doNotTrack(): boolean;
27
42
  /** The campaign parameters in a URL, named `$utm_source` and so on. */
package/dist/context.js CHANGED
@@ -74,7 +74,91 @@ export function browserContext(appVersion) {
74
74
  };
75
75
  if (appVersion)
76
76
  context.app_version = appVersion;
77
- return { context, browserVersion: parsed.browserVersion };
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);
78
162
  }
79
163
  /** True when the browser asks not to be tracked: Do Not Track, or Global Privacy Control. */
80
164
  export function doNotTrack() {
package/dist/daybook.js CHANGED
@@ -1 +1 @@
1
- "use strict";(()=>{function J(n,t=0){let e=h=>{var v,y;return(y=(v=h.exec(n))==null?void 0:v[1])!=null?y:""},i="",s="",r=(h,v)=>{var N;let y=v.exec(n);return y?(i=h,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 u=/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:u}}function j(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 D(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,browserVersion:e.browserVersion}}function M(){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 F=["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 F){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 R(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 k=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 z(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 I(n,t){var e,i;return n==="memory"?b():n==="cookie"||t?(e=z(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 m="0.2.0";var W=512*1024,C=60*1024,P=1e3,x=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<C})}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(C,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(W);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,u;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 h of r)this.log.warn(`"${(l=(o=i[h.index])==null?void 0:o.event)!=null?l:"?"}" was refused (${h.reason}): ${(u=h.message)!=null?u:""}`)}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 p(){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 V="https://api.daybook.team",q="$pageview",H="$pageleave",K="$session_start",X=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,u,h;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 k(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?I((s=t.persistence)!=null?s:"localStorage",t.cookieDomain):b(),this.state={anon:p(),props:{}},!this.browser)return;let e=(r=navigator.userAgent)!=null?r:"";t.ignoreBots!==!1&&j(e)&&(this.ignored=!0,this.log.debug("this browser says it is a crawler; nothing is sent from it"));let i=D(t.appVersion);this.context=i.context,this.browserVersion=i.browserVersion,this.state=this.load(),(o=(a=this.state).initial)!=null||(a.initial=R(location.href,document.referrer)),t.properties&&Object.assign(this.state.props,f(t.properties)),this.save(),this.outbox=new _(new x((l=t.apiUrl)!=null?l:V,t.key.trim()),A("sessionStorage"),`${this.stateName}_queue`,{batchSize:Math.max(1,Math.min(1e3,(u=t.batchSize)!=null?u:50)),flushIntervalMs:Math.max(0,(h=t.flushIntervalMs)!=null?h: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(q,{$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?f(e):void 0}}))}}reset(){this.browser&&(this.sync(),this.state={anon:p(),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:f(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:f(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,f(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&&M())}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(K,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:p(),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:m,...this.state.initial,...this.state.props,...f(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)>X?(this.state.session={id:p(),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(H,{$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:p(),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 f(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 g=null;function U(n){return g?(n!=null&&n.key&&n.key.trim()!==g.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."),g):(g=new d(n),g)}function B(){return g}var E=globalThis,T=typeof document!="undefined"?document.currentScript:null;function L(n){let t=E.daybook,e=U(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:L,getAnalytics:B,DaybookAnalytics:d,version:m};var c=T==null?void 0:T.dataset;c!=null&&c.key&&L({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"});})();
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"});})();
package/dist/types.d.ts CHANGED
@@ -16,6 +16,25 @@ export interface EventContext {
16
16
  device_model?: string;
17
17
  browser?: string;
18
18
  locale?: string;
19
+ /** Every language the person prefers, in their order, comma-separated: `pl-PL,en-US`. */
20
+ languages?: string;
21
+ /** The device's time zone setting, IANA: `Europe/Warsaw`. */
22
+ timezone?: string;
23
+ /** The calendar the person's dates are written in: `gregory`, `buddhist`, `islamic`… */
24
+ calendar?: string;
25
+ /** The digits their numbers are written with: `latn`, `arab`… */
26
+ numbering_system?: string;
27
+ /** A 12- or 24-hour clock: `h12`, `h23`. */
28
+ hour_cycle?: string;
29
+ /** The screen, in CSS pixels. */
30
+ screen_width?: number;
31
+ screen_height?: number;
32
+ /** Device pixels to a CSS pixel: 2 on most phones and Retina screens. */
33
+ pixel_ratio?: number;
34
+ /** `light` or `dark`, as the person prefers. */
35
+ color_scheme?: string;
36
+ /** The connection as the browser rates it, where it says: `4g`, `3g`, `2g`, `slow-2g`. */
37
+ network?: string;
19
38
  }
20
39
  /**
21
40
  * One event exactly as it is sent to `/analytics/v1/batch`, which is also what `beforeSend` is given.
package/dist/version.d.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  * of the SDK its pages run. A constant rather than read from package.json at build time, because the
4
4
  * npm build is plain tsc; test/version.test.js refuses a build where the two disagree.
5
5
  */
6
- export declare const SDK_VERSION = "0.2.0";
6
+ export declare const SDK_VERSION = "0.3.0";
7
7
  /**
8
8
  * What the API records as every event's `source`, and one of the names it knows as a Daybook SDK
9
9
  * (PM-T-0528): only those may send `$pageview` and `$pageleave`.
package/dist/version.js CHANGED
@@ -3,7 +3,7 @@
3
3
  * of the SDK its pages run. A constant rather than read from package.json at build time, because the
4
4
  * npm build is plain tsc; test/version.test.js refuses a build where the two disagree.
5
5
  */
6
- export const SDK_VERSION = '0.2.0';
6
+ export const SDK_VERSION = '0.3.0';
7
7
  /**
8
8
  * What the API records as every event's `source`, and one of the names it knows as a Daybook SDK
9
9
  * (PM-T-0528): only those may send `$pageview` and `$pageleave`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@daybook/analytics",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Product analytics for the web: page views, sessions, attribution and your own events, sent to Daybook's Analytics hub. Plain JS, React and Vue.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",