@indiebob/tracker 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/vue.js CHANGED
@@ -1,5 +1,12 @@
1
1
  // src/core/config.ts
2
2
  var DEFAULT_ENDPOINT = "https://www.indiebob.com/api/collect";
3
+ var OPTIONS = "projectId endpoint debug respectDnt respectGpc autoDetect hashMode persistence";
4
+ var AUTO_OPTIONS = "signupPaths loginPaths pricingPaths checkoutPaths successPaths onboardingPaths contactPaths dataAttributes formSubmit outboundClicks fileDownloads";
5
+ function warnUnknown(obj, known, where) {
6
+ for (const k of Object.keys(obj)) {
7
+ if (!known.split(" ").includes(k)) console.warn(`[IndieBob] Unknown option ${where}"${k}" ignored`);
8
+ }
9
+ }
3
10
  function resolveConfig(input) {
4
11
  var _a, _b, _c, _d, _e, _f;
5
12
  if (!input.projectId || !input.projectId.startsWith("proj_")) {
@@ -7,6 +14,11 @@ function resolveConfig(input) {
7
14
  `[IndieBob] Invalid projectId "${input.projectId}". Must start with "proj_".`
8
15
  );
9
16
  }
17
+ warnUnknown(input, OPTIONS, "");
18
+ if (typeof input.autoDetect === "object") warnUnknown(input.autoDetect, AUTO_OPTIONS, "autoDetect.");
19
+ if (input.persistence !== void 0 && input.persistence !== "local" && input.persistence !== "none") {
20
+ console.warn(`[IndieBob] persistence "${String(input.persistence)}" is not 'none' or 'local'; using 'none'`);
21
+ }
10
22
  return {
11
23
  projectId: input.projectId,
12
24
  endpoint: (_a = input.endpoint) != null ? _a : DEFAULT_ENDPOINT,
@@ -14,7 +26,8 @@ function resolveConfig(input) {
14
26
  respectDnt: (_c = input.respectDnt) != null ? _c : true,
15
27
  respectGpc: (_d = input.respectGpc) != null ? _d : true,
16
28
  autoDetect: (_e = input.autoDetect) != null ? _e : true,
17
- hashMode: (_f = input.hashMode) != null ? _f : false
29
+ hashMode: (_f = input.hashMode) != null ? _f : false,
30
+ persistence: input.persistence === "local" ? "local" : "none"
18
31
  };
19
32
  }
20
33
 
@@ -277,7 +290,6 @@ async function sendBatch(payload, config, isUnloading = false) {
277
290
  var OFFLINE_KEY = "_ib_queue";
278
291
  var MAX_BATCH = 10;
279
292
  var FLUSH_INTERVAL_MS = 5e3;
280
- var MAX_OFFLINE = 50;
281
293
  var EventQueue = class {
282
294
  /**
283
295
  * @param beforeHide runs right before the hide flush, so an event that
@@ -285,7 +297,9 @@ var EventQueue = class {
285
297
  */
286
298
  constructor(config, beforeHide) {
287
299
  this.b = [];
288
- this.i = false;
300
+ /** Failed events awaiting a retry, when nothing may be stored ('none'). */
301
+ this.j = [];
302
+ this.k = false;
289
303
  this.a = config;
290
304
  setInterval(() => {
291
305
  if (this.b.length > 0) void this.flush();
@@ -300,10 +314,10 @@ var EventQueue = class {
300
314
  });
301
315
  window.addEventListener("pagehide", hide);
302
316
  window.addEventListener("online", () => {
303
- void this.m();
317
+ void this.o();
304
318
  });
305
319
  if (navigator.onLine) {
306
- void this.m();
320
+ void this.o();
307
321
  }
308
322
  }
309
323
  push(event) {
@@ -313,32 +327,49 @@ var EventQueue = class {
313
327
  }
314
328
  }
315
329
  async flush(isUnloading = false) {
316
- if (this.i && !isUnloading) return;
330
+ if (this.k && !isUnloading) return;
317
331
  if (this.b.length === 0) return;
318
- this.i = true;
332
+ this.k = true;
319
333
  const batch = this.b.splice(0);
320
334
  const payload = { batch };
321
335
  const ok = await sendBatch(payload, this.a, isUnloading);
322
336
  if (!ok) {
323
- try {
324
- const trimmed = [...this.n(), ...batch].slice(-MAX_OFFLINE);
325
- localStorage.setItem(OFFLINE_KEY, JSON.stringify(trimmed));
326
- } catch (e) {
327
- }
337
+ this.t([...this.p(), ...batch].slice(-50));
328
338
  }
329
- this.i = false;
339
+ this.k = false;
330
340
  }
331
- async m() {
332
- const stored = this.n();
341
+ async o() {
342
+ const stored = this.p();
333
343
  if (stored.length === 0) return;
344
+ this.clearStored();
345
+ const payload = { batch: stored };
346
+ await sendBatch(payload, this.a);
347
+ }
348
+ /** Give events still waiting the ids they lacked (storage was just allowed). */
349
+ stamp(anonymousId, sessionId) {
350
+ for (const e of this.b) if (!e.anonymousId) Object.assign(e, { anonymousId, sessionId });
351
+ }
352
+ /** Drop the retry queue, wherever it is kept. */
353
+ clearStored() {
354
+ this.j = [];
334
355
  try {
335
356
  localStorage.removeItem(OFFLINE_KEY);
336
357
  } catch (e) {
337
358
  }
338
- const payload = { batch: stored };
339
- await sendBatch(payload, this.a);
340
359
  }
341
- n() {
360
+ /** In localStorage only with persistence 'local'; in memory otherwise. */
361
+ t(events) {
362
+ if (this.a.persistence !== "local") {
363
+ this.j = events;
364
+ return;
365
+ }
366
+ try {
367
+ localStorage.setItem(OFFLINE_KEY, JSON.stringify(events));
368
+ } catch (e) {
369
+ }
370
+ }
371
+ p() {
372
+ if (this.a.persistence !== "local") return this.j;
342
373
  try {
343
374
  const raw = localStorage.getItem(OFFLINE_KEY);
344
375
  if (!raw) return [];
@@ -349,9 +380,40 @@ var EventQueue = class {
349
380
  }
350
381
  };
351
382
 
383
+ // src/core/url.ts
384
+ var KEEP = /^(utm_\w+|ref)$/;
385
+ function cleanSearch(search) {
386
+ const out = new URLSearchParams();
387
+ new URLSearchParams(search).forEach((v, k) => {
388
+ if (KEEP.test(k)) out.append(k, v);
389
+ });
390
+ const s = out.toString();
391
+ return s ? "?" + s : "";
392
+ }
393
+ function cleanHash(hash) {
394
+ const route = hash.split("?")[0];
395
+ return route.includes("=") ? "" : route;
396
+ }
397
+ function cleanUrl(href, hashMode) {
398
+ try {
399
+ const u = new URL(href);
400
+ return u.origin + u.pathname + cleanSearch(u.search) + (hashMode ? cleanHash(u.hash) : "");
401
+ } catch (e) {
402
+ return "";
403
+ }
404
+ }
405
+ function cleanReferrer(ref) {
406
+ try {
407
+ const u = new URL(ref);
408
+ return u.origin + u.pathname;
409
+ } catch (e) {
410
+ return "";
411
+ }
412
+ }
413
+
352
414
  // src/collectors/page.ts
353
415
  function pagePath(loc, hashMode) {
354
- return loc.pathname + loc.search + (hashMode ? loc.hash : "");
416
+ return loc.pathname + cleanSearch(loc.search) + (hashMode ? cleanHash(loc.hash) : "");
355
417
  }
356
418
  function patchHistory(onNavigate, hashMode) {
357
419
  if (typeof window === "undefined") return () => {
@@ -377,9 +439,9 @@ function patchHistory(onNavigate, hashMode) {
377
439
 
378
440
  // src/collectors/context.ts
379
441
  var PAYMENT_HOST = /^https?:\/\/[^/]*(stripe\.com|paypal\.com|paddle\.com|lemonsqueezy\.com|gumroad\.com)(\/|$)/i;
380
- function buildContext(overrides, hashMode) {
381
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
382
- const sdkVersion = "0.3.0" ;
442
+ function buildContext(overrides, hashMode, local) {
443
+ var _a, _b, _c, _d, _e, _f, _g, _h;
444
+ const sdkVersion = "0.4.1" ;
383
445
  if (typeof window === "undefined") {
384
446
  return {
385
447
  page: { path: (_a = overrides == null ? void 0 : overrides.path) != null ? _a : "", url: "", title: (_b = overrides == null ? void 0 : overrides.title) != null ? _b : "", referrer: (_c = overrides == null ? void 0 : overrides.referrer) != null ? _c : "" },
@@ -394,18 +456,19 @@ function buildContext(overrides, hashMode) {
394
456
  return {
395
457
  page: {
396
458
  path: (_e = overrides == null ? void 0 : overrides.path) != null ? _e : pagePath(location, hashMode),
397
- url: location.href,
459
+ url: cleanUrl(location.href, hashMode),
398
460
  title: (_f = overrides == null ? void 0 : overrides.title) != null ? _f : document.title,
399
461
  // First touch survives the round trip: a /thanks page reached from Stripe
400
- // reports the referrer and UTM the visit STARTED with, not checkout.stripe.com
401
- // — otherwise every sale files itself under the payment host.
402
- referrer: liveReferrer === "" || PAYMENT_HOST.test(liveReferrer) ? (_g = getStoredReferrer()) != null ? _g : liveReferrer : liveReferrer
462
+ // reports the referrer the visit STARTED with (stored with 'local'), and
463
+ // never checkout.stripe.com — otherwise every sale files itself under the
464
+ // payment host. Without storage the server's visit already holds it.
465
+ referrer: cleanReferrer(liveReferrer === "" || PAYMENT_HOST.test(liveReferrer) ? local && getStoredReferrer() || "" : liveReferrer)
403
466
  },
404
467
  // Device class from the viewport width; still required by /api/collect
405
468
  device: { width, height: innerHeight, type: width <= 768 ? "mobile" : width <= 1024 ? "tablet" : "desktop" },
406
- utm: (_h = parseUtm(location.search)) != null ? _h : getStoredFirstUtm(),
469
+ utm: (_g = parseUtm(location.search)) != null ? _g : local ? getStoredFirstUtm() : void 0,
407
470
  locale: navigator.language,
408
- timezone: (_i = Intl.DateTimeFormat().resolvedOptions().timeZone) != null ? _i : "UTC",
471
+ timezone: (_h = Intl.DateTimeFormat().resolvedOptions().timeZone) != null ? _h : "UTC",
409
472
  sdkVersion
410
473
  };
411
474
  }
@@ -576,9 +639,9 @@ function trackEngagement() {
576
639
  window.addEventListener("scroll", sample);
577
640
  reset();
578
641
  return {
579
- r: sample,
580
- s: reset,
581
- t(measure) {
642
+ u: sample,
643
+ w: reset,
644
+ x(measure) {
582
645
  if (measure) sample();
583
646
  tick();
584
647
  if (!shouldSendEngagement(ms, scroll, sent)) return null;
@@ -597,17 +660,17 @@ function unseen() {
597
660
  }
598
661
  var IndieBob = class _IndieBob {
599
662
  constructor(config) {
600
- this.f = null;
601
- this.k = null;
602
663
  this.g = null;
664
+ this.m = null;
665
+ this.h = null;
603
666
  /** Engagement meter for the current page (browser only). */
604
- this.d = null;
667
+ this.e = null;
605
668
  /** Context of the page last counted — what an engagement event describes. */
606
- this.l = null;
669
+ this.n = null;
607
670
  /** A first pageview waiting for the tab to become visible. */
608
- this.h = false;
671
+ this.i = false;
609
672
  this.a = config;
610
- this.b = new EventQueue(config, () => this.q(true));
673
+ this.b = new EventQueue(config, () => this.s(true));
611
674
  if (typeof window !== "undefined") {
612
675
  try {
613
676
  if (applyIgnore(window.location.search, localStorage)) {
@@ -615,17 +678,17 @@ var IndieBob = class _IndieBob {
615
678
  }
616
679
  } catch (e) {
617
680
  }
618
- initAttribution(window.location.search, document.referrer);
619
- this.d = trackEngagement();
681
+ if (this.c && isTrackingAllowed(config)) initAttribution(window.location.search, document.referrer);
682
+ this.e = trackEngagement();
620
683
  window.addEventListener("pageshow", (e) => {
621
- if (e.persisted && this.e !== void 0) {
622
- this.e = void 0;
623
- this.page(this.o);
684
+ if (e.persisted && this.f !== void 0) {
685
+ this.f = void 0;
686
+ this.page(this.q);
624
687
  }
625
688
  });
626
689
  if (config.autoDetect !== false) {
627
690
  const opts = typeof config.autoDetect === "object" ? config.autoDetect : {};
628
- this.k = initClickTracking(
691
+ this.m = initClickTracking(
629
692
  (event, properties) => this.track(event, properties),
630
693
  opts.dataAttributes !== false,
631
694
  opts.fileDownloads !== false,
@@ -660,14 +723,14 @@ var IndieBob = class _IndieBob {
660
723
  page(overrides) {
661
724
  var _a;
662
725
  if (!isTrackingAllowed(this.a)) return;
663
- if (this.e === void 0 && unseen()) {
664
- this.p = overrides;
665
- if (!this.h) {
666
- this.h = true;
726
+ if (this.f === void 0 && unseen()) {
727
+ this.r = overrides;
728
+ if (!this.i) {
729
+ this.i = true;
667
730
  const go = () => {
668
- if (this.h && !unseen()) {
669
- this.h = false;
670
- this.page(this.p);
731
+ if (this.i && !unseen()) {
732
+ this.i = false;
733
+ this.page(this.r);
671
734
  }
672
735
  };
673
736
  document.addEventListener("visibilitychange", go);
@@ -675,34 +738,34 @@ var IndieBob = class _IndieBob {
675
738
  }
676
739
  return;
677
740
  }
678
- const ctx = buildContext(overrides, this.a.hashMode);
679
- if (ctx.page.path === this.e) return;
680
- this.q(false);
681
- this.e = ctx.page.path;
682
- this.o = overrides;
683
- this.l = ctx;
684
- if (this.d) {
685
- this.d.s();
686
- setTimeout(this.d.r, 1e3);
741
+ const ctx = buildContext(overrides, this.a.hashMode, this.c);
742
+ if (ctx.page.path === this.f) return;
743
+ this.s(false);
744
+ this.f = ctx.page.path;
745
+ this.q = overrides;
746
+ this.n = ctx;
747
+ if (this.e) {
748
+ this.e.w();
749
+ setTimeout(this.e.u, 1e3);
687
750
  }
688
- this.b.push(this.c("page", { context: ctx }));
751
+ this.b.push(this.d("page", { context: ctx }));
689
752
  if (this.a.autoDetect !== false) {
690
753
  const path = ctx.page.path;
691
754
  const opts = typeof this.a.autoDetect === "object" ? this.a.autoDetect : {};
692
755
  const intent = detectIntent(path, opts);
693
756
  if (intent) {
694
- this.b.push(this.c("track", {
757
+ this.b.push(this.d("track", {
695
758
  event: intent,
696
759
  properties: { auto: true },
697
760
  context: ctx
698
761
  }));
699
762
  log(this.a, `auto-detected: ${intent} on ${path}`);
700
763
  if (opts.formSubmit !== false) {
701
- (_a = this.g) == null ? void 0 : _a.call(this);
764
+ (_a = this.h) == null ? void 0 : _a.call(this);
702
765
  const submitEvent = intentToSubmitEvent(intent);
703
766
  if (submitEvent) {
704
- this.g = observeFormSubmits(submitEvent, (eventName) => {
705
- this.b.push(this.c("track", {
767
+ this.h = observeFormSubmits(submitEvent, (eventName) => {
768
+ this.b.push(this.d("track", {
706
769
  event: eventName,
707
770
  properties: { auto: true }
708
771
  }));
@@ -722,7 +785,7 @@ var IndieBob = class _IndieBob {
722
785
  */
723
786
  track(event, properties) {
724
787
  if (!isTrackingAllowed(this.a)) return;
725
- this.b.push(this.c("track", { event, properties }));
788
+ this.b.push(this.d("track", { event, properties }));
726
789
  }
727
790
  /**
728
791
  * Associate the current anonymous visitor with a known user ID.
@@ -747,18 +810,19 @@ var IndieBob = class _IndieBob {
747
810
  */
748
811
  identify(userId, traits, options) {
749
812
  if (!isTrackingAllowed(this.a)) return;
750
- this.j = userId;
751
- this.b.push(this.c("identify", { traits, userId }));
752
- if (this.a.autoDetect !== false) {
753
- const first = typeof (options == null ? void 0 : options.isNew) === "boolean" ? options.isNew : isFirstIdentify();
813
+ this.l = userId;
814
+ this.b.push(this.d("identify", { traits, userId }));
815
+ const known = typeof (options == null ? void 0 : options.isNew) === "boolean";
816
+ if (this.a.autoDetect !== false && (known || this.c)) {
817
+ const first = known ? options.isNew : isFirstIdentify();
754
818
  const eventName = first ? "signup" : "login";
755
- this.b.push(this.c("track", {
819
+ this.b.push(this.d("track", {
756
820
  event: eventName,
757
821
  // `auto` says where the verdict came from, so a funnel that looks
758
822
  // wrong later can be traced to a guess rather than to the server.
759
- properties: { auto: typeof (options == null ? void 0 : options.isNew) !== "boolean" }
823
+ properties: { auto: !known }
760
824
  }));
761
- markIdentified();
825
+ if (this.c) markIdentified();
762
826
  log(this.a, `${eventName} for ${userId}`);
763
827
  }
764
828
  }
@@ -771,7 +835,7 @@ var IndieBob = class _IndieBob {
771
835
  revenue(data) {
772
836
  var _a;
773
837
  if (!isTrackingAllowed(this.a)) return;
774
- this.b.push(this.c("revenue", {
838
+ this.b.push(this.d("revenue", {
775
839
  revenue: {
776
840
  amount: data.amount,
777
841
  currency: (_a = data.currency) != null ? _a : "USD",
@@ -789,11 +853,11 @@ var IndieBob = class _IndieBob {
789
853
  void this.b.flush();
790
854
  optOut();
791
855
  clearIdentified();
792
- this.j = void 0;
793
- (_a = this.k) == null ? void 0 : _a.call(this);
794
- (_b = this.g) == null ? void 0 : _b.call(this);
795
- this.k = null;
796
- this.g = null;
856
+ this.l = void 0;
857
+ (_a = this.m) == null ? void 0 : _a.call(this);
858
+ (_b = this.h) == null ? void 0 : _b.call(this);
859
+ this.m = null;
860
+ this.h = null;
797
861
  log(this.a, "opted out");
798
862
  }
799
863
  /** Re-enable tracking after optOut(). */
@@ -816,13 +880,42 @@ var IndieBob = class _IndieBob {
816
880
  async flush() {
817
881
  await this.b.flush();
818
882
  }
819
- /** Get the current anonymous ID. */
883
+ /** The stored anonymous ID with `persistence: 'local'`; '' without storage. */
820
884
  getAnonymousId() {
821
- return getAnonymousId();
885
+ return this.c ? getAnonymousId() : "";
822
886
  }
823
- /** Get the current session ID. */
887
+ /** The stored session ID with `persistence: 'local'`; '' without storage. */
824
888
  getSessionId() {
825
- return getSessionId();
889
+ return this.c ? getSessionId() : "";
890
+ }
891
+ /**
892
+ * Switch storage on or off — call it from your consent banner.
893
+ * `'local'` starts storing the visitor id and first-touch attribution from
894
+ * this page on; `'none'` removes everything the tracker stored.
895
+ *
896
+ * @example
897
+ * onConsent(() => bob.setPersistence('local'))
898
+ * onConsentWithdrawn(() => bob.setPersistence('none'))
899
+ */
900
+ setPersistence(mode) {
901
+ if (mode !== "local" && mode !== "none") return;
902
+ this.a.persistence = mode;
903
+ if (mode === "local") {
904
+ if (typeof window !== "undefined" && isTrackingAllowed(this.a)) {
905
+ initAttribution(location.search, document.referrer);
906
+ this.b.stamp(getAnonymousId(), getSessionId());
907
+ }
908
+ } else {
909
+ clearAnonymousId();
910
+ clearSession();
911
+ clearAttribution();
912
+ clearIdentified();
913
+ this.b.clearStored();
914
+ }
915
+ log(this.a, `persistence: ${mode}`);
916
+ }
917
+ get c() {
918
+ return this.a.persistence === "local";
826
919
  }
827
920
  /** Get the resolved configuration (read-only). */
828
921
  getConfig() {
@@ -838,12 +931,12 @@ var IndieBob = class _IndieBob {
838
931
  */
839
932
  enableAutoPage() {
840
933
  var _a;
841
- (_a = this.f) == null ? void 0 : _a.call(this);
842
- this.f = patchHistory(() => this.page(), this.a.hashMode);
934
+ (_a = this.g) == null ? void 0 : _a.call(this);
935
+ this.g = patchHistory(() => this.page(), this.a.hashMode);
843
936
  return () => {
844
937
  var _a2;
845
- (_a2 = this.f) == null ? void 0 : _a2.call(this);
846
- this.f = null;
938
+ (_a2 = this.g) == null ? void 0 : _a2.call(this);
939
+ this.g = null;
847
940
  };
848
941
  }
849
942
  /**
@@ -851,14 +944,14 @@ var IndieBob = class _IndieBob {
851
944
  * worth sending. `measure`: sample the scroll first (false on an SPA
852
945
  * change, when the DOM already shows the next page).
853
946
  */
854
- q(measure) {
947
+ s(measure) {
855
948
  var _a;
856
- const reading = this.l && ((_a = this.d) == null ? void 0 : _a.t(measure));
949
+ const reading = this.n && ((_a = this.e) == null ? void 0 : _a.x(measure));
857
950
  if (reading && isTrackingAllowed(this.a)) {
858
- this.b.push(this.c("engagement", { context: this.l, engagement: reading }));
951
+ this.b.push(this.d("engagement", { context: this.n, engagement: reading }));
859
952
  }
860
953
  }
861
- c(type, extras) {
954
+ d(type, extras) {
862
955
  var _a, _b;
863
956
  return {
864
957
  ...extras,
@@ -866,11 +959,11 @@ var IndieBob = class _IndieBob {
866
959
  id: generateId(),
867
960
  projectId: this.a.projectId,
868
961
  type,
869
- anonymousId: getAnonymousId(),
870
- userId: (_a = this.j) != null ? _a : extras.userId,
871
- sessionId: getSessionId(),
962
+ // Without storage the server derives both from its daily hash
963
+ ...this.c ? { anonymousId: getAnonymousId(), sessionId: getSessionId() } : {},
964
+ userId: (_a = this.l) != null ? _a : extras.userId,
872
965
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
873
- context: (_b = extras.context) != null ? _b : buildContext(void 0, this.a.hashMode)
966
+ context: (_b = extras.context) != null ? _b : buildContext(void 0, this.a.hashMode, this.c)
874
967
  };
875
968
  }
876
969
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@indiebob/tracker",
3
- "version": "0.3.0",
4
- "description": "Privacy-first analytics SDK for web applications. <5KB gzipped. No cookies.",
3
+ "version": "0.4.1",
4
+ "description": "Analytics for IndieBob. Stores nothing in the visitor's browser by default; no cookies; about 5.7 KB gzipped.",
5
5
  "private": false,
6
6
  "license": "MIT",
7
7
  "author": "IndieBob <info@indiebob.com>",
@@ -1,2 +0,0 @@
1
- var J=Object.defineProperty,z=Object.defineProperties;var G=Object.getOwnPropertyDescriptors;var k=Object.getOwnPropertySymbols;var W=Object.prototype.hasOwnProperty,Z=Object.prototype.propertyIsEnumerable;var A=(e,t,o)=>t in e?J(e,t,{enumerable:true,configurable:true,writable:true,value:o}):e[t]=o,d=(e,t)=>{for(var o in t||(t={}))W.call(t,o)&&A(e,o,t[o]);if(k)for(var o of k(t))Z.call(t,o)&&A(e,o,t[o]);return e},x=(e,t)=>z(e,G(t));var a=(e,t,o)=>new Promise((n,i)=>{var r=s=>{try{l(o.next(s));}catch(c){i(c);}},g=s=>{try{l(o.throw(s));}catch(c){i(c);}},l=s=>s.done?n(s.value):Promise.resolve(s.value).then(r,g);l((o=o.apply(e,t)).next());});var $="https://www.indiebob.com/api/collect";function D(e){var t,o,n,i;if(!e.projectId||!e.projectId.startsWith("proj_"))throw new Error(`[IndieBob] Invalid projectId "${e.projectId}". Must start with "proj_".`);return {projectId:e.projectId,endpoint:(t=e.endpoint)!=null?t:$,debug:(o=e.debug)!=null?o:false,respectDnt:(n=e.respectDnt)!=null?n:true,respectGpc:(i=e.respectGpc)!=null?i:true}}var u="_ib_anon";function h(){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-",t="";if(typeof crypto!="undefined"&&crypto.getRandomValues){let o=new Uint8Array(21);crypto.getRandomValues(o);for(let n of o)t+=e[n%e.length];}else for(let o=0;o<21;o++)t+=e[Math.floor(Math.random()*e.length)];return t}function v(){try{let e=localStorage.getItem(u);return e||(e=h(),localStorage.setItem(u,e)),e}catch(e){try{let t=sessionStorage.getItem(u);return t||(t=h(),sessionStorage.setItem(u,t)),t}catch(t){return h()}}}function P(){try{localStorage.removeItem(u);}catch(e){}try{sessionStorage.removeItem(u);}catch(e){}}var y="_ib_session",I="_ib_session_last";function N(){try{return crypto.randomUUID()}catch(e){return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}}function S(){var e;try{let t=Date.now(),o=parseInt((e=sessionStorage.getItem(I))!=null?e:"0",10),n=sessionStorage.getItem(y),i=o>0&&t-o>18e5;return (!n||i)&&(n=N(),sessionStorage.setItem(y,n)),sessionStorage.setItem(I,String(t)),n}catch(t){return N()}}function U(){try{sessionStorage.removeItem(y);}catch(e){}try{sessionStorage.removeItem(I);}catch(e){}}var b="_ib_first_utm",M="_ib_last_utm",_="_ib_referrer";function q(e){let t=new URLSearchParams(e),o={},n=false;return t.has("utm_source")&&(o.source=t.get("utm_source"),n=true),t.has("utm_medium")&&(o.medium=t.get("utm_medium"),n=true),t.has("utm_campaign")&&(o.campaign=t.get("utm_campaign"),n=true),t.has("utm_term")&&(o.term=t.get("utm_term"),n=true),t.has("utm_content")&&(o.content=t.get("utm_content"),n=true),n?o:null}function B(e,t){let o=q(e);try{o&&!localStorage.getItem(b)&&localStorage.setItem(b,JSON.stringify(o)),o&&localStorage.setItem(M,JSON.stringify(o)),t&&!localStorage.getItem(_)&&localStorage.setItem(_,t);}catch(n){}}function F(e){var t;return (t=q(e))!=null?t:void 0}function L(){try{localStorage.removeItem(b);}catch(e){}try{localStorage.removeItem(M);}catch(e){}try{localStorage.removeItem(_);}catch(e){}}var p="_ib_optout",tt="_ib_queue";function f(e){try{if(localStorage.getItem(p))return !1}catch(t){}return !(e.respectDnt&&typeof navigator!="undefined"&&(navigator.doNotTrack==="1"||navigator.msDoNotTrack==="1")||e.respectGpc&&typeof navigator!="undefined"&&navigator.globalPrivacyControl===true)}function j(){try{localStorage.setItem(p,"1");}catch(e){}P(),U(),L();try{localStorage.removeItem(tt);}catch(e){}}function Y(){try{localStorage.removeItem(p);}catch(e){}}function K(){try{return !!localStorage.getItem(p)}catch(e){return false}}var et=[1e3,2e3,4e3];function ot(e){return a(this,null,function*(){return new Promise(t=>setTimeout(t,e))})}function w(e,t,o=false){return a(this,null,function*(){let n=JSON.stringify(e);if(o&&typeof navigator!="undefined"&&navigator.sendBeacon){let i=new Blob([n],{type:"application/json"}),r=navigator.sendBeacon(t.endpoint,i);return t.debug&&console.log("[IndieBob] sendBeacon:",r,e.batch.length,"events"),r}for(let i=0;i<3;i++){try{let r=yield fetch(t.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:n,keepalive:!0});if(r.ok)return t.debug&&console.log("[IndieBob] sent:",e.batch.length,"events"),!0;if(r.status>=400&&r.status<500)return t.debug&&console.warn("[IndieBob] 4xx error, not retrying:",r.status),!1}catch(r){t.debug&&console.warn("[IndieBob] fetch error (attempt",i+1,"):",r);}i<2&&(yield ot(et[i]));}return t.debug&&console.warn("[IndieBob] failed to send after",3,"attempts"),false})}var E="_ib_queue",nt=10,it=5e3,rt=50,m=class{constructor(t){this.queue=[];this.timer=null;this.flushing=false;this.config=t,this.startTimer(),this.setupVisibilityFlush(),this.setupOnlineFlush();}push(t){this.queue.push(t),this.queue.length>=nt&&this.flush();}flush(t=false){return a(this,null,function*(){if(this.flushing&&!t||this.queue.length===0)return;this.flushing=true;let o=this.queue.splice(0);(yield w({batch:o},this.config,t))||this.pushToOfflineQueue(o),this.flushing=false;})}flushOfflineQueue(){return a(this,null,function*(){let t=this.getOfflineQueue();if(t.length===0)return;this.clearOfflineQueue(),yield w({batch:t},this.config);})}destroy(){this.timer&&clearInterval(this.timer);}startTimer(){this.timer=setInterval(()=>{this.queue.length>0&&this.flush();},it);}setupVisibilityFlush(){typeof document!="undefined"&&document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flush(true);},{passive:true});}setupOnlineFlush(){typeof window!="undefined"&&(window.addEventListener("online",()=>{this.flushOfflineQueue();}),navigator.onLine&&this.flushOfflineQueue());}pushToOfflineQueue(t){try{let i=[...this.getOfflineQueue(),...t].slice(-rt);localStorage.setItem(E,JSON.stringify(i));}catch(o){}}getOfflineQueue(){try{let t=localStorage.getItem(E);return t?JSON.parse(t):[]}catch(t){return []}}clearOfflineQueue(){try{localStorage.removeItem(E);}catch(t){}}};function Q(){if(typeof window=="undefined")return "desktop";let e=window.innerWidth;return e<=768?"mobile":e<=1024?"tablet":"desktop"}function V(){return typeof window=="undefined"?{width:0,height:0}:{width:window.innerWidth,height:window.innerHeight}}function T(e){var c,O,R,C;let t=typeof window=="undefined",o=(c=e==null?void 0:e.path)!=null?c:t?"":window.location.pathname+window.location.search,n=t?"":window.location.href,i=(O=e==null?void 0:e.title)!=null?O:t?"":document.title,r=(R=e==null?void 0:e.referrer)!=null?R:t?"":document.referrer,g=V(),l=Q(),s=t?void 0:F(window.location.search);return {page:{path:o,url:n,title:i,referrer:r},device:x(d({},g),{type:l}),utm:s,locale:t?"en":navigator.language,timezone:t?"UTC":(C=Intl.DateTimeFormat().resolvedOptions().timeZone)!=null?C:"UTC",sdkVersion:"0.1.1"}}function H(e){if(typeof window=="undefined")return ()=>{};let t=history.pushState.bind(history),o=history.replaceState.bind(history);return history.pushState=function(...n){t(...n),e();},history.replaceState=function(...n){o(...n);},window.addEventListener("popstate",e),()=>{history.pushState=t,history.replaceState=o,window.removeEventListener("popstate",e);}}var X=class e{constructor(t){this.cleanupHistory=null;this.config=t,this.queue=new m(t),typeof window!="undefined"&&B(window.location.search,document.referrer);}static init(t){let o=D(t);return new e(o)}page(t){f(this.config)&&this.queue.push(this.buildEvent("page",{context:T(t)}));}track(t,o){f(this.config)&&this.queue.push(this.buildEvent("track",{event:t,properties:o}));}identify(t,o){f(this.config)&&(this.userId=t,this.queue.push(this.buildEvent("identify",{traits:o,userId:t})));}revenue(t){var o;f(this.config)&&this.queue.push(this.buildEvent("revenue",{revenue:{amount:t.amount,currency:(o=t.currency)!=null?o:"USD",plan:t.plan,type:t.type}}));}optOut(){this.queue.flush(),j(),this.userId=void 0,this.config.debug&&console.log("[IndieBob] opted out");}optIn(){Y(),this.config.debug&&console.log("[IndieBob] opted in");}isOptedOut(){return K()}flush(){return a(this,null,function*(){yield this.queue.flush();})}getAnonymousId(){return v()}getSessionId(){return S()}getConfig(){return Object.freeze(d({},this.config))}enableAutoPage(){var t;return (t=this.cleanupHistory)==null||t.call(this),this.cleanupHistory=H(()=>this.page()),()=>{var o;(o=this.cleanupHistory)==null||o.call(this),this.cleanupHistory=null;}}buildEvent(t,o){var n,i;return {v:1,projectId:this.config.projectId,type:t,anonymousId:v(),userId:(n=this.userId)!=null?n:o.userId,sessionId:S(),timestamp:new Date().toISOString(),context:(i=o.context)!=null?i:T(),event:o.event,properties:o.properties,traits:o.traits,revenue:o.revenue}}};
2
- export{X as a};
@@ -1,2 +0,0 @@
1
- var tt=Object.defineProperty,et=Object.defineProperties;var nt=Object.getOwnPropertyDescriptors;var P=Object.getOwnPropertySymbols;var ot=Object.prototype.hasOwnProperty,it=Object.prototype.propertyIsEnumerable;var k=(e,t,n)=>t in e?tt(e,t,{enumerable:true,configurable:true,writable:true,value:n}):e[t]=n,d=(e,t)=>{for(var n in t||(t={}))ot.call(t,n)&&k(e,n,t[n]);if(P)for(var n of P(t))it.call(t,n)&&k(e,n,t[n]);return e},A=(e,t)=>et(e,nt(t));var c=(e,t,n)=>new Promise((o,i)=>{var r=a=>{try{f(n.next(a));}catch(u){i(u);}},s=a=>{try{f(n.throw(a));}catch(u){i(u);}},f=a=>a.done?o(a.value):Promise.resolve(a.value).then(r,s);f((n=n.apply(e,t)).next());});var rt="https://www.indiebob.com/api/collect";function N(e){var t,n,o,i,r;if(!e.projectId||!e.projectId.startsWith("proj_"))throw new Error(`[IndieBob] Invalid projectId "${e.projectId}". Must start with "proj_".`);return {projectId:e.projectId,endpoint:(t=e.endpoint)!=null?t:rt,debug:(n=e.debug)!=null?n:false,respectDnt:(o=e.respectDnt)!=null?o:true,respectGpc:(i=e.respectGpc)!=null?i:true,autoDetect:(r=e.autoDetect)!=null?r:true}}var l="_ib_anon";function m(){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-",t="";if(typeof crypto!="undefined"&&crypto.getRandomValues){let n=new Uint8Array(21);crypto.getRandomValues(n);for(let o of n)t+=e[o%e.length];}else for(let n=0;n<21;n++)t+=e[Math.floor(Math.random()*e.length)];return t}function v(){try{let e=localStorage.getItem(l);return e||(e=m(),localStorage.setItem(l,e)),e}catch(e){try{let t=sessionStorage.getItem(l);return t||(t=m(),sessionStorage.setItem(l,t)),t}catch(t){return m()}}}function U(){try{localStorage.removeItem(l);}catch(e){}try{sessionStorage.removeItem(l);}catch(e){}}var y="_ib_session",I="_ib_session_last";function M(){try{return crypto.randomUUID()}catch(e){return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}}function S(){var e;try{let t=Date.now(),n=parseInt((e=sessionStorage.getItem(I))!=null?e:"0",10),o=sessionStorage.getItem(y),i=n>0&&t-n>18e5;return (!o||i)&&(o=M(),sessionStorage.setItem(y,o)),sessionStorage.setItem(I,String(t)),o}catch(t){return M()}}function F(){try{sessionStorage.removeItem(y);}catch(e){}try{sessionStorage.removeItem(I);}catch(e){}}var b="_ib_first_utm",q="_ib_last_utm",_="_ib_referrer";function B(e){let t=new URLSearchParams(e),n={},o=false;return t.has("utm_source")&&(n.source=t.get("utm_source"),o=true),t.has("utm_medium")&&(n.medium=t.get("utm_medium"),o=true),t.has("utm_campaign")&&(n.campaign=t.get("utm_campaign"),o=true),t.has("utm_term")&&(n.term=t.get("utm_term"),o=true),t.has("utm_content")&&(n.content=t.get("utm_content"),o=true),o?n:null}function j(e,t){let n=B(e);try{n&&!localStorage.getItem(b)&&localStorage.setItem(b,JSON.stringify(n)),n&&localStorage.setItem(q,JSON.stringify(n)),t&&!localStorage.getItem(_)&&localStorage.setItem(_,t);}catch(o){}}function L(e){var t;return (t=B(e))!=null?t:void 0}function Y(){try{localStorage.removeItem(b);}catch(e){}try{localStorage.removeItem(q);}catch(e){}try{localStorage.removeItem(_);}catch(e){}}var g="_ib_optout",st="_ib_queue";function p(e){try{if(localStorage.getItem(g))return !1}catch(t){}return !(e.respectDnt&&typeof navigator!="undefined"&&(navigator.doNotTrack==="1"||navigator.msDoNotTrack==="1")||e.respectGpc&&typeof navigator!="undefined"&&navigator.globalPrivacyControl===true)}function K(){try{localStorage.setItem(g,"1");}catch(e){}U(),F(),Y();try{localStorage.removeItem(st);}catch(e){}}function Q(){try{localStorage.removeItem(g);}catch(e){}}function V(){try{return !!localStorage.getItem(g)}catch(e){return false}}var at=[1e3,2e3,4e3];function ct(e){return c(this,null,function*(){return new Promise(t=>setTimeout(t,e))})}function E(e,t,n=false){return c(this,null,function*(){let o=JSON.stringify(e);if(n&&typeof navigator!="undefined"&&navigator.sendBeacon){let i=new Blob([o],{type:"application/json"}),r=navigator.sendBeacon(t.endpoint,i);return t.debug&&console.log("[IndieBob] sendBeacon:",r,e.batch.length,"events"),r}for(let i=0;i<3;i++){try{let r=yield fetch(t.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:o,keepalive:!0});if(r.ok)return t.debug&&console.log("[IndieBob] sent:",e.batch.length,"events"),!0;if(r.status>=400&&r.status<500)return t.debug&&console.warn("[IndieBob] 4xx error, not retrying:",r.status),!1}catch(r){t.debug&&console.warn("[IndieBob] fetch error (attempt",i+1,"):",r);}i<2&&(yield ct(at[i]));}return t.debug&&console.warn("[IndieBob] failed to send after",3,"attempts"),false})}var w="_ib_queue",ut=10,lt=5e3,ft=50,h=class{constructor(t){this.queue=[];this.timer=null;this.flushing=false;this.config=t,this.startTimer(),this.setupVisibilityFlush(),this.setupOnlineFlush();}push(t){this.queue.push(t),this.queue.length>=ut&&this.flush();}flush(t=false){return c(this,null,function*(){if(this.flushing&&!t||this.queue.length===0)return;this.flushing=true;let n=this.queue.splice(0);(yield E({batch:n},this.config,t))||this.pushToOfflineQueue(n),this.flushing=false;})}flushOfflineQueue(){return c(this,null,function*(){let t=this.getOfflineQueue();if(t.length===0)return;this.clearOfflineQueue(),yield E({batch:t},this.config);})}destroy(){this.timer&&clearInterval(this.timer);}startTimer(){this.timer=setInterval(()=>{this.queue.length>0&&this.flush();},lt);}setupVisibilityFlush(){typeof document!="undefined"&&document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flush(true);},{passive:true});}setupOnlineFlush(){typeof window!="undefined"&&(window.addEventListener("online",()=>{this.flushOfflineQueue();}),navigator.onLine&&this.flushOfflineQueue());}pushToOfflineQueue(t){try{let i=[...this.getOfflineQueue(),...t].slice(-ft);localStorage.setItem(w,JSON.stringify(i));}catch(n){}}getOfflineQueue(){try{let t=localStorage.getItem(w);return t?JSON.parse(t):[]}catch(t){return []}}clearOfflineQueue(){try{localStorage.removeItem(w);}catch(t){}}};function H(){if(typeof window=="undefined")return "desktop";let e=window.innerWidth;return e<=768?"mobile":e<=1024?"tablet":"desktop"}function X(){return typeof window=="undefined"?{width:0,height:0}:{width:window.innerWidth,height:window.innerHeight}}function T(e){var u,C,x,D;let t=typeof window=="undefined",n=(u=e==null?void 0:e.path)!=null?u:t?"":window.location.pathname+window.location.search,o=t?"":window.location.href,i=(C=e==null?void 0:e.title)!=null?C:t?"":document.title,r=(x=e==null?void 0:e.referrer)!=null?x:t?"":document.referrer,s=X(),f=H(),a=t?void 0:L(window.location.search);return {page:{path:n,url:o,title:i,referrer:r},device:A(d({},s),{type:f}),utm:a,locale:t?"en":navigator.language,timezone:t?"UTC":(D=Intl.DateTimeFormat().resolvedOptions().timeZone)!=null?D:"UTC",sdkVersion:"0.1.1"}}function J(e){if(typeof window=="undefined")return ()=>{};let t=history.pushState.bind(history),n=history.replaceState.bind(history);return history.pushState=function(...o){t(...o),e();},history.replaceState=function(...o){n(...o);},window.addEventListener("popstate",e),()=>{history.pushState=t,history.replaceState=n,window.removeEventListener("popstate",e);}}var R={signup:[/\/(sign-?up|register|join|create-?account|get-?started|onboard)/i],login:[/\/(log-?in|sign-?in|auth(\/login)?)/i],pricing:[/\/(pricing|plans|upgrade|subscribe)/i]};function z(e,t){var o,i,r;let n={signup:(o=t==null?void 0:t.signup)!=null?o:R.signup,login:(i=t==null?void 0:t.login)!=null?i:R.login,pricing:(r=t==null?void 0:t.pricing)!=null?r:R.pricing};return n.signup.some(s=>s.test(e))?"signup_start":n.login.some(s=>s.test(e))?"login_view":n.pricing.some(s=>s.test(e))?"pricing_view":null}var O="ib_identified";function $(){return typeof localStorage=="undefined"?true:!localStorage.getItem(O)}function G(){typeof localStorage!="undefined"&&localStorage.setItem(O,"1");}function W(){typeof localStorage!="undefined"&&localStorage.removeItem(O);}var Z=class e{constructor(t){this.cleanupHistory=null;this.config=t,this.queue=new h(t),typeof window!="undefined"&&j(window.location.search,document.referrer);}static init(t){let n=N(t);return new e(n)}page(t){if(!p(this.config))return;let n=T(t);if(this.queue.push(this.buildEvent("page",{context:n})),this.config.autoDetect!==false){let o=n.page.path,i=typeof this.config.autoDetect=="object"?{signup:this.config.autoDetect.signupPaths,login:this.config.autoDetect.loginPaths,pricing:this.config.autoDetect.pricingPaths}:void 0,r=z(o,i);r&&(this.queue.push(this.buildEvent("track",{event:r,properties:{auto:true},context:n})),this.config.debug&&console.log(`[IndieBob] auto-detected: ${r} on ${o}`));}}track(t,n){p(this.config)&&this.queue.push(this.buildEvent("track",{event:t,properties:n}));}identify(t,n){if(p(this.config)&&(this.userId=t,this.queue.push(this.buildEvent("identify",{traits:n,userId:t})),this.config.autoDetect!==false)){let o=$(),i=o?"signup":"login";this.queue.push(this.buildEvent("track",{event:i,properties:{auto:true}})),o&&G(),this.config.debug&&console.log(`[IndieBob] auto-detected: ${i} for ${t}`);}}revenue(t){var n;p(this.config)&&this.queue.push(this.buildEvent("revenue",{revenue:{amount:t.amount,currency:(n=t.currency)!=null?n:"USD",plan:t.plan,type:t.type}}));}optOut(){this.queue.flush(),K(),W(),this.userId=void 0,this.config.debug&&console.log("[IndieBob] opted out");}optIn(){Q(),this.config.debug&&console.log("[IndieBob] opted in");}isOptedOut(){return V()}flush(){return c(this,null,function*(){yield this.queue.flush();})}getAnonymousId(){return v()}getSessionId(){return S()}getConfig(){return Object.freeze(d({},this.config))}enableAutoPage(){var t;return (t=this.cleanupHistory)==null||t.call(this),this.cleanupHistory=J(()=>this.page()),()=>{var n;(n=this.cleanupHistory)==null||n.call(this),this.cleanupHistory=null;}}buildEvent(t,n){var o,i;return {v:1,projectId:this.config.projectId,type:t,anonymousId:v(),userId:(o=this.userId)!=null?o:n.userId,sessionId:S(),timestamp:new Date().toISOString(),context:(i=n.context)!=null?i:T(),event:n.event,properties:n.properties,traits:n.traits,revenue:n.revenue}}};
2
- export{Z as a};
@@ -1,2 +0,0 @@
1
- var J=Object.defineProperty,z=Object.defineProperties;var G=Object.getOwnPropertyDescriptors;var k=Object.getOwnPropertySymbols;var W=Object.prototype.hasOwnProperty,Z=Object.prototype.propertyIsEnumerable;var A=(e,t,o)=>t in e?J(e,t,{enumerable:true,configurable:true,writable:true,value:o}):e[t]=o,d=(e,t)=>{for(var o in t||(t={}))W.call(t,o)&&A(e,o,t[o]);if(k)for(var o of k(t))Z.call(t,o)&&A(e,o,t[o]);return e},x=(e,t)=>z(e,G(t));var a=(e,t,o)=>new Promise((n,i)=>{var r=s=>{try{l(o.next(s));}catch(c){i(c);}},g=s=>{try{l(o.throw(s));}catch(c){i(c);}},l=s=>s.done?n(s.value):Promise.resolve(s.value).then(r,g);l((o=o.apply(e,t)).next());});var $="https://indiebob.com/api/collect";function D(e){var t,o,n,i;if(!e.projectId||!e.projectId.startsWith("proj_"))throw new Error(`[IndieBob] Invalid projectId "${e.projectId}". Must start with "proj_".`);return {projectId:e.projectId,endpoint:(t=e.endpoint)!=null?t:$,debug:(o=e.debug)!=null?o:false,respectDnt:(n=e.respectDnt)!=null?n:true,respectGpc:(i=e.respectGpc)!=null?i:true}}var u="_ib_anon";function h(){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-",t="";if(typeof crypto!="undefined"&&crypto.getRandomValues){let o=new Uint8Array(21);crypto.getRandomValues(o);for(let n of o)t+=e[n%e.length];}else for(let o=0;o<21;o++)t+=e[Math.floor(Math.random()*e.length)];return t}function v(){try{let e=localStorage.getItem(u);return e||(e=h(),localStorage.setItem(u,e)),e}catch(e){try{let t=sessionStorage.getItem(u);return t||(t=h(),sessionStorage.setItem(u,t)),t}catch(t){return h()}}}function P(){try{localStorage.removeItem(u);}catch(e){}try{sessionStorage.removeItem(u);}catch(e){}}var y="_ib_session",I="_ib_session_last";function N(){try{return crypto.randomUUID()}catch(e){return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}}function S(){var e;try{let t=Date.now(),o=parseInt((e=sessionStorage.getItem(I))!=null?e:"0",10),n=sessionStorage.getItem(y),i=o>0&&t-o>18e5;return (!n||i)&&(n=N(),sessionStorage.setItem(y,n)),sessionStorage.setItem(I,String(t)),n}catch(t){return N()}}function U(){try{sessionStorage.removeItem(y);}catch(e){}try{sessionStorage.removeItem(I);}catch(e){}}var b="_ib_first_utm",M="_ib_last_utm",_="_ib_referrer";function q(e){let t=new URLSearchParams(e),o={},n=false;return t.has("utm_source")&&(o.source=t.get("utm_source"),n=true),t.has("utm_medium")&&(o.medium=t.get("utm_medium"),n=true),t.has("utm_campaign")&&(o.campaign=t.get("utm_campaign"),n=true),t.has("utm_term")&&(o.term=t.get("utm_term"),n=true),t.has("utm_content")&&(o.content=t.get("utm_content"),n=true),n?o:null}function B(e,t){let o=q(e);try{o&&!localStorage.getItem(b)&&localStorage.setItem(b,JSON.stringify(o)),o&&localStorage.setItem(M,JSON.stringify(o)),t&&!localStorage.getItem(_)&&localStorage.setItem(_,t);}catch(n){}}function F(e){var t;return (t=q(e))!=null?t:void 0}function L(){try{localStorage.removeItem(b);}catch(e){}try{localStorage.removeItem(M);}catch(e){}try{localStorage.removeItem(_);}catch(e){}}var p="_ib_optout",tt="_ib_queue";function f(e){try{if(localStorage.getItem(p))return !1}catch(t){}return !(e.respectDnt&&typeof navigator!="undefined"&&(navigator.doNotTrack==="1"||navigator.msDoNotTrack==="1")||e.respectGpc&&typeof navigator!="undefined"&&navigator.globalPrivacyControl===true)}function j(){try{localStorage.setItem(p,"1");}catch(e){}P(),U(),L();try{localStorage.removeItem(tt);}catch(e){}}function Y(){try{localStorage.removeItem(p);}catch(e){}}function K(){try{return !!localStorage.getItem(p)}catch(e){return false}}var et=[1e3,2e3,4e3];function ot(e){return a(this,null,function*(){return new Promise(t=>setTimeout(t,e))})}function w(e,t,o=false){return a(this,null,function*(){let n=JSON.stringify(e);if(o&&typeof navigator!="undefined"&&navigator.sendBeacon){let i=new Blob([n],{type:"application/json"}),r=navigator.sendBeacon(t.endpoint,i);return t.debug&&console.log("[IndieBob] sendBeacon:",r,e.batch.length,"events"),r}for(let i=0;i<3;i++){try{let r=yield fetch(t.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:n,keepalive:!0});if(r.ok)return t.debug&&console.log("[IndieBob] sent:",e.batch.length,"events"),!0;if(r.status>=400&&r.status<500)return t.debug&&console.warn("[IndieBob] 4xx error, not retrying:",r.status),!1}catch(r){t.debug&&console.warn("[IndieBob] fetch error (attempt",i+1,"):",r);}i<2&&(yield ot(et[i]));}return t.debug&&console.warn("[IndieBob] failed to send after",3,"attempts"),false})}var E="_ib_queue",nt=10,it=5e3,rt=50,m=class{constructor(t){this.queue=[];this.timer=null;this.flushing=false;this.config=t,this.startTimer(),this.setupVisibilityFlush(),this.setupOnlineFlush();}push(t){this.queue.push(t),this.queue.length>=nt&&this.flush();}flush(t=false){return a(this,null,function*(){if(this.flushing&&!t||this.queue.length===0)return;this.flushing=true;let o=this.queue.splice(0);(yield w({batch:o},this.config,t))||this.pushToOfflineQueue(o),this.flushing=false;})}flushOfflineQueue(){return a(this,null,function*(){let t=this.getOfflineQueue();if(t.length===0)return;this.clearOfflineQueue(),yield w({batch:t},this.config);})}destroy(){this.timer&&clearInterval(this.timer);}startTimer(){this.timer=setInterval(()=>{this.queue.length>0&&this.flush();},it);}setupVisibilityFlush(){typeof document!="undefined"&&document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flush(true);},{passive:true});}setupOnlineFlush(){typeof window!="undefined"&&(window.addEventListener("online",()=>{this.flushOfflineQueue();}),navigator.onLine&&this.flushOfflineQueue());}pushToOfflineQueue(t){try{let i=[...this.getOfflineQueue(),...t].slice(-rt);localStorage.setItem(E,JSON.stringify(i));}catch(o){}}getOfflineQueue(){try{let t=localStorage.getItem(E);return t?JSON.parse(t):[]}catch(t){return []}}clearOfflineQueue(){try{localStorage.removeItem(E);}catch(t){}}};function Q(){if(typeof window=="undefined")return "desktop";let e=window.innerWidth;return e<=768?"mobile":e<=1024?"tablet":"desktop"}function V(){return typeof window=="undefined"?{width:0,height:0}:{width:window.innerWidth,height:window.innerHeight}}function T(e){var c,O,R,C;let t=typeof window=="undefined",o=(c=e==null?void 0:e.path)!=null?c:t?"":window.location.pathname+window.location.search,n=t?"":window.location.href,i=(O=e==null?void 0:e.title)!=null?O:t?"":document.title,r=(R=e==null?void 0:e.referrer)!=null?R:t?"":document.referrer,g=V(),l=Q(),s=t?void 0:F(window.location.search);return {page:{path:o,url:n,title:i,referrer:r},device:x(d({},g),{type:l}),utm:s,locale:t?"en":navigator.language,timezone:t?"UTC":(C=Intl.DateTimeFormat().resolvedOptions().timeZone)!=null?C:"UTC",sdkVersion:"0.1.0"}}function H(e){if(typeof window=="undefined")return ()=>{};let t=history.pushState.bind(history),o=history.replaceState.bind(history);return history.pushState=function(...n){t(...n),e();},history.replaceState=function(...n){o(...n);},window.addEventListener("popstate",e),()=>{history.pushState=t,history.replaceState=o,window.removeEventListener("popstate",e);}}var X=class e{constructor(t){this.cleanupHistory=null;this.config=t,this.queue=new m(t),typeof window!="undefined"&&B(window.location.search,document.referrer);}static init(t){let o=D(t);return new e(o)}page(t){f(this.config)&&this.queue.push(this.buildEvent("page",{context:T(t)}));}track(t,o){f(this.config)&&this.queue.push(this.buildEvent("track",{event:t,properties:o}));}identify(t,o){f(this.config)&&(this.userId=t,this.queue.push(this.buildEvent("identify",{traits:o,userId:t})));}revenue(t){var o;f(this.config)&&this.queue.push(this.buildEvent("revenue",{revenue:{amount:t.amount,currency:(o=t.currency)!=null?o:"USD",plan:t.plan,type:t.type}}));}optOut(){this.queue.flush(),j(),this.userId=void 0,this.config.debug&&console.log("[IndieBob] opted out");}optIn(){Y(),this.config.debug&&console.log("[IndieBob] opted in");}isOptedOut(){return K()}flush(){return a(this,null,function*(){yield this.queue.flush();})}getAnonymousId(){return v()}getSessionId(){return S()}getConfig(){return Object.freeze(d({},this.config))}enableAutoPage(){var t;return (t=this.cleanupHistory)==null||t.call(this),this.cleanupHistory=H(()=>this.page()),()=>{var o;(o=this.cleanupHistory)==null||o.call(this),this.cleanupHistory=null;}}buildEvent(t,o){var n,i;return {v:1,projectId:this.config.projectId,type:t,anonymousId:v(),userId:(n=this.userId)!=null?n:o.userId,sessionId:S(),timestamp:new Date().toISOString(),context:(i=o.context)!=null?i:T(),event:o.event,properties:o.properties,traits:o.traits,revenue:o.revenue}}};
2
- export{X as a};