usebecky 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/README.md +701 -2
  2. package/dist/analytics/client.d.ts +219 -0
  3. package/dist/analytics/client.js +923 -0
  4. package/dist/analytics/cmp.d.ts +20 -0
  5. package/dist/analytics/cmp.js +166 -0
  6. package/dist/analytics/context.d.ts +29 -0
  7. package/dist/analytics/context.js +97 -0
  8. package/dist/auth/client.d.ts +401 -0
  9. package/dist/auth/client.js +1081 -0
  10. package/dist/auth/webauthn.d.ts +18 -0
  11. package/dist/auth/webauthn.js +138 -0
  12. package/dist/cli/ai.d.ts +54 -0
  13. package/dist/cli/ai.js +202 -0
  14. package/dist/cli/analytics.d.ts +53 -0
  15. package/dist/cli/analytics.js +357 -0
  16. package/dist/cli/config.d.ts +75 -0
  17. package/dist/cli/config.js +718 -0
  18. package/dist/cli/db.d.ts +48 -0
  19. package/dist/cli/db.js +215 -0
  20. package/dist/cli/deploy-api.d.ts +168 -0
  21. package/dist/cli/deploy-api.js +177 -0
  22. package/dist/cli/deploy-ci.d.ts +15 -0
  23. package/dist/cli/deploy-ci.js +54 -0
  24. package/dist/cli/deploy-detect.d.ts +64 -0
  25. package/dist/cli/deploy-detect.js +249 -0
  26. package/dist/cli/deploy-files.d.ts +112 -0
  27. package/dist/cli/deploy-files.js +778 -0
  28. package/dist/cli/deploy.d.ts +10 -0
  29. package/dist/cli/deploy.js +430 -0
  30. package/dist/cli/emails.d.ts +29 -0
  31. package/dist/cli/emails.js +122 -0
  32. package/dist/cli/framework.d.ts +135 -0
  33. package/dist/cli/framework.js +459 -0
  34. package/dist/cli/functions.d.ts +59 -0
  35. package/dist/cli/functions.js +426 -0
  36. package/dist/cli/hosting.d.ts +4 -0
  37. package/dist/cli/hosting.js +532 -0
  38. package/dist/cli/index.d.ts +2 -0
  39. package/dist/cli/index.js +9 -0
  40. package/dist/cli/payments.d.ts +35 -0
  41. package/dist/cli/payments.js +176 -0
  42. package/dist/cli/push.d.ts +36 -0
  43. package/dist/cli/push.js +172 -0
  44. package/dist/cli/run.d.ts +65 -0
  45. package/dist/cli/run.js +850 -0
  46. package/dist/cli/social.d.ts +52 -0
  47. package/dist/cli/social.js +532 -0
  48. package/dist/cli/tokens.d.ts +28 -0
  49. package/dist/cli/tokens.js +114 -0
  50. package/dist/cli/ui.d.ts +38 -0
  51. package/dist/cli/ui.js +140 -0
  52. package/dist/client.d.ts +94 -0
  53. package/dist/client.js +156 -0
  54. package/dist/db/query.d.ts +162 -0
  55. package/dist/db/query.js +336 -0
  56. package/dist/db/types.d.ts +93 -0
  57. package/dist/db/types.js +4 -0
  58. package/dist/forms/client.d.ts +65 -0
  59. package/dist/forms/client.js +106 -0
  60. package/dist/functions/client.d.ts +37 -0
  61. package/dist/functions/client.js +76 -0
  62. package/dist/index.d.ts +17 -0
  63. package/dist/index.js +16 -0
  64. package/dist/lib/dashboard-paths.d.ts +4 -0
  65. package/dist/lib/dashboard-paths.js +8 -0
  66. package/dist/lib/env.d.ts +9 -0
  67. package/dist/lib/env.js +55 -0
  68. package/dist/lib/errors.d.ts +22 -0
  69. package/dist/lib/errors.js +90 -0
  70. package/dist/lib/hosted.d.ts +2 -0
  71. package/dist/lib/hosted.js +7 -0
  72. package/dist/lib/http.d.ts +59 -0
  73. package/dist/lib/http.js +172 -0
  74. package/dist/lib/jwt.d.ts +1 -0
  75. package/dist/lib/jwt.js +31 -0
  76. package/dist/lib/locale.d.ts +12 -0
  77. package/dist/lib/locale.js +51 -0
  78. package/dist/lib/pkce.d.ts +20 -0
  79. package/dist/lib/pkce.js +124 -0
  80. package/dist/lib/storage-adapter.d.ts +15 -0
  81. package/dist/lib/storage-adapter.js +91 -0
  82. package/dist/lib/types.d.ts +339 -0
  83. package/dist/lib/types.js +1 -0
  84. package/dist/newsletter/client.d.ts +140 -0
  85. package/dist/newsletter/client.js +85 -0
  86. package/dist/payments/client.d.ts +352 -0
  87. package/dist/payments/client.js +323 -0
  88. package/dist/push/client.d.ts +110 -0
  89. package/dist/push/client.js +179 -0
  90. package/dist/realtime/client.d.ts +131 -0
  91. package/dist/realtime/client.js +513 -0
  92. package/dist/server/analytics.d.ts +176 -0
  93. package/dist/server/analytics.js +49 -0
  94. package/dist/server/cache.d.ts +74 -0
  95. package/dist/server/cache.js +154 -0
  96. package/dist/server/emails.d.ts +142 -0
  97. package/dist/server/emails.js +123 -0
  98. package/dist/server/events.d.ts +357 -0
  99. package/dist/server/events.js +219 -0
  100. package/dist/server/functions.d.ts +40 -0
  101. package/dist/server/functions.js +1 -0
  102. package/dist/server/http-utils.d.ts +10 -0
  103. package/dist/server/http-utils.js +115 -0
  104. package/dist/server/index.d.ts +195 -0
  105. package/dist/server/index.js +314 -0
  106. package/dist/server/payments.d.ts +218 -0
  107. package/dist/server/payments.js +150 -0
  108. package/dist/server/push.d.ts +85 -0
  109. package/dist/server/push.js +37 -0
  110. package/dist/server/usage.d.ts +43 -0
  111. package/dist/server/usage.js +8 -0
  112. package/dist/storage/client.d.ts +143 -0
  113. package/dist/storage/client.js +224 -0
  114. package/package.json +52 -4
  115. package/skill/usebecky/SKILL.md +339 -0
  116. package/skill/usebecky/references/access-rules.md +307 -0
  117. package/skill/usebecky/references/addons.md +68 -0
  118. package/skill/usebecky/references/analytics.md +166 -0
  119. package/skill/usebecky/references/android.md +434 -0
  120. package/skill/usebecky/references/auth.md +379 -0
  121. package/skill/usebecky/references/cache.md +51 -0
  122. package/skill/usebecky/references/components.md +127 -0
  123. package/skill/usebecky/references/emails.md +105 -0
  124. package/skill/usebecky/references/expo.md +147 -0
  125. package/skill/usebecky/references/functions.md +99 -0
  126. package/skill/usebecky/references/hosting.md +119 -0
  127. package/skill/usebecky/references/http-api.md +233 -0
  128. package/skill/usebecky/references/ios.md +355 -0
  129. package/skill/usebecky/references/payments.md +493 -0
  130. package/skill/usebecky/references/realtime.md +143 -0
  131. package/skill/usebecky/references/scheduled-jobs.md +82 -0
  132. package/skill/usebecky/references/sdk.md +838 -0
  133. package/skill/usebecky/references/storage.md +210 -0
  134. package/skill/usebecky/references/templates.md +191 -0
  135. package/skill/usebecky/references/wordpress.md +87 -0
@@ -0,0 +1,923 @@
1
+ // Product analytics for your app: `baas.analytics.track('signed_up')`, `page()`, `identify()`.
2
+ // Events are queued and sent in batches (every 5 seconds or 20 events) to POST /analytics/v1/events,
3
+ // and handed to navigator.sendBeacon / fetch keepalive when the page is hidden or closed.
4
+ // Nothing in here ever throws into your app; bad input is dropped with one console warning.
5
+ //
6
+ // Two modes (option `storage`, like the website script's data-storage attribute):
7
+ // 'none' privacy mode, the default in browsers: no visitor or visit id is sent and nothing is kept
8
+ // on the device (only an opt-out, when the person asks for one). Events carry the page, the
9
+ // hostname and the landing page's UTM parameters; the browser adds its user agent and
10
+ // Accept-Language. The server recognizes the visitor for one day (hash of a daily random
11
+ // salt, IP, user agent and hostname) and continues the visit for 30 minutes of inactivity.
12
+ // 'local' the default in React Native and Node: a random anonymous id, the session and the date of
13
+ // the first visit are kept in storage, and each event also carries the visit context from
14
+ // context.ts: primary language, timezone, screen size bucket, the landing page's UTM
15
+ // parameters (kept for the session) and `is_new_visitor` on a session's first event. In a
16
+ // browser in the EU this usually needs consent. Nothing is written to the device's storage
17
+ // until analytics is enabled and something is tracked.
18
+ // The wire format is the same in both: events without anonymous_id and session_id get server-made ones.
19
+ //
20
+ // consent(true) (from the site's consent banner) switches a browser in privacy mode to 'local' when the
21
+ // project has "Remember returning visitors" on (GET /analytics/v1/config): the choice is kept (key
22
+ // -consent, shared with the website script), the id is replaced after 13 months, and events carry
23
+ // `consent: true` (stored in privacy mode by the server while the setting is off). consent(false) deletes
24
+ // the ids again. The last call wins: a config answer that arrives after a later consent() call is ignored,
25
+ // and only an explicit `remember_visitors: false` (never a failed request) makes the device forget.
26
+ //
27
+ // "Follow my cookie banner" (Analytics → Settings, consent_source 'cmp' in the config, also switched on by a cookie
28
+ // banner extension like cookiepass): in a browser the client asks the config once it starts and then takes the
29
+ // visitor's answer from the site's cookie banner (cmp.ts: GPC, cookiepass, Google Consent Mode, IAB TCF) and calls
30
+ // consent(true / false) itself whenever it changes.
31
+ //
32
+ // Server-side tagging (an extension that forwards purchases, sign-ups and leads to the site's Google Tag Manager
33
+ // server): payments, sign-up and forms send consentRef() along: the visitor's latest answer (consent(), the banner,
34
+ // or one kept from an earlier page), "no" with Global Privacy Control, and with a yes the Google Analytics client id
35
+ // from the _ga cookie when the project asks for it (send_ga_client_id). No answer: nothing is sent, and the server
36
+ // doesn't forward that event.
37
+ //
38
+ // "Ignore my visits" (Analytics → Settings): the site owner's browser keeps `-analytics-ignore = "1"` (set by
39
+ // opening the site with #usebecky-ignore, cleared with #usebecky-count; shared with the website script).
40
+ // While it is there nothing is sent. It is separate from the visitor's opt-out (disable()/enable()).
41
+ //
42
+ // Works in Node too (track, identify, flush). page() without a path needs a browser.
43
+ import { UseBeckyError } from "../lib/errors.js";
44
+ import { readGaClientId, watchConsentSignals } from "./cmp.js";
45
+ import { cleanUtm, DATE, onVisitorDevice, today, utmFromSearch, visitContext } from "./context.js";
46
+ const g = globalThis;
47
+ /** Limits enforced by the API (POST /analytics/v1/events). */
48
+ export const ANALYTICS_LIMITS = { maxBatch: 50, maxNameLength: 100, maxPropsBytes: 4096 };
49
+ const BEACON_MAX_BYTES = 60_000;
50
+ /** A remembered visitor gets a new id after 13 months (like a consent cookie's longest life). */
51
+ const MAX_ID_AGE_MS = 395 * 24 * 3600_000;
52
+ const MAX_RETRY_DELAY_MS = 60_000;
53
+ function warn(msg) {
54
+ try {
55
+ g.console?.warn?.(msg);
56
+ }
57
+ catch { }
58
+ }
59
+ function uuid() {
60
+ try {
61
+ if (typeof g.crypto?.randomUUID === 'function')
62
+ return g.crypto.randomUUID();
63
+ }
64
+ catch { }
65
+ let s = '';
66
+ for (let i = 0; i < 32; i++)
67
+ s += Math.floor(Math.random() * 16).toString(16);
68
+ return `${s.slice(0, 8)}-${s.slice(8, 12)}-4${s.slice(13, 16)}-a${s.slice(17, 20)}-${s.slice(20, 32)}`;
69
+ }
70
+ function inBrowser() {
71
+ return typeof g.window === 'object' && g.window !== null && typeof g.document === 'object' && g.document !== null;
72
+ }
73
+ /** True when the browser asks not to be tracked: Do Not Track, or Global Privacy Control (like the website script). */
74
+ export function doNotTrack() {
75
+ if (g.navigator?.globalPrivacyControl === true)
76
+ return true;
77
+ const v = g.navigator?.doNotTrack ?? g.window?.doNotTrack ?? g.navigator?.msDoNotTrack;
78
+ return v === '1' || v === 'yes';
79
+ }
80
+ function isThenable(v) {
81
+ return !!v && typeof v.then === 'function';
82
+ }
83
+ function isPlainObject(v) {
84
+ return !!v && typeof v === 'object' && !Array.isArray(v) && (Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null);
85
+ }
86
+ function byteLength(s) {
87
+ try {
88
+ if (typeof g.TextEncoder === 'function')
89
+ return new g.TextEncoder().encode(s).length;
90
+ }
91
+ catch { }
92
+ return s.length;
93
+ }
94
+ export class AnalyticsClient {
95
+ http;
96
+ key;
97
+ storage;
98
+ keys;
99
+ getSession;
100
+ opts;
101
+ /** Privacy mode: no ids, nothing read from or written to storage except the opt-out and consent flags. */
102
+ privacy;
103
+ /** `storage: 'none'` was set explicitly: consent() never switches to remembering. */
104
+ alwaysPrivate;
105
+ /** The visitor agreed to be remembered and the project remembers visitors (consent()). */
106
+ consented = false;
107
+ disabledByConfig;
108
+ optedOut = false;
109
+ /** The site owner's "Ignore my visits" flag in this browser (-analytics-ignore). */
110
+ ignored = false;
111
+ /** Counts consent() calls: a config answer only applies to the latest one. */
112
+ consentCalls = 0;
113
+ /** The visitor's latest answer (consent(), the cookie banner, or a consent kept from an earlier page). */
114
+ answer = undefined;
115
+ /** GET /analytics/v1/config, asked once per page load in a browser (null when it failed). */
116
+ projectConfig = null;
117
+ /** Follows the site's cookie banner while the project says consent_source 'cmp' (cmp.ts). */
118
+ banner = null;
119
+ /** The banner's answer last handed to consent() (only while collecting). */
120
+ bannerApplied = undefined;
121
+ /** enable()/disable() was called, so the stored opt-out (loaded later from async storage) must not override it. */
122
+ optOutDecided = false;
123
+ queue = [];
124
+ timer = null;
125
+ retryDelay = 0;
126
+ flushing = null;
127
+ anonId = null;
128
+ session = null;
129
+ /** Date this device's anonymous id was first used ("YYYY-MM-DD"); null = no session yet (a new
130
+ * visitor); undefined = not loaded from (async) storage yet. */
131
+ firstSeen = undefined;
132
+ /** UTM parameters in the address when this page loaded; used by the session the page starts. */
133
+ landingUtm;
134
+ context = null;
135
+ /** Ids created in memory but not yet written to storage: nothing is stored on the device until
136
+ * analytics is enabled and something is tracked (e.g. not before cookie consent). */
137
+ unsaved = { anon: false, firstSeen: false };
138
+ /** Last access token seen per user, so events tracked before a sign-out still go out as that user. */
139
+ tokens = new Map();
140
+ lastPath = null;
141
+ referrerSent = false;
142
+ started = false;
143
+ warned = new Set();
144
+ /** Resolves once the stored anonymous id / opt-out are loaded (async storage like AsyncStorage). */
145
+ ready;
146
+ constructor(init) {
147
+ this.http = init.http;
148
+ this.key = init.key;
149
+ this.storage = init.storage;
150
+ this.getSession = init.getSession;
151
+ this.keys = {
152
+ anon: `${init.storageKey}-anon-id`,
153
+ session: `${init.storageKey}-session`,
154
+ optOut: `${init.storageKey}-analytics-optout`,
155
+ ignore: `${init.storageKey}-analytics-ignore`,
156
+ firstSeen: `${init.storageKey}-first-seen`,
157
+ consent: `${init.storageKey}-consent`,
158
+ };
159
+ // Read now: single-page apps often remove ?utm_... from the address right after loading.
160
+ this.landingUtm = inBrowser() ? utmFromSearch(g.location?.search) : null;
161
+ const o = init.options === false ? { enabled: false } : init.options === true || !init.options ? {} : init.options;
162
+ this.disabledByConfig = o.enabled === false;
163
+ this.opts = {
164
+ autoPageviews: o.autoPageviews ?? false,
165
+ respectDoNotTrack: o.respectDoNotTrack ?? true,
166
+ flushInterval: Math.max(250, o.flushInterval ?? 5000),
167
+ batchSize: Math.min(ANALYTICS_LIMITS.maxBatch, Math.max(1, o.batchSize ?? 20)),
168
+ maxQueueSize: Math.max(1, o.maxQueueSize ?? 500),
169
+ sessionTimeoutMinutes: Math.max(1, o.sessionTimeoutMinutes ?? 30),
170
+ storage: o.storage === 'none' || o.storage === 'local' ? o.storage : inBrowser() && !onVisitorDevice(false) ? 'none' : 'local',
171
+ };
172
+ this.privacy = this.opts.storage === 'none';
173
+ this.alwaysPrivate = o.storage === 'none';
174
+ this.ready = this.load();
175
+ this.loadIgnored();
176
+ if (this.enabled)
177
+ this.start();
178
+ }
179
+ // ---- public API ---------------------------------------------------------------------------
180
+ /** True when events are being collected (not disabled, not opted out, not the site owner's ignored browser, not blocked by Do Not Track or Global Privacy Control). */
181
+ get enabled() {
182
+ return !this.disabledByConfig && !this.optedOut && !this.ignored && !(this.opts.respectDoNotTrack && doNotTrack());
183
+ }
184
+ /**
185
+ * Record that something happened, e.g. `track('signed_up', { plan: 'pro' })`.
186
+ * `event`: up to 100 characters, not starting with "$". `props`: a JSON object up to 4 KB.
187
+ */
188
+ track(event, props) {
189
+ this.safely(() => this.enqueue(event, props, {}, false));
190
+ }
191
+ /**
192
+ * Record a page view (stored as the event `$pageview`). `path` defaults to `location.pathname`;
193
+ * the page title and, for the first page of a visit, the external referrer are sent too.
194
+ * Outside a browser, pass the path: `page('/pricing')`.
195
+ */
196
+ page(path, props) {
197
+ this.safely(() => {
198
+ if (!this.enabled)
199
+ return;
200
+ const loc = g.location;
201
+ const p = typeof path === 'string' && path ? path : typeof loc?.pathname === 'string' ? loc.pathname : '';
202
+ if (!p) {
203
+ this.warnOnce('page-path', '[usebecky] analytics.page() needs a browser to know the current page. Pass the path instead: baas.analytics.page("/pricing").');
204
+ return;
205
+ }
206
+ const extra = { path: p };
207
+ const title = g.document?.title;
208
+ if (typeof title === 'string' && title)
209
+ extra.title = title.slice(0, 300);
210
+ if (!this.referrerSent) {
211
+ this.referrerSent = true;
212
+ const ref = this.externalReferrer();
213
+ if (ref)
214
+ extra.referrer = ref;
215
+ }
216
+ this.lastPath = typeof loc?.pathname === 'string' && !path ? loc.pathname : p;
217
+ this.enqueue('$pageview', props, extra, true);
218
+ });
219
+ }
220
+ /**
221
+ * Describe the current person, e.g. `identify({ plan: 'pro' })` after sign-in. The signed-in user
222
+ * id is attached automatically. Stored as the event `$identify` (not counted in event totals).
223
+ */
224
+ identify(traits) {
225
+ this.safely(() => this.enqueue('$identify', traits, {}, true));
226
+ }
227
+ /** Send every queued event now. Await it before a Node script exits. Never throws.
228
+ * `sent` counts the events delivered by this call, including a send that was already in progress. */
229
+ async flush() {
230
+ try {
231
+ let carried = 0;
232
+ while (this.flushing)
233
+ carried += (await this.flushing.catch(() => null))?.data?.sent ?? 0;
234
+ const run = this.sendQueued();
235
+ this.flushing = run;
236
+ try {
237
+ const result = await run;
238
+ return result.error ? result : { data: { sent: result.data.sent + carried }, error: null };
239
+ }
240
+ finally {
241
+ if (this.flushing === run)
242
+ this.flushing = null;
243
+ }
244
+ }
245
+ catch (err) {
246
+ return { data: null, error: new UseBeckyError({ code: 'analytics_error', message: `Could not send analytics events: ${err?.message ?? err}`, status: 0 }) };
247
+ }
248
+ }
249
+ /** Stop collecting and drop queued events. Remembered on this device (an opt-out) until enable(). */
250
+ disable() {
251
+ this.safely(() => {
252
+ this.optedOut = true;
253
+ this.optOutDecided = true;
254
+ this.queue = [];
255
+ this.clearTimer();
256
+ this.write(this.keys.optOut, '1');
257
+ });
258
+ }
259
+ /** Start collecting again (also turns on a client created with `analytics: false`). Do Not Track still applies unless `respectDoNotTrack: false`. */
260
+ enable() {
261
+ this.safely(() => {
262
+ this.optedOut = false;
263
+ this.optOutDecided = true;
264
+ this.disabledByConfig = false;
265
+ this.remove(this.keys.optOut);
266
+ if (this.enabled)
267
+ this.start();
268
+ });
269
+ }
270
+ /**
271
+ * The visitor's answer in your consent banner. `true`: when the project has "Remember returning visitors"
272
+ * on (Analytics → Settings), a random id is kept on this device so returning visitors are known across
273
+ * days (replaced after 13 months); otherwise nothing changes (privacy mode). `false`: the id is deleted
274
+ * and privacy mode is used again. The website script on the same site shares the choice.
275
+ */
276
+ consent(granted) {
277
+ this.safely(() => {
278
+ const call = ++this.consentCalls;
279
+ this.answer = !!granted;
280
+ if (!granted)
281
+ return this.forgetDevice();
282
+ if (this.alwaysPrivate)
283
+ return;
284
+ void this.checkConsent(true, call);
285
+ });
286
+ }
287
+ /**
288
+ * The visit to send along with a checkout or payment form (see `VisitRef`), or undefined: when the visitor opted out,
289
+ * Do Not Track applies, this is the site owner's ignored browser, or there is no visit to point at (a Node script, or
290
+ * a remembered id that was never used for an event). It doesn't depend on `enabled`: the website script may be the
291
+ * one counting visits while the SDK only handles sign-in and payments. Used by `baas.payments`; never throws.
292
+ */
293
+ visitRef() {
294
+ try {
295
+ if (this.optedOut || this.ignored || (this.opts.respectDoNotTrack && doNotTrack()))
296
+ return undefined;
297
+ if (!onVisitorDevice(inBrowser()))
298
+ return undefined;
299
+ if (!this.privacy && this.anonId && !this.unsaved.anon) {
300
+ return this.session?.id ? { anonymous_id: this.anonId, session_id: this.session.id } : { anonymous_id: this.anonId };
301
+ }
302
+ const host = inBrowser() ? g.location?.hostname : undefined;
303
+ if (this.privacy && typeof host === 'string' && host)
304
+ return { hostname: host };
305
+ }
306
+ catch { }
307
+ return undefined;
308
+ }
309
+ /**
310
+ * The visitor's consent state to send with a checkout, payment form, sign-up or form (see `ConsentRef`), or undefined
311
+ * when nobody answered. Global Privacy Control is always a no. With "Follow my cookie banner" on, the banner's answer
312
+ * comes first. Used by `baas.payments`, `baas.auth` and `baas.forms`; never throws.
313
+ */
314
+ async consentRef() {
315
+ try {
316
+ if (g.navigator?.globalPrivacyControl === true)
317
+ return { analytics: false };
318
+ let answer = this.answer;
319
+ const cfg = inBrowser() ? await this.config(1500) : null;
320
+ if (cfg?.consent_source === 'cmp') {
321
+ const now = this.followBanner().current();
322
+ if (now !== undefined)
323
+ answer = now;
324
+ }
325
+ if (answer === undefined)
326
+ return undefined;
327
+ const ref = { analytics: answer };
328
+ if (answer && cfg?.send_ga_client_id) {
329
+ const id = readGaClientId();
330
+ if (id)
331
+ ref.ga_client_id = id;
332
+ }
333
+ return ref;
334
+ }
335
+ catch {
336
+ return undefined;
337
+ }
338
+ }
339
+ /** Forget this device's anonymous id and session (e.g. on a shared computer after sign-out). Privacy mode keeps nothing to forget. */
340
+ reset() {
341
+ this.safely(() => {
342
+ this.referrerSent = false;
343
+ if (this.privacy)
344
+ return;
345
+ this.anonId = uuid();
346
+ this.session = null;
347
+ this.firstSeen = null;
348
+ this.referrerSent = false;
349
+ this.unsaved = { anon: true, firstSeen: false };
350
+ this.remove(this.keys.anon);
351
+ this.remove(this.keys.session);
352
+ this.remove(this.keys.firstSeen);
353
+ });
354
+ }
355
+ // ---- internals ------------------------------------------------------------------------------
356
+ safely(fn) {
357
+ try {
358
+ fn();
359
+ }
360
+ catch (err) {
361
+ this.warnOnce('internal', `[usebecky] analytics: ${err?.message ?? err}`);
362
+ }
363
+ }
364
+ warnOnce(key, msg) {
365
+ if (this.warned.has(key))
366
+ return;
367
+ this.warned.add(key);
368
+ warn(msg);
369
+ }
370
+ read(key) {
371
+ try {
372
+ return this.storage.getItem(key);
373
+ }
374
+ catch {
375
+ return null;
376
+ }
377
+ }
378
+ write(key, value) {
379
+ try {
380
+ const r = this.storage.setItem(key, value);
381
+ if (isThenable(r))
382
+ r.catch(() => { });
383
+ }
384
+ catch { }
385
+ }
386
+ remove(key) {
387
+ try {
388
+ const r = this.storage.removeItem(key);
389
+ if (isThenable(r))
390
+ r.catch(() => { });
391
+ }
392
+ catch { }
393
+ }
394
+ /** GET /analytics/v1/config once per page load (null when it fails); `waitMs`: give up waiting after that long. */
395
+ config(waitMs) {
396
+ this.projectConfig ??= this.http
397
+ .request('/analytics/v1/config', { method: 'GET', token: null })
398
+ .then((res) => (res.error ? null : (res.data ?? null)))
399
+ .catch(() => null);
400
+ if (!waitMs)
401
+ return this.projectConfig;
402
+ return Promise.race([this.projectConfig, new Promise((resolve) => setTimeout(() => resolve(null), waitMs))]);
403
+ }
404
+ /** Start following the site's cookie banner (once). Its answer goes to consent() while collecting; otherwise it
405
+ * is only remembered for consentRef(). */
406
+ followBanner() {
407
+ this.banner ??= watchConsentSignals((granted) => this.applyBanner(granted));
408
+ return this.banner;
409
+ }
410
+ /** The banner answered: remember it; while collecting, hand it to consent() (once per change). */
411
+ applyBanner(granted) {
412
+ this.answer = granted;
413
+ if (!this.enabled || granted === this.bannerApplied)
414
+ return;
415
+ this.bannerApplied = granted;
416
+ this.consent(granted);
417
+ }
418
+ /** Ask the project whether it remembers visitors; remember this device (`grant`) or forget it when it says it
419
+ * doesn't. `call`: the consent() call that asked; the answer is ignored once a later call was made. A failed
420
+ * request changes nothing. */
421
+ async checkConsent(grant, call) {
422
+ const res = await this.http.request('/analytics/v1/config', { method: 'GET', token: null });
423
+ this.safely(() => {
424
+ if (res.error || (call !== undefined && call !== this.consentCalls))
425
+ return;
426
+ if (!res.data?.remember_visitors) {
427
+ if (this.consented && res.data?.remember_visitors === false)
428
+ this.forgetDevice();
429
+ return;
430
+ }
431
+ if (!grant || this.consented)
432
+ return;
433
+ this.consented = true;
434
+ this.write(this.keys.consent, '1');
435
+ if (this.privacy)
436
+ this.rememberDevice();
437
+ });
438
+ }
439
+ /** The site owner's "Ignore my visits" flag: #usebecky-ignore / #usebecky-count in the address set or clear it
440
+ * (like the website script), otherwise it is read from storage. */
441
+ loadIgnored() {
442
+ const apply = (v) => {
443
+ this.ignored = v === '1';
444
+ if (this.ignored)
445
+ this.queue = [];
446
+ };
447
+ const own = inBrowser() ? /^#usebecky-(ignore|count)$/.exec(String(g.location?.hash ?? '')) : null;
448
+ if (own) {
449
+ if (own[1] === 'ignore')
450
+ this.write(this.keys.ignore, '1');
451
+ else
452
+ this.remove(this.keys.ignore);
453
+ apply(own[1] === 'ignore' ? '1' : null);
454
+ try {
455
+ g.console?.info?.(`[usebecky] ${own[1] === 'ignore' ? 'ignoring' : 'counting'} this browser`);
456
+ }
457
+ catch { }
458
+ return;
459
+ }
460
+ const v = this.read(this.keys.ignore);
461
+ if (isThenable(v))
462
+ v.then(apply, () => { });
463
+ else
464
+ apply(v);
465
+ }
466
+ /** Switch from privacy mode to remembering this device (ids loaded from storage, or made). */
467
+ rememberDevice() {
468
+ this.privacy = false;
469
+ this.anonId = null;
470
+ this.session = null;
471
+ this.firstSeen = undefined;
472
+ this.ready = this.load();
473
+ }
474
+ /** Delete this device's ids and the consent, and use privacy mode from now on. */
475
+ forgetDevice() {
476
+ for (const k of [this.keys.anon, this.keys.session, this.keys.firstSeen, this.keys.consent])
477
+ this.remove(k);
478
+ this.consented = false;
479
+ this.privacy = true;
480
+ this.anonId = null;
481
+ this.session = null;
482
+ this.firstSeen = undefined;
483
+ this.context = null;
484
+ this.unsaved = { anon: false, firstSeen: false };
485
+ }
486
+ load() {
487
+ if (this.privacy) {
488
+ // Privacy mode reads only the opt-out flag (the person's own choice) and the consent to be
489
+ // remembered, and never makes ids.
490
+ const apply = (o, c) => {
491
+ if (!this.optOutDecided)
492
+ this.optedOut = o === '1';
493
+ if (this.optedOut)
494
+ this.queue = [];
495
+ // A consent kept from an earlier page (this SDK or the website script) is the visitor's answer.
496
+ if (c === '1' && this.answer === undefined)
497
+ this.answer = true;
498
+ if (c === '1' && !this.alwaysPrivate && !this.consented) {
499
+ this.consented = true;
500
+ this.privacy = false;
501
+ // The project may have stopped remembering visitors since: then the device forgets the ids.
502
+ void this.checkConsent(false).catch(() => { });
503
+ return this.load();
504
+ }
505
+ };
506
+ const optOut = this.read(this.keys.optOut);
507
+ const consent = this.read(this.keys.consent);
508
+ if (isThenable(optOut) || isThenable(consent)) {
509
+ return Promise.all([optOut, consent].map((v) => Promise.resolve(v).catch(() => null))).then(([o, c]) => apply(o, c));
510
+ }
511
+ return apply(optOut, consent) ?? Promise.resolve();
512
+ }
513
+ const anon = this.read(this.keys.anon);
514
+ const optOut = this.read(this.keys.optOut);
515
+ const session = this.read(this.keys.session);
516
+ const firstSeen = this.read(this.keys.firstSeen);
517
+ const apply = (a, o, s, f) => {
518
+ if (!this.optOutDecided)
519
+ this.optedOut = o === '1';
520
+ if (this.optedOut)
521
+ this.queue = [];
522
+ if (!this.anonId) {
523
+ const known = typeof a === 'string' && !!a && a.length <= 100;
524
+ this.anonId = known ? a : uuid();
525
+ if (!known)
526
+ this.unsaved.anon = true;
527
+ if (this.firstSeen === undefined) {
528
+ if (!known)
529
+ this.firstSeen = null; // a brand-new visitor
530
+ else if (typeof f === 'string' && DATE.test(f))
531
+ this.firstSeen = f;
532
+ else {
533
+ // An id from before first-seen dates were kept: a returning visitor.
534
+ this.firstSeen = today();
535
+ this.unsaved.firstSeen = true;
536
+ }
537
+ }
538
+ }
539
+ if (this.firstSeen === undefined)
540
+ this.firstSeen = typeof f === 'string' && DATE.test(f) ? f : null;
541
+ if (!this.session)
542
+ this.session = this.parseSession(s);
543
+ // Remembered after consent: a new id after 13 months.
544
+ if (this.consented && typeof this.firstSeen === 'string' && Date.now() - Date.parse(this.firstSeen) > MAX_ID_AGE_MS) {
545
+ for (const k of [this.keys.anon, this.keys.session, this.keys.firstSeen])
546
+ this.remove(k);
547
+ this.anonId = uuid();
548
+ this.unsaved = { anon: true, firstSeen: false };
549
+ this.firstSeen = null;
550
+ this.session = null;
551
+ }
552
+ if (this.enabled && this.queue.length)
553
+ this.persist();
554
+ };
555
+ if (isThenable(anon) || isThenable(optOut) || isThenable(session) || isThenable(firstSeen)) {
556
+ return Promise.all([anon, optOut, session, firstSeen].map((v) => Promise.resolve(v).catch(() => null))).then(([a, o, s, f]) => apply(a, o, s, f));
557
+ }
558
+ apply(anon, optOut, session, firstSeen);
559
+ return Promise.resolve();
560
+ }
561
+ parseSession(raw) {
562
+ if (typeof raw !== 'string')
563
+ return null;
564
+ try {
565
+ const v = JSON.parse(raw);
566
+ if (typeof v?.id !== 'string' || typeof v?.last !== 'number')
567
+ return null;
568
+ const utm = cleanUtm(v.utm);
569
+ return utm ? { id: v.id, last: v.last, utm } : { id: v.id, last: v.last };
570
+ }
571
+ catch {
572
+ return null;
573
+ }
574
+ }
575
+ /** Write ids that only lived in memory so far (called once analytics is on and in use). */
576
+ persist() {
577
+ if (this.unsaved.anon && this.anonId) {
578
+ this.unsaved.anon = false;
579
+ this.write(this.keys.anon, this.anonId);
580
+ }
581
+ if (this.unsaved.firstSeen && this.firstSeen) {
582
+ this.unsaved.firstSeen = false;
583
+ this.write(this.keys.firstSeen, this.firstSeen);
584
+ }
585
+ }
586
+ /** Current session; starts a new one after `sessionTimeoutMinutes` of inactivity. */
587
+ touchSession(now) {
588
+ // Other tabs share the session through localStorage (sync storage only).
589
+ const stored = this.read(this.keys.session);
590
+ if (!isThenable(stored)) {
591
+ const s = this.parseSession(stored);
592
+ if (s && (!this.session || s.last > this.session.last))
593
+ this.session = s;
594
+ }
595
+ // The address's UTM parameters only describe how a visit started: the first session this page
596
+ // load starts takes them (a session that is already running keeps its own).
597
+ const landing = this.landingUtm;
598
+ this.landingUtm = null;
599
+ const timeout = this.opts.sessionTimeoutMinutes * 60_000;
600
+ let started = false;
601
+ if (!this.session || now - this.session.last > timeout) {
602
+ this.session = landing && Object.keys(landing).length ? { id: uuid(), last: now, utm: landing } : { id: uuid(), last: now };
603
+ started = true;
604
+ }
605
+ else
606
+ this.session.last = now;
607
+ this.write(this.keys.session, JSON.stringify(this.session));
608
+ return { session: this.session, started };
609
+ }
610
+ /** For the first event of a session: is this the device's first session? Undefined while async
611
+ * storage is still loading (decided at send time). */
612
+ newVisitorFlag() {
613
+ if (this.firstSeen === null) {
614
+ // Another tab may have started this visitor's first session already.
615
+ const stored = this.read(this.keys.firstSeen);
616
+ if (typeof stored === 'string' && DATE.test(stored))
617
+ this.firstSeen = stored;
618
+ }
619
+ if (this.firstSeen === undefined)
620
+ return undefined;
621
+ if (this.firstSeen !== null)
622
+ return false;
623
+ this.firstSeen = today();
624
+ this.write(this.keys.firstSeen, this.firstSeen);
625
+ return true;
626
+ }
627
+ currentSession() {
628
+ try {
629
+ return this.getSession();
630
+ }
631
+ catch {
632
+ return null;
633
+ }
634
+ }
635
+ enqueue(name, props, extra, internal) {
636
+ if (!this.enabled)
637
+ return;
638
+ if (typeof name !== 'string' || !name.trim()) {
639
+ this.warnOnce('name', '[usebecky] analytics.track() needs an event name, e.g. track("signed_up").');
640
+ return;
641
+ }
642
+ const eventName = name.trim();
643
+ if (eventName.length > ANALYTICS_LIMITS.maxNameLength) {
644
+ this.warnOnce('name-long', `[usebecky] analytics: event names can be at most ${ANALYTICS_LIMITS.maxNameLength} characters. "${eventName.slice(0, 40)}..." was not sent.`);
645
+ return;
646
+ }
647
+ if (!internal && eventName.startsWith('$')) {
648
+ this.warnOnce('name-reserved', `[usebecky] analytics: event names starting with "$" are reserved ("${eventName}" was not sent). Use page() for page views.`);
649
+ return;
650
+ }
651
+ let cleanProps;
652
+ if (props !== undefined && props !== null) {
653
+ if (!isPlainObject(props)) {
654
+ this.warnOnce('props', `[usebecky] analytics: props must be a plain object like { plan: "pro" } ("${eventName}" was not sent).`);
655
+ return;
656
+ }
657
+ let json;
658
+ try {
659
+ json = JSON.stringify(props);
660
+ }
661
+ catch {
662
+ this.warnOnce('props-json', `[usebecky] analytics: props for "${eventName}" can't be turned into JSON (circular?), so it was not sent.`);
663
+ return;
664
+ }
665
+ if (byteLength(json) > ANALYTICS_LIMITS.maxPropsBytes) {
666
+ this.warnOnce('props-size', `[usebecky] analytics: props for "${eventName}" are larger than ${ANALYTICS_LIMITS.maxPropsBytes} bytes, so it was not sent.`);
667
+ return;
668
+ }
669
+ cleanProps = JSON.parse(json); // snapshot: later changes to the object don't leak in
670
+ }
671
+ const now = Date.now();
672
+ const s = this.currentSession();
673
+ const uid = s?.user?.id ?? null;
674
+ if (uid && s?.access_token)
675
+ this.tokens.set(uid, s.access_token);
676
+ const timestamp = new Date(now).toISOString();
677
+ if (this.privacy) {
678
+ // No ids and no device details; every event of this page load carries the landing page's UTM
679
+ // parameters (the server keeps the first ones of the visit).
680
+ const event = { name: eventName, timestamp, ...this.landingUtm, ...extra };
681
+ const host = inBrowser() ? g.location?.hostname : undefined;
682
+ if (typeof host === 'string' && host)
683
+ event.hostname = host;
684
+ if (cleanProps && Object.keys(cleanProps).length)
685
+ event.props = cleanProps;
686
+ if (event.path === undefined && typeof g.location?.pathname === 'string' && inBrowser())
687
+ event.path = g.location.pathname;
688
+ this.push({ event, uid, privacy: true });
689
+ return;
690
+ }
691
+ this.persist();
692
+ const { session, started } = this.touchSession(now);
693
+ this.context ??= visitContext(inBrowser());
694
+ const event = { name: eventName, session_id: session.id, timestamp, ...this.context, ...session.utm, ...extra };
695
+ if (cleanProps && Object.keys(cleanProps).length)
696
+ event.props = cleanProps;
697
+ if (this.anonId)
698
+ event.anonymous_id = this.anonId;
699
+ if (this.consented)
700
+ event.consent = true;
701
+ if (event.path === undefined && typeof g.location?.pathname === 'string' && inBrowser())
702
+ event.path = g.location.pathname;
703
+ const queued = { event, uid };
704
+ // New vs returning only means something for a person's device (not a Node script).
705
+ if (started && onVisitorDevice(inBrowser())) {
706
+ const isNew = this.newVisitorFlag();
707
+ if (isNew === undefined)
708
+ queued.pendingNew = true;
709
+ else
710
+ event.is_new_visitor = isNew;
711
+ }
712
+ this.push(queued);
713
+ }
714
+ push(queued) {
715
+ this.queue.push(queued);
716
+ if (this.queue.length > this.opts.maxQueueSize)
717
+ this.queue.splice(0, this.queue.length - this.opts.maxQueueSize);
718
+ // A send in progress keeps draining the queue, so only start one when none is running.
719
+ if (this.queue.length >= this.opts.batchSize && !this.retryDelay && !this.flushing)
720
+ void this.flush();
721
+ else
722
+ this.schedule();
723
+ }
724
+ schedule(delay = this.retryDelay || this.opts.flushInterval) {
725
+ if (this.timer || !this.queue.length)
726
+ return;
727
+ this.timer = setTimeout(() => {
728
+ this.timer = null;
729
+ void this.flush();
730
+ }, delay);
731
+ this.timer?.unref?.();
732
+ }
733
+ clearTimer() {
734
+ if (this.timer)
735
+ clearTimeout(this.timer);
736
+ this.timer = null;
737
+ }
738
+ /** Up to `max` consecutive queued events tracked by the same user. */
739
+ takeBatch(max) {
740
+ const first = this.queue[0];
741
+ let n = 1;
742
+ while (n < this.queue.length && n < max && this.queue[n].uid === first.uid)
743
+ n++;
744
+ return this.queue.splice(0, n);
745
+ }
746
+ /** Which access token goes with events tracked by `uid`: undefined = the current one (refreshed if needed), null = none. */
747
+ tokenFor(uid) {
748
+ if (!uid)
749
+ return null;
750
+ const current = this.currentSession()?.user?.id ?? null;
751
+ return uid === current ? undefined : (this.tokens.get(uid) ?? null);
752
+ }
753
+ withAnon(q) {
754
+ return q.event.anonymous_id || !this.anonId || q.privacy ? q.event : { ...q.event, anonymous_id: this.anonId };
755
+ }
756
+ async sendQueued() {
757
+ this.clearTimer();
758
+ await this.ready;
759
+ if (!this.enabled) {
760
+ this.queue = [];
761
+ return { data: { sent: 0 }, error: null };
762
+ }
763
+ // Sessions started before async storage answered: decide new vs returning now, in order.
764
+ for (const q of this.queue) {
765
+ if (!q.pendingNew)
766
+ continue;
767
+ q.pendingNew = false;
768
+ const isNew = this.newVisitorFlag();
769
+ if (isNew !== undefined)
770
+ q.event.is_new_visitor = isNew;
771
+ }
772
+ let sent = 0;
773
+ let dropped = null;
774
+ while (this.queue.length) {
775
+ const batch = this.takeBatch(ANALYTICS_LIMITS.maxBatch);
776
+ const res = await this.http.request('/analytics/v1/events', {
777
+ method: 'POST',
778
+ body: { sent_at: new Date().toISOString(), events: batch.map((q) => this.withAnon(q)) },
779
+ token: this.tokenFor(batch[0].uid),
780
+ });
781
+ if (res.error) {
782
+ const retry = res.error.status === 0 || res.error.status === 429 || res.error.status >= 500;
783
+ if (retry) {
784
+ // Keep the events and try again later, backing off up to a minute.
785
+ this.queue.unshift(...batch);
786
+ if (this.queue.length > this.opts.maxQueueSize)
787
+ this.queue.splice(0, this.queue.length - this.opts.maxQueueSize);
788
+ this.retryDelay = Math.min(MAX_RETRY_DELAY_MS, this.retryDelay ? this.retryDelay * 2 : this.opts.flushInterval * 2);
789
+ this.schedule();
790
+ return { data: null, error: res.error };
791
+ }
792
+ // The API refused these events (bad key, invalid data): sending them again won't help.
793
+ this.warnOnce(`rejected:${res.error.code}`, `[usebecky] analytics: ${batch.length} event(s) were rejected: ${res.error.message}${res.error.hint ? ` ${res.error.hint}` : ''}`);
794
+ dropped = res.error;
795
+ continue;
796
+ }
797
+ this.retryDelay = 0;
798
+ sent += batch.length;
799
+ // Analytics is turned off for this project (it's off until the owner turns it on): the server
800
+ // accepts the events but stores nothing. Say so once, so nobody wonders where the data went.
801
+ if (res.data?.reason === 'analytics_off') {
802
+ this.warnOnce('analytics-off', '[usebecky] analytics: visitor analytics is off for this project, so these events were not saved. Turn it on in your dashboard: Analytics → Turn on.');
803
+ }
804
+ }
805
+ return dropped ? { data: null, error: dropped } : { data: { sent }, error: null };
806
+ }
807
+ /** Page is being hidden or closed: hand everything to sendBeacon (or fetch keepalive) synchronously. */
808
+ flushOnExit() {
809
+ this.safely(() => {
810
+ if (!this.queue.length || !this.enabled)
811
+ return;
812
+ this.clearTimer();
813
+ const url = `${this.http.url}/analytics/v1/events?apikey=${encodeURIComponent(this.key)}`;
814
+ const sentAt = new Date().toISOString();
815
+ const pending = this.queue;
816
+ this.queue = [];
817
+ const failed = [];
818
+ let i = 0;
819
+ while (i < pending.length) {
820
+ // Consecutive events of one user, at most 50 per request and under the ~64 KB beacon limit.
821
+ const uid = pending[i].uid;
822
+ const token = this.tokenFor(uid);
823
+ const accessToken = token === undefined ? this.currentSession()?.access_token : token;
824
+ const chunk = [];
825
+ let size = 200 + (accessToken?.length ?? 0);
826
+ while (i < pending.length && pending[i].uid === uid && chunk.length < ANALYTICS_LIMITS.maxBatch) {
827
+ const bytes = byteLength(JSON.stringify(this.withAnon(pending[i]))) + 1;
828
+ if (chunk.length && size + bytes > BEACON_MAX_BYTES)
829
+ break;
830
+ size += bytes;
831
+ chunk.push(pending[i++]);
832
+ }
833
+ const body = JSON.stringify({ sent_at: sentAt, ...(accessToken ? { access_token: accessToken } : {}), events: chunk.map((q) => this.withAnon(q)) });
834
+ if (!this.beacon(url, body))
835
+ failed.push(...chunk);
836
+ }
837
+ // Couldn't hand them off (no sendBeacon/fetch): keep them for the next flush, e.g. after bfcache restore.
838
+ if (failed.length)
839
+ this.queue = failed.concat(this.queue);
840
+ });
841
+ }
842
+ /** text/plain + key in the URL = a "simple" request: no CORS preflight, allowed in sendBeacon. */
843
+ beacon(url, body) {
844
+ try {
845
+ const nav = g.navigator;
846
+ if (typeof nav?.sendBeacon === 'function' && typeof g.Blob === 'function') {
847
+ if (nav.sendBeacon(url, new g.Blob([body], { type: 'text/plain;charset=UTF-8' })))
848
+ return true;
849
+ }
850
+ }
851
+ catch { }
852
+ try {
853
+ if (typeof g.fetch === 'function') {
854
+ void Promise.resolve(g.fetch(url, { method: 'POST', body, keepalive: true, headers: { 'content-type': 'text/plain;charset=UTF-8' } })).catch(() => { });
855
+ return true;
856
+ }
857
+ }
858
+ catch { }
859
+ return false;
860
+ }
861
+ externalReferrer() {
862
+ const ref = g.document?.referrer;
863
+ if (typeof ref !== 'string' || !ref)
864
+ return undefined;
865
+ try {
866
+ if (new URL(ref).host === g.location?.host)
867
+ return undefined;
868
+ }
869
+ catch {
870
+ return undefined;
871
+ }
872
+ return ref.slice(0, 2000);
873
+ }
874
+ /** Browser hooks: send on pagehide / tab hidden, and (opt-in) automatic page views. */
875
+ start() {
876
+ if (this.started || !inBrowser())
877
+ return;
878
+ this.started = true;
879
+ const exit = () => this.flushOnExit();
880
+ try {
881
+ g.addEventListener?.('pagehide', exit);
882
+ g.document?.addEventListener?.('visibilitychange', () => {
883
+ if (g.document?.visibilityState === 'hidden')
884
+ exit();
885
+ });
886
+ }
887
+ catch { }
888
+ // "Follow my cookie banner": the project's config says where consent comes from.
889
+ void this.config().then((cfg) => this.safely(() => {
890
+ if (cfg?.consent_source !== 'cmp')
891
+ return;
892
+ // Already following (consentRef() started it while analytics was off): apply its answer now.
893
+ const now = this.followBanner().current();
894
+ if (now !== undefined)
895
+ this.applyBanner(now);
896
+ }));
897
+ if (!this.opts.autoPageviews)
898
+ return;
899
+ const check = () => this.safely(() => {
900
+ if (!this.enabled || !this.opts.autoPageviews)
901
+ return;
902
+ const p = g.location?.pathname;
903
+ if (typeof p === 'string' && p !== this.lastPath)
904
+ this.page();
905
+ });
906
+ try {
907
+ const h = g.history;
908
+ for (const method of ['pushState', 'replaceState']) {
909
+ const original = h?.[method];
910
+ if (typeof original !== 'function')
911
+ continue;
912
+ h[method] = function (...args) {
913
+ const result = original.apply(this, args);
914
+ setTimeout(check, 0);
915
+ return result;
916
+ };
917
+ }
918
+ g.addEventListener?.('popstate', () => setTimeout(check, 0));
919
+ }
920
+ catch { }
921
+ check();
922
+ }
923
+ }