@sentry/replay 7.32.0 → 7.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esm/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { getCurrentHub, addBreadcrumb, prepareEvent, setContext, captureException, addGlobalEventProcessor } from '@sentry/core';
2
- import { GLOBAL_OBJ, htmlTreeAsString, logger, uuid4, browserPerformanceTimeOrigin, createEnvelope, createEventEnvelopeHeaders, getSdkMetadataForEnvelopeHeader, updateRateLimits, isRateLimited, addInstrumentationHandler, disabledUntil, isNodeEnv } from '@sentry/utils';
1
+ import { getCurrentHub, addBreadcrumb, addGlobalEventProcessor, prepareEvent, setContext, captureException } from '@sentry/core';
2
+ import { GLOBAL_OBJ, logger, uuid4, htmlTreeAsString, addInstrumentationHandler, browserPerformanceTimeOrigin, createEnvelope, createEventEnvelopeHeaders, getSdkMetadataForEnvelopeHeader, updateRateLimits, isRateLimited, disabledUntil, isNodeEnv } from '@sentry/utils';
3
3
 
4
4
  // exporting a separate copy of `WINDOW` rather than exporting the one from `@sentry/browser`
5
5
  // prevents the browser package from being bundled in the CDN bundle, and avoids a
@@ -20,12 +20,6 @@ const VISIBILITY_CHANGE_TIMEOUT = SESSION_IDLE_DURATION;
20
20
  // The maximum length of a session
21
21
  const MAX_SESSION_LIFE = 3600000; // 60 minutes
22
22
 
23
- /**
24
- * Defaults for sampling rates
25
- */
26
- const DEFAULT_SESSION_SAMPLE_RATE = 0.1;
27
- const DEFAULT_ERROR_SAMPLE_RATE = 1.0;
28
-
29
23
  /** The select to use for the `maskAllText` option */
30
24
  const MASK_ALL_TEXT_SELECTOR = 'body *:not(style), body *:not(script)';
31
25
 
@@ -3286,1087 +3280,1158 @@ record.takeFullSnapshot = function (isCheckout) {
3286
3280
  };
3287
3281
  record.mirror = mirror;
3288
3282
 
3289
- /**
3290
- * Create a breadcrumb for a replay.
3291
- */
3292
- function createBreadcrumb(
3293
- breadcrumb,
3294
- ) {
3295
- return {
3296
- timestamp: new Date().getTime() / 1000,
3297
- type: 'default',
3298
- ...breadcrumb,
3283
+ const NAVIGATION_ENTRY_KEYS = [
3284
+ 'name',
3285
+ 'type',
3286
+ 'startTime',
3287
+ 'transferSize',
3288
+ 'duration',
3289
+ ];
3290
+
3291
+ function isNavigationEntryEqual(a) {
3292
+ return function (b) {
3293
+ return NAVIGATION_ENTRY_KEYS.every(key => a[key] === b[key]);
3299
3294
  };
3300
3295
  }
3301
3296
 
3302
3297
  /**
3303
- * An event handler to react to DOM events.
3298
+ * There are some difficulties diagnosing why there are duplicate navigation
3299
+ * entries. We've witnessed several intermittent results:
3300
+ * - duplicate entries have duration = 0
3301
+ * - duplicate entries are the same object reference
3302
+ * - none of the above
3303
+ *
3304
+ * Compare the values of several keys to determine if the entries are duplicates or not.
3304
3305
  */
3305
- function handleDom(handlerData) {
3306
- // Taken from https://github.com/getsentry/sentry-javascript/blob/master/packages/browser/src/integrations/breadcrumbs.ts#L112
3307
- let target;
3308
- let targetNode;
3306
+ // TODO (high-prio): Figure out wth is returned here
3307
+ // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
3308
+ function dedupePerformanceEntries(
3309
+ currentList,
3310
+ newList,
3311
+ ) {
3312
+ // Partition `currentList` into 3 different lists based on entryType
3313
+ const [existingNavigationEntries, existingLcpEntries, existingEntries] = currentList.reduce(
3314
+ (acc, entry) => {
3315
+ if (entry.entryType === 'navigation') {
3316
+ acc[0].push(entry );
3317
+ } else if (entry.entryType === 'largest-contentful-paint') {
3318
+ acc[1].push(entry );
3319
+ } else {
3320
+ acc[2].push(entry);
3321
+ }
3322
+ return acc;
3323
+ },
3324
+ [[], [], []],
3325
+ );
3309
3326
 
3310
- // Accessing event.target can throw (see getsentry/raven-js#838, #768)
3311
- try {
3312
- targetNode = getTargetNode(handlerData);
3313
- target = htmlTreeAsString(targetNode);
3314
- } catch (e) {
3315
- target = '<unknown>';
3316
- }
3327
+ const newEntries = [];
3328
+ const newNavigationEntries = [];
3329
+ let newLcpEntry = existingLcpEntries.length
3330
+ ? existingLcpEntries[existingLcpEntries.length - 1] // Take the last element as list is sorted
3331
+ : undefined;
3317
3332
 
3318
- if (target.length === 0) {
3319
- return null;
3320
- }
3333
+ newList.forEach(entry => {
3334
+ if (entry.entryType === 'largest-contentful-paint') {
3335
+ // We want the latest LCP event only
3336
+ if (!newLcpEntry || newLcpEntry.startTime < entry.startTime) {
3337
+ newLcpEntry = entry;
3338
+ }
3339
+ return;
3340
+ }
3321
3341
 
3322
- return createBreadcrumb({
3323
- category: `ui.${handlerData.name}`,
3324
- message: target,
3325
- data: {
3326
- // Not sure why this errors, Node should be correct (Argument of type 'Node' is not assignable to parameter of type 'INode')
3327
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
3328
- ...(targetNode ? { nodeId: record.mirror.getId(targetNode ) } : {}),
3329
- },
3330
- });
3331
- }
3342
+ if (entry.entryType === 'navigation') {
3343
+ const navigationEntry = entry ;
3332
3344
 
3333
- function getTargetNode(handlerData) {
3334
- if (isEventWithTarget(handlerData.event)) {
3335
- return handlerData.event.target;
3336
- }
3345
+ // Check if the navigation entry is contained in currentList or newList
3346
+ if (
3347
+ // Ignore any navigation entries with duration 0, as they are likely duplicates
3348
+ entry.duration > 0 &&
3349
+ // Ensure new entry does not already exist in existing entries
3350
+ !existingNavigationEntries.find(isNavigationEntryEqual(navigationEntry)) &&
3351
+ // Ensure new entry does not already exist in new list of navigation entries
3352
+ !newNavigationEntries.find(isNavigationEntryEqual(navigationEntry))
3353
+ ) {
3354
+ newNavigationEntries.push(navigationEntry);
3355
+ }
3337
3356
 
3338
- return handlerData.event;
3339
- }
3357
+ // Otherwise this navigation entry is considered a duplicate and is thrown away
3358
+ return;
3359
+ }
3340
3360
 
3341
- function isEventWithTarget(event) {
3342
- return !!(event ).target;
3343
- }
3361
+ newEntries.push(entry);
3362
+ });
3344
3363
 
3345
- let _LAST_BREADCRUMB = null;
3364
+ // Re-combine and sort by startTime
3365
+ return [
3366
+ ...(newLcpEntry ? [newLcpEntry] : []),
3367
+ ...existingNavigationEntries,
3368
+ ...existingEntries,
3369
+ ...newEntries,
3370
+ ...newNavigationEntries,
3371
+ ].sort((a, b) => a.startTime - b.startTime);
3372
+ }
3346
3373
 
3347
3374
  /**
3348
- * An event handler to handle scope changes.
3375
+ * Sets up a PerformanceObserver to listen to all performance entry types.
3349
3376
  */
3350
- function handleScope(scope) {
3351
- const newBreadcrumb = scope.getLastBreadcrumb();
3352
-
3353
- // Listener can be called when breadcrumbs have not changed, so we store the
3354
- // reference to the last crumb and only return a crumb if it has changed
3355
- if (_LAST_BREADCRUMB === newBreadcrumb || !newBreadcrumb) {
3356
- return null;
3357
- }
3377
+ function setupPerformanceObserver(replay) {
3378
+ const performanceObserverHandler = (list) => {
3379
+ // For whatever reason the observer was returning duplicate navigation
3380
+ // entries (the other entry types were not duplicated).
3381
+ const newPerformanceEntries = dedupePerformanceEntries(
3382
+ replay.performanceEvents,
3383
+ list.getEntries() ,
3384
+ );
3385
+ replay.performanceEvents = newPerformanceEntries;
3386
+ };
3358
3387
 
3359
- _LAST_BREADCRUMB = newBreadcrumb;
3388
+ const performanceObserver = new PerformanceObserver(performanceObserverHandler);
3360
3389
 
3361
- if (
3362
- newBreadcrumb.category &&
3363
- (['fetch', 'xhr', 'sentry.event', 'sentry.transaction'].includes(newBreadcrumb.category) ||
3364
- newBreadcrumb.category.startsWith('ui.'))
3365
- ) {
3366
- return null;
3367
- }
3390
+ [
3391
+ 'element',
3392
+ 'event',
3393
+ 'first-input',
3394
+ 'largest-contentful-paint',
3395
+ 'layout-shift',
3396
+ 'longtask',
3397
+ 'navigation',
3398
+ 'paint',
3399
+ 'resource',
3400
+ ].forEach(type => {
3401
+ try {
3402
+ performanceObserver.observe({
3403
+ type,
3404
+ buffered: true,
3405
+ });
3406
+ } catch (e) {
3407
+ // This can throw if an entry type is not supported in the browser.
3408
+ // Ignore these errors.
3409
+ }
3410
+ });
3368
3411
 
3369
- return createBreadcrumb(newBreadcrumb);
3412
+ return performanceObserver;
3370
3413
  }
3371
3414
 
3415
+ const workerString = `/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */
3416
+ function t(t){let e=t.length;for(;--e>=0;)t[e]=0}const e=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),a=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),i=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),n=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),s=new Array(576);t(s);const r=new Array(60);t(r);const o=new Array(512);t(o);const l=new Array(256);t(l);const h=new Array(29);t(h);const d=new Array(30);function _(t,e,a,i,n){this.static_tree=t,this.extra_bits=e,this.extra_base=a,this.elems=i,this.max_length=n,this.has_stree=t&&t.length}let f,c,u;function w(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}t(d);const m=t=>t<256?o[t]:o[256+(t>>>7)],b=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},g=(t,e,a)=>{t.bi_valid>16-a?(t.bi_buf|=e<<t.bi_valid&65535,b(t,t.bi_buf),t.bi_buf=e>>16-t.bi_valid,t.bi_valid+=a-16):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=a)},p=(t,e,a)=>{g(t,a[2*e],a[2*e+1])},k=(t,e)=>{let a=0;do{a|=1&t,t>>>=1,a<<=1}while(--e>0);return a>>>1},v=(t,e,a)=>{const i=new Array(16);let n,s,r=0;for(n=1;n<=15;n++)r=r+a[n-1]<<1,i[n]=r;for(s=0;s<=e;s++){let e=t[2*s+1];0!==e&&(t[2*s]=k(i[e]++,e))}},y=t=>{let e;for(e=0;e<286;e++)t.dyn_ltree[2*e]=0;for(e=0;e<30;e++)t.dyn_dtree[2*e]=0;for(e=0;e<19;e++)t.bl_tree[2*e]=0;t.dyn_ltree[512]=1,t.opt_len=t.static_len=0,t.sym_next=t.matches=0},x=t=>{t.bi_valid>8?b(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},z=(t,e,a,i)=>{const n=2*e,s=2*a;return t[n]<t[s]||t[n]===t[s]&&i[e]<=i[a]},A=(t,e,a)=>{const i=t.heap[a];let n=a<<1;for(;n<=t.heap_len&&(n<t.heap_len&&z(e,t.heap[n+1],t.heap[n],t.depth)&&n++,!z(e,i,t.heap[n],t.depth));)t.heap[a]=t.heap[n],a=n,n<<=1;t.heap[a]=i},E=(t,i,n)=>{let s,r,o,_,f=0;if(0!==t.sym_next)do{s=255&t.pending_buf[t.sym_buf+f++],s+=(255&t.pending_buf[t.sym_buf+f++])<<8,r=t.pending_buf[t.sym_buf+f++],0===s?p(t,r,i):(o=l[r],p(t,o+256+1,i),_=e[o],0!==_&&(r-=h[o],g(t,r,_)),s--,o=m(s),p(t,o,n),_=a[o],0!==_&&(s-=d[o],g(t,s,_)))}while(f<t.sym_next);p(t,256,i)},R=(t,e)=>{const a=e.dyn_tree,i=e.stat_desc.static_tree,n=e.stat_desc.has_stree,s=e.stat_desc.elems;let r,o,l,h=-1;for(t.heap_len=0,t.heap_max=573,r=0;r<s;r++)0!==a[2*r]?(t.heap[++t.heap_len]=h=r,t.depth[r]=0):a[2*r+1]=0;for(;t.heap_len<2;)l=t.heap[++t.heap_len]=h<2?++h:0,a[2*l]=1,t.depth[l]=0,t.opt_len--,n&&(t.static_len-=i[2*l+1]);for(e.max_code=h,r=t.heap_len>>1;r>=1;r--)A(t,a,r);l=s;do{r=t.heap[1],t.heap[1]=t.heap[t.heap_len--],A(t,a,1),o=t.heap[1],t.heap[--t.heap_max]=r,t.heap[--t.heap_max]=o,a[2*l]=a[2*r]+a[2*o],t.depth[l]=(t.depth[r]>=t.depth[o]?t.depth[r]:t.depth[o])+1,a[2*r+1]=a[2*o+1]=l,t.heap[1]=l++,A(t,a,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],((t,e)=>{const a=e.dyn_tree,i=e.max_code,n=e.stat_desc.static_tree,s=e.stat_desc.has_stree,r=e.stat_desc.extra_bits,o=e.stat_desc.extra_base,l=e.stat_desc.max_length;let h,d,_,f,c,u,w=0;for(f=0;f<=15;f++)t.bl_count[f]=0;for(a[2*t.heap[t.heap_max]+1]=0,h=t.heap_max+1;h<573;h++)d=t.heap[h],f=a[2*a[2*d+1]+1]+1,f>l&&(f=l,w++),a[2*d+1]=f,d>i||(t.bl_count[f]++,c=0,d>=o&&(c=r[d-o]),u=a[2*d],t.opt_len+=u*(f+c),s&&(t.static_len+=u*(n[2*d+1]+c)));if(0!==w){do{for(f=l-1;0===t.bl_count[f];)f--;t.bl_count[f]--,t.bl_count[f+1]+=2,t.bl_count[l]--,w-=2}while(w>0);for(f=l;0!==f;f--)for(d=t.bl_count[f];0!==d;)_=t.heap[--h],_>i||(a[2*_+1]!==f&&(t.opt_len+=(f-a[2*_+1])*a[2*_],a[2*_+1]=f),d--)}})(t,e),v(a,h,t.bl_count)},Z=(t,e,a)=>{let i,n,s=-1,r=e[1],o=0,l=7,h=4;for(0===r&&(l=138,h=3),e[2*(a+1)+1]=65535,i=0;i<=a;i++)n=r,r=e[2*(i+1)+1],++o<l&&n===r||(o<h?t.bl_tree[2*n]+=o:0!==n?(n!==s&&t.bl_tree[2*n]++,t.bl_tree[32]++):o<=10?t.bl_tree[34]++:t.bl_tree[36]++,o=0,s=n,0===r?(l=138,h=3):n===r?(l=6,h=3):(l=7,h=4))},S=(t,e,a)=>{let i,n,s=-1,r=e[1],o=0,l=7,h=4;for(0===r&&(l=138,h=3),i=0;i<=a;i++)if(n=r,r=e[2*(i+1)+1],!(++o<l&&n===r)){if(o<h)do{p(t,n,t.bl_tree)}while(0!=--o);else 0!==n?(n!==s&&(p(t,n,t.bl_tree),o--),p(t,16,t.bl_tree),g(t,o-3,2)):o<=10?(p(t,17,t.bl_tree),g(t,o-3,3)):(p(t,18,t.bl_tree),g(t,o-11,7));o=0,s=n,0===r?(l=138,h=3):n===r?(l=6,h=3):(l=7,h=4)}};let U=!1;const D=(t,e,a,i)=>{g(t,0+(i?1:0),3),x(t),b(t,a),b(t,~a),a&&t.pending_buf.set(t.window.subarray(e,e+a),t.pending),t.pending+=a};var O=(t,e,a,i)=>{let o,l,h=0;t.level>0?(2===t.strm.data_type&&(t.strm.data_type=(t=>{let e,a=4093624447;for(e=0;e<=31;e++,a>>>=1)if(1&a&&0!==t.dyn_ltree[2*e])return 0;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return 1;for(e=32;e<256;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0})(t)),R(t,t.l_desc),R(t,t.d_desc),h=(t=>{let e;for(Z(t,t.dyn_ltree,t.l_desc.max_code),Z(t,t.dyn_dtree,t.d_desc.max_code),R(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*n[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e})(t),o=t.opt_len+3+7>>>3,l=t.static_len+3+7>>>3,l<=o&&(o=l)):o=l=a+5,a+4<=o&&-1!==e?D(t,e,a,i):4===t.strategy||l===o?(g(t,2+(i?1:0),3),E(t,s,r)):(g(t,4+(i?1:0),3),((t,e,a,i)=>{let s;for(g(t,e-257,5),g(t,a-1,5),g(t,i-4,4),s=0;s<i;s++)g(t,t.bl_tree[2*n[s]+1],3);S(t,t.dyn_ltree,e-1),S(t,t.dyn_dtree,a-1)})(t,t.l_desc.max_code+1,t.d_desc.max_code+1,h+1),E(t,t.dyn_ltree,t.dyn_dtree)),y(t),i&&x(t)},T={_tr_init:t=>{U||((()=>{let t,n,w,m,b;const g=new Array(16);for(w=0,m=0;m<28;m++)for(h[m]=w,t=0;t<1<<e[m];t++)l[w++]=m;for(l[w-1]=m,b=0,m=0;m<16;m++)for(d[m]=b,t=0;t<1<<a[m];t++)o[b++]=m;for(b>>=7;m<30;m++)for(d[m]=b<<7,t=0;t<1<<a[m]-7;t++)o[256+b++]=m;for(n=0;n<=15;n++)g[n]=0;for(t=0;t<=143;)s[2*t+1]=8,t++,g[8]++;for(;t<=255;)s[2*t+1]=9,t++,g[9]++;for(;t<=279;)s[2*t+1]=7,t++,g[7]++;for(;t<=287;)s[2*t+1]=8,t++,g[8]++;for(v(s,287,g),t=0;t<30;t++)r[2*t+1]=5,r[2*t]=k(t,5);f=new _(s,e,257,286,15),c=new _(r,a,0,30,15),u=new _(new Array(0),i,0,19,7)})(),U=!0),t.l_desc=new w(t.dyn_ltree,f),t.d_desc=new w(t.dyn_dtree,c),t.bl_desc=new w(t.bl_tree,u),t.bi_buf=0,t.bi_valid=0,y(t)},_tr_stored_block:D,_tr_flush_block:O,_tr_tally:(t,e,a)=>(t.pending_buf[t.sym_buf+t.sym_next++]=e,t.pending_buf[t.sym_buf+t.sym_next++]=e>>8,t.pending_buf[t.sym_buf+t.sym_next++]=a,0===e?t.dyn_ltree[2*a]++:(t.matches++,e--,t.dyn_ltree[2*(l[a]+256+1)]++,t.dyn_dtree[2*m(e)]++),t.sym_next===t.sym_end),_tr_align:t=>{g(t,2,3),p(t,256,s),(t=>{16===t.bi_valid?(b(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)})(t)}};var N=(t,e,a,i)=>{let n=65535&t|0,s=t>>>16&65535|0,r=0;for(;0!==a;){r=a>2e3?2e3:a,a-=r;do{n=n+e[i++]|0,s=s+n|0}while(--r);n%=65521,s%=65521}return n|s<<16|0};const F=new Uint32Array((()=>{let t,e=[];for(var a=0;a<256;a++){t=a;for(var i=0;i<8;i++)t=1&t?3988292384^t>>>1:t>>>1;e[a]=t}return e})());var L=(t,e,a,i)=>{const n=F,s=i+a;t^=-1;for(let a=i;a<s;a++)t=t>>>8^n[255&(t^e[a])];return-1^t},I={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},B={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:C,_tr_stored_block:H,_tr_flush_block:M,_tr_tally:j,_tr_align:K}=T,{Z_NO_FLUSH:P,Z_PARTIAL_FLUSH:Y,Z_FULL_FLUSH:G,Z_FINISH:X,Z_BLOCK:J,Z_OK:W,Z_STREAM_END:q,Z_STREAM_ERROR:Q,Z_DATA_ERROR:V,Z_BUF_ERROR:$,Z_DEFAULT_COMPRESSION:tt,Z_FILTERED:et,Z_HUFFMAN_ONLY:at,Z_RLE:it,Z_FIXED:nt,Z_DEFAULT_STRATEGY:st,Z_UNKNOWN:rt,Z_DEFLATED:ot}=B,lt=(t,e)=>(t.msg=I[e],e),ht=t=>2*t-(t>4?9:0),dt=t=>{let e=t.length;for(;--e>=0;)t[e]=0},_t=t=>{let e,a,i,n=t.w_size;e=t.hash_size,i=e;do{a=t.head[--i],t.head[i]=a>=n?a-n:0}while(--e);e=n,i=e;do{a=t.prev[--i],t.prev[i]=a>=n?a-n:0}while(--e)};let ft=(t,e,a)=>(e<<t.hash_shift^a)&t.hash_mask;const ct=t=>{const e=t.state;let a=e.pending;a>t.avail_out&&(a=t.avail_out),0!==a&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+a),t.next_out),t.next_out+=a,e.pending_out+=a,t.total_out+=a,t.avail_out-=a,e.pending-=a,0===e.pending&&(e.pending_out=0))},ut=(t,e)=>{M(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,ct(t.strm)},wt=(t,e)=>{t.pending_buf[t.pending++]=e},mt=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},bt=(t,e,a,i)=>{let n=t.avail_in;return n>i&&(n=i),0===n?0:(t.avail_in-=n,e.set(t.input.subarray(t.next_in,t.next_in+n),a),1===t.state.wrap?t.adler=N(t.adler,e,n,a):2===t.state.wrap&&(t.adler=L(t.adler,e,n,a)),t.next_in+=n,t.total_in+=n,n)},gt=(t,e)=>{let a,i,n=t.max_chain_length,s=t.strstart,r=t.prev_length,o=t.nice_match;const l=t.strstart>t.w_size-262?t.strstart-(t.w_size-262):0,h=t.window,d=t.w_mask,_=t.prev,f=t.strstart+258;let c=h[s+r-1],u=h[s+r];t.prev_length>=t.good_match&&(n>>=2),o>t.lookahead&&(o=t.lookahead);do{if(a=e,h[a+r]===u&&h[a+r-1]===c&&h[a]===h[s]&&h[++a]===h[s+1]){s+=2,a++;do{}while(h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&s<f);if(i=258-(f-s),s=f-258,i>r){if(t.match_start=e,r=i,i>=o)break;c=h[s+r-1],u=h[s+r]}}}while((e=_[e&d])>l&&0!=--n);return r<=t.lookahead?r:t.lookahead},pt=t=>{const e=t.w_size;let a,i,n;do{if(i=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-262)&&(t.window.set(t.window.subarray(e,e+e-i),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),_t(t),i+=e),0===t.strm.avail_in)break;if(a=bt(t.strm,t.window,t.strstart+t.lookahead,i),t.lookahead+=a,t.lookahead+t.insert>=3)for(n=t.strstart-t.insert,t.ins_h=t.window[n],t.ins_h=ft(t,t.ins_h,t.window[n+1]);t.insert&&(t.ins_h=ft(t,t.ins_h,t.window[n+3-1]),t.prev[n&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=n,n++,t.insert--,!(t.lookahead+t.insert<3)););}while(t.lookahead<262&&0!==t.strm.avail_in)},kt=(t,e)=>{let a,i,n,s=t.pending_buf_size-5>t.w_size?t.w_size:t.pending_buf_size-5,r=0,o=t.strm.avail_in;do{if(a=65535,n=t.bi_valid+42>>3,t.strm.avail_out<n)break;if(n=t.strm.avail_out-n,i=t.strstart-t.block_start,a>i+t.strm.avail_in&&(a=i+t.strm.avail_in),a>n&&(a=n),a<s&&(0===a&&e!==X||e===P||a!==i+t.strm.avail_in))break;r=e===X&&a===i+t.strm.avail_in?1:0,H(t,0,0,r),t.pending_buf[t.pending-4]=a,t.pending_buf[t.pending-3]=a>>8,t.pending_buf[t.pending-2]=~a,t.pending_buf[t.pending-1]=~a>>8,ct(t.strm),i&&(i>a&&(i=a),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+i),t.strm.next_out),t.strm.next_out+=i,t.strm.avail_out-=i,t.strm.total_out+=i,t.block_start+=i,a-=i),a&&(bt(t.strm,t.strm.output,t.strm.next_out,a),t.strm.next_out+=a,t.strm.avail_out-=a,t.strm.total_out+=a)}while(0===r);return o-=t.strm.avail_in,o&&(o>=t.w_size?(t.matches=2,t.window.set(t.strm.input.subarray(t.strm.next_in-t.w_size,t.strm.next_in),0),t.strstart=t.w_size,t.insert=t.strstart):(t.window_size-t.strstart<=o&&(t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,t.insert>t.strstart&&(t.insert=t.strstart)),t.window.set(t.strm.input.subarray(t.strm.next_in-o,t.strm.next_in),t.strstart),t.strstart+=o,t.insert+=o>t.w_size-t.insert?t.w_size-t.insert:o),t.block_start=t.strstart),t.high_water<t.strstart&&(t.high_water=t.strstart),r?4:e!==P&&e!==X&&0===t.strm.avail_in&&t.strstart===t.block_start?2:(n=t.window_size-t.strstart,t.strm.avail_in>n&&t.block_start>=t.w_size&&(t.block_start-=t.w_size,t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,n+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),n>t.strm.avail_in&&(n=t.strm.avail_in),n&&(bt(t.strm,t.window,t.strstart,n),t.strstart+=n,t.insert+=n>t.w_size-t.insert?t.w_size-t.insert:n),t.high_water<t.strstart&&(t.high_water=t.strstart),n=t.bi_valid+42>>3,n=t.pending_buf_size-n>65535?65535:t.pending_buf_size-n,s=n>t.w_size?t.w_size:n,i=t.strstart-t.block_start,(i>=s||(i||e===X)&&e!==P&&0===t.strm.avail_in&&i<=n)&&(a=i>n?n:i,r=e===X&&0===t.strm.avail_in&&a===i?1:0,H(t,t.block_start,a,r),t.block_start+=a,ct(t.strm)),r?3:1)},vt=(t,e)=>{let a,i;for(;;){if(t.lookahead<262){if(pt(t),t.lookahead<262&&e===P)return 1;if(0===t.lookahead)break}if(a=0,t.lookahead>=3&&(t.ins_h=ft(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==a&&t.strstart-a<=t.w_size-262&&(t.match_length=gt(t,a)),t.match_length>=3)if(i=j(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do{t.strstart++,t.ins_h=ft(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!=--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=ft(t,t.ins_h,t.window[t.strstart+1]);else i=j(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(i&&(ut(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,e===X?(ut(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ut(t,!1),0===t.strm.avail_out)?1:2},yt=(t,e)=>{let a,i,n;for(;;){if(t.lookahead<262){if(pt(t),t.lookahead<262&&e===P)return 1;if(0===t.lookahead)break}if(a=0,t.lookahead>=3&&(t.ins_h=ft(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=2,0!==a&&t.prev_length<t.max_lazy_match&&t.strstart-a<=t.w_size-262&&(t.match_length=gt(t,a),t.match_length<=5&&(t.strategy===et||3===t.match_length&&t.strstart-t.match_start>4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){n=t.strstart+t.lookahead-3,i=j(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=n&&(t.ins_h=ft(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!=--t.prev_length);if(t.match_available=0,t.match_length=2,t.strstart++,i&&(ut(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if(i=j(t,0,t.window[t.strstart-1]),i&&ut(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return 1}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(i=j(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===X?(ut(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ut(t,!1),0===t.strm.avail_out)?1:2};function xt(t,e,a,i,n){this.good_length=t,this.max_lazy=e,this.nice_length=a,this.max_chain=i,this.func=n}const zt=[new xt(0,0,0,0,kt),new xt(4,4,8,4,vt),new xt(4,5,16,8,vt),new xt(4,6,32,32,vt),new xt(4,4,16,16,yt),new xt(8,16,32,32,yt),new xt(8,16,128,128,yt),new xt(8,32,128,256,yt),new xt(32,128,258,1024,yt),new xt(32,258,258,4096,yt)];function At(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=ot,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),dt(this.dyn_ltree),dt(this.dyn_dtree),dt(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),dt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),dt(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const Et=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||42!==e.status&&57!==e.status&&69!==e.status&&73!==e.status&&91!==e.status&&103!==e.status&&113!==e.status&&666!==e.status?1:0},Rt=t=>{if(Et(t))return lt(t,Q);t.total_in=t.total_out=0,t.data_type=rt;const e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=2===e.wrap?57:e.wrap?42:113,t.adler=2===e.wrap?0:1,e.last_flush=-2,C(e),W},Zt=t=>{const e=Rt(t);var a;return e===W&&((a=t.state).window_size=2*a.w_size,dt(a.head),a.max_lazy_match=zt[a.level].max_lazy,a.good_match=zt[a.level].good_length,a.nice_match=zt[a.level].nice_length,a.max_chain_length=zt[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=2,a.match_available=0,a.ins_h=0),e},St=(t,e,a,i,n,s)=>{if(!t)return Q;let r=1;if(e===tt&&(e=6),i<0?(r=0,i=-i):i>15&&(r=2,i-=16),n<1||n>9||a!==ot||i<8||i>15||e<0||e>9||s<0||s>nt||8===i&&1!==r)return lt(t,Q);8===i&&(i=9);const o=new At;return t.state=o,o.strm=t,o.status=42,o.wrap=r,o.gzhead=null,o.w_bits=i,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=n+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+3-1)/3),o.window=new Uint8Array(2*o.w_size),o.head=new Uint16Array(o.hash_size),o.prev=new Uint16Array(o.w_size),o.lit_bufsize=1<<n+6,o.pending_buf_size=4*o.lit_bufsize,o.pending_buf=new Uint8Array(o.pending_buf_size),o.sym_buf=o.lit_bufsize,o.sym_end=3*(o.lit_bufsize-1),o.level=e,o.strategy=s,o.method=a,Zt(t)};var Ut={deflateInit:(t,e)=>St(t,e,ot,15,8,st),deflateInit2:St,deflateReset:Zt,deflateResetKeep:Rt,deflateSetHeader:(t,e)=>Et(t)||2!==t.state.wrap?Q:(t.state.gzhead=e,W),deflate:(t,e)=>{if(Et(t)||e>J||e<0)return t?lt(t,Q):Q;const a=t.state;if(!t.output||0!==t.avail_in&&!t.input||666===a.status&&e!==X)return lt(t,0===t.avail_out?$:Q);const i=a.last_flush;if(a.last_flush=e,0!==a.pending){if(ct(t),0===t.avail_out)return a.last_flush=-1,W}else if(0===t.avail_in&&ht(e)<=ht(i)&&e!==X)return lt(t,$);if(666===a.status&&0!==t.avail_in)return lt(t,$);if(42===a.status&&0===a.wrap&&(a.status=113),42===a.status){let e=ot+(a.w_bits-8<<4)<<8,i=-1;if(i=a.strategy>=at||a.level<2?0:a.level<6?1:6===a.level?2:3,e|=i<<6,0!==a.strstart&&(e|=32),e+=31-e%31,mt(a,e),0!==a.strstart&&(mt(a,t.adler>>>16),mt(a,65535&t.adler)),t.adler=1,a.status=113,ct(t),0!==a.pending)return a.last_flush=-1,W}if(57===a.status)if(t.adler=0,wt(a,31),wt(a,139),wt(a,8),a.gzhead)wt(a,(a.gzhead.text?1:0)+(a.gzhead.hcrc?2:0)+(a.gzhead.extra?4:0)+(a.gzhead.name?8:0)+(a.gzhead.comment?16:0)),wt(a,255&a.gzhead.time),wt(a,a.gzhead.time>>8&255),wt(a,a.gzhead.time>>16&255),wt(a,a.gzhead.time>>24&255),wt(a,9===a.level?2:a.strategy>=at||a.level<2?4:0),wt(a,255&a.gzhead.os),a.gzhead.extra&&a.gzhead.extra.length&&(wt(a,255&a.gzhead.extra.length),wt(a,a.gzhead.extra.length>>8&255)),a.gzhead.hcrc&&(t.adler=L(t.adler,a.pending_buf,a.pending,0)),a.gzindex=0,a.status=69;else if(wt(a,0),wt(a,0),wt(a,0),wt(a,0),wt(a,0),wt(a,9===a.level?2:a.strategy>=at||a.level<2?4:0),wt(a,3),a.status=113,ct(t),0!==a.pending)return a.last_flush=-1,W;if(69===a.status){if(a.gzhead.extra){let e=a.pending,i=(65535&a.gzhead.extra.length)-a.gzindex;for(;a.pending+i>a.pending_buf_size;){let n=a.pending_buf_size-a.pending;if(a.pending_buf.set(a.gzhead.extra.subarray(a.gzindex,a.gzindex+n),a.pending),a.pending=a.pending_buf_size,a.gzhead.hcrc&&a.pending>e&&(t.adler=L(t.adler,a.pending_buf,a.pending-e,e)),a.gzindex+=n,ct(t),0!==a.pending)return a.last_flush=-1,W;e=0,i-=n}let n=new Uint8Array(a.gzhead.extra);a.pending_buf.set(n.subarray(a.gzindex,a.gzindex+i),a.pending),a.pending+=i,a.gzhead.hcrc&&a.pending>e&&(t.adler=L(t.adler,a.pending_buf,a.pending-e,e)),a.gzindex=0}a.status=73}if(73===a.status){if(a.gzhead.name){let e,i=a.pending;do{if(a.pending===a.pending_buf_size){if(a.gzhead.hcrc&&a.pending>i&&(t.adler=L(t.adler,a.pending_buf,a.pending-i,i)),ct(t),0!==a.pending)return a.last_flush=-1,W;i=0}e=a.gzindex<a.gzhead.name.length?255&a.gzhead.name.charCodeAt(a.gzindex++):0,wt(a,e)}while(0!==e);a.gzhead.hcrc&&a.pending>i&&(t.adler=L(t.adler,a.pending_buf,a.pending-i,i)),a.gzindex=0}a.status=91}if(91===a.status){if(a.gzhead.comment){let e,i=a.pending;do{if(a.pending===a.pending_buf_size){if(a.gzhead.hcrc&&a.pending>i&&(t.adler=L(t.adler,a.pending_buf,a.pending-i,i)),ct(t),0!==a.pending)return a.last_flush=-1,W;i=0}e=a.gzindex<a.gzhead.comment.length?255&a.gzhead.comment.charCodeAt(a.gzindex++):0,wt(a,e)}while(0!==e);a.gzhead.hcrc&&a.pending>i&&(t.adler=L(t.adler,a.pending_buf,a.pending-i,i))}a.status=103}if(103===a.status){if(a.gzhead.hcrc){if(a.pending+2>a.pending_buf_size&&(ct(t),0!==a.pending))return a.last_flush=-1,W;wt(a,255&t.adler),wt(a,t.adler>>8&255),t.adler=0}if(a.status=113,ct(t),0!==a.pending)return a.last_flush=-1,W}if(0!==t.avail_in||0!==a.lookahead||e!==P&&666!==a.status){let i=0===a.level?kt(a,e):a.strategy===at?((t,e)=>{let a;for(;;){if(0===t.lookahead&&(pt(t),0===t.lookahead)){if(e===P)return 1;break}if(t.match_length=0,a=j(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,a&&(ut(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===X?(ut(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ut(t,!1),0===t.strm.avail_out)?1:2})(a,e):a.strategy===it?((t,e)=>{let a,i,n,s;const r=t.window;for(;;){if(t.lookahead<=258){if(pt(t),t.lookahead<=258&&e===P)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(n=t.strstart-1,i=r[n],i===r[++n]&&i===r[++n]&&i===r[++n])){s=t.strstart+258;do{}while(i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&n<s);t.match_length=258-(s-n),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(a=j(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(a=j(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),a&&(ut(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===X?(ut(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ut(t,!1),0===t.strm.avail_out)?1:2})(a,e):zt[a.level].func(a,e);if(3!==i&&4!==i||(a.status=666),1===i||3===i)return 0===t.avail_out&&(a.last_flush=-1),W;if(2===i&&(e===Y?K(a):e!==J&&(H(a,0,0,!1),e===G&&(dt(a.head),0===a.lookahead&&(a.strstart=0,a.block_start=0,a.insert=0))),ct(t),0===t.avail_out))return a.last_flush=-1,W}return e!==X?W:a.wrap<=0?q:(2===a.wrap?(wt(a,255&t.adler),wt(a,t.adler>>8&255),wt(a,t.adler>>16&255),wt(a,t.adler>>24&255),wt(a,255&t.total_in),wt(a,t.total_in>>8&255),wt(a,t.total_in>>16&255),wt(a,t.total_in>>24&255)):(mt(a,t.adler>>>16),mt(a,65535&t.adler)),ct(t),a.wrap>0&&(a.wrap=-a.wrap),0!==a.pending?W:q)},deflateEnd:t=>{if(Et(t))return Q;const e=t.state.status;return t.state=null,113===e?lt(t,V):W},deflateSetDictionary:(t,e)=>{let a=e.length;if(Et(t))return Q;const i=t.state,n=i.wrap;if(2===n||1===n&&42!==i.status||i.lookahead)return Q;if(1===n&&(t.adler=N(t.adler,e,a,0)),i.wrap=0,a>=i.w_size){0===n&&(dt(i.head),i.strstart=0,i.block_start=0,i.insert=0);let t=new Uint8Array(i.w_size);t.set(e.subarray(a-i.w_size,a),0),e=t,a=i.w_size}const s=t.avail_in,r=t.next_in,o=t.input;for(t.avail_in=a,t.next_in=0,t.input=e,pt(i);i.lookahead>=3;){let t=i.strstart,e=i.lookahead-2;do{i.ins_h=ft(i,i.ins_h,i.window[t+3-1]),i.prev[t&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=t,t++}while(--e);i.strstart=t,i.lookahead=2,pt(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=2,i.match_available=0,t.next_in=r,t.input=o,t.avail_in=s,i.wrap=n,W},deflateInfo:"pako deflate (from Nodeca project)"};const Dt=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var Ot=function(t){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const a=e.shift();if(a){if("object"!=typeof a)throw new TypeError(a+"must be non-object");for(const e in a)Dt(a,e)&&(t[e]=a[e])}}return t},Tt=t=>{let e=0;for(let a=0,i=t.length;a<i;a++)e+=t[a].length;const a=new Uint8Array(e);for(let e=0,i=0,n=t.length;e<n;e++){let n=t[e];a.set(n,i),i+=n.length}return a};let Nt=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){Nt=!1}const Ft=new Uint8Array(256);for(let t=0;t<256;t++)Ft[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;Ft[254]=Ft[254]=1;var Lt=t=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,a,i,n,s,r=t.length,o=0;for(n=0;n<r;n++)a=t.charCodeAt(n),55296==(64512&a)&&n+1<r&&(i=t.charCodeAt(n+1),56320==(64512&i)&&(a=65536+(a-55296<<10)+(i-56320),n++)),o+=a<128?1:a<2048?2:a<65536?3:4;for(e=new Uint8Array(o),s=0,n=0;s<o;n++)a=t.charCodeAt(n),55296==(64512&a)&&n+1<r&&(i=t.charCodeAt(n+1),56320==(64512&i)&&(a=65536+(a-55296<<10)+(i-56320),n++)),a<128?e[s++]=a:a<2048?(e[s++]=192|a>>>6,e[s++]=128|63&a):a<65536?(e[s++]=224|a>>>12,e[s++]=128|a>>>6&63,e[s++]=128|63&a):(e[s++]=240|a>>>18,e[s++]=128|a>>>12&63,e[s++]=128|a>>>6&63,e[s++]=128|63&a);return e},It=(t,e)=>{const a=e||t.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(t.subarray(0,e));let i,n;const s=new Array(2*a);for(n=0,i=0;i<a;){let e=t[i++];if(e<128){s[n++]=e;continue}let r=Ft[e];if(r>4)s[n++]=65533,i+=r-1;else{for(e&=2===r?31:3===r?15:7;r>1&&i<a;)e=e<<6|63&t[i++],r--;r>1?s[n++]=65533:e<65536?s[n++]=e:(e-=65536,s[n++]=55296|e>>10&1023,s[n++]=56320|1023&e)}}return((t,e)=>{if(e<65534&&t.subarray&&Nt)return String.fromCharCode.apply(null,t.length===e?t:t.subarray(0,e));let a="";for(let i=0;i<e;i++)a+=String.fromCharCode(t[i]);return a})(s,n)},Bt=(t,e)=>{(e=e||t.length)>t.length&&(e=t.length);let a=e-1;for(;a>=0&&128==(192&t[a]);)a--;return a<0||0===a?e:a+Ft[t[a]]>e?a:e};var Ct=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0};const Ht=Object.prototype.toString,{Z_NO_FLUSH:Mt,Z_SYNC_FLUSH:jt,Z_FULL_FLUSH:Kt,Z_FINISH:Pt,Z_OK:Yt,Z_STREAM_END:Gt,Z_DEFAULT_COMPRESSION:Xt,Z_DEFAULT_STRATEGY:Jt,Z_DEFLATED:Wt}=B;function qt(t){this.options=Ot({level:Xt,method:Wt,chunkSize:16384,windowBits:15,memLevel:8,strategy:Jt},t||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Ct,this.strm.avail_out=0;let a=Ut.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(a!==Yt)throw new Error(I[a]);if(e.header&&Ut.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t="string"==typeof e.dictionary?Lt(e.dictionary):"[object ArrayBuffer]"===Ht.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,a=Ut.deflateSetDictionary(this.strm,t),a!==Yt)throw new Error(I[a]);this._dict_set=!0}}function Qt(t,e){const a=new qt(e);if(a.push(t,!0),a.err)throw a.msg||I[a.err];return a.result}qt.prototype.push=function(t,e){const a=this.strm,i=this.options.chunkSize;let n,s;if(this.ended)return!1;for(s=e===~~e?e:!0===e?Pt:Mt,"string"==typeof t?a.input=Lt(t):"[object ArrayBuffer]"===Ht.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;;)if(0===a.avail_out&&(a.output=new Uint8Array(i),a.next_out=0,a.avail_out=i),(s===jt||s===Kt)&&a.avail_out<=6)this.onData(a.output.subarray(0,a.next_out)),a.avail_out=0;else{if(n=Ut.deflate(a,s),n===Gt)return a.next_out>0&&this.onData(a.output.subarray(0,a.next_out)),n=Ut.deflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===Yt;if(0!==a.avail_out){if(s>0&&a.next_out>0)this.onData(a.output.subarray(0,a.next_out)),a.avail_out=0;else if(0===a.avail_in)break}else this.onData(a.output)}return!0},qt.prototype.onData=function(t){this.chunks.push(t)},qt.prototype.onEnd=function(t){t===Yt&&(this.result=Tt(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var Vt={Deflate:qt,deflate:Qt,deflateRaw:function(t,e){return(e=e||{}).raw=!0,Qt(t,e)},gzip:function(t,e){return(e=e||{}).gzip=!0,Qt(t,e)},constants:B};var $t=function(t,e){let a,i,n,s,r,o,l,h,d,_,f,c,u,w,m,b,g,p,k,v,y,x,z,A;const E=t.state;a=t.next_in,z=t.input,i=a+(t.avail_in-5),n=t.next_out,A=t.output,s=n-(e-t.avail_out),r=n+(t.avail_out-257),o=E.dmax,l=E.wsize,h=E.whave,d=E.wnext,_=E.window,f=E.hold,c=E.bits,u=E.lencode,w=E.distcode,m=(1<<E.lenbits)-1,b=(1<<E.distbits)-1;t:do{c<15&&(f+=z[a++]<<c,c+=8,f+=z[a++]<<c,c+=8),g=u[f&m];e:for(;;){if(p=g>>>24,f>>>=p,c-=p,p=g>>>16&255,0===p)A[n++]=65535&g;else{if(!(16&p)){if(0==(64&p)){g=u[(65535&g)+(f&(1<<p)-1)];continue e}if(32&p){E.mode=16191;break t}t.msg="invalid literal/length code",E.mode=16209;break t}k=65535&g,p&=15,p&&(c<p&&(f+=z[a++]<<c,c+=8),k+=f&(1<<p)-1,f>>>=p,c-=p),c<15&&(f+=z[a++]<<c,c+=8,f+=z[a++]<<c,c+=8),g=w[f&b];a:for(;;){if(p=g>>>24,f>>>=p,c-=p,p=g>>>16&255,!(16&p)){if(0==(64&p)){g=w[(65535&g)+(f&(1<<p)-1)];continue a}t.msg="invalid distance code",E.mode=16209;break t}if(v=65535&g,p&=15,c<p&&(f+=z[a++]<<c,c+=8,c<p&&(f+=z[a++]<<c,c+=8)),v+=f&(1<<p)-1,v>o){t.msg="invalid distance too far back",E.mode=16209;break t}if(f>>>=p,c-=p,p=n-s,v>p){if(p=v-p,p>h&&E.sane){t.msg="invalid distance too far back",E.mode=16209;break t}if(y=0,x=_,0===d){if(y+=l-p,p<k){k-=p;do{A[n++]=_[y++]}while(--p);y=n-v,x=A}}else if(d<p){if(y+=l+d-p,p-=d,p<k){k-=p;do{A[n++]=_[y++]}while(--p);if(y=0,d<k){p=d,k-=p;do{A[n++]=_[y++]}while(--p);y=n-v,x=A}}}else if(y+=d-p,p<k){k-=p;do{A[n++]=_[y++]}while(--p);y=n-v,x=A}for(;k>2;)A[n++]=x[y++],A[n++]=x[y++],A[n++]=x[y++],k-=3;k&&(A[n++]=x[y++],k>1&&(A[n++]=x[y++]))}else{y=n-v;do{A[n++]=A[y++],A[n++]=A[y++],A[n++]=A[y++],k-=3}while(k>2);k&&(A[n++]=A[y++],k>1&&(A[n++]=A[y++]))}break}}break}}while(a<i&&n<r);k=c>>3,a-=k,c-=k<<3,f&=(1<<c)-1,t.next_in=a,t.next_out=n,t.avail_in=a<i?i-a+5:5-(a-i),t.avail_out=n<r?r-n+257:257-(n-r),E.hold=f,E.bits=c};const te=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),ee=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),ae=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),ie=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]);var ne=(t,e,a,i,n,s,r,o)=>{const l=o.bits;let h,d,_,f,c,u,w=0,m=0,b=0,g=0,p=0,k=0,v=0,y=0,x=0,z=0,A=null;const E=new Uint16Array(16),R=new Uint16Array(16);let Z,S,U,D=null;for(w=0;w<=15;w++)E[w]=0;for(m=0;m<i;m++)E[e[a+m]]++;for(p=l,g=15;g>=1&&0===E[g];g--);if(p>g&&(p=g),0===g)return n[s++]=20971520,n[s++]=20971520,o.bits=1,0;for(b=1;b<g&&0===E[b];b++);for(p<b&&(p=b),y=1,w=1;w<=15;w++)if(y<<=1,y-=E[w],y<0)return-1;if(y>0&&(0===t||1!==g))return-1;for(R[1]=0,w=1;w<15;w++)R[w+1]=R[w]+E[w];for(m=0;m<i;m++)0!==e[a+m]&&(r[R[e[a+m]]++]=m);if(0===t?(A=D=r,u=20):1===t?(A=te,D=ee,u=257):(A=ae,D=ie,u=0),z=0,m=0,w=b,c=s,k=p,v=0,_=-1,x=1<<p,f=x-1,1===t&&x>852||2===t&&x>592)return 1;for(;;){Z=w-v,r[m]+1<u?(S=0,U=r[m]):r[m]>=u?(S=D[r[m]-u],U=A[r[m]-u]):(S=96,U=0),h=1<<w-v,d=1<<k,b=d;do{d-=h,n[c+(z>>v)+d]=Z<<24|S<<16|U|0}while(0!==d);for(h=1<<w-1;z&h;)h>>=1;if(0!==h?(z&=h-1,z+=h):z=0,m++,0==--E[w]){if(w===g)break;w=e[a+r[m]]}if(w>p&&(z&f)!==_){for(0===v&&(v=p),c+=b,k=w-v,y=1<<k;k+v<g&&(y-=E[k+v],!(y<=0));)k++,y<<=1;if(x+=1<<k,1===t&&x>852||2===t&&x>592)return 1;_=z&f,n[_]=p<<24|k<<16|c-s|0}}return 0!==z&&(n[c+z]=w-v<<24|64<<16|0),o.bits=p,0};const{Z_FINISH:se,Z_BLOCK:re,Z_TREES:oe,Z_OK:le,Z_STREAM_END:he,Z_NEED_DICT:de,Z_STREAM_ERROR:_e,Z_DATA_ERROR:fe,Z_MEM_ERROR:ce,Z_BUF_ERROR:ue,Z_DEFLATED:we}=B,me=16209,be=t=>(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24);function ge(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const pe=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.mode<16180||e.mode>16211?1:0},ke=t=>{if(pe(t))return _e;const e=t.state;return t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=16180,e.last=0,e.havedict=0,e.flags=-1,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(852),e.distcode=e.distdyn=new Int32Array(592),e.sane=1,e.back=-1,le},ve=t=>{if(pe(t))return _e;const e=t.state;return e.wsize=0,e.whave=0,e.wnext=0,ke(t)},ye=(t,e)=>{let a;if(pe(t))return _e;const i=t.state;return e<0?(a=0,e=-e):(a=5+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?_e:(null!==i.window&&i.wbits!==e&&(i.window=null),i.wrap=a,i.wbits=e,ve(t))},xe=(t,e)=>{if(!t)return _e;const a=new ge;t.state=a,a.strm=t,a.window=null,a.mode=16180;const i=ye(t,e);return i!==le&&(t.state=null),i};let ze,Ae,Ee=!0;const Re=t=>{if(Ee){ze=new Int32Array(512),Ae=new Int32Array(32);let e=0;for(;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(ne(1,t.lens,0,288,ze,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;ne(2,t.lens,0,32,Ae,0,t.work,{bits:5}),Ee=!1}t.lencode=ze,t.lenbits=9,t.distcode=Ae,t.distbits=5},Ze=(t,e,a,i)=>{let n;const s=t.state;return null===s.window&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new Uint8Array(s.wsize)),i>=s.wsize?(s.window.set(e.subarray(a-s.wsize,a),0),s.wnext=0,s.whave=s.wsize):(n=s.wsize-s.wnext,n>i&&(n=i),s.window.set(e.subarray(a-i,a-i+n),s.wnext),(i-=n)?(s.window.set(e.subarray(a-i,a),0),s.wnext=i,s.whave=s.wsize):(s.wnext+=n,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=n))),0};var Se={inflateReset:ve,inflateReset2:ye,inflateResetKeep:ke,inflateInit:t=>xe(t,15),inflateInit2:xe,inflate:(t,e)=>{let a,i,n,s,r,o,l,h,d,_,f,c,u,w,m,b,g,p,k,v,y,x,z=0;const A=new Uint8Array(4);let E,R;const Z=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(pe(t)||!t.output||!t.input&&0!==t.avail_in)return _e;a=t.state,16191===a.mode&&(a.mode=16192),r=t.next_out,n=t.output,l=t.avail_out,s=t.next_in,i=t.input,o=t.avail_in,h=a.hold,d=a.bits,_=o,f=l,x=le;t:for(;;)switch(a.mode){case 16180:if(0===a.wrap){a.mode=16192;break}for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(2&a.wrap&&35615===h){0===a.wbits&&(a.wbits=15),a.check=0,A[0]=255&h,A[1]=h>>>8&255,a.check=L(a.check,A,2,0),h=0,d=0,a.mode=16181;break}if(a.head&&(a.head.done=!1),!(1&a.wrap)||(((255&h)<<8)+(h>>8))%31){t.msg="incorrect header check",a.mode=me;break}if((15&h)!==we){t.msg="unknown compression method",a.mode=me;break}if(h>>>=4,d-=4,y=8+(15&h),0===a.wbits&&(a.wbits=y),y>15||y>a.wbits){t.msg="invalid window size",a.mode=me;break}a.dmax=1<<a.wbits,a.flags=0,t.adler=a.check=1,a.mode=512&h?16189:16191,h=0,d=0;break;case 16181:for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(a.flags=h,(255&a.flags)!==we){t.msg="unknown compression method",a.mode=me;break}if(57344&a.flags){t.msg="unknown header flags set",a.mode=me;break}a.head&&(a.head.text=h>>8&1),512&a.flags&&4&a.wrap&&(A[0]=255&h,A[1]=h>>>8&255,a.check=L(a.check,A,2,0)),h=0,d=0,a.mode=16182;case 16182:for(;d<32;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}a.head&&(a.head.time=h),512&a.flags&&4&a.wrap&&(A[0]=255&h,A[1]=h>>>8&255,A[2]=h>>>16&255,A[3]=h>>>24&255,a.check=L(a.check,A,4,0)),h=0,d=0,a.mode=16183;case 16183:for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}a.head&&(a.head.xflags=255&h,a.head.os=h>>8),512&a.flags&&4&a.wrap&&(A[0]=255&h,A[1]=h>>>8&255,a.check=L(a.check,A,2,0)),h=0,d=0,a.mode=16184;case 16184:if(1024&a.flags){for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}a.length=h,a.head&&(a.head.extra_len=h),512&a.flags&&4&a.wrap&&(A[0]=255&h,A[1]=h>>>8&255,a.check=L(a.check,A,2,0)),h=0,d=0}else a.head&&(a.head.extra=null);a.mode=16185;case 16185:if(1024&a.flags&&(c=a.length,c>o&&(c=o),c&&(a.head&&(y=a.head.extra_len-a.length,a.head.extra||(a.head.extra=new Uint8Array(a.head.extra_len)),a.head.extra.set(i.subarray(s,s+c),y)),512&a.flags&&4&a.wrap&&(a.check=L(a.check,i,c,s)),o-=c,s+=c,a.length-=c),a.length))break t;a.length=0,a.mode=16186;case 16186:if(2048&a.flags){if(0===o)break t;c=0;do{y=i[s+c++],a.head&&y&&a.length<65536&&(a.head.name+=String.fromCharCode(y))}while(y&&c<o);if(512&a.flags&&4&a.wrap&&(a.check=L(a.check,i,c,s)),o-=c,s+=c,y)break t}else a.head&&(a.head.name=null);a.length=0,a.mode=16187;case 16187:if(4096&a.flags){if(0===o)break t;c=0;do{y=i[s+c++],a.head&&y&&a.length<65536&&(a.head.comment+=String.fromCharCode(y))}while(y&&c<o);if(512&a.flags&&4&a.wrap&&(a.check=L(a.check,i,c,s)),o-=c,s+=c,y)break t}else a.head&&(a.head.comment=null);a.mode=16188;case 16188:if(512&a.flags){for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(4&a.wrap&&h!==(65535&a.check)){t.msg="header crc mismatch",a.mode=me;break}h=0,d=0}a.head&&(a.head.hcrc=a.flags>>9&1,a.head.done=!0),t.adler=a.check=0,a.mode=16191;break;case 16189:for(;d<32;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}t.adler=a.check=be(h),h=0,d=0,a.mode=16190;case 16190:if(0===a.havedict)return t.next_out=r,t.avail_out=l,t.next_in=s,t.avail_in=o,a.hold=h,a.bits=d,de;t.adler=a.check=1,a.mode=16191;case 16191:if(e===re||e===oe)break t;case 16192:if(a.last){h>>>=7&d,d-=7&d,a.mode=16206;break}for(;d<3;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}switch(a.last=1&h,h>>>=1,d-=1,3&h){case 0:a.mode=16193;break;case 1:if(Re(a),a.mode=16199,e===oe){h>>>=2,d-=2;break t}break;case 2:a.mode=16196;break;case 3:t.msg="invalid block type",a.mode=me}h>>>=2,d-=2;break;case 16193:for(h>>>=7&d,d-=7&d;d<32;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if((65535&h)!=(h>>>16^65535)){t.msg="invalid stored block lengths",a.mode=me;break}if(a.length=65535&h,h=0,d=0,a.mode=16194,e===oe)break t;case 16194:a.mode=16195;case 16195:if(c=a.length,c){if(c>o&&(c=o),c>l&&(c=l),0===c)break t;n.set(i.subarray(s,s+c),r),o-=c,s+=c,l-=c,r+=c,a.length-=c;break}a.mode=16191;break;case 16196:for(;d<14;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(a.nlen=257+(31&h),h>>>=5,d-=5,a.ndist=1+(31&h),h>>>=5,d-=5,a.ncode=4+(15&h),h>>>=4,d-=4,a.nlen>286||a.ndist>30){t.msg="too many length or distance symbols",a.mode=me;break}a.have=0,a.mode=16197;case 16197:for(;a.have<a.ncode;){for(;d<3;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}a.lens[Z[a.have++]]=7&h,h>>>=3,d-=3}for(;a.have<19;)a.lens[Z[a.have++]]=0;if(a.lencode=a.lendyn,a.lenbits=7,E={bits:a.lenbits},x=ne(0,a.lens,0,19,a.lencode,0,a.work,E),a.lenbits=E.bits,x){t.msg="invalid code lengths set",a.mode=me;break}a.have=0,a.mode=16198;case 16198:for(;a.have<a.nlen+a.ndist;){for(;z=a.lencode[h&(1<<a.lenbits)-1],m=z>>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(g<16)h>>>=m,d-=m,a.lens[a.have++]=g;else{if(16===g){for(R=m+2;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(h>>>=m,d-=m,0===a.have){t.msg="invalid bit length repeat",a.mode=me;break}y=a.lens[a.have-1],c=3+(3&h),h>>>=2,d-=2}else if(17===g){for(R=m+3;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}h>>>=m,d-=m,y=0,c=3+(7&h),h>>>=3,d-=3}else{for(R=m+7;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}h>>>=m,d-=m,y=0,c=11+(127&h),h>>>=7,d-=7}if(a.have+c>a.nlen+a.ndist){t.msg="invalid bit length repeat",a.mode=me;break}for(;c--;)a.lens[a.have++]=y}}if(a.mode===me)break;if(0===a.lens[256]){t.msg="invalid code -- missing end-of-block",a.mode=me;break}if(a.lenbits=9,E={bits:a.lenbits},x=ne(1,a.lens,0,a.nlen,a.lencode,0,a.work,E),a.lenbits=E.bits,x){t.msg="invalid literal/lengths set",a.mode=me;break}if(a.distbits=6,a.distcode=a.distdyn,E={bits:a.distbits},x=ne(2,a.lens,a.nlen,a.ndist,a.distcode,0,a.work,E),a.distbits=E.bits,x){t.msg="invalid distances set",a.mode=me;break}if(a.mode=16199,e===oe)break t;case 16199:a.mode=16200;case 16200:if(o>=6&&l>=258){t.next_out=r,t.avail_out=l,t.next_in=s,t.avail_in=o,a.hold=h,a.bits=d,$t(t,f),r=t.next_out,n=t.output,l=t.avail_out,s=t.next_in,i=t.input,o=t.avail_in,h=a.hold,d=a.bits,16191===a.mode&&(a.back=-1);break}for(a.back=0;z=a.lencode[h&(1<<a.lenbits)-1],m=z>>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(b&&0==(240&b)){for(p=m,k=b,v=g;z=a.lencode[v+((h&(1<<p+k)-1)>>p)],m=z>>>24,b=z>>>16&255,g=65535&z,!(p+m<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}h>>>=p,d-=p,a.back+=p}if(h>>>=m,d-=m,a.back+=m,a.length=g,0===b){a.mode=16205;break}if(32&b){a.back=-1,a.mode=16191;break}if(64&b){t.msg="invalid literal/length code",a.mode=me;break}a.extra=15&b,a.mode=16201;case 16201:if(a.extra){for(R=a.extra;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}a.length+=h&(1<<a.extra)-1,h>>>=a.extra,d-=a.extra,a.back+=a.extra}a.was=a.length,a.mode=16202;case 16202:for(;z=a.distcode[h&(1<<a.distbits)-1],m=z>>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(0==(240&b)){for(p=m,k=b,v=g;z=a.distcode[v+((h&(1<<p+k)-1)>>p)],m=z>>>24,b=z>>>16&255,g=65535&z,!(p+m<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}h>>>=p,d-=p,a.back+=p}if(h>>>=m,d-=m,a.back+=m,64&b){t.msg="invalid distance code",a.mode=me;break}a.offset=g,a.extra=15&b,a.mode=16203;case 16203:if(a.extra){for(R=a.extra;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}a.offset+=h&(1<<a.extra)-1,h>>>=a.extra,d-=a.extra,a.back+=a.extra}if(a.offset>a.dmax){t.msg="invalid distance too far back",a.mode=me;break}a.mode=16204;case 16204:if(0===l)break t;if(c=f-l,a.offset>c){if(c=a.offset-c,c>a.whave&&a.sane){t.msg="invalid distance too far back",a.mode=me;break}c>a.wnext?(c-=a.wnext,u=a.wsize-c):u=a.wnext-c,c>a.length&&(c=a.length),w=a.window}else w=n,u=r-a.offset,c=a.length;c>l&&(c=l),l-=c,a.length-=c;do{n[r++]=w[u++]}while(--c);0===a.length&&(a.mode=16200);break;case 16205:if(0===l)break t;n[r++]=a.length,l--,a.mode=16200;break;case 16206:if(a.wrap){for(;d<32;){if(0===o)break t;o--,h|=i[s++]<<d,d+=8}if(f-=l,t.total_out+=f,a.total+=f,4&a.wrap&&f&&(t.adler=a.check=a.flags?L(a.check,n,f,r-f):N(a.check,n,f,r-f)),f=l,4&a.wrap&&(a.flags?h:be(h))!==a.check){t.msg="incorrect data check",a.mode=me;break}h=0,d=0}a.mode=16207;case 16207:if(a.wrap&&a.flags){for(;d<32;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(4&a.wrap&&h!==(4294967295&a.total)){t.msg="incorrect length check",a.mode=me;break}h=0,d=0}a.mode=16208;case 16208:x=he;break t;case me:x=fe;break t;case 16210:return ce;default:return _e}return t.next_out=r,t.avail_out=l,t.next_in=s,t.avail_in=o,a.hold=h,a.bits=d,(a.wsize||f!==t.avail_out&&a.mode<me&&(a.mode<16206||e!==se))&&Ze(t,t.output,t.next_out,f-t.avail_out),_-=t.avail_in,f-=t.avail_out,t.total_in+=_,t.total_out+=f,a.total+=f,4&a.wrap&&f&&(t.adler=a.check=a.flags?L(a.check,n,f,t.next_out-f):N(a.check,n,f,t.next_out-f)),t.data_type=a.bits+(a.last?64:0)+(16191===a.mode?128:0)+(16199===a.mode||16194===a.mode?256:0),(0===_&&0===f||e===se)&&x===le&&(x=ue),x},inflateEnd:t=>{if(pe(t))return _e;let e=t.state;return e.window&&(e.window=null),t.state=null,le},inflateGetHeader:(t,e)=>{if(pe(t))return _e;const a=t.state;return 0==(2&a.wrap)?_e:(a.head=e,e.done=!1,le)},inflateSetDictionary:(t,e)=>{const a=e.length;let i,n,s;return pe(t)?_e:(i=t.state,0!==i.wrap&&16190!==i.mode?_e:16190===i.mode&&(n=1,n=N(n,e,a,0),n!==i.check)?fe:(s=Ze(t,e,a,a),s?(i.mode=16210,ce):(i.havedict=1,le)))},inflateInfo:"pako inflate (from Nodeca project)"};var Ue=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1};const De=Object.prototype.toString,{Z_NO_FLUSH:Oe,Z_FINISH:Te,Z_OK:Ne,Z_STREAM_END:Fe,Z_NEED_DICT:Le,Z_STREAM_ERROR:Ie,Z_DATA_ERROR:Be,Z_MEM_ERROR:Ce}=B;function He(t){this.options=Ot({chunkSize:65536,windowBits:15,to:""},t||{});const e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&0==(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Ct,this.strm.avail_out=0;let a=Se.inflateInit2(this.strm,e.windowBits);if(a!==Ne)throw new Error(I[a]);if(this.header=new Ue,Se.inflateGetHeader(this.strm,this.header),e.dictionary&&("string"==typeof e.dictionary?e.dictionary=Lt(e.dictionary):"[object ArrayBuffer]"===De.call(e.dictionary)&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(a=Se.inflateSetDictionary(this.strm,e.dictionary),a!==Ne)))throw new Error(I[a])}He.prototype.push=function(t,e){const a=this.strm,i=this.options.chunkSize,n=this.options.dictionary;let s,r,o;if(this.ended)return!1;for(r=e===~~e?e:!0===e?Te:Oe,"[object ArrayBuffer]"===De.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;;){for(0===a.avail_out&&(a.output=new Uint8Array(i),a.next_out=0,a.avail_out=i),s=Se.inflate(a,r),s===Le&&n&&(s=Se.inflateSetDictionary(a,n),s===Ne?s=Se.inflate(a,r):s===Be&&(s=Le));a.avail_in>0&&s===Fe&&a.state.wrap>0&&0!==t[a.next_in];)Se.inflateReset(a),s=Se.inflate(a,r);switch(s){case Ie:case Be:case Le:case Ce:return this.onEnd(s),this.ended=!0,!1}if(o=a.avail_out,a.next_out&&(0===a.avail_out||s===Fe))if("string"===this.options.to){let t=Bt(a.output,a.next_out),e=a.next_out-t,n=It(a.output,t);a.next_out=e,a.avail_out=i-e,e&&a.output.set(a.output.subarray(t,t+e),0),this.onData(n)}else this.onData(a.output.length===a.next_out?a.output:a.output.subarray(0,a.next_out));if(s!==Ne||0!==o){if(s===Fe)return s=Se.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(0===a.avail_in)break}}return!0},He.prototype.onData=function(t){this.chunks.push(t)},He.prototype.onEnd=function(t){t===Ne&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=Tt(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};const{Deflate:Me,deflate:je,deflateRaw:Ke,gzip:Pe}=Vt;var Ye=Me,Ge=B;const Xe=new class{constructor(){this.added=0,this.init()}init(){this.added=0,this.deflate=new Ye,this.deflate.push("[",Ge.Z_NO_FLUSH)}addEvent(t){if(!t)throw new Error("Adding invalid event");const e=this.added>0?",":"";this.deflate.push(e+JSON.stringify(t),Ge.Z_SYNC_FLUSH),this.added++}finish(){if(this.deflate.push("]",Ge.Z_FINISH),this.deflate.err)throw this.deflate.err;const t=this.deflate.result;return this.init(),t}},Je={init:()=>(Xe.init(),""),addEvent:t=>Xe.addEvent(t),finish:()=>Xe.finish()};addEventListener("message",(function(t){const e=t.data.method,a=t.data.id,[i]=t.data.args?JSON.parse(t.data.args):[];if(e in Je&&"function"==typeof Je[e])try{const t=Je[e](i);postMessage({id:a,method:e,success:!0,response:t})}catch(t){postMessage({id:a,method:e,success:!1,response:t.message}),console.error(t)}})),postMessage({id:void 0,method:"init",success:!0,response:void 0});`;
3417
+
3372
3418
  /**
3373
- * An event handler to react to breadcrumbs.
3419
+ * Create an event buffer for replays.
3374
3420
  */
3375
- function breadcrumbHandler(type, handlerData) {
3376
- if (type === 'scope') {
3377
- return handleScope(handlerData );
3421
+ function createEventBuffer({ useCompression }) {
3422
+ // eslint-disable-next-line no-restricted-globals
3423
+ if (useCompression && window.Worker) {
3424
+ const workerBlob = new Blob([workerString]);
3425
+ const workerUrl = URL.createObjectURL(workerBlob);
3426
+
3427
+ (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Using compression worker');
3428
+ const worker = new Worker(workerUrl);
3429
+ return new EventBufferProxy(worker);
3378
3430
  }
3379
3431
 
3380
- return handleDom(handlerData );
3432
+ (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Using simple buffer');
3433
+ return new EventBufferArray();
3381
3434
  }
3382
3435
 
3383
3436
  /**
3384
- * Add an event to the event buffer
3437
+ * This proxy will try to use the compression worker, and fall back to use the simple buffer if an error occurs there.
3438
+ * This can happen e.g. if the worker cannot be loaded.
3439
+ * Exported only for testing.
3385
3440
  */
3386
- async function addEvent(
3387
- replay,
3388
- event,
3389
- isCheckout,
3390
- ) {
3391
- if (!replay.eventBuffer) {
3392
- // This implies that `_isEnabled` is false
3393
- return null;
3441
+ class EventBufferProxy {
3442
+
3443
+ constructor(worker) {
3444
+ this._fallback = new EventBufferArray();
3445
+ this._compression = new EventBufferCompressionWorker(worker);
3446
+ this._used = this._fallback;
3447
+
3448
+ void this._ensureWorkerIsLoaded();
3394
3449
  }
3395
3450
 
3396
- if (replay.isPaused()) {
3397
- // Do not add to event buffer when recording is paused
3398
- return null;
3451
+ /** @inheritDoc */
3452
+ get pendingLength() {
3453
+ return this._used.pendingLength;
3399
3454
  }
3400
3455
 
3401
- // TODO: sadness -- we will want to normalize timestamps to be in ms -
3402
- // requires coordination with frontend
3403
- const isMs = event.timestamp > 9999999999;
3404
- const timestampInMs = isMs ? event.timestamp : event.timestamp * 1000;
3456
+ /** @inheritDoc */
3457
+ get pendingEvents() {
3458
+ return this._used.pendingEvents;
3459
+ }
3405
3460
 
3406
- // Throw out events that happen more than 5 minutes ago. This can happen if
3407
- // page has been left open and idle for a long period of time and user
3408
- // comes back to trigger a new session. The performance entries rely on
3409
- // `performance.timeOrigin`, which is when the page first opened.
3410
- if (timestampInMs + SESSION_IDLE_DURATION < new Date().getTime()) {
3411
- return null;
3461
+ /** @inheritDoc */
3462
+ destroy() {
3463
+ this._fallback.destroy();
3464
+ this._compression.destroy();
3412
3465
  }
3413
3466
 
3414
- // Only record earliest event if a new session was created, otherwise it
3415
- // shouldn't be relevant
3416
- const earliestEvent = replay.getContext().earliestEvent;
3417
- if (replay.session && replay.session.segmentId === 0 && (!earliestEvent || timestampInMs < earliestEvent)) {
3418
- replay.getContext().earliestEvent = timestampInMs;
3467
+ /**
3468
+ * Add an event to the event buffer.
3469
+ *
3470
+ * Returns true if event was successfully added.
3471
+ */
3472
+ addEvent(event, isCheckout) {
3473
+ return this._used.addEvent(event, isCheckout);
3419
3474
  }
3420
3475
 
3421
- return replay.eventBuffer.addEvent(event, isCheckout);
3422
- }
3476
+ /** @inheritDoc */
3477
+ finish() {
3478
+ return this._used.finish();
3479
+ }
3423
3480
 
3424
- /**
3425
- * Create a "span" for each performance entry. The parent transaction is `this.replayEvent`.
3426
- */
3427
- function createPerformanceSpans(
3428
- replay,
3429
- entries,
3430
- ) {
3431
- return entries.map(({ type, start, end, name, data }) =>
3432
- addEvent(replay, {
3433
- type: EventType.Custom,
3434
- timestamp: start,
3435
- data: {
3436
- tag: 'performanceSpan',
3437
- payload: {
3438
- op: type,
3439
- description: name,
3440
- startTimestamp: start,
3441
- endTimestamp: end,
3442
- data,
3443
- },
3444
- },
3445
- }),
3446
- );
3447
- }
3481
+ /** Ensure the worker has loaded. */
3482
+ async _ensureWorkerIsLoaded() {
3483
+ try {
3484
+ await this._compression.ensureReady();
3485
+ } catch (error) {
3486
+ // If the worker fails to load, we fall back to the simple buffer.
3487
+ // Nothing more to do from our side here
3488
+ (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Failed to load the compression worker, falling back to simple buffer');
3489
+ return;
3490
+ }
3448
3491
 
3449
- /**
3450
- * Check whether a given request URL should be filtered out.
3451
- */
3452
- function shouldFilterRequest(replay, url) {
3453
- // If we enabled the `traceInternals` experiment, we want to trace everything
3454
- if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && replay.getOptions()._experiments.traceInternals) {
3455
- return false;
3456
- }
3492
+ // Compression worker is ready, we can use it
3493
+ // Now we need to switch over the array buffer to the compression worker
3494
+ const addEventPromises = [];
3495
+ for (const event of this._fallback.pendingEvents) {
3496
+ addEventPromises.push(this._compression.addEvent(event));
3497
+ }
3457
3498
 
3458
- return !_isSentryRequest(url);
3459
- }
3499
+ // We switch over to the compression buffer immediately - any further events will be added
3500
+ // after the previously buffered ones
3501
+ this._used = this._compression;
3460
3502
 
3461
- /**
3462
- * Checks wether a given URL belongs to the configured Sentry DSN.
3463
- */
3464
- function _isSentryRequest(url) {
3465
- const client = getCurrentHub().getClient();
3466
- const dsn = client && client.getDsn();
3467
- return dsn ? url.includes(dsn.host) : false;
3503
+ // Wait for original events to be re-added before resolving
3504
+ await Promise.all(addEventPromises);
3505
+ }
3468
3506
  }
3469
3507
 
3470
- /** only exported for tests */
3471
- function handleFetch(handlerData) {
3472
- if (!handlerData.endTimestamp) {
3473
- return null;
3474
- }
3508
+ class EventBufferArray {
3475
3509
 
3476
- const { startTimestamp, endTimestamp, fetchData, response } = handlerData;
3510
+ constructor() {
3511
+ this._events = [];
3512
+ }
3477
3513
 
3478
- return {
3479
- type: 'resource.fetch',
3480
- start: startTimestamp / 1000,
3481
- end: endTimestamp / 1000,
3482
- name: fetchData.url,
3483
- data: {
3484
- method: fetchData.method,
3485
- statusCode: response.status,
3486
- },
3487
- };
3488
- }
3514
+ get pendingLength() {
3515
+ return this._events.length;
3516
+ }
3489
3517
 
3490
- /**
3491
- * Returns a listener to be added to `addInstrumentationHandler('fetch', listener)`.
3492
- */
3493
- function handleFetchSpanListener(replay) {
3494
- return (handlerData) => {
3495
- if (!replay.isEnabled()) {
3496
- return;
3497
- }
3518
+ /**
3519
+ * Returns the raw events that are buffered. In `EventBufferArray`, this is the
3520
+ * same as `this._events`.
3521
+ */
3522
+ get pendingEvents() {
3523
+ return this._events;
3524
+ }
3498
3525
 
3499
- const result = handleFetch(handlerData);
3526
+ destroy() {
3527
+ this._events = [];
3528
+ }
3500
3529
 
3501
- if (result === null) {
3530
+ async addEvent(event, isCheckout) {
3531
+ if (isCheckout) {
3532
+ this._events = [event];
3502
3533
  return;
3503
3534
  }
3504
3535
 
3505
- if (shouldFilterRequest(replay, result.name)) {
3506
- return;
3507
- }
3536
+ this._events.push(event);
3537
+ return;
3538
+ }
3508
3539
 
3509
- replay.addUpdate(() => {
3510
- createPerformanceSpans(replay, [result]);
3511
- // Returning true will cause `addUpdate` to not flush
3512
- // We do not want network requests to cause a flush. This will prevent
3513
- // recurring/polling requests from keeping the replay session alive.
3514
- return true;
3540
+ finish() {
3541
+ return new Promise(resolve => {
3542
+ // Make a copy of the events array reference and immediately clear the
3543
+ // events member so that we do not lose new events while uploading
3544
+ // attachment.
3545
+ const eventsRet = this._events;
3546
+ this._events = [];
3547
+ resolve(JSON.stringify(eventsRet));
3515
3548
  });
3516
- };
3517
- }
3518
-
3519
- /**
3520
- * Returns true if we think the given event is an error originating inside of rrweb.
3521
- */
3522
- function isRrwebError(event) {
3523
- if (event.type || !event.exception || !event.exception.values || !event.exception.values.length) {
3524
- return false;
3525
3549
  }
3526
-
3527
- // Check if any exception originates from rrweb
3528
- return event.exception.values.some(exception => {
3529
- if (!exception.stacktrace || !exception.stacktrace.frames || !exception.stacktrace.frames.length) {
3530
- return false;
3531
- }
3532
-
3533
- return exception.stacktrace.frames.some(frame => frame.filename && frame.filename.includes('/rrweb/src/'));
3534
- });
3535
3550
  }
3536
3551
 
3537
3552
  /**
3538
- * Returns a listener to be added to `addGlobalEventProcessor(listener)`.
3553
+ * Event buffer that uses a web worker to compress events.
3554
+ * Exported only for testing.
3539
3555
  */
3540
- function handleGlobalEventListener(replay) {
3541
- return (event) => {
3542
- // Do not apply replayId to the root event
3543
- if (event.type === REPLAY_EVENT_NAME) {
3544
- // Replays have separate set of breadcrumbs, do not include breadcrumbs
3545
- // from core SDK
3546
- delete event.breadcrumbs;
3547
- return event;
3548
- }
3549
-
3550
- // Unless `captureExceptions` is enabled, we want to ignore errors coming from rrweb
3551
- // As there can be a bunch of stuff going wrong in internals there, that we don't want to bubble up to users
3552
- if (isRrwebError(event) && !replay.getOptions()._experiments.captureExceptions) {
3553
- (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Ignoring error from rrweb internals', event);
3554
- return null;
3555
- }
3556
-
3557
- // Only tag transactions with replayId if not waiting for an error
3558
- // @ts-ignore private
3559
- if (!event.type || replay.recordingMode === 'session') {
3560
- event.tags = { ...event.tags, replayId: replay.getSessionId() };
3561
- }
3562
-
3563
- // Collect traceIds in _context regardless of `recordingMode` - if it's true,
3564
- // _context gets cleared on every checkout
3565
- if (event.type === 'transaction' && event.contexts && event.contexts.trace && event.contexts.trace.trace_id) {
3566
- replay.getContext().traceIds.add(event.contexts.trace.trace_id );
3567
- return event;
3568
- }
3569
-
3570
- // no event type means error
3571
- if (!event.type) {
3572
- replay.getContext().errorIds.add(event.event_id );
3573
- }
3574
-
3575
- if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && replay.getOptions()._experiments.traceInternals) {
3576
- const exc = getEventExceptionValues(event);
3577
- addInternalBreadcrumb({
3578
- message: `Tagging event (${event.event_id}) - ${event.message} - ${exc.type}: ${exc.value}`,
3579
- });
3580
- }
3581
-
3582
- // Need to be very careful that this does not cause an infinite loop
3583
- if (
3584
- replay.recordingMode === 'error' &&
3585
- event.exception &&
3586
- event.message !== UNABLE_TO_SEND_REPLAY // ignore this error because otherwise we could loop indefinitely with trying to capture replay and failing
3587
- ) {
3588
- setTimeout(async () => {
3589
- // Allow flush to complete before resuming as a session recording, otherwise
3590
- // the checkout from `startRecording` may be included in the payload.
3591
- // Prefer to keep the error replay as a separate (and smaller) segment
3592
- // than the session replay.
3593
- await replay.flushImmediate();
3594
-
3595
- if (replay.stopRecording()) {
3596
- // Reset all "capture on error" configuration before
3597
- // starting a new recording
3598
- replay.recordingMode = 'session';
3599
- replay.startRecording();
3600
- }
3601
- });
3602
- }
3556
+ class EventBufferCompressionWorker {
3557
+ /**
3558
+ * Keeps track of the list of events since the last flush that have not been compressed.
3559
+ * For example, page is reloaded and a flush attempt is made, but
3560
+ * `finish()` (and thus the flush), does not complete.
3561
+ */
3562
+ __init() {this._pendingEvents = [];}
3603
3563
 
3604
- return event;
3605
- };
3606
- }
3564
+ __init2() {this._eventBufferItemLength = 0;}
3565
+ __init3() {this._id = 0;}
3607
3566
 
3608
- function addInternalBreadcrumb(arg) {
3609
- const { category, level, message, ...rest } = arg;
3567
+ constructor(worker) {EventBufferCompressionWorker.prototype.__init.call(this);EventBufferCompressionWorker.prototype.__init2.call(this);EventBufferCompressionWorker.prototype.__init3.call(this);
3568
+ this._worker = worker;
3569
+ }
3610
3570
 
3611
- addBreadcrumb({
3612
- category: category || 'console',
3613
- level: level || 'debug',
3614
- message: `[debug]: ${message}`,
3615
- ...rest,
3616
- });
3617
- }
3571
+ /**
3572
+ * The number of raw events that are buffered. This may not be the same as
3573
+ * the number of events that have been compresed in the worker because
3574
+ * `addEvent` is async.
3575
+ */
3576
+ get pendingLength() {
3577
+ return this._eventBufferItemLength;
3578
+ }
3618
3579
 
3619
- function getEventExceptionValues(event) {
3620
- return {
3621
- type: 'Unknown',
3622
- value: 'n/a',
3623
- ...(event.exception && event.exception.values && event.exception.values[0]),
3624
- };
3625
- }
3580
+ /**
3581
+ * Returns a list of the raw recording events that are being compressed.
3582
+ */
3583
+ get pendingEvents() {
3584
+ return this._pendingEvents;
3585
+ }
3626
3586
 
3627
- function handleHistory(handlerData) {
3628
- const { from, to } = handlerData;
3587
+ /**
3588
+ * Ensure the worker is ready (or not).
3589
+ * This will either resolve when the worker is ready, or reject if an error occured.
3590
+ */
3591
+ ensureReady() {
3592
+ return new Promise((resolve, reject) => {
3593
+ this._worker.addEventListener(
3594
+ 'message',
3595
+ ({ data }) => {
3596
+ if (data.success) {
3597
+ resolve();
3598
+ } else {
3599
+ reject();
3600
+ }
3601
+ },
3602
+ { once: true },
3603
+ );
3629
3604
 
3630
- const now = new Date().getTime() / 1000;
3605
+ this._worker.addEventListener(
3606
+ 'error',
3607
+ error => {
3608
+ reject(error);
3609
+ },
3610
+ { once: true },
3611
+ );
3612
+ });
3613
+ }
3631
3614
 
3632
- return {
3633
- type: 'navigation.push',
3634
- start: now,
3635
- end: now,
3636
- name: to,
3637
- data: {
3638
- previous: from,
3639
- },
3640
- };
3641
- }
3615
+ /**
3616
+ * Destroy the event buffer.
3617
+ */
3618
+ destroy() {
3619
+ (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Destroying compression worker');
3620
+ this._worker.terminate();
3621
+ }
3642
3622
 
3643
- /**
3644
- * Returns a listener to be added to `addInstrumentationHandler('history', listener)`.
3645
- */
3646
- function handleHistorySpanListener(replay) {
3647
- return (handlerData) => {
3648
- if (!replay.isEnabled()) {
3649
- return;
3623
+ /**
3624
+ * Add an event to the event buffer.
3625
+ *
3626
+ * Returns true if event was successfuly received and processed by worker.
3627
+ */
3628
+ async addEvent(event, isCheckout) {
3629
+ if (isCheckout) {
3630
+ // This event is a checkout, make sure worker buffer is cleared before
3631
+ // proceeding.
3632
+ await this._postMessage({
3633
+ id: this._getAndIncrementId(),
3634
+ method: 'init',
3635
+ args: [],
3636
+ });
3650
3637
  }
3651
3638
 
3652
- const result = handleHistory(handlerData);
3653
-
3654
- if (result === null) {
3655
- return;
3639
+ // Don't store checkout events in `_pendingEvents` because they are too large
3640
+ if (!isCheckout) {
3641
+ this._pendingEvents.push(event);
3656
3642
  }
3657
3643
 
3658
- // Need to collect visited URLs
3659
- replay.getContext().urls.push(result.name);
3660
- replay.triggerUserActivity();
3644
+ return this._sendEventToWorker(event);
3645
+ }
3661
3646
 
3662
- replay.addUpdate(() => {
3663
- createPerformanceSpans(replay, [result]);
3664
- // Returning false to flush
3665
- return false;
3666
- });
3667
- };
3668
- }
3647
+ /**
3648
+ * Finish the event buffer and return the compressed data.
3649
+ */
3650
+ finish() {
3651
+ return this._finishRequest(this._getAndIncrementId());
3652
+ }
3669
3653
 
3670
- // From sentry-javascript
3671
- // e.g. https://github.com/getsentry/sentry-javascript/blob/c7fc025bf9fa8c073fdb56351808ce53909fbe45/packages/utils/src/instrument.ts#L180
3654
+ /**
3655
+ * Post message to worker and wait for response before resolving promise.
3656
+ */
3657
+ _postMessage({ id, method, args }) {
3658
+ return new Promise((resolve, reject) => {
3659
+ // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
3660
+ const listener = ({ data }) => {
3661
+ if (data.method !== method) {
3662
+ return;
3663
+ }
3672
3664
 
3673
- function handleXhr(handlerData) {
3674
- if (handlerData.xhr.__sentry_own_request__) {
3675
- // Taken from sentry-javascript
3676
- // Only capture non-sentry requests
3677
- return null;
3678
- }
3665
+ // There can be multiple listeners for a single method, the id ensures
3666
+ // that the response matches the caller.
3667
+ if (data.id !== id) {
3668
+ return;
3669
+ }
3679
3670
 
3680
- if (handlerData.startTimestamp) {
3681
- // TODO: See if this is still needed
3682
- handlerData.xhr.__sentry_xhr__ = handlerData.xhr.__sentry_xhr__ || {};
3683
- handlerData.xhr.__sentry_xhr__.startTimestamp = handlerData.startTimestamp;
3684
- }
3671
+ // At this point, we'll always want to remove listener regardless of result status
3672
+ this._worker.removeEventListener('message', listener);
3685
3673
 
3686
- if (!handlerData.endTimestamp) {
3687
- return null;
3688
- }
3674
+ if (!data.success) {
3675
+ // TODO: Do some error handling, not sure what
3676
+ (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('[Replay]', data.response);
3689
3677
 
3690
- const { method, url, status_code: statusCode } = handlerData.xhr.__sentry_xhr__ || {};
3678
+ reject(new Error('Error in compression worker'));
3679
+ return;
3680
+ }
3691
3681
 
3692
- if (url === undefined) {
3693
- return null;
3682
+ resolve(data.response);
3683
+ };
3684
+
3685
+ let stringifiedArgs;
3686
+ try {
3687
+ stringifiedArgs = JSON.stringify(args);
3688
+ } catch (err) {
3689
+ (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('[Replay] Error when trying to stringify args', err);
3690
+ stringifiedArgs = '[]';
3691
+ }
3692
+
3693
+ // Note: we can't use `once` option because it's possible it needs to
3694
+ // listen to multiple messages
3695
+ this._worker.addEventListener('message', listener);
3696
+ this._worker.postMessage({ id, method, args: stringifiedArgs });
3697
+ });
3694
3698
  }
3695
3699
 
3696
- const timestamp = handlerData.xhr.__sentry_xhr__
3697
- ? handlerData.xhr.__sentry_xhr__.startTimestamp || 0
3698
- : handlerData.endTimestamp;
3700
+ /**
3701
+ * Send the event to the worker.
3702
+ */
3703
+ async _sendEventToWorker(event) {
3704
+ const promise = this._postMessage({
3705
+ id: this._getAndIncrementId(),
3706
+ method: 'addEvent',
3707
+ args: [event],
3708
+ });
3699
3709
 
3700
- return {
3701
- type: 'resource.xhr',
3702
- name: url,
3703
- start: timestamp / 1000,
3704
- end: handlerData.endTimestamp / 1000,
3705
- data: {
3706
- method,
3707
- statusCode,
3708
- },
3709
- };
3710
- }
3710
+ // XXX: See note in `get length()`
3711
+ this._eventBufferItemLength++;
3711
3712
 
3712
- /**
3713
- * Returns a listener to be added to `addInstrumentationHandler('xhr', listener)`.
3714
- */
3715
- function handleXhrSpanListener(replay) {
3716
- return (handlerData) => {
3717
- if (!replay.isEnabled()) {
3718
- return;
3719
- }
3713
+ return promise;
3714
+ }
3720
3715
 
3721
- const result = handleXhr(handlerData);
3716
+ /**
3717
+ * Finish the request and return the compressed data from the worker.
3718
+ */
3719
+ async _finishRequest(id) {
3720
+ const promise = this._postMessage({ id, method: 'finish', args: [] });
3722
3721
 
3723
- if (result === null) {
3724
- return;
3725
- }
3722
+ // XXX: See note in `get length()`
3723
+ this._eventBufferItemLength = 0;
3726
3724
 
3727
- if (shouldFilterRequest(replay, result.name)) {
3728
- return;
3729
- }
3725
+ await promise;
3730
3726
 
3731
- replay.addUpdate(() => {
3732
- createPerformanceSpans(replay, [result]);
3733
- // Returning true will cause `addUpdate` to not flush
3734
- // We do not want network requests to cause a flush. This will prevent
3735
- // recurring/polling requests from keeping the replay session alive.
3736
- return true;
3737
- });
3738
- };
3739
- }
3727
+ this._pendingEvents = [];
3740
3728
 
3741
- const NAVIGATION_ENTRY_KEYS = [
3742
- 'name',
3743
- 'type',
3744
- 'startTime',
3745
- 'transferSize',
3746
- 'duration',
3747
- ];
3729
+ return promise;
3730
+ }
3748
3731
 
3749
- function isNavigationEntryEqual(a) {
3750
- return function (b) {
3751
- return NAVIGATION_ENTRY_KEYS.every(key => a[key] === b[key]);
3752
- };
3732
+ /** Get the current ID and increment it for the next call. */
3733
+ _getAndIncrementId() {
3734
+ return this._id++;
3735
+ }
3753
3736
  }
3754
3737
 
3755
3738
  /**
3756
- * There are some difficulties diagnosing why there are duplicate navigation
3757
- * entries. We've witnessed several intermittent results:
3758
- * - duplicate entries have duration = 0
3759
- * - duplicate entries are the same object reference
3760
- * - none of the above
3761
- *
3762
- * Compare the values of several keys to determine if the entries are duplicates or not.
3739
+ * Given an initial timestamp and an expiry duration, checks to see if current
3740
+ * time should be considered as expired.
3763
3741
  */
3764
- // TODO (high-prio): Figure out wth is returned here
3765
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
3766
- function dedupePerformanceEntries(
3767
- currentList,
3768
- newList,
3742
+ function isExpired(
3743
+ initialTime,
3744
+ expiry,
3745
+ targetTime = +new Date(),
3769
3746
  ) {
3770
- // Partition `currentList` into 3 different lists based on entryType
3771
- const [existingNavigationEntries, existingLcpEntries, existingEntries] = currentList.reduce(
3772
- (acc, entry) => {
3773
- if (entry.entryType === 'navigation') {
3774
- acc[0].push(entry );
3775
- } else if (entry.entryType === 'largest-contentful-paint') {
3776
- acc[1].push(entry );
3777
- } else {
3778
- acc[2].push(entry);
3779
- }
3780
- return acc;
3781
- },
3782
- [[], [], []],
3783
- );
3747
+ // Always expired if < 0
3748
+ if (initialTime === null || expiry === undefined || expiry < 0) {
3749
+ return true;
3750
+ }
3784
3751
 
3785
- const newEntries = [];
3786
- const newNavigationEntries = [];
3787
- let newLcpEntry = existingLcpEntries.length
3788
- ? existingLcpEntries[existingLcpEntries.length - 1] // Take the last element as list is sorted
3789
- : undefined;
3752
+ // Never expires if == 0
3753
+ if (expiry === 0) {
3754
+ return false;
3755
+ }
3790
3756
 
3791
- newList.forEach(entry => {
3792
- if (entry.entryType === 'largest-contentful-paint') {
3793
- // We want the latest LCP event only
3794
- if (!newLcpEntry || newLcpEntry.startTime < entry.startTime) {
3795
- newLcpEntry = entry;
3796
- }
3797
- return;
3798
- }
3757
+ return initialTime + expiry <= targetTime;
3758
+ }
3799
3759
 
3800
- if (entry.entryType === 'navigation') {
3801
- const navigationEntry = entry ;
3760
+ /**
3761
+ * Checks to see if session is expired
3762
+ */
3763
+ function isSessionExpired(session, idleTimeout, targetTime = +new Date()) {
3764
+ return (
3765
+ // First, check that maximum session length has not been exceeded
3766
+ isExpired(session.started, MAX_SESSION_LIFE, targetTime) ||
3767
+ // check that the idle timeout has not been exceeded (i.e. user has
3768
+ // performed an action within the last `idleTimeout` ms)
3769
+ isExpired(session.lastActivity, idleTimeout, targetTime)
3770
+ );
3771
+ }
3802
3772
 
3803
- // Check if the navigation entry is contained in currentList or newList
3804
- if (
3805
- // Ignore any navigation entries with duration 0, as they are likely duplicates
3806
- entry.duration > 0 &&
3807
- // Ensure new entry does not already exist in existing entries
3808
- !existingNavigationEntries.find(isNavigationEntryEqual(navigationEntry)) &&
3809
- // Ensure new entry does not already exist in new list of navigation entries
3810
- !newNavigationEntries.find(isNavigationEntryEqual(navigationEntry))
3811
- ) {
3812
- newNavigationEntries.push(navigationEntry);
3813
- }
3773
+ /**
3774
+ * Save a session to session storage.
3775
+ */
3776
+ function saveSession(session) {
3777
+ const hasSessionStorage = 'sessionStorage' in WINDOW;
3778
+ if (!hasSessionStorage) {
3779
+ return;
3780
+ }
3814
3781
 
3815
- // Otherwise this navigation entry is considered a duplicate and is thrown away
3816
- return;
3817
- }
3782
+ try {
3783
+ WINDOW.sessionStorage.setItem(REPLAY_SESSION_KEY, JSON.stringify(session));
3784
+ } catch (e) {
3785
+ // Ignore potential SecurityError exceptions
3786
+ }
3787
+ }
3818
3788
 
3819
- newEntries.push(entry);
3820
- });
3789
+ /**
3790
+ * Given a sample rate, returns true if replay should be sampled.
3791
+ *
3792
+ * 1.0 = 100% sampling
3793
+ * 0.0 = 0% sampling
3794
+ */
3795
+ function isSampled(sampleRate) {
3796
+ if (sampleRate === undefined) {
3797
+ return false;
3798
+ }
3821
3799
 
3822
- // Re-combine and sort by startTime
3823
- return [
3824
- ...(newLcpEntry ? [newLcpEntry] : []),
3825
- ...existingNavigationEntries,
3826
- ...existingEntries,
3827
- ...newEntries,
3828
- ...newNavigationEntries,
3829
- ].sort((a, b) => a.startTime - b.startTime);
3800
+ // Math.random() returns a number in range of 0 to 1 (inclusive of 0, but not 1)
3801
+ return Math.random() < sampleRate;
3830
3802
  }
3831
3803
 
3832
3804
  /**
3833
- * Sets up a PerformanceObserver to listen to all performance entry types.
3805
+ * Get a session with defaults & applied sampling.
3834
3806
  */
3835
- function setupPerformanceObserver(replay) {
3836
- const performanceObserverHandler = (list) => {
3837
- // For whatever reason the observer was returning duplicate navigation
3838
- // entries (the other entry types were not duplicated).
3839
- const newPerformanceEntries = dedupePerformanceEntries(
3840
- replay.performanceEvents,
3841
- list.getEntries() ,
3842
- );
3843
- replay.performanceEvents = newPerformanceEntries;
3807
+ function makeSession(session) {
3808
+ const now = new Date().getTime();
3809
+ const id = session.id || uuid4();
3810
+ // Note that this means we cannot set a started/lastActivity of `0`, but this should not be relevant outside of tests.
3811
+ const started = session.started || now;
3812
+ const lastActivity = session.lastActivity || now;
3813
+ const segmentId = session.segmentId || 0;
3814
+ const sampled = session.sampled;
3815
+
3816
+ return {
3817
+ id,
3818
+ started,
3819
+ lastActivity,
3820
+ segmentId,
3821
+ sampled,
3844
3822
  };
3823
+ }
3845
3824
 
3846
- const performanceObserver = new PerformanceObserver(performanceObserverHandler);
3825
+ /**
3826
+ * Get the sampled status for a session based on sample rates & current sampled status.
3827
+ */
3828
+ function getSessionSampleType(sessionSampleRate, errorSampleRate) {
3829
+ return isSampled(sessionSampleRate) ? 'session' : isSampled(errorSampleRate) ? 'error' : false;
3830
+ }
3847
3831
 
3848
- [
3849
- 'element',
3850
- 'event',
3851
- 'first-input',
3852
- 'largest-contentful-paint',
3853
- 'layout-shift',
3854
- 'longtask',
3855
- 'navigation',
3856
- 'paint',
3857
- 'resource',
3858
- ].forEach(type => {
3859
- try {
3860
- performanceObserver.observe({
3861
- type,
3862
- buffered: true,
3863
- });
3864
- } catch (e) {
3865
- // This can throw if an entry type is not supported in the browser.
3866
- // Ignore these errors.
3867
- }
3832
+ /**
3833
+ * Create a new session, which in its current implementation is a Sentry event
3834
+ * that all replays will be saved to as attachments. Currently, we only expect
3835
+ * one of these Sentry events per "replay session".
3836
+ */
3837
+ function createSession({ sessionSampleRate, errorSampleRate, stickySession = false }) {
3838
+ const sampled = getSessionSampleType(sessionSampleRate, errorSampleRate);
3839
+ const session = makeSession({
3840
+ sampled,
3868
3841
  });
3869
3842
 
3870
- return performanceObserver;
3871
- }
3843
+ (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`[Replay] Creating new session: ${session.id}`);
3872
3844
 
3873
- const workerString = `/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */
3874
- function t(t){let e=t.length;for(;--e>=0;)t[e]=0}const e=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),a=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),i=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),n=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),s=new Array(576);t(s);const r=new Array(60);t(r);const o=new Array(512);t(o);const l=new Array(256);t(l);const h=new Array(29);t(h);const d=new Array(30);function _(t,e,a,i,n){this.static_tree=t,this.extra_bits=e,this.extra_base=a,this.elems=i,this.max_length=n,this.has_stree=t&&t.length}let f,c,u;function w(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}t(d);const m=t=>t<256?o[t]:o[256+(t>>>7)],b=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},g=(t,e,a)=>{t.bi_valid>16-a?(t.bi_buf|=e<<t.bi_valid&65535,b(t,t.bi_buf),t.bi_buf=e>>16-t.bi_valid,t.bi_valid+=a-16):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=a)},p=(t,e,a)=>{g(t,a[2*e],a[2*e+1])},k=(t,e)=>{let a=0;do{a|=1&t,t>>>=1,a<<=1}while(--e>0);return a>>>1},v=(t,e,a)=>{const i=new Array(16);let n,s,r=0;for(n=1;n<=15;n++)r=r+a[n-1]<<1,i[n]=r;for(s=0;s<=e;s++){let e=t[2*s+1];0!==e&&(t[2*s]=k(i[e]++,e))}},y=t=>{let e;for(e=0;e<286;e++)t.dyn_ltree[2*e]=0;for(e=0;e<30;e++)t.dyn_dtree[2*e]=0;for(e=0;e<19;e++)t.bl_tree[2*e]=0;t.dyn_ltree[512]=1,t.opt_len=t.static_len=0,t.sym_next=t.matches=0},x=t=>{t.bi_valid>8?b(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},z=(t,e,a,i)=>{const n=2*e,s=2*a;return t[n]<t[s]||t[n]===t[s]&&i[e]<=i[a]},A=(t,e,a)=>{const i=t.heap[a];let n=a<<1;for(;n<=t.heap_len&&(n<t.heap_len&&z(e,t.heap[n+1],t.heap[n],t.depth)&&n++,!z(e,i,t.heap[n],t.depth));)t.heap[a]=t.heap[n],a=n,n<<=1;t.heap[a]=i},E=(t,i,n)=>{let s,r,o,_,f=0;if(0!==t.sym_next)do{s=255&t.pending_buf[t.sym_buf+f++],s+=(255&t.pending_buf[t.sym_buf+f++])<<8,r=t.pending_buf[t.sym_buf+f++],0===s?p(t,r,i):(o=l[r],p(t,o+256+1,i),_=e[o],0!==_&&(r-=h[o],g(t,r,_)),s--,o=m(s),p(t,o,n),_=a[o],0!==_&&(s-=d[o],g(t,s,_)))}while(f<t.sym_next);p(t,256,i)},R=(t,e)=>{const a=e.dyn_tree,i=e.stat_desc.static_tree,n=e.stat_desc.has_stree,s=e.stat_desc.elems;let r,o,l,h=-1;for(t.heap_len=0,t.heap_max=573,r=0;r<s;r++)0!==a[2*r]?(t.heap[++t.heap_len]=h=r,t.depth[r]=0):a[2*r+1]=0;for(;t.heap_len<2;)l=t.heap[++t.heap_len]=h<2?++h:0,a[2*l]=1,t.depth[l]=0,t.opt_len--,n&&(t.static_len-=i[2*l+1]);for(e.max_code=h,r=t.heap_len>>1;r>=1;r--)A(t,a,r);l=s;do{r=t.heap[1],t.heap[1]=t.heap[t.heap_len--],A(t,a,1),o=t.heap[1],t.heap[--t.heap_max]=r,t.heap[--t.heap_max]=o,a[2*l]=a[2*r]+a[2*o],t.depth[l]=(t.depth[r]>=t.depth[o]?t.depth[r]:t.depth[o])+1,a[2*r+1]=a[2*o+1]=l,t.heap[1]=l++,A(t,a,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],((t,e)=>{const a=e.dyn_tree,i=e.max_code,n=e.stat_desc.static_tree,s=e.stat_desc.has_stree,r=e.stat_desc.extra_bits,o=e.stat_desc.extra_base,l=e.stat_desc.max_length;let h,d,_,f,c,u,w=0;for(f=0;f<=15;f++)t.bl_count[f]=0;for(a[2*t.heap[t.heap_max]+1]=0,h=t.heap_max+1;h<573;h++)d=t.heap[h],f=a[2*a[2*d+1]+1]+1,f>l&&(f=l,w++),a[2*d+1]=f,d>i||(t.bl_count[f]++,c=0,d>=o&&(c=r[d-o]),u=a[2*d],t.opt_len+=u*(f+c),s&&(t.static_len+=u*(n[2*d+1]+c)));if(0!==w){do{for(f=l-1;0===t.bl_count[f];)f--;t.bl_count[f]--,t.bl_count[f+1]+=2,t.bl_count[l]--,w-=2}while(w>0);for(f=l;0!==f;f--)for(d=t.bl_count[f];0!==d;)_=t.heap[--h],_>i||(a[2*_+1]!==f&&(t.opt_len+=(f-a[2*_+1])*a[2*_],a[2*_+1]=f),d--)}})(t,e),v(a,h,t.bl_count)},Z=(t,e,a)=>{let i,n,s=-1,r=e[1],o=0,l=7,h=4;for(0===r&&(l=138,h=3),e[2*(a+1)+1]=65535,i=0;i<=a;i++)n=r,r=e[2*(i+1)+1],++o<l&&n===r||(o<h?t.bl_tree[2*n]+=o:0!==n?(n!==s&&t.bl_tree[2*n]++,t.bl_tree[32]++):o<=10?t.bl_tree[34]++:t.bl_tree[36]++,o=0,s=n,0===r?(l=138,h=3):n===r?(l=6,h=3):(l=7,h=4))},S=(t,e,a)=>{let i,n,s=-1,r=e[1],o=0,l=7,h=4;for(0===r&&(l=138,h=3),i=0;i<=a;i++)if(n=r,r=e[2*(i+1)+1],!(++o<l&&n===r)){if(o<h)do{p(t,n,t.bl_tree)}while(0!=--o);else 0!==n?(n!==s&&(p(t,n,t.bl_tree),o--),p(t,16,t.bl_tree),g(t,o-3,2)):o<=10?(p(t,17,t.bl_tree),g(t,o-3,3)):(p(t,18,t.bl_tree),g(t,o-11,7));o=0,s=n,0===r?(l=138,h=3):n===r?(l=6,h=3):(l=7,h=4)}};let U=!1;const D=(t,e,a,i)=>{g(t,0+(i?1:0),3),x(t),b(t,a),b(t,~a),a&&t.pending_buf.set(t.window.subarray(e,e+a),t.pending),t.pending+=a};var O=(t,e,a,i)=>{let o,l,h=0;t.level>0?(2===t.strm.data_type&&(t.strm.data_type=(t=>{let e,a=4093624447;for(e=0;e<=31;e++,a>>>=1)if(1&a&&0!==t.dyn_ltree[2*e])return 0;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return 1;for(e=32;e<256;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0})(t)),R(t,t.l_desc),R(t,t.d_desc),h=(t=>{let e;for(Z(t,t.dyn_ltree,t.l_desc.max_code),Z(t,t.dyn_dtree,t.d_desc.max_code),R(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*n[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e})(t),o=t.opt_len+3+7>>>3,l=t.static_len+3+7>>>3,l<=o&&(o=l)):o=l=a+5,a+4<=o&&-1!==e?D(t,e,a,i):4===t.strategy||l===o?(g(t,2+(i?1:0),3),E(t,s,r)):(g(t,4+(i?1:0),3),((t,e,a,i)=>{let s;for(g(t,e-257,5),g(t,a-1,5),g(t,i-4,4),s=0;s<i;s++)g(t,t.bl_tree[2*n[s]+1],3);S(t,t.dyn_ltree,e-1),S(t,t.dyn_dtree,a-1)})(t,t.l_desc.max_code+1,t.d_desc.max_code+1,h+1),E(t,t.dyn_ltree,t.dyn_dtree)),y(t),i&&x(t)},T={_tr_init:t=>{U||((()=>{let t,n,w,m,b;const g=new Array(16);for(w=0,m=0;m<28;m++)for(h[m]=w,t=0;t<1<<e[m];t++)l[w++]=m;for(l[w-1]=m,b=0,m=0;m<16;m++)for(d[m]=b,t=0;t<1<<a[m];t++)o[b++]=m;for(b>>=7;m<30;m++)for(d[m]=b<<7,t=0;t<1<<a[m]-7;t++)o[256+b++]=m;for(n=0;n<=15;n++)g[n]=0;for(t=0;t<=143;)s[2*t+1]=8,t++,g[8]++;for(;t<=255;)s[2*t+1]=9,t++,g[9]++;for(;t<=279;)s[2*t+1]=7,t++,g[7]++;for(;t<=287;)s[2*t+1]=8,t++,g[8]++;for(v(s,287,g),t=0;t<30;t++)r[2*t+1]=5,r[2*t]=k(t,5);f=new _(s,e,257,286,15),c=new _(r,a,0,30,15),u=new _(new Array(0),i,0,19,7)})(),U=!0),t.l_desc=new w(t.dyn_ltree,f),t.d_desc=new w(t.dyn_dtree,c),t.bl_desc=new w(t.bl_tree,u),t.bi_buf=0,t.bi_valid=0,y(t)},_tr_stored_block:D,_tr_flush_block:O,_tr_tally:(t,e,a)=>(t.pending_buf[t.sym_buf+t.sym_next++]=e,t.pending_buf[t.sym_buf+t.sym_next++]=e>>8,t.pending_buf[t.sym_buf+t.sym_next++]=a,0===e?t.dyn_ltree[2*a]++:(t.matches++,e--,t.dyn_ltree[2*(l[a]+256+1)]++,t.dyn_dtree[2*m(e)]++),t.sym_next===t.sym_end),_tr_align:t=>{g(t,2,3),p(t,256,s),(t=>{16===t.bi_valid?(b(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)})(t)}};var N=(t,e,a,i)=>{let n=65535&t|0,s=t>>>16&65535|0,r=0;for(;0!==a;){r=a>2e3?2e3:a,a-=r;do{n=n+e[i++]|0,s=s+n|0}while(--r);n%=65521,s%=65521}return n|s<<16|0};const F=new Uint32Array((()=>{let t,e=[];for(var a=0;a<256;a++){t=a;for(var i=0;i<8;i++)t=1&t?3988292384^t>>>1:t>>>1;e[a]=t}return e})());var L=(t,e,a,i)=>{const n=F,s=i+a;t^=-1;for(let a=i;a<s;a++)t=t>>>8^n[255&(t^e[a])];return-1^t},I={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},B={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:C,_tr_stored_block:H,_tr_flush_block:M,_tr_tally:j,_tr_align:K}=T,{Z_NO_FLUSH:P,Z_PARTIAL_FLUSH:Y,Z_FULL_FLUSH:G,Z_FINISH:X,Z_BLOCK:J,Z_OK:W,Z_STREAM_END:q,Z_STREAM_ERROR:Q,Z_DATA_ERROR:V,Z_BUF_ERROR:$,Z_DEFAULT_COMPRESSION:tt,Z_FILTERED:et,Z_HUFFMAN_ONLY:at,Z_RLE:it,Z_FIXED:nt,Z_DEFAULT_STRATEGY:st,Z_UNKNOWN:rt,Z_DEFLATED:ot}=B,lt=(t,e)=>(t.msg=I[e],e),ht=t=>2*t-(t>4?9:0),dt=t=>{let e=t.length;for(;--e>=0;)t[e]=0},_t=t=>{let e,a,i,n=t.w_size;e=t.hash_size,i=e;do{a=t.head[--i],t.head[i]=a>=n?a-n:0}while(--e);e=n,i=e;do{a=t.prev[--i],t.prev[i]=a>=n?a-n:0}while(--e)};let ft=(t,e,a)=>(e<<t.hash_shift^a)&t.hash_mask;const ct=t=>{const e=t.state;let a=e.pending;a>t.avail_out&&(a=t.avail_out),0!==a&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+a),t.next_out),t.next_out+=a,e.pending_out+=a,t.total_out+=a,t.avail_out-=a,e.pending-=a,0===e.pending&&(e.pending_out=0))},ut=(t,e)=>{M(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,ct(t.strm)},wt=(t,e)=>{t.pending_buf[t.pending++]=e},mt=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},bt=(t,e,a,i)=>{let n=t.avail_in;return n>i&&(n=i),0===n?0:(t.avail_in-=n,e.set(t.input.subarray(t.next_in,t.next_in+n),a),1===t.state.wrap?t.adler=N(t.adler,e,n,a):2===t.state.wrap&&(t.adler=L(t.adler,e,n,a)),t.next_in+=n,t.total_in+=n,n)},gt=(t,e)=>{let a,i,n=t.max_chain_length,s=t.strstart,r=t.prev_length,o=t.nice_match;const l=t.strstart>t.w_size-262?t.strstart-(t.w_size-262):0,h=t.window,d=t.w_mask,_=t.prev,f=t.strstart+258;let c=h[s+r-1],u=h[s+r];t.prev_length>=t.good_match&&(n>>=2),o>t.lookahead&&(o=t.lookahead);do{if(a=e,h[a+r]===u&&h[a+r-1]===c&&h[a]===h[s]&&h[++a]===h[s+1]){s+=2,a++;do{}while(h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&s<f);if(i=258-(f-s),s=f-258,i>r){if(t.match_start=e,r=i,i>=o)break;c=h[s+r-1],u=h[s+r]}}}while((e=_[e&d])>l&&0!=--n);return r<=t.lookahead?r:t.lookahead},pt=t=>{const e=t.w_size;let a,i,n;do{if(i=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-262)&&(t.window.set(t.window.subarray(e,e+e-i),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),_t(t),i+=e),0===t.strm.avail_in)break;if(a=bt(t.strm,t.window,t.strstart+t.lookahead,i),t.lookahead+=a,t.lookahead+t.insert>=3)for(n=t.strstart-t.insert,t.ins_h=t.window[n],t.ins_h=ft(t,t.ins_h,t.window[n+1]);t.insert&&(t.ins_h=ft(t,t.ins_h,t.window[n+3-1]),t.prev[n&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=n,n++,t.insert--,!(t.lookahead+t.insert<3)););}while(t.lookahead<262&&0!==t.strm.avail_in)},kt=(t,e)=>{let a,i,n,s=t.pending_buf_size-5>t.w_size?t.w_size:t.pending_buf_size-5,r=0,o=t.strm.avail_in;do{if(a=65535,n=t.bi_valid+42>>3,t.strm.avail_out<n)break;if(n=t.strm.avail_out-n,i=t.strstart-t.block_start,a>i+t.strm.avail_in&&(a=i+t.strm.avail_in),a>n&&(a=n),a<s&&(0===a&&e!==X||e===P||a!==i+t.strm.avail_in))break;r=e===X&&a===i+t.strm.avail_in?1:0,H(t,0,0,r),t.pending_buf[t.pending-4]=a,t.pending_buf[t.pending-3]=a>>8,t.pending_buf[t.pending-2]=~a,t.pending_buf[t.pending-1]=~a>>8,ct(t.strm),i&&(i>a&&(i=a),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+i),t.strm.next_out),t.strm.next_out+=i,t.strm.avail_out-=i,t.strm.total_out+=i,t.block_start+=i,a-=i),a&&(bt(t.strm,t.strm.output,t.strm.next_out,a),t.strm.next_out+=a,t.strm.avail_out-=a,t.strm.total_out+=a)}while(0===r);return o-=t.strm.avail_in,o&&(o>=t.w_size?(t.matches=2,t.window.set(t.strm.input.subarray(t.strm.next_in-t.w_size,t.strm.next_in),0),t.strstart=t.w_size,t.insert=t.strstart):(t.window_size-t.strstart<=o&&(t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,t.insert>t.strstart&&(t.insert=t.strstart)),t.window.set(t.strm.input.subarray(t.strm.next_in-o,t.strm.next_in),t.strstart),t.strstart+=o,t.insert+=o>t.w_size-t.insert?t.w_size-t.insert:o),t.block_start=t.strstart),t.high_water<t.strstart&&(t.high_water=t.strstart),r?4:e!==P&&e!==X&&0===t.strm.avail_in&&t.strstart===t.block_start?2:(n=t.window_size-t.strstart,t.strm.avail_in>n&&t.block_start>=t.w_size&&(t.block_start-=t.w_size,t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,n+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),n>t.strm.avail_in&&(n=t.strm.avail_in),n&&(bt(t.strm,t.window,t.strstart,n),t.strstart+=n,t.insert+=n>t.w_size-t.insert?t.w_size-t.insert:n),t.high_water<t.strstart&&(t.high_water=t.strstart),n=t.bi_valid+42>>3,n=t.pending_buf_size-n>65535?65535:t.pending_buf_size-n,s=n>t.w_size?t.w_size:n,i=t.strstart-t.block_start,(i>=s||(i||e===X)&&e!==P&&0===t.strm.avail_in&&i<=n)&&(a=i>n?n:i,r=e===X&&0===t.strm.avail_in&&a===i?1:0,H(t,t.block_start,a,r),t.block_start+=a,ct(t.strm)),r?3:1)},vt=(t,e)=>{let a,i;for(;;){if(t.lookahead<262){if(pt(t),t.lookahead<262&&e===P)return 1;if(0===t.lookahead)break}if(a=0,t.lookahead>=3&&(t.ins_h=ft(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==a&&t.strstart-a<=t.w_size-262&&(t.match_length=gt(t,a)),t.match_length>=3)if(i=j(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do{t.strstart++,t.ins_h=ft(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!=--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=ft(t,t.ins_h,t.window[t.strstart+1]);else i=j(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(i&&(ut(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,e===X?(ut(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ut(t,!1),0===t.strm.avail_out)?1:2},yt=(t,e)=>{let a,i,n;for(;;){if(t.lookahead<262){if(pt(t),t.lookahead<262&&e===P)return 1;if(0===t.lookahead)break}if(a=0,t.lookahead>=3&&(t.ins_h=ft(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=2,0!==a&&t.prev_length<t.max_lazy_match&&t.strstart-a<=t.w_size-262&&(t.match_length=gt(t,a),t.match_length<=5&&(t.strategy===et||3===t.match_length&&t.strstart-t.match_start>4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){n=t.strstart+t.lookahead-3,i=j(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=n&&(t.ins_h=ft(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!=--t.prev_length);if(t.match_available=0,t.match_length=2,t.strstart++,i&&(ut(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if(i=j(t,0,t.window[t.strstart-1]),i&&ut(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return 1}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(i=j(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===X?(ut(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ut(t,!1),0===t.strm.avail_out)?1:2};function xt(t,e,a,i,n){this.good_length=t,this.max_lazy=e,this.nice_length=a,this.max_chain=i,this.func=n}const zt=[new xt(0,0,0,0,kt),new xt(4,4,8,4,vt),new xt(4,5,16,8,vt),new xt(4,6,32,32,vt),new xt(4,4,16,16,yt),new xt(8,16,32,32,yt),new xt(8,16,128,128,yt),new xt(8,32,128,256,yt),new xt(32,128,258,1024,yt),new xt(32,258,258,4096,yt)];function At(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=ot,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),dt(this.dyn_ltree),dt(this.dyn_dtree),dt(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),dt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),dt(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const Et=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||42!==e.status&&57!==e.status&&69!==e.status&&73!==e.status&&91!==e.status&&103!==e.status&&113!==e.status&&666!==e.status?1:0},Rt=t=>{if(Et(t))return lt(t,Q);t.total_in=t.total_out=0,t.data_type=rt;const e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=2===e.wrap?57:e.wrap?42:113,t.adler=2===e.wrap?0:1,e.last_flush=-2,C(e),W},Zt=t=>{const e=Rt(t);var a;return e===W&&((a=t.state).window_size=2*a.w_size,dt(a.head),a.max_lazy_match=zt[a.level].max_lazy,a.good_match=zt[a.level].good_length,a.nice_match=zt[a.level].nice_length,a.max_chain_length=zt[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=2,a.match_available=0,a.ins_h=0),e},St=(t,e,a,i,n,s)=>{if(!t)return Q;let r=1;if(e===tt&&(e=6),i<0?(r=0,i=-i):i>15&&(r=2,i-=16),n<1||n>9||a!==ot||i<8||i>15||e<0||e>9||s<0||s>nt||8===i&&1!==r)return lt(t,Q);8===i&&(i=9);const o=new At;return t.state=o,o.strm=t,o.status=42,o.wrap=r,o.gzhead=null,o.w_bits=i,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=n+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+3-1)/3),o.window=new Uint8Array(2*o.w_size),o.head=new Uint16Array(o.hash_size),o.prev=new Uint16Array(o.w_size),o.lit_bufsize=1<<n+6,o.pending_buf_size=4*o.lit_bufsize,o.pending_buf=new Uint8Array(o.pending_buf_size),o.sym_buf=o.lit_bufsize,o.sym_end=3*(o.lit_bufsize-1),o.level=e,o.strategy=s,o.method=a,Zt(t)};var Ut={deflateInit:(t,e)=>St(t,e,ot,15,8,st),deflateInit2:St,deflateReset:Zt,deflateResetKeep:Rt,deflateSetHeader:(t,e)=>Et(t)||2!==t.state.wrap?Q:(t.state.gzhead=e,W),deflate:(t,e)=>{if(Et(t)||e>J||e<0)return t?lt(t,Q):Q;const a=t.state;if(!t.output||0!==t.avail_in&&!t.input||666===a.status&&e!==X)return lt(t,0===t.avail_out?$:Q);const i=a.last_flush;if(a.last_flush=e,0!==a.pending){if(ct(t),0===t.avail_out)return a.last_flush=-1,W}else if(0===t.avail_in&&ht(e)<=ht(i)&&e!==X)return lt(t,$);if(666===a.status&&0!==t.avail_in)return lt(t,$);if(42===a.status&&0===a.wrap&&(a.status=113),42===a.status){let e=ot+(a.w_bits-8<<4)<<8,i=-1;if(i=a.strategy>=at||a.level<2?0:a.level<6?1:6===a.level?2:3,e|=i<<6,0!==a.strstart&&(e|=32),e+=31-e%31,mt(a,e),0!==a.strstart&&(mt(a,t.adler>>>16),mt(a,65535&t.adler)),t.adler=1,a.status=113,ct(t),0!==a.pending)return a.last_flush=-1,W}if(57===a.status)if(t.adler=0,wt(a,31),wt(a,139),wt(a,8),a.gzhead)wt(a,(a.gzhead.text?1:0)+(a.gzhead.hcrc?2:0)+(a.gzhead.extra?4:0)+(a.gzhead.name?8:0)+(a.gzhead.comment?16:0)),wt(a,255&a.gzhead.time),wt(a,a.gzhead.time>>8&255),wt(a,a.gzhead.time>>16&255),wt(a,a.gzhead.time>>24&255),wt(a,9===a.level?2:a.strategy>=at||a.level<2?4:0),wt(a,255&a.gzhead.os),a.gzhead.extra&&a.gzhead.extra.length&&(wt(a,255&a.gzhead.extra.length),wt(a,a.gzhead.extra.length>>8&255)),a.gzhead.hcrc&&(t.adler=L(t.adler,a.pending_buf,a.pending,0)),a.gzindex=0,a.status=69;else if(wt(a,0),wt(a,0),wt(a,0),wt(a,0),wt(a,0),wt(a,9===a.level?2:a.strategy>=at||a.level<2?4:0),wt(a,3),a.status=113,ct(t),0!==a.pending)return a.last_flush=-1,W;if(69===a.status){if(a.gzhead.extra){let e=a.pending,i=(65535&a.gzhead.extra.length)-a.gzindex;for(;a.pending+i>a.pending_buf_size;){let n=a.pending_buf_size-a.pending;if(a.pending_buf.set(a.gzhead.extra.subarray(a.gzindex,a.gzindex+n),a.pending),a.pending=a.pending_buf_size,a.gzhead.hcrc&&a.pending>e&&(t.adler=L(t.adler,a.pending_buf,a.pending-e,e)),a.gzindex+=n,ct(t),0!==a.pending)return a.last_flush=-1,W;e=0,i-=n}let n=new Uint8Array(a.gzhead.extra);a.pending_buf.set(n.subarray(a.gzindex,a.gzindex+i),a.pending),a.pending+=i,a.gzhead.hcrc&&a.pending>e&&(t.adler=L(t.adler,a.pending_buf,a.pending-e,e)),a.gzindex=0}a.status=73}if(73===a.status){if(a.gzhead.name){let e,i=a.pending;do{if(a.pending===a.pending_buf_size){if(a.gzhead.hcrc&&a.pending>i&&(t.adler=L(t.adler,a.pending_buf,a.pending-i,i)),ct(t),0!==a.pending)return a.last_flush=-1,W;i=0}e=a.gzindex<a.gzhead.name.length?255&a.gzhead.name.charCodeAt(a.gzindex++):0,wt(a,e)}while(0!==e);a.gzhead.hcrc&&a.pending>i&&(t.adler=L(t.adler,a.pending_buf,a.pending-i,i)),a.gzindex=0}a.status=91}if(91===a.status){if(a.gzhead.comment){let e,i=a.pending;do{if(a.pending===a.pending_buf_size){if(a.gzhead.hcrc&&a.pending>i&&(t.adler=L(t.adler,a.pending_buf,a.pending-i,i)),ct(t),0!==a.pending)return a.last_flush=-1,W;i=0}e=a.gzindex<a.gzhead.comment.length?255&a.gzhead.comment.charCodeAt(a.gzindex++):0,wt(a,e)}while(0!==e);a.gzhead.hcrc&&a.pending>i&&(t.adler=L(t.adler,a.pending_buf,a.pending-i,i))}a.status=103}if(103===a.status){if(a.gzhead.hcrc){if(a.pending+2>a.pending_buf_size&&(ct(t),0!==a.pending))return a.last_flush=-1,W;wt(a,255&t.adler),wt(a,t.adler>>8&255),t.adler=0}if(a.status=113,ct(t),0!==a.pending)return a.last_flush=-1,W}if(0!==t.avail_in||0!==a.lookahead||e!==P&&666!==a.status){let i=0===a.level?kt(a,e):a.strategy===at?((t,e)=>{let a;for(;;){if(0===t.lookahead&&(pt(t),0===t.lookahead)){if(e===P)return 1;break}if(t.match_length=0,a=j(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,a&&(ut(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===X?(ut(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ut(t,!1),0===t.strm.avail_out)?1:2})(a,e):a.strategy===it?((t,e)=>{let a,i,n,s;const r=t.window;for(;;){if(t.lookahead<=258){if(pt(t),t.lookahead<=258&&e===P)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(n=t.strstart-1,i=r[n],i===r[++n]&&i===r[++n]&&i===r[++n])){s=t.strstart+258;do{}while(i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&n<s);t.match_length=258-(s-n),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(a=j(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(a=j(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),a&&(ut(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===X?(ut(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ut(t,!1),0===t.strm.avail_out)?1:2})(a,e):zt[a.level].func(a,e);if(3!==i&&4!==i||(a.status=666),1===i||3===i)return 0===t.avail_out&&(a.last_flush=-1),W;if(2===i&&(e===Y?K(a):e!==J&&(H(a,0,0,!1),e===G&&(dt(a.head),0===a.lookahead&&(a.strstart=0,a.block_start=0,a.insert=0))),ct(t),0===t.avail_out))return a.last_flush=-1,W}return e!==X?W:a.wrap<=0?q:(2===a.wrap?(wt(a,255&t.adler),wt(a,t.adler>>8&255),wt(a,t.adler>>16&255),wt(a,t.adler>>24&255),wt(a,255&t.total_in),wt(a,t.total_in>>8&255),wt(a,t.total_in>>16&255),wt(a,t.total_in>>24&255)):(mt(a,t.adler>>>16),mt(a,65535&t.adler)),ct(t),a.wrap>0&&(a.wrap=-a.wrap),0!==a.pending?W:q)},deflateEnd:t=>{if(Et(t))return Q;const e=t.state.status;return t.state=null,113===e?lt(t,V):W},deflateSetDictionary:(t,e)=>{let a=e.length;if(Et(t))return Q;const i=t.state,n=i.wrap;if(2===n||1===n&&42!==i.status||i.lookahead)return Q;if(1===n&&(t.adler=N(t.adler,e,a,0)),i.wrap=0,a>=i.w_size){0===n&&(dt(i.head),i.strstart=0,i.block_start=0,i.insert=0);let t=new Uint8Array(i.w_size);t.set(e.subarray(a-i.w_size,a),0),e=t,a=i.w_size}const s=t.avail_in,r=t.next_in,o=t.input;for(t.avail_in=a,t.next_in=0,t.input=e,pt(i);i.lookahead>=3;){let t=i.strstart,e=i.lookahead-2;do{i.ins_h=ft(i,i.ins_h,i.window[t+3-1]),i.prev[t&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=t,t++}while(--e);i.strstart=t,i.lookahead=2,pt(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=2,i.match_available=0,t.next_in=r,t.input=o,t.avail_in=s,i.wrap=n,W},deflateInfo:"pako deflate (from Nodeca project)"};const Dt=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var Ot=function(t){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const a=e.shift();if(a){if("object"!=typeof a)throw new TypeError(a+"must be non-object");for(const e in a)Dt(a,e)&&(t[e]=a[e])}}return t},Tt=t=>{let e=0;for(let a=0,i=t.length;a<i;a++)e+=t[a].length;const a=new Uint8Array(e);for(let e=0,i=0,n=t.length;e<n;e++){let n=t[e];a.set(n,i),i+=n.length}return a};let Nt=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){Nt=!1}const Ft=new Uint8Array(256);for(let t=0;t<256;t++)Ft[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;Ft[254]=Ft[254]=1;var Lt=t=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,a,i,n,s,r=t.length,o=0;for(n=0;n<r;n++)a=t.charCodeAt(n),55296==(64512&a)&&n+1<r&&(i=t.charCodeAt(n+1),56320==(64512&i)&&(a=65536+(a-55296<<10)+(i-56320),n++)),o+=a<128?1:a<2048?2:a<65536?3:4;for(e=new Uint8Array(o),s=0,n=0;s<o;n++)a=t.charCodeAt(n),55296==(64512&a)&&n+1<r&&(i=t.charCodeAt(n+1),56320==(64512&i)&&(a=65536+(a-55296<<10)+(i-56320),n++)),a<128?e[s++]=a:a<2048?(e[s++]=192|a>>>6,e[s++]=128|63&a):a<65536?(e[s++]=224|a>>>12,e[s++]=128|a>>>6&63,e[s++]=128|63&a):(e[s++]=240|a>>>18,e[s++]=128|a>>>12&63,e[s++]=128|a>>>6&63,e[s++]=128|63&a);return e},It=(t,e)=>{const a=e||t.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(t.subarray(0,e));let i,n;const s=new Array(2*a);for(n=0,i=0;i<a;){let e=t[i++];if(e<128){s[n++]=e;continue}let r=Ft[e];if(r>4)s[n++]=65533,i+=r-1;else{for(e&=2===r?31:3===r?15:7;r>1&&i<a;)e=e<<6|63&t[i++],r--;r>1?s[n++]=65533:e<65536?s[n++]=e:(e-=65536,s[n++]=55296|e>>10&1023,s[n++]=56320|1023&e)}}return((t,e)=>{if(e<65534&&t.subarray&&Nt)return String.fromCharCode.apply(null,t.length===e?t:t.subarray(0,e));let a="";for(let i=0;i<e;i++)a+=String.fromCharCode(t[i]);return a})(s,n)},Bt=(t,e)=>{(e=e||t.length)>t.length&&(e=t.length);let a=e-1;for(;a>=0&&128==(192&t[a]);)a--;return a<0||0===a?e:a+Ft[t[a]]>e?a:e};var Ct=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0};const Ht=Object.prototype.toString,{Z_NO_FLUSH:Mt,Z_SYNC_FLUSH:jt,Z_FULL_FLUSH:Kt,Z_FINISH:Pt,Z_OK:Yt,Z_STREAM_END:Gt,Z_DEFAULT_COMPRESSION:Xt,Z_DEFAULT_STRATEGY:Jt,Z_DEFLATED:Wt}=B;function qt(t){this.options=Ot({level:Xt,method:Wt,chunkSize:16384,windowBits:15,memLevel:8,strategy:Jt},t||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Ct,this.strm.avail_out=0;let a=Ut.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(a!==Yt)throw new Error(I[a]);if(e.header&&Ut.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t="string"==typeof e.dictionary?Lt(e.dictionary):"[object ArrayBuffer]"===Ht.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,a=Ut.deflateSetDictionary(this.strm,t),a!==Yt)throw new Error(I[a]);this._dict_set=!0}}function Qt(t,e){const a=new qt(e);if(a.push(t,!0),a.err)throw a.msg||I[a.err];return a.result}qt.prototype.push=function(t,e){const a=this.strm,i=this.options.chunkSize;let n,s;if(this.ended)return!1;for(s=e===~~e?e:!0===e?Pt:Mt,"string"==typeof t?a.input=Lt(t):"[object ArrayBuffer]"===Ht.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;;)if(0===a.avail_out&&(a.output=new Uint8Array(i),a.next_out=0,a.avail_out=i),(s===jt||s===Kt)&&a.avail_out<=6)this.onData(a.output.subarray(0,a.next_out)),a.avail_out=0;else{if(n=Ut.deflate(a,s),n===Gt)return a.next_out>0&&this.onData(a.output.subarray(0,a.next_out)),n=Ut.deflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===Yt;if(0!==a.avail_out){if(s>0&&a.next_out>0)this.onData(a.output.subarray(0,a.next_out)),a.avail_out=0;else if(0===a.avail_in)break}else this.onData(a.output)}return!0},qt.prototype.onData=function(t){this.chunks.push(t)},qt.prototype.onEnd=function(t){t===Yt&&(this.result=Tt(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var Vt={Deflate:qt,deflate:Qt,deflateRaw:function(t,e){return(e=e||{}).raw=!0,Qt(t,e)},gzip:function(t,e){return(e=e||{}).gzip=!0,Qt(t,e)},constants:B};var $t=function(t,e){let a,i,n,s,r,o,l,h,d,_,f,c,u,w,m,b,g,p,k,v,y,x,z,A;const E=t.state;a=t.next_in,z=t.input,i=a+(t.avail_in-5),n=t.next_out,A=t.output,s=n-(e-t.avail_out),r=n+(t.avail_out-257),o=E.dmax,l=E.wsize,h=E.whave,d=E.wnext,_=E.window,f=E.hold,c=E.bits,u=E.lencode,w=E.distcode,m=(1<<E.lenbits)-1,b=(1<<E.distbits)-1;t:do{c<15&&(f+=z[a++]<<c,c+=8,f+=z[a++]<<c,c+=8),g=u[f&m];e:for(;;){if(p=g>>>24,f>>>=p,c-=p,p=g>>>16&255,0===p)A[n++]=65535&g;else{if(!(16&p)){if(0==(64&p)){g=u[(65535&g)+(f&(1<<p)-1)];continue e}if(32&p){E.mode=16191;break t}t.msg="invalid literal/length code",E.mode=16209;break t}k=65535&g,p&=15,p&&(c<p&&(f+=z[a++]<<c,c+=8),k+=f&(1<<p)-1,f>>>=p,c-=p),c<15&&(f+=z[a++]<<c,c+=8,f+=z[a++]<<c,c+=8),g=w[f&b];a:for(;;){if(p=g>>>24,f>>>=p,c-=p,p=g>>>16&255,!(16&p)){if(0==(64&p)){g=w[(65535&g)+(f&(1<<p)-1)];continue a}t.msg="invalid distance code",E.mode=16209;break t}if(v=65535&g,p&=15,c<p&&(f+=z[a++]<<c,c+=8,c<p&&(f+=z[a++]<<c,c+=8)),v+=f&(1<<p)-1,v>o){t.msg="invalid distance too far back",E.mode=16209;break t}if(f>>>=p,c-=p,p=n-s,v>p){if(p=v-p,p>h&&E.sane){t.msg="invalid distance too far back",E.mode=16209;break t}if(y=0,x=_,0===d){if(y+=l-p,p<k){k-=p;do{A[n++]=_[y++]}while(--p);y=n-v,x=A}}else if(d<p){if(y+=l+d-p,p-=d,p<k){k-=p;do{A[n++]=_[y++]}while(--p);if(y=0,d<k){p=d,k-=p;do{A[n++]=_[y++]}while(--p);y=n-v,x=A}}}else if(y+=d-p,p<k){k-=p;do{A[n++]=_[y++]}while(--p);y=n-v,x=A}for(;k>2;)A[n++]=x[y++],A[n++]=x[y++],A[n++]=x[y++],k-=3;k&&(A[n++]=x[y++],k>1&&(A[n++]=x[y++]))}else{y=n-v;do{A[n++]=A[y++],A[n++]=A[y++],A[n++]=A[y++],k-=3}while(k>2);k&&(A[n++]=A[y++],k>1&&(A[n++]=A[y++]))}break}}break}}while(a<i&&n<r);k=c>>3,a-=k,c-=k<<3,f&=(1<<c)-1,t.next_in=a,t.next_out=n,t.avail_in=a<i?i-a+5:5-(a-i),t.avail_out=n<r?r-n+257:257-(n-r),E.hold=f,E.bits=c};const te=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),ee=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),ae=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),ie=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]);var ne=(t,e,a,i,n,s,r,o)=>{const l=o.bits;let h,d,_,f,c,u,w=0,m=0,b=0,g=0,p=0,k=0,v=0,y=0,x=0,z=0,A=null;const E=new Uint16Array(16),R=new Uint16Array(16);let Z,S,U,D=null;for(w=0;w<=15;w++)E[w]=0;for(m=0;m<i;m++)E[e[a+m]]++;for(p=l,g=15;g>=1&&0===E[g];g--);if(p>g&&(p=g),0===g)return n[s++]=20971520,n[s++]=20971520,o.bits=1,0;for(b=1;b<g&&0===E[b];b++);for(p<b&&(p=b),y=1,w=1;w<=15;w++)if(y<<=1,y-=E[w],y<0)return-1;if(y>0&&(0===t||1!==g))return-1;for(R[1]=0,w=1;w<15;w++)R[w+1]=R[w]+E[w];for(m=0;m<i;m++)0!==e[a+m]&&(r[R[e[a+m]]++]=m);if(0===t?(A=D=r,u=20):1===t?(A=te,D=ee,u=257):(A=ae,D=ie,u=0),z=0,m=0,w=b,c=s,k=p,v=0,_=-1,x=1<<p,f=x-1,1===t&&x>852||2===t&&x>592)return 1;for(;;){Z=w-v,r[m]+1<u?(S=0,U=r[m]):r[m]>=u?(S=D[r[m]-u],U=A[r[m]-u]):(S=96,U=0),h=1<<w-v,d=1<<k,b=d;do{d-=h,n[c+(z>>v)+d]=Z<<24|S<<16|U|0}while(0!==d);for(h=1<<w-1;z&h;)h>>=1;if(0!==h?(z&=h-1,z+=h):z=0,m++,0==--E[w]){if(w===g)break;w=e[a+r[m]]}if(w>p&&(z&f)!==_){for(0===v&&(v=p),c+=b,k=w-v,y=1<<k;k+v<g&&(y-=E[k+v],!(y<=0));)k++,y<<=1;if(x+=1<<k,1===t&&x>852||2===t&&x>592)return 1;_=z&f,n[_]=p<<24|k<<16|c-s|0}}return 0!==z&&(n[c+z]=w-v<<24|64<<16|0),o.bits=p,0};const{Z_FINISH:se,Z_BLOCK:re,Z_TREES:oe,Z_OK:le,Z_STREAM_END:he,Z_NEED_DICT:de,Z_STREAM_ERROR:_e,Z_DATA_ERROR:fe,Z_MEM_ERROR:ce,Z_BUF_ERROR:ue,Z_DEFLATED:we}=B,me=16209,be=t=>(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24);function ge(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const pe=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.mode<16180||e.mode>16211?1:0},ke=t=>{if(pe(t))return _e;const e=t.state;return t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=16180,e.last=0,e.havedict=0,e.flags=-1,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(852),e.distcode=e.distdyn=new Int32Array(592),e.sane=1,e.back=-1,le},ve=t=>{if(pe(t))return _e;const e=t.state;return e.wsize=0,e.whave=0,e.wnext=0,ke(t)},ye=(t,e)=>{let a;if(pe(t))return _e;const i=t.state;return e<0?(a=0,e=-e):(a=5+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?_e:(null!==i.window&&i.wbits!==e&&(i.window=null),i.wrap=a,i.wbits=e,ve(t))},xe=(t,e)=>{if(!t)return _e;const a=new ge;t.state=a,a.strm=t,a.window=null,a.mode=16180;const i=ye(t,e);return i!==le&&(t.state=null),i};let ze,Ae,Ee=!0;const Re=t=>{if(Ee){ze=new Int32Array(512),Ae=new Int32Array(32);let e=0;for(;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(ne(1,t.lens,0,288,ze,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;ne(2,t.lens,0,32,Ae,0,t.work,{bits:5}),Ee=!1}t.lencode=ze,t.lenbits=9,t.distcode=Ae,t.distbits=5},Ze=(t,e,a,i)=>{let n;const s=t.state;return null===s.window&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new Uint8Array(s.wsize)),i>=s.wsize?(s.window.set(e.subarray(a-s.wsize,a),0),s.wnext=0,s.whave=s.wsize):(n=s.wsize-s.wnext,n>i&&(n=i),s.window.set(e.subarray(a-i,a-i+n),s.wnext),(i-=n)?(s.window.set(e.subarray(a-i,a),0),s.wnext=i,s.whave=s.wsize):(s.wnext+=n,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=n))),0};var Se={inflateReset:ve,inflateReset2:ye,inflateResetKeep:ke,inflateInit:t=>xe(t,15),inflateInit2:xe,inflate:(t,e)=>{let a,i,n,s,r,o,l,h,d,_,f,c,u,w,m,b,g,p,k,v,y,x,z=0;const A=new Uint8Array(4);let E,R;const Z=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(pe(t)||!t.output||!t.input&&0!==t.avail_in)return _e;a=t.state,16191===a.mode&&(a.mode=16192),r=t.next_out,n=t.output,l=t.avail_out,s=t.next_in,i=t.input,o=t.avail_in,h=a.hold,d=a.bits,_=o,f=l,x=le;t:for(;;)switch(a.mode){case 16180:if(0===a.wrap){a.mode=16192;break}for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(2&a.wrap&&35615===h){0===a.wbits&&(a.wbits=15),a.check=0,A[0]=255&h,A[1]=h>>>8&255,a.check=L(a.check,A,2,0),h=0,d=0,a.mode=16181;break}if(a.head&&(a.head.done=!1),!(1&a.wrap)||(((255&h)<<8)+(h>>8))%31){t.msg="incorrect header check",a.mode=me;break}if((15&h)!==we){t.msg="unknown compression method",a.mode=me;break}if(h>>>=4,d-=4,y=8+(15&h),0===a.wbits&&(a.wbits=y),y>15||y>a.wbits){t.msg="invalid window size",a.mode=me;break}a.dmax=1<<a.wbits,a.flags=0,t.adler=a.check=1,a.mode=512&h?16189:16191,h=0,d=0;break;case 16181:for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(a.flags=h,(255&a.flags)!==we){t.msg="unknown compression method",a.mode=me;break}if(57344&a.flags){t.msg="unknown header flags set",a.mode=me;break}a.head&&(a.head.text=h>>8&1),512&a.flags&&4&a.wrap&&(A[0]=255&h,A[1]=h>>>8&255,a.check=L(a.check,A,2,0)),h=0,d=0,a.mode=16182;case 16182:for(;d<32;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}a.head&&(a.head.time=h),512&a.flags&&4&a.wrap&&(A[0]=255&h,A[1]=h>>>8&255,A[2]=h>>>16&255,A[3]=h>>>24&255,a.check=L(a.check,A,4,0)),h=0,d=0,a.mode=16183;case 16183:for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}a.head&&(a.head.xflags=255&h,a.head.os=h>>8),512&a.flags&&4&a.wrap&&(A[0]=255&h,A[1]=h>>>8&255,a.check=L(a.check,A,2,0)),h=0,d=0,a.mode=16184;case 16184:if(1024&a.flags){for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}a.length=h,a.head&&(a.head.extra_len=h),512&a.flags&&4&a.wrap&&(A[0]=255&h,A[1]=h>>>8&255,a.check=L(a.check,A,2,0)),h=0,d=0}else a.head&&(a.head.extra=null);a.mode=16185;case 16185:if(1024&a.flags&&(c=a.length,c>o&&(c=o),c&&(a.head&&(y=a.head.extra_len-a.length,a.head.extra||(a.head.extra=new Uint8Array(a.head.extra_len)),a.head.extra.set(i.subarray(s,s+c),y)),512&a.flags&&4&a.wrap&&(a.check=L(a.check,i,c,s)),o-=c,s+=c,a.length-=c),a.length))break t;a.length=0,a.mode=16186;case 16186:if(2048&a.flags){if(0===o)break t;c=0;do{y=i[s+c++],a.head&&y&&a.length<65536&&(a.head.name+=String.fromCharCode(y))}while(y&&c<o);if(512&a.flags&&4&a.wrap&&(a.check=L(a.check,i,c,s)),o-=c,s+=c,y)break t}else a.head&&(a.head.name=null);a.length=0,a.mode=16187;case 16187:if(4096&a.flags){if(0===o)break t;c=0;do{y=i[s+c++],a.head&&y&&a.length<65536&&(a.head.comment+=String.fromCharCode(y))}while(y&&c<o);if(512&a.flags&&4&a.wrap&&(a.check=L(a.check,i,c,s)),o-=c,s+=c,y)break t}else a.head&&(a.head.comment=null);a.mode=16188;case 16188:if(512&a.flags){for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(4&a.wrap&&h!==(65535&a.check)){t.msg="header crc mismatch",a.mode=me;break}h=0,d=0}a.head&&(a.head.hcrc=a.flags>>9&1,a.head.done=!0),t.adler=a.check=0,a.mode=16191;break;case 16189:for(;d<32;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}t.adler=a.check=be(h),h=0,d=0,a.mode=16190;case 16190:if(0===a.havedict)return t.next_out=r,t.avail_out=l,t.next_in=s,t.avail_in=o,a.hold=h,a.bits=d,de;t.adler=a.check=1,a.mode=16191;case 16191:if(e===re||e===oe)break t;case 16192:if(a.last){h>>>=7&d,d-=7&d,a.mode=16206;break}for(;d<3;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}switch(a.last=1&h,h>>>=1,d-=1,3&h){case 0:a.mode=16193;break;case 1:if(Re(a),a.mode=16199,e===oe){h>>>=2,d-=2;break t}break;case 2:a.mode=16196;break;case 3:t.msg="invalid block type",a.mode=me}h>>>=2,d-=2;break;case 16193:for(h>>>=7&d,d-=7&d;d<32;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if((65535&h)!=(h>>>16^65535)){t.msg="invalid stored block lengths",a.mode=me;break}if(a.length=65535&h,h=0,d=0,a.mode=16194,e===oe)break t;case 16194:a.mode=16195;case 16195:if(c=a.length,c){if(c>o&&(c=o),c>l&&(c=l),0===c)break t;n.set(i.subarray(s,s+c),r),o-=c,s+=c,l-=c,r+=c,a.length-=c;break}a.mode=16191;break;case 16196:for(;d<14;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(a.nlen=257+(31&h),h>>>=5,d-=5,a.ndist=1+(31&h),h>>>=5,d-=5,a.ncode=4+(15&h),h>>>=4,d-=4,a.nlen>286||a.ndist>30){t.msg="too many length or distance symbols",a.mode=me;break}a.have=0,a.mode=16197;case 16197:for(;a.have<a.ncode;){for(;d<3;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}a.lens[Z[a.have++]]=7&h,h>>>=3,d-=3}for(;a.have<19;)a.lens[Z[a.have++]]=0;if(a.lencode=a.lendyn,a.lenbits=7,E={bits:a.lenbits},x=ne(0,a.lens,0,19,a.lencode,0,a.work,E),a.lenbits=E.bits,x){t.msg="invalid code lengths set",a.mode=me;break}a.have=0,a.mode=16198;case 16198:for(;a.have<a.nlen+a.ndist;){for(;z=a.lencode[h&(1<<a.lenbits)-1],m=z>>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(g<16)h>>>=m,d-=m,a.lens[a.have++]=g;else{if(16===g){for(R=m+2;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(h>>>=m,d-=m,0===a.have){t.msg="invalid bit length repeat",a.mode=me;break}y=a.lens[a.have-1],c=3+(3&h),h>>>=2,d-=2}else if(17===g){for(R=m+3;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}h>>>=m,d-=m,y=0,c=3+(7&h),h>>>=3,d-=3}else{for(R=m+7;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}h>>>=m,d-=m,y=0,c=11+(127&h),h>>>=7,d-=7}if(a.have+c>a.nlen+a.ndist){t.msg="invalid bit length repeat",a.mode=me;break}for(;c--;)a.lens[a.have++]=y}}if(a.mode===me)break;if(0===a.lens[256]){t.msg="invalid code -- missing end-of-block",a.mode=me;break}if(a.lenbits=9,E={bits:a.lenbits},x=ne(1,a.lens,0,a.nlen,a.lencode,0,a.work,E),a.lenbits=E.bits,x){t.msg="invalid literal/lengths set",a.mode=me;break}if(a.distbits=6,a.distcode=a.distdyn,E={bits:a.distbits},x=ne(2,a.lens,a.nlen,a.ndist,a.distcode,0,a.work,E),a.distbits=E.bits,x){t.msg="invalid distances set",a.mode=me;break}if(a.mode=16199,e===oe)break t;case 16199:a.mode=16200;case 16200:if(o>=6&&l>=258){t.next_out=r,t.avail_out=l,t.next_in=s,t.avail_in=o,a.hold=h,a.bits=d,$t(t,f),r=t.next_out,n=t.output,l=t.avail_out,s=t.next_in,i=t.input,o=t.avail_in,h=a.hold,d=a.bits,16191===a.mode&&(a.back=-1);break}for(a.back=0;z=a.lencode[h&(1<<a.lenbits)-1],m=z>>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(b&&0==(240&b)){for(p=m,k=b,v=g;z=a.lencode[v+((h&(1<<p+k)-1)>>p)],m=z>>>24,b=z>>>16&255,g=65535&z,!(p+m<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}h>>>=p,d-=p,a.back+=p}if(h>>>=m,d-=m,a.back+=m,a.length=g,0===b){a.mode=16205;break}if(32&b){a.back=-1,a.mode=16191;break}if(64&b){t.msg="invalid literal/length code",a.mode=me;break}a.extra=15&b,a.mode=16201;case 16201:if(a.extra){for(R=a.extra;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}a.length+=h&(1<<a.extra)-1,h>>>=a.extra,d-=a.extra,a.back+=a.extra}a.was=a.length,a.mode=16202;case 16202:for(;z=a.distcode[h&(1<<a.distbits)-1],m=z>>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(0==(240&b)){for(p=m,k=b,v=g;z=a.distcode[v+((h&(1<<p+k)-1)>>p)],m=z>>>24,b=z>>>16&255,g=65535&z,!(p+m<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}h>>>=p,d-=p,a.back+=p}if(h>>>=m,d-=m,a.back+=m,64&b){t.msg="invalid distance code",a.mode=me;break}a.offset=g,a.extra=15&b,a.mode=16203;case 16203:if(a.extra){for(R=a.extra;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}a.offset+=h&(1<<a.extra)-1,h>>>=a.extra,d-=a.extra,a.back+=a.extra}if(a.offset>a.dmax){t.msg="invalid distance too far back",a.mode=me;break}a.mode=16204;case 16204:if(0===l)break t;if(c=f-l,a.offset>c){if(c=a.offset-c,c>a.whave&&a.sane){t.msg="invalid distance too far back",a.mode=me;break}c>a.wnext?(c-=a.wnext,u=a.wsize-c):u=a.wnext-c,c>a.length&&(c=a.length),w=a.window}else w=n,u=r-a.offset,c=a.length;c>l&&(c=l),l-=c,a.length-=c;do{n[r++]=w[u++]}while(--c);0===a.length&&(a.mode=16200);break;case 16205:if(0===l)break t;n[r++]=a.length,l--,a.mode=16200;break;case 16206:if(a.wrap){for(;d<32;){if(0===o)break t;o--,h|=i[s++]<<d,d+=8}if(f-=l,t.total_out+=f,a.total+=f,4&a.wrap&&f&&(t.adler=a.check=a.flags?L(a.check,n,f,r-f):N(a.check,n,f,r-f)),f=l,4&a.wrap&&(a.flags?h:be(h))!==a.check){t.msg="incorrect data check",a.mode=me;break}h=0,d=0}a.mode=16207;case 16207:if(a.wrap&&a.flags){for(;d<32;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(4&a.wrap&&h!==(4294967295&a.total)){t.msg="incorrect length check",a.mode=me;break}h=0,d=0}a.mode=16208;case 16208:x=he;break t;case me:x=fe;break t;case 16210:return ce;default:return _e}return t.next_out=r,t.avail_out=l,t.next_in=s,t.avail_in=o,a.hold=h,a.bits=d,(a.wsize||f!==t.avail_out&&a.mode<me&&(a.mode<16206||e!==se))&&Ze(t,t.output,t.next_out,f-t.avail_out),_-=t.avail_in,f-=t.avail_out,t.total_in+=_,t.total_out+=f,a.total+=f,4&a.wrap&&f&&(t.adler=a.check=a.flags?L(a.check,n,f,t.next_out-f):N(a.check,n,f,t.next_out-f)),t.data_type=a.bits+(a.last?64:0)+(16191===a.mode?128:0)+(16199===a.mode||16194===a.mode?256:0),(0===_&&0===f||e===se)&&x===le&&(x=ue),x},inflateEnd:t=>{if(pe(t))return _e;let e=t.state;return e.window&&(e.window=null),t.state=null,le},inflateGetHeader:(t,e)=>{if(pe(t))return _e;const a=t.state;return 0==(2&a.wrap)?_e:(a.head=e,e.done=!1,le)},inflateSetDictionary:(t,e)=>{const a=e.length;let i,n,s;return pe(t)?_e:(i=t.state,0!==i.wrap&&16190!==i.mode?_e:16190===i.mode&&(n=1,n=N(n,e,a,0),n!==i.check)?fe:(s=Ze(t,e,a,a),s?(i.mode=16210,ce):(i.havedict=1,le)))},inflateInfo:"pako inflate (from Nodeca project)"};var Ue=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1};const De=Object.prototype.toString,{Z_NO_FLUSH:Oe,Z_FINISH:Te,Z_OK:Ne,Z_STREAM_END:Fe,Z_NEED_DICT:Le,Z_STREAM_ERROR:Ie,Z_DATA_ERROR:Be,Z_MEM_ERROR:Ce}=B;function He(t){this.options=Ot({chunkSize:65536,windowBits:15,to:""},t||{});const e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&0==(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Ct,this.strm.avail_out=0;let a=Se.inflateInit2(this.strm,e.windowBits);if(a!==Ne)throw new Error(I[a]);if(this.header=new Ue,Se.inflateGetHeader(this.strm,this.header),e.dictionary&&("string"==typeof e.dictionary?e.dictionary=Lt(e.dictionary):"[object ArrayBuffer]"===De.call(e.dictionary)&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(a=Se.inflateSetDictionary(this.strm,e.dictionary),a!==Ne)))throw new Error(I[a])}He.prototype.push=function(t,e){const a=this.strm,i=this.options.chunkSize,n=this.options.dictionary;let s,r,o;if(this.ended)return!1;for(r=e===~~e?e:!0===e?Te:Oe,"[object ArrayBuffer]"===De.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;;){for(0===a.avail_out&&(a.output=new Uint8Array(i),a.next_out=0,a.avail_out=i),s=Se.inflate(a,r),s===Le&&n&&(s=Se.inflateSetDictionary(a,n),s===Ne?s=Se.inflate(a,r):s===Be&&(s=Le));a.avail_in>0&&s===Fe&&a.state.wrap>0&&0!==t[a.next_in];)Se.inflateReset(a),s=Se.inflate(a,r);switch(s){case Ie:case Be:case Le:case Ce:return this.onEnd(s),this.ended=!0,!1}if(o=a.avail_out,a.next_out&&(0===a.avail_out||s===Fe))if("string"===this.options.to){let t=Bt(a.output,a.next_out),e=a.next_out-t,n=It(a.output,t);a.next_out=e,a.avail_out=i-e,e&&a.output.set(a.output.subarray(t,t+e),0),this.onData(n)}else this.onData(a.output.length===a.next_out?a.output:a.output.subarray(0,a.next_out));if(s!==Ne||0!==o){if(s===Fe)return s=Se.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(0===a.avail_in)break}}return!0},He.prototype.onData=function(t){this.chunks.push(t)},He.prototype.onEnd=function(t){t===Ne&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=Tt(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};const{Deflate:Me,deflate:je,deflateRaw:Ke,gzip:Pe}=Vt;var Ye=Me,Ge=B;const Xe=new class{constructor(){this.added=0,this.init()}init(){this.added=0,this.deflate=new Ye,this.deflate.push("[",Ge.Z_NO_FLUSH)}addEvent(t){if(!t)throw new Error("Adding invalid event");const e=this.added>0?",":"";this.deflate.push(e+JSON.stringify(t),Ge.Z_SYNC_FLUSH),this.added++}finish(){if(this.deflate.push("]",Ge.Z_FINISH),this.deflate.err)throw this.deflate.err;const t=this.deflate.result;return this.init(),t}},Je={init:()=>(Xe.init(),""),addEvent:t=>Xe.addEvent(t),finish:()=>Xe.finish()};addEventListener("message",(function(t){const e=t.data.method,a=t.data.id,[i]=t.data.args?JSON.parse(t.data.args):[];if(e in Je&&"function"==typeof Je[e])try{const t=Je[e](i);postMessage({id:a,method:e,success:!0,response:t})}catch(t){postMessage({id:a,method:e,success:!1,response:t.message}),console.error(t)}})),postMessage({id:void 0,method:"init",success:!0,response:void 0});`;
3845
+ if (stickySession) {
3846
+ saveSession(session);
3847
+ }
3848
+
3849
+ return session;
3850
+ }
3875
3851
 
3876
3852
  /**
3877
- * Create an event buffer for replays.
3853
+ * Fetches a session from storage
3878
3854
  */
3879
- function createEventBuffer({ useCompression }) {
3880
- // eslint-disable-next-line no-restricted-globals
3881
- if (useCompression && window.Worker) {
3882
- const workerBlob = new Blob([workerString]);
3883
- const workerUrl = URL.createObjectURL(workerBlob);
3855
+ function fetchSession() {
3856
+ const hasSessionStorage = 'sessionStorage' in WINDOW;
3884
3857
 
3885
- (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Using compression worker');
3886
- const worker = new Worker(workerUrl);
3887
- return new EventBufferProxy(worker);
3858
+ if (!hasSessionStorage) {
3859
+ return null;
3888
3860
  }
3889
3861
 
3890
- (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Using simple buffer');
3891
- return new EventBufferArray();
3862
+ try {
3863
+ // This can throw if cookies are disabled
3864
+ const sessionStringFromStorage = WINDOW.sessionStorage.getItem(REPLAY_SESSION_KEY);
3865
+
3866
+ if (!sessionStringFromStorage) {
3867
+ return null;
3868
+ }
3869
+
3870
+ const sessionObj = JSON.parse(sessionStringFromStorage) ;
3871
+
3872
+ return makeSession(sessionObj);
3873
+ } catch (e) {
3874
+ return null;
3875
+ }
3892
3876
  }
3893
3877
 
3894
3878
  /**
3895
- * This proxy will try to use the compression worker, and fall back to use the simple buffer if an error occurs there.
3896
- * This can happen e.g. if the worker cannot be loaded.
3897
- * Exported only for testing.
3879
+ * Get or create a session
3898
3880
  */
3899
- class EventBufferProxy {
3900
-
3901
- constructor(worker) {
3902
- this._fallback = new EventBufferArray();
3903
- this._compression = new EventBufferCompressionWorker(worker);
3904
- this._used = this._fallback;
3881
+ function getSession({
3882
+ expiry,
3883
+ currentSession,
3884
+ stickySession,
3885
+ sessionSampleRate,
3886
+ errorSampleRate,
3887
+ }) {
3888
+ // If session exists and is passed, use it instead of always hitting session storage
3889
+ const session = currentSession || (stickySession && fetchSession());
3905
3890
 
3906
- void this._ensureWorkerIsLoaded();
3907
- }
3891
+ if (session) {
3892
+ // If there is a session, check if it is valid (e.g. "last activity" time
3893
+ // should be within the "session idle time", and "session started" time is
3894
+ // within "max session time").
3895
+ const isExpired = isSessionExpired(session, expiry);
3908
3896
 
3909
- /** @inheritDoc */
3910
- get pendingLength() {
3911
- return this._used.pendingLength;
3897
+ if (!isExpired) {
3898
+ return { type: 'saved', session };
3899
+ } else {
3900
+ (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Session has expired');
3901
+ }
3902
+ // Otherwise continue to create a new session
3912
3903
  }
3913
3904
 
3914
- /** @inheritDoc */
3915
- get pendingEvents() {
3916
- return this._used.pendingEvents;
3917
- }
3905
+ const newSession = createSession({
3906
+ stickySession,
3907
+ sessionSampleRate,
3908
+ errorSampleRate,
3909
+ });
3918
3910
 
3919
- /** @inheritDoc */
3920
- destroy() {
3921
- this._fallback.destroy();
3922
- this._compression.destroy();
3923
- }
3911
+ return { type: 'new', session: newSession };
3912
+ }
3924
3913
 
3925
- /**
3926
- * Add an event to the event buffer.
3927
- *
3928
- * Returns true if event was successfully added.
3929
- */
3930
- addEvent(event, isCheckout) {
3931
- return this._used.addEvent(event, isCheckout);
3914
+ /**
3915
+ * Add an event to the event buffer
3916
+ */
3917
+ async function addEvent(
3918
+ replay,
3919
+ event,
3920
+ isCheckout,
3921
+ ) {
3922
+ if (!replay.eventBuffer) {
3923
+ // This implies that `_isEnabled` is false
3924
+ return null;
3932
3925
  }
3933
3926
 
3934
- /** @inheritDoc */
3935
- finish() {
3936
- return this._used.finish();
3927
+ if (replay.isPaused()) {
3928
+ // Do not add to event buffer when recording is paused
3929
+ return null;
3937
3930
  }
3938
3931
 
3939
- /** Ensure the worker has loaded. */
3940
- async _ensureWorkerIsLoaded() {
3941
- try {
3942
- await this._compression.ensureReady();
3943
- } catch (error) {
3944
- // If the worker fails to load, we fall back to the simple buffer.
3945
- // Nothing more to do from our side here
3946
- (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Failed to load the compression worker, falling back to simple buffer');
3947
- return;
3948
- }
3949
-
3950
- // Compression worker is ready, we can use it
3951
- // Now we need to switch over the array buffer to the compression worker
3952
- const addEventPromises = [];
3953
- for (const event of this._fallback.pendingEvents) {
3954
- addEventPromises.push(this._compression.addEvent(event));
3955
- }
3932
+ // TODO: sadness -- we will want to normalize timestamps to be in ms -
3933
+ // requires coordination with frontend
3934
+ const isMs = event.timestamp > 9999999999;
3935
+ const timestampInMs = isMs ? event.timestamp : event.timestamp * 1000;
3956
3936
 
3957
- // We switch over to the compression buffer immediately - any further events will be added
3958
- // after the previously buffered ones
3959
- this._used = this._compression;
3937
+ // Throw out events that happen more than 5 minutes ago. This can happen if
3938
+ // page has been left open and idle for a long period of time and user
3939
+ // comes back to trigger a new session. The performance entries rely on
3940
+ // `performance.timeOrigin`, which is when the page first opened.
3941
+ if (timestampInMs + SESSION_IDLE_DURATION < new Date().getTime()) {
3942
+ return null;
3943
+ }
3960
3944
 
3961
- // Wait for original events to be re-added before resolving
3962
- await Promise.all(addEventPromises);
3945
+ // Only record earliest event if a new session was created, otherwise it
3946
+ // shouldn't be relevant
3947
+ const earliestEvent = replay.getContext().earliestEvent;
3948
+ if (replay.session && replay.session.segmentId === 0 && (!earliestEvent || timestampInMs < earliestEvent)) {
3949
+ replay.getContext().earliestEvent = timestampInMs;
3963
3950
  }
3951
+
3952
+ return replay.eventBuffer.addEvent(event, isCheckout);
3964
3953
  }
3965
3954
 
3966
- class EventBufferArray {
3955
+ /**
3956
+ * Create a breadcrumb for a replay.
3957
+ */
3958
+ function createBreadcrumb(
3959
+ breadcrumb,
3960
+ ) {
3961
+ return {
3962
+ timestamp: new Date().getTime() / 1000,
3963
+ type: 'default',
3964
+ ...breadcrumb,
3965
+ };
3966
+ }
3967
3967
 
3968
- constructor() {
3969
- this._events = [];
3968
+ /**
3969
+ * Add a breadcrumb event to replay.
3970
+ */
3971
+ function addBreadcrumbEvent(replay, breadcrumb) {
3972
+ if (breadcrumb.category === 'sentry.transaction') {
3973
+ return;
3970
3974
  }
3971
3975
 
3972
- get pendingLength() {
3973
- return this._events.length;
3976
+ if (breadcrumb.category === 'ui.click') {
3977
+ replay.triggerUserActivity();
3978
+ } else {
3979
+ replay.checkAndHandleExpiredSession();
3974
3980
  }
3975
3981
 
3976
- /**
3977
- * Returns the raw events that are buffered. In `EventBufferArray`, this is the
3978
- * same as `this._events`.
3979
- */
3980
- get pendingEvents() {
3981
- return this._events;
3982
- }
3982
+ replay.addUpdate(() => {
3983
+ void addEvent(replay, {
3984
+ type: EventType.Custom,
3985
+ // TODO: We were converting from ms to seconds for breadcrumbs, spans,
3986
+ // but maybe we should just keep them as milliseconds
3987
+ timestamp: (breadcrumb.timestamp || 0) * 1000,
3988
+ data: {
3989
+ tag: 'breadcrumb',
3990
+ payload: breadcrumb,
3991
+ },
3992
+ });
3983
3993
 
3984
- destroy() {
3985
- this._events = [];
3986
- }
3994
+ // Do not flush after console log messages
3995
+ return breadcrumb.category === 'console';
3996
+ });
3997
+ }
3987
3998
 
3988
- async addEvent(event, isCheckout) {
3989
- if (isCheckout) {
3990
- this._events = [event];
3999
+ const handleDomListener =
4000
+ (replay) =>
4001
+ (handlerData) => {
4002
+ if (!replay.isEnabled()) {
3991
4003
  return;
3992
4004
  }
3993
4005
 
3994
- this._events.push(event);
3995
- return;
3996
- }
4006
+ const result = handleDom(handlerData);
3997
4007
 
3998
- finish() {
3999
- return new Promise(resolve => {
4000
- // Make a copy of the events array reference and immediately clear the
4001
- // events member so that we do not lose new events while uploading
4002
- // attachment.
4003
- const eventsRet = this._events;
4004
- this._events = [];
4005
- resolve(JSON.stringify(eventsRet));
4006
- });
4007
- }
4008
- }
4008
+ if (!result) {
4009
+ return;
4010
+ }
4011
+
4012
+ addBreadcrumbEvent(replay, result);
4013
+ };
4009
4014
 
4010
4015
  /**
4011
- * Event buffer that uses a web worker to compress events.
4012
- * Exported only for testing.
4016
+ * An event handler to react to DOM events.
4013
4017
  */
4014
- class EventBufferCompressionWorker {
4015
- /**
4016
- * Keeps track of the list of events since the last flush that have not been compressed.
4017
- * For example, page is reloaded and a flush attempt is made, but
4018
- * `finish()` (and thus the flush), does not complete.
4019
- */
4020
- __init() {this._pendingEvents = [];}
4021
-
4022
- __init2() {this._eventBufferItemLength = 0;}
4023
- __init3() {this._id = 0;}
4018
+ function handleDom(handlerData) {
4019
+ // Taken from https://github.com/getsentry/sentry-javascript/blob/master/packages/browser/src/integrations/breadcrumbs.ts#L112
4020
+ let target;
4021
+ let targetNode;
4024
4022
 
4025
- constructor(worker) {EventBufferCompressionWorker.prototype.__init.call(this);EventBufferCompressionWorker.prototype.__init2.call(this);EventBufferCompressionWorker.prototype.__init3.call(this);
4026
- this._worker = worker;
4023
+ // Accessing event.target can throw (see getsentry/raven-js#838, #768)
4024
+ try {
4025
+ targetNode = getTargetNode(handlerData);
4026
+ target = htmlTreeAsString(targetNode);
4027
+ } catch (e) {
4028
+ target = '<unknown>';
4027
4029
  }
4028
4030
 
4029
- /**
4030
- * The number of raw events that are buffered. This may not be the same as
4031
- * the number of events that have been compresed in the worker because
4032
- * `addEvent` is async.
4033
- */
4034
- get pendingLength() {
4035
- return this._eventBufferItemLength;
4031
+ if (target.length === 0) {
4032
+ return null;
4036
4033
  }
4037
4034
 
4038
- /**
4039
- * Returns a list of the raw recording events that are being compressed.
4040
- */
4041
- get pendingEvents() {
4042
- return this._pendingEvents;
4035
+ return createBreadcrumb({
4036
+ category: `ui.${handlerData.name}`,
4037
+ message: target,
4038
+ data: {
4039
+ // Not sure why this errors, Node should be correct (Argument of type 'Node' is not assignable to parameter of type 'INode')
4040
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
4041
+ ...(targetNode ? { nodeId: record.mirror.getId(targetNode ) } : {}),
4042
+ },
4043
+ });
4044
+ }
4045
+
4046
+ function getTargetNode(handlerData) {
4047
+ if (isEventWithTarget(handlerData.event)) {
4048
+ return handlerData.event.target;
4043
4049
  }
4044
4050
 
4045
- /**
4046
- * Ensure the worker is ready (or not).
4047
- * This will either resolve when the worker is ready, or reject if an error occured.
4048
- */
4049
- ensureReady() {
4050
- return new Promise((resolve, reject) => {
4051
- this._worker.addEventListener(
4052
- 'message',
4053
- ({ data }) => {
4054
- if (data.success) {
4055
- resolve();
4056
- } else {
4057
- reject();
4058
- }
4059
- },
4060
- { once: true },
4061
- );
4051
+ return handlerData.event;
4052
+ }
4062
4053
 
4063
- this._worker.addEventListener(
4064
- 'error',
4065
- error => {
4066
- reject(error);
4054
+ function isEventWithTarget(event) {
4055
+ return !!(event ).target;
4056
+ }
4057
+
4058
+ /**
4059
+ * Create a "span" for each performance entry. The parent transaction is `this.replayEvent`.
4060
+ */
4061
+ function createPerformanceSpans(
4062
+ replay,
4063
+ entries,
4064
+ ) {
4065
+ return entries.map(({ type, start, end, name, data }) =>
4066
+ addEvent(replay, {
4067
+ type: EventType.Custom,
4068
+ timestamp: start,
4069
+ data: {
4070
+ tag: 'performanceSpan',
4071
+ payload: {
4072
+ op: type,
4073
+ description: name,
4074
+ startTimestamp: start,
4075
+ endTimestamp: end,
4076
+ data,
4067
4077
  },
4068
- { once: true },
4069
- );
4070
- });
4078
+ },
4079
+ }),
4080
+ );
4081
+ }
4082
+
4083
+ /**
4084
+ * Check whether a given request URL should be filtered out.
4085
+ */
4086
+ function shouldFilterRequest(replay, url) {
4087
+ // If we enabled the `traceInternals` experiment, we want to trace everything
4088
+ if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && replay.getOptions()._experiments.traceInternals) {
4089
+ return false;
4071
4090
  }
4072
4091
 
4073
- /**
4074
- * Destroy the event buffer.
4075
- */
4076
- destroy() {
4077
- (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Destroying compression worker');
4078
- this._worker.terminate();
4092
+ return !_isSentryRequest(url);
4093
+ }
4094
+
4095
+ /**
4096
+ * Checks wether a given URL belongs to the configured Sentry DSN.
4097
+ */
4098
+ function _isSentryRequest(url) {
4099
+ const client = getCurrentHub().getClient();
4100
+ const dsn = client && client.getDsn();
4101
+ return dsn ? url.includes(dsn.host) : false;
4102
+ }
4103
+
4104
+ /** only exported for tests */
4105
+ function handleFetch(handlerData) {
4106
+ if (!handlerData.endTimestamp) {
4107
+ return null;
4079
4108
  }
4080
4109
 
4081
- /**
4082
- * Add an event to the event buffer.
4083
- *
4084
- * Returns true if event was successfuly received and processed by worker.
4085
- */
4086
- async addEvent(event, isCheckout) {
4087
- if (isCheckout) {
4088
- // This event is a checkout, make sure worker buffer is cleared before
4089
- // proceeding.
4090
- await this._postMessage({
4091
- id: this._getAndIncrementId(),
4092
- method: 'init',
4093
- args: [],
4094
- });
4095
- }
4110
+ const { startTimestamp, endTimestamp, fetchData, response } = handlerData;
4096
4111
 
4097
- // Don't store checkout events in `_pendingEvents` because they are too large
4098
- if (!isCheckout) {
4099
- this._pendingEvents.push(event);
4112
+ return {
4113
+ type: 'resource.fetch',
4114
+ start: startTimestamp / 1000,
4115
+ end: endTimestamp / 1000,
4116
+ name: fetchData.url,
4117
+ data: {
4118
+ method: fetchData.method,
4119
+ statusCode: response.status,
4120
+ },
4121
+ };
4122
+ }
4123
+
4124
+ /**
4125
+ * Returns a listener to be added to `addInstrumentationHandler('fetch', listener)`.
4126
+ */
4127
+ function handleFetchSpanListener(replay) {
4128
+ return (handlerData) => {
4129
+ if (!replay.isEnabled()) {
4130
+ return;
4100
4131
  }
4101
4132
 
4102
- return this._sendEventToWorker(event);
4103
- }
4133
+ const result = handleFetch(handlerData);
4104
4134
 
4105
- /**
4106
- * Finish the event buffer and return the compressed data.
4107
- */
4108
- finish() {
4109
- return this._finishRequest(this._getAndIncrementId());
4110
- }
4135
+ if (result === null) {
4136
+ return;
4137
+ }
4111
4138
 
4112
- /**
4113
- * Post message to worker and wait for response before resolving promise.
4114
- */
4115
- _postMessage({ id, method, args }) {
4116
- return new Promise((resolve, reject) => {
4117
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
4118
- const listener = ({ data }) => {
4119
- if (data.method !== method) {
4120
- return;
4121
- }
4139
+ if (shouldFilterRequest(replay, result.name)) {
4140
+ return;
4141
+ }
4122
4142
 
4123
- // There can be multiple listeners for a single method, the id ensures
4124
- // that the response matches the caller.
4125
- if (data.id !== id) {
4126
- return;
4127
- }
4143
+ replay.addUpdate(() => {
4144
+ createPerformanceSpans(replay, [result]);
4145
+ // Returning true will cause `addUpdate` to not flush
4146
+ // We do not want network requests to cause a flush. This will prevent
4147
+ // recurring/polling requests from keeping the replay session alive.
4148
+ return true;
4149
+ });
4150
+ };
4151
+ }
4128
4152
 
4129
- // At this point, we'll always want to remove listener regardless of result status
4130
- this._worker.removeEventListener('message', listener);
4153
+ /**
4154
+ * Returns true if we think the given event is an error originating inside of rrweb.
4155
+ */
4156
+ function isRrwebError(event) {
4157
+ if (event.type || !event.exception || !event.exception.values || !event.exception.values.length) {
4158
+ return false;
4159
+ }
4131
4160
 
4132
- if (!data.success) {
4133
- // TODO: Do some error handling, not sure what
4134
- (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('[Replay]', data.response);
4161
+ // Check if any exception originates from rrweb
4162
+ return event.exception.values.some(exception => {
4163
+ if (!exception.stacktrace || !exception.stacktrace.frames || !exception.stacktrace.frames.length) {
4164
+ return false;
4165
+ }
4135
4166
 
4136
- reject(new Error('Error in compression worker'));
4137
- return;
4138
- }
4167
+ return exception.stacktrace.frames.some(frame => frame.filename && frame.filename.includes('/rrweb/src/'));
4168
+ });
4169
+ }
4139
4170
 
4140
- resolve(data.response);
4141
- };
4171
+ /**
4172
+ * Returns a listener to be added to `addGlobalEventProcessor(listener)`.
4173
+ */
4174
+ function handleGlobalEventListener(replay) {
4175
+ return (event) => {
4176
+ // Do not apply replayId to the root event
4177
+ if (event.type === REPLAY_EVENT_NAME) {
4178
+ // Replays have separate set of breadcrumbs, do not include breadcrumbs
4179
+ // from core SDK
4180
+ delete event.breadcrumbs;
4181
+ return event;
4182
+ }
4142
4183
 
4143
- let stringifiedArgs;
4144
- try {
4145
- stringifiedArgs = JSON.stringify(args);
4146
- } catch (err) {
4147
- (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('[Replay] Error when trying to stringify args', err);
4148
- stringifiedArgs = '[]';
4149
- }
4184
+ // Unless `captureExceptions` is enabled, we want to ignore errors coming from rrweb
4185
+ // As there can be a bunch of stuff going wrong in internals there, that we don't want to bubble up to users
4186
+ if (isRrwebError(event) && !replay.getOptions()._experiments.captureExceptions) {
4187
+ (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Ignoring error from rrweb internals', event);
4188
+ return null;
4189
+ }
4150
4190
 
4151
- // Note: we can't use `once` option because it's possible it needs to
4152
- // listen to multiple messages
4153
- this._worker.addEventListener('message', listener);
4154
- this._worker.postMessage({ id, method, args: stringifiedArgs });
4155
- });
4156
- }
4191
+ // Only tag transactions with replayId if not waiting for an error
4192
+ // @ts-ignore private
4193
+ if (!event.type || replay.recordingMode === 'session') {
4194
+ event.tags = { ...event.tags, replayId: replay.getSessionId() };
4195
+ }
4157
4196
 
4158
- /**
4159
- * Send the event to the worker.
4160
- */
4161
- async _sendEventToWorker(event) {
4162
- const promise = this._postMessage({
4163
- id: this._getAndIncrementId(),
4164
- method: 'addEvent',
4165
- args: [event],
4166
- });
4197
+ // Collect traceIds in _context regardless of `recordingMode` - if it's true,
4198
+ // _context gets cleared on every checkout
4199
+ if (event.type === 'transaction' && event.contexts && event.contexts.trace && event.contexts.trace.trace_id) {
4200
+ replay.getContext().traceIds.add(event.contexts.trace.trace_id );
4201
+ return event;
4202
+ }
4167
4203
 
4168
- // XXX: See note in `get length()`
4169
- this._eventBufferItemLength++;
4204
+ // no event type means error
4205
+ if (!event.type) {
4206
+ replay.getContext().errorIds.add(event.event_id );
4207
+ }
4170
4208
 
4171
- return promise;
4172
- }
4209
+ if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && replay.getOptions()._experiments.traceInternals) {
4210
+ const exc = getEventExceptionValues(event);
4211
+ addInternalBreadcrumb({
4212
+ message: `Tagging event (${event.event_id}) - ${event.message} - ${exc.type}: ${exc.value}`,
4213
+ });
4214
+ }
4173
4215
 
4174
- /**
4175
- * Finish the request and return the compressed data from the worker.
4176
- */
4177
- async _finishRequest(id) {
4178
- const promise = this._postMessage({ id, method: 'finish', args: [] });
4216
+ // Need to be very careful that this does not cause an infinite loop
4217
+ if (
4218
+ replay.recordingMode === 'error' &&
4219
+ event.exception &&
4220
+ event.message !== UNABLE_TO_SEND_REPLAY // ignore this error because otherwise we could loop indefinitely with trying to capture replay and failing
4221
+ ) {
4222
+ setTimeout(async () => {
4223
+ // Allow flush to complete before resuming as a session recording, otherwise
4224
+ // the checkout from `startRecording` may be included in the payload.
4225
+ // Prefer to keep the error replay as a separate (and smaller) segment
4226
+ // than the session replay.
4227
+ await replay.flushImmediate();
4179
4228
 
4180
- // XXX: See note in `get length()`
4181
- this._eventBufferItemLength = 0;
4229
+ if (replay.stopRecording()) {
4230
+ // Reset all "capture on error" configuration before
4231
+ // starting a new recording
4232
+ replay.recordingMode = 'session';
4233
+ replay.startRecording();
4234
+ }
4235
+ });
4236
+ }
4182
4237
 
4183
- await promise;
4238
+ return event;
4239
+ };
4240
+ }
4184
4241
 
4185
- this._pendingEvents = [];
4242
+ function addInternalBreadcrumb(arg) {
4243
+ const { category, level, message, ...rest } = arg;
4186
4244
 
4187
- return promise;
4188
- }
4245
+ addBreadcrumb({
4246
+ category: category || 'console',
4247
+ level: level || 'debug',
4248
+ message: `[debug]: ${message}`,
4249
+ ...rest,
4250
+ });
4251
+ }
4189
4252
 
4190
- /** Get the current ID and increment it for the next call. */
4191
- _getAndIncrementId() {
4192
- return this._id++;
4193
- }
4253
+ function getEventExceptionValues(event) {
4254
+ return {
4255
+ type: 'Unknown',
4256
+ value: 'n/a',
4257
+ ...(event.exception && event.exception.values && event.exception.values[0]),
4258
+ };
4194
4259
  }
4195
4260
 
4196
- /**
4197
- * Given an initial timestamp and an expiry duration, checks to see if current
4198
- * time should be considered as expired.
4199
- */
4200
- function isExpired(
4201
- initialTime,
4202
- expiry,
4203
- targetTime = +new Date(),
4204
- ) {
4205
- // Always expired if < 0
4206
- if (initialTime === null || expiry === undefined || expiry < 0) {
4207
- return true;
4208
- }
4261
+ function handleHistory(handlerData) {
4262
+ const { from, to } = handlerData;
4209
4263
 
4210
- // Never expires if == 0
4211
- if (expiry === 0) {
4212
- return false;
4213
- }
4264
+ const now = new Date().getTime() / 1000;
4214
4265
 
4215
- return initialTime + expiry <= targetTime;
4266
+ return {
4267
+ type: 'navigation.push',
4268
+ start: now,
4269
+ end: now,
4270
+ name: to,
4271
+ data: {
4272
+ previous: from,
4273
+ },
4274
+ };
4216
4275
  }
4217
4276
 
4218
4277
  /**
4219
- * Checks to see if session is expired
4278
+ * Returns a listener to be added to `addInstrumentationHandler('history', listener)`.
4220
4279
  */
4221
- function isSessionExpired(session, idleTimeout, targetTime = +new Date()) {
4222
- return (
4223
- // First, check that maximum session length has not been exceeded
4224
- isExpired(session.started, MAX_SESSION_LIFE, targetTime) ||
4225
- // check that the idle timeout has not been exceeded (i.e. user has
4226
- // performed an action within the last `idleTimeout` ms)
4227
- isExpired(session.lastActivity, idleTimeout, targetTime)
4228
- );
4229
- }
4280
+ function handleHistorySpanListener(replay) {
4281
+ return (handlerData) => {
4282
+ if (!replay.isEnabled()) {
4283
+ return;
4284
+ }
4230
4285
 
4231
- /**
4232
- * Save a session to session storage.
4233
- */
4234
- function saveSession(session) {
4235
- const hasSessionStorage = 'sessionStorage' in WINDOW;
4236
- if (!hasSessionStorage) {
4237
- return;
4238
- }
4286
+ const result = handleHistory(handlerData);
4239
4287
 
4240
- try {
4241
- WINDOW.sessionStorage.setItem(REPLAY_SESSION_KEY, JSON.stringify(session));
4242
- } catch (e) {
4243
- // Ignore potential SecurityError exceptions
4244
- }
4245
- }
4288
+ if (result === null) {
4289
+ return;
4290
+ }
4246
4291
 
4247
- /**
4248
- * Given a sample rate, returns true if replay should be sampled.
4249
- *
4250
- * 1.0 = 100% sampling
4251
- * 0.0 = 0% sampling
4252
- */
4253
- function isSampled(sampleRate) {
4254
- if (sampleRate === undefined) {
4255
- return false;
4256
- }
4292
+ // Need to collect visited URLs
4293
+ replay.getContext().urls.push(result.name);
4294
+ replay.triggerUserActivity();
4257
4295
 
4258
- // Math.random() returns a number in range of 0 to 1 (inclusive of 0, but not 1)
4259
- return Math.random() < sampleRate;
4296
+ replay.addUpdate(() => {
4297
+ createPerformanceSpans(replay, [result]);
4298
+ // Returning false to flush
4299
+ return false;
4300
+ });
4301
+ };
4260
4302
  }
4261
4303
 
4262
- /**
4263
- * Get a session with defaults & applied sampling.
4264
- */
4265
- function makeSession(session) {
4266
- const now = new Date().getTime();
4267
- const id = session.id || uuid4();
4268
- // Note that this means we cannot set a started/lastActivity of `0`, but this should not be relevant outside of tests.
4269
- const started = session.started || now;
4270
- const lastActivity = session.lastActivity || now;
4271
- const segmentId = session.segmentId || 0;
4272
- const sampled = session.sampled;
4304
+ let _LAST_BREADCRUMB = null;
4273
4305
 
4274
- return {
4275
- id,
4276
- started,
4277
- lastActivity,
4278
- segmentId,
4279
- sampled,
4306
+ const handleScopeListener =
4307
+ (replay) =>
4308
+ (scope) => {
4309
+ if (!replay.isEnabled()) {
4310
+ return;
4311
+ }
4312
+
4313
+ const result = handleScope(scope);
4314
+
4315
+ if (!result) {
4316
+ return;
4317
+ }
4318
+
4319
+ addBreadcrumbEvent(replay, result);
4280
4320
  };
4281
- }
4282
4321
 
4283
4322
  /**
4284
- * Get the sampled status for a session based on sample rates & current sampled status.
4323
+ * An event handler to handle scope changes.
4285
4324
  */
4286
- function getSessionSampleType(sessionSampleRate, errorSampleRate) {
4287
- return isSampled(sessionSampleRate) ? 'session' : isSampled(errorSampleRate) ? 'error' : false;
4288
- }
4325
+ function handleScope(scope) {
4326
+ const newBreadcrumb = scope.getLastBreadcrumb();
4289
4327
 
4290
- /**
4291
- * Create a new session, which in its current implementation is a Sentry event
4292
- * that all replays will be saved to as attachments. Currently, we only expect
4293
- * one of these Sentry events per "replay session".
4294
- */
4295
- function createSession({ sessionSampleRate, errorSampleRate, stickySession = false }) {
4296
- const sampled = getSessionSampleType(sessionSampleRate, errorSampleRate);
4297
- const session = makeSession({
4298
- sampled,
4299
- });
4328
+ // Listener can be called when breadcrumbs have not changed, so we store the
4329
+ // reference to the last crumb and only return a crumb if it has changed
4330
+ if (_LAST_BREADCRUMB === newBreadcrumb || !newBreadcrumb) {
4331
+ return null;
4332
+ }
4300
4333
 
4301
- (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`[Replay] Creating new session: ${session.id}`);
4334
+ _LAST_BREADCRUMB = newBreadcrumb;
4302
4335
 
4303
- if (stickySession) {
4304
- saveSession(session);
4336
+ if (
4337
+ newBreadcrumb.category &&
4338
+ (['fetch', 'xhr', 'sentry.event', 'sentry.transaction'].includes(newBreadcrumb.category) ||
4339
+ newBreadcrumb.category.startsWith('ui.'))
4340
+ ) {
4341
+ return null;
4305
4342
  }
4306
4343
 
4307
- return session;
4344
+ return createBreadcrumb(newBreadcrumb);
4308
4345
  }
4309
4346
 
4310
- /**
4311
- * Fetches a session from storage
4312
- */
4313
- function fetchSession() {
4314
- const hasSessionStorage = 'sessionStorage' in WINDOW;
4347
+ // From sentry-javascript
4348
+ // e.g. https://github.com/getsentry/sentry-javascript/blob/c7fc025bf9fa8c073fdb56351808ce53909fbe45/packages/utils/src/instrument.ts#L180
4315
4349
 
4316
- if (!hasSessionStorage) {
4350
+ function handleXhr(handlerData) {
4351
+ if (handlerData.xhr.__sentry_own_request__) {
4352
+ // Taken from sentry-javascript
4353
+ // Only capture non-sentry requests
4317
4354
  return null;
4318
4355
  }
4319
4356
 
4320
- try {
4321
- // This can throw if cookies are disabled
4322
- const sessionStringFromStorage = WINDOW.sessionStorage.getItem(REPLAY_SESSION_KEY);
4357
+ if (handlerData.startTimestamp) {
4358
+ // TODO: See if this is still needed
4359
+ handlerData.xhr.__sentry_xhr__ = handlerData.xhr.__sentry_xhr__ || {};
4360
+ handlerData.xhr.__sentry_xhr__.startTimestamp = handlerData.startTimestamp;
4361
+ }
4323
4362
 
4324
- if (!sessionStringFromStorage) {
4325
- return null;
4326
- }
4363
+ if (!handlerData.endTimestamp) {
4364
+ return null;
4365
+ }
4327
4366
 
4328
- const sessionObj = JSON.parse(sessionStringFromStorage) ;
4367
+ const { method, url, status_code: statusCode } = handlerData.xhr.__sentry_xhr__ || {};
4329
4368
 
4330
- return makeSession(sessionObj);
4331
- } catch (e) {
4369
+ if (url === undefined) {
4332
4370
  return null;
4333
4371
  }
4372
+
4373
+ const timestamp = handlerData.xhr.__sentry_xhr__
4374
+ ? handlerData.xhr.__sentry_xhr__.startTimestamp || 0
4375
+ : handlerData.endTimestamp;
4376
+
4377
+ return {
4378
+ type: 'resource.xhr',
4379
+ name: url,
4380
+ start: timestamp / 1000,
4381
+ end: handlerData.endTimestamp / 1000,
4382
+ data: {
4383
+ method,
4384
+ statusCode,
4385
+ },
4386
+ };
4334
4387
  }
4335
4388
 
4336
4389
  /**
4337
- * Get or create a session
4390
+ * Returns a listener to be added to `addInstrumentationHandler('xhr', listener)`.
4338
4391
  */
4339
- function getSession({
4340
- expiry,
4341
- currentSession,
4342
- stickySession,
4343
- sessionSampleRate,
4344
- errorSampleRate,
4345
- }) {
4346
- // If session exists and is passed, use it instead of always hitting session storage
4347
- const session = currentSession || (stickySession && fetchSession());
4392
+ function handleXhrSpanListener(replay) {
4393
+ return (handlerData) => {
4394
+ if (!replay.isEnabled()) {
4395
+ return;
4396
+ }
4348
4397
 
4349
- if (session) {
4350
- // If there is a session, check if it is valid (e.g. "last activity" time
4351
- // should be within the "session idle time", and "session started" time is
4352
- // within "max session time").
4353
- const isExpired = isSessionExpired(session, expiry);
4398
+ const result = handleXhr(handlerData);
4354
4399
 
4355
- if (!isExpired) {
4356
- return { type: 'saved', session };
4357
- } else {
4358
- (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Session has expired');
4400
+ if (result === null) {
4401
+ return;
4359
4402
  }
4360
- // Otherwise continue to create a new session
4361
- }
4362
4403
 
4363
- const newSession = createSession({
4364
- stickySession,
4365
- sessionSampleRate,
4366
- errorSampleRate,
4367
- });
4404
+ if (shouldFilterRequest(replay, result.name)) {
4405
+ return;
4406
+ }
4368
4407
 
4369
- return { type: 'new', session: newSession };
4408
+ replay.addUpdate(() => {
4409
+ createPerformanceSpans(replay, [result]);
4410
+ // Returning true will cause `addUpdate` to not flush
4411
+ // We do not want network requests to cause a flush. This will prevent
4412
+ // recurring/polling requests from keeping the replay session alive.
4413
+ return true;
4414
+ });
4415
+ };
4416
+ }
4417
+
4418
+ /**
4419
+ * Add global listeners that cannot be removed.
4420
+ */
4421
+ function addGlobalListeners(replay) {
4422
+ // Listeners from core SDK //
4423
+ const scope = getCurrentHub().getScope();
4424
+ if (scope) {
4425
+ scope.addScopeListener(handleScopeListener(replay));
4426
+ }
4427
+ addInstrumentationHandler('dom', handleDomListener(replay));
4428
+ addInstrumentationHandler('fetch', handleFetchSpanListener(replay));
4429
+ addInstrumentationHandler('xhr', handleXhrSpanListener(replay));
4430
+ addInstrumentationHandler('history', handleHistorySpanListener(replay));
4431
+
4432
+ // Tag all (non replay) events that get sent to Sentry with the current
4433
+ // replay ID so that we can reference them later in the UI
4434
+ addGlobalEventProcessor(handleGlobalEventListener(replay));
4370
4435
  }
4371
4436
 
4372
4437
  /**
@@ -4993,7 +5058,7 @@ class ReplayContainer {
4993
5058
  recordingOptions,
4994
5059
  }
4995
5060
 
4996
- ) {ReplayContainer.prototype.__init.call(this);ReplayContainer.prototype.__init2.call(this);ReplayContainer.prototype.__init3.call(this);ReplayContainer.prototype.__init4.call(this);ReplayContainer.prototype.__init5.call(this);ReplayContainer.prototype.__init6.call(this);ReplayContainer.prototype.__init7.call(this);ReplayContainer.prototype.__init8.call(this);ReplayContainer.prototype.__init9.call(this);ReplayContainer.prototype.__init10.call(this);ReplayContainer.prototype.__init11.call(this);ReplayContainer.prototype.__init12.call(this);ReplayContainer.prototype.__init13.call(this);ReplayContainer.prototype.__init14.call(this);ReplayContainer.prototype.__init15.call(this);ReplayContainer.prototype.__init16.call(this);ReplayContainer.prototype.__init17.call(this);
5061
+ ) {ReplayContainer.prototype.__init.call(this);ReplayContainer.prototype.__init2.call(this);ReplayContainer.prototype.__init3.call(this);ReplayContainer.prototype.__init4.call(this);ReplayContainer.prototype.__init5.call(this);ReplayContainer.prototype.__init6.call(this);ReplayContainer.prototype.__init7.call(this);ReplayContainer.prototype.__init8.call(this);ReplayContainer.prototype.__init9.call(this);ReplayContainer.prototype.__init10.call(this);ReplayContainer.prototype.__init11.call(this);ReplayContainer.prototype.__init12.call(this);ReplayContainer.prototype.__init13.call(this);ReplayContainer.prototype.__init14.call(this);ReplayContainer.prototype.__init15.call(this);ReplayContainer.prototype.__init16.call(this);
4997
5062
  this._recordingOptions = recordingOptions;
4998
5063
  this._options = options;
4999
5064
 
@@ -5091,12 +5156,18 @@ class ReplayContainer {
5091
5156
  * Returns true if it was stopped, else false.
5092
5157
  */
5093
5158
  stopRecording() {
5094
- if (this._stopRecording) {
5095
- this._stopRecording();
5096
- return true;
5097
- }
5159
+ try {
5160
+ if (this._stopRecording) {
5161
+ this._stopRecording();
5162
+ this._stopRecording = undefined;
5163
+ return true;
5164
+ }
5098
5165
 
5099
- return false;
5166
+ return false;
5167
+ } catch (err) {
5168
+ this._handleException(err);
5169
+ return false;
5170
+ }
5100
5171
  }
5101
5172
 
5102
5173
  /**
@@ -5108,7 +5179,7 @@ class ReplayContainer {
5108
5179
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Stopping Replays');
5109
5180
  this._isEnabled = false;
5110
5181
  this._removeListeners();
5111
- this._stopRecording && this._stopRecording();
5182
+ this.stopRecording();
5112
5183
  this.eventBuffer && this.eventBuffer.destroy();
5113
5184
  this.eventBuffer = null;
5114
5185
  this._debouncedFlush.cancel();
@@ -5124,14 +5195,7 @@ class ReplayContainer {
5124
5195
  */
5125
5196
  pause() {
5126
5197
  this._isPaused = true;
5127
- try {
5128
- if (this._stopRecording) {
5129
- this._stopRecording();
5130
- this._stopRecording = undefined;
5131
- }
5132
- } catch (err) {
5133
- this._handleException(err);
5134
- }
5198
+ this.stopRecording();
5135
5199
  }
5136
5200
 
5137
5201
  /**
@@ -5195,7 +5259,7 @@ class ReplayContainer {
5195
5259
  }
5196
5260
 
5197
5261
  // Otherwise... recording was never suspended, continue as normalish
5198
- this._checkAndHandleExpiredSession();
5262
+ this.checkAndHandleExpiredSession();
5199
5263
 
5200
5264
  this._updateSessionActivity();
5201
5265
  }
@@ -5217,6 +5281,44 @@ class ReplayContainer {
5217
5281
  return this.session && this.session.id;
5218
5282
  }
5219
5283
 
5284
+ /**
5285
+ * Checks if recording should be stopped due to user inactivity. Otherwise
5286
+ * check if session is expired and create a new session if so. Triggers a new
5287
+ * full snapshot on new session.
5288
+ *
5289
+ * Returns true if session is not expired, false otherwise.
5290
+ * @hidden
5291
+ */
5292
+ checkAndHandleExpiredSession({ expiry = SESSION_IDLE_DURATION } = {}) {
5293
+ const oldSessionId = this.getSessionId();
5294
+
5295
+ // Prevent starting a new session if the last user activity is older than
5296
+ // MAX_SESSION_LIFE. Otherwise non-user activity can trigger a new
5297
+ // session+recording. This creates noisy replays that do not have much
5298
+ // content in them.
5299
+ if (this._lastActivity && isExpired(this._lastActivity, MAX_SESSION_LIFE)) {
5300
+ // Pause recording
5301
+ this.pause();
5302
+ return;
5303
+ }
5304
+
5305
+ // --- There is recent user activity --- //
5306
+ // This will create a new session if expired, based on expiry length
5307
+ this._loadSession({ expiry });
5308
+
5309
+ // Session was expired if session ids do not match
5310
+ const expired = oldSessionId !== this.getSessionId();
5311
+
5312
+ if (!expired) {
5313
+ return true;
5314
+ }
5315
+
5316
+ // Session is expired, trigger a full snapshot (which will create a new session)
5317
+ this._triggerFullSnapshot();
5318
+
5319
+ return false;
5320
+ }
5321
+
5220
5322
  /** A wrapper to conditionally capture exceptions. */
5221
5323
  _handleException(error) {
5222
5324
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('[Replay]', error);
@@ -5286,19 +5388,7 @@ class ReplayContainer {
5286
5388
 
5287
5389
  // There is no way to remove these listeners, so ensure they are only added once
5288
5390
  if (!this._hasInitializedCoreListeners) {
5289
- // Listeners from core SDK //
5290
- const scope = getCurrentHub().getScope();
5291
- if (scope) {
5292
- scope.addScopeListener(this._handleCoreBreadcrumbListener('scope'));
5293
- }
5294
- addInstrumentationHandler('dom', this._handleCoreBreadcrumbListener('dom'));
5295
- addInstrumentationHandler('fetch', handleFetchSpanListener(this));
5296
- addInstrumentationHandler('xhr', handleXhrSpanListener(this));
5297
- addInstrumentationHandler('history', handleHistorySpanListener(this));
5298
-
5299
- // Tag all (non replay) events that get sent to Sentry with the current
5300
- // replay ID so that we can reference them later in the UI
5301
- addGlobalEventProcessor(handleGlobalEventListener(this));
5391
+ addGlobalListeners(this);
5302
5392
 
5303
5393
  this._hasInitializedCoreListeners = true;
5304
5394
  }
@@ -5345,7 +5435,7 @@ class ReplayContainer {
5345
5435
  isCheckout,
5346
5436
  ) => {
5347
5437
  // If this is false, it means session is expired, create and a new session and wait for checkout
5348
- if (!this._checkAndHandleExpiredSession()) {
5438
+ if (!this.checkAndHandleExpiredSession()) {
5349
5439
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('[Replay] Received replay event after session expired.');
5350
5440
 
5351
5441
  return;
@@ -5440,51 +5530,6 @@ class ReplayContainer {
5440
5530
  this._doChangeToForegroundTasks(breadcrumb);
5441
5531
  };}
5442
5532
 
5443
- /**
5444
- * Handler for Sentry Core SDK events.
5445
- *
5446
- * These events will create breadcrumb-like objects in the recording.
5447
- */
5448
- __init16() {this._handleCoreBreadcrumbListener =
5449
- (type) =>
5450
- (handlerData) => {
5451
- if (!this._isEnabled) {
5452
- return;
5453
- }
5454
-
5455
- const result = breadcrumbHandler(type, handlerData);
5456
-
5457
- if (result === null) {
5458
- return;
5459
- }
5460
-
5461
- if (result.category === 'sentry.transaction') {
5462
- return;
5463
- }
5464
-
5465
- if (result.category === 'ui.click') {
5466
- this.triggerUserActivity();
5467
- } else {
5468
- this._checkAndHandleExpiredSession();
5469
- }
5470
-
5471
- this.addUpdate(() => {
5472
- void addEvent(this, {
5473
- type: EventType.Custom,
5474
- // TODO: We were converting from ms to seconds for breadcrumbs, spans,
5475
- // but maybe we should just keep them as milliseconds
5476
- timestamp: (result.timestamp || 0) * 1000,
5477
- data: {
5478
- tag: 'breadcrumb',
5479
- payload: result,
5480
- },
5481
- });
5482
-
5483
- // Do not flush after console log messages
5484
- return result.category === 'console';
5485
- });
5486
- };}
5487
-
5488
5533
  /**
5489
5534
  * Tasks to run when we consider a page to be hidden (via blurring and/or visibility)
5490
5535
  */
@@ -5513,7 +5558,7 @@ class ReplayContainer {
5513
5558
  return;
5514
5559
  }
5515
5560
 
5516
- const isSessionActive = this._checkAndHandleExpiredSession({
5561
+ const isSessionActive = this.checkAndHandleExpiredSession({
5517
5562
  expiry: VISIBILITY_CHANGE_TIMEOUT,
5518
5563
  });
5519
5564
 
@@ -5535,8 +5580,12 @@ class ReplayContainer {
5535
5580
  * create a new Replay event.
5536
5581
  */
5537
5582
  _triggerFullSnapshot() {
5538
- (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Taking full rrweb snapshot');
5539
- record.takeFullSnapshot(true);
5583
+ try {
5584
+ (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Taking full rrweb snapshot');
5585
+ record.takeFullSnapshot(true);
5586
+ } catch (err) {
5587
+ this._handleException(err);
5588
+ }
5540
5589
  }
5541
5590
 
5542
5591
  /**
@@ -5584,43 +5633,6 @@ class ReplayContainer {
5584
5633
  return Promise.all(createPerformanceSpans(this, createPerformanceEntries(entries)));
5585
5634
  }
5586
5635
 
5587
- /**
5588
- * Checks if recording should be stopped due to user inactivity. Otherwise
5589
- * check if session is expired and create a new session if so. Triggers a new
5590
- * full snapshot on new session.
5591
- *
5592
- * Returns true if session is not expired, false otherwise.
5593
- */
5594
- _checkAndHandleExpiredSession({ expiry = SESSION_IDLE_DURATION } = {}) {
5595
- const oldSessionId = this.getSessionId();
5596
-
5597
- // Prevent starting a new session if the last user activity is older than
5598
- // MAX_SESSION_LIFE. Otherwise non-user activity can trigger a new
5599
- // session+recording. This creates noisy replays that do not have much
5600
- // content in them.
5601
- if (this._lastActivity && isExpired(this._lastActivity, MAX_SESSION_LIFE)) {
5602
- // Pause recording
5603
- this.pause();
5604
- return;
5605
- }
5606
-
5607
- // --- There is recent user activity --- //
5608
- // This will create a new session if expired, based on expiry length
5609
- this._loadSession({ expiry });
5610
-
5611
- // Session was expired if session ids do not match
5612
- const expired = oldSessionId !== this.getSessionId();
5613
-
5614
- if (!expired) {
5615
- return true;
5616
- }
5617
-
5618
- // Session is expired, trigger a full snapshot (which will create a new session)
5619
- this._triggerFullSnapshot();
5620
-
5621
- return false;
5622
- }
5623
-
5624
5636
  /**
5625
5637
  * Only flush if `this.recordingMode === 'session'`
5626
5638
  */
@@ -5733,13 +5745,13 @@ class ReplayContainer {
5733
5745
  * Flush recording data to Sentry. Creates a lock so that only a single flush
5734
5746
  * can be active at a time. Do not call this directly.
5735
5747
  */
5736
- __init17() {this._flush = async () => {
5748
+ __init16() {this._flush = async () => {
5737
5749
  if (!this._isEnabled) {
5738
5750
  // This can happen if e.g. the replay was stopped because of exceeding the retry limit
5739
5751
  return;
5740
5752
  }
5741
5753
 
5742
- if (!this._checkAndHandleExpiredSession()) {
5754
+ if (!this.checkAndHandleExpiredSession()) {
5743
5755
  (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('[Replay] Attempting to finish replay event after session expired.');
5744
5756
  return;
5745
5757
  }
@@ -5876,8 +5888,8 @@ class Replay {
5876
5888
  flushMinDelay,
5877
5889
  flushMaxDelay,
5878
5890
  stickySession,
5879
- sessionSampleRate: DEFAULT_SESSION_SAMPLE_RATE,
5880
- errorSampleRate: DEFAULT_ERROR_SAMPLE_RATE,
5891
+ sessionSampleRate: 0,
5892
+ errorSampleRate: 0,
5881
5893
  useCompression,
5882
5894
  maskAllText: typeof maskAllText === 'boolean' ? maskAllText : !maskTextSelector,
5883
5895
  blockAllMedia,