@daybook/analytics 0.3.0 → 0.4.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/dist/browser.js CHANGED
@@ -1,30 +1,121 @@
1
+ import { Daybook, registeredModules } from '@daybook/core';
1
2
  import { DaybookAnalytics, getAnalytics, init as start, SDK_VERSION } from './index.js';
2
3
  const w = globalThis;
3
4
  const script = typeof document !== 'undefined' ? document.currentScript : null;
4
- function init(options) {
5
+ /** Analytics' own calls, which a page written for the tag before the family makes on `window.daybook`. */
6
+ const ANALYTICS = [
7
+ 'track', 'page', 'register', 'unregister', 'setPersonProperties', 'setPersonPropertiesOnce', 'optIn', 'optOut', 'flush',
8
+ ];
9
+ function queued() {
5
10
  const stub = w.daybook;
11
+ return Array.isArray(stub?.q) ? stub.q : [];
12
+ }
13
+ /** The way before the family: analytics alone, as `window.daybook`. */
14
+ function init(options) {
15
+ const calls = queued();
6
16
  const instance = start(options);
7
17
  w.daybook = instance;
8
- for (const [method, args] of Array.isArray(stub?.q) ? stub.q : []) {
18
+ for (const [method, args] of calls) {
9
19
  const fn = instance[method];
10
20
  if (typeof fn === 'function')
11
21
  fn.apply(instance, args);
12
22
  }
13
23
  return instance;
14
24
  }
25
+ /** A module that is not in this file, from the file beside it: feedback.js for `feedback`. */
26
+ function load(name) {
27
+ return new Promise((resolve) => {
28
+ try {
29
+ const tag = document.createElement('script');
30
+ tag.async = true;
31
+ tag.src = new URL(`${name}.js`, script?.src || location.href).href;
32
+ tag.onload = () => resolve();
33
+ tag.onerror = () => {
34
+ console.warn(`[daybook] ${name}: its script could not be loaded from ${tag.src}; the other modules start without it`);
35
+ resolve();
36
+ };
37
+ document.head.appendChild(tag);
38
+ }
39
+ catch {
40
+ resolve();
41
+ }
42
+ });
43
+ }
44
+ /** The family: the core as `window.daybook`, with the modules the tag names. */
45
+ async function initialize(key, options = {}) {
46
+ const calls = queued();
47
+ const names = options.modules ?? ['analytics'];
48
+ await Promise.all(names.filter((name) => /^[a-z]+$/.test(name) && !registeredModules().includes(name)).map(load));
49
+ const daybook = await Daybook.initialize(key, { ...options, modules: names });
50
+ const doors = daybook;
51
+ // A page that called daybook.track(…) with analytics' own key keeps working with the site's key.
52
+ for (const method of ANALYTICS) {
53
+ if (method in doors)
54
+ continue;
55
+ doors[method] = (...args) => call(doors.analytics, method, args);
56
+ }
57
+ w.daybook = daybook;
58
+ for (const [path, args] of calls) {
59
+ try {
60
+ const at = path.lastIndexOf('.');
61
+ call(at < 0 ? doors : doors[path.slice(0, at)], path.slice(at + 1), args);
62
+ }
63
+ catch (error) {
64
+ // One queued call that throws must not keep the rest from being played back.
65
+ console.warn(`[daybook] ${path} was queued before the script loaded and failed: ${String(error)}`);
66
+ }
67
+ }
68
+ return daybook;
69
+ }
70
+ /**
71
+ * What `window.daybook` is between the tag running and the family having started, which takes a
72
+ * moment even for a tag that is not async: calls made then are kept and played back in order. A page
73
+ * that loads the tag async puts the same stub before it (the README has it).
74
+ */
75
+ function stub() {
76
+ const q = [];
77
+ const keep = (path) => (...args) => void q.push([path, args]);
78
+ const doors = (prefix, methods) => Object.fromEntries(methods.map((method) => [method, keep(prefix + method)]));
79
+ return {
80
+ q,
81
+ ...doors('', ['identify', 'reset', 'setTrackingConsent', ...ANALYTICS]),
82
+ analytics: doors('analytics.', ANALYTICS),
83
+ feedback: doors('feedback.', ['open', 'start', 'stop', 'authenticate']),
84
+ };
85
+ }
86
+ function call(target, method, args) {
87
+ const fn = target?.[method];
88
+ return typeof fn === 'function' ? fn.apply(target, args) : undefined;
89
+ }
15
90
  w.DaybookAnalytics = { init, getAnalytics, DaybookAnalytics, version: SDK_VERSION };
91
+ w.Daybook = { initialize, version: Daybook.version };
16
92
  const data = script?.dataset;
93
+ const flag = (value) => value !== undefined && value !== 'false';
17
94
  if (data?.key) {
18
- init({
19
- key: data.key,
95
+ const analytics = {
20
96
  apiUrl: data.apiUrl,
21
97
  appVersion: data.appVersion,
22
98
  autoPageviews: data.pageviews !== 'false',
23
99
  pageleave: data.pageleave !== 'false',
24
100
  persistence: data.persistence,
25
101
  cookieDomain: data.cookieDomain,
26
- optOutByDefault: data.optOutByDefault !== undefined && data.optOutByDefault !== 'false',
27
- respectDoNotTrack: data.respectDnt !== undefined && data.respectDnt !== 'false',
28
- debug: data.debug !== undefined && data.debug !== 'false',
29
- });
102
+ respectDoNotTrack: flag(data.respectDnt),
103
+ debug: flag(data.debug),
104
+ };
105
+ if (data.key.trim().startsWith('dbk_') || data.modules !== undefined) {
106
+ if (!Array.isArray(w.daybook?.q))
107
+ w.daybook = stub();
108
+ void initialize(data.key, {
109
+ modules: (data.modules ?? 'analytics').split(',').map((name) => name.trim()).filter(Boolean),
110
+ serverUrl: data.apiUrl,
111
+ userId: data.userId,
112
+ trackingConsent: !flag(data.optOutByDefault) && data.trackingConsent !== 'false',
113
+ logging: flag(data.debug),
114
+ analytics,
115
+ feedback: { app: data.appVersion ? { version: data.appVersion } : undefined, surface: data.surface },
116
+ });
117
+ }
118
+ else {
119
+ init({ ...analytics, key: data.key, optOutByDefault: flag(data.optOutByDefault) });
120
+ }
30
121
  }
package/dist/client.d.ts CHANGED
@@ -5,6 +5,22 @@ import type { AnalyticsOptions, Properties } from './types.js';
5
5
  * inside bundles cached on other people's pages.
6
6
  */
7
7
  export declare const DEFAULT_API_URL = "https://api.daybook.team";
8
+ /**
9
+ * What ties an instance to Daybook's core when it runs as the family's analytics module (PM-T-0971):
10
+ * the core decides whether the visitor may be measured, and is told the anonymous id.
11
+ */
12
+ export interface Family {
13
+ /** Whether the visitor may be measured now. */
14
+ consent(): boolean;
15
+ /** Whether that is the visitor's own answer, which wins over Do Not Track as `optIn()` does. */
16
+ answered(): boolean;
17
+ /** The visitor answered at this instance's own door: `optIn()` and `optOut()`. */
18
+ answer(granted: boolean): void;
19
+ /** The id a browser with no state of its own starts with: the core's. */
20
+ anonymousId: string;
21
+ /** The anonymous id changed: a reset, another user, another tab. */
22
+ onAnonymousId(id: string): void;
23
+ }
8
24
  /**
9
25
  * Product analytics for one site (PM-R-0062).
10
26
  *
@@ -17,6 +33,7 @@ export declare const DEFAULT_API_URL = "https://api.daybook.team";
17
33
  */
18
34
  export declare class DaybookAnalytics {
19
35
  readonly options: AnalyticsOptions;
36
+ private readonly family?;
20
37
  private readonly browser;
21
38
  private readonly log;
22
39
  private readonly store;
@@ -30,7 +47,8 @@ export declare class DaybookAnalytics {
30
47
  /** Where the page now shown was reached from: the last page of this app, or the document's referrer. */
31
48
  private referrer;
32
49
  private ignored;
33
- constructor(options: AnalyticsOptions);
50
+ /** `family` is the core's, when this instance is its analytics module; a site never passes it. */
51
+ constructor(options: AnalyticsOptions, family?: Family | undefined);
34
52
  /** The anonymous id this browser sends events under. */
35
53
  get distinctId(): string;
36
54
  /** Who `identify()` said is signed in, or null. */
@@ -79,11 +97,18 @@ export declare class DaybookAnalytics {
79
97
  optIn(): void;
80
98
  /** The visitor declined: send nothing, forget what was waiting, and keep only the choice. */
81
99
  optOut(): void;
100
+ /**
101
+ * @internal The core's answer changed. `wasSending` is how it was before. Granted, the state is
102
+ * written and the page the visitor is on is counted; taken back, what was waiting is forgotten and
103
+ * nothing of this module's is left in storage, since the core keeps the answer.
104
+ */
105
+ consented(wasSending: boolean): void;
82
106
  /** Sends what is waiting now. Resolves when it is sent or the API cannot be reached. */
83
107
  flush(): Promise<void>;
84
108
  /** Stops listening and sending; for tests and hot reload. */
85
109
  destroy(): void;
86
- private get sending();
110
+ /** @internal Whether events are sent and the state is kept. */
111
+ get sending(): boolean;
87
112
  private capture;
88
113
  /** What a session began from: the referrer of the page it began on, and that page's campaign. */
89
114
  private entry;
@@ -108,6 +133,11 @@ export declare class DaybookAnalytics {
108
133
  */
109
134
  private listen;
110
135
  private on;
136
+ /**
137
+ * What this browser kept under the hub's own key, for a site that has just moved to the family: the
138
+ * visitor stays who they were, with their session, their properties and where they first came from.
139
+ */
140
+ private earlier;
111
141
  private load;
112
142
  /**
113
143
  * Picks up what another tab of the same site wrote — its sign-in, its reset, its session — so every
package/dist/client.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { browserContext, campaign, clientHints, doNotTrack, initialAttribution, isBot, referringDomain, routeOf } from './context.js';
2
2
  import { Log } from './log.js';
3
- import { memoryStore, readState, storeFor, webStore } from './storage.js';
3
+ import { earlierState, memoryStore, readState, stateNameOf, storeFor, webStore } from './storage.js';
4
4
  import { Outbox, Transport } from './transport.js';
5
5
  import { uuid } from './uuid.js';
6
6
  import { SDK_VERSION } from './version.js';
@@ -26,9 +26,11 @@ const MAX_SESSION_MS = 24 * 60 * 60000;
26
26
  * on the server (Next.js, Nuxt), where it does nothing.
27
27
  */
28
28
  export class DaybookAnalytics {
29
- constructor(options) {
29
+ /** `family` is the core's, when this instance is its analytics module; a site never passes it. */
30
+ constructor(options, family) {
30
31
  var _a;
31
32
  this.options = options;
33
+ this.family = family;
32
34
  this.context = {};
33
35
  this.browserVersion = '';
34
36
  this.outbox = null;
@@ -38,13 +40,13 @@ export class DaybookAnalytics {
38
40
  this.referrer = null;
39
41
  this.ignored = false;
40
42
  if (!options || typeof options.key !== 'string' || options.key.trim() === '')
41
- throw new Error('@daybook/analytics: `key` is required — the ingest key from Analytics → Settings.');
43
+ throw new Error("@daybook/analytics: `key` is required: the site's key from the project's settings, or the ingest key from Analytics → Settings.");
42
44
  this.log = new Log(options.debug === true);
43
45
  this.browser = typeof window !== 'undefined' && typeof document !== 'undefined';
44
46
  // Two projects on one site keep apart: the stored names carry the key's first letters.
45
- this.stateName = `dbk_${options.key.trim().replace(/^dak_/, '').slice(0, 8)}`;
47
+ this.stateName = stateNameOf(options.key);
46
48
  this.store = this.browser ? storeFor(options.persistence ?? 'localStorage', options.cookieDomain) : memoryStore();
47
- this.state = { anon: uuid(), props: {} };
49
+ this.state = { anon: family?.anonymousId || uuid(), props: {} };
48
50
  if (!this.browser)
49
51
  return;
50
52
  const ua = navigator.userAgent ?? '';
@@ -58,7 +60,7 @@ export class DaybookAnalytics {
58
60
  // A phone's model and the real OS version arrive a moment later, where the browser gives them;
59
61
  // every event from then on carries them.
60
62
  void clientHints().then((hints) => Object.assign(this.context, hints));
61
- this.state = this.load();
63
+ this.state = this.load(readState(this.store, this.stateName) ?? this.earlier());
62
64
  (_a = this.state).initial ?? (_a.initial = initialAttribution(location.href, document.referrer));
63
65
  if (options.properties)
64
66
  Object.assign(this.state.props, clean(options.properties));
@@ -213,20 +215,43 @@ export class DaybookAnalytics {
213
215
  optIn() {
214
216
  if (!this.browser)
215
217
  return;
218
+ if (this.family)
219
+ return this.family.answer(true);
216
220
  const wasSending = this.sending;
217
221
  this.state.consent = 'in';
218
- this.save();
219
- if (!wasSending && this.options.autoPageviews !== false)
220
- this.page();
222
+ this.consented(wasSending);
221
223
  }
222
224
  /** The visitor declined: send nothing, forget what was waiting, and keep only the choice. */
223
225
  optOut() {
224
226
  if (!this.browser)
225
227
  return;
228
+ if (this.family)
229
+ return this.family.answer(false);
226
230
  this.state.consent = 'out';
227
231
  this.outbox?.clear();
228
232
  this.save();
229
233
  }
234
+ /**
235
+ * @internal The core's answer changed. `wasSending` is how it was before. Granted, the state is
236
+ * written and the page the visitor is on is counted; taken back, what was waiting is forgotten and
237
+ * nothing of this module's is left in storage, since the core keeps the answer.
238
+ */
239
+ consented(wasSending) {
240
+ if (!this.browser)
241
+ return;
242
+ if (this.sending) {
243
+ this.save();
244
+ if (!wasSending && this.options.autoPageviews !== false)
245
+ this.page();
246
+ }
247
+ else {
248
+ this.outbox?.clear();
249
+ if (this.family)
250
+ this.store.remove(this.stateName);
251
+ else
252
+ this.save();
253
+ }
254
+ }
230
255
  /** Sends what is waiting now. Resolves when it is sent or the API cannot be reached. */
231
256
  flush() {
232
257
  return this.outbox?.flush() ?? Promise.resolve();
@@ -237,9 +262,15 @@ export class DaybookAnalytics {
237
262
  undo();
238
263
  this.outbox?.stop();
239
264
  }
265
+ /** @internal Whether events are sent and the state is kept. */
240
266
  get sending() {
241
267
  if (this.ignored)
242
268
  return false;
269
+ if (this.family) {
270
+ if (this.options.respectDoNotTrack && doNotTrack() && !this.family.answered())
271
+ return false;
272
+ return this.family.consent();
273
+ }
243
274
  if (this.state.consent)
244
275
  return this.state.consent === 'in';
245
276
  if (this.options.optOutByDefault)
@@ -401,15 +432,23 @@ export class DaybookAnalytics {
401
432
  target.addEventListener(type, listener, options);
402
433
  this.cleanup.push(() => target.removeEventListener(type, listener, options));
403
434
  }
435
+ /**
436
+ * What this browser kept under the hub's own key, for a site that has just moved to the family: the
437
+ * visitor stays who they were, with their session, their properties and where they first came from.
438
+ */
439
+ earlier() {
440
+ return this.family ? earlierState(this.store, this.stateName) : null;
441
+ }
404
442
  load(stored = readState(this.store, this.stateName)) {
405
443
  return {
406
- anon: typeof stored?.anon === 'string' && stored.anon ? stored.anon : uuid(),
444
+ anon: typeof stored?.anon === 'string' && stored.anon ? stored.anon : this.family?.anonymousId || uuid(),
407
445
  user: typeof stored?.user === 'string' && stored.user ? stored.user : undefined,
408
446
  props: stored?.props && typeof stored.props === 'object' ? stored.props : {},
409
447
  initial: stored?.initial && typeof stored.initial === 'object' ? stored.initial : undefined,
410
448
  initialSent: stored?.initialSent === true ? true : undefined,
411
449
  session: stored?.session && typeof stored.session.id === 'string' ? stored.session : undefined,
412
- consent: stored?.consent === 'in' || stored?.consent === 'out' ? stored.consent : undefined,
450
+ // In the family the core keeps the answer.
451
+ consent: !this.family && (stored?.consent === 'in' || stored?.consent === 'out') ? stored.consent : undefined,
413
452
  };
414
453
  }
415
454
  /**
@@ -431,6 +470,7 @@ export class DaybookAnalytics {
431
470
  save() {
432
471
  if (!this.browser)
433
472
  return;
473
+ this.family?.onAnonymousId(this.state.anon);
434
474
  if (this.sending)
435
475
  this.store.set(this.stateName, JSON.stringify(this.state));
436
476
  else if (this.state.consent === 'out')
package/dist/daybook.js CHANGED
@@ -1 +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"});})();
1
+ "use strict";(()=>{var M=class{constructor(t=!1){this.enabled=t,this.said=new Set}debug(t,e,...i){this.enabled&&console.log(`[daybook] ${t}: ${e}`,...i)}warn(t,e){let i=`[daybook] ${t}: ${e}`;this.said.has(i)||(this.said.add(i),console.warn(i))}};var nt=Symbol.for("daybook.modules");function E(){var t;let n=globalThis;return(t=n[nt])!=null?t:n[nt]=new Map}function F(n,t){let e=E();e.has(n)||e.set(n,t)}function L(){return[...E().keys()]}function st(){return[...E().values()].map(n=>n())}function rt(){E().clear()}var B="daybook";function ot(){let n={},t=()=>{try{return typeof localStorage!="undefined"?localStorage:null}catch{return null}};return{get(){var e;try{let i=(e=t())==null?void 0:e.getItem(B),s=i?JSON.parse(i):null;if(s&&typeof s=="object"&&!Array.isArray(s))return s}catch{}return{...n}},set(e){var i,s;n={...e};try{Object.keys(e).length===0?(i=t())==null||i.removeItem(B):(s=t())==null||s.setItem(B,JSON.stringify(e))}catch{}}}}function at(){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 ct="0.1.0";var ht="https://api.daybook.team",b=null,O=null,S=class n{constructor(t,e){this.context=t,this.store=e,this.started=[],this.failed={}}static initialize(t,e={}){return b?(typeof t=="string"&&t.trim()!==""&&t.trim()!==b.context.key&&b.context.log.warn("core","initialize was called again with another key; the first one is kept."),Promise.resolve(b)):O!=null?O:O=_t(t,e!=null?e:{}).then(i=>b=i)}static get instance(){if(!b)throw new Error("Daybook is not started. Call `await Daybook.initialize('dbk_\u2026')` once, before using it.");return b}static get isInitialized(){return b!==null}static resetForTesting(t={}){b=null,O=null,t.modules&&rt()}static async create(t,e,i){var Z,Q,tt;let s=e,r=new M(e.logging===!0),a=typeof window!="undefined"&&typeof document!="undefined";t=typeof t=="string"?t.trim():"",t===""?r.warn("core","initialize needs the site's key, dbk_\u2026, from the project's settings in Daybook. Nothing will be sent."):t.startsWith("dbk_")||r.warn("core","the key does not start with dbk_. Daybook takes the site's key from the project's settings, not a key of one hub (dak_ or pmi_); a hub's key works only at that hub's door."),Array.isArray(e.modules)&&(i=i.filter(u=>e.modules.includes(u.name))),i=[...i].sort((u,d)=>{var et,it;return((et=u.order)!=null?et:100)-((it=d.order)!=null?it:100)||u.name.localeCompare(d.name)});let o=ot(),c=a?o.get():{},l=m(c.visitor_id),f=typeof c.tracking_consent=="boolean"?c.tracking_consent:void 0;if(a&&l===void 0&&f===void 0)for(let u of i)try{let d=(Z=u.legacy)==null?void 0:Z.call(u,s[u.name]);l===void 0&&m(d==null?void 0:d.visitorId)!==void 0&&(l=m(d==null?void 0:d.visitorId),r.debug("core",`kept the visitor id the ${u.name} module already had`)),f===void 0&&typeof(d==null?void 0:d.trackingConsent)=="boolean"&&(f=d.trackingConsent)}catch{}l!=null||(l=at());let g=c.user,p=g&&typeof g=="object"&&m(g.id)!==void 0?{id:m(g.id),email:m(g.email),name:m(g.name)}:null,k=m(e.userId);k!==void 0&&k!==(p==null?void 0:p.id)&&(p={id:k});let y=null,G={key:t,serverUrl:((Q=m(e.serverUrl))!=null?Q:ht).replace(/\/+$/,""),visitorId:l,anonymousId:(tt=m(c.anonymous_id))!=null?tt:l,trackingConsent:f!=null?f:e.trackingConsent!==!1,trackingConsentAnswered:f!==void 0,user:p,browser:a,log:r,options:s,setTrackingConsent:u=>y==null?void 0:y.setTrackingConsent(u)};y=new n(G,o),y.save();for(let u of i)try{if(u.name in y)throw new Error(`"${u.name}" is a name of the core's own`);let d=await u.start(G);Object.defineProperty(y,u.name,{value:d,enumerable:!0,configurable:!0}),y.started.push(u),r.debug("core",`the ${u.name} module started`)}catch(d){y.failed[u.name]=J(d),r.warn(u.name,`did not start: ${J(d)}`)}return y.save(),i.length===0&&r.warn("core","no Daybook module is loaded. Import @daybook/analytics or @daybook/feedback beside @daybook/core."),y}get key(){return this.context.key}get visitorId(){return this.context.visitorId}get userId(){var t,e;return(e=(t=this.context.user)==null?void 0:t.id)!=null?e:null}get trackingConsent(){return this.context.trackingConsent}get modules(){return this.started.map(t=>t.name)}get failedModules(){return{...this.failed}}has(t){return this.started.some(e=>e.name===t)}module(t){if(this.has(t))return this[t];let e=this.failed[t];throw new Error(e!==void 0?`Daybook's ${t} module did not start: ${e}`:`Daybook's ${t} module is not loaded. Import @daybook/${t} beside @daybook/core, before Daybook.initialize.`)}identify(t,e={}){let i=typeof t=="string"||typeof t=="number"?String(t).trim():"";if(i===""){this.context.log.warn("core","identify needs the user's id; got an empty one");return}let s={id:i,email:m(e==null?void 0:e.email),name:m(e==null?void 0:e.name)};this.context.user=s,this.save(),this.each("identify",r=>{var a;return(a=r.identify)==null?void 0:a.call(r,s)}),this.save()}reset(){this.context.user=null,this.each("reset",t=>{var e;return(e=t.reset)==null?void 0:e.call(t)}),this.save()}setTrackingConsent(t){t=t===!0,this.context.trackingConsent=t,this.context.trackingConsentAnswered=!0,this.save(),this.each("setTrackingConsent",e=>{var i;return(i=e.setTrackingConsent)==null?void 0:i.call(e,t)}),this.save()}each(t,e){for(let i of this.started)try{e(i)}catch(s){this.context.log.warn(i.name,`${t} did not go through: ${J(s)}`)}}save(){let t=this.context;if(!t.browser)return;if(!t.trackingConsent){this.store.set(t.trackingConsentAnswered?{tracking_consent:!1}:{});return}let e={visitor_id:t.visitorId,anonymous_id:t.anonymousId};t.user&&(e.user=t.user),t.trackingConsentAnswered&&(e.tracking_consent=!0),this.store.set(e)}};S.version=ct;function _t(n,t){return S.create(n,t,st())}function m(n){return typeof n=="string"&&n.trim()!==""?n.trim():void 0}function J(n){return n instanceof Error?n.message:String(n)}function At(n,t=0){let e=f=>{var g,p;return(p=(g=f.exec(n))==null?void 0:g[1])!=null?p:""},i="",s="",r=(f,g)=>{var k;let p=g.exec(n);return p?(i=f,s=(k=p[1])!=null?k:"",!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="",c=/Macintosh/.test(n)&&t>1;/iPhone|iPad|iPod/.test(n)||c?(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 l=/iPad|Tablet/.test(n)||c||/Android/.test(n)&&!/Mobile/.test(n)?"tablet":/Mobi|iPhone|iPod/.test(n)?"mobile":"desktop";return{browser:i,browserVersion:s,os:a,osVersion:o,deviceType:l}}function lt(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 ut(n){var s,r,a;let t=globalThis.navigator,e=At((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,...Ot()},browserVersion:e.browserVersion}}function Ot(){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 c=new Intl.DateTimeFormat(void 0,{hour:"numeric"}).resolvedOptions().hourCycle;c&&(n.hour_cycle=c)}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 ft(){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=It(String((e=s.platform)!=null?e:""),String((i=s.platformVersion)!=null?i:""));return a&&(r.os_version=a),r}catch{return{}}}function It(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 W(){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 Tt=["utm_source","utm_medium","utm_campaign","utm_term","utm_content","gclid","fbclid"];function C(n){let t={};try{let e=new URL(n).searchParams;for(let i of Tt){let s=e.get(i);s&&(t[`$${i}`]=s.slice(0,200))}}catch{}return t}function j(n){if(!n)return"$direct";try{return new URL(n).hostname}catch{return"$direct"}}function dt(n,t){let e={$initial_referrer:t||"$direct",$initial_referring_domain:j(t)};for(let[i,s]of Object.entries(C(n)))e[`$initial_${i.slice(1)}`]=s;return e}function q(n){var e;let t=(e=n.hash)!=null?e:"";return n.pathname+(t.startsWith("#/")||t.startsWith("#!")?t.split("?")[0]:"")}var P=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 I(){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)},names:()=>[...n.keys()]}}function K(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{}},names:()=>{try{return Array.from({length:t.length},(e,i)=>t.key(i)).filter(e=>typeof e=="string")}catch{return[]}}}}function Dt(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{}},names:()=>{try{return document.cookie.split("; ").map(s=>{var r;return(r=s.split("=")[0])!=null?r:""}).filter(Boolean)}catch{return[]}}}}function U(n,t){var e,i;return n==="memory"?I():n==="cookie"||t?(e=Dt(t))!=null?e:I():(i=K("localStorage"))!=null?i:I()}function T(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}}function V(n,t){var i,s,r,a;let e=null;for(let o of n.names()){if(o===t||!/^dbk_[A-Za-z0-9]{1,8}$/.test(o))continue;let c=T(n,o);!c||typeof c.anon!="string"&&c.consent===void 0||(!e||((s=(i=c.session)==null?void 0:i.last)!=null?s:0)>((a=(r=e.session)==null?void 0:r.last)!=null?a:0))&&(e=c)}return e}function gt(n){return`dbk_${n.trim().replace(/^dak_/,"").slice(0,8)}`}var D="0.4.0";var Nt=512*1024,pt=60*1024,H=1e3,R=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<pt})}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}}},z=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>H&&(this.jobs.splice(0,this.jobs.length-H),this.log.warn(`more than ${H} 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(pt,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(Nt);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 c=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:c)/1e3)} s`),this.schedule((e=o.afterMs)!=null?e:c);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 c=JSON.stringify(o.e).length+1;if(r.length>0&&a+c>t)break;r.push(o.e),a+=c}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,c,l;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 f of r)this.log.warn(`"${(c=(o=i[f.index])==null?void 0:o.event)!=null?c:"?"}" was refused (${f.reason}): ${(l=f.message)!=null?l:""}`)}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 v(){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 mt="https://api.daybook.team",Mt="$pageview",Et="$pageleave",Ct="$session_start",jt=1440*6e4,w=class{constructor(t,e){var a,o,c,l,f,g,p;var i;if(this.options=t,this.family=e,this.context={},this.browserVersion="",this.outbox=null,this.cleanup=[],this.current=null,this.referrer=null,this.ignored=!1,!t||typeof t.key!="string"||t.key.trim()==="")throw new Error("@daybook/analytics: `key` is required: the site's key from the project's settings, or the ingest key from Analytics \u2192 Settings.");if(this.log=new P(t.debug===!0),this.browser=typeof window!="undefined"&&typeof document!="undefined",this.stateName=gt(t.key),this.store=this.browser?U((a=t.persistence)!=null?a:"localStorage",t.cookieDomain):I(),this.state={anon:(e==null?void 0:e.anonymousId)||v(),props:{}},!this.browser)return;let s=(o=navigator.userAgent)!=null?o:"";t.ignoreBots!==!1&&lt(s)&&(this.ignored=!0,this.log.debug("this browser says it is a crawler; nothing is sent from it"));let r=ut(t.appVersion);this.context=r.context,this.browserVersion=r.browserVersion,ft().then(k=>Object.assign(this.context,k)),this.state=this.load((c=T(this.store,this.stateName))!=null?c:this.earlier()),(l=(i=this.state).initial)!=null||(i.initial=dt(location.href,document.referrer)),t.properties&&Object.assign(this.state.props,$(t.properties)),this.save(),this.outbox=new z(new R((f=t.apiUrl)!=null?f:mt,t.key.trim()),K("sessionStorage"),`${this.stateName}_queue`,{batchSize:Math.max(1,Math.min(1e3,(g=t.batchSize)!=null?g:50)),flushIntervalMs:Math.max(0,(p=t.flushIntervalMs)!=null?p: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=q(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(Mt,{$title:document.title,$referrer:r||"$direct",$referring_domain:j(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,...C(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?$(e):void 0}}))}}reset(){this.browser&&(this.sync(),this.state={anon:v(),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:$(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:$(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,$(t)),this.save())}unregister(t){this.browser&&(this.sync(),delete this.state.props[t],this.save())}optIn(){if(!this.browser)return;if(this.family)return this.family.answer(!0);let t=this.sending;this.state.consent="in",this.consented(t)}optOut(){var t;if(this.browser){if(this.family)return this.family.answer(!1);this.state.consent="out",(t=this.outbox)==null||t.clear(),this.save()}}consented(t){var e;this.browser&&(this.sending?(this.save(),!t&&this.options.autoPageviews!==!1&&this.page()):((e=this.outbox)==null||e.clear(),this.family?this.store.remove(this.stateName):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.family?this.options.respectDoNotTrack&&W()&&!this.family.answered()?!1:this.family.consent():this.state.consent?this.state.consent==="in":!(this.options.optOutByDefault||this.options.respectDoNotTrack&&W())}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(Ct,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:j(t),...C(location.href)}}emit(t,e,i,s){if(!this.outbox)return;let r={event:t,event_id:v(),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:D,...this.state.initial,...this.state.props,...$(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(c){this.log.warn(`beforeSend threw, so "${t}" was dropped: ${String(c)}`);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)>jt?(this.state.session={id:v(),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(Et,{$url:e.url,$path:e.path,$duration_ms:Math.max(0,t-e.at)})}watchHistory(){let t=()=>setTimeout(()=>{!this.current||this.current.route!==q(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))}earlier(){return this.family?V(this.store,this.stateName):null}load(t=T(this.store,this.stateName)){var e;return{anon:typeof(t==null?void 0:t.anon)=="string"&&t.anon?t.anon:((e=this.family)==null?void 0:e.anonymousId)||v(),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:!this.family&&((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=T(this.store,this.stateName);typeof(t==null?void 0:t.anon)=="string"&&t.anon!==""&&(this.state=this.load(t))}save(){var t;this.browser&&((t=this.family)==null||t.onAnonymousId(this.state.anon),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 $(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 X=class{constructor(){this.name="analytics",this.order=10,this.client=null,this.sending=!1}legacy(t){var s;if(typeof window=="undefined"||typeof document=="undefined")return null;let e=t!=null?t:{},i=V(U((s=e.persistence)!=null?s:"localStorage",e.cookieDomain),"");return i?{visitorId:typeof i.anon=="string"?i.anon:void 0,trackingConsent:i.consent==="in"?!0:i.consent==="out"?!1:void 0}:null}start(t){var s,r,a;if(t.key==="")throw new Error("there is no key to send events with");let e=(s=t.options.analytics)!=null?s:{},i=new w({...e,key:t.key,apiUrl:(r=e.apiUrl)!=null?r:t.serverUrl,debug:(a=e.debug)!=null?a:t.log.enabled},{consent:()=>t.trackingConsent,answered:()=>t.trackingConsentAnswered,answer:o=>t.setTrackingConsent(o),anonymousId:t.anonymousId,onAnonymousId:o=>{t.anonymousId=o}});return this.client=i,this.sending=i.sending,t.anonymousId=i.distinctId,t.user&&i.userId!==t.user.id&&this.identify(t.user),i}identify(t){var i;let e={};t.email&&(e.$email=t.email),t.name&&(e.$name=t.name),(i=this.client)==null||i.identify(t.id,Object.keys(e).length>0?e:void 0)}reset(){var t;(t=this.client)==null||t.reset()}setTrackingConsent(){var e,i;let t=this.sending;this.sending=((e=this.client)==null?void 0:e.sending)===!0,(i=this.client)==null||i.consented(t)}};F("analytics",()=>new X);var _=null;function yt(n){return _?(n!=null&&n.key&&n.key.trim()!==_.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."),_):(_=new w(n),_)}function bt(){return _}var x=globalThis,A=typeof document!="undefined"?document.currentScript:null,Y=["track","page","register","unregister","setPersonProperties","setPersonPropertiesOnce","optIn","optOut","flush"];function xt(){let n=x.daybook;return Array.isArray(n==null?void 0:n.q)?n.q:[]}function vt(n){let t=xt(),e=yt(n);x.daybook=e;for(let[i,s]of t){let r=e[i];typeof r=="function"&&r.apply(e,s)}return e}function Pt(n){return new Promise(t=>{try{let e=document.createElement("script");e.async=!0,e.src=new URL(`${n}.js`,(A==null?void 0:A.src)||location.href).href,e.onload=()=>t(),e.onerror=()=>{console.warn(`[daybook] ${n}: its script could not be loaded from ${e.src}; the other modules start without it`),t()},document.head.appendChild(e)}catch{t()}})}async function $t(n,t={}){var a;let e=xt(),i=(a=t.modules)!=null?a:["analytics"];await Promise.all(i.filter(o=>/^[a-z]+$/.test(o)&&!L().includes(o)).map(Pt));let s=await S.initialize(n,{...t,modules:i}),r=s;for(let o of Y)o in r||(r[o]=(...c)=>wt(r.analytics,o,c));x.daybook=s;for(let[o,c]of e)try{let l=o.lastIndexOf(".");wt(l<0?r:r[o.slice(0,l)],o.slice(l+1),c)}catch(l){console.warn(`[daybook] ${o} was queued before the script loaded and failed: ${String(l)}`)}return s}function Ut(){let n=[],t=i=>(...s)=>{n.push([i,s])},e=(i,s)=>Object.fromEntries(s.map(r=>[r,t(i+r)]));return{q:n,...e("",["identify","reset","setTrackingConsent",...Y]),analytics:e("analytics.",Y),feedback:e("feedback.",["open","start","stop","authenticate"])}}function wt(n,t,e){let i=n==null?void 0:n[t];return typeof i=="function"?i.apply(n,e):void 0}x.DaybookAnalytics={init:vt,getAnalytics:bt,DaybookAnalytics:w,version:D};x.Daybook={initialize:$t,version:S.version};var h=A==null?void 0:A.dataset,N=n=>n!==void 0&&n!=="false",kt,St;if(h!=null&&h.key){let n={apiUrl:h.apiUrl,appVersion:h.appVersion,autoPageviews:h.pageviews!=="false",pageleave:h.pageleave!=="false",persistence:h.persistence,cookieDomain:h.cookieDomain,respectDoNotTrack:N(h.respectDnt),debug:N(h.debug)};h.key.trim().startsWith("dbk_")||h.modules!==void 0?(Array.isArray((kt=x.daybook)==null?void 0:kt.q)||(x.daybook=Ut()),$t(h.key,{modules:((St=h.modules)!=null?St:"analytics").split(",").map(t=>t.trim()).filter(Boolean),serverUrl:h.apiUrl,userId:h.userId,trackingConsent:!N(h.optOutByDefault)&&h.trackingConsent!=="false",logging:N(h.debug),analytics:n,feedback:{app:h.appVersion?{version:h.appVersion}:void 0,surface:h.surface}})):vt({...n,key:h.key,optOutByDefault:N(h.optOutByDefault)})}})();
package/dist/index.d.ts CHANGED
@@ -1,16 +1,26 @@
1
1
  import { DaybookAnalytics } from './client.js';
2
+ import './module.js';
2
3
  import type { AnalyticsOptions } from './types.js';
4
+ export type { AnalyticsModuleOptions } from './module.js';
3
5
  export { DaybookAnalytics, DEFAULT_API_URL } from './client.js';
4
6
  export { SDK_VERSION } from './version.js';
5
7
  export type { AnalyticsEvent, AnalyticsOptions, EventContext, Persistence, Properties, PropertyValue, } from './types.js';
6
8
  /**
7
- * Starts analytics for this site, once:
9
+ * Starts analytics by itself, once: the way before Daybook's core, kept for sites that use it.
8
10
  *
9
11
  * import { init } from '@daybook/analytics'
10
12
  *
11
13
  * const analytics = init({ key: 'dak_…' })
12
14
  * analytics.track('signed_up', { plan: 'pro' })
13
15
  *
16
+ * A new site starts the core instead, with the site's one key, and analytics starts with it:
17
+ *
18
+ * import { Daybook } from '@daybook/core'
19
+ * import '@daybook/analytics'
20
+ *
21
+ * const daybook = await Daybook.initialize('dbk_…')
22
+ * daybook.analytics.track('signed_up', { plan: 'pro' })
23
+ *
14
24
  * A second call returns the same instance, so a component that re-renders, a hot reload or a provider
15
25
  * mounted twice cannot start a second one that sends every page view again.
16
26
  */
package/dist/index.js CHANGED
@@ -1,15 +1,24 @@
1
1
  import { DaybookAnalytics } from './client.js';
2
+ import './module.js';
2
3
  export { DaybookAnalytics, DEFAULT_API_URL } from './client.js';
3
4
  export { SDK_VERSION } from './version.js';
4
5
  let shared = null;
5
6
  /**
6
- * Starts analytics for this site, once:
7
+ * Starts analytics by itself, once: the way before Daybook's core, kept for sites that use it.
7
8
  *
8
9
  * import { init } from '@daybook/analytics'
9
10
  *
10
11
  * const analytics = init({ key: 'dak_…' })
11
12
  * analytics.track('signed_up', { plan: 'pro' })
12
13
  *
14
+ * A new site starts the core instead, with the site's one key, and analytics starts with it:
15
+ *
16
+ * import { Daybook } from '@daybook/core'
17
+ * import '@daybook/analytics'
18
+ *
19
+ * const daybook = await Daybook.initialize('dbk_…')
20
+ * daybook.analytics.track('signed_up', { plan: 'pro' })
21
+ *
13
22
  * A second call returns the same instance, so a component that re-renders, a hot reload or a provider
14
23
  * mounted twice cannot start a second one that sends every page view again.
15
24
  */
@@ -0,0 +1,17 @@
1
+ import { DaybookAnalytics } from './client.js';
2
+ import type { AnalyticsOptions } from './types.js';
3
+ /**
4
+ * What `Daybook.initialize` takes under `analytics`: every option of analytics but the ones the core
5
+ * holds. The key and the address are the core's, and consent is `trackingConsent`.
6
+ */
7
+ export type AnalyticsModuleOptions = Omit<AnalyticsOptions, 'key' | 'optOutByDefault'>;
8
+ declare module '@daybook/core' {
9
+ interface Daybook {
10
+ /** Analytics' door: events, page views, the person's properties. From `@daybook/analytics`. */
11
+ readonly analytics: DaybookAnalytics;
12
+ }
13
+ interface DaybookOptions {
14
+ /** What only analytics needs: page views, where its state is kept, `beforeSend`. */
15
+ analytics?: AnalyticsModuleOptions;
16
+ }
17
+ }
package/dist/module.js ADDED
@@ -0,0 +1,70 @@
1
+ import { registerModule } from '@daybook/core';
2
+ import { DaybookAnalytics } from './client.js';
3
+ import { earlierState, storeFor } from './storage.js';
4
+ /**
5
+ * Analytics as a module of Daybook's core (PM-R-0110, PM-T-0971): importing `@daybook/analytics`
6
+ * registers it, `Daybook.initialize` starts it with the site's one key, and `daybook.analytics` is the
7
+ * same object `init({ key })` used to answer.
8
+ */
9
+ class AnalyticsModule {
10
+ constructor() {
11
+ this.name = 'analytics';
12
+ /** First: it owns the anonymous id the other modules may send. */
13
+ this.order = 10;
14
+ this.client = null;
15
+ this.sending = false;
16
+ }
17
+ /**
18
+ * Before the family, analytics kept the visitor by itself, under its hub key's own name. A site
19
+ * that has that keeps the visitor's id and the answer they gave about being measured.
20
+ */
21
+ legacy(options) {
22
+ if (typeof window === 'undefined' || typeof document === 'undefined')
23
+ return null;
24
+ const o = (options ?? {});
25
+ const earlier = earlierState(storeFor(o.persistence ?? 'localStorage', o.cookieDomain), '');
26
+ if (!earlier)
27
+ return null;
28
+ return {
29
+ visitorId: typeof earlier.anon === 'string' ? earlier.anon : undefined,
30
+ trackingConsent: earlier.consent === 'in' ? true : earlier.consent === 'out' ? false : undefined,
31
+ };
32
+ }
33
+ start(context) {
34
+ if (context.key === '')
35
+ throw new Error('there is no key to send events with');
36
+ const o = (context.options.analytics ?? {});
37
+ const client = new DaybookAnalytics({ ...o, key: context.key, apiUrl: o.apiUrl ?? context.serverUrl, debug: o.debug ?? context.log.enabled }, {
38
+ consent: () => context.trackingConsent,
39
+ answered: () => context.trackingConsentAnswered,
40
+ answer: (granted) => context.setTrackingConsent(granted),
41
+ anonymousId: context.anonymousId,
42
+ onAnonymousId: (id) => { context.anonymousId = id; },
43
+ });
44
+ this.client = client;
45
+ this.sending = client.sending;
46
+ context.anonymousId = client.distinctId;
47
+ // The site may already know who is signed in when it starts.
48
+ if (context.user && client.userId !== context.user.id)
49
+ this.identify(context.user);
50
+ return client;
51
+ }
52
+ identify(user) {
53
+ const person = {};
54
+ if (user.email)
55
+ person.$email = user.email;
56
+ if (user.name)
57
+ person.$name = user.name;
58
+ this.client?.identify(user.id, Object.keys(person).length > 0 ? person : undefined);
59
+ }
60
+ reset() {
61
+ this.client?.reset();
62
+ }
63
+ setTrackingConsent() {
64
+ // The core has changed its answer already, so how it was before is remembered here.
65
+ const before = this.sending;
66
+ this.sending = this.client?.sending === true;
67
+ this.client?.consented(before);
68
+ }
69
+ }
70
+ registerModule('analytics', () => new AnalyticsModule());
package/dist/storage.d.ts CHANGED
@@ -4,6 +4,8 @@ export interface Store {
4
4
  get(name: string): string | null;
5
5
  set(name: string, value: string): void;
6
6
  remove(name: string): void;
7
+ /** Every name kept here, so a state written under another key can be found (PM-T-0971). */
8
+ names(): string[];
7
9
  }
8
10
  /** What the SDK remembers about this browser between page loads. */
9
11
  export interface State {
@@ -42,3 +44,12 @@ export declare function cookieStore(domain?: string): Store | null;
42
44
  export declare function storeFor(persistence: Persistence, cookieDomain?: string): Store;
43
45
  /** A stored state, or null when there is none or it is not one. */
44
46
  export declare function readState(store: Store, name: string): Partial<State> | null;
47
+ /**
48
+ * The state this browser kept under another key of the same site, newest first by its session: what a
49
+ * site that started analytics with its hub key (`dak_…`) has when it moves to the site's one key
50
+ * (`dbk_…`). The stored name carries the key's first letters, so a new key is a new name, and without
51
+ * this the visitor would be somebody new (PM-T-0971).
52
+ */
53
+ export declare function earlierState(store: Store, ownName: string): Partial<State> | null;
54
+ /** The name a key's state is kept under: two projects on one site keep apart by the key's first letters. */
55
+ export declare function stateNameOf(key: string): string;