@sprig-technologies/sprig-browser 2.32.7 → 2.32.10

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/core.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const i=require("./metricsReporter-DNKMOwn_.cjs"),e=require("./core-DdcxBCQS.cjs");exports.DismissReason=i.DismissReason,exports.SprigEvent=i.SprigEvent,exports.SprigAPI=e.SprigAPI,exports.default=e.core,exports.sprig=e.sprig;
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const i=require("./metricsReporter-eI04W7R0.cjs"),e=require("./core-B_CnBIaq.cjs");exports.DismissReason=i.DismissReason,exports.SprigEvent=i.SprigEvent,exports.SprigAPI=e.SprigAPI,exports.default=e.core,exports.sprig=e.sprig;
package/dist/core.d.ts CHANGED
@@ -1507,6 +1507,7 @@ type SprigEventMap = {
1507
1507
  answeredAt?: number;
1508
1508
  questionIndex?: number;
1509
1509
  value: unknown;
1510
+ "survey.id": number;
1510
1511
  }
1511
1512
  ];
1512
1513
  [SprigEvent.ReplayCapture]: [
@@ -1916,6 +1917,7 @@ declare namespace sprigConfig {
1916
1917
  envId: string;
1917
1918
  error?: Error;
1918
1919
  feedbackCustomStyles?: string;
1920
+ forceDirectEmbed?: boolean;
1919
1921
  frameId: string;
1920
1922
  isMobileSDK?: boolean;
1921
1923
  loaded: boolean;
@@ -1966,7 +1968,7 @@ declare global {
1966
1968
  Sprig: sprigConfig.WindowSprig;
1967
1969
  UserLeap: sprigConfig.WindowSprig;
1968
1970
  rrwebRecord?: (typeof _rrweb_record)["record"];
1969
- sprigAPI?: object;
1971
+ sprigAPI?: { openUrl: (url: string) => void };
1970
1972
  SprigLoggerCallback?: (message: string) => void;
1971
1973
  }
1972
1974
 
package/dist/core.js CHANGED
@@ -1,5 +1,5 @@
1
- import { D as r, S as e } from "./metricsReporter-rplm9tEP.js";
2
- import { S as o, c as p, s as t } from "./core-B-DyGs3n.js";
1
+ import { D as r, S as e } from "./metricsReporter-lf84Y5sr.js";
2
+ import { S as o, c as p, s as t } from "./core-s7v77Fsd.js";
3
3
  export {
4
4
  r as DismissReason,
5
5
  o as SprigAPI,
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("./core-DdcxBCQS.cjs");require("./replay.cjs");const r=require("./metricsReporter-DNKMOwn_.cjs");exports.SprigAPI=e.SprigAPI,exports.default=e.core,exports.sprig=e.sprig,exports.DismissReason=r.DismissReason,exports.SprigEvent=r.SprigEvent;
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("./core-B_CnBIaq.cjs");require("./replay.cjs");const r=require("./metricsReporter-eI04W7R0.cjs");exports.SprigAPI=e.SprigAPI,exports.default=e.core,exports.sprig=e.sprig,exports.DismissReason=r.DismissReason,exports.SprigEvent=r.SprigEvent;
package/dist/index.d.ts CHANGED
@@ -1507,6 +1507,7 @@ type SprigEventMap = {
1507
1507
  answeredAt?: number;
1508
1508
  questionIndex?: number;
1509
1509
  value: unknown;
1510
+ "survey.id": number;
1510
1511
  }
1511
1512
  ];
1512
1513
  [SprigEvent.ReplayCapture]: [
@@ -1916,6 +1917,7 @@ declare namespace sprigConfig {
1916
1917
  envId: string;
1917
1918
  error?: Error;
1918
1919
  feedbackCustomStyles?: string;
1920
+ forceDirectEmbed?: boolean;
1919
1921
  frameId: string;
1920
1922
  isMobileSDK?: boolean;
1921
1923
  loaded: boolean;
@@ -1966,7 +1968,7 @@ declare global {
1966
1968
  Sprig: sprigConfig.WindowSprig;
1967
1969
  UserLeap: sprigConfig.WindowSprig;
1968
1970
  rrwebRecord?: (typeof _rrweb_record)["record"];
1969
- sprigAPI?: object;
1971
+ sprigAPI?: { openUrl: (url: string) => void };
1970
1972
  SprigLoggerCallback?: (message: string) => void;
1971
1973
  }
1972
1974
 
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { S as i, c as o, s as p } from "./core-B-DyGs3n.js";
1
+ import { S as i, c as o, s as p } from "./core-s7v77Fsd.js";
2
2
  import "./replay.js";
3
- import { D as t, S as m } from "./metricsReporter-rplm9tEP.js";
3
+ import { D as t, S as m } from "./metricsReporter-lf84Y5sr.js";
4
4
  export {
5
5
  t as DismissReason,
6
6
  i as SprigAPI,
@@ -0,0 +1 @@
1
+ "use strict";var Y=Object.defineProperty;var j=(e,t,r)=>t in e?Y(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var l=(e,t,r)=>(j(e,typeof t!="symbol"?t+"":t,r),r);var U=(e=>(e.Closed="close.click",e.Complete="survey.completed",e.FeedbackClosed="feedback.closed",e.PageChange="page.change",e.API="api",e.Override="override",e))(U||{}),A=(e=>(e.ReplayCapture="replay.capture",e.FeedbackButtonLoaded="feedback.button.loaded",e.SDKReady="sdk.ready",e.SurveyAppeared="survey.appeared",e.SurveyClosed="survey.closed",e.SurveyDimensions="survey.dimensions",e.SurveyFadingOut="survey.fadingOut",e.SurveyHeight="survey.height",e.SurveyPresented="survey.presented",e.SurveyLifeCycle="survey.lifeCycle",e.SurveyWidth="survey.width",e.SurveyWillClose="survey.willClose",e.SurveyWillPresent="survey.will.present",e.CloseSurveyOnOverlayClick="close.survey.overlayClick",e.VisitorIDUpdated="visitor.id.updated",e.QuestionAnswered="question.answered",e))(A||{});let m;const H=new Uint8Array(16);function B(){if(!m&&(m=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!m))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return m(H)}const o=[];for(let e=0;e<256;++e)o.push((e+256).toString(16).slice(1));const w={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)},b=new class{constructor(){l(this,"breadcrumbs",[])}getTimeStamp(){return new Date().toISOString()}addBreadcrumb(e){this.breadcrumbs.push(e),this.breadcrumbs.length>300&&this.breadcrumbs.shift()}debug(e,t="debug"){this.addBreadcrumb({category:t,level:"info",message:e,timestamp:this.getTimeStamp(),type:"debug"})}error(e,t={}){this.addBreadcrumb({category:"error",data:t,level:"error",message:e,timestamp:this.getTimeStamp(),type:"error"})}http(e,t){this.addBreadcrumb({category:"xhr",data:t,message:e,timestamp:this.getTimeStamp(),type:"http"})}info(e,t={}){this.addBreadcrumb({category:"info",data:t,level:"info",message:e,timestamp:this.getTimeStamp(),type:"info"})}navigation(e,t){this.addBreadcrumb({category:"navigation",data:t,message:e,timestamp:this.getTimeStamp(),type:"navigation"})}};var F=class extends Error{constructor(e,t,r){super(`Possible EventEmitter memory leak detected. ${r} ${t.toString()} listeners added. Use emitter.setMaxListeners() to increase limit`),this.emitter=e,this.type=t,this.count=r,this.name="MaxListenersExceededWarning"}},D=class{static listenerCount(e,t){return e.listenerCount(t)}constructor(){this.events=new Map,this.maxListeners=D.defaultMaxListeners,this.hasWarnedAboutPotentialMemoryLeak=!1}_emitInternalEvent(e,t,r){this.emit(e,t,r)}_getListeners(e){return Array.prototype.concat.apply([],this.events.get(e))||[]}_removeListener(e,t){const r=e.indexOf(t);return r>-1&&e.splice(r,1),[]}_wrapOnceListener(e,t){const r=(...s)=>(this.removeListener(e,r),t.apply(this,s));return Object.defineProperty(r,"name",{value:t.name}),r}setMaxListeners(e){return this.maxListeners=e,this}getMaxListeners(){return this.maxListeners}eventNames(){return Array.from(this.events.keys())}emit(e,...t){const r=this._getListeners(e);return r.forEach(s=>{s.apply(this,t)}),r.length>0}addListener(e,t){this._emitInternalEvent("newListener",e,t);const r=this._getListeners(e).concat(t);if(this.events.set(e,r),this.maxListeners>0&&this.listenerCount(e)>this.maxListeners&&!this.hasWarnedAboutPotentialMemoryLeak){this.hasWarnedAboutPotentialMemoryLeak=!0;const s=new F(this,e,this.listenerCount(e));console.warn(s)}return this}on(e,t){return this.addListener(e,t)}once(e,t){return this.addListener(e,this._wrapOnceListener(e,t))}prependListener(e,t){const r=this._getListeners(e);if(r.length>0){const s=[t].concat(r);this.events.set(e,s)}else this.events.set(e,r.concat(t));return this}prependOnceListener(e,t){return this.prependListener(e,this._wrapOnceListener(e,t))}removeListener(e,t){const r=this._getListeners(e);return r.length>0&&(this._removeListener(r,t),this.events.set(e,r),this._emitInternalEvent("removeListener",e,t)),this}off(e,t){return this.removeListener(e,t)}removeAllListeners(e){return e?this.events.delete(e):this.events.clear(),this}listeners(e){return Array.from(this._getListeners(e))}listenerCount(e){return this._getListeners(e).length}rawListeners(e){return this.listeners(e)}},C=D;C.defaultMaxListeners=10;const q=new C,S=async e=>{await new Promise(t=>{setTimeout(t,e)})};class x{constructor(t){l(this,"storage");l(this,"tempStorage",{});l(this,"isStorageAvailable");try{this.storage=window[t];const r="__storage_test__";this.storage.setItem(r,r),this.storage.removeItem(r),this.isStorageAvailable=!0}catch{this.isStorageAvailable=!1}}setItem(t,r){this.isStorageAvailable&&this.storage?this.storage.setItem(t,r):this.tempStorage[t]=r}setItemObject(t,r){try{this.setItem(t,JSON.stringify(r))}catch(s){s instanceof Error&&(s.stack=t+": "+r,window.UserLeap.reportError("Failed to save to local storage",s))}}getItem(t){return this.isStorageAvailable&&this.storage?this.storage.getItem(t):this.tempStorage[t]}getItemObject(t){const r=this.getItem(t);if(r)try{return JSON.parse(r)}catch(s){s instanceof Error&&(s.stack=t+": "+r,window.UserLeap.reportError("Failed to parse local storage",s))}return{}}removeItem(t){this.isStorageAvailable&&this.storage?this.storage.removeItem(t):delete this.tempStorage[t]}clear(){this.isStorageAvailable&&this.storage?this.storage.clear():this.tempStorage={}}}const J=new x("sessionStorage"),$=new x("localStorage");class K{constructor(t){l(this,"payload");l(this,"promise");l(this,"reject",()=>{});l(this,"resolve",()=>{});this.payload=t,this.promise=new Promise((r,s)=>{this.reject=s,this.resolve=r})}resolveRequest(t){this.resolve(t)}}const E={replay:null},G=()=>{const e=[];return E.replay&&e.push("replay"),e.join(",")},z=10;let T=!1,M="",g=!1,P=!1,y=[];const Q=e=>e._config&&e._config.installationMethod?e._config.installationMethod:e._gtm?"web-gtm":e._segment?"web-segment":"web-snippet",N=(e="")=>{T=!0,M=e},I=async({shouldDropOnRateLimit:e,...t})=>{if(e)return{status:429};{const r=new K(t);return y.push(r),r.promise}},v=async(e,t)=>{const{retries:r=0,shouldDropOnRateLimit:s=!1,shouldRetryRequest:i=!1,...n}=t,d={url:e,options:n,retries:r,shouldDropOnRateLimit:s};if(g&&!i)return I(d);const u={ok:!1,reportError:!1};if(T)return console.info(`UserLeap - ${M}`),u;try{const c=await fetch(e,n);if(c.status===429){if(!g&&!s||i){g=!0;const a=c.headers.has("ratelimit-reset")?Number(c.headers.get("ratelimit-reset")):z;return await S(1e3*a),v(e,{...n,shouldDropOnRateLimit:s,shouldRetryRequest:!0})}return I(d)}if(g=!1,y.length&&(y.map(a=>{const h=a.payload;v(h.url,{...h.options,retries:h.retries,shouldDropOnRateLimit:h.shouldDropOnRateLimit}).then(W=>{a.resolveRequest(W)})}),y=[]),c.ok){if(c.status===249)return N(),u;const a=await c.text();try{return a&&a!=="OK"&&(c.json=JSON.parse(a)),c}catch{return{ok:!1,reportError:!1,error:new Error(`failed parsing response json for ${e} - ${a}`)}}}return c}catch(c){const a=r+1;return a>5||P?{ok:!1,reportError:!1,error:c}:(await S(1e3*Math.pow(2,r)),v(e,{...n,retries:a}))}},R=Object.freeze({contains:(e,t)=>t.includes(e),notContains:(e,t)=>!t.includes(e),exactly:(e,t)=>t===e,notExactly:(e,t)=>t!==e,startsWith:(e,t)=>t.startsWith(e),endsWith:(e,t)=>t.endsWith(e),regex:(e,t)=>new RegExp(e).test(t),legacy:(e,t)=>new RegExp(e,"i").test(t)});function k(e,t){const{matchType:r,pattern:s}=e,i=r?R[r]:R.legacy;let n=!1;try{n=i(s,t)}catch(d){const u=`[Sprig] (ERR-445) Failed to check url match with pattern ${s}`;d instanceof Error&&(console.warn(u,d),d.stack=JSON.stringify(e),window.UserLeap.reportError(u,d))}return n}let V=!0,f=!1;const X=["sdk_event_queue_latency_seconds","sdk_replay_add_event_batch_seconds","sdk_replay_cleanup_seconds","sdk_replay_compression_seconds","sdk_replay_get_events_between_seconds","sdk_replay_snapshot_seconds","sdk_mutations_nodes_added","sdk_mutations_nodes_removed","sdk_mutations_attributes_changed","sdk_mutations_character_data","sdk_dom_nodes_count","sdk_page_html_characters"];let L,p={};class Z{constructor(t){l(this,"_values",[]);l(this,"_isWebMetric");this.name=t,this._isWebMetric=X.includes(this.name)}report(t){if(V&&this._values.push({time:Date.now(),value:t}),f||!this._isWebMetric)return;const r=this.findExceededThreshold(t);r&&L&&L(t,r)}collect(){const t=this._values;return this._values=[],t}findExceededThreshold(t){const r=p[this.name];if(r)return r.find(s=>this.valueExceedsThreshold(t,s))}valueExceedsThreshold(t,r){return r.type==="max"?t>r.value:r.type==="min"&&t<r.value}}const _={},O=e=>{const t=new Z(e);return _[e]=t,t};exports.DismissReason=U,exports.EVENTS={FEEDBACK_BUTTON_LOADED:"feedback.button.loaded",SDK_READY:"sdk.ready",SURVEY_APPEARED:"survey.appeared",SURVEY_CLOSED:"survey.closed",SURVEY_DIMENSIONS:"survey.dimensions",SURVEY_FADING_OUT:"survey.fadingOut",SURVEY_HEIGHT:"survey.height",SURVEY_WIDTH:"survey.width",SURVEY_PRESENTED:"survey.presented",SURVEY_LIFE_CYCLE:"survey.lifeCycle",SURVEY_WILL_CLOSE:"survey.willClose",SURVEY_WILL_PRESENT:"survey.will.present",QUESTION_ANSWERED:"question.answered",REPLAY_CAPTURE:"replay.capture",CLOSE_SURVEY_ON_OVERLAY_CLICK:"close.survey.overlayClick",VISITOR_ID_UPDATED:"visitor.id.updated",DATA:{DISMISS_REASONS:{API:"api",CLOSED:"close.click",COMPLETE:"survey.completed",PAGE_CHANGE:"page.change",OVERRIDE:"override"},SURVEY_ID:"survey.id"}},exports.PerformanceMetrics=_,exports.SprigEvent=A,exports.breadcrumbsLogger=b,exports.checkUrlMatch=k,exports.checkUrlStillMatching=e=>{const{pageUrlEvents:t}=window.UserLeap._config,r=t==null?void 0:t.find(s=>s.id===e);return!!r&&k(r,window.location.href)},exports.cspViolationHandler=e=>{var t;(t=e==null?void 0:e.blockedURI)!=null&&t.includes(window.UserLeap._API_URL)&&(P=!0,console.warn(`[Sprig] ${e.blockedURI} is blocked by Content-Security-Policy`))},exports.delay=S,exports.disableThresholdChecking=()=>f=!0,exports.eventEmitter=q,exports.getHttpHeaders=function(e={}){const t={"Content-Type":"application/json","userleap-platform":"web","x-ul-sdk-version":"2.32.10","x-ul-installation-method":Q(e),"sprig-modules":G()};if(e.envId&&(t["x-ul-environment-id"]=e.envId),e.token&&(t.Authorization="Bearer "+e.token),e.userId&&(t["x-ul-user-id"]=e.userId),e.visitorId&&(t["x-ul-visitor-id"]=e.visitorId),e.partnerAnonymousId&&(t["x-ul-anonymous-id"]=e.partnerAnonymousId),e.mobileHeadersJSON){const r=JSON.parse(e.mobileHeadersJSON);Object.assign(t,r)}return e.locale&&(t["accept-language"]=e.locale),window.previewMode&&(t["x-ul-preview-mode"]="1"),t},exports.initPerformanceReporting=({reportingIntervalSeconds:e,postMetrics:t})=>{e?setInterval(()=>{(async r=>{const s=Object.values(_).map(i=>({name:i.name,values:i.collect()}));if(s.some(i=>i.values.length))try{await r(JSON.stringify(s))}catch(i){i instanceof Error&&b.error("MetricsErr",{error:{message:i.message,name:i.name}})}})(t)},1e3*e):V=!1},exports.killNetworkRequests=N,exports.localStorageHelper=$,exports.modules=E,exports.registerMetric=O,exports.registerReplay=e=>{E.replay=e},exports.registerThresholds=(e,t)=>{p={},f=!1,e==null||e.forEach(r=>{var s;r.metric in p||(p[r.metric]=[]),(s=p[r.metric])==null||s.push(r)}),L=t},exports.reportAndRegister=(e,t)=>{let r=_[e];return r||(r=O(e)),r.report(t)},exports.sessionStorageHelper=J,exports.shouldDirectEmbed=({"userleap-platform":e})=>{var t;return((t=window.UserLeap)==null?void 0:t.forceDirectEmbed)||e!=="web"},exports.sprigFetch=v,exports.v4=function(e,t,r){if(w.randomUUID&&!t&&!e)return w.randomUUID();const s=(e=e||{}).random||(e.rng||B)();return s[6]=15&s[6]|64,s[8]=63&s[8]|128,function(i,n=0){return o[i[n+0]]+o[i[n+1]]+o[i[n+2]]+o[i[n+3]]+"-"+o[i[n+4]]+o[i[n+5]]+"-"+o[i[n+6]]+o[i[n+7]]+"-"+o[i[n+8]]+o[i[n+9]]+"-"+o[i[n+10]]+o[i[n+11]]+o[i[n+12]]+o[i[n+13]]+o[i[n+14]]+o[i[n+15]]}(s)};
@@ -141,24 +141,25 @@ const ee = new O(), L = async (e) => {
141
141
  await new Promise((t) => {
142
142
  setTimeout(t, e);
143
143
  });
144
- }, te = ({ "userleap-platform": e }) => e !== "web";
144
+ }, te = ({ "userleap-platform": e }) => {
145
+ var t;
146
+ return ((t = window.UserLeap) == null ? void 0 : t.forceDirectEmbed) || e !== "web";
147
+ };
145
148
  class R {
146
149
  constructor(t) {
147
150
  l(this, "storage");
148
151
  l(this, "tempStorage", {});
149
152
  l(this, "isStorageAvailable");
150
- this.storage = window[t], this.isStorageAvailable = this.checkIfStorageAvailable();
151
- }
152
- checkIfStorageAvailable() {
153
153
  try {
154
- const t = "__storage_test__";
155
- return this.storage.setItem(t, t), this.storage.removeItem(t), !0;
154
+ this.storage = window[t];
155
+ const s = "__storage_test__";
156
+ this.storage.setItem(s, s), this.storage.removeItem(s), this.isStorageAvailable = !0;
156
157
  } catch {
157
- return !1;
158
+ this.isStorageAvailable = !1;
158
159
  }
159
160
  }
160
161
  setItem(t, s) {
161
- this.isStorageAvailable ? this.storage.setItem(t, s) : this.tempStorage[t] = s;
162
+ this.isStorageAvailable && this.storage ? this.storage.setItem(t, s) : this.tempStorage[t] = s;
162
163
  }
163
164
  setItemObject(t, s) {
164
165
  try {
@@ -168,7 +169,7 @@ class R {
168
169
  }
169
170
  }
170
171
  getItem(t) {
171
- return this.isStorageAvailable ? this.storage.getItem(t) : this.tempStorage[t];
172
+ return this.isStorageAvailable && this.storage ? this.storage.getItem(t) : this.tempStorage[t];
172
173
  }
173
174
  getItemObject(t) {
174
175
  const s = this.getItem(t);
@@ -181,10 +182,10 @@ class R {
181
182
  return {};
182
183
  }
183
184
  removeItem(t) {
184
- this.isStorageAvailable ? this.storage.removeItem(t) : delete this.tempStorage[t];
185
+ this.isStorageAvailable && this.storage ? this.storage.removeItem(t) : delete this.tempStorage[t];
185
186
  }
186
187
  clear() {
187
- this.isStorageAvailable ? this.storage.clear() : this.tempStorage = {};
188
+ this.isStorageAvailable && this.storage ? this.storage.clear() : this.tempStorage = {};
188
189
  }
189
190
  }
190
191
  const se = new R("sessionStorage"), re = new R("localStorage");
@@ -210,15 +211,15 @@ const k = { replay: null }, ne = (e) => {
210
211
  const e = [];
211
212
  return k.replay && e.push("replay"), e.join(",");
212
213
  }, q = 10;
213
- let A = !1, U = "", y = !1, D = !1, g = [];
214
+ let U = !1, A = "", y = !1, D = !1, g = [];
214
215
  const J = (e) => e._config && e._config.installationMethod ? e._config.installationMethod : e._gtm ? "web-gtm" : e._segment ? "web-segment" : "web-snippet", ie = (e) => {
215
216
  var t;
216
217
  (t = e == null ? void 0 : e.blockedURI) != null && t.includes(window.UserLeap._API_URL) && (D = !0, console.warn(`[Sprig] ${e.blockedURI} is blocked by Content-Security-Policy`));
217
218
  }, H = (e = "") => {
218
- A = !0, U = e;
219
+ U = !0, A = e;
219
220
  };
220
221
  function ae(e = {}) {
221
- const t = { "Content-Type": "application/json", "userleap-platform": "web", "x-ul-sdk-version": "2.32.7", "x-ul-installation-method": J(e), "sprig-modules": F() };
222
+ const t = { "Content-Type": "application/json", "userleap-platform": "web", "x-ul-sdk-version": "2.32.10", "x-ul-installation-method": J(e), "sprig-modules": F() };
222
223
  if (e.envId && (t["x-ul-environment-id"] = e.envId), e.token && (t.Authorization = "Bearer " + e.token), e.userId && (t["x-ul-user-id"] = e.userId), e.visitorId && (t["x-ul-visitor-id"] = e.visitorId), e.partnerAnonymousId && (t["x-ul-anonymous-id"] = e.partnerAnonymousId), e.mobileHeadersJSON) {
223
224
  const s = JSON.parse(e.mobileHeadersJSON);
224
225
  Object.assign(t, s);
@@ -237,8 +238,8 @@ const w = async ({ shouldDropOnRateLimit: e, ...t }) => {
237
238
  if (y && !n)
238
239
  return w(d);
239
240
  const u = { ok: !1, reportError: !1 };
240
- if (A)
241
- return console.info(`UserLeap - ${U}`), u;
241
+ if (U)
242
+ return console.info(`UserLeap - ${A}`), u;
242
243
  try {
243
244
  const c = await fetch(e, i);
244
245
  if (c.status === 429) {
package/dist/replay.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var Ee=Object.defineProperty;var ke=(e,t,r)=>t in e?Ee(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var _=(e,t,r)=>(ke(e,typeof t!="symbol"?t+"":t,r),r);const s=require("./metricsReporter-DNKMOwn_.cjs");var P=(e=>(e[e.DomContentLoaded=0]="DomContentLoaded",e[e.Load=1]="Load",e[e.FullSnapshot=2]="FullSnapshot",e[e.IncrementalSnapshot=3]="IncrementalSnapshot",e[e.Meta=4]="Meta",e[e.Custom=5]="Custom",e[e.Plugin=6]="Plugin",e))(P||{});const ne=new class{constructor(e){_(this,"awaitingResolvers",[]);_(this,"activeCount",0);this.capacity=e}async acquire(){if(!(this.activeCount<this.capacity))return new Promise(e=>{this.awaitingResolvers.push(e)});this.activeCount++}release(){const e=this.awaitingResolvers.shift();e&&this.activeCount<=this.capacity?e():this.activeCount--}async execute(e){try{return await this.acquire(),await e()}finally{this.release()}}setLimit(e){this.capacity=e}}(2),ae=async({apiUrl:e,surveyId:t,uploadId:r,etags:n,headers:a,responseGroupUuid:o,replayDuration:i,eventDigest:c},d=!1)=>{var w;if(!d&&!r&&!n)return void s.breadcrumbsLogger.error("UploadErr",{isMobile:d,uploadId:r,etags:n});s.breadcrumbsLogger.info("MarkUploadComplete",{surveyId:t});const u=await s.sprigFetch(`${e}/sdk/1/completeSessionReplay`,{method:"POST",body:JSON.stringify({etags:n,uploadId:r,responseGroupUuid:o,surveyId:t,replayDuration:i,eventDigest:c,userAgent:(w=window==null?void 0:window.navigator)==null?void 0:w.userAgent}),headers:a,shouldRetryRequest:!0});return s.breadcrumbsLogger.info("MarkUploadDone",{surveyId:t}),u},H=(e,t)=>t.some(r=>e instanceof r);let J,Q;const M=new WeakMap,A=new WeakMap,U=new WeakMap;let O={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return M.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return D(e[t])},set:(e,t,r)=>(e[t]=r,!0),has:(e,t)=>e instanceof IDBTransaction&&(t==="done"||t==="store")||t in e};function oe(e){O=e(O)}function Ce(e){return(Q||(Q=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(F(this),t),D(this.request)}:function(...t){return D(e.apply(F(this),t))}}function Pe(e){return typeof e=="function"?Ce(e):(e instanceof IDBTransaction&&function(t){if(M.has(t))return;const r=new Promise((n,a)=>{const o=()=>{a(t.error||new DOMException("AbortError","AbortError"))};t.oncomplete=()=>{n()},t.onerror=o,t.onabort=o});M.set(t,r)}(e),H(e,J||(J=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,O):e)}function D(e){if(e instanceof IDBRequest)return function(r){const n=new Promise((a,o)=>{r.onsuccess=()=>{a(D(r.result))},r.onerror=()=>{o(r.error)}});return U.set(n,r),n}(e);if(A.has(e))return A.get(e);const t=Pe(e);return t!==e&&(A.set(e,t),U.set(t,e)),t}const F=e=>U.get(e);function j(e,{blocked:t}={}){const r=indexedDB.deleteDatabase(e);return t&&(r.onblocked=n=>t(n.oldVersion,n)),D(r).then(()=>{})}const Re=["get","getKey","getAll","getAllKeys","count"],Be=["put","add","delete","clear"],N=new Map;function X(e,t){if(!(e instanceof IDBDatabase)||t in e||typeof t!="string")return;if(N.get(t))return N.get(t);const r=t.replace(/FromIndex$/,""),n=t!==r,a=Be.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!a&&!Re.includes(r))return;const o=async function(i,...c){const d=this.transaction(i,a?"readwrite":"readonly");let u=d.store;return n&&(u=u.index(c.shift())),(await Promise.all([u[r](...c),a&&d.done]))[0]};return N.set(t,o),o}oe(e=>({...e,get:(t,r,n)=>X(t,r)||e.get(t,r,n),has:(t,r)=>!!X(t,r)||e.has(t,r)}));const xe=["continue","continuePrimaryKey","advance"],Y={},V=new WeakMap,se=new WeakMap,Ue={get(e,t){if(!xe.includes(t))return e[t];let r=Y[t];return r||(r=Y[t]=function(...n){V.set(this,se.get(this)[t](...n))}),r}};async function*Le(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const r=new Proxy(t,Ue);for(se.set(r,t),U.set(r,F(t));t;)yield r,t=await(V.get(r)||t.continue()),V.delete(r)}function Z(e,t){return t===Symbol.asyncIterator&&H(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&H(e,[IDBIndex,IDBObjectStore])}oe(e=>({...e,get:(t,r,n)=>Z(t,r)?Le:e.get(t,r,n),has:(t,r)=>Z(t,r)||e.has(t,r)}));const Te=e=>{if(e instanceof Attr)return null;let t=1;for(let r=e.previousSibling;r;r=r.previousSibling)r.nodeName===e.nodeName&&++t;return t},ie=e=>{if(e===null)return"";const t=[];if(e instanceof Document)return"/";for(let r=e;r&&!(r instanceof Document)&&r!==null;r=r instanceof Attr?r.ownerElement:r.parentElement){const n=t[t.length]={name:void 0,position:null};switch(r.nodeType){case Node.TEXT_NODE:n.name="text()";break;case Node.ATTRIBUTE_NODE:n.name="@"+r.nodeName;break;case Node.PROCESSING_INSTRUCTION_NODE:n.name="processing-instruction()";break;case Node.COMMENT_NODE:n.name="comment()";break;case Node.ELEMENT_NODE:n.name=r.nodeName}n.position=Te(r)}return"/"+t.reverse().map(r=>r.position!==null?`/${r.name}[${r.position}]`:`/${r.name}`).join("")},I={capture:!0,passive:!0},_e=["a","button","input","option","li","link"],Ae=["Escape","Enter","Backspace","F5","Tab"];let L=!1;const Ne=["label","type","role","title","placeholder","errormessage","valuetext","href"],He="aria-",ee=e=>{var n;if(((n=e.tagName)==null?void 0:n.toLowerCase())==="html")return{element:"html"};const t=e.textContent,r=t?{text:t}:{};r.element=(a=>{if(!a.tagName)return"No tagName";const o=a.getAttribute("type");return o?`${o} ${a.tagName.toLowerCase()}`:a.tagName.toLowerCase()})(e);for(const a of e.attributes){let o=a.name;const i=a.value;o.startsWith(He)&&(o=o.substring(5)),Ne.includes(o)&&(r[o]=i)}return r},Me=e=>{var n;if(!e)return{};const t={...ee(e)},r=e.parentElement;if(r&&_e.includes((n=r.tagName)==null?void 0:n.toLowerCase())){const a=ee(r);Object.assign(t,a)}return t},de=(e,t)=>{var n;let r=t.target;t.target===((n=window.document)==null?void 0:n.body)&&window.Sprig.pointerDownTarget&&(r=window.Sprig.pointerDownTarget),Fe({x:t.x,y:t.y,type:e,elementAttributes:Me(r),windowHeight:window.innerHeight,windowWidth:window.innerWidth,...r instanceof HTMLElement?{rect:r==null?void 0:r.getBoundingClientRect(),xPath:ie(r)}:{}})},ce=e=>{Ae.includes(e.key)&&Ke({key:e.key})},ue=((e,t)=>{let r;return n=>{clearTimeout(r),r=window.setTimeout(()=>e(n),t)}})(e=>{if(!(e.target instanceof HTMLElement||e.target instanceof Document))return;let t=e.target;"scrollTop"in t||(t=t.documentElement),Ge({xPath:ie(t),x:t.scrollLeft,y:t.scrollTop,elementAttributes:{targetScrollWidth:t.scrollWidth,targetClientWidth:t.clientWidth,targetScrollHeight:t.scrollHeight,targetClientHeight:t.clientHeight}})},750),le=(te="left_click",e=>de(te,e));var te;const pe=e=>{e.button===2&&de("right_click",e)},ge=e=>{window.Sprig&&(window.Sprig.pointerDownTarget=e.target)},Oe=()=>{L||(window.addEventListener("click",le,I),window.addEventListener("pointerdown",ge,I),window.addEventListener("mousedown",pe,I),window.addEventListener("keydown",ce,I),window.addEventListener("scroll",ue,I),L=!0,window.performance.getEntriesByType("navigation").map(e=>e.type).includes("reload")&&je({url:window.location.href,currentPageTitle:document.title}),window.performance.getEntriesByType("navigation").map(e=>e.type).includes("back_forward")&&Ve({curUrl:window.location.href,fromUrl:document.referrer,currentPageTitle:document.title}))},p={isRecording:!1,scrollEventUuids:{},stopRecording:()=>{}},y=(()=>{const e=s.sessionStorageHelper.getItem("sprig.sessionId");if(e)return s.breadcrumbsLogger.info("SessionIDFound",{savedSessionId:e}),s.sessionStorageHelper.removeItem("sprig.sessionId"),e;const t=s.v4();return s.breadcrumbsLogger.info("GeneratedSessionID",{uuid:t}),t})(),K=()=>{s.sessionStorageHelper.setItem("sprig.disableReplayRecording","disabled")},v=()=>!!s.sessionStorageHelper.getItem("sprig.disableReplayRecording");window.addEventListener("beforeunload",()=>{s.breadcrumbsLogger.info("BeforeUnload",{sessionId:y}),s.sessionStorageHelper.setItem("sprig.sessionId",y)});const z=e=>e&&e.trim().substring(0,500).replace(/\s\s+/g," ").replace(/\r?\n|\r/g," ").substring(0,250),b=(e,t)=>{var r,n;if(!v()&&p.isRecording)try{(n=(r=window.rrwebRecord)==null?void 0:r.addCustomEvent)==null||n.call(r,e,t)}catch(a){T("Error recording custom event",a)}},Fe=e=>{var t;(t=e==null?void 0:e.elementAttributes)!=null&&t.text&&(e.elementAttributes.text=z(e.elementAttributes.text)),b("Sprig_Click",e)},je=e=>{b("Sprig_Refresh",e)},Ve=e=>{e.currentPageTitle&&(e.currentPageTitle=z(e.currentPageTitle)),b("Sprig_BackForward",e)},Ke=e=>{b("Sprig_Keystroke",e)},Ge=async e=>{const{x:t,xPath:r,y:n}=e,a=p.scrollEventUuids[r];if(a)return f(async()=>{var c,d,u,w;const o=await l.openDB(),i=await o.get("events",a);if(i!=null&&i.event){const g=JSON.parse(i.event),h=t>((d=(c=g.data)==null?void 0:c.payload)==null?void 0:d.x),m=n>((w=(u=g.data)==null?void 0:u.payload)==null?void 0:w.y);if(!h&&!m)return null;h&&(g.data.payload.x=t),m&&(g.data.payload.y=n),g.data.payload.elementAttributes=e.elementAttributes,i.event=JSON.stringify(g),await o.put("events",i)}else b("Sprig_Scroll",e)},"Error updating scroll event");b("Sprig_Scroll",e)},me=()=>{p.stopRecording&&(p.stopRecording(),p.stopRecording=void 0),p.isRecording=!1,["cleanupInterval","inactivityInterval","pendingCheckInterval"].forEach(e=>{p[e]&&(clearInterval(p[e]),p[e]=void 0)}),L&&(window.removeEventListener("click",le,I),window.removeEventListener("pointerdown",ge,I),window.removeEventListener("mousedown",pe,I),window.removeEventListener("keydown",ce,I),window.removeEventListener("scroll",ue,I),L=!1)},We=["did not allow mutations","called in an invalid security context"],$e=(e,t,{reportError:r=!0,extraInfo:n={}})=>{if(!v()&&t instanceof Error){if(K(),t.name==="VersionError")return s.breadcrumbsLogger.error("VersionErr",{message:e}),l.deleteDB();(a=>{if(!a)return!0;for(const o of We)if(a.toLowerCase().includes(o))return!1;return!0})(t==null?void 0:t.message)&&(r&&window.UserLeap.reportError(e,t,n),l.clearAll())}},T=(e,t,{reportError:r}={reportError:!0})=>{me(),s.breadcrumbsLogger.error("ReplayErr",{code:t.code,name:t.name}),$e(e,t,{reportError:r})},f=async(e,t)=>{try{await e()}catch(r){T(t,r)}};j("replayStorage").catch(console.error),j("sprig.replay").catch(console.error);const l=new class{openDB(){return function(e,t,{blocked:r,upgrade:n,blocking:a,terminated:o}={}){const i=indexedDB.open(e,t),c=D(i);return n&&(i.onupgradeneeded=d=>{n(D(i.result),d.oldVersion,d.newVersion,D(i.transaction),d)}),r&&(i.onblocked=d=>r(d.oldVersion,d.newVersion,d)),c.then(d=>{o&&(d.onclose=()=>o()),a&&(d.onversionchange=u=>a(u.oldVersion,u.newVersion,u))}).catch(()=>{}),c}("sprigReplay",1,{upgrade:(e,t,r)=>{if(r===0&&s.sessionStorageHelper.setItem("sprig.pendingCount","0"),!e.objectStoreNames.contains("events")){const n=e.createObjectStore("events",{keyPath:"uuid"});n.createIndex("sessionId","sessionId"),n.createIndex("timestamp","timestamp"),n.createIndex("[sessionId+timestamp]",["sessionId","timestamp"])}if(!e.objectStoreNames.contains("chunkUploads")){const n=e.createObjectStore("chunkUploads",{keyPath:"uuid"});n.createIndex("sessionId","sessionId"),n.createIndex("timestamp","timestamp"),n.createIndex("[sessionId+status]",["sessionId","status"]),n.createIndex("[uploadId+status]",["uploadId","status"]),n.createIndex("[sessionId+status+uploadId]",["sessionId","status","uploadId"])}if(!e.objectStoreNames.contains("pendingCaptures")){const n=e.createObjectStore("pendingCaptures",{keyPath:"uuid"});n.createIndex("sessionId","sessionId"),n.createIndex("timestamp","timestamp"),n.createIndex("[sessionId+targetTimestamp]",["sessionId","targetTimestamp"])}}})}deleteDB(){return j("sprigReplay").catch(console.error)}async bulkAdd(e,t){const r=(await this.openDB()).transaction(e,"readwrite");return Promise.all([...t.map(n=>r.store.add(n)),r.done])}async clearAll(){const e=(await this.openDB()).transaction(["events","chunkUploads","pendingCaptures"],"readwrite");return Promise.all([e.objectStore("events").clear(),e.objectStore("chunkUploads").clear(),e.objectStore("pendingCaptures").clear()])}async deleteBySessionId(e,t){const r=IDBKeyRange.only(t),n=(await this.openDB()).transaction(e,"readwrite"),a=n.store.index("sessionId");for await(const o of a.iterate(r))await o.delete();await n.done}async updatePartial(e,t,r){const n=(await this.openDB()).transaction(e,"readwrite"),a=await n.store.get(t);a&&await n.store.put({...a,...r}),await n.done}async deleteRowsBefore(e,t,r=()=>!0){const n=IDBKeyRange.upperBound(t,!0),a=(await this.openDB()).transaction(e,"readwrite"),o=a.store.index("timestamp");for await(const i of o.iterate(n))r(i.value)&&await i.delete();await a.done}async getEventsBetween(e,t=Date.now()){if(e>=t)return Promise.resolve([]);const r=IDBKeyRange.bound([y,e],[y,t],!1,!0);return(await this.openDB()).getAllFromIndex("events","[sessionId+timestamp]",r)}async updateEventsExpiredAt(e,t,r=30){const n=new Date,a=n.setMinutes(n.getMinutes()+(r??30)),o=(await this.openDB()).transaction("events","readwrite"),i=o.store.index("[sessionId+timestamp]"),c=IDBKeyRange.bound([y,e],[y,t],!1,!0);for await(const d of i.iterate(c))await d.update({...d.value,expiredAt:a});await o.done}async deleteChunkUploads(e,t){const r=IDBKeyRange.only([t,e]),n=(await this.openDB()).transaction("chunkUploads","readwrite");let o=await n.store.index("[uploadId+status]").openCursor(r);for(;o;)o.delete(),o=await o.continue();await n.done}async getChunkUploadsByStatus({sessionId:e,status:t,uploadId:r}){const n=(await this.openDB()).transaction("chunkUploads","readonly"),a=r?n.store.index("[uploadId+status]"):n.store.index("[sessionId+status]"),o=r?IDBKeyRange.only([r,t]):IDBKeyRange.only([e,t]);return a.getAll(o)}async getPendingCaptures(e={}){return(await(await this.openDB()).getAllFromIndex("pendingCaptures","sessionId",y)).filter(r=>!e.beforePresent||r.targetTimestamp<Date.now()).filter(r=>!e.isBeforeType||r.captureParams.replayParams.replayDurationType==="before").filter(r=>!e.isHeatmap||(r.captureParams.isHeatmap??!1))}async markPendingCaptureToCanUpload(e){const t=(await this.openDB()).transaction("pendingCaptures","readwrite"),r=t.store.index("sessionId");for await(const n of r.iterate(y)){const a=n.value;a.captureParams.responseGroupId===e&&await n.update({...a,canUpload:!0})}await t.done}async markPendingHeatmapsReady(e){if(parseInt(s.sessionStorageHelper.getItem("sprig.pendingCount")??"0")===0)return null;const t=Date.now(),r=(await this.openDB()).transaction("pendingCaptures","readwrite"),n=r.store.index("sessionId");for await(const a of n.iterate(y)){const o=a.value;!o.captureParams.isHeatmap||e&&!e.includes(o.uuid)||await a.update({...o,targetTimestamp:t,captureParams:{...o.captureParams,triggerTimestamp:t,replayParams:{...o.captureParams.replayParams,replayDurationSeconds:Math.floor((t-o.timestamp)/1e3)}}})}await r.done}},we=async(e,t)=>{const r=performance.now();let n;try{n=await e()}finally{const a=performance.now()-r;let o=s.PerformanceMetrics[t];o||(o=s.registerMetric(t)),o.report(a/1e3)}return n},ye=(e,t)=>{const r=performance.now();try{e()}finally{const n=performance.now()-r;let a=s.PerformanceMetrics[t];a||(a=s.registerMetric(t)),a.report(n/1e3)}};let fe=5e3,G=6e4,W=0,E,$=!1,q=[];const qe=e=>{var t,r,n,a;if((t=e.event)!=null&&t.includes("Sprig_Scroll")){const o=(a=(n=(r=JSON.parse(e.event))==null?void 0:r.data)==null?void 0:n.payload)==null?void 0:a.xPath;if(!o)return;p.scrollEventUuids[o]=e.uuid}q.push(e),$||ze()},ze=()=>{$=!0,setTimeout(async()=>{if(v())return;const e=q;q=[],$=!1,ye(async()=>{await(async t=>{const r=t.map(n=>({...n,sessionId:n.sessionId??y}));if(r.length!==0)return f(()=>l.bulkAdd("events",r),"Error storing replay events")})(e)},"sdk_replay_add_event_batch_seconds")},500)},Je=(e,t,r)=>{p.cleanupInterval=window.setInterval(()=>{const n=Date.now();we(()=>f(async()=>{v()||await Promise.all([l.deleteRowsBefore("events",n-1e3*e,a=>a.expiredAt===void 0||a.expiredAt<n-1e3*e),l.deleteRowsBefore("chunkUploads",n-1e3*t),l.deleteRowsBefore("pendingCaptures",n-1e3*r,a=>!a.canUpload)])},"Error deleting table rows"),"sdk_replay_cleanup_seconds"),s.breadcrumbsLogger.debug("CleanupComplete")},3e4)},Qe=()=>{p.pendingCheckInterval=window.setInterval(async()=>{f(async()=>{await he()},"Error initiating pending captures")},5e3)},he=async(e=!1)=>{const t=parseInt(E??"0");if(t===0)return;const r=await l.getPendingCaptures({beforePresent:!0,isBeforeType:e}),n=await l.openDB();await Promise.all(r.map(async a=>(await n.delete("pendingCaptures",a.uuid),ve(a.captureParams,a.canUpload)))),E=(t-r.length).toString(),s.sessionStorageHelper.setItem("sprig.pendingCount",E)},Xe=async(e,t,r,n,a)=>{const o=Math.min(e+a,r),i=await we(()=>l.getEventsBetween(e,o),"sdk_replay_get_events_between_seconds");if(!(i!=null&&i.length))return s.breadcrumbsLogger.debug("NoEventsFound"),{validStartFound:n,events:[]};if(!n){s.breadcrumbsLogger.debug("ValidStartSearch");let c=-1;return i==null||i.forEach((d,u)=>{if(!d.isValidStart)return;const w=d.timestamp<=t;(c<0||w)&&(c=u)}),c<0?(s.breadcrumbsLogger.debug("ValidStartNotFound"),{validStartFound:n,events:[]}):{validStartFound:!0,events:i==null?void 0:i.slice(c)}}return{validStartFound:n,events:i}},Ie=e=>Promise.all(e.map(async t=>{const r=await(async n=>ne.execute(async()=>{var i;s.breadcrumbsLogger.info("UploadChunkStart",{chunkIndex:n.chunkIndex,surveyId:n.surveyId});const a=await s.sprigFetch(n.uploadUrl,{body:n.data,method:"PUT"});s.breadcrumbsLogger.http("UploadChunkEnd",{url:n.uploadUrl,method:"PUT",status_code:a.status,reason:a.statusText??"OK",chunkIndex:n.chunkIndex,surveyId:n.surveyId});const o=(i=a.headers)==null?void 0:i.get("ETag");if(!o)throw new Error(`Upload response did not include etag for upload ${n.uploadId}, part ${n.chunkIndex}`);return o}))(t);return await l.updatePartial("chunkUploads",t.uuid,{data:null,etag:r,status:"UploadComplete"}),t.uploadId})),be=async e=>{const t=await l.getChunkUploadsByStatus({status:"UploadComplete",uploadId:e});if(!(t!=null&&t.length))return void s.breadcrumbsLogger.info("NoChunksForUpload",{uploadId:e});const r=t.reduce((o,i)=>(o.find(c=>c.chunkIndex===i.chunkIndex)||o.push(i),o),[]);r.sort((o,i)=>o.chunkIndex-i.chunkIndex);const n=r.map(o=>({ETag:o.etag,PartNumber:o.chunkIndex})).filter(o=>o.ETag!==null),a=r[0];await ae({apiUrl:a.apiUrl,surveyId:a.surveyId,uploadId:e,responseGroupUuid:a.responseGroupId,etags:n,headers:a.completeUploadHeaders,replayDuration:a.replayDuration}),await l.deleteChunkUploads("UploadComplete",e)},Ye=()=>{f(async()=>{const e=await l.getChunkUploadsByStatus({sessionId:y,status:"ReadyForUpload"});if(!(e!=null&&e.length))return;const t=await Ie(e);t!=null&&t.length&&await Promise.all(t.map(r=>{if(r)return be(r)}))},"Error uploading unfinished chunks")},Ze=async(e,t)=>{const r=t??Date.now();return(async(n,a)=>{const o=new TextEncoder;let i=null;const c=new CompressionStream("gzip"),d=c.writable.getWriter();let u=!1,w=!1,[g,h]=[0,0],m=[];for(let k=n-35e3;k<a;k+=G){if({validStartFound:w,events:m}=await Xe(k,n,a,w,G),!(m!=null&&m.length)){s.breadcrumbsLogger.debug("NoEventsFound");continue}g===0&&(g=m[0].timestamp),h=m[m.length-1].timestamp;const R=m.map(C=>C.event);R.push(`{"timestamp":${a}}`);const B=`${u?",":"["}${R}`,x=o.encode(B);ye(()=>{d.write(x)},"sdk_replay_compression_seconds"),u=!0}if(h-g<fe)return s.breadcrumbsLogger.debug("ReplayTooShort"),null;const S=o.encode("]");return d.write(S),d.close(),i=new Uint8Array(await new Response(c.readable).arrayBuffer()),i})(r-e,r)},re=async e=>{const{surveyId:t,responseGroupId:r,visitorId:n,apiUrl:a,completeUploadHeaders:o,replayParams:i,triggerTimestamp:c}=e,d=await Ze(1e3*i.replayDurationSeconds,c);if(!(d!=null&&d.length))return void s.breadcrumbsLogger.info("FileDataEmpty",{surveyId:t});const u=((g,h,m)=>{const S=g.length,k=1024*h*1024,R=Math.ceil(S/m),B=Math.max(k,R),x=[];let C=0;for(;C<S;)x.push(g.slice(C,C+B)),C+=B;return x})(d,i.minimumChunkSizeMb,i.signedUrls.length),w=await Promise.all(u.map(async(g,h)=>{const m=s.v4(),S={apiUrl:a,chunkIndex:h+1,completeUploadHeaders:o,etag:null,responseGroupId:r,status:"ReadyForUpload",surveyId:t,timestamp:c,totalChunks:u.length,data:g,uploadId:i.uploadId,uploadUrl:i.signedUrls[h].url,uuid:m,visitorId:n};return await(await l.openDB()).add("chunkUploads",{...S,sessionId:S.sessionId??y}),S}));await(async(g,h)=>{await Ie(h),await Promise.all(g.map(m=>be(m)))})([i.uploadId],w)},ve=async(e,t)=>{if(v())return s.breadcrumbsLogger.debug("ReplayDisabled-ScheduleOrCapture");const{isHeatmap:r,isStandalone:n,replayParams:a,triggerTimestamp:o,responseGroupId:i}=e,c=async()=>{setTimeout(()=>s.eventEmitter.removeListener(s.SprigEvent.QuestionAnswered,c),0),f(async()=>{a.replayDurationType==="before"?await re(e):await l.markPendingCaptureToCanUpload(i)},"Error in schedule/capture callback")};f(async()=>{if(a.replayDurationType==="after"||a.replayDurationType==="beforeAndAfter")return!n&&!r&&s.eventEmitter.on(s.SprigEvent.QuestionAnswered,c),void await De(e);if(n||r||t)await re(e),r&&et();else{const d=35+a.replayDurationSeconds,u=o-1e3*d,w=o;await l.updateEventsExpiredAt(u,w,a.expirationTimeLimitMinutes),s.eventEmitter.on(s.SprigEvent.QuestionAnswered,c)}},"Error in scheduling/capturing replay")},et=async()=>{parseInt(E??"0")||s.sessionStorageHelper.removeItem("sprig.isCapturingHeatmap"),s.sessionStorageHelper.getItem("sprig.teardownAfterCapture")&&(me(),Se(),s.sessionStorageHelper.removeItem("sprig.teardownAfterCapture"))},Se=async()=>v()?s.breadcrumbsLogger.debug("ReplayDisabled-ClearData"):Promise.all([l.deleteBySessionId("events",y),l.deleteBySessionId("pendingCaptures",y)]).catch(e=>{T("Error clearing user replay data",e)}),De=async e=>{if(v())return;const{isHeatmap:t,surveyId:r}=e,n=await l.getPendingCaptures(),a=n==null?void 0:n.filter(d=>d.captureParams.surveyId===r);if(a!=null&&a.length)return void s.breadcrumbsLogger.info("PendingCaptureExists",{surveyId:r});t&&(p.isRecording&&f(()=>{var d,u;return(u=(d=window.rrwebRecord)==null?void 0:d.takeFullSnapshot)==null?void 0:u.call(d,!0)},"Error recording full snapshot"),s.sessionStorageHelper.setItem("sprig.isCapturingHeatmap","true"),W=Date.now(),p.inactivityInterval||(p.inactivityInterval=window.setInterval(()=>{var d;d=W,Date.now()-d>=3e4&&f(()=>l.markPendingHeatmapsReady(),"Error in heatmap inactivity")},1e3)));const o={...e,replayParams:{...e.replayParams}};e.replayParams.replayDurationType==="beforeAndAfter"&&(o.replayParams.replayDurationSeconds*=2),o.replayParams.replayDurationType="before";const i=e.triggerTimestamp+1e3*e.replayParams.replayDurationSeconds;o.triggerTimestamp=i,E=(parseInt(E??"0")+1).toString(),s.sessionStorageHelper.setItem("sprig.pendingCount",E),await(await l.openDB()).add("pendingCaptures",{canUpload:!1,captureParams:o,sessionId:y,targetTimestamp:i,timestamp:Date.now(),uuid:s.v4()})},tt=Object.freeze(Object.defineProperty({__proto__:null,RecordEvent:e=>{b("Sprig_TrackEvent",e)},RecordPageView:e=>{e.description&&(e.description=z(e.description)),b("Sprig_PageView",e)},RecordSurveyShown:e=>{b("Sprig_ShowSurvey",e)},_completeSessionReplay:async({surveyId:e,responseGroupUuid:t,eventDigest:r,headers:n})=>{if(!e||!t)return!1;const a=window.UserLeap._API_URL,o=await ae({surveyId:e,responseGroupUuid:t,eventDigest:r,apiUrl:a,headers:n},!0);return!(o!=null&&o.error)},checkPendingHeatmapsUrl:()=>v()?s.breadcrumbsLogger.debug("ReplayDisabled-PendingHeatmaps"):f(async()=>{const e=(await l.getPendingCaptures({isHeatmap:!0})).map(t=>({eventId:t.captureParams.eventId,uuid:t.uuid})).filter(({eventId:t})=>!s.checkUrlStillMatching(t)).map(({uuid:t})=>t);s.breadcrumbsLogger.info("PendingHeatmapsToComplete",{count:e.length}),e.length&&(await l.markPendingHeatmapsReady(e),s.breadcrumbsLogger.info("MarkedPendingHeatmapsReady"))},"Error marking pending heatmaps ready"),clearUserReplayData:Se,disableRecording:T,initializeReplay:async({maxReplayDurationSeconds:e,maxInflightRequests:t=2,replaySettings:r,teardownAfter:n=!1})=>{if(E=s.sessionStorageHelper.getItem("sprig.pendingCount"),!p.isRecording){if(n&&s.sessionStorageHelper.setItem("sprig.teardownAfterCapture","true"),v())return s.breadcrumbsLogger.debug("ReplayDisabled");if(await(async()=>{var a;if(!window.indexedDB||!window.IDBKeyRange||!window.CompressionStream)return!0;if((a=window.navigator.storage)!=null&&a.estimate)try{const{quota:o=0,usage:i=0}=await window.navigator.storage.estimate(),c=(o-i)/1024**3;return s.breadcrumbsLogger.info("Storage",{availableGb:c}),c<.5}catch{return!0}return!1})())return s.breadcrumbsLogger.debug("IDBNotSupported"),K();try{const a=await l.openDB();s.breadcrumbsLogger.info("DBVersion",{version:a.version})}catch(a){return s.breadcrumbsLogger.error("ReplayOpenErr",{name:a.name}),a.name==="VersionError"&&l.deleteDB(),K()}if(f(async()=>{await he(!0)},"Error uploading ready pending captures"),!e)return s.breadcrumbsLogger.debug("MissingDuration");s.breadcrumbsLogger.debug("ReplayInit"),await f(async()=>{var a;if(r!=null&&r.minDuration&&(fe=r.minDuration),r!=null&&r.batchDuration&&(G=r.batchDuration),a=t,ne.setLimit(a),Ye(),Je(e+35,1800,e+35),Qe(),!window.rrwebRecord){const{record:d}=await import(window.UserLeap.replayLibraryURL??"https://cdn.sprig.com/dependencies/record-2.0.0-alpha.17.min.js");window.rrwebRecord=d}const o=window.rrwebRecord;if(!o)return s.breadcrumbsLogger.error("RecordScriptFailed");let i=!0,c=0;p.stopRecording=o({checkoutEveryNms:3e4,sampling:{input:"last",scroll:250,media:800},emit:(d,u)=>{if(d.type===P.Custom&&(W=Date.now()),v())return;if(u&&d.type===P.Meta)c=performance.now();else if(u&&c&&d.type===P.FullSnapshot){const g=performance.now()-c;s.reportAndRegister("sdk_replay_snapshot_seconds",g/1e3)}const w=i||!!u&&d.type===P.Meta;i=!1,qe({uuid:s.v4(),event:JSON.stringify(d),isValidStart:w,timestamp:Date.now()})},...r}),p.isRecording=!!p.stopRecording,p.isRecording&&(s.eventEmitter.on("survey.complete",d=>{var u;u={id:d,userAgent:window.navigator.userAgent},b("Sprig_SubmitSurvey",u)}),Oe())},"Error initializing replay")}},isReplayRecording:()=>p.isRecording,scheduleCapture:De,scheduleOrCaptureReplay:ve,tryReplayAction:f},Symbol.toStringTag,{value:"Module"}));s.registerReplay(tt);
1
+ "use strict";var ke=Object.defineProperty;var Ce=(e,t,r)=>t in e?ke(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var _=(e,t,r)=>(Ce(e,typeof t!="symbol"?t+"":t,r),r);const s=require("./metricsReporter-eI04W7R0.cjs");var P=(e=>(e[e.DomContentLoaded=0]="DomContentLoaded",e[e.Load=1]="Load",e[e.FullSnapshot=2]="FullSnapshot",e[e.IncrementalSnapshot=3]="IncrementalSnapshot",e[e.Meta=4]="Meta",e[e.Custom=5]="Custom",e[e.Plugin=6]="Plugin",e))(P||{});const ne=new class{constructor(e){_(this,"awaitingResolvers",[]);_(this,"activeCount",0);this.capacity=e}async acquire(){if(!(this.activeCount<this.capacity))return new Promise(e=>{this.awaitingResolvers.push(e)});this.activeCount++}release(){const e=this.awaitingResolvers.shift();e&&this.activeCount<=this.capacity?e():this.activeCount--}async execute(e){try{return await this.acquire(),await e()}finally{this.release()}}setLimit(e){this.capacity=e}}(2),ae=async({apiUrl:e,surveyId:t,uploadId:r,etags:n,headers:a,responseGroupUuid:o,replayDuration:i,eventDigest:c},d=!1)=>{var w;if(!d&&!r&&!n)return void s.breadcrumbsLogger.error("UploadErr",{isMobile:d,uploadId:r,etags:n});s.breadcrumbsLogger.info("MarkUploadComplete",{surveyId:t});const u=await s.sprigFetch(`${e}/sdk/1/completeSessionReplay`,{method:"POST",body:JSON.stringify({etags:n,uploadId:r,responseGroupUuid:o,surveyId:t,replayDuration:i,eventDigest:c,userAgent:(w=window==null?void 0:window.navigator)==null?void 0:w.userAgent}),headers:a,shouldRetryRequest:!0});return s.breadcrumbsLogger.info("MarkUploadDone",{surveyId:t}),u},H=(e,t)=>t.some(r=>e instanceof r);let J,Q;const M=new WeakMap,A=new WeakMap,U=new WeakMap;let O={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return M.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return D(e[t])},set:(e,t,r)=>(e[t]=r,!0),has:(e,t)=>e instanceof IDBTransaction&&(t==="done"||t==="store")||t in e};function oe(e){O=e(O)}function Pe(e){return(Q||(Q=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(F(this),t),D(this.request)}:function(...t){return D(e.apply(F(this),t))}}function Re(e){return typeof e=="function"?Pe(e):(e instanceof IDBTransaction&&function(t){if(M.has(t))return;const r=new Promise((n,a)=>{const o=()=>{a(t.error||new DOMException("AbortError","AbortError"))};t.oncomplete=()=>{n()},t.onerror=o,t.onabort=o});M.set(t,r)}(e),H(e,J||(J=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,O):e)}function D(e){if(e instanceof IDBRequest)return function(r){const n=new Promise((a,o)=>{r.onsuccess=()=>{a(D(r.result))},r.onerror=()=>{o(r.error)}});return U.set(n,r),n}(e);if(A.has(e))return A.get(e);const t=Re(e);return t!==e&&(A.set(e,t),U.set(t,e)),t}const F=e=>U.get(e);function j(e,{blocked:t}={}){const r=indexedDB.deleteDatabase(e);return t&&(r.onblocked=n=>t(n.oldVersion,n)),D(r).then(()=>{})}const Be=["get","getKey","getAll","getAllKeys","count"],xe=["put","add","delete","clear"],N=new Map;function X(e,t){if(!(e instanceof IDBDatabase)||t in e||typeof t!="string")return;if(N.get(t))return N.get(t);const r=t.replace(/FromIndex$/,""),n=t!==r,a=xe.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!a&&!Be.includes(r))return;const o=async function(i,...c){const d=this.transaction(i,a?"readwrite":"readonly");let u=d.store;return n&&(u=u.index(c.shift())),(await Promise.all([u[r](...c),a&&d.done]))[0]};return N.set(t,o),o}oe(e=>({...e,get:(t,r,n)=>X(t,r)||e.get(t,r,n),has:(t,r)=>!!X(t,r)||e.has(t,r)}));const Ue=["continue","continuePrimaryKey","advance"],Y={},V=new WeakMap,se=new WeakMap,Le={get(e,t){if(!Ue.includes(t))return e[t];let r=Y[t];return r||(r=Y[t]=function(...n){V.set(this,se.get(this)[t](...n))}),r}};async function*Te(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const r=new Proxy(t,Le);for(se.set(r,t),U.set(r,F(t));t;)yield r,t=await(V.get(r)||t.continue()),V.delete(r)}function Z(e,t){return t===Symbol.asyncIterator&&H(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&H(e,[IDBIndex,IDBObjectStore])}oe(e=>({...e,get:(t,r,n)=>Z(t,r)?Te:e.get(t,r,n),has:(t,r)=>Z(t,r)||e.has(t,r)}));const _e=e=>{if(e instanceof Attr)return null;let t=1;for(let r=e.previousSibling;r;r=r.previousSibling)r.nodeName===e.nodeName&&++t;return t},ie=e=>{if(e===null)return"";const t=[];if(e instanceof Document)return"/";for(let r=e;r&&!(r instanceof Document)&&r!==null;r=r instanceof Attr?r.ownerElement:r.parentElement){const n=t[t.length]={name:void 0,position:null};switch(r.nodeType){case Node.TEXT_NODE:n.name="text()";break;case Node.ATTRIBUTE_NODE:n.name="@"+r.nodeName;break;case Node.PROCESSING_INSTRUCTION_NODE:n.name="processing-instruction()";break;case Node.COMMENT_NODE:n.name="comment()";break;case Node.ELEMENT_NODE:n.name=r.nodeName}n.position=_e(r)}return"/"+t.reverse().map(r=>r.position!==null?`/${r.name}[${r.position}]`:`/${r.name}`).join("")},I={capture:!0,passive:!0},Ae=["a","button","input","option","li","link"],Ne=["Escape","Enter","Backspace","F5","Tab"];let L=!1;const He=["label","type","role","title","placeholder","errormessage","valuetext","href"],Me="aria-",ee=e=>{var n;if(((n=e.tagName)==null?void 0:n.toLowerCase())==="html")return{element:"html"};const t=e.textContent,r=t?{text:t}:{};r.element=(a=>{if(!a.tagName)return"No tagName";const o=a.getAttribute("type");return o?`${o} ${a.tagName.toLowerCase()}`:a.tagName.toLowerCase()})(e);for(const a of e.attributes){let o=a.name;const i=a.value;o.startsWith(Me)&&(o=o.substring(5)),He.includes(o)&&(r[o]=i)}return r},Oe=e=>{var n;if(!e)return{};const t={...ee(e)},r=e.parentElement;if(r&&Ae.includes((n=r.tagName)==null?void 0:n.toLowerCase())){const a=ee(r);Object.assign(t,a)}return t},de=(e,t)=>{var n;let r=t.target;t.target===((n=window.document)==null?void 0:n.body)&&window.Sprig.pointerDownTarget&&(r=window.Sprig.pointerDownTarget),je({x:t.x,y:t.y,type:e,elementAttributes:Oe(r),windowHeight:window.innerHeight,windowWidth:window.innerWidth,...r instanceof HTMLElement?{rect:r==null?void 0:r.getBoundingClientRect(),xPath:ie(r)}:{}})},ce=e=>{Ne.includes(e.key)&&Ge({key:e.key})},ue=((e,t)=>{let r;return n=>{clearTimeout(r),r=window.setTimeout(()=>e(n),t)}})(e=>{if(!(e.target instanceof HTMLElement||e.target instanceof Document))return;let t=e.target;"scrollTop"in t||(t=t.documentElement),We({xPath:ie(t),x:t.scrollLeft,y:t.scrollTop,elementAttributes:{targetScrollWidth:t.scrollWidth,targetClientWidth:t.clientWidth,targetScrollHeight:t.scrollHeight,targetClientHeight:t.clientHeight}})},750),le=(te="left_click",e=>de(te,e));var te;const pe=e=>{e.button===2&&de("right_click",e)},ge=e=>{window.Sprig&&(window.Sprig.pointerDownTarget=e.target)},Fe=()=>{L||(window.addEventListener("click",le,I),window.addEventListener("pointerdown",ge,I),window.addEventListener("mousedown",pe,I),window.addEventListener("keydown",ce,I),window.addEventListener("scroll",ue,I),L=!0,window.performance.getEntriesByType("navigation").map(e=>e.type).includes("reload")&&Ve({url:window.location.href,currentPageTitle:document.title}),window.performance.getEntriesByType("navigation").map(e=>e.type).includes("back_forward")&&Ke({curUrl:window.location.href,fromUrl:document.referrer,currentPageTitle:document.title}))},p={isRecording:!1,scrollEventUuids:{},stopRecording:()=>{}},me=()=>window.indexedDB&&window.IDBKeyRange&&window.CompressionStream,y=(()=>{const e=s.sessionStorageHelper.getItem("sprig.sessionId");if(e)return s.breadcrumbsLogger.info("SessionIDFound",{savedSessionId:e}),s.sessionStorageHelper.removeItem("sprig.sessionId"),e;const t=s.v4();return s.breadcrumbsLogger.info("GeneratedSessionID",{uuid:t}),t})(),K=()=>{s.sessionStorageHelper.setItem("sprig.disableReplayRecording","disabled")},v=()=>!!s.sessionStorageHelper.getItem("sprig.disableReplayRecording");window.addEventListener("beforeunload",()=>{s.breadcrumbsLogger.info("BeforeUnload",{sessionId:y}),s.sessionStorageHelper.setItem("sprig.sessionId",y)});const z=e=>e&&e.trim().substring(0,500).replace(/\s\s+/g," ").replace(/\r?\n|\r/g," ").substring(0,250),b=(e,t)=>{var r,n;if(!v()&&p.isRecording)try{(n=(r=window.rrwebRecord)==null?void 0:r.addCustomEvent)==null||n.call(r,e,t)}catch(a){T("Error recording custom event",a)}},je=e=>{var t;(t=e==null?void 0:e.elementAttributes)!=null&&t.text&&(e.elementAttributes.text=z(e.elementAttributes.text)),b("Sprig_Click",e)},Ve=e=>{b("Sprig_Refresh",e)},Ke=e=>{e.currentPageTitle&&(e.currentPageTitle=z(e.currentPageTitle)),b("Sprig_BackForward",e)},Ge=e=>{b("Sprig_Keystroke",e)},We=async e=>{const{x:t,xPath:r,y:n}=e,a=p.scrollEventUuids[r];if(a)return f(async()=>{var c,d,u,w;const o=await l.openDB(),i=await o.get("events",a);if(i!=null&&i.event){const g=JSON.parse(i.event),h=t>((d=(c=g.data)==null?void 0:c.payload)==null?void 0:d.x),m=n>((w=(u=g.data)==null?void 0:u.payload)==null?void 0:w.y);if(!h&&!m)return null;h&&(g.data.payload.x=t),m&&(g.data.payload.y=n),g.data.payload.elementAttributes=e.elementAttributes,i.event=JSON.stringify(g),await o.put("events",i)}else b("Sprig_Scroll",e)},"Error updating scroll event");b("Sprig_Scroll",e)},we=()=>{p.stopRecording&&(p.stopRecording(),p.stopRecording=void 0),p.isRecording=!1,["cleanupInterval","inactivityInterval","pendingCheckInterval"].forEach(e=>{p[e]&&(clearInterval(p[e]),p[e]=void 0)}),L&&(window.removeEventListener("click",le,I),window.removeEventListener("pointerdown",ge,I),window.removeEventListener("mousedown",pe,I),window.removeEventListener("keydown",ce,I),window.removeEventListener("scroll",ue,I),L=!1)},$e=["did not allow mutations","called in an invalid security context"],qe=(e,t,{reportError:r=!0,extraInfo:n={}})=>{if(!v()&&t instanceof Error){if(K(),t.name==="VersionError")return s.breadcrumbsLogger.error("VersionErr",{message:e}),l.deleteDB();(a=>{if(!a)return!0;for(const o of $e)if(a.toLowerCase().includes(o))return!1;return!0})(t==null?void 0:t.message)&&(r&&window.UserLeap.reportError(e,t,n),l.clearAll())}},T=(e,t,{reportError:r}={reportError:!0})=>{we(),s.breadcrumbsLogger.error("ReplayErr",{code:t.code,name:t.name}),qe(e,t,{reportError:r})},f=async(e,t)=>{try{await e()}catch(r){T(t,r)}};me()&&(j("replayStorage").catch(console.error),j("sprig.replay").catch(console.error));const l=new class{openDB(){return function(e,t,{blocked:r,upgrade:n,blocking:a,terminated:o}={}){const i=indexedDB.open(e,t),c=D(i);return n&&(i.onupgradeneeded=d=>{n(D(i.result),d.oldVersion,d.newVersion,D(i.transaction),d)}),r&&(i.onblocked=d=>r(d.oldVersion,d.newVersion,d)),c.then(d=>{o&&(d.onclose=()=>o()),a&&(d.onversionchange=u=>a(u.oldVersion,u.newVersion,u))}).catch(()=>{}),c}("sprigReplay",1,{upgrade:(e,t,r)=>{if(r===0&&s.sessionStorageHelper.setItem("sprig.pendingCount","0"),!e.objectStoreNames.contains("events")){const n=e.createObjectStore("events",{keyPath:"uuid"});n.createIndex("sessionId","sessionId"),n.createIndex("timestamp","timestamp"),n.createIndex("[sessionId+timestamp]",["sessionId","timestamp"])}if(!e.objectStoreNames.contains("chunkUploads")){const n=e.createObjectStore("chunkUploads",{keyPath:"uuid"});n.createIndex("sessionId","sessionId"),n.createIndex("timestamp","timestamp"),n.createIndex("[sessionId+status]",["sessionId","status"]),n.createIndex("[uploadId+status]",["uploadId","status"]),n.createIndex("[sessionId+status+uploadId]",["sessionId","status","uploadId"])}if(!e.objectStoreNames.contains("pendingCaptures")){const n=e.createObjectStore("pendingCaptures",{keyPath:"uuid"});n.createIndex("sessionId","sessionId"),n.createIndex("timestamp","timestamp"),n.createIndex("[sessionId+targetTimestamp]",["sessionId","targetTimestamp"])}}})}deleteDB(){return j("sprigReplay").catch(console.error)}async bulkAdd(e,t){const r=(await this.openDB()).transaction(e,"readwrite");return Promise.all([...t.map(n=>r.store.add(n)),r.done])}async clearAll(){const e=(await this.openDB()).transaction(["events","chunkUploads","pendingCaptures"],"readwrite");return Promise.all([e.objectStore("events").clear(),e.objectStore("chunkUploads").clear(),e.objectStore("pendingCaptures").clear()])}async deleteBySessionId(e,t){const r=IDBKeyRange.only(t),n=(await this.openDB()).transaction(e,"readwrite"),a=n.store.index("sessionId");for await(const o of a.iterate(r))await o.delete();await n.done}async updatePartial(e,t,r){const n=(await this.openDB()).transaction(e,"readwrite"),a=await n.store.get(t);a&&await n.store.put({...a,...r}),await n.done}async deleteRowsBefore(e,t,r=()=>!0){const n=IDBKeyRange.upperBound(t,!0),a=(await this.openDB()).transaction(e,"readwrite"),o=a.store.index("timestamp");for await(const i of o.iterate(n))r(i.value)&&await i.delete();await a.done}async getEventsBetween(e,t=Date.now()){if(e>=t)return Promise.resolve([]);const r=IDBKeyRange.bound([y,e],[y,t],!1,!0);return(await this.openDB()).getAllFromIndex("events","[sessionId+timestamp]",r)}async updateEventsExpiredAt(e,t,r=30){const n=new Date,a=n.setMinutes(n.getMinutes()+(r??30)),o=(await this.openDB()).transaction("events","readwrite"),i=o.store.index("[sessionId+timestamp]"),c=IDBKeyRange.bound([y,e],[y,t],!1,!0);for await(const d of i.iterate(c))await d.update({...d.value,expiredAt:a});await o.done}async deleteChunkUploads(e,t){const r=IDBKeyRange.only([t,e]),n=(await this.openDB()).transaction("chunkUploads","readwrite");let o=await n.store.index("[uploadId+status]").openCursor(r);for(;o;)o.delete(),o=await o.continue();await n.done}async getChunkUploadsByStatus({sessionId:e,status:t,uploadId:r}){const n=(await this.openDB()).transaction("chunkUploads","readonly"),a=r?n.store.index("[uploadId+status]"):n.store.index("[sessionId+status]"),o=r?IDBKeyRange.only([r,t]):IDBKeyRange.only([e,t]);return a.getAll(o)}async getPendingCaptures(e={}){return(await(await this.openDB()).getAllFromIndex("pendingCaptures","sessionId",y)).filter(r=>!e.beforePresent||r.targetTimestamp<Date.now()).filter(r=>!e.isBeforeType||r.captureParams.replayParams.replayDurationType==="before").filter(r=>!e.isHeatmap||(r.captureParams.isHeatmap??!1))}async markPendingCaptureToCanUpload(e){const t=(await this.openDB()).transaction("pendingCaptures","readwrite"),r=t.store.index("sessionId");for await(const n of r.iterate(y)){const a=n.value;a.captureParams.responseGroupId===e&&await n.update({...a,canUpload:!0})}await t.done}async markPendingHeatmapsReady(e){if(parseInt(s.sessionStorageHelper.getItem("sprig.pendingCount")??"0")===0)return null;const t=Date.now(),r=(await this.openDB()).transaction("pendingCaptures","readwrite"),n=r.store.index("sessionId");for await(const a of n.iterate(y)){const o=a.value;!o.captureParams.isHeatmap||e&&!e.includes(o.uuid)||await a.update({...o,targetTimestamp:t,captureParams:{...o.captureParams,triggerTimestamp:t,replayParams:{...o.captureParams.replayParams,replayDurationSeconds:Math.floor((t-o.timestamp)/1e3)}}})}await r.done}},ye=async(e,t)=>{const r=performance.now();let n;try{n=await e()}finally{const a=performance.now()-r;let o=s.PerformanceMetrics[t];o||(o=s.registerMetric(t)),o.report(a/1e3)}return n},fe=(e,t)=>{const r=performance.now();try{e()}finally{const n=performance.now()-r;let a=s.PerformanceMetrics[t];a||(a=s.registerMetric(t)),a.report(n/1e3)}};let he=5e3,G=6e4,W=0,E,$=!1,q=[];const ze=e=>{var t,r,n,a;if((t=e.event)!=null&&t.includes("Sprig_Scroll")){const o=(a=(n=(r=JSON.parse(e.event))==null?void 0:r.data)==null?void 0:n.payload)==null?void 0:a.xPath;if(!o)return;p.scrollEventUuids[o]=e.uuid}q.push(e),$||Je()},Je=()=>{$=!0,setTimeout(async()=>{if(v())return;const e=q;q=[],$=!1,fe(async()=>{await(async t=>{const r=t.map(n=>({...n,sessionId:n.sessionId??y}));if(r.length!==0)return f(()=>l.bulkAdd("events",r),"Error storing replay events")})(e)},"sdk_replay_add_event_batch_seconds")},500)},Qe=(e,t,r)=>{p.cleanupInterval=window.setInterval(()=>{const n=Date.now();ye(()=>f(async()=>{v()||await Promise.all([l.deleteRowsBefore("events",n-1e3*e,a=>a.expiredAt===void 0||a.expiredAt<n-1e3*e),l.deleteRowsBefore("chunkUploads",n-1e3*t),l.deleteRowsBefore("pendingCaptures",n-1e3*r,a=>!a.canUpload)])},"Error deleting table rows"),"sdk_replay_cleanup_seconds"),s.breadcrumbsLogger.debug("CleanupComplete")},3e4)},Xe=()=>{p.pendingCheckInterval=window.setInterval(async()=>{f(async()=>{await Ie()},"Error initiating pending captures")},5e3)},Ie=async(e=!1)=>{const t=parseInt(E??"0");if(t===0)return;const r=await l.getPendingCaptures({beforePresent:!0,isBeforeType:e}),n=await l.openDB();await Promise.all(r.map(async a=>(await n.delete("pendingCaptures",a.uuid),Se(a.captureParams,a.canUpload)))),E=(t-r.length).toString(),s.sessionStorageHelper.setItem("sprig.pendingCount",E)},Ye=async(e,t,r,n,a)=>{const o=Math.min(e+a,r),i=await ye(()=>l.getEventsBetween(e,o),"sdk_replay_get_events_between_seconds");if(!(i!=null&&i.length))return s.breadcrumbsLogger.debug("NoEventsFound"),{validStartFound:n,events:[]};if(!n){s.breadcrumbsLogger.debug("ValidStartSearch");let c=-1;return i==null||i.forEach((d,u)=>{if(!d.isValidStart)return;const w=d.timestamp<=t;(c<0||w)&&(c=u)}),c<0?(s.breadcrumbsLogger.debug("ValidStartNotFound"),{validStartFound:n,events:[]}):{validStartFound:!0,events:i==null?void 0:i.slice(c)}}return{validStartFound:n,events:i}},be=e=>Promise.all(e.map(async t=>{const r=await(async n=>ne.execute(async()=>{var i;s.breadcrumbsLogger.info("UploadChunkStart",{chunkIndex:n.chunkIndex,surveyId:n.surveyId});const a=await s.sprigFetch(n.uploadUrl,{body:n.data,method:"PUT"});s.breadcrumbsLogger.http("UploadChunkEnd",{url:n.uploadUrl,method:"PUT",status_code:a.status,reason:a.statusText??"OK",chunkIndex:n.chunkIndex,surveyId:n.surveyId});const o=(i=a.headers)==null?void 0:i.get("ETag");if(!o)throw new Error(`Upload response did not include etag for upload ${n.uploadId}, part ${n.chunkIndex}`);return o}))(t);return await l.updatePartial("chunkUploads",t.uuid,{data:null,etag:r,status:"UploadComplete"}),t.uploadId})),ve=async e=>{const t=await l.getChunkUploadsByStatus({status:"UploadComplete",uploadId:e});if(!(t!=null&&t.length))return void s.breadcrumbsLogger.info("NoChunksForUpload",{uploadId:e});const r=t.reduce((o,i)=>(o.find(c=>c.chunkIndex===i.chunkIndex)||o.push(i),o),[]);r.sort((o,i)=>o.chunkIndex-i.chunkIndex);const n=r.map(o=>({ETag:o.etag,PartNumber:o.chunkIndex})).filter(o=>o.ETag!==null),a=r[0];await ae({apiUrl:a.apiUrl,surveyId:a.surveyId,uploadId:e,responseGroupUuid:a.responseGroupId,etags:n,headers:a.completeUploadHeaders,replayDuration:a.replayDuration}),await l.deleteChunkUploads("UploadComplete",e)},Ze=()=>{f(async()=>{const e=await l.getChunkUploadsByStatus({sessionId:y,status:"ReadyForUpload"});if(!(e!=null&&e.length))return;const t=await be(e);t!=null&&t.length&&await Promise.all(t.map(r=>{if(r)return ve(r)}))},"Error uploading unfinished chunks")},et=async(e,t)=>{const r=t??Date.now();return(async(n,a)=>{const o=new TextEncoder;let i=null;const c=new CompressionStream("gzip"),d=c.writable.getWriter();let u=!1,w=!1,[g,h]=[0,0],m=[];for(let k=n-35e3;k<a;k+=G){if({validStartFound:w,events:m}=await Ye(k,n,a,w,G),!(m!=null&&m.length)){s.breadcrumbsLogger.debug("NoEventsFound");continue}g===0&&(g=m[0].timestamp),h=m[m.length-1].timestamp;const R=m.map(C=>C.event);R.push(`{"timestamp":${a}}`);const B=`${u?",":"["}${R}`,x=o.encode(B);fe(()=>{d.write(x)},"sdk_replay_compression_seconds"),u=!0}if(h-g<he)return s.breadcrumbsLogger.debug("ReplayTooShort"),null;const S=o.encode("]");return d.write(S),d.close(),i=new Uint8Array(await new Response(c.readable).arrayBuffer()),i})(r-e,r)},re=async e=>{const{surveyId:t,responseGroupId:r,visitorId:n,apiUrl:a,completeUploadHeaders:o,replayParams:i,triggerTimestamp:c}=e,d=await et(1e3*i.replayDurationSeconds,c);if(!(d!=null&&d.length))return void s.breadcrumbsLogger.info("FileDataEmpty",{surveyId:t});const u=((g,h,m)=>{const S=g.length,k=1024*h*1024,R=Math.ceil(S/m),B=Math.max(k,R),x=[];let C=0;for(;C<S;)x.push(g.slice(C,C+B)),C+=B;return x})(d,i.minimumChunkSizeMb,i.signedUrls.length),w=await Promise.all(u.map(async(g,h)=>{const m=s.v4(),S={apiUrl:a,chunkIndex:h+1,completeUploadHeaders:o,etag:null,responseGroupId:r,status:"ReadyForUpload",surveyId:t,timestamp:c,totalChunks:u.length,data:g,uploadId:i.uploadId,uploadUrl:i.signedUrls[h].url,uuid:m,visitorId:n};return await(await l.openDB()).add("chunkUploads",{...S,sessionId:S.sessionId??y}),S}));await(async(g,h)=>{await be(h),await Promise.all(g.map(m=>ve(m)))})([i.uploadId],w)},Se=async(e,t)=>{if(v())return s.breadcrumbsLogger.debug("ReplayDisabled-ScheduleOrCapture");const{isHeatmap:r,isStandalone:n,replayParams:a,triggerTimestamp:o,responseGroupId:i}=e,c=async()=>{setTimeout(()=>s.eventEmitter.removeListener(s.SprigEvent.QuestionAnswered,c),0),f(async()=>{a.replayDurationType==="before"?await re(e):await l.markPendingCaptureToCanUpload(i)},"Error in schedule/capture callback")};f(async()=>{if(a.replayDurationType==="after"||a.replayDurationType==="beforeAndAfter")return!n&&!r&&s.eventEmitter.on(s.SprigEvent.QuestionAnswered,c),void await Ee(e);if(n||r||t)await re(e),r&&tt();else{const d=35+a.replayDurationSeconds,u=o-1e3*d,w=o;await l.updateEventsExpiredAt(u,w,a.expirationTimeLimitMinutes),s.eventEmitter.on(s.SprigEvent.QuestionAnswered,c)}},"Error in scheduling/capturing replay")},tt=async()=>{parseInt(E??"0")||s.sessionStorageHelper.removeItem("sprig.isCapturingHeatmap"),s.sessionStorageHelper.getItem("sprig.teardownAfterCapture")&&(we(),De(),s.sessionStorageHelper.removeItem("sprig.teardownAfterCapture"))},De=async()=>v()?s.breadcrumbsLogger.debug("ReplayDisabled-ClearData"):Promise.all([l.deleteBySessionId("events",y),l.deleteBySessionId("pendingCaptures",y)]).catch(e=>{T("Error clearing user replay data",e)}),Ee=async e=>{if(v())return;const{isHeatmap:t,surveyId:r}=e,n=await l.getPendingCaptures(),a=n==null?void 0:n.filter(d=>d.captureParams.surveyId===r);if(a!=null&&a.length)return void s.breadcrumbsLogger.info("PendingCaptureExists",{surveyId:r});t&&(p.isRecording&&f(()=>{var d,u;return(u=(d=window.rrwebRecord)==null?void 0:d.takeFullSnapshot)==null?void 0:u.call(d,!0)},"Error recording full snapshot"),s.sessionStorageHelper.setItem("sprig.isCapturingHeatmap","true"),W=Date.now(),p.inactivityInterval||(p.inactivityInterval=window.setInterval(()=>{var d;d=W,Date.now()-d>=3e4&&f(()=>l.markPendingHeatmapsReady(),"Error in heatmap inactivity")},1e3)));const o={...e,replayParams:{...e.replayParams}};e.replayParams.replayDurationType==="beforeAndAfter"&&(o.replayParams.replayDurationSeconds*=2),o.replayParams.replayDurationType="before";const i=e.triggerTimestamp+1e3*e.replayParams.replayDurationSeconds;o.triggerTimestamp=i,E=(parseInt(E??"0")+1).toString(),s.sessionStorageHelper.setItem("sprig.pendingCount",E),await(await l.openDB()).add("pendingCaptures",{canUpload:!1,captureParams:o,sessionId:y,targetTimestamp:i,timestamp:Date.now(),uuid:s.v4()})},rt=Object.freeze(Object.defineProperty({__proto__:null,RecordEvent:e=>{b("Sprig_TrackEvent",e)},RecordPageView:e=>{e.description&&(e.description=z(e.description)),b("Sprig_PageView",e)},RecordSurveyShown:e=>{b("Sprig_ShowSurvey",e)},_completeSessionReplay:async({surveyId:e,responseGroupUuid:t,eventDigest:r,headers:n})=>{if(!e||!t)return!1;const a=window.UserLeap._API_URL,o=await ae({surveyId:e,responseGroupUuid:t,eventDigest:r,apiUrl:a,headers:n},!0);return!(o!=null&&o.error)},checkPendingHeatmapsUrl:()=>v()?s.breadcrumbsLogger.debug("ReplayDisabled-PendingHeatmaps"):f(async()=>{const e=(await l.getPendingCaptures({isHeatmap:!0})).map(t=>({eventId:t.captureParams.eventId,uuid:t.uuid})).filter(({eventId:t})=>!s.checkUrlStillMatching(t)).map(({uuid:t})=>t);s.breadcrumbsLogger.info("PendingHeatmapsToComplete",{count:e.length}),e.length&&(await l.markPendingHeatmapsReady(e),s.breadcrumbsLogger.info("MarkedPendingHeatmapsReady"))},"Error marking pending heatmaps ready"),clearUserReplayData:De,disableRecording:T,initializeReplay:async({maxReplayDurationSeconds:e,maxInflightRequests:t=2,replaySettings:r,teardownAfter:n=!1})=>{if(E=s.sessionStorageHelper.getItem("sprig.pendingCount"),!p.isRecording){if(n&&s.sessionStorageHelper.setItem("sprig.teardownAfterCapture","true"),v())return s.breadcrumbsLogger.debug("ReplayDisabled");if(await(async()=>{var a;if(!me())return!0;if((a=window.navigator.storage)!=null&&a.estimate)try{const{quota:o=0,usage:i=0}=await window.navigator.storage.estimate(),c=(o-i)/1024**3;return s.breadcrumbsLogger.info("Storage",{availableGb:c}),c<.5}catch{return!0}return!1})())return s.breadcrumbsLogger.debug("IDBNotSupported"),K();try{const a=await l.openDB();s.breadcrumbsLogger.info("DBVersion",{version:a.version})}catch(a){return s.breadcrumbsLogger.error("ReplayOpenErr",{name:a.name}),a.name==="VersionError"&&l.deleteDB(),K()}if(f(async()=>{await Ie(!0)},"Error uploading ready pending captures"),!e)return s.breadcrumbsLogger.debug("MissingDuration");s.breadcrumbsLogger.debug("ReplayInit"),await f(async()=>{var a;if(r!=null&&r.minDuration&&(he=r.minDuration),r!=null&&r.batchDuration&&(G=r.batchDuration),a=t,ne.setLimit(a),Ze(),Qe(e+35,1800,e+35),Xe(),!window.rrwebRecord){const{record:d}=await import(window.UserLeap.replayLibraryURL??"https://cdn.sprig.com/dependencies/record-2.0.0-alpha.17.min.js");window.rrwebRecord=d}const o=window.rrwebRecord;if(!o)return s.breadcrumbsLogger.error("RecordScriptFailed");let i=!0,c=0;p.stopRecording=o({checkoutEveryNms:3e4,sampling:{input:"last",scroll:250,media:800},emit:(d,u)=>{if(d.type===P.Custom&&(W=Date.now()),v())return;if(u&&d.type===P.Meta)c=performance.now();else if(u&&c&&d.type===P.FullSnapshot){const g=performance.now()-c;s.reportAndRegister("sdk_replay_snapshot_seconds",g/1e3)}const w=i||!!u&&d.type===P.Meta;i=!1,ze({uuid:s.v4(),event:JSON.stringify(d),isValidStart:w,timestamp:Date.now()})},...r}),p.isRecording=!!p.stopRecording,p.isRecording&&(s.eventEmitter.on("survey.complete",d=>{var u;u={id:d,userAgent:window.navigator.userAgent},b("Sprig_SubmitSurvey",u)}),Fe())},"Error initializing replay")}},isReplayRecording:()=>p.isRecording,scheduleCapture:Ee,scheduleOrCaptureReplay:Se,tryReplayAction:f},Symbol.toStringTag,{value:"Module"}));s.registerReplay(rt);