@amityco/ts-sdk 6.17.3-e382dbe.0 → 6.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/.env +26 -26
  2. package/dist/@types/domains/client.d.ts +1 -1
  3. package/dist/@types/domains/client.d.ts.map +1 -1
  4. package/dist/@types/domains/community.d.ts +1 -3
  5. package/dist/@types/domains/community.d.ts.map +1 -1
  6. package/dist/@types/domains/story.d.ts +3 -3
  7. package/dist/@types/domains/story.d.ts.map +1 -1
  8. package/dist/client/api/accessTokenExpiryWatcher.d.ts +1 -1
  9. package/dist/client/api/accessTokenExpiryWatcher.d.ts.map +1 -1
  10. package/dist/client/api/login.d.ts.map +1 -1
  11. package/dist/client/api/renewal.d.ts.map +1 -1
  12. package/dist/client/utils/setClientToken.d.ts.map +1 -1
  13. package/dist/index.cjs.js +35 -26
  14. package/dist/index.esm.js +35 -26
  15. package/dist/index.umd.js +2 -2
  16. package/dist/storyRepository/observers/getGlobalStoryTargets/GlobalStoryLiveCollectionController.d.ts.map +1 -1
  17. package/dist/storyRepository/utils/StoryComputedValue.d.ts +0 -2
  18. package/dist/storyRepository/utils/StoryComputedValue.d.ts.map +1 -1
  19. package/dist/storyRepository/utils/convertStoryPayloadToRaw.d.ts.map +1 -1
  20. package/dist/utils/linkedObject/storyTargetLinkedObject.d.ts.map +1 -1
  21. package/package.json +1 -1
  22. package/src/@types/domains/client.ts +1 -5
  23. package/src/@types/domains/community.ts +2 -3
  24. package/src/@types/domains/story.ts +5 -3
  25. package/src/client/api/accessTokenExpiryWatcher.ts +7 -2
  26. package/src/client/api/login.ts +1 -5
  27. package/src/client/api/renewal.ts +2 -5
  28. package/src/client/utils/setClientToken.ts +0 -2
  29. package/src/storyRepository/observers/getGlobalStoryTargets/GlobalStoryLiveCollectionController.ts +7 -8
  30. package/src/storyRepository/utils/StoryComputedValue.ts +0 -8
  31. package/src/storyRepository/utils/convertStoryPayloadToRaw.ts +23 -0
  32. package/src/utils/linkedObject/storyTargetLinkedObject.ts +0 -1
package/dist/index.umd.js CHANGED
@@ -1,6 +1,6 @@
1
- var Amity=function(e){"use strict";const t=Object.freeze({FILE:"file",IMAGE:"image",VIDEO:"video"}),r=Object.freeze({"1080P":"1080p","720P":"720p","480P":"480p","360P":"360p",ORIGINAL:"original"}),n=Object.freeze({UPLOADED:"uploaded",TRANSCODING:"transcoding",TRANSCODED:"transcoded",TRANSCODE_FAILED:"transcodeFailed"}),s=Object.freeze({LOW:"low",MEDIUM:"medium",HIGH:"high",ORIGINAL:"original"}),i=Object.freeze({ONLY_ADMIN_CAN_POST:"ONLY_ADMIN_CAN_POST",ADMIN_REVIEW_POST_REQUIRED:"ADMIN_REVIEW_POST_REQUIRED",ANYONE_CAN_POST:"ANYONE_CAN_POST"}),a=Object.freeze({ONLY_ADMIN_CAN_POST:{needApprovalOnPostCreation:!1,onlyAdminCanPost:!0},ADMIN_REVIEW_POST_REQUIRED:{needApprovalOnPostCreation:!0,onlyAdminCanPost:!1},ANYONE_CAN_POST:{needApprovalOnPostCreation:!1,onlyAdminCanPost:!1}}),o="ONLY_ADMIN_CAN_POST",l=Object.freeze({STORY:"story",CLIP:"clip",CHAT:"chat",POST:"post",MESSAGE:"message"}),c=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",AUDIO:"audio",CUSTOM:"custom"}),d=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",LIVESTREAM:"liveStream",POLL:"poll",CUSTOM:"custom"});const u=function(){try{return"v6.17.2-umd"}catch(e){return"__dev__"}}(),h=5,f="cache_then_server",p="For using Live Collection feature you need to enable Cache!",g="Observing unsynced object is not supported by Live Object.",m=864e5,y=6e5,v="dead",b=2e3,w=6e4,E=e=>JSON.stringify(e,((e,t)=>{return"object"==typeof t?(r=t,Object.keys(r).sort().reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:r[t]})),{})):t;var r})),S=e=>JSON.parse(e),T=(e,t)=>e===t||!(!e||!t)&&("object"==typeof e&&Object.keys(e).every((r=>T(e[r],t[r])))),C=e=>[400400,400300].includes(e),k="function"==typeof atob,A="function"==typeof btoa,I="function"==typeof Buffer,_="function"==typeof TextDecoder?new TextDecoder:void 0,R="function"==typeof TextEncoder?new TextEncoder:void 0,L=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),D=(e=>{let t={};return e.forEach(((e,r)=>t[e]=r)),t})(L),x=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,O=String.fromCharCode.bind(String),P="function"==typeof Uint8Array.from?Uint8Array.from.bind(Uint8Array):(e,t=(e=>e))=>new Uint8Array(Array.prototype.slice.call(e,0).map(t)),M=e=>e.replace(/[^A-Za-z0-9\+\/]/g,""),F=A?e=>btoa(e):I?e=>Buffer.from(e,"binary").toString("base64"):e=>{let t,r,n,s,i="";const a=e.length%3;for(let a=0;a<e.length;){if((r=e.charCodeAt(a++))>255||(n=e.charCodeAt(a++))>255||(s=e.charCodeAt(a++))>255)throw new TypeError("invalid character found");t=r<<16|n<<8|s,i+=L[t>>18&63]+L[t>>12&63]+L[t>>6&63]+L[63&t]}return a?i.slice(0,a-3)+"===".substring(a):i},U=I?e=>Buffer.from(e).toString("base64"):e=>{let t=[];for(let r=0,n=e.length;r<n;r+=4096)t.push(O.apply(null,e.subarray(r,r+4096)));return F(t.join(""))},N=e=>{if(e.length<2)return(t=e.charCodeAt(0))<128?e:t<2048?O(192|t>>>6)+O(128|63&t):O(224|t>>>12&15)+O(128|t>>>6&63)+O(128|63&t);var t=65536+1024*(e.charCodeAt(0)-55296)+(e.charCodeAt(1)-56320);return O(240|t>>>18&7)+O(128|t>>>12&63)+O(128|t>>>6&63)+O(128|63&t)},B=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,j=I?e=>Buffer.from(e,"utf8").toString("base64"):R?e=>U(R.encode(e)):e=>F(e.replace(B,N)),$=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,q=e=>{switch(e.length){case 4:var t=((7&e.charCodeAt(0))<<18|(63&e.charCodeAt(1))<<12|(63&e.charCodeAt(2))<<6|63&e.charCodeAt(3))-65536;return O(55296+(t>>>10))+O(56320+(1023&t));case 3:return O((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return O((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},K=k?e=>atob(M(e)):I?e=>Buffer.from(e,"base64").toString("binary"):e=>{if(e=e.replace(/\s+/g,""),!x.test(e))throw new TypeError("malformed base64.");e+="==".slice(2-(3&e.length));let t,r,n,s="";for(let i=0;i<e.length;)t=D[e.charAt(i++)]<<18|D[e.charAt(i++)]<<12|(r=D[e.charAt(i++)])<<6|(n=D[e.charAt(i++)]),s+=64===r?O(t>>16&255):64===n?O(t>>16&255,t>>8&255):O(t>>16&255,t>>8&255,255&t);return s},G=I?e=>P(Buffer.from(e,"base64")):e=>P(K(e),(e=>e.charCodeAt(0))),H=I?e=>Buffer.from(e,"base64").toString("utf8"):_?e=>_.decode(G(e)):e=>K(e).replace($,q),V=e=>H(M(e.replace(/[-_]/g,(e=>"-"==e?"+":"/")))),z=e=>["skip"].some((t=>t in e)),W=e=>["after","before","first","last","limit"].some((t=>t in e)),Y=e=>"limit"in e,Q=e=>(null==e?void 0:e.hasOwnProperty("data"))&&(null==e?void 0:e.hasOwnProperty("nextPage"))&&(null==e?void 0:e.hasOwnProperty("prevPage")),X=(e,t)=>{var r;if(!e||!Object.keys(e).length)return;let n={};return"skiplimit"===t?n={skip:null!==(r=e.after)&&void 0!==r?r:0,limit:e.limit}:"afterbefore"===t&&W(e)?((null==e?void 0:e.before)&&(n=Object.assign(Object.assign({},n),{before:e.before})),(null==e?void 0:e.after)&&(n=Object.assign(Object.assign({},n),{after:e.after})),Number.isNaN(Number(null==e?void 0:e.limit))||(n=Object.assign(Object.assign({},n),{limit:e.limit}))):"afterbeforeraw"===t&&(n=e),Object.keys(n).length?((e,t=!1)=>t?(e=>e.replace(/=/g,"").replace(/[+\/]/g,(e=>"+"==e?"-":"_")))(j(e)):j(e))(JSON.stringify(n)):void 0},J=e=>{if(!e)return;const t=JSON.parse(V(e));if(z(t))return{after:t.skip,limit:t.limit};if(W(t)){if("before"in t)return{before:t.before,limit:t.last};if("after"in t)return{after:t.after,limit:t.first}}},Z=e=>{if(!e)return;const t=JSON.parse(V(e));return Y(t)?t:void 0},ee=e=>"locally"in e,te=e=>"optimistically"in e,re=e=>ee(e)||te(e),ne=e=>null==e?void 0:e.hasOwnProperty("cachedAt"),se=(e,t=6e4)=>{var r;return Date.now()-(null!==(r=null==e?void 0:e.cachedAt)&&void 0!==r?r:0)<=t},ie=(e,...t)=>({func:e,args:t}),ae=(e,t=6e4)=>"cache_only"===e?{lifeSpan:1/0}:{lifeSpan:t<w?w:t},oe=({func:e,args:t},r,n=ae("cache_then_server"))=>{let s;const{lifeSpan:i}=ae("cache_then_server",n.lifeSpan);if(re(e)){try{s=te(e)?e.optimistically(...t):e.locally(...t)}catch(e){null==r||r(le(void 0,{origin:"local",loading:!1,error:e}))}const n=ne(s)&&se(s,i);if(null==r||r(le(s,{origin:"local",loading:!(ee(e)&&n)})),n)return}else null==r||r(le(void 0,{origin:"local",loading:!0}));e(...t).then((e=>{null==r||r(le(e,{origin:"server",loading:!1}))})).catch((e=>{null==r||r(le(void 0,{origin:"server",loading:!1,error:e}))}))};function le(e,t){return Q(e)||ne(e)?Object.assign(Object.assign({},t),e):Object.assign(Object.assign({},t),{data:e})}const ce={user:({userId:e})=>e,file:({fileId:e})=>e,role:({roleId:e})=>e,channel:({channelId:e})=>e,subChannel:({subChannelId:e})=>e,channelUsers:({channelId:e,userId:t})=>`${e}#${t}`,message:({messageId:e})=>e,messagePreviewChannel:({channelId:e})=>`${e}`,messagePreviewSubChannel:({subChannelId:e})=>`${e}`,channelUnreadInfo:({channelId:e})=>e,subChannelUnreadInfo:({subChannelId:e})=>e,channelMarker:({entityId:e,userId:t})=>`${e}#${t}`,subChannelMarker:({entityId:e,feedId:t,userId:r})=>`${e}#${t}#${r}`,messageMarker:({feedId:e,contentId:t,creatorId:r})=>`${e}#${t}#${r}`,feedMarker:({feedId:e,entityId:t})=>`${e}#${t}`,userMarker:({userId:e})=>e,community:({communityId:e})=>e,category:({categoryId:e})=>e,communityUsers:({communityId:e,userId:t})=>`${e}#${t}`,post:({postId:e})=>e,comment:({commentId:e})=>e,commentChildren:({commentId:e})=>e,poll:({pollId:e})=>e,reaction:({referenceType:e,referenceId:t})=>`${e}#${t}`,reactor:({reactionId:e})=>e,stream:({streamId:e})=>e,follow:({from:e,to:t})=>`${e}#${t}`,followInfo:({userId:e})=>e,followCount:({userId:e})=>e,feed:({targetId:e,feedId:t})=>`${e}#${t}`,story:({referenceId:e})=>e,storyTarget:({targetId:e})=>e},de=e=>ce[e],ue={users:"user",files:"file",roles:"role",stories:"story",storyTargets:"storyTarget",channels:"channel",messageFeeds:"subChannel",channelUsers:"channelUsers",messages:"message",messagePreviewChannel:"messagePreviewChannel",messagePreviewSubChannel:"messagePreviewSubChannel",channelUnreadInfo:"channelUnreadInfo",subChannelUnreadInfo:"subChannelUnreadInfo",userEntityMarkers:"channelMarker",userFeedMarkers:"subChannelMarker",contentMarkers:"messageMarker",feedMarkers:"feedMarker",userMarkers:"userMarker",communities:"community",categories:"category",communityUsers:"communityUsers",posts:"post",postChildren:"post",comments:"comment",commentChildren:"comment",polls:"poll",reactors:"reactor",reactions:"reaction",videoStreamings:"stream",follows:"follow",followCounts:"followCount",feeds:"feed"};function he(e=(new Date).toISOString()){return new Date(new Date(e).getTime()+1).toISOString()}class fe extends Error{constructor(e,t,r){super(`Amity SDK (${t}): ${e}`),this.code=t,this.level=r,this.type="ASC",this.timestamp=Date.now(),Error.captureStackTrace&&Error.captureStackTrace(this,fe)}}class pe extends fe{constructor(e,t,r){super(e,t,r)}}class ge extends fe{constructor(e=8e5,t="fatal"){super("Unexpected error",e,t)}}class me extends fe{constructor(e,t="SDK client is having connection issues"){super(`${t} (${e})`,"disconnected"===e?800211:800210,"error"),this.event=e}}let ye=null;const ve=()=>{if(!ye)throw new fe("There is no active client",8e5,"fatal");return ye},be=e=>{ye=e},we=e=>{const{log:t,cache:r}=ve();if(r)return t("cache/api/queryCache",{key:e}),Object.keys(r.data).filter((t=>{const r=S(t);return T(e,r)})).map((e=>r.data[e]))},Ee=e=>{const{log:t,cache:r}=ve();if(!r)return;t("cache/api/pullFromCache",e);const n=E(e);return r.data[n]?r.data[n]:void 0},Se=(e,t,r={cachedAt:Date.now()})=>{const{log:n,cache:s}=ve();if(!s)return!1;n("cache/api/pushToCache",{key:e,data:t,options:r}),!(null==r?void 0:r.hasOwnProperty("offline"))&&s.persistIf&&(r.offline=s.persistIf(e,t));const i=E(e);return s.data[i]=Object.assign({key:e,data:t},r),!0},Te=(e,t,r)=>{const{log:n,cache:s}=ve();if(!s)return!1;n("cache/api/mergeInCache",{key:e,mutation:t});const i=Ee(e);if(!i)return!1;const a="function"==typeof t?t(i.data):Object.assign(Object.assign({},i.data),t);return o=i.data,!("updatedAt"in(l=a)&&"updatedAt"in l&&new Date(l.updatedAt)<new Date(o.updatedAt))&&(Se(e,a,r),!0);var o,l},Ce=(e,t,r={cachedAt:Date.now()})=>{const{log:n,cache:s}=ve();if(!s)return!1;n("cache/api/upsertInCache",{key:e,data:t,options:r});return Ee(e)?Te(e,t,r):Se(e,t,r)},ke=(e,t=!1)=>{const{log:r,cache:n}=ve();if(!n)return!1;if(r("cache/api/dropFromCache",{key:e,exact:t}),!t)return Object.keys(n.data).map((e=>S(e))).filter((t=>T(e,t))).map((e=>ke(e,!0))).every((e=>e));const s=E(e);return s in n.data&&(delete n.data[s],!0)},Ae=(e,t,r)=>void 0!==r?e.filter((e=>JSON.stringify(e[t])===JSON.stringify(r))):e,Ie=(e,t,r)=>void 0!==r?e.filter((e=>"string"==typeof e[t]&&"string"==typeof r&&String(e[t]).toLowerCase().match(r.toLowerCase()))):e,_e=(e,t,r)=>(null==r?void 0:r.length)?e.filter((e=>Array.isArray(e[t])&&r.some((r=>e[t].includes(r))))):e,Re=(e,t,r)=>"all"===t?e:e.filter((e=>{var n;if("community"===e.type)return!0;const s=de("channelUsers")({channelId:e.channelId,userId:r}),i=null===(n=Ee(["channelUsers","get",s]))||void 0===n?void 0:n.data;return"member"===t?i&&"none"!==i.membership:!i||"none"===i.membership})),Le=(e,t)=>e.filter((({targetId:e,feedId:r})=>{var n;const s=null===(n=Ee(["feed","get",de("feed")({targetId:e,feedId:r})]))||void 0===n?void 0:n.data;return s&&s.feedType===t})),De=(e,t,r)=>"all"===t?e:e.filter((e=>{var n;const s=de("communityUsers")({communityId:e.communityId,userId:r}),i=null===(n=Ee(["communityUsers","get",s]))||void 0===n?void 0:n.data;return"member"===t?i&&"member"===i.communityMembership:!i||"none"!==i.communityMembership})),xe=(e,t)=>{const r=[];return e.reduce(((e,n)=>{var s;if("text"===n.dataType&&!n.children.length)return e;if(r.includes(n.postId))return e;if((null==t?void 0:t.includes(n.dataType))&&e.push(n),!n.children.length)return e;const i=null===(s=Ee(["post","get",n.children[0]]))||void 0===s?void 0:s.data;return i?r.includes(i.postId)?e:(null==t?void 0:t.includes(null==i?void 0:i.dataType))?(r.push(i.postId),e.push(i),e):e:e}),[])},Oe=(e,t)=>{const r=new RegExp(t,"i");return e.filter((e=>{var t;return!!e.userId.match(r)||e.user&&(null===(t=e.user.displayName)||void 0===t?void 0:t.match(r))}))},Pe=({displayName:e},{displayName:t})=>e===t?0:e<t?-1:1,Me=({name:e},{name:t})=>e.localeCompare(t),Fe=({createdAt:e},{createdAt:t})=>new Date(e).valueOf()-new Date(t).valueOf(),Ue=({localSortingDate:e},{localSortingDate:t})=>new Date(t).getTime()-new Date(e).getTime(),Ne=({createdAt:e},{createdAt:t})=>new Date(t).valueOf()-new Date(e).valueOf(),Be=({updatedAt:e=0},{updatedAt:t=0})=>new Date(e).valueOf()-new Date(t).valueOf(),je=({updatedAt:e=0},{updatedAt:t=0})=>new Date(t).valueOf()-new Date(e).valueOf(),$e=({lastActivity:e},{lastActivity:t})=>new Date(t).valueOf()-new Date(e).valueOf();let qe=null;const Ke=()=>{if(!qe)throw new fe("Connect client first",8e5,"fatal");return qe},Ge=e=>{qe={_id:e._id,userId:e.userId,path:e.path}};let He,Ve=[];const ze=e=>{clearTimeout(He),Ve.push(e),He=setTimeout((()=>{Ve.forEach((e=>e())),Ve=[]}),0)},We=["disconnected","error","connect_error","reconnect_error","reconnect_failed","sessionStateChange","tokenExpired"],Ye=["connect","message","disconnect","error","close","end","reconnect","user.didGlobalBan"],Qe=()=>{return{all:e=e||new Map,on:function(t,r){var n=e.get(t);n?n.push(r):e.set(t,[r])},off:function(t,r){var n=e.get(t);n&&(r?n.splice(n.indexOf(r)>>>0,1):e.set(t,[]))},emit:function(t,r){var n=e.get(t);n&&n.slice().map((function(e){e(r)})),(n=e.get("*"))&&n.slice().map((function(e){e(t,r)}))}};var e},Xe=(e,t,r,n)=>{const{log:s,emitter:i}=e,a=Date.now();s(`${t}(tmpid: ${a}) > listen`);const o=(...e)=>{s(`${t}(tmpid: ${a}) > trigger`,e);try{n(...e)}catch(e){s(`${t}(tmpid: ${a}) > error`,e)}};return i.on(r,o),()=>{s(`${t}(tmpid: ${a}) > dispose`),i.off(r,o)}},Je=(e,t)=>{const{emitter:r}=ve();ze((()=>{r.emit(e,t)}))};let Ze,et;async function tt(){var e;const{mqtt:t,emitter:r,token:n}=ve(),s=null!==(e=null==n?void 0:n.accessToken)&&void 0!==e?e:"",i=Ke();Ze===s&&et===i._id||(Ze=s,et=i._id,await t.connect({accessToken:Ze,userId:et}),((e,t)=>{Ye.forEach((r=>{e.on(r,((...e)=>{t.emit(r,1===e.length?e[0]:e)}))})),e.on("message",((e,r)=>{const n=JSON.parse(r.toString());t.emit(n.eventType,n.data)}))})(t,r))}var rt;e.SubscriptionLevels=void 0,(rt=e.SubscriptionLevels||(e.SubscriptionLevels={})).COMMUNITY="community",rt.POST="post",rt.COMMENT="comment",rt.POST_AND_COMMENT="post_and_comment",rt.USER="user";const nt=(e,t)=>{switch(t){case"post":return`${e}/post/+`;case"comment":return`${e}/post/+/comment/+`;case"post_and_comment":return`${e}/post/#`;default:return e}},st=e=>e.path.split("/user/")[0],it=({path:t},r=e.SubscriptionLevels.USER)=>nt(r===e.SubscriptionLevels.USER?t:t.replace(/^(\w*)/,"$1/social"),r),at=({channelId:e,subChannelId:t})=>{const r=Ke();return`${st(r)}/marker/channel/${e}/message/${t}`},ot=()=>{const e=Ke();return`${st(e)}/marker/user/${e._id}`},lt=()=>st(Ke()),ct=()=>{const e=Ke();return`${st(e)}/smartfeed/${e._id}/channels`},dt=()=>{const e=Ke();return`${st(e)}/smartfeed/${e._id}/messagefeeds`},ut=()=>{const e=Ke();return`${st(e)}/smartfeed/${e._id}/messages`};function ht(e,t){const{mqtt:r}=ve();return tt(),r.subscribe(e,t)}var ft="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function pt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function gt(e){var t=e.default;if("function"==typeof t){var r=function(){return t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})})),r}var mt,yt,vt={exports:{}};function bt(){if(yt)return mt;yt=1;var e=1e3,t=60*e,r=60*t,n=24*r,s=7*n,i=365.25*n;function a(e,t,r,n){var s=t>=1.5*r;return Math.round(e/r)+" "+n+(s?"s":"")}return mt=function(o,l){l=l||{};var c=typeof o;if("string"===c&&o.length>0)return function(a){if((a=String(a)).length>100)return;var o=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(a);if(!o)return;var l=parseFloat(o[1]);switch((o[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return l*i;case"weeks":case"week":case"w":return l*s;case"days":case"day":case"d":return l*n;case"hours":case"hour":case"hrs":case"hr":case"h":return l*r;case"minutes":case"minute":case"mins":case"min":case"m":return l*t;case"seconds":case"second":case"secs":case"sec":case"s":return l*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return l;default:return}}(o);if("number"===c&&isFinite(o))return l.long?function(s){var i=Math.abs(s);if(i>=n)return a(s,i,n,"day");if(i>=r)return a(s,i,r,"hour");if(i>=t)return a(s,i,t,"minute");if(i>=e)return a(s,i,e,"second");return s+" ms"}(o):function(s){var i=Math.abs(s);if(i>=n)return Math.round(s/n)+"d";if(i>=r)return Math.round(s/r)+"h";if(i>=t)return Math.round(s/t)+"m";if(i>=e)return Math.round(s/e)+"s";return s+"ms"}(o);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(o))},mt}var wt=function(e){function t(e){let n,s,i,a=null;function o(...e){if(!o.enabled)return;const r=o,s=Number(new Date),i=s-(n||s);r.diff=i,r.prev=n,r.curr=s,n=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,s)=>{if("%%"===n)return"%";a++;const i=t.formatters[s];if("function"==typeof i){const t=e[a];n=i.call(r,t),e.splice(a,1),a--}return n})),t.formatArgs.call(r,e);(r.log||t.log).apply(r,e)}return o.namespace=e,o.useColors=t.useColors(),o.color=t.selectColor(e),o.extend=r,o.destroy=t.destroy,Object.defineProperty(o,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(s!==t.namespaces&&(s=t.namespaces,i=t.enabled(e)),i),set:e=>{a=e}}),"function"==typeof t.init&&t.init(o),o}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),s=n.length;for(r=0;r<s;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=bt(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t};!function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,s=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(s=n))})),t.splice(s,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=wt(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(vt,vt.exports);var Et,St=vt.exports;const Tt="object"==typeof globalThis?globalThis:"object"==typeof global?global:window,{process:Ct={}}=Tt,kt="production"===(null===(Et=Ct.env)||void 0===Et?void 0:Et.NODE_ENV),At={EU:"eu",SG:"sg",US:"us"},It={http:"https://api.{region}.amity.co",mqtt:"wss://sse.{region}.amity.co:443/mqtt"};function _t(e,t){return It[e].replace("{region}",t)}function Rt(e,t){return function(){return e.apply(t,arguments)}}const{toString:Lt}=Object.prototype,{getPrototypeOf:Dt}=Object,xt=(Ot=Object.create(null),e=>{const t=Lt.call(e);return Ot[t]||(Ot[t]=t.slice(8,-1).toLowerCase())});var Ot;const Pt=e=>(e=e.toLowerCase(),t=>xt(t)===e),Mt=e=>t=>typeof t===e,{isArray:Ft}=Array,Ut=Mt("undefined");const Nt=Pt("ArrayBuffer");const Bt=Mt("string"),jt=Mt("function"),$t=Mt("number"),qt=e=>null!==e&&"object"==typeof e,Kt=e=>{if("object"!==xt(e))return!1;const t=Dt(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)},Gt=Pt("Date"),Ht=Pt("File"),Vt=Pt("Blob"),zt=Pt("FileList"),Wt=Pt("URLSearchParams");function Yt(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let n,s;if("object"!=typeof e&&(e=[e]),Ft(e))for(n=0,s=e.length;n<s;n++)t.call(null,e[n],n,e);else{const s=r?Object.getOwnPropertyNames(e):Object.keys(e),i=s.length;let a;for(n=0;n<i;n++)a=s[n],t.call(null,e[a],a,e)}}function Qt(e,t){t=t.toLowerCase();const r=Object.keys(e);let n,s=r.length;for(;s-- >0;)if(n=r[s],t===n.toLowerCase())return n;return null}const Xt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,Jt=e=>!Ut(e)&&e!==Xt;const Zt=(er="undefined"!=typeof Uint8Array&&Dt(Uint8Array),e=>er&&e instanceof er);var er;const tr=Pt("HTMLFormElement"),rr=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),nr=Pt("RegExp"),sr=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};Yt(r,((r,s)=>{!1!==t(r,s,e)&&(n[s]=r)})),Object.defineProperties(e,n)};var ir={isArray:Ft,isArrayBuffer:Nt,isBuffer:function(e){return null!==e&&!Ut(e)&&null!==e.constructor&&!Ut(e.constructor)&&jt(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{const t="[object FormData]";return e&&("function"==typeof FormData&&e instanceof FormData||Lt.call(e)===t||jt(e.toString)&&e.toString()===t)},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Nt(e.buffer),t},isString:Bt,isNumber:$t,isBoolean:e=>!0===e||!1===e,isObject:qt,isPlainObject:Kt,isUndefined:Ut,isDate:Gt,isFile:Ht,isBlob:Vt,isRegExp:nr,isFunction:jt,isStream:e=>qt(e)&&jt(e.pipe),isURLSearchParams:Wt,isTypedArray:Zt,isFileList:zt,forEach:Yt,merge:function e(){const{caseless:t}=Jt(this)&&this||{},r={},n=(n,s)=>{const i=t&&Qt(r,s)||s;Kt(r[i])&&Kt(n)?r[i]=e(r[i],n):Kt(n)?r[i]=e({},n):Ft(n)?r[i]=n.slice():r[i]=n};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&Yt(arguments[e],n);return r},extend:(e,t,r,{allOwnKeys:n}={})=>(Yt(t,((t,n)=>{r&&jt(t)?e[n]=Rt(t,r):e[n]=t}),{allOwnKeys:n}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,n)=>{let s,i,a;const o={};if(t=t||{},null==e)return t;do{for(s=Object.getOwnPropertyNames(e),i=s.length;i-- >0;)a=s[i],n&&!n(a,e,t)||o[a]||(t[a]=e[a],o[a]=!0);e=!1!==r&&Dt(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:xt,kindOfTest:Pt,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return-1!==n&&n===r},toArray:e=>{if(!e)return null;if(Ft(e))return e;let t=e.length;if(!$t(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let n;for(;(n=r.next())&&!n.done;){const r=n.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const n=[];for(;null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm:tr,hasOwnProperty:rr,hasOwnProp:rr,reduceDescriptors:sr,freezeMethods:e=>{sr(e,((t,r)=>{if(jt(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const n=e[r];jt(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))}))},toObjectSet:(e,t)=>{const r={},n=e=>{e.forEach((e=>{r[e]=!0}))};return Ft(e)?n(e):n(String(e).split(t)),r},toCamelCase:e=>e.toLowerCase().replace(/[_-\s]([a-z\d])(\w*)/g,(function(e,t,r){return t.toUpperCase()+r})),noop:()=>{},toFiniteNumber:(e,t)=>(e=+e,Number.isFinite(e)?e:t),findKey:Qt,global:Xt,isContextDefined:Jt,toJSONObject:e=>{const t=new Array(10),r=(e,n)=>{if(qt(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[n]=e;const s=Ft(e)?[]:{};return Yt(e,((e,t)=>{const i=r(e,n+1);!Ut(i)&&(s[t]=i)})),t[n]=void 0,s}}return e};return r(e,0)}};function ar(e,t,r,n,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),s&&(this.response=s)}ir.inherits(ar,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:ir.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const or=ar.prototype,lr={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach((e=>{lr[e]={value:e}})),Object.defineProperties(ar,lr),Object.defineProperty(or,"isAxiosError",{value:!0}),ar.from=(e,t,r,n,s,i)=>{const a=Object.create(or);return ir.toFlatObject(e,a,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),ar.call(a,e.message,t,r,n,s),a.cause=e,a.name=e.name,i&&Object.assign(a,i),a};var cr="object"==typeof self?self.FormData:window.FormData;function dr(e){return ir.isPlainObject(e)||ir.isArray(e)}function ur(e){return ir.endsWith(e,"[]")?e.slice(0,-2):e}function hr(e,t,r){return e?e.concat(t).map((function(e,t){return e=ur(e),!r&&t?"["+e+"]":e})).join(r?".":""):t}const fr=ir.toFlatObject(ir,{},null,(function(e){return/^is[A-Z]/.test(e)}));function pr(e,t,r){if(!ir.isObject(e))throw new TypeError("target must be an object");t=t||new(cr||FormData);const n=(r=ir.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!ir.isUndefined(t[e])}))).metaTokens,s=r.visitor||d,i=r.dots,a=r.indexes,o=(r.Blob||"undefined"!=typeof Blob&&Blob)&&((l=t)&&ir.isFunction(l.append)&&"FormData"===l[Symbol.toStringTag]&&l[Symbol.iterator]);var l;if(!ir.isFunction(s))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(ir.isDate(e))return e.toISOString();if(!o&&ir.isBlob(e))throw new ar("Blob is not supported. Use a Buffer instead.");return ir.isArrayBuffer(e)||ir.isTypedArray(e)?o&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function d(e,r,s){let o=e;if(e&&!s&&"object"==typeof e)if(ir.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if(ir.isArray(e)&&function(e){return ir.isArray(e)&&!e.some(dr)}(e)||ir.isFileList(e)||ir.endsWith(r,"[]")&&(o=ir.toArray(e)))return r=ur(r),o.forEach((function(e,n){!ir.isUndefined(e)&&null!==e&&t.append(!0===a?hr([r],n,i):null===a?r:r+"[]",c(e))})),!1;return!!dr(e)||(t.append(hr(s,r,i),c(e)),!1)}const u=[],h=Object.assign(fr,{defaultVisitor:d,convertValue:c,isVisitable:dr});if(!ir.isObject(e))throw new TypeError("data must be an object");return function e(r,n){if(!ir.isUndefined(r)){if(-1!==u.indexOf(r))throw Error("Circular reference detected in "+n.join("."));u.push(r),ir.forEach(r,(function(r,i){!0===(!(ir.isUndefined(r)||null===r)&&s.call(t,r,ir.isString(i)?i.trim():i,n,h))&&e(r,n?n.concat(i):[i])})),u.pop()}}(e),t}function gr(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function mr(e,t){this._pairs=[],e&&pr(e,this,t)}const yr=mr.prototype;function vr(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function br(e,t,r){if(!t)return e;const n=r&&r.encode||vr,s=r&&r.serialize;let i;if(i=s?s(t,r):ir.isURLSearchParams(t)?t.toString():new mr(t,r).toString(n),i){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+i}return e}yr.append=function(e,t){this._pairs.push([e,t])},yr.toString=function(e){const t=e?function(t){return e.call(this,t,gr)}:gr;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};class wr{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){ir.forEach(this.handlers,(function(t){null!==t&&e(t)}))}}var Er={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Sr="undefined"!=typeof URLSearchParams?URLSearchParams:mr,Tr=FormData;const Cr=(()=>{let e;return("undefined"==typeof navigator||"ReactNative"!==(e=navigator.product)&&"NativeScript"!==e&&"NS"!==e)&&("undefined"!=typeof window&&"undefined"!=typeof document)})(),kr="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts;var Ar={isBrowser:!0,classes:{URLSearchParams:Sr,FormData:Tr,Blob:Blob},isStandardBrowserEnv:Cr,isStandardBrowserWebWorkerEnv:kr,protocols:["http","https","file","blob","url","data"]};function Ir(e){function t(e,r,n,s){let i=e[s++];const a=Number.isFinite(+i),o=s>=e.length;if(i=!i&&ir.isArray(n)?n.length:i,o)return ir.hasOwnProp(n,i)?n[i]=[n[i],r]:n[i]=r,!a;n[i]&&ir.isObject(n[i])||(n[i]=[]);return t(e,r,n[i],s)&&ir.isArray(n[i])&&(n[i]=function(e){const t={},r=Object.keys(e);let n;const s=r.length;let i;for(n=0;n<s;n++)i=r[n],t[i]=e[i];return t}(n[i])),!a}if(ir.isFormData(e)&&ir.isFunction(e.entries)){const r={};return ir.forEachEntry(e,((e,n)=>{t(function(e){return ir.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),n,r,0)})),r}return null}const _r={"Content-Type":void 0};const Rr={transitional:Er,adapter:["xhr","http"],transformRequest:[function(e,t){const r=t.getContentType()||"",n=r.indexOf("application/json")>-1,s=ir.isObject(e);s&&ir.isHTMLForm(e)&&(e=new FormData(e));if(ir.isFormData(e))return n&&n?JSON.stringify(Ir(e)):e;if(ir.isArrayBuffer(e)||ir.isBuffer(e)||ir.isStream(e)||ir.isFile(e)||ir.isBlob(e))return e;if(ir.isArrayBufferView(e))return e.buffer;if(ir.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let i;if(s){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return pr(e,new Ar.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,n){return Ar.isNode&&ir.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((i=ir.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return pr(i?{"files[]":e}:e,t&&new t,this.formSerializer)}}return s||n?(t.setContentType("application/json",!1),function(e,t,r){if(ir.isString(e))try{return(t||JSON.parse)(e),ir.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Rr.transitional,r=t&&t.forcedJSONParsing,n="json"===this.responseType;if(e&&ir.isString(e)&&(r&&!this.responseType||n)){const r=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(e){if(r){if("SyntaxError"===e.name)throw ar.from(e,ar.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Ar.classes.FormData,Blob:Ar.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};ir.forEach(["delete","get","head"],(function(e){Rr.headers[e]={}})),ir.forEach(["post","put","patch"],(function(e){Rr.headers[e]=ir.merge(_r)}));const Lr=ir.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const Dr=Symbol("internals");function xr(e){return e&&String(e).trim().toLowerCase()}function Or(e){return!1===e||null==e?e:ir.isArray(e)?e.map(Or):String(e)}function Pr(e,t,r,n){return ir.isFunction(n)?n.call(this,t,r):ir.isString(t)?ir.isString(n)?-1!==t.indexOf(n):ir.isRegExp(n)?n.test(t):void 0:void 0}class Mr{constructor(e){e&&this.set(e)}set(e,t,r){const n=this;function s(e,t,r){const s=xr(t);if(!s)throw new Error("header name must be a non-empty string");const i=ir.findKey(n,s);(!i||void 0===n[i]||!0===r||void 0===r&&!1!==n[i])&&(n[i||t]=Or(e))}const i=(e,t)=>ir.forEach(e,((e,r)=>s(e,r,t)));return ir.isPlainObject(e)||e instanceof this.constructor?i(e,t):ir.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z]+$/.test(e.trim())?i((e=>{const t={};let r,n,s;return e&&e.split("\n").forEach((function(e){s=e.indexOf(":"),r=e.substring(0,s).trim().toLowerCase(),n=e.substring(s+1).trim(),!r||t[r]&&Lr[r]||("set-cookie"===r?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)})),t})(e),t):null!=e&&s(t,e,r),this}get(e,t){if(e=xr(e)){const r=ir.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}(e);if(ir.isFunction(t))return t.call(this,e,r);if(ir.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=xr(e)){const r=ir.findKey(this,e);return!(!r||t&&!Pr(0,this[r],r,t))}return!1}delete(e,t){const r=this;let n=!1;function s(e){if(e=xr(e)){const s=ir.findKey(r,e);!s||t&&!Pr(0,r[s],s,t)||(delete r[s],n=!0)}}return ir.isArray(e)?e.forEach(s):s(e),n}clear(){return Object.keys(this).forEach(this.delete.bind(this))}normalize(e){const t=this,r={};return ir.forEach(this,((n,s)=>{const i=ir.findKey(r,s);if(i)return t[i]=Or(n),void delete t[s];const a=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,r)=>t.toUpperCase()+r))}(s):String(s).trim();a!==s&&delete t[s],t[a]=Or(n),r[a]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return ir.forEach(this,((r,n)=>{null!=r&&!1!==r&&(t[n]=e&&ir.isArray(r)?r.join(", "):r)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((([e,t])=>e+": "+t)).join("\n")}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach((e=>r.set(e))),r}static accessor(e){const t=(this[Dr]=this[Dr]={accessors:{}}).accessors,r=this.prototype;function n(e){const n=xr(e);t[n]||(!function(e,t){const r=ir.toCamelCase(" "+t);["get","set","has"].forEach((n=>{Object.defineProperty(e,n+r,{value:function(e,r,s){return this[n].call(this,t,e,r,s)},configurable:!0})}))}(r,e),t[n]=!0)}return ir.isArray(e)?e.forEach(n):n(e),this}}function Fr(e,t){const r=this||Rr,n=t||r,s=Mr.from(n.headers);let i=n.data;return ir.forEach(e,(function(e){i=e.call(r,i,s.normalize(),t?t.status:void 0)})),s.normalize(),i}function Ur(e){return!(!e||!e.__CANCEL__)}function Nr(e,t,r){ar.call(this,null==e?"canceled":e,ar.ERR_CANCELED,t,r),this.name="CanceledError"}Mr.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent"]),ir.freezeMethods(Mr.prototype),ir.freezeMethods(Mr),ir.inherits(Nr,ar,{__CANCEL__:!0});var Br=Ar.isStandardBrowserEnv?{write:function(e,t,r,n,s,i){const a=[];a.push(e+"="+encodeURIComponent(t)),ir.isNumber(r)&&a.push("expires="+new Date(r).toGMTString()),ir.isString(n)&&a.push("path="+n),ir.isString(s)&&a.push("domain="+s),!0===i&&a.push("secure"),document.cookie=a.join("; ")},read:function(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}};function jr(e,t){return e&&!function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}(t)?function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}var $r=Ar.isStandardBrowserEnv?function(){const e=/(msie|trident)/i.test(navigator.userAgent),t=document.createElement("a");let r;function n(r){let n=r;return e&&(t.setAttribute("href",n),n=t.href),t.setAttribute("href",n),{href:t.href,protocol:t.protocol?t.protocol.replace(/:$/,""):"",host:t.host,search:t.search?t.search.replace(/^\?/,""):"",hash:t.hash?t.hash.replace(/^#/,""):"",hostname:t.hostname,port:t.port,pathname:"/"===t.pathname.charAt(0)?t.pathname:"/"+t.pathname}}return r=n(window.location.href),function(e){const t=ir.isString(e)?n(e):e;return t.protocol===r.protocol&&t.host===r.host}}():function(){return!0};function qr(e,t){let r=0;const n=function(e,t){e=e||10;const r=new Array(e),n=new Array(e);let s,i=0,a=0;return t=void 0!==t?t:1e3,function(o){const l=Date.now(),c=n[a];s||(s=l),r[i]=o,n[i]=l;let d=a,u=0;for(;d!==i;)u+=r[d++],d%=e;if(i=(i+1)%e,i===a&&(a=(a+1)%e),l-s<t)return;const h=c&&l-c;return h?Math.round(1e3*u/h):void 0}}(50,250);return s=>{const i=s.loaded,a=s.lengthComputable?s.total:void 0,o=i-r,l=n(o);r=i;const c={loaded:i,total:a,progress:a?i/a:void 0,bytes:o,rate:l||void 0,estimated:l&&a&&i<=a?(a-i)/l:void 0,event:s};c[t?"download":"upload"]=!0,e(c)}}var Kr="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,r){let n=e.data;const s=Mr.from(e.headers).normalize(),i=e.responseType;let a;function o(){e.cancelToken&&e.cancelToken.unsubscribe(a),e.signal&&e.signal.removeEventListener("abort",a)}ir.isFormData(n)&&(Ar.isStandardBrowserEnv||Ar.isStandardBrowserWebWorkerEnv)&&s.setContentType(!1);let l=new XMLHttpRequest;if(e.auth){const t=e.auth.username||"",r=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";s.set("Authorization","Basic "+btoa(t+":"+r))}const c=jr(e.baseURL,e.url);function d(){if(!l)return;const n=Mr.from("getAllResponseHeaders"in l&&l.getAllResponseHeaders());!function(e,t,r){const n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new ar("Request failed with status code "+r.status,[ar.ERR_BAD_REQUEST,ar.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}((function(e){t(e),o()}),(function(e){r(e),o()}),{data:i&&"text"!==i&&"json"!==i?l.response:l.responseText,status:l.status,statusText:l.statusText,headers:n,config:e,request:l}),l=null}if(l.open(e.method.toUpperCase(),br(c,e.params,e.paramsSerializer),!0),l.timeout=e.timeout,"onloadend"in l?l.onloadend=d:l.onreadystatechange=function(){l&&4===l.readyState&&(0!==l.status||l.responseURL&&0===l.responseURL.indexOf("file:"))&&setTimeout(d)},l.onabort=function(){l&&(r(new ar("Request aborted",ar.ECONNABORTED,e,l)),l=null)},l.onerror=function(){r(new ar("Network Error",ar.ERR_NETWORK,e,l)),l=null},l.ontimeout=function(){let t=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const n=e.transitional||Er;e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),r(new ar(t,n.clarifyTimeoutError?ar.ETIMEDOUT:ar.ECONNABORTED,e,l)),l=null},Ar.isStandardBrowserEnv){const t=(e.withCredentials||$r(c))&&e.xsrfCookieName&&Br.read(e.xsrfCookieName);t&&s.set(e.xsrfHeaderName,t)}void 0===n&&s.setContentType(null),"setRequestHeader"in l&&ir.forEach(s.toJSON(),(function(e,t){l.setRequestHeader(t,e)})),ir.isUndefined(e.withCredentials)||(l.withCredentials=!!e.withCredentials),i&&"json"!==i&&(l.responseType=e.responseType),"function"==typeof e.onDownloadProgress&&l.addEventListener("progress",qr(e.onDownloadProgress,!0)),"function"==typeof e.onUploadProgress&&l.upload&&l.upload.addEventListener("progress",qr(e.onUploadProgress)),(e.cancelToken||e.signal)&&(a=t=>{l&&(r(!t||t.type?new Nr(null,e,l):t),l.abort(),l=null)},e.cancelToken&&e.cancelToken.subscribe(a),e.signal&&(e.signal.aborted?a():e.signal.addEventListener("abort",a)));const u=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(c);u&&-1===Ar.protocols.indexOf(u)?r(new ar("Unsupported protocol "+u+":",ar.ERR_BAD_REQUEST,e)):l.send(n||null)}))};const Gr={http:null,xhr:Kr};ir.forEach(Gr,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}}));var Hr=e=>{e=ir.isArray(e)?e:[e];const{length:t}=e;let r,n;for(let s=0;s<t&&(r=e[s],!(n=ir.isString(r)?Gr[r.toLowerCase()]:r));s++);if(!n){if(!1===n)throw new ar(`Adapter ${r} is not supported by the environment`,"ERR_NOT_SUPPORT");throw new Error(ir.hasOwnProp(Gr,r)?`Adapter '${r}' is not available in the build`:`Unknown adapter '${r}'`)}if(!ir.isFunction(n))throw new TypeError("adapter is not a function");return n};function Vr(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Nr(null,e)}function zr(e){Vr(e),e.headers=Mr.from(e.headers),e.data=Fr.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Hr(e.adapter||Rr.adapter)(e).then((function(t){return Vr(e),t.data=Fr.call(e,e.transformResponse,t),t.headers=Mr.from(t.headers),t}),(function(t){return Ur(t)||(Vr(e),t&&t.response&&(t.response.data=Fr.call(e,e.transformResponse,t.response),t.response.headers=Mr.from(t.response.headers))),Promise.reject(t)}))}const Wr=e=>e instanceof Mr?e.toJSON():e;function Yr(e,t){t=t||{};const r={};function n(e,t,r){return ir.isPlainObject(e)&&ir.isPlainObject(t)?ir.merge.call({caseless:r},e,t):ir.isPlainObject(t)?ir.merge({},t):ir.isArray(t)?t.slice():t}function s(e,t,r){return ir.isUndefined(t)?ir.isUndefined(e)?void 0:n(void 0,e,r):n(e,t,r)}function i(e,t){if(!ir.isUndefined(t))return n(void 0,t)}function a(e,t){return ir.isUndefined(t)?ir.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function o(r,s,i){return i in t?n(r,s):i in e?n(void 0,r):void 0}const l={url:i,method:i,data:i,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:o,headers:(e,t)=>s(Wr(e),Wr(t),!0)};return ir.forEach(Object.keys(e).concat(Object.keys(t)),(function(n){const i=l[n]||s,a=i(e[n],t[n],n);ir.isUndefined(a)&&i!==o||(r[n]=a)})),r}const Qr="1.2.3",Xr={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{Xr[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));const Jr={};Xr.transitional=function(e,t,r){function n(e,t){return"[Axios v1.2.3] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,s,i)=>{if(!1===e)throw new ar(n(s," has been removed"+(t?" in "+t:"")),ar.ERR_DEPRECATED);return t&&!Jr[s]&&(Jr[s]=!0,console.warn(n(s," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,s,i)}};var Zr={assertOptions:function(e,t,r){if("object"!=typeof e)throw new ar("options must be an object",ar.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let s=n.length;for(;s-- >0;){const i=n[s],a=t[i];if(a){const t=e[i],r=void 0===t||a(t,i,e);if(!0!==r)throw new ar("option "+i+" must be "+r,ar.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new ar("Unknown option "+i,ar.ERR_BAD_OPTION)}},validators:Xr};const en=Zr.validators;class tn{constructor(e){this.defaults=e,this.interceptors={request:new wr,response:new wr}}request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=Yr(this.defaults,t);const{transitional:r,paramsSerializer:n,headers:s}=t;let i;void 0!==r&&Zr.assertOptions(r,{silentJSONParsing:en.transitional(en.boolean),forcedJSONParsing:en.transitional(en.boolean),clarifyTimeoutError:en.transitional(en.boolean)},!1),void 0!==n&&Zr.assertOptions(n,{encode:en.function,serialize:en.function},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase(),i=s&&ir.merge(s.common,s[t.method]),i&&ir.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete s[e]})),t.headers=Mr.concat(i,s);const a=[];let o=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(o=o&&e.synchronous,a.unshift(e.fulfilled,e.rejected))}));const l=[];let c;this.interceptors.response.forEach((function(e){l.push(e.fulfilled,e.rejected)}));let d,u=0;if(!o){const e=[zr.bind(this),void 0];for(e.unshift.apply(e,a),e.push.apply(e,l),d=e.length,c=Promise.resolve(t);u<d;)c=c.then(e[u++],e[u++]);return c}d=a.length;let h=t;for(u=0;u<d;){const e=a[u++],t=a[u++];try{h=e(h)}catch(e){t.call(this,e);break}}try{c=zr.call(this,h)}catch(e){return Promise.reject(e)}for(u=0,d=l.length;u<d;)c=c.then(l[u++],l[u++]);return c}getUri(e){return br(jr((e=Yr(this.defaults,e)).baseURL,e.url),e.params,e.paramsSerializer)}}ir.forEach(["delete","get","head","options"],(function(e){tn.prototype[e]=function(t,r){return this.request(Yr(r||{},{method:e,url:t,data:(r||{}).data}))}})),ir.forEach(["post","put","patch"],(function(e){function t(t){return function(r,n,s){return this.request(Yr(s||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:n}))}}tn.prototype[e]=t(),tn.prototype[e+"Form"]=t(!0)}));class rn{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise((function(e){t=e}));const r=this;this.promise.then((e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null})),this.promise.then=e=>{let t;const n=new Promise((e=>{r.subscribe(e),t=e})).then(e);return n.cancel=function(){r.unsubscribe(t)},n},e((function(e,n,s){r.reason||(r.reason=new Nr(e,n,s),t(r.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}static source(){let e;return{token:new rn((function(t){e=t})),cancel:e}}}const nn={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(nn).forEach((([e,t])=>{nn[t]=e}));const sn=function e(t){const r=new tn(t),n=Rt(tn.prototype.request,r);return ir.extend(n,tn.prototype,r,{allOwnKeys:!0}),ir.extend(n,r,null,{allOwnKeys:!0}),n.create=function(r){return e(Yr(t,r))},n}(Rr);sn.Axios=tn,sn.CanceledError=Nr,sn.CancelToken=rn,sn.isCancel=Ur,sn.VERSION=Qr,sn.toFormData=pr,sn.AxiosError=ar,sn.Cancel=sn.CanceledError,sn.all=function(e){return Promise.all(e)},sn.spread=function(e){return function(t){return e.apply(null,t)}},sn.isAxiosError=function(e){return ir.isObject(e)&&!0===e.isAxiosError},sn.mergeConfig=Yr,sn.AxiosHeaders=Mr,sn.formToJSON=e=>Ir(ir.isHTMLForm(e)?new FormData(e):e),sn.HttpStatusCode=nn,sn.default=sn;var an={exports:{}};an.exports=ln;var on=an.exports.HttpsAgent=ln;function ln(){}var cn;!function(e){e.UserDeleted="User Deleted",e.UserGlobalBanned="User Global Banned",e.TokenExpired="Token Expired"}(cn||(cn={}));const dn=new AbortController,un=e=>{switch(e){case cn.UserGlobalBanned:throw new fe(e,400312,"fatal");case cn.UserDeleted:throw new fe(e,400100,"fatal");case cn.TokenExpired:throw Je("tokenExpired","tokenExpired"),new fe(e,800403,"fatal");default:throw new fe("Request Aborted",8e5,"error")}},hn=e=>{const t={maxSockets:100,maxFreeSockets:10,timeout:6e4,freeSocketTimeout:3e4},r=sn.create({baseURL:e,httpAgent:new an.exports(t),httpsAgent:new on(t),signal:dn.signal});return r.interceptors.request.use((e=>{if("/api/v4/sessions"===e.url)return e;if(e.metadata){const{tokenExpiry:t,isGlobalBanned:r,isUserDeleted:n}=e.metadata;r&&(dn.abort(),un(cn.UserGlobalBanned)),n&&(dn.abort(),un(cn.UserDeleted)),t&&Date.now()>=Date.parse(t)&&(dn.abort(cn.UserDeleted),un(cn.TokenExpired))}return e})),r.interceptors.response.use((e=>e),(e=>{var t,r;const{response:n}=e;if(400100===(null==n?void 0:n.data.code)&&Je("tokenTerminated","terminated"),(null===(t=null==n?void 0:n.data)||void 0===t?void 0:t.status)&&(e=>{if("success"===e.status)return e.data;if("fail"===e.status)throw new ge(e.code);if("error"===e.status)throw new pe(e.message,e.code,"error")})(null==n?void 0:n.data),dn.signal.aborted)throw e;throw new Error(null!==(r=null==n?void 0:n.data)&&void 0!==r?r:e)})),r.defaults.paramsSerializer={encode:e=>encodeURIComponent(e)},r};var fn={exports:{}},pn=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,gn=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],mn=function(e){var t=e,r=e.indexOf("["),n=e.indexOf("]");-1!=r&&-1!=n&&(e=e.substring(0,r)+e.substring(r,n).replace(/:/g,";")+e.substring(n,e.length));for(var s=pn.exec(e||""),i={},a=14;a--;)i[gn[a]]=s[a]||"";return-1!=r&&-1!=n&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i},yn={exports:{}},vn={exports:{}},bn=1e3,wn=6e4,En=60*wn,Sn=24*En,Tn=365.25*Sn,Cn=function(e,t){t=t||{};var r=typeof e;if("string"===r&&e.length>0)return function(e){if((e=String(e)).length>100)return;var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(!t)return;var r=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return r*Tn;case"days":case"day":case"d":return r*Sn;case"hours":case"hour":case"hrs":case"hr":case"h":return r*En;case"minutes":case"minute":case"mins":case"min":case"m":return r*wn;case"seconds":case"second":case"secs":case"sec":case"s":return r*bn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}(e);if("number"===r&&!1===isNaN(e))return t.long?function(e){return kn(e,Sn,"day")||kn(e,En,"hour")||kn(e,wn,"minute")||kn(e,bn,"second")||e+" ms"}(e):function(e){if(e>=Sn)return Math.round(e/Sn)+"d";if(e>=En)return Math.round(e/En)+"h";if(e>=wn)return Math.round(e/wn)+"m";if(e>=bn)return Math.round(e/bn)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function kn(e,t,r){if(!(e<t))return e<1.5*t?Math.floor(e/t)+" "+r:Math.ceil(e/t)+" "+r+"s"}!function(e,t){function r(e){var r;function s(){if(s.enabled){var e=s,n=+new Date,i=n-(r||n);e.diff=i,e.prev=r,e.curr=n,r=n;for(var a=new Array(arguments.length),o=0;o<a.length;o++)a[o]=arguments[o];a[0]=t.coerce(a[0]),"string"!=typeof a[0]&&a.unshift("%O");var l=0;a[0]=a[0].replace(/%([a-zA-Z%])/g,(function(r,n){if("%%"===r)return r;l++;var s=t.formatters[n];if("function"==typeof s){var i=a[l];r=s.call(e,i),a.splice(l,1),l--}return r})),t.formatArgs.call(e,a);var c=s.log||t.log||console.log.bind(console);c.apply(e,a)}}return s.namespace=e,s.enabled=t.enabled(e),s.useColors=t.useColors(),s.color=function(e){var r,n=0;for(r in e)n=(n<<5)-n+e.charCodeAt(r),n|=0;return t.colors[Math.abs(n)%t.colors.length]}(e),s.destroy=n,"function"==typeof t.init&&t.init(s),t.instances.push(s),s}function n(){var e=t.instances.indexOf(this);return-1!==e&&(t.instances.splice(e,1),!0)}(t=e.exports=r.debug=r.default=r).coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){t.enable("")},t.enable=function(e){var r;t.save(e),t.names=[],t.skips=[];var n=("string"==typeof e?e:"").split(/[\s,]+/),s=n.length;for(r=0;r<s;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.substr(1)+"$")):t.names.push(new RegExp("^"+e+"$")));for(r=0;r<t.instances.length;r++){var i=t.instances[r];i.enabled=t.enabled(i.namespace)}},t.enabled=function(e){if("*"===e[e.length-1])return!0;var r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=Cn,t.instances=[],t.names=[],t.skips=[],t.formatters={}}(vn,vn.exports),function(e,t){function r(){var e;try{e=t.storage.debug}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e}(t=e.exports=vn.exports).log=function(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)},t.formatArgs=function(e){var r=this.useColors;if(e[0]=(r?"%c":"")+this.namespace+(r?" %c":" ")+e[0]+(r?"%c ":" ")+"+"+t.humanize(this.diff),!r)return;var n="color: "+this.color;e.splice(1,0,n,"color: inherit");var s=0,i=0;e[0].replace(/%[a-zA-Z%]/g,(function(e){"%%"!==e&&(s++,"%c"===e&&(i=s))})),e.splice(i,0,n)},t.save=function(e){try{null==e?t.storage.removeItem("debug"):t.storage.debug=e}catch(e){}},t.load=r,t.useColors=function(){if("undefined"!=typeof window&&window.process&&"renderer"===window.process.type)return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(e){}}(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},t.enable(r())}(yn,yn.exports);var An=mn,In=yn.exports("socket.io-client:url"),_n=function(e,t){var r=e;t=t||"undefined"!=typeof location&&location,null==e&&(e=t.protocol+"//"+t.host);"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?t.protocol+e:t.host+e),/^(https?|wss?):\/\//.test(e)||(In("protocol-less url %s",e),e=void 0!==t?t.protocol+"//"+e:"https://"+e),In("parse %s",e),r=An(e));r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443"));r.path=r.path||"/";var n=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+n+":"+r.port,r.href=r.protocol+"://"+n+(t&&t.port===r.port?"":":"+r.port),r};var Rn={},Ln={exports:{}},Dn={exports:{}},xn=1e3,On=6e4,Pn=60*On,Mn=24*Pn,Fn=365.25*Mn,Un=function(e,t){t=t||{};var r=typeof e;if("string"===r&&e.length>0)return function(e){if((e=String(e)).length>100)return;var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(!t)return;var r=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return r*Fn;case"days":case"day":case"d":return r*Mn;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Pn;case"minutes":case"minute":case"mins":case"min":case"m":return r*On;case"seconds":case"second":case"secs":case"sec":case"s":return r*xn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}(e);if("number"===r&&!1===isNaN(e))return t.long?function(e){return Nn(e,Mn,"day")||Nn(e,Pn,"hour")||Nn(e,On,"minute")||Nn(e,xn,"second")||e+" ms"}(e):function(e){if(e>=Mn)return Math.round(e/Mn)+"d";if(e>=Pn)return Math.round(e/Pn)+"h";if(e>=On)return Math.round(e/On)+"m";if(e>=xn)return Math.round(e/xn)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function Nn(e,t,r){if(!(e<t))return e<1.5*t?Math.floor(e/t)+" "+r:Math.ceil(e/t)+" "+r+"s"}!function(e,t){function r(e){var r;function s(){if(s.enabled){var e=s,n=+new Date,i=n-(r||n);e.diff=i,e.prev=r,e.curr=n,r=n;for(var a=new Array(arguments.length),o=0;o<a.length;o++)a[o]=arguments[o];a[0]=t.coerce(a[0]),"string"!=typeof a[0]&&a.unshift("%O");var l=0;a[0]=a[0].replace(/%([a-zA-Z%])/g,(function(r,n){if("%%"===r)return r;l++;var s=t.formatters[n];if("function"==typeof s){var i=a[l];r=s.call(e,i),a.splice(l,1),l--}return r})),t.formatArgs.call(e,a);var c=s.log||t.log||console.log.bind(console);c.apply(e,a)}}return s.namespace=e,s.enabled=t.enabled(e),s.useColors=t.useColors(),s.color=function(e){var r,n=0;for(r in e)n=(n<<5)-n+e.charCodeAt(r),n|=0;return t.colors[Math.abs(n)%t.colors.length]}(e),s.destroy=n,"function"==typeof t.init&&t.init(s),t.instances.push(s),s}function n(){var e=t.instances.indexOf(this);return-1!==e&&(t.instances.splice(e,1),!0)}(t=e.exports=r.debug=r.default=r).coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){t.enable("")},t.enable=function(e){var r;t.save(e),t.names=[],t.skips=[];var n=("string"==typeof e?e:"").split(/[\s,]+/),s=n.length;for(r=0;r<s;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.substr(1)+"$")):t.names.push(new RegExp("^"+e+"$")));for(r=0;r<t.instances.length;r++){var i=t.instances[r];i.enabled=t.enabled(i.namespace)}},t.enabled=function(e){if("*"===e[e.length-1])return!0;var r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=Un,t.instances=[],t.names=[],t.skips=[],t.formatters={}}(Dn,Dn.exports),function(e,t){function r(){var e;try{e=t.storage.debug}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e}(t=e.exports=Dn.exports).log=function(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)},t.formatArgs=function(e){var r=this.useColors;if(e[0]=(r?"%c":"")+this.namespace+(r?" %c":" ")+e[0]+(r?"%c ":" ")+"+"+t.humanize(this.diff),!r)return;var n="color: "+this.color;e.splice(1,0,n,"color: inherit");var s=0,i=0;e[0].replace(/%[a-zA-Z%]/g,(function(e){"%%"!==e&&(s++,"%c"===e&&(i=s))})),e.splice(i,0,n)},t.save=function(e){try{null==e?t.storage.removeItem("debug"):t.storage.debug=e}catch(e){}},t.load=r,t.useColors=function(){if("undefined"!=typeof window&&window.process&&"renderer"===window.process.type)return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(e){}}(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},t.enable(r())}(Ln,Ln.exports);var Bn={exports:{}};!function(e){function t(e){if(e)return function(e){for(var r in t.prototype)e[r]=t.prototype[r];return e}(e)}e.exports=t,t.prototype.on=t.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},t.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},t.prototype.off=t.prototype.removeListener=t.prototype.removeAllListeners=t.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,n=this._callbacks["$"+e];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var s=0;s<n.length;s++)if((r=n[s])===t||r.fn===t){n.splice(s,1);break}return 0===n.length&&delete this._callbacks["$"+e],this},t.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(r){n=0;for(var s=(r=r.slice(0)).length;n<s;++n)r[n].apply(this,t)}return this},t.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},t.prototype.hasListeners=function(e){return!!this.listeners(e).length}}(Bn);var jn={},$n={}.toString,qn=Array.isArray||function(e){return"[object Array]"==$n.call(e)},Kn=function(e){return Gn&&Buffer.isBuffer(e)||Hn&&(e instanceof ArrayBuffer||function(e){return"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer}(e))},Gn="function"==typeof Buffer&&"function"==typeof Buffer.isBuffer,Hn="function"==typeof ArrayBuffer;var Vn=qn,zn=Kn,Wn=Object.prototype.toString,Yn="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Wn.call(Blob),Qn="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Wn.call(File);function Xn(e,t){if(!e)return e;if(zn(e)){var r={_placeholder:!0,num:t.length};return t.push(e),r}if(Vn(e)){for(var n=new Array(e.length),s=0;s<e.length;s++)n[s]=Xn(e[s],t);return n}if("object"==typeof e&&!(e instanceof Date)){n={};for(var i in e)n[i]=Xn(e[i],t);return n}return e}function Jn(e,t){if(!e)return e;if(e&&e._placeholder)return t[e.num];if(Vn(e))for(var r=0;r<e.length;r++)e[r]=Jn(e[r],t);else if("object"==typeof e)for(var n in e)e[n]=Jn(e[n],t);return e}jn.deconstructPacket=function(e){var t=[],r=e.data,n=e;return n.data=Xn(r,t),n.attachments=t.length,{packet:n,buffers:t}},jn.reconstructPacket=function(e,t){return e.data=Jn(e.data,t),e.attachments=void 0,e},jn.removeBlobs=function(e,t){var r=0,n=e;!function e(s,i,a){if(!s)return s;if(Yn&&s instanceof Blob||Qn&&s instanceof File){r++;var o=new FileReader;o.onload=function(){a?a[i]=this.result:n=this.result,--r||t(n)},o.readAsArrayBuffer(s)}else if(Vn(s))for(var l=0;l<s.length;l++)e(s[l],l,s);else if("object"==typeof s&&!zn(s))for(var c in s)e(s[c],c,s)}(n),r||t(n)},function(e){var t=Ln.exports("socket.io-parser"),r=Bn.exports,n=jn,s=qn,i=Kn;function a(){}e.protocol=4,e.types=["CONNECT","DISCONNECT","EVENT","ACK","ERROR","BINARY_EVENT","BINARY_ACK"],e.CONNECT=0,e.DISCONNECT=1,e.EVENT=2,e.ACK=3,e.ERROR=4,e.BINARY_EVENT=5,e.BINARY_ACK=6,e.Encoder=a,e.Decoder=c;var o=e.ERROR+'"encode error"';function l(r){var n=""+r.type;if(e.BINARY_EVENT!==r.type&&e.BINARY_ACK!==r.type||(n+=r.attachments+"-"),r.nsp&&"/"!==r.nsp&&(n+=r.nsp+","),null!=r.id&&(n+=r.id),null!=r.data){var s=function(e){try{return JSON.stringify(e)}catch(e){return!1}}(r.data);if(!1===s)return o;n+=s}return t("encoded %j as %s",r,n),n}function c(){this.reconstructor=null}function d(e){this.reconPack=e,this.buffers=[]}function u(t){return{type:e.ERROR,data:"parser error: "+t}}a.prototype.encode=function(r,s){(t("encoding packet %j",r),e.BINARY_EVENT===r.type||e.BINARY_ACK===r.type)?function(e,t){function r(e){var r=n.deconstructPacket(e),s=l(r.packet),i=r.buffers;i.unshift(s),t(i)}n.removeBlobs(e,r)}(r,s):s([l(r)])},r(c.prototype),c.prototype.add=function(r){var n;if("string"==typeof r)n=function(r){var n=0,i={type:Number(r.charAt(0))};if(null==e.types[i.type])return u("unknown packet type "+i.type);if(e.BINARY_EVENT===i.type||e.BINARY_ACK===i.type){for(var a=n+1;"-"!==r.charAt(++n)&&n!=r.length;);var o=r.substring(a,n);if(o!=Number(o)||"-"!==r.charAt(n))throw new Error("Illegal attachments");i.attachments=Number(o)}if("/"===r.charAt(n+1)){for(a=n+1;++n;){if(","===(c=r.charAt(n)))break;if(n===r.length)break}i.nsp=r.substring(a,n)}else i.nsp="/";var l=r.charAt(n+1);if(""!==l&&Number(l)==l){for(a=n+1;++n;){var c;if(null==(c=r.charAt(n))||Number(c)!=c){--n;break}if(n===r.length)break}i.id=Number(r.substring(a,n+1))}if(r.charAt(++n)){var d=function(e){try{return JSON.parse(e)}catch(e){return!1}}(r.substr(n));if(!(!1!==d&&(i.type===e.ERROR||s(d))))return u("invalid payload");i.data=d}return t("decoded %s as %j",r,i),i}(r),e.BINARY_EVENT===n.type||e.BINARY_ACK===n.type?(this.reconstructor=new d(n),0===this.reconstructor.reconPack.attachments&&this.emit("decoded",n)):this.emit("decoded",n);else{if(!i(r)&&!r.base64)throw new Error("Unknown type: "+r);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");(n=this.reconstructor.takeBinaryData(r))&&(this.reconstructor=null,this.emit("decoded",n))}},c.prototype.destroy=function(){this.reconstructor&&this.reconstructor.finishedReconstruction()},d.prototype.takeBinaryData=function(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){var t=n.reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null},d.prototype.finishedReconstruction=function(){this.reconPack=null,this.buffers=[]}}(Rn);var Zn={exports:{}},es={},ts={exports:{}};try{ts.exports="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){ts.exports=!1}var rs,ns,ss,is,as=ts.exports,os=function(e){var t=e.xdomain,r=e.xscheme,n=e.enablesXDR;try{if("undefined"!=typeof XMLHttpRequest&&(!t||as))return new XMLHttpRequest}catch(e){}try{if("undefined"!=typeof XDomainRequest&&!r&&n)return new XDomainRequest}catch(e){}if(!t)try{return new(self[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}},ls={exports:{}},cs={},ds=Object.keys||function(e){var t=[],r=Object.prototype.hasOwnProperty;for(var n in e)r.call(e,n)&&t.push(n);return t};function us(){if(is)return ss;is=1;var e=function(){if(ns)return rs;ns=1;var e={}.toString;return rs=Array.isArray||function(t){return"[object Array]"==e.call(t)}}(),t=Object.prototype.toString,r="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===t.call(Blob),n="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===t.call(File);return ss=function t(s){if(!s||"object"!=typeof s)return!1;if(e(s)){for(var i=0,a=s.length;i<a;i++)if(t(s[i]))return!0;return!1}if("function"==typeof Buffer&&Buffer.isBuffer&&Buffer.isBuffer(s)||"function"==typeof ArrayBuffer&&s instanceof ArrayBuffer||r&&s instanceof Blob||n&&s instanceof File)return!0;if(s.toJSON&&"function"==typeof s.toJSON&&1===arguments.length)return t(s.toJSON(),!0);for(var o in s)if(Object.prototype.hasOwnProperty.call(s,o)&&t(s[o]))return!0;return!1},ss}var hs=function(e,t,r){var n=e.byteLength;if(t=t||0,r=r||n,e.slice)return e.slice(t,r);if(t<0&&(t+=n),r<0&&(r+=n),r>n&&(r=n),t>=n||t>=r||0===n)return new ArrayBuffer(0);for(var s=new Uint8Array(e),i=new Uint8Array(r-t),a=t,o=0;a<r;a++,o++)i[o]=s[a];return i.buffer},fs=function(e,t,r){var n=!1;return r=r||ps,s.count=e,0===e?t():s;function s(e,i){if(s.count<=0)throw new Error("after called too many times");--s.count,e?(n=!0,t(e),t=r):0!==s.count||n||t(null,i)}};function ps(){}
1
+ var Amity=function(e){"use strict";const t=Object.freeze({FILE:"file",IMAGE:"image",VIDEO:"video"}),r=Object.freeze({"1080P":"1080p","720P":"720p","480P":"480p","360P":"360p",ORIGINAL:"original"}),n=Object.freeze({UPLOADED:"uploaded",TRANSCODING:"transcoding",TRANSCODED:"transcoded",TRANSCODE_FAILED:"transcodeFailed"}),s=Object.freeze({LOW:"low",MEDIUM:"medium",HIGH:"high",ORIGINAL:"original"}),i=Object.freeze({ONLY_ADMIN_CAN_POST:"ONLY_ADMIN_CAN_POST",ADMIN_REVIEW_POST_REQUIRED:"ADMIN_REVIEW_POST_REQUIRED",ANYONE_CAN_POST:"ANYONE_CAN_POST"}),a=Object.freeze({ONLY_ADMIN_CAN_POST:{needApprovalOnPostCreation:!1,onlyAdminCanPost:!0},ADMIN_REVIEW_POST_REQUIRED:{needApprovalOnPostCreation:!0,onlyAdminCanPost:!1},ANYONE_CAN_POST:{needApprovalOnPostCreation:!1,onlyAdminCanPost:!1}}),o="ONLY_ADMIN_CAN_POST",l=Object.freeze({STORY:"story",CLIP:"clip",CHAT:"chat",POST:"post",MESSAGE:"message"}),c=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",AUDIO:"audio",CUSTOM:"custom"}),d=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",LIVESTREAM:"liveStream",POLL:"poll",CUSTOM:"custom"});const u=function(){try{return"v6.18.0-umd"}catch(e){return"__dev__"}}(),h=5,f="cache_then_server",p="For using Live Collection feature you need to enable Cache!",g="Observing unsynced object is not supported by Live Object.",m=864e5,y=6e5,v="dead",b=2e3,w=6e4,E=e=>JSON.stringify(e,((e,t)=>{return"object"==typeof t?(r=t,Object.keys(r).sort().reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:r[t]})),{})):t;var r})),S=e=>JSON.parse(e),T=(e,t)=>e===t||!(!e||!t)&&("object"==typeof e&&Object.keys(e).every((r=>T(e[r],t[r])))),C=e=>[400400,400300].includes(e),k="function"==typeof atob,A="function"==typeof btoa,I="function"==typeof Buffer,_="function"==typeof TextDecoder?new TextDecoder:void 0,R="function"==typeof TextEncoder?new TextEncoder:void 0,L=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),D=(e=>{let t={};return e.forEach(((e,r)=>t[e]=r)),t})(L),x=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,O=String.fromCharCode.bind(String),P="function"==typeof Uint8Array.from?Uint8Array.from.bind(Uint8Array):(e,t=(e=>e))=>new Uint8Array(Array.prototype.slice.call(e,0).map(t)),M=e=>e.replace(/[^A-Za-z0-9\+\/]/g,""),F=A?e=>btoa(e):I?e=>Buffer.from(e,"binary").toString("base64"):e=>{let t,r,n,s,i="";const a=e.length%3;for(let a=0;a<e.length;){if((r=e.charCodeAt(a++))>255||(n=e.charCodeAt(a++))>255||(s=e.charCodeAt(a++))>255)throw new TypeError("invalid character found");t=r<<16|n<<8|s,i+=L[t>>18&63]+L[t>>12&63]+L[t>>6&63]+L[63&t]}return a?i.slice(0,a-3)+"===".substring(a):i},U=I?e=>Buffer.from(e).toString("base64"):e=>{let t=[];for(let r=0,n=e.length;r<n;r+=4096)t.push(O.apply(null,e.subarray(r,r+4096)));return F(t.join(""))},N=e=>{if(e.length<2)return(t=e.charCodeAt(0))<128?e:t<2048?O(192|t>>>6)+O(128|63&t):O(224|t>>>12&15)+O(128|t>>>6&63)+O(128|63&t);var t=65536+1024*(e.charCodeAt(0)-55296)+(e.charCodeAt(1)-56320);return O(240|t>>>18&7)+O(128|t>>>12&63)+O(128|t>>>6&63)+O(128|63&t)},B=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,j=I?e=>Buffer.from(e,"utf8").toString("base64"):R?e=>U(R.encode(e)):e=>F(e.replace(B,N)),$=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,q=e=>{switch(e.length){case 4:var t=((7&e.charCodeAt(0))<<18|(63&e.charCodeAt(1))<<12|(63&e.charCodeAt(2))<<6|63&e.charCodeAt(3))-65536;return O(55296+(t>>>10))+O(56320+(1023&t));case 3:return O((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return O((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},K=k?e=>atob(M(e)):I?e=>Buffer.from(e,"base64").toString("binary"):e=>{if(e=e.replace(/\s+/g,""),!x.test(e))throw new TypeError("malformed base64.");e+="==".slice(2-(3&e.length));let t,r,n,s="";for(let i=0;i<e.length;)t=D[e.charAt(i++)]<<18|D[e.charAt(i++)]<<12|(r=D[e.charAt(i++)])<<6|(n=D[e.charAt(i++)]),s+=64===r?O(t>>16&255):64===n?O(t>>16&255,t>>8&255):O(t>>16&255,t>>8&255,255&t);return s},G=I?e=>P(Buffer.from(e,"base64")):e=>P(K(e),(e=>e.charCodeAt(0))),H=I?e=>Buffer.from(e,"base64").toString("utf8"):_?e=>_.decode(G(e)):e=>K(e).replace($,q),V=e=>H(M(e.replace(/[-_]/g,(e=>"-"==e?"+":"/")))),z=e=>["skip"].some((t=>t in e)),W=e=>["after","before","first","last","limit"].some((t=>t in e)),Y=e=>"limit"in e,Q=e=>(null==e?void 0:e.hasOwnProperty("data"))&&(null==e?void 0:e.hasOwnProperty("nextPage"))&&(null==e?void 0:e.hasOwnProperty("prevPage")),X=(e,t)=>{var r;if(!e||!Object.keys(e).length)return;let n={};return"skiplimit"===t?n={skip:null!==(r=e.after)&&void 0!==r?r:0,limit:e.limit}:"afterbefore"===t&&W(e)?((null==e?void 0:e.before)&&(n=Object.assign(Object.assign({},n),{before:e.before})),(null==e?void 0:e.after)&&(n=Object.assign(Object.assign({},n),{after:e.after})),Number.isNaN(Number(null==e?void 0:e.limit))||(n=Object.assign(Object.assign({},n),{limit:e.limit}))):"afterbeforeraw"===t&&(n=e),Object.keys(n).length?((e,t=!1)=>t?(e=>e.replace(/=/g,"").replace(/[+\/]/g,(e=>"+"==e?"-":"_")))(j(e)):j(e))(JSON.stringify(n)):void 0},J=e=>{if(!e)return;const t=JSON.parse(V(e));if(z(t))return{after:t.skip,limit:t.limit};if(W(t)){if("before"in t)return{before:t.before,limit:t.last};if("after"in t)return{after:t.after,limit:t.first}}},Z=e=>{if(!e)return;const t=JSON.parse(V(e));return Y(t)?t:void 0},ee=e=>"locally"in e,te=e=>"optimistically"in e,re=e=>ee(e)||te(e),ne=e=>null==e?void 0:e.hasOwnProperty("cachedAt"),se=(e,t=6e4)=>{var r;return Date.now()-(null!==(r=null==e?void 0:e.cachedAt)&&void 0!==r?r:0)<=t},ie=(e,...t)=>({func:e,args:t}),ae=(e,t=6e4)=>"cache_only"===e?{lifeSpan:1/0}:{lifeSpan:t<w?w:t},oe=({func:e,args:t},r,n=ae("cache_then_server"))=>{let s;const{lifeSpan:i}=ae("cache_then_server",n.lifeSpan);if(re(e)){try{s=te(e)?e.optimistically(...t):e.locally(...t)}catch(e){null==r||r(le(void 0,{origin:"local",loading:!1,error:e}))}const n=ne(s)&&se(s,i);if(null==r||r(le(s,{origin:"local",loading:!(ee(e)&&n)})),n)return}else null==r||r(le(void 0,{origin:"local",loading:!0}));e(...t).then((e=>{null==r||r(le(e,{origin:"server",loading:!1}))})).catch((e=>{null==r||r(le(void 0,{origin:"server",loading:!1,error:e}))}))};function le(e,t){return Q(e)||ne(e)?Object.assign(Object.assign({},t),e):Object.assign(Object.assign({},t),{data:e})}const ce={user:({userId:e})=>e,file:({fileId:e})=>e,role:({roleId:e})=>e,channel:({channelId:e})=>e,subChannel:({subChannelId:e})=>e,channelUsers:({channelId:e,userId:t})=>`${e}#${t}`,message:({messageId:e})=>e,messagePreviewChannel:({channelId:e})=>`${e}`,messagePreviewSubChannel:({subChannelId:e})=>`${e}`,channelUnreadInfo:({channelId:e})=>e,subChannelUnreadInfo:({subChannelId:e})=>e,channelMarker:({entityId:e,userId:t})=>`${e}#${t}`,subChannelMarker:({entityId:e,feedId:t,userId:r})=>`${e}#${t}#${r}`,messageMarker:({feedId:e,contentId:t,creatorId:r})=>`${e}#${t}#${r}`,feedMarker:({feedId:e,entityId:t})=>`${e}#${t}`,userMarker:({userId:e})=>e,community:({communityId:e})=>e,category:({categoryId:e})=>e,communityUsers:({communityId:e,userId:t})=>`${e}#${t}`,post:({postId:e})=>e,comment:({commentId:e})=>e,commentChildren:({commentId:e})=>e,poll:({pollId:e})=>e,reaction:({referenceType:e,referenceId:t})=>`${e}#${t}`,reactor:({reactionId:e})=>e,stream:({streamId:e})=>e,follow:({from:e,to:t})=>`${e}#${t}`,followInfo:({userId:e})=>e,followCount:({userId:e})=>e,feed:({targetId:e,feedId:t})=>`${e}#${t}`,story:({referenceId:e})=>e,storyTarget:({targetId:e})=>e},de=e=>ce[e],ue={users:"user",files:"file",roles:"role",stories:"story",storyTargets:"storyTarget",channels:"channel",messageFeeds:"subChannel",channelUsers:"channelUsers",messages:"message",messagePreviewChannel:"messagePreviewChannel",messagePreviewSubChannel:"messagePreviewSubChannel",channelUnreadInfo:"channelUnreadInfo",subChannelUnreadInfo:"subChannelUnreadInfo",userEntityMarkers:"channelMarker",userFeedMarkers:"subChannelMarker",contentMarkers:"messageMarker",feedMarkers:"feedMarker",userMarkers:"userMarker",communities:"community",categories:"category",communityUsers:"communityUsers",posts:"post",postChildren:"post",comments:"comment",commentChildren:"comment",polls:"poll",reactors:"reactor",reactions:"reaction",videoStreamings:"stream",follows:"follow",followCounts:"followCount",feeds:"feed"};function he(e=(new Date).toISOString()){return new Date(new Date(e).getTime()+1).toISOString()}class fe extends Error{constructor(e,t,r){super(`Amity SDK (${t}): ${e}`),this.code=t,this.level=r,this.type="ASC",this.timestamp=Date.now(),Error.captureStackTrace&&Error.captureStackTrace(this,fe)}}class pe extends fe{constructor(e,t,r){super(e,t,r)}}class ge extends fe{constructor(e=8e5,t="fatal"){super("Unexpected error",e,t)}}class me extends fe{constructor(e,t="SDK client is having connection issues"){super(`${t} (${e})`,"disconnected"===e?800211:800210,"error"),this.event=e}}let ye=null;const ve=()=>{if(!ye)throw new fe("There is no active client",8e5,"fatal");return ye},be=e=>{ye=e},we=e=>{const{log:t,cache:r}=ve();if(r)return t("cache/api/queryCache",{key:e}),Object.keys(r.data).filter((t=>{const r=S(t);return T(e,r)})).map((e=>r.data[e]))},Ee=e=>{const{log:t,cache:r}=ve();if(!r)return;t("cache/api/pullFromCache",e);const n=E(e);return r.data[n]?r.data[n]:void 0},Se=(e,t,r={cachedAt:Date.now()})=>{const{log:n,cache:s}=ve();if(!s)return!1;n("cache/api/pushToCache",{key:e,data:t,options:r}),!(null==r?void 0:r.hasOwnProperty("offline"))&&s.persistIf&&(r.offline=s.persistIf(e,t));const i=E(e);return s.data[i]=Object.assign({key:e,data:t},r),!0},Te=(e,t,r)=>{const{log:n,cache:s}=ve();if(!s)return!1;n("cache/api/mergeInCache",{key:e,mutation:t});const i=Ee(e);if(!i)return!1;const a="function"==typeof t?t(i.data):Object.assign(Object.assign({},i.data),t);return o=i.data,!("updatedAt"in(l=a)&&"updatedAt"in l&&new Date(l.updatedAt)<new Date(o.updatedAt))&&(Se(e,a,r),!0);var o,l},Ce=(e,t,r={cachedAt:Date.now()})=>{const{log:n,cache:s}=ve();if(!s)return!1;n("cache/api/upsertInCache",{key:e,data:t,options:r});return Ee(e)?Te(e,t,r):Se(e,t,r)},ke=(e,t=!1)=>{const{log:r,cache:n}=ve();if(!n)return!1;if(r("cache/api/dropFromCache",{key:e,exact:t}),!t)return Object.keys(n.data).map((e=>S(e))).filter((t=>T(e,t))).map((e=>ke(e,!0))).every((e=>e));const s=E(e);return s in n.data&&(delete n.data[s],!0)},Ae=(e,t,r)=>void 0!==r?e.filter((e=>JSON.stringify(e[t])===JSON.stringify(r))):e,Ie=(e,t,r)=>void 0!==r?e.filter((e=>"string"==typeof e[t]&&"string"==typeof r&&String(e[t]).toLowerCase().match(r.toLowerCase()))):e,_e=(e,t,r)=>(null==r?void 0:r.length)?e.filter((e=>Array.isArray(e[t])&&r.some((r=>e[t].includes(r))))):e,Re=(e,t,r)=>"all"===t?e:e.filter((e=>{var n;if("community"===e.type)return!0;const s=de("channelUsers")({channelId:e.channelId,userId:r}),i=null===(n=Ee(["channelUsers","get",s]))||void 0===n?void 0:n.data;return"member"===t?i&&"none"!==i.membership:!i||"none"===i.membership})),Le=(e,t)=>e.filter((({targetId:e,feedId:r})=>{var n;const s=null===(n=Ee(["feed","get",de("feed")({targetId:e,feedId:r})]))||void 0===n?void 0:n.data;return s&&s.feedType===t})),De=(e,t,r)=>"all"===t?e:e.filter((e=>{var n;const s=de("communityUsers")({communityId:e.communityId,userId:r}),i=null===(n=Ee(["communityUsers","get",s]))||void 0===n?void 0:n.data;return"member"===t?i&&"member"===i.communityMembership:!i||"none"!==i.communityMembership})),xe=(e,t)=>{const r=[];return e.reduce(((e,n)=>{var s;if("text"===n.dataType&&!n.children.length)return e;if(r.includes(n.postId))return e;if((null==t?void 0:t.includes(n.dataType))&&e.push(n),!n.children.length)return e;const i=null===(s=Ee(["post","get",n.children[0]]))||void 0===s?void 0:s.data;return i?r.includes(i.postId)?e:(null==t?void 0:t.includes(null==i?void 0:i.dataType))?(r.push(i.postId),e.push(i),e):e:e}),[])},Oe=(e,t)=>{const r=new RegExp(t,"i");return e.filter((e=>{var t;return!!e.userId.match(r)||e.user&&(null===(t=e.user.displayName)||void 0===t?void 0:t.match(r))}))},Pe=({displayName:e},{displayName:t})=>e===t?0:e<t?-1:1,Me=({name:e},{name:t})=>e.localeCompare(t),Fe=({createdAt:e},{createdAt:t})=>new Date(e).valueOf()-new Date(t).valueOf(),Ue=({localSortingDate:e},{localSortingDate:t})=>new Date(t).getTime()-new Date(e).getTime(),Ne=({createdAt:e},{createdAt:t})=>new Date(t).valueOf()-new Date(e).valueOf(),Be=({updatedAt:e=0},{updatedAt:t=0})=>new Date(e).valueOf()-new Date(t).valueOf(),je=({updatedAt:e=0},{updatedAt:t=0})=>new Date(t).valueOf()-new Date(e).valueOf(),$e=({lastActivity:e},{lastActivity:t})=>new Date(t).valueOf()-new Date(e).valueOf();let qe=null;const Ke=()=>{if(!qe)throw new fe("Connect client first",8e5,"fatal");return qe},Ge=e=>{qe={_id:e._id,userId:e.userId,path:e.path}};let He,Ve=[];const ze=e=>{clearTimeout(He),Ve.push(e),He=setTimeout((()=>{Ve.forEach((e=>e())),Ve=[]}),0)},We=["disconnected","error","connect_error","reconnect_error","reconnect_failed","sessionStateChange","tokenExpired"],Ye=["connect","message","disconnect","error","close","end","reconnect","user.didGlobalBan"],Qe=()=>{return{all:e=e||new Map,on:function(t,r){var n=e.get(t);n?n.push(r):e.set(t,[r])},off:function(t,r){var n=e.get(t);n&&(r?n.splice(n.indexOf(r)>>>0,1):e.set(t,[]))},emit:function(t,r){var n=e.get(t);n&&n.slice().map((function(e){e(r)})),(n=e.get("*"))&&n.slice().map((function(e){e(t,r)}))}};var e},Xe=(e,t,r,n)=>{const{log:s,emitter:i}=e,a=Date.now();s(`${t}(tmpid: ${a}) > listen`);const o=(...e)=>{s(`${t}(tmpid: ${a}) > trigger`,e);try{n(...e)}catch(e){s(`${t}(tmpid: ${a}) > error`,e)}};return i.on(r,o),()=>{s(`${t}(tmpid: ${a}) > dispose`),i.off(r,o)}},Je=(e,t)=>{const{emitter:r}=ve();ze((()=>{r.emit(e,t)}))};let Ze,et;async function tt(){var e;const{mqtt:t,emitter:r,token:n}=ve(),s=null!==(e=null==n?void 0:n.accessToken)&&void 0!==e?e:"",i=Ke();Ze===s&&et===i._id||(Ze=s,et=i._id,await t.connect({accessToken:Ze,userId:et}),((e,t)=>{Ye.forEach((r=>{e.on(r,((...e)=>{t.emit(r,1===e.length?e[0]:e)}))})),e.on("message",((e,r)=>{const n=JSON.parse(r.toString());t.emit(n.eventType,n.data)}))})(t,r))}var rt;e.SubscriptionLevels=void 0,(rt=e.SubscriptionLevels||(e.SubscriptionLevels={})).COMMUNITY="community",rt.POST="post",rt.COMMENT="comment",rt.POST_AND_COMMENT="post_and_comment",rt.USER="user";const nt=(e,t)=>{switch(t){case"post":return`${e}/post/+`;case"comment":return`${e}/post/+/comment/+`;case"post_and_comment":return`${e}/post/#`;default:return e}},st=e=>e.path.split("/user/")[0],it=({path:t},r=e.SubscriptionLevels.USER)=>nt(r===e.SubscriptionLevels.USER?t:t.replace(/^(\w*)/,"$1/social"),r),at=({channelId:e,subChannelId:t})=>{const r=Ke();return`${st(r)}/marker/channel/${e}/message/${t}`},ot=()=>{const e=Ke();return`${st(e)}/marker/user/${e._id}`},lt=()=>st(Ke()),ct=()=>{const e=Ke();return`${st(e)}/smartfeed/${e._id}/channels`},dt=()=>{const e=Ke();return`${st(e)}/smartfeed/${e._id}/messagefeeds`},ut=()=>{const e=Ke();return`${st(e)}/smartfeed/${e._id}/messages`};function ht(e,t){const{mqtt:r}=ve();return tt(),r.subscribe(e,t)}var ft="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function pt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function gt(e){var t=e.default;if("function"==typeof t){var r=function(){return t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})})),r}var mt,yt,vt={exports:{}};function bt(){if(yt)return mt;yt=1;var e=1e3,t=60*e,r=60*t,n=24*r,s=7*n,i=365.25*n;function a(e,t,r,n){var s=t>=1.5*r;return Math.round(e/r)+" "+n+(s?"s":"")}return mt=function(o,l){l=l||{};var c=typeof o;if("string"===c&&o.length>0)return function(a){if((a=String(a)).length>100)return;var o=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(a);if(!o)return;var l=parseFloat(o[1]);switch((o[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return l*i;case"weeks":case"week":case"w":return l*s;case"days":case"day":case"d":return l*n;case"hours":case"hour":case"hrs":case"hr":case"h":return l*r;case"minutes":case"minute":case"mins":case"min":case"m":return l*t;case"seconds":case"second":case"secs":case"sec":case"s":return l*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return l;default:return}}(o);if("number"===c&&isFinite(o))return l.long?function(s){var i=Math.abs(s);if(i>=n)return a(s,i,n,"day");if(i>=r)return a(s,i,r,"hour");if(i>=t)return a(s,i,t,"minute");if(i>=e)return a(s,i,e,"second");return s+" ms"}(o):function(s){var i=Math.abs(s);if(i>=n)return Math.round(s/n)+"d";if(i>=r)return Math.round(s/r)+"h";if(i>=t)return Math.round(s/t)+"m";if(i>=e)return Math.round(s/e)+"s";return s+"ms"}(o);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(o))},mt}var wt=function(e){function t(e){let n,s,i,a=null;function o(...e){if(!o.enabled)return;const r=o,s=Number(new Date),i=s-(n||s);r.diff=i,r.prev=n,r.curr=s,n=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,s)=>{if("%%"===n)return"%";a++;const i=t.formatters[s];if("function"==typeof i){const t=e[a];n=i.call(r,t),e.splice(a,1),a--}return n})),t.formatArgs.call(r,e);(r.log||t.log).apply(r,e)}return o.namespace=e,o.useColors=t.useColors(),o.color=t.selectColor(e),o.extend=r,o.destroy=t.destroy,Object.defineProperty(o,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(s!==t.namespaces&&(s=t.namespaces,i=t.enabled(e)),i),set:e=>{a=e}}),"function"==typeof t.init&&t.init(o),o}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),s=n.length;for(r=0;r<s;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=bt(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t};!function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,s=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(s=n))})),t.splice(s,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=wt(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(vt,vt.exports);var Et,St=vt.exports;const Tt="object"==typeof globalThis?globalThis:"object"==typeof global?global:window,{process:Ct={}}=Tt,kt="production"===(null===(Et=Ct.env)||void 0===Et?void 0:Et.NODE_ENV),At={EU:"eu",SG:"sg",US:"us"},It={http:"https://api.{region}.amity.co",mqtt:"wss://sse.{region}.amity.co:443/mqtt"};function _t(e,t){return It[e].replace("{region}",t)}function Rt(e,t){return function(){return e.apply(t,arguments)}}const{toString:Lt}=Object.prototype,{getPrototypeOf:Dt}=Object,xt=(Ot=Object.create(null),e=>{const t=Lt.call(e);return Ot[t]||(Ot[t]=t.slice(8,-1).toLowerCase())});var Ot;const Pt=e=>(e=e.toLowerCase(),t=>xt(t)===e),Mt=e=>t=>typeof t===e,{isArray:Ft}=Array,Ut=Mt("undefined");const Nt=Pt("ArrayBuffer");const Bt=Mt("string"),jt=Mt("function"),$t=Mt("number"),qt=e=>null!==e&&"object"==typeof e,Kt=e=>{if("object"!==xt(e))return!1;const t=Dt(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)},Gt=Pt("Date"),Ht=Pt("File"),Vt=Pt("Blob"),zt=Pt("FileList"),Wt=Pt("URLSearchParams");function Yt(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let n,s;if("object"!=typeof e&&(e=[e]),Ft(e))for(n=0,s=e.length;n<s;n++)t.call(null,e[n],n,e);else{const s=r?Object.getOwnPropertyNames(e):Object.keys(e),i=s.length;let a;for(n=0;n<i;n++)a=s[n],t.call(null,e[a],a,e)}}function Qt(e,t){t=t.toLowerCase();const r=Object.keys(e);let n,s=r.length;for(;s-- >0;)if(n=r[s],t===n.toLowerCase())return n;return null}const Xt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,Jt=e=>!Ut(e)&&e!==Xt;const Zt=(er="undefined"!=typeof Uint8Array&&Dt(Uint8Array),e=>er&&e instanceof er);var er;const tr=Pt("HTMLFormElement"),rr=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),nr=Pt("RegExp"),sr=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};Yt(r,((r,s)=>{!1!==t(r,s,e)&&(n[s]=r)})),Object.defineProperties(e,n)};var ir={isArray:Ft,isArrayBuffer:Nt,isBuffer:function(e){return null!==e&&!Ut(e)&&null!==e.constructor&&!Ut(e.constructor)&&jt(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{const t="[object FormData]";return e&&("function"==typeof FormData&&e instanceof FormData||Lt.call(e)===t||jt(e.toString)&&e.toString()===t)},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Nt(e.buffer),t},isString:Bt,isNumber:$t,isBoolean:e=>!0===e||!1===e,isObject:qt,isPlainObject:Kt,isUndefined:Ut,isDate:Gt,isFile:Ht,isBlob:Vt,isRegExp:nr,isFunction:jt,isStream:e=>qt(e)&&jt(e.pipe),isURLSearchParams:Wt,isTypedArray:Zt,isFileList:zt,forEach:Yt,merge:function e(){const{caseless:t}=Jt(this)&&this||{},r={},n=(n,s)=>{const i=t&&Qt(r,s)||s;Kt(r[i])&&Kt(n)?r[i]=e(r[i],n):Kt(n)?r[i]=e({},n):Ft(n)?r[i]=n.slice():r[i]=n};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&Yt(arguments[e],n);return r},extend:(e,t,r,{allOwnKeys:n}={})=>(Yt(t,((t,n)=>{r&&jt(t)?e[n]=Rt(t,r):e[n]=t}),{allOwnKeys:n}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,n)=>{let s,i,a;const o={};if(t=t||{},null==e)return t;do{for(s=Object.getOwnPropertyNames(e),i=s.length;i-- >0;)a=s[i],n&&!n(a,e,t)||o[a]||(t[a]=e[a],o[a]=!0);e=!1!==r&&Dt(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:xt,kindOfTest:Pt,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return-1!==n&&n===r},toArray:e=>{if(!e)return null;if(Ft(e))return e;let t=e.length;if(!$t(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let n;for(;(n=r.next())&&!n.done;){const r=n.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const n=[];for(;null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm:tr,hasOwnProperty:rr,hasOwnProp:rr,reduceDescriptors:sr,freezeMethods:e=>{sr(e,((t,r)=>{if(jt(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const n=e[r];jt(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))}))},toObjectSet:(e,t)=>{const r={},n=e=>{e.forEach((e=>{r[e]=!0}))};return Ft(e)?n(e):n(String(e).split(t)),r},toCamelCase:e=>e.toLowerCase().replace(/[_-\s]([a-z\d])(\w*)/g,(function(e,t,r){return t.toUpperCase()+r})),noop:()=>{},toFiniteNumber:(e,t)=>(e=+e,Number.isFinite(e)?e:t),findKey:Qt,global:Xt,isContextDefined:Jt,toJSONObject:e=>{const t=new Array(10),r=(e,n)=>{if(qt(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[n]=e;const s=Ft(e)?[]:{};return Yt(e,((e,t)=>{const i=r(e,n+1);!Ut(i)&&(s[t]=i)})),t[n]=void 0,s}}return e};return r(e,0)}};function ar(e,t,r,n,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),s&&(this.response=s)}ir.inherits(ar,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:ir.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const or=ar.prototype,lr={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach((e=>{lr[e]={value:e}})),Object.defineProperties(ar,lr),Object.defineProperty(or,"isAxiosError",{value:!0}),ar.from=(e,t,r,n,s,i)=>{const a=Object.create(or);return ir.toFlatObject(e,a,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),ar.call(a,e.message,t,r,n,s),a.cause=e,a.name=e.name,i&&Object.assign(a,i),a};var cr="object"==typeof self?self.FormData:window.FormData;function dr(e){return ir.isPlainObject(e)||ir.isArray(e)}function ur(e){return ir.endsWith(e,"[]")?e.slice(0,-2):e}function hr(e,t,r){return e?e.concat(t).map((function(e,t){return e=ur(e),!r&&t?"["+e+"]":e})).join(r?".":""):t}const fr=ir.toFlatObject(ir,{},null,(function(e){return/^is[A-Z]/.test(e)}));function pr(e,t,r){if(!ir.isObject(e))throw new TypeError("target must be an object");t=t||new(cr||FormData);const n=(r=ir.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!ir.isUndefined(t[e])}))).metaTokens,s=r.visitor||d,i=r.dots,a=r.indexes,o=(r.Blob||"undefined"!=typeof Blob&&Blob)&&((l=t)&&ir.isFunction(l.append)&&"FormData"===l[Symbol.toStringTag]&&l[Symbol.iterator]);var l;if(!ir.isFunction(s))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(ir.isDate(e))return e.toISOString();if(!o&&ir.isBlob(e))throw new ar("Blob is not supported. Use a Buffer instead.");return ir.isArrayBuffer(e)||ir.isTypedArray(e)?o&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function d(e,r,s){let o=e;if(e&&!s&&"object"==typeof e)if(ir.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if(ir.isArray(e)&&function(e){return ir.isArray(e)&&!e.some(dr)}(e)||ir.isFileList(e)||ir.endsWith(r,"[]")&&(o=ir.toArray(e)))return r=ur(r),o.forEach((function(e,n){!ir.isUndefined(e)&&null!==e&&t.append(!0===a?hr([r],n,i):null===a?r:r+"[]",c(e))})),!1;return!!dr(e)||(t.append(hr(s,r,i),c(e)),!1)}const u=[],h=Object.assign(fr,{defaultVisitor:d,convertValue:c,isVisitable:dr});if(!ir.isObject(e))throw new TypeError("data must be an object");return function e(r,n){if(!ir.isUndefined(r)){if(-1!==u.indexOf(r))throw Error("Circular reference detected in "+n.join("."));u.push(r),ir.forEach(r,(function(r,i){!0===(!(ir.isUndefined(r)||null===r)&&s.call(t,r,ir.isString(i)?i.trim():i,n,h))&&e(r,n?n.concat(i):[i])})),u.pop()}}(e),t}function gr(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function mr(e,t){this._pairs=[],e&&pr(e,this,t)}const yr=mr.prototype;function vr(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function br(e,t,r){if(!t)return e;const n=r&&r.encode||vr,s=r&&r.serialize;let i;if(i=s?s(t,r):ir.isURLSearchParams(t)?t.toString():new mr(t,r).toString(n),i){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+i}return e}yr.append=function(e,t){this._pairs.push([e,t])},yr.toString=function(e){const t=e?function(t){return e.call(this,t,gr)}:gr;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};class wr{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){ir.forEach(this.handlers,(function(t){null!==t&&e(t)}))}}var Er={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Sr="undefined"!=typeof URLSearchParams?URLSearchParams:mr,Tr=FormData;const Cr=(()=>{let e;return("undefined"==typeof navigator||"ReactNative"!==(e=navigator.product)&&"NativeScript"!==e&&"NS"!==e)&&("undefined"!=typeof window&&"undefined"!=typeof document)})(),kr="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts;var Ar={isBrowser:!0,classes:{URLSearchParams:Sr,FormData:Tr,Blob:Blob},isStandardBrowserEnv:Cr,isStandardBrowserWebWorkerEnv:kr,protocols:["http","https","file","blob","url","data"]};function Ir(e){function t(e,r,n,s){let i=e[s++];const a=Number.isFinite(+i),o=s>=e.length;if(i=!i&&ir.isArray(n)?n.length:i,o)return ir.hasOwnProp(n,i)?n[i]=[n[i],r]:n[i]=r,!a;n[i]&&ir.isObject(n[i])||(n[i]=[]);return t(e,r,n[i],s)&&ir.isArray(n[i])&&(n[i]=function(e){const t={},r=Object.keys(e);let n;const s=r.length;let i;for(n=0;n<s;n++)i=r[n],t[i]=e[i];return t}(n[i])),!a}if(ir.isFormData(e)&&ir.isFunction(e.entries)){const r={};return ir.forEachEntry(e,((e,n)=>{t(function(e){return ir.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),n,r,0)})),r}return null}const _r={"Content-Type":void 0};const Rr={transitional:Er,adapter:["xhr","http"],transformRequest:[function(e,t){const r=t.getContentType()||"",n=r.indexOf("application/json")>-1,s=ir.isObject(e);s&&ir.isHTMLForm(e)&&(e=new FormData(e));if(ir.isFormData(e))return n&&n?JSON.stringify(Ir(e)):e;if(ir.isArrayBuffer(e)||ir.isBuffer(e)||ir.isStream(e)||ir.isFile(e)||ir.isBlob(e))return e;if(ir.isArrayBufferView(e))return e.buffer;if(ir.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let i;if(s){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return pr(e,new Ar.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,n){return Ar.isNode&&ir.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((i=ir.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return pr(i?{"files[]":e}:e,t&&new t,this.formSerializer)}}return s||n?(t.setContentType("application/json",!1),function(e,t,r){if(ir.isString(e))try{return(t||JSON.parse)(e),ir.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Rr.transitional,r=t&&t.forcedJSONParsing,n="json"===this.responseType;if(e&&ir.isString(e)&&(r&&!this.responseType||n)){const r=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(e){if(r){if("SyntaxError"===e.name)throw ar.from(e,ar.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Ar.classes.FormData,Blob:Ar.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};ir.forEach(["delete","get","head"],(function(e){Rr.headers[e]={}})),ir.forEach(["post","put","patch"],(function(e){Rr.headers[e]=ir.merge(_r)}));const Lr=ir.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const Dr=Symbol("internals");function xr(e){return e&&String(e).trim().toLowerCase()}function Or(e){return!1===e||null==e?e:ir.isArray(e)?e.map(Or):String(e)}function Pr(e,t,r,n){return ir.isFunction(n)?n.call(this,t,r):ir.isString(t)?ir.isString(n)?-1!==t.indexOf(n):ir.isRegExp(n)?n.test(t):void 0:void 0}class Mr{constructor(e){e&&this.set(e)}set(e,t,r){const n=this;function s(e,t,r){const s=xr(t);if(!s)throw new Error("header name must be a non-empty string");const i=ir.findKey(n,s);(!i||void 0===n[i]||!0===r||void 0===r&&!1!==n[i])&&(n[i||t]=Or(e))}const i=(e,t)=>ir.forEach(e,((e,r)=>s(e,r,t)));return ir.isPlainObject(e)||e instanceof this.constructor?i(e,t):ir.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z]+$/.test(e.trim())?i((e=>{const t={};let r,n,s;return e&&e.split("\n").forEach((function(e){s=e.indexOf(":"),r=e.substring(0,s).trim().toLowerCase(),n=e.substring(s+1).trim(),!r||t[r]&&Lr[r]||("set-cookie"===r?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)})),t})(e),t):null!=e&&s(t,e,r),this}get(e,t){if(e=xr(e)){const r=ir.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}(e);if(ir.isFunction(t))return t.call(this,e,r);if(ir.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=xr(e)){const r=ir.findKey(this,e);return!(!r||t&&!Pr(0,this[r],r,t))}return!1}delete(e,t){const r=this;let n=!1;function s(e){if(e=xr(e)){const s=ir.findKey(r,e);!s||t&&!Pr(0,r[s],s,t)||(delete r[s],n=!0)}}return ir.isArray(e)?e.forEach(s):s(e),n}clear(){return Object.keys(this).forEach(this.delete.bind(this))}normalize(e){const t=this,r={};return ir.forEach(this,((n,s)=>{const i=ir.findKey(r,s);if(i)return t[i]=Or(n),void delete t[s];const a=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,r)=>t.toUpperCase()+r))}(s):String(s).trim();a!==s&&delete t[s],t[a]=Or(n),r[a]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return ir.forEach(this,((r,n)=>{null!=r&&!1!==r&&(t[n]=e&&ir.isArray(r)?r.join(", "):r)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((([e,t])=>e+": "+t)).join("\n")}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach((e=>r.set(e))),r}static accessor(e){const t=(this[Dr]=this[Dr]={accessors:{}}).accessors,r=this.prototype;function n(e){const n=xr(e);t[n]||(!function(e,t){const r=ir.toCamelCase(" "+t);["get","set","has"].forEach((n=>{Object.defineProperty(e,n+r,{value:function(e,r,s){return this[n].call(this,t,e,r,s)},configurable:!0})}))}(r,e),t[n]=!0)}return ir.isArray(e)?e.forEach(n):n(e),this}}function Fr(e,t){const r=this||Rr,n=t||r,s=Mr.from(n.headers);let i=n.data;return ir.forEach(e,(function(e){i=e.call(r,i,s.normalize(),t?t.status:void 0)})),s.normalize(),i}function Ur(e){return!(!e||!e.__CANCEL__)}function Nr(e,t,r){ar.call(this,null==e?"canceled":e,ar.ERR_CANCELED,t,r),this.name="CanceledError"}Mr.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent"]),ir.freezeMethods(Mr.prototype),ir.freezeMethods(Mr),ir.inherits(Nr,ar,{__CANCEL__:!0});var Br=Ar.isStandardBrowserEnv?{write:function(e,t,r,n,s,i){const a=[];a.push(e+"="+encodeURIComponent(t)),ir.isNumber(r)&&a.push("expires="+new Date(r).toGMTString()),ir.isString(n)&&a.push("path="+n),ir.isString(s)&&a.push("domain="+s),!0===i&&a.push("secure"),document.cookie=a.join("; ")},read:function(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}};function jr(e,t){return e&&!function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}(t)?function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}var $r=Ar.isStandardBrowserEnv?function(){const e=/(msie|trident)/i.test(navigator.userAgent),t=document.createElement("a");let r;function n(r){let n=r;return e&&(t.setAttribute("href",n),n=t.href),t.setAttribute("href",n),{href:t.href,protocol:t.protocol?t.protocol.replace(/:$/,""):"",host:t.host,search:t.search?t.search.replace(/^\?/,""):"",hash:t.hash?t.hash.replace(/^#/,""):"",hostname:t.hostname,port:t.port,pathname:"/"===t.pathname.charAt(0)?t.pathname:"/"+t.pathname}}return r=n(window.location.href),function(e){const t=ir.isString(e)?n(e):e;return t.protocol===r.protocol&&t.host===r.host}}():function(){return!0};function qr(e,t){let r=0;const n=function(e,t){e=e||10;const r=new Array(e),n=new Array(e);let s,i=0,a=0;return t=void 0!==t?t:1e3,function(o){const l=Date.now(),c=n[a];s||(s=l),r[i]=o,n[i]=l;let d=a,u=0;for(;d!==i;)u+=r[d++],d%=e;if(i=(i+1)%e,i===a&&(a=(a+1)%e),l-s<t)return;const h=c&&l-c;return h?Math.round(1e3*u/h):void 0}}(50,250);return s=>{const i=s.loaded,a=s.lengthComputable?s.total:void 0,o=i-r,l=n(o);r=i;const c={loaded:i,total:a,progress:a?i/a:void 0,bytes:o,rate:l||void 0,estimated:l&&a&&i<=a?(a-i)/l:void 0,event:s};c[t?"download":"upload"]=!0,e(c)}}var Kr="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,r){let n=e.data;const s=Mr.from(e.headers).normalize(),i=e.responseType;let a;function o(){e.cancelToken&&e.cancelToken.unsubscribe(a),e.signal&&e.signal.removeEventListener("abort",a)}ir.isFormData(n)&&(Ar.isStandardBrowserEnv||Ar.isStandardBrowserWebWorkerEnv)&&s.setContentType(!1);let l=new XMLHttpRequest;if(e.auth){const t=e.auth.username||"",r=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";s.set("Authorization","Basic "+btoa(t+":"+r))}const c=jr(e.baseURL,e.url);function d(){if(!l)return;const n=Mr.from("getAllResponseHeaders"in l&&l.getAllResponseHeaders());!function(e,t,r){const n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new ar("Request failed with status code "+r.status,[ar.ERR_BAD_REQUEST,ar.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}((function(e){t(e),o()}),(function(e){r(e),o()}),{data:i&&"text"!==i&&"json"!==i?l.response:l.responseText,status:l.status,statusText:l.statusText,headers:n,config:e,request:l}),l=null}if(l.open(e.method.toUpperCase(),br(c,e.params,e.paramsSerializer),!0),l.timeout=e.timeout,"onloadend"in l?l.onloadend=d:l.onreadystatechange=function(){l&&4===l.readyState&&(0!==l.status||l.responseURL&&0===l.responseURL.indexOf("file:"))&&setTimeout(d)},l.onabort=function(){l&&(r(new ar("Request aborted",ar.ECONNABORTED,e,l)),l=null)},l.onerror=function(){r(new ar("Network Error",ar.ERR_NETWORK,e,l)),l=null},l.ontimeout=function(){let t=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const n=e.transitional||Er;e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),r(new ar(t,n.clarifyTimeoutError?ar.ETIMEDOUT:ar.ECONNABORTED,e,l)),l=null},Ar.isStandardBrowserEnv){const t=(e.withCredentials||$r(c))&&e.xsrfCookieName&&Br.read(e.xsrfCookieName);t&&s.set(e.xsrfHeaderName,t)}void 0===n&&s.setContentType(null),"setRequestHeader"in l&&ir.forEach(s.toJSON(),(function(e,t){l.setRequestHeader(t,e)})),ir.isUndefined(e.withCredentials)||(l.withCredentials=!!e.withCredentials),i&&"json"!==i&&(l.responseType=e.responseType),"function"==typeof e.onDownloadProgress&&l.addEventListener("progress",qr(e.onDownloadProgress,!0)),"function"==typeof e.onUploadProgress&&l.upload&&l.upload.addEventListener("progress",qr(e.onUploadProgress)),(e.cancelToken||e.signal)&&(a=t=>{l&&(r(!t||t.type?new Nr(null,e,l):t),l.abort(),l=null)},e.cancelToken&&e.cancelToken.subscribe(a),e.signal&&(e.signal.aborted?a():e.signal.addEventListener("abort",a)));const u=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(c);u&&-1===Ar.protocols.indexOf(u)?r(new ar("Unsupported protocol "+u+":",ar.ERR_BAD_REQUEST,e)):l.send(n||null)}))};const Gr={http:null,xhr:Kr};ir.forEach(Gr,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}}));var Hr=e=>{e=ir.isArray(e)?e:[e];const{length:t}=e;let r,n;for(let s=0;s<t&&(r=e[s],!(n=ir.isString(r)?Gr[r.toLowerCase()]:r));s++);if(!n){if(!1===n)throw new ar(`Adapter ${r} is not supported by the environment`,"ERR_NOT_SUPPORT");throw new Error(ir.hasOwnProp(Gr,r)?`Adapter '${r}' is not available in the build`:`Unknown adapter '${r}'`)}if(!ir.isFunction(n))throw new TypeError("adapter is not a function");return n};function Vr(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Nr(null,e)}function zr(e){Vr(e),e.headers=Mr.from(e.headers),e.data=Fr.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Hr(e.adapter||Rr.adapter)(e).then((function(t){return Vr(e),t.data=Fr.call(e,e.transformResponse,t),t.headers=Mr.from(t.headers),t}),(function(t){return Ur(t)||(Vr(e),t&&t.response&&(t.response.data=Fr.call(e,e.transformResponse,t.response),t.response.headers=Mr.from(t.response.headers))),Promise.reject(t)}))}const Wr=e=>e instanceof Mr?e.toJSON():e;function Yr(e,t){t=t||{};const r={};function n(e,t,r){return ir.isPlainObject(e)&&ir.isPlainObject(t)?ir.merge.call({caseless:r},e,t):ir.isPlainObject(t)?ir.merge({},t):ir.isArray(t)?t.slice():t}function s(e,t,r){return ir.isUndefined(t)?ir.isUndefined(e)?void 0:n(void 0,e,r):n(e,t,r)}function i(e,t){if(!ir.isUndefined(t))return n(void 0,t)}function a(e,t){return ir.isUndefined(t)?ir.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function o(r,s,i){return i in t?n(r,s):i in e?n(void 0,r):void 0}const l={url:i,method:i,data:i,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:o,headers:(e,t)=>s(Wr(e),Wr(t),!0)};return ir.forEach(Object.keys(e).concat(Object.keys(t)),(function(n){const i=l[n]||s,a=i(e[n],t[n],n);ir.isUndefined(a)&&i!==o||(r[n]=a)})),r}const Qr="1.2.3",Xr={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{Xr[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));const Jr={};Xr.transitional=function(e,t,r){function n(e,t){return"[Axios v1.2.3] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,s,i)=>{if(!1===e)throw new ar(n(s," has been removed"+(t?" in "+t:"")),ar.ERR_DEPRECATED);return t&&!Jr[s]&&(Jr[s]=!0,console.warn(n(s," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,s,i)}};var Zr={assertOptions:function(e,t,r){if("object"!=typeof e)throw new ar("options must be an object",ar.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let s=n.length;for(;s-- >0;){const i=n[s],a=t[i];if(a){const t=e[i],r=void 0===t||a(t,i,e);if(!0!==r)throw new ar("option "+i+" must be "+r,ar.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new ar("Unknown option "+i,ar.ERR_BAD_OPTION)}},validators:Xr};const en=Zr.validators;class tn{constructor(e){this.defaults=e,this.interceptors={request:new wr,response:new wr}}request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=Yr(this.defaults,t);const{transitional:r,paramsSerializer:n,headers:s}=t;let i;void 0!==r&&Zr.assertOptions(r,{silentJSONParsing:en.transitional(en.boolean),forcedJSONParsing:en.transitional(en.boolean),clarifyTimeoutError:en.transitional(en.boolean)},!1),void 0!==n&&Zr.assertOptions(n,{encode:en.function,serialize:en.function},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase(),i=s&&ir.merge(s.common,s[t.method]),i&&ir.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete s[e]})),t.headers=Mr.concat(i,s);const a=[];let o=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(o=o&&e.synchronous,a.unshift(e.fulfilled,e.rejected))}));const l=[];let c;this.interceptors.response.forEach((function(e){l.push(e.fulfilled,e.rejected)}));let d,u=0;if(!o){const e=[zr.bind(this),void 0];for(e.unshift.apply(e,a),e.push.apply(e,l),d=e.length,c=Promise.resolve(t);u<d;)c=c.then(e[u++],e[u++]);return c}d=a.length;let h=t;for(u=0;u<d;){const e=a[u++],t=a[u++];try{h=e(h)}catch(e){t.call(this,e);break}}try{c=zr.call(this,h)}catch(e){return Promise.reject(e)}for(u=0,d=l.length;u<d;)c=c.then(l[u++],l[u++]);return c}getUri(e){return br(jr((e=Yr(this.defaults,e)).baseURL,e.url),e.params,e.paramsSerializer)}}ir.forEach(["delete","get","head","options"],(function(e){tn.prototype[e]=function(t,r){return this.request(Yr(r||{},{method:e,url:t,data:(r||{}).data}))}})),ir.forEach(["post","put","patch"],(function(e){function t(t){return function(r,n,s){return this.request(Yr(s||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:n}))}}tn.prototype[e]=t(),tn.prototype[e+"Form"]=t(!0)}));class rn{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise((function(e){t=e}));const r=this;this.promise.then((e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null})),this.promise.then=e=>{let t;const n=new Promise((e=>{r.subscribe(e),t=e})).then(e);return n.cancel=function(){r.unsubscribe(t)},n},e((function(e,n,s){r.reason||(r.reason=new Nr(e,n,s),t(r.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}static source(){let e;return{token:new rn((function(t){e=t})),cancel:e}}}const nn={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(nn).forEach((([e,t])=>{nn[t]=e}));const sn=function e(t){const r=new tn(t),n=Rt(tn.prototype.request,r);return ir.extend(n,tn.prototype,r,{allOwnKeys:!0}),ir.extend(n,r,null,{allOwnKeys:!0}),n.create=function(r){return e(Yr(t,r))},n}(Rr);sn.Axios=tn,sn.CanceledError=Nr,sn.CancelToken=rn,sn.isCancel=Ur,sn.VERSION=Qr,sn.toFormData=pr,sn.AxiosError=ar,sn.Cancel=sn.CanceledError,sn.all=function(e){return Promise.all(e)},sn.spread=function(e){return function(t){return e.apply(null,t)}},sn.isAxiosError=function(e){return ir.isObject(e)&&!0===e.isAxiosError},sn.mergeConfig=Yr,sn.AxiosHeaders=Mr,sn.formToJSON=e=>Ir(ir.isHTMLForm(e)?new FormData(e):e),sn.HttpStatusCode=nn,sn.default=sn;var an={exports:{}};an.exports=ln;var on=an.exports.HttpsAgent=ln;function ln(){}var cn;!function(e){e.UserDeleted="User Deleted",e.UserGlobalBanned="User Global Banned",e.TokenExpired="Token Expired"}(cn||(cn={}));const dn=new AbortController,un=e=>{switch(e){case cn.UserGlobalBanned:throw new fe(e,400312,"fatal");case cn.UserDeleted:throw new fe(e,400100,"fatal");case cn.TokenExpired:throw Je("tokenExpired","tokenExpired"),new fe(e,800403,"fatal");default:throw new fe("Request Aborted",8e5,"error")}},hn=e=>{const t={maxSockets:100,maxFreeSockets:10,timeout:6e4,freeSocketTimeout:3e4},r=sn.create({baseURL:e,httpAgent:new an.exports(t),httpsAgent:new on(t),signal:dn.signal});return r.interceptors.request.use((e=>{if("/api/v4/sessions"===e.url)return e;if(e.metadata){const{tokenExpiry:t,isGlobalBanned:r,isUserDeleted:n}=e.metadata;r&&(dn.abort(),un(cn.UserGlobalBanned)),n&&(dn.abort(),un(cn.UserDeleted)),t&&Date.now()>=Date.parse(t)&&(dn.abort(cn.UserDeleted),un(cn.TokenExpired))}return e})),r.interceptors.response.use((e=>e),(e=>{var t,r;const{response:n}=e;if(400100===(null==n?void 0:n.data.code)&&Je("tokenTerminated","terminated"),(null===(t=null==n?void 0:n.data)||void 0===t?void 0:t.status)&&(e=>{if("success"===e.status)return e.data;if("fail"===e.status)throw new ge(e.code);if("error"===e.status)throw new pe(e.message,e.code,"error")})(null==n?void 0:n.data),dn.signal.aborted)throw e;throw new Error(null!==(r=null==n?void 0:n.data)&&void 0!==r?r:e)})),r.defaults.paramsSerializer={encode:e=>encodeURIComponent(e)},r};var fn={exports:{}},pn=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,gn=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],mn=function(e){var t=e,r=e.indexOf("["),n=e.indexOf("]");-1!=r&&-1!=n&&(e=e.substring(0,r)+e.substring(r,n).replace(/:/g,";")+e.substring(n,e.length));for(var s=pn.exec(e||""),i={},a=14;a--;)i[gn[a]]=s[a]||"";return-1!=r&&-1!=n&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i},yn={exports:{}},vn={exports:{}},bn=1e3,wn=6e4,En=60*wn,Sn=24*En,Tn=365.25*Sn,Cn=function(e,t){t=t||{};var r=typeof e;if("string"===r&&e.length>0)return function(e){if((e=String(e)).length>100)return;var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(!t)return;var r=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return r*Tn;case"days":case"day":case"d":return r*Sn;case"hours":case"hour":case"hrs":case"hr":case"h":return r*En;case"minutes":case"minute":case"mins":case"min":case"m":return r*wn;case"seconds":case"second":case"secs":case"sec":case"s":return r*bn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}(e);if("number"===r&&!1===isNaN(e))return t.long?function(e){return kn(e,Sn,"day")||kn(e,En,"hour")||kn(e,wn,"minute")||kn(e,bn,"second")||e+" ms"}(e):function(e){if(e>=Sn)return Math.round(e/Sn)+"d";if(e>=En)return Math.round(e/En)+"h";if(e>=wn)return Math.round(e/wn)+"m";if(e>=bn)return Math.round(e/bn)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function kn(e,t,r){if(!(e<t))return e<1.5*t?Math.floor(e/t)+" "+r:Math.ceil(e/t)+" "+r+"s"}!function(e,t){function r(e){var r;function s(){if(s.enabled){var e=s,n=+new Date,i=n-(r||n);e.diff=i,e.prev=r,e.curr=n,r=n;for(var a=new Array(arguments.length),o=0;o<a.length;o++)a[o]=arguments[o];a[0]=t.coerce(a[0]),"string"!=typeof a[0]&&a.unshift("%O");var l=0;a[0]=a[0].replace(/%([a-zA-Z%])/g,(function(r,n){if("%%"===r)return r;l++;var s=t.formatters[n];if("function"==typeof s){var i=a[l];r=s.call(e,i),a.splice(l,1),l--}return r})),t.formatArgs.call(e,a);var c=s.log||t.log||console.log.bind(console);c.apply(e,a)}}return s.namespace=e,s.enabled=t.enabled(e),s.useColors=t.useColors(),s.color=function(e){var r,n=0;for(r in e)n=(n<<5)-n+e.charCodeAt(r),n|=0;return t.colors[Math.abs(n)%t.colors.length]}(e),s.destroy=n,"function"==typeof t.init&&t.init(s),t.instances.push(s),s}function n(){var e=t.instances.indexOf(this);return-1!==e&&(t.instances.splice(e,1),!0)}(t=e.exports=r.debug=r.default=r).coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){t.enable("")},t.enable=function(e){var r;t.save(e),t.names=[],t.skips=[];var n=("string"==typeof e?e:"").split(/[\s,]+/),s=n.length;for(r=0;r<s;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.substr(1)+"$")):t.names.push(new RegExp("^"+e+"$")));for(r=0;r<t.instances.length;r++){var i=t.instances[r];i.enabled=t.enabled(i.namespace)}},t.enabled=function(e){if("*"===e[e.length-1])return!0;var r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=Cn,t.instances=[],t.names=[],t.skips=[],t.formatters={}}(vn,vn.exports),function(e,t){function r(){var e;try{e=t.storage.debug}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e}(t=e.exports=vn.exports).log=function(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)},t.formatArgs=function(e){var r=this.useColors;if(e[0]=(r?"%c":"")+this.namespace+(r?" %c":" ")+e[0]+(r?"%c ":" ")+"+"+t.humanize(this.diff),!r)return;var n="color: "+this.color;e.splice(1,0,n,"color: inherit");var s=0,i=0;e[0].replace(/%[a-zA-Z%]/g,(function(e){"%%"!==e&&(s++,"%c"===e&&(i=s))})),e.splice(i,0,n)},t.save=function(e){try{null==e?t.storage.removeItem("debug"):t.storage.debug=e}catch(e){}},t.load=r,t.useColors=function(){if("undefined"!=typeof window&&window.process&&"renderer"===window.process.type)return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(e){}}(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},t.enable(r())}(yn,yn.exports);var An=mn,In=yn.exports("socket.io-client:url"),_n=function(e,t){var r=e;t=t||"undefined"!=typeof location&&location,null==e&&(e=t.protocol+"//"+t.host);"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?t.protocol+e:t.host+e),/^(https?|wss?):\/\//.test(e)||(In("protocol-less url %s",e),e=void 0!==t?t.protocol+"//"+e:"https://"+e),In("parse %s",e),r=An(e));r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443"));r.path=r.path||"/";var n=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+n+":"+r.port,r.href=r.protocol+"://"+n+(t&&t.port===r.port?"":":"+r.port),r};var Rn={},Ln={exports:{}},Dn={exports:{}},xn=1e3,On=6e4,Pn=60*On,Mn=24*Pn,Fn=365.25*Mn,Un=function(e,t){t=t||{};var r=typeof e;if("string"===r&&e.length>0)return function(e){if((e=String(e)).length>100)return;var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(!t)return;var r=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return r*Fn;case"days":case"day":case"d":return r*Mn;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Pn;case"minutes":case"minute":case"mins":case"min":case"m":return r*On;case"seconds":case"second":case"secs":case"sec":case"s":return r*xn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}(e);if("number"===r&&!1===isNaN(e))return t.long?function(e){return Nn(e,Mn,"day")||Nn(e,Pn,"hour")||Nn(e,On,"minute")||Nn(e,xn,"second")||e+" ms"}(e):function(e){if(e>=Mn)return Math.round(e/Mn)+"d";if(e>=Pn)return Math.round(e/Pn)+"h";if(e>=On)return Math.round(e/On)+"m";if(e>=xn)return Math.round(e/xn)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function Nn(e,t,r){if(!(e<t))return e<1.5*t?Math.floor(e/t)+" "+r:Math.ceil(e/t)+" "+r+"s"}!function(e,t){function r(e){var r;function s(){if(s.enabled){var e=s,n=+new Date,i=n-(r||n);e.diff=i,e.prev=r,e.curr=n,r=n;for(var a=new Array(arguments.length),o=0;o<a.length;o++)a[o]=arguments[o];a[0]=t.coerce(a[0]),"string"!=typeof a[0]&&a.unshift("%O");var l=0;a[0]=a[0].replace(/%([a-zA-Z%])/g,(function(r,n){if("%%"===r)return r;l++;var s=t.formatters[n];if("function"==typeof s){var i=a[l];r=s.call(e,i),a.splice(l,1),l--}return r})),t.formatArgs.call(e,a);var c=s.log||t.log||console.log.bind(console);c.apply(e,a)}}return s.namespace=e,s.enabled=t.enabled(e),s.useColors=t.useColors(),s.color=function(e){var r,n=0;for(r in e)n=(n<<5)-n+e.charCodeAt(r),n|=0;return t.colors[Math.abs(n)%t.colors.length]}(e),s.destroy=n,"function"==typeof t.init&&t.init(s),t.instances.push(s),s}function n(){var e=t.instances.indexOf(this);return-1!==e&&(t.instances.splice(e,1),!0)}(t=e.exports=r.debug=r.default=r).coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){t.enable("")},t.enable=function(e){var r;t.save(e),t.names=[],t.skips=[];var n=("string"==typeof e?e:"").split(/[\s,]+/),s=n.length;for(r=0;r<s;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.substr(1)+"$")):t.names.push(new RegExp("^"+e+"$")));for(r=0;r<t.instances.length;r++){var i=t.instances[r];i.enabled=t.enabled(i.namespace)}},t.enabled=function(e){if("*"===e[e.length-1])return!0;var r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=Un,t.instances=[],t.names=[],t.skips=[],t.formatters={}}(Dn,Dn.exports),function(e,t){function r(){var e;try{e=t.storage.debug}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e}(t=e.exports=Dn.exports).log=function(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)},t.formatArgs=function(e){var r=this.useColors;if(e[0]=(r?"%c":"")+this.namespace+(r?" %c":" ")+e[0]+(r?"%c ":" ")+"+"+t.humanize(this.diff),!r)return;var n="color: "+this.color;e.splice(1,0,n,"color: inherit");var s=0,i=0;e[0].replace(/%[a-zA-Z%]/g,(function(e){"%%"!==e&&(s++,"%c"===e&&(i=s))})),e.splice(i,0,n)},t.save=function(e){try{null==e?t.storage.removeItem("debug"):t.storage.debug=e}catch(e){}},t.load=r,t.useColors=function(){if("undefined"!=typeof window&&window.process&&"renderer"===window.process.type)return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(e){}}(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},t.enable(r())}(Ln,Ln.exports);var Bn={exports:{}};!function(e){function t(e){if(e)return function(e){for(var r in t.prototype)e[r]=t.prototype[r];return e}(e)}e.exports=t,t.prototype.on=t.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},t.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},t.prototype.off=t.prototype.removeListener=t.prototype.removeAllListeners=t.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,n=this._callbacks["$"+e];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var s=0;s<n.length;s++)if((r=n[s])===t||r.fn===t){n.splice(s,1);break}return 0===n.length&&delete this._callbacks["$"+e],this},t.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(r){n=0;for(var s=(r=r.slice(0)).length;n<s;++n)r[n].apply(this,t)}return this},t.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},t.prototype.hasListeners=function(e){return!!this.listeners(e).length}}(Bn);var jn={},$n={}.toString,qn=Array.isArray||function(e){return"[object Array]"==$n.call(e)},Kn=function(e){return Gn&&Buffer.isBuffer(e)||Hn&&(e instanceof ArrayBuffer||function(e){return"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer}(e))},Gn="function"==typeof Buffer&&"function"==typeof Buffer.isBuffer,Hn="function"==typeof ArrayBuffer;var Vn=qn,zn=Kn,Wn=Object.prototype.toString,Yn="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Wn.call(Blob),Qn="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Wn.call(File);function Xn(e,t){if(!e)return e;if(zn(e)){var r={_placeholder:!0,num:t.length};return t.push(e),r}if(Vn(e)){for(var n=new Array(e.length),s=0;s<e.length;s++)n[s]=Xn(e[s],t);return n}if("object"==typeof e&&!(e instanceof Date)){n={};for(var i in e)n[i]=Xn(e[i],t);return n}return e}function Jn(e,t){if(!e)return e;if(e&&e._placeholder)return t[e.num];if(Vn(e))for(var r=0;r<e.length;r++)e[r]=Jn(e[r],t);else if("object"==typeof e)for(var n in e)e[n]=Jn(e[n],t);return e}jn.deconstructPacket=function(e){var t=[],r=e.data,n=e;return n.data=Xn(r,t),n.attachments=t.length,{packet:n,buffers:t}},jn.reconstructPacket=function(e,t){return e.data=Jn(e.data,t),e.attachments=void 0,e},jn.removeBlobs=function(e,t){var r=0,n=e;!function e(s,i,a){if(!s)return s;if(Yn&&s instanceof Blob||Qn&&s instanceof File){r++;var o=new FileReader;o.onload=function(){a?a[i]=this.result:n=this.result,--r||t(n)},o.readAsArrayBuffer(s)}else if(Vn(s))for(var l=0;l<s.length;l++)e(s[l],l,s);else if("object"==typeof s&&!zn(s))for(var c in s)e(s[c],c,s)}(n),r||t(n)},function(e){var t=Ln.exports("socket.io-parser"),r=Bn.exports,n=jn,s=qn,i=Kn;function a(){}e.protocol=4,e.types=["CONNECT","DISCONNECT","EVENT","ACK","ERROR","BINARY_EVENT","BINARY_ACK"],e.CONNECT=0,e.DISCONNECT=1,e.EVENT=2,e.ACK=3,e.ERROR=4,e.BINARY_EVENT=5,e.BINARY_ACK=6,e.Encoder=a,e.Decoder=c;var o=e.ERROR+'"encode error"';function l(r){var n=""+r.type;if(e.BINARY_EVENT!==r.type&&e.BINARY_ACK!==r.type||(n+=r.attachments+"-"),r.nsp&&"/"!==r.nsp&&(n+=r.nsp+","),null!=r.id&&(n+=r.id),null!=r.data){var s=function(e){try{return JSON.stringify(e)}catch(e){return!1}}(r.data);if(!1===s)return o;n+=s}return t("encoded %j as %s",r,n),n}function c(){this.reconstructor=null}function d(e){this.reconPack=e,this.buffers=[]}function u(t){return{type:e.ERROR,data:"parser error: "+t}}a.prototype.encode=function(r,s){(t("encoding packet %j",r),e.BINARY_EVENT===r.type||e.BINARY_ACK===r.type)?function(e,t){function r(e){var r=n.deconstructPacket(e),s=l(r.packet),i=r.buffers;i.unshift(s),t(i)}n.removeBlobs(e,r)}(r,s):s([l(r)])},r(c.prototype),c.prototype.add=function(r){var n;if("string"==typeof r)n=function(r){var n=0,i={type:Number(r.charAt(0))};if(null==e.types[i.type])return u("unknown packet type "+i.type);if(e.BINARY_EVENT===i.type||e.BINARY_ACK===i.type){for(var a=n+1;"-"!==r.charAt(++n)&&n!=r.length;);var o=r.substring(a,n);if(o!=Number(o)||"-"!==r.charAt(n))throw new Error("Illegal attachments");i.attachments=Number(o)}if("/"===r.charAt(n+1)){for(a=n+1;++n;){if(","===(c=r.charAt(n)))break;if(n===r.length)break}i.nsp=r.substring(a,n)}else i.nsp="/";var l=r.charAt(n+1);if(""!==l&&Number(l)==l){for(a=n+1;++n;){var c;if(null==(c=r.charAt(n))||Number(c)!=c){--n;break}if(n===r.length)break}i.id=Number(r.substring(a,n+1))}if(r.charAt(++n)){var d=function(e){try{return JSON.parse(e)}catch(e){return!1}}(r.substr(n));if(!(!1!==d&&(i.type===e.ERROR||s(d))))return u("invalid payload");i.data=d}return t("decoded %s as %j",r,i),i}(r),e.BINARY_EVENT===n.type||e.BINARY_ACK===n.type?(this.reconstructor=new d(n),0===this.reconstructor.reconPack.attachments&&this.emit("decoded",n)):this.emit("decoded",n);else{if(!i(r)&&!r.base64)throw new Error("Unknown type: "+r);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");(n=this.reconstructor.takeBinaryData(r))&&(this.reconstructor=null,this.emit("decoded",n))}},c.prototype.destroy=function(){this.reconstructor&&this.reconstructor.finishedReconstruction()},d.prototype.takeBinaryData=function(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){var t=n.reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null},d.prototype.finishedReconstruction=function(){this.reconPack=null,this.buffers=[]}}(Rn);var Zn={exports:{}},es={},ts={exports:{}};try{ts.exports="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){ts.exports=!1}var rs,ns,ss,is,as=ts.exports,os=function(e){var t=e.xdomain,r=e.xscheme,n=e.enablesXDR;try{if("undefined"!=typeof XMLHttpRequest&&(!t||as))return new XMLHttpRequest}catch(e){}try{if("undefined"!=typeof XDomainRequest&&!r&&n)return new XDomainRequest}catch(e){}if(!t)try{return new(self[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}},ls={exports:{}},cs={},ds=Object.keys||function(e){var t=[],r=Object.prototype.hasOwnProperty;for(var n in e)r.call(e,n)&&t.push(n);return t};function us(){if(is)return ss;is=1;var e=function(){if(ns)return rs;ns=1;var e={}.toString;return rs=Array.isArray||function(t){return"[object Array]"==e.call(t)}}(),t=Object.prototype.toString,r="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===t.call(Blob),n="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===t.call(File);return ss=function t(s){if(!s||"object"!=typeof s)return!1;if(e(s)){for(var i=0,a=s.length;i<a;i++)if(t(s[i]))return!0;return!1}if("function"==typeof Buffer&&Buffer.isBuffer&&Buffer.isBuffer(s)||"function"==typeof ArrayBuffer&&s instanceof ArrayBuffer||r&&s instanceof Blob||n&&s instanceof File)return!0;if(s.toJSON&&"function"==typeof s.toJSON&&1===arguments.length)return t(s.toJSON(),!0);for(var o in s)if(Object.prototype.hasOwnProperty.call(s,o)&&t(s[o]))return!0;return!1},ss}var hs=function(e,t,r){var n=e.byteLength;if(t=t||0,r=r||n,e.slice)return e.slice(t,r);if(t<0&&(t+=n),r<0&&(r+=n),r>n&&(r=n),t>=n||t>=r||0===n)return new ArrayBuffer(0);for(var s=new Uint8Array(e),i=new Uint8Array(r-t),a=t,o=0;a<r;a++,o++)i[o]=s[a];return i.buffer},fs=function(e,t,r){var n=!1;return r=r||ps,s.count=e,0===e?t():s;function s(e,i){if(s.count<=0)throw new Error("after called too many times");--s.count,e?(n=!0,t(e),t=r):0!==s.count||n||t(null,i)}};function ps(){}
2
2
  /*! https://mths.be/utf8js v2.1.2 by @mathias */var gs,ms,ys,vs=String.fromCharCode;function bs(e){for(var t,r,n=[],s=0,i=e.length;s<i;)(t=e.charCodeAt(s++))>=55296&&t<=56319&&s<i?56320==(64512&(r=e.charCodeAt(s++)))?n.push(((1023&t)<<10)+(1023&r)+65536):(n.push(t),s--):n.push(t);return n}function ws(e,t){if(e>=55296&&e<=57343){if(t)throw Error("Lone surrogate U+"+e.toString(16).toUpperCase()+" is not a scalar value");return!1}return!0}function Es(e,t){return vs(e>>t&63|128)}function Ss(e,t){if(0==(4294967168&e))return vs(e);var r="";return 0==(4294965248&e)?r=vs(e>>6&31|192):0==(4294901760&e)?(ws(e,t)||(e=65533),r=vs(e>>12&15|224),r+=Es(e,6)):0==(4292870144&e)&&(r=vs(e>>18&7|240),r+=Es(e,12),r+=Es(e,6)),r+=vs(63&e|128)}function Ts(){if(ys>=ms)throw Error("Invalid byte index");var e=255&gs[ys];if(ys++,128==(192&e))return 63&e;throw Error("Invalid continuation byte")}function Cs(e){var t,r;if(ys>ms)throw Error("Invalid byte index");if(ys==ms)return!1;if(t=255&gs[ys],ys++,0==(128&t))return t;if(192==(224&t)){if((r=(31&t)<<6|Ts())>=128)return r;throw Error("Invalid continuation byte")}if(224==(240&t)){if((r=(15&t)<<12|Ts()<<6|Ts())>=2048)return ws(r,e)?r:65533;throw Error("Invalid continuation byte")}if(240==(248&t)&&(r=(7&t)<<18|Ts()<<12|Ts()<<6|Ts())>=65536&&r<=1114111)return r;throw Error("Invalid UTF-8 detected")}var ks,As,Is,_s={version:"2.1.2",encode:function(e,t){for(var r=!1!==(t=t||{}).strict,n=bs(e),s=n.length,i=-1,a="";++i<s;)a+=Ss(n[i],r);return a},decode:function(e,t){var r=!1!==(t=t||{}).strict;gs=bs(e),ms=gs.length,ys=0;for(var n,s=[];!1!==(n=Cs(r));)s.push(n);return function(e){for(var t,r=e.length,n=-1,s="";++n<r;)(t=e[n])>65535&&(s+=vs((t-=65536)>>>10&1023|55296),t=56320|1023&t),s+=vs(t);return s}(s)}},Rs={};function Ls(){if(Is)return As;Is=1;var e=void 0!==e?e:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder&&MozBlobBuilder,t=function(){try{return 2===new Blob(["hi"]).size}catch(e){return!1}}(),r=t&&function(){try{return 2===new Blob([new Uint8Array([1,2])]).size}catch(e){return!1}}(),n=e&&e.prototype.append&&e.prototype.getBlob;function s(e){return e.map((function(e){if(e.buffer instanceof ArrayBuffer){var t=e.buffer;if(e.byteLength!==t.byteLength){var r=new Uint8Array(e.byteLength);r.set(new Uint8Array(t,e.byteOffset,e.byteLength)),t=r.buffer}return t}return e}))}function i(t,r){r=r||{};var n=new e;return s(t).forEach((function(e){n.append(e)})),r.type?n.getBlob(r.type):n.getBlob()}function a(e,t){return new Blob(s(e),t||{})}return"undefined"!=typeof Blob&&(i.prototype=Blob.prototype,a.prototype=Blob.prototype),As=t?r?Blob:a:n?i:void 0}!function(e){var t,r=ds,n=us(),s=hs,i=fs,a=_s;"undefined"!=typeof ArrayBuffer&&(ks||(ks=1,function(){for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=new Uint8Array(256),r=0;r<e.length;r++)t[e.charCodeAt(r)]=r;Rs.encode=function(t){var r,n=new Uint8Array(t),s=n.length,i="";for(r=0;r<s;r+=3)i+=e[n[r]>>2],i+=e[(3&n[r])<<4|n[r+1]>>4],i+=e[(15&n[r+1])<<2|n[r+2]>>6],i+=e[63&n[r+2]];return s%3==2?i=i.substring(0,i.length-1)+"=":s%3==1&&(i=i.substring(0,i.length-2)+"=="),i},Rs.decode=function(e){var r,n,s,i,a,o=.75*e.length,l=e.length,c=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);var d=new ArrayBuffer(o),u=new Uint8Array(d);for(r=0;r<l;r+=4)n=t[e.charCodeAt(r)],s=t[e.charCodeAt(r+1)],i=t[e.charCodeAt(r+2)],a=t[e.charCodeAt(r+3)],u[c++]=n<<2|s>>4,u[c++]=(15&s)<<4|i>>2,u[c++]=(3&i)<<6|63&a;return d}}()),t=Rs);var o="undefined"!=typeof navigator&&/Android/i.test(navigator.userAgent),l="undefined"!=typeof navigator&&/PhantomJS/i.test(navigator.userAgent),c=o||l;e.protocol=3;var d=e.packets={open:0,close:1,ping:2,pong:3,message:4,upgrade:5,noop:6},u=r(d),h={type:"error",data:"parser error"},f=Ls();function p(e,t,r){for(var n=new Array(e.length),s=i(e.length,r),a=function(e,r,s){t(r,(function(t,r){n[e]=r,s(t,n)}))},o=0;o<e.length;o++)a(o,e[o],s)}e.encodePacket=function(t,r,n,s){"function"==typeof r&&(s=r,r=!1),"function"==typeof n&&(s=n,n=null);var i=void 0===t.data?void 0:t.data.buffer||t.data;if("undefined"!=typeof ArrayBuffer&&i instanceof ArrayBuffer)return function(t,r,n){if(!r)return e.encodeBase64Packet(t,n);var s=t.data,i=new Uint8Array(s),a=new Uint8Array(1+s.byteLength);a[0]=d[t.type];for(var o=0;o<i.length;o++)a[o+1]=i[o];return n(a.buffer)}(t,r,s);if(void 0!==f&&i instanceof f)return function(t,r,n){if(!r)return e.encodeBase64Packet(t,n);if(c)return function(t,r,n){if(!r)return e.encodeBase64Packet(t,n);var s=new FileReader;return s.onload=function(){e.encodePacket({type:t.type,data:s.result},r,!0,n)},s.readAsArrayBuffer(t.data)}(t,r,n);var s=new Uint8Array(1);s[0]=d[t.type];var i=new f([s.buffer,t.data]);return n(i)}(t,r,s);if(i&&i.base64)return function(t,r){var n="b"+e.packets[t.type]+t.data.data;return r(n)}(t,s);var o=d[t.type];return void 0!==t.data&&(o+=n?a.encode(String(t.data),{strict:!1}):String(t.data)),s(""+o)},e.encodeBase64Packet=function(t,r){var n,s="b"+e.packets[t.type];if(void 0!==f&&t.data instanceof f){var i=new FileReader;return i.onload=function(){var e=i.result.split(",")[1];r(s+e)},i.readAsDataURL(t.data)}try{n=String.fromCharCode.apply(null,new Uint8Array(t.data))}catch(e){for(var a=new Uint8Array(t.data),o=new Array(a.length),l=0;l<a.length;l++)o[l]=a[l];n=String.fromCharCode.apply(null,o)}return s+=btoa(n),r(s)},e.decodePacket=function(t,r,n){if(void 0===t)return h;if("string"==typeof t){if("b"===t.charAt(0))return e.decodeBase64Packet(t.substr(1),r);if(n&&!1===(t=function(e){try{e=a.decode(e,{strict:!1})}catch(e){return!1}return e}(t)))return h;var i=t.charAt(0);return Number(i)==i&&u[i]?t.length>1?{type:u[i],data:t.substring(1)}:{type:u[i]}:h}i=new Uint8Array(t)[0];var o=s(t,1);return f&&"blob"===r&&(o=new f([o])),{type:u[i],data:o}},e.decodeBase64Packet=function(e,r){var n=u[e.charAt(0)];if(!t)return{type:n,data:{base64:!0,data:e.substr(1)}};var s=t.decode(e.substr(1));return"blob"===r&&f&&(s=new f([s])),{type:n,data:s}},e.encodePayload=function(t,r,s){"function"==typeof r&&(s=r,r=null);var i=n(t);if(r&&i)return f&&!c?e.encodePayloadAsBlob(t,s):e.encodePayloadAsArrayBuffer(t,s);if(!t.length)return s("0:");p(t,(function(t,n){e.encodePacket(t,!!i&&r,!1,(function(e){n(null,function(e){return e.length+":"+e}(e))}))}),(function(e,t){return s(t.join(""))}))},e.decodePayload=function(t,r,n){if("string"!=typeof t)return e.decodePayloadAsBinary(t,r,n);var s;if("function"==typeof r&&(n=r,r=null),""===t)return n(h,0,1);for(var i,a,o="",l=0,c=t.length;l<c;l++){var d=t.charAt(l);if(":"===d){if(""===o||o!=(i=Number(o)))return n(h,0,1);if(o!=(a=t.substr(l+1,i)).length)return n(h,0,1);if(a.length){if(s=e.decodePacket(a,r,!1),h.type===s.type&&h.data===s.data)return n(h,0,1);if(!1===n(s,l+i,c))return}l+=i,o=""}else o+=d}return""!==o?n(h,0,1):void 0},e.encodePayloadAsArrayBuffer=function(t,r){if(!t.length)return r(new ArrayBuffer(0));p(t,(function(t,r){e.encodePacket(t,!0,!0,(function(e){return r(null,e)}))}),(function(e,t){var n=t.reduce((function(e,t){var r;return e+(r="string"==typeof t?t.length:t.byteLength).toString().length+r+2}),0),s=new Uint8Array(n),i=0;return t.forEach((function(e){var t="string"==typeof e,r=e;if(t){for(var n=new Uint8Array(e.length),a=0;a<e.length;a++)n[a]=e.charCodeAt(a);r=n.buffer}s[i++]=t?0:1;var o=r.byteLength.toString();for(a=0;a<o.length;a++)s[i++]=parseInt(o[a]);s[i++]=255;for(n=new Uint8Array(r),a=0;a<n.length;a++)s[i++]=n[a]})),r(s.buffer)}))},e.encodePayloadAsBlob=function(t,r){p(t,(function(t,r){e.encodePacket(t,!0,!0,(function(e){var t=new Uint8Array(1);if(t[0]=1,"string"==typeof e){for(var n=new Uint8Array(e.length),s=0;s<e.length;s++)n[s]=e.charCodeAt(s);e=n.buffer,t[0]=0}var i=(e instanceof ArrayBuffer?e.byteLength:e.size).toString(),a=new Uint8Array(i.length+1);for(s=0;s<i.length;s++)a[s]=parseInt(i[s]);if(a[i.length]=255,f){var o=new f([t.buffer,a.buffer,e]);r(null,o)}}))}),(function(e,t){return r(new f(t))}))},e.decodePayloadAsBinary=function(t,r,n){"function"==typeof r&&(n=r,r=null);for(var i=t,a=[];i.byteLength>0;){for(var o=new Uint8Array(i),l=0===o[0],c="",d=1;255!==o[d];d++){if(c.length>310)return n(h,0,1);c+=o[d]}i=s(i,2+c.length),c=parseInt(c);var u=s(i,0,c);if(l)try{u=String.fromCharCode.apply(null,new Uint8Array(u))}catch(e){var f=new Uint8Array(u);u="";for(d=0;d<f.length;d++)u+=String.fromCharCode(f[d])}a.push(u),i=s(i,c)}var p=a.length;a.forEach((function(t,s){n(e.decodePacket(t,r,!0),s,p)}))}}(cs);var Ds,xs,Os={exports:{}};function Ps(){if(xs)return Ds;xs=1;var e=cs;function t(e){this.path=e.path,this.hostname=e.hostname,this.port=e.port,this.secure=e.secure,this.query=e.query,this.timestampParam=e.timestampParam,this.timestampRequests=e.timestampRequests,this.readyState="",this.agent=e.agent||!1,this.socket=e.socket,this.enablesXDR=e.enablesXDR,this.pfx=e.pfx,this.key=e.key,this.passphrase=e.passphrase,this.cert=e.cert,this.ca=e.ca,this.ciphers=e.ciphers,this.rejectUnauthorized=e.rejectUnauthorized,this.forceNode=e.forceNode,this.isReactNative=e.isReactNative,this.extraHeaders=e.extraHeaders,this.localAddress=e.localAddress}return Ds=t,(0,Os.exports)(t.prototype),t.prototype.onError=function(e,t){var r=new Error(e);return r.type="TransportError",r.description=t,this.emit("error",r),this},t.prototype.open=function(){return"closed"!==this.readyState&&""!==this.readyState||(this.readyState="opening",this.doOpen()),this},t.prototype.close=function(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this},t.prototype.send=function(e){if("open"!==this.readyState)throw new Error("Transport not open");this.write(e)},t.prototype.onOpen=function(){this.readyState="open",this.writable=!0,this.emit("open")},t.prototype.onData=function(t){var r=e.decodePacket(t,this.socket.binaryType);this.onPacket(r)},t.prototype.onPacket=function(e){this.emit("packet",e)},t.prototype.onClose=function(){this.readyState="closed",this.emit("close")},Ds}!function(e){function t(e){if(e)return function(e){for(var r in t.prototype)e[r]=t.prototype[r];return e}(e)}e.exports=t,t.prototype.on=t.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},t.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},t.prototype.off=t.prototype.removeListener=t.prototype.removeAllListeners=t.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,n=this._callbacks["$"+e];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var s=0;s<n.length;s++)if((r=n[s])===t||r.fn===t){n.splice(s,1);break}return this},t.prototype.emit=function(e){this._callbacks=this._callbacks||{};var t=[].slice.call(arguments,1),r=this._callbacks["$"+e];if(r)for(var n=0,s=(r=r.slice(0)).length;n<s;++n)r[n].apply(this,t);return this},t.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},t.prototype.hasListeners=function(e){return!!this.listeners(e).length}}(Os);var Ms,Fs={};function Us(){return Ms||(Ms=1,Fs.encode=function(e){var t="";for(var r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t},Fs.decode=function(e){for(var t={},r=e.split("&"),n=0,s=r.length;n<s;n++){var i=r[n].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}),Fs}var Ns,Bs=function(e,t){var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e},js="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),$s={},qs=0,Ks=0;function Gs(e){var t="";do{t=js[e%64]+t,e=Math.floor(e/64)}while(e>0);return t}function Hs(){var e=Gs(+new Date);return e!==Ns?(qs=0,Ns=e):e+"."+Gs(qs++)}for(;Ks<64;Ks++)$s[js[Ks]]=Ks;Hs.encode=Gs,Hs.decode=function(e){var t=0;for(Ks=0;Ks<e.length;Ks++)t=64*t+$s[e.charAt(Ks)];return t};var Vs=Hs,zs={exports:{}},Ws={exports:{}},Ys=1e3,Qs=60*Ys,Xs=60*Qs,Js=24*Xs,Zs=365.25*Js,ei=function(e,t){t=t||{};var r=typeof e;if("string"===r&&e.length>0)return function(e){if((e=String(e)).length>100)return;var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(!t)return;var r=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return r*Zs;case"days":case"day":case"d":return r*Js;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Xs;case"minutes":case"minute":case"mins":case"min":case"m":return r*Qs;case"seconds":case"second":case"secs":case"sec":case"s":return r*Ys;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}(e);if("number"===r&&!1===isNaN(e))return t.long?function(e){return ti(e,Js,"day")||ti(e,Xs,"hour")||ti(e,Qs,"minute")||ti(e,Ys,"second")||e+" ms"}(e):function(e){if(e>=Js)return Math.round(e/Js)+"d";if(e>=Xs)return Math.round(e/Xs)+"h";if(e>=Qs)return Math.round(e/Qs)+"m";if(e>=Ys)return Math.round(e/Ys)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function ti(e,t,r){if(!(e<t))return e<1.5*t?Math.floor(e/t)+" "+r:Math.ceil(e/t)+" "+r+"s"}!function(e,t){function r(e){var r;function s(){if(s.enabled){var e=s,n=+new Date,i=n-(r||n);e.diff=i,e.prev=r,e.curr=n,r=n;for(var a=new Array(arguments.length),o=0;o<a.length;o++)a[o]=arguments[o];a[0]=t.coerce(a[0]),"string"!=typeof a[0]&&a.unshift("%O");var l=0;a[0]=a[0].replace(/%([a-zA-Z%])/g,(function(r,n){if("%%"===r)return r;l++;var s=t.formatters[n];if("function"==typeof s){var i=a[l];r=s.call(e,i),a.splice(l,1),l--}return r})),t.formatArgs.call(e,a);var c=s.log||t.log||console.log.bind(console);c.apply(e,a)}}return s.namespace=e,s.enabled=t.enabled(e),s.useColors=t.useColors(),s.color=function(e){var r,n=0;for(r in e)n=(n<<5)-n+e.charCodeAt(r),n|=0;return t.colors[Math.abs(n)%t.colors.length]}(e),s.destroy=n,"function"==typeof t.init&&t.init(s),t.instances.push(s),s}function n(){var e=t.instances.indexOf(this);return-1!==e&&(t.instances.splice(e,1),!0)}(t=e.exports=r.debug=r.default=r).coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){t.enable("")},t.enable=function(e){var r;t.save(e),t.names=[],t.skips=[];var n=("string"==typeof e?e:"").split(/[\s,]+/),s=n.length;for(r=0;r<s;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.substr(1)+"$")):t.names.push(new RegExp("^"+e+"$")));for(r=0;r<t.instances.length;r++){var i=t.instances[r];i.enabled=t.enabled(i.namespace)}},t.enabled=function(e){if("*"===e[e.length-1])return!0;var r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=ei,t.instances=[],t.names=[],t.skips=[],t.formatters={}}(Ws,Ws.exports),function(e,t){function r(){var e;try{e=t.storage.debug}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e}(t=e.exports=Ws.exports).log=function(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)},t.formatArgs=function(e){var r=this.useColors;if(e[0]=(r?"%c":"")+this.namespace+(r?" %c":" ")+e[0]+(r?"%c ":" ")+"+"+t.humanize(this.diff),!r)return;var n="color: "+this.color;e.splice(1,0,n,"color: inherit");var s=0,i=0;e[0].replace(/%[a-zA-Z%]/g,(function(e){"%%"!==e&&(s++,"%c"===e&&(i=s))})),e.splice(i,0,n)},t.save=function(e){try{null==e?t.storage.removeItem("debug"):t.storage.debug=e}catch(e){}},t.load=r,t.useColors=function(){if("undefined"!=typeof window&&window.process&&"renderer"===window.process.type)return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(e){}}(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},t.enable(r())}(zs,zs.exports);var ri=Ps(),ni=Us(),si=cs,ii=Bs,ai=Vs,oi=zs.exports("engine.io-client:polling"),li=di,ci=null!=new os({xdomain:!1}).responseType;function di(e){var t=e&&e.forceBase64;ci&&!t||(this.supportsBinary=!1),ri.call(this,e)}ii(di,ri),di.prototype.name="polling",di.prototype.doOpen=function(){this.poll()},di.prototype.pause=function(e){var t=this;function r(){oi("paused"),t.readyState="paused",e()}if(this.readyState="pausing",this.polling||!this.writable){var n=0;this.polling&&(oi("we are currently polling - waiting to pause"),n++,this.once("pollComplete",(function(){oi("pre-pause polling complete"),--n||r()}))),this.writable||(oi("we are currently writing - waiting to pause"),n++,this.once("drain",(function(){oi("pre-pause writing complete"),--n||r()})))}else r()},di.prototype.poll=function(){oi("polling"),this.polling=!0,this.doPoll(),this.emit("poll")},di.prototype.onData=function(e){var t=this;oi("polling got data %s",e);si.decodePayload(e,this.socket.binaryType,(function(e,r,n){if("opening"===t.readyState&&t.onOpen(),"close"===e.type)return t.onClose(),!1;t.onPacket(e)})),"closed"!==this.readyState&&(this.polling=!1,this.emit("pollComplete"),"open"===this.readyState?this.poll():oi('ignoring poll - transport state "%s"',this.readyState))},di.prototype.doClose=function(){var e=this;function t(){oi("writing close packet"),e.write([{type:"close"}])}"open"===this.readyState?(oi("transport open - closing"),t()):(oi("transport not open - deferring close"),this.once("open",t))},di.prototype.write=function(e){var t=this;this.writable=!1;var r=function(){t.writable=!0,t.emit("drain")};si.encodePayload(e,this.supportsBinary,(function(e){t.doWrite(e,r)}))},di.prototype.uri=function(){var e=this.query||{},t=this.secure?"https":"http",r="";return!1!==this.timestampRequests&&(e[this.timestampParam]=ai()),this.supportsBinary||e.sid||(e.b64=1),e=ni.encode(e),this.port&&("https"===t&&443!==Number(this.port)||"http"===t&&80!==Number(this.port))&&(r=":"+this.port),e.length&&(e="?"+e),t+"://"+(-1!==this.hostname.indexOf(":")?"["+this.hostname+"]":this.hostname)+r+this.path+e};var ui=os,hi=li,fi=Os.exports,pi=Bs,gi=zs.exports("engine.io-client:polling-xhr");function mi(){}function yi(e){if(hi.call(this,e),this.requestTimeout=e.requestTimeout,this.extraHeaders=e.extraHeaders,"undefined"!=typeof location){var t="https:"===location.protocol,r=location.port;r||(r=t?443:80),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||r!==e.port,this.xs=e.secure!==t}}function vi(e){this.method=e.method||"GET",this.uri=e.uri,this.xd=!!e.xd,this.xs=!!e.xs,this.async=!1!==e.async,this.data=void 0!==e.data?e.data:null,this.agent=e.agent,this.isBinary=e.isBinary,this.supportsBinary=e.supportsBinary,this.enablesXDR=e.enablesXDR,this.requestTimeout=e.requestTimeout,this.pfx=e.pfx,this.key=e.key,this.passphrase=e.passphrase,this.cert=e.cert,this.ca=e.ca,this.ciphers=e.ciphers,this.rejectUnauthorized=e.rejectUnauthorized,this.extraHeaders=e.extraHeaders,this.create()}if(ls.exports=yi,ls.exports.Request=vi,pi(yi,hi),yi.prototype.supportsBinary=!0,yi.prototype.request=function(e){return(e=e||{}).uri=this.uri(),e.xd=this.xd,e.xs=this.xs,e.agent=this.agent||!1,e.supportsBinary=this.supportsBinary,e.enablesXDR=this.enablesXDR,e.pfx=this.pfx,e.key=this.key,e.passphrase=this.passphrase,e.cert=this.cert,e.ca=this.ca,e.ciphers=this.ciphers,e.rejectUnauthorized=this.rejectUnauthorized,e.requestTimeout=this.requestTimeout,e.extraHeaders=this.extraHeaders,new vi(e)},yi.prototype.doWrite=function(e,t){var r="string"!=typeof e&&void 0!==e,n=this.request({method:"POST",data:e,isBinary:r}),s=this;n.on("success",t),n.on("error",(function(e){s.onError("xhr post error",e)})),this.sendXhr=n},yi.prototype.doPoll=function(){gi("xhr poll");var e=this.request(),t=this;e.on("data",(function(e){t.onData(e)})),e.on("error",(function(e){t.onError("xhr poll error",e)})),this.pollXhr=e},fi(vi.prototype),vi.prototype.create=function(){var e={agent:this.agent,xdomain:this.xd,xscheme:this.xs,enablesXDR:this.enablesXDR};e.pfx=this.pfx,e.key=this.key,e.passphrase=this.passphrase,e.cert=this.cert,e.ca=this.ca,e.ciphers=this.ciphers,e.rejectUnauthorized=this.rejectUnauthorized;var t=this.xhr=new ui(e),r=this;try{gi("xhr open %s: %s",this.method,this.uri),t.open(this.method,this.uri,this.async);try{if(this.extraHeaders)for(var n in t.setDisableHeaderCheck&&t.setDisableHeaderCheck(!0),this.extraHeaders)this.extraHeaders.hasOwnProperty(n)&&t.setRequestHeader(n,this.extraHeaders[n])}catch(e){}if("POST"===this.method)try{this.isBinary?t.setRequestHeader("Content-type","application/octet-stream"):t.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{t.setRequestHeader("Accept","*/*")}catch(e){}"withCredentials"in t&&(t.withCredentials=!0),this.requestTimeout&&(t.timeout=this.requestTimeout),this.hasXDR()?(t.onload=function(){r.onLoad()},t.onerror=function(){r.onError(t.responseText)}):t.onreadystatechange=function(){if(2===t.readyState)try{var e=t.getResponseHeader("Content-Type");r.supportsBinary&&"application/octet-stream"===e&&(t.responseType="arraybuffer")}catch(e){}4===t.readyState&&(200===t.status||1223===t.status?r.onLoad():setTimeout((function(){r.onError(t.status)}),0))},gi("xhr data %s",this.data),t.send(this.data)}catch(e){return void setTimeout((function(){r.onError(e)}),0)}"undefined"!=typeof document&&(this.index=vi.requestsCount++,vi.requests[this.index]=this)},vi.prototype.onSuccess=function(){this.emit("success"),this.cleanup()},vi.prototype.onData=function(e){this.emit("data",e),this.onSuccess()},vi.prototype.onError=function(e){this.emit("error",e),this.cleanup(!0)},vi.prototype.cleanup=function(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.hasXDR()?this.xhr.onload=this.xhr.onerror=mi:this.xhr.onreadystatechange=mi,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete vi.requests[this.index],this.xhr=null}},vi.prototype.onLoad=function(){var e;try{var t;try{t=this.xhr.getResponseHeader("Content-Type")}catch(e){}e="application/octet-stream"===t&&this.xhr.response||this.xhr.responseText}catch(e){this.onError(e)}null!=e&&this.onData(e)},vi.prototype.hasXDR=function(){return"undefined"!=typeof XDomainRequest&&!this.xs&&this.enablesXDR},vi.prototype.abort=function(){this.cleanup()},vi.requestsCount=0,vi.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",wi);else if("function"==typeof addEventListener){var bi="onpagehide"in self?"pagehide":"unload";addEventListener(bi,wi,!1)}function wi(){for(var e in vi.requests)vi.requests.hasOwnProperty(e)&&vi.requests[e].abort()}var Ei,Si=li,Ti=_i,Ci=/\n/g,ki=/\\n/g;function Ai(){}function Ii(){return"undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==ft?ft:{}}function _i(e){if(Si.call(this,e),this.query=this.query||{},!Ei){var t=Ii();Ei=t.___eio=t.___eio||[]}this.index=Ei.length;var r=this;Ei.push((function(e){r.onData(e)})),this.query.j=this.index,"function"==typeof addEventListener&&addEventListener("beforeunload",(function(){r.script&&(r.script.onerror=Ai)}),!1)}Bs(_i,Si),_i.prototype.supportsBinary=!1,_i.prototype.doClose=function(){this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),this.form&&(this.form.parentNode.removeChild(this.form),this.form=null,this.iframe=null),Si.prototype.doClose.call(this)},_i.prototype.doPoll=function(){var e=this,t=document.createElement("script");this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),t.async=!0,t.src=this.uri(),t.onerror=function(t){e.onError("jsonp poll error",t)};var r=document.getElementsByTagName("script")[0];r?r.parentNode.insertBefore(t,r):(document.head||document.body).appendChild(t),this.script=t,"undefined"!=typeof navigator&&/gecko/i.test(navigator.userAgent)&&setTimeout((function(){var e=document.createElement("iframe");document.body.appendChild(e),document.body.removeChild(e)}),100)},_i.prototype.doWrite=function(e,t){var r=this;if(!this.form){var n,s=document.createElement("form"),i=document.createElement("textarea"),a=this.iframeId="eio_iframe_"+this.index;s.className="socketio",s.style.position="absolute",s.style.top="-1000px",s.style.left="-1000px",s.target=a,s.method="POST",s.setAttribute("accept-charset","utf-8"),i.name="d",s.appendChild(i),document.body.appendChild(s),this.form=s,this.area=i}function o(){l(),t()}function l(){if(r.iframe)try{r.form.removeChild(r.iframe)}catch(e){r.onError("jsonp polling iframe removal error",e)}try{var e='<iframe src="javascript:0" name="'+r.iframeId+'">';n=document.createElement(e)}catch(e){(n=document.createElement("iframe")).name=r.iframeId,n.src="javascript:0"}n.id=r.iframeId,r.form.appendChild(n),r.iframe=n}this.form.action=this.uri(),l(),e=e.replace(ki,"\\\n"),this.area.value=e.replace(Ci,"\\n");try{this.form.submit()}catch(e){}this.iframe.attachEvent?this.iframe.onreadystatechange=function(){"complete"===r.iframe.readyState&&o()}:this.iframe.onload=o};var Ri,Li,Di=gt(Object.freeze({__proto__:null,default:{}})),xi=Ps(),Oi=cs,Pi=Us(),Mi=Bs,Fi=Vs,Ui=zs.exports("engine.io-client:websocket");if("undefined"!=typeof WebSocket)Ri=WebSocket;else if("undefined"!=typeof self)Ri=self.WebSocket||self.MozWebSocket;else try{Li=Di}catch(e){}var Ni=Ri||Li,Bi=ji;function ji(e){e&&e.forceBase64&&(this.supportsBinary=!1),this.perMessageDeflate=e.perMessageDeflate,this.usingBrowserWebSocket=Ri&&!e.forceNode,this.protocols=e.protocols,this.usingBrowserWebSocket||(Ni=Li),xi.call(this,e)}Mi(ji,xi),ji.prototype.name="websocket",ji.prototype.supportsBinary=!0,ji.prototype.doOpen=function(){if(this.check()){var e=this.uri(),t=this.protocols,r={agent:this.agent,perMessageDeflate:this.perMessageDeflate};r.pfx=this.pfx,r.key=this.key,r.passphrase=this.passphrase,r.cert=this.cert,r.ca=this.ca,r.ciphers=this.ciphers,r.rejectUnauthorized=this.rejectUnauthorized,this.extraHeaders&&(r.headers=this.extraHeaders),this.localAddress&&(r.localAddress=this.localAddress);try{this.ws=this.usingBrowserWebSocket&&!this.isReactNative?t?new Ni(e,t):new Ni(e):new Ni(e,t,r)}catch(e){return this.emit("error",e)}void 0===this.ws.binaryType&&(this.supportsBinary=!1),this.ws.supports&&this.ws.supports.binary?(this.supportsBinary=!0,this.ws.binaryType="nodebuffer"):this.ws.binaryType="arraybuffer",this.addEventListeners()}},ji.prototype.addEventListeners=function(){var e=this;this.ws.onopen=function(){e.onOpen()},this.ws.onclose=function(){e.onClose()},this.ws.onmessage=function(t){e.onData(t.data)},this.ws.onerror=function(t){e.onError("websocket error",t)}},ji.prototype.write=function(e){var t=this;this.writable=!1;for(var r=e.length,n=0,s=r;n<s;n++)!function(e){Oi.encodePacket(e,t.supportsBinary,(function(n){if(!t.usingBrowserWebSocket){var s={};if(e.options&&(s.compress=e.options.compress),t.perMessageDeflate)("string"==typeof n?Buffer.byteLength(n):n.length)<t.perMessageDeflate.threshold&&(s.compress=!1)}try{t.usingBrowserWebSocket?t.ws.send(n):t.ws.send(n,s)}catch(e){Ui("websocket closed before onclose event")}--r||i()}))}(e[n]);function i(){t.emit("flush"),setTimeout((function(){t.writable=!0,t.emit("drain")}),0)}},ji.prototype.onClose=function(){xi.prototype.onClose.call(this)},ji.prototype.doClose=function(){void 0!==this.ws&&this.ws.close()},ji.prototype.uri=function(){var e=this.query||{},t=this.secure?"wss":"ws",r="";return this.port&&("wss"===t&&443!==Number(this.port)||"ws"===t&&80!==Number(this.port))&&(r=":"+this.port),this.timestampRequests&&(e[this.timestampParam]=Fi()),this.supportsBinary||(e.b64=1),(e=Pi.encode(e)).length&&(e="?"+e),t+"://"+(-1!==this.hostname.indexOf(":")?"["+this.hostname+"]":this.hostname)+r+this.path+e},ji.prototype.check=function(){return!(!Ni||"__initialize"in Ni&&this.name===ji.prototype.name)};var $i=os,qi=ls.exports,Ki=Ti,Gi=Bi;es.polling=function(e){var t=!1,r=!1,n=!1!==e.jsonp;if("undefined"!=typeof location){var s="https:"===location.protocol,i=location.port;i||(i=s?443:80),t=e.hostname!==location.hostname||i!==e.port,r=e.secure!==s}if(e.xdomain=t,e.xscheme=r,"open"in new $i(e)&&!e.forceJSONP)return new qi(e);if(!n)throw new Error("JSONP disabled");return new Ki(e)},es.websocket=Gi;var Hi,Vi=[].indexOf,zi=function(e,t){if(Vi)return e.indexOf(t);for(var r=0;r<e.length;++r)if(e[r]===t)return r;return-1},Wi=es,Yi=Os.exports,Qi=zs.exports("engine.io-client:socket"),Xi=zi,Ji=cs,Zi=mn,ea=Us(),ta=ra;function ra(e,t){if(!(this instanceof ra))return new ra(e,t);t=t||{},e&&"object"==typeof e&&(t=e,e=null),e?(e=Zi(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=Zi(t.host).host),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.agent=t.agent||!1,this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?443:80),this.query=t.query||{},"string"==typeof this.query&&(this.query=ea.decode(this.query)),this.upgrade=!1!==t.upgrade,this.path=(t.path||"/engine.io").replace(/\/$/,"")+"/",this.forceJSONP=!!t.forceJSONP,this.jsonp=!1!==t.jsonp,this.forceBase64=!!t.forceBase64,this.enablesXDR=!!t.enablesXDR,this.timestampParam=t.timestampParam||"t",this.timestampRequests=t.timestampRequests,this.transports=t.transports||["polling","websocket"],this.transportOptions=t.transportOptions||{},this.readyState="",this.writeBuffer=[],this.prevBufferLen=0,this.policyPort=t.policyPort||843,this.rememberUpgrade=t.rememberUpgrade||!1,this.binaryType=null,this.onlyBinaryUpgrades=t.onlyBinaryUpgrades,this.perMessageDeflate=!1!==t.perMessageDeflate&&(t.perMessageDeflate||{}),!0===this.perMessageDeflate&&(this.perMessageDeflate={}),this.perMessageDeflate&&null==this.perMessageDeflate.threshold&&(this.perMessageDeflate.threshold=1024),this.pfx=t.pfx||null,this.key=t.key||null,this.passphrase=t.passphrase||null,this.cert=t.cert||null,this.ca=t.ca||null,this.ciphers=t.ciphers||null,this.rejectUnauthorized=void 0===t.rejectUnauthorized||t.rejectUnauthorized,this.forceNode=!!t.forceNode,this.isReactNative="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),("undefined"==typeof self||this.isReactNative)&&(t.extraHeaders&&Object.keys(t.extraHeaders).length>0&&(this.extraHeaders=t.extraHeaders),t.localAddress&&(this.localAddress=t.localAddress)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingIntervalTimer=null,this.pingTimeoutTimer=null,this.open()}ra.priorWebsocketSuccess=!1,Yi(ra.prototype),ra.protocol=Ji.protocol,ra.Socket=ra,ra.Transport=Ps(),ra.transports=es,ra.parser=cs,ra.prototype.createTransport=function(e){Qi('creating transport "%s"',e);var t=function(e){var t={};for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);return t}(this.query);t.EIO=Ji.protocol,t.transport=e;var r=this.transportOptions[e]||{};return this.id&&(t.sid=this.id),new Wi[e]({query:t,socket:this,agent:r.agent||this.agent,hostname:r.hostname||this.hostname,port:r.port||this.port,secure:r.secure||this.secure,path:r.path||this.path,forceJSONP:r.forceJSONP||this.forceJSONP,jsonp:r.jsonp||this.jsonp,forceBase64:r.forceBase64||this.forceBase64,enablesXDR:r.enablesXDR||this.enablesXDR,timestampRequests:r.timestampRequests||this.timestampRequests,timestampParam:r.timestampParam||this.timestampParam,policyPort:r.policyPort||this.policyPort,pfx:r.pfx||this.pfx,key:r.key||this.key,passphrase:r.passphrase||this.passphrase,cert:r.cert||this.cert,ca:r.ca||this.ca,ciphers:r.ciphers||this.ciphers,rejectUnauthorized:r.rejectUnauthorized||this.rejectUnauthorized,perMessageDeflate:r.perMessageDeflate||this.perMessageDeflate,extraHeaders:r.extraHeaders||this.extraHeaders,forceNode:r.forceNode||this.forceNode,localAddress:r.localAddress||this.localAddress,requestTimeout:r.requestTimeout||this.requestTimeout,protocols:r.protocols||void 0,isReactNative:this.isReactNative})},ra.prototype.open=function(){var e;if(this.rememberUpgrade&&ra.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))e="websocket";else{if(0===this.transports.length){var t=this;return void setTimeout((function(){t.emit("error","No transports available")}),0)}e=this.transports[0]}this.readyState="opening";try{e=this.createTransport(e)}catch(e){return this.transports.shift(),void this.open()}e.open(),this.setTransport(e)},ra.prototype.setTransport=function(e){Qi("setting transport %s",e.name);var t=this;this.transport&&(Qi("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=e,e.on("drain",(function(){t.onDrain()})).on("packet",(function(e){t.onPacket(e)})).on("error",(function(e){t.onError(e)})).on("close",(function(){t.onClose("transport close")}))},ra.prototype.probe=function(e){Qi('probing transport "%s"',e);var t=this.createTransport(e,{probe:1}),r=!1,n=this;function s(){if(n.onlyBinaryUpgrades){var s=!this.supportsBinary&&n.transport.supportsBinary;r=r||s}r||(Qi('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",(function(s){if(!r)if("pong"===s.type&&"probe"===s.data){if(Qi('probe transport "%s" pong',e),n.upgrading=!0,n.emit("upgrading",t),!t)return;ra.priorWebsocketSuccess="websocket"===t.name,Qi('pausing current transport "%s"',n.transport.name),n.transport.pause((function(){r||"closed"!==n.readyState&&(Qi("changing transport and sending upgrade packet"),d(),n.setTransport(t),t.send([{type:"upgrade"}]),n.emit("upgrade",t),t=null,n.upgrading=!1,n.flush())}))}else{Qi('probe transport "%s" failed',e);var i=new Error("probe error");i.transport=t.name,n.emit("upgradeError",i)}})))}function i(){r||(r=!0,d(),t.close(),t=null)}function a(r){var s=new Error("probe error: "+r);s.transport=t.name,i(),Qi('probe transport "%s" failed because of error: %s',e,r),n.emit("upgradeError",s)}function o(){a("transport closed")}function l(){a("socket closed")}function c(e){t&&e.name!==t.name&&(Qi('"%s" works - aborting "%s"',e.name,t.name),i())}function d(){t.removeListener("open",s),t.removeListener("error",a),t.removeListener("close",o),n.removeListener("close",l),n.removeListener("upgrading",c)}ra.priorWebsocketSuccess=!1,t.once("open",s),t.once("error",a),t.once("close",o),this.once("close",l),this.once("upgrading",c),t.open()},ra.prototype.onOpen=function(){if(Qi("socket open"),this.readyState="open",ra.priorWebsocketSuccess="websocket"===this.transport.name,this.emit("open"),this.flush(),"open"===this.readyState&&this.upgrade&&this.transport.pause){Qi("starting upgrade probes");for(var e=0,t=this.upgrades.length;e<t;e++)this.probe(this.upgrades[e])}},ra.prototype.onPacket=function(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(Qi('socket receive: type "%s", data "%s"',e.type,e.data),this.emit("packet",e),this.emit("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"pong":this.setPing(),this.emit("pong");break;case"error":var t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emit("data",e.data),this.emit("message",e.data)}else Qi('packet received with socket readyState "%s"',this.readyState)},ra.prototype.onHandshake=function(e){this.emit("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.onOpen(),"closed"!==this.readyState&&(this.setPing(),this.removeListener("heartbeat",this.onHeartbeat),this.on("heartbeat",this.onHeartbeat))},ra.prototype.onHeartbeat=function(e){clearTimeout(this.pingTimeoutTimer);var t=this;t.pingTimeoutTimer=setTimeout((function(){"closed"!==t.readyState&&t.onClose("ping timeout")}),e||t.pingInterval+t.pingTimeout)},ra.prototype.setPing=function(){var e=this;clearTimeout(e.pingIntervalTimer),e.pingIntervalTimer=setTimeout((function(){Qi("writing ping packet - expecting pong within %sms",e.pingTimeout),e.ping(),e.onHeartbeat(e.pingTimeout)}),e.pingInterval)},ra.prototype.ping=function(){var e=this;this.sendPacket("ping",(function(){e.emit("ping")}))},ra.prototype.onDrain=function(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emit("drain"):this.flush()},ra.prototype.flush=function(){"closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length&&(Qi("flushing %d packets in socket",this.writeBuffer.length),this.transport.send(this.writeBuffer),this.prevBufferLen=this.writeBuffer.length,this.emit("flush"))},ra.prototype.write=ra.prototype.send=function(e,t,r){return this.sendPacket("message",e,t,r),this},ra.prototype.sendPacket=function(e,t,r,n){if("function"==typeof t&&(n=t,t=void 0),"function"==typeof r&&(n=r,r=null),"closing"!==this.readyState&&"closed"!==this.readyState){(r=r||{}).compress=!1!==r.compress;var s={type:e,data:t,options:r};this.emit("packetCreate",s),this.writeBuffer.push(s),n&&this.once("flush",n),this.flush()}},ra.prototype.close=function(){if("opening"===this.readyState||"open"===this.readyState){this.readyState="closing";var e=this;this.writeBuffer.length?this.once("drain",(function(){this.upgrading?n():t()})):this.upgrading?n():t()}function t(){e.onClose("forced close"),Qi("socket closing - telling transport to close"),e.transport.close()}function r(){e.removeListener("upgrade",r),e.removeListener("upgradeError",r),t()}function n(){e.once("upgrade",r),e.once("upgradeError",r)}return this},ra.prototype.onError=function(e){Qi("socket error %j",e),ra.priorWebsocketSuccess=!1,this.emit("error",e),this.onClose("transport error",e)},ra.prototype.onClose=function(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){Qi('socket close with reason: "%s"',e);clearTimeout(this.pingIntervalTimer),clearTimeout(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),this.readyState="closed",this.id=null,this.emit("close",e,t),this.writeBuffer=[],this.prevBufferLen=0}},ra.prototype.filterUpgrades=function(e){for(var t=[],r=0,n=e.length;r<n;r++)~Xi(this.transports,e[r])&&t.push(e[r]);return t},(Hi=Zn).exports=ta,Hi.exports.parser=cs;var na,sa,ia={exports:{}},aa={exports:{}};!function(e){function t(e){if(e)return function(e){for(var r in t.prototype)e[r]=t.prototype[r];return e}(e)}e.exports=t,t.prototype.on=t.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},t.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},t.prototype.off=t.prototype.removeListener=t.prototype.removeAllListeners=t.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,n=this._callbacks["$"+e];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var s=0;s<n.length;s++)if((r=n[s])===t||r.fn===t){n.splice(s,1);break}return this},t.prototype.emit=function(e){this._callbacks=this._callbacks||{};var t=[].slice.call(arguments,1),r=this._callbacks["$"+e];if(r)for(var n=0,s=(r=r.slice(0)).length;n<s;++n)r[n].apply(this,t);return this},t.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},t.prototype.hasListeners=function(e){return!!this.listeners(e).length}}(aa);var oa=function(e,t,r){return e.on(t,r),{destroy:function(){e.removeListener(t,r)}}};var la,ca=[].slice,da=function(e,t){if("string"==typeof t&&(t=e[t]),"function"!=typeof t)throw new Error("bind() requires a function");var r=ca.call(arguments,2);return function(){return t.apply(e,r.concat(ca.call(arguments)))}};function ua(){return la||(la=1,function(e,t){var r=Rn,n=aa.exports,s=(sa||(sa=1,na=function(e,t){for(var r=[],n=(t=t||0)||0;n<e.length;n++)r[n-t]=e[n];return r}),na),i=oa,a=da,o=yn.exports("socket.io-client:socket"),l=Us(),c=us();e.exports=h;var d={connect:1,connect_error:1,connect_timeout:1,connecting:1,disconnect:1,error:1,reconnect:1,reconnect_attempt:1,reconnect_failed:1,reconnect_error:1,reconnecting:1,ping:1,pong:1},u=n.prototype.emit;function h(e,t,r){this.io=e,this.nsp=t,this.json=this,this.ids=0,this.acks={},this.receiveBuffer=[],this.sendBuffer=[],this.connected=!1,this.disconnected=!0,this.flags={},r&&r.query&&(this.query=r.query),this.io.autoConnect&&this.open()}n(h.prototype),h.prototype.subEvents=function(){if(!this.subs){var e=this.io;this.subs=[i(e,"open",a(this,"onopen")),i(e,"packet",a(this,"onpacket")),i(e,"close",a(this,"onclose"))]}},h.prototype.open=h.prototype.connect=function(){return this.connected||(this.subEvents(),this.io.open(),"open"===this.io.readyState&&this.onopen(),this.emit("connecting")),this},h.prototype.send=function(){var e=s(arguments);return e.unshift("message"),this.emit.apply(this,e),this},h.prototype.emit=function(e){if(d.hasOwnProperty(e))return u.apply(this,arguments),this;var t=s(arguments),n={type:(void 0!==this.flags.binary?this.flags.binary:c(t))?r.BINARY_EVENT:r.EVENT,data:t,options:{}};return n.options.compress=!this.flags||!1!==this.flags.compress,"function"==typeof t[t.length-1]&&(o("emitting packet with ack id %d",this.ids),this.acks[this.ids]=t.pop(),n.id=this.ids++),this.connected?this.packet(n):this.sendBuffer.push(n),this.flags={},this},h.prototype.packet=function(e){e.nsp=this.nsp,this.io.packet(e)},h.prototype.onopen=function(){if(o("transport is open - connecting"),"/"!==this.nsp)if(this.query){var e="object"==typeof this.query?l.encode(this.query):this.query;o("sending connect packet with query %s",e),this.packet({type:r.CONNECT,query:e})}else this.packet({type:r.CONNECT})},h.prototype.onclose=function(e){o("close (%s)",e),this.connected=!1,this.disconnected=!0,delete this.id,this.emit("disconnect",e)},h.prototype.onpacket=function(e){var t=e.nsp===this.nsp,n=e.type===r.ERROR&&"/"===e.nsp;if(t||n)switch(e.type){case r.CONNECT:this.onconnect();break;case r.EVENT:case r.BINARY_EVENT:this.onevent(e);break;case r.ACK:case r.BINARY_ACK:this.onack(e);break;case r.DISCONNECT:this.ondisconnect();break;case r.ERROR:this.emit("error",e.data)}},h.prototype.onevent=function(e){var t=e.data||[];o("emitting event %j",t),null!=e.id&&(o("attaching ack callback to event"),t.push(this.ack(e.id))),this.connected?u.apply(this,t):this.receiveBuffer.push(t)},h.prototype.ack=function(e){var t=this,n=!1;return function(){if(!n){n=!0;var i=s(arguments);o("sending ack %j",i),t.packet({type:c(i)?r.BINARY_ACK:r.ACK,id:e,data:i})}}},h.prototype.onack=function(e){var t=this.acks[e.id];"function"==typeof t?(o("calling ack %s with %j",e.id,e.data),t.apply(this,e.data),delete this.acks[e.id]):o("bad ack %s",e.id)},h.prototype.onconnect=function(){this.connected=!0,this.disconnected=!1,this.emit("connect"),this.emitBuffered()},h.prototype.emitBuffered=function(){var e;for(e=0;e<this.receiveBuffer.length;e++)u.apply(this,this.receiveBuffer[e]);for(this.receiveBuffer=[],e=0;e<this.sendBuffer.length;e++)this.packet(this.sendBuffer[e]);this.sendBuffer=[]},h.prototype.ondisconnect=function(){o("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")},h.prototype.destroy=function(){if(this.subs){for(var e=0;e<this.subs.length;e++)this.subs[e].destroy();this.subs=null}this.io.destroy(this)},h.prototype.close=h.prototype.disconnect=function(){return this.connected&&(o("performing disconnect (%s)",this.nsp),this.packet({type:r.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this},h.prototype.compress=function(e){return this.flags.compress=e,this},h.prototype.binary=function(e){return this.flags.binary=e,this}}(ia)),ia.exports}var ha=fa;function fa(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}fa.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=0==(1&Math.floor(10*t))?e-r:e+r}return 0|Math.min(e,this.max)},fa.prototype.reset=function(){this.attempts=0},fa.prototype.setMin=function(e){this.ms=e},fa.prototype.setMax=function(e){this.max=e},fa.prototype.setJitter=function(e){this.jitter=e};var pa=Zn.exports,ga=ua(),ma=aa.exports,ya=Rn,va=oa,ba=da,wa=yn.exports("socket.io-client:manager"),Ea=zi,Sa=ha,Ta=Object.prototype.hasOwnProperty,Ca=ka;function ka(e,t){if(!(this instanceof ka))return new ka(e,t);e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.nsps={},this.subs=[],this.opts=t,this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(t.randomizationFactor||.5),this.backoff=new Sa({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this.readyState="closed",this.uri=e,this.connecting=[],this.lastPing=null,this.encoding=!1,this.packetBuffer=[];var r=t.parser||ya;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this.autoConnect=!1!==t.autoConnect,this.autoConnect&&this.open()}ka.prototype.emitAll=function(){for(var e in this.emit.apply(this,arguments),this.nsps)Ta.call(this.nsps,e)&&this.nsps[e].emit.apply(this.nsps[e],arguments)},ka.prototype.updateSocketIds=function(){for(var e in this.nsps)Ta.call(this.nsps,e)&&(this.nsps[e].id=this.generateId(e))},ka.prototype.generateId=function(e){return("/"===e?"":e+"#")+this.engine.id},ma(ka.prototype),ka.prototype.reconnection=function(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection},ka.prototype.reconnectionAttempts=function(e){return arguments.length?(this._reconnectionAttempts=e,this):this._reconnectionAttempts},ka.prototype.reconnectionDelay=function(e){return arguments.length?(this._reconnectionDelay=e,this.backoff&&this.backoff.setMin(e),this):this._reconnectionDelay},ka.prototype.randomizationFactor=function(e){return arguments.length?(this._randomizationFactor=e,this.backoff&&this.backoff.setJitter(e),this):this._randomizationFactor},ka.prototype.reconnectionDelayMax=function(e){return arguments.length?(this._reconnectionDelayMax=e,this.backoff&&this.backoff.setMax(e),this):this._reconnectionDelayMax},ka.prototype.timeout=function(e){return arguments.length?(this._timeout=e,this):this._timeout},ka.prototype.maybeReconnectOnOpen=function(){!this.reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()},ka.prototype.open=ka.prototype.connect=function(e,t){if(wa("readyState %s",this.readyState),~this.readyState.indexOf("open"))return this;wa("opening %s",this.uri),this.engine=pa(this.uri,this.opts);var r=this.engine,n=this;this.readyState="opening",this.skipReconnect=!1;var s=va(r,"open",(function(){n.onopen(),e&&e()})),i=va(r,"error",(function(t){if(wa("connect_error"),n.cleanup(),n.readyState="closed",n.emitAll("connect_error",t),e){var r=new Error("Connection error");r.data=t,e(r)}else n.maybeReconnectOnOpen()}));if(!1!==this._timeout){var a=this._timeout;wa("connect attempt will timeout after %d",a);var o=setTimeout((function(){wa("connect attempt timed out after %d",a),s.destroy(),r.close(),r.emit("error","timeout"),n.emitAll("connect_timeout",a)}),a);this.subs.push({destroy:function(){clearTimeout(o)}})}return this.subs.push(s),this.subs.push(i),this},ka.prototype.onopen=function(){wa("open"),this.cleanup(),this.readyState="open",this.emit("open");var e=this.engine;this.subs.push(va(e,"data",ba(this,"ondata"))),this.subs.push(va(e,"ping",ba(this,"onping"))),this.subs.push(va(e,"pong",ba(this,"onpong"))),this.subs.push(va(e,"error",ba(this,"onerror"))),this.subs.push(va(e,"close",ba(this,"onclose"))),this.subs.push(va(this.decoder,"decoded",ba(this,"ondecoded")))},ka.prototype.onping=function(){this.lastPing=new Date,this.emitAll("ping")},ka.prototype.onpong=function(){this.emitAll("pong",new Date-this.lastPing)},ka.prototype.ondata=function(e){this.decoder.add(e)},ka.prototype.ondecoded=function(e){this.emit("packet",e)},ka.prototype.onerror=function(e){wa("error",e),this.emitAll("error",e)},ka.prototype.socket=function(e,t){var r=this.nsps[e];if(!r){r=new ga(this,e,t),this.nsps[e]=r;var n=this;r.on("connecting",s),r.on("connect",(function(){r.id=n.generateId(e)})),this.autoConnect&&s()}function s(){~Ea(n.connecting,r)||n.connecting.push(r)}return r},ka.prototype.destroy=function(e){var t=Ea(this.connecting,e);~t&&this.connecting.splice(t,1),this.connecting.length||this.close()},ka.prototype.packet=function(e){wa("writing packet %j",e);var t=this;e.query&&0===e.type&&(e.nsp+="?"+e.query),t.encoding?t.packetBuffer.push(e):(t.encoding=!0,this.encoder.encode(e,(function(r){for(var n=0;n<r.length;n++)t.engine.write(r[n],e.options);t.encoding=!1,t.processPacketQueue()})))},ka.prototype.processPacketQueue=function(){if(this.packetBuffer.length>0&&!this.encoding){var e=this.packetBuffer.shift();this.packet(e)}},ka.prototype.cleanup=function(){wa("cleanup");for(var e=this.subs.length,t=0;t<e;t++){this.subs.shift().destroy()}this.packetBuffer=[],this.encoding=!1,this.lastPing=null,this.decoder.destroy()},ka.prototype.close=ka.prototype.disconnect=function(){wa("disconnect"),this.skipReconnect=!0,this.reconnecting=!1,"opening"===this.readyState&&this.cleanup(),this.backoff.reset(),this.readyState="closed",this.engine&&this.engine.close()},ka.prototype.onclose=function(e){wa("onclose"),this.cleanup(),this.backoff.reset(),this.readyState="closed",this.emit("close",e),this._reconnection&&!this.skipReconnect&&this.reconnect()},ka.prototype.reconnect=function(){if(this.reconnecting||this.skipReconnect)return this;var e=this;if(this.backoff.attempts>=this._reconnectionAttempts)wa("reconnect failed"),this.backoff.reset(),this.emitAll("reconnect_failed"),this.reconnecting=!1;else{var t=this.backoff.duration();wa("will wait %dms before reconnect attempt",t),this.reconnecting=!0;var r=setTimeout((function(){e.skipReconnect||(wa("attempting reconnect"),e.emitAll("reconnect_attempt",e.backoff.attempts),e.emitAll("reconnecting",e.backoff.attempts),e.skipReconnect||e.open((function(t){t?(wa("reconnect attempt error"),e.reconnecting=!1,e.reconnect(),e.emitAll("reconnect_error",t.data)):(wa("reconnect success"),e.onreconnect())})))}),t);this.subs.push({destroy:function(){clearTimeout(r)}})}},ka.prototype.onreconnect=function(){var e=this.backoff.attempts;this.reconnecting=!1,this.backoff.reset(),this.updateSocketIds(),this.emitAll("reconnect",e)},function(e,t){var r=_n,n=Rn,s=Ca,i=yn.exports("socket.io-client");e.exports=t=o;var a=t.managers={};function o(e,t){"object"==typeof e&&(t=e,e=void 0),t=t||{};var n,o=r(e),l=o.source,c=o.id,d=o.path,u=a[c]&&d in a[c].nsps;return t.forceNew||t["force new connection"]||!1===t.multiplex||u?(i("ignoring socket cache for %s",l),n=s(l,t)):(a[c]||(i("new io instance for %s",l),a[c]=s(l,t)),n=a[c]),o.query&&!t.query&&(t.query=o.query),n.socket(o.path,t)}t.protocol=n.protocol,t.connect=o,t.Manager=Ca,t.Socket=ua()}(fn,fn.exports);var Aa=fn.exports;function Ia(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var _a={exports:{}};!function(e,t){e.exports=function(){function e(t,r,n){function s(a,o){if(!r[a]){if(!t[a]){if(!o&&Ia)return Ia(a);if(i)return i(a,!0);var l=new Error("Cannot find module '"+a+"'");throw l.code="MODULE_NOT_FOUND",l}var c=r[a]={exports:{}};t[a][0].call(c.exports,(function(e){return s(t[a][1][e]||e)}),c,c.exports,e,t,r,n)}return r[a].exports}for(var i=Ia,a=0;a<n.length;a++)s(n[a]);return s}return e}()({1:[function(e,t,r){(function(r,n){(function(){const s=e("events").EventEmitter,i=e("./store"),a=e("./topic-alias-recv"),o=e("./topic-alias-send"),l=e("mqtt-packet"),c=e("./default-message-id-provider"),d=e("readable-stream").Writable,u=e("inherits"),h=e("reinterval"),f=e("rfdc/default"),p=e("./validations"),g=e("xtend"),m=e("debug")("mqttjs:client"),y=r?r.nextTick:function(e){setTimeout(e,0)},v=n.setImmediate||function(e){y(e)},b={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1e3,connectTimeout:3e4,clean:!0,resubscribe:!0},w=["ECONNREFUSED","EADDRINUSE","ECONNRESET","ENOTFOUND"],E={0:"",1:"Unacceptable protocol version",2:"Identifier rejected",3:"Server unavailable",4:"Bad username or password",5:"Not authorized",16:"No matching subscribers",17:"No subscription existed",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",132:"Unsupported Protocol Version",133:"Client Identifier not valid",134:"Bad User Name or Password",135:"Not authorized",136:"Server unavailable",137:"Server busy",138:"Banned",139:"Server shutting down",140:"Bad authentication method",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",145:"Packet identifier in use",146:"Packet Identifier not found",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};function S(){return"mqttjs_"+Math.random().toString(16).substr(2,8)}function T(e,t){if(5===e.options.protocolVersion&&"publish"===t.cmd){let r;t.properties&&(r=t.properties.topicAlias);const n=t.topic.toString();if(e.topicAliasSend)if(r){if(0!==n.length&&(m("applyTopicAlias :: register topic: %s - alias: %d",n,r),!e.topicAliasSend.put(n,r)))return m("applyTopicAlias :: error out of range. topic: %s - alias: %d",n,r),new Error("Sending Topic Alias out of range")}else 0!==n.length&&(e.options.autoAssignTopicAlias?(r=e.topicAliasSend.getAliasByTopic(n),r?(t.topic="",t.properties={...t.properties,topicAlias:r},m("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",n,r)):(r=e.topicAliasSend.getLruAlias(),e.topicAliasSend.put(n,r),t.properties={...t.properties,topicAlias:r},m("applyTopicAlias :: auto assign topic: %s - alias: %d",n,r))):e.options.autoUseTopicAlias&&(r=e.topicAliasSend.getAliasByTopic(n),r&&(t.topic="",t.properties={...t.properties,topicAlias:r},m("applyTopicAlias :: auto use topic: %s - alias: %d",n,r))));else if(r)return m("applyTopicAlias :: error out of range. topic: %s - alias: %d",n,r),new Error("Sending Topic Alias out of range")}}function C(e,t){let r;t.properties&&(r=t.properties.topicAlias);let n=t.topic.toString();if(0===n.length){if(void 0===r)return new Error("Unregistered Topic Alias");if(n=e.topicAliasSend.getTopicByAlias(r),void 0===n)return new Error("Unregistered Topic Alias");t.topic=n}r&&delete t.properties.topicAlias}function k(e,t,r){m("sendPacket :: packet: %O",t),m("sendPacket :: emitting `packetsend`"),e.emit("packetsend",t),m("sendPacket :: writing to stream");const n=l.writeToStream(t,e.stream,e.options);m("sendPacket :: writeToStream result %s",n),!n&&r&&r!==R?(m("sendPacket :: handle events on `drain` once through callback."),e.stream.once("drain",r)):r&&(m("sendPacket :: invoking cb"),r())}function A(e){e&&(m("flush: queue exists? %b",!!e),Object.keys(e).forEach((function(t){"function"==typeof e[t].cb&&(e[t].cb(new Error("Connection closed")),delete e[t])})))}function I(e){e&&(m("flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(e).forEach((function(t){e[t].volatile&&"function"==typeof e[t].cb&&(e[t].cb(new Error("Connection closed")),delete e[t])})))}function _(e,t,r,n){m("storeAndSend :: store packet with cmd %s to outgoingStore",t.cmd);let s,i=t;if("publish"===i.cmd&&(i=f(t),s=C(e,i),s))return r&&r(s);e.outgoingStore.put(i,(function(s){if(s)return r&&r(s);n(),k(e,t,r)}))}function R(e){m("nop ::",e)}function L(e,t){let r;const n=this;if(!(this instanceof L))return new L(e,t);for(r in this.options=t||{},b)void 0===this.options[r]?this.options[r]=b[r]:this.options[r]=t[r];m("MqttClient :: options.protocol",t.protocol),m("MqttClient :: options.protocolVersion",t.protocolVersion),m("MqttClient :: options.username",t.username),m("MqttClient :: options.keepalive",t.keepalive),m("MqttClient :: options.reconnectPeriod",t.reconnectPeriod),m("MqttClient :: options.rejectUnauthorized",t.rejectUnauthorized),m("MqttClient :: options.topicAliasMaximum",t.topicAliasMaximum),this.options.clientId="string"==typeof t.clientId?t.clientId:S(),m("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=5===t.protocolVersion&&t.customHandleAcks?t.customHandleAcks:function(){arguments[3](0)},this.streamBuilder=e,this.messageIdProvider=void 0===this.options.messageIdProvider?new c:this.options.messageIdProvider,this.outgoingStore=t.outgoingStore||new i,this.incomingStore=t.incomingStore||new i,this.queueQoSZero=void 0===t.queueQoSZero||t.queueQoSZero,this._resubscribeTopics={},this.messageIdToTopic={},this.pingTimer=null,this.connected=!1,this.disconnecting=!1,this.queue=[],this.connackTimer=null,this.reconnectTimer=null,this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={},this._storeProcessingQueue=[],this.outgoing={},this._firstConnection=!0,t.topicAliasMaximum>0&&(t.topicAliasMaximum>65535?m("MqttClient :: options.topicAliasMaximum is out of range"):this.topicAliasRecv=new a(t.topicAliasMaximum)),this.on("connect",(function(){const e=this.queue;function t(){const r=e.shift();m("deliver :: entry %o",r);let s=null;if(!r)return void n._resubscribe();s=r.packet,m("deliver :: call _sendPacket for %o",s);let i=!0;s.messageId&&0!==s.messageId&&(n.messageIdProvider.register(s.messageId)||(i=!1)),i?n._sendPacket(s,(function(e){r.cb&&r.cb(e),t()})):(m("messageId: %d has already used. The message is skipped and removed.",s.messageId),t())}m("connect :: sending queued packets"),t()})),this.on("close",(function(){m("close :: connected set to `false`"),this.connected=!1,m("close :: clearing connackTimer"),clearTimeout(this.connackTimer),m("close :: clearing ping timer"),null!==n.pingTimer&&(n.pingTimer.clear(),n.pingTimer=null),this.topicAliasRecv&&this.topicAliasRecv.clear(),m("close :: calling _setupReconnect"),this._setupReconnect()})),s.call(this),m("MqttClient :: setting up stream"),this._setupStream()}u(L,s),L.prototype._setupStream=function(){const e=this,t=new d,r=l.parser(this.options);let n=null;const s=[];function i(){if(s.length)y(a);else{const e=n;n=null,e()}}function a(){m("work :: getting next packet in queue");const t=s.shift();if(t)m("work :: packet pulled from queue"),e._handlePacket(t,i);else{m("work :: no packets in queue");const e=n;n=null,m("work :: done flag is %s",!!e),e&&e()}}function o(t){m("streamErrorHandler :: error",t.message),w.includes(t.code)?(m("streamErrorHandler :: emitting error"),e.emit("error",t)):R(t)}m("_setupStream :: calling method to clear reconnect"),this._clearReconnect(),m("_setupStream :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),r.on("packet",(function(e){m("parser :: on packet push to packets array."),s.push(e)})),t._write=function(e,t,s){n=s,m("writable stream :: parsing buffer"),r.parse(e),a()},m("_setupStream :: pipe stream to writable stream"),this.stream.pipe(t),this.stream.on("error",o),this.stream.on("close",(function(){m("(%s)stream :: on close",e.options.clientId),I(e.outgoing),m("stream: emit close to MqttClient"),e.emit("close")})),m("_setupStream: sending packet `connect`");const c=Object.create(this.options);if(c.cmd="connect",this.topicAliasRecv&&(c.properties||(c.properties={}),this.topicAliasRecv&&(c.properties.topicAliasMaximum=this.topicAliasRecv.max)),k(this,c),r.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return e.end((()=>this.emit("error",new Error("Packet has no Authentication Method")))),this;this.options.properties.authenticationMethod&&this.options.authPacket&&"object"==typeof this.options.authPacket&&k(this,g({cmd:"auth",reasonCode:0},this.options.authPacket))}this.stream.setMaxListeners(1e3),clearTimeout(this.connackTimer),this.connackTimer=setTimeout((function(){m("!!connectTimeout hit!! Calling _cleanUp with force `true`"),e._cleanUp(!0)}),this.options.connectTimeout)},L.prototype._handlePacket=function(e,t){const r=this.options;if(5===r.protocolVersion&&r.properties&&r.properties.maximumPacketSize&&r.properties.maximumPacketSize<e.length)return this.emit("error",new Error("exceeding packets size "+e.cmd)),this.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}}),this;switch(m("_handlePacket :: emitting packetreceive"),this.emit("packetreceive",e),e.cmd){case"publish":this._handlePublish(e,t);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":this._handleAck(e),t();break;case"pubrel":this._handlePubrel(e,t);break;case"connack":this._handleConnack(e),t();break;case"auth":this._handleAuth(e),t();break;case"pingresp":this._handlePingresp(e),t();break;case"disconnect":this._handleDisconnect(e),t()}},L.prototype._checkDisconnecting=function(e){return this.disconnecting&&(e&&e!==R?e(new Error("client disconnecting")):this.emit("error",new Error("client disconnecting"))),this.disconnecting},L.prototype.publish=function(e,t,r,n){m("publish :: message `%s` to topic `%s`",t,e);const s=this.options;if("function"==typeof r&&(n=r,r=null),r=g({qos:0,retain:!1,dup:!1},r),this._checkDisconnecting(n))return this;const i=this,a=function(){let a=0;if((1===r.qos||2===r.qos)&&(a=i._nextId(),null===a))return m("No messageId left"),!1;const o={cmd:"publish",topic:e,payload:t,qos:r.qos,retain:r.retain,messageId:a,dup:r.dup};switch(5===s.protocolVersion&&(o.properties=r.properties),m("publish :: qos",r.qos),r.qos){case 1:case 2:i.outgoing[o.messageId]={volatile:!1,cb:n||R},m("MqttClient:publish: packet cmd: %s",o.cmd),i._sendPacket(o,void 0,r.cbStorePut);break;default:m("MqttClient:publish: packet cmd: %s",o.cmd),i._sendPacket(o,n,r.cbStorePut)}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!a())&&this._storeProcessingQueue.push({invoke:a,cbStorePut:r.cbStorePut,callback:n}),this},L.prototype.subscribe=function(){const e=this,t=new Array(arguments.length);for(let e=0;e<arguments.length;e++)t[e]=arguments[e];const r=[];let n=t.shift();const s=n.resubscribe;let i=t.pop()||R,a=t.pop();const o=this.options.protocolVersion;delete n.resubscribe,"string"==typeof n&&(n=[n]),"function"!=typeof i&&(a=i,i=R);const l=p.validateTopics(n);if(null!==l)return v(i,new Error("Invalid topic "+l)),this;if(this._checkDisconnecting(i))return m("subscribe: discconecting true"),this;const c={qos:0};if(5===o&&(c.nl=!1,c.rap=!1,c.rh=0),a=g(c,a),Array.isArray(n)?n.forEach((function(t){if(m("subscribe: array topic %s",t),!Object.prototype.hasOwnProperty.call(e._resubscribeTopics,t)||e._resubscribeTopics[t].qos<a.qos||s){const e={topic:t,qos:a.qos};5===o&&(e.nl=a.nl,e.rap=a.rap,e.rh=a.rh,e.properties=a.properties),m("subscribe: pushing topic `%s` and qos `%s` to subs list",e.topic,e.qos),r.push(e)}})):Object.keys(n).forEach((function(t){if(m("subscribe: object topic %s",t),!Object.prototype.hasOwnProperty.call(e._resubscribeTopics,t)||e._resubscribeTopics[t].qos<n[t].qos||s){const e={topic:t,qos:n[t].qos};5===o&&(e.nl=n[t].nl,e.rap=n[t].rap,e.rh=n[t].rh,e.properties=a.properties),m("subscribe: pushing `%s` to subs list",e),r.push(e)}})),!r.length)return i(null,[]),this;const d=function(){const t=e._nextId();if(null===t)return m("No messageId left"),!1;const n={cmd:"subscribe",subscriptions:r,qos:1,retain:!1,dup:!1,messageId:t};if(a.properties&&(n.properties=a.properties),e.options.resubscribe){m("subscribe :: resubscribe true");const t=[];r.forEach((function(r){if(e.options.reconnectPeriod>0){const n={qos:r.qos};5===o&&(n.nl=r.nl||!1,n.rap=r.rap||!1,n.rh=r.rh||0,n.properties=r.properties),e._resubscribeTopics[r.topic]=n,t.push(r.topic)}})),e.messageIdToTopic[n.messageId]=t}return e.outgoing[n.messageId]={volatile:!0,cb:function(e,t){if(!e){const e=t.granted;for(let t=0;t<e.length;t+=1)r[t].qos=e[t]}i(e,r)}},m("subscribe :: call _sendPacket"),e._sendPacket(n),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!d())&&this._storeProcessingQueue.push({invoke:d,callback:i}),this},L.prototype.unsubscribe=function(){const e=this,t=new Array(arguments.length);for(let e=0;e<arguments.length;e++)t[e]=arguments[e];let r=t.shift(),n=t.pop()||R,s=t.pop();"string"==typeof r&&(r=[r]),"function"!=typeof n&&(s=n,n=R);const i=p.validateTopics(r);if(null!==i)return v(n,new Error("Invalid topic "+i)),this;if(e._checkDisconnecting(n))return this;const a=function(){const t=e._nextId();if(null===t)return m("No messageId left"),!1;const i={cmd:"unsubscribe",qos:1,messageId:t};return"string"==typeof r?i.unsubscriptions=[r]:Array.isArray(r)&&(i.unsubscriptions=r),e.options.resubscribe&&i.unsubscriptions.forEach((function(t){delete e._resubscribeTopics[t]})),"object"==typeof s&&s.properties&&(i.properties=s.properties),e.outgoing[i.messageId]={volatile:!0,cb:n},m("unsubscribe: call _sendPacket"),e._sendPacket(i),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!a())&&this._storeProcessingQueue.push({invoke:a,callback:n}),this},L.prototype.end=function(e,t,r){const n=this;function s(){m("end :: closeStores: closing incoming and outgoing stores"),n.disconnected=!0,n.incomingStore.close((function(e){n.outgoingStore.close((function(t){if(m("end :: closeStores: emitting end"),n.emit("end"),r){const n=e||t;m("end :: closeStores: invoking callback with args"),r(n)}}))})),n._deferredReconnect&&n._deferredReconnect()}function i(){m("end :: (%s) :: finish :: calling _cleanUp with force %s",n.options.clientId,e),n._cleanUp(e,(()=>{m("end :: finish :: calling process.nextTick on closeStores"),y(s.bind(n))}),t)}return m("end :: (%s)",this.options.clientId),null!=e&&"boolean"==typeof e||(r=t||R,t=e,e=!1,"object"!=typeof t&&(r=t,t=null,"function"!=typeof r&&(r=R))),"object"!=typeof t&&(r=t,t=null),m("end :: cb? %s",!!r),r=r||R,this.disconnecting?(r(),this):(this._clearReconnect(),this.disconnecting=!0,!e&&Object.keys(this.outgoing).length>0?(m("end :: (%s) :: calling finish in 10ms once outgoing is empty",n.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,i,10))):(m("end :: (%s) :: immediately calling finish",n.options.clientId),i()),this)},L.prototype.removeOutgoingMessage=function(e){const t=this.outgoing[e]?this.outgoing[e].cb:null;return delete this.outgoing[e],this.outgoingStore.del({messageId:e},(function(){t(new Error("Message removed"))})),this},L.prototype.reconnect=function(e){m("client reconnect");const t=this,r=function(){e?(t.options.incomingStore=e.incomingStore,t.options.outgoingStore=e.outgoingStore):(t.options.incomingStore=null,t.options.outgoingStore=null),t.incomingStore=t.options.incomingStore||new i,t.outgoingStore=t.options.outgoingStore||new i,t.disconnecting=!1,t.disconnected=!1,t._deferredReconnect=null,t._reconnect()};return this.disconnecting&&!this.disconnected?this._deferredReconnect=r:r(),this},L.prototype._reconnect=function(){m("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected?(this.end((()=>{this._setupStream()})),m("client already connected. disconnecting first.")):(m("_reconnect: calling _setupStream"),this._setupStream())},L.prototype._setupReconnect=function(){const e=this;!e.disconnecting&&!e.reconnectTimer&&e.options.reconnectPeriod>0?(this.reconnecting||(m("_setupReconnect :: emit `offline` state"),this.emit("offline"),m("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0),m("_setupReconnect :: setting reconnectTimer for %d ms",e.options.reconnectPeriod),e.reconnectTimer=setInterval((function(){m("reconnectTimer :: reconnect triggered!"),e._reconnect()}),e.options.reconnectPeriod)):m("_setupReconnect :: doing nothing...")},L.prototype._clearReconnect=function(){m("_clearReconnect : clearing reconnect timer"),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null)},L.prototype._cleanUp=function(e,t){const r=arguments[2];if(t&&(m("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",t)),m("_cleanUp :: forced? %s",e),e)0===this.options.reconnectPeriod&&this.options.clean&&A(this.outgoing),m("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{const e=g({cmd:"disconnect"},r);m("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(e,v.bind(null,this.stream.end.bind(this.stream)))}this.disconnecting||(m("_cleanUp :: client not disconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect()),null!==this.pingTimer&&(m("_cleanUp :: clearing pingTimer"),this.pingTimer.clear(),this.pingTimer=null),t&&!this.connected&&(m("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",t),t())},L.prototype._sendPacket=function(e,t,r){m("_sendPacket :: (%s) :: start",this.options.clientId),r=r||R,t=t||R;const n=T(this,e);if(n)t(n);else{if(!this.connected)return"auth"===e.cmd?(this._shiftPingInterval(),void k(this,e,t)):(m("_sendPacket :: client not connected. Storing packet offline."),void this._storePacket(e,t,r));switch(this._shiftPingInterval(),e.cmd){case"publish":break;case"pubrel":return void _(this,e,t,r);default:return void k(this,e,t)}switch(e.qos){case 2:case 1:_(this,e,t,r);break;default:k(this,e,t)}m("_sendPacket :: (%s) :: end",this.options.clientId)}},L.prototype._storePacket=function(e,t,r){m("_storePacket :: packet: %o",e),m("_storePacket :: cb? %s",!!t),r=r||R;let n=e;if("publish"===n.cmd){n=f(e);const r=C(this,n);if(r)return t&&t(r)}0===(n.qos||0)&&this.queueQoSZero||"publish"!==n.cmd?this.queue.push({packet:n,cb:t}):n.qos>0?(t=this.outgoing[n.messageId]?this.outgoing[n.messageId].cb:null,this.outgoingStore.put(n,(function(e){if(e)return t&&t(e);r()}))):t&&t(new Error("No connection to broker"))},L.prototype._setupPingTimer=function(){m("_setupPingTimer :: keepalive %d (seconds)",this.options.keepalive);const e=this;!this.pingTimer&&this.options.keepalive&&(this.pingResp=!0,this.pingTimer=h((function(){e._checkPing()}),1e3*this.options.keepalive))},L.prototype._shiftPingInterval=function(){this.pingTimer&&this.options.keepalive&&this.options.reschedulePings&&this.pingTimer.reschedule(1e3*this.options.keepalive)},L.prototype._checkPing=function(){m("_checkPing :: checking ping..."),this.pingResp?(m("_checkPing :: ping response received. Clearing flag and sending `pingreq`"),this.pingResp=!1,this._sendPacket({cmd:"pingreq"})):(m("_checkPing :: calling _cleanUp with force true"),this._cleanUp(!0))},L.prototype._handlePingresp=function(){this.pingResp=!0},L.prototype._handleConnack=function(e){m("_handleConnack");const t=this.options,r=5===t.protocolVersion?e.reasonCode:e.returnCode;if(clearTimeout(this.connackTimer),delete this.topicAliasSend,e.properties){if(e.properties.topicAliasMaximum){if(e.properties.topicAliasMaximum>65535)return void this.emit("error",new Error("topicAliasMaximum from broker is out of range"));e.properties.topicAliasMaximum>0&&(this.topicAliasSend=new o(e.properties.topicAliasMaximum))}e.properties.serverKeepAlive&&t.keepalive&&(t.keepalive=e.properties.serverKeepAlive,this._shiftPingInterval()),e.properties.maximumPacketSize&&(t.properties||(t.properties={}),t.properties.maximumPacketSize=e.properties.maximumPacketSize)}if(0===r)this.reconnecting=!1,this._onConnect(e);else if(r>0){const e=new Error("Connection refused: "+E[r]);e.code=r,this.emit("error",e)}},L.prototype._handleAuth=function(e){const t=this.options.protocolVersion,r=5===t?e.reasonCode:e.returnCode;if(5!==t){const e=new Error("Protocol error: Auth packets are only supported in MQTT 5. Your version:"+t);return e.code=r,void this.emit("error",e)}const n=this;this.handleAuth(e,(function(e,t){if(e)n.emit("error",e);else if(24===r)n.reconnecting=!1,n._sendPacket(t);else{const t=new Error("Connection refused: "+E[r]);e.code=r,n.emit("error",t)}}))},L.prototype.handleAuth=function(e,t){t()},L.prototype._handlePublish=function(e,t){m("_handlePublish: packet %o",e),t=void 0!==t?t:R;let r=e.topic.toString();const n=e.payload,s=e.qos,i=e.messageId,a=this,o=this.options,l=[0,16,128,131,135,144,145,151,153];if(5===this.options.protocolVersion){let t;if(e.properties&&(t=e.properties.topicAlias),void 0!==t)if(0===r.length){if(!(t>0&&t<=65535))return m("_handlePublish :: topic alias out of range. alias: %d",t),void this.emit("error",new Error("Received Topic Alias is out of range"));{const e=this.topicAliasRecv.getTopicByAlias(t);if(!e)return m("_handlePublish :: unregistered topic alias. alias: %d",t),void this.emit("error",new Error("Received unregistered Topic Alias"));r=e,m("_handlePublish :: topic complemented by alias. topic: %s - alias: %d",r,t)}}else{if(!this.topicAliasRecv.put(r,t))return m("_handlePublish :: topic alias out of range. alias: %d",t),void this.emit("error",new Error("Received Topic Alias is out of range"));m("_handlePublish :: registered topic: %s - alias: %d",r,t)}}switch(m("_handlePublish: qos %d",s),s){case 2:o.customHandleAcks(r,n,e,(function(r,n){return r instanceof Error||(n=r,r=null),r?a.emit("error",r):-1===l.indexOf(n)?a.emit("error",new Error("Wrong reason code for pubrec")):void(n?a._sendPacket({cmd:"pubrec",messageId:i,reasonCode:n},t):a.incomingStore.put(e,(function(){a._sendPacket({cmd:"pubrec",messageId:i},t)})))}));break;case 1:o.customHandleAcks(r,n,e,(function(s,o){return s instanceof Error||(o=s,s=null),s?a.emit("error",s):-1===l.indexOf(o)?a.emit("error",new Error("Wrong reason code for puback")):(o||a.emit("message",r,n,e),void a.handleMessage(e,(function(e){if(e)return t&&t(e);a._sendPacket({cmd:"puback",messageId:i,reasonCode:o},t)})))}));break;case 0:this.emit("message",r,n,e),this.handleMessage(e,t);break;default:m("_handlePublish: unknown QoS. Doing nothing.")}},L.prototype.handleMessage=function(e,t){t()},L.prototype._handleAck=function(e){const t=e.messageId,r=e.cmd;let n=null;const s=this.outgoing[t]?this.outgoing[t].cb:null,i=this;let a;if(s){switch(m("_handleAck :: packet type",r),r){case"pubcomp":case"puback":{const r=e.reasonCode;r&&r>0&&16!==r&&(a=new Error("Publish error: "+E[r]),a.code=r,s(a,e)),delete this.outgoing[t],this.outgoingStore.del(e,s),this.messageIdProvider.deallocate(t),this._invokeStoreProcessingQueue();break}case"pubrec":{n={cmd:"pubrel",qos:2,messageId:t};const r=e.reasonCode;r&&r>0&&16!==r?(a=new Error("Publish error: "+E[r]),a.code=r,s(a,e)):this._sendPacket(n);break}case"suback":delete this.outgoing[t],this.messageIdProvider.deallocate(t);for(let r=0;r<e.granted.length;r++)if(0!=(128&e.granted[r])){const e=this.messageIdToTopic[t];e&&e.forEach((function(e){delete i._resubscribeTopics[e]}))}this._invokeStoreProcessingQueue(),s(null,e);break;case"unsuback":delete this.outgoing[t],this.messageIdProvider.deallocate(t),this._invokeStoreProcessingQueue(),s(null);break;default:i.emit("error",new Error("unrecognized packet type"))}this.disconnecting&&0===Object.keys(this.outgoing).length&&this.emit("outgoingEmpty")}else m("_handleAck :: Server sent an ack in error. Ignoring.")},L.prototype._handlePubrel=function(e,t){m("handling pubrel packet"),t=void 0!==t?t:R;const r=e.messageId,n=this,s={cmd:"pubcomp",messageId:r};n.incomingStore.get(e,(function(e,r){e?n._sendPacket(s,t):(n.emit("message",r.topic,r.payload,r),n.handleMessage(r,(function(e){if(e)return t(e);n.incomingStore.del(r,R),n._sendPacket(s,t)})))}))},L.prototype._handleDisconnect=function(e){this.emit("disconnect",e)},L.prototype._nextId=function(){return this.messageIdProvider.allocate()},L.prototype.getLastMessageId=function(){return this.messageIdProvider.getLastAllocated()},L.prototype._resubscribe=function(){m("_resubscribe");const e=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||5===this.options.protocolVersion&&!this.connackPacket.sessionPresent)&&e.length>0)if(this.options.resubscribe)if(5===this.options.protocolVersion){m("_resubscribe: protocolVersion 5");for(let t=0;t<e.length;t++){const r={};r[e[t]]=this._resubscribeTopics[e[t]],r.resubscribe=!0,this.subscribe(r,{properties:r[e[t]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1},L.prototype._onConnect=function(e){if(this.disconnected)return void this.emit("connect",e);const t=this;function r(){let n=t.outgoingStore.createStream();function s(){t._storeProcessing=!1,t._packetIdsDuringStoreProcessing={}}function i(){n.destroy(),n=null,t._flushStoreProcessingQueue(),s()}function a(){if(!n)return;t._storeProcessing=!0;const e=n.read(1);let r;e?t._packetIdsDuringStoreProcessing[e.messageId]?a():t.disconnecting||t.reconnectTimer?n.destroy&&n.destroy():(r=t.outgoing[e.messageId]?t.outgoing[e.messageId].cb:null,t.outgoing[e.messageId]={volatile:!1,cb:function(e,t){r&&r(e,t),a()}},t._packetIdsDuringStoreProcessing[e.messageId]=!0,t.messageIdProvider.register(e.messageId)?t._sendPacket(e):m("messageId: %d has already used.",e.messageId)):n.once("readable",a)}t.once("close",i),n.on("error",(function(e){s(),t._flushStoreProcessingQueue(),t.removeListener("close",i),t.emit("error",e)})),n.on("end",(function(){let n=!0;for(const e in t._packetIdsDuringStoreProcessing)if(!t._packetIdsDuringStoreProcessing[e]){n=!1;break}n?(s(),t.removeListener("close",i),t._invokeAllStoreProcessingQueue(),t.emit("connect",e)):r()})),a()}this.connackPacket=e,this.messageIdProvider.clear(),this._setupPingTimer(),this.connected=!0,r()},L.prototype._invokeStoreProcessingQueue=function(){if(this._storeProcessingQueue.length>0){const e=this._storeProcessingQueue[0];if(e&&e.invoke())return this._storeProcessingQueue.shift(),!0}return!1},L.prototype._invokeAllStoreProcessingQueue=function(){for(;this._invokeStoreProcessingQueue(););},L.prototype._flushStoreProcessingQueue=function(){for(const e of this._storeProcessingQueue)e.cbStorePut&&e.cbStorePut(new Error("Connection closed")),e.callback&&e.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)},t.exports=L}).call(this)}).call(this,e("_process"),void 0!==ft?ft:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./default-message-id-provider":7,"./store":8,"./topic-alias-recv":9,"./topic-alias-send":10,"./validations":11,_process:50,debug:18,events:22,inherits:24,"mqtt-packet":40,"readable-stream":69,reinterval:70,"rfdc/default":71,xtend:81}],2:[function(e,t,r){const{Buffer:n}=e("buffer"),s=e("readable-stream").Transform,i=e("duplexify");let a,o,l,c=!1;function d(){const e=new s;return e._write=function(e,t,r){a.sendSocketMessage({data:e.buffer,success:function(){r()},fail:function(){r(new Error)}})},e._flush=function(e){a.closeSocket({success:function(){e()}})},e}function u(e){e.hostname||(e.hostname="localhost"),e.path||(e.path="/"),e.wsOptions||(e.wsOptions={})}function h(e,t){const r="alis"===e.protocol?"wss":"ws";let n=r+"://"+e.hostname+e.path;return e.port&&80!==e.port&&443!==e.port&&(n=r+"://"+e.hostname+":"+e.port+e.path),"function"==typeof e.transformWsUrl&&(n=e.transformWsUrl(n,e,t)),n}function f(){c||(c=!0,a.onSocketOpen((function(){l.setReadable(o),l.setWritable(o),l.emit("connect")})),a.onSocketMessage((function(e){if("string"==typeof e.data){const t=n.from(e.data,"base64");o.push(t)}else{const t=new FileReader;t.addEventListener("load",(function(){let e=t.result;e=e instanceof ArrayBuffer?n.from(e):n.from(e,"utf8"),o.push(e)})),t.readAsArrayBuffer(e.data)}})),a.onSocketClose((function(){l.end(),l.destroy()})),a.onSocketError((function(e){l.destroy(e)})))}function p(e,t){if(t.hostname=t.hostname||t.host,!t.hostname)throw new Error("Could not determine host. Specify host manually.");const r="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt";u(t);const n=h(t,e);return a=t.my,a.connectSocket({url:n,protocols:r}),o=d(),l=i.obj(),f(),l}t.exports=p},{buffer:17,duplexify:20,"readable-stream":69}],3:[function(e,t,r){const n=e("net"),s=e("debug")("mqttjs:tcp");function i(e,t){t.port=t.port||1883,t.hostname=t.hostname||t.host||"localhost";const r=t.port,i=t.hostname;return s("port %d and host %s",r,i),n.createConnection(r,i)}t.exports=i},{debug:18,net:16}],4:[function(e,t,r){const n=e("tls"),s=e("net"),i=e("debug")("mqttjs:tls");function a(e,t){t.port=t.port||8883,t.host=t.hostname||t.host||"localhost",0===s.isIP(t.host)&&(t.servername=t.host),t.rejectUnauthorized=!1!==t.rejectUnauthorized,delete t.path,i("port %d host %s rejectUnauthorized %b",t.port,t.host,t.rejectUnauthorized);const r=n.connect(t);function a(n){t.rejectUnauthorized&&e.emit("error",n),r.end()}return r.on("secureConnect",(function(){t.rejectUnauthorized&&!r.authorized?r.emit("error",new Error("TLS not authorized")):r.removeListener("error",a)})),r.on("error",a),r}t.exports=a},{debug:18,net:16,tls:16}],5:[function(e,t,r){(function(r){(function(){const{Buffer:n}=e("buffer"),s=e("ws"),i=e("debug")("mqttjs:ws"),a=e("duplexify"),o=e("readable-stream").Transform,l=["rejectUnauthorized","ca","cert","key","pfx","passphrase"],c=void 0!==r&&"browser"===r.title||"function"==typeof __webpack_require__;function d(e,t){let r=e.protocol+"://"+e.hostname+":"+e.port+e.path;return"function"==typeof e.transformWsUrl&&(r=e.transformWsUrl(r,e,t)),r}function u(e){const t=e;return e.hostname||(t.hostname="localhost"),e.port||("wss"===e.protocol?t.port=443:t.port=80),e.path||(t.path="/"),e.wsOptions||(t.wsOptions={}),c||"wss"!==e.protocol||l.forEach((function(r){Object.prototype.hasOwnProperty.call(e,r)&&!Object.prototype.hasOwnProperty.call(e.wsOptions,r)&&(t.wsOptions[r]=e[r])})),t}function h(e){const t=u(e);if(t.hostname||(t.hostname=t.host),!t.hostname){if("undefined"==typeof document)throw new Error("Could not determine host. Specify host manually.");const e=new URL(document.URL);t.hostname=e.hostname,t.port||(t.port=e.port)}return void 0===t.objectMode&&(t.objectMode=!(!0===t.binary||void 0===t.binary)),t}function f(e,t,r){i("createWebSocket"),i("protocol: "+r.protocolId+" "+r.protocolVersion);const n="MQIsdp"===r.protocolId&&3===r.protocolVersion?"mqttv3.1":"mqtt";return i("creating new Websocket for url: "+t+" and protocol: "+n),new s(t,[n],r.wsOptions)}function p(e,t){const r="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt",n=d(t,e),s=new WebSocket(n,[r]);return s.binaryType="arraybuffer",s}function g(e,t){i("streamBuilder");const r=u(t),n=d(r,e),a=f(e,n,r),o=s.createWebSocketStream(a,r.wsOptions);return o.url=n,a.on("close",(()=>{o.destroy()})),o}function m(e,t){let r;i("browserStreamBuilder");const s=h(t).browserBufferSize||524288,l=t.browserBufferTimeout||1e3,c=!t.objectMode,d=p(e,t),u=g(t,E,S);t.objectMode||(u._writev=w),u.on("close",(()=>{d.close()}));const f=void 0!==d.addEventListener;function g(e,t,r){const n=new o({objectModeMode:e.objectMode});return n._write=t,n._flush=r,n}function m(){r.setReadable(u),r.setWritable(u),r.emit("connect")}function y(){r.end(),r.destroy()}function v(e){r.destroy(e)}function b(e){let t=e.data;t=t instanceof ArrayBuffer?n.from(t):n.from(t,"utf8"),u.push(t)}function w(e,t){const r=new Array(e.length);for(let t=0;t<e.length;t++)"string"==typeof e[t].chunk?r[t]=n.from(e[t],"utf8"):r[t]=e[t].chunk;this._write(n.concat(r),"binary",t)}function E(e,t,r){d.bufferedAmount>s&&setTimeout(E,l,e,t,r),c&&"string"==typeof e&&(e=n.from(e,"utf8"));try{d.send(e)}catch(e){return r(e)}r()}function S(e){d.close(),e()}return d.readyState===d.OPEN?r=u:(r=r=a(void 0,void 0,t),t.objectMode||(r._writev=w),f?d.addEventListener("open",m):d.onopen=m),r.socket=d,f?(d.addEventListener("close",y),d.addEventListener("error",v),d.addEventListener("message",b)):(d.onclose=y,d.onerror=v,d.onmessage=b),r}t.exports=c?m:g}).call(this)}).call(this,e("_process"))},{_process:50,buffer:17,debug:18,duplexify:20,"readable-stream":69,ws:80}],6:[function(e,t,r){const{Buffer:n}=e("buffer"),s=e("readable-stream").Transform,i=e("duplexify");let a,o,l;function c(){const e=new s;return e._write=function(e,t,r){a.send({data:e.buffer,success:function(){r()},fail:function(e){r(new Error(e))}})},e._flush=function(e){a.close({success:function(){e()}})},e}function d(e){e.hostname||(e.hostname="localhost"),e.path||(e.path="/"),e.wsOptions||(e.wsOptions={})}function u(e,t){const r="wxs"===e.protocol?"wss":"ws";let n=r+"://"+e.hostname+e.path;return e.port&&80!==e.port&&443!==e.port&&(n=r+"://"+e.hostname+":"+e.port+e.path),"function"==typeof e.transformWsUrl&&(n=e.transformWsUrl(n,e,t)),n}function h(){a.onOpen((function(){l.setReadable(o),l.setWritable(o),l.emit("connect")})),a.onMessage((function(e){let t=e.data;t=t instanceof ArrayBuffer?n.from(t):n.from(t,"utf8"),o.push(t)})),a.onClose((function(){l.end(),l.destroy()})),a.onError((function(e){l.destroy(new Error(e.errMsg))}))}function f(e,t){if(t.hostname=t.hostname||t.host,!t.hostname)throw new Error("Could not determine host. Specify host manually.");const r="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt";d(t);const n=u(t,e);a=wx.connectSocket({url:n,protocols:[r]}),o=c(),l=i.obj(),l._destroy=function(e,t){a.close({success:function(){t&&t(e)}})};const s=l.destroy;return l.destroy=function(){l.destroy=s;const e=this;setTimeout((function(){a.close({fail:function(){e._destroy(new Error)}})}),0)}.bind(l),h(),l}t.exports=f},{buffer:17,duplexify:20,"readable-stream":69}],7:[function(e,t,r){function n(){if(!(this instanceof n))return new n;this.nextId=Math.max(1,Math.floor(65535*Math.random()))}n.prototype.allocate=function(){const e=this.nextId++;return 65536===this.nextId&&(this.nextId=1),e},n.prototype.getLastAllocated=function(){return 1===this.nextId?65535:this.nextId-1},n.prototype.register=function(e){return!0},n.prototype.deallocate=function(e){},n.prototype.clear=function(){},t.exports=n},{}],8:[function(e,t,r){const n=e("xtend"),s=e("readable-stream").Readable,i={objectMode:!0},a={clean:!0};function o(e){if(!(this instanceof o))return new o(e);this.options=e||{},this.options=n(a,e),this._inflights=new Map}o.prototype.put=function(e,t){return this._inflights.set(e.messageId,e),t&&t(),this},o.prototype.createStream=function(){const e=new s(i),t=[];let r=!1,n=0;return this._inflights.forEach((function(e,r){t.push(e)})),e._read=function(){!r&&n<t.length?this.push(t[n++]):this.push(null)},e.destroy=function(){if(r)return;const e=this;r=!0,setTimeout((function(){e.emit("close")}),0)},e},o.prototype.del=function(e,t){return(e=this._inflights.get(e.messageId))?(this._inflights.delete(e.messageId),t(null,e)):t&&t(new Error("missing packet")),this},o.prototype.get=function(e,t){return(e=this._inflights.get(e.messageId))?t(null,e):t&&t(new Error("missing packet")),this},o.prototype.close=function(e){this.options.clean&&(this._inflights=null),e&&e()},t.exports=o},{"readable-stream":69,xtend:81}],9:[function(e,t,r){function n(e){if(!(this instanceof n))return new n(e);this.aliasToTopic={},this.max=e}n.prototype.put=function(e,t){return!(0===t||t>this.max||(this.aliasToTopic[t]=e,this.length=Object.keys(this.aliasToTopic).length,0))},n.prototype.getTopicByAlias=function(e){return this.aliasToTopic[e]},n.prototype.clear=function(){this.aliasToTopic={}},t.exports=n},{}],10:[function(e,t,r){const n=e("lru-cache"),s=e("number-allocator").NumberAllocator;function i(e){if(!(this instanceof i))return new i(e);e>0&&(this.aliasToTopic=new n({max:e}),this.topicToAlias={},this.numberAllocator=new s(1,e),this.max=e,this.length=0)}i.prototype.put=function(e,t){if(0===t||t>this.max)return!1;const r=this.aliasToTopic.get(t);return r&&delete this.topicToAlias[r],this.aliasToTopic.set(t,e),this.topicToAlias[e]=t,this.numberAllocator.use(t),this.length=this.aliasToTopic.length,!0},i.prototype.getTopicByAlias=function(e){return this.aliasToTopic.get(e)},i.prototype.getAliasByTopic=function(e){const t=this.topicToAlias[e];return void 0!==t&&this.aliasToTopic.get(t),t},i.prototype.clear=function(){this.aliasToTopic.reset(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0},i.prototype.getLruAlias=function(){const e=this.numberAllocator.firstVacant();return e||this.aliasToTopic.keys()[this.aliasToTopic.length-1]},t.exports=i},{"lru-cache":37,"number-allocator":46}],11:[function(e,t,r){function n(e){const t=e.split("/");for(let e=0;e<t.length;e++)if("+"!==t[e]){if("#"===t[e])return e===t.length-1;if(-1!==t[e].indexOf("+")||-1!==t[e].indexOf("#"))return!1}return!0}function s(e){if(0===e.length)return"empty_topic_list";for(let t=0;t<e.length;t++)if(!n(e[t]))return e[t];return null}t.exports={validateTopics:s}},{}],12:[function(e,t,r){(function(r){(function(){const n=e("../client"),s=e("../store"),i=e("url"),a=e("xtend"),o=e("debug")("mqttjs"),l={};function c(e){let t;e.auth&&(t=e.auth.match(/^(.+):(.+)$/),t?(e.username=t[1],e.password=t[2]):e.username=e.auth)}function d(e,t){if(o("connecting to an MQTT broker..."),"object"!=typeof e||t||(t=e,e=null),t=t||{},e){const r=i.parse(e,!0);if(null!=r.port&&(r.port=Number(r.port)),null===(t=a(r,t)).protocol)throw new Error("Missing protocol");t.protocol=t.protocol.replace(/:$/,"")}if(c(t),t.query&&"string"==typeof t.query.clientId&&(t.clientId=t.query.clientId),t.cert&&t.key){if(!t.protocol)throw new Error("Missing secure protocol key");if(-1===["mqtts","wss","wxs","alis"].indexOf(t.protocol))switch(t.protocol){case"mqtt":t.protocol="mqtts";break;case"ws":t.protocol="wss";break;case"wx":t.protocol="wxs";break;case"ali":t.protocol="alis";break;default:throw new Error('Unknown protocol for secure connection: "'+t.protocol+'"!')}}if(!l[t.protocol]){const e=-1!==["mqtts","wss"].indexOf(t.protocol);t.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((function(t,r){return(!e||r%2!=0)&&"function"==typeof l[t]}))[0]}if(!1===t.clean&&!t.clientId)throw new Error("Missing clientId for unclean clients");function r(e){return t.servers&&(e._reconnectCount&&e._reconnectCount!==t.servers.length||(e._reconnectCount=0),t.host=t.servers[e._reconnectCount].host,t.port=t.servers[e._reconnectCount].port,t.protocol=t.servers[e._reconnectCount].protocol?t.servers[e._reconnectCount].protocol:t.defaultProtocol,t.hostname=t.host,e._reconnectCount++),o("calling streambuilder for",t.protocol),l[t.protocol](e,t)}t.protocol&&(t.defaultProtocol=t.protocol);const s=new n(r,t);return s.on("error",(function(){})),s}void 0!==r&&"browser"!==r.title||"function"!=typeof __webpack_require__?(l.mqtt=e("./tcp"),l.tcp=e("./tcp"),l.ssl=e("./tls"),l.tls=e("./tls"),l.mqtts=e("./tls")):(l.wx=e("./wx"),l.wxs=e("./wx"),l.ali=e("./ali"),l.alis=e("./ali")),l.ws=e("./ws"),l.wss=e("./ws"),t.exports=d,t.exports.connect=d,t.exports.MqttClient=n,t.exports.Store=s}).call(this)}).call(this,e("_process"))},{"../client":1,"../store":8,"./ali":2,"./tcp":3,"./tls":4,"./ws":5,"./wx":6,_process:50,debug:18,url:76,xtend:81}],13:[function(e,t,r){r.byteLength=d,r.toByteArray=h,r.fromByteArray=g;for(var n=[],s=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,l=a.length;o<l;++o)n[o]=a[o],s[a.charCodeAt(o)]=o;function c(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function d(e){var t=c(e),r=t[0],n=t[1];return 3*(r+n)/4-n}function u(e,t,r){return 3*(t+r)/4-r}function h(e){var t,r,n=c(e),a=n[0],o=n[1],l=new i(u(e,a,o)),d=0,h=o>0?a-4:a;for(r=0;r<h;r+=4)t=s[e.charCodeAt(r)]<<18|s[e.charCodeAt(r+1)]<<12|s[e.charCodeAt(r+2)]<<6|s[e.charCodeAt(r+3)],l[d++]=t>>16&255,l[d++]=t>>8&255,l[d++]=255&t;return 2===o&&(t=s[e.charCodeAt(r)]<<2|s[e.charCodeAt(r+1)]>>4,l[d++]=255&t),1===o&&(t=s[e.charCodeAt(r)]<<10|s[e.charCodeAt(r+1)]<<4|s[e.charCodeAt(r+2)]>>2,l[d++]=t>>8&255,l[d++]=255&t),l}function f(e){return n[e>>18&63]+n[e>>12&63]+n[e>>6&63]+n[63&e]}function p(e,t,r){for(var n,s=[],i=t;i<r;i+=3)n=(e[i]<<16&16711680)+(e[i+1]<<8&65280)+(255&e[i+2]),s.push(f(n));return s.join("")}function g(e){for(var t,r=e.length,s=r%3,i=[],a=16383,o=0,l=r-s;o<l;o+=a)i.push(p(e,o,o+a>l?l:o+a));return 1===s?(t=e[r-1],i.push(n[t>>2]+n[t<<4&63]+"==")):2===s&&(t=(e[r-2]<<8)+e[r-1],i.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"=")),i.join("")}s["-".charCodeAt(0)]=62,s["_".charCodeAt(0)]=63},{}],14:[function(e,t,r){const{Buffer:n}=e("buffer"),s=Symbol.for("BufferList");function i(e){if(!(this instanceof i))return new i(e);i._init.call(this,e)}i._init=function(e){Object.defineProperty(this,s,{value:!0}),this._bufs=[],this.length=0,e&&this.append(e)},i.prototype._new=function(e){return new i(e)},i.prototype._offset=function(e){if(0===e)return[0,0];let t=0;for(let r=0;r<this._bufs.length;r++){const n=t+this._bufs[r].length;if(e<n||r===this._bufs.length-1)return[r,e-t];t=n}},i.prototype._reverseOffset=function(e){const t=e[0];let r=e[1];for(let e=0;e<t;e++)r+=this._bufs[e].length;return r},i.prototype.get=function(e){if(e>this.length||e<0)return;const t=this._offset(e);return this._bufs[t[0]][t[1]]},i.prototype.slice=function(e,t){return"number"==typeof e&&e<0&&(e+=this.length),"number"==typeof t&&t<0&&(t+=this.length),this.copy(null,0,e,t)},i.prototype.copy=function(e,t,r,s){if(("number"!=typeof r||r<0)&&(r=0),("number"!=typeof s||s>this.length)&&(s=this.length),r>=this.length)return e||n.alloc(0);if(s<=0)return e||n.alloc(0);const i=!!e,a=this._offset(r),o=s-r;let l=o,c=i&&t||0,d=a[1];if(0===r&&s===this.length){if(!i)return 1===this._bufs.length?this._bufs[0]:n.concat(this._bufs,this.length);for(let t=0;t<this._bufs.length;t++)this._bufs[t].copy(e,c),c+=this._bufs[t].length;return e}if(l<=this._bufs[a[0]].length-d)return i?this._bufs[a[0]].copy(e,t,d,d+l):this._bufs[a[0]].slice(d,d+l);i||(e=n.allocUnsafe(o));for(let t=a[0];t<this._bufs.length;t++){const r=this._bufs[t].length-d;if(!(l>r)){this._bufs[t].copy(e,c,d,d+l),c+=r;break}this._bufs[t].copy(e,c,d),c+=r,l-=r,d&&(d=0)}return e.length>c?e.slice(0,c):e},i.prototype.shallowSlice=function(e,t){if(e=e||0,t="number"!=typeof t?this.length:t,e<0&&(e+=this.length),t<0&&(t+=this.length),e===t)return this._new();const r=this._offset(e),n=this._offset(t),s=this._bufs.slice(r[0],n[0]+1);return 0===n[1]?s.pop():s[s.length-1]=s[s.length-1].slice(0,n[1]),0!==r[1]&&(s[0]=s[0].slice(r[1])),this._new(s)},i.prototype.toString=function(e,t,r){return this.slice(t,r).toString(e)},i.prototype.consume=function(e){if(e=Math.trunc(e),Number.isNaN(e)||e<=0)return this;for(;this._bufs.length;){if(!(e>=this._bufs[0].length)){this._bufs[0]=this._bufs[0].slice(e),this.length-=e;break}e-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift()}return this},i.prototype.duplicate=function(){const e=this._new();for(let t=0;t<this._bufs.length;t++)e.append(this._bufs[t]);return e},i.prototype.append=function(e){if(null==e)return this;if(e.buffer)this._appendBuffer(n.from(e.buffer,e.byteOffset,e.byteLength));else if(Array.isArray(e))for(let t=0;t<e.length;t++)this.append(e[t]);else if(this._isBufferList(e))for(let t=0;t<e._bufs.length;t++)this.append(e._bufs[t]);else"number"==typeof e&&(e=e.toString()),this._appendBuffer(n.from(e));return this},i.prototype._appendBuffer=function(e){this._bufs.push(e),this.length+=e.length},i.prototype.indexOf=function(e,t,r){if(void 0===r&&"string"==typeof t&&(r=t,t=void 0),"function"==typeof e||Array.isArray(e))throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');if("number"==typeof e?e=n.from([e]):"string"==typeof e?e=n.from(e,r):this._isBufferList(e)?e=e.slice():Array.isArray(e.buffer)?e=n.from(e.buffer,e.byteOffset,e.byteLength):n.isBuffer(e)||(e=n.from(e)),t=Number(t||0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),0===e.length)return t>this.length?this.length:t;const s=this._offset(t);let i=s[0],a=s[1];for(;i<this._bufs.length;i++){const t=this._bufs[i];for(;a<t.length;)if(t.length-a>=e.length){const r=t.indexOf(e,a);if(-1!==r)return this._reverseOffset([i,r]);a=t.length-e.length+1}else{const t=this._reverseOffset([i,a]);if(this._match(t,e))return t;a++}a=0}return-1},i.prototype._match=function(e,t){if(this.length-e<t.length)return!1;for(let r=0;r<t.length;r++)if(this.get(e+r)!==t[r])return!1;return!0},function(){const e={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(const t in e)!function(t){null===e[t]?i.prototype[t]=function(e,r){return this.slice(e,e+r)[t](0,r)}:i.prototype[t]=function(r=0){return this.slice(r,r+e[t])[t](0)}}(t)}(),i.prototype._isBufferList=function(e){return e instanceof i||i.isBufferList(e)},i.isBufferList=function(e){return null!=e&&e[s]},t.exports=i},{buffer:17}],15:[function(e,t,r){const n=e("readable-stream").Duplex,s=e("inherits"),i=e("./BufferList");function a(e){if(!(this instanceof a))return new a(e);if("function"==typeof e){this._callback=e;const t=function(e){this._callback&&(this._callback(e),this._callback=null)}.bind(this);this.on("pipe",(function(e){e.on("error",t)})),this.on("unpipe",(function(e){e.removeListener("error",t)})),e=null}i._init.call(this,e),n.call(this)}s(a,n),Object.assign(a.prototype,i.prototype),a.prototype._new=function(e){return new a(e)},a.prototype._write=function(e,t,r){this._appendBuffer(e),"function"==typeof r&&r()},a.prototype._read=function(e){if(!this.length)return this.push(null);e=Math.min(e,this.length),this.push(this.slice(0,e)),this.consume(e)},a.prototype.end=function(e){n.prototype.end.call(this,e),this._callback&&(this._callback(null,this.slice()),this._callback=null)},a.prototype._destroy=function(e,t){this._bufs.length=0,this.length=0,t(e)},a.prototype._isBufferList=function(e){return e instanceof a||e instanceof i||a.isBufferList(e)},a.isBufferList=i.isBufferList,t.exports=a,t.exports.BufferListStream=a,t.exports.BufferList=i},{"./BufferList":14,inherits:24,"readable-stream":69}],16:[function(e,t,r){},{}],17:[function(e,t,r){(function(t){(function(){var t=e("base64-js"),n=e("ieee754");r.Buffer=o,r.SlowBuffer=y,r.INSPECT_MAX_BYTES=50;var s=2147483647;function i(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(e){return!1}}function a(e){if(e>s)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=o.prototype,t}function o(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return u(e)}return l(e,t,r)}function l(e,t,r){if("string"==typeof e)return h(e,t);if(ArrayBuffer.isView(e))return f(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(Q(e,ArrayBuffer)||e&&Q(e.buffer,ArrayBuffer))return p(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return o.from(n,t,r);var s=g(e);if(s)return s;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return o.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function d(e,t,r){return c(e),e<=0?a(e):void 0!==t?"string"==typeof r?a(e).fill(t,r):a(e).fill(t):a(e)}function u(e){return c(e),a(e<0?0:0|m(e))}function h(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!o.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var r=0|v(e,t),n=a(r),s=n.write(e,t);return s!==r&&(n=n.slice(0,s)),n}function f(e){for(var t=e.length<0?0:0|m(e.length),r=a(t),n=0;n<t;n+=1)r[n]=255&e[n];return r}function p(e,t,r){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw new RangeError('"length" is outside of buffer bounds');var n;return(n=void 0===t&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,t):new Uint8Array(e,t,r)).__proto__=o.prototype,n}function g(e){if(o.isBuffer(e)){var t=0|m(e.length),r=a(t);return 0===r.length||e.copy(r,0,0,t),r}return void 0!==e.length?"number"!=typeof e.length||X(e.length)?a(0):f(e):"Buffer"===e.type&&Array.isArray(e.data)?f(e.data):void 0}function m(e){if(e>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|e}function y(e){return+e!=e&&(e=0),o.alloc(+e)}function v(e,t){if(o.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||Q(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;for(var s=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return H(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return W(e).length;default:if(s)return n?-1:H(e).length;t=(""+t).toLowerCase(),s=!0}}function b(e,t,r){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return M(this,t,r);case"utf8":case"utf-8":return L(this,t,r);case"ascii":return O(this,t,r);case"latin1":case"binary":return P(this,t,r);case"base64":return R(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return F(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function w(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function E(e,t,r,n,s){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),X(r=+r)&&(r=s?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(s)return-1;r=e.length-1}else if(r<0){if(!s)return-1;r=0}if("string"==typeof t&&(t=o.from(t,n)),o.isBuffer(t))return 0===t.length?-1:S(e,t,r,n,s);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):S(e,[t],r,n,s);throw new TypeError("val must be string, number or Buffer")}function S(e,t,r,n,s){var i,a=1,o=e.length,l=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,o/=2,l/=2,r/=2}function c(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(s){var d=-1;for(i=r;i<o;i++)if(c(e,i)===c(t,-1===d?0:i-d)){if(-1===d&&(d=i),i-d+1===l)return d*a}else-1!==d&&(i-=i-d),d=-1}else for(r+l>o&&(r=o-l),i=r;i>=0;i--){for(var u=!0,h=0;h<l;h++)if(c(e,i+h)!==c(t,h)){u=!1;break}if(u)return i}return-1}function T(e,t,r,n){r=Number(r)||0;var s=e.length-r;n?(n=Number(n))>s&&(n=s):n=s;var i=t.length;n>i/2&&(n=i/2);for(var a=0;a<n;++a){var o=parseInt(t.substr(2*a,2),16);if(X(o))return a;e[r+a]=o}return a}function C(e,t,r,n){return Y(H(t,e.length-r),e,r,n)}function k(e,t,r,n){return Y(V(t),e,r,n)}function A(e,t,r,n){return k(e,t,r,n)}function I(e,t,r,n){return Y(W(t),e,r,n)}function _(e,t,r,n){return Y(z(t,e.length-r),e,r,n)}function R(e,r,n){return 0===r&&n===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(r,n))}function L(e,t,r){r=Math.min(e.length,r);for(var n=[],s=t;s<r;){var i,a,o,l,c=e[s],d=null,u=c>239?4:c>223?3:c>191?2:1;if(s+u<=r)switch(u){case 1:c<128&&(d=c);break;case 2:128==(192&(i=e[s+1]))&&(l=(31&c)<<6|63&i)>127&&(d=l);break;case 3:i=e[s+1],a=e[s+2],128==(192&i)&&128==(192&a)&&(l=(15&c)<<12|(63&i)<<6|63&a)>2047&&(l<55296||l>57343)&&(d=l);break;case 4:i=e[s+1],a=e[s+2],o=e[s+3],128==(192&i)&&128==(192&a)&&128==(192&o)&&(l=(15&c)<<18|(63&i)<<12|(63&a)<<6|63&o)>65535&&l<1114112&&(d=l)}null===d?(d=65533,u=1):d>65535&&(d-=65536,n.push(d>>>10&1023|55296),d=56320|1023&d),n.push(d),s+=u}return x(n)}r.kMaxLength=s,o.TYPED_ARRAY_SUPPORT=i(),o.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&o[Symbol.species]===o&&Object.defineProperty(o,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),o.poolSize=8192,o.from=function(e,t,r){return l(e,t,r)},o.prototype.__proto__=Uint8Array.prototype,o.__proto__=Uint8Array,o.alloc=function(e,t,r){return d(e,t,r)},o.allocUnsafe=function(e){return u(e)},o.allocUnsafeSlow=function(e){return u(e)},o.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==o.prototype},o.compare=function(e,t){if(Q(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),Q(t,Uint8Array)&&(t=o.from(t,t.offset,t.byteLength)),!o.isBuffer(e)||!o.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var r=e.length,n=t.length,s=0,i=Math.min(r,n);s<i;++s)if(e[s]!==t[s]){r=e[s],n=t[s];break}return r<n?-1:n<r?1:0},o.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},o.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return o.alloc(0);var r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;var n=o.allocUnsafe(t),s=0;for(r=0;r<e.length;++r){var i=e[r];if(Q(i,Uint8Array)&&(i=o.from(i)),!o.isBuffer(i))throw new TypeError('"list" argument must be an Array of Buffers');i.copy(n,s),s+=i.length}return n},o.byteLength=v,o.prototype._isBuffer=!0,o.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)w(this,t,t+1);return this},o.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)w(this,t,t+3),w(this,t+1,t+2);return this},o.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)w(this,t,t+7),w(this,t+1,t+6),w(this,t+2,t+5),w(this,t+3,t+4);return this},o.prototype.toString=function(){var e=this.length;return 0===e?"":0===arguments.length?L(this,0,e):b.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(e){if(!o.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===o.compare(this,e)},o.prototype.inspect=function(){var e="",t=r.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),"<Buffer "+e+">"},o.prototype.compare=function(e,t,r,n,s){if(Q(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),!o.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===s&&(s=this.length),t<0||r>e.length||n<0||s>this.length)throw new RangeError("out of range index");if(n>=s&&t>=r)return 0;if(n>=s)return-1;if(t>=r)return 1;if(this===e)return 0;for(var i=(s>>>=0)-(n>>>=0),a=(r>>>=0)-(t>>>=0),l=Math.min(i,a),c=this.slice(n,s),d=e.slice(t,r),u=0;u<l;++u)if(c[u]!==d[u]){i=c[u],a=d[u];break}return i<a?-1:a<i?1:0},o.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},o.prototype.indexOf=function(e,t,r){return E(this,e,t,r,!0)},o.prototype.lastIndexOf=function(e,t,r){return E(this,e,t,r,!1)},o.prototype.write=function(e,t,r,n){if(void 0===t)n="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)n=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var s=this.length-t;if((void 0===r||r>s)&&(r=s),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var i=!1;;)switch(n){case"hex":return T(this,e,t,r);case"utf8":case"utf-8":return C(this,e,t,r);case"ascii":return k(this,e,t,r);case"latin1":case"binary":return A(this,e,t,r);case"base64":return I(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _(this,e,t,r);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var D=4096;function x(e){var t=e.length;if(t<=D)return String.fromCharCode.apply(String,e);for(var r="",n=0;n<t;)r+=String.fromCharCode.apply(String,e.slice(n,n+=D));return r}function O(e,t,r){var n="";r=Math.min(e.length,r);for(var s=t;s<r;++s)n+=String.fromCharCode(127&e[s]);return n}function P(e,t,r){var n="";r=Math.min(e.length,r);for(var s=t;s<r;++s)n+=String.fromCharCode(e[s]);return n}function M(e,t,r){var n=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>n)&&(r=n);for(var s="",i=t;i<r;++i)s+=G(e[i]);return s}function F(e,t,r){for(var n=e.slice(t,r),s="",i=0;i<n.length;i+=2)s+=String.fromCharCode(n[i]+256*n[i+1]);return s}function U(e,t,r){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}function N(e,t,r,n,s,i){if(!o.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>s||t<i)throw new RangeError('"value" argument is out of bounds');if(r+n>e.length)throw new RangeError("Index out of range")}function B(e,t,r,n,s,i){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function j(e,t,r,s,i){return t=+t,r>>>=0,i||B(e,t,r,4),n.write(e,t,r,s,23,4),r+4}function $(e,t,r,s,i){return t=+t,r>>>=0,i||B(e,t,r,8),n.write(e,t,r,s,52,8),r+8}o.prototype.slice=function(e,t){var r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e);var n=this.subarray(e,t);return n.__proto__=o.prototype,n},o.prototype.readUIntLE=function(e,t,r){e>>>=0,t>>>=0,r||U(e,t,this.length);for(var n=this[e],s=1,i=0;++i<t&&(s*=256);)n+=this[e+i]*s;return n},o.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||U(e,t,this.length);for(var n=this[e+--t],s=1;t>0&&(s*=256);)n+=this[e+--t]*s;return n},o.prototype.readUInt8=function(e,t){return e>>>=0,t||U(e,1,this.length),this[e]},o.prototype.readUInt16LE=function(e,t){return e>>>=0,t||U(e,2,this.length),this[e]|this[e+1]<<8},o.prototype.readUInt16BE=function(e,t){return e>>>=0,t||U(e,2,this.length),this[e]<<8|this[e+1]},o.prototype.readUInt32LE=function(e,t){return e>>>=0,t||U(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},o.prototype.readUInt32BE=function(e,t){return e>>>=0,t||U(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},o.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||U(e,t,this.length);for(var n=this[e],s=1,i=0;++i<t&&(s*=256);)n+=this[e+i]*s;return n>=(s*=128)&&(n-=Math.pow(2,8*t)),n},o.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||U(e,t,this.length);for(var n=t,s=1,i=this[e+--n];n>0&&(s*=256);)i+=this[e+--n]*s;return i>=(s*=128)&&(i-=Math.pow(2,8*t)),i},o.prototype.readInt8=function(e,t){return e>>>=0,t||U(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},o.prototype.readInt16LE=function(e,t){e>>>=0,t||U(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},o.prototype.readInt16BE=function(e,t){e>>>=0,t||U(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},o.prototype.readInt32LE=function(e,t){return e>>>=0,t||U(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},o.prototype.readInt32BE=function(e,t){return e>>>=0,t||U(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},o.prototype.readFloatLE=function(e,t){return e>>>=0,t||U(e,4,this.length),n.read(this,e,!0,23,4)},o.prototype.readFloatBE=function(e,t){return e>>>=0,t||U(e,4,this.length),n.read(this,e,!1,23,4)},o.prototype.readDoubleLE=function(e,t){return e>>>=0,t||U(e,8,this.length),n.read(this,e,!0,52,8)},o.prototype.readDoubleBE=function(e,t){return e>>>=0,t||U(e,8,this.length),n.read(this,e,!1,52,8)},o.prototype.writeUIntLE=function(e,t,r,n){e=+e,t>>>=0,r>>>=0,n||N(this,e,t,r,Math.pow(2,8*r)-1,0);var s=1,i=0;for(this[t]=255&e;++i<r&&(s*=256);)this[t+i]=e/s&255;return t+r},o.prototype.writeUIntBE=function(e,t,r,n){e=+e,t>>>=0,r>>>=0,n||N(this,e,t,r,Math.pow(2,8*r)-1,0);var s=r-1,i=1;for(this[t+s]=255&e;--s>=0&&(i*=256);)this[t+s]=e/i&255;return t+r},o.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,1,255,0),this[t]=255&e,t+1},o.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},o.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},o.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},o.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},o.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var s=Math.pow(2,8*r-1);N(this,e,t,r,s-1,-s)}var i=0,a=1,o=0;for(this[t]=255&e;++i<r&&(a*=256);)e<0&&0===o&&0!==this[t+i-1]&&(o=1),this[t+i]=(e/a>>0)-o&255;return t+r},o.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var s=Math.pow(2,8*r-1);N(this,e,t,r,s-1,-s)}var i=r-1,a=1,o=0;for(this[t+i]=255&e;--i>=0&&(a*=256);)e<0&&0===o&&0!==this[t+i+1]&&(o=1),this[t+i]=(e/a>>0)-o&255;return t+r},o.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},o.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},o.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},o.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},o.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||N(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},o.prototype.writeFloatLE=function(e,t,r){return j(this,e,t,!0,r)},o.prototype.writeFloatBE=function(e,t,r){return j(this,e,t,!1,r)},o.prototype.writeDoubleLE=function(e,t,r){return $(this,e,t,!0,r)},o.prototype.writeDoubleBE=function(e,t,r){return $(this,e,t,!1,r)},o.prototype.copy=function(e,t,r,n){if(!o.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n<r&&(n=r),n===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t<n-r&&(n=e.length-t+r);var s=n-r;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,r,n);else if(this===e&&r<t&&t<n)for(var i=s-1;i>=0;--i)e[i+t]=this[i+r];else Uint8Array.prototype.set.call(e,this.subarray(r,n),t);return s},o.prototype.fill=function(e,t,r,n){if("string"==typeof e){if("string"==typeof t?(n=t,t=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!o.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===e.length){var s=e.charCodeAt(0);("utf8"===n&&s<128||"latin1"===n)&&(e=s)}}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;var i;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(i=t;i<r;++i)this[i]=e;else{var a=o.isBuffer(e)?e:o.from(e,n),l=a.length;if(0===l)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(i=0;i<r-t;++i)this[i+t]=a[i%l]}return this};var q=/[^+/0-9A-Za-z-_]/g;function K(e){if((e=(e=e.split("=")[0]).trim().replace(q,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}function G(e){return e<16?"0"+e.toString(16):e.toString(16)}function H(e,t){var r;t=t||1/0;for(var n=e.length,s=null,i=[],a=0;a<n;++a){if((r=e.charCodeAt(a))>55295&&r<57344){if(!s){if(r>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&i.push(239,191,189);continue}s=r;continue}if(r<56320){(t-=3)>-1&&i.push(239,191,189),s=r;continue}r=65536+(s-55296<<10|r-56320)}else s&&(t-=3)>-1&&i.push(239,191,189);if(s=null,r<128){if((t-=1)<0)break;i.push(r)}else if(r<2048){if((t-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function V(e){for(var t=[],r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}function z(e,t){for(var r,n,s,i=[],a=0;a<e.length&&!((t-=2)<0);++a)n=(r=e.charCodeAt(a))>>8,s=r%256,i.push(s),i.push(n);return i}function W(e){return t.toByteArray(K(e))}function Y(e,t,r,n){for(var s=0;s<n&&!(s+r>=t.length||s>=e.length);++s)t[s+r]=e[s];return s}function Q(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function X(e){return e!=e}}).call(this)}).call(this,e("buffer").Buffer)},{"base64-js":13,buffer:17,ieee754:23}],18:[function(e,t,r){(function(n){(function(){function s(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))}function i(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;e.splice(1,0,r,"color: inherit");let n=0,s=0;e[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(s=n))})),e.splice(s,0,r)}function a(e){try{e?r.storage.setItem("debug",e):r.storage.removeItem("debug")}catch(e){}}function o(){let e;try{e=r.storage.getItem("debug")}catch(e){}return!e&&void 0!==n&&"env"in n&&(e=n.env.DEBUG),e}function l(){try{return localStorage}catch(e){}}r.formatArgs=i,r.save=a,r.load=o,r.useColors=s,r.storage=l(),r.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),r.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],r.log=console.debug||console.log||(()=>{}),t.exports=e("./common")(r);const{formatters:c}=t.exports;c.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}).call(this)}).call(this,e("_process"))},{"./common":19,_process:50}],19:[function(e,t,r){function n(t){function r(e){let t=0;for(let r=0;r<e.length;r++)t=(t<<5)-t+e.charCodeAt(r),t|=0;return n.colors[Math.abs(t)%n.colors.length]}function n(e){let t,r,i,a=null;function o(...e){if(!o.enabled)return;const r=o,s=Number(new Date),i=s-(t||s);r.diff=i,r.prev=t,r.curr=s,t=s,e[0]=n.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((t,s)=>{if("%%"===t)return"%";a++;const i=n.formatters[s];if("function"==typeof i){const n=e[a];t=i.call(r,n),e.splice(a,1),a--}return t})),n.formatArgs.call(r,e),(r.log||n.log).apply(r,e)}return o.namespace=e,o.useColors=n.useColors(),o.color=n.selectColor(e),o.extend=s,o.destroy=n.destroy,Object.defineProperty(o,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(r!==n.namespaces&&(r=n.namespaces,i=n.enabled(e)),i),set:e=>{a=e}}),"function"==typeof n.init&&n.init(o),o}function s(e,t){const r=n(this.namespace+(void 0===t?":":t)+e);return r.log=this.log,r}function i(e){let t;n.save(e),n.namespaces=e,n.names=[],n.skips=[];const r=("string"==typeof e?e:"").split(/[\s,]+/),s=r.length;for(t=0;t<s;t++)r[t]&&("-"===(e=r[t].replace(/\*/g,".*?"))[0]?n.skips.push(new RegExp("^"+e.substr(1)+"$")):n.names.push(new RegExp("^"+e+"$")))}function a(){const e=[...n.names.map(l),...n.skips.map(l).map((e=>"-"+e))].join(",");return n.enable(""),e}function o(e){if("*"===e[e.length-1])return!0;let t,r;for(t=0,r=n.skips.length;t<r;t++)if(n.skips[t].test(e))return!1;for(t=0,r=n.names.length;t<r;t++)if(n.names[t].test(e))return!0;return!1}function l(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}function c(e){return e instanceof Error?e.stack||e.message:e}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.debug=n,n.default=n,n.coerce=c,n.disable=a,n.enable=i,n.enabled=o,n.humanize=e("ms"),n.destroy=d,Object.keys(t).forEach((e=>{n[e]=t[e]})),n.names=[],n.skips=[],n.formatters={},n.selectColor=r,n.enable(n.load()),n}t.exports=n},{ms:45}],20:[function(e,t,r){(function(r,n){(function(){var s=e("readable-stream"),i=e("end-of-stream"),a=e("inherits"),o=e("stream-shift"),l=n.from&&n.from!==Uint8Array.from?n.from([0]):new n([0]),c=function(e,t){e._corked?e.once("uncork",t):t()},d=function(e,t){e._autoDestroy&&e.destroy(t)},u=function(e,t){return function(r){r?d(e,"premature close"===r.message?null:r):t&&!e._ended&&e.end()}},h=function(e,t){return e?e._writableState&&e._writableState.finished?t():e._writableState?e.end(t):(e.end(),void t()):t()},f=function(){},p=function(e){return new s.Readable({objectMode:!0,highWaterMark:16}).wrap(e)},g=function(e,t,r){if(!(this instanceof g))return new g(e,t,r);s.Duplex.call(this,r),this._writable=null,this._readable=null,this._readable2=null,this._autoDestroy=!r||!1!==r.autoDestroy,this._forwardDestroy=!r||!1!==r.destroy,this._forwardEnd=!r||!1!==r.end,this._corked=1,this._ondrain=null,this._drained=!1,this._forwarding=!1,this._unwrite=null,this._unread=null,this._ended=!1,this.destroyed=!1,e&&this.setWritable(e),t&&this.setReadable(t)};a(g,s.Duplex),g.obj=function(e,t,r){return r||(r={}),r.objectMode=!0,r.highWaterMark=16,new g(e,t,r)},g.prototype.cork=function(){1==++this._corked&&this.emit("cork")},g.prototype.uncork=function(){this._corked&&0==--this._corked&&this.emit("uncork")},g.prototype.setWritable=function(e){if(this._unwrite&&this._unwrite(),this.destroyed)e&&e.destroy&&e.destroy();else if(null!==e&&!1!==e){var t=this,n=i(e,{writable:!0,readable:!1},u(this,this._forwardEnd)),s=function(){var e=t._ondrain;t._ondrain=null,e&&e()},a=function(){t._writable.removeListener("drain",s),n()};this._unwrite&&r.nextTick(s),this._writable=e,this._writable.on("drain",s),this._unwrite=a,this.uncork()}else this.end()},g.prototype.setReadable=function(e){if(this._unread&&this._unread(),this.destroyed)e&&e.destroy&&e.destroy();else{if(null===e||!1===e)return this.push(null),void this.resume();var t=this,r=i(e,{writable:!1,readable:!0},u(this)),n=function(){t._forward()},s=function(){t.push(null)},a=function(){t._readable2.removeListener("readable",n),t._readable2.removeListener("end",s),r()};this._drained=!0,this._readable=e,this._readable2=e._readableState?e:p(e),this._readable2.on("readable",n),this._readable2.on("end",s),this._unread=a,this._forward()}},g.prototype._read=function(){this._drained=!0,this._forward()},g.prototype._forward=function(){if(!this._forwarding&&this._readable2&&this._drained){var e;for(this._forwarding=!0;this._drained&&null!==(e=o(this._readable2));)this.destroyed||(this._drained=this.push(e));this._forwarding=!1}},g.prototype.destroy=function(e,t){if(t||(t=f),this.destroyed)return t(null);this.destroyed=!0;var n=this;r.nextTick((function(){n._destroy(e),t(null)}))},g.prototype._destroy=function(e){if(e){var t=this._ondrain;this._ondrain=null,t?t(e):this.emit("error",e)}this._forwardDestroy&&(this._readable&&this._readable.destroy&&this._readable.destroy(),this._writable&&this._writable.destroy&&this._writable.destroy()),this.emit("close")},g.prototype._write=function(e,t,r){if(!this.destroyed)return this._corked?c(this,this._write.bind(this,e,t,r)):e===l?this._finish(r):this._writable?void(!1===this._writable.write(e)?this._ondrain=r:this.destroyed||r()):r()},g.prototype._finish=function(e){var t=this;this.emit("preend"),c(this,(function(){h(t._forwardEnd&&t._writable,(function(){!1===t._writableState.prefinished&&(t._writableState.prefinished=!0),t.emit("prefinish"),c(t,e)}))}))},g.prototype.end=function(e,t,r){return"function"==typeof e?this.end(null,null,e):"function"==typeof t?this.end(e,null,t):(this._ended=!0,e&&this.write(e),this._writableState.ending||this._writableState.destroyed||this.write(l),s.Writable.prototype.end.call(this,r))},t.exports=g}).call(this)}).call(this,e("_process"),e("buffer").Buffer)},{_process:50,buffer:17,"end-of-stream":21,inherits:24,"readable-stream":69,"stream-shift":74}],21:[function(e,t,r){(function(r){(function(){var n=e("once"),s=function(){},i=function(e){return e.setHeader&&"function"==typeof e.abort},a=function(e){return e.stdio&&Array.isArray(e.stdio)&&3===e.stdio.length},o=function(e,t,l){if("function"==typeof t)return o(e,null,t);t||(t={}),l=n(l||s);var c=e._writableState,d=e._readableState,u=t.readable||!1!==t.readable&&e.readable,h=t.writable||!1!==t.writable&&e.writable,f=!1,p=function(){e.writable||g()},g=function(){h=!1,u||l.call(e)},m=function(){u=!1,h||l.call(e)},y=function(t){l.call(e,t?new Error("exited with error code: "+t):null)},v=function(t){l.call(e,t)},b=function(){r.nextTick(w)},w=function(){if(!f)return(!u||d&&d.ended&&!d.destroyed)&&(!h||c&&c.ended&&!c.destroyed)?void 0:l.call(e,new Error("premature close"))},E=function(){e.req.on("finish",g)};return i(e)?(e.on("complete",g),e.on("abort",b),e.req?E():e.on("request",E)):h&&!c&&(e.on("end",p),e.on("close",p)),a(e)&&e.on("exit",y),e.on("end",m),e.on("finish",g),!1!==t.error&&e.on("error",v),e.on("close",b),function(){f=!0,e.removeListener("complete",g),e.removeListener("abort",b),e.removeListener("request",E),e.req&&e.req.removeListener("finish",g),e.removeListener("end",p),e.removeListener("close",p),e.removeListener("finish",g),e.removeListener("exit",y),e.removeListener("end",m),e.removeListener("error",v),e.removeListener("close",b)}};t.exports=o}).call(this)}).call(this,e("_process"))},{_process:50,once:48}],22:[function(e,t,r){var n=Object.create||C,s=Object.keys||k,i=Function.prototype.bind||A;function a(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=n(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}t.exports=a,a.EventEmitter=a,a.prototype._events=void 0,a.prototype._maxListeners=void 0;var o,l=10;try{var c={};Object.defineProperty&&Object.defineProperty(c,"x",{value:0}),o=0===c.x}catch(e){o=!1}function d(e){return void 0===e._maxListeners?a.defaultMaxListeners:e._maxListeners}function u(e,t,r){if(t)e.call(r);else for(var n=e.length,s=S(e,n),i=0;i<n;++i)s[i].call(r)}function h(e,t,r,n){if(t)e.call(r,n);else for(var s=e.length,i=S(e,s),a=0;a<s;++a)i[a].call(r,n)}function f(e,t,r,n,s){if(t)e.call(r,n,s);else for(var i=e.length,a=S(e,i),o=0;o<i;++o)a[o].call(r,n,s)}function p(e,t,r,n,s,i){if(t)e.call(r,n,s,i);else for(var a=e.length,o=S(e,a),l=0;l<a;++l)o[l].call(r,n,s,i)}function g(e,t,r,n){if(t)e.apply(r,n);else for(var s=e.length,i=S(e,s),a=0;a<s;++a)i[a].apply(r,n)}function m(e,t,r,s){var i,a,o;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((a=e._events)?(a.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),a=e._events),o=a[t]):(a=e._events=n(null),e._eventsCount=0),o){if("function"==typeof o?o=a[t]=s?[r,o]:[o,r]:s?o.unshift(r):o.push(r),!o.warned&&(i=d(e))&&i>0&&o.length>i){o.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+o.length+' "'+String(t)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=o.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",l.name,l.message)}}else o=a[t]=r,++e._eventsCount;return e}function y(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var e=new Array(arguments.length),t=0;t<e.length;++t)e[t]=arguments[t];this.listener.apply(this.target,e)}}function v(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},s=i.call(y,n);return s.listener=r,n.wrapFn=s,s}function b(e,t,r){var n=e._events;if(!n)return[];var s=n[t];return s?"function"==typeof s?r?[s.listener||s]:[s]:r?T(s):S(s,s.length):[]}function w(e){var t=this._events;if(t){var r=t[e];if("function"==typeof r)return 1;if(r)return r.length}return 0}function E(e,t){for(var r=t,n=r+1,s=e.length;n<s;r+=1,n+=1)e[r]=e[n];e.pop()}function S(e,t){for(var r=new Array(t),n=0;n<t;++n)r[n]=e[n];return r}function T(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}function C(e){var t=function(){};return t.prototype=e,new t}function k(e){for(var t in e)Object.prototype.hasOwnProperty.call(e,t);return t}function A(e){var t=this;return function(){return t.apply(e,arguments)}}o?Object.defineProperty(a,"defaultMaxListeners",{enumerable:!0,get:function(){return l},set:function(e){if("number"!=typeof e||e<0||e!=e)throw new TypeError('"defaultMaxListeners" must be a positive number');l=e}}):a.defaultMaxListeners=l,a.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},a.prototype.getMaxListeners=function(){return d(this)},a.prototype.emit=function(e){var t,r,n,s,i,a,o="error"===e;if(a=this._events)o=o&&null==a.error;else if(!o)return!1;if(o){if(arguments.length>1&&(t=arguments[1]),t instanceof Error)throw t;var l=new Error('Unhandled "error" event. ('+t+")");throw l.context=t,l}if(!(r=a[e]))return!1;var c="function"==typeof r;switch(n=arguments.length){case 1:u(r,c,this);break;case 2:h(r,c,this,arguments[1]);break;case 3:f(r,c,this,arguments[1],arguments[2]);break;case 4:p(r,c,this,arguments[1],arguments[2],arguments[3]);break;default:for(s=new Array(n-1),i=1;i<n;i++)s[i-1]=arguments[i];g(r,c,this,s)}return!0},a.prototype.addListener=function(e,t){return m(this,e,t,!1)},a.prototype.on=a.prototype.addListener,a.prototype.prependListener=function(e,t){return m(this,e,t,!0)},a.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,v(this,e,t)),this},a.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,v(this,e,t)),this},a.prototype.removeListener=function(e,t){var r,s,i,a,o;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(s=this._events))return this;if(!(r=s[e]))return this;if(r===t||r.listener===t)0==--this._eventsCount?this._events=n(null):(delete s[e],s.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(i=-1,a=r.length-1;a>=0;a--)if(r[a]===t||r[a].listener===t){o=r[a].listener,i=a;break}if(i<0)return this;0===i?r.shift():E(r,i),1===r.length&&(s[e]=r[0]),s.removeListener&&this.emit("removeListener",e,o||t)}return this},a.prototype.removeAllListeners=function(e){var t,r,i;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=n(null),this._eventsCount=0):r[e]&&(0==--this._eventsCount?this._events=n(null):delete r[e]),this;if(0===arguments.length){var a,o=s(r);for(i=0;i<o.length;++i)"removeListener"!==(a=o[i])&&this.removeAllListeners(a);return this.removeAllListeners("removeListener"),this._events=n(null),this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(t)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this},a.prototype.listeners=function(e){return b(this,e,!0)},a.prototype.rawListeners=function(e){return b(this,e,!1)},a.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):w.call(e,t)},a.prototype.listenerCount=w,a.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}},{}],23:[function(e,t,r){
3
3
  /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
4
4
  r.read=function(e,t,r,n,s){var i,a,o=8*s-n-1,l=(1<<o)-1,c=l>>1,d=-7,u=r?s-1:0,h=r?-1:1,f=e[t+u];for(u+=h,i=f&(1<<-d)-1,f>>=-d,d+=o;d>0;i=256*i+e[t+u],u+=h,d-=8);for(a=i&(1<<-d)-1,i>>=-d,d+=n;d>0;a=256*a+e[t+u],u+=h,d-=8);if(0===i)i=1-c;else{if(i===l)return a?NaN:1/0*(f?-1:1);a+=Math.pow(2,n),i-=c}return(f?-1:1)*a*Math.pow(2,i-n)},r.write=function(e,t,r,n,s,i){var a,o,l,c=8*i-s-1,d=(1<<c)-1,u=d>>1,h=23===s?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:i-1,p=n?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(o=isNaN(t)?1:0,a=d):(a=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-a))<1&&(a--,l*=2),(t+=a+u>=1?h/l:h*Math.pow(2,1-u))*l>=2&&(a++,l/=2),a+u>=d?(o=0,a=d):a+u>=1?(o=(t*l-1)*Math.pow(2,s),a+=u):(o=t*Math.pow(2,u-1)*Math.pow(2,s),a=0));s>=8;e[r+f]=255&o,f+=p,o/=256,s-=8);for(a=a<<s|o,c+=s;c>0;e[r+f]=255&a,f+=p,a/=256,c-=8);e[r+f-p]|=128*g}},{}],24:[function(e,t,r){"function"==typeof Object.create?t.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:t.exports=function(e,t){if(t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}},{}],25:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0});var n=function(){function e(e,t){this.color=!0,this.key=void 0,this.value=void 0,this.parent=void 0,this.brother=void 0,this.leftChild=void 0,this.rightChild=void 0,this.key=e,this.value=t}return e.prototype.rotateLeft=function(){var e=this.parent,t=this.brother,r=this.leftChild,n=this.rightChild;if(!n)throw new Error("unknown error");var s=n.leftChild,i=n.rightChild;return e&&(e.leftChild===this?e.leftChild=n:e.rightChild===this&&(e.rightChild=n)),n.parent=e,n.brother=t,n.leftChild=this,n.rightChild=i,t&&(t.brother=n),this.parent=n,this.brother=i,this.leftChild=r,this.rightChild=s,i&&(i.parent=n,i.brother=this),r&&(r.parent=this,r.brother=s),s&&(s.parent=this,s.brother=r),n},e.prototype.rotateRight=function(){var e=this.parent,t=this.brother,r=this.leftChild;if(!r)throw new Error("unknown error");var n=this.rightChild,s=r.leftChild,i=r.rightChild;return e&&(e.leftChild===this?e.leftChild=r:e.rightChild===this&&(e.rightChild=r)),r.parent=e,r.brother=t,r.leftChild=s,r.rightChild=this,t&&(t.brother=r),s&&(s.parent=r,s.brother=this),this.parent=r,this.brother=s,this.leftChild=i,this.rightChild=n,i&&(i.parent=this,i.brother=n),n&&(n.parent=this,n.brother=i),r},e.prototype.remove=function(){if(this.leftChild||this.rightChild)throw new Error("can only remove leaf node");this.parent&&(this===this.parent.leftChild?this.parent.leftChild=void 0:this===this.parent.rightChild&&(this.parent.rightChild=void 0)),this.brother&&(this.brother.brother=void 0),this.key=void 0,this.value=void 0,this.parent=void 0,this.brother=void 0},e.TreeNodeColorType={red:!0,black:!1},e}();Object.freeze(n),r.default=n},{}],26:[function(e,t,r){var n=this&&this.__generator||function(e,t){var r,n,s,i,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function o(e){return function(t){return l([e,t])}}function l(i){if(r)throw new TypeError("Generator is already executing.");for(;a;)try{if(r=1,n&&(s=2&i[0]?n.return:i[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,i[1])).done)return s;switch(n=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,n=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((s=(s=a.trys).length>0&&s[s.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){a.label=i[1];break}if(6===i[0]&&a.label<s[1]){a.label=s[1],s=i;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(i);break}s[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],n=0}finally{r=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}};function s(e){var t=this;void 0===e&&(e=[]);var r=[],i=0,a=0,o=0,l=0,c=0,d=0;this.size=function(){return d},this.empty=function(){return 0===d},this.clear=function(){i=o=a=l=c=d=0,h.call(this,s.bucketSize),d=0},this.front=function(){return r[i][a]},this.back=function(){return r[o][l]},this.forEach=function(e){if(!this.empty()){var t=0;if(i!==o){for(c=a;c<s.bucketSize;++c)e(r[i][c],t++);for(c=i+1;c<o;++c)for(var n=0;n<s.bucketSize;++n)e(r[c][n],t++);for(c=0;c<=l;++c)e(r[o][c],t++)}else for(var c=a;c<=l;++c)e(r[i][c],t++)}};var u=function(e){var t=i*s.bucketSize+a,r=t+e,n=o*s.bucketSize+l;if(r<t||r>n)throw new Error("pos should more than 0 and less than queue's size");return{curNodeBucketIndex:Math.floor(r/s.bucketSize),curNodePointerIndex:r%s.bucketSize}};this.getElementByPos=function(e){var t=u(e),n=t.curNodeBucketIndex,s=t.curNodePointerIndex;return r[n][s]},this.eraseElementByPos=function(e){var t=this;if(e<0||e>d)throw new Error("pos should more than 0 and less than queue's size");if(0===e)this.popFront();else if(e===this.size())this.popBack();else{for(var r=[],n=e+1;n<d;++n)r.push(this.getElementByPos(n));this.cut(e),this.popBack(),r.forEach((function(e){return t.pushBack(e)}))}},this.eraseElementByValue=function(e){if(!this.empty()){var t=[];this.forEach((function(r){r!==e&&t.push(r)}));for(var r=t.length,n=0;n<r;++n)this.setElementByPos(n,t[n]);this.cut(r-1)}};var h=function(e){for(var t=[],n=e*s.sigma,u=Math.max(Math.ceil(n/s.bucketSize),2),h=0;h<u;++h)t.push(new Array(s.bucketSize));var f=Math.ceil(e/s.bucketSize),p=Math.floor(u/2)-Math.floor(f/2),g=p,m=0;if(this.size())for(h=0;h<f;++h){for(var y=0;y<s.bucketSize;++y)if(t[p+h][y]=this.front(),this.popFront(),this.empty()){g=p+h,m=y;break}if(this.empty())break}r=t,i=p,a=0,o=g,l=m,c=u,d=e};this.pushBack=function(e){this.empty()||(o===c-1&&l===s.bucketSize-1&&h.call(this,this.size()),l<s.bucketSize-1?++l:o<c-1&&(++o,l=0)),++d,r[o][l]=e},this.popBack=function(){this.empty()||(1!==this.size()&&(l>0?--l:i<o&&(--o,l=s.bucketSize-1)),d>0&&--d)},this.setElementByPos=function(e,t){var n=u(e),s=n.curNodeBucketIndex,i=n.curNodePointerIndex;r[s][i]=t},this.insert=function(e,t,r){var n=this;if(void 0===r&&(r=1),0===e)for(;r--;)this.pushFront(t);else if(e===this.size())for(;r--;)this.pushBack(t);else{for(var s=[],i=e;i<d;++i)s.push(this.getElementByPos(i));for(this.cut(e-1),i=0;i<r;++i)this.pushBack(t);s.forEach((function(e){return n.pushBack(e)}))}},this.find=function(e){if(i===o){for(var t=a;t<=l;++t)if(r[i][t]===e)return!0;return!1}for(t=a;t<s.bucketSize;++t)if(r[i][t]===e)return!0;for(t=i+1;t<o;++t)for(var n=0;n<s.bucketSize;++n)if(r[t][n]===e)return!0;for(t=0;t<=l;++t)if(r[o][t]===e)return!0;return!1},this.reverse=function(){for(var e=0,t=d-1;e<t;){var r=this.getElementByPos(e);this.setElementByPos(e,this.getElementByPos(t)),this.setElementByPos(t,r),++e,--t}},this.unique=function(){if(!this.empty()){var e=[],t=this.front();this.forEach((function(r,n){0!==n&&r===t||(e.push(r),t=r)}));for(var r=0;r<d;++r)this.setElementByPos(r,e[r]);this.cut(e.length-1)}},this.sort=function(e){var t=[];this.forEach((function(e){t.push(e)})),t.sort(e);for(var r=0;r<d;++r)this.setElementByPos(r,t[r])},this.pushFront=function(e){this.empty()||(0===i&&0===a&&h.call(this,this.size()),a>0?--a:i>0&&(--i,a=s.bucketSize-1)),++d,r[i][a]=e},this.popFront=function(){this.empty()||(1!==this.size()&&(a<s.bucketSize-1?++a:i<o&&(++i,a=0)),d>0&&--d)},this.shrinkToFit=function(){var e=this,t=[];this.forEach((function(e){t.push(e)}));var n=t.length;r=[];for(var i=Math.ceil(n/s.bucketSize),a=0;a<i;++a)r.push(new Array(s.bucketSize));this.clear(),t.forEach((function(t){return e.pushBack(t)}))},this.cut=function(e){if(e<0)this.clear();else{var t=u(e),r=t.curNodeBucketIndex,n=t.curNodePointerIndex;o=r,l=n,d=e+1}},this[Symbol.iterator]=function(){return function(){var e,t;return n(this,(function(n){switch(n.label){case 0:if(0===d)return[2];if(i!==o)return[3,5];t=a,n.label=1;case 1:return t<=l?[4,r[i][t]]:[3,4];case 2:n.sent(),n.label=3;case 3:return++t,[3,1];case 4:return[2];case 5:t=a,n.label=6;case 6:return t<s.bucketSize?[4,r[i][t]]:[3,9];case 7:n.sent(),n.label=8;case 8:return++t,[3,6];case 9:t=i+1,n.label=10;case 10:if(!(t<o))return[3,15];e=0,n.label=11;case 11:return e<s.bucketSize?[4,r[t][e]]:[3,14];case 12:n.sent(),n.label=13;case 13:return++e,[3,11];case 14:return++t,[3,10];case 15:t=0,n.label=16;case 16:return t<=l?[4,r[o][t]]:[3,19];case 17:n.sent(),n.label=18;case 18:return++t,[3,16];case 19:return[2]}}))}()},function(){var n=s.bucketSize;e.size?n=e.size():e.length&&(n=e.length);var a=n*s.sigma;c=Math.ceil(a/s.bucketSize),c=Math.max(c,3);for(var l=0;l<c;++l)r.push(new Array(s.bucketSize));var d=Math.ceil(n/s.bucketSize);i=Math.floor(c/2)-Math.floor(d/2),o=i,e.forEach((function(e){return t.pushBack(e)}))}(),Object.freeze(this)}Object.defineProperty(r,"__esModule",{value:!0}),s.sigma=3,s.bucketSize=5e3,Object.freeze(s),r.default=s},{}],27:[function(e,t,r){var n=this&&this.__generator||function(e,t){var r,n,s,i,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function o(e){return function(t){return l([e,t])}}function l(i){if(r)throw new TypeError("Generator is already executing.");for(;a;)try{if(r=1,n&&(s=2&i[0]?n.return:i[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,i[1])).done)return s;switch(n=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,n=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((s=(s=a.trys).length>0&&s[s.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){a.label=i[1];break}if(6===i[0]&&a.label<s[1]){a.label=s[1],s=i;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(i);break}s[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],n=0}finally{r=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}},s=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(r,"__esModule",{value:!0});var i=e("../LinkList/LinkList"),a=e("../Map/Map");function o(e,t,r){var l=this;if(void 0===e&&(e=[]),void 0===t&&(t=o.initSize),r=r||function(e){var t,r,n=0,i="";if("number"==typeof e)n=((n=Math.floor(e))<<5)-n,n&=n;else{i="string"!=typeof e?JSON.stringify(e):e;try{for(var a=s(i),o=a.next();!o.done;o=a.next())n=(n<<5)-n+o.value.charCodeAt(0),n&=n}catch(e){t={error:e}}finally{try{o&&!o.done&&(r=a.return)&&r.call(a)}finally{if(t)throw t.error}}}return n^=n>>>16},0!=(t&t-1))throw new Error("initBucketNum must be 2 to the power of n");var c=0,d=[],u=Math.max(o.initSize,Math.min(o.maxSize,t));this.size=function(){return c},this.empty=function(){return 0===c},this.clear=function(){c=0,u=t,d=[]},this.forEach=function(e){var t=0;d.forEach((function(r){r.forEach((function(r){e(r,t++)}))}))};var h=function(e){if(!(e>=o.maxSize)){u=2*e;var t=[];d.forEach((function(n,s){if(!n.empty()){if(n instanceof i.default&&1===n.size()){var l=n.front(),c=l.key,h=l.value;t[r(c)&u-1]=new i.default([{key:c,value:h}])}else if(n instanceof a.default){var f=new i.default,p=new i.default;n.forEach((function(t){0==(r(t.key)&e)?f.pushBack(t):p.pushBack(t)})),f.size()>o.untreeifyThreshold?t[s]=new a.default(f):f.size()&&(t[s]=f),p.size()>o.untreeifyThreshold?t[s+e]=new a.default(p):p.size()&&(t[s+e]=p)}else{var g=new i.default,m=new i.default;n.forEach((function(t){0==(r(t.key)&e)?g.pushBack(t):m.pushBack(t)})),g.size()&&(t[s]=g),m.size()&&(t[s+e]=m)}d[s].clear()}})),d=t}};this.setElement=function(e,t){var n,l;if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(null!=t){var f=r(e)&u-1;if(d[f]){var p=d[f].size();if(d[f]instanceof i.default){try{for(var g=s(d[f]),m=g.next();!m.done;m=g.next()){var y=m.value;if(y.key===e)return void(y.value=t)}}catch(e){n={error:e}}finally{try{m&&!m.done&&(l=g.return)&&l.call(g)}finally{if(n)throw n.error}}d[f].pushBack({key:e,value:t}),d[f].size()>=o.treeifyThreshold&&(d[f]=new a.default(d[f]))}else d[f].setElement(e,t);var v=d[f].size();c+=v-p}else++c,d[f]=new i.default([{key:e,value:t}]);c>u*o.sigma&&h.call(this,u)}else this.eraseElementByKey(e)},this.getElementByKey=function(e){var t,n,i=r(e)&u-1;if(d[i]){if(d[i]instanceof a.default)return d[i].getElementByKey(e);try{for(var o=s(d[i]),l=o.next();!l.done;l=o.next()){var c=l.value;if(c.key===e)return c.value}}catch(e){t={error:e}}finally{try{l&&!l.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}}},this.eraseElementByKey=function(e){var t,n,l=r(e)&u-1;if(d[l]){var h=d[l].size();if(d[l]instanceof a.default)d[l].eraseElementByKey(e),d[l].size()<=o.untreeifyThreshold&&(d[l]=new i.default(d[l]));else{var f=-1;try{for(var p=s(d[l]),g=p.next();!g.done;g=p.next()){var m=g.value;if(++f,m.key===e){d[l].eraseElementByPos(f);break}}}catch(e){t={error:e}}finally{try{g&&!g.done&&(n=p.return)&&n.call(p)}finally{if(t)throw t.error}}}var y=d[l].size();c+=y-h}},this.find=function(e){var t,n,i=r(e)&u-1;if(!d[i])return!1;if(d[i]instanceof a.default)return d[i].find(e);try{for(var o=s(d[i]),l=o.next();!l.done;l=o.next())if(l.value.key===e)return!0}catch(e){t={error:e}}finally{try{l&&!l.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}return!1},this[Symbol.iterator]=function(){return function(){var e,t,r,i,a,o;return n(this,(function(n){switch(n.label){case 0:e=0,n.label=1;case 1:if(!(e<u))return[3,10];for(;e<u&&!d[e];)++e;if(e>=u)return[3,10];n.label=2;case 2:n.trys.push([2,7,8,9]),a=void 0,t=s(d[e]),r=t.next(),n.label=3;case 3:return r.done?[3,6]:[4,r.value];case 4:n.sent(),n.label=5;case 5:return r=t.next(),[3,3];case 6:return[3,9];case 7:return i=n.sent(),a={error:i},[3,9];case 8:try{r&&!r.done&&(o=t.return)&&o.call(t)}finally{if(a)throw a.error}return[7];case 9:return++e,[3,1];case 10:return[2]}}))}()},e.forEach((function(e){var t=e.key,r=e.value;return l.setElement(t,r)})),Object.freeze(this)}o.initSize=16,o.maxSize=1<<30,o.sigma=.75,o.treeifyThreshold=8,o.untreeifyThreshold=6,o.minTreeifySize=64,Object.freeze(o),r.default=o},{"../LinkList/LinkList":29,"../Map/Map":30}],28:[function(e,t,r){var n=this&&this.__generator||function(e,t){var r,n,s,i,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function o(e){return function(t){return l([e,t])}}function l(i){if(r)throw new TypeError("Generator is already executing.");for(;a;)try{if(r=1,n&&(s=2&i[0]?n.return:i[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,i[1])).done)return s;switch(n=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,n=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((s=(s=a.trys).length>0&&s[s.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){a.label=i[1];break}if(6===i[0]&&a.label<s[1]){a.label=s[1],s=i;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(i);break}s[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],n=0}finally{r=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}},s=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(r,"__esModule",{value:!0});var i=e("../Set/Set"),a=e("../LinkList/LinkList");function o(e,t,r){var l=this;if(void 0===e&&(e=[]),void 0===t&&(t=o.initSize),r=r||function(e){var t=0,r="";if("number"==typeof e)t=((t=Math.floor(e))<<5)-t,t&=t;else{r="string"!=typeof e?JSON.stringify(e):e;for(var n=0;n<r.length;n++)t=(t<<5)-t+r.charCodeAt(n),t&=t}return t^=t>>>16},0!=(t&t-1))throw new Error("initBucketNum must be 2 to the power of n");var c=0,d=[],u=Math.max(o.initSize,Math.min(o.maxSize,t));this.size=function(){return c},this.empty=function(){return 0===c},this.clear=function(){c=0,u=t,d=[]},this.forEach=function(e){var t=0;d.forEach((function(r){r.forEach((function(r){e(r,t++)}))}))};var h=function(e){if(!(e>=o.maxSize)){u=2*e;var t=[];d.forEach((function(n,s){if(!n.empty()){if(n instanceof a.default&&1===n.size()){var l=n.front();if(void 0===l)throw new Error("unknown error");t[r(l)&u-1]=new a.default([l])}else if(n instanceof i.default){var c=new a.default,h=new a.default;n.forEach((function(t){0==(r(t)&e)?c.pushBack(t):h.pushBack(t)})),c.size()>o.untreeifyThreshold?t[s]=new i.default(c):c.size()&&(t[s]=c),h.size()>o.untreeifyThreshold?t[s+e]=new i.default(h):h.size()&&(t[s+e]=h)}else{var f=new a.default,p=new a.default;n.forEach((function(t){0==(r(t)&e)?f.pushBack(t):p.pushBack(t)})),f.size()&&(t[s]=f),p.size()&&(t[s+e]=p)}d[s].clear()}})),d=t}};this.insert=function(e){if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");var t=r(e)&u-1;if(d[t]){var n=d[t].size();if(d[t]instanceof a.default){if(d[t].find(e))return;d[t].pushBack(e),d[t].size()>=o.treeifyThreshold&&(d[t]=new i.default(d[t]))}else d[t].insert(e);var s=d[t].size();c+=s-n}else d[t]=new a.default([e]),++c;c>u*o.sigma&&h.call(this,u)},this.eraseElementByValue=function(e){var t=r(e)&u-1;if(d[t]){var n=d[t].size();d[t].eraseElementByValue(e),d[t]instanceof i.default&&d[t].size()<=o.untreeifyThreshold&&(d[t]=new a.default(d[t]));var s=d[t].size();c+=s-n}},this.find=function(e){var t=r(e)&u-1;return!!d[t]&&d[t].find(e)},this[Symbol.iterator]=function(){return function(){var e,t,r,i,a,o;return n(this,(function(n){switch(n.label){case 0:e=0,n.label=1;case 1:if(!(e<u))return[3,10];for(;e<u&&!d[e];)++e;if(e>=u)return[3,10];n.label=2;case 2:n.trys.push([2,7,8,9]),a=void 0,t=s(d[e]),r=t.next(),n.label=3;case 3:return r.done?[3,6]:[4,r.value];case 4:n.sent(),n.label=5;case 5:return r=t.next(),[3,3];case 6:return[3,9];case 7:return i=n.sent(),a={error:i},[3,9];case 8:try{r&&!r.done&&(o=t.return)&&o.call(t)}finally{if(a)throw a.error}return[7];case 9:return++e,[3,1];case 10:return[2]}}))}()},e.forEach((function(e){return l.insert(e)})),Object.freeze(this)}o.initSize=16,o.maxSize=1<<30,o.sigma=.75,o.treeifyThreshold=8,o.untreeifyThreshold=6,o.minTreeifySize=64,Object.freeze(o),r.default=o},{"../LinkList/LinkList":29,"../Set/Set":33}],29:[function(e,t,r){var n=this&&this.__generator||function(e,t){var r,n,s,i,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function o(e){return function(t){return l([e,t])}}function l(i){if(r)throw new TypeError("Generator is already executing.");for(;a;)try{if(r=1,n&&(s=2&i[0]?n.return:i[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,i[1])).done)return s;switch(n=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,n=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((s=(s=a.trys).length>0&&s[s.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){a.label=i[1];break}if(6===i[0]&&a.label<s[1]){a.label=s[1],s=i;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(i);break}s[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],n=0}finally{r=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}};Object.defineProperty(r,"__esModule",{value:!0});var s=function(){function e(e){this.value=void 0,this.pre=void 0,this.next=void 0,this.value=e}return e}();function i(e){var t=this;void 0===e&&(e=[]);var r=0,i=void 0,a=void 0;this.size=function(){return r},this.empty=function(){return 0===r},this.clear=function(){i=a=void 0,r=0},this.front=function(){return null==i?void 0:i.value},this.back=function(){return null==a?void 0:a.value},this.forEach=function(e){for(var t=i,r=0;t;){if(void 0===t.value)throw new Error("unknown error");e(t.value,r++),t=t.next}},this.getElementByPos=function(e){if(e<0||e>=r)throw new Error("pos must more then 0 and less then the list length");for(var t=i;e--&&t;)t=t.next;if(!t||void 0===t.value)throw new Error("unknown error");return t.value},this.eraseElementByPos=function(e){if(e<0||e>=r)throw new Error("erase pos must more then 0 and less then the list length");if(0===e)this.popFront();else if(e===r-1)this.popBack();else{for(var t=i;e--;){if(!(null==t?void 0:t.next))throw new Error("unknown error");t=t.next}if(!t||!t.pre||!t.next)throw new Error("unknown error");var n=t.pre,s=t.next;s.pre=n,n.next=s,r>0&&--r}},this.eraseElementByValue=function(e){for(;i&&i.value===e;)this.popFront();for(;a&&a.value===e;)this.popBack();if(i)for(var t=i;t;){if(t.value===e){var n=t.pre,s=t.next;s&&(s.pre=n),n&&(n.next=s),r>0&&--r}t=t.next}},this.pushBack=function(e){if(null==e)throw new Error("you can't push null or undefined here");++r;var t=new s(e);a?(a.next=t,t.pre=a,a=t):i=a=t},this.popBack=function(){a&&(r>0&&--r,a&&(i===a?i=a=void 0:(a=a.pre)&&(a.next=void 0)))},this.setElementByPos=function(e,t){if(null==t)throw new Error("you can't set null or undefined here");if(e<0||e>=r)throw new Error("pos must more then 0 and less then the list length");for(var n=i;e--;){if(!n)throw new Error("unknown error");n=n.next}n&&(n.value=t)},this.insert=function(e,t,n){if(void 0===n&&(n=1),null==t)throw new Error("you can't insert null or undefined here");if(e<0||e>r)throw new Error("insert pos must more then 0 and less then or equal to the list length");if(n<0)throw new Error("insert size must more than 0");if(0===e)for(;n--;)this.pushFront(t);else if(e===r)for(;n--;)this.pushBack(t);else{for(var a=i,o=1;o<e;++o){if(!(null==a?void 0:a.next))throw new Error("unknown error");a=null==a?void 0:a.next}if(!a)throw new Error("unknown error");var l=a.next;for(r+=n;n--;)a.next=new s(t),a.next.pre=a,a=a.next;a.next=l,l&&(l.pre=a)}},this.find=function(e){for(var t=i;t;){if(t.value===e)return!0;t=t.next}return!1},this.reverse=function(){for(var e=i,t=a,n=0;e&&t&&2*n<r;){var s=e.value;e.value=t.value,t.value=s,e=e.next,t=t.pre,++n}},this.unique=function(){for(var e=i;e;){for(var t=e;t&&t.next&&t.value===t.next.value;)t=t.next,r>0&&--r;e.next=t.next,e.next&&(e.next.pre=e),e=e.next}},this.sort=function(e){var t=[];this.forEach((function(e){t.push(e)})),t.sort(e);var r=i;t.forEach((function(e){r&&(r.value=e,r=r.next)}))},this.pushFront=function(e){if(null==e)throw new Error("you can't push null or undefined here");++r;var t=new s(e);i?(t.next=i,i.pre=t,i=t):i=a=t},this.popFront=function(){i&&(r>0&&--r,i&&(i===a?i=a=void 0:(i=i.next)&&(i.pre=void 0)))},this.merge=function(e){var t=this,n=i;e.forEach((function(e){for(;n&&void 0!==n.value&&n.value<=e;)n=n.next;if(void 0===n)t.pushBack(e),n=a;else if(n===i)t.pushFront(e),n=i;else{++r;var o=n.pre;o&&(o.next=new s(e),o.next.pre=o,o.next.next=n,n&&(n.pre=o.next))}}))},this[Symbol.iterator]=function(){return function(){var e;return n(this,(function(t){switch(t.label){case 0:e=i,t.label=1;case 1:if(void 0===e)return[3,3];if(!e.value)throw new Error("unknown error");return[4,e.value];case 2:return t.sent(),e=e.next,[3,1];case 3:return[2]}}))}()},e.forEach((function(e){return t.pushBack(e)})),Object.freeze(this)}Object.freeze(i),r.default=i},{}],30:[function(e,t,r){var n=this&&this.__generator||function(e,t){var r,n,s,i,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function o(e){return function(t){return l([e,t])}}function l(i){if(r)throw new TypeError("Generator is already executing.");for(;a;)try{if(r=1,n&&(s=2&i[0]?n.return:i[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,i[1])).done)return s;switch(n=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,n=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((s=(s=a.trys).length>0&&s[s.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){a.label=i[1];break}if(6===i[0]&&a.label<s[1]){a.label=s[1],s=i;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(i);break}s[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],n=0}finally{r=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}},s=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(r,"__esModule",{value:!0});var i=e("../Base/TreeNode");function a(e,t){var r=this;void 0===e&&(e=[]),t=t||function(e,t){return e<t?-1:e>t?1:0};var a=0,o=new i.default;o.color=i.default.TreeNodeColorType.black,this.size=function(){return a},this.empty=function(){return 0===a},this.clear=function(){a=0,o.key=o.value=void 0,o.leftChild=o.rightChild=o.brother=void 0};var l=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.leftChild?l(e.leftChild):e},c=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.rightChild?c(e.rightChild):e};this.front=function(){if(!this.empty()){var e=l(o);if(void 0===e.key||void 0===e.value)throw new Error("unknown error");return{key:e.key,value:e.value}}},this.back=function(){if(!this.empty()){var e=c(o);if(void 0===e.key||void 0===e.value)throw new Error("unknown error");return{key:e.key,value:e.value}}},this.forEach=function(e){var t,r,n=0;try{for(var i=s(this),a=i.next();!a.done;a=i.next())e(a.value,n++)}catch(e){t={error:e}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}},this.getElementByPos=function(e){var t,r;if(e<0||e>=this.size())throw new Error("pos must more than 0 and less than set's size");var n=0;try{for(var i=s(this),a=i.next();!a.done;a=i.next()){var o=a.value;if(n===e)return o;++n}}catch(e){t={error:e}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}throw new Error("unknown Error")};var d=function(e,r){if(e&&void 0!==e.key&&void 0!==e.value){var n=t(e.key,r);return 0===n?{key:e.key,value:e.value}:n<0?d(e.rightChild,r):d(e.leftChild,r)||{key:e.key,value:e.value}}};this.lowerBound=function(e){return d(o,e)};var u=function(e,r){if(e&&void 0!==e.key&&void 0!==e.value)return t(e.key,r)<=0?u(e.rightChild,r):u(e.leftChild,r)||{key:e.key,value:e.value}};this.upperBound=function(e){return u(o,e)};var h=function(e,r){if(e&&void 0!==e.key&&void 0!==e.value){var n=t(e.key,r);return 0===n?{key:e.key,value:e.value}:n>0?h(e.leftChild,r):h(e.rightChild,r)||{key:e.key,value:e.value}}};this.reverseLowerBound=function(e){return h(o,e)};var f=function(e,r){if(e&&void 0!==e.key&&void 0!==e.value)return t(e.key,r)>=0?f(e.leftChild,r):f(e.rightChild,r)||{key:e.key,value:e.value}};this.reverseUpperBound=function(e){return f(o,e)};var p=function(e){var t=e.parent;if(!t){if(e===o)return;throw new Error("unknown error")}if(e.color!==i.default.TreeNodeColorType.red){var r=e.brother;if(!r)throw new Error("unknown error");if(e===t.leftChild)if(r.color===i.default.TreeNodeColorType.red){r.color=i.default.TreeNodeColorType.black,t.color=i.default.TreeNodeColorType.red;var n=t.rotateLeft();o===t&&(o=n),p(e)}else r.color===i.default.TreeNodeColorType.black&&(r.rightChild&&r.rightChild.color===i.default.TreeNodeColorType.red?(r.color=t.color,t.color=i.default.TreeNodeColorType.black,r.rightChild&&(r.rightChild.color=i.default.TreeNodeColorType.black),n=t.rotateLeft(),o===t&&(o=n),e.color=i.default.TreeNodeColorType.black):r.rightChild&&r.rightChild.color!==i.default.TreeNodeColorType.black||!r.leftChild||r.leftChild.color!==i.default.TreeNodeColorType.red?r.leftChild&&r.leftChild.color!==i.default.TreeNodeColorType.black||r.rightChild&&r.rightChild.color!==i.default.TreeNodeColorType.black||(r.color=i.default.TreeNodeColorType.red,p(t)):(r.color=i.default.TreeNodeColorType.red,r.leftChild&&(r.leftChild.color=i.default.TreeNodeColorType.black),n=r.rotateRight(),o===r&&(o=n),p(e)));else e===t.rightChild&&(r.color===i.default.TreeNodeColorType.red?(r.color=i.default.TreeNodeColorType.black,t.color=i.default.TreeNodeColorType.red,n=t.rotateRight(),o===t&&(o=n),p(e)):r.color===i.default.TreeNodeColorType.black&&(r.leftChild&&r.leftChild.color===i.default.TreeNodeColorType.red?(r.color=t.color,t.color=i.default.TreeNodeColorType.black,r.leftChild&&(r.leftChild.color=i.default.TreeNodeColorType.black),n=t.rotateRight(),o===t&&(o=n),e.color=i.default.TreeNodeColorType.black):r.leftChild&&r.leftChild.color!==i.default.TreeNodeColorType.black||!r.rightChild||r.rightChild.color!==i.default.TreeNodeColorType.red?r.leftChild&&r.leftChild.color!==i.default.TreeNodeColorType.black||r.rightChild&&r.rightChild.color!==i.default.TreeNodeColorType.black||(r.color=i.default.TreeNodeColorType.red,p(t)):(r.color=i.default.TreeNodeColorType.red,r.rightChild&&(r.rightChild.color=i.default.TreeNodeColorType.black),n=r.rotateLeft(),o===r&&(o=n),p(e))))}else e.color=i.default.TreeNodeColorType.black},g=function(e){for(var t=e;t.leftChild||t.rightChild;){if(t.rightChild){t=l(t.rightChild);var r=e.key;e.key=t.key,t.key=r;var n=e.value;e.value=t.value,t.value=n,e=t}t.leftChild&&(t=c(t.leftChild),r=e.key,e.key=t.key,t.key=r,n=e.value,e.value=t.value,t.value=n,e=t)}p(t),t&&t.remove(),--a,o.color=i.default.TreeNodeColorType.black},m=function(e,t){return!(!e||void 0===e.key)&&(!!m(e.leftChild,t)||!!t(e)||m(e.rightChild,t))};this.eraseElementByPos=function(e){if(e<0||e>=a)throw new Error("pos must more than 0 and less than set's size");var t=0;m(o,(function(r){return e===t?(g(r),!0):(++t,!1)}))},this.eraseElementByKey=function(e){if(!this.empty()){var r=b(o,e);void 0!==r&&void 0!==r.key&&0===t(r.key,e)&&g(r)}};var y=function(e,r){if(!e||void 0===e.key)throw new Error("unknown error");var n=t(r,e.key);return n<0?e.leftChild?y(e.leftChild,r):(e.leftChild=new i.default,e.leftChild.parent=e,e.leftChild.brother=e.rightChild,e.rightChild&&(e.rightChild.brother=e.leftChild),e.leftChild):n>0?e.rightChild?y(e.rightChild,r):(e.rightChild=new i.default,e.rightChild.parent=e,e.rightChild.brother=e.leftChild,e.leftChild&&(e.leftChild.brother=e.rightChild),e.rightChild):e},v=function(e){var t=e.parent;if(!t){if(e===o)return;throw new Error("unknown error")}if(t.color!==i.default.TreeNodeColorType.black&&t.color===i.default.TreeNodeColorType.red){var r=t.brother,n=t.parent;if(!n)throw new Error("unknown error");if(r&&r.color===i.default.TreeNodeColorType.red)r.color=t.color=i.default.TreeNodeColorType.black,n.color=i.default.TreeNodeColorType.red,v(n);else if(!r||r.color===i.default.TreeNodeColorType.black)if(t===n.leftChild)if(e===t.leftChild){t.color=i.default.TreeNodeColorType.black,n.color=i.default.TreeNodeColorType.red;var s=n.rotateRight();n===o&&(o=s)}else e===t.rightChild&&(s=t.rotateLeft(),n===o&&(o=s),v(t));else t===n.rightChild&&(e===t.leftChild?(s=t.rotateRight(),n===o&&(o=s),v(t)):e===t.rightChild&&(t.color=i.default.TreeNodeColorType.black,n.color=i.default.TreeNodeColorType.red,s=n.rotateLeft(),n===o&&(o=s)))}};this.setElement=function(e,r){if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(null!=r){if(this.empty())return++a,o.key=e,o.value=r,void(o.color=i.default.TreeNodeColorType.black);var n=y(o,e);void 0===n.key||0!==t(n.key,e)?(++a,n.key=e,n.value=r,v(n),o.color=i.default.TreeNodeColorType.black):n.value=r}else this.eraseElementByKey(e)};var b=function(e,r){if(e&&void 0!==e.key){var n=t(r,e.key);return n<0?b(e.leftChild,r):n>0?b(e.rightChild,r):e}};this.find=function(e){return!!b(o,e)},this.getElementByKey=function(e){var t=b(o,e);if(void 0===(null==t?void 0:t.key)||void 0===(null==t?void 0:t.value))throw new Error("unknown error");return t.value},this.union=function(e){var t=this;e.forEach((function(e){var r=e.key,n=e.value;return t.setElement(r,n)}))},this.getHeight=function(){if(this.empty())return 0;var e=function(t){return t?Math.max(e(t.leftChild),e(t.rightChild))+1:1};return e(o)};var w=function(e){return n(this,(function(t){switch(t.label){case 0:return e&&void 0!==e.key&&void 0!==e.value?[5,s(w(e.leftChild))]:[2];case 1:return t.sent(),[4,{key:e.key,value:e.value}];case 2:return t.sent(),[5,s(w(e.rightChild))];case 3:return t.sent(),[2]}}))};this[Symbol.iterator]=function(){return w(o)},e.forEach((function(e){var t=e.key,n=e.value;return r.setElement(t,n)})),Object.freeze(this)}Object.freeze(a),r.default=a},{"../Base/TreeNode":25}],31:[function(e,t,r){function n(e,t){void 0===e&&(e=[]),t=t||function(e,t){return e>t?-1:e<t?1:0};var r=[];e.forEach((function(e){return r.push(e)}));var n=r.length,s=function(e,t){if(e<0||e>=n)throw new Error("unknown error");if(t<0||t>=n)throw new Error("unknown error");var s=r[e];r[e]=r[t],r[t]=s},i=function(e){if(e<0||e>=n)throw new Error("unknown error");var i=2*e+1,a=2*e+2;i<n&&t(r[e],r[i])>0&&s(e,i),a<n&&t(r[e],r[a])>0&&s(e,a)};!function(){for(var e=Math.floor((n-1)/2);e>=0;--e)for(var i=e,a=2*i+1;a<n;){var o=a+1,l=a;if(o<n&&t(r[a],r[o])>0&&(l=o),t(r[i],r[l])<=0)break;s(i,l),a=2*(i=l)+1}}(),this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){n=0,r.length=0},this.push=function(e){if(r.push(e),1!=++n)for(var s=n-1;s>0;){var a=Math.floor((s-1)/2);if(t(r[a],e)<=0)break;i(a),s=a}},this.pop=function(){if(!this.empty())if(1!==this.size()){var e=r[n-1];--n;for(var s=0;s<this.size();){var i=2*s+1,a=2*s+2;if(i>=this.size())break;var o=i;if(a<this.size()&&t(r[i],r[a])>0&&(o=a),t(r[o],e)>=0)break;r[s]=r[o],s=o}r[s]=e}else--n},this.top=function(){return r[0]},Object.freeze(this)}Object.defineProperty(r,"__esModule",{value:!0}),Object.freeze(n),r.default=n},{}],32:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0});var n=e("../LinkList/LinkList");function s(e){void 0===e&&(e=[]);var t=new n.default(e);this.size=function(){return t.size()},this.empty=function(){return t.empty()},this.clear=function(){t.clear()},this.push=function(e){t.pushBack(e)},this.pop=function(){t.popFront()},this.front=function(){return t.front()},Object.freeze(this)}Object.freeze(s),r.default=s},{"../LinkList/LinkList":29}],33:[function(e,t,r){var n=this&&this.__generator||function(e,t){var r,n,s,i,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function o(e){return function(t){return l([e,t])}}function l(i){if(r)throw new TypeError("Generator is already executing.");for(;a;)try{if(r=1,n&&(s=2&i[0]?n.return:i[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,i[1])).done)return s;switch(n=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,n=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((s=(s=a.trys).length>0&&s[s.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){a.label=i[1];break}if(6===i[0]&&a.label<s[1]){a.label=s[1],s=i;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(i);break}s[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],n=0}finally{r=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}},s=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(r,"__esModule",{value:!0});var i=e("../Base/TreeNode");function a(e,t){var r=this;void 0===e&&(e=[]),t=t||function(e,t){return e<t?-1:e>t?1:0};var a=0,o=new i.default;o.color=i.default.TreeNodeColorType.black,this.size=function(){return a},this.empty=function(){return 0===a},this.clear=function(){a=0,o.key=void 0,o.leftChild=o.rightChild=o.brother=o.parent=void 0,o.color=i.default.TreeNodeColorType.black};var l=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.leftChild?l(e.leftChild):e},c=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.rightChild?c(e.rightChild):e};this.front=function(){if(!this.empty())return l(o).key},this.back=function(){if(!this.empty())return c(o).key},this.forEach=function(e){var t,r,n=0;try{for(var i=s(this),a=i.next();!a.done;a=i.next())e(a.value,n++)}catch(e){t={error:e}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}},this.getElementByPos=function(e){var t,r;if(e<0||e>=this.size())throw new Error("pos must more than 0 and less than set's size");var n=0;try{for(var i=s(this),a=i.next();!a.done;a=i.next()){var o=a.value;if(n===e)return o;++n}}catch(e){t={error:e}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}throw new Error("unknown error")};var d=function(e){var t=e.parent;if(!t){if(e===o)return;throw new Error("unknown error")}if(e.color!==i.default.TreeNodeColorType.red){var r=e.brother;if(!r)throw new Error("unknown error");if(e===t.leftChild)if(r.color===i.default.TreeNodeColorType.red){r.color=i.default.TreeNodeColorType.black,t.color=i.default.TreeNodeColorType.red;var n=t.rotateLeft();o===t&&(o=n),d(e)}else r.color===i.default.TreeNodeColorType.black&&(r.rightChild&&r.rightChild.color===i.default.TreeNodeColorType.red?(r.color=t.color,t.color=i.default.TreeNodeColorType.black,r.rightChild&&(r.rightChild.color=i.default.TreeNodeColorType.black),n=t.rotateLeft(),o===t&&(o=n),e.color=i.default.TreeNodeColorType.black):r.rightChild&&r.rightChild.color!==i.default.TreeNodeColorType.black||!r.leftChild||r.leftChild.color!==i.default.TreeNodeColorType.red?r.leftChild&&r.leftChild.color!==i.default.TreeNodeColorType.black||r.rightChild&&r.rightChild.color!==i.default.TreeNodeColorType.black||(r.color=i.default.TreeNodeColorType.red,d(t)):(r.color=i.default.TreeNodeColorType.red,r.leftChild&&(r.leftChild.color=i.default.TreeNodeColorType.black),n=r.rotateRight(),o===r&&(o=n),d(e)));else e===t.rightChild&&(r.color===i.default.TreeNodeColorType.red?(r.color=i.default.TreeNodeColorType.black,t.color=i.default.TreeNodeColorType.red,n=t.rotateRight(),o===t&&(o=n),d(e)):r.color===i.default.TreeNodeColorType.black&&(r.leftChild&&r.leftChild.color===i.default.TreeNodeColorType.red?(r.color=t.color,t.color=i.default.TreeNodeColorType.black,r.leftChild&&(r.leftChild.color=i.default.TreeNodeColorType.black),n=t.rotateRight(),o===t&&(o=n),e.color=i.default.TreeNodeColorType.black):r.leftChild&&r.leftChild.color!==i.default.TreeNodeColorType.black||!r.rightChild||r.rightChild.color!==i.default.TreeNodeColorType.red?r.leftChild&&r.leftChild.color!==i.default.TreeNodeColorType.black||r.rightChild&&r.rightChild.color!==i.default.TreeNodeColorType.black||(r.color=i.default.TreeNodeColorType.red,d(t)):(r.color=i.default.TreeNodeColorType.red,r.rightChild&&(r.rightChild.color=i.default.TreeNodeColorType.black),n=r.rotateLeft(),o===r&&(o=n),d(e))))}else e.color=i.default.TreeNodeColorType.black},u=function(e){for(var t=e;t.leftChild||t.rightChild;){if(t.rightChild){t=l(t.rightChild);var r=e.key;e.key=t.key,t.key=r,e=t}t.leftChild&&(t=c(t.leftChild),r=e.key,e.key=t.key,t.key=r,e=t)}d(t),t&&t.remove(),--a,o.color=i.default.TreeNodeColorType.black},h=function(e,t){return!(!e||void 0===e.key)&&(!!h(e.leftChild,t)||!!t(e)||h(e.rightChild,t))};this.eraseElementByPos=function(e){if(e<0||e>=a)throw new Error("pos must more than 0 and less than set's size");var t=0;h(o,(function(r){return e===t?(u(r),!0):(++t,!1)}))},this.eraseElementByValue=function(e){if(!this.empty()){var r=g(o,e);void 0!==r&&void 0!==r.key&&0===t(r.key,e)&&u(r)}};var f=function(e,r){if(!e||void 0===e.key)throw new Error("unknown error");var n=t(r,e.key);return n<0?e.leftChild?f(e.leftChild,r):(e.leftChild=new i.default,e.leftChild.parent=e,e.leftChild.brother=e.rightChild,e.rightChild&&(e.rightChild.brother=e.leftChild),e.leftChild):n>0?e.rightChild?f(e.rightChild,r):(e.rightChild=new i.default,e.rightChild.parent=e,e.rightChild.brother=e.leftChild,e.leftChild&&(e.leftChild.brother=e.rightChild),e.rightChild):e},p=function(e){var t=e.parent;if(!t){if(e===o)return;throw new Error("unknown error")}if(t.color!==i.default.TreeNodeColorType.black&&t.color===i.default.TreeNodeColorType.red){var r=t.brother,n=t.parent;if(!n)throw new Error("unknown error");if(r&&r.color===i.default.TreeNodeColorType.red)r.color=t.color=i.default.TreeNodeColorType.black,n.color=i.default.TreeNodeColorType.red,p(n);else if(!r||r.color===i.default.TreeNodeColorType.black)if(t===n.leftChild)if(e===t.leftChild){t.color=i.default.TreeNodeColorType.black,n.color=i.default.TreeNodeColorType.red;var s=n.rotateRight();n===o&&(o=s)}else e===t.rightChild&&(s=t.rotateLeft(),n===o&&(o=s),p(t));else t===n.rightChild&&(e===t.leftChild?(s=t.rotateRight(),n===o&&(o=s),p(t)):e===t.rightChild&&(t.color=i.default.TreeNodeColorType.black,n.color=i.default.TreeNodeColorType.red,s=n.rotateLeft(),n===o&&(o=s)))}};this.insert=function(e){if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(this.empty())return++a,o.key=e,void(o.color=i.default.TreeNodeColorType.black);var r=f(o,e);void 0!==r.key&&0===t(r.key,e)||(++a,r.key=e,p(r),o.color=i.default.TreeNodeColorType.black)};var g=function(e,r){if(e&&void 0!==e.key){var n=t(r,e.key);return n<0?g(e.leftChild,r):n>0?g(e.rightChild,r):e}};this.find=function(e){var r=g(o,e);return void 0!==r&&void 0!==r.key&&0===t(r.key,e)};var m=function(e,r){if(e&&void 0!==e.key){var n=t(e.key,r);if(0===n)return e.key;if(n<0)return m(e.rightChild,r);var s=m(e.leftChild,r);return void 0!==s?s:e.key}};this.lowerBound=function(e){return m(o,e)};var y=function(e,r){if(e&&void 0!==e.key){if(t(e.key,r)<=0)return y(e.rightChild,r);var n=y(e.leftChild,r);return void 0!==n?n:e.key}};this.upperBound=function(e){return y(o,e)};var v=function(e,r){if(e&&void 0!==e.key){var n=t(e.key,r);if(0===n)return e.key;if(n>0)return v(e.leftChild,r);var s=v(e.rightChild,r);return void 0!==s?s:e.key}};this.reverseLowerBound=function(e){return v(o,e)};var b=function(e,r){if(e&&void 0!==e.key){if(t(e.key,r)>=0)return b(e.leftChild,r);var n=b(e.rightChild,r);return void 0!==n?n:e.key}};this.reverseUpperBound=function(e){return b(o,e)},this.union=function(e){var t=this;e.forEach((function(e){return t.insert(e)}))},this.getHeight=function(){if(this.empty())return 0;var e=function(t){return t?Math.max(e(t.leftChild),e(t.rightChild))+1:1};return e(o)};var w=function(e){return n(this,(function(t){switch(t.label){case 0:return e&&void 0!==e.key?[5,s(w(e.leftChild))]:[2];case 1:return t.sent(),[4,e.key];case 2:return t.sent(),[5,s(w(e.rightChild))];case 3:return t.sent(),[2]}}))};this[Symbol.iterator]=function(){return w(o)},e.forEach((function(e){return r.insert(e)})),Object.freeze(this)}Object.freeze(a),r.default=a},{"../Base/TreeNode":25}],34:[function(e,t,r){function n(e){var t=this;void 0===e&&(e=[]);var r=0,n=[];this.size=function(){return r},this.empty=function(){return 0===r},this.clear=function(){r=0,n.length=0},this.push=function(e){n.push(e),++r},this.pop=function(){n.pop(),r>0&&--r},this.top=function(){return n[r-1]},e.forEach((function(e){return t.push(e)})),Object.freeze(this)}Object.defineProperty(r,"__esModule",{value:!0}),Object.freeze(n),r.default=n},{}],35:[function(e,t,r){var n=this&&this.__generator||function(e,t){var r,n,s,i,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function o(e){return function(t){return l([e,t])}}function l(i){if(r)throw new TypeError("Generator is already executing.");for(;a;)try{if(r=1,n&&(s=2&i[0]?n.return:i[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,i[1])).done)return s;switch(n=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,n=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((s=(s=a.trys).length>0&&s[s.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){a.label=i[1];break}if(6===i[0]&&a.label<s[1]){a.label=s[1],s=i;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(i);break}s[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],n=0}finally{r=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}},s=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,s,i=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)a.push(n.value)}catch(e){s={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(s)throw s.error}}return a},i=this&&this.__spreadArray||function(e,t,r){if(r||2===arguments.length)for(var n,s=0,i=t.length;s<i;s++)!n&&s in t||(n||(n=Array.prototype.slice.call(t,0,s)),n[s]=t[s]);return e.concat(n||Array.prototype.slice.call(t))},a=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};function o(e){var t=this;void 0===e&&(e=[]);var r=0,o=[];this.size=function(){return r},this.empty=function(){return 0===r},this.clear=function(){r=0,o.length=0},this.front=function(){if(!this.empty())return o[0]},this.back=function(){if(!this.empty())return o[r-1]},this.forEach=function(e){o.forEach(e)},this.getElementByPos=function(e){if(e<0||e>=r)throw new Error("pos must more than 0 and less than vector's size");return o[e]},this.eraseElementByPos=function(e){if(e<0||e>=r)throw new Error("pos must more than 0 and less than vector's size");for(var t=e;t<r-1;++t)o[t]=o[t+1];this.popBack()},this.eraseElementByValue=function(e){var t=[];this.forEach((function(r){r!==e&&t.push(r)})),t.forEach((function(e,t){o[t]=e}));for(var n=t.length;r>n;)this.popBack()},this.pushBack=function(e){o.push(e),++r},this.popBack=function(){o.pop(),r>0&&--r},this.setElementByPos=function(e,t){if(e<0||e>=r)throw new Error("pos must more than 0 and less than vector's size");o[e]=t},this.insert=function(e,t,n){if(void 0===n&&(n=1),e<0||e>r)throw new Error("pos must more than 0 and less than or equal to vector's size");o.splice.apply(o,i([e,0],s(new Array(n).fill(t)),!1)),r+=n},this.find=function(e){return o.includes(e)},this.reverse=function(){o.reverse()},this.unique=function(){var e,t=[];this.forEach((function(r,n){0!==n&&r===e||(t.push(r),e=r)})),t.forEach((function(e,t){o[t]=e}));for(var n=t.length;r>n;)this.popBack()},this.sort=function(e){o.sort(e)},this[Symbol.iterator]=function(){return function(){return n(this,(function(e){switch(e.label){case 0:return[5,a(o)];case 1:return[2,e.sent()]}}))}()},e.forEach((function(e){return t.pushBack(e)})),Object.freeze(this)}Object.defineProperty(r,"__esModule",{value:!0}),Object.freeze(o),r.default=o},{}],36:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}),r.HashMap=r.HashSet=r.Map=r.Set=r.PriorityQueue=r.Deque=r.LinkList=r.Queue=r.Stack=r.Vector=void 0;var n=e("./Vector/Vector");r.Vector=n.default;var s=e("./Stack/Stack");r.Stack=s.default;var i=e("./Queue/Queue");r.Queue=i.default;var a=e("./LinkList/LinkList");r.LinkList=a.default;var o=e("./Deque/Deque");r.Deque=o.default;var l=e("./PriorityQueue/PriorityQueue");r.PriorityQueue=l.default;var c=e("./Set/Set");r.Set=c.default;var d=e("./Map/Map");r.Map=d.default;var u=e("./HashSet/HashSet");r.HashSet=u.default;var h=e("./HashMap/HashMap");r.HashMap=h.default},{"./Deque/Deque":26,"./HashMap/HashMap":27,"./HashSet/HashSet":28,"./LinkList/LinkList":29,"./Map/Map":30,"./PriorityQueue/PriorityQueue":31,"./Queue/Queue":32,"./Set/Set":33,"./Stack/Stack":34,"./Vector/Vector":35}],37:[function(e,t,r){const n=e("yallist"),s=Symbol("max"),i=Symbol("length"),a=Symbol("lengthCalculator"),o=Symbol("allowStale"),l=Symbol("maxAge"),c=Symbol("dispose"),d=Symbol("noDisposeOnSet"),u=Symbol("lruList"),h=Symbol("cache"),f=Symbol("updateAgeOnGet"),p=()=>1;class g{constructor(e){if("number"==typeof e&&(e={max:e}),e||(e={}),e.max&&("number"!=typeof e.max||e.max<0))throw new TypeError("max must be a non-negative number");this[s]=e.max||1/0;const t=e.length||p;if(this[a]="function"!=typeof t?p:t,this[o]=e.stale||!1,e.maxAge&&"number"!=typeof e.maxAge)throw new TypeError("maxAge must be a number");this[l]=e.maxAge||0,this[c]=e.dispose,this[d]=e.noDisposeOnSet||!1,this[f]=e.updateAgeOnGet||!1,this.reset()}set max(e){if("number"!=typeof e||e<0)throw new TypeError("max must be a non-negative number");this[s]=e||1/0,v(this)}get max(){return this[s]}set allowStale(e){this[o]=!!e}get allowStale(){return this[o]}set maxAge(e){if("number"!=typeof e)throw new TypeError("maxAge must be a non-negative number");this[l]=e,v(this)}get maxAge(){return this[l]}set lengthCalculator(e){"function"!=typeof e&&(e=p),e!==this[a]&&(this[a]=e,this[i]=0,this[u].forEach((e=>{e.length=this[a](e.value,e.key),this[i]+=e.length}))),v(this)}get lengthCalculator(){return this[a]}get length(){return this[i]}get itemCount(){return this[u].length}rforEach(e,t){t=t||this;for(let r=this[u].tail;null!==r;){const n=r.prev;E(this,e,r,t),r=n}}forEach(e,t){t=t||this;for(let r=this[u].head;null!==r;){const n=r.next;E(this,e,r,t),r=n}}keys(){return this[u].toArray().map((e=>e.key))}values(){return this[u].toArray().map((e=>e.value))}reset(){this[c]&&this[u]&&this[u].length&&this[u].forEach((e=>this[c](e.key,e.value))),this[h]=new Map,this[u]=new n,this[i]=0}dump(){return this[u].map((e=>!y(this,e)&&{k:e.key,v:e.value,e:e.now+(e.maxAge||0)})).toArray().filter((e=>e))}dumpLru(){return this[u]}set(e,t,r){if((r=r||this[l])&&"number"!=typeof r)throw new TypeError("maxAge must be a number");const n=r?Date.now():0,o=this[a](t,e);if(this[h].has(e)){if(o>this[s])return b(this,this[h].get(e)),!1;const a=this[h].get(e).value;return this[c]&&(this[d]||this[c](e,a.value)),a.now=n,a.maxAge=r,a.value=t,this[i]+=o-a.length,a.length=o,this.get(e),v(this),!0}const f=new w(e,t,o,n,r);return f.length>this[s]?(this[c]&&this[c](e,t),!1):(this[i]+=f.length,this[u].unshift(f),this[h].set(e,this[u].head),v(this),!0)}has(e){if(!this[h].has(e))return!1;const t=this[h].get(e).value;return!y(this,t)}get(e){return m(this,e,!0)}peek(e){return m(this,e,!1)}pop(){const e=this[u].tail;return e?(b(this,e),e.value):null}del(e){b(this,this[h].get(e))}load(e){this.reset();const t=Date.now();for(let r=e.length-1;r>=0;r--){const n=e[r],s=n.e||0;if(0===s)this.set(n.k,n.v);else{const e=s-t;e>0&&this.set(n.k,n.v,e)}}}prune(){this[h].forEach(((e,t)=>m(this,t,!1)))}}const m=(e,t,r)=>{const n=e[h].get(t);if(n){const t=n.value;if(y(e,t)){if(b(e,n),!e[o])return}else r&&(e[f]&&(n.value.now=Date.now()),e[u].unshiftNode(n));return t.value}},y=(e,t)=>{if(!t||!t.maxAge&&!e[l])return!1;const r=Date.now()-t.now;return t.maxAge?r>t.maxAge:e[l]&&r>e[l]},v=e=>{if(e[i]>e[s])for(let t=e[u].tail;e[i]>e[s]&&null!==t;){const r=t.prev;b(e,t),t=r}},b=(e,t)=>{if(t){const r=t.value;e[c]&&e[c](r.key,r.value),e[i]-=r.length,e[h].delete(r.key),e[u].removeNode(t)}};class w{constructor(e,t,r,n,s){this.key=e,this.value=t,this.length=r,this.now=n,this.maxAge=s||0}}const E=(e,t,r,n)=>{let s=r.value;y(e,s)&&(b(e,r),e[o]||(s=void 0)),s&&t.call(n,s.value,s.key,e)};t.exports=g},{yallist:83}],38:[function(e,t,r){(function(e){(function(){const r=t.exports;r.types={0:"reserved",1:"connect",2:"connack",3:"publish",4:"puback",5:"pubrec",6:"pubrel",7:"pubcomp",8:"subscribe",9:"suback",10:"unsubscribe",11:"unsuback",12:"pingreq",13:"pingresp",14:"disconnect",15:"auth"},r.codes={};for(const e in r.types){const t=r.types[e];r.codes[t]=e}r.CMD_SHIFT=4,r.CMD_MASK=240,r.DUP_MASK=8,r.QOS_MASK=3,r.QOS_SHIFT=1,r.RETAIN_MASK=1,r.VARBYTEINT_MASK=127,r.VARBYTEINT_FIN_MASK=128,r.VARBYTEINT_MAX=268435455,r.SESSIONPRESENT_MASK=1,r.SESSIONPRESENT_HEADER=e.from([r.SESSIONPRESENT_MASK]),r.CONNACK_HEADER=e.from([r.codes.connack<<r.CMD_SHIFT]),r.USERNAME_MASK=128,r.PASSWORD_MASK=64,r.WILL_RETAIN_MASK=32,r.WILL_QOS_MASK=24,r.WILL_QOS_SHIFT=3,r.WILL_FLAG_MASK=4,r.CLEAN_SESSION_MASK=2,r.CONNECT_HEADER=e.from([r.codes.connect<<r.CMD_SHIFT]),r.properties={sessionExpiryInterval:17,willDelayInterval:24,receiveMaximum:33,maximumPacketSize:39,topicAliasMaximum:34,requestResponseInformation:25,requestProblemInformation:23,userProperties:38,authenticationMethod:21,authenticationData:22,payloadFormatIndicator:1,messageExpiryInterval:2,contentType:3,responseTopic:8,correlationData:9,maximumQoS:36,retainAvailable:37,assignedClientIdentifier:18,reasonString:31,wildcardSubscriptionAvailable:40,subscriptionIdentifiersAvailable:41,sharedSubscriptionAvailable:42,serverKeepAlive:19,responseInformation:26,serverReference:28,topicAlias:35,subscriptionIdentifier:11},r.propertiesCodes={};for(const e in r.properties){const t=r.properties[e];r.propertiesCodes[t]=e}function n(t){return[0,1,2].map((n=>[0,1].map((s=>[0,1].map((i=>{const a=e.alloc(1);return a.writeUInt8(r.codes[t]<<r.CMD_SHIFT|(s?r.DUP_MASK:0)|n<<r.QOS_SHIFT|i,0,!0),a}))))))}r.propertiesTypes={sessionExpiryInterval:"int32",willDelayInterval:"int32",receiveMaximum:"int16",maximumPacketSize:"int32",topicAliasMaximum:"int16",requestResponseInformation:"byte",requestProblemInformation:"byte",userProperties:"pair",authenticationMethod:"string",authenticationData:"binary",payloadFormatIndicator:"byte",messageExpiryInterval:"int32",contentType:"string",responseTopic:"string",correlationData:"binary",maximumQoS:"int8",retainAvailable:"byte",assignedClientIdentifier:"string",reasonString:"string",wildcardSubscriptionAvailable:"byte",subscriptionIdentifiersAvailable:"byte",sharedSubscriptionAvailable:"byte",serverKeepAlive:"int16",responseInformation:"string",serverReference:"string",topicAlias:"int16",subscriptionIdentifier:"var"},r.PUBLISH_HEADER=n("publish"),r.SUBSCRIBE_HEADER=n("subscribe"),r.SUBSCRIBE_OPTIONS_QOS_MASK=3,r.SUBSCRIBE_OPTIONS_NL_MASK=1,r.SUBSCRIBE_OPTIONS_NL_SHIFT=2,r.SUBSCRIBE_OPTIONS_RAP_MASK=1,r.SUBSCRIBE_OPTIONS_RAP_SHIFT=3,r.SUBSCRIBE_OPTIONS_RH_MASK=3,r.SUBSCRIBE_OPTIONS_RH_SHIFT=4,r.SUBSCRIBE_OPTIONS_RH=[0,16,32],r.SUBSCRIBE_OPTIONS_NL=4,r.SUBSCRIBE_OPTIONS_RAP=8,r.SUBSCRIBE_OPTIONS_QOS=[0,1,2],r.UNSUBSCRIBE_HEADER=n("unsubscribe"),r.ACKS={unsuback:n("unsuback"),puback:n("puback"),pubcomp:n("pubcomp"),pubrel:n("pubrel"),pubrec:n("pubrec")},r.SUBACK_HEADER=e.from([r.codes.suback<<r.CMD_SHIFT]),r.VERSION3=e.from([3]),r.VERSION4=e.from([4]),r.VERSION5=e.from([5]),r.VERSION131=e.from([131]),r.VERSION132=e.from([132]),r.QOS=[0,1,2].map((t=>e.from([t]))),r.EMPTY={pingreq:e.from([r.codes.pingreq<<4,0]),pingresp:e.from([r.codes.pingresp<<4,0]),disconnect:e.from([r.codes.disconnect<<4,0])}}).call(this)}).call(this,e("buffer").Buffer)},{buffer:17}],39:[function(e,t,r){(function(r){(function(){const n=e("./writeToStream"),s=e("events");function i(e,t){const r=new a;return n(e,r,t),r.concat()}class a extends s{constructor(){super(),this._array=new Array(20),this._i=0}write(e){return this._array[this._i++]=e,!0}concat(){let e=0;const t=new Array(this._array.length),n=this._array;let s,i=0;for(s=0;s<n.length&&void 0!==n[s];s++)"string"!=typeof n[s]?t[s]=n[s].length:t[s]=r.byteLength(n[s]),e+=t[s];const a=r.allocUnsafe(e);for(s=0;s<n.length&&void 0!==n[s];s++)"string"!=typeof n[s]?(n[s].copy(a,i),i+=t[s]):(a.write(n[s],i),i+=t[s]);return a}}t.exports=i}).call(this)}).call(this,e("buffer").Buffer)},{"./writeToStream":44,buffer:17,events:22}],40:[function(e,t,r){r.parser=e("./parser").parser,r.generate=e("./generate"),r.writeToStream=e("./writeToStream")},{"./generate":39,"./parser":43,"./writeToStream":44}],41:[function(e,t,r){(function(e){(function(){const r=65536,n={},s=e.isBuffer(e.from([1,2]).subarray(0,1));function i(t){const r=e.allocUnsafe(2);return r.writeUInt8(t>>8,0),r.writeUInt8(255&t,1),r}function a(){for(let e=0;e<r;e++)n[e]=i(e)}function o(t){const r=4;let n=0,i=0;const a=e.allocUnsafe(r);do{n=t%128|0,(t=t/128|0)>0&&(n|=128),a.writeUInt8(n,i++)}while(t>0&&i<r);return t>0&&(i=0),s?a.subarray(0,i):a.slice(0,i)}function l(t){const r=e.allocUnsafe(4);return r.writeUInt32BE(t,0),r}t.exports={cache:n,generateCache:a,generateNumber:i,genBufVariableByteInt:o,generate4ByteBuffer:l}}).call(this)}).call(this,e("buffer").Buffer)},{buffer:17}],42:[function(e,t,r){class n{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}}t.exports=n},{}],43:[function(e,t,r){const n=e("bl"),s=e("events"),i=e("./packet"),a=e("./constants"),o=e("debug")("mqtt-packet:parser");class l extends s{constructor(){super(),this.parser=this.constructor.parser}static parser(e){return this instanceof l?(this.settings=e||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):(new l).parser(e)}_resetState(){o("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new i,this.error=null,this._list=n(),this._stateCounter=0}parse(e){for(this.error&&this._resetState(),this._list.append(e),o("parse: current state: %s",this._states[this._stateCounter]);(-1!==this.packet.length||this._list.length>0)&&this[this._states[this._stateCounter]]()&&!this.error;)this._stateCounter++,o("parse: state complete. _stateCounter is now: %d",this._stateCounter),o("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return o("parse: exited while loop. packet: %d, buffer list length: %d",this.packet.length,this._list.length),this._list.length}_parseHeader(){const e=this._list.readUInt8(0);return this.packet.cmd=a.types[e>>a.CMD_SHIFT],this.packet.retain=0!=(e&a.RETAIN_MASK),this.packet.qos=e>>a.QOS_SHIFT&a.QOS_MASK,this.packet.dup=0!=(e&a.DUP_MASK),o("_parseHeader: packet: %o",this.packet),this._list.consume(1),!0}_parseLength(){const e=this._parseVarByteNum(!0);return e&&(this.packet.length=e.value,this._list.consume(e.bytes)),o("_parseLength %d",e.value),!!e}_parsePayload(){o("_parsePayload: payload %O",this._list);let e=!1;if(0===this.packet.length||this._list.length>=this.packet.length){switch(this._pos=0,this.packet.cmd){case"connect":this._parseConnect();break;case"connack":this._parseConnack();break;case"publish":this._parsePublish();break;case"puback":case"pubrec":case"pubrel":case"pubcomp":this._parseConfirmation();break;case"subscribe":this._parseSubscribe();break;case"suback":this._parseSuback();break;case"unsubscribe":this._parseUnsubscribe();break;case"unsuback":this._parseUnsuback();break;case"pingreq":case"pingresp":break;case"disconnect":this._parseDisconnect();break;case"auth":this._parseAuth();break;default:this._emitError(new Error("Not supported"))}e=!0}return o("_parsePayload complete result: %s",e),e}_parseConnect(){let e,t,r,n;o("_parseConnect");const s={},i=this.packet,l=this._parseString();if(null===l)return this._emitError(new Error("Cannot parse protocolId"));if("MQTT"!==l&&"MQIsdp"!==l)return this._emitError(new Error("Invalid protocolId"));if(i.protocolId=l,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(i.protocolVersion=this._list.readUInt8(this._pos),i.protocolVersion>=128&&(i.bridgeMode=!0,i.protocolVersion=i.protocolVersion-128),3!==i.protocolVersion&&4!==i.protocolVersion&&5!==i.protocolVersion)return this._emitError(new Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(s.username=this._list.readUInt8(this._pos)&a.USERNAME_MASK,s.password=this._list.readUInt8(this._pos)&a.PASSWORD_MASK,s.will=this._list.readUInt8(this._pos)&a.WILL_FLAG_MASK,s.will&&(i.will={},i.will.retain=0!=(this._list.readUInt8(this._pos)&a.WILL_RETAIN_MASK),i.will.qos=(this._list.readUInt8(this._pos)&a.WILL_QOS_MASK)>>a.WILL_QOS_SHIFT),i.clean=0!=(this._list.readUInt8(this._pos)&a.CLEAN_SESSION_MASK),this._pos++,i.keepalive=this._parseNum(),-1===i.keepalive)return this._emitError(new Error("Packet too short"));if(5===i.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(i.properties=e)}const c=this._parseString();if(null===c)return this._emitError(new Error("Packet too short"));if(i.clientId=c,o("_parseConnect: packet.clientId: %s",i.clientId),s.will){if(5===i.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(i.will.properties=e)}if(e=this._parseString(),null===e)return this._emitError(new Error("Cannot parse will topic"));if(i.will.topic=e,o("_parseConnect: packet.will.topic: %s",i.will.topic),t=this._parseBuffer(),null===t)return this._emitError(new Error("Cannot parse will payload"));i.will.payload=t,o("_parseConnect: packet.will.paylaod: %s",i.will.payload)}if(s.username){if(n=this._parseString(),null===n)return this._emitError(new Error("Cannot parse username"));i.username=n,o("_parseConnect: packet.username: %s",i.username)}if(s.password){if(r=this._parseBuffer(),null===r)return this._emitError(new Error("Cannot parse password"));i.password=r}return this.settings=i,o("_parseConnect: complete"),i}_parseConnack(){o("_parseConnack");const e=this.packet;if(this._list.length<1)return null;if(e.sessionPresent=!!(this._list.readUInt8(this._pos++)&a.SESSIONPRESENT_MASK),5===this.settings.protocolVersion)this._list.length>=2?e.reasonCode=this._list.readUInt8(this._pos++):e.reasonCode=0;else{if(this._list.length<2)return null;e.returnCode=this._list.readUInt8(this._pos++)}if(-1===e.returnCode||-1===e.reasonCode)return this._emitError(new Error("Cannot parse return code"));if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}o("_parseConnack: complete")}_parsePublish(){o("_parsePublish");const e=this.packet;if(e.topic=this._parseString(),null===e.topic)return this._emitError(new Error("Cannot parse topic"));if(!(e.qos>0)||this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}e.payload=this._list.slice(this._pos,e.length),o("_parsePublish: payload from buffer list: %o",e.payload)}}_parseSubscribe(){o("_parseSubscribe");const e=this.packet;let t,r,n,s,i,l,c;if(1!==e.qos)return this._emitError(new Error("Wrong subscribe header"));if(e.subscriptions=[],this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}for(;this._pos<e.length;){if(t=this._parseString(),null===t)return this._emitError(new Error("Cannot parse topic"));if(this._pos>=e.length)return this._emitError(new Error("Malformed Subscribe Payload"));r=this._parseByte(),n=r&a.SUBSCRIBE_OPTIONS_QOS_MASK,l=0!=(r>>a.SUBSCRIBE_OPTIONS_NL_SHIFT&a.SUBSCRIBE_OPTIONS_NL_MASK),i=0!=(r>>a.SUBSCRIBE_OPTIONS_RAP_SHIFT&a.SUBSCRIBE_OPTIONS_RAP_MASK),s=r>>a.SUBSCRIBE_OPTIONS_RH_SHIFT&a.SUBSCRIBE_OPTIONS_RH_MASK,c={topic:t,qos:n},5===this.settings.protocolVersion?(c.nl=l,c.rap=i,c.rh=s):this.settings.bridgeMode&&(c.rh=0,c.rap=!0,c.nl=!0),o("_parseSubscribe: push subscription `%s` to subscription",c),e.subscriptions.push(c)}}}_parseSuback(){o("_parseSuback");const e=this.packet;if(this.packet.granted=[],this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}for(;this._pos<this.packet.length;)this.packet.granted.push(this._list.readUInt8(this._pos++))}}_parseUnsubscribe(){o("_parseUnsubscribe");const e=this.packet;if(e.unsubscriptions=[],this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}for(;this._pos<e.length;){const t=this._parseString();if(null===t)return this._emitError(new Error("Cannot parse topic"));o("_parseUnsubscribe: push topic `%s` to unsubscriptions",t),e.unsubscriptions.push(t)}}}_parseUnsuback(){o("_parseUnsuback");const e=this.packet;if(!this._parseMessageId())return this._emitError(new Error("Cannot parse messageId"));if(5===this.settings.protocolVersion){const t=this._parseProperties();for(Object.getOwnPropertyNames(t).length&&(e.properties=t),e.granted=[];this._pos<this.packet.length;)this.packet.granted.push(this._list.readUInt8(this._pos++))}}_parseConfirmation(){o("_parseConfirmation: packet.cmd: `%s`",this.packet.cmd);const e=this.packet;if(this._parseMessageId(),5===this.settings.protocolVersion&&(e.length>2?(e.reasonCode=this._parseByte(),o("_parseConfirmation: packet.reasonCode `%d`",e.reasonCode)):e.reasonCode=0,e.length>3)){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}return!0}_parseDisconnect(){const e=this.packet;if(o("_parseDisconnect"),5===this.settings.protocolVersion){this._list.length>0?e.reasonCode=this._parseByte():e.reasonCode=0;const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}return o("_parseDisconnect result: true"),!0}_parseAuth(){o("_parseAuth");const e=this.packet;if(5!==this.settings.protocolVersion)return this._emitError(new Error("Not supported auth packet for this version MQTT"));e.reasonCode=this._parseByte();const t=this._parseProperties();return Object.getOwnPropertyNames(t).length&&(e.properties=t),o("_parseAuth: result: true"),!0}_parseMessageId(){const e=this.packet;return e.messageId=this._parseNum(),null===e.messageId?(this._emitError(new Error("Cannot parse messageId")),!1):(o("_parseMessageId: packet.messageId %d",e.messageId),!0)}_parseString(e){const t=this._parseNum(),r=t+this._pos;if(-1===t||r>this._list.length||r>this.packet.length)return null;const n=this._list.toString("utf8",this._pos,r);return this._pos+=t,o("_parseString: result: %s",n),n}_parseStringPair(){return o("_parseStringPair"),{name:this._parseString(),value:this._parseString()}}_parseBuffer(){const e=this._parseNum(),t=e+this._pos;if(-1===e||t>this._list.length||t>this.packet.length)return null;const r=this._list.slice(this._pos,t);return this._pos+=e,o("_parseBuffer: result: %o",r),r}_parseNum(){if(this._list.length-this._pos<2)return-1;const e=this._list.readUInt16BE(this._pos);return this._pos+=2,o("_parseNum: result: %s",e),e}_parse4ByteNum(){if(this._list.length-this._pos<4)return-1;const e=this._list.readUInt32BE(this._pos);return this._pos+=4,o("_parse4ByteNum: result: %s",e),e}_parseVarByteNum(e){o("_parseVarByteNum");const t=4;let r,n=0,s=1,i=0,l=!1;const c=this._pos?this._pos:0;for(;n<t&&c+n<this._list.length;){if(r=this._list.readUInt8(c+n++),i+=s*(r&a.VARBYTEINT_MASK),s*=128,0==(r&a.VARBYTEINT_FIN_MASK)){l=!0;break}if(this._list.length<=n)break}return!l&&n===t&&this._list.length>=n&&this._emitError(new Error("Invalid variable byte integer")),c&&(this._pos+=n),l=!!l&&(e?{bytes:n,value:i}:i),o("_parseVarByteNum: result: %o",l),l}_parseByte(){let e;return this._pos<this._list.length&&(e=this._list.readUInt8(this._pos),this._pos++),o("_parseByte: result: %o",e),e}_parseByType(e){switch(o("_parseByType: type: %s",e),e){case"byte":return 0!==this._parseByte();case"int8":return this._parseByte();case"int16":return this._parseNum();case"int32":return this._parse4ByteNum();case"var":return this._parseVarByteNum();case"string":return this._parseString();case"pair":return this._parseStringPair();case"binary":return this._parseBuffer()}}_parseProperties(){o("_parseProperties");const e=this._parseVarByteNum(),t=this._pos+e,r={};for(;this._pos<t;){const e=this._parseByte();if(!e)return this._emitError(new Error("Cannot parse property code type")),!1;const t=a.propertiesCodes[e];if(!t)return this._emitError(new Error("Unknown property")),!1;if("userProperties"!==t)r[t]?(Array.isArray(r[t])||(r[t]=[r[t]]),r[t].push(this._parseByType(a.propertiesTypes[t]))):r[t]=this._parseByType(a.propertiesTypes[t]);else{r[t]||(r[t]=Object.create(null));const e=this._parseByType(a.propertiesTypes[t]);if(r[t][e.name])if(Array.isArray(r[t][e.name]))r[t][e.name].push(e.value);else{const n=r[t][e.name];r[t][e.name]=[n],r[t][e.name].push(e.value)}else r[t][e.name]=e.value}}return r}_newPacket(){return o("_newPacket"),this.packet&&(this._list.consume(this.packet.length),o("_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d",this.packet.cmd,this.packet.payload,this.packet.length),this.emit("packet",this.packet)),o("_newPacket: new packet"),this.packet=new i,this._pos=0,!0}_emitError(e){o("_emitError"),this.error=e,this.emit("error",e)}}t.exports=l},{"./constants":38,"./packet":42,bl:15,debug:18,events:22}],44:[function(e,t,r){(function(r){(function(){const n=e("./constants"),s=r.allocUnsafe(0),i=r.from([0]),a=e("./numbers"),o=e("process-nextick-args").nextTick,l=e("debug")("mqtt-packet:writeToStream"),c=a.cache,d=a.generateNumber,u=a.generateCache,h=a.genBufVariableByteInt,f=a.generate4ByteBuffer;let p=O,g=!0;function m(e,t,r){switch(l("generate called"),t.cork&&(t.cork(),o(y,t)),g&&(g=!1,u()),l("generate: packet.cmd: %s",e.cmd),e.cmd){case"connect":return v(e,t);case"connack":return b(e,t,r);case"publish":return w(e,t,r);case"puback":case"pubrec":case"pubrel":case"pubcomp":return E(e,t,r);case"subscribe":return S(e,t,r);case"suback":return T(e,t,r);case"unsubscribe":return C(e,t,r);case"unsuback":return k(e,t,r);case"pingreq":case"pingresp":return A(e,t);case"disconnect":return I(e,t,r);case"auth":return _(e,t,r);default:return t.emit("error",new Error("Unknown command")),!1}}function y(e){e.uncork()}function v(e,t,s){const i=e||{},a=i.protocolId||"MQTT";let o=i.protocolVersion||4;const l=i.will;let c=i.clean;const d=i.keepalive||0,u=i.clientId||"",h=i.username,f=i.password,g=i.properties;void 0===c&&(c=!0);let m=0;if(!a||"string"!=typeof a&&!r.isBuffer(a))return t.emit("error",new Error("Invalid protocolId")),!1;if(m+=a.length+2,3!==o&&4!==o&&5!==o)return t.emit("error",new Error("Invalid protocol version")),!1;if(m+=1,("string"==typeof u||r.isBuffer(u))&&(u||o>=4)&&(u||c))m+=r.byteLength(u)+2;else{if(o<4)return t.emit("error",new Error("clientId must be supplied before 3.1.1")),!1;if(1*c==0)return t.emit("error",new Error("clientId must be given if cleanSession set to 0")),!1}if("number"!=typeof d||d<0||d>65535||d%1!=0)return t.emit("error",new Error("Invalid keepalive")),!1;if(m+=2,m+=1,5===o){var y=U(t,g);if(!y)return!1;m+=y.length}if(l){if("object"!=typeof l)return t.emit("error",new Error("Invalid will")),!1;if(!l.topic||"string"!=typeof l.topic)return t.emit("error",new Error("Invalid will topic")),!1;if(m+=r.byteLength(l.topic)+2,m+=2,l.payload){if(!(l.payload.length>=0))return t.emit("error",new Error("Invalid will payload")),!1;"string"==typeof l.payload?m+=r.byteLength(l.payload):m+=l.payload.length}var v={};if(5===o){if(!(v=U(t,l.properties)))return!1;m+=v.length}}let b=!1;if(null!=h){if(!q(h))return t.emit("error",new Error("Invalid username")),!1;b=!0,m+=r.byteLength(h)+2}if(null!=f){if(!b)return t.emit("error",new Error("Username is required to use password")),!1;if(!q(f))return t.emit("error",new Error("Invalid password")),!1;m+=$(f)+2}t.write(n.CONNECT_HEADER),L(t,m),F(t,a),i.bridgeMode&&(o+=128),t.write(131===o?n.VERSION131:132===o?n.VERSION132:4===o?n.VERSION4:5===o?n.VERSION5:n.VERSION3);let w=0;return w|=null!=h?n.USERNAME_MASK:0,w|=null!=f?n.PASSWORD_MASK:0,w|=l&&l.retain?n.WILL_RETAIN_MASK:0,w|=l&&l.qos?l.qos<<n.WILL_QOS_SHIFT:0,w|=l?n.WILL_FLAG_MASK:0,w|=c?n.CLEAN_SESSION_MASK:0,t.write(r.from([w])),p(t,d),5===o&&y.write(),F(t,u),l&&(5===o&&v.write(),D(t,l.topic),F(t,l.payload)),null!=h&&F(t,h),null!=f&&F(t,f),!0}function b(e,t,s){const a=s?s.protocolVersion:4,o=e||{},l=5===a?o.reasonCode:o.returnCode,c=o.properties;let d=2;if("number"!=typeof l)return t.emit("error",new Error("Invalid return code")),!1;let u=null;if(5===a){if(u=U(t,c),!u)return!1;d+=u.length}return t.write(n.CONNACK_HEADER),L(t,d),t.write(o.sessionPresent?n.SESSIONPRESENT_HEADER:i),t.write(r.from([l])),null!=u&&u.write(),!0}function w(e,t,i){l("publish: packet: %o",e);const a=i?i.protocolVersion:4,o=e||{},c=o.qos||0,d=o.retain?n.RETAIN_MASK:0,u=o.topic,h=o.payload||s,f=o.messageId,g=o.properties;let m=0;if("string"==typeof u)m+=r.byteLength(u)+2;else{if(!r.isBuffer(u))return t.emit("error",new Error("Invalid topic")),!1;m+=u.length+2}if(r.isBuffer(h)?m+=h.length:m+=r.byteLength(h),c&&"number"!=typeof f)return t.emit("error",new Error("Invalid messageId")),!1;c&&(m+=2);let y=null;if(5===a){if(y=U(t,g),!y)return!1;m+=y.length}return t.write(n.PUBLISH_HEADER[c][o.dup?1:0][d?1:0]),L(t,m),p(t,$(u)),t.write(u),c>0&&p(t,f),null!=y&&y.write(),l("publish: payload: %o",h),t.write(h)}function E(e,t,s){const i=s?s.protocolVersion:4,a=e||{},o=a.cmd||"puback",l=a.messageId,c=a.dup&&"pubrel"===o?n.DUP_MASK:0;let d=0;const u=a.reasonCode,h=a.properties;let f=5===i?3:2;if("pubrel"===o&&(d=1),"number"!=typeof l)return t.emit("error",new Error("Invalid messageId")),!1;let g=null;if(5===i&&"object"==typeof h){if(g=N(t,h,s,f),!g)return!1;f+=g.length}return t.write(n.ACKS[o][d][c][0]),L(t,f),p(t,l),5===i&&t.write(r.from([u])),null!==g&&g.write(),!0}function S(e,t,s){l("subscribe: packet: ");const i=s?s.protocolVersion:4,a=e||{},o=a.dup?n.DUP_MASK:0,c=a.messageId,d=a.subscriptions,u=a.properties;let h=0;if("number"!=typeof c)return t.emit("error",new Error("Invalid messageId")),!1;h+=2;let f=null;if(5===i){if(f=U(t,u),!f)return!1;h+=f.length}if("object"!=typeof d||!d.length)return t.emit("error",new Error("Invalid subscriptions")),!1;for(let e=0;e<d.length;e+=1){const n=d[e].topic,s=d[e].qos;if("string"!=typeof n)return t.emit("error",new Error("Invalid subscriptions - invalid topic")),!1;if("number"!=typeof s)return t.emit("error",new Error("Invalid subscriptions - invalid qos")),!1;if(5===i){if("boolean"!=typeof(d[e].nl||!1))return t.emit("error",new Error("Invalid subscriptions - invalid No Local")),!1;if("boolean"!=typeof(d[e].rap||!1))return t.emit("error",new Error("Invalid subscriptions - invalid Retain as Published")),!1;const r=d[e].rh||0;if("number"!=typeof r||r>2)return t.emit("error",new Error("Invalid subscriptions - invalid Retain Handling")),!1}h+=r.byteLength(n)+2+1}l("subscribe: writing to stream: %o",n.SUBSCRIBE_HEADER),t.write(n.SUBSCRIBE_HEADER[1][o?1:0][0]),L(t,h),p(t,c),null!==f&&f.write();let g=!0;for(const e of d){const s=e.topic,a=e.qos,o=+e.nl,l=+e.rap,c=e.rh;let d;D(t,s),d=n.SUBSCRIBE_OPTIONS_QOS[a],5===i&&(d|=o?n.SUBSCRIBE_OPTIONS_NL:0,d|=l?n.SUBSCRIBE_OPTIONS_RAP:0,d|=c?n.SUBSCRIBE_OPTIONS_RH[c]:0),g=t.write(r.from([d]))}return g}function T(e,t,s){const i=s?s.protocolVersion:4,a=e||{},o=a.messageId,l=a.granted,c=a.properties;let d=0;if("number"!=typeof o)return t.emit("error",new Error("Invalid messageId")),!1;if(d+=2,"object"!=typeof l||!l.length)return t.emit("error",new Error("Invalid qos vector")),!1;for(let e=0;e<l.length;e+=1){if("number"!=typeof l[e])return t.emit("error",new Error("Invalid qos vector")),!1;d+=1}let u=null;if(5===i){if(u=N(t,c,s,d),!u)return!1;d+=u.length}return t.write(n.SUBACK_HEADER),L(t,d),p(t,o),null!==u&&u.write(),t.write(r.from(l))}function C(e,t,s){const i=s?s.protocolVersion:4,a=e||{},o=a.messageId,l=a.dup?n.DUP_MASK:0,c=a.unsubscriptions,d=a.properties;let u=0;if("number"!=typeof o)return t.emit("error",new Error("Invalid messageId")),!1;if(u+=2,"object"!=typeof c||!c.length)return t.emit("error",new Error("Invalid unsubscriptions")),!1;for(let e=0;e<c.length;e+=1){if("string"!=typeof c[e])return t.emit("error",new Error("Invalid unsubscriptions")),!1;u+=r.byteLength(c[e])+2}let h=null;if(5===i){if(h=U(t,d),!h)return!1;u+=h.length}t.write(n.UNSUBSCRIBE_HEADER[1][l?1:0][0]),L(t,u),p(t,o),null!==h&&h.write();let f=!0;for(let e=0;e<c.length;e++)f=D(t,c[e]);return f}function k(e,t,s){const i=s?s.protocolVersion:4,a=e||{},o=a.messageId,l=a.dup?n.DUP_MASK:0,c=a.granted,d=a.properties,u=a.cmd,h=0;let f=2;if("number"!=typeof o)return t.emit("error",new Error("Invalid messageId")),!1;if(5===i){if("object"!=typeof c||!c.length)return t.emit("error",new Error("Invalid qos vector")),!1;for(let e=0;e<c.length;e+=1){if("number"!=typeof c[e])return t.emit("error",new Error("Invalid qos vector")),!1;f+=1}}let g=null;if(5===i){if(g=N(t,d,s,f),!g)return!1;f+=g.length}return t.write(n.ACKS[u][h][l][0]),L(t,f),p(t,o),null!==g&&g.write(),5===i&&t.write(r.from(c)),!0}function A(e,t,r){return t.write(n.EMPTY[e.cmd])}function I(e,t,s){const i=s?s.protocolVersion:4,a=e||{},o=a.reasonCode,l=a.properties;let c=5===i?1:0,d=null;if(5===i){if(d=N(t,l,s,c),!d)return!1;c+=d.length}return t.write(r.from([n.codes.disconnect<<4])),L(t,c),5===i&&t.write(r.from([o])),null!==d&&d.write(),!0}function _(e,t,s){const i=s?s.protocolVersion:4,a=e||{},o=a.reasonCode,l=a.properties;let c=5===i?1:0;5!==i&&t.emit("error",new Error("Invalid mqtt version for auth packet"));const d=N(t,l,s,c);return!!d&&(c+=d.length,t.write(r.from([n.codes.auth<<4])),L(t,c),t.write(r.from([o])),null!==d&&d.write(),!0)}Object.defineProperty(m,"cacheNumbers",{get:()=>p===O,set(e){e?(c&&0!==Object.keys(c).length||(g=!0),p=O):(g=!1,p=P)}});const R={};function L(e,t){if(t>n.VARBYTEINT_MAX)return e.emit("error",new Error(`Invalid variable byte integer: ${t}`)),!1;let r=R[t];return r||(r=h(t),t<16384&&(R[t]=r)),l("writeVarByteInt: writing to stream: %o",r),e.write(r)}function D(e,t){const n=r.byteLength(t);return p(e,n),l("writeString: %s",t),e.write(t,"utf8")}function x(e,t,r){D(e,t),D(e,r)}function O(e,t){return l("writeNumberCached: number: %d",t),l("writeNumberCached: %o",c[t]),e.write(c[t])}function P(e,t){const r=d(t);return l("writeNumberGenerated: %o",r),e.write(r)}function M(e,t){const r=f(t);return l("write4ByteNumber: %o",r),e.write(r)}function F(e,t){"string"==typeof t?D(e,t):t?(p(e,t.length),e.write(t)):p(e,0)}function U(e,t){if("object"!=typeof t||null!=t.length)return{length:1,write(){j(e,{},0)}};let s=0;function i(t,s){let i=0;switch(n.propertiesTypes[t]){case"byte":if("boolean"!=typeof s)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;i+=2;break;case"int8":if("number"!=typeof s||s<0||s>255)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;i+=2;break;case"binary":if(s&&null===s)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;i+=1+r.byteLength(s)+2;break;case"int16":if("number"!=typeof s||s<0||s>65535)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;i+=3;break;case"int32":if("number"!=typeof s||s<0||s>4294967295)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;i+=5;break;case"var":if("number"!=typeof s||s<0||s>268435455)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;i+=1+r.byteLength(h(s));break;case"string":if("string"!=typeof s)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;i+=3+r.byteLength(s.toString());break;case"pair":if("object"!=typeof s)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;i+=Object.getOwnPropertyNames(s).reduce(((e,t)=>{const n=s[t];return Array.isArray(n)?e+=n.reduce(((e,n)=>e+=3+r.byteLength(t.toString())+2+r.byteLength(n.toString())),0):e+=3+r.byteLength(t.toString())+2+r.byteLength(s[t].toString()),e}),0);break;default:return e.emit("error",new Error(`Invalid property ${t}: ${s}`)),!1}return i}if(t)for(const e in t){let r=0,n=0;const a=t[e];if(Array.isArray(a))for(let t=0;t<a.length;t++){if(n=i(e,a[t]),!n)return!1;r+=n}else{if(n=i(e,a),!n)return!1;r=n}if(!r)return!1;s+=r}return{length:r.byteLength(h(s))+s,write(){j(e,t,s)}}}function N(e,t,r,n){const s=["reasonString","userProperties"],i=r&&r.properties&&r.properties.maximumPacketSize?r.properties.maximumPacketSize:0;let a=U(e,t);if(i)for(;n+a.length>i;){const r=s.shift();if(!r||!t[r])return!1;delete t[r],a=U(e,t)}return a}function B(e,t,s){switch(n.propertiesTypes[t]){case"byte":e.write(r.from([n.properties[t]])),e.write(r.from([+s]));break;case"int8":e.write(r.from([n.properties[t]])),e.write(r.from([s]));break;case"binary":e.write(r.from([n.properties[t]])),F(e,s);break;case"int16":e.write(r.from([n.properties[t]])),p(e,s);break;case"int32":e.write(r.from([n.properties[t]])),M(e,s);break;case"var":e.write(r.from([n.properties[t]])),L(e,s);break;case"string":e.write(r.from([n.properties[t]])),D(e,s);break;case"pair":Object.getOwnPropertyNames(s).forEach((i=>{const a=s[i];Array.isArray(a)?a.forEach((s=>{e.write(r.from([n.properties[t]])),x(e,i.toString(),s.toString())})):(e.write(r.from([n.properties[t]])),x(e,i.toString(),a.toString()))}));break;default:return e.emit("error",new Error(`Invalid property ${t} value: ${s}`)),!1}}function j(e,t,r){L(e,r);for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)&&null!==t[r]){const n=t[r];if(Array.isArray(n))for(let t=0;t<n.length;t++)B(e,r,n[t]);else B(e,r,n)}}function $(e){return e?e instanceof r?e.length:r.byteLength(e):0}function q(e){return"string"==typeof e||e instanceof r}t.exports=m}).call(this)}).call(this,e("buffer").Buffer)},{"./constants":38,"./numbers":41,buffer:17,debug:18,"process-nextick-args":49}],45:[function(e,t,r){var n=1e3,s=60*n,i=60*s,a=24*i,o=7*a,l=365.25*a;function c(e){if(!((e=String(e)).length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var r=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return r*l;case"weeks":case"week":case"w":return r*o;case"days":case"day":case"d":return r*a;case"hours":case"hour":case"hrs":case"hr":case"h":return r*i;case"minutes":case"minute":case"mins":case"min":case"m":return r*s;case"seconds":case"second":case"secs":case"sec":case"s":return r*n;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function d(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+"d":t>=i?Math.round(e/i)+"h":t>=s?Math.round(e/s)+"m":t>=n?Math.round(e/n)+"s":e+"ms"}function u(e){var t=Math.abs(e);return t>=a?h(e,t,a,"day"):t>=i?h(e,t,i,"hour"):t>=s?h(e,t,s,"minute"):t>=n?h(e,t,n,"second"):e+" ms"}function h(e,t,r,n){var s=t>=1.5*r;return Math.round(e/r)+" "+n+(s?"s":"")}t.exports=function(e,t){t=t||{};var r=typeof e;if("string"===r&&e.length>0)return c(e);if("number"===r&&isFinite(e))return t.long?u(e):d(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},{}],46:[function(e,t,r){const n=e("./lib/number-allocator.js");t.exports.NumberAllocator=n},{"./lib/number-allocator.js":47}],47:[function(e,t,r){const n=e("js-sdsl").Set,s=e("debug")("number-allocator:trace"),i=e("debug")("number-allocator:error");function a(e,t){this.low=e,this.high=t}function o(e,t){if(!(this instanceof o))return new o(e,t);this.min=e,this.max=t,this.ss=new n([],((e,t)=>e.compare(t))),s("Create"),this.clear()}a.prototype.equals=function(e){return this.low===e.low&&this.high===e.high},a.prototype.compare=function(e){return this.low<e.low&&this.high<e.low?-1:e.low<this.low&&e.high<this.low?1:0},o.prototype.firstVacant=function(){return 0===this.ss.size()?null:this.ss.front().low},o.prototype.alloc=function(){if(0===this.ss.size())return s("alloc():empty"),null;const e=this.ss.front(),t=e.low;return t+1<=e.high?++e.low:this.ss.eraseElementByPos(0),s("alloc():"+t),t},o.prototype.use=function(e){const t=new a(e,e),r=this.ss.lowerBound(t);if(r){if(r.equals(t))return this.ss.eraseElementByValue(r),s("use():"+e),!0;if(r.low>e)return!1;if(r.low===e)return++r.low,s("use():"+e),!0;if(r.high===e)return--r.high,s("use():"+e),!0;const n=r.low;return r.low=e+1,this.ss.insert(new a(n,e-1)),s("use():"+e),!0}return s("use():failed"),!1},o.prototype.free=function(e){if(e<this.min||e>this.max)return void i("free():"+e+" is out of range");const t=new a(e,e),r=this.ss.lowerBound(t);if(r){if(r.low<=e&&e<=r.high)return void i("free():"+e+" has already been vacant");if(r===this.ss.front())e+1===r.low?--r.low:this.ss.insert(t);else{const n=this.ss.reverseLowerBound(t);n.high+1===e?e+1===r.low?(this.ss.eraseElementByValue(n),r.low=n.low):n.high=e:e+1===r.low?r.low=e:this.ss.insert(t)}}else{if(r===this.ss.front())return void this.ss.insert(t);const n=this.ss.reverseLowerBound(t);n.high+1===e?n.high=e:this.ss.insert(t)}s("free():"+e)},o.prototype.clear=function(){s("clear()"),this.ss.clear(),this.ss.insert(new a(this.min,this.max))},o.prototype.intervalCount=function(){return this.ss.size()},o.prototype.dump=function(){console.log("length:"+this.ss.size());for(const e of this.ss)console.log(e)},t.exports=o},{debug:18,"js-sdsl":36}],48:[function(e,t,r){var n=e("wrappy");function s(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function i(e){var t=function(){if(t.called)throw new Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)},r=e.name||"Function wrapped with `once`";return t.onceError=r+" shouldn't be called more than once",t.called=!1,t}t.exports=n(s),t.exports.strict=n(i),s.proto=s((function(){Object.defineProperty(Function.prototype,"once",{value:function(){return s(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return i(this)},configurable:!0})}))},{wrappy:79}],49:[function(e,t,r){(function(e){(function(){function r(t,r,n,s){if("function"!=typeof t)throw new TypeError('"callback" argument must be a function');var i,a,o=arguments.length;switch(o){case 0:case 1:return e.nextTick(t);case 2:return e.nextTick((function(){t.call(null,r)}));case 3:return e.nextTick((function(){t.call(null,r,n)}));case 4:return e.nextTick((function(){t.call(null,r,n,s)}));default:for(i=new Array(o-1),a=0;a<i.length;)i[a++]=arguments[a];return e.nextTick((function(){t.apply(null,i)}))}}void 0===e||!e.version||0===e.version.indexOf("v0.")||0===e.version.indexOf("v1.")&&0!==e.version.indexOf("v1.8.")?t.exports={nextTick:r}:t.exports=e}).call(this)}).call(this,e("_process"))},{_process:50}],50:[function(e,t,r){var n,s,i=t.exports={};function a(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function l(e){if(n===setTimeout)return setTimeout(e,0);if((n===a||!n)&&setTimeout)return n=setTimeout,setTimeout(e,0);try{return n(e,0)}catch(t){try{return n.call(null,e,0)}catch(t){return n.call(this,e,0)}}}function c(e){if(s===clearTimeout)return clearTimeout(e);if((s===o||!s)&&clearTimeout)return s=clearTimeout,clearTimeout(e);try{return s(e)}catch(t){try{return s.call(null,e)}catch(t){return s.call(this,e)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:a}catch(e){n=a}try{s="function"==typeof clearTimeout?clearTimeout:o}catch(e){s=o}}();var d,u=[],h=!1,f=-1;function p(){h&&d&&(h=!1,d.length?u=d.concat(u):f=-1,u.length&&g())}function g(){if(!h){var e=l(p);h=!0;for(var t=u.length;t;){for(d=u,u=[];++f<t;)d&&d[f].run();f=-1,t=u.length}d=null,h=!1,c(e)}}function m(e,t){this.fun=e,this.array=t}function y(){}i.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];u.push(new m(e,t)),1!==u.length||h||l(g)},m.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=y,i.addListener=y,i.once=y,i.off=y,i.removeListener=y,i.removeAllListeners=y,i.emit=y,i.prependListener=y,i.prependOnceListener=y,i.listeners=function(e){return[]},i.binding=function(e){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(e){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},{}],51:[function(e,t,r){(function(e){(function(){!function(n){var s="object"==typeof r&&r&&!r.nodeType&&r,i="object"==typeof t&&t&&!t.nodeType&&t,a="object"==typeof e&&e;a.global!==a&&a.window!==a&&a.self!==a||(n=a);var o,l,c=2147483647,d=36,u=1,h=26,f=38,p=700,g=72,m=128,y="-",v=/^xn--/,b=/[^\x20-\x7E]/,w=/[\x2E\u3002\uFF0E\uFF61]/g,E={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},S=d-u,T=Math.floor,C=String.fromCharCode;function k(e){throw new RangeError(E[e])}function A(e,t){for(var r=e.length,n=[];r--;)n[r]=t(e[r]);return n}function I(e,t){var r=e.split("@"),n="";return r.length>1&&(n=r[0]+"@",e=r[1]),n+A((e=e.replace(w,".")).split("."),t).join(".")}function _(e){for(var t,r,n=[],s=0,i=e.length;s<i;)(t=e.charCodeAt(s++))>=55296&&t<=56319&&s<i?56320==(64512&(r=e.charCodeAt(s++)))?n.push(((1023&t)<<10)+(1023&r)+65536):(n.push(t),s--):n.push(t);return n}function R(e){return A(e,(function(e){var t="";return e>65535&&(t+=C((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=C(e)})).join("")}function L(e){return e-48<10?e-22:e-65<26?e-65:e-97<26?e-97:d}function D(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function x(e,t,r){var n=0;for(e=r?T(e/p):e>>1,e+=T(e/t);e>S*h>>1;n+=d)e=T(e/S);return T(n+(S+1)*e/(e+f))}function O(e){var t,r,n,s,i,a,o,l,f,p,v=[],b=e.length,w=0,E=m,S=g;for((r=e.lastIndexOf(y))<0&&(r=0),n=0;n<r;++n)e.charCodeAt(n)>=128&&k("not-basic"),v.push(e.charCodeAt(n));for(s=r>0?r+1:0;s<b;){for(i=w,a=1,o=d;s>=b&&k("invalid-input"),((l=L(e.charCodeAt(s++)))>=d||l>T((c-w)/a))&&k("overflow"),w+=l*a,!(l<(f=o<=S?u:o>=S+h?h:o-S));o+=d)a>T(c/(p=d-f))&&k("overflow"),a*=p;S=x(w-i,t=v.length+1,0==i),T(w/t)>c-E&&k("overflow"),E+=T(w/t),w%=t,v.splice(w++,0,E)}return R(v)}function P(e){var t,r,n,s,i,a,o,l,f,p,v,b,w,E,S,A=[];for(b=(e=_(e)).length,t=m,r=0,i=g,a=0;a<b;++a)(v=e[a])<128&&A.push(C(v));for(n=s=A.length,s&&A.push(y);n<b;){for(o=c,a=0;a<b;++a)(v=e[a])>=t&&v<o&&(o=v);for(o-t>T((c-r)/(w=n+1))&&k("overflow"),r+=(o-t)*w,t=o,a=0;a<b;++a)if((v=e[a])<t&&++r>c&&k("overflow"),v==t){for(l=r,f=d;!(l<(p=f<=i?u:f>=i+h?h:f-i));f+=d)S=l-p,E=d-p,A.push(C(D(p+S%E,0))),l=T(S/E);A.push(C(D(l,0))),i=x(r,w,n==s),r=0,++n}++r,++t}return A.join("")}function M(e){return I(e,(function(e){return v.test(e)?O(e.slice(4).toLowerCase()):e}))}function F(e){return I(e,(function(e){return b.test(e)?"xn--"+P(e):e}))}if(o={version:"1.4.1",ucs2:{decode:_,encode:R},decode:O,encode:P,toASCII:F,toUnicode:M},s&&i)if(t.exports==s)i.exports=o;else for(l in o)o.hasOwnProperty(l)&&(s[l]=o[l]);else n.punycode=o}(this)}).call(this)}).call(this,void 0!==ft?ft:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],52:[function(e,t,r){function n(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.exports=function(e,t,r,i){t=t||"&",r=r||"=";var a={};if("string"!=typeof e||0===e.length)return a;var o=/\+/g;e=e.split(t);var l=1e3;i&&"number"==typeof i.maxKeys&&(l=i.maxKeys);var c=e.length;l>0&&c>l&&(c=l);for(var d=0;d<c;++d){var u,h,f,p,g=e[d].replace(o,"%20"),m=g.indexOf(r);m>=0?(u=g.substr(0,m),h=g.substr(m+1)):(u=g,h=""),f=decodeURIComponent(u),p=decodeURIComponent(h),n(a,f)?s(a[f])?a[f].push(p):a[f]=[a[f],p]:a[f]=p}return a};var s=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],53:[function(e,t,r){var n=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,r,o){return t=t||"&",r=r||"=",null===e&&(e=void 0),"object"==typeof e?i(a(e),(function(a){var o=encodeURIComponent(n(a))+r;return s(e[a])?i(e[a],(function(e){return o+encodeURIComponent(n(e))})).join(t):o+encodeURIComponent(n(e[a]))})).join(t):o?encodeURIComponent(n(o))+r+encodeURIComponent(n(e)):""};var s=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function i(e,t){if(e.map)return e.map(t);for(var r=[],n=0;n<e.length;n++)r.push(t(e[n],n));return r}var a=Object.keys||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t}},{}],54:[function(e,t,r){r.decode=r.parse=e("./decode"),r.encode=r.stringify=e("./encode")},{"./decode":52,"./encode":53}],55:[function(e,t,r){function n(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}var s={};function i(e,t,r){function i(e,r,n){return"string"==typeof t?t:t(e,r,n)}r||(r=Error);var a=function(e){function t(t,r,n){return e.call(this,i(t,r,n))||this}return n(t,e),t}(r);a.prototype.name=r.name,a.prototype.code=e,s[e]=a}function a(e,t){if(Array.isArray(e)){var r=e.length;return e=e.map((function(e){return String(e)})),r>2?"one of ".concat(t," ").concat(e.slice(0,r-1).join(", "),", or ")+e[r-1]:2===r?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}function o(e,t,r){return e.substr(!r||r<0?0:+r,t.length)===t}function l(e,t,r){return(void 0===r||r>e.length)&&(r=e.length),e.substring(r-t.length,r)===t}function c(e,t,r){return"number"!=typeof r&&(r=0),!(r+t.length>e.length)&&-1!==e.indexOf(t,r)}i("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError),i("ERR_INVALID_ARG_TYPE",(function(e,t,r){var n,s;if("string"==typeof t&&o(t,"not ")?(n="must not be",t=t.replace(/^not /,"")):n="must be",l(e," argument"))s="The ".concat(e," ").concat(n," ").concat(a(t,"type"));else{var i=c(e,".")?"property":"argument";s='The "'.concat(e,'" ').concat(i," ").concat(n," ").concat(a(t,"type"))}return s+=". Received type ".concat(typeof r)}),TypeError),i("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),i("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"})),i("ERR_STREAM_PREMATURE_CLOSE","Premature close"),i("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"})),i("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),i("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),i("ERR_STREAM_WRITE_AFTER_END","write after end"),i("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),i("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError),i("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),t.exports.codes=s},{}],56:[function(e,t,r){(function(r){(function(){var n=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};t.exports=c;var s=e("./_stream_readable"),i=e("./_stream_writable");e("inherits")(c,s);for(var a=n(i.prototype),o=0;o<a.length;o++){var l=a[o];c.prototype[l]||(c.prototype[l]=i.prototype[l])}function c(e){if(!(this instanceof c))return new c(e);s.call(this,e),i.call(this,e),this.allowHalfOpen=!0,e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",d)))}function d(){this._writableState.ended||r.nextTick(u,this)}function u(e){e.end()}Object.defineProperty(c.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(c.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(c.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(c.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&this._readableState.destroyed&&this._writableState.destroyed},set:function(e){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}})}).call(this)}).call(this,e("_process"))},{"./_stream_readable":58,"./_stream_writable":60,_process:50,inherits:24}],57:[function(e,t,r){t.exports=s;var n=e("./_stream_transform");function s(e){if(!(this instanceof s))return new s(e);n.call(this,e)}e("inherits")(s,n),s.prototype._transform=function(e,t,r){r(null,e)}},{"./_stream_transform":59,inherits:24}],58:[function(e,t,r){(function(r,n){(function(){var s;t.exports=_,_.ReadableState=I,e("events").EventEmitter;var i=function(e,t){return e.listeners(t).length},a=e("./internal/streams/stream"),o=e("buffer").Buffer,l=n.Uint8Array||function(){};function c(e){return o.from(e)}function d(e){return o.isBuffer(e)||e instanceof l}var u,h=e("util");u=h&&h.debuglog?h.debuglog("stream"):function(){};var f,p,g,m=e("./internal/streams/buffer_list"),y=e("./internal/streams/destroy"),v=e("./internal/streams/state").getHighWaterMark,b=e("../errors").codes,w=b.ERR_INVALID_ARG_TYPE,E=b.ERR_STREAM_PUSH_AFTER_EOF,S=b.ERR_METHOD_NOT_IMPLEMENTED,T=b.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;e("inherits")(_,a);var C=y.errorOrDestroy,k=["error","close","destroy","pause","resume"];function A(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}function I(t,r,n){s=s||e("./_stream_duplex"),t=t||{},"boolean"!=typeof n&&(n=r instanceof s),this.objectMode=!!t.objectMode,n&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=v(this,t,"readableHighWaterMark",n),this.buffer=new m,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(f||(f=e("string_decoder/").StringDecoder),this.decoder=new f(t.encoding),this.encoding=t.encoding)}function _(t){if(s=s||e("./_stream_duplex"),!(this instanceof _))return new _(t);var r=this instanceof s;this._readableState=new I(t,this,r),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),a.call(this)}function R(e,t,r,n,s){u("readableAddChunk",t);var i,a=e._readableState;if(null===t)a.reading=!1,M(e,a);else if(s||(i=D(a,t)),i)C(e,i);else if(a.objectMode||t&&t.length>0)if("string"==typeof t||a.objectMode||Object.getPrototypeOf(t)===o.prototype||(t=c(t)),n)a.endEmitted?C(e,new T):L(e,a,t,!0);else if(a.ended)C(e,new E);else{if(a.destroyed)return!1;a.reading=!1,a.decoder&&!r?(t=a.decoder.write(t),a.objectMode||0!==t.length?L(e,a,t,!1):N(e,a)):L(e,a,t,!1)}else n||(a.reading=!1,N(e,a));return!a.ended&&(a.length<a.highWaterMark||0===a.length)}function L(e,t,r,n){t.flowing&&0===t.length&&!t.sync?(t.awaitDrain=0,e.emit("data",r)):(t.length+=t.objectMode?1:r.length,n?t.buffer.unshift(r):t.buffer.push(r),t.needReadable&&F(e)),N(e,t)}function D(e,t){var r;return d(t)||"string"==typeof t||void 0===t||e.objectMode||(r=new w("chunk",["string","Buffer","Uint8Array"],t)),r}Object.defineProperty(_.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),_.prototype.destroy=y.destroy,_.prototype._undestroy=y.undestroy,_.prototype._destroy=function(e,t){t(e)},_.prototype.push=function(e,t){var r,n=this._readableState;return n.objectMode?r=!0:"string"==typeof e&&((t=t||n.defaultEncoding)!==n.encoding&&(e=o.from(e,t),t=""),r=!0),R(this,e,t,!1,r)},_.prototype.unshift=function(e){return R(this,e,null,!0,!1)},_.prototype.isPaused=function(){return!1===this._readableState.flowing},_.prototype.setEncoding=function(t){f||(f=e("string_decoder/").StringDecoder);var r=new f(t);this._readableState.decoder=r,this._readableState.encoding=this._readableState.decoder.encoding;for(var n=this._readableState.buffer.head,s="";null!==n;)s+=r.write(n.data),n=n.next;return this._readableState.buffer.clear(),""!==s&&this._readableState.buffer.push(s),this._readableState.length=s.length,this};var x=1073741824;function O(e){return e>=x?e=x:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function P(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!=e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=O(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function M(e,t){if(u("onEofChunk"),!t.ended){if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length)}t.ended=!0,t.sync?F(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,U(e)))}}function F(e){var t=e._readableState;u("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(u("emitReadable",t.flowing),t.emittedReadable=!0,r.nextTick(U,e))}function U(e){var t=e._readableState;u("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,H(e)}function N(e,t){t.readingMore||(t.readingMore=!0,r.nextTick(B,e,t))}function B(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&0===t.length);){var r=t.length;if(u("maybeReadMore read 0"),e.read(0),r===t.length)break}t.readingMore=!1}function j(e){return function(){var t=e._readableState;u("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&i(e,"data")&&(t.flowing=!0,H(e))}}function $(e){var t=e._readableState;t.readableListening=e.listenerCount("readable")>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function q(e){u("readable nexttick read 0"),e.read(0)}function K(e,t){t.resumeScheduled||(t.resumeScheduled=!0,r.nextTick(G,e,t))}function G(e,t){u("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),H(e),t.flowing&&!t.reading&&e.read(0)}function H(e){var t=e._readableState;for(u("flow",t.flowing);t.flowing&&null!==e.read(););}function V(e,t){return 0===t.length?null:(t.objectMode?r=t.buffer.shift():!e||e>=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):r=t.buffer.consume(e,t.decoder),r);var r}function z(e){var t=e._readableState;u("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,r.nextTick(W,t,e))}function W(e,t){if(u("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var r=t._writableState;(!r||r.autoDestroy&&r.finished)&&t.destroy()}}function Y(e,t){for(var r=0,n=e.length;r<n;r++)if(e[r]===t)return r;return-1}_.prototype.read=function(e){u("read",e),e=parseInt(e,10);var t=this._readableState,r=e;if(0!==e&&(t.emittedReadable=!1),0===e&&t.needReadable&&((0!==t.highWaterMark?t.length>=t.highWaterMark:t.length>0)||t.ended))return u("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?z(this):F(this),null;if(0===(e=P(e,t))&&t.ended)return 0===t.length&&z(this),null;var n,s=t.needReadable;return u("need readable",s),(0===t.length||t.length-e<t.highWaterMark)&&u("length less than watermark",s=!0),t.ended||t.reading?u("reading or ended",s=!1):s&&(u("do read"),t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=P(r,t))),null===(n=e>0?V(e,t):null)?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&z(this)),null!==n&&this.emit("data",n),n},_.prototype._read=function(e){C(this,new S("_read()"))},_.prototype.pipe=function(e,t){var n=this,s=this._readableState;switch(s.pipesCount){case 0:s.pipes=e;break;case 1:s.pipes=[s.pipes,e];break;default:s.pipes.push(e)}s.pipesCount+=1,u("pipe count=%d opts=%j",s.pipesCount,t);var a=t&&!1===t.end||e===r.stdout||e===r.stderr?y:l;function o(e,t){u("onunpipe"),e===n&&t&&!1===t.hasUnpiped&&(t.hasUnpiped=!0,h())}function l(){u("onend"),e.end()}s.endEmitted?r.nextTick(a):n.once("end",a),e.on("unpipe",o);var c=j(n);e.on("drain",c);var d=!1;function h(){u("cleanup"),e.removeListener("close",g),e.removeListener("finish",m),e.removeListener("drain",c),e.removeListener("error",p),e.removeListener("unpipe",o),n.removeListener("end",l),n.removeListener("end",y),n.removeListener("data",f),d=!0,!s.awaitDrain||e._writableState&&!e._writableState.needDrain||c()}function f(t){u("ondata");var r=e.write(t);u("dest.write",r),!1===r&&((1===s.pipesCount&&s.pipes===e||s.pipesCount>1&&-1!==Y(s.pipes,e))&&!d&&(u("false write response, pause",s.awaitDrain),s.awaitDrain++),n.pause())}function p(t){u("onerror",t),y(),e.removeListener("error",p),0===i(e,"error")&&C(e,t)}function g(){e.removeListener("finish",m),y()}function m(){u("onfinish"),e.removeListener("close",g),y()}function y(){u("unpipe"),n.unpipe(e)}return n.on("data",f),A(e,"error",p),e.once("close",g),e.once("finish",m),e.emit("pipe",n),s.flowing||(u("pipe resume"),n.resume()),e},_.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,r)),this;if(!e){var n=t.pipes,s=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;i<s;i++)n[i].emit("unpipe",this,{hasUnpiped:!1});return this}var a=Y(t.pipes,e);return-1===a||(t.pipes.splice(a,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,r)),this},_.prototype.on=function(e,t){var n=a.prototype.on.call(this,e,t),s=this._readableState;return"data"===e?(s.readableListening=this.listenerCount("readable")>0,!1!==s.flowing&&this.resume()):"readable"===e&&(s.endEmitted||s.readableListening||(s.readableListening=s.needReadable=!0,s.flowing=!1,s.emittedReadable=!1,u("on readable",s.length,s.reading),s.length?F(this):s.reading||r.nextTick(q,this))),n},_.prototype.addListener=_.prototype.on,_.prototype.removeListener=function(e,t){var n=a.prototype.removeListener.call(this,e,t);return"readable"===e&&r.nextTick($,this),n},_.prototype.removeAllListeners=function(e){var t=a.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||r.nextTick($,this),t},_.prototype.resume=function(){var e=this._readableState;return e.flowing||(u("resume"),e.flowing=!e.readableListening,K(this,e)),e.paused=!1,this},_.prototype.pause=function(){return u("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(u("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},_.prototype.wrap=function(e){var t=this,r=this._readableState,n=!1;for(var s in e.on("end",(function(){if(u("wrapped end"),r.decoder&&!r.ended){var e=r.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(s){u("wrapped data"),r.decoder&&(s=r.decoder.write(s)),r.objectMode&&null==s||(r.objectMode||s&&s.length)&&(t.push(s)||(n=!0,e.pause()))})),e)void 0===this[s]&&"function"==typeof e[s]&&(this[s]=function(t){return function(){return e[t].apply(e,arguments)}}(s));for(var i=0;i<k.length;i++)e.on(k[i],this.emit.bind(this,k[i]));return this._read=function(t){u("wrapped _read",t),n&&(n=!1,e.resume())},this},"function"==typeof Symbol&&(_.prototype[Symbol.asyncIterator]=function(){return void 0===p&&(p=e("./internal/streams/async_iterator")),p(this)}),Object.defineProperty(_.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(_.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(_.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),_._fromList=V,Object.defineProperty(_.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(_.from=function(t,r){return void 0===g&&(g=e("./internal/streams/from")),g(_,t,r)})}).call(this)}).call(this,e("_process"),void 0!==ft?ft:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":55,"./_stream_duplex":56,"./internal/streams/async_iterator":61,"./internal/streams/buffer_list":62,"./internal/streams/destroy":63,"./internal/streams/from":65,"./internal/streams/state":67,"./internal/streams/stream":68,_process:50,buffer:17,events:22,inherits:24,"string_decoder/":75,util:16}],59:[function(e,t,r){t.exports=d;var n=e("../errors").codes,s=n.ERR_METHOD_NOT_IMPLEMENTED,i=n.ERR_MULTIPLE_CALLBACK,a=n.ERR_TRANSFORM_ALREADY_TRANSFORMING,o=n.ERR_TRANSFORM_WITH_LENGTH_0,l=e("./_stream_duplex");function c(e,t){var r=this._transformState;r.transforming=!1;var n=r.writecb;if(null===n)return this.emit("error",new i);r.writechunk=null,r.writecb=null,null!=t&&this.push(t),n(e);var s=this._readableState;s.reading=!1,(s.needReadable||s.length<s.highWaterMark)&&this._read(s.highWaterMark)}function d(e){if(!(this instanceof d))return new d(e);l.call(this,e),this._transformState={afterTransform:c.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),this.on("prefinish",u)}function u(){var e=this;"function"!=typeof this._flush||this._readableState.destroyed?h(this,null,null):this._flush((function(t,r){h(e,t,r)}))}function h(e,t,r){if(t)return e.emit("error",t);if(null!=r&&e.push(r),e._writableState.length)throw new o;if(e._transformState.transforming)throw new a;return e.push(null)}e("inherits")(d,l),d.prototype.push=function(e,t){return this._transformState.needTransform=!1,l.prototype.push.call(this,e,t)},d.prototype._transform=function(e,t,r){r(new s("_transform()"))},d.prototype._write=function(e,t,r){var n=this._transformState;if(n.writecb=r,n.writechunk=e,n.writeencoding=t,!n.transforming){var s=this._readableState;(n.needTransform||s.needReadable||s.length<s.highWaterMark)&&this._read(s.highWaterMark)}},d.prototype._read=function(e){var t=this._transformState;null===t.writechunk||t.transforming?t.needTransform=!0:(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform))},d.prototype._destroy=function(e,t){l.prototype._destroy.call(this,e,(function(e){t(e)}))}},{"../errors":55,"./_stream_duplex":56,inherits:24}],60:[function(e,t,r){(function(r,n){(function(){function s(e){var t=this;this.next=null,this.entry=null,this.finish=function(){G(t,e)}}var i;t.exports=I,I.WritableState=A;var a={deprecate:e("util-deprecate")},o=e("./internal/streams/stream"),l=e("buffer").Buffer,c=n.Uint8Array||function(){};function d(e){return l.from(e)}function u(e){return l.isBuffer(e)||e instanceof c}var h,f=e("./internal/streams/destroy"),p=e("./internal/streams/state").getHighWaterMark,g=e("../errors").codes,m=g.ERR_INVALID_ARG_TYPE,y=g.ERR_METHOD_NOT_IMPLEMENTED,v=g.ERR_MULTIPLE_CALLBACK,b=g.ERR_STREAM_CANNOT_PIPE,w=g.ERR_STREAM_DESTROYED,E=g.ERR_STREAM_NULL_VALUES,S=g.ERR_STREAM_WRITE_AFTER_END,T=g.ERR_UNKNOWN_ENCODING,C=f.errorOrDestroy;function k(){}function A(t,r,n){i=i||e("./_stream_duplex"),t=t||{},"boolean"!=typeof n&&(n=r instanceof i),this.objectMode=!!t.objectMode,n&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=p(this,t,"writableHighWaterMark",n),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var a=!1===t.decodeStrings;this.decodeStrings=!a,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){M(r,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new s(this)}function I(t){var r=this instanceof(i=i||e("./_stream_duplex"));if(!r&&!h.call(I,this))return new I(t);this._writableState=new A(t,this,r),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),o.call(this)}function _(e,t){var n=new S;C(e,n),r.nextTick(t,n)}function R(e,t,n,s){var i;return null===n?i=new E:"string"==typeof n||t.objectMode||(i=new m("chunk",["string","Buffer"],n)),!i||(C(e,i),r.nextTick(s,i),!1)}function L(e,t,r){return e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=l.from(t,r)),t}function D(e,t,r,n,s,i){if(!r){var a=L(t,n,s);n!==a&&(r=!0,s="buffer",n=a)}var o=t.objectMode?1:n.length;t.length+=o;var l=t.length<t.highWaterMark;if(l||(t.needDrain=!0),t.writing||t.corked){var c=t.lastBufferedRequest;t.lastBufferedRequest={chunk:n,encoding:s,isBuf:r,callback:i,next:null},c?c.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else x(e,t,!1,o,n,s,i);return l}function x(e,t,r,n,s,i,a){t.writelen=n,t.writecb=a,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new w("write")):r?e._writev(s,t.onwrite):e._write(s,i,t.onwrite),t.sync=!1}function O(e,t,n,s,i){--t.pendingcb,n?(r.nextTick(i,s),r.nextTick(q,e,t),e._writableState.errorEmitted=!0,C(e,s)):(i(s),e._writableState.errorEmitted=!0,C(e,s),q(e,t))}function P(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function M(e,t){var n=e._writableState,s=n.sync,i=n.writecb;if("function"!=typeof i)throw new v;if(P(n),t)O(e,n,s,t,i);else{var a=B(n)||e.destroyed;a||n.corked||n.bufferProcessing||!n.bufferedRequest||N(e,n),s?r.nextTick(F,e,n,a,i):F(e,n,a,i)}}function F(e,t,r,n){r||U(e,t),t.pendingcb--,n(),q(e,t)}function U(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}function N(e,t){t.bufferProcessing=!0;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var n=t.bufferedRequestCount,i=new Array(n),a=t.corkedRequestsFree;a.entry=r;for(var o=0,l=!0;r;)i[o]=r,r.isBuf||(l=!1),r=r.next,o+=1;i.allBuffers=l,x(e,t,!0,t.length,i,"",a.finish),t.pendingcb++,t.lastBufferedRequest=null,a.next?(t.corkedRequestsFree=a.next,a.next=null):t.corkedRequestsFree=new s(t),t.bufferedRequestCount=0}else{for(;r;){var c=r.chunk,d=r.encoding,u=r.callback;if(x(e,t,!1,t.objectMode?1:c.length,c,d,u),r=r.next,t.bufferedRequestCount--,t.writing)break}null===r&&(t.lastBufferedRequest=null)}t.bufferedRequest=r,t.bufferProcessing=!1}function B(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function j(e,t){e._final((function(r){t.pendingcb--,r&&C(e,r),t.prefinished=!0,e.emit("prefinish"),q(e,t)}))}function $(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.pendingcb++,t.finalCalled=!0,r.nextTick(j,e,t)))}function q(e,t){var r=B(t);if(r&&($(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"),t.autoDestroy))){var n=e._readableState;(!n||n.autoDestroy&&n.endEmitted)&&e.destroy()}return r}function K(e,t,n){t.ending=!0,q(e,t),n&&(t.finished?r.nextTick(n):e.once("finish",n)),t.ended=!0,e.writable=!1}function G(e,t,r){var n=e.entry;for(e.entry=null;n;){var s=n.callback;t.pendingcb--,s(r),n=n.next}t.corkedRequestsFree.next=e}e("inherits")(I,o),A.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(A.prototype,"buffer",{get:a.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(h=Function.prototype[Symbol.hasInstance],Object.defineProperty(I,Symbol.hasInstance,{value:function(e){return!!h.call(this,e)||this===I&&e&&e._writableState instanceof A}})):h=function(e){return e instanceof this},I.prototype.pipe=function(){C(this,new b)},I.prototype.write=function(e,t,r){var n=this._writableState,s=!1,i=!n.objectMode&&u(e);return i&&!l.isBuffer(e)&&(e=d(e)),"function"==typeof t&&(r=t,t=null),i?t="buffer":t||(t=n.defaultEncoding),"function"!=typeof r&&(r=k),n.ending?_(this,r):(i||R(this,n,e,r))&&(n.pendingcb++,s=D(this,n,i,e,t,r)),s},I.prototype.cork=function(){this._writableState.corked++},I.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.bufferProcessing||!e.bufferedRequest||N(this,e))},I.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new T(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(I.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(I.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),I.prototype._write=function(e,t,r){r(new y("_write()"))},I.prototype._writev=null,I.prototype.end=function(e,t,r){var n=this._writableState;return"function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!=e&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||K(this,n,r),this},Object.defineProperty(I.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(I.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),I.prototype.destroy=f.destroy,I.prototype._undestroy=f.undestroy,I.prototype._destroy=function(e,t){t(e)}}).call(this)}).call(this,e("_process"),void 0!==ft?ft:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":55,"./_stream_duplex":56,"./internal/streams/destroy":63,"./internal/streams/state":67,"./internal/streams/stream":68,_process:50,buffer:17,inherits:24,"util-deprecate":78}],61:[function(e,t,r){(function(r){(function(){var n;function s(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var i=e("./end-of-stream"),a=Symbol("lastResolve"),o=Symbol("lastReject"),l=Symbol("error"),c=Symbol("ended"),d=Symbol("lastPromise"),u=Symbol("handlePromise"),h=Symbol("stream");function f(e,t){return{value:e,done:t}}function p(e){var t=e[a];if(null!==t){var r=e[h].read();null!==r&&(e[d]=null,e[a]=null,e[o]=null,t(f(r,!1)))}}function g(e){r.nextTick(p,e)}function m(e,t){return function(r,n){e.then((function(){t[c]?r(f(void 0,!0)):t[u](r,n)}),n)}}var y=Object.getPrototypeOf((function(){})),v=Object.setPrototypeOf((s(n={get stream(){return this[h]},next:function(){var e=this,t=this[l];if(null!==t)return Promise.reject(t);if(this[c])return Promise.resolve(f(void 0,!0));if(this[h].destroyed)return new Promise((function(t,n){r.nextTick((function(){e[l]?n(e[l]):t(f(void 0,!0))}))}));var n,s=this[d];if(s)n=new Promise(m(s,this));else{var i=this[h].read();if(null!==i)return Promise.resolve(f(i,!1));n=new Promise(this[u])}return this[d]=n,n}},Symbol.asyncIterator,(function(){return this})),s(n,"return",(function(){var e=this;return new Promise((function(t,r){e[h].destroy(null,(function(e){e?r(e):t(f(void 0,!0))}))}))})),n),y),b=function(e){var t,r=Object.create(v,(s(t={},h,{value:e,writable:!0}),s(t,a,{value:null,writable:!0}),s(t,o,{value:null,writable:!0}),s(t,l,{value:null,writable:!0}),s(t,c,{value:e._readableState.endEmitted,writable:!0}),s(t,u,{value:function(e,t){var n=r[h].read();n?(r[d]=null,r[a]=null,r[o]=null,e(f(n,!1))):(r[a]=e,r[o]=t)},writable:!0}),t));return r[d]=null,i(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=r[o];return null!==t&&(r[d]=null,r[a]=null,r[o]=null,t(e)),void(r[l]=e)}var n=r[a];null!==n&&(r[d]=null,r[a]=null,r[o]=null,n(f(void 0,!0))),r[c]=!0})),e.on("readable",g.bind(null,r)),r};t.exports=b}).call(this)}).call(this,e("_process"))},{"./end-of-stream":64,_process:50}],62:[function(e,t,r){function n(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function s(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?n(Object(r),!0).forEach((function(t){i(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):n(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function i(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function l(e,t,r){return t&&o(e.prototype,t),r&&o(e,r),e}var c=e("buffer").Buffer,d=e("util").inspect,u=d&&d.custom||"inspect";function h(e,t,r){c.prototype.copy.call(e,t,r)}t.exports=function(){function e(){a(this,e),this.head=null,this.tail=null,this.length=0}return l(e,[{key:"push",value:function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:"unshift",value:function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}},{key:"shift",value:function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r}},{key:"concat",value:function(e){if(0===this.length)return c.alloc(0);for(var t=c.allocUnsafe(e>>>0),r=this.head,n=0;r;)h(r.data,t,n),n+=r.data.length,r=r.next;return t}},{key:"consume",value:function(e,t){var r;return e<this.head.data.length?(r=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):r=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),r}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(e){var t=this.head,r=1,n=t.data;for(e-=n.length;t=t.next;){var s=t.data,i=e>s.length?s.length:e;if(i===s.length?n+=s:n+=s.slice(0,e),0==(e-=i)){i===s.length?(++r,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=s.slice(i));break}++r}return this.length-=r,n}},{key:"_getBuffer",value:function(e){var t=c.allocUnsafe(e),r=this.head,n=1;for(r.data.copy(t),e-=r.data.length;r=r.next;){var s=r.data,i=e>s.length?s.length:e;if(s.copy(t,t.length-e,0,i),0==(e-=i)){i===s.length?(++n,r.next?this.head=r.next:this.head=this.tail=null):(this.head=r,r.data=s.slice(i));break}++n}return this.length-=n,t}},{key:u,value:function(e,t){return d(this,s({},t,{depth:0,customInspect:!1}))}}]),e}()},{buffer:17,util:16}],63:[function(e,t,r){(function(e){(function(){function r(t,r){var i=this,o=this._readableState&&this._readableState.destroyed,l=this._writableState&&this._writableState.destroyed;return o||l?(r?r(t):t&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,e.nextTick(a,this,t)):e.nextTick(a,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,(function(t){!r&&t?i._writableState?i._writableState.errorEmitted?e.nextTick(s,i):(i._writableState.errorEmitted=!0,e.nextTick(n,i,t)):e.nextTick(n,i,t):r?(e.nextTick(s,i),r(t)):e.nextTick(s,i)})),this)}function n(e,t){a(e,t),s(e)}function s(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function i(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function a(e,t){e.emit("error",t)}function o(e,t){var r=e._readableState,n=e._writableState;r&&r.autoDestroy||n&&n.autoDestroy?e.destroy(t):e.emit("error",t)}t.exports={destroy:r,undestroy:i,errorOrDestroy:o}}).call(this)}).call(this,e("_process"))},{_process:50}],64:[function(e,t,r){var n=e("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;function s(e){var t=!1;return function(){if(!t){t=!0;for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];e.apply(this,n)}}}function i(){}function a(e){return e.setHeader&&"function"==typeof e.abort}function o(e,t,r){if("function"==typeof t)return o(e,null,t);t||(t={}),r=s(r||i);var l=t.readable||!1!==t.readable&&e.readable,c=t.writable||!1!==t.writable&&e.writable,d=function(){e.writable||h()},u=e._writableState&&e._writableState.finished,h=function(){c=!1,u=!0,l||r.call(e)},f=e._readableState&&e._readableState.endEmitted,p=function(){l=!1,f=!0,c||r.call(e)},g=function(t){r.call(e,t)},m=function(){var t;return l&&!f?(e._readableState&&e._readableState.ended||(t=new n),r.call(e,t)):c&&!u?(e._writableState&&e._writableState.ended||(t=new n),r.call(e,t)):void 0},y=function(){e.req.on("finish",h)};return a(e)?(e.on("complete",h),e.on("abort",m),e.req?y():e.on("request",y)):c&&!e._writableState&&(e.on("end",d),e.on("close",d)),e.on("end",p),e.on("finish",h),!1!==t.error&&e.on("error",g),e.on("close",m),function(){e.removeListener("complete",h),e.removeListener("abort",m),e.removeListener("request",y),e.req&&e.req.removeListener("finish",h),e.removeListener("end",d),e.removeListener("close",d),e.removeListener("finish",h),e.removeListener("end",p),e.removeListener("error",g),e.removeListener("close",m)}}t.exports=o},{"../../../errors":55}],65:[function(e,t,r){t.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],66:[function(e,t,r){var n;function s(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var i=e("../../../errors").codes,a=i.ERR_MISSING_ARGS,o=i.ERR_STREAM_DESTROYED;function l(e){if(e)throw e}function c(e){return e.setHeader&&"function"==typeof e.abort}function d(t,r,i,a){a=s(a);var l=!1;t.on("close",(function(){l=!0})),void 0===n&&(n=e("./end-of-stream")),n(t,{readable:r,writable:i},(function(e){if(e)return a(e);l=!0,a()}));var d=!1;return function(e){if(!l&&!d)return d=!0,c(t)?t.abort():"function"==typeof t.destroy?t.destroy():void a(e||new o("pipe"))}}function u(e){e()}function h(e,t){return e.pipe(t)}function f(e){return e.length?"function"!=typeof e[e.length-1]?l:e.pop():l}function p(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];var n,s=f(t);if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new a("streams");var i=t.map((function(e,r){var a=r<t.length-1;return d(e,a,r>0,(function(e){n||(n=e),e&&i.forEach(u),a||(i.forEach(u),s(n))}))}));return t.reduce(h)}t.exports=p},{"../../../errors":55,"./end-of-stream":64}],67:[function(e,t,r){var n=e("../../../errors").codes.ERR_INVALID_OPT_VALUE;function s(e,t,r){return null!=e.highWaterMark?e.highWaterMark:t?e[r]:null}function i(e,t,r,i){var a=s(t,i,r);if(null!=a){if(!isFinite(a)||Math.floor(a)!==a||a<0)throw new n(i?r:"highWaterMark",a);return Math.floor(a)}return e.objectMode?16:16384}t.exports={getHighWaterMark:i}},{"../../../errors":55}],68:[function(e,t,r){t.exports=e("events").EventEmitter},{events:22}],69:[function(e,t,r){(r=t.exports=e("./lib/_stream_readable.js")).Stream=r,r.Readable=r,r.Writable=e("./lib/_stream_writable.js"),r.Duplex=e("./lib/_stream_duplex.js"),r.Transform=e("./lib/_stream_transform.js"),r.PassThrough=e("./lib/_stream_passthrough.js"),r.finished=e("./lib/internal/streams/end-of-stream.js"),r.pipeline=e("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":56,"./lib/_stream_passthrough.js":57,"./lib/_stream_readable.js":58,"./lib/_stream_transform.js":59,"./lib/_stream_writable.js":60,"./lib/internal/streams/end-of-stream.js":64,"./lib/internal/streams/pipeline.js":66}],70:[function(e,t,r){function n(e,t,r){var n=this;this._callback=e,this._args=r,this._interval=setInterval(e,t,this._args),this.reschedule=function(e){e||(e=n._interval),n._interval&&clearInterval(n._interval),n._interval=setInterval(n._callback,e,n._args)},this.clear=function(){n._interval&&(clearInterval(n._interval),n._interval=void 0)},this.destroy=function(){n._interval&&clearInterval(n._interval),n._callback=void 0,n._interval=void 0,n._args=void 0}}function s(){if("function"!=typeof arguments[0])throw new Error("callback needed");if("number"!=typeof arguments[1])throw new Error("interval needed");var e;if(arguments.length>0){e=new Array(arguments.length-2);for(var t=0;t<e.length;t++)e[t]=arguments[t+2]}return new n(arguments[0],arguments[1],e)}t.exports=s},{}],71:[function(e,t,r){t.exports=e("./index.js")()},{"./index.js":72}],72:[function(e,t,r){(function(e){(function(){function r(t){return t instanceof e?e.from(t):new t.constructor(t.buffer.slice(),t.byteOffset,t.length)}function n(e){return(e=e||{}).circles?s(e):e.proto?i:n;function t(e,t){for(var n=Object.keys(e),s=new Array(n.length),i=0;i<n.length;i++){var a=n[i],o=e[a];"object"!=typeof o||null===o?s[a]=o:o instanceof Date?s[a]=new Date(o):ArrayBuffer.isView(o)?s[a]=r(o):s[a]=t(o)}return s}function n(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return t(e,n);if(e instanceof Map)return new Map(t(Array.from(e),n));if(e instanceof Set)return new Set(t(Array.from(e),n));var s={};for(var i in e)if(!1!==Object.hasOwnProperty.call(e,i)){var a=e[i];"object"!=typeof a||null===a?s[i]=a:a instanceof Date?s[i]=new Date(a):a instanceof Map?s[i]=new Map(t(Array.from(a),n)):a instanceof Set?s[i]=new Set(t(Array.from(a),n)):ArrayBuffer.isView(a)?s[i]=r(a):s[i]=n(a)}return s}function i(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return t(e,i);if(e instanceof Map)return new Map(t(Array.from(e),i));if(e instanceof Set)return new Set(t(Array.from(e),i));var n={};for(var s in e){var a=e[s];"object"!=typeof a||null===a?n[s]=a:a instanceof Date?n[s]=new Date(a):a instanceof Map?n[s]=new Map(t(Array.from(a),i)):a instanceof Set?n[s]=new Set(t(Array.from(a),i)):ArrayBuffer.isView(a)?n[s]=r(a):n[s]=i(a)}return n}}function s(e){var t=[],n=[];return e.proto?a:i;function s(e,s){for(var i=Object.keys(e),a=new Array(i.length),o=0;o<i.length;o++){var l=i[o],c=e[l];if("object"!=typeof c||null===c)a[l]=c;else if(c instanceof Date)a[l]=new Date(c);else if(ArrayBuffer.isView(c))a[l]=r(c);else{var d=t.indexOf(c);a[l]=-1!==d?n[d]:s(c)}}return a}function i(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return s(e,i);if(e instanceof Map)return new Map(s(Array.from(e),i));if(e instanceof Set)return new Set(s(Array.from(e),i));var a={};for(var o in t.push(e),n.push(a),e)if(!1!==Object.hasOwnProperty.call(e,o)){var l=e[o];if("object"!=typeof l||null===l)a[o]=l;else if(l instanceof Date)a[o]=new Date(l);else if(l instanceof Map)a[o]=new Map(s(Array.from(l),i));else if(l instanceof Set)a[o]=new Set(s(Array.from(l),i));else if(ArrayBuffer.isView(l))a[o]=r(l);else{var c=t.indexOf(l);a[o]=-1!==c?n[c]:i(l)}}return t.pop(),n.pop(),a}function a(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return s(e,a);if(e instanceof Map)return new Map(s(Array.from(e),a));if(e instanceof Set)return new Set(s(Array.from(e),a));var i={};for(var o in t.push(e),n.push(i),e){var l=e[o];if("object"!=typeof l||null===l)i[o]=l;else if(l instanceof Date)i[o]=new Date(l);else if(l instanceof Map)i[o]=new Map(s(Array.from(l),a));else if(l instanceof Set)i[o]=new Set(s(Array.from(l),a));else if(ArrayBuffer.isView(l))i[o]=r(l);else{var c=t.indexOf(l);i[o]=-1!==c?n[c]:a(l)}}return t.pop(),n.pop(),i}}t.exports=n}).call(this)}).call(this,e("buffer").Buffer)},{buffer:17}],73:[function(e,t,r){
5
5
  /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
6
- var n=e("buffer"),s=n.Buffer;function i(e,t){for(var r in e)t[r]=e[r]}function a(e,t,r){return s(e,t,r)}s.from&&s.alloc&&s.allocUnsafe&&s.allocUnsafeSlow?t.exports=n:(i(n,r),r.Buffer=a),a.prototype=Object.create(s.prototype),i(s,a),a.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return s(e,t,r)},a.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=s(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},a.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return s(e)},a.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},{buffer:17}],74:[function(e,t,r){function n(e){var t=e._readableState;return t?t.objectMode||"number"==typeof e._duplexState?e.read():e.read(s(t)):null}function s(e){return e.buffer.length?e.buffer.head?e.buffer.head.data.length:e.buffer[0].length:e.length}t.exports=n},{}],75:[function(e,t,r){var n=e("safe-buffer").Buffer,s=n.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function i(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}function a(e){var t=i(e);if("string"!=typeof t&&(n.isEncoding===s||!s(e)))throw new Error("Unknown encoding: "+e);return t||e}function o(e){var t;switch(this.encoding=a(e),this.encoding){case"utf16le":this.text=p,this.end=g,t=4;break;case"utf8":this.fillLast=u,t=4;break;case"base64":this.text=m,this.end=y,t=3;break;default:return this.write=v,void(this.end=b)}this.lastNeed=0,this.lastTotal=0,this.lastChar=n.allocUnsafe(t)}function l(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function c(e,t,r){var n=t.length-1;if(n<r)return 0;var s=l(t[n]);return s>=0?(s>0&&(e.lastNeed=s-1),s):--n<r||-2===s?0:(s=l(t[n]))>=0?(s>0&&(e.lastNeed=s-2),s):--n<r||-2===s?0:(s=l(t[n]))>=0?(s>0&&(2===s?s=0:e.lastNeed=s-3),s):0}function d(e,t,r){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}function u(e){var t=this.lastTotal-this.lastNeed,r=d(this,e);return void 0!==r?r:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function h(e,t){var r=c(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)}function f(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t}function p(e,t){if((e.length-t)%2==0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function g(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function m(e,t){var r=(e.length-t)%3;return 0===r?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function y(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function v(e){return e.toString(this.encoding)}function b(e){return e&&e.length?this.write(e):""}r.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return"";var t,r;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r<e.length?t?t+this.text(e,r):this.text(e,r):t||""},o.prototype.end=f,o.prototype.text=h,o.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},{"safe-buffer":73}],76:[function(e,t,r){var n=e("punycode"),s=e("./util");function i(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}r.parse=w,r.resolve=S,r.resolveObject=T,r.format=E,r.Url=i;var a=/^([a-z0-9.+-]+:)/i,o=/:[0-9]*$/,l=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,c=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),d=["'"].concat(c),u=["%","/","?",";","#"].concat(d),h=["/","?","#"],f=255,p=/^[+a-z0-9A-Z_-]{0,63}$/,g=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,m={javascript:!0,"javascript:":!0},y={javascript:!0,"javascript:":!0},v={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},b=e("querystring");function w(e,t,r){if(e&&s.isObject(e)&&e instanceof i)return e;var n=new i;return n.parse(e,t,r),n}function E(e){return s.isString(e)&&(e=w(e)),e instanceof i?e.format():i.prototype.format.call(e)}function S(e,t){return w(e,!1,!0).resolve(t)}function T(e,t){return e?w(e,!1,!0).resolveObject(t):t}i.prototype.parse=function(e,t,r){if(!s.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var i=e.indexOf("?"),o=-1!==i&&i<e.indexOf("#")?"?":"#",c=e.split(o),w=/\\/g;c[0]=c[0].replace(w,"/");var E=e=c.join(o);if(E=E.trim(),!r&&1===e.split("#").length){var S=l.exec(E);if(S)return this.path=E,this.href=E,this.pathname=S[1],S[2]?(this.search=S[2],this.query=t?b.parse(this.search.substr(1)):this.search.substr(1)):t&&(this.search="",this.query={}),this}var T=a.exec(E);if(T){var C=(T=T[0]).toLowerCase();this.protocol=C,E=E.substr(T.length)}if(r||T||E.match(/^\/\/[^@\/]+@[^@\/]+/)){var k="//"===E.substr(0,2);!k||T&&y[T]||(E=E.substr(2),this.slashes=!0)}if(!y[T]&&(k||T&&!v[T])){for(var A,I,_=-1,R=0;R<h.length;R++)-1!==(L=E.indexOf(h[R]))&&(-1===_||L<_)&&(_=L);for(-1!==(I=-1===_?E.lastIndexOf("@"):E.lastIndexOf("@",_))&&(A=E.slice(0,I),E=E.slice(I+1),this.auth=decodeURIComponent(A)),_=-1,R=0;R<u.length;R++){var L;-1!==(L=E.indexOf(u[R]))&&(-1===_||L<_)&&(_=L)}-1===_&&(_=E.length),this.host=E.slice(0,_),E=E.slice(_),this.parseHost(),this.hostname=this.hostname||"";var D="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!D)for(var x=this.hostname.split(/\./),O=(R=0,x.length);R<O;R++){var P=x[R];if(P&&!P.match(p)){for(var M="",F=0,U=P.length;F<U;F++)P.charCodeAt(F)>127?M+="x":M+=P[F];if(!M.match(p)){var N=x.slice(0,R),B=x.slice(R+1),j=P.match(g);j&&(N.push(j[1]),B.unshift(j[2])),B.length&&(E="/"+B.join(".")+E),this.hostname=N.join(".");break}}}this.hostname.length>f?this.hostname="":this.hostname=this.hostname.toLowerCase(),D||(this.hostname=n.toASCII(this.hostname));var $=this.port?":"+this.port:"",q=this.hostname||"";this.host=q+$,this.href+=this.host,D&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==E[0]&&(E="/"+E))}if(!m[C])for(R=0,O=d.length;R<O;R++){var K=d[R];if(-1!==E.indexOf(K)){var G=encodeURIComponent(K);G===K&&(G=escape(K)),E=E.split(K).join(G)}}var H=E.indexOf("#");-1!==H&&(this.hash=E.substr(H),E=E.slice(0,H));var V=E.indexOf("?");if(-1!==V?(this.search=E.substr(V),this.query=E.substr(V+1),t&&(this.query=b.parse(this.query)),E=E.slice(0,V)):t&&(this.search="",this.query={}),E&&(this.pathname=E),v[C]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){$=this.pathname||"";var z=this.search||"";this.path=$+z}return this.href=this.format(),this},i.prototype.format=function(){var e=this.auth||"";e&&(e=(e=encodeURIComponent(e)).replace(/%3A/i,":"),e+="@");var t=this.protocol||"",r=this.pathname||"",n=this.hash||"",i=!1,a="";this.host?i=e+this.host:this.hostname&&(i=e+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(i+=":"+this.port)),this.query&&s.isObject(this.query)&&Object.keys(this.query).length&&(a=b.stringify(this.query));var o=this.search||a&&"?"+a||"";return t&&":"!==t.substr(-1)&&(t+=":"),this.slashes||(!t||v[t])&&!1!==i?(i="//"+(i||""),r&&"/"!==r.charAt(0)&&(r="/"+r)):i||(i=""),n&&"#"!==n.charAt(0)&&(n="#"+n),o&&"?"!==o.charAt(0)&&(o="?"+o),t+i+(r=r.replace(/[?#]/g,(function(e){return encodeURIComponent(e)})))+(o=o.replace("#","%23"))+n},i.prototype.resolve=function(e){return this.resolveObject(w(e,!1,!0)).format()},i.prototype.resolveObject=function(e){if(s.isString(e)){var t=new i;t.parse(e,!1,!0),e=t}for(var r=new i,n=Object.keys(this),a=0;a<n.length;a++){var o=n[a];r[o]=this[o]}if(r.hash=e.hash,""===e.href)return r.href=r.format(),r;if(e.slashes&&!e.protocol){for(var l=Object.keys(e),c=0;c<l.length;c++){var d=l[c];"protocol"!==d&&(r[d]=e[d])}return v[r.protocol]&&r.hostname&&!r.pathname&&(r.path=r.pathname="/"),r.href=r.format(),r}if(e.protocol&&e.protocol!==r.protocol){if(!v[e.protocol]){for(var u=Object.keys(e),h=0;h<u.length;h++){var f=u[h];r[f]=e[f]}return r.href=r.format(),r}if(r.protocol=e.protocol,e.host||y[e.protocol])r.pathname=e.pathname;else{for(var p=(e.pathname||"").split("/");p.length&&!(e.host=p.shift()););e.host||(e.host=""),e.hostname||(e.hostname=""),""!==p[0]&&p.unshift(""),p.length<2&&p.unshift(""),r.pathname=p.join("/")}if(r.search=e.search,r.query=e.query,r.host=e.host||"",r.auth=e.auth,r.hostname=e.hostname||e.host,r.port=e.port,r.pathname||r.search){var g=r.pathname||"",m=r.search||"";r.path=g+m}return r.slashes=r.slashes||e.slashes,r.href=r.format(),r}var b=r.pathname&&"/"===r.pathname.charAt(0),w=e.host||e.pathname&&"/"===e.pathname.charAt(0),E=w||b||r.host&&e.pathname,S=E,T=r.pathname&&r.pathname.split("/")||[],C=(p=e.pathname&&e.pathname.split("/")||[],r.protocol&&!v[r.protocol]);if(C&&(r.hostname="",r.port=null,r.host&&(""===T[0]?T[0]=r.host:T.unshift(r.host)),r.host="",e.protocol&&(e.hostname=null,e.port=null,e.host&&(""===p[0]?p[0]=e.host:p.unshift(e.host)),e.host=null),E=E&&(""===p[0]||""===T[0])),w)r.host=e.host||""===e.host?e.host:r.host,r.hostname=e.hostname||""===e.hostname?e.hostname:r.hostname,r.search=e.search,r.query=e.query,T=p;else if(p.length)T||(T=[]),T.pop(),T=T.concat(p),r.search=e.search,r.query=e.query;else if(!s.isNullOrUndefined(e.search))return C&&(r.hostname=r.host=T.shift(),(R=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@"))&&(r.auth=R.shift(),r.host=r.hostname=R.shift())),r.search=e.search,r.query=e.query,s.isNull(r.pathname)&&s.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r;if(!T.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var k=T.slice(-1)[0],A=(r.host||e.host||T.length>1)&&("."===k||".."===k)||""===k,I=0,_=T.length;_>=0;_--)"."===(k=T[_])?T.splice(_,1):".."===k?(T.splice(_,1),I++):I&&(T.splice(_,1),I--);if(!E&&!S)for(;I--;I)T.unshift("..");!E||""===T[0]||T[0]&&"/"===T[0].charAt(0)||T.unshift(""),A&&"/"!==T.join("/").substr(-1)&&T.push("");var R,L=""===T[0]||T[0]&&"/"===T[0].charAt(0);return C&&(r.hostname=r.host=L?"":T.length?T.shift():"",(R=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@"))&&(r.auth=R.shift(),r.host=r.hostname=R.shift())),(E=E||r.host&&T.length)&&!L&&T.unshift(""),T.length?r.pathname=T.join("/"):(r.pathname=null,r.path=null),s.isNull(r.pathname)&&s.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=e.auth||r.auth,r.slashes=r.slashes||e.slashes,r.href=r.format(),r},i.prototype.parseHost=function(){var e=this.host,t=o.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},{"./util":77,punycode:51,querystring:54}],77:[function(e,t,r){t.exports={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}}},{}],78:[function(e,t,r){(function(e){(function(){function r(e,t){if(n("noDeprecation"))return e;var r=!1;function s(){if(!r){if(n("throwDeprecation"))throw new Error(t);n("traceDeprecation")?console.trace(t):console.warn(t),r=!0}return e.apply(this,arguments)}return s}function n(t){try{if(!e.localStorage)return!1}catch(e){return!1}var r=e.localStorage[t];return null!=r&&"true"===String(r).toLowerCase()}t.exports=r}).call(this)}).call(this,void 0!==ft?ft:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],79:[function(e,t,r){function n(e,t){if(e&&t)return n(e)(t);if("function"!=typeof e)throw new TypeError("need wrapper function");return Object.keys(e).forEach((function(t){r[t]=e[t]})),r;function r(){for(var t=new Array(arguments.length),r=0;r<t.length;r++)t[r]=arguments[r];var n=e.apply(this,t),s=t[t.length-1];return"function"==typeof n&&n!==s&&Object.keys(s).forEach((function(e){n[e]=s[e]})),n}}t.exports=n},{}],80:[function(e,t,r){t.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}},{}],81:[function(e,t,r){t.exports=s;var n=Object.prototype.hasOwnProperty;function s(){for(var e={},t=0;t<arguments.length;t++){var r=arguments[t];for(var s in r)n.call(r,s)&&(e[s]=r[s])}return e}},{}],82:[function(e,t,r){t.exports=function(e){e.prototype[Symbol.iterator]=function*(){for(let e=this.head;e;e=e.next)yield e.value}}},{}],83:[function(e,t,r){function n(e){var t=this;if(t instanceof n||(t=new n),t.tail=null,t.head=null,t.length=0,e&&"function"==typeof e.forEach)e.forEach((function(e){t.push(e)}));else if(arguments.length>0)for(var r=0,s=arguments.length;r<s;r++)t.push(arguments[r]);return t}function s(e,t,r){var n=t===e.head?new o(r,null,t,e):new o(r,t,t.next,e);return null===n.next&&(e.tail=n),null===n.prev&&(e.head=n),e.length++,n}function i(e,t){e.tail=new o(t,e.tail,null,e),e.head||(e.head=e.tail),e.length++}function a(e,t){e.head=new o(t,null,e.head,e),e.tail||(e.tail=e.head),e.length++}function o(e,t,r,n){if(!(this instanceof o))return new o(e,t,r,n);this.list=n,this.value=e,t?(t.next=this,this.prev=t):this.prev=null,r?(r.prev=this,this.next=r):this.next=null}t.exports=n,n.Node=o,n.create=n,n.prototype.removeNode=function(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");var t=e.next,r=e.prev;return t&&(t.prev=r),r&&(r.next=t),e===this.head&&(this.head=t),e===this.tail&&(this.tail=r),e.list.length--,e.next=null,e.prev=null,e.list=null,t},n.prototype.unshiftNode=function(e){if(e!==this.head){e.list&&e.list.removeNode(e);var t=this.head;e.list=this,e.next=t,t&&(t.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}},n.prototype.pushNode=function(e){if(e!==this.tail){e.list&&e.list.removeNode(e);var t=this.tail;e.list=this,e.prev=t,t&&(t.next=e),this.tail=e,this.head||(this.head=e),this.length++}},n.prototype.push=function(){for(var e=0,t=arguments.length;e<t;e++)i(this,arguments[e]);return this.length},n.prototype.unshift=function(){for(var e=0,t=arguments.length;e<t;e++)a(this,arguments[e]);return this.length},n.prototype.pop=function(){if(this.tail){var e=this.tail.value;return this.tail=this.tail.prev,this.tail?this.tail.next=null:this.head=null,this.length--,e}},n.prototype.shift=function(){if(this.head){var e=this.head.value;return this.head=this.head.next,this.head?this.head.prev=null:this.tail=null,this.length--,e}},n.prototype.forEach=function(e,t){t=t||this;for(var r=this.head,n=0;null!==r;n++)e.call(t,r.value,n,this),r=r.next},n.prototype.forEachReverse=function(e,t){t=t||this;for(var r=this.tail,n=this.length-1;null!==r;n--)e.call(t,r.value,n,this),r=r.prev},n.prototype.get=function(e){for(var t=0,r=this.head;null!==r&&t<e;t++)r=r.next;if(t===e&&null!==r)return r.value},n.prototype.getReverse=function(e){for(var t=0,r=this.tail;null!==r&&t<e;t++)r=r.prev;if(t===e&&null!==r)return r.value},n.prototype.map=function(e,t){t=t||this;for(var r=new n,s=this.head;null!==s;)r.push(e.call(t,s.value,this)),s=s.next;return r},n.prototype.mapReverse=function(e,t){t=t||this;for(var r=new n,s=this.tail;null!==s;)r.push(e.call(t,s.value,this)),s=s.prev;return r},n.prototype.reduce=function(e,t){var r,n=this.head;if(arguments.length>1)r=t;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");n=this.head.next,r=this.head.value}for(var s=0;null!==n;s++)r=e(r,n.value,s),n=n.next;return r},n.prototype.reduceReverse=function(e,t){var r,n=this.tail;if(arguments.length>1)r=t;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");n=this.tail.prev,r=this.tail.value}for(var s=this.length-1;null!==n;s--)r=e(r,n.value,s),n=n.prev;return r},n.prototype.toArray=function(){for(var e=new Array(this.length),t=0,r=this.head;null!==r;t++)e[t]=r.value,r=r.next;return e},n.prototype.toArrayReverse=function(){for(var e=new Array(this.length),t=0,r=this.tail;null!==r;t++)e[t]=r.value,r=r.prev;return e},n.prototype.slice=function(e,t){(t=t||this.length)<0&&(t+=this.length),(e=e||0)<0&&(e+=this.length);var r=new n;if(t<e||t<0)return r;e<0&&(e=0),t>this.length&&(t=this.length);for(var s=0,i=this.head;null!==i&&s<e;s++)i=i.next;for(;null!==i&&s<t;s++,i=i.next)r.push(i.value);return r},n.prototype.sliceReverse=function(e,t){(t=t||this.length)<0&&(t+=this.length),(e=e||0)<0&&(e+=this.length);var r=new n;if(t<e||t<0)return r;e<0&&(e=0),t>this.length&&(t=this.length);for(var s=this.length,i=this.tail;null!==i&&s>t;s--)i=i.prev;for(;null!==i&&s>e;s--,i=i.prev)r.push(i.value);return r},n.prototype.splice=function(e,t,...r){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);for(var n=0,i=this.head;null!==i&&n<e;n++)i=i.next;var a=[];for(n=0;i&&n<t;n++)a.push(i.value),i=this.removeNode(i);for(null===i&&(i=this.tail),i!==this.head&&i!==this.tail&&(i=i.prev),n=0;n<r.length;n++)i=s(this,i,r[n]);return a},n.prototype.reverse=function(){for(var e=this.head,t=this.tail,r=e;null!==r;r=r.prev){var n=r.prev;r.prev=r.next,r.next=n}return this.head=t,this.tail=e,this};try{e("./iterator.js")(n)}catch(e){}},{"./iterator.js":82}]},{},[12])(12)}(_a);var Ra=pt(_a.exports);class La{constructor(){this.store={},this.store={}}clear(){this.store={}}getItem(e){return this.store[e]||null}setItem(e,t){this.store[e]=String(t)}removeItem(e){delete this.store[e]}get length(){return Object.keys(this.store).length}key(e){return Object.keys(this.store)[e]||null}}const Da=()=>"undefined"!=typeof window&&window.localStorage?window:{localStorage:new La};var xa={},Oa={},Pa={};Object.defineProperty(Pa,"__esModule",{value:!0}),Pa.bytesToString=Pa.stringToBytes=Pa.NIL=Pa.X500=Pa.OID=Pa.URL=Pa.DNS=Pa.hexToByte=Pa.byteToHex=void 0;let Ma=[],Fa={};for(var Ua=0;Ua<256;Ua++)Ma[Ua]=(Ua+256).toString(16).substr(1),Fa[Ma[Ua]]=Ua;Pa.byteToHex=Ma,Pa.hexToByte=Fa,Pa.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Pa.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",Pa.OID="6ba7b812-9dad-11d1-80b4-00c04fd430c8",Pa.X500="6ba7b814-9dad-11d1-80b4-00c04fd430c8",Pa.NIL="00000000-0000-0000-0000-000000000000";Pa.stringToBytes=e=>{e=unescape(encodeURIComponent(e));const t=new Uint8Array(e.length);for(let r=0;r<e.length;++r)t[r]=e.charCodeAt(r);return t};Pa.bytesToString=e=>{const t=new Uint8Array(e,0,e.byteLength);return String.fromCharCode.apply(null,Array.from(t))},Object.defineProperty(Oa,"__esModule",{value:!0}),Oa.parse=void 0;const Na=Pa;Oa.parse=(e,t,r)=>{let n=t&&r||0,s=0;for(t=t||[],e.toLowerCase().replace(/[0-9a-f]{2}/g,(e=>(s<16&&t&&(t[n+s++]=Na.hexToByte[e]),"")));s<16;)t[n+s++]=0;return t};var Ba={};Object.defineProperty(Ba,"__esModule",{value:!0}),Ba.unparse=void 0;const ja=Pa;Ba.unparse=(e,t)=>{let r=t||0,n=ja.byteToHex;return n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]};var $a={},qa={};Object.defineProperty(qa,"__esModule",{value:!0});qa.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;var Ka=ft&&ft.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty($a,"__esModule",{value:!0}),$a.validate=void 0;const Ga=Ka(qa);$a.validate=e=>"string"==typeof e&&Ga.default.test(e);var Ha={};Object.defineProperty(Ha,"__esModule",{value:!0}),Ha.version=void 0;const Va=$a;Ha.version=e=>{if(!Va.validate(e))throw TypeError("Invalid UUID");return parseInt(e.substr(14,1),16)};var za={},Wa={};Object.defineProperty(Wa,"__esModule",{value:!0}),Wa.stringify=void 0;const Ya=$a,Qa=[];for(let e=0;e<256;++e)Qa.push((e+256).toString(16).substr(1));Wa.stringify=(e,t=0)=>{const r=(Qa[e[t+0]]+Qa[e[t+1]]+Qa[e[t+2]]+Qa[e[t+3]]+"-"+Qa[e[t+4]]+Qa[e[t+5]]+"-"+Qa[e[t+6]]+Qa[e[t+7]]+"-"+Qa[e[t+8]]+Qa[e[t+9]]+"-"+Qa[e[t+10]]+Qa[e[t+11]]+Qa[e[t+12]]+Qa[e[t+13]]+Qa[e[t+14]]+Qa[e[t+15]]).toLowerCase();if(!Ya.validate(r))throw TypeError("Stringified UUID is invalid");return r};var Xa={};Object.defineProperty(Xa,"__esModule",{value:!0}),Xa.rng=void 0;Xa.rng=()=>{let e=new Array(16);for(let t=0;t<16;t++)e[t]=255&256*Math.random()+0;return e},Object.defineProperty(za,"__esModule",{value:!0}),za.v1=void 0;const Ja=Wa,Za=Xa;let eo,to,ro=0,no=0;za.v1=(e,t,r=0)=>{let n=t&&r||0;const s=t||new Uint8Array(16);let i=e&&e.node?e.node:eo,a=e&&e.clockseq?e.clockseq:to;if(null==i||null==a){const t=e&&e.random?e.random:e&&e.rng?e.rng():Za.rng();null==i&&(i=eo=[1|t[0],t[1],t[2],t[3],t[4],t[5]]),null==a&&(a=to=16383&(t[6]<<8|t[7]))}let o=e&&e.msecs?e.msecs:Date.now(),l=e&&e.nsecs?e.nsecs:no+1;const c=o-ro+(l-no)/1e4;if(c<0&&e&&!e.clockseq&&(a=a+1&16383),(c<0||o>ro)&&e&&!e.nsecs&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");ro=o,no=l,to=a,o+=122192928e5;const d=(1e4*(268435455&o)+l)%4294967296;s[n++]=d>>>24&255,s[n++]=d>>>16&255,s[n++]=d>>>8&255,s[n++]=255&d;const u=o/4294967296*1e4&268435455;s[n++]=u>>>8&255,s[n++]=255&u,s[n++]=u>>>24&15|16,s[n++]=u>>>16&255,s[n++]=a>>>8|128,s[n++]=255&a;for(let e=0;e<6;++e)s[n+e]=i[e];return t||Ja.stringify(s)};var so={};Object.defineProperty(so,"__esModule",{value:!0}),so.v4=void 0;const io=Ba,ao=Xa;so.v4=(e,t,r)=>{let n=t&&r||0,s=ao.rng();if(!e||e instanceof String||(e.random&&(s=e.random),e.rng&&(s=e.rng())),s[6]=15&s[6]|64,s[8]=63&s[8]|128,t)for(var i=0;i<16;i++)t[n+i]=s[i];return t||io.unparse(s)};var oo={},lo={};Object.defineProperty(lo,"__esModule",{value:!0}),lo.v35=void 0;const co=Wa,uo=Oa,ho=Pa;lo.v35=(e,t,r)=>(e,n,s,i=0)=>{if("string"==typeof e&&(e=ho.stringToBytes(e)),"string"==typeof n&&(n=uo.parse(n)),n&&16!==n.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let a=new Uint8Array(16+e.length);if(a.set(n),a.set(e,n.length),a=ho.stringToBytes(r(ho.bytesToString(a))),a[6]=15&a[6]|t,a[8]=63&a[8]|128,s)for(let e=0;e<16;++e)s[i+e]=a[e];return s||co.stringify(a)};var fo={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.any_hmac_sha1=e.b64_hmac_sha1=e.hex_hmac_sha1=e.any_sha1=e.b64_sha1=e.hex_sha1=void 0;let t=0,r="";e.hex_sha1=e=>i(n(l(e))),e.default=e.hex_sha1;e.b64_sha1=e=>a(n(l(e)));e.any_sha1=(e,t)=>o(n(l(e)),t);e.hex_hmac_sha1=(e,t)=>i(s(l(e),l(t)));e.b64_hmac_sha1=(e,t)=>a(s(l(e),l(t)));e.any_hmac_sha1=(e,t,r)=>o(s(l(e),l(t)),r);const n=e=>d(u(c(e),8*e.length)),s=(e,t)=>{let r=c(e);r.length>16&&(r=u(r,8*e.length));let n=Array(16),s=Array(16);for(var i=0;i<16;i++)n[i]=909522486^r[i],s[i]=1549556828^r[i];var a=u(n.concat(c(t)),512+8*t.length);return d(u(s.concat(a),672))},i=e=>{for(var r,n=t?"0123456789ABCDEF":"0123456789abcdef",s="",i=0;i<e.length;i++)r=e.charCodeAt(i),s+=n.charAt(r>>>4&15)+n.charAt(15&r);return s},a=e=>{for(var t="",n=e.length,s=0;s<n;s+=3)for(var i=e.charCodeAt(s)<<16|(s+1<n?e.charCodeAt(s+1)<<8:0)|(s+2<n?e.charCodeAt(s+2):0),a=0;a<4;a++)8*s+6*a>8*e.length?t+=r:t+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(i>>>6*(3-a)&63);return t},o=(e,t)=>{var r,n,s,i,a=t.length,o=[],l=Array(Math.ceil(e.length/2));for(r=0;r<l.length;r++)l[r]=e.charCodeAt(2*r)<<8|e.charCodeAt(2*r+1);for(;l.length>0;){for(i=[],s=0,r=0;r<l.length;r++)s=(s<<16)+l[r],s-=(n=Math.floor(s/a))*a,(i.length>0||n>0)&&(i[i.length]=n);o[o.length]=s,l=i}var c="";for(r=o.length-1;r>=0;r--)c+=t.charAt(o[r]);var d=Math.ceil(8*e.length/(Math.log(t.length)/Math.log(2)));for(r=c.length;r<d;r++)c=t[0]+c;return c},l=e=>{for(var t,r,n="",s=-1;++s<e.length;)t=e.charCodeAt(s),r=s+1<e.length?e.charCodeAt(s+1):0,t>=55296&&t<=56319&&r>=56320&&r<=57343&&(t=65536+((1023&t)<<10)+(1023&r),s++),t<=127?n+=String.fromCharCode(t):t<=2047?n+=String.fromCharCode(192|t>>>6&31,128|63&t):t<=65535?n+=String.fromCharCode(224|t>>>12&15,128|t>>>6&63,128|63&t):t<=2097151&&(n+=String.fromCharCode(240|t>>>18&7,128|t>>>12&63,128|t>>>6&63,128|63&t));return n},c=e=>{for(var t=Array(e.length>>2),r=0;r<t.length;r++)t[r]=0;for(r=0;r<8*e.length;r+=8)t[r>>5]|=(255&e.charCodeAt(r/8))<<24-r%32;return t},d=e=>{for(var t="",r=0;r<32*e.length;r+=8)t+=String.fromCharCode(e[r>>5]>>>24-r%32&255);return t},u=(e,t)=>{e[t>>5]|=128<<24-t%32,e[15+(t+64>>9<<4)]=t;for(var r=Array(80),n=1732584193,s=-271733879,i=-1732584194,a=271733878,o=-1009589776,l=0;l<e.length;l+=16){for(var c=n,d=s,u=i,m=a,y=o,v=0;v<80;v++){r[v]=v<16?e[l+v]:g(r[v-3]^r[v-8]^r[v-14]^r[v-16],1);let t=p(p(g(n,5),h(v,s,i,a)),p(p(o,r[v]),f(v)));o=a,a=i,i=g(s,30),s=n,n=t}n=p(n,c),s=p(s,d),i=p(i,u),a=p(a,m),o=p(o,y)}return[n,s,i,a,o]},h=(e,t,r,n)=>e<20?t&r|~t&n:e<40?t^r^n:e<60?t&r|t&n|r&n:t^r^n,f=e=>e<20?1518500249:e<40?1859775393:e<60?-1894007588:-899497514,p=(e,t)=>{var r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r},g=(e,t)=>e<<t|e>>>32-t}(fo);var po=ft&&ft.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(oo,"__esModule",{value:!0}),oo.v5=void 0;const go=lo,mo=po(fo);oo.v5=go.v35("v5",80,mo.default),Object.defineProperty(xa,"__esModule",{value:!0});const yo=Oa,vo=Ba,bo=$a,wo=Ha,Eo=za,So=so,To=oo,Co=Pa;var ko=xa.default={parse:yo.parse,unparse:vo.unparse,validate:bo.validate,version:wo.version,v1:Eo.v1,v4:So.v4,v5:To.v5,NIL:Co.NIL,DNS:Co.DNS,URL:Co.URL,OID:Co.OID,X500:Co.X500};const Ao=()=>ko.v4().toString();let Io=0;if("undefined"!=typeof BroadcastChannel&&"undefined"!=typeof window){const e=Ao(),t={},r=new BroadcastChannel("amity_ts_sdk");let n;r.postMessage({type:"startup",tabId:e}),r.onmessage=({data:s})=>{s.tabId!==e&&("startup"===s.type&&r.postMessage({type:"identify",tabId:e,tabIndex:Io}),"identify"===s.type&&void 0!==s.tabIndex&&s.tabId&&(t[s.tabId]=s.tabIndex,n||(n=setTimeout((()=>{const e=Object.values(t).sort();e&&0!==e.length&&(Io=e.reduce(((e,t)=>e<t?e:t+1),0))}),15))))}}const _o=async()=>{const e=await(async e=>new Promise((t=>{t(Da().localStorage.getItem(e))})))("deviceId");if(e)return e;const t=`ascWebSdk#${Ao()}`;return await(async(e,t)=>new Promise((r=>{Da().localStorage.setItem(e,t),r(!0)})))("deviceId",t),t},Ro=()=>{const e=(()=>{var e,t;return(null===(e=Ct.versions)||void 0===e?void 0:e.node)?Ct.versions.node:navigator?`${navigator.product.toLowerCase()}#${null!==(t=navigator.userAgent)&&void 0!==t?t:"unknown_agent"}`:"unknown_model"})();return{kind:"web",model:e,sdkVersion:u}},Lo=1e3;var Do;!function(e){e[e.IDENTIFIER_REJECTED=2]="IDENTIFIER_REJECTED",e[e.BAD_USERNAME_OR_PASSWORD=134]="BAD_USERNAME_OR_PASSWORD",e[e.NOT_AUTHORIZED=135]="NOT_AUTHORIZED"}(Do||(Do={}));const xo=e=>{let t;return{connect:async function(r){const n=await(async e=>`mqttjs_${await _o()}_${e}_${Io}`)(r.userId);return t&&(t.removeAllListeners(),t.end(!0)),t=Ra.connect(e,function(e){return Object.assign({clean:!1,clientId:`mqttjs_ + ${Math.random().toString(16).substring(2,10)}`,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:Lo,will:{topic:"WillMsg",payload:"Connection Closed abnormally..!",qos:0,retain:!1},resubscribe:!0},e)}({username:r.userId,password:r.accessToken,clientId:n})),t.on("connect",(()=>{t.options.reconnectPeriod=Lo,(()=>{const e=[ht(lt()),ht(ct()),ht(dt()),ht(ut()),ht(it(Ke())),ht(ot())]})()})),t.on("error",(e=>{switch(e.code){case 2:case 134:case 135:t.end()}})),t.on("reconnect",(()=>{t.options.reconnectPeriod=Math.min(2*(t.options.reconnectPeriod||Lo),8e3)})),new Promise((e=>t.once("connect",(()=>e()))))},async disconnect(){if(this.connected)return new Promise((e=>null==t?void 0:t.end(!0,void 0,(()=>e()))))},get connected(){return!!(null==t?void 0:t.connected)},on(e,r){null==t||t.on(e,r)},once(e,r){null==t||t.once(e,r)},off(e,r){void 0!==r?null==t||t.off(e,r):null==t||t.removeAllListeners(e)},removeAllListeners(){null==t||t.removeAllListeners()},subscribe(e,r){const n=(t,n)=>{var s;if(t||128===(null===(s=n[0])||void 0===s?void 0:s.qos)){const n=t?new fe(t.message,8e5,"error"):new ge(8e5,"error");console.warn(`Failed to subscribe to topic ${e}`,n),null==r||r(n)}else console.log(`Subscribed to topic ${e}`),null==r||r()};return t?t.subscribe(e,{qos:0},n):n(new Error("No connection to broker"),[]),()=>null==t?void 0:t.unsubscribe(e)},unsubscribe(e){null==t||t.unsubscribe(e)}}},Oo=(e={},t,r=!0)=>{Object.entries(e).forEach((([e,n])=>{const s=ue[e];if(!s)return;const i=de(s);i&&n.forEach((e=>{(r?Se:Ce)([s,"get",i(e)],e,t)}))}))},Po=(e,t)=>{const{log:r,cache:n}=ve(),s=[e,v,t],i={cachedAt:Date.now()};n&&(r("cache/api/pushToTombstone",{cacheKey:s,data:i}),ke([e,"get",t],!0),Se(s,i))};function Mo(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(r[n[s]]=e[n[s]])}return r}const Fo=(e,t="userId",r="user")=>{var n;return null!==(n=null==e?void 0:e.map((e=>((e,t="userId",r="user")=>e[r]?e:Object.assign({get[r](){var r;if(!ve().cache)return;return(null===(r=Ee(["user","get",e[t]]))||void 0===r?void 0:r.data)||void 0}},e))(e,t,r))))&&void 0!==n?n:e},Uo=(e,t,r="userId",n="user")=>{const s=e,i=t,a=s[i],o=Mo(s,["symbol"==typeof i?i:i+""]),l=Fo(a,r,n);return Object.assign(Object.assign({},o),{[t]:l})};function No(e){return e.map((e=>{var{isMentioned:t}=e,r=Mo(e,["isMentioned"]);return Object.assign({hasMentioned:t},r)}))}function Bo(e){return No(e)}function jo(e){return No(e)}const $o=e=>{var t,r;return null!==(r=null===(t=Ee(["messagePreviewChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==r?r:null},qo=["analytic","normal-priority"],Ko=["analytic","high-priority"],Go=async e=>{const t=ve();await t.http.post("/api/v1/analytics/activities",{activities:e})};class Ho{constructor(){this._timer=void 0,this._high_priority_timer=void 0}start(){this.syncCapturedEvent(),this._timer=setInterval((()=>{this.syncCapturedEvent()}),6e4),this._high_priority_timer=setInterval((()=>{this.syncHighPriorityCapturedEvent()}),1e4)}stop(){this._timer&&(clearInterval(this._timer),this._timer=void 0)}async syncCapturedEvent(){try{const e=Ee(qo);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await Go(t),ke(qo)}catch(e){this.stop(),ke(qo)}}async syncHighPriorityCapturedEvent(){try{const e=Ee(Ko);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await Go(t),ke(Ko)}catch(e){this.stop(),ke(Ko)}}}class Vo{constructor(){this._expireTime=3e5,this._poolLimit=1e3,this._recentViewed={},this._recentHighPriorityViewed={},this._throttleStoryTimer=void 0,this._bufferNewSeenStoryReferenceIds=[]}isAbleToEnqueue({itemId:e,expireTime:t,isHighPriority:r=!1}){const n=new Date,s=(()=>r?this._recentHighPriorityViewed[e]:this._recentViewed[e])()||new Date(-1*m);return!(n.getTime()-s.getTime()<t)}markPostAsViewed(e){if(!this.isAbleToEnqueue({itemId:e,expireTime:this._expireTime}))return;const t=new Date,r={event:[]},n=Ee(qo);(null==n?void 0:n.data)&&(r.event=n.data.event),r.event.length>=this._poolLimit&&r.event.shift(),r.event.push({contentId:e,contentType:"post",activityType:"view",timestamp:t.toISOString()}),Ce(qo,r),this._recentViewed[e]=t}markStory(e,t){if(!e.expiresAt)return;const r=new Date,n=new Date(e.expiresAt);if(!this.isAbleToEnqueue({itemId:e.storyId,expireTime:n.getTime(),isHighPriority:!0}))return;const s={event:[]},i=Ee(Ko);if((null==i?void 0:i.data)&&(s.event=i.data.event),s.event.length>=this._poolLimit&&s.event.shift(),s.event.push({contentId:e.storyId,contentType:"story",activityType:t,timestamp:r.toISOString()}),Ce(Ko,s),this._recentHighPriorityViewed[e.storyId]=r,"linkClicked"===t)return;Se(["story-seen","get",e.storyId],(new Date).toISOString());const a=Ee(["story-last-seen",e.targetId]);(null==a?void 0:a.data)?new Date(a.data).getTime()<new Date(e.expiresAt).getTime()&&Se(["story-last-seen",e.targetId],e.expiresAt):Se(["story-last-seen",e.targetId],e.expiresAt),this._bufferNewSeenStoryReferenceIds.push(e.referenceId),this._throttleStoryTimer||(this._throttleStoryTimer=setTimeout((()=>{clearTimeout(this._throttleStoryTimer),Je("local.story.reload",{referenceIds:this._bufferNewSeenStoryReferenceIds}),this._bufferNewSeenStoryReferenceIds=[]}),300))}markStoryAsViewed(e){this.markStory(e,"view")}markStoryAsClicked(e){this.markStory(e,"linkClicked")}}class zo{constructor(){this._client=ve(),this._eventCapturer=new Vo,this._eventSyncer=new Ho}markPostAsViewed(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markPostAsViewed(e)}markStoryAsViewed(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markStoryAsViewed(e)}markStoryAsClicked(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markStoryAsClicked(e)}established(){this._eventSyncer.start()}handleTokenExpired(){this._eventSyncer.stop()}destroy(){this._eventSyncer.stop(),ke(qo)}}let Wo;var Yo=()=>(Wo||(Wo=new zo),Wo);const Qo=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return null;let r={fileId:(null===(t=e.avatarFileId)||void 0===t?void 0:t.toString())?e.avatarFileId.toString():"",type:"image",fileUrl:"",createdAt:"",attributes:{name:"",extension:"",size:"",mimeType:"",metadata:{exif:{},gps:{},width:0,height:0,isFull:!1}}};const n=Ee(["file","get",`${e.avatarFileId}`]);return(null==n?void 0:n.data)&&(r=null==n?void 0:n.data),r}});class Xo{constructor(e,t,r){this._syncingStoriesCount=0,this._syncedStoriesCount=0,this._errorStoriesCount=0,this._targetId=e,this._lastStoryExpiresAt=t,this._lastStorySeenExpiresAt=r,this.cacheStoryExpireTime=Ee(["story-expire",this._targetId]),this.cacheStoreSeenTime=Ee(["story-last-seen",this._targetId]),this.getTotalStoryByStatus()}get lastStoryExpiresAt(){return this._lastStoryExpiresAt?new Date(this._lastStoryExpiresAt).getTime():0}get lastStorySeenExpiresAt(){return this._lastStorySeenExpiresAt?new Date(this._lastStorySeenExpiresAt).getTime():0}get localLastStoryExpires(){var e,t;return(null===(e=this.cacheStoryExpireTime)||void 0===e?void 0:e.data)?new Date(null===(t=this.cacheStoryExpireTime)||void 0===t?void 0:t.data).getTime():0}get localLastStorySeenExpiresAt(){var e,t;return(null===(e=this.cacheStoreSeenTime)||void 0===e?void 0:e.data)?new Date(null===(t=this.cacheStoreSeenTime)||void 0===t?void 0:t.data).getTime():0}get isContainUnSyncedStory(){const e=Ee(["story-sync-state",this._targetId]);return!!(null==e?void 0:e.data)&&["syncing","error"].includes(e.data)}getLocalLastSortingDate(){return this.isContainUnSyncedStory?this.localLastStoryExpires:this.lastStoryExpiresAt}getHasUnseenFlag(){const e=(new Date).getTime(),t=Math.max(this.lastStorySeenExpiresAt,this.localLastStorySeenExpiresAt);return Ee(["story-sync-state",this._targetId]),this.isContainUnSyncedStory?this.localLastStoryExpires>e&&this.localLastStoryExpires>t:this.lastStoryExpiresAt>e&&this.lastStoryExpiresAt>t}getTotalStoryByStatus(){const e=we(["story","get"]);if(!e)return this._errorStoriesCount=0,this._syncedStoriesCount=0,void(this._syncingStoriesCount=0);const t=e.reduce(((e,t)=>{const{data:{targetId:r,syncState:n}}=t;return r===this._targetId&&(e[n]+=1),e}),{syncing:0,error:0,synced:0});this._errorStoriesCount=t.error,this._syncedStoriesCount=t.synced,this._syncingStoriesCount=t.syncing}get syncedStoriesCount(){return this._syncedStoriesCount}get syncingStoriesCount(){return this._syncingStoriesCount}get failedStoriesCount(){return this._errorStoriesCount}}const Jo=e=>{const{targetType:t,targetId:r,lastStoryExpiresAt:n,lastStorySeenExpiresAt:s,targetUpdatedAt:i,localFilter:a}=e,o=new Xo(r,n,s);return{targetType:t,targetId:r,lastStoryExpiresAt:n,updatedAt:i,hasUnseen:o.getHasUnseenFlag(),syncedStoriesCount:o.syncedStoriesCount,syncingStoriesCount:o.syncingStoriesCount,failedStoriesCount:o.failedStoriesCount,localFilter:a,localLastExpires:o.localLastStoryExpires,localLastSeen:o.localLastStorySeenExpiresAt,localSortingDate:o.getLocalLastSortingDate()}},Zo=e=>Object.assign(Object.assign({},e),{get target(){const t={type:e.targetType};if("user"===e.targetType)return Object.assign(Object.assign({},t),{userId:e.targetId});if("content"===t.type)return Object.assign(Object.assign({},t),{contentId:e.targetId});if("community"===t.type){const r=Ee(["communityUsers","get",`${e.targetId}#${e.userId}`]);return Object.assign(Object.assign({},t),{communityId:e.targetId,creatorMember:null==r?void 0:r.data})}return{type:"unknown"}},get creator(){const t=Ee(["user","get",e.userId]);if(null==t?void 0:t.data)return Qo(t.data)},get childrenComment(){return e.children.map((e=>{const t=Ee(["comment","get",e]);if(null==t?void 0:t.data)return null==t?void 0:t.data})).filter((e=>e)).map((e=>Zo(e)))}}),el=async e=>{var t;const r=["channelUnreadInfo","get",e],n=null===(t=Ee(r))||void 0===t?void 0:t.data,s=we(["subChannelUnreadInfo","get"]);let i=0,a=!1;if(s&&(null==s?void 0:s.length)>0){const t=null==s?void 0:s.filter((({data:t})=>t.channelId===e&&!t.isDeleted));i=t.map((({data:e})=>e.unreadCount)).reduce(((e,t)=>e+t),0),a=t.some((({data:e})=>e.isMentioned))}Se(r,Object.assign(Object.assign({},null!=n?n:{channelId:e,createdAt:(new Date).toISOString()}),{updatedAt:(new Date).toISOString(),unreadCount:i,isMentioned:a}))};class tl{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=ve(),this.getUnsyncJobs()}startSyncReadReceipt(){this.timer=setInterval((()=>{this.syncReadReceipts()}),1e3*this.RECEIPT_SYNC_INTERVAL)}syncReadReceipts(){if(0===this.jobQueue.length||!1===this.isActive)return;const e=this.getReadReceipt();e&&this.markReadApi(e)}getUnsyncJobs(){var e;const t=null===(e=we(["readReceipt"]))||void 0===e?void 0:e.filter((({data:e})=>e.latestSyncSegment<e.latestSegment));null==t||t.forEach((({data:e})=>{this.enqueueReadReceipt(e.subChannelId,e.latestSegment)}))}getReadReceipt(){var e;const t=this.jobQueue[0];if(!t)return;if("syncing"===t.syncState)return;const r=null===(e=Ee(["readReceipt",t.subChannelId]))||void 0===e?void 0:e.data;return r?(null==r?void 0:r.latestSegment)>(null==r?void 0:r.latestSyncSegment)?(t.segment=r.latestSegment,t):(this.removeSynedReceipt(r.subChannelId,r.latestSegment),this.getReadReceipt()):void 0}async markReadApi(e){var t;const r=e;r.syncState="syncing";const{subChannelId:n,segment:s}=r,i=await(async({subChannelId:e,readToSegment:t})=>{const r=ve();r.log("subChannel/markAsReadBySegment",e);try{return await r.http.put(`/api/v1/markers/message-feeds/${e}/mark-read`,{readToSegment:t}),!0}catch(e){return!1}})({subChannelId:n,readToSegment:s});if(i){this.removeSynedReceipt(e.subChannelId,e.segment);const r=null===(t=Ee(["readReceipt",n]))||void 0===t?void 0:t.data;Se(["readReceipt",n],Object.assign(Object.assign({},r),{latestSyncSegment:s}))}else i||(r.retryCount>this.MAX_RETRY?this.removeJobFromQueue(r):(r.retryCount+=1,r.syncState="create"))}removeSynedReceipt(e,t){this.jobQueue.forEach((r=>{r.subChannelId===e&&r.segment<=t&&this.removeJobFromQueue(r)}))}startObservingReadReceiptQueue(){this.client.isUnreadCountEnabled&&(this.isActive=!0,this.startSyncReadReceipt())}stopObservingReadReceiptQueue(){this.isActive=!1;this.jobQueue.map((e=>"syncing"===e.syncState?Object.assign(Object.assign({},e),{syncState:"create"}):e)),this.timer&&clearInterval(this.timer)}onSessionEstablished(){this.startObservingReadReceiptQueue()}onSessionDestroyed(){this.stopObservingReadReceiptQueue(),this.jobQueue=[]}onTokenExpired(){this.stopObservingReadReceiptQueue()}onNetworkOffline(){this.stopObservingReadReceiptQueue()}onNetworkOnline(){this.startObservingReadReceiptQueue()}markRead(e,t){var r;const n=["subChannelUnreadInfo","get",e],s=null===(r=Ee(n))||void 0===r?void 0:r.data;s&&t>s.readToSegment&&(s.readToSegment=t,s.unreadCount=Math.max(s.lastSegment-t,0),el(s.channelId)),Se(n,s),this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var r;const n=null===(r=Ee(["readReceipt",e]))||void 0===r?void 0:r.data;if(n){if(n.latestSegment<t)Se(["readReceipt",e],Object.assign(Object.assign({},n),{latestSegment:t}));else if(n.latestSyncSegment>=t)return}else{Se(["readReceipt",e],{subChannelId:e,latestSegment:t,latestSyncSegment:0})}let s=this.getSyncJob(e);null===s||"syncing"===s.syncState?(s={subChannelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(s)):s.segment<t&&(s.segment=t)}getSyncJob(e){return this.jobQueue.find((t=>t.subChannelId===e))||null}enqueueJob(e){this.jobQueue.length<this.JOB_QUEUE_SIZE||this.jobQueue.shift(),this.jobQueue.push(e)}removeJobFromQueue(e){const t=this.jobQueue.indexOf(e);t>-1&&this.jobQueue.splice(t,1)}}let rl=null;var nl=()=>(rl||(rl=new tl),rl);const sl=(e,t)=>{var r;return null!==(r=null!=t?t:(e=>{var t,r;const n={creatorId:"creatorPrivateId"in e?e.creatorPrivateId:e.creatorId,feedId:null!==(t=e.messageFeedId)&&void 0!==t?t:e.subChannelId,contentId:e.messageId};return null===(r=Ee(["messageMarker","get",de("messageMarker")(n)]))||void 0===r?void 0:r.data})(e))&&void 0!==r?r:{readCount:0,deliveredCount:0}},il={comment:Zo,post:e=>Object.assign(Object.assign({},e),{analytics:{markAsViewed:()=>{Yo().markPostAsViewed(e.postId)}},get latestComments(){return e.comments&&e.comments.map((e=>{var t;const r=null===(t=Ee(["comment","get",e]))||void 0===t?void 0:t.data;return r?Zo(r):null})).filter(Boolean)||[]},get creator(){const t=Ee(["user","get",e.postedUserId]);if(null==t?void 0:t.data)return Qo(t.data)}}),user:Qo,category:e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return null;let r={fileId:(null===(t=e.avatarFileId)||void 0===t?void 0:t.toString())?e.avatarFileId.toString():"",type:"image",fileUrl:"",createdAt:"",attributes:{name:"",extension:"",size:"",mimeType:"",metadata:{exif:{},gps:{},width:0,height:0,isFull:!1}}};const n=Ee(["file","get",`${e.avatarFileId}`]);return(null==n?void 0:n.data)&&(r=null==n?void 0:n.data),r}}),story:e=>{const t=Yo(),r=Ee(["storyTarget","get",e.targetId]),n=Ee(["community","get",e.targetId]);return Object.assign(Object.assign({},e),{analytics:{markAsSeen:()=>{e.expiresAt&&"synced"===e.syncState&&t.markStoryAsViewed(e)},markLinkAsClicked:()=>{e.expiresAt&&"synced"===e.syncState&&t.markStoryAsClicked(e)}},get videoData(){var t,r;const n=Ee(["file","get",null===(r=null===(t=e.data)||void 0===t?void 0:t.videoFileId)||void 0===r?void 0:r.original]);if(!n)return;const{data:s}=n;return s||void 0},get imageData(){var t,r;if(!(null===(t=e.data)||void 0===t?void 0:t.fileId))return;const n=Ee(["file","get",null===(r=e.data)||void 0===r?void 0:r.fileId]);if(!n)return;const{data:s}=n;return s?Object.assign(Object.assign({},s),{fileUrl:`${s.fileUrl}?size=full`}):void 0},get community(){if("community"===e.targetType&&n)return(null==n?void 0:n.data)||void 0},get communityCategories(){if("community"!==e.targetType)return;if(!n)return;const{data:{categoryIds:t}}=n;return 0!==t.length?t.map((e=>{const t=Ee(["category","get",e]);return(null==t?void 0:t.data)||void 0})).filter((e=>void 0!==e)):void 0},get creator(){const t=Ee(["user","get",e.creatorPublicId]);if(null==t?void 0:t.data)return Qo(t.data)},get storyTarget(){if(null==r?void 0:r.data)return Jo(r.data)},get isSeen(){const t=Ee(["story-last-seen",e.targetId]);if(!(null==r?void 0:r.data))return!1;const n=(null==t?void 0:t.data)?new Date(t.data).getTime():0,s=new Date(null==r?void 0:r.data.lastStorySeenExpiresAt).getTime()||0,i=new Date(e.expiresAt).getTime();return Math.max(n,s)>=i}})},storyTarget:Jo,message:e=>{const t=Mo(e,["creatorPrivateId"]);return Object.assign(Object.assign({},t),{get readCount(){return sl(e).readCount},get deliveredCount(){return sl(e).deliveredCount},markRead:()=>{const{subChannelId:t,channelSegment:r}=e;nl().markRead(t,r)}})}},al=e=>{var t;const r=e.messagePreviewId?$o(e.channelId):null,n=null===(t=Ee(["user","get",null==r?void 0:r.creatorId]))||void 0===t?void 0:t.data,s=r?Object.assign(Object.assign({},r),{user:n?il.user(n):void 0}):null;return Object.assign(Object.assign({},e),{messagePreview:s})},ol=e=>{var t,r;const n={messagePreviewChannel:null!==(r=null===(t=e.messagePreviews)||void 0===t?void 0:t.map((t=>(t=>{var r;const n=null===(r=e.messageFeedsInfo)||void 0===r?void 0:r.find((e=>e.messageFeedId===t.messageFeedId)),{channelPublicId:s,messageFeedId:i,data:a,dataType:o,isDeleted:l,segment:c,creatorPublicId:d,createdAt:u,updatedAt:h}=t;return{channelId:s,subChannelId:i,data:a,dataType:o,isDeleted:l,segment:c,creatorId:d,createdAt:u,updatedAt:h,subChannelName:null==n?void 0:n.name,messagePreviewId:null==n?void 0:n.messagePreviewId,subChannelUpdatedAt:null==n?void 0:n.updatedAt}})(t))))&&void 0!==r?r:[]};Oo(n)},ll=e=>{var t,r;return null!==(r=null===(t=Ee(["messagePreviewSubChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==r?r:null},cl=e=>{var t;const r=e.messagePreviewId?ll(e.subChannelId):null,n=r?Object.assign(Object.assign({},r),{user:null===(t=Ee(["user","get",null==r?void 0:r.creatorId]))||void 0===t?void 0:t.data}):null;return Object.assign(Object.assign({},e),{messagePreview:n})},dl=e=>{var t,r;const n={messagePreviewSubChannel:null!==(r=null===(t=e.messages)||void 0===t?void 0:t.map((t=>(t=>{var r;const n=null===(r=e.messageFeeds)||void 0===r?void 0:r.find((e=>e.messageFeedId===t.messageFeedId)),{channelPublicId:s,messageFeedId:i,messageId:a,creatorPublicId:o,data:l,dataType:c,isDeleted:d,segment:u,createdAt:h,updatedAt:f}=t;return{messagePreviewId:a,channelId:s,subChannelId:i,data:l,dataType:c,isDeleted:d,segment:u,creatorId:o,createdAt:h,updatedAt:f,subChannelName:null==n?void 0:n.name,subChannelUpdatedAt:null==n?void 0:n.updatedAt}})(t))))&&void 0!==r?r:[]};Oo(n)};function ul(e){const t=Object.create(Object.getPrototypeOf(e)),r=Object.getOwnPropertyDescriptors(e);return Object.defineProperties(t,r),t}function hl(e,t,r){Se(["subChannel","get",e],Object.assign(ul(t),r))}const fl=async e=>{var t,r,n,s;const{channelId:i,messageId:a,creatorId:o,createdAt:l,updatedAt:c,data:d,dataType:u,subChannelId:h,channelSegment:f,isDeleted:p}=e,g=null===(t=Ee(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(!g||g.segment<=e.channelSegment){const t=null===(r=Ee(["subChannel","get",h]))||void 0===r?void 0:r.data;Se(["messagePreviewSubChannel","get",e.subChannelId],{channelId:i,creatorId:o,messagePreviewId:a,createdAt:l,updatedAt:c,subChannelId:h,data:d,dataType:u,segment:f,isDeleted:p,subChannelUpdatedAt:null==t?void 0:t.updatedAt,subChannelName:null==t?void 0:t.displayName}),hl(e.subChannelId,t,{messagePreviewId:a})}const m=null===(n=Ee(["messagePreviewChannel","get",e.channelId]))||void 0===n?void 0:n.data;if(!m||new Date(m.createdAt).valueOf()<=new Date(e.createdAt).valueOf()){const t=null===(s=Ee(["subChannel","get",h]))||void 0===s?void 0:s.data;Se(["messagePreviewChannel","get",e.channelId],{channelId:i,creatorId:o,messagePreviewId:a,createdAt:l,updatedAt:c,subChannelId:h,data:d,dataType:u,segment:f,isDeleted:p,subChannelUpdatedAt:null==t?void 0:t.updatedAt,subChannelName:null==t?void 0:t.displayName})}},pl=async e=>{var t,r,n,s;const{channelId:i,messageId:a,creatorId:o,createdAt:l,updatedAt:c,data:d,dataType:u,subChannelId:h,channelSegment:f,isDeleted:p}=e,g=null===(t=Ee(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(g&&g.messagePreviewId===e.messageId){const t=null===(r=Ee(["subChannel","get",h]))||void 0===r?void 0:r.data;hl(e.subChannelId,t,{messagePreviewId:a}),Se(["messagePreviewSubChannel","get",e.subChannelId],{channelId:i,creatorId:o,messagePreviewId:a,createdAt:l,updatedAt:c,subChannelId:h,data:d,dataType:u,segment:f,isDeleted:p,subChannelUpdatedAt:null==e?void 0:e.updatedAt,subChannelName:null==t?void 0:t.displayName})}const m=null===(n=Ee(["messagePreviewChannel","get",e.channelId]))||void 0===n?void 0:n.data;if(m&&m.messagePreviewId===e.messageId){const t=null===(s=Ee(["subChannel","get",h]))||void 0===s?void 0:s.data;Se(["messagePreviewChannel","get",e.channelId],{channelId:i,creatorId:o,messagePreviewId:a,createdAt:l,updatedAt:c,subChannelId:h,data:d,dataType:u,segment:f,isDeleted:p,subChannelUpdatedAt:null==t?void 0:t.updatedAt,subChannelName:null==t?void 0:t.displayName})}},gl=async e=>{var t,r,n,s;const{channelId:i,subChannelId:a}=e,o=null===(t=Ee(["messagePreviewChannel","get",i]))||void 0===t?void 0:t.data;if((null==o?void 0:o.subChannelId)===a){const e=null===(r=Ee(["subChannel","get",a]))||void 0===r?void 0:r.data;Se(["messagePreviewChannel","get",i],Object.assign(Object.assign({},o),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}const l=null===(n=Ee(["messagePreviewSubChannel","get",a]))||void 0===n?void 0:n.data;if(l&&new Date(l.updatedAt).valueOf()>new Date(e.updatedAt).valueOf()){const e=null===(s=Ee(["subChannel","get",a]))||void 0===s?void 0:s.data;Se(["messagePreviewSubChannel","get",a],Object.assign(Object.assign({},l),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}},ml=(e,t)=>{var r,n,s,i,a;const o=ve();return o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()?null!==(n=null===(r=(e=>{var t;return null===(t=Ee(["channelUnreadInfo","get",e]))||void 0===t?void 0:t.data})(e.channelId))||void 0===r?void 0:r.unreadCount)&&void 0!==n?n:0:(null==t?void 0:t.isDeleted)?0:null!==(a=null!==(s=null==t?void 0:t.unreadCount)&&void 0!==s?s:null===(i=(e=>{var t;const r={entityId:e,userId:Ke()._id};return null===(t=Ee(["channelMarker","get",de("channelMarker")(r)]))||void 0===t?void 0:t.data})(e.channelId))||void 0===i?void 0:i.unreadCount)&&void 0!==a?a:0},yl=(e,t)=>{var r,n,s,i;const a=ve();return a.isUnreadCountEnabled&&a.getMarkerSyncConsistentMode()?null!==(n=null===(r=(e=>{var t;return null===(t=Ee(["channelUnreadInfo","get",e]))||void 0===t?void 0:t.data})(e.channelId))||void 0===r?void 0:r.isMentioned)&&void 0!==n&&n:void 0!==(null==t?void 0:t.hasMentioned)?null==t?void 0:t.hasMentioned:null!==(i=null===(s=(e=>{var t;const r={entityId:e,userId:Ke()._id};return null===(t=Ee(["channelMarker","get",de("channelMarker")(r)]))||void 0===t?void 0:t.data})(e.channelId))||void 0===s?void 0:s.hasMentioned)&&void 0!==i&&i},vl=e=>{const{feedMarkers:t,userFeedMarkers:r}=e;if(t.length>0&&r.length>0){const e=[],n=new Map(t.map((e=>[e.feedId,e])));r.forEach((t=>{const r=n.get(t.feedId);if(r&&r.feedId===t.feedId){const n=r.lastSegment-t.readToSegment,s={subChannelId:r.feedId,channelId:r.entityId,readToSegment:t.readToSegment,lastSegment:r.lastSegment,lastMentionSegment:t.lastMentionSegment,unreadCount:Math.max(0,n),isMentioned:t.isMentioned,isDeleted:r.isDeleted,createdAt:t.createdAt,updatedAt:t.updatedAt};Oo({subChannelUnreadInfo:[s]}),e.includes(r.entityId)||e.push(r.entityId)}})),e.forEach((e=>{el(e)}))}},bl=["broadcast","conversation","community"],wl=({type:e})=>bl.includes(e);function El(e,t={isMessagePreviewUpdated:!0}){var r;let{messagePreviewId:n}=e;const s=null===(r=Ee(["messagePreviewChannel","get",e.channelId]))||void 0===r?void 0:r.data;return(null==s?void 0:s.messagePreviewId)&&!t.isMessagePreviewUpdated&&(n=s.messagePreviewId),Object.assign(Object.assign({get unreadCount(){return ml(e)},get hasMentioned(){return yl(e)},get isMentioned(){return yl(e)},get subChannelsUnreadCount(){return ml(e)}},e),{defaultSubChannelId:e._id,isUnreadCountSupport:wl(e),messagePreviewId:n})}const Sl=(e,t={isMessagePreviewUpdated:!0})=>{Oo({channels:e.channels.map((e=>El(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated})))})},Tl=async(e,t={isMessagePreviewUpdated:!0})=>{const r=ve(),n=await r.getMessagePreviewSetting(!1);if(r.isUnreadCountEnabled&&r.getMarkerSyncConsistentMode()){const t=await(async e=>{const t=ve();t.log("channel/getUserMessageFeedMakers",e);const{data:r}=await t.http.get("/api/v1/markers/user-message-feed",{params:{channelIds:e}});return r})(e.channels.map((({channelId:e})=>e))),{feedMarkers:r,userFeedMarkers:n}=t;vl({feedMarkers:r,userFeedMarkers:n})}t.isMessagePreviewUpdated&&"no-message-preview"!==n&&e.messagePreviews&&e.messagePreviews.length>0&&ol(e);const s=e.channels.filter(wl).map((({channelId:e})=>e));if(s.length>0){Sl(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated});try{await(async e=>{const t=ve();t.log("channel/getChannelMarkers",e);const{data:r}=await t.http.get("/api/v1/markers/channels",{params:{channelIds:e}}),{userEntityMarkers:n,userMarkers:s}=r,i=Bo(n),a=t.cache&&Date.now();return t.cache&&Oo({userEntityMarkers:i,userMarkers:s},{cachedAt:a}),Je("local.channelMarker.fetched",{userEntityMarkers:i}),Je("local.userMarker.fetched",{userMarkers:s}),{data:i,cachedAt:a}})(s)}catch(e){}}const i=e.channels.map((e=>El(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated}))),a=Fo(e.channelUsers),o=Mo(e,["messageFeedsInfo","messagePreviews"]);return Object.assign(Object.assign({},o),{channels:i,channelUsers:a})},Cl=async e=>{const t=ve();t.log("channel/getChannelByIds",e);const r=e.map((e=>encodeURIComponent(e)));let n;try{n=(await t.http.get("/api/v3/channels/list",{params:{channelIds:r}})).data}catch(t){throw e.forEach((e=>{C(null==t?void 0:t.code)&&Po("channel",e)})),t}const s=await Tl(n),i=t.cache&&Date.now();return t.cache&&Oo(s,{cachedAt:i}),{data:s.channels,cachedAt:i}};Cl.locally=e=>{var t;const r=ve();if(r.log("channel/getChannelByIds.locally",e),!r.cache)return;const n=e.map((e=>Ee(["channel","get",e]))).filter(Boolean);if((null==n?void 0:n.length)<e.length)return;return{data:n.map((({data:e})=>e)),cachedAt:(null===(t=n.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0]).cachedAt}};const kl=async()=>{const e=ve();e.log("channel/getUserMarker");const{data:t}=await e.http.get("/api/v1/markers/userMarker"),{userMarkers:r}=t,n=e.cache&&Date.now();e.cache&&Oo({userMarkers:r},{cachedAt:n}),Je("local.userMarker.fetched",{userMarkers:r});return{data:r.reduce(((e,t)=>null==e||new Date(e.lastSyncAt).getTime()<new Date(t.lastSyncAt).getTime()?t:e),void 0),cachedAt:n}},Al=e=>!0===e&&void 0;function Il(e,t,r){var n,s;if(r)return r.hasMentioned;const i=ve();if(i.isUnreadCountEnabled&&i.getMarkerSyncConsistentMode()){const e=null===(n=Ee(["subChannelUnreadInfo","get",t]))||void 0===n?void 0:n.data;return!!e&&e.isMentioned}const a={entityId:e,feedId:t,userId:Ke()._id},o=null===(s=Ee(["subChannelMarker","get",de("subChannelMarker")(a)]))||void 0===s?void 0:s.data;return!!o&&o.hasMentioned}const _l=["broadcast","conversation","community"],Rl=({channelType:e})=>_l.includes(e);function Ll(e){var{channelId:t,channelPublicId:r,channelType:n,childCount:s,creatorId:i,creatorPublicId:a,lastMessageId:o,lastMessageTimestamp:l,messageFeedId:c,name:d}=e,u=Mo(e,["channelId","channelPublicId","channelType","childCount","creatorId","creatorPublicId","lastMessageId","lastMessageTimestamp","messageFeedId","name"]);return Object.assign(Object.assign({get unreadCount(){return function(e,t,r){var n,s;if(r)return r.unreadCount;const i=ve();if(i.isUnreadCountEnabled&&i.getMarkerSyncConsistentMode()){const e=null===(n=Ee(["subChannelUnreadInfo","get",t]))||void 0===n?void 0:n.data;return e?e.isDeleted?0:e.unreadCount:0}const a={entityId:e,feedId:t,userId:Ke()._id},o=null===(s=Ee(["subChannelMarker","get",de("subChannelMarker")(a)]))||void 0===s?void 0:s.data;return o?o.unreadCount:0}(t,c)},get hasMentioned(){return Il(t,c)},get isMentioned(){return Il(t,c)}},u),{channelId:r,creatorId:a,displayName:d,lastActivity:l,latestMessageId:o,messageCount:s,subChannelId:c,isUnreadCountSupport:Rl({channelType:n})})}function Dl(e,t,r){var n;const{channelPublicId:s,childCount:i,creatorPublicId:a,mentionedUsers:o,messageFeedId:l,myReactions:c,reactionCount:d,reactions:u,referenceId:h,segment:f,messageId:p,creatorId:g}=e,m=Mo(e,["channelPublicId","childCount","creatorPublicId","mentionedUsers","messageFeedId","myReactions","reactionCount","reactions","referenceId","segment","messageId","creatorId"]);let y;h&&(y=Ee(["message","get",h])),y||(y=Ee(["message","get",p]));const v=Object.assign(Object.assign({},m),{messageId:p,channelId:s,channelSegment:f,childrenNumber:i,creatorId:a,creatorPrivateId:e.creatorId,reactions:null!=u?u:{},myReactions:c||(null!==(n=null==y?void 0:y.data.myReactions)&&void 0!==n?n:[]),reactionsCount:d,subChannelId:l,uniqueId:y?y.data.uniqueId:p,referenceId:h});return o&&(v.mentionees=o.map((e=>"channel"===e.type?e:{type:"user",userIds:e.userPublicIds}))),t&&t.length&&r&&((e,t,r)=>{const n=ve(),s=Ee(["message","get",e.messageId]),i=(null==s?void 0:s.data.myReactions)||[];Object.assign(e,{myReactions:i});const a=t[0];a&&a.userId===n.userId&&("message.reactionAdded"!==r||i.includes(a.reactionName)||Object.assign(e,{myReactions:[...i,a.reactionName]}),"message.reactionRemoved"===r&&i.includes(a.reactionName)&&Object.assign(e,{myReactions:i.filter((e=>e!==a.reactionName))}))})(v,t,r),v}const xl={},Ol=async(e,t)=>{const r=e.messages.map((({messageId:e})=>e));if(r.length>0){Oo({messages:(n=e).messages.map((e=>Dl(e,n.reactions)))});const t=r.join("");xl[t]&&clearTimeout(xl[t]),xl[t]=setTimeout((()=>{try{(async e=>{const t=ve();t.log("channel/getMessageMarkers",e);const{data:r}=await t.http.get("/api/v1/markers/messages",{params:{messageIds:e}}),{contentMarkers:n,feedMarkers:s,userMarkers:i}=r,a=t.cache&&Date.now();t.cache&&Oo({contentMarkers:n,feedMarkers:s,userMarkers:i},{cachedAt:a}),Je("local.feedMarker.fetched",{feedMarkers:s}),Je("local.messageMarker.fetched",{contentMarkers:n}),Je("local.userMarker.fetched",{userMarkers:i})})(r)}catch(e){}}),2e3)}var n;const{messageFeeds:s}=e,i=Mo(e,["messageFeeds"]);return s&&s.length>0&&(null==s||s.forEach((e=>{var t,r;const n=null!==(r=null===(t=Ee(["subChannel","get",e.messageFeedId]))||void 0===t?void 0:t.data)&&void 0!==r?r:{},s=Mo(Ll(e),["unreadCount","hasMentioned","isMentioned"]);hl(e.messageFeedId,n,s)}))),Object.assign(Object.assign({},i),{messages:e.messages.map((r=>Dl(r,e.reactions,t)))})};function Pl(e){var{subChannelId:t,mentionees:r,dataType:n,data:s}=e,i=Mo(e,["subChannelId","mentionees","dataType","data"]);return n===c.IMAGE||n===c.FILE?Object.assign({messageFeedId:t,mentionedUsers:r,dataType:n,data:Object.assign({caption:""},s)},i):Object.assign({messageFeedId:t,mentionedUsers:r,dataType:n,data:s},i)}function Ml(e){var{sortBy:t,subChannelId:r,tags:n,includingTags:s,excludingTags:i,includeDeleted:a,aroundMessageId:o,limit:l,type:c}=e,d=Mo(e,["sortBy","subChannelId","tags","includingTags","excludingTags","includeDeleted","aroundMessageId","limit","type"]);const u=Object.assign(Object.assign({},d),{messageFeedId:r,isDeleted:Al(a),options:{sortBy:t,limit:l||h,around:o}});return n&&(u.includeTags=n),s&&(u.includeTags=s),c&&(u.dataType=c),i&&(u.excludeTags=i),u}const Fl=["broadcast","conversation","community"],Ul=({channelType:e})=>Fl.includes(e),Nl=async e=>{const t=e.messageFeeds.filter(Ul).map((({messageFeedId:e})=>e));if(t.length>0){(e=>{Oo({messageFeeds:e.messageFeeds.map((e=>Ll(e)))})})(e);try{await(async(e,t={limit:100})=>{const r=ve();r.log("channel/getSubChannelMarkers",e,t);const{data:n}=await r.http.get("/api/v1/markers/message-feeds",{params:{messageFeedIds:e,options:{token:X(t,"skiplimit")}}}),{paging:s}=n,i=Mo(n,["paging"]),{userEntityMarkers:a,userFeedMarkers:o,userMarkers:l,feedMarkers:c}=i;r.isUnreadCountEnabled&&r.getMarkerSyncConsistentMode()&&vl({feedMarkers:c,userFeedMarkers:o});const d=Bo(a),u=jo(o),h=r.cache&&Date.now();r.cache&&Oo({userEntityMarkers:d,userFeedMarkers:u,userMarkers:l},{cachedAt:h}),Je("local.channelMarker.fetched",{userEntityMarkers:d}),Je("local.subChannelMarker.fetched",{userFeedMarkers:u}),Je("local.userMarker.fetched",{userMarkers:l});const f=J(s.next);return{data:u,cachedAt:h,prevPage:J(s.previous),nextPage:f}})(t)}catch(e){}}dl(e);const r=e.messageFeeds.map(Ll),n=e.messages.map((e=>Dl(e)));return Object.assign(Object.assign({},e),{messageFeeds:r,messages:n})};const Bl=e=>{const t=ve();return Xe(t,"client/onSessionStateChange","sessionStateChange",e)},jl=(e,t)=>{const r=setInterval(e,t);return()=>clearInterval(r)},$l=e=>"undefined"!=typeof window&&window.addEventListener?(window.addEventListener("online",e),()=>window.removeEventListener("online",e)):"undefined"!=typeof document&&document.addEventListener?(document.addEventListener("online",e),()=>document.removeEventListener("online",e)):(console.error("Unsupported environment"),()=>console.error("Unsupported environment")),ql=(e,t)=>{const{log:r,cache:n}=ve(),s=[e,v,t];if(!n)return;r("cache/api/isInTombstone",s);const i=Ee(s),{lifeSpan:a}=ae("cache_then_server",18e4);if(i&&se(i.data,a))throw new pe("Item not found!",400400,"error")},Kl=async e=>{const t=ve();t.log("channel/getSubChannel",e),ql("subChannel",e);try{const r=await t.http.get(`/api/v5/message-feeds/${encodeURIComponent(e)}`),n=await Nl(r.data),s=t.cache&&Date.now();return t.cache&&Oo(n,{cachedAt:s}),Je("local.message-feed.fetched",n),{data:n.messageFeeds[0],cachedAt:s}}catch(t){throw C(null==t?void 0:t.code)&&Po("subChannel",e),t}};Kl.locally=e=>{const t=ve();if(t.log("channel/getSubChannel.locally",e),!t.cache)return;const r=Ee(["subChannel","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};let Gl=!1,Hl=[];const Vl={},zl=async()=>{const e=Object.entries(Vl).filter((([,e])=>e)).map((([e])=>e));return 0!==e.length&&(async e=>{const t=ve();t.log("subChannel/readingAPI",e);const{data:r}=await t.http.post("/api/v1/markers/message-feeds/reading",{messageFeedIds:e}),{userEntityMarkers:n,userFeedMarkers:s,feedMarkers:i,userMarkers:a}=r,o=Bo(n),l=jo(s),c=t.cache&&Date.now();return t.cache&&Oo({userEntityMarkers:o,userFeedMarkers:l,feedMarkers:i,userMarkers:a},{cachedAt:c}),Je("local.feedMarker.fetched",{feedMarkers:i}),Je("local.channelMarker.fetched",{userEntityMarkers:o}),Je("local.subChannelMarker.fetched",{userFeedMarkers:l}),Je("local.userMarker.fetched",{userMarkers:a}),!0})(e)},Wl=()=>{Gl=!1},Yl=()=>(Gl=!0,Bl((e=>{"notLoggedIn"===e&&Wl()})),()=>{Wl()}),Ql=async e=>{const t=await(async e=>{const t=Kl.locally(e);if(t)return t.data.channelId;const{data:r}=await Kl(e);return r.channelId})(e),r=at({channelId:t,subChannelId:e});Hl.push(ht(r))};jl((async()=>{Gl&&await zl()}),3e4);const Xl=async e=>{const t=ve();t.log("channel/getSubChannels",e);const r=await t.http.get("/api/v5/message-feeds/list",{params:{messageFeedIds:e.map(encodeURIComponent)}}),n=await Nl(r.data),s=t.cache&&Date.now();return t.cache&&Oo(n,{cachedAt:s}),Je("local.message-feed.fetched",n),{data:n.messageFeeds,cachedAt:s}};Xl.locally=e=>{var t;const r=ve();if(r.log("channel/getSubChannels.locally",e),!r.cache)return;const n=e.map((e=>Ee(["subChannel","get",e]))).filter(Boolean);if((null==n?void 0:n.length)<e.length)return;return{data:n.map((({data:e})=>e)),cachedAt:(null===(t=n.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0]).cachedAt}};const Jl=async(e=!0)=>{var t;const r=null===(t=Ee(["MessagePreviewSetting"]))||void 0===t?void 0:t.data;if(!e&&r)return r;const n=await(async()=>{const e=ve(),{data:t}=await e.http.get("/api/v3/network-settings/chat");return t})();var s;return(s=n).messagePreview.enabled?s.messagePreview.isIncludeDeleted?"message-preview-include-deleted":"message-preview-not-include-deleted":"no-message-preview"},Zl=async()=>{const e=ve(),{data:t}=await e.http.get("/api/v3/network-settings/social");return t.socialNetworkSetting},ec=(e,t)=>{var r;const n=null===(r=Ee(["users","get",e]))||void 0===r?void 0:r.data;return!!n&&n.permissions.some((e=>e===t))},tc=e=>{const{userId:t}=ve();return{currentUser:()=>ec(t,e),community:r=>((e,t,r)=>{var n;if(!e)return!1;const s=null===(n=Ee(["communityUsers","get",`${r}#${e}`]))||void 0===n?void 0:n.data;return!!s&&(!!s.permissions.some((e=>e===t))||ec(e,t))})(t,e,r),channel:r=>((e,t,r)=>{var n;if(!e)return!1;const s=null===(n=Ee(["channelUsers","get",`${r}#${e}`]))||void 0===n?void 0:n.data;return!!s&&(!!s.permissions.some((e=>e===t))||ec(e,t))})(t,e,r)}},rc=async e=>{const t=ve();if(t.log("channel/markerSync"),0===e.length)return!1;const{data:r}=await t.http.post("/api/v3/allowlists/verify",{data:e});return r.success},nc=async e=>{const t=ve();if(t.log("channel/markerSync"),0===e.length)return!1;const{data:r}=await t.http.post("/api/v3/blocklists/verify",{data:e});return r.success},sc=async()=>{const e=ve(),{data:t}=await e.http.get("/api/v3/network-settings/feed-setting");return Object.fromEntries(t.feedSettings.map((({feedType:e,contentSettings:t})=>[e,t])))},ic={notLoggedIn:["establishing"],terminated:["establishing"],establishing:["notLoggedIn","established"],established:["notLoggedIn","terminated","tokenExpired","establishing"],tokenExpired:["establishing"]},ac=e=>{const t=ve();t.log("client/api/setSessionState",e);const{sessionState:r}=t;if(r===e)return!1;if(!((e,t)=>ic[e].includes(t))(r,e))throw new fe(`Session state cannot change from ${r} to ${e}`,8e5,"error");return t.sessionState=e,t.emitter.emit("sessionStateChange",e),!0},oc=async e=>{const t=ve();ac("establishing");const{accessToken:r,users:n,expiresAt:s,issuedAt:i,refreshToken:a}=await(async e=>{const t=ve();t.log("client/api/getToken",e);const r=Ro(),{data:n}=await t.http.post("/api/v4/sessions",Object.assign(Object.assign({},e),{deviceInfo:r}),{headers:{"X-API-Key":t.apiKey}});return n})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${r}`,t.http.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.ws.io.opts.query={token:r},t.token={accessToken:r,issuedAt:i,expiresAt:s},ac("established"),{accessToken:r,users:n,refreshToken:a}},lc=e=>{const t=we(["subChannelUnreadInfo","get"]);if(t){(null==t?void 0:t.filter((({data:t})=>t.channelId===e))).forEach((({key:e,data:t})=>{Se(e,Object.assign(Object.assign({},t),{isDeleted:!0}))}))}},cc=e=>{var t;const r=["channelUnreadInfo","get",e];(null===(t=Ee(r))||void 0===t?void 0:t.data)&&ke(r)},dc=e=>{const t=ve();return Xe(t,"onChannelDeleted","channel.deleted",(async r=>{const n=await Tl(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&n.channels.forEach((e=>{lc(e.channelId),cc(e.channelId)})),Oo(n),e(n.channels[0])}))},uc=e=>{const t=ve();return Xe(t,"onChannelMemberBanned","channel.banned",(async r=>{const n=await Tl(r),{channels:s,channelUsers:i}=n,a=i.some((e=>"banned"===e.membership&&e.userId===t.userId));t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&a&&n.channels.forEach((e=>{lc(e.channelId),cc(e.channelId)})),Oo(n),e(s[0],i.find((e=>"banned"===e.membership)))}))},hc=(e,t)=>{const r=ve();return Xe(r,e,e,(e=>{r.cache&&Oo(e),t(e.users[0])}))},fc=e=>hc("user.deleted",e);const pc=async()=>{const e=ve();return e.log("client/api/disconnectClient"),e.mqtt.connected&&e.mqtt.disconnect(),e.ws.connected&&e.ws.disconnect(),"established"===e.sessionState&&ac("notLoggedIn"),e.emitter.all.clear(),e.ws.removeAllListeners(),e.mqtt.removeAllListeners(),e.userId=void 0,e.token=void 0,e.http.defaults.headers.common.Authorization="",e.http.defaults.metadata={tokenExpiry:"",isGlobalBanned:!1,isUserDeleted:!1},e.ws.io.opts.query={token:""},"tokenExpired"!==e.sessionState&&e.cache&&(e.cache={data:{}}),!0},gc=e=>{const t=ve();ac("terminated"),t.http.defaults.metadata&&("globalBan"===e&&(t.http.defaults.metadata.isGlobalBanned=!0),"userDeleted"===e&&(t.http.defaults.metadata.isUserDeleted=!0)),t.sessionHandler=void 0,pc()},mc=["disconnected","error","connect_error","reconnect_error","reconnect_failed"],yc=e=>{const t=ve(),r=mc.map((r=>Xe(t,`client/onConnectionError(${r})`,r,(t=>{const n=(null==t?void 0:t.code)?new fe(t.message,t.code,"fatal"):new me(r);e(n)}))));return()=>{r.forEach((e=>e()))}},vc=e=>{const t=ve();return Xe(t,"client/onConnectionError(user.didGlobalBan)","user.didGlobalBan",e)},bc=e=>{const t=de("channelMarker")({userId:Ke()._id,entityId:e.channelId});ke(["channelMarker","get",t],!0)},wc=e=>{const t=ve();return Xe(t,"onChannelCreated","channel.created",(async t=>{const r=await Tl(t);Oo(r),e(r.channels[0])}))},Ec=e=>{const t=ve(),r=[Xe(t,"onChannelUpdated","channel.updated",(async t=>{const r=await Tl(t);Oo(r),e(r.channels[0])})),Xe(t,"onChannelUpdated","local.channel.updated",(t=>e(t.channels[0])))];return()=>{r.forEach((e=>e()))}},Sc=e=>{const t=ve();return Xe(t,"onChannelJoined","channel.joined",(async t=>{const r=await Tl(t),{channels:n,channelUsers:s}=r;Oo(r),e(n[0],s[0])}))},Tc=e=>{const t=ve();return Xe(t,"onChannelLeft","channel.left",(async r=>{const{userId:n}=ve(),{channelUsers:s}=r,i=s.some((e=>e.userId===n)),a=await Tl(r,{isMessagePreviewUpdated:i});t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&i&&a.channels.forEach((e=>{lc(e.channelId),cc(e.channelId)}));const{channels:o,channelUsers:l}=a;Oo(a),e(o[0],l[0])}))},Cc=e=>{const t=ve();return Xe(t,"onChannelMuted","channel.setMuted",(async t=>{const r=await Tl(t);Oo(r),e(r.channels[0])}))},kc=e=>{const t=ve();return Xe(t,"onChannelMemberAdded","channel.membersAdded",(async t=>{const r=await Tl(t),{channels:n,channelUsers:s}=r;Oo(r),e(n[0],s.find((e=>"member"===e.membership)))}))},Ac=e=>{const t=ve();return Xe(t,"onChannelMemberRemoved","channel.membersRemoved",(async t=>{const r=await Tl(t),{channels:n,channelUsers:s}=r;Oo(r),e(n[0],s[0])}))},Ic=e=>{const t=ve();return Xe(t,"onChannelMemberUnbanned","channel.unbanned",(async t=>{const r=await Tl(t),{channels:n,channelUsers:s}=r;Oo(r),e(n[0],s.find((e=>"none"===e.membership)))}))},_c=e=>{const t=ve();return Xe(t,"onChannelMemberRoleAdded","local.channel-moderator.role-added",(async t=>{const{channels:r,channelUsers:n}=t;e(r[0],n.find((e=>"member"===e.membership)))}))},Rc=e=>{const t=ve();return Xe(t,"onChannelMemberRoleRemoved","local.channel-moderator.role-removed",(async t=>{const{channels:r,channelUsers:n}=t;e(r[0],n.find((e=>"member"===e.membership)))}))},Lc=e=>{const t=ve();return Xe(t,"feedMarker/onFeedMarkerUpdated","marker.feed-updated",(t=>{Oo(t),e(t.feedMarkers[0])}))},Dc=e=>{const t=ve(),r=[Xe(t,"message/onMessageCreated","message.created",(async r=>{const n=await Ol(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&r.messages.forEach((e=>{(e=>{var t;const r=ve(),n=["subChannelUnreadInfo","get",e.messageFeedId],s=null===(t=Ee(n))||void 0===t?void 0:t.data;if(!s)return;const i=s.lastSegment<e.segment?e.segment:s.lastSegment,a=i-s.readToSegment;let{lastMentionSegment:o}=s;e.mentionedUsers&&e.mentionedUsers.length>0&&e.mentionedUsers.forEach((t=>{("channel"===t.type||"user"===t.type&&r.userId&&t.userPublicIds.includes(r.userId))&&(o=e.segment)}));const l=Object.assign(Object.assign({},s),{lastMentionSegment:o,lastSegment:i,isMentioned:!(s.readToSegment>=o),unreadCount:Math.max(a,0)});Se(n,l)})(e),el(e.channelId)})),Oo(n),n.messages.forEach((t=>{e(t)}))}))];return()=>{r.forEach((e=>e()))}},xc=e=>{const t=ve(),r=[Xe(t,"message/onMessageCreated","local.message.created",(t=>t.messages.forEach((t=>{e(t)}))))];return()=>{r.forEach((e=>e()))}},Oc=e=>{const t=ve();return Xe(t,"onSubChannelCreated","message-feed.created",(async r=>{const n=await Nl(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&(e=>{e.messageFeeds.forEach((e=>{const t={channelId:e.channelId,subChannelId:e.messageFeedId,unreadCount:0,readToSegment:0,lastMentionSegment:0,lastSegment:0,isMentioned:!1,isDeleted:!1,createdAt:e.createdAt,updatedAt:e.updatedAt};Se(["subChannelUnreadInfo","get",t.subChannelId],t)}))})(r),Oo(n),e(n.messageFeeds[0])}))},Pc=e=>{const t=ve(),r=[Xe(t,"onSubChannelDeleted","message-feed.deleted",(async r=>{const n=await Nl(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&n.messageFeeds.forEach((e=>{(e=>{var t;const r=["subChannelUnreadInfo","get",e],n=null===(t=Ee(r))||void 0===t?void 0:t.data;n&&Se(r,Object.assign(Object.assign({},n),{isDeleted:!0}))})(e.subChannelId),el(e.channelId)})),Oo(n),e(n.messageFeeds[0])})),Xe(t,"local.message-feed.deleted","local.message-feed.deleted",(t=>e(t.messageFeeds[0])))];return()=>{r.forEach((e=>e()))}},Mc=async e=>{const t=ve();t.log("channel/markerSync");const{data:r}=await t.http.post("/api/v1/markers/sync",{deviceLastSyncAt:e}),{userEntityMarkers:n,userFeedMarkers:s,feedMarkers:i,userMarkers:a}=r,o=Bo(n),l=jo(s),c=t.cache&&Date.now();return t.cache&&Oo({userEntityMarkers:o,userFeedMarkers:l,feedMarkers:i,userMarkers:a},{cachedAt:c}),Je("local.feedMarker.fetched",{feedMarkers:i}),Je("local.channelMarker.fetched",{userEntityMarkers:o}),Je("local.subChannelMarker.fetched",{userFeedMarkers:l}),Je("local.userMarker.fetched",{userMarkers:a}),{data:r,hasMore:r.feedMarkers.length>0}},Fc=()=>{const e=ve();if(e.log("client/api/isUnreadCountEnabled",e.isUnreadCountEnabled),!e)throw new fe("There is no active client",8e5,"fatal");return!e.isUnreadCountEnabled&&(e.isUnreadCountEnabled=!0,e.emitter.emit("unreadCountEnabled",!0),!0)},Uc=e=>{const t=ve();return Xe(t,"feedMarker/onUserFeedMarkerUpdated","marker.userFeed-updated",(t=>{vl(t),e(t.feedMarkers[0])}))};let Nc=!1,Bc=[],jc=!1,$c=!0,qc=null;const Kc=e=>{null!=e&&(!qc||e.getTime()>qc.getTime())&&(qc=e)},Gc=async()=>{const{data:e}=await kl();null!=e&&Kc(new Date(e.lastSyncAt))};let Hc=[];const Vc=e=>{Hc=e},zc=e=>Hc.push(e),Wc=async()=>{if(!jc&&0!==Hc.length)try{jc=!0,Hc=[];const e=await Mc((null==qc?new Date:qc).toISOString()),t=e.data.userMarkers.reduce(((e,t)=>null==e||e.getTime()<new Date(t.lastSyncAt).getTime()?new Date(t.lastSyncAt):e),null);Kc(t),e.hasMore&&Hc.push("has_more")}catch(e){}finally{jc&&(jc=!1)}},Yc=()=>{Bc.length>0||Bc.push($l((()=>{Hc.push("resume")})),Dc((e=>{Ul(e)&&Hc.push("new message")})),wc((()=>Hc.push("subchannel is created"))),dc((()=>Hc.push("subchannel is deleted"))),Sc((()=>Hc.push("subchannel is joined"))),Tc((()=>Hc.push("subchannel is left"))),Oc((()=>Hc.push("subchannel is created"))),Pc((()=>setTimeout((()=>Hc.push("subchannel is deleted")),2e3))),Lc((()=>Hc.push("feed marker updated"))),(e=>{const t=ve();return Xe(t,"UserMarker/onUserMarkerSync","marker.user-sync",(t=>{const{userMarkers:r,userEntityMarkers:n,userFeedMarkers:s}=t,i=Mo(t,["userMarkers","userEntityMarkers","userFeedMarkers"]),a=Bo(n),o=jo(s);Oo(Object.assign({userMarkers:r,userEntityMarkers:a,userFeedMarker:o},i)),e(r[0])}))})((()=>Hc.push("feed marker updated"))),Uc((()=>Hc.push("feed marker updated"))))},Qc=()=>{Bc.forEach((e=>e())),Bc=[]},Xc=async()=>(await Gc(),zc("start syncing"),$c=!0,Nc=!0,Yc(),Qc),Jc=()=>{Nc=!1,Vc([]),Qc()};jl((async()=>{Nc&&await Wc()}),2e3);const Zc=()=>$c;let ed=[];const td=async(e,t,r)=>{var n,s;const i=ve();let a;i.log("client/api/connectClient",Object.assign({apiKey:i.apiKey,sessionState:i.sessionState},e)),i.userId&&i.userId!==e.userId&&(await pc(),ed.forEach((e=>e())),ed=[]);const o=await _o();try{const{users:r}=await oc(Object.assign(Object.assign({},e),{displayName:(null==e?void 0:e.displayName)||e.userId,deviceId:(null==e?void 0:e.deviceId)||o})),d=r.find((t=>t.userId===e.userId));if(null==d)throw new fe(`${e.userId} has not been founded`,8e5,"error");if(d.isDeleted)return gc("userDeleted"),!1;if(d.isGlobalBanned)return gc("globalBan"),!1;l=i.ws,c=i.emitter,We.forEach((e=>{l.on(e,(t=>{c.emit(e,t)}))})),i.ws.once("connect",(()=>{i.ws.open()})),i.userId=d.userId,i.sessionHandler=t,a=i.accessTokenExpiryWatcher(null===(n=i.token)||void 0===n?void 0:n.expiresAt,null===(s=i.token)||void 0===s?void 0:s.issuedAt,t),Ge(d)}catch(e){throw ac("notLoggedIn"),e}var l,c;if(!0!==(null==r?void 0:r.disableRTE)&&async function(){await tt()}(),await(async()=>{var e;const t=await Jl();if(t===(null===(e=Ee(["MessagePreviewSetting"]))||void 0===e?void 0:e.data))return;Se(["MessagePreviewSetting"],t);const r=[],n=[];if("no-message-preview"===t){const e=we(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{ke(e),e.includes("MessagePreviewChannel")&&r.push(t.channelId),e.includes("MessagePreviewSubChannel")&&n.push(t.subChannelId)}))}else if("message-preview-not-include-deleted"===t){const e=we(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{(null==t?void 0:t.isDeleted)&&(ke(e),e.includes("MessagePreviewChannel")&&r.push(t.channelId),e.includes("MessagePreviewSubChannel")&&n.push(t.subChannelId))})),0!==r.length&&await Cl(r),0!==n.length&&await Xl(n)}})(),0===ed.length){ed.push(vc((e=>{gc("globalBan"),ed.forEach((e=>e())),a()})),(e=>{const t=ve();return Xe(t,"client/onTokenTerminated","tokenTerminated",e)})((e=>{gc(),ed.forEach((e=>e())),a()})),fc((e=>{e.userId===i.userId&&(gc("userDeleted"),ed.forEach((e=>e())),a())})),(e=>{const t=ve();return Xe(t,"client/onTokenExpired","tokenExpired",e)})((e=>{ac(e),pc(),ed.forEach((e=>e()))})),dc(bc),uc(bc),Yl(),(()=>{const e=Yo();return e.established(),Bl((t=>{"established"===t?e.established():e.handleTokenExpired()})),()=>{e.destroy()}})(),(()=>{const e=nl();return e.startSyncReadReceipt(),Bl((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})());const e=await Xc();ed.push(e)}return!0},rd=()=>{let e,t=!1;const r=ve();r.log("initiating access token renewal");const n=async n=>{const{userId:s,displayName:i}=Ke(),a={userId:s,displayName:i,authToken:n,deviceId:await _o()};"tokenExpired"===r.sessionState?await td(a,r.sessionHandler):await oc(a),t=!0,e&&clearTimeout(e)};return{renew:()=>{t?console.log("'renew' method can be called only once per renewal instance"):n()},renewWithAuthToken:e=>{t?console.log("'renewWithAuthToken' method can be called only once per renewal instance"):n(e)},unableToRetrieveAuthToken:()=>{e=setTimeout((()=>{var e;null===(e=r.sessionHandler)||void 0===e||e.sessionWillRenewAccessToken(rd())}),y)}}},nd=3e5,sd=(e,t,r)=>{const n=setInterval((()=>{if((e=>Date.now()>Date.parse(e)-nd)(e))return Je("tokenExpired","tokenExpired"),void ze((()=>r.sessionWillRenewAccessToken(rd())));(e=>{const{expiresAt:t,issuedAt:r}=e,n=Date.parse(t),s=Date.parse(r),i=Date.now();return i>s+.8*(n-s-nd)&&i<n})({expiresAt:e,issuedAt:t})&&r.sessionWillRenewAccessToken(rd())}),y);return()=>clearInterval(n)},id=e=>{const t=ve();return Xe(t,"channelMarker/onChannelMarkerFetched","local.channelMarker.fetched",(t=>{t.userEntityMarkers.forEach((t=>{e(t)}))}))},ad=e=>{const t=ve();return Xe(t,"subChannelMarker/onSubChannelMarkerFetched","local.subChannelMarker.fetched",(t=>{e(t.userFeedMarkers[0])}))},od=e=>{const t=ve();return Xe(t,"subChannelMarker/onSubChannelMarkerUpdated","local.subChannelMarker.updated",(t=>{e(t.userFeedMarkers)}))},ld=e=>{const t=ve();return Xe(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers)}))},cd=e=>{const t=ve();return Xe(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers[0])}))},dd=e=>{const t=ve();return Xe(t,"messageMarker/onMessageMarkerFetched","local.messageMarker.fetched",(t=>{e(t.contentMarkers[0])}))},ud=e=>{const t=ve();return Xe(t,"messageMarker/onMessageMarked","marker.marked-message",(t=>{var r,n,s;Oo(t);const i=we(["message","collection"]),{contentMarkers:a,feedMarkers:o}=t;if(i&&(null==i?void 0:i.length)>0&&(null==o?void 0:o.length)>0){const e=i.filter((e=>{var t,r;return(null===(r=null===(t=e.data)||void 0===t?void 0:t.query)||void 0===r?void 0:r.subChannelId)===o[0].feedId}));if(e.length>0&&(null==a?void 0:a.length)>0){(null!==(s=null===(n=null===(r=e[0].data)||void 0===r?void 0:r.data)||void 0===n?void 0:n.map((e=>Ee(["message","get",e]))).map((({data:e})=>e)).filter(Boolean))&&void 0!==s?s:[]).forEach((e=>{var t,r;const n=["messageMarker","get",de("messageMarker")({creatorId:e.creatorPrivateId,feedId:e.subChannelId,contentId:e.messageId})],s=null===(t=Ee(n))||void 0===t?void 0:t.data;if(!s)return;const i=a[0].feedId===s.feedId,o=a[0].readCount>s.readCount,l=(null===(r=a[0])||void 0===r?void 0:r.deliveredCount)>s.deliveredCount;if(i){const e=Object.assign(Object.assign({},s),{readCount:o?a[0].readCount:s.readCount,deliveredCount:l?a[0].deliveredCount:s.deliveredCount});Se(n,e)}}))}}e(t.contentMarkers[0])}))};const hd=e=>{if("object"!=typeof(t=e)||null===t)return e;var t;const r=Object.entries(e).map((([t,r])=>{const n=Object.getOwnPropertyDescriptor(e,t);return"function"==typeof(null==n?void 0:n.get)?[t,n.get.call(e)]:[t,r]}));return Object.fromEntries(r)};function fd(e,t){if(null==e||null==t)return e===t;if(e.constructor!==t.constructor)return!1;if(e instanceof Function)return e===t;if(e instanceof RegExp)return e===t;if(e===t||e.valueOf()===t.valueOf())return!0;if(Array.isArray(e)&&e.length!==t.length)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(!fd(e[r],t[r]))return!1;return!0}if(e instanceof Date)return!1;if(!(e instanceof Object))return!1;if(!(t instanceof Object))return!1;const r=Object.keys(e);return Object.keys(t).every((e=>-1!==r.indexOf(e)))&&r.every((r=>fd(e[r],t[r])))}const pd=(e,t,r,n,s,i)=>{const{forceDispatch:a,callbackDataSelector:o,callbackFilter:l}=Object.assign({forceDispatch:!1,callbackDataSelector:e=>e},i),{cache:c}=ve();let d;c||console.log("For using Live Object feature you need to enable Cache!");let u=!1;const h=[],f=e=>{const{data:r}=e,n=Mo(e,["data"]);l&&!l(r,d)||t(Object.assign({data:o(r)},n)),d=hd(r)};return h.push(...s.map((t=>t((t=>((t,n=!1)=>{e===t[r]&&(d&&!n&&fd(d,t)||f({loading:!1,data:t,origin:"event"}))})(t,a)))))),(()=>{const t=ie(n,e,!0);oe(t,(({error:e,data:t,loading:r,origin:n,cachedAt:s})=>{-5===s?(f({data:t,origin:n,loading:!1,error:new pe(g,800800,"error")}),u=!0,h.forEach((e=>e()))):u||f({loading:r,data:t,origin:n,error:e}),e&&h.forEach((e=>e()))}))})(),()=>{h.forEach((e=>e()))}};var gd=Object.freeze({__proto__:null,getActiveClient:ve,getActiveUser:Ke,setActiveUser:Ge,createClient:(e,t=At.SG,{debugSession:r="amity",apiEndpoint:n}={})=>{var s,i;const a=(e=>{const t=`${null==e?void 0:e.trim()}`.length>0&&!kt,r=St(e),n=(e,...n)=>{t&&r(e,n)};return n.__instance__=r,n})(r);a("client/api/createClient",{apiKey:e.replace(/.{5}$/g,"xxxxx"),apiRegion:t});const o=null!==(s=null==n?void 0:n.http)&&void 0!==s?s:_t("http",t),l=null!==(i=null==n?void 0:n.mqtt)&&void 0!==i?i:_t("mqtt",t),c=hn(o),d=(e=>{const t=Aa(e,{autoConnect:!1,reconnectionDelay:2e3,transports:["websocket"]});return t.on("disconnect",(e=>{"io server disconnect"===e&&t.connect()})),t})(o),h=xo(l),f=Qe(),p={version:`${u}`,apiKey:e,log:a,cache:{data:{}},http:c,ws:d,mqtt:h,emitter:f,sessionState:"notLoggedIn",accessTokenExpiryWatcher:sd,sessionHandler:undefined,hasPermission:tc,validateUrls:rc,validateTexts:nc,getFeedSettings:sc,getSocialSettings:Zl,getMessagePreviewSetting:Jl,use:()=>be(p),isUnreadCountEnabled:!1,getMarkerSyncConsistentMode:Zc};try{const t=ve();if(t.apiKey===e)return t;be(p)}catch(e){be(p)}return p},login:td,logout:pc,isConnected:()=>{var e,t;const r=ve();return r.log("client/api/isConnected",r),!!(r.userId&&(null===(t=String(null===(e=r.http.defaults.headers.common)||void 0===e?void 0:e.Authorization))||void 0===t?void 0:t.length)&&r.ws.connected)},getFeedSettings:sc,renewal:rd,markerSync:Mc,enableUnreadCount:Fc,onConnectionError:yc,onClientDisconnected:e=>yc((({code:t})=>{800211===t&&e()})),onClientBanned:vc,onSessionStateChange:Bl,getTotalUnreadCount:e=>{const{_id:t}=Ke();if(!t)throw new fe("The _id has not been defined in ActiveUser",8e5,"error");return pd(t,e,"userId",(async()=>{const{data:e,cachedAt:t}=await kl();return{data:e,cachedAt:t}}),[cd],{callbackDataSelector:e=>{var t;return null!==(t=null==e?void 0:e.unreadCount)&&void 0!==t?t:0}})},getUserUnread:e=>{const{_id:t}=Ke();if(!t)throw new fe("The _id has not been defined in ActiveUser",8e5,"error");const{log:r,cache:n}=ve();n||console.log("For using Live Object feature you need to enable Cache!");r(`liveUserUnread(tmpid: ${Date.now()}) > listen`);const s=[];let i,a=!1;const o=t=>{const{data:r}=t,n=r?{unreadCount:r.unreadCount,isMentioned:r.isMentioned}:void 0;i=n?hd(n):n,e({data:n?Object.assign(Object.assign({},n),{hasMentioned:n.isMentioned}):n,loading:t.loading,error:t.error})};return s.push(ld((e=>(e=>{var r;const n=e.filter((e=>t===e.userId)),s=n.reduce(((e,t)=>null==e||new Date(t.lastSyncAt).getTime()>new Date(e.lastSyncAt).getTime()?t:e),null),a={unreadCount:null!==(r=null==s?void 0:s.unreadCount)&&void 0!==r?r:0,isMentioned:n.some((e=>!!e.isMentioned))};fd(i,a)||o({loading:!1,data:a})})(e)))),(()=>{const e=ie(kl);oe(e,(({error:e,data:t,loading:r,origin:n,cachedAt:i})=>{!function(e){return null!=e&&null!=e}(t)?o({loading:r,data:void 0,origin:n,error:e}):(-5===i?(o({data:t,origin:n,loading:!1,error:new pe(g,800800,"error")}),a=!0,s.forEach((e=>e()))):a||o({loading:r,data:t,origin:n,error:e}),e&&s.forEach((e=>e())))}))})(),()=>{s.forEach((e=>e()))}},getMarkerSyncEvents:()=>Hc,setMarkerSyncEvents:Vc,pushMarkerSyncEvent:zc,markerSyncTrigger:Wc,startMarkerSync:Xc,startUnreadSync:async()=>{await Gc(),zc("start syncing"),Fc(),$c=!1,Nc=!0,Yc()},stopUnreadSync:Jc,stopUnreadSyncing:()=>(console.warn("`stopUnreadSyncing` has been deprecated, please use `stopUnreadSync` instead"),Jc()),getMarkerSyncConsistentMode:Zc});const md=async e=>{const t=ve();let r={};if(e){const{token:t,limit:n}=e;r={limit:n,token:t}}t.log("user/queryBlockedUsers");const{data:n}=await t.http.get("/api/v4/me/user-blocks",{params:r}),{paging:s}=n,i=Mo(n,["paging"]),{users:a}=i,o=t.cache&&Date.now();if(t.cache){Oo(i,{cachedAt:o});Se(["blockedUsers","query",r],{users:a.map(de("user")),paging:s})}const{next:l,previous:c,total:d}=s,u=Z(l);return{data:a,prevPage:Z(c),nextPage:u,total:d,cachedAt:o}};md.locally=(e={})=>{var t,r,n;const s=ve();if(s.log("user/queryBlockedUsers.locally"),!s.cache)return;let i={};if(e){const{token:t,limit:r}=e;i={token:t,limit:r}}const a=["blockedUsers","query",i],{data:o,cachedAt:l}=null!==(t=Ee(a))&&void 0!==t?t:{},c=null!==(r=null==o?void 0:o.users.map((e=>Ee(["user","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[],d=Z(null==o?void 0:o.paging.next),u=Z(null==o?void 0:o.paging.previous);return c.length>0&&c.length===(null===(n=null==o?void 0:o.users)||void 0===n?void 0:n.length)?{data:c,nextPage:d,prevPage:u,total:null==o?void 0:o.paging.total,cachedAt:l}:void 0};const yd=(e,t,r)=>{const{log:n,cache:s}=ve();s||console.log(p);const i=Date.now();n(`getBlockedUsers(tmpid: ${i}) > listen`);const{limit:a}=e,o=null!=a?a:h,{policy:l=f}=null!=r?r:{},c=[],d=["blockedUsers","collection",{}],u=(e=!1)=>{var r,n;const s=null===(r=Ee(d))||void 0===r?void 0:r.data,i=null!==(n=null==s?void 0:s.data)&&void 0!==n?n:[];if(!e&&i.length>0&&!(null==s?void 0:s.params.page))return;const a=ie(md,{limit:o,token:X(e||null==s?void 0:s.params.page,"afterbeforeraw")});oe(a,(({data:e,loading:r,error:n,nextPage:s,total:a})=>{const o={loading:r,error:n,params:{page:s,total:a},data:i};e&&(o.data=[...new Set([...i,...e.map(de("user"))])]),Se(d,o),(e=>{var r,n;const s=null!==(r=e.data.map((e=>Ee(["user","get",e]))).filter(Boolean).map((({data:e})=>il.user(e))))&&void 0!==r?r:[];t({onNextPage:u,data:s,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading,error:e.error})})(o)}),ae(l,b))};return c.push((()=>{})),u(!0),()=>{n(`getCategories(tmpid: ${i}) > dispose`),c.forEach((e=>e())),ke(d)}},vd=(e,t)=>{const r=ve();return Xe(r,e,e,(e=>{var n,s;if(r.cache){Oo(e);[...null!==(n=we(["followers","query"]))&&void 0!==n?n:[],...null!==(s=we(["followings","query"]))&&void 0!==s?s:[]].filter((({key:t})=>t[2].userId===e.follows[0].from||t[2].userId===e.follows[0].to)).forEach((({key:e,data:t})=>Ce(e,t,{cachedAt:-1}))),t(e.follows[0])}else t(e.follows[0])}))},bd=e=>vd("follow.created",e),wd=e=>vd("follow.unfollowed",e),Ed=e=>vd("follow.followerDeleted",e),Sd=e=>vd("follow.requested",e),Td=e=>vd("follow.requestCanceled",e),Cd=e=>vd("follow.accepted",e),kd=e=>vd("follow.requestDeclined",e),Ad=async e=>{var t,r;const n=ve();n.log("follow/getFollowInfo",e);const{data:s}=await n.http.get(n.userId===e?"/api/v4/me/followInfo":`/api/v5/users/${e}/followInfo`),i=n.cache&&Date.now(),a="follows"in s?Object.assign(Object.assign({},s.followCounts[0]),{status:null===(r=null===(t=s.follows)||void 0===t?void 0:t[0])||void 0===r?void 0:r.status}):s.followCounts[0];return n.cache&&Se(["followInfo","get",e],a,{cachedAt:i}),{data:a,cachedAt:i}};Ad.locally=e=>{const t=ve();if(t.log("follow/getFollowInfo.locally",e),!t.cache)return;const r=Ee(["followInfo","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const Id=e=>{const t=async t=>{const[{data:r},{data:n}]=await Promise.all([Ad(t.from),Ad(t.to)]);e(r),e(n)},r=[vd("follow.created",t),vd("follow.requested",t),vd("follow.accepted",t),vd("follow.unfollowed",t),vd("follow.requestCanceled",t),vd("follow.requestDeclined",t),vd("follow.followerDeleted",t)];return()=>{r.forEach((e=>e()))}},_d=async(e,t)=>{const r=ve();r.log(`follow/queryF${e.substring(1)}`,t);const{userId:n,page:s}=t,i=Mo(t,["userId","page"]),{data:a}=await r.http.get(r.userId===n?`/api/v4/me/${e}`:`/api/v4/users/${n}/${e}`,{params:Object.assign(Object.assign({},i),{token:X(s,"afterbeforeraw")})}),{paging:o}=a,l=Mo(a,["paging"]),{follows:c}=l,d=r.cache&&Date.now();if(r.cache){Oo(l,{cachedAt:d});const t=["follow","query",Object.assign(Object.assign({},i),{userId:n,options:Object.assign({},s),type:e})];Se(t,{follows:c.map(de("follow")),paging:o})}const u=Z(o.next);return{data:c,cachedAt:d,prevPage:Z(o.previous),nextPage:u}};_d.locally=(e,t)=>{var r,n;const s=ve();if(s.log(`follow/queryF${e.substring(1)}.locally`,t),!s.cache)return;const{page:i}=t,a=Mo(t,["page"]),o=["follow","query",Object.assign(Object.assign({},a),{options:Object.assign({},i),type:e})],{data:l,cachedAt:c}=null!==(r=Ee(o))&&void 0!==r?r:{};if(!(null==l?void 0:l.follows.length))return;const d=l.follows.map((e=>Ee(["follow","get",e]))).filter(Boolean).map((({data:e})=>e)),u=Z(null==l?void 0:l.paging.previous),h=Z(null==l?void 0:l.paging.next);return d.length===(null===(n=null==l?void 0:l.follows)||void 0===n?void 0:n.length)?{data:d,cachedAt:c,prevPage:u,nextPage:h}:void 0};const Rd=async e=>_d("followers",e);Rd.locally=e=>_d.locally("followers",e);const Ld=async e=>_d("following",e);Ld.locally=e=>_d.locally("following",e);var Dd=Object.freeze({__proto__:null,blockUser:async e=>{const t=ve();t.log("user/blockUser",e);const{data:r}=await t.http.post(`/api/v4/me/user-blocks/${e}`),n=t.cache&&Date.now(),{follows:s,followCounts:i}=r,a={follows:s};return t.cache&&(Oo(a,{cachedAt:n}),Ce(["followInfo","get",e],i[0],{cachedAt:n})),Je("follow.unfollowed",a),r},unBlockUser:async e=>{const t=ve();t.log("user/unBlockUser",e);const{data:r}=await t.http.delete(`/api/v4/me/user-blocks/${e}`),n=t.cache&&Date.now(),{follows:s,followCounts:i}=r,a={follows:s};return t.cache&&(Oo(a,{cachedAt:n}),Ce(["followInfo","get",e],i[0],{cachedAt:n})),Je("follow.created",a),r},getBlockedUsers:(e,t,r)=>(console.log("Deprecation Notice: UserRepository.Relationship.getBlockedUsers will be deprecated on 9th June 2023, please use UserRepository.getBlockedUsers instead."),yd(e,t,r)),follow:async e=>{const t=ve();t.log("follow/follow",e);const{data:r}=await t.http.post(`/api/v4/me/following/${e}`),n=t.cache&&Date.now();return t.cache&&Oo(r,{cachedAt:n}),Je("accepted"===r.follows[0].status?"follow.created":"follow.requested",r),{data:r.follows[0],cachedAt:n}},unfollow:async e=>{const t=ve();t.log("follow/unfollow",e);const{data:r}=await t.http.delete(`/api/v4/me/following/${e}`);return t.cache&&Oo(r),Je("follow.unfollowed",r),!0},acceptFollower:async e=>{const t=ve();t.log("follow/acceptFollower",e);const{data:r}=await t.http.post(`/api/v4/me/followers/${e}`);return t.cache&&Oo(r),Je("follow.accepted",r),!0},acceptMyFollower:async e=>{const t=ve();t.log("follow/acceptMyFollower",e);const{data:r}=await t.http.post(`/api/v4/me/followers/${e}`);return t.cache&&Oo(r),Je("follow.accepted",r),!0},declineFollower:async e=>{const t=ve();t.log("follow/declineFollower",e);const{data:r}=await t.http.delete(`/api/v4/me/followers/${e}`);return t.cache&&Oo(r),Je("follow.requestDeclined",r),!0},declineMyFollower:async e=>{const t=ve();t.log("follow/declineMyFollower",e);const{data:r}=await t.http.delete(`/api/v4/me/followers/${e}`);return t.cache&&Oo(r),Je("follow.requestDeclined",r),!0},onUserFollowed:bd,onUserUnfollowed:wd,onFollowerDeleted:Ed,onFollowerRequested:Sd,onFollowRequestCanceled:Td,onFollowRequestAccepted:Cd,onFollowRequestDeclined:kd,onFollowInfoUpdated:Id,observeFollowInfo:(e,t,r="cache_then_server")=>{const{log:n}=ve(),s=Date.now();n(`observeFollowInfo(tmpid: ${s}) > listen`);const i=(e,r)=>{var n,s;if(t instanceof Function)return t(e);"onFetch"!==r&&(null===(n=t.onEvent)||void 0===n||n.call(t,r,e)),null===(s=t[r])||void 0===s||s.call(t,e)},a=[];return a.push(Id((t=>((t,r)=>{var n;(null===(n=t.data)||void 0===n?void 0:n.userId)===e&&i(t,r)})({data:t,loading:!1,origin:"event"},"onUpdate")))),oe(ie(Ad,e),(e=>(e.data||e.error)&&i(e,"onFetch")),ae(r)),()=>{n(`observeFollowInfo(tmpid: ${s}) > dispose`),a.forEach((e=>e()))}},observeFollowers:(e,t)=>{const{log:r}=ve(),n=Date.now();r(`observeFollowers(tmpid: ${n}) > listen`);const s=[],i=(e,r)=>{var n,s;if(t instanceof Function)return t(e);null===(n=t.onEvent)||void 0===n||n.call(t,r,e),null===(s=t[r])||void 0===s||s.call(t,e)};return s.push(Sd((e=>i(e,"onRequested"))),Cd((e=>i(e,"onAccepted"))),kd((e=>i(e,"onDeclined"))),Td((e=>i(e,"onCanceled"))),bd((e=>i(e,"onFollowed"))),wd((e=>i(e,"onUnfollowed"))),Ed((e=>i(e,"onDeleted")))),()=>{r(`observeFollowers(tmpid: ${n}) > dispose`),s.forEach((e=>e()))}},observeFollowings:(e,t)=>{const{log:r}=ve(),n=Date.now();r(`observeFollowings(tmpid: ${n}) > listen`);const s=[],i=(e,r)=>{var n,s;if(t instanceof Function)return t(e);null===(n=t.onEvent)||void 0===n||n.call(t,r,e),null===(s=t[r])||void 0===s||s.call(t,e)};return s.push(Sd((e=>i(e,"onRequested"))),Cd((e=>i(e,"onAccepted"))),kd((e=>i(e,"onDeclined"))),Td((e=>i(e,"onCanceled"))),bd((e=>i(e,"onFollowed"))),wd((e=>i(e,"onUnfollowed"))),Ed((e=>i(e,"onDeleted")))),()=>{r(`observeFollowings(tmpid: ${n}) > dispose`),s.forEach((e=>e()))}},getFollowers:(e,t,r)=>{const{log:n,cache:s}=ve();s||console.log("For using Live Collection feature you need to enable Cache!");const i=Date.now();n(`getFollowers(tmpid: ${i}) > listen`);const{limit:a}=e,o=Mo(e,["limit"]),l=null!=a?a:h,{policy:c=f}=null!=r?r:{},d=[],u=["follow","collection",{userId:e.userId,type:"follower"}],p=r=>{var n,s;let i=null!==(n=r.data.map((e=>Ee(["follow","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];e.status&&"all"!==e.status&&(i=Ae(i,"status",e.status)),t({onNextPage:m,data:i,hasNextPage:!!(null===(s=r.params)||void 0===s?void 0:s.page),loading:r.loading,error:r.error})},g=t=>r=>{var n;const s=null===(n=Ee(u))||void 0===n?void 0:n.data;e.userId===r.to&&s&&(["onDeclined","onCanceled","onUnfollowed","onDeleted"].includes(t)?s.data=s.data.filter((e=>e!==de("follow")(r))):["onRequested","onAccepted","onFollowed"].includes(t)&&(s.data=[...new Set([de("follow")(r),...s.data])]),Se(u,s),p(s))},m=(e=!1)=>{var t,r,n,s;const i=null===(t=Ee(u))||void 0===t?void 0:t.data,a=null!==(r=null==i?void 0:i.data)&&void 0!==r?r:[];if(!e&&a.length>0&&!(null===(n=null==i?void 0:i.params)||void 0===n?void 0:n.page))return;const d=ie(Rd,Object.assign(Object.assign({},o),{page:null!==(s=e||null==i?void 0:i.params.page)&&void 0!==s?s:{limit:l}}));oe(d,(({data:e,error:t,loading:r,nextPage:n})=>{const s={loading:r,error:t,params:{page:n},data:a};e&&(s.data=[...new Set([...a,...e.map(de("follow"))])]),Se(u,s),p(s)}),ae(c))};return d.push(Sd(g("onRequested")),Cd(g("onAccepted")),kd(g("onDeclined")),Td(g("onCanceled")),bd(g("onFollowed")),wd(g("onUnfollowed")),Ed(g("onDeleted"))),m(!0),()=>{n(`getFollowers(tmpid: ${i}) > dispose`),d.forEach((e=>e()))}},getFollowings:(e,t,r)=>{const{log:n,cache:s}=ve();s||console.log("For using Live Collection feature you need to enable Cache!");const i=Date.now();n(`getFollowings(tmpid: ${i}) > listen`);const{limit:a}=e,o=Mo(e,["limit"]),l=null!=a?a:h,{policy:c=f}=null!=r?r:{},d=[],u=["follow","collection",{userId:e.userId,type:"following"}],p=r=>{var n,s;let i=null!==(n=r.data.map((e=>Ee(["follow","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];e.status&&"all"!==e.status&&(i=Ae(i,"status",e.status)),t({onNextPage:m,data:i,hasNextPage:!!(null===(s=r.params)||void 0===s?void 0:s.page),loading:r.loading,error:r.error})},g=t=>r=>{var n;const s=null===(n=Ee(u))||void 0===n?void 0:n.data;e.userId===r.from&&s&&(["onDeclined","onCanceled","onUnfollowed","onDeleted"].includes(t)?s.data=s.data.filter((e=>e!==de("follow")(r))):["onRequested","onAccepted","onFollowed"].includes(t)&&(s.data=[...new Set([de("follow")(r),...s.data])]),Se(u,s),p(s))},m=(e=!1)=>{var t,r,n,s;const i=null===(t=Ee(u))||void 0===t?void 0:t.data,a=null!==(r=null==i?void 0:i.data)&&void 0!==r?r:[];if(!e&&a.length>0&&!(null===(n=null==i?void 0:i.params)||void 0===n?void 0:n.page))return;const d=ie(Ld,Object.assign(Object.assign({},o),{page:null!==(s=e||null==i?void 0:i.params.page)&&void 0!==s?s:{limit:l}}));oe(d,(({data:e,error:t,loading:r,nextPage:n})=>{const s={loading:r,error:t,params:{page:n},data:a};e&&(s.data=[...new Set([...a,...e.map(de("follow"))])]),Se(u,s),p(s)}),ae(c))};return d.push(Sd(g("onRequested")),Cd(g("onAccepted")),kd(g("onDeclined")),Td(g("onCanceled")),bd(g("onFollowed")),wd(g("onUnfollowed")),Ed(g("onDeleted"))),m(!0),()=>{n(`getFollowings(tmpid: ${i}) > dispose`),d.forEach((e=>e()))}},getFollowInfo:(e,t)=>pd(e,t,"userId",Ad,[Id],{forceDispatch:!0}),getMyFollowInfo:e=>{const{userId:t}=Ke();return pd(t,e,"userId",Ad,[Id],{forceDispatch:!0})}});const xd=async e=>{const t=ve();t.log("user/getUsers",e);const r=e.map((e=>encodeURIComponent(e))),{data:n}=await t.http.get("/api/v3/users/list",{params:{userIds:r}}),s=t.cache&&Date.now();return t.cache&&Oo(n,{cachedAt:s}),Je("user.fetched",n),{data:n.users.map((e=>il.user(e))),cachedAt:s}};xd.locally=e=>{var t;const r=ve();if(r.log("user/getUsers.locally",e),!r.cache)return;const n=e.map((e=>Ee(["user","get",e]))).filter(Boolean),s=n.map((({data:e})=>il.user(e))),i=null===(t=n.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==n?void 0:n.length)<e.length?void 0:{data:s,cachedAt:i.cachedAt}};const Od=e=>hc("user.updated",e),Pd=e=>hc("user.flagged",e),Md=e=>hc("user.unflagged",e),Fd=e=>hc("user.flagCleared",e),Ud=e=>hc("user.fetched",e),Nd=async e=>{const t=ve();let r;t.log("user/getUser",e),ql("user",e);try{r=(await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`)).data}catch(t){throw C(null==t?void 0:t.code)&&Po("user",e),t}const n=t.cache&&Date.now();t.cache&&Oo(r,{cachedAt:n});const{users:s}=r;return Je("user.fetched",r),{data:s.find((t=>t.userId===e)),cachedAt:n}};Nd.locally=e=>{const t=ve();if(t.log("user/getUser.locally",e),!t.cache)return;const r=Ee(["user","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const Bd=async(e={})=>{const t=ve();t.log("user/queryUsers",e);const{page:r,limit:n=10,displayName:s,filter:i="all",sortBy:a="displayName"}=e,o=Mo(e,["page","limit","displayName","filter","sortBy"]),{data:l}=await t.http.get("/api/v3/users",{params:Object.assign(Object.assign({},o),{keyword:s,filter:i,sortBy:a,options:r?{token:r}:{limit:n}})}),{paging:c}=l,d=Mo(l,["paging"]),{users:u}=d,h=t.cache&&Date.now();if(t.cache){Oo(d,{cachedAt:h});const t=["user","query",Object.assign(Object.assign({},e),{options:{limit:n,token:r}})];Se(t,{users:u.map(de("user")),paging:c})}return Je("user.fetched",l),{data:u,cachedAt:h,paging:c}};Bd.locally=(e={})=>{var t,r,n;const s=ve();if(s.log("user/queryUsers.locally",e),!s.cache)return;const{limit:i=10,page:a}=null!=e?e:{},o=["user","query",Object.assign(Object.assign({},e),{options:{limit:i,token:a}})],{data:l,cachedAt:c}=null!==(t=Ee(o))&&void 0!==t?t:{},d=null!==(r=null==l?void 0:l.users.map((e=>Ee(["user","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];return d.length>0&&d.length===(null===(n=null==l?void 0:l.users)||void 0===n?void 0:n.length)?{data:d,cachedAt:c,paging:null==l?void 0:l.paging}:void 0};const jd=(e,t)=>{let r=Ie(e,"displayName",t.displayName);switch(t.sortBy){case"firstCreated":r=r.sort(Fe);break;case"lastCreated":r=r.sort(Ne);break;default:r=r.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Pe)}return r},$d=(e,t,r)=>{const{log:n,cache:s}=ve();s||console.log(p);const i=Date.now();n(`liveUsers(tmpid: ${i}) > listen`);const{limit:a}=e,o=Mo(e,["limit"]),l=null!=a?a:h,{policy:c=f}=null!=r?r:{},d=[],u=["user","collection",Ao()],g=(r,n=!1)=>{var s,i;const a=null!==(s=r.data.map((e=>Ee(["user","get",e]))).filter(Boolean).map((({data:e})=>il.user(e))))&&void 0!==s?s:[];t({onNextPage:y,data:n?jd(a,e):a,hasNextPage:!!(null===(i=r.params)||void 0===i?void 0:i.page),loading:r.loading,error:r.error})},m=e=>e=>{var t;const r=null===(t=Ee(u))||void 0===t?void 0:t.data;r&&(r.data=[...new Set([e.userId,...r.data])],Se(u,r),g(r,!0))},y=(e=!1)=>{var t,r;const n=null===(t=Ee(u))||void 0===t?void 0:t.data,s=null!==(r=null==n?void 0:n.data)&&void 0!==r?r:[];if(!e&&s.length>0&&!(null==n?void 0:n.params.page))return;const i=e?{limit:l}:{page:null==n?void 0:n.params.page},a=ie(Bd,Object.assign(Object.assign({},o),i));oe(a,(({data:t,error:r,loading:n,paging:i})=>{const a={loading:n,error:r,params:{page:null==i?void 0:i.next},data:s};t&&(a.data=e?t.map(de("user")):[...new Set([...s,...t.map(de("user"))])]),Se(u,a),g(a)}),ae(c))};return d.push(Od(m()),fc(m()),Pd(m()),Md(m()),Fd(m())),y(!0),()=>{n(`liveUsers(tmpid: ${i}) > dispose`),d.forEach((e=>e()))}},qd=async e=>{const t=ve();let r;t.log("user/getUser",e),ql("user",e);try{r=(await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`)).data}catch(t){throw C(null==t?void 0:t.code)&&Po("user",e),t}const n=t.cache&&Date.now();t.cache&&Oo(r,{cachedAt:n});const{users:s}=r;return Je("user.fetched",r),{data:il.user(s.find((t=>t.userId===e))),cachedAt:n}};qd.locally=e=>{const t=ve();if(t.log("user/getUser.locally",e),!t.cache)return;const r=Ee(["user","get",e]);return r?{data:il.user(r.data),cachedAt:r.cachedAt}:void 0};const Kd=async({viewId:e,viewedType:t,limit:r,token:n})=>{const s=ve(),i={};n?i.token=n:i.limit=r;const a=`/api/v1/analytics/views/${"post"===t?"posts":"stories"}/${e}/users`,o=await s.http.get(a,{params:i});return Oo(o.data),o.data};var Gd=Object.freeze({__proto__:null,Relationship:Dd,getUserByIds:xd,updateUser:async(e,t)=>{const r=ve();r.log("user/updateUser",e,t);const{data:n}=await r.http.put("/api/v3/users/",Object.assign(Object.assign({userId:e},t),{createNewUserWhenNotFound:!1})),s=r.cache&&Date.now();r.cache&&Oo(n,{cachedAt:s});const{users:i}=n;return Je("user.updated",n),{data:i.find((t=>t.userId===e)),cachedAt:s}},flagUser:async e=>{const t=ve();t.log("user/flagUser",e);const{data:r}=await t.http.post(`api/v4/me/flags/${encodeURIComponent(e)}`);return t.cache&&Oo(r),Je("user.flagged",r),!!r},unflagUser:async e=>{const t=ve();t.log("user/unflag",e);const{data:r}=await t.http.delete(`/api/v4/me/flags/${encodeURIComponent(e)}`);return t.cache&&Oo(r),Je("user.unflagged",r),!!r},isUserFlaggedByMe:async e=>{const t=ve();t.log("user/isUserFlaggedByMe",e);const{data:{isFlagByMe:r}}=await t.http.get(`/api/v3/users/${e}/isFlagByMe`);return r},onUserUpdated:Od,onUserDeleted:fc,onUserFlagged:Pd,onUserUnflagged:Md,onUserFlagCleared:Fd,getUser:(e,t)=>pd(e,(e=>t(Object.assign(Object.assign({},e),{data:e.data?il.user(e.data):e.data}))),"userId",Nd,[Ud,Od,fc,Pd,Md,Fd]),getUsers:$d,observeUser:(e,t)=>{const{log:r}=ve(),n=Date.now();r(`observeUser(tmpid: ${n}) > listen`);const s=(r,n)=>{var s,i,a;if((null===(s=r.data)||void 0===s?void 0:s.userId)!==e)return;const o=Object.assign(Object.assign({},r),{data:il.user(r.data)});if(t instanceof Function)return t(o);"onFetch"!==n&&(null===(i=t.onEvent)||void 0===i||i.call(t,n,o)),null===(a=t[n])||void 0===a||a.call(t,o)},i=[];return i.push(Od((e=>s({data:e,loading:!1,origin:"event"},"onUpdate"))),fc((e=>s({data:e,loading:!1,origin:"event"},"onDelete"))),Pd((e=>s({data:e,loading:!1,origin:"event"},"onFlagged"))),Md((e=>s({data:e,loading:!1,origin:"event"},"onUnflagged"))),Fd((e=>s({data:e,loading:!1,origin:"event"},"onFlagCleared")))),oe(ie(qd,e),(e=>e.data&&s(e,"onFetch"))),()=>{r(`observeUser(tmpid: ${n}) > dispose`),i.forEach((e=>e()))}},getBlockedUsers:yd,searchUserByDisplayName:(e,t,r)=>$d(Object.assign(Object.assign({},e),{filter:"all"}),t,r),getViewedUsers:(e,t)=>{const{log:r,cache:n}=ve(),s=["postViewedUsers","collection",{postId:e.postId}];n||console.log(p);const i=Date.now();r(`getViewedUsers(tmpid: ${i}) > listen`);const{limit:a,postId:o}=e,l=(e=!1)=>{var r,n,i;const c=null===(r=Ee(s))||void 0===r?void 0:r.data,d=null!==(n=null==c?void 0:c.data)&&void 0!==n?n:[];if(!e&&d.length>0&&!(null==c?void 0:c.params.page))return;const u=ie(Kd,{viewId:o,viewedType:"post",limit:a||10,token:e||null===(i=null==c?void 0:c.params.page)||void 0===i?void 0:i.next});oe(u,(e=>{var r,n,i,a,o;let c=null!==(i=null===(n=null===(r=Ee(s))||void 0===r?void 0:r.data)||void 0===n?void 0:n.data)&&void 0!==i?i:[];(null===(a=e.data)||void 0===a?void 0:a.users)&&(c=[...new Set([...c,...e.data.users.map((({userId:e})=>e))])]);const d={loading:e.loading,params:{page:null===(o=e.data)||void 0===o?void 0:o.paging},data:c||[]};Se(s,d),(e=>{var r,n;let s=[];(null==e?void 0:e.data)&&(s=e.data.map((e=>Ee(["user","get",e]))).filter(Boolean).map((e=>null==e?void 0:e.data))||[]),t({onNextPage:l,data:s,hasNextPage:!!(null===(n=null===(r=e.params)||void 0===r?void 0:r.page)||void 0===n?void 0:n.next),loading:e.loading||!1})})(d)}),ae(f,b))};return l(!0),()=>{r(`getViewedUsers(tmpid: ${i}) > dispose`),ke(s)}},getReachedUsers:(e,t)=>{let r=(e=!1)=>{};const{log:n,cache:s}=ve(),i=["viewedUsers","collection",{viewId:e.viewId,viewedType:e.viewedType}];s||console.log(p);const a=Date.now();n(`getReachUsers(tmpid: ${a}) > listen`);const{limit:o,viewId:l,viewedType:c}=e;return r=(e=!1)=>{var n,s,a;const d=null===(n=Ee(i))||void 0===n?void 0:n.data,u=null!==(s=null==d?void 0:d.data)&&void 0!==s?s:[];if(!e&&u.length>0&&!(null==d?void 0:d.params.page))return;const h=ie(Kd,{viewId:l,viewedType:c,limit:o||10,token:e||null===(a=null==d?void 0:d.params.page)||void 0===a?void 0:a.next});oe(h,(e=>{var n,s,a,o,l;let c=null!==(a=null===(s=null===(n=Ee(i))||void 0===n?void 0:n.data)||void 0===s?void 0:s.data)&&void 0!==a?a:[];(null===(o=e.data)||void 0===o?void 0:o.users)&&(c=[...new Set([...c,...e.data.users.map((({userId:e})=>e))])]);const d={loading:e.loading,params:{page:null===(l=e.data)||void 0===l?void 0:l.paging},data:c||[]};Se(i,d),(e=>{var n,s;let i=[];(null==e?void 0:e.data)&&(i=e.data.map((e=>Ee(["user","get",e]))).filter(Boolean).map((e=>null==e?void 0:e.data))||[]),t({onNextPage:r,data:i,hasNextPage:!!(null===(s=null===(n=e.params)||void 0===n?void 0:n.page)||void 0===s?void 0:s.next),loading:e.loading||!1})})(d)}),ae(f,b))},r(!0),()=>{n(`getReachUsers(tmpid: ${a}) > dispose`),ke(i)}}});const Hd=async e=>{const t=ve();t.log("file/getFile",e);const{data:r}=await t.http.get(`/api/v3/files/${e}`),n=t.cache&&Date.now();return t.cache&&Oo({files:[r]},{cachedAt:n}),{data:r,cachedAt:n}};Hd.locally=e=>{const t=ve();if(t.log("file/getFile.locally",e),!t.cache)return;const r=Ee(["file","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const Vd=async(e,t,r)=>{const n=ve();if(n.log("file/uploadVideo",e),!e.getAll("files").length)throw new Error("The formData object must have a `files` key.");t&&e.append("feedType",t);const s="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await n.http.post("/api/v4/videos",e,{headers:s,onUploadProgress({loaded:e,total:t=100}){r&&r(Math.round(100*e/t))}}),a=n.cache&&Date.now();return n.cache&&Oo({files:i},{cachedAt:a}),{data:i,cachedAt:a}},zd=async(e,t)=>{const r=ve();if(r.log("file/uploadImage",e),!e.getAll("files").length)throw new Error("The formData object must have a `files` key.");const n="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:s}=await r.http.post("/api/v4/images",e,{headers:n,onUploadProgress({loaded:e,total:r=100}){t&&t(Math.round(100*e/r))}}),i=r.cache&&Date.now();return r.cache&&Oo({files:s},{cachedAt:i}),{data:s,cachedAt:i}};var Wd=Object.freeze({__proto__:null,getFile:Hd,uploadFile:async(e,t)=>{const r=ve();if(r.log("file/uploadFile",e),!e.getAll("files").length)throw new Error("The formData object must have a `files` key.");const n="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:s}=await r.http.post("/api/v4/files",e,{headers:n,onUploadProgress({loaded:e,total:r=100}){t&&t(Math.round(100*e/r))}}),i=r.cache&&Date.now();return r.cache&&Oo({files:s},{cachedAt:i}),{data:s,cachedAt:i}},deleteFile:async e=>{const t=ve();return t.log("file/deleteFile",e),await t.http.delete(`/api/v3/files/${e}`),ke(["file","get",e],!0),{success:!0}},fileUrlWithSize:(e,t)=>`${e}?size=${t}`,uploadVideo:Vd,uploadImage:zd,createImage:async(e,t)=>{const r=ve();if(r.log("file/createImage",e),!e.getAll("files").length)throw new Error("The formData object must have a `files` key.");const n="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:s}=await r.http.post("/api/v4/images",e,{headers:n,onUploadProgress({loaded:e,total:r=100}){t&&t(Math.round(100*e/r))}}),i=r.cache&&Date.now();return r.cache&&Oo({files:s},{cachedAt:i}),{data:s,cachedAt:i}},createFile:async(e,t)=>{const r=ve();if(r.log("file/createFile",e),!e.getAll("files").length)throw new Error("The formData object must have a `files` key.");const n="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:s}=await r.http.post("/api/v4/files",e,{headers:n,onUploadProgress({loaded:e,total:r=100}){t&&t(Math.round(100*e/r))}}),i=r.cache&&Date.now();return r.cache&&Oo({files:s},{cachedAt:i}),{data:s,cachedAt:i}},createVideo:async(e,t,r)=>{const n=ve();if(n.log("file/createVideo",e),!e.getAll("files").length)throw new Error("The formData object must have a `files` key.");t&&e.append("feedType",t);const s="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await n.http.post("/api/v4/videos",e,{headers:s,onUploadProgress({loaded:e,total:t=100}){r&&r(Math.round(100*e/t))}}),a=n.cache&&Date.now();return n.cache&&Oo({files:i},{cachedAt:a}),{data:i,cachedAt:a}},observeFile:(e,t)=>{const{log:r}=ve(),n=Date.now();r(`observeFile(tmpid: ${n}) > listen`);return oe(ie(Hd,e),(r=>r.data&&((r,n)=>{var s,i,a;if((null===(s=r.data)||void 0===s?void 0:s.fileId)===e){if(t instanceof Function)return t(r);"onFetch"!==n&&(null===(i=t.onEvent)||void 0===i||i.call(t,n,r)),null===(a=t[n])||void 0===a||a.call(t,r)}})(r,"onFetch"))),()=>{r(`observeFile(tmpid: ${n}) > dispose`)}}});const Yd=async e=>{const t=ve();t.log("role/queryRoles",e);const r=null!=e?e:{},{page:n,limit:s=10,queryToken:i,displayName:a,sortBy:o}=r,l=Mo(r,["page","limit","queryToken","displayName","sortBy"]),c=i?{token:i}:s?{limit:s}:n?{token:X(n,"skiplimit")}:void 0,{data:d}=await t.http.get("/api/v3/roles",{params:Object.assign(Object.assign({},l),{keyword:a,sortBy:o,options:c})}),{paging:u}=d,h=Mo(d,["paging"]),{roles:f}=h,p=t.cache&&Date.now();t.cache&&Oo(h,{cachedAt:p});const g=J(u.next);return{data:f,cachedAt:p,prevPage:J(u.previous),nextPage:g,paging:u}};Yd.locally=e=>{ve().log("role/queryRoles.locally",e)};const Qd=async e=>{const t=ve();t.log("role/getRole",e);const{data:r}=await t.http.get(`/api/v3/roles/${e}`),n=t.cache&&Date.now();return t.cache&&Oo({roles:r},{cachedAt:n}),{data:r.find((t=>t.roleId===e)),cachedAt:n}};Qd.locally=e=>{const t=ve();if(t.log("role/getRole.locally",e),!t.cache)return;const r=Ee(["role","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const Xd=(e,t)=>{"message"===e?Je("local.message.updated",{messages:[t]}):"post"===e?Je("post.updated",{posts:[t]}):"comment"===e?Je("comment.updated",{comments:[t]}):"story"===e&&Je("story.updated",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[t]})},Jd=async(e,t=!1)=>{const r=ve();let n;r.log("message/getMessage",e),t||console.log("getMessage will be deprecated on 15th November 2022, please use liveMessage instead."),ql("message",e);try{const{data:t}=await r.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);n=await Ol(t)}catch(t){throw C(null==t?void 0:t.code)&&Po("message",e),t}const s=r.cache&&Date.now();r.cache&&Oo(n,{cachedAt:s});const{messages:i}=n;return Je("local.message.fetched",{messages:i}),{data:i.find((t=>t.messageId===e)),cachedAt:s}};Jd.locally=e=>{const t=ve();if(t.log("message/getMessage.locally",e),!t.cache)return;const r=Ee(["message","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const Zd=async e=>{const t=ve();let r;t.log("post/getPost",e),ql("post",e);try{r=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw C(null==t?void 0:t.code)&&Po("post",e),t}const n=Uo(r,"communityUsers"),s=t.cache&&Date.now();t.cache&&Oo(n,{cachedAt:s});const{posts:i}=n,a=i.find((t=>t.postId===e));return{data:il.post(a),cachedAt:s}};Zd.locally=e=>{const t=ve();if(t.log("post/getPost.locally",e),!t.cache)return;const r=Ee(["post","get",e]);return r?{data:il.post(r.data),cachedAt:r.cachedAt}:void 0};const eu=async e=>{const t=ve();let r;t.log("comment/getComment",e),ql("comment",e);try{r=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw C(null==t?void 0:t.code)&&Po("comment",e),t}const n=t.cache&&Date.now();t.cache&&Oo(r,{cachedAt:n});const{comments:s}=r;return{data:il.comment(s.find((t=>t.commentId===e))),cachedAt:n}};eu.locally=e=>{const t=ve();if(t.log("comment/getComment.locally",e),!t.cache)return;const r=Ee(["comment","get",e]);return r?{data:il.comment(r.data),cachedAt:r.cachedAt}:void 0};const tu=(e,t)=>{var r,n;let s,i;if("post"===t)i="post",s=e.posts[0].postId;else if("comment"===t)i="comment",s=e.comments[0].commentId;else{if("story"!==t)throw new Error("Unknown event type");i="story",s=e.stories[0].referenceId}return(null===(n=null===(r=Ee([i,"get",s]))||void 0===r?void 0:r.data)||void 0===n?void 0:n.myReactions)||[]},ru=(e,t,r)=>{const[n]=e[t];return Object.assign(Object.assign({},e),{[t]:[Object.assign(Object.assign({},n),{myReactions:r})]})},nu=(e,t,r,n=[])=>{const s=e.split(".")[1];let i=n;if(ve().userId===t)if(["addReaction","reactionAdded"].includes(s))i.includes(r)||i.push(r);else{if(!["removeReaction","reactionRemoved"].includes(s))throw new Error(`Unknown event type: ${s}`);i=i.filter((e=>e!==r))}return i},su=(e,t)=>{const r=e.split(".")[0],n=tu(t,r),s=nu(e,t.reactor.userId,t.reactor.reactionName,n);return ru(t,`${r}s`,s)},iu=(e,t)=>{var r,n;const s=e.split(".")[0];let i=tu(t,s);return(null==t?void 0:t.reactions)&&t.reactions.length>0&&(i=nu(e,null===(r=t.reactions[0])||void 0===r?void 0:r.userId,null===(n=t.reactions[0])||void 0===n?void 0:n.reactionName,i)),ru(t,"stories",i)},au=async(e,t,r)=>{const n=ve();if(n.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:r}),await n.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:r,referenceVersion:"message"===e?5:void 0}),n.cache){const r=Ee([e,"get",t]);(null==r?void 0:r.data)&&Se([e,"get",t],r.data,{cachedAt:Date.now()})}return!0};au.optimistically=(e,t,r)=>{var n,s,i,a,o;const l=ve();if(l.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:r}),!l.cache)return;const c=Ee([e,"get",t]);if(!(null==c?void 0:c.data)||(null===(n=c.data.myReactions)||void 0===n?void 0:n.includes(r)))return;const d=Object.assign(Object.assign({},c.data),{reactionsCount:c.data.reactionsCount+1,myReactions:[...null!==(s=c.data.myReactions)&&void 0!==s?s:[],r],reactions:Object.assign(Object.assign({},c.data.reactions),{[r]:(null!==(i=c.data.reactions[r])&&void 0!==i?i:0)+1})});return Ce([e,"get",t],d,{cachedAt:-5}),Xd(e,d),null!==(o=null===(a=null==d?void 0:d.myReactions)||void 0===a?void 0:a.includes(r))&&void 0!==o&&o};const ou=async(e,t,r)=>{const n=ve();if(n.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:r}),await n.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:r,referenceVersion:"message"===e?5:void 0}}),n.cache){const r=Ee([e,"get",t]);(null==r?void 0:r.data)&&Se([e,"get",t],r.data,{cachedAt:Date.now()})}return!0};ou.optimistically=(e,t,r)=>{var n,s,i,a,o;const l=ve();if(l.log("reaction/removeReaction.optimistically",{referenceId:t,referenceType:e,reactionName:r}),!l.cache)return;const c=Ee([e,"get",t]);if(!(null==c?void 0:c.data)||!(null===(n=c.data.myReactions)||void 0===n?void 0:n.includes(r)))return;const d=Object.assign(Object.assign({},c.data),{reactionsCount:Math.max(0,c.data.reactionsCount-1),myReactions:(null!==(s=c.data.myReactions)&&void 0!==s?s:[]).filter((e=>e!==r)),reactions:Object.assign(Object.assign({},c.data.reactions),{[r]:Math.max(0,(null!==(i=c.data.reactions[r])&&void 0!==i?i:0)-1)})});return Ce([e,"get",t],d,{cachedAt:-5}),Xd(e,d),null!==(o=!(null===(a=null==d?void 0:d.myReactions)||void 0===a?void 0:a.includes(r)))&&void 0!==o&&o};const lu=(e,t)=>{const r=ve();return Xe(r,e,e,(n=>{var s;if(r.cache){const{communities:i}=n,a=Mo(n,["communities"]),o=Uo(a,"communityUsers");if(Oo(o),(null==i?void 0:i[0])&&!["post.updated"].includes(e)&&Je("community.updated",{communities:i,categories:[],communityUsers:o.communityUsers,feeds:[],files:[],users:[]}),"post.deleted"===e){const{postId:e,postedUserId:s}=n.posts[0];try{ql("post",e)}catch(e){return}return s!==r.userId&&Po("post",e),t(n.posts[0])}const l=Ee(["post","get",n.posts[0].postId]);if(["post.created","post.approved","post.declined"].includes(e)){let t=null===(s=we(["post","query"]))||void 0===s?void 0:s.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.targetId)===l.data.targetId}));"post.declined"===e&&(t=null==t?void 0:t.filter((({key:e})=>{var t;return"reviewing"===(null===(t=e[2])||void 0===t?void 0:t.feedType)}))),null==t||t.map((({key:e,data:t})=>Ce(e,t,{cachedAt:-1})))}t(l.data)}else t(n.posts[0])}))},cu=e=>lu("post.created",e),du=e=>lu("post.updated",e),uu=e=>lu("post.deleted",e),hu=e=>lu("post.approved",e),fu=e=>lu("post.declined",e),pu=e=>lu("post.flagged",e),gu=e=>lu("post.unflagged",e),mu=e=>{const t=ve();return Xe(t,"post.addReaction","post.addReaction",(r=>{if(t.cache){const t=Mo(su("post.addReaction",r),["reactor"]);Oo(t);const n=Ee(["post","get",r.posts[0].postId]);e(n.data)}else e(r.posts[0])}))},yu=e=>{const t=ve();return Xe(t,"post.removeReaction","post.removeReaction",(r=>{if(t.cache){const t=Mo(su("post.removeReaction",r),["reactor"]);Oo(t);const n=Ee(["post","get",r.posts[0].postId]);e(n.data)}else e(r.posts[0])}))},vu=(e,t)=>{const r=ve();return Xe(r,e,e,(n=>{var s;if(r.cache){Oo(n);const{comments:r}=n;if(r.length>0){const n=Ee(["comment","get",r[0].commentId]);if(["comment.created"].includes(e)){if(r[0].parentId){const e=Ee(["comment","get",r[0].parentId]);(null==e?void 0:e.data)&&Se(["comment","get",r[0].parentId],Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,r[0].commentId])]}))}const e=null===(s=we(["comment","query"]))||void 0===s?void 0:s.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===n.data.referenceId}));null==e||e.map((({key:e,data:t})=>Ce(e,t,{cachedAt:-1})))}t(il.comment(n.data))}}else t(il.comment(n.comments[0]))}))},bu=e=>vu("comment.created",e),wu=e=>vu("comment.updated",e),Eu=e=>vu("comment.deleted",e),Su=e=>vu("comment.flagged",e),Tu=e=>vu("comment.unflagged",e),Cu=e=>{const t=ve();return Xe(t,"comment.addReaction","comment.addReaction",(r=>{if(t.cache){const t=Mo(su("comment.addReaction",r),["reactor"]);Oo(t);const n=Ee(["comment","get",r.comments[0].commentId]);e(il.comment(n.data))}else e(il.comment(r.comments[0]))}))},ku=e=>{const t=ve();return Xe(t,"comment.removeReaction","comment.removeReaction",(r=>{if(t.cache){const t=Mo(su("comment.removeReaction",r),["reactor"]);Oo(t);const n=Ee(["comment","get",r.comments[0].commentId]);e(il.comment(n.data))}else e(il.comment(r.comments[0]))}))},Au=(e,t,r)=>{const n=ve(),s=(n,s,i)=>{n===e&&s===t&&r(i)};if("message"===e){return Xe(n,"reaction/onReactorAdded","message.updated",(async e=>{const t=await Ol(e);t.reactions[0]&&(Oo(t),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return Xe(n,"post.addReaction","post.addReaction",(e=>{const{reactor:t}=e,r=Mo(e,["reactor"]);Oo(r),Oo({reactions:[t]}),s("post",e.posts[0].postId,t)}))}if("story"===e){return Xe(n,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,r=Mo(e,["reactions"]);Oo(r),Oo({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}))}return Xe(n,"comment.addReaction","comment.addReaction",(e=>{const{reactor:t}=e,r=Mo(e,["reactor"]);Oo(r),Oo({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))},Iu=(e,t,r)=>{const n=ve(),s=(n,s,i)=>{n===e&&s===t&&r(i)};if("message"===e){return Xe(n,"reaction/onReactorRemoved","message.updated",(async e=>{const t=await Ol(e);t.reactions[0]&&(Oo(t),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return Xe(n,"post.removeReaction","post.removeReaction",(e=>{const{reactor:t}=e,r=Mo(e,["reactor"]);Oo(r),Oo({reactions:[t]}),s("post",e.posts[0].postId,t)}))}if("story"===e){return Xe(n,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,r=Mo(e,["reactions"]);Oo(r),Oo({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}))}return Xe(n,"comment.removeReaction","comment.removeReaction",(e=>{const{reactor:t}=e,r=Mo(e,["reactor"]);Oo(r),Oo({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))},_u=async e=>{ve().log("reaction/queryReactor",e);const t=await(async e=>{const t=ve();t.log("reaction/queryReactions",e);const r=null!=e?e:{},{page:n={limit:10}}=r,s=Mo(r,["page"]),{data:i}=await t.http.get("/api/v3/reactions",{params:Object.assign(Object.assign({},s),{referenceVersion:5,options:{token:X(n,"afterbeforeraw")}})}),{paging:a}=i,o=Mo(i,["paging"]),{reactions:l}=o;Oo(Object.assign(Object.assign({},o),{reactions:l})),Oo(Object.assign(Object.assign({},o),{reactors:l[0].reactors}));const c=Z(a.next);return{data:l,prevPage:Z(a.previous),nextPage:c}})(e),{data:r}=t,n=Mo(t,["data"]);return Object.assign(Object.assign({},n),{data:r[0].reactors})};var Ru=Object.freeze({__proto__:null,addReaction:au,removeReaction:ou,onReactionAdded:(e,t,r)=>{const n=n=>{de(e)(n)===t&&r(n)};if("message"===e){const e=ve(),t=async e=>{var t;const r=await Ol(e),s=Ee(["message","get",r.messages[0].messageId]),i=(null===(t=null==s?void 0:s.data)||void 0===t?void 0:t.reactionsCount)!==r.messages[0].reactionsCount;Oo(r),i&&n(r.messages[0])};return Xe(e,"reaction/onReactionAdded","message.updated",t)}return"post"===e?mu(n):Cu(n)},onReactionRemoved:(e,t,r)=>{const n=n=>{de(e)(n)===t&&r(n)};if("message"===e){const e=ve(),t=async e=>{var t;const r=await Ol(e),s=Ee(["message","get",r.messages[0].messageId]),i=(null===(t=null==s?void 0:s.data)||void 0===t?void 0:t.reactionsCount)!==r.messages[0].reactionsCount;Oo(r),i&&n(r.messages[0])};return Xe(e,"reaction/onReactionRemoved","message.updated",t)}return"post"===e?yu(n):ku(n)},onReactorAdded:Au,onReactorRemoved:Iu,getReactions:(e,t,r)=>{const{log:n,cache:s}=ve();s||console.log("For using Live Collection feature you need to enable Cache!");const i=Date.now();n(`liveReactions(tmpid: ${i}) > listen`);const{limit:a}=e,o=Mo(e,["limit"]),l=null!=a?a:h,{policy:c=f}=null!=r?r:{},d=[],u=["reaction","collection",{referenceId:e.referenceId,referenceType:e.referenceType}],p=e=>{var r,n;const s=null!==(r=e.data.map((e=>Ee(["reactor","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];t({onNextPage:m,data:s,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading,error:e.error})},g=e=>t=>{var r;const n=null===(r=Ee(u))||void 0===r?void 0:r.data;n&&("onAdded"===e?n.data=[...new Set([t.reactionId,...n.data])]:"onRemoved"===e&&(n.data=n.data.filter((e=>e!==t.reactionId))),Se(u,n),p(n))},m=(e=!1)=>{var t,r,n,s;const i=null===(t=Ee(u))||void 0===t?void 0:t.data,a=null!==(r=null==i?void 0:i.data)&&void 0!==r?r:[];if(!e&&a.length>0&&!(null===(n=null==i?void 0:i.params)||void 0===n?void 0:n.page))return;const d=ie(_u,Object.assign(Object.assign({},o),{page:null!==(s=e||null==i?void 0:i.params.page)&&void 0!==s?s:{limit:l}}));oe(d,(({data:e,error:t,loading:r,nextPage:n})=>{const s={loading:r,error:t,params:{page:n},data:a};e&&(s.data=[...new Set([...a,...e.map(de("reactor"))])]),Se(u,s),p(s)}),ae(c))};return d.push(Au(o.referenceType,o.referenceId,g("onAdded")),Iu(o.referenceType,o.referenceId,g("onRemoved"))),m(!0),()=>{n(`liveReactions(tmpid: ${i}) > dispose`),d.forEach((e=>e()))}}}),Lu={post:{domainName:"posts",eventName:"v3/post.isflagbyme",primaryKey:"postId"},comment:{domainName:"comments",eventName:"v3/comment.isflagbyme",primaryKey:"commentId"},message:{domainName:"messages",eventName:"v3/message.isFlaggedByMe",primaryKey:"messageId"},user:{domainName:"users",eventName:"user.isFlagByMe",primaryKey:"userId"}};const Du=async e=>{const t=ve();let r;t.log("channel/getChannel",e),ql("channel",e);try{const{data:n}=await t.http.get(`/api/v3/channels/${encodeURIComponent(e)}`);r=await Tl(n)}catch(t){throw C(null==t?void 0:t.code)&&Po("channel",e),t}const n=t.cache&&Date.now();t.cache&&Oo(r,{cachedAt:n});const{channels:s}=r;return{data:s.find((t=>t.channelId===e)),cachedAt:n}};Du.locally=e=>{const t=ve();if(t.log("channel/getChannel.locally",e),!t.cache)return;const r=Ee(["channel","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const xu=(e,t,r)=>n=>e((e=>{var s;if(!e)return e;const i=[r,"get",`${e[t]}`],a=null===(s=Ee(i))||void 0===s?void 0:s.data;return a?n(a):void 0})),Ou=e=>{const t=ve(),r=[Xe(t,"onMessageUpdated","message.updated",(async t=>{const r=await Ol(t);Oo(r),e(r.messages[0])})),Xe(t,"onMessageUpdated","local.message.updated",(t=>e(t.messages[0])))];return()=>{r.forEach((e=>e()))}},Pu=e=>{const t=ve(),r=[Xe(t,"message/onMessageDeleted","message.deleted",(async t=>{const r=await Ol(t);Oo(r),e(r.messages[0])})),Xe(t,"message/onMessageDeleted","local.message.deleted",(t=>e(t.messages[0])))];return()=>{r.forEach((e=>e()))}},Mu=e=>{const t=ve(),r=[Xe(t,"onSubChannelUpdated","message-feed.updated",(async t=>{const r=await Nl(t);Oo(r),e(r.messageFeeds[0])})),Xe(t,"onSubChannelUpdated","local.message-feed.updated",(t=>e(t.messageFeeds[0])))];return()=>{r.forEach((e=>e()))}};function Fu(e,t){Se(["channel","get",e.channelId],Object.assign(ul(e),t))}const Uu=e=>{const t=ve();return Xe(t,"channelMarker/onChannelMarkerUpdated","local.channelMarker.updated",(t=>{e(t.userEntityMarkers[0])}))},Nu=async(e,t=!1)=>{const r=ve(),n=await Kl(e);await r.http.delete(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{params:{permanent:t}});const s=Object.assign(Object.assign({},n.data),{isDeleted:!0,updatedAt:he(n.data.updatedAt)});return t?setTimeout((()=>{Po("subChannel",e)}),0):Ce(["subChannel","get",e],s),Je("local.message-feed.deleted",{messageFeeds:[s]}),s},Bu=e=>Xe(ve(),"onSubChannelFetched","local.message-feed.fetched",(t=>e(t.messageFeeds[0]))),ju=async e=>{const t=ve();t.log("message/getMessages",e);const{data:r}=await t.http.get("/api/v5/messages/list",{params:{messageIds:e.map(encodeURIComponent)}}),n=await Ol(r),s=t.cache&&Date.now();t.cache&&Oo(n,{cachedAt:s});const{messages:i}=n;return Je("local.message.fetched",{messages:i}),{data:i.map((e=>il.message(e))),cachedAt:s}};ju.locally=e=>{var t;const r=ve();if(r.log("message/getMessages.locally",e),!r.cache)return;const n=e.map((e=>Ee(["message","get",e]))).filter(Boolean),s=n.map((({data:e})=>e)),i=null===(t=n.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==n?void 0:n.length)<e.length?void 0:{data:s,cachedAt:i.cachedAt}};const $u=()=>`LOCAL_${Ao()}`;let qu;const Ku=async e=>{const t=ve();t.log("message/createMessage",e);const r=e.referenceId||qu||$u();qu=void 0;const{data:n}=await t.http.post("/api/v5/messages",Object.assign(Object.assign({},Pl(e)),{referenceId:r})),s=await Ol(n),{messages:i}=s,a=t.cache&&Date.now();return t.cache&&(ke(["message","get",r]),Oo(s,{cachedAt:a})),Je("local.message.created",{messages:i}),{data:il.message(i[0]),cachedAt:a}};Ku.optimistically=e=>{var t,r,{referenceId:n}=e,s=Mo(e,["referenceId"]);const i=ve();if(!i.cache)return;qu=n||$u();const a=Object.assign({messageId:qu,uniqueId:qu},s);i.log("message/createMessage.optimistically",a);const o=Ee(["subChannel","get",s.subChannelId]);if(o&&(Ce(["subChannel","get",s.subChannelId],Object.assign(Object.assign({},o.data),{messageCount:o.data.messageCount+1})),o.data.channelId===o.data.subChannelId)){const e=Ee(["channel","get",o.data.channelId]);(null==e?void 0:e.data)&&Ce(["channel","get",o.data.channelId],Object.assign(Object.assign({},e.data),{messageCount:(null!==(t=e.data.messageCount)&&void 0!==t?t:0)+1}))}const l=(new Date).toISOString(),c=Object.assign({creatorId:i.userId,creatorPrivateId:Ke()._id,channelSegment:(null!==(r=null==o?void 0:o.data.messageCount)&&void 0!==r?r:0)+1,childrenNumber:0,createdAt:l,updatedAt:l},a);return Se(["message","get",c.messageId],c,{cachedAt:-5}),Je("local.message.created",{messages:[c]}),{cachedAt:-5,data:il.message(c)}};const Gu=async(e,t)=>{const r=ve();r.log("message/updateMessage",t),console.warn("MessageRepository.updateMessage will be replaced with MessageRepository.editMessage");const{data:n}=await r.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,Pl(t)),s=await Ol(n),i=r.cache&&Date.now();r.cache&&Oo(s,{cachedAt:i});const{messages:a}=s;return Je("local.message.updated",{messages:a}),{data:il.message(a.find((t=>t.messageId===e))),cachedAt:i}};Gu.optimistically=(e,t)=>{const r=ve();if(r.log("message/updateMessage.optimistically",t),!r.cache)return;const n=Ee(["message","get",e]);if(!n)return;const s=Object.assign(Object.assign(Object.assign({},n.data),t),{updatedAt:(new Date).toISOString()});return Ce(["message","get",e],s,{cachedAt:-1}),Je("local.message.updated",{messages:[s]}),{data:il.message(s),cachedAt:-1}};const Hu=async(e,t)=>{const r=ve();r.log("message/editMessage",t);const{data:n}=await r.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,Pl(t)),s=await Ol(n),i=r.cache&&Date.now();r.cache&&Oo(s,{cachedAt:i});const{messages:a}=s;return Je("local.message.updated",{messages:a}),{data:il.message(a.find((t=>t.messageId===e))),cachedAt:i}};Hu.optimistically=(e,t)=>{const r=ve();if(r.log("message/editMessage.optimistically",t),!r.cache)return;const n=Ee(["message","get",e]);if(!n)return;const s=Object.assign(Object.assign(Object.assign({},n.data),t),{updatedAt:(new Date).toISOString()});return Ce(["message","get",e],s,{cachedAt:-1}),Je("local.message.updated",{messages:[s]}),{data:il.message(s),cachedAt:-1}};const Vu=async e=>{const t=ve();t.log("message/deleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const r=await Jd(e);return Je("local.message.deleted",{messages:[r.data]}),il.message(r.data)};Vu.optimistically=e=>{ve().log("message/deleteMessage.optimistically",e);const t=Ee(["message","get",e]);if(!t)return;const r=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return Ce(["message","get",e],r,{cachedAt:-1}),Je("local.message.deleted",{messages:[r]}),{data:il.message(r),cachedAt:-1}};const zu=async e=>{const t=ve();t.log("message/softDeleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const r=await Jd(e);return Je("local.message.deleted",{messages:[r.data]}),il.message(r.data)};zu.optimistically=e=>{ve().log("message/softDeleteMessage.optimistically",e);const t=Ee(["message","get",e]);if(!t)return;const r=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return Ce(["message","get",e],r,{cachedAt:-1}),Je("local.message.deleted",{messages:[r]}),{data:il.message(r),cachedAt:-1}};const Wu=async e=>{const t=ve();t.log("user/getReadUsers",e);const{page:r,messageId:n}=e,s=Mo(e,["page","messageId"]),{data:i}=await t.http.get(`/api/v1/markers/messages/${n}/read-users`,{params:Object.assign(Object.assign({},s),{options:{token:X(r,"afterbeforeraw")}})}),{paging:a,publicUserIds:o,userFeedMarkers:l}=i,c=Mo(i,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Oo(Object.assign(Object.assign({},c),{userFeedMarkers:jo(l)}),{cachedAt:d});const e=["read-user","query",Object.assign(Object.assign({messageId:n},s),{options:Object.assign({},r)})];Se(e,{users:o,paging:a})}let u=[];o.length>0&&({data:u}=await xd(o));return{data:u,cachedAt:d,prevPage:J(a.previous),nextPage:J(a.next)}};Wu.locally=e=>{var t;const r=ve();if(r.log("user/getReadUsers.locally",e),!r.cache)return;const{page:n}=e,s=Mo(e,["page"]),i=["read-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},n)})],{data:a,cachedAt:o}=null!==(t=Ee(i))&&void 0!==t?t:{},l=null==a?void 0:a.users.map((e=>{var t;return null===(t=Ee(["user","get",e]))||void 0===t?void 0:t.data}));if(!l||l.some((e=>!e)))return;return{data:l,cachedAt:o,prevPage:J(null==a?void 0:a.paging.previous),nextPage:J(null==a?void 0:a.paging.next)}};const Yu=async e=>{const t=ve();t.log("user/getDeliveredUsers",e);const{page:r,messageId:n}=e,s=Mo(e,["page","messageId"]),{data:i}=await t.http.get(`/api/v1/markers/messages/${n}/delivered-users`,{params:Object.assign(Object.assign({},s),{options:{token:X(r,"afterbeforeraw")}})}),{paging:a,publicUserIds:o,userFeedMarkers:l}=i,c=Mo(i,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Oo(Object.assign(Object.assign({},c),{userFeedMarkers:jo(l)}),{cachedAt:d});const e=["delivered-user","query",Object.assign(Object.assign({messageId:n},s),{options:Object.assign({},r)})];Se(e,{users:o,paging:a})}let u=[];o.length>0&&({data:u}=await xd(o));return{data:u,cachedAt:d,prevPage:J(a.previous),nextPage:J(a.next)}};Yu.locally=e=>{var t;const r=ve();if(r.log("user/getDeliveredUsers.locally",e),!r.cache)return;const{page:n}=e,s=Mo(e,["page"]),i=["delivered-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},n)})],{data:a,cachedAt:o}=null!==(t=Ee(i))&&void 0!==t?t:{},l=null==a?void 0:a.users.map((e=>{var t;return null===(t=Ee(["user","get",e]))||void 0===t?void 0:t.data}));if(!l||l.some((e=>!e)))return;return{data:l,cachedAt:o,prevPage:J(null==a?void 0:a.paging.previous),nextPage:J(null==a?void 0:a.paging.next)}};const Qu=e=>{const t=ve();return Xe(t,"onMessageFlagged","message.flagged",(async t=>{const r=await Ol(t);Oo(r),e(r.messages[0])}))},Xu=e=>{const t=ve();return Xe(t,"onMessageUnflagged","message.unflagged",(async t=>{const r=await Ol(t);Oo(r),e(r.messages[0])}))},Ju=e=>{const t=ve();return Xe(t,"onMessageFlagCleared","message.flagCleared",(async t=>{const r=await Ol(t);Oo(r),e(r.messages[0])}))},Zu=e=>{const t=ve();return Xe(t,"onMessageReactionAdded","message.reactionAdded",(async t=>{const r=await Ol(t,"message.reactionAdded");Oo(r),e(r.messages[0])}))},eh=e=>{const t=ve();return Xe(t,"onMessageReactionRemoved","message.reactionRemoved",(async t=>{const r=await Ol(t,"message.reactionRemoved");Oo(r),e(r.messages[0])}))},th=e=>{const t=ve();return Xe(t,"message/onMessageFetched","local.message.fetched",(t=>{Oo(t),e(t.messages[0])}))};var rh={exports:{}};!function(e,t){e.exports=function e(t,r,n){function s(a,o){if(!r[a]){if(!t[a]){if(!o&&Ia)return Ia(a);if(i)return i(a,!0);throw new Error("Cannot find module '"+a+"'")}o=r[a]={exports:{}},t[a][0].call(o.exports,(function(e){return s(t[a][1][e]||e)}),o,o.exports,e,t,r,n)}return r[a].exports}for(var i=Ia,a=0;a<n.length;a++)s(n[a]);return s}({1:[function(e,t,r){(function(n,s,i,a,o,l,c,d,u){var h=e("crypto");function f(e,t){var r;return void 0===(r="passthrough"!==(t=m(e,t)).algorithm?h.createHash(t.algorithm):new b).write&&(r.write=r.update,r.end=r.update),v(t,r).dispatch(e),r.update||r.end(""),r.digest?r.digest("buffer"===t.encoding?void 0:t.encoding):(e=r.read(),"buffer"!==t.encoding?e.toString(t.encoding):e)}(r=t.exports=f).sha1=function(e){return f(e)},r.keys=function(e){return f(e,{excludeValues:!0,algorithm:"sha1",encoding:"hex"})},r.MD5=function(e){return f(e,{algorithm:"md5",encoding:"hex"})},r.keysMD5=function(e){return f(e,{algorithm:"md5",encoding:"hex",excludeValues:!0})};var p=h.getHashes?h.getHashes().slice():["sha1","md5"],g=(p.push("passthrough"),["buffer","hex","binary","base64"]);function m(e,t){var r={};if(r.algorithm=(t=t||{}).algorithm||"sha1",r.encoding=t.encoding||"hex",r.excludeValues=!!t.excludeValues,r.algorithm=r.algorithm.toLowerCase(),r.encoding=r.encoding.toLowerCase(),r.ignoreUnknown=!0===t.ignoreUnknown,r.respectType=!1!==t.respectType,r.respectFunctionNames=!1!==t.respectFunctionNames,r.respectFunctionProperties=!1!==t.respectFunctionProperties,r.unorderedArrays=!0===t.unorderedArrays,r.unorderedSets=!1!==t.unorderedSets,r.unorderedObjects=!1!==t.unorderedObjects,r.replacer=t.replacer||void 0,r.excludeKeys=t.excludeKeys||void 0,void 0===e)throw new Error("Object argument required.");for(var n=0;n<p.length;++n)p[n].toLowerCase()===r.algorithm.toLowerCase()&&(r.algorithm=p[n]);if(-1===p.indexOf(r.algorithm))throw new Error('Algorithm "'+r.algorithm+'" not supported. supported values: '+p.join(", "));if(-1===g.indexOf(r.encoding)&&"passthrough"!==r.algorithm)throw new Error('Encoding "'+r.encoding+'" not supported. supported values: '+g.join(", "));return r}function y(e){if("function"==typeof e)return null!=/^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i.exec(Function.prototype.toString.call(e))}function v(e,t,r){function n(e){return t.update?t.update(e,"utf8"):t.write(e,"utf8")}return r=r||[],{dispatch:function(t){return this["_"+(null===(t=e.replacer?e.replacer(t):t)?"null":typeof t)](t)},_object:function(t){var s,a=Object.prototype.toString.call(t),o=/\[object (.*)\]/i.exec(a);if(o=(o=o?o[1]:"unknown:["+a+"]").toLowerCase(),0<=(a=r.indexOf(t)))return this.dispatch("[CIRCULAR:"+a+"]");if(r.push(t),void 0!==i&&i.isBuffer&&i.isBuffer(t))return n("buffer:"),n(t);if("object"===o||"function"===o||"asyncfunction"===o)return a=Object.keys(t),e.unorderedObjects&&(a=a.sort()),!1===e.respectType||y(t)||a.splice(0,0,"prototype","__proto__","constructor"),e.excludeKeys&&(a=a.filter((function(t){return!e.excludeKeys(t)}))),n("object:"+a.length+":"),s=this,a.forEach((function(r){s.dispatch(r),n(":"),e.excludeValues||s.dispatch(t[r]),n(",")}));if(!this["_"+o]){if(e.ignoreUnknown)return n("["+o+"]");throw new Error('Unknown object type "'+o+'"')}this["_"+o](t)},_array:function(t,s){s=void 0!==s?s:!1!==e.unorderedArrays;var i=this;if(n("array:"+t.length+":"),!s||t.length<=1)return t.forEach((function(e){return i.dispatch(e)}));var a=[];return s=t.map((function(t){var n=new b,s=r.slice();return v(e,n,s).dispatch(t),a=a.concat(s.slice(r.length)),n.read().toString()})),r=r.concat(a),s.sort(),this._array(s,!1)},_date:function(e){return n("date:"+e.toJSON())},_symbol:function(e){return n("symbol:"+e.toString())},_error:function(e){return n("error:"+e.toString())},_boolean:function(e){return n("bool:"+e.toString())},_string:function(e){n("string:"+e.length+":"),n(e.toString())},_function:function(t){n("fn:"),y(t)?this.dispatch("[native]"):this.dispatch(t.toString()),!1!==e.respectFunctionNames&&this.dispatch("function-name:"+String(t.name)),e.respectFunctionProperties&&this._object(t)},_number:function(e){return n("number:"+e.toString())},_xml:function(e){return n("xml:"+e.toString())},_null:function(){return n("Null")},_undefined:function(){return n("Undefined")},_regexp:function(e){return n("regex:"+e.toString())},_uint8array:function(e){return n("uint8array:"),this.dispatch(Array.prototype.slice.call(e))},_uint8clampedarray:function(e){return n("uint8clampedarray:"),this.dispatch(Array.prototype.slice.call(e))},_int8array:function(e){return n("int8array:"),this.dispatch(Array.prototype.slice.call(e))},_uint16array:function(e){return n("uint16array:"),this.dispatch(Array.prototype.slice.call(e))},_int16array:function(e){return n("int16array:"),this.dispatch(Array.prototype.slice.call(e))},_uint32array:function(e){return n("uint32array:"),this.dispatch(Array.prototype.slice.call(e))},_int32array:function(e){return n("int32array:"),this.dispatch(Array.prototype.slice.call(e))},_float32array:function(e){return n("float32array:"),this.dispatch(Array.prototype.slice.call(e))},_float64array:function(e){return n("float64array:"),this.dispatch(Array.prototype.slice.call(e))},_arraybuffer:function(e){return n("arraybuffer:"),this.dispatch(new Uint8Array(e))},_url:function(e){return n("url:"+e.toString())},_map:function(t){return n("map:"),t=Array.from(t),this._array(t,!1!==e.unorderedSets)},_set:function(t){return n("set:"),t=Array.from(t),this._array(t,!1!==e.unorderedSets)},_file:function(e){return n("file:"),this.dispatch([e.name,e.size,e.type,e.lastModfied])},_blob:function(){if(e.ignoreUnknown)return n("[blob]");throw Error('Hashing Blob objects is currently not supported\n(see https://github.com/puleos/object-hash/issues/26)\nUse "options.replacer" or "options.ignoreUnknown"\n')},_domwindow:function(){return n("domwindow")},_bigint:function(e){return n("bigint:"+e.toString())},_process:function(){return n("process")},_timer:function(){return n("timer")},_pipe:function(){return n("pipe")},_tcp:function(){return n("tcp")},_udp:function(){return n("udp")},_tty:function(){return n("tty")},_statwatcher:function(){return n("statwatcher")},_securecontext:function(){return n("securecontext")},_connection:function(){return n("connection")},_zlib:function(){return n("zlib")},_context:function(){return n("context")},_nodescript:function(){return n("nodescript")},_httpparser:function(){return n("httpparser")},_dataview:function(){return n("dataview")},_signal:function(){return n("signal")},_fsevent:function(){return n("fsevent")},_tlswrap:function(){return n("tlswrap")}}}function b(){return{buf:"",write:function(e){this.buf+=e},end:function(e){this.buf+=e},read:function(){return this.buf}}}r.writeToStream=function(e,t,r){return void 0===r&&(r=t,t={}),v(t=m(e,t),r).dispatch(e)}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/fake_9a5aa49d.js","/")},{buffer:3,crypto:5,lYpoI2:11}],2:[function(e,t,r){(function(e,t,n,s,i,a,o,l,c){!function(e){var t="undefined"!=typeof Uint8Array?Uint8Array:Array,r="+".charCodeAt(0),n="/".charCodeAt(0),s="0".charCodeAt(0),i="a".charCodeAt(0),a="A".charCodeAt(0),o="-".charCodeAt(0),l="_".charCodeAt(0);function c(e){return(e=e.charCodeAt(0))===r||e===o?62:e===n||e===l?63:e<s?-1:e<s+10?e-s+26+26:e<a+26?e-a:e<i+26?e-i+26:void 0}e.toByteArray=function(e){var r,n;if(0<e.length%4)throw new Error("Invalid string. Length must be a multiple of 4");var s=e.length,i=(s="="===e.charAt(s-2)?2:"="===e.charAt(s-1)?1:0,new t(3*e.length/4-s)),a=0<s?e.length-4:e.length,o=0;function l(e){i[o++]=e}for(r=0;r<a;r+=4,0)l((16711680&(n=c(e.charAt(r))<<18|c(e.charAt(r+1))<<12|c(e.charAt(r+2))<<6|c(e.charAt(r+3))))>>16),l((65280&n)>>8),l(255&n);return 2==s?l(255&(n=c(e.charAt(r))<<2|c(e.charAt(r+1))>>4)):1==s&&(l((n=c(e.charAt(r))<<10|c(e.charAt(r+1))<<4|c(e.charAt(r+2))>>2)>>8&255),l(255&n)),i},e.fromByteArray=function(e){var t,r,n,s,i=e.length%3,a="";function o(e){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(e)}for(t=0,n=e.length-i;t<n;t+=3)a+=o((s=r=(e[t]<<16)+(e[t+1]<<8)+e[t+2])>>18&63)+o(s>>12&63)+o(s>>6&63)+o(63&s);switch(i){case 1:a=(a+=o((r=e[e.length-1])>>2))+o(r<<4&63)+"==";break;case 2:a=(a=(a+=o((r=(e[e.length-2]<<8)+e[e.length-1])>>10))+o(r>>4&63))+o(r<<2&63)+"="}return a}}(void 0===r?this.base64js={}:r)}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/base64-js/lib/b64.js","/node_modules/gulp-browserify/node_modules/base64-js/lib")},{buffer:3,lYpoI2:11}],3:[function(e,t,r){(function(t,n,s,i,a,o,l,c,d){var u=e("base64-js"),h=e("ieee754");function s(e,t,r){if(!(this instanceof s))return new s(e,t,r);var n,i,a,o,l=typeof e;if("base64"===t&&"string"==l)for(e=(o=e).trim?o.trim():o.replace(/^\s+|\s+$/g,"");e.length%4!=0;)e+="=";if("number"==l)n=L(e);else if("string"==l)n=s.byteLength(e,t);else{if("object"!=l)throw new Error("First argument needs to be a number, array or string.");n=L(e.length)}if(s._useTypedArrays?i=s._augment(new Uint8Array(n)):((i=this).length=n,i._isBuffer=!0),s._useTypedArrays&&"number"==typeof e.byteLength)i._set(e);else if(D(o=e)||s.isBuffer(o)||o&&"object"==typeof o&&"number"==typeof o.length)for(a=0;a<n;a++)s.isBuffer(e)?i[a]=e.readUInt8(a):i[a]=e[a];else if("string"==l)i.write(e,0,t);else if("number"==l&&!s._useTypedArrays&&!r)for(a=0;a<n;a++)i[a]=0;return i}function f(e,t,r,n){return s._charsWritten=M(function(e){for(var t=[],r=0;r<e.length;r++)t.push(255&e.charCodeAt(r));return t}(t),e,r,n)}function p(e,t,r,n){return s._charsWritten=M(function(e){for(var t,r,n=[],s=0;s<e.length;s++)t=(r=e.charCodeAt(s))>>8,r%=256,n.push(r),n.push(t);return n}(t),e,r,n)}function g(e,t,r){var n="";r=Math.min(e.length,r);for(var s=t;s<r;s++)n+=String.fromCharCode(e[s]);return n}function m(e,t,r,n){var s;if(n||(j("boolean"==typeof r,"missing or invalid endian"),j(null!=t,"missing offset"),j(t+1<e.length,"Trying to read beyond buffer length")),!((n=e.length)<=t))return r?(s=e[t],t+1<n&&(s|=e[t+1]<<8)):(s=e[t]<<8,t+1<n&&(s|=e[t+1])),s}function y(e,t,r,n){var s;if(n||(j("boolean"==typeof r,"missing or invalid endian"),j(null!=t,"missing offset"),j(t+3<e.length,"Trying to read beyond buffer length")),!((n=e.length)<=t))return r?(t+2<n&&(s=e[t+2]<<16),t+1<n&&(s|=e[t+1]<<8),s|=e[t],t+3<n&&(s+=e[t+3]<<24>>>0)):(t+1<n&&(s=e[t+1]<<16),t+2<n&&(s|=e[t+2]<<8),t+3<n&&(s|=e[t+3]),s+=e[t]<<24>>>0),s}function v(e,t,r,n){if(n||(j("boolean"==typeof r,"missing or invalid endian"),j(null!=t,"missing offset"),j(t+1<e.length,"Trying to read beyond buffer length")),!(e.length<=t))return 32768&(n=m(e,t,r,!0))?-1*(65535-n+1):n}function b(e,t,r,n){if(n||(j("boolean"==typeof r,"missing or invalid endian"),j(null!=t,"missing offset"),j(t+3<e.length,"Trying to read beyond buffer length")),!(e.length<=t))return 2147483648&(n=y(e,t,r,!0))?-1*(4294967295-n+1):n}function w(e,t,r,n){return n||(j("boolean"==typeof r,"missing or invalid endian"),j(t+3<e.length,"Trying to read beyond buffer length")),h.read(e,t,r,23,4)}function E(e,t,r,n){return n||(j("boolean"==typeof r,"missing or invalid endian"),j(t+7<e.length,"Trying to read beyond buffer length")),h.read(e,t,r,52,8)}function S(e,t,r,n,s){if(s||(j(null!=t,"missing value"),j("boolean"==typeof n,"missing or invalid endian"),j(null!=r,"missing offset"),j(r+1<e.length,"trying to write beyond buffer length"),U(t,65535)),!((s=e.length)<=r))for(var i=0,a=Math.min(s-r,2);i<a;i++)e[r+i]=(t&255<<8*(n?i:1-i))>>>8*(n?i:1-i)}function T(e,t,r,n,s){if(s||(j(null!=t,"missing value"),j("boolean"==typeof n,"missing or invalid endian"),j(null!=r,"missing offset"),j(r+3<e.length,"trying to write beyond buffer length"),U(t,4294967295)),!((s=e.length)<=r))for(var i=0,a=Math.min(s-r,4);i<a;i++)e[r+i]=t>>>8*(n?i:3-i)&255}function C(e,t,r,n,s){s||(j(null!=t,"missing value"),j("boolean"==typeof n,"missing or invalid endian"),j(null!=r,"missing offset"),j(r+1<e.length,"Trying to write beyond buffer length"),N(t,32767,-32768)),e.length<=r||S(e,0<=t?t:65535+t+1,r,n,s)}function k(e,t,r,n,s){s||(j(null!=t,"missing value"),j("boolean"==typeof n,"missing or invalid endian"),j(null!=r,"missing offset"),j(r+3<e.length,"Trying to write beyond buffer length"),N(t,2147483647,-2147483648)),e.length<=r||T(e,0<=t?t:4294967295+t+1,r,n,s)}function A(e,t,r,n,s){s||(j(null!=t,"missing value"),j("boolean"==typeof n,"missing or invalid endian"),j(null!=r,"missing offset"),j(r+3<e.length,"Trying to write beyond buffer length"),B(t,34028234663852886e22,-34028234663852886e22)),e.length<=r||h.write(e,t,r,n,23,4)}function I(e,t,r,n,s){s||(j(null!=t,"missing value"),j("boolean"==typeof n,"missing or invalid endian"),j(null!=r,"missing offset"),j(r+7<e.length,"Trying to write beyond buffer length"),B(t,17976931348623157e292,-17976931348623157e292)),e.length<=r||h.write(e,t,r,n,52,8)}r.Buffer=s,r.SlowBuffer=s,r.INSPECT_MAX_BYTES=50,s.poolSize=8192,s._useTypedArrays=function(){try{var e=new ArrayBuffer(0),t=new Uint8Array(e);return t.foo=function(){return 42},42===t.foo()&&"function"==typeof t.subarray}catch(e){return!1}}(),s.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},s.isBuffer=function(e){return!(null==e||!e._isBuffer)},s.byteLength=function(e,t){var r;switch(e+="",t||"utf8"){case"hex":r=e.length/2;break;case"utf8":case"utf-8":r=O(e).length;break;case"ascii":case"binary":case"raw":r=e.length;break;case"base64":r=P(e).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":r=2*e.length;break;default:throw new Error("Unknown encoding")}return r},s.concat=function(e,t){if(j(D(e),"Usage: Buffer.concat(list, [totalLength])\nlist should be an Array."),0===e.length)return new s(0);if(1===e.length)return e[0];if("number"!=typeof t)for(i=t=0;i<e.length;i++)t+=e[i].length;for(var r=new s(t),n=0,i=0;i<e.length;i++){var a=e[i];a.copy(r,n),n+=a.length}return r},s.prototype.write=function(e,t,r,n){isFinite(t)?isFinite(r)||(n=r,r=void 0):(c=n,n=t,t=r,r=c),t=Number(t)||0;var i,a,o,l,c=this.length-t;switch((!r||c<(r=Number(r)))&&(r=c),n=String(n||"utf8").toLowerCase()){case"hex":i=function(e,t,r,n){r=Number(r)||0;var i=e.length-r;(!n||i<(n=Number(n)))&&(n=i),j((i=t.length)%2==0,"Invalid hex string"),i/2<n&&(n=i/2);for(var a=0;a<n;a++){var o=parseInt(t.substr(2*a,2),16);j(!isNaN(o),"Invalid hex string"),e[r+a]=o}return s._charsWritten=2*a,a}(this,e,t,r);break;case"utf8":case"utf-8":a=this,o=t,l=r,i=s._charsWritten=M(O(e),a,o,l);break;case"ascii":case"binary":i=f(this,e,t,r);break;case"base64":a=this,o=t,l=r,i=s._charsWritten=M(P(e),a,o,l);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":i=p(this,e,t,r);break;default:throw new Error("Unknown encoding")}return i},s.prototype.toString=function(e,t,r){var n,s,i,a,o=this;if(e=String(e||"utf8").toLowerCase(),t=Number(t)||0,(r=void 0!==r?Number(r):o.length)===t)return"";switch(e){case"hex":n=function(e,t,r){var n=e.length;(!t||t<0)&&(t=0),(!r||r<0||n<r)&&(r=n);for(var s="",i=t;i<r;i++)s+=x(e[i]);return s}(o,t,r);break;case"utf8":case"utf-8":n=function(e,t,r){var n="",s="";r=Math.min(e.length,r);for(var i=t;i<r;i++)e[i]<=127?(n+=F(s)+String.fromCharCode(e[i]),s=""):s+="%"+e[i].toString(16);return n+F(s)}(o,t,r);break;case"ascii":case"binary":n=g(o,t,r);break;case"base64":s=o,a=r,n=0===(i=t)&&a===s.length?u.fromByteArray(s):u.fromByteArray(s.slice(i,a));break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":n=function(e,t,r){for(var n=e.slice(t,r),s="",i=0;i<n.length;i+=2)s+=String.fromCharCode(n[i]+256*n[i+1]);return s}(o,t,r);break;default:throw new Error("Unknown encoding")}return n},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},s.prototype.copy=function(e,t,r,n){if(t=t||0,(n=n||0===n?n:this.length)!==(r=r||0)&&0!==e.length&&0!==this.length){j(r<=n,"sourceEnd < sourceStart"),j(0<=t&&t<e.length,"targetStart out of bounds"),j(0<=r&&r<this.length,"sourceStart out of bounds"),j(0<=n&&n<=this.length,"sourceEnd out of bounds"),n>this.length&&(n=this.length);var i=(n=e.length-t<n-r?e.length-t+r:n)-r;if(i<100||!s._useTypedArrays)for(var a=0;a<i;a++)e[a+t]=this[a+r];else e._set(this.subarray(r,r+i),t)}},s.prototype.slice=function(e,t){var r=this.length;if(e=R(e,r,0),t=R(t,r,r),s._useTypedArrays)return s._augment(this.subarray(e,t));for(var n=t-e,i=new s(n,void 0,!0),a=0;a<n;a++)i[a]=this[a+e];return i},s.prototype.get=function(e){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(e)},s.prototype.set=function(e,t){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(e,t)},s.prototype.readUInt8=function(e,t){if(t||(j(null!=e,"missing offset"),j(e<this.length,"Trying to read beyond buffer length")),!(e>=this.length))return this[e]},s.prototype.readUInt16LE=function(e,t){return m(this,e,!0,t)},s.prototype.readUInt16BE=function(e,t){return m(this,e,!1,t)},s.prototype.readUInt32LE=function(e,t){return y(this,e,!0,t)},s.prototype.readUInt32BE=function(e,t){return y(this,e,!1,t)},s.prototype.readInt8=function(e,t){if(t||(j(null!=e,"missing offset"),j(e<this.length,"Trying to read beyond buffer length")),!(e>=this.length))return 128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){return v(this,e,!0,t)},s.prototype.readInt16BE=function(e,t){return v(this,e,!1,t)},s.prototype.readInt32LE=function(e,t){return b(this,e,!0,t)},s.prototype.readInt32BE=function(e,t){return b(this,e,!1,t)},s.prototype.readFloatLE=function(e,t){return w(this,e,!0,t)},s.prototype.readFloatBE=function(e,t){return w(this,e,!1,t)},s.prototype.readDoubleLE=function(e,t){return E(this,e,!0,t)},s.prototype.readDoubleBE=function(e,t){return E(this,e,!1,t)},s.prototype.writeUInt8=function(e,t,r){r||(j(null!=e,"missing value"),j(null!=t,"missing offset"),j(t<this.length,"trying to write beyond buffer length"),U(e,255)),t>=this.length||(this[t]=e)},s.prototype.writeUInt16LE=function(e,t,r){S(this,e,t,!0,r)},s.prototype.writeUInt16BE=function(e,t,r){S(this,e,t,!1,r)},s.prototype.writeUInt32LE=function(e,t,r){T(this,e,t,!0,r)},s.prototype.writeUInt32BE=function(e,t,r){T(this,e,t,!1,r)},s.prototype.writeInt8=function(e,t,r){r||(j(null!=e,"missing value"),j(null!=t,"missing offset"),j(t<this.length,"Trying to write beyond buffer length"),N(e,127,-128)),t>=this.length||(0<=e?this.writeUInt8(e,t,r):this.writeUInt8(255+e+1,t,r))},s.prototype.writeInt16LE=function(e,t,r){C(this,e,t,!0,r)},s.prototype.writeInt16BE=function(e,t,r){C(this,e,t,!1,r)},s.prototype.writeInt32LE=function(e,t,r){k(this,e,t,!0,r)},s.prototype.writeInt32BE=function(e,t,r){k(this,e,t,!1,r)},s.prototype.writeFloatLE=function(e,t,r){A(this,e,t,!0,r)},s.prototype.writeFloatBE=function(e,t,r){A(this,e,t,!1,r)},s.prototype.writeDoubleLE=function(e,t,r){I(this,e,t,!0,r)},s.prototype.writeDoubleBE=function(e,t,r){I(this,e,t,!1,r)},s.prototype.fill=function(e,t,r){if(t=t||0,r=r||this.length,j("number"==typeof(e="string"==typeof(e=e||0)?e.charCodeAt(0):e)&&!isNaN(e),"value is not a number"),j(t<=r,"end < start"),r!==t&&0!==this.length){j(0<=t&&t<this.length,"start out of bounds"),j(0<=r&&r<=this.length,"end out of bounds");for(var n=t;n<r;n++)this[n]=e}},s.prototype.inspect=function(){for(var e=[],t=this.length,n=0;n<t;n++)if(e[n]=x(this[n]),n===r.INSPECT_MAX_BYTES){e[n+1]="...";break}return"<Buffer "+e.join(" ")+">"},s.prototype.toArrayBuffer=function(){if("undefined"==typeof Uint8Array)throw new Error("Buffer.toArrayBuffer not supported in this browser");if(s._useTypedArrays)return new s(this).buffer;for(var e=new Uint8Array(this.length),t=0,r=e.length;t<r;t+=1)e[t]=this[t];return e.buffer};var _=s.prototype;function R(e,t,r){return"number"!=typeof e?r:t<=(e=~~e)?t:0<=e||0<=(e+=t)?e:0}function L(e){return(e=~~Math.ceil(+e))<0?0:e}function D(e){return(Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)})(e)}function x(e){return e<16?"0"+e.toString(16):e.toString(16)}function O(e){for(var t=[],r=0;r<e.length;r++){var n=e.charCodeAt(r);if(n<=127)t.push(e.charCodeAt(r));else for(var s=r,i=(55296<=n&&n<=57343&&r++,encodeURIComponent(e.slice(s,r+1)).substr(1).split("%")),a=0;a<i.length;a++)t.push(parseInt(i[a],16))}return t}function P(e){return u.toByteArray(e)}function M(e,t,r,n){for(var s=0;s<n&&!(s+r>=t.length||s>=e.length);s++)t[s+r]=e[s];return s}function F(e){try{return decodeURIComponent(e)}catch(e){return String.fromCharCode(65533)}}function U(e,t){j("number"==typeof e,"cannot write a non-number as a number"),j(0<=e,"specified a negative value for writing an unsigned value"),j(e<=t,"value is larger than maximum value for type"),j(Math.floor(e)===e,"value has a fractional component")}function N(e,t,r){j("number"==typeof e,"cannot write a non-number as a number"),j(e<=t,"value larger than maximum allowed value"),j(r<=e,"value smaller than minimum allowed value"),j(Math.floor(e)===e,"value has a fractional component")}function B(e,t,r){j("number"==typeof e,"cannot write a non-number as a number"),j(e<=t,"value larger than maximum allowed value"),j(r<=e,"value smaller than minimum allowed value")}function j(e,t){if(!e)throw new Error(t||"Failed assertion")}s._augment=function(e){return e._isBuffer=!0,e._get=e.get,e._set=e.set,e.get=_.get,e.set=_.set,e.write=_.write,e.toString=_.toString,e.toLocaleString=_.toString,e.toJSON=_.toJSON,e.copy=_.copy,e.slice=_.slice,e.readUInt8=_.readUInt8,e.readUInt16LE=_.readUInt16LE,e.readUInt16BE=_.readUInt16BE,e.readUInt32LE=_.readUInt32LE,e.readUInt32BE=_.readUInt32BE,e.readInt8=_.readInt8,e.readInt16LE=_.readInt16LE,e.readInt16BE=_.readInt16BE,e.readInt32LE=_.readInt32LE,e.readInt32BE=_.readInt32BE,e.readFloatLE=_.readFloatLE,e.readFloatBE=_.readFloatBE,e.readDoubleLE=_.readDoubleLE,e.readDoubleBE=_.readDoubleBE,e.writeUInt8=_.writeUInt8,e.writeUInt16LE=_.writeUInt16LE,e.writeUInt16BE=_.writeUInt16BE,e.writeUInt32LE=_.writeUInt32LE,e.writeUInt32BE=_.writeUInt32BE,e.writeInt8=_.writeInt8,e.writeInt16LE=_.writeInt16LE,e.writeInt16BE=_.writeInt16BE,e.writeInt32LE=_.writeInt32LE,e.writeInt32BE=_.writeInt32BE,e.writeFloatLE=_.writeFloatLE,e.writeFloatBE=_.writeFloatBE,e.writeDoubleLE=_.writeDoubleLE,e.writeDoubleBE=_.writeDoubleBE,e.fill=_.fill,e.inspect=_.inspect,e.toArrayBuffer=_.toArrayBuffer,e}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/buffer/index.js","/node_modules/gulp-browserify/node_modules/buffer")},{"base64-js":2,buffer:3,ieee754:10,lYpoI2:11}],4:[function(e,t,r){(function(r,n,s,i,a,o,l,c,d){s=e("buffer").Buffer;var u=4,h=new s(u);h.fill(0),t.exports={hash:function(e,t,r,n){for(var i=t(function(e,t){e.length%u!=0&&(r=e.length+(u-e.length%u),e=s.concat([e,h],r));for(var r,n=[],i=t?e.readInt32BE:e.readInt32LE,a=0;a<e.length;a+=u)n.push(i.call(e,a));return n}(e=s.isBuffer(e)?e:new s(e),n),8*e.length),a=(t=n,new s(r)),o=t?a.writeInt32BE:a.writeInt32LE,l=0;l<i.length;l++)o.call(a,i[l],4*l,!0);return a}}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/helpers.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],5:[function(e,t,r){(function(t,n,s,i,a,o,l,c,d){s=e("buffer").Buffer;var u=e("./sha"),h=e("./sha256"),f=e("./rng"),p={sha1:u,sha256:h,md5:e("./md5")},g=64,m=new s(g);function y(e,t){var r=p[e=e||"sha1"],n=[];return r||v("algorithm:",e,"is not yet supported"),{update:function(e){return s.isBuffer(e)||(e=new s(e)),n.push(e),e.length,this},digest:function(e){var i=s.concat(n);return i=t?function(e,t,r){s.isBuffer(t)||(t=new s(t)),s.isBuffer(r)||(r=new s(r)),t.length>g?t=e(t):t.length<g&&(t=s.concat([t,m],g));for(var n=new s(g),i=new s(g),a=0;a<g;a++)n[a]=54^t[a],i[a]=92^t[a];return r=e(s.concat([n,r])),e(s.concat([i,r]))}(r,t,i):r(i),n=null,e?i.toString(e):i}}}function v(){var e=[].slice.call(arguments).join(" ");throw new Error([e,"we accept pull requests","http://github.com/dominictarr/crypto-browserify"].join("\n"))}m.fill(0),r.createHash=function(e){return y(e)},r.createHmac=y,r.randomBytes=function(e,t){if(!t||!t.call)return new s(f(e));try{t.call(this,void 0,new s(f(e)))}catch(e){t(e)}};var b,w=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],E=function(e){r[e]=function(){v("sorry,",e,"is not implemented yet")}};for(b in w)E(w[b])}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/index.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./md5":6,"./rng":7,"./sha":8,"./sha256":9,buffer:3,lYpoI2:11}],6:[function(e,t,r){(function(r,n,s,i,a,o,l,c,d){var u=e("./helpers");function h(e,t){e[t>>5]|=128<<t%32,e[14+(t+64>>>9<<4)]=t;for(var r=1732584193,n=-271733879,s=-1732584194,i=271733878,a=0;a<e.length;a+=16){var o=r,l=n,c=s,d=i;r=p(r,n,s,i,e[a+0],7,-680876936),i=p(i,r,n,s,e[a+1],12,-389564586),s=p(s,i,r,n,e[a+2],17,606105819),n=p(n,s,i,r,e[a+3],22,-1044525330),r=p(r,n,s,i,e[a+4],7,-176418897),i=p(i,r,n,s,e[a+5],12,1200080426),s=p(s,i,r,n,e[a+6],17,-1473231341),n=p(n,s,i,r,e[a+7],22,-45705983),r=p(r,n,s,i,e[a+8],7,1770035416),i=p(i,r,n,s,e[a+9],12,-1958414417),s=p(s,i,r,n,e[a+10],17,-42063),n=p(n,s,i,r,e[a+11],22,-1990404162),r=p(r,n,s,i,e[a+12],7,1804603682),i=p(i,r,n,s,e[a+13],12,-40341101),s=p(s,i,r,n,e[a+14],17,-1502002290),r=g(r,n=p(n,s,i,r,e[a+15],22,1236535329),s,i,e[a+1],5,-165796510),i=g(i,r,n,s,e[a+6],9,-1069501632),s=g(s,i,r,n,e[a+11],14,643717713),n=g(n,s,i,r,e[a+0],20,-373897302),r=g(r,n,s,i,e[a+5],5,-701558691),i=g(i,r,n,s,e[a+10],9,38016083),s=g(s,i,r,n,e[a+15],14,-660478335),n=g(n,s,i,r,e[a+4],20,-405537848),r=g(r,n,s,i,e[a+9],5,568446438),i=g(i,r,n,s,e[a+14],9,-1019803690),s=g(s,i,r,n,e[a+3],14,-187363961),n=g(n,s,i,r,e[a+8],20,1163531501),r=g(r,n,s,i,e[a+13],5,-1444681467),i=g(i,r,n,s,e[a+2],9,-51403784),s=g(s,i,r,n,e[a+7],14,1735328473),r=m(r,n=g(n,s,i,r,e[a+12],20,-1926607734),s,i,e[a+5],4,-378558),i=m(i,r,n,s,e[a+8],11,-2022574463),s=m(s,i,r,n,e[a+11],16,1839030562),n=m(n,s,i,r,e[a+14],23,-35309556),r=m(r,n,s,i,e[a+1],4,-1530992060),i=m(i,r,n,s,e[a+4],11,1272893353),s=m(s,i,r,n,e[a+7],16,-155497632),n=m(n,s,i,r,e[a+10],23,-1094730640),r=m(r,n,s,i,e[a+13],4,681279174),i=m(i,r,n,s,e[a+0],11,-358537222),s=m(s,i,r,n,e[a+3],16,-722521979),n=m(n,s,i,r,e[a+6],23,76029189),r=m(r,n,s,i,e[a+9],4,-640364487),i=m(i,r,n,s,e[a+12],11,-421815835),s=m(s,i,r,n,e[a+15],16,530742520),r=y(r,n=m(n,s,i,r,e[a+2],23,-995338651),s,i,e[a+0],6,-198630844),i=y(i,r,n,s,e[a+7],10,1126891415),s=y(s,i,r,n,e[a+14],15,-1416354905),n=y(n,s,i,r,e[a+5],21,-57434055),r=y(r,n,s,i,e[a+12],6,1700485571),i=y(i,r,n,s,e[a+3],10,-1894986606),s=y(s,i,r,n,e[a+10],15,-1051523),n=y(n,s,i,r,e[a+1],21,-2054922799),r=y(r,n,s,i,e[a+8],6,1873313359),i=y(i,r,n,s,e[a+15],10,-30611744),s=y(s,i,r,n,e[a+6],15,-1560198380),n=y(n,s,i,r,e[a+13],21,1309151649),r=y(r,n,s,i,e[a+4],6,-145523070),i=y(i,r,n,s,e[a+11],10,-1120210379),s=y(s,i,r,n,e[a+2],15,718787259),n=y(n,s,i,r,e[a+9],21,-343485551),r=v(r,o),n=v(n,l),s=v(s,c),i=v(i,d)}return Array(r,n,s,i)}function f(e,t,r,n,s,i){return v((t=v(v(t,e),v(n,i)))<<s|t>>>32-s,r)}function p(e,t,r,n,s,i,a){return f(t&r|~t&n,e,t,s,i,a)}function g(e,t,r,n,s,i,a){return f(t&n|r&~n,e,t,s,i,a)}function m(e,t,r,n,s,i,a){return f(t^r^n,e,t,s,i,a)}function y(e,t,r,n,s,i,a){return f(r^(t|~n),e,t,s,i,a)}function v(e,t){var r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}t.exports=function(e){return u.hash(e,h,16)}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/md5.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],7:[function(e,t,r){(function(e,r,n,s,i,a,o,l,c){t.exports=function(e){for(var t,r=new Array(e),n=0;n<e;n++)0==(3&n)&&(t=4294967296*Math.random()),r[n]=t>>>((3&n)<<3)&255;return r}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/rng.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],8:[function(e,t,r){(function(r,n,s,i,a,o,l,c,d){var u=e("./helpers");function h(e,t){e[t>>5]|=128<<24-t%32,e[15+(t+64>>9<<4)]=t;for(var r,n,s,i=Array(80),a=1732584193,o=-271733879,l=-1732584194,c=271733878,d=-1009589776,u=0;u<e.length;u+=16){for(var h=a,g=o,m=l,y=c,v=d,b=0;b<80;b++){i[b]=b<16?e[u+b]:p(i[b-3]^i[b-8]^i[b-14]^i[b-16],1);var w=f(f(p(a,5),(w=o,n=l,s=c,(r=b)<20?w&n|~w&s:!(r<40)&&r<60?w&n|w&s|n&s:w^n^s)),f(f(d,i[b]),(r=b)<20?1518500249:r<40?1859775393:r<60?-1894007588:-899497514));d=c,c=l,l=p(o,30),o=a,a=w}a=f(a,h),o=f(o,g),l=f(l,m),c=f(c,y),d=f(d,v)}return Array(a,o,l,c,d)}function f(e,t){var r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function p(e,t){return e<<t|e>>>32-t}t.exports=function(e){return u.hash(e,h,20,!0)}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],9:[function(e,t,r){(function(r,n,s,i,a,o,l,c,d){function u(e,t){var r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function h(e,t){var r,n=new Array(1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298),s=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),i=new Array(64);e[t>>5]|=128<<24-t%32,e[15+(t+64>>9<<4)]=t;for(var a,o,l=0;l<e.length;l+=16){for(var c=s[0],d=s[1],h=s[2],f=s[3],m=s[4],y=s[5],v=s[6],b=s[7],w=0;w<64;w++)i[w]=w<16?e[w+l]:u(u(u((o=i[w-2],p(o,17)^p(o,19)^g(o,10)),i[w-7]),(o=i[w-15],p(o,7)^p(o,18)^g(o,3))),i[w-16]),r=u(u(u(u(b,p(o=m,6)^p(o,11)^p(o,25)),m&y^~m&v),n[w]),i[w]),a=u(p(a=c,2)^p(a,13)^p(a,22),c&d^c&h^d&h),b=v,v=y,y=m,m=u(f,r),f=h,h=d,d=c,c=u(r,a);s[0]=u(c,s[0]),s[1]=u(d,s[1]),s[2]=u(h,s[2]),s[3]=u(f,s[3]),s[4]=u(m,s[4]),s[5]=u(y,s[5]),s[6]=u(v,s[6]),s[7]=u(b,s[7])}return s}var f=e("./helpers"),p=function(e,t){return e>>>t|e<<32-t},g=function(e,t){return e>>>t};t.exports=function(e){return f.hash(e,h,32,!0)}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha256.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],10:[function(e,t,r){(function(e,t,n,s,i,a,o,l,c){r.read=function(e,t,r,n,s){var i,a,o=8*s-n-1,l=(1<<o)-1,c=l>>1,d=-7,u=r?s-1:0,h=r?-1:1;for(s=e[t+u],u+=h,i=s&(1<<-d)-1,s>>=-d,d+=o;0<d;i=256*i+e[t+u],u+=h,d-=8);for(a=i&(1<<-d)-1,i>>=-d,d+=n;0<d;a=256*a+e[t+u],u+=h,d-=8);if(0===i)i=1-c;else{if(i===l)return a?NaN:1/0*(s?-1:1);a+=Math.pow(2,n),i-=c}return(s?-1:1)*a*Math.pow(2,i-n)},r.write=function(e,t,r,n,s,i){var a,o,l=8*i-s-1,c=(1<<l)-1,d=c>>1,u=23===s?Math.pow(2,-24)-Math.pow(2,-77):0,h=n?0:i-1,f=n?1:-1;for(i=t<0||0===t&&1/t<0?1:0,t=Math.abs(t),isNaN(t)||t===1/0?(o=isNaN(t)?1:0,a=c):(a=Math.floor(Math.log(t)/Math.LN2),t*(n=Math.pow(2,-a))<1&&(a--,n*=2),2<=(t+=1<=a+d?u/n:u*Math.pow(2,1-d))*n&&(a++,n/=2),c<=a+d?(o=0,a=c):1<=a+d?(o=(t*n-1)*Math.pow(2,s),a+=d):(o=t*Math.pow(2,d-1)*Math.pow(2,s),a=0));8<=s;e[r+h]=255&o,h+=f,o/=256,s-=8);for(a=a<<s|o,l+=s;0<l;e[r+h]=255&a,h+=f,a/=256,l-=8);e[r+h-f]|=128*i}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/ieee754/index.js","/node_modules/gulp-browserify/node_modules/ieee754")},{buffer:3,lYpoI2:11}],11:[function(e,t,r){(function(e,r,n,s,i,a,o,l,c){var d,u,h;function f(){}(e=t.exports={}).nextTick=(u="undefined"!=typeof window&&window.setImmediate,h="undefined"!=typeof window&&window.postMessage&&window.addEventListener,u?function(e){return window.setImmediate(e)}:h?(d=[],window.addEventListener("message",(function(e){var t=e.source;t!==window&&null!==t||"process-tick"!==e.data||(e.stopPropagation(),0<d.length&&d.shift()())}),!0),function(e){d.push(e),window.postMessage("process-tick","*")}):function(e){setTimeout(e,0)}),e.title="browser",e.browser=!0,e.env={},e.argv=[],e.on=f,e.addListener=f,e.once=f,e.off=f,e.removeListener=f,e.removeAllListeners=f,e.emit=f,e.binding=function(e){throw new Error("process.binding is not supported")},e.cwd=function(){return"/"},e.chdir=function(e){throw new Error("process.chdir is not supported")}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/process/browser.js","/node_modules/gulp-browserify/node_modules/process")},{buffer:3,lYpoI2:11}]},{},[1])(1)}(rh);var nh=rh.exports;class sh{constructor(e){const{http:t}=ve();this.queryParams=e,this.http=t}loadFirstPage(){return this.onFetch("first")}loadNextPage(){return this.onFetch("next")}loadPreviousPage(){return this.onFetch("prev")}async onFetch(e="first"){var t,r,n,s;if("prev"===e&&!this.previousToken)return;if("next"===e&&!this.nextToken)return;let i;"prev"===e&&(i=this.previousToken),"next"===e&&(i=this.nextToken);const a=await this.getRequest(this.queryParams,i);return"first"===e&&(this.nextToken=null===(t=a.paging)||void 0===t?void 0:t.next,this.previousToken=null===(r=a.paging)||void 0===r?void 0:r.previous),"prev"===e&&(this.previousToken=null===(n=a.paging)||void 0===n?void 0:n.previous),"next"===e&&(this.nextToken=null===(s=a.paging)||void 0===s?void 0:s.next),a}getNextToken(){return this.nextToken}getPrevToken(){return this.previousToken}}class ih extends sh{async getRequest(e,t){const r=Ml(e),{data:n}=await this.http.get("/api/v5/messages",{params:Object.assign(Object.assign({},r),{options:t?{token:t}:Object.assign({},r.options)})});return n}}class ah{constructor(e,t){this.query=e,this.cacheKey=t}}class oh extends ah{constructor(e,t,r,n,s){super(e,t),this.notifyChange=r,this.preparePayload=n,this.paginationController=s}async saveToMainDB(e){const t=await this.preparePayload(e),r=ve(),n=r.cache&&Date.now();r.cache&&Oo(t,{cachedAt:n})}appendToQueryStream(e,t,r=!1){var n,s;if(r)Se(this.cacheKey,{data:e.messages.map(de("message")),query:this.query});else{const r=null===(n=Ee(this.cacheKey))||void 0===n?void 0:n.data,i=null!==(s=null==r?void 0:r.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},r),{data:"next"===t?[...new Set([...i,...e.messages.map(de("message"))])]:[...new Set([...e.messages.map(de("message")),...i])]}))}}reactor(e){return t=>{var r,n,s,i,a;if("onCreate"===e){const e=null===(r=Ee(this.cacheKey))||void 0===r?void 0:r.data;if(!e)return;if(this.query.subChannelId!==(null==t?void 0:t.subChannelId)||!e)return;if(this.query.type&&this.query.type!==t.dataType)return;if(this.query.dataType&&this.query.dataType!==t.dataType)return;if(this.query.excludingTags&&(null===(n=this.query.excludingTags)||void 0===n?void 0:n.some((e=>{var r;return null===(r=t.tags)||void 0===r?void 0:r.includes(e)}))))return;if(this.query.excludeTags&&(null===(s=this.query.excludeTags)||void 0===s?void 0:s.some((e=>{var r;return null===(r=t.tags)||void 0===r?void 0:r.includes(e)}))))return;if(!!this.query.hasFlags!=!!t.flagCount)return;if(this.query.parentId&&this.query.parentId!==t.parentId)return;if(this.query.hasOwnProperty("includeDeleted")&&!this.query.includeDeleted&&t.isDeleted)return;if(this.query.includingTags&&!(null===(i=this.query.includingTags)||void 0===i?void 0:i.some((e=>{var r;return null===(r=t.tags)||void 0===r?void 0:r.includes(e)}))))return;if(this.query.tags&&!(null===(a=this.query.tags)||void 0===a?void 0:a.some((e=>{var r;return null===(r=t.tags)||void 0===r?void 0:r.includes(e)}))))return;this.query.sortBy&&"segmentDesc"!==this.query.sortBy||this.paginationController.getPrevToken()||(e.data=[...new Set([t.messageId,...e.data])]),"segmentAsc"!==this.query.sortBy||this.paginationController.getNextToken()||(e.data=[...new Set([...e.data,t.messageId])]),Se(this.cacheKey,e)}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class lh{constructor(e){const{http:t}=ve();this.queryParams=e,this.http=t}async onFetch(){return await this.getRequest(this.queryParams)}}class ch{constructor(e,t,r,n){this.paginationController=e,this.queryStreamId=t,this.cacheKey=r,this.callback=n}async refresh(){try{let e;if(e=this.paginationController instanceof lh?await this.paginationController.onFetch():await this.paginationController.loadFirstPage(),!e)return;await this.persistModel(e),this.persistQueryStream({response:e,direction:"next",refresh:!0}),this.notifyChange({origin:"server",loading:!1})}catch(e){this.notifyChange({origin:"server",loading:!1,error:e})}}loadPage(e=!1,t="next"){this.setup(),this.notifyChange({origin:"local",loading:!0}),e?this.refresh():"prev"===t?this.loadPrevPage():"next"===t&&this.loadNextPage()}async loadNextPage(){try{if(this.paginationController instanceof lh)return;const e=await this.paginationController.loadNextPage();if(!e)return;await this.persistModel(e),this.persistQueryStream({response:e,direction:"next"}),this.notifyChange({origin:"server",loading:!1})}catch(e){this.notifyChange({origin:"server",loading:!1,error:e})}}async loadPrevPage(){try{if(this.paginationController instanceof lh)return;const e=await this.paginationController.loadPreviousPage();if(!e)return;await this.persistModel(e),this.persistQueryStream({response:e,direction:"prev"}),this.notifyChange({origin:"server",loading:!1})}catch(e){this.notifyChange({origin:"server",loading:!1,error:e})}}shouldNotify(e){return!fd(this.snapshot,e)&&(this.snapshot=e.map((e=>hd(e))),!0)}getCacheKey(){return this.cacheKey}}class dh extends ch{constructor(e,t){const r=nh(e),n=["message","collection",r];super(new ih(e),r,n,t),this.query=e,this.queryStreamController=new oh(this.query,this.cacheKey,this.notifyChange.bind(this),Ol,this.paginationController),this.callback=t.bind(this),this.loadPage(!0)}setup(){var e;(null===(e=Ee(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],query:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:r}){this.queryStreamController.appendToQueryStream(e,t,r)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Dc,action:"onCreate"},{fn:Pu,action:"onDelete"},{fn:Ou,action:"onUpdate"},{fn:Qu,action:"onFlagged"},{fn:Xu,action:"onUnflagged"},{fn:Ju,action:"onFlagCleared"},{fn:Zu,action:"onReactionAdded"},{fn:eh,action:"onReactionRemoved"},{fn:xu(dd,"contentId","message"),action:"onUpdate"},{fn:xu(ud,"contentId","message"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:r}){var n,s;const i=null===(n=Ee(this.cacheKey))||void 0===n?void 0:n.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>Ee(["message","get",e]))).filter(Boolean).map((({data:e})=>e)).map((e=>il.message(e))))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage(!1,"next"),onPrevPage:()=>this.loadPage(!1,"prev"),data:a,hasNextPage:!!this.paginationController.getNextToken(),hasPrevPage:!!this.paginationController.getPrevToken(),loading:t,error:r})}applyFilter(e){let t=e;return t=t.filter((e=>!this.query.tags||this.query.tags.find((t=>!!e.tags&&e.tags.includes(t))))),t=t.filter((e=>!this.query.excludeTags||(this.query.excludeTags||[]).find((t=>!e.tags||!e.tags.includes(t))))),this.query.includeDeleted||(t=Ae(t,"isDeleted",!1)),t=t.sort(((e,t)=>"segmentAsc"===this.query.sortBy?e.channelSegment-t.channelSegment:"segmentDesc"===this.query.sortBy?t.channelSegment-e.channelSegment:0)),t}}const uh=async(e,t=!1)=>{const r=ve();let n;r.log("message/getMessage",e),t||console.log("getMessage will be deprecated on 15th November 2022, please use liveMessage instead."),ql("message",e);try{const{data:t}=await r.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);n=await Ol(t)}catch(t){throw C(null==t?void 0:t.code)&&Po("message",e),t}const s=r.cache&&Date.now();r.cache&&Oo(n,{cachedAt:s});const{messages:i}=n;return Je("local.message.fetched",{messages:i}),{data:il.message(i.find((t=>t.messageId===e))),cachedAt:s}};uh.locally=e=>{const t=ve();if(t.log("message/getMessage.locally",e),!t.cache)return;const r=Ee(["message","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};var hh=Object.freeze({__proto__:null,getMessageByIds:ju,createMessage:Ku,updateMessage:Gu,editMessage:Hu,deleteMessage:Vu,softDeleteMessage:zu,markAsDelivered:async(e,t)=>{const r=ve();r.log("message/markAsDelivered",e,t);const{data:n}=await r.http.put(`/api/v1/markers/message-feeds/${e}/mark-delivering`,{messageId:t}),{userMarkers:s,userEntityMarkers:i,userFeedMarkers:a}=n,o=Mo(n,["userMarkers","userEntityMarkers","userFeedMarkers"]),l=r.cache&&Date.now();return r.cache&&Oo(Object.assign({userMarkers:s,userEntityMarkers:Bo(i),userFeedMarkers:jo(a)},o),{cachedAt:l}),!0},getReadUsers:Wu,getDeliveredUsers:Yu,flagMessage:async e=>{const t=ve();t.log("message/flag",e);const{data:r}=await t.http.post(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await Ol(r);Oo(e)}return Je("message.flagged",r),!!r},unflagMessage:async e=>{const t=ve();t.log("message/unflag",e);const{data:r}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await Ol(r);Oo(e)}return Je("message.unflagged",r),!!r},isMessageFlaggedByMe:async e=>{const t=ve();t.log("message/isMessageFlaggedByMe",e);const{data:r}=await t.http.get(`/api/v5/messages/${encodeURIComponent(e)}/flags`);return r.result},onMessageCreatedMqtt:Dc,onMessageCreatedLocal:xc,onMessageUpdated:Ou,onMessageDeleted:Pu,onMessageFlagged:Qu,onMessageUnflagged:Xu,onMessageFlagCleared:Ju,onMessageReactionAdded:Zu,onMessageReactionRemoved:eh,onMessageFetched:th,getMessage:(e,t)=>pd(e,(e=>{const{data:r}=e;t(Object.assign(Object.assign({},e),{data:r?il.message(e.data):r}))}),"messageId",Jd,[th,Ou,Pu,Qu,Xu,Ju,Zu,eh,xu(dd,"contentId","message"),xu(ud,"contentId","message")]),getMessages:(e,t,r)=>{const{log:n,cache:s}=ve();s||console.log(p);const i=Date.now();n(`getMessages(tmpid: ${i}) > listen`);const a=new dh(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>{ke(l)})),()=>{n(`getMessages(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},observeMessage:(e,t,r="cache_then_server")=>{const{log:n}=ve(),s=Date.now();n(`observeMessage(tmpid: ${s}) > listen`),console.log("observeMessage will be deprecated on 15th November 2022, please use liveMessage instead.");const i=(r,n)=>{var s,i,a;if((null===(s=r.data)||void 0===s?void 0:s.messageId)===e){if(t instanceof Function)return t(r);"onFetch"!==n&&(null===(i=t.onEvent)||void 0===i||i.call(t,n,r)),null===(a=t[n])||void 0===a||a.call(t,r)}},a=[];return a.push(Ou((e=>i({data:il.message(e),loading:!1,origin:"event"},"onUpdate"))),Pu((e=>i({data:il.message(e),loading:!1,origin:"event"},"onDelete"))),xu(dd,"contentId","message")((e=>i({data:il.message(e),loading:!1,origin:"event"},"onUpdate"))),xu(ud,"contentId","message")((e=>i({data:il.message(e),loading:!1,origin:"event"},"onUpdate")))),"no_fetch"!==r&&oe(ie(uh,e),(e=>e.data&&i(e,"onFetch")),ae(r)),()=>{n(`observeMessages(tmpid: ${s}) > dispose`),a.forEach((e=>e()))}},observeMessages:(e,t)=>{const{log:r}=ve(),n=Date.now();r(`observeMessages(tmpid: ${n}) > listen`);const s=[],i=(r,n)=>{var s,i,a;if((null===(s=r.data)||void 0===s?void 0:s.subChannelId)===e){if(t instanceof Function)return t(r);null===(i=t.onEvent)||void 0===i||i.call(t,n,r),null===(a=t[n])||void 0===a||a.call(t,r)}};return s.push(Dc((e=>i({data:il.message(e),loading:!1,origin:"event"},"onCreate"))),xc((e=>i({data:il.message(e),loading:!1,origin:"event"},"onCreate"))),Ou((e=>i({data:il.message(e),loading:!1,origin:"event"},"onUpdate"))),Pu((e=>i({data:il.message(e),loading:!1,origin:"event"},"onDelete"))),xu(dd,"contentId","message")((e=>i({data:il.message(e),loading:!1,origin:"event"},"onCreate"))),xu(ud,"contentId","message")((e=>i({data:il.message(e),loading:!1,origin:"event"},"onCreate")))),()=>{r(`observeMessages(tmpid: ${n}) > dispose`),s.forEach((e=>e()))}},convertFromRaw:Dl,prepareMessagePayload:Ol,convertParams:Pl,convertQueryParams:Ml});class fh extends sh{async getRequest(e,t){var r;const{limit:n=h}=e,s=null!==(r=function(e){var{excludeDefaultSubChannel:t}=e,r=Mo(e,["excludeDefaultSubChannel"]);const n=Object.assign({},r);return void 0!==t&&(n.excludeDefaultMessageFeed=t),n}(Mo(e,["limit"])))&&void 0!==r?r:{},{channelId:i,includeDeleted:a}=s,o=Mo(s,["channelId","includeDeleted"]),l=t?{token:t}:{limit:n},{data:c}=await this.http.get(`/api/v5/message-feeds/channel/${i}`,{params:Object.assign(Object.assign({},o),{isDeleted:Al(a),options:l})});return c}}class ph extends ah{constructor(e,t,r,n){super(e,t),this.notifyChange=r,this.preparePayload=n}async saveToMainDB(e){const t=await this.preparePayload(e),r=ve(),n=r.cache&&Date.now();r.cache&&Oo(t,{cachedAt:n})}appendToQueryStream(e,t,r=!1){var n,s;if(r)Se(this.cacheKey,{data:e.messageFeeds.map((({messageFeedId:e})=>e))});else{const t=null===(n=Ee(this.cacheKey))||void 0===n?void 0:n.data,r=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...r,...e.messageFeeds.map((({messageFeedId:e})=>e))])]}))}}reactor(e){return t=>{var r;const n=null===(r=Ee(this.cacheKey))||void 0===r?void 0:r.data;if(n){if(!Array.isArray(t)){if(this.query.channelId!==t.channelId)return;"onCreate"===e&&(n.data=[...new Set([t.subChannelId,...n.data])]),Se(this.cacheKey,n)}this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class gh extends ch{constructor(e,t){const r=nh(e),n=["subChannel","collection",r];super(new fh(e),r,n,t),this.query=e,this.queryStreamController=new ph(this.query,this.cacheKey,this.notifyChange.bind(this),Nl),this.callback=t.bind(this),this.loadPage(!0)}setup(){var e;(null===(e=Ee(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[]})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:r}){this.queryStreamController.appendToQueryStream(e,t,r)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Bu,action:"onCreate"},{fn:Oc,action:"onCreate"},{fn:Pc,action:"onDelete"},{fn:e=>Mu((async t=>{var r;const n=null===(r=Ee(this.cacheKey))||void 0===r?void 0:r.data;if(!n||!n.data.includes(t.subChannelId))return;const s=ve();if("no-message-preview"!==await s.getMessagePreviewSetting(!1)){const e=ll(t.subChannelId);(null==e?void 0:e.subChannelId)===t.subChannelId&&Se(["messagePreviewSubChannel","get",t.subChannelId],Object.assign(Object.assign({},e),{subChannelName:t.displayName,subChannelUpdatedAt:t.updatedAt}))}e(t)})),action:"onUpdate"},{fn:e=>Dc((async t=>{var r,n;const s=Ee(["subChannel","get",t.subChannelId]);if(!s)return;const i=null===(r=Ee(this.cacheKey))||void 0===r?void 0:r.data;if(!i||!i.data.includes(t.subChannelId))return;const a=ve();if("no-message-preview"===await a.getMessagePreviewSetting(!1))return;fl(t);const o=null===(n=Ee(["subChannel","get",t.subChannelId]))||void 0===n?void 0:n.data;o&&(hl(t.subChannelId,o,{lastActivity:t.createdAt,messagePreviewId:t.messageId}),e(Object.assign(Object.assign({},s.data),{messagePreviewId:t.messageId,subChannelId:t.subChannelId,lastActivity:t.createdAt})))})),action:"onUpdate"},{fn:e=>xc((async t=>{var r,n;const s=Ee(["subChannel","get",t.subChannelId]);if(!s)return;const i=null===(r=Ee(this.cacheKey))||void 0===r?void 0:r.data;if(!i||!i.data.includes(t.subChannelId))return;const a=ve();if("no-message-preview"===await a.getMessagePreviewSetting(!1))return;fl(t);const o=null===(n=Ee(["subChannel","get",t.subChannelId]))||void 0===n?void 0:n.data;o&&(hl(t.subChannelId,o,{lastActivity:t.createdAt,messagePreviewId:t.messageId}),e(Object.assign(Object.assign({},s.data),{messagePreviewId:t.messageId,subChannelId:t.subChannelId,lastActivity:t.createdAt})))})),action:"onUpdate"},{fn:e=>od((t=>{var r;const n=null!==(r=t.map((({feedId:e})=>Ee(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];0!==n.length&&e(n)})),action:"onUpdate"},{fn:xu(ad,"feedId","subChannel"),action:"onUpdate"},{fn:xu((e=>Ou((async t=>{var r;const n=ve();if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;const s=null===(r=Ee(this.cacheKey))||void 0===r?void 0:r.data;s&&s.data.includes(t.subChannelId)&&(pl(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:xu((e=>Pu((async t=>{var r;const n=ve(),s=await n.getMessagePreviewSetting(!1);if("no-message-preview"===s)return;const i=null===(r=Ee(this.cacheKey))||void 0===r?void 0:r.data;i&&i.data.includes(t.subChannelId)&&("message-preview-not-include-deleted"===s?await Kl(t.subChannelId):await pl(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:xu(Uc,"feedId","subChannel"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:r}){var n,s;const i=null===(n=Ee(this.cacheKey))||void 0===n?void 0:n.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>Ee(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(cl))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage(!1,"next"),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:r})}applyFilter(e){let t=e;return this.query.includeDeleted||(t=Ae(e,"isDeleted",!1)),t.sort($e),t}}const mh={},yh=async e=>{const t=await(async e=>{const t=Kl.locally(e);if(t)return t.data.channelId;const{data:r}=await Kl(e);return r.channelId})(e),r=at({channelId:t,subChannelId:e});mh[e]=ht(r)};var vh=Object.freeze({__proto__:null,getSubChannelByIds:Xl,createSubChannel:async e=>{const t=ve();t.log("user/createSubChannel",e);const r=await t.http.post("/api/v5/message-feeds",{channelId:e.channelId,name:e.displayName}),n=await Nl(r.data),s=t.cache&&Date.now();return t.cache&&Oo(n,{cachedAt:s}),Je("message-feed.created",r.data),{data:n.messageFeeds[0],cachedAt:s}},updateSubChannel:async(e,t)=>{const r=ve();r.log("channel/updateSubChannel",e,t);const n=await r.http.put(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{name:t.displayName}),s=await Nl(n.data),i=r.cache&&Date.now();return r.cache&&Oo(s,{cachedAt:i}),Je("message-feed.updated",n.data),{data:s.messageFeeds[0],cachedAt:i}},deleteSubChannel:Nu,hardDeleteSubChannel:async e=>{ve().log("channel/hardDeleteSubChannel",e);return await Nu(e,!0)},softDeleteSubChannel:async e=>{ve().log("channel/softDeleteSubChannel",e);return await Nu(e,!1)},onSubChannelCreated:Oc,onSubChannelUpdated:Mu,onSubChannelDeleted:Pc,getSubChannel:(e,t)=>{const r=ve();let n;return pd(e,(e=>{if(!e.data)return t(e);const r=Object.assign(Object.assign({},e),{data:cl(e.data)}),s=Mo(r,["origin"]);return fd(n,s)?void 0:(n=s,t(r))}),"subChannelId",Kl,[Bu,t=>Mu((async n=>{"no-message-preview"!==await r.getMessagePreviewSetting(!1)&&(gl(n),n.subChannelId===e&&t(n))})),Pc,xu(ad,"feedId","subChannel"),t=>od((r=>{var n;if(!r.find((({feedId:t})=>t===e)))return;const s=null===(n=Ee(["subChannel","get",e]))||void 0===n?void 0:n.data;s&&t(s)})),xu((t=>Dc((async n=>{var s;if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;if(await fl(n),n.subChannelId!==e)return;const i=null===(s=Ee(["subChannel","get",e]))||void 0===s?void 0:s.data;i&&(hl(n.subChannelId,i,{messagePreviewId:n.messageId}),t(n))}))),"subChannelId","subChannel"),xu((t=>xc((async n=>{var s;if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;if(await fl(n),n.subChannelId!==e)return;const i=null===(s=Ee(["subChannel","get",e]))||void 0===s?void 0:s.data;i&&(hl(n.subChannelId,i,{messagePreviewId:n.messageId}),t(n))}))),"subChannelId","subChannel"),xu((t=>Ou((async n=>{"no-message-preview"!==await r.getMessagePreviewSetting(!1)&&n.subChannelId===e&&(pl(n),t(n))}))),"subChannelId","subChannel"),xu((t=>Pu((async n=>{const s=await r.getMessagePreviewSetting(!1);"no-message-preview"!==s&&n.subChannelId===e&&("message-preview-include-deleted"===s&&await pl(n),"message-preview-not-include-deleted"===s&&await Kl(n.subChannelId),t(n))}))),"subChannelId","subChannel"),xu(Uc,"feedId","subChannel")],{forceDispatch:!0})},getSubChannels:(e,t,r)=>{const{log:n,cache:s}=ve(),i=Date.now();n(`getSubChannels(tmpid: ${i}) > listen`),s||console.log(p);const a=new gh(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>{ke(l)})),()=>{n(`getSubChannels(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},markReadEngineOnLoginHandler:Yl,startReading:async e=>{Vl[e]=!0,0===Hl.length&&(Hl.length>0||Hl.push($l((()=>{zl()}))),Ql(e));try{return await(async e=>{const t=ve();t.log("subChannel/startReadingAPI",e);const{data:r}=await t.http.post(`/api/v1/markers/message-feeds/${e}/start-reading`),{userEntityMarkers:n,userFeedMarkers:s,feedMarkers:i,userMarkers:a}=r,o=Bo(n),l=jo(s),c=t.cache&&Date.now();return t.cache&&Oo({userEntityMarkers:o,userFeedMarkers:l,feedMarkers:i,userMarkers:a},{cachedAt:c}),Je("local.feedMarker.fetched",{feedMarkers:i}),Je("local.channelMarker.fetched",{userEntityMarkers:o}),Je("local.subChannelMarker.fetched",{userFeedMarkers:l}),Je("local.userMarker.fetched",{userMarkers:a}),!0})(e)}catch(t){return Vl[e]=!1,!1}},stopReading:e=>(Vl[e]=!1,Hl.forEach((e=>e())),Hl=[],(async e=>{const t=ve();t.log("channel/stopReadingAPI",e);const{data:r}=await t.http.post(`/api/v1/markers/message-feeds/${e}/stop-reading`),{userEntityMarkers:n,userFeedMarkers:s,feedMarkers:i,userMarkers:a}=r,o=Bo(n),l=jo(s),c=t.cache&&Date.now();return t.cache&&Oo({userEntityMarkers:o,userFeedMarkers:l,feedMarkers:i,userMarkers:a},{cachedAt:c}),Je("local.feedMarker.fetched",{feedMarkers:i}),Je("local.channelMarker.fetched",{userEntityMarkers:o}),Je("local.subChannelMarker.fetched",{userFeedMarkers:l}),Je("local.userMarker.fetched",{userMarkers:a}),!0})(e)),startMessageReceiptSync:async e=>(await yh(e),!0),stopMessageReceiptSync:e=>(mh[e]&&mh[e](),!0)});class bh extends sh{async getRequest(e,t){const{limit:r=h,displayName:n,membership:s}=e,i=Mo(e,["limit","displayName","membership"]),a=t?{token:t}:{limit:r},{data:o}=await this.http.get("/api/v3/channels",{params:Object.assign(Object.assign({},i),{keyword:n,filter:s,options:a})});return o}}class wh extends ah{constructor(e,t,r,n,s){super(e,t),this.notifyChange=r,this.preparePayload=n,this.paginationController=s}async saveToMainDB(e){const t=await this.preparePayload(e),r=ve(),n=r.cache&&Date.now();r.cache&&Oo(t,{cachedAt:n})}appendToQueryStream(e,t,r=!1){var n,s;if(r)Se(this.cacheKey,{data:e.channels.map(de("channel"))});else{const t=null===(n=Ee(this.cacheKey))||void 0===n?void 0:n.data,r=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...r,...e.channels.map(de("channel"))])]}))}}reactor(e){return t=>{var r;const n=null===(r=Ee(this.cacheKey))||void 0===r?void 0:r.data;n&&(this.paginationController instanceof bh&&"onCreate"===e&&(n.data=[...new Set([t.channelId,...n.data])],Se(this.cacheKey,n)),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Eh extends lh{async getRequest(e){const{data:t}=await this.http.get("/api/v3/channels/list",{params:Object.assign({},e)});return t}}class Sh extends ch{constructor(e,t){const r=nh(e),n=["channel","collection",r],s=Sh.getPaginationController(e);super(s,r,n,t),this.query=e,this.queryStreamController=new wh(this.query,this.cacheKey,this.notifyChange.bind(this),Tl,s),this.paginationController=s,this.callback=t.bind(this),this.loadPage(!0)}setup(){var e;(null===(e=Ee(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:r}){this.queryStreamController.appendToQueryStream(e,t,r)}startSubscription(){return this.queryStreamController.subscribeRTE(this.getSubscriptions())}notifyChange({origin:e,loading:t,error:r}){var n,s;const i=null===(n=Ee(this.cacheKey))||void 0===n?void 0:n.data;if(!i)return;let a=null!==(s=i.data.map((e=>Ee(["channel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(al))&&void 0!==s?s:[];this.paginationController instanceof bh&&(a=this.applyFilter(a)),(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:this.paginationController instanceof bh?()=>this.loadPage(!1,"next"):void 0,data:a,hasNextPage:this.paginationController instanceof bh&&!!this.paginationController.getNextToken(),loading:t,error:r})}applyFilter(e){const{userId:t}=ve();let r=e;switch(r=Ae(r,"isDeleted",this.query.isDeleted),r=Ae(r,"displayName",this.query.displayName),this.query.types&&(r=r.filter((e=>{var t;return null===(t=this.query.types)||void 0===t?void 0:t.includes(e.type)}))),this.query.tags&&(r=r.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.excludeTags&&(r=r.filter((e=>{var t;return!(null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.excludeTags)||void 0===t?void 0:t.includes(e)})))}))),this.query.membership&&t&&(r=Re(r,this.query.membership,t)),this.query.sortBy){case"firstCreated":r=r.sort(Fe);break;case"lastCreated":r=r.sort(Ne);break;case"displayName":r=r.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Pe);break;default:r=r.sort($e)}return r}shouldAbort(e){var t,r;const n=null===(t=Ee(this.cacheKey))||void 0===t?void 0:t.data;if(!n)return!0;return!(null===(r=null==n?void 0:n.data)||void 0===r?void 0:r.find((t=>t===e)))}static getMessagePreviewSetting(){return ve().getMessagePreviewSetting(!1)}static getPaginationController(e){return e.channelIds&&e.channelIds.length>0?new Eh(e):new bh(e)}getSubscriptions(){const e=[{fn:xu((e=>Dc((t=>{var r;const n=null===(r=Ee(["channel","get",t.channelId]))||void 0===r?void 0:r.data;n&&(Fu(n,{lastActivity:t.createdAt}),e(t))}))),"messageId","channel"),action:"onUpdate"},{fn:xu((e=>xc((t=>{var r;const n=null===(r=Ee(["channel","get",t.channelId]))||void 0===r?void 0:r.data;n&&(Fu(n,{lastActivity:t.createdAt}),e(t))}))),"messageId","channel"),action:"onUpdate"},{fn:dc,action:"onDelete"},{fn:Ec,action:"onUpdate"},{fn:Cc,action:"onMute"},{fn:Sc,action:"onJoin"},{fn:e=>Tc(((t,r)=>{var n,s;const{userId:i}=ve();if("member"===this.query.membership&&i===r.userId){const e=null===(n=Ee(this.cacheKey))||void 0===n?void 0:n.data;Se(this.cacheKey,Object.assign(Object.assign({},e),{data:null!==(s=null==e?void 0:e.data.filter((e=>e!==t.channelId)))&&void 0!==s?s:[]}))}return e(t)})),action:"onLeft"},{fn:kc,action:"onMemberAdded"},{fn:Ac,action:"onMemberRemoved"},{fn:xu(id,"entityId","channel"),action:"onUpdate"},{fn:xu(Uu,"entityId","channel"),action:"onUpdate"},{fn:xu((e=>Dc((async t=>{var r;if("no-message-preview"===await Sh.getMessagePreviewSetting())return;if(fl(t),this.shouldAbort(t.channelId))return;const n=null===(r=Ee(["channel","get",t.channelId]))||void 0===r?void 0:r.data;n&&(Fu(n,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:xu((e=>xc((async t=>{var r;if("no-message-preview"===await Sh.getMessagePreviewSetting())return;if(fl(t),this.shouldAbort(t.channelId))return;const n=null===(r=Ee(["channel","get",t.channelId]))||void 0===r?void 0:r.data;n&&(Fu(n,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:xu((e=>Ou((async t=>{"no-message-preview"!==await Sh.getMessagePreviewSetting()&&(pl(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:xu((e=>Pu((async t=>{const r=await Sh.getMessagePreviewSetting();"no-message-preview"!==r&&("message-preview-include-deleted"===r&&await pl(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===r&&await Du(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:xu((e=>Pc((async t=>{var r;const n=null===(r=Ee(this.cacheKey))||void 0===r?void 0:r.data;if(!n)return;n.data.find((e=>{const r=$o(e);return(null==r?void 0:r.subChannelId)===t.subChannelId}))&&(await Du(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:xu((e=>Mu((async t=>{var r;if("no-message-preview"===await Sh.getMessagePreviewSetting())return;(null===(r=Ee(this.cacheKey))||void 0===r?void 0:r.data)&&(await gl(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:xu(Uc,"entityId","channel"),action:"onUpdate"},{fn:xu(Oc,"channelId","channel"),action:"onUpdate"}];return this.paginationController instanceof sh?[...e,{fn:wc,action:"onCreate"}]:e}}class Th extends sh{async getRequest(e,t){const{limit:r=h}=e,n=Mo(e,["limit"]),s=t?{token:t}:{limit:r},{data:i}=await this.http.get(`/api/v4/channels/${encodeURIComponent(n.channelId)}/users`,{params:Object.assign(Object.assign({},n),{options:s})});return i}}class Ch extends ah{constructor(e,t,r,n){super(e,t),this.notifyChange=r,this.preparePayload=n}async saveToMainDB(e){const t=await this.preparePayload(e),r=ve(),n=r.cache&&Date.now();r.cache&&Oo(t,{cachedAt:n})}appendToQueryStream(e,t,r=!1){var n,s;if(r)Se(this.cacheKey,{data:e.channelUsers.map((({channelId:e,userId:t})=>de("channelUsers")({channelId:e,userId:t})))});else{const t=null===(n=Ee(this.cacheKey))||void 0===n?void 0:n.data,r=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...r,...e.channelUsers.map((({channelId:e,userId:t})=>de("channelUsers")({channelId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var r;if(this.query.channelId!==t.channelId)return;const n=null===(r=Ee(this.cacheKey))||void 0===r?void 0:r.data;if(!n)return;const s=de("channelUsers")({channelId:this.query.channelId,userId:t.userId});"none"===t.membership?n.data=n.data.filter((e=>e!==s)):n.data.includes(s)||(n.data=[s,...n.data]),Se(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class kh extends ch{constructor(e,t){const r=nh(e),n=["channelUsers","collection",r];super(new Th(e),r,n,t),this.query=e,this.queryStreamController=new Ch(this.query,this.cacheKey,this.notifyChange.bind(this),Tl),this.callback=t.bind(this),this.loadPage(!0)}setup(){var e;(null===(e=Ee(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:r}){this.queryStreamController.appendToQueryStream(e,t,r)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Sc,action:"onJoin"},{fn:Tc,action:"onLeft"},{fn:kc,action:"onMemberAdded"},{fn:Ac,action:"onMemberRemoved"},{fn:uc,action:"onChannelMemberBanned"},{fn:Ic,action:"onChannelMemberUnbanned"},{fn:_c,action:"onChannelMemberRoleAdded"},{fn:Rc,action:"onChannelMemberRoleRemoved"}])}notifyChange({origin:e,loading:t,error:r}){var n,s;const i=null===(n=Ee(this.cacheKey))||void 0===n?void 0:n.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>Ee(["channelUsers","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage(!1,"next"),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:r})}applyFilter(e){let t=_e(e,"roles",this.query.roles);this.query.memberships&&(t=t.filter((e=>{var t,r;return!(!(null===(t=this.query.memberships)||void 0===t?void 0:t.includes("muted"))||!e.isMuted)||"none"!==e.membership&&(null===(r=this.query.memberships)||void 0===r?void 0:r.includes(e.membership))}))),this.query.search&&(console.warn("`search` param will be deprecated in the next major release. If you want to search channel members by displayName, Please use `searchMembers()` instead."),t=Oe(t,this.query.search));const r=this.query.sortBy?this.query.sortBy:"lastCreated";return t=t.sort("lastCreated"===r?Ne:Fe),t}}const Ah=(e,t,r)=>{const{log:n,cache:s}=ve();s||console.log(p);const i=Date.now();n(`getMembers(tmpid: ${i}) > listen`);const a=new kh(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>{ke(l)})),()=>{n(`getMembers(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}};var Ih=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const r=ve();r.log("channel/addMembers",e,t);const{data:n}=await r.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users`,{channelId:e,userIds:t});t.forEach((e=>Je("channel.membersAdded",Object.assign(Object.assign({},n),{channelUsers:n.channelUsers.filter((t=>t.userId===e))}))));const s=await Tl(n);r.cache&&Oo(s);const{channelUsers:i}=s;return!!i.find((t=>t.channelId===e&&"member"===t.membership))},removeMembers:async(e,t)=>{const r=ve();r.log("channel/removeMembers",e,t);const{data:n}=await r.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users`,{data:{channelId:e,userIds:t}});t.forEach((e=>Je("channel.membersRemoved",Object.assign(Object.assign({},n),{channelUsers:n.channelUsers.filter((t=>t.userId===e))}))));const s=await Tl(n);r.cache&&Oo(s);const{channelUsers:i}=s;return!!i.find((t=>t.channelId===e&&"member"!==t.membership))},applyFilter:(e,t)=>{let r=_e(e,"roles",t.roles);t.memberships&&(r=r.filter((e=>!(!t.memberships.includes("muted")||!e.isMuted)||t.memberships.includes(e.membership)))),t.search&&(console.warn("`search` param will be deprecated in the next major release. If you want to search channel members by displayName, Please use `searchMembers()` instead."),r=Oe(r,t.search));const n=t.sortBy?t.sortBy:"lastCreated";return r=r.sort("lastCreated"===n?Ne:Fe),r},getMembers:Ah,searchMembers:(e,t,r)=>Ah(e,t)});var _h=Object.freeze({__proto__:null,addRole:async(e,t,r)=>{const n=ve();n.log("channel/addRole",e,t,r);const{data:s}=await n.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{channelId:e,role:t,userIds:r}),i=await Tl(s);n.cache&&Oo(i),Je("local.channel-moderator.role-added",i);const{channelUsers:a}=i;return!!a.find((r=>r.channelId===e&&r.roles.includes(t)))},removeRole:async(e,t,r)=>{const n=ve();n.log("channel/removeRole",e,t,r);const{data:s}=await n.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{data:{channelId:e,role:t,userIds:r}}),i=await Tl(s);n.cache&&Oo(i),Je("local.channel-moderator.role-removed",i);const{channelUsers:a}=i;return!!a.find((r=>r.channelId===e&&!r.roles.includes(t)))},banMembers:async(e,t)=>{const r=ve();r.log("channel/banMembers",{userIds:t,channelId:e});const{data:n}=await r.http.put(`/api/v3/channels/${e}/users/ban`,{userIds:t}),s=await Tl(n),{channelUsers:i}=s,a=r.cache&&Date.now();return r.cache&&Oo(s,{cachedAt:a}),{data:null==i?void 0:i.filter((e=>"banned"===e.membership)),cachedAt:a}},unbanMembers:async(e,t)=>{const r=ve();r.log("channel/unbanMembers",{userIds:t,channelId:e});const{data:n}=await r.http.put(`/api/v3/channels/${encodeURIComponent(e)}/users/unban`,{userIds:t}),s=await Tl(n),i=r.cache&&Date.now();r.cache&&Oo(s,{cachedAt:i});const{channelUsers:a}=s;return{data:null==a?void 0:a.filter((e=>"member"===e.membership)),cachedAt:i}},muteMembers:async(e,t,r=-1)=>{const n=ve();n.log("channel/muteMembers",{userIds:t,channelId:e,mutePeriod:r});const{data:s}=await n.http.put(`/api/v2/channel/${e}/users/mute`,{userIds:t,mutePeriod:-1===r?r:1e3*r}),{success:i}=s;return i},unmuteMembers:async(e,t)=>{const r=ve();r.log("channel/unmuteMembers",{userIds:t,channelId:e});const{data:n}=await r.http.put(`/api/v2/channel/${encodeURIComponent(e)}/users/mute`,{userIds:t,mutePeriod:0}),{success:s}=n;return s}}),Rh=Object.freeze({__proto__:null,Membership:Ih,Moderation:_h,getChannelByIds:Cl,createChannel:async e=>{const t=ve();let r;if(t.log("user/createChannel",e),"conversation"===(null==e?void 0:e.type))r=await t.http.post("/api/v3/channels/conversation",Object.assign(Object.assign({},e),{isDistinct:!0}));else{const{isPublic:n}=e,s=Mo(e,["isPublic"]);r=await t.http.post("/api/v3/channels",Object.assign(Object.assign({},s),{isPublic:"community"===(null==e?void 0:e.type)?n:void 0}))}const n=await Tl(r.data),s=t.cache&&Date.now();t.cache&&Oo(n,{cachedAt:s});const{channels:i}=n;return{data:i[0],cachedAt:s}},updateChannel:async(e,t)=>{const r=ve();r.log("channel/updateChannel",e,t);const{data:n}=await r.http.put(`/api/v3/channels/${encodeURIComponent(e)}`,t),s=await Tl(n),i=r.cache&&Date.now();r.cache&&Oo(s,{cachedAt:i});const{channels:a}=s;return{data:a.find((t=>t.channelId===e)),cachedAt:i}},deleteChannel:async e=>{const t=ve();t.log("channel/deleteChannel",e),await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}`);return(await Du(e)).data},joinChannel:async e=>{const t=ve();t.log("channel/joinChannel",e);const{data:r}=await t.http.post(`/api/v3/channels/${encodeURIComponent(e)}/join`),n=await Tl(r);t.cache&&Oo(n);const{channelUsers:s}=n;return!!s.find((t=>t.channelId===e&&"member"===t.membership))},leaveChannel:async e=>{const t=ve();t.log("channel/leaveChannel",e);const{data:r}=await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/leave`),n=await Tl(r);t.cache&&Oo(n);const{channelUsers:s}=n;return!!s.find((t=>t.channelId===e&&"member"!==t.membership))},muteChannel:async(e,t=-1)=>{const r=ve();if(r.log("channel/muteChannel",e),-1!==t&&t<0)throw new fe("Mute Period can only be positive numbers or -1(mute forever)",800110,"error");const{data:n}=await r.http.put(`/api/v2/channel/${encodeURIComponent(e)}/mute`,{mutePeriod:t}),{success:s}=n;return s},unmuteChannel:async e=>{const t=ve();t.log("channel/unmuteChannel",e);const{data:r}=await t.http.put(`/api/v2/channel/${encodeURIComponent(e)}/mute`,{mutePeriod:0}),{success:n}=r;return n},markAsRead:async e=>{const t=ve();t.log("channel/markAsRead",e);const{data:r}=await t.http.put(`/api/v1/markers/channels/${e}/mark-read`),{userMarkers:n,userEntityMarkers:s,userFeedMarkers:i}=r,a=Mo(r,["userMarkers","userEntityMarkers","userFeedMarkers"]),o=t.cache&&Date.now(),l=Bo(s),c=jo(i);return t.cache&&Oo(Object.assign({userMarkers:n,userEntityMarkers:l,userFeedMarkers:c},a),{cachedAt:o}),Je("local.channelMarker.updated",{userEntityMarkers:l}),Je("local.subChannelMarker.updated",{userFeedMarkers:c}),!0},onChannelCreated:wc,onChannelUpdated:Ec,onChannelDeleted:dc,onChannelJoined:Sc,onChannelLeft:Tc,onChannelMuted:Cc,onChannelMemberAdded:kc,onChannelMemberRemoved:Ac,onChannelMemberBanned:uc,onChannelMemberUnbanned:Ic,onChannelMemberRoleAdded:_c,onChannelMemberRoleRemoved:Rc,observeChannel:(e,t)=>{const{log:r}=ve(),n=Date.now();r(`observeChannel(tmpid: ${n}) > listen`);const s=(r,n)=>{var s,i,a;if((null===(s=r.data)||void 0===s?void 0:s.channelId)===e){if(t instanceof Function)return t(r);"onFetch"!==n&&(null===(i=t.onEvent)||void 0===i||i.call(t,n,r)),null===(a=t[n])||void 0===a||a.call(t,r)}},i=[];return i.push(Ec((e=>s({data:e,loading:!1,origin:"event"},"onUpdate"))),dc((e=>s({data:e,loading:!1,origin:"event"},"onDelete"))),Sc((e=>s({data:e,loading:!1,origin:"event"},"onJoin"))),Tc((e=>s({data:e,loading:!1,origin:"event"},"onLeft"))),Cc((e=>s({data:e,loading:!1,origin:"event"},"onMute"))),kc((e=>s({data:e,loading:!1,origin:"event"},"onMemberAdded"))),Ac((e=>s({data:e,loading:!1,origin:"event"},"onMemberRemoved"))),xu(id,"entityId","channel")((e=>s({data:e,loading:!1,origin:"event"},"onUpdate")))),oe(ie(Du,e),(e=>e.data&&s(e,"onFetch"))),()=>{r(`observeChannel(tmpid: ${n}) > dispose`),i.forEach((e=>e()))}},observeChannels:e=>{const{log:t}=ve(),r=Date.now();t(`observeChannels(tmpid: ${r}) > listen`);const n=[],s=(t,r)=>{var n,s;if(e instanceof Function)return e(t);null===(n=e.onEvent)||void 0===n||n.call(e,r,t),null===(s=e[r])||void 0===s||s.call(e,t)};return n.push(wc((e=>s(e,"onCreate"))),Ec((e=>s(e,"onUpdate"))),dc((e=>s(e,"onDelete"))),Sc((e=>s(e,"onJoin"))),Tc((e=>s(e,"onLeft"))),Cc((e=>s(e,"onMute"))),kc((e=>s(e,"onMemberAdded"))),Ac((e=>s(e,"onMemberRemoved"))),xu(id,"entityId","channel")((e=>s(e,"onUpdate")))),()=>{t(`observeChannels(tmpid: ${r}) > dispose`),n.forEach((e=>e()))}},getChannel:(e,t)=>{const r=ve();let n;return pd(e,(async e=>{if(!e.data)return t(e);const r=Object.assign(Object.assign({},e),{data:al(e.data)}),s=Mo(r,["origin"]);return fd(n,s)?void 0:(n=s,t(r))}),"channelId",Du,[Ec,dc,Sc,Tc,kc,Ac,uc,Ic,Cc,xu(id,"entityId","channel"),xu(Uu,"entityId","channel"),xu((t=>Dc((async n=>{var s;if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;if(await fl(n),n.channelId!==e)return;const i=null===(s=Ee(["channel","get",e]))||void 0===s?void 0:s.data;i&&(Fu(i,{messagePreviewId:n.messageId}),t(n))}))),"channelId","channel"),xu((t=>xc((async n=>{var s;if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;if(await fl(n),n.channelId!==e)return;const i=null===(s=Ee(["channel","get",e]))||void 0===s?void 0:s.data;i&&(Fu(i,{messagePreviewId:n.messageId}),t(n))}))),"channelId","channel"),xu((t=>Ou((async n=>{var s;const i=null===(s=Ee(["channel","get",e]))||void 0===s?void 0:s.data;if(!i||i.messagePreviewId!==n.messageId)return;"no-message-preview"!==await r.getMessagePreviewSetting(!1)&&(await pl(n),t(n))}))),"channelId","channel"),xu((t=>Pu((async n=>{var s;const i=null===(s=Ee(["channel","get",e]))||void 0===s?void 0:s.data;if(!i||i.messagePreviewId!==n.messageId)return;const a=await r.getMessagePreviewSetting(!1);"no-message-preview"!==a&&("message-preview-not-include-deleted"===a?(ke(["messagePreviewChannel","get",e]),await Du(n.channelId)):await pl(n),t(n))}))),"channelId","channel"),xu((e=>Pc((async t=>{var n,s;const{channelId:i,subChannelId:a}=t,o=null===(n=Ee(["messagePreviewChannel","get",i]))||void 0===n?void 0:n.data;if(!o||o.subChannelId!==a)return;if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;await Du(i);(null===(s=Ee(["channel","get",i]))||void 0===s?void 0:s.data)&&e(t)}))),"channelId","channel"),xu((t=>Mu((async n=>{var s,i;if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;gl(n);const a=null===(s=Ee(["messagePreviewChannel","get",e]))||void 0===s?void 0:s.data;if(!a||a.subChannelId!==n.subChannelId)return;(null===(i=Ee(["channel","get",e]))||void 0===i?void 0:i.data)&&t(n)}))),"channelId","channel"),xu(Oc,"channelId","channel"),xu(Uc,"entityId","channel")],{forceDispatch:!0})},getChannels:(e,t,r)=>{const{log:n,cache:s,userId:i}=ve();s||console.log(p);const a=Date.now();n(`getChannels(tmpid: ${a}) > listen`);const o=new Sh(e,t),l=o.startSubscription(),c=o.getCacheKey();return l.push((()=>{ke(c)})),()=>{n(`getChannels(tmpid: ${a}) > dispose`),l.forEach((e=>e()))}},MARKER_INCLUDED_CHANNEL_TYPE:bl,isUnreadCountSupport:wl,convertFromRaw:El,preUpdateChannelCache:Sl,prepareChannelPayload:Tl});function Lh(e,t){return e.map((e=>{const r=t.some((t=>function(e,t){const{userId:r}=Ke();return e.communityId===t.communityId&&t.userId===r}(e,t)&&"none"!==t.communityMembership));return Object.assign(Object.assign({},e),{isJoined:r})}))}const Dh=e=>{var t;return null!==(t=Object.keys(a).find((t=>e.needApprovalOnPostCreation===a[t].needApprovalOnPostCreation&&e.onlyAdminCanPost===a[t].onlyAdminCanPost)))&&void 0!==t?t:o},xh=e=>{const t=e.communities.map((e=>{var{needApprovalOnPostCreation:t,onlyAdminCanPost:r}=e,n=Mo(e,["needApprovalOnPostCreation","onlyAdminCanPost"]);return Object.assign({postSetting:Dh({needApprovalOnPostCreation:t,onlyAdminCanPost:r})},n)})),r=Fo(e.communityUsers),n=Lh(t,r);return Object.assign(Object.assign({},e),{communities:n,communityUsers:r})},Oh=e=>{const{postSetting:t,storySetting:r}=e,n=Mo(e,["postSetting","storySetting"]);return Object.assign(Object.assign(Object.assign({},n),t?a[t]:void 0),{allowCommentInStory:!1!==(null==r?void 0:r.enableComment)})},Ph=async e=>{const t=ve();t.log("community/getCommunities",e);const{data:r}=await t.http.get("/api/v3/communities/list",{params:{communityIds:e}}),n=xh(r),s=t.cache&&Date.now();return t.cache&&Oo(n,{cachedAt:s}),{data:n.communities,cachedAt:s}};Ph.locally=e=>{var t;const r=ve();if(r.log("community/getCommunities.locally",e),!r.cache)return;const n=e.map((e=>Ee(["community","get",e]))).filter(Boolean),s=n.map((({data:e})=>e)),i=null===(t=n.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==n?void 0:n.length)<e.length?void 0:{data:s,cachedAt:i.cachedAt}};const Mh=async e=>{const t=ve();t.log("community/getCommunity",e);const{data:r}=await t.http.get(`/api/v3/communities/${e}`),n=xh(r),s=t.cache&&Date.now();t.cache&&Oo(n,{cachedAt:s});const{communities:i}=n;return{data:i.find((t=>t.communityId===e)),cachedAt:s}};Mh.locally=e=>{const t=ve();if(t.log("community/getCommunity.locally",e),!t.cache)return;const r=Ee(["community","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const Fh=async e=>{const t=ve();t.log("channel/getTopTrendingCommunities",e);const{limit:r=5}=null!=e?e:{},{data:n}=await t.http.get("/api/v3/communities/top-trending",{params:{options:{limit:r}}}),s=xh(n),{communities:i}=s,a=t.cache&&Date.now();if(t.cache){Oo(s,{cachedAt:a});Se(["community","top-trending",{params:{options:{limit:r}}}],{communities:i.map(de("community"))})}return{data:i,cachedAt:a}};Fh.locally=e=>{var t,r;const n=ve();if(n.log("community/getTopTrendingCommunities.locally",e),!n.cache)return;const{limit:s=5}=null!=e?e:{},i=["community","top-trending",{params:{options:{limit:s}}}],{data:a,cachedAt:o}=null!==(t=Ee(i))&&void 0!==t?t:{};if(!(null==a?void 0:a.communities.length))return;const l=a.communities.map((e=>Ee(["community","get",e]))).filter(Boolean).map((({data:e})=>e));return l.length===(null===(r=null==a?void 0:a.communities)||void 0===r?void 0:r.length)?{data:l,cachedAt:o}:void 0};const Uh=(e,t)=>{const r=ve();return Xe(r,e,e,(e=>{const n=xh(e);if(r.cache){Oo(n);const e=Ee(["community","get",n.communities[0].communityId]);t(e.data)}else t(n.communities[0])}))},Nh=e=>Uh("community.created",e),Bh=e=>Uh("community.updated",e),jh=e=>Uh("community.deleted",e);function $h(e){return null!=e}function qh(e,t,r){return!!e.permissions.some((e=>e===r))||t.users.find((t=>t.userId===e.userId)).permissions.some((e=>e===r))}function Kh(e,t){return"community.joined"===e||"community.left"===e?t.communityUsers:"community.userRemoved"===e?t.communityUsers.filter((e=>"none"===e.communityMembership)):"community.userBanned"===e?t.communityUsers.filter((e=>"banned"===e.communityMembership)):"community.userUnbanned"===e?t.communityUsers.filter((e=>!qh(e,t,"BAN_COMMUNITY_USER"))):t.communityUsers.filter((e=>!qh(e,t,"ADD_COMMUNITY_USER")))}const Gh=(e,t)=>{const r=ve();return Xe(r,e,e,(n=>{const s=xh(n),{communities:i,communityUsers:a}=s,o=Lh(i,a);if(s.communities=o,r.cache){Oo(s);const r=Ee(["community","get",s.communities[0].communityId]),n=Kh(e,s).map((e=>{const t=Ee(["communityUsers","get",de("communityUsers")(e)]);return null==t?void 0:t.data})).filter($h);t(r.data,n)}else t(s.communities[0],Kh(e,s))}))},Hh=e=>Gh("community.userAdded",e),Vh=e=>Gh("community.userRemoved",e),zh=e=>Gh("community.userBanned",e),Wh=e=>Gh("community.userChanged",e),Yh=e=>Gh("community.userUnbanned",e),Qh=e=>Gh("community.roleAdded",e),Xh=e=>Gh("community.roleRemoved",e),Jh=e=>Gh("community.joined",e),Zh=e=>Gh("community.left",e),ef=async e=>{const t=ve();t.log("channel/queryCommunities",e);const r=null!=e?e:{},{page:n,limit:s=10}=r,i=Mo(r,["page","limit"]),a=null!=i?i:{},{displayName:o,membership:l,includeDeleted:c}=a,d=Mo(a,["displayName","membership","includeDeleted"]),u=n?{token:n}:s?{limit:s}:void 0,{data:h}=await t.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},d),{isDeleted:Al(c),keyword:o,filter:l,options:u})}),{paging:f}=h,p=Mo(h,["paging"]),g=xh(p),{communities:m}=g,y=t.cache&&Date.now();if(t.cache){Oo(g,{cachedAt:y});const e=["community","query",Object.assign(Object.assign({},i),{options:u})];Se(e,{communities:m.map(de("community")),paging:f})}return{data:m,cachedAt:y,paging:f}},tf=async e=>{const t=ve();t.log("community/getTrendingCommunities",e);const{limit:r=h}=null!=e?e:{},{data:n}=await t.http.get("/api/v3/communities/top-trending",{params:{options:{limit:r}}}),s=xh(n),{communities:i}=s,a=t.cache&&Date.now();return t.cache&&Oo(s,{cachedAt:a}),{data:i,cachedAt:a}},rf=(e,t,r)=>{let n=e;n=Ae(n,"displayName",t.displayName),t.includeDeleted||(n=Ae(n,"isDeleted",!1)),t.categoryId&&(n=n.filter((e=>{var r;return null===(r=e.categoryIds)||void 0===r?void 0:r.includes(t.categoryId)}))),t.tags&&(n=n.filter((e=>{var r;return null===(r=e.tags)||void 0===r?void 0:r.some((e=>{var r;return null===(r=t.tags)||void 0===r?void 0:r.includes(e)}))}))),t.membership&&r&&(n=De(n,t.membership,r));const s=t.sortBy||"lastCreated";return"lastCreated"!==s&&"firstCreated"!==s||(n=n.sort("lastCreated"===s?Ne:Fe)),"displayName"===s&&(n=n.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Pe)),n},nf=async e=>{const t=ve();t.log("community/getRecommendedCommunities",e);const{limit:r=h}=null!=e?e:{},{data:n}=await t.http.get("/api/v3/communities/recommended",{params:{options:{limit:r}}}),s=xh(n),{communities:i}=s,a=t.cache&&Date.now();return t.cache&&Oo(s,{cachedAt:a}),{data:i,cachedAt:a}};var sf=Object.freeze({__proto__:null,addRoles:async(e,t,r)=>{const n=ve();n.log("community/moderation/addRoles",e,t,r);const{data:s}=await n.http.post(`/api/v4/communities/${e}/users/roles`,{communityId:e,roles:t,userIds:r}),i=Uo(s,"communityUsers");n.cache&&Oo(i);const{communityUsers:a}=i;return!!a.find((r=>r.communityId===e&&t.some((e=>r.roles.includes(e)))))},removeRoles:async(e,t,r)=>{const n=ve();n.log("community/moderation/removeRoles",e,t,r);const{data:s}=await n.http.delete(`/api/v4/communities/${e}/users/roles`,{data:{communityId:e,roles:t,userIds:r}}),i=Uo(s,"communityUsers");n.cache&&Oo(i);const{communityUsers:a}=i;return!!a.find((r=>r.communityId===e&&!t.some((e=>r.roles.includes(e)))))},banMembers:async(e,t)=>{const r=ve();r.log("community/banMembers",{userIds:t,communityId:e});const{data:n}=await r.http.put(`/api/v3/communities/${e}/users/ban`,{userIds:t}),s=Uo(n,"communityUsers"),i=r.cache&&Date.now();r.cache&&Oo(s,{cachedAt:i});const{communityUsers:a}=s;return{data:a.filter((e=>t.includes(e.userId))),cachedAt:i}},unbanMembers:async(e,t)=>{const r=ve();r.log("community/unbanMembers",{userIds:t,communityId:e});const{data:n}=await r.http.put(`/api/v3/communities/${e}/users/unban`,{userIds:t}),s=Uo(n,"communityUsers"),i=r.cache&&Date.now();r.cache&&Oo(s,{cachedAt:i});const{communityUsers:a}=s;return{data:a.filter((e=>t.includes(e.userId))),cachedAt:i}}});const af=async e=>{const t=ve();t.log("community/queryCommunityMembers",e);const r=null!=e?e:{},{page:n,limit:s}=r,i=Mo(r,["page","limit"]),a=n?{token:n}:s?{limit:s}:void 0,{data:o}=await t.http.get(`/api/v3/communities/${i.communityId}/users`,{params:Object.assign(Object.assign({},i),{options:a})}),{paging:l}=o,c=Mo(o,["paging"]),d=Uo(c,"communityUsers"),{communityUsers:u}=d,h=t.cache&&Date.now();if(t.cache){Oo(d,{cachedAt:h});const e=["communityUsers","query",Object.assign(Object.assign({},i),{options:a})];Se(e,{communityUsers:u.map((({communityId:e,userId:t})=>de("communityUsers")({communityId:e,userId:t}))),paging:l})}return{data:u,cachedAt:h,paging:l}};af.locally=e=>{var t,r;const n=ve();if(n.log("community/queryCommunityMembers",e),!n.cache)return;const s=null!=e?e:{},{page:i,limit:a}=s,o=Mo(s,["page","limit"]),l=i?{token:i}:a?{limit:a}:void 0,c=["communityUsers","query",Object.assign(Object.assign({},o),{options:l})],{data:d,cachedAt:u}=null!==(t=Ee(c))&&void 0!==t?t:{};if(!(null==d?void 0:d.communityUsers.length))return;const h=d.communityUsers.map((e=>Ee(["communityUsers","get",e]))).filter(Boolean).map((({data:e})=>e)),{paging:f}=d;return h.length===(null===(r=null==d?void 0:d.communityUsers)||void 0===r?void 0:r.length)?{data:h,cachedAt:u,paging:f}:void 0};const of=(e,t)=>{let r=_e(e,"roles",t.roles);t.memberships&&(r=r.filter((({communityMembership:e})=>t.memberships.includes(e)))),t.search&&(r=Oe(r,t.search));const n=t.sortBy?t.sortBy:"lastCreated";return r=r.sort("lastCreated"===n?Ne:Fe),r};var lf=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const r=ve();r.log("community/moderation/addMembers",e,t);const{data:n}=await r.http.post(`/api/v3/communities/${e}/users`,{communityId:e,userIds:t});Je("community.userAdded",n);const s=Uo(n,"communityUsers");r.cache&&Oo(s);const{communityUsers:i}=s;return!!i.find((t=>t.communityId===e&&"member"===t.communityMembership))},removeMembers:async(e,t)=>{const r=ve();r.log("community/moderation/removeMembers",e,t);const{data:n}=await r.http.delete(`/api/v3/communities/${e}/users`,{data:{communityId:e,userIds:t}});Je("community.userRemoved",n);const s=Uo(n,"communityUsers");r.cache&&Oo(s);const{communityUsers:i}=s;return!!i.find((t=>t.communityId===e&&"member"!==t.communityMembership))},applyFilter:of,getMembers:(e,t,r)=>{const{log:n,cache:s}=ve();s||console.log(p);const i=Date.now();n(`getMembers(tmpid: ${i}) > listen`);const{limit:a}=e,o=Mo(e,["limit"]),l=null!=a?a:h,{policy:c=f}=null!=r?r:{},d=[],u=["communityUsers","collection",o],g=["communityUsers","collection",{communityId:e.communityId}],m=(r,n=!1)=>{var s,i;const a=null!==(s=r.data.map((e=>Ee(["communityUsers","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==s?s:[];t({onNextPage:v,data:n?of(a,e):a,hasNextPage:!!(null===(i=r.params)||void 0===i?void 0:i.page),loading:r.loading,error:r.error})},y=t=>(t,r)=>{var n;const s=null===(n=Ee(u))||void 0===n?void 0:n.data;if(!s)return;const i=r.map((t=>{if(e.communityId!==t.communityId)return;return de("communityUsers")({communityId:e.communityId,userId:t.userId})})).filter($h);s.data=[...new Set([...i,...s.data])],Se(u,s),Se(g,s),m(s,!0)},v=(e=!1)=>{var t,r;const n=null===(t=Ee(u))||void 0===t?void 0:t.data,s=null!==(r=null==n?void 0:n.data)&&void 0!==r?r:[];if(!e&&s.length>0&&!(null==n?void 0:n.params.page))return;const i=ie(af,Object.assign(Object.assign({},o),{limit:e?l:void 0,page:e||null==n?void 0:n.params.page}));oe(i,(({data:e,error:t,loading:r,paging:n})=>{const i={loading:r,error:t,params:{page:null==n?void 0:n.next},data:s};e&&(i.data=[...new Set([...s,...e.map(de("communityUsers"))])]),Se(u,i),Se(g,i),m(i)}),ae(c))};return d.push(Zh(y()),Jh(y()),zh(y()),Yh(y()),Wh(y()),Qh(y()),Xh(y())),v(!0),()=>{n(`getMembers(tmpid: ${i}) > dispose`),d.forEach((e=>e()))}},onCommunityUserAdded:Hh,onCommunityUserRemoved:Vh,onCommunityUserBanned:zh,onCommunityUserChanged:Wh,onCommunityUserUnbanned:Yh,onCommunityUserRoleAdded:Qh,onCommunityUserRoleRemoved:Xh,onCommunityJoined:Jh,onCommunityLeft:Zh}),cf=Object.freeze({__proto__:null,Moderation:sf,Membership:lf,getCommunityByIds:Ph,createCommunity:async e=>{const t=ve();t.log("user/createCommunity",e);const{data:r}=await t.http.post("/api/v3/communities/",Oh(e));Je("community.created",r);const n=xh(r),s=t.cache&&Date.now();t.cache&&Oo(n,{cachedAt:s});const{communities:i}=n;return{data:i[0],cachedAt:s}},updateCommunity:async(e,t)=>{const r=ve();r.log("community/updateCommunity",e,t);const{data:n}=await r.http.put(`/api/v3/communities/${e}`,Oh(t));Je("community.updated",n);const s=xh(n),i=r.cache&&Date.now();r.cache&&Oo(s,{cachedAt:i});const{communities:a}=s;return{data:a.find((t=>t.communityId===e)),cachedAt:i}},deleteCommunity:async e=>{const t=ve();t.log("community/deleteCommunity",e),await t.http.delete(`/api/v3/communities/${e}`);const r=await Mh(e);return Je("community.deleted",{communities:[r.data],categories:[],communityUsers:[],feeds:[],files:[],users:[]}),r.data},joinCommunity:async e=>{const t=ve();t.log("community/joinCommunity",e);const{data:r}=await t.http.post(`/api/v3/communities/${e}/join`);Je("community.joined",r);const n=xh(r),s=t.cache&&Date.now();t.cache&&Oo(n,{cachedAt:s});const{communityUsers:i}=n;return!!i.find((t=>t.communityId===e&&"member"===t.communityMembership))},leaveCommunity:async e=>{const t=ve();t.log("community/leaveCommunity",e);const{data:r}=await t.http.delete(`/api/v3/communities/${e}/leave`);Je("community.left",r);const n=xh(r),s=t.cache&&Date.now();t.cache&&Oo(n,{cachedAt:s});const{communityUsers:i}=n;return!!i.find((t=>t.communityId===e&&"member"!==t.communityMembership))},getTopTrendingCommunities:Fh,onCommunityCreated:Nh,onCommunityUpdated:Bh,onCommunityDeleted:jh,observeCommunity:(e,t)=>{const{log:r}=ve(),n=Date.now();r(`observeCommunity(tmpid: ${n}) > listen`);const s=(e,r)=>{var n,s;if(t instanceof Function)return t(e);"onFetch"!==r&&(null===(n=t.onEvent)||void 0===n||n.call(t,r,e)),null===(s=t[r])||void 0===s||s.call(t,e)},i=(t,r)=>{var n;(null===(n=t.data)||void 0===n?void 0:n.communityId)===e&&s(t,r)},a=[];return a.push(Bh((e=>i({data:e,loading:!1,origin:"event"},"onUpdate"))),jh((e=>i({data:e,loading:!1,origin:"event"},"onDelete"))),Jh((e=>i({data:e,loading:!1,origin:"event"},"onJoin"))),Zh((e=>i({data:e,loading:!1,origin:"event"},"onLeft"))),Hh((e=>i({data:e,loading:!1,origin:"event"},"onUserAdded"))),Vh((e=>i({data:e,loading:!1,origin:"event"},"onUserRemoved"))),zh((e=>i({data:e,loading:!1,origin:"event"},"onUserBanned"))),Yh((e=>i({data:e,loading:!1,origin:"event"},"onUserUnbanned")))),oe(ie(Mh,e),(e=>(e.data||e.error)&&s(e,"onFetch"))),()=>{r(`observeCommunity(tmpid: ${n}) > dispose`),a.forEach((e=>e()))}},getCommunities:(e,t,r)=>{const{log:n,cache:s,userId:i}=ve();s||console.log(p);const a=Date.now();n(`getCommunities(tmpid: ${a}) > listen`);const{limit:o}=e,l=Mo(e,["limit"]),c=null!=o?o:h,{policy:d=f}=null!=r?r:{},u=[],g=["community","collection",l],m=r=>{var n,s;let a=null!==(n=r.data.map((e=>Ee(["community","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];a=Ie(a,"displayName",e.displayName),e.includeDeleted||(a=Ae(a,"isDeleted",!1)),e.categoryId&&(a=a.filter((t=>{var r;return null===(r=t.categoryIds)||void 0===r?void 0:r.includes(e.categoryId)}))),e.tags&&(a=a.filter((t=>{var r;return null===(r=t.tags)||void 0===r?void 0:r.some((t=>{var r;return null===(r=e.tags)||void 0===r?void 0:r.includes(t)}))}))),e.membership&&i&&(a=De(a,e.membership,i));const o=e.sortBy||"lastCreated";"lastCreated"!==o&&"firstCreated"!==o||(a=a.sort("lastCreated"===o?Ne:Fe)),"displayName"===o&&(a=a.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Pe)),t({onNextPage:v,data:a,hasNextPage:!!(null===(s=r.params)||void 0===s?void 0:s.page),loading:r.loading,error:r.error})},y=e=>e=>{var t;const r=null===(t=Ee(g))||void 0===t?void 0:t.data;r&&(r.data=[...new Set([e.communityId,...r.data])],Se(g,r),m(r))},v=(e=!1)=>{var t,r;const n=null===(t=Ee(g))||void 0===t?void 0:t.data,s=null!==(r=null==n?void 0:n.data)&&void 0!==r?r:[];if(!e&&s.length>0&&!(null==n?void 0:n.params.page))return;const i=ie(ef,Object.assign(Object.assign({},l),{limit:e?c:void 0,page:e||null==n?void 0:n.params.page}));oe(i,(({data:t,error:r,loading:n,paging:i})=>{const a={loading:n,error:r,params:{page:null==i?void 0:i.next},data:s};t&&(a.data=e?t.map(de("community")):[...new Set([...s,...t.map(de("community"))])]),Se(g,a),m(a)}),ae(d,b))};return u.push(Nh(y()),jh(y()),Bh(y()),Jh(y()),Zh(y()),Wh(y())),v(!0),u.push((()=>ke(g))),()=>{n(`getCommunities(tmpid: ${a}) > dispose`),u.forEach((e=>e()))}},getCommunity:(e,t)=>pd(e,t,"communityId",Mh,[Bh,jh,Jh,Zh,zh,Yh,Wh]),getTrendingCommunities:(e,t,r)=>{const{log:n,cache:s,userId:i}=ve();s||console.log(p);const a=Date.now();n(`getTrendingCommunities(tmpid: ${a}) > listen`);const{limit:o}=e,l=null!=o?o:h,{policy:c=f}=null!=r?r:{},d=[],u=["community","top-trending",{params:{options:{limit:l}}}],g=(r,n=!1)=>{var s,a;const o=null!==(s=r.data.map((e=>Ee(["community","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==s?s:[];t({onNextPage:m,data:n?rf(o,e,i):o,hasNextPage:!!(null===(a=r.params)||void 0===a?void 0:a.page),loading:r.loading,error:r.error})},m=(t=!1)=>{var r,n;const s=null===(r=Ee(u))||void 0===r?void 0:r.data,i=null!==(n=null==s?void 0:s.data)&&void 0!==n?n:[];if(!t&&i.length>0&&!(null==s?void 0:s.params.page))return;const a=ie(tf,e);oe(a,(({data:t,error:r,loading:n})=>{const s={loading:n,error:r,params:e,data:i};t&&(s.data=[...new Set([...i,...t.map(de("community"))])]),Se(u,s),g(s)}),ae(c,b))};return d.push(Wh((e=>{var t;const r=null===(t=Ee(u))||void 0===t?void 0:t.data;r&&(r.data=[...new Set([e.communityId,...r.data])],Se(u,r),g(r))}))),m(!0),d.push((()=>ke(u))),()=>{n(`getTrendingCommunities(tmpid: ${a}) > dispose`),d.forEach((e=>e()))}},getRecommendedCommunities:(e,t,r)=>{const{log:n,cache:s,userId:i}=ve();s||console.log(p);const a=Date.now();n(`getRecommendedCommunities(tmpid: ${a}) > listen`);const{limit:o}=e;Mo(e,["limit"]);const l=null!=o?o:h,{policy:c=f}=null!=r?r:{},d=[],u=["community","recommended",{params:{options:{limit:l}}}],g=(r,n=!1)=>{var s,a;const o=null!==(s=r.data.map((e=>Ee(["community","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==s?s:[];t({onNextPage:m,data:n?rf(o,e,i):o,hasNextPage:!!(null===(a=r.params)||void 0===a?void 0:a.page),loading:r.loading,error:r.error})},m=(t=!1)=>{var r,n;const s=null===(r=Ee(u))||void 0===r?void 0:r.data,i=null!==(n=null==s?void 0:s.data)&&void 0!==n?n:[];if(!t&&i.length>0&&!(null==s?void 0:s.params.page))return;const a=ie(nf,e);oe(a,(({data:t,error:r,loading:n})=>{const s={loading:n,error:r,params:e,data:i};t&&(s.data=[...new Set([...i,...t.map(de("community"))])]),Se(u,s),g(s)}),ae(c,b))};return d.push(Wh((e=>{var t;const r=null===(t=Ee(u))||void 0===t?void 0:t.data;r&&(r.data=[...new Set([e.communityId,...r.data])],Se(u,r),g(r))}))),m(!0),d.push((()=>ke(u))),()=>{n(`getRecommendedCommunities(tmpid: ${a}) > dispose`),d.forEach((e=>e()))}}});const df=async e=>{const t=ve();t.log("category/getCategory",e);const{data:r}=await t.http.get(`/api/v3/community-categories/${encodeURIComponent(e)}`),n=t.cache&&Date.now();t.cache&&Oo(r,{cachedAt:n});const{categories:s}=r;return{data:il.category(s.find((t=>t.categoryId===e))),cachedAt:n}};df.locally=e=>{const t=ve();if(t.log("category/getCategory.locally",e),!t.cache)return;const r=Ee(["category","get",e]);return r?{data:il.category(r.data),cachedAt:r.cachedAt}:void 0};const uf=async e=>{const t=ve();t.log("category/queryCategories",e);const r=null!=e?e:{},{page:n,limit:s,includeDeleted:i}=r,a=Mo(r,["page","limit","includeDeleted"]),o=n?{token:n}:s?{limit:s}:void 0,{data:l}=await t.http.get("/api/v3/community-categories",{params:Object.assign(Object.assign({},a),{isDeleted:Al(i),options:o})}),{paging:c}=l,d=Mo(l,["paging"]),{categories:u}=d,h=t.cache&&Date.now();if(t.cache){Oo(d,{cachedAt:h});const e=["category","query",Object.assign(Object.assign({},a),{includeDeleted:i,options:o})];Se(e,{categories:u.map(de("category")),paging:c})}return{data:u,cachedAt:h,paging:c}};uf.locally=e=>{var t,r;const n=ve();if(n.log("category/queryCategories.locally",e),!n.cache)return;const s=null!=e?e:{},{page:i,limit:a=10}=s,o=Mo(s,["page","limit"]),l=i?{token:i}:a?{limit:a}:void 0,c=["category","query",Object.assign(Object.assign({},o),{options:l})],{data:d,cachedAt:u}=null!==(t=Ee(c))&&void 0!==t?t:{};if(!(null==d?void 0:d.categories.length))return;const h=d.categories.map((e=>Ee(["category","get",e]))).filter(Boolean).map((({data:e})=>e)),{paging:f}=d;return h.length===(null===(r=null==d?void 0:d.categories)||void 0===r?void 0:r.length)?{data:h,cachedAt:u,paging:f}:void 0};var hf=Object.freeze({__proto__:null,getCategory:df,getCategories:(e,t,r)=>{const{log:n,cache:s}=ve();s||console.log(p);const i=Date.now();n(`getCategories(tmpid: ${i}) > listen`);const{limit:a}=e,o=Mo(e,["limit"]),l=null!=a?a:h,{policy:c=f}=null!=r?r:{},d=[],u=["category","collection",{}],g=(r=!1)=>{var n,s;const i=null===(n=Ee(u))||void 0===n?void 0:n.data,a=null!==(s=null==i?void 0:i.data)&&void 0!==s?s:[];if(!r&&a.length>0&&!(null==i?void 0:i.params.page))return;const d=ie(uf,Object.assign(Object.assign({},o),{limit:r?l:void 0,page:r||null==i?void 0:i.params.page}));oe(d,(({data:r,error:n,loading:s,paging:i})=>{const o={loading:s,error:n,params:{page:null==i?void 0:i.next},data:a};r&&(o.data=[...new Set([...a,...r.map(de("category"))])]),Se(u,o),(r=>{var n,s;let i=null!==(n=r.data.map((e=>Ee(["category","get",e]))).filter(Boolean).map((({data:e})=>il.category(e))))&&void 0!==n?n:[];switch(e.includeDeleted||(i=Ae(i,"isDeleted",!1)),e.sortBy){case"firstCreated":i=i.sort(Fe);break;case"lastCreated":i=i.sort(Ne);break;default:i=i.sort(Me)}t({onNextPage:g,data:i,hasNextPage:!!(null===(s=r.params)||void 0===s?void 0:s.page),loading:r.loading,error:r.error})})(o)}),ae(c))};return d.push((()=>{})),g(!0),()=>{n(`getCategories(tmpid: ${i}) > dispose`),d.forEach((e=>e()))}}});const ff=async e=>{const t=ve();t.log("feed/queryGlobalFeed",e);const r=null!=e?e:{},{useCustomRanking:n,page:s,queryToken:i}=r,a=Mo(r,["useCustomRanking","page","queryToken"]);n&&console.warn('The param "useCustomRanking" has been deprecated. To get custom ranking feed use FeedRepository.getCustomRankingGlobalFeed instead'),s&&console.warn('The param "page" has been deprecated. Please use "queryToken" instead.');const o=i?{token:i}:s?{token:X(s,"skiplimit")}:void 0,{data:l}=await t.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},a),{options:o})}),{paging:c}=l,d=Mo(l,["paging"]),u=Uo(d,"communityUsers"),{posts:h}=u,f=t.cache&&Date.now();if(t.cache){Oo(u);const e=["globalFeed","query",Object.assign(Object.assign({},a),{options:Object.assign({},s)})];Se(e,{posts:h.map(de("post")),paging:c})}const p=J(c.next),g=J(c.previous);return{data:h.map(il.post),cachedAt:f,prevPage:g,nextPage:p,paging:c}};ff.locally=e=>{var t,r;const n=ve();if(n.log("post/queryGlobalFeed.locally",e),!n.cache)return;const s=null!=e?e:{},{page:i}=s,a=Mo(s,["page"]),o=["globalFeed","query",Object.assign(Object.assign({},a),{options:Object.assign({},i)})],{data:l,cachedAt:c}=null!==(t=Ee(o))&&void 0!==t?t:{};if(!(null==l?void 0:l.posts.length))return;const d=l.posts.map((e=>Ee(["post","get",e]))).filter(Boolean).map((({data:e})=>e)).map(il.post),{paging:u}=l,h=J(null==l?void 0:l.paging.previous),f=J(null==l?void 0:l.paging.next);return d.length===(null===(r=null==l?void 0:l.posts)||void 0===r?void 0:r.length)?{data:d,cachedAt:c,prevPage:h,nextPage:f,paging:u}:void 0};const pf=async e=>{const t=ve();t.log("feed/getCustomRankingGlobalFeed",e);const r=null!=e?e:{},{page:n,queryToken:s,limit:i}=r,a=Mo(r,["page","queryToken","limit"]),o=s?{token:s}:n?{token:X(n,"skiplimit")}:void 0,{data:l}=await t.http.get("/api/v5/me/global-feeds",{params:Object.assign(Object.assign({},a),{limit:s?void 0:i,options:o})}),{paging:c}=l,d=Mo(l,["paging"]),u=Uo(d,"communityUsers"),{posts:h}=u,f=t.cache&&Date.now();if(t.cache){Oo(u);const e=["customGlobalFeed","query",Object.assign(Object.assign({},a),{options:Object.assign({},n)})];Se(e,{posts:h.map(de("post")),paging:c})}const p=J(c.next),g=J(c.previous);return{data:h.map(il.post),cachedAt:f,prevPage:g,nextPage:p,paging:c}};pf.locally=e=>{var t,r;const n=ve();if(n.log("post/getCustomRankingGlobalFeed.locally",e),!n.cache)return;const s=null!=e?e:{},{page:i}=s,a=Mo(s,["page"]),o=["customGlobalFeed","query",Object.assign(Object.assign({},a),{options:Object.assign({},i)})],{data:l,cachedAt:c}=null!==(t=Ee(o))&&void 0!==t?t:{};if(!(null==l?void 0:l.posts.length))return;const d=l.posts.map((e=>Ee(["post","get",e]))).filter(Boolean).map((({data:e})=>e)),u=J(null==l?void 0:l.paging.previous),h=J(null==l?void 0:l.paging.next),{paging:f}=l;return d.length===(null===(r=null==l?void 0:l.posts)||void 0===r?void 0:r.length)?{data:d.map(il.post),cachedAt:c,prevPage:u,nextPage:h,paging:f}:void 0};var gf=Object.freeze({__proto__:null,queryGlobalFeed:ff,getCustomRankingGlobalFeed:pf});const mf=async e=>{const t=ve();t.log("post/getPostByIds",e);const r=e.map((e=>encodeURIComponent(e)));let n;try{n=(await t.http.get("/api/v3/posts/list",{params:{postIds:r}})).data}catch(t){throw e.forEach((e=>{C(null==t?void 0:t.code)&&Po("post",e)})),t}const s=Uo(n,"communityUsers"),i=t.cache&&Date.now();return t.cache&&Oo(s,{cachedAt:i}),{data:s.posts.map(il.post),cachedAt:i}};mf.locally=e=>{var t;const r=ve();if(r.log("post/getPostByIds.locally",e),!r.cache)return;const n=e.map((e=>Ee(["post","get",e]))).filter(Boolean),s=n.map((({data:e})=>e)),i=null===(t=n.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==n?void 0:n.length)<e.length?void 0:{data:s.map(il.post),cachedAt:i.cachedAt}};const yf=async(e,t=!1)=>{var r;const n=ve(),s=await Zd(e);if(await n.http.delete(`/api/v4/posts/${encodeURIComponent(e)}`,{params:{postId:e,permanent:t}}),"community"===s.data.targetType){const e=await Mh(s.data.targetId),t=(null!==(r=we(["communityUsers","get"]))&&void 0!==r?r:[]).filter((({key:t})=>"communityUsers"===t[0]&&("get"===t[1]&&("string"==typeof t[2]&&t[2].includes(e.data.communityId))))).map((({data:e})=>e));Je("community.updated",{communities:[e.data],categories:[],communityUsers:t,feeds:[],files:[],users:[]})}const i=Object.assign(Object.assign({},s.data),{isDeleted:!0});return Je("post.deleted",{posts:[i],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[]}),t?setTimeout((()=>{Po("post",e)}),0):Ce(["post","get",e],{isDeleted:!0}),il.post(i)},vf=async e=>{const t=ve();t.log("post/queryPosts",e);const{page:r,limit:n=10,includeDeleted:s}=e,i=Mo(e,["page","limit","includeDeleted"]),{dataTypes:a,matchingOnlyParentPost:o}=i,l=r?{token:r}:n?{limit:n}:void 0,{data:c}=await t.http.get("/api/v4/posts",{params:Object.assign(Object.assign({},i),{isDeleted:Al(s),matchingOnlyParentPost:null!=o?o:!(null==a?void 0:a.length),options:l})}),{paging:d}=c,u=Mo(c,["paging"]),h=Uo(u,"communityUsers"),{posts:f}=u,p=t.cache&&Date.now();if(t.cache){Oo(h,{cachedAt:p});const e=["post","query",Object.assign(Object.assign({},i),{options:l})];Se(e,{posts:f.map(de("post")),paging:d})}return{data:f.map(il.post),cachedAt:p,paging:d}};var bf=Object.freeze({__proto__:null,getPostByIds:mf,createPost:async e=>{const t=ve();t.log("post/createPost",e),e.dataType&&!["text","image","file","video"].includes(e.dataType)||delete e.dataType;const{data:r}=await t.http.post("/api/v4/posts",e);Je("post.created",r);const n=Uo(r,"communityUsers"),s=t.cache&&Date.now();t.cache&&Oo(n,{cachedAt:s});const{posts:i}=n;return{data:il.post(i[0]),cachedAt:s}},updatePost:async(e,t)=>{const r=ve();r.log("user/updatePost",t),console.warn("Deprecation: updatePost has been renamed to editPost. Update post API will be deprecated soon.");const{data:n}=await r.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,t),s=Uo(n,"communityUsers"),i=r.cache&&Date.now();r.cache&&Oo(s,{cachedAt:i}),Je("post.updated",s);const{posts:a}=s;return{data:il.post(a.find((t=>t.postId===e))),cachedAt:i}},editPost:async(e,t)=>{const r=ve();r.log("user/editPost",t);const{data:n}=await r.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,t),s=Uo(n,"communityUsers"),i=r.cache&&Date.now();r.cache&&Oo(s,{cachedAt:i}),Je("post.updated",s);const{posts:a}=s;return{data:il.post(a.find((t=>t.postId===e))),cachedAt:i}},deletePost:yf,softDeletePost:async e=>{ve().log("post/softDeletePost",e);const t=await yf(e,!1);return il.post(t)},hardDeletePost:async e=>{ve().log("post/hardDeletePost",e);const t=await yf(e,!0);return il.post(t)},approvePost:async e=>{const t=ve();t.log("post/approvePost",e);const{data:r}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/approve`);Je("post.approved",r),"community"===r.posts[0].targetType&&Je("community.updated",r);const n=Uo(r,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Oo(n,{cachedAt:s}),{data:il.post(n.posts.find((t=>t.postId===e))),cachedAt:s}},declinePost:async e=>{const t=ve();t.log("post/declinePost",e);const{data:r}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/decline`);"community"===r.posts[0].targetType&&Je("community.updated",r),Je("post.declined",r);const n=Uo(r,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Oo(n,{cachedAt:s}),{data:il.post(r.posts.find((t=>t.postId===e))),cachedAt:s}},flagPost:async e=>{const t=ve();t.log("post/flagPost",e);const{data:r}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/flag`);return t.cache&&Oo(Uo(r,"communityUsers")),Je("post.flagged",r),!!r},unflagPost:async e=>{const t=ve();t.log("post/unflagPost",e);const{data:r}=await t.http.delete(`/api/v3/posts/${encodeURIComponent(e)}/unflag`);return t.cache&&Oo(Uo(r,"communityUsers")),Je("post.unflagged",r),!!r},isPostFlaggedByMe:async e=>{const t=ve();t.log("post/isPostFlaggedByMe",e);const{data:{result:r}}=await t.http.get(`/api/v3/posts/${e}/isflagbyme`);return r},onPostCreated:cu,onPostUpdated:du,onPostDeleted:uu,onPostApproved:hu,onPostDeclined:fu,onPostFlagged:pu,onPostUnflagged:gu,onPostReactionAdded:mu,onPostReactionRemoved:yu,observePosts:(e,t)=>{const{log:r}=ve(),n=Date.now();r(`observePosts(tmpid: ${n}) > listen`);const s=[],i=(r,n)=>{var s,i;if(e.targetId===r.targetId&&e.targetType===r.targetType){if(t instanceof Function)return t(il.post(r));null===(s=t.onEvent)||void 0===s||s.call(t,n,il.post(r)),null===(i=t[n])||void 0===i||i.call(t,il.post(r))}};return s.push(cu((e=>i(e,"onCreate"))),du((e=>i(e,"onUpdate"))),uu((e=>i(e,"onDelete"))),hu((e=>i(e,"onApproved"))),fu((e=>i(e,"onDeclined"))),pu((e=>i(e,"onFlagged"))),gu((e=>i(e,"onUnflagged"))),mu((e=>i(e,"onReactionAdded"))),yu((e=>i(e,"onReactionRemoved")))),()=>{r(`observePosts(tmpid: ${n}) > dispose`),s.forEach((e=>e()))}},observePost:(e,t,r="cache_then_server")=>{const{log:n}=ve(),s=Date.now();n(`observePost(tmpid: ${s}) > listen`);const i=(e,r)=>{var n,s;if(t instanceof Function)return t(e);"onFetch"!==r&&(null===(n=t.onEvent)||void 0===n||n.call(t,r,e)),null===(s=t[r])||void 0===s||s.call(t,e)},a=(t,r)=>{var n;(null===(n=t.data)||void 0===n?void 0:n.postId)===e&&i(Object.assign(Object.assign({},t),{data:t.data&&il.post(t.data)}),r)},o=[];return o.push(du((e=>a({data:e,loading:!1,origin:"event"},"onUpdate"))),uu((e=>a({data:e,loading:!1,origin:"event"},"onDelete"))),hu((e=>a({data:e,loading:!1,origin:"event"},"onApproved"))),fu((e=>a({data:e,loading:!1,origin:"event"},"onDeclined"))),pu((e=>a({data:e,loading:!1,origin:"event"},"onFlagged"))),gu((e=>a({data:e,loading:!1,origin:"event"},"onUnflagged"))),mu((e=>a({data:e,loading:!1,origin:"event"},"onReactionAdded"))),yu((e=>a({data:e,loading:!1,origin:"event"},"onReactionRemoved")))),oe(ie(Zd,e),(e=>(e.data||e.error)&&i(Object.assign(Object.assign({},e),{data:e.data&&il.post(e.data)}),"onFetch")),ae(r)),()=>{n(`observePosts(tmpid: ${s}) > dispose`),o.forEach((e=>e()))}},getPost:(e,t)=>pd(e,t,"postId",Zd,[hu,fu,t=>uu((r=>{var n;let s=r;if(r.parentPostId===e&&r.isDeleted){const e=null===(n=Ee(["post","get",r.parentPostId]))||void 0===n?void 0:n.data;e&&(e.children=e.children.filter((e=>e!==r.postId)),Se(["post","get",e.postId],e),s=e)}t(s)})),pu,mu,yu,gu,du]),getPosts:(e,t,r)=>{const{log:n,cache:s}=ve();s||console.log(p);const i=Date.now();n(`getPosts(tmpid: ${i}) > listen`);const{limit:a}=e,o=Mo(e,["limit"]),l=null!=a?a:h,{policy:c=f}=null!=r?r:{},d=[],u=["post","collection",{targetId:e.targetId,targetType:e.targetType}],g=r=>{var n,s,i;let a=null!==(n=r.data.map((e=>Ee(["post","get",e]))).filter(Boolean).map((({data:e})=>il.post(e))))&&void 0!==n?n:[];const o=e.sortBy?e.sortBy:"lastCreated";a=a.sort("lastCreated"===o?Ne:Fe),e.includeDeleted||(a=Ae(a,"isDeleted",!1)),e.tags&&(a=a.filter((t=>{var r;return null===(r=t.tags)||void 0===r?void 0:r.some((t=>{var r;return null===(r=e.tags)||void 0===r?void 0:r.includes(t)}))}))),"community"===e.targetType&&e.feedType&&(a=Le(a,e.feedType)),(null===(s=e.dataTypes)||void 0===s?void 0:s.length)&&(a=xe(a,e.dataTypes)),t({onNextPage:y,data:a,hasNextPage:!!(null===(i=r.params)||void 0===i?void 0:i.page),loading:r.loading,error:r.error})},m=t=>r=>{var n,s;const i=null===(n=Ee(u))||void 0===n?void 0:n.data;if(i){if(r.parentPostId&&r.isDeleted){const t=null===(s=Ee(["post","get",r.parentPostId]))||void 0===s?void 0:s.data;if(!t||(null==t?void 0:t.targetId)!==e.targetId)return;t.children=t.children.filter((e=>e!==r.postId)),Se(["post","get",t.postId],t)}else{if(e.targetId!==r.targetId)return;if(e.targetType!==r.targetType)return}i.data="onDeclined"===t?i.data.filter((e=>e!==r.postId)):[...new Set([r.postId,...i.data])],Se(u,i),g(i)}},y=(e=!1)=>{var t,r,n;const s=null===(t=Ee(u))||void 0===t?void 0:t.data,i=null!==(r=null==s?void 0:s.data)&&void 0!==r?r:[];if(!e&&i.length>0&&!(null===(n=null==s?void 0:s.params)||void 0===n?void 0:n.page))return;const a=ie(vf,Object.assign(Object.assign({},o),{limit:e?l:void 0,page:e||null==s?void 0:s.params.page}));oe(a,(({data:t,error:r,loading:n,paging:s})=>{const a={loading:n,error:r,params:{page:null==s?void 0:s.next},data:i};t&&(a.data=e?t.map(de("post")):[...new Set([...i,...t.map(de("post"))])]),Se(u,a),g(a)}),ae(c,b))};return d.push(cu(m("onCreate")),hu(m("onApproved")),fu(m("onDeclined")),uu(m("onDelete")),du(m("onUpdate")),pu(m("onFlagged")),gu(m("onUnflagged")),mu(m("onReactionAdded")),yu(m("onReactionRemoved"))),y(!0),d.push((()=>ke(u))),()=>{n(`getPosts(tmpid: ${i}) > dispose`),d.forEach((e=>e()))}}});const wf=async e=>{const t=ve();t.log("comment/getCommentByIds",e);const r=e.map((e=>encodeURIComponent(e)));let n;try{n=(await t.http.get("/api/v3/comments/list",{params:{commentIds:r}})).data}catch(t){throw e.forEach((e=>{C(null==t?void 0:t.code)&&Po("comment",e)})),t}const s=t.cache&&Date.now();return t.cache&&Oo(n,{cachedAt:s}),{data:n.comments.map((e=>il.comment(e))),cachedAt:s}};wf.locally=e=>{var t;const r=ve();if(r.log("comment/getCommentByIds.locally",e),!r.cache)return;const n=e.map((e=>Ee(["comment","get",e]))).filter(Boolean),s=n.map((({data:e})=>e)),i=null===(t=n.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==n?void 0:n.length)<e.length?void 0:{data:s.map((e=>il.comment(e))),cachedAt:i.cachedAt}};const Ef=(e,t=!1)=>{const{stories:r}=e,n=r.map((e=>((e,t=!1)=>{const{storyId:r,referenceId:n}=e;return!t&&n?Object.assign(Object.assign({},e),{syncState:"synced"}):Object.assign(Object.assign({},e),{syncState:"synced",referenceId:r})})(e,t)));return Object.assign(Object.assign({},e),{stories:n})},Sf=async e=>{const t=ve();t.log("story/getStoryByStoryId",e);const r=Ee(["story-reference",e]);if(null==r?void 0:r.data){const{data:e}=r;ql("story",e)}let n;try{const r=await t.http.get(`/api/v4/stories/${e}`);n=Ef(r.data)}catch(t){throw C(null==t?void 0:t.code)&&Po("story",e),t}const s=t.cache&&Date.now();return t.cache&&Oo(n,{cachedAt:s}),{data:n.stories[0],cachedAt:s}};Sf.locally=e=>{const t=ve();t.log("story/getStorybyStoryId",e);const r=Ee(["story-reference",e]);if(null==r?void 0:r.data){const{data:e}=r;ql("story",e)}const n=t.cache&&Date.now(),s=Ee(["story","get",e]);if(s)return{data:s.data,cachedAt:n}};const Tf=async(e,t=!1)=>{const r=ve(),n=await eu(e);await r.http.delete(`/api/v4/comments/${encodeURIComponent(e)}`,{params:{commentId:e,permanent:t}});const s=Object.assign(Object.assign({},n.data),{isDeleted:!0});if("story"===n.data.referenceType){const e=await Sf(n.data.referenceId);Je("local.story.updated",{stories:[e.data],categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[]})}else{const e=await Zd(n.data.referenceId);Je("post.updated",{posts:[e.data],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[]})}return Je("comment.deleted",{comments:[s],commentChildren:[],files:[],users:[],communityUsers:[]}),t?ze((()=>Po("comment",e))):Ce(["comment","get",e],{isDeleted:!0}),s},Cf=async e=>{const t=ve();let r;t.log("comment/getComment",e),ql("comment",e);try{r=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw C(null==t?void 0:t.code)&&Po("comment",e),t}const n=t.cache&&Date.now();t.cache&&Oo(r,{cachedAt:n});const{comments:s}=r;return{data:s.find((t=>t.commentId===e)),cachedAt:n}};Cf.locally=e=>{const t=ve();if(t.log("comment/getComment.locally",e),!t.cache)return;const r=Ee(["comment","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const kf=async e=>{const t=ve();t.log("comment/queryComments",e);const{limit:r=10,includeDeleted:n}=e,s=Mo(e,["limit","includeDeleted"]),i={type:s.sortBy||e.limit?"pagination":void 0,limit:e.limit,token:e.page},{data:a}=await t.http.get("/api/v3/comments",{params:Object.assign(Object.assign({},s),{isDeleted:Al(n),options:i})}),{paging:o}=a,l=(e=>{const{comments:t}=e;return Object.assign(Object.assign({},e),{comments:t.map((e=>e.hasOwnProperty("myReactions")?e:Object.assign({myReactions:[]},e)))})})(Mo(a,["paging"])),{comments:c}=l,d=t.cache&&Date.now();if(t.cache){Oo(l,{cachedAt:d});const e=["comment","query",Object.assign(Object.assign({},s),{options:{limit:r}})];Se(e,{comments:c.map(de("comment")),paging:o})}return{data:c,cachedAt:d,paging:o}};var Af=Object.freeze({__proto__:null,getCommentByIds:wf,createComment:async e=>{const t=ve();t.log("comment/createComment",e);const{data:r}=await t.http.post("/api/v3/comments",e),{comments:n}=r;if(0===n.length)throw new Error("Comment not created");const s=t.cache&&Date.now();if(t.cache&&Oo(r,{cachedAt:s}),["post","content"].includes(e.referenceType)){const t=await Zd(e.referenceId);Je("post.updated",{posts:[t.data],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[]})}else if("story"===e.referenceType){const t=Ee(["story-reference",e.referenceId]);if(null==t?void 0:t.data){const e=Ee(["story","get",t.data]);(null==e?void 0:e.data)&&Je("story.updated",{stories:[Object.assign(Object.assign({},e.data),{commentsCount:e.data.commentsCount+1,comments:[...new Set([...e.data.comments,n[0].commentId])]})],categories:[],comments:n,communities:[],communityUsers:r.communityUsers,files:r.files,users:r.users})}}return Je("comment.created",r),{data:il.comment(n[0]),cachedAt:s}},updateComment:async(e,t)=>{const r=ve();r.log("user/updateComment",t);const{data:n}=await r.http.put(`/api/v3/comments/${encodeURIComponent(e)}`,t),s=r.cache&&Date.now();r.cache&&Oo(n,{cachedAt:s}),Je("comment.updated",n);const{comments:i}=n;return{data:il.comment(i.find((t=>t.commentId===e))),cachedAt:s}},deleteComment:Tf,softDeleteComment:async e=>{ve().log("comment/softDeleteComment",e);return Tf(e)},hardDeleteComment:async e=>{ve().log("comment/hardDeleteComment",e);return Tf(e,!0)},flagComment:async e=>{const t=ve();t.log("comment/flagComment",e);const{data:r}=await t.http.post(`/api/v3/comments/${encodeURIComponent(e)}/flag`);return t.cache&&Oo(r),Je("comment.flagged",r),!!r},unflagComment:async e=>{const t=ve();t.log("comment/unflagComment",e);const{data:r}=await t.http.delete(`/api/v3/comments/${encodeURIComponent(e)}/unflag`);return t.cache&&Oo(r),Je("comment.unflagged",r),!!r},isCommentFlaggedByMe:async e=>{const t=ve();t.log("comment/isCommentFlaggedByMe",e);const{data:{result:r}}=await t.http.get(`/api/v3/comments/${e}/isflagbyme`);return r},onCommentCreated:bu,onCommentUpdated:wu,onCommentDeleted:Eu,onCommentFlagged:Su,onCommentUnflagged:Tu,onCommentReactionAdded:Cu,onCommentReactionRemoved:ku,observeComments:(e,t)=>{const{log:r}=ve(),n=Date.now();r(`observeComments(tmpid: ${n}) > listen`);const s=[],i=(r,n)=>{var s,i;if(r.referenceId===e){if(t instanceof Function)return t(r);null===(s=t.onEvent)||void 0===s||s.call(t,n,r),null===(i=t[n])||void 0===i||i.call(t,r)}};return s.push(bu((e=>i(e,"onCreate"))),wu((e=>i(e,"onUpdate"))),Eu((e=>i(e,"onDelete"))),Su((e=>i(e,"onFlagged"))),Tu((e=>i(e,"onUnflagged"))),Cu((e=>i(e,"onReactionAdded"))),ku((e=>i(e,"onReactionRemoved")))),()=>{r(`observeComments(tmpid: ${n}) > dispose`),s.forEach((e=>e()))}},observeComment:(e,t,r="cache_then_server")=>{const{log:n}=ve(),s=Date.now();n(`observeComment(tmpid: ${s}) > listen`);const i=(e,r)=>{var n,s;if(t instanceof Function)return t(e);"onFetch"!==r&&(null===(n=t.onEvent)||void 0===n||n.call(t,r,e)),null===(s=t[r])||void 0===s||s.call(t,e)},a=(t,r)=>{var n;(null===(n=t.data)||void 0===n?void 0:n.commentId)===e&&i(t,r)},o=[];return o.push(wu((e=>a({data:e,loading:!1,origin:"event"},"onUpdate"))),Eu((e=>a({data:e,loading:!1,origin:"event"},"onDelete"))),Su((e=>a({data:e,loading:!1,origin:"event"},"onFlagged"))),Tu((e=>a({data:e,loading:!1,origin:"event"},"onUnflagged"))),Cu((e=>a({data:e,loading:!1,origin:"event"},"onReactionAdded"))),ku((e=>a({data:e,loading:!1,origin:"event"},"onReactionRemoved")))),oe(ie(Cf,e),(e=>(e.data||e.error)&&i(e,"onFetch")),ae(r)),()=>{n(`observeComment(tmpid: ${s}) > dispose`),o.forEach((e=>e()))}},getComment:(e,t)=>pd(e,t,"commentId",Cf,[Eu,Su,Cu,ku,Tu,wu,t=>bu((r=>{if(r.parentId!==e)return;const n=Ee(["comment","get",r.parentId]);(null==n?void 0:n.data)&&t(Object.assign(Object.assign({},n.data),{childrenNumber:n.data.childrenNumber+1,children:[...new Set([...n.data.children,r.commentId])]}))}))]),getComments:(e,t,r)=>{const{log:n,cache:s}=ve();s||console.log("For using Live Collection feature you need to enable Cache!");const i=Date.now();n(`getComments(tmpid: ${i}) > listen`);const{limit:a}=e,o=Mo(e,["limit"]),{policy:l=f}=null!=r?r:{},c=[],d=["comment","collection",{referenceId:e.referenceType,referenceType:e.referenceId,parentId:(null==e?void 0:e.parentId)||""}],u=r=>{var n,s;let i=null!==(n=r.data.map((e=>Ee(["comment","get",e]))).filter((({data:t})=>t.parentId===(null==e?void 0:e.parentId))).filter(Boolean).map((({data:e})=>il.comment(e))))&&void 0!==n?n:[];e.includeDeleted||(i=Ae(i,"isDeleted",!1));const a=e.sortBy?e.sortBy:"lastCreated";i=i.sort("lastCreated"===a?Ne:Fe),t({onNextPage:p,data:i,hasNextPage:!!(null===(s=r.params)||void 0===s?void 0:s.page),loading:r.loading,error:r.error})},h=t=>r=>{var n;const s=null===(n=Ee(d))||void 0===n?void 0:n.data;e.referenceId===r.referenceId&&e.referenceType===r.referenceType&&s&&("onCreate"===t?s.data=[...new Set([r.commentId,...s.data])]:"onDelete"===t&&(s.data=s.data.filter((e=>e!==r.commentId))),Se(d,s),u(s))},p=(e=!1)=>{var t,r,n;const s=null===(t=Ee(d))||void 0===t?void 0:t.data,i=null!==(r=null==s?void 0:s.data)&&void 0!==r?r:[];if(!e&&i.length>0&&!(null===(n=null==s?void 0:s.params)||void 0===n?void 0:n.page))return;const c=ie(kf,Object.assign(Object.assign({},o),{limit:a,page:e||null==s?void 0:s.params.page}));oe(c,(({data:t,error:r,loading:n,paging:s})=>{const a={loading:n,error:r,params:{page:"lastCreated"===(o.sortBy||"lastCreated")?null==s?void 0:s.next:null==s?void 0:s.previous},data:i};t&&(a.data=e?t.map(de("comment")):[...new Set([...i,...t.map(de("comment"))])]),Se(d,a),u(a)}),ae(l,b))};return c.push(bu(h("onCreate")),wu(h("onUpdate")),Eu(h("onDelete")),Su(h("onFlagged")),Tu(h("onUnflagged")),Cu(h("onReactionAdded")),ku(h("onReactionRemoved"))),p(!0),c.push((()=>ke(d))),()=>{n(`getComments(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}}});const If=async e=>{const t=ve();t.log("stream/getStream",e);const{data:r}=await t.http.get(`/api/v3/video-streaming/${e}`),n=t.cache&&Date.now();t.cache&&Oo(r,{cachedAt:n});const{videoStreamings:s}=r;return{data:s.find((t=>t.streamId===e)),cachedAt:n}};If.locally=e=>{const t=ve();if(t.log("stream/getStream",e),!t.cache)return;const r=Ee(["stream","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const _f=e=>{const t=ve();return Xe(t,"stream/onStreamStarted","video-streaming.didStart",(t=>{Oo(t),e(t.videoStreamings[0])}))},Rf=e=>{const t=ve();return Xe(t,"stream/onStreamStarted","video-streaming.didStop",(t=>{Oo(t),e(t.videoStreamings[0])}))},Lf=e=>{const t=ve();return Xe(t,"stream/onStreamRecorded","video-streaming.didRecord",(t=>{Oo(t),e(t.videoStreamings[0])}))},Df=(e,t)=>pd(e,t,"streamId",If,[Lf,_f,Rf]);Df.locally=e=>{const t=ve();if(t.log("stream/getStreamById",e),!t.cache)return;const r=Ee(["stream","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const xf=async e=>{const t=ve();t.log("stream/queryStreams",e);const r=null!=e?e:{},{page:n,limit:s}=r,i=Mo(r,["page","limit"]),a=n?{token:n}:s?{limit:s}:void 0,{data:o}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},i),{options:a})}),{paging:l,results:c}=o,{videoStreamings:d}=c,u=t.cache&&Date.now();return t.cache&&Oo(c,{cachedAt:u}),{data:d,cachedAt:u,paging:l}};var Of=Object.freeze({__proto__:null,createStream:async e=>{const t=ve();t.log("stream/createStream",e);const{data:r}=await t.http.post("/api/v3/video-streaming",e),n=t.cache&&Date.now();t.cache&&Oo(r,{cachedAt:n});const{videoStreamings:s}=r;return{data:s[0],cachedAt:n}},updateStream:async(e,t)=>{const r=ve();r.log("stream/updateStream",e,t);const{data:n}=await r.http.put(`/api/v3/video-streaming/${e}`,t),s=r.cache&&Date.now();r.cache&&Oo(n,{cachedAt:s});const{videoStreamings:i}=n;return{data:i.find((t=>t.streamId===e)),cachedAt:s}},deleteStream:async e=>{const t=ve();t.log("stream/deleteStream",e);const r=await If(e),{data:n}=await t.http.delete(`/api/v3/video-streaming/${e}`),{success:s}=n,i=Object.assign(Object.assign({},r.data),{isDeleted:!0});return Ce(["stream","get",e],i),s},disposeStream:async e=>{const t=ve();t.log("stream/disposeStream",e);const{data:r}=await t.http.delete(`/api/v3/video-streaming/${e}/streaming-url`),n=t.cache&&Date.now();t.cache&&Oo(r,{cachedAt:n});const{videoStreamings:s}=r;return{data:s.find((t=>t.streamId===e)),cachedAt:n}},queryStreams:async e=>{const t=ve();t.log("stream/queryStreams",e);const r=null!=e?e:{},{page:n}=r,s=Mo(r,["page"]),{data:i}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},s),{options:{token:X(n,"skiplimit")}})}),{paging:a,results:o}=i,{videoStreamings:l}=o,c=t.cache&&Date.now();t.cache&&Oo(o,{cachedAt:c});const d=J(a.next);return{data:l,cachedAt:c,prevPage:J(a.previous),nextPage:d}},getStream:If,onStreamStarted:_f,onStreamStopped:Rf,onStreamRecorded:Lf,getStreamById:Df,getStreams:(e,t,r)=>{const{log:n,cache:s}=ve();s||console.log(p);const i=Date.now();n(`getStreams(tmpid: ${i}) > listen`);const{limit:a}=e,o=Mo(e,["limit"]),l=null!=a?a:h,{policy:c=f}=null!=r?r:{},d=[],u=["streams","collection",e],g=t=>{let r=Ae(t,"isDeleted",e.isDeleted);return r=r.sort("lastCreated"===e.sortBy?Ne:Fe),r},m=(e,r=!1)=>{var n,s;const i=null!==(n=e.data.map((e=>Ee(["stream","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];t({onNextPage:v,data:r?g(i):i,hasNextPage:!!(null===(s=e.params)||void 0===s?void 0:s.page),loading:e.loading,error:e.error})},y=e=>e=>{var t;const r=null===(t=Ee(u))||void 0===t?void 0:t.data;r&&(r.data=[...new Set([e.streamId,...r.data])],Se(u,r),m(r,!0))},v=(e=!1)=>{var t,r;const n=null===(t=Ee(u))||void 0===t?void 0:t.data,s=null!==(r=null==n?void 0:n.data)&&void 0!==r?r:[];if(!e&&s.length>0&&!(null==n?void 0:n.params.page))return;const i=ie(xf,Object.assign(Object.assign({},o),{limit:e?l:void 0,page:e||null==n?void 0:n.params.page}));oe(i,(({data:e,error:t,loading:r,paging:n})=>{const i={loading:r,error:t,params:{page:null==n?void 0:n.next},data:s};e&&(i.data=[...new Set([...s,...e.map(de("stream"))])]),Se(u,i),m(i)}),ae(c))};return d.push(Lf(y()),_f(y()),Rf(y())),v(!0),()=>{n(`getStreams(tmpid: ${i}) > dispose`),d.forEach((e=>e()))}}});const Pf=async e=>{const t=ve();t.log("poll/getPoll",e);const{data:r}=await t.http.get(`/api/v3/polls/${e}`),n=t.cache&&Date.now();t.cache&&Oo(r,{cachedAt:n});const{polls:s}=r;return{data:s.find((t=>t.pollId===e)),cachedAt:n}};Pf.locally=e=>{const t=ve();if(t.log("poll/getPoll",e),!t.cache)return;const r=Ee(["poll","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const Mf=e=>{const t=ve();return Xe(t,"poll/onPollUpdated","poll.updated",(r=>{t.cache&&Oo(r),e(r.polls[0])}))},Ff=e=>{const t=ve();return Xe(t,"poll/onPollDeleted","poll.deleted",(r=>{t.cache&&Oo(r),e(r.polls[0])}))};var Uf=Object.freeze({__proto__:null,createPoll:async e=>{const t=ve();t.log("post/createPoll",e);const{data:r}=await t.http.post("/api/v3/polls",e),n=t.cache&&Date.now();t.cache&&Oo(r,{cachedAt:n});const{polls:s}=r;return{data:s[0],cachedAt:n}},closePoll:async e=>{const t=ve();t.log("user/closePoll",e);const{data:r}=await t.http.put(`/api/v3/polls/${encodeURIComponent(e)}`,{status:"closed"}),n=t.cache&&Date.now();t.cache&&Oo(r,{cachedAt:n}),Je("poll.updated",r);const{polls:s}=r;return{data:s.find((t=>t.pollId===e)),cachedAt:n}},deletePoll:async e=>{const t=ve();t.log("poll/deletePoll",e);const r=await Pf(e),{data:n}=await t.http.delete(`/api/v3/polls/${e}`),{success:s}=n,i=Object.assign(Object.assign({},r.data),{isDeleted:!0});return Ce(["poll","get",e],i),Je("poll.deleted",{polls:[i],users:[]}),s},votePoll:async(e,t)=>{const r=ve();r.log("user/votePoll",e);const{data:n}=await r.http.post(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:t}),s=r.cache&&Date.now();r.cache&&Oo(n,{cachedAt:s});const{polls:i}=n;return Je("poll.updated",n),{data:i.find((t=>t.pollId===e)),cachedAt:s}},onPollUpdated:Mf,onPollDeleted:Ff,observePoll:(e,t,r="cache_then_server")=>{const{log:n}=ve(),s=Date.now();n(`observePoll(tmpid: ${s}) > listen`);const i=(e,r)=>{var n,s;if(t instanceof Function)return t(e);"onFetch"!==r&&(null===(n=t.onEvent)||void 0===n||n.call(t,r,e)),null===(s=t[r])||void 0===s||s.call(t,e)},a=(t,r)=>{var n;(null===(n=t.data)||void 0===n?void 0:n.pollId)===e&&i(t,r)},o=[];return o.push(Mf((e=>a({data:e,loading:!1,origin:"event"},"onUpdate"))),Ff((e=>a({data:e,loading:!1,origin:"event"},"onDelete")))),oe(ie(Pf,e),(e=>(e.data||e.error)&&i(e,"onFetch")),ae(r)),()=>{n(`observePoll(tmpid: ${s}) > dispose`),o.forEach((e=>e()))}},getPoll:(e,t)=>pd(e,t,"pollId",Pf,[Mf,Ff])});function Nf(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Bf={exports:{}};!function(e,t){var r,n,s,i,a;r=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,n=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,i=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,r){if(r=r||{},e=e.trim(),!(t=t.trim())){if(!r.alwaysNormalize)return e;var s=a.parseURL(e);if(!s)throw new Error("Error trying to parse base URL.");return s.path=a.normalizePath(s.path),a.buildURLFromParts(s)}var i=a.parseURL(t);if(!i)throw new Error("Error trying to parse relative URL.");if(i.scheme)return r.alwaysNormalize?(i.path=a.normalizePath(i.path),a.buildURLFromParts(i)):t;var o=a.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=n.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var c={scheme:o.scheme,netLoc:i.netLoc,path:null,params:i.params,query:i.query,fragment:i.fragment};if(!i.netLoc&&(c.netLoc=o.netLoc,"/"!==i.path[0]))if(i.path){var d=o.path,u=d.substring(0,d.lastIndexOf("/")+1)+i.path;c.path=a.normalizePath(u)}else c.path=o.path,i.params||(c.params=o.params,i.query||(c.query=o.query));return null===c.path&&(c.path=r.alwaysNormalize?a.normalizePath(i.path):i.path),a.buildURLFromParts(c)},parseURL:function(e){var t=r.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(s,"");e.length!==(e=e.replace(i,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},e.exports=a}(Bf);var jf=Bf.exports;function $f(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function qf(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?$f(Object(r),!0).forEach((function(t){Kf(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):$f(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Kf(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Gf(){return Gf=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Gf.apply(this,arguments)}const Hf=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)};let Vf=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e}({}),zf=function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e}({}),Wf=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.UNKNOWN="unknown",e}({});const Yf=function(){},Qf={trace:Yf,debug:Yf,log:Yf,warn:Yf,info:Yf,error:Yf};let Xf=Qf;function Jf(e,...t){t.forEach((function(t){Xf[t]=e[t]?e[t].bind(e):function(e){const t=self.console[e];return t?t.bind(self.console,`[${e}] >`):Yf}(t)}))}const Zf=Xf,ep=/^(\d+)x(\d+)$/,tp=/(.+?)=(".*?"|.*?)(?:,|$)/g;class rp{constructor(e){"string"==typeof e&&(e=rp.parseAttrList(e));for(const t in e)e.hasOwnProperty(t)&&("X-"===t.substring(0,2)&&(this.clientAttrs=this.clientAttrs||[],this.clientAttrs.push(t)),this[t]=e[t])}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;const r=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)r[e]=parseInt(t.slice(2*e,2*e+2),16);return r}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const r=this[e];return r?parseFloat(r):t}enumeratedString(e){return this[e]}bool(e){return"YES"===this[e]}decimalResolution(e){const t=ep.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t;const r={};for(tp.lastIndex=0;null!==(t=tp.exec(e));){let e=t[2];0===e.indexOf('"')&&e.lastIndexOf('"')===e.length-1&&(e=e.slice(1,-1));r[t[1].trim()]=e}return r}}function np(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e}class sp{constructor(e,t){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,t){const r=t.attr;for(const t in r)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==r[t]){Zf.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=Gf(new rp({}),r,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const e=new Date(this.attr["END-DATE"]);Hf(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const e=this.duration;return null!==e?new Date(this._startDate.getTime()+1e3*e):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(Hf(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isValid(){return!!this.id&&!this._badValueForSameId&&Hf(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class ip{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var ap="audio",op="video",lp="audiovideo";class cp{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[ap]:null,[op]:null,[lp]:null},this.baseurl=e}setByteRange(e,t){const r=e.split("@",2),n=[];1===r.length?n[0]=t?t.byteRangeEndOffset:0:n[0]=parseInt(r[1]),n[1]=parseInt(r[0])+n[0],this._byteRange=n}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=jf.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class dp extends cp{constructor(e,t){super(t),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new ip,this.urlId=0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.type=e}get decryptdata(){const{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const e=this.levelkeys.identity;if(e)this._decryptdata=e.getDecryptData(this.sn);else{const e=Object.keys(this.levelkeys);if(1===e.length)return this._decryptdata=this.levelkeys[e[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;if(!Hf(this.programDateTime))return null;const e=Hf(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){const e=Object.keys(this.levelkeys),t=e.length;if(t>1||1===t&&this.levelkeys[e[0]].encrypted)return!0}return!1}setKeyFormat(e){if(this.levelkeys){const t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,r,n,s,i=!1){const{elementaryStreams:a}=this,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,n),o.endDTS=Math.max(o.endDTS,s)):a[e]={startPTS:t,endPTS:r,startDTS:n,endDTS:s,partial:i}}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[ap]=null,e[op]=null,e[lp]=null}}class up extends cp{constructor(e,t,r,n,s){super(r),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new ip,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=n;const i=e.enumeratedString("BYTERANGE");i&&this.setByteRange(i,s),s&&(this.fragOffset=s.fragOffset+s.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}class hp{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e)return this.advanced=!0,void(this.updated=!0);const t=this.lastPartSn-e.lastPartSn,r=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!r||!!t,this.advanced=this.endSN>e.endSN||t>0||0===t&&r>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return!!this.fragments.length&&Hf(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const e=this.driftEndTime-this.driftStartTime;if(e>0){return 1e3*(this.driftEnd-this.driftStart)/e}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var e;return null!=(e=this.fragments)&&e.length?this.fragments[this.fragments.length-1].end:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function fp(e){return Uint8Array.from(atob(e),(e=>e.charCodeAt(0)))}function pp(e){const t=e.split(":");let r=null;if("data"===t[0]&&2===t.length){const e=t[1].split(";"),n=e[e.length-1].split(",");if(2===n.length){const t="base64"===n[0],s=n[1];t?(e.splice(-1,1),r=fp(s)):r=function(e){const t=gp(e).subarray(0,16),r=new Uint8Array(16);return r.set(t,16-t.length),r}(s)}}return r}function gp(e){return Uint8Array.from(unescape(encodeURIComponent(e)),(e=>e.charCodeAt(0)))}var mp={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},yp="org.w3.clearkey",vp="com.apple.streamingkeydelivery",bp="com.microsoft.playready",wp="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function Ep(e){switch(e){case vp:return mp.FAIRPLAY;case bp:return mp.PLAYREADY;case wp:return mp.WIDEVINE;case yp:return mp.CLEARKEY}}var Sp="edef8ba979d64acea3c827dcd51d21ed";function Tp(e){switch(e){case mp.FAIRPLAY:return vp;case mp.PLAYREADY:return bp;case mp.WIDEVINE:return wp;case mp.CLEARKEY:return yp}}function Cp(e){const{drmSystems:t,widevineLicenseUrl:r}=e,n=t?[mp.FAIRPLAY,mp.WIDEVINE,mp.PLAYREADY,mp.CLEARKEY].filter((e=>!!t[e])):[];return!n[mp.WIDEVINE]&&r&&n.push(mp.WIDEVINE),n}const kp="undefined"!=typeof self&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function Ap(e,t,r){return Uint8Array.prototype.slice?e.slice(t,r):new Uint8Array(Array.prototype.slice.call(e,t,r))}const Ip=(e,t)=>t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128,_p=(e,t)=>t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128,Rp=(e,t)=>{const r=t;let n=0;for(;Ip(e,t);){n+=10;n+=Lp(e,t+6),_p(e,t+10)&&(n+=10),t+=n}if(n>0)return e.subarray(r,r+n)},Lp=(e,t)=>{let r=0;return r=(127&e[t])<<21,r|=(127&e[t+1])<<14,r|=(127&e[t+2])<<7,r|=127&e[t+3],r},Dp=(e,t)=>Ip(e,t)&&Lp(e,t+6)+10<=e.length-t,xp=e=>e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info,Op=e=>{const t=String.fromCharCode(e[0],e[1],e[2],e[3]),r=Lp(e,4);return{type:t,size:r,data:e.subarray(10,10+r)}},Pp=e=>{let t=0;const r=[];for(;Ip(e,t);){const n=Lp(e,t+6);t+=10;const s=t+n;for(;t+8<s;){const n=Op(e.subarray(t)),s=Mp(n);s&&r.push(s),t+=n.size+10}_p(e,t)&&(t+=10)}return r},Mp=e=>"PRIV"===e.type?Fp(e):"W"===e.type[0]?Np(e):Up(e),Fp=e=>{if(e.size<2)return;const t=jp(e.data,!0),r=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:r.buffer}},Up=e=>{if(e.size<2)return;if("TXXX"===e.type){let t=1;const r=jp(e.data.subarray(t),!0);t+=r.length+1;const n=jp(e.data.subarray(t));return{key:e.type,info:r,data:n}}const t=jp(e.data.subarray(1));return{key:e.type,data:t}},Np=e=>{if("WXXX"===e.type){if(e.size<2)return;let t=1;const r=jp(e.data.subarray(t),!0);t+=r.length+1;const n=jp(e.data.subarray(t));return{key:e.type,info:r,data:n}}const t=jp(e.data);return{key:e.type,data:t}},Bp=e=>{if(8===e.data.byteLength){const t=new Uint8Array(e.data),r=1&t[3];let n=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return n/=45,r&&(n+=47721858.84),Math.round(n)}},jp=(e,t=!1)=>{const r=qp();if(r){const n=r.decode(e);if(t){const e=n.indexOf("\0");return-1!==e?n.substring(0,e):n}return n.replace(/\0/g,"")}const n=e.length;let s,i,a,o="",l=0;for(;l<n;){if(s=e[l++],0===s&&t)return o;if(0!==s&&3!==s)switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(s);break;case 12:case 13:i=e[l++],o+=String.fromCharCode((31&s)<<6|63&i);break;case 14:i=e[l++],a=e[l++],o+=String.fromCharCode((15&s)<<12|(63&i)<<6|(63&a)<<0)}}return o};let $p;function qp(){return $p||void 0===self.TextDecoder||($p=new self.TextDecoder("utf-8")),$p}const Kp=function(e){let t="";for(let r=0;r<e.length;r++){let n=e[r].toString(16);n.length<2&&(n="0"+n),t+=n}return t},Gp=Math.pow(2,32)-1,Hp=[].push,Vp={video:1,audio:2,id3:3,text:4};function zp(e){return String.fromCharCode.apply(null,e)}function Wp(e,t){const r=e[t]<<8|e[t+1];return r<0?65536+r:r}function Yp(e,t){const r=Qp(e,t);return r<0?4294967296+r:r}function Qp(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function Xp(e,t,r){e[t]=r>>24,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r}function Jp(e,t){const r=[];if(!t.length)return r;const n=e.byteLength;for(let s=0;s<n;){const i=Yp(e,s),a=i>1?s+i:n;if(zp(e.subarray(s+4,s+8))===t[0])if(1===t.length)r.push(e.subarray(s+8,a));else{const n=Jp(e.subarray(s+8,a),t.slice(1));n.length&&Hp.apply(r,n)}s=a}return r}function Zp(e){const t=[],r=e[0];let n=8;const s=Yp(e,n);n+=4;n+=0===r?8:16,n+=2;let i=e.length+0;const a=Wp(e,n);n+=2;for(let r=0;r<a;r++){let r=n;const a=Yp(e,r);r+=4;const o=2147483647&a;if(1===(2147483648&a)>>>31)return Zf.warn("SIDX has hierarchical references (not supported)"),null;const l=Yp(e,r);r+=4,t.push({referenceSize:o,subsegmentDuration:l,info:{duration:l/s,start:i,end:i+o-1}}),i+=o,r+=4,n=r}return{earliestPresentationTime:0,timescale:s,version:r,referencesCount:a,references:t}}function eg(e){const t=[],r=Jp(e,["moov","trak"]);for(let e=0;e<r.length;e++){const n=r[e],s=Jp(n,["tkhd"])[0];if(s){let e=s[0],r=0===e?12:20;const i=Yp(s,r),a=Jp(n,["mdia","mdhd"])[0];if(a){e=a[0],r=0===e?12:20;const s=Yp(a,r),o=Jp(n,["mdia","hdlr"])[0];if(o){const e=zp(o.subarray(8,12)),r={soun:ap,vide:op}[e];if(r){const e=Jp(n,["mdia","minf","stbl","stsd"])[0];let a;e&&(a=zp(e.subarray(12,16))),t[i]={timescale:s,type:r},t[r]={timescale:s,id:i,codec:a}}}}}}return Jp(e,["moov","mvex","trex"]).forEach((e=>{const r=Yp(e,4),n=t[r];n&&(n.default={duration:Yp(e,12),flags:Yp(e,20)})})),t}function tg(e){const t=Jp(e,["schm"])[0];if(t){const r=zp(t.subarray(4,8));if("cbcs"===r||"cenc"===r)return Jp(e,["schi","tenc"])[0]}return Zf.error("[eme] missing 'schm' box"),null}function rg(e){const t=Yp(e,0);let r=8;1&t&&(r+=4),4&t&&(r+=4);let n=0;const s=Yp(e,4);for(let i=0;i<s;i++){if(256&t){n+=Yp(e,r),r+=4}512&t&&(r+=4),1024&t&&(r+=4),2048&t&&(r+=4)}return n}function ng(e,t){const r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}function sg(e,t){const r=[],n=t.samples,s=t.timescale,i=t.id;let a=!1;return Jp(n,["moof"]).map((o=>{const l=o.byteOffset-8;Jp(o,["traf"]).map((o=>{const c=Jp(o,["tfdt"]).map((e=>{const t=e[0];let r=Yp(e,4);return 1===t&&(r*=Math.pow(2,32),r+=Yp(e,8)),r/s}))[0];return void 0!==c&&(e=c),Jp(o,["tfhd"]).map((c=>{const d=Yp(c,4),u=16777215&Yp(c,0);let h=0;const f=0!=(16&u);let p=0;const g=0!=(32&u);let m=8;d===i&&(0!=(1&u)&&(m+=8),0!=(2&u)&&(m+=4),0!=(8&u)&&(h=Yp(c,m),m+=4),f&&(p=Yp(c,m),m+=4),g&&(m+=4),"video"===t.type&&(a=function(e){if(!e)return!1;const t=e.indexOf("."),r=t<0?e:e.substring(0,t);return"hvc1"===r||"hev1"===r||"dvh1"===r||"dvhe"===r}(t.codec)),Jp(o,["trun"]).map((i=>{const o=i[0],c=16777215&Yp(i,0),d=0!=(1&c);let u=0;const f=0!=(4&c),g=0!=(256&c);let m=0;const y=0!=(512&c);let v=0;const b=0!=(1024&c),w=0!=(2048&c);let E=0;const S=Yp(i,4);let T=8;d&&(u=Yp(i,T),T+=4),f&&(T+=4);let C=u+l;for(let l=0;l<S;l++){if(g?(m=Yp(i,T),T+=4):m=h,y?(v=Yp(i,T),T+=4):v=p,b&&(T+=4),w&&(E=0===o?Yp(i,T):Qp(i,T),T+=4),t.type===op){let t=0;for(;t<v;){const i=Yp(n,C);if(C+=4,ig(a,n[C])){ag(n.subarray(C,C+i),a?2:1,e+E/s,r)}C+=i,t+=i+4}}e+=m/s}})))}))}))})),r}function ig(e,t){if(e){const e=t>>1&63;return 39===e||40===e}return 6===(31&t)}function ag(e,t,r,n){const s=og(e);let i=0;i+=t;let a=0,o=0,l=!1,c=0;for(;i<s.length;){a=0;do{if(i>=s.length)break;c=s[i++],a+=c}while(255===c);o=0;do{if(i>=s.length)break;c=s[i++],o+=c}while(255===c);const e=s.length-i;if(!l&&4===a&&i<s.length){l=!0;if(181===s[i++]){const e=Wp(s,i);if(i+=2,49===e){const e=Yp(s,i);if(i+=4,1195456820===e){const e=s[i++];if(3===e){const t=s[i++],o=31&t,l=64&t,c=l?2+3*o:0,d=new Uint8Array(c);if(l){d[0]=t;for(let e=1;e<c;e++)d[e]=s[i++]}n.push({type:e,payloadType:a,pts:r,bytes:d})}}}}}else if(5===a&&o<e){if(l=!0,o>16){const e=[];for(let t=0;t<16;t++){const r=s[i++].toString(16);e.push(1==r.length?"0"+r:r),3!==t&&5!==t&&7!==t&&9!==t||e.push("-")}const t=o-16,l=new Uint8Array(t);for(let e=0;e<t;e++)l[e]=s[i++];n.push({payloadType:a,pts:r,uuid:e.join(""),userData:jp(l),userDataBytes:l})}}else if(o<e)i+=o;else if(o>e)break}}function og(e){const t=e.byteLength,r=[];let n=1;for(;n<t-2;)0===e[n]&&0===e[n+1]&&3===e[n+2]?(r.push(n+2),n+=2):n++;if(0===r.length)return e;const s=t-r.length,i=new Uint8Array(s);let a=0;for(n=0;n<s;a++,n++)a===r[0]&&(a++,r.shift()),i[n]=e[a];return i}function lg(e,t,r){if(16!==e.byteLength)throw new RangeError("Invalid system id");let n,s,i;if(t){n=1,s=new Uint8Array(16*t.length);for(let e=0;e<t.length;e++){const r=t[e];if(16!==r.byteLength)throw new RangeError("Invalid key");s.set(r,16*e)}}else n=0,s=new Uint8Array;n>0?(i=new Uint8Array(4),t.length>0&&new DataView(i.buffer).setUint32(0,t.length,!1)):i=new Uint8Array;const a=new Uint8Array(4);return r&&r.byteLength>0&&new DataView(a.buffer).setUint32(0,r.byteLength,!1),function(e,...t){const r=t.length;let n=8,s=r;for(;s--;)n+=t[s].byteLength;const i=new Uint8Array(n);for(i[0]=n>>24&255,i[1]=n>>16&255,i[2]=n>>8&255,i[3]=255&n,i.set(e,4),s=0,n=8;s<r;s++)i.set(t[s],n),n+=t[s].byteLength;return i}([112,115,115,104],new Uint8Array([n,0,0,0]),e,i,s,a,r||new Uint8Array)}let cg={};class dg{static clearKeyUriToKeyIdMap(){cg={}}constructor(e,t,r,n=[1],s=null){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=r,this.keyFormatVersions=n,this.iv=s,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&"AES-128"!==e}isSupported(){if(this.method){if("AES-128"===this.method||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case vp:case wp:case bp:case yp:return-1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if("AES-128"===this.method&&this.uri&&!this.iv){"number"!=typeof e&&("AES-128"!==this.method||this.iv||Zf.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const t=function(e){const t=new Uint8Array(16);for(let r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t}(e);return new dg(this.method,this.uri,"identity",this.keyFormatVersions,t)}const t=pp(this.uri);if(t)switch(this.keyFormat){case wp:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case bp:{const e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=lg(e,null,t);const r=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),n=String.fromCharCode.apply(null,Array.from(r)),s=n.substring(n.indexOf("<"),n.length),i=(new DOMParser).parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(i){const e=i.childNodes[0]?i.childNodes[0].nodeValue:i.getAttribute("VALUE");if(e){const t=fp(e).subarray(0,16);!function(e){const t=function(e,t,r){const n=e[t];e[t]=e[r],e[r]=n};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}(t),this.keyId=t}}break}default:{let e=t.subarray(0,16);if(16!==e.length){const t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e;break}}if(!this.keyId||16!==this.keyId.byteLength){let e=cg[this.uri];if(!e){const t=Object.keys(cg).length%Number.MAX_SAFE_INTEGER;e=new Uint8Array(16);new DataView(e.buffer,12,4).setUint32(0,t),cg[this.uri]=e}this.keyId=e}return this}}const ug=/\{\$([a-zA-Z0-9-_]+)\}/g;function hg(e){return ug.test(e)}function fg(e,t,r){if(null!==e.variableList||e.hasVariableRefs)for(let n=r.length;n--;){const s=r[n],i=t[s];i&&(t[s]=pg(e,i))}}function pg(e,t){if(null!==e.variableList||e.hasVariableRefs){const r=e.variableList;return t.replace(ug,(t=>{const n=t.substring(2,t.length-1),s=null==r?void 0:r[n];return void 0===s?(e.playlistParsingError||(e.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${n}"`)),t):s}))}return t}function gg(e,t,r){let n,s,i=e.variableList;if(i||(e.variableList=i={}),"QUERYPARAM"in t){n=t.QUERYPARAM;try{const e=new self.URL(r).searchParams;if(!e.has(n))throw new Error(`"${n}" does not match any query parameter in URI: "${r}"`);s=e.get(n)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`))}}else n=t.NAME,s=t.VALUE;n in i?e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${n}"`)):i[n]=s||""}function mg(e,t,r){const n=t.IMPORT;if(r&&n in r){let t=e.variableList;t||(e.variableList=t={}),t[n]=r[n]}else e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${n}"`))}function yg(){if("undefined"!=typeof self)return self.MediaSource||self.WebKitMediaSource}const vg={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,av01:!0,drac:!0,dva1:!0,dvav:!0,dvh1:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0},text:{stpp:!0,wvtt:!0}},bg=yg();function wg(e,t){var r;return null!=(r=null==bg?void 0:bg.isTypeSupported(`${t||"video"}/mp4;codecs="${e}"`))&&r}const Eg=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,Sg=/#EXT-X-MEDIA:(.*)/g,Tg=/^#EXT(?:INF|-X-TARGETDURATION):/m,Cg=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),kg=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class Ag{static findGroup(e,t){for(let r=0;r<e.length;r++){const n=e[r];if(n.id===t)return n}}static convertAVC1ToAVCOTI(e){const t=e.split(".");if(t.length>2){let e=t.shift()+".";return e+=parseInt(t.shift()).toString(16),e+=("000"+parseInt(t.shift()).toString(16)).slice(-4),e}return e}static resolve(e,t){return jf.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Tg.test(e)}static parseMasterPlaylist(e,t){const r={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:hg(e)},n=[];let s;for(Eg.lastIndex=0;null!=(s=Eg.exec(e));)if(s[1]){var i;const e=new rp(s[1]);fg(r,e,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const a=pg(r,s[2]),o={attrs:e,bitrate:e.decimalInteger("AVERAGE-BANDWIDTH")||e.decimalInteger("BANDWIDTH"),name:e.NAME,url:Ag.resolve(a,t)},l=e.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),Rg((e.CODECS||"").split(/[ ,]+/).filter((e=>e)),o),o.videoCodec&&-1!==o.videoCodec.indexOf("avc1")&&(o.videoCodec=Ag.convertAVC1ToAVCOTI(o.videoCodec)),null!=(i=o.unknownCodecs)&&i.length||n.push(o),r.levels.push(o)}else if(s[3]){const e=s[3],n=s[4];switch(e){case"SESSION-DATA":{const e=new rp(n);fg(r,e,["DATA-ID","LANGUAGE","VALUE","URI"]);const t=e["DATA-ID"];t&&(null===r.sessionData&&(r.sessionData={}),r.sessionData[t]=e);break}case"SESSION-KEY":{const e=Ig(n,t,r);e.encrypted&&e.isSupported()?(null===r.sessionKeys&&(r.sessionKeys=[]),r.sessionKeys.push(e)):Zf.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${n}"`);break}case"DEFINE":{const e=new rp(n);fg(r,e,["NAME","VALUE","QUERYPARAM"]),gg(r,e,t)}break;case"CONTENT-STEERING":{const e=new rp(n);fg(r,e,["SERVER-URI","PATHWAY-ID"]),r.contentSteering={uri:Ag.resolve(e["SERVER-URI"],t),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":r.startTimeOffset=_g(n)}}const a=n.length>0&&n.length<r.levels.length;return r.levels=a?n:r.levels,0===r.levels.length&&(r.playlistParsingError=new Error("no levels found in manifest")),r}static parseMasterPlaylistMedia(e,t,r){let n;const s={},i=r.levels,a={AUDIO:i.map((e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec}))),SUBTITLES:i.map((e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec}))),"CLOSED-CAPTIONS":[]};let o=0;for(Sg.lastIndex=0;null!==(n=Sg.exec(e));){const e=new rp(n[1]),i=e.TYPE;if(i){const n=a[i],l=s[i]||[];s[i]=l,fg(r,e,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const c={attrs:e,bitrate:0,id:o++,groupId:e["GROUP-ID"]||"",instreamId:e["INSTREAM-ID"],name:e.NAME||e.LANGUAGE||"",type:i,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:e.LANGUAGE,url:e.URI?Ag.resolve(e.URI,t):""};if(null!=n&&n.length){const e=Ag.findGroup(n,c.groupId)||n[0];Lg(c,e,"audioCodec"),Lg(c,e,"textCodec")}l.push(c)}}return s}static parseLevelPlaylist(e,t,r,n,s,i){const a=new hp(t),o=a.fragments;let l,c,d,u=null,h=0,f=0,p=0,g=0,m=null,y=new dp(n,t),v=-1,b=!1;for(Cg.lastIndex=0,a.m3u8=e,a.hasVariableRefs=hg(e);null!==(l=Cg.exec(e));){b&&(b=!1,y=new dp(n,t),y.start=p,y.sn=h,y.cc=g,y.level=r,u&&(y.initSegment=u,y.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null));const e=l[1];if(e){y.duration=parseFloat(e);const t=(" "+l[2]).slice(1);y.title=t||null,y.tagList.push(t?["INF",e,t]:["INF",e])}else if(l[3]){if(Hf(y.duration)){y.start=p,d&&Og(y,d,a),y.sn=h,y.level=r,y.cc=g,y.urlId=s,o.push(y);const e=(" "+l[3]).slice(1);y.relurl=pg(a,e),Dg(y,m),m=y,p+=y.duration,h++,f=0,b=!0}}else if(l[4]){const e=(" "+l[4]).slice(1);m?y.setByteRange(e,m):y.setByteRange(e)}else if(l[5])y.rawProgramDateTime=(" "+l[5]).slice(1),y.tagList.push(["PROGRAM-DATE-TIME",y.rawProgramDateTime]),-1===v&&(v=o.length);else{if(l=l[0].match(kg),!l){Zf.warn("No matches on slow regex match for level playlist!");continue}for(c=1;c<l.length&&void 0===l[c];c++);const e=(" "+l[c]).slice(1),s=(" "+l[c+1]).slice(1),p=l[c+2]?(" "+l[c+2]).slice(1):"";switch(e){case"PLAYLIST-TYPE":a.type=s.toUpperCase();break;case"MEDIA-SEQUENCE":h=a.startSN=parseInt(s);break;case"SKIP":{const e=new rp(s);fg(a,e,["RECENTLY-REMOVED-DATERANGES"]);const t=e.decimalInteger("SKIPPED-SEGMENTS");if(Hf(t)){a.skippedSegments=t;for(let e=t;e--;)o.unshift(null);h+=t}const r=e.enumeratedString("RECENTLY-REMOVED-DATERANGES");r&&(a.recentlyRemovedDateranges=r.split("\t"));break}case"TARGETDURATION":a.targetduration=Math.max(parseInt(s),1);break;case"VERSION":a.version=parseInt(s);break;case"EXTM3U":break;case"ENDLIST":a.live=!1;break;case"#":(s||p)&&y.tagList.push(p?[s,p]:[s]);break;case"DISCONTINUITY":g++,y.tagList.push(["DIS"]);break;case"GAP":y.gap=!0,y.tagList.push([e]);break;case"BITRATE":y.tagList.push([e,s]);break;case"DATERANGE":{const e=new rp(s);fg(a,e,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),fg(a,e,e.clientAttrs);const t=new sp(e,a.dateRanges[e.ID]);t.isValid||a.skippedSegments?a.dateRanges[t.id]=t:Zf.warn(`Ignoring invalid DATERANGE tag: "${s}"`),y.tagList.push(["EXT-X-DATERANGE",s]);break}case"DEFINE":{const e=new rp(s);fg(a,e,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in e?mg(a,e,i):gg(a,e,t)}break;case"DISCONTINUITY-SEQUENCE":g=parseInt(s);break;case"KEY":{const e=Ig(s,t,a);if(e.isSupported()){if("NONE"===e.method){d=void 0;break}d||(d={}),d[e.keyFormat]&&(d=Gf({},d)),d[e.keyFormat]=e}else Zf.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${s}"`);break}case"START":a.startTimeOffset=_g(s);break;case"MAP":{const e=new rp(s);if(fg(a,e,["BYTERANGE","URI"]),y.duration){const s=new dp(n,t);xg(s,e,r,d),u=s,y.initSegment=u,u.rawProgramDateTime&&!y.rawProgramDateTime&&(y.rawProgramDateTime=u.rawProgramDateTime)}else xg(y,e,r,d),u=y,b=!0;break}case"SERVER-CONTROL":{const e=new rp(s);a.canBlockReload=e.bool("CAN-BLOCK-RELOAD"),a.canSkipUntil=e.optionalFloat("CAN-SKIP-UNTIL",0),a.canSkipDateRanges=a.canSkipUntil>0&&e.bool("CAN-SKIP-DATERANGES"),a.partHoldBack=e.optionalFloat("PART-HOLD-BACK",0),a.holdBack=e.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const e=new rp(s);a.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=a.partList;e||(e=a.partList=[]);const r=f>0?e[e.length-1]:void 0,n=f++,i=new rp(s);fg(a,i,["BYTERANGE","URI"]);const o=new up(i,y,t,n,r);e.push(o),y.duration+=o.duration;break}case"PRELOAD-HINT":{const e=new rp(s);fg(a,e,["URI"]),a.preloadHint=e;break}case"RENDITION-REPORT":{const e=new rp(s);fg(a,e,["URI"]),a.renditionReports=a.renditionReports||[],a.renditionReports.push(e);break}default:Zf.warn(`line parsed but not handled: ${l}`)}}}m&&!m.relurl?(o.pop(),p-=m.duration,a.partList&&(a.fragmentHint=m)):a.partList&&(Dg(y,m),y.cc=g,a.fragmentHint=y,d&&Og(y,d,a));const w=o.length,E=o[0],S=o[w-1];if(p+=a.skippedSegments*a.targetduration,p>0&&w&&S){a.averagetargetduration=p/w;const e=S.sn;a.endSN="initSegment"!==e?e:0,a.live||(S.endList=!0),E&&(a.startCC=E.cc)}else a.endSN=0,a.startCC=0;return a.fragmentHint&&(p+=a.fragmentHint.duration),a.totalduration=p,a.endCC=g,v>0&&function(e,t){let r=e[t];for(let n=t;n--;){const t=e[n];if(!t)return;t.programDateTime=r.programDateTime-1e3*t.duration,r=t}}(o,v),a}}function Ig(e,t,r){var n,s;const i=new rp(e);fg(r,i,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=null!=(n=i.METHOD)?n:"",o=i.URI,l=i.hexadecimalInteger("IV"),c=i.KEYFORMATVERSIONS,d=null!=(s=i.KEYFORMAT)?s:"identity";o&&i.IV&&!l&&Zf.error(`Invalid IV: ${i.IV}`);const u=o?Ag.resolve(o,t):"",h=(c||"1").split("/").map(Number).filter(Number.isFinite);return new dg(a,u,d,h,l)}function _g(e){const t=new rp(e).decimalFloatingPoint("TIME-OFFSET");return Hf(t)?t:null}function Rg(e,t){["video","audio","text"].forEach((r=>{const n=e.filter((e=>function(e,t){const r=vg[t];return!!r&&!0===r[e.slice(0,4)]}(e,r)));if(n.length){const s=n.filter((e=>0===e.lastIndexOf("avc1",0)||0===e.lastIndexOf("mp4a",0)));t[`${r}Codec`]=s.length>0?s[0]:n[0],e=e.filter((e=>-1===n.indexOf(e)))}})),t.unknownCodecs=e}function Lg(e,t,r){const n=t[r];n&&(e[r]=n)}function Dg(e,t){e.rawProgramDateTime?e.programDateTime=Date.parse(e.rawProgramDateTime):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime),Hf(e.programDateTime)||(e.programDateTime=null,e.rawProgramDateTime=null)}function xg(e,t,r,n){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=r,e.sn="initSegment",n&&(e.levelkeys=n),e.initSegment=null}function Og(e,t,r){e.levelkeys=t;const{encryptedFragments:n}=r;n.length&&n[n.length-1].levelkeys===t||!Object.keys(t).some((e=>t[e].isCommonEncryption))||n.push(e)}var Pg="manifest",Mg="level",Fg="audioTrack",Ug="subtitleTrack",Ng="main",Bg="audio",jg="subtitle";function $g(e){const{type:t}=e;switch(t){case Fg:return Bg;case Ug:return jg;default:return Ng}}function qg(e,t){let r=e.url;return void 0!==r&&0!==r.indexOf("data:")||(r=t.url),r}class Kg{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Vf.LEVEL_LOADING,this.onLevelLoading,this),e.on(Vf.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(Vf.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:e}=this;e.off(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Vf.LEVEL_LOADING,this.onLevelLoading,this),e.off(Vf.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(Vf.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(e){const t=this.hls.config,r=t.pLoader,n=t.loader,s=new(r||n)(t);return this.loaders[e.type]=s,s}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:r}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Pg,url:r,deliveryDirectives:null})}onLevelLoading(e,t){const{id:r,level:n,url:s,deliveryDirectives:i}=t;this.load({id:r,level:n,responseType:"text",type:Mg,url:s,deliveryDirectives:i})}onAudioTrackLoading(e,t){const{id:r,groupId:n,url:s,deliveryDirectives:i}=t;this.load({id:r,groupId:n,level:null,responseType:"text",type:Fg,url:s,deliveryDirectives:i})}onSubtitleTrackLoading(e,t){const{id:r,groupId:n,url:s,deliveryDirectives:i}=t;this.load({id:r,groupId:n,level:null,responseType:"text",type:Ug,url:s,deliveryDirectives:i})}load(e){var t;const r=this.hls.config;let n,s=this.getInternalLoader(e);if(s){const t=s.context;if(t&&t.url===e.url)return void Zf.trace("[playlist-loader]: playlist request ongoing");Zf.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}if(n=e.type===Pg?r.manifestLoadPolicy.default:Gf({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),null!=(t=e.deliveryDirectives)&&t.part){let t;if(e.type===Mg&&null!==e.level?t=this.hls.levels[e.level].details:e.type===Fg&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===Ug&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){const e=t.partTarget,r=t.targetduration;if(e&&r){const t=1e3*Math.max(3*e,.8*r);n=Gf({},n,{maxTimeToFirstByteMs:Math.min(t,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,n.maxTimeToFirstByteMs)})}}}const i=n.errorRetry||n.timeoutRetry||{},a={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:i.maxNumRetry||0,retryDelay:i.retryDelayMs||0,maxRetryDelay:i.maxRetryDelayMs||0},o={onSuccess:(e,t,r,n)=>{const s=this.getInternalLoader(r);this.resetInternalLoader(r.type);const i=e.data;0===i.indexOf("#EXTM3U")?(t.parsing.start=performance.now(),Ag.isMediaPlaylist(i)?this.handleTrackOrLevelPlaylist(e,t,r,n||null,s):this.handleMasterPlaylist(e,t,r,n)):this.handleManifestParsingError(e,r,new Error("no EXTM3U delimiter"),n||null,t)},onError:(e,t,r,n)=>{this.handleNetworkError(t,r,!1,e,n)},onTimeout:(e,t,r)=>{this.handleNetworkError(t,r,!0,void 0,e)}};s.load(e,a,o)}handleMasterPlaylist(e,t,r,n){const s=this.hls,i=e.data,a=qg(e,r),o=Ag.parseMasterPlaylist(i,a);if(o.playlistParsingError)return void this.handleManifestParsingError(e,r,o.playlistParsingError,n,t);const{contentSteering:l,levels:c,sessionData:d,sessionKeys:u,startTimeOffset:h,variableList:f}=o;this.variableList=f;const{AUDIO:p=[],SUBTITLES:g,"CLOSED-CAPTIONS":m}=Ag.parseMasterPlaylistMedia(i,a,o);if(p.length){p.some((e=>!e.url))||!c[0].audioCodec||c[0].attrs.AUDIO||(Zf.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new rp({}),bitrate:0,url:""}))}s.trigger(Vf.MANIFEST_LOADED,{levels:c,audioTracks:p,subtitles:g,captions:m,contentSteering:l,url:a,stats:t,networkDetails:n,sessionData:d,sessionKeys:u,startTimeOffset:h,variableList:f})}handleTrackOrLevelPlaylist(e,t,r,n,s){const i=this.hls,{id:a,level:o,type:l}=r,c=qg(e,r),d=Hf(a)?a:0,u=Hf(o)?o:d,h=$g(r),f=Ag.parseLevelPlaylist(e.data,c,u,h,d,this.variableList);if(l===Pg){const e={attrs:new rp({}),bitrate:0,details:f,name:"",url:c};i.trigger(Vf.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:c,stats:t,networkDetails:n,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),r.levelDetails=f,this.handlePlaylistLoaded(f,e,t,r,n,s)}handleManifestParsingError(e,t,r,n,s){this.hls.trigger(Vf.ERROR,{type:zf.NETWORK_ERROR,details:Wf.MANIFEST_PARSING_ERROR,fatal:t.type===Pg,url:e.url,err:r,error:r,reason:r.message,response:e,context:t,networkDetails:n,stats:s})}handleNetworkError(e,t,r=!1,n,s){let i=`A network ${r?"timeout":"error"+(n?" (status "+n.code+")":"")} occurred while loading ${e.type}`;e.type===Mg?i+=`: ${e.level} id: ${e.id}`:e.type!==Fg&&e.type!==Ug||(i+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(i);Zf.warn(`[playlist-loader]: ${i}`);let o=Wf.UNKNOWN,l=!1;const c=this.getInternalLoader(e);switch(e.type){case Pg:o=r?Wf.MANIFEST_LOAD_TIMEOUT:Wf.MANIFEST_LOAD_ERROR,l=!0;break;case Mg:o=r?Wf.LEVEL_LOAD_TIMEOUT:Wf.LEVEL_LOAD_ERROR,l=!1;break;case Fg:o=r?Wf.AUDIO_TRACK_LOAD_TIMEOUT:Wf.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case Ug:o=r?Wf.SUBTITLE_TRACK_LOAD_TIMEOUT:Wf.SUBTITLE_LOAD_ERROR,l=!1}c&&this.resetInternalLoader(e.type);const d={type:zf.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:c,context:e,error:a,networkDetails:t,stats:s};if(n){const r=(null==t?void 0:t.url)||e.url;d.response=qf({url:r,data:void 0},n)}this.hls.trigger(Vf.ERROR,d)}handlePlaylistLoaded(e,t,r,n,s,i){const a=this.hls,{type:o,level:l,id:c,groupId:d,deliveryDirectives:u}=n,h=qg(t,n),f=$g(n),p="number"==typeof n.level&&f===Ng?l:void 0;if(!e.fragments.length){const e=new Error("No Segments found in Playlist");return void a.trigger(Vf.ERROR,{type:zf.NETWORK_ERROR,details:Wf.LEVEL_EMPTY_ERROR,fatal:!1,url:h,error:e,reason:e.message,response:t,context:n,level:p,parent:f,networkDetails:s,stats:r})}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const g=e.playlistParsingError;if(g)a.trigger(Vf.ERROR,{type:zf.NETWORK_ERROR,details:Wf.LEVEL_PARSING_ERROR,fatal:!1,url:h,error:g,reason:g.message,response:t,context:n,level:p,parent:f,networkDetails:s,stats:r});else switch(e.live&&i&&(i.getCacheAge&&(e.ageHeader=i.getCacheAge()||0),i.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case Pg:case Mg:a.trigger(Vf.LEVEL_LOADED,{details:e,level:p||0,id:c||0,stats:r,networkDetails:s,deliveryDirectives:u});break;case Fg:a.trigger(Vf.AUDIO_TRACK_LOADED,{details:e,id:c||0,groupId:d||"",stats:r,networkDetails:s,deliveryDirectives:u});break;case Ug:a.trigger(Vf.SUBTITLE_TRACK_LOADED,{details:e,id:c||0,groupId:d||"",stats:r,networkDetails:s,deliveryDirectives:u})}}}function Gg(e,t){let r;try{r=new Event("addtrack")}catch(e){r=document.createEvent("Event"),r.initEvent("addtrack",!1,!1)}r.track=e,t.dispatchEvent(r)}function Hg(e,t){const r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(r){Zf.debug(`[texttrack-utils]: ${r}`);try{const r=new self.TextTrackCue(t.startTime,t.endTime,t.text);r.id=t.id,e.addCue(r)}catch(e){Zf.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}"disabled"===r&&(e.mode=r)}function Vg(e){const t=e.mode;if("disabled"===t&&(e.mode="hidden"),e.cues)for(let t=e.cues.length;t--;)e.removeCue(e.cues[t]);"disabled"===t&&(e.mode=t)}function zg(e,t,r,n){const s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues&&e.cues.length>0){const s=function(e,t,r){const n=[],s=function(e,t){if(t<e[0].startTime)return 0;const r=e.length-1;if(t>e[r].endTime)return-1;let n=0,s=r;for(;n<=s;){const i=Math.floor((s+n)/2);if(t<e[i].startTime)s=i-1;else{if(!(t>e[i].startTime&&n<r))return i;n=i+1}}return e[n].startTime-t<t-e[s].startTime?n:s}(e,t);if(s>-1)for(let i=s,a=e.length;i<a;i++){const s=e[i];if(s.startTime>=t&&s.endTime<=r)n.push(s);else if(s.startTime>r)return n}return n}(e.cues,t,r);for(let t=0;t<s.length;t++)n&&!n(s[t])||e.removeCue(s[t])}"disabled"===s&&(e.mode=s)}var Wg="org.id3",Yg="com.apple.quicktime.HLS",Qg="https://aomedia.org/emsg/ID3";function Xg(){if("undefined"!=typeof self)return self.WebKitDataCue||self.VTTCue||self.TextTrackCue}const Jg=(()=>{const e=Xg();try{new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function Zg(e,t){return e.getTime()/1e3-t}class em{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:e}=this;e.on(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Vf.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(Vf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Vf.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Vf.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(Vf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Vf.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&(Vg(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const r=e[t];if("metadata"===r.kind&&"id3"===r.label)return Gg(r,this.media),r}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:r,enableID3MetadataCues:n}}}=this;if(!r&&!n)return;const{samples:s}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const i=Xg();for(let e=0;e<s.length;e++){const t=s[e].type;if(t===Qg&&!r||!n)continue;const a=Pp(s[e].data);if(a){const r=s[e].pts;let n=r+s[e].duration;n>Jg&&(n=Jg);n-r<=0&&(n=r+.25);for(let e=0;e<a.length;e++){const s=a[e];if(!xp(s)){this.updateId3CueEnds(r,t);const e=new i(r,n,"");e.value=s,t&&(e.type=t),this.id3Track.addCue(e)}}}}}updateId3CueEnds(e,t){var r;const n=null==(r=this.id3Track)?void 0:r.cues;if(n)for(let r=n.length;r--;){const s=n[r];s.type===t&&s.startTime<e&&s.endTime===Jg&&(s.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:r,type:n}){const{id3Track:s,hls:i}=this;if(!i)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=i;if(s&&(a||o)){let e;e="audio"===n?e=>e.type===Wg&&o:"video"===n?e=>e.type===Qg&&a:e=>e.type===Wg&&o||e.type===Qg&&a,zg(s,t,r,e)}}onLevelUpdated(e,{details:t}){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:r,id3Track:n}=this,{dateRanges:s}=t,i=Object.keys(s);if(n){const e=Object.keys(r).filter((e=>!i.includes(e)));for(let t=e.length;t--;){const s=e[t];Object.keys(r[s].cues).forEach((e=>{n.removeCue(r[s].cues[e])})),delete r[s]}}const a=t.fragments[t.fragments.length-1];if(0===i.length||!Hf(null==a?void 0:a.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=a.programDateTime/1e3-a.start,l=Xg();for(let e=0;e<i.length;e++){const t=i[e],n=s[t],a=r[t],u=(null==a?void 0:a.cues)||{};let h=(null==a?void 0:a.durationKnown)||!1;const f=Zg(n.startDate,o);let p=Jg;const g=n.endDate;if(g)p=Zg(g,o),h=!0;else if(n.endOnNext&&!h){const e=i.reduce(((e,t)=>{const r=s[t];return r.class===n.class&&r.id!==t&&r.startDate>n.startDate&&e.push(r),e}),[]).sort(((e,t)=>e.startDate.getTime()-t.startDate.getTime()))[0];e&&(p=Zg(e.startDate,o),h=!0)}const m=Object.keys(n.attr);for(let e=0;e<m.length;e++){const r=m[e];if("ID"===(d=r)||"CLASS"===d||"START-DATE"===d||"DURATION"===d||"END-DATE"===d||"END-ON-NEXT"===d)continue;let s=u[r];if(s)h&&!a.durationKnown&&(s.endTime=p);else{let e=n.attr[r];s=new l(f,p,""),np(r)&&(c=e,e=Uint8Array.from(c.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer),s.value={key:r,data:e},s.type=Yg,s.id=t,this.id3Track.addCue(s),u[r]=s}}r[t]={cues:u,dateRange:n,durationKnown:h}}var c,d}}class tm{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=()=>this.timeupdate(),this.hls=e,this.config=e.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:e,levelDetails:t}=this;return void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const{levelDetails:e}=this;if(null===e)return null;const{holdBack:t,partHoldBack:r,targetduration:n}=e,{liveSyncDuration:s,liveSyncDurationCount:i,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&r||t;(o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==s?s:i*n);const c=n;return l+Math.min(1*this.stallCount,c)}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency,r=this.levelDetails;if(null===e||null===t||null===r)return null;const n=r.edge,s=e-t-this.edgeStalled,i=n-r.totalduration,a=n-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(i,s),a)}get drift(){const{levelDetails:e}=this;return null===e?1:e.drift}get edgeStalled(){const{levelDetails:e}=this;if(null===e)return 0;const t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e,levelDetails:t}=this;if(!e||!t)return 0;const r=e.buffered.length;return(r?e.buffered.end(r-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(Vf.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(Vf.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(Vf.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(Vf.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(Vf.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(Vf.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){this.levelDetails=t,t.advanced&&this.timeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(e,t){var r;t.details===Wf.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(r=this.levelDetails)&&r.live&&Zf.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:e,levelDetails:t}=this;if(!e||!t)return;this.currentTime=e.currentTime;const r=this.computeLatency();if(null===r)return;this._latency=r;const{lowLatencyMode:n,maxLiveSyncPlaybackRate:s}=this.config;if(!n||1===s)return;const i=this.targetLatency;if(null===i)return;const a=r-i,o=a<Math.min(this.maxLatency,i+t.targetduration);if(t.live&&o&&a>.05&&this.forwardBufferLength>1){const t=Math.min(2,Math.max(1,s)),r=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20;e.playbackRate=Math.min(t,Math.max(1,r))}else 1!==e.playbackRate&&0!==e.playbackRate&&(e.playbackRate=1)}estimateLiveEdge(){const{levelDetails:e}=this;return null===e?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}const rm=["NONE","TYPE-0","TYPE-1",null];var nm="",sm="YES",im="v2";class am{constructor(e,t,r){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=r}addDirectives(e){const t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class om{constructor(e){this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.unknownCodecs=void 0,this.audioGroupIds=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.textGroupIds=void 0,this.url=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.unknownCodecs=e.unknownCodecs,this.codecSet=[e.videoCodec,e.audioCodec].filter((e=>e)).join(",").replace(/\.[^.,]+/g,"")}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get attrs(){return this._attrs[this._urlId]}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get uri(){return this.url[this._urlId]||""}get urlId(){return this._urlId}set urlId(e){const t=e%this.url.length;this._urlId!==t&&(this.fragmentError=0,this.loadError=0,this.details=void 0,this._urlId=t)}get audioGroupId(){var e;return null==(e=this.audioGroupIds)?void 0:e[this.urlId]}get textGroupId(){var e;return null==(e=this.textGroupIds)?void 0:e[this.urlId]}addFallback(e){this.url.push(e.url),this._attrs.push(e.attrs)}}function lm(e,t){const r=t.startPTS;if(Hf(r)){let n,s=0;t.sn>e.sn?(s=r-e.start,n=e):(s=e.start-r,n=t),n.duration!==s&&(n.duration=s)}else if(t.sn>e.sn){e.cc===t.cc&&e.minEndPTS?t.start=e.start+(e.minEndPTS-e.start):t.start=e.start+e.duration}else t.start=Math.max(e.start-t.duration,0)}function cm(e,t,r,n,s,i){n-r<=0&&(Zf.warn("Fragment should have a positive duration",t),n=r+t.duration,i=s+t.duration);let a=r,o=n;const l=t.startPTS,c=t.endPTS;if(Hf(l)){const e=Math.abs(l-r);Hf(t.deltaPTS)?t.deltaPTS=Math.max(e,t.deltaPTS):t.deltaPTS=e,a=Math.max(r,l),r=Math.min(r,l),s=Math.min(s,t.startDTS),o=Math.min(n,c),n=Math.max(n,c),i=Math.max(i,t.endDTS)}const d=r-t.start;0!==t.start&&(t.start=r),t.duration=n-t.start,t.startPTS=r,t.maxStartPTS=a,t.startDTS=s,t.endPTS=n,t.minEndPTS=o,t.endDTS=i;const u=t.sn;if(!e||u<e.startSN||u>e.endSN)return 0;let h;const f=u-e.startSN,p=e.fragments;for(p[f]=t,h=f;h>0;h--)lm(p[h],p[h-1]);for(h=f;h<p.length-1;h++)lm(p[h],p[h+1]);return e.fragmentHint&&lm(p[p.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,d}function dm(e,t){let r=null;const n=e.fragments;for(let e=n.length-1;e>=0;e--){const t=n[e].initSegment;if(t){r=t;break}}e.fragmentHint&&delete e.fragmentHint.endPTS;let s,i=0;if(function(e,t,r){const n=t.skippedSegments,s=Math.max(e.startSN,t.startSN)-t.startSN,i=(e.fragmentHint?1:0)+(n?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let e=s;e<=i;e++){const s=l[a+e];let i=o[e];n&&!i&&e<n&&(i=t.fragments[e]=s),s&&i&&r(s,i)}}(e,t,((e,n)=>{e.relurl&&(i=e.cc-n.cc),Hf(e.startPTS)&&Hf(e.endPTS)&&(n.start=n.startPTS=e.startPTS,n.startDTS=e.startDTS,n.maxStartPTS=e.maxStartPTS,n.endPTS=e.endPTS,n.endDTS=e.endDTS,n.minEndPTS=e.minEndPTS,n.duration=e.endPTS-e.startPTS,n.duration&&(s=n),t.PTSKnown=t.alignedSliding=!0),n.elementaryStreams=e.elementaryStreams,n.loader=e.loader,n.stats=e.stats,n.urlId=e.urlId,e.initSegment&&(n.initSegment=e.initSegment,r=e.initSegment)})),r){(t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments).forEach((e=>{var t;e.initSegment&&e.initSegment.relurl!==(null==(t=r)?void 0:t.relurl)||(e.initSegment=r)}))}if(t.skippedSegments)if(t.deltaUpdateFailed=t.fragments.some((e=>!e)),t.deltaUpdateFailed){Zf.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)t.fragments.shift();t.startSN=t.fragments[0].sn,t.startCC=t.fragments[0].cc}else t.canSkipDateRanges&&(t.dateRanges=function(e,t,r){const n=Gf({},e);r&&r.forEach((e=>{delete n[e]}));return Object.keys(t).forEach((e=>{const r=new sp(t[e].attr,n[e]);r.isValid?n[e]=r:Zf.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(t[e].attr)}"`)})),n}(e.dateRanges,t.dateRanges,t.recentlyRemovedDateranges));const a=t.fragments;if(i){Zf.warn("discontinuity sliding from playlist, take drift into account");for(let e=0;e<a.length;e++)a[e].cc+=i}t.skippedSegments&&(t.startCC=t.fragments[0].cc),function(e,t,r){if(e&&t){let n=0;for(let s=0,i=e.length;s<=i;s++){const i=e[s],a=t[s+n];i&&a&&i.index===a.index&&i.fragment.sn===a.fragment.sn?r(i,a):n--}}}(e.partList,t.partList,((e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats})),s?cm(t,s,s.startPTS,s.endPTS,s.startDTS,s.endDTS):um(e,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const o=t.advancedDateTime;if(t.advanced&&o){const e=t.edge;t.driftStart||(t.driftStartTime=o,t.driftStart=e),t.driftEndTime=o,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime}function um(e,t){const r=t.startSN+t.skippedSegments-e.startSN,n=e.fragments;r<0||r>=n.length||hm(t,n[r].start)}function hm(e,t){if(t){const r=e.fragments;for(let n=e.skippedSegments;n<r.length;n++)r[n].start+=t;e.fragmentHint&&(e.fragmentHint.start+=t)}}function fm(e,t,r){var n;return null!=e&&e.details?pm(null==(n=e.details)?void 0:n.partList,t,r):null}function pm(e,t,r){if(e)for(let n=e.length;n--;){const s=e[n];if(s.index===r&&s.fragment.sn===t)return s}return null}function gm(e){switch(e.details){case Wf.FRAG_LOAD_TIMEOUT:case Wf.KEY_LOAD_TIMEOUT:case Wf.LEVEL_LOAD_TIMEOUT:case Wf.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function mm(e,t){const r=gm(t);return e.default[(r?"timeout":"error")+"Retry"]}function ym(e,t){const r="linear"===e.backoff?1:Math.pow(2,t);return Math.min(r*e.retryDelayMs,e.maxRetryDelayMs)}function vm(e){return qf(qf({},e),{errorRetry:null,timeoutRetry:null})}function bm(e,t,r,n){return!!e&&t<e.maxNumRetry&&(function(e){return 0===e&&!1===navigator.onLine||!!e&&(e<400||e>499)}(n)||!!r)}const wm=function(e,t){let r=0,n=e.length-1,s=null,i=null;for(;r<=n;){s=(r+n)/2|0,i=e[s];const a=t(i);if(a>0)r=s+1;else{if(!(a<0))return i;n=s-1}}return null};function Em(e,t,r=0,n=0){let s=null;if(e?s=t[e.sn-t[0].sn+1]||null:0===r&&0===t[0].start&&(s=t[0]),s&&0===Sm(r,n,s))return s;const i=wm(t,Sm.bind(null,r,n));return!i||i===e&&s?s:i}function Sm(e=0,t=0,r){if(r.start<=e&&r.start+r.duration>e)return 0;const n=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-n<=e?1:r.start-n>e&&r.start?-1:0}function Tm(e,t,r){const n=1e3*Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-n>e}var Cm=0,km=2,Am=5,Im=0,_m=1,Rm=2;function Lm(e,t,r){if(performance.now()-e.lastErrorPerfMs>3e5)return!0;const n=e.details;if(t.details===Wf.FRAG_GAP&&n&&t.frag){const e=t.frag.start,r=Em(null,n.fragments,e);if(r&&!r.gap)return!0}if(r&&e.errors.length<r.errors.length){const r=e.errors[e.errors.length-1];if(n&&r.frag&&t.frag&&Math.abs(r.frag.start-t.frag.start)>3*n.targetduration)return!0}return!1}class Dm{constructor(e,t){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=Zf.log.bind(Zf,`${t}:`),this.warn=Zf.warn.bind(Zf,`${t}:`),this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){clearTimeout(this.timer),this.timer=-1}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t){const r=null==t?void 0:t.renditionReports;if(r){let n=-1;for(let s=0;s<r.length;s++){const i=r[s];let a;try{a=new self.URL(i.URI,t.url).href}catch(e){Zf.warn(`Could not construct new URL for Rendition Report: ${e}`),a=i.URI||""}if(a===e){n=s;break}a===e.substring(0,a.length)&&(n=s)}if(-1!==n){const e=r[n],s=parseInt(e["LAST-MSN"])||(null==t?void 0:t.lastPartSn);let i=parseInt(e["LAST-PART"])||(null==t?void 0:t.lastPartIndex);if(this.hls.config.lowLatencyMode){const e=Math.min(t.age-t.partTarget,t.targetduration);i>=0&&e>t.partTarget&&(i+=1)}return new am(s,i>=0?i:void 0,nm)}}}loadPlaylist(e){-1===this.requestScheduled&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}shouldReloadPlaylist(e){return-1===this.timer&&-1===this.requestScheduled&&this.shouldLoadPlaylist(e)}playlistLoaded(e,t,r){const{details:n,stats:s}=t,i=self.performance.now(),a=s.loading.first?Math.max(0,i-s.loading.first):0;if(n.advancedDateTime=Date.now()-a,n.live||null!=r&&r.live){if(n.reloaded(r),r&&this.log(`live playlist ${e} ${n.advanced?"REFRESHED "+n.lastPartSn+"-"+n.lastPartIndex:"MISSED"}`),r&&n.fragments.length>0&&dm(r,n),!this.canLoad||!n.live)return;let a,o,l;if(n.canBlockReload&&n.endSN&&n.advanced){const e=this.hls.config.lowLatencyMode,s=n.lastPartSn,i=n.endSN,c=n.lastPartIndex,d=s===i,u=e?0:c;-1!==c?(o=d?i+1:s,l=d?u:c+1):o=i+1;const h=n.age,f=h+n.ageHeader;let p=Math.min(f-n.partTarget,1.5*n.targetduration);if(p>0){if(r&&p>r.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${r.tuneInGoal} to: ${p} with playlist age: ${n.age}`),p=0;else{const e=Math.floor(p/n.targetduration);if(o+=e,void 0!==l){l+=Math.round(p%n.targetduration/n.partTarget)}this.log(`CDN Tune-in age: ${n.ageHeader}s last advanced ${h.toFixed(2)}s goal: ${p} skip sn ${e} to part ${l}`)}n.tuneInGoal=p}if(a=this.getDeliveryDirectives(n,t.deliveryDirectives,o,l),e||!d)return void this.loadPlaylist(a)}else n.canBlockReload&&(a=this.getDeliveryDirectives(n,t.deliveryDirectives,o,l));const c=this.hls.mainForwardBufferInfo,d=c?c.end-c.len:0,u=function(e,t=1/0){let r=1e3*e.targetduration;if(e.updated){const n=e.fragments,s=4;if(n.length&&r*s>t){const e=1e3*n[n.length-1].duration;e<r&&(r=e)}}else r/=2;return Math.round(r)}(n,1e3*(n.edge-d));n.updated&&i>this.requestScheduled+u&&(this.requestScheduled=s.loading.start),void 0!==o&&n.canBlockReload?this.requestScheduled=s.loading.first+u-(1e3*n.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+u<i?this.requestScheduled=i:this.requestScheduled-i<=0&&(this.requestScheduled+=u);let h=this.requestScheduled-i;h=Math.max(0,h),this.log(`reload live playlist ${e} in ${Math.round(h)} ms`),this.timer=self.setTimeout((()=>this.loadPlaylist(a)),h)}else this.clearTimer()}getDeliveryDirectives(e,t,r,n){let s=function(e,t){const{canSkipUntil:r,canSkipDateRanges:n,endSN:s}=e;return r&&(void 0!==t?t-s:0)<r?n?im:sm:nm}(e,r);return null!=t&&t.skip&&e.deltaUpdateFailed&&(r=t.msn,n=t.part,s=nm),new am(r,n,s)}checkRetry(e){const t=e.details,r=gm(e),n=e.errorAction,{action:s,retryCount:i=0,retryConfig:a}=n||{},o=!!n&&!!a&&(s===Am||!n.resolved&&s===km);if(o){var l;if(this.requestScheduled=-1,i>=a.maxNumRetry)return!1;if(r&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${i+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const e=ym(a,i);this.timer=self.setTimeout((()=>this.loadPlaylist()),e),this.warn(`Retrying playlist loading ${i+1}/${a.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,n.resolved=!0}return o}}let xm;class Om extends Dm{constructor(e,t){super(e,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Vf.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Vf.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Vf.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Vf.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(Vf.FRAG_LOADED,this.onFragLoaded,this),e.on(Vf.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Vf.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Vf.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Vf.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Vf.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(Vf.FRAG_LOADED,this.onFragLoaded,this),e.off(Vf.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}startLoad(){this._levels.forEach((e=>{e.loadError=0,e.fragmentError=0})),super.startLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[]}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const r=[],n={};let s;t.levels.forEach((e=>{var t;const i=e.attrs;-1!==(null==(t=e.audioCodec)?void 0:t.indexOf("mp4a.40.34"))&&(xm||(xm=/chrome|firefox/i.test(navigator.userAgent)),xm&&(e.audioCodec=void 0));const{AUDIO:a,CODECS:o,"FRAME-RATE":l,"PATHWAY-ID":c,RESOLUTION:d,SUBTITLES:u}=i,h=`${`${c||"."}-`}${e.bitrate}-${d}-${l}-${o}`;s=n[h],s?s.addFallback(e):(s=new om(e),n[h]=s,r.push(s)),Pm(s,"audio",a),Pm(s,"text",u)})),this.filterAndSortMediaOptions(r,t)}filterAndSortMediaOptions(e,t){let r=[],n=[],s=!1,i=!1,a=!1,o=e.filter((({audioCodec:e,videoCodec:t,width:r,height:n,unknownCodecs:o})=>(s||(s=!(!r||!n)),i||(i=!!t),a||(a=!!e),!(null!=o&&o.length)&&(!e||wg(e,"audio"))&&(!t||wg(t,"video")))));if((s||i)&&a&&(o=o.filter((({videoCodec:e,width:t,height:r})=>!!e||!(!t||!r)))),0===o.length)return void Promise.resolve().then((()=>{if(this.hls){const e=new Error("no level with compatible codecs found in manifest");this.hls.trigger(Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:e,reason:e.message})}}));t.audioTracks&&(r=t.audioTracks.filter((e=>!e.audioCodec||wg(e.audioCodec,"audio"))),Mm(r)),t.subtitles&&(n=t.subtitles,Mm(n));const l=o.slice(0);o.sort(((e,t)=>e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"]?(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1:e.bitrate!==t.bitrate?e.bitrate-t.bitrate:e.attrs["FRAME-RATE"]!==t.attrs["FRAME-RATE"]?e.attrs.decimalFloatingPoint("FRAME-RATE")-t.attrs.decimalFloatingPoint("FRAME-RATE"):e.attrs.SCORE!==t.attrs.SCORE?e.attrs.decimalFloatingPoint("SCORE")-t.attrs.decimalFloatingPoint("SCORE"):s&&e.height!==t.height?e.height-t.height:0));let c=l[0];if(this.steering&&(o=this.steering.filterParsedLevels(o),o.length!==l.length))for(let e=0;e<l.length;e++)if(l[e].pathwayId===o[0].pathwayId){c=l[e];break}this._levels=o;for(let e=0;e<o.length;e++)if(o[e]===c){this._firstLevel=e,this.log(`manifest loaded, ${o.length} level(s) found, first bitrate: ${c.bitrate}`);break}const d=a&&!i,u={levels:o,audioTracks:r,subtitleTracks:n,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:a,video:i,altAudio:!d&&r.some((e=>!!e.url))};this.hls.trigger(Vf.MANIFEST_PARSED,u),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return 0===this._levels.length?null:this._levels}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){const r=new Error("invalid level idx"),n=e<0;if(this.hls.trigger(Vf.ERROR,{type:zf.OTHER_ERROR,details:Wf.LEVEL_SWITCH_ERROR,level:e,fatal:n,error:r,reason:r.message}),n)return;e=Math.min(e,t.length-1)}const r=this.currentLevelIndex,n=this.currentLevel,s=n?n.attrs["PATHWAY-ID"]:void 0,i=t[e],a=i.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=i,r===e&&i.details&&n&&s===a)return;this.log(`Switching to level ${e}${a?" with Pathway "+a:""} from level ${r}${s?" with Pathway "+s:""}`);const o=Gf({},i,{level:e,maxBitrate:i.maxBitrate,attrs:i.attrs,uri:i.uri,urlId:i.urlId});delete o._attrs,delete o._urlId,this.hls.trigger(Vf.LEVEL_SWITCHING,o);const l=i.details;if(!l||l.live){const e=this.switchParams(i.uri,null==n?void 0:n.details);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){const e=this.hls.config.startLevel;return void 0!==e?e:this._firstLevel}return this._startLevel}set startLevel(e){this._startLevel=e}onError(e,t){!t.fatal&&t.context&&t.context.type===Mg&&t.context.level===this.level&&this.checkRetry(t)}onFragLoaded(e,{frag:t}){if(void 0!==t&&t.type===Ng){const e=this._levels[t.level];void 0!==e&&(e.loadError=0)}}onLevelLoaded(e,t){var r;const{level:n,details:s}=t,i=this._levels[n];var a;if(!i)return this.warn(`Invalid level index ${n}`),void(null!=(a=t.deliveryDirectives)&&a.skip&&(s.deltaUpdateFailed=!0));n===this.currentLevelIndex?(0===i.fragmentError&&(i.loadError=0),this.playlistLoaded(n,t,i.details)):null!=(r=t.deliveryDirectives)&&r.skip&&(s.deltaUpdateFailed=!0)}onAudioTrackSwitched(e,t){const r=this.currentLevel;if(!r)return;const n=this.hls.audioTracks[t.id].groupId;if(r.audioGroupIds&&r.audioGroupId!==n){let e=-1;for(let t=0;t<r.audioGroupIds.length;t++)if(r.audioGroupIds[t]===n){e=t;break}-1!==e&&e!==r.urlId&&(r.urlId=e,this.canLoad&&this.startLoad())}}loadPlaylist(e){super.loadPlaylist();const t=this.currentLevelIndex,r=this.currentLevel;if(r&&this.shouldLoadPlaylist(r)){const n=r.urlId;let s=r.uri;if(e)try{s=e.addDirectives(s)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}const i=r.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""} with${i?" Pathway "+i:""} URI ${n+1}/${r.url.length} ${s}`),this.clearTimer(),this.hls.trigger(Vf.LEVEL_LOADING,{url:s,level:t,id:n,deliveryDirectives:e||null})}}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e,t){const r=(e,r)=>r!==t,n=this._levels.filter(((n,s)=>s!==e||(n.url.length>1&&void 0!==t?(n.url=n.url.filter(r),n.audioGroupIds&&(n.audioGroupIds=n.audioGroupIds.filter(r)),n.textGroupIds&&(n.textGroupIds=n.textGroupIds.filter(r)),n.urlId=0,!0):(this.steering&&this.steering.removeLevel(n),!1))));this.hls.trigger(Vf.LEVELS_UPDATED,{levels:n})}onLevelsUpdated(e,{levels:t}){t.forEach(((e,t)=>{const{details:r}=e;null!=r&&r.fragments&&r.fragments.forEach((e=>{e.level=t}))})),this._levels=t}}function Pm(e,t,r){r&&("audio"===t?(e.audioGroupIds||(e.audioGroupIds=[]),e.audioGroupIds[e.url.length-1]=r):"text"===t&&(e.textGroupIds||(e.textGroupIds=[]),e.textGroupIds[e.url.length-1]=r))}function Mm(e){const t={};e.forEach((e=>{const r=e.groupId||"";e.id=t[r]=t[r]||0,t[r]++}))}var Fm="NOT_LOADED",Um="APPENDING",Nm="PARTIAL",Bm="OK";class jm{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(Vf.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Vf.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Vf.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(Vf.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Vf.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Vf.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const r=this.activePartLists[t];if(r)for(let t=r.length;t--;){const n=r[t];if(!n)break;const s=n.end;if(n.start<=e&&null!==s&&e<=s)return n}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){const{fragments:r}=this,n=Object.keys(r);for(let s=n.length;s--;){const i=r[n[s]];if((null==i?void 0:i.body.type)===t&&i.buffered){const t=i.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,r,n){this.timeRanges&&(this.timeRanges[e]=t);const s=(null==n?void 0:n.fragment.sn)||-1;Object.keys(this.fragments).forEach((n=>{const i=this.fragments[n];if(!i)return;if(s>=i.body.sn)return;if(!i.buffered&&!i.loaded)return void(i.body.type===r&&this.removeFragment(i.body));const a=i.range[e];a&&a.time.some((e=>{const r=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return r&&this.removeFragment(i.body),r}))}))}detectPartialFragments(e){const t=this.timeRanges,{frag:r,part:n}=e;if(!t||"initSegment"===r.sn)return;const s=qm(r),i=this.fragments[s];if(!i||i.buffered&&r.gap)return;const a=!r.relurl;Object.keys(t).forEach((e=>{const s=r.elementaryStreams[e];if(!s)return;const o=t[e],l=a||!0===s.partial;i.range[e]=this.getBufferedTimes(r,n,l,o)})),i.loaded=null,Object.keys(i.range).length?(i.buffered=!0,i.body.endList&&(this.endListFragments[i.body.type]=i),$m(i)||this.removeParts(r.sn-1,r.type)):this.removeFragment(i.body)}removeParts(e,t){const r=this.activePartLists[t];r&&(this.activePartLists[t]=r.filter((t=>t.fragment.sn>=e)))}fragBuffered(e,t){const r=qm(e);let n=this.fragments[r];!n&&t&&(n=this.fragments[r]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),n&&(n.loaded=null,n.buffered=!0)}getBufferedTimes(e,t,r,n){const s={time:[],partial:r},i=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||i;for(let e=0;e<n.length;e++){const t=n.start(e)-this.bufferPadding,r=n.end(e)+this.bufferPadding;if(l>=t&&o<=r){s.time.push({startPTS:Math.max(i,n.start(e)),endPTS:Math.min(a,n.end(e))});break}if(i<r&&a>t)s.partial=!0,s.time.push({startPTS:Math.max(i,n.start(e)),endPTS:Math.min(a,n.end(e))});else if(a<=t)break}return s}getPartialFragment(e){let t,r,n,s=null,i=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach((l=>{const c=o[l];c&&$m(c)&&(r=c.body.start-a,n=c.body.end+a,e>=r&&e<=n&&(t=Math.min(e-r,n-e),i<=t&&(s=c.body,i=t)))})),s}isEndListAppended(e){const t=this.endListFragments[e];return void 0!==t&&(t.buffered||$m(t))}getState(e){const t=qm(e),r=this.fragments[t];return r?r.buffered?$m(r)?Nm:Bm:Um:Fm}isTimeBuffered(e,t,r){let n,s;for(let i=0;i<r.length;i++){if(n=r.start(i)-this.bufferPadding,s=r.end(i)+this.bufferPadding,e>=n&&t<=s)return!0;if(t<=n)return!1}return!1}onFragLoaded(e,t){const{frag:r,part:n}=t;if("initSegment"===r.sn||r.bitrateTest)return;const s=n?null:t,i=qm(r);this.fragments[i]={body:r,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:r,part:n,timeRanges:s}=t;if("initSegment"===r.sn)return;const i=r.type;if(n){let e=this.activePartLists[i];e||(this.activePartLists[i]=e=[]),e.push(n)}this.timeRanges=s,Object.keys(s).forEach((e=>{const t=s[e];this.detectEvictedFragments(e,t,i,n)}))}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=qm(e);return!!this.fragments[t]}hasParts(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}removeFragmentsInRange(e,t,r,n,s){n&&!this.hasGaps||Object.keys(this.fragments).forEach((i=>{const a=this.fragments[i];if(!a)return;const o=a.body;o.type!==r||n&&!o.gap||o.start<t&&o.end>e&&(a.buffered||s)&&this.removeFragment(o)}))}removeFragment(e){const t=qm(e);e.stats.loaded=0,e.clearElementaryStreamInfo();const r=this.activePartLists[e.type];if(r){const t=e.sn;this.activePartLists[e.type]=r.filter((e=>e.fragment.sn!==t))}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function $m(e){var t,r,n;return e.buffered&&(e.body.gap||(null==(t=e.range.video)?void 0:t.partial)||(null==(r=e.range.audio)?void 0:r.partial)||(null==(n=e.range.audiovideo)?void 0:n.partial))}function qm(e){return`${e.type}_${e.level}_${e.urlId}_${e.sn}`}const Km=Math.pow(2,17);class Gm{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const r=e.url;if(!r)return Promise.reject(new zm({type:zf.NETWORK_ERROR,details:Wf.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(r?"part list":"url")),networkDetails:null}));this.abort();const n=this.config,s=n.fLoader,i=n.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some((e=>"GAP"===e[0])))return void o(Vm(e));e.gap=!1}const l=this.loader=e.loader=s?new s(n):new i(n),c=Hm(e),d=vm(n.fragLoadPolicy.default),u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:Km};e.stats=l.stats,l.load(c,u,{onSuccess:(t,r,n,s)=>{this.resetLoader(e,l);let i=t.data;n.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(i.slice(0,16)),i=i.slice(16)),a({frag:e,part:null,payload:i,networkDetails:s})},onError:(t,n,s,i)=>{this.resetLoader(e,l),o(new zm({type:zf.NETWORK_ERROR,details:Wf.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:qf({url:r,data:void 0},t),error:new Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:s,stats:i}))},onAbort:(t,r,n)=>{this.resetLoader(e,l),o(new zm({type:zf.NETWORK_ERROR,details:Wf.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:n,stats:t}))},onTimeout:(t,r,n)=>{this.resetLoader(e,l),o(new zm({type:zf.NETWORK_ERROR,details:Wf.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:n,stats:t}))},onProgress:(r,n,s,i)=>{t&&t({frag:e,part:null,payload:s,networkDetails:i})}})}))}loadPart(e,t,r){this.abort();const n=this.config,s=n.fLoader,i=n.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void o(Vm(e,t));const l=this.loader=e.loader=s?new s(n):new i(n),c=Hm(e,t),d=vm(n.fragLoadPolicy.default),u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Km};t.stats=l.stats,l.load(c,u,{onSuccess:(n,s,i,o)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const c={frag:e,part:t,payload:n.data,networkDetails:o};r(c),a(c)},onError:(r,n,s,i)=>{this.resetLoader(e,l),o(new zm({type:zf.NETWORK_ERROR,details:Wf.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:qf({url:c.url,data:void 0},r),error:new Error(`HTTP Error ${r.code} ${r.text}`),networkDetails:s,stats:i}))},onAbort:(r,n,s)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),o(new zm({type:zf.NETWORK_ERROR,details:Wf.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:s,stats:r}))},onTimeout:(r,n,s)=>{this.resetLoader(e,l),o(new zm({type:zf.NETWORK_ERROR,details:Wf.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:s,stats:r}))}})}))}updateStatsFromPart(e,t){const r=e.stats,n=t.stats,s=n.total;if(r.loaded+=n.loaded,s){const n=Math.round(e.duration/t.duration),i=Math.min(Math.round(r.loaded/s),n),a=(n-i)*Math.round(r.loaded/i);r.total=r.loaded+a}else r.total=Math.max(r.loaded,r.total);const i=r.loading,a=n.loading;i.start?i.first+=a.first-a.start:(i.start=a.start,i.first=a.first),i.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Hm(e,t=null){const r=t||e,n={frag:e,part:t,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},s=r.byteRangeStartOffset,i=r.byteRangeEndOffset;if(Hf(s)&&Hf(i)){var a;let t=s,r=i;if("initSegment"===e.sn&&"AES-128"===(null==(a=e.decryptdata)?void 0:a.method)){const e=i-s;e%16&&(r=i+(16-e%16)),0!==s&&(n.resetIV=!0,t=s-16)}n.rangeStart=t,n.rangeEnd=r}return n}function Vm(e,t){const r=new Error(`GAP ${e.gap?"tag":"attribute"} found`),n={type:zf.MEDIA_ERROR,details:Wf.FRAG_GAP,fatal:!1,frag:e,error:r,networkDetails:null};return t&&(n.part=t),(t||e).stats.aborted=!0,new zm(n)}class zm extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Wm{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const t in this.keyUriToKeyInfo){const r=this.keyUriToKeyInfo[t].loader;if(r){if(e&&e!==r.context.frag.type)return;r.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=Wf.KEY_LOAD_ERROR,r,n,s){return new zm({type:zf.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:s,error:r,networkDetails:n})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:r,cc:n}=e;for(let e=0;e<t.length;e++){const s=t[e];if(n<=s.cc&&("initSegment"===r||"initSegment"===s.sn||r<s.sn)){this.emeController.selectKeySystemFormat(s).then((e=>{s.setKeyFormat(e)}));break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then((t=>this.loadInternal(e,t))):this.loadInternal(e)}loadInternal(e,t){var r,n;t&&e.setKeyFormat(t);const s=e.decryptdata;if(!s){const r=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,Wf.KEY_LOAD_ERROR,r))}const i=s.uri;if(!i)return Promise.reject(this.createKeyLoadError(e,Wf.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${i}"`)));let a=this.keyUriToKeyInfo[i];if(null!=(r=a)&&r.decryptdata.key)return s.key=a.decryptdata.key,Promise.resolve({frag:e,keyInfo:a});var o;if(null!=(n=a)&&n.keyLoadPromise)switch(null==(o=a.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then((t=>(s.key=t.keyInfo.decryptdata.key,{frag:e,keyInfo:a})))}switch(a=this.keyUriToKeyInfo[i]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===s.keyFormat?this.loadKeyHTTP(a,e):this.loadKeyEME(a,e);case"AES-128":return this.loadKeyHTTP(a,e);default:return Promise.reject(this.createKeyLoadError(e,Wf.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(e,t){const r={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const t=this.emeController.loadKey(r);if(t)return(e.keyLoadPromise=t.then((t=>(e.mediaKeySessionContext=t,r)))).catch((t=>{throw e.keyLoadPromise=null,t}))}return Promise.resolve(r)}loadKeyHTTP(e,t){const r=this.config,n=new(0,r.loader)(r);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise(((s,i)=>{const a={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},o=r.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(e,t,r,n)=>{const{frag:a,keyInfo:o,url:l}=r;if(!a.decryptdata||o!==this.keyUriToKeyInfo[l])return i(this.createKeyLoadError(a,Wf.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),n));o.decryptdata.key=a.decryptdata.key=new Uint8Array(e.data),a.keyLoader=null,o.loader=null,s({frag:a,keyInfo:o})},onError:(e,r,n,s)=>{this.resetLoader(r),i(this.createKeyLoadError(t,Wf.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),n,qf({url:a.url,data:void 0},e)))},onTimeout:(e,r,n)=>{this.resetLoader(r),i(this.createKeyLoadError(t,Wf.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),n))},onAbort:(e,r,n)=>{this.resetLoader(r),i(this.createKeyLoadError(t,Wf.INTERNAL_ABORTED,new Error("key loading aborted"),n))}};n.load(a,l,c)}))}resetLoader(e){const{frag:t,keyInfo:r,url:n}=e,s=r.loader;t.keyLoader===s&&(t.keyLoader=null,r.loader=null),delete this.keyUriToKeyInfo[n],s&&s.destroy()}}const Ym={length:0,start:()=>0,end:()=>0};class Qm{static isBuffered(e,t){try{if(e){const r=Qm.getBuffered(e);for(let e=0;e<r.length;e++)if(t>=r.start(e)&&t<=r.end(e))return!0}}catch(e){}return!1}static bufferInfo(e,t,r){try{if(e){const n=Qm.getBuffered(e),s=[];let i;for(i=0;i<n.length;i++)s.push({start:n.start(i),end:n.end(i)});return this.bufferedInfo(s,t,r)}}catch(e){}return{len:0,start:t,end:t,nextStart:void 0}}static bufferedInfo(e,t,r){t=Math.max(0,t),e.sort((function(e,t){const r=e.start-t.start;return r||t.end-e.end}));let n=[];if(r)for(let t=0;t<e.length;t++){const s=n.length;if(s){const i=n[s-1].end;e[t].start-i<r?e[t].end>i&&(n[s-1].end=e[t].end):n.push(e[t])}else n.push(e[t])}else n=e;let s,i=0,a=t,o=t;for(let e=0;e<n.length;e++){const l=n[e].start,c=n[e].end;if(t+r>=l&&t<c)a=l,o=c,i=o-t;else if(t+r<l){s=l;break}}return{len:i,start:a||0,end:o||0,nextStart:s}}static getBuffered(e){try{return e.buffered}catch(e){return Zf.log("failed to get media.buffered",e),Ym}}}class Xm{constructor(e,t,r,n=0,s=-1,i=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=r,this.size=n,this.part=s,this.partial=i}}function Jm(e,t){let r=null;for(let n=0,s=e.length;n<s;n++){const s=e[n];if(s&&s.cc===t){r=s;break}}return r}function Zm(e,t){if(e){const r=e.start+t;e.start=e.startPTS=r,e.endPTS=r+e.duration}}function ey(e,t){const r=t.fragments;for(let t=0,n=r.length;t<n;t++)Zm(r[t],e);t.fragmentHint&&Zm(t.fragmentHint,e),t.alignedSliding=!0}function ty(e,t,r){t&&(!function(e,t,r){if(function(e,t,r){return!(!t.details||!(r.endCC>r.startCC||e&&e.cc<r.startCC))}(e,r,t)){const e=function(e,t,r=0){const n=e.fragments,s=t.fragments;if(!s.length||!n.length)return void Zf.log("No fragments to align");const i=Jm(n,s[0].cc);if(i&&(!i||i.startPTS))return i;Zf.log("No frag in previous level to align on")}(r.details,t);e&&Hf(e.start)&&(Zf.log(`Adjusting PTS using last level due to CC increase within current level ${t.url}`),ey(e.start,t))}}(e,r,t),!r.alignedSliding&&t.details&&function(e,t){if(!t.fragments.length||!e.hasProgramDateTime||!t.hasProgramDateTime)return;const r=t.fragments[0].programDateTime,n=e.fragments[0].programDateTime,s=(n-r)/1e3+t.fragments[0].start;s&&Hf(s)&&(Zf.log(`Adjusting PTS using programDateTime delta ${n-r}ms, sliding:${s.toFixed(3)} ${e.url} `),ey(s,e))}(r,t.details),r.alignedSliding||!t.details||r.skippedSegments||um(t.details,r))}function ry(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;const r=e.fragments,n=t.fragments;if(!r.length||!n.length)return;const s=n[Math.round(n.length/2)-1],i=Jm(r,s.cc)||r[Math.round(r.length/2)-1],a=s.programDateTime,o=i.programDateTime;if(null===a||null===o)return;ey((o-a)/1e3-(i.start-s.start),e)}class ny{constructor(e,t){this.subtle=void 0,this.aesIV=void 0,this.subtle=e,this.aesIV=t}decrypt(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)}}class sy{constructor(e,t){this.subtle=void 0,this.key=void 0,this.subtle=e,this.key=t}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}class iy{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),r=new Uint32Array(4);for(let e=0;e<4;e++)r[e]=t.getUint32(4*e);return r}initTable(){const e=this.sBox,t=this.invSBox,r=this.subMix,n=r[0],s=r[1],i=r[2],a=r[3],o=this.invSubMix,l=o[0],c=o[1],d=o[2],u=o[3],h=new Uint32Array(256);let f=0,p=0,g=0;for(g=0;g<256;g++)h[g]=g<128?g<<1:g<<1^283;for(g=0;g<256;g++){let r=p^p<<1^p<<2^p<<3^p<<4;r=r>>>8^255&r^99,e[f]=r,t[r]=f;const o=h[f],g=h[o],m=h[g];let y=257*h[r]^16843008*r;n[f]=y<<24|y>>>8,s[f]=y<<16|y>>>16,i[f]=y<<8|y>>>24,a[f]=y,y=16843009*m^65537*g^257*o^16843008*f,l[r]=y<<24|y>>>8,c[r]=y<<16|y>>>16,d[r]=y<<8|y>>>24,u[r]=y,f?(f=o^h[h[h[m^o]]],p^=h[h[p]]):f=p=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let r=!0,n=0;for(;n<t.length&&r;)r=t[n]===this.key[n],n++;if(r)return;this.key=t;const s=this.keySize=t.length;if(4!==s&&6!==s&&8!==s)throw new Error("Invalid aes key size="+s);const i=this.ksRows=4*(s+6+1);let a,o;const l=this.keySchedule=new Uint32Array(i),c=this.invKeySchedule=new Uint32Array(i),d=this.sBox,u=this.rcon,h=this.invSubMix,f=h[0],p=h[1],g=h[2],m=h[3];let y,v;for(a=0;a<i;a++)a<s?y=l[a]=t[a]:(v=y,a%s==0?(v=v<<8|v>>>24,v=d[v>>>24]<<24|d[v>>>16&255]<<16|d[v>>>8&255]<<8|d[255&v],v^=u[a/s|0]<<24):s>6&&a%s==4&&(v=d[v>>>24]<<24|d[v>>>16&255]<<16|d[v>>>8&255]<<8|d[255&v]),l[a]=y=(l[a-s]^v)>>>0);for(o=0;o<i;o++)a=i-o,v=3&o?l[a]:l[a-4],c[o]=o<4||a<=4?v:f[d[v>>>24]]^p[d[v>>>16&255]]^g[d[v>>>8&255]]^m[d[255&v]],c[o]=c[o]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}decrypt(e,t,r){const n=this.keySize+6,s=this.invKeySchedule,i=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],c=a[2],d=a[3],u=this.uint8ArrayToUint32Array_(r);let h=u[0],f=u[1],p=u[2],g=u[3];const m=new Int32Array(e),y=new Int32Array(m.length);let v,b,w,E,S,T,C,k,A,I,_,R,L,D;const x=this.networkToHostOrderSwap;for(;t<m.length;){for(A=x(m[t]),I=x(m[t+1]),_=x(m[t+2]),R=x(m[t+3]),S=A^s[0],T=R^s[1],C=_^s[2],k=I^s[3],L=4,D=1;D<n;D++)v=o[S>>>24]^l[T>>16&255]^c[C>>8&255]^d[255&k]^s[L],b=o[T>>>24]^l[C>>16&255]^c[k>>8&255]^d[255&S]^s[L+1],w=o[C>>>24]^l[k>>16&255]^c[S>>8&255]^d[255&T]^s[L+2],E=o[k>>>24]^l[S>>16&255]^c[T>>8&255]^d[255&C]^s[L+3],S=v,T=b,C=w,k=E,L+=4;v=i[S>>>24]<<24^i[T>>16&255]<<16^i[C>>8&255]<<8^i[255&k]^s[L],b=i[T>>>24]<<24^i[C>>16&255]<<16^i[k>>8&255]<<8^i[255&S]^s[L+1],w=i[C>>>24]<<24^i[k>>16&255]<<16^i[S>>8&255]<<8^i[255&T]^s[L+2],E=i[k>>>24]<<24^i[S>>16&255]<<16^i[T>>8&255]<<8^i[255&C]^s[L+3],y[t]=x(v^h),y[t+1]=x(E^f),y[t+2]=x(w^p),y[t+3]=x(b^g),h=A,f=I,p=_,g=R,t+=4}return y.buffer}}class ay{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.useSoftware=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch(e){}null===this.subtle&&(this.useSoftware=!0)}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const r=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?function(e){const t=e.byteLength,r=t&&new DataView(e.buffer).getUint8(t-1);return r?Ap(e,0,t-r):e}(r):r}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,r){return this.useSoftware?new Promise(((n,s)=>{this.softwareDecrypt(new Uint8Array(e),t,r);const i=this.flush();i?n(i.buffer):s(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(e),t,r)}softwareDecrypt(e,t,r){const{currentIV:n,currentResult:s,remainderData:i}=this;this.logOnce("JS AES decrypt"),i&&(e=ng(i,e),this.remainderData=null);const a=this.getValidChunk(e);if(!a.length)return null;n&&(r=n);let o=this.softwareDecrypter;o||(o=this.softwareDecrypter=new iy),o.expandKey(t);const l=s;return this.currentResult=o.decrypt(a.buffer,0,r),this.currentIV=Ap(a,-16).buffer,l||null}webCryptoDecrypt(e,t,r){const n=this.subtle;return this.key===t&&this.fastAesKey||(this.key=t,this.fastAesKey=new sy(n,t)),this.fastAesKey.expandKey().then((t=>{if(!n)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new ny(n,new Uint8Array(r)).decrypt(e.buffer,t)})).catch((n=>(Zf.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,r))))}onWebCryptoError(e,t,r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,r);const n=this.flush();if(n)return n.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(e){let t=e;const r=e.length-e.length%16;return r!==e.length&&(t=Ap(e,0,r),this.remainderData=Ap(e,r)),t}logOnce(e){this.logEnabled&&(Zf.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const oy=function(e){let t="";const r=e.length;for(let n=0;n<r;n++)t+=`[${e.start(n).toFixed(3)}-${e.end(n).toFixed(3)}]`;return t},ly="STOPPED",cy="IDLE",dy="KEY_LOADING",uy="FRAG_LOADING",hy="FRAG_LOADING_WAITING_RETRY",fy="WAITING_TRACK",py="PARSING",gy="PARSED",my="ENDED",yy="ERROR",vy="WAITING_INIT_PTS",by="WAITING_LEVEL";class wy extends class{constructor(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}{constructor(e,t,r,n,s){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=ly,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.loadedmetadata=!1,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.onvseeking=null,this.onvended=null,this.logPrefix="",this.log=void 0,this.warn=void 0,this.playlistType=s,this.logPrefix=n,this.log=Zf.log.bind(Zf,`${n}:`),this.warn=Zf.warn.bind(Zf,`${n}:`),this.hls=e,this.fragmentLoader=new Gm(e.config),this.keyLoader=r,this.fragmentTracker=t,this.config=e.config,this.decrypter=new ay(e.config),e.on(Vf.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=ly}_streamEnded(e,t){if(t.live||e.nextStart||!e.end||!this.media)return!1;const r=t.partList;if(null!=r&&r.length){const e=r[r.length-1];return Qm.isBuffered(this.media,e.start+e.duration/2)}const n=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(n)}getLevelDetails(){var e;if(this.levels&&null!==this.levelLastLoaded)return null==(e=this.levels[this.levelLastLoaded])?void 0:e.details}onMediaAttached(e,t){const r=this.media=this.mediaBuffer=t.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),r.addEventListener("seeking",this.onvseeking),r.addEventListener("ended",this.onvended);const n=this.config;this.levels&&n.autoStartLoad&&this.state===ly&&this.startLoad(n.startPosition)}onMediaDetaching(){const e=this.media;null!=e&&e.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),e&&this.onvseeking&&this.onvended&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}onMediaSeeking(){const{config:e,fragCurrent:t,media:r,mediaBuffer:n,state:s}=this,i=r?r.currentTime:0,a=Qm.bufferInfo(n||r,i,e.maxBufferHole);if(this.log(`media seeking to ${Hf(i)?i.toFixed(3):i}, state: ${s}`),this.state===my)this.resetLoadingState();else if(t){const r=e.maxFragLookUpTolerance,n=t.start-r,s=t.start+t.duration+r;if(!a.len||s<a.start||n>a.end){const e=i>s;(i<n||e)&&(e&&t.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}r&&(this.fragmentTracker.removeFragmentsInRange(i,1/0,this.playlistType,!0),this.lastCurrentTime=i),this.loadedmetadata||a.len||(this.nextLoadPosition=this.startPosition=i),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.stopLoad(),super.onHandlerDestroying()}onHandlerDestroyed(){this.state=ly,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,r){this._loadFragForPlayback(e,t,r)}_loadFragForPlayback(e,t,r){this._doFragLoad(e,t,r,(t=>{if(this.fragContextChanged(e))return this.warn(`Fragment ${e.sn}${t.part?" p: "+t.part.index:""} of level ${e.level} was dropped during download.`),void this.fragmentTracker.removeFragment(e);e.stats.chunkCount++,this._handleFragmentLoadProgress(t)})).then((t=>{if(!t)return;const r=this.state;this.fragContextChanged(e)?(r===uy||!this.fragCurrent&&r===py)&&(this.fragmentTracker.removeFragment(e),this.state=cy):("payload"in t&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(Vf.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))})).catch((t=>{this.state!==ly&&this.state!==yy&&(this.warn(t),this.resetFragmentLoading(e))}))}clearTrackerIfNeeded(e){var t;const{fragmentTracker:r}=this;if(r.getState(e)===Um){const t=e.type,n=this.getFwdBufferInfo(this.mediaBuffer,t),s=Math.max(e.duration,n?n.len:this.config.maxBufferLength);this.reduceMaxBufferLength(s)&&r.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?r.removeAllFragments():r.hasParts(e.type)&&(r.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),r.getState(e)===Nm&&r.removeFragment(e))}flushMainBuffer(e,t,r=null){if(!(e-t))return;const n={startOffset:e,endOffset:t,type:r};this.hls.trigger(Vf.BUFFER_FLUSHING,n)}_loadInitSegment(e,t){this._doFragLoad(e,t).then((t=>{if(!t||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return t})).then((t=>{const{hls:r}=this,{payload:n}=t,s=e.decryptdata;if(n&&n.byteLength>0&&s&&s.key&&s.iv&&"AES-128"===s.method){const i=self.performance.now();return this.decrypter.decrypt(new Uint8Array(n),s.key.buffer,s.iv.buffer).catch((t=>{throw r.trigger(Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t})).then((n=>{const s=self.performance.now();return r.trigger(Vf.FRAG_DECRYPTED,{frag:e,payload:n,stats:{tstart:i,tdecrypt:s}}),t.payload=n,t}))}return t})).then((r=>{const{fragCurrent:n,hls:s,levels:i}=this;if(!i)throw new Error("init load aborted, missing levels");const a=e.stats;this.state=cy,t.fragmentError=0,e.data=new Uint8Array(r.payload),a.parsing.start=a.buffering.start=self.performance.now(),a.parsing.end=a.buffering.end=self.performance.now(),r.frag===n&&s.trigger(Vf.FRAG_BUFFERED,{stats:a,frag:n,part:null,id:e.type}),this.tick()})).catch((t=>{this.state!==ly&&this.state!==yy&&(this.warn(t),this.resetFragmentLoading(e))}))}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.level!==t.level||e.sn!==t.sn||e.urlId!==t.urlId}fragBufferedComplete(e,t){var r,n,s,i;const a=this.mediaBuffer?this.mediaBuffer:this.media;this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.playlistType===Ng?"level":"track"} ${e.level} (frag:[${(null!=(r=e.startPTS)?r:NaN).toFixed(3)}-${(null!=(n=e.endPTS)?n:NaN).toFixed(3)}] > buffer:${a?oy(Qm.getBuffered(a)):"(detached)"})`),this.state=cy,a&&(!this.loadedmetadata&&e.type==Ng&&a.buffered.length&&(null==(s=this.fragCurrent)?void 0:s.sn)===(null==(i=this.fragPrevious)?void 0:i.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:r,part:n,partsLoaded:s}=e,i=!s||0===s.length||s.some((e=>!e)),a=new Xm(r.level,r.sn,r.stats.chunkCount+1,0,n?n.index:-1,!i);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,r=null,n){var s;const i=null==t?void 0:t.details;if(!this.levels||!i)throw new Error(`frag load aborted, missing level${i?"":" detail"}s`);let a=null;if(!e.encrypted||null!=(s=e.decryptdata)&&s.key?!e.encrypted&&i.encryptedFragments.length&&this.keyLoader.loadClear(e,i.encryptedFragments):(this.log(`Loading key for ${e.sn} of [${i.startSN}-${i.endSN}], ${"[stream-controller]"===this.logPrefix?"level":"track"} ${e.level}`),this.state=dy,this.fragCurrent=e,a=this.keyLoader.load(e).then((e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(Vf.KEY_LOADED,e),this.state===dy&&(this.state=cy),e})),this.hls.trigger(Vf.KEY_LOADING,{frag:e}),null===this.fragCurrent&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))),r=Math.max(e.start,r||0),this.config.lowLatencyMode&&"initSegment"!==e.sn){const s=i.partList;if(s&&n){r>e.end&&i.fragmentHint&&(e=i.fragmentHint);const o=this.getNextPart(s,e,r);if(o>-1){const l=s[o];let c;return this.log(`Loading part sn: ${e.sn} p: ${l.index} cc: ${e.cc} of playlist [${i.startSN}-${i.endSN}] parts [0-${o}-${s.length-1}] ${"[stream-controller]"===this.logPrefix?"level":"track"}: ${e.level}, target: ${parseFloat(r.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=uy,c=a?a.then((r=>!r||this.fragContextChanged(r.frag)?null:this.doFragPartsLoad(e,l,t,n))).catch((e=>this.handleFragLoadError(e))):this.doFragPartsLoad(e,l,t,n).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(Vf.FRAG_LOADING,{frag:e,part:l,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):c}if(!e.url||this.loadedEndOfParts(s,r))return Promise.resolve(null)}}this.log(`Loading fragment ${e.sn} cc: ${e.cc} ${i?"of ["+i.startSN+"-"+i.endSN+"] ":""}${"[stream-controller]"===this.logPrefix?"level":"track"}: ${e.level}, target: ${parseFloat(r.toFixed(3))}`),Hf(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=uy;const o=this.config.progressive;let l;return l=o&&a?a.then((t=>!t||this.fragContextChanged(null==t?void 0:t.frag)?null:this.fragmentLoader.load(e,n))).catch((e=>this.handleFragLoadError(e))):Promise.all([this.fragmentLoader.load(e,o?n:void 0),a]).then((([e])=>(!o&&e&&n&&n(e),e))).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(Vf.FRAG_LOADING,{frag:e,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):l}doFragPartsLoad(e,t,r,n){return new Promise(((s,i)=>{var a;const o=[],l=null==(a=r.details)?void 0:a.partList,c=t=>{this.fragmentLoader.loadPart(e,t,n).then((n=>{o[t.index]=n;const i=n.part;this.hls.trigger(Vf.FRAG_LOADED,n);const a=fm(r,e.sn,t.index+1)||pm(l,e.sn,t.index+1);if(!a)return s({frag:e,part:i,partsLoaded:o});c(a)})).catch(i)};c(t)}))}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===Wf.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(Vf.ERROR,t)}else this.hls.trigger(Vf.ERROR,{type:zf.OTHER_ERROR,details:Wf.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==py)return void(this.fragCurrent||this.state===ly||this.state===yy||(this.state=cy));const{frag:r,part:n,level:s}=t,i=self.performance.now();r.stats.parsing.end=i,n&&(n.stats.parsing.end=i),this.updateLevelTiming(r,n,s,e.partial)}getCurrentContext(e){const{levels:t,fragCurrent:r}=this,{level:n,sn:s,part:i}=e;if(null==t||!t[n])return this.warn(`Levels object was unset while buffering fragment ${s} of level ${n}. The current chunk will not be buffered.`),null;const a=t[n],o=i>-1?fm(a,s,i):null,l=o?o.fragment:function(e,t,r){if(null==e||!e.details)return null;const n=e.details;let s=n.fragments[t-n.startSN];return s||(s=n.fragmentHint,s&&s.sn===t?s:t<n.startSN&&r&&r.sn===t?r:null)}(a,s,r);return l?(r&&r!==l&&(l.stats=r.stats),{frag:l,part:o,level:a}):null}bufferFragmentData(e,t,r,n,s){var i;if(!e||this.state!==py)return;const{data1:a,data2:o}=e;let l=a;if(a&&o&&(l=ng(a,o)),null==(i=l)||!i.length)return;const c={type:e.type,frag:t,part:r,chunkMeta:n,parent:t.type,data:l};if(this.hls.trigger(Vf.BUFFER_APPENDING,c),e.dropped&&e.independent&&!r){if(s)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!Qm.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);const r=t.currentTime,n=Qm.bufferInfo(t,r,0),s=e.duration,i=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),a=Math.max(Math.min(e.start-i,n.end-i),r+i);e.start-a>i&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){const r=this.getLoadPosition();return Hf(r)?this.getFwdBufferInfoAtPos(e,r,t):null}getFwdBufferInfoAtPos(e,t,r){const{config:{maxBufferHole:n}}=this,s=Qm.bufferInfo(e,t,n);if(0===s.len&&void 0!==s.nextStart){const i=this.fragmentTracker.getBufferedFrag(t,r);if(i&&s.nextStart<i.end)return Qm.bufferInfo(e,t,Math.max(s.nextStart,n))}return s}getMaxBufferLength(e){const{config:t}=this;let r;return r=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(r,t.maxMaxBufferLength)}reduceMaxBufferLength(e){const t=this.config,r=e||t.maxBufferLength;return t.maxMaxBufferLength>=r&&(t.maxMaxBufferLength/=2,this.warn(`Reduce max buffer length to ${t.maxMaxBufferLength}s`),!0)}getAppendedFrag(e,t=Ng){const r=this.fragmentTracker.getAppendedFrag(e,Ng);return r&&"fragment"in r?r.fragment:r}getNextFragment(e,t){const r=t.fragments,n=r.length;if(!n)return null;const{config:s}=this,i=r[0].start;let a;if(t.live){const i=s.initialLiveManifestSize;if(n<i)return this.warn(`Not enough fragments to start playback (have: ${n}, need: ${i})`),null;t.PTSKnown||this.startFragRequested||-1!==this.startPosition||(a=this.getInitialLiveFragment(t,r),this.startPosition=a?this.hls.liveSyncPosition||a.start:e)}else e<=i&&(a=r[0]);if(!a){const r=s.lowLatencyMode?t.partEnd:t.fragmentEnd;a=this.getFragmentAtPosition(e,r,t)}return this.mapToInitFragWhenRequired(a)}isLoopLoading(e,t){const r=this.fragmentTracker.getState(e);return(r===Bm||r===Nm&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,r,n,s){const i=e.gap,a=this.getNextFragment(this.nextLoadPosition,t);if(null===a)return a;if(e=a,i&&e&&!e.gap&&r.nextStart){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,n);if(null!==t&&r.len+t.len>=s)return this.log(`buffer full after gaps in "${n}" playlist starting at sn: ${e.sn}`),null}return e}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||null!=e&&e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,r){let n=-1,s=!1,i=!0;for(let a=0,o=e.length;a<o;a++){const o=e[a];if(i=i&&!o.independent,n>-1&&r<o.start)break;const l=o.loaded;l?n=-1:(s||o.independent||i)&&o.fragment===t&&(n=a),s=l}return n}loadedEndOfParts(e,t){const r=e[e.length-1];return r&&t>r.start&&r.loaded}getInitialLiveFragment(e,t){const r=this.fragPrevious;let n=null;if(r){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${r.programDateTime}`),n=function(e,t,r){if(null===t||!Array.isArray(e)||!e.length||!Hf(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;r=r||0;for(let n=0;n<e.length;++n){const s=e[n];if(Tm(t,r,s))return s}return null}(t,r.endProgramDateTime,this.config.maxFragLookUpTolerance)),!n){const s=r.sn+1;if(s>=e.startSN&&s<=e.endSN){const i=t[s-e.startSN];r.cc===i.cc&&(n=i,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=function(e,t){return wm(e,(e=>e.cc<t?1:e.cc>t?-1:0))}(t,r.cc),n&&this.log(`Live playlist, switching playlist, load frag with same CC: ${n.sn}`))}}else{const t=this.hls.liveSyncPosition;null!==t&&(n=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return n}getFragmentAtPosition(e,t,r){const{config:n}=this;let{fragPrevious:s}=this,{fragments:i,endSN:a}=r;const{fragmentHint:o}=r,l=n.maxFragLookUpTolerance,c=r.partList,d=!!(n.lowLatencyMode&&null!=c&&c.length&&o);let u;if(d&&o&&!this.bitrateTest&&(i=i.concat(o),a=o.sn),e<t){u=Em(s,i,e,e>t-l?0:l)}else u=i[i.length-1];if(u){const e=u.sn-r.startSN,t=this.fragmentTracker.getState(u);if((t===Bm||t===Nm&&u.gap)&&(s=u),s&&u.sn===s.sn&&(!d||c[0].fragment.sn>u.sn)){if(s&&u.level===s.level){const t=i[e+1];u=u.sn<a&&this.fragmentTracker.getState(t)!==Bm?t:null}}}return u}synchronizeToLiveEdge(e){const{config:t,media:r}=this;if(!r)return;const n=this.hls.liveSyncPosition,s=r.currentTime,i=e.fragments[0].start,a=e.edge,o=s>=i-t.maxFragLookUpTolerance&&s<=a;if(null!==n&&r.duration>n&&(s<n||!o)){const i=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!o&&r.readyState<4||s<a-i)&&(this.loadedmetadata||(this.nextLoadPosition=n),r.readyState&&(this.warn(`Playback: ${s.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${n.toFixed(3)}`),r.currentTime=n))}}alignPlaylists(e,t){const{levels:r,levelLastLoaded:n,fragPrevious:s}=this,i=null!==n?r[n]:null,a=e.fragments.length;if(!a)return this.warn("No fragments in live playlist"),0;const o=e.fragments[0].start,l=!t,c=e.alignedSliding&&Hf(o);if(l||!c&&!o){ty(s,i,e);const r=e.fragments[0].start;return this.log(`Live playlist sliding: ${r.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} prev-sn: ${s?s.sn:"na"} fragments: ${a}`),r}return o}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let r=this.startPosition;if(r<t&&(r=-1),-1===r||-1===this.lastCurrentTime){const n=null!==this.startTimeOffset,s=n?this.startTimeOffset:e.startTimeOffset;null!==s&&Hf(s)?(r=t+s,s<0&&(r+=e.totalduration),r=Math.min(Math.max(t,r),t+e.totalduration),this.log(`Start time offset ${s} found in ${n?"multivariant":"media"} playlist, adjust startPosition to ${r}`),this.startPosition=r):e.live?r=this.hls.liveSyncPosition||t:this.startPosition=r=0,this.lastCurrentTime=r}this.nextLoadPosition=r}getLoadPosition(){const{media:e}=this;let t=0;return this.loadedmetadata&&e?t=e.currentTime:this.nextLoadPosition&&(t=this.nextLoadPosition),t}handleFragLoadAborted(e,t){this.transmuxer&&"initSegment"!==e.sn&&e.stats.aborted&&(this.warn(`Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===hy)||(this.state=cy)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}const r=t.frag;if(!r||r.type!==e||!this.levels)return;var n;if(this.fragContextChanged(r))return void this.warn(`Frag load error must match current frag to retry ${r.url} > ${null==(n=this.fragCurrent)?void 0:n.url}`);const s=t.details===Wf.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(r,!0);const i=t.errorAction,{action:a,retryCount:o=0,retryConfig:l}=i||{};if(i&&a===Am&&l){var c;this.resetStartWhenNotLoaded(null!=(c=this.levelLastLoaded)?c:r.level);const n=ym(l,o);this.warn(`Fragment ${r.sn} of ${e} ${r.level} errored with ${t.details}, retrying loading ${o+1}/${l.maxNumRetry} in ${n}ms`),i.resolved=!0,this.retryDate=self.performance.now()+n,this.state=hy}else l&&i?(this.resetFragmentErrors(e),o<l.maxNumRetry?s||(i.resolved=!0):Zf.warn(`${t.details} reached or exceeded max retry (${o})`)):(null==i?void 0:i.action)===km?this.state=by:this.state=yy;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===py||this.state===gy){const t=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,t),n=r&&r.len>.5;n&&this.reduceMaxBufferLength(r.len);const s=!n;return s&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${t} buffer`),e.frag&&(this.fragmentTracker.removeFragment(e.frag),this.nextLoadPosition=e.frag.start),this.resetLoadingState(),s}return!1}resetFragmentErrors(e){e===Bg&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==ly&&(this.state=cy)}afterBufferFlushed(e,t,r){if(!e)return;const n=Qm.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,r),this.state===my&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=cy}resetStartWhenNotLoaded(e){if(!this.loadedmetadata){this.startFragRequested=!1;const t=this.levels?this.levels[e].details:null;null!=t&&t.live?(this.startPosition=-1,this.setStartPosition(t,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){var t;this.warn(`The loading context changed while buffering fragment ${e.sn} of level ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(null!=(t=this.levelLastLoaded)?t:e.level),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,r,n){var s;const i=r.details;if(!i)return void this.warn("level.details undefined");if(Object.keys(e.elementaryStreams).reduce(((t,s)=>{const a=e.elementaryStreams[s];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${e.sn} ${s} duration reliably (${o})`),t||!1;const l=n?0:cm(i,e,a.startPTS,a.endPTS,a.startDTS,a.endDTS);return this.hls.trigger(Vf.LEVEL_PTS_UPDATED,{details:i,level:r,drift:l,type:s,frag:e,start:a.startPTS,end:a.endPTS}),!0}return t}),!1))r.fragmentError=0;else if(null===(null==(s=this.transmuxer)?void 0:s.error)){const t=new Error(`Found no media in fragment ${e.sn} of level ${e.level} resetting transmuxer to fallback to playlist timing`);if(0===r.fragmentError&&(r.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)),this.warn(t.message),this.hls.trigger(Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of level "${r.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=gy,this.hls.trigger(Vf.FRAG_PARSED,{frag:e,part:t})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(e){var t,r,n;"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(null!=(t=null!=(r=this.levelLastLoaded)?r:null==(n=this.fragCurrent)?void 0:n.level)?t:0),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function Ey(){return self.SourceBuffer||self.WebKitSourceBuffer}function Sy(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class Ty{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,r,n){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,r){}demux(e,t){this.cachedData&&(e=ng(this.cachedData,e),this.cachedData=null);let r,n=Rp(e,0),s=n?n.length:0;const i=this._audioTrack,a=this._id3Track,o=n?(e=>{const t=Pp(e);for(let e=0;e<t.length;e++){const r=t[e];if(xp(r))return Bp(r)}})(n):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&Hf(o))&&(this.basePTS=Cy(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),n&&n.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:Wg,duration:Number.POSITIVE_INFINITY});s<l;){if(this.canParse(e,s)){const t=this.appendFrame(i,e,s);t?(this.frameIndex++,this.lastPTS=t.sample.pts,s+=t.length,r=s):s=l}else Dp(e,s)?(n=Rp(e,s),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:Wg,duration:Number.POSITIVE_INFINITY}),s+=n.length,r=s):s++;if(s===l&&r!==l){const t=Ap(e,r);this.cachedData?this.cachedData=ng(this.cachedData,t):this.cachedData=t}}return{audioTrack:i,videoTrack:Sy(),id3Track:a,textTrack:Sy()}}demuxSampleAes(e,t,r){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Sy(),id3Track:this._id3Track,textTrack:Sy()}}destroy(){}}const Cy=(e,t,r)=>{if(Hf(e))return 90*e;return 9e4*t+(r?9e4*r.baseTime/r.timescale:0)};function ky(e,t){return 255===e[t]&&240==(246&e[t+1])}function Ay(e,t){return 1&e[t+1]?7:9}function Iy(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function _y(e,t){return t+1<e.length&&ky(e,t)}function Ry(e,t){if(_y(e,t)){const r=Ay(e,t);if(t+r>=e.length)return!1;const n=Iy(e,t);if(n<=r)return!1;const s=t+n;return s===e.length||_y(e,s)}return!1}function Ly(e,t,r,n,s){if(!e.samplerate){const i=function(e,t,r,n){let s,i,a,o;const l=navigator.userAgent.toLowerCase(),c=n,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=1+((192&t[r+2])>>>6);const u=(60&t[r+2])>>>2;if(!(u>d.length-1))return a=(1&t[r+2])<<2,a|=(192&t[r+3])>>>6,Zf.log(`manifest codec:${n}, ADTS type:${s}, samplingIndex:${u}`),/firefox/i.test(l)?u>=6?(s=5,o=new Array(4),i=u-3):(s=2,o=new Array(2),i=u):-1!==l.indexOf("android")?(s=2,o=new Array(2),i=u):(s=5,o=new Array(4),n&&(-1!==n.indexOf("mp4a.40.29")||-1!==n.indexOf("mp4a.40.5"))||!n&&u>=6?i=u-3:((n&&-1!==n.indexOf("mp4a.40.2")&&(u>=6&&1===a||/vivaldi/i.test(l))||!n&&1===a)&&(s=2,o=new Array(2)),i=u)),o[0]=s<<3,o[0]|=(14&u)>>1,o[1]|=(1&u)<<7,o[1]|=a<<3,5===s&&(o[1]|=(14&i)>>1,o[2]=(1&i)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:d[u],channelCount:a,codec:"mp4a.40."+s,manifestCodec:c};e.trigger(Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.FRAG_PARSING_ERROR,fatal:!0,reason:`invalid ADTS sampling index:${u}`})}(t,r,n,s);if(!i)return;e.config=i.config,e.samplerate=i.samplerate,e.channelCount=i.channelCount,e.codec=i.codec,e.manifestCodec=i.manifestCodec,Zf.log(`parsed codec:${e.codec}, rate:${i.samplerate}, channels:${i.channelCount}`)}}function Dy(e){return 9216e4/e}function xy(e,t,r,n,s){const i=n+s*Dy(e.samplerate),a=function(e,t){const r=Ay(e,t);if(t+r<=e.length){const n=Iy(e,t)-r;if(n>0)return{headerLength:r,frameLength:n}}}(t,r);let o;if(a){const{frameLength:n,headerLength:s}=a,l=s+n,c=Math.max(0,r+l-t.length);c?(o=new Uint8Array(l-s),o.set(t.subarray(r+s,t.length),0)):o=t.subarray(r+s,r+l);const d={unit:o,pts:i};return c||e.samples.push(d),{sample:d,length:l,missing:c}}const l=t.length-r;o=new Uint8Array(l),o.set(t.subarray(r,t.length),0);return{sample:{unit:o,pts:i},length:l,missing:-1}}const Oy=/\/emsg[-/]ID3/i;let Py=null;const My=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],Fy=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Uy=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Ny=[0,1,1,4];function By(e,t,r,n,s){if(r+24>t.length)return;const i=jy(t,r);if(i&&r+i.frameLength<=t.length){const a=n+s*(9e4*i.samplesPerFrame/i.sampleRate),o={unit:t.subarray(r,r+i.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=i.channelCount,e.samplerate=i.sampleRate,e.samples.push(o),{sample:o,length:i.frameLength,missing:0}}}function jy(e,t){const r=e[t+1]>>3&3,n=e[t+1]>>1&3,s=e[t+2]>>4&15,i=e[t+2]>>2&3;if(1!==r&&0!==s&&15!==s&&3!==i){const a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*My[14*(3===r?3-n:3===n?3:4)+s-1],c=Fy[3*(3===r?0:2===r?1:2)+i],d=3===o?1:2,u=Uy[r][n],h=Ny[n],f=8*u*h,p=Math.floor(u*l/c+a)*h;if(null===Py){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Py=e?parseInt(e[1]):0}return!!Py&&Py<=87&&2===n&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:c,channelCount:d,frameLength:p,samplesPerFrame:f}}}function $y(e,t){return 255===e[t]&&224==(224&e[t+1])&&0!=(6&e[t+1])}function qy(e,t){return t+1<e.length&&$y(e,t)}function Ky(e,t){if(t+1<e.length&&$y(e,t)){const r=4,n=jy(e,t);let s=r;null!=n&&n.frameLength&&(s=n.frameLength);const i=t+s;return i===e.length||qy(e,i)}return!1}class Gy{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,r=e.byteLength-t,n=new Uint8Array(4),s=Math.min(4,t);if(0===s)throw new Error("no bytes available");n.set(e.subarray(r,r+s)),this.word=new DataView(n.buffer).getUint32(0),this.bitsAvailable=8*s,this.bytesAvailable-=s}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(t=(e-=this.bitsAvailable)>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const r=this.word>>>32-t;if(e>32&&Zf.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return t=e-t,t>0&&this.bitsAvailable?r<<t|this.readBits(t):r}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(0!=(this.word&2147483648>>>e))return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(e){let t,r=8,n=8;for(let s=0;s<e;s++)0!==n&&(t=this.readEG(),n=(r+t+256)%256),r=0===n?r:n}readSPS(){let e,t,r,n=0,s=0,i=0,a=0;const o=this.readUByte.bind(this),l=this.readBits.bind(this),c=this.readUEG.bind(this),d=this.readBoolean.bind(this),u=this.skipBits.bind(this),h=this.skipEG.bind(this),f=this.skipUEG.bind(this),p=this.skipScalingList.bind(this);o();const g=o();if(l(5),u(3),o(),f(),100===g||110===g||122===g||244===g||44===g||83===g||86===g||118===g||128===g){const e=c();if(3===e&&u(1),f(),f(),u(1),d())for(t=3!==e?8:12,r=0;r<t;r++)d()&&p(r<6?16:64)}f();const m=c();if(0===m)c();else if(1===m)for(u(1),h(),h(),e=c(),r=0;r<e;r++)h();f(),u(1);const y=c(),v=c(),b=l(1);0===b&&u(1),u(1),d()&&(n=c(),s=c(),i=c(),a=c());let w=[1,1];if(d()&&d()){switch(o()){case 1:w=[1,1];break;case 2:w=[12,11];break;case 3:w=[10,11];break;case 4:w=[16,11];break;case 5:w=[40,33];break;case 6:w=[24,11];break;case 7:w=[20,11];break;case 8:w=[32,11];break;case 9:w=[80,33];break;case 10:w=[18,11];break;case 11:w=[15,11];break;case 12:w=[64,33];break;case 13:w=[160,99];break;case 14:w=[4,3];break;case 15:w=[3,2];break;case 16:w=[2,1];break;case 255:w=[o()<<8|o(),o()<<8|o()]}}return{width:Math.ceil(16*(y+1)-2*n-2*s),height:(2-b)*(v+1)*16-(b?2:4)*(i+a),pixelRatio:w}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class Hy{constructor(e,t,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new ay(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(e,t,r){const n=e[t].unit;if(n.length<=16)return;const s=n.subarray(16,n.length-n.length%16),i=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(i).then((s=>{const i=new Uint8Array(s);n.set(i,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,r)}))}decryptAacSamples(e,t,r){for(;;t++){if(t>=e.length)return void r();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,r),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t);let n=0;for(let t=32;t<e.length-16;t+=160,n+=16)r.set(e.subarray(t,t+16),n);return r}getAvcDecryptedUnit(e,t){const r=new Uint8Array(t);let n=0;for(let t=32;t<e.length-16;t+=160,n+=16)e.set(r.subarray(n,n+16),t);return e}decryptAvcSample(e,t,r,n,s){const i=og(s.data),a=this.getAvcEncryptedData(i);this.decryptBuffer(a.buffer).then((a=>{s.data=this.getAvcDecryptedUnit(i,a),this.decrypter.isSync()||this.decryptAvcSamples(e,t,r+1,n)}))}decryptAvcSamples(e,t,r,n){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,r=0){if(t>=e.length)return void n();const s=e[t].units;for(;!(r>=s.length);r++){const i=s[r];if(!(i.data.length<=48||1!==i.type&&5!==i.type||(this.decryptAvcSample(e,t,r,n,i),this.decrypter.isSync())))return}}}}const Vy=188;class zy{constructor(e,t,r){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._avcTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.observer=e,this.config=t,this.typeSupported=r}static probe(e){const t=zy.syncOffset(e);return t>0&&Zf.warn(`MPEG2-TS detected but first sync word found @ offset ${t}`),-1!==t}static syncOffset(e){const t=e.length;let r=Math.min(940,e.length-Vy)+1,n=0;for(;n<r;){let s=!1,i=-1,a=0;for(let o=n;o<t;o+=Vy){if(71!==e[o]){if(a)return-1;break}if(a++,-1===i&&(i=o,0!==i&&(r=Math.min(i+18612,e.length-Vy)+1)),s||(s=0===Yy(e,o)),s&&a>1&&(0===i&&a>2||o+Vy>r))return i}n++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:Vp[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(e,t,r,n){this.pmtParsed=!1,this._pmtId=-1,this._avcTrack=zy.createTrack("video"),this._audioTrack=zy.createTrack("audio",n),this._id3Track=zy.createTrack("id3"),this._txtTrack=zy.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=r,this._duration=n}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_avcTrack:t,_id3Track:r}=this;e&&(e.pesData=null),t&&(t.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.avcSample=null,this.remainderData=null}demux(e,t,r=!1,n=!1){let s;r||(this.sampleAes=null);const i=this._avcTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let c=i.pid,d=i.pesData,u=a.pid,h=o.pid,f=a.pesData,p=o.pesData,g=null,m=this.pmtParsed,y=this._pmtId,v=e.length;if(this.remainderData&&(v=(e=ng(this.remainderData,e)).length,this.remainderData=null),v<Vy&&!n)return this.remainderData=e,{audioTrack:a,videoTrack:i,id3Track:o,textTrack:l};const b=Math.max(0,zy.syncOffset(e));v-=(v-b)%Vy,v<e.byteLength&&!n&&(this.remainderData=new Uint8Array(e.buffer,v,e.buffer.byteLength-v));let w=0;for(let t=b;t<v;t+=Vy)if(71===e[t]){const n=!!(64&e[t+1]),v=Yy(e,t);let w;if((48&e[t+3])>>4>1){if(w=t+5+e[t+4],w===t+Vy)continue}else w=t+4;switch(v){case c:n&&(d&&(s=Jy(d))&&this.parseAVCPES(i,l,s,!1),d={data:[],size:0}),d&&(d.data.push(e.subarray(w,t+Vy)),d.size+=t+Vy-w);break;case u:if(n){if(f&&(s=Jy(f)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,s);break;case"mp3":this.parseMPEGPES(a,s)}f={data:[],size:0}}f&&(f.data.push(e.subarray(w,t+Vy)),f.size+=t+Vy-w);break;case h:n&&(p&&(s=Jy(p))&&this.parseID3PES(o,s),p={data:[],size:0}),p&&(p.data.push(e.subarray(w,t+Vy)),p.size+=t+Vy-w);break;case 0:n&&(w+=e[w]+1),y=this._pmtId=Qy(e,w);break;case y:{n&&(w+=e[w]+1);const s=Xy(e,w,this.typeSupported,r);c=s.avc,c>0&&(i.pid=c),u=s.audio,u>0&&(a.pid=u,a.segmentCodec=s.segmentCodec),h=s.id3,h>0&&(o.pid=h),null===g||m||(Zf.warn(`MPEG-TS PMT found at ${t} after unknown PID '${g}'. Backtracking to sync byte @${b} to parse all TS packets.`),g=null,t=b-188),m=this.pmtParsed=!0;break}case 17:case 8191:break;default:g=v}}else w++;if(w>0){const e=new Error(`Found ${w} TS packet/s that do not start with 0x47`);this.observer.emit(Vf.ERROR,Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message})}i.pesData=d,a.pesData=f,o.pesData=p;const E={audioTrack:a,videoTrack:i,id3Track:o,textTrack:l};return n&&this.extractRemainingSamples(E),E}flush(){const{remainderData:e}=this;let t;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._avcTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:r,id3Track:n,textTrack:s}=e,i=r.pesData,a=t.pesData,o=n.pesData;let l;if(i&&(l=Jy(i))?(this.parseAVCPES(r,s,l,!0),r.pesData=null):r.pesData=i,a&&(l=Jy(a))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l)}t.pesData=null}else null!=a&&a.size&&Zf.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;o&&(l=Jy(o))?(this.parseID3PES(n,l),n.pesData=null):n.pesData=o}demuxSampleAes(e,t,r){const n=this.demux(e,r,!0,!this.config.progressive),s=this.sampleAes=new Hy(this.observer,this.config,t);return this.decrypt(n,s)}decrypt(e,t){return new Promise((r=>{const{audioTrack:n,videoTrack:s}=e;n.samples&&"aac"===n.segmentCodec?t.decryptAacSamples(n.samples,0,(()=>{s.samples?t.decryptAvcSamples(s.samples,0,0,(()=>{r(e)})):r(e)})):s.samples&&t.decryptAvcSamples(s.samples,0,0,(()=>{r(e)}))}))}destroy(){this._duration=0}parseAVCPES(e,t,r,n){const s=this.parseAVCNALu(e,r.data);let i,a=this.avcSample,o=!1;r.data=null,a&&s.length&&!e.audFound&&(Zy(a,e),a=this.avcSample=Wy(!1,r.pts,r.dts,"")),s.forEach((n=>{var s;switch(n.type){case 1:{let t=!1;i=!0;const s=n.data;if(o&&s.length>4){const e=new Gy(s).readSliceType();2!==e&&4!==e&&7!==e&&9!==e||(t=!0)}var l;if(t)null!=(l=a)&&l.frame&&!a.key&&(Zy(a,e),a=this.avcSample=null);a||(a=this.avcSample=Wy(!0,r.pts,r.dts,"")),a.frame=!0,a.key=t;break}case 5:i=!0,null!=(s=a)&&s.frame&&!a.key&&(Zy(a,e),a=this.avcSample=null),a||(a=this.avcSample=Wy(!0,r.pts,r.dts,"")),a.key=!0,a.frame=!0;break;case 6:i=!0,ag(n.data,1,r.pts,t.samples);break;case 7:if(i=!0,o=!0,!e.sps){const t=n.data,r=new Gy(t).readSPS();e.width=r.width,e.height=r.height,e.pixelRatio=r.pixelRatio,e.sps=[t],e.duration=this._duration;const s=t.subarray(1,4);let i="avc1.";for(let e=0;e<3;e++){let t=s[e].toString(16);t.length<2&&(t="0"+t),i+=t}e.codec=i}break;case 8:i=!0,e.pps||(e.pps=[n.data]);break;case 9:i=!1,e.audFound=!0,a&&Zy(a,e),a=this.avcSample=Wy(!1,r.pts,r.dts,"");break;case 12:i=!0;break;default:i=!1,a&&(a.debug+="unknown NAL "+n.type+" ")}if(a&&i){a.units.push(n)}})),n&&a&&(Zy(a,e),this.avcSample=null)}getLastNalUnit(e){var t;let r,n=this.avcSample;if(n&&0!==n.units.length||(n=e[e.length-1]),null!=(t=n)&&t.units){const e=n.units;r=e[e.length-1]}return r}parseAVCNALu(e,t){const r=t.byteLength;let n=e.naluState||0;const s=n,i=[];let a,o,l,c=0,d=-1,u=0;for(-1===n&&(d=0,u=31&t[0],n=0,c=1);c<r;)if(a=t[c++],n)if(1!==n)if(a)if(1===a){if(d>=0){const e={data:t.subarray(d,c-n-1),type:u};i.push(e)}else{const r=this.getLastNalUnit(e.samples);if(r&&(s&&c<=4-s&&r.state&&(r.data=r.data.subarray(0,r.data.byteLength-s)),o=c-n-1,o>0)){const e=new Uint8Array(r.data.byteLength+o);e.set(r.data,0),e.set(t.subarray(0,o),r.data.byteLength),r.data=e,r.state=0}}c<r?(l=31&t[c],d=c,u=l,n=0):n=-1}else n=0;else n=3;else n=a?0:2;else n=a?0:1;if(d>=0&&n>=0){const e={data:t.subarray(d,r),type:u,state:n};i.push(e)}if(0===i.length){const r=this.getLastNalUnit(e.samples);if(r){const e=new Uint8Array(r.data.byteLength+t.byteLength);e.set(r.data,0),e.set(t,r.data.byteLength),r.data=e}}return e.naluState=n,i}parseAACPES(e,t){let r=0;const n=this.aacOverFlow;let s,i,a,o=t.data;if(n){this.aacOverFlow=null;const t=n.missing,s=n.sample.unit.byteLength;if(-1===t){const e=new Uint8Array(s+o.byteLength);e.set(n.sample.unit,0),e.set(o,s),o=e}else{const i=s-t;n.sample.unit.set(o.subarray(0,t),i),e.samples.push(n.sample),r=n.missing}}for(s=r,i=o.length;s<i-1&&!_y(o,s);s++);if(s!==r){let e;const t=s<i-1;e=t?`AAC PES did not start with ADTS header,offset:${s}`:"No ADTS header found in AAC PES";const r=new Error(e);if(Zf.warn(`parsing error: ${e}`),this.observer.emit(Vf.ERROR,Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:r,reason:e}),!t)return}if(Ly(e,this.observer,o,s,this.audioCodec),void 0!==t.pts)a=t.pts;else{if(!n)return void Zf.warn("[tsdemuxer]: AAC PES unknown PTS");{const t=Dy(e.samplerate);a=n.sample.pts+t}}let l,c=0;for(;s<i;){if(l=xy(e,o,s,a,c),s+=l.length,l.missing){this.aacOverFlow=l;break}for(c++;s<i-1&&!_y(o,s);s++);}}parseMPEGPES(e,t){const r=t.data,n=r.length;let s=0,i=0;const a=t.pts;if(void 0!==a)for(;i<n;)if(qy(r,i)){const t=By(e,r,i,a,s);if(!t)break;i+=t.length,s++}else i++;else Zf.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseID3PES(e,t){if(void 0===t.pts)return void Zf.warn("[tsdemuxer]: ID3 PES unknown PTS");const r=Gf({},t,{type:this._avcTrack?Qg:Wg,duration:Number.POSITIVE_INFINITY});e.samples.push(r)}}function Wy(e,t,r,n){return{key:e,frame:!1,pts:t,dts:r,units:[],debug:n,length:0}}function Yy(e,t){return((31&e[t+1])<<8)+e[t+2]}function Qy(e,t){return(31&e[t+10])<<8|e[t+11]}function Xy(e,t,r,n){const s={audio:-1,avc:-1,id3:-1,segmentCodec:"aac"},i=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<i;){const i=Yy(e,t);switch(e[t]){case 207:if(!n){Zf.log("ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream");break}case 15:-1===s.audio&&(s.audio=i);break;case 21:-1===s.id3&&(s.id3=i);break;case 219:if(!n){Zf.log("H.264 with AES-128-CBC slice encryption found in unencrypted stream");break}case 27:-1===s.avc&&(s.avc=i);break;case 3:case 4:!0!==r.mpeg&&!0!==r.mp3?Zf.log("MPEG audio found, not supported in this browser"):-1===s.audio&&(s.audio=i,s.segmentCodec="mp3");break;case 36:Zf.warn("Unsupported HEVC stream type found")}t+=5+((15&e[t+3])<<8|e[t+4])}return s}function Jy(e){let t,r,n,s,i,a=0;const o=e.data;if(!e||0===e.size)return null;for(;o[0].length<19&&o.length>1;){const e=new Uint8Array(o[0].length+o[1].length);e.set(o[0]),e.set(o[1],o[0].length),o[0]=e,o.splice(1,1)}t=o[0];if(1===(t[0]<<16)+(t[1]<<8)+t[2]){if(r=(t[4]<<8)+t[5],r&&r>e.size-6)return null;const l=t[7];192&l&&(s=536870912*(14&t[9])+4194304*(255&t[10])+16384*(254&t[11])+128*(255&t[12])+(254&t[13])/2,64&l?(i=536870912*(14&t[14])+4194304*(255&t[15])+16384*(254&t[16])+128*(255&t[17])+(254&t[18])/2,s-i>54e5&&(Zf.warn(`${Math.round((s-i)/9e4)}s delta between PTS and DTS, align them`),s=i)):i=s),n=t[8];let c=n+9;if(e.size<=c)return null;e.size-=c;const d=new Uint8Array(e.size);for(let e=0,r=o.length;e<r;e++){t=o[e];let r=t.byteLength;if(c){if(c>r){c-=r;continue}t=t.subarray(c),r-=c,c=0}d.set(t,a),a+=r}return r&&(r-=n+3),{data:d,pts:s,dts:i,len:r}}return null}function Zy(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){const r=t.samples,n=r.length;if(!n)return void t.dropped++;{const t=r[n-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}e.debug.length&&Zf.log(e.pts+"/"+e.dts+":"+e.debug)}class ev{static getSilentFrame(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}const tv=Math.pow(2,32)-1;class rv{static init(){let e;for(e in rv.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},rv.types)rv.types.hasOwnProperty(e)&&(rv.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),r=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);rv.HDLR_TYPES={video:t,audio:r};const n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),s=new Uint8Array([0,0,0,0,0,0,0,0]);rv.STTS=rv.STSC=rv.STCO=s,rv.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),rv.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),rv.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),rv.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const i=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);rv.FTYP=rv.box(rv.types.ftyp,i,o,i,a),rv.DINF=rv.box(rv.types.dinf,rv.box(rv.types.dref,n))}static box(e,...t){let r=8,n=t.length;const s=n;for(;n--;)r+=t[n].byteLength;const i=new Uint8Array(r);for(i[0]=r>>24&255,i[1]=r>>16&255,i[2]=r>>8&255,i[3]=255&r,i.set(e,4),n=0,r=8;n<s;n++)i.set(t[n],r),r+=t[n].byteLength;return i}static hdlr(e){return rv.box(rv.types.hdlr,rv.HDLR_TYPES[e])}static mdat(e){return rv.box(rv.types.mdat,e)}static mdhd(e,t){t*=e;const r=Math.floor(t/(tv+1)),n=Math.floor(t%(tv+1));return rv.box(rv.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,r>>24,r>>16&255,r>>8&255,255&r,n>>24,n>>16&255,n>>8&255,255&n,85,196,0,0]))}static mdia(e){return rv.box(rv.types.mdia,rv.mdhd(e.timescale,e.duration),rv.hdlr(e.type),rv.minf(e))}static mfhd(e){return rv.box(rv.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?rv.box(rv.types.minf,rv.box(rv.types.smhd,rv.SMHD),rv.DINF,rv.stbl(e)):rv.box(rv.types.minf,rv.box(rv.types.vmhd,rv.VMHD),rv.DINF,rv.stbl(e))}static moof(e,t,r){return rv.box(rv.types.moof,rv.mfhd(e),rv.traf(r,t))}static moov(e){let t=e.length;const r=[];for(;t--;)r[t]=rv.trak(e[t]);return rv.box.apply(null,[rv.types.moov,rv.mvhd(e[0].timescale,e[0].duration)].concat(r).concat(rv.mvex(e)))}static mvex(e){let t=e.length;const r=[];for(;t--;)r[t]=rv.trex(e[t]);return rv.box.apply(null,[rv.types.mvex,...r])}static mvhd(e,t){t*=e;const r=Math.floor(t/(tv+1)),n=Math.floor(t%(tv+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,r>>24,r>>16&255,r>>8&255,255&r,n>>24,n>>16&255,n>>8&255,255&n,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return rv.box(rv.types.mvhd,s)}static sdtp(e){const t=e.samples||[],r=new Uint8Array(4+t.length);let n,s;for(n=0;n<t.length;n++)s=t[n].flags,r[n+4]=s.dependsOn<<4|s.isDependedOn<<2|s.hasRedundancy;return rv.box(rv.types.sdtp,r)}static stbl(e){return rv.box(rv.types.stbl,rv.stsd(e),rv.box(rv.types.stts,rv.STTS),rv.box(rv.types.stsc,rv.STSC),rv.box(rv.types.stsz,rv.STSZ),rv.box(rv.types.stco,rv.STCO))}static avc1(e){let t,r,n,s=[],i=[];for(t=0;t<e.sps.length;t++)r=e.sps[t],n=r.byteLength,s.push(n>>>8&255),s.push(255&n),s=s.concat(Array.prototype.slice.call(r));for(t=0;t<e.pps.length;t++)r=e.pps[t],n=r.byteLength,i.push(n>>>8&255),i.push(255&n),i=i.concat(Array.prototype.slice.call(r));const a=rv.box(rv.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|e.sps.length].concat(s).concat([e.pps.length]).concat(i))),o=e.width,l=e.height,c=e.pixelRatio[0],d=e.pixelRatio[1];return rv.box(rv.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,o>>8&255,255&o,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,rv.box(rv.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),rv.box(rv.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,255&c,d>>24,d>>16&255,d>>8&255,255&d])))}static esds(e){const t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))}static mp4a(e){const t=e.samplerate;return rv.box(rv.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,255&t,0,0]),rv.box(rv.types.esds,rv.esds(e)))}static mp3(e){const t=e.samplerate;return rv.box(rv.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,255&t,0,0]))}static stsd(e){return"audio"===e.type?"mp3"===e.segmentCodec&&"mp3"===e.codec?rv.box(rv.types.stsd,rv.STSD,rv.mp3(e)):rv.box(rv.types.stsd,rv.STSD,rv.mp4a(e)):rv.box(rv.types.stsd,rv.STSD,rv.avc1(e))}static tkhd(e){const t=e.id,r=e.duration*e.timescale,n=e.width,s=e.height,i=Math.floor(r/(tv+1)),a=Math.floor(r%(tv+1));return rv.box(rv.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i,a>>24,a>>16&255,a>>8&255,255&a,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,n>>8&255,255&n,0,0,s>>8&255,255&s,0,0]))}static traf(e,t){const r=rv.sdtp(e),n=e.id,s=Math.floor(t/(tv+1)),i=Math.floor(t%(tv+1));return rv.box(rv.types.traf,rv.box(rv.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),rv.box(rv.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,i>>24,i>>16&255,i>>8&255,255&i])),rv.trun(e,r.length+16+20+8+16+8+8),r)}static trak(e){return e.duration=e.duration||4294967295,rv.box(rv.types.trak,rv.tkhd(e),rv.mdia(e))}static trex(e){const t=e.id;return rv.box(rv.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const r=e.samples||[],n=r.length,s=12+16*n,i=new Uint8Array(s);let a,o,l,c,d,u;for(t+=8+s,i.set(["video"===e.type?1:0,0,15,1,n>>>24&255,n>>>16&255,n>>>8&255,255&n,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),a=0;a<n;a++)o=r[a],l=o.duration,c=o.size,d=o.flags,u=o.cts,i.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,c>>>24&255,c>>>16&255,c>>>8&255,255&c,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,61440&d.degradPrio,15&d.degradPrio,u>>>24&255,u>>>16&255,u>>>8&255,255&u],12+16*a);return rv.box(rv.types.trun,i)}static initSegment(e){rv.types||rv.init();const t=rv.moov(e),r=new Uint8Array(rv.FTYP.byteLength+t.byteLength);return r.set(rv.FTYP),r.set(t,rv.FTYP.byteLength),r}}rv.types=void 0,rv.HDLR_TYPES=void 0,rv.STTS=void 0,rv.STSC=void 0,rv.STCO=void 0,rv.STSZ=void 0,rv.VMHD=void 0,rv.SMHD=void 0,rv.STSD=void 0,rv.FTYP=void 0,rv.DINF=void 0;function nv(e,t,r=1,n=!1){const s=e*t*r;return n?Math.round(s):s}function sv(e,t=!1){return nv(e,1e3,1/9e4,t)}let iv,av=null,ov=null;class lv{constructor(e,t,r,n=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.observer=e,this.config=t,this.typeSupported=r,this.ISGenerated=!1,null===av){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);av=e?parseInt(e[1]):0}if(null===ov){const e=navigator.userAgent.match(/Safari\/(\d+)/i);ov=e?parseInt(e[1]):0}}destroy(){}resetTimeStamp(e){Zf.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){Zf.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){Zf.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1}getVideoStartPts(e){let t=!1;const r=e.reduce(((e,r)=>{const n=r.pts-e;return n<-4294967296?(t=!0,cv(e,r.pts)):n>0?e:r.pts}),e[0].pts);return t&&Zf.debug("PTS rollover detected"),r}remux(e,t,r,n,s,i,a,o){let l,c,d,u,h,f,p=s,g=s;const m=e.pid>-1,y=t.pid>-1,v=t.samples.length,b=e.samples.length>0,w=a&&v>0||v>1;if((!m||b)&&(!y||w)||this.ISGenerated||a){this.ISGenerated||(d=this.generateIS(e,t,s,i));const r=this.isVideoContiguous;let n,a=-1;if(w&&(a=function(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!r&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){Zf.warn(`[mp4-remuxer]: Dropped ${a} out of ${v} video samples due to a missing keyframe`);const e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(a),t.dropped+=a,g+=(t.samples[0].pts-e)/t.inputTimeScale,n=g}else-1===a&&(Zf.warn(`[mp4-remuxer]: No keyframe found out of ${v} video samples`),f=!1);if(this.ISGenerated){if(b&&w){const r=this.getVideoStartPts(t.samples),n=(cv(e.samples[0].pts,r)-r)/t.inputTimeScale;p+=Math.max(0,n),g+=Math.max(0,-n)}if(b){if(e.samplerate||(Zf.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(e,t,s,i)),c=this.remuxAudio(e,p,this.isAudioContiguous,i,y||w||o===Bg?g:void 0),w){const n=c?c.endPTS-c.startPTS:0;t.inputTimeScale||(Zf.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(e,t,s,i)),l=this.remuxVideo(t,g,r,n)}}else w&&(l=this.remuxVideo(t,g,r,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=n)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(h=dv(r,s,this._initPTS,this._initDTS)),n.samples.length&&(u=uv(n,s,this._initPTS))),{audio:c,video:l,initSegment:d,independent:f,text:u,id3:h}}generateIS(e,t,r,n){const s=e.samples,i=t.samples,a=this.typeSupported,o={},l=this._initPTS;let c,d,u,h=!l||n,f="audio/mp4";if(h&&(c=d=1/0),e.config&&s.length){if(e.timescale=e.samplerate,"mp3"===e.segmentCodec)a.mpeg?(f="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");o.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&a.mpeg?new Uint8Array(0):rv.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(u=e.inputTimeScale,l&&u===l.timescale?h=!1:c=d=s[0].pts-Math.round(u*r))}if(t.sps&&t.pps&&i.length&&(t.timescale=t.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:rv.initSegment([t]),metadata:{width:t.width,height:t.height}},h))if(u=t.inputTimeScale,l&&u===l.timescale)h=!1;else{const e=this.getVideoStartPts(i),t=Math.round(u*r);d=Math.min(d,cv(i[0].dts,e)-t),c=Math.min(c,e-t)}if(Object.keys(o).length)return this.ISGenerated=!0,h?(this._initPTS={baseTime:c,timescale:u},this._initDTS={baseTime:d,timescale:u}):c=u=void 0,{tracks:o,initPTS:c,timescale:u}}remuxVideo(e,t,r,n){const s=e.inputTimeScale,i=e.samples,a=[],o=i.length,l=this._initPTS;let c,d,u=this.nextAvcDts,h=8,f=this.videoSampleDuration,p=Number.POSITIVE_INFINITY,g=Number.NEGATIVE_INFINITY,m=!1;if(!r||null===u){u=t*s-(i[0].pts-cv(i[0].dts,i[0].pts))}const y=l.baseTime*s/l.timescale;for(let e=0;e<o;e++){const t=i[e];t.pts=cv(t.pts-y,u),t.dts=cv(t.dts-y,u),t.dts<i[e>0?e-1:e].dts&&(m=!0)}m&&i.sort((function(e,t){const r=e.dts-t.dts,n=e.pts-t.pts;return r||n})),c=i[0].dts,d=i[i.length-1].dts;const v=d-c,b=v?Math.round(v/(o-1)):f||e.inputTimeScale/30;if(r){const e=c-u,t=e>b,r=e<-1;if((t||r)&&(t?Zf.warn(`AVC: ${sv(e,!0)} ms (${e}dts) hole between fragments detected, filling it`):Zf.warn(`AVC: ${sv(-e,!0)} ms (${e}dts) overlapping between fragments detected`),!r||u>=i[0].pts)){c=u;const t=i[0].pts-e;i[0].dts=c,i[0].pts=t,Zf.log(`Video: First PTS/DTS adjusted: ${sv(t,!0)}/${sv(c,!0)}, delta: ${sv(e,!0)} ms`)}}c=Math.max(0,c);let w=0,E=0;for(let e=0;e<o;e++){const t=i[e],r=t.units,n=r.length;let s=0;for(let e=0;e<n;e++)s+=r[e].data.length;E+=s,w+=n,t.length=s,t.dts=Math.max(t.dts,c),p=Math.min(t.pts,p),g=Math.max(t.pts,g)}d=i[o-1].dts;const S=E+4*w+8;let T;try{T=new Uint8Array(S)}catch(e){return void this.observer.emit(Vf.ERROR,Vf.ERROR,{type:zf.MUX_ERROR,details:Wf.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:S,reason:`fail allocating video mdat ${S}`})}const C=new DataView(T.buffer);C.setUint32(0,S),T.set(rv.types.mdat,4);let k=!1,A=Number.POSITIVE_INFINITY,I=Number.POSITIVE_INFINITY,_=Number.NEGATIVE_INFINITY,R=Number.NEGATIVE_INFINITY;for(let e=0;e<o;e++){const t=i[e],r=t.units;let l,c=0;for(let e=0,t=r.length;e<t;e++){const t=r[e],n=t.data,s=t.data.byteLength;C.setUint32(h,s),h+=4,T.set(n,h),h+=s,c+=4+s}if(e<o-1)f=i[e+1].dts-t.dts,l=i[e+1].pts-t.pts;else{const r=this.config,a=e>0?t.dts-i[e-1].dts:b;if(l=e>0?t.pts-i[e-1].pts:b,r.stretchShortVideoTrack&&null!==this.nextAudioPts){const e=Math.floor(r.maxBufferHole*s),i=(n?p+n*s:this.nextAudioPts)-t.pts;i>e?(f=i-a,f<0?f=a:k=!0,Zf.log(`[mp4-remuxer]: It is approximately ${i/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=a}else f=a}const d=Math.round(t.pts-t.dts);A=Math.min(A,f),_=Math.max(_,f),I=Math.min(I,l),R=Math.max(R,l),a.push(new hv(t.key,f,c,d))}if(a.length)if(av){if(av<70){const e=a[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(ov&&R-I<_-A&&b/_<.025&&0===a[0].cts){Zf.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let e=c;for(let t=0,r=a.length;t<r;t++){const n=e+a[t].duration,s=e+a[t].cts;if(t<r-1){const e=n+a[t+1].cts;a[t].duration=e-s}else a[t].duration=t?a[t-1].duration:b;a[t].cts=0,e=n}}f=k||!f?b:f,this.nextAvcDts=u=d+f,this.videoSampleDuration=f,this.isVideoContiguous=!0;const L={data1:rv.moof(e.sequenceNumber++,c,Gf({},e,{samples:a})),data2:T,startPTS:p/s,endPTS:(g+f)/s,startDTS:c/s,endDTS:u/s,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,L}remuxAudio(e,t,r,n,s){const i=e.inputTimeScale,a=i/(e.samplerate?e.samplerate:i),o="aac"===e.segmentCodec?1024:1152,l=o*a,c=this._initPTS,d="mp3"===e.segmentCodec&&this.typeSupported.mpeg,u=[],h=void 0!==s;let f=e.samples,p=d?0:8,g=this.nextAudioPts||-1;const m=t*i,y=c.baseTime*i/c.timescale;if(this.isAudioContiguous=r=r||f.length&&g>0&&(n&&Math.abs(m-g)<9e3||Math.abs(cv(f[0].pts-y,m)-g)<20*l),f.forEach((function(e){e.pts=cv(e.pts-y,m)})),!r||g<0){if(f=f.filter((e=>e.pts>=0)),!f.length)return;g=0===s?0:n&&!h?Math.max(0,m):f[0].pts}if("aac"===e.segmentCodec){const t=this.config.maxAudioFramesDrift;for(let r=0,n=g;r<f.length;r++){const s=f[r],a=s.pts,o=a-n,c=Math.abs(1e3*o/i);if(o<=-t*l&&h)0===r&&(Zf.warn(`Audio frame @ ${(a/i).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*o/i)} ms.`),this.nextAudioPts=g=n=a);else if(o>=t*l&&c<1e4&&h){let t=Math.round(o/l);n=a-t*l,n<0&&(t--,n+=l),0===r&&(this.nextAudioPts=g=n),Zf.warn(`[mp4-remuxer]: Injecting ${t} audio frame @ ${(n/i).toFixed(3)}s due to ${Math.round(1e3*o/i)} ms gap.`);for(let i=0;i<t;i++){const t=Math.max(n,0);let i=ev.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);i||(Zf.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),i=s.unit.subarray()),f.splice(r,0,{unit:i,pts:t}),n+=l,r++}}s.pts=n,n+=l}}let v,b=null,w=null,E=0,S=f.length;for(;S--;)E+=f[S].unit.byteLength;for(let t=0,n=f.length;t<n;t++){const n=f[t],s=n.unit;let i=n.pts;if(null!==w){u[t-1].duration=Math.round((i-w)/a)}else{if(r&&"aac"===e.segmentCodec&&(i=g),b=i,!(E>0))return;E+=p;try{v=new Uint8Array(E)}catch(e){return void this.observer.emit(Vf.ERROR,Vf.ERROR,{type:zf.MUX_ERROR,details:Wf.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:E,reason:`fail allocating audio mdat ${E}`})}if(!d){new DataView(v.buffer).setUint32(0,E),v.set(rv.types.mdat,4)}}v.set(s,p);const l=s.byteLength;p+=l,u.push(new hv(!0,o,l,0)),w=i}const T=u.length;if(!T)return;const C=u[u.length-1];this.nextAudioPts=g=w+a*C.duration;const k=d?new Uint8Array(0):rv.moof(e.sequenceNumber++,b/a,Gf({},e,{samples:u}));e.samples=[];const A=b/i,I=g/i,_={data1:k,data2:v,startPTS:A,endPTS:I,startDTS:A,endDTS:I,type:"audio",hasAudio:!0,hasVideo:!1,nb:T};return this.isAudioContiguous=!0,_}remuxEmptyAudio(e,t,r,n){const s=e.inputTimeScale,i=s/(e.samplerate?e.samplerate:s),a=this.nextAudioPts,o=this._initDTS,l=9e4*o.baseTime/o.timescale,c=(null!==a?a:n.startDTS*s)+l,d=n.endDTS*s+l,u=1024*i,h=Math.ceil((d-c)/u),f=ev.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(Zf.warn("[mp4-remuxer]: remux empty Audio"),!f)return void Zf.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");const p=[];for(let e=0;e<h;e++){const t=c+e*u;p.push({unit:f,pts:t,dts:t})}return e.samples=p,this.remuxAudio(e,t,r,!1)}}function cv(e,t){let r;if(null===t)return e;for(r=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=r;return e}function dv(e,t,r,n){const s=e.samples.length;if(!s)return;const i=e.inputTimeScale;for(let a=0;a<s;a++){const s=e.samples[a];s.pts=cv(s.pts-r.baseTime*i/r.timescale,t*i)/i,s.dts=cv(s.dts-n.baseTime*i/n.timescale,t*i)/i}const a=e.samples;return e.samples=[],{samples:a}}function uv(e,t,r){const n=e.samples.length;if(!n)return;const s=e.inputTimeScale;for(let i=0;i<n;i++){const n=e.samples[i];n.pts=cv(n.pts-r.baseTime*s/r.timescale,t*s)/s}e.samples.sort(((e,t)=>e.pts-t.pts));const i=e.samples;return e.samples=[],{samples:i}}class hv{constructor(e,t,r,n){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=t,this.size=r,this.cts=n,this.flags=new fv(e)}}class fv{constructor(e){this.isLeading=0,this.isDependedOn=0,this.hasRedundancy=0,this.degradPrio=0,this.dependsOn=1,this.isNonSync=1,this.dependsOn=e?2:1,this.isNonSync=e?0:1}}function pv(e,t){const r=null==e?void 0:e.codec;return r&&r.length>4?r:"hvc1"===r||"hev1"===r?"hvc1.1.6.L120.90":"av01"===r?"av01.0.04M.08":"avc1"===r||t===op?"avc1.42e01e":"mp4a.40.5"}try{iv=self.performance.now.bind(self.performance)}catch(e){Zf.debug("Unable to use Performance API on this environment"),iv="undefined"!=typeof self&&self.Date.now}const gv=[{demux:class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,r,n){const s=this.videoTrack=Sy("video",1),i=this.audioTrack=Sy("audio",1),a=this.txtTrack=Sy("text",1);if(this.id3Track=Sy("id3",1),this.timeOffset=0,null==e||!e.byteLength)return;const o=eg(e);if(o.video){const{id:e,timescale:t,codec:r}=o.video;s.id=e,s.timescale=a.timescale=t,s.codec=r}if(o.audio){const{id:e,timescale:t,codec:r}=o.audio;i.id=e,i.timescale=t,i.codec=r}a.id=Vp.text,s.sampleDuration=0,s.duration=i.duration=n}resetContiguity(){this.remainderData=null}static probe(e){return Jp(e=e.length>16384?e.subarray(0,16384):e,["moof"]).length>0}demux(e,t){this.timeOffset=t;let r=e;const n=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=ng(this.remainderData,e));const t=function(e){const t={valid:null,remainder:null},r=Jp(e,["moof"]);if(!r)return t;if(r.length<2)return t.remainder=e,t;const n=r[r.length-1];return t.valid=Ap(e,0,n.byteOffset-8),t.remainder=Ap(e,n.byteOffset-8),t}(r);this.remainderData=t.remainder,n.samples=t.valid||new Uint8Array}else n.samples=r;const i=this.extractID3Track(n,t);return s.samples=sg(t,n),{videoTrack:n,audioTrack:this.audioTrack,id3Track:i,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,r=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const n=this.extractID3Track(t,this.timeOffset);return r.samples=sg(e,t),{videoTrack:t,audioTrack:Sy(),id3Track:n,textTrack:Sy()}}extractID3Track(e,t){const r=this.id3Track;if(e.samples.length){const n=Jp(e.samples,["emsg"]);n&&n.forEach((e=>{const n=function(e){const t=e[0];let r="",n="",s=0,i=0,a=0,o=0,l=0,c=0;if(0===t){for(;"\0"!==zp(e.subarray(c,c+1));)r+=zp(e.subarray(c,c+1)),c+=1;for(r+=zp(e.subarray(c,c+1)),c+=1;"\0"!==zp(e.subarray(c,c+1));)n+=zp(e.subarray(c,c+1)),c+=1;n+=zp(e.subarray(c,c+1)),c+=1,s=Yp(e,12),i=Yp(e,16),o=Yp(e,20),l=Yp(e,24),c=28}else if(1===t){c+=4,s=Yp(e,c),c+=4;const t=Yp(e,c);c+=4;const i=Yp(e,c);for(c+=4,a=2**32*t+i,Number.isSafeInteger(a)||(a=Number.MAX_SAFE_INTEGER,Zf.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Yp(e,c),c+=4,l=Yp(e,c),c+=4;"\0"!==zp(e.subarray(c,c+1));)r+=zp(e.subarray(c,c+1)),c+=1;for(r+=zp(e.subarray(c,c+1)),c+=1;"\0"!==zp(e.subarray(c,c+1));)n+=zp(e.subarray(c,c+1)),c+=1;n+=zp(e.subarray(c,c+1)),c+=1}return{schemeIdUri:r,value:n,timeScale:s,presentationTime:a,presentationTimeDelta:i,eventDuration:o,id:l,payload:e.subarray(c,e.byteLength)}}(e);if(Oy.test(n.schemeIdUri)){const e=Hf(n.presentationTime)?n.presentationTime/n.timeScale:t+n.presentationTimeDelta/n.timeScale;let s=4294967295===n.eventDuration?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);const i=n.payload;r.samples.push({data:i,len:i.byteLength,dts:e,pts:e,type:Qg,duration:s})}}))}return r}demuxSampleAes(e,t,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}},remux:class{constructor(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,r,n){this.audioCodec=t,this.videoCodec=r,this.generateInitSegment(function(e,t){if(!e||!t)return e;const r=t.keyId;r&&t.isCommonEncryption&&Jp(e,["moov","trak"]).forEach((e=>{const t=Jp(e,["mdia","minf","stbl","stsd"])[0].subarray(8);let n=Jp(t,["enca"]);const s=n.length>0;s||(n=Jp(t,["encv"])),n.forEach((e=>{Jp(s?e.subarray(28):e.subarray(78),["sinf"]).forEach((e=>{const t=tg(e);if(t){const e=t.subarray(8,24);e.some((e=>0!==e))||(Zf.log(`[eme] Patching keyId in 'enc${s?"a":"v"}>sinf>>tenc' box: ${Kp(e)} -> ${Kp(r)}`),t.set(r,8))}}))}))}));return e}(e,n)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:r}=this;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const n=this.initData=eg(e);t||(t=pv(n.audio,ap)),r||(r=pv(n.video,op));const s={};n.audio&&n.video?s.audiovideo={container:"video/mp4",codec:t+","+r,initSegment:e,id:"main"}:n.audio?s.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:n.video?s.video={container:"video/mp4",codec:r,initSegment:e,id:"main"}:Zf.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=s}remux(e,t,r,n,s,i){var a,o;let{initPTS:l,lastEndTime:c}=this;const d={audio:void 0,video:void 0,text:n,id3:r,initSegment:void 0};Hf(c)||(c=this.lastEndTime=s||0);const u=t.samples;if(null==u||!u.length)return d;const h={initPTS:void 0,timescale:1};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(u),f=this.initData),null==(o=f)||!o.length)return Zf.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),d;this.emitInitSegment&&(h.tracks=this.initTracks,this.emitInitSegment=!1);const p=function(e,t){let r=0,n=0,s=0;const i=Jp(e,["moof","traf"]);for(let e=0;e<i.length;e++){const a=i[e],o=Jp(a,["tfhd"])[0],l=t[Yp(o,4)];if(!l)continue;const c=l.default,d=Yp(o,0)|(null==c?void 0:c.flags);let u=null==c?void 0:c.duration;8&d&&(u=Yp(o,2&d?12:8));const h=l.timescale||9e4,f=Jp(a,["trun"]);for(let e=0;e<f.length;e++)r=rg(f[e]),!r&&u&&(r=u*Yp(f[e],4)),l.type===op?n+=r/h:l.type===ap&&(s+=r/h)}if(0===n&&0===s){let t=0;const r=Jp(e,["sidx"]);for(let e=0;e<r.length;e++){const n=Zp(r[e]);null!=n&&n.references&&(t+=n.references.reduce(((e,t)=>e+t.info.duration||0),0))}return t}return n||s}(u,f),g=function(e,t){return Jp(t,["moof","traf"]).reduce(((t,r)=>{const n=Jp(r,["tfdt"])[0],s=n[0],i=Jp(r,["tfhd"]).reduce(((t,r)=>{const i=Yp(r,4),a=e[i];if(a){let e=Yp(n,4);if(1===s){if(e===Gp)return Zf.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),t;e*=Gp+1,e+=Yp(n,8)}const r=e/(a.timescale||9e4);if(isFinite(r)&&(null===t||r<t))return r}return t}),null);return null!==i&&isFinite(i)&&(null===t||i<t)?i:t}),null)}(f,u),m=null===g?s:g;(function(e,t,r,n){if(null===e)return!0;const s=Math.max(n,1),i=t-e.baseTime/e.timescale;return Math.abs(i-r)>s}(l,m,s,p)||h.timescale!==l.timescale&&i)&&(h.initPTS=m-s,l&&1===l.timescale&&Zf.warn("Adjusting initPTS by "+(h.initPTS-l.baseTime)),this.initPTS=l={baseTime:h.initPTS,timescale:1});const y=e?m-l.baseTime/l.timescale:c,v=y+p;!function(e,t,r){Jp(t,["moof","traf"]).forEach((t=>{Jp(t,["tfhd"]).forEach((n=>{const s=Yp(n,4),i=e[s];if(!i)return;const a=i.timescale||9e4;Jp(t,["tfdt"]).forEach((e=>{const t=e[0];let n=Yp(e,4);if(0===t)n-=r*a,n=Math.max(n,0),Xp(e,4,n);else{n*=Math.pow(2,32),n+=Yp(e,8),n-=r*a,n=Math.max(n,0);const t=Math.floor(n/(Gp+1)),s=Math.floor(n%(Gp+1));Xp(e,4,t),Xp(e,8,s)}}))}))}))}(f,u,l.baseTime/l.timescale),p>0?this.lastEndTime=v:(Zf.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const b=!!f.audio,w=!!f.video;let E="";b&&(E+="audio"),w&&(E+="video");const S={data1:u,startPTS:y,startDTS:y,endPTS:v,endDTS:v,type:E,hasAudio:b,hasVideo:w,nb:1,dropped:0};return d.audio="audio"===S.type?S:void 0,d.video="audio"!==S.type?S:void 0,d.initSegment=h,d.id3=dv(r,s,l,l),n.samples.length&&(d.text=uv(n,s,l)),d}}},{demux:zy,remux:lv},{demux:class extends Ty{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,r,n){super.resetInitSegment(e,t,r,n),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=(Rp(e,0)||[]).length;for(let r=e.length;t<r;t++)if(Ry(e,t))return Zf.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&ky(e,t)&&Iy(e,t)<=e.length-t}(e,t)}appendFrame(e,t,r){Ly(e,this.observer,t,r,e.manifestCodec);const n=xy(e,t,r,this.basePTS,this.frameIndex);if(n&&0===n.missing)return n}},remux:lv},{demux:class extends Ty{resetInitSegment(e,t,r,n){super.resetInitSegment(e,t,r,n),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=(Rp(e,0)||[]).length;for(let r=e.length;t<r;t++)if(Ky(e,t))return Zf.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return $y(e,t)&&4<=e.length-t}(e,t)}appendFrame(e,t,r){if(null!==this.basePTS)return By(e,t,r,this.basePTS,this.frameIndex)}},remux:lv}];class mv{constructor(e,t,r,n,s){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=r,this.vendor=n,this.id=s}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,r,n){const s=r.transmuxing;s.executeStart=iv();let i=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:o}=this;n&&(this.currentTransmuxState=n);const{contiguous:l,discontinuity:c,trackSwitch:d,accurateTimeOffset:u,timeOffset:h,initSegmentChange:f}=n||a,{audioCodec:p,videoCodec:g,defaultInitPts:m,duration:y,initSegmentData:v}=o,b=function(e,t){let r=null;e.byteLength>0&&null!=t&&null!=t.key&&null!==t.iv&&null!=t.method&&(r=t);return r}(i,t);if(b&&"AES-128"===b.method){const e=this.getDecrypter();if(!e.isSync())return this.decryptionPromise=e.webCryptoDecrypt(i,b.key.buffer,b.iv.buffer).then((e=>{const t=this.push(e,null,r);return this.decryptionPromise=null,t})),this.decryptionPromise;{let t=e.softwareDecrypt(i,b.key.buffer,b.iv.buffer);if(r.part>-1&&(t=e.flush()),!t)return s.executeEnd=iv(),yv(r);i=new Uint8Array(t)}}const w=this.needsProbing(c,d);if(w){const e=this.configureTransmuxer(i);if(e)return Zf.warn(`[transmuxer] ${e.message}`),this.observer.emit(Vf.ERROR,Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),s.executeEnd=iv(),yv(r)}(c||d||f||w)&&this.resetInitSegment(v,p,g,y,t),(c||f||w)&&this.resetInitialTimestamp(m),l||this.resetContiguity();const E=this.transmux(i,b,h,u,r),S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,s.executeEnd=iv(),E}flush(e){const t=e.transmuxing;t.executeStart=iv();const{decrypter:r,currentTransmuxState:n,decryptionPromise:s}=this;if(s)return s.then((()=>this.flush(e)));const i=[],{timeOffset:a}=n;if(r){const t=r.flush();t&&i.push(this.push(t,null,e))}const{demuxer:o,remuxer:l}=this;if(!o||!l)return t.executeEnd=iv(),[yv(e)];const c=o.flush(a);return vv(c)?c.then((t=>(this.flushRemux(i,t,e),i))):(this.flushRemux(i,c,e),i)}flushRemux(e,t,r){const{audioTrack:n,videoTrack:s,id3Track:i,textTrack:a}=t,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;Zf.log(`[transmuxer.ts]: Flushed fragment ${r.sn}${r.part>-1?" p: "+r.part:""} of level ${r.level}`);const c=this.remuxer.remux(n,s,i,a,l,o,!0,this.id);e.push({remuxResult:c,chunkMeta:r}),r.transmuxing.executeEnd=iv()}resetInitialTimestamp(e){const{demuxer:t,remuxer:r}=this;t&&r&&(t.resetTimeStamp(e),r.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,r,n,s){const{demuxer:i,remuxer:a}=this;i&&a&&(i.resetInitSegment(e,t,r,n),a.resetInitSegment(e,t,r,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,r,n,s){let i;return i=t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,r,n,s):this.transmuxUnencrypted(e,r,n,s),i}transmuxUnencrypted(e,t,r,n){const{audioTrack:s,videoTrack:i,id3Track:a,textTrack:o}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,i,a,o,t,r,!1,this.id),chunkMeta:n}}transmuxSampleAes(e,t,r,n,s){return this.demuxer.demuxSampleAes(e,t,r).then((e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,r,n,!1,this.id),chunkMeta:s})))}configureTransmuxer(e){const{config:t,observer:r,typeSupported:n,vendor:s}=this;let i;for(let t=0,r=gv.length;t<r;t++)if(gv[t].demux.probe(e)){i=gv[t];break}if(!i)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=i.remux,c=i.demux;o&&o instanceof l||(this.remuxer=new l(r,t,n,s)),a&&a instanceof c||(this.demuxer=new c(r,t,n),this.probe=c.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new ay(this.config)),e}}const yv=e=>({remuxResult:{},chunkMeta:e});function vv(e){return"then"in e&&e.then instanceof Function}class bv{constructor(e,t,r,n,s){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=r,this.duration=n,this.defaultInitPts=s||null}}class wv{constructor(e,t,r,n,s,i){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=r,this.trackSwitch=n,this.timeOffset=s,this.initSegmentChange=i}}var Ev={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}function s(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function i(e,t,n,i,a){if("function"!=typeof n)throw new TypeError("The listener must be a function");var o=new s(n,i||e,a),l=r?r+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function o(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),o.prototype.eventNames=function(){var e,n,s=[];if(0===this._eventsCount)return s;for(n in e=this._events)t.call(e,n)&&s.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},o.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,i=n.length,a=new Array(i);s<i;s++)a[s]=n[s].fn;return a},o.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},o.prototype.emit=function(e,t,n,s,i,a){var o=r?r+e:e;if(!this._events[o])return!1;var l,c,d=this._events[o],u=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),u){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,n),!0;case 4:return d.fn.call(d.context,t,n,s),!0;case 5:return d.fn.call(d.context,t,n,s,i),!0;case 6:return d.fn.call(d.context,t,n,s,i,a),!0}for(c=1,l=new Array(u-1);c<u;c++)l[c-1]=arguments[c];d.fn.apply(d.context,l)}else{var h,f=d.length;for(c=0;c<f;c++)switch(d[c].once&&this.removeListener(e,d[c].fn,void 0,!0),u){case 1:d[c].fn.call(d[c].context);break;case 2:d[c].fn.call(d[c].context,t);break;case 3:d[c].fn.call(d[c].context,t,n);break;case 4:d[c].fn.call(d[c].context,t,n,s);break;default:if(!l)for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];d[c].fn.apply(d[c].context,l)}}return!0},o.prototype.on=function(e,t,r){return i(this,e,t,r,!1)},o.prototype.once=function(e,t,r){return i(this,e,t,r,!0)},o.prototype.removeListener=function(e,t,n,s){var i=r?r+e:e;if(!this._events[i])return this;if(!t)return a(this,i),this;var o=this._events[i];if(o.fn)o.fn!==t||s&&!o.once||n&&o.context!==n||a(this,i);else{for(var l=0,c=[],d=o.length;l<d;l++)(o[l].fn!==t||s&&!o[l].once||n&&o[l].context!==n)&&c.push(o[l]);c.length?this._events[i]=1===c.length?c[0]:c:a(this,i)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&a(this,t)):(this._events=new n,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=r,o.EventEmitter=o,e.exports=o}(Ev);var Sv=Nf(Ev.exports);const Tv=yg()||{isTypeSupported:()=>!1};class Cv{constructor(e,t,r,n){this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;const s=e.config;this.hls=e,this.id=t,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=r,this.onFlush=n;const i=(e,t)=>{(t=t||{}).frag=this.frag,t.id=this.id,e===Vf.ERROR&&(this.error=t.error),this.hls.trigger(e,t)};this.observer=new Sv,this.observer.on(Vf.FRAG_DECRYPTED,i),this.observer.on(Vf.ERROR,i);const a={mp4:Tv.isTypeSupported("video/mp4"),mpeg:Tv.isTypeSupported("audio/mpeg"),mp3:Tv.isTypeSupported('audio/mp4; codecs="mp3"')},o=navigator.vendor;if(this.useWorker&&"undefined"!=typeof Worker){if(s.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{s.workerPath?(Zf.log(`loading Web Worker ${s.workerPath} for "${t}"`),this.workerContext=function(e){const t=new self.URL(e,self.location.href).href;return{worker:new self.Worker(t),scriptURL:t}}(s.workerPath)):(Zf.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e);return{worker:new self.Worker(t),objectURL:t}}()),this.onwmsg=e=>this.onWorkerMessage(e);const{worker:e}=this.workerContext;e.addEventListener("message",this.onwmsg),e.onerror=e=>{const r=new Error(`${e.message} (${e.filename}:${e.lineno})`);s.enableWorker=!1,Zf.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(Vf.ERROR,{type:zf.OTHER_ERROR,details:Wf.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:r})},e.postMessage({cmd:"init",typeSupported:a,vendor:o,id:t,config:JSON.stringify(s)})}catch(e){Zf.warn(`Error setting up "${t}" Web Worker, fallback to inline`,e),this.resetWorker(),this.error=null,this.transmuxer=new mv(this.observer,a,s,o,t)}return}}this.transmuxer=new mv(this.observer,a,s,o,t)}resetWorker(){if(this.workerContext){const{worker:e,objectURL:t}=this.workerContext;t&&self.URL.revokeObjectURL(t),e.removeEventListener("message",this.onwmsg),e.onerror=null,e.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(e,t,r,n,s,i,a,o,l,c){var d,u;l.transmuxing.start=self.performance.now();const{transmuxer:h}=this,f=i?i.start:s.start,p=s.decryptdata,g=this.frag,m=!(g&&s.cc===g.cc),y=!(g&&l.level===g.level),v=g?l.sn-g.sn:-1,b=this.part?l.part-this.part.index:-1,w=0===v&&l.id>1&&l.id===(null==g?void 0:g.stats.chunkCount),E=!y&&(1===v||0===v&&(1===b||w&&b<=0)),S=self.performance.now();(y||v||0===s.stats.parsing.start)&&(s.stats.parsing.start=S),!i||!b&&E||(i.stats.parsing.start=S);const T=!(g&&(null==(d=s.initSegment)?void 0:d.url)===(null==(u=g.initSegment)?void 0:u.url)),C=new wv(m,E,o,y,f,T);if(!E||m||T){Zf.log(`[transmuxer-interface, ${s.type}]: Starting new transmux session for sn: ${l.sn} p: ${l.part} level: ${l.level} id: ${l.id}\n discontinuity: ${m}\n trackSwitch: ${y}\n contiguous: ${E}\n accurateTimeOffset: ${o}\n timeOffset: ${f}\n initSegmentChange: ${T}`);const e=new bv(r,n,t,a,c);this.configureTransmuxer(e)}if(this.frag=s,this.part=i,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:p,chunkMeta:l,state:C},e instanceof ArrayBuffer?[e]:[]);else if(h){const t=h.push(e,p,l,C);vv(t)?(h.async=!0,t.then((e=>{this.handleTransmuxComplete(e)})).catch((e=>{this.transmuxerError(e,l,"transmuxer-interface push error")}))):(h.async=!1,this.handleTransmuxComplete(t))}}flush(e){e.transmuxing.start=self.performance.now();const{transmuxer:t}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(t){let r=t.flush(e);vv(r)||t.async?(vv(r)||(r=Promise.resolve(r)),r.then((t=>{this.handleFlushResult(t,e)})).catch((t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")}))):this.handleFlushResult(r,e)}}transmuxerError(e,t,r){this.hls&&(this.error=e,this.hls.trigger(Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.FRAG_PARSING_ERROR,chunkMeta:t,fatal:!1,error:e,err:e,reason:r}))}handleFlushResult(e,t){e.forEach((e=>{this.handleTransmuxComplete(e)})),this.onFlush(t)}onWorkerMessage(e){const t=e.data,r=this.hls;switch(t.event){case"init":{var n;const e=null==(n=this.workerContext)?void 0:n.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":Zf[t.data.logType]&&Zf[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,r.trigger(t.event,t.data)}}configureTransmuxer(e){const{transmuxer:t}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:e}):t&&t.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}class kv{constructor(e,t,r,n){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=r,this.hls=n}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){const{config:r,media:n,stalled:s}=this;if(null===n)return;const{currentTime:i,seeking:a}=n,o=this.seeking&&!a,l=!this.seeking&&a;if(this.seeking=a,i!==e){if(this.moved=!0,null!==s){if(this.stallReported){const e=self.performance.now()-s;Zf.warn(`playback not stuck anymore @${i}, after ${Math.round(e)}ms`),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}return}if(l||o)return void(this.stalled=null);if(n.paused&&!a||n.ended||0===n.playbackRate||!Qm.getBuffered(n).length)return;const c=Qm.bufferInfo(n,i,0),d=c.len>0,u=c.nextStart||0;if(!d&&!u)return;if(a){const e=c.len>2,r=!u||t&&t.start<=i||u-i>2&&!this.fragmentTracker.getPartialFragment(i);if(e||r)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var h;const e=Math.max(u,c.start||0)-i,t=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,r=(null==t||null==(h=t.details)?void 0:h.live)?2*t.details.targetduration:2,n=this.fragmentTracker.getPartialFragment(i);if(e>0&&(e<=r||n))return void this._trySkipBufferHole(n)}const f=self.performance.now();if(null===s)return void(this.stalled=f);const p=f-s;if(!a&&p>=250&&(this._reportStall(c),!this.media))return;const g=Qm.bufferInfo(n,i,r.maxBufferHole);this._tryFixBufferStall(g,p)}_tryFixBufferStall(e,t){const{config:r,fragmentTracker:n,media:s}=this;if(null===s)return;const i=s.currentTime,a=n.getPartialFragment(i);if(a){if(this._trySkipBufferHole(a)||!this.media)return}(e.len>r.maxBufferHole||e.nextStart&&e.nextStart-i<r.maxBufferHole)&&t>1e3*r.highBufferWatchdogPeriod&&(Zf.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:t,media:r,stallReported:n}=this;if(!n&&r){this.stallReported=!0;const n=new Error(`Playback stalling at @${r.currentTime} due to low buffer (${JSON.stringify(e)})`);Zf.warn(n.message),t.trigger(Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len})}}_trySkipBufferHole(e){const{config:t,hls:r,media:n}=this;if(null===n)return 0;const s=n.currentTime,i=Qm.bufferInfo(n,s,0),a=s<i.start?i.start:i.nextStart;if(a){const o=i.len<=t.maxBufferHole,l=i.len>0&&i.len<1&&n.readyState<3,c=a-s;if(c>0&&(o||l)){if(c>t.maxBufferHole){const{fragmentTracker:t}=this;let r=!1;if(0===s){const e=t.getAppendedFrag(0,Ng);e&&a<e.end&&(r=!0)}if(!r){const r=e||t.getAppendedFrag(s,Ng);if(r){let e=!1,n=r.end;for(;n<a;){const r=t.getPartialFragment(n);if(!r){e=!0;break}n+=r.duration}if(e)return 0}}}const i=Math.max(a+.05,s+.1);if(Zf.warn(`skipping hole, adjusting currentTime from ${s} to ${i}`),this.moved=!0,this.stalled=null,n.currentTime=i,e&&!e.gap){const t=new Error(`fragment loaded with buffer holes, seeking from ${s} to ${i}`);r.trigger(Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:t,reason:t.message,frag:e})}return i}}return 0}_tryNudgeBuffer(){const{config:e,hls:t,media:r,nudgeRetry:n}=this;if(null===r)return;const s=r.currentTime;if(this.nudgeRetry++,n<e.nudgeMaxRetry){const i=s+(n+1)*e.nudgeOffset,a=new Error(`Nudging 'currentTime' from ${s} to ${i}`);Zf.warn(a.message),r.currentTime=i,t.trigger(Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.BUFFER_NUDGE_ON_STALL,error:a,fatal:!1})}else{const r=new Error(`Playhead still not moving while enough data buffered @${s} after ${e.nudgeMaxRetry} nudges`);Zf.error(r.message),t.trigger(Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.BUFFER_STALLED_ERROR,error:r,fatal:!0})}}}class Av extends wy{constructor(e,t,r){super(e,t,r,"[stream-controller]",Ng),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Vf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Vf.LEVEL_LOADING,this.onLevelLoading,this),e.on(Vf.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Vf.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(Vf.ERROR,this.onError,this),e.on(Vf.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Vf.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(Vf.BUFFER_CREATED,this.onBufferCreated,this),e.on(Vf.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Vf.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Vf.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Vf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Vf.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Vf.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(Vf.ERROR,this.onError,this),e.off(Vf.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Vf.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(Vf.BUFFER_CREATED,this.onBufferCreated,this),e.off(Vf.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Vf.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Vf.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),this.onMediaDetaching()}startLoad(e){if(this.levels){const{lastCurrentTime:t,hls:r}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let e=r.startLevel;-1===e&&(r.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=r.nextAutoLevel),this.level=r.nextLoadLevel=e,this.loadedmetadata=!1}t>0&&-1===e&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=cy,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=ly}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case by:{var e;const{levels:t,level:r}=this,n=null==t||null==(e=t[r])?void 0:e.details;if(n&&(!n.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(n))break;this.state=cy;break}if(this.hls.nextLoadLevel!==this.level){this.state=cy;break}break}case hy:{var t;const e=self.performance.now(),r=this.retryDate;(!r||e>=r||null!=(t=this.media)&&t.seeking)&&(this.resetStartWhenNotLoaded(this.level),this.state=cy)}}this.state===cy&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:r,media:n}=this,{config:s,nextLoadLevel:i}=e;if(null===t||!n&&(this.startFragRequested||!s.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;if(null==r||!r[i])return;const a=r[i],o=this.getMainFwdBufferInfo();if(null===o)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const e={};return this.altAudio&&(e.type="video"),this.hls.trigger(Vf.BUFFER_EOS,e),void(this.state=my)}e.loadLevel!==i&&-1===e.manualLevel&&this.log(`Adapting to level ${i} from level ${this.level}`),this.level=e.nextLoadLevel=i;const c=a.details;if(!c||this.state===by||c.live&&this.levelLastLoaded!==i)return this.level=i,void(this.state=by);const d=o.len,u=this.getMaxBufferLength(a.maxBitrate);if(d>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const h=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(h,c);if(this.couldBacktrack&&!this.fragPrevious&&f&&"initSegment"!==f.sn&&this.fragmentTracker.getState(f)!==Bm){var p;const e=(null!=(p=this.backtrackFragment)?p:f).sn-c.startSN,t=c.fragments[e-1];t&&f.cc===t.cc&&(f=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){const e=this.audioOnly&&!this.altAudio?ap:op,t=(e===op?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,Ng)}f=this.getNextFragmentLoopLoading(f,c,o,Ng,u)}f&&(!f.initSegment||f.initSegment.data||this.bitrateTest||(f=f.initSegment),this.loadFragment(f,a,h))}loadFragment(e,t,r){const n=this.fragmentTracker.getState(e);this.fragCurrent=e,n===Fm||n===Nm?"initSegment"===e.sn?this._loadInitSegment(e,t):this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):(this.startFragRequested=!0,super.loadFragment(e,t,r)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,Ng)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(null!=t&&t.readyState){let r;const n=this.getAppendedFrag(t.currentTime);n&&n.start>1&&this.flushMainBuffer(0,n.start-1);const s=this.getLevelDetails();if(null!=s&&s.live){const e=this.getMainFwdBufferInfo();if(!e||e.len<2*s.targetduration)return}if(!t.paused&&e){const t=e[this.hls.nextLoadLevel],n=this.fragLastKbps;r=n&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*n)+1:0}else r=0;const i=this.getBufferedFrag(t.currentTime+r);if(i){const e=this.followingBufferedFrag(i);if(e){this.abortCurrentFrag();const t=e.maxStartPTS?e.maxStartPTS:e.start,r=e.duration,n=Math.max(i.end,t+Math.min(Math.max(r-this.config.maxFragLookUpTolerance,.5*r),.75*r));this.flushMainBuffer(n,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case dy:case uy:case hy:case py:case gy:this.state=cy}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const r=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),r.addEventListener("playing",this.onvplaying),r.addEventListener("seeked",this.onvseeked),this.gapController=new kv(this.config,r,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:e}=this;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const e=this.media,t=e?e.currentTime:null;Hf(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);const r=this.getMainFwdBufferInfo();null!==r&&0!==r.len?this.tick():this.warn(`Main forward buffer length on "seeked" event ${r?r.len:"empty"})`)}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(Vf.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=0,this.levels=this.fragPlaying=this.backtrackFragment=null,this.altAudio=this.audioOnly=!1}onManifestParsed(e,t){let r,n=!1,s=!1;t.levels.forEach((e=>{r=e.audioCodec,r&&(-1!==r.indexOf("mp4a.40.2")&&(n=!0),-1!==r.indexOf("mp4a.40.5")&&(s=!0))})),this.audioCodecSwitch=n&&s&&!function(){var e;const t=Ey();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:r}=this;if(!r||this.state!==cy)return;const n=r[t.level];(!n.details||n.details.live&&this.levelLastLoaded!==t.level||this.waitForCdnTuneIn(n.details))&&(this.state=by)}onLevelLoaded(e,t){var r;const{levels:n}=this,s=t.level,i=t.details,a=i.totalduration;if(!n)return void this.warn(`Levels were reset while loading level ${s}`);this.log(`Level ${s} loaded [${i.startSN},${i.endSN}]${i.lastPartSn?`[part-${i.lastPartSn}-${i.lastPartIndex}]`:""}, cc [${i.startCC}, ${i.endCC}] duration:${a}`);const o=n[s],l=this.fragCurrent;!l||this.state!==uy&&this.state!==hy||l.level===t.level&&l.urlId===o.urlId||!l.loader||this.abortCurrentFrag();let c=0;if(i.live||null!=(r=o.details)&&r.live){if(i.fragments[0]||(i.deltaUpdateFailed=!0),i.deltaUpdateFailed)return;c=this.alignPlaylists(i,o.details)}if(o.details=i,this.levelLastLoaded=s,this.hls.trigger(Vf.LEVEL_UPDATED,{details:i,level:s}),this.state===by){if(this.waitForCdnTuneIn(i))return;this.state=cy}this.startFragRequested?i.live&&this.synchronizeToLiveEdge(i):this.setStartPosition(i,c),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:r,part:n,payload:s}=e,{levels:i}=this;if(!i)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);const a=i[r.level],o=a.details;if(!o)return this.warn(`Dropping fragment ${r.sn} of level ${r.level} after level details were reset`),void this.fragmentTracker.removeFragment(r);const l=a.videoCodec,c=o.PTSKnown||!o.live,d=null==(t=r.initSegment)?void 0:t.data,u=this._getAudioCodec(a),h=this.transmuxer=this.transmuxer||new Cv(this.hls,Ng,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=n?n.index:-1,p=-1!==f,g=new Xm(r.level,r.sn,r.stats.chunkCount,s.byteLength,f,p),m=this.initPTS[r.cc];h.push(s,d,u,l,r,n,o.totalduration,c,g,m)}onAudioTrackSwitching(e,t){const r=this.altAudio;if(!!!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const e=this.hls;r&&(e.trigger(Vf.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),e.trigger(Vf.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const r=t.id,n=!!this.hls.audioTracks[r].url;if(n){const e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=n,this.tick()}onBufferCreated(e,t){const r=t.tracks;let n,s,i=!1;for(const e in r){const t=r[e];if("main"===t.id){if(s=e,n=t,"video"===e){const t=r[e];t&&(this.videoBuffer=t.buffer)}}else i=!0}i&&n?(this.log(`Alternate track found, use ${s}.buffered to schedule main fragment loading`),this.mediaBuffer=n.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:r,part:n}=t;if(r&&r.type!==Ng)return;if(this.fragContextChanged(r))return this.warn(`Fragment ${r.sn}${n?" p: "+n.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===gy&&(this.state=cy));const s=n?n.stats:r.stats;this.fragLastKbps=Math.round(8*s.total/(s.buffering.end-s.loading.first)),"initSegment"!==r.sn&&(this.fragPrevious=r),this.fragBufferedComplete(r,n)}onError(e,t){var r;if(t.fatal)this.state=yy;else switch(t.details){case Wf.FRAG_GAP:case Wf.FRAG_PARSING_ERROR:case Wf.FRAG_DECRYPT_ERROR:case Wf.FRAG_LOAD_ERROR:case Wf.FRAG_LOAD_TIMEOUT:case Wf.KEY_LOAD_ERROR:case Wf.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Ng,t);break;case Wf.LEVEL_LOAD_ERROR:case Wf.LEVEL_LOAD_TIMEOUT:case Wf.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==by||(null==(r=t.context)?void 0:r.type)!==Mg||(this.state=cy);break;case Wf.BUFFER_FULL_ERROR:if(!t.parent||"main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case Wf.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}checkBuffer(){const{media:e,gapController:t}=this;if(e&&t&&e.readyState){if(this.loadedmetadata||!Qm.getBuffered(e).length){const e=this.state!==cy?this.fragCurrent:null;t.poll(this.lastCurrentTime,e)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=cy,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==ap||this.audioOnly&&!this.altAudio){const e=(t===op?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(e,t,Ng)}}onLevelsUpdated(e,t){this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let r=this.startPosition;if(r>=0&&t<r){if(e.seeking)return void this.log(`could not seek to ${r}, already seeking at ${t}`);const n=Qm.getBuffered(e),s=(n.length?n.start(0):0)-r;s>0&&(s<this.config.maxBufferHole||s<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${s} to match buffer start`),r+=s,this.startPosition=r),this.log(`seek to target start position ${r} from current time ${t}`),e.currentTime=r}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then((r=>{const{hls:n}=this;if(!r||this.fragContextChanged(e))return;t.fragmentError=0,this.state=cy,this.startFragRequested=!1,this.bitrateTest=!1;const s=e.stats;s.parsing.start=s.parsing.end=s.buffering.start=s.buffering.end=self.performance.now(),n.trigger(Vf.FRAG_LOADED,r),e.bitrateTest=!1}))}_handleTransmuxComplete(e){var t;const r="main",{hls:n}=this,{remuxResult:s,chunkMeta:i}=e,a=this.getCurrentContext(i);if(!a)return void this.resetWhenMissingContext(i);const{frag:o,part:l,level:c}=a,{video:d,text:u,id3:h,initSegment:f}=s,{details:p}=c,g=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=py,f){if(null!=f&&f.tracks){const e=o.initSegment||o;this._bufferInitSegment(c,f.tracks,e,i),n.trigger(Vf.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:r,tracks:f.tracks})}const e=f.initPTS,t=f.timescale;Hf(e)&&(this.initPTS[o.cc]={baseTime:e,timescale:t},n.trigger(Vf.INIT_PTS_FOUND,{frag:o,id:r,initPTS:e,timescale:t}))}if(d&&p&&"initSegment"!==o.sn){const e=p.fragments[o.sn-1-p.startSN],t=o.sn===p.startSN,r=!e||o.cc>e.cc;if(!1!==s.independent){const{startPTS:e,endPTS:n,startDTS:s,endDTS:a}=d;if(l)l.elementaryStreams[d.type]={startPTS:e,endPTS:n,startDTS:s,endDTS:a};else if(d.firstKeyFrame&&d.independent&&1===i.id&&!r&&(this.couldBacktrack=!0),d.dropped&&d.independent){const s=this.getMainFwdBufferInfo(),i=(s?s.end:this.getLoadPosition())+this.config.maxBufferHole,l=d.firstKeyFramePTS?d.firstKeyFramePTS:e;if(!t&&i<l-this.config.maxBufferHole&&!r)return void this.backtrack(o);r&&(o.gap=!0),o.setElementaryStreamInfo(d.type,o.start,n,o.start,a,!0)}o.setElementaryStreamInfo(d.type,e,n,s,a),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(d,o,l,i,t||r)}else{if(!t&&!r)return void this.backtrack(o);o.gap=!0}}if(g){const{startPTS:e,endPTS:t,startDTS:r,endDTS:n}=g;l&&(l.elementaryStreams[ap]={startPTS:e,endPTS:t,startDTS:r,endDTS:n}),o.setElementaryStreamInfo(ap,e,t,r,n),this.bufferFragmentData(g,o,l,i)}if(p&&null!=h&&null!=(t=h.samples)&&t.length){const e={id:r,frag:o,details:p,samples:h.samples};n.trigger(Vf.FRAG_PARSING_METADATA,e)}if(p&&u){const e={id:r,frag:o,details:p,samples:u.samples};n.trigger(Vf.FRAG_PARSING_USERDATA,e)}}}_bufferInitSegment(e,t,r,n){if(this.state!==py)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;const{audio:s,video:i,audiovideo:a}=t;if(s){let t=e.audioCodec;const r=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(t&&(t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),1!==s.metadata.channelCount&&-1===r.indexOf("firefox")&&(t="mp4a.40.5")),-1!==r.indexOf("android")&&"audio/mpeg"!==s.container&&(t="mp4a.40.2",this.log(`Android: force audio codec to ${t}`)),e.audioCodec&&e.audioCodec!==t&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${t}"`),s.levelCodec=t,s.id="main",this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${t||""}/${e.audioCodec||""}/${s.codec}]`)}i&&(i.levelCodec=e.videoCodec,i.id="main",this.log(`Init video buffer, container:${i.container}, codecs[level/parsed]=[${e.videoCodec||""}/${i.codec}]`)),a&&this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.attrs.CODECS||""}/${a.codec}]`),this.hls.trigger(Vf.BUFFER_CODECS,t),Object.keys(t).forEach((e=>{const s=t[e].initSegment;null!=s&&s.byteLength&&this.hls.trigger(Vf.BUFFER_APPENDING,{type:e,data:s,frag:r,part:null,chunkMeta:n,parent:r.type})})),this.tick()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,Ng)}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=cy}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const r=e.currentTime;if(Qm.isBuffered(e,r)?t=this.getAppendedFrag(r):Qm.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t){this.backtrackFragment=null;const e=this.fragPlaying,r=t.level;e&&t.sn===e.sn&&e.level===r&&t.urlId===e.urlId||(this.fragPlaying=t,this.hls.trigger(Vf.FRAG_CHANGED,{frag:t}),e&&e.level===r||this.hls.trigger(Vf.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){const e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){const e=this.media;if(e){const t=e.currentTime,r=this.currentFrag;if(r&&Hf(t)&&Hf(r.programDateTime)){const e=r.programDateTime+1e3*(t-r.start);return new Date(e)}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class Iv{constructor(e,t=0,r=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=r}sample(e,t){const r=Math.pow(this.alpha_,e);this.estimate_=t*(1-r)+r*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class _v{constructor(e,t,r,n=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Iv(e),this.fast_=new Iv(t),this.defaultTTFB_=n,this.ttfb_=new Iv(e)}update(e,t){const{slow_:r,fast_:n,ttfb_:s}=this;r.halfLife!==e&&(this.slow_=new Iv(e,r.getEstimate(),r.getTotalWeight())),n.halfLife!==t&&(this.fast_=new Iv(t,n.getEstimate(),n.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new Iv(e,s.getEstimate(),s.getTotalWeight()))}sample(e,t){const r=(e=Math.max(e,this.minDelayMs_))/1e3,n=8*t/r;this.fast_.sample(r,n),this.slow_.sample(r,n)}sampleTTFB(e){const t=e/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(r,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}destroy(){}}class Rv{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let r;return e.length?(r=1===e.length?e[0]:function(e,t){const r=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.length}return r}(e,t),this.reset(),r):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}function Lv(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Dv(e[r].attrs,t[r].attrs))return!1;return!0}function Dv(e,t){const r=e["STABLE-RENDITION-ID"];return r?r===t["STABLE-RENDITION-ID"]:!["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED"].some((r=>e[r]!==t[r]))}class xv{constructor(e){this.buffered=void 0;const t=(t,r,n)=>{if((r>>>=0)>n-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${r}) is greater than the maximum bound (${n})`);return e[r][t]};this.buffered={get length(){return e.length},end:r=>t("end",r,e.length),start:r=>t("start",r,e.length)}}}function Ov(e){const t=[];for(let r=0;r<e.length;r++){const n=e[r];"subtitles"!==n.kind&&"captions"!==n.kind||!n.label||t.push(e[r])}return t}class Pv{constructor(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}append(e,t){const r=this.queues[t];r.push(e),1===r.length&&this.buffers[t]&&this.executeNext(t)}insertAbort(e,t){this.queues[t].unshift(e),this.executeNext(t)}appendBlocker(e){let t;const r=new Promise((e=>{t=e})),n={execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(n,e),r}executeNext(e){const{buffers:t,queues:r}=this,n=t[e],s=r[e];if(s.length){const t=s[0];try{t.execute()}catch(r){Zf.warn("[buffer-operation-queue]: Unhandled exception executing the current operation"),t.onError(r),null!=n&&n.updating||(s.shift(),this.executeNext(e))}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}}const Mv=yg(),Fv=/([ha]vc.)(?:\.[^.,]+)+/;const Uv={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},Nv=function(e){let t=e;return Uv.hasOwnProperty(e)&&(t=Uv[e]),String.fromCharCode(t)},Bv=15,jv=100,$v={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},qv={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Kv={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Gv={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Hv=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Vv{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const r="function"==typeof t?t():t;Zf.log(`${this.time} [${e}] ${r}`)}}}const zv=function(e){const t=[];for(let r=0;r<e.length;r++)t.push(e[r].toString(16));return t};class Wv{constructor(e,t,r,n,s){this.foreground=void 0,this.underline=void 0,this.italics=void 0,this.background=void 0,this.flash=void 0,this.foreground=e||"white",this.underline=t||!1,this.italics=r||!1,this.background=n||"black",this.flash=s||!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let r=0;r<t.length;r++){const n=t[r];e.hasOwnProperty(n)&&(this[n]=e[n])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class Yv{constructor(e,t,r,n,s,i){this.uchar=void 0,this.penState=void 0,this.uchar=e||" ",this.penState=new Wv(t,r,n,s,i)}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class Qv{constructor(e){this.chars=void 0,this.pos=void 0,this.currPenState=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chars=[];for(let e=0;e<jv;e++)this.chars.push(new Yv);this.logger=e,this.pos=0,this.currPenState=new Wv}equals(e){let t=!0;for(let r=0;r<jv;r++)if(!this.chars[r].equals(e.chars[r])){t=!1;break}return t}copy(e){for(let t=0;t<jv;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<jv;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>jv&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=jv)}moveCursor(e){const t=this.pos+e;if(e>1)for(let e=this.pos+1;e<t+1;e++)this.chars[e].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=Nv(e);this.pos>=jv?this.logger.log(0,(()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!")):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}clearFromPos(e){let t;for(t=e;t<jv;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let r=0;r<jv;r++){const n=this.chars[r].uchar;" "!==n&&(t=!1),e.push(n)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e);this.chars[this.pos].setPenState(this.currPenState)}}class Xv{constructor(e){this.rows=void 0,this.currRow=void 0,this.nrRollUpRows=void 0,this.lastOutputScreen=void 0,this.logger=void 0,this.rows=[];for(let t=0;t<Bv;t++)this.rows.push(new Qv(e));this.logger=e,this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.reset()}reset(){for(let e=0;e<Bv;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let r=0;r<Bv;r++)if(!this.rows[r].equals(e.rows[r])){t=!1;break}return t}copy(e){for(let t=0;t<Bv;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<Bv;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e);this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,(()=>"pacData = "+JSON.stringify(e)));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let e=0;e<Bv;e++)this.rows[e].clear();const e=this.currRow+1-this.nrRollUpRows,r=this.lastOutputScreen;if(r){const n=r.rows[e].cueStartTime,s=this.logger.time;if(n&&null!==s&&n<s)for(let n=0;n<this.nrRollUpRows;n++)this.rows[t-this.nrRollUpRows+n+1].copy(r.rows[e+n])}}this.currRow=t;const r=this.rows[this.currRow];if(null!==e.indent){const t=e.indent,n=Math.max(t-1,0);r.setCursor(e.indent),e.color=r.chars[n].penState.foreground}const n={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(n)}setBkgData(e){this.logger.log(2,(()=>"bkgData = "+JSON.stringify(e))),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,(()=>this.getDisplayText()));const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let r="",n=-1;for(let r=0;r<Bv;r++){const s=this.rows[r].getTextString();s&&(n=r+1,e?t.push("Row "+n+": '"+s+"'"):t.push(s.trim()))}return t.length>0&&(r=e?"["+t.join(" | ")+"]":t.join("\n")),r}getTextAndFormat(){return this.rows}}class Jv{constructor(e,t,r){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new Xv(r),this.nonDisplayedMemory=new Xv(r),this.lastOutputScreen=new Xv(r),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=r}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,(()=>"MODE="+e)),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,(()=>t+": "+this.writeScreen.getDisplayText(!0))),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,(()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0))),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(()=>"DISP: "+this.displayedMemory.getDisplayText()))}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{const r=Math.floor(e/2)-16,n=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=n[r]}this.logger.log(2,"MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class Zv{constructor(e,t,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=void 0,this.logger=void 0;const n=new Vv;this.channels=[null,new Jv(e,t,n),new Jv(e+1,r,n)],this.cmdHistory={a:null,b:null},this.logger=n}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){let r,n,s,i=!1;this.logger.time=e;for(let e=0;e<t.length;e+=2)if(n=127&t[e],s=127&t[e+1],0!==n||0!==s){if(this.logger.log(3,"["+zv([t[e],t[e+1]])+"] -> ("+zv([n,s])+")"),r=this.parseCmd(n,s),r||(r=this.parseMidrow(n,s)),r||(r=this.parsePAC(n,s)),r||(r=this.parseBackgroundAttributes(n,s)),!r&&(i=this.parseChars(n,s),i)){const e=this.currentChannel;if(e&&e>0){this.channels[e].insertChars(i)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}r||i||this.logger.log(2,"Couldn't parse cleaned data "+zv([n,s])+" orig: "+zv([t[e],t[e+1]]))}}parseCmd(e,t){const{cmdHistory:r}=this;if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=33&&t<=35))return!1;if(tb(e,t,r))return eb(null,null,r),this.logger.log(3,"Repeated command ("+zv([e,t])+") is dropped"),!0;const n=20===e||21===e||23===e?1:2,s=this.channels[n];return 20===e||21===e||28===e||29===e?32===t?s.ccRCL():33===t?s.ccBS():34===t?s.ccAOF():35===t?s.ccAON():36===t?s.ccDER():37===t?s.ccRU(2):38===t?s.ccRU(3):39===t?s.ccRU(4):40===t?s.ccFON():41===t?s.ccRDC():42===t?s.ccTR():43===t?s.ccRTD():44===t?s.ccEDM():45===t?s.ccCR():46===t?s.ccENM():47===t&&s.ccEOC():s.ccTO(t-32),eb(e,t,r),this.currentChannel=n,!0}parseMidrow(e,t){let r=0;if((17===e||25===e)&&t>=32&&t<=47){if(r=17===e?1:2,r!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const n=this.channels[r];return!!n&&(n.ccMIDROW(t),this.logger.log(3,"MIDROW ("+zv([e,t])+")"),!0)}return!1}parsePAC(e,t){let r;const n=this.cmdHistory;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;if(tb(e,t,n))return eb(null,null,n),!0;const s=e<=23?1:2;r=t>=64&&t<=95?1===s?$v[e]:Kv[e]:1===s?qv[e]:Gv[e];const i=this.channels[s];return!!i&&(i.setPAC(this.interpretPAC(r,t)),eb(e,t,n),this.currentChannel=s,!0)}interpretPAC(e,t){let r;const n={color:null,italics:!1,indent:null,underline:!1,row:e};return r=t>95?t-96:t-64,n.underline=1==(1&r),r<=13?n.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(n.italics=!0,n.color="white"):n.indent=4*Math.floor((r-16)/2),n}parseChars(e,t){let r,n=null,s=null;if(e>=25?(r=2,s=e-8):(r=1,s=e),s>=17&&s<=19){let e;e=17===s?t+80:18===s?t+112:t+144,this.logger.log(2,"Special char '"+Nv(e)+"' in channel "+r),n=[e]}else e>=32&&e<=127&&(n=0===t?[e]:[e,t]);if(n){const r=zv(n);this.logger.log(3,"Char codes = "+r.join(",")),eb(e,t,this.cmdHistory)}return n}parseBackgroundAttributes(e,t){if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;let r;const n={};16===e||24===e?(r=Math.floor((t-32)/2),n.background=Hv[r],t%2==1&&(n.background=n.background+"_semi")):45===t?n.background="transparent":(n.foreground="black",47===t&&(n.underline=!0));const s=e<=23?1:2;return this.channels[s].setBkgData(n),eb(e,t,this.cmdHistory),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}this.cmdHistory={a:null,b:null}}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const r=this.channels[t];r&&r.cueSplitAtTime(e)}}}function eb(e,t,r){r.a=e,r.b=t}function tb(e,t,r){return r.a===e&&r.b===t}class rb{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,r){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var nb=function(){if("undefined"!=typeof self&&self.VTTCue)return self.VTTCue;const e=["","lr","rl"],t=["start","middle","end","left","right"];function r(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;const r=t.toLowerCase();return!!~e.indexOf(r)&&r}function n(e){return r(t,e)}function s(e,...t){let r=1;for(;r<arguments.length;r++){const t=arguments[r];for(const r in t)e[r]=t[r]}return e}function i(t,i,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let c="",d=!1,u=t,h=i,f=a,p=null,g="",m=!0,y="auto",v="start",b=50,w="middle",E=50,S="middle";Object.defineProperty(o,"id",s({},l,{get:function(){return c},set:function(e){c=""+e}})),Object.defineProperty(o,"pauseOnExit",s({},l,{get:function(){return d},set:function(e){d=!!e}})),Object.defineProperty(o,"startTime",s({},l,{get:function(){return u},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");u=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",s({},l,{get:function(){return h},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");h=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",s({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",s({},l,{get:function(){return p},set:function(e){p=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",s({},l,{get:function(){return g},set:function(t){const n=function(t){return r(e,t)}(t);if(!1===n)throw new SyntaxError("An invalid or illegal string was specified.");g=n,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",s({},l,{get:function(){return m},set:function(e){m=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",s({},l,{get:function(){return y},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",s({},l,{get:function(){return v},set:function(e){const t=n(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");v=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",s({},l,{get:function(){return b},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");b=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",s({},l,{get:function(){return w},set:function(e){const t=n(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");w=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",s({},l,{get:function(){return E},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",s({},l,{get:function(){return S},set:function(e){const t=n(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");S=t,this.hasBeenReset=!0}})),o.displayState=void 0}return i.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},i}();class sb{decode(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function ib(e){function t(e,t,r,n){return 3600*(0|e)+60*(0|t)+(0|r)+parseFloat(n||0)}const r=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?t(r[2],r[3],0,r[4]):t(r[1],r[2],r[3],r[4]):null}class ab{constructor(){this.values=Object.create(null)}set(e,t){this.get(e)||""===t||(this.values[e]=t)}get(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,r){for(let n=0;n<r.length;++n)if(t===r[n]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const r=parseFloat(t);if(r>=0&&r<=100)return this.set(e,r),!0}return!1}}function ob(e,t,r,n){const s=n?e.split(n):[e];for(const e in s){if("string"!=typeof s[e])continue;const n=s[e].split(r);if(2!==n.length)continue;t(n[0],n[1])}}const lb=new nb(0,0,""),cb="middle"===lb.align?"middle":"center";function db(e,t,r){const n=e;function s(){const t=ib(e);if(null===t)throw new Error("Malformed timestamp: "+n);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function i(){e=e.replace(/^\s+/,"")}if(i(),t.startTime=s(),i(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+n);e=e.slice(3),i(),t.endTime=s(),i(),function(e,t){const n=new ab;ob(e,(function(e,t){let s;switch(e){case"region":for(let s=r.length-1;s>=0;s--)if(r[s].id===t){n.set(e,r[s].region);break}break;case"vertical":n.alt(e,t,["rl","lr"]);break;case"line":s=t.split(","),n.integer(e,s[0]),n.percent(e,s[0])&&n.set("snapToLines",!1),n.alt(e,s[0],["auto"]),2===s.length&&n.alt("lineAlign",s[1],["start",cb,"end"]);break;case"position":s=t.split(","),n.percent(e,s[0]),2===s.length&&n.alt("positionAlign",s[1],["start",cb,"end","line-left","line-right","auto"]);break;case"size":n.percent(e,t);break;case"align":n.alt(e,t,["start",cb,"end","left","right"])}}),/:/,/\s/),t.region=n.get("region",null),t.vertical=n.get("vertical","");let s=n.get("line","auto");"auto"===s&&-1===lb.line&&(s=-1),t.line=s,t.lineAlign=n.get("lineAlign","start"),t.snapToLines=n.get("snapToLines",!0),t.size=n.get("size",100),t.align=n.get("align",cb);let i=n.get("position","auto");"auto"===i&&50===lb.position&&(i="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=i}(e,t)}function ub(e){return e.replace(/<br(?: \/)?>/gi,"\n")}class hb{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new sb,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;function r(){let e=t.buffer,r=0;for(e=ub(e);r<e.length&&"\r"!==e[r]&&"\n"!==e[r];)++r;const n=e.slice(0,r);return"\r"===e[r]&&++r,"\n"===e[r]&&++r,t.buffer=e.slice(r),n}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{let e="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;e=r();const n=e.match(/^()?WEBVTT([ \t].*)?$/);if(null==n||!n[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let n=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(n?n=!1:e=r(),t.state){case"HEADER":/:/.test(e)?ob(e,(function(e,t){}),/:/):e||(t.state="ID");continue;case"NOTE":e||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(e)){t.state="NOTE";break}if(!e)continue;if(t.cue=new nb(0,0,""),t.state="CUE",-1===e.indexOf("--\x3e")){t.cue.id=e;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{db(e,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const r=-1!==e.indexOf("--\x3e");if(!e||r&&(n=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=e}continue;case"BADCUE":e||(t.state="ID")}}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const fb=/\r\n|\n\r|\n|\r/g,pb=function(e,t,r=0){return e.slice(r,r+t.length)===t},gb=function(e){let t=5381,r=e.length;for(;r;)t=33*t^e.charCodeAt(--r);return(t>>>0).toString()};function mb(e,t,r){return gb(e.toString())+gb(t.toString())+gb(r)}function yb(e,t,r,n,s,i,a){const o=new hb,l=jp(new Uint8Array(e)).trim().replace(fb,"\n").split("\n"),c=[],d=t?function(e,t=1){return nv(e,9e4,1/t)}(t.baseTime,t.timescale):0;let u,h="00:00.000",f=0,p=0,g=!0;o.oncue=function(e){const i=r[n];let a=r.ccOffset;const o=(f-d)/9e4;if(null!=i&&i.new&&(void 0!==p?a=r.ccOffset=i.start:function(e,t,r){let n=e[t],s=e[n.prevCC];if(!s||!s.new&&n.new)return e.ccOffset=e.presentationOffset=n.start,void(n.new=!1);for(;null!=(i=s)&&i.new;){var i;e.ccOffset+=n.start-s.start,n.new=!1,n=s,s=e[n.prevCC]}e.presentationOffset=r}(r,n,o)),o){if(!t)return void(u=new Error("Missing initPTS for VTT MPEGTS"));a=o-r.presentationOffset}const l=e.endTime-e.startTime,h=cv(9e4*(e.startTime+a-p),9e4*s)/9e4;e.startTime=Math.max(h,0),e.endTime=Math.max(h+l,0);const g=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(g)),e.id||(e.id=mb(e.startTime,e.endTime,g)),e.endTime>0&&c.push(e)},o.onparsingerror=function(e){u=e},o.onflush=function(){u?a(u):i(c)},l.forEach((e=>{if(g){if(pb(e,"X-TIMESTAMP-MAP=")){g=!1,e.slice(16).split(",").forEach((e=>{pb(e,"LOCAL:")?h=e.slice(6):pb(e,"MPEGTS:")&&(f=parseInt(e.slice(7)))}));try{p=function(e){let t=parseInt(e.slice(-3));const r=parseInt(e.slice(-6,-4)),n=parseInt(e.slice(-9,-7)),s=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(Hf(t)&&Hf(r)&&Hf(n)&&Hf(s)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*r,t+=6e4*n,t+=36e5*s,t}(h)/1e3}catch(e){u=e}return}""===e&&(g=!1)}o.parse(e+"\n")})),o.flush()}const vb="stpp.ttml.im1t",bb=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,wb=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Eb={left:"start",center:"center",right:"end",start:"start",end:"end"};function Sb(e,t,r,n){const s=Jp(new Uint8Array(e),["mdat"]);if(0===s.length)return void n(new Error("Could not parse IMSC1 mdat"));const i=s.map((e=>jp(e))),a=function(e,t,r=1,n=!1){return nv(e,t,1/r,n)}(t.baseTime,1,t.timescale);try{i.forEach((e=>r(function(e,t){const r=new DOMParser,n=r.parseFromString(e,"text/xml").getElementsByTagName("tt")[0];if(!n)throw new Error("Invalid ttml");const s={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},i=Object.keys(s).reduce(((e,t)=>(e[t]=n.getAttribute(`ttp:${t}`)||s[t],e)),{}),a="preserve"!==n.getAttribute("xml:space"),o=Cb(Tb(n,"styling","style")),l=Cb(Tb(n,"layout","region")),c=Tb(n,"body","[begin]");return[].map.call(c,(e=>{const r=kb(e,a);if(!r||!e.hasAttribute("begin"))return null;const n=_b(e.getAttribute("begin"),i),s=_b(e.getAttribute("dur"),i);let c=_b(e.getAttribute("end"),i);if(null===n)throw Ib(e);if(null===c){if(null===s)throw Ib(e);c=n+s}const d=new nb(n-t,c-t,r);d.id=mb(d.startTime,d.endTime,d.text);const u=function(e,t,r){const n="http://www.w3.org/ns/ttml#styling";let s=null;const i=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;a&&r.hasOwnProperty(a)&&(s=r[a]);return i.reduce(((r,i)=>{const a=Ab(t,n,i)||Ab(e,n,i)||Ab(s,n,i);return a&&(r[i]=a),r}),{})}(l[e.getAttribute("region")],o[e.getAttribute("style")],o),{textAlign:h}=u;if(h){const e=Eb[h];e&&(d.lineAlign=e),d.align=h}return Gf(d,u),d})).filter((e=>null!==e))}(e,a))))}catch(e){n(e)}}function Tb(e,t,r){const n=e.getElementsByTagName(t)[0];return n?[].slice.call(n.querySelectorAll(r)):[]}function Cb(e){return e.reduce(((e,t)=>{const r=t.getAttribute("xml:id");return r&&(e[r]=t),e}),{})}function kb(e,t){return[].slice.call(e.childNodes).reduce(((e,r,n)=>{var s;return"br"===r.nodeName&&n?e+"\n":null!=(s=r.childNodes)&&s.length?kb(r,t):t?e+r.textContent.trim().replace(/\s+/g," "):e+r.textContent}),"")}function Ab(e,t,r){return e&&e.hasAttributeNS(t,r)?e.getAttributeNS(t,r):null}function Ib(e){return new Error(`Could not parse ttml timestamp ${e}`)}function _b(e,t){if(!e)return null;let r=ib(e);return null===r&&(bb.test(e)?r=function(e,t){const r=bb.exec(e),n=(0|r[4])+(0|r[5])/t.subFrameRate;return 3600*(0|r[1])+60*(0|r[2])+(0|r[3])+n/t.frameRate}(e,t):wb.test(e)&&(r=function(e,t){const r=wb.exec(e),n=Number(r[1]);switch(r[2]){case"h":return 3600*n;case"m":return 60*n;case"ms":return 1e3*n;case"f":return n/t.frameRate;case"t":return n/t.tickRate}return n}(e,t))),r}function Rb(e,t){return!!e&&e.label===t.name&&!(e.textTrack1||e.textTrack2)}class Lb{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.unregisterListener(),this.hls.config.capLevelToPlayerSize&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(Vf.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(Vf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Vf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Vf.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Vf.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(Vf.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(Vf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Vf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Vf.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Vf.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const r=this.hls.levels[t.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null}onManifestParsed(e,t){const r=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,r.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media&&this.mediaHeight>0&&this.mediaWidth>0){const e=this.hls.levels;if(e.length){const t=this.hls;t.autoLevelCapping=this.getMaxLevel(e.length-1),t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const r=t.filter(((t,r)=>this.isLevelAllowed(t)&&r<=e));return this.clientRect=null,Lb.getMaxLevelByMediaSize(r,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,t.width||t.height||(t.width=r.right-r.left||e.width||0,t.height=r.bottom-r.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(e){}return e}isLevelAllowed(e){return!this.restrictedLevels.some((t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height))}static getMaxLevelByMediaSize(e,t,r){if(null==e||!e.length)return-1;let n=e.length-1;for(let a=0;a<e.length;a+=1){const o=e[a];if((o.width>=t||o.height>=r)&&(s=o,!(i=e[a+1])||s.width!==i.width||s.height!==i.height)){n=a;break}}var s,i;return n}}const Db="[eme]";class xb{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=xb.CDMCleanupPromise?[xb.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=Zf.debug.bind(Zf,Db),this.log=Zf.log.bind(Zf,Db),this.warn=Zf.warn.bind(Zf,Db),this.error=Zf.error.bind(Zf,Db),this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(Vf.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(Vf.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(Vf.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(Vf.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(Vf.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(Vf.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:r}=this.config,n=t[e];if(n)return n.licenseUrl;if(e===mp.WIDEVINE&&r)return r;throw new Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){const{drmSystems:t}=this.config,r=t[e];if(r)return r.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,r=(e,t,r)=>!!e&&r.indexOf(e)===t,n=t.map((e=>e.audioCodec)).filter(r),s=t.map((e=>e.videoCodec)).filter(r);return n.length+s.length===0&&s.push("avc1.42e01e"),new Promise(((t,r)=>{const i=e=>{const a=e.shift();this.getMediaKeysPromise(a,n,s).then((e=>t({keySystem:a,mediaKeys:e}))).catch((t=>{e.length?i(e):r(t instanceof Ob?t:new Ob({type:zf.KEY_SYSTEM_ERROR,details:Wf.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))}))};i(e)}))}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:r}=this.config;if("function"!=typeof r){let e=`Configured requestMediaKeySystemAccess is not a function ${r}`;return null===kp&&"http:"===self.location.protocol&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(e))}return r(e,t)}getMediaKeysPromise(e,t,r){const n=function(e,t,r,n){let s;switch(e){case mp.FAIRPLAY:s=["cenc","sinf"];break;case mp.WIDEVINE:case mp.PLAYREADY:s=["cenc"];break;case mp.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${e}`)}return function(e,t,r,n){return[{initDataTypes:e,persistentState:n.persistentState||"not-allowed",distinctiveIdentifier:n.distinctiveIdentifier||"not-allowed",sessionTypes:n.sessionTypes||[n.sessionType||"temporary"],audioCapabilities:t.map((e=>({contentType:`audio/mp4; codecs="${e}"`,robustness:n.audioRobustness||"",encryptionScheme:n.audioEncryptionScheme||null}))),videoCapabilities:r.map((e=>({contentType:`video/mp4; codecs="${e}"`,robustness:n.videoRobustness||"",encryptionScheme:n.videoEncryptionScheme||null})))}]}(s,t,r,n)}(e,t,r,this.config.drmSystemOptions),s=this.keySystemAccessPromises[e];let i=null==s?void 0:s.keySystemAccess;if(!i){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(n)}`),i=this.requestMediaKeySystemAccess(e,n);const t=this.keySystemAccessPromises[e]={keySystemAccess:i};return i.catch((t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)})),i.then((r=>{this.log(`Access for key-system "${r.keySystem}" obtained`);const n=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),t.mediaKeys=r.createMediaKeys().then((t=>(this.log(`Media-keys created for "${e}"`),n.then((r=>r?this.setMediaKeysServerCertificate(t,e,r):t))))),t.mediaKeys.catch((t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)})),t.mediaKeys}))}return i.then((()=>s.mediaKeys))}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:r}){this.log(`Creating key-system session "${t}" keyId: ${Kp(e.keyId||[])}`);const n=r.createSession(),s={decryptdata:e,keySystem:t,mediaKeys:r,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const r=this.createMediaKeySessionContext(e),n=this.getKeyIdString(t),s="cenc";this.keyIdToKeySessionPromise[n]=this.generateRequestWithPreferredKeySession(r,s,t.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return Kp(e.keyId)}updateKeySession(e,t){var r;const n=e.mediaKeysSession;return this.log(`Updating key-session "${n.sessionId}" for keyID ${Kp((null==(r=e.decryptdata)?void 0:r.keyId)||[])}\n } (data length: ${t?t.byteLength:t})`),n.update(t)}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise(((t,r)=>{const n=Cp(this.config),s=e.map(Ep).filter((e=>!!e&&-1!==n.indexOf(e)));return this.getKeySystemSelectionPromise(s).then((({keySystem:e})=>{const n=Tp(e);n?t(n):r(new Error(`Unable to find format for key-system "${e}"`))})).catch(r)}))}loadKey(e){const t=e.keyInfo.decryptdata,r=this.getKeyIdString(t),n=`(keyId: ${r} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${n}`);let s=this.keyIdToKeySessionPromise[r];return s||(s=this.keyIdToKeySessionPromise[r]=this.getKeySystemForKeyPromise(t).then((({keySystem:r,mediaKeys:s})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${n}`),this.attemptSetMediaKeys(r,s).then((()=>{this.throwIfDestroyed();const e=this.createMediaKeySessionContext({keySystem:r,mediaKeys:s,decryptdata:t});return this.generateRequestWithPreferredKeySession(e,"cenc",t.pssh,"playlist-key")}))))),s.catch((e=>this.handleError(e)))),s}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof Ob?this.hls.trigger(Vf.ERROR,e.data):this.hls.trigger(Vf.ERROR,{type:zf.KEY_SYSTEM_ERROR,details:Wf.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),r=this.keyIdToKeySessionPromise[t];if(!r){const t=Ep(e.keyFormat),r=t?[t]:Cp(this.config);return this.attemptKeySystemAccess(r)}return r}getKeySystemSelectionPromise(e){if(e.length||(e=Cp(this.config)),0===e.length)throw new Ob({type:zf.KEY_SYSTEM_ERROR,details:Wf.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){const{initDataType:t,initData:r}=e;if(this.debug(`"${e.type}" event: init data type: "${t}"`),null===r)return;let n,s;if("sinf"===t&&this.config.drmSystems[mp.FAIRPLAY]){const e=zp(new Uint8Array(r));try{const t=fp(JSON.parse(e).sinf),r=tg(new Uint8Array(t));if(!r)return;n=r.subarray(8,24),s=mp.FAIRPLAY}catch(e){return void this.warn('Failed to parse sinf "encrypted" event message initData')}}else{const e=function(e){if(!(e instanceof ArrayBuffer)||e.byteLength<32)return null;const t={version:0,systemId:"",kids:null,data:null},r=new DataView(e),n=r.getUint32(0);if(e.byteLength!==n&&n>44)return null;if(1886614376!==r.getUint32(4))return null;if(t.version=r.getUint32(8)>>>24,t.version>1)return null;t.systemId=Kp(new Uint8Array(e,12,16));const s=r.getUint32(28);if(0===t.version){if(n-32<s)return null;t.data=new Uint8Array(e,32,s)}else if(1===t.version){t.kids=[];for(let r=0;r<s;r++)t.kids.push(new Uint8Array(e,32+16*r,16))}return t}(r);if(null===e)return;0===e.version&&e.systemId===Sp&&e.data&&(n=e.data.subarray(8,24)),s=function(e){if(e===Sp)return mp.WIDEVINE}(e.systemId)}if(!s||!n)return;const i=Kp(n),{keyIdToKeySessionPromise:a,mediaKeySessions:o}=this;let l=a[i];for(let e=0;e<o.length;e++){const s=o[e],c=s.decryptdata;if(c.pssh||!c.keyId)continue;const d=Kp(c.keyId);if(i===d||-1!==c.uri.replace(/-/g,"").indexOf(i)){l=a[d],delete a[d],c.pssh=new Uint8Array(r),c.keyId=n,l=a[i]=l.then((()=>this.generateRequestWithPreferredKeySession(s,t,r,"encrypted-event-key-match")));break}}l||(l=a[i]=this.getKeySystemSelectionPromise([s]).then((({keySystem:e,mediaKeys:s})=>{var a;this.throwIfDestroyed();const o=new dg("ISO-23001-7",i,null!=(a=Tp(e))?a:"");return o.pssh=new Uint8Array(r),o.keyId=n,this.attemptSetMediaKeys(e,s).then((()=>{this.throwIfDestroyed();const n=this.createMediaKeySessionContext({decryptdata:o,keySystem:e,mediaKeys:s});return this.generateRequestWithPreferredKeySession(n,t,r,"encrypted-event-no-match")}))}))),l.catch((e=>this.handleError(e)))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,t){const r=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const n=Promise.all(r).then((()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)}));return this.setMediaKeysQueue.push(n),n.then((()=>{this.log(`Media-keys set for "${e}"`),r.push(n),this.setMediaKeysQueue=this.setMediaKeysQueue.filter((e=>-1===r.indexOf(e)))}))}generateRequestWithPreferredKeySession(e,t,r,n){var s,i;const a=null==(s=this.config.drmSystems)||null==(i=s[e.keySystem])?void 0:i.generateRequest;if(a)try{const n=a.call(this.hls,t,r,e);if(!n)throw new Error("Invalid response from configured generateRequest filter");t=n.initDataType,r=e.decryptdata.pssh=n.initData?new Uint8Array(n.initData):null}catch(e){var o;if(this.warn(e.message),null!=(o=this.hls)&&o.config.debug)throw e}if(null===r)return this.log(`Skipping key-session request for "${n}" (no initData)`),Promise.resolve(e);const l=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${n}": ${l} (init data type: ${t} length: ${r?r.byteLength:null})`);const c=new Sv;e.mediaKeysSession.onmessage=t=>{const r=e.mediaKeysSession;if(!r)return void c.emit("error",new Error("invalid state"));const{messageType:n,message:s}=t;this.log(`"${n}" message event for session "${r.sessionId}" message size: ${s.byteLength}`),"license-request"===n||"license-renewal"===n?this.renewLicense(e,s).catch((e=>{this.handleError(e),c.emit("error",e)})):"license-release"===n?e.keySystem===mp.FAIRPLAY&&(this.updateKeySession(e,gp("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${n}"`)},e.mediaKeysSession.onkeystatuseschange=t=>{if(!e.mediaKeysSession)return void c.emit("error",new Error("invalid state"));this.onKeyStatusChange(e);const r=e.keyStatus;c.emit("keyStatus",r),"expired"===r&&(this.warn(`${e.keySystem} expired for key ${l}`),this.renewKeySession(e))};const d=new Promise(((e,t)=>{c.on("error",t),c.on("keyStatus",(r=>{r.startsWith("usable")?e():"output-restricted"===r?t(new Ob({type:zf.KEY_SYSTEM_ERROR,details:Wf.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===r?t(new Ob({type:zf.KEY_SYSTEM_ERROR,details:Wf.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${r}"`)):"expired"===r?t(new Error("key expired while generating request")):this.warn(`unhandled key status change "${r}"`)}))}));return e.mediaKeysSession.generateRequest(t,r).then((()=>{var t;this.log(`Request generated for key-session "${null==(t=e.mediaKeysSession)?void 0:t.sessionId}" keyId: ${l}`)})).catch((e=>{throw new Ob({type:zf.KEY_SYSTEM_ERROR,details:Wf.KEY_SYSTEM_NO_SESSION,error:e,fatal:!1},`Error generating key-session request: ${e}`)})).then((()=>d)).catch((t=>{throw c.removeAllListeners(),this.removeSession(e),t})).then((()=>(c.removeAllListeners(),e)))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach(((t,r)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${Kp("buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r))} session keyId: ${Kp(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t}))}fetchServerCertificate(e){const t=this.config,r=new(0,t.loader)(t),n=this.getServerCertificateUrl(e);return n?(this.log(`Fetching serverCertificate for "${e}"`),new Promise(((s,i)=>{const a={responseType:"arraybuffer",url:n},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(e,t,r,n)=>{s(e.data)},onError:(t,r,s,o)=>{i(new Ob({type:zf.KEY_SYSTEM_ERROR,details:Wf.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:qf({url:a.url,data:void 0},t)},`"${e}" certificate request failed (${n}). Status: ${t.code} (${t.text})`))},onTimeout:(t,r,s)=>{i(new Ob({type:zf.KEY_SYSTEM_ERROR,details:Wf.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:{url:a.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(e,t,r)=>{i(new Error("aborted"))}};r.load(a,l,c)}))):Promise.resolve()}setMediaKeysServerCertificate(e,t,r){return new Promise(((n,s)=>{e.setServerCertificate(r).then((s=>{this.log(`setServerCertificate ${s?"success":"not supported by CDM"} (${null==r?void 0:r.byteLength}) on "${t}"`),n(e)})).catch((e=>{s(new Ob({type:zf.KEY_SYSTEM_ERROR,details:Wf.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))}))}))}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then((t=>this.updateKeySession(e,new Uint8Array(t)).catch((e=>{throw new Ob({type:zf.KEY_SYSTEM_ERROR,details:Wf.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:e,fatal:!0},e.message)}))))}setupLicenseXHR(e,t,r,n){const s=this.config.licenseXhrSetup;return s?Promise.resolve().then((()=>{if(!r.decryptdata)throw new Error("Key removed");return s.call(this.hls,e,t,r,n)})).catch((i=>{if(!r.decryptdata)throw i;return e.open("POST",t,!0),s.call(this.hls,e,t,r,n)})).then((r=>{e.readyState||e.open("POST",t,!0);return{xhr:e,licenseChallenge:r||n}})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:n}))}requestLicense(e,t){const r=this.config.keyLoadPolicy.default;return new Promise(((n,s)=>{const i=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${i}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return s(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let t=a.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);const r=this.config.licenseResponseCallback;if(r)try{t=r.call(this.hls,a,i,e)}catch(e){this.error(e)}n(t)}else{const o=r.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)s(new Ob({type:zf.KEY_SYSTEM_ERROR,details:Wf.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:i,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${i}). Status: ${a.status} (${a.statusText})`));else{const r=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${r} attempts left`),this.requestLicense(e,t).then(n,s)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,i,e,t).then((({xhr:e,licenseChallenge:t})=>{e.send(t)}))}))}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const r=t.media;this.media=r,r.addEventListener("encrypted",this.onMediaEncrypted),r.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media,t=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},dg.clearKeyUriToKeyIdMap();const r=t.length;xb.CDMCleanupPromise=Promise.all(t.map((e=>this.removeSession(e))).concat(null==e?void 0:e.setMediaKeys(null).catch((t=>{this.log(`Could not clear media keys: ${t}. media.src: ${null==e?void 0:e.src}`)})))).then((()=>{r&&(this.log("finished closing key sessions and clearing media keys"),t.length=0)})).catch((t=>{this.log(`Could not close sessions and clear media keys: ${t}. media.src: ${null==e?void 0:e.src}`)}))}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){const e=t.reduce(((e,t)=>(-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e)),[]);this.log(`Selecting key-system from session-keys ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:r}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),t.onmessage=null,t.onkeystatuseschange=null,r&&r.readyState!==XMLHttpRequest.DONE&&r.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const n=this.mediaKeySessions.indexOf(e);return n>-1&&this.mediaKeySessions.splice(n,1),t.remove().catch((e=>{this.log(`Could not remove session: ${e}`)})).then((()=>t.close())).catch((e=>{this.log(`Could not close session: ${e}`)}))}}}xb.CDMCleanupPromise=void 0;class Ob extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}var Pb="m",Mb="a",Fb="v",Ub="av",Nb="i",Bb="tt";class jb{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=e=>{try{this.apply(e,{ot:Pb,su:!this.initialized})}catch(e){Zf.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=e=>{try{const t=e.frag,r=this.hls.levels[t.level],n=this.getObjectType(t),s={d:1e3*t.duration,ot:n};n!==Fb&&n!==Mb&&n!=Ub||(s.br=r.bitrate/1e3,s.tb=this.getTopBandwidth(n)/1e3,s.bl=this.getBufferLength(n)),this.apply(e,s)}catch(e){Zf.warn("Could not generate segment CMCD data.",e)}},this.hls=e;const t=this.config=e.config,{cmcd:r}=t;null!=r&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=r.sessionId||jb.uuid(),this.cid=r.contentId,this.useHeaders=!0===r.useHeaders,this.registerListeners())}registerListeners(){const e=this.hls;e.on(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Vf.MEDIA_DETACHED,this.onMediaDetached,this),e.on(Vf.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Vf.MEDIA_DETACHED,this.onMediaDetached,this),e.off(Vf.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var r,n;this.audioBuffer=null==(r=t.tracks.audio)?void 0:r.buffer,this.videoBuffer=null==(n=t.tracks.video)?void 0:n.buffer}createData(){var e;return{v:1,sf:"h",sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){Gf(t,this.createData());const r=t.ot===Nb||t.ot===Fb||t.ot===Ub;if(this.starved&&r&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering),this.useHeaders){const r=jb.toHeaders(t);if(!Object.keys(r).length)return;e.headers||(e.headers={}),Gf(e.headers,r)}else{const r=jb.toQuery(t);if(!r)return;e.url=jb.appendQueryToUri(e.url,r)}}getObjectType(e){const{type:t}=e;return"subtitle"===t?Bb:"initSegment"===e.sn?Nb:"audio"===t?Mb:"main"===t?this.hls.audioTracks.length?Fb:Ub:void 0}getTopBandwidth(e){let t,r=0;const n=this.hls;if(e===Mb)t=n.audioTracks;else{const e=n.maxAutoLevel,r=e>-1?e+1:n.levels.length;t=n.levels.slice(0,r)}for(const e of t)e.bitrate>r&&(r=e.bitrate);return r>0?r:NaN}getBufferLength(e){const t=this.hls.media,r=e===Mb?this.audioBuffer:this.videoBuffer;if(!r||!t)return NaN;return 1e3*Qm.bufferInfo(r,t.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,r=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new r(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,r,n){t(e),this.loader.load(e,r,n)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,r=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new r(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,r,n){t(e),this.loader.load(e,r,n)}}}static uuid(){const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}static serialize(e){const t=[],r=e=>!Number.isNaN(e)&&null!=e&&""!==e&&!1!==e,n=e=>Math.round(e),s=e=>100*n(e/100),i={br:n,d:n,bl:s,dl:s,mtp:s,nor:e=>encodeURIComponent(e),rtp:s,tb:n},a=Object.keys(e||{}).sort();for(const n of a){let s=e[n];if(!r(s))continue;if("v"===n&&1===s)continue;if("pr"==n&&1===s)continue;const a=i[n];a&&(s=a(s));const o=typeof s;let l;l="ot"===n||"sf"===n||"st"===n?`${n}=${s}`:"boolean"===o?n:"number"===o?`${n}=${s}`:`${n}=${JSON.stringify(s)}`,t.push(l)}return t.join(",")}static toHeaders(e){const t=Object.keys(e),r={},n=["Object","Request","Session","Status"],s=[{},{},{},{}],i={br:0,d:0,ot:0,tb:0,bl:1,dl:1,mtp:1,nor:1,nrr:1,su:1,cid:2,pr:2,sf:2,sid:2,st:2,v:2,bs:3,rtp:3};for(const r of t){s[null!=i[r]?i[r]:1][r]=e[r]}for(let e=0;e<s.length;e++){const t=jb.serialize(s[e]);t&&(r[`CMCD-${n[e]}`]=t)}return r}static toQuery(e){return`CMCD=${encodeURIComponent(jb.serialize(e))}`}static appendQueryToUri(e,t){if(!t)return e;const r=e.includes("?")?"&":"?";return`${e}${r}${t}`}}function $b(e,t,r,n){e&&Object.keys(t).forEach((s=>{const i=e.filter((e=>e.groupId===s)).map((e=>{const i=Gf({},e);return i.details=void 0,i.attrs=new rp(i.attrs),i.url=i.attrs.URI=qb(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),i.groupId=i.attrs["GROUP-ID"]=t[s],i.attrs["PATHWAY-ID"]=n,i}));e.push(...i)}))}function qb(e,t,r,n){const{HOST:s,PARAMS:i,[r]:a}=n;let o;t&&(o=null==a?void 0:a[t],o&&(e=o));const l=new self.URL(e);return s&&!o&&(l.host=s),i&&Object.keys(i).sort().forEach((e=>{e&&l.searchParams.set(e,i[e])})),l.href}const Kb=/^age:\s*[\d.]+\s*$/im;class Gb{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=void 0,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new ip,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,r){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=r,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e)return;const r=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;const s=this.xhrSetup;s?Promise.resolve().then((()=>{if(!this.stats.aborted)return s(r,t.url)})).catch((e=>(r.open("GET",t.url,!0),s(r,t.url)))).then((()=>{this.stats.aborted||this.openAndSendXhr(r,t,e)})).catch((e=>{this.callbacks.onError({code:r.status,text:e.message},t,r,n)})):this.openAndSendXhr(r,t,e)}openAndSendXhr(e,t,r){e.readyState||e.open("GET",t.url,!0);const n=this.context.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:i}=r.loadPolicy;if(n)for(const t in n)e.setRequestHeader(t,n[t]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),r.timeout=s&&Hf(s)?s:i,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:r}=this;if(!e||!t)return;const n=t.readyState,s=this.config;if(!r.aborted&&n>=2&&(0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),4===n)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const n=t.status,i="text"!==t.responseType;if(n>=200&&n<300&&(i&&t.response||null!==t.responseText)){r.loading.end=Math.max(self.performance.now(),r.loading.first);const s=i?t.response:t.responseText,a="arraybuffer"===t.responseType?s.byteLength:s.length;if(r.loaded=r.total=a,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first),!this.callbacks)return;const o=this.callbacks.onProgress;if(o&&o(r,e,s,t),!this.callbacks)return;const l={url:t.responseURL,data:s,code:n};this.callbacks.onSuccess(l,r,e,t)}else{const i=s.loadPolicy.errorRetry;bm(i,r.retry,!1,n)?this.retry(i):(Zf.error(`${n} while loading ${e.url}`),this.callbacks.onError({code:n,text:t.statusText},e,t,r))}}}loadtimeout(){var e;const t=null==(e=this.config)?void 0:e.loadPolicy.timeoutRetry;if(bm(t,this.stats.retry,!0))this.retry(t);else{Zf.warn(`timeout while loading ${this.context.url}`);const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:r}=this;this.retryDelay=ym(e,r.retry),r.retry++,Zf.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t.url}, retrying ${r.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Kb.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const Hb=/(\d+)-(\d+)\/(\d+)/;class Vb{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=void 0,this.response=void 0,this.controller=void 0,this.context=void 0,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||zb,this.controller=new self.AbortController,this.stats=new ip}destroy(){this.loader=this.callbacks=null,this.abortInternal()}abortInternal(){const e=this.response;null!=e&&e.ok||(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,r){const n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();const s=function(e,t){const r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Gf({},e.headers))};e.rangeEnd&&r.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return r}(e,this.controller.signal),i=r.onProgress,a="arraybuffer"===e.responseType,o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:c}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=r,this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),t.timeout=l&&Hf(l)?l:c,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),r.onTimeout(n,e,this.response)}),t.timeout),self.fetch(this.request).then((s=>{this.response=this.loader=s;const o=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=c,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),r.onTimeout(n,e,this.response)}),c-(o-n.loading.start)),!s.ok){const{status:e,statusText:t}=s;throw new Wb(t||"fetch, bad network response",e,s)}return n.loading.first=o,n.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=Hb.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(Hf(e))return e}const r=e.get("Content-Length");if(r)return parseInt(r)}(s.headers)||n.total,i&&Hf(t.highWaterMark)?this.loadProgressively(s,n,e,t.highWaterMark,i):a?s.arrayBuffer():"json"===e.responseType?s.json():s.text()})).then((s=>{const{response:a}=this;self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);const l=s[o];l&&(n.loaded=n.total=l);const c={url:a.url,data:s,code:a.status};i&&!Hf(t.highWaterMark)&&i(n,e,s,a),r.onSuccess(c,n,e,a)})).catch((t=>{if(self.clearTimeout(this.requestTimeout),n.aborted)return;const s=t&&t.code||0,i=t?t.message:null;r.onError({code:s,text:i},e,t?t.details:null,n)}))}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,r,n=0,s){const i=new Rv,a=e.body.getReader(),o=()=>a.read().then((a=>{if(a.done)return i.dataLength&&s(t,r,i.flush(),e),Promise.resolve(new ArrayBuffer(0));const l=a.value,c=l.length;return t.loaded+=c,c<n||i.dataLength?(i.push(l),i.dataLength>=n&&s(t,r,i.flush(),e)):s(t,r,l,e),o()})).catch((()=>Promise.reject()));return o()}}function zb(e,t){return new self.Request(e.url,t)}class Wb extends Error{constructor(e,t,r){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=r}}const Yb=/\s/,Qb={newCue(e,t,r,n){const s=[];let i,a,o,l,c;const d=self.VTTCue||self.TextTrackCue;for(let h=0;h<n.rows.length;h++)if(i=n.rows[h],o=!0,l=0,c="",!i.isEmpty()){var u;for(let e=0;e<i.chars.length;e++)Yb.test(i.chars[e].uchar)&&o?l++:(c+=i.chars[e].uchar,o=!1);i.cueStartTime=t,t===r&&(r+=1e-4),l>=16?l--:l++;const n=ub(c.trim()),f=mb(t,r,n);null!=e&&null!=(u=e.cues)&&u.getCueById(f)||(a=new d(t,r,n),a.id=f,a.line=h+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),s.push(a))}return e&&s.length&&(s.sort(((e,t)=>"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line)),s.forEach((t=>Hg(e,t)))),s}},Xb=qf(qf({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,maxBufferSize:6e7,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:Gb,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class{constructor(e){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=0,this._nextAutoLevel=-1,this.timer=-1,this.onCheck=this._abandonRulesCheck.bind(this),this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this.hls=e;const t=e.config;this.bwEstimator=new _v(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate),this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(Vf.FRAG_LOADING,this.onFragLoading,this),e.on(Vf.FRAG_LOADED,this.onFragLoaded,this),e.on(Vf.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Vf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Vf.LEVEL_LOADED,this.onLevelLoaded,this)}unregisterListeners(){const{hls:e}=this;e.off(Vf.FRAG_LOADING,this.onFragLoading,this),e.off(Vf.FRAG_LOADED,this.onFragLoaded,this),e.off(Vf.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Vf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Vf.LEVEL_LOADED,this.onLevelLoaded,this)}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this.onCheck=null,this.fragCurrent=this.partCurrent=null}onFragLoading(e,t){var r;const n=t.frag;this.ignoreFragment(n)||(this.fragCurrent=n,this.partCurrent=null!=(r=t.part)?r:null,this.clearTimer(),this.timer=self.setInterval(this.onCheck,100))}onLevelSwitching(e,t){this.clearTimer()}getTimeToLoadFrag(e,t,r,n){return e+r/t+(n?this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const r=this.hls.config,{total:n,bwEstimate:s}=t.stats;Hf(n)&&Hf(s)&&(this.lastLevelLoadSec=8*n/s),t.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD)}_abandonRulesCheck(){const{fragCurrent:e,partCurrent:t,hls:r}=this,{autoLevelEnabled:n,media:s}=r;if(!e||!s)return;const i=performance.now(),a=t?t.stats:e.stats,o=t?t.duration:e.duration,l=i-a.loading.start;if(a.aborted||a.loaded&&a.loaded===a.total||0===e.level)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!n||s.paused||!s.playbackRate||!s.readyState)return;const c=r.mainForwardBufferInfo;if(null===c)return;const d=this.bwEstimator.getEstimateTTFB(),u=Math.abs(s.playbackRate);if(l<=Math.max(d,o/(2*u)*1e3))return;const h=c.len/u;if(h>=2*o/u)return;const f=a.loading.first?a.loading.first-a.loading.start:-1,p=a.loaded&&f>-1,g=this.bwEstimator.getEstimate(),{levels:m,minAutoLevel:y}=r,v=m[e.level],b=a.total||Math.max(a.loaded,Math.round(o*v.maxBitrate/8));let w=l-f;w<1&&p&&(w=Math.min(l,8*a.loaded/g));const E=p?1e3*a.loaded/w:0,S=E?(b-a.loaded)/E:8*b/g+d/1e3;if(S<=h)return;const T=E?8*E:g;let C,k=Number.POSITIVE_INFINITY;for(C=e.level-1;C>y;C--){const e=m[C].maxBitrate;if(k=this.getTimeToLoadFrag(d/1e3,T,o*e,!m[C].details),k<h)break}k>=S||k>10*o||(r.nextLoadLevel=C,p?this.bwEstimator.sample(l-Math.min(d,f),a.loaded):this.bwEstimator.sampleTTFB(l),this.clearTimer(),Zf.warn(`[abr] Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} is loading too slowly;\n Time to underbuffer: ${h.toFixed(3)} s\n Estimated load time for current fragment: ${S.toFixed(3)} s\n Estimated load time for down switch fragment: ${k.toFixed(3)} s\n TTFB estimate: ${f}\n Current BW estimate: ${Hf(g)?(g/1024).toFixed(3):"Unknown"} Kb/s\n New BW estimate: ${(this.bwEstimator.getEstimate()/1024).toFixed(3)} Kb/s\n Aborting and switching to level ${C}`),e.loader&&(this.fragCurrent=this.partCurrent=null,e.abortRequests()),r.trigger(Vf.FRAG_LOAD_EMERGENCY_ABORTED,{frag:e,part:t,stats:a}))}onFragLoaded(e,{frag:t,part:r}){const n=r?r.stats:t.stats;if(t.type===Ng&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),this.lastLoadedFragLevel=t.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){const e=r?r.duration:t.duration,s=this.hls.levels[t.level],i=(s.loaded?s.loaded.bytes:0)+n.loaded,a=(s.loaded?s.loaded.duration:0)+e;s.loaded={bytes:i,duration:a},s.realBitrate=Math.round(8*i/a)}if(t.bitrateTest){const e={stats:n,frag:t,part:r,id:t.type};this.onFragBuffered(Vf.FRAG_BUFFERED,e),t.bitrateTest=!1}}}onFragBuffered(e,t){const{frag:r,part:n}=t,s=null!=n&&n.stats.loaded?n.stats:r.stats;if(s.aborted)return;if(this.ignoreFragment(r))return;const i=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(i,s.loaded),s.bwEstimate=this.bwEstimator.getEstimate(),r.bitrateTest?this.bitrateTestDelay=i/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==Ng||"initSegment"===e.sn}clearTimer(){self.clearInterval(this.timer)}get nextAutoLevel(){const e=this._nextAutoLevel,t=this.bwEstimator;if(-1!==e&&!t.canEstimate())return e;let r=this.getNextABRAutoLevel();if(-1!==e){const t=this.hls.levels;if(t.length>Math.max(e,r)&&t[e].loadError<=t[r].loadError)return e}return-1!==e&&(r=Math.min(e,r)),r}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:r}=this,{maxAutoLevel:n,config:s,minAutoLevel:i,media:a}=r,o=t?t.duration:e?e.duration:0,l=a&&0!==a.playbackRate?Math.abs(a.playbackRate):1,c=this.bwEstimator?this.bwEstimator.getEstimate():s.abrEwmaDefaultEstimate,d=r.mainForwardBufferInfo,u=(d?d.len:0)/l;let h=this.findBestLevel(c,i,n,u,s.abrBandWidthFactor,s.abrBandWidthUpFactor);if(h>=0)return h;Zf.trace(`[abr] ${u?"rebuffering expected":"buffer is empty"}, finding optimal quality level`);let f=o?Math.min(o,s.maxStarvationDelay):s.maxStarvationDelay,p=s.abrBandWidthFactor,g=s.abrBandWidthUpFactor;if(!u){const e=this.bitrateTestDelay;if(e){f=(o?Math.min(o,s.maxLoadingDelay):s.maxLoadingDelay)-e,Zf.trace(`[abr] bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*f)} ms`),p=g=1}}return h=this.findBestLevel(c,i,n,u+f,p,g),Math.max(h,0)}findBestLevel(e,t,r,n,s,i){var a;const{fragCurrent:o,partCurrent:l,lastLoadedFragLevel:c}=this,{levels:d}=this.hls,u=d[c],h=!(null==u||null==(a=u.details)||!a.live),f=null==u?void 0:u.codecSet,p=l?l.duration:o?o.duration:0,g=this.bwEstimator.getEstimateTTFB()/1e3;let m=t,y=-1;for(let a=r;a>=t;a--){const t=d[a];if(!t||f&&t.codecSet!==f){t&&(m=Math.min(a,m),y=Math.max(a,y));continue}-1!==y&&Zf.trace(`[abr] Skipped level(s) ${m}-${y} with CODECS:"${d[y].attrs.CODECS}"; not compatible with "${u.attrs.CODECS}"`);const r=t.details,o=(l?null==r?void 0:r.partTarget:null==r?void 0:r.averagetargetduration)||p;let v;v=a<=c?s*e:i*e;const b=d[a].maxBitrate,w=this.getTimeToLoadFrag(g,v,b*o,void 0===r);if(Zf.trace(`[abr] level:${a} adjustedbw-bitrate:${Math.round(v-b)} avgDuration:${o.toFixed(1)} maxFetchDuration:${n.toFixed(1)} fetchDuration:${w.toFixed(1)}`),v>b&&(0===w||!Hf(w)||h&&!this.bitrateTestDelay||w<n))return a}return-1}set nextAutoLevel(e){this._nextAutoLevel=e}},bufferController:class{constructor(e){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendError=0,this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this._onMediaSourceOpen=()=>{const{media:e,mediaSource:t}=this;Zf.log("[buffer-controller]: Media source opened"),e&&(e.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(Vf.MEDIA_ATTACHED,{media:e})),t&&t.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{Zf.log("[buffer-controller]: Media source closed")},this._onMediaSourceEnded=()=>{Zf.log("[buffer-controller]: Media source ended")},this._onMediaEmptied=()=>{const{media:e,_objectUrl:t}=this;e&&e.src!==t&&Zf.error(`Media element src was set while attaching MediaSource (${t} > ${e.src})`)},this.hls=e,this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null}registerListeners(){const{hls:e}=this;e.on(Vf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Vf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Vf.BUFFER_RESET,this.onBufferReset,this),e.on(Vf.BUFFER_APPENDING,this.onBufferAppending,this),e.on(Vf.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Vf.BUFFER_EOS,this.onBufferEos,this),e.on(Vf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Vf.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Vf.FRAG_PARSED,this.onFragParsed,this),e.on(Vf.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:e}=this;e.off(Vf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Vf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Vf.BUFFER_RESET,this.onBufferReset,this),e.off(Vf.BUFFER_APPENDING,this.onBufferAppending,this),e.off(Vf.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Vf.BUFFER_EOS,this.onBufferEos,this),e.off(Vf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Vf.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Vf.FRAG_PARSED,this.onFragParsed,this),e.off(Vf.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new Pv(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){let r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=r,Zf.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,t){const r=this.media=t.media;if(r&&Mv){const e=this.mediaSource=new Mv;e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),r.src=self.URL.createObjectURL(e),this._objectUrl=r.src,r.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:e,mediaSource:t,_objectUrl:r}=this;if(t){if(Zf.log("[buffer-controller]: media source detaching"),"open"===t.readyState)try{t.endOfStream()}catch(e){Zf.warn(`[buffer-controller]: onMediaDetaching: ${e.message} while calling endOfStream`)}this.onBufferReset(),t.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("sourceended",this._onMediaSourceEnded),t.removeEventListener("sourceclose",this._onMediaSourceClose),e&&(e.removeEventListener("emptied",this._onMediaEmptied),r&&self.URL.revokeObjectURL(r),e.src===r?(e.removeAttribute("src"),e.load()):Zf.warn("[buffer-controller]: media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(Vf.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach((e=>{const t=this.sourceBuffer[e];try{t&&(this.removeBufferListeners(e),this.mediaSource&&this.mediaSource.removeSourceBuffer(t),this.sourceBuffer[e]=void 0)}catch(t){Zf.warn(`[buffer-controller]: Failed to reset the ${e} buffer`,t)}})),this._initSourceBuffer()}onBufferCodecs(e,t){const r=this.getSourceBufferTypes().length;Object.keys(t).forEach((e=>{if(r){const r=this.tracks[e];if(r&&"function"==typeof r.buffer.changeType){const{id:n,codec:s,levelCodec:i,container:a,metadata:o}=t[e],l=(r.levelCodec||r.codec).replace(Fv,"$1"),c=(i||s).replace(Fv,"$1");if(l!==c){const t=`${a};codecs=${i||s}`;this.appendChangeType(e,t),Zf.log(`[buffer-controller]: switching codec ${l} to ${c}`),this.tracks[e]={buffer:r.buffer,codec:s,container:a,levelCodec:i,metadata:o,id:n}}}}else this.pendingTracks[e]=t[e]})),r||(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks())}appendChangeType(e,t){const{operationQueue:r}=this,n={execute:()=>{const n=this.sourceBuffer[e];n&&(Zf.log(`[buffer-controller]: changing ${e} sourceBuffer type to ${t}`),n.changeType(t)),r.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{Zf.warn(`[buffer-controller]: Failed to change ${e} SourceBuffer type`,t)}};r.append(n,e)}onBufferAppending(e,t){const{hls:r,operationQueue:n,tracks:s}=this,{data:i,type:a,frag:o,part:l,chunkMeta:c}=t,d=c.buffering[a],u=self.performance.now();d.start=u;const h=o.stats.buffering,f=l?l.stats.buffering:null;0===h.start&&(h.start=u),f&&0===f.start&&(f.start=u);const p=s.audio;let g=!1;"audio"===a&&"audio/mpeg"===(null==p?void 0:p.container)&&(g=!this.lastMpegAudioChunk||1===c.id||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);const m=o.start,y={execute:()=>{if(d.executeStart=self.performance.now(),g){const e=this.sourceBuffer[a];if(e){const t=m-e.timestampOffset;Math.abs(t)>=.1&&(Zf.log(`[buffer-controller]: Updating audio SourceBuffer timestampOffset to ${m} (delta: ${t}) sn: ${o.sn})`),e.timestampOffset=m)}}this.appendExecutor(i,a)},onStart:()=>{},onComplete:()=>{const e=self.performance.now();d.executeEnd=d.end=e,0===h.first&&(h.first=e),f&&0===f.first&&(f.first=e);const{sourceBuffer:t}=this,r={};for(const e in t)r[e]=Qm.getBuffered(t[e]);this.appendError=0,this.hls.trigger(Vf.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:c,parent:o.type,timeRanges:r})},onError:e=>{Zf.error(`[buffer-controller]: Error encountered while trying to append to the ${a} SourceBuffer`,e);const t={type:zf.MEDIA_ERROR,parent:o.type,details:Wf.BUFFER_APPEND_ERROR,frag:o,part:l,chunkMeta:c,error:e,err:e,fatal:!1};e.code===DOMException.QUOTA_EXCEEDED_ERR?t.details=Wf.BUFFER_FULL_ERROR:(this.appendError++,t.details=Wf.BUFFER_APPEND_ERROR,this.appendError>r.config.appendErrorMaxRetry&&(Zf.error(`[buffer-controller]: Failed ${r.config.appendErrorMaxRetry} times to append segment in sourceBuffer`),t.fatal=!0)),r.trigger(Vf.ERROR,t)}};n.append(y,a)}onBufferFlushing(e,t){const{operationQueue:r}=this,n=e=>({execute:this.removeExecutor.bind(this,e,t.startOffset,t.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(Vf.BUFFER_FLUSHED,{type:e})},onError:t=>{Zf.warn(`[buffer-controller]: Failed to remove from ${e} SourceBuffer`,t)}});t.type?r.append(n(t.type),t.type):this.getSourceBufferTypes().forEach((e=>{r.append(n(e),e)}))}onFragParsed(e,t){const{frag:r,part:n}=t,s=[],i=n?n.elementaryStreams:r.elementaryStreams;i[lp]?s.push("audiovideo"):(i[ap]&&s.push("audio"),i[op]&&s.push("video"));0===s.length&&Zf.warn(`Fragments must have at least one ElementaryStreamType set. type: ${r.type} level: ${r.level} sn: ${r.sn}`),this.blockBuffers((()=>{const e=self.performance.now();r.stats.buffering.end=e,n&&(n.stats.buffering.end=e);const t=n?n.stats:r.stats;this.hls.trigger(Vf.FRAG_BUFFERED,{frag:r,part:n,stats:t,id:r.type})}),s)}onFragChanged(e,t){this.flushBackBuffer()}onBufferEos(e,t){this.getSourceBufferTypes().reduce(((e,r)=>{const n=this.sourceBuffer[r];return!n||t.type&&t.type!==r||(n.ending=!0,n.ended||(n.ended=!0,Zf.log(`[buffer-controller]: ${r} sourceBuffer now EOS`))),e&&!(n&&!n.ended)}),!0)&&(Zf.log("[buffer-controller]: Queueing mediaSource.endOfStream()"),this.blockBuffers((()=>{this.getSourceBufferTypes().forEach((e=>{const t=this.sourceBuffer[e];t&&(t.ending=!1)}));const{mediaSource:e}=this;e&&"open"===e.readyState?(Zf.log("[buffer-controller]: Calling mediaSource.endOfStream()"),e.endOfStream()):e&&Zf.info(`[buffer-controller]: Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`)})))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}flushBackBuffer(){const{hls:e,details:t,media:r,sourceBuffer:n}=this;if(!r||null===t)return;const s=this.getSourceBufferTypes();if(!s.length)return;const i=t.live&&null!==e.config.liveBackBufferLength?e.config.liveBackBufferLength:e.config.backBufferLength;if(!Hf(i)||i<0)return;const a=r.currentTime,o=t.levelTargetDuration,l=Math.max(i,o),c=Math.floor(a/o)*o-l;s.forEach((r=>{const s=n[r];if(s){const n=Qm.getBuffered(s);if(n.length>0&&c>n.start(0)){if(e.trigger(Vf.BACK_BUFFER_REACHED,{bufferEnd:c}),t.live)e.trigger(Vf.LIVE_BACK_BUFFER_REACHED,{bufferEnd:c});else if(s.ended&&n.end(n.length-1)-a<2*o)return void Zf.info(`[buffer-controller]: Cannot flush ${r} back buffer while SourceBuffer is in ended state`);e.trigger(Vf.BUFFER_FLUSHING,{startOffset:0,endOffset:c,type:r})}}}))}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||"open"!==this.mediaSource.readyState)return;const{details:e,hls:t,media:r,mediaSource:n}=this,s=e.fragments[0].start+e.totalduration,i=r.duration,a=Hf(n.duration)?n.duration:0;e.live&&t.config.liveDurationInfinity?(Zf.log("[buffer-controller]: Media Source duration is set to Infinity"),n.duration=1/0,this.updateSeekableRange(e)):(s>a&&s>i||!Hf(i))&&(Zf.log(`[buffer-controller]: Updating Media Source duration to ${s.toFixed(3)}`),n.duration=s)}updateSeekableRange(e){const t=this.mediaSource,r=e.fragments;if(r.length&&e.live&&null!=t&&t.setLiveSeekableRange){const n=Math.max(0,r[0].start),s=Math.max(n,n+e.totalduration);t.setLiveSeekableRange(n,s)}}checkPendingTracks(){const{bufferCodecEventsExpected:e,operationQueue:t,pendingTracks:r}=this,n=Object.keys(r).length;if(n&&!e||2===n){this.createSourceBuffers(r),this.pendingTracks={};const e=this.getSourceBufferTypes();if(e.length)this.hls.trigger(Vf.BUFFER_CREATED,{tracks:this.tracks}),e.forEach((e=>{t.executeNext(e)}));else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}}createSourceBuffers(e){const{sourceBuffer:t,mediaSource:r}=this;if(!r)throw Error("createSourceBuffers called when mediaSource was null");for(const n in e)if(!t[n]){const s=e[n];if(!s)throw Error(`source buffer exists for track ${n}, however track does not`);const i=s.levelCodec||s.codec,a=`${s.container};codecs=${i}`;Zf.log(`[buffer-controller]: creating sourceBuffer(${a})`);try{const e=t[n]=r.addSourceBuffer(a),o=n;this.addBufferListener(o,"updatestart",this._onSBUpdateStart),this.addBufferListener(o,"updateend",this._onSBUpdateEnd),this.addBufferListener(o,"error",this._onSBUpdateError),this.tracks[n]={buffer:e,codec:i,container:s.container,levelCodec:s.levelCodec,metadata:s.metadata,id:s.id}}catch(e){Zf.error(`[buffer-controller]: error while trying to add sourceBuffer: ${e.message}`),this.hls.trigger(Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,mimeType:a})}}}_onSBUpdateStart(e){const{operationQueue:t}=this;t.current(e).onStart()}_onSBUpdateEnd(e){const{operationQueue:t}=this;t.current(e).onComplete(),t.shiftAndExecuteNext(e)}_onSBUpdateError(e,t){const r=new Error(`${e} SourceBuffer error`);Zf.error(`[buffer-controller]: ${r}`,t),this.hls.trigger(Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.BUFFER_APPENDING_ERROR,error:r,fatal:!1});const n=this.operationQueue.current(e);n&&n.onError(t)}removeExecutor(e,t,r){const{media:n,mediaSource:s,operationQueue:i,sourceBuffer:a}=this,o=a[e];if(!n||!s||!o)return Zf.warn(`[buffer-controller]: Attempting to remove from the ${e} SourceBuffer, but it does not exist`),void i.shiftAndExecuteNext(e);const l=Hf(n.duration)?n.duration:1/0,c=Hf(s.duration)?s.duration:1/0,d=Math.max(0,t),u=Math.min(r,l,c);u>d&&!o.ending?(o.ended=!1,Zf.log(`[buffer-controller]: Removing [${d},${u}] from the ${e} SourceBuffer`),o.remove(d,u)):i.shiftAndExecuteNext(e)}appendExecutor(e,t){const{operationQueue:r,sourceBuffer:n}=this,s=n[t];if(!s)return Zf.warn(`[buffer-controller]: Attempting to append to the ${t} SourceBuffer, but it does not exist`),void r.shiftAndExecuteNext(t);s.ended=!1,s.appendBuffer(e)}blockBuffers(e,t=this.getSourceBufferTypes()){if(!t.length)return Zf.log("[buffer-controller]: Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(e);const{operationQueue:r}=this,n=t.map((e=>r.appendBlocker(e)));Promise.all(n).then((()=>{e(),t.forEach((e=>{const t=this.sourceBuffer[e];null!=t&&t.updating||r.shiftAndExecuteNext(e)}))}))}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,t,r){const n=this.sourceBuffer[e];if(!n)return;const s=r.bind(this,e);this.listeners[e].push({event:t,listener:s}),n.addEventListener(t,s)}removeBufferListeners(e){const t=this.sourceBuffer[e];t&&this.listeners[e].forEach((e=>{t.removeEventListener(e.event,e.listener)}))}},capLevelController:Lb,errorController:class{constructor(e){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=e,this.log=Zf.log.bind(Zf,"[info]:"),this.warn=Zf.warn.bind(Zf,"[warning]:"),this.error=Zf.error.bind(Zf,"[error]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(Vf.ERROR,this.onError,this),e.on(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Vf.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Vf.ERROR,this.onError,this),e.off(Vf.ERROR,this.onErrorOut,this),e.off(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Vf.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){this.playlistError=0}stopLoad(){}getVariantLevelIndex(e){return(null==e?void 0:e.type)===Ng?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var r,n;if(t.fatal)return;const s=this.hls,i=t.context;switch(t.details){case Wf.FRAG_LOAD_ERROR:case Wf.FRAG_LOAD_TIMEOUT:case Wf.KEY_LOAD_ERROR:case Wf.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case Wf.FRAG_PARSING_ERROR:if(null!=(r=t.frag)&&r.gap)return void(t.errorAction={action:Cm,flags:Im});case Wf.FRAG_GAP:case Wf.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=km);case Wf.LEVEL_EMPTY_ERROR:case Wf.LEVEL_PARSING_ERROR:{var a,o;const e=t.parent===Ng?t.level:s.loadLevel;t.details===Wf.LEVEL_EMPTY_ERROR&&null!=(a=t.context)&&null!=(o=a.levelDetails)&&o.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case Wf.LEVEL_LOAD_ERROR:case Wf.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==i?void 0:i.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.level)));case Wf.AUDIO_TRACK_LOAD_ERROR:case Wf.AUDIO_TRACK_LOAD_TIMEOUT:case Wf.SUBTITLE_LOAD_ERROR:case Wf.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const e=s.levels[s.loadLevel];if(e&&(i.type===Fg&&i.groupId===e.audioGroupId||i.type===Ug&&i.groupId===e.textGroupId))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=km,void(t.errorAction.flags=_m)}return;case Wf.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const e=s.levels[s.loadLevel],r=null==e?void 0:e.attrs["HDCP-LEVEL"];r&&(t.errorAction={action:km,flags:Rm,hdcpLevel:r})}return;case Wf.BUFFER_ADD_CODEC_ERROR:case Wf.REMUX_ALLOC_ERROR:return void(t.errorAction=this.getLevelSwitchAction(t,null!=(n=t.level)?n:s.loadLevel));case Wf.INTERNAL_EXCEPTION:case Wf.BUFFER_APPENDING_ERROR:case Wf.BUFFER_APPEND_ERROR:case Wf.BUFFER_FULL_ERROR:case Wf.LEVEL_SWITCH_ERROR:case Wf.BUFFER_STALLED_ERROR:case Wf.BUFFER_SEEK_OVER_HOLE:case Wf.BUFFER_NUDGE_ON_STALL:return void(t.errorAction={action:Cm,flags:Im})}if(t.type===zf.KEY_SYSTEM_ERROR){const e=this.getVariantLevelIndex(t.frag);return t.levelRetry=!1,void(t.errorAction=this.getLevelSwitchAction(t,e))}}getPlaylistRetryOrSwitchAction(e,t){var r;const n=mm(this.hls.config.playlistLoadPolicy,e),s=this.playlistError++,i=null==(r=e.response)?void 0:r.code;if(bm(n,s,gm(e),i))return{action:Am,flags:Im,retryConfig:n,retryCount:s};const a=this.getLevelSwitchAction(e,t);return n&&(a.retryConfig=n,a.retryCount=s),a}getFragRetryOrSwitchAction(e){const t=this.hls,r=this.getVariantLevelIndex(e.frag),n=t.levels[r],{fragLoadPolicy:s,keyLoadPolicy:i}=t.config,a=mm(e.details.startsWith("key")?i:s,e),o=t.levels.reduce(((e,t)=>e+t.fragmentError),0);if(n){var l;e.details!==Wf.FRAG_GAP&&n.fragmentError++;const t=null==(l=e.response)?void 0:l.code;if(bm(a,o,gm(e),t))return{action:Am,flags:Im,retryConfig:a,retryCount:o}}const c=this.getLevelSwitchAction(e,r);return a&&(c.retryConfig=a,c.retryCount=o),c}getLevelSwitchAction(e,t){const r=this.hls;null==t&&(t=r.loadLevel);const n=this.hls.levels[t];if(n&&(n.loadError++,r.autoLevelEnabled)){var s,i;let t=-1;const{levels:a,loadLevel:o,minAutoLevel:l,maxAutoLevel:c}=r,d=null==(s=e.frag)?void 0:s.type,{type:u,groupId:h}=null!=(i=e.context)?i:{};for(let r=a.length;r--;){const s=(r+o)%a.length;if(s!==o&&s>=l&&s<=c&&0===a[s].loadError){const r=a[s];if(e.details===Wf.FRAG_GAP&&e.frag){const t=a[s].details;if(t){const r=Em(e.frag,t.fragments,e.frag.start);if(null!=r&&r.gap)continue}}else{if(u===Fg&&h===r.audioGroupId||u===Ug&&h===r.textGroupId)continue;if(d===Bg&&n.audioGroupId===r.audioGroupId||d===jg&&n.textGroupId===r.textGroupId)continue}t=s;break}}if(t>-1&&r.loadLevel!==t)return e.levelRetry=!0,this.playlistError=0,{action:km,flags:Im,nextAutoLevel:t}}return{action:km,flags:_m}}onErrorOut(e,t){var r;switch(null==(r=t.errorAction)?void 0:r.action){case Cm:break;case km:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===Wf.FRAG_GAP||(t.fatal=!0)}t.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(e){const t=this.hls,r=e.errorAction;if(!r)return;const{flags:n,hdcpLevel:s,nextAutoLevel:i}=r;switch(n){case Im:this.switchLevel(e,i);break;case _m:r.resolved||(r.resolved=this.redundantFailover(e));break;case Rm:s&&(t.maxHdcpLevel=rm[rm.indexOf(s)-1],r.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)}r.resolved||this.switchLevel(e,i)}switchLevel(e,t){void 0!==t&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}redundantFailover(e){const{hls:t,penalizedRenditions:r}=this,n=e.parent===Ng?e.level:t.loadLevel,s=t.levels[n],i=s.url.length,a=e.frag?e.frag.urlId:s.urlId;s.urlId!==a||e.frag&&!s.details||this.penalizeRendition(s,e);for(let o=1;o<i;o++){const l=(a+o)%i,c=r[l];if(!c||Lm(c,e,r[a]))return this.warn(`Switching to Redundant Stream ${l+1}/${i}: "${s.url[l]}" after ${e.details}`),this.playlistError=0,t.levels.forEach((e=>{e.urlId=l})),t.nextLoadLevel=n,!0}return!1}penalizeRendition(e,t){const{penalizedRenditions:r}=this,n=r[e.urlId]||{lastErrorPerfMs:0,errors:[],details:void 0};n.lastErrorPerfMs=performance.now(),n.errors.push(t),n.details=e.details,r[e.urlId]=n}},fpsController:class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(Vf.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(Vf.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const r=this.hls.config;if(r.capLevelOnFPSDrop){const e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}}checkFPS(e,t,r){const n=performance.now();if(t){if(this.lastTime){const e=n-this.lastTime,s=r-this.lastDroppedFrames,i=t-this.lastDecodedFrames,a=1e3*s/e,o=this.hls;if(o.trigger(Vf.FPS_DROP,{currentDropped:s,currentDecoded:i,totalDroppedFrames:r}),a>0&&s>o.config.fpsDroppedMonitoringThreshold*i){let e=o.currentLevel;Zf.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=e)&&(e-=1,o.trigger(Vf.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:o.currentLevel}),o.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=n,this.lastDroppedFrames=r,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:kp,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:Qb,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:class extends wy{constructor(e,t,r){super(e,t,r,"[subtitle-stream-controller]",jg),this.levels=[],this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null}_registerListeners(){const{hls:e}=this;e.on(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Vf.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Vf.ERROR,this.onError,this),e.on(Vf.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Vf.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(Vf.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Vf.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(Vf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Vf.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Vf.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Vf.ERROR,this.onError,this),e.off(Vf.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Vf.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(Vf.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Vf.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(Vf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Vf.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state=cy,this.setInterval(500),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:r,success:n}=t;if(this.fragPrevious=r,this.state=cy,!n)return;const s=this.tracksBuffered[this.currentTrackId];if(!s)return;let i;const a=r.start;for(let e=0;e<s.length;e++)if(a>=s[e].start&&a<=s[e].end){i=s[e];break}const o=r.start+r.duration;i?i.end=o:(i={start:a,end:o},s.push(i)),this.fragmentTracker.fragBuffered(r)}onBufferFlushing(e,t){const{startOffset:r,endOffset:n}=t;if(0===r&&n!==Number.POSITIVE_INFINITY){const e=n-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach((t=>{for(let r=0;r<t.length;)if(t[r].end<=e)t.shift();else{if(!(t[r].start<e))break;t[r].start=e,r++}})),this.fragmentTracker.removeFragmentsInRange(r,e,jg)}}onFragBuffered(e,t){var r;this.loadedmetadata||t.frag.type!==Ng||null!=(r=this.media)&&r.buffered.length&&(this.loadedmetadata=!0)}onError(e,t){const r=t.frag;(null==r?void 0:r.type)===jg&&(this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==ly&&(this.state=cy))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){Lv(this.levels,t)?this.levels=t.map((e=>new om(e))):(this.tracksBuffered=[],this.levels=t.map((e=>{const t=new om(e);return this.tracksBuffered[t.id]=[],t})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,jg),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(e,t){if(this.currentTrackId=t.id,!this.levels.length||-1===this.currentTrackId)return void this.clearInterval();const r=this.levels[this.currentTrackId];null!=r&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.setInterval(500)}onSubtitleTrackLoaded(e,t){var r;const{details:n,id:s}=t,{currentTrackId:i,levels:a}=this;if(!a.length)return;const o=a[i];if(s>=a.length||s!==i||!o)return;this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||null!=(r=o.details)&&r.live){const e=this.mainDetails;if(n.deltaUpdateFailed||!e)return;const t=e.fragments[0];o.details?(l=this.alignPlaylists(n,o.details),0===l&&t&&(l=t.start,hm(n,l))):n.hasProgramDateTime&&e.hasProgramDateTime?(ry(n,e),l=n.fragments[0].start):t&&(l=t.start,hm(n,l))}if(o.details=n,this.levelLastLoaded=s,this.startFragRequested||!this.mainDetails&&n.live||this.setStartPosition(o.details,l),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===cy){Em(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(e){const{frag:t,payload:r}=e,n=t.decryptdata,s=this.hls;if(!this.fragContextChanged(t)&&r&&r.byteLength>0&&n&&n.key&&n.iv&&"AES-128"===n.method){const e=performance.now();this.decrypter.decrypt(new Uint8Array(r),n.key.buffer,n.iv.buffer).catch((e=>{throw s.trigger(Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e})).then((r=>{const n=performance.now();s.trigger(Vf.FRAG_DECRYPTED,{frag:t,payload:r,stats:{tstart:e,tdecrypt:n}})})).catch((e=>{this.warn(`${e.name}: ${e.message}`),this.state=cy}))}}doTick(){if(this.media){if(this.state===cy){const{currentTrackId:e,levels:t}=this,r=t[e];if(!t.length||!r||!r.details)return;const{config:n}=this,s=this.getLoadPosition(),i=Qm.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,n.maxBufferHole),{end:a,len:o}=i,l=this.getFwdBufferInfo(this.media,Ng),c=r.details;if(o>this.getMaxBufferLength(null==l?void 0:l.len)+c.levelTargetDuration)return;const d=c.fragments,u=d.length,h=c.edge;let f=null;const p=this.fragPrevious;if(a<h){const e=n.maxFragLookUpTolerance,t=a>h-e?0:e;f=Em(p,d,Math.max(d[0].start,a),t),!f&&p&&p.start<d[0].start&&(f=d[0])}else f=d[u-1];if(!f)return;if(f=this.mapToInitFragWhenRequired(f),"initSegment"!==f.sn){const e=d[f.sn-c.startSN-1];e&&e.cc===f.cc&&this.fragmentTracker.getState(e)===Fm&&(f=e)}this.fragmentTracker.getState(f)===Fm&&this.loadFragment(f,r,a)}}else this.state=cy}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.max(t,e):t}loadFragment(e,t,r){this.fragCurrent=e,"initSegment"===e.sn?this._loadInitSegment(e,t):(this.startFragRequested=!0,super.loadFragment(e,t,r))}get mediaBufferTimeRanges(){return new xv(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends Dm{constructor(e){super(e,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.trackChangeListener=()=>this.onTextTracksChanged(),this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.trackChangeListener=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes(this.trackId)}registerListeners(){const{hls:e}=this;e.on(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Vf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Vf.LEVEL_LOADING,this.onLevelLoading,this),e.on(Vf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Vf.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Vf.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Vf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Vf.LEVEL_LOADING,this.onLevelLoading,this),e.off(Vf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Vf.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Vf.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.trackChangeListener,e)}onMediaDetaching(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId);Ov(this.media.textTracks).forEach((e=>{Vg(e)})),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:r,details:n}=t,{trackId:s}=this,i=this.tracksInGroup[s];if(!i)return void this.warn(`Invalid subtitle track id ${r}`);const a=i.details;i.details=t.details,this.log(`subtitle track ${r} loaded [${n.startSN}-${n.endSN}]`),r===this.trackId&&this.playlistLoaded(r,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(null==t||!t.textGroupIds)return;const r=t.textGroupIds[t.urlId],n=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;if(this.groupId!==r){const e=this.tracks.filter((e=>!r||e.groupId===r));this.tracksInGroup=e;const t=this.findTrackId(null==n?void 0:n.name)||this.findTrackId();this.groupId=r||null;const s={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${r}" group-id`),this.hls.trigger(Vf.SUBTITLE_TRACKS_UPDATED,s),-1!==t&&this.setSubtitleTrack(t,n)}else this.shouldReloadPlaylist(n)&&this.setSubtitleTrack(this.trackId,n)}findTrackId(e){const t=this.tracksInGroup;for(let r=0;r<t.length;r++){const n=t[r];if((!this.selectDefaultTrack||n.default)&&(!e||e===n.name))return n.id}return-1}onError(e,t){!t.fatal&&t.context&&t.context.type===Ug&&t.context.id===this.trackId&&t.context.groupId===this.groupId&&this.checkRetry(t)}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1;const t=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;this.setSubtitleTrack(e,t)}loadPlaylist(e){super.loadPlaylist();const t=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(t)){const r=t.id,n=t.groupId;let s=t.url;if(e)try{s=e.addDirectives(s)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}this.log(`Loading subtitle playlist for id ${r}`),this.hls.trigger(Vf.SUBTITLE_TRACK_LOADING,{url:s,id:r,groupId:n,deliveryDirectives:e||null})}}toggleTrackModes(e){const{media:t,trackId:r}=this;if(!t)return;const n=Ov(t.textTracks),s=n.filter((e=>e.groupId===this.groupId));if(-1===e)[].slice.call(n).forEach((e=>{e.mode="disabled"}));else{const e=s[r];e&&(e.mode="disabled")}const i=s[e];i&&(i.mode=this.subtitleDisplay?"showing":"hidden")}setSubtitleTrack(e,t){var r;const n=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=e);if(this.trackId!==e&&this.toggleTrackModes(e),this.trackId===e&&(-1===e||null!=(r=n[e])&&r.details)||e<-1||e>=n.length)return;this.clearTimer();const s=n[e];if(this.log(`Switching to subtitle-track ${e}`+(s?` "${s.name}" lang:${s.lang} group:${s.groupId}`:"")),this.trackId=e,s){const{id:e,groupId:r="",name:n,type:i,url:a}=s;this.hls.trigger(Vf.SUBTITLE_TRACK_SWITCH,{id:e,groupId:r,name:n,type:i,url:a});const o=this.switchParams(s.url,null==t?void 0:t.details);this.loadPlaylist(o)}else this.hls.trigger(Vf.SUBTITLE_TRACK_SWITCH,{id:e})}onTextTracksChanged(){if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=-1;const t=Ov(this.media.textTracks);for(let r=0;r<t.length;r++)if("hidden"===t[r].mode)e=r;else if("showing"===t[r].mode){e=r;break}this.subtitleTrack!==e&&(this.subtitleTrack=e)}},timelineController:class{constructor(e){if(this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},this.config.enableCEA708Captions){const e=new rb(this,"textTrack1"),t=new rb(this,"textTrack2"),r=new rb(this,"textTrack3"),n=new rb(this,"textTrack4");this.cea608Parser1=new Zv(1,e,t),this.cea608Parser2=new Zv(3,r,n)}e.on(Vf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Vf.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Vf.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Vf.FRAG_LOADING,this.onFragLoading,this),e.on(Vf.FRAG_LOADED,this.onFragLoaded,this),e.on(Vf.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(Vf.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(Vf.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Vf.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(Vf.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(Vf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Vf.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Vf.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Vf.FRAG_LOADING,this.onFragLoading,this),e.off(Vf.FRAG_LOADED,this.onFragLoaded,this),e.off(Vf.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(Vf.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(Vf.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Vf.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(Vf.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.cea608Parser1=this.cea608Parser2=null}addCues(e,t,r,n,s){let i=!1;for(let e=s.length;e--;){const n=s[e],d=(a=n[0],o=n[1],l=t,c=r,Math.min(o,c)-Math.max(a,l));if(d>=0&&(n[0]=Math.min(n[0],t),n[1]=Math.max(n[1],r),i=!0,d/(r-t)>.5))return}var a,o,l,c;if(i||s.push([t,r]),this.config.renderTextTracksNatively){const s=this.captionsTracks[e];this.Cues.newCue(s,t,r,n)}else{const s=this.Cues.newCue(null,t,r,n);this.hls.trigger(Vf.CUES_PARSED,{type:"captions",cues:s,track:e})}}onInitPtsFound(e,{frag:t,id:r,initPTS:n,timescale:s}){const{unparsedVttFrags:i}=this;"main"===r&&(this.initPTS[t.cc]={baseTime:n,timescale:s}),i.length&&(this.unparsedVttFrags=[],i.forEach((e=>{this.onFragLoaded(Vf.FRAG_LOADED,e)})))}getExistingTrack(e){const{media:t}=this;if(t)for(let r=0;r<t.textTracks.length;r++){const n=t.textTracks[r];if(n[e])return n}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:r,media:n}=this,{label:s,languageCode:i}=t[e],a=this.getExistingTrack(e);if(a)r[e]=a,Vg(r[e]),Gg(r[e],n);else{const t=this.createTextTrack("captions",s,i);t&&(t[e]=!0,r[e]=t)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const r={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(Vf.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}createTextTrack(e,t,r){const n=this.media;if(n)return n.addTextTrack(e,t,r)}onMediaAttaching(e,t){this.media=t.media,this._cleanTracks()}onMediaDetaching(){const{captionsTracks:e}=this;Object.keys(e).forEach((t=>{Vg(e[t]),delete e[t]})),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let e=0;e<t.length;e++)Vg(t[e])}onSubtitleTracksUpdated(e,t){const r=t.subtitleTracks||[],n=r.some((e=>e.textCodec===vb));if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(Lv(this.tracks,r))return void(this.tracks=r);if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){const e=this.media?this.media.textTracks:null;this.tracks.forEach(((t,r)=>{let n;if(e&&r<e.length){let r=null;for(let n=0;n<e.length;n++)if(Rb(e[n],t)){r=e[n];break}r&&(n=r)}if(n)Vg(n);else{const e=this._captionsOrSubtitlesFromCharacteristics(t);n=this.createTextTrack(e,t.name,t.lang),n&&(n.mode="disabled")}n&&(n.groupId=t.groupId,this.textTracks.push(n))}))}else if(this.tracks.length){const e=this.tracks.map((e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e})));this.hls.trigger(Vf.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}}}_captionsOrSubtitlesFromCharacteristics(e){if(e.attrs.CHARACTERISTICS){const t=/transcribes-spoken-dialog/gi.test(e.attrs.CHARACTERISTICS),r=/describes-music-and-sound/gi.test(e.attrs.CHARACTERISTICS);if(t&&r)return"captions"}return"subtitles"}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach((e=>{const t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;const r=`textTrack${t[1]}`,n=this.captionsProperties[r];n&&(n.label=e.name,e.lang&&(n.languageCode=e.lang),n.media=e)}))}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){const{cea608Parser1:r,cea608Parser2:n,lastSn:s,lastPartIndex:i}=this;if(this.enabled&&r&&n&&t.frag.type===Ng){var a,o;const e=t.frag.sn,l=null!=(a=null==t||null==(o=t.part)?void 0:o.index)?a:-1;e===s+1||e===s&&l===i+1||(r.reset(),n.reset()),this.lastSn=e,this.lastPartIndex=l}}onFragLoaded(e,t){const{frag:r,payload:n}=t;if(r.type===jg)if(n.byteLength){const e=r.decryptdata,s="stats"in t;if(null==e||!e.encrypted||s){const e=this.tracks[r.level],s=this.vttCCs;s[r.cc]||(s[r.cc]={start:r.start,prevCC:this.prevCC,new:!0},this.prevCC=r.cc),e&&e.textCodec===vb?this._parseIMSC1(r,n):this._parseVTTs(t)}}else this.hls.trigger(Vf.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const r=this.hls;Sb(t,this.initPTS[e.cc],(t=>{this._appendCues(t,e.level),r.trigger(Vf.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})}),(t=>{Zf.log(`Failed to parse IMSC1: ${t}`),r.trigger(Vf.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})}))}_parseVTTs(e){var t;const{frag:r,payload:n}=e,{initPTS:s,unparsedVttFrags:i}=this,a=s.length-1;if(!s[r.cc]&&-1===a)return void i.push(e);const o=this.hls;yb(null!=(t=r.initSegment)&&t.data?ng(r.initSegment.data,new Uint8Array(n)):n,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,(e=>{this._appendCues(e,r.level),o.trigger(Vf.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r})}),(t=>{const s="Missing initPTS for VTT MPEGTS"===t.message;s?i.push(e):this._fallbackToIMSC1(r,n),Zf.log(`Failed to parse VTT cue: ${t}`),s&&a>r.cc||o.trigger(Vf.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:t})}))}_fallbackToIMSC1(e,t){const r=this.tracks[e.level];r.textCodec||Sb(t,this.initPTS[e.cc],(()=>{r.textCodec=vb,this._parseIMSC1(e,t)}),(()=>{r.textCodec="wvtt"}))}_appendCues(e,t){const r=this.hls;if(this.config.renderTextTracksNatively){const r=this.textTracks[t];if(!r||"disabled"===r.mode)return;e.forEach((e=>Hg(r,e)))}else{const n=this.tracks[t];if(!n)return;const s=n.default?"default":"subtitles"+t;r.trigger(Vf.CUES_PARSED,{type:"subtitles",cues:e,track:s})}}onFragDecrypted(e,t){const{frag:r}=t;r.type===jg&&this.onFragLoaded(Vf.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){const{cea608Parser1:r,cea608Parser2:n}=this;if(!this.enabled||!r||!n)return;const{frag:s,samples:i}=t;if(s.type!==Ng||"NONE"!==this.closedCaptionsForLevel(s))for(let e=0;e<i.length;e++){const t=i[e].bytes;if(t){const s=this.extractCea608Data(t);r.addData(i[e].pts,s[0]),n.addData(i[e].pts,s[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:r,endOffsetSubtitles:n,type:s}){const{media:i}=this;if(i&&!(i.currentTime<r)){if(!s||"video"===s){const{captionsTracks:e}=this;Object.keys(e).forEach((n=>zg(e[n],t,r)))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==n){const{textTracks:e}=this;Object.keys(e).forEach((r=>zg(e[r],t,n)))}}}extractCea608Data(e){const t=[[],[]],r=31&e[0];let n=2;for(let s=0;s<r;s++){const r=e[n++],s=127&e[n++],i=127&e[n++];if(0===s&&0===i)continue;if(0!=(4&r)){const e=3&r;0!==e&&1!==e||(t[e].push(s),t[e].push(i))}}return t}},audioStreamController:class extends wy{constructor(e,t,r){super(e,t,r,"[audio-stream-controller]",Bg),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:e}=this;e.on(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Vf.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Vf.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(Vf.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Vf.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Vf.ERROR,this.onError,this),e.on(Vf.BUFFER_RESET,this.onBufferReset,this),e.on(Vf.BUFFER_CREATED,this.onBufferCreated,this),e.on(Vf.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Vf.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Vf.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Vf.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Vf.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(Vf.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Vf.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Vf.ERROR,this.onError,this),e.off(Vf.BUFFER_RESET,this.onBufferReset,this),e.off(Vf.BUFFER_CREATED,this.onBufferCreated,this),e.off(Vf.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Vf.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Vf.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(e,{frag:t,id:r,initPTS:n,timescale:s}){if("main"===r){const e=t.cc;this.initPTS[t.cc]={baseTime:n,timescale:s},this.log(`InitPTS for cc: ${e} found from main: ${n}`),this.videoTrackCC=e,this.state===vy&&this.tick()}}startLoad(e){if(!this.levels)return this.startPosition=e,void(this.state=ly);const t=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),t>0&&-1===e?(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t,this.state=cy):(this.loadedmetadata=!1,this.state=fy),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case cy:this.doTickIdle();break;case fy:{var e;const{levels:t,trackId:r}=this,n=null==t||null==(e=t[r])?void 0:e.details;if(n){if(this.waitForCdnTuneIn(n))break;this.state=vy}break}case hy:{var t;const e=performance.now(),r=this.retryDate;(!r||e>=r||null!=(t=this.media)&&t.seeking)&&(this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded(this.trackId),this.state=cy);break}case vy:{const e=this.waitingData;if(e){const{frag:t,part:r,cache:n,complete:s}=e;if(void 0!==this.initPTS[t.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=uy;const e={frag:t,part:r,payload:n.flush(),networkDetails:null};this._handleFragmentLoadProgress(e),s&&super._handleFragmentLoadComplete(e)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${t.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const e=this.getLoadPosition(),r=Qm.bufferInfo(this.mediaBuffer,e,this.config.maxBufferHole);Sm(r.end,this.config.maxFragLookUpTolerance,t)<0&&(this.log(`Waiting fragment cc (${t.cc}) @ ${t.start} cancelled because another fragment at ${r.end} is needed`),this.clearWaitingFragment())}}else this.state=cy}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=cy)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){const{hls:e,levels:t,media:r,trackId:n}=this,s=e.config;if(null==t||!t[n])return;if(!r&&(this.startFragRequested||!s.startFragPrefetch))return;const i=t[n],a=i.details;if(!a||a.live&&this.levelLastLoaded!==n||this.waitForCdnTuneIn(a))return void(this.state=fy);const o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,ap,Bg));const l=this.getFwdBufferInfo(o,Bg);if(null===l)return;const{bufferedTrack:c,switchingTrack:d}=this;if(!d&&this._streamEnded(l,a))return e.trigger(Vf.BUFFER_EOS,{type:"audio"}),void(this.state=my);const u=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,Ng),h=l.len,f=this.getMaxBufferLength(null==u?void 0:u.len);if(h>=f&&!d)return;const p=a.fragments[0].start;let g=l.end;if(d&&r){const e=this.getLoadPosition();c&&d.attrs!==c.attrs&&(g=e),a.PTSKnown&&e<p&&(l.end>p||l.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=p+.05)}let m=this.getNextFragment(g,a),y=!1;if(m&&this.isLoopLoading(m,g)&&(y=!!m.gap,m=this.getNextFragmentLoopLoading(m,a,l,Ng,f)),!m)return void(this.bufferFlushed=!0);const v=u&&m.start>u.end+a.targetduration;if(v||(null==u||!u.len)&&l.len){const e=this.getAppendedFrag(m.start,Ng);if(null===e)return;if(y||(y=!!e.gap||!!v&&0===u.len),v&&!y||y&&l.nextStart&&l.nextStart<e.end)return}this.loadFragment(m,i,g)}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.min(Math.max(t,e),this.config.maxMaxBufferLength):t}onMediaDetaching(){this.videoBuffer=null,super.onMediaDetaching()}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map((e=>new om(e)))}onAudioTrackSwitching(e,t){const r=!!t.url;this.trackId=t.id;const{fragCurrent:n}=this;n&&(n.abortRequests(),this.removeUnbufferedFrags(n.start)),this.resetLoadingState(),r?this.setInterval(100):this.resetTransmuxer(),r?(this.switchingTrack=t,this.state=cy):(this.switchingTrack=null,this.bufferedTrack=t,this.state=ly),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(e,t){this.mainDetails=t.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(Vf.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(e,t){var r;if(null==this.mainDetails)return void(this.cachedTrackLoadedData=t);const{levels:n}=this,{details:s,id:i}=t;if(!n)return void this.warn(`Audio tracks were reset while loading level ${i}`);this.log(`Track ${i} loaded [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""},duration:${s.totalduration}`);const a=n[i];let o=0;if(s.live||null!=(r=a.details)&&r.live){const e=this.mainDetails;if(s.fragments[0]||(s.deltaUpdateFailed=!0),s.deltaUpdateFailed||!e)return;!a.details&&s.hasProgramDateTime&&e.hasProgramDateTime?(ry(s,e),o=s.fragments[0].start):o=this.alignPlaylists(s,a.details)}a.details=s,this.levelLastLoaded=i,this.startFragRequested||!this.mainDetails&&s.live||this.setStartPosition(a.details,o),this.state!==fy||this.waitForCdnTuneIn(s)||(this.state=cy),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:r,part:n,payload:s}=e,{config:i,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const c=l.details;if(!c)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(r.start);const d=i.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let u=this.transmuxer;u||(u=this.transmuxer=new Cv(this.hls,Bg,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const h=this.initPTS[r.cc],f=null==(t=r.initSegment)?void 0:t.data;if(void 0!==h){const e=!1,t=n?n.index:-1,i=-1!==t,a=new Xm(r.level,r.sn,r.stats.chunkCount,s.byteLength,t,i);u.push(s,f,d,"",r,n,c.totalduration,e,a,h)}else{this.log(`Unknown video PTS for cc ${r.cc}, waiting for video PTS before demuxing audio frag ${r.sn} of [${c.startSN} ,${c.endSN}],track ${a}`);const{cache:e}=this.waitingData=this.waitingData||{frag:r,part:n,cache:new Rv,complete:!1};e.push(new Uint8Array(s)),this.waitingVideoCC=this.videoTrackCC,this.state=vy}}_handleFragmentLoadComplete(e){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(e,t){const r=t.tracks.audio;r&&(this.mediaBuffer=r.buffer||null),t.tracks.video&&(this.videoBuffer=t.tracks.video.buffer||null)}onFragBuffered(e,t){const{frag:r,part:n}=t;if(r.type===Bg)if(this.fragContextChanged(r))this.warn(`Fragment ${r.sn}${n?" p: "+n.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if("initSegment"!==r.sn){this.fragPrevious=r;const e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(Vf.AUDIO_TRACK_SWITCHED,qf({},e)))}this.fragBufferedComplete(r,n)}else if(!this.loadedmetadata&&r.type===Ng){const e=this.videoBuffer||this.media;if(e){Qm.getBuffered(e).length&&(this.loadedmetadata=!0)}}}onError(e,t){var r;if(t.fatal)this.state=yy;else switch(t.details){case Wf.FRAG_GAP:case Wf.FRAG_PARSING_ERROR:case Wf.FRAG_DECRYPT_ERROR:case Wf.FRAG_LOAD_ERROR:case Wf.FRAG_LOAD_TIMEOUT:case Wf.KEY_LOAD_ERROR:case Wf.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Bg,t);break;case Wf.AUDIO_TRACK_LOAD_ERROR:case Wf.AUDIO_TRACK_LOAD_TIMEOUT:case Wf.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==fy||(null==(r=t.context)?void 0:r.type)!==Fg||(this.state=cy);break;case Wf.BUFFER_FULL_ERROR:if(!t.parent||"audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case Wf.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushed(e,{type:t}){t===ap&&(this.bufferFlushed=!0,this.state===my&&(this.state=cy))}_handleTransmuxComplete(e){var t;const r="audio",{hls:n}=this,{remuxResult:s,chunkMeta:i}=e,a=this.getCurrentContext(i);if(!a)return void this.resetWhenMissingContext(i);const{frag:o,part:l,level:c}=a,{details:d}=c,{audio:u,text:h,id3:f,initSegment:p}=s;if(!this.fragContextChanged(o)&&d){if(this.state=py,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),null!=p&&p.tracks){const e=o.initSegment||o;this._bufferInitSegment(p.tracks,e,i),n.trigger(Vf.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:r,tracks:p.tracks})}if(u){const{startPTS:e,endPTS:t,startDTS:r,endDTS:n}=u;l&&(l.elementaryStreams[ap]={startPTS:e,endPTS:t,startDTS:r,endDTS:n}),o.setElementaryStreamInfo(ap,e,t,r,n),this.bufferFragmentData(u,o,l,i)}if(null!=f&&null!=(t=f.samples)&&t.length){const e=Gf({id:r,frag:o,details:d},f);n.trigger(Vf.FRAG_PARSING_METADATA,e)}if(h){const e=Gf({id:r,frag:o,details:d},h);n.trigger(Vf.FRAG_PARSING_USERDATA,e)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(e,t,r){if(this.state!==py)return;e.video&&delete e.video;const n=e.audio;if(!n)return;n.levelCodec=n.codec,n.id="audio",this.log(`Init audio buffer, container:${n.container}, codecs[parsed]=[${n.codec}]`),this.hls.trigger(Vf.BUFFER_CODECS,e);const s=n.initSegment;if(null!=s&&s.byteLength){const e={type:"audio",frag:t,part:null,chunkMeta:r,parent:t.type,data:s};this.hls.trigger(Vf.BUFFER_APPENDING,e)}this.tick()}loadFragment(e,t,r){const n=this.fragmentTracker.getState(e);var s;(this.fragCurrent=e,this.switchingTrack||n===Fm||n===Nm)?"initSegment"===e.sn?this._loadInitSegment(e,t):null!=(s=t.details)&&s.live&&!this.initPTS[e.cc]?(this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=vy):(this.startFragRequested=!0,super.loadFragment(e,t,r)):this.clearTrackerIfNeeded(e)}completeAudioSwitch(e){const{hls:t,media:r,bufferedTrack:n}=this,s=null==n?void 0:n.attrs,i=e.attrs;r&&s&&(s.CHANNELS!==i.CHANNELS||s.NAME!==i.NAME||s.LANGUAGE!==i.LANGUAGE)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(Vf.AUDIO_TRACK_SWITCHED,qf({},e))}},audioTrackController:class extends Dm{constructor(e){super(e,"[audio-track-controller]"),this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Vf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Vf.LEVEL_LOADING,this.onLevelLoading,this),e.on(Vf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Vf.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Vf.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Vf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Vf.LEVEL_LOADING,this.onLevelLoading,this),e.off(Vf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Vf.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Vf.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:r,groupId:n,details:s}=t,i=this.tracksInGroup[r];if(!i||i.groupId!==n)return void this.warn(`Track with id:${r} and group:${n} not found in active group ${i.groupId}`);const a=i.details;i.details=t.details,this.log(`audio-track ${r} "${i.name}" lang:${i.lang} group:${n} loaded [${s.startSN}-${s.endSN}]`),r===this.trackId&&this.playlistLoaded(r,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(null==t||!t.audioGroupIds)return;const r=t.audioGroupIds[t.urlId];if(this.groupId!==r){this.groupId=r||null;const e=this.tracks.filter((e=>!r||e.groupId===r));this.selectDefaultTrack&&!e.some((e=>e.default))&&(this.selectDefaultTrack=!1),this.tracksInGroup=e;const t={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group:${r}`),this.hls.trigger(Vf.AUDIO_TRACKS_UPDATED,t),this.selectInitialTrack()}else this.shouldReloadPlaylist(this.currentTrack)&&this.setAudioTrack(this.trackId)}onError(e,t){!t.fatal&&t.context&&t.context.type===Fg&&t.context.id===this.trackId&&t.context.groupId===this.groupId&&(this.requestScheduled=-1,this.checkRetry(t))}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length)return void this.warn("Invalid id passed to audio-track controller");this.clearTimer();const r=this.currentTrack;t[this.trackId];const n=t[e],{groupId:s,name:i}=n;if(this.log(`Switching to audio-track ${e} "${i}" lang:${n.lang} group:${s}`),this.trackId=e,this.currentTrack=n,this.selectDefaultTrack=!1,this.hls.trigger(Vf.AUDIO_TRACK_SWITCHING,qf({},n)),n.details&&!n.details.live)return;const a=this.switchParams(n.url,null==r?void 0:r.details);this.loadPlaylist(a)}selectInitialTrack(){const e=this.tracksInGroup,t=this.findTrackId(this.currentTrack)|this.findTrackId(null);if(-1!==t)this.setAudioTrack(t);else{const t=new Error(`No track found for running audio group-ID: ${this.groupId} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}findTrackId(e){const t=this.tracksInGroup;for(let r=0;r<t.length;r++){const n=t[r];if(!this.selectDefaultTrack||n.default){if(!e||void 0!==e.attrs["STABLE-RENDITION-ID"]&&e.attrs["STABLE-RENDITION-ID"]===n.attrs["STABLE-RENDITION-ID"])return n.id;if(e.name===n.name&&e.lang===n.lang)return n.id}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(t)){const r=t.id,n=t.groupId;let s=t.url;if(e)try{s=e.addDirectives(s)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}this.log(`loading audio-track playlist ${r} "${t.name}" lang:${t.lang} group:${n}`),this.clearTimer(),this.hls.trigger(Vf.AUDIO_TRACK_LOADING,{url:s,id:r,groupId:n,deliveryDirectives:e||null})}}},emeController:xb,cmcdController:jb,contentSteeringController:class{constructor(e){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.log=Zf.log.bind(Zf,"[content-steering]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Vf.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Vf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Vf.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Vf.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Vf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Vf.ERROR,this.onError,this))}startLoad(){if(this.started=!0,self.clearTimeout(this.reloadTimer),this.enabled&&this.uri)if(this.updated){const e=Math.max(1e3*this.timeToLoad-(performance.now()-this.updated),0);this.scheduleRefresh(this.uri,e)}else this.loadSteeringManifest(this.uri)}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),self.clearTimeout(this.reloadTimer)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter((t=>t!==e)))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:r}=t;null!==r&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:r}=t;if((null==r?void 0:r.action)===km&&r.flags===_m){let e=this.pathwayPriority;const t=this.pathwayId;this.penalizedPathways[t]||(this.penalizedPathways[t]=performance.now()),!e&&this.levels&&(e=this.levels.reduce(((e,t)=>(-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e)),[])),e&&e.length>1&&(this.updatePathwayPriority(e),r.resolved=this.pathwayId!==t)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){const r=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${r}"`),t=this.getLevelsForPathway(r),this.pathwayId=r}return t.length!==e.length?(this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t):e}getLevelsForPathway(e){return null===this.levels?[]:this.levels.filter((t=>e===t.pathwayId))}updatePathwayPriority(e){let t;this.pathwayPriority=e;const r=this.penalizedPathways,n=performance.now();Object.keys(r).forEach((e=>{n-r[e]>3e5&&delete r[e]}));for(let n=0;n<e.length;n++){const s=e[n];if(r[s])continue;if(s===this.pathwayId)return;const i=this.hls.nextLoadLevel,a=this.hls.levels[i];if(t=this.getLevelsForPathway(s),t.length>0){this.log(`Setting Pathway to "${s}"`),this.pathwayId=s,this.hls.trigger(Vf.LEVELS_UPDATED,{levels:t});const e=this.hls.levels[i];a&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=i);break}}}clonePathways(e){const t=this.levels;if(!t)return;const r={},n={};e.forEach((e=>{const{ID:s,"BASE-ID":i,"URI-REPLACEMENT":a}=e;if(t.some((e=>e.pathwayId===s)))return;const o=this.getLevelsForPathway(i).map((e=>{const t=Gf({},e);t.details=void 0,t.url=qb(e.uri,e.attrs["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a);const i=new rp(e.attrs);i["PATHWAY-ID"]=s;const o=i.AUDIO&&`${i.AUDIO}_clone_${s}`,l=i.SUBTITLES&&`${i.SUBTITLES}_clone_${s}`;o&&(r[i.AUDIO]=o,i.AUDIO=o),l&&(n[i.SUBTITLES]=l,i.SUBTITLES=l),t.attrs=i;const c=new om(t);return Pm(c,"audio",o),Pm(c,"text",l),c}));t.push(...o),$b(this.audioTracks,r,a,s),$b(this.subtitleTracks,n,a,s)}))}loadSteeringManifest(e){const t=this.hls.config,r=t.loader;let n;this.loader&&this.loader.destroy(),this.loader=new r(t);try{n=new self.URL(e)}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${e}`)}if("data:"!==n.protocol){const e=0|(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate);n.searchParams.set("_HLS_pathway",this.pathwayId),n.searchParams.set("_HLS_throughput",""+e)}const s={responseType:"json",url:n.href},i=t.steeringManifestLoadPolicy.default,a=i.errorRetry||i.timeoutRetry||{},o={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(e,t,r,s)=>{this.log(`Loaded steering manifest: "${n}"`);const i=e.data;if(1!==i.VERSION)return void this.log(`Steering VERSION ${i.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=i.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=i;if(a)try{this.uri=new self.URL(a,n).href}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||r.url),o&&this.clonePathways(o),l&&this.updatePathwayPriority(l)},onError:(e,t,r,n)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code)return this.enabled=!1,void this.log(`Steering manifest ${t.url} no longer available`);let s=1e3*this.timeToLoad;if(429!==e.code)this.scheduleRefresh(this.uri||t.url,s);else{const e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){const t=e.getResponseHeader("Retry-After");t&&(s=1e3*parseFloat(t))}this.log(`Steering manifest ${t.url} rate limited`)}},onTimeout:(e,t,r)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}};this.log(`Requesting steering manifest: ${n}`),this.loader.load(s,o,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){self.clearTimeout(this.reloadTimer),this.reloadTimer=self.setTimeout((()=>{this.loadSteeringManifest(e)}),t)}}});function Jb(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(Jb):Object.keys(e).reduce(((t,r)=>(t[r]=Jb(e[r]),t)),{}):e}function Zb(e){const t=e.loader;if(t!==Vb&&t!==Gb)Zf.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1})()&&(e.loader=Vb,e.progressive=!0,e.enableSoftwareAES=!0,Zf.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class ew{static get version(){return"1.4.10"}static isSupported(){return function(){const e=yg();if(!e)return!1;const t=Ey(),r=e&&"function"==typeof e.isTypeSupported&&e.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),n=!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove;return!!r&&!!n}()}static get Events(){return Vf}static get ErrorTypes(){return zf}static get ErrorDetails(){return Wf}static get DefaultConfig(){return ew.defaultConfig?ew.defaultConfig:Xb}static set DefaultConfig(e){ew.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Sv,this._autoLevelCapping=void 0,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,function(e,t){if(self.console&&!0===e||"object"==typeof e){Jf(e,"debug","log","info","warn","error");try{Xf.log(`Debug logs enabled for "${t}" in hls.js version 1.4.10`)}catch(e){Xf=Qf}}else Xf=Qf}(e.debug||!1,"Hls instance");const t=this.config=function(e,t){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const r=Jb(e),n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((e=>{const s=`${"level"===e?"playlist":e}LoadPolicy`,i=void 0===t[s],a=[];n.forEach((n=>{const o=`${e}Loading${n}`,l=t[o];if(void 0!==l&&i){a.push(o);const e=r[s].default;switch(t[s]={default:e},n){case"TimeOut":e.maxLoadTimeMs=l,e.maxTimeToFirstByteMs=l;break;case"MaxRetry":e.errorRetry.maxNumRetry=l,e.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":e.errorRetry.retryDelayMs=l,e.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=l,e.timeoutRetry.maxRetryDelayMs=l}}})),a.length&&Zf.warn(`hls.js config: "${a.join('", "')}" setting(s) are deprecated, use "${s}": ${JSON.stringify(t[s])}`)})),qf(qf({},r),t)}(ew.DefaultConfig,e);this.userConfig=e,this._autoLevelCapping=-1,t.progressive&&Zb(t);const{abrController:r,bufferController:n,capLevelController:s,errorController:i,fpsController:a}=t,o=new i(this),l=this.abrController=new r(this),c=this.bufferController=new n(this),d=this.capLevelController=new s(this),u=new a(this),h=new Kg(this),f=new em(this),p=t.contentSteeringController,g=p?new p(this):null,m=this.levelController=new Om(this,g),y=new jm(this),v=new Wm(this.config),b=this.streamController=new Av(this,y,v);d.setStreamController(b),u.setStreamController(b);const w=[h,m,b];g&&w.splice(1,0,g),this.networkControllers=w;const E=[l,c,d,u,f,y];this.audioTrackController=this.createController(t.audioTrackController,w);const S=t.audioStreamController;S&&w.push(new S(this,y,v)),this.subtitleTrackController=this.createController(t.subtitleTrackController,w);const T=t.subtitleStreamController;T&&w.push(new T(this,y,v)),this.createController(t.timelineController,E),v.emeController=this.emeController=this.createController(t.emeController,E),this.cmcdController=this.createController(t.cmcdController,E),this.latencyController=this.createController(tm,E),this.coreComponents=E,w.push(o);const C=o.onErrorOut;"function"==typeof C&&this.on(Vf.ERROR,C,o)}createController(e,t){if(e){const r=new e(this);return t&&t.push(r),r}return null}on(e,t,r=this){this._emitter.on(e,t,r)}once(e,t,r=this){this._emitter.once(e,t,r)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,r=this,n){this._emitter.off(e,t,r,n)}listeners(e){return this._emitter.listeners(e)}emit(e,t,r){return this._emitter.emit(e,t,r)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){Zf.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),this.trigger(Vf.ERROR,{type:zf.OTHER_ERROR,details:Wf.INTERNAL_EXCEPTION,fatal:!1,event:e,error:t})}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){Zf.log("destroy"),this.trigger(Vf.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach((e=>e.destroy())),this.networkControllers.length=0,this.coreComponents.forEach((e=>e.destroy())),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){Zf.log("attachMedia"),this._media=e,this.trigger(Vf.MEDIA_ATTACHING,{media:e})}detachMedia(){Zf.log("detachMedia"),this.trigger(Vf.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const t=this.media,r=this.url,n=this.url=jf.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});Zf.log(`loadSource:${n}`),t&&r&&(r!==n||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(Vf.MANIFEST_LOADING,{url:e})}startLoad(e=-1){Zf.log(`startLoad(${e})`),this.networkControllers.forEach((t=>{t.startLoad(e)}))}stopLoad(){Zf.log("stopLoad"),this.networkControllers.forEach((e=>{e.stopLoad()}))}swapAudioCodec(){Zf.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){Zf.log("recoverMediaError");const e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e,t=0){this.levelController.removeLevel(e,t)}get levels(){const e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){Zf.log(`set currentLevel:${e}`),this.loadLevel=e,this.abrController.clearTimer(),this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){Zf.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){Zf.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){Zf.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){return this.levelController.startLevel}set startLevel(e){Zf.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(Zf.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e)}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){rm.indexOf(e)>-1&&(this._maxHdcpLevel=e)}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const r=e.length;for(let n=0;n<r;n++)if(e[n].maxBitrate>=t)return n;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:r}=this;let n;if(n=-1===t&&e&&e.length?e.length-1:t,r)for(let t=n;t--;){const n=e[t].attrs["HDCP-LEVEL"];if(n&&n<=r)return t}return n}get nextAutoLevel(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)}set nextAutoLevel(e){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,e)}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}ew.defaultConfig=void 0;const tw={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};function rw(e){const t=new Uint8Array(e);let r="";return t.forEach((e=>{r+=String.fromCharCode(e)})),F(r)}function nw(e){const t=e.substring("-----BEGIN PRIVATE KEY-----".length,e.length-"-----END PRIVATE KEY-----".length),r=function(e){const t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0,n=e.length;t<n;t+=1)r[t]=e.charCodeAt(t);return t}(K(t));return crypto.subtle.importKey("pkcs8",r,tw,!1,["sign"])}async function sw({bufferCurrentUsage:e,getActiveStreams:t,updateUsage:r,dispose:n}){const s=e();if(s.length)try{const r=(new Date).toISOString(),i=await async function({timestamp:e,streams:t}){const r=t.map((e=>Object.keys(e).sort().map((t=>`${t}=${e[t]}`)).join("&"))).join(";"),n=ko.v4(),s=`nonceStr=${n}&timestamp=${e}&data=${r}==`,i=(new TextEncoder).encode(s),a=await nw("-----BEGIN PRIVATE KEY-----\nMIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDAARz+hmBgi8pJ\nQb8LeY41gtHhk+ACMwRfhsn7GqpqRQNG2qU0755mzZuVDUqjQMGSo8THJB7O+OJs\nflbZRkFXlFoFOVNw1UpNOgwEQZ6wB9oRwzepTJAfF1sVhm/o/ixvXh1zDFNDy6yZ\npXyiiJHUVxqyjllZhxnwdvjoVtDs6hW6awG09bB9nh/TTejlUKXoAgzqVwu/1QMu\nUVViET495elEe19aUarEy+oL2iKeXCEvqda/pWNBdbieFyJvvZ08HN8dPuT88wq2\njZLEAth1vrwQ2IAa4ktaLcBQdLJgIkrbDvAiVZ8lQAjS/bq5vXQikTGvoPlC5bbn\nvuOM/3eLAgMBAAECggEAVZ+peHAghq2QVj71nX5lxsNCKaCyYwixSJBpfouTt7Rz\nE6PpzMOXFi1W1o+I22jDakuSM2SOQKqI/u0QefB0r0O/KVk5NrZHXk0mkrdYtxOp\nUgaGyf8UvmjB+8VqHrNKyZdk9qtmbnNj01kTTcAtmE4H39zPR7eR/8Rul94vaZbs\nwCnKJS3mLT3JxyGug6lxanveKkjG+CKC1nJQYWaxCJxaFSzbwXQPvDhB+TvrIbee\npd5v4EAyEJohpr+T9oDGGJkb/KARBZCtwLyB976PKJwwBA8MRVL1i5QwawuMiMq5\nUtnOnbGKtCeFzaLbNU0Qi8bqyims84EQxC6DOu1fkQKBgQDdvsoBsEhsOXV7hlIJ\naEd0eSJZVkdqimxH8uGoMM2FeNaOrcB6yBXqTSP0R3OIyf8eaY6yjRvP30ZNXcll\n/gD3O1Mu6YmWQdt1W2WA6pKOsUuPXasf0pdOF7IiFZKlSabz5YHXFqwVuqm8loaj\nsXel3YWqPVdHiankE7tz+3ssnQKBgQDdqi4TNdD1MdEpihx19jr0QjUiXW3939FK\nqp30HESPEGDGQzXdmJgif9HhZb+cJSuWaHEbjgBrYahvgCF+y6LbEpOD+D/dmT+s\nDEAQaR84sah6dokwPjV8fjBSrcVFjCS+doxv0d3p/9OUEeyUhFrY03nxtIEYkLIE\n/Zvn37b4RwKBgQCLENVFe9XfsaVhQ5r9dV2iyTlmh7qgMZG5CbTFs12hQGhm8McO\n+Z7s41YSJCFr/yq1WwP4LJDtrBw99vyQr1zRsG35tNLp3gGRNzGQSQyC2uQFVHw2\np+7mNewsfhUK/gbrXNsyFnDz6635rPlhfbII3sWuP2wWXFqkxE9CbMwR7QKBgQC6\nawDMzxmo2/iYArrkyevSuEuPVxvFwpF1RgAI6C0QVCnPE38dmdN4UB7mfHekje4W\nVEercMURidPp0cxZolCYBQtilUjAyL0vqC3In1/Ogjq6oy3FEMxSop1pKxMY5j+Q\nnoqFD+6deLUrddeNH7J3X4LSr4dSbX4JjG+tlgt+yQKBgQCuwTL4hA6KqeInQ0Ta\n9VQX5Qr8hFlqJz1gpymi/k63tW/Ob8yedbg3WWNWyShwRMFYyY9S81ITFWM95uL6\nvF3x9rmRjwElJw9PMwVu6dmf/CO0Z1wzXSp2VVD12gbrUD/0/d7MUoJ9LgC8X8f/\nn0txLHYGHbx+nf95+JUg6lV3hg==\n-----END PRIVATE KEY-----");return{signature:rw(await crypto.subtle.sign(tw,a,i)),nonceStr:n}}({timestamp:r,streams:s});if(!i||!i.signature)throw new Error("Signature is undefined");const a={signature:i.signature,nonceStr:i.nonceStr,timestamp:r,streams:s},o=ve();return await o.http.post("/api/v3/user-event/video-streaming",a),t().length||e().length||n(),!0}catch(e){return s.forEach((e=>r(e))),!1}}class iw{constructor(){this._unsyncedData=[],this._syncBuffer=[],this._activeStreams=[],this._startInterval(),this._syncInterval=null}registerStream(e){this._activeStreams.push(e)}getActiveStreams(){return this._activeStreams}unregisterStream(e){this._activeStreams=this._activeStreams.filter((t=>t!==e))}updateUsage(e){this._unsyncedData.push(e)}bufferCurrentUsage(){const e=this._unsyncedData;return this._unsyncedData=[],e}dispose(){this._syncInterval&&clearInterval(this._syncInterval)}_startInterval(){this._syncInterval=setInterval((()=>{sw({bufferCurrentUsage:this.bufferCurrentUsage.bind(this),getActiveStreams:this.getActiveStreams.bind(this),updateUsage:this.updateUsage.bind(this),dispose:this.dispose.bind(this)})}),2e4)}}let aw=null;class ow{constructor(e,t){this.player=e,this.resolution=t,this._startTime=null,this._usageCollector=aw||(aw=new iw,aw),this._usageCollector.registerStream(e.id),this._sessionId=String(ko.v4()),this._controller=new AbortController,this._observer=new MutationObserver((t=>{t.forEach((t=>{t.removedNodes.forEach((t=>{t===e&&this._unregisterEvents()}))}))}))}_resetStartTime(){this._startTime=Date.now()}_shouldUpdateCollector(){return!!this._startTime&&Date.now()-this._startTime>2e4}_sendUsageToCollector(){if(!this._startTime)return;const e=Date.now(),t=e-this._startTime,r=Math.round(t/1e3);r&&this._usageCollector.updateUsage({streamId:this.player.id,sessionId:this._sessionId,startTime:this._startTime?new Date(this._startTime).toISOString():null,endTime:new Date(e).toISOString(),watchSeconds:r,resolution:this.resolution})}registerEvents(){this.player.addEventListener("play",(()=>{this._startTime||this._resetStartTime()}),{signal:this._controller.signal}),this.player.addEventListener("playing",(()=>{this._startTime||this._resetStartTime()}),{signal:this._controller.signal}),this.player.addEventListener("timeupdate",(()=>{this._shouldUpdateCollector()&&(this._sendUsageToCollector(),this._resetStartTime())}),{signal:this._controller.signal}),this.player.addEventListener("pause",(()=>{this._sendUsageToCollector(),this._startTime=null}),{signal:this._controller.signal}),this.player.addEventListener("ended",(()=>{this._sendUsageToCollector(),this._startTime=null}),{signal:this._controller.signal})}_unregisterEvents(){this._usageCollector.unregisterStream(this.player.id),this._controller.abort(),this._observer.disconnect()}}var lw=Object.freeze({__proto__:null,getPlayer:async e=>{const{streamId:t}=e;if(!document)throw new Error("This method can be invoked within the browser enviornment only");if(!ew.isSupported())throw new Error("This browswer does not support hls, unable to play stream");const{data:r}=await If(t),{watcherUrl:n,status:s,recordings:i=[],resolution:a}=r;if(!n.hls)throw new Error("This stream does not support hls. Unable to play");const o=document.createElement("video");o.id=t,o.controls=!0;const l=new ew;if(l.attachMedia(o),"recorded"!==s){let{url:e}=n.hls;e=e.replace("http:","https:"),l.loadSource(e)}else{const e=i.find((e=>!!e.mp4));if(!e||!e.mp4)throw new Error("No playable recording available");o.src=e.mp4.url}return new ow(o,a).registerEvents(),o}});const cw=e=>{const t=(e=>{const t=ve(),r=new Date,n=r.getTime()+31536e6;return{stories:[Object.assign({createdAt:r.toISOString(),updatedAt:r.toISOString(),flagCount:0,hashFlag:null,reactions:{},reactionsCount:0,storyId:e.referenceId,path:"",creatorId:t.userId||"",creatorPublicId:t.userId||"",targetPublicId:e.targetId,comments:[],commentsCount:0,isDeleted:!1,hasFlaggedComment:!1,mentionedUsers:[],impression:0,reach:0,expiresAt:new Date(n).toISOString()},e)],categories:[],communityUsers:[],comments:[],files:[],users:[],communities:[]}})(e);return Oo(t),t},dw=({payload:e,formData:t,isVideo:r=!1},n)=>{if(t){const s=t.get("files"),i=new FileReader;i.readAsDataURL(s),i.onload=()=>n(cw(r?Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileId:void 0,videoFileId:{original:void 0},fileData:null==i?void 0:i.result})}):Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileId:void 0,fileData:null==i?void 0:i.result})})))}return n(cw(Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileData:null})})))},uw=async e=>{const t=ve();t.log("post/createStory",e);const r=await t.http.post("/api/v4/stories",e),n=Ef(r.data);t.cache&&Oo(n),Se(["story-sync-state",e.targetId],"synced"),Je("local.story.created",n);const s=t.cache&&Date.now();return{data:n.stories.length>0?n.stories[0]:void 0,cachedAt:s}},hw=e=>e?Ee(["story","get",e]):{data:void 0,cachedAt:void 0},fw=async(e,t=!1)=>{const r=ve();let n;if(r.log("story/deleteStory",e),r.cache&&(n=hw(e),null==n?void 0:n.data)){const{data:e}=n;Je("local.story.deleted",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[Object.assign(Object.assign({},e),{isDeleted:!0})]})}return(await r.http.delete(`/api/v4/stories/${e}`,{params:{permanent:t}})).data.success},pw=e=>{const t=ve(),r=[Xe(t,"onStoryUpdated","story.updated",(async t=>{const r=Ef(t);Oo(r),e(r.stories)}))];return()=>{r.forEach((e=>e()))}},gw=e=>{const t=ve(),r=[Xe(t,"onStoryUpdated","local.story.updated",(async t=>{Oo(t),e(t.stories)}))];return()=>{r.forEach((e=>e()))}},mw=e=>{const t=ve(),r=[Xe(t,"onStoryReactionAdded","story.reactionAdded",(async t=>{const{reactions:r}=t,n=Mo(t,["reactions"]),s=Ef(n),i=iu("story.reactionAdded",Object.assign(Object.assign({},s),{reactions:r}));Oo(i),e(i.stories)}))];return()=>{r.forEach((e=>e()))}},yw=e=>{const t=ve(),r=[Xe(t,"onStoryReactionAdded","local.story.reactionAdded",(async t=>{Oo(t),e(t.stories)}))];return()=>{r.forEach((e=>e()))}},vw=e=>{const t=ve(),r=[Xe(t,"onStoryReactionRemoved","story.reactionRemoved",(async t=>{const{reactions:r}=t,n=Mo(t,["reactions"]),s=Ef(n),i=iu("story.reactionRemoved",Object.assign(Object.assign({},s),{reactions:r}));Oo(i),e(i.stories)}))];return()=>{r.forEach((e=>e()))}},bw=e=>{const t=ve(),r=[Xe(t,"onStoryReactionRemoved","local.story.reactionRemoved",(async t=>{Oo(t),e(t.stories)}))];return()=>{r.forEach((e=>e()))}},ww=e=>{e.forEach((e=>{const t=Ee(["story-expire",e.targetId]),r=new Date(e.expiresAt||0);r<new Date((null==t?void 0:t.data)||0)||Se(["story-expire",e.targetId],r.toISOString())}))},Ew=e=>{e.forEach((e=>{Se(["story-reference",e.storyId],e.referenceId)}))},Sw=async({targetType:e,targetId:t,options:r})=>{const n=ve();n.log("story/getActiveStoriesByTarget");const s=n.cache&&Date.now(),i=await n.http.get("/api/v4/stories",{params:{targetType:e,targetId:t,options:{sortBy:(null==r?void 0:r.sortBy)||"createdAt",orderBy:(null==r?void 0:r.orderBy)||"desc"}}}),a=Ef(i.data);return n.cache&&(Oo(a),ww(a.stories),Ew(a.stories)),{data:a.stories,cachedAt:s,paging:{next:void 0,previous:void 0}}},Tw=e=>{const t=ve(),r=[Xe(t,"onStoryCreated","story.created",(async t=>{const r=Ef(t,!0);Oo(r),e(r.stories)}))];return()=>{r.forEach((e=>e()))}},Cw=e=>{const t=ve(),r=[Xe(t,"onStoryCreated","local.story.created",(async t=>{Oo(t),e(t.stories)}))];return()=>{r.forEach((e=>e()))}},kw=e=>{const t=ve(),r=[Xe(t,"onStoryDeleted","story.deleted",(async t=>{const r=Ef(t);Oo(r),e(r.stories)}))];return()=>{r.forEach((e=>e()))}},Aw=e=>{const t=ve(),r=[Xe(t,"onStoryDeleted","local.story.deleted",(async t=>{Oo(t),e(t.stories)}))];return()=>{r.forEach((e=>e()))}},Iw=e=>{const t=ve();return Xe(t,"onStoryError","local.story.error",(async t=>{Oo(t),e(t.stories)}))},_w=e=>t=>e((e=>t(e[0]))),Rw=async e=>{const t=ve();t.log("story/getTargetsByTargetIds",e);const r=await t.http.get("/api/v4/stories/seen",{params:{targets:e}}),{data:n}=r;return t.cache&&Oo(r.data),{data:n.storyTargets,cachedAt:Date.now()}};class Lw extends ah{constructor(e,t,r,n){super(e,t),this.notifyChange=r,this.paginationController=n}saveToMainDB(e){const t=ve(),r=t.cache&&Date.now(),n=Ef(e);t.cache&&(Oo(n,{cachedAt:r}),ww(n.stories),Ew(n.stories))}getStoryReferenceIds(e){return(null==e?void 0:e.referenceId)?e.referenceId:e.storyId}appendToQueryStream(e,t,r=!1){var n,s;if(r)Se(this.cacheKey,{data:e.stories.map(this.getStoryReferenceIds)});else{const t=null===(n=Ee(this.cacheKey))||void 0===n?void 0:n.data,r=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...r,...e.stories.map(this.getStoryReferenceIds)])]}))}}reactor(e){return e=>{var t;const r=null===(t=Ee(this.cacheKey))||void 0===t?void 0:t.data;if(!r)return;const n=e.map((({referenceId:e})=>e));r.data=[...new Set([...n,...r.data])],Se(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Dw extends lh{async getRequest(e){const{data:t}=await this.http.get("/api/v4/stories-by-targets",{params:Object.assign({},e)});return t}}class xw extends ch{constructor(e,t){const r=nh(e),n=["story-target-ids","collection",r],s=new Dw(e);super(s,r,n,t),this.query=e,this.queryStreamController=new Lw(this.query,this.cacheKey,this.notifyChange.bind(this),s),this.paginationController=s,this.callback=t.bind(this),this.loadPage(!0)}setup(){var e;(null===(e=Ee(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}persistModel(e){this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:r}){this.queryStreamController.appendToQueryStream(e,t,r)}notifyChange({origin:e,loading:t,error:r}){var n;const s=null===(n=Ee(this.cacheKey))||void 0===n?void 0:n.data;if(!s)return;let i=s.data.map((e=>Ee(["story","get",e]))).filter(Boolean).map((e=>il.story(e.data)));(this.shouldNotify(i)||"event"!==e)&&(i=this.applyFilter(i),this.callback({onNextPage:void 0,data:i,hasNextPage:!1,loading:t,error:r}))}applyFilter(e){var t,r;const n=e;return"asc"===((null===(r=null===(t=this.query)||void 0===t?void 0:t.options)||void 0===r?void 0:r.orderBy)||"desc")?n.sort(Fe):n.sort(Ne)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Tw,action:"onCreate"},{fn:pw,action:"onUpdate"},{fn:kw,action:"onDelete"},{fn:Iw,action:"onError"}])}}const Ow=(e,t)=>{var r,n;const s=null===(r=Ee(e))||void 0===r?void 0:r.data,i=null!==(n=null==s?void 0:s.data)&&void 0!==n?n:[];Se(e,Object.assign(Object.assign({},s),{data:[...new Set([...i,...t])]}))};class Pw extends ah{constructor(e,t,r,n){super(e,t),this.notifyChange=r,this.paginationController=n,this.preparePayload=e=>e}saveToMainDB(e){const t=ve(),r=t.cache&&Date.now(),n=this.preparePayload(e);t.cache&&Oo(n,{cachedAt:r})}appendToQueryStream(e,t,r=!1){r?Se(this.cacheKey,{data:e.storyTargets.map((({targetId:e})=>e))}):Ow(this.cacheKey,e.storyTargets.map((({targetId:e})=>e)))}reactor(e){return t=>{"onCreate"===e&&"seen"!==this.query.seenState&&Ow(this.cacheKey,t.map((({targetId:e})=>e))),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Mw extends sh{constructor(){super(...arguments),this.smartFilterState="unseen"}async getRequest(e,t){var r;const{limit:n=10,seenState:s="unseen"}=e,i=await this.createRequest({seenState:"smart"===s?this.smartFilterState:s,limit:n,token:t});if(null===(r=i.paging)||void 0===r?void 0:r.next)return i;if("smart"!==s)return i;if("seen"===this.smartFilterState)return i;this.smartFilterState="seen";const a=await this.createRequest({seenState:this.smartFilterState,limit:n});return l=a,{categories:(o=i).categories.concat(l.categories),communities:o.communities.concat(l.communities),communityUsers:o.communityUsers.concat(l.communityUsers),files:o.files.concat(l.files),storyTargets:o.storyTargets.concat(l.storyTargets),users:o.users.concat(l.users),paging:l.paging};var o,l}async createRequest(e){const{data:t}=await this.http.get("/api/v5/me/global-story-targets",{params:e});return r=t,n=e.seenState,Object.assign(Object.assign({},r),{storyTargets:r.storyTargets.map((e=>Object.assign(Object.assign({},e),{localFilter:n})))||[]});var r,n}}class Fw extends ch{constructor(e,t){const r=nh(e),n=["story-global-feed","collection",r],s=new Mw(e);super(s,r,n,t),this.query=e,this.queryStreamController=new Pw(this.query,this.cacheKey,this.notifyChange.bind(this),s),this.paginationController=s,this.callback=t.bind(this),this.loadPage(!0)}setup(){var e;(null===(e=Ee(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}persistModel(e){this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:r}){this.queryStreamController.appendToQueryStream(e,t,r)}notifyChange({origin:e,loading:t,error:r}){var n;const s=null===(n=Ee(this.cacheKey))||void 0===n?void 0:n.data;if(!s)return;let i=s.data.map((e=>Ee(["storyTarget","get",e]))).filter(Boolean).map((e=>il.storyTarget(e.data)));(this.shouldNotify(i)||"event"!==e)&&(i=this.applyFilter(i),this.callback({onNextPage:()=>this.loadPage(!1,"next"),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:r}))}applyFilter(e){if("smart"!==this.query.seenState)return e.filter((({hasUnseen:e})=>"all"===this.query.seenState||("seen"===this.query.seenState&&!e||"unseen"===this.query.seenState&&e))).sort(Ue);const t=e.reduce(((e,t)=>("unseen"===t.localFilter?e.unseen.push(t):"seen"===t.localFilter?e.seen.push(t):e.unknown.push(t),e)),{unseen:[],seen:[],unknown:[]}),r=t.unknown.sort(Ue)||[],n=t.unseen.sort(Ue)||[],s=t.seen.sort(Ue)||[];return r.concat(n,s).map((e=>Mo(e,["localFilter","localLastExpires","localLastSeen","localSortingDate"])))}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Tw,action:"onCreate"},{fn:pw,action:"onUpdate"},{fn:kw,action:"onDelete"},{fn:Cw,action:"onCreate"},{fn:gw,action:"onUpdate"},{fn:Aw,action:"onDelete"},{fn:Iw,action:"onError"}])}}var Uw=Object.freeze({__proto__:null,createImageStory:async(e,t,r,n={},s="fit",i=[])=>{if(!r.getAll("files").length)throw new Error("The formData object must have a `files` key.");let a={data:{text:"",fileId:void 0,fileData:null,imageDisplayMode:s},syncState:"syncing",referenceId:Ao(),dataType:"image",items:i,targetType:e,targetId:t,metadata:n};const o=new Date;Se(["story-sync-state",t],"syncing"),Se(["story-expire",t],new Date(o.setFullYear(o.getFullYear()+1))),dw({payload:a,formData:r},(e=>{Je("local.story.created",e)}));try{const{data:e}=await zd(r);if(0===e.length)throw new Error("Failed to upload image");const{fileId:t}=e[0];a=Object.assign(Object.assign({},a),{data:Object.assign(Object.assign({},a.data),{fileId:t})}),dw({payload:a,formData:r},(e=>{Je("local.story.created",e)}));const n=await uw(a);return n.data?Object.assign(Object.assign({},n),{data:il.story(n.data)}):n}catch(e){throw Se(["story-sync-state",t],"error"),dw({payload:Object.assign(Object.assign({},a),{syncState:"error"}),formData:r},(e=>{Je("local.story.error",e)})),e}},createVideoStory:async(e,t,r,n={},s=[])=>{if(!r.getAll("files").length)throw new Error("The formData object must have a `files` key.");let i={data:{text:"",fileId:void 0,fileData:null},syncState:"syncing",referenceId:Ao(),dataType:"video",items:s,targetType:e,targetId:t,metadata:n};const a=new Date;Se(["story-sync-state",t],"syncing"),Se(["story-expire",t],new Date(a.setFullYear(a.getFullYear()+1))),dw({payload:i,formData:r,isVideo:!0},(e=>{Je("local.story.created",e)}));try{const{data:e}=await Vd(r,l.STORY);if(0===e.length)throw new Error("Failed to upload video");const{fileId:t}=e[0];i=Object.assign(Object.assign({},i),{data:Object.assign(Object.assign({},i.data),{fileId:t,videoFileId:{original:t}})}),dw({payload:i,formData:r,isVideo:!0},(e=>{Je("local.story.created",e)}));const n=await uw(i);return n.data?Object.assign(Object.assign({},n),{data:il.story(n.data)}):n}catch(e){throw Se(["story-sync-state",t],"error"),dw({payload:Object.assign(Object.assign({},i),{syncState:"error"}),formData:r,isVideo:!0},(e=>{Je("local.story.error",e)})),e}},hardDeleteStory:async e=>await fw(e,!0),softDeleteStory:async e=>await fw(e),getActiveStoriesByTarget:(e,t)=>{const{log:r,cache:n}=ve(),s=[],i=["story-target","collection",e],a=Date.now();r(`getActiveStoriesByTarget(tmpid: ${a}) > listen`),n||console.log(p);const o=t=>{var r,n;const s=(null===(r=e.options)||void 0===r?void 0:r.sortBy)||"createdAt",i=(null===(n=e.options)||void 0===n?void 0:n.orderBy)||"desc";return 0===t.length?[]:"createdAt"===s?"asc"===i?t.sort(Fe):t.sort(Ne):"asc"===i?t.sort(Be):t.sort(je)},l=e=>{var r;const n=e.data.map((e=>{const t=hw(e);if(null==t?void 0:t.data)return il.story(t.data)})).filter(Boolean).filter((e=>!!e&&!e.isDeleted)),s=[];if(n.length>0){const e=n.reduce(((e,t)=>{if(!t)return e;const{syncState:r}=t;if(!r)return e;let n=e.get(r);return n||(n=[]),n.push(t),e.set(r,n),e}),new Map);if(e.has("error")){const t=o(e.get("error")||[]);s.push(...t)}if(e.has("syncing")){const t=o(e.get("syncing")||[]);s.push(...t)}if(e.has("synced")){const t=o(e.get("synced")||[]);s.push(...t)}}t({onNextPage:()=>!1,data:s||n,hasNextPage:!!(null===(r=e.params)||void 0===r?void 0:r.page),loading:e.loading||!1})},c=(e,t,r=!1,n=!1,s=!1)=>{const a=Ee(i),o={loading:n,error:s,params:{page:void 0},data:(null==a?void 0:a.data)||[]};if(e)if("onDelete"===t){const t=e.map((({referenceId:e})=>e));o.data=o.data.filter((e=>!t.includes(e)))||[]}else o.data=r?e.map(de("story")):[...new Set([...o.data,...e.map(de("story"))])];Se(i,o.data),l(o)},d=e=>t=>{c(t,e)};return(t=>{const r=ie(Sw,e);oe(r,(({data:e,error:r,loading:n})=>{c(e,"fetch",t,n,r)}))})(!0),s.push(Tw(d("onCreate")),pw(d("onUpdate")),kw(d("onDelete")),mw(d("onReactionAdded")),vw(d("onReactionRemoved")),Iw(d("onError")),Cw(d("onCreate")),gw(d("onUpdate")),Aw(d("onDelete")),yw(d("onReactionAdded")),bw(d("onReactionRemoved")),(e=>{const t=ve();return Xe(t,"onStoryLocalDataUpdated","local.story.reload",(t=>{e(t)}))})((e=>{const t=Ee(i);if(!t)return;if(0===e.referenceIds.length||0===(null==t?void 0:t.data.length))return;if(!(null==t?void 0:t.data.find((t=>e.referenceIds.includes(t)))))return;const r={loading:!1,error:!1,params:{page:void 0},data:(null==t?void 0:t.data)||[]};l(r)})),(()=>ke(i))),()=>{r(`getActiveStoriesByTarget(tmpid: ${a}) > dispose`),s.forEach((e=>e()))}},getStoryByStoryId:(e,t)=>pd(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:il.story(e.data)})):t(e)}),"storyId",Sf,[_w(pw),_w(kw),_w(mw),_w(vw),_w(Iw),_w(gw),_w(Aw),_w(yw),_w(bw)]),getTargetById:(e,t)=>pd(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:il.storyTarget(e.data[0])})):t(e)}),"query",(e=>Rw([e])),[]),getTargetsByTargetIds:(e,t)=>{const{log:r,cache:n}=ve(),s=[],i=["storyTargets","collection",e],a=Date.now();r(`getTargetsByTargetIds(tmpid: ${a}) > listen`),n||console.log(p);const o=(e,r=!1,n=!1,s=!1)=>{const a=Ee(i),o={loading:n,error:s,params:{page:void 0},data:[]};e&&(o.data=r?e.map(de("storyTarget")):[...new Set([...(null==a?void 0:a.data)||[],...e.map(de("storyTarget"))])]),Se(i,o.data),(e=>{var r;const n=e.data.map((e=>{const t=Ee(["storyTarget","get",e]);if(null==t?void 0:t.data)return il.storyTarget(t.data)})).filter(Boolean);t({onNextPage:void 0,data:n,hasNextPage:!!(null===(r=e.params)||void 0===r?void 0:r.page),loading:e.loading||!1})})(o)};return(t=>{const r=ie(Rw,e);oe(r,(({data:e,error:r,loading:n})=>{o(e,t,n,r)}))})(!0),s.push((()=>ke(i))),()=>{r(`getTargetsByTargetIds(tmpid: ${a}) > dispose`),s.forEach((e=>e()))}},getStoriesByTargetIds:(e,t,r)=>{const{log:n,cache:s,userId:i}=ve();s||console.log(p);const a=Date.now();n(`getStoriesByTargetIds(tmpid: ${a}) > listen`);const o=new xw(e,t),l=o.startSubscription(),c=o.getCacheKey();return l.push((()=>{ke(c)})),()=>{n(`getStoriesByTargetIds(tmpid: ${a}) > dispose`),l.forEach((e=>e()))}},getGlobalStoryTargets:(e,t,r)=>{const{log:n,cache:s,userId:i}=ve();s||console.log(p);const a=Date.now();n(`getGlobalStoryTarget(tmpid: ${a}) > listen`);const o=new Fw(e,t),l=o.startSubscription(),c=o.getCacheKey();return l.push((()=>{ke(c)})),()=>{n(`getGlobalStoryTarget(tmpid: ${a}) > dispose`),l.forEach((e=>e()))}}});return e.API_REGIONS=At,e.CategoryRepository=hf,e.ChannelRepository=Rh,e.Client=gd,e.CommentRepository=Af,e.CommunityPostSettingMaps=a,e.CommunityPostSettings=i,e.CommunityRepository=cf,e.ContentFeedType=l,e.DefaultCommunityPostSetting=o,e.FeedRepository=gf,e.FileRepository=Wd,e.FileType=t,e.LiveStreamPlayer=lw,e.MessageContentType=c,e.MessageRepository=hh,e.PollRepository=Uf,e.PostContentType=d,e.PostRepository=bf,e.ReactionRepository=Ru,e.StoryRepository=Uw,e.StreamRepository=Of,e.SubChannelRepository=vh,e.UserRepository=Gd,e.VERSION=u,e.VideoResolution=r,e.VideoSize=s,e.VideoTranscodingStatus=n,e.backupCache=async(e="amitySdk",t=(e=>e.offline))=>{const{log:r,cache:n,userId:s}=ve();if(!n)return!1;r("cache/api/backupCache",{storageKey:e});const i=Object.fromEntries(Object.entries(n.data).filter((([e,r])=>t(r))));return!!Object.keys(i).length&&(localStorage&&await localStorage.setItem(`${e}#${s}`,JSON.stringify(i)),!0)},e.createQuery=ie,e.createReport=async(e,t)=>{const r=ve();r.log("report/createReport",{referenceType:e,referenceId:t});const{data:n}=await r.http.post((()=>{if("user"===e)return`/api/v4/me/flags/${encodeURIComponent(t)}`;if("message"===e)return`/api/v5/messages/${encodeURIComponent(t)}/flags`;const{domainName:r}=Lu[e];return`/api/v3/${r}/${encodeURIComponent(t)}/flag`})());if(r.cache)if("message"===e){const e=await Ol(n);Oo(e)}else Oo("post"===e?Uo(n,"communityUsers"):n);return Je(`${e}.flagged`,n),!!n},e.createUserToken=async(e,t,r)=>{const n=await _o(),s=Ro(),i=hn(_t("http",t)),{data:a}=await i.post("/api/v4/sessions",Object.assign(Object.assign({},r),{deviceId:n,deviceInfo:Object.assign(Object.assign({},s),{model:"token management API on TS-SDK"})}),{headers:{"X-API-Key":e}});return{accessToken:a.accessToken}},e.deleteReport=async(e,t)=>{const r=ve();r.log("report/deleteReport",{referenceType:e,referenceId:t});const{data:n}=await r.http.delete((()=>{if("user"===e)return`/api/v4/me/flags/${encodeURIComponent(t)}`;if("message"===e)return`/api/v5/messages/${encodeURIComponent(t)}/flags`;const{domainName:r}=Lu[e];return`/api/v3/${r}/${encodeURIComponent(t)}/unflag`})());if(r.cache)if("message"===e){const e=await Ol(n);Oo(e)}else Oo("post"===e?Uo(n,"communityUsers"):n);return Je(`${e}.unflagged`,n),!!n},e.disableCache=()=>{const e=ve();e.cache&&(e.log("cache/api/disableCache"),delete e.cache)},e.dropFromCache=ke,e.enableCache=(e={},t)=>{const r=ve();r.cache||(r.log("cache/api/enableCache"),r.cache={data:e,persistIf:t})},e.filterByChannelMembership=Re,e.filterByCommunityMembership=De,e.filterByFeedType=Le,e.filterByPostDataTypes=xe,e.filterByPropEquality=Ae,e.filterByPropInclusion=(e,t,r)=>void 0!==r?e.filter((e=>r.includes(e[t]))):e,e.filterByPropIntersection=_e,e.filterBySearchTerm=Oe,e.filterByStringComparePartially=Ie,e.getChannelTopic=e=>`${e.path}/#`,e.getCommentTopic=({path:e})=>e,e.getCommunityStoriesTopic=({targetId:e,targetType:t})=>{const r=Ke();return`${st(r)}/social/${t}/${e}/story/#`},e.getCommunityTopic=({path:t},r=e.SubscriptionLevels.COMMUNITY)=>nt(t,r),e.getMarkedMessageTopic=at,e.getMarkerUserFeedTopic=ot,e.getMessageTopic=e=>e.path,e.getMyFollowersTopic=()=>{const e=Ke();return`${st(e)}/membership/${e._id}/+/+`},e.getMyFollowingsTopic=()=>{const e=Ke();return`${st(e)}/membership/+/${e._id}/+`},e.getNetworkTopic=lt,e.getPostTopic=({path:t},r=e.SubscriptionLevels.POST)=>"comment"===r?`${t}/comment/+`:t,e.getRole=Qd,e.getSmartFeedChannelTopic=ct,e.getSmartFeedMessageTopic=ut,e.getSmartFeedSubChannelTopic=dt,e.getStoryTopic=({targetId:e,targetType:t,storyId:r})=>{const n=Ke();return`${st(n)}/social/${t}/${e}/story/${r}/#`},e.getSubChannelTopic=e=>`${e.path}/#`,e.getUserTopic=it,e.isAfterBefore=W,e.isAfterBeforeRaw=Y,e.isCachable=ne,e.isFetcher=ee,e.isFresh=se,e.isLocal=e=>ne(e)&&-1===(null==e?void 0:e.cachedAt),e.isMutator=te,e.isOffline=re,e.isPaged=Q,e.isReportedByMe=async(e,t)=>{var r;const n=ve();n.log("report/isReportedByMe",{referenceType:e,referenceId:t});const{domainName:s}=Lu[e];if("message"===e){const{data:e}=await n.http.get(`/api/v5/messages/${encodeURIComponent(t)}/flags`);return e.result}const{data:i}=await n.http.get(`/api/v3/${s}/${t}/isflagbyme`),{result:a,isFlagByMe:o}=null!=i?i:{};return null!==(r=null!=a?a:o)&&void 0!==r&&r},e.isSkip=z,e.mergeInCache=Te,e.onChannelMarkerFetched=id,e.onFeedMarkerFetched=e=>{const t=ve();return Xe(t,"feedMarker/onFeedMarkerFetched","local.feedMarker.fetched",(t=>{e(t.feedMarkers[0])}))},e.onFeedMarkerUpdated=Lc,e.onMessageMarked=ud,e.onMessageMarkerFetched=dd,e.onSubChannelMarkerFetched=ad,e.onSubChannelMarkerUpdated=od,e.onUserMarkerFetched=ld,e.onUserMarkerFetchedLegacy=cd,e.pullFromCache=Ee,e.pushToCache=Se,e.queryCache=we,e.queryOptions=ae,e.queryRoles=Yd,e.restoreCache=async(e="amitySdk")=>{var t;const r=ve();if(!r.cache)return!1;r.log("cache/api/restoreCache",{storageKey:e});const n=localStorage&&null!==(t=await localStorage.getItem(`${e}#${r.userId}`))&&void 0!==t?t:"{}";let s={};try{s=JSON.parse(n)}catch(e){}return r.cache.data=Object.assign(Object.assign({},s),r.cache.data),!0},e.runQuery=oe,e.sortByChannelSegment=({channelSegment:e},{channelSegment:t})=>e-t,e.sortByDisplayName=Pe,e.sortByFirstCreated=Fe,e.sortByFirstUpdated=Be,e.sortByLastActivity=$e,e.sortByLastCreated=Ne,e.sortByLastUpdated=je,e.sortByLocalSortingDate=Ue,e.sortByName=Me,e.sortBySegmentNumber=({segmentNumber:e},{segmentNumber:t})=>e-t,e.subscribeTopic=ht,e.toPage=J,e.toPageRaw=Z,e.toToken=X,e.upsertInCache=Ce,e.wipeCache=async(e="amitySdk")=>{const{log:t,cache:r,userId:n}=ve();return!!r&&(t("cache/api/wipeCache",{storageKey:e}),r.data={},localStorage&&await localStorage.setItem(`${e}#${n}`,"{}"),!0)},Object.defineProperty(e,"__esModule",{value:!0}),e}({});
6
+ var n=e("buffer"),s=n.Buffer;function i(e,t){for(var r in e)t[r]=e[r]}function a(e,t,r){return s(e,t,r)}s.from&&s.alloc&&s.allocUnsafe&&s.allocUnsafeSlow?t.exports=n:(i(n,r),r.Buffer=a),a.prototype=Object.create(s.prototype),i(s,a),a.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return s(e,t,r)},a.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=s(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},a.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return s(e)},a.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},{buffer:17}],74:[function(e,t,r){function n(e){var t=e._readableState;return t?t.objectMode||"number"==typeof e._duplexState?e.read():e.read(s(t)):null}function s(e){return e.buffer.length?e.buffer.head?e.buffer.head.data.length:e.buffer[0].length:e.length}t.exports=n},{}],75:[function(e,t,r){var n=e("safe-buffer").Buffer,s=n.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function i(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}function a(e){var t=i(e);if("string"!=typeof t&&(n.isEncoding===s||!s(e)))throw new Error("Unknown encoding: "+e);return t||e}function o(e){var t;switch(this.encoding=a(e),this.encoding){case"utf16le":this.text=p,this.end=g,t=4;break;case"utf8":this.fillLast=u,t=4;break;case"base64":this.text=m,this.end=y,t=3;break;default:return this.write=v,void(this.end=b)}this.lastNeed=0,this.lastTotal=0,this.lastChar=n.allocUnsafe(t)}function l(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function c(e,t,r){var n=t.length-1;if(n<r)return 0;var s=l(t[n]);return s>=0?(s>0&&(e.lastNeed=s-1),s):--n<r||-2===s?0:(s=l(t[n]))>=0?(s>0&&(e.lastNeed=s-2),s):--n<r||-2===s?0:(s=l(t[n]))>=0?(s>0&&(2===s?s=0:e.lastNeed=s-3),s):0}function d(e,t,r){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}function u(e){var t=this.lastTotal-this.lastNeed,r=d(this,e);return void 0!==r?r:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function h(e,t){var r=c(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)}function f(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t}function p(e,t){if((e.length-t)%2==0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function g(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function m(e,t){var r=(e.length-t)%3;return 0===r?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function y(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function v(e){return e.toString(this.encoding)}function b(e){return e&&e.length?this.write(e):""}r.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return"";var t,r;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r<e.length?t?t+this.text(e,r):this.text(e,r):t||""},o.prototype.end=f,o.prototype.text=h,o.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},{"safe-buffer":73}],76:[function(e,t,r){var n=e("punycode"),s=e("./util");function i(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}r.parse=w,r.resolve=S,r.resolveObject=T,r.format=E,r.Url=i;var a=/^([a-z0-9.+-]+:)/i,o=/:[0-9]*$/,l=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,c=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),d=["'"].concat(c),u=["%","/","?",";","#"].concat(d),h=["/","?","#"],f=255,p=/^[+a-z0-9A-Z_-]{0,63}$/,g=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,m={javascript:!0,"javascript:":!0},y={javascript:!0,"javascript:":!0},v={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},b=e("querystring");function w(e,t,r){if(e&&s.isObject(e)&&e instanceof i)return e;var n=new i;return n.parse(e,t,r),n}function E(e){return s.isString(e)&&(e=w(e)),e instanceof i?e.format():i.prototype.format.call(e)}function S(e,t){return w(e,!1,!0).resolve(t)}function T(e,t){return e?w(e,!1,!0).resolveObject(t):t}i.prototype.parse=function(e,t,r){if(!s.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var i=e.indexOf("?"),o=-1!==i&&i<e.indexOf("#")?"?":"#",c=e.split(o),w=/\\/g;c[0]=c[0].replace(w,"/");var E=e=c.join(o);if(E=E.trim(),!r&&1===e.split("#").length){var S=l.exec(E);if(S)return this.path=E,this.href=E,this.pathname=S[1],S[2]?(this.search=S[2],this.query=t?b.parse(this.search.substr(1)):this.search.substr(1)):t&&(this.search="",this.query={}),this}var T=a.exec(E);if(T){var C=(T=T[0]).toLowerCase();this.protocol=C,E=E.substr(T.length)}if(r||T||E.match(/^\/\/[^@\/]+@[^@\/]+/)){var k="//"===E.substr(0,2);!k||T&&y[T]||(E=E.substr(2),this.slashes=!0)}if(!y[T]&&(k||T&&!v[T])){for(var A,I,_=-1,R=0;R<h.length;R++)-1!==(L=E.indexOf(h[R]))&&(-1===_||L<_)&&(_=L);for(-1!==(I=-1===_?E.lastIndexOf("@"):E.lastIndexOf("@",_))&&(A=E.slice(0,I),E=E.slice(I+1),this.auth=decodeURIComponent(A)),_=-1,R=0;R<u.length;R++){var L;-1!==(L=E.indexOf(u[R]))&&(-1===_||L<_)&&(_=L)}-1===_&&(_=E.length),this.host=E.slice(0,_),E=E.slice(_),this.parseHost(),this.hostname=this.hostname||"";var D="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!D)for(var x=this.hostname.split(/\./),O=(R=0,x.length);R<O;R++){var P=x[R];if(P&&!P.match(p)){for(var M="",F=0,U=P.length;F<U;F++)P.charCodeAt(F)>127?M+="x":M+=P[F];if(!M.match(p)){var N=x.slice(0,R),B=x.slice(R+1),j=P.match(g);j&&(N.push(j[1]),B.unshift(j[2])),B.length&&(E="/"+B.join(".")+E),this.hostname=N.join(".");break}}}this.hostname.length>f?this.hostname="":this.hostname=this.hostname.toLowerCase(),D||(this.hostname=n.toASCII(this.hostname));var $=this.port?":"+this.port:"",q=this.hostname||"";this.host=q+$,this.href+=this.host,D&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==E[0]&&(E="/"+E))}if(!m[C])for(R=0,O=d.length;R<O;R++){var K=d[R];if(-1!==E.indexOf(K)){var G=encodeURIComponent(K);G===K&&(G=escape(K)),E=E.split(K).join(G)}}var H=E.indexOf("#");-1!==H&&(this.hash=E.substr(H),E=E.slice(0,H));var V=E.indexOf("?");if(-1!==V?(this.search=E.substr(V),this.query=E.substr(V+1),t&&(this.query=b.parse(this.query)),E=E.slice(0,V)):t&&(this.search="",this.query={}),E&&(this.pathname=E),v[C]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){$=this.pathname||"";var z=this.search||"";this.path=$+z}return this.href=this.format(),this},i.prototype.format=function(){var e=this.auth||"";e&&(e=(e=encodeURIComponent(e)).replace(/%3A/i,":"),e+="@");var t=this.protocol||"",r=this.pathname||"",n=this.hash||"",i=!1,a="";this.host?i=e+this.host:this.hostname&&(i=e+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(i+=":"+this.port)),this.query&&s.isObject(this.query)&&Object.keys(this.query).length&&(a=b.stringify(this.query));var o=this.search||a&&"?"+a||"";return t&&":"!==t.substr(-1)&&(t+=":"),this.slashes||(!t||v[t])&&!1!==i?(i="//"+(i||""),r&&"/"!==r.charAt(0)&&(r="/"+r)):i||(i=""),n&&"#"!==n.charAt(0)&&(n="#"+n),o&&"?"!==o.charAt(0)&&(o="?"+o),t+i+(r=r.replace(/[?#]/g,(function(e){return encodeURIComponent(e)})))+(o=o.replace("#","%23"))+n},i.prototype.resolve=function(e){return this.resolveObject(w(e,!1,!0)).format()},i.prototype.resolveObject=function(e){if(s.isString(e)){var t=new i;t.parse(e,!1,!0),e=t}for(var r=new i,n=Object.keys(this),a=0;a<n.length;a++){var o=n[a];r[o]=this[o]}if(r.hash=e.hash,""===e.href)return r.href=r.format(),r;if(e.slashes&&!e.protocol){for(var l=Object.keys(e),c=0;c<l.length;c++){var d=l[c];"protocol"!==d&&(r[d]=e[d])}return v[r.protocol]&&r.hostname&&!r.pathname&&(r.path=r.pathname="/"),r.href=r.format(),r}if(e.protocol&&e.protocol!==r.protocol){if(!v[e.protocol]){for(var u=Object.keys(e),h=0;h<u.length;h++){var f=u[h];r[f]=e[f]}return r.href=r.format(),r}if(r.protocol=e.protocol,e.host||y[e.protocol])r.pathname=e.pathname;else{for(var p=(e.pathname||"").split("/");p.length&&!(e.host=p.shift()););e.host||(e.host=""),e.hostname||(e.hostname=""),""!==p[0]&&p.unshift(""),p.length<2&&p.unshift(""),r.pathname=p.join("/")}if(r.search=e.search,r.query=e.query,r.host=e.host||"",r.auth=e.auth,r.hostname=e.hostname||e.host,r.port=e.port,r.pathname||r.search){var g=r.pathname||"",m=r.search||"";r.path=g+m}return r.slashes=r.slashes||e.slashes,r.href=r.format(),r}var b=r.pathname&&"/"===r.pathname.charAt(0),w=e.host||e.pathname&&"/"===e.pathname.charAt(0),E=w||b||r.host&&e.pathname,S=E,T=r.pathname&&r.pathname.split("/")||[],C=(p=e.pathname&&e.pathname.split("/")||[],r.protocol&&!v[r.protocol]);if(C&&(r.hostname="",r.port=null,r.host&&(""===T[0]?T[0]=r.host:T.unshift(r.host)),r.host="",e.protocol&&(e.hostname=null,e.port=null,e.host&&(""===p[0]?p[0]=e.host:p.unshift(e.host)),e.host=null),E=E&&(""===p[0]||""===T[0])),w)r.host=e.host||""===e.host?e.host:r.host,r.hostname=e.hostname||""===e.hostname?e.hostname:r.hostname,r.search=e.search,r.query=e.query,T=p;else if(p.length)T||(T=[]),T.pop(),T=T.concat(p),r.search=e.search,r.query=e.query;else if(!s.isNullOrUndefined(e.search))return C&&(r.hostname=r.host=T.shift(),(R=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@"))&&(r.auth=R.shift(),r.host=r.hostname=R.shift())),r.search=e.search,r.query=e.query,s.isNull(r.pathname)&&s.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r;if(!T.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var k=T.slice(-1)[0],A=(r.host||e.host||T.length>1)&&("."===k||".."===k)||""===k,I=0,_=T.length;_>=0;_--)"."===(k=T[_])?T.splice(_,1):".."===k?(T.splice(_,1),I++):I&&(T.splice(_,1),I--);if(!E&&!S)for(;I--;I)T.unshift("..");!E||""===T[0]||T[0]&&"/"===T[0].charAt(0)||T.unshift(""),A&&"/"!==T.join("/").substr(-1)&&T.push("");var R,L=""===T[0]||T[0]&&"/"===T[0].charAt(0);return C&&(r.hostname=r.host=L?"":T.length?T.shift():"",(R=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@"))&&(r.auth=R.shift(),r.host=r.hostname=R.shift())),(E=E||r.host&&T.length)&&!L&&T.unshift(""),T.length?r.pathname=T.join("/"):(r.pathname=null,r.path=null),s.isNull(r.pathname)&&s.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=e.auth||r.auth,r.slashes=r.slashes||e.slashes,r.href=r.format(),r},i.prototype.parseHost=function(){var e=this.host,t=o.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},{"./util":77,punycode:51,querystring:54}],77:[function(e,t,r){t.exports={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}}},{}],78:[function(e,t,r){(function(e){(function(){function r(e,t){if(n("noDeprecation"))return e;var r=!1;function s(){if(!r){if(n("throwDeprecation"))throw new Error(t);n("traceDeprecation")?console.trace(t):console.warn(t),r=!0}return e.apply(this,arguments)}return s}function n(t){try{if(!e.localStorage)return!1}catch(e){return!1}var r=e.localStorage[t];return null!=r&&"true"===String(r).toLowerCase()}t.exports=r}).call(this)}).call(this,void 0!==ft?ft:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],79:[function(e,t,r){function n(e,t){if(e&&t)return n(e)(t);if("function"!=typeof e)throw new TypeError("need wrapper function");return Object.keys(e).forEach((function(t){r[t]=e[t]})),r;function r(){for(var t=new Array(arguments.length),r=0;r<t.length;r++)t[r]=arguments[r];var n=e.apply(this,t),s=t[t.length-1];return"function"==typeof n&&n!==s&&Object.keys(s).forEach((function(e){n[e]=s[e]})),n}}t.exports=n},{}],80:[function(e,t,r){t.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}},{}],81:[function(e,t,r){t.exports=s;var n=Object.prototype.hasOwnProperty;function s(){for(var e={},t=0;t<arguments.length;t++){var r=arguments[t];for(var s in r)n.call(r,s)&&(e[s]=r[s])}return e}},{}],82:[function(e,t,r){t.exports=function(e){e.prototype[Symbol.iterator]=function*(){for(let e=this.head;e;e=e.next)yield e.value}}},{}],83:[function(e,t,r){function n(e){var t=this;if(t instanceof n||(t=new n),t.tail=null,t.head=null,t.length=0,e&&"function"==typeof e.forEach)e.forEach((function(e){t.push(e)}));else if(arguments.length>0)for(var r=0,s=arguments.length;r<s;r++)t.push(arguments[r]);return t}function s(e,t,r){var n=t===e.head?new o(r,null,t,e):new o(r,t,t.next,e);return null===n.next&&(e.tail=n),null===n.prev&&(e.head=n),e.length++,n}function i(e,t){e.tail=new o(t,e.tail,null,e),e.head||(e.head=e.tail),e.length++}function a(e,t){e.head=new o(t,null,e.head,e),e.tail||(e.tail=e.head),e.length++}function o(e,t,r,n){if(!(this instanceof o))return new o(e,t,r,n);this.list=n,this.value=e,t?(t.next=this,this.prev=t):this.prev=null,r?(r.prev=this,this.next=r):this.next=null}t.exports=n,n.Node=o,n.create=n,n.prototype.removeNode=function(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");var t=e.next,r=e.prev;return t&&(t.prev=r),r&&(r.next=t),e===this.head&&(this.head=t),e===this.tail&&(this.tail=r),e.list.length--,e.next=null,e.prev=null,e.list=null,t},n.prototype.unshiftNode=function(e){if(e!==this.head){e.list&&e.list.removeNode(e);var t=this.head;e.list=this,e.next=t,t&&(t.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}},n.prototype.pushNode=function(e){if(e!==this.tail){e.list&&e.list.removeNode(e);var t=this.tail;e.list=this,e.prev=t,t&&(t.next=e),this.tail=e,this.head||(this.head=e),this.length++}},n.prototype.push=function(){for(var e=0,t=arguments.length;e<t;e++)i(this,arguments[e]);return this.length},n.prototype.unshift=function(){for(var e=0,t=arguments.length;e<t;e++)a(this,arguments[e]);return this.length},n.prototype.pop=function(){if(this.tail){var e=this.tail.value;return this.tail=this.tail.prev,this.tail?this.tail.next=null:this.head=null,this.length--,e}},n.prototype.shift=function(){if(this.head){var e=this.head.value;return this.head=this.head.next,this.head?this.head.prev=null:this.tail=null,this.length--,e}},n.prototype.forEach=function(e,t){t=t||this;for(var r=this.head,n=0;null!==r;n++)e.call(t,r.value,n,this),r=r.next},n.prototype.forEachReverse=function(e,t){t=t||this;for(var r=this.tail,n=this.length-1;null!==r;n--)e.call(t,r.value,n,this),r=r.prev},n.prototype.get=function(e){for(var t=0,r=this.head;null!==r&&t<e;t++)r=r.next;if(t===e&&null!==r)return r.value},n.prototype.getReverse=function(e){for(var t=0,r=this.tail;null!==r&&t<e;t++)r=r.prev;if(t===e&&null!==r)return r.value},n.prototype.map=function(e,t){t=t||this;for(var r=new n,s=this.head;null!==s;)r.push(e.call(t,s.value,this)),s=s.next;return r},n.prototype.mapReverse=function(e,t){t=t||this;for(var r=new n,s=this.tail;null!==s;)r.push(e.call(t,s.value,this)),s=s.prev;return r},n.prototype.reduce=function(e,t){var r,n=this.head;if(arguments.length>1)r=t;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");n=this.head.next,r=this.head.value}for(var s=0;null!==n;s++)r=e(r,n.value,s),n=n.next;return r},n.prototype.reduceReverse=function(e,t){var r,n=this.tail;if(arguments.length>1)r=t;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");n=this.tail.prev,r=this.tail.value}for(var s=this.length-1;null!==n;s--)r=e(r,n.value,s),n=n.prev;return r},n.prototype.toArray=function(){for(var e=new Array(this.length),t=0,r=this.head;null!==r;t++)e[t]=r.value,r=r.next;return e},n.prototype.toArrayReverse=function(){for(var e=new Array(this.length),t=0,r=this.tail;null!==r;t++)e[t]=r.value,r=r.prev;return e},n.prototype.slice=function(e,t){(t=t||this.length)<0&&(t+=this.length),(e=e||0)<0&&(e+=this.length);var r=new n;if(t<e||t<0)return r;e<0&&(e=0),t>this.length&&(t=this.length);for(var s=0,i=this.head;null!==i&&s<e;s++)i=i.next;for(;null!==i&&s<t;s++,i=i.next)r.push(i.value);return r},n.prototype.sliceReverse=function(e,t){(t=t||this.length)<0&&(t+=this.length),(e=e||0)<0&&(e+=this.length);var r=new n;if(t<e||t<0)return r;e<0&&(e=0),t>this.length&&(t=this.length);for(var s=this.length,i=this.tail;null!==i&&s>t;s--)i=i.prev;for(;null!==i&&s>e;s--,i=i.prev)r.push(i.value);return r},n.prototype.splice=function(e,t,...r){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);for(var n=0,i=this.head;null!==i&&n<e;n++)i=i.next;var a=[];for(n=0;i&&n<t;n++)a.push(i.value),i=this.removeNode(i);for(null===i&&(i=this.tail),i!==this.head&&i!==this.tail&&(i=i.prev),n=0;n<r.length;n++)i=s(this,i,r[n]);return a},n.prototype.reverse=function(){for(var e=this.head,t=this.tail,r=e;null!==r;r=r.prev){var n=r.prev;r.prev=r.next,r.next=n}return this.head=t,this.tail=e,this};try{e("./iterator.js")(n)}catch(e){}},{"./iterator.js":82}]},{},[12])(12)}(_a);var Ra=pt(_a.exports);class La{constructor(){this.store={},this.store={}}clear(){this.store={}}getItem(e){return this.store[e]||null}setItem(e,t){this.store[e]=String(t)}removeItem(e){delete this.store[e]}get length(){return Object.keys(this.store).length}key(e){return Object.keys(this.store)[e]||null}}const Da=()=>"undefined"!=typeof window&&window.localStorage?window:{localStorage:new La};var xa={},Oa={},Pa={};Object.defineProperty(Pa,"__esModule",{value:!0}),Pa.bytesToString=Pa.stringToBytes=Pa.NIL=Pa.X500=Pa.OID=Pa.URL=Pa.DNS=Pa.hexToByte=Pa.byteToHex=void 0;let Ma=[],Fa={};for(var Ua=0;Ua<256;Ua++)Ma[Ua]=(Ua+256).toString(16).substr(1),Fa[Ma[Ua]]=Ua;Pa.byteToHex=Ma,Pa.hexToByte=Fa,Pa.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Pa.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",Pa.OID="6ba7b812-9dad-11d1-80b4-00c04fd430c8",Pa.X500="6ba7b814-9dad-11d1-80b4-00c04fd430c8",Pa.NIL="00000000-0000-0000-0000-000000000000";Pa.stringToBytes=e=>{e=unescape(encodeURIComponent(e));const t=new Uint8Array(e.length);for(let r=0;r<e.length;++r)t[r]=e.charCodeAt(r);return t};Pa.bytesToString=e=>{const t=new Uint8Array(e,0,e.byteLength);return String.fromCharCode.apply(null,Array.from(t))},Object.defineProperty(Oa,"__esModule",{value:!0}),Oa.parse=void 0;const Na=Pa;Oa.parse=(e,t,r)=>{let n=t&&r||0,s=0;for(t=t||[],e.toLowerCase().replace(/[0-9a-f]{2}/g,(e=>(s<16&&t&&(t[n+s++]=Na.hexToByte[e]),"")));s<16;)t[n+s++]=0;return t};var Ba={};Object.defineProperty(Ba,"__esModule",{value:!0}),Ba.unparse=void 0;const ja=Pa;Ba.unparse=(e,t)=>{let r=t||0,n=ja.byteToHex;return n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]};var $a={},qa={};Object.defineProperty(qa,"__esModule",{value:!0});qa.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;var Ka=ft&&ft.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty($a,"__esModule",{value:!0}),$a.validate=void 0;const Ga=Ka(qa);$a.validate=e=>"string"==typeof e&&Ga.default.test(e);var Ha={};Object.defineProperty(Ha,"__esModule",{value:!0}),Ha.version=void 0;const Va=$a;Ha.version=e=>{if(!Va.validate(e))throw TypeError("Invalid UUID");return parseInt(e.substr(14,1),16)};var za={},Wa={};Object.defineProperty(Wa,"__esModule",{value:!0}),Wa.stringify=void 0;const Ya=$a,Qa=[];for(let e=0;e<256;++e)Qa.push((e+256).toString(16).substr(1));Wa.stringify=(e,t=0)=>{const r=(Qa[e[t+0]]+Qa[e[t+1]]+Qa[e[t+2]]+Qa[e[t+3]]+"-"+Qa[e[t+4]]+Qa[e[t+5]]+"-"+Qa[e[t+6]]+Qa[e[t+7]]+"-"+Qa[e[t+8]]+Qa[e[t+9]]+"-"+Qa[e[t+10]]+Qa[e[t+11]]+Qa[e[t+12]]+Qa[e[t+13]]+Qa[e[t+14]]+Qa[e[t+15]]).toLowerCase();if(!Ya.validate(r))throw TypeError("Stringified UUID is invalid");return r};var Xa={};Object.defineProperty(Xa,"__esModule",{value:!0}),Xa.rng=void 0;Xa.rng=()=>{let e=new Array(16);for(let t=0;t<16;t++)e[t]=255&256*Math.random()+0;return e},Object.defineProperty(za,"__esModule",{value:!0}),za.v1=void 0;const Ja=Wa,Za=Xa;let eo,to,ro=0,no=0;za.v1=(e,t,r=0)=>{let n=t&&r||0;const s=t||new Uint8Array(16);let i=e&&e.node?e.node:eo,a=e&&e.clockseq?e.clockseq:to;if(null==i||null==a){const t=e&&e.random?e.random:e&&e.rng?e.rng():Za.rng();null==i&&(i=eo=[1|t[0],t[1],t[2],t[3],t[4],t[5]]),null==a&&(a=to=16383&(t[6]<<8|t[7]))}let o=e&&e.msecs?e.msecs:Date.now(),l=e&&e.nsecs?e.nsecs:no+1;const c=o-ro+(l-no)/1e4;if(c<0&&e&&!e.clockseq&&(a=a+1&16383),(c<0||o>ro)&&e&&!e.nsecs&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");ro=o,no=l,to=a,o+=122192928e5;const d=(1e4*(268435455&o)+l)%4294967296;s[n++]=d>>>24&255,s[n++]=d>>>16&255,s[n++]=d>>>8&255,s[n++]=255&d;const u=o/4294967296*1e4&268435455;s[n++]=u>>>8&255,s[n++]=255&u,s[n++]=u>>>24&15|16,s[n++]=u>>>16&255,s[n++]=a>>>8|128,s[n++]=255&a;for(let e=0;e<6;++e)s[n+e]=i[e];return t||Ja.stringify(s)};var so={};Object.defineProperty(so,"__esModule",{value:!0}),so.v4=void 0;const io=Ba,ao=Xa;so.v4=(e,t,r)=>{let n=t&&r||0,s=ao.rng();if(!e||e instanceof String||(e.random&&(s=e.random),e.rng&&(s=e.rng())),s[6]=15&s[6]|64,s[8]=63&s[8]|128,t)for(var i=0;i<16;i++)t[n+i]=s[i];return t||io.unparse(s)};var oo={},lo={};Object.defineProperty(lo,"__esModule",{value:!0}),lo.v35=void 0;const co=Wa,uo=Oa,ho=Pa;lo.v35=(e,t,r)=>(e,n,s,i=0)=>{if("string"==typeof e&&(e=ho.stringToBytes(e)),"string"==typeof n&&(n=uo.parse(n)),n&&16!==n.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let a=new Uint8Array(16+e.length);if(a.set(n),a.set(e,n.length),a=ho.stringToBytes(r(ho.bytesToString(a))),a[6]=15&a[6]|t,a[8]=63&a[8]|128,s)for(let e=0;e<16;++e)s[i+e]=a[e];return s||co.stringify(a)};var fo={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.any_hmac_sha1=e.b64_hmac_sha1=e.hex_hmac_sha1=e.any_sha1=e.b64_sha1=e.hex_sha1=void 0;let t=0,r="";e.hex_sha1=e=>i(n(l(e))),e.default=e.hex_sha1;e.b64_sha1=e=>a(n(l(e)));e.any_sha1=(e,t)=>o(n(l(e)),t);e.hex_hmac_sha1=(e,t)=>i(s(l(e),l(t)));e.b64_hmac_sha1=(e,t)=>a(s(l(e),l(t)));e.any_hmac_sha1=(e,t,r)=>o(s(l(e),l(t)),r);const n=e=>d(u(c(e),8*e.length)),s=(e,t)=>{let r=c(e);r.length>16&&(r=u(r,8*e.length));let n=Array(16),s=Array(16);for(var i=0;i<16;i++)n[i]=909522486^r[i],s[i]=1549556828^r[i];var a=u(n.concat(c(t)),512+8*t.length);return d(u(s.concat(a),672))},i=e=>{for(var r,n=t?"0123456789ABCDEF":"0123456789abcdef",s="",i=0;i<e.length;i++)r=e.charCodeAt(i),s+=n.charAt(r>>>4&15)+n.charAt(15&r);return s},a=e=>{for(var t="",n=e.length,s=0;s<n;s+=3)for(var i=e.charCodeAt(s)<<16|(s+1<n?e.charCodeAt(s+1)<<8:0)|(s+2<n?e.charCodeAt(s+2):0),a=0;a<4;a++)8*s+6*a>8*e.length?t+=r:t+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(i>>>6*(3-a)&63);return t},o=(e,t)=>{var r,n,s,i,a=t.length,o=[],l=Array(Math.ceil(e.length/2));for(r=0;r<l.length;r++)l[r]=e.charCodeAt(2*r)<<8|e.charCodeAt(2*r+1);for(;l.length>0;){for(i=[],s=0,r=0;r<l.length;r++)s=(s<<16)+l[r],s-=(n=Math.floor(s/a))*a,(i.length>0||n>0)&&(i[i.length]=n);o[o.length]=s,l=i}var c="";for(r=o.length-1;r>=0;r--)c+=t.charAt(o[r]);var d=Math.ceil(8*e.length/(Math.log(t.length)/Math.log(2)));for(r=c.length;r<d;r++)c=t[0]+c;return c},l=e=>{for(var t,r,n="",s=-1;++s<e.length;)t=e.charCodeAt(s),r=s+1<e.length?e.charCodeAt(s+1):0,t>=55296&&t<=56319&&r>=56320&&r<=57343&&(t=65536+((1023&t)<<10)+(1023&r),s++),t<=127?n+=String.fromCharCode(t):t<=2047?n+=String.fromCharCode(192|t>>>6&31,128|63&t):t<=65535?n+=String.fromCharCode(224|t>>>12&15,128|t>>>6&63,128|63&t):t<=2097151&&(n+=String.fromCharCode(240|t>>>18&7,128|t>>>12&63,128|t>>>6&63,128|63&t));return n},c=e=>{for(var t=Array(e.length>>2),r=0;r<t.length;r++)t[r]=0;for(r=0;r<8*e.length;r+=8)t[r>>5]|=(255&e.charCodeAt(r/8))<<24-r%32;return t},d=e=>{for(var t="",r=0;r<32*e.length;r+=8)t+=String.fromCharCode(e[r>>5]>>>24-r%32&255);return t},u=(e,t)=>{e[t>>5]|=128<<24-t%32,e[15+(t+64>>9<<4)]=t;for(var r=Array(80),n=1732584193,s=-271733879,i=-1732584194,a=271733878,o=-1009589776,l=0;l<e.length;l+=16){for(var c=n,d=s,u=i,m=a,y=o,v=0;v<80;v++){r[v]=v<16?e[l+v]:g(r[v-3]^r[v-8]^r[v-14]^r[v-16],1);let t=p(p(g(n,5),h(v,s,i,a)),p(p(o,r[v]),f(v)));o=a,a=i,i=g(s,30),s=n,n=t}n=p(n,c),s=p(s,d),i=p(i,u),a=p(a,m),o=p(o,y)}return[n,s,i,a,o]},h=(e,t,r,n)=>e<20?t&r|~t&n:e<40?t^r^n:e<60?t&r|t&n|r&n:t^r^n,f=e=>e<20?1518500249:e<40?1859775393:e<60?-1894007588:-899497514,p=(e,t)=>{var r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r},g=(e,t)=>e<<t|e>>>32-t}(fo);var po=ft&&ft.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(oo,"__esModule",{value:!0}),oo.v5=void 0;const go=lo,mo=po(fo);oo.v5=go.v35("v5",80,mo.default),Object.defineProperty(xa,"__esModule",{value:!0});const yo=Oa,vo=Ba,bo=$a,wo=Ha,Eo=za,So=so,To=oo,Co=Pa;var ko=xa.default={parse:yo.parse,unparse:vo.unparse,validate:bo.validate,version:wo.version,v1:Eo.v1,v4:So.v4,v5:To.v5,NIL:Co.NIL,DNS:Co.DNS,URL:Co.URL,OID:Co.OID,X500:Co.X500};const Ao=()=>ko.v4().toString();let Io=0;if("undefined"!=typeof BroadcastChannel&&"undefined"!=typeof window){const e=Ao(),t={},r=new BroadcastChannel("amity_ts_sdk");let n;r.postMessage({type:"startup",tabId:e}),r.onmessage=({data:s})=>{s.tabId!==e&&("startup"===s.type&&r.postMessage({type:"identify",tabId:e,tabIndex:Io}),"identify"===s.type&&void 0!==s.tabIndex&&s.tabId&&(t[s.tabId]=s.tabIndex,n||(n=setTimeout((()=>{const e=Object.values(t).sort();e&&0!==e.length&&(Io=e.reduce(((e,t)=>e<t?e:t+1),0))}),15))))}}const _o=async()=>{const e=await(async e=>new Promise((t=>{t(Da().localStorage.getItem(e))})))("deviceId");if(e)return e;const t=`ascWebSdk#${Ao()}`;return await(async(e,t)=>new Promise((r=>{Da().localStorage.setItem(e,t),r(!0)})))("deviceId",t),t},Ro=()=>{const e=(()=>{var e,t;return(null===(e=Ct.versions)||void 0===e?void 0:e.node)?Ct.versions.node:navigator?`${navigator.product.toLowerCase()}#${null!==(t=navigator.userAgent)&&void 0!==t?t:"unknown_agent"}`:"unknown_model"})();return{kind:"web",model:e,sdkVersion:u}},Lo=1e3;var Do;!function(e){e[e.IDENTIFIER_REJECTED=2]="IDENTIFIER_REJECTED",e[e.BAD_USERNAME_OR_PASSWORD=134]="BAD_USERNAME_OR_PASSWORD",e[e.NOT_AUTHORIZED=135]="NOT_AUTHORIZED"}(Do||(Do={}));const xo=e=>{let t;return{connect:async function(r){const n=await(async e=>`mqttjs_${await _o()}_${e}_${Io}`)(r.userId);return t&&(t.removeAllListeners(),t.end(!0)),t=Ra.connect(e,function(e){return Object.assign({clean:!1,clientId:`mqttjs_ + ${Math.random().toString(16).substring(2,10)}`,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:Lo,will:{topic:"WillMsg",payload:"Connection Closed abnormally..!",qos:0,retain:!1},resubscribe:!0},e)}({username:r.userId,password:r.accessToken,clientId:n})),t.on("connect",(()=>{t.options.reconnectPeriod=Lo,(()=>{const e=[ht(lt()),ht(ct()),ht(dt()),ht(ut()),ht(it(Ke())),ht(ot())]})()})),t.on("error",(e=>{switch(e.code){case 2:case 134:case 135:t.end()}})),t.on("reconnect",(()=>{t.options.reconnectPeriod=Math.min(2*(t.options.reconnectPeriod||Lo),8e3)})),new Promise((e=>t.once("connect",(()=>e()))))},async disconnect(){if(this.connected)return new Promise((e=>null==t?void 0:t.end(!0,void 0,(()=>e()))))},get connected(){return!!(null==t?void 0:t.connected)},on(e,r){null==t||t.on(e,r)},once(e,r){null==t||t.once(e,r)},off(e,r){void 0!==r?null==t||t.off(e,r):null==t||t.removeAllListeners(e)},removeAllListeners(){null==t||t.removeAllListeners()},subscribe(e,r){const n=(t,n)=>{var s;if(t||128===(null===(s=n[0])||void 0===s?void 0:s.qos)){const n=t?new fe(t.message,8e5,"error"):new ge(8e5,"error");console.warn(`Failed to subscribe to topic ${e}`,n),null==r||r(n)}else console.log(`Subscribed to topic ${e}`),null==r||r()};return t?t.subscribe(e,{qos:0},n):n(new Error("No connection to broker"),[]),()=>null==t?void 0:t.unsubscribe(e)},unsubscribe(e){null==t||t.unsubscribe(e)}}},Oo=(e={},t,r=!0)=>{Object.entries(e).forEach((([e,n])=>{const s=ue[e];if(!s)return;const i=de(s);i&&n.forEach((e=>{(r?Se:Ce)([s,"get",i(e)],e,t)}))}))},Po=(e,t)=>{const{log:r,cache:n}=ve(),s=[e,v,t],i={cachedAt:Date.now()};n&&(r("cache/api/pushToTombstone",{cacheKey:s,data:i}),ke([e,"get",t],!0),Se(s,i))};function Mo(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(r[n[s]]=e[n[s]])}return r}const Fo=(e,t="userId",r="user")=>{var n;return null!==(n=null==e?void 0:e.map((e=>((e,t="userId",r="user")=>e[r]?e:Object.assign({get[r](){var r;if(!ve().cache)return;return(null===(r=Ee(["user","get",e[t]]))||void 0===r?void 0:r.data)||void 0}},e))(e,t,r))))&&void 0!==n?n:e},Uo=(e,t,r="userId",n="user")=>{const s=e,i=t,a=s[i],o=Mo(s,["symbol"==typeof i?i:i+""]),l=Fo(a,r,n);return Object.assign(Object.assign({},o),{[t]:l})};function No(e){return e.map((e=>{var{isMentioned:t}=e,r=Mo(e,["isMentioned"]);return Object.assign({hasMentioned:t},r)}))}function Bo(e){return No(e)}function jo(e){return No(e)}const $o=e=>{var t,r;return null!==(r=null===(t=Ee(["messagePreviewChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==r?r:null},qo=["analytic","normal-priority"],Ko=["analytic","high-priority"],Go=async e=>{const t=ve();await t.http.post("/api/v1/analytics/activities",{activities:e})};class Ho{constructor(){this._timer=void 0,this._high_priority_timer=void 0}start(){this.syncCapturedEvent(),this._timer=setInterval((()=>{this.syncCapturedEvent()}),6e4),this._high_priority_timer=setInterval((()=>{this.syncHighPriorityCapturedEvent()}),1e4)}stop(){this._timer&&(clearInterval(this._timer),this._timer=void 0)}async syncCapturedEvent(){try{const e=Ee(qo);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await Go(t),ke(qo)}catch(e){this.stop(),ke(qo)}}async syncHighPriorityCapturedEvent(){try{const e=Ee(Ko);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await Go(t),ke(Ko)}catch(e){this.stop(),ke(Ko)}}}class Vo{constructor(){this._expireTime=3e5,this._poolLimit=1e3,this._recentViewed={},this._recentHighPriorityViewed={},this._throttleStoryTimer=void 0,this._bufferNewSeenStoryReferenceIds=[]}isAbleToEnqueue({itemId:e,expireTime:t,isHighPriority:r=!1}){const n=new Date,s=(()=>r?this._recentHighPriorityViewed[e]:this._recentViewed[e])()||new Date(-1*m);return!(n.getTime()-s.getTime()<t)}markPostAsViewed(e){if(!this.isAbleToEnqueue({itemId:e,expireTime:this._expireTime}))return;const t=new Date,r={event:[]},n=Ee(qo);(null==n?void 0:n.data)&&(r.event=n.data.event),r.event.length>=this._poolLimit&&r.event.shift(),r.event.push({contentId:e,contentType:"post",activityType:"view",timestamp:t.toISOString()}),Ce(qo,r),this._recentViewed[e]=t}markStory(e,t){if(!e.expiresAt)return;const r=new Date,n=new Date(e.expiresAt);if(!this.isAbleToEnqueue({itemId:e.storyId,expireTime:n.getTime(),isHighPriority:!0}))return;const s={event:[]},i=Ee(Ko);if((null==i?void 0:i.data)&&(s.event=i.data.event),s.event.length>=this._poolLimit&&s.event.shift(),s.event.push({contentId:e.storyId,contentType:"story",activityType:t,timestamp:r.toISOString()}),Ce(Ko,s),this._recentHighPriorityViewed[e.storyId]=r,"linkClicked"===t)return;Se(["story-seen","get",e.storyId],(new Date).toISOString());const a=Ee(["story-last-seen",e.targetId]);(null==a?void 0:a.data)?new Date(a.data).getTime()<new Date(e.expiresAt).getTime()&&Se(["story-last-seen",e.targetId],e.expiresAt):Se(["story-last-seen",e.targetId],e.expiresAt),this._bufferNewSeenStoryReferenceIds.push(e.referenceId),this._throttleStoryTimer||(this._throttleStoryTimer=setTimeout((()=>{clearTimeout(this._throttleStoryTimer),Je("local.story.reload",{referenceIds:this._bufferNewSeenStoryReferenceIds}),this._bufferNewSeenStoryReferenceIds=[]}),300))}markStoryAsViewed(e){this.markStory(e,"view")}markStoryAsClicked(e){this.markStory(e,"linkClicked")}}class zo{constructor(){this._client=ve(),this._eventCapturer=new Vo,this._eventSyncer=new Ho}markPostAsViewed(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markPostAsViewed(e)}markStoryAsViewed(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markStoryAsViewed(e)}markStoryAsClicked(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markStoryAsClicked(e)}established(){this._eventSyncer.start()}handleTokenExpired(){this._eventSyncer.stop()}destroy(){this._eventSyncer.stop(),ke(qo)}}let Wo;var Yo=()=>(Wo||(Wo=new zo),Wo);const Qo=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return null;let r={fileId:(null===(t=e.avatarFileId)||void 0===t?void 0:t.toString())?e.avatarFileId.toString():"",type:"image",fileUrl:"",createdAt:"",attributes:{name:"",extension:"",size:"",mimeType:"",metadata:{exif:{},gps:{},width:0,height:0,isFull:!1}}};const n=Ee(["file","get",`${e.avatarFileId}`]);return(null==n?void 0:n.data)&&(r=null==n?void 0:n.data),r}});class Xo{constructor(e,t,r){this._syncingStoriesCount=0,this._errorStoriesCount=0,this._targetId=e,this._lastStoryExpiresAt=t,this._lastStorySeenExpiresAt=r,this.cacheStoryExpireTime=Ee(["story-expire",this._targetId]),this.cacheStoreSeenTime=Ee(["story-last-seen",this._targetId]),this.getTotalStoryByStatus()}get lastStoryExpiresAt(){return this._lastStoryExpiresAt?new Date(this._lastStoryExpiresAt).getTime():0}get lastStorySeenExpiresAt(){return this._lastStorySeenExpiresAt?new Date(this._lastStorySeenExpiresAt).getTime():0}get localLastStoryExpires(){var e,t;return(null===(e=this.cacheStoryExpireTime)||void 0===e?void 0:e.data)?new Date(null===(t=this.cacheStoryExpireTime)||void 0===t?void 0:t.data).getTime():0}get localLastStorySeenExpiresAt(){var e,t;return(null===(e=this.cacheStoreSeenTime)||void 0===e?void 0:e.data)?new Date(null===(t=this.cacheStoreSeenTime)||void 0===t?void 0:t.data).getTime():0}get isContainUnSyncedStory(){const e=Ee(["story-sync-state",this._targetId]);return!!(null==e?void 0:e.data)&&["syncing","error"].includes(e.data)}getLocalLastSortingDate(){return this.isContainUnSyncedStory?this.localLastStoryExpires:this.lastStoryExpiresAt}getHasUnseenFlag(){const e=(new Date).getTime(),t=Math.max(this.lastStorySeenExpiresAt,this.localLastStorySeenExpiresAt);return Ee(["story-sync-state",this._targetId]),this.isContainUnSyncedStory?this.localLastStoryExpires>e&&this.localLastStoryExpires>t:this.lastStoryExpiresAt>e&&this.lastStoryExpiresAt>t}getTotalStoryByStatus(){const e=we(["story","get"]);if(!e)return this._errorStoriesCount=0,void(this._syncingStoriesCount=0);const t=e.reduce(((e,t)=>{const{data:{targetId:r,syncState:n}}=t;return r===this._targetId&&(e[n]+=1),e}),{syncing:0,error:0,synced:0});this._errorStoriesCount=t.error,this._syncingStoriesCount=t.syncing}get syncingStoriesCount(){return this._syncingStoriesCount}get failedStoriesCount(){return this._errorStoriesCount}}const Jo=e=>{const{targetType:t,targetId:r,lastStoryExpiresAt:n,lastStorySeenExpiresAt:s,targetUpdatedAt:i,localFilter:a}=e,o=new Xo(r,n,s);return{targetType:t,targetId:r,lastStoryExpiresAt:n,updatedAt:i,hasUnseen:o.getHasUnseenFlag(),syncingStoriesCount:o.syncingStoriesCount,failedStoriesCount:o.failedStoriesCount,localFilter:a,localLastExpires:o.localLastStoryExpires,localLastSeen:o.localLastStorySeenExpiresAt,localSortingDate:o.getLocalLastSortingDate()}},Zo=e=>Object.assign(Object.assign({},e),{get target(){const t={type:e.targetType};if("user"===e.targetType)return Object.assign(Object.assign({},t),{userId:e.targetId});if("content"===t.type)return Object.assign(Object.assign({},t),{contentId:e.targetId});if("community"===t.type){const r=Ee(["communityUsers","get",`${e.targetId}#${e.userId}`]);return Object.assign(Object.assign({},t),{communityId:e.targetId,creatorMember:null==r?void 0:r.data})}return{type:"unknown"}},get creator(){const t=Ee(["user","get",e.userId]);if(null==t?void 0:t.data)return Qo(t.data)},get childrenComment(){return e.children.map((e=>{const t=Ee(["comment","get",e]);if(null==t?void 0:t.data)return null==t?void 0:t.data})).filter((e=>e)).map((e=>Zo(e)))}}),el=async e=>{var t;const r=["channelUnreadInfo","get",e],n=null===(t=Ee(r))||void 0===t?void 0:t.data,s=we(["subChannelUnreadInfo","get"]);let i=0,a=!1;if(s&&(null==s?void 0:s.length)>0){const t=null==s?void 0:s.filter((({data:t})=>t.channelId===e&&!t.isDeleted));i=t.map((({data:e})=>e.unreadCount)).reduce(((e,t)=>e+t),0),a=t.some((({data:e})=>e.isMentioned))}Se(r,Object.assign(Object.assign({},null!=n?n:{channelId:e,createdAt:(new Date).toISOString()}),{updatedAt:(new Date).toISOString(),unreadCount:i,isMentioned:a}))};class tl{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=ve(),this.getUnsyncJobs()}startSyncReadReceipt(){this.timer=setInterval((()=>{this.syncReadReceipts()}),1e3*this.RECEIPT_SYNC_INTERVAL)}syncReadReceipts(){if(0===this.jobQueue.length||!1===this.isActive)return;const e=this.getReadReceipt();e&&this.markReadApi(e)}getUnsyncJobs(){var e;const t=null===(e=we(["readReceipt"]))||void 0===e?void 0:e.filter((({data:e})=>e.latestSyncSegment<e.latestSegment));null==t||t.forEach((({data:e})=>{this.enqueueReadReceipt(e.subChannelId,e.latestSegment)}))}getReadReceipt(){var e;const t=this.jobQueue[0];if(!t)return;if("syncing"===t.syncState)return;const r=null===(e=Ee(["readReceipt",t.subChannelId]))||void 0===e?void 0:e.data;return r?(null==r?void 0:r.latestSegment)>(null==r?void 0:r.latestSyncSegment)?(t.segment=r.latestSegment,t):(this.removeSynedReceipt(r.subChannelId,r.latestSegment),this.getReadReceipt()):void 0}async markReadApi(e){var t;const r=e;r.syncState="syncing";const{subChannelId:n,segment:s}=r,i=await(async({subChannelId:e,readToSegment:t})=>{const r=ve();r.log("subChannel/markAsReadBySegment",e);try{return await r.http.put(`/api/v1/markers/message-feeds/${e}/mark-read`,{readToSegment:t}),!0}catch(e){return!1}})({subChannelId:n,readToSegment:s});if(i){this.removeSynedReceipt(e.subChannelId,e.segment);const r=null===(t=Ee(["readReceipt",n]))||void 0===t?void 0:t.data;Se(["readReceipt",n],Object.assign(Object.assign({},r),{latestSyncSegment:s}))}else i||(r.retryCount>this.MAX_RETRY?this.removeJobFromQueue(r):(r.retryCount+=1,r.syncState="create"))}removeSynedReceipt(e,t){this.jobQueue.forEach((r=>{r.subChannelId===e&&r.segment<=t&&this.removeJobFromQueue(r)}))}startObservingReadReceiptQueue(){this.client.isUnreadCountEnabled&&(this.isActive=!0,this.startSyncReadReceipt())}stopObservingReadReceiptQueue(){this.isActive=!1;this.jobQueue.map((e=>"syncing"===e.syncState?Object.assign(Object.assign({},e),{syncState:"create"}):e)),this.timer&&clearInterval(this.timer)}onSessionEstablished(){this.startObservingReadReceiptQueue()}onSessionDestroyed(){this.stopObservingReadReceiptQueue(),this.jobQueue=[]}onTokenExpired(){this.stopObservingReadReceiptQueue()}onNetworkOffline(){this.stopObservingReadReceiptQueue()}onNetworkOnline(){this.startObservingReadReceiptQueue()}markRead(e,t){var r;const n=["subChannelUnreadInfo","get",e],s=null===(r=Ee(n))||void 0===r?void 0:r.data;s&&t>s.readToSegment&&(s.readToSegment=t,s.unreadCount=Math.max(s.lastSegment-t,0),el(s.channelId)),Se(n,s),this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var r;const n=null===(r=Ee(["readReceipt",e]))||void 0===r?void 0:r.data;if(n){if(n.latestSegment<t)Se(["readReceipt",e],Object.assign(Object.assign({},n),{latestSegment:t}));else if(n.latestSyncSegment>=t)return}else{Se(["readReceipt",e],{subChannelId:e,latestSegment:t,latestSyncSegment:0})}let s=this.getSyncJob(e);null===s||"syncing"===s.syncState?(s={subChannelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(s)):s.segment<t&&(s.segment=t)}getSyncJob(e){return this.jobQueue.find((t=>t.subChannelId===e))||null}enqueueJob(e){this.jobQueue.length<this.JOB_QUEUE_SIZE||this.jobQueue.shift(),this.jobQueue.push(e)}removeJobFromQueue(e){const t=this.jobQueue.indexOf(e);t>-1&&this.jobQueue.splice(t,1)}}let rl=null;var nl=()=>(rl||(rl=new tl),rl);const sl=(e,t)=>{var r;return null!==(r=null!=t?t:(e=>{var t,r;const n={creatorId:"creatorPrivateId"in e?e.creatorPrivateId:e.creatorId,feedId:null!==(t=e.messageFeedId)&&void 0!==t?t:e.subChannelId,contentId:e.messageId};return null===(r=Ee(["messageMarker","get",de("messageMarker")(n)]))||void 0===r?void 0:r.data})(e))&&void 0!==r?r:{readCount:0,deliveredCount:0}},il={comment:Zo,post:e=>Object.assign(Object.assign({},e),{analytics:{markAsViewed:()=>{Yo().markPostAsViewed(e.postId)}},get latestComments(){return e.comments&&e.comments.map((e=>{var t;const r=null===(t=Ee(["comment","get",e]))||void 0===t?void 0:t.data;return r?Zo(r):null})).filter(Boolean)||[]},get creator(){const t=Ee(["user","get",e.postedUserId]);if(null==t?void 0:t.data)return Qo(t.data)}}),user:Qo,category:e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return null;let r={fileId:(null===(t=e.avatarFileId)||void 0===t?void 0:t.toString())?e.avatarFileId.toString():"",type:"image",fileUrl:"",createdAt:"",attributes:{name:"",extension:"",size:"",mimeType:"",metadata:{exif:{},gps:{},width:0,height:0,isFull:!1}}};const n=Ee(["file","get",`${e.avatarFileId}`]);return(null==n?void 0:n.data)&&(r=null==n?void 0:n.data),r}}),story:e=>{const t=Yo(),r=Ee(["storyTarget","get",e.targetId]),n=Ee(["community","get",e.targetId]);return Object.assign(Object.assign({},e),{analytics:{markAsSeen:()=>{e.expiresAt&&"synced"===e.syncState&&t.markStoryAsViewed(e)},markLinkAsClicked:()=>{e.expiresAt&&"synced"===e.syncState&&t.markStoryAsClicked(e)}},get videoData(){var t,r;const n=Ee(["file","get",null===(r=null===(t=e.data)||void 0===t?void 0:t.videoFileId)||void 0===r?void 0:r.original]);if(!n)return;const{data:s}=n;return s||void 0},get imageData(){var t,r;if(!(null===(t=e.data)||void 0===t?void 0:t.fileId))return;const n=Ee(["file","get",null===(r=e.data)||void 0===r?void 0:r.fileId]);if(!n)return;const{data:s}=n;return s?Object.assign(Object.assign({},s),{fileUrl:`${s.fileUrl}?size=full`}):void 0},get community(){if("community"===e.targetType&&n)return(null==n?void 0:n.data)||void 0},get communityCategories(){if("community"!==e.targetType)return;if(!n)return;const{data:{categoryIds:t}}=n;return 0!==t.length?t.map((e=>{const t=Ee(["category","get",e]);return(null==t?void 0:t.data)||void 0})).filter((e=>void 0!==e)):void 0},get creator(){const t=Ee(["user","get",e.creatorPublicId]);if(null==t?void 0:t.data)return Qo(t.data)},get storyTarget(){if(null==r?void 0:r.data)return Jo(r.data)},get isSeen(){const t=Ee(["story-last-seen",e.targetId]);if(!(null==r?void 0:r.data))return!1;const n=(null==t?void 0:t.data)?new Date(t.data).getTime():0,s=new Date(null==r?void 0:r.data.lastStorySeenExpiresAt).getTime()||0,i=new Date(e.expiresAt).getTime();return Math.max(n,s)>=i}})},storyTarget:Jo,message:e=>{const t=Mo(e,["creatorPrivateId"]);return Object.assign(Object.assign({},t),{get readCount(){return sl(e).readCount},get deliveredCount(){return sl(e).deliveredCount},markRead:()=>{const{subChannelId:t,channelSegment:r}=e;nl().markRead(t,r)}})}},al=e=>{var t;const r=e.messagePreviewId?$o(e.channelId):null,n=null===(t=Ee(["user","get",null==r?void 0:r.creatorId]))||void 0===t?void 0:t.data,s=r?Object.assign(Object.assign({},r),{user:n?il.user(n):void 0}):null;return Object.assign(Object.assign({},e),{messagePreview:s})},ol=e=>{var t,r;const n={messagePreviewChannel:null!==(r=null===(t=e.messagePreviews)||void 0===t?void 0:t.map((t=>(t=>{var r;const n=null===(r=e.messageFeedsInfo)||void 0===r?void 0:r.find((e=>e.messageFeedId===t.messageFeedId)),{channelPublicId:s,messageFeedId:i,data:a,dataType:o,isDeleted:l,segment:c,creatorPublicId:d,createdAt:u,updatedAt:h}=t;return{channelId:s,subChannelId:i,data:a,dataType:o,isDeleted:l,segment:c,creatorId:d,createdAt:u,updatedAt:h,subChannelName:null==n?void 0:n.name,messagePreviewId:null==n?void 0:n.messagePreviewId,subChannelUpdatedAt:null==n?void 0:n.updatedAt}})(t))))&&void 0!==r?r:[]};Oo(n)},ll=e=>{var t,r;return null!==(r=null===(t=Ee(["messagePreviewSubChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==r?r:null},cl=e=>{var t;const r=e.messagePreviewId?ll(e.subChannelId):null,n=r?Object.assign(Object.assign({},r),{user:null===(t=Ee(["user","get",null==r?void 0:r.creatorId]))||void 0===t?void 0:t.data}):null;return Object.assign(Object.assign({},e),{messagePreview:n})},dl=e=>{var t,r;const n={messagePreviewSubChannel:null!==(r=null===(t=e.messages)||void 0===t?void 0:t.map((t=>(t=>{var r;const n=null===(r=e.messageFeeds)||void 0===r?void 0:r.find((e=>e.messageFeedId===t.messageFeedId)),{channelPublicId:s,messageFeedId:i,messageId:a,creatorPublicId:o,data:l,dataType:c,isDeleted:d,segment:u,createdAt:h,updatedAt:f}=t;return{messagePreviewId:a,channelId:s,subChannelId:i,data:l,dataType:c,isDeleted:d,segment:u,creatorId:o,createdAt:h,updatedAt:f,subChannelName:null==n?void 0:n.name,subChannelUpdatedAt:null==n?void 0:n.updatedAt}})(t))))&&void 0!==r?r:[]};Oo(n)};function ul(e){const t=Object.create(Object.getPrototypeOf(e)),r=Object.getOwnPropertyDescriptors(e);return Object.defineProperties(t,r),t}function hl(e,t,r){Se(["subChannel","get",e],Object.assign(ul(t),r))}const fl=async e=>{var t,r,n,s;const{channelId:i,messageId:a,creatorId:o,createdAt:l,updatedAt:c,data:d,dataType:u,subChannelId:h,channelSegment:f,isDeleted:p}=e,g=null===(t=Ee(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(!g||g.segment<=e.channelSegment){const t=null===(r=Ee(["subChannel","get",h]))||void 0===r?void 0:r.data;Se(["messagePreviewSubChannel","get",e.subChannelId],{channelId:i,creatorId:o,messagePreviewId:a,createdAt:l,updatedAt:c,subChannelId:h,data:d,dataType:u,segment:f,isDeleted:p,subChannelUpdatedAt:null==t?void 0:t.updatedAt,subChannelName:null==t?void 0:t.displayName}),hl(e.subChannelId,t,{messagePreviewId:a})}const m=null===(n=Ee(["messagePreviewChannel","get",e.channelId]))||void 0===n?void 0:n.data;if(!m||new Date(m.createdAt).valueOf()<=new Date(e.createdAt).valueOf()){const t=null===(s=Ee(["subChannel","get",h]))||void 0===s?void 0:s.data;Se(["messagePreviewChannel","get",e.channelId],{channelId:i,creatorId:o,messagePreviewId:a,createdAt:l,updatedAt:c,subChannelId:h,data:d,dataType:u,segment:f,isDeleted:p,subChannelUpdatedAt:null==t?void 0:t.updatedAt,subChannelName:null==t?void 0:t.displayName})}},pl=async e=>{var t,r,n,s;const{channelId:i,messageId:a,creatorId:o,createdAt:l,updatedAt:c,data:d,dataType:u,subChannelId:h,channelSegment:f,isDeleted:p}=e,g=null===(t=Ee(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(g&&g.messagePreviewId===e.messageId){const t=null===(r=Ee(["subChannel","get",h]))||void 0===r?void 0:r.data;hl(e.subChannelId,t,{messagePreviewId:a}),Se(["messagePreviewSubChannel","get",e.subChannelId],{channelId:i,creatorId:o,messagePreviewId:a,createdAt:l,updatedAt:c,subChannelId:h,data:d,dataType:u,segment:f,isDeleted:p,subChannelUpdatedAt:null==e?void 0:e.updatedAt,subChannelName:null==t?void 0:t.displayName})}const m=null===(n=Ee(["messagePreviewChannel","get",e.channelId]))||void 0===n?void 0:n.data;if(m&&m.messagePreviewId===e.messageId){const t=null===(s=Ee(["subChannel","get",h]))||void 0===s?void 0:s.data;Se(["messagePreviewChannel","get",e.channelId],{channelId:i,creatorId:o,messagePreviewId:a,createdAt:l,updatedAt:c,subChannelId:h,data:d,dataType:u,segment:f,isDeleted:p,subChannelUpdatedAt:null==t?void 0:t.updatedAt,subChannelName:null==t?void 0:t.displayName})}},gl=async e=>{var t,r,n,s;const{channelId:i,subChannelId:a}=e,o=null===(t=Ee(["messagePreviewChannel","get",i]))||void 0===t?void 0:t.data;if((null==o?void 0:o.subChannelId)===a){const e=null===(r=Ee(["subChannel","get",a]))||void 0===r?void 0:r.data;Se(["messagePreviewChannel","get",i],Object.assign(Object.assign({},o),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}const l=null===(n=Ee(["messagePreviewSubChannel","get",a]))||void 0===n?void 0:n.data;if(l&&new Date(l.updatedAt).valueOf()>new Date(e.updatedAt).valueOf()){const e=null===(s=Ee(["subChannel","get",a]))||void 0===s?void 0:s.data;Se(["messagePreviewSubChannel","get",a],Object.assign(Object.assign({},l),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}},ml=(e,t)=>{var r,n,s,i,a;const o=ve();return o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()?null!==(n=null===(r=(e=>{var t;return null===(t=Ee(["channelUnreadInfo","get",e]))||void 0===t?void 0:t.data})(e.channelId))||void 0===r?void 0:r.unreadCount)&&void 0!==n?n:0:(null==t?void 0:t.isDeleted)?0:null!==(a=null!==(s=null==t?void 0:t.unreadCount)&&void 0!==s?s:null===(i=(e=>{var t;const r={entityId:e,userId:Ke()._id};return null===(t=Ee(["channelMarker","get",de("channelMarker")(r)]))||void 0===t?void 0:t.data})(e.channelId))||void 0===i?void 0:i.unreadCount)&&void 0!==a?a:0},yl=(e,t)=>{var r,n,s,i;const a=ve();return a.isUnreadCountEnabled&&a.getMarkerSyncConsistentMode()?null!==(n=null===(r=(e=>{var t;return null===(t=Ee(["channelUnreadInfo","get",e]))||void 0===t?void 0:t.data})(e.channelId))||void 0===r?void 0:r.isMentioned)&&void 0!==n&&n:void 0!==(null==t?void 0:t.hasMentioned)?null==t?void 0:t.hasMentioned:null!==(i=null===(s=(e=>{var t;const r={entityId:e,userId:Ke()._id};return null===(t=Ee(["channelMarker","get",de("channelMarker")(r)]))||void 0===t?void 0:t.data})(e.channelId))||void 0===s?void 0:s.hasMentioned)&&void 0!==i&&i},vl=e=>{const{feedMarkers:t,userFeedMarkers:r}=e;if(t.length>0&&r.length>0){const e=[],n=new Map(t.map((e=>[e.feedId,e])));r.forEach((t=>{const r=n.get(t.feedId);if(r&&r.feedId===t.feedId){const n=r.lastSegment-t.readToSegment,s={subChannelId:r.feedId,channelId:r.entityId,readToSegment:t.readToSegment,lastSegment:r.lastSegment,lastMentionSegment:t.lastMentionSegment,unreadCount:Math.max(0,n),isMentioned:t.isMentioned,isDeleted:r.isDeleted,createdAt:t.createdAt,updatedAt:t.updatedAt};Oo({subChannelUnreadInfo:[s]}),e.includes(r.entityId)||e.push(r.entityId)}})),e.forEach((e=>{el(e)}))}},bl=["broadcast","conversation","community"],wl=({type:e})=>bl.includes(e);function El(e,t={isMessagePreviewUpdated:!0}){var r;let{messagePreviewId:n}=e;const s=null===(r=Ee(["messagePreviewChannel","get",e.channelId]))||void 0===r?void 0:r.data;return(null==s?void 0:s.messagePreviewId)&&!t.isMessagePreviewUpdated&&(n=s.messagePreviewId),Object.assign(Object.assign({get unreadCount(){return ml(e)},get hasMentioned(){return yl(e)},get isMentioned(){return yl(e)},get subChannelsUnreadCount(){return ml(e)}},e),{defaultSubChannelId:e._id,isUnreadCountSupport:wl(e),messagePreviewId:n})}const Sl=(e,t={isMessagePreviewUpdated:!0})=>{Oo({channels:e.channels.map((e=>El(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated})))})},Tl=async(e,t={isMessagePreviewUpdated:!0})=>{const r=ve(),n=await r.getMessagePreviewSetting(!1);if(r.isUnreadCountEnabled&&r.getMarkerSyncConsistentMode()){const t=await(async e=>{const t=ve();t.log("channel/getUserMessageFeedMakers",e);const{data:r}=await t.http.get("/api/v1/markers/user-message-feed",{params:{channelIds:e}});return r})(e.channels.map((({channelId:e})=>e))),{feedMarkers:r,userFeedMarkers:n}=t;vl({feedMarkers:r,userFeedMarkers:n})}t.isMessagePreviewUpdated&&"no-message-preview"!==n&&e.messagePreviews&&e.messagePreviews.length>0&&ol(e);const s=e.channels.filter(wl).map((({channelId:e})=>e));if(s.length>0){Sl(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated});try{await(async e=>{const t=ve();t.log("channel/getChannelMarkers",e);const{data:r}=await t.http.get("/api/v1/markers/channels",{params:{channelIds:e}}),{userEntityMarkers:n,userMarkers:s}=r,i=Bo(n),a=t.cache&&Date.now();return t.cache&&Oo({userEntityMarkers:i,userMarkers:s},{cachedAt:a}),Je("local.channelMarker.fetched",{userEntityMarkers:i}),Je("local.userMarker.fetched",{userMarkers:s}),{data:i,cachedAt:a}})(s)}catch(e){}}const i=e.channels.map((e=>El(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated}))),a=Fo(e.channelUsers),o=Mo(e,["messageFeedsInfo","messagePreviews"]);return Object.assign(Object.assign({},o),{channels:i,channelUsers:a})},Cl=async e=>{const t=ve();t.log("channel/getChannelByIds",e);const r=e.map((e=>encodeURIComponent(e)));let n;try{n=(await t.http.get("/api/v3/channels/list",{params:{channelIds:r}})).data}catch(t){throw e.forEach((e=>{C(null==t?void 0:t.code)&&Po("channel",e)})),t}const s=await Tl(n),i=t.cache&&Date.now();return t.cache&&Oo(s,{cachedAt:i}),{data:s.channels,cachedAt:i}};Cl.locally=e=>{var t;const r=ve();if(r.log("channel/getChannelByIds.locally",e),!r.cache)return;const n=e.map((e=>Ee(["channel","get",e]))).filter(Boolean);if((null==n?void 0:n.length)<e.length)return;return{data:n.map((({data:e})=>e)),cachedAt:(null===(t=n.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0]).cachedAt}};const kl=async()=>{const e=ve();e.log("channel/getUserMarker");const{data:t}=await e.http.get("/api/v1/markers/userMarker"),{userMarkers:r}=t,n=e.cache&&Date.now();e.cache&&Oo({userMarkers:r},{cachedAt:n}),Je("local.userMarker.fetched",{userMarkers:r});return{data:r.reduce(((e,t)=>null==e||new Date(e.lastSyncAt).getTime()<new Date(t.lastSyncAt).getTime()?t:e),void 0),cachedAt:n}},Al=e=>!0===e&&void 0;function Il(e,t,r){var n,s;if(r)return r.hasMentioned;const i=ve();if(i.isUnreadCountEnabled&&i.getMarkerSyncConsistentMode()){const e=null===(n=Ee(["subChannelUnreadInfo","get",t]))||void 0===n?void 0:n.data;return!!e&&e.isMentioned}const a={entityId:e,feedId:t,userId:Ke()._id},o=null===(s=Ee(["subChannelMarker","get",de("subChannelMarker")(a)]))||void 0===s?void 0:s.data;return!!o&&o.hasMentioned}const _l=["broadcast","conversation","community"],Rl=({channelType:e})=>_l.includes(e);function Ll(e){var{channelId:t,channelPublicId:r,channelType:n,childCount:s,creatorId:i,creatorPublicId:a,lastMessageId:o,lastMessageTimestamp:l,messageFeedId:c,name:d}=e,u=Mo(e,["channelId","channelPublicId","channelType","childCount","creatorId","creatorPublicId","lastMessageId","lastMessageTimestamp","messageFeedId","name"]);return Object.assign(Object.assign({get unreadCount(){return function(e,t,r){var n,s;if(r)return r.unreadCount;const i=ve();if(i.isUnreadCountEnabled&&i.getMarkerSyncConsistentMode()){const e=null===(n=Ee(["subChannelUnreadInfo","get",t]))||void 0===n?void 0:n.data;return e?e.isDeleted?0:e.unreadCount:0}const a={entityId:e,feedId:t,userId:Ke()._id},o=null===(s=Ee(["subChannelMarker","get",de("subChannelMarker")(a)]))||void 0===s?void 0:s.data;return o?o.unreadCount:0}(t,c)},get hasMentioned(){return Il(t,c)},get isMentioned(){return Il(t,c)}},u),{channelId:r,creatorId:a,displayName:d,lastActivity:l,latestMessageId:o,messageCount:s,subChannelId:c,isUnreadCountSupport:Rl({channelType:n})})}function Dl(e,t,r){var n;const{channelPublicId:s,childCount:i,creatorPublicId:a,mentionedUsers:o,messageFeedId:l,myReactions:c,reactionCount:d,reactions:u,referenceId:h,segment:f,messageId:p,creatorId:g}=e,m=Mo(e,["channelPublicId","childCount","creatorPublicId","mentionedUsers","messageFeedId","myReactions","reactionCount","reactions","referenceId","segment","messageId","creatorId"]);let y;h&&(y=Ee(["message","get",h])),y||(y=Ee(["message","get",p]));const v=Object.assign(Object.assign({},m),{messageId:p,channelId:s,channelSegment:f,childrenNumber:i,creatorId:a,creatorPrivateId:e.creatorId,reactions:null!=u?u:{},myReactions:c||(null!==(n=null==y?void 0:y.data.myReactions)&&void 0!==n?n:[]),reactionsCount:d,subChannelId:l,uniqueId:y?y.data.uniqueId:p,referenceId:h});return o&&(v.mentionees=o.map((e=>"channel"===e.type?e:{type:"user",userIds:e.userPublicIds}))),t&&t.length&&r&&((e,t,r)=>{const n=ve(),s=Ee(["message","get",e.messageId]),i=(null==s?void 0:s.data.myReactions)||[];Object.assign(e,{myReactions:i});const a=t[0];a&&a.userId===n.userId&&("message.reactionAdded"!==r||i.includes(a.reactionName)||Object.assign(e,{myReactions:[...i,a.reactionName]}),"message.reactionRemoved"===r&&i.includes(a.reactionName)&&Object.assign(e,{myReactions:i.filter((e=>e!==a.reactionName))}))})(v,t,r),v}const xl={},Ol=async(e,t)=>{const r=e.messages.map((({messageId:e})=>e));if(r.length>0){Oo({messages:(n=e).messages.map((e=>Dl(e,n.reactions)))});const t=r.join("");xl[t]&&clearTimeout(xl[t]),xl[t]=setTimeout((()=>{try{(async e=>{const t=ve();t.log("channel/getMessageMarkers",e);const{data:r}=await t.http.get("/api/v1/markers/messages",{params:{messageIds:e}}),{contentMarkers:n,feedMarkers:s,userMarkers:i}=r,a=t.cache&&Date.now();t.cache&&Oo({contentMarkers:n,feedMarkers:s,userMarkers:i},{cachedAt:a}),Je("local.feedMarker.fetched",{feedMarkers:s}),Je("local.messageMarker.fetched",{contentMarkers:n}),Je("local.userMarker.fetched",{userMarkers:i})})(r)}catch(e){}}),2e3)}var n;const{messageFeeds:s}=e,i=Mo(e,["messageFeeds"]);return s&&s.length>0&&(null==s||s.forEach((e=>{var t,r;const n=null!==(r=null===(t=Ee(["subChannel","get",e.messageFeedId]))||void 0===t?void 0:t.data)&&void 0!==r?r:{},s=Mo(Ll(e),["unreadCount","hasMentioned","isMentioned"]);hl(e.messageFeedId,n,s)}))),Object.assign(Object.assign({},i),{messages:e.messages.map((r=>Dl(r,e.reactions,t)))})};function Pl(e){var{subChannelId:t,mentionees:r,dataType:n,data:s}=e,i=Mo(e,["subChannelId","mentionees","dataType","data"]);return n===c.IMAGE||n===c.FILE?Object.assign({messageFeedId:t,mentionedUsers:r,dataType:n,data:Object.assign({caption:""},s)},i):Object.assign({messageFeedId:t,mentionedUsers:r,dataType:n,data:s},i)}function Ml(e){var{sortBy:t,subChannelId:r,tags:n,includingTags:s,excludingTags:i,includeDeleted:a,aroundMessageId:o,limit:l,type:c}=e,d=Mo(e,["sortBy","subChannelId","tags","includingTags","excludingTags","includeDeleted","aroundMessageId","limit","type"]);const u=Object.assign(Object.assign({},d),{messageFeedId:r,isDeleted:Al(a),options:{sortBy:t,limit:l||h,around:o}});return n&&(u.includeTags=n),s&&(u.includeTags=s),c&&(u.dataType=c),i&&(u.excludeTags=i),u}const Fl=["broadcast","conversation","community"],Ul=({channelType:e})=>Fl.includes(e),Nl=async e=>{const t=e.messageFeeds.filter(Ul).map((({messageFeedId:e})=>e));if(t.length>0){(e=>{Oo({messageFeeds:e.messageFeeds.map((e=>Ll(e)))})})(e);try{await(async(e,t={limit:100})=>{const r=ve();r.log("channel/getSubChannelMarkers",e,t);const{data:n}=await r.http.get("/api/v1/markers/message-feeds",{params:{messageFeedIds:e,options:{token:X(t,"skiplimit")}}}),{paging:s}=n,i=Mo(n,["paging"]),{userEntityMarkers:a,userFeedMarkers:o,userMarkers:l,feedMarkers:c}=i;r.isUnreadCountEnabled&&r.getMarkerSyncConsistentMode()&&vl({feedMarkers:c,userFeedMarkers:o});const d=Bo(a),u=jo(o),h=r.cache&&Date.now();r.cache&&Oo({userEntityMarkers:d,userFeedMarkers:u,userMarkers:l},{cachedAt:h}),Je("local.channelMarker.fetched",{userEntityMarkers:d}),Je("local.subChannelMarker.fetched",{userFeedMarkers:u}),Je("local.userMarker.fetched",{userMarkers:l});const f=J(s.next);return{data:u,cachedAt:h,prevPage:J(s.previous),nextPage:f}})(t)}catch(e){}}dl(e);const r=e.messageFeeds.map(Ll),n=e.messages.map((e=>Dl(e)));return Object.assign(Object.assign({},e),{messageFeeds:r,messages:n})};const Bl=e=>{const t=ve();return Xe(t,"client/onSessionStateChange","sessionStateChange",e)},jl=(e,t)=>{const r=setInterval(e,t);return()=>clearInterval(r)},$l=e=>"undefined"!=typeof window&&window.addEventListener?(window.addEventListener("online",e),()=>window.removeEventListener("online",e)):"undefined"!=typeof document&&document.addEventListener?(document.addEventListener("online",e),()=>document.removeEventListener("online",e)):(console.error("Unsupported environment"),()=>console.error("Unsupported environment")),ql=(e,t)=>{const{log:r,cache:n}=ve(),s=[e,v,t];if(!n)return;r("cache/api/isInTombstone",s);const i=Ee(s),{lifeSpan:a}=ae("cache_then_server",18e4);if(i&&se(i.data,a))throw new pe("Item not found!",400400,"error")},Kl=async e=>{const t=ve();t.log("channel/getSubChannel",e),ql("subChannel",e);try{const r=await t.http.get(`/api/v5/message-feeds/${encodeURIComponent(e)}`),n=await Nl(r.data),s=t.cache&&Date.now();return t.cache&&Oo(n,{cachedAt:s}),Je("local.message-feed.fetched",n),{data:n.messageFeeds[0],cachedAt:s}}catch(t){throw C(null==t?void 0:t.code)&&Po("subChannel",e),t}};Kl.locally=e=>{const t=ve();if(t.log("channel/getSubChannel.locally",e),!t.cache)return;const r=Ee(["subChannel","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};let Gl=!1,Hl=[];const Vl={},zl=async()=>{const e=Object.entries(Vl).filter((([,e])=>e)).map((([e])=>e));return 0!==e.length&&(async e=>{const t=ve();t.log("subChannel/readingAPI",e);const{data:r}=await t.http.post("/api/v1/markers/message-feeds/reading",{messageFeedIds:e}),{userEntityMarkers:n,userFeedMarkers:s,feedMarkers:i,userMarkers:a}=r,o=Bo(n),l=jo(s),c=t.cache&&Date.now();return t.cache&&Oo({userEntityMarkers:o,userFeedMarkers:l,feedMarkers:i,userMarkers:a},{cachedAt:c}),Je("local.feedMarker.fetched",{feedMarkers:i}),Je("local.channelMarker.fetched",{userEntityMarkers:o}),Je("local.subChannelMarker.fetched",{userFeedMarkers:l}),Je("local.userMarker.fetched",{userMarkers:a}),!0})(e)},Wl=()=>{Gl=!1},Yl=()=>(Gl=!0,Bl((e=>{"notLoggedIn"===e&&Wl()})),()=>{Wl()}),Ql=async e=>{const t=await(async e=>{const t=Kl.locally(e);if(t)return t.data.channelId;const{data:r}=await Kl(e);return r.channelId})(e),r=at({channelId:t,subChannelId:e});Hl.push(ht(r))};jl((async()=>{Gl&&await zl()}),3e4);const Xl=async e=>{const t=ve();t.log("channel/getSubChannels",e);const r=await t.http.get("/api/v5/message-feeds/list",{params:{messageFeedIds:e.map(encodeURIComponent)}}),n=await Nl(r.data),s=t.cache&&Date.now();return t.cache&&Oo(n,{cachedAt:s}),Je("local.message-feed.fetched",n),{data:n.messageFeeds,cachedAt:s}};Xl.locally=e=>{var t;const r=ve();if(r.log("channel/getSubChannels.locally",e),!r.cache)return;const n=e.map((e=>Ee(["subChannel","get",e]))).filter(Boolean);if((null==n?void 0:n.length)<e.length)return;return{data:n.map((({data:e})=>e)),cachedAt:(null===(t=n.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0]).cachedAt}};const Jl=async(e=!0)=>{var t;const r=null===(t=Ee(["MessagePreviewSetting"]))||void 0===t?void 0:t.data;if(!e&&r)return r;const n=await(async()=>{const e=ve(),{data:t}=await e.http.get("/api/v3/network-settings/chat");return t})();var s;return(s=n).messagePreview.enabled?s.messagePreview.isIncludeDeleted?"message-preview-include-deleted":"message-preview-not-include-deleted":"no-message-preview"},Zl=async()=>{const e=ve(),{data:t}=await e.http.get("/api/v3/network-settings/social");return t.socialNetworkSetting},ec=(e,t)=>{var r;const n=null===(r=Ee(["users","get",e]))||void 0===r?void 0:r.data;return!!n&&n.permissions.some((e=>e===t))},tc=e=>{const{userId:t}=ve();return{currentUser:()=>ec(t,e),community:r=>((e,t,r)=>{var n;if(!e)return!1;const s=null===(n=Ee(["communityUsers","get",`${r}#${e}`]))||void 0===n?void 0:n.data;return!!s&&(!!s.permissions.some((e=>e===t))||ec(e,t))})(t,e,r),channel:r=>((e,t,r)=>{var n;if(!e)return!1;const s=null===(n=Ee(["channelUsers","get",`${r}#${e}`]))||void 0===n?void 0:n.data;return!!s&&(!!s.permissions.some((e=>e===t))||ec(e,t))})(t,e,r)}},rc=async e=>{const t=ve();if(t.log("channel/markerSync"),0===e.length)return!1;const{data:r}=await t.http.post("/api/v3/allowlists/verify",{data:e});return r.success},nc=async e=>{const t=ve();if(t.log("channel/markerSync"),0===e.length)return!1;const{data:r}=await t.http.post("/api/v3/blocklists/verify",{data:e});return r.success},sc=async()=>{const e=ve(),{data:t}=await e.http.get("/api/v3/network-settings/feed-setting");return Object.fromEntries(t.feedSettings.map((({feedType:e,contentSettings:t})=>[e,t])))},ic={notLoggedIn:["establishing"],terminated:["establishing"],establishing:["notLoggedIn","established"],established:["notLoggedIn","terminated","tokenExpired","establishing"],tokenExpired:["establishing"]},ac=e=>{const t=ve();t.log("client/api/setSessionState",e);const{sessionState:r}=t;if(r===e)return!1;if(!((e,t)=>ic[e].includes(t))(r,e))throw new fe(`Session state cannot change from ${r} to ${e}`,8e5,"error");return t.sessionState=e,t.emitter.emit("sessionStateChange",e),!0},oc=async e=>{const t=ve();ac("establishing");const{accessToken:r,users:n,expiresAt:s,issuedAt:i,refreshToken:a}=await(async e=>{const t=ve();t.log("client/api/getToken",e);const r=Ro(),{data:n}=await t.http.post("/api/v4/sessions",Object.assign(Object.assign({},e),{deviceInfo:r}),{headers:{"X-API-Key":t.apiKey}});return n})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${r}`,t.http.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.ws.io.opts.query={token:r},t.token={accessToken:r,issuedAt:i,expiresAt:s},ac("established"),{accessToken:r,users:n,refreshToken:a}},lc=e=>{const t=we(["subChannelUnreadInfo","get"]);if(t){(null==t?void 0:t.filter((({data:t})=>t.channelId===e))).forEach((({key:e,data:t})=>{Se(e,Object.assign(Object.assign({},t),{isDeleted:!0}))}))}},cc=e=>{var t;const r=["channelUnreadInfo","get",e];(null===(t=Ee(r))||void 0===t?void 0:t.data)&&ke(r)},dc=e=>{const t=ve();return Xe(t,"onChannelDeleted","channel.deleted",(async r=>{const n=await Tl(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&n.channels.forEach((e=>{lc(e.channelId),cc(e.channelId)})),Oo(n),e(n.channels[0])}))},uc=e=>{const t=ve();return Xe(t,"onChannelMemberBanned","channel.banned",(async r=>{const n=await Tl(r),{channels:s,channelUsers:i}=n,a=i.some((e=>"banned"===e.membership&&e.userId===t.userId));t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&a&&n.channels.forEach((e=>{lc(e.channelId),cc(e.channelId)})),Oo(n),e(s[0],i.find((e=>"banned"===e.membership)))}))},hc=(e,t)=>{const r=ve();return Xe(r,e,e,(e=>{r.cache&&Oo(e),t(e.users[0])}))},fc=e=>hc("user.deleted",e);const pc=async()=>{const e=ve();return e.log("client/api/disconnectClient"),e.mqtt.connected&&e.mqtt.disconnect(),e.ws.connected&&e.ws.disconnect(),"established"===e.sessionState&&ac("notLoggedIn"),e.emitter.all.clear(),e.ws.removeAllListeners(),e.mqtt.removeAllListeners(),e.userId=void 0,e.token=void 0,e.http.defaults.headers.common.Authorization="",e.http.defaults.metadata={tokenExpiry:"",isGlobalBanned:!1,isUserDeleted:!1},e.ws.io.opts.query={token:""},"tokenExpired"!==e.sessionState&&e.cache&&(e.cache={data:{}}),!0},gc=e=>{const t=ve();ac("terminated"),t.http.defaults.metadata&&("globalBan"===e&&(t.http.defaults.metadata.isGlobalBanned=!0),"userDeleted"===e&&(t.http.defaults.metadata.isUserDeleted=!0)),t.sessionHandler=void 0,pc()},mc=["disconnected","error","connect_error","reconnect_error","reconnect_failed"],yc=e=>{const t=ve(),r=mc.map((r=>Xe(t,`client/onConnectionError(${r})`,r,(t=>{const n=(null==t?void 0:t.code)?new fe(t.message,t.code,"fatal"):new me(r);e(n)}))));return()=>{r.forEach((e=>e()))}},vc=e=>{const t=ve();return Xe(t,"client/onConnectionError(user.didGlobalBan)","user.didGlobalBan",e)},bc=e=>{const t=de("channelMarker")({userId:Ke()._id,entityId:e.channelId});ke(["channelMarker","get",t],!0)},wc=e=>{const t=ve();return Xe(t,"onChannelCreated","channel.created",(async t=>{const r=await Tl(t);Oo(r),e(r.channels[0])}))},Ec=e=>{const t=ve(),r=[Xe(t,"onChannelUpdated","channel.updated",(async t=>{const r=await Tl(t);Oo(r),e(r.channels[0])})),Xe(t,"onChannelUpdated","local.channel.updated",(t=>e(t.channels[0])))];return()=>{r.forEach((e=>e()))}},Sc=e=>{const t=ve();return Xe(t,"onChannelJoined","channel.joined",(async t=>{const r=await Tl(t),{channels:n,channelUsers:s}=r;Oo(r),e(n[0],s[0])}))},Tc=e=>{const t=ve();return Xe(t,"onChannelLeft","channel.left",(async r=>{const{userId:n}=ve(),{channelUsers:s}=r,i=s.some((e=>e.userId===n)),a=await Tl(r,{isMessagePreviewUpdated:i});t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&i&&a.channels.forEach((e=>{lc(e.channelId),cc(e.channelId)}));const{channels:o,channelUsers:l}=a;Oo(a),e(o[0],l[0])}))},Cc=e=>{const t=ve();return Xe(t,"onChannelMuted","channel.setMuted",(async t=>{const r=await Tl(t);Oo(r),e(r.channels[0])}))},kc=e=>{const t=ve();return Xe(t,"onChannelMemberAdded","channel.membersAdded",(async t=>{const r=await Tl(t),{channels:n,channelUsers:s}=r;Oo(r),e(n[0],s.find((e=>"member"===e.membership)))}))},Ac=e=>{const t=ve();return Xe(t,"onChannelMemberRemoved","channel.membersRemoved",(async t=>{const r=await Tl(t),{channels:n,channelUsers:s}=r;Oo(r),e(n[0],s[0])}))},Ic=e=>{const t=ve();return Xe(t,"onChannelMemberUnbanned","channel.unbanned",(async t=>{const r=await Tl(t),{channels:n,channelUsers:s}=r;Oo(r),e(n[0],s.find((e=>"none"===e.membership)))}))},_c=e=>{const t=ve();return Xe(t,"onChannelMemberRoleAdded","local.channel-moderator.role-added",(async t=>{const{channels:r,channelUsers:n}=t;e(r[0],n.find((e=>"member"===e.membership)))}))},Rc=e=>{const t=ve();return Xe(t,"onChannelMemberRoleRemoved","local.channel-moderator.role-removed",(async t=>{const{channels:r,channelUsers:n}=t;e(r[0],n.find((e=>"member"===e.membership)))}))},Lc=e=>{const t=ve();return Xe(t,"feedMarker/onFeedMarkerUpdated","marker.feed-updated",(t=>{Oo(t),e(t.feedMarkers[0])}))},Dc=e=>{const t=ve(),r=[Xe(t,"message/onMessageCreated","message.created",(async r=>{const n=await Ol(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&r.messages.forEach((e=>{(e=>{var t;const r=ve(),n=["subChannelUnreadInfo","get",e.messageFeedId],s=null===(t=Ee(n))||void 0===t?void 0:t.data;if(!s)return;const i=s.lastSegment<e.segment?e.segment:s.lastSegment,a=i-s.readToSegment;let{lastMentionSegment:o}=s;e.mentionedUsers&&e.mentionedUsers.length>0&&e.mentionedUsers.forEach((t=>{("channel"===t.type||"user"===t.type&&r.userId&&t.userPublicIds.includes(r.userId))&&(o=e.segment)}));const l=Object.assign(Object.assign({},s),{lastMentionSegment:o,lastSegment:i,isMentioned:!(s.readToSegment>=o),unreadCount:Math.max(a,0)});Se(n,l)})(e),el(e.channelId)})),Oo(n),n.messages.forEach((t=>{e(t)}))}))];return()=>{r.forEach((e=>e()))}},xc=e=>{const t=ve(),r=[Xe(t,"message/onMessageCreated","local.message.created",(t=>t.messages.forEach((t=>{e(t)}))))];return()=>{r.forEach((e=>e()))}},Oc=e=>{const t=ve();return Xe(t,"onSubChannelCreated","message-feed.created",(async r=>{const n=await Nl(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&(e=>{e.messageFeeds.forEach((e=>{const t={channelId:e.channelId,subChannelId:e.messageFeedId,unreadCount:0,readToSegment:0,lastMentionSegment:0,lastSegment:0,isMentioned:!1,isDeleted:!1,createdAt:e.createdAt,updatedAt:e.updatedAt};Se(["subChannelUnreadInfo","get",t.subChannelId],t)}))})(r),Oo(n),e(n.messageFeeds[0])}))},Pc=e=>{const t=ve(),r=[Xe(t,"onSubChannelDeleted","message-feed.deleted",(async r=>{const n=await Nl(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&n.messageFeeds.forEach((e=>{(e=>{var t;const r=["subChannelUnreadInfo","get",e],n=null===(t=Ee(r))||void 0===t?void 0:t.data;n&&Se(r,Object.assign(Object.assign({},n),{isDeleted:!0}))})(e.subChannelId),el(e.channelId)})),Oo(n),e(n.messageFeeds[0])})),Xe(t,"local.message-feed.deleted","local.message-feed.deleted",(t=>e(t.messageFeeds[0])))];return()=>{r.forEach((e=>e()))}},Mc=async e=>{const t=ve();t.log("channel/markerSync");const{data:r}=await t.http.post("/api/v1/markers/sync",{deviceLastSyncAt:e}),{userEntityMarkers:n,userFeedMarkers:s,feedMarkers:i,userMarkers:a}=r,o=Bo(n),l=jo(s),c=t.cache&&Date.now();return t.cache&&Oo({userEntityMarkers:o,userFeedMarkers:l,feedMarkers:i,userMarkers:a},{cachedAt:c}),Je("local.feedMarker.fetched",{feedMarkers:i}),Je("local.channelMarker.fetched",{userEntityMarkers:o}),Je("local.subChannelMarker.fetched",{userFeedMarkers:l}),Je("local.userMarker.fetched",{userMarkers:a}),{data:r,hasMore:r.feedMarkers.length>0}},Fc=()=>{const e=ve();if(e.log("client/api/isUnreadCountEnabled",e.isUnreadCountEnabled),!e)throw new fe("There is no active client",8e5,"fatal");return!e.isUnreadCountEnabled&&(e.isUnreadCountEnabled=!0,e.emitter.emit("unreadCountEnabled",!0),!0)},Uc=e=>{const t=ve();return Xe(t,"feedMarker/onUserFeedMarkerUpdated","marker.userFeed-updated",(t=>{vl(t),e(t.feedMarkers[0])}))};let Nc=!1,Bc=[],jc=!1,$c=!0,qc=null;const Kc=e=>{null!=e&&(!qc||e.getTime()>qc.getTime())&&(qc=e)},Gc=async()=>{const{data:e}=await kl();null!=e&&Kc(new Date(e.lastSyncAt))};let Hc=[];const Vc=e=>{Hc=e},zc=e=>Hc.push(e),Wc=async()=>{if(!jc&&0!==Hc.length)try{jc=!0,Hc=[];const e=await Mc((null==qc?new Date:qc).toISOString()),t=e.data.userMarkers.reduce(((e,t)=>null==e||e.getTime()<new Date(t.lastSyncAt).getTime()?new Date(t.lastSyncAt):e),null);Kc(t),e.hasMore&&Hc.push("has_more")}catch(e){}finally{jc&&(jc=!1)}},Yc=()=>{Bc.length>0||Bc.push($l((()=>{Hc.push("resume")})),Dc((e=>{Ul(e)&&Hc.push("new message")})),wc((()=>Hc.push("subchannel is created"))),dc((()=>Hc.push("subchannel is deleted"))),Sc((()=>Hc.push("subchannel is joined"))),Tc((()=>Hc.push("subchannel is left"))),Oc((()=>Hc.push("subchannel is created"))),Pc((()=>setTimeout((()=>Hc.push("subchannel is deleted")),2e3))),Lc((()=>Hc.push("feed marker updated"))),(e=>{const t=ve();return Xe(t,"UserMarker/onUserMarkerSync","marker.user-sync",(t=>{const{userMarkers:r,userEntityMarkers:n,userFeedMarkers:s}=t,i=Mo(t,["userMarkers","userEntityMarkers","userFeedMarkers"]),a=Bo(n),o=jo(s);Oo(Object.assign({userMarkers:r,userEntityMarkers:a,userFeedMarker:o},i)),e(r[0])}))})((()=>Hc.push("feed marker updated"))),Uc((()=>Hc.push("feed marker updated"))))},Qc=()=>{Bc.forEach((e=>e())),Bc=[]},Xc=async()=>(await Gc(),zc("start syncing"),$c=!0,Nc=!0,Yc(),Qc),Jc=()=>{Nc=!1,Vc([]),Qc()};jl((async()=>{Nc&&await Wc()}),2e3);const Zc=()=>$c;let ed=[];const td=async(e,t,r)=>{const n=ve();let s;n.log("client/api/connectClient",Object.assign({apiKey:n.apiKey,sessionState:n.sessionState},e)),n.userId&&n.userId!==e.userId&&(await pc(),ed.forEach((e=>e())),ed=[]);const i=await _o();try{const{users:r}=await oc(Object.assign(Object.assign({},e),{displayName:(null==e?void 0:e.displayName)||e.userId,deviceId:(null==e?void 0:e.deviceId)||i})),l=r.find((t=>t.userId===e.userId));if(null==l)throw new fe(`${e.userId} has not been founded`,8e5,"error");if(l.isDeleted)return gc("userDeleted"),!1;if(l.isGlobalBanned)return gc("globalBan"),!1;a=n.ws,o=n.emitter,We.forEach((e=>{a.on(e,(t=>{o.emit(e,t)}))})),n.ws.once("connect",(()=>{n.ws.open()})),n.userId=l.userId,n.sessionHandler=t,s=n.accessTokenExpiryWatcher(t),Ge(l)}catch(e){throw ac("notLoggedIn"),e}var a,o;if(!0!==(null==r?void 0:r.disableRTE)&&async function(){await tt()}(),await(async()=>{var e;const t=await Jl();if(t===(null===(e=Ee(["MessagePreviewSetting"]))||void 0===e?void 0:e.data))return;Se(["MessagePreviewSetting"],t);const r=[],n=[];if("no-message-preview"===t){const e=we(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{ke(e),e.includes("MessagePreviewChannel")&&r.push(t.channelId),e.includes("MessagePreviewSubChannel")&&n.push(t.subChannelId)}))}else if("message-preview-not-include-deleted"===t){const e=we(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{(null==t?void 0:t.isDeleted)&&(ke(e),e.includes("MessagePreviewChannel")&&r.push(t.channelId),e.includes("MessagePreviewSubChannel")&&n.push(t.subChannelId))})),0!==r.length&&await Cl(r),0!==n.length&&await Xl(n)}})(),0===ed.length){ed.push(vc((e=>{gc("globalBan"),ed.forEach((e=>e())),s()})),(e=>{const t=ve();return Xe(t,"client/onTokenTerminated","tokenTerminated",e)})((e=>{gc(),ed.forEach((e=>e())),s()})),fc((e=>{e.userId===n.userId&&(gc("userDeleted"),ed.forEach((e=>e())),s())})),(e=>{const t=ve();return Xe(t,"client/onTokenExpired","tokenExpired",e)})((e=>{ac(e),pc(),ed.forEach((e=>e()))})),dc(bc),uc(bc),Yl(),(()=>{const e=Yo();return e.established(),Bl((t=>{"established"===t?e.established():e.handleTokenExpired()})),()=>{e.destroy()}})(),(()=>{const e=nl();return e.startSyncReadReceipt(),Bl((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})());const e=await Xc();ed.push(e)}return!0},rd=()=>{let e,t=!1;const r=ve();r.log("initiating access token renewal");const n=async n=>{const{userId:s,displayName:i}=Ke(),a={userId:s,displayName:i,authToken:n,deviceId:await _o()};"tokenExpired"===r.sessionState&&r.sessionHandler?await td(a,r.sessionHandler):await oc(a),t=!0,e&&clearTimeout(e)};return{renew:()=>{t?console.log("'renew' method can be called only once per renewal instance"):n()},renewWithAuthToken:e=>{t?console.log("'renewWithAuthToken' method can be called only once per renewal instance"):n(e)},unableToRetrieveAuthToken:()=>{e=setTimeout((()=>{var e;null===(e=r.sessionHandler)||void 0===e||e.sessionWillRenewAccessToken(rd())}),y)}}},nd=3e5,sd=e=>{const t=setInterval((()=>{const t=ve();if(!t.token)return;const{issuedAt:r,expiresAt:n}=t.token;if((e=>Date.now()>Date.parse(e)-nd)(n))return Je("tokenExpired","tokenExpired"),void ze((()=>e.sessionWillRenewAccessToken(rd())));(e=>{const{expiresAt:t,issuedAt:r}=e,n=Date.parse(t),s=Date.parse(r),i=Date.now();return i>s+.8*(n-s-nd)&&i<n})({expiresAt:n,issuedAt:r})&&e.sessionWillRenewAccessToken(rd())}),y);return()=>clearInterval(t)},id=e=>{const t=ve();return Xe(t,"channelMarker/onChannelMarkerFetched","local.channelMarker.fetched",(t=>{t.userEntityMarkers.forEach((t=>{e(t)}))}))},ad=e=>{const t=ve();return Xe(t,"subChannelMarker/onSubChannelMarkerFetched","local.subChannelMarker.fetched",(t=>{e(t.userFeedMarkers[0])}))},od=e=>{const t=ve();return Xe(t,"subChannelMarker/onSubChannelMarkerUpdated","local.subChannelMarker.updated",(t=>{e(t.userFeedMarkers)}))},ld=e=>{const t=ve();return Xe(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers)}))},cd=e=>{const t=ve();return Xe(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers[0])}))},dd=e=>{const t=ve();return Xe(t,"messageMarker/onMessageMarkerFetched","local.messageMarker.fetched",(t=>{e(t.contentMarkers[0])}))},ud=e=>{const t=ve();return Xe(t,"messageMarker/onMessageMarked","marker.marked-message",(t=>{var r,n,s;Oo(t);const i=we(["message","collection"]),{contentMarkers:a,feedMarkers:o}=t;if(i&&(null==i?void 0:i.length)>0&&(null==o?void 0:o.length)>0){const e=i.filter((e=>{var t,r;return(null===(r=null===(t=e.data)||void 0===t?void 0:t.query)||void 0===r?void 0:r.subChannelId)===o[0].feedId}));if(e.length>0&&(null==a?void 0:a.length)>0){(null!==(s=null===(n=null===(r=e[0].data)||void 0===r?void 0:r.data)||void 0===n?void 0:n.map((e=>Ee(["message","get",e]))).map((({data:e})=>e)).filter(Boolean))&&void 0!==s?s:[]).forEach((e=>{var t,r;const n=["messageMarker","get",de("messageMarker")({creatorId:e.creatorPrivateId,feedId:e.subChannelId,contentId:e.messageId})],s=null===(t=Ee(n))||void 0===t?void 0:t.data;if(!s)return;const i=a[0].feedId===s.feedId,o=a[0].readCount>s.readCount,l=(null===(r=a[0])||void 0===r?void 0:r.deliveredCount)>s.deliveredCount;if(i){const e=Object.assign(Object.assign({},s),{readCount:o?a[0].readCount:s.readCount,deliveredCount:l?a[0].deliveredCount:s.deliveredCount});Se(n,e)}}))}}e(t.contentMarkers[0])}))};const hd=e=>{if("object"!=typeof(t=e)||null===t)return e;var t;const r=Object.entries(e).map((([t,r])=>{const n=Object.getOwnPropertyDescriptor(e,t);return"function"==typeof(null==n?void 0:n.get)?[t,n.get.call(e)]:[t,r]}));return Object.fromEntries(r)};function fd(e,t){if(null==e||null==t)return e===t;if(e.constructor!==t.constructor)return!1;if(e instanceof Function)return e===t;if(e instanceof RegExp)return e===t;if(e===t||e.valueOf()===t.valueOf())return!0;if(Array.isArray(e)&&e.length!==t.length)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(!fd(e[r],t[r]))return!1;return!0}if(e instanceof Date)return!1;if(!(e instanceof Object))return!1;if(!(t instanceof Object))return!1;const r=Object.keys(e);return Object.keys(t).every((e=>-1!==r.indexOf(e)))&&r.every((r=>fd(e[r],t[r])))}const pd=(e,t,r,n,s,i)=>{const{forceDispatch:a,callbackDataSelector:o,callbackFilter:l}=Object.assign({forceDispatch:!1,callbackDataSelector:e=>e},i),{cache:c}=ve();let d;c||console.log("For using Live Object feature you need to enable Cache!");let u=!1;const h=[],f=e=>{const{data:r}=e,n=Mo(e,["data"]);l&&!l(r,d)||t(Object.assign({data:o(r)},n)),d=hd(r)};return h.push(...s.map((t=>t((t=>((t,n=!1)=>{e===t[r]&&(d&&!n&&fd(d,t)||f({loading:!1,data:t,origin:"event"}))})(t,a)))))),(()=>{const t=ie(n,e,!0);oe(t,(({error:e,data:t,loading:r,origin:n,cachedAt:s})=>{-5===s?(f({data:t,origin:n,loading:!1,error:new pe(g,800800,"error")}),u=!0,h.forEach((e=>e()))):u||f({loading:r,data:t,origin:n,error:e}),e&&h.forEach((e=>e()))}))})(),()=>{h.forEach((e=>e()))}};var gd=Object.freeze({__proto__:null,getActiveClient:ve,getActiveUser:Ke,setActiveUser:Ge,createClient:(e,t=At.SG,{debugSession:r="amity",apiEndpoint:n}={})=>{var s,i;const a=(e=>{const t=`${null==e?void 0:e.trim()}`.length>0&&!kt,r=St(e),n=(e,...n)=>{t&&r(e,n)};return n.__instance__=r,n})(r);a("client/api/createClient",{apiKey:e.replace(/.{5}$/g,"xxxxx"),apiRegion:t});const o=null!==(s=null==n?void 0:n.http)&&void 0!==s?s:_t("http",t),l=null!==(i=null==n?void 0:n.mqtt)&&void 0!==i?i:_t("mqtt",t),c=hn(o),d=(e=>{const t=Aa(e,{autoConnect:!1,reconnectionDelay:2e3,transports:["websocket"]});return t.on("disconnect",(e=>{"io server disconnect"===e&&t.connect()})),t})(o),h=xo(l),f=Qe(),p={version:`${u}`,apiKey:e,log:a,cache:{data:{}},http:c,ws:d,mqtt:h,emitter:f,sessionState:"notLoggedIn",accessTokenExpiryWatcher:sd,sessionHandler:undefined,hasPermission:tc,validateUrls:rc,validateTexts:nc,getFeedSettings:sc,getSocialSettings:Zl,getMessagePreviewSetting:Jl,use:()=>be(p),isUnreadCountEnabled:!1,getMarkerSyncConsistentMode:Zc};try{const t=ve();if(t.apiKey===e)return t;be(p)}catch(e){be(p)}return p},login:td,logout:pc,isConnected:()=>{var e,t;const r=ve();return r.log("client/api/isConnected",r),!!(r.userId&&(null===(t=String(null===(e=r.http.defaults.headers.common)||void 0===e?void 0:e.Authorization))||void 0===t?void 0:t.length)&&r.ws.connected)},getFeedSettings:sc,renewal:rd,markerSync:Mc,enableUnreadCount:Fc,onConnectionError:yc,onClientDisconnected:e=>yc((({code:t})=>{800211===t&&e()})),onClientBanned:vc,onSessionStateChange:Bl,getTotalUnreadCount:e=>{const{_id:t}=Ke();if(!t)throw new fe("The _id has not been defined in ActiveUser",8e5,"error");return pd(t,e,"userId",(async()=>{const{data:e,cachedAt:t}=await kl();return{data:e,cachedAt:t}}),[cd],{callbackDataSelector:e=>{var t;return null!==(t=null==e?void 0:e.unreadCount)&&void 0!==t?t:0}})},getUserUnread:e=>{const{_id:t}=Ke();if(!t)throw new fe("The _id has not been defined in ActiveUser",8e5,"error");const{log:r,cache:n}=ve();n||console.log("For using Live Object feature you need to enable Cache!");r(`liveUserUnread(tmpid: ${Date.now()}) > listen`);const s=[];let i,a=!1;const o=t=>{const{data:r}=t,n=r?{unreadCount:r.unreadCount,isMentioned:r.isMentioned}:void 0;i=n?hd(n):n,e({data:n?Object.assign(Object.assign({},n),{hasMentioned:n.isMentioned}):n,loading:t.loading,error:t.error})};return s.push(ld((e=>(e=>{var r;const n=e.filter((e=>t===e.userId)),s=n.reduce(((e,t)=>null==e||new Date(t.lastSyncAt).getTime()>new Date(e.lastSyncAt).getTime()?t:e),null),a={unreadCount:null!==(r=null==s?void 0:s.unreadCount)&&void 0!==r?r:0,isMentioned:n.some((e=>!!e.isMentioned))};fd(i,a)||o({loading:!1,data:a})})(e)))),(()=>{const e=ie(kl);oe(e,(({error:e,data:t,loading:r,origin:n,cachedAt:i})=>{!function(e){return null!=e&&null!=e}(t)?o({loading:r,data:void 0,origin:n,error:e}):(-5===i?(o({data:t,origin:n,loading:!1,error:new pe(g,800800,"error")}),a=!0,s.forEach((e=>e()))):a||o({loading:r,data:t,origin:n,error:e}),e&&s.forEach((e=>e())))}))})(),()=>{s.forEach((e=>e()))}},getMarkerSyncEvents:()=>Hc,setMarkerSyncEvents:Vc,pushMarkerSyncEvent:zc,markerSyncTrigger:Wc,startMarkerSync:Xc,startUnreadSync:async()=>{await Gc(),zc("start syncing"),Fc(),$c=!1,Nc=!0,Yc()},stopUnreadSync:Jc,stopUnreadSyncing:()=>(console.warn("`stopUnreadSyncing` has been deprecated, please use `stopUnreadSync` instead"),Jc()),getMarkerSyncConsistentMode:Zc});const md=async e=>{const t=ve();let r={};if(e){const{token:t,limit:n}=e;r={limit:n,token:t}}t.log("user/queryBlockedUsers");const{data:n}=await t.http.get("/api/v4/me/user-blocks",{params:r}),{paging:s}=n,i=Mo(n,["paging"]),{users:a}=i,o=t.cache&&Date.now();if(t.cache){Oo(i,{cachedAt:o});Se(["blockedUsers","query",r],{users:a.map(de("user")),paging:s})}const{next:l,previous:c,total:d}=s,u=Z(l);return{data:a,prevPage:Z(c),nextPage:u,total:d,cachedAt:o}};md.locally=(e={})=>{var t,r,n;const s=ve();if(s.log("user/queryBlockedUsers.locally"),!s.cache)return;let i={};if(e){const{token:t,limit:r}=e;i={token:t,limit:r}}const a=["blockedUsers","query",i],{data:o,cachedAt:l}=null!==(t=Ee(a))&&void 0!==t?t:{},c=null!==(r=null==o?void 0:o.users.map((e=>Ee(["user","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[],d=Z(null==o?void 0:o.paging.next),u=Z(null==o?void 0:o.paging.previous);return c.length>0&&c.length===(null===(n=null==o?void 0:o.users)||void 0===n?void 0:n.length)?{data:c,nextPage:d,prevPage:u,total:null==o?void 0:o.paging.total,cachedAt:l}:void 0};const yd=(e,t,r)=>{const{log:n,cache:s}=ve();s||console.log(p);const i=Date.now();n(`getBlockedUsers(tmpid: ${i}) > listen`);const{limit:a}=e,o=null!=a?a:h,{policy:l=f}=null!=r?r:{},c=[],d=["blockedUsers","collection",{}],u=(e=!1)=>{var r,n;const s=null===(r=Ee(d))||void 0===r?void 0:r.data,i=null!==(n=null==s?void 0:s.data)&&void 0!==n?n:[];if(!e&&i.length>0&&!(null==s?void 0:s.params.page))return;const a=ie(md,{limit:o,token:X(e||null==s?void 0:s.params.page,"afterbeforeraw")});oe(a,(({data:e,loading:r,error:n,nextPage:s,total:a})=>{const o={loading:r,error:n,params:{page:s,total:a},data:i};e&&(o.data=[...new Set([...i,...e.map(de("user"))])]),Se(d,o),(e=>{var r,n;const s=null!==(r=e.data.map((e=>Ee(["user","get",e]))).filter(Boolean).map((({data:e})=>il.user(e))))&&void 0!==r?r:[];t({onNextPage:u,data:s,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading,error:e.error})})(o)}),ae(l,b))};return c.push((()=>{})),u(!0),()=>{n(`getCategories(tmpid: ${i}) > dispose`),c.forEach((e=>e())),ke(d)}},vd=(e,t)=>{const r=ve();return Xe(r,e,e,(e=>{var n,s;if(r.cache){Oo(e);[...null!==(n=we(["followers","query"]))&&void 0!==n?n:[],...null!==(s=we(["followings","query"]))&&void 0!==s?s:[]].filter((({key:t})=>t[2].userId===e.follows[0].from||t[2].userId===e.follows[0].to)).forEach((({key:e,data:t})=>Ce(e,t,{cachedAt:-1}))),t(e.follows[0])}else t(e.follows[0])}))},bd=e=>vd("follow.created",e),wd=e=>vd("follow.unfollowed",e),Ed=e=>vd("follow.followerDeleted",e),Sd=e=>vd("follow.requested",e),Td=e=>vd("follow.requestCanceled",e),Cd=e=>vd("follow.accepted",e),kd=e=>vd("follow.requestDeclined",e),Ad=async e=>{var t,r;const n=ve();n.log("follow/getFollowInfo",e);const{data:s}=await n.http.get(n.userId===e?"/api/v4/me/followInfo":`/api/v5/users/${e}/followInfo`),i=n.cache&&Date.now(),a="follows"in s?Object.assign(Object.assign({},s.followCounts[0]),{status:null===(r=null===(t=s.follows)||void 0===t?void 0:t[0])||void 0===r?void 0:r.status}):s.followCounts[0];return n.cache&&Se(["followInfo","get",e],a,{cachedAt:i}),{data:a,cachedAt:i}};Ad.locally=e=>{const t=ve();if(t.log("follow/getFollowInfo.locally",e),!t.cache)return;const r=Ee(["followInfo","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const Id=e=>{const t=async t=>{const[{data:r},{data:n}]=await Promise.all([Ad(t.from),Ad(t.to)]);e(r),e(n)},r=[vd("follow.created",t),vd("follow.requested",t),vd("follow.accepted",t),vd("follow.unfollowed",t),vd("follow.requestCanceled",t),vd("follow.requestDeclined",t),vd("follow.followerDeleted",t)];return()=>{r.forEach((e=>e()))}},_d=async(e,t)=>{const r=ve();r.log(`follow/queryF${e.substring(1)}`,t);const{userId:n,page:s}=t,i=Mo(t,["userId","page"]),{data:a}=await r.http.get(r.userId===n?`/api/v4/me/${e}`:`/api/v4/users/${n}/${e}`,{params:Object.assign(Object.assign({},i),{token:X(s,"afterbeforeraw")})}),{paging:o}=a,l=Mo(a,["paging"]),{follows:c}=l,d=r.cache&&Date.now();if(r.cache){Oo(l,{cachedAt:d});const t=["follow","query",Object.assign(Object.assign({},i),{userId:n,options:Object.assign({},s),type:e})];Se(t,{follows:c.map(de("follow")),paging:o})}const u=Z(o.next);return{data:c,cachedAt:d,prevPage:Z(o.previous),nextPage:u}};_d.locally=(e,t)=>{var r,n;const s=ve();if(s.log(`follow/queryF${e.substring(1)}.locally`,t),!s.cache)return;const{page:i}=t,a=Mo(t,["page"]),o=["follow","query",Object.assign(Object.assign({},a),{options:Object.assign({},i),type:e})],{data:l,cachedAt:c}=null!==(r=Ee(o))&&void 0!==r?r:{};if(!(null==l?void 0:l.follows.length))return;const d=l.follows.map((e=>Ee(["follow","get",e]))).filter(Boolean).map((({data:e})=>e)),u=Z(null==l?void 0:l.paging.previous),h=Z(null==l?void 0:l.paging.next);return d.length===(null===(n=null==l?void 0:l.follows)||void 0===n?void 0:n.length)?{data:d,cachedAt:c,prevPage:u,nextPage:h}:void 0};const Rd=async e=>_d("followers",e);Rd.locally=e=>_d.locally("followers",e);const Ld=async e=>_d("following",e);Ld.locally=e=>_d.locally("following",e);var Dd=Object.freeze({__proto__:null,blockUser:async e=>{const t=ve();t.log("user/blockUser",e);const{data:r}=await t.http.post(`/api/v4/me/user-blocks/${e}`),n=t.cache&&Date.now(),{follows:s,followCounts:i}=r,a={follows:s};return t.cache&&(Oo(a,{cachedAt:n}),Ce(["followInfo","get",e],i[0],{cachedAt:n})),Je("follow.unfollowed",a),r},unBlockUser:async e=>{const t=ve();t.log("user/unBlockUser",e);const{data:r}=await t.http.delete(`/api/v4/me/user-blocks/${e}`),n=t.cache&&Date.now(),{follows:s,followCounts:i}=r,a={follows:s};return t.cache&&(Oo(a,{cachedAt:n}),Ce(["followInfo","get",e],i[0],{cachedAt:n})),Je("follow.created",a),r},getBlockedUsers:(e,t,r)=>(console.log("Deprecation Notice: UserRepository.Relationship.getBlockedUsers will be deprecated on 9th June 2023, please use UserRepository.getBlockedUsers instead."),yd(e,t,r)),follow:async e=>{const t=ve();t.log("follow/follow",e);const{data:r}=await t.http.post(`/api/v4/me/following/${e}`),n=t.cache&&Date.now();return t.cache&&Oo(r,{cachedAt:n}),Je("accepted"===r.follows[0].status?"follow.created":"follow.requested",r),{data:r.follows[0],cachedAt:n}},unfollow:async e=>{const t=ve();t.log("follow/unfollow",e);const{data:r}=await t.http.delete(`/api/v4/me/following/${e}`);return t.cache&&Oo(r),Je("follow.unfollowed",r),!0},acceptFollower:async e=>{const t=ve();t.log("follow/acceptFollower",e);const{data:r}=await t.http.post(`/api/v4/me/followers/${e}`);return t.cache&&Oo(r),Je("follow.accepted",r),!0},acceptMyFollower:async e=>{const t=ve();t.log("follow/acceptMyFollower",e);const{data:r}=await t.http.post(`/api/v4/me/followers/${e}`);return t.cache&&Oo(r),Je("follow.accepted",r),!0},declineFollower:async e=>{const t=ve();t.log("follow/declineFollower",e);const{data:r}=await t.http.delete(`/api/v4/me/followers/${e}`);return t.cache&&Oo(r),Je("follow.requestDeclined",r),!0},declineMyFollower:async e=>{const t=ve();t.log("follow/declineMyFollower",e);const{data:r}=await t.http.delete(`/api/v4/me/followers/${e}`);return t.cache&&Oo(r),Je("follow.requestDeclined",r),!0},onUserFollowed:bd,onUserUnfollowed:wd,onFollowerDeleted:Ed,onFollowerRequested:Sd,onFollowRequestCanceled:Td,onFollowRequestAccepted:Cd,onFollowRequestDeclined:kd,onFollowInfoUpdated:Id,observeFollowInfo:(e,t,r="cache_then_server")=>{const{log:n}=ve(),s=Date.now();n(`observeFollowInfo(tmpid: ${s}) > listen`);const i=(e,r)=>{var n,s;if(t instanceof Function)return t(e);"onFetch"!==r&&(null===(n=t.onEvent)||void 0===n||n.call(t,r,e)),null===(s=t[r])||void 0===s||s.call(t,e)},a=[];return a.push(Id((t=>((t,r)=>{var n;(null===(n=t.data)||void 0===n?void 0:n.userId)===e&&i(t,r)})({data:t,loading:!1,origin:"event"},"onUpdate")))),oe(ie(Ad,e),(e=>(e.data||e.error)&&i(e,"onFetch")),ae(r)),()=>{n(`observeFollowInfo(tmpid: ${s}) > dispose`),a.forEach((e=>e()))}},observeFollowers:(e,t)=>{const{log:r}=ve(),n=Date.now();r(`observeFollowers(tmpid: ${n}) > listen`);const s=[],i=(e,r)=>{var n,s;if(t instanceof Function)return t(e);null===(n=t.onEvent)||void 0===n||n.call(t,r,e),null===(s=t[r])||void 0===s||s.call(t,e)};return s.push(Sd((e=>i(e,"onRequested"))),Cd((e=>i(e,"onAccepted"))),kd((e=>i(e,"onDeclined"))),Td((e=>i(e,"onCanceled"))),bd((e=>i(e,"onFollowed"))),wd((e=>i(e,"onUnfollowed"))),Ed((e=>i(e,"onDeleted")))),()=>{r(`observeFollowers(tmpid: ${n}) > dispose`),s.forEach((e=>e()))}},observeFollowings:(e,t)=>{const{log:r}=ve(),n=Date.now();r(`observeFollowings(tmpid: ${n}) > listen`);const s=[],i=(e,r)=>{var n,s;if(t instanceof Function)return t(e);null===(n=t.onEvent)||void 0===n||n.call(t,r,e),null===(s=t[r])||void 0===s||s.call(t,e)};return s.push(Sd((e=>i(e,"onRequested"))),Cd((e=>i(e,"onAccepted"))),kd((e=>i(e,"onDeclined"))),Td((e=>i(e,"onCanceled"))),bd((e=>i(e,"onFollowed"))),wd((e=>i(e,"onUnfollowed"))),Ed((e=>i(e,"onDeleted")))),()=>{r(`observeFollowings(tmpid: ${n}) > dispose`),s.forEach((e=>e()))}},getFollowers:(e,t,r)=>{const{log:n,cache:s}=ve();s||console.log("For using Live Collection feature you need to enable Cache!");const i=Date.now();n(`getFollowers(tmpid: ${i}) > listen`);const{limit:a}=e,o=Mo(e,["limit"]),l=null!=a?a:h,{policy:c=f}=null!=r?r:{},d=[],u=["follow","collection",{userId:e.userId,type:"follower"}],p=r=>{var n,s;let i=null!==(n=r.data.map((e=>Ee(["follow","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];e.status&&"all"!==e.status&&(i=Ae(i,"status",e.status)),t({onNextPage:m,data:i,hasNextPage:!!(null===(s=r.params)||void 0===s?void 0:s.page),loading:r.loading,error:r.error})},g=t=>r=>{var n;const s=null===(n=Ee(u))||void 0===n?void 0:n.data;e.userId===r.to&&s&&(["onDeclined","onCanceled","onUnfollowed","onDeleted"].includes(t)?s.data=s.data.filter((e=>e!==de("follow")(r))):["onRequested","onAccepted","onFollowed"].includes(t)&&(s.data=[...new Set([de("follow")(r),...s.data])]),Se(u,s),p(s))},m=(e=!1)=>{var t,r,n,s;const i=null===(t=Ee(u))||void 0===t?void 0:t.data,a=null!==(r=null==i?void 0:i.data)&&void 0!==r?r:[];if(!e&&a.length>0&&!(null===(n=null==i?void 0:i.params)||void 0===n?void 0:n.page))return;const d=ie(Rd,Object.assign(Object.assign({},o),{page:null!==(s=e||null==i?void 0:i.params.page)&&void 0!==s?s:{limit:l}}));oe(d,(({data:e,error:t,loading:r,nextPage:n})=>{const s={loading:r,error:t,params:{page:n},data:a};e&&(s.data=[...new Set([...a,...e.map(de("follow"))])]),Se(u,s),p(s)}),ae(c))};return d.push(Sd(g("onRequested")),Cd(g("onAccepted")),kd(g("onDeclined")),Td(g("onCanceled")),bd(g("onFollowed")),wd(g("onUnfollowed")),Ed(g("onDeleted"))),m(!0),()=>{n(`getFollowers(tmpid: ${i}) > dispose`),d.forEach((e=>e()))}},getFollowings:(e,t,r)=>{const{log:n,cache:s}=ve();s||console.log("For using Live Collection feature you need to enable Cache!");const i=Date.now();n(`getFollowings(tmpid: ${i}) > listen`);const{limit:a}=e,o=Mo(e,["limit"]),l=null!=a?a:h,{policy:c=f}=null!=r?r:{},d=[],u=["follow","collection",{userId:e.userId,type:"following"}],p=r=>{var n,s;let i=null!==(n=r.data.map((e=>Ee(["follow","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];e.status&&"all"!==e.status&&(i=Ae(i,"status",e.status)),t({onNextPage:m,data:i,hasNextPage:!!(null===(s=r.params)||void 0===s?void 0:s.page),loading:r.loading,error:r.error})},g=t=>r=>{var n;const s=null===(n=Ee(u))||void 0===n?void 0:n.data;e.userId===r.from&&s&&(["onDeclined","onCanceled","onUnfollowed","onDeleted"].includes(t)?s.data=s.data.filter((e=>e!==de("follow")(r))):["onRequested","onAccepted","onFollowed"].includes(t)&&(s.data=[...new Set([de("follow")(r),...s.data])]),Se(u,s),p(s))},m=(e=!1)=>{var t,r,n,s;const i=null===(t=Ee(u))||void 0===t?void 0:t.data,a=null!==(r=null==i?void 0:i.data)&&void 0!==r?r:[];if(!e&&a.length>0&&!(null===(n=null==i?void 0:i.params)||void 0===n?void 0:n.page))return;const d=ie(Ld,Object.assign(Object.assign({},o),{page:null!==(s=e||null==i?void 0:i.params.page)&&void 0!==s?s:{limit:l}}));oe(d,(({data:e,error:t,loading:r,nextPage:n})=>{const s={loading:r,error:t,params:{page:n},data:a};e&&(s.data=[...new Set([...a,...e.map(de("follow"))])]),Se(u,s),p(s)}),ae(c))};return d.push(Sd(g("onRequested")),Cd(g("onAccepted")),kd(g("onDeclined")),Td(g("onCanceled")),bd(g("onFollowed")),wd(g("onUnfollowed")),Ed(g("onDeleted"))),m(!0),()=>{n(`getFollowings(tmpid: ${i}) > dispose`),d.forEach((e=>e()))}},getFollowInfo:(e,t)=>pd(e,t,"userId",Ad,[Id],{forceDispatch:!0}),getMyFollowInfo:e=>{const{userId:t}=Ke();return pd(t,e,"userId",Ad,[Id],{forceDispatch:!0})}});const xd=async e=>{const t=ve();t.log("user/getUsers",e);const r=e.map((e=>encodeURIComponent(e))),{data:n}=await t.http.get("/api/v3/users/list",{params:{userIds:r}}),s=t.cache&&Date.now();return t.cache&&Oo(n,{cachedAt:s}),Je("user.fetched",n),{data:n.users.map((e=>il.user(e))),cachedAt:s}};xd.locally=e=>{var t;const r=ve();if(r.log("user/getUsers.locally",e),!r.cache)return;const n=e.map((e=>Ee(["user","get",e]))).filter(Boolean),s=n.map((({data:e})=>il.user(e))),i=null===(t=n.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==n?void 0:n.length)<e.length?void 0:{data:s,cachedAt:i.cachedAt}};const Od=e=>hc("user.updated",e),Pd=e=>hc("user.flagged",e),Md=e=>hc("user.unflagged",e),Fd=e=>hc("user.flagCleared",e),Ud=e=>hc("user.fetched",e),Nd=async e=>{const t=ve();let r;t.log("user/getUser",e),ql("user",e);try{r=(await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`)).data}catch(t){throw C(null==t?void 0:t.code)&&Po("user",e),t}const n=t.cache&&Date.now();t.cache&&Oo(r,{cachedAt:n});const{users:s}=r;return Je("user.fetched",r),{data:s.find((t=>t.userId===e)),cachedAt:n}};Nd.locally=e=>{const t=ve();if(t.log("user/getUser.locally",e),!t.cache)return;const r=Ee(["user","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const Bd=async(e={})=>{const t=ve();t.log("user/queryUsers",e);const{page:r,limit:n=10,displayName:s,filter:i="all",sortBy:a="displayName"}=e,o=Mo(e,["page","limit","displayName","filter","sortBy"]),{data:l}=await t.http.get("/api/v3/users",{params:Object.assign(Object.assign({},o),{keyword:s,filter:i,sortBy:a,options:r?{token:r}:{limit:n}})}),{paging:c}=l,d=Mo(l,["paging"]),{users:u}=d,h=t.cache&&Date.now();if(t.cache){Oo(d,{cachedAt:h});const t=["user","query",Object.assign(Object.assign({},e),{options:{limit:n,token:r}})];Se(t,{users:u.map(de("user")),paging:c})}return Je("user.fetched",l),{data:u,cachedAt:h,paging:c}};Bd.locally=(e={})=>{var t,r,n;const s=ve();if(s.log("user/queryUsers.locally",e),!s.cache)return;const{limit:i=10,page:a}=null!=e?e:{},o=["user","query",Object.assign(Object.assign({},e),{options:{limit:i,token:a}})],{data:l,cachedAt:c}=null!==(t=Ee(o))&&void 0!==t?t:{},d=null!==(r=null==l?void 0:l.users.map((e=>Ee(["user","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];return d.length>0&&d.length===(null===(n=null==l?void 0:l.users)||void 0===n?void 0:n.length)?{data:d,cachedAt:c,paging:null==l?void 0:l.paging}:void 0};const jd=(e,t)=>{let r=Ie(e,"displayName",t.displayName);switch(t.sortBy){case"firstCreated":r=r.sort(Fe);break;case"lastCreated":r=r.sort(Ne);break;default:r=r.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Pe)}return r},$d=(e,t,r)=>{const{log:n,cache:s}=ve();s||console.log(p);const i=Date.now();n(`liveUsers(tmpid: ${i}) > listen`);const{limit:a}=e,o=Mo(e,["limit"]),l=null!=a?a:h,{policy:c=f}=null!=r?r:{},d=[],u=["user","collection",Ao()],g=(r,n=!1)=>{var s,i;const a=null!==(s=r.data.map((e=>Ee(["user","get",e]))).filter(Boolean).map((({data:e})=>il.user(e))))&&void 0!==s?s:[];t({onNextPage:y,data:n?jd(a,e):a,hasNextPage:!!(null===(i=r.params)||void 0===i?void 0:i.page),loading:r.loading,error:r.error})},m=e=>e=>{var t;const r=null===(t=Ee(u))||void 0===t?void 0:t.data;r&&(r.data=[...new Set([e.userId,...r.data])],Se(u,r),g(r,!0))},y=(e=!1)=>{var t,r;const n=null===(t=Ee(u))||void 0===t?void 0:t.data,s=null!==(r=null==n?void 0:n.data)&&void 0!==r?r:[];if(!e&&s.length>0&&!(null==n?void 0:n.params.page))return;const i=e?{limit:l}:{page:null==n?void 0:n.params.page},a=ie(Bd,Object.assign(Object.assign({},o),i));oe(a,(({data:t,error:r,loading:n,paging:i})=>{const a={loading:n,error:r,params:{page:null==i?void 0:i.next},data:s};t&&(a.data=e?t.map(de("user")):[...new Set([...s,...t.map(de("user"))])]),Se(u,a),g(a)}),ae(c))};return d.push(Od(m()),fc(m()),Pd(m()),Md(m()),Fd(m())),y(!0),()=>{n(`liveUsers(tmpid: ${i}) > dispose`),d.forEach((e=>e()))}},qd=async e=>{const t=ve();let r;t.log("user/getUser",e),ql("user",e);try{r=(await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`)).data}catch(t){throw C(null==t?void 0:t.code)&&Po("user",e),t}const n=t.cache&&Date.now();t.cache&&Oo(r,{cachedAt:n});const{users:s}=r;return Je("user.fetched",r),{data:il.user(s.find((t=>t.userId===e))),cachedAt:n}};qd.locally=e=>{const t=ve();if(t.log("user/getUser.locally",e),!t.cache)return;const r=Ee(["user","get",e]);return r?{data:il.user(r.data),cachedAt:r.cachedAt}:void 0};const Kd=async({viewId:e,viewedType:t,limit:r,token:n})=>{const s=ve(),i={};n?i.token=n:i.limit=r;const a=`/api/v1/analytics/views/${"post"===t?"posts":"stories"}/${e}/users`,o=await s.http.get(a,{params:i});return Oo(o.data),o.data};var Gd=Object.freeze({__proto__:null,Relationship:Dd,getUserByIds:xd,updateUser:async(e,t)=>{const r=ve();r.log("user/updateUser",e,t);const{data:n}=await r.http.put("/api/v3/users/",Object.assign(Object.assign({userId:e},t),{createNewUserWhenNotFound:!1})),s=r.cache&&Date.now();r.cache&&Oo(n,{cachedAt:s});const{users:i}=n;return Je("user.updated",n),{data:i.find((t=>t.userId===e)),cachedAt:s}},flagUser:async e=>{const t=ve();t.log("user/flagUser",e);const{data:r}=await t.http.post(`api/v4/me/flags/${encodeURIComponent(e)}`);return t.cache&&Oo(r),Je("user.flagged",r),!!r},unflagUser:async e=>{const t=ve();t.log("user/unflag",e);const{data:r}=await t.http.delete(`/api/v4/me/flags/${encodeURIComponent(e)}`);return t.cache&&Oo(r),Je("user.unflagged",r),!!r},isUserFlaggedByMe:async e=>{const t=ve();t.log("user/isUserFlaggedByMe",e);const{data:{isFlagByMe:r}}=await t.http.get(`/api/v3/users/${e}/isFlagByMe`);return r},onUserUpdated:Od,onUserDeleted:fc,onUserFlagged:Pd,onUserUnflagged:Md,onUserFlagCleared:Fd,getUser:(e,t)=>pd(e,(e=>t(Object.assign(Object.assign({},e),{data:e.data?il.user(e.data):e.data}))),"userId",Nd,[Ud,Od,fc,Pd,Md,Fd]),getUsers:$d,observeUser:(e,t)=>{const{log:r}=ve(),n=Date.now();r(`observeUser(tmpid: ${n}) > listen`);const s=(r,n)=>{var s,i,a;if((null===(s=r.data)||void 0===s?void 0:s.userId)!==e)return;const o=Object.assign(Object.assign({},r),{data:il.user(r.data)});if(t instanceof Function)return t(o);"onFetch"!==n&&(null===(i=t.onEvent)||void 0===i||i.call(t,n,o)),null===(a=t[n])||void 0===a||a.call(t,o)},i=[];return i.push(Od((e=>s({data:e,loading:!1,origin:"event"},"onUpdate"))),fc((e=>s({data:e,loading:!1,origin:"event"},"onDelete"))),Pd((e=>s({data:e,loading:!1,origin:"event"},"onFlagged"))),Md((e=>s({data:e,loading:!1,origin:"event"},"onUnflagged"))),Fd((e=>s({data:e,loading:!1,origin:"event"},"onFlagCleared")))),oe(ie(qd,e),(e=>e.data&&s(e,"onFetch"))),()=>{r(`observeUser(tmpid: ${n}) > dispose`),i.forEach((e=>e()))}},getBlockedUsers:yd,searchUserByDisplayName:(e,t,r)=>$d(Object.assign(Object.assign({},e),{filter:"all"}),t,r),getViewedUsers:(e,t)=>{const{log:r,cache:n}=ve(),s=["postViewedUsers","collection",{postId:e.postId}];n||console.log(p);const i=Date.now();r(`getViewedUsers(tmpid: ${i}) > listen`);const{limit:a,postId:o}=e,l=(e=!1)=>{var r,n,i;const c=null===(r=Ee(s))||void 0===r?void 0:r.data,d=null!==(n=null==c?void 0:c.data)&&void 0!==n?n:[];if(!e&&d.length>0&&!(null==c?void 0:c.params.page))return;const u=ie(Kd,{viewId:o,viewedType:"post",limit:a||10,token:e||null===(i=null==c?void 0:c.params.page)||void 0===i?void 0:i.next});oe(u,(e=>{var r,n,i,a,o;let c=null!==(i=null===(n=null===(r=Ee(s))||void 0===r?void 0:r.data)||void 0===n?void 0:n.data)&&void 0!==i?i:[];(null===(a=e.data)||void 0===a?void 0:a.users)&&(c=[...new Set([...c,...e.data.users.map((({userId:e})=>e))])]);const d={loading:e.loading,params:{page:null===(o=e.data)||void 0===o?void 0:o.paging},data:c||[]};Se(s,d),(e=>{var r,n;let s=[];(null==e?void 0:e.data)&&(s=e.data.map((e=>Ee(["user","get",e]))).filter(Boolean).map((e=>null==e?void 0:e.data))||[]),t({onNextPage:l,data:s,hasNextPage:!!(null===(n=null===(r=e.params)||void 0===r?void 0:r.page)||void 0===n?void 0:n.next),loading:e.loading||!1})})(d)}),ae(f,b))};return l(!0),()=>{r(`getViewedUsers(tmpid: ${i}) > dispose`),ke(s)}},getReachedUsers:(e,t)=>{let r=(e=!1)=>{};const{log:n,cache:s}=ve(),i=["viewedUsers","collection",{viewId:e.viewId,viewedType:e.viewedType}];s||console.log(p);const a=Date.now();n(`getReachUsers(tmpid: ${a}) > listen`);const{limit:o,viewId:l,viewedType:c}=e;return r=(e=!1)=>{var n,s,a;const d=null===(n=Ee(i))||void 0===n?void 0:n.data,u=null!==(s=null==d?void 0:d.data)&&void 0!==s?s:[];if(!e&&u.length>0&&!(null==d?void 0:d.params.page))return;const h=ie(Kd,{viewId:l,viewedType:c,limit:o||10,token:e||null===(a=null==d?void 0:d.params.page)||void 0===a?void 0:a.next});oe(h,(e=>{var n,s,a,o,l;let c=null!==(a=null===(s=null===(n=Ee(i))||void 0===n?void 0:n.data)||void 0===s?void 0:s.data)&&void 0!==a?a:[];(null===(o=e.data)||void 0===o?void 0:o.users)&&(c=[...new Set([...c,...e.data.users.map((({userId:e})=>e))])]);const d={loading:e.loading,params:{page:null===(l=e.data)||void 0===l?void 0:l.paging},data:c||[]};Se(i,d),(e=>{var n,s;let i=[];(null==e?void 0:e.data)&&(i=e.data.map((e=>Ee(["user","get",e]))).filter(Boolean).map((e=>null==e?void 0:e.data))||[]),t({onNextPage:r,data:i,hasNextPage:!!(null===(s=null===(n=e.params)||void 0===n?void 0:n.page)||void 0===s?void 0:s.next),loading:e.loading||!1})})(d)}),ae(f,b))},r(!0),()=>{n(`getReachUsers(tmpid: ${a}) > dispose`),ke(i)}}});const Hd=async e=>{const t=ve();t.log("file/getFile",e);const{data:r}=await t.http.get(`/api/v3/files/${e}`),n=t.cache&&Date.now();return t.cache&&Oo({files:[r]},{cachedAt:n}),{data:r,cachedAt:n}};Hd.locally=e=>{const t=ve();if(t.log("file/getFile.locally",e),!t.cache)return;const r=Ee(["file","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const Vd=async(e,t,r)=>{const n=ve();if(n.log("file/uploadVideo",e),!e.getAll("files").length)throw new Error("The formData object must have a `files` key.");t&&e.append("feedType",t);const s="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await n.http.post("/api/v4/videos",e,{headers:s,onUploadProgress({loaded:e,total:t=100}){r&&r(Math.round(100*e/t))}}),a=n.cache&&Date.now();return n.cache&&Oo({files:i},{cachedAt:a}),{data:i,cachedAt:a}},zd=async(e,t)=>{const r=ve();if(r.log("file/uploadImage",e),!e.getAll("files").length)throw new Error("The formData object must have a `files` key.");const n="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:s}=await r.http.post("/api/v4/images",e,{headers:n,onUploadProgress({loaded:e,total:r=100}){t&&t(Math.round(100*e/r))}}),i=r.cache&&Date.now();return r.cache&&Oo({files:s},{cachedAt:i}),{data:s,cachedAt:i}};var Wd=Object.freeze({__proto__:null,getFile:Hd,uploadFile:async(e,t)=>{const r=ve();if(r.log("file/uploadFile",e),!e.getAll("files").length)throw new Error("The formData object must have a `files` key.");const n="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:s}=await r.http.post("/api/v4/files",e,{headers:n,onUploadProgress({loaded:e,total:r=100}){t&&t(Math.round(100*e/r))}}),i=r.cache&&Date.now();return r.cache&&Oo({files:s},{cachedAt:i}),{data:s,cachedAt:i}},deleteFile:async e=>{const t=ve();return t.log("file/deleteFile",e),await t.http.delete(`/api/v3/files/${e}`),ke(["file","get",e],!0),{success:!0}},fileUrlWithSize:(e,t)=>`${e}?size=${t}`,uploadVideo:Vd,uploadImage:zd,createImage:async(e,t)=>{const r=ve();if(r.log("file/createImage",e),!e.getAll("files").length)throw new Error("The formData object must have a `files` key.");const n="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:s}=await r.http.post("/api/v4/images",e,{headers:n,onUploadProgress({loaded:e,total:r=100}){t&&t(Math.round(100*e/r))}}),i=r.cache&&Date.now();return r.cache&&Oo({files:s},{cachedAt:i}),{data:s,cachedAt:i}},createFile:async(e,t)=>{const r=ve();if(r.log("file/createFile",e),!e.getAll("files").length)throw new Error("The formData object must have a `files` key.");const n="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:s}=await r.http.post("/api/v4/files",e,{headers:n,onUploadProgress({loaded:e,total:r=100}){t&&t(Math.round(100*e/r))}}),i=r.cache&&Date.now();return r.cache&&Oo({files:s},{cachedAt:i}),{data:s,cachedAt:i}},createVideo:async(e,t,r)=>{const n=ve();if(n.log("file/createVideo",e),!e.getAll("files").length)throw new Error("The formData object must have a `files` key.");t&&e.append("feedType",t);const s="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await n.http.post("/api/v4/videos",e,{headers:s,onUploadProgress({loaded:e,total:t=100}){r&&r(Math.round(100*e/t))}}),a=n.cache&&Date.now();return n.cache&&Oo({files:i},{cachedAt:a}),{data:i,cachedAt:a}},observeFile:(e,t)=>{const{log:r}=ve(),n=Date.now();r(`observeFile(tmpid: ${n}) > listen`);return oe(ie(Hd,e),(r=>r.data&&((r,n)=>{var s,i,a;if((null===(s=r.data)||void 0===s?void 0:s.fileId)===e){if(t instanceof Function)return t(r);"onFetch"!==n&&(null===(i=t.onEvent)||void 0===i||i.call(t,n,r)),null===(a=t[n])||void 0===a||a.call(t,r)}})(r,"onFetch"))),()=>{r(`observeFile(tmpid: ${n}) > dispose`)}}});const Yd=async e=>{const t=ve();t.log("role/queryRoles",e);const r=null!=e?e:{},{page:n,limit:s=10,queryToken:i,displayName:a,sortBy:o}=r,l=Mo(r,["page","limit","queryToken","displayName","sortBy"]),c=i?{token:i}:s?{limit:s}:n?{token:X(n,"skiplimit")}:void 0,{data:d}=await t.http.get("/api/v3/roles",{params:Object.assign(Object.assign({},l),{keyword:a,sortBy:o,options:c})}),{paging:u}=d,h=Mo(d,["paging"]),{roles:f}=h,p=t.cache&&Date.now();t.cache&&Oo(h,{cachedAt:p});const g=J(u.next);return{data:f,cachedAt:p,prevPage:J(u.previous),nextPage:g,paging:u}};Yd.locally=e=>{ve().log("role/queryRoles.locally",e)};const Qd=async e=>{const t=ve();t.log("role/getRole",e);const{data:r}=await t.http.get(`/api/v3/roles/${e}`),n=t.cache&&Date.now();return t.cache&&Oo({roles:r},{cachedAt:n}),{data:r.find((t=>t.roleId===e)),cachedAt:n}};Qd.locally=e=>{const t=ve();if(t.log("role/getRole.locally",e),!t.cache)return;const r=Ee(["role","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const Xd=(e,t)=>{"message"===e?Je("local.message.updated",{messages:[t]}):"post"===e?Je("post.updated",{posts:[t]}):"comment"===e?Je("comment.updated",{comments:[t]}):"story"===e&&Je("story.updated",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[t]})},Jd=async(e,t=!1)=>{const r=ve();let n;r.log("message/getMessage",e),t||console.log("getMessage will be deprecated on 15th November 2022, please use liveMessage instead."),ql("message",e);try{const{data:t}=await r.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);n=await Ol(t)}catch(t){throw C(null==t?void 0:t.code)&&Po("message",e),t}const s=r.cache&&Date.now();r.cache&&Oo(n,{cachedAt:s});const{messages:i}=n;return Je("local.message.fetched",{messages:i}),{data:i.find((t=>t.messageId===e)),cachedAt:s}};Jd.locally=e=>{const t=ve();if(t.log("message/getMessage.locally",e),!t.cache)return;const r=Ee(["message","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const Zd=async e=>{const t=ve();let r;t.log("post/getPost",e),ql("post",e);try{r=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw C(null==t?void 0:t.code)&&Po("post",e),t}const n=Uo(r,"communityUsers"),s=t.cache&&Date.now();t.cache&&Oo(n,{cachedAt:s});const{posts:i}=n,a=i.find((t=>t.postId===e));return{data:il.post(a),cachedAt:s}};Zd.locally=e=>{const t=ve();if(t.log("post/getPost.locally",e),!t.cache)return;const r=Ee(["post","get",e]);return r?{data:il.post(r.data),cachedAt:r.cachedAt}:void 0};const eu=async e=>{const t=ve();let r;t.log("comment/getComment",e),ql("comment",e);try{r=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw C(null==t?void 0:t.code)&&Po("comment",e),t}const n=t.cache&&Date.now();t.cache&&Oo(r,{cachedAt:n});const{comments:s}=r;return{data:il.comment(s.find((t=>t.commentId===e))),cachedAt:n}};eu.locally=e=>{const t=ve();if(t.log("comment/getComment.locally",e),!t.cache)return;const r=Ee(["comment","get",e]);return r?{data:il.comment(r.data),cachedAt:r.cachedAt}:void 0};const tu=(e,t)=>{var r,n;let s,i;if("post"===t)i="post",s=e.posts[0].postId;else if("comment"===t)i="comment",s=e.comments[0].commentId;else{if("story"!==t)throw new Error("Unknown event type");i="story",s=e.stories[0].referenceId}return(null===(n=null===(r=Ee([i,"get",s]))||void 0===r?void 0:r.data)||void 0===n?void 0:n.myReactions)||[]},ru=(e,t,r)=>{const[n]=e[t];return Object.assign(Object.assign({},e),{[t]:[Object.assign(Object.assign({},n),{myReactions:r})]})},nu=(e,t,r,n=[])=>{const s=e.split(".")[1];let i=n;if(ve().userId===t)if(["addReaction","reactionAdded"].includes(s))i.includes(r)||i.push(r);else{if(!["removeReaction","reactionRemoved"].includes(s))throw new Error(`Unknown event type: ${s}`);i=i.filter((e=>e!==r))}return i},su=(e,t)=>{const r=e.split(".")[0],n=tu(t,r),s=nu(e,t.reactor.userId,t.reactor.reactionName,n);return ru(t,`${r}s`,s)},iu=(e,t)=>{var r,n;const s=e.split(".")[0];let i=tu(t,s);return(null==t?void 0:t.reactions)&&t.reactions.length>0&&(i=nu(e,null===(r=t.reactions[0])||void 0===r?void 0:r.userId,null===(n=t.reactions[0])||void 0===n?void 0:n.reactionName,i)),ru(t,"stories",i)},au=async(e,t,r)=>{const n=ve();if(n.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:r}),await n.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:r,referenceVersion:"message"===e?5:void 0}),n.cache){const r=Ee([e,"get",t]);(null==r?void 0:r.data)&&Se([e,"get",t],r.data,{cachedAt:Date.now()})}return!0};au.optimistically=(e,t,r)=>{var n,s,i,a,o;const l=ve();if(l.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:r}),!l.cache)return;const c=Ee([e,"get",t]);if(!(null==c?void 0:c.data)||(null===(n=c.data.myReactions)||void 0===n?void 0:n.includes(r)))return;const d=Object.assign(Object.assign({},c.data),{reactionsCount:c.data.reactionsCount+1,myReactions:[...null!==(s=c.data.myReactions)&&void 0!==s?s:[],r],reactions:Object.assign(Object.assign({},c.data.reactions),{[r]:(null!==(i=c.data.reactions[r])&&void 0!==i?i:0)+1})});return Ce([e,"get",t],d,{cachedAt:-5}),Xd(e,d),null!==(o=null===(a=null==d?void 0:d.myReactions)||void 0===a?void 0:a.includes(r))&&void 0!==o&&o};const ou=async(e,t,r)=>{const n=ve();if(n.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:r}),await n.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:r,referenceVersion:"message"===e?5:void 0}}),n.cache){const r=Ee([e,"get",t]);(null==r?void 0:r.data)&&Se([e,"get",t],r.data,{cachedAt:Date.now()})}return!0};ou.optimistically=(e,t,r)=>{var n,s,i,a,o;const l=ve();if(l.log("reaction/removeReaction.optimistically",{referenceId:t,referenceType:e,reactionName:r}),!l.cache)return;const c=Ee([e,"get",t]);if(!(null==c?void 0:c.data)||!(null===(n=c.data.myReactions)||void 0===n?void 0:n.includes(r)))return;const d=Object.assign(Object.assign({},c.data),{reactionsCount:Math.max(0,c.data.reactionsCount-1),myReactions:(null!==(s=c.data.myReactions)&&void 0!==s?s:[]).filter((e=>e!==r)),reactions:Object.assign(Object.assign({},c.data.reactions),{[r]:Math.max(0,(null!==(i=c.data.reactions[r])&&void 0!==i?i:0)-1)})});return Ce([e,"get",t],d,{cachedAt:-5}),Xd(e,d),null!==(o=!(null===(a=null==d?void 0:d.myReactions)||void 0===a?void 0:a.includes(r)))&&void 0!==o&&o};const lu=(e,t)=>{const r=ve();return Xe(r,e,e,(n=>{var s;if(r.cache){const{communities:i}=n,a=Mo(n,["communities"]),o=Uo(a,"communityUsers");if(Oo(o),(null==i?void 0:i[0])&&!["post.updated"].includes(e)&&Je("community.updated",{communities:i,categories:[],communityUsers:o.communityUsers,feeds:[],files:[],users:[]}),"post.deleted"===e){const{postId:e,postedUserId:s}=n.posts[0];try{ql("post",e)}catch(e){return}return s!==r.userId&&Po("post",e),t(n.posts[0])}const l=Ee(["post","get",n.posts[0].postId]);if(["post.created","post.approved","post.declined"].includes(e)){let t=null===(s=we(["post","query"]))||void 0===s?void 0:s.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.targetId)===l.data.targetId}));"post.declined"===e&&(t=null==t?void 0:t.filter((({key:e})=>{var t;return"reviewing"===(null===(t=e[2])||void 0===t?void 0:t.feedType)}))),null==t||t.map((({key:e,data:t})=>Ce(e,t,{cachedAt:-1})))}t(l.data)}else t(n.posts[0])}))},cu=e=>lu("post.created",e),du=e=>lu("post.updated",e),uu=e=>lu("post.deleted",e),hu=e=>lu("post.approved",e),fu=e=>lu("post.declined",e),pu=e=>lu("post.flagged",e),gu=e=>lu("post.unflagged",e),mu=e=>{const t=ve();return Xe(t,"post.addReaction","post.addReaction",(r=>{if(t.cache){const t=Mo(su("post.addReaction",r),["reactor"]);Oo(t);const n=Ee(["post","get",r.posts[0].postId]);e(n.data)}else e(r.posts[0])}))},yu=e=>{const t=ve();return Xe(t,"post.removeReaction","post.removeReaction",(r=>{if(t.cache){const t=Mo(su("post.removeReaction",r),["reactor"]);Oo(t);const n=Ee(["post","get",r.posts[0].postId]);e(n.data)}else e(r.posts[0])}))},vu=(e,t)=>{const r=ve();return Xe(r,e,e,(n=>{var s;if(r.cache){Oo(n);const{comments:r}=n;if(r.length>0){const n=Ee(["comment","get",r[0].commentId]);if(["comment.created"].includes(e)){if(r[0].parentId){const e=Ee(["comment","get",r[0].parentId]);(null==e?void 0:e.data)&&Se(["comment","get",r[0].parentId],Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,r[0].commentId])]}))}const e=null===(s=we(["comment","query"]))||void 0===s?void 0:s.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===n.data.referenceId}));null==e||e.map((({key:e,data:t})=>Ce(e,t,{cachedAt:-1})))}t(il.comment(n.data))}}else t(il.comment(n.comments[0]))}))},bu=e=>vu("comment.created",e),wu=e=>vu("comment.updated",e),Eu=e=>vu("comment.deleted",e),Su=e=>vu("comment.flagged",e),Tu=e=>vu("comment.unflagged",e),Cu=e=>{const t=ve();return Xe(t,"comment.addReaction","comment.addReaction",(r=>{if(t.cache){const t=Mo(su("comment.addReaction",r),["reactor"]);Oo(t);const n=Ee(["comment","get",r.comments[0].commentId]);e(il.comment(n.data))}else e(il.comment(r.comments[0]))}))},ku=e=>{const t=ve();return Xe(t,"comment.removeReaction","comment.removeReaction",(r=>{if(t.cache){const t=Mo(su("comment.removeReaction",r),["reactor"]);Oo(t);const n=Ee(["comment","get",r.comments[0].commentId]);e(il.comment(n.data))}else e(il.comment(r.comments[0]))}))},Au=(e,t,r)=>{const n=ve(),s=(n,s,i)=>{n===e&&s===t&&r(i)};if("message"===e){return Xe(n,"reaction/onReactorAdded","message.updated",(async e=>{const t=await Ol(e);t.reactions[0]&&(Oo(t),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return Xe(n,"post.addReaction","post.addReaction",(e=>{const{reactor:t}=e,r=Mo(e,["reactor"]);Oo(r),Oo({reactions:[t]}),s("post",e.posts[0].postId,t)}))}if("story"===e){return Xe(n,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,r=Mo(e,["reactions"]);Oo(r),Oo({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}))}return Xe(n,"comment.addReaction","comment.addReaction",(e=>{const{reactor:t}=e,r=Mo(e,["reactor"]);Oo(r),Oo({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))},Iu=(e,t,r)=>{const n=ve(),s=(n,s,i)=>{n===e&&s===t&&r(i)};if("message"===e){return Xe(n,"reaction/onReactorRemoved","message.updated",(async e=>{const t=await Ol(e);t.reactions[0]&&(Oo(t),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return Xe(n,"post.removeReaction","post.removeReaction",(e=>{const{reactor:t}=e,r=Mo(e,["reactor"]);Oo(r),Oo({reactions:[t]}),s("post",e.posts[0].postId,t)}))}if("story"===e){return Xe(n,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,r=Mo(e,["reactions"]);Oo(r),Oo({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}))}return Xe(n,"comment.removeReaction","comment.removeReaction",(e=>{const{reactor:t}=e,r=Mo(e,["reactor"]);Oo(r),Oo({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))},_u=async e=>{ve().log("reaction/queryReactor",e);const t=await(async e=>{const t=ve();t.log("reaction/queryReactions",e);const r=null!=e?e:{},{page:n={limit:10}}=r,s=Mo(r,["page"]),{data:i}=await t.http.get("/api/v3/reactions",{params:Object.assign(Object.assign({},s),{referenceVersion:5,options:{token:X(n,"afterbeforeraw")}})}),{paging:a}=i,o=Mo(i,["paging"]),{reactions:l}=o;Oo(Object.assign(Object.assign({},o),{reactions:l})),Oo(Object.assign(Object.assign({},o),{reactors:l[0].reactors}));const c=Z(a.next);return{data:l,prevPage:Z(a.previous),nextPage:c}})(e),{data:r}=t,n=Mo(t,["data"]);return Object.assign(Object.assign({},n),{data:r[0].reactors})};var Ru=Object.freeze({__proto__:null,addReaction:au,removeReaction:ou,onReactionAdded:(e,t,r)=>{const n=n=>{de(e)(n)===t&&r(n)};if("message"===e){const e=ve(),t=async e=>{var t;const r=await Ol(e),s=Ee(["message","get",r.messages[0].messageId]),i=(null===(t=null==s?void 0:s.data)||void 0===t?void 0:t.reactionsCount)!==r.messages[0].reactionsCount;Oo(r),i&&n(r.messages[0])};return Xe(e,"reaction/onReactionAdded","message.updated",t)}return"post"===e?mu(n):Cu(n)},onReactionRemoved:(e,t,r)=>{const n=n=>{de(e)(n)===t&&r(n)};if("message"===e){const e=ve(),t=async e=>{var t;const r=await Ol(e),s=Ee(["message","get",r.messages[0].messageId]),i=(null===(t=null==s?void 0:s.data)||void 0===t?void 0:t.reactionsCount)!==r.messages[0].reactionsCount;Oo(r),i&&n(r.messages[0])};return Xe(e,"reaction/onReactionRemoved","message.updated",t)}return"post"===e?yu(n):ku(n)},onReactorAdded:Au,onReactorRemoved:Iu,getReactions:(e,t,r)=>{const{log:n,cache:s}=ve();s||console.log("For using Live Collection feature you need to enable Cache!");const i=Date.now();n(`liveReactions(tmpid: ${i}) > listen`);const{limit:a}=e,o=Mo(e,["limit"]),l=null!=a?a:h,{policy:c=f}=null!=r?r:{},d=[],u=["reaction","collection",{referenceId:e.referenceId,referenceType:e.referenceType}],p=e=>{var r,n;const s=null!==(r=e.data.map((e=>Ee(["reactor","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];t({onNextPage:m,data:s,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading,error:e.error})},g=e=>t=>{var r;const n=null===(r=Ee(u))||void 0===r?void 0:r.data;n&&("onAdded"===e?n.data=[...new Set([t.reactionId,...n.data])]:"onRemoved"===e&&(n.data=n.data.filter((e=>e!==t.reactionId))),Se(u,n),p(n))},m=(e=!1)=>{var t,r,n,s;const i=null===(t=Ee(u))||void 0===t?void 0:t.data,a=null!==(r=null==i?void 0:i.data)&&void 0!==r?r:[];if(!e&&a.length>0&&!(null===(n=null==i?void 0:i.params)||void 0===n?void 0:n.page))return;const d=ie(_u,Object.assign(Object.assign({},o),{page:null!==(s=e||null==i?void 0:i.params.page)&&void 0!==s?s:{limit:l}}));oe(d,(({data:e,error:t,loading:r,nextPage:n})=>{const s={loading:r,error:t,params:{page:n},data:a};e&&(s.data=[...new Set([...a,...e.map(de("reactor"))])]),Se(u,s),p(s)}),ae(c))};return d.push(Au(o.referenceType,o.referenceId,g("onAdded")),Iu(o.referenceType,o.referenceId,g("onRemoved"))),m(!0),()=>{n(`liveReactions(tmpid: ${i}) > dispose`),d.forEach((e=>e()))}}}),Lu={post:{domainName:"posts",eventName:"v3/post.isflagbyme",primaryKey:"postId"},comment:{domainName:"comments",eventName:"v3/comment.isflagbyme",primaryKey:"commentId"},message:{domainName:"messages",eventName:"v3/message.isFlaggedByMe",primaryKey:"messageId"},user:{domainName:"users",eventName:"user.isFlagByMe",primaryKey:"userId"}};const Du=async e=>{const t=ve();let r;t.log("channel/getChannel",e),ql("channel",e);try{const{data:n}=await t.http.get(`/api/v3/channels/${encodeURIComponent(e)}`);r=await Tl(n)}catch(t){throw C(null==t?void 0:t.code)&&Po("channel",e),t}const n=t.cache&&Date.now();t.cache&&Oo(r,{cachedAt:n});const{channels:s}=r;return{data:s.find((t=>t.channelId===e)),cachedAt:n}};Du.locally=e=>{const t=ve();if(t.log("channel/getChannel.locally",e),!t.cache)return;const r=Ee(["channel","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const xu=(e,t,r)=>n=>e((e=>{var s;if(!e)return e;const i=[r,"get",`${e[t]}`],a=null===(s=Ee(i))||void 0===s?void 0:s.data;return a?n(a):void 0})),Ou=e=>{const t=ve(),r=[Xe(t,"onMessageUpdated","message.updated",(async t=>{const r=await Ol(t);Oo(r),e(r.messages[0])})),Xe(t,"onMessageUpdated","local.message.updated",(t=>e(t.messages[0])))];return()=>{r.forEach((e=>e()))}},Pu=e=>{const t=ve(),r=[Xe(t,"message/onMessageDeleted","message.deleted",(async t=>{const r=await Ol(t);Oo(r),e(r.messages[0])})),Xe(t,"message/onMessageDeleted","local.message.deleted",(t=>e(t.messages[0])))];return()=>{r.forEach((e=>e()))}},Mu=e=>{const t=ve(),r=[Xe(t,"onSubChannelUpdated","message-feed.updated",(async t=>{const r=await Nl(t);Oo(r),e(r.messageFeeds[0])})),Xe(t,"onSubChannelUpdated","local.message-feed.updated",(t=>e(t.messageFeeds[0])))];return()=>{r.forEach((e=>e()))}};function Fu(e,t){Se(["channel","get",e.channelId],Object.assign(ul(e),t))}const Uu=e=>{const t=ve();return Xe(t,"channelMarker/onChannelMarkerUpdated","local.channelMarker.updated",(t=>{e(t.userEntityMarkers[0])}))},Nu=async(e,t=!1)=>{const r=ve(),n=await Kl(e);await r.http.delete(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{params:{permanent:t}});const s=Object.assign(Object.assign({},n.data),{isDeleted:!0,updatedAt:he(n.data.updatedAt)});return t?setTimeout((()=>{Po("subChannel",e)}),0):Ce(["subChannel","get",e],s),Je("local.message-feed.deleted",{messageFeeds:[s]}),s},Bu=e=>Xe(ve(),"onSubChannelFetched","local.message-feed.fetched",(t=>e(t.messageFeeds[0]))),ju=async e=>{const t=ve();t.log("message/getMessages",e);const{data:r}=await t.http.get("/api/v5/messages/list",{params:{messageIds:e.map(encodeURIComponent)}}),n=await Ol(r),s=t.cache&&Date.now();t.cache&&Oo(n,{cachedAt:s});const{messages:i}=n;return Je("local.message.fetched",{messages:i}),{data:i.map((e=>il.message(e))),cachedAt:s}};ju.locally=e=>{var t;const r=ve();if(r.log("message/getMessages.locally",e),!r.cache)return;const n=e.map((e=>Ee(["message","get",e]))).filter(Boolean),s=n.map((({data:e})=>e)),i=null===(t=n.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==n?void 0:n.length)<e.length?void 0:{data:s,cachedAt:i.cachedAt}};const $u=()=>`LOCAL_${Ao()}`;let qu;const Ku=async e=>{const t=ve();t.log("message/createMessage",e);const r=e.referenceId||qu||$u();qu=void 0;const{data:n}=await t.http.post("/api/v5/messages",Object.assign(Object.assign({},Pl(e)),{referenceId:r})),s=await Ol(n),{messages:i}=s,a=t.cache&&Date.now();return t.cache&&(ke(["message","get",r]),Oo(s,{cachedAt:a})),Je("local.message.created",{messages:i}),{data:il.message(i[0]),cachedAt:a}};Ku.optimistically=e=>{var t,r,{referenceId:n}=e,s=Mo(e,["referenceId"]);const i=ve();if(!i.cache)return;qu=n||$u();const a=Object.assign({messageId:qu,uniqueId:qu},s);i.log("message/createMessage.optimistically",a);const o=Ee(["subChannel","get",s.subChannelId]);if(o&&(Ce(["subChannel","get",s.subChannelId],Object.assign(Object.assign({},o.data),{messageCount:o.data.messageCount+1})),o.data.channelId===o.data.subChannelId)){const e=Ee(["channel","get",o.data.channelId]);(null==e?void 0:e.data)&&Ce(["channel","get",o.data.channelId],Object.assign(Object.assign({},e.data),{messageCount:(null!==(t=e.data.messageCount)&&void 0!==t?t:0)+1}))}const l=(new Date).toISOString(),c=Object.assign({creatorId:i.userId,creatorPrivateId:Ke()._id,channelSegment:(null!==(r=null==o?void 0:o.data.messageCount)&&void 0!==r?r:0)+1,childrenNumber:0,createdAt:l,updatedAt:l},a);return Se(["message","get",c.messageId],c,{cachedAt:-5}),Je("local.message.created",{messages:[c]}),{cachedAt:-5,data:il.message(c)}};const Gu=async(e,t)=>{const r=ve();r.log("message/updateMessage",t),console.warn("MessageRepository.updateMessage will be replaced with MessageRepository.editMessage");const{data:n}=await r.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,Pl(t)),s=await Ol(n),i=r.cache&&Date.now();r.cache&&Oo(s,{cachedAt:i});const{messages:a}=s;return Je("local.message.updated",{messages:a}),{data:il.message(a.find((t=>t.messageId===e))),cachedAt:i}};Gu.optimistically=(e,t)=>{const r=ve();if(r.log("message/updateMessage.optimistically",t),!r.cache)return;const n=Ee(["message","get",e]);if(!n)return;const s=Object.assign(Object.assign(Object.assign({},n.data),t),{updatedAt:(new Date).toISOString()});return Ce(["message","get",e],s,{cachedAt:-1}),Je("local.message.updated",{messages:[s]}),{data:il.message(s),cachedAt:-1}};const Hu=async(e,t)=>{const r=ve();r.log("message/editMessage",t);const{data:n}=await r.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,Pl(t)),s=await Ol(n),i=r.cache&&Date.now();r.cache&&Oo(s,{cachedAt:i});const{messages:a}=s;return Je("local.message.updated",{messages:a}),{data:il.message(a.find((t=>t.messageId===e))),cachedAt:i}};Hu.optimistically=(e,t)=>{const r=ve();if(r.log("message/editMessage.optimistically",t),!r.cache)return;const n=Ee(["message","get",e]);if(!n)return;const s=Object.assign(Object.assign(Object.assign({},n.data),t),{updatedAt:(new Date).toISOString()});return Ce(["message","get",e],s,{cachedAt:-1}),Je("local.message.updated",{messages:[s]}),{data:il.message(s),cachedAt:-1}};const Vu=async e=>{const t=ve();t.log("message/deleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const r=await Jd(e);return Je("local.message.deleted",{messages:[r.data]}),il.message(r.data)};Vu.optimistically=e=>{ve().log("message/deleteMessage.optimistically",e);const t=Ee(["message","get",e]);if(!t)return;const r=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return Ce(["message","get",e],r,{cachedAt:-1}),Je("local.message.deleted",{messages:[r]}),{data:il.message(r),cachedAt:-1}};const zu=async e=>{const t=ve();t.log("message/softDeleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const r=await Jd(e);return Je("local.message.deleted",{messages:[r.data]}),il.message(r.data)};zu.optimistically=e=>{ve().log("message/softDeleteMessage.optimistically",e);const t=Ee(["message","get",e]);if(!t)return;const r=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return Ce(["message","get",e],r,{cachedAt:-1}),Je("local.message.deleted",{messages:[r]}),{data:il.message(r),cachedAt:-1}};const Wu=async e=>{const t=ve();t.log("user/getReadUsers",e);const{page:r,messageId:n}=e,s=Mo(e,["page","messageId"]),{data:i}=await t.http.get(`/api/v1/markers/messages/${n}/read-users`,{params:Object.assign(Object.assign({},s),{options:{token:X(r,"afterbeforeraw")}})}),{paging:a,publicUserIds:o,userFeedMarkers:l}=i,c=Mo(i,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Oo(Object.assign(Object.assign({},c),{userFeedMarkers:jo(l)}),{cachedAt:d});const e=["read-user","query",Object.assign(Object.assign({messageId:n},s),{options:Object.assign({},r)})];Se(e,{users:o,paging:a})}let u=[];o.length>0&&({data:u}=await xd(o));return{data:u,cachedAt:d,prevPage:J(a.previous),nextPage:J(a.next)}};Wu.locally=e=>{var t;const r=ve();if(r.log("user/getReadUsers.locally",e),!r.cache)return;const{page:n}=e,s=Mo(e,["page"]),i=["read-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},n)})],{data:a,cachedAt:o}=null!==(t=Ee(i))&&void 0!==t?t:{},l=null==a?void 0:a.users.map((e=>{var t;return null===(t=Ee(["user","get",e]))||void 0===t?void 0:t.data}));if(!l||l.some((e=>!e)))return;return{data:l,cachedAt:o,prevPage:J(null==a?void 0:a.paging.previous),nextPage:J(null==a?void 0:a.paging.next)}};const Yu=async e=>{const t=ve();t.log("user/getDeliveredUsers",e);const{page:r,messageId:n}=e,s=Mo(e,["page","messageId"]),{data:i}=await t.http.get(`/api/v1/markers/messages/${n}/delivered-users`,{params:Object.assign(Object.assign({},s),{options:{token:X(r,"afterbeforeraw")}})}),{paging:a,publicUserIds:o,userFeedMarkers:l}=i,c=Mo(i,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Oo(Object.assign(Object.assign({},c),{userFeedMarkers:jo(l)}),{cachedAt:d});const e=["delivered-user","query",Object.assign(Object.assign({messageId:n},s),{options:Object.assign({},r)})];Se(e,{users:o,paging:a})}let u=[];o.length>0&&({data:u}=await xd(o));return{data:u,cachedAt:d,prevPage:J(a.previous),nextPage:J(a.next)}};Yu.locally=e=>{var t;const r=ve();if(r.log("user/getDeliveredUsers.locally",e),!r.cache)return;const{page:n}=e,s=Mo(e,["page"]),i=["delivered-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},n)})],{data:a,cachedAt:o}=null!==(t=Ee(i))&&void 0!==t?t:{},l=null==a?void 0:a.users.map((e=>{var t;return null===(t=Ee(["user","get",e]))||void 0===t?void 0:t.data}));if(!l||l.some((e=>!e)))return;return{data:l,cachedAt:o,prevPage:J(null==a?void 0:a.paging.previous),nextPage:J(null==a?void 0:a.paging.next)}};const Qu=e=>{const t=ve();return Xe(t,"onMessageFlagged","message.flagged",(async t=>{const r=await Ol(t);Oo(r),e(r.messages[0])}))},Xu=e=>{const t=ve();return Xe(t,"onMessageUnflagged","message.unflagged",(async t=>{const r=await Ol(t);Oo(r),e(r.messages[0])}))},Ju=e=>{const t=ve();return Xe(t,"onMessageFlagCleared","message.flagCleared",(async t=>{const r=await Ol(t);Oo(r),e(r.messages[0])}))},Zu=e=>{const t=ve();return Xe(t,"onMessageReactionAdded","message.reactionAdded",(async t=>{const r=await Ol(t,"message.reactionAdded");Oo(r),e(r.messages[0])}))},eh=e=>{const t=ve();return Xe(t,"onMessageReactionRemoved","message.reactionRemoved",(async t=>{const r=await Ol(t,"message.reactionRemoved");Oo(r),e(r.messages[0])}))},th=e=>{const t=ve();return Xe(t,"message/onMessageFetched","local.message.fetched",(t=>{Oo(t),e(t.messages[0])}))};var rh={exports:{}};!function(e,t){e.exports=function e(t,r,n){function s(a,o){if(!r[a]){if(!t[a]){if(!o&&Ia)return Ia(a);if(i)return i(a,!0);throw new Error("Cannot find module '"+a+"'")}o=r[a]={exports:{}},t[a][0].call(o.exports,(function(e){return s(t[a][1][e]||e)}),o,o.exports,e,t,r,n)}return r[a].exports}for(var i=Ia,a=0;a<n.length;a++)s(n[a]);return s}({1:[function(e,t,r){(function(n,s,i,a,o,l,c,d,u){var h=e("crypto");function f(e,t){var r;return void 0===(r="passthrough"!==(t=m(e,t)).algorithm?h.createHash(t.algorithm):new b).write&&(r.write=r.update,r.end=r.update),v(t,r).dispatch(e),r.update||r.end(""),r.digest?r.digest("buffer"===t.encoding?void 0:t.encoding):(e=r.read(),"buffer"!==t.encoding?e.toString(t.encoding):e)}(r=t.exports=f).sha1=function(e){return f(e)},r.keys=function(e){return f(e,{excludeValues:!0,algorithm:"sha1",encoding:"hex"})},r.MD5=function(e){return f(e,{algorithm:"md5",encoding:"hex"})},r.keysMD5=function(e){return f(e,{algorithm:"md5",encoding:"hex",excludeValues:!0})};var p=h.getHashes?h.getHashes().slice():["sha1","md5"],g=(p.push("passthrough"),["buffer","hex","binary","base64"]);function m(e,t){var r={};if(r.algorithm=(t=t||{}).algorithm||"sha1",r.encoding=t.encoding||"hex",r.excludeValues=!!t.excludeValues,r.algorithm=r.algorithm.toLowerCase(),r.encoding=r.encoding.toLowerCase(),r.ignoreUnknown=!0===t.ignoreUnknown,r.respectType=!1!==t.respectType,r.respectFunctionNames=!1!==t.respectFunctionNames,r.respectFunctionProperties=!1!==t.respectFunctionProperties,r.unorderedArrays=!0===t.unorderedArrays,r.unorderedSets=!1!==t.unorderedSets,r.unorderedObjects=!1!==t.unorderedObjects,r.replacer=t.replacer||void 0,r.excludeKeys=t.excludeKeys||void 0,void 0===e)throw new Error("Object argument required.");for(var n=0;n<p.length;++n)p[n].toLowerCase()===r.algorithm.toLowerCase()&&(r.algorithm=p[n]);if(-1===p.indexOf(r.algorithm))throw new Error('Algorithm "'+r.algorithm+'" not supported. supported values: '+p.join(", "));if(-1===g.indexOf(r.encoding)&&"passthrough"!==r.algorithm)throw new Error('Encoding "'+r.encoding+'" not supported. supported values: '+g.join(", "));return r}function y(e){if("function"==typeof e)return null!=/^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i.exec(Function.prototype.toString.call(e))}function v(e,t,r){function n(e){return t.update?t.update(e,"utf8"):t.write(e,"utf8")}return r=r||[],{dispatch:function(t){return this["_"+(null===(t=e.replacer?e.replacer(t):t)?"null":typeof t)](t)},_object:function(t){var s,a=Object.prototype.toString.call(t),o=/\[object (.*)\]/i.exec(a);if(o=(o=o?o[1]:"unknown:["+a+"]").toLowerCase(),0<=(a=r.indexOf(t)))return this.dispatch("[CIRCULAR:"+a+"]");if(r.push(t),void 0!==i&&i.isBuffer&&i.isBuffer(t))return n("buffer:"),n(t);if("object"===o||"function"===o||"asyncfunction"===o)return a=Object.keys(t),e.unorderedObjects&&(a=a.sort()),!1===e.respectType||y(t)||a.splice(0,0,"prototype","__proto__","constructor"),e.excludeKeys&&(a=a.filter((function(t){return!e.excludeKeys(t)}))),n("object:"+a.length+":"),s=this,a.forEach((function(r){s.dispatch(r),n(":"),e.excludeValues||s.dispatch(t[r]),n(",")}));if(!this["_"+o]){if(e.ignoreUnknown)return n("["+o+"]");throw new Error('Unknown object type "'+o+'"')}this["_"+o](t)},_array:function(t,s){s=void 0!==s?s:!1!==e.unorderedArrays;var i=this;if(n("array:"+t.length+":"),!s||t.length<=1)return t.forEach((function(e){return i.dispatch(e)}));var a=[];return s=t.map((function(t){var n=new b,s=r.slice();return v(e,n,s).dispatch(t),a=a.concat(s.slice(r.length)),n.read().toString()})),r=r.concat(a),s.sort(),this._array(s,!1)},_date:function(e){return n("date:"+e.toJSON())},_symbol:function(e){return n("symbol:"+e.toString())},_error:function(e){return n("error:"+e.toString())},_boolean:function(e){return n("bool:"+e.toString())},_string:function(e){n("string:"+e.length+":"),n(e.toString())},_function:function(t){n("fn:"),y(t)?this.dispatch("[native]"):this.dispatch(t.toString()),!1!==e.respectFunctionNames&&this.dispatch("function-name:"+String(t.name)),e.respectFunctionProperties&&this._object(t)},_number:function(e){return n("number:"+e.toString())},_xml:function(e){return n("xml:"+e.toString())},_null:function(){return n("Null")},_undefined:function(){return n("Undefined")},_regexp:function(e){return n("regex:"+e.toString())},_uint8array:function(e){return n("uint8array:"),this.dispatch(Array.prototype.slice.call(e))},_uint8clampedarray:function(e){return n("uint8clampedarray:"),this.dispatch(Array.prototype.slice.call(e))},_int8array:function(e){return n("int8array:"),this.dispatch(Array.prototype.slice.call(e))},_uint16array:function(e){return n("uint16array:"),this.dispatch(Array.prototype.slice.call(e))},_int16array:function(e){return n("int16array:"),this.dispatch(Array.prototype.slice.call(e))},_uint32array:function(e){return n("uint32array:"),this.dispatch(Array.prototype.slice.call(e))},_int32array:function(e){return n("int32array:"),this.dispatch(Array.prototype.slice.call(e))},_float32array:function(e){return n("float32array:"),this.dispatch(Array.prototype.slice.call(e))},_float64array:function(e){return n("float64array:"),this.dispatch(Array.prototype.slice.call(e))},_arraybuffer:function(e){return n("arraybuffer:"),this.dispatch(new Uint8Array(e))},_url:function(e){return n("url:"+e.toString())},_map:function(t){return n("map:"),t=Array.from(t),this._array(t,!1!==e.unorderedSets)},_set:function(t){return n("set:"),t=Array.from(t),this._array(t,!1!==e.unorderedSets)},_file:function(e){return n("file:"),this.dispatch([e.name,e.size,e.type,e.lastModfied])},_blob:function(){if(e.ignoreUnknown)return n("[blob]");throw Error('Hashing Blob objects is currently not supported\n(see https://github.com/puleos/object-hash/issues/26)\nUse "options.replacer" or "options.ignoreUnknown"\n')},_domwindow:function(){return n("domwindow")},_bigint:function(e){return n("bigint:"+e.toString())},_process:function(){return n("process")},_timer:function(){return n("timer")},_pipe:function(){return n("pipe")},_tcp:function(){return n("tcp")},_udp:function(){return n("udp")},_tty:function(){return n("tty")},_statwatcher:function(){return n("statwatcher")},_securecontext:function(){return n("securecontext")},_connection:function(){return n("connection")},_zlib:function(){return n("zlib")},_context:function(){return n("context")},_nodescript:function(){return n("nodescript")},_httpparser:function(){return n("httpparser")},_dataview:function(){return n("dataview")},_signal:function(){return n("signal")},_fsevent:function(){return n("fsevent")},_tlswrap:function(){return n("tlswrap")}}}function b(){return{buf:"",write:function(e){this.buf+=e},end:function(e){this.buf+=e},read:function(){return this.buf}}}r.writeToStream=function(e,t,r){return void 0===r&&(r=t,t={}),v(t=m(e,t),r).dispatch(e)}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/fake_9a5aa49d.js","/")},{buffer:3,crypto:5,lYpoI2:11}],2:[function(e,t,r){(function(e,t,n,s,i,a,o,l,c){!function(e){var t="undefined"!=typeof Uint8Array?Uint8Array:Array,r="+".charCodeAt(0),n="/".charCodeAt(0),s="0".charCodeAt(0),i="a".charCodeAt(0),a="A".charCodeAt(0),o="-".charCodeAt(0),l="_".charCodeAt(0);function c(e){return(e=e.charCodeAt(0))===r||e===o?62:e===n||e===l?63:e<s?-1:e<s+10?e-s+26+26:e<a+26?e-a:e<i+26?e-i+26:void 0}e.toByteArray=function(e){var r,n;if(0<e.length%4)throw new Error("Invalid string. Length must be a multiple of 4");var s=e.length,i=(s="="===e.charAt(s-2)?2:"="===e.charAt(s-1)?1:0,new t(3*e.length/4-s)),a=0<s?e.length-4:e.length,o=0;function l(e){i[o++]=e}for(r=0;r<a;r+=4,0)l((16711680&(n=c(e.charAt(r))<<18|c(e.charAt(r+1))<<12|c(e.charAt(r+2))<<6|c(e.charAt(r+3))))>>16),l((65280&n)>>8),l(255&n);return 2==s?l(255&(n=c(e.charAt(r))<<2|c(e.charAt(r+1))>>4)):1==s&&(l((n=c(e.charAt(r))<<10|c(e.charAt(r+1))<<4|c(e.charAt(r+2))>>2)>>8&255),l(255&n)),i},e.fromByteArray=function(e){var t,r,n,s,i=e.length%3,a="";function o(e){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(e)}for(t=0,n=e.length-i;t<n;t+=3)a+=o((s=r=(e[t]<<16)+(e[t+1]<<8)+e[t+2])>>18&63)+o(s>>12&63)+o(s>>6&63)+o(63&s);switch(i){case 1:a=(a+=o((r=e[e.length-1])>>2))+o(r<<4&63)+"==";break;case 2:a=(a=(a+=o((r=(e[e.length-2]<<8)+e[e.length-1])>>10))+o(r>>4&63))+o(r<<2&63)+"="}return a}}(void 0===r?this.base64js={}:r)}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/base64-js/lib/b64.js","/node_modules/gulp-browserify/node_modules/base64-js/lib")},{buffer:3,lYpoI2:11}],3:[function(e,t,r){(function(t,n,s,i,a,o,l,c,d){var u=e("base64-js"),h=e("ieee754");function s(e,t,r){if(!(this instanceof s))return new s(e,t,r);var n,i,a,o,l=typeof e;if("base64"===t&&"string"==l)for(e=(o=e).trim?o.trim():o.replace(/^\s+|\s+$/g,"");e.length%4!=0;)e+="=";if("number"==l)n=L(e);else if("string"==l)n=s.byteLength(e,t);else{if("object"!=l)throw new Error("First argument needs to be a number, array or string.");n=L(e.length)}if(s._useTypedArrays?i=s._augment(new Uint8Array(n)):((i=this).length=n,i._isBuffer=!0),s._useTypedArrays&&"number"==typeof e.byteLength)i._set(e);else if(D(o=e)||s.isBuffer(o)||o&&"object"==typeof o&&"number"==typeof o.length)for(a=0;a<n;a++)s.isBuffer(e)?i[a]=e.readUInt8(a):i[a]=e[a];else if("string"==l)i.write(e,0,t);else if("number"==l&&!s._useTypedArrays&&!r)for(a=0;a<n;a++)i[a]=0;return i}function f(e,t,r,n){return s._charsWritten=M(function(e){for(var t=[],r=0;r<e.length;r++)t.push(255&e.charCodeAt(r));return t}(t),e,r,n)}function p(e,t,r,n){return s._charsWritten=M(function(e){for(var t,r,n=[],s=0;s<e.length;s++)t=(r=e.charCodeAt(s))>>8,r%=256,n.push(r),n.push(t);return n}(t),e,r,n)}function g(e,t,r){var n="";r=Math.min(e.length,r);for(var s=t;s<r;s++)n+=String.fromCharCode(e[s]);return n}function m(e,t,r,n){var s;if(n||(j("boolean"==typeof r,"missing or invalid endian"),j(null!=t,"missing offset"),j(t+1<e.length,"Trying to read beyond buffer length")),!((n=e.length)<=t))return r?(s=e[t],t+1<n&&(s|=e[t+1]<<8)):(s=e[t]<<8,t+1<n&&(s|=e[t+1])),s}function y(e,t,r,n){var s;if(n||(j("boolean"==typeof r,"missing or invalid endian"),j(null!=t,"missing offset"),j(t+3<e.length,"Trying to read beyond buffer length")),!((n=e.length)<=t))return r?(t+2<n&&(s=e[t+2]<<16),t+1<n&&(s|=e[t+1]<<8),s|=e[t],t+3<n&&(s+=e[t+3]<<24>>>0)):(t+1<n&&(s=e[t+1]<<16),t+2<n&&(s|=e[t+2]<<8),t+3<n&&(s|=e[t+3]),s+=e[t]<<24>>>0),s}function v(e,t,r,n){if(n||(j("boolean"==typeof r,"missing or invalid endian"),j(null!=t,"missing offset"),j(t+1<e.length,"Trying to read beyond buffer length")),!(e.length<=t))return 32768&(n=m(e,t,r,!0))?-1*(65535-n+1):n}function b(e,t,r,n){if(n||(j("boolean"==typeof r,"missing or invalid endian"),j(null!=t,"missing offset"),j(t+3<e.length,"Trying to read beyond buffer length")),!(e.length<=t))return 2147483648&(n=y(e,t,r,!0))?-1*(4294967295-n+1):n}function w(e,t,r,n){return n||(j("boolean"==typeof r,"missing or invalid endian"),j(t+3<e.length,"Trying to read beyond buffer length")),h.read(e,t,r,23,4)}function E(e,t,r,n){return n||(j("boolean"==typeof r,"missing or invalid endian"),j(t+7<e.length,"Trying to read beyond buffer length")),h.read(e,t,r,52,8)}function S(e,t,r,n,s){if(s||(j(null!=t,"missing value"),j("boolean"==typeof n,"missing or invalid endian"),j(null!=r,"missing offset"),j(r+1<e.length,"trying to write beyond buffer length"),U(t,65535)),!((s=e.length)<=r))for(var i=0,a=Math.min(s-r,2);i<a;i++)e[r+i]=(t&255<<8*(n?i:1-i))>>>8*(n?i:1-i)}function T(e,t,r,n,s){if(s||(j(null!=t,"missing value"),j("boolean"==typeof n,"missing or invalid endian"),j(null!=r,"missing offset"),j(r+3<e.length,"trying to write beyond buffer length"),U(t,4294967295)),!((s=e.length)<=r))for(var i=0,a=Math.min(s-r,4);i<a;i++)e[r+i]=t>>>8*(n?i:3-i)&255}function C(e,t,r,n,s){s||(j(null!=t,"missing value"),j("boolean"==typeof n,"missing or invalid endian"),j(null!=r,"missing offset"),j(r+1<e.length,"Trying to write beyond buffer length"),N(t,32767,-32768)),e.length<=r||S(e,0<=t?t:65535+t+1,r,n,s)}function k(e,t,r,n,s){s||(j(null!=t,"missing value"),j("boolean"==typeof n,"missing or invalid endian"),j(null!=r,"missing offset"),j(r+3<e.length,"Trying to write beyond buffer length"),N(t,2147483647,-2147483648)),e.length<=r||T(e,0<=t?t:4294967295+t+1,r,n,s)}function A(e,t,r,n,s){s||(j(null!=t,"missing value"),j("boolean"==typeof n,"missing or invalid endian"),j(null!=r,"missing offset"),j(r+3<e.length,"Trying to write beyond buffer length"),B(t,34028234663852886e22,-34028234663852886e22)),e.length<=r||h.write(e,t,r,n,23,4)}function I(e,t,r,n,s){s||(j(null!=t,"missing value"),j("boolean"==typeof n,"missing or invalid endian"),j(null!=r,"missing offset"),j(r+7<e.length,"Trying to write beyond buffer length"),B(t,17976931348623157e292,-17976931348623157e292)),e.length<=r||h.write(e,t,r,n,52,8)}r.Buffer=s,r.SlowBuffer=s,r.INSPECT_MAX_BYTES=50,s.poolSize=8192,s._useTypedArrays=function(){try{var e=new ArrayBuffer(0),t=new Uint8Array(e);return t.foo=function(){return 42},42===t.foo()&&"function"==typeof t.subarray}catch(e){return!1}}(),s.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},s.isBuffer=function(e){return!(null==e||!e._isBuffer)},s.byteLength=function(e,t){var r;switch(e+="",t||"utf8"){case"hex":r=e.length/2;break;case"utf8":case"utf-8":r=O(e).length;break;case"ascii":case"binary":case"raw":r=e.length;break;case"base64":r=P(e).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":r=2*e.length;break;default:throw new Error("Unknown encoding")}return r},s.concat=function(e,t){if(j(D(e),"Usage: Buffer.concat(list, [totalLength])\nlist should be an Array."),0===e.length)return new s(0);if(1===e.length)return e[0];if("number"!=typeof t)for(i=t=0;i<e.length;i++)t+=e[i].length;for(var r=new s(t),n=0,i=0;i<e.length;i++){var a=e[i];a.copy(r,n),n+=a.length}return r},s.prototype.write=function(e,t,r,n){isFinite(t)?isFinite(r)||(n=r,r=void 0):(c=n,n=t,t=r,r=c),t=Number(t)||0;var i,a,o,l,c=this.length-t;switch((!r||c<(r=Number(r)))&&(r=c),n=String(n||"utf8").toLowerCase()){case"hex":i=function(e,t,r,n){r=Number(r)||0;var i=e.length-r;(!n||i<(n=Number(n)))&&(n=i),j((i=t.length)%2==0,"Invalid hex string"),i/2<n&&(n=i/2);for(var a=0;a<n;a++){var o=parseInt(t.substr(2*a,2),16);j(!isNaN(o),"Invalid hex string"),e[r+a]=o}return s._charsWritten=2*a,a}(this,e,t,r);break;case"utf8":case"utf-8":a=this,o=t,l=r,i=s._charsWritten=M(O(e),a,o,l);break;case"ascii":case"binary":i=f(this,e,t,r);break;case"base64":a=this,o=t,l=r,i=s._charsWritten=M(P(e),a,o,l);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":i=p(this,e,t,r);break;default:throw new Error("Unknown encoding")}return i},s.prototype.toString=function(e,t,r){var n,s,i,a,o=this;if(e=String(e||"utf8").toLowerCase(),t=Number(t)||0,(r=void 0!==r?Number(r):o.length)===t)return"";switch(e){case"hex":n=function(e,t,r){var n=e.length;(!t||t<0)&&(t=0),(!r||r<0||n<r)&&(r=n);for(var s="",i=t;i<r;i++)s+=x(e[i]);return s}(o,t,r);break;case"utf8":case"utf-8":n=function(e,t,r){var n="",s="";r=Math.min(e.length,r);for(var i=t;i<r;i++)e[i]<=127?(n+=F(s)+String.fromCharCode(e[i]),s=""):s+="%"+e[i].toString(16);return n+F(s)}(o,t,r);break;case"ascii":case"binary":n=g(o,t,r);break;case"base64":s=o,a=r,n=0===(i=t)&&a===s.length?u.fromByteArray(s):u.fromByteArray(s.slice(i,a));break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":n=function(e,t,r){for(var n=e.slice(t,r),s="",i=0;i<n.length;i+=2)s+=String.fromCharCode(n[i]+256*n[i+1]);return s}(o,t,r);break;default:throw new Error("Unknown encoding")}return n},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},s.prototype.copy=function(e,t,r,n){if(t=t||0,(n=n||0===n?n:this.length)!==(r=r||0)&&0!==e.length&&0!==this.length){j(r<=n,"sourceEnd < sourceStart"),j(0<=t&&t<e.length,"targetStart out of bounds"),j(0<=r&&r<this.length,"sourceStart out of bounds"),j(0<=n&&n<=this.length,"sourceEnd out of bounds"),n>this.length&&(n=this.length);var i=(n=e.length-t<n-r?e.length-t+r:n)-r;if(i<100||!s._useTypedArrays)for(var a=0;a<i;a++)e[a+t]=this[a+r];else e._set(this.subarray(r,r+i),t)}},s.prototype.slice=function(e,t){var r=this.length;if(e=R(e,r,0),t=R(t,r,r),s._useTypedArrays)return s._augment(this.subarray(e,t));for(var n=t-e,i=new s(n,void 0,!0),a=0;a<n;a++)i[a]=this[a+e];return i},s.prototype.get=function(e){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(e)},s.prototype.set=function(e,t){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(e,t)},s.prototype.readUInt8=function(e,t){if(t||(j(null!=e,"missing offset"),j(e<this.length,"Trying to read beyond buffer length")),!(e>=this.length))return this[e]},s.prototype.readUInt16LE=function(e,t){return m(this,e,!0,t)},s.prototype.readUInt16BE=function(e,t){return m(this,e,!1,t)},s.prototype.readUInt32LE=function(e,t){return y(this,e,!0,t)},s.prototype.readUInt32BE=function(e,t){return y(this,e,!1,t)},s.prototype.readInt8=function(e,t){if(t||(j(null!=e,"missing offset"),j(e<this.length,"Trying to read beyond buffer length")),!(e>=this.length))return 128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){return v(this,e,!0,t)},s.prototype.readInt16BE=function(e,t){return v(this,e,!1,t)},s.prototype.readInt32LE=function(e,t){return b(this,e,!0,t)},s.prototype.readInt32BE=function(e,t){return b(this,e,!1,t)},s.prototype.readFloatLE=function(e,t){return w(this,e,!0,t)},s.prototype.readFloatBE=function(e,t){return w(this,e,!1,t)},s.prototype.readDoubleLE=function(e,t){return E(this,e,!0,t)},s.prototype.readDoubleBE=function(e,t){return E(this,e,!1,t)},s.prototype.writeUInt8=function(e,t,r){r||(j(null!=e,"missing value"),j(null!=t,"missing offset"),j(t<this.length,"trying to write beyond buffer length"),U(e,255)),t>=this.length||(this[t]=e)},s.prototype.writeUInt16LE=function(e,t,r){S(this,e,t,!0,r)},s.prototype.writeUInt16BE=function(e,t,r){S(this,e,t,!1,r)},s.prototype.writeUInt32LE=function(e,t,r){T(this,e,t,!0,r)},s.prototype.writeUInt32BE=function(e,t,r){T(this,e,t,!1,r)},s.prototype.writeInt8=function(e,t,r){r||(j(null!=e,"missing value"),j(null!=t,"missing offset"),j(t<this.length,"Trying to write beyond buffer length"),N(e,127,-128)),t>=this.length||(0<=e?this.writeUInt8(e,t,r):this.writeUInt8(255+e+1,t,r))},s.prototype.writeInt16LE=function(e,t,r){C(this,e,t,!0,r)},s.prototype.writeInt16BE=function(e,t,r){C(this,e,t,!1,r)},s.prototype.writeInt32LE=function(e,t,r){k(this,e,t,!0,r)},s.prototype.writeInt32BE=function(e,t,r){k(this,e,t,!1,r)},s.prototype.writeFloatLE=function(e,t,r){A(this,e,t,!0,r)},s.prototype.writeFloatBE=function(e,t,r){A(this,e,t,!1,r)},s.prototype.writeDoubleLE=function(e,t,r){I(this,e,t,!0,r)},s.prototype.writeDoubleBE=function(e,t,r){I(this,e,t,!1,r)},s.prototype.fill=function(e,t,r){if(t=t||0,r=r||this.length,j("number"==typeof(e="string"==typeof(e=e||0)?e.charCodeAt(0):e)&&!isNaN(e),"value is not a number"),j(t<=r,"end < start"),r!==t&&0!==this.length){j(0<=t&&t<this.length,"start out of bounds"),j(0<=r&&r<=this.length,"end out of bounds");for(var n=t;n<r;n++)this[n]=e}},s.prototype.inspect=function(){for(var e=[],t=this.length,n=0;n<t;n++)if(e[n]=x(this[n]),n===r.INSPECT_MAX_BYTES){e[n+1]="...";break}return"<Buffer "+e.join(" ")+">"},s.prototype.toArrayBuffer=function(){if("undefined"==typeof Uint8Array)throw new Error("Buffer.toArrayBuffer not supported in this browser");if(s._useTypedArrays)return new s(this).buffer;for(var e=new Uint8Array(this.length),t=0,r=e.length;t<r;t+=1)e[t]=this[t];return e.buffer};var _=s.prototype;function R(e,t,r){return"number"!=typeof e?r:t<=(e=~~e)?t:0<=e||0<=(e+=t)?e:0}function L(e){return(e=~~Math.ceil(+e))<0?0:e}function D(e){return(Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)})(e)}function x(e){return e<16?"0"+e.toString(16):e.toString(16)}function O(e){for(var t=[],r=0;r<e.length;r++){var n=e.charCodeAt(r);if(n<=127)t.push(e.charCodeAt(r));else for(var s=r,i=(55296<=n&&n<=57343&&r++,encodeURIComponent(e.slice(s,r+1)).substr(1).split("%")),a=0;a<i.length;a++)t.push(parseInt(i[a],16))}return t}function P(e){return u.toByteArray(e)}function M(e,t,r,n){for(var s=0;s<n&&!(s+r>=t.length||s>=e.length);s++)t[s+r]=e[s];return s}function F(e){try{return decodeURIComponent(e)}catch(e){return String.fromCharCode(65533)}}function U(e,t){j("number"==typeof e,"cannot write a non-number as a number"),j(0<=e,"specified a negative value for writing an unsigned value"),j(e<=t,"value is larger than maximum value for type"),j(Math.floor(e)===e,"value has a fractional component")}function N(e,t,r){j("number"==typeof e,"cannot write a non-number as a number"),j(e<=t,"value larger than maximum allowed value"),j(r<=e,"value smaller than minimum allowed value"),j(Math.floor(e)===e,"value has a fractional component")}function B(e,t,r){j("number"==typeof e,"cannot write a non-number as a number"),j(e<=t,"value larger than maximum allowed value"),j(r<=e,"value smaller than minimum allowed value")}function j(e,t){if(!e)throw new Error(t||"Failed assertion")}s._augment=function(e){return e._isBuffer=!0,e._get=e.get,e._set=e.set,e.get=_.get,e.set=_.set,e.write=_.write,e.toString=_.toString,e.toLocaleString=_.toString,e.toJSON=_.toJSON,e.copy=_.copy,e.slice=_.slice,e.readUInt8=_.readUInt8,e.readUInt16LE=_.readUInt16LE,e.readUInt16BE=_.readUInt16BE,e.readUInt32LE=_.readUInt32LE,e.readUInt32BE=_.readUInt32BE,e.readInt8=_.readInt8,e.readInt16LE=_.readInt16LE,e.readInt16BE=_.readInt16BE,e.readInt32LE=_.readInt32LE,e.readInt32BE=_.readInt32BE,e.readFloatLE=_.readFloatLE,e.readFloatBE=_.readFloatBE,e.readDoubleLE=_.readDoubleLE,e.readDoubleBE=_.readDoubleBE,e.writeUInt8=_.writeUInt8,e.writeUInt16LE=_.writeUInt16LE,e.writeUInt16BE=_.writeUInt16BE,e.writeUInt32LE=_.writeUInt32LE,e.writeUInt32BE=_.writeUInt32BE,e.writeInt8=_.writeInt8,e.writeInt16LE=_.writeInt16LE,e.writeInt16BE=_.writeInt16BE,e.writeInt32LE=_.writeInt32LE,e.writeInt32BE=_.writeInt32BE,e.writeFloatLE=_.writeFloatLE,e.writeFloatBE=_.writeFloatBE,e.writeDoubleLE=_.writeDoubleLE,e.writeDoubleBE=_.writeDoubleBE,e.fill=_.fill,e.inspect=_.inspect,e.toArrayBuffer=_.toArrayBuffer,e}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/buffer/index.js","/node_modules/gulp-browserify/node_modules/buffer")},{"base64-js":2,buffer:3,ieee754:10,lYpoI2:11}],4:[function(e,t,r){(function(r,n,s,i,a,o,l,c,d){s=e("buffer").Buffer;var u=4,h=new s(u);h.fill(0),t.exports={hash:function(e,t,r,n){for(var i=t(function(e,t){e.length%u!=0&&(r=e.length+(u-e.length%u),e=s.concat([e,h],r));for(var r,n=[],i=t?e.readInt32BE:e.readInt32LE,a=0;a<e.length;a+=u)n.push(i.call(e,a));return n}(e=s.isBuffer(e)?e:new s(e),n),8*e.length),a=(t=n,new s(r)),o=t?a.writeInt32BE:a.writeInt32LE,l=0;l<i.length;l++)o.call(a,i[l],4*l,!0);return a}}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/helpers.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],5:[function(e,t,r){(function(t,n,s,i,a,o,l,c,d){s=e("buffer").Buffer;var u=e("./sha"),h=e("./sha256"),f=e("./rng"),p={sha1:u,sha256:h,md5:e("./md5")},g=64,m=new s(g);function y(e,t){var r=p[e=e||"sha1"],n=[];return r||v("algorithm:",e,"is not yet supported"),{update:function(e){return s.isBuffer(e)||(e=new s(e)),n.push(e),e.length,this},digest:function(e){var i=s.concat(n);return i=t?function(e,t,r){s.isBuffer(t)||(t=new s(t)),s.isBuffer(r)||(r=new s(r)),t.length>g?t=e(t):t.length<g&&(t=s.concat([t,m],g));for(var n=new s(g),i=new s(g),a=0;a<g;a++)n[a]=54^t[a],i[a]=92^t[a];return r=e(s.concat([n,r])),e(s.concat([i,r]))}(r,t,i):r(i),n=null,e?i.toString(e):i}}}function v(){var e=[].slice.call(arguments).join(" ");throw new Error([e,"we accept pull requests","http://github.com/dominictarr/crypto-browserify"].join("\n"))}m.fill(0),r.createHash=function(e){return y(e)},r.createHmac=y,r.randomBytes=function(e,t){if(!t||!t.call)return new s(f(e));try{t.call(this,void 0,new s(f(e)))}catch(e){t(e)}};var b,w=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],E=function(e){r[e]=function(){v("sorry,",e,"is not implemented yet")}};for(b in w)E(w[b])}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/index.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./md5":6,"./rng":7,"./sha":8,"./sha256":9,buffer:3,lYpoI2:11}],6:[function(e,t,r){(function(r,n,s,i,a,o,l,c,d){var u=e("./helpers");function h(e,t){e[t>>5]|=128<<t%32,e[14+(t+64>>>9<<4)]=t;for(var r=1732584193,n=-271733879,s=-1732584194,i=271733878,a=0;a<e.length;a+=16){var o=r,l=n,c=s,d=i;r=p(r,n,s,i,e[a+0],7,-680876936),i=p(i,r,n,s,e[a+1],12,-389564586),s=p(s,i,r,n,e[a+2],17,606105819),n=p(n,s,i,r,e[a+3],22,-1044525330),r=p(r,n,s,i,e[a+4],7,-176418897),i=p(i,r,n,s,e[a+5],12,1200080426),s=p(s,i,r,n,e[a+6],17,-1473231341),n=p(n,s,i,r,e[a+7],22,-45705983),r=p(r,n,s,i,e[a+8],7,1770035416),i=p(i,r,n,s,e[a+9],12,-1958414417),s=p(s,i,r,n,e[a+10],17,-42063),n=p(n,s,i,r,e[a+11],22,-1990404162),r=p(r,n,s,i,e[a+12],7,1804603682),i=p(i,r,n,s,e[a+13],12,-40341101),s=p(s,i,r,n,e[a+14],17,-1502002290),r=g(r,n=p(n,s,i,r,e[a+15],22,1236535329),s,i,e[a+1],5,-165796510),i=g(i,r,n,s,e[a+6],9,-1069501632),s=g(s,i,r,n,e[a+11],14,643717713),n=g(n,s,i,r,e[a+0],20,-373897302),r=g(r,n,s,i,e[a+5],5,-701558691),i=g(i,r,n,s,e[a+10],9,38016083),s=g(s,i,r,n,e[a+15],14,-660478335),n=g(n,s,i,r,e[a+4],20,-405537848),r=g(r,n,s,i,e[a+9],5,568446438),i=g(i,r,n,s,e[a+14],9,-1019803690),s=g(s,i,r,n,e[a+3],14,-187363961),n=g(n,s,i,r,e[a+8],20,1163531501),r=g(r,n,s,i,e[a+13],5,-1444681467),i=g(i,r,n,s,e[a+2],9,-51403784),s=g(s,i,r,n,e[a+7],14,1735328473),r=m(r,n=g(n,s,i,r,e[a+12],20,-1926607734),s,i,e[a+5],4,-378558),i=m(i,r,n,s,e[a+8],11,-2022574463),s=m(s,i,r,n,e[a+11],16,1839030562),n=m(n,s,i,r,e[a+14],23,-35309556),r=m(r,n,s,i,e[a+1],4,-1530992060),i=m(i,r,n,s,e[a+4],11,1272893353),s=m(s,i,r,n,e[a+7],16,-155497632),n=m(n,s,i,r,e[a+10],23,-1094730640),r=m(r,n,s,i,e[a+13],4,681279174),i=m(i,r,n,s,e[a+0],11,-358537222),s=m(s,i,r,n,e[a+3],16,-722521979),n=m(n,s,i,r,e[a+6],23,76029189),r=m(r,n,s,i,e[a+9],4,-640364487),i=m(i,r,n,s,e[a+12],11,-421815835),s=m(s,i,r,n,e[a+15],16,530742520),r=y(r,n=m(n,s,i,r,e[a+2],23,-995338651),s,i,e[a+0],6,-198630844),i=y(i,r,n,s,e[a+7],10,1126891415),s=y(s,i,r,n,e[a+14],15,-1416354905),n=y(n,s,i,r,e[a+5],21,-57434055),r=y(r,n,s,i,e[a+12],6,1700485571),i=y(i,r,n,s,e[a+3],10,-1894986606),s=y(s,i,r,n,e[a+10],15,-1051523),n=y(n,s,i,r,e[a+1],21,-2054922799),r=y(r,n,s,i,e[a+8],6,1873313359),i=y(i,r,n,s,e[a+15],10,-30611744),s=y(s,i,r,n,e[a+6],15,-1560198380),n=y(n,s,i,r,e[a+13],21,1309151649),r=y(r,n,s,i,e[a+4],6,-145523070),i=y(i,r,n,s,e[a+11],10,-1120210379),s=y(s,i,r,n,e[a+2],15,718787259),n=y(n,s,i,r,e[a+9],21,-343485551),r=v(r,o),n=v(n,l),s=v(s,c),i=v(i,d)}return Array(r,n,s,i)}function f(e,t,r,n,s,i){return v((t=v(v(t,e),v(n,i)))<<s|t>>>32-s,r)}function p(e,t,r,n,s,i,a){return f(t&r|~t&n,e,t,s,i,a)}function g(e,t,r,n,s,i,a){return f(t&n|r&~n,e,t,s,i,a)}function m(e,t,r,n,s,i,a){return f(t^r^n,e,t,s,i,a)}function y(e,t,r,n,s,i,a){return f(r^(t|~n),e,t,s,i,a)}function v(e,t){var r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}t.exports=function(e){return u.hash(e,h,16)}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/md5.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],7:[function(e,t,r){(function(e,r,n,s,i,a,o,l,c){t.exports=function(e){for(var t,r=new Array(e),n=0;n<e;n++)0==(3&n)&&(t=4294967296*Math.random()),r[n]=t>>>((3&n)<<3)&255;return r}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/rng.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],8:[function(e,t,r){(function(r,n,s,i,a,o,l,c,d){var u=e("./helpers");function h(e,t){e[t>>5]|=128<<24-t%32,e[15+(t+64>>9<<4)]=t;for(var r,n,s,i=Array(80),a=1732584193,o=-271733879,l=-1732584194,c=271733878,d=-1009589776,u=0;u<e.length;u+=16){for(var h=a,g=o,m=l,y=c,v=d,b=0;b<80;b++){i[b]=b<16?e[u+b]:p(i[b-3]^i[b-8]^i[b-14]^i[b-16],1);var w=f(f(p(a,5),(w=o,n=l,s=c,(r=b)<20?w&n|~w&s:!(r<40)&&r<60?w&n|w&s|n&s:w^n^s)),f(f(d,i[b]),(r=b)<20?1518500249:r<40?1859775393:r<60?-1894007588:-899497514));d=c,c=l,l=p(o,30),o=a,a=w}a=f(a,h),o=f(o,g),l=f(l,m),c=f(c,y),d=f(d,v)}return Array(a,o,l,c,d)}function f(e,t){var r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function p(e,t){return e<<t|e>>>32-t}t.exports=function(e){return u.hash(e,h,20,!0)}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],9:[function(e,t,r){(function(r,n,s,i,a,o,l,c,d){function u(e,t){var r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function h(e,t){var r,n=new Array(1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298),s=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),i=new Array(64);e[t>>5]|=128<<24-t%32,e[15+(t+64>>9<<4)]=t;for(var a,o,l=0;l<e.length;l+=16){for(var c=s[0],d=s[1],h=s[2],f=s[3],m=s[4],y=s[5],v=s[6],b=s[7],w=0;w<64;w++)i[w]=w<16?e[w+l]:u(u(u((o=i[w-2],p(o,17)^p(o,19)^g(o,10)),i[w-7]),(o=i[w-15],p(o,7)^p(o,18)^g(o,3))),i[w-16]),r=u(u(u(u(b,p(o=m,6)^p(o,11)^p(o,25)),m&y^~m&v),n[w]),i[w]),a=u(p(a=c,2)^p(a,13)^p(a,22),c&d^c&h^d&h),b=v,v=y,y=m,m=u(f,r),f=h,h=d,d=c,c=u(r,a);s[0]=u(c,s[0]),s[1]=u(d,s[1]),s[2]=u(h,s[2]),s[3]=u(f,s[3]),s[4]=u(m,s[4]),s[5]=u(y,s[5]),s[6]=u(v,s[6]),s[7]=u(b,s[7])}return s}var f=e("./helpers"),p=function(e,t){return e>>>t|e<<32-t},g=function(e,t){return e>>>t};t.exports=function(e){return f.hash(e,h,32,!0)}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha256.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],10:[function(e,t,r){(function(e,t,n,s,i,a,o,l,c){r.read=function(e,t,r,n,s){var i,a,o=8*s-n-1,l=(1<<o)-1,c=l>>1,d=-7,u=r?s-1:0,h=r?-1:1;for(s=e[t+u],u+=h,i=s&(1<<-d)-1,s>>=-d,d+=o;0<d;i=256*i+e[t+u],u+=h,d-=8);for(a=i&(1<<-d)-1,i>>=-d,d+=n;0<d;a=256*a+e[t+u],u+=h,d-=8);if(0===i)i=1-c;else{if(i===l)return a?NaN:1/0*(s?-1:1);a+=Math.pow(2,n),i-=c}return(s?-1:1)*a*Math.pow(2,i-n)},r.write=function(e,t,r,n,s,i){var a,o,l=8*i-s-1,c=(1<<l)-1,d=c>>1,u=23===s?Math.pow(2,-24)-Math.pow(2,-77):0,h=n?0:i-1,f=n?1:-1;for(i=t<0||0===t&&1/t<0?1:0,t=Math.abs(t),isNaN(t)||t===1/0?(o=isNaN(t)?1:0,a=c):(a=Math.floor(Math.log(t)/Math.LN2),t*(n=Math.pow(2,-a))<1&&(a--,n*=2),2<=(t+=1<=a+d?u/n:u*Math.pow(2,1-d))*n&&(a++,n/=2),c<=a+d?(o=0,a=c):1<=a+d?(o=(t*n-1)*Math.pow(2,s),a+=d):(o=t*Math.pow(2,d-1)*Math.pow(2,s),a=0));8<=s;e[r+h]=255&o,h+=f,o/=256,s-=8);for(a=a<<s|o,l+=s;0<l;e[r+h]=255&a,h+=f,a/=256,l-=8);e[r+h-f]|=128*i}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/ieee754/index.js","/node_modules/gulp-browserify/node_modules/ieee754")},{buffer:3,lYpoI2:11}],11:[function(e,t,r){(function(e,r,n,s,i,a,o,l,c){var d,u,h;function f(){}(e=t.exports={}).nextTick=(u="undefined"!=typeof window&&window.setImmediate,h="undefined"!=typeof window&&window.postMessage&&window.addEventListener,u?function(e){return window.setImmediate(e)}:h?(d=[],window.addEventListener("message",(function(e){var t=e.source;t!==window&&null!==t||"process-tick"!==e.data||(e.stopPropagation(),0<d.length&&d.shift()())}),!0),function(e){d.push(e),window.postMessage("process-tick","*")}):function(e){setTimeout(e,0)}),e.title="browser",e.browser=!0,e.env={},e.argv=[],e.on=f,e.addListener=f,e.once=f,e.off=f,e.removeListener=f,e.removeAllListeners=f,e.emit=f,e.binding=function(e){throw new Error("process.binding is not supported")},e.cwd=function(){return"/"},e.chdir=function(e){throw new Error("process.chdir is not supported")}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/process/browser.js","/node_modules/gulp-browserify/node_modules/process")},{buffer:3,lYpoI2:11}]},{},[1])(1)}(rh);var nh=rh.exports;class sh{constructor(e){const{http:t}=ve();this.queryParams=e,this.http=t}loadFirstPage(){return this.onFetch("first")}loadNextPage(){return this.onFetch("next")}loadPreviousPage(){return this.onFetch("prev")}async onFetch(e="first"){var t,r,n,s;if("prev"===e&&!this.previousToken)return;if("next"===e&&!this.nextToken)return;let i;"prev"===e&&(i=this.previousToken),"next"===e&&(i=this.nextToken);const a=await this.getRequest(this.queryParams,i);return"first"===e&&(this.nextToken=null===(t=a.paging)||void 0===t?void 0:t.next,this.previousToken=null===(r=a.paging)||void 0===r?void 0:r.previous),"prev"===e&&(this.previousToken=null===(n=a.paging)||void 0===n?void 0:n.previous),"next"===e&&(this.nextToken=null===(s=a.paging)||void 0===s?void 0:s.next),a}getNextToken(){return this.nextToken}getPrevToken(){return this.previousToken}}class ih extends sh{async getRequest(e,t){const r=Ml(e),{data:n}=await this.http.get("/api/v5/messages",{params:Object.assign(Object.assign({},r),{options:t?{token:t}:Object.assign({},r.options)})});return n}}class ah{constructor(e,t){this.query=e,this.cacheKey=t}}class oh extends ah{constructor(e,t,r,n,s){super(e,t),this.notifyChange=r,this.preparePayload=n,this.paginationController=s}async saveToMainDB(e){const t=await this.preparePayload(e),r=ve(),n=r.cache&&Date.now();r.cache&&Oo(t,{cachedAt:n})}appendToQueryStream(e,t,r=!1){var n,s;if(r)Se(this.cacheKey,{data:e.messages.map(de("message")),query:this.query});else{const r=null===(n=Ee(this.cacheKey))||void 0===n?void 0:n.data,i=null!==(s=null==r?void 0:r.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},r),{data:"next"===t?[...new Set([...i,...e.messages.map(de("message"))])]:[...new Set([...e.messages.map(de("message")),...i])]}))}}reactor(e){return t=>{var r,n,s,i,a;if("onCreate"===e){const e=null===(r=Ee(this.cacheKey))||void 0===r?void 0:r.data;if(!e)return;if(this.query.subChannelId!==(null==t?void 0:t.subChannelId)||!e)return;if(this.query.type&&this.query.type!==t.dataType)return;if(this.query.dataType&&this.query.dataType!==t.dataType)return;if(this.query.excludingTags&&(null===(n=this.query.excludingTags)||void 0===n?void 0:n.some((e=>{var r;return null===(r=t.tags)||void 0===r?void 0:r.includes(e)}))))return;if(this.query.excludeTags&&(null===(s=this.query.excludeTags)||void 0===s?void 0:s.some((e=>{var r;return null===(r=t.tags)||void 0===r?void 0:r.includes(e)}))))return;if(!!this.query.hasFlags!=!!t.flagCount)return;if(this.query.parentId&&this.query.parentId!==t.parentId)return;if(this.query.hasOwnProperty("includeDeleted")&&!this.query.includeDeleted&&t.isDeleted)return;if(this.query.includingTags&&!(null===(i=this.query.includingTags)||void 0===i?void 0:i.some((e=>{var r;return null===(r=t.tags)||void 0===r?void 0:r.includes(e)}))))return;if(this.query.tags&&!(null===(a=this.query.tags)||void 0===a?void 0:a.some((e=>{var r;return null===(r=t.tags)||void 0===r?void 0:r.includes(e)}))))return;this.query.sortBy&&"segmentDesc"!==this.query.sortBy||this.paginationController.getPrevToken()||(e.data=[...new Set([t.messageId,...e.data])]),"segmentAsc"!==this.query.sortBy||this.paginationController.getNextToken()||(e.data=[...new Set([...e.data,t.messageId])]),Se(this.cacheKey,e)}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class lh{constructor(e){const{http:t}=ve();this.queryParams=e,this.http=t}async onFetch(){return await this.getRequest(this.queryParams)}}class ch{constructor(e,t,r,n){this.paginationController=e,this.queryStreamId=t,this.cacheKey=r,this.callback=n}async refresh(){try{let e;if(e=this.paginationController instanceof lh?await this.paginationController.onFetch():await this.paginationController.loadFirstPage(),!e)return;await this.persistModel(e),this.persistQueryStream({response:e,direction:"next",refresh:!0}),this.notifyChange({origin:"server",loading:!1})}catch(e){this.notifyChange({origin:"server",loading:!1,error:e})}}loadPage(e=!1,t="next"){this.setup(),this.notifyChange({origin:"local",loading:!0}),e?this.refresh():"prev"===t?this.loadPrevPage():"next"===t&&this.loadNextPage()}async loadNextPage(){try{if(this.paginationController instanceof lh)return;const e=await this.paginationController.loadNextPage();if(!e)return;await this.persistModel(e),this.persistQueryStream({response:e,direction:"next"}),this.notifyChange({origin:"server",loading:!1})}catch(e){this.notifyChange({origin:"server",loading:!1,error:e})}}async loadPrevPage(){try{if(this.paginationController instanceof lh)return;const e=await this.paginationController.loadPreviousPage();if(!e)return;await this.persistModel(e),this.persistQueryStream({response:e,direction:"prev"}),this.notifyChange({origin:"server",loading:!1})}catch(e){this.notifyChange({origin:"server",loading:!1,error:e})}}shouldNotify(e){return!fd(this.snapshot,e)&&(this.snapshot=e.map((e=>hd(e))),!0)}getCacheKey(){return this.cacheKey}}class dh extends ch{constructor(e,t){const r=nh(e),n=["message","collection",r];super(new ih(e),r,n,t),this.query=e,this.queryStreamController=new oh(this.query,this.cacheKey,this.notifyChange.bind(this),Ol,this.paginationController),this.callback=t.bind(this),this.loadPage(!0)}setup(){var e;(null===(e=Ee(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],query:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:r}){this.queryStreamController.appendToQueryStream(e,t,r)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Dc,action:"onCreate"},{fn:Pu,action:"onDelete"},{fn:Ou,action:"onUpdate"},{fn:Qu,action:"onFlagged"},{fn:Xu,action:"onUnflagged"},{fn:Ju,action:"onFlagCleared"},{fn:Zu,action:"onReactionAdded"},{fn:eh,action:"onReactionRemoved"},{fn:xu(dd,"contentId","message"),action:"onUpdate"},{fn:xu(ud,"contentId","message"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:r}){var n,s;const i=null===(n=Ee(this.cacheKey))||void 0===n?void 0:n.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>Ee(["message","get",e]))).filter(Boolean).map((({data:e})=>e)).map((e=>il.message(e))))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage(!1,"next"),onPrevPage:()=>this.loadPage(!1,"prev"),data:a,hasNextPage:!!this.paginationController.getNextToken(),hasPrevPage:!!this.paginationController.getPrevToken(),loading:t,error:r})}applyFilter(e){let t=e;return t=t.filter((e=>!this.query.tags||this.query.tags.find((t=>!!e.tags&&e.tags.includes(t))))),t=t.filter((e=>!this.query.excludeTags||(this.query.excludeTags||[]).find((t=>!e.tags||!e.tags.includes(t))))),this.query.includeDeleted||(t=Ae(t,"isDeleted",!1)),t=t.sort(((e,t)=>"segmentAsc"===this.query.sortBy?e.channelSegment-t.channelSegment:"segmentDesc"===this.query.sortBy?t.channelSegment-e.channelSegment:0)),t}}const uh=async(e,t=!1)=>{const r=ve();let n;r.log("message/getMessage",e),t||console.log("getMessage will be deprecated on 15th November 2022, please use liveMessage instead."),ql("message",e);try{const{data:t}=await r.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);n=await Ol(t)}catch(t){throw C(null==t?void 0:t.code)&&Po("message",e),t}const s=r.cache&&Date.now();r.cache&&Oo(n,{cachedAt:s});const{messages:i}=n;return Je("local.message.fetched",{messages:i}),{data:il.message(i.find((t=>t.messageId===e))),cachedAt:s}};uh.locally=e=>{const t=ve();if(t.log("message/getMessage.locally",e),!t.cache)return;const r=Ee(["message","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};var hh=Object.freeze({__proto__:null,getMessageByIds:ju,createMessage:Ku,updateMessage:Gu,editMessage:Hu,deleteMessage:Vu,softDeleteMessage:zu,markAsDelivered:async(e,t)=>{const r=ve();r.log("message/markAsDelivered",e,t);const{data:n}=await r.http.put(`/api/v1/markers/message-feeds/${e}/mark-delivering`,{messageId:t}),{userMarkers:s,userEntityMarkers:i,userFeedMarkers:a}=n,o=Mo(n,["userMarkers","userEntityMarkers","userFeedMarkers"]),l=r.cache&&Date.now();return r.cache&&Oo(Object.assign({userMarkers:s,userEntityMarkers:Bo(i),userFeedMarkers:jo(a)},o),{cachedAt:l}),!0},getReadUsers:Wu,getDeliveredUsers:Yu,flagMessage:async e=>{const t=ve();t.log("message/flag",e);const{data:r}=await t.http.post(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await Ol(r);Oo(e)}return Je("message.flagged",r),!!r},unflagMessage:async e=>{const t=ve();t.log("message/unflag",e);const{data:r}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await Ol(r);Oo(e)}return Je("message.unflagged",r),!!r},isMessageFlaggedByMe:async e=>{const t=ve();t.log("message/isMessageFlaggedByMe",e);const{data:r}=await t.http.get(`/api/v5/messages/${encodeURIComponent(e)}/flags`);return r.result},onMessageCreatedMqtt:Dc,onMessageCreatedLocal:xc,onMessageUpdated:Ou,onMessageDeleted:Pu,onMessageFlagged:Qu,onMessageUnflagged:Xu,onMessageFlagCleared:Ju,onMessageReactionAdded:Zu,onMessageReactionRemoved:eh,onMessageFetched:th,getMessage:(e,t)=>pd(e,(e=>{const{data:r}=e;t(Object.assign(Object.assign({},e),{data:r?il.message(e.data):r}))}),"messageId",Jd,[th,Ou,Pu,Qu,Xu,Ju,Zu,eh,xu(dd,"contentId","message"),xu(ud,"contentId","message")]),getMessages:(e,t,r)=>{const{log:n,cache:s}=ve();s||console.log(p);const i=Date.now();n(`getMessages(tmpid: ${i}) > listen`);const a=new dh(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>{ke(l)})),()=>{n(`getMessages(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},observeMessage:(e,t,r="cache_then_server")=>{const{log:n}=ve(),s=Date.now();n(`observeMessage(tmpid: ${s}) > listen`),console.log("observeMessage will be deprecated on 15th November 2022, please use liveMessage instead.");const i=(r,n)=>{var s,i,a;if((null===(s=r.data)||void 0===s?void 0:s.messageId)===e){if(t instanceof Function)return t(r);"onFetch"!==n&&(null===(i=t.onEvent)||void 0===i||i.call(t,n,r)),null===(a=t[n])||void 0===a||a.call(t,r)}},a=[];return a.push(Ou((e=>i({data:il.message(e),loading:!1,origin:"event"},"onUpdate"))),Pu((e=>i({data:il.message(e),loading:!1,origin:"event"},"onDelete"))),xu(dd,"contentId","message")((e=>i({data:il.message(e),loading:!1,origin:"event"},"onUpdate"))),xu(ud,"contentId","message")((e=>i({data:il.message(e),loading:!1,origin:"event"},"onUpdate")))),"no_fetch"!==r&&oe(ie(uh,e),(e=>e.data&&i(e,"onFetch")),ae(r)),()=>{n(`observeMessages(tmpid: ${s}) > dispose`),a.forEach((e=>e()))}},observeMessages:(e,t)=>{const{log:r}=ve(),n=Date.now();r(`observeMessages(tmpid: ${n}) > listen`);const s=[],i=(r,n)=>{var s,i,a;if((null===(s=r.data)||void 0===s?void 0:s.subChannelId)===e){if(t instanceof Function)return t(r);null===(i=t.onEvent)||void 0===i||i.call(t,n,r),null===(a=t[n])||void 0===a||a.call(t,r)}};return s.push(Dc((e=>i({data:il.message(e),loading:!1,origin:"event"},"onCreate"))),xc((e=>i({data:il.message(e),loading:!1,origin:"event"},"onCreate"))),Ou((e=>i({data:il.message(e),loading:!1,origin:"event"},"onUpdate"))),Pu((e=>i({data:il.message(e),loading:!1,origin:"event"},"onDelete"))),xu(dd,"contentId","message")((e=>i({data:il.message(e),loading:!1,origin:"event"},"onCreate"))),xu(ud,"contentId","message")((e=>i({data:il.message(e),loading:!1,origin:"event"},"onCreate")))),()=>{r(`observeMessages(tmpid: ${n}) > dispose`),s.forEach((e=>e()))}},convertFromRaw:Dl,prepareMessagePayload:Ol,convertParams:Pl,convertQueryParams:Ml});class fh extends sh{async getRequest(e,t){var r;const{limit:n=h}=e,s=null!==(r=function(e){var{excludeDefaultSubChannel:t}=e,r=Mo(e,["excludeDefaultSubChannel"]);const n=Object.assign({},r);return void 0!==t&&(n.excludeDefaultMessageFeed=t),n}(Mo(e,["limit"])))&&void 0!==r?r:{},{channelId:i,includeDeleted:a}=s,o=Mo(s,["channelId","includeDeleted"]),l=t?{token:t}:{limit:n},{data:c}=await this.http.get(`/api/v5/message-feeds/channel/${i}`,{params:Object.assign(Object.assign({},o),{isDeleted:Al(a),options:l})});return c}}class ph extends ah{constructor(e,t,r,n){super(e,t),this.notifyChange=r,this.preparePayload=n}async saveToMainDB(e){const t=await this.preparePayload(e),r=ve(),n=r.cache&&Date.now();r.cache&&Oo(t,{cachedAt:n})}appendToQueryStream(e,t,r=!1){var n,s;if(r)Se(this.cacheKey,{data:e.messageFeeds.map((({messageFeedId:e})=>e))});else{const t=null===(n=Ee(this.cacheKey))||void 0===n?void 0:n.data,r=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...r,...e.messageFeeds.map((({messageFeedId:e})=>e))])]}))}}reactor(e){return t=>{var r;const n=null===(r=Ee(this.cacheKey))||void 0===r?void 0:r.data;if(n){if(!Array.isArray(t)){if(this.query.channelId!==t.channelId)return;"onCreate"===e&&(n.data=[...new Set([t.subChannelId,...n.data])]),Se(this.cacheKey,n)}this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class gh extends ch{constructor(e,t){const r=nh(e),n=["subChannel","collection",r];super(new fh(e),r,n,t),this.query=e,this.queryStreamController=new ph(this.query,this.cacheKey,this.notifyChange.bind(this),Nl),this.callback=t.bind(this),this.loadPage(!0)}setup(){var e;(null===(e=Ee(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[]})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:r}){this.queryStreamController.appendToQueryStream(e,t,r)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Bu,action:"onCreate"},{fn:Oc,action:"onCreate"},{fn:Pc,action:"onDelete"},{fn:e=>Mu((async t=>{var r;const n=null===(r=Ee(this.cacheKey))||void 0===r?void 0:r.data;if(!n||!n.data.includes(t.subChannelId))return;const s=ve();if("no-message-preview"!==await s.getMessagePreviewSetting(!1)){const e=ll(t.subChannelId);(null==e?void 0:e.subChannelId)===t.subChannelId&&Se(["messagePreviewSubChannel","get",t.subChannelId],Object.assign(Object.assign({},e),{subChannelName:t.displayName,subChannelUpdatedAt:t.updatedAt}))}e(t)})),action:"onUpdate"},{fn:e=>Dc((async t=>{var r,n;const s=Ee(["subChannel","get",t.subChannelId]);if(!s)return;const i=null===(r=Ee(this.cacheKey))||void 0===r?void 0:r.data;if(!i||!i.data.includes(t.subChannelId))return;const a=ve();if("no-message-preview"===await a.getMessagePreviewSetting(!1))return;fl(t);const o=null===(n=Ee(["subChannel","get",t.subChannelId]))||void 0===n?void 0:n.data;o&&(hl(t.subChannelId,o,{lastActivity:t.createdAt,messagePreviewId:t.messageId}),e(Object.assign(Object.assign({},s.data),{messagePreviewId:t.messageId,subChannelId:t.subChannelId,lastActivity:t.createdAt})))})),action:"onUpdate"},{fn:e=>xc((async t=>{var r,n;const s=Ee(["subChannel","get",t.subChannelId]);if(!s)return;const i=null===(r=Ee(this.cacheKey))||void 0===r?void 0:r.data;if(!i||!i.data.includes(t.subChannelId))return;const a=ve();if("no-message-preview"===await a.getMessagePreviewSetting(!1))return;fl(t);const o=null===(n=Ee(["subChannel","get",t.subChannelId]))||void 0===n?void 0:n.data;o&&(hl(t.subChannelId,o,{lastActivity:t.createdAt,messagePreviewId:t.messageId}),e(Object.assign(Object.assign({},s.data),{messagePreviewId:t.messageId,subChannelId:t.subChannelId,lastActivity:t.createdAt})))})),action:"onUpdate"},{fn:e=>od((t=>{var r;const n=null!==(r=t.map((({feedId:e})=>Ee(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];0!==n.length&&e(n)})),action:"onUpdate"},{fn:xu(ad,"feedId","subChannel"),action:"onUpdate"},{fn:xu((e=>Ou((async t=>{var r;const n=ve();if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;const s=null===(r=Ee(this.cacheKey))||void 0===r?void 0:r.data;s&&s.data.includes(t.subChannelId)&&(pl(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:xu((e=>Pu((async t=>{var r;const n=ve(),s=await n.getMessagePreviewSetting(!1);if("no-message-preview"===s)return;const i=null===(r=Ee(this.cacheKey))||void 0===r?void 0:r.data;i&&i.data.includes(t.subChannelId)&&("message-preview-not-include-deleted"===s?await Kl(t.subChannelId):await pl(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:xu(Uc,"feedId","subChannel"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:r}){var n,s;const i=null===(n=Ee(this.cacheKey))||void 0===n?void 0:n.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>Ee(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(cl))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage(!1,"next"),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:r})}applyFilter(e){let t=e;return this.query.includeDeleted||(t=Ae(e,"isDeleted",!1)),t.sort($e),t}}const mh={},yh=async e=>{const t=await(async e=>{const t=Kl.locally(e);if(t)return t.data.channelId;const{data:r}=await Kl(e);return r.channelId})(e),r=at({channelId:t,subChannelId:e});mh[e]=ht(r)};var vh=Object.freeze({__proto__:null,getSubChannelByIds:Xl,createSubChannel:async e=>{const t=ve();t.log("user/createSubChannel",e);const r=await t.http.post("/api/v5/message-feeds",{channelId:e.channelId,name:e.displayName}),n=await Nl(r.data),s=t.cache&&Date.now();return t.cache&&Oo(n,{cachedAt:s}),Je("message-feed.created",r.data),{data:n.messageFeeds[0],cachedAt:s}},updateSubChannel:async(e,t)=>{const r=ve();r.log("channel/updateSubChannel",e,t);const n=await r.http.put(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{name:t.displayName}),s=await Nl(n.data),i=r.cache&&Date.now();return r.cache&&Oo(s,{cachedAt:i}),Je("message-feed.updated",n.data),{data:s.messageFeeds[0],cachedAt:i}},deleteSubChannel:Nu,hardDeleteSubChannel:async e=>{ve().log("channel/hardDeleteSubChannel",e);return await Nu(e,!0)},softDeleteSubChannel:async e=>{ve().log("channel/softDeleteSubChannel",e);return await Nu(e,!1)},onSubChannelCreated:Oc,onSubChannelUpdated:Mu,onSubChannelDeleted:Pc,getSubChannel:(e,t)=>{const r=ve();let n;return pd(e,(e=>{if(!e.data)return t(e);const r=Object.assign(Object.assign({},e),{data:cl(e.data)}),s=Mo(r,["origin"]);return fd(n,s)?void 0:(n=s,t(r))}),"subChannelId",Kl,[Bu,t=>Mu((async n=>{"no-message-preview"!==await r.getMessagePreviewSetting(!1)&&(gl(n),n.subChannelId===e&&t(n))})),Pc,xu(ad,"feedId","subChannel"),t=>od((r=>{var n;if(!r.find((({feedId:t})=>t===e)))return;const s=null===(n=Ee(["subChannel","get",e]))||void 0===n?void 0:n.data;s&&t(s)})),xu((t=>Dc((async n=>{var s;if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;if(await fl(n),n.subChannelId!==e)return;const i=null===(s=Ee(["subChannel","get",e]))||void 0===s?void 0:s.data;i&&(hl(n.subChannelId,i,{messagePreviewId:n.messageId}),t(n))}))),"subChannelId","subChannel"),xu((t=>xc((async n=>{var s;if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;if(await fl(n),n.subChannelId!==e)return;const i=null===(s=Ee(["subChannel","get",e]))||void 0===s?void 0:s.data;i&&(hl(n.subChannelId,i,{messagePreviewId:n.messageId}),t(n))}))),"subChannelId","subChannel"),xu((t=>Ou((async n=>{"no-message-preview"!==await r.getMessagePreviewSetting(!1)&&n.subChannelId===e&&(pl(n),t(n))}))),"subChannelId","subChannel"),xu((t=>Pu((async n=>{const s=await r.getMessagePreviewSetting(!1);"no-message-preview"!==s&&n.subChannelId===e&&("message-preview-include-deleted"===s&&await pl(n),"message-preview-not-include-deleted"===s&&await Kl(n.subChannelId),t(n))}))),"subChannelId","subChannel"),xu(Uc,"feedId","subChannel")],{forceDispatch:!0})},getSubChannels:(e,t,r)=>{const{log:n,cache:s}=ve(),i=Date.now();n(`getSubChannels(tmpid: ${i}) > listen`),s||console.log(p);const a=new gh(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>{ke(l)})),()=>{n(`getSubChannels(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}},markReadEngineOnLoginHandler:Yl,startReading:async e=>{Vl[e]=!0,0===Hl.length&&(Hl.length>0||Hl.push($l((()=>{zl()}))),Ql(e));try{return await(async e=>{const t=ve();t.log("subChannel/startReadingAPI",e);const{data:r}=await t.http.post(`/api/v1/markers/message-feeds/${e}/start-reading`),{userEntityMarkers:n,userFeedMarkers:s,feedMarkers:i,userMarkers:a}=r,o=Bo(n),l=jo(s),c=t.cache&&Date.now();return t.cache&&Oo({userEntityMarkers:o,userFeedMarkers:l,feedMarkers:i,userMarkers:a},{cachedAt:c}),Je("local.feedMarker.fetched",{feedMarkers:i}),Je("local.channelMarker.fetched",{userEntityMarkers:o}),Je("local.subChannelMarker.fetched",{userFeedMarkers:l}),Je("local.userMarker.fetched",{userMarkers:a}),!0})(e)}catch(t){return Vl[e]=!1,!1}},stopReading:e=>(Vl[e]=!1,Hl.forEach((e=>e())),Hl=[],(async e=>{const t=ve();t.log("channel/stopReadingAPI",e);const{data:r}=await t.http.post(`/api/v1/markers/message-feeds/${e}/stop-reading`),{userEntityMarkers:n,userFeedMarkers:s,feedMarkers:i,userMarkers:a}=r,o=Bo(n),l=jo(s),c=t.cache&&Date.now();return t.cache&&Oo({userEntityMarkers:o,userFeedMarkers:l,feedMarkers:i,userMarkers:a},{cachedAt:c}),Je("local.feedMarker.fetched",{feedMarkers:i}),Je("local.channelMarker.fetched",{userEntityMarkers:o}),Je("local.subChannelMarker.fetched",{userFeedMarkers:l}),Je("local.userMarker.fetched",{userMarkers:a}),!0})(e)),startMessageReceiptSync:async e=>(await yh(e),!0),stopMessageReceiptSync:e=>(mh[e]&&mh[e](),!0)});class bh extends sh{async getRequest(e,t){const{limit:r=h,displayName:n,membership:s}=e,i=Mo(e,["limit","displayName","membership"]),a=t?{token:t}:{limit:r},{data:o}=await this.http.get("/api/v3/channels",{params:Object.assign(Object.assign({},i),{keyword:n,filter:s,options:a})});return o}}class wh extends ah{constructor(e,t,r,n,s){super(e,t),this.notifyChange=r,this.preparePayload=n,this.paginationController=s}async saveToMainDB(e){const t=await this.preparePayload(e),r=ve(),n=r.cache&&Date.now();r.cache&&Oo(t,{cachedAt:n})}appendToQueryStream(e,t,r=!1){var n,s;if(r)Se(this.cacheKey,{data:e.channels.map(de("channel"))});else{const t=null===(n=Ee(this.cacheKey))||void 0===n?void 0:n.data,r=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...r,...e.channels.map(de("channel"))])]}))}}reactor(e){return t=>{var r;const n=null===(r=Ee(this.cacheKey))||void 0===r?void 0:r.data;n&&(this.paginationController instanceof bh&&"onCreate"===e&&(n.data=[...new Set([t.channelId,...n.data])],Se(this.cacheKey,n)),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Eh extends lh{async getRequest(e){const{data:t}=await this.http.get("/api/v3/channels/list",{params:Object.assign({},e)});return t}}class Sh extends ch{constructor(e,t){const r=nh(e),n=["channel","collection",r],s=Sh.getPaginationController(e);super(s,r,n,t),this.query=e,this.queryStreamController=new wh(this.query,this.cacheKey,this.notifyChange.bind(this),Tl,s),this.paginationController=s,this.callback=t.bind(this),this.loadPage(!0)}setup(){var e;(null===(e=Ee(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:r}){this.queryStreamController.appendToQueryStream(e,t,r)}startSubscription(){return this.queryStreamController.subscribeRTE(this.getSubscriptions())}notifyChange({origin:e,loading:t,error:r}){var n,s;const i=null===(n=Ee(this.cacheKey))||void 0===n?void 0:n.data;if(!i)return;let a=null!==(s=i.data.map((e=>Ee(["channel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(al))&&void 0!==s?s:[];this.paginationController instanceof bh&&(a=this.applyFilter(a)),(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:this.paginationController instanceof bh?()=>this.loadPage(!1,"next"):void 0,data:a,hasNextPage:this.paginationController instanceof bh&&!!this.paginationController.getNextToken(),loading:t,error:r})}applyFilter(e){const{userId:t}=ve();let r=e;switch(r=Ae(r,"isDeleted",this.query.isDeleted),r=Ae(r,"displayName",this.query.displayName),this.query.types&&(r=r.filter((e=>{var t;return null===(t=this.query.types)||void 0===t?void 0:t.includes(e.type)}))),this.query.tags&&(r=r.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.excludeTags&&(r=r.filter((e=>{var t;return!(null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.excludeTags)||void 0===t?void 0:t.includes(e)})))}))),this.query.membership&&t&&(r=Re(r,this.query.membership,t)),this.query.sortBy){case"firstCreated":r=r.sort(Fe);break;case"lastCreated":r=r.sort(Ne);break;case"displayName":r=r.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Pe);break;default:r=r.sort($e)}return r}shouldAbort(e){var t,r;const n=null===(t=Ee(this.cacheKey))||void 0===t?void 0:t.data;if(!n)return!0;return!(null===(r=null==n?void 0:n.data)||void 0===r?void 0:r.find((t=>t===e)))}static getMessagePreviewSetting(){return ve().getMessagePreviewSetting(!1)}static getPaginationController(e){return e.channelIds&&e.channelIds.length>0?new Eh(e):new bh(e)}getSubscriptions(){const e=[{fn:xu((e=>Dc((t=>{var r;const n=null===(r=Ee(["channel","get",t.channelId]))||void 0===r?void 0:r.data;n&&(Fu(n,{lastActivity:t.createdAt}),e(t))}))),"messageId","channel"),action:"onUpdate"},{fn:xu((e=>xc((t=>{var r;const n=null===(r=Ee(["channel","get",t.channelId]))||void 0===r?void 0:r.data;n&&(Fu(n,{lastActivity:t.createdAt}),e(t))}))),"messageId","channel"),action:"onUpdate"},{fn:dc,action:"onDelete"},{fn:Ec,action:"onUpdate"},{fn:Cc,action:"onMute"},{fn:Sc,action:"onJoin"},{fn:e=>Tc(((t,r)=>{var n,s;const{userId:i}=ve();if("member"===this.query.membership&&i===r.userId){const e=null===(n=Ee(this.cacheKey))||void 0===n?void 0:n.data;Se(this.cacheKey,Object.assign(Object.assign({},e),{data:null!==(s=null==e?void 0:e.data.filter((e=>e!==t.channelId)))&&void 0!==s?s:[]}))}return e(t)})),action:"onLeft"},{fn:kc,action:"onMemberAdded"},{fn:Ac,action:"onMemberRemoved"},{fn:xu(id,"entityId","channel"),action:"onUpdate"},{fn:xu(Uu,"entityId","channel"),action:"onUpdate"},{fn:xu((e=>Dc((async t=>{var r;if("no-message-preview"===await Sh.getMessagePreviewSetting())return;if(fl(t),this.shouldAbort(t.channelId))return;const n=null===(r=Ee(["channel","get",t.channelId]))||void 0===r?void 0:r.data;n&&(Fu(n,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:xu((e=>xc((async t=>{var r;if("no-message-preview"===await Sh.getMessagePreviewSetting())return;if(fl(t),this.shouldAbort(t.channelId))return;const n=null===(r=Ee(["channel","get",t.channelId]))||void 0===r?void 0:r.data;n&&(Fu(n,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:xu((e=>Ou((async t=>{"no-message-preview"!==await Sh.getMessagePreviewSetting()&&(pl(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:xu((e=>Pu((async t=>{const r=await Sh.getMessagePreviewSetting();"no-message-preview"!==r&&("message-preview-include-deleted"===r&&await pl(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===r&&await Du(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:xu((e=>Pc((async t=>{var r;const n=null===(r=Ee(this.cacheKey))||void 0===r?void 0:r.data;if(!n)return;n.data.find((e=>{const r=$o(e);return(null==r?void 0:r.subChannelId)===t.subChannelId}))&&(await Du(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:xu((e=>Mu((async t=>{var r;if("no-message-preview"===await Sh.getMessagePreviewSetting())return;(null===(r=Ee(this.cacheKey))||void 0===r?void 0:r.data)&&(await gl(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:xu(Uc,"entityId","channel"),action:"onUpdate"},{fn:xu(Oc,"channelId","channel"),action:"onUpdate"}];return this.paginationController instanceof sh?[...e,{fn:wc,action:"onCreate"}]:e}}class Th extends sh{async getRequest(e,t){const{limit:r=h}=e,n=Mo(e,["limit"]),s=t?{token:t}:{limit:r},{data:i}=await this.http.get(`/api/v4/channels/${encodeURIComponent(n.channelId)}/users`,{params:Object.assign(Object.assign({},n),{options:s})});return i}}class Ch extends ah{constructor(e,t,r,n){super(e,t),this.notifyChange=r,this.preparePayload=n}async saveToMainDB(e){const t=await this.preparePayload(e),r=ve(),n=r.cache&&Date.now();r.cache&&Oo(t,{cachedAt:n})}appendToQueryStream(e,t,r=!1){var n,s;if(r)Se(this.cacheKey,{data:e.channelUsers.map((({channelId:e,userId:t})=>de("channelUsers")({channelId:e,userId:t})))});else{const t=null===(n=Ee(this.cacheKey))||void 0===n?void 0:n.data,r=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...r,...e.channelUsers.map((({channelId:e,userId:t})=>de("channelUsers")({channelId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var r;if(this.query.channelId!==t.channelId)return;const n=null===(r=Ee(this.cacheKey))||void 0===r?void 0:r.data;if(!n)return;const s=de("channelUsers")({channelId:this.query.channelId,userId:t.userId});"none"===t.membership?n.data=n.data.filter((e=>e!==s)):n.data.includes(s)||(n.data=[s,...n.data]),Se(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class kh extends ch{constructor(e,t){const r=nh(e),n=["channelUsers","collection",r];super(new Th(e),r,n,t),this.query=e,this.queryStreamController=new Ch(this.query,this.cacheKey,this.notifyChange.bind(this),Tl),this.callback=t.bind(this),this.loadPage(!0)}setup(){var e;(null===(e=Ee(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:r}){this.queryStreamController.appendToQueryStream(e,t,r)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Sc,action:"onJoin"},{fn:Tc,action:"onLeft"},{fn:kc,action:"onMemberAdded"},{fn:Ac,action:"onMemberRemoved"},{fn:uc,action:"onChannelMemberBanned"},{fn:Ic,action:"onChannelMemberUnbanned"},{fn:_c,action:"onChannelMemberRoleAdded"},{fn:Rc,action:"onChannelMemberRoleRemoved"}])}notifyChange({origin:e,loading:t,error:r}){var n,s;const i=null===(n=Ee(this.cacheKey))||void 0===n?void 0:n.data;if(!i)return;const a=this.applyFilter(null!==(s=i.data.map((e=>Ee(["channelUsers","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage(!1,"next"),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:r})}applyFilter(e){let t=_e(e,"roles",this.query.roles);this.query.memberships&&(t=t.filter((e=>{var t,r;return!(!(null===(t=this.query.memberships)||void 0===t?void 0:t.includes("muted"))||!e.isMuted)||"none"!==e.membership&&(null===(r=this.query.memberships)||void 0===r?void 0:r.includes(e.membership))}))),this.query.search&&(console.warn("`search` param will be deprecated in the next major release. If you want to search channel members by displayName, Please use `searchMembers()` instead."),t=Oe(t,this.query.search));const r=this.query.sortBy?this.query.sortBy:"lastCreated";return t=t.sort("lastCreated"===r?Ne:Fe),t}}const Ah=(e,t,r)=>{const{log:n,cache:s}=ve();s||console.log(p);const i=Date.now();n(`getMembers(tmpid: ${i}) > listen`);const a=new kh(e,t),o=a.startSubscription(),l=a.getCacheKey();return o.push((()=>{ke(l)})),()=>{n(`getMembers(tmpid: ${i}) > dispose`),o.forEach((e=>e()))}};var Ih=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const r=ve();r.log("channel/addMembers",e,t);const{data:n}=await r.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users`,{channelId:e,userIds:t});t.forEach((e=>Je("channel.membersAdded",Object.assign(Object.assign({},n),{channelUsers:n.channelUsers.filter((t=>t.userId===e))}))));const s=await Tl(n);r.cache&&Oo(s);const{channelUsers:i}=s;return!!i.find((t=>t.channelId===e&&"member"===t.membership))},removeMembers:async(e,t)=>{const r=ve();r.log("channel/removeMembers",e,t);const{data:n}=await r.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users`,{data:{channelId:e,userIds:t}});t.forEach((e=>Je("channel.membersRemoved",Object.assign(Object.assign({},n),{channelUsers:n.channelUsers.filter((t=>t.userId===e))}))));const s=await Tl(n);r.cache&&Oo(s);const{channelUsers:i}=s;return!!i.find((t=>t.channelId===e&&"member"!==t.membership))},applyFilter:(e,t)=>{let r=_e(e,"roles",t.roles);t.memberships&&(r=r.filter((e=>!(!t.memberships.includes("muted")||!e.isMuted)||t.memberships.includes(e.membership)))),t.search&&(console.warn("`search` param will be deprecated in the next major release. If you want to search channel members by displayName, Please use `searchMembers()` instead."),r=Oe(r,t.search));const n=t.sortBy?t.sortBy:"lastCreated";return r=r.sort("lastCreated"===n?Ne:Fe),r},getMembers:Ah,searchMembers:(e,t,r)=>Ah(e,t)});var _h=Object.freeze({__proto__:null,addRole:async(e,t,r)=>{const n=ve();n.log("channel/addRole",e,t,r);const{data:s}=await n.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{channelId:e,role:t,userIds:r}),i=await Tl(s);n.cache&&Oo(i),Je("local.channel-moderator.role-added",i);const{channelUsers:a}=i;return!!a.find((r=>r.channelId===e&&r.roles.includes(t)))},removeRole:async(e,t,r)=>{const n=ve();n.log("channel/removeRole",e,t,r);const{data:s}=await n.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{data:{channelId:e,role:t,userIds:r}}),i=await Tl(s);n.cache&&Oo(i),Je("local.channel-moderator.role-removed",i);const{channelUsers:a}=i;return!!a.find((r=>r.channelId===e&&!r.roles.includes(t)))},banMembers:async(e,t)=>{const r=ve();r.log("channel/banMembers",{userIds:t,channelId:e});const{data:n}=await r.http.put(`/api/v3/channels/${e}/users/ban`,{userIds:t}),s=await Tl(n),{channelUsers:i}=s,a=r.cache&&Date.now();return r.cache&&Oo(s,{cachedAt:a}),{data:null==i?void 0:i.filter((e=>"banned"===e.membership)),cachedAt:a}},unbanMembers:async(e,t)=>{const r=ve();r.log("channel/unbanMembers",{userIds:t,channelId:e});const{data:n}=await r.http.put(`/api/v3/channels/${encodeURIComponent(e)}/users/unban`,{userIds:t}),s=await Tl(n),i=r.cache&&Date.now();r.cache&&Oo(s,{cachedAt:i});const{channelUsers:a}=s;return{data:null==a?void 0:a.filter((e=>"member"===e.membership)),cachedAt:i}},muteMembers:async(e,t,r=-1)=>{const n=ve();n.log("channel/muteMembers",{userIds:t,channelId:e,mutePeriod:r});const{data:s}=await n.http.put(`/api/v2/channel/${e}/users/mute`,{userIds:t,mutePeriod:-1===r?r:1e3*r}),{success:i}=s;return i},unmuteMembers:async(e,t)=>{const r=ve();r.log("channel/unmuteMembers",{userIds:t,channelId:e});const{data:n}=await r.http.put(`/api/v2/channel/${encodeURIComponent(e)}/users/mute`,{userIds:t,mutePeriod:0}),{success:s}=n;return s}}),Rh=Object.freeze({__proto__:null,Membership:Ih,Moderation:_h,getChannelByIds:Cl,createChannel:async e=>{const t=ve();let r;if(t.log("user/createChannel",e),"conversation"===(null==e?void 0:e.type))r=await t.http.post("/api/v3/channels/conversation",Object.assign(Object.assign({},e),{isDistinct:!0}));else{const{isPublic:n}=e,s=Mo(e,["isPublic"]);r=await t.http.post("/api/v3/channels",Object.assign(Object.assign({},s),{isPublic:"community"===(null==e?void 0:e.type)?n:void 0}))}const n=await Tl(r.data),s=t.cache&&Date.now();t.cache&&Oo(n,{cachedAt:s});const{channels:i}=n;return{data:i[0],cachedAt:s}},updateChannel:async(e,t)=>{const r=ve();r.log("channel/updateChannel",e,t);const{data:n}=await r.http.put(`/api/v3/channels/${encodeURIComponent(e)}`,t),s=await Tl(n),i=r.cache&&Date.now();r.cache&&Oo(s,{cachedAt:i});const{channels:a}=s;return{data:a.find((t=>t.channelId===e)),cachedAt:i}},deleteChannel:async e=>{const t=ve();t.log("channel/deleteChannel",e),await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}`);return(await Du(e)).data},joinChannel:async e=>{const t=ve();t.log("channel/joinChannel",e);const{data:r}=await t.http.post(`/api/v3/channels/${encodeURIComponent(e)}/join`),n=await Tl(r);t.cache&&Oo(n);const{channelUsers:s}=n;return!!s.find((t=>t.channelId===e&&"member"===t.membership))},leaveChannel:async e=>{const t=ve();t.log("channel/leaveChannel",e);const{data:r}=await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/leave`),n=await Tl(r);t.cache&&Oo(n);const{channelUsers:s}=n;return!!s.find((t=>t.channelId===e&&"member"!==t.membership))},muteChannel:async(e,t=-1)=>{const r=ve();if(r.log("channel/muteChannel",e),-1!==t&&t<0)throw new fe("Mute Period can only be positive numbers or -1(mute forever)",800110,"error");const{data:n}=await r.http.put(`/api/v2/channel/${encodeURIComponent(e)}/mute`,{mutePeriod:t}),{success:s}=n;return s},unmuteChannel:async e=>{const t=ve();t.log("channel/unmuteChannel",e);const{data:r}=await t.http.put(`/api/v2/channel/${encodeURIComponent(e)}/mute`,{mutePeriod:0}),{success:n}=r;return n},markAsRead:async e=>{const t=ve();t.log("channel/markAsRead",e);const{data:r}=await t.http.put(`/api/v1/markers/channels/${e}/mark-read`),{userMarkers:n,userEntityMarkers:s,userFeedMarkers:i}=r,a=Mo(r,["userMarkers","userEntityMarkers","userFeedMarkers"]),o=t.cache&&Date.now(),l=Bo(s),c=jo(i);return t.cache&&Oo(Object.assign({userMarkers:n,userEntityMarkers:l,userFeedMarkers:c},a),{cachedAt:o}),Je("local.channelMarker.updated",{userEntityMarkers:l}),Je("local.subChannelMarker.updated",{userFeedMarkers:c}),!0},onChannelCreated:wc,onChannelUpdated:Ec,onChannelDeleted:dc,onChannelJoined:Sc,onChannelLeft:Tc,onChannelMuted:Cc,onChannelMemberAdded:kc,onChannelMemberRemoved:Ac,onChannelMemberBanned:uc,onChannelMemberUnbanned:Ic,onChannelMemberRoleAdded:_c,onChannelMemberRoleRemoved:Rc,observeChannel:(e,t)=>{const{log:r}=ve(),n=Date.now();r(`observeChannel(tmpid: ${n}) > listen`);const s=(r,n)=>{var s,i,a;if((null===(s=r.data)||void 0===s?void 0:s.channelId)===e){if(t instanceof Function)return t(r);"onFetch"!==n&&(null===(i=t.onEvent)||void 0===i||i.call(t,n,r)),null===(a=t[n])||void 0===a||a.call(t,r)}},i=[];return i.push(Ec((e=>s({data:e,loading:!1,origin:"event"},"onUpdate"))),dc((e=>s({data:e,loading:!1,origin:"event"},"onDelete"))),Sc((e=>s({data:e,loading:!1,origin:"event"},"onJoin"))),Tc((e=>s({data:e,loading:!1,origin:"event"},"onLeft"))),Cc((e=>s({data:e,loading:!1,origin:"event"},"onMute"))),kc((e=>s({data:e,loading:!1,origin:"event"},"onMemberAdded"))),Ac((e=>s({data:e,loading:!1,origin:"event"},"onMemberRemoved"))),xu(id,"entityId","channel")((e=>s({data:e,loading:!1,origin:"event"},"onUpdate")))),oe(ie(Du,e),(e=>e.data&&s(e,"onFetch"))),()=>{r(`observeChannel(tmpid: ${n}) > dispose`),i.forEach((e=>e()))}},observeChannels:e=>{const{log:t}=ve(),r=Date.now();t(`observeChannels(tmpid: ${r}) > listen`);const n=[],s=(t,r)=>{var n,s;if(e instanceof Function)return e(t);null===(n=e.onEvent)||void 0===n||n.call(e,r,t),null===(s=e[r])||void 0===s||s.call(e,t)};return n.push(wc((e=>s(e,"onCreate"))),Ec((e=>s(e,"onUpdate"))),dc((e=>s(e,"onDelete"))),Sc((e=>s(e,"onJoin"))),Tc((e=>s(e,"onLeft"))),Cc((e=>s(e,"onMute"))),kc((e=>s(e,"onMemberAdded"))),Ac((e=>s(e,"onMemberRemoved"))),xu(id,"entityId","channel")((e=>s(e,"onUpdate")))),()=>{t(`observeChannels(tmpid: ${r}) > dispose`),n.forEach((e=>e()))}},getChannel:(e,t)=>{const r=ve();let n;return pd(e,(async e=>{if(!e.data)return t(e);const r=Object.assign(Object.assign({},e),{data:al(e.data)}),s=Mo(r,["origin"]);return fd(n,s)?void 0:(n=s,t(r))}),"channelId",Du,[Ec,dc,Sc,Tc,kc,Ac,uc,Ic,Cc,xu(id,"entityId","channel"),xu(Uu,"entityId","channel"),xu((t=>Dc((async n=>{var s;if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;if(await fl(n),n.channelId!==e)return;const i=null===(s=Ee(["channel","get",e]))||void 0===s?void 0:s.data;i&&(Fu(i,{messagePreviewId:n.messageId}),t(n))}))),"channelId","channel"),xu((t=>xc((async n=>{var s;if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;if(await fl(n),n.channelId!==e)return;const i=null===(s=Ee(["channel","get",e]))||void 0===s?void 0:s.data;i&&(Fu(i,{messagePreviewId:n.messageId}),t(n))}))),"channelId","channel"),xu((t=>Ou((async n=>{var s;const i=null===(s=Ee(["channel","get",e]))||void 0===s?void 0:s.data;if(!i||i.messagePreviewId!==n.messageId)return;"no-message-preview"!==await r.getMessagePreviewSetting(!1)&&(await pl(n),t(n))}))),"channelId","channel"),xu((t=>Pu((async n=>{var s;const i=null===(s=Ee(["channel","get",e]))||void 0===s?void 0:s.data;if(!i||i.messagePreviewId!==n.messageId)return;const a=await r.getMessagePreviewSetting(!1);"no-message-preview"!==a&&("message-preview-not-include-deleted"===a?(ke(["messagePreviewChannel","get",e]),await Du(n.channelId)):await pl(n),t(n))}))),"channelId","channel"),xu((e=>Pc((async t=>{var n,s;const{channelId:i,subChannelId:a}=t,o=null===(n=Ee(["messagePreviewChannel","get",i]))||void 0===n?void 0:n.data;if(!o||o.subChannelId!==a)return;if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;await Du(i);(null===(s=Ee(["channel","get",i]))||void 0===s?void 0:s.data)&&e(t)}))),"channelId","channel"),xu((t=>Mu((async n=>{var s,i;if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;gl(n);const a=null===(s=Ee(["messagePreviewChannel","get",e]))||void 0===s?void 0:s.data;if(!a||a.subChannelId!==n.subChannelId)return;(null===(i=Ee(["channel","get",e]))||void 0===i?void 0:i.data)&&t(n)}))),"channelId","channel"),xu(Oc,"channelId","channel"),xu(Uc,"entityId","channel")],{forceDispatch:!0})},getChannels:(e,t,r)=>{const{log:n,cache:s,userId:i}=ve();s||console.log(p);const a=Date.now();n(`getChannels(tmpid: ${a}) > listen`);const o=new Sh(e,t),l=o.startSubscription(),c=o.getCacheKey();return l.push((()=>{ke(c)})),()=>{n(`getChannels(tmpid: ${a}) > dispose`),l.forEach((e=>e()))}},MARKER_INCLUDED_CHANNEL_TYPE:bl,isUnreadCountSupport:wl,convertFromRaw:El,preUpdateChannelCache:Sl,prepareChannelPayload:Tl});function Lh(e,t){return e.map((e=>{const r=t.some((t=>function(e,t){const{userId:r}=Ke();return e.communityId===t.communityId&&t.userId===r}(e,t)&&"none"!==t.communityMembership));return Object.assign(Object.assign({},e),{isJoined:r})}))}const Dh=e=>{var t;return null!==(t=Object.keys(a).find((t=>e.needApprovalOnPostCreation===a[t].needApprovalOnPostCreation&&e.onlyAdminCanPost===a[t].onlyAdminCanPost)))&&void 0!==t?t:o},xh=e=>{const t=e.communities.map((e=>{var{needApprovalOnPostCreation:t,onlyAdminCanPost:r}=e,n=Mo(e,["needApprovalOnPostCreation","onlyAdminCanPost"]);return Object.assign({postSetting:Dh({needApprovalOnPostCreation:t,onlyAdminCanPost:r})},n)})),r=Fo(e.communityUsers),n=Lh(t,r);return Object.assign(Object.assign({},e),{communities:n,communityUsers:r})},Oh=e=>{const{postSetting:t,storySetting:r}=e,n=Mo(e,["postSetting","storySetting"]);return Object.assign(Object.assign(Object.assign({},n),t?a[t]:void 0),{allowCommentInStory:!1!==(null==r?void 0:r.enableComment)})},Ph=async e=>{const t=ve();t.log("community/getCommunities",e);const{data:r}=await t.http.get("/api/v3/communities/list",{params:{communityIds:e}}),n=xh(r),s=t.cache&&Date.now();return t.cache&&Oo(n,{cachedAt:s}),{data:n.communities,cachedAt:s}};Ph.locally=e=>{var t;const r=ve();if(r.log("community/getCommunities.locally",e),!r.cache)return;const n=e.map((e=>Ee(["community","get",e]))).filter(Boolean),s=n.map((({data:e})=>e)),i=null===(t=n.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==n?void 0:n.length)<e.length?void 0:{data:s,cachedAt:i.cachedAt}};const Mh=async e=>{const t=ve();t.log("community/getCommunity",e);const{data:r}=await t.http.get(`/api/v3/communities/${e}`),n=xh(r),s=t.cache&&Date.now();t.cache&&Oo(n,{cachedAt:s});const{communities:i}=n;return{data:i.find((t=>t.communityId===e)),cachedAt:s}};Mh.locally=e=>{const t=ve();if(t.log("community/getCommunity.locally",e),!t.cache)return;const r=Ee(["community","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const Fh=async e=>{const t=ve();t.log("channel/getTopTrendingCommunities",e);const{limit:r=5}=null!=e?e:{},{data:n}=await t.http.get("/api/v3/communities/top-trending",{params:{options:{limit:r}}}),s=xh(n),{communities:i}=s,a=t.cache&&Date.now();if(t.cache){Oo(s,{cachedAt:a});Se(["community","top-trending",{params:{options:{limit:r}}}],{communities:i.map(de("community"))})}return{data:i,cachedAt:a}};Fh.locally=e=>{var t,r;const n=ve();if(n.log("community/getTopTrendingCommunities.locally",e),!n.cache)return;const{limit:s=5}=null!=e?e:{},i=["community","top-trending",{params:{options:{limit:s}}}],{data:a,cachedAt:o}=null!==(t=Ee(i))&&void 0!==t?t:{};if(!(null==a?void 0:a.communities.length))return;const l=a.communities.map((e=>Ee(["community","get",e]))).filter(Boolean).map((({data:e})=>e));return l.length===(null===(r=null==a?void 0:a.communities)||void 0===r?void 0:r.length)?{data:l,cachedAt:o}:void 0};const Uh=(e,t)=>{const r=ve();return Xe(r,e,e,(e=>{const n=xh(e);if(r.cache){Oo(n);const e=Ee(["community","get",n.communities[0].communityId]);t(e.data)}else t(n.communities[0])}))},Nh=e=>Uh("community.created",e),Bh=e=>Uh("community.updated",e),jh=e=>Uh("community.deleted",e);function $h(e){return null!=e}function qh(e,t,r){return!!e.permissions.some((e=>e===r))||t.users.find((t=>t.userId===e.userId)).permissions.some((e=>e===r))}function Kh(e,t){return"community.joined"===e||"community.left"===e?t.communityUsers:"community.userRemoved"===e?t.communityUsers.filter((e=>"none"===e.communityMembership)):"community.userBanned"===e?t.communityUsers.filter((e=>"banned"===e.communityMembership)):"community.userUnbanned"===e?t.communityUsers.filter((e=>!qh(e,t,"BAN_COMMUNITY_USER"))):t.communityUsers.filter((e=>!qh(e,t,"ADD_COMMUNITY_USER")))}const Gh=(e,t)=>{const r=ve();return Xe(r,e,e,(n=>{const s=xh(n),{communities:i,communityUsers:a}=s,o=Lh(i,a);if(s.communities=o,r.cache){Oo(s);const r=Ee(["community","get",s.communities[0].communityId]),n=Kh(e,s).map((e=>{const t=Ee(["communityUsers","get",de("communityUsers")(e)]);return null==t?void 0:t.data})).filter($h);t(r.data,n)}else t(s.communities[0],Kh(e,s))}))},Hh=e=>Gh("community.userAdded",e),Vh=e=>Gh("community.userRemoved",e),zh=e=>Gh("community.userBanned",e),Wh=e=>Gh("community.userChanged",e),Yh=e=>Gh("community.userUnbanned",e),Qh=e=>Gh("community.roleAdded",e),Xh=e=>Gh("community.roleRemoved",e),Jh=e=>Gh("community.joined",e),Zh=e=>Gh("community.left",e),ef=async e=>{const t=ve();t.log("channel/queryCommunities",e);const r=null!=e?e:{},{page:n,limit:s=10}=r,i=Mo(r,["page","limit"]),a=null!=i?i:{},{displayName:o,membership:l,includeDeleted:c}=a,d=Mo(a,["displayName","membership","includeDeleted"]),u=n?{token:n}:s?{limit:s}:void 0,{data:h}=await t.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},d),{isDeleted:Al(c),keyword:o,filter:l,options:u})}),{paging:f}=h,p=Mo(h,["paging"]),g=xh(p),{communities:m}=g,y=t.cache&&Date.now();if(t.cache){Oo(g,{cachedAt:y});const e=["community","query",Object.assign(Object.assign({},i),{options:u})];Se(e,{communities:m.map(de("community")),paging:f})}return{data:m,cachedAt:y,paging:f}},tf=async e=>{const t=ve();t.log("community/getTrendingCommunities",e);const{limit:r=h}=null!=e?e:{},{data:n}=await t.http.get("/api/v3/communities/top-trending",{params:{options:{limit:r}}}),s=xh(n),{communities:i}=s,a=t.cache&&Date.now();return t.cache&&Oo(s,{cachedAt:a}),{data:i,cachedAt:a}},rf=(e,t,r)=>{let n=e;n=Ae(n,"displayName",t.displayName),t.includeDeleted||(n=Ae(n,"isDeleted",!1)),t.categoryId&&(n=n.filter((e=>{var r;return null===(r=e.categoryIds)||void 0===r?void 0:r.includes(t.categoryId)}))),t.tags&&(n=n.filter((e=>{var r;return null===(r=e.tags)||void 0===r?void 0:r.some((e=>{var r;return null===(r=t.tags)||void 0===r?void 0:r.includes(e)}))}))),t.membership&&r&&(n=De(n,t.membership,r));const s=t.sortBy||"lastCreated";return"lastCreated"!==s&&"firstCreated"!==s||(n=n.sort("lastCreated"===s?Ne:Fe)),"displayName"===s&&(n=n.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Pe)),n},nf=async e=>{const t=ve();t.log("community/getRecommendedCommunities",e);const{limit:r=h}=null!=e?e:{},{data:n}=await t.http.get("/api/v3/communities/recommended",{params:{options:{limit:r}}}),s=xh(n),{communities:i}=s,a=t.cache&&Date.now();return t.cache&&Oo(s,{cachedAt:a}),{data:i,cachedAt:a}};var sf=Object.freeze({__proto__:null,addRoles:async(e,t,r)=>{const n=ve();n.log("community/moderation/addRoles",e,t,r);const{data:s}=await n.http.post(`/api/v4/communities/${e}/users/roles`,{communityId:e,roles:t,userIds:r}),i=Uo(s,"communityUsers");n.cache&&Oo(i);const{communityUsers:a}=i;return!!a.find((r=>r.communityId===e&&t.some((e=>r.roles.includes(e)))))},removeRoles:async(e,t,r)=>{const n=ve();n.log("community/moderation/removeRoles",e,t,r);const{data:s}=await n.http.delete(`/api/v4/communities/${e}/users/roles`,{data:{communityId:e,roles:t,userIds:r}}),i=Uo(s,"communityUsers");n.cache&&Oo(i);const{communityUsers:a}=i;return!!a.find((r=>r.communityId===e&&!t.some((e=>r.roles.includes(e)))))},banMembers:async(e,t)=>{const r=ve();r.log("community/banMembers",{userIds:t,communityId:e});const{data:n}=await r.http.put(`/api/v3/communities/${e}/users/ban`,{userIds:t}),s=Uo(n,"communityUsers"),i=r.cache&&Date.now();r.cache&&Oo(s,{cachedAt:i});const{communityUsers:a}=s;return{data:a.filter((e=>t.includes(e.userId))),cachedAt:i}},unbanMembers:async(e,t)=>{const r=ve();r.log("community/unbanMembers",{userIds:t,communityId:e});const{data:n}=await r.http.put(`/api/v3/communities/${e}/users/unban`,{userIds:t}),s=Uo(n,"communityUsers"),i=r.cache&&Date.now();r.cache&&Oo(s,{cachedAt:i});const{communityUsers:a}=s;return{data:a.filter((e=>t.includes(e.userId))),cachedAt:i}}});const af=async e=>{const t=ve();t.log("community/queryCommunityMembers",e);const r=null!=e?e:{},{page:n,limit:s}=r,i=Mo(r,["page","limit"]),a=n?{token:n}:s?{limit:s}:void 0,{data:o}=await t.http.get(`/api/v3/communities/${i.communityId}/users`,{params:Object.assign(Object.assign({},i),{options:a})}),{paging:l}=o,c=Mo(o,["paging"]),d=Uo(c,"communityUsers"),{communityUsers:u}=d,h=t.cache&&Date.now();if(t.cache){Oo(d,{cachedAt:h});const e=["communityUsers","query",Object.assign(Object.assign({},i),{options:a})];Se(e,{communityUsers:u.map((({communityId:e,userId:t})=>de("communityUsers")({communityId:e,userId:t}))),paging:l})}return{data:u,cachedAt:h,paging:l}};af.locally=e=>{var t,r;const n=ve();if(n.log("community/queryCommunityMembers",e),!n.cache)return;const s=null!=e?e:{},{page:i,limit:a}=s,o=Mo(s,["page","limit"]),l=i?{token:i}:a?{limit:a}:void 0,c=["communityUsers","query",Object.assign(Object.assign({},o),{options:l})],{data:d,cachedAt:u}=null!==(t=Ee(c))&&void 0!==t?t:{};if(!(null==d?void 0:d.communityUsers.length))return;const h=d.communityUsers.map((e=>Ee(["communityUsers","get",e]))).filter(Boolean).map((({data:e})=>e)),{paging:f}=d;return h.length===(null===(r=null==d?void 0:d.communityUsers)||void 0===r?void 0:r.length)?{data:h,cachedAt:u,paging:f}:void 0};const of=(e,t)=>{let r=_e(e,"roles",t.roles);t.memberships&&(r=r.filter((({communityMembership:e})=>t.memberships.includes(e)))),t.search&&(r=Oe(r,t.search));const n=t.sortBy?t.sortBy:"lastCreated";return r=r.sort("lastCreated"===n?Ne:Fe),r};var lf=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const r=ve();r.log("community/moderation/addMembers",e,t);const{data:n}=await r.http.post(`/api/v3/communities/${e}/users`,{communityId:e,userIds:t});Je("community.userAdded",n);const s=Uo(n,"communityUsers");r.cache&&Oo(s);const{communityUsers:i}=s;return!!i.find((t=>t.communityId===e&&"member"===t.communityMembership))},removeMembers:async(e,t)=>{const r=ve();r.log("community/moderation/removeMembers",e,t);const{data:n}=await r.http.delete(`/api/v3/communities/${e}/users`,{data:{communityId:e,userIds:t}});Je("community.userRemoved",n);const s=Uo(n,"communityUsers");r.cache&&Oo(s);const{communityUsers:i}=s;return!!i.find((t=>t.communityId===e&&"member"!==t.communityMembership))},applyFilter:of,getMembers:(e,t,r)=>{const{log:n,cache:s}=ve();s||console.log(p);const i=Date.now();n(`getMembers(tmpid: ${i}) > listen`);const{limit:a}=e,o=Mo(e,["limit"]),l=null!=a?a:h,{policy:c=f}=null!=r?r:{},d=[],u=["communityUsers","collection",o],g=["communityUsers","collection",{communityId:e.communityId}],m=(r,n=!1)=>{var s,i;const a=null!==(s=r.data.map((e=>Ee(["communityUsers","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==s?s:[];t({onNextPage:v,data:n?of(a,e):a,hasNextPage:!!(null===(i=r.params)||void 0===i?void 0:i.page),loading:r.loading,error:r.error})},y=t=>(t,r)=>{var n;const s=null===(n=Ee(u))||void 0===n?void 0:n.data;if(!s)return;const i=r.map((t=>{if(e.communityId!==t.communityId)return;return de("communityUsers")({communityId:e.communityId,userId:t.userId})})).filter($h);s.data=[...new Set([...i,...s.data])],Se(u,s),Se(g,s),m(s,!0)},v=(e=!1)=>{var t,r;const n=null===(t=Ee(u))||void 0===t?void 0:t.data,s=null!==(r=null==n?void 0:n.data)&&void 0!==r?r:[];if(!e&&s.length>0&&!(null==n?void 0:n.params.page))return;const i=ie(af,Object.assign(Object.assign({},o),{limit:e?l:void 0,page:e||null==n?void 0:n.params.page}));oe(i,(({data:e,error:t,loading:r,paging:n})=>{const i={loading:r,error:t,params:{page:null==n?void 0:n.next},data:s};e&&(i.data=[...new Set([...s,...e.map(de("communityUsers"))])]),Se(u,i),Se(g,i),m(i)}),ae(c))};return d.push(Zh(y()),Jh(y()),zh(y()),Yh(y()),Wh(y()),Qh(y()),Xh(y())),v(!0),()=>{n(`getMembers(tmpid: ${i}) > dispose`),d.forEach((e=>e()))}},onCommunityUserAdded:Hh,onCommunityUserRemoved:Vh,onCommunityUserBanned:zh,onCommunityUserChanged:Wh,onCommunityUserUnbanned:Yh,onCommunityUserRoleAdded:Qh,onCommunityUserRoleRemoved:Xh,onCommunityJoined:Jh,onCommunityLeft:Zh}),cf=Object.freeze({__proto__:null,Moderation:sf,Membership:lf,getCommunityByIds:Ph,createCommunity:async e=>{const t=ve();t.log("user/createCommunity",e);const{data:r}=await t.http.post("/api/v3/communities/",Oh(e));Je("community.created",r);const n=xh(r),s=t.cache&&Date.now();t.cache&&Oo(n,{cachedAt:s});const{communities:i}=n;return{data:i[0],cachedAt:s}},updateCommunity:async(e,t)=>{const r=ve();r.log("community/updateCommunity",e,t);const{data:n}=await r.http.put(`/api/v3/communities/${e}`,Oh(t));Je("community.updated",n);const s=xh(n),i=r.cache&&Date.now();r.cache&&Oo(s,{cachedAt:i});const{communities:a}=s;return{data:a.find((t=>t.communityId===e)),cachedAt:i}},deleteCommunity:async e=>{const t=ve();t.log("community/deleteCommunity",e),await t.http.delete(`/api/v3/communities/${e}`);const r=await Mh(e);return Je("community.deleted",{communities:[r.data],categories:[],communityUsers:[],feeds:[],files:[],users:[]}),r.data},joinCommunity:async e=>{const t=ve();t.log("community/joinCommunity",e);const{data:r}=await t.http.post(`/api/v3/communities/${e}/join`);Je("community.joined",r);const n=xh(r),s=t.cache&&Date.now();t.cache&&Oo(n,{cachedAt:s});const{communityUsers:i}=n;return!!i.find((t=>t.communityId===e&&"member"===t.communityMembership))},leaveCommunity:async e=>{const t=ve();t.log("community/leaveCommunity",e);const{data:r}=await t.http.delete(`/api/v3/communities/${e}/leave`);Je("community.left",r);const n=xh(r),s=t.cache&&Date.now();t.cache&&Oo(n,{cachedAt:s});const{communityUsers:i}=n;return!!i.find((t=>t.communityId===e&&"member"!==t.communityMembership))},getTopTrendingCommunities:Fh,onCommunityCreated:Nh,onCommunityUpdated:Bh,onCommunityDeleted:jh,observeCommunity:(e,t)=>{const{log:r}=ve(),n=Date.now();r(`observeCommunity(tmpid: ${n}) > listen`);const s=(e,r)=>{var n,s;if(t instanceof Function)return t(e);"onFetch"!==r&&(null===(n=t.onEvent)||void 0===n||n.call(t,r,e)),null===(s=t[r])||void 0===s||s.call(t,e)},i=(t,r)=>{var n;(null===(n=t.data)||void 0===n?void 0:n.communityId)===e&&s(t,r)},a=[];return a.push(Bh((e=>i({data:e,loading:!1,origin:"event"},"onUpdate"))),jh((e=>i({data:e,loading:!1,origin:"event"},"onDelete"))),Jh((e=>i({data:e,loading:!1,origin:"event"},"onJoin"))),Zh((e=>i({data:e,loading:!1,origin:"event"},"onLeft"))),Hh((e=>i({data:e,loading:!1,origin:"event"},"onUserAdded"))),Vh((e=>i({data:e,loading:!1,origin:"event"},"onUserRemoved"))),zh((e=>i({data:e,loading:!1,origin:"event"},"onUserBanned"))),Yh((e=>i({data:e,loading:!1,origin:"event"},"onUserUnbanned")))),oe(ie(Mh,e),(e=>(e.data||e.error)&&s(e,"onFetch"))),()=>{r(`observeCommunity(tmpid: ${n}) > dispose`),a.forEach((e=>e()))}},getCommunities:(e,t,r)=>{const{log:n,cache:s,userId:i}=ve();s||console.log(p);const a=Date.now();n(`getCommunities(tmpid: ${a}) > listen`);const{limit:o}=e,l=Mo(e,["limit"]),c=null!=o?o:h,{policy:d=f}=null!=r?r:{},u=[],g=["community","collection",l],m=r=>{var n,s;let a=null!==(n=r.data.map((e=>Ee(["community","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];a=Ie(a,"displayName",e.displayName),e.includeDeleted||(a=Ae(a,"isDeleted",!1)),e.categoryId&&(a=a.filter((t=>{var r;return null===(r=t.categoryIds)||void 0===r?void 0:r.includes(e.categoryId)}))),e.tags&&(a=a.filter((t=>{var r;return null===(r=t.tags)||void 0===r?void 0:r.some((t=>{var r;return null===(r=e.tags)||void 0===r?void 0:r.includes(t)}))}))),e.membership&&i&&(a=De(a,e.membership,i));const o=e.sortBy||"lastCreated";"lastCreated"!==o&&"firstCreated"!==o||(a=a.sort("lastCreated"===o?Ne:Fe)),"displayName"===o&&(a=a.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Pe)),t({onNextPage:v,data:a,hasNextPage:!!(null===(s=r.params)||void 0===s?void 0:s.page),loading:r.loading,error:r.error})},y=e=>e=>{var t;const r=null===(t=Ee(g))||void 0===t?void 0:t.data;r&&(r.data=[...new Set([e.communityId,...r.data])],Se(g,r),m(r))},v=(e=!1)=>{var t,r;const n=null===(t=Ee(g))||void 0===t?void 0:t.data,s=null!==(r=null==n?void 0:n.data)&&void 0!==r?r:[];if(!e&&s.length>0&&!(null==n?void 0:n.params.page))return;const i=ie(ef,Object.assign(Object.assign({},l),{limit:e?c:void 0,page:e||null==n?void 0:n.params.page}));oe(i,(({data:t,error:r,loading:n,paging:i})=>{const a={loading:n,error:r,params:{page:null==i?void 0:i.next},data:s};t&&(a.data=e?t.map(de("community")):[...new Set([...s,...t.map(de("community"))])]),Se(g,a),m(a)}),ae(d,b))};return u.push(Nh(y()),jh(y()),Bh(y()),Jh(y()),Zh(y()),Wh(y())),v(!0),u.push((()=>ke(g))),()=>{n(`getCommunities(tmpid: ${a}) > dispose`),u.forEach((e=>e()))}},getCommunity:(e,t)=>pd(e,t,"communityId",Mh,[Bh,jh,Jh,Zh,zh,Yh,Wh]),getTrendingCommunities:(e,t,r)=>{const{log:n,cache:s,userId:i}=ve();s||console.log(p);const a=Date.now();n(`getTrendingCommunities(tmpid: ${a}) > listen`);const{limit:o}=e,l=null!=o?o:h,{policy:c=f}=null!=r?r:{},d=[],u=["community","top-trending",{params:{options:{limit:l}}}],g=(r,n=!1)=>{var s,a;const o=null!==(s=r.data.map((e=>Ee(["community","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==s?s:[];t({onNextPage:m,data:n?rf(o,e,i):o,hasNextPage:!!(null===(a=r.params)||void 0===a?void 0:a.page),loading:r.loading,error:r.error})},m=(t=!1)=>{var r,n;const s=null===(r=Ee(u))||void 0===r?void 0:r.data,i=null!==(n=null==s?void 0:s.data)&&void 0!==n?n:[];if(!t&&i.length>0&&!(null==s?void 0:s.params.page))return;const a=ie(tf,e);oe(a,(({data:t,error:r,loading:n})=>{const s={loading:n,error:r,params:e,data:i};t&&(s.data=[...new Set([...i,...t.map(de("community"))])]),Se(u,s),g(s)}),ae(c,b))};return d.push(Wh((e=>{var t;const r=null===(t=Ee(u))||void 0===t?void 0:t.data;r&&(r.data=[...new Set([e.communityId,...r.data])],Se(u,r),g(r))}))),m(!0),d.push((()=>ke(u))),()=>{n(`getTrendingCommunities(tmpid: ${a}) > dispose`),d.forEach((e=>e()))}},getRecommendedCommunities:(e,t,r)=>{const{log:n,cache:s,userId:i}=ve();s||console.log(p);const a=Date.now();n(`getRecommendedCommunities(tmpid: ${a}) > listen`);const{limit:o}=e;Mo(e,["limit"]);const l=null!=o?o:h,{policy:c=f}=null!=r?r:{},d=[],u=["community","recommended",{params:{options:{limit:l}}}],g=(r,n=!1)=>{var s,a;const o=null!==(s=r.data.map((e=>Ee(["community","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==s?s:[];t({onNextPage:m,data:n?rf(o,e,i):o,hasNextPage:!!(null===(a=r.params)||void 0===a?void 0:a.page),loading:r.loading,error:r.error})},m=(t=!1)=>{var r,n;const s=null===(r=Ee(u))||void 0===r?void 0:r.data,i=null!==(n=null==s?void 0:s.data)&&void 0!==n?n:[];if(!t&&i.length>0&&!(null==s?void 0:s.params.page))return;const a=ie(nf,e);oe(a,(({data:t,error:r,loading:n})=>{const s={loading:n,error:r,params:e,data:i};t&&(s.data=[...new Set([...i,...t.map(de("community"))])]),Se(u,s),g(s)}),ae(c,b))};return d.push(Wh((e=>{var t;const r=null===(t=Ee(u))||void 0===t?void 0:t.data;r&&(r.data=[...new Set([e.communityId,...r.data])],Se(u,r),g(r))}))),m(!0),d.push((()=>ke(u))),()=>{n(`getRecommendedCommunities(tmpid: ${a}) > dispose`),d.forEach((e=>e()))}}});const df=async e=>{const t=ve();t.log("category/getCategory",e);const{data:r}=await t.http.get(`/api/v3/community-categories/${encodeURIComponent(e)}`),n=t.cache&&Date.now();t.cache&&Oo(r,{cachedAt:n});const{categories:s}=r;return{data:il.category(s.find((t=>t.categoryId===e))),cachedAt:n}};df.locally=e=>{const t=ve();if(t.log("category/getCategory.locally",e),!t.cache)return;const r=Ee(["category","get",e]);return r?{data:il.category(r.data),cachedAt:r.cachedAt}:void 0};const uf=async e=>{const t=ve();t.log("category/queryCategories",e);const r=null!=e?e:{},{page:n,limit:s,includeDeleted:i}=r,a=Mo(r,["page","limit","includeDeleted"]),o=n?{token:n}:s?{limit:s}:void 0,{data:l}=await t.http.get("/api/v3/community-categories",{params:Object.assign(Object.assign({},a),{isDeleted:Al(i),options:o})}),{paging:c}=l,d=Mo(l,["paging"]),{categories:u}=d,h=t.cache&&Date.now();if(t.cache){Oo(d,{cachedAt:h});const e=["category","query",Object.assign(Object.assign({},a),{includeDeleted:i,options:o})];Se(e,{categories:u.map(de("category")),paging:c})}return{data:u,cachedAt:h,paging:c}};uf.locally=e=>{var t,r;const n=ve();if(n.log("category/queryCategories.locally",e),!n.cache)return;const s=null!=e?e:{},{page:i,limit:a=10}=s,o=Mo(s,["page","limit"]),l=i?{token:i}:a?{limit:a}:void 0,c=["category","query",Object.assign(Object.assign({},o),{options:l})],{data:d,cachedAt:u}=null!==(t=Ee(c))&&void 0!==t?t:{};if(!(null==d?void 0:d.categories.length))return;const h=d.categories.map((e=>Ee(["category","get",e]))).filter(Boolean).map((({data:e})=>e)),{paging:f}=d;return h.length===(null===(r=null==d?void 0:d.categories)||void 0===r?void 0:r.length)?{data:h,cachedAt:u,paging:f}:void 0};var hf=Object.freeze({__proto__:null,getCategory:df,getCategories:(e,t,r)=>{const{log:n,cache:s}=ve();s||console.log(p);const i=Date.now();n(`getCategories(tmpid: ${i}) > listen`);const{limit:a}=e,o=Mo(e,["limit"]),l=null!=a?a:h,{policy:c=f}=null!=r?r:{},d=[],u=["category","collection",{}],g=(r=!1)=>{var n,s;const i=null===(n=Ee(u))||void 0===n?void 0:n.data,a=null!==(s=null==i?void 0:i.data)&&void 0!==s?s:[];if(!r&&a.length>0&&!(null==i?void 0:i.params.page))return;const d=ie(uf,Object.assign(Object.assign({},o),{limit:r?l:void 0,page:r||null==i?void 0:i.params.page}));oe(d,(({data:r,error:n,loading:s,paging:i})=>{const o={loading:s,error:n,params:{page:null==i?void 0:i.next},data:a};r&&(o.data=[...new Set([...a,...r.map(de("category"))])]),Se(u,o),(r=>{var n,s;let i=null!==(n=r.data.map((e=>Ee(["category","get",e]))).filter(Boolean).map((({data:e})=>il.category(e))))&&void 0!==n?n:[];switch(e.includeDeleted||(i=Ae(i,"isDeleted",!1)),e.sortBy){case"firstCreated":i=i.sort(Fe);break;case"lastCreated":i=i.sort(Ne);break;default:i=i.sort(Me)}t({onNextPage:g,data:i,hasNextPage:!!(null===(s=r.params)||void 0===s?void 0:s.page),loading:r.loading,error:r.error})})(o)}),ae(c))};return d.push((()=>{})),g(!0),()=>{n(`getCategories(tmpid: ${i}) > dispose`),d.forEach((e=>e()))}}});const ff=async e=>{const t=ve();t.log("feed/queryGlobalFeed",e);const r=null!=e?e:{},{useCustomRanking:n,page:s,queryToken:i}=r,a=Mo(r,["useCustomRanking","page","queryToken"]);n&&console.warn('The param "useCustomRanking" has been deprecated. To get custom ranking feed use FeedRepository.getCustomRankingGlobalFeed instead'),s&&console.warn('The param "page" has been deprecated. Please use "queryToken" instead.');const o=i?{token:i}:s?{token:X(s,"skiplimit")}:void 0,{data:l}=await t.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},a),{options:o})}),{paging:c}=l,d=Mo(l,["paging"]),u=Uo(d,"communityUsers"),{posts:h}=u,f=t.cache&&Date.now();if(t.cache){Oo(u);const e=["globalFeed","query",Object.assign(Object.assign({},a),{options:Object.assign({},s)})];Se(e,{posts:h.map(de("post")),paging:c})}const p=J(c.next),g=J(c.previous);return{data:h.map(il.post),cachedAt:f,prevPage:g,nextPage:p,paging:c}};ff.locally=e=>{var t,r;const n=ve();if(n.log("post/queryGlobalFeed.locally",e),!n.cache)return;const s=null!=e?e:{},{page:i}=s,a=Mo(s,["page"]),o=["globalFeed","query",Object.assign(Object.assign({},a),{options:Object.assign({},i)})],{data:l,cachedAt:c}=null!==(t=Ee(o))&&void 0!==t?t:{};if(!(null==l?void 0:l.posts.length))return;const d=l.posts.map((e=>Ee(["post","get",e]))).filter(Boolean).map((({data:e})=>e)).map(il.post),{paging:u}=l,h=J(null==l?void 0:l.paging.previous),f=J(null==l?void 0:l.paging.next);return d.length===(null===(r=null==l?void 0:l.posts)||void 0===r?void 0:r.length)?{data:d,cachedAt:c,prevPage:h,nextPage:f,paging:u}:void 0};const pf=async e=>{const t=ve();t.log("feed/getCustomRankingGlobalFeed",e);const r=null!=e?e:{},{page:n,queryToken:s,limit:i}=r,a=Mo(r,["page","queryToken","limit"]),o=s?{token:s}:n?{token:X(n,"skiplimit")}:void 0,{data:l}=await t.http.get("/api/v5/me/global-feeds",{params:Object.assign(Object.assign({},a),{limit:s?void 0:i,options:o})}),{paging:c}=l,d=Mo(l,["paging"]),u=Uo(d,"communityUsers"),{posts:h}=u,f=t.cache&&Date.now();if(t.cache){Oo(u);const e=["customGlobalFeed","query",Object.assign(Object.assign({},a),{options:Object.assign({},n)})];Se(e,{posts:h.map(de("post")),paging:c})}const p=J(c.next),g=J(c.previous);return{data:h.map(il.post),cachedAt:f,prevPage:g,nextPage:p,paging:c}};pf.locally=e=>{var t,r;const n=ve();if(n.log("post/getCustomRankingGlobalFeed.locally",e),!n.cache)return;const s=null!=e?e:{},{page:i}=s,a=Mo(s,["page"]),o=["customGlobalFeed","query",Object.assign(Object.assign({},a),{options:Object.assign({},i)})],{data:l,cachedAt:c}=null!==(t=Ee(o))&&void 0!==t?t:{};if(!(null==l?void 0:l.posts.length))return;const d=l.posts.map((e=>Ee(["post","get",e]))).filter(Boolean).map((({data:e})=>e)),u=J(null==l?void 0:l.paging.previous),h=J(null==l?void 0:l.paging.next),{paging:f}=l;return d.length===(null===(r=null==l?void 0:l.posts)||void 0===r?void 0:r.length)?{data:d.map(il.post),cachedAt:c,prevPage:u,nextPage:h,paging:f}:void 0};var gf=Object.freeze({__proto__:null,queryGlobalFeed:ff,getCustomRankingGlobalFeed:pf});const mf=async e=>{const t=ve();t.log("post/getPostByIds",e);const r=e.map((e=>encodeURIComponent(e)));let n;try{n=(await t.http.get("/api/v3/posts/list",{params:{postIds:r}})).data}catch(t){throw e.forEach((e=>{C(null==t?void 0:t.code)&&Po("post",e)})),t}const s=Uo(n,"communityUsers"),i=t.cache&&Date.now();return t.cache&&Oo(s,{cachedAt:i}),{data:s.posts.map(il.post),cachedAt:i}};mf.locally=e=>{var t;const r=ve();if(r.log("post/getPostByIds.locally",e),!r.cache)return;const n=e.map((e=>Ee(["post","get",e]))).filter(Boolean),s=n.map((({data:e})=>e)),i=null===(t=n.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==n?void 0:n.length)<e.length?void 0:{data:s.map(il.post),cachedAt:i.cachedAt}};const yf=async(e,t=!1)=>{var r;const n=ve(),s=await Zd(e);if(await n.http.delete(`/api/v4/posts/${encodeURIComponent(e)}`,{params:{postId:e,permanent:t}}),"community"===s.data.targetType){const e=await Mh(s.data.targetId),t=(null!==(r=we(["communityUsers","get"]))&&void 0!==r?r:[]).filter((({key:t})=>"communityUsers"===t[0]&&("get"===t[1]&&("string"==typeof t[2]&&t[2].includes(e.data.communityId))))).map((({data:e})=>e));Je("community.updated",{communities:[e.data],categories:[],communityUsers:t,feeds:[],files:[],users:[]})}const i=Object.assign(Object.assign({},s.data),{isDeleted:!0});return Je("post.deleted",{posts:[i],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[]}),t?setTimeout((()=>{Po("post",e)}),0):Ce(["post","get",e],{isDeleted:!0}),il.post(i)},vf=async e=>{const t=ve();t.log("post/queryPosts",e);const{page:r,limit:n=10,includeDeleted:s}=e,i=Mo(e,["page","limit","includeDeleted"]),{dataTypes:a,matchingOnlyParentPost:o}=i,l=r?{token:r}:n?{limit:n}:void 0,{data:c}=await t.http.get("/api/v4/posts",{params:Object.assign(Object.assign({},i),{isDeleted:Al(s),matchingOnlyParentPost:null!=o?o:!(null==a?void 0:a.length),options:l})}),{paging:d}=c,u=Mo(c,["paging"]),h=Uo(u,"communityUsers"),{posts:f}=u,p=t.cache&&Date.now();if(t.cache){Oo(h,{cachedAt:p});const e=["post","query",Object.assign(Object.assign({},i),{options:l})];Se(e,{posts:f.map(de("post")),paging:d})}return{data:f.map(il.post),cachedAt:p,paging:d}};var bf=Object.freeze({__proto__:null,getPostByIds:mf,createPost:async e=>{const t=ve();t.log("post/createPost",e),e.dataType&&!["text","image","file","video"].includes(e.dataType)||delete e.dataType;const{data:r}=await t.http.post("/api/v4/posts",e);Je("post.created",r);const n=Uo(r,"communityUsers"),s=t.cache&&Date.now();t.cache&&Oo(n,{cachedAt:s});const{posts:i}=n;return{data:il.post(i[0]),cachedAt:s}},updatePost:async(e,t)=>{const r=ve();r.log("user/updatePost",t),console.warn("Deprecation: updatePost has been renamed to editPost. Update post API will be deprecated soon.");const{data:n}=await r.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,t),s=Uo(n,"communityUsers"),i=r.cache&&Date.now();r.cache&&Oo(s,{cachedAt:i}),Je("post.updated",s);const{posts:a}=s;return{data:il.post(a.find((t=>t.postId===e))),cachedAt:i}},editPost:async(e,t)=>{const r=ve();r.log("user/editPost",t);const{data:n}=await r.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,t),s=Uo(n,"communityUsers"),i=r.cache&&Date.now();r.cache&&Oo(s,{cachedAt:i}),Je("post.updated",s);const{posts:a}=s;return{data:il.post(a.find((t=>t.postId===e))),cachedAt:i}},deletePost:yf,softDeletePost:async e=>{ve().log("post/softDeletePost",e);const t=await yf(e,!1);return il.post(t)},hardDeletePost:async e=>{ve().log("post/hardDeletePost",e);const t=await yf(e,!0);return il.post(t)},approvePost:async e=>{const t=ve();t.log("post/approvePost",e);const{data:r}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/approve`);Je("post.approved",r),"community"===r.posts[0].targetType&&Je("community.updated",r);const n=Uo(r,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Oo(n,{cachedAt:s}),{data:il.post(n.posts.find((t=>t.postId===e))),cachedAt:s}},declinePost:async e=>{const t=ve();t.log("post/declinePost",e);const{data:r}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/decline`);"community"===r.posts[0].targetType&&Je("community.updated",r),Je("post.declined",r);const n=Uo(r,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Oo(n,{cachedAt:s}),{data:il.post(r.posts.find((t=>t.postId===e))),cachedAt:s}},flagPost:async e=>{const t=ve();t.log("post/flagPost",e);const{data:r}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/flag`);return t.cache&&Oo(Uo(r,"communityUsers")),Je("post.flagged",r),!!r},unflagPost:async e=>{const t=ve();t.log("post/unflagPost",e);const{data:r}=await t.http.delete(`/api/v3/posts/${encodeURIComponent(e)}/unflag`);return t.cache&&Oo(Uo(r,"communityUsers")),Je("post.unflagged",r),!!r},isPostFlaggedByMe:async e=>{const t=ve();t.log("post/isPostFlaggedByMe",e);const{data:{result:r}}=await t.http.get(`/api/v3/posts/${e}/isflagbyme`);return r},onPostCreated:cu,onPostUpdated:du,onPostDeleted:uu,onPostApproved:hu,onPostDeclined:fu,onPostFlagged:pu,onPostUnflagged:gu,onPostReactionAdded:mu,onPostReactionRemoved:yu,observePosts:(e,t)=>{const{log:r}=ve(),n=Date.now();r(`observePosts(tmpid: ${n}) > listen`);const s=[],i=(r,n)=>{var s,i;if(e.targetId===r.targetId&&e.targetType===r.targetType){if(t instanceof Function)return t(il.post(r));null===(s=t.onEvent)||void 0===s||s.call(t,n,il.post(r)),null===(i=t[n])||void 0===i||i.call(t,il.post(r))}};return s.push(cu((e=>i(e,"onCreate"))),du((e=>i(e,"onUpdate"))),uu((e=>i(e,"onDelete"))),hu((e=>i(e,"onApproved"))),fu((e=>i(e,"onDeclined"))),pu((e=>i(e,"onFlagged"))),gu((e=>i(e,"onUnflagged"))),mu((e=>i(e,"onReactionAdded"))),yu((e=>i(e,"onReactionRemoved")))),()=>{r(`observePosts(tmpid: ${n}) > dispose`),s.forEach((e=>e()))}},observePost:(e,t,r="cache_then_server")=>{const{log:n}=ve(),s=Date.now();n(`observePost(tmpid: ${s}) > listen`);const i=(e,r)=>{var n,s;if(t instanceof Function)return t(e);"onFetch"!==r&&(null===(n=t.onEvent)||void 0===n||n.call(t,r,e)),null===(s=t[r])||void 0===s||s.call(t,e)},a=(t,r)=>{var n;(null===(n=t.data)||void 0===n?void 0:n.postId)===e&&i(Object.assign(Object.assign({},t),{data:t.data&&il.post(t.data)}),r)},o=[];return o.push(du((e=>a({data:e,loading:!1,origin:"event"},"onUpdate"))),uu((e=>a({data:e,loading:!1,origin:"event"},"onDelete"))),hu((e=>a({data:e,loading:!1,origin:"event"},"onApproved"))),fu((e=>a({data:e,loading:!1,origin:"event"},"onDeclined"))),pu((e=>a({data:e,loading:!1,origin:"event"},"onFlagged"))),gu((e=>a({data:e,loading:!1,origin:"event"},"onUnflagged"))),mu((e=>a({data:e,loading:!1,origin:"event"},"onReactionAdded"))),yu((e=>a({data:e,loading:!1,origin:"event"},"onReactionRemoved")))),oe(ie(Zd,e),(e=>(e.data||e.error)&&i(Object.assign(Object.assign({},e),{data:e.data&&il.post(e.data)}),"onFetch")),ae(r)),()=>{n(`observePosts(tmpid: ${s}) > dispose`),o.forEach((e=>e()))}},getPost:(e,t)=>pd(e,t,"postId",Zd,[hu,fu,t=>uu((r=>{var n;let s=r;if(r.parentPostId===e&&r.isDeleted){const e=null===(n=Ee(["post","get",r.parentPostId]))||void 0===n?void 0:n.data;e&&(e.children=e.children.filter((e=>e!==r.postId)),Se(["post","get",e.postId],e),s=e)}t(s)})),pu,mu,yu,gu,du]),getPosts:(e,t,r)=>{const{log:n,cache:s}=ve();s||console.log(p);const i=Date.now();n(`getPosts(tmpid: ${i}) > listen`);const{limit:a}=e,o=Mo(e,["limit"]),l=null!=a?a:h,{policy:c=f}=null!=r?r:{},d=[],u=["post","collection",{targetId:e.targetId,targetType:e.targetType}],g=r=>{var n,s,i;let a=null!==(n=r.data.map((e=>Ee(["post","get",e]))).filter(Boolean).map((({data:e})=>il.post(e))))&&void 0!==n?n:[];const o=e.sortBy?e.sortBy:"lastCreated";a=a.sort("lastCreated"===o?Ne:Fe),e.includeDeleted||(a=Ae(a,"isDeleted",!1)),e.tags&&(a=a.filter((t=>{var r;return null===(r=t.tags)||void 0===r?void 0:r.some((t=>{var r;return null===(r=e.tags)||void 0===r?void 0:r.includes(t)}))}))),"community"===e.targetType&&e.feedType&&(a=Le(a,e.feedType)),(null===(s=e.dataTypes)||void 0===s?void 0:s.length)&&(a=xe(a,e.dataTypes)),t({onNextPage:y,data:a,hasNextPage:!!(null===(i=r.params)||void 0===i?void 0:i.page),loading:r.loading,error:r.error})},m=t=>r=>{var n,s;const i=null===(n=Ee(u))||void 0===n?void 0:n.data;if(i){if(r.parentPostId&&r.isDeleted){const t=null===(s=Ee(["post","get",r.parentPostId]))||void 0===s?void 0:s.data;if(!t||(null==t?void 0:t.targetId)!==e.targetId)return;t.children=t.children.filter((e=>e!==r.postId)),Se(["post","get",t.postId],t)}else{if(e.targetId!==r.targetId)return;if(e.targetType!==r.targetType)return}i.data="onDeclined"===t?i.data.filter((e=>e!==r.postId)):[...new Set([r.postId,...i.data])],Se(u,i),g(i)}},y=(e=!1)=>{var t,r,n;const s=null===(t=Ee(u))||void 0===t?void 0:t.data,i=null!==(r=null==s?void 0:s.data)&&void 0!==r?r:[];if(!e&&i.length>0&&!(null===(n=null==s?void 0:s.params)||void 0===n?void 0:n.page))return;const a=ie(vf,Object.assign(Object.assign({},o),{limit:e?l:void 0,page:e||null==s?void 0:s.params.page}));oe(a,(({data:t,error:r,loading:n,paging:s})=>{const a={loading:n,error:r,params:{page:null==s?void 0:s.next},data:i};t&&(a.data=e?t.map(de("post")):[...new Set([...i,...t.map(de("post"))])]),Se(u,a),g(a)}),ae(c,b))};return d.push(cu(m("onCreate")),hu(m("onApproved")),fu(m("onDeclined")),uu(m("onDelete")),du(m("onUpdate")),pu(m("onFlagged")),gu(m("onUnflagged")),mu(m("onReactionAdded")),yu(m("onReactionRemoved"))),y(!0),d.push((()=>ke(u))),()=>{n(`getPosts(tmpid: ${i}) > dispose`),d.forEach((e=>e()))}}});const wf=async e=>{const t=ve();t.log("comment/getCommentByIds",e);const r=e.map((e=>encodeURIComponent(e)));let n;try{n=(await t.http.get("/api/v3/comments/list",{params:{commentIds:r}})).data}catch(t){throw e.forEach((e=>{C(null==t?void 0:t.code)&&Po("comment",e)})),t}const s=t.cache&&Date.now();return t.cache&&Oo(n,{cachedAt:s}),{data:n.comments.map((e=>il.comment(e))),cachedAt:s}};wf.locally=e=>{var t;const r=ve();if(r.log("comment/getCommentByIds.locally",e),!r.cache)return;const n=e.map((e=>Ee(["comment","get",e]))).filter(Boolean),s=n.map((({data:e})=>e)),i=null===(t=n.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==n?void 0:n.length)<e.length?void 0:{data:s.map((e=>il.comment(e))),cachedAt:i.cachedAt}};const Ef=(e,t=!1)=>{const{stories:r}=e,n=r.map((e=>((e,t=!1)=>{const{storyId:r,referenceId:n}=e;return!t&&n?Object.assign(Object.assign({},e),{syncState:"synced"}):Object.assign(Object.assign({},e),{syncState:"synced",referenceId:r})})(e,t)));return Object.assign(Object.assign({},e),{stories:n})},Sf=async e=>{const t=ve();t.log("story/getStoryByStoryId",e);const r=Ee(["story-reference",e]);if(null==r?void 0:r.data){const{data:e}=r;ql("story",e)}let n;try{const r=await t.http.get(`/api/v4/stories/${e}`);n=Ef(r.data)}catch(t){throw C(null==t?void 0:t.code)&&Po("story",e),t}const s=t.cache&&Date.now();return t.cache&&Oo(n,{cachedAt:s}),{data:n.stories[0],cachedAt:s}};Sf.locally=e=>{const t=ve();t.log("story/getStorybyStoryId",e);const r=Ee(["story-reference",e]);if(null==r?void 0:r.data){const{data:e}=r;ql("story",e)}const n=t.cache&&Date.now(),s=Ee(["story","get",e]);if(s)return{data:s.data,cachedAt:n}};const Tf=async(e,t=!1)=>{const r=ve(),n=await eu(e);await r.http.delete(`/api/v4/comments/${encodeURIComponent(e)}`,{params:{commentId:e,permanent:t}});const s=Object.assign(Object.assign({},n.data),{isDeleted:!0});if("story"===n.data.referenceType){const e=await Sf(n.data.referenceId);Je("local.story.updated",{stories:[e.data],categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[]})}else{const e=await Zd(n.data.referenceId);Je("post.updated",{posts:[e.data],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[]})}return Je("comment.deleted",{comments:[s],commentChildren:[],files:[],users:[],communityUsers:[]}),t?ze((()=>Po("comment",e))):Ce(["comment","get",e],{isDeleted:!0}),s},Cf=async e=>{const t=ve();let r;t.log("comment/getComment",e),ql("comment",e);try{r=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw C(null==t?void 0:t.code)&&Po("comment",e),t}const n=t.cache&&Date.now();t.cache&&Oo(r,{cachedAt:n});const{comments:s}=r;return{data:s.find((t=>t.commentId===e)),cachedAt:n}};Cf.locally=e=>{const t=ve();if(t.log("comment/getComment.locally",e),!t.cache)return;const r=Ee(["comment","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const kf=async e=>{const t=ve();t.log("comment/queryComments",e);const{limit:r=10,includeDeleted:n}=e,s=Mo(e,["limit","includeDeleted"]),i={type:s.sortBy||e.limit?"pagination":void 0,limit:e.limit,token:e.page},{data:a}=await t.http.get("/api/v3/comments",{params:Object.assign(Object.assign({},s),{isDeleted:Al(n),options:i})}),{paging:o}=a,l=(e=>{const{comments:t}=e;return Object.assign(Object.assign({},e),{comments:t.map((e=>e.hasOwnProperty("myReactions")?e:Object.assign({myReactions:[]},e)))})})(Mo(a,["paging"])),{comments:c}=l,d=t.cache&&Date.now();if(t.cache){Oo(l,{cachedAt:d});const e=["comment","query",Object.assign(Object.assign({},s),{options:{limit:r}})];Se(e,{comments:c.map(de("comment")),paging:o})}return{data:c,cachedAt:d,paging:o}};var Af=Object.freeze({__proto__:null,getCommentByIds:wf,createComment:async e=>{const t=ve();t.log("comment/createComment",e);const{data:r}=await t.http.post("/api/v3/comments",e),{comments:n}=r;if(0===n.length)throw new Error("Comment not created");const s=t.cache&&Date.now();if(t.cache&&Oo(r,{cachedAt:s}),["post","content"].includes(e.referenceType)){const t=await Zd(e.referenceId);Je("post.updated",{posts:[t.data],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[]})}else if("story"===e.referenceType){const t=Ee(["story-reference",e.referenceId]);if(null==t?void 0:t.data){const e=Ee(["story","get",t.data]);(null==e?void 0:e.data)&&Je("story.updated",{stories:[Object.assign(Object.assign({},e.data),{commentsCount:e.data.commentsCount+1,comments:[...new Set([...e.data.comments,n[0].commentId])]})],categories:[],comments:n,communities:[],communityUsers:r.communityUsers,files:r.files,users:r.users})}}return Je("comment.created",r),{data:il.comment(n[0]),cachedAt:s}},updateComment:async(e,t)=>{const r=ve();r.log("user/updateComment",t);const{data:n}=await r.http.put(`/api/v3/comments/${encodeURIComponent(e)}`,t),s=r.cache&&Date.now();r.cache&&Oo(n,{cachedAt:s}),Je("comment.updated",n);const{comments:i}=n;return{data:il.comment(i.find((t=>t.commentId===e))),cachedAt:s}},deleteComment:Tf,softDeleteComment:async e=>{ve().log("comment/softDeleteComment",e);return Tf(e)},hardDeleteComment:async e=>{ve().log("comment/hardDeleteComment",e);return Tf(e,!0)},flagComment:async e=>{const t=ve();t.log("comment/flagComment",e);const{data:r}=await t.http.post(`/api/v3/comments/${encodeURIComponent(e)}/flag`);return t.cache&&Oo(r),Je("comment.flagged",r),!!r},unflagComment:async e=>{const t=ve();t.log("comment/unflagComment",e);const{data:r}=await t.http.delete(`/api/v3/comments/${encodeURIComponent(e)}/unflag`);return t.cache&&Oo(r),Je("comment.unflagged",r),!!r},isCommentFlaggedByMe:async e=>{const t=ve();t.log("comment/isCommentFlaggedByMe",e);const{data:{result:r}}=await t.http.get(`/api/v3/comments/${e}/isflagbyme`);return r},onCommentCreated:bu,onCommentUpdated:wu,onCommentDeleted:Eu,onCommentFlagged:Su,onCommentUnflagged:Tu,onCommentReactionAdded:Cu,onCommentReactionRemoved:ku,observeComments:(e,t)=>{const{log:r}=ve(),n=Date.now();r(`observeComments(tmpid: ${n}) > listen`);const s=[],i=(r,n)=>{var s,i;if(r.referenceId===e){if(t instanceof Function)return t(r);null===(s=t.onEvent)||void 0===s||s.call(t,n,r),null===(i=t[n])||void 0===i||i.call(t,r)}};return s.push(bu((e=>i(e,"onCreate"))),wu((e=>i(e,"onUpdate"))),Eu((e=>i(e,"onDelete"))),Su((e=>i(e,"onFlagged"))),Tu((e=>i(e,"onUnflagged"))),Cu((e=>i(e,"onReactionAdded"))),ku((e=>i(e,"onReactionRemoved")))),()=>{r(`observeComments(tmpid: ${n}) > dispose`),s.forEach((e=>e()))}},observeComment:(e,t,r="cache_then_server")=>{const{log:n}=ve(),s=Date.now();n(`observeComment(tmpid: ${s}) > listen`);const i=(e,r)=>{var n,s;if(t instanceof Function)return t(e);"onFetch"!==r&&(null===(n=t.onEvent)||void 0===n||n.call(t,r,e)),null===(s=t[r])||void 0===s||s.call(t,e)},a=(t,r)=>{var n;(null===(n=t.data)||void 0===n?void 0:n.commentId)===e&&i(t,r)},o=[];return o.push(wu((e=>a({data:e,loading:!1,origin:"event"},"onUpdate"))),Eu((e=>a({data:e,loading:!1,origin:"event"},"onDelete"))),Su((e=>a({data:e,loading:!1,origin:"event"},"onFlagged"))),Tu((e=>a({data:e,loading:!1,origin:"event"},"onUnflagged"))),Cu((e=>a({data:e,loading:!1,origin:"event"},"onReactionAdded"))),ku((e=>a({data:e,loading:!1,origin:"event"},"onReactionRemoved")))),oe(ie(Cf,e),(e=>(e.data||e.error)&&i(e,"onFetch")),ae(r)),()=>{n(`observeComment(tmpid: ${s}) > dispose`),o.forEach((e=>e()))}},getComment:(e,t)=>pd(e,t,"commentId",Cf,[Eu,Su,Cu,ku,Tu,wu,t=>bu((r=>{if(r.parentId!==e)return;const n=Ee(["comment","get",r.parentId]);(null==n?void 0:n.data)&&t(Object.assign(Object.assign({},n.data),{childrenNumber:n.data.childrenNumber+1,children:[...new Set([...n.data.children,r.commentId])]}))}))]),getComments:(e,t,r)=>{const{log:n,cache:s}=ve();s||console.log("For using Live Collection feature you need to enable Cache!");const i=Date.now();n(`getComments(tmpid: ${i}) > listen`);const{limit:a}=e,o=Mo(e,["limit"]),{policy:l=f}=null!=r?r:{},c=[],d=["comment","collection",{referenceId:e.referenceType,referenceType:e.referenceId,parentId:(null==e?void 0:e.parentId)||""}],u=r=>{var n,s;let i=null!==(n=r.data.map((e=>Ee(["comment","get",e]))).filter((({data:t})=>t.parentId===(null==e?void 0:e.parentId))).filter(Boolean).map((({data:e})=>il.comment(e))))&&void 0!==n?n:[];e.includeDeleted||(i=Ae(i,"isDeleted",!1));const a=e.sortBy?e.sortBy:"lastCreated";i=i.sort("lastCreated"===a?Ne:Fe),t({onNextPage:p,data:i,hasNextPage:!!(null===(s=r.params)||void 0===s?void 0:s.page),loading:r.loading,error:r.error})},h=t=>r=>{var n;const s=null===(n=Ee(d))||void 0===n?void 0:n.data;e.referenceId===r.referenceId&&e.referenceType===r.referenceType&&s&&("onCreate"===t?s.data=[...new Set([r.commentId,...s.data])]:"onDelete"===t&&(s.data=s.data.filter((e=>e!==r.commentId))),Se(d,s),u(s))},p=(e=!1)=>{var t,r,n;const s=null===(t=Ee(d))||void 0===t?void 0:t.data,i=null!==(r=null==s?void 0:s.data)&&void 0!==r?r:[];if(!e&&i.length>0&&!(null===(n=null==s?void 0:s.params)||void 0===n?void 0:n.page))return;const c=ie(kf,Object.assign(Object.assign({},o),{limit:a,page:e||null==s?void 0:s.params.page}));oe(c,(({data:t,error:r,loading:n,paging:s})=>{const a={loading:n,error:r,params:{page:"lastCreated"===(o.sortBy||"lastCreated")?null==s?void 0:s.next:null==s?void 0:s.previous},data:i};t&&(a.data=e?t.map(de("comment")):[...new Set([...i,...t.map(de("comment"))])]),Se(d,a),u(a)}),ae(l,b))};return c.push(bu(h("onCreate")),wu(h("onUpdate")),Eu(h("onDelete")),Su(h("onFlagged")),Tu(h("onUnflagged")),Cu(h("onReactionAdded")),ku(h("onReactionRemoved"))),p(!0),c.push((()=>ke(d))),()=>{n(`getComments(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}}});const If=async e=>{const t=ve();t.log("stream/getStream",e);const{data:r}=await t.http.get(`/api/v3/video-streaming/${e}`),n=t.cache&&Date.now();t.cache&&Oo(r,{cachedAt:n});const{videoStreamings:s}=r;return{data:s.find((t=>t.streamId===e)),cachedAt:n}};If.locally=e=>{const t=ve();if(t.log("stream/getStream",e),!t.cache)return;const r=Ee(["stream","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const _f=e=>{const t=ve();return Xe(t,"stream/onStreamStarted","video-streaming.didStart",(t=>{Oo(t),e(t.videoStreamings[0])}))},Rf=e=>{const t=ve();return Xe(t,"stream/onStreamStarted","video-streaming.didStop",(t=>{Oo(t),e(t.videoStreamings[0])}))},Lf=e=>{const t=ve();return Xe(t,"stream/onStreamRecorded","video-streaming.didRecord",(t=>{Oo(t),e(t.videoStreamings[0])}))},Df=(e,t)=>pd(e,t,"streamId",If,[Lf,_f,Rf]);Df.locally=e=>{const t=ve();if(t.log("stream/getStreamById",e),!t.cache)return;const r=Ee(["stream","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const xf=async e=>{const t=ve();t.log("stream/queryStreams",e);const r=null!=e?e:{},{page:n,limit:s}=r,i=Mo(r,["page","limit"]),a=n?{token:n}:s?{limit:s}:void 0,{data:o}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},i),{options:a})}),{paging:l,results:c}=o,{videoStreamings:d}=c,u=t.cache&&Date.now();return t.cache&&Oo(c,{cachedAt:u}),{data:d,cachedAt:u,paging:l}};var Of=Object.freeze({__proto__:null,createStream:async e=>{const t=ve();t.log("stream/createStream",e);const{data:r}=await t.http.post("/api/v3/video-streaming",e),n=t.cache&&Date.now();t.cache&&Oo(r,{cachedAt:n});const{videoStreamings:s}=r;return{data:s[0],cachedAt:n}},updateStream:async(e,t)=>{const r=ve();r.log("stream/updateStream",e,t);const{data:n}=await r.http.put(`/api/v3/video-streaming/${e}`,t),s=r.cache&&Date.now();r.cache&&Oo(n,{cachedAt:s});const{videoStreamings:i}=n;return{data:i.find((t=>t.streamId===e)),cachedAt:s}},deleteStream:async e=>{const t=ve();t.log("stream/deleteStream",e);const r=await If(e),{data:n}=await t.http.delete(`/api/v3/video-streaming/${e}`),{success:s}=n,i=Object.assign(Object.assign({},r.data),{isDeleted:!0});return Ce(["stream","get",e],i),s},disposeStream:async e=>{const t=ve();t.log("stream/disposeStream",e);const{data:r}=await t.http.delete(`/api/v3/video-streaming/${e}/streaming-url`),n=t.cache&&Date.now();t.cache&&Oo(r,{cachedAt:n});const{videoStreamings:s}=r;return{data:s.find((t=>t.streamId===e)),cachedAt:n}},queryStreams:async e=>{const t=ve();t.log("stream/queryStreams",e);const r=null!=e?e:{},{page:n}=r,s=Mo(r,["page"]),{data:i}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},s),{options:{token:X(n,"skiplimit")}})}),{paging:a,results:o}=i,{videoStreamings:l}=o,c=t.cache&&Date.now();t.cache&&Oo(o,{cachedAt:c});const d=J(a.next);return{data:l,cachedAt:c,prevPage:J(a.previous),nextPage:d}},getStream:If,onStreamStarted:_f,onStreamStopped:Rf,onStreamRecorded:Lf,getStreamById:Df,getStreams:(e,t,r)=>{const{log:n,cache:s}=ve();s||console.log(p);const i=Date.now();n(`getStreams(tmpid: ${i}) > listen`);const{limit:a}=e,o=Mo(e,["limit"]),l=null!=a?a:h,{policy:c=f}=null!=r?r:{},d=[],u=["streams","collection",e],g=t=>{let r=Ae(t,"isDeleted",e.isDeleted);return r=r.sort("lastCreated"===e.sortBy?Ne:Fe),r},m=(e,r=!1)=>{var n,s;const i=null!==(n=e.data.map((e=>Ee(["stream","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];t({onNextPage:v,data:r?g(i):i,hasNextPage:!!(null===(s=e.params)||void 0===s?void 0:s.page),loading:e.loading,error:e.error})},y=e=>e=>{var t;const r=null===(t=Ee(u))||void 0===t?void 0:t.data;r&&(r.data=[...new Set([e.streamId,...r.data])],Se(u,r),m(r,!0))},v=(e=!1)=>{var t,r;const n=null===(t=Ee(u))||void 0===t?void 0:t.data,s=null!==(r=null==n?void 0:n.data)&&void 0!==r?r:[];if(!e&&s.length>0&&!(null==n?void 0:n.params.page))return;const i=ie(xf,Object.assign(Object.assign({},o),{limit:e?l:void 0,page:e||null==n?void 0:n.params.page}));oe(i,(({data:e,error:t,loading:r,paging:n})=>{const i={loading:r,error:t,params:{page:null==n?void 0:n.next},data:s};e&&(i.data=[...new Set([...s,...e.map(de("stream"))])]),Se(u,i),m(i)}),ae(c))};return d.push(Lf(y()),_f(y()),Rf(y())),v(!0),()=>{n(`getStreams(tmpid: ${i}) > dispose`),d.forEach((e=>e()))}}});const Pf=async e=>{const t=ve();t.log("poll/getPoll",e);const{data:r}=await t.http.get(`/api/v3/polls/${e}`),n=t.cache&&Date.now();t.cache&&Oo(r,{cachedAt:n});const{polls:s}=r;return{data:s.find((t=>t.pollId===e)),cachedAt:n}};Pf.locally=e=>{const t=ve();if(t.log("poll/getPoll",e),!t.cache)return;const r=Ee(["poll","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const Mf=e=>{const t=ve();return Xe(t,"poll/onPollUpdated","poll.updated",(r=>{t.cache&&Oo(r),e(r.polls[0])}))},Ff=e=>{const t=ve();return Xe(t,"poll/onPollDeleted","poll.deleted",(r=>{t.cache&&Oo(r),e(r.polls[0])}))};var Uf=Object.freeze({__proto__:null,createPoll:async e=>{const t=ve();t.log("post/createPoll",e);const{data:r}=await t.http.post("/api/v3/polls",e),n=t.cache&&Date.now();t.cache&&Oo(r,{cachedAt:n});const{polls:s}=r;return{data:s[0],cachedAt:n}},closePoll:async e=>{const t=ve();t.log("user/closePoll",e);const{data:r}=await t.http.put(`/api/v3/polls/${encodeURIComponent(e)}`,{status:"closed"}),n=t.cache&&Date.now();t.cache&&Oo(r,{cachedAt:n}),Je("poll.updated",r);const{polls:s}=r;return{data:s.find((t=>t.pollId===e)),cachedAt:n}},deletePoll:async e=>{const t=ve();t.log("poll/deletePoll",e);const r=await Pf(e),{data:n}=await t.http.delete(`/api/v3/polls/${e}`),{success:s}=n,i=Object.assign(Object.assign({},r.data),{isDeleted:!0});return Ce(["poll","get",e],i),Je("poll.deleted",{polls:[i],users:[]}),s},votePoll:async(e,t)=>{const r=ve();r.log("user/votePoll",e);const{data:n}=await r.http.post(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:t}),s=r.cache&&Date.now();r.cache&&Oo(n,{cachedAt:s});const{polls:i}=n;return Je("poll.updated",n),{data:i.find((t=>t.pollId===e)),cachedAt:s}},onPollUpdated:Mf,onPollDeleted:Ff,observePoll:(e,t,r="cache_then_server")=>{const{log:n}=ve(),s=Date.now();n(`observePoll(tmpid: ${s}) > listen`);const i=(e,r)=>{var n,s;if(t instanceof Function)return t(e);"onFetch"!==r&&(null===(n=t.onEvent)||void 0===n||n.call(t,r,e)),null===(s=t[r])||void 0===s||s.call(t,e)},a=(t,r)=>{var n;(null===(n=t.data)||void 0===n?void 0:n.pollId)===e&&i(t,r)},o=[];return o.push(Mf((e=>a({data:e,loading:!1,origin:"event"},"onUpdate"))),Ff((e=>a({data:e,loading:!1,origin:"event"},"onDelete")))),oe(ie(Pf,e),(e=>(e.data||e.error)&&i(e,"onFetch")),ae(r)),()=>{n(`observePoll(tmpid: ${s}) > dispose`),o.forEach((e=>e()))}},getPoll:(e,t)=>pd(e,t,"pollId",Pf,[Mf,Ff])});function Nf(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Bf={exports:{}};!function(e,t){var r,n,s,i,a;r=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,n=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,i=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,r){if(r=r||{},e=e.trim(),!(t=t.trim())){if(!r.alwaysNormalize)return e;var s=a.parseURL(e);if(!s)throw new Error("Error trying to parse base URL.");return s.path=a.normalizePath(s.path),a.buildURLFromParts(s)}var i=a.parseURL(t);if(!i)throw new Error("Error trying to parse relative URL.");if(i.scheme)return r.alwaysNormalize?(i.path=a.normalizePath(i.path),a.buildURLFromParts(i)):t;var o=a.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=n.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var c={scheme:o.scheme,netLoc:i.netLoc,path:null,params:i.params,query:i.query,fragment:i.fragment};if(!i.netLoc&&(c.netLoc=o.netLoc,"/"!==i.path[0]))if(i.path){var d=o.path,u=d.substring(0,d.lastIndexOf("/")+1)+i.path;c.path=a.normalizePath(u)}else c.path=o.path,i.params||(c.params=o.params,i.query||(c.query=o.query));return null===c.path&&(c.path=r.alwaysNormalize?a.normalizePath(i.path):i.path),a.buildURLFromParts(c)},parseURL:function(e){var t=r.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(s,"");e.length!==(e=e.replace(i,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},e.exports=a}(Bf);var jf=Bf.exports;function $f(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function qf(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?$f(Object(r),!0).forEach((function(t){Kf(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):$f(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Kf(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Gf(){return Gf=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Gf.apply(this,arguments)}const Hf=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)};let Vf=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e}({}),zf=function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e}({}),Wf=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.UNKNOWN="unknown",e}({});const Yf=function(){},Qf={trace:Yf,debug:Yf,log:Yf,warn:Yf,info:Yf,error:Yf};let Xf=Qf;function Jf(e,...t){t.forEach((function(t){Xf[t]=e[t]?e[t].bind(e):function(e){const t=self.console[e];return t?t.bind(self.console,`[${e}] >`):Yf}(t)}))}const Zf=Xf,ep=/^(\d+)x(\d+)$/,tp=/(.+?)=(".*?"|.*?)(?:,|$)/g;class rp{constructor(e){"string"==typeof e&&(e=rp.parseAttrList(e));for(const t in e)e.hasOwnProperty(t)&&("X-"===t.substring(0,2)&&(this.clientAttrs=this.clientAttrs||[],this.clientAttrs.push(t)),this[t]=e[t])}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;const r=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)r[e]=parseInt(t.slice(2*e,2*e+2),16);return r}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const r=this[e];return r?parseFloat(r):t}enumeratedString(e){return this[e]}bool(e){return"YES"===this[e]}decimalResolution(e){const t=ep.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t;const r={};for(tp.lastIndex=0;null!==(t=tp.exec(e));){let e=t[2];0===e.indexOf('"')&&e.lastIndexOf('"')===e.length-1&&(e=e.slice(1,-1));r[t[1].trim()]=e}return r}}function np(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e}class sp{constructor(e,t){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,t){const r=t.attr;for(const t in r)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==r[t]){Zf.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=Gf(new rp({}),r,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const e=new Date(this.attr["END-DATE"]);Hf(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const e=this.duration;return null!==e?new Date(this._startDate.getTime()+1e3*e):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(Hf(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isValid(){return!!this.id&&!this._badValueForSameId&&Hf(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class ip{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var ap="audio",op="video",lp="audiovideo";class cp{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[ap]:null,[op]:null,[lp]:null},this.baseurl=e}setByteRange(e,t){const r=e.split("@",2),n=[];1===r.length?n[0]=t?t.byteRangeEndOffset:0:n[0]=parseInt(r[1]),n[1]=parseInt(r[0])+n[0],this._byteRange=n}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=jf.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class dp extends cp{constructor(e,t){super(t),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new ip,this.urlId=0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.type=e}get decryptdata(){const{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const e=this.levelkeys.identity;if(e)this._decryptdata=e.getDecryptData(this.sn);else{const e=Object.keys(this.levelkeys);if(1===e.length)return this._decryptdata=this.levelkeys[e[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;if(!Hf(this.programDateTime))return null;const e=Hf(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){const e=Object.keys(this.levelkeys),t=e.length;if(t>1||1===t&&this.levelkeys[e[0]].encrypted)return!0}return!1}setKeyFormat(e){if(this.levelkeys){const t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,r,n,s,i=!1){const{elementaryStreams:a}=this,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,n),o.endDTS=Math.max(o.endDTS,s)):a[e]={startPTS:t,endPTS:r,startDTS:n,endDTS:s,partial:i}}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[ap]=null,e[op]=null,e[lp]=null}}class up extends cp{constructor(e,t,r,n,s){super(r),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new ip,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=n;const i=e.enumeratedString("BYTERANGE");i&&this.setByteRange(i,s),s&&(this.fragOffset=s.fragOffset+s.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}class hp{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e)return this.advanced=!0,void(this.updated=!0);const t=this.lastPartSn-e.lastPartSn,r=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!r||!!t,this.advanced=this.endSN>e.endSN||t>0||0===t&&r>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return!!this.fragments.length&&Hf(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const e=this.driftEndTime-this.driftStartTime;if(e>0){return 1e3*(this.driftEnd-this.driftStart)/e}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var e;return null!=(e=this.fragments)&&e.length?this.fragments[this.fragments.length-1].end:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function fp(e){return Uint8Array.from(atob(e),(e=>e.charCodeAt(0)))}function pp(e){const t=e.split(":");let r=null;if("data"===t[0]&&2===t.length){const e=t[1].split(";"),n=e[e.length-1].split(",");if(2===n.length){const t="base64"===n[0],s=n[1];t?(e.splice(-1,1),r=fp(s)):r=function(e){const t=gp(e).subarray(0,16),r=new Uint8Array(16);return r.set(t,16-t.length),r}(s)}}return r}function gp(e){return Uint8Array.from(unescape(encodeURIComponent(e)),(e=>e.charCodeAt(0)))}var mp={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},yp="org.w3.clearkey",vp="com.apple.streamingkeydelivery",bp="com.microsoft.playready",wp="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function Ep(e){switch(e){case vp:return mp.FAIRPLAY;case bp:return mp.PLAYREADY;case wp:return mp.WIDEVINE;case yp:return mp.CLEARKEY}}var Sp="edef8ba979d64acea3c827dcd51d21ed";function Tp(e){switch(e){case mp.FAIRPLAY:return vp;case mp.PLAYREADY:return bp;case mp.WIDEVINE:return wp;case mp.CLEARKEY:return yp}}function Cp(e){const{drmSystems:t,widevineLicenseUrl:r}=e,n=t?[mp.FAIRPLAY,mp.WIDEVINE,mp.PLAYREADY,mp.CLEARKEY].filter((e=>!!t[e])):[];return!n[mp.WIDEVINE]&&r&&n.push(mp.WIDEVINE),n}const kp="undefined"!=typeof self&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function Ap(e,t,r){return Uint8Array.prototype.slice?e.slice(t,r):new Uint8Array(Array.prototype.slice.call(e,t,r))}const Ip=(e,t)=>t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128,_p=(e,t)=>t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128,Rp=(e,t)=>{const r=t;let n=0;for(;Ip(e,t);){n+=10;n+=Lp(e,t+6),_p(e,t+10)&&(n+=10),t+=n}if(n>0)return e.subarray(r,r+n)},Lp=(e,t)=>{let r=0;return r=(127&e[t])<<21,r|=(127&e[t+1])<<14,r|=(127&e[t+2])<<7,r|=127&e[t+3],r},Dp=(e,t)=>Ip(e,t)&&Lp(e,t+6)+10<=e.length-t,xp=e=>e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info,Op=e=>{const t=String.fromCharCode(e[0],e[1],e[2],e[3]),r=Lp(e,4);return{type:t,size:r,data:e.subarray(10,10+r)}},Pp=e=>{let t=0;const r=[];for(;Ip(e,t);){const n=Lp(e,t+6);t+=10;const s=t+n;for(;t+8<s;){const n=Op(e.subarray(t)),s=Mp(n);s&&r.push(s),t+=n.size+10}_p(e,t)&&(t+=10)}return r},Mp=e=>"PRIV"===e.type?Fp(e):"W"===e.type[0]?Np(e):Up(e),Fp=e=>{if(e.size<2)return;const t=jp(e.data,!0),r=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:r.buffer}},Up=e=>{if(e.size<2)return;if("TXXX"===e.type){let t=1;const r=jp(e.data.subarray(t),!0);t+=r.length+1;const n=jp(e.data.subarray(t));return{key:e.type,info:r,data:n}}const t=jp(e.data.subarray(1));return{key:e.type,data:t}},Np=e=>{if("WXXX"===e.type){if(e.size<2)return;let t=1;const r=jp(e.data.subarray(t),!0);t+=r.length+1;const n=jp(e.data.subarray(t));return{key:e.type,info:r,data:n}}const t=jp(e.data);return{key:e.type,data:t}},Bp=e=>{if(8===e.data.byteLength){const t=new Uint8Array(e.data),r=1&t[3];let n=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return n/=45,r&&(n+=47721858.84),Math.round(n)}},jp=(e,t=!1)=>{const r=qp();if(r){const n=r.decode(e);if(t){const e=n.indexOf("\0");return-1!==e?n.substring(0,e):n}return n.replace(/\0/g,"")}const n=e.length;let s,i,a,o="",l=0;for(;l<n;){if(s=e[l++],0===s&&t)return o;if(0!==s&&3!==s)switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(s);break;case 12:case 13:i=e[l++],o+=String.fromCharCode((31&s)<<6|63&i);break;case 14:i=e[l++],a=e[l++],o+=String.fromCharCode((15&s)<<12|(63&i)<<6|(63&a)<<0)}}return o};let $p;function qp(){return $p||void 0===self.TextDecoder||($p=new self.TextDecoder("utf-8")),$p}const Kp=function(e){let t="";for(let r=0;r<e.length;r++){let n=e[r].toString(16);n.length<2&&(n="0"+n),t+=n}return t},Gp=Math.pow(2,32)-1,Hp=[].push,Vp={video:1,audio:2,id3:3,text:4};function zp(e){return String.fromCharCode.apply(null,e)}function Wp(e,t){const r=e[t]<<8|e[t+1];return r<0?65536+r:r}function Yp(e,t){const r=Qp(e,t);return r<0?4294967296+r:r}function Qp(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function Xp(e,t,r){e[t]=r>>24,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r}function Jp(e,t){const r=[];if(!t.length)return r;const n=e.byteLength;for(let s=0;s<n;){const i=Yp(e,s),a=i>1?s+i:n;if(zp(e.subarray(s+4,s+8))===t[0])if(1===t.length)r.push(e.subarray(s+8,a));else{const n=Jp(e.subarray(s+8,a),t.slice(1));n.length&&Hp.apply(r,n)}s=a}return r}function Zp(e){const t=[],r=e[0];let n=8;const s=Yp(e,n);n+=4;n+=0===r?8:16,n+=2;let i=e.length+0;const a=Wp(e,n);n+=2;for(let r=0;r<a;r++){let r=n;const a=Yp(e,r);r+=4;const o=2147483647&a;if(1===(2147483648&a)>>>31)return Zf.warn("SIDX has hierarchical references (not supported)"),null;const l=Yp(e,r);r+=4,t.push({referenceSize:o,subsegmentDuration:l,info:{duration:l/s,start:i,end:i+o-1}}),i+=o,r+=4,n=r}return{earliestPresentationTime:0,timescale:s,version:r,referencesCount:a,references:t}}function eg(e){const t=[],r=Jp(e,["moov","trak"]);for(let e=0;e<r.length;e++){const n=r[e],s=Jp(n,["tkhd"])[0];if(s){let e=s[0],r=0===e?12:20;const i=Yp(s,r),a=Jp(n,["mdia","mdhd"])[0];if(a){e=a[0],r=0===e?12:20;const s=Yp(a,r),o=Jp(n,["mdia","hdlr"])[0];if(o){const e=zp(o.subarray(8,12)),r={soun:ap,vide:op}[e];if(r){const e=Jp(n,["mdia","minf","stbl","stsd"])[0];let a;e&&(a=zp(e.subarray(12,16))),t[i]={timescale:s,type:r},t[r]={timescale:s,id:i,codec:a}}}}}}return Jp(e,["moov","mvex","trex"]).forEach((e=>{const r=Yp(e,4),n=t[r];n&&(n.default={duration:Yp(e,12),flags:Yp(e,20)})})),t}function tg(e){const t=Jp(e,["schm"])[0];if(t){const r=zp(t.subarray(4,8));if("cbcs"===r||"cenc"===r)return Jp(e,["schi","tenc"])[0]}return Zf.error("[eme] missing 'schm' box"),null}function rg(e){const t=Yp(e,0);let r=8;1&t&&(r+=4),4&t&&(r+=4);let n=0;const s=Yp(e,4);for(let i=0;i<s;i++){if(256&t){n+=Yp(e,r),r+=4}512&t&&(r+=4),1024&t&&(r+=4),2048&t&&(r+=4)}return n}function ng(e,t){const r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}function sg(e,t){const r=[],n=t.samples,s=t.timescale,i=t.id;let a=!1;return Jp(n,["moof"]).map((o=>{const l=o.byteOffset-8;Jp(o,["traf"]).map((o=>{const c=Jp(o,["tfdt"]).map((e=>{const t=e[0];let r=Yp(e,4);return 1===t&&(r*=Math.pow(2,32),r+=Yp(e,8)),r/s}))[0];return void 0!==c&&(e=c),Jp(o,["tfhd"]).map((c=>{const d=Yp(c,4),u=16777215&Yp(c,0);let h=0;const f=0!=(16&u);let p=0;const g=0!=(32&u);let m=8;d===i&&(0!=(1&u)&&(m+=8),0!=(2&u)&&(m+=4),0!=(8&u)&&(h=Yp(c,m),m+=4),f&&(p=Yp(c,m),m+=4),g&&(m+=4),"video"===t.type&&(a=function(e){if(!e)return!1;const t=e.indexOf("."),r=t<0?e:e.substring(0,t);return"hvc1"===r||"hev1"===r||"dvh1"===r||"dvhe"===r}(t.codec)),Jp(o,["trun"]).map((i=>{const o=i[0],c=16777215&Yp(i,0),d=0!=(1&c);let u=0;const f=0!=(4&c),g=0!=(256&c);let m=0;const y=0!=(512&c);let v=0;const b=0!=(1024&c),w=0!=(2048&c);let E=0;const S=Yp(i,4);let T=8;d&&(u=Yp(i,T),T+=4),f&&(T+=4);let C=u+l;for(let l=0;l<S;l++){if(g?(m=Yp(i,T),T+=4):m=h,y?(v=Yp(i,T),T+=4):v=p,b&&(T+=4),w&&(E=0===o?Yp(i,T):Qp(i,T),T+=4),t.type===op){let t=0;for(;t<v;){const i=Yp(n,C);if(C+=4,ig(a,n[C])){ag(n.subarray(C,C+i),a?2:1,e+E/s,r)}C+=i,t+=i+4}}e+=m/s}})))}))}))})),r}function ig(e,t){if(e){const e=t>>1&63;return 39===e||40===e}return 6===(31&t)}function ag(e,t,r,n){const s=og(e);let i=0;i+=t;let a=0,o=0,l=!1,c=0;for(;i<s.length;){a=0;do{if(i>=s.length)break;c=s[i++],a+=c}while(255===c);o=0;do{if(i>=s.length)break;c=s[i++],o+=c}while(255===c);const e=s.length-i;if(!l&&4===a&&i<s.length){l=!0;if(181===s[i++]){const e=Wp(s,i);if(i+=2,49===e){const e=Yp(s,i);if(i+=4,1195456820===e){const e=s[i++];if(3===e){const t=s[i++],o=31&t,l=64&t,c=l?2+3*o:0,d=new Uint8Array(c);if(l){d[0]=t;for(let e=1;e<c;e++)d[e]=s[i++]}n.push({type:e,payloadType:a,pts:r,bytes:d})}}}}}else if(5===a&&o<e){if(l=!0,o>16){const e=[];for(let t=0;t<16;t++){const r=s[i++].toString(16);e.push(1==r.length?"0"+r:r),3!==t&&5!==t&&7!==t&&9!==t||e.push("-")}const t=o-16,l=new Uint8Array(t);for(let e=0;e<t;e++)l[e]=s[i++];n.push({payloadType:a,pts:r,uuid:e.join(""),userData:jp(l),userDataBytes:l})}}else if(o<e)i+=o;else if(o>e)break}}function og(e){const t=e.byteLength,r=[];let n=1;for(;n<t-2;)0===e[n]&&0===e[n+1]&&3===e[n+2]?(r.push(n+2),n+=2):n++;if(0===r.length)return e;const s=t-r.length,i=new Uint8Array(s);let a=0;for(n=0;n<s;a++,n++)a===r[0]&&(a++,r.shift()),i[n]=e[a];return i}function lg(e,t,r){if(16!==e.byteLength)throw new RangeError("Invalid system id");let n,s,i;if(t){n=1,s=new Uint8Array(16*t.length);for(let e=0;e<t.length;e++){const r=t[e];if(16!==r.byteLength)throw new RangeError("Invalid key");s.set(r,16*e)}}else n=0,s=new Uint8Array;n>0?(i=new Uint8Array(4),t.length>0&&new DataView(i.buffer).setUint32(0,t.length,!1)):i=new Uint8Array;const a=new Uint8Array(4);return r&&r.byteLength>0&&new DataView(a.buffer).setUint32(0,r.byteLength,!1),function(e,...t){const r=t.length;let n=8,s=r;for(;s--;)n+=t[s].byteLength;const i=new Uint8Array(n);for(i[0]=n>>24&255,i[1]=n>>16&255,i[2]=n>>8&255,i[3]=255&n,i.set(e,4),s=0,n=8;s<r;s++)i.set(t[s],n),n+=t[s].byteLength;return i}([112,115,115,104],new Uint8Array([n,0,0,0]),e,i,s,a,r||new Uint8Array)}let cg={};class dg{static clearKeyUriToKeyIdMap(){cg={}}constructor(e,t,r,n=[1],s=null){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=r,this.keyFormatVersions=n,this.iv=s,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&"AES-128"!==e}isSupported(){if(this.method){if("AES-128"===this.method||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case vp:case wp:case bp:case yp:return-1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if("AES-128"===this.method&&this.uri&&!this.iv){"number"!=typeof e&&("AES-128"!==this.method||this.iv||Zf.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const t=function(e){const t=new Uint8Array(16);for(let r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t}(e);return new dg(this.method,this.uri,"identity",this.keyFormatVersions,t)}const t=pp(this.uri);if(t)switch(this.keyFormat){case wp:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case bp:{const e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=lg(e,null,t);const r=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),n=String.fromCharCode.apply(null,Array.from(r)),s=n.substring(n.indexOf("<"),n.length),i=(new DOMParser).parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(i){const e=i.childNodes[0]?i.childNodes[0].nodeValue:i.getAttribute("VALUE");if(e){const t=fp(e).subarray(0,16);!function(e){const t=function(e,t,r){const n=e[t];e[t]=e[r],e[r]=n};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}(t),this.keyId=t}}break}default:{let e=t.subarray(0,16);if(16!==e.length){const t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e;break}}if(!this.keyId||16!==this.keyId.byteLength){let e=cg[this.uri];if(!e){const t=Object.keys(cg).length%Number.MAX_SAFE_INTEGER;e=new Uint8Array(16);new DataView(e.buffer,12,4).setUint32(0,t),cg[this.uri]=e}this.keyId=e}return this}}const ug=/\{\$([a-zA-Z0-9-_]+)\}/g;function hg(e){return ug.test(e)}function fg(e,t,r){if(null!==e.variableList||e.hasVariableRefs)for(let n=r.length;n--;){const s=r[n],i=t[s];i&&(t[s]=pg(e,i))}}function pg(e,t){if(null!==e.variableList||e.hasVariableRefs){const r=e.variableList;return t.replace(ug,(t=>{const n=t.substring(2,t.length-1),s=null==r?void 0:r[n];return void 0===s?(e.playlistParsingError||(e.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${n}"`)),t):s}))}return t}function gg(e,t,r){let n,s,i=e.variableList;if(i||(e.variableList=i={}),"QUERYPARAM"in t){n=t.QUERYPARAM;try{const e=new self.URL(r).searchParams;if(!e.has(n))throw new Error(`"${n}" does not match any query parameter in URI: "${r}"`);s=e.get(n)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`))}}else n=t.NAME,s=t.VALUE;n in i?e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${n}"`)):i[n]=s||""}function mg(e,t,r){const n=t.IMPORT;if(r&&n in r){let t=e.variableList;t||(e.variableList=t={}),t[n]=r[n]}else e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${n}"`))}function yg(){if("undefined"!=typeof self)return self.MediaSource||self.WebKitMediaSource}const vg={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,av01:!0,drac:!0,dva1:!0,dvav:!0,dvh1:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0},text:{stpp:!0,wvtt:!0}},bg=yg();function wg(e,t){var r;return null!=(r=null==bg?void 0:bg.isTypeSupported(`${t||"video"}/mp4;codecs="${e}"`))&&r}const Eg=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,Sg=/#EXT-X-MEDIA:(.*)/g,Tg=/^#EXT(?:INF|-X-TARGETDURATION):/m,Cg=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),kg=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class Ag{static findGroup(e,t){for(let r=0;r<e.length;r++){const n=e[r];if(n.id===t)return n}}static convertAVC1ToAVCOTI(e){const t=e.split(".");if(t.length>2){let e=t.shift()+".";return e+=parseInt(t.shift()).toString(16),e+=("000"+parseInt(t.shift()).toString(16)).slice(-4),e}return e}static resolve(e,t){return jf.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Tg.test(e)}static parseMasterPlaylist(e,t){const r={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:hg(e)},n=[];let s;for(Eg.lastIndex=0;null!=(s=Eg.exec(e));)if(s[1]){var i;const e=new rp(s[1]);fg(r,e,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const a=pg(r,s[2]),o={attrs:e,bitrate:e.decimalInteger("AVERAGE-BANDWIDTH")||e.decimalInteger("BANDWIDTH"),name:e.NAME,url:Ag.resolve(a,t)},l=e.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),Rg((e.CODECS||"").split(/[ ,]+/).filter((e=>e)),o),o.videoCodec&&-1!==o.videoCodec.indexOf("avc1")&&(o.videoCodec=Ag.convertAVC1ToAVCOTI(o.videoCodec)),null!=(i=o.unknownCodecs)&&i.length||n.push(o),r.levels.push(o)}else if(s[3]){const e=s[3],n=s[4];switch(e){case"SESSION-DATA":{const e=new rp(n);fg(r,e,["DATA-ID","LANGUAGE","VALUE","URI"]);const t=e["DATA-ID"];t&&(null===r.sessionData&&(r.sessionData={}),r.sessionData[t]=e);break}case"SESSION-KEY":{const e=Ig(n,t,r);e.encrypted&&e.isSupported()?(null===r.sessionKeys&&(r.sessionKeys=[]),r.sessionKeys.push(e)):Zf.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${n}"`);break}case"DEFINE":{const e=new rp(n);fg(r,e,["NAME","VALUE","QUERYPARAM"]),gg(r,e,t)}break;case"CONTENT-STEERING":{const e=new rp(n);fg(r,e,["SERVER-URI","PATHWAY-ID"]),r.contentSteering={uri:Ag.resolve(e["SERVER-URI"],t),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":r.startTimeOffset=_g(n)}}const a=n.length>0&&n.length<r.levels.length;return r.levels=a?n:r.levels,0===r.levels.length&&(r.playlistParsingError=new Error("no levels found in manifest")),r}static parseMasterPlaylistMedia(e,t,r){let n;const s={},i=r.levels,a={AUDIO:i.map((e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec}))),SUBTITLES:i.map((e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec}))),"CLOSED-CAPTIONS":[]};let o=0;for(Sg.lastIndex=0;null!==(n=Sg.exec(e));){const e=new rp(n[1]),i=e.TYPE;if(i){const n=a[i],l=s[i]||[];s[i]=l,fg(r,e,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const c={attrs:e,bitrate:0,id:o++,groupId:e["GROUP-ID"]||"",instreamId:e["INSTREAM-ID"],name:e.NAME||e.LANGUAGE||"",type:i,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:e.LANGUAGE,url:e.URI?Ag.resolve(e.URI,t):""};if(null!=n&&n.length){const e=Ag.findGroup(n,c.groupId)||n[0];Lg(c,e,"audioCodec"),Lg(c,e,"textCodec")}l.push(c)}}return s}static parseLevelPlaylist(e,t,r,n,s,i){const a=new hp(t),o=a.fragments;let l,c,d,u=null,h=0,f=0,p=0,g=0,m=null,y=new dp(n,t),v=-1,b=!1;for(Cg.lastIndex=0,a.m3u8=e,a.hasVariableRefs=hg(e);null!==(l=Cg.exec(e));){b&&(b=!1,y=new dp(n,t),y.start=p,y.sn=h,y.cc=g,y.level=r,u&&(y.initSegment=u,y.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null));const e=l[1];if(e){y.duration=parseFloat(e);const t=(" "+l[2]).slice(1);y.title=t||null,y.tagList.push(t?["INF",e,t]:["INF",e])}else if(l[3]){if(Hf(y.duration)){y.start=p,d&&Og(y,d,a),y.sn=h,y.level=r,y.cc=g,y.urlId=s,o.push(y);const e=(" "+l[3]).slice(1);y.relurl=pg(a,e),Dg(y,m),m=y,p+=y.duration,h++,f=0,b=!0}}else if(l[4]){const e=(" "+l[4]).slice(1);m?y.setByteRange(e,m):y.setByteRange(e)}else if(l[5])y.rawProgramDateTime=(" "+l[5]).slice(1),y.tagList.push(["PROGRAM-DATE-TIME",y.rawProgramDateTime]),-1===v&&(v=o.length);else{if(l=l[0].match(kg),!l){Zf.warn("No matches on slow regex match for level playlist!");continue}for(c=1;c<l.length&&void 0===l[c];c++);const e=(" "+l[c]).slice(1),s=(" "+l[c+1]).slice(1),p=l[c+2]?(" "+l[c+2]).slice(1):"";switch(e){case"PLAYLIST-TYPE":a.type=s.toUpperCase();break;case"MEDIA-SEQUENCE":h=a.startSN=parseInt(s);break;case"SKIP":{const e=new rp(s);fg(a,e,["RECENTLY-REMOVED-DATERANGES"]);const t=e.decimalInteger("SKIPPED-SEGMENTS");if(Hf(t)){a.skippedSegments=t;for(let e=t;e--;)o.unshift(null);h+=t}const r=e.enumeratedString("RECENTLY-REMOVED-DATERANGES");r&&(a.recentlyRemovedDateranges=r.split("\t"));break}case"TARGETDURATION":a.targetduration=Math.max(parseInt(s),1);break;case"VERSION":a.version=parseInt(s);break;case"EXTM3U":break;case"ENDLIST":a.live=!1;break;case"#":(s||p)&&y.tagList.push(p?[s,p]:[s]);break;case"DISCONTINUITY":g++,y.tagList.push(["DIS"]);break;case"GAP":y.gap=!0,y.tagList.push([e]);break;case"BITRATE":y.tagList.push([e,s]);break;case"DATERANGE":{const e=new rp(s);fg(a,e,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),fg(a,e,e.clientAttrs);const t=new sp(e,a.dateRanges[e.ID]);t.isValid||a.skippedSegments?a.dateRanges[t.id]=t:Zf.warn(`Ignoring invalid DATERANGE tag: "${s}"`),y.tagList.push(["EXT-X-DATERANGE",s]);break}case"DEFINE":{const e=new rp(s);fg(a,e,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in e?mg(a,e,i):gg(a,e,t)}break;case"DISCONTINUITY-SEQUENCE":g=parseInt(s);break;case"KEY":{const e=Ig(s,t,a);if(e.isSupported()){if("NONE"===e.method){d=void 0;break}d||(d={}),d[e.keyFormat]&&(d=Gf({},d)),d[e.keyFormat]=e}else Zf.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${s}"`);break}case"START":a.startTimeOffset=_g(s);break;case"MAP":{const e=new rp(s);if(fg(a,e,["BYTERANGE","URI"]),y.duration){const s=new dp(n,t);xg(s,e,r,d),u=s,y.initSegment=u,u.rawProgramDateTime&&!y.rawProgramDateTime&&(y.rawProgramDateTime=u.rawProgramDateTime)}else xg(y,e,r,d),u=y,b=!0;break}case"SERVER-CONTROL":{const e=new rp(s);a.canBlockReload=e.bool("CAN-BLOCK-RELOAD"),a.canSkipUntil=e.optionalFloat("CAN-SKIP-UNTIL",0),a.canSkipDateRanges=a.canSkipUntil>0&&e.bool("CAN-SKIP-DATERANGES"),a.partHoldBack=e.optionalFloat("PART-HOLD-BACK",0),a.holdBack=e.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const e=new rp(s);a.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=a.partList;e||(e=a.partList=[]);const r=f>0?e[e.length-1]:void 0,n=f++,i=new rp(s);fg(a,i,["BYTERANGE","URI"]);const o=new up(i,y,t,n,r);e.push(o),y.duration+=o.duration;break}case"PRELOAD-HINT":{const e=new rp(s);fg(a,e,["URI"]),a.preloadHint=e;break}case"RENDITION-REPORT":{const e=new rp(s);fg(a,e,["URI"]),a.renditionReports=a.renditionReports||[],a.renditionReports.push(e);break}default:Zf.warn(`line parsed but not handled: ${l}`)}}}m&&!m.relurl?(o.pop(),p-=m.duration,a.partList&&(a.fragmentHint=m)):a.partList&&(Dg(y,m),y.cc=g,a.fragmentHint=y,d&&Og(y,d,a));const w=o.length,E=o[0],S=o[w-1];if(p+=a.skippedSegments*a.targetduration,p>0&&w&&S){a.averagetargetduration=p/w;const e=S.sn;a.endSN="initSegment"!==e?e:0,a.live||(S.endList=!0),E&&(a.startCC=E.cc)}else a.endSN=0,a.startCC=0;return a.fragmentHint&&(p+=a.fragmentHint.duration),a.totalduration=p,a.endCC=g,v>0&&function(e,t){let r=e[t];for(let n=t;n--;){const t=e[n];if(!t)return;t.programDateTime=r.programDateTime-1e3*t.duration,r=t}}(o,v),a}}function Ig(e,t,r){var n,s;const i=new rp(e);fg(r,i,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=null!=(n=i.METHOD)?n:"",o=i.URI,l=i.hexadecimalInteger("IV"),c=i.KEYFORMATVERSIONS,d=null!=(s=i.KEYFORMAT)?s:"identity";o&&i.IV&&!l&&Zf.error(`Invalid IV: ${i.IV}`);const u=o?Ag.resolve(o,t):"",h=(c||"1").split("/").map(Number).filter(Number.isFinite);return new dg(a,u,d,h,l)}function _g(e){const t=new rp(e).decimalFloatingPoint("TIME-OFFSET");return Hf(t)?t:null}function Rg(e,t){["video","audio","text"].forEach((r=>{const n=e.filter((e=>function(e,t){const r=vg[t];return!!r&&!0===r[e.slice(0,4)]}(e,r)));if(n.length){const s=n.filter((e=>0===e.lastIndexOf("avc1",0)||0===e.lastIndexOf("mp4a",0)));t[`${r}Codec`]=s.length>0?s[0]:n[0],e=e.filter((e=>-1===n.indexOf(e)))}})),t.unknownCodecs=e}function Lg(e,t,r){const n=t[r];n&&(e[r]=n)}function Dg(e,t){e.rawProgramDateTime?e.programDateTime=Date.parse(e.rawProgramDateTime):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime),Hf(e.programDateTime)||(e.programDateTime=null,e.rawProgramDateTime=null)}function xg(e,t,r,n){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=r,e.sn="initSegment",n&&(e.levelkeys=n),e.initSegment=null}function Og(e,t,r){e.levelkeys=t;const{encryptedFragments:n}=r;n.length&&n[n.length-1].levelkeys===t||!Object.keys(t).some((e=>t[e].isCommonEncryption))||n.push(e)}var Pg="manifest",Mg="level",Fg="audioTrack",Ug="subtitleTrack",Ng="main",Bg="audio",jg="subtitle";function $g(e){const{type:t}=e;switch(t){case Fg:return Bg;case Ug:return jg;default:return Ng}}function qg(e,t){let r=e.url;return void 0!==r&&0!==r.indexOf("data:")||(r=t.url),r}class Kg{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Vf.LEVEL_LOADING,this.onLevelLoading,this),e.on(Vf.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(Vf.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:e}=this;e.off(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Vf.LEVEL_LOADING,this.onLevelLoading,this),e.off(Vf.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(Vf.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(e){const t=this.hls.config,r=t.pLoader,n=t.loader,s=new(r||n)(t);return this.loaders[e.type]=s,s}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:r}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Pg,url:r,deliveryDirectives:null})}onLevelLoading(e,t){const{id:r,level:n,url:s,deliveryDirectives:i}=t;this.load({id:r,level:n,responseType:"text",type:Mg,url:s,deliveryDirectives:i})}onAudioTrackLoading(e,t){const{id:r,groupId:n,url:s,deliveryDirectives:i}=t;this.load({id:r,groupId:n,level:null,responseType:"text",type:Fg,url:s,deliveryDirectives:i})}onSubtitleTrackLoading(e,t){const{id:r,groupId:n,url:s,deliveryDirectives:i}=t;this.load({id:r,groupId:n,level:null,responseType:"text",type:Ug,url:s,deliveryDirectives:i})}load(e){var t;const r=this.hls.config;let n,s=this.getInternalLoader(e);if(s){const t=s.context;if(t&&t.url===e.url)return void Zf.trace("[playlist-loader]: playlist request ongoing");Zf.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}if(n=e.type===Pg?r.manifestLoadPolicy.default:Gf({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),null!=(t=e.deliveryDirectives)&&t.part){let t;if(e.type===Mg&&null!==e.level?t=this.hls.levels[e.level].details:e.type===Fg&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===Ug&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){const e=t.partTarget,r=t.targetduration;if(e&&r){const t=1e3*Math.max(3*e,.8*r);n=Gf({},n,{maxTimeToFirstByteMs:Math.min(t,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,n.maxTimeToFirstByteMs)})}}}const i=n.errorRetry||n.timeoutRetry||{},a={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:i.maxNumRetry||0,retryDelay:i.retryDelayMs||0,maxRetryDelay:i.maxRetryDelayMs||0},o={onSuccess:(e,t,r,n)=>{const s=this.getInternalLoader(r);this.resetInternalLoader(r.type);const i=e.data;0===i.indexOf("#EXTM3U")?(t.parsing.start=performance.now(),Ag.isMediaPlaylist(i)?this.handleTrackOrLevelPlaylist(e,t,r,n||null,s):this.handleMasterPlaylist(e,t,r,n)):this.handleManifestParsingError(e,r,new Error("no EXTM3U delimiter"),n||null,t)},onError:(e,t,r,n)=>{this.handleNetworkError(t,r,!1,e,n)},onTimeout:(e,t,r)=>{this.handleNetworkError(t,r,!0,void 0,e)}};s.load(e,a,o)}handleMasterPlaylist(e,t,r,n){const s=this.hls,i=e.data,a=qg(e,r),o=Ag.parseMasterPlaylist(i,a);if(o.playlistParsingError)return void this.handleManifestParsingError(e,r,o.playlistParsingError,n,t);const{contentSteering:l,levels:c,sessionData:d,sessionKeys:u,startTimeOffset:h,variableList:f}=o;this.variableList=f;const{AUDIO:p=[],SUBTITLES:g,"CLOSED-CAPTIONS":m}=Ag.parseMasterPlaylistMedia(i,a,o);if(p.length){p.some((e=>!e.url))||!c[0].audioCodec||c[0].attrs.AUDIO||(Zf.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new rp({}),bitrate:0,url:""}))}s.trigger(Vf.MANIFEST_LOADED,{levels:c,audioTracks:p,subtitles:g,captions:m,contentSteering:l,url:a,stats:t,networkDetails:n,sessionData:d,sessionKeys:u,startTimeOffset:h,variableList:f})}handleTrackOrLevelPlaylist(e,t,r,n,s){const i=this.hls,{id:a,level:o,type:l}=r,c=qg(e,r),d=Hf(a)?a:0,u=Hf(o)?o:d,h=$g(r),f=Ag.parseLevelPlaylist(e.data,c,u,h,d,this.variableList);if(l===Pg){const e={attrs:new rp({}),bitrate:0,details:f,name:"",url:c};i.trigger(Vf.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:c,stats:t,networkDetails:n,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),r.levelDetails=f,this.handlePlaylistLoaded(f,e,t,r,n,s)}handleManifestParsingError(e,t,r,n,s){this.hls.trigger(Vf.ERROR,{type:zf.NETWORK_ERROR,details:Wf.MANIFEST_PARSING_ERROR,fatal:t.type===Pg,url:e.url,err:r,error:r,reason:r.message,response:e,context:t,networkDetails:n,stats:s})}handleNetworkError(e,t,r=!1,n,s){let i=`A network ${r?"timeout":"error"+(n?" (status "+n.code+")":"")} occurred while loading ${e.type}`;e.type===Mg?i+=`: ${e.level} id: ${e.id}`:e.type!==Fg&&e.type!==Ug||(i+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(i);Zf.warn(`[playlist-loader]: ${i}`);let o=Wf.UNKNOWN,l=!1;const c=this.getInternalLoader(e);switch(e.type){case Pg:o=r?Wf.MANIFEST_LOAD_TIMEOUT:Wf.MANIFEST_LOAD_ERROR,l=!0;break;case Mg:o=r?Wf.LEVEL_LOAD_TIMEOUT:Wf.LEVEL_LOAD_ERROR,l=!1;break;case Fg:o=r?Wf.AUDIO_TRACK_LOAD_TIMEOUT:Wf.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case Ug:o=r?Wf.SUBTITLE_TRACK_LOAD_TIMEOUT:Wf.SUBTITLE_LOAD_ERROR,l=!1}c&&this.resetInternalLoader(e.type);const d={type:zf.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:c,context:e,error:a,networkDetails:t,stats:s};if(n){const r=(null==t?void 0:t.url)||e.url;d.response=qf({url:r,data:void 0},n)}this.hls.trigger(Vf.ERROR,d)}handlePlaylistLoaded(e,t,r,n,s,i){const a=this.hls,{type:o,level:l,id:c,groupId:d,deliveryDirectives:u}=n,h=qg(t,n),f=$g(n),p="number"==typeof n.level&&f===Ng?l:void 0;if(!e.fragments.length){const e=new Error("No Segments found in Playlist");return void a.trigger(Vf.ERROR,{type:zf.NETWORK_ERROR,details:Wf.LEVEL_EMPTY_ERROR,fatal:!1,url:h,error:e,reason:e.message,response:t,context:n,level:p,parent:f,networkDetails:s,stats:r})}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const g=e.playlistParsingError;if(g)a.trigger(Vf.ERROR,{type:zf.NETWORK_ERROR,details:Wf.LEVEL_PARSING_ERROR,fatal:!1,url:h,error:g,reason:g.message,response:t,context:n,level:p,parent:f,networkDetails:s,stats:r});else switch(e.live&&i&&(i.getCacheAge&&(e.ageHeader=i.getCacheAge()||0),i.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case Pg:case Mg:a.trigger(Vf.LEVEL_LOADED,{details:e,level:p||0,id:c||0,stats:r,networkDetails:s,deliveryDirectives:u});break;case Fg:a.trigger(Vf.AUDIO_TRACK_LOADED,{details:e,id:c||0,groupId:d||"",stats:r,networkDetails:s,deliveryDirectives:u});break;case Ug:a.trigger(Vf.SUBTITLE_TRACK_LOADED,{details:e,id:c||0,groupId:d||"",stats:r,networkDetails:s,deliveryDirectives:u})}}}function Gg(e,t){let r;try{r=new Event("addtrack")}catch(e){r=document.createEvent("Event"),r.initEvent("addtrack",!1,!1)}r.track=e,t.dispatchEvent(r)}function Hg(e,t){const r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(r){Zf.debug(`[texttrack-utils]: ${r}`);try{const r=new self.TextTrackCue(t.startTime,t.endTime,t.text);r.id=t.id,e.addCue(r)}catch(e){Zf.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}"disabled"===r&&(e.mode=r)}function Vg(e){const t=e.mode;if("disabled"===t&&(e.mode="hidden"),e.cues)for(let t=e.cues.length;t--;)e.removeCue(e.cues[t]);"disabled"===t&&(e.mode=t)}function zg(e,t,r,n){const s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues&&e.cues.length>0){const s=function(e,t,r){const n=[],s=function(e,t){if(t<e[0].startTime)return 0;const r=e.length-1;if(t>e[r].endTime)return-1;let n=0,s=r;for(;n<=s;){const i=Math.floor((s+n)/2);if(t<e[i].startTime)s=i-1;else{if(!(t>e[i].startTime&&n<r))return i;n=i+1}}return e[n].startTime-t<t-e[s].startTime?n:s}(e,t);if(s>-1)for(let i=s,a=e.length;i<a;i++){const s=e[i];if(s.startTime>=t&&s.endTime<=r)n.push(s);else if(s.startTime>r)return n}return n}(e.cues,t,r);for(let t=0;t<s.length;t++)n&&!n(s[t])||e.removeCue(s[t])}"disabled"===s&&(e.mode=s)}var Wg="org.id3",Yg="com.apple.quicktime.HLS",Qg="https://aomedia.org/emsg/ID3";function Xg(){if("undefined"!=typeof self)return self.WebKitDataCue||self.VTTCue||self.TextTrackCue}const Jg=(()=>{const e=Xg();try{new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function Zg(e,t){return e.getTime()/1e3-t}class em{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:e}=this;e.on(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Vf.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(Vf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Vf.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Vf.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(Vf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Vf.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&(Vg(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const r=e[t];if("metadata"===r.kind&&"id3"===r.label)return Gg(r,this.media),r}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:r,enableID3MetadataCues:n}}}=this;if(!r&&!n)return;const{samples:s}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const i=Xg();for(let e=0;e<s.length;e++){const t=s[e].type;if(t===Qg&&!r||!n)continue;const a=Pp(s[e].data);if(a){const r=s[e].pts;let n=r+s[e].duration;n>Jg&&(n=Jg);n-r<=0&&(n=r+.25);for(let e=0;e<a.length;e++){const s=a[e];if(!xp(s)){this.updateId3CueEnds(r,t);const e=new i(r,n,"");e.value=s,t&&(e.type=t),this.id3Track.addCue(e)}}}}}updateId3CueEnds(e,t){var r;const n=null==(r=this.id3Track)?void 0:r.cues;if(n)for(let r=n.length;r--;){const s=n[r];s.type===t&&s.startTime<e&&s.endTime===Jg&&(s.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:r,type:n}){const{id3Track:s,hls:i}=this;if(!i)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=i;if(s&&(a||o)){let e;e="audio"===n?e=>e.type===Wg&&o:"video"===n?e=>e.type===Qg&&a:e=>e.type===Wg&&o||e.type===Qg&&a,zg(s,t,r,e)}}onLevelUpdated(e,{details:t}){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:r,id3Track:n}=this,{dateRanges:s}=t,i=Object.keys(s);if(n){const e=Object.keys(r).filter((e=>!i.includes(e)));for(let t=e.length;t--;){const s=e[t];Object.keys(r[s].cues).forEach((e=>{n.removeCue(r[s].cues[e])})),delete r[s]}}const a=t.fragments[t.fragments.length-1];if(0===i.length||!Hf(null==a?void 0:a.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=a.programDateTime/1e3-a.start,l=Xg();for(let e=0;e<i.length;e++){const t=i[e],n=s[t],a=r[t],u=(null==a?void 0:a.cues)||{};let h=(null==a?void 0:a.durationKnown)||!1;const f=Zg(n.startDate,o);let p=Jg;const g=n.endDate;if(g)p=Zg(g,o),h=!0;else if(n.endOnNext&&!h){const e=i.reduce(((e,t)=>{const r=s[t];return r.class===n.class&&r.id!==t&&r.startDate>n.startDate&&e.push(r),e}),[]).sort(((e,t)=>e.startDate.getTime()-t.startDate.getTime()))[0];e&&(p=Zg(e.startDate,o),h=!0)}const m=Object.keys(n.attr);for(let e=0;e<m.length;e++){const r=m[e];if("ID"===(d=r)||"CLASS"===d||"START-DATE"===d||"DURATION"===d||"END-DATE"===d||"END-ON-NEXT"===d)continue;let s=u[r];if(s)h&&!a.durationKnown&&(s.endTime=p);else{let e=n.attr[r];s=new l(f,p,""),np(r)&&(c=e,e=Uint8Array.from(c.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer),s.value={key:r,data:e},s.type=Yg,s.id=t,this.id3Track.addCue(s),u[r]=s}}r[t]={cues:u,dateRange:n,durationKnown:h}}var c,d}}class tm{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=()=>this.timeupdate(),this.hls=e,this.config=e.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:e,levelDetails:t}=this;return void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const{levelDetails:e}=this;if(null===e)return null;const{holdBack:t,partHoldBack:r,targetduration:n}=e,{liveSyncDuration:s,liveSyncDurationCount:i,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&r||t;(o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==s?s:i*n);const c=n;return l+Math.min(1*this.stallCount,c)}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency,r=this.levelDetails;if(null===e||null===t||null===r)return null;const n=r.edge,s=e-t-this.edgeStalled,i=n-r.totalduration,a=n-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(i,s),a)}get drift(){const{levelDetails:e}=this;return null===e?1:e.drift}get edgeStalled(){const{levelDetails:e}=this;if(null===e)return 0;const t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e,levelDetails:t}=this;if(!e||!t)return 0;const r=e.buffered.length;return(r?e.buffered.end(r-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(Vf.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(Vf.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(Vf.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(Vf.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(Vf.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(Vf.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){this.levelDetails=t,t.advanced&&this.timeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(e,t){var r;t.details===Wf.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(r=this.levelDetails)&&r.live&&Zf.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:e,levelDetails:t}=this;if(!e||!t)return;this.currentTime=e.currentTime;const r=this.computeLatency();if(null===r)return;this._latency=r;const{lowLatencyMode:n,maxLiveSyncPlaybackRate:s}=this.config;if(!n||1===s)return;const i=this.targetLatency;if(null===i)return;const a=r-i,o=a<Math.min(this.maxLatency,i+t.targetduration);if(t.live&&o&&a>.05&&this.forwardBufferLength>1){const t=Math.min(2,Math.max(1,s)),r=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20;e.playbackRate=Math.min(t,Math.max(1,r))}else 1!==e.playbackRate&&0!==e.playbackRate&&(e.playbackRate=1)}estimateLiveEdge(){const{levelDetails:e}=this;return null===e?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}const rm=["NONE","TYPE-0","TYPE-1",null];var nm="",sm="YES",im="v2";class am{constructor(e,t,r){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=r}addDirectives(e){const t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class om{constructor(e){this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.unknownCodecs=void 0,this.audioGroupIds=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.textGroupIds=void 0,this.url=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.unknownCodecs=e.unknownCodecs,this.codecSet=[e.videoCodec,e.audioCodec].filter((e=>e)).join(",").replace(/\.[^.,]+/g,"")}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get attrs(){return this._attrs[this._urlId]}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get uri(){return this.url[this._urlId]||""}get urlId(){return this._urlId}set urlId(e){const t=e%this.url.length;this._urlId!==t&&(this.fragmentError=0,this.loadError=0,this.details=void 0,this._urlId=t)}get audioGroupId(){var e;return null==(e=this.audioGroupIds)?void 0:e[this.urlId]}get textGroupId(){var e;return null==(e=this.textGroupIds)?void 0:e[this.urlId]}addFallback(e){this.url.push(e.url),this._attrs.push(e.attrs)}}function lm(e,t){const r=t.startPTS;if(Hf(r)){let n,s=0;t.sn>e.sn?(s=r-e.start,n=e):(s=e.start-r,n=t),n.duration!==s&&(n.duration=s)}else if(t.sn>e.sn){e.cc===t.cc&&e.minEndPTS?t.start=e.start+(e.minEndPTS-e.start):t.start=e.start+e.duration}else t.start=Math.max(e.start-t.duration,0)}function cm(e,t,r,n,s,i){n-r<=0&&(Zf.warn("Fragment should have a positive duration",t),n=r+t.duration,i=s+t.duration);let a=r,o=n;const l=t.startPTS,c=t.endPTS;if(Hf(l)){const e=Math.abs(l-r);Hf(t.deltaPTS)?t.deltaPTS=Math.max(e,t.deltaPTS):t.deltaPTS=e,a=Math.max(r,l),r=Math.min(r,l),s=Math.min(s,t.startDTS),o=Math.min(n,c),n=Math.max(n,c),i=Math.max(i,t.endDTS)}const d=r-t.start;0!==t.start&&(t.start=r),t.duration=n-t.start,t.startPTS=r,t.maxStartPTS=a,t.startDTS=s,t.endPTS=n,t.minEndPTS=o,t.endDTS=i;const u=t.sn;if(!e||u<e.startSN||u>e.endSN)return 0;let h;const f=u-e.startSN,p=e.fragments;for(p[f]=t,h=f;h>0;h--)lm(p[h],p[h-1]);for(h=f;h<p.length-1;h++)lm(p[h],p[h+1]);return e.fragmentHint&&lm(p[p.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,d}function dm(e,t){let r=null;const n=e.fragments;for(let e=n.length-1;e>=0;e--){const t=n[e].initSegment;if(t){r=t;break}}e.fragmentHint&&delete e.fragmentHint.endPTS;let s,i=0;if(function(e,t,r){const n=t.skippedSegments,s=Math.max(e.startSN,t.startSN)-t.startSN,i=(e.fragmentHint?1:0)+(n?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let e=s;e<=i;e++){const s=l[a+e];let i=o[e];n&&!i&&e<n&&(i=t.fragments[e]=s),s&&i&&r(s,i)}}(e,t,((e,n)=>{e.relurl&&(i=e.cc-n.cc),Hf(e.startPTS)&&Hf(e.endPTS)&&(n.start=n.startPTS=e.startPTS,n.startDTS=e.startDTS,n.maxStartPTS=e.maxStartPTS,n.endPTS=e.endPTS,n.endDTS=e.endDTS,n.minEndPTS=e.minEndPTS,n.duration=e.endPTS-e.startPTS,n.duration&&(s=n),t.PTSKnown=t.alignedSliding=!0),n.elementaryStreams=e.elementaryStreams,n.loader=e.loader,n.stats=e.stats,n.urlId=e.urlId,e.initSegment&&(n.initSegment=e.initSegment,r=e.initSegment)})),r){(t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments).forEach((e=>{var t;e.initSegment&&e.initSegment.relurl!==(null==(t=r)?void 0:t.relurl)||(e.initSegment=r)}))}if(t.skippedSegments)if(t.deltaUpdateFailed=t.fragments.some((e=>!e)),t.deltaUpdateFailed){Zf.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)t.fragments.shift();t.startSN=t.fragments[0].sn,t.startCC=t.fragments[0].cc}else t.canSkipDateRanges&&(t.dateRanges=function(e,t,r){const n=Gf({},e);r&&r.forEach((e=>{delete n[e]}));return Object.keys(t).forEach((e=>{const r=new sp(t[e].attr,n[e]);r.isValid?n[e]=r:Zf.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(t[e].attr)}"`)})),n}(e.dateRanges,t.dateRanges,t.recentlyRemovedDateranges));const a=t.fragments;if(i){Zf.warn("discontinuity sliding from playlist, take drift into account");for(let e=0;e<a.length;e++)a[e].cc+=i}t.skippedSegments&&(t.startCC=t.fragments[0].cc),function(e,t,r){if(e&&t){let n=0;for(let s=0,i=e.length;s<=i;s++){const i=e[s],a=t[s+n];i&&a&&i.index===a.index&&i.fragment.sn===a.fragment.sn?r(i,a):n--}}}(e.partList,t.partList,((e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats})),s?cm(t,s,s.startPTS,s.endPTS,s.startDTS,s.endDTS):um(e,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const o=t.advancedDateTime;if(t.advanced&&o){const e=t.edge;t.driftStart||(t.driftStartTime=o,t.driftStart=e),t.driftEndTime=o,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime}function um(e,t){const r=t.startSN+t.skippedSegments-e.startSN,n=e.fragments;r<0||r>=n.length||hm(t,n[r].start)}function hm(e,t){if(t){const r=e.fragments;for(let n=e.skippedSegments;n<r.length;n++)r[n].start+=t;e.fragmentHint&&(e.fragmentHint.start+=t)}}function fm(e,t,r){var n;return null!=e&&e.details?pm(null==(n=e.details)?void 0:n.partList,t,r):null}function pm(e,t,r){if(e)for(let n=e.length;n--;){const s=e[n];if(s.index===r&&s.fragment.sn===t)return s}return null}function gm(e){switch(e.details){case Wf.FRAG_LOAD_TIMEOUT:case Wf.KEY_LOAD_TIMEOUT:case Wf.LEVEL_LOAD_TIMEOUT:case Wf.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function mm(e,t){const r=gm(t);return e.default[(r?"timeout":"error")+"Retry"]}function ym(e,t){const r="linear"===e.backoff?1:Math.pow(2,t);return Math.min(r*e.retryDelayMs,e.maxRetryDelayMs)}function vm(e){return qf(qf({},e),{errorRetry:null,timeoutRetry:null})}function bm(e,t,r,n){return!!e&&t<e.maxNumRetry&&(function(e){return 0===e&&!1===navigator.onLine||!!e&&(e<400||e>499)}(n)||!!r)}const wm=function(e,t){let r=0,n=e.length-1,s=null,i=null;for(;r<=n;){s=(r+n)/2|0,i=e[s];const a=t(i);if(a>0)r=s+1;else{if(!(a<0))return i;n=s-1}}return null};function Em(e,t,r=0,n=0){let s=null;if(e?s=t[e.sn-t[0].sn+1]||null:0===r&&0===t[0].start&&(s=t[0]),s&&0===Sm(r,n,s))return s;const i=wm(t,Sm.bind(null,r,n));return!i||i===e&&s?s:i}function Sm(e=0,t=0,r){if(r.start<=e&&r.start+r.duration>e)return 0;const n=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-n<=e?1:r.start-n>e&&r.start?-1:0}function Tm(e,t,r){const n=1e3*Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-n>e}var Cm=0,km=2,Am=5,Im=0,_m=1,Rm=2;function Lm(e,t,r){if(performance.now()-e.lastErrorPerfMs>3e5)return!0;const n=e.details;if(t.details===Wf.FRAG_GAP&&n&&t.frag){const e=t.frag.start,r=Em(null,n.fragments,e);if(r&&!r.gap)return!0}if(r&&e.errors.length<r.errors.length){const r=e.errors[e.errors.length-1];if(n&&r.frag&&t.frag&&Math.abs(r.frag.start-t.frag.start)>3*n.targetduration)return!0}return!1}class Dm{constructor(e,t){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=Zf.log.bind(Zf,`${t}:`),this.warn=Zf.warn.bind(Zf,`${t}:`),this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){clearTimeout(this.timer),this.timer=-1}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t){const r=null==t?void 0:t.renditionReports;if(r){let n=-1;for(let s=0;s<r.length;s++){const i=r[s];let a;try{a=new self.URL(i.URI,t.url).href}catch(e){Zf.warn(`Could not construct new URL for Rendition Report: ${e}`),a=i.URI||""}if(a===e){n=s;break}a===e.substring(0,a.length)&&(n=s)}if(-1!==n){const e=r[n],s=parseInt(e["LAST-MSN"])||(null==t?void 0:t.lastPartSn);let i=parseInt(e["LAST-PART"])||(null==t?void 0:t.lastPartIndex);if(this.hls.config.lowLatencyMode){const e=Math.min(t.age-t.partTarget,t.targetduration);i>=0&&e>t.partTarget&&(i+=1)}return new am(s,i>=0?i:void 0,nm)}}}loadPlaylist(e){-1===this.requestScheduled&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}shouldReloadPlaylist(e){return-1===this.timer&&-1===this.requestScheduled&&this.shouldLoadPlaylist(e)}playlistLoaded(e,t,r){const{details:n,stats:s}=t,i=self.performance.now(),a=s.loading.first?Math.max(0,i-s.loading.first):0;if(n.advancedDateTime=Date.now()-a,n.live||null!=r&&r.live){if(n.reloaded(r),r&&this.log(`live playlist ${e} ${n.advanced?"REFRESHED "+n.lastPartSn+"-"+n.lastPartIndex:"MISSED"}`),r&&n.fragments.length>0&&dm(r,n),!this.canLoad||!n.live)return;let a,o,l;if(n.canBlockReload&&n.endSN&&n.advanced){const e=this.hls.config.lowLatencyMode,s=n.lastPartSn,i=n.endSN,c=n.lastPartIndex,d=s===i,u=e?0:c;-1!==c?(o=d?i+1:s,l=d?u:c+1):o=i+1;const h=n.age,f=h+n.ageHeader;let p=Math.min(f-n.partTarget,1.5*n.targetduration);if(p>0){if(r&&p>r.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${r.tuneInGoal} to: ${p} with playlist age: ${n.age}`),p=0;else{const e=Math.floor(p/n.targetduration);if(o+=e,void 0!==l){l+=Math.round(p%n.targetduration/n.partTarget)}this.log(`CDN Tune-in age: ${n.ageHeader}s last advanced ${h.toFixed(2)}s goal: ${p} skip sn ${e} to part ${l}`)}n.tuneInGoal=p}if(a=this.getDeliveryDirectives(n,t.deliveryDirectives,o,l),e||!d)return void this.loadPlaylist(a)}else n.canBlockReload&&(a=this.getDeliveryDirectives(n,t.deliveryDirectives,o,l));const c=this.hls.mainForwardBufferInfo,d=c?c.end-c.len:0,u=function(e,t=1/0){let r=1e3*e.targetduration;if(e.updated){const n=e.fragments,s=4;if(n.length&&r*s>t){const e=1e3*n[n.length-1].duration;e<r&&(r=e)}}else r/=2;return Math.round(r)}(n,1e3*(n.edge-d));n.updated&&i>this.requestScheduled+u&&(this.requestScheduled=s.loading.start),void 0!==o&&n.canBlockReload?this.requestScheduled=s.loading.first+u-(1e3*n.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+u<i?this.requestScheduled=i:this.requestScheduled-i<=0&&(this.requestScheduled+=u);let h=this.requestScheduled-i;h=Math.max(0,h),this.log(`reload live playlist ${e} in ${Math.round(h)} ms`),this.timer=self.setTimeout((()=>this.loadPlaylist(a)),h)}else this.clearTimer()}getDeliveryDirectives(e,t,r,n){let s=function(e,t){const{canSkipUntil:r,canSkipDateRanges:n,endSN:s}=e;return r&&(void 0!==t?t-s:0)<r?n?im:sm:nm}(e,r);return null!=t&&t.skip&&e.deltaUpdateFailed&&(r=t.msn,n=t.part,s=nm),new am(r,n,s)}checkRetry(e){const t=e.details,r=gm(e),n=e.errorAction,{action:s,retryCount:i=0,retryConfig:a}=n||{},o=!!n&&!!a&&(s===Am||!n.resolved&&s===km);if(o){var l;if(this.requestScheduled=-1,i>=a.maxNumRetry)return!1;if(r&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${i+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const e=ym(a,i);this.timer=self.setTimeout((()=>this.loadPlaylist()),e),this.warn(`Retrying playlist loading ${i+1}/${a.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,n.resolved=!0}return o}}let xm;class Om extends Dm{constructor(e,t){super(e,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Vf.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Vf.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Vf.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Vf.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(Vf.FRAG_LOADED,this.onFragLoaded,this),e.on(Vf.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Vf.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Vf.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Vf.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Vf.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(Vf.FRAG_LOADED,this.onFragLoaded,this),e.off(Vf.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}startLoad(){this._levels.forEach((e=>{e.loadError=0,e.fragmentError=0})),super.startLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[]}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const r=[],n={};let s;t.levels.forEach((e=>{var t;const i=e.attrs;-1!==(null==(t=e.audioCodec)?void 0:t.indexOf("mp4a.40.34"))&&(xm||(xm=/chrome|firefox/i.test(navigator.userAgent)),xm&&(e.audioCodec=void 0));const{AUDIO:a,CODECS:o,"FRAME-RATE":l,"PATHWAY-ID":c,RESOLUTION:d,SUBTITLES:u}=i,h=`${`${c||"."}-`}${e.bitrate}-${d}-${l}-${o}`;s=n[h],s?s.addFallback(e):(s=new om(e),n[h]=s,r.push(s)),Pm(s,"audio",a),Pm(s,"text",u)})),this.filterAndSortMediaOptions(r,t)}filterAndSortMediaOptions(e,t){let r=[],n=[],s=!1,i=!1,a=!1,o=e.filter((({audioCodec:e,videoCodec:t,width:r,height:n,unknownCodecs:o})=>(s||(s=!(!r||!n)),i||(i=!!t),a||(a=!!e),!(null!=o&&o.length)&&(!e||wg(e,"audio"))&&(!t||wg(t,"video")))));if((s||i)&&a&&(o=o.filter((({videoCodec:e,width:t,height:r})=>!!e||!(!t||!r)))),0===o.length)return void Promise.resolve().then((()=>{if(this.hls){const e=new Error("no level with compatible codecs found in manifest");this.hls.trigger(Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:e,reason:e.message})}}));t.audioTracks&&(r=t.audioTracks.filter((e=>!e.audioCodec||wg(e.audioCodec,"audio"))),Mm(r)),t.subtitles&&(n=t.subtitles,Mm(n));const l=o.slice(0);o.sort(((e,t)=>e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"]?(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1:e.bitrate!==t.bitrate?e.bitrate-t.bitrate:e.attrs["FRAME-RATE"]!==t.attrs["FRAME-RATE"]?e.attrs.decimalFloatingPoint("FRAME-RATE")-t.attrs.decimalFloatingPoint("FRAME-RATE"):e.attrs.SCORE!==t.attrs.SCORE?e.attrs.decimalFloatingPoint("SCORE")-t.attrs.decimalFloatingPoint("SCORE"):s&&e.height!==t.height?e.height-t.height:0));let c=l[0];if(this.steering&&(o=this.steering.filterParsedLevels(o),o.length!==l.length))for(let e=0;e<l.length;e++)if(l[e].pathwayId===o[0].pathwayId){c=l[e];break}this._levels=o;for(let e=0;e<o.length;e++)if(o[e]===c){this._firstLevel=e,this.log(`manifest loaded, ${o.length} level(s) found, first bitrate: ${c.bitrate}`);break}const d=a&&!i,u={levels:o,audioTracks:r,subtitleTracks:n,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:a,video:i,altAudio:!d&&r.some((e=>!!e.url))};this.hls.trigger(Vf.MANIFEST_PARSED,u),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return 0===this._levels.length?null:this._levels}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){const r=new Error("invalid level idx"),n=e<0;if(this.hls.trigger(Vf.ERROR,{type:zf.OTHER_ERROR,details:Wf.LEVEL_SWITCH_ERROR,level:e,fatal:n,error:r,reason:r.message}),n)return;e=Math.min(e,t.length-1)}const r=this.currentLevelIndex,n=this.currentLevel,s=n?n.attrs["PATHWAY-ID"]:void 0,i=t[e],a=i.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=i,r===e&&i.details&&n&&s===a)return;this.log(`Switching to level ${e}${a?" with Pathway "+a:""} from level ${r}${s?" with Pathway "+s:""}`);const o=Gf({},i,{level:e,maxBitrate:i.maxBitrate,attrs:i.attrs,uri:i.uri,urlId:i.urlId});delete o._attrs,delete o._urlId,this.hls.trigger(Vf.LEVEL_SWITCHING,o);const l=i.details;if(!l||l.live){const e=this.switchParams(i.uri,null==n?void 0:n.details);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){const e=this.hls.config.startLevel;return void 0!==e?e:this._firstLevel}return this._startLevel}set startLevel(e){this._startLevel=e}onError(e,t){!t.fatal&&t.context&&t.context.type===Mg&&t.context.level===this.level&&this.checkRetry(t)}onFragLoaded(e,{frag:t}){if(void 0!==t&&t.type===Ng){const e=this._levels[t.level];void 0!==e&&(e.loadError=0)}}onLevelLoaded(e,t){var r;const{level:n,details:s}=t,i=this._levels[n];var a;if(!i)return this.warn(`Invalid level index ${n}`),void(null!=(a=t.deliveryDirectives)&&a.skip&&(s.deltaUpdateFailed=!0));n===this.currentLevelIndex?(0===i.fragmentError&&(i.loadError=0),this.playlistLoaded(n,t,i.details)):null!=(r=t.deliveryDirectives)&&r.skip&&(s.deltaUpdateFailed=!0)}onAudioTrackSwitched(e,t){const r=this.currentLevel;if(!r)return;const n=this.hls.audioTracks[t.id].groupId;if(r.audioGroupIds&&r.audioGroupId!==n){let e=-1;for(let t=0;t<r.audioGroupIds.length;t++)if(r.audioGroupIds[t]===n){e=t;break}-1!==e&&e!==r.urlId&&(r.urlId=e,this.canLoad&&this.startLoad())}}loadPlaylist(e){super.loadPlaylist();const t=this.currentLevelIndex,r=this.currentLevel;if(r&&this.shouldLoadPlaylist(r)){const n=r.urlId;let s=r.uri;if(e)try{s=e.addDirectives(s)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}const i=r.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""} with${i?" Pathway "+i:""} URI ${n+1}/${r.url.length} ${s}`),this.clearTimer(),this.hls.trigger(Vf.LEVEL_LOADING,{url:s,level:t,id:n,deliveryDirectives:e||null})}}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e,t){const r=(e,r)=>r!==t,n=this._levels.filter(((n,s)=>s!==e||(n.url.length>1&&void 0!==t?(n.url=n.url.filter(r),n.audioGroupIds&&(n.audioGroupIds=n.audioGroupIds.filter(r)),n.textGroupIds&&(n.textGroupIds=n.textGroupIds.filter(r)),n.urlId=0,!0):(this.steering&&this.steering.removeLevel(n),!1))));this.hls.trigger(Vf.LEVELS_UPDATED,{levels:n})}onLevelsUpdated(e,{levels:t}){t.forEach(((e,t)=>{const{details:r}=e;null!=r&&r.fragments&&r.fragments.forEach((e=>{e.level=t}))})),this._levels=t}}function Pm(e,t,r){r&&("audio"===t?(e.audioGroupIds||(e.audioGroupIds=[]),e.audioGroupIds[e.url.length-1]=r):"text"===t&&(e.textGroupIds||(e.textGroupIds=[]),e.textGroupIds[e.url.length-1]=r))}function Mm(e){const t={};e.forEach((e=>{const r=e.groupId||"";e.id=t[r]=t[r]||0,t[r]++}))}var Fm="NOT_LOADED",Um="APPENDING",Nm="PARTIAL",Bm="OK";class jm{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(Vf.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Vf.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Vf.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(Vf.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Vf.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Vf.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const r=this.activePartLists[t];if(r)for(let t=r.length;t--;){const n=r[t];if(!n)break;const s=n.end;if(n.start<=e&&null!==s&&e<=s)return n}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){const{fragments:r}=this,n=Object.keys(r);for(let s=n.length;s--;){const i=r[n[s]];if((null==i?void 0:i.body.type)===t&&i.buffered){const t=i.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,r,n){this.timeRanges&&(this.timeRanges[e]=t);const s=(null==n?void 0:n.fragment.sn)||-1;Object.keys(this.fragments).forEach((n=>{const i=this.fragments[n];if(!i)return;if(s>=i.body.sn)return;if(!i.buffered&&!i.loaded)return void(i.body.type===r&&this.removeFragment(i.body));const a=i.range[e];a&&a.time.some((e=>{const r=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return r&&this.removeFragment(i.body),r}))}))}detectPartialFragments(e){const t=this.timeRanges,{frag:r,part:n}=e;if(!t||"initSegment"===r.sn)return;const s=qm(r),i=this.fragments[s];if(!i||i.buffered&&r.gap)return;const a=!r.relurl;Object.keys(t).forEach((e=>{const s=r.elementaryStreams[e];if(!s)return;const o=t[e],l=a||!0===s.partial;i.range[e]=this.getBufferedTimes(r,n,l,o)})),i.loaded=null,Object.keys(i.range).length?(i.buffered=!0,i.body.endList&&(this.endListFragments[i.body.type]=i),$m(i)||this.removeParts(r.sn-1,r.type)):this.removeFragment(i.body)}removeParts(e,t){const r=this.activePartLists[t];r&&(this.activePartLists[t]=r.filter((t=>t.fragment.sn>=e)))}fragBuffered(e,t){const r=qm(e);let n=this.fragments[r];!n&&t&&(n=this.fragments[r]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),n&&(n.loaded=null,n.buffered=!0)}getBufferedTimes(e,t,r,n){const s={time:[],partial:r},i=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||i;for(let e=0;e<n.length;e++){const t=n.start(e)-this.bufferPadding,r=n.end(e)+this.bufferPadding;if(l>=t&&o<=r){s.time.push({startPTS:Math.max(i,n.start(e)),endPTS:Math.min(a,n.end(e))});break}if(i<r&&a>t)s.partial=!0,s.time.push({startPTS:Math.max(i,n.start(e)),endPTS:Math.min(a,n.end(e))});else if(a<=t)break}return s}getPartialFragment(e){let t,r,n,s=null,i=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach((l=>{const c=o[l];c&&$m(c)&&(r=c.body.start-a,n=c.body.end+a,e>=r&&e<=n&&(t=Math.min(e-r,n-e),i<=t&&(s=c.body,i=t)))})),s}isEndListAppended(e){const t=this.endListFragments[e];return void 0!==t&&(t.buffered||$m(t))}getState(e){const t=qm(e),r=this.fragments[t];return r?r.buffered?$m(r)?Nm:Bm:Um:Fm}isTimeBuffered(e,t,r){let n,s;for(let i=0;i<r.length;i++){if(n=r.start(i)-this.bufferPadding,s=r.end(i)+this.bufferPadding,e>=n&&t<=s)return!0;if(t<=n)return!1}return!1}onFragLoaded(e,t){const{frag:r,part:n}=t;if("initSegment"===r.sn||r.bitrateTest)return;const s=n?null:t,i=qm(r);this.fragments[i]={body:r,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:r,part:n,timeRanges:s}=t;if("initSegment"===r.sn)return;const i=r.type;if(n){let e=this.activePartLists[i];e||(this.activePartLists[i]=e=[]),e.push(n)}this.timeRanges=s,Object.keys(s).forEach((e=>{const t=s[e];this.detectEvictedFragments(e,t,i,n)}))}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=qm(e);return!!this.fragments[t]}hasParts(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}removeFragmentsInRange(e,t,r,n,s){n&&!this.hasGaps||Object.keys(this.fragments).forEach((i=>{const a=this.fragments[i];if(!a)return;const o=a.body;o.type!==r||n&&!o.gap||o.start<t&&o.end>e&&(a.buffered||s)&&this.removeFragment(o)}))}removeFragment(e){const t=qm(e);e.stats.loaded=0,e.clearElementaryStreamInfo();const r=this.activePartLists[e.type];if(r){const t=e.sn;this.activePartLists[e.type]=r.filter((e=>e.fragment.sn!==t))}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function $m(e){var t,r,n;return e.buffered&&(e.body.gap||(null==(t=e.range.video)?void 0:t.partial)||(null==(r=e.range.audio)?void 0:r.partial)||(null==(n=e.range.audiovideo)?void 0:n.partial))}function qm(e){return`${e.type}_${e.level}_${e.urlId}_${e.sn}`}const Km=Math.pow(2,17);class Gm{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const r=e.url;if(!r)return Promise.reject(new zm({type:zf.NETWORK_ERROR,details:Wf.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(r?"part list":"url")),networkDetails:null}));this.abort();const n=this.config,s=n.fLoader,i=n.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some((e=>"GAP"===e[0])))return void o(Vm(e));e.gap=!1}const l=this.loader=e.loader=s?new s(n):new i(n),c=Hm(e),d=vm(n.fragLoadPolicy.default),u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:Km};e.stats=l.stats,l.load(c,u,{onSuccess:(t,r,n,s)=>{this.resetLoader(e,l);let i=t.data;n.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(i.slice(0,16)),i=i.slice(16)),a({frag:e,part:null,payload:i,networkDetails:s})},onError:(t,n,s,i)=>{this.resetLoader(e,l),o(new zm({type:zf.NETWORK_ERROR,details:Wf.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:qf({url:r,data:void 0},t),error:new Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:s,stats:i}))},onAbort:(t,r,n)=>{this.resetLoader(e,l),o(new zm({type:zf.NETWORK_ERROR,details:Wf.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:n,stats:t}))},onTimeout:(t,r,n)=>{this.resetLoader(e,l),o(new zm({type:zf.NETWORK_ERROR,details:Wf.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:n,stats:t}))},onProgress:(r,n,s,i)=>{t&&t({frag:e,part:null,payload:s,networkDetails:i})}})}))}loadPart(e,t,r){this.abort();const n=this.config,s=n.fLoader,i=n.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void o(Vm(e,t));const l=this.loader=e.loader=s?new s(n):new i(n),c=Hm(e,t),d=vm(n.fragLoadPolicy.default),u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Km};t.stats=l.stats,l.load(c,u,{onSuccess:(n,s,i,o)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const c={frag:e,part:t,payload:n.data,networkDetails:o};r(c),a(c)},onError:(r,n,s,i)=>{this.resetLoader(e,l),o(new zm({type:zf.NETWORK_ERROR,details:Wf.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:qf({url:c.url,data:void 0},r),error:new Error(`HTTP Error ${r.code} ${r.text}`),networkDetails:s,stats:i}))},onAbort:(r,n,s)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),o(new zm({type:zf.NETWORK_ERROR,details:Wf.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:s,stats:r}))},onTimeout:(r,n,s)=>{this.resetLoader(e,l),o(new zm({type:zf.NETWORK_ERROR,details:Wf.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:s,stats:r}))}})}))}updateStatsFromPart(e,t){const r=e.stats,n=t.stats,s=n.total;if(r.loaded+=n.loaded,s){const n=Math.round(e.duration/t.duration),i=Math.min(Math.round(r.loaded/s),n),a=(n-i)*Math.round(r.loaded/i);r.total=r.loaded+a}else r.total=Math.max(r.loaded,r.total);const i=r.loading,a=n.loading;i.start?i.first+=a.first-a.start:(i.start=a.start,i.first=a.first),i.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Hm(e,t=null){const r=t||e,n={frag:e,part:t,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},s=r.byteRangeStartOffset,i=r.byteRangeEndOffset;if(Hf(s)&&Hf(i)){var a;let t=s,r=i;if("initSegment"===e.sn&&"AES-128"===(null==(a=e.decryptdata)?void 0:a.method)){const e=i-s;e%16&&(r=i+(16-e%16)),0!==s&&(n.resetIV=!0,t=s-16)}n.rangeStart=t,n.rangeEnd=r}return n}function Vm(e,t){const r=new Error(`GAP ${e.gap?"tag":"attribute"} found`),n={type:zf.MEDIA_ERROR,details:Wf.FRAG_GAP,fatal:!1,frag:e,error:r,networkDetails:null};return t&&(n.part=t),(t||e).stats.aborted=!0,new zm(n)}class zm extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Wm{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const t in this.keyUriToKeyInfo){const r=this.keyUriToKeyInfo[t].loader;if(r){if(e&&e!==r.context.frag.type)return;r.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=Wf.KEY_LOAD_ERROR,r,n,s){return new zm({type:zf.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:s,error:r,networkDetails:n})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:r,cc:n}=e;for(let e=0;e<t.length;e++){const s=t[e];if(n<=s.cc&&("initSegment"===r||"initSegment"===s.sn||r<s.sn)){this.emeController.selectKeySystemFormat(s).then((e=>{s.setKeyFormat(e)}));break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then((t=>this.loadInternal(e,t))):this.loadInternal(e)}loadInternal(e,t){var r,n;t&&e.setKeyFormat(t);const s=e.decryptdata;if(!s){const r=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,Wf.KEY_LOAD_ERROR,r))}const i=s.uri;if(!i)return Promise.reject(this.createKeyLoadError(e,Wf.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${i}"`)));let a=this.keyUriToKeyInfo[i];if(null!=(r=a)&&r.decryptdata.key)return s.key=a.decryptdata.key,Promise.resolve({frag:e,keyInfo:a});var o;if(null!=(n=a)&&n.keyLoadPromise)switch(null==(o=a.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then((t=>(s.key=t.keyInfo.decryptdata.key,{frag:e,keyInfo:a})))}switch(a=this.keyUriToKeyInfo[i]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===s.keyFormat?this.loadKeyHTTP(a,e):this.loadKeyEME(a,e);case"AES-128":return this.loadKeyHTTP(a,e);default:return Promise.reject(this.createKeyLoadError(e,Wf.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(e,t){const r={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const t=this.emeController.loadKey(r);if(t)return(e.keyLoadPromise=t.then((t=>(e.mediaKeySessionContext=t,r)))).catch((t=>{throw e.keyLoadPromise=null,t}))}return Promise.resolve(r)}loadKeyHTTP(e,t){const r=this.config,n=new(0,r.loader)(r);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise(((s,i)=>{const a={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},o=r.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(e,t,r,n)=>{const{frag:a,keyInfo:o,url:l}=r;if(!a.decryptdata||o!==this.keyUriToKeyInfo[l])return i(this.createKeyLoadError(a,Wf.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),n));o.decryptdata.key=a.decryptdata.key=new Uint8Array(e.data),a.keyLoader=null,o.loader=null,s({frag:a,keyInfo:o})},onError:(e,r,n,s)=>{this.resetLoader(r),i(this.createKeyLoadError(t,Wf.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),n,qf({url:a.url,data:void 0},e)))},onTimeout:(e,r,n)=>{this.resetLoader(r),i(this.createKeyLoadError(t,Wf.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),n))},onAbort:(e,r,n)=>{this.resetLoader(r),i(this.createKeyLoadError(t,Wf.INTERNAL_ABORTED,new Error("key loading aborted"),n))}};n.load(a,l,c)}))}resetLoader(e){const{frag:t,keyInfo:r,url:n}=e,s=r.loader;t.keyLoader===s&&(t.keyLoader=null,r.loader=null),delete this.keyUriToKeyInfo[n],s&&s.destroy()}}const Ym={length:0,start:()=>0,end:()=>0};class Qm{static isBuffered(e,t){try{if(e){const r=Qm.getBuffered(e);for(let e=0;e<r.length;e++)if(t>=r.start(e)&&t<=r.end(e))return!0}}catch(e){}return!1}static bufferInfo(e,t,r){try{if(e){const n=Qm.getBuffered(e),s=[];let i;for(i=0;i<n.length;i++)s.push({start:n.start(i),end:n.end(i)});return this.bufferedInfo(s,t,r)}}catch(e){}return{len:0,start:t,end:t,nextStart:void 0}}static bufferedInfo(e,t,r){t=Math.max(0,t),e.sort((function(e,t){const r=e.start-t.start;return r||t.end-e.end}));let n=[];if(r)for(let t=0;t<e.length;t++){const s=n.length;if(s){const i=n[s-1].end;e[t].start-i<r?e[t].end>i&&(n[s-1].end=e[t].end):n.push(e[t])}else n.push(e[t])}else n=e;let s,i=0,a=t,o=t;for(let e=0;e<n.length;e++){const l=n[e].start,c=n[e].end;if(t+r>=l&&t<c)a=l,o=c,i=o-t;else if(t+r<l){s=l;break}}return{len:i,start:a||0,end:o||0,nextStart:s}}static getBuffered(e){try{return e.buffered}catch(e){return Zf.log("failed to get media.buffered",e),Ym}}}class Xm{constructor(e,t,r,n=0,s=-1,i=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=r,this.size=n,this.part=s,this.partial=i}}function Jm(e,t){let r=null;for(let n=0,s=e.length;n<s;n++){const s=e[n];if(s&&s.cc===t){r=s;break}}return r}function Zm(e,t){if(e){const r=e.start+t;e.start=e.startPTS=r,e.endPTS=r+e.duration}}function ey(e,t){const r=t.fragments;for(let t=0,n=r.length;t<n;t++)Zm(r[t],e);t.fragmentHint&&Zm(t.fragmentHint,e),t.alignedSliding=!0}function ty(e,t,r){t&&(!function(e,t,r){if(function(e,t,r){return!(!t.details||!(r.endCC>r.startCC||e&&e.cc<r.startCC))}(e,r,t)){const e=function(e,t,r=0){const n=e.fragments,s=t.fragments;if(!s.length||!n.length)return void Zf.log("No fragments to align");const i=Jm(n,s[0].cc);if(i&&(!i||i.startPTS))return i;Zf.log("No frag in previous level to align on")}(r.details,t);e&&Hf(e.start)&&(Zf.log(`Adjusting PTS using last level due to CC increase within current level ${t.url}`),ey(e.start,t))}}(e,r,t),!r.alignedSliding&&t.details&&function(e,t){if(!t.fragments.length||!e.hasProgramDateTime||!t.hasProgramDateTime)return;const r=t.fragments[0].programDateTime,n=e.fragments[0].programDateTime,s=(n-r)/1e3+t.fragments[0].start;s&&Hf(s)&&(Zf.log(`Adjusting PTS using programDateTime delta ${n-r}ms, sliding:${s.toFixed(3)} ${e.url} `),ey(s,e))}(r,t.details),r.alignedSliding||!t.details||r.skippedSegments||um(t.details,r))}function ry(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;const r=e.fragments,n=t.fragments;if(!r.length||!n.length)return;const s=n[Math.round(n.length/2)-1],i=Jm(r,s.cc)||r[Math.round(r.length/2)-1],a=s.programDateTime,o=i.programDateTime;if(null===a||null===o)return;ey((o-a)/1e3-(i.start-s.start),e)}class ny{constructor(e,t){this.subtle=void 0,this.aesIV=void 0,this.subtle=e,this.aesIV=t}decrypt(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)}}class sy{constructor(e,t){this.subtle=void 0,this.key=void 0,this.subtle=e,this.key=t}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}class iy{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),r=new Uint32Array(4);for(let e=0;e<4;e++)r[e]=t.getUint32(4*e);return r}initTable(){const e=this.sBox,t=this.invSBox,r=this.subMix,n=r[0],s=r[1],i=r[2],a=r[3],o=this.invSubMix,l=o[0],c=o[1],d=o[2],u=o[3],h=new Uint32Array(256);let f=0,p=0,g=0;for(g=0;g<256;g++)h[g]=g<128?g<<1:g<<1^283;for(g=0;g<256;g++){let r=p^p<<1^p<<2^p<<3^p<<4;r=r>>>8^255&r^99,e[f]=r,t[r]=f;const o=h[f],g=h[o],m=h[g];let y=257*h[r]^16843008*r;n[f]=y<<24|y>>>8,s[f]=y<<16|y>>>16,i[f]=y<<8|y>>>24,a[f]=y,y=16843009*m^65537*g^257*o^16843008*f,l[r]=y<<24|y>>>8,c[r]=y<<16|y>>>16,d[r]=y<<8|y>>>24,u[r]=y,f?(f=o^h[h[h[m^o]]],p^=h[h[p]]):f=p=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let r=!0,n=0;for(;n<t.length&&r;)r=t[n]===this.key[n],n++;if(r)return;this.key=t;const s=this.keySize=t.length;if(4!==s&&6!==s&&8!==s)throw new Error("Invalid aes key size="+s);const i=this.ksRows=4*(s+6+1);let a,o;const l=this.keySchedule=new Uint32Array(i),c=this.invKeySchedule=new Uint32Array(i),d=this.sBox,u=this.rcon,h=this.invSubMix,f=h[0],p=h[1],g=h[2],m=h[3];let y,v;for(a=0;a<i;a++)a<s?y=l[a]=t[a]:(v=y,a%s==0?(v=v<<8|v>>>24,v=d[v>>>24]<<24|d[v>>>16&255]<<16|d[v>>>8&255]<<8|d[255&v],v^=u[a/s|0]<<24):s>6&&a%s==4&&(v=d[v>>>24]<<24|d[v>>>16&255]<<16|d[v>>>8&255]<<8|d[255&v]),l[a]=y=(l[a-s]^v)>>>0);for(o=0;o<i;o++)a=i-o,v=3&o?l[a]:l[a-4],c[o]=o<4||a<=4?v:f[d[v>>>24]]^p[d[v>>>16&255]]^g[d[v>>>8&255]]^m[d[255&v]],c[o]=c[o]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}decrypt(e,t,r){const n=this.keySize+6,s=this.invKeySchedule,i=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],c=a[2],d=a[3],u=this.uint8ArrayToUint32Array_(r);let h=u[0],f=u[1],p=u[2],g=u[3];const m=new Int32Array(e),y=new Int32Array(m.length);let v,b,w,E,S,T,C,k,A,I,_,R,L,D;const x=this.networkToHostOrderSwap;for(;t<m.length;){for(A=x(m[t]),I=x(m[t+1]),_=x(m[t+2]),R=x(m[t+3]),S=A^s[0],T=R^s[1],C=_^s[2],k=I^s[3],L=4,D=1;D<n;D++)v=o[S>>>24]^l[T>>16&255]^c[C>>8&255]^d[255&k]^s[L],b=o[T>>>24]^l[C>>16&255]^c[k>>8&255]^d[255&S]^s[L+1],w=o[C>>>24]^l[k>>16&255]^c[S>>8&255]^d[255&T]^s[L+2],E=o[k>>>24]^l[S>>16&255]^c[T>>8&255]^d[255&C]^s[L+3],S=v,T=b,C=w,k=E,L+=4;v=i[S>>>24]<<24^i[T>>16&255]<<16^i[C>>8&255]<<8^i[255&k]^s[L],b=i[T>>>24]<<24^i[C>>16&255]<<16^i[k>>8&255]<<8^i[255&S]^s[L+1],w=i[C>>>24]<<24^i[k>>16&255]<<16^i[S>>8&255]<<8^i[255&T]^s[L+2],E=i[k>>>24]<<24^i[S>>16&255]<<16^i[T>>8&255]<<8^i[255&C]^s[L+3],y[t]=x(v^h),y[t+1]=x(E^f),y[t+2]=x(w^p),y[t+3]=x(b^g),h=A,f=I,p=_,g=R,t+=4}return y.buffer}}class ay{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.useSoftware=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch(e){}null===this.subtle&&(this.useSoftware=!0)}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const r=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?function(e){const t=e.byteLength,r=t&&new DataView(e.buffer).getUint8(t-1);return r?Ap(e,0,t-r):e}(r):r}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,r){return this.useSoftware?new Promise(((n,s)=>{this.softwareDecrypt(new Uint8Array(e),t,r);const i=this.flush();i?n(i.buffer):s(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(e),t,r)}softwareDecrypt(e,t,r){const{currentIV:n,currentResult:s,remainderData:i}=this;this.logOnce("JS AES decrypt"),i&&(e=ng(i,e),this.remainderData=null);const a=this.getValidChunk(e);if(!a.length)return null;n&&(r=n);let o=this.softwareDecrypter;o||(o=this.softwareDecrypter=new iy),o.expandKey(t);const l=s;return this.currentResult=o.decrypt(a.buffer,0,r),this.currentIV=Ap(a,-16).buffer,l||null}webCryptoDecrypt(e,t,r){const n=this.subtle;return this.key===t&&this.fastAesKey||(this.key=t,this.fastAesKey=new sy(n,t)),this.fastAesKey.expandKey().then((t=>{if(!n)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new ny(n,new Uint8Array(r)).decrypt(e.buffer,t)})).catch((n=>(Zf.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,r))))}onWebCryptoError(e,t,r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,r);const n=this.flush();if(n)return n.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(e){let t=e;const r=e.length-e.length%16;return r!==e.length&&(t=Ap(e,0,r),this.remainderData=Ap(e,r)),t}logOnce(e){this.logEnabled&&(Zf.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const oy=function(e){let t="";const r=e.length;for(let n=0;n<r;n++)t+=`[${e.start(n).toFixed(3)}-${e.end(n).toFixed(3)}]`;return t},ly="STOPPED",cy="IDLE",dy="KEY_LOADING",uy="FRAG_LOADING",hy="FRAG_LOADING_WAITING_RETRY",fy="WAITING_TRACK",py="PARSING",gy="PARSED",my="ENDED",yy="ERROR",vy="WAITING_INIT_PTS",by="WAITING_LEVEL";class wy extends class{constructor(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}{constructor(e,t,r,n,s){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=ly,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.loadedmetadata=!1,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.onvseeking=null,this.onvended=null,this.logPrefix="",this.log=void 0,this.warn=void 0,this.playlistType=s,this.logPrefix=n,this.log=Zf.log.bind(Zf,`${n}:`),this.warn=Zf.warn.bind(Zf,`${n}:`),this.hls=e,this.fragmentLoader=new Gm(e.config),this.keyLoader=r,this.fragmentTracker=t,this.config=e.config,this.decrypter=new ay(e.config),e.on(Vf.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=ly}_streamEnded(e,t){if(t.live||e.nextStart||!e.end||!this.media)return!1;const r=t.partList;if(null!=r&&r.length){const e=r[r.length-1];return Qm.isBuffered(this.media,e.start+e.duration/2)}const n=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(n)}getLevelDetails(){var e;if(this.levels&&null!==this.levelLastLoaded)return null==(e=this.levels[this.levelLastLoaded])?void 0:e.details}onMediaAttached(e,t){const r=this.media=this.mediaBuffer=t.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),r.addEventListener("seeking",this.onvseeking),r.addEventListener("ended",this.onvended);const n=this.config;this.levels&&n.autoStartLoad&&this.state===ly&&this.startLoad(n.startPosition)}onMediaDetaching(){const e=this.media;null!=e&&e.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),e&&this.onvseeking&&this.onvended&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}onMediaSeeking(){const{config:e,fragCurrent:t,media:r,mediaBuffer:n,state:s}=this,i=r?r.currentTime:0,a=Qm.bufferInfo(n||r,i,e.maxBufferHole);if(this.log(`media seeking to ${Hf(i)?i.toFixed(3):i}, state: ${s}`),this.state===my)this.resetLoadingState();else if(t){const r=e.maxFragLookUpTolerance,n=t.start-r,s=t.start+t.duration+r;if(!a.len||s<a.start||n>a.end){const e=i>s;(i<n||e)&&(e&&t.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}r&&(this.fragmentTracker.removeFragmentsInRange(i,1/0,this.playlistType,!0),this.lastCurrentTime=i),this.loadedmetadata||a.len||(this.nextLoadPosition=this.startPosition=i),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.stopLoad(),super.onHandlerDestroying()}onHandlerDestroyed(){this.state=ly,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,r){this._loadFragForPlayback(e,t,r)}_loadFragForPlayback(e,t,r){this._doFragLoad(e,t,r,(t=>{if(this.fragContextChanged(e))return this.warn(`Fragment ${e.sn}${t.part?" p: "+t.part.index:""} of level ${e.level} was dropped during download.`),void this.fragmentTracker.removeFragment(e);e.stats.chunkCount++,this._handleFragmentLoadProgress(t)})).then((t=>{if(!t)return;const r=this.state;this.fragContextChanged(e)?(r===uy||!this.fragCurrent&&r===py)&&(this.fragmentTracker.removeFragment(e),this.state=cy):("payload"in t&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(Vf.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))})).catch((t=>{this.state!==ly&&this.state!==yy&&(this.warn(t),this.resetFragmentLoading(e))}))}clearTrackerIfNeeded(e){var t;const{fragmentTracker:r}=this;if(r.getState(e)===Um){const t=e.type,n=this.getFwdBufferInfo(this.mediaBuffer,t),s=Math.max(e.duration,n?n.len:this.config.maxBufferLength);this.reduceMaxBufferLength(s)&&r.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?r.removeAllFragments():r.hasParts(e.type)&&(r.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),r.getState(e)===Nm&&r.removeFragment(e))}flushMainBuffer(e,t,r=null){if(!(e-t))return;const n={startOffset:e,endOffset:t,type:r};this.hls.trigger(Vf.BUFFER_FLUSHING,n)}_loadInitSegment(e,t){this._doFragLoad(e,t).then((t=>{if(!t||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return t})).then((t=>{const{hls:r}=this,{payload:n}=t,s=e.decryptdata;if(n&&n.byteLength>0&&s&&s.key&&s.iv&&"AES-128"===s.method){const i=self.performance.now();return this.decrypter.decrypt(new Uint8Array(n),s.key.buffer,s.iv.buffer).catch((t=>{throw r.trigger(Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t})).then((n=>{const s=self.performance.now();return r.trigger(Vf.FRAG_DECRYPTED,{frag:e,payload:n,stats:{tstart:i,tdecrypt:s}}),t.payload=n,t}))}return t})).then((r=>{const{fragCurrent:n,hls:s,levels:i}=this;if(!i)throw new Error("init load aborted, missing levels");const a=e.stats;this.state=cy,t.fragmentError=0,e.data=new Uint8Array(r.payload),a.parsing.start=a.buffering.start=self.performance.now(),a.parsing.end=a.buffering.end=self.performance.now(),r.frag===n&&s.trigger(Vf.FRAG_BUFFERED,{stats:a,frag:n,part:null,id:e.type}),this.tick()})).catch((t=>{this.state!==ly&&this.state!==yy&&(this.warn(t),this.resetFragmentLoading(e))}))}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.level!==t.level||e.sn!==t.sn||e.urlId!==t.urlId}fragBufferedComplete(e,t){var r,n,s,i;const a=this.mediaBuffer?this.mediaBuffer:this.media;this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.playlistType===Ng?"level":"track"} ${e.level} (frag:[${(null!=(r=e.startPTS)?r:NaN).toFixed(3)}-${(null!=(n=e.endPTS)?n:NaN).toFixed(3)}] > buffer:${a?oy(Qm.getBuffered(a)):"(detached)"})`),this.state=cy,a&&(!this.loadedmetadata&&e.type==Ng&&a.buffered.length&&(null==(s=this.fragCurrent)?void 0:s.sn)===(null==(i=this.fragPrevious)?void 0:i.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:r,part:n,partsLoaded:s}=e,i=!s||0===s.length||s.some((e=>!e)),a=new Xm(r.level,r.sn,r.stats.chunkCount+1,0,n?n.index:-1,!i);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,r=null,n){var s;const i=null==t?void 0:t.details;if(!this.levels||!i)throw new Error(`frag load aborted, missing level${i?"":" detail"}s`);let a=null;if(!e.encrypted||null!=(s=e.decryptdata)&&s.key?!e.encrypted&&i.encryptedFragments.length&&this.keyLoader.loadClear(e,i.encryptedFragments):(this.log(`Loading key for ${e.sn} of [${i.startSN}-${i.endSN}], ${"[stream-controller]"===this.logPrefix?"level":"track"} ${e.level}`),this.state=dy,this.fragCurrent=e,a=this.keyLoader.load(e).then((e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(Vf.KEY_LOADED,e),this.state===dy&&(this.state=cy),e})),this.hls.trigger(Vf.KEY_LOADING,{frag:e}),null===this.fragCurrent&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))),r=Math.max(e.start,r||0),this.config.lowLatencyMode&&"initSegment"!==e.sn){const s=i.partList;if(s&&n){r>e.end&&i.fragmentHint&&(e=i.fragmentHint);const o=this.getNextPart(s,e,r);if(o>-1){const l=s[o];let c;return this.log(`Loading part sn: ${e.sn} p: ${l.index} cc: ${e.cc} of playlist [${i.startSN}-${i.endSN}] parts [0-${o}-${s.length-1}] ${"[stream-controller]"===this.logPrefix?"level":"track"}: ${e.level}, target: ${parseFloat(r.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=uy,c=a?a.then((r=>!r||this.fragContextChanged(r.frag)?null:this.doFragPartsLoad(e,l,t,n))).catch((e=>this.handleFragLoadError(e))):this.doFragPartsLoad(e,l,t,n).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(Vf.FRAG_LOADING,{frag:e,part:l,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):c}if(!e.url||this.loadedEndOfParts(s,r))return Promise.resolve(null)}}this.log(`Loading fragment ${e.sn} cc: ${e.cc} ${i?"of ["+i.startSN+"-"+i.endSN+"] ":""}${"[stream-controller]"===this.logPrefix?"level":"track"}: ${e.level}, target: ${parseFloat(r.toFixed(3))}`),Hf(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=uy;const o=this.config.progressive;let l;return l=o&&a?a.then((t=>!t||this.fragContextChanged(null==t?void 0:t.frag)?null:this.fragmentLoader.load(e,n))).catch((e=>this.handleFragLoadError(e))):Promise.all([this.fragmentLoader.load(e,o?n:void 0),a]).then((([e])=>(!o&&e&&n&&n(e),e))).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(Vf.FRAG_LOADING,{frag:e,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):l}doFragPartsLoad(e,t,r,n){return new Promise(((s,i)=>{var a;const o=[],l=null==(a=r.details)?void 0:a.partList,c=t=>{this.fragmentLoader.loadPart(e,t,n).then((n=>{o[t.index]=n;const i=n.part;this.hls.trigger(Vf.FRAG_LOADED,n);const a=fm(r,e.sn,t.index+1)||pm(l,e.sn,t.index+1);if(!a)return s({frag:e,part:i,partsLoaded:o});c(a)})).catch(i)};c(t)}))}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===Wf.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(Vf.ERROR,t)}else this.hls.trigger(Vf.ERROR,{type:zf.OTHER_ERROR,details:Wf.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==py)return void(this.fragCurrent||this.state===ly||this.state===yy||(this.state=cy));const{frag:r,part:n,level:s}=t,i=self.performance.now();r.stats.parsing.end=i,n&&(n.stats.parsing.end=i),this.updateLevelTiming(r,n,s,e.partial)}getCurrentContext(e){const{levels:t,fragCurrent:r}=this,{level:n,sn:s,part:i}=e;if(null==t||!t[n])return this.warn(`Levels object was unset while buffering fragment ${s} of level ${n}. The current chunk will not be buffered.`),null;const a=t[n],o=i>-1?fm(a,s,i):null,l=o?o.fragment:function(e,t,r){if(null==e||!e.details)return null;const n=e.details;let s=n.fragments[t-n.startSN];return s||(s=n.fragmentHint,s&&s.sn===t?s:t<n.startSN&&r&&r.sn===t?r:null)}(a,s,r);return l?(r&&r!==l&&(l.stats=r.stats),{frag:l,part:o,level:a}):null}bufferFragmentData(e,t,r,n,s){var i;if(!e||this.state!==py)return;const{data1:a,data2:o}=e;let l=a;if(a&&o&&(l=ng(a,o)),null==(i=l)||!i.length)return;const c={type:e.type,frag:t,part:r,chunkMeta:n,parent:t.type,data:l};if(this.hls.trigger(Vf.BUFFER_APPENDING,c),e.dropped&&e.independent&&!r){if(s)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!Qm.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);const r=t.currentTime,n=Qm.bufferInfo(t,r,0),s=e.duration,i=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),a=Math.max(Math.min(e.start-i,n.end-i),r+i);e.start-a>i&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){const r=this.getLoadPosition();return Hf(r)?this.getFwdBufferInfoAtPos(e,r,t):null}getFwdBufferInfoAtPos(e,t,r){const{config:{maxBufferHole:n}}=this,s=Qm.bufferInfo(e,t,n);if(0===s.len&&void 0!==s.nextStart){const i=this.fragmentTracker.getBufferedFrag(t,r);if(i&&s.nextStart<i.end)return Qm.bufferInfo(e,t,Math.max(s.nextStart,n))}return s}getMaxBufferLength(e){const{config:t}=this;let r;return r=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(r,t.maxMaxBufferLength)}reduceMaxBufferLength(e){const t=this.config,r=e||t.maxBufferLength;return t.maxMaxBufferLength>=r&&(t.maxMaxBufferLength/=2,this.warn(`Reduce max buffer length to ${t.maxMaxBufferLength}s`),!0)}getAppendedFrag(e,t=Ng){const r=this.fragmentTracker.getAppendedFrag(e,Ng);return r&&"fragment"in r?r.fragment:r}getNextFragment(e,t){const r=t.fragments,n=r.length;if(!n)return null;const{config:s}=this,i=r[0].start;let a;if(t.live){const i=s.initialLiveManifestSize;if(n<i)return this.warn(`Not enough fragments to start playback (have: ${n}, need: ${i})`),null;t.PTSKnown||this.startFragRequested||-1!==this.startPosition||(a=this.getInitialLiveFragment(t,r),this.startPosition=a?this.hls.liveSyncPosition||a.start:e)}else e<=i&&(a=r[0]);if(!a){const r=s.lowLatencyMode?t.partEnd:t.fragmentEnd;a=this.getFragmentAtPosition(e,r,t)}return this.mapToInitFragWhenRequired(a)}isLoopLoading(e,t){const r=this.fragmentTracker.getState(e);return(r===Bm||r===Nm&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,r,n,s){const i=e.gap,a=this.getNextFragment(this.nextLoadPosition,t);if(null===a)return a;if(e=a,i&&e&&!e.gap&&r.nextStart){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,n);if(null!==t&&r.len+t.len>=s)return this.log(`buffer full after gaps in "${n}" playlist starting at sn: ${e.sn}`),null}return e}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||null!=e&&e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,r){let n=-1,s=!1,i=!0;for(let a=0,o=e.length;a<o;a++){const o=e[a];if(i=i&&!o.independent,n>-1&&r<o.start)break;const l=o.loaded;l?n=-1:(s||o.independent||i)&&o.fragment===t&&(n=a),s=l}return n}loadedEndOfParts(e,t){const r=e[e.length-1];return r&&t>r.start&&r.loaded}getInitialLiveFragment(e,t){const r=this.fragPrevious;let n=null;if(r){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${r.programDateTime}`),n=function(e,t,r){if(null===t||!Array.isArray(e)||!e.length||!Hf(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;r=r||0;for(let n=0;n<e.length;++n){const s=e[n];if(Tm(t,r,s))return s}return null}(t,r.endProgramDateTime,this.config.maxFragLookUpTolerance)),!n){const s=r.sn+1;if(s>=e.startSN&&s<=e.endSN){const i=t[s-e.startSN];r.cc===i.cc&&(n=i,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=function(e,t){return wm(e,(e=>e.cc<t?1:e.cc>t?-1:0))}(t,r.cc),n&&this.log(`Live playlist, switching playlist, load frag with same CC: ${n.sn}`))}}else{const t=this.hls.liveSyncPosition;null!==t&&(n=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return n}getFragmentAtPosition(e,t,r){const{config:n}=this;let{fragPrevious:s}=this,{fragments:i,endSN:a}=r;const{fragmentHint:o}=r,l=n.maxFragLookUpTolerance,c=r.partList,d=!!(n.lowLatencyMode&&null!=c&&c.length&&o);let u;if(d&&o&&!this.bitrateTest&&(i=i.concat(o),a=o.sn),e<t){u=Em(s,i,e,e>t-l?0:l)}else u=i[i.length-1];if(u){const e=u.sn-r.startSN,t=this.fragmentTracker.getState(u);if((t===Bm||t===Nm&&u.gap)&&(s=u),s&&u.sn===s.sn&&(!d||c[0].fragment.sn>u.sn)){if(s&&u.level===s.level){const t=i[e+1];u=u.sn<a&&this.fragmentTracker.getState(t)!==Bm?t:null}}}return u}synchronizeToLiveEdge(e){const{config:t,media:r}=this;if(!r)return;const n=this.hls.liveSyncPosition,s=r.currentTime,i=e.fragments[0].start,a=e.edge,o=s>=i-t.maxFragLookUpTolerance&&s<=a;if(null!==n&&r.duration>n&&(s<n||!o)){const i=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!o&&r.readyState<4||s<a-i)&&(this.loadedmetadata||(this.nextLoadPosition=n),r.readyState&&(this.warn(`Playback: ${s.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${n.toFixed(3)}`),r.currentTime=n))}}alignPlaylists(e,t){const{levels:r,levelLastLoaded:n,fragPrevious:s}=this,i=null!==n?r[n]:null,a=e.fragments.length;if(!a)return this.warn("No fragments in live playlist"),0;const o=e.fragments[0].start,l=!t,c=e.alignedSliding&&Hf(o);if(l||!c&&!o){ty(s,i,e);const r=e.fragments[0].start;return this.log(`Live playlist sliding: ${r.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} prev-sn: ${s?s.sn:"na"} fragments: ${a}`),r}return o}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let r=this.startPosition;if(r<t&&(r=-1),-1===r||-1===this.lastCurrentTime){const n=null!==this.startTimeOffset,s=n?this.startTimeOffset:e.startTimeOffset;null!==s&&Hf(s)?(r=t+s,s<0&&(r+=e.totalduration),r=Math.min(Math.max(t,r),t+e.totalduration),this.log(`Start time offset ${s} found in ${n?"multivariant":"media"} playlist, adjust startPosition to ${r}`),this.startPosition=r):e.live?r=this.hls.liveSyncPosition||t:this.startPosition=r=0,this.lastCurrentTime=r}this.nextLoadPosition=r}getLoadPosition(){const{media:e}=this;let t=0;return this.loadedmetadata&&e?t=e.currentTime:this.nextLoadPosition&&(t=this.nextLoadPosition),t}handleFragLoadAborted(e,t){this.transmuxer&&"initSegment"!==e.sn&&e.stats.aborted&&(this.warn(`Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===hy)||(this.state=cy)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}const r=t.frag;if(!r||r.type!==e||!this.levels)return;var n;if(this.fragContextChanged(r))return void this.warn(`Frag load error must match current frag to retry ${r.url} > ${null==(n=this.fragCurrent)?void 0:n.url}`);const s=t.details===Wf.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(r,!0);const i=t.errorAction,{action:a,retryCount:o=0,retryConfig:l}=i||{};if(i&&a===Am&&l){var c;this.resetStartWhenNotLoaded(null!=(c=this.levelLastLoaded)?c:r.level);const n=ym(l,o);this.warn(`Fragment ${r.sn} of ${e} ${r.level} errored with ${t.details}, retrying loading ${o+1}/${l.maxNumRetry} in ${n}ms`),i.resolved=!0,this.retryDate=self.performance.now()+n,this.state=hy}else l&&i?(this.resetFragmentErrors(e),o<l.maxNumRetry?s||(i.resolved=!0):Zf.warn(`${t.details} reached or exceeded max retry (${o})`)):(null==i?void 0:i.action)===km?this.state=by:this.state=yy;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===py||this.state===gy){const t=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,t),n=r&&r.len>.5;n&&this.reduceMaxBufferLength(r.len);const s=!n;return s&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${t} buffer`),e.frag&&(this.fragmentTracker.removeFragment(e.frag),this.nextLoadPosition=e.frag.start),this.resetLoadingState(),s}return!1}resetFragmentErrors(e){e===Bg&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==ly&&(this.state=cy)}afterBufferFlushed(e,t,r){if(!e)return;const n=Qm.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,r),this.state===my&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=cy}resetStartWhenNotLoaded(e){if(!this.loadedmetadata){this.startFragRequested=!1;const t=this.levels?this.levels[e].details:null;null!=t&&t.live?(this.startPosition=-1,this.setStartPosition(t,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){var t;this.warn(`The loading context changed while buffering fragment ${e.sn} of level ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(null!=(t=this.levelLastLoaded)?t:e.level),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,r,n){var s;const i=r.details;if(!i)return void this.warn("level.details undefined");if(Object.keys(e.elementaryStreams).reduce(((t,s)=>{const a=e.elementaryStreams[s];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${e.sn} ${s} duration reliably (${o})`),t||!1;const l=n?0:cm(i,e,a.startPTS,a.endPTS,a.startDTS,a.endDTS);return this.hls.trigger(Vf.LEVEL_PTS_UPDATED,{details:i,level:r,drift:l,type:s,frag:e,start:a.startPTS,end:a.endPTS}),!0}return t}),!1))r.fragmentError=0;else if(null===(null==(s=this.transmuxer)?void 0:s.error)){const t=new Error(`Found no media in fragment ${e.sn} of level ${e.level} resetting transmuxer to fallback to playlist timing`);if(0===r.fragmentError&&(r.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)),this.warn(t.message),this.hls.trigger(Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of level "${r.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=gy,this.hls.trigger(Vf.FRAG_PARSED,{frag:e,part:t})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(e){var t,r,n;"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(null!=(t=null!=(r=this.levelLastLoaded)?r:null==(n=this.fragCurrent)?void 0:n.level)?t:0),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function Ey(){return self.SourceBuffer||self.WebKitSourceBuffer}function Sy(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class Ty{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,r,n){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,r){}demux(e,t){this.cachedData&&(e=ng(this.cachedData,e),this.cachedData=null);let r,n=Rp(e,0),s=n?n.length:0;const i=this._audioTrack,a=this._id3Track,o=n?(e=>{const t=Pp(e);for(let e=0;e<t.length;e++){const r=t[e];if(xp(r))return Bp(r)}})(n):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&Hf(o))&&(this.basePTS=Cy(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),n&&n.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:Wg,duration:Number.POSITIVE_INFINITY});s<l;){if(this.canParse(e,s)){const t=this.appendFrame(i,e,s);t?(this.frameIndex++,this.lastPTS=t.sample.pts,s+=t.length,r=s):s=l}else Dp(e,s)?(n=Rp(e,s),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:Wg,duration:Number.POSITIVE_INFINITY}),s+=n.length,r=s):s++;if(s===l&&r!==l){const t=Ap(e,r);this.cachedData?this.cachedData=ng(this.cachedData,t):this.cachedData=t}}return{audioTrack:i,videoTrack:Sy(),id3Track:a,textTrack:Sy()}}demuxSampleAes(e,t,r){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Sy(),id3Track:this._id3Track,textTrack:Sy()}}destroy(){}}const Cy=(e,t,r)=>{if(Hf(e))return 90*e;return 9e4*t+(r?9e4*r.baseTime/r.timescale:0)};function ky(e,t){return 255===e[t]&&240==(246&e[t+1])}function Ay(e,t){return 1&e[t+1]?7:9}function Iy(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function _y(e,t){return t+1<e.length&&ky(e,t)}function Ry(e,t){if(_y(e,t)){const r=Ay(e,t);if(t+r>=e.length)return!1;const n=Iy(e,t);if(n<=r)return!1;const s=t+n;return s===e.length||_y(e,s)}return!1}function Ly(e,t,r,n,s){if(!e.samplerate){const i=function(e,t,r,n){let s,i,a,o;const l=navigator.userAgent.toLowerCase(),c=n,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=1+((192&t[r+2])>>>6);const u=(60&t[r+2])>>>2;if(!(u>d.length-1))return a=(1&t[r+2])<<2,a|=(192&t[r+3])>>>6,Zf.log(`manifest codec:${n}, ADTS type:${s}, samplingIndex:${u}`),/firefox/i.test(l)?u>=6?(s=5,o=new Array(4),i=u-3):(s=2,o=new Array(2),i=u):-1!==l.indexOf("android")?(s=2,o=new Array(2),i=u):(s=5,o=new Array(4),n&&(-1!==n.indexOf("mp4a.40.29")||-1!==n.indexOf("mp4a.40.5"))||!n&&u>=6?i=u-3:((n&&-1!==n.indexOf("mp4a.40.2")&&(u>=6&&1===a||/vivaldi/i.test(l))||!n&&1===a)&&(s=2,o=new Array(2)),i=u)),o[0]=s<<3,o[0]|=(14&u)>>1,o[1]|=(1&u)<<7,o[1]|=a<<3,5===s&&(o[1]|=(14&i)>>1,o[2]=(1&i)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:d[u],channelCount:a,codec:"mp4a.40."+s,manifestCodec:c};e.trigger(Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.FRAG_PARSING_ERROR,fatal:!0,reason:`invalid ADTS sampling index:${u}`})}(t,r,n,s);if(!i)return;e.config=i.config,e.samplerate=i.samplerate,e.channelCount=i.channelCount,e.codec=i.codec,e.manifestCodec=i.manifestCodec,Zf.log(`parsed codec:${e.codec}, rate:${i.samplerate}, channels:${i.channelCount}`)}}function Dy(e){return 9216e4/e}function xy(e,t,r,n,s){const i=n+s*Dy(e.samplerate),a=function(e,t){const r=Ay(e,t);if(t+r<=e.length){const n=Iy(e,t)-r;if(n>0)return{headerLength:r,frameLength:n}}}(t,r);let o;if(a){const{frameLength:n,headerLength:s}=a,l=s+n,c=Math.max(0,r+l-t.length);c?(o=new Uint8Array(l-s),o.set(t.subarray(r+s,t.length),0)):o=t.subarray(r+s,r+l);const d={unit:o,pts:i};return c||e.samples.push(d),{sample:d,length:l,missing:c}}const l=t.length-r;o=new Uint8Array(l),o.set(t.subarray(r,t.length),0);return{sample:{unit:o,pts:i},length:l,missing:-1}}const Oy=/\/emsg[-/]ID3/i;let Py=null;const My=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],Fy=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Uy=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Ny=[0,1,1,4];function By(e,t,r,n,s){if(r+24>t.length)return;const i=jy(t,r);if(i&&r+i.frameLength<=t.length){const a=n+s*(9e4*i.samplesPerFrame/i.sampleRate),o={unit:t.subarray(r,r+i.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=i.channelCount,e.samplerate=i.sampleRate,e.samples.push(o),{sample:o,length:i.frameLength,missing:0}}}function jy(e,t){const r=e[t+1]>>3&3,n=e[t+1]>>1&3,s=e[t+2]>>4&15,i=e[t+2]>>2&3;if(1!==r&&0!==s&&15!==s&&3!==i){const a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*My[14*(3===r?3-n:3===n?3:4)+s-1],c=Fy[3*(3===r?0:2===r?1:2)+i],d=3===o?1:2,u=Uy[r][n],h=Ny[n],f=8*u*h,p=Math.floor(u*l/c+a)*h;if(null===Py){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Py=e?parseInt(e[1]):0}return!!Py&&Py<=87&&2===n&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:c,channelCount:d,frameLength:p,samplesPerFrame:f}}}function $y(e,t){return 255===e[t]&&224==(224&e[t+1])&&0!=(6&e[t+1])}function qy(e,t){return t+1<e.length&&$y(e,t)}function Ky(e,t){if(t+1<e.length&&$y(e,t)){const r=4,n=jy(e,t);let s=r;null!=n&&n.frameLength&&(s=n.frameLength);const i=t+s;return i===e.length||qy(e,i)}return!1}class Gy{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,r=e.byteLength-t,n=new Uint8Array(4),s=Math.min(4,t);if(0===s)throw new Error("no bytes available");n.set(e.subarray(r,r+s)),this.word=new DataView(n.buffer).getUint32(0),this.bitsAvailable=8*s,this.bytesAvailable-=s}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(t=(e-=this.bitsAvailable)>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const r=this.word>>>32-t;if(e>32&&Zf.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return t=e-t,t>0&&this.bitsAvailable?r<<t|this.readBits(t):r}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(0!=(this.word&2147483648>>>e))return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(e){let t,r=8,n=8;for(let s=0;s<e;s++)0!==n&&(t=this.readEG(),n=(r+t+256)%256),r=0===n?r:n}readSPS(){let e,t,r,n=0,s=0,i=0,a=0;const o=this.readUByte.bind(this),l=this.readBits.bind(this),c=this.readUEG.bind(this),d=this.readBoolean.bind(this),u=this.skipBits.bind(this),h=this.skipEG.bind(this),f=this.skipUEG.bind(this),p=this.skipScalingList.bind(this);o();const g=o();if(l(5),u(3),o(),f(),100===g||110===g||122===g||244===g||44===g||83===g||86===g||118===g||128===g){const e=c();if(3===e&&u(1),f(),f(),u(1),d())for(t=3!==e?8:12,r=0;r<t;r++)d()&&p(r<6?16:64)}f();const m=c();if(0===m)c();else if(1===m)for(u(1),h(),h(),e=c(),r=0;r<e;r++)h();f(),u(1);const y=c(),v=c(),b=l(1);0===b&&u(1),u(1),d()&&(n=c(),s=c(),i=c(),a=c());let w=[1,1];if(d()&&d()){switch(o()){case 1:w=[1,1];break;case 2:w=[12,11];break;case 3:w=[10,11];break;case 4:w=[16,11];break;case 5:w=[40,33];break;case 6:w=[24,11];break;case 7:w=[20,11];break;case 8:w=[32,11];break;case 9:w=[80,33];break;case 10:w=[18,11];break;case 11:w=[15,11];break;case 12:w=[64,33];break;case 13:w=[160,99];break;case 14:w=[4,3];break;case 15:w=[3,2];break;case 16:w=[2,1];break;case 255:w=[o()<<8|o(),o()<<8|o()]}}return{width:Math.ceil(16*(y+1)-2*n-2*s),height:(2-b)*(v+1)*16-(b?2:4)*(i+a),pixelRatio:w}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class Hy{constructor(e,t,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new ay(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(e,t,r){const n=e[t].unit;if(n.length<=16)return;const s=n.subarray(16,n.length-n.length%16),i=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(i).then((s=>{const i=new Uint8Array(s);n.set(i,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,r)}))}decryptAacSamples(e,t,r){for(;;t++){if(t>=e.length)return void r();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,r),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t);let n=0;for(let t=32;t<e.length-16;t+=160,n+=16)r.set(e.subarray(t,t+16),n);return r}getAvcDecryptedUnit(e,t){const r=new Uint8Array(t);let n=0;for(let t=32;t<e.length-16;t+=160,n+=16)e.set(r.subarray(n,n+16),t);return e}decryptAvcSample(e,t,r,n,s){const i=og(s.data),a=this.getAvcEncryptedData(i);this.decryptBuffer(a.buffer).then((a=>{s.data=this.getAvcDecryptedUnit(i,a),this.decrypter.isSync()||this.decryptAvcSamples(e,t,r+1,n)}))}decryptAvcSamples(e,t,r,n){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,r=0){if(t>=e.length)return void n();const s=e[t].units;for(;!(r>=s.length);r++){const i=s[r];if(!(i.data.length<=48||1!==i.type&&5!==i.type||(this.decryptAvcSample(e,t,r,n,i),this.decrypter.isSync())))return}}}}const Vy=188;class zy{constructor(e,t,r){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._avcTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.observer=e,this.config=t,this.typeSupported=r}static probe(e){const t=zy.syncOffset(e);return t>0&&Zf.warn(`MPEG2-TS detected but first sync word found @ offset ${t}`),-1!==t}static syncOffset(e){const t=e.length;let r=Math.min(940,e.length-Vy)+1,n=0;for(;n<r;){let s=!1,i=-1,a=0;for(let o=n;o<t;o+=Vy){if(71!==e[o]){if(a)return-1;break}if(a++,-1===i&&(i=o,0!==i&&(r=Math.min(i+18612,e.length-Vy)+1)),s||(s=0===Yy(e,o)),s&&a>1&&(0===i&&a>2||o+Vy>r))return i}n++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:Vp[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(e,t,r,n){this.pmtParsed=!1,this._pmtId=-1,this._avcTrack=zy.createTrack("video"),this._audioTrack=zy.createTrack("audio",n),this._id3Track=zy.createTrack("id3"),this._txtTrack=zy.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=r,this._duration=n}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_avcTrack:t,_id3Track:r}=this;e&&(e.pesData=null),t&&(t.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.avcSample=null,this.remainderData=null}demux(e,t,r=!1,n=!1){let s;r||(this.sampleAes=null);const i=this._avcTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let c=i.pid,d=i.pesData,u=a.pid,h=o.pid,f=a.pesData,p=o.pesData,g=null,m=this.pmtParsed,y=this._pmtId,v=e.length;if(this.remainderData&&(v=(e=ng(this.remainderData,e)).length,this.remainderData=null),v<Vy&&!n)return this.remainderData=e,{audioTrack:a,videoTrack:i,id3Track:o,textTrack:l};const b=Math.max(0,zy.syncOffset(e));v-=(v-b)%Vy,v<e.byteLength&&!n&&(this.remainderData=new Uint8Array(e.buffer,v,e.buffer.byteLength-v));let w=0;for(let t=b;t<v;t+=Vy)if(71===e[t]){const n=!!(64&e[t+1]),v=Yy(e,t);let w;if((48&e[t+3])>>4>1){if(w=t+5+e[t+4],w===t+Vy)continue}else w=t+4;switch(v){case c:n&&(d&&(s=Jy(d))&&this.parseAVCPES(i,l,s,!1),d={data:[],size:0}),d&&(d.data.push(e.subarray(w,t+Vy)),d.size+=t+Vy-w);break;case u:if(n){if(f&&(s=Jy(f)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,s);break;case"mp3":this.parseMPEGPES(a,s)}f={data:[],size:0}}f&&(f.data.push(e.subarray(w,t+Vy)),f.size+=t+Vy-w);break;case h:n&&(p&&(s=Jy(p))&&this.parseID3PES(o,s),p={data:[],size:0}),p&&(p.data.push(e.subarray(w,t+Vy)),p.size+=t+Vy-w);break;case 0:n&&(w+=e[w]+1),y=this._pmtId=Qy(e,w);break;case y:{n&&(w+=e[w]+1);const s=Xy(e,w,this.typeSupported,r);c=s.avc,c>0&&(i.pid=c),u=s.audio,u>0&&(a.pid=u,a.segmentCodec=s.segmentCodec),h=s.id3,h>0&&(o.pid=h),null===g||m||(Zf.warn(`MPEG-TS PMT found at ${t} after unknown PID '${g}'. Backtracking to sync byte @${b} to parse all TS packets.`),g=null,t=b-188),m=this.pmtParsed=!0;break}case 17:case 8191:break;default:g=v}}else w++;if(w>0){const e=new Error(`Found ${w} TS packet/s that do not start with 0x47`);this.observer.emit(Vf.ERROR,Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message})}i.pesData=d,a.pesData=f,o.pesData=p;const E={audioTrack:a,videoTrack:i,id3Track:o,textTrack:l};return n&&this.extractRemainingSamples(E),E}flush(){const{remainderData:e}=this;let t;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._avcTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:r,id3Track:n,textTrack:s}=e,i=r.pesData,a=t.pesData,o=n.pesData;let l;if(i&&(l=Jy(i))?(this.parseAVCPES(r,s,l,!0),r.pesData=null):r.pesData=i,a&&(l=Jy(a))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l)}t.pesData=null}else null!=a&&a.size&&Zf.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;o&&(l=Jy(o))?(this.parseID3PES(n,l),n.pesData=null):n.pesData=o}demuxSampleAes(e,t,r){const n=this.demux(e,r,!0,!this.config.progressive),s=this.sampleAes=new Hy(this.observer,this.config,t);return this.decrypt(n,s)}decrypt(e,t){return new Promise((r=>{const{audioTrack:n,videoTrack:s}=e;n.samples&&"aac"===n.segmentCodec?t.decryptAacSamples(n.samples,0,(()=>{s.samples?t.decryptAvcSamples(s.samples,0,0,(()=>{r(e)})):r(e)})):s.samples&&t.decryptAvcSamples(s.samples,0,0,(()=>{r(e)}))}))}destroy(){this._duration=0}parseAVCPES(e,t,r,n){const s=this.parseAVCNALu(e,r.data);let i,a=this.avcSample,o=!1;r.data=null,a&&s.length&&!e.audFound&&(Zy(a,e),a=this.avcSample=Wy(!1,r.pts,r.dts,"")),s.forEach((n=>{var s;switch(n.type){case 1:{let t=!1;i=!0;const s=n.data;if(o&&s.length>4){const e=new Gy(s).readSliceType();2!==e&&4!==e&&7!==e&&9!==e||(t=!0)}var l;if(t)null!=(l=a)&&l.frame&&!a.key&&(Zy(a,e),a=this.avcSample=null);a||(a=this.avcSample=Wy(!0,r.pts,r.dts,"")),a.frame=!0,a.key=t;break}case 5:i=!0,null!=(s=a)&&s.frame&&!a.key&&(Zy(a,e),a=this.avcSample=null),a||(a=this.avcSample=Wy(!0,r.pts,r.dts,"")),a.key=!0,a.frame=!0;break;case 6:i=!0,ag(n.data,1,r.pts,t.samples);break;case 7:if(i=!0,o=!0,!e.sps){const t=n.data,r=new Gy(t).readSPS();e.width=r.width,e.height=r.height,e.pixelRatio=r.pixelRatio,e.sps=[t],e.duration=this._duration;const s=t.subarray(1,4);let i="avc1.";for(let e=0;e<3;e++){let t=s[e].toString(16);t.length<2&&(t="0"+t),i+=t}e.codec=i}break;case 8:i=!0,e.pps||(e.pps=[n.data]);break;case 9:i=!1,e.audFound=!0,a&&Zy(a,e),a=this.avcSample=Wy(!1,r.pts,r.dts,"");break;case 12:i=!0;break;default:i=!1,a&&(a.debug+="unknown NAL "+n.type+" ")}if(a&&i){a.units.push(n)}})),n&&a&&(Zy(a,e),this.avcSample=null)}getLastNalUnit(e){var t;let r,n=this.avcSample;if(n&&0!==n.units.length||(n=e[e.length-1]),null!=(t=n)&&t.units){const e=n.units;r=e[e.length-1]}return r}parseAVCNALu(e,t){const r=t.byteLength;let n=e.naluState||0;const s=n,i=[];let a,o,l,c=0,d=-1,u=0;for(-1===n&&(d=0,u=31&t[0],n=0,c=1);c<r;)if(a=t[c++],n)if(1!==n)if(a)if(1===a){if(d>=0){const e={data:t.subarray(d,c-n-1),type:u};i.push(e)}else{const r=this.getLastNalUnit(e.samples);if(r&&(s&&c<=4-s&&r.state&&(r.data=r.data.subarray(0,r.data.byteLength-s)),o=c-n-1,o>0)){const e=new Uint8Array(r.data.byteLength+o);e.set(r.data,0),e.set(t.subarray(0,o),r.data.byteLength),r.data=e,r.state=0}}c<r?(l=31&t[c],d=c,u=l,n=0):n=-1}else n=0;else n=3;else n=a?0:2;else n=a?0:1;if(d>=0&&n>=0){const e={data:t.subarray(d,r),type:u,state:n};i.push(e)}if(0===i.length){const r=this.getLastNalUnit(e.samples);if(r){const e=new Uint8Array(r.data.byteLength+t.byteLength);e.set(r.data,0),e.set(t,r.data.byteLength),r.data=e}}return e.naluState=n,i}parseAACPES(e,t){let r=0;const n=this.aacOverFlow;let s,i,a,o=t.data;if(n){this.aacOverFlow=null;const t=n.missing,s=n.sample.unit.byteLength;if(-1===t){const e=new Uint8Array(s+o.byteLength);e.set(n.sample.unit,0),e.set(o,s),o=e}else{const i=s-t;n.sample.unit.set(o.subarray(0,t),i),e.samples.push(n.sample),r=n.missing}}for(s=r,i=o.length;s<i-1&&!_y(o,s);s++);if(s!==r){let e;const t=s<i-1;e=t?`AAC PES did not start with ADTS header,offset:${s}`:"No ADTS header found in AAC PES";const r=new Error(e);if(Zf.warn(`parsing error: ${e}`),this.observer.emit(Vf.ERROR,Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:r,reason:e}),!t)return}if(Ly(e,this.observer,o,s,this.audioCodec),void 0!==t.pts)a=t.pts;else{if(!n)return void Zf.warn("[tsdemuxer]: AAC PES unknown PTS");{const t=Dy(e.samplerate);a=n.sample.pts+t}}let l,c=0;for(;s<i;){if(l=xy(e,o,s,a,c),s+=l.length,l.missing){this.aacOverFlow=l;break}for(c++;s<i-1&&!_y(o,s);s++);}}parseMPEGPES(e,t){const r=t.data,n=r.length;let s=0,i=0;const a=t.pts;if(void 0!==a)for(;i<n;)if(qy(r,i)){const t=By(e,r,i,a,s);if(!t)break;i+=t.length,s++}else i++;else Zf.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseID3PES(e,t){if(void 0===t.pts)return void Zf.warn("[tsdemuxer]: ID3 PES unknown PTS");const r=Gf({},t,{type:this._avcTrack?Qg:Wg,duration:Number.POSITIVE_INFINITY});e.samples.push(r)}}function Wy(e,t,r,n){return{key:e,frame:!1,pts:t,dts:r,units:[],debug:n,length:0}}function Yy(e,t){return((31&e[t+1])<<8)+e[t+2]}function Qy(e,t){return(31&e[t+10])<<8|e[t+11]}function Xy(e,t,r,n){const s={audio:-1,avc:-1,id3:-1,segmentCodec:"aac"},i=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<i;){const i=Yy(e,t);switch(e[t]){case 207:if(!n){Zf.log("ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream");break}case 15:-1===s.audio&&(s.audio=i);break;case 21:-1===s.id3&&(s.id3=i);break;case 219:if(!n){Zf.log("H.264 with AES-128-CBC slice encryption found in unencrypted stream");break}case 27:-1===s.avc&&(s.avc=i);break;case 3:case 4:!0!==r.mpeg&&!0!==r.mp3?Zf.log("MPEG audio found, not supported in this browser"):-1===s.audio&&(s.audio=i,s.segmentCodec="mp3");break;case 36:Zf.warn("Unsupported HEVC stream type found")}t+=5+((15&e[t+3])<<8|e[t+4])}return s}function Jy(e){let t,r,n,s,i,a=0;const o=e.data;if(!e||0===e.size)return null;for(;o[0].length<19&&o.length>1;){const e=new Uint8Array(o[0].length+o[1].length);e.set(o[0]),e.set(o[1],o[0].length),o[0]=e,o.splice(1,1)}t=o[0];if(1===(t[0]<<16)+(t[1]<<8)+t[2]){if(r=(t[4]<<8)+t[5],r&&r>e.size-6)return null;const l=t[7];192&l&&(s=536870912*(14&t[9])+4194304*(255&t[10])+16384*(254&t[11])+128*(255&t[12])+(254&t[13])/2,64&l?(i=536870912*(14&t[14])+4194304*(255&t[15])+16384*(254&t[16])+128*(255&t[17])+(254&t[18])/2,s-i>54e5&&(Zf.warn(`${Math.round((s-i)/9e4)}s delta between PTS and DTS, align them`),s=i)):i=s),n=t[8];let c=n+9;if(e.size<=c)return null;e.size-=c;const d=new Uint8Array(e.size);for(let e=0,r=o.length;e<r;e++){t=o[e];let r=t.byteLength;if(c){if(c>r){c-=r;continue}t=t.subarray(c),r-=c,c=0}d.set(t,a),a+=r}return r&&(r-=n+3),{data:d,pts:s,dts:i,len:r}}return null}function Zy(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){const r=t.samples,n=r.length;if(!n)return void t.dropped++;{const t=r[n-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}e.debug.length&&Zf.log(e.pts+"/"+e.dts+":"+e.debug)}class ev{static getSilentFrame(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}const tv=Math.pow(2,32)-1;class rv{static init(){let e;for(e in rv.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},rv.types)rv.types.hasOwnProperty(e)&&(rv.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),r=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);rv.HDLR_TYPES={video:t,audio:r};const n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),s=new Uint8Array([0,0,0,0,0,0,0,0]);rv.STTS=rv.STSC=rv.STCO=s,rv.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),rv.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),rv.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),rv.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const i=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);rv.FTYP=rv.box(rv.types.ftyp,i,o,i,a),rv.DINF=rv.box(rv.types.dinf,rv.box(rv.types.dref,n))}static box(e,...t){let r=8,n=t.length;const s=n;for(;n--;)r+=t[n].byteLength;const i=new Uint8Array(r);for(i[0]=r>>24&255,i[1]=r>>16&255,i[2]=r>>8&255,i[3]=255&r,i.set(e,4),n=0,r=8;n<s;n++)i.set(t[n],r),r+=t[n].byteLength;return i}static hdlr(e){return rv.box(rv.types.hdlr,rv.HDLR_TYPES[e])}static mdat(e){return rv.box(rv.types.mdat,e)}static mdhd(e,t){t*=e;const r=Math.floor(t/(tv+1)),n=Math.floor(t%(tv+1));return rv.box(rv.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,r>>24,r>>16&255,r>>8&255,255&r,n>>24,n>>16&255,n>>8&255,255&n,85,196,0,0]))}static mdia(e){return rv.box(rv.types.mdia,rv.mdhd(e.timescale,e.duration),rv.hdlr(e.type),rv.minf(e))}static mfhd(e){return rv.box(rv.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?rv.box(rv.types.minf,rv.box(rv.types.smhd,rv.SMHD),rv.DINF,rv.stbl(e)):rv.box(rv.types.minf,rv.box(rv.types.vmhd,rv.VMHD),rv.DINF,rv.stbl(e))}static moof(e,t,r){return rv.box(rv.types.moof,rv.mfhd(e),rv.traf(r,t))}static moov(e){let t=e.length;const r=[];for(;t--;)r[t]=rv.trak(e[t]);return rv.box.apply(null,[rv.types.moov,rv.mvhd(e[0].timescale,e[0].duration)].concat(r).concat(rv.mvex(e)))}static mvex(e){let t=e.length;const r=[];for(;t--;)r[t]=rv.trex(e[t]);return rv.box.apply(null,[rv.types.mvex,...r])}static mvhd(e,t){t*=e;const r=Math.floor(t/(tv+1)),n=Math.floor(t%(tv+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,r>>24,r>>16&255,r>>8&255,255&r,n>>24,n>>16&255,n>>8&255,255&n,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return rv.box(rv.types.mvhd,s)}static sdtp(e){const t=e.samples||[],r=new Uint8Array(4+t.length);let n,s;for(n=0;n<t.length;n++)s=t[n].flags,r[n+4]=s.dependsOn<<4|s.isDependedOn<<2|s.hasRedundancy;return rv.box(rv.types.sdtp,r)}static stbl(e){return rv.box(rv.types.stbl,rv.stsd(e),rv.box(rv.types.stts,rv.STTS),rv.box(rv.types.stsc,rv.STSC),rv.box(rv.types.stsz,rv.STSZ),rv.box(rv.types.stco,rv.STCO))}static avc1(e){let t,r,n,s=[],i=[];for(t=0;t<e.sps.length;t++)r=e.sps[t],n=r.byteLength,s.push(n>>>8&255),s.push(255&n),s=s.concat(Array.prototype.slice.call(r));for(t=0;t<e.pps.length;t++)r=e.pps[t],n=r.byteLength,i.push(n>>>8&255),i.push(255&n),i=i.concat(Array.prototype.slice.call(r));const a=rv.box(rv.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|e.sps.length].concat(s).concat([e.pps.length]).concat(i))),o=e.width,l=e.height,c=e.pixelRatio[0],d=e.pixelRatio[1];return rv.box(rv.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,o>>8&255,255&o,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,rv.box(rv.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),rv.box(rv.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,255&c,d>>24,d>>16&255,d>>8&255,255&d])))}static esds(e){const t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))}static mp4a(e){const t=e.samplerate;return rv.box(rv.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,255&t,0,0]),rv.box(rv.types.esds,rv.esds(e)))}static mp3(e){const t=e.samplerate;return rv.box(rv.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,255&t,0,0]))}static stsd(e){return"audio"===e.type?"mp3"===e.segmentCodec&&"mp3"===e.codec?rv.box(rv.types.stsd,rv.STSD,rv.mp3(e)):rv.box(rv.types.stsd,rv.STSD,rv.mp4a(e)):rv.box(rv.types.stsd,rv.STSD,rv.avc1(e))}static tkhd(e){const t=e.id,r=e.duration*e.timescale,n=e.width,s=e.height,i=Math.floor(r/(tv+1)),a=Math.floor(r%(tv+1));return rv.box(rv.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i,a>>24,a>>16&255,a>>8&255,255&a,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,n>>8&255,255&n,0,0,s>>8&255,255&s,0,0]))}static traf(e,t){const r=rv.sdtp(e),n=e.id,s=Math.floor(t/(tv+1)),i=Math.floor(t%(tv+1));return rv.box(rv.types.traf,rv.box(rv.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),rv.box(rv.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,i>>24,i>>16&255,i>>8&255,255&i])),rv.trun(e,r.length+16+20+8+16+8+8),r)}static trak(e){return e.duration=e.duration||4294967295,rv.box(rv.types.trak,rv.tkhd(e),rv.mdia(e))}static trex(e){const t=e.id;return rv.box(rv.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const r=e.samples||[],n=r.length,s=12+16*n,i=new Uint8Array(s);let a,o,l,c,d,u;for(t+=8+s,i.set(["video"===e.type?1:0,0,15,1,n>>>24&255,n>>>16&255,n>>>8&255,255&n,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),a=0;a<n;a++)o=r[a],l=o.duration,c=o.size,d=o.flags,u=o.cts,i.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,c>>>24&255,c>>>16&255,c>>>8&255,255&c,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,61440&d.degradPrio,15&d.degradPrio,u>>>24&255,u>>>16&255,u>>>8&255,255&u],12+16*a);return rv.box(rv.types.trun,i)}static initSegment(e){rv.types||rv.init();const t=rv.moov(e),r=new Uint8Array(rv.FTYP.byteLength+t.byteLength);return r.set(rv.FTYP),r.set(t,rv.FTYP.byteLength),r}}rv.types=void 0,rv.HDLR_TYPES=void 0,rv.STTS=void 0,rv.STSC=void 0,rv.STCO=void 0,rv.STSZ=void 0,rv.VMHD=void 0,rv.SMHD=void 0,rv.STSD=void 0,rv.FTYP=void 0,rv.DINF=void 0;function nv(e,t,r=1,n=!1){const s=e*t*r;return n?Math.round(s):s}function sv(e,t=!1){return nv(e,1e3,1/9e4,t)}let iv,av=null,ov=null;class lv{constructor(e,t,r,n=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.observer=e,this.config=t,this.typeSupported=r,this.ISGenerated=!1,null===av){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);av=e?parseInt(e[1]):0}if(null===ov){const e=navigator.userAgent.match(/Safari\/(\d+)/i);ov=e?parseInt(e[1]):0}}destroy(){}resetTimeStamp(e){Zf.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){Zf.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){Zf.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1}getVideoStartPts(e){let t=!1;const r=e.reduce(((e,r)=>{const n=r.pts-e;return n<-4294967296?(t=!0,cv(e,r.pts)):n>0?e:r.pts}),e[0].pts);return t&&Zf.debug("PTS rollover detected"),r}remux(e,t,r,n,s,i,a,o){let l,c,d,u,h,f,p=s,g=s;const m=e.pid>-1,y=t.pid>-1,v=t.samples.length,b=e.samples.length>0,w=a&&v>0||v>1;if((!m||b)&&(!y||w)||this.ISGenerated||a){this.ISGenerated||(d=this.generateIS(e,t,s,i));const r=this.isVideoContiguous;let n,a=-1;if(w&&(a=function(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!r&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){Zf.warn(`[mp4-remuxer]: Dropped ${a} out of ${v} video samples due to a missing keyframe`);const e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(a),t.dropped+=a,g+=(t.samples[0].pts-e)/t.inputTimeScale,n=g}else-1===a&&(Zf.warn(`[mp4-remuxer]: No keyframe found out of ${v} video samples`),f=!1);if(this.ISGenerated){if(b&&w){const r=this.getVideoStartPts(t.samples),n=(cv(e.samples[0].pts,r)-r)/t.inputTimeScale;p+=Math.max(0,n),g+=Math.max(0,-n)}if(b){if(e.samplerate||(Zf.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(e,t,s,i)),c=this.remuxAudio(e,p,this.isAudioContiguous,i,y||w||o===Bg?g:void 0),w){const n=c?c.endPTS-c.startPTS:0;t.inputTimeScale||(Zf.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(e,t,s,i)),l=this.remuxVideo(t,g,r,n)}}else w&&(l=this.remuxVideo(t,g,r,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=n)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(h=dv(r,s,this._initPTS,this._initDTS)),n.samples.length&&(u=uv(n,s,this._initPTS))),{audio:c,video:l,initSegment:d,independent:f,text:u,id3:h}}generateIS(e,t,r,n){const s=e.samples,i=t.samples,a=this.typeSupported,o={},l=this._initPTS;let c,d,u,h=!l||n,f="audio/mp4";if(h&&(c=d=1/0),e.config&&s.length){if(e.timescale=e.samplerate,"mp3"===e.segmentCodec)a.mpeg?(f="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");o.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&a.mpeg?new Uint8Array(0):rv.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(u=e.inputTimeScale,l&&u===l.timescale?h=!1:c=d=s[0].pts-Math.round(u*r))}if(t.sps&&t.pps&&i.length&&(t.timescale=t.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:rv.initSegment([t]),metadata:{width:t.width,height:t.height}},h))if(u=t.inputTimeScale,l&&u===l.timescale)h=!1;else{const e=this.getVideoStartPts(i),t=Math.round(u*r);d=Math.min(d,cv(i[0].dts,e)-t),c=Math.min(c,e-t)}if(Object.keys(o).length)return this.ISGenerated=!0,h?(this._initPTS={baseTime:c,timescale:u},this._initDTS={baseTime:d,timescale:u}):c=u=void 0,{tracks:o,initPTS:c,timescale:u}}remuxVideo(e,t,r,n){const s=e.inputTimeScale,i=e.samples,a=[],o=i.length,l=this._initPTS;let c,d,u=this.nextAvcDts,h=8,f=this.videoSampleDuration,p=Number.POSITIVE_INFINITY,g=Number.NEGATIVE_INFINITY,m=!1;if(!r||null===u){u=t*s-(i[0].pts-cv(i[0].dts,i[0].pts))}const y=l.baseTime*s/l.timescale;for(let e=0;e<o;e++){const t=i[e];t.pts=cv(t.pts-y,u),t.dts=cv(t.dts-y,u),t.dts<i[e>0?e-1:e].dts&&(m=!0)}m&&i.sort((function(e,t){const r=e.dts-t.dts,n=e.pts-t.pts;return r||n})),c=i[0].dts,d=i[i.length-1].dts;const v=d-c,b=v?Math.round(v/(o-1)):f||e.inputTimeScale/30;if(r){const e=c-u,t=e>b,r=e<-1;if((t||r)&&(t?Zf.warn(`AVC: ${sv(e,!0)} ms (${e}dts) hole between fragments detected, filling it`):Zf.warn(`AVC: ${sv(-e,!0)} ms (${e}dts) overlapping between fragments detected`),!r||u>=i[0].pts)){c=u;const t=i[0].pts-e;i[0].dts=c,i[0].pts=t,Zf.log(`Video: First PTS/DTS adjusted: ${sv(t,!0)}/${sv(c,!0)}, delta: ${sv(e,!0)} ms`)}}c=Math.max(0,c);let w=0,E=0;for(let e=0;e<o;e++){const t=i[e],r=t.units,n=r.length;let s=0;for(let e=0;e<n;e++)s+=r[e].data.length;E+=s,w+=n,t.length=s,t.dts=Math.max(t.dts,c),p=Math.min(t.pts,p),g=Math.max(t.pts,g)}d=i[o-1].dts;const S=E+4*w+8;let T;try{T=new Uint8Array(S)}catch(e){return void this.observer.emit(Vf.ERROR,Vf.ERROR,{type:zf.MUX_ERROR,details:Wf.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:S,reason:`fail allocating video mdat ${S}`})}const C=new DataView(T.buffer);C.setUint32(0,S),T.set(rv.types.mdat,4);let k=!1,A=Number.POSITIVE_INFINITY,I=Number.POSITIVE_INFINITY,_=Number.NEGATIVE_INFINITY,R=Number.NEGATIVE_INFINITY;for(let e=0;e<o;e++){const t=i[e],r=t.units;let l,c=0;for(let e=0,t=r.length;e<t;e++){const t=r[e],n=t.data,s=t.data.byteLength;C.setUint32(h,s),h+=4,T.set(n,h),h+=s,c+=4+s}if(e<o-1)f=i[e+1].dts-t.dts,l=i[e+1].pts-t.pts;else{const r=this.config,a=e>0?t.dts-i[e-1].dts:b;if(l=e>0?t.pts-i[e-1].pts:b,r.stretchShortVideoTrack&&null!==this.nextAudioPts){const e=Math.floor(r.maxBufferHole*s),i=(n?p+n*s:this.nextAudioPts)-t.pts;i>e?(f=i-a,f<0?f=a:k=!0,Zf.log(`[mp4-remuxer]: It is approximately ${i/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=a}else f=a}const d=Math.round(t.pts-t.dts);A=Math.min(A,f),_=Math.max(_,f),I=Math.min(I,l),R=Math.max(R,l),a.push(new hv(t.key,f,c,d))}if(a.length)if(av){if(av<70){const e=a[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(ov&&R-I<_-A&&b/_<.025&&0===a[0].cts){Zf.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let e=c;for(let t=0,r=a.length;t<r;t++){const n=e+a[t].duration,s=e+a[t].cts;if(t<r-1){const e=n+a[t+1].cts;a[t].duration=e-s}else a[t].duration=t?a[t-1].duration:b;a[t].cts=0,e=n}}f=k||!f?b:f,this.nextAvcDts=u=d+f,this.videoSampleDuration=f,this.isVideoContiguous=!0;const L={data1:rv.moof(e.sequenceNumber++,c,Gf({},e,{samples:a})),data2:T,startPTS:p/s,endPTS:(g+f)/s,startDTS:c/s,endDTS:u/s,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,L}remuxAudio(e,t,r,n,s){const i=e.inputTimeScale,a=i/(e.samplerate?e.samplerate:i),o="aac"===e.segmentCodec?1024:1152,l=o*a,c=this._initPTS,d="mp3"===e.segmentCodec&&this.typeSupported.mpeg,u=[],h=void 0!==s;let f=e.samples,p=d?0:8,g=this.nextAudioPts||-1;const m=t*i,y=c.baseTime*i/c.timescale;if(this.isAudioContiguous=r=r||f.length&&g>0&&(n&&Math.abs(m-g)<9e3||Math.abs(cv(f[0].pts-y,m)-g)<20*l),f.forEach((function(e){e.pts=cv(e.pts-y,m)})),!r||g<0){if(f=f.filter((e=>e.pts>=0)),!f.length)return;g=0===s?0:n&&!h?Math.max(0,m):f[0].pts}if("aac"===e.segmentCodec){const t=this.config.maxAudioFramesDrift;for(let r=0,n=g;r<f.length;r++){const s=f[r],a=s.pts,o=a-n,c=Math.abs(1e3*o/i);if(o<=-t*l&&h)0===r&&(Zf.warn(`Audio frame @ ${(a/i).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*o/i)} ms.`),this.nextAudioPts=g=n=a);else if(o>=t*l&&c<1e4&&h){let t=Math.round(o/l);n=a-t*l,n<0&&(t--,n+=l),0===r&&(this.nextAudioPts=g=n),Zf.warn(`[mp4-remuxer]: Injecting ${t} audio frame @ ${(n/i).toFixed(3)}s due to ${Math.round(1e3*o/i)} ms gap.`);for(let i=0;i<t;i++){const t=Math.max(n,0);let i=ev.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);i||(Zf.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),i=s.unit.subarray()),f.splice(r,0,{unit:i,pts:t}),n+=l,r++}}s.pts=n,n+=l}}let v,b=null,w=null,E=0,S=f.length;for(;S--;)E+=f[S].unit.byteLength;for(let t=0,n=f.length;t<n;t++){const n=f[t],s=n.unit;let i=n.pts;if(null!==w){u[t-1].duration=Math.round((i-w)/a)}else{if(r&&"aac"===e.segmentCodec&&(i=g),b=i,!(E>0))return;E+=p;try{v=new Uint8Array(E)}catch(e){return void this.observer.emit(Vf.ERROR,Vf.ERROR,{type:zf.MUX_ERROR,details:Wf.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:E,reason:`fail allocating audio mdat ${E}`})}if(!d){new DataView(v.buffer).setUint32(0,E),v.set(rv.types.mdat,4)}}v.set(s,p);const l=s.byteLength;p+=l,u.push(new hv(!0,o,l,0)),w=i}const T=u.length;if(!T)return;const C=u[u.length-1];this.nextAudioPts=g=w+a*C.duration;const k=d?new Uint8Array(0):rv.moof(e.sequenceNumber++,b/a,Gf({},e,{samples:u}));e.samples=[];const A=b/i,I=g/i,_={data1:k,data2:v,startPTS:A,endPTS:I,startDTS:A,endDTS:I,type:"audio",hasAudio:!0,hasVideo:!1,nb:T};return this.isAudioContiguous=!0,_}remuxEmptyAudio(e,t,r,n){const s=e.inputTimeScale,i=s/(e.samplerate?e.samplerate:s),a=this.nextAudioPts,o=this._initDTS,l=9e4*o.baseTime/o.timescale,c=(null!==a?a:n.startDTS*s)+l,d=n.endDTS*s+l,u=1024*i,h=Math.ceil((d-c)/u),f=ev.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(Zf.warn("[mp4-remuxer]: remux empty Audio"),!f)return void Zf.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");const p=[];for(let e=0;e<h;e++){const t=c+e*u;p.push({unit:f,pts:t,dts:t})}return e.samples=p,this.remuxAudio(e,t,r,!1)}}function cv(e,t){let r;if(null===t)return e;for(r=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=r;return e}function dv(e,t,r,n){const s=e.samples.length;if(!s)return;const i=e.inputTimeScale;for(let a=0;a<s;a++){const s=e.samples[a];s.pts=cv(s.pts-r.baseTime*i/r.timescale,t*i)/i,s.dts=cv(s.dts-n.baseTime*i/n.timescale,t*i)/i}const a=e.samples;return e.samples=[],{samples:a}}function uv(e,t,r){const n=e.samples.length;if(!n)return;const s=e.inputTimeScale;for(let i=0;i<n;i++){const n=e.samples[i];n.pts=cv(n.pts-r.baseTime*s/r.timescale,t*s)/s}e.samples.sort(((e,t)=>e.pts-t.pts));const i=e.samples;return e.samples=[],{samples:i}}class hv{constructor(e,t,r,n){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=t,this.size=r,this.cts=n,this.flags=new fv(e)}}class fv{constructor(e){this.isLeading=0,this.isDependedOn=0,this.hasRedundancy=0,this.degradPrio=0,this.dependsOn=1,this.isNonSync=1,this.dependsOn=e?2:1,this.isNonSync=e?0:1}}function pv(e,t){const r=null==e?void 0:e.codec;return r&&r.length>4?r:"hvc1"===r||"hev1"===r?"hvc1.1.6.L120.90":"av01"===r?"av01.0.04M.08":"avc1"===r||t===op?"avc1.42e01e":"mp4a.40.5"}try{iv=self.performance.now.bind(self.performance)}catch(e){Zf.debug("Unable to use Performance API on this environment"),iv="undefined"!=typeof self&&self.Date.now}const gv=[{demux:class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,r,n){const s=this.videoTrack=Sy("video",1),i=this.audioTrack=Sy("audio",1),a=this.txtTrack=Sy("text",1);if(this.id3Track=Sy("id3",1),this.timeOffset=0,null==e||!e.byteLength)return;const o=eg(e);if(o.video){const{id:e,timescale:t,codec:r}=o.video;s.id=e,s.timescale=a.timescale=t,s.codec=r}if(o.audio){const{id:e,timescale:t,codec:r}=o.audio;i.id=e,i.timescale=t,i.codec=r}a.id=Vp.text,s.sampleDuration=0,s.duration=i.duration=n}resetContiguity(){this.remainderData=null}static probe(e){return Jp(e=e.length>16384?e.subarray(0,16384):e,["moof"]).length>0}demux(e,t){this.timeOffset=t;let r=e;const n=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=ng(this.remainderData,e));const t=function(e){const t={valid:null,remainder:null},r=Jp(e,["moof"]);if(!r)return t;if(r.length<2)return t.remainder=e,t;const n=r[r.length-1];return t.valid=Ap(e,0,n.byteOffset-8),t.remainder=Ap(e,n.byteOffset-8),t}(r);this.remainderData=t.remainder,n.samples=t.valid||new Uint8Array}else n.samples=r;const i=this.extractID3Track(n,t);return s.samples=sg(t,n),{videoTrack:n,audioTrack:this.audioTrack,id3Track:i,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,r=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const n=this.extractID3Track(t,this.timeOffset);return r.samples=sg(e,t),{videoTrack:t,audioTrack:Sy(),id3Track:n,textTrack:Sy()}}extractID3Track(e,t){const r=this.id3Track;if(e.samples.length){const n=Jp(e.samples,["emsg"]);n&&n.forEach((e=>{const n=function(e){const t=e[0];let r="",n="",s=0,i=0,a=0,o=0,l=0,c=0;if(0===t){for(;"\0"!==zp(e.subarray(c,c+1));)r+=zp(e.subarray(c,c+1)),c+=1;for(r+=zp(e.subarray(c,c+1)),c+=1;"\0"!==zp(e.subarray(c,c+1));)n+=zp(e.subarray(c,c+1)),c+=1;n+=zp(e.subarray(c,c+1)),c+=1,s=Yp(e,12),i=Yp(e,16),o=Yp(e,20),l=Yp(e,24),c=28}else if(1===t){c+=4,s=Yp(e,c),c+=4;const t=Yp(e,c);c+=4;const i=Yp(e,c);for(c+=4,a=2**32*t+i,Number.isSafeInteger(a)||(a=Number.MAX_SAFE_INTEGER,Zf.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Yp(e,c),c+=4,l=Yp(e,c),c+=4;"\0"!==zp(e.subarray(c,c+1));)r+=zp(e.subarray(c,c+1)),c+=1;for(r+=zp(e.subarray(c,c+1)),c+=1;"\0"!==zp(e.subarray(c,c+1));)n+=zp(e.subarray(c,c+1)),c+=1;n+=zp(e.subarray(c,c+1)),c+=1}return{schemeIdUri:r,value:n,timeScale:s,presentationTime:a,presentationTimeDelta:i,eventDuration:o,id:l,payload:e.subarray(c,e.byteLength)}}(e);if(Oy.test(n.schemeIdUri)){const e=Hf(n.presentationTime)?n.presentationTime/n.timeScale:t+n.presentationTimeDelta/n.timeScale;let s=4294967295===n.eventDuration?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);const i=n.payload;r.samples.push({data:i,len:i.byteLength,dts:e,pts:e,type:Qg,duration:s})}}))}return r}demuxSampleAes(e,t,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}},remux:class{constructor(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,r,n){this.audioCodec=t,this.videoCodec=r,this.generateInitSegment(function(e,t){if(!e||!t)return e;const r=t.keyId;r&&t.isCommonEncryption&&Jp(e,["moov","trak"]).forEach((e=>{const t=Jp(e,["mdia","minf","stbl","stsd"])[0].subarray(8);let n=Jp(t,["enca"]);const s=n.length>0;s||(n=Jp(t,["encv"])),n.forEach((e=>{Jp(s?e.subarray(28):e.subarray(78),["sinf"]).forEach((e=>{const t=tg(e);if(t){const e=t.subarray(8,24);e.some((e=>0!==e))||(Zf.log(`[eme] Patching keyId in 'enc${s?"a":"v"}>sinf>>tenc' box: ${Kp(e)} -> ${Kp(r)}`),t.set(r,8))}}))}))}));return e}(e,n)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:r}=this;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const n=this.initData=eg(e);t||(t=pv(n.audio,ap)),r||(r=pv(n.video,op));const s={};n.audio&&n.video?s.audiovideo={container:"video/mp4",codec:t+","+r,initSegment:e,id:"main"}:n.audio?s.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:n.video?s.video={container:"video/mp4",codec:r,initSegment:e,id:"main"}:Zf.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=s}remux(e,t,r,n,s,i){var a,o;let{initPTS:l,lastEndTime:c}=this;const d={audio:void 0,video:void 0,text:n,id3:r,initSegment:void 0};Hf(c)||(c=this.lastEndTime=s||0);const u=t.samples;if(null==u||!u.length)return d;const h={initPTS:void 0,timescale:1};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(u),f=this.initData),null==(o=f)||!o.length)return Zf.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),d;this.emitInitSegment&&(h.tracks=this.initTracks,this.emitInitSegment=!1);const p=function(e,t){let r=0,n=0,s=0;const i=Jp(e,["moof","traf"]);for(let e=0;e<i.length;e++){const a=i[e],o=Jp(a,["tfhd"])[0],l=t[Yp(o,4)];if(!l)continue;const c=l.default,d=Yp(o,0)|(null==c?void 0:c.flags);let u=null==c?void 0:c.duration;8&d&&(u=Yp(o,2&d?12:8));const h=l.timescale||9e4,f=Jp(a,["trun"]);for(let e=0;e<f.length;e++)r=rg(f[e]),!r&&u&&(r=u*Yp(f[e],4)),l.type===op?n+=r/h:l.type===ap&&(s+=r/h)}if(0===n&&0===s){let t=0;const r=Jp(e,["sidx"]);for(let e=0;e<r.length;e++){const n=Zp(r[e]);null!=n&&n.references&&(t+=n.references.reduce(((e,t)=>e+t.info.duration||0),0))}return t}return n||s}(u,f),g=function(e,t){return Jp(t,["moof","traf"]).reduce(((t,r)=>{const n=Jp(r,["tfdt"])[0],s=n[0],i=Jp(r,["tfhd"]).reduce(((t,r)=>{const i=Yp(r,4),a=e[i];if(a){let e=Yp(n,4);if(1===s){if(e===Gp)return Zf.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),t;e*=Gp+1,e+=Yp(n,8)}const r=e/(a.timescale||9e4);if(isFinite(r)&&(null===t||r<t))return r}return t}),null);return null!==i&&isFinite(i)&&(null===t||i<t)?i:t}),null)}(f,u),m=null===g?s:g;(function(e,t,r,n){if(null===e)return!0;const s=Math.max(n,1),i=t-e.baseTime/e.timescale;return Math.abs(i-r)>s}(l,m,s,p)||h.timescale!==l.timescale&&i)&&(h.initPTS=m-s,l&&1===l.timescale&&Zf.warn("Adjusting initPTS by "+(h.initPTS-l.baseTime)),this.initPTS=l={baseTime:h.initPTS,timescale:1});const y=e?m-l.baseTime/l.timescale:c,v=y+p;!function(e,t,r){Jp(t,["moof","traf"]).forEach((t=>{Jp(t,["tfhd"]).forEach((n=>{const s=Yp(n,4),i=e[s];if(!i)return;const a=i.timescale||9e4;Jp(t,["tfdt"]).forEach((e=>{const t=e[0];let n=Yp(e,4);if(0===t)n-=r*a,n=Math.max(n,0),Xp(e,4,n);else{n*=Math.pow(2,32),n+=Yp(e,8),n-=r*a,n=Math.max(n,0);const t=Math.floor(n/(Gp+1)),s=Math.floor(n%(Gp+1));Xp(e,4,t),Xp(e,8,s)}}))}))}))}(f,u,l.baseTime/l.timescale),p>0?this.lastEndTime=v:(Zf.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const b=!!f.audio,w=!!f.video;let E="";b&&(E+="audio"),w&&(E+="video");const S={data1:u,startPTS:y,startDTS:y,endPTS:v,endDTS:v,type:E,hasAudio:b,hasVideo:w,nb:1,dropped:0};return d.audio="audio"===S.type?S:void 0,d.video="audio"!==S.type?S:void 0,d.initSegment=h,d.id3=dv(r,s,l,l),n.samples.length&&(d.text=uv(n,s,l)),d}}},{demux:zy,remux:lv},{demux:class extends Ty{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,r,n){super.resetInitSegment(e,t,r,n),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=(Rp(e,0)||[]).length;for(let r=e.length;t<r;t++)if(Ry(e,t))return Zf.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&ky(e,t)&&Iy(e,t)<=e.length-t}(e,t)}appendFrame(e,t,r){Ly(e,this.observer,t,r,e.manifestCodec);const n=xy(e,t,r,this.basePTS,this.frameIndex);if(n&&0===n.missing)return n}},remux:lv},{demux:class extends Ty{resetInitSegment(e,t,r,n){super.resetInitSegment(e,t,r,n),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=(Rp(e,0)||[]).length;for(let r=e.length;t<r;t++)if(Ky(e,t))return Zf.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return $y(e,t)&&4<=e.length-t}(e,t)}appendFrame(e,t,r){if(null!==this.basePTS)return By(e,t,r,this.basePTS,this.frameIndex)}},remux:lv}];class mv{constructor(e,t,r,n,s){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=r,this.vendor=n,this.id=s}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,r,n){const s=r.transmuxing;s.executeStart=iv();let i=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:o}=this;n&&(this.currentTransmuxState=n);const{contiguous:l,discontinuity:c,trackSwitch:d,accurateTimeOffset:u,timeOffset:h,initSegmentChange:f}=n||a,{audioCodec:p,videoCodec:g,defaultInitPts:m,duration:y,initSegmentData:v}=o,b=function(e,t){let r=null;e.byteLength>0&&null!=t&&null!=t.key&&null!==t.iv&&null!=t.method&&(r=t);return r}(i,t);if(b&&"AES-128"===b.method){const e=this.getDecrypter();if(!e.isSync())return this.decryptionPromise=e.webCryptoDecrypt(i,b.key.buffer,b.iv.buffer).then((e=>{const t=this.push(e,null,r);return this.decryptionPromise=null,t})),this.decryptionPromise;{let t=e.softwareDecrypt(i,b.key.buffer,b.iv.buffer);if(r.part>-1&&(t=e.flush()),!t)return s.executeEnd=iv(),yv(r);i=new Uint8Array(t)}}const w=this.needsProbing(c,d);if(w){const e=this.configureTransmuxer(i);if(e)return Zf.warn(`[transmuxer] ${e.message}`),this.observer.emit(Vf.ERROR,Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),s.executeEnd=iv(),yv(r)}(c||d||f||w)&&this.resetInitSegment(v,p,g,y,t),(c||f||w)&&this.resetInitialTimestamp(m),l||this.resetContiguity();const E=this.transmux(i,b,h,u,r),S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,s.executeEnd=iv(),E}flush(e){const t=e.transmuxing;t.executeStart=iv();const{decrypter:r,currentTransmuxState:n,decryptionPromise:s}=this;if(s)return s.then((()=>this.flush(e)));const i=[],{timeOffset:a}=n;if(r){const t=r.flush();t&&i.push(this.push(t,null,e))}const{demuxer:o,remuxer:l}=this;if(!o||!l)return t.executeEnd=iv(),[yv(e)];const c=o.flush(a);return vv(c)?c.then((t=>(this.flushRemux(i,t,e),i))):(this.flushRemux(i,c,e),i)}flushRemux(e,t,r){const{audioTrack:n,videoTrack:s,id3Track:i,textTrack:a}=t,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;Zf.log(`[transmuxer.ts]: Flushed fragment ${r.sn}${r.part>-1?" p: "+r.part:""} of level ${r.level}`);const c=this.remuxer.remux(n,s,i,a,l,o,!0,this.id);e.push({remuxResult:c,chunkMeta:r}),r.transmuxing.executeEnd=iv()}resetInitialTimestamp(e){const{demuxer:t,remuxer:r}=this;t&&r&&(t.resetTimeStamp(e),r.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,r,n,s){const{demuxer:i,remuxer:a}=this;i&&a&&(i.resetInitSegment(e,t,r,n),a.resetInitSegment(e,t,r,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,r,n,s){let i;return i=t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,r,n,s):this.transmuxUnencrypted(e,r,n,s),i}transmuxUnencrypted(e,t,r,n){const{audioTrack:s,videoTrack:i,id3Track:a,textTrack:o}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,i,a,o,t,r,!1,this.id),chunkMeta:n}}transmuxSampleAes(e,t,r,n,s){return this.demuxer.demuxSampleAes(e,t,r).then((e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,r,n,!1,this.id),chunkMeta:s})))}configureTransmuxer(e){const{config:t,observer:r,typeSupported:n,vendor:s}=this;let i;for(let t=0,r=gv.length;t<r;t++)if(gv[t].demux.probe(e)){i=gv[t];break}if(!i)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=i.remux,c=i.demux;o&&o instanceof l||(this.remuxer=new l(r,t,n,s)),a&&a instanceof c||(this.demuxer=new c(r,t,n),this.probe=c.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new ay(this.config)),e}}const yv=e=>({remuxResult:{},chunkMeta:e});function vv(e){return"then"in e&&e.then instanceof Function}class bv{constructor(e,t,r,n,s){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=r,this.duration=n,this.defaultInitPts=s||null}}class wv{constructor(e,t,r,n,s,i){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=r,this.trackSwitch=n,this.timeOffset=s,this.initSegmentChange=i}}var Ev={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}function s(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function i(e,t,n,i,a){if("function"!=typeof n)throw new TypeError("The listener must be a function");var o=new s(n,i||e,a),l=r?r+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function o(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),o.prototype.eventNames=function(){var e,n,s=[];if(0===this._eventsCount)return s;for(n in e=this._events)t.call(e,n)&&s.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},o.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,i=n.length,a=new Array(i);s<i;s++)a[s]=n[s].fn;return a},o.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},o.prototype.emit=function(e,t,n,s,i,a){var o=r?r+e:e;if(!this._events[o])return!1;var l,c,d=this._events[o],u=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),u){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,n),!0;case 4:return d.fn.call(d.context,t,n,s),!0;case 5:return d.fn.call(d.context,t,n,s,i),!0;case 6:return d.fn.call(d.context,t,n,s,i,a),!0}for(c=1,l=new Array(u-1);c<u;c++)l[c-1]=arguments[c];d.fn.apply(d.context,l)}else{var h,f=d.length;for(c=0;c<f;c++)switch(d[c].once&&this.removeListener(e,d[c].fn,void 0,!0),u){case 1:d[c].fn.call(d[c].context);break;case 2:d[c].fn.call(d[c].context,t);break;case 3:d[c].fn.call(d[c].context,t,n);break;case 4:d[c].fn.call(d[c].context,t,n,s);break;default:if(!l)for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];d[c].fn.apply(d[c].context,l)}}return!0},o.prototype.on=function(e,t,r){return i(this,e,t,r,!1)},o.prototype.once=function(e,t,r){return i(this,e,t,r,!0)},o.prototype.removeListener=function(e,t,n,s){var i=r?r+e:e;if(!this._events[i])return this;if(!t)return a(this,i),this;var o=this._events[i];if(o.fn)o.fn!==t||s&&!o.once||n&&o.context!==n||a(this,i);else{for(var l=0,c=[],d=o.length;l<d;l++)(o[l].fn!==t||s&&!o[l].once||n&&o[l].context!==n)&&c.push(o[l]);c.length?this._events[i]=1===c.length?c[0]:c:a(this,i)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&a(this,t)):(this._events=new n,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=r,o.EventEmitter=o,e.exports=o}(Ev);var Sv=Nf(Ev.exports);const Tv=yg()||{isTypeSupported:()=>!1};class Cv{constructor(e,t,r,n){this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;const s=e.config;this.hls=e,this.id=t,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=r,this.onFlush=n;const i=(e,t)=>{(t=t||{}).frag=this.frag,t.id=this.id,e===Vf.ERROR&&(this.error=t.error),this.hls.trigger(e,t)};this.observer=new Sv,this.observer.on(Vf.FRAG_DECRYPTED,i),this.observer.on(Vf.ERROR,i);const a={mp4:Tv.isTypeSupported("video/mp4"),mpeg:Tv.isTypeSupported("audio/mpeg"),mp3:Tv.isTypeSupported('audio/mp4; codecs="mp3"')},o=navigator.vendor;if(this.useWorker&&"undefined"!=typeof Worker){if(s.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{s.workerPath?(Zf.log(`loading Web Worker ${s.workerPath} for "${t}"`),this.workerContext=function(e){const t=new self.URL(e,self.location.href).href;return{worker:new self.Worker(t),scriptURL:t}}(s.workerPath)):(Zf.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e);return{worker:new self.Worker(t),objectURL:t}}()),this.onwmsg=e=>this.onWorkerMessage(e);const{worker:e}=this.workerContext;e.addEventListener("message",this.onwmsg),e.onerror=e=>{const r=new Error(`${e.message} (${e.filename}:${e.lineno})`);s.enableWorker=!1,Zf.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(Vf.ERROR,{type:zf.OTHER_ERROR,details:Wf.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:r})},e.postMessage({cmd:"init",typeSupported:a,vendor:o,id:t,config:JSON.stringify(s)})}catch(e){Zf.warn(`Error setting up "${t}" Web Worker, fallback to inline`,e),this.resetWorker(),this.error=null,this.transmuxer=new mv(this.observer,a,s,o,t)}return}}this.transmuxer=new mv(this.observer,a,s,o,t)}resetWorker(){if(this.workerContext){const{worker:e,objectURL:t}=this.workerContext;t&&self.URL.revokeObjectURL(t),e.removeEventListener("message",this.onwmsg),e.onerror=null,e.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(e,t,r,n,s,i,a,o,l,c){var d,u;l.transmuxing.start=self.performance.now();const{transmuxer:h}=this,f=i?i.start:s.start,p=s.decryptdata,g=this.frag,m=!(g&&s.cc===g.cc),y=!(g&&l.level===g.level),v=g?l.sn-g.sn:-1,b=this.part?l.part-this.part.index:-1,w=0===v&&l.id>1&&l.id===(null==g?void 0:g.stats.chunkCount),E=!y&&(1===v||0===v&&(1===b||w&&b<=0)),S=self.performance.now();(y||v||0===s.stats.parsing.start)&&(s.stats.parsing.start=S),!i||!b&&E||(i.stats.parsing.start=S);const T=!(g&&(null==(d=s.initSegment)?void 0:d.url)===(null==(u=g.initSegment)?void 0:u.url)),C=new wv(m,E,o,y,f,T);if(!E||m||T){Zf.log(`[transmuxer-interface, ${s.type}]: Starting new transmux session for sn: ${l.sn} p: ${l.part} level: ${l.level} id: ${l.id}\n discontinuity: ${m}\n trackSwitch: ${y}\n contiguous: ${E}\n accurateTimeOffset: ${o}\n timeOffset: ${f}\n initSegmentChange: ${T}`);const e=new bv(r,n,t,a,c);this.configureTransmuxer(e)}if(this.frag=s,this.part=i,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:p,chunkMeta:l,state:C},e instanceof ArrayBuffer?[e]:[]);else if(h){const t=h.push(e,p,l,C);vv(t)?(h.async=!0,t.then((e=>{this.handleTransmuxComplete(e)})).catch((e=>{this.transmuxerError(e,l,"transmuxer-interface push error")}))):(h.async=!1,this.handleTransmuxComplete(t))}}flush(e){e.transmuxing.start=self.performance.now();const{transmuxer:t}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(t){let r=t.flush(e);vv(r)||t.async?(vv(r)||(r=Promise.resolve(r)),r.then((t=>{this.handleFlushResult(t,e)})).catch((t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")}))):this.handleFlushResult(r,e)}}transmuxerError(e,t,r){this.hls&&(this.error=e,this.hls.trigger(Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.FRAG_PARSING_ERROR,chunkMeta:t,fatal:!1,error:e,err:e,reason:r}))}handleFlushResult(e,t){e.forEach((e=>{this.handleTransmuxComplete(e)})),this.onFlush(t)}onWorkerMessage(e){const t=e.data,r=this.hls;switch(t.event){case"init":{var n;const e=null==(n=this.workerContext)?void 0:n.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":Zf[t.data.logType]&&Zf[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,r.trigger(t.event,t.data)}}configureTransmuxer(e){const{transmuxer:t}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:e}):t&&t.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}class kv{constructor(e,t,r,n){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=r,this.hls=n}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){const{config:r,media:n,stalled:s}=this;if(null===n)return;const{currentTime:i,seeking:a}=n,o=this.seeking&&!a,l=!this.seeking&&a;if(this.seeking=a,i!==e){if(this.moved=!0,null!==s){if(this.stallReported){const e=self.performance.now()-s;Zf.warn(`playback not stuck anymore @${i}, after ${Math.round(e)}ms`),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}return}if(l||o)return void(this.stalled=null);if(n.paused&&!a||n.ended||0===n.playbackRate||!Qm.getBuffered(n).length)return;const c=Qm.bufferInfo(n,i,0),d=c.len>0,u=c.nextStart||0;if(!d&&!u)return;if(a){const e=c.len>2,r=!u||t&&t.start<=i||u-i>2&&!this.fragmentTracker.getPartialFragment(i);if(e||r)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var h;const e=Math.max(u,c.start||0)-i,t=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,r=(null==t||null==(h=t.details)?void 0:h.live)?2*t.details.targetduration:2,n=this.fragmentTracker.getPartialFragment(i);if(e>0&&(e<=r||n))return void this._trySkipBufferHole(n)}const f=self.performance.now();if(null===s)return void(this.stalled=f);const p=f-s;if(!a&&p>=250&&(this._reportStall(c),!this.media))return;const g=Qm.bufferInfo(n,i,r.maxBufferHole);this._tryFixBufferStall(g,p)}_tryFixBufferStall(e,t){const{config:r,fragmentTracker:n,media:s}=this;if(null===s)return;const i=s.currentTime,a=n.getPartialFragment(i);if(a){if(this._trySkipBufferHole(a)||!this.media)return}(e.len>r.maxBufferHole||e.nextStart&&e.nextStart-i<r.maxBufferHole)&&t>1e3*r.highBufferWatchdogPeriod&&(Zf.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:t,media:r,stallReported:n}=this;if(!n&&r){this.stallReported=!0;const n=new Error(`Playback stalling at @${r.currentTime} due to low buffer (${JSON.stringify(e)})`);Zf.warn(n.message),t.trigger(Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len})}}_trySkipBufferHole(e){const{config:t,hls:r,media:n}=this;if(null===n)return 0;const s=n.currentTime,i=Qm.bufferInfo(n,s,0),a=s<i.start?i.start:i.nextStart;if(a){const o=i.len<=t.maxBufferHole,l=i.len>0&&i.len<1&&n.readyState<3,c=a-s;if(c>0&&(o||l)){if(c>t.maxBufferHole){const{fragmentTracker:t}=this;let r=!1;if(0===s){const e=t.getAppendedFrag(0,Ng);e&&a<e.end&&(r=!0)}if(!r){const r=e||t.getAppendedFrag(s,Ng);if(r){let e=!1,n=r.end;for(;n<a;){const r=t.getPartialFragment(n);if(!r){e=!0;break}n+=r.duration}if(e)return 0}}}const i=Math.max(a+.05,s+.1);if(Zf.warn(`skipping hole, adjusting currentTime from ${s} to ${i}`),this.moved=!0,this.stalled=null,n.currentTime=i,e&&!e.gap){const t=new Error(`fragment loaded with buffer holes, seeking from ${s} to ${i}`);r.trigger(Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:t,reason:t.message,frag:e})}return i}}return 0}_tryNudgeBuffer(){const{config:e,hls:t,media:r,nudgeRetry:n}=this;if(null===r)return;const s=r.currentTime;if(this.nudgeRetry++,n<e.nudgeMaxRetry){const i=s+(n+1)*e.nudgeOffset,a=new Error(`Nudging 'currentTime' from ${s} to ${i}`);Zf.warn(a.message),r.currentTime=i,t.trigger(Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.BUFFER_NUDGE_ON_STALL,error:a,fatal:!1})}else{const r=new Error(`Playhead still not moving while enough data buffered @${s} after ${e.nudgeMaxRetry} nudges`);Zf.error(r.message),t.trigger(Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.BUFFER_STALLED_ERROR,error:r,fatal:!0})}}}class Av extends wy{constructor(e,t,r){super(e,t,r,"[stream-controller]",Ng),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Vf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Vf.LEVEL_LOADING,this.onLevelLoading,this),e.on(Vf.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Vf.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(Vf.ERROR,this.onError,this),e.on(Vf.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Vf.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(Vf.BUFFER_CREATED,this.onBufferCreated,this),e.on(Vf.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Vf.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Vf.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Vf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Vf.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Vf.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(Vf.ERROR,this.onError,this),e.off(Vf.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Vf.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(Vf.BUFFER_CREATED,this.onBufferCreated,this),e.off(Vf.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Vf.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Vf.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),this.onMediaDetaching()}startLoad(e){if(this.levels){const{lastCurrentTime:t,hls:r}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let e=r.startLevel;-1===e&&(r.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=r.nextAutoLevel),this.level=r.nextLoadLevel=e,this.loadedmetadata=!1}t>0&&-1===e&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=cy,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=ly}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case by:{var e;const{levels:t,level:r}=this,n=null==t||null==(e=t[r])?void 0:e.details;if(n&&(!n.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(n))break;this.state=cy;break}if(this.hls.nextLoadLevel!==this.level){this.state=cy;break}break}case hy:{var t;const e=self.performance.now(),r=this.retryDate;(!r||e>=r||null!=(t=this.media)&&t.seeking)&&(this.resetStartWhenNotLoaded(this.level),this.state=cy)}}this.state===cy&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:r,media:n}=this,{config:s,nextLoadLevel:i}=e;if(null===t||!n&&(this.startFragRequested||!s.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;if(null==r||!r[i])return;const a=r[i],o=this.getMainFwdBufferInfo();if(null===o)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const e={};return this.altAudio&&(e.type="video"),this.hls.trigger(Vf.BUFFER_EOS,e),void(this.state=my)}e.loadLevel!==i&&-1===e.manualLevel&&this.log(`Adapting to level ${i} from level ${this.level}`),this.level=e.nextLoadLevel=i;const c=a.details;if(!c||this.state===by||c.live&&this.levelLastLoaded!==i)return this.level=i,void(this.state=by);const d=o.len,u=this.getMaxBufferLength(a.maxBitrate);if(d>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const h=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(h,c);if(this.couldBacktrack&&!this.fragPrevious&&f&&"initSegment"!==f.sn&&this.fragmentTracker.getState(f)!==Bm){var p;const e=(null!=(p=this.backtrackFragment)?p:f).sn-c.startSN,t=c.fragments[e-1];t&&f.cc===t.cc&&(f=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){const e=this.audioOnly&&!this.altAudio?ap:op,t=(e===op?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,Ng)}f=this.getNextFragmentLoopLoading(f,c,o,Ng,u)}f&&(!f.initSegment||f.initSegment.data||this.bitrateTest||(f=f.initSegment),this.loadFragment(f,a,h))}loadFragment(e,t,r){const n=this.fragmentTracker.getState(e);this.fragCurrent=e,n===Fm||n===Nm?"initSegment"===e.sn?this._loadInitSegment(e,t):this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):(this.startFragRequested=!0,super.loadFragment(e,t,r)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,Ng)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(null!=t&&t.readyState){let r;const n=this.getAppendedFrag(t.currentTime);n&&n.start>1&&this.flushMainBuffer(0,n.start-1);const s=this.getLevelDetails();if(null!=s&&s.live){const e=this.getMainFwdBufferInfo();if(!e||e.len<2*s.targetduration)return}if(!t.paused&&e){const t=e[this.hls.nextLoadLevel],n=this.fragLastKbps;r=n&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*n)+1:0}else r=0;const i=this.getBufferedFrag(t.currentTime+r);if(i){const e=this.followingBufferedFrag(i);if(e){this.abortCurrentFrag();const t=e.maxStartPTS?e.maxStartPTS:e.start,r=e.duration,n=Math.max(i.end,t+Math.min(Math.max(r-this.config.maxFragLookUpTolerance,.5*r),.75*r));this.flushMainBuffer(n,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case dy:case uy:case hy:case py:case gy:this.state=cy}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const r=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),r.addEventListener("playing",this.onvplaying),r.addEventListener("seeked",this.onvseeked),this.gapController=new kv(this.config,r,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:e}=this;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const e=this.media,t=e?e.currentTime:null;Hf(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);const r=this.getMainFwdBufferInfo();null!==r&&0!==r.len?this.tick():this.warn(`Main forward buffer length on "seeked" event ${r?r.len:"empty"})`)}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(Vf.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=0,this.levels=this.fragPlaying=this.backtrackFragment=null,this.altAudio=this.audioOnly=!1}onManifestParsed(e,t){let r,n=!1,s=!1;t.levels.forEach((e=>{r=e.audioCodec,r&&(-1!==r.indexOf("mp4a.40.2")&&(n=!0),-1!==r.indexOf("mp4a.40.5")&&(s=!0))})),this.audioCodecSwitch=n&&s&&!function(){var e;const t=Ey();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:r}=this;if(!r||this.state!==cy)return;const n=r[t.level];(!n.details||n.details.live&&this.levelLastLoaded!==t.level||this.waitForCdnTuneIn(n.details))&&(this.state=by)}onLevelLoaded(e,t){var r;const{levels:n}=this,s=t.level,i=t.details,a=i.totalduration;if(!n)return void this.warn(`Levels were reset while loading level ${s}`);this.log(`Level ${s} loaded [${i.startSN},${i.endSN}]${i.lastPartSn?`[part-${i.lastPartSn}-${i.lastPartIndex}]`:""}, cc [${i.startCC}, ${i.endCC}] duration:${a}`);const o=n[s],l=this.fragCurrent;!l||this.state!==uy&&this.state!==hy||l.level===t.level&&l.urlId===o.urlId||!l.loader||this.abortCurrentFrag();let c=0;if(i.live||null!=(r=o.details)&&r.live){if(i.fragments[0]||(i.deltaUpdateFailed=!0),i.deltaUpdateFailed)return;c=this.alignPlaylists(i,o.details)}if(o.details=i,this.levelLastLoaded=s,this.hls.trigger(Vf.LEVEL_UPDATED,{details:i,level:s}),this.state===by){if(this.waitForCdnTuneIn(i))return;this.state=cy}this.startFragRequested?i.live&&this.synchronizeToLiveEdge(i):this.setStartPosition(i,c),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:r,part:n,payload:s}=e,{levels:i}=this;if(!i)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);const a=i[r.level],o=a.details;if(!o)return this.warn(`Dropping fragment ${r.sn} of level ${r.level} after level details were reset`),void this.fragmentTracker.removeFragment(r);const l=a.videoCodec,c=o.PTSKnown||!o.live,d=null==(t=r.initSegment)?void 0:t.data,u=this._getAudioCodec(a),h=this.transmuxer=this.transmuxer||new Cv(this.hls,Ng,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=n?n.index:-1,p=-1!==f,g=new Xm(r.level,r.sn,r.stats.chunkCount,s.byteLength,f,p),m=this.initPTS[r.cc];h.push(s,d,u,l,r,n,o.totalduration,c,g,m)}onAudioTrackSwitching(e,t){const r=this.altAudio;if(!!!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const e=this.hls;r&&(e.trigger(Vf.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),e.trigger(Vf.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const r=t.id,n=!!this.hls.audioTracks[r].url;if(n){const e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=n,this.tick()}onBufferCreated(e,t){const r=t.tracks;let n,s,i=!1;for(const e in r){const t=r[e];if("main"===t.id){if(s=e,n=t,"video"===e){const t=r[e];t&&(this.videoBuffer=t.buffer)}}else i=!0}i&&n?(this.log(`Alternate track found, use ${s}.buffered to schedule main fragment loading`),this.mediaBuffer=n.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:r,part:n}=t;if(r&&r.type!==Ng)return;if(this.fragContextChanged(r))return this.warn(`Fragment ${r.sn}${n?" p: "+n.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===gy&&(this.state=cy));const s=n?n.stats:r.stats;this.fragLastKbps=Math.round(8*s.total/(s.buffering.end-s.loading.first)),"initSegment"!==r.sn&&(this.fragPrevious=r),this.fragBufferedComplete(r,n)}onError(e,t){var r;if(t.fatal)this.state=yy;else switch(t.details){case Wf.FRAG_GAP:case Wf.FRAG_PARSING_ERROR:case Wf.FRAG_DECRYPT_ERROR:case Wf.FRAG_LOAD_ERROR:case Wf.FRAG_LOAD_TIMEOUT:case Wf.KEY_LOAD_ERROR:case Wf.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Ng,t);break;case Wf.LEVEL_LOAD_ERROR:case Wf.LEVEL_LOAD_TIMEOUT:case Wf.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==by||(null==(r=t.context)?void 0:r.type)!==Mg||(this.state=cy);break;case Wf.BUFFER_FULL_ERROR:if(!t.parent||"main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case Wf.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}checkBuffer(){const{media:e,gapController:t}=this;if(e&&t&&e.readyState){if(this.loadedmetadata||!Qm.getBuffered(e).length){const e=this.state!==cy?this.fragCurrent:null;t.poll(this.lastCurrentTime,e)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=cy,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==ap||this.audioOnly&&!this.altAudio){const e=(t===op?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(e,t,Ng)}}onLevelsUpdated(e,t){this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let r=this.startPosition;if(r>=0&&t<r){if(e.seeking)return void this.log(`could not seek to ${r}, already seeking at ${t}`);const n=Qm.getBuffered(e),s=(n.length?n.start(0):0)-r;s>0&&(s<this.config.maxBufferHole||s<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${s} to match buffer start`),r+=s,this.startPosition=r),this.log(`seek to target start position ${r} from current time ${t}`),e.currentTime=r}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then((r=>{const{hls:n}=this;if(!r||this.fragContextChanged(e))return;t.fragmentError=0,this.state=cy,this.startFragRequested=!1,this.bitrateTest=!1;const s=e.stats;s.parsing.start=s.parsing.end=s.buffering.start=s.buffering.end=self.performance.now(),n.trigger(Vf.FRAG_LOADED,r),e.bitrateTest=!1}))}_handleTransmuxComplete(e){var t;const r="main",{hls:n}=this,{remuxResult:s,chunkMeta:i}=e,a=this.getCurrentContext(i);if(!a)return void this.resetWhenMissingContext(i);const{frag:o,part:l,level:c}=a,{video:d,text:u,id3:h,initSegment:f}=s,{details:p}=c,g=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=py,f){if(null!=f&&f.tracks){const e=o.initSegment||o;this._bufferInitSegment(c,f.tracks,e,i),n.trigger(Vf.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:r,tracks:f.tracks})}const e=f.initPTS,t=f.timescale;Hf(e)&&(this.initPTS[o.cc]={baseTime:e,timescale:t},n.trigger(Vf.INIT_PTS_FOUND,{frag:o,id:r,initPTS:e,timescale:t}))}if(d&&p&&"initSegment"!==o.sn){const e=p.fragments[o.sn-1-p.startSN],t=o.sn===p.startSN,r=!e||o.cc>e.cc;if(!1!==s.independent){const{startPTS:e,endPTS:n,startDTS:s,endDTS:a}=d;if(l)l.elementaryStreams[d.type]={startPTS:e,endPTS:n,startDTS:s,endDTS:a};else if(d.firstKeyFrame&&d.independent&&1===i.id&&!r&&(this.couldBacktrack=!0),d.dropped&&d.independent){const s=this.getMainFwdBufferInfo(),i=(s?s.end:this.getLoadPosition())+this.config.maxBufferHole,l=d.firstKeyFramePTS?d.firstKeyFramePTS:e;if(!t&&i<l-this.config.maxBufferHole&&!r)return void this.backtrack(o);r&&(o.gap=!0),o.setElementaryStreamInfo(d.type,o.start,n,o.start,a,!0)}o.setElementaryStreamInfo(d.type,e,n,s,a),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(d,o,l,i,t||r)}else{if(!t&&!r)return void this.backtrack(o);o.gap=!0}}if(g){const{startPTS:e,endPTS:t,startDTS:r,endDTS:n}=g;l&&(l.elementaryStreams[ap]={startPTS:e,endPTS:t,startDTS:r,endDTS:n}),o.setElementaryStreamInfo(ap,e,t,r,n),this.bufferFragmentData(g,o,l,i)}if(p&&null!=h&&null!=(t=h.samples)&&t.length){const e={id:r,frag:o,details:p,samples:h.samples};n.trigger(Vf.FRAG_PARSING_METADATA,e)}if(p&&u){const e={id:r,frag:o,details:p,samples:u.samples};n.trigger(Vf.FRAG_PARSING_USERDATA,e)}}}_bufferInitSegment(e,t,r,n){if(this.state!==py)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;const{audio:s,video:i,audiovideo:a}=t;if(s){let t=e.audioCodec;const r=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(t&&(t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),1!==s.metadata.channelCount&&-1===r.indexOf("firefox")&&(t="mp4a.40.5")),-1!==r.indexOf("android")&&"audio/mpeg"!==s.container&&(t="mp4a.40.2",this.log(`Android: force audio codec to ${t}`)),e.audioCodec&&e.audioCodec!==t&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${t}"`),s.levelCodec=t,s.id="main",this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${t||""}/${e.audioCodec||""}/${s.codec}]`)}i&&(i.levelCodec=e.videoCodec,i.id="main",this.log(`Init video buffer, container:${i.container}, codecs[level/parsed]=[${e.videoCodec||""}/${i.codec}]`)),a&&this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.attrs.CODECS||""}/${a.codec}]`),this.hls.trigger(Vf.BUFFER_CODECS,t),Object.keys(t).forEach((e=>{const s=t[e].initSegment;null!=s&&s.byteLength&&this.hls.trigger(Vf.BUFFER_APPENDING,{type:e,data:s,frag:r,part:null,chunkMeta:n,parent:r.type})})),this.tick()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,Ng)}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=cy}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const r=e.currentTime;if(Qm.isBuffered(e,r)?t=this.getAppendedFrag(r):Qm.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t){this.backtrackFragment=null;const e=this.fragPlaying,r=t.level;e&&t.sn===e.sn&&e.level===r&&t.urlId===e.urlId||(this.fragPlaying=t,this.hls.trigger(Vf.FRAG_CHANGED,{frag:t}),e&&e.level===r||this.hls.trigger(Vf.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){const e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){const e=this.media;if(e){const t=e.currentTime,r=this.currentFrag;if(r&&Hf(t)&&Hf(r.programDateTime)){const e=r.programDateTime+1e3*(t-r.start);return new Date(e)}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class Iv{constructor(e,t=0,r=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=r}sample(e,t){const r=Math.pow(this.alpha_,e);this.estimate_=t*(1-r)+r*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class _v{constructor(e,t,r,n=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Iv(e),this.fast_=new Iv(t),this.defaultTTFB_=n,this.ttfb_=new Iv(e)}update(e,t){const{slow_:r,fast_:n,ttfb_:s}=this;r.halfLife!==e&&(this.slow_=new Iv(e,r.getEstimate(),r.getTotalWeight())),n.halfLife!==t&&(this.fast_=new Iv(t,n.getEstimate(),n.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new Iv(e,s.getEstimate(),s.getTotalWeight()))}sample(e,t){const r=(e=Math.max(e,this.minDelayMs_))/1e3,n=8*t/r;this.fast_.sample(r,n),this.slow_.sample(r,n)}sampleTTFB(e){const t=e/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(r,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}destroy(){}}class Rv{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let r;return e.length?(r=1===e.length?e[0]:function(e,t){const r=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.length}return r}(e,t),this.reset(),r):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}function Lv(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Dv(e[r].attrs,t[r].attrs))return!1;return!0}function Dv(e,t){const r=e["STABLE-RENDITION-ID"];return r?r===t["STABLE-RENDITION-ID"]:!["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED"].some((r=>e[r]!==t[r]))}class xv{constructor(e){this.buffered=void 0;const t=(t,r,n)=>{if((r>>>=0)>n-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${r}) is greater than the maximum bound (${n})`);return e[r][t]};this.buffered={get length(){return e.length},end:r=>t("end",r,e.length),start:r=>t("start",r,e.length)}}}function Ov(e){const t=[];for(let r=0;r<e.length;r++){const n=e[r];"subtitles"!==n.kind&&"captions"!==n.kind||!n.label||t.push(e[r])}return t}class Pv{constructor(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}append(e,t){const r=this.queues[t];r.push(e),1===r.length&&this.buffers[t]&&this.executeNext(t)}insertAbort(e,t){this.queues[t].unshift(e),this.executeNext(t)}appendBlocker(e){let t;const r=new Promise((e=>{t=e})),n={execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(n,e),r}executeNext(e){const{buffers:t,queues:r}=this,n=t[e],s=r[e];if(s.length){const t=s[0];try{t.execute()}catch(r){Zf.warn("[buffer-operation-queue]: Unhandled exception executing the current operation"),t.onError(r),null!=n&&n.updating||(s.shift(),this.executeNext(e))}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}}const Mv=yg(),Fv=/([ha]vc.)(?:\.[^.,]+)+/;const Uv={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},Nv=function(e){let t=e;return Uv.hasOwnProperty(e)&&(t=Uv[e]),String.fromCharCode(t)},Bv=15,jv=100,$v={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},qv={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Kv={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Gv={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Hv=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Vv{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const r="function"==typeof t?t():t;Zf.log(`${this.time} [${e}] ${r}`)}}}const zv=function(e){const t=[];for(let r=0;r<e.length;r++)t.push(e[r].toString(16));return t};class Wv{constructor(e,t,r,n,s){this.foreground=void 0,this.underline=void 0,this.italics=void 0,this.background=void 0,this.flash=void 0,this.foreground=e||"white",this.underline=t||!1,this.italics=r||!1,this.background=n||"black",this.flash=s||!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let r=0;r<t.length;r++){const n=t[r];e.hasOwnProperty(n)&&(this[n]=e[n])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class Yv{constructor(e,t,r,n,s,i){this.uchar=void 0,this.penState=void 0,this.uchar=e||" ",this.penState=new Wv(t,r,n,s,i)}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class Qv{constructor(e){this.chars=void 0,this.pos=void 0,this.currPenState=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chars=[];for(let e=0;e<jv;e++)this.chars.push(new Yv);this.logger=e,this.pos=0,this.currPenState=new Wv}equals(e){let t=!0;for(let r=0;r<jv;r++)if(!this.chars[r].equals(e.chars[r])){t=!1;break}return t}copy(e){for(let t=0;t<jv;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<jv;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>jv&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=jv)}moveCursor(e){const t=this.pos+e;if(e>1)for(let e=this.pos+1;e<t+1;e++)this.chars[e].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=Nv(e);this.pos>=jv?this.logger.log(0,(()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!")):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}clearFromPos(e){let t;for(t=e;t<jv;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let r=0;r<jv;r++){const n=this.chars[r].uchar;" "!==n&&(t=!1),e.push(n)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e);this.chars[this.pos].setPenState(this.currPenState)}}class Xv{constructor(e){this.rows=void 0,this.currRow=void 0,this.nrRollUpRows=void 0,this.lastOutputScreen=void 0,this.logger=void 0,this.rows=[];for(let t=0;t<Bv;t++)this.rows.push(new Qv(e));this.logger=e,this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.reset()}reset(){for(let e=0;e<Bv;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let r=0;r<Bv;r++)if(!this.rows[r].equals(e.rows[r])){t=!1;break}return t}copy(e){for(let t=0;t<Bv;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<Bv;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e);this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,(()=>"pacData = "+JSON.stringify(e)));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let e=0;e<Bv;e++)this.rows[e].clear();const e=this.currRow+1-this.nrRollUpRows,r=this.lastOutputScreen;if(r){const n=r.rows[e].cueStartTime,s=this.logger.time;if(n&&null!==s&&n<s)for(let n=0;n<this.nrRollUpRows;n++)this.rows[t-this.nrRollUpRows+n+1].copy(r.rows[e+n])}}this.currRow=t;const r=this.rows[this.currRow];if(null!==e.indent){const t=e.indent,n=Math.max(t-1,0);r.setCursor(e.indent),e.color=r.chars[n].penState.foreground}const n={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(n)}setBkgData(e){this.logger.log(2,(()=>"bkgData = "+JSON.stringify(e))),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,(()=>this.getDisplayText()));const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let r="",n=-1;for(let r=0;r<Bv;r++){const s=this.rows[r].getTextString();s&&(n=r+1,e?t.push("Row "+n+": '"+s+"'"):t.push(s.trim()))}return t.length>0&&(r=e?"["+t.join(" | ")+"]":t.join("\n")),r}getTextAndFormat(){return this.rows}}class Jv{constructor(e,t,r){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new Xv(r),this.nonDisplayedMemory=new Xv(r),this.lastOutputScreen=new Xv(r),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=r}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,(()=>"MODE="+e)),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,(()=>t+": "+this.writeScreen.getDisplayText(!0))),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,(()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0))),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(()=>"DISP: "+this.displayedMemory.getDisplayText()))}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{const r=Math.floor(e/2)-16,n=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=n[r]}this.logger.log(2,"MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class Zv{constructor(e,t,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=void 0,this.logger=void 0;const n=new Vv;this.channels=[null,new Jv(e,t,n),new Jv(e+1,r,n)],this.cmdHistory={a:null,b:null},this.logger=n}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){let r,n,s,i=!1;this.logger.time=e;for(let e=0;e<t.length;e+=2)if(n=127&t[e],s=127&t[e+1],0!==n||0!==s){if(this.logger.log(3,"["+zv([t[e],t[e+1]])+"] -> ("+zv([n,s])+")"),r=this.parseCmd(n,s),r||(r=this.parseMidrow(n,s)),r||(r=this.parsePAC(n,s)),r||(r=this.parseBackgroundAttributes(n,s)),!r&&(i=this.parseChars(n,s),i)){const e=this.currentChannel;if(e&&e>0){this.channels[e].insertChars(i)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}r||i||this.logger.log(2,"Couldn't parse cleaned data "+zv([n,s])+" orig: "+zv([t[e],t[e+1]]))}}parseCmd(e,t){const{cmdHistory:r}=this;if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=33&&t<=35))return!1;if(tb(e,t,r))return eb(null,null,r),this.logger.log(3,"Repeated command ("+zv([e,t])+") is dropped"),!0;const n=20===e||21===e||23===e?1:2,s=this.channels[n];return 20===e||21===e||28===e||29===e?32===t?s.ccRCL():33===t?s.ccBS():34===t?s.ccAOF():35===t?s.ccAON():36===t?s.ccDER():37===t?s.ccRU(2):38===t?s.ccRU(3):39===t?s.ccRU(4):40===t?s.ccFON():41===t?s.ccRDC():42===t?s.ccTR():43===t?s.ccRTD():44===t?s.ccEDM():45===t?s.ccCR():46===t?s.ccENM():47===t&&s.ccEOC():s.ccTO(t-32),eb(e,t,r),this.currentChannel=n,!0}parseMidrow(e,t){let r=0;if((17===e||25===e)&&t>=32&&t<=47){if(r=17===e?1:2,r!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const n=this.channels[r];return!!n&&(n.ccMIDROW(t),this.logger.log(3,"MIDROW ("+zv([e,t])+")"),!0)}return!1}parsePAC(e,t){let r;const n=this.cmdHistory;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;if(tb(e,t,n))return eb(null,null,n),!0;const s=e<=23?1:2;r=t>=64&&t<=95?1===s?$v[e]:Kv[e]:1===s?qv[e]:Gv[e];const i=this.channels[s];return!!i&&(i.setPAC(this.interpretPAC(r,t)),eb(e,t,n),this.currentChannel=s,!0)}interpretPAC(e,t){let r;const n={color:null,italics:!1,indent:null,underline:!1,row:e};return r=t>95?t-96:t-64,n.underline=1==(1&r),r<=13?n.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(n.italics=!0,n.color="white"):n.indent=4*Math.floor((r-16)/2),n}parseChars(e,t){let r,n=null,s=null;if(e>=25?(r=2,s=e-8):(r=1,s=e),s>=17&&s<=19){let e;e=17===s?t+80:18===s?t+112:t+144,this.logger.log(2,"Special char '"+Nv(e)+"' in channel "+r),n=[e]}else e>=32&&e<=127&&(n=0===t?[e]:[e,t]);if(n){const r=zv(n);this.logger.log(3,"Char codes = "+r.join(",")),eb(e,t,this.cmdHistory)}return n}parseBackgroundAttributes(e,t){if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;let r;const n={};16===e||24===e?(r=Math.floor((t-32)/2),n.background=Hv[r],t%2==1&&(n.background=n.background+"_semi")):45===t?n.background="transparent":(n.foreground="black",47===t&&(n.underline=!0));const s=e<=23?1:2;return this.channels[s].setBkgData(n),eb(e,t,this.cmdHistory),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}this.cmdHistory={a:null,b:null}}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const r=this.channels[t];r&&r.cueSplitAtTime(e)}}}function eb(e,t,r){r.a=e,r.b=t}function tb(e,t,r){return r.a===e&&r.b===t}class rb{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,r){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var nb=function(){if("undefined"!=typeof self&&self.VTTCue)return self.VTTCue;const e=["","lr","rl"],t=["start","middle","end","left","right"];function r(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;const r=t.toLowerCase();return!!~e.indexOf(r)&&r}function n(e){return r(t,e)}function s(e,...t){let r=1;for(;r<arguments.length;r++){const t=arguments[r];for(const r in t)e[r]=t[r]}return e}function i(t,i,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let c="",d=!1,u=t,h=i,f=a,p=null,g="",m=!0,y="auto",v="start",b=50,w="middle",E=50,S="middle";Object.defineProperty(o,"id",s({},l,{get:function(){return c},set:function(e){c=""+e}})),Object.defineProperty(o,"pauseOnExit",s({},l,{get:function(){return d},set:function(e){d=!!e}})),Object.defineProperty(o,"startTime",s({},l,{get:function(){return u},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");u=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",s({},l,{get:function(){return h},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");h=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",s({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",s({},l,{get:function(){return p},set:function(e){p=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",s({},l,{get:function(){return g},set:function(t){const n=function(t){return r(e,t)}(t);if(!1===n)throw new SyntaxError("An invalid or illegal string was specified.");g=n,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",s({},l,{get:function(){return m},set:function(e){m=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",s({},l,{get:function(){return y},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",s({},l,{get:function(){return v},set:function(e){const t=n(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");v=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",s({},l,{get:function(){return b},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");b=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",s({},l,{get:function(){return w},set:function(e){const t=n(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");w=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",s({},l,{get:function(){return E},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",s({},l,{get:function(){return S},set:function(e){const t=n(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");S=t,this.hasBeenReset=!0}})),o.displayState=void 0}return i.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},i}();class sb{decode(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function ib(e){function t(e,t,r,n){return 3600*(0|e)+60*(0|t)+(0|r)+parseFloat(n||0)}const r=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?t(r[2],r[3],0,r[4]):t(r[1],r[2],r[3],r[4]):null}class ab{constructor(){this.values=Object.create(null)}set(e,t){this.get(e)||""===t||(this.values[e]=t)}get(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,r){for(let n=0;n<r.length;++n)if(t===r[n]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const r=parseFloat(t);if(r>=0&&r<=100)return this.set(e,r),!0}return!1}}function ob(e,t,r,n){const s=n?e.split(n):[e];for(const e in s){if("string"!=typeof s[e])continue;const n=s[e].split(r);if(2!==n.length)continue;t(n[0],n[1])}}const lb=new nb(0,0,""),cb="middle"===lb.align?"middle":"center";function db(e,t,r){const n=e;function s(){const t=ib(e);if(null===t)throw new Error("Malformed timestamp: "+n);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function i(){e=e.replace(/^\s+/,"")}if(i(),t.startTime=s(),i(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+n);e=e.slice(3),i(),t.endTime=s(),i(),function(e,t){const n=new ab;ob(e,(function(e,t){let s;switch(e){case"region":for(let s=r.length-1;s>=0;s--)if(r[s].id===t){n.set(e,r[s].region);break}break;case"vertical":n.alt(e,t,["rl","lr"]);break;case"line":s=t.split(","),n.integer(e,s[0]),n.percent(e,s[0])&&n.set("snapToLines",!1),n.alt(e,s[0],["auto"]),2===s.length&&n.alt("lineAlign",s[1],["start",cb,"end"]);break;case"position":s=t.split(","),n.percent(e,s[0]),2===s.length&&n.alt("positionAlign",s[1],["start",cb,"end","line-left","line-right","auto"]);break;case"size":n.percent(e,t);break;case"align":n.alt(e,t,["start",cb,"end","left","right"])}}),/:/,/\s/),t.region=n.get("region",null),t.vertical=n.get("vertical","");let s=n.get("line","auto");"auto"===s&&-1===lb.line&&(s=-1),t.line=s,t.lineAlign=n.get("lineAlign","start"),t.snapToLines=n.get("snapToLines",!0),t.size=n.get("size",100),t.align=n.get("align",cb);let i=n.get("position","auto");"auto"===i&&50===lb.position&&(i="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=i}(e,t)}function ub(e){return e.replace(/<br(?: \/)?>/gi,"\n")}class hb{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new sb,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;function r(){let e=t.buffer,r=0;for(e=ub(e);r<e.length&&"\r"!==e[r]&&"\n"!==e[r];)++r;const n=e.slice(0,r);return"\r"===e[r]&&++r,"\n"===e[r]&&++r,t.buffer=e.slice(r),n}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{let e="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;e=r();const n=e.match(/^()?WEBVTT([ \t].*)?$/);if(null==n||!n[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let n=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(n?n=!1:e=r(),t.state){case"HEADER":/:/.test(e)?ob(e,(function(e,t){}),/:/):e||(t.state="ID");continue;case"NOTE":e||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(e)){t.state="NOTE";break}if(!e)continue;if(t.cue=new nb(0,0,""),t.state="CUE",-1===e.indexOf("--\x3e")){t.cue.id=e;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{db(e,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const r=-1!==e.indexOf("--\x3e");if(!e||r&&(n=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=e}continue;case"BADCUE":e||(t.state="ID")}}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const fb=/\r\n|\n\r|\n|\r/g,pb=function(e,t,r=0){return e.slice(r,r+t.length)===t},gb=function(e){let t=5381,r=e.length;for(;r;)t=33*t^e.charCodeAt(--r);return(t>>>0).toString()};function mb(e,t,r){return gb(e.toString())+gb(t.toString())+gb(r)}function yb(e,t,r,n,s,i,a){const o=new hb,l=jp(new Uint8Array(e)).trim().replace(fb,"\n").split("\n"),c=[],d=t?function(e,t=1){return nv(e,9e4,1/t)}(t.baseTime,t.timescale):0;let u,h="00:00.000",f=0,p=0,g=!0;o.oncue=function(e){const i=r[n];let a=r.ccOffset;const o=(f-d)/9e4;if(null!=i&&i.new&&(void 0!==p?a=r.ccOffset=i.start:function(e,t,r){let n=e[t],s=e[n.prevCC];if(!s||!s.new&&n.new)return e.ccOffset=e.presentationOffset=n.start,void(n.new=!1);for(;null!=(i=s)&&i.new;){var i;e.ccOffset+=n.start-s.start,n.new=!1,n=s,s=e[n.prevCC]}e.presentationOffset=r}(r,n,o)),o){if(!t)return void(u=new Error("Missing initPTS for VTT MPEGTS"));a=o-r.presentationOffset}const l=e.endTime-e.startTime,h=cv(9e4*(e.startTime+a-p),9e4*s)/9e4;e.startTime=Math.max(h,0),e.endTime=Math.max(h+l,0);const g=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(g)),e.id||(e.id=mb(e.startTime,e.endTime,g)),e.endTime>0&&c.push(e)},o.onparsingerror=function(e){u=e},o.onflush=function(){u?a(u):i(c)},l.forEach((e=>{if(g){if(pb(e,"X-TIMESTAMP-MAP=")){g=!1,e.slice(16).split(",").forEach((e=>{pb(e,"LOCAL:")?h=e.slice(6):pb(e,"MPEGTS:")&&(f=parseInt(e.slice(7)))}));try{p=function(e){let t=parseInt(e.slice(-3));const r=parseInt(e.slice(-6,-4)),n=parseInt(e.slice(-9,-7)),s=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(Hf(t)&&Hf(r)&&Hf(n)&&Hf(s)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*r,t+=6e4*n,t+=36e5*s,t}(h)/1e3}catch(e){u=e}return}""===e&&(g=!1)}o.parse(e+"\n")})),o.flush()}const vb="stpp.ttml.im1t",bb=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,wb=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Eb={left:"start",center:"center",right:"end",start:"start",end:"end"};function Sb(e,t,r,n){const s=Jp(new Uint8Array(e),["mdat"]);if(0===s.length)return void n(new Error("Could not parse IMSC1 mdat"));const i=s.map((e=>jp(e))),a=function(e,t,r=1,n=!1){return nv(e,t,1/r,n)}(t.baseTime,1,t.timescale);try{i.forEach((e=>r(function(e,t){const r=new DOMParser,n=r.parseFromString(e,"text/xml").getElementsByTagName("tt")[0];if(!n)throw new Error("Invalid ttml");const s={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},i=Object.keys(s).reduce(((e,t)=>(e[t]=n.getAttribute(`ttp:${t}`)||s[t],e)),{}),a="preserve"!==n.getAttribute("xml:space"),o=Cb(Tb(n,"styling","style")),l=Cb(Tb(n,"layout","region")),c=Tb(n,"body","[begin]");return[].map.call(c,(e=>{const r=kb(e,a);if(!r||!e.hasAttribute("begin"))return null;const n=_b(e.getAttribute("begin"),i),s=_b(e.getAttribute("dur"),i);let c=_b(e.getAttribute("end"),i);if(null===n)throw Ib(e);if(null===c){if(null===s)throw Ib(e);c=n+s}const d=new nb(n-t,c-t,r);d.id=mb(d.startTime,d.endTime,d.text);const u=function(e,t,r){const n="http://www.w3.org/ns/ttml#styling";let s=null;const i=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;a&&r.hasOwnProperty(a)&&(s=r[a]);return i.reduce(((r,i)=>{const a=Ab(t,n,i)||Ab(e,n,i)||Ab(s,n,i);return a&&(r[i]=a),r}),{})}(l[e.getAttribute("region")],o[e.getAttribute("style")],o),{textAlign:h}=u;if(h){const e=Eb[h];e&&(d.lineAlign=e),d.align=h}return Gf(d,u),d})).filter((e=>null!==e))}(e,a))))}catch(e){n(e)}}function Tb(e,t,r){const n=e.getElementsByTagName(t)[0];return n?[].slice.call(n.querySelectorAll(r)):[]}function Cb(e){return e.reduce(((e,t)=>{const r=t.getAttribute("xml:id");return r&&(e[r]=t),e}),{})}function kb(e,t){return[].slice.call(e.childNodes).reduce(((e,r,n)=>{var s;return"br"===r.nodeName&&n?e+"\n":null!=(s=r.childNodes)&&s.length?kb(r,t):t?e+r.textContent.trim().replace(/\s+/g," "):e+r.textContent}),"")}function Ab(e,t,r){return e&&e.hasAttributeNS(t,r)?e.getAttributeNS(t,r):null}function Ib(e){return new Error(`Could not parse ttml timestamp ${e}`)}function _b(e,t){if(!e)return null;let r=ib(e);return null===r&&(bb.test(e)?r=function(e,t){const r=bb.exec(e),n=(0|r[4])+(0|r[5])/t.subFrameRate;return 3600*(0|r[1])+60*(0|r[2])+(0|r[3])+n/t.frameRate}(e,t):wb.test(e)&&(r=function(e,t){const r=wb.exec(e),n=Number(r[1]);switch(r[2]){case"h":return 3600*n;case"m":return 60*n;case"ms":return 1e3*n;case"f":return n/t.frameRate;case"t":return n/t.tickRate}return n}(e,t))),r}function Rb(e,t){return!!e&&e.label===t.name&&!(e.textTrack1||e.textTrack2)}class Lb{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.unregisterListener(),this.hls.config.capLevelToPlayerSize&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(Vf.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(Vf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Vf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Vf.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Vf.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(Vf.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(Vf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Vf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Vf.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Vf.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const r=this.hls.levels[t.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null}onManifestParsed(e,t){const r=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,r.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media&&this.mediaHeight>0&&this.mediaWidth>0){const e=this.hls.levels;if(e.length){const t=this.hls;t.autoLevelCapping=this.getMaxLevel(e.length-1),t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const r=t.filter(((t,r)=>this.isLevelAllowed(t)&&r<=e));return this.clientRect=null,Lb.getMaxLevelByMediaSize(r,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,t.width||t.height||(t.width=r.right-r.left||e.width||0,t.height=r.bottom-r.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(e){}return e}isLevelAllowed(e){return!this.restrictedLevels.some((t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height))}static getMaxLevelByMediaSize(e,t,r){if(null==e||!e.length)return-1;let n=e.length-1;for(let a=0;a<e.length;a+=1){const o=e[a];if((o.width>=t||o.height>=r)&&(s=o,!(i=e[a+1])||s.width!==i.width||s.height!==i.height)){n=a;break}}var s,i;return n}}const Db="[eme]";class xb{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=xb.CDMCleanupPromise?[xb.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=Zf.debug.bind(Zf,Db),this.log=Zf.log.bind(Zf,Db),this.warn=Zf.warn.bind(Zf,Db),this.error=Zf.error.bind(Zf,Db),this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(Vf.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(Vf.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(Vf.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(Vf.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(Vf.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(Vf.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:r}=this.config,n=t[e];if(n)return n.licenseUrl;if(e===mp.WIDEVINE&&r)return r;throw new Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){const{drmSystems:t}=this.config,r=t[e];if(r)return r.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,r=(e,t,r)=>!!e&&r.indexOf(e)===t,n=t.map((e=>e.audioCodec)).filter(r),s=t.map((e=>e.videoCodec)).filter(r);return n.length+s.length===0&&s.push("avc1.42e01e"),new Promise(((t,r)=>{const i=e=>{const a=e.shift();this.getMediaKeysPromise(a,n,s).then((e=>t({keySystem:a,mediaKeys:e}))).catch((t=>{e.length?i(e):r(t instanceof Ob?t:new Ob({type:zf.KEY_SYSTEM_ERROR,details:Wf.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))}))};i(e)}))}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:r}=this.config;if("function"!=typeof r){let e=`Configured requestMediaKeySystemAccess is not a function ${r}`;return null===kp&&"http:"===self.location.protocol&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(e))}return r(e,t)}getMediaKeysPromise(e,t,r){const n=function(e,t,r,n){let s;switch(e){case mp.FAIRPLAY:s=["cenc","sinf"];break;case mp.WIDEVINE:case mp.PLAYREADY:s=["cenc"];break;case mp.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${e}`)}return function(e,t,r,n){return[{initDataTypes:e,persistentState:n.persistentState||"not-allowed",distinctiveIdentifier:n.distinctiveIdentifier||"not-allowed",sessionTypes:n.sessionTypes||[n.sessionType||"temporary"],audioCapabilities:t.map((e=>({contentType:`audio/mp4; codecs="${e}"`,robustness:n.audioRobustness||"",encryptionScheme:n.audioEncryptionScheme||null}))),videoCapabilities:r.map((e=>({contentType:`video/mp4; codecs="${e}"`,robustness:n.videoRobustness||"",encryptionScheme:n.videoEncryptionScheme||null})))}]}(s,t,r,n)}(e,t,r,this.config.drmSystemOptions),s=this.keySystemAccessPromises[e];let i=null==s?void 0:s.keySystemAccess;if(!i){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(n)}`),i=this.requestMediaKeySystemAccess(e,n);const t=this.keySystemAccessPromises[e]={keySystemAccess:i};return i.catch((t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)})),i.then((r=>{this.log(`Access for key-system "${r.keySystem}" obtained`);const n=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),t.mediaKeys=r.createMediaKeys().then((t=>(this.log(`Media-keys created for "${e}"`),n.then((r=>r?this.setMediaKeysServerCertificate(t,e,r):t))))),t.mediaKeys.catch((t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)})),t.mediaKeys}))}return i.then((()=>s.mediaKeys))}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:r}){this.log(`Creating key-system session "${t}" keyId: ${Kp(e.keyId||[])}`);const n=r.createSession(),s={decryptdata:e,keySystem:t,mediaKeys:r,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const r=this.createMediaKeySessionContext(e),n=this.getKeyIdString(t),s="cenc";this.keyIdToKeySessionPromise[n]=this.generateRequestWithPreferredKeySession(r,s,t.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return Kp(e.keyId)}updateKeySession(e,t){var r;const n=e.mediaKeysSession;return this.log(`Updating key-session "${n.sessionId}" for keyID ${Kp((null==(r=e.decryptdata)?void 0:r.keyId)||[])}\n } (data length: ${t?t.byteLength:t})`),n.update(t)}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise(((t,r)=>{const n=Cp(this.config),s=e.map(Ep).filter((e=>!!e&&-1!==n.indexOf(e)));return this.getKeySystemSelectionPromise(s).then((({keySystem:e})=>{const n=Tp(e);n?t(n):r(new Error(`Unable to find format for key-system "${e}"`))})).catch(r)}))}loadKey(e){const t=e.keyInfo.decryptdata,r=this.getKeyIdString(t),n=`(keyId: ${r} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${n}`);let s=this.keyIdToKeySessionPromise[r];return s||(s=this.keyIdToKeySessionPromise[r]=this.getKeySystemForKeyPromise(t).then((({keySystem:r,mediaKeys:s})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${n}`),this.attemptSetMediaKeys(r,s).then((()=>{this.throwIfDestroyed();const e=this.createMediaKeySessionContext({keySystem:r,mediaKeys:s,decryptdata:t});return this.generateRequestWithPreferredKeySession(e,"cenc",t.pssh,"playlist-key")}))))),s.catch((e=>this.handleError(e)))),s}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof Ob?this.hls.trigger(Vf.ERROR,e.data):this.hls.trigger(Vf.ERROR,{type:zf.KEY_SYSTEM_ERROR,details:Wf.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),r=this.keyIdToKeySessionPromise[t];if(!r){const t=Ep(e.keyFormat),r=t?[t]:Cp(this.config);return this.attemptKeySystemAccess(r)}return r}getKeySystemSelectionPromise(e){if(e.length||(e=Cp(this.config)),0===e.length)throw new Ob({type:zf.KEY_SYSTEM_ERROR,details:Wf.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){const{initDataType:t,initData:r}=e;if(this.debug(`"${e.type}" event: init data type: "${t}"`),null===r)return;let n,s;if("sinf"===t&&this.config.drmSystems[mp.FAIRPLAY]){const e=zp(new Uint8Array(r));try{const t=fp(JSON.parse(e).sinf),r=tg(new Uint8Array(t));if(!r)return;n=r.subarray(8,24),s=mp.FAIRPLAY}catch(e){return void this.warn('Failed to parse sinf "encrypted" event message initData')}}else{const e=function(e){if(!(e instanceof ArrayBuffer)||e.byteLength<32)return null;const t={version:0,systemId:"",kids:null,data:null},r=new DataView(e),n=r.getUint32(0);if(e.byteLength!==n&&n>44)return null;if(1886614376!==r.getUint32(4))return null;if(t.version=r.getUint32(8)>>>24,t.version>1)return null;t.systemId=Kp(new Uint8Array(e,12,16));const s=r.getUint32(28);if(0===t.version){if(n-32<s)return null;t.data=new Uint8Array(e,32,s)}else if(1===t.version){t.kids=[];for(let r=0;r<s;r++)t.kids.push(new Uint8Array(e,32+16*r,16))}return t}(r);if(null===e)return;0===e.version&&e.systemId===Sp&&e.data&&(n=e.data.subarray(8,24)),s=function(e){if(e===Sp)return mp.WIDEVINE}(e.systemId)}if(!s||!n)return;const i=Kp(n),{keyIdToKeySessionPromise:a,mediaKeySessions:o}=this;let l=a[i];for(let e=0;e<o.length;e++){const s=o[e],c=s.decryptdata;if(c.pssh||!c.keyId)continue;const d=Kp(c.keyId);if(i===d||-1!==c.uri.replace(/-/g,"").indexOf(i)){l=a[d],delete a[d],c.pssh=new Uint8Array(r),c.keyId=n,l=a[i]=l.then((()=>this.generateRequestWithPreferredKeySession(s,t,r,"encrypted-event-key-match")));break}}l||(l=a[i]=this.getKeySystemSelectionPromise([s]).then((({keySystem:e,mediaKeys:s})=>{var a;this.throwIfDestroyed();const o=new dg("ISO-23001-7",i,null!=(a=Tp(e))?a:"");return o.pssh=new Uint8Array(r),o.keyId=n,this.attemptSetMediaKeys(e,s).then((()=>{this.throwIfDestroyed();const n=this.createMediaKeySessionContext({decryptdata:o,keySystem:e,mediaKeys:s});return this.generateRequestWithPreferredKeySession(n,t,r,"encrypted-event-no-match")}))}))),l.catch((e=>this.handleError(e)))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,t){const r=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const n=Promise.all(r).then((()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)}));return this.setMediaKeysQueue.push(n),n.then((()=>{this.log(`Media-keys set for "${e}"`),r.push(n),this.setMediaKeysQueue=this.setMediaKeysQueue.filter((e=>-1===r.indexOf(e)))}))}generateRequestWithPreferredKeySession(e,t,r,n){var s,i;const a=null==(s=this.config.drmSystems)||null==(i=s[e.keySystem])?void 0:i.generateRequest;if(a)try{const n=a.call(this.hls,t,r,e);if(!n)throw new Error("Invalid response from configured generateRequest filter");t=n.initDataType,r=e.decryptdata.pssh=n.initData?new Uint8Array(n.initData):null}catch(e){var o;if(this.warn(e.message),null!=(o=this.hls)&&o.config.debug)throw e}if(null===r)return this.log(`Skipping key-session request for "${n}" (no initData)`),Promise.resolve(e);const l=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${n}": ${l} (init data type: ${t} length: ${r?r.byteLength:null})`);const c=new Sv;e.mediaKeysSession.onmessage=t=>{const r=e.mediaKeysSession;if(!r)return void c.emit("error",new Error("invalid state"));const{messageType:n,message:s}=t;this.log(`"${n}" message event for session "${r.sessionId}" message size: ${s.byteLength}`),"license-request"===n||"license-renewal"===n?this.renewLicense(e,s).catch((e=>{this.handleError(e),c.emit("error",e)})):"license-release"===n?e.keySystem===mp.FAIRPLAY&&(this.updateKeySession(e,gp("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${n}"`)},e.mediaKeysSession.onkeystatuseschange=t=>{if(!e.mediaKeysSession)return void c.emit("error",new Error("invalid state"));this.onKeyStatusChange(e);const r=e.keyStatus;c.emit("keyStatus",r),"expired"===r&&(this.warn(`${e.keySystem} expired for key ${l}`),this.renewKeySession(e))};const d=new Promise(((e,t)=>{c.on("error",t),c.on("keyStatus",(r=>{r.startsWith("usable")?e():"output-restricted"===r?t(new Ob({type:zf.KEY_SYSTEM_ERROR,details:Wf.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===r?t(new Ob({type:zf.KEY_SYSTEM_ERROR,details:Wf.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${r}"`)):"expired"===r?t(new Error("key expired while generating request")):this.warn(`unhandled key status change "${r}"`)}))}));return e.mediaKeysSession.generateRequest(t,r).then((()=>{var t;this.log(`Request generated for key-session "${null==(t=e.mediaKeysSession)?void 0:t.sessionId}" keyId: ${l}`)})).catch((e=>{throw new Ob({type:zf.KEY_SYSTEM_ERROR,details:Wf.KEY_SYSTEM_NO_SESSION,error:e,fatal:!1},`Error generating key-session request: ${e}`)})).then((()=>d)).catch((t=>{throw c.removeAllListeners(),this.removeSession(e),t})).then((()=>(c.removeAllListeners(),e)))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach(((t,r)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${Kp("buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r))} session keyId: ${Kp(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t}))}fetchServerCertificate(e){const t=this.config,r=new(0,t.loader)(t),n=this.getServerCertificateUrl(e);return n?(this.log(`Fetching serverCertificate for "${e}"`),new Promise(((s,i)=>{const a={responseType:"arraybuffer",url:n},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(e,t,r,n)=>{s(e.data)},onError:(t,r,s,o)=>{i(new Ob({type:zf.KEY_SYSTEM_ERROR,details:Wf.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:qf({url:a.url,data:void 0},t)},`"${e}" certificate request failed (${n}). Status: ${t.code} (${t.text})`))},onTimeout:(t,r,s)=>{i(new Ob({type:zf.KEY_SYSTEM_ERROR,details:Wf.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:{url:a.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(e,t,r)=>{i(new Error("aborted"))}};r.load(a,l,c)}))):Promise.resolve()}setMediaKeysServerCertificate(e,t,r){return new Promise(((n,s)=>{e.setServerCertificate(r).then((s=>{this.log(`setServerCertificate ${s?"success":"not supported by CDM"} (${null==r?void 0:r.byteLength}) on "${t}"`),n(e)})).catch((e=>{s(new Ob({type:zf.KEY_SYSTEM_ERROR,details:Wf.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))}))}))}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then((t=>this.updateKeySession(e,new Uint8Array(t)).catch((e=>{throw new Ob({type:zf.KEY_SYSTEM_ERROR,details:Wf.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:e,fatal:!0},e.message)}))))}setupLicenseXHR(e,t,r,n){const s=this.config.licenseXhrSetup;return s?Promise.resolve().then((()=>{if(!r.decryptdata)throw new Error("Key removed");return s.call(this.hls,e,t,r,n)})).catch((i=>{if(!r.decryptdata)throw i;return e.open("POST",t,!0),s.call(this.hls,e,t,r,n)})).then((r=>{e.readyState||e.open("POST",t,!0);return{xhr:e,licenseChallenge:r||n}})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:n}))}requestLicense(e,t){const r=this.config.keyLoadPolicy.default;return new Promise(((n,s)=>{const i=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${i}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return s(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let t=a.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);const r=this.config.licenseResponseCallback;if(r)try{t=r.call(this.hls,a,i,e)}catch(e){this.error(e)}n(t)}else{const o=r.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)s(new Ob({type:zf.KEY_SYSTEM_ERROR,details:Wf.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:i,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${i}). Status: ${a.status} (${a.statusText})`));else{const r=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${r} attempts left`),this.requestLicense(e,t).then(n,s)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,i,e,t).then((({xhr:e,licenseChallenge:t})=>{e.send(t)}))}))}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const r=t.media;this.media=r,r.addEventListener("encrypted",this.onMediaEncrypted),r.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media,t=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},dg.clearKeyUriToKeyIdMap();const r=t.length;xb.CDMCleanupPromise=Promise.all(t.map((e=>this.removeSession(e))).concat(null==e?void 0:e.setMediaKeys(null).catch((t=>{this.log(`Could not clear media keys: ${t}. media.src: ${null==e?void 0:e.src}`)})))).then((()=>{r&&(this.log("finished closing key sessions and clearing media keys"),t.length=0)})).catch((t=>{this.log(`Could not close sessions and clear media keys: ${t}. media.src: ${null==e?void 0:e.src}`)}))}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){const e=t.reduce(((e,t)=>(-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e)),[]);this.log(`Selecting key-system from session-keys ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:r}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),t.onmessage=null,t.onkeystatuseschange=null,r&&r.readyState!==XMLHttpRequest.DONE&&r.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const n=this.mediaKeySessions.indexOf(e);return n>-1&&this.mediaKeySessions.splice(n,1),t.remove().catch((e=>{this.log(`Could not remove session: ${e}`)})).then((()=>t.close())).catch((e=>{this.log(`Could not close session: ${e}`)}))}}}xb.CDMCleanupPromise=void 0;class Ob extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}var Pb="m",Mb="a",Fb="v",Ub="av",Nb="i",Bb="tt";class jb{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=e=>{try{this.apply(e,{ot:Pb,su:!this.initialized})}catch(e){Zf.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=e=>{try{const t=e.frag,r=this.hls.levels[t.level],n=this.getObjectType(t),s={d:1e3*t.duration,ot:n};n!==Fb&&n!==Mb&&n!=Ub||(s.br=r.bitrate/1e3,s.tb=this.getTopBandwidth(n)/1e3,s.bl=this.getBufferLength(n)),this.apply(e,s)}catch(e){Zf.warn("Could not generate segment CMCD data.",e)}},this.hls=e;const t=this.config=e.config,{cmcd:r}=t;null!=r&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=r.sessionId||jb.uuid(),this.cid=r.contentId,this.useHeaders=!0===r.useHeaders,this.registerListeners())}registerListeners(){const e=this.hls;e.on(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Vf.MEDIA_DETACHED,this.onMediaDetached,this),e.on(Vf.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Vf.MEDIA_DETACHED,this.onMediaDetached,this),e.off(Vf.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var r,n;this.audioBuffer=null==(r=t.tracks.audio)?void 0:r.buffer,this.videoBuffer=null==(n=t.tracks.video)?void 0:n.buffer}createData(){var e;return{v:1,sf:"h",sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){Gf(t,this.createData());const r=t.ot===Nb||t.ot===Fb||t.ot===Ub;if(this.starved&&r&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering),this.useHeaders){const r=jb.toHeaders(t);if(!Object.keys(r).length)return;e.headers||(e.headers={}),Gf(e.headers,r)}else{const r=jb.toQuery(t);if(!r)return;e.url=jb.appendQueryToUri(e.url,r)}}getObjectType(e){const{type:t}=e;return"subtitle"===t?Bb:"initSegment"===e.sn?Nb:"audio"===t?Mb:"main"===t?this.hls.audioTracks.length?Fb:Ub:void 0}getTopBandwidth(e){let t,r=0;const n=this.hls;if(e===Mb)t=n.audioTracks;else{const e=n.maxAutoLevel,r=e>-1?e+1:n.levels.length;t=n.levels.slice(0,r)}for(const e of t)e.bitrate>r&&(r=e.bitrate);return r>0?r:NaN}getBufferLength(e){const t=this.hls.media,r=e===Mb?this.audioBuffer:this.videoBuffer;if(!r||!t)return NaN;return 1e3*Qm.bufferInfo(r,t.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,r=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new r(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,r,n){t(e),this.loader.load(e,r,n)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,r=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new r(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,r,n){t(e),this.loader.load(e,r,n)}}}static uuid(){const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}static serialize(e){const t=[],r=e=>!Number.isNaN(e)&&null!=e&&""!==e&&!1!==e,n=e=>Math.round(e),s=e=>100*n(e/100),i={br:n,d:n,bl:s,dl:s,mtp:s,nor:e=>encodeURIComponent(e),rtp:s,tb:n},a=Object.keys(e||{}).sort();for(const n of a){let s=e[n];if(!r(s))continue;if("v"===n&&1===s)continue;if("pr"==n&&1===s)continue;const a=i[n];a&&(s=a(s));const o=typeof s;let l;l="ot"===n||"sf"===n||"st"===n?`${n}=${s}`:"boolean"===o?n:"number"===o?`${n}=${s}`:`${n}=${JSON.stringify(s)}`,t.push(l)}return t.join(",")}static toHeaders(e){const t=Object.keys(e),r={},n=["Object","Request","Session","Status"],s=[{},{},{},{}],i={br:0,d:0,ot:0,tb:0,bl:1,dl:1,mtp:1,nor:1,nrr:1,su:1,cid:2,pr:2,sf:2,sid:2,st:2,v:2,bs:3,rtp:3};for(const r of t){s[null!=i[r]?i[r]:1][r]=e[r]}for(let e=0;e<s.length;e++){const t=jb.serialize(s[e]);t&&(r[`CMCD-${n[e]}`]=t)}return r}static toQuery(e){return`CMCD=${encodeURIComponent(jb.serialize(e))}`}static appendQueryToUri(e,t){if(!t)return e;const r=e.includes("?")?"&":"?";return`${e}${r}${t}`}}function $b(e,t,r,n){e&&Object.keys(t).forEach((s=>{const i=e.filter((e=>e.groupId===s)).map((e=>{const i=Gf({},e);return i.details=void 0,i.attrs=new rp(i.attrs),i.url=i.attrs.URI=qb(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),i.groupId=i.attrs["GROUP-ID"]=t[s],i.attrs["PATHWAY-ID"]=n,i}));e.push(...i)}))}function qb(e,t,r,n){const{HOST:s,PARAMS:i,[r]:a}=n;let o;t&&(o=null==a?void 0:a[t],o&&(e=o));const l=new self.URL(e);return s&&!o&&(l.host=s),i&&Object.keys(i).sort().forEach((e=>{e&&l.searchParams.set(e,i[e])})),l.href}const Kb=/^age:\s*[\d.]+\s*$/im;class Gb{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=void 0,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new ip,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,r){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=r,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e)return;const r=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;const s=this.xhrSetup;s?Promise.resolve().then((()=>{if(!this.stats.aborted)return s(r,t.url)})).catch((e=>(r.open("GET",t.url,!0),s(r,t.url)))).then((()=>{this.stats.aborted||this.openAndSendXhr(r,t,e)})).catch((e=>{this.callbacks.onError({code:r.status,text:e.message},t,r,n)})):this.openAndSendXhr(r,t,e)}openAndSendXhr(e,t,r){e.readyState||e.open("GET",t.url,!0);const n=this.context.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:i}=r.loadPolicy;if(n)for(const t in n)e.setRequestHeader(t,n[t]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),r.timeout=s&&Hf(s)?s:i,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:r}=this;if(!e||!t)return;const n=t.readyState,s=this.config;if(!r.aborted&&n>=2&&(0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),4===n)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const n=t.status,i="text"!==t.responseType;if(n>=200&&n<300&&(i&&t.response||null!==t.responseText)){r.loading.end=Math.max(self.performance.now(),r.loading.first);const s=i?t.response:t.responseText,a="arraybuffer"===t.responseType?s.byteLength:s.length;if(r.loaded=r.total=a,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first),!this.callbacks)return;const o=this.callbacks.onProgress;if(o&&o(r,e,s,t),!this.callbacks)return;const l={url:t.responseURL,data:s,code:n};this.callbacks.onSuccess(l,r,e,t)}else{const i=s.loadPolicy.errorRetry;bm(i,r.retry,!1,n)?this.retry(i):(Zf.error(`${n} while loading ${e.url}`),this.callbacks.onError({code:n,text:t.statusText},e,t,r))}}}loadtimeout(){var e;const t=null==(e=this.config)?void 0:e.loadPolicy.timeoutRetry;if(bm(t,this.stats.retry,!0))this.retry(t);else{Zf.warn(`timeout while loading ${this.context.url}`);const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:r}=this;this.retryDelay=ym(e,r.retry),r.retry++,Zf.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t.url}, retrying ${r.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Kb.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const Hb=/(\d+)-(\d+)\/(\d+)/;class Vb{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=void 0,this.response=void 0,this.controller=void 0,this.context=void 0,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||zb,this.controller=new self.AbortController,this.stats=new ip}destroy(){this.loader=this.callbacks=null,this.abortInternal()}abortInternal(){const e=this.response;null!=e&&e.ok||(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,r){const n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();const s=function(e,t){const r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Gf({},e.headers))};e.rangeEnd&&r.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return r}(e,this.controller.signal),i=r.onProgress,a="arraybuffer"===e.responseType,o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:c}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=r,this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),t.timeout=l&&Hf(l)?l:c,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),r.onTimeout(n,e,this.response)}),t.timeout),self.fetch(this.request).then((s=>{this.response=this.loader=s;const o=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=c,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),r.onTimeout(n,e,this.response)}),c-(o-n.loading.start)),!s.ok){const{status:e,statusText:t}=s;throw new Wb(t||"fetch, bad network response",e,s)}return n.loading.first=o,n.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=Hb.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(Hf(e))return e}const r=e.get("Content-Length");if(r)return parseInt(r)}(s.headers)||n.total,i&&Hf(t.highWaterMark)?this.loadProgressively(s,n,e,t.highWaterMark,i):a?s.arrayBuffer():"json"===e.responseType?s.json():s.text()})).then((s=>{const{response:a}=this;self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);const l=s[o];l&&(n.loaded=n.total=l);const c={url:a.url,data:s,code:a.status};i&&!Hf(t.highWaterMark)&&i(n,e,s,a),r.onSuccess(c,n,e,a)})).catch((t=>{if(self.clearTimeout(this.requestTimeout),n.aborted)return;const s=t&&t.code||0,i=t?t.message:null;r.onError({code:s,text:i},e,t?t.details:null,n)}))}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,r,n=0,s){const i=new Rv,a=e.body.getReader(),o=()=>a.read().then((a=>{if(a.done)return i.dataLength&&s(t,r,i.flush(),e),Promise.resolve(new ArrayBuffer(0));const l=a.value,c=l.length;return t.loaded+=c,c<n||i.dataLength?(i.push(l),i.dataLength>=n&&s(t,r,i.flush(),e)):s(t,r,l,e),o()})).catch((()=>Promise.reject()));return o()}}function zb(e,t){return new self.Request(e.url,t)}class Wb extends Error{constructor(e,t,r){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=r}}const Yb=/\s/,Qb={newCue(e,t,r,n){const s=[];let i,a,o,l,c;const d=self.VTTCue||self.TextTrackCue;for(let h=0;h<n.rows.length;h++)if(i=n.rows[h],o=!0,l=0,c="",!i.isEmpty()){var u;for(let e=0;e<i.chars.length;e++)Yb.test(i.chars[e].uchar)&&o?l++:(c+=i.chars[e].uchar,o=!1);i.cueStartTime=t,t===r&&(r+=1e-4),l>=16?l--:l++;const n=ub(c.trim()),f=mb(t,r,n);null!=e&&null!=(u=e.cues)&&u.getCueById(f)||(a=new d(t,r,n),a.id=f,a.line=h+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),s.push(a))}return e&&s.length&&(s.sort(((e,t)=>"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line)),s.forEach((t=>Hg(e,t)))),s}},Xb=qf(qf({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,maxBufferSize:6e7,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:Gb,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class{constructor(e){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=0,this._nextAutoLevel=-1,this.timer=-1,this.onCheck=this._abandonRulesCheck.bind(this),this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this.hls=e;const t=e.config;this.bwEstimator=new _v(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate),this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(Vf.FRAG_LOADING,this.onFragLoading,this),e.on(Vf.FRAG_LOADED,this.onFragLoaded,this),e.on(Vf.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Vf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Vf.LEVEL_LOADED,this.onLevelLoaded,this)}unregisterListeners(){const{hls:e}=this;e.off(Vf.FRAG_LOADING,this.onFragLoading,this),e.off(Vf.FRAG_LOADED,this.onFragLoaded,this),e.off(Vf.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Vf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Vf.LEVEL_LOADED,this.onLevelLoaded,this)}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this.onCheck=null,this.fragCurrent=this.partCurrent=null}onFragLoading(e,t){var r;const n=t.frag;this.ignoreFragment(n)||(this.fragCurrent=n,this.partCurrent=null!=(r=t.part)?r:null,this.clearTimer(),this.timer=self.setInterval(this.onCheck,100))}onLevelSwitching(e,t){this.clearTimer()}getTimeToLoadFrag(e,t,r,n){return e+r/t+(n?this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const r=this.hls.config,{total:n,bwEstimate:s}=t.stats;Hf(n)&&Hf(s)&&(this.lastLevelLoadSec=8*n/s),t.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD)}_abandonRulesCheck(){const{fragCurrent:e,partCurrent:t,hls:r}=this,{autoLevelEnabled:n,media:s}=r;if(!e||!s)return;const i=performance.now(),a=t?t.stats:e.stats,o=t?t.duration:e.duration,l=i-a.loading.start;if(a.aborted||a.loaded&&a.loaded===a.total||0===e.level)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!n||s.paused||!s.playbackRate||!s.readyState)return;const c=r.mainForwardBufferInfo;if(null===c)return;const d=this.bwEstimator.getEstimateTTFB(),u=Math.abs(s.playbackRate);if(l<=Math.max(d,o/(2*u)*1e3))return;const h=c.len/u;if(h>=2*o/u)return;const f=a.loading.first?a.loading.first-a.loading.start:-1,p=a.loaded&&f>-1,g=this.bwEstimator.getEstimate(),{levels:m,minAutoLevel:y}=r,v=m[e.level],b=a.total||Math.max(a.loaded,Math.round(o*v.maxBitrate/8));let w=l-f;w<1&&p&&(w=Math.min(l,8*a.loaded/g));const E=p?1e3*a.loaded/w:0,S=E?(b-a.loaded)/E:8*b/g+d/1e3;if(S<=h)return;const T=E?8*E:g;let C,k=Number.POSITIVE_INFINITY;for(C=e.level-1;C>y;C--){const e=m[C].maxBitrate;if(k=this.getTimeToLoadFrag(d/1e3,T,o*e,!m[C].details),k<h)break}k>=S||k>10*o||(r.nextLoadLevel=C,p?this.bwEstimator.sample(l-Math.min(d,f),a.loaded):this.bwEstimator.sampleTTFB(l),this.clearTimer(),Zf.warn(`[abr] Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} is loading too slowly;\n Time to underbuffer: ${h.toFixed(3)} s\n Estimated load time for current fragment: ${S.toFixed(3)} s\n Estimated load time for down switch fragment: ${k.toFixed(3)} s\n TTFB estimate: ${f}\n Current BW estimate: ${Hf(g)?(g/1024).toFixed(3):"Unknown"} Kb/s\n New BW estimate: ${(this.bwEstimator.getEstimate()/1024).toFixed(3)} Kb/s\n Aborting and switching to level ${C}`),e.loader&&(this.fragCurrent=this.partCurrent=null,e.abortRequests()),r.trigger(Vf.FRAG_LOAD_EMERGENCY_ABORTED,{frag:e,part:t,stats:a}))}onFragLoaded(e,{frag:t,part:r}){const n=r?r.stats:t.stats;if(t.type===Ng&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),this.lastLoadedFragLevel=t.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){const e=r?r.duration:t.duration,s=this.hls.levels[t.level],i=(s.loaded?s.loaded.bytes:0)+n.loaded,a=(s.loaded?s.loaded.duration:0)+e;s.loaded={bytes:i,duration:a},s.realBitrate=Math.round(8*i/a)}if(t.bitrateTest){const e={stats:n,frag:t,part:r,id:t.type};this.onFragBuffered(Vf.FRAG_BUFFERED,e),t.bitrateTest=!1}}}onFragBuffered(e,t){const{frag:r,part:n}=t,s=null!=n&&n.stats.loaded?n.stats:r.stats;if(s.aborted)return;if(this.ignoreFragment(r))return;const i=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(i,s.loaded),s.bwEstimate=this.bwEstimator.getEstimate(),r.bitrateTest?this.bitrateTestDelay=i/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==Ng||"initSegment"===e.sn}clearTimer(){self.clearInterval(this.timer)}get nextAutoLevel(){const e=this._nextAutoLevel,t=this.bwEstimator;if(-1!==e&&!t.canEstimate())return e;let r=this.getNextABRAutoLevel();if(-1!==e){const t=this.hls.levels;if(t.length>Math.max(e,r)&&t[e].loadError<=t[r].loadError)return e}return-1!==e&&(r=Math.min(e,r)),r}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:r}=this,{maxAutoLevel:n,config:s,minAutoLevel:i,media:a}=r,o=t?t.duration:e?e.duration:0,l=a&&0!==a.playbackRate?Math.abs(a.playbackRate):1,c=this.bwEstimator?this.bwEstimator.getEstimate():s.abrEwmaDefaultEstimate,d=r.mainForwardBufferInfo,u=(d?d.len:0)/l;let h=this.findBestLevel(c,i,n,u,s.abrBandWidthFactor,s.abrBandWidthUpFactor);if(h>=0)return h;Zf.trace(`[abr] ${u?"rebuffering expected":"buffer is empty"}, finding optimal quality level`);let f=o?Math.min(o,s.maxStarvationDelay):s.maxStarvationDelay,p=s.abrBandWidthFactor,g=s.abrBandWidthUpFactor;if(!u){const e=this.bitrateTestDelay;if(e){f=(o?Math.min(o,s.maxLoadingDelay):s.maxLoadingDelay)-e,Zf.trace(`[abr] bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*f)} ms`),p=g=1}}return h=this.findBestLevel(c,i,n,u+f,p,g),Math.max(h,0)}findBestLevel(e,t,r,n,s,i){var a;const{fragCurrent:o,partCurrent:l,lastLoadedFragLevel:c}=this,{levels:d}=this.hls,u=d[c],h=!(null==u||null==(a=u.details)||!a.live),f=null==u?void 0:u.codecSet,p=l?l.duration:o?o.duration:0,g=this.bwEstimator.getEstimateTTFB()/1e3;let m=t,y=-1;for(let a=r;a>=t;a--){const t=d[a];if(!t||f&&t.codecSet!==f){t&&(m=Math.min(a,m),y=Math.max(a,y));continue}-1!==y&&Zf.trace(`[abr] Skipped level(s) ${m}-${y} with CODECS:"${d[y].attrs.CODECS}"; not compatible with "${u.attrs.CODECS}"`);const r=t.details,o=(l?null==r?void 0:r.partTarget:null==r?void 0:r.averagetargetduration)||p;let v;v=a<=c?s*e:i*e;const b=d[a].maxBitrate,w=this.getTimeToLoadFrag(g,v,b*o,void 0===r);if(Zf.trace(`[abr] level:${a} adjustedbw-bitrate:${Math.round(v-b)} avgDuration:${o.toFixed(1)} maxFetchDuration:${n.toFixed(1)} fetchDuration:${w.toFixed(1)}`),v>b&&(0===w||!Hf(w)||h&&!this.bitrateTestDelay||w<n))return a}return-1}set nextAutoLevel(e){this._nextAutoLevel=e}},bufferController:class{constructor(e){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendError=0,this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this._onMediaSourceOpen=()=>{const{media:e,mediaSource:t}=this;Zf.log("[buffer-controller]: Media source opened"),e&&(e.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(Vf.MEDIA_ATTACHED,{media:e})),t&&t.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{Zf.log("[buffer-controller]: Media source closed")},this._onMediaSourceEnded=()=>{Zf.log("[buffer-controller]: Media source ended")},this._onMediaEmptied=()=>{const{media:e,_objectUrl:t}=this;e&&e.src!==t&&Zf.error(`Media element src was set while attaching MediaSource (${t} > ${e.src})`)},this.hls=e,this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null}registerListeners(){const{hls:e}=this;e.on(Vf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Vf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Vf.BUFFER_RESET,this.onBufferReset,this),e.on(Vf.BUFFER_APPENDING,this.onBufferAppending,this),e.on(Vf.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Vf.BUFFER_EOS,this.onBufferEos,this),e.on(Vf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Vf.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Vf.FRAG_PARSED,this.onFragParsed,this),e.on(Vf.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:e}=this;e.off(Vf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Vf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Vf.BUFFER_RESET,this.onBufferReset,this),e.off(Vf.BUFFER_APPENDING,this.onBufferAppending,this),e.off(Vf.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Vf.BUFFER_EOS,this.onBufferEos,this),e.off(Vf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Vf.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Vf.FRAG_PARSED,this.onFragParsed,this),e.off(Vf.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new Pv(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){let r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=r,Zf.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,t){const r=this.media=t.media;if(r&&Mv){const e=this.mediaSource=new Mv;e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),r.src=self.URL.createObjectURL(e),this._objectUrl=r.src,r.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:e,mediaSource:t,_objectUrl:r}=this;if(t){if(Zf.log("[buffer-controller]: media source detaching"),"open"===t.readyState)try{t.endOfStream()}catch(e){Zf.warn(`[buffer-controller]: onMediaDetaching: ${e.message} while calling endOfStream`)}this.onBufferReset(),t.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("sourceended",this._onMediaSourceEnded),t.removeEventListener("sourceclose",this._onMediaSourceClose),e&&(e.removeEventListener("emptied",this._onMediaEmptied),r&&self.URL.revokeObjectURL(r),e.src===r?(e.removeAttribute("src"),e.load()):Zf.warn("[buffer-controller]: media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(Vf.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach((e=>{const t=this.sourceBuffer[e];try{t&&(this.removeBufferListeners(e),this.mediaSource&&this.mediaSource.removeSourceBuffer(t),this.sourceBuffer[e]=void 0)}catch(t){Zf.warn(`[buffer-controller]: Failed to reset the ${e} buffer`,t)}})),this._initSourceBuffer()}onBufferCodecs(e,t){const r=this.getSourceBufferTypes().length;Object.keys(t).forEach((e=>{if(r){const r=this.tracks[e];if(r&&"function"==typeof r.buffer.changeType){const{id:n,codec:s,levelCodec:i,container:a,metadata:o}=t[e],l=(r.levelCodec||r.codec).replace(Fv,"$1"),c=(i||s).replace(Fv,"$1");if(l!==c){const t=`${a};codecs=${i||s}`;this.appendChangeType(e,t),Zf.log(`[buffer-controller]: switching codec ${l} to ${c}`),this.tracks[e]={buffer:r.buffer,codec:s,container:a,levelCodec:i,metadata:o,id:n}}}}else this.pendingTracks[e]=t[e]})),r||(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks())}appendChangeType(e,t){const{operationQueue:r}=this,n={execute:()=>{const n=this.sourceBuffer[e];n&&(Zf.log(`[buffer-controller]: changing ${e} sourceBuffer type to ${t}`),n.changeType(t)),r.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{Zf.warn(`[buffer-controller]: Failed to change ${e} SourceBuffer type`,t)}};r.append(n,e)}onBufferAppending(e,t){const{hls:r,operationQueue:n,tracks:s}=this,{data:i,type:a,frag:o,part:l,chunkMeta:c}=t,d=c.buffering[a],u=self.performance.now();d.start=u;const h=o.stats.buffering,f=l?l.stats.buffering:null;0===h.start&&(h.start=u),f&&0===f.start&&(f.start=u);const p=s.audio;let g=!1;"audio"===a&&"audio/mpeg"===(null==p?void 0:p.container)&&(g=!this.lastMpegAudioChunk||1===c.id||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);const m=o.start,y={execute:()=>{if(d.executeStart=self.performance.now(),g){const e=this.sourceBuffer[a];if(e){const t=m-e.timestampOffset;Math.abs(t)>=.1&&(Zf.log(`[buffer-controller]: Updating audio SourceBuffer timestampOffset to ${m} (delta: ${t}) sn: ${o.sn})`),e.timestampOffset=m)}}this.appendExecutor(i,a)},onStart:()=>{},onComplete:()=>{const e=self.performance.now();d.executeEnd=d.end=e,0===h.first&&(h.first=e),f&&0===f.first&&(f.first=e);const{sourceBuffer:t}=this,r={};for(const e in t)r[e]=Qm.getBuffered(t[e]);this.appendError=0,this.hls.trigger(Vf.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:c,parent:o.type,timeRanges:r})},onError:e=>{Zf.error(`[buffer-controller]: Error encountered while trying to append to the ${a} SourceBuffer`,e);const t={type:zf.MEDIA_ERROR,parent:o.type,details:Wf.BUFFER_APPEND_ERROR,frag:o,part:l,chunkMeta:c,error:e,err:e,fatal:!1};e.code===DOMException.QUOTA_EXCEEDED_ERR?t.details=Wf.BUFFER_FULL_ERROR:(this.appendError++,t.details=Wf.BUFFER_APPEND_ERROR,this.appendError>r.config.appendErrorMaxRetry&&(Zf.error(`[buffer-controller]: Failed ${r.config.appendErrorMaxRetry} times to append segment in sourceBuffer`),t.fatal=!0)),r.trigger(Vf.ERROR,t)}};n.append(y,a)}onBufferFlushing(e,t){const{operationQueue:r}=this,n=e=>({execute:this.removeExecutor.bind(this,e,t.startOffset,t.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(Vf.BUFFER_FLUSHED,{type:e})},onError:t=>{Zf.warn(`[buffer-controller]: Failed to remove from ${e} SourceBuffer`,t)}});t.type?r.append(n(t.type),t.type):this.getSourceBufferTypes().forEach((e=>{r.append(n(e),e)}))}onFragParsed(e,t){const{frag:r,part:n}=t,s=[],i=n?n.elementaryStreams:r.elementaryStreams;i[lp]?s.push("audiovideo"):(i[ap]&&s.push("audio"),i[op]&&s.push("video"));0===s.length&&Zf.warn(`Fragments must have at least one ElementaryStreamType set. type: ${r.type} level: ${r.level} sn: ${r.sn}`),this.blockBuffers((()=>{const e=self.performance.now();r.stats.buffering.end=e,n&&(n.stats.buffering.end=e);const t=n?n.stats:r.stats;this.hls.trigger(Vf.FRAG_BUFFERED,{frag:r,part:n,stats:t,id:r.type})}),s)}onFragChanged(e,t){this.flushBackBuffer()}onBufferEos(e,t){this.getSourceBufferTypes().reduce(((e,r)=>{const n=this.sourceBuffer[r];return!n||t.type&&t.type!==r||(n.ending=!0,n.ended||(n.ended=!0,Zf.log(`[buffer-controller]: ${r} sourceBuffer now EOS`))),e&&!(n&&!n.ended)}),!0)&&(Zf.log("[buffer-controller]: Queueing mediaSource.endOfStream()"),this.blockBuffers((()=>{this.getSourceBufferTypes().forEach((e=>{const t=this.sourceBuffer[e];t&&(t.ending=!1)}));const{mediaSource:e}=this;e&&"open"===e.readyState?(Zf.log("[buffer-controller]: Calling mediaSource.endOfStream()"),e.endOfStream()):e&&Zf.info(`[buffer-controller]: Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`)})))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}flushBackBuffer(){const{hls:e,details:t,media:r,sourceBuffer:n}=this;if(!r||null===t)return;const s=this.getSourceBufferTypes();if(!s.length)return;const i=t.live&&null!==e.config.liveBackBufferLength?e.config.liveBackBufferLength:e.config.backBufferLength;if(!Hf(i)||i<0)return;const a=r.currentTime,o=t.levelTargetDuration,l=Math.max(i,o),c=Math.floor(a/o)*o-l;s.forEach((r=>{const s=n[r];if(s){const n=Qm.getBuffered(s);if(n.length>0&&c>n.start(0)){if(e.trigger(Vf.BACK_BUFFER_REACHED,{bufferEnd:c}),t.live)e.trigger(Vf.LIVE_BACK_BUFFER_REACHED,{bufferEnd:c});else if(s.ended&&n.end(n.length-1)-a<2*o)return void Zf.info(`[buffer-controller]: Cannot flush ${r} back buffer while SourceBuffer is in ended state`);e.trigger(Vf.BUFFER_FLUSHING,{startOffset:0,endOffset:c,type:r})}}}))}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||"open"!==this.mediaSource.readyState)return;const{details:e,hls:t,media:r,mediaSource:n}=this,s=e.fragments[0].start+e.totalduration,i=r.duration,a=Hf(n.duration)?n.duration:0;e.live&&t.config.liveDurationInfinity?(Zf.log("[buffer-controller]: Media Source duration is set to Infinity"),n.duration=1/0,this.updateSeekableRange(e)):(s>a&&s>i||!Hf(i))&&(Zf.log(`[buffer-controller]: Updating Media Source duration to ${s.toFixed(3)}`),n.duration=s)}updateSeekableRange(e){const t=this.mediaSource,r=e.fragments;if(r.length&&e.live&&null!=t&&t.setLiveSeekableRange){const n=Math.max(0,r[0].start),s=Math.max(n,n+e.totalduration);t.setLiveSeekableRange(n,s)}}checkPendingTracks(){const{bufferCodecEventsExpected:e,operationQueue:t,pendingTracks:r}=this,n=Object.keys(r).length;if(n&&!e||2===n){this.createSourceBuffers(r),this.pendingTracks={};const e=this.getSourceBufferTypes();if(e.length)this.hls.trigger(Vf.BUFFER_CREATED,{tracks:this.tracks}),e.forEach((e=>{t.executeNext(e)}));else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}}createSourceBuffers(e){const{sourceBuffer:t,mediaSource:r}=this;if(!r)throw Error("createSourceBuffers called when mediaSource was null");for(const n in e)if(!t[n]){const s=e[n];if(!s)throw Error(`source buffer exists for track ${n}, however track does not`);const i=s.levelCodec||s.codec,a=`${s.container};codecs=${i}`;Zf.log(`[buffer-controller]: creating sourceBuffer(${a})`);try{const e=t[n]=r.addSourceBuffer(a),o=n;this.addBufferListener(o,"updatestart",this._onSBUpdateStart),this.addBufferListener(o,"updateend",this._onSBUpdateEnd),this.addBufferListener(o,"error",this._onSBUpdateError),this.tracks[n]={buffer:e,codec:i,container:s.container,levelCodec:s.levelCodec,metadata:s.metadata,id:s.id}}catch(e){Zf.error(`[buffer-controller]: error while trying to add sourceBuffer: ${e.message}`),this.hls.trigger(Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,mimeType:a})}}}_onSBUpdateStart(e){const{operationQueue:t}=this;t.current(e).onStart()}_onSBUpdateEnd(e){const{operationQueue:t}=this;t.current(e).onComplete(),t.shiftAndExecuteNext(e)}_onSBUpdateError(e,t){const r=new Error(`${e} SourceBuffer error`);Zf.error(`[buffer-controller]: ${r}`,t),this.hls.trigger(Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.BUFFER_APPENDING_ERROR,error:r,fatal:!1});const n=this.operationQueue.current(e);n&&n.onError(t)}removeExecutor(e,t,r){const{media:n,mediaSource:s,operationQueue:i,sourceBuffer:a}=this,o=a[e];if(!n||!s||!o)return Zf.warn(`[buffer-controller]: Attempting to remove from the ${e} SourceBuffer, but it does not exist`),void i.shiftAndExecuteNext(e);const l=Hf(n.duration)?n.duration:1/0,c=Hf(s.duration)?s.duration:1/0,d=Math.max(0,t),u=Math.min(r,l,c);u>d&&!o.ending?(o.ended=!1,Zf.log(`[buffer-controller]: Removing [${d},${u}] from the ${e} SourceBuffer`),o.remove(d,u)):i.shiftAndExecuteNext(e)}appendExecutor(e,t){const{operationQueue:r,sourceBuffer:n}=this,s=n[t];if(!s)return Zf.warn(`[buffer-controller]: Attempting to append to the ${t} SourceBuffer, but it does not exist`),void r.shiftAndExecuteNext(t);s.ended=!1,s.appendBuffer(e)}blockBuffers(e,t=this.getSourceBufferTypes()){if(!t.length)return Zf.log("[buffer-controller]: Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(e);const{operationQueue:r}=this,n=t.map((e=>r.appendBlocker(e)));Promise.all(n).then((()=>{e(),t.forEach((e=>{const t=this.sourceBuffer[e];null!=t&&t.updating||r.shiftAndExecuteNext(e)}))}))}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,t,r){const n=this.sourceBuffer[e];if(!n)return;const s=r.bind(this,e);this.listeners[e].push({event:t,listener:s}),n.addEventListener(t,s)}removeBufferListeners(e){const t=this.sourceBuffer[e];t&&this.listeners[e].forEach((e=>{t.removeEventListener(e.event,e.listener)}))}},capLevelController:Lb,errorController:class{constructor(e){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=e,this.log=Zf.log.bind(Zf,"[info]:"),this.warn=Zf.warn.bind(Zf,"[warning]:"),this.error=Zf.error.bind(Zf,"[error]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(Vf.ERROR,this.onError,this),e.on(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Vf.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Vf.ERROR,this.onError,this),e.off(Vf.ERROR,this.onErrorOut,this),e.off(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Vf.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){this.playlistError=0}stopLoad(){}getVariantLevelIndex(e){return(null==e?void 0:e.type)===Ng?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var r,n;if(t.fatal)return;const s=this.hls,i=t.context;switch(t.details){case Wf.FRAG_LOAD_ERROR:case Wf.FRAG_LOAD_TIMEOUT:case Wf.KEY_LOAD_ERROR:case Wf.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case Wf.FRAG_PARSING_ERROR:if(null!=(r=t.frag)&&r.gap)return void(t.errorAction={action:Cm,flags:Im});case Wf.FRAG_GAP:case Wf.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=km);case Wf.LEVEL_EMPTY_ERROR:case Wf.LEVEL_PARSING_ERROR:{var a,o;const e=t.parent===Ng?t.level:s.loadLevel;t.details===Wf.LEVEL_EMPTY_ERROR&&null!=(a=t.context)&&null!=(o=a.levelDetails)&&o.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case Wf.LEVEL_LOAD_ERROR:case Wf.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==i?void 0:i.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.level)));case Wf.AUDIO_TRACK_LOAD_ERROR:case Wf.AUDIO_TRACK_LOAD_TIMEOUT:case Wf.SUBTITLE_LOAD_ERROR:case Wf.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const e=s.levels[s.loadLevel];if(e&&(i.type===Fg&&i.groupId===e.audioGroupId||i.type===Ug&&i.groupId===e.textGroupId))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=km,void(t.errorAction.flags=_m)}return;case Wf.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const e=s.levels[s.loadLevel],r=null==e?void 0:e.attrs["HDCP-LEVEL"];r&&(t.errorAction={action:km,flags:Rm,hdcpLevel:r})}return;case Wf.BUFFER_ADD_CODEC_ERROR:case Wf.REMUX_ALLOC_ERROR:return void(t.errorAction=this.getLevelSwitchAction(t,null!=(n=t.level)?n:s.loadLevel));case Wf.INTERNAL_EXCEPTION:case Wf.BUFFER_APPENDING_ERROR:case Wf.BUFFER_APPEND_ERROR:case Wf.BUFFER_FULL_ERROR:case Wf.LEVEL_SWITCH_ERROR:case Wf.BUFFER_STALLED_ERROR:case Wf.BUFFER_SEEK_OVER_HOLE:case Wf.BUFFER_NUDGE_ON_STALL:return void(t.errorAction={action:Cm,flags:Im})}if(t.type===zf.KEY_SYSTEM_ERROR){const e=this.getVariantLevelIndex(t.frag);return t.levelRetry=!1,void(t.errorAction=this.getLevelSwitchAction(t,e))}}getPlaylistRetryOrSwitchAction(e,t){var r;const n=mm(this.hls.config.playlistLoadPolicy,e),s=this.playlistError++,i=null==(r=e.response)?void 0:r.code;if(bm(n,s,gm(e),i))return{action:Am,flags:Im,retryConfig:n,retryCount:s};const a=this.getLevelSwitchAction(e,t);return n&&(a.retryConfig=n,a.retryCount=s),a}getFragRetryOrSwitchAction(e){const t=this.hls,r=this.getVariantLevelIndex(e.frag),n=t.levels[r],{fragLoadPolicy:s,keyLoadPolicy:i}=t.config,a=mm(e.details.startsWith("key")?i:s,e),o=t.levels.reduce(((e,t)=>e+t.fragmentError),0);if(n){var l;e.details!==Wf.FRAG_GAP&&n.fragmentError++;const t=null==(l=e.response)?void 0:l.code;if(bm(a,o,gm(e),t))return{action:Am,flags:Im,retryConfig:a,retryCount:o}}const c=this.getLevelSwitchAction(e,r);return a&&(c.retryConfig=a,c.retryCount=o),c}getLevelSwitchAction(e,t){const r=this.hls;null==t&&(t=r.loadLevel);const n=this.hls.levels[t];if(n&&(n.loadError++,r.autoLevelEnabled)){var s,i;let t=-1;const{levels:a,loadLevel:o,minAutoLevel:l,maxAutoLevel:c}=r,d=null==(s=e.frag)?void 0:s.type,{type:u,groupId:h}=null!=(i=e.context)?i:{};for(let r=a.length;r--;){const s=(r+o)%a.length;if(s!==o&&s>=l&&s<=c&&0===a[s].loadError){const r=a[s];if(e.details===Wf.FRAG_GAP&&e.frag){const t=a[s].details;if(t){const r=Em(e.frag,t.fragments,e.frag.start);if(null!=r&&r.gap)continue}}else{if(u===Fg&&h===r.audioGroupId||u===Ug&&h===r.textGroupId)continue;if(d===Bg&&n.audioGroupId===r.audioGroupId||d===jg&&n.textGroupId===r.textGroupId)continue}t=s;break}}if(t>-1&&r.loadLevel!==t)return e.levelRetry=!0,this.playlistError=0,{action:km,flags:Im,nextAutoLevel:t}}return{action:km,flags:_m}}onErrorOut(e,t){var r;switch(null==(r=t.errorAction)?void 0:r.action){case Cm:break;case km:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===Wf.FRAG_GAP||(t.fatal=!0)}t.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(e){const t=this.hls,r=e.errorAction;if(!r)return;const{flags:n,hdcpLevel:s,nextAutoLevel:i}=r;switch(n){case Im:this.switchLevel(e,i);break;case _m:r.resolved||(r.resolved=this.redundantFailover(e));break;case Rm:s&&(t.maxHdcpLevel=rm[rm.indexOf(s)-1],r.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)}r.resolved||this.switchLevel(e,i)}switchLevel(e,t){void 0!==t&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}redundantFailover(e){const{hls:t,penalizedRenditions:r}=this,n=e.parent===Ng?e.level:t.loadLevel,s=t.levels[n],i=s.url.length,a=e.frag?e.frag.urlId:s.urlId;s.urlId!==a||e.frag&&!s.details||this.penalizeRendition(s,e);for(let o=1;o<i;o++){const l=(a+o)%i,c=r[l];if(!c||Lm(c,e,r[a]))return this.warn(`Switching to Redundant Stream ${l+1}/${i}: "${s.url[l]}" after ${e.details}`),this.playlistError=0,t.levels.forEach((e=>{e.urlId=l})),t.nextLoadLevel=n,!0}return!1}penalizeRendition(e,t){const{penalizedRenditions:r}=this,n=r[e.urlId]||{lastErrorPerfMs:0,errors:[],details:void 0};n.lastErrorPerfMs=performance.now(),n.errors.push(t),n.details=e.details,r[e.urlId]=n}},fpsController:class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(Vf.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(Vf.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const r=this.hls.config;if(r.capLevelOnFPSDrop){const e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}}checkFPS(e,t,r){const n=performance.now();if(t){if(this.lastTime){const e=n-this.lastTime,s=r-this.lastDroppedFrames,i=t-this.lastDecodedFrames,a=1e3*s/e,o=this.hls;if(o.trigger(Vf.FPS_DROP,{currentDropped:s,currentDecoded:i,totalDroppedFrames:r}),a>0&&s>o.config.fpsDroppedMonitoringThreshold*i){let e=o.currentLevel;Zf.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=e)&&(e-=1,o.trigger(Vf.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:o.currentLevel}),o.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=n,this.lastDroppedFrames=r,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:kp,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:Qb,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:class extends wy{constructor(e,t,r){super(e,t,r,"[subtitle-stream-controller]",jg),this.levels=[],this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null}_registerListeners(){const{hls:e}=this;e.on(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Vf.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Vf.ERROR,this.onError,this),e.on(Vf.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Vf.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(Vf.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Vf.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(Vf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Vf.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Vf.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Vf.ERROR,this.onError,this),e.off(Vf.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Vf.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(Vf.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Vf.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(Vf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Vf.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state=cy,this.setInterval(500),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:r,success:n}=t;if(this.fragPrevious=r,this.state=cy,!n)return;const s=this.tracksBuffered[this.currentTrackId];if(!s)return;let i;const a=r.start;for(let e=0;e<s.length;e++)if(a>=s[e].start&&a<=s[e].end){i=s[e];break}const o=r.start+r.duration;i?i.end=o:(i={start:a,end:o},s.push(i)),this.fragmentTracker.fragBuffered(r)}onBufferFlushing(e,t){const{startOffset:r,endOffset:n}=t;if(0===r&&n!==Number.POSITIVE_INFINITY){const e=n-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach((t=>{for(let r=0;r<t.length;)if(t[r].end<=e)t.shift();else{if(!(t[r].start<e))break;t[r].start=e,r++}})),this.fragmentTracker.removeFragmentsInRange(r,e,jg)}}onFragBuffered(e,t){var r;this.loadedmetadata||t.frag.type!==Ng||null!=(r=this.media)&&r.buffered.length&&(this.loadedmetadata=!0)}onError(e,t){const r=t.frag;(null==r?void 0:r.type)===jg&&(this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==ly&&(this.state=cy))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){Lv(this.levels,t)?this.levels=t.map((e=>new om(e))):(this.tracksBuffered=[],this.levels=t.map((e=>{const t=new om(e);return this.tracksBuffered[t.id]=[],t})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,jg),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(e,t){if(this.currentTrackId=t.id,!this.levels.length||-1===this.currentTrackId)return void this.clearInterval();const r=this.levels[this.currentTrackId];null!=r&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.setInterval(500)}onSubtitleTrackLoaded(e,t){var r;const{details:n,id:s}=t,{currentTrackId:i,levels:a}=this;if(!a.length)return;const o=a[i];if(s>=a.length||s!==i||!o)return;this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||null!=(r=o.details)&&r.live){const e=this.mainDetails;if(n.deltaUpdateFailed||!e)return;const t=e.fragments[0];o.details?(l=this.alignPlaylists(n,o.details),0===l&&t&&(l=t.start,hm(n,l))):n.hasProgramDateTime&&e.hasProgramDateTime?(ry(n,e),l=n.fragments[0].start):t&&(l=t.start,hm(n,l))}if(o.details=n,this.levelLastLoaded=s,this.startFragRequested||!this.mainDetails&&n.live||this.setStartPosition(o.details,l),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===cy){Em(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(e){const{frag:t,payload:r}=e,n=t.decryptdata,s=this.hls;if(!this.fragContextChanged(t)&&r&&r.byteLength>0&&n&&n.key&&n.iv&&"AES-128"===n.method){const e=performance.now();this.decrypter.decrypt(new Uint8Array(r),n.key.buffer,n.iv.buffer).catch((e=>{throw s.trigger(Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e})).then((r=>{const n=performance.now();s.trigger(Vf.FRAG_DECRYPTED,{frag:t,payload:r,stats:{tstart:e,tdecrypt:n}})})).catch((e=>{this.warn(`${e.name}: ${e.message}`),this.state=cy}))}}doTick(){if(this.media){if(this.state===cy){const{currentTrackId:e,levels:t}=this,r=t[e];if(!t.length||!r||!r.details)return;const{config:n}=this,s=this.getLoadPosition(),i=Qm.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,n.maxBufferHole),{end:a,len:o}=i,l=this.getFwdBufferInfo(this.media,Ng),c=r.details;if(o>this.getMaxBufferLength(null==l?void 0:l.len)+c.levelTargetDuration)return;const d=c.fragments,u=d.length,h=c.edge;let f=null;const p=this.fragPrevious;if(a<h){const e=n.maxFragLookUpTolerance,t=a>h-e?0:e;f=Em(p,d,Math.max(d[0].start,a),t),!f&&p&&p.start<d[0].start&&(f=d[0])}else f=d[u-1];if(!f)return;if(f=this.mapToInitFragWhenRequired(f),"initSegment"!==f.sn){const e=d[f.sn-c.startSN-1];e&&e.cc===f.cc&&this.fragmentTracker.getState(e)===Fm&&(f=e)}this.fragmentTracker.getState(f)===Fm&&this.loadFragment(f,r,a)}}else this.state=cy}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.max(t,e):t}loadFragment(e,t,r){this.fragCurrent=e,"initSegment"===e.sn?this._loadInitSegment(e,t):(this.startFragRequested=!0,super.loadFragment(e,t,r))}get mediaBufferTimeRanges(){return new xv(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends Dm{constructor(e){super(e,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.trackChangeListener=()=>this.onTextTracksChanged(),this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.trackChangeListener=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes(this.trackId)}registerListeners(){const{hls:e}=this;e.on(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Vf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Vf.LEVEL_LOADING,this.onLevelLoading,this),e.on(Vf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Vf.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Vf.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Vf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Vf.LEVEL_LOADING,this.onLevelLoading,this),e.off(Vf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Vf.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Vf.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.trackChangeListener,e)}onMediaDetaching(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId);Ov(this.media.textTracks).forEach((e=>{Vg(e)})),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:r,details:n}=t,{trackId:s}=this,i=this.tracksInGroup[s];if(!i)return void this.warn(`Invalid subtitle track id ${r}`);const a=i.details;i.details=t.details,this.log(`subtitle track ${r} loaded [${n.startSN}-${n.endSN}]`),r===this.trackId&&this.playlistLoaded(r,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(null==t||!t.textGroupIds)return;const r=t.textGroupIds[t.urlId],n=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;if(this.groupId!==r){const e=this.tracks.filter((e=>!r||e.groupId===r));this.tracksInGroup=e;const t=this.findTrackId(null==n?void 0:n.name)||this.findTrackId();this.groupId=r||null;const s={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${r}" group-id`),this.hls.trigger(Vf.SUBTITLE_TRACKS_UPDATED,s),-1!==t&&this.setSubtitleTrack(t,n)}else this.shouldReloadPlaylist(n)&&this.setSubtitleTrack(this.trackId,n)}findTrackId(e){const t=this.tracksInGroup;for(let r=0;r<t.length;r++){const n=t[r];if((!this.selectDefaultTrack||n.default)&&(!e||e===n.name))return n.id}return-1}onError(e,t){!t.fatal&&t.context&&t.context.type===Ug&&t.context.id===this.trackId&&t.context.groupId===this.groupId&&this.checkRetry(t)}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1;const t=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;this.setSubtitleTrack(e,t)}loadPlaylist(e){super.loadPlaylist();const t=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(t)){const r=t.id,n=t.groupId;let s=t.url;if(e)try{s=e.addDirectives(s)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}this.log(`Loading subtitle playlist for id ${r}`),this.hls.trigger(Vf.SUBTITLE_TRACK_LOADING,{url:s,id:r,groupId:n,deliveryDirectives:e||null})}}toggleTrackModes(e){const{media:t,trackId:r}=this;if(!t)return;const n=Ov(t.textTracks),s=n.filter((e=>e.groupId===this.groupId));if(-1===e)[].slice.call(n).forEach((e=>{e.mode="disabled"}));else{const e=s[r];e&&(e.mode="disabled")}const i=s[e];i&&(i.mode=this.subtitleDisplay?"showing":"hidden")}setSubtitleTrack(e,t){var r;const n=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=e);if(this.trackId!==e&&this.toggleTrackModes(e),this.trackId===e&&(-1===e||null!=(r=n[e])&&r.details)||e<-1||e>=n.length)return;this.clearTimer();const s=n[e];if(this.log(`Switching to subtitle-track ${e}`+(s?` "${s.name}" lang:${s.lang} group:${s.groupId}`:"")),this.trackId=e,s){const{id:e,groupId:r="",name:n,type:i,url:a}=s;this.hls.trigger(Vf.SUBTITLE_TRACK_SWITCH,{id:e,groupId:r,name:n,type:i,url:a});const o=this.switchParams(s.url,null==t?void 0:t.details);this.loadPlaylist(o)}else this.hls.trigger(Vf.SUBTITLE_TRACK_SWITCH,{id:e})}onTextTracksChanged(){if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=-1;const t=Ov(this.media.textTracks);for(let r=0;r<t.length;r++)if("hidden"===t[r].mode)e=r;else if("showing"===t[r].mode){e=r;break}this.subtitleTrack!==e&&(this.subtitleTrack=e)}},timelineController:class{constructor(e){if(this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},this.config.enableCEA708Captions){const e=new rb(this,"textTrack1"),t=new rb(this,"textTrack2"),r=new rb(this,"textTrack3"),n=new rb(this,"textTrack4");this.cea608Parser1=new Zv(1,e,t),this.cea608Parser2=new Zv(3,r,n)}e.on(Vf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Vf.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Vf.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Vf.FRAG_LOADING,this.onFragLoading,this),e.on(Vf.FRAG_LOADED,this.onFragLoaded,this),e.on(Vf.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(Vf.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(Vf.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Vf.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(Vf.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(Vf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Vf.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Vf.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Vf.FRAG_LOADING,this.onFragLoading,this),e.off(Vf.FRAG_LOADED,this.onFragLoaded,this),e.off(Vf.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(Vf.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(Vf.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Vf.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(Vf.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.cea608Parser1=this.cea608Parser2=null}addCues(e,t,r,n,s){let i=!1;for(let e=s.length;e--;){const n=s[e],d=(a=n[0],o=n[1],l=t,c=r,Math.min(o,c)-Math.max(a,l));if(d>=0&&(n[0]=Math.min(n[0],t),n[1]=Math.max(n[1],r),i=!0,d/(r-t)>.5))return}var a,o,l,c;if(i||s.push([t,r]),this.config.renderTextTracksNatively){const s=this.captionsTracks[e];this.Cues.newCue(s,t,r,n)}else{const s=this.Cues.newCue(null,t,r,n);this.hls.trigger(Vf.CUES_PARSED,{type:"captions",cues:s,track:e})}}onInitPtsFound(e,{frag:t,id:r,initPTS:n,timescale:s}){const{unparsedVttFrags:i}=this;"main"===r&&(this.initPTS[t.cc]={baseTime:n,timescale:s}),i.length&&(this.unparsedVttFrags=[],i.forEach((e=>{this.onFragLoaded(Vf.FRAG_LOADED,e)})))}getExistingTrack(e){const{media:t}=this;if(t)for(let r=0;r<t.textTracks.length;r++){const n=t.textTracks[r];if(n[e])return n}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:r,media:n}=this,{label:s,languageCode:i}=t[e],a=this.getExistingTrack(e);if(a)r[e]=a,Vg(r[e]),Gg(r[e],n);else{const t=this.createTextTrack("captions",s,i);t&&(t[e]=!0,r[e]=t)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const r={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(Vf.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}createTextTrack(e,t,r){const n=this.media;if(n)return n.addTextTrack(e,t,r)}onMediaAttaching(e,t){this.media=t.media,this._cleanTracks()}onMediaDetaching(){const{captionsTracks:e}=this;Object.keys(e).forEach((t=>{Vg(e[t]),delete e[t]})),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let e=0;e<t.length;e++)Vg(t[e])}onSubtitleTracksUpdated(e,t){const r=t.subtitleTracks||[],n=r.some((e=>e.textCodec===vb));if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(Lv(this.tracks,r))return void(this.tracks=r);if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){const e=this.media?this.media.textTracks:null;this.tracks.forEach(((t,r)=>{let n;if(e&&r<e.length){let r=null;for(let n=0;n<e.length;n++)if(Rb(e[n],t)){r=e[n];break}r&&(n=r)}if(n)Vg(n);else{const e=this._captionsOrSubtitlesFromCharacteristics(t);n=this.createTextTrack(e,t.name,t.lang),n&&(n.mode="disabled")}n&&(n.groupId=t.groupId,this.textTracks.push(n))}))}else if(this.tracks.length){const e=this.tracks.map((e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e})));this.hls.trigger(Vf.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}}}_captionsOrSubtitlesFromCharacteristics(e){if(e.attrs.CHARACTERISTICS){const t=/transcribes-spoken-dialog/gi.test(e.attrs.CHARACTERISTICS),r=/describes-music-and-sound/gi.test(e.attrs.CHARACTERISTICS);if(t&&r)return"captions"}return"subtitles"}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach((e=>{const t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;const r=`textTrack${t[1]}`,n=this.captionsProperties[r];n&&(n.label=e.name,e.lang&&(n.languageCode=e.lang),n.media=e)}))}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){const{cea608Parser1:r,cea608Parser2:n,lastSn:s,lastPartIndex:i}=this;if(this.enabled&&r&&n&&t.frag.type===Ng){var a,o;const e=t.frag.sn,l=null!=(a=null==t||null==(o=t.part)?void 0:o.index)?a:-1;e===s+1||e===s&&l===i+1||(r.reset(),n.reset()),this.lastSn=e,this.lastPartIndex=l}}onFragLoaded(e,t){const{frag:r,payload:n}=t;if(r.type===jg)if(n.byteLength){const e=r.decryptdata,s="stats"in t;if(null==e||!e.encrypted||s){const e=this.tracks[r.level],s=this.vttCCs;s[r.cc]||(s[r.cc]={start:r.start,prevCC:this.prevCC,new:!0},this.prevCC=r.cc),e&&e.textCodec===vb?this._parseIMSC1(r,n):this._parseVTTs(t)}}else this.hls.trigger(Vf.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const r=this.hls;Sb(t,this.initPTS[e.cc],(t=>{this._appendCues(t,e.level),r.trigger(Vf.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})}),(t=>{Zf.log(`Failed to parse IMSC1: ${t}`),r.trigger(Vf.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})}))}_parseVTTs(e){var t;const{frag:r,payload:n}=e,{initPTS:s,unparsedVttFrags:i}=this,a=s.length-1;if(!s[r.cc]&&-1===a)return void i.push(e);const o=this.hls;yb(null!=(t=r.initSegment)&&t.data?ng(r.initSegment.data,new Uint8Array(n)):n,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,(e=>{this._appendCues(e,r.level),o.trigger(Vf.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r})}),(t=>{const s="Missing initPTS for VTT MPEGTS"===t.message;s?i.push(e):this._fallbackToIMSC1(r,n),Zf.log(`Failed to parse VTT cue: ${t}`),s&&a>r.cc||o.trigger(Vf.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:t})}))}_fallbackToIMSC1(e,t){const r=this.tracks[e.level];r.textCodec||Sb(t,this.initPTS[e.cc],(()=>{r.textCodec=vb,this._parseIMSC1(e,t)}),(()=>{r.textCodec="wvtt"}))}_appendCues(e,t){const r=this.hls;if(this.config.renderTextTracksNatively){const r=this.textTracks[t];if(!r||"disabled"===r.mode)return;e.forEach((e=>Hg(r,e)))}else{const n=this.tracks[t];if(!n)return;const s=n.default?"default":"subtitles"+t;r.trigger(Vf.CUES_PARSED,{type:"subtitles",cues:e,track:s})}}onFragDecrypted(e,t){const{frag:r}=t;r.type===jg&&this.onFragLoaded(Vf.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){const{cea608Parser1:r,cea608Parser2:n}=this;if(!this.enabled||!r||!n)return;const{frag:s,samples:i}=t;if(s.type!==Ng||"NONE"!==this.closedCaptionsForLevel(s))for(let e=0;e<i.length;e++){const t=i[e].bytes;if(t){const s=this.extractCea608Data(t);r.addData(i[e].pts,s[0]),n.addData(i[e].pts,s[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:r,endOffsetSubtitles:n,type:s}){const{media:i}=this;if(i&&!(i.currentTime<r)){if(!s||"video"===s){const{captionsTracks:e}=this;Object.keys(e).forEach((n=>zg(e[n],t,r)))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==n){const{textTracks:e}=this;Object.keys(e).forEach((r=>zg(e[r],t,n)))}}}extractCea608Data(e){const t=[[],[]],r=31&e[0];let n=2;for(let s=0;s<r;s++){const r=e[n++],s=127&e[n++],i=127&e[n++];if(0===s&&0===i)continue;if(0!=(4&r)){const e=3&r;0!==e&&1!==e||(t[e].push(s),t[e].push(i))}}return t}},audioStreamController:class extends wy{constructor(e,t,r){super(e,t,r,"[audio-stream-controller]",Bg),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:e}=this;e.on(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Vf.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Vf.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(Vf.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Vf.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Vf.ERROR,this.onError,this),e.on(Vf.BUFFER_RESET,this.onBufferReset,this),e.on(Vf.BUFFER_CREATED,this.onBufferCreated,this),e.on(Vf.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Vf.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Vf.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(Vf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Vf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Vf.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Vf.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(Vf.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Vf.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Vf.ERROR,this.onError,this),e.off(Vf.BUFFER_RESET,this.onBufferReset,this),e.off(Vf.BUFFER_CREATED,this.onBufferCreated,this),e.off(Vf.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Vf.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Vf.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(e,{frag:t,id:r,initPTS:n,timescale:s}){if("main"===r){const e=t.cc;this.initPTS[t.cc]={baseTime:n,timescale:s},this.log(`InitPTS for cc: ${e} found from main: ${n}`),this.videoTrackCC=e,this.state===vy&&this.tick()}}startLoad(e){if(!this.levels)return this.startPosition=e,void(this.state=ly);const t=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),t>0&&-1===e?(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t,this.state=cy):(this.loadedmetadata=!1,this.state=fy),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case cy:this.doTickIdle();break;case fy:{var e;const{levels:t,trackId:r}=this,n=null==t||null==(e=t[r])?void 0:e.details;if(n){if(this.waitForCdnTuneIn(n))break;this.state=vy}break}case hy:{var t;const e=performance.now(),r=this.retryDate;(!r||e>=r||null!=(t=this.media)&&t.seeking)&&(this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded(this.trackId),this.state=cy);break}case vy:{const e=this.waitingData;if(e){const{frag:t,part:r,cache:n,complete:s}=e;if(void 0!==this.initPTS[t.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=uy;const e={frag:t,part:r,payload:n.flush(),networkDetails:null};this._handleFragmentLoadProgress(e),s&&super._handleFragmentLoadComplete(e)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${t.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const e=this.getLoadPosition(),r=Qm.bufferInfo(this.mediaBuffer,e,this.config.maxBufferHole);Sm(r.end,this.config.maxFragLookUpTolerance,t)<0&&(this.log(`Waiting fragment cc (${t.cc}) @ ${t.start} cancelled because another fragment at ${r.end} is needed`),this.clearWaitingFragment())}}else this.state=cy}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=cy)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){const{hls:e,levels:t,media:r,trackId:n}=this,s=e.config;if(null==t||!t[n])return;if(!r&&(this.startFragRequested||!s.startFragPrefetch))return;const i=t[n],a=i.details;if(!a||a.live&&this.levelLastLoaded!==n||this.waitForCdnTuneIn(a))return void(this.state=fy);const o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,ap,Bg));const l=this.getFwdBufferInfo(o,Bg);if(null===l)return;const{bufferedTrack:c,switchingTrack:d}=this;if(!d&&this._streamEnded(l,a))return e.trigger(Vf.BUFFER_EOS,{type:"audio"}),void(this.state=my);const u=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,Ng),h=l.len,f=this.getMaxBufferLength(null==u?void 0:u.len);if(h>=f&&!d)return;const p=a.fragments[0].start;let g=l.end;if(d&&r){const e=this.getLoadPosition();c&&d.attrs!==c.attrs&&(g=e),a.PTSKnown&&e<p&&(l.end>p||l.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=p+.05)}let m=this.getNextFragment(g,a),y=!1;if(m&&this.isLoopLoading(m,g)&&(y=!!m.gap,m=this.getNextFragmentLoopLoading(m,a,l,Ng,f)),!m)return void(this.bufferFlushed=!0);const v=u&&m.start>u.end+a.targetduration;if(v||(null==u||!u.len)&&l.len){const e=this.getAppendedFrag(m.start,Ng);if(null===e)return;if(y||(y=!!e.gap||!!v&&0===u.len),v&&!y||y&&l.nextStart&&l.nextStart<e.end)return}this.loadFragment(m,i,g)}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.min(Math.max(t,e),this.config.maxMaxBufferLength):t}onMediaDetaching(){this.videoBuffer=null,super.onMediaDetaching()}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map((e=>new om(e)))}onAudioTrackSwitching(e,t){const r=!!t.url;this.trackId=t.id;const{fragCurrent:n}=this;n&&(n.abortRequests(),this.removeUnbufferedFrags(n.start)),this.resetLoadingState(),r?this.setInterval(100):this.resetTransmuxer(),r?(this.switchingTrack=t,this.state=cy):(this.switchingTrack=null,this.bufferedTrack=t,this.state=ly),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(e,t){this.mainDetails=t.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(Vf.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(e,t){var r;if(null==this.mainDetails)return void(this.cachedTrackLoadedData=t);const{levels:n}=this,{details:s,id:i}=t;if(!n)return void this.warn(`Audio tracks were reset while loading level ${i}`);this.log(`Track ${i} loaded [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""},duration:${s.totalduration}`);const a=n[i];let o=0;if(s.live||null!=(r=a.details)&&r.live){const e=this.mainDetails;if(s.fragments[0]||(s.deltaUpdateFailed=!0),s.deltaUpdateFailed||!e)return;!a.details&&s.hasProgramDateTime&&e.hasProgramDateTime?(ry(s,e),o=s.fragments[0].start):o=this.alignPlaylists(s,a.details)}a.details=s,this.levelLastLoaded=i,this.startFragRequested||!this.mainDetails&&s.live||this.setStartPosition(a.details,o),this.state!==fy||this.waitForCdnTuneIn(s)||(this.state=cy),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:r,part:n,payload:s}=e,{config:i,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const c=l.details;if(!c)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(r.start);const d=i.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let u=this.transmuxer;u||(u=this.transmuxer=new Cv(this.hls,Bg,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const h=this.initPTS[r.cc],f=null==(t=r.initSegment)?void 0:t.data;if(void 0!==h){const e=!1,t=n?n.index:-1,i=-1!==t,a=new Xm(r.level,r.sn,r.stats.chunkCount,s.byteLength,t,i);u.push(s,f,d,"",r,n,c.totalduration,e,a,h)}else{this.log(`Unknown video PTS for cc ${r.cc}, waiting for video PTS before demuxing audio frag ${r.sn} of [${c.startSN} ,${c.endSN}],track ${a}`);const{cache:e}=this.waitingData=this.waitingData||{frag:r,part:n,cache:new Rv,complete:!1};e.push(new Uint8Array(s)),this.waitingVideoCC=this.videoTrackCC,this.state=vy}}_handleFragmentLoadComplete(e){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(e,t){const r=t.tracks.audio;r&&(this.mediaBuffer=r.buffer||null),t.tracks.video&&(this.videoBuffer=t.tracks.video.buffer||null)}onFragBuffered(e,t){const{frag:r,part:n}=t;if(r.type===Bg)if(this.fragContextChanged(r))this.warn(`Fragment ${r.sn}${n?" p: "+n.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if("initSegment"!==r.sn){this.fragPrevious=r;const e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(Vf.AUDIO_TRACK_SWITCHED,qf({},e)))}this.fragBufferedComplete(r,n)}else if(!this.loadedmetadata&&r.type===Ng){const e=this.videoBuffer||this.media;if(e){Qm.getBuffered(e).length&&(this.loadedmetadata=!0)}}}onError(e,t){var r;if(t.fatal)this.state=yy;else switch(t.details){case Wf.FRAG_GAP:case Wf.FRAG_PARSING_ERROR:case Wf.FRAG_DECRYPT_ERROR:case Wf.FRAG_LOAD_ERROR:case Wf.FRAG_LOAD_TIMEOUT:case Wf.KEY_LOAD_ERROR:case Wf.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Bg,t);break;case Wf.AUDIO_TRACK_LOAD_ERROR:case Wf.AUDIO_TRACK_LOAD_TIMEOUT:case Wf.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==fy||(null==(r=t.context)?void 0:r.type)!==Fg||(this.state=cy);break;case Wf.BUFFER_FULL_ERROR:if(!t.parent||"audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case Wf.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushed(e,{type:t}){t===ap&&(this.bufferFlushed=!0,this.state===my&&(this.state=cy))}_handleTransmuxComplete(e){var t;const r="audio",{hls:n}=this,{remuxResult:s,chunkMeta:i}=e,a=this.getCurrentContext(i);if(!a)return void this.resetWhenMissingContext(i);const{frag:o,part:l,level:c}=a,{details:d}=c,{audio:u,text:h,id3:f,initSegment:p}=s;if(!this.fragContextChanged(o)&&d){if(this.state=py,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),null!=p&&p.tracks){const e=o.initSegment||o;this._bufferInitSegment(p.tracks,e,i),n.trigger(Vf.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:r,tracks:p.tracks})}if(u){const{startPTS:e,endPTS:t,startDTS:r,endDTS:n}=u;l&&(l.elementaryStreams[ap]={startPTS:e,endPTS:t,startDTS:r,endDTS:n}),o.setElementaryStreamInfo(ap,e,t,r,n),this.bufferFragmentData(u,o,l,i)}if(null!=f&&null!=(t=f.samples)&&t.length){const e=Gf({id:r,frag:o,details:d},f);n.trigger(Vf.FRAG_PARSING_METADATA,e)}if(h){const e=Gf({id:r,frag:o,details:d},h);n.trigger(Vf.FRAG_PARSING_USERDATA,e)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(e,t,r){if(this.state!==py)return;e.video&&delete e.video;const n=e.audio;if(!n)return;n.levelCodec=n.codec,n.id="audio",this.log(`Init audio buffer, container:${n.container}, codecs[parsed]=[${n.codec}]`),this.hls.trigger(Vf.BUFFER_CODECS,e);const s=n.initSegment;if(null!=s&&s.byteLength){const e={type:"audio",frag:t,part:null,chunkMeta:r,parent:t.type,data:s};this.hls.trigger(Vf.BUFFER_APPENDING,e)}this.tick()}loadFragment(e,t,r){const n=this.fragmentTracker.getState(e);var s;(this.fragCurrent=e,this.switchingTrack||n===Fm||n===Nm)?"initSegment"===e.sn?this._loadInitSegment(e,t):null!=(s=t.details)&&s.live&&!this.initPTS[e.cc]?(this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=vy):(this.startFragRequested=!0,super.loadFragment(e,t,r)):this.clearTrackerIfNeeded(e)}completeAudioSwitch(e){const{hls:t,media:r,bufferedTrack:n}=this,s=null==n?void 0:n.attrs,i=e.attrs;r&&s&&(s.CHANNELS!==i.CHANNELS||s.NAME!==i.NAME||s.LANGUAGE!==i.LANGUAGE)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(Vf.AUDIO_TRACK_SWITCHED,qf({},e))}},audioTrackController:class extends Dm{constructor(e){super(e,"[audio-track-controller]"),this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Vf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Vf.LEVEL_LOADING,this.onLevelLoading,this),e.on(Vf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Vf.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Vf.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Vf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Vf.LEVEL_LOADING,this.onLevelLoading,this),e.off(Vf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Vf.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Vf.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:r,groupId:n,details:s}=t,i=this.tracksInGroup[r];if(!i||i.groupId!==n)return void this.warn(`Track with id:${r} and group:${n} not found in active group ${i.groupId}`);const a=i.details;i.details=t.details,this.log(`audio-track ${r} "${i.name}" lang:${i.lang} group:${n} loaded [${s.startSN}-${s.endSN}]`),r===this.trackId&&this.playlistLoaded(r,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(null==t||!t.audioGroupIds)return;const r=t.audioGroupIds[t.urlId];if(this.groupId!==r){this.groupId=r||null;const e=this.tracks.filter((e=>!r||e.groupId===r));this.selectDefaultTrack&&!e.some((e=>e.default))&&(this.selectDefaultTrack=!1),this.tracksInGroup=e;const t={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group:${r}`),this.hls.trigger(Vf.AUDIO_TRACKS_UPDATED,t),this.selectInitialTrack()}else this.shouldReloadPlaylist(this.currentTrack)&&this.setAudioTrack(this.trackId)}onError(e,t){!t.fatal&&t.context&&t.context.type===Fg&&t.context.id===this.trackId&&t.context.groupId===this.groupId&&(this.requestScheduled=-1,this.checkRetry(t))}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length)return void this.warn("Invalid id passed to audio-track controller");this.clearTimer();const r=this.currentTrack;t[this.trackId];const n=t[e],{groupId:s,name:i}=n;if(this.log(`Switching to audio-track ${e} "${i}" lang:${n.lang} group:${s}`),this.trackId=e,this.currentTrack=n,this.selectDefaultTrack=!1,this.hls.trigger(Vf.AUDIO_TRACK_SWITCHING,qf({},n)),n.details&&!n.details.live)return;const a=this.switchParams(n.url,null==r?void 0:r.details);this.loadPlaylist(a)}selectInitialTrack(){const e=this.tracksInGroup,t=this.findTrackId(this.currentTrack)|this.findTrackId(null);if(-1!==t)this.setAudioTrack(t);else{const t=new Error(`No track found for running audio group-ID: ${this.groupId} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(Vf.ERROR,{type:zf.MEDIA_ERROR,details:Wf.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}findTrackId(e){const t=this.tracksInGroup;for(let r=0;r<t.length;r++){const n=t[r];if(!this.selectDefaultTrack||n.default){if(!e||void 0!==e.attrs["STABLE-RENDITION-ID"]&&e.attrs["STABLE-RENDITION-ID"]===n.attrs["STABLE-RENDITION-ID"])return n.id;if(e.name===n.name&&e.lang===n.lang)return n.id}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(t)){const r=t.id,n=t.groupId;let s=t.url;if(e)try{s=e.addDirectives(s)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}this.log(`loading audio-track playlist ${r} "${t.name}" lang:${t.lang} group:${n}`),this.clearTimer(),this.hls.trigger(Vf.AUDIO_TRACK_LOADING,{url:s,id:r,groupId:n,deliveryDirectives:e||null})}}},emeController:xb,cmcdController:jb,contentSteeringController:class{constructor(e){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.log=Zf.log.bind(Zf,"[content-steering]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Vf.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Vf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Vf.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Vf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Vf.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Vf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Vf.ERROR,this.onError,this))}startLoad(){if(this.started=!0,self.clearTimeout(this.reloadTimer),this.enabled&&this.uri)if(this.updated){const e=Math.max(1e3*this.timeToLoad-(performance.now()-this.updated),0);this.scheduleRefresh(this.uri,e)}else this.loadSteeringManifest(this.uri)}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),self.clearTimeout(this.reloadTimer)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter((t=>t!==e)))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:r}=t;null!==r&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:r}=t;if((null==r?void 0:r.action)===km&&r.flags===_m){let e=this.pathwayPriority;const t=this.pathwayId;this.penalizedPathways[t]||(this.penalizedPathways[t]=performance.now()),!e&&this.levels&&(e=this.levels.reduce(((e,t)=>(-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e)),[])),e&&e.length>1&&(this.updatePathwayPriority(e),r.resolved=this.pathwayId!==t)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){const r=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${r}"`),t=this.getLevelsForPathway(r),this.pathwayId=r}return t.length!==e.length?(this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t):e}getLevelsForPathway(e){return null===this.levels?[]:this.levels.filter((t=>e===t.pathwayId))}updatePathwayPriority(e){let t;this.pathwayPriority=e;const r=this.penalizedPathways,n=performance.now();Object.keys(r).forEach((e=>{n-r[e]>3e5&&delete r[e]}));for(let n=0;n<e.length;n++){const s=e[n];if(r[s])continue;if(s===this.pathwayId)return;const i=this.hls.nextLoadLevel,a=this.hls.levels[i];if(t=this.getLevelsForPathway(s),t.length>0){this.log(`Setting Pathway to "${s}"`),this.pathwayId=s,this.hls.trigger(Vf.LEVELS_UPDATED,{levels:t});const e=this.hls.levels[i];a&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=i);break}}}clonePathways(e){const t=this.levels;if(!t)return;const r={},n={};e.forEach((e=>{const{ID:s,"BASE-ID":i,"URI-REPLACEMENT":a}=e;if(t.some((e=>e.pathwayId===s)))return;const o=this.getLevelsForPathway(i).map((e=>{const t=Gf({},e);t.details=void 0,t.url=qb(e.uri,e.attrs["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a);const i=new rp(e.attrs);i["PATHWAY-ID"]=s;const o=i.AUDIO&&`${i.AUDIO}_clone_${s}`,l=i.SUBTITLES&&`${i.SUBTITLES}_clone_${s}`;o&&(r[i.AUDIO]=o,i.AUDIO=o),l&&(n[i.SUBTITLES]=l,i.SUBTITLES=l),t.attrs=i;const c=new om(t);return Pm(c,"audio",o),Pm(c,"text",l),c}));t.push(...o),$b(this.audioTracks,r,a,s),$b(this.subtitleTracks,n,a,s)}))}loadSteeringManifest(e){const t=this.hls.config,r=t.loader;let n;this.loader&&this.loader.destroy(),this.loader=new r(t);try{n=new self.URL(e)}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${e}`)}if("data:"!==n.protocol){const e=0|(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate);n.searchParams.set("_HLS_pathway",this.pathwayId),n.searchParams.set("_HLS_throughput",""+e)}const s={responseType:"json",url:n.href},i=t.steeringManifestLoadPolicy.default,a=i.errorRetry||i.timeoutRetry||{},o={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(e,t,r,s)=>{this.log(`Loaded steering manifest: "${n}"`);const i=e.data;if(1!==i.VERSION)return void this.log(`Steering VERSION ${i.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=i.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=i;if(a)try{this.uri=new self.URL(a,n).href}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||r.url),o&&this.clonePathways(o),l&&this.updatePathwayPriority(l)},onError:(e,t,r,n)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code)return this.enabled=!1,void this.log(`Steering manifest ${t.url} no longer available`);let s=1e3*this.timeToLoad;if(429!==e.code)this.scheduleRefresh(this.uri||t.url,s);else{const e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){const t=e.getResponseHeader("Retry-After");t&&(s=1e3*parseFloat(t))}this.log(`Steering manifest ${t.url} rate limited`)}},onTimeout:(e,t,r)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}};this.log(`Requesting steering manifest: ${n}`),this.loader.load(s,o,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){self.clearTimeout(this.reloadTimer),this.reloadTimer=self.setTimeout((()=>{this.loadSteeringManifest(e)}),t)}}});function Jb(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(Jb):Object.keys(e).reduce(((t,r)=>(t[r]=Jb(e[r]),t)),{}):e}function Zb(e){const t=e.loader;if(t!==Vb&&t!==Gb)Zf.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1})()&&(e.loader=Vb,e.progressive=!0,e.enableSoftwareAES=!0,Zf.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class ew{static get version(){return"1.4.10"}static isSupported(){return function(){const e=yg();if(!e)return!1;const t=Ey(),r=e&&"function"==typeof e.isTypeSupported&&e.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),n=!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove;return!!r&&!!n}()}static get Events(){return Vf}static get ErrorTypes(){return zf}static get ErrorDetails(){return Wf}static get DefaultConfig(){return ew.defaultConfig?ew.defaultConfig:Xb}static set DefaultConfig(e){ew.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Sv,this._autoLevelCapping=void 0,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,function(e,t){if(self.console&&!0===e||"object"==typeof e){Jf(e,"debug","log","info","warn","error");try{Xf.log(`Debug logs enabled for "${t}" in hls.js version 1.4.10`)}catch(e){Xf=Qf}}else Xf=Qf}(e.debug||!1,"Hls instance");const t=this.config=function(e,t){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const r=Jb(e),n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((e=>{const s=`${"level"===e?"playlist":e}LoadPolicy`,i=void 0===t[s],a=[];n.forEach((n=>{const o=`${e}Loading${n}`,l=t[o];if(void 0!==l&&i){a.push(o);const e=r[s].default;switch(t[s]={default:e},n){case"TimeOut":e.maxLoadTimeMs=l,e.maxTimeToFirstByteMs=l;break;case"MaxRetry":e.errorRetry.maxNumRetry=l,e.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":e.errorRetry.retryDelayMs=l,e.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=l,e.timeoutRetry.maxRetryDelayMs=l}}})),a.length&&Zf.warn(`hls.js config: "${a.join('", "')}" setting(s) are deprecated, use "${s}": ${JSON.stringify(t[s])}`)})),qf(qf({},r),t)}(ew.DefaultConfig,e);this.userConfig=e,this._autoLevelCapping=-1,t.progressive&&Zb(t);const{abrController:r,bufferController:n,capLevelController:s,errorController:i,fpsController:a}=t,o=new i(this),l=this.abrController=new r(this),c=this.bufferController=new n(this),d=this.capLevelController=new s(this),u=new a(this),h=new Kg(this),f=new em(this),p=t.contentSteeringController,g=p?new p(this):null,m=this.levelController=new Om(this,g),y=new jm(this),v=new Wm(this.config),b=this.streamController=new Av(this,y,v);d.setStreamController(b),u.setStreamController(b);const w=[h,m,b];g&&w.splice(1,0,g),this.networkControllers=w;const E=[l,c,d,u,f,y];this.audioTrackController=this.createController(t.audioTrackController,w);const S=t.audioStreamController;S&&w.push(new S(this,y,v)),this.subtitleTrackController=this.createController(t.subtitleTrackController,w);const T=t.subtitleStreamController;T&&w.push(new T(this,y,v)),this.createController(t.timelineController,E),v.emeController=this.emeController=this.createController(t.emeController,E),this.cmcdController=this.createController(t.cmcdController,E),this.latencyController=this.createController(tm,E),this.coreComponents=E,w.push(o);const C=o.onErrorOut;"function"==typeof C&&this.on(Vf.ERROR,C,o)}createController(e,t){if(e){const r=new e(this);return t&&t.push(r),r}return null}on(e,t,r=this){this._emitter.on(e,t,r)}once(e,t,r=this){this._emitter.once(e,t,r)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,r=this,n){this._emitter.off(e,t,r,n)}listeners(e){return this._emitter.listeners(e)}emit(e,t,r){return this._emitter.emit(e,t,r)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){Zf.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),this.trigger(Vf.ERROR,{type:zf.OTHER_ERROR,details:Wf.INTERNAL_EXCEPTION,fatal:!1,event:e,error:t})}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){Zf.log("destroy"),this.trigger(Vf.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach((e=>e.destroy())),this.networkControllers.length=0,this.coreComponents.forEach((e=>e.destroy())),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){Zf.log("attachMedia"),this._media=e,this.trigger(Vf.MEDIA_ATTACHING,{media:e})}detachMedia(){Zf.log("detachMedia"),this.trigger(Vf.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const t=this.media,r=this.url,n=this.url=jf.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});Zf.log(`loadSource:${n}`),t&&r&&(r!==n||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(Vf.MANIFEST_LOADING,{url:e})}startLoad(e=-1){Zf.log(`startLoad(${e})`),this.networkControllers.forEach((t=>{t.startLoad(e)}))}stopLoad(){Zf.log("stopLoad"),this.networkControllers.forEach((e=>{e.stopLoad()}))}swapAudioCodec(){Zf.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){Zf.log("recoverMediaError");const e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e,t=0){this.levelController.removeLevel(e,t)}get levels(){const e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){Zf.log(`set currentLevel:${e}`),this.loadLevel=e,this.abrController.clearTimer(),this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){Zf.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){Zf.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){Zf.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){return this.levelController.startLevel}set startLevel(e){Zf.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(Zf.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e)}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){rm.indexOf(e)>-1&&(this._maxHdcpLevel=e)}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const r=e.length;for(let n=0;n<r;n++)if(e[n].maxBitrate>=t)return n;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:r}=this;let n;if(n=-1===t&&e&&e.length?e.length-1:t,r)for(let t=n;t--;){const n=e[t].attrs["HDCP-LEVEL"];if(n&&n<=r)return t}return n}get nextAutoLevel(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)}set nextAutoLevel(e){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,e)}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}ew.defaultConfig=void 0;const tw={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};function rw(e){const t=new Uint8Array(e);let r="";return t.forEach((e=>{r+=String.fromCharCode(e)})),F(r)}function nw(e){const t=e.substring("-----BEGIN PRIVATE KEY-----".length,e.length-"-----END PRIVATE KEY-----".length),r=function(e){const t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0,n=e.length;t<n;t+=1)r[t]=e.charCodeAt(t);return t}(K(t));return crypto.subtle.importKey("pkcs8",r,tw,!1,["sign"])}async function sw({bufferCurrentUsage:e,getActiveStreams:t,updateUsage:r,dispose:n}){const s=e();if(s.length)try{const r=(new Date).toISOString(),i=await async function({timestamp:e,streams:t}){const r=t.map((e=>Object.keys(e).sort().map((t=>`${t}=${e[t]}`)).join("&"))).join(";"),n=ko.v4(),s=`nonceStr=${n}&timestamp=${e}&data=${r}==`,i=(new TextEncoder).encode(s),a=await nw("-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDHo80SecH7FuF2\nhFYnb+l26/VN8UMLXAQFLnxciNTEwkGVFMpdezlH8rU2HtUJL4RETogbAOLVY0XM\njs6sPn8G1nALmh9qeDpUtVqFOVtBHxEZ910TLOtQiunjqJKO5nWdqZ71EC3OFluR\niGQkO84BiIFbv37ub7xl3S8XarbtKoLcyVpkDHi+1wx1pgCAn6gtBUgckPL5NR8j\nLseabl3HAXQfhTCKo4tmOFM2Dxwl1IUMmIJrJg/aIU/U0tj/1Eoo7mG0JcNWX19l\nW3EecCbi0ncCJOrkUdwlBrcjaMayaX/ubEwyUeTGiLdyc4L3GRLHjyK8xgVNXRMH\nbZWJ2a5NAgMBAAECggEASxuE+35zTFO/XydKgmvIGcWL9FbgMlXb7Vcf0nBoG945\nbiz0NVc2paraIhJXc608xbYF3qLmtAE1MVBI0ORyRdBHNxY024l/6H6SH60Ed+uI\nM4ysp5ourY6Vj+DLwpdRiI9YDjqYAQDIUmhNxJP7XPhOMoZI6st+xZQBM34ic/bv\nAMSJm9OZphSp3+qXVkFZztr2mxD2EZSJJLYxi8BCdgM2qhazalbcJ6zDKHCZWVWm\n8RRxDGldyMb/237JxETzP40tAlzOZDmBAbUgEnurDJ93RVDIE3rbZUshwgeQd18a\nem096mWgvB1AIKYgsTAR3pw+V19YWAjq/glP6fz8wQKBgQD/oQq+ukKF0PRgBeM5\ngeTjSwsdGppQLmf5ndujvoiz/TpdjDEPu6R8kigQr1rG2t4K/yfdZoI8RdmJD1al\n3Q7N9hofooSy4rj6E3txzWZCHJjHad2cnCp/O26HiReGAl7wTcfTmNdiFHhZQzm5\nJBkvWAiwuvQMNfEbnXxw6/vIDwKBgQDH7fX8gsc77JLvAWgp1MaQN/sbqVb6JeT1\nFQfR8E/WFCSmzQBtNzd5KgYuCeelwr/8DyYytvN2BzCYZXp73gI1jF3YlW5jVn74\nOY6TwQ095digwo6Z0yuxopdIOApKgAkL9PRKgNrqAf3NAyMua6lOGifzjDojC3KU\nfylQmxMn4wKBgHp2B9O/H0dEBw5JQ8W0+JX6yWQz7mEjGiR2/1W+XXb8hQ1zr709\nw1r6Gb+EghRpnZ3fBpYGGbYOMFx8wKHM+N6qW3F0ReX8v2juFGE8aRSa5oYBrWzt\nU16Idjbv8hj84cZ1PJmdyvDtpYn9rpWHOZl4rxEbPvbqkIsOMyNVqdT5AoGAOSge\nmwIIU2le2FVeohbibXiToWTYKMuMmURZ5/r72AgKMmWJKbAPe+Q3wBG01/7FRBpQ\noU8Ma0HC8s6QJbliiEyIx9JwrJWd1vkdecBHONrtA4ibm/5zD2WcOllLF+FitLhi\n3qnX6+6F0IaFGFBPJrTzlv0P4dTz/OAdv52V7GECgYEA2TttOKBAqWllgOaZOkql\nLVMJVmgR7s6tLi1+cEP8ZcapV9aRbRzTAKXm4f8AEhtlG9F9kCOvHYCYGi6JaiWJ\nZkHjeex3T+eE6Di6y5Bm/Ift5jtVhJ4jCVwHOKTMej79NPUFTJfv8hCo29haBDv6\nRXFrv+T21KCcw8k3sJeJWWQ=\n-----END PRIVATE KEY-----");return{signature:rw(await crypto.subtle.sign(tw,a,i)),nonceStr:n}}({timestamp:r,streams:s});if(!i||!i.signature)throw new Error("Signature is undefined");const a={signature:i.signature,nonceStr:i.nonceStr,timestamp:r,streams:s},o=ve();return await o.http.post("/api/v3/user-event/video-streaming",a),t().length||e().length||n(),!0}catch(e){return s.forEach((e=>r(e))),!1}}class iw{constructor(){this._unsyncedData=[],this._syncBuffer=[],this._activeStreams=[],this._startInterval(),this._syncInterval=null}registerStream(e){this._activeStreams.push(e)}getActiveStreams(){return this._activeStreams}unregisterStream(e){this._activeStreams=this._activeStreams.filter((t=>t!==e))}updateUsage(e){this._unsyncedData.push(e)}bufferCurrentUsage(){const e=this._unsyncedData;return this._unsyncedData=[],e}dispose(){this._syncInterval&&clearInterval(this._syncInterval)}_startInterval(){this._syncInterval=setInterval((()=>{sw({bufferCurrentUsage:this.bufferCurrentUsage.bind(this),getActiveStreams:this.getActiveStreams.bind(this),updateUsage:this.updateUsage.bind(this),dispose:this.dispose.bind(this)})}),2e4)}}let aw=null;class ow{constructor(e,t){this.player=e,this.resolution=t,this._startTime=null,this._usageCollector=aw||(aw=new iw,aw),this._usageCollector.registerStream(e.id),this._sessionId=String(ko.v4()),this._controller=new AbortController,this._observer=new MutationObserver((t=>{t.forEach((t=>{t.removedNodes.forEach((t=>{t===e&&this._unregisterEvents()}))}))}))}_resetStartTime(){this._startTime=Date.now()}_shouldUpdateCollector(){return!!this._startTime&&Date.now()-this._startTime>2e4}_sendUsageToCollector(){if(!this._startTime)return;const e=Date.now(),t=e-this._startTime,r=Math.round(t/1e3);r&&this._usageCollector.updateUsage({streamId:this.player.id,sessionId:this._sessionId,startTime:this._startTime?new Date(this._startTime).toISOString():null,endTime:new Date(e).toISOString(),watchSeconds:r,resolution:this.resolution})}registerEvents(){this.player.addEventListener("play",(()=>{this._startTime||this._resetStartTime()}),{signal:this._controller.signal}),this.player.addEventListener("playing",(()=>{this._startTime||this._resetStartTime()}),{signal:this._controller.signal}),this.player.addEventListener("timeupdate",(()=>{this._shouldUpdateCollector()&&(this._sendUsageToCollector(),this._resetStartTime())}),{signal:this._controller.signal}),this.player.addEventListener("pause",(()=>{this._sendUsageToCollector(),this._startTime=null}),{signal:this._controller.signal}),this.player.addEventListener("ended",(()=>{this._sendUsageToCollector(),this._startTime=null}),{signal:this._controller.signal})}_unregisterEvents(){this._usageCollector.unregisterStream(this.player.id),this._controller.abort(),this._observer.disconnect()}}var lw=Object.freeze({__proto__:null,getPlayer:async e=>{const{streamId:t}=e;if(!document)throw new Error("This method can be invoked within the browser enviornment only");if(!ew.isSupported())throw new Error("This browswer does not support hls, unable to play stream");const{data:r}=await If(t),{watcherUrl:n,status:s,recordings:i=[],resolution:a}=r;if(!n.hls)throw new Error("This stream does not support hls. Unable to play");const o=document.createElement("video");o.id=t,o.controls=!0;const l=new ew;if(l.attachMedia(o),"recorded"!==s){let{url:e}=n.hls;e=e.replace("http:","https:"),l.loadSource(e)}else{const e=i.find((e=>!!e.mp4));if(!e||!e.mp4)throw new Error("No playable recording available");o.src=e.mp4.url}return new ow(o,a).registerEvents(),o}});const cw=e=>{const t=(e=>{var t;const r=ve(),n=new Date,s=n.getTime()+31536e6,i=new Date(s).toISOString();let a=null===(t=Ee(["storyTarget","get",e.targetId]))||void 0===t?void 0:t.data;return a||(a={targetType:e.targetType,targetId:e.targetId,lastStoryExpiresAt:i,targetPublicId:e.targetId,targetUpdatedAt:n.toISOString()},Oo({storyTargets:[a]})),{stories:[Object.assign({createdAt:n.toISOString(),updatedAt:n.toISOString(),flagCount:0,hashFlag:null,reactions:{},reactionsCount:0,storyId:e.referenceId,path:"",creatorId:r.userId||"",creatorPublicId:r.userId||"",targetPublicId:e.targetId,comments:[],commentsCount:0,isDeleted:!1,hasFlaggedComment:!1,mentionedUsers:[],impression:0,reach:0,expiresAt:new Date(s).toISOString()},e)],categories:[],communityUsers:[],comments:[],files:[],users:[],communities:[]}})(e);return Oo(t),t},dw=({payload:e,formData:t,isVideo:r=!1},n)=>{if(t){const s=t.get("files"),i=new FileReader;i.readAsDataURL(s),i.onload=()=>n(cw(r?Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileId:void 0,videoFileId:{original:void 0},fileData:null==i?void 0:i.result})}):Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileId:void 0,fileData:null==i?void 0:i.result})})))}return n(cw(Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileData:null})})))},uw=async e=>{const t=ve();t.log("post/createStory",e);const r=await t.http.post("/api/v4/stories",e),n=Ef(r.data);t.cache&&Oo(n),Se(["story-sync-state",e.targetId],"synced"),Je("local.story.created",n);const s=t.cache&&Date.now();return{data:n.stories.length>0?n.stories[0]:void 0,cachedAt:s}},hw=e=>e?Ee(["story","get",e]):{data:void 0,cachedAt:void 0},fw=async(e,t=!1)=>{const r=ve();let n;if(r.log("story/deleteStory",e),r.cache&&(n=hw(e),null==n?void 0:n.data)){const{data:e}=n;Je("local.story.deleted",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[Object.assign(Object.assign({},e),{isDeleted:!0})]})}return(await r.http.delete(`/api/v4/stories/${e}`,{params:{permanent:t}})).data.success},pw=e=>{const t=ve(),r=[Xe(t,"onStoryUpdated","story.updated",(async t=>{const r=Ef(t);Oo(r),e(r.stories)}))];return()=>{r.forEach((e=>e()))}},gw=e=>{const t=ve(),r=[Xe(t,"onStoryUpdated","local.story.updated",(async t=>{Oo(t),e(t.stories)}))];return()=>{r.forEach((e=>e()))}},mw=e=>{const t=ve(),r=[Xe(t,"onStoryReactionAdded","story.reactionAdded",(async t=>{const{reactions:r}=t,n=Mo(t,["reactions"]),s=Ef(n),i=iu("story.reactionAdded",Object.assign(Object.assign({},s),{reactions:r}));Oo(i),e(i.stories)}))];return()=>{r.forEach((e=>e()))}},yw=e=>{const t=ve(),r=[Xe(t,"onStoryReactionAdded","local.story.reactionAdded",(async t=>{Oo(t),e(t.stories)}))];return()=>{r.forEach((e=>e()))}},vw=e=>{const t=ve(),r=[Xe(t,"onStoryReactionRemoved","story.reactionRemoved",(async t=>{const{reactions:r}=t,n=Mo(t,["reactions"]),s=Ef(n),i=iu("story.reactionRemoved",Object.assign(Object.assign({},s),{reactions:r}));Oo(i),e(i.stories)}))];return()=>{r.forEach((e=>e()))}},bw=e=>{const t=ve(),r=[Xe(t,"onStoryReactionRemoved","local.story.reactionRemoved",(async t=>{Oo(t),e(t.stories)}))];return()=>{r.forEach((e=>e()))}},ww=e=>{e.forEach((e=>{const t=Ee(["story-expire",e.targetId]),r=new Date(e.expiresAt||0);r<new Date((null==t?void 0:t.data)||0)||Se(["story-expire",e.targetId],r.toISOString())}))},Ew=e=>{e.forEach((e=>{Se(["story-reference",e.storyId],e.referenceId)}))},Sw=async({targetType:e,targetId:t,options:r})=>{const n=ve();n.log("story/getActiveStoriesByTarget");const s=n.cache&&Date.now(),i=await n.http.get("/api/v4/stories",{params:{targetType:e,targetId:t,options:{sortBy:(null==r?void 0:r.sortBy)||"createdAt",orderBy:(null==r?void 0:r.orderBy)||"desc"}}}),a=Ef(i.data);return n.cache&&(Oo(a),ww(a.stories),Ew(a.stories)),{data:a.stories,cachedAt:s,paging:{next:void 0,previous:void 0}}},Tw=e=>{const t=ve(),r=[Xe(t,"onStoryCreated","story.created",(async t=>{const r=Ef(t,!0);Oo(r),e(r.stories)}))];return()=>{r.forEach((e=>e()))}},Cw=e=>{const t=ve(),r=[Xe(t,"onStoryCreated","local.story.created",(async t=>{Oo(t),e(t.stories)}))];return()=>{r.forEach((e=>e()))}},kw=e=>{const t=ve(),r=[Xe(t,"onStoryDeleted","story.deleted",(async t=>{const r=Ef(t);Oo(r),e(r.stories)}))];return()=>{r.forEach((e=>e()))}},Aw=e=>{const t=ve(),r=[Xe(t,"onStoryDeleted","local.story.deleted",(async t=>{Oo(t),e(t.stories)}))];return()=>{r.forEach((e=>e()))}},Iw=e=>{const t=ve();return Xe(t,"onStoryError","local.story.error",(async t=>{Oo(t),e(t.stories)}))},_w=e=>t=>e((e=>t(e[0]))),Rw=async e=>{const t=ve();t.log("story/getTargetsByTargetIds",e);const r=await t.http.get("/api/v4/stories/seen",{params:{targets:e}}),{data:n}=r;return t.cache&&Oo(r.data),{data:n.storyTargets,cachedAt:Date.now()}};class Lw extends ah{constructor(e,t,r,n){super(e,t),this.notifyChange=r,this.paginationController=n}saveToMainDB(e){const t=ve(),r=t.cache&&Date.now(),n=Ef(e);t.cache&&(Oo(n,{cachedAt:r}),ww(n.stories),Ew(n.stories))}getStoryReferenceIds(e){return(null==e?void 0:e.referenceId)?e.referenceId:e.storyId}appendToQueryStream(e,t,r=!1){var n,s;if(r)Se(this.cacheKey,{data:e.stories.map(this.getStoryReferenceIds)});else{const t=null===(n=Ee(this.cacheKey))||void 0===n?void 0:n.data,r=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...r,...e.stories.map(this.getStoryReferenceIds)])]}))}}reactor(e){return e=>{var t;const r=null===(t=Ee(this.cacheKey))||void 0===t?void 0:t.data;if(!r)return;const n=e.map((({referenceId:e})=>e));r.data=[...new Set([...n,...r.data])],Se(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Dw extends lh{async getRequest(e){const{data:t}=await this.http.get("/api/v4/stories-by-targets",{params:Object.assign({},e)});return t}}class xw extends ch{constructor(e,t){const r=nh(e),n=["story-target-ids","collection",r],s=new Dw(e);super(s,r,n,t),this.query=e,this.queryStreamController=new Lw(this.query,this.cacheKey,this.notifyChange.bind(this),s),this.paginationController=s,this.callback=t.bind(this),this.loadPage(!0)}setup(){var e;(null===(e=Ee(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}persistModel(e){this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:r}){this.queryStreamController.appendToQueryStream(e,t,r)}notifyChange({origin:e,loading:t,error:r}){var n;const s=null===(n=Ee(this.cacheKey))||void 0===n?void 0:n.data;if(!s)return;let i=s.data.map((e=>Ee(["story","get",e]))).filter(Boolean).map((e=>il.story(e.data)));(this.shouldNotify(i)||"event"!==e)&&(i=this.applyFilter(i),this.callback({onNextPage:void 0,data:i,hasNextPage:!1,loading:t,error:r}))}applyFilter(e){var t,r;const n=e;return"asc"===((null===(r=null===(t=this.query)||void 0===t?void 0:t.options)||void 0===r?void 0:r.orderBy)||"desc")?n.sort(Fe):n.sort(Ne)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Tw,action:"onCreate"},{fn:pw,action:"onUpdate"},{fn:kw,action:"onDelete"},{fn:Iw,action:"onError"}])}}const Ow=(e,t)=>{var r,n;const s=null===(r=Ee(e))||void 0===r?void 0:r.data,i=null!==(n=null==s?void 0:s.data)&&void 0!==n?n:[];Se(e,Object.assign(Object.assign({},s),{data:[...new Set([...i,...t])]}))};class Pw extends ah{constructor(e,t,r,n){super(e,t),this.notifyChange=r,this.paginationController=n,this.preparePayload=e=>e}saveToMainDB(e){const t=ve(),r=t.cache&&Date.now(),n=this.preparePayload(e);t.cache&&Oo(n,{cachedAt:r})}appendToQueryStream(e,t,r=!1){r?Se(this.cacheKey,{data:e.storyTargets.map((({targetId:e})=>e))}):Ow(this.cacheKey,e.storyTargets.map((({targetId:e})=>e)))}reactor(e){return t=>{"onCreate"===e&&"seen"!==this.query.seenState&&Ow(this.cacheKey,t.map((({targetId:e})=>e))),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Mw extends sh{constructor(){super(...arguments),this.smartFilterState="unseen"}async getRequest(e,t){var r;const{limit:n=10,seenState:s="unseen"}=e,i=await this.createRequest({seenState:"smart"===s?this.smartFilterState:s,limit:n,token:t});if(null===(r=i.paging)||void 0===r?void 0:r.next)return i;if("smart"!==s)return i;if("seen"===this.smartFilterState)return i;this.smartFilterState="seen";const a=await this.createRequest({seenState:this.smartFilterState,limit:n});return l=a,{categories:(o=i).categories.concat(l.categories),communities:o.communities.concat(l.communities),communityUsers:o.communityUsers.concat(l.communityUsers),files:o.files.concat(l.files),storyTargets:o.storyTargets.concat(l.storyTargets),users:o.users.concat(l.users),paging:l.paging};var o,l}async createRequest(e){const{data:t}=await this.http.get("/api/v5/me/global-story-targets",{params:e});return r=t,n=e.seenState,Object.assign(Object.assign({},r),{storyTargets:r.storyTargets.map((e=>Object.assign(Object.assign({},e),{localFilter:n})))||[]});var r,n}}class Fw extends ch{constructor(e,t){const r=nh(e),n=["story-global-feed","collection",r],s=new Mw(e);super(s,r,n,t),this.query=e,this.queryStreamController=new Pw(this.query,this.cacheKey,this.notifyChange.bind(this),s),this.paginationController=s,this.callback=t.bind(this),this.loadPage(!0)}setup(){var e;(null===(e=Ee(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}persistModel(e){this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:r}){this.queryStreamController.appendToQueryStream(e,t,r)}notifyChange({origin:e,loading:t,error:r}){var n;const s=null===(n=Ee(this.cacheKey))||void 0===n?void 0:n.data;if(!s)return;let i=s.data.map((e=>Ee(["storyTarget","get",e]))).filter(Boolean).map((e=>il.storyTarget(e.data)));(this.shouldNotify(i)||"event"!==e)&&(i=this.applyFilter(i).map((e=>Mo(e,["localFilter","localLastExpires","localLastSeen","localSortingDate"]))),this.callback({onNextPage:()=>this.loadPage(!1,"next"),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:r}))}applyFilter(e){if("smart"!==this.query.seenState)return e.filter((({hasUnseen:e})=>"all"===this.query.seenState||("seen"===this.query.seenState&&!e||"unseen"===this.query.seenState&&e))).sort(Ue);const t=e.reduce(((e,t)=>("unseen"===t.localFilter?e.unseen.push(t):"seen"===t.localFilter?e.seen.push(t):e.unknown.push(t),e)),{unseen:[],seen:[],unknown:[]}),r=t.unknown.sort(Ue)||[],n=t.unseen.sort(Ue)||[],s=t.seen.sort(Ue)||[];return r.concat(n,s)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Tw,action:"onCreate"},{fn:pw,action:"onUpdate"},{fn:kw,action:"onDelete"},{fn:Cw,action:"onCreate"},{fn:gw,action:"onUpdate"},{fn:Aw,action:"onDelete"},{fn:Iw,action:"onError"}])}}var Uw=Object.freeze({__proto__:null,createImageStory:async(e,t,r,n={},s="fit",i=[])=>{if(!r.getAll("files").length)throw new Error("The formData object must have a `files` key.");let a={data:{text:"",fileId:void 0,fileData:null,imageDisplayMode:s},syncState:"syncing",referenceId:Ao(),dataType:"image",items:i,targetType:e,targetId:t,metadata:n};const o=new Date;Se(["story-sync-state",t],"syncing"),Se(["story-expire",t],new Date(o.setFullYear(o.getFullYear()+1))),dw({payload:a,formData:r},(e=>{Je("local.story.created",e)}));try{const{data:e}=await zd(r);if(0===e.length)throw new Error("Failed to upload image");const{fileId:t}=e[0];a=Object.assign(Object.assign({},a),{data:Object.assign(Object.assign({},a.data),{fileId:t})}),dw({payload:a,formData:r},(e=>{Je("local.story.created",e)}));const n=await uw(a);return n.data?Object.assign(Object.assign({},n),{data:il.story(n.data)}):n}catch(e){throw Se(["story-sync-state",t],"error"),dw({payload:Object.assign(Object.assign({},a),{syncState:"error"}),formData:r},(e=>{Je("local.story.error",e)})),e}},createVideoStory:async(e,t,r,n={},s=[])=>{if(!r.getAll("files").length)throw new Error("The formData object must have a `files` key.");let i={data:{text:"",fileId:void 0,fileData:null},syncState:"syncing",referenceId:Ao(),dataType:"video",items:s,targetType:e,targetId:t,metadata:n};const a=new Date;Se(["story-sync-state",t],"syncing"),Se(["story-expire",t],new Date(a.setFullYear(a.getFullYear()+1))),dw({payload:i,formData:r,isVideo:!0},(e=>{Je("local.story.created",e)}));try{const{data:e}=await Vd(r,l.STORY);if(0===e.length)throw new Error("Failed to upload video");const{fileId:t}=e[0];i=Object.assign(Object.assign({},i),{data:Object.assign(Object.assign({},i.data),{fileId:t,videoFileId:{original:t}})}),dw({payload:i,formData:r,isVideo:!0},(e=>{Je("local.story.created",e)}));const n=await uw(i);return n.data?Object.assign(Object.assign({},n),{data:il.story(n.data)}):n}catch(e){throw Se(["story-sync-state",t],"error"),dw({payload:Object.assign(Object.assign({},i),{syncState:"error"}),formData:r,isVideo:!0},(e=>{Je("local.story.error",e)})),e}},hardDeleteStory:async e=>await fw(e,!0),softDeleteStory:async e=>await fw(e),getActiveStoriesByTarget:(e,t)=>{const{log:r,cache:n}=ve(),s=[],i=["story-target","collection",e],a=Date.now();r(`getActiveStoriesByTarget(tmpid: ${a}) > listen`),n||console.log(p);const o=t=>{var r,n;const s=(null===(r=e.options)||void 0===r?void 0:r.sortBy)||"createdAt",i=(null===(n=e.options)||void 0===n?void 0:n.orderBy)||"desc";return 0===t.length?[]:"createdAt"===s?"asc"===i?t.sort(Fe):t.sort(Ne):"asc"===i?t.sort(Be):t.sort(je)},l=e=>{var r;const n=e.data.map((e=>{const t=hw(e);if(null==t?void 0:t.data)return il.story(t.data)})).filter(Boolean).filter((e=>!!e&&!e.isDeleted)),s=[];if(n.length>0){const e=n.reduce(((e,t)=>{if(!t)return e;const{syncState:r}=t;if(!r)return e;let n=e.get(r);return n||(n=[]),n.push(t),e.set(r,n),e}),new Map);if(e.has("error")){const t=o(e.get("error")||[]);s.push(...t)}if(e.has("syncing")){const t=o(e.get("syncing")||[]);s.push(...t)}if(e.has("synced")){const t=o(e.get("synced")||[]);s.push(...t)}}t({onNextPage:()=>!1,data:s||n,hasNextPage:!!(null===(r=e.params)||void 0===r?void 0:r.page),loading:e.loading||!1})},c=(e,t,r=!1,n=!1,s=!1)=>{const a=Ee(i),o={loading:n,error:s,params:{page:void 0},data:(null==a?void 0:a.data)||[]};if(e)if("onDelete"===t){const t=e.map((({referenceId:e})=>e));o.data=o.data.filter((e=>!t.includes(e)))||[]}else o.data=r?e.map(de("story")):[...new Set([...o.data,...e.map(de("story"))])];Se(i,o.data),l(o)},d=e=>t=>{c(t,e)};return(t=>{const r=ie(Sw,e);oe(r,(({data:e,error:r,loading:n})=>{c(e,"fetch",t,n,r)}))})(!0),s.push(Tw(d("onCreate")),pw(d("onUpdate")),kw(d("onDelete")),mw(d("onReactionAdded")),vw(d("onReactionRemoved")),Iw(d("onError")),Cw(d("onCreate")),gw(d("onUpdate")),Aw(d("onDelete")),yw(d("onReactionAdded")),bw(d("onReactionRemoved")),(e=>{const t=ve();return Xe(t,"onStoryLocalDataUpdated","local.story.reload",(t=>{e(t)}))})((e=>{const t=Ee(i);if(!t)return;if(0===e.referenceIds.length||0===(null==t?void 0:t.data.length))return;if(!(null==t?void 0:t.data.find((t=>e.referenceIds.includes(t)))))return;const r={loading:!1,error:!1,params:{page:void 0},data:(null==t?void 0:t.data)||[]};l(r)})),(()=>ke(i))),()=>{r(`getActiveStoriesByTarget(tmpid: ${a}) > dispose`),s.forEach((e=>e()))}},getStoryByStoryId:(e,t)=>pd(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:il.story(e.data)})):t(e)}),"storyId",Sf,[_w(pw),_w(kw),_w(mw),_w(vw),_w(Iw),_w(gw),_w(Aw),_w(yw),_w(bw)]),getTargetById:(e,t)=>pd(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:il.storyTarget(e.data[0])})):t(e)}),"query",(e=>Rw([e])),[]),getTargetsByTargetIds:(e,t)=>{const{log:r,cache:n}=ve(),s=[],i=["storyTargets","collection",e],a=Date.now();r(`getTargetsByTargetIds(tmpid: ${a}) > listen`),n||console.log(p);const o=(e,r=!1,n=!1,s=!1)=>{const a=Ee(i),o={loading:n,error:s,params:{page:void 0},data:[]};e&&(o.data=r?e.map(de("storyTarget")):[...new Set([...(null==a?void 0:a.data)||[],...e.map(de("storyTarget"))])]),Se(i,o.data),(e=>{var r;const n=e.data.map((e=>{const t=Ee(["storyTarget","get",e]);if(null==t?void 0:t.data)return il.storyTarget(t.data)})).filter(Boolean);t({onNextPage:void 0,data:n,hasNextPage:!!(null===(r=e.params)||void 0===r?void 0:r.page),loading:e.loading||!1})})(o)};return(t=>{const r=ie(Rw,e);oe(r,(({data:e,error:r,loading:n})=>{o(e,t,n,r)}))})(!0),s.push((()=>ke(i))),()=>{r(`getTargetsByTargetIds(tmpid: ${a}) > dispose`),s.forEach((e=>e()))}},getStoriesByTargetIds:(e,t,r)=>{const{log:n,cache:s,userId:i}=ve();s||console.log(p);const a=Date.now();n(`getStoriesByTargetIds(tmpid: ${a}) > listen`);const o=new xw(e,t),l=o.startSubscription(),c=o.getCacheKey();return l.push((()=>{ke(c)})),()=>{n(`getStoriesByTargetIds(tmpid: ${a}) > dispose`),l.forEach((e=>e()))}},getGlobalStoryTargets:(e,t,r)=>{const{log:n,cache:s,userId:i}=ve();s||console.log(p);const a=Date.now();n(`getGlobalStoryTarget(tmpid: ${a}) > listen`);const o=new Fw(e,t),l=o.startSubscription(),c=o.getCacheKey();return l.push((()=>{ke(c)})),()=>{n(`getGlobalStoryTarget(tmpid: ${a}) > dispose`),l.forEach((e=>e()))}}});return e.API_REGIONS=At,e.CategoryRepository=hf,e.ChannelRepository=Rh,e.Client=gd,e.CommentRepository=Af,e.CommunityPostSettingMaps=a,e.CommunityPostSettings=i,e.CommunityRepository=cf,e.ContentFeedType=l,e.DefaultCommunityPostSetting=o,e.FeedRepository=gf,e.FileRepository=Wd,e.FileType=t,e.LiveStreamPlayer=lw,e.MessageContentType=c,e.MessageRepository=hh,e.PollRepository=Uf,e.PostContentType=d,e.PostRepository=bf,e.ReactionRepository=Ru,e.StoryRepository=Uw,e.StreamRepository=Of,e.SubChannelRepository=vh,e.UserRepository=Gd,e.VERSION=u,e.VideoResolution=r,e.VideoSize=s,e.VideoTranscodingStatus=n,e.backupCache=async(e="amitySdk",t=(e=>e.offline))=>{const{log:r,cache:n,userId:s}=ve();if(!n)return!1;r("cache/api/backupCache",{storageKey:e});const i=Object.fromEntries(Object.entries(n.data).filter((([e,r])=>t(r))));return!!Object.keys(i).length&&(localStorage&&await localStorage.setItem(`${e}#${s}`,JSON.stringify(i)),!0)},e.createQuery=ie,e.createReport=async(e,t)=>{const r=ve();r.log("report/createReport",{referenceType:e,referenceId:t});const{data:n}=await r.http.post((()=>{if("user"===e)return`/api/v4/me/flags/${encodeURIComponent(t)}`;if("message"===e)return`/api/v5/messages/${encodeURIComponent(t)}/flags`;const{domainName:r}=Lu[e];return`/api/v3/${r}/${encodeURIComponent(t)}/flag`})());if(r.cache)if("message"===e){const e=await Ol(n);Oo(e)}else Oo("post"===e?Uo(n,"communityUsers"):n);return Je(`${e}.flagged`,n),!!n},e.createUserToken=async(e,t,r)=>{const n=await _o(),s=Ro(),i=hn(_t("http",t)),{data:a}=await i.post("/api/v4/sessions",Object.assign(Object.assign({},r),{deviceId:n,deviceInfo:Object.assign(Object.assign({},s),{model:"token management API on TS-SDK"})}),{headers:{"X-API-Key":e}});return{accessToken:a.accessToken}},e.deleteReport=async(e,t)=>{const r=ve();r.log("report/deleteReport",{referenceType:e,referenceId:t});const{data:n}=await r.http.delete((()=>{if("user"===e)return`/api/v4/me/flags/${encodeURIComponent(t)}`;if("message"===e)return`/api/v5/messages/${encodeURIComponent(t)}/flags`;const{domainName:r}=Lu[e];return`/api/v3/${r}/${encodeURIComponent(t)}/unflag`})());if(r.cache)if("message"===e){const e=await Ol(n);Oo(e)}else Oo("post"===e?Uo(n,"communityUsers"):n);return Je(`${e}.unflagged`,n),!!n},e.disableCache=()=>{const e=ve();e.cache&&(e.log("cache/api/disableCache"),delete e.cache)},e.dropFromCache=ke,e.enableCache=(e={},t)=>{const r=ve();r.cache||(r.log("cache/api/enableCache"),r.cache={data:e,persistIf:t})},e.filterByChannelMembership=Re,e.filterByCommunityMembership=De,e.filterByFeedType=Le,e.filterByPostDataTypes=xe,e.filterByPropEquality=Ae,e.filterByPropInclusion=(e,t,r)=>void 0!==r?e.filter((e=>r.includes(e[t]))):e,e.filterByPropIntersection=_e,e.filterBySearchTerm=Oe,e.filterByStringComparePartially=Ie,e.getChannelTopic=e=>`${e.path}/#`,e.getCommentTopic=({path:e})=>e,e.getCommunityStoriesTopic=({targetId:e,targetType:t})=>{const r=Ke();return`${st(r)}/social/${t}/${e}/story/#`},e.getCommunityTopic=({path:t},r=e.SubscriptionLevels.COMMUNITY)=>nt(t,r),e.getMarkedMessageTopic=at,e.getMarkerUserFeedTopic=ot,e.getMessageTopic=e=>e.path,e.getMyFollowersTopic=()=>{const e=Ke();return`${st(e)}/membership/${e._id}/+/+`},e.getMyFollowingsTopic=()=>{const e=Ke();return`${st(e)}/membership/+/${e._id}/+`},e.getNetworkTopic=lt,e.getPostTopic=({path:t},r=e.SubscriptionLevels.POST)=>"comment"===r?`${t}/comment/+`:t,e.getRole=Qd,e.getSmartFeedChannelTopic=ct,e.getSmartFeedMessageTopic=ut,e.getSmartFeedSubChannelTopic=dt,e.getStoryTopic=({targetId:e,targetType:t,storyId:r})=>{const n=Ke();return`${st(n)}/social/${t}/${e}/story/${r}/#`},e.getSubChannelTopic=e=>`${e.path}/#`,e.getUserTopic=it,e.isAfterBefore=W,e.isAfterBeforeRaw=Y,e.isCachable=ne,e.isFetcher=ee,e.isFresh=se,e.isLocal=e=>ne(e)&&-1===(null==e?void 0:e.cachedAt),e.isMutator=te,e.isOffline=re,e.isPaged=Q,e.isReportedByMe=async(e,t)=>{var r;const n=ve();n.log("report/isReportedByMe",{referenceType:e,referenceId:t});const{domainName:s}=Lu[e];if("message"===e){const{data:e}=await n.http.get(`/api/v5/messages/${encodeURIComponent(t)}/flags`);return e.result}const{data:i}=await n.http.get(`/api/v3/${s}/${t}/isflagbyme`),{result:a,isFlagByMe:o}=null!=i?i:{};return null!==(r=null!=a?a:o)&&void 0!==r&&r},e.isSkip=z,e.mergeInCache=Te,e.onChannelMarkerFetched=id,e.onFeedMarkerFetched=e=>{const t=ve();return Xe(t,"feedMarker/onFeedMarkerFetched","local.feedMarker.fetched",(t=>{e(t.feedMarkers[0])}))},e.onFeedMarkerUpdated=Lc,e.onMessageMarked=ud,e.onMessageMarkerFetched=dd,e.onSubChannelMarkerFetched=ad,e.onSubChannelMarkerUpdated=od,e.onUserMarkerFetched=ld,e.onUserMarkerFetchedLegacy=cd,e.pullFromCache=Ee,e.pushToCache=Se,e.queryCache=we,e.queryOptions=ae,e.queryRoles=Yd,e.restoreCache=async(e="amitySdk")=>{var t;const r=ve();if(!r.cache)return!1;r.log("cache/api/restoreCache",{storageKey:e});const n=localStorage&&null!==(t=await localStorage.getItem(`${e}#${r.userId}`))&&void 0!==t?t:"{}";let s={};try{s=JSON.parse(n)}catch(e){}return r.cache.data=Object.assign(Object.assign({},s),r.cache.data),!0},e.runQuery=oe,e.sortByChannelSegment=({channelSegment:e},{channelSegment:t})=>e-t,e.sortByDisplayName=Pe,e.sortByFirstCreated=Fe,e.sortByFirstUpdated=Be,e.sortByLastActivity=$e,e.sortByLastCreated=Ne,e.sortByLastUpdated=je,e.sortByLocalSortingDate=Ue,e.sortByName=Me,e.sortBySegmentNumber=({segmentNumber:e},{segmentNumber:t})=>e-t,e.subscribeTopic=ht,e.toPage=J,e.toPageRaw=Z,e.toToken=X,e.upsertInCache=Ce,e.wipeCache=async(e="amitySdk")=>{const{log:t,cache:r,userId:n}=ve();return!!r&&(t("cache/api/wipeCache",{storageKey:e}),r.data={},localStorage&&await localStorage.setItem(`${e}#${n}`,"{}"),!0)},Object.defineProperty(e,"__esModule",{value:!0}),e}({});