@amityco/ts-sdk 6.17.0 → 6.17.1-1144fc8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env +26 -26
- package/dist/@types/core/permissions.d.ts +14 -0
- package/dist/@types/core/permissions.d.ts.map +1 -1
- package/dist/@types/domains/client.d.ts +1 -0
- package/dist/@types/domains/client.d.ts.map +1 -1
- package/dist/channelRepository/channelMembership/observers/getMembers/ChannelMemberLiveCollectionController.d.ts.map +1 -0
- package/dist/channelRepository/channelMembership/observers/getMembers/ChannelMemberPaginationController.d.ts.map +1 -0
- package/dist/channelRepository/channelMembership/observers/getMembers/ChannelMemberQueryStreamController.d.ts.map +1 -0
- package/dist/channelRepository/channelMembership/observers/getMembers/getMembers.d.ts.map +1 -0
- package/dist/channelRepository/channelMembership/observers/getMembers/index.d.ts +2 -0
- package/dist/channelRepository/channelMembership/observers/getMembers/index.d.ts.map +1 -0
- package/dist/channelRepository/observers/getChannels/ChannelLiveCollectionController.d.ts.map +1 -0
- package/dist/channelRepository/observers/getChannels/ChannelPaginationController.d.ts.map +1 -0
- package/dist/channelRepository/observers/getChannels/ChannelPagnationNoPageController.d.ts.map +1 -0
- package/dist/channelRepository/observers/getChannels/ChannelQueryStreamController.d.ts.map +1 -0
- package/dist/channelRepository/observers/getChannels/getChannels.d.ts.map +1 -0
- package/dist/channelRepository/observers/getChannels/index.d.ts +2 -0
- package/dist/channelRepository/observers/getChannels/index.d.ts.map +1 -0
- package/dist/client/api/createClient.d.ts.map +1 -1
- package/dist/client/utils/hasPermission/checkChannelPermission.d.ts +2 -0
- package/dist/client/utils/hasPermission/checkChannelPermission.d.ts.map +1 -0
- package/dist/client/utils/hasPermission/checkCommunityPermission.d.ts +2 -0
- package/dist/client/utils/hasPermission/checkCommunityPermission.d.ts.map +1 -0
- package/dist/client/utils/hasPermission/checkUserPermission.d.ts +2 -0
- package/dist/client/utils/hasPermission/checkUserPermission.d.ts.map +1 -0
- package/dist/client/utils/hasPermission/hasPermission.d.ts +6 -0
- package/dist/client/utils/hasPermission/hasPermission.d.ts.map +1 -0
- package/dist/client/utils/hasPermission/index.d.ts +2 -0
- package/dist/client/utils/hasPermission/index.d.ts.map +1 -0
- package/dist/commentRepository/events/utils.d.ts.map +1 -1
- package/dist/core/liveCollection/LiveCollectionController.d.ts +1 -1
- package/dist/core/liveCollection/LiveCollectionController.d.ts.map +1 -1
- package/dist/core/liveCollection/QueryStreamController.d.ts +1 -1
- package/dist/core/liveCollection/QueryStreamController.d.ts.map +1 -1
- package/dist/index.cjs.js +69 -18
- package/dist/index.esm.js +69 -18
- package/dist/index.umd.js +1 -1
- package/dist/messageRepository/observers/getMessages/MessageLiveCollectionController.d.ts.map +1 -0
- package/dist/messageRepository/observers/getMessages/MessagePaginationController.d.ts.map +1 -0
- package/dist/messageRepository/observers/getMessages/MessageQueryStreamController.d.ts.map +1 -0
- package/dist/messageRepository/observers/getMessages/getMessages.d.ts.map +1 -0
- package/dist/messageRepository/observers/getMessages/index.d.ts +2 -0
- package/dist/messageRepository/observers/getMessages/index.d.ts.map +1 -0
- package/dist/subChannelRepository/observers/{liveCollection → getSubChannels}/SubChannelLiveCollectionController.d.ts.map +1 -1
- package/dist/subChannelRepository/observers/{liveCollection → getSubChannels}/SubChannelPaginationController.d.ts.map +1 -1
- package/dist/subChannelRepository/observers/{liveCollection → getSubChannels}/SubChannelQueryStreamController.d.ts.map +1 -1
- package/dist/subChannelRepository/observers/getSubChannels/getSubChannels.d.ts.map +1 -0
- package/dist/subChannelRepository/observers/getSubChannels/index.d.ts +2 -0
- package/dist/subChannelRepository/observers/getSubChannels/index.d.ts.map +1 -0
- package/package.json +1 -1
- package/src/@types/core/permissions.ts +16 -0
- package/src/@types/domains/client.ts +2 -0
- package/src/analytic/api/queryReachUser.ts +1 -1
- package/src/channelRepository/channelMembership/observers/{getMembers.ts → getMembers/getMembers.ts} +1 -1
- package/src/channelRepository/channelMembership/observers/getMembers/index.ts +1 -0
- package/src/channelRepository/observers/{getChannels.ts → getChannels/getChannels.ts} +1 -1
- package/src/channelRepository/observers/getChannels/index.ts +1 -0
- package/src/client/api/createClient.ts +3 -1
- package/src/client/utils/hasPermission/checkChannelPermission.ts +22 -0
- package/src/client/utils/hasPermission/checkCommunityPermission.ts +22 -0
- package/src/client/utils/hasPermission/checkUserPermission.ts +12 -0
- package/src/client/utils/hasPermission/hasPermission.ts +18 -0
- package/src/client/utils/hasPermission/index.ts +1 -0
- package/src/commentRepository/events/utils.ts +1 -2
- package/src/core/liveCollection/LiveCollectionController.ts +2 -2
- package/src/core/liveCollection/QueryStreamController.ts +1 -1
- package/src/messageRepository/observers/{getMessages.ts → getMessages/getMessages.ts} +4 -26
- package/src/messageRepository/observers/getMessages/index.ts +1 -0
- package/src/subChannelRepository/observers/{getSubChannels.ts → getSubChannels/getSubChannels.ts} +1 -1
- package/src/subChannelRepository/observers/getSubChannels/index.ts +1 -0
- package/dist/channelRepository/channelMembership/observers/getMembers.d.ts.map +0 -1
- package/dist/channelRepository/channelMembership/observers/liveCollection/ChannelMemberLiveCollectionController.d.ts.map +0 -1
- package/dist/channelRepository/channelMembership/observers/liveCollection/ChannelMemberPaginationController.d.ts.map +0 -1
- package/dist/channelRepository/channelMembership/observers/liveCollection/ChannelMemberQueryStreamController.d.ts.map +0 -1
- package/dist/channelRepository/observers/getChannels.d.ts.map +0 -1
- package/dist/channelRepository/observers/liveCollection/ChannelLiveCollectionController.d.ts.map +0 -1
- package/dist/channelRepository/observers/liveCollection/ChannelPaginationController.d.ts.map +0 -1
- package/dist/channelRepository/observers/liveCollection/ChannelPagnationNoPageController.d.ts.map +0 -1
- package/dist/channelRepository/observers/liveCollection/ChannelQueryStreamController.d.ts.map +0 -1
- package/dist/messageRepository/observers/getMessages.d.ts.map +0 -1
- package/dist/messageRepository/observers/liveCollection/MessageLiveCollectionController.d.ts.map +0 -1
- package/dist/messageRepository/observers/liveCollection/MessagePaginationController.d.ts.map +0 -1
- package/dist/messageRepository/observers/liveCollection/MessageQueryStreamController.d.ts.map +0 -1
- package/dist/subChannelRepository/observers/getSubChannels.d.ts.map +0 -1
- /package/dist/channelRepository/channelMembership/observers/{liveCollection → getMembers}/ChannelMemberLiveCollectionController.d.ts +0 -0
- /package/dist/channelRepository/channelMembership/observers/{liveCollection → getMembers}/ChannelMemberPaginationController.d.ts +0 -0
- /package/dist/channelRepository/channelMembership/observers/{liveCollection → getMembers}/ChannelMemberQueryStreamController.d.ts +0 -0
- /package/dist/channelRepository/channelMembership/observers/{getMembers.d.ts → getMembers/getMembers.d.ts} +0 -0
- /package/dist/channelRepository/observers/{liveCollection → getChannels}/ChannelLiveCollectionController.d.ts +0 -0
- /package/dist/channelRepository/observers/{liveCollection → getChannels}/ChannelPaginationController.d.ts +0 -0
- /package/dist/channelRepository/observers/{liveCollection → getChannels}/ChannelPagnationNoPageController.d.ts +0 -0
- /package/dist/channelRepository/observers/{liveCollection → getChannels}/ChannelQueryStreamController.d.ts +0 -0
- /package/dist/channelRepository/observers/{getChannels.d.ts → getChannels/getChannels.d.ts} +0 -0
- /package/dist/messageRepository/observers/{liveCollection → getMessages}/MessageLiveCollectionController.d.ts +0 -0
- /package/dist/messageRepository/observers/{liveCollection → getMessages}/MessagePaginationController.d.ts +0 -0
- /package/dist/messageRepository/observers/{liveCollection → getMessages}/MessageQueryStreamController.d.ts +0 -0
- /package/dist/messageRepository/observers/{getMessages.d.ts → getMessages/getMessages.d.ts} +0 -0
- /package/dist/subChannelRepository/observers/{liveCollection → getSubChannels}/SubChannelLiveCollectionController.d.ts +0 -0
- /package/dist/subChannelRepository/observers/{liveCollection → getSubChannels}/SubChannelPaginationController.d.ts +0 -0
- /package/dist/subChannelRepository/observers/{liveCollection → getSubChannels}/SubChannelQueryStreamController.d.ts +0 -0
- /package/dist/subChannelRepository/observers/{getSubChannels.d.ts → getSubChannels/getSubChannels.d.ts} +0 -0
- /package/src/channelRepository/channelMembership/observers/{liveCollection → getMembers}/ChannelMemberLiveCollectionController.ts +0 -0
- /package/src/channelRepository/channelMembership/observers/{liveCollection → getMembers}/ChannelMemberPaginationController.ts +0 -0
- /package/src/channelRepository/channelMembership/observers/{liveCollection → getMembers}/ChannelMemberQueryStreamController.ts +0 -0
- /package/src/channelRepository/observers/{liveCollection → getChannels}/ChannelLiveCollectionController.ts +0 -0
- /package/src/channelRepository/observers/{liveCollection → getChannels}/ChannelPaginationController.ts +0 -0
- /package/src/channelRepository/observers/{liveCollection → getChannels}/ChannelPagnationNoPageController.ts +0 -0
- /package/src/channelRepository/observers/{liveCollection → getChannels}/ChannelQueryStreamController.ts +0 -0
- /package/src/messageRepository/observers/{liveCollection → getMessages}/MessageLiveCollectionController.ts +0 -0
- /package/src/messageRepository/observers/{liveCollection → getMessages}/MessagePaginationController.ts +0 -0
- /package/src/messageRepository/observers/{liveCollection → getMessages}/MessageQueryStreamController.ts +0 -0
- /package/src/subChannelRepository/observers/{liveCollection → getSubChannels}/SubChannelLiveCollectionController.ts +0 -0
- /package/src/subChannelRepository/observers/{liveCollection → getSubChannels}/SubChannelPaginationController.ts +0 -0
- /package/src/subChannelRepository/observers/{liveCollection → getSubChannels}/SubChannelQueryStreamController.ts +0 -0
package/dist/index.umd.js
CHANGED
|
@@ -3,4 +3,4 @@ var Amity=function(e){"use strict";const t=Object.freeze({FILE:"file",IMAGE:"ima
|
|
|
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,o,a=8*s-n-1,l=(1<<a)-1,c=l>>1,u=-7,d=r?s-1:0,h=r?-1:1,f=e[t+d];for(d+=h,i=f&(1<<-u)-1,f>>=-u,u+=a;u>0;i=256*i+e[t+d],d+=h,u-=8);for(o=i&(1<<-u)-1,i>>=-u,u+=n;u>0;o=256*o+e[t+d],d+=h,u-=8);if(0===i)i=1-c;else{if(i===l)return o?NaN:1/0*(f?-1:1);o+=Math.pow(2,n),i-=c}return(f?-1:1)*o*Math.pow(2,i-n)},r.write=function(e,t,r,n,s,i){var o,a,l,c=8*i-s-1,u=(1<<c)-1,d=u>>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?(a=isNaN(t)?1:0,o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-o))<1&&(o--,l*=2),(t+=o+d>=1?h/l:h*Math.pow(2,1-d))*l>=2&&(o++,l/=2),o+d>=u?(a=0,o=u):o+d>=1?(a=(t*l-1)*Math.pow(2,s),o+=d):(a=t*Math.pow(2,d-1)*Math.pow(2,s),o=0));s>=8;e[r+f]=255&a,f+=p,a/=256,s-=8);for(o=o<<s|a,c+=s;c>0;e[r+f]=255&o,f+=p,o/=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,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(e){return function(t){return l([e,t])}}function l(i){if(r)throw new TypeError("Generator is already executing.");for(;o;)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 o.label++,{value:i[1],done:!1};case 5:o.label++,n=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){o.label=i[1];break}if(6===i[0]&&o.label<s[1]){o.label=s[1],s=i;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(i);break}s[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}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,o=0,a=0,l=0,c=0,u=0;this.size=function(){return u},this.empty=function(){return 0===u},this.clear=function(){i=a=o=l=c=u=0,h.call(this,s.bucketSize),u=0},this.front=function(){return r[i][o]},this.back=function(){return r[a][l]},this.forEach=function(e){if(!this.empty()){var t=0;if(i!==a){for(c=o;c<s.bucketSize;++c)e(r[i][c],t++);for(c=i+1;c<a;++c)for(var n=0;n<s.bucketSize;++n)e(r[c][n],t++);for(c=0;c<=l;++c)e(r[a][c],t++)}else for(var c=o;c<=l;++c)e(r[i][c],t++)}};var d=function(e){var t=i*s.bucketSize+o,r=t+e,n=a*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=d(e),n=t.curNodeBucketIndex,s=t.curNodePointerIndex;return r[n][s]},this.eraseElementByPos=function(e){var t=this;if(e<0||e>u)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<u;++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,d=Math.max(Math.ceil(n/s.bucketSize),2),h=0;h<d;++h)t.push(new Array(s.bucketSize));var f=Math.ceil(e/s.bucketSize),p=Math.floor(d/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,o=0,a=g,l=m,c=d,u=e};this.pushBack=function(e){this.empty()||(a===c-1&&l===s.bucketSize-1&&h.call(this,this.size()),l<s.bucketSize-1?++l:a<c-1&&(++a,l=0)),++u,r[a][l]=e},this.popBack=function(){this.empty()||(1!==this.size()&&(l>0?--l:i<a&&(--a,l=s.bucketSize-1)),u>0&&--u)},this.setElementByPos=function(e,t){var n=d(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<u;++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===a){for(var t=o;t<=l;++t)if(r[i][t]===e)return!0;return!1}for(t=o;t<s.bucketSize;++t)if(r[i][t]===e)return!0;for(t=i+1;t<a;++t)for(var n=0;n<s.bucketSize;++n)if(r[t][n]===e)return!0;for(t=0;t<=l;++t)if(r[a][t]===e)return!0;return!1},this.reverse=function(){for(var e=0,t=u-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<u;++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<u;++r)this.setElementByPos(r,t[r])},this.pushFront=function(e){this.empty()||(0===i&&0===o&&h.call(this,this.size()),o>0?--o:i>0&&(--i,o=s.bucketSize-1)),++u,r[i][o]=e},this.popFront=function(){this.empty()||(1!==this.size()&&(o<s.bucketSize-1?++o:i<a&&(++i,o=0)),u>0&&--u)},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),o=0;o<i;++o)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=d(e),r=t.curNodeBucketIndex,n=t.curNodePointerIndex;a=r,l=n,u=e+1}},this[Symbol.iterator]=function(){return function(){var e,t;return n(this,(function(n){switch(n.label){case 0:if(0===u)return[2];if(i!==a)return[3,5];t=o,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=o,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<a))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[a][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 o=n*s.sigma;c=Math.ceil(o/s.bucketSize),c=Math.max(c,3);for(var l=0;l<c;++l)r.push(new Array(s.bucketSize));var u=Math.ceil(n/s.bucketSize);i=Math.floor(c/2)-Math.floor(u/2),a=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,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(e){return function(t){return l([e,t])}}function l(i){if(r)throw new TypeError("Generator is already executing.");for(;o;)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 o.label++,{value:i[1],done:!1};case 5:o.label++,n=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){o.label=i[1];break}if(6===i[0]&&o.label<s[1]){o.label=s[1],s=i;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(i);break}s[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}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"),o=e("../Map/Map");function a(e,t,r){var l=this;if(void 0===e&&(e=[]),void 0===t&&(t=a.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 o=s(i),a=o.next();!a.done;a=o.next())n=(n<<5)-n+a.value.charCodeAt(0),n&=n}catch(e){t={error:e}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}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,u=[],d=Math.max(a.initSize,Math.min(a.maxSize,t));this.size=function(){return c},this.empty=function(){return 0===c},this.clear=function(){c=0,d=t,u=[]},this.forEach=function(e){var t=0;u.forEach((function(r){r.forEach((function(r){e(r,t++)}))}))};var h=function(e){if(!(e>=a.maxSize)){d=2*e;var t=[];u.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)&d-1]=new i.default([{key:c,value:h}])}else if(n instanceof o.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()>a.untreeifyThreshold?t[s]=new o.default(f):f.size()&&(t[s]=f),p.size()>a.untreeifyThreshold?t[s+e]=new o.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)}u[s].clear()}})),u=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)&d-1;if(u[f]){var p=u[f].size();if(u[f]instanceof i.default){try{for(var g=s(u[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}}u[f].pushBack({key:e,value:t}),u[f].size()>=a.treeifyThreshold&&(u[f]=new o.default(u[f]))}else u[f].setElement(e,t);var v=u[f].size();c+=v-p}else++c,u[f]=new i.default([{key:e,value:t}]);c>d*a.sigma&&h.call(this,d)}else this.eraseElementByKey(e)},this.getElementByKey=function(e){var t,n,i=r(e)&d-1;if(u[i]){if(u[i]instanceof o.default)return u[i].getElementByKey(e);try{for(var a=s(u[i]),l=a.next();!l.done;l=a.next()){var c=l.value;if(c.key===e)return c.value}}catch(e){t={error:e}}finally{try{l&&!l.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}}},this.eraseElementByKey=function(e){var t,n,l=r(e)&d-1;if(u[l]){var h=u[l].size();if(u[l]instanceof o.default)u[l].eraseElementByKey(e),u[l].size()<=a.untreeifyThreshold&&(u[l]=new i.default(u[l]));else{var f=-1;try{for(var p=s(u[l]),g=p.next();!g.done;g=p.next()){var m=g.value;if(++f,m.key===e){u[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=u[l].size();c+=y-h}},this.find=function(e){var t,n,i=r(e)&d-1;if(!u[i])return!1;if(u[i]instanceof o.default)return u[i].find(e);try{for(var a=s(u[i]),l=a.next();!l.done;l=a.next())if(l.value.key===e)return!0}catch(e){t={error:e}}finally{try{l&&!l.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}return!1},this[Symbol.iterator]=function(){return function(){var e,t,r,i,o,a;return n(this,(function(n){switch(n.label){case 0:e=0,n.label=1;case 1:if(!(e<d))return[3,10];for(;e<d&&!u[e];)++e;if(e>=d)return[3,10];n.label=2;case 2:n.trys.push([2,7,8,9]),o=void 0,t=s(u[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(),o={error:i},[3,9];case 8:try{r&&!r.done&&(a=t.return)&&a.call(t)}finally{if(o)throw o.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)}a.initSize=16,a.maxSize=1<<30,a.sigma=.75,a.treeifyThreshold=8,a.untreeifyThreshold=6,a.minTreeifySize=64,Object.freeze(a),r.default=a},{"../LinkList/LinkList":29,"../Map/Map":30}],28:[function(e,t,r){var n=this&&this.__generator||function(e,t){var r,n,s,i,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(e){return function(t){return l([e,t])}}function l(i){if(r)throw new TypeError("Generator is already executing.");for(;o;)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 o.label++,{value:i[1],done:!1};case 5:o.label++,n=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){o.label=i[1];break}if(6===i[0]&&o.label<s[1]){o.label=s[1],s=i;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(i);break}s[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}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"),o=e("../LinkList/LinkList");function a(e,t,r){var l=this;if(void 0===e&&(e=[]),void 0===t&&(t=a.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,u=[],d=Math.max(a.initSize,Math.min(a.maxSize,t));this.size=function(){return c},this.empty=function(){return 0===c},this.clear=function(){c=0,d=t,u=[]},this.forEach=function(e){var t=0;u.forEach((function(r){r.forEach((function(r){e(r,t++)}))}))};var h=function(e){if(!(e>=a.maxSize)){d=2*e;var t=[];u.forEach((function(n,s){if(!n.empty()){if(n instanceof o.default&&1===n.size()){var l=n.front();if(void 0===l)throw new Error("unknown error");t[r(l)&d-1]=new o.default([l])}else if(n instanceof i.default){var c=new o.default,h=new o.default;n.forEach((function(t){0==(r(t)&e)?c.pushBack(t):h.pushBack(t)})),c.size()>a.untreeifyThreshold?t[s]=new i.default(c):c.size()&&(t[s]=c),h.size()>a.untreeifyThreshold?t[s+e]=new i.default(h):h.size()&&(t[s+e]=h)}else{var f=new o.default,p=new o.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)}u[s].clear()}})),u=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)&d-1;if(u[t]){var n=u[t].size();if(u[t]instanceof o.default){if(u[t].find(e))return;u[t].pushBack(e),u[t].size()>=a.treeifyThreshold&&(u[t]=new i.default(u[t]))}else u[t].insert(e);var s=u[t].size();c+=s-n}else u[t]=new o.default([e]),++c;c>d*a.sigma&&h.call(this,d)},this.eraseElementByValue=function(e){var t=r(e)&d-1;if(u[t]){var n=u[t].size();u[t].eraseElementByValue(e),u[t]instanceof i.default&&u[t].size()<=a.untreeifyThreshold&&(u[t]=new o.default(u[t]));var s=u[t].size();c+=s-n}},this.find=function(e){var t=r(e)&d-1;return!!u[t]&&u[t].find(e)},this[Symbol.iterator]=function(){return function(){var e,t,r,i,o,a;return n(this,(function(n){switch(n.label){case 0:e=0,n.label=1;case 1:if(!(e<d))return[3,10];for(;e<d&&!u[e];)++e;if(e>=d)return[3,10];n.label=2;case 2:n.trys.push([2,7,8,9]),o=void 0,t=s(u[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(),o={error:i},[3,9];case 8:try{r&&!r.done&&(a=t.return)&&a.call(t)}finally{if(o)throw o.error}return[7];case 9:return++e,[3,1];case 10:return[2]}}))}()},e.forEach((function(e){return l.insert(e)})),Object.freeze(this)}a.initSize=16,a.maxSize=1<<30,a.sigma=.75,a.treeifyThreshold=8,a.untreeifyThreshold=6,a.minTreeifySize=64,Object.freeze(a),r.default=a},{"../LinkList/LinkList":29,"../Set/Set":33}],29:[function(e,t,r){var n=this&&this.__generator||function(e,t){var r,n,s,i,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(e){return function(t){return l([e,t])}}function l(i){if(r)throw new TypeError("Generator is already executing.");for(;o;)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 o.label++,{value:i[1],done:!1};case 5:o.label++,n=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){o.label=i[1];break}if(6===i[0]&&o.label<s[1]){o.label=s[1],s=i;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(i);break}s[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}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,o=void 0;this.size=function(){return r},this.empty=function(){return 0===r},this.clear=function(){i=o=void 0,r=0},this.front=function(){return null==i?void 0:i.value},this.back=function(){return null==o?void 0:o.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(;o&&o.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);o?(o.next=t,t.pre=o,o=t):i=o=t},this.popBack=function(){o&&(r>0&&--r,o&&(i===o?i=o=void 0:(o=o.pre)&&(o.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 o=i,a=1;a<e;++a){if(!(null==o?void 0:o.next))throw new Error("unknown error");o=null==o?void 0:o.next}if(!o)throw new Error("unknown error");var l=o.next;for(r+=n;n--;)o.next=new s(t),o.next.pre=o,o=o.next;o.next=l,l&&(l.pre=o)}},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=o,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=o=t},this.popFront=function(){i&&(r>0&&--r,i&&(i===o?i=o=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=o;else if(n===i)t.pushFront(e),n=i;else{++r;var a=n.pre;a&&(a.next=new s(e),a.next.pre=a,a.next.next=n,n&&(n.pre=a.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,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(e){return function(t){return l([e,t])}}function l(i){if(r)throw new TypeError("Generator is already executing.");for(;o;)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 o.label++,{value:i[1],done:!1};case 5:o.label++,n=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){o.label=i[1];break}if(6===i[0]&&o.label<s[1]){o.label=s[1],s=i;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(i);break}s[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}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 o(e,t){var r=this;void 0===e&&(e=[]),t=t||function(e,t){return e<t?-1:e>t?1:0};var o=0,a=new i.default;a.color=i.default.TreeNodeColorType.black,this.size=function(){return o},this.empty=function(){return 0===o},this.clear=function(){o=0,a.key=a.value=void 0,a.leftChild=a.rightChild=a.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(a);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(a);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),o=i.next();!o.done;o=i.next())e(o.value,n++)}catch(e){t={error:e}}finally{try{o&&!o.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),o=i.next();!o.done;o=i.next()){var a=o.value;if(n===e)return a;++n}}catch(e){t={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}throw new Error("unknown Error")};var u=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?u(e.rightChild,r):u(e.leftChild,r)||{key:e.key,value:e.value}}};this.lowerBound=function(e){return u(a,e)};var d=function(e,r){if(e&&void 0!==e.key&&void 0!==e.value)return t(e.key,r)<=0?d(e.rightChild,r):d(e.leftChild,r)||{key:e.key,value:e.value}};this.upperBound=function(e){return d(a,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(a,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(a,e)};var p=function(e){var t=e.parent;if(!t){if(e===a)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();a===t&&(a=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(),a===t&&(a=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(),a===r&&(a=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(),a===t&&(a=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(),a===t&&(a=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(),a===r&&(a=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(),--o,a.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>=o)throw new Error("pos must more than 0 and less than set's size");var t=0;m(a,(function(r){return e===t?(g(r),!0):(++t,!1)}))},this.eraseElementByKey=function(e){if(!this.empty()){var r=b(a,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===a)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===a&&(a=s)}else e===t.rightChild&&(s=t.rotateLeft(),n===a&&(a=s),v(t));else t===n.rightChild&&(e===t.leftChild?(s=t.rotateRight(),n===a&&(a=s),v(t)):e===t.rightChild&&(t.color=i.default.TreeNodeColorType.black,n.color=i.default.TreeNodeColorType.red,s=n.rotateLeft(),n===a&&(a=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++o,a.key=e,a.value=r,void(a.color=i.default.TreeNodeColorType.black);var n=y(a,e);void 0===n.key||0!==t(n.key,e)?(++o,n.key=e,n.value=r,v(n),a.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(a,e)},this.getElementByKey=function(e){var t=b(a,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(a)};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(a)},e.forEach((function(e){var t=e.key,n=e.value;return r.setElement(t,n)})),Object.freeze(this)}Object.freeze(o),r.default=o},{"../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,o=2*e+2;i<n&&t(r[e],r[i])>0&&s(e,i),o<n&&t(r[e],r[o])>0&&s(e,o)};!function(){for(var e=Math.floor((n-1)/2);e>=0;--e)for(var i=e,o=2*i+1;o<n;){var a=o+1,l=o;if(a<n&&t(r[o],r[a])>0&&(l=a),t(r[i],r[l])<=0)break;s(i,l),o=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 o=Math.floor((s-1)/2);if(t(r[o],e)<=0)break;i(o),s=o}},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,o=2*s+2;if(i>=this.size())break;var a=i;if(o<this.size()&&t(r[i],r[o])>0&&(a=o),t(r[a],e)>=0)break;r[s]=r[a],s=a}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,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(e){return function(t){return l([e,t])}}function l(i){if(r)throw new TypeError("Generator is already executing.");for(;o;)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 o.label++,{value:i[1],done:!1};case 5:o.label++,n=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){o.label=i[1];break}if(6===i[0]&&o.label<s[1]){o.label=s[1],s=i;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(i);break}s[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}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 o(e,t){var r=this;void 0===e&&(e=[]),t=t||function(e,t){return e<t?-1:e>t?1:0};var o=0,a=new i.default;a.color=i.default.TreeNodeColorType.black,this.size=function(){return o},this.empty=function(){return 0===o},this.clear=function(){o=0,a.key=void 0,a.leftChild=a.rightChild=a.brother=a.parent=void 0,a.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(a).key},this.back=function(){if(!this.empty())return c(a).key},this.forEach=function(e){var t,r,n=0;try{for(var i=s(this),o=i.next();!o.done;o=i.next())e(o.value,n++)}catch(e){t={error:e}}finally{try{o&&!o.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),o=i.next();!o.done;o=i.next()){var a=o.value;if(n===e)return a;++n}}catch(e){t={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}throw new Error("unknown error")};var u=function(e){var t=e.parent;if(!t){if(e===a)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();a===t&&(a=n),u(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(),a===t&&(a=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,u(t)):(r.color=i.default.TreeNodeColorType.red,r.leftChild&&(r.leftChild.color=i.default.TreeNodeColorType.black),n=r.rotateRight(),a===r&&(a=n),u(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(),a===t&&(a=n),u(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(),a===t&&(a=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,u(t)):(r.color=i.default.TreeNodeColorType.red,r.rightChild&&(r.rightChild.color=i.default.TreeNodeColorType.black),n=r.rotateLeft(),a===r&&(a=n),u(e))))}else e.color=i.default.TreeNodeColorType.black},d=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)}u(t),t&&t.remove(),--o,a.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>=o)throw new Error("pos must more than 0 and less than set's size");var t=0;h(a,(function(r){return e===t?(d(r),!0):(++t,!1)}))},this.eraseElementByValue=function(e){if(!this.empty()){var r=g(a,e);void 0!==r&&void 0!==r.key&&0===t(r.key,e)&&d(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===a)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===a&&(a=s)}else e===t.rightChild&&(s=t.rotateLeft(),n===a&&(a=s),p(t));else t===n.rightChild&&(e===t.leftChild?(s=t.rotateRight(),n===a&&(a=s),p(t)):e===t.rightChild&&(t.color=i.default.TreeNodeColorType.black,n.color=i.default.TreeNodeColorType.red,s=n.rotateLeft(),n===a&&(a=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++o,a.key=e,void(a.color=i.default.TreeNodeColorType.black);var r=f(a,e);void 0!==r.key&&0===t(r.key,e)||(++o,r.key=e,p(r),a.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(a,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(a,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(a,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(a,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(a,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(a)};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(a)},e.forEach((function(e){return r.insert(e)})),Object.freeze(this)}Object.freeze(o),r.default=o},{"../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,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(e){return function(t){return l([e,t])}}function l(i){if(r)throw new TypeError("Generator is already executing.");for(;o;)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 o.label++,{value:i[1],done:!1};case 5:o.label++,n=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){o.label=i[1];break}if(6===i[0]&&o.label<s[1]){o.label=s[1],s=i;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(i);break}s[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}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),o=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)o.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 o},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))},o=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 a(e){var t=this;void 0===e&&(e=[]);var r=0,a=[];this.size=function(){return r},this.empty=function(){return 0===r},this.clear=function(){r=0,a.length=0},this.front=function(){if(!this.empty())return a[0]},this.back=function(){if(!this.empty())return a[r-1]},this.forEach=function(e){a.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 a[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)a[t]=a[t+1];this.popBack()},this.eraseElementByValue=function(e){var t=[];this.forEach((function(r){r!==e&&t.push(r)})),t.forEach((function(e,t){a[t]=e}));for(var n=t.length;r>n;)this.popBack()},this.pushBack=function(e){a.push(e),++r},this.popBack=function(){a.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");a[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");a.splice.apply(a,i([e,0],s(new Array(n).fill(t)),!1)),r+=n},this.find=function(e){return a.includes(e)},this.reverse=function(){a.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){a[t]=e}));for(var n=t.length;r>n;)this.popBack()},this.sort=function(e){a.sort(e)},this[Symbol.iterator]=function(){return function(){return n(this,(function(e){switch(e.label){case 0:return[5,o(a)];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(a),r.default=a},{}],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 o=e("./LinkList/LinkList");r.LinkList=o.default;var a=e("./Deque/Deque");r.Deque=a.default;var l=e("./PriorityQueue/PriorityQueue");r.PriorityQueue=l.default;var c=e("./Set/Set");r.Set=c.default;var u=e("./Map/Map");r.Map=u.default;var d=e("./HashSet/HashSet");r.HashSet=d.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"),o=Symbol("lengthCalculator"),a=Symbol("allowStale"),l=Symbol("maxAge"),c=Symbol("dispose"),u=Symbol("noDisposeOnSet"),d=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[o]="function"!=typeof t?p:t,this[a]=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[u]=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[a]=!!e}get allowStale(){return this[a]}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[o]&&(this[o]=e,this[i]=0,this[d].forEach((e=>{e.length=this[o](e.value,e.key),this[i]+=e.length}))),v(this)}get lengthCalculator(){return this[o]}get length(){return this[i]}get itemCount(){return this[d].length}rforEach(e,t){t=t||this;for(let r=this[d].tail;null!==r;){const n=r.prev;E(this,e,r,t),r=n}}forEach(e,t){t=t||this;for(let r=this[d].head;null!==r;){const n=r.next;E(this,e,r,t),r=n}}keys(){return this[d].toArray().map((e=>e.key))}values(){return this[d].toArray().map((e=>e.value))}reset(){this[c]&&this[d]&&this[d].length&&this[d].forEach((e=>this[c](e.key,e.value))),this[h]=new Map,this[d]=new n,this[i]=0}dump(){return this[d].map((e=>!y(this,e)&&{k:e.key,v:e.value,e:e.now+(e.maxAge||0)})).toArray().filter((e=>e))}dumpLru(){return this[d]}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,a=this[o](t,e);if(this[h].has(e)){if(a>this[s])return b(this,this[h].get(e)),!1;const o=this[h].get(e).value;return this[c]&&(this[u]||this[c](e,o.value)),o.now=n,o.maxAge=r,o.value=t,this[i]+=a-o.length,o.length=a,this.get(e),v(this),!0}const f=new w(e,t,a,n,r);return f.length>this[s]?(this[c]&&this[c](e,t),!1):(this[i]+=f.length,this[d].unshift(f),this[h].set(e,this[d].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[d].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[a])return}else r&&(e[f]&&(n.value.now=Date.now()),e[d].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[d].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[d].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[a]||(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 o=e.alloc(1);return o.writeUInt8(r.codes[t]<<r.CMD_SHIFT|(s?r.DUP_MASK:0)|n<<r.QOS_SHIFT|i,0,!0),o}))))))}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 o;return n(e,r,t),r.concat()}class o 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 o=r.allocUnsafe(e);for(s=0;s<n.length&&void 0!==n[s];s++)"string"!=typeof n[s]?(n[s].copy(o,i),i+=t[s]):(o.write(n[s],i),i+=t[s]);return o}}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 o(){for(let e=0;e<r;e++)n[e]=i(e)}function a(t){const r=4;let n=0,i=0;const o=e.allocUnsafe(r);do{n=t%128|0,(t=t/128|0)>0&&(n|=128),o.writeUInt8(n,i++)}while(t>0&&i<r);return t>0&&(i=0),s?o.subarray(0,i):o.slice(0,i)}function l(t){const r=e.allocUnsafe(4);return r.writeUInt32BE(t,0),r}t.exports={cache:n,generateCache:o,generateNumber:i,genBufVariableByteInt:a,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"),o=e("./constants"),a=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(){a("_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),a("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++,a("parse: state complete. _stateCounter is now: %d",this._stateCounter),a("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return a("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=o.types[e>>o.CMD_SHIFT],this.packet.retain=0!=(e&o.RETAIN_MASK),this.packet.qos=e>>o.QOS_SHIFT&o.QOS_MASK,this.packet.dup=0!=(e&o.DUP_MASK),a("_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)),a("_parseLength %d",e.value),!!e}_parsePayload(){a("_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 a("_parsePayload complete result: %s",e),e}_parseConnect(){let e,t,r,n;a("_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)&o.USERNAME_MASK,s.password=this._list.readUInt8(this._pos)&o.PASSWORD_MASK,s.will=this._list.readUInt8(this._pos)&o.WILL_FLAG_MASK,s.will&&(i.will={},i.will.retain=0!=(this._list.readUInt8(this._pos)&o.WILL_RETAIN_MASK),i.will.qos=(this._list.readUInt8(this._pos)&o.WILL_QOS_MASK)>>o.WILL_QOS_SHIFT),i.clean=0!=(this._list.readUInt8(this._pos)&o.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,a("_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,a("_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,a("_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,a("_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,a("_parseConnect: complete"),i}_parseConnack(){a("_parseConnack");const e=this.packet;if(this._list.length<1)return null;if(e.sessionPresent=!!(this._list.readUInt8(this._pos++)&o.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)}a("_parseConnack: complete")}_parsePublish(){a("_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),a("_parsePublish: payload from buffer list: %o",e.payload)}}_parseSubscribe(){a("_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&o.SUBSCRIBE_OPTIONS_QOS_MASK,l=0!=(r>>o.SUBSCRIBE_OPTIONS_NL_SHIFT&o.SUBSCRIBE_OPTIONS_NL_MASK),i=0!=(r>>o.SUBSCRIBE_OPTIONS_RAP_SHIFT&o.SUBSCRIBE_OPTIONS_RAP_MASK),s=r>>o.SUBSCRIBE_OPTIONS_RH_SHIFT&o.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),a("_parseSubscribe: push subscription `%s` to subscription",c),e.subscriptions.push(c)}}}_parseSuback(){a("_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(){a("_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"));a("_parseUnsubscribe: push topic `%s` to unsubscriptions",t),e.unsubscriptions.push(t)}}}_parseUnsuback(){a("_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(){a("_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(),a("_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(a("_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 a("_parseDisconnect result: true"),!0}_parseAuth(){a("_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),a("_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):(a("_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,a("_parseString: result: %s",n),n}_parseStringPair(){return a("_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,a("_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,a("_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,a("_parse4ByteNum: result: %s",e),e}_parseVarByteNum(e){a("_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&o.VARBYTEINT_MASK),s*=128,0==(r&o.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),a("_parseVarByteNum: result: %o",l),l}_parseByte(){let e;return this._pos<this._list.length&&(e=this._list.readUInt8(this._pos),this._pos++),a("_parseByte: result: %o",e),e}_parseByType(e){switch(a("_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(){a("_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=o.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(o.propertiesTypes[t]))):r[t]=this._parseByType(o.propertiesTypes[t]);else{r[t]||(r[t]=Object.create(null));const e=this._parseByType(o.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 a("_newPacket"),this.packet&&(this._list.consume(this.packet.length),a("_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)),a("_newPacket: new packet"),this.packet=new i,this._pos=0,!0}_emitError(e){a("_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]),o=e("./numbers"),a=e("process-nextick-args").nextTick,l=e("debug")("mqtt-packet:writeToStream"),c=o.cache,u=o.generateNumber,d=o.generateCache,h=o.genBufVariableByteInt,f=o.generate4ByteBuffer;let p=O,g=!0;function m(e,t,r){switch(l("generate called"),t.cork&&(t.cork(),a(y,t)),g&&(g=!1,d()),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 T(e,t,r);case"suback":return S(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 _(e,t,r);case"auth":return I(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||{},o=i.protocolId||"MQTT";let a=i.protocolVersion||4;const l=i.will;let c=i.clean;const u=i.keepalive||0,d=i.clientId||"",h=i.username,f=i.password,g=i.properties;void 0===c&&(c=!0);let m=0;if(!o||"string"!=typeof o&&!r.isBuffer(o))return t.emit("error",new Error("Invalid protocolId")),!1;if(m+=o.length+2,3!==a&&4!==a&&5!==a)return t.emit("error",new Error("Invalid protocol version")),!1;if(m+=1,("string"==typeof d||r.isBuffer(d))&&(d||a>=4)&&(d||c))m+=r.byteLength(d)+2;else{if(a<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 u||u<0||u>65535||u%1!=0)return t.emit("error",new Error("Invalid keepalive")),!1;if(m+=2,m+=1,5===a){var y=N(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===a){if(!(v=N(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,o),i.bridgeMode&&(a+=128),t.write(131===a?n.VERSION131:132===a?n.VERSION132:4===a?n.VERSION4:5===a?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,u),5===a&&y.write(),F(t,d),l&&(5===a&&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 o=s?s.protocolVersion:4,a=e||{},l=5===o?a.reasonCode:a.returnCode,c=a.properties;let u=2;if("number"!=typeof l)return t.emit("error",new Error("Invalid return code")),!1;let d=null;if(5===o){if(d=N(t,c),!d)return!1;u+=d.length}return t.write(n.CONNACK_HEADER),L(t,u),t.write(a.sessionPresent?n.SESSIONPRESENT_HEADER:i),t.write(r.from([l])),null!=d&&d.write(),!0}function w(e,t,i){l("publish: packet: %o",e);const o=i?i.protocolVersion:4,a=e||{},c=a.qos||0,u=a.retain?n.RETAIN_MASK:0,d=a.topic,h=a.payload||s,f=a.messageId,g=a.properties;let m=0;if("string"==typeof d)m+=r.byteLength(d)+2;else{if(!r.isBuffer(d))return t.emit("error",new Error("Invalid topic")),!1;m+=d.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===o){if(y=N(t,g),!y)return!1;m+=y.length}return t.write(n.PUBLISH_HEADER[c][a.dup?1:0][u?1:0]),L(t,m),p(t,$(d)),t.write(d),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,o=e||{},a=o.cmd||"puback",l=o.messageId,c=o.dup&&"pubrel"===a?n.DUP_MASK:0;let u=0;const d=o.reasonCode,h=o.properties;let f=5===i?3:2;if("pubrel"===a&&(u=1),"number"!=typeof l)return t.emit("error",new Error("Invalid messageId")),!1;let g=null;if(5===i&&"object"==typeof h){if(g=U(t,h,s,f),!g)return!1;f+=g.length}return t.write(n.ACKS[a][u][c][0]),L(t,f),p(t,l),5===i&&t.write(r.from([d])),null!==g&&g.write(),!0}function T(e,t,s){l("subscribe: packet: ");const i=s?s.protocolVersion:4,o=e||{},a=o.dup?n.DUP_MASK:0,c=o.messageId,u=o.subscriptions,d=o.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=N(t,d),!f)return!1;h+=f.length}if("object"!=typeof u||!u.length)return t.emit("error",new Error("Invalid subscriptions")),!1;for(let e=0;e<u.length;e+=1){const n=u[e].topic,s=u[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(u[e].nl||!1))return t.emit("error",new Error("Invalid subscriptions - invalid No Local")),!1;if("boolean"!=typeof(u[e].rap||!1))return t.emit("error",new Error("Invalid subscriptions - invalid Retain as Published")),!1;const r=u[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][a?1:0][0]),L(t,h),p(t,c),null!==f&&f.write();let g=!0;for(const e of u){const s=e.topic,o=e.qos,a=+e.nl,l=+e.rap,c=e.rh;let u;D(t,s),u=n.SUBSCRIBE_OPTIONS_QOS[o],5===i&&(u|=a?n.SUBSCRIBE_OPTIONS_NL:0,u|=l?n.SUBSCRIBE_OPTIONS_RAP:0,u|=c?n.SUBSCRIBE_OPTIONS_RH[c]:0),g=t.write(r.from([u]))}return g}function S(e,t,s){const i=s?s.protocolVersion:4,o=e||{},a=o.messageId,l=o.granted,c=o.properties;let u=0;if("number"!=typeof a)return t.emit("error",new Error("Invalid messageId")),!1;if(u+=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;u+=1}let d=null;if(5===i){if(d=U(t,c,s,u),!d)return!1;u+=d.length}return t.write(n.SUBACK_HEADER),L(t,u),p(t,a),null!==d&&d.write(),t.write(r.from(l))}function C(e,t,s){const i=s?s.protocolVersion:4,o=e||{},a=o.messageId,l=o.dup?n.DUP_MASK:0,c=o.unsubscriptions,u=o.properties;let d=0;if("number"!=typeof a)return t.emit("error",new Error("Invalid messageId")),!1;if(d+=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;d+=r.byteLength(c[e])+2}let h=null;if(5===i){if(h=N(t,u),!h)return!1;d+=h.length}t.write(n.UNSUBSCRIBE_HEADER[1][l?1:0][0]),L(t,d),p(t,a),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,o=e||{},a=o.messageId,l=o.dup?n.DUP_MASK:0,c=o.granted,u=o.properties,d=o.cmd,h=0;let f=2;if("number"!=typeof a)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=U(t,u,s,f),!g)return!1;f+=g.length}return t.write(n.ACKS[d][h][l][0]),L(t,f),p(t,a),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 _(e,t,s){const i=s?s.protocolVersion:4,o=e||{},a=o.reasonCode,l=o.properties;let c=5===i?1:0,u=null;if(5===i){if(u=U(t,l,s,c),!u)return!1;c+=u.length}return t.write(r.from([n.codes.disconnect<<4])),L(t,c),5===i&&t.write(r.from([a])),null!==u&&u.write(),!0}function I(e,t,s){const i=s?s.protocolVersion:4,o=e||{},a=o.reasonCode,l=o.properties;let c=5===i?1:0;5!==i&&t.emit("error",new Error("Invalid mqtt version for auth packet"));const u=U(t,l,s,c);return!!u&&(c+=u.length,t.write(r.from([n.codes.auth<<4])),L(t,c),t.write(r.from([a])),null!==u&&u.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=u(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 N(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 o=t[e];if(Array.isArray(o))for(let t=0;t<o.length;t++){if(n=i(e,o[t]),!n)return!1;r+=n}else{if(n=i(e,o),!n)return!1;r=n}if(!r)return!1;s+=r}return{length:r.byteLength(h(s))+s,write(){j(e,t,s)}}}function U(e,t,r,n){const s=["reasonString","userProperties"],i=r&&r.properties&&r.properties.maximumPacketSize?r.properties.maximumPacketSize:0;let o=N(e,t);if(i)for(;n+o.length>i;){const r=s.shift();if(!r||!t[r])return!1;delete t[r],o=N(e,t)}return o}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 o=s[i];Array.isArray(o)?o.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(),o.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,o=24*i,a=7*o,l=365.25*o;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*a;case"days":case"day":case"d":return r*o;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 u(e){var t=Math.abs(e);return t>=o?Math.round(e/o)+"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 d(e){var t=Math.abs(e);return t>=o?h(e,t,o,"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?d(e):u(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 o(e,t){this.low=e,this.high=t}function a(e,t){if(!(this instanceof a))return new a(e,t);this.min=e,this.max=t,this.ss=new n([],((e,t)=>e.compare(t))),s("Create"),this.clear()}o.prototype.equals=function(e){return this.low===e.low&&this.high===e.high},o.prototype.compare=function(e){return this.low<e.low&&this.high<e.low?-1:e.low<this.low&&e.high<this.low?1:0},a.prototype.firstVacant=function(){return 0===this.ss.size()?null:this.ss.front().low},a.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},a.prototype.use=function(e){const t=new o(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 o(n,e-1)),s("use():"+e),!0}return s("use():failed"),!1},a.prototype.free=function(e){if(e<this.min||e>this.max)return void i("free():"+e+" is out of range");const t=new o(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)},a.prototype.clear=function(){s("clear()"),this.ss.clear(),this.ss.insert(new o(this.min,this.max))},a.prototype.intervalCount=function(){return this.ss.size()},a.prototype.dump=function(){console.log("length:"+this.ss.size());for(const e of this.ss)console.log(e)},t.exports=a},{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,o,a=arguments.length;switch(a){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(a-1),o=0;o<i.length;)i[o++]=arguments[o];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 o(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function l(e){if(n===setTimeout)return setTimeout(e,0);if((n===o||!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===a||!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:o}catch(e){n=o}try{s="function"==typeof clearTimeout?clearTimeout:a}catch(e){s=a}}();var u,d=[],h=!1,f=-1;function p(){h&&u&&(h=!1,u.length?d=u.concat(d):f=-1,d.length&&g())}function g(){if(!h){var e=l(p);h=!0;for(var t=d.length;t;){for(u=d,d=[];++f<t;)u&&u[f].run();f=-1,t=d.length}u=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];d.push(new m(e,t)),1!==d.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,o="object"==typeof e&&e;o.global!==o&&o.window!==o&&o.self!==o||(n=o);var a,l,c=2147483647,u=36,d=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"},T=u-d,S=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 _(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 I(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:u}function D(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function x(e,t,r){var n=0;for(e=r?S(e/p):e>>1,e+=S(e/t);e>T*h>>1;n+=u)e=S(e/T);return S(n+(T+1)*e/(e+f))}function O(e){var t,r,n,s,i,o,a,l,f,p,v=[],b=e.length,w=0,E=m,T=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,o=1,a=u;s>=b&&k("invalid-input"),((l=L(e.charCodeAt(s++)))>=u||l>S((c-w)/o))&&k("overflow"),w+=l*o,!(l<(f=a<=T?d:a>=T+h?h:a-T));a+=u)o>S(c/(p=u-f))&&k("overflow"),o*=p;T=x(w-i,t=v.length+1,0==i),S(w/t)>c-E&&k("overflow"),E+=S(w/t),w%=t,v.splice(w++,0,E)}return R(v)}function P(e){var t,r,n,s,i,o,a,l,f,p,v,b,w,E,T,A=[];for(b=(e=I(e)).length,t=m,r=0,i=g,o=0;o<b;++o)(v=e[o])<128&&A.push(C(v));for(n=s=A.length,s&&A.push(y);n<b;){for(a=c,o=0;o<b;++o)(v=e[o])>=t&&v<a&&(a=v);for(a-t>S((c-r)/(w=n+1))&&k("overflow"),r+=(a-t)*w,t=a,o=0;o<b;++o)if((v=e[o])<t&&++r>c&&k("overflow"),v==t){for(l=r,f=u;!(l<(p=f<=i?d:f>=i+h?h:f-i));f+=u)T=l-p,E=u-p,A.push(C(D(p+T%E,0))),l=S(T/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 _(e,(function(e){return v.test(e)?O(e.slice(4).toLowerCase()):e}))}function F(e){return _(e,(function(e){return b.test(e)?"xn--"+P(e):e}))}if(a={version:"1.4.1",ucs2:{decode:I,encode:R},decode:O,encode:P,toASCII:F,toUnicode:M},s&&i)if(t.exports==s)i.exports=a;else for(l in a)a.hasOwnProperty(l)&&(s[l]=a[l]);else n.punycode=a}(this)}).call(this)}).call(this,void 0!==ut?ut:"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 o={};if("string"!=typeof e||0===e.length)return o;var a=/\+/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 u=0;u<c;++u){var d,h,f,p,g=e[u].replace(a,"%20"),m=g.indexOf(r);m>=0?(d=g.substr(0,m),h=g.substr(m+1)):(d=g,h=""),f=decodeURIComponent(d),p=decodeURIComponent(h),n(o,f)?s(o[f])?o[f].push(p):o[f]=[o[f],p]:o[f]=p}return o};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,a){return t=t||"&",r=r||"=",null===e&&(e=void 0),"object"==typeof e?i(o(e),(function(o){var a=encodeURIComponent(n(o))+r;return s(e[o])?i(e[o],(function(e){return a+encodeURIComponent(n(e))})).join(t):a+encodeURIComponent(n(e[o]))})).join(t):a?encodeURIComponent(n(a))+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 o=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 o=function(e){function t(t,r,n){return e.call(this,i(t,r,n))||this}return n(t,e),t}(r);o.prototype.name=r.name,o.prototype.code=e,s[e]=o}function o(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 a(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&&a(t,"not ")?(n="must not be",t=t.replace(/^not /,"")):n="must be",l(e," argument"))s="The ".concat(e," ").concat(n," ").concat(o(t,"type"));else{var i=c(e,".")?"property":"argument";s='The "'.concat(e,'" ').concat(i," ").concat(n," ").concat(o(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 o=n(i.prototype),a=0;a<o.length;a++){var l=o[a];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",u)))}function u(){this._writableState.ended||r.nextTick(d,this)}function d(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=I,I.ReadableState=_,e("events").EventEmitter;var i=function(e,t){return e.listeners(t).length},o=e("./internal/streams/stream"),a=e("buffer").Buffer,l=n.Uint8Array||function(){};function c(e){return a.from(e)}function u(e){return a.isBuffer(e)||e instanceof l}var d,h=e("util");d=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,T=b.ERR_METHOD_NOT_IMPLEMENTED,S=b.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;e("inherits")(I,o);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 _(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 I(t){if(s=s||e("./_stream_duplex"),!(this instanceof I))return new I(t);var r=this instanceof s;this._readableState=new _(t,this,r),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),o.call(this)}function R(e,t,r,n,s){d("readableAddChunk",t);var i,o=e._readableState;if(null===t)o.reading=!1,M(e,o);else if(s||(i=D(o,t)),i)C(e,i);else if(o.objectMode||t&&t.length>0)if("string"==typeof t||o.objectMode||Object.getPrototypeOf(t)===a.prototype||(t=c(t)),n)o.endEmitted?C(e,new S):L(e,o,t,!0);else if(o.ended)C(e,new E);else{if(o.destroyed)return!1;o.reading=!1,o.decoder&&!r?(t=o.decoder.write(t),o.objectMode||0!==t.length?L(e,o,t,!1):U(e,o)):L(e,o,t,!1)}else n||(o.reading=!1,U(e,o));return!o.ended&&(o.length<o.highWaterMark||0===o.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)),U(e,t)}function D(e,t){var r;return u(t)||"string"==typeof t||void 0===t||e.objectMode||(r=new w("chunk",["string","Buffer","Uint8Array"],t)),r}Object.defineProperty(I.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),I.prototype.destroy=y.destroy,I.prototype._undestroy=y.undestroy,I.prototype._destroy=function(e,t){t(e)},I.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=a.from(e,t),t=""),r=!0),R(this,e,t,!1,r)},I.prototype.unshift=function(e){return R(this,e,null,!0,!1)},I.prototype.isPaused=function(){return!1===this._readableState.flowing},I.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(d("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,N(e)))}}function F(e){var t=e._readableState;d("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(d("emitReadable",t.flowing),t.emittedReadable=!0,r.nextTick(N,e))}function N(e){var t=e._readableState;d("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 U(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(d("maybeReadMore read 0"),e.read(0),r===t.length)break}t.readingMore=!1}function j(e){return function(){var t=e._readableState;d("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){d("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){d("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(d("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;d("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,r.nextTick(W,t,e))}function W(e,t){if(d("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}I.prototype.read=function(e){d("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 d("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 d("need readable",s),(0===t.length||t.length-e<t.highWaterMark)&&d("length less than watermark",s=!0),t.ended||t.reading?d("reading or ended",s=!1):s&&(d("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},I.prototype._read=function(e){C(this,new T("_read()"))},I.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,d("pipe count=%d opts=%j",s.pipesCount,t);var o=t&&!1===t.end||e===r.stdout||e===r.stderr?y:l;function a(e,t){d("onunpipe"),e===n&&t&&!1===t.hasUnpiped&&(t.hasUnpiped=!0,h())}function l(){d("onend"),e.end()}s.endEmitted?r.nextTick(o):n.once("end",o),e.on("unpipe",a);var c=j(n);e.on("drain",c);var u=!1;function h(){d("cleanup"),e.removeListener("close",g),e.removeListener("finish",m),e.removeListener("drain",c),e.removeListener("error",p),e.removeListener("unpipe",a),n.removeListener("end",l),n.removeListener("end",y),n.removeListener("data",f),u=!0,!s.awaitDrain||e._writableState&&!e._writableState.needDrain||c()}function f(t){d("ondata");var r=e.write(t);d("dest.write",r),!1===r&&((1===s.pipesCount&&s.pipes===e||s.pipesCount>1&&-1!==Y(s.pipes,e))&&!u&&(d("false write response, pause",s.awaitDrain),s.awaitDrain++),n.pause())}function p(t){d("onerror",t),y(),e.removeListener("error",p),0===i(e,"error")&&C(e,t)}function g(){e.removeListener("finish",m),y()}function m(){d("onfinish"),e.removeListener("close",g),y()}function y(){d("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||(d("pipe resume"),n.resume()),e},I.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 o=Y(t.pipes,e);return-1===o||(t.pipes.splice(o,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,r)),this},I.prototype.on=function(e,t){var n=o.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,d("on readable",s.length,s.reading),s.length?F(this):s.reading||r.nextTick(q,this))),n},I.prototype.addListener=I.prototype.on,I.prototype.removeListener=function(e,t){var n=o.prototype.removeListener.call(this,e,t);return"readable"===e&&r.nextTick($,this),n},I.prototype.removeAllListeners=function(e){var t=o.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||r.nextTick($,this),t},I.prototype.resume=function(){var e=this._readableState;return e.flowing||(d("resume"),e.flowing=!e.readableListening,K(this,e)),e.paused=!1,this},I.prototype.pause=function(){return d("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(d("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},I.prototype.wrap=function(e){var t=this,r=this._readableState,n=!1;for(var s in e.on("end",(function(){if(d("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){d("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){d("wrapped _read",t),n&&(n=!1,e.resume())},this},"function"==typeof Symbol&&(I.prototype[Symbol.asyncIterator]=function(){return void 0===p&&(p=e("./internal/streams/async_iterator")),p(this)}),Object.defineProperty(I.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(I.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(I.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),I._fromList=V,Object.defineProperty(I.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(I.from=function(t,r){return void 0===g&&(g=e("./internal/streams/from")),g(I,t,r)})}).call(this)}).call(this,e("_process"),void 0!==ut?ut:"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=u;var n=e("../errors").codes,s=n.ERR_METHOD_NOT_IMPLEMENTED,i=n.ERR_MULTIPLE_CALLBACK,o=n.ERR_TRANSFORM_ALREADY_TRANSFORMING,a=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 u(e){if(!(this instanceof u))return new u(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",d)}function d(){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 a;if(e._transformState.transforming)throw new o;return e.push(null)}e("inherits")(u,l),u.prototype.push=function(e,t){return this._transformState.needTransform=!1,l.prototype.push.call(this,e,t)},u.prototype._transform=function(e,t,r){r(new s("_transform()"))},u.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)}},u.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))},u.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=_,_.WritableState=A;var o={deprecate:e("util-deprecate")},a=e("./internal/streams/stream"),l=e("buffer").Buffer,c=n.Uint8Array||function(){};function u(e){return l.from(e)}function d(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,T=g.ERR_STREAM_WRITE_AFTER_END,S=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 o=!1===t.decodeStrings;this.decodeStrings=!o,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 _(t){var r=this instanceof(i=i||e("./_stream_duplex"));if(!r&&!h.call(_,this))return new _(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)),a.call(this)}function I(e,t){var n=new T;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 o=L(t,n,s);n!==o&&(r=!0,s="buffer",n=o)}var a=t.objectMode?1:n.length;t.length+=a;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,a,n,s,i);return l}function x(e,t,r,n,s,i,o){t.writelen=n,t.writecb=o,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 o=B(n)||e.destroyed;o||n.corked||n.bufferProcessing||!n.bufferedRequest||U(e,n),s?r.nextTick(F,e,n,o,i):F(e,n,o,i)}}function F(e,t,r,n){r||N(e,t),t.pendingcb--,n(),q(e,t)}function N(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}function U(e,t){t.bufferProcessing=!0;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var n=t.bufferedRequestCount,i=new Array(n),o=t.corkedRequestsFree;o.entry=r;for(var a=0,l=!0;r;)i[a]=r,r.isBuf||(l=!1),r=r.next,a+=1;i.allBuffers=l,x(e,t,!0,t.length,i,"",o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new s(t),t.bufferedRequestCount=0}else{for(;r;){var c=r.chunk,u=r.encoding,d=r.callback;if(x(e,t,!1,t.objectMode?1:c.length,c,u,d),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")(_,a),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:o.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(_,Symbol.hasInstance,{value:function(e){return!!h.call(this,e)||this===_&&e&&e._writableState instanceof A}})):h=function(e){return e instanceof this},_.prototype.pipe=function(){C(this,new b)},_.prototype.write=function(e,t,r){var n=this._writableState,s=!1,i=!n.objectMode&&d(e);return i&&!l.isBuffer(e)&&(e=u(e)),"function"==typeof t&&(r=t,t=null),i?t="buffer":t||(t=n.defaultEncoding),"function"!=typeof r&&(r=k),n.ending?I(this,r):(i||R(this,n,e,r))&&(n.pendingcb++,s=D(this,n,i,e,t,r)),s},_.prototype.cork=function(){this._writableState.corked++},_.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.bufferProcessing||!e.bufferedRequest||U(this,e))},_.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 S(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(_.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(_.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),_.prototype._write=function(e,t,r){r(new y("_write()"))},_.prototype._writev=null,_.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(_.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(_.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),_.prototype.destroy=f.destroy,_.prototype._undestroy=f.undestroy,_.prototype._destroy=function(e,t){t(e)}}).call(this)}).call(this,e("_process"),void 0!==ut?ut:"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"),o=Symbol("lastResolve"),a=Symbol("lastReject"),l=Symbol("error"),c=Symbol("ended"),u=Symbol("lastPromise"),d=Symbol("handlePromise"),h=Symbol("stream");function f(e,t){return{value:e,done:t}}function p(e){var t=e[o];if(null!==t){var r=e[h].read();null!==r&&(e[u]=null,e[o]=null,e[a]=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[d](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[u];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[d])}return this[u]=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,o,{value:null,writable:!0}),s(t,a,{value:null,writable:!0}),s(t,l,{value:null,writable:!0}),s(t,c,{value:e._readableState.endEmitted,writable:!0}),s(t,d,{value:function(e,t){var n=r[h].read();n?(r[u]=null,r[o]=null,r[a]=null,e(f(n,!1))):(r[o]=e,r[a]=t)},writable:!0}),t));return r[u]=null,i(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=r[a];return null!==t&&(r[u]=null,r[o]=null,r[a]=null,t(e)),void(r[l]=e)}var n=r[o];null!==n&&(r[u]=null,r[o]=null,r[a]=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 o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(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&&a(e.prototype,t),r&&a(e,r),e}var c=e("buffer").Buffer,u=e("util").inspect,d=u&&u.custom||"inspect";function h(e,t,r){c.prototype.copy.call(e,t,r)}t.exports=function(){function e(){o(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:d,value:function(e,t){return u(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,a=this._readableState&&this._readableState.destroyed,l=this._writableState&&this._writableState.destroyed;return a||l?(r?r(t):t&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,e.nextTick(o,this,t)):e.nextTick(o,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){o(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 o(e,t){e.emit("error",t)}function a(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:a}}).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 o(e){return e.setHeader&&"function"==typeof e.abort}function a(e,t,r){if("function"==typeof t)return a(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,u=function(){e.writable||h()},d=e._writableState&&e._writableState.finished,h=function(){c=!1,d=!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&&!d?(e._writableState&&e._writableState.ended||(t=new n),r.call(e,t)):void 0},y=function(){e.req.on("finish",h)};return o(e)?(e.on("complete",h),e.on("abort",m),e.req?y():e.on("request",y)):c&&!e._writableState&&(e.on("end",u),e.on("close",u)),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",u),e.removeListener("close",u),e.removeListener("finish",h),e.removeListener("end",p),e.removeListener("error",g),e.removeListener("close",m)}}t.exports=a},{"../../../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,o=i.ERR_MISSING_ARGS,a=i.ERR_STREAM_DESTROYED;function l(e){if(e)throw e}function c(e){return e.setHeader&&"function"==typeof e.abort}function u(t,r,i,o){o=s(o);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 o(e);l=!0,o()}));var u=!1;return function(e){if(!l&&!u)return u=!0,c(t)?t.abort():"function"==typeof t.destroy?t.destroy():void o(e||new a("pipe"))}}function d(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 o("streams");var i=t.map((function(e,r){var o=r<t.length-1;return u(e,o,r>0,(function(e){n||(n=e),e&&i.forEach(d),o||(i.forEach(d),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 o=s(t,i,r);if(null!=o){if(!isFinite(o)||Math.floor(o)!==o||o<0)throw new n(i?r:"highWaterMark",o);return Math.floor(o)}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 o=n[i],a=e[o];"object"!=typeof a||null===a?s[o]=a:a instanceof Date?s[o]=new Date(a):ArrayBuffer.isView(a)?s[o]=r(a):s[o]=t(a)}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 o=e[i];"object"!=typeof o||null===o?s[i]=o:o instanceof Date?s[i]=new Date(o):o instanceof Map?s[i]=new Map(t(Array.from(o),n)):o instanceof Set?s[i]=new Set(t(Array.from(o),n)):ArrayBuffer.isView(o)?s[i]=r(o):s[i]=n(o)}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 o=e[s];"object"!=typeof o||null===o?n[s]=o:o instanceof Date?n[s]=new Date(o):o instanceof Map?n[s]=new Map(t(Array.from(o),i)):o instanceof Set?n[s]=new Set(t(Array.from(o),i)):ArrayBuffer.isView(o)?n[s]=r(o):n[s]=i(o)}return n}}function s(e){var t=[],n=[];return e.proto?o:i;function s(e,s){for(var i=Object.keys(e),o=new Array(i.length),a=0;a<i.length;a++){var l=i[a],c=e[l];if("object"!=typeof c||null===c)o[l]=c;else if(c instanceof Date)o[l]=new Date(c);else if(ArrayBuffer.isView(c))o[l]=r(c);else{var u=t.indexOf(c);o[l]=-1!==u?n[u]:s(c)}}return o}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 o={};for(var a in t.push(e),n.push(o),e)if(!1!==Object.hasOwnProperty.call(e,a)){var l=e[a];if("object"!=typeof l||null===l)o[a]=l;else if(l instanceof Date)o[a]=new Date(l);else if(l instanceof Map)o[a]=new Map(s(Array.from(l),i));else if(l instanceof Set)o[a]=new Set(s(Array.from(l),i));else if(ArrayBuffer.isView(l))o[a]=r(l);else{var c=t.indexOf(l);o[a]=-1!==c?n[c]:i(l)}}return t.pop(),n.pop(),o}function o(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return s(e,o);if(e instanceof Map)return new Map(s(Array.from(e),o));if(e instanceof Set)return new Set(s(Array.from(e),o));var i={};for(var a in t.push(e),n.push(i),e){var l=e[a];if("object"!=typeof l||null===l)i[a]=l;else if(l instanceof Date)i[a]=new Date(l);else if(l instanceof Map)i[a]=new Map(s(Array.from(l),o));else if(l instanceof Set)i[a]=new Set(s(Array.from(l),o));else if(ArrayBuffer.isView(l))i[a]=r(l);else{var c=t.indexOf(l);i[a]=-1!==c?n[c]:o(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 o(e,t,r){return s(e,t,r)}s.from&&s.alloc&&s.allocUnsafe&&s.allocUnsafeSlow?t.exports=n:(i(n,r),r.Buffer=o),o.prototype=Object.create(s.prototype),i(s,o),o.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return s(e,t,r)},o.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},o.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return s(e)},o.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 o(e){var t=i(e);if("string"!=typeof t&&(n.isEncoding===s||!s(e)))throw new Error("Unknown encoding: "+e);return t||e}function a(e){var t;switch(this.encoding=o(e),this.encoding){case"utf16le":this.text=p,this.end=g,t=4;break;case"utf8":this.fillLast=d,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 u(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 d(e){var t=this.lastTotal-this.lastNeed,r=u(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=a,a.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||""},a.prototype.end=f,a.prototype.text=h,a.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=T,r.resolveObject=S,r.format=E,r.Url=i;var o=/^([a-z0-9.+-]+:)/i,a=/:[0-9]*$/,l=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,c=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),u=["'"].concat(c),d=["%","/","?",";","#"].concat(u),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 T(e,t){return w(e,!1,!0).resolve(t)}function S(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("?"),a=-1!==i&&i<e.indexOf("#")?"?":"#",c=e.split(a),w=/\\/g;c[0]=c[0].replace(w,"/");var E=e=c.join(a);if(E=E.trim(),!r&&1===e.split("#").length){var T=l.exec(E);if(T)return this.path=E,this.href=E,this.pathname=T[1],T[2]?(this.search=T[2],this.query=t?b.parse(this.search.substr(1)):this.search.substr(1)):t&&(this.search="",this.query={}),this}var S=o.exec(E);if(S){var C=(S=S[0]).toLowerCase();this.protocol=C,E=E.substr(S.length)}if(r||S||E.match(/^\/\/[^@\/]+@[^@\/]+/)){var k="//"===E.substr(0,2);!k||S&&y[S]||(E=E.substr(2),this.slashes=!0)}if(!y[S]&&(k||S&&!v[S])){for(var A,_,I=-1,R=0;R<h.length;R++)-1!==(L=E.indexOf(h[R]))&&(-1===I||L<I)&&(I=L);for(-1!==(_=-1===I?E.lastIndexOf("@"):E.lastIndexOf("@",I))&&(A=E.slice(0,_),E=E.slice(_+1),this.auth=decodeURIComponent(A)),I=-1,R=0;R<d.length;R++){var L;-1!==(L=E.indexOf(d[R]))&&(-1===I||L<I)&&(I=L)}-1===I&&(I=E.length),this.host=E.slice(0,I),E=E.slice(I),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,N=P.length;F<N;F++)P.charCodeAt(F)>127?M+="x":M+=P[F];if(!M.match(p)){var U=x.slice(0,R),B=x.slice(R+1),j=P.match(g);j&&(U.push(j[1]),B.unshift(j[2])),B.length&&(E="/"+B.join(".")+E),this.hostname=U.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=u.length;R<O;R++){var K=u[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,o="";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&&(o=b.stringify(this.query));var a=this.search||o&&"?"+o||"";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),a&&"?"!==a.charAt(0)&&(a="?"+a),t+i+(r=r.replace(/[?#]/g,(function(e){return encodeURIComponent(e)})))+(a=a.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),o=0;o<n.length;o++){var a=n[o];r[a]=this[a]}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 u=l[c];"protocol"!==u&&(r[u]=e[u])}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 d=Object.keys(e),h=0;h<d.length;h++){var f=d[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,T=E,S=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&&(""===S[0]?S[0]=r.host:S.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]||""===S[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,S=p;else if(p.length)S||(S=[]),S.pop(),S=S.concat(p),r.search=e.search,r.query=e.query;else if(!s.isNullOrUndefined(e.search))return C&&(r.hostname=r.host=S.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(!S.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var k=S.slice(-1)[0],A=(r.host||e.host||S.length>1)&&("."===k||".."===k)||""===k,_=0,I=S.length;I>=0;I--)"."===(k=S[I])?S.splice(I,1):".."===k?(S.splice(I,1),_++):_&&(S.splice(I,1),_--);if(!E&&!T)for(;_--;_)S.unshift("..");!E||""===S[0]||S[0]&&"/"===S[0].charAt(0)||S.unshift(""),A&&"/"!==S.join("/").substr(-1)&&S.push("");var R,L=""===S[0]||S[0]&&"/"===S[0].charAt(0);return C&&(r.hostname=r.host=L?"":S.length?S.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&&S.length)&&!L&&S.unshift(""),S.length?r.pathname=S.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=a.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!==ut?ut:"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 a(r,null,t,e):new a(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 a(t,e.tail,null,e),e.head||(e.head=e.tail),e.length++}function o(e,t){e.head=new a(t,null,e.head,e),e.tail||(e.tail=e.head),e.length++}function a(e,t,r,n){if(!(this instanceof a))return new a(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=a,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++)o(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 o=[];for(n=0;i&&n<t;n++)o.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 o},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)}(Ao);var _o=dt(Ao.exports);class Io{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 Ro=()=>"undefined"!=typeof window&&window.localStorage?window:{localStorage:new Io};var Lo={},Do={},xo={};Object.defineProperty(xo,"__esModule",{value:!0}),xo.bytesToString=xo.stringToBytes=xo.NIL=xo.X500=xo.OID=xo.URL=xo.DNS=xo.hexToByte=xo.byteToHex=void 0;let Oo=[],Po={};for(var Mo=0;Mo<256;Mo++)Oo[Mo]=(Mo+256).toString(16).substr(1),Po[Oo[Mo]]=Mo;xo.byteToHex=Oo,xo.hexToByte=Po,xo.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",xo.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",xo.OID="6ba7b812-9dad-11d1-80b4-00c04fd430c8",xo.X500="6ba7b814-9dad-11d1-80b4-00c04fd430c8",xo.NIL="00000000-0000-0000-0000-000000000000";xo.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};xo.bytesToString=e=>{const t=new Uint8Array(e,0,e.byteLength);return String.fromCharCode.apply(null,Array.from(t))},Object.defineProperty(Do,"__esModule",{value:!0}),Do.parse=void 0;const Fo=xo;Do.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++]=Fo.hexToByte[e]),"")));s<16;)t[n+s++]=0;return t};var No={};Object.defineProperty(No,"__esModule",{value:!0}),No.unparse=void 0;const Uo=xo;No.unparse=(e,t)=>{let r=t||0,n=Uo.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 Bo={},jo={};Object.defineProperty(jo,"__esModule",{value:!0});jo.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 $o=ut&&ut.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Bo,"__esModule",{value:!0}),Bo.validate=void 0;const qo=$o(jo);Bo.validate=e=>"string"==typeof e&&qo.default.test(e);var Ko={};Object.defineProperty(Ko,"__esModule",{value:!0}),Ko.version=void 0;const Go=Bo;Ko.version=e=>{if(!Go.validate(e))throw TypeError("Invalid UUID");return parseInt(e.substr(14,1),16)};var Ho={},Vo={};Object.defineProperty(Vo,"__esModule",{value:!0}),Vo.stringify=void 0;const zo=Bo,Wo=[];for(let e=0;e<256;++e)Wo.push((e+256).toString(16).substr(1));Vo.stringify=(e,t=0)=>{const r=(Wo[e[t+0]]+Wo[e[t+1]]+Wo[e[t+2]]+Wo[e[t+3]]+"-"+Wo[e[t+4]]+Wo[e[t+5]]+"-"+Wo[e[t+6]]+Wo[e[t+7]]+"-"+Wo[e[t+8]]+Wo[e[t+9]]+"-"+Wo[e[t+10]]+Wo[e[t+11]]+Wo[e[t+12]]+Wo[e[t+13]]+Wo[e[t+14]]+Wo[e[t+15]]).toLowerCase();if(!zo.validate(r))throw TypeError("Stringified UUID is invalid");return r};var Yo={};Object.defineProperty(Yo,"__esModule",{value:!0}),Yo.rng=void 0;Yo.rng=()=>{let e=new Array(16);for(let t=0;t<16;t++)e[t]=255&256*Math.random()+0;return e},Object.defineProperty(Ho,"__esModule",{value:!0}),Ho.v1=void 0;const Qo=Vo,Xo=Yo;let Jo,Zo,ea=0,ta=0;Ho.v1=(e,t,r=0)=>{let n=t&&r||0;const s=t||new Uint8Array(16);let i=e&&e.node?e.node:Jo,o=e&&e.clockseq?e.clockseq:Zo;if(null==i||null==o){const t=e&&e.random?e.random:e&&e.rng?e.rng():Xo.rng();null==i&&(i=Jo=[1|t[0],t[1],t[2],t[3],t[4],t[5]]),null==o&&(o=Zo=16383&(t[6]<<8|t[7]))}let a=e&&e.msecs?e.msecs:Date.now(),l=e&&e.nsecs?e.nsecs:ta+1;const c=a-ea+(l-ta)/1e4;if(c<0&&e&&!e.clockseq&&(o=o+1&16383),(c<0||a>ea)&&e&&!e.nsecs&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");ea=a,ta=l,Zo=o,a+=122192928e5;const u=(1e4*(268435455&a)+l)%4294967296;s[n++]=u>>>24&255,s[n++]=u>>>16&255,s[n++]=u>>>8&255,s[n++]=255&u;const d=a/4294967296*1e4&268435455;s[n++]=d>>>8&255,s[n++]=255&d,s[n++]=d>>>24&15|16,s[n++]=d>>>16&255,s[n++]=o>>>8|128,s[n++]=255&o;for(let e=0;e<6;++e)s[n+e]=i[e];return t||Qo.stringify(s)};var ra={};Object.defineProperty(ra,"__esModule",{value:!0}),ra.v4=void 0;const na=No,sa=Yo;ra.v4=(e,t,r)=>{let n=t&&r||0,s=sa.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||na.unparse(s)};var ia={},oa={};Object.defineProperty(oa,"__esModule",{value:!0}),oa.v35=void 0;const aa=Vo,la=Do,ca=xo;oa.v35=(e,t,r)=>(e,n,s,i=0)=>{if("string"==typeof e&&(e=ca.stringToBytes(e)),"string"==typeof n&&(n=la.parse(n)),n&&16!==n.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let o=new Uint8Array(16+e.length);if(o.set(n),o.set(e,n.length),o=ca.stringToBytes(r(ca.bytesToString(o))),o[6]=15&o[6]|t,o[8]=63&o[8]|128,s)for(let e=0;e<16;++e)s[i+e]=o[e];return s||aa.stringify(o)};var ua={};!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=>o(n(l(e)));e.any_sha1=(e,t)=>a(n(l(e)),t);e.hex_hmac_sha1=(e,t)=>i(s(l(e),l(t)));e.b64_hmac_sha1=(e,t)=>o(s(l(e),l(t)));e.any_hmac_sha1=(e,t,r)=>a(s(l(e),l(t)),r);const n=e=>u(d(c(e),8*e.length)),s=(e,t)=>{let r=c(e);r.length>16&&(r=d(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 o=d(n.concat(c(t)),512+8*t.length);return u(d(s.concat(o),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},o=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),o=0;o<4;o++)8*s+6*o>8*e.length?t+=r:t+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(i>>>6*(3-o)&63);return t},a=(e,t)=>{var r,n,s,i,o=t.length,a=[],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/o))*o,(i.length>0||n>0)&&(i[i.length]=n);a[a.length]=s,l=i}var c="";for(r=a.length-1;r>=0;r--)c+=t.charAt(a[r]);var u=Math.ceil(8*e.length/(Math.log(t.length)/Math.log(2)));for(r=c.length;r<u;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},u=e=>{for(var t="",r=0;r<32*e.length;r+=8)t+=String.fromCharCode(e[r>>5]>>>24-r%32&255);return t},d=(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,o=271733878,a=-1009589776,l=0;l<e.length;l+=16){for(var c=n,u=s,d=i,m=o,y=a,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,o)),p(p(a,r[v]),f(v)));a=o,o=i,i=g(s,30),s=n,n=t}n=p(n,c),s=p(s,u),i=p(i,d),o=p(o,m),a=p(a,y)}return[n,s,i,o,a]},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}(ua);var da=ut&&ut.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ia,"__esModule",{value:!0}),ia.v5=void 0;const ha=oa,fa=da(ua);ia.v5=ha.v35("v5",80,fa.default),Object.defineProperty(Lo,"__esModule",{value:!0});const pa=Do,ga=No,ma=Bo,ya=Ko,va=Ho,ba=ra,wa=ia,Ea=xo;var Ta=Lo.default={parse:pa.parse,unparse:ga.unparse,validate:ma.validate,version:ya.version,v1:va.v1,v4:ba.v4,v5:wa.v5,NIL:Ea.NIL,DNS:Ea.DNS,URL:Ea.URL,OID:Ea.OID,X500:Ea.X500};const Sa=()=>Ta.v4().toString();let Ca=0;if("undefined"!=typeof BroadcastChannel&&"undefined"!=typeof window){const e=Sa(),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:Ca}),"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&&(Ca=e.reduce(((e,t)=>e<t?e:t+1),0))}),15))))}}const ka=async()=>{const e=await(async e=>new Promise((t=>{t(Ro().localStorage.getItem(e))})))("deviceId");if(e)return e;const t=`ascWebSdk#${Sa()}`;return await(async(e,t)=>new Promise((r=>{Ro().localStorage.setItem(e,t),r(!0)})))("deviceId",t),t},Aa=()=>{const e=(()=>{var e,t;return(null===(e=Et.versions)||void 0===e?void 0:e.node)?Et.versions.node:navigator?`${navigator.product.toLowerCase()}#${null!==(t=navigator.userAgent)&&void 0!==t?t:"unknown_agent"}`:"unknown_model"})();return{kind:"web",model:e,sdkVersion:d}},_a=1e3;var Ia;!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"}(Ia||(Ia={}));const Ra=e=>{let t;return{connect:async function(r){const n=await(async e=>`mqttjs_${await ka()}_${e}_${Ca}`)(r.userId);return t&&(t.removeAllListeners(),t.end(!0)),t=_o.connect(e,function(e){return Object.assign({clean:!1,clientId:`mqttjs_ + ${Math.random().toString(16).substring(2,10)}`,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:_a,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=_a,(()=>{const e=[ct(it()),ct(ot()),ct(at()),ct(lt()),ct(nt($e()))]})()})),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||_a),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 he(t.message,8e5,"error"):new pe(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)}}},La=(e={},t,r=!0)=>{Object.entries(e).forEach((([e,n])=>{const s=ue[e];if(!s)return;const i=ce(s);i&&n.forEach((e=>{(r?Ee:Se)([s,"get",i(e)],e,t)}))}))},Da=(e,t)=>{const{log:r,cache:n}=ye(),s=[e,y,t],i={cachedAt:Date.now()};n&&(r("cache/api/pushToTombstone",{cacheKey:s,data:i}),Ce([e,"get",t],!0),Ee(s,i))};function xa(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 Oa=(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(!ye().cache)return;return(null===(r=we(["user","get",e[t]]))||void 0===r?void 0:r.data)||void 0}},e))(e,t,r))))&&void 0!==n?n:e},Pa=(e,t,r="userId",n="user")=>{const s=e,i=t,o=s[i],a=xa(s,["symbol"==typeof i?i:i+""]),l=Oa(o,r,n);return Object.assign(Object.assign({},a),{[t]:l})};function Ma(e){return e.map((e=>{var{isMentioned:t}=e,r=xa(e,["isMentioned"]);return Object.assign({hasMentioned:t},r)}))}function Fa(e){return Ma(e)}function Na(e){return Ma(e)}function Ua(e){return Ma(e)}const Ba=(e,t)=>{var r,n,s;return(null==t?void 0:t.isDeleted)?0:null!==(s=null!==(r=null==t?void 0:t.unreadCount)&&void 0!==r?r:null===(n=(e=>{var t;const r={entityId:e,userId:$e()._id};return null===(t=we(["channelMarker","get",ce("channelMarker")(r)]))||void 0===t?void 0:t.data})(e.channelId))||void 0===n?void 0:n.unreadCount)&&void 0!==s?s:0},ja=(e,t)=>{var r,n;return void 0!==(null==t?void 0:t.hasMentioned)?null==t?void 0:t.hasMentioned:null!==(n=null===(r=(e=>{var t;const r={entityId:e,userId:$e()._id};return null===(t=we(["channelMarker","get",ce("channelMarker")(r)]))||void 0===t?void 0:t.data})(e.channelId))||void 0===r?void 0:r.hasMentioned)&&void 0!==n&&n},$a=e=>{var t,r;return null!==(r=null===(t=we(["messagePreviewChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==r?r:null},qa=["analytic","normal-priority"],Ka=["analytic","high-priority"],Ga=async e=>{const t=ye();await t.http.post("/api/v1/analytics/activities",{activities:e})};class Ha{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=we(qa);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await Ga(t),Ce(qa)}catch(e){this.stop(),Ce(qa)}}async syncHighPriorityCapturedEvent(){try{const e=we(Ka);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await Ga(t),Ce(Ka)}catch(e){this.stop(),Ce(Ka)}}}class Va{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*g);return!(n.getTime()-s.getTime()<t)}markPostAsViewed(e){if(!this.isAbleToEnqueue({itemId:e,expireTime:this._expireTime}))return;const t=new Date,r={event:[]},n=we(qa);(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()}),Se(qa,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=we(Ka);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()}),Se(Ka,s),this._recentHighPriorityViewed[e.storyId]=r,"linkClicked"===t)return;Ee(["story-seen","get",e.storyId],(new Date).toISOString());const o=we(["story-last-seen",e.targetId]);(null==o?void 0:o.data)?new Date(o.data).getTime()<new Date(e.expiresAt).getTime()&&Ee(["story-last-seen",e.targetId],e.expiresAt):Ee(["story-last-seen",e.targetId],e.expiresAt),this._bufferNewSeenStoryReferenceIds.push(e.referenceId),this._throttleStoryTimer||(this._throttleStoryTimer=setTimeout((()=>{clearTimeout(this._throttleStoryTimer),Qe("local.story.updated",{referenceIds:this._bufferNewSeenStoryReferenceIds}),this._bufferNewSeenStoryReferenceIds=[]}),300))}markStoryAsViewed(e){this.markStory(e,"view")}markStoryAsClicked(e){this.markStory(e,"linkClicked")}}class za{constructor(){this._client=ye(),this._eventCapturer=new Va,this._eventSyncer=new Ha}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(),Ce(qa)}}let Wa;var Ya=()=>(Wa||(Wa=new za),Wa);const Qa=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=we(["file","get",`${e.avatarFileId}`]);return(null==n?void 0:n.data)&&(r=null==n?void 0:n.data),r}}),Xa=e=>{const t=we(["story-expire",e.targetId]),r=we(["story-last-seen",e.targetId]),n=(new Date).getTime(),s=e.lastStoryExpiresAt?new Date(e.lastStoryExpiresAt).getTime():0,i=e.lastStorySeenExpiresAt?new Date(e.lastStorySeenExpiresAt).getTime():0,o=(null==t?void 0:t.data)?new Date(null==t?void 0:t.data).getTime():0,a=(null==r?void 0:r.data)?new Date(null==r?void 0:r.data).getTime():0,l=Math.max(i,a),c=we(["story-sync-state",e.targetId]);return(null==c?void 0:c.data)&&["syncing","error"].includes(c.data)?o>n&&o>l:s>n&&s>l},Ja=e=>{const{targetType:t,targetId:r,lastStoryExpiresAt:n,lastStorySeenExpiresAt:s,targetUpdatedAt:i}=e;return{targetType:t,targetId:r,updatedAt:i,hasUnseen:Xa({targetId:r,lastStoryExpiresAt:n,lastStorySeenExpiresAt:s})}},Za=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=we(["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=we(["user","get",e.userId]);if(null==t?void 0:t.data)return Qa(t.data)},get childrenComment(){return e.children.map((e=>{const t=we(["comment","get",e]);if(null==t?void 0:t.data)return null==t?void 0:t.data})).filter((e=>e)).map((e=>Za(e)))}}),el={comment:Za,post:e=>Object.assign(Object.assign({},e),{analytics:{markAsViewed:()=>{Ya().markPostAsViewed(e.postId)}},get latestComments(){return e.comments&&e.comments.map((e=>{var t;const r=null===(t=we(["comment","get",e]))||void 0===t?void 0:t.data;return r?Za(r):null})).filter(Boolean)||[]},get creator(){const t=we(["user","get",e.postedUserId]);if(null==t?void 0:t.data)return Qa(t.data)}}),user:Qa,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=we(["file","get",`${e.avatarFileId}`]);return(null==n?void 0:n.data)&&(r=null==n?void 0:n.data),r}}),story:e=>{const t=Ya(),r=we(["storyTarget","get",e.targetId]),n=we(["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=we(["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=we(["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=we(["category","get",e]);return(null==t?void 0:t.data)||void 0})).filter((e=>void 0!==e)):void 0},get creator(){const t=we(["user","get",e.creatorPublicId]);if(null==t?void 0:t.data)return Qa(t.data)},get storyTarget(){if(null==r?void 0:r.data)return Ja(r.data)},get isSeen(){const t=we(["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:Ja},tl=e=>{var t;const r=e.messagePreviewId?$a(e.channelId):null,n=null===(t=we(["user","get",null==r?void 0:r.creatorId]))||void 0===t?void 0:t.data,s=r?Object.assign(Object.assign({},r),{user:n?el.user(n):void 0}):null;return Object.assign(Object.assign({},e),{messagePreview:s})},rl=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:o,dataType:a,isDeleted:l,segment:c,creatorPublicId:u,createdAt:d,updatedAt:h}=t;return{channelId:s,subChannelId:i,data:o,dataType:a,isDeleted:l,segment:c,creatorId:u,createdAt:d,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:[]};La(n)},nl=e=>{var t,r;return null!==(r=null===(t=we(["messagePreviewSubChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==r?r:null},sl=e=>{var t;const r=e.messagePreviewId?nl(e.subChannelId):null,n=r?Object.assign(Object.assign({},r),{user:null===(t=we(["user","get",null==r?void 0:r.creatorId]))||void 0===t?void 0:t.data}):null;return Object.assign(Object.assign({},e),{messagePreview:n})},il=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:o,creatorPublicId:a,data:l,dataType:c,isDeleted:u,segment:d,createdAt:h,updatedAt:f}=t;return{messagePreviewId:o,channelId:s,subChannelId:i,data:l,dataType:c,isDeleted:u,segment:d,creatorId:a,createdAt:h,updatedAt:f,subChannelName:null==n?void 0:n.name,subChannelUpdatedAt:null==n?void 0:n.updatedAt}})(t))))&&void 0!==r?r:[]};La(n)};function ol(e){const t=Object.create(Object.getPrototypeOf(e)),r=Object.getOwnPropertyDescriptors(e);return Object.defineProperties(t,r),t}function al(e,t,r){Ee(["subChannel","get",e],Object.assign(ol(t),r))}const ll=async e=>{var t,r,n,s;const{channelId:i,messageId:o,creatorId:a,createdAt:l,updatedAt:c,data:u,dataType:d,subChannelId:h,channelSegment:f,isDeleted:p}=e,g=null===(t=we(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(!g||g.segment<=e.channelSegment){const t=null===(r=we(["subChannel","get",h]))||void 0===r?void 0:r.data;Ee(["messagePreviewSubChannel","get",e.subChannelId],{channelId:i,creatorId:a,messagePreviewId:o,createdAt:l,updatedAt:c,subChannelId:h,data:u,dataType:d,segment:f,isDeleted:p,subChannelUpdatedAt:null==t?void 0:t.updatedAt,subChannelName:null==t?void 0:t.displayName}),al(e.subChannelId,t,{messagePreviewId:o})}const m=null===(n=we(["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=we(["subChannel","get",h]))||void 0===s?void 0:s.data;Ee(["messagePreviewChannel","get",e.channelId],{channelId:i,creatorId:a,messagePreviewId:o,createdAt:l,updatedAt:c,subChannelId:h,data:u,dataType:d,segment:f,isDeleted:p,subChannelUpdatedAt:null==t?void 0:t.updatedAt,subChannelName:null==t?void 0:t.displayName})}},cl=async e=>{var t,r,n,s;const{channelId:i,messageId:o,creatorId:a,createdAt:l,updatedAt:c,data:u,dataType:d,subChannelId:h,channelSegment:f,isDeleted:p}=e,g=null===(t=we(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(g&&g.messagePreviewId===e.messageId){const t=null===(r=we(["subChannel","get",h]))||void 0===r?void 0:r.data;al(e.subChannelId,t,{messagePreviewId:o}),Ee(["messagePreviewSubChannel","get",e.subChannelId],{channelId:i,creatorId:a,messagePreviewId:o,createdAt:l,updatedAt:c,subChannelId:h,data:u,dataType:d,segment:f,isDeleted:p,subChannelUpdatedAt:null==e?void 0:e.updatedAt,subChannelName:null==t?void 0:t.displayName})}const m=null===(n=we(["messagePreviewChannel","get",e.channelId]))||void 0===n?void 0:n.data;if(m&&m.messagePreviewId===e.messageId){const t=null===(s=we(["subChannel","get",h]))||void 0===s?void 0:s.data;Ee(["messagePreviewChannel","get",e.channelId],{channelId:i,creatorId:a,messagePreviewId:o,createdAt:l,updatedAt:c,subChannelId:h,data:u,dataType:d,segment:f,isDeleted:p,subChannelUpdatedAt:null==t?void 0:t.updatedAt,subChannelName:null==t?void 0:t.displayName})}},ul=async e=>{var t,r,n,s;const{channelId:i,subChannelId:o}=e,a=null===(t=we(["messagePreviewChannel","get",i]))||void 0===t?void 0:t.data;if((null==a?void 0:a.subChannelId)===o){const e=null===(r=we(["subChannel","get",o]))||void 0===r?void 0:r.data;Ee(["messagePreviewChannel","get",i],Object.assign(Object.assign({},a),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}const l=null===(n=we(["messagePreviewSubChannel","get",o]))||void 0===n?void 0:n.data;if(l&&new Date(l.updatedAt).valueOf()>new Date(e.updatedAt).valueOf()){const e=null===(s=we(["subChannel","get",o]))||void 0===s?void 0:s.data;Ee(["messagePreviewSubChannel","get",o],Object.assign(Object.assign({},l),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}},dl=["broadcast","conversation","community"],hl=({type:e})=>dl.includes(e);function fl(e,t={isMessagePreviewUpdated:!0}){var r;let{messagePreviewId:n}=e;const s=null===(r=we(["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 Ba(e)},get hasMentioned(){return ja(e)}},e),{defaultSubChannelId:e._id,isUnreadCountSupport:hl(e),messagePreviewId:n})}const pl=(e,t={isMessagePreviewUpdated:!0})=>{La({channels:e.channels.map((e=>fl(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated})))})},gl=async(e,t={isMessagePreviewUpdated:!0})=>{const r=ye(),n=await r.getMessagePreviewSetting(!1);t.isMessagePreviewUpdated&&"no-message-preview"!==n&&e.messagePreviews&&e.messagePreviews.length>0&&rl(e);const s=e.channels.filter(hl).map((({channelId:e})=>e));if(s.length>0){pl(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated});try{await(async e=>{const t=ye();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=Fa(s),o=Na(n),a=t.cache&&Date.now();return t.cache&&La({userEntityMarkers:o,userMarkers:i},{cachedAt:a}),Qe("local.channelMarker.fetched",{userEntityMarkers:o}),Qe("local.userMarker.fetched",{userMarkers:i}),{data:o,cachedAt:a}})(s)}catch(e){}}const i=e.channels.map((e=>fl(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated}))),o=Oa(e.channelUsers),a=xa(e,["messageFeedsInfo","messagePreviews"]);return Object.assign(Object.assign({},a),{channels:i,channelUsers:o})},ml=async e=>{const t=ye();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=>{S(null==t?void 0:t.code)&&Da("channel",e)})),t}const s=await gl(n),i=t.cache&&Date.now();return t.cache&&La(s,{cachedAt:i}),{data:s.channels,cachedAt:i}};ml.locally=e=>{var t;const r=ye();if(r.log("channel/getChannelByIds.locally",e),!r.cache)return;const n=e.map((e=>we(["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 yl=async()=>{const e=ye();e.log("channel/getUserMarker");const{data:t}=await e.http.get("/api/v1/markers/userMarker"),{userMarkers:r}=t,n=Fa(r),s=e.cache&&Date.now();return e.cache&&La({userMarkers:n},{cachedAt:s}),Qe("local.userMarker.fetched",{userMarkers:n}),{data:n[0],cachedAt:s}},vl=e=>!0===e&&void 0,bl=(e,t)=>{var r;return null!==(r=null!=t?t:(e=>{var t,r;const n={creatorId:e.creatorId,feedId:null!==(t=e.messageFeedId)&&void 0!==t?t:e.subChannelId,contentId:e.messageId};return null===(r=we(["messageMarker","get",ce("messageMarker")(n)]))||void 0===r?void 0:r.data})(e))&&void 0!==r?r:{readCount:0,deliveredCount:0}};const wl=["broadcast","conversation","community"],El=({channelType:e})=>wl.includes(e);function Tl(e){var{channelId:t,channelPublicId:r,channelType:n,childCount:s,creatorId:i,creatorPublicId:o,lastMessageId:a,lastMessageTimestamp:l,messageFeedId:c,name:u}=e,d=xa(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;if(r)return r.unreadCount;const s={entityId:e,feedId:t,userId:$e()._id},i=null===(n=we(["subChannelMarker","get",ce("subChannelMarker")(s)]))||void 0===n?void 0:n.data;return i?i.unreadCount:0}(t,c)},get hasMentioned(){return function(e,t,r){var n;if(r)return r.hasMentioned;const s={entityId:e,feedId:t,userId:$e()._id},i=null===(n=we(["subChannelMarker","get",ce("subChannelMarker")(s)]))||void 0===n?void 0:n.data;return!!i&&i.hasMentioned}(t,c)}},d),{channelId:r,creatorId:o,displayName:u,lastActivity:l,latestMessageId:a,messageCount:s,subChannelId:c,isUnreadCountSupport:El({channelType:n})})}function Sl(e,t,r){var n;const{channelPublicId:s,childCount:i,creatorPublicId:o,mentionedUsers:a,messageFeedId:l,myReactions:c,reactionCount:u,reactions:d,referenceId:h,segment:f,messageId:p}=e,g=xa(e,["channelPublicId","childCount","creatorPublicId","mentionedUsers","messageFeedId","myReactions","reactionCount","reactions","referenceId","segment","messageId"]);let m;h&&(m=we(["message","get",h])),m||(m=we(["message","get",p]));const y=Object.assign(Object.assign({get readCount(){return bl(e).readCount},get deliveredCount(){return bl(e).deliveredCount}},g),{messageId:p,channelId:s,channelSegment:f,childrenNumber:i,creatorId:o,reactions:null!=d?d:{},myReactions:c||(null!==(n=null==m?void 0:m.data.myReactions)&&void 0!==n?n:[]),reactionsCount:u,subChannelId:l,uniqueId:m?m.data.uniqueId:p,referenceId:h});return a&&(y.mentionees=a.map((e=>"channel"===e.type?e:{type:"user",userIds:e.userPublicIds}))),t&&t.length&&r&&((e,t,r)=>{const n=ye(),s=we(["message","get",e.messageId]),i=(null==s?void 0:s.data.myReactions)||[];Object.assign(e,{myReactions:i});const o=t[0];o&&o.userId===n.userId&&("message.reactionAdded"!==r||i.includes(o.reactionName)||Object.assign(e,{myReactions:[...i,o.reactionName]}),"message.reactionRemoved"===r&&i.includes(o.reactionName)&&Object.assign(e,{myReactions:i.filter((e=>e!==o.reactionName))}))})(y,t,r),y}const Cl=async(e,t)=>{const r=e.messages.map((({messageId:e})=>e));if(r.length>0){La({messages:(n=e).messages.map((e=>Sl(e,n.reactions)))});try{await(async e=>{const t=ye();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,o=Fa(i),a=t.cache&&Date.now();return t.cache&&La({contentMarkers:n,feedMarkers:s,userMarkers:o},{cachedAt:a}),Qe("local.feedMarker.fetched",{feedMarkers:s}),Qe("local.messageMarker.fetched",{contentMarkers:n}),Qe("local.userMarker.fetched",{userMarkers:o}),{data:n,cachedAt:a}})(r)}catch(e){}}var n;const{messageFeeds:s}=e,i=xa(e,["messageFeeds"]);return s&&s.length>0&&(null==s||s.forEach((e=>{var t,r;const n=null!==(r=null===(t=we(["subChannel","get",e.messageFeedId]))||void 0===t?void 0:t.data)&&void 0!==r?r:{},s=xa(Tl(e),["unreadCount","hasMentioned"]);al(e.messageFeedId,n,s)}))),Object.assign(Object.assign({},i),{messages:e.messages.map((r=>Sl(r,e.reactions,t)))})};function kl(e){var{subChannelId:t,mentionees:r,dataType:n,data:s}=e,i=xa(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 Al(e){var{sortBy:t,subChannelId:r,tags:n,includingTags:s,excludingTags:i,includeDeleted:o,aroundMessageId:a,limit:l,type:c}=e,u=xa(e,["sortBy","subChannelId","tags","includingTags","excludingTags","includeDeleted","aroundMessageId","limit","type"]);const d=Object.assign(Object.assign({},u),{messageFeedId:r,isDeleted:vl(o),options:{sortBy:t,limit:l||h,around:a}});return n&&(d.includeTags=n),s&&(d.includeTags=s),c&&(d.dataType=c),i&&(d.excludeTags=i),d}const _l=["broadcast","conversation","community"],Il=({channelType:e})=>_l.includes(e),Rl=async e=>{const t=e.messageFeeds.filter(Il).map((({messageFeedId:e})=>e));if(t.length>0){(e=>{La({messageFeeds:e.messageFeeds.map((e=>Tl(e)))})})(e);try{await(async(e,t={limit:100})=>{const r=ye();r.log("channel/getSubChannelMarkers",e,t);const{data:n}=await r.http.get("/api/v1/markers/message-feeds",{params:{messageFeedIds:e,options:{token:Q(t,"skiplimit")}}}),{paging:s}=n,i=xa(n,["paging"]),{userEntityMarkers:o,userFeedMarkers:a,userMarkers:l}=i,c=Fa(l),u=Na(o),d=Ua(a),h=r.cache&&Date.now();r.cache&&La({userEntityMarkers:u,userFeedMarkers:d,userMarkers:c},{cachedAt:h}),Qe("local.channelMarker.fetched",{userEntityMarkers:u}),Qe("local.subChannelMarker.fetched",{userFeedMarkers:d}),Qe("local.userMarker.fetched",{userMarkers:c});const f=X(s.next);return{data:d,cachedAt:h,prevPage:X(s.previous),nextPage:f}})(t)}catch(e){}}il(e);const r=e.messageFeeds.map(Tl),n=e.messages.map((e=>Sl(e)));return Object.assign(Object.assign({},e),{messageFeeds:r,messages:n})};const Ll=e=>{const t=ye();return Ye(t,"client/onSessionStateChange","sessionStateChange",e)},Dl=(e,t)=>{const r=setInterval(e,t);return()=>clearInterval(r)},xl=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")),Ol=(e,t)=>{const{log:r,cache:n}=ye(),s=[e,y,t];if(!n)return;r("cache/api/isInTombstone",s);const i=we(s),{lifeSpan:o}=ie("cache_then_server",18e4);if(i&&ne(i.data,o))throw new fe("Item not found!",400400,"error")},Pl=async e=>{const t=ye();t.log("channel/getSubChannel",e),Ol("subChannel",e);try{const r=await t.http.get(`/api/v5/message-feeds/${encodeURIComponent(e)}`),n=await Rl(r.data),s=t.cache&&Date.now();return t.cache&&La(n,{cachedAt:s}),Qe("local.message-feed.fetched",n),{data:n.messageFeeds[0],cachedAt:s}}catch(t){throw S(null==t?void 0:t.code)&&Da("subChannel",e),t}};Pl.locally=e=>{const t=ye();if(t.log("channel/getSubChannel.locally",e),!t.cache)return;const r=we(["subChannel","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};let Ml=!1,Fl=[];const Nl={},Ul=async()=>{const e=Object.entries(Nl).filter((([,e])=>e)).map((([e])=>e));return 0!==e.length&&(async e=>{const t=ye();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:o}=r,a=Fa(o),l=Na(n),c=Ua(s),u=t.cache&&Date.now();return t.cache&&La({userEntityMarkers:l,userFeedMarkers:c,feedMarkers:i,userMarkers:a},{cachedAt:u}),Qe("local.feedMarker.fetched",{feedMarkers:i}),Qe("local.channelMarker.fetched",{userEntityMarkers:l}),Qe("local.subChannelMarker.fetched",{userFeedMarkers:c}),Qe("local.userMarker.fetched",{userMarkers:a}),!0})(e)},Bl=()=>{Ml=!1},jl=()=>(Ml=!0,Ll((e=>{"notLoggedIn"===e&&Bl()})),()=>{Bl()}),$l=async e=>{const t=await(async e=>{const t=Pl.locally(e);if(t)return t.data.channelId;const{data:r}=await Pl(e);return r.channelId})(e),r=st({channelId:t,subChannelId:e});Fl.push(ct(r))};Dl((async()=>{Ml&&await Ul()}),3e4);const ql=async e=>{const t=ye();t.log("channel/getSubChannels",e);const r=await t.http.get("/api/v5/message-feeds/list",{params:{messageFeedIds:e.map(encodeURIComponent)}}),n=await Rl(r.data),s=t.cache&&Date.now();return t.cache&&La(n,{cachedAt:s}),Qe("local.message-feed.fetched",n),{data:n.messageFeeds,cachedAt:s}};ql.locally=e=>{var t;const r=ye();if(r.log("channel/getSubChannels.locally",e),!r.cache)return;const n=e.map((e=>we(["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 Kl=async(e=!0)=>{var t;const r=null===(t=we(["MessagePreviewSetting"]))||void 0===t?void 0:t.data;if(!e&&r)return r;const n=await(async()=>{const e=ye(),{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"},Gl=async()=>{const e=ye(),{data:t}=await e.http.get("/api/v3/network-settings/feed-setting");return Object.fromEntries(t.feedSettings.map((({feedType:e,contentSettings:t})=>[e,t])))},Hl=async()=>{const e=ye(),{data:t}=await e.http.get("/api/v3/network-settings/social");return t.socialNetworkSetting},Vl={notLoggedIn:["establishing"],terminated:["establishing"],establishing:["notLoggedIn","established"],established:["notLoggedIn","terminated","tokenExpired","establishing"],tokenExpired:["establishing"]},zl=e=>{const t=ye();t.log("client/api/setSessionState",e);const{sessionState:r}=t;if(r===e)return!1;if(!((e,t)=>Vl[e].includes(t))(r,e))throw new he(`Session state cannot change from ${r} to ${e}`,8e5,"error");return t.sessionState=e,t.emitter.emit("sessionStateChange",e),!0},Wl=async e=>{const t=ye();zl("establishing");const{accessToken:r,users:n,expiresAt:s,issuedAt:i,refreshToken:o}=await(async e=>{const t=ye();t.log("client/api/getToken",e);const r=Aa(),{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},zl("established"),{accessToken:r,users:n,refreshToken:o}},Yl=e=>{const t=ye();return Ye(t,"onChannelDeleted","channel.deleted",(async t=>{const r=await gl(t);La(r),e(r.channels[0])}))},Ql=e=>{const t=ye();return Ye(t,"onChannelMemberBanned","channel.banned",(async t=>{const r=await gl(t),{channels:n,channelUsers:s}=r;La(r),e(n[0],s.find((e=>"banned"===e.membership)))}))},Xl=(e,t)=>{const r=ye();return Ye(r,e,e,(e=>{r.cache&&La(e),t(e.users[0])}))},Jl=e=>Xl("user.deleted",e);const Zl=async()=>{const e=ye();return e.log("client/api/disconnectClient"),e.mqtt.connected&&e.mqtt.disconnect(),e.ws.connected&&e.ws.disconnect(),"established"===e.sessionState&&zl("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.ws.io.opts.query={token:""},"tokenExpired"!==e.sessionState&&e.cache&&(e.cache={data:{}}),!0},ec=e=>{const t=ye();zl("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,Zl()},tc=["disconnected","error","connect_error","reconnect_error","reconnect_failed"],rc=e=>{const t=ye(),r=tc.map((r=>Ye(t,`client/onConnectionError(${r})`,r,(t=>{const n=(null==t?void 0:t.code)?new he(t.message,t.code,"fatal"):new ge(r);e(n)}))));return()=>{r.forEach((e=>e()))}},nc=e=>{const t=ye();return Ye(t,"client/onConnectionError(user.didGlobalBan)","user.didGlobalBan",e)},sc=e=>{const t=ce("channelMarker")({userId:$e()._id,entityId:e.channelId});Ce(["channelMarker","get",t],!0)};let ic=[];const oc=async(e,t,r)=>{var n,s,i;const o=ye();let a;o.log("client/api/connectClient",Object.assign({apiKey:o.apiKey,sessionState:o.sessionState},e)),o.userId&&o.userId!==e.userId&&(await Zl(),ic.forEach((e=>e())),ic=[]),null!==(n=e.deviceId)&&void 0!==n||(e.deviceId=await ka());try{const{users:r}=await Wl(e);l=o.ws,c=o.emitter,Ve.forEach((e=>{l.on(e,(t=>{c.emit(e,t)}))})),o.ws.once("connect",(()=>{o.ws.open()})),o.userId=e.userId,o.sessionHandler=t,a=o.accessTokenExpiryWatcher(null===(s=o.token)||void 0===s?void 0:s.expiresAt,null===(i=o.token)||void 0===i?void 0:i.issuedAt,t),qe(r[0])}catch(e){throw zl("notLoggedIn"),e}var l,c;return!0!==(null==r?void 0:r.disableRTE)&&async function(){await Ze()}(),await(async()=>{var e;const t=await Kl();if(t===(null===(e=we(["MessagePreviewSetting"]))||void 0===e?void 0:e.data))return;Ee(["MessagePreviewSetting"],t);const r=[],n=[];if("no-message-preview"===t){const e=be(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{Ce(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=be(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{(null==t?void 0:t.isDeleted)&&(Ce(e),e.includes("MessagePreviewChannel")&&r.push(t.channelId),e.includes("MessagePreviewSubChannel")&&n.push(t.subChannelId))})),0!==r.length&&await ml(r),0!==n.length&&await ql(n)}})(),0===ic.length&&ic.push(nc((e=>{ec("globalBan"),ic.forEach((e=>e())),a()})),(e=>{const t=ye();return Ye(t,"client/onTokenTerminated","tokenTerminated",e)})((e=>{ec(),ic.forEach((e=>e())),a()})),Jl((e=>{e.userId===o.userId&&(ec("userDeleted"),ic.forEach((e=>e())),a())})),(e=>{const t=ye();return Ye(t,"client/onTokenExpired","tokenExpired",e)})((e=>{zl(e),Zl(),ic.forEach((e=>e()))})),Yl(sc),Ql(sc),jl(),(()=>{const e=Ya();return e.established(),Ll((t=>{"established"===t?e.established():e.handleTokenExpired()})),()=>{e.destroy()}})()),!0},ac=()=>{let e,t=!1;const r=ye();r.log("initiating access token renewal");const n=async n=>{const{userId:s,displayName:i}=$e(),o={userId:s,displayName:i,authToken:n,deviceId:await ka()};"tokenExpired"===r.sessionState?await oc(o,r.sessionHandler):await Wl(o),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(ac())}),m)}}},lc=3e5,cc=(e,t,r)=>{const n=setInterval((()=>{if((e=>Date.now()>Date.parse(e)-lc)(e))return Qe("tokenExpired","tokenExpired"),void He((()=>r.sessionWillRenewAccessToken(ac())));(e=>{const{expiresAt:t,issuedAt:r}=e,n=Date.parse(t),s=Date.parse(r),i=Date.now();return i>s+.8*(n-s-lc)&&i<n})({expiresAt:e,issuedAt:t})&&r.sessionWillRenewAccessToken(ac())}),m);return()=>clearInterval(n)},uc=async e=>{const t=ye();t.log("channel/markerSync");const{data:r}=await t.http.post("/api/v1/markers/sync",{deviceLastSyncAt:e}),{userEntityMarkers:n,userFeedMarkers:s,feedMarkers:i,userMarkers:o}=r,a=Fa(o),l=Na(n),c=Ua(s),u=t.cache&&Date.now();return t.cache&&La({userEntityMarkers:l,userFeedMarkers:c,feedMarkers:i,userMarkers:a},{cachedAt:u}),Qe("local.feedMarker.fetched",{feedMarkers:i}),Qe("local.channelMarker.fetched",{userEntityMarkers:l}),Qe("local.subChannelMarker.fetched",{userFeedMarkers:c}),Qe("local.userMarker.fetched",{userMarkers:a}),{data:r,hasMore:r.feedMarkers.length>0}},dc=e=>{const t=ye();return Ye(t,"channelMarker/onChannelMarkerFetched","local.channelMarker.fetched",(t=>{e(t.userEntityMarkers[0])}))},hc=e=>{const t=ye();return Ye(t,"subChannelMarker/onSubChannelMarkerFetched","local.subChannelMarker.fetched",(t=>{e(t.userFeedMarkers[0])}))},fc=e=>{const t=ye();return Ye(t,"subChannelMarker/onSubChannelMarkerUpdated","local.subChannelMarker.updated",(t=>{e(t.userFeedMarkers)}))},pc=e=>{const t=ye();return Ye(t,"feedMarker/onFeedMarkerUpdated","marker.feed-updated",(t=>{La(t),e(t.feedMarkers[0])}))},gc=e=>{const t=ye();return Ye(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers[0])}))},mc=e=>{const t=ye();return Ye(t,"messageMarker/onMessageMarkerFetched","local.messageMarker.fetched",(t=>{e(t.contentMarkers[0])}))},yc=e=>{const t=ye();return Ye(t,"messageMarker/onMessageMarked","marker.marked-message",(t=>{var r,n;La(t);const s=be(["message","collection"]),{contentMarkers:i,feedMarkers:o}=t;if(s&&(null==s?void 0:s.length)>0&&(null==o?void 0:o.length)>0){const e=s.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==i?void 0:i.length)>0){((null===(n=null===(r=e[0].data)||void 0===r?void 0:r.data)||void 0===n?void 0:n.map((e=>we(["message","get",e]))))||[]).forEach((e=>{var t;const r=i[0].feedId===(null==e?void 0:e.data.subChannelId),n=i[0].readCount>(null==e?void 0:e.data.readCount),s=(null===(t=i[0])||void 0===t?void 0:t.deliveredCount)>(null==e?void 0:e.data.deliveredCount);r&&Ee(["message","get",e.data.messageId],Object.assign(Object.assign({},e.data),{readCount:n?i[0].readCount:null==e?void 0:e.data.readCount,deliveredCount:s?i[0].deliveredCount:null==e?void 0:e.data.deliveredCount}))}))}}e(t.contentMarkers[0])}))};const vc=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 bc(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(!bc(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=>bc(e[r],t[r])))}const wc=(e,t,r,n,s,i)=>{const{forceDispatch:o,callbackDataSelector:a,callbackFilter:l}=Object.assign({forceDispatch:!1,callbackDataSelector:e=>e},i),{cache:c}=ye();let u;c||console.log("For using Live Object feature you need to enable Cache!");let d=!1;const h=[],f=e=>{const{data:r}=e,n=xa(e,["data"]);l&&!l(r,u)||t(Object.assign({data:a(r)},n)),u=vc(r)};return h.push(...s.map((t=>t((t=>((t,n=!1)=>{e===t[r]&&(u&&!n&&bc(u,t)||f({loading:!1,data:t,origin:"event"}))})(t,o)))))),(()=>{const t=se(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 fe("Observing unsynced object is not supported by Live Object.",800800,"error")}),d=!0,h.forEach((e=>e()))):d||f({loading:r,data:t,origin:n,error:e}),e&&h.forEach((e=>e()))}))})(),()=>{h.forEach((e=>e()))}},Ec=e=>{const t=ye();return Ye(t,"onChannelCreated","channel.created",(async t=>{const r=await gl(t);La(r),e(r.channels[0])}))},Tc=e=>{const t=ye(),r=[Ye(t,"onChannelUpdated","channel.updated",(async t=>{const r=await gl(t);La(r),e(r.channels[0])})),Ye(t,"onChannelUpdated","local.channel.updated",(t=>e(t.channels[0])))];return()=>{r.forEach((e=>e()))}},Sc=e=>{const t=ye();return Ye(t,"onChannelJoined","channel.joined",(async t=>{const r=await gl(t),{channels:n,channelUsers:s}=r;La(r),e(n[0],s[0])}))},Cc=e=>{const t=ye();return Ye(t,"onChannelLeft","channel.left",(async t=>{const{userId:r}=ye(),{channelUsers:n}=t,s=n.some((e=>e.userId===r)),i=await gl(t,{isMessagePreviewUpdated:s}),{channels:o,channelUsers:a}=i;La(i),e(o[0],a[0])}))},kc=e=>{const t=ye();return Ye(t,"onChannelMuted","channel.setMuted",(async t=>{const r=await gl(t);La(r),e(r.channels[0])}))},Ac=e=>{const t=ye();return Ye(t,"onChannelMemberAdded","channel.membersAdded",(async t=>{const r=await gl(t),{channels:n,channelUsers:s}=r;La(r),e(n[0],s.find((e=>"member"===e.membership)))}))},_c=e=>{const t=ye();return Ye(t,"onChannelMemberRemoved","channel.membersRemoved",(async t=>{const r=await gl(t),{channels:n,channelUsers:s}=r;La(r),e(n[0],s[0])}))},Ic=e=>{const t=ye();return Ye(t,"onChannelMemberUnbanned","channel.unbanned",(async t=>{const r=await gl(t),{channels:n,channelUsers:s}=r;La(r),e(n[0],s.find((e=>"none"===e.membership)))}))},Rc=e=>{const t=ye();return Ye(t,"onChannelMemberRoleAdded","local.channel-moderator.role-added",(async t=>{const{channels:r,channelUsers:n}=t;e(r[0],n.find((e=>"member"===e.membership)))}))},Lc=e=>{const t=ye();return Ye(t,"onChannelMemberRoleRemoved","local.channel-moderator.role-removed",(async t=>{const{channels:r,channelUsers:n}=t;e(r[0],n.find((e=>"member"===e.membership)))}))},Dc=(e,t=!0)=>{const r=ye(),n=[Ye(r,"message/onMessageCreated","message.created",(async t=>{const r=await Cl(t),n=r.messages[0];La(r),e(n)}))];return t&&Ye(r,"message/onMessageCreated","local.message.created",(t=>e(t.messages[0]))),()=>{n.forEach((e=>e()))}},xc=e=>{const t=ye(),r=[Ye(t,"onMessageUpdated","message.updated",(async t=>{const r=await Cl(t);La(r),e(r.messages[0])})),Ye(t,"onMessageUpdated","local.message.updated",(t=>e(t.messages[0])))];return()=>{r.forEach((e=>e()))}},Oc=e=>{const t=ye(),r=[Ye(t,"message/onMessageDeleted","message.deleted",(async t=>{const r=await Cl(t);La(r),e(r.messages[0])})),Ye(t,"message/onMessageDeleted","local.message.deleted",(t=>e(t.messages[0])))];return()=>{r.forEach((e=>e()))}},Pc=e=>{const t=ye();return Ye(t,"onMessageFlagged","message.flagged",(async t=>{const r=await Cl(t);La(r),e(r.messages[0])}))},Mc=e=>{const t=ye();return Ye(t,"onMessageUnflagged","message.unflagged",(async t=>{const r=await Cl(t);La(r),e(r.messages[0])}))},Fc=e=>{const t=ye();return Ye(t,"onMessageFlagCleared","message.flagCleared",(async t=>{const r=await Cl(t);La(r),e(r.messages[0])}))},Nc=e=>{const t=ye();return Ye(t,"onMessageReactionAdded","message.reactionAdded",(async t=>{const r=await Cl(t,"message.reactionAdded");La(r),e(r.messages[0])}))},Uc=e=>{const t=ye();return Ye(t,"onMessageReactionRemoved","message.reactionRemoved",(async t=>{const r=await Cl(t,"message.reactionRemoved");La(r),e(r.messages[0])}))},Bc=e=>{const t=ye();return Ye(t,"message/onMessageFetched","local.message.fetched",(t=>{La(t),e(t.messages[0])}))},jc=e=>{const t=ye();return Ye(t,"onSubChannelCreated","message-feed.created",(async t=>{const r=await Rl(t);La(r),e(r.messageFeeds[0])}))},$c=e=>{const t=ye(),r=[Ye(t,"onSubChannelUpdated","message-feed.updated",(async t=>{const r=await Rl(t);La(r),e(r.messageFeeds[0])})),Ye(t,"onSubChannelUpdated","local.message-feed.updated",(t=>e(t.messageFeeds[0])))];return()=>{r.forEach((e=>e()))}},qc=e=>{const t=ye(),r=[Ye(t,"onSubChannelDeleted","message-feed.deleted",(async t=>{const r=await Rl(t);La(r),e(r.messageFeeds[0])})),Ye(t,"local.message-feed.deleted","local.message-feed.deleted",(t=>e(t.messageFeeds[0])))];return()=>{r.forEach((e=>e()))}};let Kc=!1,Gc=[],Hc=!1,Vc=null;const zc=e=>{(!Vc||new Date(e).getTime()>new Date(Vc).getTime())&&(Vc=e)};let Wc=[];const Yc=e=>{Wc=e},Qc=e=>Wc.push(e),Xc=async()=>{if(Hc)return;if(0===Wc.length)return;Hc=!0,Wc=[];const e=await uc(null==Vc?(new Date).toISOString():Vc);zc(e.data.userMarkers[0].lastSyncAt),e.hasMore&&Wc.push("has_more"),Hc=!1},Jc=()=>{Gc.length>0||Gc.push(xl((()=>{Wc.push("resume")})),Dc((e=>{Il(e)&&Wc.push("new message")}),!1),Ec((()=>Wc.push("subchannel is created"))),Yl((()=>Wc.push("subchannel is deleted"))),Sc((()=>Wc.push("subchannel is joined"))),Cc((()=>Wc.push("subchannel is left"))),jc((()=>Wc.push("subchannel is created"))),qc((()=>setTimeout((()=>Wc.push("subchannel is deleted")),2e3))),pc((()=>Wc.push("feed marker updated"))),(e=>{const t=ye();return Ye(t,"UserMarker/onUserMarkerSync","marker.user-sync",(t=>{const{userMarkers:r,userEntityMarkers:n,userFeedMarkers:s}=t,i=xa(t,["userMarkers","userEntityMarkers","userFeedMarkers"]),o=Fa(r),a=Na(n),l=Ua(s);La(Object.assign({userMarkers:o,userEntityMarkers:a,userFeedMarker:l},i)),e(o[0])}))})((()=>Wc.push("feed marker updated"))))},Zc=()=>{Kc=!1,Yc([]),Gc.forEach((e=>e())),Gc=[]};Dl((async()=>{Kc&&await Xc()}),2e3);var eu=Object.freeze({__proto__:null,getActiveClient:ye,getActiveUser:$e,setActiveUser:qe,createClient:(e,t=St.SG,{debugSession:r="amity",apiEndpoint:n}={})=>{var s,i;const o=(e=>{const t=`${null==e?void 0:e.trim()}`.length>0&&!Tt,r=bt(e),n=(e,...n)=>{t&&r(e,n)};return n.__instance__=r,n})(r);o("client/api/createClient",{apiKey:e.replace(/.{5}$/g,"xxxxx"),apiRegion:t});const a=null!==(s=null==n?void 0:n.http)&&void 0!==s?s:kt("http",t),l=null!==(i=null==n?void 0:n.mqtt)&&void 0!==i?i:kt("mqtt",t),c=cn(a),u=(e=>{const t=Co(e,{autoConnect:!1,reconnectionDelay:2e3,transports:["websocket"]});return t.on("disconnect",(e=>{"io server disconnect"===e&&t.connect()})),t})(a),h=Ra(l),f=We(),p={version:`${d}`,apiKey:e,log:o,cache:{data:{}},http:c,ws:u,mqtt:h,emitter:f,sessionState:"notLoggedIn",accessTokenExpiryWatcher:cc,sessionHandler:undefined,getFeedSettings:Gl,getSocialSettings:Hl,getMessagePreviewSetting:Kl,use:()=>ve(p)};try{const t=ye();if(t.apiKey===e)return t;ve(p)}catch(e){ve(p)}return p},login:oc,logout:Zl,isConnected:()=>{var e,t;const r=ye();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:Gl,renewal:ac,markerSync:uc,onConnectionError:rc,onClientDisconnected:e=>rc((({code:t})=>{800211===t&&e()})),onClientBanned:nc,onSessionStateChange:Ll,getTotalUnreadCount:e=>{const{_id:t}=$e();if(!t)throw new he("The _id has not been defined in ActiveUser",8e5,"error");return wc(t,e,"userId",yl,[gc],{callbackDataSelector:e=>{var t;return null!==(t=null==e?void 0:e.unreadCount)&&void 0!==t?t:0}})},getUserUnread:e=>{const{_id:t}=$e();if(!t)throw new he("The _id has not been defined in ActiveUser",8e5,"error");return wc(t,e,"userId",yl,[gc],{callbackDataSelector:e=>{var t;return{unreadCount:null!==(t=null==e?void 0:e.unreadCount)&&void 0!==t?t:0,hasMentioned:!!(null==e?void 0:e.hasMentioned)}}})},getMarkerSyncEvents:()=>Wc,setMarkerSyncEvents:Yc,pushMarkerSyncEvent:Qc,markerSyncTrigger:Xc,startUnreadSync:async()=>{await(async()=>{const{data:e}=await yl();zc(e.lastSyncAt)})(),Qc("start syncing"),Kc=!0,Jc()},stopUnreadSync:Zc,stopUnreadSyncing:()=>(console.warn("`stopUnreadSyncing` has been deprecated, please use `stopUnreadSync` instead"),Zc())});const tu=async e=>{const t=ye();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=xa(n,["paging"]),{users:o}=i,a=t.cache&&Date.now();if(t.cache){La(i,{cachedAt:a});Ee(["blockedUsers","query",r],{users:o.map(ce("user")),paging:s})}const{next:l,previous:c,total:u}=s,d=J(l);return{data:o,prevPage:J(c),nextPage:d,total:u,cachedAt:a}};tu.locally=(e={})=>{var t,r,n;const s=ye();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 o=["blockedUsers","query",i],{data:a,cachedAt:l}=null!==(t=we(o))&&void 0!==t?t:{},c=null!==(r=null==a?void 0:a.users.map((e=>we(["user","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[],u=J(null==a?void 0:a.paging.next),d=J(null==a?void 0:a.paging.previous);return c.length>0&&c.length===(null===(n=null==a?void 0:a.users)||void 0===n?void 0:n.length)?{data:c,nextPage:u,prevPage:d,total:null==a?void 0:a.paging.total,cachedAt:l}:void 0};const ru=(e,t,r)=>{const{log:n,cache:s}=ye();s||console.log(p);const i=Date.now();n(`getBlockedUsers(tmpid: ${i}) > listen`);const{limit:o}=e,a=null!=o?o:h,{policy:l=f}=null!=r?r:{},c=[],u=["blockedUsers","collection",{}],d=(e=!1)=>{var r,n;const s=null===(r=we(u))||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 o=se(tu,{limit:a,token:Q(e||null==s?void 0:s.params.page,"afterbeforeraw")});oe(o,(({data:e,loading:r,error:n,nextPage:s,total:o})=>{const a={loading:r,error:n,params:{page:s,total:o},data:i};e&&(a.data=[...new Set([...i,...e.map(ce("user"))])]),Ee(u,a),(e=>{var r,n;const s=null!==(r=e.data.map((e=>we(["user","get",e]))).filter(Boolean).map((({data:e})=>el.user(e))))&&void 0!==r?r:[];t({onNextPage:d,data:s,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading,error:e.error})})(a)}),ie(l,v))};return c.push((()=>{})),d(!0),()=>{n(`getCategories(tmpid: ${i}) > dispose`),c.forEach((e=>e())),Ce(u)}},nu=(e,t)=>{const r=ye();return Ye(r,e,e,(e=>{var n,s;if(r.cache){La(e);[...null!==(n=be(["followers","query"]))&&void 0!==n?n:[],...null!==(s=be(["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})=>Se(e,t,{cachedAt:-1}))),t(e.follows[0])}else t(e.follows[0])}))},su=e=>nu("follow.created",e),iu=e=>nu("follow.unfollowed",e),ou=e=>nu("follow.followerDeleted",e),au=e=>nu("follow.requested",e),lu=e=>nu("follow.requestCanceled",e),cu=e=>nu("follow.accepted",e),uu=e=>nu("follow.requestDeclined",e),du=async e=>{var t,r;const n=ye();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(),o="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&&Ee(["followInfo","get",e],o,{cachedAt:i}),{data:o,cachedAt:i}};du.locally=e=>{const t=ye();if(t.log("follow/getFollowInfo.locally",e),!t.cache)return;const r=we(["followInfo","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const hu=e=>{const t=async t=>{const[{data:r},{data:n}]=await Promise.all([du(t.from),du(t.to)]);e(r),e(n)},r=[nu("follow.created",t),nu("follow.requested",t),nu("follow.accepted",t),nu("follow.unfollowed",t),nu("follow.requestCanceled",t),nu("follow.requestDeclined",t),nu("follow.followerDeleted",t)];return()=>{r.forEach((e=>e()))}},fu=async(e,t)=>{const r=ye();r.log(`follow/queryF${e.substring(1)}`,t);const{userId:n,page:s}=t,i=xa(t,["userId","page"]),{data:o}=await r.http.get(r.userId===n?`/api/v4/me/${e}`:`/api/v4/users/${n}/${e}`,{params:Object.assign(Object.assign({},i),{token:Q(s,"afterbeforeraw")})}),{paging:a}=o,l=xa(o,["paging"]),{follows:c}=l,u=r.cache&&Date.now();if(r.cache){La(l,{cachedAt:u});const t=["follow","query",Object.assign(Object.assign({},i),{userId:n,options:Object.assign({},s),type:e})];Ee(t,{follows:c.map(ce("follow")),paging:a})}const d=J(a.next);return{data:c,cachedAt:u,prevPage:J(a.previous),nextPage:d}};fu.locally=(e,t)=>{var r,n;const s=ye();if(s.log(`follow/queryF${e.substring(1)}.locally`,t),!s.cache)return;const{page:i}=t,o=xa(t,["page"]),a=["follow","query",Object.assign(Object.assign({},o),{options:Object.assign({},i),type:e})],{data:l,cachedAt:c}=null!==(r=we(a))&&void 0!==r?r:{};if(!(null==l?void 0:l.follows.length))return;const u=l.follows.map((e=>we(["follow","get",e]))).filter(Boolean).map((({data:e})=>e)),d=J(null==l?void 0:l.paging.previous),h=J(null==l?void 0:l.paging.next);return u.length===(null===(n=null==l?void 0:l.follows)||void 0===n?void 0:n.length)?{data:u,cachedAt:c,prevPage:d,nextPage:h}:void 0};const pu=async e=>fu("followers",e);pu.locally=e=>fu.locally("followers",e);const gu=async e=>fu("following",e);gu.locally=e=>fu.locally("following",e);var mu=Object.freeze({__proto__:null,blockUser:async e=>{const t=ye();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,o={follows:s};return t.cache&&(La(o,{cachedAt:n}),Se(["followInfo","get",e],i[0],{cachedAt:n})),Qe("follow.unfollowed",o),r},unBlockUser:async e=>{const t=ye();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,o={follows:s};return t.cache&&(La(o,{cachedAt:n}),Se(["followInfo","get",e],i[0],{cachedAt:n})),Qe("follow.created",o),r},getBlockedUsers:(e,t,r)=>(console.log("Deprecation Notice: UserRepository.Relationship.getBlockedUsers will be deprecated on 9th June 2023, please use UserRepository.getBlockedUsers instead."),ru(e,t,r)),follow:async e=>{const t=ye();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&&La(r,{cachedAt:n}),Qe("accepted"===r.follows[0].status?"follow.created":"follow.requested",r),{data:r.follows[0],cachedAt:n}},unfollow:async e=>{const t=ye();t.log("follow/unfollow",e);const{data:r}=await t.http.delete(`/api/v4/me/following/${e}`);return t.cache&&La(r),Qe("follow.unfollowed",r),!0},acceptFollower:async e=>{const t=ye();t.log("follow/acceptFollower",e);const{data:r}=await t.http.post(`/api/v4/me/followers/${e}`);return t.cache&&La(r),Qe("follow.accepted",r),!0},acceptMyFollower:async e=>{const t=ye();t.log("follow/acceptMyFollower",e);const{data:r}=await t.http.post(`/api/v4/me/followers/${e}`);return t.cache&&La(r),Qe("follow.accepted",r),!0},declineFollower:async e=>{const t=ye();t.log("follow/declineFollower",e);const{data:r}=await t.http.delete(`/api/v4/me/followers/${e}`);return t.cache&&La(r),Qe("follow.requestDeclined",r),!0},declineMyFollower:async e=>{const t=ye();t.log("follow/declineMyFollower",e);const{data:r}=await t.http.delete(`/api/v4/me/followers/${e}`);return t.cache&&La(r),Qe("follow.requestDeclined",r),!0},onUserFollowed:su,onUserUnfollowed:iu,onFollowerDeleted:ou,onFollowerRequested:au,onFollowRequestCanceled:lu,onFollowRequestAccepted:cu,onFollowRequestDeclined:uu,onFollowInfoUpdated:hu,observeFollowInfo:(e,t,r="cache_then_server")=>{const{log:n}=ye(),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)},o=[];return o.push(hu((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(se(du,e),(e=>(e.data||e.error)&&i(e,"onFetch")),ie(r)),()=>{n(`observeFollowInfo(tmpid: ${s}) > dispose`),o.forEach((e=>e()))}},observeFollowers:(e,t)=>{const{log:r}=ye(),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(au((e=>i(e,"onRequested"))),cu((e=>i(e,"onAccepted"))),uu((e=>i(e,"onDeclined"))),lu((e=>i(e,"onCanceled"))),su((e=>i(e,"onFollowed"))),iu((e=>i(e,"onUnfollowed"))),ou((e=>i(e,"onDeleted")))),()=>{r(`observeFollowers(tmpid: ${n}) > dispose`),s.forEach((e=>e()))}},observeFollowings:(e,t)=>{const{log:r}=ye(),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(au((e=>i(e,"onRequested"))),cu((e=>i(e,"onAccepted"))),uu((e=>i(e,"onDeclined"))),lu((e=>i(e,"onCanceled"))),su((e=>i(e,"onFollowed"))),iu((e=>i(e,"onUnfollowed"))),ou((e=>i(e,"onDeleted")))),()=>{r(`observeFollowings(tmpid: ${n}) > dispose`),s.forEach((e=>e()))}},getFollowers:(e,t,r)=>{const{log:n,cache:s}=ye();s||console.log("For using Live Collection feature you need to enable Cache!");const i=Date.now();n(`getFollowers(tmpid: ${i}) > listen`);const{limit:o}=e,a=xa(e,["limit"]),l=null!=o?o:h,{policy:c=f}=null!=r?r:{},u=[],d=["follow","collection",{userId:e.userId,type:"follower"}],p=r=>{var n,s;let i=null!==(n=r.data.map((e=>we(["follow","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];e.status&&"all"!==e.status&&(i=ke(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=we(d))||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!==ce("follow")(r))):["onRequested","onAccepted","onFollowed"].includes(t)&&(s.data=[...new Set([ce("follow")(r),...s.data])]),Ee(d,s),p(s))},m=(e=!1)=>{var t,r,n,s;const i=null===(t=we(d))||void 0===t?void 0:t.data,o=null!==(r=null==i?void 0:i.data)&&void 0!==r?r:[];if(!e&&o.length>0&&!(null===(n=null==i?void 0:i.params)||void 0===n?void 0:n.page))return;const u=se(pu,Object.assign(Object.assign({},a),{page:null!==(s=e||null==i?void 0:i.params.page)&&void 0!==s?s:{limit:l}}));oe(u,(({data:e,error:t,loading:r,nextPage:n})=>{const s={loading:r,error:t,params:{page:n},data:o};e&&(s.data=[...new Set([...o,...e.map(ce("follow"))])]),Ee(d,s),p(s)}),ie(c))};return u.push(au(g("onRequested")),cu(g("onAccepted")),uu(g("onDeclined")),lu(g("onCanceled")),su(g("onFollowed")),iu(g("onUnfollowed")),ou(g("onDeleted"))),m(!0),()=>{n(`getFollowers(tmpid: ${i}) > dispose`),u.forEach((e=>e()))}},getFollowings:(e,t,r)=>{const{log:n,cache:s}=ye();s||console.log("For using Live Collection feature you need to enable Cache!");const i=Date.now();n(`getFollowings(tmpid: ${i}) > listen`);const{limit:o}=e,a=xa(e,["limit"]),l=null!=o?o:h,{policy:c=f}=null!=r?r:{},u=[],d=["follow","collection",{userId:e.userId,type:"following"}],p=r=>{var n,s;let i=null!==(n=r.data.map((e=>we(["follow","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];e.status&&"all"!==e.status&&(i=ke(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=we(d))||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!==ce("follow")(r))):["onRequested","onAccepted","onFollowed"].includes(t)&&(s.data=[...new Set([ce("follow")(r),...s.data])]),Ee(d,s),p(s))},m=(e=!1)=>{var t,r,n,s;const i=null===(t=we(d))||void 0===t?void 0:t.data,o=null!==(r=null==i?void 0:i.data)&&void 0!==r?r:[];if(!e&&o.length>0&&!(null===(n=null==i?void 0:i.params)||void 0===n?void 0:n.page))return;const u=se(gu,Object.assign(Object.assign({},a),{page:null!==(s=e||null==i?void 0:i.params.page)&&void 0!==s?s:{limit:l}}));oe(u,(({data:e,error:t,loading:r,nextPage:n})=>{const s={loading:r,error:t,params:{page:n},data:o};e&&(s.data=[...new Set([...o,...e.map(ce("follow"))])]),Ee(d,s),p(s)}),ie(c))};return u.push(au(g("onRequested")),cu(g("onAccepted")),uu(g("onDeclined")),lu(g("onCanceled")),su(g("onFollowed")),iu(g("onUnfollowed")),ou(g("onDeleted"))),m(!0),()=>{n(`getFollowings(tmpid: ${i}) > dispose`),u.forEach((e=>e()))}},getFollowInfo:(e,t)=>wc(e,t,"userId",du,[hu],{forceDispatch:!0}),getMyFollowInfo:e=>{const{userId:t}=$e();return wc(t,e,"userId",du,[hu],{forceDispatch:!0})}});const yu=async e=>{const t=ye();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&&La(n,{cachedAt:s}),Qe("user.fetched",n),{data:n.users.map((e=>el.user(e))),cachedAt:s}};yu.locally=e=>{var t;const r=ye();if(r.log("user/getUsers.locally",e),!r.cache)return;const n=e.map((e=>we(["user","get",e]))).filter(Boolean),s=n.map((({data:e})=>el.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 vu=e=>Xl("user.updated",e),bu=e=>Xl("user.flagged",e),wu=e=>Xl("user.unflagged",e),Eu=e=>Xl("user.flagCleared",e),Tu=e=>Xl("user.fetched",e),Su=async e=>{const t=ye();let r;t.log("user/getUser",e),Ol("user",e);try{r=(await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`)).data}catch(t){throw S(null==t?void 0:t.code)&&Da("user",e),t}const n=t.cache&&Date.now();t.cache&&La(r,{cachedAt:n});const{users:s}=r;return Qe("user.fetched",r),{data:s.find((t=>t.userId===e)),cachedAt:n}};Su.locally=e=>{const t=ye();if(t.log("user/getUser.locally",e),!t.cache)return;const r=we(["user","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const Cu=async(e={})=>{const t=ye();t.log("user/queryUsers",e);const{page:r,limit:n=10,displayName:s,filter:i="all",sortBy:o="displayName"}=e,a=xa(e,["page","limit","displayName","filter","sortBy"]),{data:l}=await t.http.get("/api/v3/users",{params:Object.assign(Object.assign({},a),{keyword:s,filter:i,sortBy:o,options:r?{token:r}:{limit:n}})}),{paging:c}=l,u=xa(l,["paging"]),{users:d}=u,h=t.cache&&Date.now();if(t.cache){La(u,{cachedAt:h});const t=["user","query",Object.assign(Object.assign({},e),{options:{limit:n,token:r}})];Ee(t,{users:d.map(ce("user")),paging:c})}return Qe("user.fetched",l),{data:d,cachedAt:h,paging:c}};Cu.locally=(e={})=>{var t,r,n;const s=ye();if(s.log("user/queryUsers.locally",e),!s.cache)return;const{limit:i=10,page:o}=null!=e?e:{},a=["user","query",Object.assign(Object.assign({},e),{options:{limit:i,token:o}})],{data:l,cachedAt:c}=null!==(t=we(a))&&void 0!==t?t:{},u=null!==(r=null==l?void 0:l.users.map((e=>we(["user","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];return u.length>0&&u.length===(null===(n=null==l?void 0:l.users)||void 0===n?void 0:n.length)?{data:u,cachedAt:c,paging:null==l?void 0:l.paging}:void 0};const ku=(e,t)=>{let r=Ae(e,"displayName",t.displayName);switch(t.sortBy){case"firstCreated":r=r.sort(Me);break;case"lastCreated":r=r.sort(Fe);break;default:r=r.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Oe)}return r},Au=(e,t,r)=>{const{log:n,cache:s}=ye();s||console.log(p);const i=Date.now();n(`liveUsers(tmpid: ${i}) > listen`);const{limit:o}=e,a=xa(e,["limit"]),l=null!=o?o:h,{policy:c=f}=null!=r?r:{},u=[],d=["user","collection",Sa()],g=(r,n=!1)=>{var s,i;const o=null!==(s=r.data.map((e=>we(["user","get",e]))).filter(Boolean).map((({data:e})=>el.user(e))))&&void 0!==s?s:[];t({onNextPage:y,data:n?ku(o,e):o,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=we(d))||void 0===t?void 0:t.data;r&&(r.data=[...new Set([e.userId,...r.data])],Ee(d,r),g(r,!0))},y=(e=!1)=>{var t,r;const n=null===(t=we(d))||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},o=se(Cu,Object.assign(Object.assign({},a),i));oe(o,(({data:t,error:r,loading:n,paging:i})=>{const o={loading:n,error:r,params:{page:null==i?void 0:i.next},data:s};t&&(o.data=e?t.map(ce("user")):[...new Set([...s,...t.map(ce("user"))])]),Ee(d,o),g(o)}),ie(c))};return u.push(vu(m()),Jl(m()),bu(m()),wu(m()),Eu(m())),y(!0),()=>{n(`liveUsers(tmpid: ${i}) > dispose`),u.forEach((e=>e()))}},_u=async e=>{const t=ye();let r;t.log("user/getUser",e),Ol("user",e);try{r=(await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`)).data}catch(t){throw S(null==t?void 0:t.code)&&Da("user",e),t}const n=t.cache&&Date.now();t.cache&&La(r,{cachedAt:n});const{users:s}=r;return Qe("user.fetched",r),{data:el.user(s.find((t=>t.userId===e))),cachedAt:n}};_u.locally=e=>{const t=ye();if(t.log("user/getUser.locally",e),!t.cache)return;const r=we(["user","get",e]);return r?{data:el.user(r.data),cachedAt:r.cachedAt}:void 0};const Iu=async({viewId:e,viewedType:t,limit:r,token:n})=>{const s=ye(),i={};n?i.token=n:i.limit=r;const o=`/api/v1/analytics/views/${"post"===t?"posts":"stories"}/${e}/users`,a=await s.http.get(o,{params:i});return La(a.data),a.data};var Ru=Object.freeze({__proto__:null,Relationship:mu,getUserByIds:yu,updateUser:async(e,t)=>{const r=ye();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&&La(n,{cachedAt:s});const{users:i}=n;return Qe("user.updated",n),{data:i.find((t=>t.userId===e)),cachedAt:s}},flagUser:async e=>{const t=ye();t.log("user/flagUser",e);const{data:r}=await t.http.post(`api/v4/me/flags/${encodeURIComponent(e)}`);return t.cache&&La(r),Qe("user.flagged",r),!!r},unflagUser:async e=>{const t=ye();t.log("user/unflag",e);const{data:r}=await t.http.delete(`/api/v4/me/flags/${encodeURIComponent(e)}`);return t.cache&&La(r),Qe("user.unflagged",r),!!r},isUserFlaggedByMe:async e=>{const t=ye();t.log("user/isUserFlaggedByMe",e);const{data:{isFlagByMe:r}}=await t.http.get(`/api/v3/users/${e}/isFlagByMe`);return r},onUserUpdated:vu,onUserDeleted:Jl,onUserFlagged:bu,onUserUnflagged:wu,onUserFlagCleared:Eu,getUser:(e,t)=>wc(e,(e=>t(Object.assign(Object.assign({},e),{data:e.data?el.user(e.data):e.data}))),"userId",Su,[Tu,vu,Jl,bu,wu,Eu]),getUsers:Au,observeUser:(e,t)=>{const{log:r}=ye(),n=Date.now();r(`observeUser(tmpid: ${n}) > listen`);const s=(r,n)=>{var s,i,o;if((null===(s=r.data)||void 0===s?void 0:s.userId)!==e)return;const a=Object.assign(Object.assign({},r),{data:el.user(r.data)});if(t instanceof Function)return t(a);"onFetch"!==n&&(null===(i=t.onEvent)||void 0===i||i.call(t,n,a)),null===(o=t[n])||void 0===o||o.call(t,a)},i=[];return i.push(vu((e=>s({data:e,loading:!1,origin:"event"},"onUpdate"))),Jl((e=>s({data:e,loading:!1,origin:"event"},"onDelete"))),bu((e=>s({data:e,loading:!1,origin:"event"},"onFlagged"))),wu((e=>s({data:e,loading:!1,origin:"event"},"onUnflagged"))),Eu((e=>s({data:e,loading:!1,origin:"event"},"onFlagCleared")))),oe(se(_u,e),(e=>e.data&&s(e,"onFetch"))),()=>{r(`observeUser(tmpid: ${n}) > dispose`),i.forEach((e=>e()))}},getBlockedUsers:ru,searchUserByDisplayName:(e,t,r)=>Au(Object.assign(Object.assign({},e),{filter:"all"}),t,r),getViewedUsers:(e,t)=>{const{log:r,cache:n}=ye(),s=["postViewedUsers","collection",{postId:e.postId}];n||console.log(p);const i=Date.now();r(`getViewedUsers(tmpid: ${i}) > listen`);const{limit:o,postId:a}=e,l=(e=!1)=>{var r,n,i;const c=null===(r=we(s))||void 0===r?void 0:r.data,u=null!==(n=null==c?void 0:c.data)&&void 0!==n?n:[];if(!e&&u.length>0&&!(null==c?void 0:c.params.page))return;const d=se(Iu,{viewId:a,viewedType:"post",limit:o||10,token:e||null===(i=null==c?void 0:c.params.page)||void 0===i?void 0:i.next});oe(d,(e=>{var r,n,i,o,a;let c=null!==(i=null===(n=null===(r=we(s))||void 0===r?void 0:r.data)||void 0===n?void 0:n.data)&&void 0!==i?i:[];(null===(o=e.data)||void 0===o?void 0:o.users)&&(c=[...new Set([...c,...e.data.users.map((({userId:e})=>e))])]);const u={loading:e.loading,params:{page:null===(a=e.data)||void 0===a?void 0:a.paging},data:c||[]};Ee(s,u),(e=>{var r,n;let s=[];(null==e?void 0:e.data)&&(s=e.data.map((e=>we(["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})})(u)}),ie(f,v))};return l(!0),()=>{r(`getViewedUsers(tmpid: ${i}) > dispose`),Ce(s)}},getReachedUsers:(e,t)=>{let r=(e=!1)=>{};const{log:n,cache:s}=ye(),i=["viewedUsers","collection",{viewId:e.viewId,viewedType:e.viewedType}];s||console.log(p);const o=Date.now();n(`getReachUsers(tmpid: ${o}) > listen`);const{limit:a,viewId:l,viewedType:c}=e;return r=(e=!1)=>{var n,s,o;const u=null===(n=we(i))||void 0===n?void 0:n.data,d=null!==(s=null==u?void 0:u.data)&&void 0!==s?s:[];if(!e&&d.length>0&&!(null==u?void 0:u.params.page))return;const h=se(Iu,{viewId:l,viewedType:c,limit:a||10,token:e||null===(o=null==u?void 0:u.params.page)||void 0===o?void 0:o.next});oe(h,(e=>{var n,s,o,a,l;let c=null!==(o=null===(s=null===(n=we(i))||void 0===n?void 0:n.data)||void 0===s?void 0:s.data)&&void 0!==o?o:[];(null===(a=e.data)||void 0===a?void 0:a.users)&&(c=[...new Set([...c,...e.data.users.map((({userId:e})=>e))])]);const u={loading:e.loading,params:{page:null===(l=e.data)||void 0===l?void 0:l.paging},data:c||[]};Ee(i,u),(e=>{var n,s;let i=[];(null==e?void 0:e.data)&&(i=e.data.map((e=>we(["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})})(u)}),ie(f,v))},r(!0),()=>{n(`getReachUsers(tmpid: ${o}) > dispose`),Ce(i)}}});const Lu=async e=>{const t=ye();t.log("file/getFile",e);const{data:r}=await t.http.get(`/api/v3/files/${e}`),n=t.cache&&Date.now();return t.cache&&La({files:[r]},{cachedAt:n}),{data:r,cachedAt:n}};Lu.locally=e=>{const t=ye();if(t.log("file/getFile.locally",e),!t.cache)return;const r=we(["file","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const Du=async(e,t,r)=>{const n=ye();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))}}),o=n.cache&&Date.now();return n.cache&&La({files:i},{cachedAt:o}),{data:i,cachedAt:o}},xu=async(e,t)=>{const r=ye();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&&La({files:s},{cachedAt:i}),{data:s,cachedAt:i}};var Ou=Object.freeze({__proto__:null,getFile:Lu,uploadFile:async(e,t)=>{const r=ye();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&&La({files:s},{cachedAt:i}),{data:s,cachedAt:i}},deleteFile:async e=>{const t=ye();return t.log("file/deleteFile",e),await t.http.delete(`/api/v3/files/${e}`),Ce(["file","get",e],!0),{success:!0}},fileUrlWithSize:(e,t)=>`${e}?size=${t}`,uploadVideo:Du,uploadImage:xu,createImage:async(e,t)=>{const r=ye();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&&La({files:s},{cachedAt:i}),{data:s,cachedAt:i}},createFile:async(e,t)=>{const r=ye();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&&La({files:s},{cachedAt:i}),{data:s,cachedAt:i}},createVideo:async(e,t,r)=>{const n=ye();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))}}),o=n.cache&&Date.now();return n.cache&&La({files:i},{cachedAt:o}),{data:i,cachedAt:o}},observeFile:(e,t)=>{const{log:r}=ye(),n=Date.now();r(`observeFile(tmpid: ${n}) > listen`);return oe(se(Lu,e),(r=>r.data&&((r,n)=>{var s,i,o;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===(o=t[n])||void 0===o||o.call(t,r)}})(r,"onFetch"))),()=>{r(`observeFile(tmpid: ${n}) > dispose`)}}});const Pu=async e=>{const t=ye();t.log("role/queryRoles",e);const r=null!=e?e:{},{page:n,limit:s=10,queryToken:i,displayName:o,sortBy:a}=r,l=xa(r,["page","limit","queryToken","displayName","sortBy"]),c=i?{token:i}:s?{limit:s}:n?{token:Q(n,"skiplimit")}:void 0,{data:u}=await t.http.get("/api/v3/roles",{params:Object.assign(Object.assign({},l),{keyword:o,sortBy:a,options:c})}),{paging:d}=u,h=xa(u,["paging"]),{roles:f}=h,p=t.cache&&Date.now();t.cache&&La(h,{cachedAt:p});const g=X(d.next);return{data:f,cachedAt:p,prevPage:X(d.previous),nextPage:g,paging:d}};Pu.locally=e=>{ye().log("role/queryRoles.locally",e)};const Mu=async e=>{const t=ye();t.log("role/getRole",e);const{data:r}=await t.http.get(`/api/v3/roles/${e}`),n=t.cache&&Date.now();return t.cache&&La({roles:r},{cachedAt:n}),{data:r.find((t=>t.roleId===e)),cachedAt:n}};Mu.locally=e=>{const t=ye();if(t.log("role/getRole.locally",e),!t.cache)return;const r=we(["role","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const Fu=(e,t)=>{"message"===e?Qe("local.message.updated",{messages:[t]}):"post"===e?Qe("post.updated",{posts:[t]}):"comment"===e?Qe("comment.updated",{comments:[t]}):"story"===e&&Qe("story.updated",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[t]})},Nu=async(e,t=!1)=>{const r=ye();let n;r.log("message/getMessage",e),t||console.log("getMessage will be deprecated on 15th November 2022, please use liveMessage instead."),Ol("message",e);try{const{data:t}=await r.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);n=await Cl(t)}catch(t){throw S(null==t?void 0:t.code)&&Da("message",e),t}const s=r.cache&&Date.now();r.cache&&La(n,{cachedAt:s});const{messages:i}=n;return Qe("local.message.fetched",{messages:i}),{data:i.find((t=>t.messageId===e)),cachedAt:s}};Nu.locally=e=>{const t=ye();if(t.log("message/getMessage.locally",e),!t.cache)return;const r=we(["message","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const Uu=async e=>{const t=ye();let r;t.log("post/getPost",e),Ol("post",e);try{r=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw S(null==t?void 0:t.code)&&Da("post",e),t}const n=Pa(r,"communityUsers"),s=t.cache&&Date.now();t.cache&&La(n,{cachedAt:s});const{posts:i}=n,o=i.find((t=>t.postId===e));return{data:el.post(o),cachedAt:s}};Uu.locally=e=>{const t=ye();if(t.log("post/getPost.locally",e),!t.cache)return;const r=we(["post","get",e]);return r?{data:el.post(r.data),cachedAt:r.cachedAt}:void 0};const Bu=async e=>{const t=ye();let r;t.log("comment/getComment",e),Ol("comment",e);try{r=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw S(null==t?void 0:t.code)&&Da("comment",e),t}const n=t.cache&&Date.now();t.cache&&La(r,{cachedAt:n});const{comments:s}=r;return{data:el.comment(s.find((t=>t.commentId===e))),cachedAt:n}};Bu.locally=e=>{const t=ye();if(t.log("comment/getComment.locally",e),!t.cache)return;const r=we(["comment","get",e]);return r?{data:el.comment(r.data),cachedAt:r.cachedAt}:void 0};const ju=(e,t)=>{const r=e.split(".")[0],n=e.split(".")[1];let s=((e,t)=>{var r,n;let s,i;if("post"===t)i="post",s=e.posts[0].postId;else{if("comment"!==t)throw new Error("Unknown event type");i="comment",s=e.comments[0].commentId}return(null===(n=null===(r=we([i,"get",s]))||void 0===r?void 0:r.data)||void 0===n?void 0:n.myReactions)||[]})(t,r);if(ye().userId===t.reactor.userId)if("addReaction"===n)s.includes(t.reactor.reactionName)||s.push(t.reactor.reactionName);else{if("removeReaction"!==n)throw new Error(`Unknown event type: ${n}`);s=s.filter((e=>e!==t.reactor.reactionName))}return((e,t,r)=>{const[n]=e[t];return Object.assign(Object.assign({},e),{[t]:[Object.assign(Object.assign({},n),{myReactions:r})]})})(t,`${r}s`,s)},$u=async(e,t,r)=>{const n=ye();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=we([e,"get",t]);(null==r?void 0:r.data)&&Ee([e,"get",t],r.data,{cachedAt:Date.now()})}return!0};$u.optimistically=(e,t,r)=>{var n,s,i,o,a;const l=ye();if(l.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:r}),!l.cache)return;const c=we([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 u=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 Se([e,"get",t],u,{cachedAt:-5}),Fu(e,u),null!==(a=null===(o=null==u?void 0:u.myReactions)||void 0===o?void 0:o.includes(r))&&void 0!==a&&a};const qu=async(e,t,r)=>{const n=ye();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=we([e,"get",t]);(null==r?void 0:r.data)&&Ee([e,"get",t],r.data,{cachedAt:Date.now()})}return!0};qu.optimistically=(e,t,r)=>{var n,s,i,o,a;const l=ye();if(l.log("reaction/removeReaction.optimistically",{referenceId:t,referenceType:e,reactionName:r}),!l.cache)return;const c=we([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 u=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 Se([e,"get",t],u,{cachedAt:-5}),Fu(e,u),null!==(a=!(null===(o=null==u?void 0:u.myReactions)||void 0===o?void 0:o.includes(r)))&&void 0!==a&&a};const Ku=(e,t)=>{const r=ye();return Ye(r,e,e,(n=>{var s;if(r.cache){const{communities:i}=n,o=xa(n,["communities"]),a=Pa(o,"communityUsers");if(La(a),(null==i?void 0:i[0])&&!["post.updated"].includes(e)&&Qe("community.updated",{communities:i,categories:[],communityUsers:a.communityUsers,feeds:[],files:[],users:[]}),"post.deleted"===e){const{postId:e,postedUserId:s}=n.posts[0];try{Ol("post",e)}catch(e){return}return s!==r.userId&&Da("post",e),t(n.posts[0])}const l=we(["post","get",n.posts[0].postId]);if(["post.created","post.approved","post.declined"].includes(e)){let t=null===(s=be(["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})=>Se(e,t,{cachedAt:-1})))}t(l.data)}else t(n.posts[0])}))},Gu=e=>Ku("post.created",e),Hu=e=>Ku("post.updated",e),Vu=e=>Ku("post.deleted",e),zu=e=>Ku("post.approved",e),Wu=e=>Ku("post.declined",e),Yu=e=>Ku("post.flagged",e),Qu=e=>Ku("post.unflagged",e),Xu=e=>{const t=ye();return Ye(t,"post.addReaction","post.addReaction",(r=>{if(t.cache){const t=xa(ju("post.addReaction",r),["reactor"]);La(t);const n=we(["post","get",r.posts[0].postId]);e(n.data)}else e(r.posts[0])}))},Ju=e=>{const t=ye();return Ye(t,"post.removeReaction","post.removeReaction",(r=>{if(t.cache){const t=xa(ju("post.removeReaction",r),["reactor"]);La(t);const n=we(["post","get",r.posts[0].postId]);e(n.data)}else e(r.posts[0])}))},Zu=(e,t)=>{const r=ye();return Ye(r,e,e,(n=>{var s;if(r.cache){La(n);const{comments:r}=n;if(r.length>0){const n=we(["comment","get",r[0].commentId]);if(["comment.created"].includes(e)){if(r[0].parentId){const e=we(["comment","get",r[0].parentId]);(null==e?void 0:e.data)&&Ee(["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=be(["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})=>Se(e,t,{cachedAt:-1})))}t(el.comment(n.data))}}else t(el.comment(n.comments[0]))}))},ed=e=>Zu("comment.created",e),td=e=>Zu("comment.updated",e),rd=e=>Zu("comment.deleted",e),nd=e=>Zu("comment.flagged",e),sd=e=>Zu("comment.unflagged",e),id=e=>{const t=ye();return Ye(t,"comment.addReaction","comment.addReaction",(r=>{if(t.cache){const t=xa(ju("comment.addReaction",r),["reactor"]);La(t);const n=we(["comment","get",r.comments[0].commentId]);e(el.comment(n.data))}else e(el.comment(r.comments[0]))}))},od=e=>{const t=ye();return Ye(t,"comment.removeReaction","comment.removeReaction",(r=>{if(t.cache){const t=xa(ju("comment.removeReaction",r),["reactor"]);La(t);const n=we(["comment","get",r.comments[0].commentId]);e(el.comment(n.data))}else e(el.comment(r.comments[0]))}))},ad=(e,t,r)=>{const n=ye(),s=(n,s,i)=>{n===e&&s===t&&r(i)};if("message"===e){return Ye(n,"reaction/onReactorAdded","message.updated",(async e=>{const t=await Cl(e);t.reactions[0]&&(La(t),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return Ye(n,"post.addReaction","post.addReaction",(e=>{const{reactor:t}=e,r=xa(e,["reactor"]);La(r),La({reactions:[t]}),s("post",e.posts[0].postId,t)}))}return Ye(n,"comment.addReaction","comment.addReaction",(e=>{const{reactor:t}=e,r=xa(e,["reactor"]);La(r),La({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))},ld=(e,t,r)=>{const n=ye(),s=(n,s,i)=>{n===e&&s===t&&r(i)};if("message"===e){return Ye(n,"reaction/onReactorRemoved","message.updated",(async e=>{const t=await Cl(e);t.reactions[0]&&(La(t),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return Ye(n,"post.removeReaction","post.removeReaction",(e=>{const{reactor:t}=e,r=xa(e,["reactor"]);La(r),La({reactions:[t]}),s("post",e.posts[0].postId,t)}))}return Ye(n,"comment.removeReaction","comment.removeReaction",(e=>{const{reactor:t}=e,r=xa(e,["reactor"]);La(r),La({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))},cd=async e=>{ye().log("reaction/queryReactor",e);const t=await(async e=>{const t=ye();t.log("reaction/queryReactions",e);const r=null!=e?e:{},{page:n={limit:10}}=r,s=xa(r,["page"]),{data:i}=await t.http.get("/api/v3/reactions",{params:Object.assign(Object.assign({},s),{referenceVersion:5,options:{token:Q(n,"afterbeforeraw")}})}),{paging:o}=i,a=xa(i,["paging"]),{reactions:l}=a;La(Object.assign(Object.assign({},a),{reactions:l})),La(Object.assign(Object.assign({},a),{reactors:l[0].reactors}));const c=J(o.next);return{data:l,prevPage:J(o.previous),nextPage:c}})(e),{data:r}=t,n=xa(t,["data"]);return Object.assign(Object.assign({},n),{data:r[0].reactors})};var ud=Object.freeze({__proto__:null,addReaction:$u,removeReaction:qu,onReactionAdded:(e,t,r)=>{const n=n=>{ce(e)(n)===t&&r(n)};if("message"===e){const e=ye(),t=async e=>{var t;const r=await Cl(e),s=we(["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;La(r),i&&n(r.messages[0])};return Ye(e,"reaction/onReactionAdded","message.updated",t)}return"post"===e?Xu(n):id(n)},onReactionRemoved:(e,t,r)=>{const n=n=>{ce(e)(n)===t&&r(n)};if("message"===e){const e=ye(),t=async e=>{var t;const r=await Cl(e),s=we(["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;La(r),i&&n(r.messages[0])};return Ye(e,"reaction/onReactionRemoved","message.updated",t)}return"post"===e?Ju(n):od(n)},onReactorAdded:ad,onReactorRemoved:ld,getReactions:(e,t,r)=>{const{log:n,cache:s}=ye();s||console.log("For using Live Collection feature you need to enable Cache!");const i=Date.now();n(`liveReactions(tmpid: ${i}) > listen`);const{limit:o}=e,a=xa(e,["limit"]),l=null!=o?o:h,{policy:c=f}=null!=r?r:{},u=[],d=["reaction","collection",{referenceId:e.referenceId,referenceType:e.referenceType}],p=e=>{var r,n;const s=null!==(r=e.data.map((e=>we(["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=we(d))||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))),Ee(d,n),p(n))},m=(e=!1)=>{var t,r,n,s;const i=null===(t=we(d))||void 0===t?void 0:t.data,o=null!==(r=null==i?void 0:i.data)&&void 0!==r?r:[];if(!e&&o.length>0&&!(null===(n=null==i?void 0:i.params)||void 0===n?void 0:n.page))return;const u=se(cd,Object.assign(Object.assign({},a),{page:null!==(s=e||null==i?void 0:i.params.page)&&void 0!==s?s:{limit:l}}));oe(u,(({data:e,error:t,loading:r,nextPage:n})=>{const s={loading:r,error:t,params:{page:n},data:o};e&&(s.data=[...new Set([...o,...e.map(ce("reactor"))])]),Ee(d,s),p(s)}),ie(c))};return u.push(ad(a.referenceType,a.referenceId,g("onAdded")),ld(a.referenceType,a.referenceId,g("onRemoved"))),m(!0),()=>{n(`liveReactions(tmpid: ${i}) > dispose`),u.forEach((e=>e()))}}}),dd={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 hd=async e=>{const t=ye();let r;t.log("channel/getChannel",e),Ol("channel",e);try{const{data:n}=await t.http.get(`/api/v3/channels/${encodeURIComponent(e)}`);r=await gl(n)}catch(t){throw S(null==t?void 0:t.code)&&Da("channel",e),t}const n=t.cache&&Date.now();t.cache&&La(r,{cachedAt:n});const{channels:s}=r;return{data:s.find((t=>t.channelId===e)),cachedAt:n}};hd.locally=e=>{const t=ye();if(t.log("channel/getChannel.locally",e),!t.cache)return;const r=we(["channel","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const fd=(e,t,r)=>n=>e((e=>{var s;if(!e)return e;const i=[r,"get",`${e[t]}`],o=null===(s=we(i))||void 0===s?void 0:s.data;return o?n(o):void 0}));function pd(e,t){Ee(["channel","get",e.channelId],Object.assign(ol(e),t))}const gd=e=>{const t=ye();return Ye(t,"channelMarker/onChannelMarkerUpdated","local.channelMarker.updated",(t=>{e(t.userEntityMarkers[0])}))};var md={exports:{}};!function(e,t){e.exports=function e(t,r,n){function s(o,a){if(!r[o]){if(!t[o]){if(!a&&ko)return ko(o);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}a=r[o]={exports:{}},t[o][0].call(a.exports,(function(e){return s(t[o][1][e]||e)}),a,a.exports,e,t,r,n)}return r[o].exports}for(var i=ko,o=0;o<n.length;o++)s(n[o]);return s}({1:[function(e,t,r){(function(n,s,i,o,a,l,c,u,d){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,o=Object.prototype.toString.call(t),a=/\[object (.*)\]/i.exec(o);if(a=(a=a?a[1]:"unknown:["+o+"]").toLowerCase(),0<=(o=r.indexOf(t)))return this.dispatch("[CIRCULAR:"+o+"]");if(r.push(t),void 0!==i&&i.isBuffer&&i.isBuffer(t))return n("buffer:"),n(t);if("object"===a||"function"===a||"asyncfunction"===a)return o=Object.keys(t),e.unorderedObjects&&(o=o.sort()),!1===e.respectType||y(t)||o.splice(0,0,"prototype","__proto__","constructor"),e.excludeKeys&&(o=o.filter((function(t){return!e.excludeKeys(t)}))),n("object:"+o.length+":"),s=this,o.forEach((function(r){s.dispatch(r),n(":"),e.excludeValues||s.dispatch(t[r]),n(",")}));if(!this["_"+a]){if(e.ignoreUnknown)return n("["+a+"]");throw new Error('Unknown object type "'+a+'"')}this["_"+a](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 o=[];return s=t.map((function(t){var n=new b,s=r.slice();return v(e,n,s).dispatch(t),o=o.concat(s.slice(r.length)),n.read().toString()})),r=r.concat(o),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,o,a,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),o="A".charCodeAt(0),a="-".charCodeAt(0),l="_".charCodeAt(0);function c(e){return(e=e.charCodeAt(0))===r||e===a?62:e===n||e===l?63:e<s?-1:e<s+10?e-s+26+26:e<o+26?e-o: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)),o=0<s?e.length-4:e.length,a=0;function l(e){i[a++]=e}for(r=0;r<o;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,o="";function a(e){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(e)}for(t=0,n=e.length-i;t<n;t+=3)o+=a((s=r=(e[t]<<16)+(e[t+1]<<8)+e[t+2])>>18&63)+a(s>>12&63)+a(s>>6&63)+a(63&s);switch(i){case 1:o=(o+=a((r=e[e.length-1])>>2))+a(r<<4&63)+"==";break;case 2:o=(o=(o+=a((r=(e[e.length-2]<<8)+e[e.length-1])>>10))+a(r>>4&63))+a(r<<2&63)+"="}return o}}(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,o,a,l,c,u){var d=e("base64-js"),h=e("ieee754");function s(e,t,r){if(!(this instanceof s))return new s(e,t,r);var n,i,o,a,l=typeof e;if("base64"===t&&"string"==l)for(e=(a=e).trim?a.trim():a.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(a=e)||s.isBuffer(a)||a&&"object"==typeof a&&"number"==typeof a.length)for(o=0;o<n;o++)s.isBuffer(e)?i[o]=e.readUInt8(o):i[o]=e[o];else if("string"==l)i.write(e,0,t);else if("number"==l&&!s._useTypedArrays&&!r)for(o=0;o<n;o++)i[o]=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 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+1<e.length,"trying to write beyond buffer length"),N(t,65535)),!((s=e.length)<=r))for(var i=0,o=Math.min(s-r,2);i<o;i++)e[r+i]=(t&255<<8*(n?i:1-i))>>>8*(n?i:1-i)}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+3<e.length,"trying to write beyond buffer length"),N(t,4294967295)),!((s=e.length)<=r))for(var i=0,o=Math.min(s-r,4);i<o;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"),U(t,32767,-32768)),e.length<=r||T(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"),U(t,2147483647,-2147483648)),e.length<=r||S(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 _(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 o=e[i];o.copy(r,n),n+=o.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,o,a,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 o=0;o<n;o++){var a=parseInt(t.substr(2*o,2),16);j(!isNaN(a),"Invalid hex string"),e[r+o]=a}return s._charsWritten=2*o,o}(this,e,t,r);break;case"utf8":case"utf-8":o=this,a=t,l=r,i=s._charsWritten=M(O(e),o,a,l);break;case"ascii":case"binary":i=f(this,e,t,r);break;case"base64":o=this,a=t,l=r,i=s._charsWritten=M(P(e),o,a,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,o,a=this;if(e=String(e||"utf8").toLowerCase(),t=Number(t)||0,(r=void 0!==r?Number(r):a.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}(a,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)}(a,t,r);break;case"ascii":case"binary":n=g(a,t,r);break;case"base64":s=a,o=r,n=0===(i=t)&&o===s.length?d.fromByteArray(s):d.fromByteArray(s.slice(i,o));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}(a,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 o=0;o<i;o++)e[o+t]=this[o+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),o=0;o<n;o++)i[o]=this[o+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"),N(e,255)),t>=this.length||(this[t]=e)},s.prototype.writeUInt16LE=function(e,t,r){T(this,e,t,!0,r)},s.prototype.writeUInt16BE=function(e,t,r){T(this,e,t,!1,r)},s.prototype.writeUInt32LE=function(e,t,r){S(this,e,t,!0,r)},s.prototype.writeUInt32BE=function(e,t,r){S(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"),U(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){_(this,e,t,!0,r)},s.prototype.writeDoubleBE=function(e,t,r){_(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 I=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("%")),o=0;o<i.length;o++)t.push(parseInt(i[o],16))}return t}function P(e){return d.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 N(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 U(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=I.get,e.set=I.set,e.write=I.write,e.toString=I.toString,e.toLocaleString=I.toString,e.toJSON=I.toJSON,e.copy=I.copy,e.slice=I.slice,e.readUInt8=I.readUInt8,e.readUInt16LE=I.readUInt16LE,e.readUInt16BE=I.readUInt16BE,e.readUInt32LE=I.readUInt32LE,e.readUInt32BE=I.readUInt32BE,e.readInt8=I.readInt8,e.readInt16LE=I.readInt16LE,e.readInt16BE=I.readInt16BE,e.readInt32LE=I.readInt32LE,e.readInt32BE=I.readInt32BE,e.readFloatLE=I.readFloatLE,e.readFloatBE=I.readFloatBE,e.readDoubleLE=I.readDoubleLE,e.readDoubleBE=I.readDoubleBE,e.writeUInt8=I.writeUInt8,e.writeUInt16LE=I.writeUInt16LE,e.writeUInt16BE=I.writeUInt16BE,e.writeUInt32LE=I.writeUInt32LE,e.writeUInt32BE=I.writeUInt32BE,e.writeInt8=I.writeInt8,e.writeInt16LE=I.writeInt16LE,e.writeInt16BE=I.writeInt16BE,e.writeInt32LE=I.writeInt32LE,e.writeInt32BE=I.writeInt32BE,e.writeFloatLE=I.writeFloatLE,e.writeFloatBE=I.writeFloatBE,e.writeDoubleLE=I.writeDoubleLE,e.writeDoubleBE=I.writeDoubleBE,e.fill=I.fill,e.inspect=I.inspect,e.toArrayBuffer=I.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,o,a,l,c,u){s=e("buffer").Buffer;var d=4,h=new s(d);h.fill(0),t.exports={hash:function(e,t,r,n){for(var i=t(function(e,t){e.length%d!=0&&(r=e.length+(d-e.length%d),e=s.concat([e,h],r));for(var r,n=[],i=t?e.readInt32BE:e.readInt32LE,o=0;o<e.length;o+=d)n.push(i.call(e,o));return n}(e=s.isBuffer(e)?e:new s(e),n),8*e.length),o=(t=n,new s(r)),a=t?o.writeInt32BE:o.writeInt32LE,l=0;l<i.length;l++)a.call(o,i[l],4*l,!0);return o}}}).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,o,a,l,c,u){s=e("buffer").Buffer;var d=e("./sha"),h=e("./sha256"),f=e("./rng"),p={sha1:d,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),o=0;o<g;o++)n[o]=54^t[o],i[o]=92^t[o];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,o,a,l,c,u){var d=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,o=0;o<e.length;o+=16){var a=r,l=n,c=s,u=i;r=p(r,n,s,i,e[o+0],7,-680876936),i=p(i,r,n,s,e[o+1],12,-389564586),s=p(s,i,r,n,e[o+2],17,606105819),n=p(n,s,i,r,e[o+3],22,-1044525330),r=p(r,n,s,i,e[o+4],7,-176418897),i=p(i,r,n,s,e[o+5],12,1200080426),s=p(s,i,r,n,e[o+6],17,-1473231341),n=p(n,s,i,r,e[o+7],22,-45705983),r=p(r,n,s,i,e[o+8],7,1770035416),i=p(i,r,n,s,e[o+9],12,-1958414417),s=p(s,i,r,n,e[o+10],17,-42063),n=p(n,s,i,r,e[o+11],22,-1990404162),r=p(r,n,s,i,e[o+12],7,1804603682),i=p(i,r,n,s,e[o+13],12,-40341101),s=p(s,i,r,n,e[o+14],17,-1502002290),r=g(r,n=p(n,s,i,r,e[o+15],22,1236535329),s,i,e[o+1],5,-165796510),i=g(i,r,n,s,e[o+6],9,-1069501632),s=g(s,i,r,n,e[o+11],14,643717713),n=g(n,s,i,r,e[o+0],20,-373897302),r=g(r,n,s,i,e[o+5],5,-701558691),i=g(i,r,n,s,e[o+10],9,38016083),s=g(s,i,r,n,e[o+15],14,-660478335),n=g(n,s,i,r,e[o+4],20,-405537848),r=g(r,n,s,i,e[o+9],5,568446438),i=g(i,r,n,s,e[o+14],9,-1019803690),s=g(s,i,r,n,e[o+3],14,-187363961),n=g(n,s,i,r,e[o+8],20,1163531501),r=g(r,n,s,i,e[o+13],5,-1444681467),i=g(i,r,n,s,e[o+2],9,-51403784),s=g(s,i,r,n,e[o+7],14,1735328473),r=m(r,n=g(n,s,i,r,e[o+12],20,-1926607734),s,i,e[o+5],4,-378558),i=m(i,r,n,s,e[o+8],11,-2022574463),s=m(s,i,r,n,e[o+11],16,1839030562),n=m(n,s,i,r,e[o+14],23,-35309556),r=m(r,n,s,i,e[o+1],4,-1530992060),i=m(i,r,n,s,e[o+4],11,1272893353),s=m(s,i,r,n,e[o+7],16,-155497632),n=m(n,s,i,r,e[o+10],23,-1094730640),r=m(r,n,s,i,e[o+13],4,681279174),i=m(i,r,n,s,e[o+0],11,-358537222),s=m(s,i,r,n,e[o+3],16,-722521979),n=m(n,s,i,r,e[o+6],23,76029189),r=m(r,n,s,i,e[o+9],4,-640364487),i=m(i,r,n,s,e[o+12],11,-421815835),s=m(s,i,r,n,e[o+15],16,530742520),r=y(r,n=m(n,s,i,r,e[o+2],23,-995338651),s,i,e[o+0],6,-198630844),i=y(i,r,n,s,e[o+7],10,1126891415),s=y(s,i,r,n,e[o+14],15,-1416354905),n=y(n,s,i,r,e[o+5],21,-57434055),r=y(r,n,s,i,e[o+12],6,1700485571),i=y(i,r,n,s,e[o+3],10,-1894986606),s=y(s,i,r,n,e[o+10],15,-1051523),n=y(n,s,i,r,e[o+1],21,-2054922799),r=y(r,n,s,i,e[o+8],6,1873313359),i=y(i,r,n,s,e[o+15],10,-30611744),s=y(s,i,r,n,e[o+6],15,-1560198380),n=y(n,s,i,r,e[o+13],21,1309151649),r=y(r,n,s,i,e[o+4],6,-145523070),i=y(i,r,n,s,e[o+11],10,-1120210379),s=y(s,i,r,n,e[o+2],15,718787259),n=y(n,s,i,r,e[o+9],21,-343485551),r=v(r,a),n=v(n,l),s=v(s,c),i=v(i,u)}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,o){return f(t&r|~t&n,e,t,s,i,o)}function g(e,t,r,n,s,i,o){return f(t&n|r&~n,e,t,s,i,o)}function m(e,t,r,n,s,i,o){return f(t^r^n,e,t,s,i,o)}function y(e,t,r,n,s,i,o){return f(r^(t|~n),e,t,s,i,o)}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 d.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,o,a,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,o,a,l,c,u){var d=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),o=1732584193,a=-271733879,l=-1732584194,c=271733878,u=-1009589776,d=0;d<e.length;d+=16){for(var h=o,g=a,m=l,y=c,v=u,b=0;b<80;b++){i[b]=b<16?e[d+b]:p(i[b-3]^i[b-8]^i[b-14]^i[b-16],1);var w=f(f(p(o,5),(w=a,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(u,i[b]),(r=b)<20?1518500249:r<40?1859775393:r<60?-1894007588:-899497514));u=c,c=l,l=p(a,30),a=o,o=w}o=f(o,h),a=f(a,g),l=f(l,m),c=f(c,y),u=f(u,v)}return Array(o,a,l,c,u)}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 d.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,o,a,l,c,u){function d(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 o,a,l=0;l<e.length;l+=16){for(var c=s[0],u=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]:d(d(d((a=i[w-2],p(a,17)^p(a,19)^g(a,10)),i[w-7]),(a=i[w-15],p(a,7)^p(a,18)^g(a,3))),i[w-16]),r=d(d(d(d(b,p(a=m,6)^p(a,11)^p(a,25)),m&y^~m&v),n[w]),i[w]),o=d(p(o=c,2)^p(o,13)^p(o,22),c&u^c&h^u&h),b=v,v=y,y=m,m=d(f,r),f=h,h=u,u=c,c=d(r,o);s[0]=d(c,s[0]),s[1]=d(u,s[1]),s[2]=d(h,s[2]),s[3]=d(f,s[3]),s[4]=d(m,s[4]),s[5]=d(y,s[5]),s[6]=d(v,s[6]),s[7]=d(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,o,a,l,c){r.read=function(e,t,r,n,s){var i,o,a=8*s-n-1,l=(1<<a)-1,c=l>>1,u=-7,d=r?s-1:0,h=r?-1:1;for(s=e[t+d],d+=h,i=s&(1<<-u)-1,s>>=-u,u+=a;0<u;i=256*i+e[t+d],d+=h,u-=8);for(o=i&(1<<-u)-1,i>>=-u,u+=n;0<u;o=256*o+e[t+d],d+=h,u-=8);if(0===i)i=1-c;else{if(i===l)return o?NaN:1/0*(s?-1:1);o+=Math.pow(2,n),i-=c}return(s?-1:1)*o*Math.pow(2,i-n)},r.write=function(e,t,r,n,s,i){var o,a,l=8*i-s-1,c=(1<<l)-1,u=c>>1,d=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?(a=isNaN(t)?1:0,o=c):(o=Math.floor(Math.log(t)/Math.LN2),t*(n=Math.pow(2,-o))<1&&(o--,n*=2),2<=(t+=1<=o+u?d/n:d*Math.pow(2,1-u))*n&&(o++,n/=2),c<=o+u?(a=0,o=c):1<=o+u?(a=(t*n-1)*Math.pow(2,s),o+=u):(a=t*Math.pow(2,u-1)*Math.pow(2,s),o=0));8<=s;e[r+h]=255&a,h+=f,a/=256,s-=8);for(o=o<<s|a,l+=s;0<l;e[r+h]=255&o,h+=f,o/=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,o,a,l,c){var u,d,h;function f(){}(e=t.exports={}).nextTick=(d="undefined"!=typeof window&&window.setImmediate,h="undefined"!=typeof window&&window.postMessage&&window.addEventListener,d?function(e){return window.setImmediate(e)}:h?(u=[],window.addEventListener("message",(function(e){var t=e.source;t!==window&&null!==t||"process-tick"!==e.data||(e.stopPropagation(),0<u.length&&u.shift()())}),!0),function(e){u.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)}(md);var yd=md.exports;class vd{constructor(e){const{http:t}=ye();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 o=await this.getRequest(this.queryParams,i);return"first"===e&&(this.nextToken=null===(t=o.paging)||void 0===t?void 0:t.next,this.previousToken=null===(r=o.paging)||void 0===r?void 0:r.previous),"prev"===e&&(this.previousToken=null===(n=o.paging)||void 0===n?void 0:n.previous),"next"===e&&(this.nextToken=null===(s=o.paging)||void 0===s?void 0:s.next),o}getNextToken(){return this.nextToken}getPrevToken(){return this.previousToken}}class bd extends vd{async getRequest(e,t){const{limit:r=h,displayName:n,membership:s}=e,i=xa(e,["limit","displayName","membership"]),o=t?{token:t}:{limit:r},{data:a}=await this.http.get("/api/v3/channels",{params:Object.assign(Object.assign({},i),{keyword:n,filter:s,options:o})});return a}}class wd{constructor(e,t){this.query=e,this.cacheKey=t}}class Ed extends wd{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=ye(),n=r.cache&&Date.now();r.cache&&La(t,{cachedAt:n})}appendToQueryStream(e,t,r=!1){var n,s;if(r)Ee(this.cacheKey,{data:e.channels.map(ce("channel"))});else{const t=null===(n=we(this.cacheKey))||void 0===n?void 0:n.data,r=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Ee(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...r,...e.channels.map(ce("channel"))])]}))}}reactor(e){return e=>{var t;const r=null===(t=we(this.cacheKey))||void 0===t?void 0:t.data;r&&(this.paginationController instanceof bd&&(r.data=[...new Set([e.channelId,...r.data])],Ee(this.cacheKey,r)),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Td{constructor(e){const{http:t}=ye();this.queryParams=e,this.http=t}async onFetch(){return await this.getRequest(this.queryParams)}}class Sd{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 Td?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 Td)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 Td)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!bc(this.snapshot,e)&&(this.snapshot=e.map((e=>vc(e))),!0)}getCacheKey(){return this.cacheKey}}class Cd extends Td{async getRequest(e){const{data:t}=await this.http.get("/api/v3/channels/list",{params:Object.assign({},e)});return t}}class kd extends Sd{constructor(e,t){const r=yd(e),n=["channel","collection",r],s=kd.getPaginationController(e);super(s,r,n,t),this.query=e,this.queryStreamController=new Ed(this.query,this.cacheKey,this.notifyChange.bind(this),gl,s),this.paginationController=s,this.callback=t.bind(this),this.loadPage(!0)}setup(){var e;(null===(e=we(this.cacheKey))||void 0===e?void 0:e.data)||Ee(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=we(this.cacheKey))||void 0===n?void 0:n.data;if(!i)return;let o=null!==(s=i.data.map((e=>we(["channel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(tl))&&void 0!==s?s:[];this.paginationController instanceof bd&&(o=this.applyFilter(o)),(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:this.paginationController instanceof bd?()=>this.loadPage(!1,"next"):void 0,data:o,hasNextPage:this.paginationController instanceof bd&&!!this.paginationController.getNextToken(),loading:t,error:r})}applyFilter(e){const{userId:t}=ye();let r=e;switch(r=ke(r,"isDeleted",this.query.isDeleted),r=ke(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=Ie(r,this.query.membership,t)),this.query.sortBy){case"firstCreated":r=r.sort(Me);break;case"lastCreated":r=r.sort(Fe);break;case"displayName":r=r.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Oe);break;default:r=r.sort(Be)}return r}shouldAbort(e){var t,r;const n=null===(t=we(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 ye().getMessagePreviewSetting(!1)}static getPaginationController(e){return e.channelIds&&e.channelIds.length>0?new Cd(e):new bd(e)}getSubscriptions(){const e=[{fn:fd((e=>Dc((t=>{var r;const n=null===(r=we(["channel","get",t.channelId]))||void 0===r?void 0:r.data;n&&(pd(n,{lastActivity:t.createdAt}),e(t))}))),"messageId","channel"),action:"onUpdate"},{fn:Yl,action:"onDelete"},{fn:Tc,action:"onUpdate"},{fn:kc,action:"onMute"},{fn:Sc,action:"onJoin"},{fn:Cc,action:"onLeft"},{fn:Ac,action:"onMemberAdded"},{fn:_c,action:"onMemberRemoved"},{fn:fd(dc,"entityId","channel"),action:"onUpdate"},{fn:fd(gd,"entityId","channel"),action:"onUpdate"},{fn:fd((e=>Dc((async t=>{var r;if("no-message-preview"===await kd.getMessagePreviewSetting())return;if(ll(t),this.shouldAbort(t.channelId))return;const n=null===(r=we(["channel","get",t.channelId]))||void 0===r?void 0:r.data;n&&(pd(n,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:fd((e=>xc((async t=>{"no-message-preview"!==await kd.getMessagePreviewSetting()&&(cl(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:fd((e=>Oc((async t=>{const r=await kd.getMessagePreviewSetting();"no-message-preview"!==r&&("message-preview-include-deleted"===r&&await cl(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===r&&await hd(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:fd((e=>qc((async t=>{var r;const n=null===(r=we(this.cacheKey))||void 0===r?void 0:r.data;if(!n)return;n.data.find((e=>{const r=$a(e);return(null==r?void 0:r.subChannelId)===t.subChannelId}))&&(await hd(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:fd((e=>$c((async t=>{var r;if("no-message-preview"===await kd.getMessagePreviewSetting())return;(null===(r=we(this.cacheKey))||void 0===r?void 0:r.data)&&(await ul(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"}];return this.paginationController instanceof vd?[...e,{fn:Ec,action:"onCreate"}]:e}}class Ad extends vd{async getRequest(e,t){const{limit:r=h}=e,n=xa(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 _d extends wd{constructor(e,t,r,n){super(e,t),this.notifyChange=r,this.preparePayload=n}async saveToMainDB(e){const t=await this.preparePayload(e),r=ye(),n=r.cache&&Date.now();r.cache&&La(t,{cachedAt:n})}appendToQueryStream(e,t,r=!1){var n,s;if(r)Ee(this.cacheKey,{data:e.channelUsers.map((({channelId:e,userId:t})=>ce("channelUsers")({channelId:e,userId:t})))});else{const t=null===(n=we(this.cacheKey))||void 0===n?void 0:n.data,r=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Ee(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...r,...e.channelUsers.map((({channelId:e,userId:t})=>ce("channelUsers")({channelId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var r;if(this.query.channelId!==t.channelId)return;const n=null===(r=we(this.cacheKey))||void 0===r?void 0:r.data;if(!n)return;const s=ce("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]),Ee(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Id extends Sd{constructor(e,t){const r=yd(e),n=["channelUsers","collection",r];super(new Ad(e),r,n,t),this.query=e,this.queryStreamController=new _d(this.query,this.cacheKey,this.notifyChange.bind(this),gl),this.callback=t.bind(this),this.loadPage(!0)}setup(){var e;(null===(e=we(this.cacheKey))||void 0===e?void 0:e.data)||Ee(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:Cc,action:"onLeft"},{fn:Ac,action:"onMemberAdded"},{fn:_c,action:"onMemberRemoved"},{fn:Ql,action:"onChannelMemberBanned"},{fn:Ic,action:"onChannelMemberUnbanned"},{fn:Rc,action:"onChannelMemberRoleAdded"},{fn:Lc,action:"onChannelMemberRoleRemoved"}])}notifyChange({origin:e,loading:t,error:r}){var n,s;const i=null===(n=we(this.cacheKey))||void 0===n?void 0:n.data;if(!i)return;const o=this.applyFilter(null!==(s=i.data.map((e=>we(["channelUsers","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage(!1,"next"),data:o,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=xe(t,this.query.search));const r=this.query.sortBy?this.query.sortBy:"lastCreated";return t=t.sort("lastCreated"===r?Fe:Me),t}}const Rd=(e,t,r)=>{const{log:n,cache:s}=ye();s||console.log(p);const i=Date.now();n(`getMembers(tmpid: ${i}) > listen`);const o=new Id(e,t),a=o.startSubscription(),l=o.getCacheKey();return a.push((()=>{Ce(l)})),()=>{n(`getMembers(tmpid: ${i}) > dispose`),a.forEach((e=>e()))}};var Ld=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const r=ye();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=>Qe("channel.membersAdded",Object.assign(Object.assign({},n),{channelUsers:n.channelUsers.filter((t=>t.userId===e))}))));const s=await gl(n);r.cache&&La(s);const{channelUsers:i}=s;return!!i.find((t=>t.channelId===e&&"member"===t.membership))},removeMembers:async(e,t)=>{const r=ye();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=>Qe("channel.membersRemoved",Object.assign(Object.assign({},n),{channelUsers:n.channelUsers.filter((t=>t.userId===e))}))));const s=await gl(n);r.cache&&La(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=xe(r,t.search));const n=t.sortBy?t.sortBy:"lastCreated";return r=r.sort("lastCreated"===n?Fe:Me),r},getMembers:Rd,searchMembers:(e,t,r)=>Rd(e,t)});var Dd=Object.freeze({__proto__:null,addRole:async(e,t,r)=>{const n=ye();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 gl(s);n.cache&&La(i),Qe("local.channel-moderator.role-added",i);const{channelUsers:o}=i;return!!o.find((r=>r.channelId===e&&r.roles.includes(t)))},removeRole:async(e,t,r)=>{const n=ye();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 gl(s);n.cache&&La(i),Qe("local.channel-moderator.role-removed",i);const{channelUsers:o}=i;return!!o.find((r=>r.channelId===e&&!r.roles.includes(t)))},banMembers:async(e,t)=>{const r=ye();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 gl(n),{channelUsers:i}=s,o=r.cache&&Date.now();return r.cache&&La(s,{cachedAt:o}),{data:null==i?void 0:i.filter((e=>"banned"===e.membership)),cachedAt:o}},unbanMembers:async(e,t)=>{const r=ye();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 gl(n),i=r.cache&&Date.now();r.cache&&La(s,{cachedAt:i});const{channelUsers:o}=s;return{data:null==o?void 0:o.filter((e=>"member"===e.membership)),cachedAt:i}}}),xd=Object.freeze({__proto__:null,Membership:Ld,Moderation:Dd,getChannelByIds:ml,createChannel:async e=>{const t=ye();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=xa(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 gl(r.data),s=t.cache&&Date.now();t.cache&&La(n,{cachedAt:s});const{channels:i}=n;return{data:i[0],cachedAt:s}},updateChannel:async(e,t)=>{const r=ye();r.log("channel/updateChannel",e,t);const{data:n}=await r.http.put(`/api/v3/channels/${encodeURIComponent(e)}`,t),s=await gl(n),i=r.cache&&Date.now();r.cache&&La(s,{cachedAt:i});const{channels:o}=s;return{data:o.find((t=>t.channelId===e)),cachedAt:i}},deleteChannel:async e=>{const t=ye();t.log("channel/deleteChannel",e),await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}`);return(await hd(e)).data},joinChannel:async e=>{const t=ye();t.log("channel/joinChannel",e);const{data:r}=await t.http.post(`/api/v3/channels/${encodeURIComponent(e)}/join`),n=await gl(r);t.cache&&La(n);const{channelUsers:s}=n;return!!s.find((t=>t.channelId===e&&"member"===t.membership))},leaveChannel:async e=>{const t=ye();t.log("channel/leaveChannel",e);const{data:r}=await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/leave`),n=await gl(r);t.cache&&La(n);const{channelUsers:s}=n;return!!s.find((t=>t.channelId===e&&"member"!==t.membership))},muteChannel:async(e,t=-1)=>{const r=ye();if(r.log("channel/muteChannel",e),-1!==t&&t<0)throw new he("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=ye();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=ye();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,o=xa(r,["userMarkers","userEntityMarkers","userFeedMarkers"]),a=t.cache&&Date.now(),l=Na(s),c=Ua(i);return t.cache&&La(Object.assign({userMarkers:Fa(n),userEntityMarkers:l,userFeedMarkers:c},o),{cachedAt:a}),Qe("local.channelMarker.updated",{userEntityMarkers:l}),Qe("local.subChannelMarker.updated",{userFeedMarkers:c}),!0},onChannelCreated:Ec,onChannelUpdated:Tc,onChannelDeleted:Yl,onChannelJoined:Sc,onChannelLeft:Cc,onChannelMuted:kc,onChannelMemberAdded:Ac,onChannelMemberRemoved:_c,onChannelMemberBanned:Ql,onChannelMemberUnbanned:Ic,onChannelMemberRoleAdded:Rc,onChannelMemberRoleRemoved:Lc,observeChannel:(e,t)=>{const{log:r}=ye(),n=Date.now();r(`observeChannel(tmpid: ${n}) > listen`);const s=(r,n)=>{var s,i,o;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===(o=t[n])||void 0===o||o.call(t,r)}},i=[];return i.push(Tc((e=>s({data:e,loading:!1,origin:"event"},"onUpdate"))),Yl((e=>s({data:e,loading:!1,origin:"event"},"onDelete"))),Sc((e=>s({data:e,loading:!1,origin:"event"},"onJoin"))),Cc((e=>s({data:e,loading:!1,origin:"event"},"onLeft"))),kc((e=>s({data:e,loading:!1,origin:"event"},"onMute"))),Ac((e=>s({data:e,loading:!1,origin:"event"},"onMemberAdded"))),_c((e=>s({data:e,loading:!1,origin:"event"},"onMemberRemoved"))),fd(dc,"entityId","channel")((e=>s({data:e,loading:!1,origin:"event"},"onUpdate")))),oe(se(hd,e),(e=>e.data&&s(e,"onFetch"))),()=>{r(`observeChannel(tmpid: ${n}) > dispose`),i.forEach((e=>e()))}},observeChannels:e=>{const{log:t}=ye(),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(Ec((e=>s(e,"onCreate"))),Tc((e=>s(e,"onUpdate"))),Yl((e=>s(e,"onDelete"))),Sc((e=>s(e,"onJoin"))),Cc((e=>s(e,"onLeft"))),kc((e=>s(e,"onMute"))),Ac((e=>s(e,"onMemberAdded"))),_c((e=>s(e,"onMemberRemoved"))),fd(dc,"entityId","channel")((e=>s(e,"onUpdate")))),()=>{t(`observeChannels(tmpid: ${r}) > dispose`),n.forEach((e=>e()))}},getChannel:(e,t)=>{const r=ye();let n;return wc(e,(async e=>{if(!e.data)return t(e);const r=Object.assign(Object.assign({},e),{data:tl(e.data)}),s=xa(r,["origin"]);return bc(n,s)?void 0:(n=s,t(r))}),"channelId",hd,[Tc,Yl,Sc,Cc,Ac,_c,Ql,Ic,kc,fd(dc,"entityId","channel"),fd(gd,"entityId","channel"),fd((t=>Dc((async n=>{var s;if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;if(await ll(n),n.channelId!==e)return;const i=null===(s=we(["channel","get",e]))||void 0===s?void 0:s.data;i&&(pd(i,{messagePreviewId:n.messageId}),t(n))}))),"channelId","channel"),fd((t=>xc((async n=>{var s;const i=null===(s=we(["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 cl(n),t(n))}))),"channelId","channel"),fd((t=>Oc((async n=>{var s;const i=null===(s=we(["channel","get",e]))||void 0===s?void 0:s.data;if(!i||i.messagePreviewId!==n.messageId)return;const o=await r.getMessagePreviewSetting(!1);"no-message-preview"!==o&&("message-preview-not-include-deleted"===o?(Ce(["messagePreviewChannel","get",e]),await hd(n.channelId)):await cl(n),t(n))}))),"channelId","channel"),fd((e=>qc((async t=>{var n,s;const{channelId:i,subChannelId:o}=t,a=null===(n=we(["messagePreviewChannel","get",i]))||void 0===n?void 0:n.data;if(!a||a.subChannelId!==o)return;if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;await hd(i);(null===(s=we(["channel","get",i]))||void 0===s?void 0:s.data)&&e(t)}))),"channelId","channel"),fd((t=>$c((async n=>{var s,i;if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;ul(n);const o=null===(s=we(["messagePreviewChannel","get",e]))||void 0===s?void 0:s.data;if(!o||o.subChannelId!==n.subChannelId)return;(null===(i=we(["channel","get",e]))||void 0===i?void 0:i.data)&&t(n)}))),"channelId","channel")],{forceDispatch:!0})},getChannels:(e,t,r)=>{const{log:n,cache:s,userId:i}=ye();s||console.log(p);const o=Date.now();n(`getChannels(tmpid: ${o}) > listen`);const a=new kd(e,t),l=a.startSubscription(),c=a.getCacheKey();return l.push((()=>{Ce(c)})),()=>{n(`getChannels(tmpid: ${o}) > dispose`),l.forEach((e=>e()))}},MARKER_INCLUDED_CHANNEL_TYPE:dl,isUnreadCountSupport:hl,convertFromRaw:fl,preUpdateChannelCache:pl,prepareChannelPayload:gl});const Od=async e=>{const t=ye();t.log("message/getMessages",e);const{data:r}=await t.http.get("/api/v5/messages/list",{params:{messageIds:e.map(encodeURIComponent)}}),n=await Cl(r),s=t.cache&&Date.now();t.cache&&La(n,{cachedAt:s});const{messages:i}=n;return Qe("local.message.fetched",{messages:i}),{data:i,cachedAt:s}};Od.locally=e=>{var t;const r=ye();if(r.log("message/getMessages.locally",e),!r.cache)return;const n=e.map((e=>we(["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 Pd=()=>`LOCAL_${Sa()}`;let Md;const Fd=async e=>{const t=ye();t.log("message/createMessage",e);const r=e.referenceId||Md||Pd();Md=void 0;const{data:n}=await t.http.post("/api/v5/messages",Object.assign(Object.assign({},kl(e)),{referenceId:r})),s=await Cl(n),{messages:i}=s,o=t.cache&&Date.now();return t.cache&&(Ce(["message","get",r]),La(s,{cachedAt:o})),Qe("local.message.created",{messages:i}),{data:i[0],cachedAt:o}};Fd.optimistically=e=>{var t,r,{referenceId:n}=e,s=xa(e,["referenceId"]);const i=ye();if(!i.cache)return;Md=n||Pd();const o=Object.assign({messageId:Md,uniqueId:Md},s);i.log("message/createMessage.optimistically",o);const a=we(["subChannel","get",s.subChannelId]);if(a&&(Se(["subChannel","get",s.subChannelId],Object.assign(Object.assign({},a.data),{messageCount:a.data.messageCount+1})),a.data.channelId===a.data.subChannelId)){const e=we(["channel","get",a.data.channelId]);(null==e?void 0:e.data)&&Se(["channel","get",a.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,channelSegment:(null!==(r=null==a?void 0:a.data.messageCount)&&void 0!==r?r:0)+1,childrenNumber:0,createdAt:l,updatedAt:l},o);return Ee(["message","get",c.messageId],c,{cachedAt:-5}),Qe("local.message.created",{messages:[c]}),{cachedAt:-5,data:c}};const Nd=async(e,t)=>{const r=ye();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)}`,kl(t)),s=await Cl(n),i=r.cache&&Date.now();r.cache&&La(s,{cachedAt:i});const{messages:o}=s;return Qe("local.message.updated",{messages:o}),{data:o.find((t=>t.messageId===e)),cachedAt:i}};Nd.optimistically=(e,t)=>{const r=ye();if(r.log("message/updateMessage.optimistically",t),!r.cache)return;const n=we(["message","get",e]);if(!n)return;const s=Object.assign(Object.assign(Object.assign({},n.data),t),{updatedAt:(new Date).toISOString()});return Se(["message","get",e],s,{cachedAt:-1}),Qe("local.message.updated",{messages:[s]}),{data:s,cachedAt:-1}};const Ud=async(e,t)=>{const r=ye();r.log("message/editMessage",t);const{data:n}=await r.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,kl(t)),s=await Cl(n),i=r.cache&&Date.now();r.cache&&La(s,{cachedAt:i});const{messages:o}=s;return Qe("local.message.updated",{messages:o}),{data:o.find((t=>t.messageId===e)),cachedAt:i}};Ud.optimistically=(e,t)=>{const r=ye();if(r.log("message/editMessage.optimistically",t),!r.cache)return;const n=we(["message","get",e]);if(!n)return;const s=Object.assign(Object.assign(Object.assign({},n.data),t),{updatedAt:(new Date).toISOString()});return Se(["message","get",e],s,{cachedAt:-1}),Qe("local.message.updated",{messages:[s]}),{data:s,cachedAt:-1}};const Bd=async e=>{const t=ye();t.log("message/deleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const r=await Nu(e);return Qe("local.message.deleted",{messages:[r.data]}),r.data};Bd.optimistically=e=>{ye().log("message/deleteMessage.optimistically",e);const t=we(["message","get",e]);if(!t)return;const r=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return Se(["message","get",e],r,{cachedAt:-1}),Qe("local.message.deleted",{messages:[r]}),{data:r,cachedAt:-1}};const jd=async e=>{const t=ye();t.log("message/softDeleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const r=await Nu(e);return Qe("local.message.deleted",{messages:[r.data]}),r.data};jd.optimistically=e=>{ye().log("message/softDeleteMessage.optimistically",e);const t=we(["message","get",e]);if(!t)return;const r=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return Se(["message","get",e],r,{cachedAt:-1}),Qe("local.message.deleted",{messages:[r]}),{data:r,cachedAt:-1}};const $d=async e=>{const t=ye();t.log("user/getReadUsers",e);const{page:r,messageId:n}=e,s=xa(e,["page","messageId"]),{data:i}=await t.http.get(`/api/v1/markers/messages/${n}/read-users`,{params:Object.assign(Object.assign({},s),{options:{token:Q(r,"afterbeforeraw")}})}),{paging:o,publicUserIds:a,userFeedMarkers:l}=i,c=xa(i,["paging","publicUserIds","userFeedMarkers"]),u=t.cache&&Date.now();if(t.cache){La(Object.assign(Object.assign({},c),{userFeedMarkers:Ua(l)}),{cachedAt:u});const e=["read-user","query",Object.assign(Object.assign({messageId:n},s),{options:Object.assign({},r)})];Ee(e,{users:a,paging:o})}let d=[];a.length>0&&({data:d}=await yu(a));return{data:d,cachedAt:u,prevPage:X(o.previous),nextPage:X(o.next)}};$d.locally=e=>{var t;const r=ye();if(r.log("user/getReadUsers.locally",e),!r.cache)return;const{page:n}=e,s=xa(e,["page"]),i=["read-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},n)})],{data:o,cachedAt:a}=null!==(t=we(i))&&void 0!==t?t:{},l=null==o?void 0:o.users.map((e=>{var t;return null===(t=we(["user","get",e]))||void 0===t?void 0:t.data}));if(!l||l.some((e=>!e)))return;return{data:l,cachedAt:a,prevPage:X(null==o?void 0:o.paging.previous),nextPage:X(null==o?void 0:o.paging.next)}};const qd=async e=>{const t=ye();t.log("user/getDeliveredUsers",e);const{page:r,messageId:n}=e,s=xa(e,["page","messageId"]),{data:i}=await t.http.get(`/api/v1/markers/messages/${n}/delivered-users`,{params:Object.assign(Object.assign({},s),{options:{token:Q(r,"afterbeforeraw")}})}),{paging:o,publicUserIds:a,userFeedMarkers:l}=i,c=xa(i,["paging","publicUserIds","userFeedMarkers"]),u=t.cache&&Date.now();if(t.cache){La(Object.assign(Object.assign({},c),{userFeedMarkers:Ua(l)}),{cachedAt:u});const e=["delivered-user","query",Object.assign(Object.assign({messageId:n},s),{options:Object.assign({},r)})];Ee(e,{users:a,paging:o})}let d=[];a.length>0&&({data:d}=await yu(a));return{data:d,cachedAt:u,prevPage:X(o.previous),nextPage:X(o.next)}};qd.locally=e=>{var t;const r=ye();if(r.log("user/getDeliveredUsers.locally",e),!r.cache)return;const{page:n}=e,s=xa(e,["page"]),i=["delivered-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},n)})],{data:o,cachedAt:a}=null!==(t=we(i))&&void 0!==t?t:{},l=null==o?void 0:o.users.map((e=>{var t;return null===(t=we(["user","get",e]))||void 0===t?void 0:t.data}));if(!l||l.some((e=>!e)))return;return{data:l,cachedAt:a,prevPage:X(null==o?void 0:o.paging.previous),nextPage:X(null==o?void 0:o.paging.next)}};class Kd extends vd{async getRequest(e,t){const r=Al(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 Gd extends wd{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=ye(),n=r.cache&&Date.now();r.cache&&La(t,{cachedAt:n})}appendToQueryStream(e,t,r=!1){var n,s;if(r)Ee(this.cacheKey,{data:e.messages.map(ce("message")),query:this.query});else{const r=null===(n=we(this.cacheKey))||void 0===n?void 0:n.data,i=null!==(s=null==r?void 0:r.data)&&void 0!==s?s:[];Ee(this.cacheKey,Object.assign(Object.assign({},r),{data:"next"===t?[...new Set([...i,...e.messages.map(ce("message"))])]:[...new Set([...e.messages.map(ce("message")),...i])]}))}}reactor(e){return t=>{var r,n,s,i,o;if("onCreate"===e){const e=null===(r=we(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===(o=this.query.tags)||void 0===o?void 0:o.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])]),Ee(this.cacheKey,e)}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Hd extends Sd{constructor(e,t){const r=yd(e),n=["message","collection",r];super(new Kd(e),r,n,t),this.query=e,this.queryStreamController=new Gd(this.query,this.cacheKey,this.notifyChange.bind(this),Cl,this.paginationController),this.callback=t.bind(this),this.loadPage(!0)}setup(){var e;(null===(e=we(this.cacheKey))||void 0===e?void 0:e.data)||Ee(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:Oc,action:"onDelete"},{fn:xc,action:"onUpdate"},{fn:Pc,action:"onFlagged"},{fn:Mc,action:"onUnflagged"},{fn:Fc,action:"onFlagCleared"},{fn:Nc,action:"onReactionAdded"},{fn:Uc,action:"onReactionRemoved"},{fn:fd(mc,"contentId","message"),action:"onUpdate"},{fn:fd(yc,"contentId","message"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:r}){var n,s;const i=null===(n=we(this.cacheKey))||void 0===n?void 0:n.data;if(!i)return;const o=this.applyFilter(null!==(s=i.data.map((e=>we(["message","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage(!1,"next"),onPrevPage:()=>this.loadPage(!1,"prev"),data:o,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=ke(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}}var Vd=Object.freeze({__proto__:null,getMessageByIds:Od,createMessage:Fd,updateMessage:Nd,editMessage:Ud,deleteMessage:Bd,softDeleteMessage:jd,markAsDelivered:async(e,t)=>{const r=ye();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:o}=n,a=xa(n,["userMarkers","userEntityMarkers","userFeedMarkers"]),l=r.cache&&Date.now();return r.cache&&La(Object.assign({userMarkers:Fa(s),userEntityMarkers:Na(i),userFeedMarkers:Ua(o)},a),{cachedAt:l}),!0},getReadUsers:$d,getDeliveredUsers:qd,flagMessage:async e=>{const t=ye();t.log("message/flag",e);const{data:r}=await t.http.post(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await Cl(r);La(e)}return Qe("message.flagged",r),!!r},unflagMessage:async e=>{const t=ye();t.log("message/unflag",e);const{data:r}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await Cl(r);La(e)}return Qe("message.unflagged",r),!!r},isMessageFlaggedByMe:async e=>{const t=ye();t.log("message/isMessageFlaggedByMe",e);const{data:r}=await t.http.get(`/api/v5/messages/${encodeURIComponent(e)}/flags`);return r.result},onMessageCreated:Dc,onMessageUpdated:xc,onMessageDeleted:Oc,onMessageFlagged:Pc,onMessageUnflagged:Mc,onMessageFlagCleared:Fc,onMessageReactionAdded:Nc,onMessageReactionRemoved:Uc,onMessageFetched:Bc,getMessage:(e,t)=>wc(e,t,"messageId",Nu,[Bc,xc,Oc,Pc,Mc,Fc,Nc,Uc,fd(mc,"contentId","message"),fd(yc,"contentId","message")]),getMessages:(e,t,r)=>{const{log:n,cache:s}=ye();s||console.log(p);const i=Date.now();n(`getMessages(tmpid: ${i}) > listen`);const o=new Hd(e,t),a=o.startSubscription(),l=o.getCacheKey();return a.push((()=>{Ce(l)})),()=>{n(`getMessages(tmpid: ${i}) > dispose`),a.forEach((e=>e()))}},observeMessage:(e,t,r="cache_then_server")=>{const{log:n}=ye(),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,o;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===(o=t[n])||void 0===o||o.call(t,r)}},o=[];return o.push(xc((e=>i({data:e,loading:!1,origin:"event"},"onUpdate"))),Oc((e=>i({data:e,loading:!1,origin:"event"},"onDelete"))),fd(mc,"contentId","message")((e=>i({data:e,loading:!1,origin:"event"},"onUpdate"))),fd(yc,"contentId","message")((e=>i({data:e,loading:!1,origin:"event"},"onUpdate")))),"no_fetch"!==r&&oe(se(Nu,e),(e=>e.data&&i(e,"onFetch")),ie(r)),()=>{n(`observeMessages(tmpid: ${s}) > dispose`),o.forEach((e=>e()))}},observeMessages:(e,t)=>{const{log:r}=ye(),n=Date.now();r(`observeMessages(tmpid: ${n}) > listen`);const s=[],i=(r,n)=>{var s,i,o;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===(o=t[n])||void 0===o||o.call(t,r)}};return s.push(Dc((e=>i({data:e,loading:!1,origin:"event"},"onCreate"))),xc((e=>i({data:e,loading:!1,origin:"event"},"onUpdate"))),Oc((e=>i({data:e,loading:!1,origin:"event"},"onDelete"))),fd(mc,"contentId","message")((e=>i({data:e,loading:!1,origin:"event"},"onCreate"))),fd(yc,"contentId","message")((e=>i({data:e,loading:!1,origin:"event"},"onCreate")))),()=>{r(`observeMessages(tmpid: ${n}) > dispose`),s.forEach((e=>e()))}},convertFromRaw:Sl,prepareMessagePayload:Cl,convertParams:kl,convertQueryParams:Al});const zd=async(e,t=!1)=>{const r=ye(),n=await Pl(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:de(n.data.updatedAt)});return t?setTimeout((()=>{Da("subChannel",e)}),0):Se(["subChannel","get",e],s),Qe("local.message-feed.deleted",{messageFeeds:[s]}),s},Wd=e=>Ye(ye(),"onSubChannelFetched","local.message-feed.fetched",(t=>e(t.messageFeeds[0])));class Yd extends vd{async getRequest(e,t){var r;const{limit:n=h}=e,s=null!==(r=function(e){var{excludeDefaultSubChannel:t}=e,r=xa(e,["excludeDefaultSubChannel"]);const n=Object.assign({},r);return void 0!==t&&(n.excludeDefaultMessageFeed=t),n}(xa(e,["limit"])))&&void 0!==r?r:{},{channelId:i,includeDeleted:o}=s,a=xa(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({},a),{isDeleted:vl(o),options:l})});return c}}class Qd extends wd{constructor(e,t,r,n){super(e,t),this.notifyChange=r,this.preparePayload=n}async saveToMainDB(e){const t=await this.preparePayload(e),r=ye(),n=r.cache&&Date.now();r.cache&&La(t,{cachedAt:n})}appendToQueryStream(e,t,r=!1){var n,s;if(r)Ee(this.cacheKey,{data:e.messageFeeds.map((({messageFeedId:e})=>e))});else{const t=null===(n=we(this.cacheKey))||void 0===n?void 0:n.data,r=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Ee(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=we(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])]),Ee(this.cacheKey,n)}this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Xd extends Sd{constructor(e,t){const r=yd(e),n=["subChannel","collection",r];super(new Yd(e),r,n,t),this.query=e,this.queryStreamController=new Qd(this.query,this.cacheKey,this.notifyChange.bind(this),Rl),this.callback=t.bind(this),this.loadPage(!0)}setup(){var e;(null===(e=we(this.cacheKey))||void 0===e?void 0:e.data)||Ee(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:Wd,action:"onCreate"},{fn:jc,action:"onCreate"},{fn:qc,action:"onDelete"},{fn:e=>$c((async t=>{var r;const n=null===(r=we(this.cacheKey))||void 0===r?void 0:r.data;if(!n||!n.data.includes(t.subChannelId))return;const s=ye();if("no-message-preview"!==await s.getMessagePreviewSetting(!1)){const e=nl(t.subChannelId);(null==e?void 0:e.subChannelId)===t.subChannelId&&Ee(["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=we(["subChannel","get",t.subChannelId]);if(!s)return;const i=null===(r=we(this.cacheKey))||void 0===r?void 0:r.data;if(!i||!i.data.includes(t.subChannelId))return;const o=ye();if("no-message-preview"===await o.getMessagePreviewSetting(!1))return;ll(t);const a=null===(n=we(["subChannel","get",t.subChannelId]))||void 0===n?void 0:n.data;a&&(al(t.subChannelId,a,{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=>fc((t=>{var r;const n=null!==(r=t.map((({feedId:e})=>we(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];0!==n.length&&e(n)})),action:"onUpdate"},{fn:fd(hc,"feedId","subChannel"),action:"onUpdate"},{fn:fd((e=>xc((async t=>{var r;const n=ye();if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;const s=null===(r=we(this.cacheKey))||void 0===r?void 0:r.data;s&&s.data.includes(t.subChannelId)&&(cl(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:fd((e=>Oc((async t=>{var r;const n=ye(),s=await n.getMessagePreviewSetting(!1);if("no-message-preview"===s)return;const i=null===(r=we(this.cacheKey))||void 0===r?void 0:r.data;i&&i.data.includes(t.subChannelId)&&("message-preview-not-include-deleted"===s?await Pl(t.subChannelId):await cl(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:r}){var n,s;const i=null===(n=we(this.cacheKey))||void 0===n?void 0:n.data;if(!i)return;const o=this.applyFilter(null!==(s=i.data.map((e=>we(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(sl))&&void 0!==s?s:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage(!1,"next"),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:r})}applyFilter(e){let t=e;return this.query.includeDeleted||(t=ke(e,"isDeleted",!1)),t.sort(Be),t}}var Jd=Object.freeze({__proto__:null,getSubChannelByIds:ql,createSubChannel:async e=>{const t=ye();t.log("user/createSubChannel",e);const r=await t.http.post("/api/v5/message-feeds",{channelId:e.channelId,name:e.displayName}),n=await Rl(r.data),s=t.cache&&Date.now();return t.cache&&La(n,{cachedAt:s}),Qe("message-feed.created",r.data),{data:n.messageFeeds[0],cachedAt:s}},updateSubChannel:async(e,t)=>{const r=ye();r.log("channel/updateSubChannel",e,t);const n=await r.http.put(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{name:t.displayName}),s=await Rl(n.data),i=r.cache&&Date.now();return r.cache&&La(s,{cachedAt:i}),Qe("message-feed.updated",n.data),{data:s.messageFeeds[0],cachedAt:i}},deleteSubChannel:zd,hardDeleteSubChannel:async e=>{ye().log("channel/hardDeleteSubChannel",e);return await zd(e,!0)},softDeleteSubChannel:async e=>{ye().log("channel/softDeleteSubChannel",e);return await zd(e,!1)},onSubChannelCreated:jc,onSubChannelUpdated:$c,onSubChannelDeleted:qc,getSubChannel:(e,t)=>{const r=ye();let n;return wc(e,(e=>{if(!e.data)return t(e);const r=Object.assign(Object.assign({},e),{data:sl(e.data)}),s=xa(r,["origin"]);return bc(n,s)?void 0:(n=s,t(r))}),"subChannelId",Pl,[Wd,t=>$c((async n=>{"no-message-preview"!==await r.getMessagePreviewSetting(!1)&&(ul(n),n.subChannelId===e&&t(n))})),qc,fd(hc,"feedId","subChannel"),t=>fc((r=>{var n;if(!r.find((({feedId:t})=>t===e)))return;const s=null===(n=we(["subChannel","get",e]))||void 0===n?void 0:n.data;s&&t(s)})),fd((t=>Dc((async n=>{var s;if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;if(await ll(n),n.subChannelId!==e)return;const i=null===(s=we(["subChannel","get",e]))||void 0===s?void 0:s.data;i&&(al(n.subChannelId,i,{messagePreviewId:n.messageId}),t(n))}))),"subChannelId","subChannel"),fd((t=>xc((async n=>{"no-message-preview"!==await r.getMessagePreviewSetting(!1)&&n.subChannelId===e&&(cl(n),t(n))}))),"subChannelId","subChannel"),fd((t=>Oc((async n=>{const s=await r.getMessagePreviewSetting(!1);"no-message-preview"!==s&&n.subChannelId===e&&("message-preview-include-deleted"===s&&await cl(n),"message-preview-not-include-deleted"===s&&await Pl(n.subChannelId),t(n))}))),"subChannelId","subChannel")],{forceDispatch:!0})},getSubChannels:(e,t,r)=>{const{log:n,cache:s}=ye(),i=Date.now();n(`getSubChannels(tmpid: ${i}) > listen`),s||console.log(p);const o=new Xd(e,t),a=o.startSubscription(),l=o.getCacheKey();return a.push((()=>{Ce(l)})),()=>{n(`getSubChannels(tmpid: ${i}) > dispose`),a.forEach((e=>e()))}},markReadEngineOnLoginHandler:jl,startReading:async e=>{Nl[e]=!0,0===Fl.length&&(Fl.length>0||Fl.push(xl((()=>{Ul()}))),$l(e));try{return await(async e=>{const t=ye();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:o}=r,a=Fa(o),l=Na(n),c=Ua(s),u=t.cache&&Date.now();return t.cache&&La({userEntityMarkers:l,userFeedMarkers:c,feedMarkers:i,userMarkers:a},{cachedAt:u}),Qe("local.feedMarker.fetched",{feedMarkers:i}),Qe("local.channelMarker.fetched",{userEntityMarkers:l}),Qe("local.subChannelMarker.fetched",{userFeedMarkers:c}),Qe("local.userMarker.fetched",{userMarkers:a}),!0})(e)}catch(t){return Nl[e]=!1,!1}},stopReading:e=>(Nl[e]=!1,Fl.forEach((e=>e())),Fl=[],(async e=>{const t=ye();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:o}=r,a=Fa(o),l=Na(n),c=Ua(s),u=t.cache&&Date.now();return t.cache&&La({userEntityMarkers:l,userFeedMarkers:c,feedMarkers:i,userMarkers:a},{cachedAt:u}),Qe("local.feedMarker.fetched",{feedMarkers:i}),Qe("local.channelMarker.fetched",{userEntityMarkers:l}),Qe("local.subChannelMarker.fetched",{userFeedMarkers:c}),Qe("local.userMarker.fetched",{userMarkers:a}),!0})(e))});function Zd(e,t){return e.map((e=>{const r=t.some((t=>function(e,t){const{userId:r}=$e();return e.communityId===t.communityId&&t.userId===r}(e,t)&&"none"!==t.communityMembership));return Object.assign(Object.assign({},e),{isJoined:r})}))}const eh=e=>{var t;return null!==(t=Object.keys(o).find((t=>e.needApprovalOnPostCreation===o[t].needApprovalOnPostCreation&&e.onlyAdminCanPost===o[t].onlyAdminCanPost)))&&void 0!==t?t:a},th=e=>{const t=e.communities.map((e=>{var{needApprovalOnPostCreation:t,onlyAdminCanPost:r}=e,n=xa(e,["needApprovalOnPostCreation","onlyAdminCanPost"]);return Object.assign({postSetting:eh({needApprovalOnPostCreation:t,onlyAdminCanPost:r})},n)})),r=Oa(e.communityUsers),n=Zd(t,r);return Object.assign(Object.assign({},e),{communities:n,communityUsers:r})},rh=e=>{const{postSetting:t,storySetting:r}=e,n=xa(e,["postSetting","storySetting"]);return Object.assign(Object.assign(Object.assign({},n),t?o[t]:void 0),{allowCommentInStory:!1!==(null==r?void 0:r.enableComment)})},nh=async e=>{const t=ye();t.log("community/getCommunities",e);const{data:r}=await t.http.get("/api/v3/communities/list",{params:{communityIds:e}}),n=th(r),s=t.cache&&Date.now();return t.cache&&La(n,{cachedAt:s}),{data:n.communities,cachedAt:s}};nh.locally=e=>{var t;const r=ye();if(r.log("community/getCommunities.locally",e),!r.cache)return;const n=e.map((e=>we(["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 sh=async e=>{const t=ye();t.log("community/getCommunity",e);const{data:r}=await t.http.get(`/api/v3/communities/${e}`),n=th(r),s=t.cache&&Date.now();t.cache&&La(n,{cachedAt:s});const{communities:i}=n;return{data:i.find((t=>t.communityId===e)),cachedAt:s}};sh.locally=e=>{const t=ye();if(t.log("community/getCommunity.locally",e),!t.cache)return;const r=we(["community","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const ih=async e=>{const t=ye();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=th(n),{communities:i}=s,o=t.cache&&Date.now();if(t.cache){La(s,{cachedAt:o});Ee(["community","top-trending",{params:{options:{limit:r}}}],{communities:i.map(ce("community"))})}return{data:i,cachedAt:o}};ih.locally=e=>{var t,r;const n=ye();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:o,cachedAt:a}=null!==(t=we(i))&&void 0!==t?t:{};if(!(null==o?void 0:o.communities.length))return;const l=o.communities.map((e=>we(["community","get",e]))).filter(Boolean).map((({data:e})=>e));return l.length===(null===(r=null==o?void 0:o.communities)||void 0===r?void 0:r.length)?{data:l,cachedAt:a}:void 0};const oh=(e,t)=>{const r=ye();return Ye(r,e,e,(e=>{const n=th(e);if(r.cache){La(n);const e=we(["community","get",n.communities[0].communityId]);t(e.data)}else t(n.communities[0])}))},ah=e=>oh("community.created",e),lh=e=>oh("community.updated",e),ch=e=>oh("community.deleted",e);function uh(e,t,r){return!!e.permissions.some((e=>e===r))||t.users.find((t=>t.userId===e.userId)).permissions.some((e=>e===r))}function dh(e,t){return"community.joined"===e||"community.left"===e?t.communityUsers[0]:"community.userRemoved"===e?t.communityUsers.filter((e=>"none"===e.communityMembership))[0]:"community.userBanned"===e?t.communityUsers.filter((e=>"banned"===e.communityMembership))[0]:"community.userUnbanned"===e?t.communityUsers.filter((e=>!uh(e,t,"BAN_COMMUNITY_USER")))[0]:t.communityUsers.filter((e=>!uh(e,t,"ADD_COMMUNITY_USER")))[0]}const hh=(e,t)=>{const r=ye();return Ye(r,e,e,(n=>{const s=th(n),{communities:i,communityUsers:o}=s,a=Zd(i,o);if(s.communities=a,r.cache){La(s);const r=we(["community","get",s.communities[0].communityId]),n=we(["communityUsers","get",ce("communityUsers")(dh(e,s))]);t(r.data,n.data)}else t(s.communities[0],dh(e,s))}))},fh=e=>hh("community.userAdded",e),ph=e=>hh("community.userRemoved",e),gh=e=>hh("community.userBanned",e),mh=e=>hh("community.userChanged",e),yh=e=>hh("community.userUnbanned",e),vh=e=>hh("community.roleAdded",e),bh=e=>hh("community.roleRemoved",e),wh=e=>hh("community.joined",e),Eh=e=>hh("community.left",e),Th=async e=>{const t=ye();t.log("channel/queryCommunities",e);const r=null!=e?e:{},{page:n,limit:s=10}=r,i=xa(r,["page","limit"]),o=null!=i?i:{},{displayName:a,membership:l,includeDeleted:c}=o,u=xa(o,["displayName","membership","includeDeleted"]),d=n?{token:n}:s?{limit:s}:void 0,{data:h}=await t.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},u),{isDeleted:vl(c),keyword:a,filter:l,options:d})}),{paging:f}=h,p=xa(h,["paging"]),g=th(p),{communities:m}=g,y=t.cache&&Date.now();if(t.cache){La(g,{cachedAt:y});const e=["community","query",Object.assign(Object.assign({},i),{options:d})];Ee(e,{communities:m.map(ce("community")),paging:f})}return{data:m,cachedAt:y,paging:f}},Sh=async e=>{const t=ye();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=th(n),{communities:i}=s,o=t.cache&&Date.now();return t.cache&&La(s,{cachedAt:o}),{data:i,cachedAt:o}},Ch=(e,t,r)=>{let n=e;n=ke(n,"displayName",t.displayName),t.includeDeleted||(n=ke(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=Le(n,t.membership,r));const s=t.sortBy||"lastCreated";return"lastCreated"!==s&&"firstCreated"!==s||(n=n.sort("lastCreated"===s?Fe:Me)),"displayName"===s&&(n=n.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Oe)),n},kh=async e=>{const t=ye();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=th(n),{communities:i}=s,o=t.cache&&Date.now();return t.cache&&La(s,{cachedAt:o}),{data:i,cachedAt:o}};var Ah=Object.freeze({__proto__:null,addRoles:async(e,t,r)=>{const n=ye();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=Pa(s,"communityUsers");n.cache&&La(i);const{communityUsers:o}=i;return!!o.find((r=>r.communityId===e&&t.some((e=>r.roles.includes(e)))))},removeRoles:async(e,t,r)=>{const n=ye();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=Pa(s,"communityUsers");n.cache&&La(i);const{communityUsers:o}=i;return!!o.find((r=>r.communityId===e&&!t.some((e=>r.roles.includes(e)))))},banMembers:async(e,t)=>{const r=ye();r.log("community/banMembers",{userIds:t,communityId:e});const{data:n}=await r.http.put(`/api/v3/communities/${e}/users/ban`,{userIds:t}),s=Pa(n,"communityUsers"),i=r.cache&&Date.now();r.cache&&La(s,{cachedAt:i});const{communityUsers:o}=s;return{data:o.filter((e=>t.includes(e.userId))),cachedAt:i}},unbanMembers:async(e,t)=>{const r=ye();r.log("community/unbanMembers",{userIds:t,communityId:e});const{data:n}=await r.http.put(`/api/v3/communities/${e}/users/unban`,{userIds:t}),s=Pa(n,"communityUsers"),i=r.cache&&Date.now();r.cache&&La(s,{cachedAt:i});const{communityUsers:o}=s;return{data:o.filter((e=>t.includes(e.userId))),cachedAt:i}}});const _h=async e=>{const t=ye();t.log("community/queryCommunityMembers",e);const r=null!=e?e:{},{page:n,limit:s}=r,i=xa(r,["page","limit"]),o=n?{token:n}:s?{limit:s}:void 0,{data:a}=await t.http.get(`/api/v3/communities/${i.communityId}/users`,{params:Object.assign(Object.assign({},i),{options:o})}),{paging:l}=a,c=xa(a,["paging"]),u=Pa(c,"communityUsers"),{communityUsers:d}=u,h=t.cache&&Date.now();if(t.cache){La(u,{cachedAt:h});const e=["communityUsers","query",Object.assign(Object.assign({},i),{options:o})];Ee(e,{communityUsers:d.map((({communityId:e,userId:t})=>ce("communityUsers")({communityId:e,userId:t}))),paging:l})}return{data:d,cachedAt:h,paging:l}};_h.locally=e=>{var t,r;const n=ye();if(n.log("community/queryCommunityMembers",e),!n.cache)return;const s=null!=e?e:{},{page:i,limit:o}=s,a=xa(s,["page","limit"]),l=i?{token:i}:o?{limit:o}:void 0,c=["communityUsers","query",Object.assign(Object.assign({},a),{options:l})],{data:u,cachedAt:d}=null!==(t=we(c))&&void 0!==t?t:{};if(!(null==u?void 0:u.communityUsers.length))return;const h=u.communityUsers.map((e=>we(["communityUsers","get",e]))).filter(Boolean).map((({data:e})=>e)),{paging:f}=u;return h.length===(null===(r=null==u?void 0:u.communityUsers)||void 0===r?void 0:r.length)?{data:h,cachedAt:d,paging:f}:void 0};const Ih=(e,t)=>{let r=_e(e,"roles",t.roles);t.memberships&&(r=r.filter((({communityMembership:e})=>t.memberships.includes(e)))),t.search&&(r=xe(r,t.search));const n=t.sortBy?t.sortBy:"lastCreated";return r=r.sort("lastCreated"===n?Fe:Me),r};var Rh=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const r=ye();r.log("community/moderation/addMembers",e,t);const{data:n}=await r.http.post(`/api/v3/communities/${e}/users`,{communityId:e,userIds:t});Qe("community.userAdded",n);const s=Pa(n,"communityUsers");r.cache&&La(s);const{communityUsers:i}=s;return!!i.find((t=>t.communityId===e&&"member"===t.communityMembership))},removeMembers:async(e,t)=>{const r=ye();r.log("community/moderation/removeMembers",e,t);const{data:n}=await r.http.delete(`/api/v3/communities/${e}/users`,{data:{communityId:e,userIds:t}});Qe("community.userRemoved",n);const s=Pa(n,"communityUsers");r.cache&&La(s);const{communityUsers:i}=s;return!!i.find((t=>t.communityId===e&&"member"!==t.communityMembership))},applyFilter:Ih,getMembers:(e,t,r)=>{const{log:n,cache:s}=ye();s||console.log(p);const i=Date.now();n(`getMembers(tmpid: ${i}) > listen`);const{limit:o}=e,a=xa(e,["limit"]),l=null!=o?o:h,{policy:c=f}=null!=r?r:{},u=[],d=["communityUsers","collection",a],g=["communityUsers","collection",{communityId:e.communityId}],m=(r,n=!1)=>{var s,i;const o=null!==(s=r.data.map((e=>we(["communityUsers","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==s?s:[];t({onNextPage:v,data:n?Ih(o,e):o,hasNextPage:!!(null===(i=r.params)||void 0===i?void 0:i.page),loading:r.loading,error:r.error})},y=t=>(t,r)=>{var n;if(e.communityId!==r.communityId)return;const s=null===(n=we(d))||void 0===n?void 0:n.data;if(!s)return;const i=ce("communityUsers")({communityId:e.communityId,userId:r.userId});s.data=[...new Set([i,...s.data])],Ee(d,s),Ee(g,s),m(s,!0)},v=(e=!1)=>{var t,r;const n=null===(t=we(d))||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=se(_h,Object.assign(Object.assign({},a),{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(ce("communityUsers"))])]),Ee(d,i),Ee(g,i),m(i)}),ie(c))};return u.push(Eh(y()),wh(y()),gh(y()),yh(y()),mh(y()),vh(y()),bh(y())),v(!0),()=>{n(`getMembers(tmpid: ${i}) > dispose`),u.forEach((e=>e()))}},onCommunityUserAdded:fh,onCommunityUserRemoved:ph,onCommunityUserBanned:gh,onCommunityUserChanged:mh,onCommunityUserUnbanned:yh,onCommunityUserRoleAdded:vh,onCommunityUserRoleRemoved:bh,onCommunityJoined:wh,onCommunityLeft:Eh}),Lh=Object.freeze({__proto__:null,Moderation:Ah,Membership:Rh,getCommunityByIds:nh,createCommunity:async e=>{const t=ye();t.log("user/createCommunity",e);const{data:r}=await t.http.post("/api/v3/communities/",rh(e));Qe("community.created",r);const n=th(r),s=t.cache&&Date.now();t.cache&&La(n,{cachedAt:s});const{communities:i}=n;return{data:i[0],cachedAt:s}},updateCommunity:async(e,t)=>{const r=ye();r.log("community/updateCommunity",e,t);const{data:n}=await r.http.put(`/api/v3/communities/${e}`,rh(t));Qe("community.updated",n);const s=th(n),i=r.cache&&Date.now();r.cache&&La(s,{cachedAt:i});const{communities:o}=s;return{data:o.find((t=>t.communityId===e)),cachedAt:i}},deleteCommunity:async e=>{const t=ye();t.log("community/deleteCommunity",e),await t.http.delete(`/api/v3/communities/${e}`);const r=await sh(e);return Qe("community.deleted",{communities:[r.data],categories:[],communityUsers:[],feeds:[],files:[],users:[]}),r.data},joinCommunity:async e=>{const t=ye();t.log("community/joinCommunity",e);const{data:r}=await t.http.post(`/api/v3/communities/${e}/join`);Qe("community.joined",r);const n=th(r),s=t.cache&&Date.now();t.cache&&La(n,{cachedAt:s});const{communityUsers:i}=n;return!!i.find((t=>t.communityId===e&&"member"===t.communityMembership))},leaveCommunity:async e=>{const t=ye();t.log("community/leaveCommunity",e);const{data:r}=await t.http.delete(`/api/v3/communities/${e}/leave`);Qe("community.left",r);const n=th(r),s=t.cache&&Date.now();t.cache&&La(n,{cachedAt:s});const{communityUsers:i}=n;return!!i.find((t=>t.communityId===e&&"member"!==t.communityMembership))},getTopTrendingCommunities:ih,onCommunityCreated:ah,onCommunityUpdated:lh,onCommunityDeleted:ch,observeCommunity:(e,t)=>{const{log:r}=ye(),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)},o=[];return o.push(lh((e=>i({data:e,loading:!1,origin:"event"},"onUpdate"))),ch((e=>i({data:e,loading:!1,origin:"event"},"onDelete"))),wh((e=>i({data:e,loading:!1,origin:"event"},"onJoin"))),Eh((e=>i({data:e,loading:!1,origin:"event"},"onLeft"))),fh((e=>i({data:e,loading:!1,origin:"event"},"onUserAdded"))),ph((e=>i({data:e,loading:!1,origin:"event"},"onUserRemoved"))),gh((e=>i({data:e,loading:!1,origin:"event"},"onUserBanned"))),yh((e=>i({data:e,loading:!1,origin:"event"},"onUserUnbanned")))),oe(se(sh,e),(e=>(e.data||e.error)&&s(e,"onFetch"))),()=>{r(`observeCommunity(tmpid: ${n}) > dispose`),o.forEach((e=>e()))}},getCommunities:(e,t,r)=>{const{log:n,cache:s,userId:i}=ye();s||console.log(p);const o=Date.now();n(`getCommunities(tmpid: ${o}) > listen`);const{limit:a}=e,l=xa(e,["limit"]),c=null!=a?a:h,{policy:u=f}=null!=r?r:{},d=[],g=["community","collection",l],m=r=>{var n,s;let o=null!==(n=r.data.map((e=>we(["community","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];o=Ae(o,"displayName",e.displayName),e.includeDeleted||(o=ke(o,"isDeleted",!1)),e.categoryId&&(o=o.filter((t=>{var r;return null===(r=t.categoryIds)||void 0===r?void 0:r.includes(e.categoryId)}))),e.tags&&(o=o.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&&(o=Le(o,e.membership,i));const a=e.sortBy||"lastCreated";"lastCreated"!==a&&"firstCreated"!==a||(o=o.sort("lastCreated"===a?Fe:Me)),"displayName"===a&&(o=o.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Oe)),t({onNextPage:b,data:o,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=we(g))||void 0===t?void 0:t.data;r&&(r.data=[...new Set([e.communityId,...r.data])],Ee(g,r),m(r))},b=(e=!1)=>{var t,r;const n=null===(t=we(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=se(Th,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 o={loading:n,error:r,params:{page:null==i?void 0:i.next},data:s};t&&(o.data=e?t.map(ce("community")):[...new Set([...s,...t.map(ce("community"))])]),Ee(g,o),m(o)}),ie(u,v))};return d.push(ah(y()),ch(y()),lh(y()),wh(y()),Eh(y()),mh(y())),b(!0),d.push((()=>Ce(g))),()=>{n(`getCommunities(tmpid: ${o}) > dispose`),d.forEach((e=>e()))}},getCommunity:(e,t)=>wc(e,t,"communityId",sh,[lh,ch,wh,Eh,gh,yh,mh]),getTrendingCommunities:(e,t,r)=>{const{log:n,cache:s,userId:i}=ye();s||console.log(p);const o=Date.now();n(`getTrendingCommunities(tmpid: ${o}) > listen`);const{limit:a}=e,l=null!=a?a:h,{policy:c=f}=null!=r?r:{},u=[],d=["community","top-trending",{params:{options:{limit:l}}}],g=(r,n=!1)=>{var s,o;const a=null!==(s=r.data.map((e=>we(["community","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==s?s:[];t({onNextPage:m,data:n?Ch(a,e,i):a,hasNextPage:!!(null===(o=r.params)||void 0===o?void 0:o.page),loading:r.loading,error:r.error})},m=(t=!1)=>{var r,n;const s=null===(r=we(d))||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 o=se(Sh,e);oe(o,(({data:t,error:r,loading:n})=>{const s={loading:n,error:r,params:e,data:i};t&&(s.data=[...new Set([...i,...t.map(ce("community"))])]),Ee(d,s),g(s)}),ie(c,v))};return u.push(mh((e=>{var t;const r=null===(t=we(d))||void 0===t?void 0:t.data;r&&(r.data=[...new Set([e.communityId,...r.data])],Ee(d,r),g(r))}))),m(!0),u.push((()=>Ce(d))),()=>{n(`getTrendingCommunities(tmpid: ${o}) > dispose`),u.forEach((e=>e()))}},getRecommendedCommunities:(e,t,r)=>{const{log:n,cache:s,userId:i}=ye();s||console.log(p);const o=Date.now();n(`getRecommendedCommunities(tmpid: ${o}) > listen`);const{limit:a}=e;xa(e,["limit"]);const l=null!=a?a:h,{policy:c=f}=null!=r?r:{},u=[],d=["community","recommended",{params:{options:{limit:l}}}],g=(r,n=!1)=>{var s,o;const a=null!==(s=r.data.map((e=>we(["community","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==s?s:[];t({onNextPage:m,data:n?Ch(a,e,i):a,hasNextPage:!!(null===(o=r.params)||void 0===o?void 0:o.page),loading:r.loading,error:r.error})},m=(t=!1)=>{var r,n;const s=null===(r=we(d))||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 o=se(kh,e);oe(o,(({data:t,error:r,loading:n})=>{const s={loading:n,error:r,params:e,data:i};t&&(s.data=[...new Set([...i,...t.map(ce("community"))])]),Ee(d,s),g(s)}),ie(c,v))};return u.push(mh((e=>{var t;const r=null===(t=we(d))||void 0===t?void 0:t.data;r&&(r.data=[...new Set([e.communityId,...r.data])],Ee(d,r),g(r))}))),m(!0),u.push((()=>Ce(d))),()=>{n(`getRecommendedCommunities(tmpid: ${o}) > dispose`),u.forEach((e=>e()))}}});const Dh=async e=>{const t=ye();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&&La(r,{cachedAt:n});const{categories:s}=r;return{data:el.category(s.find((t=>t.categoryId===e))),cachedAt:n}};Dh.locally=e=>{const t=ye();if(t.log("category/getCategory.locally",e),!t.cache)return;const r=we(["category","get",e]);return r?{data:el.category(r.data),cachedAt:r.cachedAt}:void 0};const xh=async e=>{const t=ye();t.log("category/queryCategories",e);const r=null!=e?e:{},{page:n,limit:s,includeDeleted:i}=r,o=xa(r,["page","limit","includeDeleted"]),a=n?{token:n}:s?{limit:s}:void 0,{data:l}=await t.http.get("/api/v3/community-categories",{params:Object.assign(Object.assign({},o),{isDeleted:vl(i),options:a})}),{paging:c}=l,u=xa(l,["paging"]),{categories:d}=u,h=t.cache&&Date.now();if(t.cache){La(u,{cachedAt:h});const e=["category","query",Object.assign(Object.assign({},o),{includeDeleted:i,options:a})];Ee(e,{categories:d.map(ce("category")),paging:c})}return{data:d,cachedAt:h,paging:c}};xh.locally=e=>{var t,r;const n=ye();if(n.log("category/queryCategories.locally",e),!n.cache)return;const s=null!=e?e:{},{page:i,limit:o=10}=s,a=xa(s,["page","limit"]),l=i?{token:i}:o?{limit:o}:void 0,c=["category","query",Object.assign(Object.assign({},a),{options:l})],{data:u,cachedAt:d}=null!==(t=we(c))&&void 0!==t?t:{};if(!(null==u?void 0:u.categories.length))return;const h=u.categories.map((e=>we(["category","get",e]))).filter(Boolean).map((({data:e})=>e)),{paging:f}=u;return h.length===(null===(r=null==u?void 0:u.categories)||void 0===r?void 0:r.length)?{data:h,cachedAt:d,paging:f}:void 0};var Oh=Object.freeze({__proto__:null,getCategory:Dh,getCategories:(e,t,r)=>{const{log:n,cache:s}=ye();s||console.log(p);const i=Date.now();n(`getCategories(tmpid: ${i}) > listen`);const{limit:o}=e,a=xa(e,["limit"]),l=null!=o?o:h,{policy:c=f}=null!=r?r:{},u=[],d=["category","collection",{}],g=(r=!1)=>{var n,s;const i=null===(n=we(d))||void 0===n?void 0:n.data,o=null!==(s=null==i?void 0:i.data)&&void 0!==s?s:[];if(!r&&o.length>0&&!(null==i?void 0:i.params.page))return;const u=se(xh,Object.assign(Object.assign({},a),{limit:r?l:void 0,page:r||null==i?void 0:i.params.page}));oe(u,(({data:r,error:n,loading:s,paging:i})=>{const a={loading:s,error:n,params:{page:null==i?void 0:i.next},data:o};r&&(a.data=[...new Set([...o,...r.map(ce("category"))])]),Ee(d,a),(r=>{var n,s;let i=null!==(n=r.data.map((e=>we(["category","get",e]))).filter(Boolean).map((({data:e})=>el.category(e))))&&void 0!==n?n:[];switch(e.includeDeleted||(i=ke(i,"isDeleted",!1)),e.sortBy){case"firstCreated":i=i.sort(Me);break;case"lastCreated":i=i.sort(Fe);break;default:i=i.sort(Pe)}t({onNextPage:g,data:i,hasNextPage:!!(null===(s=r.params)||void 0===s?void 0:s.page),loading:r.loading,error:r.error})})(a)}),ie(c))};return u.push((()=>{})),g(!0),()=>{n(`getCategories(tmpid: ${i}) > dispose`),u.forEach((e=>e()))}}});const Ph=async e=>{const t=ye();t.log("feed/queryGlobalFeed",e);const r=null!=e?e:{},{useCustomRanking:n,page:s,queryToken:i}=r,o=xa(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 a=i?{token:i}:s?{token:Q(s,"skiplimit")}:void 0,{data:l}=await t.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},o),{options:a})}),{paging:c}=l,u=xa(l,["paging"]),d=Pa(u,"communityUsers"),{posts:h}=d,f=t.cache&&Date.now();if(t.cache){La(d);const e=["globalFeed","query",Object.assign(Object.assign({},o),{options:Object.assign({},s)})];Ee(e,{posts:h.map(ce("post")),paging:c})}const p=X(c.next),g=X(c.previous);return{data:h.map(el.post),cachedAt:f,prevPage:g,nextPage:p,paging:c}};Ph.locally=e=>{var t,r;const n=ye();if(n.log("post/queryGlobalFeed.locally",e),!n.cache)return;const s=null!=e?e:{},{page:i}=s,o=xa(s,["page"]),a=["globalFeed","query",Object.assign(Object.assign({},o),{options:Object.assign({},i)})],{data:l,cachedAt:c}=null!==(t=we(a))&&void 0!==t?t:{};if(!(null==l?void 0:l.posts.length))return;const u=l.posts.map((e=>we(["post","get",e]))).filter(Boolean).map((({data:e})=>e)).map(el.post),{paging:d}=l,h=X(null==l?void 0:l.paging.previous),f=X(null==l?void 0:l.paging.next);return u.length===(null===(r=null==l?void 0:l.posts)||void 0===r?void 0:r.length)?{data:u,cachedAt:c,prevPage:h,nextPage:f,paging:d}:void 0};const Mh=async e=>{const t=ye();t.log("feed/getCustomRankingGlobalFeed",e);const r=null!=e?e:{},{page:n,queryToken:s,limit:i}=r,o=xa(r,["page","queryToken","limit"]),a=s?{token:s}:n?{token:Q(n,"skiplimit")}:void 0,{data:l}=await t.http.get("/api/v5/me/global-feeds",{params:Object.assign(Object.assign({},o),{limit:s?void 0:i,options:a})}),{paging:c}=l,u=xa(l,["paging"]),d=Pa(u,"communityUsers"),{posts:h}=d,f=t.cache&&Date.now();if(t.cache){La(d);const e=["customGlobalFeed","query",Object.assign(Object.assign({},o),{options:Object.assign({},n)})];Ee(e,{posts:h.map(ce("post")),paging:c})}const p=X(c.next),g=X(c.previous);return{data:h.map(el.post),cachedAt:f,prevPage:g,nextPage:p,paging:c}};Mh.locally=e=>{var t,r;const n=ye();if(n.log("post/getCustomRankingGlobalFeed.locally",e),!n.cache)return;const s=null!=e?e:{},{page:i}=s,o=xa(s,["page"]),a=["customGlobalFeed","query",Object.assign(Object.assign({},o),{options:Object.assign({},i)})],{data:l,cachedAt:c}=null!==(t=we(a))&&void 0!==t?t:{};if(!(null==l?void 0:l.posts.length))return;const u=l.posts.map((e=>we(["post","get",e]))).filter(Boolean).map((({data:e})=>e)),d=X(null==l?void 0:l.paging.previous),h=X(null==l?void 0:l.paging.next),{paging:f}=l;return u.length===(null===(r=null==l?void 0:l.posts)||void 0===r?void 0:r.length)?{data:u.map(el.post),cachedAt:c,prevPage:d,nextPage:h,paging:f}:void 0};var Fh=Object.freeze({__proto__:null,queryGlobalFeed:Ph,getCustomRankingGlobalFeed:Mh});const Nh=async e=>{const t=ye();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=>{S(null==t?void 0:t.code)&&Da("post",e)})),t}const s=Pa(n,"communityUsers"),i=t.cache&&Date.now();return t.cache&&La(s,{cachedAt:i}),{data:s.posts.map(el.post),cachedAt:i}};Nh.locally=e=>{var t;const r=ye();if(r.log("post/getPostByIds.locally",e),!r.cache)return;const n=e.map((e=>we(["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(el.post),cachedAt:i.cachedAt}};const Uh=async(e,t=!1)=>{var r;const n=ye(),s=await Uu(e);if(await n.http.delete(`/api/v4/posts/${encodeURIComponent(e)}`,{params:{postId:e,permanent:t}}),"community"===s.data.targetType){const e=await sh(s.data.targetId),t=(null!==(r=be(["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));Qe("community.updated",{communities:[e.data],categories:[],communityUsers:t,feeds:[],files:[],users:[]})}const i=Object.assign(Object.assign({},s.data),{isDeleted:!0});return Qe("post.deleted",{posts:[i],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[]}),t?setTimeout((()=>{Da("post",e)}),0):Se(["post","get",e],{isDeleted:!0}),el.post(i)},Bh=async e=>{const t=ye();t.log("post/queryPosts",e);const{page:r,limit:n=10,includeDeleted:s}=e,i=xa(e,["page","limit","includeDeleted"]),{dataTypes:o,matchingOnlyParentPost:a}=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:vl(s),matchingOnlyParentPost:null!=a?a:!(null==o?void 0:o.length),options:l})}),{paging:u}=c,d=xa(c,["paging"]),h=Pa(d,"communityUsers"),{posts:f}=d,p=t.cache&&Date.now();if(t.cache){La(h,{cachedAt:p});const e=["post","query",Object.assign(Object.assign({},i),{options:l})];Ee(e,{posts:f.map(ce("post")),paging:u})}return{data:f.map(el.post),cachedAt:p,paging:u}};var jh=Object.freeze({__proto__:null,getPostByIds:Nh,createPost:async e=>{const t=ye();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);Qe("post.created",r);const n=Pa(r,"communityUsers"),s=t.cache&&Date.now();t.cache&&La(n,{cachedAt:s});const{posts:i}=n;return{data:el.post(i[0]),cachedAt:s}},updatePost:async(e,t)=>{const r=ye();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=Pa(n,"communityUsers"),i=r.cache&&Date.now();r.cache&&La(s,{cachedAt:i}),Qe("post.updated",s);const{posts:o}=s;return{data:el.post(o.find((t=>t.postId===e))),cachedAt:i}},editPost:async(e,t)=>{const r=ye();r.log("user/editPost",t);const{data:n}=await r.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,t),s=Pa(n,"communityUsers"),i=r.cache&&Date.now();r.cache&&La(s,{cachedAt:i}),Qe("post.updated",s);const{posts:o}=s;return{data:el.post(o.find((t=>t.postId===e))),cachedAt:i}},deletePost:Uh,softDeletePost:async e=>{ye().log("post/softDeletePost",e);const t=await Uh(e,!1);return el.post(t)},hardDeletePost:async e=>{ye().log("post/hardDeletePost",e);const t=await Uh(e,!0);return el.post(t)},approvePost:async e=>{const t=ye();t.log("post/approvePost",e);const{data:r}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/approve`);Qe("post.approved",r),"community"===r.posts[0].targetType&&Qe("community.updated",r);const n=Pa(r,"communityUsers"),s=t.cache&&Date.now();return t.cache&&La(n,{cachedAt:s}),{data:el.post(n.posts.find((t=>t.postId===e))),cachedAt:s}},declinePost:async e=>{const t=ye();t.log("post/declinePost",e);const{data:r}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/decline`);"community"===r.posts[0].targetType&&Qe("community.updated",r),Qe("post.declined",r);const n=Pa(r,"communityUsers"),s=t.cache&&Date.now();return t.cache&&La(n,{cachedAt:s}),{data:el.post(r.posts.find((t=>t.postId===e))),cachedAt:s}},flagPost:async e=>{const t=ye();t.log("post/flagPost",e);const{data:r}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/flag`);return t.cache&&La(Pa(r,"communityUsers")),Qe("post.flagged",r),!!r},unflagPost:async e=>{const t=ye();t.log("post/unflagPost",e);const{data:r}=await t.http.delete(`/api/v3/posts/${encodeURIComponent(e)}/unflag`);return t.cache&&La(Pa(r,"communityUsers")),Qe("post.unflagged",r),!!r},isPostFlaggedByMe:async e=>{const t=ye();t.log("post/isPostFlaggedByMe",e);const{data:{result:r}}=await t.http.get(`/api/v3/posts/${e}/isflagbyme`);return r},onPostCreated:Gu,onPostUpdated:Hu,onPostDeleted:Vu,onPostApproved:zu,onPostDeclined:Wu,onPostFlagged:Yu,onPostUnflagged:Qu,onPostReactionAdded:Xu,onPostReactionRemoved:Ju,observePosts:(e,t)=>{const{log:r}=ye(),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(el.post(r));null===(s=t.onEvent)||void 0===s||s.call(t,n,el.post(r)),null===(i=t[n])||void 0===i||i.call(t,el.post(r))}};return s.push(Gu((e=>i(e,"onCreate"))),Hu((e=>i(e,"onUpdate"))),Vu((e=>i(e,"onDelete"))),zu((e=>i(e,"onApproved"))),Wu((e=>i(e,"onDeclined"))),Yu((e=>i(e,"onFlagged"))),Qu((e=>i(e,"onUnflagged"))),Xu((e=>i(e,"onReactionAdded"))),Ju((e=>i(e,"onReactionRemoved")))),()=>{r(`observePosts(tmpid: ${n}) > dispose`),s.forEach((e=>e()))}},observePost:(e,t,r="cache_then_server")=>{const{log:n}=ye(),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)},o=(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&&el.post(t.data)}),r)},a=[];return a.push(Hu((e=>o({data:e,loading:!1,origin:"event"},"onUpdate"))),Vu((e=>o({data:e,loading:!1,origin:"event"},"onDelete"))),zu((e=>o({data:e,loading:!1,origin:"event"},"onApproved"))),Wu((e=>o({data:e,loading:!1,origin:"event"},"onDeclined"))),Yu((e=>o({data:e,loading:!1,origin:"event"},"onFlagged"))),Qu((e=>o({data:e,loading:!1,origin:"event"},"onUnflagged"))),Xu((e=>o({data:e,loading:!1,origin:"event"},"onReactionAdded"))),Ju((e=>o({data:e,loading:!1,origin:"event"},"onReactionRemoved")))),oe(se(Uu,e),(e=>(e.data||e.error)&&i(Object.assign(Object.assign({},e),{data:e.data&&el.post(e.data)}),"onFetch")),ie(r)),()=>{n(`observePosts(tmpid: ${s}) > dispose`),a.forEach((e=>e()))}},getPost:(e,t)=>wc(e,t,"postId",Uu,[zu,Wu,t=>Vu((r=>{var n;let s=r;if(r.parentPostId===e&&r.isDeleted){const e=null===(n=we(["post","get",r.parentPostId]))||void 0===n?void 0:n.data;e&&(e.children=e.children.filter((e=>e!==r.postId)),Ee(["post","get",e.postId],e),s=e)}t(s)})),Yu,Xu,Ju,Qu,Hu]),getPosts:(e,t,r)=>{const{log:n,cache:s}=ye();s||console.log(p);const i=Date.now();n(`getPosts(tmpid: ${i}) > listen`);const{limit:o}=e,a=xa(e,["limit"]),l=null!=o?o:h,{policy:c=f}=null!=r?r:{},u=[],d=["post","collection",{targetId:e.targetId,targetType:e.targetType}],g=r=>{var n,s,i;let o=null!==(n=r.data.map((e=>we(["post","get",e]))).filter(Boolean).map((({data:e})=>el.post(e))))&&void 0!==n?n:[];const a=e.sortBy?e.sortBy:"lastCreated";o=o.sort("lastCreated"===a?Fe:Me),e.includeDeleted||(o=ke(o,"isDeleted",!1)),e.tags&&(o=o.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&&(o=Re(o,e.feedType)),(null===(s=e.dataTypes)||void 0===s?void 0:s.length)&&(o=De(o,e.dataTypes)),t({onNextPage:y,data:o,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=we(d))||void 0===n?void 0:n.data;if(i){if(r.parentPostId&&r.isDeleted){const t=null===(s=we(["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)),Ee(["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])],Ee(d,i),g(i)}},y=(e=!1)=>{var t,r,n;const s=null===(t=we(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 o=se(Bh,Object.assign(Object.assign({},a),{limit:e?l:void 0,page:e||null==s?void 0:s.params.page}));oe(o,(({data:t,error:r,loading:n,paging:s})=>{const o={loading:n,error:r,params:{page:null==s?void 0:s.next},data:i};t&&(o.data=e?t.map(ce("post")):[...new Set([...i,...t.map(ce("post"))])]),Ee(d,o),g(o)}),ie(c,v))};return u.push(Gu(m("onCreate")),zu(m("onApproved")),Wu(m("onDeclined")),Vu(m("onDelete")),Hu(m("onUpdate")),Yu(m("onFlagged")),Qu(m("onUnflagged")),Xu(m("onReactionAdded")),Ju(m("onReactionRemoved"))),y(!0),u.push((()=>Ce(d))),()=>{n(`getPosts(tmpid: ${i}) > dispose`),u.forEach((e=>e()))}}});const $h=async e=>{const t=ye();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=>{S(null==t?void 0:t.code)&&Da("comment",e)})),t}const s=t.cache&&Date.now();return t.cache&&La(n,{cachedAt:s}),{data:n.comments.map((e=>el.comment(e))),cachedAt:s}};$h.locally=e=>{var t;const r=ye();if(r.log("comment/getCommentByIds.locally",e),!r.cache)return;const n=e.map((e=>we(["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=>el.comment(e))),cachedAt:i.cachedAt}};const qh=async(e,t=!1)=>{const r=ye(),n=await Bu(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}),i=await Uu(n.data.referenceId);return Qe("post.updated",{posts:[i.data],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[]}),Qe("comment.deleted",{comments:[s],commentChildren:[],files:[],users:[],communityUsers:[]}),t?He((()=>Da("comment",e))):Se(["comment","get",e],{isDeleted:!0}),s},Kh=async e=>{const t=ye();let r;t.log("comment/getComment",e),Ol("comment",e);try{r=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw S(null==t?void 0:t.code)&&Da("comment",e),t}const n=t.cache&&Date.now();t.cache&&La(r,{cachedAt:n});const{comments:s}=r;return{data:s.find((t=>t.commentId===e)),cachedAt:n}};Kh.locally=e=>{const t=ye();if(t.log("comment/getComment.locally",e),!t.cache)return;const r=we(["comment","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const Gh=async e=>{const t=ye();t.log("comment/queryComments",e);const{limit:r=10,includeDeleted:n}=e,s=xa(e,["limit","includeDeleted"]),i={type:s.sortBy||e.limit?"pagination":void 0,limit:e.limit,token:e.page},{data:o}=await t.http.get("/api/v3/comments",{params:Object.assign(Object.assign({},s),{isDeleted:vl(n),options:i})}),{paging:a}=o,l=xa(o,["paging"]),{comments:c}=l,u=t.cache&&Date.now();if(t.cache){La(l,{cachedAt:u});const e=["comment","query",Object.assign(Object.assign({},s),{options:{limit:r}})];Ee(e,{comments:c.map(ce("comment")),paging:a})}return{data:c,cachedAt:u,paging:a}};var Hh=Object.freeze({__proto__:null,getCommentByIds:$h,createComment:async e=>{const t=ye();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&&La(r,{cachedAt:s}),["post","content"].includes(e.referenceType)){const t=await Uu(e.referenceId);Qe("post.updated",{posts:[t.data],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[]})}else if("story"===e.referenceType){const t=we(["story-reference",e.referenceId]);if(null==t?void 0:t.data){const e=we(["story","get",t.data]);(null==e?void 0:e.data)&&Qe("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 Qe("comment.created",r),{data:el.comment(n[0]),cachedAt:s}},updateComment:async(e,t)=>{const r=ye();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&&La(n,{cachedAt:s}),Qe("comment.updated",n);const{comments:i}=n;return{data:el.comment(i.find((t=>t.commentId===e))),cachedAt:s}},deleteComment:qh,softDeleteComment:async e=>{ye().log("comment/softDeleteComment",e);return qh(e)},hardDeleteComment:async e=>{ye().log("comment/hardDeleteComment",e);return qh(e,!0)},flagComment:async e=>{const t=ye();t.log("comment/flagComment",e);const{data:r}=await t.http.post(`/api/v3/comments/${encodeURIComponent(e)}/flag`);return t.cache&&La(r),Qe("comment.flagged",r),!!r},unflagComment:async e=>{const t=ye();t.log("comment/unflagComment",e);const{data:r}=await t.http.delete(`/api/v3/comments/${encodeURIComponent(e)}/unflag`);return t.cache&&La(r),Qe("comment.unflagged",r),!!r},isCommentFlaggedByMe:async e=>{const t=ye();t.log("comment/isCommentFlaggedByMe",e);const{data:{result:r}}=await t.http.get(`/api/v3/comments/${e}/isflagbyme`);return r},onCommentCreated:ed,onCommentUpdated:td,onCommentDeleted:rd,onCommentFlagged:nd,onCommentUnflagged:sd,onCommentReactionAdded:id,onCommentReactionRemoved:od,observeComments:(e,t)=>{const{log:r}=ye(),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(ed((e=>i(e,"onCreate"))),td((e=>i(e,"onUpdate"))),rd((e=>i(e,"onDelete"))),nd((e=>i(e,"onFlagged"))),sd((e=>i(e,"onUnflagged"))),id((e=>i(e,"onReactionAdded"))),od((e=>i(e,"onReactionRemoved")))),()=>{r(`observeComments(tmpid: ${n}) > dispose`),s.forEach((e=>e()))}},observeComment:(e,t,r="cache_then_server")=>{const{log:n}=ye(),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)},o=(t,r)=>{var n;(null===(n=t.data)||void 0===n?void 0:n.commentId)===e&&i(t,r)},a=[];return a.push(td((e=>o({data:e,loading:!1,origin:"event"},"onUpdate"))),rd((e=>o({data:e,loading:!1,origin:"event"},"onDelete"))),nd((e=>o({data:e,loading:!1,origin:"event"},"onFlagged"))),sd((e=>o({data:e,loading:!1,origin:"event"},"onUnflagged"))),id((e=>o({data:e,loading:!1,origin:"event"},"onReactionAdded"))),od((e=>o({data:e,loading:!1,origin:"event"},"onReactionRemoved")))),oe(se(Kh,e),(e=>(e.data||e.error)&&i(e,"onFetch")),ie(r)),()=>{n(`observeComment(tmpid: ${s}) > dispose`),a.forEach((e=>e()))}},getComment:(e,t)=>wc(e,t,"commentId",Kh,[rd,nd,id,od,sd,td,t=>ed((r=>{if(r.parentId!==e)return;const n=we(["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}=ye();s||console.log("For using Live Collection feature you need to enable Cache!");const i=Date.now();n(`getComments(tmpid: ${i}) > listen`);const{limit:o}=e,a=xa(e,["limit"]),{policy:l=f}=null!=r?r:{},c=[],u=["comment","collection",{referenceId:e.referenceType,referenceType:e.referenceId,parentId:(null==e?void 0:e.parentId)||""}],d=r=>{var n,s;let i=null!==(n=r.data.map((e=>we(["comment","get",e]))).filter((({data:t})=>t.parentId===(null==e?void 0:e.parentId))).filter(Boolean).map((({data:e})=>el.comment(e))))&&void 0!==n?n:[];e.includeDeleted||(i=ke(i,"isDeleted",!1));const o=e.sortBy?e.sortBy:"lastCreated";i=i.sort("lastCreated"===o?Fe:Me),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=we(u))||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))),Ee(u,s),d(s))},p=(e=!1)=>{var t,r,n;const s=null===(t=we(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 c=se(Gh,Object.assign(Object.assign({},a),{limit:o,page:e||null==s?void 0:s.params.page}));oe(c,(({data:t,error:r,loading:n,paging:s})=>{const o={loading:n,error:r,params:{page:"lastCreated"===(a.sortBy||"lastCreated")?null==s?void 0:s.next:null==s?void 0:s.previous},data:i};t&&(o.data=e?t.map(ce("comment")):[...new Set([...i,...t.map(ce("comment"))])]),Ee(u,o),d(o)}),ie(l,v))};return c.push(ed(h("onCreate")),td(h("onUpdate")),rd(h("onDelete")),nd(h("onFlagged")),sd(h("onUnflagged")),id(h("onReactionAdded")),od(h("onReactionRemoved"))),p(!0),c.push((()=>Ce(u))),()=>{n(`getComments(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}}});const Vh=async e=>{const t=ye();t.log("stream/getStream",e);const{data:r}=await t.http.get(`/api/v3/video-streaming/${e}`),n=t.cache&&Date.now();t.cache&&La(r,{cachedAt:n});const{videoStreamings:s}=r;return{data:s.find((t=>t.streamId===e)),cachedAt:n}};Vh.locally=e=>{const t=ye();if(t.log("stream/getStream",e),!t.cache)return;const r=we(["stream","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const zh=e=>{const t=ye();return Ye(t,"stream/onStreamStarted","video-streaming.didStart",(t=>{La(t),e(t.videoStreamings[0])}))},Wh=e=>{const t=ye();return Ye(t,"stream/onStreamStarted","video-streaming.didStop",(t=>{La(t),e(t.videoStreamings[0])}))},Yh=e=>{const t=ye();return Ye(t,"stream/onStreamRecorded","video-streaming.didRecord",(t=>{La(t),e(t.videoStreamings[0])}))},Qh=(e,t)=>wc(e,t,"streamId",Vh,[Yh,zh,Wh]);Qh.locally=e=>{const t=ye();if(t.log("stream/getStreamById",e),!t.cache)return;const r=we(["stream","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const Xh=async e=>{const t=ye();t.log("stream/queryStreams",e);const r=null!=e?e:{},{page:n,limit:s}=r,i=xa(r,["page","limit"]),o=n?{token:n}:s?{limit:s}:void 0,{data:a}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},i),{options:o})}),{paging:l,results:c}=a,{videoStreamings:u}=c,d=t.cache&&Date.now();return t.cache&&La(c,{cachedAt:d}),{data:u,cachedAt:d,paging:l}};var Jh=Object.freeze({__proto__:null,createStream:async e=>{const t=ye();t.log("stream/createStream",e);const{data:r}=await t.http.post("/api/v3/video-streaming",e),n=t.cache&&Date.now();t.cache&&La(r,{cachedAt:n});const{videoStreamings:s}=r;return{data:s[0],cachedAt:n}},updateStream:async(e,t)=>{const r=ye();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&&La(n,{cachedAt:s});const{videoStreamings:i}=n;return{data:i.find((t=>t.streamId===e)),cachedAt:s}},deleteStream:async e=>{const t=ye();t.log("stream/deleteStream",e);const r=await Vh(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 Se(["stream","get",e],i),s},disposeStream:async e=>{const t=ye();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&&La(r,{cachedAt:n});const{videoStreamings:s}=r;return{data:s.find((t=>t.streamId===e)),cachedAt:n}},queryStreams:async e=>{const t=ye();t.log("stream/queryStreams",e);const r=null!=e?e:{},{page:n}=r,s=xa(r,["page"]),{data:i}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},s),{options:{token:Q(n,"skiplimit")}})}),{paging:o,results:a}=i,{videoStreamings:l}=a,c=t.cache&&Date.now();t.cache&&La(a,{cachedAt:c});const u=X(o.next);return{data:l,cachedAt:c,prevPage:X(o.previous),nextPage:u}},getStream:Vh,onStreamStarted:zh,onStreamStopped:Wh,onStreamRecorded:Yh,getStreamById:Qh,getStreams:(e,t,r)=>{const{log:n,cache:s}=ye();s||console.log(p);const i=Date.now();n(`getStreams(tmpid: ${i}) > listen`);const{limit:o}=e,a=xa(e,["limit"]),l=null!=o?o:h,{policy:c=f}=null!=r?r:{},u=[],d=["streams","collection",e],g=t=>{let r=ke(t,"isDeleted",e.isDeleted);return r=r.sort("lastCreated"===e.sortBy?Fe:Me),r},m=(e,r=!1)=>{var n,s;const i=null!==(n=e.data.map((e=>we(["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=we(d))||void 0===t?void 0:t.data;r&&(r.data=[...new Set([e.streamId,...r.data])],Ee(d,r),m(r,!0))},v=(e=!1)=>{var t,r;const n=null===(t=we(d))||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=se(Xh,Object.assign(Object.assign({},a),{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(ce("stream"))])]),Ee(d,i),m(i)}),ie(c))};return u.push(Yh(y()),zh(y()),Wh(y())),v(!0),()=>{n(`getStreams(tmpid: ${i}) > dispose`),u.forEach((e=>e()))}}});const Zh=async e=>{const t=ye();t.log("poll/getPoll",e);const{data:r}=await t.http.get(`/api/v3/polls/${e}`),n=t.cache&&Date.now();t.cache&&La(r,{cachedAt:n});const{polls:s}=r;return{data:s.find((t=>t.pollId===e)),cachedAt:n}};Zh.locally=e=>{const t=ye();if(t.log("poll/getPoll",e),!t.cache)return;const r=we(["poll","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const ef=e=>{const t=ye();return Ye(t,"poll/onPollUpdated","poll.updated",(r=>{t.cache&&La(r),e(r.polls[0])}))},tf=e=>{const t=ye();return Ye(t,"poll/onPollDeleted","poll.deleted",(r=>{t.cache&&La(r),e(r.polls[0])}))};var rf=Object.freeze({__proto__:null,createPoll:async e=>{const t=ye();t.log("post/createPoll",e);const{data:r}=await t.http.post("/api/v3/polls",e),n=t.cache&&Date.now();t.cache&&La(r,{cachedAt:n});const{polls:s}=r;return{data:s[0],cachedAt:n}},closePoll:async e=>{const t=ye();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&&La(r,{cachedAt:n}),Qe("poll.updated",r);const{polls:s}=r;return{data:s.find((t=>t.pollId===e)),cachedAt:n}},deletePoll:async e=>{const t=ye();t.log("poll/deletePoll",e);const r=await Zh(e),{data:n}=await t.http.delete(`/api/v3/polls/${e}`),{success:s}=n,i=Object.assign(Object.assign({},r.data),{isDeleted:!0});return Se(["poll","get",e],i),Qe("poll.deleted",{polls:[i],users:[]}),s},votePoll:async(e,t)=>{const r=ye();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&&La(n,{cachedAt:s});const{polls:i}=n;return Qe("poll.updated",n),{data:i.find((t=>t.pollId===e)),cachedAt:s}},onPollUpdated:ef,onPollDeleted:tf,observePoll:(e,t,r="cache_then_server")=>{const{log:n}=ye(),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)},o=(t,r)=>{var n;(null===(n=t.data)||void 0===n?void 0:n.pollId)===e&&i(t,r)},a=[];return a.push(ef((e=>o({data:e,loading:!1,origin:"event"},"onUpdate"))),tf((e=>o({data:e,loading:!1,origin:"event"},"onDelete")))),oe(se(Zh,e),(e=>(e.data||e.error)&&i(e,"onFetch")),ie(r)),()=>{n(`observePoll(tmpid: ${s}) > dispose`),a.forEach((e=>e()))}},getPoll:(e,t)=>wc(e,t,"pollId",Zh,[ef,tf])});function nf(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var sf={exports:{}};!function(e,t){var r,n,s,i,o;r=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,n=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,i=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(e,t,r){if(r=r||{},e=e.trim(),!(t=t.trim())){if(!r.alwaysNormalize)return e;var s=o.parseURL(e);if(!s)throw new Error("Error trying to parse base URL.");return s.path=o.normalizePath(s.path),o.buildURLFromParts(s)}var i=o.parseURL(t);if(!i)throw new Error("Error trying to parse relative URL.");if(i.scheme)return r.alwaysNormalize?(i.path=o.normalizePath(i.path),o.buildURLFromParts(i)):t;var a=o.parseURL(e);if(!a)throw new Error("Error trying to parse base URL.");if(!a.netLoc&&a.path&&"/"!==a.path[0]){var l=n.exec(a.path);a.netLoc=l[1],a.path=l[2]}a.netLoc&&!a.path&&(a.path="/");var c={scheme:a.scheme,netLoc:i.netLoc,path:null,params:i.params,query:i.query,fragment:i.fragment};if(!i.netLoc&&(c.netLoc=a.netLoc,"/"!==i.path[0]))if(i.path){var u=a.path,d=u.substring(0,u.lastIndexOf("/")+1)+i.path;c.path=o.normalizePath(d)}else c.path=a.path,i.params||(c.params=a.params,i.query||(c.query=a.query));return null===c.path&&(c.path=r.alwaysNormalize?o.normalizePath(i.path):i.path),o.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=o}(sf);var of=sf.exports;function af(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 lf(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?af(Object(r),!0).forEach((function(t){cf(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):af(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function cf(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 uf(){return uf=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},uf.apply(this,arguments)}const df=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)};let hf=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}({}),ff=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}({}),pf=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 gf=function(){},mf={trace:gf,debug:gf,log:gf,warn:gf,info:gf,error:gf};let yf=mf;function vf(e,...t){t.forEach((function(t){yf[t]=e[t]?e[t].bind(e):function(e){const t=self.console[e];return t?t.bind(self.console,`[${e}] >`):gf}(t)}))}const bf=yf,wf=/^(\d+)x(\d+)$/,Ef=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Tf{constructor(e){"string"==typeof e&&(e=Tf.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=wf.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(Ef.lastIndex=0;null!==(t=Ef.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 Sf(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e}class Cf{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]){bf.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=uf(new Tf({}),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"]);df(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(df(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&&df(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class kf{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 Af="audio",_f="video",If="audiovideo";class Rf{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[Af]:null,[_f]:null,[If]: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=of.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class Lf extends Rf{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 kf,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(!df(this.programDateTime))return null;const e=df(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:o}=this,a=o[e];a?(a.startPTS=Math.min(a.startPTS,t),a.endPTS=Math.max(a.endPTS,r),a.startDTS=Math.min(a.startDTS,n),a.endDTS=Math.max(a.endDTS,s)):o[e]={startPTS:t,endPTS:r,startDTS:n,endDTS:s,partial:i}}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[Af]=null,e[_f]=null,e[If]=null}}class Df extends Rf{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 kf,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 xf{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&&df(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 Of(e){return Uint8Array.from(atob(e),(e=>e.charCodeAt(0)))}function Pf(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=Of(s)):r=function(e){const t=Mf(e).subarray(0,16),r=new Uint8Array(16);return r.set(t,16-t.length),r}(s)}}return r}function Mf(e){return Uint8Array.from(unescape(encodeURIComponent(e)),(e=>e.charCodeAt(0)))}var Ff={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Nf="org.w3.clearkey",Uf="com.apple.streamingkeydelivery",Bf="com.microsoft.playready",jf="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function $f(e){switch(e){case Uf:return Ff.FAIRPLAY;case Bf:return Ff.PLAYREADY;case jf:return Ff.WIDEVINE;case Nf:return Ff.CLEARKEY}}var qf="edef8ba979d64acea3c827dcd51d21ed";function Kf(e){switch(e){case Ff.FAIRPLAY:return Uf;case Ff.PLAYREADY:return Bf;case Ff.WIDEVINE:return jf;case Ff.CLEARKEY:return Nf}}function Gf(e){const{drmSystems:t,widevineLicenseUrl:r}=e,n=t?[Ff.FAIRPLAY,Ff.WIDEVINE,Ff.PLAYREADY,Ff.CLEARKEY].filter((e=>!!t[e])):[];return!n[Ff.WIDEVINE]&&r&&n.push(Ff.WIDEVINE),n}const Hf="undefined"!=typeof self&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function Vf(e,t,r){return Uint8Array.prototype.slice?e.slice(t,r):new Uint8Array(Array.prototype.slice.call(e,t,r))}const zf=(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,Wf=(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,Yf=(e,t)=>{const r=t;let n=0;for(;zf(e,t);){n+=10;n+=Qf(e,t+6),Wf(e,t+10)&&(n+=10),t+=n}if(n>0)return e.subarray(r,r+n)},Qf=(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},Xf=(e,t)=>zf(e,t)&&Qf(e,t+6)+10<=e.length-t,Jf=e=>e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info,Zf=e=>{const t=String.fromCharCode(e[0],e[1],e[2],e[3]),r=Qf(e,4);return{type:t,size:r,data:e.subarray(10,10+r)}},ep=e=>{let t=0;const r=[];for(;zf(e,t);){const n=Qf(e,t+6);t+=10;const s=t+n;for(;t+8<s;){const n=Zf(e.subarray(t)),s=tp(n);s&&r.push(s),t+=n.size+10}Wf(e,t)&&(t+=10)}return r},tp=e=>"PRIV"===e.type?rp(e):"W"===e.type[0]?sp(e):np(e),rp=e=>{if(e.size<2)return;const t=op(e.data,!0),r=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:r.buffer}},np=e=>{if(e.size<2)return;if("TXXX"===e.type){let t=1;const r=op(e.data.subarray(t),!0);t+=r.length+1;const n=op(e.data.subarray(t));return{key:e.type,info:r,data:n}}const t=op(e.data.subarray(1));return{key:e.type,data:t}},sp=e=>{if("WXXX"===e.type){if(e.size<2)return;let t=1;const r=op(e.data.subarray(t),!0);t+=r.length+1;const n=op(e.data.subarray(t));return{key:e.type,info:r,data:n}}const t=op(e.data);return{key:e.type,data:t}},ip=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)}},op=(e,t=!1)=>{const r=lp();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,o,a="",l=0;for(;l<n;){if(s=e[l++],0===s&&t)return a;if(0!==s&&3!==s)switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(s);break;case 12:case 13:i=e[l++],a+=String.fromCharCode((31&s)<<6|63&i);break;case 14:i=e[l++],o=e[l++],a+=String.fromCharCode((15&s)<<12|(63&i)<<6|(63&o)<<0)}}return a};let ap;function lp(){return ap||void 0===self.TextDecoder||(ap=new self.TextDecoder("utf-8")),ap}const cp=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},up=Math.pow(2,32)-1,dp=[].push,hp={video:1,audio:2,id3:3,text:4};function fp(e){return String.fromCharCode.apply(null,e)}function pp(e,t){const r=e[t]<<8|e[t+1];return r<0?65536+r:r}function gp(e,t){const r=mp(e,t);return r<0?4294967296+r:r}function mp(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function yp(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 vp(e,t){const r=[];if(!t.length)return r;const n=e.byteLength;for(let s=0;s<n;){const i=gp(e,s),o=i>1?s+i:n;if(fp(e.subarray(s+4,s+8))===t[0])if(1===t.length)r.push(e.subarray(s+8,o));else{const n=vp(e.subarray(s+8,o),t.slice(1));n.length&&dp.apply(r,n)}s=o}return r}function bp(e){const t=[],r=e[0];let n=8;const s=gp(e,n);n+=4;n+=0===r?8:16,n+=2;let i=e.length+0;const o=pp(e,n);n+=2;for(let r=0;r<o;r++){let r=n;const o=gp(e,r);r+=4;const a=2147483647&o;if(1===(2147483648&o)>>>31)return bf.warn("SIDX has hierarchical references (not supported)"),null;const l=gp(e,r);r+=4,t.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/s,start:i,end:i+a-1}}),i+=a,r+=4,n=r}return{earliestPresentationTime:0,timescale:s,version:r,referencesCount:o,references:t}}function wp(e){const t=[],r=vp(e,["moov","trak"]);for(let e=0;e<r.length;e++){const n=r[e],s=vp(n,["tkhd"])[0];if(s){let e=s[0],r=0===e?12:20;const i=gp(s,r),o=vp(n,["mdia","mdhd"])[0];if(o){e=o[0],r=0===e?12:20;const s=gp(o,r),a=vp(n,["mdia","hdlr"])[0];if(a){const e=fp(a.subarray(8,12)),r={soun:Af,vide:_f}[e];if(r){const e=vp(n,["mdia","minf","stbl","stsd"])[0];let o;e&&(o=fp(e.subarray(12,16))),t[i]={timescale:s,type:r},t[r]={timescale:s,id:i,codec:o}}}}}}return vp(e,["moov","mvex","trex"]).forEach((e=>{const r=gp(e,4),n=t[r];n&&(n.default={duration:gp(e,12),flags:gp(e,20)})})),t}function Ep(e){const t=vp(e,["schm"])[0];if(t){const r=fp(t.subarray(4,8));if("cbcs"===r||"cenc"===r)return vp(e,["schi","tenc"])[0]}return bf.error("[eme] missing 'schm' box"),null}function Tp(e){const t=gp(e,0);let r=8;1&t&&(r+=4),4&t&&(r+=4);let n=0;const s=gp(e,4);for(let i=0;i<s;i++){if(256&t){n+=gp(e,r),r+=4}512&t&&(r+=4),1024&t&&(r+=4),2048&t&&(r+=4)}return n}function Sp(e,t){const r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}function Cp(e,t){const r=[],n=t.samples,s=t.timescale,i=t.id;let o=!1;return vp(n,["moof"]).map((a=>{const l=a.byteOffset-8;vp(a,["traf"]).map((a=>{const c=vp(a,["tfdt"]).map((e=>{const t=e[0];let r=gp(e,4);return 1===t&&(r*=Math.pow(2,32),r+=gp(e,8)),r/s}))[0];return void 0!==c&&(e=c),vp(a,["tfhd"]).map((c=>{const u=gp(c,4),d=16777215&gp(c,0);let h=0;const f=0!=(16&d);let p=0;const g=0!=(32&d);let m=8;u===i&&(0!=(1&d)&&(m+=8),0!=(2&d)&&(m+=4),0!=(8&d)&&(h=gp(c,m),m+=4),f&&(p=gp(c,m),m+=4),g&&(m+=4),"video"===t.type&&(o=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)),vp(a,["trun"]).map((i=>{const a=i[0],c=16777215&gp(i,0),u=0!=(1&c);let d=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 T=gp(i,4);let S=8;u&&(d=gp(i,S),S+=4),f&&(S+=4);let C=d+l;for(let l=0;l<T;l++){if(g?(m=gp(i,S),S+=4):m=h,y?(v=gp(i,S),S+=4):v=p,b&&(S+=4),w&&(E=0===a?gp(i,S):mp(i,S),S+=4),t.type===_f){let t=0;for(;t<v;){const i=gp(n,C);if(C+=4,kp(o,n[C])){Ap(n.subarray(C,C+i),o?2:1,e+E/s,r)}C+=i,t+=i+4}}e+=m/s}})))}))}))})),r}function kp(e,t){if(e){const e=t>>1&63;return 39===e||40===e}return 6===(31&t)}function Ap(e,t,r,n){const s=_p(e);let i=0;i+=t;let o=0,a=0,l=!1,c=0;for(;i<s.length;){o=0;do{if(i>=s.length)break;c=s[i++],o+=c}while(255===c);a=0;do{if(i>=s.length)break;c=s[i++],a+=c}while(255===c);const e=s.length-i;if(!l&&4===o&&i<s.length){l=!0;if(181===s[i++]){const e=pp(s,i);if(i+=2,49===e){const e=gp(s,i);if(i+=4,1195456820===e){const e=s[i++];if(3===e){const t=s[i++],a=31&t,l=64&t,c=l?2+3*a:0,u=new Uint8Array(c);if(l){u[0]=t;for(let e=1;e<c;e++)u[e]=s[i++]}n.push({type:e,payloadType:o,pts:r,bytes:u})}}}}}else if(5===o&&a<e){if(l=!0,a>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=a-16,l=new Uint8Array(t);for(let e=0;e<t;e++)l[e]=s[i++];n.push({payloadType:o,pts:r,uuid:e.join(""),userData:op(l),userDataBytes:l})}}else if(a<e)i+=a;else if(a>e)break}}function _p(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 o=0;for(n=0;n<s;o++,n++)o===r[0]&&(o++,r.shift()),i[n]=e[o];return i}function Ip(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 o=new Uint8Array(4);return r&&r.byteLength>0&&new DataView(o.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,o,r||new Uint8Array)}let Rp={};class Lp{static clearKeyUriToKeyIdMap(){Rp={}}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 Uf:case jf:case Bf:case Nf: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||bf.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 Lp(this.method,this.uri,"identity",this.keyFormatVersions,t)}const t=Pf(this.uri);if(t)switch(this.keyFormat){case jf:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case Bf:{const e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Ip(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=Of(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=Rp[this.uri];if(!e){const t=Object.keys(Rp).length%Number.MAX_SAFE_INTEGER;e=new Uint8Array(16);new DataView(e.buffer,12,4).setUint32(0,t),Rp[this.uri]=e}this.keyId=e}return this}}const Dp=/\{\$([a-zA-Z0-9-_]+)\}/g;function xp(e){return Dp.test(e)}function Op(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]=Pp(e,i))}}function Pp(e,t){if(null!==e.variableList||e.hasVariableRefs){const r=e.variableList;return t.replace(Dp,(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 Mp(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 Fp(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 Np(){if("undefined"!=typeof self)return self.MediaSource||self.WebKitMediaSource}const Up={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}},Bp=Np();function jp(e,t){var r;return null!=(r=null==Bp?void 0:Bp.isTypeSupported(`${t||"video"}/mp4;codecs="${e}"`))&&r}const $p=/#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,qp=/#EXT-X-MEDIA:(.*)/g,Kp=/^#EXT(?:INF|-X-TARGETDURATION):/m,Gp=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),Hp=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 Vp{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 of.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Kp.test(e)}static parseMasterPlaylist(e,t){const r={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:xp(e)},n=[];let s;for($p.lastIndex=0;null!=(s=$p.exec(e));)if(s[1]){var i;const e=new Tf(s[1]);Op(r,e,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const o=Pp(r,s[2]),a={attrs:e,bitrate:e.decimalInteger("AVERAGE-BANDWIDTH")||e.decimalInteger("BANDWIDTH"),name:e.NAME,url:Vp.resolve(o,t)},l=e.decimalResolution("RESOLUTION");l&&(a.width=l.width,a.height=l.height),Yp((e.CODECS||"").split(/[ ,]+/).filter((e=>e)),a),a.videoCodec&&-1!==a.videoCodec.indexOf("avc1")&&(a.videoCodec=Vp.convertAVC1ToAVCOTI(a.videoCodec)),null!=(i=a.unknownCodecs)&&i.length||n.push(a),r.levels.push(a)}else if(s[3]){const e=s[3],n=s[4];switch(e){case"SESSION-DATA":{const e=new Tf(n);Op(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=zp(n,t,r);e.encrypted&&e.isSupported()?(null===r.sessionKeys&&(r.sessionKeys=[]),r.sessionKeys.push(e)):bf.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${n}"`);break}case"DEFINE":{const e=new Tf(n);Op(r,e,["NAME","VALUE","QUERYPARAM"]),Mp(r,e,t)}break;case"CONTENT-STEERING":{const e=new Tf(n);Op(r,e,["SERVER-URI","PATHWAY-ID"]),r.contentSteering={uri:Vp.resolve(e["SERVER-URI"],t),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":r.startTimeOffset=Wp(n)}}const o=n.length>0&&n.length<r.levels.length;return r.levels=o?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,o={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 a=0;for(qp.lastIndex=0;null!==(n=qp.exec(e));){const e=new Tf(n[1]),i=e.TYPE;if(i){const n=o[i],l=s[i]||[];s[i]=l,Op(r,e,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const c={attrs:e,bitrate:0,id:a++,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?Vp.resolve(e.URI,t):""};if(null!=n&&n.length){const e=Vp.findGroup(n,c.groupId)||n[0];Qp(c,e,"audioCodec"),Qp(c,e,"textCodec")}l.push(c)}}return s}static parseLevelPlaylist(e,t,r,n,s,i){const o=new xf(t),a=o.fragments;let l,c,u,d=null,h=0,f=0,p=0,g=0,m=null,y=new Lf(n,t),v=-1,b=!1;for(Gp.lastIndex=0,o.m3u8=e,o.hasVariableRefs=xp(e);null!==(l=Gp.exec(e));){b&&(b=!1,y=new Lf(n,t),y.start=p,y.sn=h,y.cc=g,y.level=r,d&&(y.initSegment=d,y.rawProgramDateTime=d.rawProgramDateTime,d.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(df(y.duration)){y.start=p,u&&Zp(y,u,o),y.sn=h,y.level=r,y.cc=g,y.urlId=s,a.push(y);const e=(" "+l[3]).slice(1);y.relurl=Pp(o,e),Xp(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=a.length);else{if(l=l[0].match(Hp),!l){bf.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":o.type=s.toUpperCase();break;case"MEDIA-SEQUENCE":h=o.startSN=parseInt(s);break;case"SKIP":{const e=new Tf(s);Op(o,e,["RECENTLY-REMOVED-DATERANGES"]);const t=e.decimalInteger("SKIPPED-SEGMENTS");if(df(t)){o.skippedSegments=t;for(let e=t;e--;)a.unshift(null);h+=t}const r=e.enumeratedString("RECENTLY-REMOVED-DATERANGES");r&&(o.recentlyRemovedDateranges=r.split("\t"));break}case"TARGETDURATION":o.targetduration=Math.max(parseInt(s),1);break;case"VERSION":o.version=parseInt(s);break;case"EXTM3U":break;case"ENDLIST":o.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 Tf(s);Op(o,e,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),Op(o,e,e.clientAttrs);const t=new Cf(e,o.dateRanges[e.ID]);t.isValid||o.skippedSegments?o.dateRanges[t.id]=t:bf.warn(`Ignoring invalid DATERANGE tag: "${s}"`),y.tagList.push(["EXT-X-DATERANGE",s]);break}case"DEFINE":{const e=new Tf(s);Op(o,e,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in e?Fp(o,e,i):Mp(o,e,t)}break;case"DISCONTINUITY-SEQUENCE":g=parseInt(s);break;case"KEY":{const e=zp(s,t,o);if(e.isSupported()){if("NONE"===e.method){u=void 0;break}u||(u={}),u[e.keyFormat]&&(u=uf({},u)),u[e.keyFormat]=e}else bf.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${s}"`);break}case"START":o.startTimeOffset=Wp(s);break;case"MAP":{const e=new Tf(s);if(Op(o,e,["BYTERANGE","URI"]),y.duration){const s=new Lf(n,t);Jp(s,e,r,u),d=s,y.initSegment=d,d.rawProgramDateTime&&!y.rawProgramDateTime&&(y.rawProgramDateTime=d.rawProgramDateTime)}else Jp(y,e,r,u),d=y,b=!0;break}case"SERVER-CONTROL":{const e=new Tf(s);o.canBlockReload=e.bool("CAN-BLOCK-RELOAD"),o.canSkipUntil=e.optionalFloat("CAN-SKIP-UNTIL",0),o.canSkipDateRanges=o.canSkipUntil>0&&e.bool("CAN-SKIP-DATERANGES"),o.partHoldBack=e.optionalFloat("PART-HOLD-BACK",0),o.holdBack=e.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const e=new Tf(s);o.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=o.partList;e||(e=o.partList=[]);const r=f>0?e[e.length-1]:void 0,n=f++,i=new Tf(s);Op(o,i,["BYTERANGE","URI"]);const a=new Df(i,y,t,n,r);e.push(a),y.duration+=a.duration;break}case"PRELOAD-HINT":{const e=new Tf(s);Op(o,e,["URI"]),o.preloadHint=e;break}case"RENDITION-REPORT":{const e=new Tf(s);Op(o,e,["URI"]),o.renditionReports=o.renditionReports||[],o.renditionReports.push(e);break}default:bf.warn(`line parsed but not handled: ${l}`)}}}m&&!m.relurl?(a.pop(),p-=m.duration,o.partList&&(o.fragmentHint=m)):o.partList&&(Xp(y,m),y.cc=g,o.fragmentHint=y,u&&Zp(y,u,o));const w=a.length,E=a[0],T=a[w-1];if(p+=o.skippedSegments*o.targetduration,p>0&&w&&T){o.averagetargetduration=p/w;const e=T.sn;o.endSN="initSegment"!==e?e:0,o.live||(T.endList=!0),E&&(o.startCC=E.cc)}else o.endSN=0,o.startCC=0;return o.fragmentHint&&(p+=o.fragmentHint.duration),o.totalduration=p,o.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}}(a,v),o}}function zp(e,t,r){var n,s;const i=new Tf(e);Op(r,i,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const o=null!=(n=i.METHOD)?n:"",a=i.URI,l=i.hexadecimalInteger("IV"),c=i.KEYFORMATVERSIONS,u=null!=(s=i.KEYFORMAT)?s:"identity";a&&i.IV&&!l&&bf.error(`Invalid IV: ${i.IV}`);const d=a?Vp.resolve(a,t):"",h=(c||"1").split("/").map(Number).filter(Number.isFinite);return new Lp(o,d,u,h,l)}function Wp(e){const t=new Tf(e).decimalFloatingPoint("TIME-OFFSET");return df(t)?t:null}function Yp(e,t){["video","audio","text"].forEach((r=>{const n=e.filter((e=>function(e,t){const r=Up[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 Qp(e,t,r){const n=t[r];n&&(e[r]=n)}function Xp(e,t){e.rawProgramDateTime?e.programDateTime=Date.parse(e.rawProgramDateTime):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime),df(e.programDateTime)||(e.programDateTime=null,e.rawProgramDateTime=null)}function Jp(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 Zp(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 eg="manifest",tg="level",rg="audioTrack",ng="subtitleTrack",sg="main",ig="audio",og="subtitle";function ag(e){const{type:t}=e;switch(t){case rg:return ig;case ng:return og;default:return sg}}function lg(e,t){let r=e.url;return void 0!==r&&0!==r.indexOf("data:")||(r=t.url),r}class cg{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(hf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(hf.LEVEL_LOADING,this.onLevelLoading,this),e.on(hf.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(hf.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:e}=this;e.off(hf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(hf.LEVEL_LOADING,this.onLevelLoading,this),e.off(hf.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(hf.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:eg,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:tg,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:rg,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:ng,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 bf.trace("[playlist-loader]: playlist request ongoing");bf.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}if(n=e.type===eg?r.manifestLoadPolicy.default:uf({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),null!=(t=e.deliveryDirectives)&&t.part){let t;if(e.type===tg&&null!==e.level?t=this.hls.levels[e.level].details:e.type===rg&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===ng&&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=uf({},n,{maxTimeToFirstByteMs:Math.min(t,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,n.maxTimeToFirstByteMs)})}}}const i=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:i.maxNumRetry||0,retryDelay:i.retryDelayMs||0,maxRetryDelay:i.maxRetryDelayMs||0},a={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(),Vp.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,o,a)}handleMasterPlaylist(e,t,r,n){const s=this.hls,i=e.data,o=lg(e,r),a=Vp.parseMasterPlaylist(i,o);if(a.playlistParsingError)return void this.handleManifestParsingError(e,r,a.playlistParsingError,n,t);const{contentSteering:l,levels:c,sessionData:u,sessionKeys:d,startTimeOffset:h,variableList:f}=a;this.variableList=f;const{AUDIO:p=[],SUBTITLES:g,"CLOSED-CAPTIONS":m}=Vp.parseMasterPlaylistMedia(i,o,a);if(p.length){p.some((e=>!e.url))||!c[0].audioCodec||c[0].attrs.AUDIO||(bf.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 Tf({}),bitrate:0,url:""}))}s.trigger(hf.MANIFEST_LOADED,{levels:c,audioTracks:p,subtitles:g,captions:m,contentSteering:l,url:o,stats:t,networkDetails:n,sessionData:u,sessionKeys:d,startTimeOffset:h,variableList:f})}handleTrackOrLevelPlaylist(e,t,r,n,s){const i=this.hls,{id:o,level:a,type:l}=r,c=lg(e,r),u=df(o)?o:0,d=df(a)?a:u,h=ag(r),f=Vp.parseLevelPlaylist(e.data,c,d,h,u,this.variableList);if(l===eg){const e={attrs:new Tf({}),bitrate:0,details:f,name:"",url:c};i.trigger(hf.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(hf.ERROR,{type:ff.NETWORK_ERROR,details:pf.MANIFEST_PARSING_ERROR,fatal:t.type===eg,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===tg?i+=`: ${e.level} id: ${e.id}`:e.type!==rg&&e.type!==ng||(i+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(i);bf.warn(`[playlist-loader]: ${i}`);let a=pf.UNKNOWN,l=!1;const c=this.getInternalLoader(e);switch(e.type){case eg:a=r?pf.MANIFEST_LOAD_TIMEOUT:pf.MANIFEST_LOAD_ERROR,l=!0;break;case tg:a=r?pf.LEVEL_LOAD_TIMEOUT:pf.LEVEL_LOAD_ERROR,l=!1;break;case rg:a=r?pf.AUDIO_TRACK_LOAD_TIMEOUT:pf.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case ng:a=r?pf.SUBTITLE_TRACK_LOAD_TIMEOUT:pf.SUBTITLE_LOAD_ERROR,l=!1}c&&this.resetInternalLoader(e.type);const u={type:ff.NETWORK_ERROR,details:a,fatal:l,url:e.url,loader:c,context:e,error:o,networkDetails:t,stats:s};if(n){const r=(null==t?void 0:t.url)||e.url;u.response=lf({url:r,data:void 0},n)}this.hls.trigger(hf.ERROR,u)}handlePlaylistLoaded(e,t,r,n,s,i){const o=this.hls,{type:a,level:l,id:c,groupId:u,deliveryDirectives:d}=n,h=lg(t,n),f=ag(n),p="number"==typeof n.level&&f===sg?l:void 0;if(!e.fragments.length){const e=new Error("No Segments found in Playlist");return void o.trigger(hf.ERROR,{type:ff.NETWORK_ERROR,details:pf.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)o.trigger(hf.ERROR,{type:ff.NETWORK_ERROR,details:pf.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)),a){case eg:case tg:o.trigger(hf.LEVEL_LOADED,{details:e,level:p||0,id:c||0,stats:r,networkDetails:s,deliveryDirectives:d});break;case rg:o.trigger(hf.AUDIO_TRACK_LOADED,{details:e,id:c||0,groupId:u||"",stats:r,networkDetails:s,deliveryDirectives:d});break;case ng:o.trigger(hf.SUBTITLE_TRACK_LOADED,{details:e,id:c||0,groupId:u||"",stats:r,networkDetails:s,deliveryDirectives:d})}}}function ug(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 dg(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){bf.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){bf.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}"disabled"===r&&(e.mode=r)}function hg(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 fg(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,o=e.length;i<o;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 pg="org.id3",gg="com.apple.quicktime.HLS",mg="https://aomedia.org/emsg/ID3";function yg(){if("undefined"!=typeof self)return self.WebKitDataCue||self.VTTCue||self.TextTrackCue}const vg=(()=>{const e=yg();try{new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function bg(e,t){return e.getTime()/1e3-t}class wg{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(hf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(hf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(hf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(hf.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(hf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(hf.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(hf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(hf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(hf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(hf.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(hf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(hf.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&(hg(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 ug(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=yg();for(let e=0;e<s.length;e++){const t=s[e].type;if(t===mg&&!r||!n)continue;const o=ep(s[e].data);if(o){const r=s[e].pts;let n=r+s[e].duration;n>vg&&(n=vg);n-r<=0&&(n=r+.25);for(let e=0;e<o.length;e++){const s=o[e];if(!Jf(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===vg&&(s.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:r,type:n}){const{id3Track:s,hls:i}=this;if(!i)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:a}}=i;if(s&&(o||a)){let e;e="audio"===n?e=>e.type===pg&&a:"video"===n?e=>e.type===mg&&o:e=>e.type===pg&&a||e.type===mg&&o,fg(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 o=t.fragments[t.fragments.length-1];if(0===i.length||!df(null==o?void 0:o.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=o.programDateTime/1e3-o.start,l=yg();for(let e=0;e<i.length;e++){const t=i[e],n=s[t],o=r[t],d=(null==o?void 0:o.cues)||{};let h=(null==o?void 0:o.durationKnown)||!1;const f=bg(n.startDate,a);let p=vg;const g=n.endDate;if(g)p=bg(g,a),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=bg(e.startDate,a),h=!0)}const m=Object.keys(n.attr);for(let e=0;e<m.length;e++){const r=m[e];if("ID"===(u=r)||"CLASS"===u||"START-DATE"===u||"DURATION"===u||"END-DATE"===u||"END-ON-NEXT"===u)continue;let s=d[r];if(s)h&&!o.durationKnown&&(s.endTime=p);else{let e=n.attr[r];s=new l(f,p,""),Sf(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=gg,s.id=t,this.id3Track.addCue(s),d[r]=s}}r[t]={cues:d,dateRange:n,durationKnown:h}}var c,u}}class Eg{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:o}=this.config,a=this.hls.userConfig;let l=o&&r||t;(a.liveSyncDuration||a.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,o=n-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(i,s),o)}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(hf.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(hf.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(hf.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(hf.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(hf.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(hf.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(hf.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(hf.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(hf.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(hf.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===pf.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(r=this.levelDetails)&&r.live&&bf.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 o=r-i,a=o<Math.min(this.maxLatency,i+t.targetduration);if(t.live&&a&&o>.05&&this.forwardBufferLength>1){const t=Math.min(2,Math.max(1,s)),r=Math.round(2/(1+Math.exp(-.75*o-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 Tg=["NONE","TYPE-0","TYPE-1",null];var Sg="",Cg="YES",kg="v2";class Ag{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 _g{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 Ig(e,t){const r=t.startPTS;if(df(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 Rg(e,t,r,n,s,i){n-r<=0&&(bf.warn("Fragment should have a positive duration",t),n=r+t.duration,i=s+t.duration);let o=r,a=n;const l=t.startPTS,c=t.endPTS;if(df(l)){const e=Math.abs(l-r);df(t.deltaPTS)?t.deltaPTS=Math.max(e,t.deltaPTS):t.deltaPTS=e,o=Math.max(r,l),r=Math.min(r,l),s=Math.min(s,t.startDTS),a=Math.min(n,c),n=Math.max(n,c),i=Math.max(i,t.endDTS)}const u=r-t.start;0!==t.start&&(t.start=r),t.duration=n-t.start,t.startPTS=r,t.maxStartPTS=o,t.startDTS=s,t.endPTS=n,t.minEndPTS=a,t.endDTS=i;const d=t.sn;if(!e||d<e.startSN||d>e.endSN)return 0;let h;const f=d-e.startSN,p=e.fragments;for(p[f]=t,h=f;h>0;h--)Ig(p[h],p[h-1]);for(h=f;h<p.length-1;h++)Ig(p[h],p[h+1]);return e.fragmentHint&&Ig(p[p.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,u}function Lg(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,o=t.startSN-e.startSN,a=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[o+e];let i=a[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),df(e.startPTS)&&df(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){bf.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=uf({},e);r&&r.forEach((e=>{delete n[e]}));return Object.keys(t).forEach((e=>{const r=new Cf(t[e].attr,n[e]);r.isValid?n[e]=r:bf.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(t[e].attr)}"`)})),n}(e.dateRanges,t.dateRanges,t.recentlyRemovedDateranges));const o=t.fragments;if(i){bf.warn("discontinuity sliding from playlist, take drift into account");for(let e=0;e<o.length;e++)o[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],o=t[s+n];i&&o&&i.index===o.index&&i.fragment.sn===o.fragment.sn?r(i,o):n--}}}(e.partList,t.partList,((e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats})),s?Rg(t,s,s.startPTS,s.endPTS,s.startDTS,s.endDTS):Dg(e,t),o.length&&(t.totalduration=t.edge-o[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const a=t.advancedDateTime;if(t.advanced&&a){const e=t.edge;t.driftStart||(t.driftStartTime=a,t.driftStart=e),t.driftEndTime=a,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime}function Dg(e,t){const r=t.startSN+t.skippedSegments-e.startSN,n=e.fragments;r<0||r>=n.length||xg(t,n[r].start)}function xg(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 Og(e,t,r){var n;return null!=e&&e.details?Pg(null==(n=e.details)?void 0:n.partList,t,r):null}function Pg(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 Mg(e){switch(e.details){case pf.FRAG_LOAD_TIMEOUT:case pf.KEY_LOAD_TIMEOUT:case pf.LEVEL_LOAD_TIMEOUT:case pf.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Fg(e,t){const r=Mg(t);return e.default[(r?"timeout":"error")+"Retry"]}function Ng(e,t){const r="linear"===e.backoff?1:Math.pow(2,t);return Math.min(r*e.retryDelayMs,e.maxRetryDelayMs)}function Ug(e){return lf(lf({},e),{errorRetry:null,timeoutRetry:null})}function Bg(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 jg=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 o=t(i);if(o>0)r=s+1;else{if(!(o<0))return i;n=s-1}}return null};function $g(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===qg(r,n,s))return s;const i=jg(t,qg.bind(null,r,n));return!i||i===e&&s?s:i}function qg(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 Kg(e,t,r){const n=1e3*Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-n>e}var Gg=0,Hg=2,Vg=5,zg=0,Wg=1,Yg=2;function Qg(e,t,r){if(performance.now()-e.lastErrorPerfMs>3e5)return!0;const n=e.details;if(t.details===pf.FRAG_GAP&&n&&t.frag){const e=t.frag.start,r=$g(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 Xg{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=bf.log.bind(bf,`${t}:`),this.warn=bf.warn.bind(bf,`${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 o;try{o=new self.URL(i.URI,t.url).href}catch(e){bf.warn(`Could not construct new URL for Rendition Report: ${e}`),o=i.URI||""}if(o===e){n=s;break}o===e.substring(0,o.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 Ag(s,i>=0?i:void 0,Sg)}}}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(),o=s.loading.first?Math.max(0,i-s.loading.first):0;if(n.advancedDateTime=Date.now()-o,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&&Lg(r,n),!this.canLoad||!n.live)return;let o,a,l;if(n.canBlockReload&&n.endSN&&n.advanced){const e=this.hls.config.lowLatencyMode,s=n.lastPartSn,i=n.endSN,c=n.lastPartIndex,u=s===i,d=e?0:c;-1!==c?(a=u?i+1:s,l=u?d:c+1):a=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(a+=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(o=this.getDeliveryDirectives(n,t.deliveryDirectives,a,l),e||!u)return void this.loadPlaylist(o)}else n.canBlockReload&&(o=this.getDeliveryDirectives(n,t.deliveryDirectives,a,l));const c=this.hls.mainForwardBufferInfo,u=c?c.end-c.len:0,d=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-u));n.updated&&i>this.requestScheduled+d&&(this.requestScheduled=s.loading.start),void 0!==a&&n.canBlockReload?this.requestScheduled=s.loading.first+d-(1e3*n.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+d<i?this.requestScheduled=i:this.requestScheduled-i<=0&&(this.requestScheduled+=d);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(o)),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?kg:Cg:Sg}(e,r);return null!=t&&t.skip&&e.deltaUpdateFailed&&(r=t.msn,n=t.part,s=Sg),new Ag(r,n,s)}checkRetry(e){const t=e.details,r=Mg(e),n=e.errorAction,{action:s,retryCount:i=0,retryConfig:o}=n||{},a=!!n&&!!o&&(s===Vg||!n.resolved&&s===Hg);if(a){var l;if(this.requestScheduled=-1,i>=o.maxNumRetry)return!1;if(r&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${i+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const e=Ng(o,i);this.timer=self.setTimeout((()=>this.loadPlaylist()),e),this.warn(`Retrying playlist loading ${i+1}/${o.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,n.resolved=!0}return a}}let Jg;class Zg extends Xg{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(hf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(hf.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(hf.LEVEL_LOADED,this.onLevelLoaded,this),e.on(hf.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(hf.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(hf.FRAG_LOADED,this.onFragLoaded,this),e.on(hf.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(hf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(hf.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(hf.LEVEL_LOADED,this.onLevelLoaded,this),e.off(hf.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(hf.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(hf.FRAG_LOADED,this.onFragLoaded,this),e.off(hf.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"))&&(Jg||(Jg=/chrome|firefox/i.test(navigator.userAgent)),Jg&&(e.audioCodec=void 0));const{AUDIO:o,CODECS:a,"FRAME-RATE":l,"PATHWAY-ID":c,RESOLUTION:u,SUBTITLES:d}=i,h=`${`${c||"."}-`}${e.bitrate}-${u}-${l}-${a}`;s=n[h],s?s.addFallback(e):(s=new _g(e),n[h]=s,r.push(s)),em(s,"audio",o),em(s,"text",d)})),this.filterAndSortMediaOptions(r,t)}filterAndSortMediaOptions(e,t){let r=[],n=[],s=!1,i=!1,o=!1,a=e.filter((({audioCodec:e,videoCodec:t,width:r,height:n,unknownCodecs:a})=>(s||(s=!(!r||!n)),i||(i=!!t),o||(o=!!e),!(null!=a&&a.length)&&(!e||jp(e,"audio"))&&(!t||jp(t,"video")))));if((s||i)&&o&&(a=a.filter((({videoCodec:e,width:t,height:r})=>!!e||!(!t||!r)))),0===a.length)return void Promise.resolve().then((()=>{if(this.hls){const e=new Error("no level with compatible codecs found in manifest");this.hls.trigger(hf.ERROR,{type:ff.MEDIA_ERROR,details:pf.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:e,reason:e.message})}}));t.audioTracks&&(r=t.audioTracks.filter((e=>!e.audioCodec||jp(e.audioCodec,"audio"))),tm(r)),t.subtitles&&(n=t.subtitles,tm(n));const l=a.slice(0);a.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&&(a=this.steering.filterParsedLevels(a),a.length!==l.length))for(let e=0;e<l.length;e++)if(l[e].pathwayId===a[0].pathwayId){c=l[e];break}this._levels=a;for(let e=0;e<a.length;e++)if(a[e]===c){this._firstLevel=e,this.log(`manifest loaded, ${a.length} level(s) found, first bitrate: ${c.bitrate}`);break}const u=o&&!i,d={levels:a,audioTracks:r,subtitleTracks:n,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:o,video:i,altAudio:!u&&r.some((e=>!!e.url))};this.hls.trigger(hf.MANIFEST_PARSED,d),(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(hf.ERROR,{type:ff.OTHER_ERROR,details:pf.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],o=i.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=i,r===e&&i.details&&n&&s===o)return;this.log(`Switching to level ${e}${o?" with Pathway "+o:""} from level ${r}${s?" with Pathway "+s:""}`);const a=uf({},i,{level:e,maxBitrate:i.maxBitrate,attrs:i.attrs,uri:i.uri,urlId:i.urlId});delete a._attrs,delete a._urlId,this.hls.trigger(hf.LEVEL_SWITCHING,a);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===tg&&t.context.level===this.level&&this.checkRetry(t)}onFragLoaded(e,{frag:t}){if(void 0!==t&&t.type===sg){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 o;if(!i)return this.warn(`Invalid level index ${n}`),void(null!=(o=t.deliveryDirectives)&&o.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(hf.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(hf.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 em(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 tm(e){const t={};e.forEach((e=>{const r=e.groupId||"";e.id=t[r]=t[r]||0,t[r]++}))}var rm="NOT_LOADED",nm="APPENDING",sm="PARTIAL",im="OK";class om{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(hf.BUFFER_APPENDED,this.onBufferAppended,this),e.on(hf.FRAG_BUFFERED,this.onFragBuffered,this),e.on(hf.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(hf.BUFFER_APPENDED,this.onBufferAppended,this),e.off(hf.FRAG_BUFFERED,this.onFragBuffered,this),e.off(hf.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 o=i.range[e];o&&o.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=lm(r),i=this.fragments[s];if(!i||i.buffered&&r.gap)return;const o=!r.relurl;Object.keys(t).forEach((e=>{const s=r.elementaryStreams[e];if(!s)return;const a=t[e],l=o||!0===s.partial;i.range[e]=this.getBufferedTimes(r,n,l,a)})),i.loaded=null,Object.keys(i.range).length?(i.buffered=!0,i.body.endList&&(this.endListFragments[i.body.type]=i),am(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=lm(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,o=e.end,a=e.minEndPTS||o,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&&a<=r){s.time.push({startPTS:Math.max(i,n.start(e)),endPTS:Math.min(o,n.end(e))});break}if(i<r&&o>t)s.partial=!0,s.time.push({startPTS:Math.max(i,n.start(e)),endPTS:Math.min(o,n.end(e))});else if(o<=t)break}return s}getPartialFragment(e){let t,r,n,s=null,i=0;const{bufferPadding:o,fragments:a}=this;return Object.keys(a).forEach((l=>{const c=a[l];c&&am(c)&&(r=c.body.start-o,n=c.body.end+o,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||am(t))}getState(e){const t=lm(e),r=this.fragments[t];return r?r.buffered?am(r)?sm:im:nm:rm}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=lm(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=lm(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 o=this.fragments[i];if(!o)return;const a=o.body;a.type!==r||n&&!a.gap||a.start<t&&a.end>e&&(o.buffered||s)&&this.removeFragment(a)}))}removeFragment(e){const t=lm(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 am(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 lm(e){return`${e.type}_${e.level}_${e.urlId}_${e.sn}`}const cm=Math.pow(2,17);class um{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 fm({type:ff.NETWORK_ERROR,details:pf.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(((o,a)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some((e=>"GAP"===e[0])))return void a(hm(e));e.gap=!1}const l=this.loader=e.loader=s?new s(n):new i(n),c=dm(e),u=Ug(n.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:cm};e.stats=l.stats,l.load(c,d,{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)),o({frag:e,part:null,payload:i,networkDetails:s})},onError:(t,n,s,i)=>{this.resetLoader(e,l),a(new fm({type:ff.NETWORK_ERROR,details:pf.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:lf({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),a(new fm({type:ff.NETWORK_ERROR,details:pf.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:n,stats:t}))},onTimeout:(t,r,n)=>{this.resetLoader(e,l),a(new fm({type:ff.NETWORK_ERROR,details:pf.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${d.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(((o,a)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void a(hm(e,t));const l=this.loader=e.loader=s?new s(n):new i(n),c=dm(e,t),u=Ug(n.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:cm};t.stats=l.stats,l.load(c,d,{onSuccess:(n,s,i,a)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const c={frag:e,part:t,payload:n.data,networkDetails:a};r(c),o(c)},onError:(r,n,s,i)=>{this.resetLoader(e,l),a(new fm({type:ff.NETWORK_ERROR,details:pf.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:lf({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),a(new fm({type:ff.NETWORK_ERROR,details:pf.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:s,stats:r}))},onTimeout:(r,n,s)=>{this.resetLoader(e,l),a(new fm({type:ff.NETWORK_ERROR,details:pf.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.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),o=(n-i)*Math.round(r.loaded/i);r.total=r.loaded+o}else r.total=Math.max(r.loaded,r.total);const i=r.loading,o=n.loading;i.start?i.first+=o.first-o.start:(i.start=o.start,i.first=o.first),i.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function dm(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(df(s)&&df(i)){var o;let t=s,r=i;if("initSegment"===e.sn&&"AES-128"===(null==(o=e.decryptdata)?void 0:o.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 hm(e,t){const r=new Error(`GAP ${e.gap?"tag":"attribute"} found`),n={type:ff.MEDIA_ERROR,details:pf.FRAG_GAP,fatal:!1,frag:e,error:r,networkDetails:null};return t&&(n.part=t),(t||e).stats.aborted=!0,new fm(n)}class fm extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class pm{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=pf.KEY_LOAD_ERROR,r,n,s){return new fm({type:ff.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,pf.KEY_LOAD_ERROR,r))}const i=s.uri;if(!i)return Promise.reject(this.createKeyLoadError(e,pf.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${i}"`)));let o=this.keyUriToKeyInfo[i];if(null!=(r=o)&&r.decryptdata.key)return s.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});var a;if(null!=(n=o)&&n.keyLoadPromise)switch(null==(a=o.mediaKeySessionContext)?void 0:a.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then((t=>(s.key=t.keyInfo.decryptdata.key,{frag:e,keyInfo:o})))}switch(o=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(o,e):this.loadKeyEME(o,e);case"AES-128":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,pf.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 o={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},a=r.keyLoadPolicy.default,l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(e,t,r,n)=>{const{frag:o,keyInfo:a,url:l}=r;if(!o.decryptdata||a!==this.keyUriToKeyInfo[l])return i(this.createKeyLoadError(o,pf.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),n));a.decryptdata.key=o.decryptdata.key=new Uint8Array(e.data),o.keyLoader=null,a.loader=null,s({frag:o,keyInfo:a})},onError:(e,r,n,s)=>{this.resetLoader(r),i(this.createKeyLoadError(t,pf.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),n,lf({url:o.url,data:void 0},e)))},onTimeout:(e,r,n)=>{this.resetLoader(r),i(this.createKeyLoadError(t,pf.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),n))},onAbort:(e,r,n)=>{this.resetLoader(r),i(this.createKeyLoadError(t,pf.INTERNAL_ABORTED,new Error("key loading aborted"),n))}};n.load(o,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 gm={length:0,start:()=>0,end:()=>0};class mm{static isBuffered(e,t){try{if(e){const r=mm.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=mm.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,o=t,a=t;for(let e=0;e<n.length;e++){const l=n[e].start,c=n[e].end;if(t+r>=l&&t<c)o=l,a=c,i=a-t;else if(t+r<l){s=l;break}}return{len:i,start:o||0,end:a||0,nextStart:s}}static getBuffered(e){try{return e.buffered}catch(e){return bf.log("failed to get media.buffered",e),gm}}}class ym{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 vm(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 bm(e,t){if(e){const r=e.start+t;e.start=e.startPTS=r,e.endPTS=r+e.duration}}function wm(e,t){const r=t.fragments;for(let t=0,n=r.length;t<n;t++)bm(r[t],e);t.fragmentHint&&bm(t.fragmentHint,e),t.alignedSliding=!0}function Em(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 bf.log("No fragments to align");const i=vm(n,s[0].cc);if(i&&(!i||i.startPTS))return i;bf.log("No frag in previous level to align on")}(r.details,t);e&&df(e.start)&&(bf.log(`Adjusting PTS using last level due to CC increase within current level ${t.url}`),wm(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&&df(s)&&(bf.log(`Adjusting PTS using programDateTime delta ${n-r}ms, sliding:${s.toFixed(3)} ${e.url} `),wm(s,e))}(r,t.details),r.alignedSliding||!t.details||r.skippedSegments||Dg(t.details,r))}function Tm(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=vm(r,s.cc)||r[Math.round(r.length/2)-1],o=s.programDateTime,a=i.programDateTime;if(null===o||null===a)return;wm((a-o)/1e3-(i.start-s.start),e)}class Sm{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 Cm{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 km{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],o=r[3],a=this.invSubMix,l=a[0],c=a[1],u=a[2],d=a[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 a=h[f],g=h[a],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,o[f]=y,y=16843009*m^65537*g^257*a^16843008*f,l[r]=y<<24|y>>>8,c[r]=y<<16|y>>>16,u[r]=y<<8|y>>>24,d[r]=y,f?(f=a^h[h[h[m^a]]],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 o,a;const l=this.keySchedule=new Uint32Array(i),c=this.invKeySchedule=new Uint32Array(i),u=this.sBox,d=this.rcon,h=this.invSubMix,f=h[0],p=h[1],g=h[2],m=h[3];let y,v;for(o=0;o<i;o++)o<s?y=l[o]=t[o]:(v=y,o%s==0?(v=v<<8|v>>>24,v=u[v>>>24]<<24|u[v>>>16&255]<<16|u[v>>>8&255]<<8|u[255&v],v^=d[o/s|0]<<24):s>6&&o%s==4&&(v=u[v>>>24]<<24|u[v>>>16&255]<<16|u[v>>>8&255]<<8|u[255&v]),l[o]=y=(l[o-s]^v)>>>0);for(a=0;a<i;a++)o=i-a,v=3&a?l[o]:l[o-4],c[a]=a<4||o<=4?v:f[u[v>>>24]]^p[u[v>>>16&255]]^g[u[v>>>8&255]]^m[u[255&v]],c[a]=c[a]>>>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,o=this.invSubMix,a=o[0],l=o[1],c=o[2],u=o[3],d=this.uint8ArrayToUint32Array_(r);let h=d[0],f=d[1],p=d[2],g=d[3];const m=new Int32Array(e),y=new Int32Array(m.length);let v,b,w,E,T,S,C,k,A,_,I,R,L,D;const x=this.networkToHostOrderSwap;for(;t<m.length;){for(A=x(m[t]),_=x(m[t+1]),I=x(m[t+2]),R=x(m[t+3]),T=A^s[0],S=R^s[1],C=I^s[2],k=_^s[3],L=4,D=1;D<n;D++)v=a[T>>>24]^l[S>>16&255]^c[C>>8&255]^u[255&k]^s[L],b=a[S>>>24]^l[C>>16&255]^c[k>>8&255]^u[255&T]^s[L+1],w=a[C>>>24]^l[k>>16&255]^c[T>>8&255]^u[255&S]^s[L+2],E=a[k>>>24]^l[T>>16&255]^c[S>>8&255]^u[255&C]^s[L+3],T=v,S=b,C=w,k=E,L+=4;v=i[T>>>24]<<24^i[S>>16&255]<<16^i[C>>8&255]<<8^i[255&k]^s[L],b=i[S>>>24]<<24^i[C>>16&255]<<16^i[k>>8&255]<<8^i[255&T]^s[L+1],w=i[C>>>24]<<24^i[k>>16&255]<<16^i[T>>8&255]<<8^i[255&S]^s[L+2],E=i[k>>>24]<<24^i[T>>16&255]<<16^i[S>>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=_,p=I,g=R,t+=4}return y.buffer}}class Am{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?Vf(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=Sp(i,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;n&&(r=n);let a=this.softwareDecrypter;a||(a=this.softwareDecrypter=new km),a.expandKey(t);const l=s;return this.currentResult=a.decrypt(o.buffer,0,r),this.currentIV=Vf(o,-16).buffer,l||null}webCryptoDecrypt(e,t,r){const n=this.subtle;return this.key===t&&this.fastAesKey||(this.key=t,this.fastAesKey=new Cm(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 Sm(n,new Uint8Array(r)).decrypt(e.buffer,t)})).catch((n=>(bf.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=Vf(e,0,r),this.remainderData=Vf(e,r)),t}logOnce(e){this.logEnabled&&(bf.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const _m=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},Im="STOPPED",Rm="IDLE",Lm="KEY_LOADING",Dm="FRAG_LOADING",xm="FRAG_LOADING_WAITING_RETRY",Om="WAITING_TRACK",Pm="PARSING",Mm="PARSED",Fm="ENDED",Nm="ERROR",Um="WAITING_INIT_PTS",Bm="WAITING_LEVEL";class jm 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=Im,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=bf.log.bind(bf,`${n}:`),this.warn=bf.warn.bind(bf,`${n}:`),this.hls=e,this.fragmentLoader=new um(e.config),this.keyLoader=r,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Am(e.config),e.on(hf.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=Im}_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 mm.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===Im&&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,o=mm.bufferInfo(n||r,i,e.maxBufferHole);if(this.log(`media seeking to ${df(i)?i.toFixed(3):i}, state: ${s}`),this.state===Fm)this.resetLoadingState();else if(t){const r=e.maxFragLookUpTolerance,n=t.start-r,s=t.start+t.duration+r;if(!o.len||s<o.start||n>o.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||o.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=Im,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===Dm||!this.fragCurrent&&r===Pm)&&(this.fragmentTracker.removeFragment(e),this.state=Rm):("payload"in t&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(hf.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))})).catch((t=>{this.state!==Im&&this.state!==Nm&&(this.warn(t),this.resetFragmentLoading(e))}))}clearTrackerIfNeeded(e){var t;const{fragmentTracker:r}=this;if(r.getState(e)===nm){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)===sm&&r.removeFragment(e))}flushMainBuffer(e,t,r=null){if(!(e-t))return;const n={startOffset:e,endOffset:t,type:r};this.hls.trigger(hf.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(hf.ERROR,{type:ff.MEDIA_ERROR,details:pf.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t})).then((n=>{const s=self.performance.now();return r.trigger(hf.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 o=e.stats;this.state=Rm,t.fragmentError=0,e.data=new Uint8Array(r.payload),o.parsing.start=o.buffering.start=self.performance.now(),o.parsing.end=o.buffering.end=self.performance.now(),r.frag===n&&s.trigger(hf.FRAG_BUFFERED,{stats:o,frag:n,part:null,id:e.type}),this.tick()})).catch((t=>{this.state!==Im&&this.state!==Nm&&(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 o=this.mediaBuffer?this.mediaBuffer:this.media;this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.playlistType===sg?"level":"track"} ${e.level} (frag:[${(null!=(r=e.startPTS)?r:NaN).toFixed(3)}-${(null!=(n=e.endPTS)?n:NaN).toFixed(3)}] > buffer:${o?_m(mm.getBuffered(o)):"(detached)"})`),this.state=Rm,o&&(!this.loadedmetadata&&e.type==sg&&o.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)),o=new ym(r.level,r.sn,r.stats.chunkCount+1,0,n?n.index:-1,!i);t.flush(o)}_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 o=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=Lm,this.fragCurrent=e,o=this.keyLoader.load(e).then((e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(hf.KEY_LOADED,e),this.state===Lm&&(this.state=Rm),e})),this.hls.trigger(hf.KEY_LOADING,{frag:e}),null===this.fragCurrent&&(o=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 a=this.getNextPart(s,e,r);if(a>-1){const l=s[a];let c;return this.log(`Loading part sn: ${e.sn} p: ${l.index} cc: ${e.cc} of playlist [${i.startSN}-${i.endSN}] parts [0-${a}-${s.length-1}] ${"[stream-controller]"===this.logPrefix?"level":"track"}: ${e.level}, target: ${parseFloat(r.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=Dm,c=o?o.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(hf.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))}`),df(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Dm;const a=this.config.progressive;let l;return l=a&&o?o.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,a?n:void 0),o]).then((([e])=>(!a&&e&&n&&n(e),e))).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(hf.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 o;const a=[],l=null==(o=r.details)?void 0:o.partList,c=t=>{this.fragmentLoader.loadPart(e,t,n).then((n=>{a[t.index]=n;const i=n.part;this.hls.trigger(hf.FRAG_LOADED,n);const o=Og(r,e.sn,t.index+1)||Pg(l,e.sn,t.index+1);if(!o)return s({frag:e,part:i,partsLoaded:a});c(o)})).catch(i)};c(t)}))}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===pf.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(hf.ERROR,t)}else this.hls.trigger(hf.ERROR,{type:ff.OTHER_ERROR,details:pf.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==Pm)return void(this.fragCurrent||this.state===Im||this.state===Nm||(this.state=Rm));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 o=t[n],a=i>-1?Og(o,s,i):null,l=a?a.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)}(o,s,r);return l?(r&&r!==l&&(l.stats=r.stats),{frag:l,part:a,level:o}):null}bufferFragmentData(e,t,r,n,s){var i;if(!e||this.state!==Pm)return;const{data1:o,data2:a}=e;let l=o;if(o&&a&&(l=Sp(o,a)),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(hf.BUFFER_APPENDING,c),e.dropped&&e.independent&&!r){if(s)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!mm.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);const r=t.currentTime,n=mm.bufferInfo(t,r,0),s=e.duration,i=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),o=Math.max(Math.min(e.start-i,n.end-i),r+i);e.start-o>i&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){const r=this.getLoadPosition();return df(r)?this.getFwdBufferInfoAtPos(e,r,t):null}getFwdBufferInfoAtPos(e,t,r){const{config:{maxBufferHole:n}}=this,s=mm.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 mm.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=sg){const r=this.fragmentTracker.getAppendedFrag(e,sg);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 o;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||(o=this.getInitialLiveFragment(t,r),this.startPosition=o?this.hls.liveSyncPosition||o.start:e)}else e<=i&&(o=r[0]);if(!o){const r=s.lowLatencyMode?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,r,t)}return this.mapToInitFragWhenRequired(o)}isLoopLoading(e,t){const r=this.fragmentTracker.getState(e);return(r===im||r===sm&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,r,n,s){const i=e.gap,o=this.getNextFragment(this.nextLoadPosition,t);if(null===o)return o;if(e=o,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 o=0,a=e.length;o<a;o++){const a=e[o];if(i=i&&!a.independent,n>-1&&r<a.start)break;const l=a.loaded;l?n=-1:(s||a.independent||i)&&a.fragment===t&&(n=o),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||!df(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(Kg(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 jg(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:o}=r;const{fragmentHint:a}=r,l=n.maxFragLookUpTolerance,c=r.partList,u=!!(n.lowLatencyMode&&null!=c&&c.length&&a);let d;if(u&&a&&!this.bitrateTest&&(i=i.concat(a),o=a.sn),e<t){d=$g(s,i,e,e>t-l?0:l)}else d=i[i.length-1];if(d){const e=d.sn-r.startSN,t=this.fragmentTracker.getState(d);if((t===im||t===sm&&d.gap)&&(s=d),s&&d.sn===s.sn&&(!u||c[0].fragment.sn>d.sn)){if(s&&d.level===s.level){const t=i[e+1];d=d.sn<o&&this.fragmentTracker.getState(t)!==im?t:null}}}return d}synchronizeToLiveEdge(e){const{config:t,media:r}=this;if(!r)return;const n=this.hls.liveSyncPosition,s=r.currentTime,i=e.fragments[0].start,o=e.edge,a=s>=i-t.maxFragLookUpTolerance&&s<=o;if(null!==n&&r.duration>n&&(s<n||!a)){const i=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!a&&r.readyState<4||s<o-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: ${o}, 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,o=e.fragments.length;if(!o)return this.warn("No fragments in live playlist"),0;const a=e.fragments[0].start,l=!t,c=e.alignedSliding&&df(a);if(l||!c&&!a){Em(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: ${o}`),r}return a}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&&df(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===xm)||(this.state=Rm)}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===pf.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(r,!0);const i=t.errorAction,{action:o,retryCount:a=0,retryConfig:l}=i||{};if(i&&o===Vg&&l){var c;this.resetStartWhenNotLoaded(null!=(c=this.levelLastLoaded)?c:r.level);const n=Ng(l,a);this.warn(`Fragment ${r.sn} of ${e} ${r.level} errored with ${t.details}, retrying loading ${a+1}/${l.maxNumRetry} in ${n}ms`),i.resolved=!0,this.retryDate=self.performance.now()+n,this.state=xm}else l&&i?(this.resetFragmentErrors(e),a<l.maxNumRetry?s||(i.resolved=!0):bf.warn(`${t.details} reached or exceeded max retry (${a})`)):(null==i?void 0:i.action)===Hg?this.state=Bm:this.state=Nm;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===Pm||this.state===Mm){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===ig&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==Im&&(this.state=Rm)}afterBufferFlushed(e,t,r){if(!e)return;const n=mm.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,r),this.state===Fm&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=Rm}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 o=e.elementaryStreams[s];if(o){const a=o.endPTS-o.startPTS;if(a<=0)return this.warn(`Could not parse fragment ${e.sn} ${s} duration reliably (${a})`),t||!1;const l=n?0:Rg(i,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS);return this.hls.trigger(hf.LEVEL_PTS_UPDATED,{details:i,level:r,drift:l,type:s,frag:e,start:o.startPTS,end:o.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(hf.ERROR,{type:ff.MEDIA_ERROR,details:pf.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=Mm,this.hls.trigger(hf.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 $m(){return self.SourceBuffer||self.WebKitSourceBuffer}function qm(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class Km{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=Sp(this.cachedData,e),this.cachedData=null);let r,n=Yf(e,0),s=n?n.length:0;const i=this._audioTrack,o=this._id3Track,a=n?(e=>{const t=ep(e);for(let e=0;e<t.length;e++){const r=t[e];if(Jf(r))return ip(r)}})(n):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&df(a))&&(this.basePTS=Gm(a,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),n&&n.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:pg,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 Xf(e,s)?(n=Yf(e,s),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:pg,duration:Number.POSITIVE_INFINITY}),s+=n.length,r=s):s++;if(s===l&&r!==l){const t=Vf(e,r);this.cachedData?this.cachedData=Sp(this.cachedData,t):this.cachedData=t}}return{audioTrack:i,videoTrack:qm(),id3Track:o,textTrack:qm()}}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:qm(),id3Track:this._id3Track,textTrack:qm()}}destroy(){}}const Gm=(e,t,r)=>{if(df(e))return 90*e;return 9e4*t+(r?9e4*r.baseTime/r.timescale:0)};function Hm(e,t){return 255===e[t]&&240==(246&e[t+1])}function Vm(e,t){return 1&e[t+1]?7:9}function zm(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function Wm(e,t){return t+1<e.length&&Hm(e,t)}function Ym(e,t){if(Wm(e,t)){const r=Vm(e,t);if(t+r>=e.length)return!1;const n=zm(e,t);if(n<=r)return!1;const s=t+n;return s===e.length||Wm(e,s)}return!1}function Qm(e,t,r,n,s){if(!e.samplerate){const i=function(e,t,r,n){let s,i,o,a;const l=navigator.userAgent.toLowerCase(),c=n,u=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=1+((192&t[r+2])>>>6);const d=(60&t[r+2])>>>2;if(!(d>u.length-1))return o=(1&t[r+2])<<2,o|=(192&t[r+3])>>>6,bf.log(`manifest codec:${n}, ADTS type:${s}, samplingIndex:${d}`),/firefox/i.test(l)?d>=6?(s=5,a=new Array(4),i=d-3):(s=2,a=new Array(2),i=d):-1!==l.indexOf("android")?(s=2,a=new Array(2),i=d):(s=5,a=new Array(4),n&&(-1!==n.indexOf("mp4a.40.29")||-1!==n.indexOf("mp4a.40.5"))||!n&&d>=6?i=d-3:((n&&-1!==n.indexOf("mp4a.40.2")&&(d>=6&&1===o||/vivaldi/i.test(l))||!n&&1===o)&&(s=2,a=new Array(2)),i=d)),a[0]=s<<3,a[0]|=(14&d)>>1,a[1]|=(1&d)<<7,a[1]|=o<<3,5===s&&(a[1]|=(14&i)>>1,a[2]=(1&i)<<7,a[2]|=8,a[3]=0),{config:a,samplerate:u[d],channelCount:o,codec:"mp4a.40."+s,manifestCodec:c};e.trigger(hf.ERROR,{type:ff.MEDIA_ERROR,details:pf.FRAG_PARSING_ERROR,fatal:!0,reason:`invalid ADTS sampling index:${d}`})}(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,bf.log(`parsed codec:${e.codec}, rate:${i.samplerate}, channels:${i.channelCount}`)}}function Xm(e){return 9216e4/e}function Jm(e,t,r,n,s){const i=n+s*Xm(e.samplerate),o=function(e,t){const r=Vm(e,t);if(t+r<=e.length){const n=zm(e,t)-r;if(n>0)return{headerLength:r,frameLength:n}}}(t,r);let a;if(o){const{frameLength:n,headerLength:s}=o,l=s+n,c=Math.max(0,r+l-t.length);c?(a=new Uint8Array(l-s),a.set(t.subarray(r+s,t.length),0)):a=t.subarray(r+s,r+l);const u={unit:a,pts:i};return c||e.samples.push(u),{sample:u,length:l,missing:c}}const l=t.length-r;a=new Uint8Array(l),a.set(t.subarray(r,t.length),0);return{sample:{unit:a,pts:i},length:l,missing:-1}}const Zm=/\/emsg[-/]ID3/i;let ey=null;const ty=[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],ry=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],ny=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],sy=[0,1,1,4];function iy(e,t,r,n,s){if(r+24>t.length)return;const i=oy(t,r);if(i&&r+i.frameLength<=t.length){const o=n+s*(9e4*i.samplesPerFrame/i.sampleRate),a={unit:t.subarray(r,r+i.frameLength),pts:o,dts:o};return e.config=[],e.channelCount=i.channelCount,e.samplerate=i.sampleRate,e.samples.push(a),{sample:a,length:i.frameLength,missing:0}}}function oy(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 o=e[t+2]>>1&1,a=e[t+3]>>6,l=1e3*ty[14*(3===r?3-n:3===n?3:4)+s-1],c=ry[3*(3===r?0:2===r?1:2)+i],u=3===a?1:2,d=ny[r][n],h=sy[n],f=8*d*h,p=Math.floor(d*l/c+o)*h;if(null===ey){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ey=e?parseInt(e[1]):0}return!!ey&&ey<=87&&2===n&&l>=224e3&&0===a&&(e[t+3]=128|e[t+3]),{sampleRate:c,channelCount:u,frameLength:p,samplesPerFrame:f}}}function ay(e,t){return 255===e[t]&&224==(224&e[t+1])&&0!=(6&e[t+1])}function ly(e,t){return t+1<e.length&&ay(e,t)}function cy(e,t){if(t+1<e.length&&ay(e,t)){const r=4,n=oy(e,t);let s=r;null!=n&&n.frameLength&&(s=n.frameLength);const i=t+s;return i===e.length||ly(e,i)}return!1}class uy{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&&bf.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,o=0;const a=this.readUByte.bind(this),l=this.readBits.bind(this),c=this.readUEG.bind(this),u=this.readBoolean.bind(this),d=this.skipBits.bind(this),h=this.skipEG.bind(this),f=this.skipUEG.bind(this),p=this.skipScalingList.bind(this);a();const g=a();if(l(5),d(3),a(),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&&d(1),f(),f(),d(1),u())for(t=3!==e?8:12,r=0;r<t;r++)u()&&p(r<6?16:64)}f();const m=c();if(0===m)c();else if(1===m)for(d(1),h(),h(),e=c(),r=0;r<e;r++)h();f(),d(1);const y=c(),v=c(),b=l(1);0===b&&d(1),d(1),u()&&(n=c(),s=c(),i=c(),o=c());let w=[1,1];if(u()&&u()){switch(a()){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=[a()<<8|a(),a()<<8|a()]}}return{width:Math.ceil(16*(y+1)-2*n-2*s),height:(2-b)*(v+1)*16-(b?2:4)*(i+o),pixelRatio:w}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class dy{constructor(e,t,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new Am(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=_p(s.data),o=this.getAvcEncryptedData(i);this.decryptBuffer(o.buffer).then((o=>{s.data=this.getAvcDecryptedUnit(i,o),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 hy=188;class fy{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=fy.syncOffset(e);return t>0&&bf.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-hy)+1,n=0;for(;n<r;){let s=!1,i=-1,o=0;for(let a=n;a<t;a+=hy){if(71!==e[a]){if(o)return-1;break}if(o++,-1===i&&(i=a,0!==i&&(r=Math.min(i+18612,e.length-hy)+1)),s||(s=0===gy(e,a)),s&&o>1&&(0===i&&o>2||a+hy>r))return i}n++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:hp[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=fy.createTrack("video"),this._audioTrack=fy.createTrack("audio",n),this._id3Track=fy.createTrack("id3"),this._txtTrack=fy.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,o=this._audioTrack,a=this._id3Track,l=this._txtTrack;let c=i.pid,u=i.pesData,d=o.pid,h=a.pid,f=o.pesData,p=a.pesData,g=null,m=this.pmtParsed,y=this._pmtId,v=e.length;if(this.remainderData&&(v=(e=Sp(this.remainderData,e)).length,this.remainderData=null),v<hy&&!n)return this.remainderData=e,{audioTrack:o,videoTrack:i,id3Track:a,textTrack:l};const b=Math.max(0,fy.syncOffset(e));v-=(v-b)%hy,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+=hy)if(71===e[t]){const n=!!(64&e[t+1]),v=gy(e,t);let w;if((48&e[t+3])>>4>1){if(w=t+5+e[t+4],w===t+hy)continue}else w=t+4;switch(v){case c:n&&(u&&(s=vy(u))&&this.parseAVCPES(i,l,s,!1),u={data:[],size:0}),u&&(u.data.push(e.subarray(w,t+hy)),u.size+=t+hy-w);break;case d:if(n){if(f&&(s=vy(f)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,s);break;case"mp3":this.parseMPEGPES(o,s)}f={data:[],size:0}}f&&(f.data.push(e.subarray(w,t+hy)),f.size+=t+hy-w);break;case h:n&&(p&&(s=vy(p))&&this.parseID3PES(a,s),p={data:[],size:0}),p&&(p.data.push(e.subarray(w,t+hy)),p.size+=t+hy-w);break;case 0:n&&(w+=e[w]+1),y=this._pmtId=my(e,w);break;case y:{n&&(w+=e[w]+1);const s=yy(e,w,this.typeSupported,r);c=s.avc,c>0&&(i.pid=c),d=s.audio,d>0&&(o.pid=d,o.segmentCodec=s.segmentCodec),h=s.id3,h>0&&(a.pid=h),null===g||m||(bf.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(hf.ERROR,hf.ERROR,{type:ff.MEDIA_ERROR,details:pf.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message})}i.pesData=u,o.pesData=f,a.pesData=p;const E={audioTrack:o,videoTrack:i,id3Track:a,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,o=t.pesData,a=n.pesData;let l;if(i&&(l=vy(i))?(this.parseAVCPES(r,s,l,!0),r.pesData=null):r.pesData=i,o&&(l=vy(o))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l)}t.pesData=null}else null!=o&&o.size&&bf.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;a&&(l=vy(a))?(this.parseID3PES(n,l),n.pesData=null):n.pesData=a}demuxSampleAes(e,t,r){const n=this.demux(e,r,!0,!this.config.progressive),s=this.sampleAes=new dy(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,o=this.avcSample,a=!1;r.data=null,o&&s.length&&!e.audFound&&(by(o,e),o=this.avcSample=py(!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(a&&s.length>4){const e=new uy(s).readSliceType();2!==e&&4!==e&&7!==e&&9!==e||(t=!0)}var l;if(t)null!=(l=o)&&l.frame&&!o.key&&(by(o,e),o=this.avcSample=null);o||(o=this.avcSample=py(!0,r.pts,r.dts,"")),o.frame=!0,o.key=t;break}case 5:i=!0,null!=(s=o)&&s.frame&&!o.key&&(by(o,e),o=this.avcSample=null),o||(o=this.avcSample=py(!0,r.pts,r.dts,"")),o.key=!0,o.frame=!0;break;case 6:i=!0,Ap(n.data,1,r.pts,t.samples);break;case 7:if(i=!0,a=!0,!e.sps){const t=n.data,r=new uy(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,o&&by(o,e),o=this.avcSample=py(!1,r.pts,r.dts,"");break;case 12:i=!0;break;default:i=!1,o&&(o.debug+="unknown NAL "+n.type+" ")}if(o&&i){o.units.push(n)}})),n&&o&&(by(o,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 o,a,l,c=0,u=-1,d=0;for(-1===n&&(u=0,d=31&t[0],n=0,c=1);c<r;)if(o=t[c++],n)if(1!==n)if(o)if(1===o){if(u>=0){const e={data:t.subarray(u,c-n-1),type:d};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)),a=c-n-1,a>0)){const e=new Uint8Array(r.data.byteLength+a);e.set(r.data,0),e.set(t.subarray(0,a),r.data.byteLength),r.data=e,r.state=0}}c<r?(l=31&t[c],u=c,d=l,n=0):n=-1}else n=0;else n=3;else n=o?0:2;else n=o?0:1;if(u>=0&&n>=0){const e={data:t.subarray(u,r),type:d,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,o,a=t.data;if(n){this.aacOverFlow=null;const t=n.missing,s=n.sample.unit.byteLength;if(-1===t){const e=new Uint8Array(s+a.byteLength);e.set(n.sample.unit,0),e.set(a,s),a=e}else{const i=s-t;n.sample.unit.set(a.subarray(0,t),i),e.samples.push(n.sample),r=n.missing}}for(s=r,i=a.length;s<i-1&&!Wm(a,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(bf.warn(`parsing error: ${e}`),this.observer.emit(hf.ERROR,hf.ERROR,{type:ff.MEDIA_ERROR,details:pf.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:r,reason:e}),!t)return}if(Qm(e,this.observer,a,s,this.audioCodec),void 0!==t.pts)o=t.pts;else{if(!n)return void bf.warn("[tsdemuxer]: AAC PES unknown PTS");{const t=Xm(e.samplerate);o=n.sample.pts+t}}let l,c=0;for(;s<i;){if(l=Jm(e,a,s,o,c),s+=l.length,l.missing){this.aacOverFlow=l;break}for(c++;s<i-1&&!Wm(a,s);s++);}}parseMPEGPES(e,t){const r=t.data,n=r.length;let s=0,i=0;const o=t.pts;if(void 0!==o)for(;i<n;)if(ly(r,i)){const t=iy(e,r,i,o,s);if(!t)break;i+=t.length,s++}else i++;else bf.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseID3PES(e,t){if(void 0===t.pts)return void bf.warn("[tsdemuxer]: ID3 PES unknown PTS");const r=uf({},t,{type:this._avcTrack?mg:pg,duration:Number.POSITIVE_INFINITY});e.samples.push(r)}}function py(e,t,r,n){return{key:e,frame:!1,pts:t,dts:r,units:[],debug:n,length:0}}function gy(e,t){return((31&e[t+1])<<8)+e[t+2]}function my(e,t){return(31&e[t+10])<<8|e[t+11]}function yy(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=gy(e,t);switch(e[t]){case 207:if(!n){bf.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){bf.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?bf.log("MPEG audio found, not supported in this browser"):-1===s.audio&&(s.audio=i,s.segmentCodec="mp3");break;case 36:bf.warn("Unsupported HEVC stream type found")}t+=5+((15&e[t+3])<<8|e[t+4])}return s}function vy(e){let t,r,n,s,i,o=0;const a=e.data;if(!e||0===e.size)return null;for(;a[0].length<19&&a.length>1;){const e=new Uint8Array(a[0].length+a[1].length);e.set(a[0]),e.set(a[1],a[0].length),a[0]=e,a.splice(1,1)}t=a[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&&(bf.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 u=new Uint8Array(e.size);for(let e=0,r=a.length;e<r;e++){t=a[e];let r=t.byteLength;if(c){if(c>r){c-=r;continue}t=t.subarray(c),r-=c,c=0}u.set(t,o),o+=r}return r&&(r-=n+3),{data:u,pts:s,dts:i,len:r}}return null}function by(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&&bf.log(e.pts+"/"+e.dts+":"+e.debug)}class wy{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 Ey=Math.pow(2,32)-1;class Ty{static init(){let e;for(e in Ty.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:[]},Ty.types)Ty.types.hasOwnProperty(e)&&(Ty.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]);Ty.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]);Ty.STTS=Ty.STSC=Ty.STCO=s,Ty.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Ty.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Ty.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Ty.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const i=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),a=new Uint8Array([0,0,0,1]);Ty.FTYP=Ty.box(Ty.types.ftyp,i,a,i,o),Ty.DINF=Ty.box(Ty.types.dinf,Ty.box(Ty.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 Ty.box(Ty.types.hdlr,Ty.HDLR_TYPES[e])}static mdat(e){return Ty.box(Ty.types.mdat,e)}static mdhd(e,t){t*=e;const r=Math.floor(t/(Ey+1)),n=Math.floor(t%(Ey+1));return Ty.box(Ty.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 Ty.box(Ty.types.mdia,Ty.mdhd(e.timescale,e.duration),Ty.hdlr(e.type),Ty.minf(e))}static mfhd(e){return Ty.box(Ty.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?Ty.box(Ty.types.minf,Ty.box(Ty.types.smhd,Ty.SMHD),Ty.DINF,Ty.stbl(e)):Ty.box(Ty.types.minf,Ty.box(Ty.types.vmhd,Ty.VMHD),Ty.DINF,Ty.stbl(e))}static moof(e,t,r){return Ty.box(Ty.types.moof,Ty.mfhd(e),Ty.traf(r,t))}static moov(e){let t=e.length;const r=[];for(;t--;)r[t]=Ty.trak(e[t]);return Ty.box.apply(null,[Ty.types.moov,Ty.mvhd(e[0].timescale,e[0].duration)].concat(r).concat(Ty.mvex(e)))}static mvex(e){let t=e.length;const r=[];for(;t--;)r[t]=Ty.trex(e[t]);return Ty.box.apply(null,[Ty.types.mvex,...r])}static mvhd(e,t){t*=e;const r=Math.floor(t/(Ey+1)),n=Math.floor(t%(Ey+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 Ty.box(Ty.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 Ty.box(Ty.types.sdtp,r)}static stbl(e){return Ty.box(Ty.types.stbl,Ty.stsd(e),Ty.box(Ty.types.stts,Ty.STTS),Ty.box(Ty.types.stsc,Ty.STSC),Ty.box(Ty.types.stsz,Ty.STSZ),Ty.box(Ty.types.stco,Ty.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 o=Ty.box(Ty.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|e.sps.length].concat(s).concat([e.pps.length]).concat(i))),a=e.width,l=e.height,c=e.pixelRatio[0],u=e.pixelRatio[1];return Ty.box(Ty.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,a>>8&255,255&a,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]),o,Ty.box(Ty.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Ty.box(Ty.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,255&c,u>>24,u>>16&255,u>>8&255,255&u])))}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 Ty.box(Ty.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]),Ty.box(Ty.types.esds,Ty.esds(e)))}static mp3(e){const t=e.samplerate;return Ty.box(Ty.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?Ty.box(Ty.types.stsd,Ty.STSD,Ty.mp3(e)):Ty.box(Ty.types.stsd,Ty.STSD,Ty.mp4a(e)):Ty.box(Ty.types.stsd,Ty.STSD,Ty.avc1(e))}static tkhd(e){const t=e.id,r=e.duration*e.timescale,n=e.width,s=e.height,i=Math.floor(r/(Ey+1)),o=Math.floor(r%(Ey+1));return Ty.box(Ty.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,o>>24,o>>16&255,o>>8&255,255&o,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=Ty.sdtp(e),n=e.id,s=Math.floor(t/(Ey+1)),i=Math.floor(t%(Ey+1));return Ty.box(Ty.types.traf,Ty.box(Ty.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),Ty.box(Ty.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])),Ty.trun(e,r.length+16+20+8+16+8+8),r)}static trak(e){return e.duration=e.duration||4294967295,Ty.box(Ty.types.trak,Ty.tkhd(e),Ty.mdia(e))}static trex(e){const t=e.id;return Ty.box(Ty.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 o,a,l,c,u,d;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),o=0;o<n;o++)a=r[o],l=a.duration,c=a.size,u=a.flags,d=a.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,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,61440&u.degradPrio,15&u.degradPrio,d>>>24&255,d>>>16&255,d>>>8&255,255&d],12+16*o);return Ty.box(Ty.types.trun,i)}static initSegment(e){Ty.types||Ty.init();const t=Ty.moov(e),r=new Uint8Array(Ty.FTYP.byteLength+t.byteLength);return r.set(Ty.FTYP),r.set(t,Ty.FTYP.byteLength),r}}Ty.types=void 0,Ty.HDLR_TYPES=void 0,Ty.STTS=void 0,Ty.STSC=void 0,Ty.STCO=void 0,Ty.STSZ=void 0,Ty.VMHD=void 0,Ty.SMHD=void 0,Ty.STSD=void 0,Ty.FTYP=void 0,Ty.DINF=void 0;function Sy(e,t,r=1,n=!1){const s=e*t*r;return n?Math.round(s):s}function Cy(e,t=!1){return Sy(e,1e3,1/9e4,t)}let ky,Ay=null,_y=null;class Iy{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===Ay){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ay=e?parseInt(e[1]):0}if(null===_y){const e=navigator.userAgent.match(/Safari\/(\d+)/i);_y=e?parseInt(e[1]):0}}destroy(){}resetTimeStamp(e){bf.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){bf.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){bf.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,Ry(e,r.pts)):n>0?e:r.pts}),e[0].pts);return t&&bf.debug("PTS rollover detected"),r}remux(e,t,r,n,s,i,o,a){let l,c,u,d,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=o&&v>0||v>1;if((!m||b)&&(!y||w)||this.ISGenerated||o){this.ISGenerated||(u=this.generateIS(e,t,s,i));const r=this.isVideoContiguous;let n,o=-1;if(w&&(o=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,o>0){bf.warn(`[mp4-remuxer]: Dropped ${o} out of ${v} video samples due to a missing keyframe`);const e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(o),t.dropped+=o,g+=(t.samples[0].pts-e)/t.inputTimeScale,n=g}else-1===o&&(bf.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=(Ry(e.samples[0].pts,r)-r)/t.inputTimeScale;p+=Math.max(0,n),g+=Math.max(0,-n)}if(b){if(e.samplerate||(bf.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),u=this.generateIS(e,t,s,i)),c=this.remuxAudio(e,p,this.isAudioContiguous,i,y||w||a===ig?g:void 0),w){const n=c?c.endPTS-c.startPTS:0;t.inputTimeScale||(bf.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),u=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=o,l.independent=-1!==o,l.firstKeyFramePTS=n)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(h=Ly(r,s,this._initPTS,this._initDTS)),n.samples.length&&(d=Dy(n,s,this._initPTS))),{audio:c,video:l,initSegment:u,independent:f,text:d,id3:h}}generateIS(e,t,r,n){const s=e.samples,i=t.samples,o=this.typeSupported,a={},l=this._initPTS;let c,u,d,h=!l||n,f="audio/mp4";if(h&&(c=u=1/0),e.config&&s.length){if(e.timescale=e.samplerate,"mp3"===e.segmentCodec)o.mpeg?(f="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");a.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&o.mpeg?new Uint8Array(0):Ty.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(d=e.inputTimeScale,l&&d===l.timescale?h=!1:c=u=s[0].pts-Math.round(d*r))}if(t.sps&&t.pps&&i.length&&(t.timescale=t.inputTimeScale,a.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Ty.initSegment([t]),metadata:{width:t.width,height:t.height}},h))if(d=t.inputTimeScale,l&&d===l.timescale)h=!1;else{const e=this.getVideoStartPts(i),t=Math.round(d*r);u=Math.min(u,Ry(i[0].dts,e)-t),c=Math.min(c,e-t)}if(Object.keys(a).length)return this.ISGenerated=!0,h?(this._initPTS={baseTime:c,timescale:d},this._initDTS={baseTime:u,timescale:d}):c=d=void 0,{tracks:a,initPTS:c,timescale:d}}remuxVideo(e,t,r,n){const s=e.inputTimeScale,i=e.samples,o=[],a=i.length,l=this._initPTS;let c,u,d=this.nextAvcDts,h=8,f=this.videoSampleDuration,p=Number.POSITIVE_INFINITY,g=Number.NEGATIVE_INFINITY,m=!1;if(!r||null===d){d=t*s-(i[0].pts-Ry(i[0].dts,i[0].pts))}const y=l.baseTime*s/l.timescale;for(let e=0;e<a;e++){const t=i[e];t.pts=Ry(t.pts-y,d),t.dts=Ry(t.dts-y,d),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,u=i[i.length-1].dts;const v=u-c,b=v?Math.round(v/(a-1)):f||e.inputTimeScale/30;if(r){const e=c-d,t=e>b,r=e<-1;if((t||r)&&(t?bf.warn(`AVC: ${Cy(e,!0)} ms (${e}dts) hole between fragments detected, filling it`):bf.warn(`AVC: ${Cy(-e,!0)} ms (${e}dts) overlapping between fragments detected`),!r||d>=i[0].pts)){c=d;const t=i[0].pts-e;i[0].dts=c,i[0].pts=t,bf.log(`Video: First PTS/DTS adjusted: ${Cy(t,!0)}/${Cy(c,!0)}, delta: ${Cy(e,!0)} ms`)}}c=Math.max(0,c);let w=0,E=0;for(let e=0;e<a;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)}u=i[a-1].dts;const T=E+4*w+8;let S;try{S=new Uint8Array(T)}catch(e){return void this.observer.emit(hf.ERROR,hf.ERROR,{type:ff.MUX_ERROR,details:pf.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:T,reason:`fail allocating video mdat ${T}`})}const C=new DataView(S.buffer);C.setUint32(0,T),S.set(Ty.types.mdat,4);let k=!1,A=Number.POSITIVE_INFINITY,_=Number.POSITIVE_INFINITY,I=Number.NEGATIVE_INFINITY,R=Number.NEGATIVE_INFINITY;for(let e=0;e<a;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,S.set(n,h),h+=s,c+=4+s}if(e<a-1)f=i[e+1].dts-t.dts,l=i[e+1].pts-t.pts;else{const r=this.config,o=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-o,f<0?f=o:k=!0,bf.log(`[mp4-remuxer]: It is approximately ${i/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=o}else f=o}const u=Math.round(t.pts-t.dts);A=Math.min(A,f),I=Math.max(I,f),_=Math.min(_,l),R=Math.max(R,l),o.push(new xy(t.key,f,c,u))}if(o.length)if(Ay){if(Ay<70){const e=o[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(_y&&R-_<I-A&&b/I<.025&&0===o[0].cts){bf.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=o.length;t<r;t++){const n=e+o[t].duration,s=e+o[t].cts;if(t<r-1){const e=n+o[t+1].cts;o[t].duration=e-s}else o[t].duration=t?o[t-1].duration:b;o[t].cts=0,e=n}}f=k||!f?b:f,this.nextAvcDts=d=u+f,this.videoSampleDuration=f,this.isVideoContiguous=!0;const L={data1:Ty.moof(e.sequenceNumber++,c,uf({},e,{samples:o})),data2:S,startPTS:p/s,endPTS:(g+f)/s,startDTS:c/s,endDTS:d/s,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,L}remuxAudio(e,t,r,n,s){const i=e.inputTimeScale,o=i/(e.samplerate?e.samplerate:i),a="aac"===e.segmentCodec?1024:1152,l=a*o,c=this._initPTS,u="mp3"===e.segmentCodec&&this.typeSupported.mpeg,d=[],h=void 0!==s;let f=e.samples,p=u?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(Ry(f[0].pts-y,m)-g)<20*l),f.forEach((function(e){e.pts=Ry(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],o=s.pts,a=o-n,c=Math.abs(1e3*a/i);if(a<=-t*l&&h)0===r&&(bf.warn(`Audio frame @ ${(o/i).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*a/i)} ms.`),this.nextAudioPts=g=n=o);else if(a>=t*l&&c<1e4&&h){let t=Math.round(a/l);n=o-t*l,n<0&&(t--,n+=l),0===r&&(this.nextAudioPts=g=n),bf.warn(`[mp4-remuxer]: Injecting ${t} audio frame @ ${(n/i).toFixed(3)}s due to ${Math.round(1e3*a/i)} ms gap.`);for(let i=0;i<t;i++){const t=Math.max(n,0);let i=wy.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);i||(bf.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,T=f.length;for(;T--;)E+=f[T].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){d[t-1].duration=Math.round((i-w)/o)}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(hf.ERROR,hf.ERROR,{type:ff.MUX_ERROR,details:pf.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:E,reason:`fail allocating audio mdat ${E}`})}if(!u){new DataView(v.buffer).setUint32(0,E),v.set(Ty.types.mdat,4)}}v.set(s,p);const l=s.byteLength;p+=l,d.push(new xy(!0,a,l,0)),w=i}const S=d.length;if(!S)return;const C=d[d.length-1];this.nextAudioPts=g=w+o*C.duration;const k=u?new Uint8Array(0):Ty.moof(e.sequenceNumber++,b/o,uf({},e,{samples:d}));e.samples=[];const A=b/i,_=g/i,I={data1:k,data2:v,startPTS:A,endPTS:_,startDTS:A,endDTS:_,type:"audio",hasAudio:!0,hasVideo:!1,nb:S};return this.isAudioContiguous=!0,I}remuxEmptyAudio(e,t,r,n){const s=e.inputTimeScale,i=s/(e.samplerate?e.samplerate:s),o=this.nextAudioPts,a=this._initDTS,l=9e4*a.baseTime/a.timescale,c=(null!==o?o:n.startDTS*s)+l,u=n.endDTS*s+l,d=1024*i,h=Math.ceil((u-c)/d),f=wy.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(bf.warn("[mp4-remuxer]: remux empty Audio"),!f)return void bf.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*d;p.push({unit:f,pts:t,dts:t})}return e.samples=p,this.remuxAudio(e,t,r,!1)}}function Ry(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 Ly(e,t,r,n){const s=e.samples.length;if(!s)return;const i=e.inputTimeScale;for(let o=0;o<s;o++){const s=e.samples[o];s.pts=Ry(s.pts-r.baseTime*i/r.timescale,t*i)/i,s.dts=Ry(s.dts-n.baseTime*i/n.timescale,t*i)/i}const o=e.samples;return e.samples=[],{samples:o}}function Dy(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=Ry(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 xy{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 Oy(e)}}class Oy{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 Py(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===_f?"avc1.42e01e":"mp4a.40.5"}try{ky=self.performance.now.bind(self.performance)}catch(e){bf.debug("Unable to use Performance API on this environment"),ky="undefined"!=typeof self&&self.Date.now}const My=[{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=qm("video",1),i=this.audioTrack=qm("audio",1),o=this.txtTrack=qm("text",1);if(this.id3Track=qm("id3",1),this.timeOffset=0,null==e||!e.byteLength)return;const a=wp(e);if(a.video){const{id:e,timescale:t,codec:r}=a.video;s.id=e,s.timescale=o.timescale=t,s.codec=r}if(a.audio){const{id:e,timescale:t,codec:r}=a.audio;i.id=e,i.timescale=t,i.codec=r}o.id=hp.text,s.sampleDuration=0,s.duration=i.duration=n}resetContiguity(){this.remainderData=null}static probe(e){return vp(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=Sp(this.remainderData,e));const t=function(e){const t={valid:null,remainder:null},r=vp(e,["moof"]);if(!r)return t;if(r.length<2)return t.remainder=e,t;const n=r[r.length-1];return t.valid=Vf(e,0,n.byteOffset-8),t.remainder=Vf(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=Cp(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=Cp(e,t),{videoTrack:t,audioTrack:qm(),id3Track:n,textTrack:qm()}}extractID3Track(e,t){const r=this.id3Track;if(e.samples.length){const n=vp(e.samples,["emsg"]);n&&n.forEach((e=>{const n=function(e){const t=e[0];let r="",n="",s=0,i=0,o=0,a=0,l=0,c=0;if(0===t){for(;"\0"!==fp(e.subarray(c,c+1));)r+=fp(e.subarray(c,c+1)),c+=1;for(r+=fp(e.subarray(c,c+1)),c+=1;"\0"!==fp(e.subarray(c,c+1));)n+=fp(e.subarray(c,c+1)),c+=1;n+=fp(e.subarray(c,c+1)),c+=1,s=gp(e,12),i=gp(e,16),a=gp(e,20),l=gp(e,24),c=28}else if(1===t){c+=4,s=gp(e,c),c+=4;const t=gp(e,c);c+=4;const i=gp(e,c);for(c+=4,o=2**32*t+i,Number.isSafeInteger(o)||(o=Number.MAX_SAFE_INTEGER,bf.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),a=gp(e,c),c+=4,l=gp(e,c),c+=4;"\0"!==fp(e.subarray(c,c+1));)r+=fp(e.subarray(c,c+1)),c+=1;for(r+=fp(e.subarray(c,c+1)),c+=1;"\0"!==fp(e.subarray(c,c+1));)n+=fp(e.subarray(c,c+1)),c+=1;n+=fp(e.subarray(c,c+1)),c+=1}return{schemeIdUri:r,value:n,timeScale:s,presentationTime:o,presentationTimeDelta:i,eventDuration:a,id:l,payload:e.subarray(c,e.byteLength)}}(e);if(Zm.test(n.schemeIdUri)){const e=df(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:mg,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&&vp(e,["moov","trak"]).forEach((e=>{const t=vp(e,["mdia","minf","stbl","stsd"])[0].subarray(8);let n=vp(t,["enca"]);const s=n.length>0;s||(n=vp(t,["encv"])),n.forEach((e=>{vp(s?e.subarray(28):e.subarray(78),["sinf"]).forEach((e=>{const t=Ep(e);if(t){const e=t.subarray(8,24);e.some((e=>0!==e))||(bf.log(`[eme] Patching keyId in 'enc${s?"a":"v"}>sinf>>tenc' box: ${cp(e)} -> ${cp(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=wp(e);t||(t=Py(n.audio,Af)),r||(r=Py(n.video,_f));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"}:bf.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=s}remux(e,t,r,n,s,i){var o,a;let{initPTS:l,lastEndTime:c}=this;const u={audio:void 0,video:void 0,text:n,id3:r,initSegment:void 0};df(c)||(c=this.lastEndTime=s||0);const d=t.samples;if(null==d||!d.length)return u;const h={initPTS:void 0,timescale:1};let f=this.initData;if(null!=(o=f)&&o.length||(this.generateInitSegment(d),f=this.initData),null==(a=f)||!a.length)return bf.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),u;this.emitInitSegment&&(h.tracks=this.initTracks,this.emitInitSegment=!1);const p=function(e,t){let r=0,n=0,s=0;const i=vp(e,["moof","traf"]);for(let e=0;e<i.length;e++){const o=i[e],a=vp(o,["tfhd"])[0],l=t[gp(a,4)];if(!l)continue;const c=l.default,u=gp(a,0)|(null==c?void 0:c.flags);let d=null==c?void 0:c.duration;8&u&&(d=gp(a,2&u?12:8));const h=l.timescale||9e4,f=vp(o,["trun"]);for(let e=0;e<f.length;e++)r=Tp(f[e]),!r&&d&&(r=d*gp(f[e],4)),l.type===_f?n+=r/h:l.type===Af&&(s+=r/h)}if(0===n&&0===s){let t=0;const r=vp(e,["sidx"]);for(let e=0;e<r.length;e++){const n=bp(r[e]);null!=n&&n.references&&(t+=n.references.reduce(((e,t)=>e+t.info.duration||0),0))}return t}return n||s}(d,f),g=function(e,t){return vp(t,["moof","traf"]).reduce(((t,r)=>{const n=vp(r,["tfdt"])[0],s=n[0],i=vp(r,["tfhd"]).reduce(((t,r)=>{const i=gp(r,4),o=e[i];if(o){let e=gp(n,4);if(1===s){if(e===up)return bf.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),t;e*=up+1,e+=gp(n,8)}const r=e/(o.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,d),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&&bf.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){vp(t,["moof","traf"]).forEach((t=>{vp(t,["tfhd"]).forEach((n=>{const s=gp(n,4),i=e[s];if(!i)return;const o=i.timescale||9e4;vp(t,["tfdt"]).forEach((e=>{const t=e[0];let n=gp(e,4);if(0===t)n-=r*o,n=Math.max(n,0),yp(e,4,n);else{n*=Math.pow(2,32),n+=gp(e,8),n-=r*o,n=Math.max(n,0);const t=Math.floor(n/(up+1)),s=Math.floor(n%(up+1));yp(e,4,t),yp(e,8,s)}}))}))}))}(f,d,l.baseTime/l.timescale),p>0?this.lastEndTime=v:(bf.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 T={data1:d,startPTS:y,startDTS:y,endPTS:v,endDTS:v,type:E,hasAudio:b,hasVideo:w,nb:1,dropped:0};return u.audio="audio"===T.type?T:void 0,u.video="audio"!==T.type?T:void 0,u.initSegment=h,u.id3=Ly(r,s,l,l),n.samples.length&&(u.text=Dy(n,s,l)),u}}},{demux:fy,remux:Iy},{demux:class extends Km{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=(Yf(e,0)||[]).length;for(let r=e.length;t<r;t++)if(Ym(e,t))return bf.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)&&Hm(e,t)&&zm(e,t)<=e.length-t}(e,t)}appendFrame(e,t,r){Qm(e,this.observer,t,r,e.manifestCodec);const n=Jm(e,t,r,this.basePTS,this.frameIndex);if(n&&0===n.missing)return n}},remux:Iy},{demux:class extends Km{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=(Yf(e,0)||[]).length;for(let r=e.length;t<r;t++)if(cy(e,t))return bf.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return ay(e,t)&&4<=e.length-t}(e,t)}appendFrame(e,t,r){if(null!==this.basePTS)return iy(e,t,r,this.basePTS,this.frameIndex)}},remux:Iy}];class Fy{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=ky();let i=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:a}=this;n&&(this.currentTransmuxState=n);const{contiguous:l,discontinuity:c,trackSwitch:u,accurateTimeOffset:d,timeOffset:h,initSegmentChange:f}=n||o,{audioCodec:p,videoCodec:g,defaultInitPts:m,duration:y,initSegmentData:v}=a,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=ky(),Ny(r);i=new Uint8Array(t)}}const w=this.needsProbing(c,u);if(w){const e=this.configureTransmuxer(i);if(e)return bf.warn(`[transmuxer] ${e.message}`),this.observer.emit(hf.ERROR,hf.ERROR,{type:ff.MEDIA_ERROR,details:pf.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),s.executeEnd=ky(),Ny(r)}(c||u||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,d,r),T=this.currentTransmuxState;return T.contiguous=!0,T.discontinuity=!1,T.trackSwitch=!1,s.executeEnd=ky(),E}flush(e){const t=e.transmuxing;t.executeStart=ky();const{decrypter:r,currentTransmuxState:n,decryptionPromise:s}=this;if(s)return s.then((()=>this.flush(e)));const i=[],{timeOffset:o}=n;if(r){const t=r.flush();t&&i.push(this.push(t,null,e))}const{demuxer:a,remuxer:l}=this;if(!a||!l)return t.executeEnd=ky(),[Ny(e)];const c=a.flush(o);return Uy(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:o}=t,{accurateTimeOffset:a,timeOffset:l}=this.currentTransmuxState;bf.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,o,l,a,!0,this.id);e.push({remuxResult:c,chunkMeta:r}),r.transmuxing.executeEnd=ky()}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:o}=this;i&&o&&(i.resetInitSegment(e,t,r,n),o.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:o,textTrack:a}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,i,o,a,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=My.length;t<r;t++)if(My[t].demux.probe(e)){i=My[t];break}if(!i)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,a=this.remuxer,l=i.remux,c=i.demux;a&&a instanceof l||(this.remuxer=new l(r,t,n,s)),o&&o 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 Am(this.config)),e}}const Ny=e=>({remuxResult:{},chunkMeta:e});function Uy(e){return"then"in e&&e.then instanceof Function}class By{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 jy{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 $y={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,o){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new s(n,i||e,o),l=r?r+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],a]:e._events[l].push(a):(e._events[l]=a,e._eventsCount++),e}function o(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.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},a.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,o=new Array(i);s<i;s++)o[s]=n[s].fn;return o},a.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},a.prototype.emit=function(e,t,n,s,i,o){var a=r?r+e:e;if(!this._events[a])return!1;var l,c,u=this._events[a],d=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),d){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,n),!0;case 4:return u.fn.call(u.context,t,n,s),!0;case 5:return u.fn.call(u.context,t,n,s,i),!0;case 6:return u.fn.call(u.context,t,n,s,i,o),!0}for(c=1,l=new Array(d-1);c<d;c++)l[c-1]=arguments[c];u.fn.apply(u.context,l)}else{var h,f=u.length;for(c=0;c<f;c++)switch(u[c].once&&this.removeListener(e,u[c].fn,void 0,!0),d){case 1:u[c].fn.call(u[c].context);break;case 2:u[c].fn.call(u[c].context,t);break;case 3:u[c].fn.call(u[c].context,t,n);break;case 4:u[c].fn.call(u[c].context,t,n,s);break;default:if(!l)for(h=1,l=new Array(d-1);h<d;h++)l[h-1]=arguments[h];u[c].fn.apply(u[c].context,l)}}return!0},a.prototype.on=function(e,t,r){return i(this,e,t,r,!1)},a.prototype.once=function(e,t,r){return i(this,e,t,r,!0)},a.prototype.removeListener=function(e,t,n,s){var i=r?r+e:e;if(!this._events[i])return this;if(!t)return o(this,i),this;var a=this._events[i];if(a.fn)a.fn!==t||s&&!a.once||n&&a.context!==n||o(this,i);else{for(var l=0,c=[],u=a.length;l<u;l++)(a[l].fn!==t||s&&!a[l].once||n&&a[l].context!==n)&&c.push(a[l]);c.length?this._events[i]=1===c.length?c[0]:c:o(this,i)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&o(this,t)):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=r,a.EventEmitter=a,e.exports=a}($y);var qy=nf($y.exports);const Ky=Np()||{isTypeSupported:()=>!1};class Gy{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===hf.ERROR&&(this.error=t.error),this.hls.trigger(e,t)};this.observer=new qy,this.observer.on(hf.FRAG_DECRYPTED,i),this.observer.on(hf.ERROR,i);const o={mp4:Ky.isTypeSupported("video/mp4"),mpeg:Ky.isTypeSupported("audio/mpeg"),mp3:Ky.isTypeSupported('audio/mp4; codecs="mp3"')},a=navigator.vendor;if(this.useWorker&&"undefined"!=typeof Worker){if(s.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{s.workerPath?(bf.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)):(bf.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,bf.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(hf.ERROR,{type:ff.OTHER_ERROR,details:pf.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:r})},e.postMessage({cmd:"init",typeSupported:o,vendor:a,id:t,config:JSON.stringify(s)})}catch(e){bf.warn(`Error setting up "${t}" Web Worker, fallback to inline`,e),this.resetWorker(),this.error=null,this.transmuxer=new Fy(this.observer,o,s,a,t)}return}}this.transmuxer=new Fy(this.observer,o,s,a,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,o,a,l,c){var u,d;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)),T=self.performance.now();(y||v||0===s.stats.parsing.start)&&(s.stats.parsing.start=T),!i||!b&&E||(i.stats.parsing.start=T);const S=!(g&&(null==(u=s.initSegment)?void 0:u.url)===(null==(d=g.initSegment)?void 0:d.url)),C=new jy(m,E,a,y,f,S);if(!E||m||S){bf.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: ${a}\n timeOffset: ${f}\n initSegmentChange: ${S}`);const e=new By(r,n,t,o,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);Uy(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);Uy(r)||t.async?(Uy(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(hf.ERROR,{type:ff.MEDIA_ERROR,details:pf.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":bf[t.data.logType]&&bf[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 Hy{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:o}=n,a=this.seeking&&!o,l=!this.seeking&&o;if(this.seeking=o,i!==e){if(this.moved=!0,null!==s){if(this.stallReported){const e=self.performance.now()-s;bf.warn(`playback not stuck anymore @${i}, after ${Math.round(e)}ms`),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}return}if(l||a)return void(this.stalled=null);if(n.paused&&!o||n.ended||0===n.playbackRate||!mm.getBuffered(n).length)return;const c=mm.bufferInfo(n,i,0),u=c.len>0,d=c.nextStart||0;if(!u&&!d)return;if(o){const e=c.len>2,r=!d||t&&t.start<=i||d-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(d,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(!o&&p>=250&&(this._reportStall(c),!this.media))return;const g=mm.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,o=n.getPartialFragment(i);if(o){if(this._trySkipBufferHole(o)||!this.media)return}(e.len>r.maxBufferHole||e.nextStart&&e.nextStart-i<r.maxBufferHole)&&t>1e3*r.highBufferWatchdogPeriod&&(bf.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)})`);bf.warn(n.message),t.trigger(hf.ERROR,{type:ff.MEDIA_ERROR,details:pf.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=mm.bufferInfo(n,s,0),o=s<i.start?i.start:i.nextStart;if(o){const a=i.len<=t.maxBufferHole,l=i.len>0&&i.len<1&&n.readyState<3,c=o-s;if(c>0&&(a||l)){if(c>t.maxBufferHole){const{fragmentTracker:t}=this;let r=!1;if(0===s){const e=t.getAppendedFrag(0,sg);e&&o<e.end&&(r=!0)}if(!r){const r=e||t.getAppendedFrag(s,sg);if(r){let e=!1,n=r.end;for(;n<o;){const r=t.getPartialFragment(n);if(!r){e=!0;break}n+=r.duration}if(e)return 0}}}const i=Math.max(o+.05,s+.1);if(bf.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(hf.ERROR,{type:ff.MEDIA_ERROR,details:pf.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,o=new Error(`Nudging 'currentTime' from ${s} to ${i}`);bf.warn(o.message),r.currentTime=i,t.trigger(hf.ERROR,{type:ff.MEDIA_ERROR,details:pf.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1})}else{const r=new Error(`Playhead still not moving while enough data buffered @${s} after ${e.nudgeMaxRetry} nudges`);bf.error(r.message),t.trigger(hf.ERROR,{type:ff.MEDIA_ERROR,details:pf.BUFFER_STALLED_ERROR,error:r,fatal:!0})}}}class Vy extends jm{constructor(e,t,r){super(e,t,r,"[stream-controller]",sg),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(hf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(hf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(hf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(hf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(hf.LEVEL_LOADING,this.onLevelLoading,this),e.on(hf.LEVEL_LOADED,this.onLevelLoaded,this),e.on(hf.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(hf.ERROR,this.onError,this),e.on(hf.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(hf.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(hf.BUFFER_CREATED,this.onBufferCreated,this),e.on(hf.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(hf.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(hf.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(hf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(hf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(hf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(hf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(hf.LEVEL_LOADED,this.onLevelLoaded,this),e.off(hf.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(hf.ERROR,this.onError,this),e.off(hf.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(hf.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(hf.BUFFER_CREATED,this.onBufferCreated,this),e.off(hf.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(hf.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(hf.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=Rm,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=Im}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Bm:{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=Rm;break}if(this.hls.nextLoadLevel!==this.level){this.state=Rm;break}break}case xm:{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=Rm)}}this.state===Rm&&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 o=r[i],a=this.getMainFwdBufferInfo();if(null===a)return;const l=this.getLevelDetails();if(l&&this._streamEnded(a,l)){const e={};return this.altAudio&&(e.type="video"),this.hls.trigger(hf.BUFFER_EOS,e),void(this.state=Fm)}e.loadLevel!==i&&-1===e.manualLevel&&this.log(`Adapting to level ${i} from level ${this.level}`),this.level=e.nextLoadLevel=i;const c=o.details;if(!c||this.state===Bm||c.live&&this.levelLastLoaded!==i)return this.level=i,void(this.state=Bm);const u=a.len,d=this.getMaxBufferLength(o.maxBitrate);if(u>=d)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const h=this.backtrackFragment?this.backtrackFragment.start:a.end;let f=this.getNextFragment(h,c);if(this.couldBacktrack&&!this.fragPrevious&&f&&"initSegment"!==f.sn&&this.fragmentTracker.getState(f)!==im){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&&a.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){const e=this.audioOnly&&!this.altAudio?Af:_f,t=(e===_f?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,sg)}f=this.getNextFragmentLoopLoading(f,c,a,sg,d)}f&&(!f.initSegment||f.initSegment.data||this.bitrateTest||(f=f.initSegment),this.loadFragment(f,o,h))}loadFragment(e,t,r){const n=this.fragmentTracker.getState(e);this.fragCurrent=e,n===rm||n===sm?"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,sg)}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 Lm:case Dm:case xm:case Pm:case Mm:this.state=Rm}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 Hy(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;df(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(hf.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=$m();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!==Rm)return;const n=r[t.level];(!n.details||n.details.live&&this.levelLastLoaded!==t.level||this.waitForCdnTuneIn(n.details))&&(this.state=Bm)}onLevelLoaded(e,t){var r;const{levels:n}=this,s=t.level,i=t.details,o=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:${o}`);const a=n[s],l=this.fragCurrent;!l||this.state!==Dm&&this.state!==xm||l.level===t.level&&l.urlId===a.urlId||!l.loader||this.abortCurrentFrag();let c=0;if(i.live||null!=(r=a.details)&&r.live){if(i.fragments[0]||(i.deltaUpdateFailed=!0),i.deltaUpdateFailed)return;c=this.alignPlaylists(i,a.details)}if(a.details=i,this.levelLastLoaded=s,this.hls.trigger(hf.LEVEL_UPDATED,{details:i,level:s}),this.state===Bm){if(this.waitForCdnTuneIn(i))return;this.state=Rm}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 o=i[r.level],a=o.details;if(!a)return this.warn(`Dropping fragment ${r.sn} of level ${r.level} after level details were reset`),void this.fragmentTracker.removeFragment(r);const l=o.videoCodec,c=a.PTSKnown||!a.live,u=null==(t=r.initSegment)?void 0:t.data,d=this._getAudioCodec(o),h=this.transmuxer=this.transmuxer||new Gy(this.hls,sg,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=n?n.index:-1,p=-1!==f,g=new ym(r.level,r.sn,r.stats.chunkCount,s.byteLength,f,p),m=this.initPTS[r.cc];h.push(s,u,d,l,r,n,a.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(hf.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),e.trigger(hf.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!==sg)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===Mm&&(this.state=Rm));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=Nm;else switch(t.details){case pf.FRAG_GAP:case pf.FRAG_PARSING_ERROR:case pf.FRAG_DECRYPT_ERROR:case pf.FRAG_LOAD_ERROR:case pf.FRAG_LOAD_TIMEOUT:case pf.KEY_LOAD_ERROR:case pf.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(sg,t);break;case pf.LEVEL_LOAD_ERROR:case pf.LEVEL_LOAD_TIMEOUT:case pf.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==Bm||(null==(r=t.context)?void 0:r.type)!==tg||(this.state=Rm);break;case pf.BUFFER_FULL_ERROR:if(!t.parent||"main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case pf.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}checkBuffer(){const{media:e,gapController:t}=this;if(e&&t&&e.readyState){if(this.loadedmetadata||!mm.getBuffered(e).length){const e=this.state!==Rm?this.fragCurrent:null;t.poll(this.lastCurrentTime,e)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=Rm,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==Af||this.audioOnly&&!this.altAudio){const e=(t===_f?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(e,t,sg)}}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=mm.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=Rm,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(hf.FRAG_LOADED,r),e.bitrateTest=!1}))}_handleTransmuxComplete(e){var t;const r="main",{hls:n}=this,{remuxResult:s,chunkMeta:i}=e,o=this.getCurrentContext(i);if(!o)return void this.resetWhenMissingContext(i);const{frag:a,part:l,level:c}=o,{video:u,text:d,id3:h,initSegment:f}=s,{details:p}=c,g=this.altAudio?void 0:s.audio;if(this.fragContextChanged(a))this.fragmentTracker.removeFragment(a);else{if(this.state=Pm,f){if(null!=f&&f.tracks){const e=a.initSegment||a;this._bufferInitSegment(c,f.tracks,e,i),n.trigger(hf.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:r,tracks:f.tracks})}const e=f.initPTS,t=f.timescale;df(e)&&(this.initPTS[a.cc]={baseTime:e,timescale:t},n.trigger(hf.INIT_PTS_FOUND,{frag:a,id:r,initPTS:e,timescale:t}))}if(u&&p&&"initSegment"!==a.sn){const e=p.fragments[a.sn-1-p.startSN],t=a.sn===p.startSN,r=!e||a.cc>e.cc;if(!1!==s.independent){const{startPTS:e,endPTS:n,startDTS:s,endDTS:o}=u;if(l)l.elementaryStreams[u.type]={startPTS:e,endPTS:n,startDTS:s,endDTS:o};else if(u.firstKeyFrame&&u.independent&&1===i.id&&!r&&(this.couldBacktrack=!0),u.dropped&&u.independent){const s=this.getMainFwdBufferInfo(),i=(s?s.end:this.getLoadPosition())+this.config.maxBufferHole,l=u.firstKeyFramePTS?u.firstKeyFramePTS:e;if(!t&&i<l-this.config.maxBufferHole&&!r)return void this.backtrack(a);r&&(a.gap=!0),a.setElementaryStreamInfo(u.type,a.start,n,a.start,o,!0)}a.setElementaryStreamInfo(u.type,e,n,s,o),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(u,a,l,i,t||r)}else{if(!t&&!r)return void this.backtrack(a);a.gap=!0}}if(g){const{startPTS:e,endPTS:t,startDTS:r,endDTS:n}=g;l&&(l.elementaryStreams[Af]={startPTS:e,endPTS:t,startDTS:r,endDTS:n}),a.setElementaryStreamInfo(Af,e,t,r,n),this.bufferFragmentData(g,a,l,i)}if(p&&null!=h&&null!=(t=h.samples)&&t.length){const e={id:r,frag:a,details:p,samples:h.samples};n.trigger(hf.FRAG_PARSING_METADATA,e)}if(p&&d){const e={id:r,frag:a,details:p,samples:d.samples};n.trigger(hf.FRAG_PARSING_USERDATA,e)}}}_bufferInitSegment(e,t,r,n){if(this.state!==Pm)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;const{audio:s,video:i,audiovideo:o}=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}]`)),o&&this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.attrs.CODECS||""}/${o.codec}]`),this.hls.trigger(hf.BUFFER_CODECS,t),Object.keys(t).forEach((e=>{const s=t[e].initSegment;null!=s&&s.byteLength&&this.hls.trigger(hf.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,sg)}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=Rm}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const r=e.currentTime;if(mm.isBuffered(e,r)?t=this.getAppendedFrag(r):mm.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(hf.FRAG_CHANGED,{frag:t}),e&&e.level===r||this.hls.trigger(hf.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&&df(t)&&df(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 zy{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 Wy{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 zy(e),this.fast_=new zy(t),this.defaultTTFB_=n,this.ttfb_=new zy(e)}update(e,t){const{slow_:r,fast_:n,ttfb_:s}=this;r.halfLife!==e&&(this.slow_=new zy(e,r.getEstimate(),r.getTotalWeight())),n.halfLife!==t&&(this.fast_=new zy(t,n.getEstimate(),n.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new zy(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 Yy{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 Qy(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Xy(e[r].attrs,t[r].attrs))return!1;return!0}function Xy(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 Jy{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 Zy(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 ev{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){bf.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 tv=Np(),rv=/([ha]vc.)(?:\.[^.,]+)+/;const nv={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},sv=function(e){let t=e;return nv.hasOwnProperty(e)&&(t=nv[e]),String.fromCharCode(t)},iv=15,ov=100,av={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},lv={17:2,18:4,21:6,22:8,23:10,19:13,20:15},cv={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},uv={25:2,26:4,29:6,30:8,31:10,27:13,28:15},dv=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class hv{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const r="function"==typeof t?t():t;bf.log(`${this.time} [${e}] ${r}`)}}}const fv=function(e){const t=[];for(let r=0;r<e.length;r++)t.push(e[r].toString(16));return t};class pv{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 gv{constructor(e,t,r,n,s,i){this.uchar=void 0,this.penState=void 0,this.uchar=e||" ",this.penState=new pv(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 mv{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<ov;e++)this.chars.push(new gv);this.logger=e,this.pos=0,this.currPenState=new pv}equals(e){let t=!0;for(let r=0;r<ov;r++)if(!this.chars[r].equals(e.chars[r])){t=!1;break}return t}copy(e){for(let t=0;t<ov;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<ov;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>ov&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=ov)}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=sv(e);this.pos>=ov?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<ov;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<ov;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 yv{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<iv;t++)this.rows.push(new mv(e));this.logger=e,this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.reset()}reset(){for(let e=0;e<iv;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let r=0;r<iv;r++)if(!this.rows[r].equals(e.rows[r])){t=!1;break}return t}copy(e){for(let t=0;t<iv;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<iv;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<iv;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<iv;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 vv{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 yv(r),this.nonDisplayedMemory=new yv(r),this.lastOutputScreen=new yv(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 bv{constructor(e,t,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=void 0,this.logger=void 0;const n=new hv;this.channels=[null,new vv(e,t,n),new vv(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,"["+fv([t[e],t[e+1]])+"] -> ("+fv([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 "+fv([n,s])+" orig: "+fv([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(Ev(e,t,r))return wv(null,null,r),this.logger.log(3,"Repeated command ("+fv([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),wv(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 ("+fv([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(Ev(e,t,n))return wv(null,null,n),!0;const s=e<=23?1:2;r=t>=64&&t<=95?1===s?av[e]:cv[e]:1===s?lv[e]:uv[e];const i=this.channels[s];return!!i&&(i.setPAC(this.interpretPAC(r,t)),wv(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 '"+sv(e)+"' in channel "+r),n=[e]}else e>=32&&e<=127&&(n=0===t?[e]:[e,t]);if(n){const r=fv(n);this.logger.log(3,"Char codes = "+r.join(",")),wv(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=dv[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),wv(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 wv(e,t,r){r.a=e,r.b=t}function Ev(e,t,r){return r.a===e&&r.b===t}class Tv{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 Sv=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,o){const a=this,l={enumerable:!0};a.hasBeenReset=!1;let c="",u=!1,d=t,h=i,f=o,p=null,g="",m=!0,y="auto",v="start",b=50,w="middle",E=50,T="middle";Object.defineProperty(a,"id",s({},l,{get:function(){return c},set:function(e){c=""+e}})),Object.defineProperty(a,"pauseOnExit",s({},l,{get:function(){return u},set:function(e){u=!!e}})),Object.defineProperty(a,"startTime",s({},l,{get:function(){return d},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");d=e,this.hasBeenReset=!0}})),Object.defineProperty(a,"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(a,"text",s({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(a,"region",s({},l,{get:function(){return p},set:function(e){p=e,this.hasBeenReset=!0}})),Object.defineProperty(a,"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(a,"snapToLines",s({},l,{get:function(){return m},set:function(e){m=!!e,this.hasBeenReset=!0}})),Object.defineProperty(a,"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(a,"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(a,"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(a,"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(a,"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(a,"align",s({},l,{get:function(){return T},set:function(e){const t=n(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");T=t,this.hasBeenReset=!0}})),a.displayState=void 0}return i.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},i}();class Cv{decode(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function kv(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 Av{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 _v(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 Iv=new Sv(0,0,""),Rv="middle"===Iv.align?"middle":"center";function Lv(e,t,r){const n=e;function s(){const t=kv(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 Av;_v(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",Rv,"end"]);break;case"position":s=t.split(","),n.percent(e,s[0]),2===s.length&&n.alt("positionAlign",s[1],["start",Rv,"end","line-left","line-right","auto"]);break;case"size":n.percent(e,t);break;case"align":n.alt(e,t,["start",Rv,"end","left","right"])}}),/:/,/\s/),t.region=n.get("region",null),t.vertical=n.get("vertical","");let s=n.get("line","auto");"auto"===s&&-1===Iv.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",Rv);let i=n.get("position","auto");"auto"===i&&50===Iv.position&&(i="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=i}(e,t)}function Dv(e){return e.replace(/<br(?: \/)?>/gi,"\n")}class xv{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Cv,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=Dv(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)?_v(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 Sv(0,0,""),t.state="CUE",-1===e.indexOf("--\x3e")){t.cue.id=e;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Lv(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 Ov=/\r\n|\n\r|\n|\r/g,Pv=function(e,t,r=0){return e.slice(r,r+t.length)===t},Mv=function(e){let t=5381,r=e.length;for(;r;)t=33*t^e.charCodeAt(--r);return(t>>>0).toString()};function Fv(e,t,r){return Mv(e.toString())+Mv(t.toString())+Mv(r)}function Nv(e,t,r,n,s,i,o){const a=new xv,l=op(new Uint8Array(e)).trim().replace(Ov,"\n").split("\n"),c=[],u=t?function(e,t=1){return Sy(e,9e4,1/t)}(t.baseTime,t.timescale):0;let d,h="00:00.000",f=0,p=0,g=!0;a.oncue=function(e){const i=r[n];let o=r.ccOffset;const a=(f-u)/9e4;if(null!=i&&i.new&&(void 0!==p?o=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,a)),a){if(!t)return void(d=new Error("Missing initPTS for VTT MPEGTS"));o=a-r.presentationOffset}const l=e.endTime-e.startTime,h=Ry(9e4*(e.startTime+o-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=Fv(e.startTime,e.endTime,g)),e.endTime>0&&c.push(e)},a.onparsingerror=function(e){d=e},a.onflush=function(){d?o(d):i(c)},l.forEach((e=>{if(g){if(Pv(e,"X-TIMESTAMP-MAP=")){g=!1,e.slice(16).split(",").forEach((e=>{Pv(e,"LOCAL:")?h=e.slice(6):Pv(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(!(df(t)&&df(r)&&df(n)&&df(s)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*r,t+=6e4*n,t+=36e5*s,t}(h)/1e3}catch(e){d=e}return}""===e&&(g=!1)}a.parse(e+"\n")})),a.flush()}const Uv="stpp.ttml.im1t",Bv=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,jv=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,$v={left:"start",center:"center",right:"end",start:"start",end:"end"};function qv(e,t,r,n){const s=vp(new Uint8Array(e),["mdat"]);if(0===s.length)return void n(new Error("Could not parse IMSC1 mdat"));const i=s.map((e=>op(e))),o=function(e,t,r=1,n=!1){return Sy(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)),{}),o="preserve"!==n.getAttribute("xml:space"),a=Gv(Kv(n,"styling","style")),l=Gv(Kv(n,"layout","region")),c=Kv(n,"body","[begin]");return[].map.call(c,(e=>{const r=Hv(e,o);if(!r||!e.hasAttribute("begin"))return null;const n=Wv(e.getAttribute("begin"),i),s=Wv(e.getAttribute("dur"),i);let c=Wv(e.getAttribute("end"),i);if(null===n)throw zv(e);if(null===c){if(null===s)throw zv(e);c=n+s}const u=new Sv(n-t,c-t,r);u.id=Fv(u.startTime,u.endTime,u.text);const d=function(e,t,r){const n="http://www.w3.org/ns/ttml#styling";let s=null;const i=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],o=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;o&&r.hasOwnProperty(o)&&(s=r[o]);return i.reduce(((r,i)=>{const o=Vv(t,n,i)||Vv(e,n,i)||Vv(s,n,i);return o&&(r[i]=o),r}),{})}(l[e.getAttribute("region")],a[e.getAttribute("style")],a),{textAlign:h}=d;if(h){const e=$v[h];e&&(u.lineAlign=e),u.align=h}return uf(u,d),u})).filter((e=>null!==e))}(e,o))))}catch(e){n(e)}}function Kv(e,t,r){const n=e.getElementsByTagName(t)[0];return n?[].slice.call(n.querySelectorAll(r)):[]}function Gv(e){return e.reduce(((e,t)=>{const r=t.getAttribute("xml:id");return r&&(e[r]=t),e}),{})}function Hv(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?Hv(r,t):t?e+r.textContent.trim().replace(/\s+/g," "):e+r.textContent}),"")}function Vv(e,t,r){return e&&e.hasAttributeNS(t,r)?e.getAttributeNS(t,r):null}function zv(e){return new Error(`Could not parse ttml timestamp ${e}`)}function Wv(e,t){if(!e)return null;let r=kv(e);return null===r&&(Bv.test(e)?r=function(e,t){const r=Bv.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):jv.test(e)&&(r=function(e,t){const r=jv.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 Yv(e,t){return!!e&&e.label===t.name&&!(e.textTrack1||e.textTrack2)}class Qv{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(hf.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(hf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(hf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(hf.BUFFER_CODECS,this.onBufferCodecs,this),e.on(hf.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(hf.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(hf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(hf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(hf.BUFFER_CODECS,this.onBufferCodecs,this),e.off(hf.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,Qv.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 o=0;o<e.length;o+=1){const a=e[o];if((a.width>=t||a.height>=r)&&(s=a,!(i=e[o+1])||s.width!==i.width||s.height!==i.height)){n=o;break}}var s,i;return n}}const Xv="[eme]";class Jv{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=Jv.CDMCleanupPromise?[Jv.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=bf.debug.bind(bf,Xv),this.log=bf.log.bind(bf,Xv),this.warn=bf.warn.bind(bf,Xv),this.error=bf.error.bind(bf,Xv),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(hf.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(hf.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(hf.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(hf.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(hf.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(hf.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(hf.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(hf.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:r}=this.config,n=t[e];if(n)return n.licenseUrl;if(e===Ff.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 o=e.shift();this.getMediaKeysPromise(o,n,s).then((e=>t({keySystem:o,mediaKeys:e}))).catch((t=>{e.length?i(e):r(t instanceof Zv?t:new Zv({type:ff.KEY_SYSTEM_ERROR,details:pf.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===Hf&&"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 Ff.FAIRPLAY:s=["cenc","sinf"];break;case Ff.WIDEVINE:case Ff.PLAYREADY:s=["cenc"];break;case Ff.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: ${cp(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 cp(e.keyId)}updateKeySession(e,t){var r;const n=e.mediaKeysSession;return this.log(`Updating key-session "${n.sessionId}" for keyID ${cp((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=Gf(this.config),s=e.map($f).filter((e=>!!e&&-1!==n.indexOf(e)));return this.getKeySystemSelectionPromise(s).then((({keySystem:e})=>{const n=Kf(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 Zv?this.hls.trigger(hf.ERROR,e.data):this.hls.trigger(hf.ERROR,{type:ff.KEY_SYSTEM_ERROR,details:pf.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),r=this.keyIdToKeySessionPromise[t];if(!r){const t=$f(e.keyFormat),r=t?[t]:Gf(this.config);return this.attemptKeySystemAccess(r)}return r}getKeySystemSelectionPromise(e){if(e.length||(e=Gf(this.config)),0===e.length)throw new Zv({type:ff.KEY_SYSTEM_ERROR,details:pf.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[Ff.FAIRPLAY]){const e=fp(new Uint8Array(r));try{const t=Of(JSON.parse(e).sinf),r=Ep(new Uint8Array(t));if(!r)return;n=r.subarray(8,24),s=Ff.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=cp(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===qf&&e.data&&(n=e.data.subarray(8,24)),s=function(e){if(e===qf)return Ff.WIDEVINE}(e.systemId)}if(!s||!n)return;const i=cp(n),{keyIdToKeySessionPromise:o,mediaKeySessions:a}=this;let l=o[i];for(let e=0;e<a.length;e++){const s=a[e],c=s.decryptdata;if(c.pssh||!c.keyId)continue;const u=cp(c.keyId);if(i===u||-1!==c.uri.replace(/-/g,"").indexOf(i)){l=o[u],delete o[u],c.pssh=new Uint8Array(r),c.keyId=n,l=o[i]=l.then((()=>this.generateRequestWithPreferredKeySession(s,t,r,"encrypted-event-key-match")));break}}l||(l=o[i]=this.getKeySystemSelectionPromise([s]).then((({keySystem:e,mediaKeys:s})=>{var o;this.throwIfDestroyed();const a=new Lp("ISO-23001-7",i,null!=(o=Kf(e))?o:"");return a.pssh=new Uint8Array(r),a.keyId=n,this.attemptSetMediaKeys(e,s).then((()=>{this.throwIfDestroyed();const n=this.createMediaKeySessionContext({decryptdata:a,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 o=null==(s=this.config.drmSystems)||null==(i=s[e.keySystem])?void 0:i.generateRequest;if(o)try{const n=o.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 a;if(this.warn(e.message),null!=(a=this.hls)&&a.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 qy;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===Ff.FAIRPLAY&&(this.updateKeySession(e,Mf("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 u=new Promise(((e,t)=>{c.on("error",t),c.on("keyStatus",(r=>{r.startsWith("usable")?e():"output-restricted"===r?t(new Zv({type:ff.KEY_SYSTEM_ERROR,details:pf.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===r?t(new Zv({type:ff.KEY_SYSTEM_ERROR,details:pf.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 Zv({type:ff.KEY_SYSTEM_ERROR,details:pf.KEY_SYSTEM_NO_SESSION,error:e,fatal:!1},`Error generating key-session request: ${e}`)})).then((()=>u)).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: ${cp("buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r))} session keyId: ${cp(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 o={responseType:"arraybuffer",url:n},a=t.certLoadPolicy.default,l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(e,t,r,n)=>{s(e.data)},onError:(t,r,s,a)=>{i(new Zv({type:ff.KEY_SYSTEM_ERROR,details:pf.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:lf({url:o.url,data:void 0},t)},`"${e}" certificate request failed (${n}). Status: ${t.code} (${t.text})`))},onTimeout:(t,r,s)=>{i(new Zv({type:ff.KEY_SYSTEM_ERROR,details:pf.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:{url:o.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(e,t,r)=>{i(new Error("aborted"))}};r.load(o,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 Zv({type:ff.KEY_SYSTEM_ERROR,details:pf.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 Zv({type:ff.KEY_SYSTEM_ERROR,details:pf.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 o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return s(new Error("invalid state"));if(4===o.readyState)if(200===o.status){this._requestLicenseFailureCount=0;let t=o.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);const r=this.config.licenseResponseCallback;if(r)try{t=r.call(this.hls,o,i,e)}catch(e){this.error(e)}n(t)}else{const a=r.errorRetry,l=a?a.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||o.status>=400&&o.status<500)s(new Zv({type:ff.KEY_SYSTEM_ERROR,details:pf.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:i,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${i}). Status: ${o.status} (${o.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=o,this.setupLicenseXHR(o,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={},Lp.clearKeyUriToKeyIdMap();const r=t.length;Jv.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}`)}))}}}Jv.CDMCleanupPromise=void 0;class Zv 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 eb="m",tb="a",rb="v",nb="av",sb="i",ib="tt";class ob{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:eb,su:!this.initialized})}catch(e){bf.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!==rb&&n!==tb&&n!=nb||(s.br=r.bitrate/1e3,s.tb=this.getTopBandwidth(n)/1e3,s.bl=this.getBufferLength(n)),this.apply(e,s)}catch(e){bf.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||ob.uuid(),this.cid=r.contentId,this.useHeaders=!0===r.useHeaders,this.registerListeners())}registerListeners(){const e=this.hls;e.on(hf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(hf.MEDIA_DETACHED,this.onMediaDetached,this),e.on(hf.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(hf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(hf.MEDIA_DETACHED,this.onMediaDetached,this),e.off(hf.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={}){uf(t,this.createData());const r=t.ot===sb||t.ot===rb||t.ot===nb;if(this.starved&&r&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering),this.useHeaders){const r=ob.toHeaders(t);if(!Object.keys(r).length)return;e.headers||(e.headers={}),uf(e.headers,r)}else{const r=ob.toQuery(t);if(!r)return;e.url=ob.appendQueryToUri(e.url,r)}}getObjectType(e){const{type:t}=e;return"subtitle"===t?ib:"initSegment"===e.sn?sb:"audio"===t?tb:"main"===t?this.hls.audioTracks.length?rb:nb:void 0}getTopBandwidth(e){let t,r=0;const n=this.hls;if(e===tb)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===tb?this.audioBuffer:this.videoBuffer;if(!r||!t)return NaN;return 1e3*mm.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},o=Object.keys(e||{}).sort();for(const n of o){let s=e[n];if(!r(s))continue;if("v"===n&&1===s)continue;if("pr"==n&&1===s)continue;const o=i[n];o&&(s=o(s));const a=typeof s;let l;l="ot"===n||"sf"===n||"st"===n?`${n}=${s}`:"boolean"===a?n:"number"===a?`${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=ob.serialize(s[e]);t&&(r[`CMCD-${n[e]}`]=t)}return r}static toQuery(e){return`CMCD=${encodeURIComponent(ob.serialize(e))}`}static appendQueryToUri(e,t){if(!t)return e;const r=e.includes("?")?"&":"?";return`${e}${r}${t}`}}function ab(e,t,r,n){e&&Object.keys(t).forEach((s=>{const i=e.filter((e=>e.groupId===s)).map((e=>{const i=uf({},e);return i.details=void 0,i.attrs=new Tf(i.attrs),i.url=i.attrs.URI=lb(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 lb(e,t,r,n){const{HOST:s,PARAMS:i,[r]:o}=n;let a;t&&(a=null==o?void 0:o[t],a&&(e=a));const l=new self.URL(e);return s&&!a&&(l.host=s),i&&Object.keys(i).sort().forEach((e=>{e&&l.searchParams.set(e,i[e])})),l.href}const cb=/^age:\s*[\d.]+\s*$/im;class ub{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 kf,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&&df(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,o="arraybuffer"===t.responseType?s.byteLength:s.length;if(r.loaded=r.total=o,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first),!this.callbacks)return;const a=this.callbacks.onProgress;if(a&&a(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;Bg(i,r.retry,!1,n)?this.retry(i):(bf.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(Bg(t,this.stats.retry,!0))this.retry(t);else{bf.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=Ng(e,r.retry),r.retry++,bf.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&&cb.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 db=/(\d+)-(\d+)\/(\d+)/;class hb{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||fb,this.controller=new self.AbortController,this.stats=new kf}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(uf({},e.headers))};e.rangeEnd&&r.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return r}(e,this.controller.signal),i=r.onProgress,o="arraybuffer"===e.responseType,a=o?"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&&df(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 a=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-(a-n.loading.start)),!s.ok){const{status:e,statusText:t}=s;throw new pb(t||"fetch, bad network response",e,s)}return n.loading.first=a,n.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=db.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(df(e))return e}const r=e.get("Content-Length");if(r)return parseInt(r)}(s.headers)||n.total,i&&df(t.highWaterMark)?this.loadProgressively(s,n,e,t.highWaterMark,i):o?s.arrayBuffer():"json"===e.responseType?s.json():s.text()})).then((s=>{const{response:o}=this;self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);const l=s[a];l&&(n.loaded=n.total=l);const c={url:o.url,data:s,code:o.status};i&&!df(t.highWaterMark)&&i(n,e,s,o),r.onSuccess(c,n,e,o)})).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 Yy,o=e.body.getReader(),a=()=>o.read().then((o=>{if(o.done)return i.dataLength&&s(t,r,i.flush(),e),Promise.resolve(new ArrayBuffer(0));const l=o.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),a()})).catch((()=>Promise.reject()));return a()}}function fb(e,t){return new self.Request(e.url,t)}class pb extends Error{constructor(e,t,r){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=r}}const gb=/\s/,mb={newCue(e,t,r,n){const s=[];let i,o,a,l,c;const u=self.VTTCue||self.TextTrackCue;for(let h=0;h<n.rows.length;h++)if(i=n.rows[h],a=!0,l=0,c="",!i.isEmpty()){var d;for(let e=0;e<i.chars.length;e++)gb.test(i.chars[e].uchar)&&a?l++:(c+=i.chars[e].uchar,a=!1);i.cueStartTime=t,t===r&&(r+=1e-4),l>=16?l--:l++;const n=Dv(c.trim()),f=Fv(t,r,n);null!=e&&null!=(d=e.cues)&&d.getCueById(f)||(o=new u(t,r,n),o.id=f,o.line=h+1,o.align="left",o.position=10+Math.min(80,10*Math.floor(8*l/32)),s.push(o))}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=>dg(e,t)))),s}},yb=lf(lf({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:ub,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 Wy(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate),this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(hf.FRAG_LOADING,this.onFragLoading,this),e.on(hf.FRAG_LOADED,this.onFragLoaded,this),e.on(hf.FRAG_BUFFERED,this.onFragBuffered,this),e.on(hf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(hf.LEVEL_LOADED,this.onLevelLoaded,this)}unregisterListeners(){const{hls:e}=this;e.off(hf.FRAG_LOADING,this.onFragLoading,this),e.off(hf.FRAG_LOADED,this.onFragLoaded,this),e.off(hf.FRAG_BUFFERED,this.onFragBuffered,this),e.off(hf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(hf.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;df(n)&&df(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(),o=t?t.stats:e.stats,a=t?t.duration:e.duration,l=i-o.loading.start;if(o.aborted||o.loaded&&o.loaded===o.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 u=this.bwEstimator.getEstimateTTFB(),d=Math.abs(s.playbackRate);if(l<=Math.max(u,a/(2*d)*1e3))return;const h=c.len/d;if(h>=2*a/d)return;const f=o.loading.first?o.loading.first-o.loading.start:-1,p=o.loaded&&f>-1,g=this.bwEstimator.getEstimate(),{levels:m,minAutoLevel:y}=r,v=m[e.level],b=o.total||Math.max(o.loaded,Math.round(a*v.maxBitrate/8));let w=l-f;w<1&&p&&(w=Math.min(l,8*o.loaded/g));const E=p?1e3*o.loaded/w:0,T=E?(b-o.loaded)/E:8*b/g+u/1e3;if(T<=h)return;const S=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(u/1e3,S,a*e,!m[C].details),k<h)break}k>=T||k>10*a||(r.nextLoadLevel=C,p?this.bwEstimator.sample(l-Math.min(u,f),o.loaded):this.bwEstimator.sampleTTFB(l),this.clearTimer(),bf.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: ${T.toFixed(3)} s\n Estimated load time for down switch fragment: ${k.toFixed(3)} s\n TTFB estimate: ${f}\n Current BW estimate: ${df(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(hf.FRAG_LOAD_EMERGENCY_ABORTED,{frag:e,part:t,stats:o}))}onFragLoaded(e,{frag:t,part:r}){const n=r?r.stats:t.stats;if(t.type===sg&&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,o=(s.loaded?s.loaded.duration:0)+e;s.loaded={bytes:i,duration:o},s.realBitrate=Math.round(8*i/o)}if(t.bitrateTest){const e={stats:n,frag:t,part:r,id:t.type};this.onFragBuffered(hf.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!==sg||"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:o}=r,a=t?t.duration:e?e.duration:0,l=o&&0!==o.playbackRate?Math.abs(o.playbackRate):1,c=this.bwEstimator?this.bwEstimator.getEstimate():s.abrEwmaDefaultEstimate,u=r.mainForwardBufferInfo,d=(u?u.len:0)/l;let h=this.findBestLevel(c,i,n,d,s.abrBandWidthFactor,s.abrBandWidthUpFactor);if(h>=0)return h;bf.trace(`[abr] ${d?"rebuffering expected":"buffer is empty"}, finding optimal quality level`);let f=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay,p=s.abrBandWidthFactor,g=s.abrBandWidthUpFactor;if(!d){const e=this.bitrateTestDelay;if(e){f=(a?Math.min(a,s.maxLoadingDelay):s.maxLoadingDelay)-e,bf.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,d+f,p,g),Math.max(h,0)}findBestLevel(e,t,r,n,s,i){var o;const{fragCurrent:a,partCurrent:l,lastLoadedFragLevel:c}=this,{levels:u}=this.hls,d=u[c],h=!(null==d||null==(o=d.details)||!o.live),f=null==d?void 0:d.codecSet,p=l?l.duration:a?a.duration:0,g=this.bwEstimator.getEstimateTTFB()/1e3;let m=t,y=-1;for(let o=r;o>=t;o--){const t=u[o];if(!t||f&&t.codecSet!==f){t&&(m=Math.min(o,m),y=Math.max(o,y));continue}-1!==y&&bf.trace(`[abr] Skipped level(s) ${m}-${y} with CODECS:"${u[y].attrs.CODECS}"; not compatible with "${d.attrs.CODECS}"`);const r=t.details,a=(l?null==r?void 0:r.partTarget:null==r?void 0:r.averagetargetduration)||p;let v;v=o<=c?s*e:i*e;const b=u[o].maxBitrate,w=this.getTimeToLoadFrag(g,v,b*a,void 0===r);if(bf.trace(`[abr] level:${o} adjustedbw-bitrate:${Math.round(v-b)} avgDuration:${a.toFixed(1)} maxFetchDuration:${n.toFixed(1)} fetchDuration:${w.toFixed(1)}`),v>b&&(0===w||!df(w)||h&&!this.bitrateTestDelay||w<n))return o}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;bf.log("[buffer-controller]: Media source opened"),e&&(e.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(hf.MEDIA_ATTACHED,{media:e})),t&&t.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{bf.log("[buffer-controller]: Media source closed")},this._onMediaSourceEnded=()=>{bf.log("[buffer-controller]: Media source ended")},this._onMediaEmptied=()=>{const{media:e,_objectUrl:t}=this;e&&e.src!==t&&bf.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(hf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(hf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(hf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(hf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(hf.BUFFER_RESET,this.onBufferReset,this),e.on(hf.BUFFER_APPENDING,this.onBufferAppending,this),e.on(hf.BUFFER_CODECS,this.onBufferCodecs,this),e.on(hf.BUFFER_EOS,this.onBufferEos,this),e.on(hf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(hf.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(hf.FRAG_PARSED,this.onFragParsed,this),e.on(hf.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:e}=this;e.off(hf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(hf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(hf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(hf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(hf.BUFFER_RESET,this.onBufferReset,this),e.off(hf.BUFFER_APPENDING,this.onBufferAppending,this),e.off(hf.BUFFER_CODECS,this.onBufferCodecs,this),e.off(hf.BUFFER_EOS,this.onBufferEos,this),e.off(hf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(hf.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(hf.FRAG_PARSED,this.onFragParsed,this),e.off(hf.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new ev(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,bf.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,t){const r=this.media=t.media;if(r&&tv){const e=this.mediaSource=new tv;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(bf.log("[buffer-controller]: media source detaching"),"open"===t.readyState)try{t.endOfStream()}catch(e){bf.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()):bf.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(hf.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){bf.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:o,metadata:a}=t[e],l=(r.levelCodec||r.codec).replace(rv,"$1"),c=(i||s).replace(rv,"$1");if(l!==c){const t=`${o};codecs=${i||s}`;this.appendChangeType(e,t),bf.log(`[buffer-controller]: switching codec ${l} to ${c}`),this.tracks[e]={buffer:r.buffer,codec:s,container:o,levelCodec:i,metadata:a,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&&(bf.log(`[buffer-controller]: changing ${e} sourceBuffer type to ${t}`),n.changeType(t)),r.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{bf.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:o,frag:a,part:l,chunkMeta:c}=t,u=c.buffering[o],d=self.performance.now();u.start=d;const h=a.stats.buffering,f=l?l.stats.buffering:null;0===h.start&&(h.start=d),f&&0===f.start&&(f.start=d);const p=s.audio;let g=!1;"audio"===o&&"audio/mpeg"===(null==p?void 0:p.container)&&(g=!this.lastMpegAudioChunk||1===c.id||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);const m=a.start,y={execute:()=>{if(u.executeStart=self.performance.now(),g){const e=this.sourceBuffer[o];if(e){const t=m-e.timestampOffset;Math.abs(t)>=.1&&(bf.log(`[buffer-controller]: Updating audio SourceBuffer timestampOffset to ${m} (delta: ${t}) sn: ${a.sn})`),e.timestampOffset=m)}}this.appendExecutor(i,o)},onStart:()=>{},onComplete:()=>{const e=self.performance.now();u.executeEnd=u.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]=mm.getBuffered(t[e]);this.appendError=0,this.hls.trigger(hf.BUFFER_APPENDED,{type:o,frag:a,part:l,chunkMeta:c,parent:a.type,timeRanges:r})},onError:e=>{bf.error(`[buffer-controller]: Error encountered while trying to append to the ${o} SourceBuffer`,e);const t={type:ff.MEDIA_ERROR,parent:a.type,details:pf.BUFFER_APPEND_ERROR,frag:a,part:l,chunkMeta:c,error:e,err:e,fatal:!1};e.code===DOMException.QUOTA_EXCEEDED_ERR?t.details=pf.BUFFER_FULL_ERROR:(this.appendError++,t.details=pf.BUFFER_APPEND_ERROR,this.appendError>r.config.appendErrorMaxRetry&&(bf.error(`[buffer-controller]: Failed ${r.config.appendErrorMaxRetry} times to append segment in sourceBuffer`),t.fatal=!0)),r.trigger(hf.ERROR,t)}};n.append(y,o)}onBufferFlushing(e,t){const{operationQueue:r}=this,n=e=>({execute:this.removeExecutor.bind(this,e,t.startOffset,t.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(hf.BUFFER_FLUSHED,{type:e})},onError:t=>{bf.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[If]?s.push("audiovideo"):(i[Af]&&s.push("audio"),i[_f]&&s.push("video"));0===s.length&&bf.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(hf.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,bf.log(`[buffer-controller]: ${r} sourceBuffer now EOS`))),e&&!(n&&!n.ended)}),!0)&&(bf.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?(bf.log("[buffer-controller]: Calling mediaSource.endOfStream()"),e.endOfStream()):e&&bf.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(!df(i)||i<0)return;const o=r.currentTime,a=t.levelTargetDuration,l=Math.max(i,a),c=Math.floor(o/a)*a-l;s.forEach((r=>{const s=n[r];if(s){const n=mm.getBuffered(s);if(n.length>0&&c>n.start(0)){if(e.trigger(hf.BACK_BUFFER_REACHED,{bufferEnd:c}),t.live)e.trigger(hf.LIVE_BACK_BUFFER_REACHED,{bufferEnd:c});else if(s.ended&&n.end(n.length-1)-o<2*a)return void bf.info(`[buffer-controller]: Cannot flush ${r} back buffer while SourceBuffer is in ended state`);e.trigger(hf.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,o=df(n.duration)?n.duration:0;e.live&&t.config.liveDurationInfinity?(bf.log("[buffer-controller]: Media Source duration is set to Infinity"),n.duration=1/0,this.updateSeekableRange(e)):(s>o&&s>i||!df(i))&&(bf.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(hf.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(hf.ERROR,{type:ff.MEDIA_ERROR,details:pf.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,o=`${s.container};codecs=${i}`;bf.log(`[buffer-controller]: creating sourceBuffer(${o})`);try{const e=t[n]=r.addSourceBuffer(o),a=n;this.addBufferListener(a,"updatestart",this._onSBUpdateStart),this.addBufferListener(a,"updateend",this._onSBUpdateEnd),this.addBufferListener(a,"error",this._onSBUpdateError),this.tracks[n]={buffer:e,codec:i,container:s.container,levelCodec:s.levelCodec,metadata:s.metadata,id:s.id}}catch(e){bf.error(`[buffer-controller]: error while trying to add sourceBuffer: ${e.message}`),this.hls.trigger(hf.ERROR,{type:ff.MEDIA_ERROR,details:pf.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,mimeType:o})}}}_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`);bf.error(`[buffer-controller]: ${r}`,t),this.hls.trigger(hf.ERROR,{type:ff.MEDIA_ERROR,details:pf.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:o}=this,a=o[e];if(!n||!s||!a)return bf.warn(`[buffer-controller]: Attempting to remove from the ${e} SourceBuffer, but it does not exist`),void i.shiftAndExecuteNext(e);const l=df(n.duration)?n.duration:1/0,c=df(s.duration)?s.duration:1/0,u=Math.max(0,t),d=Math.min(r,l,c);d>u&&!a.ending?(a.ended=!1,bf.log(`[buffer-controller]: Removing [${u},${d}] from the ${e} SourceBuffer`),a.remove(u,d)):i.shiftAndExecuteNext(e)}appendExecutor(e,t){const{operationQueue:r,sourceBuffer:n}=this,s=n[t];if(!s)return bf.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 bf.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:Qv,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=bf.log.bind(bf,"[info]:"),this.warn=bf.warn.bind(bf,"[warning]:"),this.error=bf.error.bind(bf,"[error]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(hf.ERROR,this.onError,this),e.on(hf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(hf.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(hf.ERROR,this.onError,this),e.off(hf.ERROR,this.onErrorOut,this),e.off(hf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(hf.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)===sg?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 pf.FRAG_LOAD_ERROR:case pf.FRAG_LOAD_TIMEOUT:case pf.KEY_LOAD_ERROR:case pf.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case pf.FRAG_PARSING_ERROR:if(null!=(r=t.frag)&&r.gap)return void(t.errorAction={action:Gg,flags:zg});case pf.FRAG_GAP:case pf.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=Hg);case pf.LEVEL_EMPTY_ERROR:case pf.LEVEL_PARSING_ERROR:{var o,a;const e=t.parent===sg?t.level:s.loadLevel;t.details===pf.LEVEL_EMPTY_ERROR&&null!=(o=t.context)&&null!=(a=o.levelDetails)&&a.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case pf.LEVEL_LOAD_ERROR:case pf.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==i?void 0:i.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.level)));case pf.AUDIO_TRACK_LOAD_ERROR:case pf.AUDIO_TRACK_LOAD_TIMEOUT:case pf.SUBTITLE_LOAD_ERROR:case pf.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const e=s.levels[s.loadLevel];if(e&&(i.type===rg&&i.groupId===e.audioGroupId||i.type===ng&&i.groupId===e.textGroupId))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=Hg,void(t.errorAction.flags=Wg)}return;case pf.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const e=s.levels[s.loadLevel],r=null==e?void 0:e.attrs["HDCP-LEVEL"];r&&(t.errorAction={action:Hg,flags:Yg,hdcpLevel:r})}return;case pf.BUFFER_ADD_CODEC_ERROR:case pf.REMUX_ALLOC_ERROR:return void(t.errorAction=this.getLevelSwitchAction(t,null!=(n=t.level)?n:s.loadLevel));case pf.INTERNAL_EXCEPTION:case pf.BUFFER_APPENDING_ERROR:case pf.BUFFER_APPEND_ERROR:case pf.BUFFER_FULL_ERROR:case pf.LEVEL_SWITCH_ERROR:case pf.BUFFER_STALLED_ERROR:case pf.BUFFER_SEEK_OVER_HOLE:case pf.BUFFER_NUDGE_ON_STALL:return void(t.errorAction={action:Gg,flags:zg})}if(t.type===ff.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=Fg(this.hls.config.playlistLoadPolicy,e),s=this.playlistError++,i=null==(r=e.response)?void 0:r.code;if(Bg(n,s,Mg(e),i))return{action:Vg,flags:zg,retryConfig:n,retryCount:s};const o=this.getLevelSwitchAction(e,t);return n&&(o.retryConfig=n,o.retryCount=s),o}getFragRetryOrSwitchAction(e){const t=this.hls,r=this.getVariantLevelIndex(e.frag),n=t.levels[r],{fragLoadPolicy:s,keyLoadPolicy:i}=t.config,o=Fg(e.details.startsWith("key")?i:s,e),a=t.levels.reduce(((e,t)=>e+t.fragmentError),0);if(n){var l;e.details!==pf.FRAG_GAP&&n.fragmentError++;const t=null==(l=e.response)?void 0:l.code;if(Bg(o,a,Mg(e),t))return{action:Vg,flags:zg,retryConfig:o,retryCount:a}}const c=this.getLevelSwitchAction(e,r);return o&&(c.retryConfig=o,c.retryCount=a),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:o,loadLevel:a,minAutoLevel:l,maxAutoLevel:c}=r,u=null==(s=e.frag)?void 0:s.type,{type:d,groupId:h}=null!=(i=e.context)?i:{};for(let r=o.length;r--;){const s=(r+a)%o.length;if(s!==a&&s>=l&&s<=c&&0===o[s].loadError){const r=o[s];if(e.details===pf.FRAG_GAP&&e.frag){const t=o[s].details;if(t){const r=$g(e.frag,t.fragments,e.frag.start);if(null!=r&&r.gap)continue}}else{if(d===rg&&h===r.audioGroupId||d===ng&&h===r.textGroupId)continue;if(u===ig&&n.audioGroupId===r.audioGroupId||u===og&&n.textGroupId===r.textGroupId)continue}t=s;break}}if(t>-1&&r.loadLevel!==t)return e.levelRetry=!0,this.playlistError=0,{action:Hg,flags:zg,nextAutoLevel:t}}return{action:Hg,flags:Wg}}onErrorOut(e,t){var r;switch(null==(r=t.errorAction)?void 0:r.action){case Gg:break;case Hg:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===pf.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 zg:this.switchLevel(e,i);break;case Wg:r.resolved||(r.resolved=this.redundantFailover(e));break;case Yg:s&&(t.maxHdcpLevel=Tg[Tg.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===sg?e.level:t.loadLevel,s=t.levels[n],i=s.url.length,o=e.frag?e.frag.urlId:s.urlId;s.urlId!==o||e.frag&&!s.details||this.penalizeRendition(s,e);for(let a=1;a<i;a++){const l=(o+a)%i,c=r[l];if(!c||Qg(c,e,r[o]))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(hf.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(hf.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,o=1e3*s/e,a=this.hls;if(a.trigger(hf.FPS_DROP,{currentDropped:s,currentDecoded:i,totalDroppedFrames:r}),o>0&&s>a.config.fpsDroppedMonitoringThreshold*i){let e=a.currentLevel;bf.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===a.autoLevelCapping||a.autoLevelCapping>=e)&&(e-=1,a.trigger(hf.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:a.currentLevel}),a.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:Hf,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:mb,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 jm{constructor(e,t,r){super(e,t,r,"[subtitle-stream-controller]",og),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(hf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(hf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(hf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(hf.LEVEL_LOADED,this.onLevelLoaded,this),e.on(hf.ERROR,this.onError,this),e.on(hf.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(hf.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(hf.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(hf.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(hf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(hf.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(hf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(hf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(hf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(hf.LEVEL_LOADED,this.onLevelLoaded,this),e.off(hf.ERROR,this.onError,this),e.off(hf.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(hf.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(hf.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(hf.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(hf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(hf.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state=Rm,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=Rm,!n)return;const s=this.tracksBuffered[this.currentTrackId];if(!s)return;let i;const o=r.start;for(let e=0;e<s.length;e++)if(o>=s[e].start&&o<=s[e].end){i=s[e];break}const a=r.start+r.duration;i?i.end=a:(i={start:o,end:a},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,og)}}onFragBuffered(e,t){var r;this.loadedmetadata||t.frag.type!==sg||null!=(r=this.media)&&r.buffered.length&&(this.loadedmetadata=!0)}onError(e,t){const r=t.frag;(null==r?void 0:r.type)===og&&(this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==Im&&(this.state=Rm))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){Qy(this.levels,t)?this.levels=t.map((e=>new _g(e))):(this.tracksBuffered=[],this.levels=t.map((e=>{const t=new _g(e);return this.tracksBuffered[t.id]=[],t})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,og),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:o}=this;if(!o.length)return;const a=o[i];if(s>=o.length||s!==i||!a)return;this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||null!=(r=a.details)&&r.live){const e=this.mainDetails;if(n.deltaUpdateFailed||!e)return;const t=e.fragments[0];a.details?(l=this.alignPlaylists(n,a.details),0===l&&t&&(l=t.start,xg(n,l))):n.hasProgramDateTime&&e.hasProgramDateTime?(Tm(n,e),l=n.fragments[0].start):t&&(l=t.start,xg(n,l))}if(a.details=n,this.levelLastLoaded=s,this.startFragRequested||!this.mainDetails&&n.live||this.setStartPosition(a.details,l),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===Rm){$g(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),a.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(hf.ERROR,{type:ff.MEDIA_ERROR,details:pf.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e})).then((r=>{const n=performance.now();s.trigger(hf.FRAG_DECRYPTED,{frag:t,payload:r,stats:{tstart:e,tdecrypt:n}})})).catch((e=>{this.warn(`${e.name}: ${e.message}`),this.state=Rm}))}}doTick(){if(this.media){if(this.state===Rm){const{currentTrackId:e,levels:t}=this,r=t[e];if(!t.length||!r||!r.details)return;const{config:n}=this,s=this.getLoadPosition(),i=mm.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,n.maxBufferHole),{end:o,len:a}=i,l=this.getFwdBufferInfo(this.media,sg),c=r.details;if(a>this.getMaxBufferLength(null==l?void 0:l.len)+c.levelTargetDuration)return;const u=c.fragments,d=u.length,h=c.edge;let f=null;const p=this.fragPrevious;if(o<h){const e=n.maxFragLookUpTolerance,t=o>h-e?0:e;f=$g(p,u,Math.max(u[0].start,o),t),!f&&p&&p.start<u[0].start&&(f=u[0])}else f=u[d-1];if(!f)return;if(f=this.mapToInitFragWhenRequired(f),"initSegment"!==f.sn){const e=u[f.sn-c.startSN-1];e&&e.cc===f.cc&&this.fragmentTracker.getState(e)===rm&&(f=e)}this.fragmentTracker.getState(f)===rm&&this.loadFragment(f,r,o)}}else this.state=Rm}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 Jy(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends Xg{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(hf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(hf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(hf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(hf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(hf.LEVEL_LOADING,this.onLevelLoading,this),e.on(hf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(hf.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(hf.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(hf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(hf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(hf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(hf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(hf.LEVEL_LOADING,this.onLevelLoading,this),e.off(hf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(hf.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(hf.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);Zy(this.media.textTracks).forEach((e=>{hg(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 o=i.details;i.details=t.details,this.log(`subtitle track ${r} loaded [${n.startSN}-${n.endSN}]`),r===this.trackId&&this.playlistLoaded(r,t,o)}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(hf.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===ng&&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(hf.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=Zy(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:o}=s;this.hls.trigger(hf.SUBTITLE_TRACK_SWITCH,{id:e,groupId:r,name:n,type:i,url:o});const a=this.switchParams(s.url,null==t?void 0:t.details);this.loadPlaylist(a)}else this.hls.trigger(hf.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=Zy(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 Tv(this,"textTrack1"),t=new Tv(this,"textTrack2"),r=new Tv(this,"textTrack3"),n=new Tv(this,"textTrack4");this.cea608Parser1=new bv(1,e,t),this.cea608Parser2=new bv(3,r,n)}e.on(hf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(hf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(hf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(hf.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(hf.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(hf.FRAG_LOADING,this.onFragLoading,this),e.on(hf.FRAG_LOADED,this.onFragLoaded,this),e.on(hf.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(hf.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(hf.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(hf.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(hf.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(hf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(hf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(hf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(hf.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(hf.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(hf.FRAG_LOADING,this.onFragLoading,this),e.off(hf.FRAG_LOADED,this.onFragLoaded,this),e.off(hf.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(hf.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(hf.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(hf.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(hf.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],u=(o=n[0],a=n[1],l=t,c=r,Math.min(a,c)-Math.max(o,l));if(u>=0&&(n[0]=Math.min(n[0],t),n[1]=Math.max(n[1],r),i=!0,u/(r-t)>.5))return}var o,a,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(hf.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(hf.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],o=this.getExistingTrack(e);if(o)r[e]=o,hg(r[e]),ug(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(hf.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=>{hg(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++)hg(t[e])}onSubtitleTracksUpdated(e,t){const r=t.subtitleTracks||[],n=r.some((e=>e.textCodec===Uv));if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(Qy(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(Yv(e[n],t)){r=e[n];break}r&&(n=r)}if(n)hg(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(hf.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===sg){var o,a;const e=t.frag.sn,l=null!=(o=null==t||null==(a=t.part)?void 0:a.index)?o:-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===og)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===Uv?this._parseIMSC1(r,n):this._parseVTTs(t)}}else this.hls.trigger(hf.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const r=this.hls;qv(t,this.initPTS[e.cc],(t=>{this._appendCues(t,e.level),r.trigger(hf.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})}),(t=>{bf.log(`Failed to parse IMSC1: ${t}`),r.trigger(hf.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})}))}_parseVTTs(e){var t;const{frag:r,payload:n}=e,{initPTS:s,unparsedVttFrags:i}=this,o=s.length-1;if(!s[r.cc]&&-1===o)return void i.push(e);const a=this.hls;Nv(null!=(t=r.initSegment)&&t.data?Sp(r.initSegment.data,new Uint8Array(n)):n,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,(e=>{this._appendCues(e,r.level),a.trigger(hf.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),bf.log(`Failed to parse VTT cue: ${t}`),s&&o>r.cc||a.trigger(hf.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:t})}))}_fallbackToIMSC1(e,t){const r=this.tracks[e.level];r.textCodec||qv(t,this.initPTS[e.cc],(()=>{r.textCodec=Uv,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=>dg(r,e)))}else{const n=this.tracks[t];if(!n)return;const s=n.default?"default":"subtitles"+t;r.trigger(hf.CUES_PARSED,{type:"subtitles",cues:e,track:s})}}onFragDecrypted(e,t){const{frag:r}=t;r.type===og&&this.onFragLoaded(hf.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!==sg||"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=>fg(e[n],t,r)))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==n){const{textTracks:e}=this;Object.keys(e).forEach((r=>fg(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 jm{constructor(e,t,r){super(e,t,r,"[audio-stream-controller]",ig),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(hf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(hf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(hf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(hf.LEVEL_LOADED,this.onLevelLoaded,this),e.on(hf.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(hf.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(hf.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(hf.ERROR,this.onError,this),e.on(hf.BUFFER_RESET,this.onBufferReset,this),e.on(hf.BUFFER_CREATED,this.onBufferCreated,this),e.on(hf.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(hf.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(hf.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(hf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(hf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(hf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(hf.LEVEL_LOADED,this.onLevelLoaded,this),e.off(hf.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(hf.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(hf.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(hf.ERROR,this.onError,this),e.off(hf.BUFFER_RESET,this.onBufferReset,this),e.off(hf.BUFFER_CREATED,this.onBufferCreated,this),e.off(hf.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(hf.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(hf.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===Um&&this.tick()}}startLoad(e){if(!this.levels)return this.startPosition=e,void(this.state=Im);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=Rm):(this.loadedmetadata=!1,this.state=Om),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case Rm:this.doTickIdle();break;case Om:{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=Um}break}case xm:{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=Rm);break}case Um:{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=Dm;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=mm.bufferInfo(this.mediaBuffer,e,this.config.maxBufferHole);qg(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=Rm}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=Rm)}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],o=i.details;if(!o||o.live&&this.levelLastLoaded!==n||this.waitForCdnTuneIn(o))return void(this.state=Om);const a=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&a&&(this.bufferFlushed=!1,this.afterBufferFlushed(a,Af,ig));const l=this.getFwdBufferInfo(a,ig);if(null===l)return;const{bufferedTrack:c,switchingTrack:u}=this;if(!u&&this._streamEnded(l,o))return e.trigger(hf.BUFFER_EOS,{type:"audio"}),void(this.state=Fm);const d=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,sg),h=l.len,f=this.getMaxBufferLength(null==d?void 0:d.len);if(h>=f&&!u)return;const p=o.fragments[0].start;let g=l.end;if(u&&r){const e=this.getLoadPosition();c&&u.attrs!==c.attrs&&(g=e),o.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,o),y=!1;if(m&&this.isLoopLoading(m,g)&&(y=!!m.gap,m=this.getNextFragmentLoopLoading(m,o,l,sg,f)),!m)return void(this.bufferFlushed=!0);const v=d&&m.start>d.end+o.targetduration;if(v||(null==d||!d.len)&&l.len){const e=this.getAppendedFrag(m.start,sg);if(null===e)return;if(y||(y=!!e.gap||!!v&&0===d.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 _g(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=Rm):(this.switchingTrack=null,this.bufferedTrack=t,this.state=Im),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(hf.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 o=n[i];let a=0;if(s.live||null!=(r=o.details)&&r.live){const e=this.mainDetails;if(s.fragments[0]||(s.deltaUpdateFailed=!0),s.deltaUpdateFailed||!e)return;!o.details&&s.hasProgramDateTime&&e.hasProgramDateTime?(Tm(s,e),a=s.fragments[0].start):a=this.alignPlaylists(s,o.details)}o.details=s,this.levelLastLoaded=i,this.startFragRequested||!this.mainDetails&&s.live||this.setStartPosition(o.details,a),this.state!==Om||this.waitForCdnTuneIn(s)||(this.state=Rm),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:r,part:n,payload:s}=e,{config:i,trackId:o,levels:a}=this;if(!a)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=a[o];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 u=i.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new Gy(this.hls,ig,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,o=new ym(r.level,r.sn,r.stats.chunkCount,s.byteLength,t,i);d.push(s,f,u,"",r,n,c.totalduration,e,o,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 ${o}`);const{cache:e}=this.waitingData=this.waitingData||{frag:r,part:n,cache:new Yy,complete:!1};e.push(new Uint8Array(s)),this.waitingVideoCC=this.videoTrackCC,this.state=Um}}_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===ig)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(hf.AUDIO_TRACK_SWITCHED,lf({},e)))}this.fragBufferedComplete(r,n)}else if(!this.loadedmetadata&&r.type===sg){const e=this.videoBuffer||this.media;if(e){mm.getBuffered(e).length&&(this.loadedmetadata=!0)}}}onError(e,t){var r;if(t.fatal)this.state=Nm;else switch(t.details){case pf.FRAG_GAP:case pf.FRAG_PARSING_ERROR:case pf.FRAG_DECRYPT_ERROR:case pf.FRAG_LOAD_ERROR:case pf.FRAG_LOAD_TIMEOUT:case pf.KEY_LOAD_ERROR:case pf.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ig,t);break;case pf.AUDIO_TRACK_LOAD_ERROR:case pf.AUDIO_TRACK_LOAD_TIMEOUT:case pf.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==Om||(null==(r=t.context)?void 0:r.type)!==rg||(this.state=Rm);break;case pf.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 pf.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushed(e,{type:t}){t===Af&&(this.bufferFlushed=!0,this.state===Fm&&(this.state=Rm))}_handleTransmuxComplete(e){var t;const r="audio",{hls:n}=this,{remuxResult:s,chunkMeta:i}=e,o=this.getCurrentContext(i);if(!o)return void this.resetWhenMissingContext(i);const{frag:a,part:l,level:c}=o,{details:u}=c,{audio:d,text:h,id3:f,initSegment:p}=s;if(!this.fragContextChanged(a)&&u){if(this.state=Pm,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),null!=p&&p.tracks){const e=a.initSegment||a;this._bufferInitSegment(p.tracks,e,i),n.trigger(hf.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:r,tracks:p.tracks})}if(d){const{startPTS:e,endPTS:t,startDTS:r,endDTS:n}=d;l&&(l.elementaryStreams[Af]={startPTS:e,endPTS:t,startDTS:r,endDTS:n}),a.setElementaryStreamInfo(Af,e,t,r,n),this.bufferFragmentData(d,a,l,i)}if(null!=f&&null!=(t=f.samples)&&t.length){const e=uf({id:r,frag:a,details:u},f);n.trigger(hf.FRAG_PARSING_METADATA,e)}if(h){const e=uf({id:r,frag:a,details:u},h);n.trigger(hf.FRAG_PARSING_USERDATA,e)}}else this.fragmentTracker.removeFragment(a)}_bufferInitSegment(e,t,r){if(this.state!==Pm)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(hf.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(hf.BUFFER_APPENDING,e)}this.tick()}loadFragment(e,t,r){const n=this.fragmentTracker.getState(e);var s;(this.fragCurrent=e,this.switchingTrack||n===rm||n===sm)?"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=Um):(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(hf.AUDIO_TRACK_SWITCHED,lf({},e))}},audioTrackController:class extends Xg{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(hf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(hf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(hf.LEVEL_LOADING,this.onLevelLoading,this),e.on(hf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(hf.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(hf.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(hf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(hf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(hf.LEVEL_LOADING,this.onLevelLoading,this),e.off(hf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(hf.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(hf.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 o=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,o)}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(hf.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===rg&&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(hf.AUDIO_TRACK_SWITCHING,lf({},n)),n.details&&!n.details.live)return;const o=this.switchParams(n.url,null==r?void 0:r.details);this.loadPlaylist(o)}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(hf.ERROR,{type:ff.MEDIA_ERROR,details:pf.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(hf.AUDIO_TRACK_LOADING,{url:s,id:r,groupId:n,deliveryDirectives:e||null})}}},emeController:Jv,cmcdController:ob,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=bf.log.bind(bf,"[content-steering]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(hf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(hf.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(hf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(hf.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(hf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(hf.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(hf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(hf.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)===Hg&&r.flags===Wg){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,o=this.hls.levels[i];if(t=this.getLevelsForPathway(s),t.length>0){this.log(`Setting Pathway to "${s}"`),this.pathwayId=s,this.hls.trigger(hf.LEVELS_UPDATED,{levels:t});const e=this.hls.levels[i];o&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==o.bitrate&&this.log(`Unstable Pathways change from bitrate ${o.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":o}=e;if(t.some((e=>e.pathwayId===s)))return;const a=this.getLevelsForPathway(i).map((e=>{const t=uf({},e);t.details=void 0,t.url=lb(e.uri,e.attrs["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",o);const i=new Tf(e.attrs);i["PATHWAY-ID"]=s;const a=i.AUDIO&&`${i.AUDIO}_clone_${s}`,l=i.SUBTITLES&&`${i.SUBTITLES}_clone_${s}`;a&&(r[i.AUDIO]=a,i.AUDIO=a),l&&(n[i.SUBTITLES]=l,i.SUBTITLES=l),t.attrs=i;const c=new _g(t);return em(c,"audio",a),em(c,"text",l),c}));t.push(...a),ab(this.audioTracks,r,o,s),ab(this.subtitleTracks,n,o,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,o=i.errorRetry||i.timeoutRetry||{},a={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.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":o,"PATHWAY-CLONES":a,"PATHWAY-PRIORITY":l}=i;if(o)try{this.uri=new self.URL(o,n).href}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${o}`)}this.scheduleRefresh(this.uri||r.url),a&&this.clonePathways(a),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,a,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){self.clearTimeout(this.reloadTimer),this.reloadTimer=self.setTimeout((()=>{this.loadSteeringManifest(e)}),t)}}});function vb(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(vb):Object.keys(e).reduce(((t,r)=>(t[r]=vb(e[r]),t)),{}):e}function bb(e){const t=e.loader;if(t!==hb&&t!==ub)bf.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=hb,e.progressive=!0,e.enableSoftwareAES=!0,bf.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class wb{static get version(){return"1.4.10"}static isSupported(){return function(){const e=Np();if(!e)return!1;const t=$m(),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 hf}static get ErrorTypes(){return ff}static get ErrorDetails(){return pf}static get DefaultConfig(){return wb.defaultConfig?wb.defaultConfig:yb}static set DefaultConfig(e){wb.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new qy,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){vf(e,"debug","log","info","warn","error");try{yf.log(`Debug logs enabled for "${t}" in hls.js version 1.4.10`)}catch(e){yf=mf}}else yf=mf}(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=vb(e),n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((e=>{const s=`${"level"===e?"playlist":e}LoadPolicy`,i=void 0===t[s],o=[];n.forEach((n=>{const a=`${e}Loading${n}`,l=t[a];if(void 0!==l&&i){o.push(a);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}}})),o.length&&bf.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${s}": ${JSON.stringify(t[s])}`)})),lf(lf({},r),t)}(wb.DefaultConfig,e);this.userConfig=e,this._autoLevelCapping=-1,t.progressive&&bb(t);const{abrController:r,bufferController:n,capLevelController:s,errorController:i,fpsController:o}=t,a=new i(this),l=this.abrController=new r(this),c=this.bufferController=new n(this),u=this.capLevelController=new s(this),d=new o(this),h=new cg(this),f=new wg(this),p=t.contentSteeringController,g=p?new p(this):null,m=this.levelController=new Zg(this,g),y=new om(this),v=new pm(this.config),b=this.streamController=new Vy(this,y,v);u.setStreamController(b),d.setStreamController(b);const w=[h,m,b];g&&w.splice(1,0,g),this.networkControllers=w;const E=[l,c,u,d,f,y];this.audioTrackController=this.createController(t.audioTrackController,w);const T=t.audioStreamController;T&&w.push(new T(this,y,v)),this.subtitleTrackController=this.createController(t.subtitleTrackController,w);const S=t.subtitleStreamController;S&&w.push(new S(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(Eg,E),this.coreComponents=E,w.push(a);const C=a.onErrorOut;"function"==typeof C&&this.on(hf.ERROR,C,a)}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){bf.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),this.trigger(hf.ERROR,{type:ff.OTHER_ERROR,details:pf.INTERNAL_EXCEPTION,fatal:!1,event:e,error:t})}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){bf.log("destroy"),this.trigger(hf.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){bf.log("attachMedia"),this._media=e,this.trigger(hf.MEDIA_ATTACHING,{media:e})}detachMedia(){bf.log("detachMedia"),this.trigger(hf.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const t=this.media,r=this.url,n=this.url=of.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});bf.log(`loadSource:${n}`),t&&r&&(r!==n||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(hf.MANIFEST_LOADING,{url:e})}startLoad(e=-1){bf.log(`startLoad(${e})`),this.networkControllers.forEach((t=>{t.startLoad(e)}))}stopLoad(){bf.log("stopLoad"),this.networkControllers.forEach((e=>{e.stopLoad()}))}swapAudioCodec(){bf.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){bf.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){bf.log(`set currentLevel:${e}`),this.loadLevel=e,this.abrController.clearTimer(),this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){bf.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){bf.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){bf.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){return this.levelController.startLevel}set startLevel(e){bf.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&&(bf.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e)}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){Tg.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}}wb.defaultConfig=void 0;const Eb={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};function Tb(e){const t=new Uint8Array(e);let r="";return t.forEach((e=>{r+=String.fromCharCode(e)})),M(r)}function Sb(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}(q(t));return crypto.subtle.importKey("pkcs8",r,Eb,!1,["sign"])}async function Cb({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=Ta.v4(),s=`nonceStr=${n}×tamp=${e}&data=${r}==`,i=(new TextEncoder).encode(s),o=await Sb("-----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:Tb(await crypto.subtle.sign(Eb,o,i)),nonceStr:n}}({timestamp:r,streams:s});if(!i||!i.signature)throw new Error("Signature is undefined");const o={signature:i.signature,nonceStr:i.nonceStr,timestamp:r,streams:s},a=ye();return await a.http.post("/api/v3/user-event/video-streaming",o),t().length||e().length||n(),!0}catch(e){return s.forEach((e=>r(e))),!1}}class kb{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((()=>{Cb({bufferCurrentUsage:this.bufferCurrentUsage.bind(this),getActiveStreams:this.getActiveStreams.bind(this),updateUsage:this.updateUsage.bind(this),dispose:this.dispose.bind(this)})}),2e4)}}let Ab=null;class _b{constructor(e,t){this.player=e,this.resolution=t,this._startTime=null,this._usageCollector=Ab||(Ab=new kb,Ab),this._usageCollector.registerStream(e.id),this._sessionId=String(Ta.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 Ib=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(!wb.isSupported())throw new Error("This browswer does not support hls, unable to play stream");const{data:r}=await Vh(t),{watcherUrl:n,status:s,recordings:i=[],resolution:o}=r;if(!n.hls)throw new Error("This stream does not support hls. Unable to play");const a=document.createElement("video");a.id=t,a.controls=!0;const l=new wb;if(l.attachMedia(a),"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");a.src=e.mp4.url}return new _b(a,o).registerEvents(),a}});const Rb=e=>{const t=(e=>{const t=ye(),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 La(t),t},Lb=({payload:e,formData:t,isVideo:r=!1},n)=>{if(t){const s=t.get("files"),i=new FileReader;i.readAsDataURL(s),i.onload=()=>n(Rb(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(Rb(Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileData:null})})))},Db=e=>{const{storyId:t,referenceId:r}=e;return r?Object.assign(Object.assign({},e),{syncState:"synced"}):Object.assign(Object.assign({},e),{syncState:"synced",referenceId:t})},xb=e=>{const{stories:t}=e,r=t.map(Db);return Object.assign(Object.assign({},e),{stories:r})},Ob=async e=>{const t=ye();t.log("post/createStory",e);const r=await t.http.post("/api/v4/stories",e),n=xb(r.data);t.cache&&La(n),Ee(["story-sync-state",e.targetId],"synced"),Qe("story.created",n);const s=t.cache&&Date.now();return{data:n.stories.length>0?n.stories[0]:void 0,cachedAt:s}},Pb=e=>e?we(["story","get",e]):{data:void 0,cachedAt:void 0},Mb=async(e,t=!1)=>{const r=ye();let n;if(r.log("story/deleteStory",e),r.cache&&(n=Pb(e),null==n?void 0:n.data)){const{data:e}=n;Qe("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},Fb=async({targetType:e,targetId:t,options:r})=>{const n=ye();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"}}}),o=xb(i.data);return n.cache&&(La(o),o.stories.forEach((e=>{const t=we(["story-expire",e.targetId]),r=new Date(e.expiresAt||0);r<new Date((null==t?void 0:t.data)||0)||Ee(["story-expire",e.targetId],r.toISOString())})),(e=>{e.forEach((e=>{Ee(["story-reference",e.storyId],e.referenceId)}))})(o.stories)),{data:o.stories,cachedAt:s,paging:{next:void 0,previous:void 0}}},Nb=e=>{const t=ye();return Ye(t,"onStoryDeleted","story.deleted",(async t=>{La(t),e(t.stories)}))},Ub=e=>{const t=ye();return Ye(t,"onStoryError","story.error",(async t=>{La(t),e(t.stories)}))},Bb=async e=>{const t=ye();t.log("story/getStoryByStoryId",e);const r=we(["story-reference",e]);if(null==r?void 0:r.data){const{data:e}=r;Ol("story",e)}let n;try{n=(await t.http.get(`/api/v4/stories/${e}`)).data}catch(t){throw S(null==t?void 0:t.code)&&Da("story",e),t}const s=t.cache&&Date.now();return t.cache&&La(n,{cachedAt:s}),{data:n.stories[0],cachedAt:s}};Bb.locally=e=>{const t=ye();t.log("story/getStorybyStoryId",e);const r=we(["story-reference",e]);if(null==r?void 0:r.data){const{data:e}=r;Ol("story",e)}const n=t.cache&&Date.now(),s=we(["story","get",e]);if(s)return{data:s.data,cachedAt:n}};const jb=e=>t=>e((e=>t(e[0]))),$b=async e=>{const t=ye();t.log("story/getTargetsByTargetIds",e);const r=await t.http.get("/api/v4/stories/seen",{params:{targets:e}}),{data:n}=r;return t.cache&&La(r.data),{data:n.storyTargets,cachedAt:Date.now()}};var qb=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 o={data:{text:"",fileId:void 0,fileData:null,imageDisplayMode:s},syncState:"syncing",referenceId:Sa(),dataType:"image",items:i,targetType:e,targetId:t,metadata:n};Ee(["story-sync-state",t],"syncing"),Lb({payload:o,formData:r},(e=>{Qe("story.created",e)}));try{const{data:e}=await xu(r);if(0===e.length)throw new Error("Failed to upload image");const{fileId:t}=e[0];o=Object.assign(Object.assign({},o),{data:Object.assign(Object.assign({},o.data),{fileId:t})}),Lb({payload:o,formData:r},(e=>{Qe("story.created",e)}));const n=await Ob(o);return n.data?Object.assign(Object.assign({},n),{data:el.story(n.data)}):n}catch(e){throw Ee(["story-sync-state",t],"error"),Lb({payload:Object.assign(Object.assign({},o),{syncState:"error"}),formData:r},(e=>{Qe("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:Sa(),dataType:"video",items:s,targetType:e,targetId:t,metadata:n};Ee(["story-sync-state",t],"syncing"),Lb({payload:i,formData:r,isVideo:!0},(e=>{Qe("story.created",e)}));try{const{data:e}=await Du(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}})}),Lb({payload:i,formData:r,isVideo:!0},(e=>{Qe("story.created",e)}));const n=await Ob(i);return n.data?Object.assign(Object.assign({},n),{data:el.story(n.data)}):n}catch(e){throw Ee(["story-sync-state",t],"error"),Lb({payload:Object.assign(Object.assign({},i),{syncState:"error"}),formData:r,isVideo:!0},(e=>{Qe("story.error",e)})),e}},hardDeleteStory:async e=>await Mb(e,!0),softDeleteStory:async e=>await Mb(e),getActiveStoriesByTarget:(e,t)=>{const{log:r,cache:n}=ye(),s=[],i=["story-target","collection",e],o=Date.now();r(`getActiveStoriesByTarget(tmpid: ${o}) > listen`),n||console.log(p);const a=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(Me):t.sort(Fe):"asc"===i?t.sort(Ne):t.sort(Ue)},l=e=>{var r;const n=e.data.map((e=>{const t=Pb(e);if(null==t?void 0:t.data)return el.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=a(e.get("error")||[]);s.push(...t)}if(e.has("syncing")){const t=a(e.get("syncing")||[]);s.push(...t)}if(e.has("synced")){const t=a(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=!1,r=!1,n=!1)=>{const s=we(i),o={loading:r,error:n,params:{page:void 0},data:(null==s?void 0:s.data)||[]};e&&(o.data=t?e.map(ce("story")):[...new Set([...o.data,...e.map(ce("story"))])]),Ee(i,o.data),l(o)},u=e=>e=>{c(e)};return(t=>{const r=se(Fb,e);oe(r,(({data:e,error:r,loading:n})=>{c(e,t,n,r)}))})(!0),s.push((e=>{const t=ye();return Ye(t,"onStoryCreated","story.created",(async t=>{La(t),e(t.stories)}))})(u()),(e=>{const t=ye();return Ye(t,"onStoryUpdated","story.updated",(async t=>{La(t),e(t.stories)}))})(u()),Nb(u()),Ub(u()),(e=>{const t=ye();return Ye(t,"onStoryLocalDataUpdated","local.story.updated",(t=>{e(t)}))})((e=>{const t=we(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)})),(()=>Ce(i))),()=>{r(`getActiveStoriesByTarget(tmpid: ${o}) > dispose`),s.forEach((e=>e()))}},getStoryByStoryId:(e,t)=>wc(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:el.story(e.data)})):t(e)}),"storyId",Bb,[jb(Nb),jb(Ub)]),getTargetById:(e,t)=>wc(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:el.storyTarget(e.data[0])})):t(e)}),"query",(e=>$b([e])),[]),getTargetsByTargetIds:(e,t)=>{const{log:r,cache:n}=ye(),s=[],i=["storyTargets","collection",e],o=Date.now();r(`getTargetsByTargetIds(tmpid: ${o}) > listen`),n||console.log(p);const a=(e,r=!1,n=!1,s=!1)=>{const o=we(i),a={loading:n,error:s,params:{page:void 0},data:[]};e&&(a.data=r?e.map(ce("storyTarget")):[...new Set([...(null==o?void 0:o.data)||[],...e.map(ce("storyTarget"))])]),Ee(i,a.data),(e=>{var r;const n=e.data.map((e=>{const t=we(["storyTarget","get",e]);if(null==t?void 0:t.data)return el.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})})(a)};return(t=>{const r=se($b,e);oe(r,(({data:e,error:r,loading:n})=>{a(e,t,n,r)}))})(!0),s.push((()=>Ce(i))),()=>{r(`getTargetsByTargetIds(tmpid: ${o}) > dispose`),s.forEach((e=>e()))}}});return e.API_REGIONS=St,e.CategoryRepository=Oh,e.ChannelRepository=xd,e.Client=eu,e.CommentRepository=Hh,e.CommunityPostSettingMaps=o,e.CommunityPostSettings=i,e.CommunityRepository=Lh,e.ContentFeedType=l,e.DefaultCommunityPostSetting=a,e.FeedRepository=Fh,e.FileRepository=Ou,e.FileType=t,e.LiveStreamPlayer=Ib,e.MessageContentType=c,e.MessageRepository=Vd,e.PollRepository=rf,e.PostContentType=u,e.PostRepository=jh,e.ReactionRepository=ud,e.StoryRepository=qb,e.StreamRepository=Jh,e.SubChannelRepository=Jd,e.UserRepository=Ru,e.VERSION=d,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}=ye();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=se,e.createReport=async(e,t)=>{const r=ye();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}=dd[e];return`/api/v3/${r}/${encodeURIComponent(t)}/flag`})());if(r.cache)if("message"===e){const e=await Cl(n);La(e)}else La("post"===e?Pa(n,"communityUsers"):n);return Qe(`${e}.flagged`,n),!!n},e.createUserToken=async(e,t,r)=>{const n=await ka(),s=Aa(),i=cn(kt("http",t)),{data:o}=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:o.accessToken}},e.deleteReport=async(e,t)=>{const r=ye();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}=dd[e];return`/api/v3/${r}/${encodeURIComponent(t)}/unflag`})());if(r.cache)if("message"===e){const e=await Cl(n);La(e)}else La("post"===e?Pa(n,"communityUsers"):n);return Qe(`${e}.unflagged`,n),!!n},e.disableCache=()=>{const e=ye();e.cache&&(e.log("cache/api/disableCache"),delete e.cache)},e.dropFromCache=Ce,e.enableCache=(e={},t)=>{const r=ye();r.cache||(r.log("cache/api/enableCache"),r.cache={data:e,persistIf:t})},e.filterByChannelMembership=Ie,e.filterByCommunityMembership=Le,e.filterByFeedType=Re,e.filterByPostDataTypes=De,e.filterByPropEquality=ke,e.filterByPropInclusion=(e,t,r)=>void 0!==r?e.filter((e=>r.includes(e[t]))):e,e.filterByPropIntersection=_e,e.filterBySearchTerm=xe,e.filterByStringComparePartially=Ae,e.getChannelTopic=e=>`${e.path}/#`,e.getCommentTopic=({path:e})=>e,e.getCommunityTopic=({path:t},r=e.SubscriptionLevels.COMMUNITY)=>tt(t,r),e.getMarkedMessageTopic=st,e.getMessageTopic=e=>e.path,e.getMyFollowersTopic=()=>{const e=$e();return`${rt(e)}/membership/${e._id}/+/+`},e.getMyFollowingsTopic=()=>{const e=$e();return`${rt(e)}/membership/+/${e._id}/+`},e.getNetworkTopic=it,e.getPostTopic=({path:t},r=e.SubscriptionLevels.POST)=>"comment"===r?`${t}/comment/+`:t,e.getRole=Mu,e.getSmartFeedChannelTopic=ot,e.getSmartFeedMessageTopic=lt,e.getSmartFeedSubChannelTopic=at,e.getSubChannelTopic=e=>`${e.path}/#`,e.getUserTopic=nt,e.isAfterBefore=z,e.isAfterBeforeRaw=W,e.isCachable=re,e.isFetcher=Z,e.isFresh=ne,e.isLocal=e=>re(e)&&-1===(null==e?void 0:e.cachedAt),e.isMutator=ee,e.isOffline=te,e.isPaged=Y,e.isReportedByMe=async(e,t)=>{var r;const n=ye();n.log("report/isReportedByMe",{referenceType:e,referenceId:t});const{domainName:s}=dd[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:o,isFlagByMe:a}=null!=i?i:{};return null!==(r=null!=o?o:a)&&void 0!==r&&r},e.isSkip=V,e.mergeInCache=Te,e.onChannelMarkerFetched=dc,e.onFeedMarkerFetched=e=>{const t=ye();return Ye(t,"feedMarker/onFeedMarkerFetched","local.feedMarker.fetched",(t=>{e(t.feedMarkers[0])}))},e.onFeedMarkerUpdated=pc,e.onMessageMarked=yc,e.onMessageMarkerFetched=mc,e.onSubChannelMarkerFetched=hc,e.onSubChannelMarkerUpdated=fc,e.onUserMarkerFetched=gc,e.pullFromCache=we,e.pushToCache=Ee,e.queryCache=be,e.queryOptions=ie,e.queryRoles=Pu,e.restoreCache=async(e="amitySdk")=>{var t;const r=ye();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=Oe,e.sortByFirstCreated=Me,e.sortByFirstUpdated=Ne,e.sortByLastActivity=Be,e.sortByLastCreated=Fe,e.sortByLastUpdated=Ue,e.sortByName=Pe,e.sortBySegmentNumber=({segmentNumber:e},{segmentNumber:t})=>e-t,e.subscribeTopic=ct,e.toPage=X,e.toPageRaw=J,e.toToken=Q,e.upsertInCache=Se,e.wipeCache=async(e="amitySdk")=>{const{log:t,cache:r,userId:n}=ye();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 o(e,t,r){return s(e,t,r)}s.from&&s.alloc&&s.allocUnsafe&&s.allocUnsafeSlow?t.exports=n:(i(n,r),r.Buffer=o),o.prototype=Object.create(s.prototype),i(s,o),o.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return s(e,t,r)},o.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},o.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return s(e)},o.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 o(e){var t=i(e);if("string"!=typeof t&&(n.isEncoding===s||!s(e)))throw new Error("Unknown encoding: "+e);return t||e}function a(e){var t;switch(this.encoding=o(e),this.encoding){case"utf16le":this.text=p,this.end=g,t=4;break;case"utf8":this.fillLast=d,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 u(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 d(e){var t=this.lastTotal-this.lastNeed,r=u(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=a,a.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||""},a.prototype.end=f,a.prototype.text=h,a.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=T,r.resolveObject=S,r.format=E,r.Url=i;var o=/^([a-z0-9.+-]+:)/i,a=/:[0-9]*$/,l=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,c=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),u=["'"].concat(c),d=["%","/","?",";","#"].concat(u),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 T(e,t){return w(e,!1,!0).resolve(t)}function S(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("?"),a=-1!==i&&i<e.indexOf("#")?"?":"#",c=e.split(a),w=/\\/g;c[0]=c[0].replace(w,"/");var E=e=c.join(a);if(E=E.trim(),!r&&1===e.split("#").length){var T=l.exec(E);if(T)return this.path=E,this.href=E,this.pathname=T[1],T[2]?(this.search=T[2],this.query=t?b.parse(this.search.substr(1)):this.search.substr(1)):t&&(this.search="",this.query={}),this}var S=o.exec(E);if(S){var C=(S=S[0]).toLowerCase();this.protocol=C,E=E.substr(S.length)}if(r||S||E.match(/^\/\/[^@\/]+@[^@\/]+/)){var k="//"===E.substr(0,2);!k||S&&y[S]||(E=E.substr(2),this.slashes=!0)}if(!y[S]&&(k||S&&!v[S])){for(var A,_,I=-1,R=0;R<h.length;R++)-1!==(L=E.indexOf(h[R]))&&(-1===I||L<I)&&(I=L);for(-1!==(_=-1===I?E.lastIndexOf("@"):E.lastIndexOf("@",I))&&(A=E.slice(0,_),E=E.slice(_+1),this.auth=decodeURIComponent(A)),I=-1,R=0;R<d.length;R++){var L;-1!==(L=E.indexOf(d[R]))&&(-1===I||L<I)&&(I=L)}-1===I&&(I=E.length),this.host=E.slice(0,I),E=E.slice(I),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,N=P.length;F<N;F++)P.charCodeAt(F)>127?M+="x":M+=P[F];if(!M.match(p)){var U=x.slice(0,R),B=x.slice(R+1),j=P.match(g);j&&(U.push(j[1]),B.unshift(j[2])),B.length&&(E="/"+B.join(".")+E),this.hostname=U.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=u.length;R<O;R++){var K=u[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,o="";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&&(o=b.stringify(this.query));var a=this.search||o&&"?"+o||"";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),a&&"?"!==a.charAt(0)&&(a="?"+a),t+i+(r=r.replace(/[?#]/g,(function(e){return encodeURIComponent(e)})))+(a=a.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),o=0;o<n.length;o++){var a=n[o];r[a]=this[a]}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 u=l[c];"protocol"!==u&&(r[u]=e[u])}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 d=Object.keys(e),h=0;h<d.length;h++){var f=d[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,T=E,S=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&&(""===S[0]?S[0]=r.host:S.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]||""===S[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,S=p;else if(p.length)S||(S=[]),S.pop(),S=S.concat(p),r.search=e.search,r.query=e.query;else if(!s.isNullOrUndefined(e.search))return C&&(r.hostname=r.host=S.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(!S.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var k=S.slice(-1)[0],A=(r.host||e.host||S.length>1)&&("."===k||".."===k)||""===k,_=0,I=S.length;I>=0;I--)"."===(k=S[I])?S.splice(I,1):".."===k?(S.splice(I,1),_++):_&&(S.splice(I,1),_--);if(!E&&!T)for(;_--;_)S.unshift("..");!E||""===S[0]||S[0]&&"/"===S[0].charAt(0)||S.unshift(""),A&&"/"!==S.join("/").substr(-1)&&S.push("");var R,L=""===S[0]||S[0]&&"/"===S[0].charAt(0);return C&&(r.hostname=r.host=L?"":S.length?S.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&&S.length)&&!L&&S.unshift(""),S.length?r.pathname=S.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=a.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!==ut?ut:"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 a(r,null,t,e):new a(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 a(t,e.tail,null,e),e.head||(e.head=e.tail),e.length++}function o(e,t){e.head=new a(t,null,e.head,e),e.tail||(e.tail=e.head),e.length++}function a(e,t,r,n){if(!(this instanceof a))return new a(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=a,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++)o(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 o=[];for(n=0;i&&n<t;n++)o.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 o},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)}(Ao);var _o=dt(Ao.exports);class Io{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 Ro=()=>"undefined"!=typeof window&&window.localStorage?window:{localStorage:new Io};var Lo={},Do={},xo={};Object.defineProperty(xo,"__esModule",{value:!0}),xo.bytesToString=xo.stringToBytes=xo.NIL=xo.X500=xo.OID=xo.URL=xo.DNS=xo.hexToByte=xo.byteToHex=void 0;let Oo=[],Po={};for(var Mo=0;Mo<256;Mo++)Oo[Mo]=(Mo+256).toString(16).substr(1),Po[Oo[Mo]]=Mo;xo.byteToHex=Oo,xo.hexToByte=Po,xo.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",xo.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",xo.OID="6ba7b812-9dad-11d1-80b4-00c04fd430c8",xo.X500="6ba7b814-9dad-11d1-80b4-00c04fd430c8",xo.NIL="00000000-0000-0000-0000-000000000000";xo.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};xo.bytesToString=e=>{const t=new Uint8Array(e,0,e.byteLength);return String.fromCharCode.apply(null,Array.from(t))},Object.defineProperty(Do,"__esModule",{value:!0}),Do.parse=void 0;const Fo=xo;Do.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++]=Fo.hexToByte[e]),"")));s<16;)t[n+s++]=0;return t};var No={};Object.defineProperty(No,"__esModule",{value:!0}),No.unparse=void 0;const Uo=xo;No.unparse=(e,t)=>{let r=t||0,n=Uo.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 Bo={},jo={};Object.defineProperty(jo,"__esModule",{value:!0});jo.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 $o=ut&&ut.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Bo,"__esModule",{value:!0}),Bo.validate=void 0;const qo=$o(jo);Bo.validate=e=>"string"==typeof e&&qo.default.test(e);var Ko={};Object.defineProperty(Ko,"__esModule",{value:!0}),Ko.version=void 0;const Go=Bo;Ko.version=e=>{if(!Go.validate(e))throw TypeError("Invalid UUID");return parseInt(e.substr(14,1),16)};var Ho={},Vo={};Object.defineProperty(Vo,"__esModule",{value:!0}),Vo.stringify=void 0;const zo=Bo,Wo=[];for(let e=0;e<256;++e)Wo.push((e+256).toString(16).substr(1));Vo.stringify=(e,t=0)=>{const r=(Wo[e[t+0]]+Wo[e[t+1]]+Wo[e[t+2]]+Wo[e[t+3]]+"-"+Wo[e[t+4]]+Wo[e[t+5]]+"-"+Wo[e[t+6]]+Wo[e[t+7]]+"-"+Wo[e[t+8]]+Wo[e[t+9]]+"-"+Wo[e[t+10]]+Wo[e[t+11]]+Wo[e[t+12]]+Wo[e[t+13]]+Wo[e[t+14]]+Wo[e[t+15]]).toLowerCase();if(!zo.validate(r))throw TypeError("Stringified UUID is invalid");return r};var Yo={};Object.defineProperty(Yo,"__esModule",{value:!0}),Yo.rng=void 0;Yo.rng=()=>{let e=new Array(16);for(let t=0;t<16;t++)e[t]=255&256*Math.random()+0;return e},Object.defineProperty(Ho,"__esModule",{value:!0}),Ho.v1=void 0;const Qo=Vo,Xo=Yo;let Jo,Zo,ea=0,ta=0;Ho.v1=(e,t,r=0)=>{let n=t&&r||0;const s=t||new Uint8Array(16);let i=e&&e.node?e.node:Jo,o=e&&e.clockseq?e.clockseq:Zo;if(null==i||null==o){const t=e&&e.random?e.random:e&&e.rng?e.rng():Xo.rng();null==i&&(i=Jo=[1|t[0],t[1],t[2],t[3],t[4],t[5]]),null==o&&(o=Zo=16383&(t[6]<<8|t[7]))}let a=e&&e.msecs?e.msecs:Date.now(),l=e&&e.nsecs?e.nsecs:ta+1;const c=a-ea+(l-ta)/1e4;if(c<0&&e&&!e.clockseq&&(o=o+1&16383),(c<0||a>ea)&&e&&!e.nsecs&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");ea=a,ta=l,Zo=o,a+=122192928e5;const u=(1e4*(268435455&a)+l)%4294967296;s[n++]=u>>>24&255,s[n++]=u>>>16&255,s[n++]=u>>>8&255,s[n++]=255&u;const d=a/4294967296*1e4&268435455;s[n++]=d>>>8&255,s[n++]=255&d,s[n++]=d>>>24&15|16,s[n++]=d>>>16&255,s[n++]=o>>>8|128,s[n++]=255&o;for(let e=0;e<6;++e)s[n+e]=i[e];return t||Qo.stringify(s)};var ra={};Object.defineProperty(ra,"__esModule",{value:!0}),ra.v4=void 0;const na=No,sa=Yo;ra.v4=(e,t,r)=>{let n=t&&r||0,s=sa.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||na.unparse(s)};var ia={},oa={};Object.defineProperty(oa,"__esModule",{value:!0}),oa.v35=void 0;const aa=Vo,la=Do,ca=xo;oa.v35=(e,t,r)=>(e,n,s,i=0)=>{if("string"==typeof e&&(e=ca.stringToBytes(e)),"string"==typeof n&&(n=la.parse(n)),n&&16!==n.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let o=new Uint8Array(16+e.length);if(o.set(n),o.set(e,n.length),o=ca.stringToBytes(r(ca.bytesToString(o))),o[6]=15&o[6]|t,o[8]=63&o[8]|128,s)for(let e=0;e<16;++e)s[i+e]=o[e];return s||aa.stringify(o)};var ua={};!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=>o(n(l(e)));e.any_sha1=(e,t)=>a(n(l(e)),t);e.hex_hmac_sha1=(e,t)=>i(s(l(e),l(t)));e.b64_hmac_sha1=(e,t)=>o(s(l(e),l(t)));e.any_hmac_sha1=(e,t,r)=>a(s(l(e),l(t)),r);const n=e=>u(d(c(e),8*e.length)),s=(e,t)=>{let r=c(e);r.length>16&&(r=d(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 o=d(n.concat(c(t)),512+8*t.length);return u(d(s.concat(o),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},o=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),o=0;o<4;o++)8*s+6*o>8*e.length?t+=r:t+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(i>>>6*(3-o)&63);return t},a=(e,t)=>{var r,n,s,i,o=t.length,a=[],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/o))*o,(i.length>0||n>0)&&(i[i.length]=n);a[a.length]=s,l=i}var c="";for(r=a.length-1;r>=0;r--)c+=t.charAt(a[r]);var u=Math.ceil(8*e.length/(Math.log(t.length)/Math.log(2)));for(r=c.length;r<u;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},u=e=>{for(var t="",r=0;r<32*e.length;r+=8)t+=String.fromCharCode(e[r>>5]>>>24-r%32&255);return t},d=(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,o=271733878,a=-1009589776,l=0;l<e.length;l+=16){for(var c=n,u=s,d=i,m=o,y=a,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,o)),p(p(a,r[v]),f(v)));a=o,o=i,i=g(s,30),s=n,n=t}n=p(n,c),s=p(s,u),i=p(i,d),o=p(o,m),a=p(a,y)}return[n,s,i,o,a]},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}(ua);var da=ut&&ut.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ia,"__esModule",{value:!0}),ia.v5=void 0;const ha=oa,fa=da(ua);ia.v5=ha.v35("v5",80,fa.default),Object.defineProperty(Lo,"__esModule",{value:!0});const pa=Do,ga=No,ma=Bo,ya=Ko,va=Ho,ba=ra,wa=ia,Ea=xo;var Ta=Lo.default={parse:pa.parse,unparse:ga.unparse,validate:ma.validate,version:ya.version,v1:va.v1,v4:ba.v4,v5:wa.v5,NIL:Ea.NIL,DNS:Ea.DNS,URL:Ea.URL,OID:Ea.OID,X500:Ea.X500};const Sa=()=>Ta.v4().toString();let Ca=0;if("undefined"!=typeof BroadcastChannel&&"undefined"!=typeof window){const e=Sa(),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:Ca}),"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&&(Ca=e.reduce(((e,t)=>e<t?e:t+1),0))}),15))))}}const ka=async()=>{const e=await(async e=>new Promise((t=>{t(Ro().localStorage.getItem(e))})))("deviceId");if(e)return e;const t=`ascWebSdk#${Sa()}`;return await(async(e,t)=>new Promise((r=>{Ro().localStorage.setItem(e,t),r(!0)})))("deviceId",t),t},Aa=()=>{const e=(()=>{var e,t;return(null===(e=Et.versions)||void 0===e?void 0:e.node)?Et.versions.node:navigator?`${navigator.product.toLowerCase()}#${null!==(t=navigator.userAgent)&&void 0!==t?t:"unknown_agent"}`:"unknown_model"})();return{kind:"web",model:e,sdkVersion:d}},_a=1e3;var Ia;!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"}(Ia||(Ia={}));const Ra=e=>{let t;return{connect:async function(r){const n=await(async e=>`mqttjs_${await ka()}_${e}_${Ca}`)(r.userId);return t&&(t.removeAllListeners(),t.end(!0)),t=_o.connect(e,function(e){return Object.assign({clean:!1,clientId:`mqttjs_ + ${Math.random().toString(16).substring(2,10)}`,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:_a,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=_a,(()=>{const e=[ct(it()),ct(ot()),ct(at()),ct(lt()),ct(nt($e()))]})()})),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||_a),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 he(t.message,8e5,"error"):new pe(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)}}},La=(e={},t,r=!0)=>{Object.entries(e).forEach((([e,n])=>{const s=ue[e];if(!s)return;const i=ce(s);i&&n.forEach((e=>{(r?Ee:Se)([s,"get",i(e)],e,t)}))}))},Da=(e,t)=>{const{log:r,cache:n}=ye(),s=[e,y,t],i={cachedAt:Date.now()};n&&(r("cache/api/pushToTombstone",{cacheKey:s,data:i}),Ce([e,"get",t],!0),Ee(s,i))};function xa(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 Oa=(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(!ye().cache)return;return(null===(r=we(["user","get",e[t]]))||void 0===r?void 0:r.data)||void 0}},e))(e,t,r))))&&void 0!==n?n:e},Pa=(e,t,r="userId",n="user")=>{const s=e,i=t,o=s[i],a=xa(s,["symbol"==typeof i?i:i+""]),l=Oa(o,r,n);return Object.assign(Object.assign({},a),{[t]:l})};function Ma(e){return e.map((e=>{var{isMentioned:t}=e,r=xa(e,["isMentioned"]);return Object.assign({hasMentioned:t},r)}))}function Fa(e){return Ma(e)}function Na(e){return Ma(e)}function Ua(e){return Ma(e)}const Ba=(e,t)=>{var r,n,s;return(null==t?void 0:t.isDeleted)?0:null!==(s=null!==(r=null==t?void 0:t.unreadCount)&&void 0!==r?r:null===(n=(e=>{var t;const r={entityId:e,userId:$e()._id};return null===(t=we(["channelMarker","get",ce("channelMarker")(r)]))||void 0===t?void 0:t.data})(e.channelId))||void 0===n?void 0:n.unreadCount)&&void 0!==s?s:0},ja=(e,t)=>{var r,n;return void 0!==(null==t?void 0:t.hasMentioned)?null==t?void 0:t.hasMentioned:null!==(n=null===(r=(e=>{var t;const r={entityId:e,userId:$e()._id};return null===(t=we(["channelMarker","get",ce("channelMarker")(r)]))||void 0===t?void 0:t.data})(e.channelId))||void 0===r?void 0:r.hasMentioned)&&void 0!==n&&n},$a=e=>{var t,r;return null!==(r=null===(t=we(["messagePreviewChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==r?r:null},qa=["analytic","normal-priority"],Ka=["analytic","high-priority"],Ga=async e=>{const t=ye();await t.http.post("/api/v1/analytics/activities",{activities:e})};class Ha{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=we(qa);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await Ga(t),Ce(qa)}catch(e){this.stop(),Ce(qa)}}async syncHighPriorityCapturedEvent(){try{const e=we(Ka);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await Ga(t),Ce(Ka)}catch(e){this.stop(),Ce(Ka)}}}class Va{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*g);return!(n.getTime()-s.getTime()<t)}markPostAsViewed(e){if(!this.isAbleToEnqueue({itemId:e,expireTime:this._expireTime}))return;const t=new Date,r={event:[]},n=we(qa);(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()}),Se(qa,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=we(Ka);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()}),Se(Ka,s),this._recentHighPriorityViewed[e.storyId]=r,"linkClicked"===t)return;Ee(["story-seen","get",e.storyId],(new Date).toISOString());const o=we(["story-last-seen",e.targetId]);(null==o?void 0:o.data)?new Date(o.data).getTime()<new Date(e.expiresAt).getTime()&&Ee(["story-last-seen",e.targetId],e.expiresAt):Ee(["story-last-seen",e.targetId],e.expiresAt),this._bufferNewSeenStoryReferenceIds.push(e.referenceId),this._throttleStoryTimer||(this._throttleStoryTimer=setTimeout((()=>{clearTimeout(this._throttleStoryTimer),Qe("local.story.updated",{referenceIds:this._bufferNewSeenStoryReferenceIds}),this._bufferNewSeenStoryReferenceIds=[]}),300))}markStoryAsViewed(e){this.markStory(e,"view")}markStoryAsClicked(e){this.markStory(e,"linkClicked")}}class za{constructor(){this._client=ye(),this._eventCapturer=new Va,this._eventSyncer=new Ha}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(),Ce(qa)}}let Wa;var Ya=()=>(Wa||(Wa=new za),Wa);const Qa=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=we(["file","get",`${e.avatarFileId}`]);return(null==n?void 0:n.data)&&(r=null==n?void 0:n.data),r}}),Xa=e=>{const t=we(["story-expire",e.targetId]),r=we(["story-last-seen",e.targetId]),n=(new Date).getTime(),s=e.lastStoryExpiresAt?new Date(e.lastStoryExpiresAt).getTime():0,i=e.lastStorySeenExpiresAt?new Date(e.lastStorySeenExpiresAt).getTime():0,o=(null==t?void 0:t.data)?new Date(null==t?void 0:t.data).getTime():0,a=(null==r?void 0:r.data)?new Date(null==r?void 0:r.data).getTime():0,l=Math.max(i,a),c=we(["story-sync-state",e.targetId]);return(null==c?void 0:c.data)&&["syncing","error"].includes(c.data)?o>n&&o>l:s>n&&s>l},Ja=e=>{const{targetType:t,targetId:r,lastStoryExpiresAt:n,lastStorySeenExpiresAt:s,targetUpdatedAt:i}=e;return{targetType:t,targetId:r,updatedAt:i,hasUnseen:Xa({targetId:r,lastStoryExpiresAt:n,lastStorySeenExpiresAt:s})}},Za=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=we(["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=we(["user","get",e.userId]);if(null==t?void 0:t.data)return Qa(t.data)},get childrenComment(){return e.children.map((e=>{const t=we(["comment","get",e]);if(null==t?void 0:t.data)return null==t?void 0:t.data})).filter((e=>e)).map((e=>Za(e)))}}),el={comment:Za,post:e=>Object.assign(Object.assign({},e),{analytics:{markAsViewed:()=>{Ya().markPostAsViewed(e.postId)}},get latestComments(){return e.comments&&e.comments.map((e=>{var t;const r=null===(t=we(["comment","get",e]))||void 0===t?void 0:t.data;return r?Za(r):null})).filter(Boolean)||[]},get creator(){const t=we(["user","get",e.postedUserId]);if(null==t?void 0:t.data)return Qa(t.data)}}),user:Qa,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=we(["file","get",`${e.avatarFileId}`]);return(null==n?void 0:n.data)&&(r=null==n?void 0:n.data),r}}),story:e=>{const t=Ya(),r=we(["storyTarget","get",e.targetId]),n=we(["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=we(["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=we(["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=we(["category","get",e]);return(null==t?void 0:t.data)||void 0})).filter((e=>void 0!==e)):void 0},get creator(){const t=we(["user","get",e.creatorPublicId]);if(null==t?void 0:t.data)return Qa(t.data)},get storyTarget(){if(null==r?void 0:r.data)return Ja(r.data)},get isSeen(){const t=we(["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:Ja},tl=e=>{var t;const r=e.messagePreviewId?$a(e.channelId):null,n=null===(t=we(["user","get",null==r?void 0:r.creatorId]))||void 0===t?void 0:t.data,s=r?Object.assign(Object.assign({},r),{user:n?el.user(n):void 0}):null;return Object.assign(Object.assign({},e),{messagePreview:s})},rl=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:o,dataType:a,isDeleted:l,segment:c,creatorPublicId:u,createdAt:d,updatedAt:h}=t;return{channelId:s,subChannelId:i,data:o,dataType:a,isDeleted:l,segment:c,creatorId:u,createdAt:d,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:[]};La(n)},nl=e=>{var t,r;return null!==(r=null===(t=we(["messagePreviewSubChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==r?r:null},sl=e=>{var t;const r=e.messagePreviewId?nl(e.subChannelId):null,n=r?Object.assign(Object.assign({},r),{user:null===(t=we(["user","get",null==r?void 0:r.creatorId]))||void 0===t?void 0:t.data}):null;return Object.assign(Object.assign({},e),{messagePreview:n})},il=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:o,creatorPublicId:a,data:l,dataType:c,isDeleted:u,segment:d,createdAt:h,updatedAt:f}=t;return{messagePreviewId:o,channelId:s,subChannelId:i,data:l,dataType:c,isDeleted:u,segment:d,creatorId:a,createdAt:h,updatedAt:f,subChannelName:null==n?void 0:n.name,subChannelUpdatedAt:null==n?void 0:n.updatedAt}})(t))))&&void 0!==r?r:[]};La(n)};function ol(e){const t=Object.create(Object.getPrototypeOf(e)),r=Object.getOwnPropertyDescriptors(e);return Object.defineProperties(t,r),t}function al(e,t,r){Ee(["subChannel","get",e],Object.assign(ol(t),r))}const ll=async e=>{var t,r,n,s;const{channelId:i,messageId:o,creatorId:a,createdAt:l,updatedAt:c,data:u,dataType:d,subChannelId:h,channelSegment:f,isDeleted:p}=e,g=null===(t=we(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(!g||g.segment<=e.channelSegment){const t=null===(r=we(["subChannel","get",h]))||void 0===r?void 0:r.data;Ee(["messagePreviewSubChannel","get",e.subChannelId],{channelId:i,creatorId:a,messagePreviewId:o,createdAt:l,updatedAt:c,subChannelId:h,data:u,dataType:d,segment:f,isDeleted:p,subChannelUpdatedAt:null==t?void 0:t.updatedAt,subChannelName:null==t?void 0:t.displayName}),al(e.subChannelId,t,{messagePreviewId:o})}const m=null===(n=we(["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=we(["subChannel","get",h]))||void 0===s?void 0:s.data;Ee(["messagePreviewChannel","get",e.channelId],{channelId:i,creatorId:a,messagePreviewId:o,createdAt:l,updatedAt:c,subChannelId:h,data:u,dataType:d,segment:f,isDeleted:p,subChannelUpdatedAt:null==t?void 0:t.updatedAt,subChannelName:null==t?void 0:t.displayName})}},cl=async e=>{var t,r,n,s;const{channelId:i,messageId:o,creatorId:a,createdAt:l,updatedAt:c,data:u,dataType:d,subChannelId:h,channelSegment:f,isDeleted:p}=e,g=null===(t=we(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(g&&g.messagePreviewId===e.messageId){const t=null===(r=we(["subChannel","get",h]))||void 0===r?void 0:r.data;al(e.subChannelId,t,{messagePreviewId:o}),Ee(["messagePreviewSubChannel","get",e.subChannelId],{channelId:i,creatorId:a,messagePreviewId:o,createdAt:l,updatedAt:c,subChannelId:h,data:u,dataType:d,segment:f,isDeleted:p,subChannelUpdatedAt:null==e?void 0:e.updatedAt,subChannelName:null==t?void 0:t.displayName})}const m=null===(n=we(["messagePreviewChannel","get",e.channelId]))||void 0===n?void 0:n.data;if(m&&m.messagePreviewId===e.messageId){const t=null===(s=we(["subChannel","get",h]))||void 0===s?void 0:s.data;Ee(["messagePreviewChannel","get",e.channelId],{channelId:i,creatorId:a,messagePreviewId:o,createdAt:l,updatedAt:c,subChannelId:h,data:u,dataType:d,segment:f,isDeleted:p,subChannelUpdatedAt:null==t?void 0:t.updatedAt,subChannelName:null==t?void 0:t.displayName})}},ul=async e=>{var t,r,n,s;const{channelId:i,subChannelId:o}=e,a=null===(t=we(["messagePreviewChannel","get",i]))||void 0===t?void 0:t.data;if((null==a?void 0:a.subChannelId)===o){const e=null===(r=we(["subChannel","get",o]))||void 0===r?void 0:r.data;Ee(["messagePreviewChannel","get",i],Object.assign(Object.assign({},a),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}const l=null===(n=we(["messagePreviewSubChannel","get",o]))||void 0===n?void 0:n.data;if(l&&new Date(l.updatedAt).valueOf()>new Date(e.updatedAt).valueOf()){const e=null===(s=we(["subChannel","get",o]))||void 0===s?void 0:s.data;Ee(["messagePreviewSubChannel","get",o],Object.assign(Object.assign({},l),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}},dl=["broadcast","conversation","community"],hl=({type:e})=>dl.includes(e);function fl(e,t={isMessagePreviewUpdated:!0}){var r;let{messagePreviewId:n}=e;const s=null===(r=we(["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 Ba(e)},get hasMentioned(){return ja(e)}},e),{defaultSubChannelId:e._id,isUnreadCountSupport:hl(e),messagePreviewId:n})}const pl=(e,t={isMessagePreviewUpdated:!0})=>{La({channels:e.channels.map((e=>fl(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated})))})},gl=async(e,t={isMessagePreviewUpdated:!0})=>{const r=ye(),n=await r.getMessagePreviewSetting(!1);t.isMessagePreviewUpdated&&"no-message-preview"!==n&&e.messagePreviews&&e.messagePreviews.length>0&&rl(e);const s=e.channels.filter(hl).map((({channelId:e})=>e));if(s.length>0){pl(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated});try{await(async e=>{const t=ye();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=Fa(s),o=Na(n),a=t.cache&&Date.now();return t.cache&&La({userEntityMarkers:o,userMarkers:i},{cachedAt:a}),Qe("local.channelMarker.fetched",{userEntityMarkers:o}),Qe("local.userMarker.fetched",{userMarkers:i}),{data:o,cachedAt:a}})(s)}catch(e){}}const i=e.channels.map((e=>fl(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated}))),o=Oa(e.channelUsers),a=xa(e,["messageFeedsInfo","messagePreviews"]);return Object.assign(Object.assign({},a),{channels:i,channelUsers:o})},ml=async e=>{const t=ye();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=>{S(null==t?void 0:t.code)&&Da("channel",e)})),t}const s=await gl(n),i=t.cache&&Date.now();return t.cache&&La(s,{cachedAt:i}),{data:s.channels,cachedAt:i}};ml.locally=e=>{var t;const r=ye();if(r.log("channel/getChannelByIds.locally",e),!r.cache)return;const n=e.map((e=>we(["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 yl=async()=>{const e=ye();e.log("channel/getUserMarker");const{data:t}=await e.http.get("/api/v1/markers/userMarker"),{userMarkers:r}=t,n=Fa(r),s=e.cache&&Date.now();return e.cache&&La({userMarkers:n},{cachedAt:s}),Qe("local.userMarker.fetched",{userMarkers:n}),{data:n[0],cachedAt:s}},vl=e=>!0===e&&void 0,bl=(e,t)=>{var r;return null!==(r=null!=t?t:(e=>{var t,r;const n={creatorId:e.creatorId,feedId:null!==(t=e.messageFeedId)&&void 0!==t?t:e.subChannelId,contentId:e.messageId};return null===(r=we(["messageMarker","get",ce("messageMarker")(n)]))||void 0===r?void 0:r.data})(e))&&void 0!==r?r:{readCount:0,deliveredCount:0}};const wl=["broadcast","conversation","community"],El=({channelType:e})=>wl.includes(e);function Tl(e){var{channelId:t,channelPublicId:r,channelType:n,childCount:s,creatorId:i,creatorPublicId:o,lastMessageId:a,lastMessageTimestamp:l,messageFeedId:c,name:u}=e,d=xa(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;if(r)return r.unreadCount;const s={entityId:e,feedId:t,userId:$e()._id},i=null===(n=we(["subChannelMarker","get",ce("subChannelMarker")(s)]))||void 0===n?void 0:n.data;return i?i.unreadCount:0}(t,c)},get hasMentioned(){return function(e,t,r){var n;if(r)return r.hasMentioned;const s={entityId:e,feedId:t,userId:$e()._id},i=null===(n=we(["subChannelMarker","get",ce("subChannelMarker")(s)]))||void 0===n?void 0:n.data;return!!i&&i.hasMentioned}(t,c)}},d),{channelId:r,creatorId:o,displayName:u,lastActivity:l,latestMessageId:a,messageCount:s,subChannelId:c,isUnreadCountSupport:El({channelType:n})})}function Sl(e,t,r){var n;const{channelPublicId:s,childCount:i,creatorPublicId:o,mentionedUsers:a,messageFeedId:l,myReactions:c,reactionCount:u,reactions:d,referenceId:h,segment:f,messageId:p}=e,g=xa(e,["channelPublicId","childCount","creatorPublicId","mentionedUsers","messageFeedId","myReactions","reactionCount","reactions","referenceId","segment","messageId"]);let m;h&&(m=we(["message","get",h])),m||(m=we(["message","get",p]));const y=Object.assign(Object.assign({get readCount(){return bl(e).readCount},get deliveredCount(){return bl(e).deliveredCount}},g),{messageId:p,channelId:s,channelSegment:f,childrenNumber:i,creatorId:o,reactions:null!=d?d:{},myReactions:c||(null!==(n=null==m?void 0:m.data.myReactions)&&void 0!==n?n:[]),reactionsCount:u,subChannelId:l,uniqueId:m?m.data.uniqueId:p,referenceId:h});return a&&(y.mentionees=a.map((e=>"channel"===e.type?e:{type:"user",userIds:e.userPublicIds}))),t&&t.length&&r&&((e,t,r)=>{const n=ye(),s=we(["message","get",e.messageId]),i=(null==s?void 0:s.data.myReactions)||[];Object.assign(e,{myReactions:i});const o=t[0];o&&o.userId===n.userId&&("message.reactionAdded"!==r||i.includes(o.reactionName)||Object.assign(e,{myReactions:[...i,o.reactionName]}),"message.reactionRemoved"===r&&i.includes(o.reactionName)&&Object.assign(e,{myReactions:i.filter((e=>e!==o.reactionName))}))})(y,t,r),y}const Cl=async(e,t)=>{const r=e.messages.map((({messageId:e})=>e));if(r.length>0){La({messages:(n=e).messages.map((e=>Sl(e,n.reactions)))});try{await(async e=>{const t=ye();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,o=Fa(i),a=t.cache&&Date.now();return t.cache&&La({contentMarkers:n,feedMarkers:s,userMarkers:o},{cachedAt:a}),Qe("local.feedMarker.fetched",{feedMarkers:s}),Qe("local.messageMarker.fetched",{contentMarkers:n}),Qe("local.userMarker.fetched",{userMarkers:o}),{data:n,cachedAt:a}})(r)}catch(e){}}var n;const{messageFeeds:s}=e,i=xa(e,["messageFeeds"]);return s&&s.length>0&&(null==s||s.forEach((e=>{var t,r;const n=null!==(r=null===(t=we(["subChannel","get",e.messageFeedId]))||void 0===t?void 0:t.data)&&void 0!==r?r:{},s=xa(Tl(e),["unreadCount","hasMentioned"]);al(e.messageFeedId,n,s)}))),Object.assign(Object.assign({},i),{messages:e.messages.map((r=>Sl(r,e.reactions,t)))})};function kl(e){var{subChannelId:t,mentionees:r,dataType:n,data:s}=e,i=xa(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 Al(e){var{sortBy:t,subChannelId:r,tags:n,includingTags:s,excludingTags:i,includeDeleted:o,aroundMessageId:a,limit:l,type:c}=e,u=xa(e,["sortBy","subChannelId","tags","includingTags","excludingTags","includeDeleted","aroundMessageId","limit","type"]);const d=Object.assign(Object.assign({},u),{messageFeedId:r,isDeleted:vl(o),options:{sortBy:t,limit:l||h,around:a}});return n&&(d.includeTags=n),s&&(d.includeTags=s),c&&(d.dataType=c),i&&(d.excludeTags=i),d}const _l=["broadcast","conversation","community"],Il=({channelType:e})=>_l.includes(e),Rl=async e=>{const t=e.messageFeeds.filter(Il).map((({messageFeedId:e})=>e));if(t.length>0){(e=>{La({messageFeeds:e.messageFeeds.map((e=>Tl(e)))})})(e);try{await(async(e,t={limit:100})=>{const r=ye();r.log("channel/getSubChannelMarkers",e,t);const{data:n}=await r.http.get("/api/v1/markers/message-feeds",{params:{messageFeedIds:e,options:{token:Q(t,"skiplimit")}}}),{paging:s}=n,i=xa(n,["paging"]),{userEntityMarkers:o,userFeedMarkers:a,userMarkers:l}=i,c=Fa(l),u=Na(o),d=Ua(a),h=r.cache&&Date.now();r.cache&&La({userEntityMarkers:u,userFeedMarkers:d,userMarkers:c},{cachedAt:h}),Qe("local.channelMarker.fetched",{userEntityMarkers:u}),Qe("local.subChannelMarker.fetched",{userFeedMarkers:d}),Qe("local.userMarker.fetched",{userMarkers:c});const f=X(s.next);return{data:d,cachedAt:h,prevPage:X(s.previous),nextPage:f}})(t)}catch(e){}}il(e);const r=e.messageFeeds.map(Tl),n=e.messages.map((e=>Sl(e)));return Object.assign(Object.assign({},e),{messageFeeds:r,messages:n})};const Ll=e=>{const t=ye();return Ye(t,"client/onSessionStateChange","sessionStateChange",e)},Dl=(e,t)=>{const r=setInterval(e,t);return()=>clearInterval(r)},xl=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")),Ol=(e,t)=>{const{log:r,cache:n}=ye(),s=[e,y,t];if(!n)return;r("cache/api/isInTombstone",s);const i=we(s),{lifeSpan:o}=ie("cache_then_server",18e4);if(i&&ne(i.data,o))throw new fe("Item not found!",400400,"error")},Pl=async e=>{const t=ye();t.log("channel/getSubChannel",e),Ol("subChannel",e);try{const r=await t.http.get(`/api/v5/message-feeds/${encodeURIComponent(e)}`),n=await Rl(r.data),s=t.cache&&Date.now();return t.cache&&La(n,{cachedAt:s}),Qe("local.message-feed.fetched",n),{data:n.messageFeeds[0],cachedAt:s}}catch(t){throw S(null==t?void 0:t.code)&&Da("subChannel",e),t}};Pl.locally=e=>{const t=ye();if(t.log("channel/getSubChannel.locally",e),!t.cache)return;const r=we(["subChannel","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};let Ml=!1,Fl=[];const Nl={},Ul=async()=>{const e=Object.entries(Nl).filter((([,e])=>e)).map((([e])=>e));return 0!==e.length&&(async e=>{const t=ye();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:o}=r,a=Fa(o),l=Na(n),c=Ua(s),u=t.cache&&Date.now();return t.cache&&La({userEntityMarkers:l,userFeedMarkers:c,feedMarkers:i,userMarkers:a},{cachedAt:u}),Qe("local.feedMarker.fetched",{feedMarkers:i}),Qe("local.channelMarker.fetched",{userEntityMarkers:l}),Qe("local.subChannelMarker.fetched",{userFeedMarkers:c}),Qe("local.userMarker.fetched",{userMarkers:a}),!0})(e)},Bl=()=>{Ml=!1},jl=()=>(Ml=!0,Ll((e=>{"notLoggedIn"===e&&Bl()})),()=>{Bl()}),$l=async e=>{const t=await(async e=>{const t=Pl.locally(e);if(t)return t.data.channelId;const{data:r}=await Pl(e);return r.channelId})(e),r=st({channelId:t,subChannelId:e});Fl.push(ct(r))};Dl((async()=>{Ml&&await Ul()}),3e4);const ql=async e=>{const t=ye();t.log("channel/getSubChannels",e);const r=await t.http.get("/api/v5/message-feeds/list",{params:{messageFeedIds:e.map(encodeURIComponent)}}),n=await Rl(r.data),s=t.cache&&Date.now();return t.cache&&La(n,{cachedAt:s}),Qe("local.message-feed.fetched",n),{data:n.messageFeeds,cachedAt:s}};ql.locally=e=>{var t;const r=ye();if(r.log("channel/getSubChannels.locally",e),!r.cache)return;const n=e.map((e=>we(["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 Kl=async(e=!0)=>{var t;const r=null===(t=we(["MessagePreviewSetting"]))||void 0===t?void 0:t.data;if(!e&&r)return r;const n=await(async()=>{const e=ye(),{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"},Gl=async()=>{const e=ye(),{data:t}=await e.http.get("/api/v3/network-settings/social");return t.socialNetworkSetting},Hl=(e,t)=>{var r;const n=null===(r=we(["users","get",e]))||void 0===r?void 0:r.data;return!!n&&n.permissions.some((e=>e===t))},Vl=e=>{const{userId:t}=ye();return{currentUser:()=>Hl(t,e),community:r=>((e,t,r)=>{var n;if(!e)return!1;const s=null===(n=we(["communityUsers","get",`${r}#${e}`]))||void 0===n?void 0:n.data;return!!s&&(!!s.permissions.some((e=>e===t))||Hl(e,t))})(t,e,r),channel:r=>((e,t,r)=>{var n;if(!e)return!1;const s=null===(n=we(["channelUsers","get",`${r}#${e}`]))||void 0===n?void 0:n.data;return!!s&&(!!s.permissions.some((e=>e===t))||Hl(e,t))})(t,e,r)}},zl=async()=>{const e=ye(),{data:t}=await e.http.get("/api/v3/network-settings/feed-setting");return Object.fromEntries(t.feedSettings.map((({feedType:e,contentSettings:t})=>[e,t])))},Wl={notLoggedIn:["establishing"],terminated:["establishing"],establishing:["notLoggedIn","established"],established:["notLoggedIn","terminated","tokenExpired","establishing"],tokenExpired:["establishing"]},Yl=e=>{const t=ye();t.log("client/api/setSessionState",e);const{sessionState:r}=t;if(r===e)return!1;if(!((e,t)=>Wl[e].includes(t))(r,e))throw new he(`Session state cannot change from ${r} to ${e}`,8e5,"error");return t.sessionState=e,t.emitter.emit("sessionStateChange",e),!0},Ql=async e=>{const t=ye();Yl("establishing");const{accessToken:r,users:n,expiresAt:s,issuedAt:i,refreshToken:o}=await(async e=>{const t=ye();t.log("client/api/getToken",e);const r=Aa(),{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},Yl("established"),{accessToken:r,users:n,refreshToken:o}},Xl=e=>{const t=ye();return Ye(t,"onChannelDeleted","channel.deleted",(async t=>{const r=await gl(t);La(r),e(r.channels[0])}))},Jl=e=>{const t=ye();return Ye(t,"onChannelMemberBanned","channel.banned",(async t=>{const r=await gl(t),{channels:n,channelUsers:s}=r;La(r),e(n[0],s.find((e=>"banned"===e.membership)))}))},Zl=(e,t)=>{const r=ye();return Ye(r,e,e,(e=>{r.cache&&La(e),t(e.users[0])}))},ec=e=>Zl("user.deleted",e);const tc=async()=>{const e=ye();return e.log("client/api/disconnectClient"),e.mqtt.connected&&e.mqtt.disconnect(),e.ws.connected&&e.ws.disconnect(),"established"===e.sessionState&&Yl("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.ws.io.opts.query={token:""},"tokenExpired"!==e.sessionState&&e.cache&&(e.cache={data:{}}),!0},rc=e=>{const t=ye();Yl("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,tc()},nc=["disconnected","error","connect_error","reconnect_error","reconnect_failed"],sc=e=>{const t=ye(),r=nc.map((r=>Ye(t,`client/onConnectionError(${r})`,r,(t=>{const n=(null==t?void 0:t.code)?new he(t.message,t.code,"fatal"):new ge(r);e(n)}))));return()=>{r.forEach((e=>e()))}},ic=e=>{const t=ye();return Ye(t,"client/onConnectionError(user.didGlobalBan)","user.didGlobalBan",e)},oc=e=>{const t=ce("channelMarker")({userId:$e()._id,entityId:e.channelId});Ce(["channelMarker","get",t],!0)};let ac=[];const lc=async(e,t,r)=>{var n,s,i;const o=ye();let a;o.log("client/api/connectClient",Object.assign({apiKey:o.apiKey,sessionState:o.sessionState},e)),o.userId&&o.userId!==e.userId&&(await tc(),ac.forEach((e=>e())),ac=[]),null!==(n=e.deviceId)&&void 0!==n||(e.deviceId=await ka());try{const{users:r}=await Ql(e);l=o.ws,c=o.emitter,Ve.forEach((e=>{l.on(e,(t=>{c.emit(e,t)}))})),o.ws.once("connect",(()=>{o.ws.open()})),o.userId=e.userId,o.sessionHandler=t,a=o.accessTokenExpiryWatcher(null===(s=o.token)||void 0===s?void 0:s.expiresAt,null===(i=o.token)||void 0===i?void 0:i.issuedAt,t),qe(r[0])}catch(e){throw Yl("notLoggedIn"),e}var l,c;return!0!==(null==r?void 0:r.disableRTE)&&async function(){await Ze()}(),await(async()=>{var e;const t=await Kl();if(t===(null===(e=we(["MessagePreviewSetting"]))||void 0===e?void 0:e.data))return;Ee(["MessagePreviewSetting"],t);const r=[],n=[];if("no-message-preview"===t){const e=be(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{Ce(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=be(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{(null==t?void 0:t.isDeleted)&&(Ce(e),e.includes("MessagePreviewChannel")&&r.push(t.channelId),e.includes("MessagePreviewSubChannel")&&n.push(t.subChannelId))})),0!==r.length&&await ml(r),0!==n.length&&await ql(n)}})(),0===ac.length&&ac.push(ic((e=>{rc("globalBan"),ac.forEach((e=>e())),a()})),(e=>{const t=ye();return Ye(t,"client/onTokenTerminated","tokenTerminated",e)})((e=>{rc(),ac.forEach((e=>e())),a()})),ec((e=>{e.userId===o.userId&&(rc("userDeleted"),ac.forEach((e=>e())),a())})),(e=>{const t=ye();return Ye(t,"client/onTokenExpired","tokenExpired",e)})((e=>{Yl(e),tc(),ac.forEach((e=>e()))})),Xl(oc),Jl(oc),jl(),(()=>{const e=Ya();return e.established(),Ll((t=>{"established"===t?e.established():e.handleTokenExpired()})),()=>{e.destroy()}})()),!0},cc=()=>{let e,t=!1;const r=ye();r.log("initiating access token renewal");const n=async n=>{const{userId:s,displayName:i}=$e(),o={userId:s,displayName:i,authToken:n,deviceId:await ka()};"tokenExpired"===r.sessionState?await lc(o,r.sessionHandler):await Ql(o),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(cc())}),m)}}},uc=3e5,dc=(e,t,r)=>{const n=setInterval((()=>{if((e=>Date.now()>Date.parse(e)-uc)(e))return Qe("tokenExpired","tokenExpired"),void He((()=>r.sessionWillRenewAccessToken(cc())));(e=>{const{expiresAt:t,issuedAt:r}=e,n=Date.parse(t),s=Date.parse(r),i=Date.now();return i>s+.8*(n-s-uc)&&i<n})({expiresAt:e,issuedAt:t})&&r.sessionWillRenewAccessToken(cc())}),m);return()=>clearInterval(n)},hc=async e=>{const t=ye();t.log("channel/markerSync");const{data:r}=await t.http.post("/api/v1/markers/sync",{deviceLastSyncAt:e}),{userEntityMarkers:n,userFeedMarkers:s,feedMarkers:i,userMarkers:o}=r,a=Fa(o),l=Na(n),c=Ua(s),u=t.cache&&Date.now();return t.cache&&La({userEntityMarkers:l,userFeedMarkers:c,feedMarkers:i,userMarkers:a},{cachedAt:u}),Qe("local.feedMarker.fetched",{feedMarkers:i}),Qe("local.channelMarker.fetched",{userEntityMarkers:l}),Qe("local.subChannelMarker.fetched",{userFeedMarkers:c}),Qe("local.userMarker.fetched",{userMarkers:a}),{data:r,hasMore:r.feedMarkers.length>0}},fc=e=>{const t=ye();return Ye(t,"channelMarker/onChannelMarkerFetched","local.channelMarker.fetched",(t=>{e(t.userEntityMarkers[0])}))},pc=e=>{const t=ye();return Ye(t,"subChannelMarker/onSubChannelMarkerFetched","local.subChannelMarker.fetched",(t=>{e(t.userFeedMarkers[0])}))},gc=e=>{const t=ye();return Ye(t,"subChannelMarker/onSubChannelMarkerUpdated","local.subChannelMarker.updated",(t=>{e(t.userFeedMarkers)}))},mc=e=>{const t=ye();return Ye(t,"feedMarker/onFeedMarkerUpdated","marker.feed-updated",(t=>{La(t),e(t.feedMarkers[0])}))},yc=e=>{const t=ye();return Ye(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers[0])}))},vc=e=>{const t=ye();return Ye(t,"messageMarker/onMessageMarkerFetched","local.messageMarker.fetched",(t=>{e(t.contentMarkers[0])}))},bc=e=>{const t=ye();return Ye(t,"messageMarker/onMessageMarked","marker.marked-message",(t=>{var r,n;La(t);const s=be(["message","collection"]),{contentMarkers:i,feedMarkers:o}=t;if(s&&(null==s?void 0:s.length)>0&&(null==o?void 0:o.length)>0){const e=s.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==i?void 0:i.length)>0){((null===(n=null===(r=e[0].data)||void 0===r?void 0:r.data)||void 0===n?void 0:n.map((e=>we(["message","get",e]))))||[]).forEach((e=>{var t;const r=i[0].feedId===(null==e?void 0:e.data.subChannelId),n=i[0].readCount>(null==e?void 0:e.data.readCount),s=(null===(t=i[0])||void 0===t?void 0:t.deliveredCount)>(null==e?void 0:e.data.deliveredCount);r&&Ee(["message","get",e.data.messageId],Object.assign(Object.assign({},e.data),{readCount:n?i[0].readCount:null==e?void 0:e.data.readCount,deliveredCount:s?i[0].deliveredCount:null==e?void 0:e.data.deliveredCount}))}))}}e(t.contentMarkers[0])}))};const wc=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 Ec(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(!Ec(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=>Ec(e[r],t[r])))}const Tc=(e,t,r,n,s,i)=>{const{forceDispatch:o,callbackDataSelector:a,callbackFilter:l}=Object.assign({forceDispatch:!1,callbackDataSelector:e=>e},i),{cache:c}=ye();let u;c||console.log("For using Live Object feature you need to enable Cache!");let d=!1;const h=[],f=e=>{const{data:r}=e,n=xa(e,["data"]);l&&!l(r,u)||t(Object.assign({data:a(r)},n)),u=wc(r)};return h.push(...s.map((t=>t((t=>((t,n=!1)=>{e===t[r]&&(u&&!n&&Ec(u,t)||f({loading:!1,data:t,origin:"event"}))})(t,o)))))),(()=>{const t=se(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 fe("Observing unsynced object is not supported by Live Object.",800800,"error")}),d=!0,h.forEach((e=>e()))):d||f({loading:r,data:t,origin:n,error:e}),e&&h.forEach((e=>e()))}))})(),()=>{h.forEach((e=>e()))}},Sc=e=>{const t=ye();return Ye(t,"onChannelCreated","channel.created",(async t=>{const r=await gl(t);La(r),e(r.channels[0])}))},Cc=e=>{const t=ye(),r=[Ye(t,"onChannelUpdated","channel.updated",(async t=>{const r=await gl(t);La(r),e(r.channels[0])})),Ye(t,"onChannelUpdated","local.channel.updated",(t=>e(t.channels[0])))];return()=>{r.forEach((e=>e()))}},kc=e=>{const t=ye();return Ye(t,"onChannelJoined","channel.joined",(async t=>{const r=await gl(t),{channels:n,channelUsers:s}=r;La(r),e(n[0],s[0])}))},Ac=e=>{const t=ye();return Ye(t,"onChannelLeft","channel.left",(async t=>{const{userId:r}=ye(),{channelUsers:n}=t,s=n.some((e=>e.userId===r)),i=await gl(t,{isMessagePreviewUpdated:s}),{channels:o,channelUsers:a}=i;La(i),e(o[0],a[0])}))},_c=e=>{const t=ye();return Ye(t,"onChannelMuted","channel.setMuted",(async t=>{const r=await gl(t);La(r),e(r.channels[0])}))},Ic=e=>{const t=ye();return Ye(t,"onChannelMemberAdded","channel.membersAdded",(async t=>{const r=await gl(t),{channels:n,channelUsers:s}=r;La(r),e(n[0],s.find((e=>"member"===e.membership)))}))},Rc=e=>{const t=ye();return Ye(t,"onChannelMemberRemoved","channel.membersRemoved",(async t=>{const r=await gl(t),{channels:n,channelUsers:s}=r;La(r),e(n[0],s[0])}))},Lc=e=>{const t=ye();return Ye(t,"onChannelMemberUnbanned","channel.unbanned",(async t=>{const r=await gl(t),{channels:n,channelUsers:s}=r;La(r),e(n[0],s.find((e=>"none"===e.membership)))}))},Dc=e=>{const t=ye();return Ye(t,"onChannelMemberRoleAdded","local.channel-moderator.role-added",(async t=>{const{channels:r,channelUsers:n}=t;e(r[0],n.find((e=>"member"===e.membership)))}))},xc=e=>{const t=ye();return Ye(t,"onChannelMemberRoleRemoved","local.channel-moderator.role-removed",(async t=>{const{channels:r,channelUsers:n}=t;e(r[0],n.find((e=>"member"===e.membership)))}))},Oc=(e,t=!0)=>{const r=ye(),n=[Ye(r,"message/onMessageCreated","message.created",(async t=>{const r=await Cl(t),n=r.messages[0];La(r),e(n)}))];return t&&Ye(r,"message/onMessageCreated","local.message.created",(t=>e(t.messages[0]))),()=>{n.forEach((e=>e()))}},Pc=e=>{const t=ye(),r=[Ye(t,"onMessageUpdated","message.updated",(async t=>{const r=await Cl(t);La(r),e(r.messages[0])})),Ye(t,"onMessageUpdated","local.message.updated",(t=>e(t.messages[0])))];return()=>{r.forEach((e=>e()))}},Mc=e=>{const t=ye(),r=[Ye(t,"message/onMessageDeleted","message.deleted",(async t=>{const r=await Cl(t);La(r),e(r.messages[0])})),Ye(t,"message/onMessageDeleted","local.message.deleted",(t=>e(t.messages[0])))];return()=>{r.forEach((e=>e()))}},Fc=e=>{const t=ye();return Ye(t,"onMessageFlagged","message.flagged",(async t=>{const r=await Cl(t);La(r),e(r.messages[0])}))},Nc=e=>{const t=ye();return Ye(t,"onMessageUnflagged","message.unflagged",(async t=>{const r=await Cl(t);La(r),e(r.messages[0])}))},Uc=e=>{const t=ye();return Ye(t,"onMessageFlagCleared","message.flagCleared",(async t=>{const r=await Cl(t);La(r),e(r.messages[0])}))},Bc=e=>{const t=ye();return Ye(t,"onMessageReactionAdded","message.reactionAdded",(async t=>{const r=await Cl(t,"message.reactionAdded");La(r),e(r.messages[0])}))},jc=e=>{const t=ye();return Ye(t,"onMessageReactionRemoved","message.reactionRemoved",(async t=>{const r=await Cl(t,"message.reactionRemoved");La(r),e(r.messages[0])}))},$c=e=>{const t=ye();return Ye(t,"message/onMessageFetched","local.message.fetched",(t=>{La(t),e(t.messages[0])}))},qc=e=>{const t=ye();return Ye(t,"onSubChannelCreated","message-feed.created",(async t=>{const r=await Rl(t);La(r),e(r.messageFeeds[0])}))},Kc=e=>{const t=ye(),r=[Ye(t,"onSubChannelUpdated","message-feed.updated",(async t=>{const r=await Rl(t);La(r),e(r.messageFeeds[0])})),Ye(t,"onSubChannelUpdated","local.message-feed.updated",(t=>e(t.messageFeeds[0])))];return()=>{r.forEach((e=>e()))}},Gc=e=>{const t=ye(),r=[Ye(t,"onSubChannelDeleted","message-feed.deleted",(async t=>{const r=await Rl(t);La(r),e(r.messageFeeds[0])})),Ye(t,"local.message-feed.deleted","local.message-feed.deleted",(t=>e(t.messageFeeds[0])))];return()=>{r.forEach((e=>e()))}};let Hc=!1,Vc=[],zc=!1,Wc=null;const Yc=e=>{(!Wc||new Date(e).getTime()>new Date(Wc).getTime())&&(Wc=e)};let Qc=[];const Xc=e=>{Qc=e},Jc=e=>Qc.push(e),Zc=async()=>{if(zc)return;if(0===Qc.length)return;zc=!0,Qc=[];const e=await hc(null==Wc?(new Date).toISOString():Wc);Yc(e.data.userMarkers[0].lastSyncAt),e.hasMore&&Qc.push("has_more"),zc=!1},eu=()=>{Vc.length>0||Vc.push(xl((()=>{Qc.push("resume")})),Oc((e=>{Il(e)&&Qc.push("new message")}),!1),Sc((()=>Qc.push("subchannel is created"))),Xl((()=>Qc.push("subchannel is deleted"))),kc((()=>Qc.push("subchannel is joined"))),Ac((()=>Qc.push("subchannel is left"))),qc((()=>Qc.push("subchannel is created"))),Gc((()=>setTimeout((()=>Qc.push("subchannel is deleted")),2e3))),mc((()=>Qc.push("feed marker updated"))),(e=>{const t=ye();return Ye(t,"UserMarker/onUserMarkerSync","marker.user-sync",(t=>{const{userMarkers:r,userEntityMarkers:n,userFeedMarkers:s}=t,i=xa(t,["userMarkers","userEntityMarkers","userFeedMarkers"]),o=Fa(r),a=Na(n),l=Ua(s);La(Object.assign({userMarkers:o,userEntityMarkers:a,userFeedMarker:l},i)),e(o[0])}))})((()=>Qc.push("feed marker updated"))))},tu=()=>{Hc=!1,Xc([]),Vc.forEach((e=>e())),Vc=[]};Dl((async()=>{Hc&&await Zc()}),2e3);var ru=Object.freeze({__proto__:null,getActiveClient:ye,getActiveUser:$e,setActiveUser:qe,createClient:(e,t=St.SG,{debugSession:r="amity",apiEndpoint:n}={})=>{var s,i;const o=(e=>{const t=`${null==e?void 0:e.trim()}`.length>0&&!Tt,r=bt(e),n=(e,...n)=>{t&&r(e,n)};return n.__instance__=r,n})(r);o("client/api/createClient",{apiKey:e.replace(/.{5}$/g,"xxxxx"),apiRegion:t});const a=null!==(s=null==n?void 0:n.http)&&void 0!==s?s:kt("http",t),l=null!==(i=null==n?void 0:n.mqtt)&&void 0!==i?i:kt("mqtt",t),c=cn(a),u=(e=>{const t=Co(e,{autoConnect:!1,reconnectionDelay:2e3,transports:["websocket"]});return t.on("disconnect",(e=>{"io server disconnect"===e&&t.connect()})),t})(a),h=Ra(l),f=We(),p={version:`${d}`,apiKey:e,log:o,cache:{data:{}},http:c,ws:u,mqtt:h,emitter:f,sessionState:"notLoggedIn",accessTokenExpiryWatcher:dc,sessionHandler:undefined,hasPermission:Vl,getFeedSettings:zl,getSocialSettings:Gl,getMessagePreviewSetting:Kl,use:()=>ve(p)};try{const t=ye();if(t.apiKey===e)return t;ve(p)}catch(e){ve(p)}return p},login:lc,logout:tc,isConnected:()=>{var e,t;const r=ye();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:zl,renewal:cc,markerSync:hc,onConnectionError:sc,onClientDisconnected:e=>sc((({code:t})=>{800211===t&&e()})),onClientBanned:ic,onSessionStateChange:Ll,getTotalUnreadCount:e=>{const{_id:t}=$e();if(!t)throw new he("The _id has not been defined in ActiveUser",8e5,"error");return Tc(t,e,"userId",yl,[yc],{callbackDataSelector:e=>{var t;return null!==(t=null==e?void 0:e.unreadCount)&&void 0!==t?t:0}})},getUserUnread:e=>{const{_id:t}=$e();if(!t)throw new he("The _id has not been defined in ActiveUser",8e5,"error");return Tc(t,e,"userId",yl,[yc],{callbackDataSelector:e=>{var t;return{unreadCount:null!==(t=null==e?void 0:e.unreadCount)&&void 0!==t?t:0,hasMentioned:!!(null==e?void 0:e.hasMentioned)}}})},getMarkerSyncEvents:()=>Qc,setMarkerSyncEvents:Xc,pushMarkerSyncEvent:Jc,markerSyncTrigger:Zc,startUnreadSync:async()=>{await(async()=>{const{data:e}=await yl();Yc(e.lastSyncAt)})(),Jc("start syncing"),Hc=!0,eu()},stopUnreadSync:tu,stopUnreadSyncing:()=>(console.warn("`stopUnreadSyncing` has been deprecated, please use `stopUnreadSync` instead"),tu())});const nu=async e=>{const t=ye();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=xa(n,["paging"]),{users:o}=i,a=t.cache&&Date.now();if(t.cache){La(i,{cachedAt:a});Ee(["blockedUsers","query",r],{users:o.map(ce("user")),paging:s})}const{next:l,previous:c,total:u}=s,d=J(l);return{data:o,prevPage:J(c),nextPage:d,total:u,cachedAt:a}};nu.locally=(e={})=>{var t,r,n;const s=ye();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 o=["blockedUsers","query",i],{data:a,cachedAt:l}=null!==(t=we(o))&&void 0!==t?t:{},c=null!==(r=null==a?void 0:a.users.map((e=>we(["user","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[],u=J(null==a?void 0:a.paging.next),d=J(null==a?void 0:a.paging.previous);return c.length>0&&c.length===(null===(n=null==a?void 0:a.users)||void 0===n?void 0:n.length)?{data:c,nextPage:u,prevPage:d,total:null==a?void 0:a.paging.total,cachedAt:l}:void 0};const su=(e,t,r)=>{const{log:n,cache:s}=ye();s||console.log(p);const i=Date.now();n(`getBlockedUsers(tmpid: ${i}) > listen`);const{limit:o}=e,a=null!=o?o:h,{policy:l=f}=null!=r?r:{},c=[],u=["blockedUsers","collection",{}],d=(e=!1)=>{var r,n;const s=null===(r=we(u))||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 o=se(nu,{limit:a,token:Q(e||null==s?void 0:s.params.page,"afterbeforeraw")});oe(o,(({data:e,loading:r,error:n,nextPage:s,total:o})=>{const a={loading:r,error:n,params:{page:s,total:o},data:i};e&&(a.data=[...new Set([...i,...e.map(ce("user"))])]),Ee(u,a),(e=>{var r,n;const s=null!==(r=e.data.map((e=>we(["user","get",e]))).filter(Boolean).map((({data:e})=>el.user(e))))&&void 0!==r?r:[];t({onNextPage:d,data:s,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading,error:e.error})})(a)}),ie(l,v))};return c.push((()=>{})),d(!0),()=>{n(`getCategories(tmpid: ${i}) > dispose`),c.forEach((e=>e())),Ce(u)}},iu=(e,t)=>{const r=ye();return Ye(r,e,e,(e=>{var n,s;if(r.cache){La(e);[...null!==(n=be(["followers","query"]))&&void 0!==n?n:[],...null!==(s=be(["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})=>Se(e,t,{cachedAt:-1}))),t(e.follows[0])}else t(e.follows[0])}))},ou=e=>iu("follow.created",e),au=e=>iu("follow.unfollowed",e),lu=e=>iu("follow.followerDeleted",e),cu=e=>iu("follow.requested",e),uu=e=>iu("follow.requestCanceled",e),du=e=>iu("follow.accepted",e),hu=e=>iu("follow.requestDeclined",e),fu=async e=>{var t,r;const n=ye();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(),o="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&&Ee(["followInfo","get",e],o,{cachedAt:i}),{data:o,cachedAt:i}};fu.locally=e=>{const t=ye();if(t.log("follow/getFollowInfo.locally",e),!t.cache)return;const r=we(["followInfo","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const pu=e=>{const t=async t=>{const[{data:r},{data:n}]=await Promise.all([fu(t.from),fu(t.to)]);e(r),e(n)},r=[iu("follow.created",t),iu("follow.requested",t),iu("follow.accepted",t),iu("follow.unfollowed",t),iu("follow.requestCanceled",t),iu("follow.requestDeclined",t),iu("follow.followerDeleted",t)];return()=>{r.forEach((e=>e()))}},gu=async(e,t)=>{const r=ye();r.log(`follow/queryF${e.substring(1)}`,t);const{userId:n,page:s}=t,i=xa(t,["userId","page"]),{data:o}=await r.http.get(r.userId===n?`/api/v4/me/${e}`:`/api/v4/users/${n}/${e}`,{params:Object.assign(Object.assign({},i),{token:Q(s,"afterbeforeraw")})}),{paging:a}=o,l=xa(o,["paging"]),{follows:c}=l,u=r.cache&&Date.now();if(r.cache){La(l,{cachedAt:u});const t=["follow","query",Object.assign(Object.assign({},i),{userId:n,options:Object.assign({},s),type:e})];Ee(t,{follows:c.map(ce("follow")),paging:a})}const d=J(a.next);return{data:c,cachedAt:u,prevPage:J(a.previous),nextPage:d}};gu.locally=(e,t)=>{var r,n;const s=ye();if(s.log(`follow/queryF${e.substring(1)}.locally`,t),!s.cache)return;const{page:i}=t,o=xa(t,["page"]),a=["follow","query",Object.assign(Object.assign({},o),{options:Object.assign({},i),type:e})],{data:l,cachedAt:c}=null!==(r=we(a))&&void 0!==r?r:{};if(!(null==l?void 0:l.follows.length))return;const u=l.follows.map((e=>we(["follow","get",e]))).filter(Boolean).map((({data:e})=>e)),d=J(null==l?void 0:l.paging.previous),h=J(null==l?void 0:l.paging.next);return u.length===(null===(n=null==l?void 0:l.follows)||void 0===n?void 0:n.length)?{data:u,cachedAt:c,prevPage:d,nextPage:h}:void 0};const mu=async e=>gu("followers",e);mu.locally=e=>gu.locally("followers",e);const yu=async e=>gu("following",e);yu.locally=e=>gu.locally("following",e);var vu=Object.freeze({__proto__:null,blockUser:async e=>{const t=ye();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,o={follows:s};return t.cache&&(La(o,{cachedAt:n}),Se(["followInfo","get",e],i[0],{cachedAt:n})),Qe("follow.unfollowed",o),r},unBlockUser:async e=>{const t=ye();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,o={follows:s};return t.cache&&(La(o,{cachedAt:n}),Se(["followInfo","get",e],i[0],{cachedAt:n})),Qe("follow.created",o),r},getBlockedUsers:(e,t,r)=>(console.log("Deprecation Notice: UserRepository.Relationship.getBlockedUsers will be deprecated on 9th June 2023, please use UserRepository.getBlockedUsers instead."),su(e,t,r)),follow:async e=>{const t=ye();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&&La(r,{cachedAt:n}),Qe("accepted"===r.follows[0].status?"follow.created":"follow.requested",r),{data:r.follows[0],cachedAt:n}},unfollow:async e=>{const t=ye();t.log("follow/unfollow",e);const{data:r}=await t.http.delete(`/api/v4/me/following/${e}`);return t.cache&&La(r),Qe("follow.unfollowed",r),!0},acceptFollower:async e=>{const t=ye();t.log("follow/acceptFollower",e);const{data:r}=await t.http.post(`/api/v4/me/followers/${e}`);return t.cache&&La(r),Qe("follow.accepted",r),!0},acceptMyFollower:async e=>{const t=ye();t.log("follow/acceptMyFollower",e);const{data:r}=await t.http.post(`/api/v4/me/followers/${e}`);return t.cache&&La(r),Qe("follow.accepted",r),!0},declineFollower:async e=>{const t=ye();t.log("follow/declineFollower",e);const{data:r}=await t.http.delete(`/api/v4/me/followers/${e}`);return t.cache&&La(r),Qe("follow.requestDeclined",r),!0},declineMyFollower:async e=>{const t=ye();t.log("follow/declineMyFollower",e);const{data:r}=await t.http.delete(`/api/v4/me/followers/${e}`);return t.cache&&La(r),Qe("follow.requestDeclined",r),!0},onUserFollowed:ou,onUserUnfollowed:au,onFollowerDeleted:lu,onFollowerRequested:cu,onFollowRequestCanceled:uu,onFollowRequestAccepted:du,onFollowRequestDeclined:hu,onFollowInfoUpdated:pu,observeFollowInfo:(e,t,r="cache_then_server")=>{const{log:n}=ye(),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)},o=[];return o.push(pu((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(se(fu,e),(e=>(e.data||e.error)&&i(e,"onFetch")),ie(r)),()=>{n(`observeFollowInfo(tmpid: ${s}) > dispose`),o.forEach((e=>e()))}},observeFollowers:(e,t)=>{const{log:r}=ye(),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(cu((e=>i(e,"onRequested"))),du((e=>i(e,"onAccepted"))),hu((e=>i(e,"onDeclined"))),uu((e=>i(e,"onCanceled"))),ou((e=>i(e,"onFollowed"))),au((e=>i(e,"onUnfollowed"))),lu((e=>i(e,"onDeleted")))),()=>{r(`observeFollowers(tmpid: ${n}) > dispose`),s.forEach((e=>e()))}},observeFollowings:(e,t)=>{const{log:r}=ye(),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(cu((e=>i(e,"onRequested"))),du((e=>i(e,"onAccepted"))),hu((e=>i(e,"onDeclined"))),uu((e=>i(e,"onCanceled"))),ou((e=>i(e,"onFollowed"))),au((e=>i(e,"onUnfollowed"))),lu((e=>i(e,"onDeleted")))),()=>{r(`observeFollowings(tmpid: ${n}) > dispose`),s.forEach((e=>e()))}},getFollowers:(e,t,r)=>{const{log:n,cache:s}=ye();s||console.log("For using Live Collection feature you need to enable Cache!");const i=Date.now();n(`getFollowers(tmpid: ${i}) > listen`);const{limit:o}=e,a=xa(e,["limit"]),l=null!=o?o:h,{policy:c=f}=null!=r?r:{},u=[],d=["follow","collection",{userId:e.userId,type:"follower"}],p=r=>{var n,s;let i=null!==(n=r.data.map((e=>we(["follow","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];e.status&&"all"!==e.status&&(i=ke(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=we(d))||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!==ce("follow")(r))):["onRequested","onAccepted","onFollowed"].includes(t)&&(s.data=[...new Set([ce("follow")(r),...s.data])]),Ee(d,s),p(s))},m=(e=!1)=>{var t,r,n,s;const i=null===(t=we(d))||void 0===t?void 0:t.data,o=null!==(r=null==i?void 0:i.data)&&void 0!==r?r:[];if(!e&&o.length>0&&!(null===(n=null==i?void 0:i.params)||void 0===n?void 0:n.page))return;const u=se(mu,Object.assign(Object.assign({},a),{page:null!==(s=e||null==i?void 0:i.params.page)&&void 0!==s?s:{limit:l}}));oe(u,(({data:e,error:t,loading:r,nextPage:n})=>{const s={loading:r,error:t,params:{page:n},data:o};e&&(s.data=[...new Set([...o,...e.map(ce("follow"))])]),Ee(d,s),p(s)}),ie(c))};return u.push(cu(g("onRequested")),du(g("onAccepted")),hu(g("onDeclined")),uu(g("onCanceled")),ou(g("onFollowed")),au(g("onUnfollowed")),lu(g("onDeleted"))),m(!0),()=>{n(`getFollowers(tmpid: ${i}) > dispose`),u.forEach((e=>e()))}},getFollowings:(e,t,r)=>{const{log:n,cache:s}=ye();s||console.log("For using Live Collection feature you need to enable Cache!");const i=Date.now();n(`getFollowings(tmpid: ${i}) > listen`);const{limit:o}=e,a=xa(e,["limit"]),l=null!=o?o:h,{policy:c=f}=null!=r?r:{},u=[],d=["follow","collection",{userId:e.userId,type:"following"}],p=r=>{var n,s;let i=null!==(n=r.data.map((e=>we(["follow","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];e.status&&"all"!==e.status&&(i=ke(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=we(d))||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!==ce("follow")(r))):["onRequested","onAccepted","onFollowed"].includes(t)&&(s.data=[...new Set([ce("follow")(r),...s.data])]),Ee(d,s),p(s))},m=(e=!1)=>{var t,r,n,s;const i=null===(t=we(d))||void 0===t?void 0:t.data,o=null!==(r=null==i?void 0:i.data)&&void 0!==r?r:[];if(!e&&o.length>0&&!(null===(n=null==i?void 0:i.params)||void 0===n?void 0:n.page))return;const u=se(yu,Object.assign(Object.assign({},a),{page:null!==(s=e||null==i?void 0:i.params.page)&&void 0!==s?s:{limit:l}}));oe(u,(({data:e,error:t,loading:r,nextPage:n})=>{const s={loading:r,error:t,params:{page:n},data:o};e&&(s.data=[...new Set([...o,...e.map(ce("follow"))])]),Ee(d,s),p(s)}),ie(c))};return u.push(cu(g("onRequested")),du(g("onAccepted")),hu(g("onDeclined")),uu(g("onCanceled")),ou(g("onFollowed")),au(g("onUnfollowed")),lu(g("onDeleted"))),m(!0),()=>{n(`getFollowings(tmpid: ${i}) > dispose`),u.forEach((e=>e()))}},getFollowInfo:(e,t)=>Tc(e,t,"userId",fu,[pu],{forceDispatch:!0}),getMyFollowInfo:e=>{const{userId:t}=$e();return Tc(t,e,"userId",fu,[pu],{forceDispatch:!0})}});const bu=async e=>{const t=ye();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&&La(n,{cachedAt:s}),Qe("user.fetched",n),{data:n.users.map((e=>el.user(e))),cachedAt:s}};bu.locally=e=>{var t;const r=ye();if(r.log("user/getUsers.locally",e),!r.cache)return;const n=e.map((e=>we(["user","get",e]))).filter(Boolean),s=n.map((({data:e})=>el.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 wu=e=>Zl("user.updated",e),Eu=e=>Zl("user.flagged",e),Tu=e=>Zl("user.unflagged",e),Su=e=>Zl("user.flagCleared",e),Cu=e=>Zl("user.fetched",e),ku=async e=>{const t=ye();let r;t.log("user/getUser",e),Ol("user",e);try{r=(await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`)).data}catch(t){throw S(null==t?void 0:t.code)&&Da("user",e),t}const n=t.cache&&Date.now();t.cache&&La(r,{cachedAt:n});const{users:s}=r;return Qe("user.fetched",r),{data:s.find((t=>t.userId===e)),cachedAt:n}};ku.locally=e=>{const t=ye();if(t.log("user/getUser.locally",e),!t.cache)return;const r=we(["user","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const Au=async(e={})=>{const t=ye();t.log("user/queryUsers",e);const{page:r,limit:n=10,displayName:s,filter:i="all",sortBy:o="displayName"}=e,a=xa(e,["page","limit","displayName","filter","sortBy"]),{data:l}=await t.http.get("/api/v3/users",{params:Object.assign(Object.assign({},a),{keyword:s,filter:i,sortBy:o,options:r?{token:r}:{limit:n}})}),{paging:c}=l,u=xa(l,["paging"]),{users:d}=u,h=t.cache&&Date.now();if(t.cache){La(u,{cachedAt:h});const t=["user","query",Object.assign(Object.assign({},e),{options:{limit:n,token:r}})];Ee(t,{users:d.map(ce("user")),paging:c})}return Qe("user.fetched",l),{data:d,cachedAt:h,paging:c}};Au.locally=(e={})=>{var t,r,n;const s=ye();if(s.log("user/queryUsers.locally",e),!s.cache)return;const{limit:i=10,page:o}=null!=e?e:{},a=["user","query",Object.assign(Object.assign({},e),{options:{limit:i,token:o}})],{data:l,cachedAt:c}=null!==(t=we(a))&&void 0!==t?t:{},u=null!==(r=null==l?void 0:l.users.map((e=>we(["user","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];return u.length>0&&u.length===(null===(n=null==l?void 0:l.users)||void 0===n?void 0:n.length)?{data:u,cachedAt:c,paging:null==l?void 0:l.paging}:void 0};const _u=(e,t)=>{let r=Ae(e,"displayName",t.displayName);switch(t.sortBy){case"firstCreated":r=r.sort(Me);break;case"lastCreated":r=r.sort(Fe);break;default:r=r.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Oe)}return r},Iu=(e,t,r)=>{const{log:n,cache:s}=ye();s||console.log(p);const i=Date.now();n(`liveUsers(tmpid: ${i}) > listen`);const{limit:o}=e,a=xa(e,["limit"]),l=null!=o?o:h,{policy:c=f}=null!=r?r:{},u=[],d=["user","collection",Sa()],g=(r,n=!1)=>{var s,i;const o=null!==(s=r.data.map((e=>we(["user","get",e]))).filter(Boolean).map((({data:e})=>el.user(e))))&&void 0!==s?s:[];t({onNextPage:y,data:n?_u(o,e):o,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=we(d))||void 0===t?void 0:t.data;r&&(r.data=[...new Set([e.userId,...r.data])],Ee(d,r),g(r,!0))},y=(e=!1)=>{var t,r;const n=null===(t=we(d))||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},o=se(Au,Object.assign(Object.assign({},a),i));oe(o,(({data:t,error:r,loading:n,paging:i})=>{const o={loading:n,error:r,params:{page:null==i?void 0:i.next},data:s};t&&(o.data=e?t.map(ce("user")):[...new Set([...s,...t.map(ce("user"))])]),Ee(d,o),g(o)}),ie(c))};return u.push(wu(m()),ec(m()),Eu(m()),Tu(m()),Su(m())),y(!0),()=>{n(`liveUsers(tmpid: ${i}) > dispose`),u.forEach((e=>e()))}},Ru=async e=>{const t=ye();let r;t.log("user/getUser",e),Ol("user",e);try{r=(await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`)).data}catch(t){throw S(null==t?void 0:t.code)&&Da("user",e),t}const n=t.cache&&Date.now();t.cache&&La(r,{cachedAt:n});const{users:s}=r;return Qe("user.fetched",r),{data:el.user(s.find((t=>t.userId===e))),cachedAt:n}};Ru.locally=e=>{const t=ye();if(t.log("user/getUser.locally",e),!t.cache)return;const r=we(["user","get",e]);return r?{data:el.user(r.data),cachedAt:r.cachedAt}:void 0};const Lu=async({viewId:e,viewedType:t,limit:r,token:n})=>{const s=ye(),i={};n?i.token=n:i.limit=r;const o=`/api/v1/analytics/views/${"post"===t?"posts":"stories"}/${e}/users`,a=await s.http.get(o,{params:i});return La(a.data),a.data};var Du=Object.freeze({__proto__:null,Relationship:vu,getUserByIds:bu,updateUser:async(e,t)=>{const r=ye();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&&La(n,{cachedAt:s});const{users:i}=n;return Qe("user.updated",n),{data:i.find((t=>t.userId===e)),cachedAt:s}},flagUser:async e=>{const t=ye();t.log("user/flagUser",e);const{data:r}=await t.http.post(`api/v4/me/flags/${encodeURIComponent(e)}`);return t.cache&&La(r),Qe("user.flagged",r),!!r},unflagUser:async e=>{const t=ye();t.log("user/unflag",e);const{data:r}=await t.http.delete(`/api/v4/me/flags/${encodeURIComponent(e)}`);return t.cache&&La(r),Qe("user.unflagged",r),!!r},isUserFlaggedByMe:async e=>{const t=ye();t.log("user/isUserFlaggedByMe",e);const{data:{isFlagByMe:r}}=await t.http.get(`/api/v3/users/${e}/isFlagByMe`);return r},onUserUpdated:wu,onUserDeleted:ec,onUserFlagged:Eu,onUserUnflagged:Tu,onUserFlagCleared:Su,getUser:(e,t)=>Tc(e,(e=>t(Object.assign(Object.assign({},e),{data:e.data?el.user(e.data):e.data}))),"userId",ku,[Cu,wu,ec,Eu,Tu,Su]),getUsers:Iu,observeUser:(e,t)=>{const{log:r}=ye(),n=Date.now();r(`observeUser(tmpid: ${n}) > listen`);const s=(r,n)=>{var s,i,o;if((null===(s=r.data)||void 0===s?void 0:s.userId)!==e)return;const a=Object.assign(Object.assign({},r),{data:el.user(r.data)});if(t instanceof Function)return t(a);"onFetch"!==n&&(null===(i=t.onEvent)||void 0===i||i.call(t,n,a)),null===(o=t[n])||void 0===o||o.call(t,a)},i=[];return i.push(wu((e=>s({data:e,loading:!1,origin:"event"},"onUpdate"))),ec((e=>s({data:e,loading:!1,origin:"event"},"onDelete"))),Eu((e=>s({data:e,loading:!1,origin:"event"},"onFlagged"))),Tu((e=>s({data:e,loading:!1,origin:"event"},"onUnflagged"))),Su((e=>s({data:e,loading:!1,origin:"event"},"onFlagCleared")))),oe(se(Ru,e),(e=>e.data&&s(e,"onFetch"))),()=>{r(`observeUser(tmpid: ${n}) > dispose`),i.forEach((e=>e()))}},getBlockedUsers:su,searchUserByDisplayName:(e,t,r)=>Iu(Object.assign(Object.assign({},e),{filter:"all"}),t,r),getViewedUsers:(e,t)=>{const{log:r,cache:n}=ye(),s=["postViewedUsers","collection",{postId:e.postId}];n||console.log(p);const i=Date.now();r(`getViewedUsers(tmpid: ${i}) > listen`);const{limit:o,postId:a}=e,l=(e=!1)=>{var r,n,i;const c=null===(r=we(s))||void 0===r?void 0:r.data,u=null!==(n=null==c?void 0:c.data)&&void 0!==n?n:[];if(!e&&u.length>0&&!(null==c?void 0:c.params.page))return;const d=se(Lu,{viewId:a,viewedType:"post",limit:o||10,token:e||null===(i=null==c?void 0:c.params.page)||void 0===i?void 0:i.next});oe(d,(e=>{var r,n,i,o,a;let c=null!==(i=null===(n=null===(r=we(s))||void 0===r?void 0:r.data)||void 0===n?void 0:n.data)&&void 0!==i?i:[];(null===(o=e.data)||void 0===o?void 0:o.users)&&(c=[...new Set([...c,...e.data.users.map((({userId:e})=>e))])]);const u={loading:e.loading,params:{page:null===(a=e.data)||void 0===a?void 0:a.paging},data:c||[]};Ee(s,u),(e=>{var r,n;let s=[];(null==e?void 0:e.data)&&(s=e.data.map((e=>we(["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})})(u)}),ie(f,v))};return l(!0),()=>{r(`getViewedUsers(tmpid: ${i}) > dispose`),Ce(s)}},getReachedUsers:(e,t)=>{let r=(e=!1)=>{};const{log:n,cache:s}=ye(),i=["viewedUsers","collection",{viewId:e.viewId,viewedType:e.viewedType}];s||console.log(p);const o=Date.now();n(`getReachUsers(tmpid: ${o}) > listen`);const{limit:a,viewId:l,viewedType:c}=e;return r=(e=!1)=>{var n,s,o;const u=null===(n=we(i))||void 0===n?void 0:n.data,d=null!==(s=null==u?void 0:u.data)&&void 0!==s?s:[];if(!e&&d.length>0&&!(null==u?void 0:u.params.page))return;const h=se(Lu,{viewId:l,viewedType:c,limit:a||10,token:e||null===(o=null==u?void 0:u.params.page)||void 0===o?void 0:o.next});oe(h,(e=>{var n,s,o,a,l;let c=null!==(o=null===(s=null===(n=we(i))||void 0===n?void 0:n.data)||void 0===s?void 0:s.data)&&void 0!==o?o:[];(null===(a=e.data)||void 0===a?void 0:a.users)&&(c=[...new Set([...c,...e.data.users.map((({userId:e})=>e))])]);const u={loading:e.loading,params:{page:null===(l=e.data)||void 0===l?void 0:l.paging},data:c||[]};Ee(i,u),(e=>{var n,s;let i=[];(null==e?void 0:e.data)&&(i=e.data.map((e=>we(["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})})(u)}),ie(f,v))},r(!0),()=>{n(`getReachUsers(tmpid: ${o}) > dispose`),Ce(i)}}});const xu=async e=>{const t=ye();t.log("file/getFile",e);const{data:r}=await t.http.get(`/api/v3/files/${e}`),n=t.cache&&Date.now();return t.cache&&La({files:[r]},{cachedAt:n}),{data:r,cachedAt:n}};xu.locally=e=>{const t=ye();if(t.log("file/getFile.locally",e),!t.cache)return;const r=we(["file","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const Ou=async(e,t,r)=>{const n=ye();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))}}),o=n.cache&&Date.now();return n.cache&&La({files:i},{cachedAt:o}),{data:i,cachedAt:o}},Pu=async(e,t)=>{const r=ye();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&&La({files:s},{cachedAt:i}),{data:s,cachedAt:i}};var Mu=Object.freeze({__proto__:null,getFile:xu,uploadFile:async(e,t)=>{const r=ye();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&&La({files:s},{cachedAt:i}),{data:s,cachedAt:i}},deleteFile:async e=>{const t=ye();return t.log("file/deleteFile",e),await t.http.delete(`/api/v3/files/${e}`),Ce(["file","get",e],!0),{success:!0}},fileUrlWithSize:(e,t)=>`${e}?size=${t}`,uploadVideo:Ou,uploadImage:Pu,createImage:async(e,t)=>{const r=ye();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&&La({files:s},{cachedAt:i}),{data:s,cachedAt:i}},createFile:async(e,t)=>{const r=ye();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&&La({files:s},{cachedAt:i}),{data:s,cachedAt:i}},createVideo:async(e,t,r)=>{const n=ye();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))}}),o=n.cache&&Date.now();return n.cache&&La({files:i},{cachedAt:o}),{data:i,cachedAt:o}},observeFile:(e,t)=>{const{log:r}=ye(),n=Date.now();r(`observeFile(tmpid: ${n}) > listen`);return oe(se(xu,e),(r=>r.data&&((r,n)=>{var s,i,o;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===(o=t[n])||void 0===o||o.call(t,r)}})(r,"onFetch"))),()=>{r(`observeFile(tmpid: ${n}) > dispose`)}}});const Fu=async e=>{const t=ye();t.log("role/queryRoles",e);const r=null!=e?e:{},{page:n,limit:s=10,queryToken:i,displayName:o,sortBy:a}=r,l=xa(r,["page","limit","queryToken","displayName","sortBy"]),c=i?{token:i}:s?{limit:s}:n?{token:Q(n,"skiplimit")}:void 0,{data:u}=await t.http.get("/api/v3/roles",{params:Object.assign(Object.assign({},l),{keyword:o,sortBy:a,options:c})}),{paging:d}=u,h=xa(u,["paging"]),{roles:f}=h,p=t.cache&&Date.now();t.cache&&La(h,{cachedAt:p});const g=X(d.next);return{data:f,cachedAt:p,prevPage:X(d.previous),nextPage:g,paging:d}};Fu.locally=e=>{ye().log("role/queryRoles.locally",e)};const Nu=async e=>{const t=ye();t.log("role/getRole",e);const{data:r}=await t.http.get(`/api/v3/roles/${e}`),n=t.cache&&Date.now();return t.cache&&La({roles:r},{cachedAt:n}),{data:r.find((t=>t.roleId===e)),cachedAt:n}};Nu.locally=e=>{const t=ye();if(t.log("role/getRole.locally",e),!t.cache)return;const r=we(["role","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const Uu=(e,t)=>{"message"===e?Qe("local.message.updated",{messages:[t]}):"post"===e?Qe("post.updated",{posts:[t]}):"comment"===e?Qe("comment.updated",{comments:[t]}):"story"===e&&Qe("story.updated",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[t]})},Bu=async(e,t=!1)=>{const r=ye();let n;r.log("message/getMessage",e),t||console.log("getMessage will be deprecated on 15th November 2022, please use liveMessage instead."),Ol("message",e);try{const{data:t}=await r.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);n=await Cl(t)}catch(t){throw S(null==t?void 0:t.code)&&Da("message",e),t}const s=r.cache&&Date.now();r.cache&&La(n,{cachedAt:s});const{messages:i}=n;return Qe("local.message.fetched",{messages:i}),{data:i.find((t=>t.messageId===e)),cachedAt:s}};Bu.locally=e=>{const t=ye();if(t.log("message/getMessage.locally",e),!t.cache)return;const r=we(["message","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const ju=async e=>{const t=ye();let r;t.log("post/getPost",e),Ol("post",e);try{r=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw S(null==t?void 0:t.code)&&Da("post",e),t}const n=Pa(r,"communityUsers"),s=t.cache&&Date.now();t.cache&&La(n,{cachedAt:s});const{posts:i}=n,o=i.find((t=>t.postId===e));return{data:el.post(o),cachedAt:s}};ju.locally=e=>{const t=ye();if(t.log("post/getPost.locally",e),!t.cache)return;const r=we(["post","get",e]);return r?{data:el.post(r.data),cachedAt:r.cachedAt}:void 0};const $u=async e=>{const t=ye();let r;t.log("comment/getComment",e),Ol("comment",e);try{r=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw S(null==t?void 0:t.code)&&Da("comment",e),t}const n=t.cache&&Date.now();t.cache&&La(r,{cachedAt:n});const{comments:s}=r;return{data:el.comment(s.find((t=>t.commentId===e))),cachedAt:n}};$u.locally=e=>{const t=ye();if(t.log("comment/getComment.locally",e),!t.cache)return;const r=we(["comment","get",e]);return r?{data:el.comment(r.data),cachedAt:r.cachedAt}:void 0};const qu=(e,t)=>{const r=e.split(".")[0],n=e.split(".")[1];let s=((e,t)=>{var r,n;let s,i;if("post"===t)i="post",s=e.posts[0].postId;else{if("comment"!==t)throw new Error("Unknown event type");i="comment",s=e.comments[0].commentId}return(null===(n=null===(r=we([i,"get",s]))||void 0===r?void 0:r.data)||void 0===n?void 0:n.myReactions)||[]})(t,r);if(ye().userId===t.reactor.userId)if("addReaction"===n)s.includes(t.reactor.reactionName)||s.push(t.reactor.reactionName);else{if("removeReaction"!==n)throw new Error(`Unknown event type: ${n}`);s=s.filter((e=>e!==t.reactor.reactionName))}return((e,t,r)=>{const[n]=e[t];return Object.assign(Object.assign({},e),{[t]:[Object.assign(Object.assign({},n),{myReactions:r})]})})(t,`${r}s`,s)},Ku=async(e,t,r)=>{const n=ye();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=we([e,"get",t]);(null==r?void 0:r.data)&&Ee([e,"get",t],r.data,{cachedAt:Date.now()})}return!0};Ku.optimistically=(e,t,r)=>{var n,s,i,o,a;const l=ye();if(l.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:r}),!l.cache)return;const c=we([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 u=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 Se([e,"get",t],u,{cachedAt:-5}),Uu(e,u),null!==(a=null===(o=null==u?void 0:u.myReactions)||void 0===o?void 0:o.includes(r))&&void 0!==a&&a};const Gu=async(e,t,r)=>{const n=ye();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=we([e,"get",t]);(null==r?void 0:r.data)&&Ee([e,"get",t],r.data,{cachedAt:Date.now()})}return!0};Gu.optimistically=(e,t,r)=>{var n,s,i,o,a;const l=ye();if(l.log("reaction/removeReaction.optimistically",{referenceId:t,referenceType:e,reactionName:r}),!l.cache)return;const c=we([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 u=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 Se([e,"get",t],u,{cachedAt:-5}),Uu(e,u),null!==(a=!(null===(o=null==u?void 0:u.myReactions)||void 0===o?void 0:o.includes(r)))&&void 0!==a&&a};const Hu=(e,t)=>{const r=ye();return Ye(r,e,e,(n=>{var s;if(r.cache){const{communities:i}=n,o=xa(n,["communities"]),a=Pa(o,"communityUsers");if(La(a),(null==i?void 0:i[0])&&!["post.updated"].includes(e)&&Qe("community.updated",{communities:i,categories:[],communityUsers:a.communityUsers,feeds:[],files:[],users:[]}),"post.deleted"===e){const{postId:e,postedUserId:s}=n.posts[0];try{Ol("post",e)}catch(e){return}return s!==r.userId&&Da("post",e),t(n.posts[0])}const l=we(["post","get",n.posts[0].postId]);if(["post.created","post.approved","post.declined"].includes(e)){let t=null===(s=be(["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})=>Se(e,t,{cachedAt:-1})))}t(l.data)}else t(n.posts[0])}))},Vu=e=>Hu("post.created",e),zu=e=>Hu("post.updated",e),Wu=e=>Hu("post.deleted",e),Yu=e=>Hu("post.approved",e),Qu=e=>Hu("post.declined",e),Xu=e=>Hu("post.flagged",e),Ju=e=>Hu("post.unflagged",e),Zu=e=>{const t=ye();return Ye(t,"post.addReaction","post.addReaction",(r=>{if(t.cache){const t=xa(qu("post.addReaction",r),["reactor"]);La(t);const n=we(["post","get",r.posts[0].postId]);e(n.data)}else e(r.posts[0])}))},ed=e=>{const t=ye();return Ye(t,"post.removeReaction","post.removeReaction",(r=>{if(t.cache){const t=xa(qu("post.removeReaction",r),["reactor"]);La(t);const n=we(["post","get",r.posts[0].postId]);e(n.data)}else e(r.posts[0])}))},td=(e,t)=>{const r=ye();return Ye(r,e,e,(n=>{var s;if(r.cache){La(n);const{comments:r}=n;if(r.length>0){const n=we(["comment","get",r[0].commentId]);if(["comment.created"].includes(e)){if(r[0].parentId){const e=we(["comment","get",r[0].parentId]);(null==e?void 0:e.data)&&Ee(["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=be(["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})=>Se(e,t,{cachedAt:-1})))}t(el.comment(n.data))}}else t(el.comment(n.comments[0]))}))},rd=e=>td("comment.created",e),nd=e=>td("comment.updated",e),sd=e=>td("comment.deleted",e),id=e=>td("comment.flagged",e),od=e=>td("comment.unflagged",e),ad=e=>{const t=ye();return Ye(t,"comment.addReaction","comment.addReaction",(r=>{if(t.cache){const t=xa(qu("comment.addReaction",r),["reactor"]);La(t);const n=we(["comment","get",r.comments[0].commentId]);e(el.comment(n.data))}else e(el.comment(r.comments[0]))}))},ld=e=>{const t=ye();return Ye(t,"comment.removeReaction","comment.removeReaction",(r=>{if(t.cache){const t=xa(qu("comment.removeReaction",r),["reactor"]);La(t);const n=we(["comment","get",r.comments[0].commentId]);e(el.comment(n.data))}else e(el.comment(r.comments[0]))}))},cd=(e,t,r)=>{const n=ye(),s=(n,s,i)=>{n===e&&s===t&&r(i)};if("message"===e){return Ye(n,"reaction/onReactorAdded","message.updated",(async e=>{const t=await Cl(e);t.reactions[0]&&(La(t),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return Ye(n,"post.addReaction","post.addReaction",(e=>{const{reactor:t}=e,r=xa(e,["reactor"]);La(r),La({reactions:[t]}),s("post",e.posts[0].postId,t)}))}return Ye(n,"comment.addReaction","comment.addReaction",(e=>{const{reactor:t}=e,r=xa(e,["reactor"]);La(r),La({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))},ud=(e,t,r)=>{const n=ye(),s=(n,s,i)=>{n===e&&s===t&&r(i)};if("message"===e){return Ye(n,"reaction/onReactorRemoved","message.updated",(async e=>{const t=await Cl(e);t.reactions[0]&&(La(t),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return Ye(n,"post.removeReaction","post.removeReaction",(e=>{const{reactor:t}=e,r=xa(e,["reactor"]);La(r),La({reactions:[t]}),s("post",e.posts[0].postId,t)}))}return Ye(n,"comment.removeReaction","comment.removeReaction",(e=>{const{reactor:t}=e,r=xa(e,["reactor"]);La(r),La({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))},dd=async e=>{ye().log("reaction/queryReactor",e);const t=await(async e=>{const t=ye();t.log("reaction/queryReactions",e);const r=null!=e?e:{},{page:n={limit:10}}=r,s=xa(r,["page"]),{data:i}=await t.http.get("/api/v3/reactions",{params:Object.assign(Object.assign({},s),{referenceVersion:5,options:{token:Q(n,"afterbeforeraw")}})}),{paging:o}=i,a=xa(i,["paging"]),{reactions:l}=a;La(Object.assign(Object.assign({},a),{reactions:l})),La(Object.assign(Object.assign({},a),{reactors:l[0].reactors}));const c=J(o.next);return{data:l,prevPage:J(o.previous),nextPage:c}})(e),{data:r}=t,n=xa(t,["data"]);return Object.assign(Object.assign({},n),{data:r[0].reactors})};var hd=Object.freeze({__proto__:null,addReaction:Ku,removeReaction:Gu,onReactionAdded:(e,t,r)=>{const n=n=>{ce(e)(n)===t&&r(n)};if("message"===e){const e=ye(),t=async e=>{var t;const r=await Cl(e),s=we(["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;La(r),i&&n(r.messages[0])};return Ye(e,"reaction/onReactionAdded","message.updated",t)}return"post"===e?Zu(n):ad(n)},onReactionRemoved:(e,t,r)=>{const n=n=>{ce(e)(n)===t&&r(n)};if("message"===e){const e=ye(),t=async e=>{var t;const r=await Cl(e),s=we(["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;La(r),i&&n(r.messages[0])};return Ye(e,"reaction/onReactionRemoved","message.updated",t)}return"post"===e?ed(n):ld(n)},onReactorAdded:cd,onReactorRemoved:ud,getReactions:(e,t,r)=>{const{log:n,cache:s}=ye();s||console.log("For using Live Collection feature you need to enable Cache!");const i=Date.now();n(`liveReactions(tmpid: ${i}) > listen`);const{limit:o}=e,a=xa(e,["limit"]),l=null!=o?o:h,{policy:c=f}=null!=r?r:{},u=[],d=["reaction","collection",{referenceId:e.referenceId,referenceType:e.referenceType}],p=e=>{var r,n;const s=null!==(r=e.data.map((e=>we(["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=we(d))||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))),Ee(d,n),p(n))},m=(e=!1)=>{var t,r,n,s;const i=null===(t=we(d))||void 0===t?void 0:t.data,o=null!==(r=null==i?void 0:i.data)&&void 0!==r?r:[];if(!e&&o.length>0&&!(null===(n=null==i?void 0:i.params)||void 0===n?void 0:n.page))return;const u=se(dd,Object.assign(Object.assign({},a),{page:null!==(s=e||null==i?void 0:i.params.page)&&void 0!==s?s:{limit:l}}));oe(u,(({data:e,error:t,loading:r,nextPage:n})=>{const s={loading:r,error:t,params:{page:n},data:o};e&&(s.data=[...new Set([...o,...e.map(ce("reactor"))])]),Ee(d,s),p(s)}),ie(c))};return u.push(cd(a.referenceType,a.referenceId,g("onAdded")),ud(a.referenceType,a.referenceId,g("onRemoved"))),m(!0),()=>{n(`liveReactions(tmpid: ${i}) > dispose`),u.forEach((e=>e()))}}}),fd={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 pd=async e=>{const t=ye();let r;t.log("channel/getChannel",e),Ol("channel",e);try{const{data:n}=await t.http.get(`/api/v3/channels/${encodeURIComponent(e)}`);r=await gl(n)}catch(t){throw S(null==t?void 0:t.code)&&Da("channel",e),t}const n=t.cache&&Date.now();t.cache&&La(r,{cachedAt:n});const{channels:s}=r;return{data:s.find((t=>t.channelId===e)),cachedAt:n}};pd.locally=e=>{const t=ye();if(t.log("channel/getChannel.locally",e),!t.cache)return;const r=we(["channel","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const gd=(e,t,r)=>n=>e((e=>{var s;if(!e)return e;const i=[r,"get",`${e[t]}`],o=null===(s=we(i))||void 0===s?void 0:s.data;return o?n(o):void 0}));function md(e,t){Ee(["channel","get",e.channelId],Object.assign(ol(e),t))}const yd=e=>{const t=ye();return Ye(t,"channelMarker/onChannelMarkerUpdated","local.channelMarker.updated",(t=>{e(t.userEntityMarkers[0])}))};var vd={exports:{}};!function(e,t){e.exports=function e(t,r,n){function s(o,a){if(!r[o]){if(!t[o]){if(!a&&ko)return ko(o);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}a=r[o]={exports:{}},t[o][0].call(a.exports,(function(e){return s(t[o][1][e]||e)}),a,a.exports,e,t,r,n)}return r[o].exports}for(var i=ko,o=0;o<n.length;o++)s(n[o]);return s}({1:[function(e,t,r){(function(n,s,i,o,a,l,c,u,d){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,o=Object.prototype.toString.call(t),a=/\[object (.*)\]/i.exec(o);if(a=(a=a?a[1]:"unknown:["+o+"]").toLowerCase(),0<=(o=r.indexOf(t)))return this.dispatch("[CIRCULAR:"+o+"]");if(r.push(t),void 0!==i&&i.isBuffer&&i.isBuffer(t))return n("buffer:"),n(t);if("object"===a||"function"===a||"asyncfunction"===a)return o=Object.keys(t),e.unorderedObjects&&(o=o.sort()),!1===e.respectType||y(t)||o.splice(0,0,"prototype","__proto__","constructor"),e.excludeKeys&&(o=o.filter((function(t){return!e.excludeKeys(t)}))),n("object:"+o.length+":"),s=this,o.forEach((function(r){s.dispatch(r),n(":"),e.excludeValues||s.dispatch(t[r]),n(",")}));if(!this["_"+a]){if(e.ignoreUnknown)return n("["+a+"]");throw new Error('Unknown object type "'+a+'"')}this["_"+a](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 o=[];return s=t.map((function(t){var n=new b,s=r.slice();return v(e,n,s).dispatch(t),o=o.concat(s.slice(r.length)),n.read().toString()})),r=r.concat(o),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,o,a,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),o="A".charCodeAt(0),a="-".charCodeAt(0),l="_".charCodeAt(0);function c(e){return(e=e.charCodeAt(0))===r||e===a?62:e===n||e===l?63:e<s?-1:e<s+10?e-s+26+26:e<o+26?e-o: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)),o=0<s?e.length-4:e.length,a=0;function l(e){i[a++]=e}for(r=0;r<o;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,o="";function a(e){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(e)}for(t=0,n=e.length-i;t<n;t+=3)o+=a((s=r=(e[t]<<16)+(e[t+1]<<8)+e[t+2])>>18&63)+a(s>>12&63)+a(s>>6&63)+a(63&s);switch(i){case 1:o=(o+=a((r=e[e.length-1])>>2))+a(r<<4&63)+"==";break;case 2:o=(o=(o+=a((r=(e[e.length-2]<<8)+e[e.length-1])>>10))+a(r>>4&63))+a(r<<2&63)+"="}return o}}(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,o,a,l,c,u){var d=e("base64-js"),h=e("ieee754");function s(e,t,r){if(!(this instanceof s))return new s(e,t,r);var n,i,o,a,l=typeof e;if("base64"===t&&"string"==l)for(e=(a=e).trim?a.trim():a.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(a=e)||s.isBuffer(a)||a&&"object"==typeof a&&"number"==typeof a.length)for(o=0;o<n;o++)s.isBuffer(e)?i[o]=e.readUInt8(o):i[o]=e[o];else if("string"==l)i.write(e,0,t);else if("number"==l&&!s._useTypedArrays&&!r)for(o=0;o<n;o++)i[o]=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 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+1<e.length,"trying to write beyond buffer length"),N(t,65535)),!((s=e.length)<=r))for(var i=0,o=Math.min(s-r,2);i<o;i++)e[r+i]=(t&255<<8*(n?i:1-i))>>>8*(n?i:1-i)}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+3<e.length,"trying to write beyond buffer length"),N(t,4294967295)),!((s=e.length)<=r))for(var i=0,o=Math.min(s-r,4);i<o;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"),U(t,32767,-32768)),e.length<=r||T(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"),U(t,2147483647,-2147483648)),e.length<=r||S(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 _(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 o=e[i];o.copy(r,n),n+=o.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,o,a,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 o=0;o<n;o++){var a=parseInt(t.substr(2*o,2),16);j(!isNaN(a),"Invalid hex string"),e[r+o]=a}return s._charsWritten=2*o,o}(this,e,t,r);break;case"utf8":case"utf-8":o=this,a=t,l=r,i=s._charsWritten=M(O(e),o,a,l);break;case"ascii":case"binary":i=f(this,e,t,r);break;case"base64":o=this,a=t,l=r,i=s._charsWritten=M(P(e),o,a,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,o,a=this;if(e=String(e||"utf8").toLowerCase(),t=Number(t)||0,(r=void 0!==r?Number(r):a.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}(a,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)}(a,t,r);break;case"ascii":case"binary":n=g(a,t,r);break;case"base64":s=a,o=r,n=0===(i=t)&&o===s.length?d.fromByteArray(s):d.fromByteArray(s.slice(i,o));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}(a,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 o=0;o<i;o++)e[o+t]=this[o+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),o=0;o<n;o++)i[o]=this[o+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"),N(e,255)),t>=this.length||(this[t]=e)},s.prototype.writeUInt16LE=function(e,t,r){T(this,e,t,!0,r)},s.prototype.writeUInt16BE=function(e,t,r){T(this,e,t,!1,r)},s.prototype.writeUInt32LE=function(e,t,r){S(this,e,t,!0,r)},s.prototype.writeUInt32BE=function(e,t,r){S(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"),U(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){_(this,e,t,!0,r)},s.prototype.writeDoubleBE=function(e,t,r){_(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 I=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("%")),o=0;o<i.length;o++)t.push(parseInt(i[o],16))}return t}function P(e){return d.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 N(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 U(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=I.get,e.set=I.set,e.write=I.write,e.toString=I.toString,e.toLocaleString=I.toString,e.toJSON=I.toJSON,e.copy=I.copy,e.slice=I.slice,e.readUInt8=I.readUInt8,e.readUInt16LE=I.readUInt16LE,e.readUInt16BE=I.readUInt16BE,e.readUInt32LE=I.readUInt32LE,e.readUInt32BE=I.readUInt32BE,e.readInt8=I.readInt8,e.readInt16LE=I.readInt16LE,e.readInt16BE=I.readInt16BE,e.readInt32LE=I.readInt32LE,e.readInt32BE=I.readInt32BE,e.readFloatLE=I.readFloatLE,e.readFloatBE=I.readFloatBE,e.readDoubleLE=I.readDoubleLE,e.readDoubleBE=I.readDoubleBE,e.writeUInt8=I.writeUInt8,e.writeUInt16LE=I.writeUInt16LE,e.writeUInt16BE=I.writeUInt16BE,e.writeUInt32LE=I.writeUInt32LE,e.writeUInt32BE=I.writeUInt32BE,e.writeInt8=I.writeInt8,e.writeInt16LE=I.writeInt16LE,e.writeInt16BE=I.writeInt16BE,e.writeInt32LE=I.writeInt32LE,e.writeInt32BE=I.writeInt32BE,e.writeFloatLE=I.writeFloatLE,e.writeFloatBE=I.writeFloatBE,e.writeDoubleLE=I.writeDoubleLE,e.writeDoubleBE=I.writeDoubleBE,e.fill=I.fill,e.inspect=I.inspect,e.toArrayBuffer=I.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,o,a,l,c,u){s=e("buffer").Buffer;var d=4,h=new s(d);h.fill(0),t.exports={hash:function(e,t,r,n){for(var i=t(function(e,t){e.length%d!=0&&(r=e.length+(d-e.length%d),e=s.concat([e,h],r));for(var r,n=[],i=t?e.readInt32BE:e.readInt32LE,o=0;o<e.length;o+=d)n.push(i.call(e,o));return n}(e=s.isBuffer(e)?e:new s(e),n),8*e.length),o=(t=n,new s(r)),a=t?o.writeInt32BE:o.writeInt32LE,l=0;l<i.length;l++)a.call(o,i[l],4*l,!0);return o}}}).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,o,a,l,c,u){s=e("buffer").Buffer;var d=e("./sha"),h=e("./sha256"),f=e("./rng"),p={sha1:d,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),o=0;o<g;o++)n[o]=54^t[o],i[o]=92^t[o];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,o,a,l,c,u){var d=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,o=0;o<e.length;o+=16){var a=r,l=n,c=s,u=i;r=p(r,n,s,i,e[o+0],7,-680876936),i=p(i,r,n,s,e[o+1],12,-389564586),s=p(s,i,r,n,e[o+2],17,606105819),n=p(n,s,i,r,e[o+3],22,-1044525330),r=p(r,n,s,i,e[o+4],7,-176418897),i=p(i,r,n,s,e[o+5],12,1200080426),s=p(s,i,r,n,e[o+6],17,-1473231341),n=p(n,s,i,r,e[o+7],22,-45705983),r=p(r,n,s,i,e[o+8],7,1770035416),i=p(i,r,n,s,e[o+9],12,-1958414417),s=p(s,i,r,n,e[o+10],17,-42063),n=p(n,s,i,r,e[o+11],22,-1990404162),r=p(r,n,s,i,e[o+12],7,1804603682),i=p(i,r,n,s,e[o+13],12,-40341101),s=p(s,i,r,n,e[o+14],17,-1502002290),r=g(r,n=p(n,s,i,r,e[o+15],22,1236535329),s,i,e[o+1],5,-165796510),i=g(i,r,n,s,e[o+6],9,-1069501632),s=g(s,i,r,n,e[o+11],14,643717713),n=g(n,s,i,r,e[o+0],20,-373897302),r=g(r,n,s,i,e[o+5],5,-701558691),i=g(i,r,n,s,e[o+10],9,38016083),s=g(s,i,r,n,e[o+15],14,-660478335),n=g(n,s,i,r,e[o+4],20,-405537848),r=g(r,n,s,i,e[o+9],5,568446438),i=g(i,r,n,s,e[o+14],9,-1019803690),s=g(s,i,r,n,e[o+3],14,-187363961),n=g(n,s,i,r,e[o+8],20,1163531501),r=g(r,n,s,i,e[o+13],5,-1444681467),i=g(i,r,n,s,e[o+2],9,-51403784),s=g(s,i,r,n,e[o+7],14,1735328473),r=m(r,n=g(n,s,i,r,e[o+12],20,-1926607734),s,i,e[o+5],4,-378558),i=m(i,r,n,s,e[o+8],11,-2022574463),s=m(s,i,r,n,e[o+11],16,1839030562),n=m(n,s,i,r,e[o+14],23,-35309556),r=m(r,n,s,i,e[o+1],4,-1530992060),i=m(i,r,n,s,e[o+4],11,1272893353),s=m(s,i,r,n,e[o+7],16,-155497632),n=m(n,s,i,r,e[o+10],23,-1094730640),r=m(r,n,s,i,e[o+13],4,681279174),i=m(i,r,n,s,e[o+0],11,-358537222),s=m(s,i,r,n,e[o+3],16,-722521979),n=m(n,s,i,r,e[o+6],23,76029189),r=m(r,n,s,i,e[o+9],4,-640364487),i=m(i,r,n,s,e[o+12],11,-421815835),s=m(s,i,r,n,e[o+15],16,530742520),r=y(r,n=m(n,s,i,r,e[o+2],23,-995338651),s,i,e[o+0],6,-198630844),i=y(i,r,n,s,e[o+7],10,1126891415),s=y(s,i,r,n,e[o+14],15,-1416354905),n=y(n,s,i,r,e[o+5],21,-57434055),r=y(r,n,s,i,e[o+12],6,1700485571),i=y(i,r,n,s,e[o+3],10,-1894986606),s=y(s,i,r,n,e[o+10],15,-1051523),n=y(n,s,i,r,e[o+1],21,-2054922799),r=y(r,n,s,i,e[o+8],6,1873313359),i=y(i,r,n,s,e[o+15],10,-30611744),s=y(s,i,r,n,e[o+6],15,-1560198380),n=y(n,s,i,r,e[o+13],21,1309151649),r=y(r,n,s,i,e[o+4],6,-145523070),i=y(i,r,n,s,e[o+11],10,-1120210379),s=y(s,i,r,n,e[o+2],15,718787259),n=y(n,s,i,r,e[o+9],21,-343485551),r=v(r,a),n=v(n,l),s=v(s,c),i=v(i,u)}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,o){return f(t&r|~t&n,e,t,s,i,o)}function g(e,t,r,n,s,i,o){return f(t&n|r&~n,e,t,s,i,o)}function m(e,t,r,n,s,i,o){return f(t^r^n,e,t,s,i,o)}function y(e,t,r,n,s,i,o){return f(r^(t|~n),e,t,s,i,o)}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 d.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,o,a,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,o,a,l,c,u){var d=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),o=1732584193,a=-271733879,l=-1732584194,c=271733878,u=-1009589776,d=0;d<e.length;d+=16){for(var h=o,g=a,m=l,y=c,v=u,b=0;b<80;b++){i[b]=b<16?e[d+b]:p(i[b-3]^i[b-8]^i[b-14]^i[b-16],1);var w=f(f(p(o,5),(w=a,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(u,i[b]),(r=b)<20?1518500249:r<40?1859775393:r<60?-1894007588:-899497514));u=c,c=l,l=p(a,30),a=o,o=w}o=f(o,h),a=f(a,g),l=f(l,m),c=f(c,y),u=f(u,v)}return Array(o,a,l,c,u)}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 d.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,o,a,l,c,u){function d(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 o,a,l=0;l<e.length;l+=16){for(var c=s[0],u=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]:d(d(d((a=i[w-2],p(a,17)^p(a,19)^g(a,10)),i[w-7]),(a=i[w-15],p(a,7)^p(a,18)^g(a,3))),i[w-16]),r=d(d(d(d(b,p(a=m,6)^p(a,11)^p(a,25)),m&y^~m&v),n[w]),i[w]),o=d(p(o=c,2)^p(o,13)^p(o,22),c&u^c&h^u&h),b=v,v=y,y=m,m=d(f,r),f=h,h=u,u=c,c=d(r,o);s[0]=d(c,s[0]),s[1]=d(u,s[1]),s[2]=d(h,s[2]),s[3]=d(f,s[3]),s[4]=d(m,s[4]),s[5]=d(y,s[5]),s[6]=d(v,s[6]),s[7]=d(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,o,a,l,c){r.read=function(e,t,r,n,s){var i,o,a=8*s-n-1,l=(1<<a)-1,c=l>>1,u=-7,d=r?s-1:0,h=r?-1:1;for(s=e[t+d],d+=h,i=s&(1<<-u)-1,s>>=-u,u+=a;0<u;i=256*i+e[t+d],d+=h,u-=8);for(o=i&(1<<-u)-1,i>>=-u,u+=n;0<u;o=256*o+e[t+d],d+=h,u-=8);if(0===i)i=1-c;else{if(i===l)return o?NaN:1/0*(s?-1:1);o+=Math.pow(2,n),i-=c}return(s?-1:1)*o*Math.pow(2,i-n)},r.write=function(e,t,r,n,s,i){var o,a,l=8*i-s-1,c=(1<<l)-1,u=c>>1,d=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?(a=isNaN(t)?1:0,o=c):(o=Math.floor(Math.log(t)/Math.LN2),t*(n=Math.pow(2,-o))<1&&(o--,n*=2),2<=(t+=1<=o+u?d/n:d*Math.pow(2,1-u))*n&&(o++,n/=2),c<=o+u?(a=0,o=c):1<=o+u?(a=(t*n-1)*Math.pow(2,s),o+=u):(a=t*Math.pow(2,u-1)*Math.pow(2,s),o=0));8<=s;e[r+h]=255&a,h+=f,a/=256,s-=8);for(o=o<<s|a,l+=s;0<l;e[r+h]=255&o,h+=f,o/=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,o,a,l,c){var u,d,h;function f(){}(e=t.exports={}).nextTick=(d="undefined"!=typeof window&&window.setImmediate,h="undefined"!=typeof window&&window.postMessage&&window.addEventListener,d?function(e){return window.setImmediate(e)}:h?(u=[],window.addEventListener("message",(function(e){var t=e.source;t!==window&&null!==t||"process-tick"!==e.data||(e.stopPropagation(),0<u.length&&u.shift()())}),!0),function(e){u.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)}(vd);var bd=vd.exports;class wd{constructor(e){const{http:t}=ye();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 o=await this.getRequest(this.queryParams,i);return"first"===e&&(this.nextToken=null===(t=o.paging)||void 0===t?void 0:t.next,this.previousToken=null===(r=o.paging)||void 0===r?void 0:r.previous),"prev"===e&&(this.previousToken=null===(n=o.paging)||void 0===n?void 0:n.previous),"next"===e&&(this.nextToken=null===(s=o.paging)||void 0===s?void 0:s.next),o}getNextToken(){return this.nextToken}getPrevToken(){return this.previousToken}}class Ed extends wd{async getRequest(e,t){const{limit:r=h,displayName:n,membership:s}=e,i=xa(e,["limit","displayName","membership"]),o=t?{token:t}:{limit:r},{data:a}=await this.http.get("/api/v3/channels",{params:Object.assign(Object.assign({},i),{keyword:n,filter:s,options:o})});return a}}class Td{constructor(e,t){this.query=e,this.cacheKey=t}}class Sd extends Td{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=ye(),n=r.cache&&Date.now();r.cache&&La(t,{cachedAt:n})}appendToQueryStream(e,t,r=!1){var n,s;if(r)Ee(this.cacheKey,{data:e.channels.map(ce("channel"))});else{const t=null===(n=we(this.cacheKey))||void 0===n?void 0:n.data,r=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Ee(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...r,...e.channels.map(ce("channel"))])]}))}}reactor(e){return e=>{var t;const r=null===(t=we(this.cacheKey))||void 0===t?void 0:t.data;r&&(this.paginationController instanceof Ed&&(r.data=[...new Set([e.channelId,...r.data])],Ee(this.cacheKey,r)),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Cd{constructor(e){const{http:t}=ye();this.queryParams=e,this.http=t}async onFetch(){return await this.getRequest(this.queryParams)}}class kd{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 Cd?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 Cd)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 Cd)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!Ec(this.snapshot,e)&&(this.snapshot=e.map((e=>wc(e))),!0)}getCacheKey(){return this.cacheKey}}class Ad extends Cd{async getRequest(e){const{data:t}=await this.http.get("/api/v3/channels/list",{params:Object.assign({},e)});return t}}class _d extends kd{constructor(e,t){const r=bd(e),n=["channel","collection",r],s=_d.getPaginationController(e);super(s,r,n,t),this.query=e,this.queryStreamController=new Sd(this.query,this.cacheKey,this.notifyChange.bind(this),gl,s),this.paginationController=s,this.callback=t.bind(this),this.loadPage(!0)}setup(){var e;(null===(e=we(this.cacheKey))||void 0===e?void 0:e.data)||Ee(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=we(this.cacheKey))||void 0===n?void 0:n.data;if(!i)return;let o=null!==(s=i.data.map((e=>we(["channel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(tl))&&void 0!==s?s:[];this.paginationController instanceof Ed&&(o=this.applyFilter(o)),(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:this.paginationController instanceof Ed?()=>this.loadPage(!1,"next"):void 0,data:o,hasNextPage:this.paginationController instanceof Ed&&!!this.paginationController.getNextToken(),loading:t,error:r})}applyFilter(e){const{userId:t}=ye();let r=e;switch(r=ke(r,"isDeleted",this.query.isDeleted),r=ke(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=Ie(r,this.query.membership,t)),this.query.sortBy){case"firstCreated":r=r.sort(Me);break;case"lastCreated":r=r.sort(Fe);break;case"displayName":r=r.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Oe);break;default:r=r.sort(Be)}return r}shouldAbort(e){var t,r;const n=null===(t=we(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 ye().getMessagePreviewSetting(!1)}static getPaginationController(e){return e.channelIds&&e.channelIds.length>0?new Ad(e):new Ed(e)}getSubscriptions(){const e=[{fn:gd((e=>Oc((t=>{var r;const n=null===(r=we(["channel","get",t.channelId]))||void 0===r?void 0:r.data;n&&(md(n,{lastActivity:t.createdAt}),e(t))}))),"messageId","channel"),action:"onUpdate"},{fn:Xl,action:"onDelete"},{fn:Cc,action:"onUpdate"},{fn:_c,action:"onMute"},{fn:kc,action:"onJoin"},{fn:Ac,action:"onLeft"},{fn:Ic,action:"onMemberAdded"},{fn:Rc,action:"onMemberRemoved"},{fn:gd(fc,"entityId","channel"),action:"onUpdate"},{fn:gd(yd,"entityId","channel"),action:"onUpdate"},{fn:gd((e=>Oc((async t=>{var r;if("no-message-preview"===await _d.getMessagePreviewSetting())return;if(ll(t),this.shouldAbort(t.channelId))return;const n=null===(r=we(["channel","get",t.channelId]))||void 0===r?void 0:r.data;n&&(md(n,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:gd((e=>Pc((async t=>{"no-message-preview"!==await _d.getMessagePreviewSetting()&&(cl(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:gd((e=>Mc((async t=>{const r=await _d.getMessagePreviewSetting();"no-message-preview"!==r&&("message-preview-include-deleted"===r&&await cl(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===r&&await pd(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:gd((e=>Gc((async t=>{var r;const n=null===(r=we(this.cacheKey))||void 0===r?void 0:r.data;if(!n)return;n.data.find((e=>{const r=$a(e);return(null==r?void 0:r.subChannelId)===t.subChannelId}))&&(await pd(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:gd((e=>Kc((async t=>{var r;if("no-message-preview"===await _d.getMessagePreviewSetting())return;(null===(r=we(this.cacheKey))||void 0===r?void 0:r.data)&&(await ul(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"}];return this.paginationController instanceof wd?[...e,{fn:Sc,action:"onCreate"}]:e}}class Id extends wd{async getRequest(e,t){const{limit:r=h}=e,n=xa(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 Rd extends Td{constructor(e,t,r,n){super(e,t),this.notifyChange=r,this.preparePayload=n}async saveToMainDB(e){const t=await this.preparePayload(e),r=ye(),n=r.cache&&Date.now();r.cache&&La(t,{cachedAt:n})}appendToQueryStream(e,t,r=!1){var n,s;if(r)Ee(this.cacheKey,{data:e.channelUsers.map((({channelId:e,userId:t})=>ce("channelUsers")({channelId:e,userId:t})))});else{const t=null===(n=we(this.cacheKey))||void 0===n?void 0:n.data,r=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Ee(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...r,...e.channelUsers.map((({channelId:e,userId:t})=>ce("channelUsers")({channelId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var r;if(this.query.channelId!==t.channelId)return;const n=null===(r=we(this.cacheKey))||void 0===r?void 0:r.data;if(!n)return;const s=ce("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]),Ee(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Ld extends kd{constructor(e,t){const r=bd(e),n=["channelUsers","collection",r];super(new Id(e),r,n,t),this.query=e,this.queryStreamController=new Rd(this.query,this.cacheKey,this.notifyChange.bind(this),gl),this.callback=t.bind(this),this.loadPage(!0)}setup(){var e;(null===(e=we(this.cacheKey))||void 0===e?void 0:e.data)||Ee(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:kc,action:"onJoin"},{fn:Ac,action:"onLeft"},{fn:Ic,action:"onMemberAdded"},{fn:Rc,action:"onMemberRemoved"},{fn:Jl,action:"onChannelMemberBanned"},{fn:Lc,action:"onChannelMemberUnbanned"},{fn:Dc,action:"onChannelMemberRoleAdded"},{fn:xc,action:"onChannelMemberRoleRemoved"}])}notifyChange({origin:e,loading:t,error:r}){var n,s;const i=null===(n=we(this.cacheKey))||void 0===n?void 0:n.data;if(!i)return;const o=this.applyFilter(null!==(s=i.data.map((e=>we(["channelUsers","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage(!1,"next"),data:o,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=xe(t,this.query.search));const r=this.query.sortBy?this.query.sortBy:"lastCreated";return t=t.sort("lastCreated"===r?Fe:Me),t}}const Dd=(e,t,r)=>{const{log:n,cache:s}=ye();s||console.log(p);const i=Date.now();n(`getMembers(tmpid: ${i}) > listen`);const o=new Ld(e,t),a=o.startSubscription(),l=o.getCacheKey();return a.push((()=>{Ce(l)})),()=>{n(`getMembers(tmpid: ${i}) > dispose`),a.forEach((e=>e()))}};var xd=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const r=ye();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=>Qe("channel.membersAdded",Object.assign(Object.assign({},n),{channelUsers:n.channelUsers.filter((t=>t.userId===e))}))));const s=await gl(n);r.cache&&La(s);const{channelUsers:i}=s;return!!i.find((t=>t.channelId===e&&"member"===t.membership))},removeMembers:async(e,t)=>{const r=ye();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=>Qe("channel.membersRemoved",Object.assign(Object.assign({},n),{channelUsers:n.channelUsers.filter((t=>t.userId===e))}))));const s=await gl(n);r.cache&&La(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=xe(r,t.search));const n=t.sortBy?t.sortBy:"lastCreated";return r=r.sort("lastCreated"===n?Fe:Me),r},getMembers:Dd,searchMembers:(e,t,r)=>Dd(e,t)});var Od=Object.freeze({__proto__:null,addRole:async(e,t,r)=>{const n=ye();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 gl(s);n.cache&&La(i),Qe("local.channel-moderator.role-added",i);const{channelUsers:o}=i;return!!o.find((r=>r.channelId===e&&r.roles.includes(t)))},removeRole:async(e,t,r)=>{const n=ye();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 gl(s);n.cache&&La(i),Qe("local.channel-moderator.role-removed",i);const{channelUsers:o}=i;return!!o.find((r=>r.channelId===e&&!r.roles.includes(t)))},banMembers:async(e,t)=>{const r=ye();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 gl(n),{channelUsers:i}=s,o=r.cache&&Date.now();return r.cache&&La(s,{cachedAt:o}),{data:null==i?void 0:i.filter((e=>"banned"===e.membership)),cachedAt:o}},unbanMembers:async(e,t)=>{const r=ye();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 gl(n),i=r.cache&&Date.now();r.cache&&La(s,{cachedAt:i});const{channelUsers:o}=s;return{data:null==o?void 0:o.filter((e=>"member"===e.membership)),cachedAt:i}}}),Pd=Object.freeze({__proto__:null,Membership:xd,Moderation:Od,getChannelByIds:ml,createChannel:async e=>{const t=ye();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=xa(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 gl(r.data),s=t.cache&&Date.now();t.cache&&La(n,{cachedAt:s});const{channels:i}=n;return{data:i[0],cachedAt:s}},updateChannel:async(e,t)=>{const r=ye();r.log("channel/updateChannel",e,t);const{data:n}=await r.http.put(`/api/v3/channels/${encodeURIComponent(e)}`,t),s=await gl(n),i=r.cache&&Date.now();r.cache&&La(s,{cachedAt:i});const{channels:o}=s;return{data:o.find((t=>t.channelId===e)),cachedAt:i}},deleteChannel:async e=>{const t=ye();t.log("channel/deleteChannel",e),await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}`);return(await pd(e)).data},joinChannel:async e=>{const t=ye();t.log("channel/joinChannel",e);const{data:r}=await t.http.post(`/api/v3/channels/${encodeURIComponent(e)}/join`),n=await gl(r);t.cache&&La(n);const{channelUsers:s}=n;return!!s.find((t=>t.channelId===e&&"member"===t.membership))},leaveChannel:async e=>{const t=ye();t.log("channel/leaveChannel",e);const{data:r}=await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/leave`),n=await gl(r);t.cache&&La(n);const{channelUsers:s}=n;return!!s.find((t=>t.channelId===e&&"member"!==t.membership))},muteChannel:async(e,t=-1)=>{const r=ye();if(r.log("channel/muteChannel",e),-1!==t&&t<0)throw new he("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=ye();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=ye();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,o=xa(r,["userMarkers","userEntityMarkers","userFeedMarkers"]),a=t.cache&&Date.now(),l=Na(s),c=Ua(i);return t.cache&&La(Object.assign({userMarkers:Fa(n),userEntityMarkers:l,userFeedMarkers:c},o),{cachedAt:a}),Qe("local.channelMarker.updated",{userEntityMarkers:l}),Qe("local.subChannelMarker.updated",{userFeedMarkers:c}),!0},onChannelCreated:Sc,onChannelUpdated:Cc,onChannelDeleted:Xl,onChannelJoined:kc,onChannelLeft:Ac,onChannelMuted:_c,onChannelMemberAdded:Ic,onChannelMemberRemoved:Rc,onChannelMemberBanned:Jl,onChannelMemberUnbanned:Lc,onChannelMemberRoleAdded:Dc,onChannelMemberRoleRemoved:xc,observeChannel:(e,t)=>{const{log:r}=ye(),n=Date.now();r(`observeChannel(tmpid: ${n}) > listen`);const s=(r,n)=>{var s,i,o;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===(o=t[n])||void 0===o||o.call(t,r)}},i=[];return i.push(Cc((e=>s({data:e,loading:!1,origin:"event"},"onUpdate"))),Xl((e=>s({data:e,loading:!1,origin:"event"},"onDelete"))),kc((e=>s({data:e,loading:!1,origin:"event"},"onJoin"))),Ac((e=>s({data:e,loading:!1,origin:"event"},"onLeft"))),_c((e=>s({data:e,loading:!1,origin:"event"},"onMute"))),Ic((e=>s({data:e,loading:!1,origin:"event"},"onMemberAdded"))),Rc((e=>s({data:e,loading:!1,origin:"event"},"onMemberRemoved"))),gd(fc,"entityId","channel")((e=>s({data:e,loading:!1,origin:"event"},"onUpdate")))),oe(se(pd,e),(e=>e.data&&s(e,"onFetch"))),()=>{r(`observeChannel(tmpid: ${n}) > dispose`),i.forEach((e=>e()))}},observeChannels:e=>{const{log:t}=ye(),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(Sc((e=>s(e,"onCreate"))),Cc((e=>s(e,"onUpdate"))),Xl((e=>s(e,"onDelete"))),kc((e=>s(e,"onJoin"))),Ac((e=>s(e,"onLeft"))),_c((e=>s(e,"onMute"))),Ic((e=>s(e,"onMemberAdded"))),Rc((e=>s(e,"onMemberRemoved"))),gd(fc,"entityId","channel")((e=>s(e,"onUpdate")))),()=>{t(`observeChannels(tmpid: ${r}) > dispose`),n.forEach((e=>e()))}},getChannel:(e,t)=>{const r=ye();let n;return Tc(e,(async e=>{if(!e.data)return t(e);const r=Object.assign(Object.assign({},e),{data:tl(e.data)}),s=xa(r,["origin"]);return Ec(n,s)?void 0:(n=s,t(r))}),"channelId",pd,[Cc,Xl,kc,Ac,Ic,Rc,Jl,Lc,_c,gd(fc,"entityId","channel"),gd(yd,"entityId","channel"),gd((t=>Oc((async n=>{var s;if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;if(await ll(n),n.channelId!==e)return;const i=null===(s=we(["channel","get",e]))||void 0===s?void 0:s.data;i&&(md(i,{messagePreviewId:n.messageId}),t(n))}))),"channelId","channel"),gd((t=>Pc((async n=>{var s;const i=null===(s=we(["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 cl(n),t(n))}))),"channelId","channel"),gd((t=>Mc((async n=>{var s;const i=null===(s=we(["channel","get",e]))||void 0===s?void 0:s.data;if(!i||i.messagePreviewId!==n.messageId)return;const o=await r.getMessagePreviewSetting(!1);"no-message-preview"!==o&&("message-preview-not-include-deleted"===o?(Ce(["messagePreviewChannel","get",e]),await pd(n.channelId)):await cl(n),t(n))}))),"channelId","channel"),gd((e=>Gc((async t=>{var n,s;const{channelId:i,subChannelId:o}=t,a=null===(n=we(["messagePreviewChannel","get",i]))||void 0===n?void 0:n.data;if(!a||a.subChannelId!==o)return;if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;await pd(i);(null===(s=we(["channel","get",i]))||void 0===s?void 0:s.data)&&e(t)}))),"channelId","channel"),gd((t=>Kc((async n=>{var s,i;if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;ul(n);const o=null===(s=we(["messagePreviewChannel","get",e]))||void 0===s?void 0:s.data;if(!o||o.subChannelId!==n.subChannelId)return;(null===(i=we(["channel","get",e]))||void 0===i?void 0:i.data)&&t(n)}))),"channelId","channel")],{forceDispatch:!0})},getChannels:(e,t,r)=>{const{log:n,cache:s,userId:i}=ye();s||console.log(p);const o=Date.now();n(`getChannels(tmpid: ${o}) > listen`);const a=new _d(e,t),l=a.startSubscription(),c=a.getCacheKey();return l.push((()=>{Ce(c)})),()=>{n(`getChannels(tmpid: ${o}) > dispose`),l.forEach((e=>e()))}},MARKER_INCLUDED_CHANNEL_TYPE:dl,isUnreadCountSupport:hl,convertFromRaw:fl,preUpdateChannelCache:pl,prepareChannelPayload:gl});const Md=async e=>{const t=ye();t.log("message/getMessages",e);const{data:r}=await t.http.get("/api/v5/messages/list",{params:{messageIds:e.map(encodeURIComponent)}}),n=await Cl(r),s=t.cache&&Date.now();t.cache&&La(n,{cachedAt:s});const{messages:i}=n;return Qe("local.message.fetched",{messages:i}),{data:i,cachedAt:s}};Md.locally=e=>{var t;const r=ye();if(r.log("message/getMessages.locally",e),!r.cache)return;const n=e.map((e=>we(["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 Fd=()=>`LOCAL_${Sa()}`;let Nd;const Ud=async e=>{const t=ye();t.log("message/createMessage",e);const r=e.referenceId||Nd||Fd();Nd=void 0;const{data:n}=await t.http.post("/api/v5/messages",Object.assign(Object.assign({},kl(e)),{referenceId:r})),s=await Cl(n),{messages:i}=s,o=t.cache&&Date.now();return t.cache&&(Ce(["message","get",r]),La(s,{cachedAt:o})),Qe("local.message.created",{messages:i}),{data:i[0],cachedAt:o}};Ud.optimistically=e=>{var t,r,{referenceId:n}=e,s=xa(e,["referenceId"]);const i=ye();if(!i.cache)return;Nd=n||Fd();const o=Object.assign({messageId:Nd,uniqueId:Nd},s);i.log("message/createMessage.optimistically",o);const a=we(["subChannel","get",s.subChannelId]);if(a&&(Se(["subChannel","get",s.subChannelId],Object.assign(Object.assign({},a.data),{messageCount:a.data.messageCount+1})),a.data.channelId===a.data.subChannelId)){const e=we(["channel","get",a.data.channelId]);(null==e?void 0:e.data)&&Se(["channel","get",a.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,channelSegment:(null!==(r=null==a?void 0:a.data.messageCount)&&void 0!==r?r:0)+1,childrenNumber:0,createdAt:l,updatedAt:l},o);return Ee(["message","get",c.messageId],c,{cachedAt:-5}),Qe("local.message.created",{messages:[c]}),{cachedAt:-5,data:c}};const Bd=async(e,t)=>{const r=ye();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)}`,kl(t)),s=await Cl(n),i=r.cache&&Date.now();r.cache&&La(s,{cachedAt:i});const{messages:o}=s;return Qe("local.message.updated",{messages:o}),{data:o.find((t=>t.messageId===e)),cachedAt:i}};Bd.optimistically=(e,t)=>{const r=ye();if(r.log("message/updateMessage.optimistically",t),!r.cache)return;const n=we(["message","get",e]);if(!n)return;const s=Object.assign(Object.assign(Object.assign({},n.data),t),{updatedAt:(new Date).toISOString()});return Se(["message","get",e],s,{cachedAt:-1}),Qe("local.message.updated",{messages:[s]}),{data:s,cachedAt:-1}};const jd=async(e,t)=>{const r=ye();r.log("message/editMessage",t);const{data:n}=await r.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,kl(t)),s=await Cl(n),i=r.cache&&Date.now();r.cache&&La(s,{cachedAt:i});const{messages:o}=s;return Qe("local.message.updated",{messages:o}),{data:o.find((t=>t.messageId===e)),cachedAt:i}};jd.optimistically=(e,t)=>{const r=ye();if(r.log("message/editMessage.optimistically",t),!r.cache)return;const n=we(["message","get",e]);if(!n)return;const s=Object.assign(Object.assign(Object.assign({},n.data),t),{updatedAt:(new Date).toISOString()});return Se(["message","get",e],s,{cachedAt:-1}),Qe("local.message.updated",{messages:[s]}),{data:s,cachedAt:-1}};const $d=async e=>{const t=ye();t.log("message/deleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const r=await Bu(e);return Qe("local.message.deleted",{messages:[r.data]}),r.data};$d.optimistically=e=>{ye().log("message/deleteMessage.optimistically",e);const t=we(["message","get",e]);if(!t)return;const r=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return Se(["message","get",e],r,{cachedAt:-1}),Qe("local.message.deleted",{messages:[r]}),{data:r,cachedAt:-1}};const qd=async e=>{const t=ye();t.log("message/softDeleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const r=await Bu(e);return Qe("local.message.deleted",{messages:[r.data]}),r.data};qd.optimistically=e=>{ye().log("message/softDeleteMessage.optimistically",e);const t=we(["message","get",e]);if(!t)return;const r=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return Se(["message","get",e],r,{cachedAt:-1}),Qe("local.message.deleted",{messages:[r]}),{data:r,cachedAt:-1}};const Kd=async e=>{const t=ye();t.log("user/getReadUsers",e);const{page:r,messageId:n}=e,s=xa(e,["page","messageId"]),{data:i}=await t.http.get(`/api/v1/markers/messages/${n}/read-users`,{params:Object.assign(Object.assign({},s),{options:{token:Q(r,"afterbeforeraw")}})}),{paging:o,publicUserIds:a,userFeedMarkers:l}=i,c=xa(i,["paging","publicUserIds","userFeedMarkers"]),u=t.cache&&Date.now();if(t.cache){La(Object.assign(Object.assign({},c),{userFeedMarkers:Ua(l)}),{cachedAt:u});const e=["read-user","query",Object.assign(Object.assign({messageId:n},s),{options:Object.assign({},r)})];Ee(e,{users:a,paging:o})}let d=[];a.length>0&&({data:d}=await bu(a));return{data:d,cachedAt:u,prevPage:X(o.previous),nextPage:X(o.next)}};Kd.locally=e=>{var t;const r=ye();if(r.log("user/getReadUsers.locally",e),!r.cache)return;const{page:n}=e,s=xa(e,["page"]),i=["read-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},n)})],{data:o,cachedAt:a}=null!==(t=we(i))&&void 0!==t?t:{},l=null==o?void 0:o.users.map((e=>{var t;return null===(t=we(["user","get",e]))||void 0===t?void 0:t.data}));if(!l||l.some((e=>!e)))return;return{data:l,cachedAt:a,prevPage:X(null==o?void 0:o.paging.previous),nextPage:X(null==o?void 0:o.paging.next)}};const Gd=async e=>{const t=ye();t.log("user/getDeliveredUsers",e);const{page:r,messageId:n}=e,s=xa(e,["page","messageId"]),{data:i}=await t.http.get(`/api/v1/markers/messages/${n}/delivered-users`,{params:Object.assign(Object.assign({},s),{options:{token:Q(r,"afterbeforeraw")}})}),{paging:o,publicUserIds:a,userFeedMarkers:l}=i,c=xa(i,["paging","publicUserIds","userFeedMarkers"]),u=t.cache&&Date.now();if(t.cache){La(Object.assign(Object.assign({},c),{userFeedMarkers:Ua(l)}),{cachedAt:u});const e=["delivered-user","query",Object.assign(Object.assign({messageId:n},s),{options:Object.assign({},r)})];Ee(e,{users:a,paging:o})}let d=[];a.length>0&&({data:d}=await bu(a));return{data:d,cachedAt:u,prevPage:X(o.previous),nextPage:X(o.next)}};Gd.locally=e=>{var t;const r=ye();if(r.log("user/getDeliveredUsers.locally",e),!r.cache)return;const{page:n}=e,s=xa(e,["page"]),i=["delivered-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},n)})],{data:o,cachedAt:a}=null!==(t=we(i))&&void 0!==t?t:{},l=null==o?void 0:o.users.map((e=>{var t;return null===(t=we(["user","get",e]))||void 0===t?void 0:t.data}));if(!l||l.some((e=>!e)))return;return{data:l,cachedAt:a,prevPage:X(null==o?void 0:o.paging.previous),nextPage:X(null==o?void 0:o.paging.next)}};class Hd extends wd{async getRequest(e,t){const r=Al(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 Vd extends Td{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=ye(),n=r.cache&&Date.now();r.cache&&La(t,{cachedAt:n})}appendToQueryStream(e,t,r=!1){var n,s;if(r)Ee(this.cacheKey,{data:e.messages.map(ce("message")),query:this.query});else{const r=null===(n=we(this.cacheKey))||void 0===n?void 0:n.data,i=null!==(s=null==r?void 0:r.data)&&void 0!==s?s:[];Ee(this.cacheKey,Object.assign(Object.assign({},r),{data:"next"===t?[...new Set([...i,...e.messages.map(ce("message"))])]:[...new Set([...e.messages.map(ce("message")),...i])]}))}}reactor(e){return t=>{var r,n,s,i,o;if("onCreate"===e){const e=null===(r=we(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===(o=this.query.tags)||void 0===o?void 0:o.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])]),Ee(this.cacheKey,e)}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class zd extends kd{constructor(e,t){const r=bd(e),n=["message","collection",r];super(new Hd(e),r,n,t),this.query=e,this.queryStreamController=new Vd(this.query,this.cacheKey,this.notifyChange.bind(this),Cl,this.paginationController),this.callback=t.bind(this),this.loadPage(!0)}setup(){var e;(null===(e=we(this.cacheKey))||void 0===e?void 0:e.data)||Ee(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:Oc,action:"onCreate"},{fn:Mc,action:"onDelete"},{fn:Pc,action:"onUpdate"},{fn:Fc,action:"onFlagged"},{fn:Nc,action:"onUnflagged"},{fn:Uc,action:"onFlagCleared"},{fn:Bc,action:"onReactionAdded"},{fn:jc,action:"onReactionRemoved"},{fn:gd(vc,"contentId","message"),action:"onUpdate"},{fn:gd(bc,"contentId","message"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:r}){var n,s;const i=null===(n=we(this.cacheKey))||void 0===n?void 0:n.data;if(!i)return;const o=this.applyFilter(null!==(s=i.data.map((e=>we(["message","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage(!1,"next"),onPrevPage:()=>this.loadPage(!1,"prev"),data:o,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=ke(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}}var Wd=Object.freeze({__proto__:null,getMessageByIds:Md,createMessage:Ud,updateMessage:Bd,editMessage:jd,deleteMessage:$d,softDeleteMessage:qd,markAsDelivered:async(e,t)=>{const r=ye();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:o}=n,a=xa(n,["userMarkers","userEntityMarkers","userFeedMarkers"]),l=r.cache&&Date.now();return r.cache&&La(Object.assign({userMarkers:Fa(s),userEntityMarkers:Na(i),userFeedMarkers:Ua(o)},a),{cachedAt:l}),!0},getReadUsers:Kd,getDeliveredUsers:Gd,flagMessage:async e=>{const t=ye();t.log("message/flag",e);const{data:r}=await t.http.post(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await Cl(r);La(e)}return Qe("message.flagged",r),!!r},unflagMessage:async e=>{const t=ye();t.log("message/unflag",e);const{data:r}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await Cl(r);La(e)}return Qe("message.unflagged",r),!!r},isMessageFlaggedByMe:async e=>{const t=ye();t.log("message/isMessageFlaggedByMe",e);const{data:r}=await t.http.get(`/api/v5/messages/${encodeURIComponent(e)}/flags`);return r.result},onMessageCreated:Oc,onMessageUpdated:Pc,onMessageDeleted:Mc,onMessageFlagged:Fc,onMessageUnflagged:Nc,onMessageFlagCleared:Uc,onMessageReactionAdded:Bc,onMessageReactionRemoved:jc,onMessageFetched:$c,getMessage:(e,t)=>Tc(e,t,"messageId",Bu,[$c,Pc,Mc,Fc,Nc,Uc,Bc,jc,gd(vc,"contentId","message"),gd(bc,"contentId","message")]),getMessages:(e,t,r)=>{const{log:n,cache:s}=ye();s||console.log(p);const i=Date.now();n(`getMessages(tmpid: ${i}) > listen`);const o=new zd(e,t),a=o.startSubscription(),l=o.getCacheKey();return a.push((()=>{Ce(l)})),()=>{n(`getMessages(tmpid: ${i}) > dispose`),a.forEach((e=>e()))}},observeMessage:(e,t,r="cache_then_server")=>{const{log:n}=ye(),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,o;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===(o=t[n])||void 0===o||o.call(t,r)}},o=[];return o.push(Pc((e=>i({data:e,loading:!1,origin:"event"},"onUpdate"))),Mc((e=>i({data:e,loading:!1,origin:"event"},"onDelete"))),gd(vc,"contentId","message")((e=>i({data:e,loading:!1,origin:"event"},"onUpdate"))),gd(bc,"contentId","message")((e=>i({data:e,loading:!1,origin:"event"},"onUpdate")))),"no_fetch"!==r&&oe(se(Bu,e),(e=>e.data&&i(e,"onFetch")),ie(r)),()=>{n(`observeMessages(tmpid: ${s}) > dispose`),o.forEach((e=>e()))}},observeMessages:(e,t)=>{const{log:r}=ye(),n=Date.now();r(`observeMessages(tmpid: ${n}) > listen`);const s=[],i=(r,n)=>{var s,i,o;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===(o=t[n])||void 0===o||o.call(t,r)}};return s.push(Oc((e=>i({data:e,loading:!1,origin:"event"},"onCreate"))),Pc((e=>i({data:e,loading:!1,origin:"event"},"onUpdate"))),Mc((e=>i({data:e,loading:!1,origin:"event"},"onDelete"))),gd(vc,"contentId","message")((e=>i({data:e,loading:!1,origin:"event"},"onCreate"))),gd(bc,"contentId","message")((e=>i({data:e,loading:!1,origin:"event"},"onCreate")))),()=>{r(`observeMessages(tmpid: ${n}) > dispose`),s.forEach((e=>e()))}},convertFromRaw:Sl,prepareMessagePayload:Cl,convertParams:kl,convertQueryParams:Al});const Yd=async(e,t=!1)=>{const r=ye(),n=await Pl(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:de(n.data.updatedAt)});return t?setTimeout((()=>{Da("subChannel",e)}),0):Se(["subChannel","get",e],s),Qe("local.message-feed.deleted",{messageFeeds:[s]}),s},Qd=e=>Ye(ye(),"onSubChannelFetched","local.message-feed.fetched",(t=>e(t.messageFeeds[0])));class Xd extends wd{async getRequest(e,t){var r;const{limit:n=h}=e,s=null!==(r=function(e){var{excludeDefaultSubChannel:t}=e,r=xa(e,["excludeDefaultSubChannel"]);const n=Object.assign({},r);return void 0!==t&&(n.excludeDefaultMessageFeed=t),n}(xa(e,["limit"])))&&void 0!==r?r:{},{channelId:i,includeDeleted:o}=s,a=xa(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({},a),{isDeleted:vl(o),options:l})});return c}}class Jd extends Td{constructor(e,t,r,n){super(e,t),this.notifyChange=r,this.preparePayload=n}async saveToMainDB(e){const t=await this.preparePayload(e),r=ye(),n=r.cache&&Date.now();r.cache&&La(t,{cachedAt:n})}appendToQueryStream(e,t,r=!1){var n,s;if(r)Ee(this.cacheKey,{data:e.messageFeeds.map((({messageFeedId:e})=>e))});else{const t=null===(n=we(this.cacheKey))||void 0===n?void 0:n.data,r=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Ee(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=we(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])]),Ee(this.cacheKey,n)}this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Zd extends kd{constructor(e,t){const r=bd(e),n=["subChannel","collection",r];super(new Xd(e),r,n,t),this.query=e,this.queryStreamController=new Jd(this.query,this.cacheKey,this.notifyChange.bind(this),Rl),this.callback=t.bind(this),this.loadPage(!0)}setup(){var e;(null===(e=we(this.cacheKey))||void 0===e?void 0:e.data)||Ee(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:Qd,action:"onCreate"},{fn:qc,action:"onCreate"},{fn:Gc,action:"onDelete"},{fn:e=>Kc((async t=>{var r;const n=null===(r=we(this.cacheKey))||void 0===r?void 0:r.data;if(!n||!n.data.includes(t.subChannelId))return;const s=ye();if("no-message-preview"!==await s.getMessagePreviewSetting(!1)){const e=nl(t.subChannelId);(null==e?void 0:e.subChannelId)===t.subChannelId&&Ee(["messagePreviewSubChannel","get",t.subChannelId],Object.assign(Object.assign({},e),{subChannelName:t.displayName,subChannelUpdatedAt:t.updatedAt}))}e(t)})),action:"onUpdate"},{fn:e=>Oc((async t=>{var r,n;const s=we(["subChannel","get",t.subChannelId]);if(!s)return;const i=null===(r=we(this.cacheKey))||void 0===r?void 0:r.data;if(!i||!i.data.includes(t.subChannelId))return;const o=ye();if("no-message-preview"===await o.getMessagePreviewSetting(!1))return;ll(t);const a=null===(n=we(["subChannel","get",t.subChannelId]))||void 0===n?void 0:n.data;a&&(al(t.subChannelId,a,{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=>gc((t=>{var r;const n=null!==(r=t.map((({feedId:e})=>we(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];0!==n.length&&e(n)})),action:"onUpdate"},{fn:gd(pc,"feedId","subChannel"),action:"onUpdate"},{fn:gd((e=>Pc((async t=>{var r;const n=ye();if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;const s=null===(r=we(this.cacheKey))||void 0===r?void 0:r.data;s&&s.data.includes(t.subChannelId)&&(cl(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:gd((e=>Mc((async t=>{var r;const n=ye(),s=await n.getMessagePreviewSetting(!1);if("no-message-preview"===s)return;const i=null===(r=we(this.cacheKey))||void 0===r?void 0:r.data;i&&i.data.includes(t.subChannelId)&&("message-preview-not-include-deleted"===s?await Pl(t.subChannelId):await cl(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:r}){var n,s;const i=null===(n=we(this.cacheKey))||void 0===n?void 0:n.data;if(!i)return;const o=this.applyFilter(null!==(s=i.data.map((e=>we(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(sl))&&void 0!==s?s:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage(!1,"next"),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:r})}applyFilter(e){let t=e;return this.query.includeDeleted||(t=ke(e,"isDeleted",!1)),t.sort(Be),t}}var eh=Object.freeze({__proto__:null,getSubChannelByIds:ql,createSubChannel:async e=>{const t=ye();t.log("user/createSubChannel",e);const r=await t.http.post("/api/v5/message-feeds",{channelId:e.channelId,name:e.displayName}),n=await Rl(r.data),s=t.cache&&Date.now();return t.cache&&La(n,{cachedAt:s}),Qe("message-feed.created",r.data),{data:n.messageFeeds[0],cachedAt:s}},updateSubChannel:async(e,t)=>{const r=ye();r.log("channel/updateSubChannel",e,t);const n=await r.http.put(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{name:t.displayName}),s=await Rl(n.data),i=r.cache&&Date.now();return r.cache&&La(s,{cachedAt:i}),Qe("message-feed.updated",n.data),{data:s.messageFeeds[0],cachedAt:i}},deleteSubChannel:Yd,hardDeleteSubChannel:async e=>{ye().log("channel/hardDeleteSubChannel",e);return await Yd(e,!0)},softDeleteSubChannel:async e=>{ye().log("channel/softDeleteSubChannel",e);return await Yd(e,!1)},onSubChannelCreated:qc,onSubChannelUpdated:Kc,onSubChannelDeleted:Gc,getSubChannel:(e,t)=>{const r=ye();let n;return Tc(e,(e=>{if(!e.data)return t(e);const r=Object.assign(Object.assign({},e),{data:sl(e.data)}),s=xa(r,["origin"]);return Ec(n,s)?void 0:(n=s,t(r))}),"subChannelId",Pl,[Qd,t=>Kc((async n=>{"no-message-preview"!==await r.getMessagePreviewSetting(!1)&&(ul(n),n.subChannelId===e&&t(n))})),Gc,gd(pc,"feedId","subChannel"),t=>gc((r=>{var n;if(!r.find((({feedId:t})=>t===e)))return;const s=null===(n=we(["subChannel","get",e]))||void 0===n?void 0:n.data;s&&t(s)})),gd((t=>Oc((async n=>{var s;if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;if(await ll(n),n.subChannelId!==e)return;const i=null===(s=we(["subChannel","get",e]))||void 0===s?void 0:s.data;i&&(al(n.subChannelId,i,{messagePreviewId:n.messageId}),t(n))}))),"subChannelId","subChannel"),gd((t=>Pc((async n=>{"no-message-preview"!==await r.getMessagePreviewSetting(!1)&&n.subChannelId===e&&(cl(n),t(n))}))),"subChannelId","subChannel"),gd((t=>Mc((async n=>{const s=await r.getMessagePreviewSetting(!1);"no-message-preview"!==s&&n.subChannelId===e&&("message-preview-include-deleted"===s&&await cl(n),"message-preview-not-include-deleted"===s&&await Pl(n.subChannelId),t(n))}))),"subChannelId","subChannel")],{forceDispatch:!0})},getSubChannels:(e,t,r)=>{const{log:n,cache:s}=ye(),i=Date.now();n(`getSubChannels(tmpid: ${i}) > listen`),s||console.log(p);const o=new Zd(e,t),a=o.startSubscription(),l=o.getCacheKey();return a.push((()=>{Ce(l)})),()=>{n(`getSubChannels(tmpid: ${i}) > dispose`),a.forEach((e=>e()))}},markReadEngineOnLoginHandler:jl,startReading:async e=>{Nl[e]=!0,0===Fl.length&&(Fl.length>0||Fl.push(xl((()=>{Ul()}))),$l(e));try{return await(async e=>{const t=ye();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:o}=r,a=Fa(o),l=Na(n),c=Ua(s),u=t.cache&&Date.now();return t.cache&&La({userEntityMarkers:l,userFeedMarkers:c,feedMarkers:i,userMarkers:a},{cachedAt:u}),Qe("local.feedMarker.fetched",{feedMarkers:i}),Qe("local.channelMarker.fetched",{userEntityMarkers:l}),Qe("local.subChannelMarker.fetched",{userFeedMarkers:c}),Qe("local.userMarker.fetched",{userMarkers:a}),!0})(e)}catch(t){return Nl[e]=!1,!1}},stopReading:e=>(Nl[e]=!1,Fl.forEach((e=>e())),Fl=[],(async e=>{const t=ye();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:o}=r,a=Fa(o),l=Na(n),c=Ua(s),u=t.cache&&Date.now();return t.cache&&La({userEntityMarkers:l,userFeedMarkers:c,feedMarkers:i,userMarkers:a},{cachedAt:u}),Qe("local.feedMarker.fetched",{feedMarkers:i}),Qe("local.channelMarker.fetched",{userEntityMarkers:l}),Qe("local.subChannelMarker.fetched",{userFeedMarkers:c}),Qe("local.userMarker.fetched",{userMarkers:a}),!0})(e))});function th(e,t){return e.map((e=>{const r=t.some((t=>function(e,t){const{userId:r}=$e();return e.communityId===t.communityId&&t.userId===r}(e,t)&&"none"!==t.communityMembership));return Object.assign(Object.assign({},e),{isJoined:r})}))}const rh=e=>{var t;return null!==(t=Object.keys(o).find((t=>e.needApprovalOnPostCreation===o[t].needApprovalOnPostCreation&&e.onlyAdminCanPost===o[t].onlyAdminCanPost)))&&void 0!==t?t:a},nh=e=>{const t=e.communities.map((e=>{var{needApprovalOnPostCreation:t,onlyAdminCanPost:r}=e,n=xa(e,["needApprovalOnPostCreation","onlyAdminCanPost"]);return Object.assign({postSetting:rh({needApprovalOnPostCreation:t,onlyAdminCanPost:r})},n)})),r=Oa(e.communityUsers),n=th(t,r);return Object.assign(Object.assign({},e),{communities:n,communityUsers:r})},sh=e=>{const{postSetting:t,storySetting:r}=e,n=xa(e,["postSetting","storySetting"]);return Object.assign(Object.assign(Object.assign({},n),t?o[t]:void 0),{allowCommentInStory:!1!==(null==r?void 0:r.enableComment)})},ih=async e=>{const t=ye();t.log("community/getCommunities",e);const{data:r}=await t.http.get("/api/v3/communities/list",{params:{communityIds:e}}),n=nh(r),s=t.cache&&Date.now();return t.cache&&La(n,{cachedAt:s}),{data:n.communities,cachedAt:s}};ih.locally=e=>{var t;const r=ye();if(r.log("community/getCommunities.locally",e),!r.cache)return;const n=e.map((e=>we(["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 oh=async e=>{const t=ye();t.log("community/getCommunity",e);const{data:r}=await t.http.get(`/api/v3/communities/${e}`),n=nh(r),s=t.cache&&Date.now();t.cache&&La(n,{cachedAt:s});const{communities:i}=n;return{data:i.find((t=>t.communityId===e)),cachedAt:s}};oh.locally=e=>{const t=ye();if(t.log("community/getCommunity.locally",e),!t.cache)return;const r=we(["community","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const ah=async e=>{const t=ye();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=nh(n),{communities:i}=s,o=t.cache&&Date.now();if(t.cache){La(s,{cachedAt:o});Ee(["community","top-trending",{params:{options:{limit:r}}}],{communities:i.map(ce("community"))})}return{data:i,cachedAt:o}};ah.locally=e=>{var t,r;const n=ye();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:o,cachedAt:a}=null!==(t=we(i))&&void 0!==t?t:{};if(!(null==o?void 0:o.communities.length))return;const l=o.communities.map((e=>we(["community","get",e]))).filter(Boolean).map((({data:e})=>e));return l.length===(null===(r=null==o?void 0:o.communities)||void 0===r?void 0:r.length)?{data:l,cachedAt:a}:void 0};const lh=(e,t)=>{const r=ye();return Ye(r,e,e,(e=>{const n=nh(e);if(r.cache){La(n);const e=we(["community","get",n.communities[0].communityId]);t(e.data)}else t(n.communities[0])}))},ch=e=>lh("community.created",e),uh=e=>lh("community.updated",e),dh=e=>lh("community.deleted",e);function hh(e,t,r){return!!e.permissions.some((e=>e===r))||t.users.find((t=>t.userId===e.userId)).permissions.some((e=>e===r))}function fh(e,t){return"community.joined"===e||"community.left"===e?t.communityUsers[0]:"community.userRemoved"===e?t.communityUsers.filter((e=>"none"===e.communityMembership))[0]:"community.userBanned"===e?t.communityUsers.filter((e=>"banned"===e.communityMembership))[0]:"community.userUnbanned"===e?t.communityUsers.filter((e=>!hh(e,t,"BAN_COMMUNITY_USER")))[0]:t.communityUsers.filter((e=>!hh(e,t,"ADD_COMMUNITY_USER")))[0]}const ph=(e,t)=>{const r=ye();return Ye(r,e,e,(n=>{const s=nh(n),{communities:i,communityUsers:o}=s,a=th(i,o);if(s.communities=a,r.cache){La(s);const r=we(["community","get",s.communities[0].communityId]),n=we(["communityUsers","get",ce("communityUsers")(fh(e,s))]);t(r.data,n.data)}else t(s.communities[0],fh(e,s))}))},gh=e=>ph("community.userAdded",e),mh=e=>ph("community.userRemoved",e),yh=e=>ph("community.userBanned",e),vh=e=>ph("community.userChanged",e),bh=e=>ph("community.userUnbanned",e),wh=e=>ph("community.roleAdded",e),Eh=e=>ph("community.roleRemoved",e),Th=e=>ph("community.joined",e),Sh=e=>ph("community.left",e),Ch=async e=>{const t=ye();t.log("channel/queryCommunities",e);const r=null!=e?e:{},{page:n,limit:s=10}=r,i=xa(r,["page","limit"]),o=null!=i?i:{},{displayName:a,membership:l,includeDeleted:c}=o,u=xa(o,["displayName","membership","includeDeleted"]),d=n?{token:n}:s?{limit:s}:void 0,{data:h}=await t.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},u),{isDeleted:vl(c),keyword:a,filter:l,options:d})}),{paging:f}=h,p=xa(h,["paging"]),g=nh(p),{communities:m}=g,y=t.cache&&Date.now();if(t.cache){La(g,{cachedAt:y});const e=["community","query",Object.assign(Object.assign({},i),{options:d})];Ee(e,{communities:m.map(ce("community")),paging:f})}return{data:m,cachedAt:y,paging:f}},kh=async e=>{const t=ye();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=nh(n),{communities:i}=s,o=t.cache&&Date.now();return t.cache&&La(s,{cachedAt:o}),{data:i,cachedAt:o}},Ah=(e,t,r)=>{let n=e;n=ke(n,"displayName",t.displayName),t.includeDeleted||(n=ke(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=Le(n,t.membership,r));const s=t.sortBy||"lastCreated";return"lastCreated"!==s&&"firstCreated"!==s||(n=n.sort("lastCreated"===s?Fe:Me)),"displayName"===s&&(n=n.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Oe)),n},_h=async e=>{const t=ye();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=nh(n),{communities:i}=s,o=t.cache&&Date.now();return t.cache&&La(s,{cachedAt:o}),{data:i,cachedAt:o}};var Ih=Object.freeze({__proto__:null,addRoles:async(e,t,r)=>{const n=ye();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=Pa(s,"communityUsers");n.cache&&La(i);const{communityUsers:o}=i;return!!o.find((r=>r.communityId===e&&t.some((e=>r.roles.includes(e)))))},removeRoles:async(e,t,r)=>{const n=ye();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=Pa(s,"communityUsers");n.cache&&La(i);const{communityUsers:o}=i;return!!o.find((r=>r.communityId===e&&!t.some((e=>r.roles.includes(e)))))},banMembers:async(e,t)=>{const r=ye();r.log("community/banMembers",{userIds:t,communityId:e});const{data:n}=await r.http.put(`/api/v3/communities/${e}/users/ban`,{userIds:t}),s=Pa(n,"communityUsers"),i=r.cache&&Date.now();r.cache&&La(s,{cachedAt:i});const{communityUsers:o}=s;return{data:o.filter((e=>t.includes(e.userId))),cachedAt:i}},unbanMembers:async(e,t)=>{const r=ye();r.log("community/unbanMembers",{userIds:t,communityId:e});const{data:n}=await r.http.put(`/api/v3/communities/${e}/users/unban`,{userIds:t}),s=Pa(n,"communityUsers"),i=r.cache&&Date.now();r.cache&&La(s,{cachedAt:i});const{communityUsers:o}=s;return{data:o.filter((e=>t.includes(e.userId))),cachedAt:i}}});const Rh=async e=>{const t=ye();t.log("community/queryCommunityMembers",e);const r=null!=e?e:{},{page:n,limit:s}=r,i=xa(r,["page","limit"]),o=n?{token:n}:s?{limit:s}:void 0,{data:a}=await t.http.get(`/api/v3/communities/${i.communityId}/users`,{params:Object.assign(Object.assign({},i),{options:o})}),{paging:l}=a,c=xa(a,["paging"]),u=Pa(c,"communityUsers"),{communityUsers:d}=u,h=t.cache&&Date.now();if(t.cache){La(u,{cachedAt:h});const e=["communityUsers","query",Object.assign(Object.assign({},i),{options:o})];Ee(e,{communityUsers:d.map((({communityId:e,userId:t})=>ce("communityUsers")({communityId:e,userId:t}))),paging:l})}return{data:d,cachedAt:h,paging:l}};Rh.locally=e=>{var t,r;const n=ye();if(n.log("community/queryCommunityMembers",e),!n.cache)return;const s=null!=e?e:{},{page:i,limit:o}=s,a=xa(s,["page","limit"]),l=i?{token:i}:o?{limit:o}:void 0,c=["communityUsers","query",Object.assign(Object.assign({},a),{options:l})],{data:u,cachedAt:d}=null!==(t=we(c))&&void 0!==t?t:{};if(!(null==u?void 0:u.communityUsers.length))return;const h=u.communityUsers.map((e=>we(["communityUsers","get",e]))).filter(Boolean).map((({data:e})=>e)),{paging:f}=u;return h.length===(null===(r=null==u?void 0:u.communityUsers)||void 0===r?void 0:r.length)?{data:h,cachedAt:d,paging:f}:void 0};const Lh=(e,t)=>{let r=_e(e,"roles",t.roles);t.memberships&&(r=r.filter((({communityMembership:e})=>t.memberships.includes(e)))),t.search&&(r=xe(r,t.search));const n=t.sortBy?t.sortBy:"lastCreated";return r=r.sort("lastCreated"===n?Fe:Me),r};var Dh=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const r=ye();r.log("community/moderation/addMembers",e,t);const{data:n}=await r.http.post(`/api/v3/communities/${e}/users`,{communityId:e,userIds:t});Qe("community.userAdded",n);const s=Pa(n,"communityUsers");r.cache&&La(s);const{communityUsers:i}=s;return!!i.find((t=>t.communityId===e&&"member"===t.communityMembership))},removeMembers:async(e,t)=>{const r=ye();r.log("community/moderation/removeMembers",e,t);const{data:n}=await r.http.delete(`/api/v3/communities/${e}/users`,{data:{communityId:e,userIds:t}});Qe("community.userRemoved",n);const s=Pa(n,"communityUsers");r.cache&&La(s);const{communityUsers:i}=s;return!!i.find((t=>t.communityId===e&&"member"!==t.communityMembership))},applyFilter:Lh,getMembers:(e,t,r)=>{const{log:n,cache:s}=ye();s||console.log(p);const i=Date.now();n(`getMembers(tmpid: ${i}) > listen`);const{limit:o}=e,a=xa(e,["limit"]),l=null!=o?o:h,{policy:c=f}=null!=r?r:{},u=[],d=["communityUsers","collection",a],g=["communityUsers","collection",{communityId:e.communityId}],m=(r,n=!1)=>{var s,i;const o=null!==(s=r.data.map((e=>we(["communityUsers","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==s?s:[];t({onNextPage:v,data:n?Lh(o,e):o,hasNextPage:!!(null===(i=r.params)||void 0===i?void 0:i.page),loading:r.loading,error:r.error})},y=t=>(t,r)=>{var n;if(e.communityId!==r.communityId)return;const s=null===(n=we(d))||void 0===n?void 0:n.data;if(!s)return;const i=ce("communityUsers")({communityId:e.communityId,userId:r.userId});s.data=[...new Set([i,...s.data])],Ee(d,s),Ee(g,s),m(s,!0)},v=(e=!1)=>{var t,r;const n=null===(t=we(d))||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=se(Rh,Object.assign(Object.assign({},a),{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(ce("communityUsers"))])]),Ee(d,i),Ee(g,i),m(i)}),ie(c))};return u.push(Sh(y()),Th(y()),yh(y()),bh(y()),vh(y()),wh(y()),Eh(y())),v(!0),()=>{n(`getMembers(tmpid: ${i}) > dispose`),u.forEach((e=>e()))}},onCommunityUserAdded:gh,onCommunityUserRemoved:mh,onCommunityUserBanned:yh,onCommunityUserChanged:vh,onCommunityUserUnbanned:bh,onCommunityUserRoleAdded:wh,onCommunityUserRoleRemoved:Eh,onCommunityJoined:Th,onCommunityLeft:Sh}),xh=Object.freeze({__proto__:null,Moderation:Ih,Membership:Dh,getCommunityByIds:ih,createCommunity:async e=>{const t=ye();t.log("user/createCommunity",e);const{data:r}=await t.http.post("/api/v3/communities/",sh(e));Qe("community.created",r);const n=nh(r),s=t.cache&&Date.now();t.cache&&La(n,{cachedAt:s});const{communities:i}=n;return{data:i[0],cachedAt:s}},updateCommunity:async(e,t)=>{const r=ye();r.log("community/updateCommunity",e,t);const{data:n}=await r.http.put(`/api/v3/communities/${e}`,sh(t));Qe("community.updated",n);const s=nh(n),i=r.cache&&Date.now();r.cache&&La(s,{cachedAt:i});const{communities:o}=s;return{data:o.find((t=>t.communityId===e)),cachedAt:i}},deleteCommunity:async e=>{const t=ye();t.log("community/deleteCommunity",e),await t.http.delete(`/api/v3/communities/${e}`);const r=await oh(e);return Qe("community.deleted",{communities:[r.data],categories:[],communityUsers:[],feeds:[],files:[],users:[]}),r.data},joinCommunity:async e=>{const t=ye();t.log("community/joinCommunity",e);const{data:r}=await t.http.post(`/api/v3/communities/${e}/join`);Qe("community.joined",r);const n=nh(r),s=t.cache&&Date.now();t.cache&&La(n,{cachedAt:s});const{communityUsers:i}=n;return!!i.find((t=>t.communityId===e&&"member"===t.communityMembership))},leaveCommunity:async e=>{const t=ye();t.log("community/leaveCommunity",e);const{data:r}=await t.http.delete(`/api/v3/communities/${e}/leave`);Qe("community.left",r);const n=nh(r),s=t.cache&&Date.now();t.cache&&La(n,{cachedAt:s});const{communityUsers:i}=n;return!!i.find((t=>t.communityId===e&&"member"!==t.communityMembership))},getTopTrendingCommunities:ah,onCommunityCreated:ch,onCommunityUpdated:uh,onCommunityDeleted:dh,observeCommunity:(e,t)=>{const{log:r}=ye(),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)},o=[];return o.push(uh((e=>i({data:e,loading:!1,origin:"event"},"onUpdate"))),dh((e=>i({data:e,loading:!1,origin:"event"},"onDelete"))),Th((e=>i({data:e,loading:!1,origin:"event"},"onJoin"))),Sh((e=>i({data:e,loading:!1,origin:"event"},"onLeft"))),gh((e=>i({data:e,loading:!1,origin:"event"},"onUserAdded"))),mh((e=>i({data:e,loading:!1,origin:"event"},"onUserRemoved"))),yh((e=>i({data:e,loading:!1,origin:"event"},"onUserBanned"))),bh((e=>i({data:e,loading:!1,origin:"event"},"onUserUnbanned")))),oe(se(oh,e),(e=>(e.data||e.error)&&s(e,"onFetch"))),()=>{r(`observeCommunity(tmpid: ${n}) > dispose`),o.forEach((e=>e()))}},getCommunities:(e,t,r)=>{const{log:n,cache:s,userId:i}=ye();s||console.log(p);const o=Date.now();n(`getCommunities(tmpid: ${o}) > listen`);const{limit:a}=e,l=xa(e,["limit"]),c=null!=a?a:h,{policy:u=f}=null!=r?r:{},d=[],g=["community","collection",l],m=r=>{var n,s;let o=null!==(n=r.data.map((e=>we(["community","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];o=Ae(o,"displayName",e.displayName),e.includeDeleted||(o=ke(o,"isDeleted",!1)),e.categoryId&&(o=o.filter((t=>{var r;return null===(r=t.categoryIds)||void 0===r?void 0:r.includes(e.categoryId)}))),e.tags&&(o=o.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&&(o=Le(o,e.membership,i));const a=e.sortBy||"lastCreated";"lastCreated"!==a&&"firstCreated"!==a||(o=o.sort("lastCreated"===a?Fe:Me)),"displayName"===a&&(o=o.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Oe)),t({onNextPage:b,data:o,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=we(g))||void 0===t?void 0:t.data;r&&(r.data=[...new Set([e.communityId,...r.data])],Ee(g,r),m(r))},b=(e=!1)=>{var t,r;const n=null===(t=we(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=se(Ch,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 o={loading:n,error:r,params:{page:null==i?void 0:i.next},data:s};t&&(o.data=e?t.map(ce("community")):[...new Set([...s,...t.map(ce("community"))])]),Ee(g,o),m(o)}),ie(u,v))};return d.push(ch(y()),dh(y()),uh(y()),Th(y()),Sh(y()),vh(y())),b(!0),d.push((()=>Ce(g))),()=>{n(`getCommunities(tmpid: ${o}) > dispose`),d.forEach((e=>e()))}},getCommunity:(e,t)=>Tc(e,t,"communityId",oh,[uh,dh,Th,Sh,yh,bh,vh]),getTrendingCommunities:(e,t,r)=>{const{log:n,cache:s,userId:i}=ye();s||console.log(p);const o=Date.now();n(`getTrendingCommunities(tmpid: ${o}) > listen`);const{limit:a}=e,l=null!=a?a:h,{policy:c=f}=null!=r?r:{},u=[],d=["community","top-trending",{params:{options:{limit:l}}}],g=(r,n=!1)=>{var s,o;const a=null!==(s=r.data.map((e=>we(["community","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==s?s:[];t({onNextPage:m,data:n?Ah(a,e,i):a,hasNextPage:!!(null===(o=r.params)||void 0===o?void 0:o.page),loading:r.loading,error:r.error})},m=(t=!1)=>{var r,n;const s=null===(r=we(d))||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 o=se(kh,e);oe(o,(({data:t,error:r,loading:n})=>{const s={loading:n,error:r,params:e,data:i};t&&(s.data=[...new Set([...i,...t.map(ce("community"))])]),Ee(d,s),g(s)}),ie(c,v))};return u.push(vh((e=>{var t;const r=null===(t=we(d))||void 0===t?void 0:t.data;r&&(r.data=[...new Set([e.communityId,...r.data])],Ee(d,r),g(r))}))),m(!0),u.push((()=>Ce(d))),()=>{n(`getTrendingCommunities(tmpid: ${o}) > dispose`),u.forEach((e=>e()))}},getRecommendedCommunities:(e,t,r)=>{const{log:n,cache:s,userId:i}=ye();s||console.log(p);const o=Date.now();n(`getRecommendedCommunities(tmpid: ${o}) > listen`);const{limit:a}=e;xa(e,["limit"]);const l=null!=a?a:h,{policy:c=f}=null!=r?r:{},u=[],d=["community","recommended",{params:{options:{limit:l}}}],g=(r,n=!1)=>{var s,o;const a=null!==(s=r.data.map((e=>we(["community","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==s?s:[];t({onNextPage:m,data:n?Ah(a,e,i):a,hasNextPage:!!(null===(o=r.params)||void 0===o?void 0:o.page),loading:r.loading,error:r.error})},m=(t=!1)=>{var r,n;const s=null===(r=we(d))||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 o=se(_h,e);oe(o,(({data:t,error:r,loading:n})=>{const s={loading:n,error:r,params:e,data:i};t&&(s.data=[...new Set([...i,...t.map(ce("community"))])]),Ee(d,s),g(s)}),ie(c,v))};return u.push(vh((e=>{var t;const r=null===(t=we(d))||void 0===t?void 0:t.data;r&&(r.data=[...new Set([e.communityId,...r.data])],Ee(d,r),g(r))}))),m(!0),u.push((()=>Ce(d))),()=>{n(`getRecommendedCommunities(tmpid: ${o}) > dispose`),u.forEach((e=>e()))}}});const Oh=async e=>{const t=ye();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&&La(r,{cachedAt:n});const{categories:s}=r;return{data:el.category(s.find((t=>t.categoryId===e))),cachedAt:n}};Oh.locally=e=>{const t=ye();if(t.log("category/getCategory.locally",e),!t.cache)return;const r=we(["category","get",e]);return r?{data:el.category(r.data),cachedAt:r.cachedAt}:void 0};const Ph=async e=>{const t=ye();t.log("category/queryCategories",e);const r=null!=e?e:{},{page:n,limit:s,includeDeleted:i}=r,o=xa(r,["page","limit","includeDeleted"]),a=n?{token:n}:s?{limit:s}:void 0,{data:l}=await t.http.get("/api/v3/community-categories",{params:Object.assign(Object.assign({},o),{isDeleted:vl(i),options:a})}),{paging:c}=l,u=xa(l,["paging"]),{categories:d}=u,h=t.cache&&Date.now();if(t.cache){La(u,{cachedAt:h});const e=["category","query",Object.assign(Object.assign({},o),{includeDeleted:i,options:a})];Ee(e,{categories:d.map(ce("category")),paging:c})}return{data:d,cachedAt:h,paging:c}};Ph.locally=e=>{var t,r;const n=ye();if(n.log("category/queryCategories.locally",e),!n.cache)return;const s=null!=e?e:{},{page:i,limit:o=10}=s,a=xa(s,["page","limit"]),l=i?{token:i}:o?{limit:o}:void 0,c=["category","query",Object.assign(Object.assign({},a),{options:l})],{data:u,cachedAt:d}=null!==(t=we(c))&&void 0!==t?t:{};if(!(null==u?void 0:u.categories.length))return;const h=u.categories.map((e=>we(["category","get",e]))).filter(Boolean).map((({data:e})=>e)),{paging:f}=u;return h.length===(null===(r=null==u?void 0:u.categories)||void 0===r?void 0:r.length)?{data:h,cachedAt:d,paging:f}:void 0};var Mh=Object.freeze({__proto__:null,getCategory:Oh,getCategories:(e,t,r)=>{const{log:n,cache:s}=ye();s||console.log(p);const i=Date.now();n(`getCategories(tmpid: ${i}) > listen`);const{limit:o}=e,a=xa(e,["limit"]),l=null!=o?o:h,{policy:c=f}=null!=r?r:{},u=[],d=["category","collection",{}],g=(r=!1)=>{var n,s;const i=null===(n=we(d))||void 0===n?void 0:n.data,o=null!==(s=null==i?void 0:i.data)&&void 0!==s?s:[];if(!r&&o.length>0&&!(null==i?void 0:i.params.page))return;const u=se(Ph,Object.assign(Object.assign({},a),{limit:r?l:void 0,page:r||null==i?void 0:i.params.page}));oe(u,(({data:r,error:n,loading:s,paging:i})=>{const a={loading:s,error:n,params:{page:null==i?void 0:i.next},data:o};r&&(a.data=[...new Set([...o,...r.map(ce("category"))])]),Ee(d,a),(r=>{var n,s;let i=null!==(n=r.data.map((e=>we(["category","get",e]))).filter(Boolean).map((({data:e})=>el.category(e))))&&void 0!==n?n:[];switch(e.includeDeleted||(i=ke(i,"isDeleted",!1)),e.sortBy){case"firstCreated":i=i.sort(Me);break;case"lastCreated":i=i.sort(Fe);break;default:i=i.sort(Pe)}t({onNextPage:g,data:i,hasNextPage:!!(null===(s=r.params)||void 0===s?void 0:s.page),loading:r.loading,error:r.error})})(a)}),ie(c))};return u.push((()=>{})),g(!0),()=>{n(`getCategories(tmpid: ${i}) > dispose`),u.forEach((e=>e()))}}});const Fh=async e=>{const t=ye();t.log("feed/queryGlobalFeed",e);const r=null!=e?e:{},{useCustomRanking:n,page:s,queryToken:i}=r,o=xa(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 a=i?{token:i}:s?{token:Q(s,"skiplimit")}:void 0,{data:l}=await t.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},o),{options:a})}),{paging:c}=l,u=xa(l,["paging"]),d=Pa(u,"communityUsers"),{posts:h}=d,f=t.cache&&Date.now();if(t.cache){La(d);const e=["globalFeed","query",Object.assign(Object.assign({},o),{options:Object.assign({},s)})];Ee(e,{posts:h.map(ce("post")),paging:c})}const p=X(c.next),g=X(c.previous);return{data:h.map(el.post),cachedAt:f,prevPage:g,nextPage:p,paging:c}};Fh.locally=e=>{var t,r;const n=ye();if(n.log("post/queryGlobalFeed.locally",e),!n.cache)return;const s=null!=e?e:{},{page:i}=s,o=xa(s,["page"]),a=["globalFeed","query",Object.assign(Object.assign({},o),{options:Object.assign({},i)})],{data:l,cachedAt:c}=null!==(t=we(a))&&void 0!==t?t:{};if(!(null==l?void 0:l.posts.length))return;const u=l.posts.map((e=>we(["post","get",e]))).filter(Boolean).map((({data:e})=>e)).map(el.post),{paging:d}=l,h=X(null==l?void 0:l.paging.previous),f=X(null==l?void 0:l.paging.next);return u.length===(null===(r=null==l?void 0:l.posts)||void 0===r?void 0:r.length)?{data:u,cachedAt:c,prevPage:h,nextPage:f,paging:d}:void 0};const Nh=async e=>{const t=ye();t.log("feed/getCustomRankingGlobalFeed",e);const r=null!=e?e:{},{page:n,queryToken:s,limit:i}=r,o=xa(r,["page","queryToken","limit"]),a=s?{token:s}:n?{token:Q(n,"skiplimit")}:void 0,{data:l}=await t.http.get("/api/v5/me/global-feeds",{params:Object.assign(Object.assign({},o),{limit:s?void 0:i,options:a})}),{paging:c}=l,u=xa(l,["paging"]),d=Pa(u,"communityUsers"),{posts:h}=d,f=t.cache&&Date.now();if(t.cache){La(d);const e=["customGlobalFeed","query",Object.assign(Object.assign({},o),{options:Object.assign({},n)})];Ee(e,{posts:h.map(ce("post")),paging:c})}const p=X(c.next),g=X(c.previous);return{data:h.map(el.post),cachedAt:f,prevPage:g,nextPage:p,paging:c}};Nh.locally=e=>{var t,r;const n=ye();if(n.log("post/getCustomRankingGlobalFeed.locally",e),!n.cache)return;const s=null!=e?e:{},{page:i}=s,o=xa(s,["page"]),a=["customGlobalFeed","query",Object.assign(Object.assign({},o),{options:Object.assign({},i)})],{data:l,cachedAt:c}=null!==(t=we(a))&&void 0!==t?t:{};if(!(null==l?void 0:l.posts.length))return;const u=l.posts.map((e=>we(["post","get",e]))).filter(Boolean).map((({data:e})=>e)),d=X(null==l?void 0:l.paging.previous),h=X(null==l?void 0:l.paging.next),{paging:f}=l;return u.length===(null===(r=null==l?void 0:l.posts)||void 0===r?void 0:r.length)?{data:u.map(el.post),cachedAt:c,prevPage:d,nextPage:h,paging:f}:void 0};var Uh=Object.freeze({__proto__:null,queryGlobalFeed:Fh,getCustomRankingGlobalFeed:Nh});const Bh=async e=>{const t=ye();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=>{S(null==t?void 0:t.code)&&Da("post",e)})),t}const s=Pa(n,"communityUsers"),i=t.cache&&Date.now();return t.cache&&La(s,{cachedAt:i}),{data:s.posts.map(el.post),cachedAt:i}};Bh.locally=e=>{var t;const r=ye();if(r.log("post/getPostByIds.locally",e),!r.cache)return;const n=e.map((e=>we(["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(el.post),cachedAt:i.cachedAt}};const jh=async(e,t=!1)=>{var r;const n=ye(),s=await ju(e);if(await n.http.delete(`/api/v4/posts/${encodeURIComponent(e)}`,{params:{postId:e,permanent:t}}),"community"===s.data.targetType){const e=await oh(s.data.targetId),t=(null!==(r=be(["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));Qe("community.updated",{communities:[e.data],categories:[],communityUsers:t,feeds:[],files:[],users:[]})}const i=Object.assign(Object.assign({},s.data),{isDeleted:!0});return Qe("post.deleted",{posts:[i],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[]}),t?setTimeout((()=>{Da("post",e)}),0):Se(["post","get",e],{isDeleted:!0}),el.post(i)},$h=async e=>{const t=ye();t.log("post/queryPosts",e);const{page:r,limit:n=10,includeDeleted:s}=e,i=xa(e,["page","limit","includeDeleted"]),{dataTypes:o,matchingOnlyParentPost:a}=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:vl(s),matchingOnlyParentPost:null!=a?a:!(null==o?void 0:o.length),options:l})}),{paging:u}=c,d=xa(c,["paging"]),h=Pa(d,"communityUsers"),{posts:f}=d,p=t.cache&&Date.now();if(t.cache){La(h,{cachedAt:p});const e=["post","query",Object.assign(Object.assign({},i),{options:l})];Ee(e,{posts:f.map(ce("post")),paging:u})}return{data:f.map(el.post),cachedAt:p,paging:u}};var qh=Object.freeze({__proto__:null,getPostByIds:Bh,createPost:async e=>{const t=ye();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);Qe("post.created",r);const n=Pa(r,"communityUsers"),s=t.cache&&Date.now();t.cache&&La(n,{cachedAt:s});const{posts:i}=n;return{data:el.post(i[0]),cachedAt:s}},updatePost:async(e,t)=>{const r=ye();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=Pa(n,"communityUsers"),i=r.cache&&Date.now();r.cache&&La(s,{cachedAt:i}),Qe("post.updated",s);const{posts:o}=s;return{data:el.post(o.find((t=>t.postId===e))),cachedAt:i}},editPost:async(e,t)=>{const r=ye();r.log("user/editPost",t);const{data:n}=await r.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,t),s=Pa(n,"communityUsers"),i=r.cache&&Date.now();r.cache&&La(s,{cachedAt:i}),Qe("post.updated",s);const{posts:o}=s;return{data:el.post(o.find((t=>t.postId===e))),cachedAt:i}},deletePost:jh,softDeletePost:async e=>{ye().log("post/softDeletePost",e);const t=await jh(e,!1);return el.post(t)},hardDeletePost:async e=>{ye().log("post/hardDeletePost",e);const t=await jh(e,!0);return el.post(t)},approvePost:async e=>{const t=ye();t.log("post/approvePost",e);const{data:r}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/approve`);Qe("post.approved",r),"community"===r.posts[0].targetType&&Qe("community.updated",r);const n=Pa(r,"communityUsers"),s=t.cache&&Date.now();return t.cache&&La(n,{cachedAt:s}),{data:el.post(n.posts.find((t=>t.postId===e))),cachedAt:s}},declinePost:async e=>{const t=ye();t.log("post/declinePost",e);const{data:r}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/decline`);"community"===r.posts[0].targetType&&Qe("community.updated",r),Qe("post.declined",r);const n=Pa(r,"communityUsers"),s=t.cache&&Date.now();return t.cache&&La(n,{cachedAt:s}),{data:el.post(r.posts.find((t=>t.postId===e))),cachedAt:s}},flagPost:async e=>{const t=ye();t.log("post/flagPost",e);const{data:r}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/flag`);return t.cache&&La(Pa(r,"communityUsers")),Qe("post.flagged",r),!!r},unflagPost:async e=>{const t=ye();t.log("post/unflagPost",e);const{data:r}=await t.http.delete(`/api/v3/posts/${encodeURIComponent(e)}/unflag`);return t.cache&&La(Pa(r,"communityUsers")),Qe("post.unflagged",r),!!r},isPostFlaggedByMe:async e=>{const t=ye();t.log("post/isPostFlaggedByMe",e);const{data:{result:r}}=await t.http.get(`/api/v3/posts/${e}/isflagbyme`);return r},onPostCreated:Vu,onPostUpdated:zu,onPostDeleted:Wu,onPostApproved:Yu,onPostDeclined:Qu,onPostFlagged:Xu,onPostUnflagged:Ju,onPostReactionAdded:Zu,onPostReactionRemoved:ed,observePosts:(e,t)=>{const{log:r}=ye(),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(el.post(r));null===(s=t.onEvent)||void 0===s||s.call(t,n,el.post(r)),null===(i=t[n])||void 0===i||i.call(t,el.post(r))}};return s.push(Vu((e=>i(e,"onCreate"))),zu((e=>i(e,"onUpdate"))),Wu((e=>i(e,"onDelete"))),Yu((e=>i(e,"onApproved"))),Qu((e=>i(e,"onDeclined"))),Xu((e=>i(e,"onFlagged"))),Ju((e=>i(e,"onUnflagged"))),Zu((e=>i(e,"onReactionAdded"))),ed((e=>i(e,"onReactionRemoved")))),()=>{r(`observePosts(tmpid: ${n}) > dispose`),s.forEach((e=>e()))}},observePost:(e,t,r="cache_then_server")=>{const{log:n}=ye(),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)},o=(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&&el.post(t.data)}),r)},a=[];return a.push(zu((e=>o({data:e,loading:!1,origin:"event"},"onUpdate"))),Wu((e=>o({data:e,loading:!1,origin:"event"},"onDelete"))),Yu((e=>o({data:e,loading:!1,origin:"event"},"onApproved"))),Qu((e=>o({data:e,loading:!1,origin:"event"},"onDeclined"))),Xu((e=>o({data:e,loading:!1,origin:"event"},"onFlagged"))),Ju((e=>o({data:e,loading:!1,origin:"event"},"onUnflagged"))),Zu((e=>o({data:e,loading:!1,origin:"event"},"onReactionAdded"))),ed((e=>o({data:e,loading:!1,origin:"event"},"onReactionRemoved")))),oe(se(ju,e),(e=>(e.data||e.error)&&i(Object.assign(Object.assign({},e),{data:e.data&&el.post(e.data)}),"onFetch")),ie(r)),()=>{n(`observePosts(tmpid: ${s}) > dispose`),a.forEach((e=>e()))}},getPost:(e,t)=>Tc(e,t,"postId",ju,[Yu,Qu,t=>Wu((r=>{var n;let s=r;if(r.parentPostId===e&&r.isDeleted){const e=null===(n=we(["post","get",r.parentPostId]))||void 0===n?void 0:n.data;e&&(e.children=e.children.filter((e=>e!==r.postId)),Ee(["post","get",e.postId],e),s=e)}t(s)})),Xu,Zu,ed,Ju,zu]),getPosts:(e,t,r)=>{const{log:n,cache:s}=ye();s||console.log(p);const i=Date.now();n(`getPosts(tmpid: ${i}) > listen`);const{limit:o}=e,a=xa(e,["limit"]),l=null!=o?o:h,{policy:c=f}=null!=r?r:{},u=[],d=["post","collection",{targetId:e.targetId,targetType:e.targetType}],g=r=>{var n,s,i;let o=null!==(n=r.data.map((e=>we(["post","get",e]))).filter(Boolean).map((({data:e})=>el.post(e))))&&void 0!==n?n:[];const a=e.sortBy?e.sortBy:"lastCreated";o=o.sort("lastCreated"===a?Fe:Me),e.includeDeleted||(o=ke(o,"isDeleted",!1)),e.tags&&(o=o.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&&(o=Re(o,e.feedType)),(null===(s=e.dataTypes)||void 0===s?void 0:s.length)&&(o=De(o,e.dataTypes)),t({onNextPage:y,data:o,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=we(d))||void 0===n?void 0:n.data;if(i){if(r.parentPostId&&r.isDeleted){const t=null===(s=we(["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)),Ee(["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])],Ee(d,i),g(i)}},y=(e=!1)=>{var t,r,n;const s=null===(t=we(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 o=se($h,Object.assign(Object.assign({},a),{limit:e?l:void 0,page:e||null==s?void 0:s.params.page}));oe(o,(({data:t,error:r,loading:n,paging:s})=>{const o={loading:n,error:r,params:{page:null==s?void 0:s.next},data:i};t&&(o.data=e?t.map(ce("post")):[...new Set([...i,...t.map(ce("post"))])]),Ee(d,o),g(o)}),ie(c,v))};return u.push(Vu(m("onCreate")),Yu(m("onApproved")),Qu(m("onDeclined")),Wu(m("onDelete")),zu(m("onUpdate")),Xu(m("onFlagged")),Ju(m("onUnflagged")),Zu(m("onReactionAdded")),ed(m("onReactionRemoved"))),y(!0),u.push((()=>Ce(d))),()=>{n(`getPosts(tmpid: ${i}) > dispose`),u.forEach((e=>e()))}}});const Kh=async e=>{const t=ye();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=>{S(null==t?void 0:t.code)&&Da("comment",e)})),t}const s=t.cache&&Date.now();return t.cache&&La(n,{cachedAt:s}),{data:n.comments.map((e=>el.comment(e))),cachedAt:s}};Kh.locally=e=>{var t;const r=ye();if(r.log("comment/getCommentByIds.locally",e),!r.cache)return;const n=e.map((e=>we(["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=>el.comment(e))),cachedAt:i.cachedAt}};const Gh=async(e,t=!1)=>{const r=ye(),n=await $u(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}),i=await ju(n.data.referenceId);return Qe("post.updated",{posts:[i.data],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[]}),Qe("comment.deleted",{comments:[s],commentChildren:[],files:[],users:[],communityUsers:[]}),t?He((()=>Da("comment",e))):Se(["comment","get",e],{isDeleted:!0}),s},Hh=async e=>{const t=ye();let r;t.log("comment/getComment",e),Ol("comment",e);try{r=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw S(null==t?void 0:t.code)&&Da("comment",e),t}const n=t.cache&&Date.now();t.cache&&La(r,{cachedAt:n});const{comments:s}=r;return{data:s.find((t=>t.commentId===e)),cachedAt:n}};Hh.locally=e=>{const t=ye();if(t.log("comment/getComment.locally",e),!t.cache)return;const r=we(["comment","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const Vh=async e=>{const t=ye();t.log("comment/queryComments",e);const{limit:r=10,includeDeleted:n}=e,s=xa(e,["limit","includeDeleted"]),i={type:s.sortBy||e.limit?"pagination":void 0,limit:e.limit,token:e.page},{data:o}=await t.http.get("/api/v3/comments",{params:Object.assign(Object.assign({},s),{isDeleted:vl(n),options:i})}),{paging:a}=o,l=xa(o,["paging"]),{comments:c}=l,u=t.cache&&Date.now();if(t.cache){La(l,{cachedAt:u});const e=["comment","query",Object.assign(Object.assign({},s),{options:{limit:r}})];Ee(e,{comments:c.map(ce("comment")),paging:a})}return{data:c,cachedAt:u,paging:a}};var zh=Object.freeze({__proto__:null,getCommentByIds:Kh,createComment:async e=>{const t=ye();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&&La(r,{cachedAt:s}),["post","content"].includes(e.referenceType)){const t=await ju(e.referenceId);Qe("post.updated",{posts:[t.data],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[]})}else if("story"===e.referenceType){const t=we(["story-reference",e.referenceId]);if(null==t?void 0:t.data){const e=we(["story","get",t.data]);(null==e?void 0:e.data)&&Qe("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 Qe("comment.created",r),{data:el.comment(n[0]),cachedAt:s}},updateComment:async(e,t)=>{const r=ye();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&&La(n,{cachedAt:s}),Qe("comment.updated",n);const{comments:i}=n;return{data:el.comment(i.find((t=>t.commentId===e))),cachedAt:s}},deleteComment:Gh,softDeleteComment:async e=>{ye().log("comment/softDeleteComment",e);return Gh(e)},hardDeleteComment:async e=>{ye().log("comment/hardDeleteComment",e);return Gh(e,!0)},flagComment:async e=>{const t=ye();t.log("comment/flagComment",e);const{data:r}=await t.http.post(`/api/v3/comments/${encodeURIComponent(e)}/flag`);return t.cache&&La(r),Qe("comment.flagged",r),!!r},unflagComment:async e=>{const t=ye();t.log("comment/unflagComment",e);const{data:r}=await t.http.delete(`/api/v3/comments/${encodeURIComponent(e)}/unflag`);return t.cache&&La(r),Qe("comment.unflagged",r),!!r},isCommentFlaggedByMe:async e=>{const t=ye();t.log("comment/isCommentFlaggedByMe",e);const{data:{result:r}}=await t.http.get(`/api/v3/comments/${e}/isflagbyme`);return r},onCommentCreated:rd,onCommentUpdated:nd,onCommentDeleted:sd,onCommentFlagged:id,onCommentUnflagged:od,onCommentReactionAdded:ad,onCommentReactionRemoved:ld,observeComments:(e,t)=>{const{log:r}=ye(),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(rd((e=>i(e,"onCreate"))),nd((e=>i(e,"onUpdate"))),sd((e=>i(e,"onDelete"))),id((e=>i(e,"onFlagged"))),od((e=>i(e,"onUnflagged"))),ad((e=>i(e,"onReactionAdded"))),ld((e=>i(e,"onReactionRemoved")))),()=>{r(`observeComments(tmpid: ${n}) > dispose`),s.forEach((e=>e()))}},observeComment:(e,t,r="cache_then_server")=>{const{log:n}=ye(),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)},o=(t,r)=>{var n;(null===(n=t.data)||void 0===n?void 0:n.commentId)===e&&i(t,r)},a=[];return a.push(nd((e=>o({data:e,loading:!1,origin:"event"},"onUpdate"))),sd((e=>o({data:e,loading:!1,origin:"event"},"onDelete"))),id((e=>o({data:e,loading:!1,origin:"event"},"onFlagged"))),od((e=>o({data:e,loading:!1,origin:"event"},"onUnflagged"))),ad((e=>o({data:e,loading:!1,origin:"event"},"onReactionAdded"))),ld((e=>o({data:e,loading:!1,origin:"event"},"onReactionRemoved")))),oe(se(Hh,e),(e=>(e.data||e.error)&&i(e,"onFetch")),ie(r)),()=>{n(`observeComment(tmpid: ${s}) > dispose`),a.forEach((e=>e()))}},getComment:(e,t)=>Tc(e,t,"commentId",Hh,[sd,id,ad,ld,od,nd,t=>rd((r=>{if(r.parentId!==e)return;const n=we(["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}=ye();s||console.log("For using Live Collection feature you need to enable Cache!");const i=Date.now();n(`getComments(tmpid: ${i}) > listen`);const{limit:o}=e,a=xa(e,["limit"]),{policy:l=f}=null!=r?r:{},c=[],u=["comment","collection",{referenceId:e.referenceType,referenceType:e.referenceId,parentId:(null==e?void 0:e.parentId)||""}],d=r=>{var n,s;let i=null!==(n=r.data.map((e=>we(["comment","get",e]))).filter((({data:t})=>t.parentId===(null==e?void 0:e.parentId))).filter(Boolean).map((({data:e})=>el.comment(e))))&&void 0!==n?n:[];e.includeDeleted||(i=ke(i,"isDeleted",!1));const o=e.sortBy?e.sortBy:"lastCreated";i=i.sort("lastCreated"===o?Fe:Me),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=we(u))||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))),Ee(u,s),d(s))},p=(e=!1)=>{var t,r,n;const s=null===(t=we(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 c=se(Vh,Object.assign(Object.assign({},a),{limit:o,page:e||null==s?void 0:s.params.page}));oe(c,(({data:t,error:r,loading:n,paging:s})=>{const o={loading:n,error:r,params:{page:"lastCreated"===(a.sortBy||"lastCreated")?null==s?void 0:s.next:null==s?void 0:s.previous},data:i};t&&(o.data=e?t.map(ce("comment")):[...new Set([...i,...t.map(ce("comment"))])]),Ee(u,o),d(o)}),ie(l,v))};return c.push(rd(h("onCreate")),nd(h("onUpdate")),sd(h("onDelete")),id(h("onFlagged")),od(h("onUnflagged")),ad(h("onReactionAdded")),ld(h("onReactionRemoved"))),p(!0),c.push((()=>Ce(u))),()=>{n(`getComments(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}}});const Wh=async e=>{const t=ye();t.log("stream/getStream",e);const{data:r}=await t.http.get(`/api/v3/video-streaming/${e}`),n=t.cache&&Date.now();t.cache&&La(r,{cachedAt:n});const{videoStreamings:s}=r;return{data:s.find((t=>t.streamId===e)),cachedAt:n}};Wh.locally=e=>{const t=ye();if(t.log("stream/getStream",e),!t.cache)return;const r=we(["stream","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const Yh=e=>{const t=ye();return Ye(t,"stream/onStreamStarted","video-streaming.didStart",(t=>{La(t),e(t.videoStreamings[0])}))},Qh=e=>{const t=ye();return Ye(t,"stream/onStreamStarted","video-streaming.didStop",(t=>{La(t),e(t.videoStreamings[0])}))},Xh=e=>{const t=ye();return Ye(t,"stream/onStreamRecorded","video-streaming.didRecord",(t=>{La(t),e(t.videoStreamings[0])}))},Jh=(e,t)=>Tc(e,t,"streamId",Wh,[Xh,Yh,Qh]);Jh.locally=e=>{const t=ye();if(t.log("stream/getStreamById",e),!t.cache)return;const r=we(["stream","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const Zh=async e=>{const t=ye();t.log("stream/queryStreams",e);const r=null!=e?e:{},{page:n,limit:s}=r,i=xa(r,["page","limit"]),o=n?{token:n}:s?{limit:s}:void 0,{data:a}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},i),{options:o})}),{paging:l,results:c}=a,{videoStreamings:u}=c,d=t.cache&&Date.now();return t.cache&&La(c,{cachedAt:d}),{data:u,cachedAt:d,paging:l}};var ef=Object.freeze({__proto__:null,createStream:async e=>{const t=ye();t.log("stream/createStream",e);const{data:r}=await t.http.post("/api/v3/video-streaming",e),n=t.cache&&Date.now();t.cache&&La(r,{cachedAt:n});const{videoStreamings:s}=r;return{data:s[0],cachedAt:n}},updateStream:async(e,t)=>{const r=ye();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&&La(n,{cachedAt:s});const{videoStreamings:i}=n;return{data:i.find((t=>t.streamId===e)),cachedAt:s}},deleteStream:async e=>{const t=ye();t.log("stream/deleteStream",e);const r=await Wh(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 Se(["stream","get",e],i),s},disposeStream:async e=>{const t=ye();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&&La(r,{cachedAt:n});const{videoStreamings:s}=r;return{data:s.find((t=>t.streamId===e)),cachedAt:n}},queryStreams:async e=>{const t=ye();t.log("stream/queryStreams",e);const r=null!=e?e:{},{page:n}=r,s=xa(r,["page"]),{data:i}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},s),{options:{token:Q(n,"skiplimit")}})}),{paging:o,results:a}=i,{videoStreamings:l}=a,c=t.cache&&Date.now();t.cache&&La(a,{cachedAt:c});const u=X(o.next);return{data:l,cachedAt:c,prevPage:X(o.previous),nextPage:u}},getStream:Wh,onStreamStarted:Yh,onStreamStopped:Qh,onStreamRecorded:Xh,getStreamById:Jh,getStreams:(e,t,r)=>{const{log:n,cache:s}=ye();s||console.log(p);const i=Date.now();n(`getStreams(tmpid: ${i}) > listen`);const{limit:o}=e,a=xa(e,["limit"]),l=null!=o?o:h,{policy:c=f}=null!=r?r:{},u=[],d=["streams","collection",e],g=t=>{let r=ke(t,"isDeleted",e.isDeleted);return r=r.sort("lastCreated"===e.sortBy?Fe:Me),r},m=(e,r=!1)=>{var n,s;const i=null!==(n=e.data.map((e=>we(["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=we(d))||void 0===t?void 0:t.data;r&&(r.data=[...new Set([e.streamId,...r.data])],Ee(d,r),m(r,!0))},v=(e=!1)=>{var t,r;const n=null===(t=we(d))||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=se(Zh,Object.assign(Object.assign({},a),{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(ce("stream"))])]),Ee(d,i),m(i)}),ie(c))};return u.push(Xh(y()),Yh(y()),Qh(y())),v(!0),()=>{n(`getStreams(tmpid: ${i}) > dispose`),u.forEach((e=>e()))}}});const tf=async e=>{const t=ye();t.log("poll/getPoll",e);const{data:r}=await t.http.get(`/api/v3/polls/${e}`),n=t.cache&&Date.now();t.cache&&La(r,{cachedAt:n});const{polls:s}=r;return{data:s.find((t=>t.pollId===e)),cachedAt:n}};tf.locally=e=>{const t=ye();if(t.log("poll/getPoll",e),!t.cache)return;const r=we(["poll","get",e]);return r?{data:r.data,cachedAt:r.cachedAt}:void 0};const rf=e=>{const t=ye();return Ye(t,"poll/onPollUpdated","poll.updated",(r=>{t.cache&&La(r),e(r.polls[0])}))},nf=e=>{const t=ye();return Ye(t,"poll/onPollDeleted","poll.deleted",(r=>{t.cache&&La(r),e(r.polls[0])}))};var sf=Object.freeze({__proto__:null,createPoll:async e=>{const t=ye();t.log("post/createPoll",e);const{data:r}=await t.http.post("/api/v3/polls",e),n=t.cache&&Date.now();t.cache&&La(r,{cachedAt:n});const{polls:s}=r;return{data:s[0],cachedAt:n}},closePoll:async e=>{const t=ye();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&&La(r,{cachedAt:n}),Qe("poll.updated",r);const{polls:s}=r;return{data:s.find((t=>t.pollId===e)),cachedAt:n}},deletePoll:async e=>{const t=ye();t.log("poll/deletePoll",e);const r=await tf(e),{data:n}=await t.http.delete(`/api/v3/polls/${e}`),{success:s}=n,i=Object.assign(Object.assign({},r.data),{isDeleted:!0});return Se(["poll","get",e],i),Qe("poll.deleted",{polls:[i],users:[]}),s},votePoll:async(e,t)=>{const r=ye();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&&La(n,{cachedAt:s});const{polls:i}=n;return Qe("poll.updated",n),{data:i.find((t=>t.pollId===e)),cachedAt:s}},onPollUpdated:rf,onPollDeleted:nf,observePoll:(e,t,r="cache_then_server")=>{const{log:n}=ye(),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)},o=(t,r)=>{var n;(null===(n=t.data)||void 0===n?void 0:n.pollId)===e&&i(t,r)},a=[];return a.push(rf((e=>o({data:e,loading:!1,origin:"event"},"onUpdate"))),nf((e=>o({data:e,loading:!1,origin:"event"},"onDelete")))),oe(se(tf,e),(e=>(e.data||e.error)&&i(e,"onFetch")),ie(r)),()=>{n(`observePoll(tmpid: ${s}) > dispose`),a.forEach((e=>e()))}},getPoll:(e,t)=>Tc(e,t,"pollId",tf,[rf,nf])});function of(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var af={exports:{}};!function(e,t){var r,n,s,i,o;r=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,n=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,i=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(e,t,r){if(r=r||{},e=e.trim(),!(t=t.trim())){if(!r.alwaysNormalize)return e;var s=o.parseURL(e);if(!s)throw new Error("Error trying to parse base URL.");return s.path=o.normalizePath(s.path),o.buildURLFromParts(s)}var i=o.parseURL(t);if(!i)throw new Error("Error trying to parse relative URL.");if(i.scheme)return r.alwaysNormalize?(i.path=o.normalizePath(i.path),o.buildURLFromParts(i)):t;var a=o.parseURL(e);if(!a)throw new Error("Error trying to parse base URL.");if(!a.netLoc&&a.path&&"/"!==a.path[0]){var l=n.exec(a.path);a.netLoc=l[1],a.path=l[2]}a.netLoc&&!a.path&&(a.path="/");var c={scheme:a.scheme,netLoc:i.netLoc,path:null,params:i.params,query:i.query,fragment:i.fragment};if(!i.netLoc&&(c.netLoc=a.netLoc,"/"!==i.path[0]))if(i.path){var u=a.path,d=u.substring(0,u.lastIndexOf("/")+1)+i.path;c.path=o.normalizePath(d)}else c.path=a.path,i.params||(c.params=a.params,i.query||(c.query=a.query));return null===c.path&&(c.path=r.alwaysNormalize?o.normalizePath(i.path):i.path),o.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=o}(af);var lf=af.exports;function cf(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 uf(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?cf(Object(r),!0).forEach((function(t){df(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):cf(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function df(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 hf(){return hf=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},hf.apply(this,arguments)}const ff=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)};let pf=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}({}),gf=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}({}),mf=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(){},vf={trace:yf,debug:yf,log:yf,warn:yf,info:yf,error:yf};let bf=vf;function wf(e,...t){t.forEach((function(t){bf[t]=e[t]?e[t].bind(e):function(e){const t=self.console[e];return t?t.bind(self.console,`[${e}] >`):yf}(t)}))}const Ef=bf,Tf=/^(\d+)x(\d+)$/,Sf=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Cf{constructor(e){"string"==typeof e&&(e=Cf.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=Tf.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(Sf.lastIndex=0;null!==(t=Sf.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 kf(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e}class Af{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]){Ef.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=hf(new Cf({}),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"]);ff(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(ff(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&&ff(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class _f{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 If="audio",Rf="video",Lf="audiovideo";class Df{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[If]:null,[Rf]:null,[Lf]: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=lf.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class xf extends Df{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 _f,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(!ff(this.programDateTime))return null;const e=ff(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:o}=this,a=o[e];a?(a.startPTS=Math.min(a.startPTS,t),a.endPTS=Math.max(a.endPTS,r),a.startDTS=Math.min(a.startDTS,n),a.endDTS=Math.max(a.endDTS,s)):o[e]={startPTS:t,endPTS:r,startDTS:n,endDTS:s,partial:i}}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[If]=null,e[Rf]=null,e[Lf]=null}}class Of extends Df{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 _f,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 Pf{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&&ff(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 Mf(e){return Uint8Array.from(atob(e),(e=>e.charCodeAt(0)))}function Ff(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=Mf(s)):r=function(e){const t=Nf(e).subarray(0,16),r=new Uint8Array(16);return r.set(t,16-t.length),r}(s)}}return r}function Nf(e){return Uint8Array.from(unescape(encodeURIComponent(e)),(e=>e.charCodeAt(0)))}var Uf={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Bf="org.w3.clearkey",jf="com.apple.streamingkeydelivery",$f="com.microsoft.playready",qf="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function Kf(e){switch(e){case jf:return Uf.FAIRPLAY;case $f:return Uf.PLAYREADY;case qf:return Uf.WIDEVINE;case Bf:return Uf.CLEARKEY}}var Gf="edef8ba979d64acea3c827dcd51d21ed";function Hf(e){switch(e){case Uf.FAIRPLAY:return jf;case Uf.PLAYREADY:return $f;case Uf.WIDEVINE:return qf;case Uf.CLEARKEY:return Bf}}function Vf(e){const{drmSystems:t,widevineLicenseUrl:r}=e,n=t?[Uf.FAIRPLAY,Uf.WIDEVINE,Uf.PLAYREADY,Uf.CLEARKEY].filter((e=>!!t[e])):[];return!n[Uf.WIDEVINE]&&r&&n.push(Uf.WIDEVINE),n}const zf="undefined"!=typeof self&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function Wf(e,t,r){return Uint8Array.prototype.slice?e.slice(t,r):new Uint8Array(Array.prototype.slice.call(e,t,r))}const Yf=(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,Qf=(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,Xf=(e,t)=>{const r=t;let n=0;for(;Yf(e,t);){n+=10;n+=Jf(e,t+6),Qf(e,t+10)&&(n+=10),t+=n}if(n>0)return e.subarray(r,r+n)},Jf=(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},Zf=(e,t)=>Yf(e,t)&&Jf(e,t+6)+10<=e.length-t,ep=e=>e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info,tp=e=>{const t=String.fromCharCode(e[0],e[1],e[2],e[3]),r=Jf(e,4);return{type:t,size:r,data:e.subarray(10,10+r)}},rp=e=>{let t=0;const r=[];for(;Yf(e,t);){const n=Jf(e,t+6);t+=10;const s=t+n;for(;t+8<s;){const n=tp(e.subarray(t)),s=np(n);s&&r.push(s),t+=n.size+10}Qf(e,t)&&(t+=10)}return r},np=e=>"PRIV"===e.type?sp(e):"W"===e.type[0]?op(e):ip(e),sp=e=>{if(e.size<2)return;const t=lp(e.data,!0),r=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:r.buffer}},ip=e=>{if(e.size<2)return;if("TXXX"===e.type){let t=1;const r=lp(e.data.subarray(t),!0);t+=r.length+1;const n=lp(e.data.subarray(t));return{key:e.type,info:r,data:n}}const t=lp(e.data.subarray(1));return{key:e.type,data:t}},op=e=>{if("WXXX"===e.type){if(e.size<2)return;let t=1;const r=lp(e.data.subarray(t),!0);t+=r.length+1;const n=lp(e.data.subarray(t));return{key:e.type,info:r,data:n}}const t=lp(e.data);return{key:e.type,data:t}},ap=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)}},lp=(e,t=!1)=>{const r=up();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,o,a="",l=0;for(;l<n;){if(s=e[l++],0===s&&t)return a;if(0!==s&&3!==s)switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(s);break;case 12:case 13:i=e[l++],a+=String.fromCharCode((31&s)<<6|63&i);break;case 14:i=e[l++],o=e[l++],a+=String.fromCharCode((15&s)<<12|(63&i)<<6|(63&o)<<0)}}return a};let cp;function up(){return cp||void 0===self.TextDecoder||(cp=new self.TextDecoder("utf-8")),cp}const dp=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},hp=Math.pow(2,32)-1,fp=[].push,pp={video:1,audio:2,id3:3,text:4};function gp(e){return String.fromCharCode.apply(null,e)}function mp(e,t){const r=e[t]<<8|e[t+1];return r<0?65536+r:r}function yp(e,t){const r=vp(e,t);return r<0?4294967296+r:r}function vp(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function bp(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 wp(e,t){const r=[];if(!t.length)return r;const n=e.byteLength;for(let s=0;s<n;){const i=yp(e,s),o=i>1?s+i:n;if(gp(e.subarray(s+4,s+8))===t[0])if(1===t.length)r.push(e.subarray(s+8,o));else{const n=wp(e.subarray(s+8,o),t.slice(1));n.length&&fp.apply(r,n)}s=o}return r}function Ep(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 o=mp(e,n);n+=2;for(let r=0;r<o;r++){let r=n;const o=yp(e,r);r+=4;const a=2147483647&o;if(1===(2147483648&o)>>>31)return Ef.warn("SIDX has hierarchical references (not supported)"),null;const l=yp(e,r);r+=4,t.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/s,start:i,end:i+a-1}}),i+=a,r+=4,n=r}return{earliestPresentationTime:0,timescale:s,version:r,referencesCount:o,references:t}}function Tp(e){const t=[],r=wp(e,["moov","trak"]);for(let e=0;e<r.length;e++){const n=r[e],s=wp(n,["tkhd"])[0];if(s){let e=s[0],r=0===e?12:20;const i=yp(s,r),o=wp(n,["mdia","mdhd"])[0];if(o){e=o[0],r=0===e?12:20;const s=yp(o,r),a=wp(n,["mdia","hdlr"])[0];if(a){const e=gp(a.subarray(8,12)),r={soun:If,vide:Rf}[e];if(r){const e=wp(n,["mdia","minf","stbl","stsd"])[0];let o;e&&(o=gp(e.subarray(12,16))),t[i]={timescale:s,type:r},t[r]={timescale:s,id:i,codec:o}}}}}}return wp(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 Sp(e){const t=wp(e,["schm"])[0];if(t){const r=gp(t.subarray(4,8));if("cbcs"===r||"cenc"===r)return wp(e,["schi","tenc"])[0]}return Ef.error("[eme] missing 'schm' box"),null}function Cp(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 kp(e,t){const r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}function Ap(e,t){const r=[],n=t.samples,s=t.timescale,i=t.id;let o=!1;return wp(n,["moof"]).map((a=>{const l=a.byteOffset-8;wp(a,["traf"]).map((a=>{const c=wp(a,["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),wp(a,["tfhd"]).map((c=>{const u=yp(c,4),d=16777215&yp(c,0);let h=0;const f=0!=(16&d);let p=0;const g=0!=(32&d);let m=8;u===i&&(0!=(1&d)&&(m+=8),0!=(2&d)&&(m+=4),0!=(8&d)&&(h=yp(c,m),m+=4),f&&(p=yp(c,m),m+=4),g&&(m+=4),"video"===t.type&&(o=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)),wp(a,["trun"]).map((i=>{const a=i[0],c=16777215&yp(i,0),u=0!=(1&c);let d=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 T=yp(i,4);let S=8;u&&(d=yp(i,S),S+=4),f&&(S+=4);let C=d+l;for(let l=0;l<T;l++){if(g?(m=yp(i,S),S+=4):m=h,y?(v=yp(i,S),S+=4):v=p,b&&(S+=4),w&&(E=0===a?yp(i,S):vp(i,S),S+=4),t.type===Rf){let t=0;for(;t<v;){const i=yp(n,C);if(C+=4,_p(o,n[C])){Ip(n.subarray(C,C+i),o?2:1,e+E/s,r)}C+=i,t+=i+4}}e+=m/s}})))}))}))})),r}function _p(e,t){if(e){const e=t>>1&63;return 39===e||40===e}return 6===(31&t)}function Ip(e,t,r,n){const s=Rp(e);let i=0;i+=t;let o=0,a=0,l=!1,c=0;for(;i<s.length;){o=0;do{if(i>=s.length)break;c=s[i++],o+=c}while(255===c);a=0;do{if(i>=s.length)break;c=s[i++],a+=c}while(255===c);const e=s.length-i;if(!l&&4===o&&i<s.length){l=!0;if(181===s[i++]){const e=mp(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++],a=31&t,l=64&t,c=l?2+3*a:0,u=new Uint8Array(c);if(l){u[0]=t;for(let e=1;e<c;e++)u[e]=s[i++]}n.push({type:e,payloadType:o,pts:r,bytes:u})}}}}}else if(5===o&&a<e){if(l=!0,a>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=a-16,l=new Uint8Array(t);for(let e=0;e<t;e++)l[e]=s[i++];n.push({payloadType:o,pts:r,uuid:e.join(""),userData:lp(l),userDataBytes:l})}}else if(a<e)i+=a;else if(a>e)break}}function Rp(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 o=0;for(n=0;n<s;o++,n++)o===r[0]&&(o++,r.shift()),i[n]=e[o];return i}function Lp(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 o=new Uint8Array(4);return r&&r.byteLength>0&&new DataView(o.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,o,r||new Uint8Array)}let Dp={};class xp{static clearKeyUriToKeyIdMap(){Dp={}}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 jf:case qf:case $f:case Bf: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||Ef.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 xp(this.method,this.uri,"identity",this.keyFormatVersions,t)}const t=Ff(this.uri);if(t)switch(this.keyFormat){case qf:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case $f:{const e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Lp(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=Mf(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=Dp[this.uri];if(!e){const t=Object.keys(Dp).length%Number.MAX_SAFE_INTEGER;e=new Uint8Array(16);new DataView(e.buffer,12,4).setUint32(0,t),Dp[this.uri]=e}this.keyId=e}return this}}const Op=/\{\$([a-zA-Z0-9-_]+)\}/g;function Pp(e){return Op.test(e)}function Mp(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]=Fp(e,i))}}function Fp(e,t){if(null!==e.variableList||e.hasVariableRefs){const r=e.variableList;return t.replace(Op,(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 Np(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 Up(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 Bp(){if("undefined"!=typeof self)return self.MediaSource||self.WebKitMediaSource}const jp={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}},$p=Bp();function qp(e,t){var r;return null!=(r=null==$p?void 0:$p.isTypeSupported(`${t||"video"}/mp4;codecs="${e}"`))&&r}const Kp=/#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,Gp=/#EXT-X-MEDIA:(.*)/g,Hp=/^#EXT(?:INF|-X-TARGETDURATION):/m,Vp=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),zp=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 Wp{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 lf.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Hp.test(e)}static parseMasterPlaylist(e,t){const r={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Pp(e)},n=[];let s;for(Kp.lastIndex=0;null!=(s=Kp.exec(e));)if(s[1]){var i;const e=new Cf(s[1]);Mp(r,e,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const o=Fp(r,s[2]),a={attrs:e,bitrate:e.decimalInteger("AVERAGE-BANDWIDTH")||e.decimalInteger("BANDWIDTH"),name:e.NAME,url:Wp.resolve(o,t)},l=e.decimalResolution("RESOLUTION");l&&(a.width=l.width,a.height=l.height),Xp((e.CODECS||"").split(/[ ,]+/).filter((e=>e)),a),a.videoCodec&&-1!==a.videoCodec.indexOf("avc1")&&(a.videoCodec=Wp.convertAVC1ToAVCOTI(a.videoCodec)),null!=(i=a.unknownCodecs)&&i.length||n.push(a),r.levels.push(a)}else if(s[3]){const e=s[3],n=s[4];switch(e){case"SESSION-DATA":{const e=new Cf(n);Mp(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=Yp(n,t,r);e.encrypted&&e.isSupported()?(null===r.sessionKeys&&(r.sessionKeys=[]),r.sessionKeys.push(e)):Ef.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${n}"`);break}case"DEFINE":{const e=new Cf(n);Mp(r,e,["NAME","VALUE","QUERYPARAM"]),Np(r,e,t)}break;case"CONTENT-STEERING":{const e=new Cf(n);Mp(r,e,["SERVER-URI","PATHWAY-ID"]),r.contentSteering={uri:Wp.resolve(e["SERVER-URI"],t),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":r.startTimeOffset=Qp(n)}}const o=n.length>0&&n.length<r.levels.length;return r.levels=o?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,o={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 a=0;for(Gp.lastIndex=0;null!==(n=Gp.exec(e));){const e=new Cf(n[1]),i=e.TYPE;if(i){const n=o[i],l=s[i]||[];s[i]=l,Mp(r,e,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const c={attrs:e,bitrate:0,id:a++,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?Wp.resolve(e.URI,t):""};if(null!=n&&n.length){const e=Wp.findGroup(n,c.groupId)||n[0];Jp(c,e,"audioCodec"),Jp(c,e,"textCodec")}l.push(c)}}return s}static parseLevelPlaylist(e,t,r,n,s,i){const o=new Pf(t),a=o.fragments;let l,c,u,d=null,h=0,f=0,p=0,g=0,m=null,y=new xf(n,t),v=-1,b=!1;for(Vp.lastIndex=0,o.m3u8=e,o.hasVariableRefs=Pp(e);null!==(l=Vp.exec(e));){b&&(b=!1,y=new xf(n,t),y.start=p,y.sn=h,y.cc=g,y.level=r,d&&(y.initSegment=d,y.rawProgramDateTime=d.rawProgramDateTime,d.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(ff(y.duration)){y.start=p,u&&tg(y,u,o),y.sn=h,y.level=r,y.cc=g,y.urlId=s,a.push(y);const e=(" "+l[3]).slice(1);y.relurl=Fp(o,e),Zp(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=a.length);else{if(l=l[0].match(zp),!l){Ef.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":o.type=s.toUpperCase();break;case"MEDIA-SEQUENCE":h=o.startSN=parseInt(s);break;case"SKIP":{const e=new Cf(s);Mp(o,e,["RECENTLY-REMOVED-DATERANGES"]);const t=e.decimalInteger("SKIPPED-SEGMENTS");if(ff(t)){o.skippedSegments=t;for(let e=t;e--;)a.unshift(null);h+=t}const r=e.enumeratedString("RECENTLY-REMOVED-DATERANGES");r&&(o.recentlyRemovedDateranges=r.split("\t"));break}case"TARGETDURATION":o.targetduration=Math.max(parseInt(s),1);break;case"VERSION":o.version=parseInt(s);break;case"EXTM3U":break;case"ENDLIST":o.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 Cf(s);Mp(o,e,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),Mp(o,e,e.clientAttrs);const t=new Af(e,o.dateRanges[e.ID]);t.isValid||o.skippedSegments?o.dateRanges[t.id]=t:Ef.warn(`Ignoring invalid DATERANGE tag: "${s}"`),y.tagList.push(["EXT-X-DATERANGE",s]);break}case"DEFINE":{const e=new Cf(s);Mp(o,e,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in e?Up(o,e,i):Np(o,e,t)}break;case"DISCONTINUITY-SEQUENCE":g=parseInt(s);break;case"KEY":{const e=Yp(s,t,o);if(e.isSupported()){if("NONE"===e.method){u=void 0;break}u||(u={}),u[e.keyFormat]&&(u=hf({},u)),u[e.keyFormat]=e}else Ef.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${s}"`);break}case"START":o.startTimeOffset=Qp(s);break;case"MAP":{const e=new Cf(s);if(Mp(o,e,["BYTERANGE","URI"]),y.duration){const s=new xf(n,t);eg(s,e,r,u),d=s,y.initSegment=d,d.rawProgramDateTime&&!y.rawProgramDateTime&&(y.rawProgramDateTime=d.rawProgramDateTime)}else eg(y,e,r,u),d=y,b=!0;break}case"SERVER-CONTROL":{const e=new Cf(s);o.canBlockReload=e.bool("CAN-BLOCK-RELOAD"),o.canSkipUntil=e.optionalFloat("CAN-SKIP-UNTIL",0),o.canSkipDateRanges=o.canSkipUntil>0&&e.bool("CAN-SKIP-DATERANGES"),o.partHoldBack=e.optionalFloat("PART-HOLD-BACK",0),o.holdBack=e.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const e=new Cf(s);o.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=o.partList;e||(e=o.partList=[]);const r=f>0?e[e.length-1]:void 0,n=f++,i=new Cf(s);Mp(o,i,["BYTERANGE","URI"]);const a=new Of(i,y,t,n,r);e.push(a),y.duration+=a.duration;break}case"PRELOAD-HINT":{const e=new Cf(s);Mp(o,e,["URI"]),o.preloadHint=e;break}case"RENDITION-REPORT":{const e=new Cf(s);Mp(o,e,["URI"]),o.renditionReports=o.renditionReports||[],o.renditionReports.push(e);break}default:Ef.warn(`line parsed but not handled: ${l}`)}}}m&&!m.relurl?(a.pop(),p-=m.duration,o.partList&&(o.fragmentHint=m)):o.partList&&(Zp(y,m),y.cc=g,o.fragmentHint=y,u&&tg(y,u,o));const w=a.length,E=a[0],T=a[w-1];if(p+=o.skippedSegments*o.targetduration,p>0&&w&&T){o.averagetargetduration=p/w;const e=T.sn;o.endSN="initSegment"!==e?e:0,o.live||(T.endList=!0),E&&(o.startCC=E.cc)}else o.endSN=0,o.startCC=0;return o.fragmentHint&&(p+=o.fragmentHint.duration),o.totalduration=p,o.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}}(a,v),o}}function Yp(e,t,r){var n,s;const i=new Cf(e);Mp(r,i,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const o=null!=(n=i.METHOD)?n:"",a=i.URI,l=i.hexadecimalInteger("IV"),c=i.KEYFORMATVERSIONS,u=null!=(s=i.KEYFORMAT)?s:"identity";a&&i.IV&&!l&&Ef.error(`Invalid IV: ${i.IV}`);const d=a?Wp.resolve(a,t):"",h=(c||"1").split("/").map(Number).filter(Number.isFinite);return new xp(o,d,u,h,l)}function Qp(e){const t=new Cf(e).decimalFloatingPoint("TIME-OFFSET");return ff(t)?t:null}function Xp(e,t){["video","audio","text"].forEach((r=>{const n=e.filter((e=>function(e,t){const r=jp[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 Jp(e,t,r){const n=t[r];n&&(e[r]=n)}function Zp(e,t){e.rawProgramDateTime?e.programDateTime=Date.parse(e.rawProgramDateTime):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime),ff(e.programDateTime)||(e.programDateTime=null,e.rawProgramDateTime=null)}function eg(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 tg(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 rg="manifest",ng="level",sg="audioTrack",ig="subtitleTrack",og="main",ag="audio",lg="subtitle";function cg(e){const{type:t}=e;switch(t){case sg:return ag;case ig:return lg;default:return og}}function ug(e,t){let r=e.url;return void 0!==r&&0!==r.indexOf("data:")||(r=t.url),r}class dg{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(pf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(pf.LEVEL_LOADING,this.onLevelLoading,this),e.on(pf.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(pf.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:e}=this;e.off(pf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(pf.LEVEL_LOADING,this.onLevelLoading,this),e.off(pf.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(pf.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:rg,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:ng,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:sg,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:ig,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 Ef.trace("[playlist-loader]: playlist request ongoing");Ef.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}if(n=e.type===rg?r.manifestLoadPolicy.default:hf({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),null!=(t=e.deliveryDirectives)&&t.part){let t;if(e.type===ng&&null!==e.level?t=this.hls.levels[e.level].details:e.type===sg&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===ig&&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=hf({},n,{maxTimeToFirstByteMs:Math.min(t,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,n.maxTimeToFirstByteMs)})}}}const i=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:i.maxNumRetry||0,retryDelay:i.retryDelayMs||0,maxRetryDelay:i.maxRetryDelayMs||0},a={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(),Wp.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,o,a)}handleMasterPlaylist(e,t,r,n){const s=this.hls,i=e.data,o=ug(e,r),a=Wp.parseMasterPlaylist(i,o);if(a.playlistParsingError)return void this.handleManifestParsingError(e,r,a.playlistParsingError,n,t);const{contentSteering:l,levels:c,sessionData:u,sessionKeys:d,startTimeOffset:h,variableList:f}=a;this.variableList=f;const{AUDIO:p=[],SUBTITLES:g,"CLOSED-CAPTIONS":m}=Wp.parseMasterPlaylistMedia(i,o,a);if(p.length){p.some((e=>!e.url))||!c[0].audioCodec||c[0].attrs.AUDIO||(Ef.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 Cf({}),bitrate:0,url:""}))}s.trigger(pf.MANIFEST_LOADED,{levels:c,audioTracks:p,subtitles:g,captions:m,contentSteering:l,url:o,stats:t,networkDetails:n,sessionData:u,sessionKeys:d,startTimeOffset:h,variableList:f})}handleTrackOrLevelPlaylist(e,t,r,n,s){const i=this.hls,{id:o,level:a,type:l}=r,c=ug(e,r),u=ff(o)?o:0,d=ff(a)?a:u,h=cg(r),f=Wp.parseLevelPlaylist(e.data,c,d,h,u,this.variableList);if(l===rg){const e={attrs:new Cf({}),bitrate:0,details:f,name:"",url:c};i.trigger(pf.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(pf.ERROR,{type:gf.NETWORK_ERROR,details:mf.MANIFEST_PARSING_ERROR,fatal:t.type===rg,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===ng?i+=`: ${e.level} id: ${e.id}`:e.type!==sg&&e.type!==ig||(i+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(i);Ef.warn(`[playlist-loader]: ${i}`);let a=mf.UNKNOWN,l=!1;const c=this.getInternalLoader(e);switch(e.type){case rg:a=r?mf.MANIFEST_LOAD_TIMEOUT:mf.MANIFEST_LOAD_ERROR,l=!0;break;case ng:a=r?mf.LEVEL_LOAD_TIMEOUT:mf.LEVEL_LOAD_ERROR,l=!1;break;case sg:a=r?mf.AUDIO_TRACK_LOAD_TIMEOUT:mf.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case ig:a=r?mf.SUBTITLE_TRACK_LOAD_TIMEOUT:mf.SUBTITLE_LOAD_ERROR,l=!1}c&&this.resetInternalLoader(e.type);const u={type:gf.NETWORK_ERROR,details:a,fatal:l,url:e.url,loader:c,context:e,error:o,networkDetails:t,stats:s};if(n){const r=(null==t?void 0:t.url)||e.url;u.response=uf({url:r,data:void 0},n)}this.hls.trigger(pf.ERROR,u)}handlePlaylistLoaded(e,t,r,n,s,i){const o=this.hls,{type:a,level:l,id:c,groupId:u,deliveryDirectives:d}=n,h=ug(t,n),f=cg(n),p="number"==typeof n.level&&f===og?l:void 0;if(!e.fragments.length){const e=new Error("No Segments found in Playlist");return void o.trigger(pf.ERROR,{type:gf.NETWORK_ERROR,details:mf.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)o.trigger(pf.ERROR,{type:gf.NETWORK_ERROR,details:mf.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)),a){case rg:case ng:o.trigger(pf.LEVEL_LOADED,{details:e,level:p||0,id:c||0,stats:r,networkDetails:s,deliveryDirectives:d});break;case sg:o.trigger(pf.AUDIO_TRACK_LOADED,{details:e,id:c||0,groupId:u||"",stats:r,networkDetails:s,deliveryDirectives:d});break;case ig:o.trigger(pf.SUBTITLE_TRACK_LOADED,{details:e,id:c||0,groupId:u||"",stats:r,networkDetails:s,deliveryDirectives:d})}}}function hg(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 fg(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){Ef.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){Ef.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}"disabled"===r&&(e.mode=r)}function pg(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 gg(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,o=e.length;i<o;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 mg="org.id3",yg="com.apple.quicktime.HLS",vg="https://aomedia.org/emsg/ID3";function bg(){if("undefined"!=typeof self)return self.WebKitDataCue||self.VTTCue||self.TextTrackCue}const wg=(()=>{const e=bg();try{new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function Eg(e,t){return e.getTime()/1e3-t}class Tg{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(pf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(pf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(pf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(pf.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(pf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(pf.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(pf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(pf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(pf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(pf.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(pf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(pf.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&(pg(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 hg(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=bg();for(let e=0;e<s.length;e++){const t=s[e].type;if(t===vg&&!r||!n)continue;const o=rp(s[e].data);if(o){const r=s[e].pts;let n=r+s[e].duration;n>wg&&(n=wg);n-r<=0&&(n=r+.25);for(let e=0;e<o.length;e++){const s=o[e];if(!ep(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===wg&&(s.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:r,type:n}){const{id3Track:s,hls:i}=this;if(!i)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:a}}=i;if(s&&(o||a)){let e;e="audio"===n?e=>e.type===mg&&a:"video"===n?e=>e.type===vg&&o:e=>e.type===mg&&a||e.type===vg&&o,gg(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 o=t.fragments[t.fragments.length-1];if(0===i.length||!ff(null==o?void 0:o.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=o.programDateTime/1e3-o.start,l=bg();for(let e=0;e<i.length;e++){const t=i[e],n=s[t],o=r[t],d=(null==o?void 0:o.cues)||{};let h=(null==o?void 0:o.durationKnown)||!1;const f=Eg(n.startDate,a);let p=wg;const g=n.endDate;if(g)p=Eg(g,a),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=Eg(e.startDate,a),h=!0)}const m=Object.keys(n.attr);for(let e=0;e<m.length;e++){const r=m[e];if("ID"===(u=r)||"CLASS"===u||"START-DATE"===u||"DURATION"===u||"END-DATE"===u||"END-ON-NEXT"===u)continue;let s=d[r];if(s)h&&!o.durationKnown&&(s.endTime=p);else{let e=n.attr[r];s=new l(f,p,""),kf(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),d[r]=s}}r[t]={cues:d,dateRange:n,durationKnown:h}}var c,u}}class Sg{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:o}=this.config,a=this.hls.userConfig;let l=o&&r||t;(a.liveSyncDuration||a.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,o=n-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(i,s),o)}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(pf.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(pf.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(pf.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(pf.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(pf.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(pf.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(pf.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(pf.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(pf.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(pf.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===mf.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(r=this.levelDetails)&&r.live&&Ef.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 o=r-i,a=o<Math.min(this.maxLatency,i+t.targetduration);if(t.live&&a&&o>.05&&this.forwardBufferLength>1){const t=Math.min(2,Math.max(1,s)),r=Math.round(2/(1+Math.exp(-.75*o-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 Cg=["NONE","TYPE-0","TYPE-1",null];var kg="",Ag="YES",_g="v2";class Ig{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 Rg{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 Lg(e,t){const r=t.startPTS;if(ff(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 Dg(e,t,r,n,s,i){n-r<=0&&(Ef.warn("Fragment should have a positive duration",t),n=r+t.duration,i=s+t.duration);let o=r,a=n;const l=t.startPTS,c=t.endPTS;if(ff(l)){const e=Math.abs(l-r);ff(t.deltaPTS)?t.deltaPTS=Math.max(e,t.deltaPTS):t.deltaPTS=e,o=Math.max(r,l),r=Math.min(r,l),s=Math.min(s,t.startDTS),a=Math.min(n,c),n=Math.max(n,c),i=Math.max(i,t.endDTS)}const u=r-t.start;0!==t.start&&(t.start=r),t.duration=n-t.start,t.startPTS=r,t.maxStartPTS=o,t.startDTS=s,t.endPTS=n,t.minEndPTS=a,t.endDTS=i;const d=t.sn;if(!e||d<e.startSN||d>e.endSN)return 0;let h;const f=d-e.startSN,p=e.fragments;for(p[f]=t,h=f;h>0;h--)Lg(p[h],p[h-1]);for(h=f;h<p.length-1;h++)Lg(p[h],p[h+1]);return e.fragmentHint&&Lg(p[p.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,u}function xg(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,o=t.startSN-e.startSN,a=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[o+e];let i=a[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),ff(e.startPTS)&&ff(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){Ef.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=hf({},e);r&&r.forEach((e=>{delete n[e]}));return Object.keys(t).forEach((e=>{const r=new Af(t[e].attr,n[e]);r.isValid?n[e]=r:Ef.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(t[e].attr)}"`)})),n}(e.dateRanges,t.dateRanges,t.recentlyRemovedDateranges));const o=t.fragments;if(i){Ef.warn("discontinuity sliding from playlist, take drift into account");for(let e=0;e<o.length;e++)o[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],o=t[s+n];i&&o&&i.index===o.index&&i.fragment.sn===o.fragment.sn?r(i,o):n--}}}(e.partList,t.partList,((e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats})),s?Dg(t,s,s.startPTS,s.endPTS,s.startDTS,s.endDTS):Og(e,t),o.length&&(t.totalduration=t.edge-o[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const a=t.advancedDateTime;if(t.advanced&&a){const e=t.edge;t.driftStart||(t.driftStartTime=a,t.driftStart=e),t.driftEndTime=a,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime}function Og(e,t){const r=t.startSN+t.skippedSegments-e.startSN,n=e.fragments;r<0||r>=n.length||Pg(t,n[r].start)}function Pg(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 Mg(e,t,r){var n;return null!=e&&e.details?Fg(null==(n=e.details)?void 0:n.partList,t,r):null}function Fg(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 Ng(e){switch(e.details){case mf.FRAG_LOAD_TIMEOUT:case mf.KEY_LOAD_TIMEOUT:case mf.LEVEL_LOAD_TIMEOUT:case mf.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Ug(e,t){const r=Ng(t);return e.default[(r?"timeout":"error")+"Retry"]}function Bg(e,t){const r="linear"===e.backoff?1:Math.pow(2,t);return Math.min(r*e.retryDelayMs,e.maxRetryDelayMs)}function jg(e){return uf(uf({},e),{errorRetry:null,timeoutRetry:null})}function $g(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 qg=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 o=t(i);if(o>0)r=s+1;else{if(!(o<0))return i;n=s-1}}return null};function Kg(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===Gg(r,n,s))return s;const i=qg(t,Gg.bind(null,r,n));return!i||i===e&&s?s:i}function Gg(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 Hg(e,t,r){const n=1e3*Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-n>e}var Vg=0,zg=2,Wg=5,Yg=0,Qg=1,Xg=2;function Jg(e,t,r){if(performance.now()-e.lastErrorPerfMs>3e5)return!0;const n=e.details;if(t.details===mf.FRAG_GAP&&n&&t.frag){const e=t.frag.start,r=Kg(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 Zg{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=Ef.log.bind(Ef,`${t}:`),this.warn=Ef.warn.bind(Ef,`${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 o;try{o=new self.URL(i.URI,t.url).href}catch(e){Ef.warn(`Could not construct new URL for Rendition Report: ${e}`),o=i.URI||""}if(o===e){n=s;break}o===e.substring(0,o.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 Ig(s,i>=0?i:void 0,kg)}}}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(),o=s.loading.first?Math.max(0,i-s.loading.first):0;if(n.advancedDateTime=Date.now()-o,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&&xg(r,n),!this.canLoad||!n.live)return;let o,a,l;if(n.canBlockReload&&n.endSN&&n.advanced){const e=this.hls.config.lowLatencyMode,s=n.lastPartSn,i=n.endSN,c=n.lastPartIndex,u=s===i,d=e?0:c;-1!==c?(a=u?i+1:s,l=u?d:c+1):a=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(a+=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(o=this.getDeliveryDirectives(n,t.deliveryDirectives,a,l),e||!u)return void this.loadPlaylist(o)}else n.canBlockReload&&(o=this.getDeliveryDirectives(n,t.deliveryDirectives,a,l));const c=this.hls.mainForwardBufferInfo,u=c?c.end-c.len:0,d=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-u));n.updated&&i>this.requestScheduled+d&&(this.requestScheduled=s.loading.start),void 0!==a&&n.canBlockReload?this.requestScheduled=s.loading.first+d-(1e3*n.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+d<i?this.requestScheduled=i:this.requestScheduled-i<=0&&(this.requestScheduled+=d);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(o)),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?_g:Ag:kg}(e,r);return null!=t&&t.skip&&e.deltaUpdateFailed&&(r=t.msn,n=t.part,s=kg),new Ig(r,n,s)}checkRetry(e){const t=e.details,r=Ng(e),n=e.errorAction,{action:s,retryCount:i=0,retryConfig:o}=n||{},a=!!n&&!!o&&(s===Wg||!n.resolved&&s===zg);if(a){var l;if(this.requestScheduled=-1,i>=o.maxNumRetry)return!1;if(r&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${i+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const e=Bg(o,i);this.timer=self.setTimeout((()=>this.loadPlaylist()),e),this.warn(`Retrying playlist loading ${i+1}/${o.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,n.resolved=!0}return a}}let em;class tm extends Zg{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(pf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(pf.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(pf.LEVEL_LOADED,this.onLevelLoaded,this),e.on(pf.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(pf.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(pf.FRAG_LOADED,this.onFragLoaded,this),e.on(pf.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(pf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(pf.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(pf.LEVEL_LOADED,this.onLevelLoaded,this),e.off(pf.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(pf.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(pf.FRAG_LOADED,this.onFragLoaded,this),e.off(pf.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"))&&(em||(em=/chrome|firefox/i.test(navigator.userAgent)),em&&(e.audioCodec=void 0));const{AUDIO:o,CODECS:a,"FRAME-RATE":l,"PATHWAY-ID":c,RESOLUTION:u,SUBTITLES:d}=i,h=`${`${c||"."}-`}${e.bitrate}-${u}-${l}-${a}`;s=n[h],s?s.addFallback(e):(s=new Rg(e),n[h]=s,r.push(s)),rm(s,"audio",o),rm(s,"text",d)})),this.filterAndSortMediaOptions(r,t)}filterAndSortMediaOptions(e,t){let r=[],n=[],s=!1,i=!1,o=!1,a=e.filter((({audioCodec:e,videoCodec:t,width:r,height:n,unknownCodecs:a})=>(s||(s=!(!r||!n)),i||(i=!!t),o||(o=!!e),!(null!=a&&a.length)&&(!e||qp(e,"audio"))&&(!t||qp(t,"video")))));if((s||i)&&o&&(a=a.filter((({videoCodec:e,width:t,height:r})=>!!e||!(!t||!r)))),0===a.length)return void Promise.resolve().then((()=>{if(this.hls){const e=new Error("no level with compatible codecs found in manifest");this.hls.trigger(pf.ERROR,{type:gf.MEDIA_ERROR,details:mf.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:e,reason:e.message})}}));t.audioTracks&&(r=t.audioTracks.filter((e=>!e.audioCodec||qp(e.audioCodec,"audio"))),nm(r)),t.subtitles&&(n=t.subtitles,nm(n));const l=a.slice(0);a.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&&(a=this.steering.filterParsedLevels(a),a.length!==l.length))for(let e=0;e<l.length;e++)if(l[e].pathwayId===a[0].pathwayId){c=l[e];break}this._levels=a;for(let e=0;e<a.length;e++)if(a[e]===c){this._firstLevel=e,this.log(`manifest loaded, ${a.length} level(s) found, first bitrate: ${c.bitrate}`);break}const u=o&&!i,d={levels:a,audioTracks:r,subtitleTracks:n,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:o,video:i,altAudio:!u&&r.some((e=>!!e.url))};this.hls.trigger(pf.MANIFEST_PARSED,d),(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(pf.ERROR,{type:gf.OTHER_ERROR,details:mf.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],o=i.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=i,r===e&&i.details&&n&&s===o)return;this.log(`Switching to level ${e}${o?" with Pathway "+o:""} from level ${r}${s?" with Pathway "+s:""}`);const a=hf({},i,{level:e,maxBitrate:i.maxBitrate,attrs:i.attrs,uri:i.uri,urlId:i.urlId});delete a._attrs,delete a._urlId,this.hls.trigger(pf.LEVEL_SWITCHING,a);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===ng&&t.context.level===this.level&&this.checkRetry(t)}onFragLoaded(e,{frag:t}){if(void 0!==t&&t.type===og){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 o;if(!i)return this.warn(`Invalid level index ${n}`),void(null!=(o=t.deliveryDirectives)&&o.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(pf.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(pf.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 rm(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 nm(e){const t={};e.forEach((e=>{const r=e.groupId||"";e.id=t[r]=t[r]||0,t[r]++}))}var sm="NOT_LOADED",im="APPENDING",om="PARTIAL",am="OK";class lm{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(pf.BUFFER_APPENDED,this.onBufferAppended,this),e.on(pf.FRAG_BUFFERED,this.onFragBuffered,this),e.on(pf.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(pf.BUFFER_APPENDED,this.onBufferAppended,this),e.off(pf.FRAG_BUFFERED,this.onFragBuffered,this),e.off(pf.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 o=i.range[e];o&&o.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=um(r),i=this.fragments[s];if(!i||i.buffered&&r.gap)return;const o=!r.relurl;Object.keys(t).forEach((e=>{const s=r.elementaryStreams[e];if(!s)return;const a=t[e],l=o||!0===s.partial;i.range[e]=this.getBufferedTimes(r,n,l,a)})),i.loaded=null,Object.keys(i.range).length?(i.buffered=!0,i.body.endList&&(this.endListFragments[i.body.type]=i),cm(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=um(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,o=e.end,a=e.minEndPTS||o,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&&a<=r){s.time.push({startPTS:Math.max(i,n.start(e)),endPTS:Math.min(o,n.end(e))});break}if(i<r&&o>t)s.partial=!0,s.time.push({startPTS:Math.max(i,n.start(e)),endPTS:Math.min(o,n.end(e))});else if(o<=t)break}return s}getPartialFragment(e){let t,r,n,s=null,i=0;const{bufferPadding:o,fragments:a}=this;return Object.keys(a).forEach((l=>{const c=a[l];c&&cm(c)&&(r=c.body.start-o,n=c.body.end+o,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||cm(t))}getState(e){const t=um(e),r=this.fragments[t];return r?r.buffered?cm(r)?om:am:im:sm}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=um(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=um(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 o=this.fragments[i];if(!o)return;const a=o.body;a.type!==r||n&&!a.gap||a.start<t&&a.end>e&&(o.buffered||s)&&this.removeFragment(a)}))}removeFragment(e){const t=um(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 cm(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 um(e){return`${e.type}_${e.level}_${e.urlId}_${e.sn}`}const dm=Math.pow(2,17);class hm{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 gm({type:gf.NETWORK_ERROR,details:mf.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(((o,a)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some((e=>"GAP"===e[0])))return void a(pm(e));e.gap=!1}const l=this.loader=e.loader=s?new s(n):new i(n),c=fm(e),u=jg(n.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:dm};e.stats=l.stats,l.load(c,d,{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)),o({frag:e,part:null,payload:i,networkDetails:s})},onError:(t,n,s,i)=>{this.resetLoader(e,l),a(new gm({type:gf.NETWORK_ERROR,details:mf.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:uf({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),a(new gm({type:gf.NETWORK_ERROR,details:mf.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:n,stats:t}))},onTimeout:(t,r,n)=>{this.resetLoader(e,l),a(new gm({type:gf.NETWORK_ERROR,details:mf.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${d.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(((o,a)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void a(pm(e,t));const l=this.loader=e.loader=s?new s(n):new i(n),c=fm(e,t),u=jg(n.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:dm};t.stats=l.stats,l.load(c,d,{onSuccess:(n,s,i,a)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const c={frag:e,part:t,payload:n.data,networkDetails:a};r(c),o(c)},onError:(r,n,s,i)=>{this.resetLoader(e,l),a(new gm({type:gf.NETWORK_ERROR,details:mf.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:uf({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),a(new gm({type:gf.NETWORK_ERROR,details:mf.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:s,stats:r}))},onTimeout:(r,n,s)=>{this.resetLoader(e,l),a(new gm({type:gf.NETWORK_ERROR,details:mf.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.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),o=(n-i)*Math.round(r.loaded/i);r.total=r.loaded+o}else r.total=Math.max(r.loaded,r.total);const i=r.loading,o=n.loading;i.start?i.first+=o.first-o.start:(i.start=o.start,i.first=o.first),i.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function fm(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(ff(s)&&ff(i)){var o;let t=s,r=i;if("initSegment"===e.sn&&"AES-128"===(null==(o=e.decryptdata)?void 0:o.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 pm(e,t){const r=new Error(`GAP ${e.gap?"tag":"attribute"} found`),n={type:gf.MEDIA_ERROR,details:mf.FRAG_GAP,fatal:!1,frag:e,error:r,networkDetails:null};return t&&(n.part=t),(t||e).stats.aborted=!0,new gm(n)}class gm extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class mm{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=mf.KEY_LOAD_ERROR,r,n,s){return new gm({type:gf.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,mf.KEY_LOAD_ERROR,r))}const i=s.uri;if(!i)return Promise.reject(this.createKeyLoadError(e,mf.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${i}"`)));let o=this.keyUriToKeyInfo[i];if(null!=(r=o)&&r.decryptdata.key)return s.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});var a;if(null!=(n=o)&&n.keyLoadPromise)switch(null==(a=o.mediaKeySessionContext)?void 0:a.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then((t=>(s.key=t.keyInfo.decryptdata.key,{frag:e,keyInfo:o})))}switch(o=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(o,e):this.loadKeyEME(o,e);case"AES-128":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,mf.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 o={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},a=r.keyLoadPolicy.default,l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(e,t,r,n)=>{const{frag:o,keyInfo:a,url:l}=r;if(!o.decryptdata||a!==this.keyUriToKeyInfo[l])return i(this.createKeyLoadError(o,mf.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),n));a.decryptdata.key=o.decryptdata.key=new Uint8Array(e.data),o.keyLoader=null,a.loader=null,s({frag:o,keyInfo:a})},onError:(e,r,n,s)=>{this.resetLoader(r),i(this.createKeyLoadError(t,mf.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),n,uf({url:o.url,data:void 0},e)))},onTimeout:(e,r,n)=>{this.resetLoader(r),i(this.createKeyLoadError(t,mf.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),n))},onAbort:(e,r,n)=>{this.resetLoader(r),i(this.createKeyLoadError(t,mf.INTERNAL_ABORTED,new Error("key loading aborted"),n))}};n.load(o,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 vm{static isBuffered(e,t){try{if(e){const r=vm.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=vm.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,o=t,a=t;for(let e=0;e<n.length;e++){const l=n[e].start,c=n[e].end;if(t+r>=l&&t<c)o=l,a=c,i=a-t;else if(t+r<l){s=l;break}}return{len:i,start:o||0,end:a||0,nextStart:s}}static getBuffered(e){try{return e.buffered}catch(e){return Ef.log("failed to get media.buffered",e),ym}}}class bm{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 wm(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 Em(e,t){if(e){const r=e.start+t;e.start=e.startPTS=r,e.endPTS=r+e.duration}}function Tm(e,t){const r=t.fragments;for(let t=0,n=r.length;t<n;t++)Em(r[t],e);t.fragmentHint&&Em(t.fragmentHint,e),t.alignedSliding=!0}function Sm(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 Ef.log("No fragments to align");const i=wm(n,s[0].cc);if(i&&(!i||i.startPTS))return i;Ef.log("No frag in previous level to align on")}(r.details,t);e&&ff(e.start)&&(Ef.log(`Adjusting PTS using last level due to CC increase within current level ${t.url}`),Tm(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&&ff(s)&&(Ef.log(`Adjusting PTS using programDateTime delta ${n-r}ms, sliding:${s.toFixed(3)} ${e.url} `),Tm(s,e))}(r,t.details),r.alignedSliding||!t.details||r.skippedSegments||Og(t.details,r))}function Cm(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=wm(r,s.cc)||r[Math.round(r.length/2)-1],o=s.programDateTime,a=i.programDateTime;if(null===o||null===a)return;Tm((a-o)/1e3-(i.start-s.start),e)}class km{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 Am{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 _m{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],o=r[3],a=this.invSubMix,l=a[0],c=a[1],u=a[2],d=a[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 a=h[f],g=h[a],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,o[f]=y,y=16843009*m^65537*g^257*a^16843008*f,l[r]=y<<24|y>>>8,c[r]=y<<16|y>>>16,u[r]=y<<8|y>>>24,d[r]=y,f?(f=a^h[h[h[m^a]]],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 o,a;const l=this.keySchedule=new Uint32Array(i),c=this.invKeySchedule=new Uint32Array(i),u=this.sBox,d=this.rcon,h=this.invSubMix,f=h[0],p=h[1],g=h[2],m=h[3];let y,v;for(o=0;o<i;o++)o<s?y=l[o]=t[o]:(v=y,o%s==0?(v=v<<8|v>>>24,v=u[v>>>24]<<24|u[v>>>16&255]<<16|u[v>>>8&255]<<8|u[255&v],v^=d[o/s|0]<<24):s>6&&o%s==4&&(v=u[v>>>24]<<24|u[v>>>16&255]<<16|u[v>>>8&255]<<8|u[255&v]),l[o]=y=(l[o-s]^v)>>>0);for(a=0;a<i;a++)o=i-a,v=3&a?l[o]:l[o-4],c[a]=a<4||o<=4?v:f[u[v>>>24]]^p[u[v>>>16&255]]^g[u[v>>>8&255]]^m[u[255&v]],c[a]=c[a]>>>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,o=this.invSubMix,a=o[0],l=o[1],c=o[2],u=o[3],d=this.uint8ArrayToUint32Array_(r);let h=d[0],f=d[1],p=d[2],g=d[3];const m=new Int32Array(e),y=new Int32Array(m.length);let v,b,w,E,T,S,C,k,A,_,I,R,L,D;const x=this.networkToHostOrderSwap;for(;t<m.length;){for(A=x(m[t]),_=x(m[t+1]),I=x(m[t+2]),R=x(m[t+3]),T=A^s[0],S=R^s[1],C=I^s[2],k=_^s[3],L=4,D=1;D<n;D++)v=a[T>>>24]^l[S>>16&255]^c[C>>8&255]^u[255&k]^s[L],b=a[S>>>24]^l[C>>16&255]^c[k>>8&255]^u[255&T]^s[L+1],w=a[C>>>24]^l[k>>16&255]^c[T>>8&255]^u[255&S]^s[L+2],E=a[k>>>24]^l[T>>16&255]^c[S>>8&255]^u[255&C]^s[L+3],T=v,S=b,C=w,k=E,L+=4;v=i[T>>>24]<<24^i[S>>16&255]<<16^i[C>>8&255]<<8^i[255&k]^s[L],b=i[S>>>24]<<24^i[C>>16&255]<<16^i[k>>8&255]<<8^i[255&T]^s[L+1],w=i[C>>>24]<<24^i[k>>16&255]<<16^i[T>>8&255]<<8^i[255&S]^s[L+2],E=i[k>>>24]<<24^i[T>>16&255]<<16^i[S>>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=_,p=I,g=R,t+=4}return y.buffer}}class Im{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?Wf(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=kp(i,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;n&&(r=n);let a=this.softwareDecrypter;a||(a=this.softwareDecrypter=new _m),a.expandKey(t);const l=s;return this.currentResult=a.decrypt(o.buffer,0,r),this.currentIV=Wf(o,-16).buffer,l||null}webCryptoDecrypt(e,t,r){const n=this.subtle;return this.key===t&&this.fastAesKey||(this.key=t,this.fastAesKey=new Am(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 km(n,new Uint8Array(r)).decrypt(e.buffer,t)})).catch((n=>(Ef.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=Wf(e,0,r),this.remainderData=Wf(e,r)),t}logOnce(e){this.logEnabled&&(Ef.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Rm=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},Lm="STOPPED",Dm="IDLE",xm="KEY_LOADING",Om="FRAG_LOADING",Pm="FRAG_LOADING_WAITING_RETRY",Mm="WAITING_TRACK",Fm="PARSING",Nm="PARSED",Um="ENDED",Bm="ERROR",jm="WAITING_INIT_PTS",$m="WAITING_LEVEL";class qm 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=Lm,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=Ef.log.bind(Ef,`${n}:`),this.warn=Ef.warn.bind(Ef,`${n}:`),this.hls=e,this.fragmentLoader=new hm(e.config),this.keyLoader=r,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Im(e.config),e.on(pf.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=Lm}_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 vm.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===Lm&&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,o=vm.bufferInfo(n||r,i,e.maxBufferHole);if(this.log(`media seeking to ${ff(i)?i.toFixed(3):i}, state: ${s}`),this.state===Um)this.resetLoadingState();else if(t){const r=e.maxFragLookUpTolerance,n=t.start-r,s=t.start+t.duration+r;if(!o.len||s<o.start||n>o.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||o.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=Lm,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===Om||!this.fragCurrent&&r===Fm)&&(this.fragmentTracker.removeFragment(e),this.state=Dm):("payload"in t&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(pf.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))})).catch((t=>{this.state!==Lm&&this.state!==Bm&&(this.warn(t),this.resetFragmentLoading(e))}))}clearTrackerIfNeeded(e){var t;const{fragmentTracker:r}=this;if(r.getState(e)===im){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)===om&&r.removeFragment(e))}flushMainBuffer(e,t,r=null){if(!(e-t))return;const n={startOffset:e,endOffset:t,type:r};this.hls.trigger(pf.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(pf.ERROR,{type:gf.MEDIA_ERROR,details:mf.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t})).then((n=>{const s=self.performance.now();return r.trigger(pf.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 o=e.stats;this.state=Dm,t.fragmentError=0,e.data=new Uint8Array(r.payload),o.parsing.start=o.buffering.start=self.performance.now(),o.parsing.end=o.buffering.end=self.performance.now(),r.frag===n&&s.trigger(pf.FRAG_BUFFERED,{stats:o,frag:n,part:null,id:e.type}),this.tick()})).catch((t=>{this.state!==Lm&&this.state!==Bm&&(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 o=this.mediaBuffer?this.mediaBuffer:this.media;this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.playlistType===og?"level":"track"} ${e.level} (frag:[${(null!=(r=e.startPTS)?r:NaN).toFixed(3)}-${(null!=(n=e.endPTS)?n:NaN).toFixed(3)}] > buffer:${o?Rm(vm.getBuffered(o)):"(detached)"})`),this.state=Dm,o&&(!this.loadedmetadata&&e.type==og&&o.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)),o=new bm(r.level,r.sn,r.stats.chunkCount+1,0,n?n.index:-1,!i);t.flush(o)}_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 o=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=xm,this.fragCurrent=e,o=this.keyLoader.load(e).then((e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(pf.KEY_LOADED,e),this.state===xm&&(this.state=Dm),e})),this.hls.trigger(pf.KEY_LOADING,{frag:e}),null===this.fragCurrent&&(o=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 a=this.getNextPart(s,e,r);if(a>-1){const l=s[a];let c;return this.log(`Loading part sn: ${e.sn} p: ${l.index} cc: ${e.cc} of playlist [${i.startSN}-${i.endSN}] parts [0-${a}-${s.length-1}] ${"[stream-controller]"===this.logPrefix?"level":"track"}: ${e.level}, target: ${parseFloat(r.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=Om,c=o?o.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(pf.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))}`),ff(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Om;const a=this.config.progressive;let l;return l=a&&o?o.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,a?n:void 0),o]).then((([e])=>(!a&&e&&n&&n(e),e))).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(pf.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 o;const a=[],l=null==(o=r.details)?void 0:o.partList,c=t=>{this.fragmentLoader.loadPart(e,t,n).then((n=>{a[t.index]=n;const i=n.part;this.hls.trigger(pf.FRAG_LOADED,n);const o=Mg(r,e.sn,t.index+1)||Fg(l,e.sn,t.index+1);if(!o)return s({frag:e,part:i,partsLoaded:a});c(o)})).catch(i)};c(t)}))}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===mf.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(pf.ERROR,t)}else this.hls.trigger(pf.ERROR,{type:gf.OTHER_ERROR,details:mf.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==Fm)return void(this.fragCurrent||this.state===Lm||this.state===Bm||(this.state=Dm));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 o=t[n],a=i>-1?Mg(o,s,i):null,l=a?a.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)}(o,s,r);return l?(r&&r!==l&&(l.stats=r.stats),{frag:l,part:a,level:o}):null}bufferFragmentData(e,t,r,n,s){var i;if(!e||this.state!==Fm)return;const{data1:o,data2:a}=e;let l=o;if(o&&a&&(l=kp(o,a)),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(pf.BUFFER_APPENDING,c),e.dropped&&e.independent&&!r){if(s)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!vm.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);const r=t.currentTime,n=vm.bufferInfo(t,r,0),s=e.duration,i=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),o=Math.max(Math.min(e.start-i,n.end-i),r+i);e.start-o>i&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){const r=this.getLoadPosition();return ff(r)?this.getFwdBufferInfoAtPos(e,r,t):null}getFwdBufferInfoAtPos(e,t,r){const{config:{maxBufferHole:n}}=this,s=vm.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 vm.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=og){const r=this.fragmentTracker.getAppendedFrag(e,og);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 o;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||(o=this.getInitialLiveFragment(t,r),this.startPosition=o?this.hls.liveSyncPosition||o.start:e)}else e<=i&&(o=r[0]);if(!o){const r=s.lowLatencyMode?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,r,t)}return this.mapToInitFragWhenRequired(o)}isLoopLoading(e,t){const r=this.fragmentTracker.getState(e);return(r===am||r===om&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,r,n,s){const i=e.gap,o=this.getNextFragment(this.nextLoadPosition,t);if(null===o)return o;if(e=o,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 o=0,a=e.length;o<a;o++){const a=e[o];if(i=i&&!a.independent,n>-1&&r<a.start)break;const l=a.loaded;l?n=-1:(s||a.independent||i)&&a.fragment===t&&(n=o),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||!ff(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(Hg(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 qg(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:o}=r;const{fragmentHint:a}=r,l=n.maxFragLookUpTolerance,c=r.partList,u=!!(n.lowLatencyMode&&null!=c&&c.length&&a);let d;if(u&&a&&!this.bitrateTest&&(i=i.concat(a),o=a.sn),e<t){d=Kg(s,i,e,e>t-l?0:l)}else d=i[i.length-1];if(d){const e=d.sn-r.startSN,t=this.fragmentTracker.getState(d);if((t===am||t===om&&d.gap)&&(s=d),s&&d.sn===s.sn&&(!u||c[0].fragment.sn>d.sn)){if(s&&d.level===s.level){const t=i[e+1];d=d.sn<o&&this.fragmentTracker.getState(t)!==am?t:null}}}return d}synchronizeToLiveEdge(e){const{config:t,media:r}=this;if(!r)return;const n=this.hls.liveSyncPosition,s=r.currentTime,i=e.fragments[0].start,o=e.edge,a=s>=i-t.maxFragLookUpTolerance&&s<=o;if(null!==n&&r.duration>n&&(s<n||!a)){const i=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!a&&r.readyState<4||s<o-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: ${o}, 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,o=e.fragments.length;if(!o)return this.warn("No fragments in live playlist"),0;const a=e.fragments[0].start,l=!t,c=e.alignedSliding&&ff(a);if(l||!c&&!a){Sm(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: ${o}`),r}return a}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&&ff(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===Pm)||(this.state=Dm)}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===mf.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(r,!0);const i=t.errorAction,{action:o,retryCount:a=0,retryConfig:l}=i||{};if(i&&o===Wg&&l){var c;this.resetStartWhenNotLoaded(null!=(c=this.levelLastLoaded)?c:r.level);const n=Bg(l,a);this.warn(`Fragment ${r.sn} of ${e} ${r.level} errored with ${t.details}, retrying loading ${a+1}/${l.maxNumRetry} in ${n}ms`),i.resolved=!0,this.retryDate=self.performance.now()+n,this.state=Pm}else l&&i?(this.resetFragmentErrors(e),a<l.maxNumRetry?s||(i.resolved=!0):Ef.warn(`${t.details} reached or exceeded max retry (${a})`)):(null==i?void 0:i.action)===zg?this.state=$m:this.state=Bm;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===Fm||this.state===Nm){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===ag&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==Lm&&(this.state=Dm)}afterBufferFlushed(e,t,r){if(!e)return;const n=vm.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,r),this.state===Um&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=Dm}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 o=e.elementaryStreams[s];if(o){const a=o.endPTS-o.startPTS;if(a<=0)return this.warn(`Could not parse fragment ${e.sn} ${s} duration reliably (${a})`),t||!1;const l=n?0:Dg(i,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS);return this.hls.trigger(pf.LEVEL_PTS_UPDATED,{details:i,level:r,drift:l,type:s,frag:e,start:o.startPTS,end:o.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(pf.ERROR,{type:gf.MEDIA_ERROR,details:mf.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=Nm,this.hls.trigger(pf.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 Km(){return self.SourceBuffer||self.WebKitSourceBuffer}function Gm(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class Hm{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=kp(this.cachedData,e),this.cachedData=null);let r,n=Xf(e,0),s=n?n.length:0;const i=this._audioTrack,o=this._id3Track,a=n?(e=>{const t=rp(e);for(let e=0;e<t.length;e++){const r=t[e];if(ep(r))return ap(r)}})(n):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&ff(a))&&(this.basePTS=Vm(a,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),n&&n.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:mg,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 Zf(e,s)?(n=Xf(e,s),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:mg,duration:Number.POSITIVE_INFINITY}),s+=n.length,r=s):s++;if(s===l&&r!==l){const t=Wf(e,r);this.cachedData?this.cachedData=kp(this.cachedData,t):this.cachedData=t}}return{audioTrack:i,videoTrack:Gm(),id3Track:o,textTrack:Gm()}}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:Gm(),id3Track:this._id3Track,textTrack:Gm()}}destroy(){}}const Vm=(e,t,r)=>{if(ff(e))return 90*e;return 9e4*t+(r?9e4*r.baseTime/r.timescale:0)};function zm(e,t){return 255===e[t]&&240==(246&e[t+1])}function Wm(e,t){return 1&e[t+1]?7:9}function Ym(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function Qm(e,t){return t+1<e.length&&zm(e,t)}function Xm(e,t){if(Qm(e,t)){const r=Wm(e,t);if(t+r>=e.length)return!1;const n=Ym(e,t);if(n<=r)return!1;const s=t+n;return s===e.length||Qm(e,s)}return!1}function Jm(e,t,r,n,s){if(!e.samplerate){const i=function(e,t,r,n){let s,i,o,a;const l=navigator.userAgent.toLowerCase(),c=n,u=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=1+((192&t[r+2])>>>6);const d=(60&t[r+2])>>>2;if(!(d>u.length-1))return o=(1&t[r+2])<<2,o|=(192&t[r+3])>>>6,Ef.log(`manifest codec:${n}, ADTS type:${s}, samplingIndex:${d}`),/firefox/i.test(l)?d>=6?(s=5,a=new Array(4),i=d-3):(s=2,a=new Array(2),i=d):-1!==l.indexOf("android")?(s=2,a=new Array(2),i=d):(s=5,a=new Array(4),n&&(-1!==n.indexOf("mp4a.40.29")||-1!==n.indexOf("mp4a.40.5"))||!n&&d>=6?i=d-3:((n&&-1!==n.indexOf("mp4a.40.2")&&(d>=6&&1===o||/vivaldi/i.test(l))||!n&&1===o)&&(s=2,a=new Array(2)),i=d)),a[0]=s<<3,a[0]|=(14&d)>>1,a[1]|=(1&d)<<7,a[1]|=o<<3,5===s&&(a[1]|=(14&i)>>1,a[2]=(1&i)<<7,a[2]|=8,a[3]=0),{config:a,samplerate:u[d],channelCount:o,codec:"mp4a.40."+s,manifestCodec:c};e.trigger(pf.ERROR,{type:gf.MEDIA_ERROR,details:mf.FRAG_PARSING_ERROR,fatal:!0,reason:`invalid ADTS sampling index:${d}`})}(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,Ef.log(`parsed codec:${e.codec}, rate:${i.samplerate}, channels:${i.channelCount}`)}}function Zm(e){return 9216e4/e}function ey(e,t,r,n,s){const i=n+s*Zm(e.samplerate),o=function(e,t){const r=Wm(e,t);if(t+r<=e.length){const n=Ym(e,t)-r;if(n>0)return{headerLength:r,frameLength:n}}}(t,r);let a;if(o){const{frameLength:n,headerLength:s}=o,l=s+n,c=Math.max(0,r+l-t.length);c?(a=new Uint8Array(l-s),a.set(t.subarray(r+s,t.length),0)):a=t.subarray(r+s,r+l);const u={unit:a,pts:i};return c||e.samples.push(u),{sample:u,length:l,missing:c}}const l=t.length-r;a=new Uint8Array(l),a.set(t.subarray(r,t.length),0);return{sample:{unit:a,pts:i},length:l,missing:-1}}const ty=/\/emsg[-/]ID3/i;let ry=null;const ny=[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],sy=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],iy=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],oy=[0,1,1,4];function ay(e,t,r,n,s){if(r+24>t.length)return;const i=ly(t,r);if(i&&r+i.frameLength<=t.length){const o=n+s*(9e4*i.samplesPerFrame/i.sampleRate),a={unit:t.subarray(r,r+i.frameLength),pts:o,dts:o};return e.config=[],e.channelCount=i.channelCount,e.samplerate=i.sampleRate,e.samples.push(a),{sample:a,length:i.frameLength,missing:0}}}function ly(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 o=e[t+2]>>1&1,a=e[t+3]>>6,l=1e3*ny[14*(3===r?3-n:3===n?3:4)+s-1],c=sy[3*(3===r?0:2===r?1:2)+i],u=3===a?1:2,d=iy[r][n],h=oy[n],f=8*d*h,p=Math.floor(d*l/c+o)*h;if(null===ry){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ry=e?parseInt(e[1]):0}return!!ry&&ry<=87&&2===n&&l>=224e3&&0===a&&(e[t+3]=128|e[t+3]),{sampleRate:c,channelCount:u,frameLength:p,samplesPerFrame:f}}}function cy(e,t){return 255===e[t]&&224==(224&e[t+1])&&0!=(6&e[t+1])}function uy(e,t){return t+1<e.length&&cy(e,t)}function dy(e,t){if(t+1<e.length&&cy(e,t)){const r=4,n=ly(e,t);let s=r;null!=n&&n.frameLength&&(s=n.frameLength);const i=t+s;return i===e.length||uy(e,i)}return!1}class hy{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&&Ef.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,o=0;const a=this.readUByte.bind(this),l=this.readBits.bind(this),c=this.readUEG.bind(this),u=this.readBoolean.bind(this),d=this.skipBits.bind(this),h=this.skipEG.bind(this),f=this.skipUEG.bind(this),p=this.skipScalingList.bind(this);a();const g=a();if(l(5),d(3),a(),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&&d(1),f(),f(),d(1),u())for(t=3!==e?8:12,r=0;r<t;r++)u()&&p(r<6?16:64)}f();const m=c();if(0===m)c();else if(1===m)for(d(1),h(),h(),e=c(),r=0;r<e;r++)h();f(),d(1);const y=c(),v=c(),b=l(1);0===b&&d(1),d(1),u()&&(n=c(),s=c(),i=c(),o=c());let w=[1,1];if(u()&&u()){switch(a()){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=[a()<<8|a(),a()<<8|a()]}}return{width:Math.ceil(16*(y+1)-2*n-2*s),height:(2-b)*(v+1)*16-(b?2:4)*(i+o),pixelRatio:w}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class fy{constructor(e,t,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new Im(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=Rp(s.data),o=this.getAvcEncryptedData(i);this.decryptBuffer(o.buffer).then((o=>{s.data=this.getAvcDecryptedUnit(i,o),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 py=188;class gy{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=gy.syncOffset(e);return t>0&&Ef.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-py)+1,n=0;for(;n<r;){let s=!1,i=-1,o=0;for(let a=n;a<t;a+=py){if(71!==e[a]){if(o)return-1;break}if(o++,-1===i&&(i=a,0!==i&&(r=Math.min(i+18612,e.length-py)+1)),s||(s=0===yy(e,a)),s&&o>1&&(0===i&&o>2||a+py>r))return i}n++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:pp[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=gy.createTrack("video"),this._audioTrack=gy.createTrack("audio",n),this._id3Track=gy.createTrack("id3"),this._txtTrack=gy.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,o=this._audioTrack,a=this._id3Track,l=this._txtTrack;let c=i.pid,u=i.pesData,d=o.pid,h=a.pid,f=o.pesData,p=a.pesData,g=null,m=this.pmtParsed,y=this._pmtId,v=e.length;if(this.remainderData&&(v=(e=kp(this.remainderData,e)).length,this.remainderData=null),v<py&&!n)return this.remainderData=e,{audioTrack:o,videoTrack:i,id3Track:a,textTrack:l};const b=Math.max(0,gy.syncOffset(e));v-=(v-b)%py,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+=py)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+py)continue}else w=t+4;switch(v){case c:n&&(u&&(s=wy(u))&&this.parseAVCPES(i,l,s,!1),u={data:[],size:0}),u&&(u.data.push(e.subarray(w,t+py)),u.size+=t+py-w);break;case d:if(n){if(f&&(s=wy(f)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,s);break;case"mp3":this.parseMPEGPES(o,s)}f={data:[],size:0}}f&&(f.data.push(e.subarray(w,t+py)),f.size+=t+py-w);break;case h:n&&(p&&(s=wy(p))&&this.parseID3PES(a,s),p={data:[],size:0}),p&&(p.data.push(e.subarray(w,t+py)),p.size+=t+py-w);break;case 0:n&&(w+=e[w]+1),y=this._pmtId=vy(e,w);break;case y:{n&&(w+=e[w]+1);const s=by(e,w,this.typeSupported,r);c=s.avc,c>0&&(i.pid=c),d=s.audio,d>0&&(o.pid=d,o.segmentCodec=s.segmentCodec),h=s.id3,h>0&&(a.pid=h),null===g||m||(Ef.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(pf.ERROR,pf.ERROR,{type:gf.MEDIA_ERROR,details:mf.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message})}i.pesData=u,o.pesData=f,a.pesData=p;const E={audioTrack:o,videoTrack:i,id3Track:a,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,o=t.pesData,a=n.pesData;let l;if(i&&(l=wy(i))?(this.parseAVCPES(r,s,l,!0),r.pesData=null):r.pesData=i,o&&(l=wy(o))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l)}t.pesData=null}else null!=o&&o.size&&Ef.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;a&&(l=wy(a))?(this.parseID3PES(n,l),n.pesData=null):n.pesData=a}demuxSampleAes(e,t,r){const n=this.demux(e,r,!0,!this.config.progressive),s=this.sampleAes=new fy(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,o=this.avcSample,a=!1;r.data=null,o&&s.length&&!e.audFound&&(Ey(o,e),o=this.avcSample=my(!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(a&&s.length>4){const e=new hy(s).readSliceType();2!==e&&4!==e&&7!==e&&9!==e||(t=!0)}var l;if(t)null!=(l=o)&&l.frame&&!o.key&&(Ey(o,e),o=this.avcSample=null);o||(o=this.avcSample=my(!0,r.pts,r.dts,"")),o.frame=!0,o.key=t;break}case 5:i=!0,null!=(s=o)&&s.frame&&!o.key&&(Ey(o,e),o=this.avcSample=null),o||(o=this.avcSample=my(!0,r.pts,r.dts,"")),o.key=!0,o.frame=!0;break;case 6:i=!0,Ip(n.data,1,r.pts,t.samples);break;case 7:if(i=!0,a=!0,!e.sps){const t=n.data,r=new hy(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,o&&Ey(o,e),o=this.avcSample=my(!1,r.pts,r.dts,"");break;case 12:i=!0;break;default:i=!1,o&&(o.debug+="unknown NAL "+n.type+" ")}if(o&&i){o.units.push(n)}})),n&&o&&(Ey(o,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 o,a,l,c=0,u=-1,d=0;for(-1===n&&(u=0,d=31&t[0],n=0,c=1);c<r;)if(o=t[c++],n)if(1!==n)if(o)if(1===o){if(u>=0){const e={data:t.subarray(u,c-n-1),type:d};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)),a=c-n-1,a>0)){const e=new Uint8Array(r.data.byteLength+a);e.set(r.data,0),e.set(t.subarray(0,a),r.data.byteLength),r.data=e,r.state=0}}c<r?(l=31&t[c],u=c,d=l,n=0):n=-1}else n=0;else n=3;else n=o?0:2;else n=o?0:1;if(u>=0&&n>=0){const e={data:t.subarray(u,r),type:d,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,o,a=t.data;if(n){this.aacOverFlow=null;const t=n.missing,s=n.sample.unit.byteLength;if(-1===t){const e=new Uint8Array(s+a.byteLength);e.set(n.sample.unit,0),e.set(a,s),a=e}else{const i=s-t;n.sample.unit.set(a.subarray(0,t),i),e.samples.push(n.sample),r=n.missing}}for(s=r,i=a.length;s<i-1&&!Qm(a,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(Ef.warn(`parsing error: ${e}`),this.observer.emit(pf.ERROR,pf.ERROR,{type:gf.MEDIA_ERROR,details:mf.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:r,reason:e}),!t)return}if(Jm(e,this.observer,a,s,this.audioCodec),void 0!==t.pts)o=t.pts;else{if(!n)return void Ef.warn("[tsdemuxer]: AAC PES unknown PTS");{const t=Zm(e.samplerate);o=n.sample.pts+t}}let l,c=0;for(;s<i;){if(l=ey(e,a,s,o,c),s+=l.length,l.missing){this.aacOverFlow=l;break}for(c++;s<i-1&&!Qm(a,s);s++);}}parseMPEGPES(e,t){const r=t.data,n=r.length;let s=0,i=0;const o=t.pts;if(void 0!==o)for(;i<n;)if(uy(r,i)){const t=ay(e,r,i,o,s);if(!t)break;i+=t.length,s++}else i++;else Ef.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseID3PES(e,t){if(void 0===t.pts)return void Ef.warn("[tsdemuxer]: ID3 PES unknown PTS");const r=hf({},t,{type:this._avcTrack?vg:mg,duration:Number.POSITIVE_INFINITY});e.samples.push(r)}}function my(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 vy(e,t){return(31&e[t+10])<<8|e[t+11]}function by(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){Ef.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){Ef.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?Ef.log("MPEG audio found, not supported in this browser"):-1===s.audio&&(s.audio=i,s.segmentCodec="mp3");break;case 36:Ef.warn("Unsupported HEVC stream type found")}t+=5+((15&e[t+3])<<8|e[t+4])}return s}function wy(e){let t,r,n,s,i,o=0;const a=e.data;if(!e||0===e.size)return null;for(;a[0].length<19&&a.length>1;){const e=new Uint8Array(a[0].length+a[1].length);e.set(a[0]),e.set(a[1],a[0].length),a[0]=e,a.splice(1,1)}t=a[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&&(Ef.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 u=new Uint8Array(e.size);for(let e=0,r=a.length;e<r;e++){t=a[e];let r=t.byteLength;if(c){if(c>r){c-=r;continue}t=t.subarray(c),r-=c,c=0}u.set(t,o),o+=r}return r&&(r-=n+3),{data:u,pts:s,dts:i,len:r}}return null}function Ey(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&&Ef.log(e.pts+"/"+e.dts+":"+e.debug)}class Ty{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 Sy=Math.pow(2,32)-1;class Cy{static init(){let e;for(e in Cy.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:[]},Cy.types)Cy.types.hasOwnProperty(e)&&(Cy.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]);Cy.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]);Cy.STTS=Cy.STSC=Cy.STCO=s,Cy.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Cy.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Cy.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Cy.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const i=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),a=new Uint8Array([0,0,0,1]);Cy.FTYP=Cy.box(Cy.types.ftyp,i,a,i,o),Cy.DINF=Cy.box(Cy.types.dinf,Cy.box(Cy.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 Cy.box(Cy.types.hdlr,Cy.HDLR_TYPES[e])}static mdat(e){return Cy.box(Cy.types.mdat,e)}static mdhd(e,t){t*=e;const r=Math.floor(t/(Sy+1)),n=Math.floor(t%(Sy+1));return Cy.box(Cy.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 Cy.box(Cy.types.mdia,Cy.mdhd(e.timescale,e.duration),Cy.hdlr(e.type),Cy.minf(e))}static mfhd(e){return Cy.box(Cy.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?Cy.box(Cy.types.minf,Cy.box(Cy.types.smhd,Cy.SMHD),Cy.DINF,Cy.stbl(e)):Cy.box(Cy.types.minf,Cy.box(Cy.types.vmhd,Cy.VMHD),Cy.DINF,Cy.stbl(e))}static moof(e,t,r){return Cy.box(Cy.types.moof,Cy.mfhd(e),Cy.traf(r,t))}static moov(e){let t=e.length;const r=[];for(;t--;)r[t]=Cy.trak(e[t]);return Cy.box.apply(null,[Cy.types.moov,Cy.mvhd(e[0].timescale,e[0].duration)].concat(r).concat(Cy.mvex(e)))}static mvex(e){let t=e.length;const r=[];for(;t--;)r[t]=Cy.trex(e[t]);return Cy.box.apply(null,[Cy.types.mvex,...r])}static mvhd(e,t){t*=e;const r=Math.floor(t/(Sy+1)),n=Math.floor(t%(Sy+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 Cy.box(Cy.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 Cy.box(Cy.types.sdtp,r)}static stbl(e){return Cy.box(Cy.types.stbl,Cy.stsd(e),Cy.box(Cy.types.stts,Cy.STTS),Cy.box(Cy.types.stsc,Cy.STSC),Cy.box(Cy.types.stsz,Cy.STSZ),Cy.box(Cy.types.stco,Cy.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 o=Cy.box(Cy.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|e.sps.length].concat(s).concat([e.pps.length]).concat(i))),a=e.width,l=e.height,c=e.pixelRatio[0],u=e.pixelRatio[1];return Cy.box(Cy.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,a>>8&255,255&a,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]),o,Cy.box(Cy.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Cy.box(Cy.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,255&c,u>>24,u>>16&255,u>>8&255,255&u])))}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 Cy.box(Cy.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]),Cy.box(Cy.types.esds,Cy.esds(e)))}static mp3(e){const t=e.samplerate;return Cy.box(Cy.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?Cy.box(Cy.types.stsd,Cy.STSD,Cy.mp3(e)):Cy.box(Cy.types.stsd,Cy.STSD,Cy.mp4a(e)):Cy.box(Cy.types.stsd,Cy.STSD,Cy.avc1(e))}static tkhd(e){const t=e.id,r=e.duration*e.timescale,n=e.width,s=e.height,i=Math.floor(r/(Sy+1)),o=Math.floor(r%(Sy+1));return Cy.box(Cy.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,o>>24,o>>16&255,o>>8&255,255&o,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=Cy.sdtp(e),n=e.id,s=Math.floor(t/(Sy+1)),i=Math.floor(t%(Sy+1));return Cy.box(Cy.types.traf,Cy.box(Cy.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),Cy.box(Cy.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])),Cy.trun(e,r.length+16+20+8+16+8+8),r)}static trak(e){return e.duration=e.duration||4294967295,Cy.box(Cy.types.trak,Cy.tkhd(e),Cy.mdia(e))}static trex(e){const t=e.id;return Cy.box(Cy.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 o,a,l,c,u,d;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),o=0;o<n;o++)a=r[o],l=a.duration,c=a.size,u=a.flags,d=a.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,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,61440&u.degradPrio,15&u.degradPrio,d>>>24&255,d>>>16&255,d>>>8&255,255&d],12+16*o);return Cy.box(Cy.types.trun,i)}static initSegment(e){Cy.types||Cy.init();const t=Cy.moov(e),r=new Uint8Array(Cy.FTYP.byteLength+t.byteLength);return r.set(Cy.FTYP),r.set(t,Cy.FTYP.byteLength),r}}Cy.types=void 0,Cy.HDLR_TYPES=void 0,Cy.STTS=void 0,Cy.STSC=void 0,Cy.STCO=void 0,Cy.STSZ=void 0,Cy.VMHD=void 0,Cy.SMHD=void 0,Cy.STSD=void 0,Cy.FTYP=void 0,Cy.DINF=void 0;function ky(e,t,r=1,n=!1){const s=e*t*r;return n?Math.round(s):s}function Ay(e,t=!1){return ky(e,1e3,1/9e4,t)}let _y,Iy=null,Ry=null;class Ly{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===Iy){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Iy=e?parseInt(e[1]):0}if(null===Ry){const e=navigator.userAgent.match(/Safari\/(\d+)/i);Ry=e?parseInt(e[1]):0}}destroy(){}resetTimeStamp(e){Ef.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){Ef.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){Ef.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,Dy(e,r.pts)):n>0?e:r.pts}),e[0].pts);return t&&Ef.debug("PTS rollover detected"),r}remux(e,t,r,n,s,i,o,a){let l,c,u,d,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=o&&v>0||v>1;if((!m||b)&&(!y||w)||this.ISGenerated||o){this.ISGenerated||(u=this.generateIS(e,t,s,i));const r=this.isVideoContiguous;let n,o=-1;if(w&&(o=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,o>0){Ef.warn(`[mp4-remuxer]: Dropped ${o} out of ${v} video samples due to a missing keyframe`);const e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(o),t.dropped+=o,g+=(t.samples[0].pts-e)/t.inputTimeScale,n=g}else-1===o&&(Ef.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=(Dy(e.samples[0].pts,r)-r)/t.inputTimeScale;p+=Math.max(0,n),g+=Math.max(0,-n)}if(b){if(e.samplerate||(Ef.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),u=this.generateIS(e,t,s,i)),c=this.remuxAudio(e,p,this.isAudioContiguous,i,y||w||a===ag?g:void 0),w){const n=c?c.endPTS-c.startPTS:0;t.inputTimeScale||(Ef.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),u=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=o,l.independent=-1!==o,l.firstKeyFramePTS=n)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(h=xy(r,s,this._initPTS,this._initDTS)),n.samples.length&&(d=Oy(n,s,this._initPTS))),{audio:c,video:l,initSegment:u,independent:f,text:d,id3:h}}generateIS(e,t,r,n){const s=e.samples,i=t.samples,o=this.typeSupported,a={},l=this._initPTS;let c,u,d,h=!l||n,f="audio/mp4";if(h&&(c=u=1/0),e.config&&s.length){if(e.timescale=e.samplerate,"mp3"===e.segmentCodec)o.mpeg?(f="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");a.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&o.mpeg?new Uint8Array(0):Cy.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(d=e.inputTimeScale,l&&d===l.timescale?h=!1:c=u=s[0].pts-Math.round(d*r))}if(t.sps&&t.pps&&i.length&&(t.timescale=t.inputTimeScale,a.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Cy.initSegment([t]),metadata:{width:t.width,height:t.height}},h))if(d=t.inputTimeScale,l&&d===l.timescale)h=!1;else{const e=this.getVideoStartPts(i),t=Math.round(d*r);u=Math.min(u,Dy(i[0].dts,e)-t),c=Math.min(c,e-t)}if(Object.keys(a).length)return this.ISGenerated=!0,h?(this._initPTS={baseTime:c,timescale:d},this._initDTS={baseTime:u,timescale:d}):c=d=void 0,{tracks:a,initPTS:c,timescale:d}}remuxVideo(e,t,r,n){const s=e.inputTimeScale,i=e.samples,o=[],a=i.length,l=this._initPTS;let c,u,d=this.nextAvcDts,h=8,f=this.videoSampleDuration,p=Number.POSITIVE_INFINITY,g=Number.NEGATIVE_INFINITY,m=!1;if(!r||null===d){d=t*s-(i[0].pts-Dy(i[0].dts,i[0].pts))}const y=l.baseTime*s/l.timescale;for(let e=0;e<a;e++){const t=i[e];t.pts=Dy(t.pts-y,d),t.dts=Dy(t.dts-y,d),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,u=i[i.length-1].dts;const v=u-c,b=v?Math.round(v/(a-1)):f||e.inputTimeScale/30;if(r){const e=c-d,t=e>b,r=e<-1;if((t||r)&&(t?Ef.warn(`AVC: ${Ay(e,!0)} ms (${e}dts) hole between fragments detected, filling it`):Ef.warn(`AVC: ${Ay(-e,!0)} ms (${e}dts) overlapping between fragments detected`),!r||d>=i[0].pts)){c=d;const t=i[0].pts-e;i[0].dts=c,i[0].pts=t,Ef.log(`Video: First PTS/DTS adjusted: ${Ay(t,!0)}/${Ay(c,!0)}, delta: ${Ay(e,!0)} ms`)}}c=Math.max(0,c);let w=0,E=0;for(let e=0;e<a;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)}u=i[a-1].dts;const T=E+4*w+8;let S;try{S=new Uint8Array(T)}catch(e){return void this.observer.emit(pf.ERROR,pf.ERROR,{type:gf.MUX_ERROR,details:mf.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:T,reason:`fail allocating video mdat ${T}`})}const C=new DataView(S.buffer);C.setUint32(0,T),S.set(Cy.types.mdat,4);let k=!1,A=Number.POSITIVE_INFINITY,_=Number.POSITIVE_INFINITY,I=Number.NEGATIVE_INFINITY,R=Number.NEGATIVE_INFINITY;for(let e=0;e<a;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,S.set(n,h),h+=s,c+=4+s}if(e<a-1)f=i[e+1].dts-t.dts,l=i[e+1].pts-t.pts;else{const r=this.config,o=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-o,f<0?f=o:k=!0,Ef.log(`[mp4-remuxer]: It is approximately ${i/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=o}else f=o}const u=Math.round(t.pts-t.dts);A=Math.min(A,f),I=Math.max(I,f),_=Math.min(_,l),R=Math.max(R,l),o.push(new Py(t.key,f,c,u))}if(o.length)if(Iy){if(Iy<70){const e=o[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(Ry&&R-_<I-A&&b/I<.025&&0===o[0].cts){Ef.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=o.length;t<r;t++){const n=e+o[t].duration,s=e+o[t].cts;if(t<r-1){const e=n+o[t+1].cts;o[t].duration=e-s}else o[t].duration=t?o[t-1].duration:b;o[t].cts=0,e=n}}f=k||!f?b:f,this.nextAvcDts=d=u+f,this.videoSampleDuration=f,this.isVideoContiguous=!0;const L={data1:Cy.moof(e.sequenceNumber++,c,hf({},e,{samples:o})),data2:S,startPTS:p/s,endPTS:(g+f)/s,startDTS:c/s,endDTS:d/s,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,L}remuxAudio(e,t,r,n,s){const i=e.inputTimeScale,o=i/(e.samplerate?e.samplerate:i),a="aac"===e.segmentCodec?1024:1152,l=a*o,c=this._initPTS,u="mp3"===e.segmentCodec&&this.typeSupported.mpeg,d=[],h=void 0!==s;let f=e.samples,p=u?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(Dy(f[0].pts-y,m)-g)<20*l),f.forEach((function(e){e.pts=Dy(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],o=s.pts,a=o-n,c=Math.abs(1e3*a/i);if(a<=-t*l&&h)0===r&&(Ef.warn(`Audio frame @ ${(o/i).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*a/i)} ms.`),this.nextAudioPts=g=n=o);else if(a>=t*l&&c<1e4&&h){let t=Math.round(a/l);n=o-t*l,n<0&&(t--,n+=l),0===r&&(this.nextAudioPts=g=n),Ef.warn(`[mp4-remuxer]: Injecting ${t} audio frame @ ${(n/i).toFixed(3)}s due to ${Math.round(1e3*a/i)} ms gap.`);for(let i=0;i<t;i++){const t=Math.max(n,0);let i=Ty.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);i||(Ef.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,T=f.length;for(;T--;)E+=f[T].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){d[t-1].duration=Math.round((i-w)/o)}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(pf.ERROR,pf.ERROR,{type:gf.MUX_ERROR,details:mf.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:E,reason:`fail allocating audio mdat ${E}`})}if(!u){new DataView(v.buffer).setUint32(0,E),v.set(Cy.types.mdat,4)}}v.set(s,p);const l=s.byteLength;p+=l,d.push(new Py(!0,a,l,0)),w=i}const S=d.length;if(!S)return;const C=d[d.length-1];this.nextAudioPts=g=w+o*C.duration;const k=u?new Uint8Array(0):Cy.moof(e.sequenceNumber++,b/o,hf({},e,{samples:d}));e.samples=[];const A=b/i,_=g/i,I={data1:k,data2:v,startPTS:A,endPTS:_,startDTS:A,endDTS:_,type:"audio",hasAudio:!0,hasVideo:!1,nb:S};return this.isAudioContiguous=!0,I}remuxEmptyAudio(e,t,r,n){const s=e.inputTimeScale,i=s/(e.samplerate?e.samplerate:s),o=this.nextAudioPts,a=this._initDTS,l=9e4*a.baseTime/a.timescale,c=(null!==o?o:n.startDTS*s)+l,u=n.endDTS*s+l,d=1024*i,h=Math.ceil((u-c)/d),f=Ty.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(Ef.warn("[mp4-remuxer]: remux empty Audio"),!f)return void Ef.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*d;p.push({unit:f,pts:t,dts:t})}return e.samples=p,this.remuxAudio(e,t,r,!1)}}function Dy(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 xy(e,t,r,n){const s=e.samples.length;if(!s)return;const i=e.inputTimeScale;for(let o=0;o<s;o++){const s=e.samples[o];s.pts=Dy(s.pts-r.baseTime*i/r.timescale,t*i)/i,s.dts=Dy(s.dts-n.baseTime*i/n.timescale,t*i)/i}const o=e.samples;return e.samples=[],{samples:o}}function Oy(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=Dy(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 Py{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 My(e)}}class My{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 Fy(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===Rf?"avc1.42e01e":"mp4a.40.5"}try{_y=self.performance.now.bind(self.performance)}catch(e){Ef.debug("Unable to use Performance API on this environment"),_y="undefined"!=typeof self&&self.Date.now}const Ny=[{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=Gm("video",1),i=this.audioTrack=Gm("audio",1),o=this.txtTrack=Gm("text",1);if(this.id3Track=Gm("id3",1),this.timeOffset=0,null==e||!e.byteLength)return;const a=Tp(e);if(a.video){const{id:e,timescale:t,codec:r}=a.video;s.id=e,s.timescale=o.timescale=t,s.codec=r}if(a.audio){const{id:e,timescale:t,codec:r}=a.audio;i.id=e,i.timescale=t,i.codec=r}o.id=pp.text,s.sampleDuration=0,s.duration=i.duration=n}resetContiguity(){this.remainderData=null}static probe(e){return wp(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=kp(this.remainderData,e));const t=function(e){const t={valid:null,remainder:null},r=wp(e,["moof"]);if(!r)return t;if(r.length<2)return t.remainder=e,t;const n=r[r.length-1];return t.valid=Wf(e,0,n.byteOffset-8),t.remainder=Wf(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=Ap(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=Ap(e,t),{videoTrack:t,audioTrack:Gm(),id3Track:n,textTrack:Gm()}}extractID3Track(e,t){const r=this.id3Track;if(e.samples.length){const n=wp(e.samples,["emsg"]);n&&n.forEach((e=>{const n=function(e){const t=e[0];let r="",n="",s=0,i=0,o=0,a=0,l=0,c=0;if(0===t){for(;"\0"!==gp(e.subarray(c,c+1));)r+=gp(e.subarray(c,c+1)),c+=1;for(r+=gp(e.subarray(c,c+1)),c+=1;"\0"!==gp(e.subarray(c,c+1));)n+=gp(e.subarray(c,c+1)),c+=1;n+=gp(e.subarray(c,c+1)),c+=1,s=yp(e,12),i=yp(e,16),a=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,o=2**32*t+i,Number.isSafeInteger(o)||(o=Number.MAX_SAFE_INTEGER,Ef.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),a=yp(e,c),c+=4,l=yp(e,c),c+=4;"\0"!==gp(e.subarray(c,c+1));)r+=gp(e.subarray(c,c+1)),c+=1;for(r+=gp(e.subarray(c,c+1)),c+=1;"\0"!==gp(e.subarray(c,c+1));)n+=gp(e.subarray(c,c+1)),c+=1;n+=gp(e.subarray(c,c+1)),c+=1}return{schemeIdUri:r,value:n,timeScale:s,presentationTime:o,presentationTimeDelta:i,eventDuration:a,id:l,payload:e.subarray(c,e.byteLength)}}(e);if(ty.test(n.schemeIdUri)){const e=ff(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:vg,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&&wp(e,["moov","trak"]).forEach((e=>{const t=wp(e,["mdia","minf","stbl","stsd"])[0].subarray(8);let n=wp(t,["enca"]);const s=n.length>0;s||(n=wp(t,["encv"])),n.forEach((e=>{wp(s?e.subarray(28):e.subarray(78),["sinf"]).forEach((e=>{const t=Sp(e);if(t){const e=t.subarray(8,24);e.some((e=>0!==e))||(Ef.log(`[eme] Patching keyId in 'enc${s?"a":"v"}>sinf>>tenc' box: ${dp(e)} -> ${dp(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=Tp(e);t||(t=Fy(n.audio,If)),r||(r=Fy(n.video,Rf));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"}:Ef.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=s}remux(e,t,r,n,s,i){var o,a;let{initPTS:l,lastEndTime:c}=this;const u={audio:void 0,video:void 0,text:n,id3:r,initSegment:void 0};ff(c)||(c=this.lastEndTime=s||0);const d=t.samples;if(null==d||!d.length)return u;const h={initPTS:void 0,timescale:1};let f=this.initData;if(null!=(o=f)&&o.length||(this.generateInitSegment(d),f=this.initData),null==(a=f)||!a.length)return Ef.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),u;this.emitInitSegment&&(h.tracks=this.initTracks,this.emitInitSegment=!1);const p=function(e,t){let r=0,n=0,s=0;const i=wp(e,["moof","traf"]);for(let e=0;e<i.length;e++){const o=i[e],a=wp(o,["tfhd"])[0],l=t[yp(a,4)];if(!l)continue;const c=l.default,u=yp(a,0)|(null==c?void 0:c.flags);let d=null==c?void 0:c.duration;8&u&&(d=yp(a,2&u?12:8));const h=l.timescale||9e4,f=wp(o,["trun"]);for(let e=0;e<f.length;e++)r=Cp(f[e]),!r&&d&&(r=d*yp(f[e],4)),l.type===Rf?n+=r/h:l.type===If&&(s+=r/h)}if(0===n&&0===s){let t=0;const r=wp(e,["sidx"]);for(let e=0;e<r.length;e++){const n=Ep(r[e]);null!=n&&n.references&&(t+=n.references.reduce(((e,t)=>e+t.info.duration||0),0))}return t}return n||s}(d,f),g=function(e,t){return wp(t,["moof","traf"]).reduce(((t,r)=>{const n=wp(r,["tfdt"])[0],s=n[0],i=wp(r,["tfhd"]).reduce(((t,r)=>{const i=yp(r,4),o=e[i];if(o){let e=yp(n,4);if(1===s){if(e===hp)return Ef.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),t;e*=hp+1,e+=yp(n,8)}const r=e/(o.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,d),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&&Ef.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){wp(t,["moof","traf"]).forEach((t=>{wp(t,["tfhd"]).forEach((n=>{const s=yp(n,4),i=e[s];if(!i)return;const o=i.timescale||9e4;wp(t,["tfdt"]).forEach((e=>{const t=e[0];let n=yp(e,4);if(0===t)n-=r*o,n=Math.max(n,0),bp(e,4,n);else{n*=Math.pow(2,32),n+=yp(e,8),n-=r*o,n=Math.max(n,0);const t=Math.floor(n/(hp+1)),s=Math.floor(n%(hp+1));bp(e,4,t),bp(e,8,s)}}))}))}))}(f,d,l.baseTime/l.timescale),p>0?this.lastEndTime=v:(Ef.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 T={data1:d,startPTS:y,startDTS:y,endPTS:v,endDTS:v,type:E,hasAudio:b,hasVideo:w,nb:1,dropped:0};return u.audio="audio"===T.type?T:void 0,u.video="audio"!==T.type?T:void 0,u.initSegment=h,u.id3=xy(r,s,l,l),n.samples.length&&(u.text=Oy(n,s,l)),u}}},{demux:gy,remux:Ly},{demux:class extends Hm{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=(Xf(e,0)||[]).length;for(let r=e.length;t<r;t++)if(Xm(e,t))return Ef.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)&&zm(e,t)&&Ym(e,t)<=e.length-t}(e,t)}appendFrame(e,t,r){Jm(e,this.observer,t,r,e.manifestCodec);const n=ey(e,t,r,this.basePTS,this.frameIndex);if(n&&0===n.missing)return n}},remux:Ly},{demux:class extends Hm{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=(Xf(e,0)||[]).length;for(let r=e.length;t<r;t++)if(dy(e,t))return Ef.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return cy(e,t)&&4<=e.length-t}(e,t)}appendFrame(e,t,r){if(null!==this.basePTS)return ay(e,t,r,this.basePTS,this.frameIndex)}},remux:Ly}];class Uy{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=_y();let i=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:a}=this;n&&(this.currentTransmuxState=n);const{contiguous:l,discontinuity:c,trackSwitch:u,accurateTimeOffset:d,timeOffset:h,initSegmentChange:f}=n||o,{audioCodec:p,videoCodec:g,defaultInitPts:m,duration:y,initSegmentData:v}=a,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=_y(),By(r);i=new Uint8Array(t)}}const w=this.needsProbing(c,u);if(w){const e=this.configureTransmuxer(i);if(e)return Ef.warn(`[transmuxer] ${e.message}`),this.observer.emit(pf.ERROR,pf.ERROR,{type:gf.MEDIA_ERROR,details:mf.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),s.executeEnd=_y(),By(r)}(c||u||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,d,r),T=this.currentTransmuxState;return T.contiguous=!0,T.discontinuity=!1,T.trackSwitch=!1,s.executeEnd=_y(),E}flush(e){const t=e.transmuxing;t.executeStart=_y();const{decrypter:r,currentTransmuxState:n,decryptionPromise:s}=this;if(s)return s.then((()=>this.flush(e)));const i=[],{timeOffset:o}=n;if(r){const t=r.flush();t&&i.push(this.push(t,null,e))}const{demuxer:a,remuxer:l}=this;if(!a||!l)return t.executeEnd=_y(),[By(e)];const c=a.flush(o);return jy(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:o}=t,{accurateTimeOffset:a,timeOffset:l}=this.currentTransmuxState;Ef.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,o,l,a,!0,this.id);e.push({remuxResult:c,chunkMeta:r}),r.transmuxing.executeEnd=_y()}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:o}=this;i&&o&&(i.resetInitSegment(e,t,r,n),o.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:o,textTrack:a}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,i,o,a,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=Ny.length;t<r;t++)if(Ny[t].demux.probe(e)){i=Ny[t];break}if(!i)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,a=this.remuxer,l=i.remux,c=i.demux;a&&a instanceof l||(this.remuxer=new l(r,t,n,s)),o&&o 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 Im(this.config)),e}}const By=e=>({remuxResult:{},chunkMeta:e});function jy(e){return"then"in e&&e.then instanceof Function}class $y{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 qy{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 Ky={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,o){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new s(n,i||e,o),l=r?r+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],a]:e._events[l].push(a):(e._events[l]=a,e._eventsCount++),e}function o(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.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},a.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,o=new Array(i);s<i;s++)o[s]=n[s].fn;return o},a.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},a.prototype.emit=function(e,t,n,s,i,o){var a=r?r+e:e;if(!this._events[a])return!1;var l,c,u=this._events[a],d=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),d){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,n),!0;case 4:return u.fn.call(u.context,t,n,s),!0;case 5:return u.fn.call(u.context,t,n,s,i),!0;case 6:return u.fn.call(u.context,t,n,s,i,o),!0}for(c=1,l=new Array(d-1);c<d;c++)l[c-1]=arguments[c];u.fn.apply(u.context,l)}else{var h,f=u.length;for(c=0;c<f;c++)switch(u[c].once&&this.removeListener(e,u[c].fn,void 0,!0),d){case 1:u[c].fn.call(u[c].context);break;case 2:u[c].fn.call(u[c].context,t);break;case 3:u[c].fn.call(u[c].context,t,n);break;case 4:u[c].fn.call(u[c].context,t,n,s);break;default:if(!l)for(h=1,l=new Array(d-1);h<d;h++)l[h-1]=arguments[h];u[c].fn.apply(u[c].context,l)}}return!0},a.prototype.on=function(e,t,r){return i(this,e,t,r,!1)},a.prototype.once=function(e,t,r){return i(this,e,t,r,!0)},a.prototype.removeListener=function(e,t,n,s){var i=r?r+e:e;if(!this._events[i])return this;if(!t)return o(this,i),this;var a=this._events[i];if(a.fn)a.fn!==t||s&&!a.once||n&&a.context!==n||o(this,i);else{for(var l=0,c=[],u=a.length;l<u;l++)(a[l].fn!==t||s&&!a[l].once||n&&a[l].context!==n)&&c.push(a[l]);c.length?this._events[i]=1===c.length?c[0]:c:o(this,i)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&o(this,t)):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=r,a.EventEmitter=a,e.exports=a}(Ky);var Gy=of(Ky.exports);const Hy=Bp()||{isTypeSupported:()=>!1};class Vy{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===pf.ERROR&&(this.error=t.error),this.hls.trigger(e,t)};this.observer=new Gy,this.observer.on(pf.FRAG_DECRYPTED,i),this.observer.on(pf.ERROR,i);const o={mp4:Hy.isTypeSupported("video/mp4"),mpeg:Hy.isTypeSupported("audio/mpeg"),mp3:Hy.isTypeSupported('audio/mp4; codecs="mp3"')},a=navigator.vendor;if(this.useWorker&&"undefined"!=typeof Worker){if(s.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{s.workerPath?(Ef.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)):(Ef.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,Ef.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(pf.ERROR,{type:gf.OTHER_ERROR,details:mf.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:r})},e.postMessage({cmd:"init",typeSupported:o,vendor:a,id:t,config:JSON.stringify(s)})}catch(e){Ef.warn(`Error setting up "${t}" Web Worker, fallback to inline`,e),this.resetWorker(),this.error=null,this.transmuxer=new Uy(this.observer,o,s,a,t)}return}}this.transmuxer=new Uy(this.observer,o,s,a,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,o,a,l,c){var u,d;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)),T=self.performance.now();(y||v||0===s.stats.parsing.start)&&(s.stats.parsing.start=T),!i||!b&&E||(i.stats.parsing.start=T);const S=!(g&&(null==(u=s.initSegment)?void 0:u.url)===(null==(d=g.initSegment)?void 0:d.url)),C=new qy(m,E,a,y,f,S);if(!E||m||S){Ef.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: ${a}\n timeOffset: ${f}\n initSegmentChange: ${S}`);const e=new $y(r,n,t,o,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);jy(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);jy(r)||t.async?(jy(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(pf.ERROR,{type:gf.MEDIA_ERROR,details:mf.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":Ef[t.data.logType]&&Ef[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 zy{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:o}=n,a=this.seeking&&!o,l=!this.seeking&&o;if(this.seeking=o,i!==e){if(this.moved=!0,null!==s){if(this.stallReported){const e=self.performance.now()-s;Ef.warn(`playback not stuck anymore @${i}, after ${Math.round(e)}ms`),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}return}if(l||a)return void(this.stalled=null);if(n.paused&&!o||n.ended||0===n.playbackRate||!vm.getBuffered(n).length)return;const c=vm.bufferInfo(n,i,0),u=c.len>0,d=c.nextStart||0;if(!u&&!d)return;if(o){const e=c.len>2,r=!d||t&&t.start<=i||d-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(d,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(!o&&p>=250&&(this._reportStall(c),!this.media))return;const g=vm.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,o=n.getPartialFragment(i);if(o){if(this._trySkipBufferHole(o)||!this.media)return}(e.len>r.maxBufferHole||e.nextStart&&e.nextStart-i<r.maxBufferHole)&&t>1e3*r.highBufferWatchdogPeriod&&(Ef.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)})`);Ef.warn(n.message),t.trigger(pf.ERROR,{type:gf.MEDIA_ERROR,details:mf.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=vm.bufferInfo(n,s,0),o=s<i.start?i.start:i.nextStart;if(o){const a=i.len<=t.maxBufferHole,l=i.len>0&&i.len<1&&n.readyState<3,c=o-s;if(c>0&&(a||l)){if(c>t.maxBufferHole){const{fragmentTracker:t}=this;let r=!1;if(0===s){const e=t.getAppendedFrag(0,og);e&&o<e.end&&(r=!0)}if(!r){const r=e||t.getAppendedFrag(s,og);if(r){let e=!1,n=r.end;for(;n<o;){const r=t.getPartialFragment(n);if(!r){e=!0;break}n+=r.duration}if(e)return 0}}}const i=Math.max(o+.05,s+.1);if(Ef.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(pf.ERROR,{type:gf.MEDIA_ERROR,details:mf.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,o=new Error(`Nudging 'currentTime' from ${s} to ${i}`);Ef.warn(o.message),r.currentTime=i,t.trigger(pf.ERROR,{type:gf.MEDIA_ERROR,details:mf.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1})}else{const r=new Error(`Playhead still not moving while enough data buffered @${s} after ${e.nudgeMaxRetry} nudges`);Ef.error(r.message),t.trigger(pf.ERROR,{type:gf.MEDIA_ERROR,details:mf.BUFFER_STALLED_ERROR,error:r,fatal:!0})}}}class Wy extends qm{constructor(e,t,r){super(e,t,r,"[stream-controller]",og),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(pf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(pf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(pf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(pf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(pf.LEVEL_LOADING,this.onLevelLoading,this),e.on(pf.LEVEL_LOADED,this.onLevelLoaded,this),e.on(pf.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(pf.ERROR,this.onError,this),e.on(pf.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(pf.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(pf.BUFFER_CREATED,this.onBufferCreated,this),e.on(pf.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(pf.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(pf.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(pf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(pf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(pf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(pf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(pf.LEVEL_LOADED,this.onLevelLoaded,this),e.off(pf.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(pf.ERROR,this.onError,this),e.off(pf.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(pf.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(pf.BUFFER_CREATED,this.onBufferCreated,this),e.off(pf.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(pf.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(pf.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=Dm,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=Lm}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case $m:{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=Dm;break}if(this.hls.nextLoadLevel!==this.level){this.state=Dm;break}break}case Pm:{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=Dm)}}this.state===Dm&&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 o=r[i],a=this.getMainFwdBufferInfo();if(null===a)return;const l=this.getLevelDetails();if(l&&this._streamEnded(a,l)){const e={};return this.altAudio&&(e.type="video"),this.hls.trigger(pf.BUFFER_EOS,e),void(this.state=Um)}e.loadLevel!==i&&-1===e.manualLevel&&this.log(`Adapting to level ${i} from level ${this.level}`),this.level=e.nextLoadLevel=i;const c=o.details;if(!c||this.state===$m||c.live&&this.levelLastLoaded!==i)return this.level=i,void(this.state=$m);const u=a.len,d=this.getMaxBufferLength(o.maxBitrate);if(u>=d)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const h=this.backtrackFragment?this.backtrackFragment.start:a.end;let f=this.getNextFragment(h,c);if(this.couldBacktrack&&!this.fragPrevious&&f&&"initSegment"!==f.sn&&this.fragmentTracker.getState(f)!==am){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&&a.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){const e=this.audioOnly&&!this.altAudio?If:Rf,t=(e===Rf?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,og)}f=this.getNextFragmentLoopLoading(f,c,a,og,d)}f&&(!f.initSegment||f.initSegment.data||this.bitrateTest||(f=f.initSegment),this.loadFragment(f,o,h))}loadFragment(e,t,r){const n=this.fragmentTracker.getState(e);this.fragCurrent=e,n===sm||n===om?"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,og)}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 xm:case Om:case Pm:case Fm:case Nm:this.state=Dm}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 zy(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;ff(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(pf.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=Km();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!==Dm)return;const n=r[t.level];(!n.details||n.details.live&&this.levelLastLoaded!==t.level||this.waitForCdnTuneIn(n.details))&&(this.state=$m)}onLevelLoaded(e,t){var r;const{levels:n}=this,s=t.level,i=t.details,o=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:${o}`);const a=n[s],l=this.fragCurrent;!l||this.state!==Om&&this.state!==Pm||l.level===t.level&&l.urlId===a.urlId||!l.loader||this.abortCurrentFrag();let c=0;if(i.live||null!=(r=a.details)&&r.live){if(i.fragments[0]||(i.deltaUpdateFailed=!0),i.deltaUpdateFailed)return;c=this.alignPlaylists(i,a.details)}if(a.details=i,this.levelLastLoaded=s,this.hls.trigger(pf.LEVEL_UPDATED,{details:i,level:s}),this.state===$m){if(this.waitForCdnTuneIn(i))return;this.state=Dm}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 o=i[r.level],a=o.details;if(!a)return this.warn(`Dropping fragment ${r.sn} of level ${r.level} after level details were reset`),void this.fragmentTracker.removeFragment(r);const l=o.videoCodec,c=a.PTSKnown||!a.live,u=null==(t=r.initSegment)?void 0:t.data,d=this._getAudioCodec(o),h=this.transmuxer=this.transmuxer||new Vy(this.hls,og,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=n?n.index:-1,p=-1!==f,g=new bm(r.level,r.sn,r.stats.chunkCount,s.byteLength,f,p),m=this.initPTS[r.cc];h.push(s,u,d,l,r,n,a.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(pf.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),e.trigger(pf.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!==og)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===Nm&&(this.state=Dm));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=Bm;else switch(t.details){case mf.FRAG_GAP:case mf.FRAG_PARSING_ERROR:case mf.FRAG_DECRYPT_ERROR:case mf.FRAG_LOAD_ERROR:case mf.FRAG_LOAD_TIMEOUT:case mf.KEY_LOAD_ERROR:case mf.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(og,t);break;case mf.LEVEL_LOAD_ERROR:case mf.LEVEL_LOAD_TIMEOUT:case mf.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==$m||(null==(r=t.context)?void 0:r.type)!==ng||(this.state=Dm);break;case mf.BUFFER_FULL_ERROR:if(!t.parent||"main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case mf.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}checkBuffer(){const{media:e,gapController:t}=this;if(e&&t&&e.readyState){if(this.loadedmetadata||!vm.getBuffered(e).length){const e=this.state!==Dm?this.fragCurrent:null;t.poll(this.lastCurrentTime,e)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=Dm,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==If||this.audioOnly&&!this.altAudio){const e=(t===Rf?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(e,t,og)}}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=vm.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=Dm,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(pf.FRAG_LOADED,r),e.bitrateTest=!1}))}_handleTransmuxComplete(e){var t;const r="main",{hls:n}=this,{remuxResult:s,chunkMeta:i}=e,o=this.getCurrentContext(i);if(!o)return void this.resetWhenMissingContext(i);const{frag:a,part:l,level:c}=o,{video:u,text:d,id3:h,initSegment:f}=s,{details:p}=c,g=this.altAudio?void 0:s.audio;if(this.fragContextChanged(a))this.fragmentTracker.removeFragment(a);else{if(this.state=Fm,f){if(null!=f&&f.tracks){const e=a.initSegment||a;this._bufferInitSegment(c,f.tracks,e,i),n.trigger(pf.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:r,tracks:f.tracks})}const e=f.initPTS,t=f.timescale;ff(e)&&(this.initPTS[a.cc]={baseTime:e,timescale:t},n.trigger(pf.INIT_PTS_FOUND,{frag:a,id:r,initPTS:e,timescale:t}))}if(u&&p&&"initSegment"!==a.sn){const e=p.fragments[a.sn-1-p.startSN],t=a.sn===p.startSN,r=!e||a.cc>e.cc;if(!1!==s.independent){const{startPTS:e,endPTS:n,startDTS:s,endDTS:o}=u;if(l)l.elementaryStreams[u.type]={startPTS:e,endPTS:n,startDTS:s,endDTS:o};else if(u.firstKeyFrame&&u.independent&&1===i.id&&!r&&(this.couldBacktrack=!0),u.dropped&&u.independent){const s=this.getMainFwdBufferInfo(),i=(s?s.end:this.getLoadPosition())+this.config.maxBufferHole,l=u.firstKeyFramePTS?u.firstKeyFramePTS:e;if(!t&&i<l-this.config.maxBufferHole&&!r)return void this.backtrack(a);r&&(a.gap=!0),a.setElementaryStreamInfo(u.type,a.start,n,a.start,o,!0)}a.setElementaryStreamInfo(u.type,e,n,s,o),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(u,a,l,i,t||r)}else{if(!t&&!r)return void this.backtrack(a);a.gap=!0}}if(g){const{startPTS:e,endPTS:t,startDTS:r,endDTS:n}=g;l&&(l.elementaryStreams[If]={startPTS:e,endPTS:t,startDTS:r,endDTS:n}),a.setElementaryStreamInfo(If,e,t,r,n),this.bufferFragmentData(g,a,l,i)}if(p&&null!=h&&null!=(t=h.samples)&&t.length){const e={id:r,frag:a,details:p,samples:h.samples};n.trigger(pf.FRAG_PARSING_METADATA,e)}if(p&&d){const e={id:r,frag:a,details:p,samples:d.samples};n.trigger(pf.FRAG_PARSING_USERDATA,e)}}}_bufferInitSegment(e,t,r,n){if(this.state!==Fm)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;const{audio:s,video:i,audiovideo:o}=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}]`)),o&&this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.attrs.CODECS||""}/${o.codec}]`),this.hls.trigger(pf.BUFFER_CODECS,t),Object.keys(t).forEach((e=>{const s=t[e].initSegment;null!=s&&s.byteLength&&this.hls.trigger(pf.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,og)}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=Dm}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const r=e.currentTime;if(vm.isBuffered(e,r)?t=this.getAppendedFrag(r):vm.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(pf.FRAG_CHANGED,{frag:t}),e&&e.level===r||this.hls.trigger(pf.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&&ff(t)&&ff(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 Yy{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 Qy{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 Yy(e),this.fast_=new Yy(t),this.defaultTTFB_=n,this.ttfb_=new Yy(e)}update(e,t){const{slow_:r,fast_:n,ttfb_:s}=this;r.halfLife!==e&&(this.slow_=new Yy(e,r.getEstimate(),r.getTotalWeight())),n.halfLife!==t&&(this.fast_=new Yy(t,n.getEstimate(),n.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new Yy(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 Xy{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 Jy(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Zy(e[r].attrs,t[r].attrs))return!1;return!0}function Zy(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 ev{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 tv(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 rv{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){Ef.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 nv=Bp(),sv=/([ha]vc.)(?:\.[^.,]+)+/;const iv={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},ov=function(e){let t=e;return iv.hasOwnProperty(e)&&(t=iv[e]),String.fromCharCode(t)},av=15,lv=100,cv={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},uv={17:2,18:4,21:6,22:8,23:10,19:13,20:15},dv={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},hv={25:2,26:4,29:6,30:8,31:10,27:13,28:15},fv=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class pv{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const r="function"==typeof t?t():t;Ef.log(`${this.time} [${e}] ${r}`)}}}const gv=function(e){const t=[];for(let r=0;r<e.length;r++)t.push(e[r].toString(16));return t};class mv{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 mv(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 vv{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<lv;e++)this.chars.push(new yv);this.logger=e,this.pos=0,this.currPenState=new mv}equals(e){let t=!0;for(let r=0;r<lv;r++)if(!this.chars[r].equals(e.chars[r])){t=!1;break}return t}copy(e){for(let t=0;t<lv;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<lv;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>lv&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=lv)}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=ov(e);this.pos>=lv?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<lv;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<lv;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 bv{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<av;t++)this.rows.push(new vv(e));this.logger=e,this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.reset()}reset(){for(let e=0;e<av;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let r=0;r<av;r++)if(!this.rows[r].equals(e.rows[r])){t=!1;break}return t}copy(e){for(let t=0;t<av;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<av;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<av;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<av;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 wv{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 bv(r),this.nonDisplayedMemory=new bv(r),this.lastOutputScreen=new bv(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 Ev{constructor(e,t,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=void 0,this.logger=void 0;const n=new pv;this.channels=[null,new wv(e,t,n),new wv(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,"["+gv([t[e],t[e+1]])+"] -> ("+gv([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 "+gv([n,s])+" orig: "+gv([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(Sv(e,t,r))return Tv(null,null,r),this.logger.log(3,"Repeated command ("+gv([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),Tv(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 ("+gv([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(Sv(e,t,n))return Tv(null,null,n),!0;const s=e<=23?1:2;r=t>=64&&t<=95?1===s?cv[e]:dv[e]:1===s?uv[e]:hv[e];const i=this.channels[s];return!!i&&(i.setPAC(this.interpretPAC(r,t)),Tv(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 '"+ov(e)+"' in channel "+r),n=[e]}else e>=32&&e<=127&&(n=0===t?[e]:[e,t]);if(n){const r=gv(n);this.logger.log(3,"Char codes = "+r.join(",")),Tv(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=fv[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),Tv(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 Tv(e,t,r){r.a=e,r.b=t}function Sv(e,t,r){return r.a===e&&r.b===t}class Cv{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 kv=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,o){const a=this,l={enumerable:!0};a.hasBeenReset=!1;let c="",u=!1,d=t,h=i,f=o,p=null,g="",m=!0,y="auto",v="start",b=50,w="middle",E=50,T="middle";Object.defineProperty(a,"id",s({},l,{get:function(){return c},set:function(e){c=""+e}})),Object.defineProperty(a,"pauseOnExit",s({},l,{get:function(){return u},set:function(e){u=!!e}})),Object.defineProperty(a,"startTime",s({},l,{get:function(){return d},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");d=e,this.hasBeenReset=!0}})),Object.defineProperty(a,"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(a,"text",s({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(a,"region",s({},l,{get:function(){return p},set:function(e){p=e,this.hasBeenReset=!0}})),Object.defineProperty(a,"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(a,"snapToLines",s({},l,{get:function(){return m},set:function(e){m=!!e,this.hasBeenReset=!0}})),Object.defineProperty(a,"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(a,"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(a,"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(a,"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(a,"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(a,"align",s({},l,{get:function(){return T},set:function(e){const t=n(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");T=t,this.hasBeenReset=!0}})),a.displayState=void 0}return i.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},i}();class Av{decode(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function _v(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 Iv{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 Rv(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 Lv=new kv(0,0,""),Dv="middle"===Lv.align?"middle":"center";function xv(e,t,r){const n=e;function s(){const t=_v(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 Iv;Rv(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",Dv,"end"]);break;case"position":s=t.split(","),n.percent(e,s[0]),2===s.length&&n.alt("positionAlign",s[1],["start",Dv,"end","line-left","line-right","auto"]);break;case"size":n.percent(e,t);break;case"align":n.alt(e,t,["start",Dv,"end","left","right"])}}),/:/,/\s/),t.region=n.get("region",null),t.vertical=n.get("vertical","");let s=n.get("line","auto");"auto"===s&&-1===Lv.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",Dv);let i=n.get("position","auto");"auto"===i&&50===Lv.position&&(i="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=i}(e,t)}function Ov(e){return e.replace(/<br(?: \/)?>/gi,"\n")}class Pv{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Av,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=Ov(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)?Rv(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 kv(0,0,""),t.state="CUE",-1===e.indexOf("--\x3e")){t.cue.id=e;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{xv(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 Mv=/\r\n|\n\r|\n|\r/g,Fv=function(e,t,r=0){return e.slice(r,r+t.length)===t},Nv=function(e){let t=5381,r=e.length;for(;r;)t=33*t^e.charCodeAt(--r);return(t>>>0).toString()};function Uv(e,t,r){return Nv(e.toString())+Nv(t.toString())+Nv(r)}function Bv(e,t,r,n,s,i,o){const a=new Pv,l=lp(new Uint8Array(e)).trim().replace(Mv,"\n").split("\n"),c=[],u=t?function(e,t=1){return ky(e,9e4,1/t)}(t.baseTime,t.timescale):0;let d,h="00:00.000",f=0,p=0,g=!0;a.oncue=function(e){const i=r[n];let o=r.ccOffset;const a=(f-u)/9e4;if(null!=i&&i.new&&(void 0!==p?o=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,a)),a){if(!t)return void(d=new Error("Missing initPTS for VTT MPEGTS"));o=a-r.presentationOffset}const l=e.endTime-e.startTime,h=Dy(9e4*(e.startTime+o-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=Uv(e.startTime,e.endTime,g)),e.endTime>0&&c.push(e)},a.onparsingerror=function(e){d=e},a.onflush=function(){d?o(d):i(c)},l.forEach((e=>{if(g){if(Fv(e,"X-TIMESTAMP-MAP=")){g=!1,e.slice(16).split(",").forEach((e=>{Fv(e,"LOCAL:")?h=e.slice(6):Fv(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(!(ff(t)&&ff(r)&&ff(n)&&ff(s)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*r,t+=6e4*n,t+=36e5*s,t}(h)/1e3}catch(e){d=e}return}""===e&&(g=!1)}a.parse(e+"\n")})),a.flush()}const jv="stpp.ttml.im1t",$v=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,qv=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Kv={left:"start",center:"center",right:"end",start:"start",end:"end"};function Gv(e,t,r,n){const s=wp(new Uint8Array(e),["mdat"]);if(0===s.length)return void n(new Error("Could not parse IMSC1 mdat"));const i=s.map((e=>lp(e))),o=function(e,t,r=1,n=!1){return ky(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)),{}),o="preserve"!==n.getAttribute("xml:space"),a=Vv(Hv(n,"styling","style")),l=Vv(Hv(n,"layout","region")),c=Hv(n,"body","[begin]");return[].map.call(c,(e=>{const r=zv(e,o);if(!r||!e.hasAttribute("begin"))return null;const n=Qv(e.getAttribute("begin"),i),s=Qv(e.getAttribute("dur"),i);let c=Qv(e.getAttribute("end"),i);if(null===n)throw Yv(e);if(null===c){if(null===s)throw Yv(e);c=n+s}const u=new kv(n-t,c-t,r);u.id=Uv(u.startTime,u.endTime,u.text);const d=function(e,t,r){const n="http://www.w3.org/ns/ttml#styling";let s=null;const i=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],o=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;o&&r.hasOwnProperty(o)&&(s=r[o]);return i.reduce(((r,i)=>{const o=Wv(t,n,i)||Wv(e,n,i)||Wv(s,n,i);return o&&(r[i]=o),r}),{})}(l[e.getAttribute("region")],a[e.getAttribute("style")],a),{textAlign:h}=d;if(h){const e=Kv[h];e&&(u.lineAlign=e),u.align=h}return hf(u,d),u})).filter((e=>null!==e))}(e,o))))}catch(e){n(e)}}function Hv(e,t,r){const n=e.getElementsByTagName(t)[0];return n?[].slice.call(n.querySelectorAll(r)):[]}function Vv(e){return e.reduce(((e,t)=>{const r=t.getAttribute("xml:id");return r&&(e[r]=t),e}),{})}function zv(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?zv(r,t):t?e+r.textContent.trim().replace(/\s+/g," "):e+r.textContent}),"")}function Wv(e,t,r){return e&&e.hasAttributeNS(t,r)?e.getAttributeNS(t,r):null}function Yv(e){return new Error(`Could not parse ttml timestamp ${e}`)}function Qv(e,t){if(!e)return null;let r=_v(e);return null===r&&($v.test(e)?r=function(e,t){const r=$v.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):qv.test(e)&&(r=function(e,t){const r=qv.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 Xv(e,t){return!!e&&e.label===t.name&&!(e.textTrack1||e.textTrack2)}class Jv{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(pf.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(pf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(pf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(pf.BUFFER_CODECS,this.onBufferCodecs,this),e.on(pf.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(pf.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(pf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(pf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(pf.BUFFER_CODECS,this.onBufferCodecs,this),e.off(pf.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,Jv.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 o=0;o<e.length;o+=1){const a=e[o];if((a.width>=t||a.height>=r)&&(s=a,!(i=e[o+1])||s.width!==i.width||s.height!==i.height)){n=o;break}}var s,i;return n}}const Zv="[eme]";class eb{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=eb.CDMCleanupPromise?[eb.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=Ef.debug.bind(Ef,Zv),this.log=Ef.log.bind(Ef,Zv),this.warn=Ef.warn.bind(Ef,Zv),this.error=Ef.error.bind(Ef,Zv),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(pf.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(pf.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(pf.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(pf.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(pf.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(pf.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(pf.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(pf.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:r}=this.config,n=t[e];if(n)return n.licenseUrl;if(e===Uf.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 o=e.shift();this.getMediaKeysPromise(o,n,s).then((e=>t({keySystem:o,mediaKeys:e}))).catch((t=>{e.length?i(e):r(t instanceof tb?t:new tb({type:gf.KEY_SYSTEM_ERROR,details:mf.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===zf&&"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 Uf.FAIRPLAY:s=["cenc","sinf"];break;case Uf.WIDEVINE:case Uf.PLAYREADY:s=["cenc"];break;case Uf.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: ${dp(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 dp(e.keyId)}updateKeySession(e,t){var r;const n=e.mediaKeysSession;return this.log(`Updating key-session "${n.sessionId}" for keyID ${dp((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=Vf(this.config),s=e.map(Kf).filter((e=>!!e&&-1!==n.indexOf(e)));return this.getKeySystemSelectionPromise(s).then((({keySystem:e})=>{const n=Hf(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 tb?this.hls.trigger(pf.ERROR,e.data):this.hls.trigger(pf.ERROR,{type:gf.KEY_SYSTEM_ERROR,details:mf.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),r=this.keyIdToKeySessionPromise[t];if(!r){const t=Kf(e.keyFormat),r=t?[t]:Vf(this.config);return this.attemptKeySystemAccess(r)}return r}getKeySystemSelectionPromise(e){if(e.length||(e=Vf(this.config)),0===e.length)throw new tb({type:gf.KEY_SYSTEM_ERROR,details:mf.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[Uf.FAIRPLAY]){const e=gp(new Uint8Array(r));try{const t=Mf(JSON.parse(e).sinf),r=Sp(new Uint8Array(t));if(!r)return;n=r.subarray(8,24),s=Uf.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=dp(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===Gf&&e.data&&(n=e.data.subarray(8,24)),s=function(e){if(e===Gf)return Uf.WIDEVINE}(e.systemId)}if(!s||!n)return;const i=dp(n),{keyIdToKeySessionPromise:o,mediaKeySessions:a}=this;let l=o[i];for(let e=0;e<a.length;e++){const s=a[e],c=s.decryptdata;if(c.pssh||!c.keyId)continue;const u=dp(c.keyId);if(i===u||-1!==c.uri.replace(/-/g,"").indexOf(i)){l=o[u],delete o[u],c.pssh=new Uint8Array(r),c.keyId=n,l=o[i]=l.then((()=>this.generateRequestWithPreferredKeySession(s,t,r,"encrypted-event-key-match")));break}}l||(l=o[i]=this.getKeySystemSelectionPromise([s]).then((({keySystem:e,mediaKeys:s})=>{var o;this.throwIfDestroyed();const a=new xp("ISO-23001-7",i,null!=(o=Hf(e))?o:"");return a.pssh=new Uint8Array(r),a.keyId=n,this.attemptSetMediaKeys(e,s).then((()=>{this.throwIfDestroyed();const n=this.createMediaKeySessionContext({decryptdata:a,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 o=null==(s=this.config.drmSystems)||null==(i=s[e.keySystem])?void 0:i.generateRequest;if(o)try{const n=o.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 a;if(this.warn(e.message),null!=(a=this.hls)&&a.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 Gy;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===Uf.FAIRPLAY&&(this.updateKeySession(e,Nf("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 u=new Promise(((e,t)=>{c.on("error",t),c.on("keyStatus",(r=>{r.startsWith("usable")?e():"output-restricted"===r?t(new tb({type:gf.KEY_SYSTEM_ERROR,details:mf.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===r?t(new tb({type:gf.KEY_SYSTEM_ERROR,details:mf.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 tb({type:gf.KEY_SYSTEM_ERROR,details:mf.KEY_SYSTEM_NO_SESSION,error:e,fatal:!1},`Error generating key-session request: ${e}`)})).then((()=>u)).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: ${dp("buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r))} session keyId: ${dp(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 o={responseType:"arraybuffer",url:n},a=t.certLoadPolicy.default,l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(e,t,r,n)=>{s(e.data)},onError:(t,r,s,a)=>{i(new tb({type:gf.KEY_SYSTEM_ERROR,details:mf.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:uf({url:o.url,data:void 0},t)},`"${e}" certificate request failed (${n}). Status: ${t.code} (${t.text})`))},onTimeout:(t,r,s)=>{i(new tb({type:gf.KEY_SYSTEM_ERROR,details:mf.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:{url:o.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(e,t,r)=>{i(new Error("aborted"))}};r.load(o,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 tb({type:gf.KEY_SYSTEM_ERROR,details:mf.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 tb({type:gf.KEY_SYSTEM_ERROR,details:mf.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 o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return s(new Error("invalid state"));if(4===o.readyState)if(200===o.status){this._requestLicenseFailureCount=0;let t=o.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);const r=this.config.licenseResponseCallback;if(r)try{t=r.call(this.hls,o,i,e)}catch(e){this.error(e)}n(t)}else{const a=r.errorRetry,l=a?a.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||o.status>=400&&o.status<500)s(new tb({type:gf.KEY_SYSTEM_ERROR,details:mf.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:i,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${i}). Status: ${o.status} (${o.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=o,this.setupLicenseXHR(o,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={},xp.clearKeyUriToKeyIdMap();const r=t.length;eb.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}`)}))}}}eb.CDMCleanupPromise=void 0;class tb 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 rb="m",nb="a",sb="v",ib="av",ob="i",ab="tt";class lb{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:rb,su:!this.initialized})}catch(e){Ef.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!==sb&&n!==nb&&n!=ib||(s.br=r.bitrate/1e3,s.tb=this.getTopBandwidth(n)/1e3,s.bl=this.getBufferLength(n)),this.apply(e,s)}catch(e){Ef.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||lb.uuid(),this.cid=r.contentId,this.useHeaders=!0===r.useHeaders,this.registerListeners())}registerListeners(){const e=this.hls;e.on(pf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(pf.MEDIA_DETACHED,this.onMediaDetached,this),e.on(pf.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(pf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(pf.MEDIA_DETACHED,this.onMediaDetached,this),e.off(pf.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={}){hf(t,this.createData());const r=t.ot===ob||t.ot===sb||t.ot===ib;if(this.starved&&r&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering),this.useHeaders){const r=lb.toHeaders(t);if(!Object.keys(r).length)return;e.headers||(e.headers={}),hf(e.headers,r)}else{const r=lb.toQuery(t);if(!r)return;e.url=lb.appendQueryToUri(e.url,r)}}getObjectType(e){const{type:t}=e;return"subtitle"===t?ab:"initSegment"===e.sn?ob:"audio"===t?nb:"main"===t?this.hls.audioTracks.length?sb:ib:void 0}getTopBandwidth(e){let t,r=0;const n=this.hls;if(e===nb)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===nb?this.audioBuffer:this.videoBuffer;if(!r||!t)return NaN;return 1e3*vm.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},o=Object.keys(e||{}).sort();for(const n of o){let s=e[n];if(!r(s))continue;if("v"===n&&1===s)continue;if("pr"==n&&1===s)continue;const o=i[n];o&&(s=o(s));const a=typeof s;let l;l="ot"===n||"sf"===n||"st"===n?`${n}=${s}`:"boolean"===a?n:"number"===a?`${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=lb.serialize(s[e]);t&&(r[`CMCD-${n[e]}`]=t)}return r}static toQuery(e){return`CMCD=${encodeURIComponent(lb.serialize(e))}`}static appendQueryToUri(e,t){if(!t)return e;const r=e.includes("?")?"&":"?";return`${e}${r}${t}`}}function cb(e,t,r,n){e&&Object.keys(t).forEach((s=>{const i=e.filter((e=>e.groupId===s)).map((e=>{const i=hf({},e);return i.details=void 0,i.attrs=new Cf(i.attrs),i.url=i.attrs.URI=ub(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 ub(e,t,r,n){const{HOST:s,PARAMS:i,[r]:o}=n;let a;t&&(a=null==o?void 0:o[t],a&&(e=a));const l=new self.URL(e);return s&&!a&&(l.host=s),i&&Object.keys(i).sort().forEach((e=>{e&&l.searchParams.set(e,i[e])})),l.href}const db=/^age:\s*[\d.]+\s*$/im;class hb{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 _f,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&&ff(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,o="arraybuffer"===t.responseType?s.byteLength:s.length;if(r.loaded=r.total=o,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first),!this.callbacks)return;const a=this.callbacks.onProgress;if(a&&a(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;$g(i,r.retry,!1,n)?this.retry(i):(Ef.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($g(t,this.stats.retry,!0))this.retry(t);else{Ef.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=Bg(e,r.retry),r.retry++,Ef.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&&db.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 fb=/(\d+)-(\d+)\/(\d+)/;class pb{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||gb,this.controller=new self.AbortController,this.stats=new _f}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(hf({},e.headers))};e.rangeEnd&&r.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return r}(e,this.controller.signal),i=r.onProgress,o="arraybuffer"===e.responseType,a=o?"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&&ff(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 a=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-(a-n.loading.start)),!s.ok){const{status:e,statusText:t}=s;throw new mb(t||"fetch, bad network response",e,s)}return n.loading.first=a,n.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=fb.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(ff(e))return e}const r=e.get("Content-Length");if(r)return parseInt(r)}(s.headers)||n.total,i&&ff(t.highWaterMark)?this.loadProgressively(s,n,e,t.highWaterMark,i):o?s.arrayBuffer():"json"===e.responseType?s.json():s.text()})).then((s=>{const{response:o}=this;self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);const l=s[a];l&&(n.loaded=n.total=l);const c={url:o.url,data:s,code:o.status};i&&!ff(t.highWaterMark)&&i(n,e,s,o),r.onSuccess(c,n,e,o)})).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 Xy,o=e.body.getReader(),a=()=>o.read().then((o=>{if(o.done)return i.dataLength&&s(t,r,i.flush(),e),Promise.resolve(new ArrayBuffer(0));const l=o.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),a()})).catch((()=>Promise.reject()));return a()}}function gb(e,t){return new self.Request(e.url,t)}class mb 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/,vb={newCue(e,t,r,n){const s=[];let i,o,a,l,c;const u=self.VTTCue||self.TextTrackCue;for(let h=0;h<n.rows.length;h++)if(i=n.rows[h],a=!0,l=0,c="",!i.isEmpty()){var d;for(let e=0;e<i.chars.length;e++)yb.test(i.chars[e].uchar)&&a?l++:(c+=i.chars[e].uchar,a=!1);i.cueStartTime=t,t===r&&(r+=1e-4),l>=16?l--:l++;const n=Ov(c.trim()),f=Uv(t,r,n);null!=e&&null!=(d=e.cues)&&d.getCueById(f)||(o=new u(t,r,n),o.id=f,o.line=h+1,o.align="left",o.position=10+Math.min(80,10*Math.floor(8*l/32)),s.push(o))}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=>fg(e,t)))),s}},bb=uf(uf({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:hb,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 Qy(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate),this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(pf.FRAG_LOADING,this.onFragLoading,this),e.on(pf.FRAG_LOADED,this.onFragLoaded,this),e.on(pf.FRAG_BUFFERED,this.onFragBuffered,this),e.on(pf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(pf.LEVEL_LOADED,this.onLevelLoaded,this)}unregisterListeners(){const{hls:e}=this;e.off(pf.FRAG_LOADING,this.onFragLoading,this),e.off(pf.FRAG_LOADED,this.onFragLoaded,this),e.off(pf.FRAG_BUFFERED,this.onFragBuffered,this),e.off(pf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(pf.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;ff(n)&&ff(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(),o=t?t.stats:e.stats,a=t?t.duration:e.duration,l=i-o.loading.start;if(o.aborted||o.loaded&&o.loaded===o.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 u=this.bwEstimator.getEstimateTTFB(),d=Math.abs(s.playbackRate);if(l<=Math.max(u,a/(2*d)*1e3))return;const h=c.len/d;if(h>=2*a/d)return;const f=o.loading.first?o.loading.first-o.loading.start:-1,p=o.loaded&&f>-1,g=this.bwEstimator.getEstimate(),{levels:m,minAutoLevel:y}=r,v=m[e.level],b=o.total||Math.max(o.loaded,Math.round(a*v.maxBitrate/8));let w=l-f;w<1&&p&&(w=Math.min(l,8*o.loaded/g));const E=p?1e3*o.loaded/w:0,T=E?(b-o.loaded)/E:8*b/g+u/1e3;if(T<=h)return;const S=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(u/1e3,S,a*e,!m[C].details),k<h)break}k>=T||k>10*a||(r.nextLoadLevel=C,p?this.bwEstimator.sample(l-Math.min(u,f),o.loaded):this.bwEstimator.sampleTTFB(l),this.clearTimer(),Ef.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: ${T.toFixed(3)} s\n Estimated load time for down switch fragment: ${k.toFixed(3)} s\n TTFB estimate: ${f}\n Current BW estimate: ${ff(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(pf.FRAG_LOAD_EMERGENCY_ABORTED,{frag:e,part:t,stats:o}))}onFragLoaded(e,{frag:t,part:r}){const n=r?r.stats:t.stats;if(t.type===og&&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,o=(s.loaded?s.loaded.duration:0)+e;s.loaded={bytes:i,duration:o},s.realBitrate=Math.round(8*i/o)}if(t.bitrateTest){const e={stats:n,frag:t,part:r,id:t.type};this.onFragBuffered(pf.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!==og||"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:o}=r,a=t?t.duration:e?e.duration:0,l=o&&0!==o.playbackRate?Math.abs(o.playbackRate):1,c=this.bwEstimator?this.bwEstimator.getEstimate():s.abrEwmaDefaultEstimate,u=r.mainForwardBufferInfo,d=(u?u.len:0)/l;let h=this.findBestLevel(c,i,n,d,s.abrBandWidthFactor,s.abrBandWidthUpFactor);if(h>=0)return h;Ef.trace(`[abr] ${d?"rebuffering expected":"buffer is empty"}, finding optimal quality level`);let f=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay,p=s.abrBandWidthFactor,g=s.abrBandWidthUpFactor;if(!d){const e=this.bitrateTestDelay;if(e){f=(a?Math.min(a,s.maxLoadingDelay):s.maxLoadingDelay)-e,Ef.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,d+f,p,g),Math.max(h,0)}findBestLevel(e,t,r,n,s,i){var o;const{fragCurrent:a,partCurrent:l,lastLoadedFragLevel:c}=this,{levels:u}=this.hls,d=u[c],h=!(null==d||null==(o=d.details)||!o.live),f=null==d?void 0:d.codecSet,p=l?l.duration:a?a.duration:0,g=this.bwEstimator.getEstimateTTFB()/1e3;let m=t,y=-1;for(let o=r;o>=t;o--){const t=u[o];if(!t||f&&t.codecSet!==f){t&&(m=Math.min(o,m),y=Math.max(o,y));continue}-1!==y&&Ef.trace(`[abr] Skipped level(s) ${m}-${y} with CODECS:"${u[y].attrs.CODECS}"; not compatible with "${d.attrs.CODECS}"`);const r=t.details,a=(l?null==r?void 0:r.partTarget:null==r?void 0:r.averagetargetduration)||p;let v;v=o<=c?s*e:i*e;const b=u[o].maxBitrate,w=this.getTimeToLoadFrag(g,v,b*a,void 0===r);if(Ef.trace(`[abr] level:${o} adjustedbw-bitrate:${Math.round(v-b)} avgDuration:${a.toFixed(1)} maxFetchDuration:${n.toFixed(1)} fetchDuration:${w.toFixed(1)}`),v>b&&(0===w||!ff(w)||h&&!this.bitrateTestDelay||w<n))return o}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;Ef.log("[buffer-controller]: Media source opened"),e&&(e.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(pf.MEDIA_ATTACHED,{media:e})),t&&t.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{Ef.log("[buffer-controller]: Media source closed")},this._onMediaSourceEnded=()=>{Ef.log("[buffer-controller]: Media source ended")},this._onMediaEmptied=()=>{const{media:e,_objectUrl:t}=this;e&&e.src!==t&&Ef.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(pf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(pf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(pf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(pf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(pf.BUFFER_RESET,this.onBufferReset,this),e.on(pf.BUFFER_APPENDING,this.onBufferAppending,this),e.on(pf.BUFFER_CODECS,this.onBufferCodecs,this),e.on(pf.BUFFER_EOS,this.onBufferEos,this),e.on(pf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(pf.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(pf.FRAG_PARSED,this.onFragParsed,this),e.on(pf.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:e}=this;e.off(pf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(pf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(pf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(pf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(pf.BUFFER_RESET,this.onBufferReset,this),e.off(pf.BUFFER_APPENDING,this.onBufferAppending,this),e.off(pf.BUFFER_CODECS,this.onBufferCodecs,this),e.off(pf.BUFFER_EOS,this.onBufferEos,this),e.off(pf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(pf.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(pf.FRAG_PARSED,this.onFragParsed,this),e.off(pf.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new rv(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,Ef.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,t){const r=this.media=t.media;if(r&&nv){const e=this.mediaSource=new nv;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(Ef.log("[buffer-controller]: media source detaching"),"open"===t.readyState)try{t.endOfStream()}catch(e){Ef.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()):Ef.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(pf.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){Ef.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:o,metadata:a}=t[e],l=(r.levelCodec||r.codec).replace(sv,"$1"),c=(i||s).replace(sv,"$1");if(l!==c){const t=`${o};codecs=${i||s}`;this.appendChangeType(e,t),Ef.log(`[buffer-controller]: switching codec ${l} to ${c}`),this.tracks[e]={buffer:r.buffer,codec:s,container:o,levelCodec:i,metadata:a,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&&(Ef.log(`[buffer-controller]: changing ${e} sourceBuffer type to ${t}`),n.changeType(t)),r.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{Ef.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:o,frag:a,part:l,chunkMeta:c}=t,u=c.buffering[o],d=self.performance.now();u.start=d;const h=a.stats.buffering,f=l?l.stats.buffering:null;0===h.start&&(h.start=d),f&&0===f.start&&(f.start=d);const p=s.audio;let g=!1;"audio"===o&&"audio/mpeg"===(null==p?void 0:p.container)&&(g=!this.lastMpegAudioChunk||1===c.id||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);const m=a.start,y={execute:()=>{if(u.executeStart=self.performance.now(),g){const e=this.sourceBuffer[o];if(e){const t=m-e.timestampOffset;Math.abs(t)>=.1&&(Ef.log(`[buffer-controller]: Updating audio SourceBuffer timestampOffset to ${m} (delta: ${t}) sn: ${a.sn})`),e.timestampOffset=m)}}this.appendExecutor(i,o)},onStart:()=>{},onComplete:()=>{const e=self.performance.now();u.executeEnd=u.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]=vm.getBuffered(t[e]);this.appendError=0,this.hls.trigger(pf.BUFFER_APPENDED,{type:o,frag:a,part:l,chunkMeta:c,parent:a.type,timeRanges:r})},onError:e=>{Ef.error(`[buffer-controller]: Error encountered while trying to append to the ${o} SourceBuffer`,e);const t={type:gf.MEDIA_ERROR,parent:a.type,details:mf.BUFFER_APPEND_ERROR,frag:a,part:l,chunkMeta:c,error:e,err:e,fatal:!1};e.code===DOMException.QUOTA_EXCEEDED_ERR?t.details=mf.BUFFER_FULL_ERROR:(this.appendError++,t.details=mf.BUFFER_APPEND_ERROR,this.appendError>r.config.appendErrorMaxRetry&&(Ef.error(`[buffer-controller]: Failed ${r.config.appendErrorMaxRetry} times to append segment in sourceBuffer`),t.fatal=!0)),r.trigger(pf.ERROR,t)}};n.append(y,o)}onBufferFlushing(e,t){const{operationQueue:r}=this,n=e=>({execute:this.removeExecutor.bind(this,e,t.startOffset,t.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(pf.BUFFER_FLUSHED,{type:e})},onError:t=>{Ef.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[Lf]?s.push("audiovideo"):(i[If]&&s.push("audio"),i[Rf]&&s.push("video"));0===s.length&&Ef.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(pf.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,Ef.log(`[buffer-controller]: ${r} sourceBuffer now EOS`))),e&&!(n&&!n.ended)}),!0)&&(Ef.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?(Ef.log("[buffer-controller]: Calling mediaSource.endOfStream()"),e.endOfStream()):e&&Ef.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(!ff(i)||i<0)return;const o=r.currentTime,a=t.levelTargetDuration,l=Math.max(i,a),c=Math.floor(o/a)*a-l;s.forEach((r=>{const s=n[r];if(s){const n=vm.getBuffered(s);if(n.length>0&&c>n.start(0)){if(e.trigger(pf.BACK_BUFFER_REACHED,{bufferEnd:c}),t.live)e.trigger(pf.LIVE_BACK_BUFFER_REACHED,{bufferEnd:c});else if(s.ended&&n.end(n.length-1)-o<2*a)return void Ef.info(`[buffer-controller]: Cannot flush ${r} back buffer while SourceBuffer is in ended state`);e.trigger(pf.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,o=ff(n.duration)?n.duration:0;e.live&&t.config.liveDurationInfinity?(Ef.log("[buffer-controller]: Media Source duration is set to Infinity"),n.duration=1/0,this.updateSeekableRange(e)):(s>o&&s>i||!ff(i))&&(Ef.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(pf.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(pf.ERROR,{type:gf.MEDIA_ERROR,details:mf.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,o=`${s.container};codecs=${i}`;Ef.log(`[buffer-controller]: creating sourceBuffer(${o})`);try{const e=t[n]=r.addSourceBuffer(o),a=n;this.addBufferListener(a,"updatestart",this._onSBUpdateStart),this.addBufferListener(a,"updateend",this._onSBUpdateEnd),this.addBufferListener(a,"error",this._onSBUpdateError),this.tracks[n]={buffer:e,codec:i,container:s.container,levelCodec:s.levelCodec,metadata:s.metadata,id:s.id}}catch(e){Ef.error(`[buffer-controller]: error while trying to add sourceBuffer: ${e.message}`),this.hls.trigger(pf.ERROR,{type:gf.MEDIA_ERROR,details:mf.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,mimeType:o})}}}_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`);Ef.error(`[buffer-controller]: ${r}`,t),this.hls.trigger(pf.ERROR,{type:gf.MEDIA_ERROR,details:mf.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:o}=this,a=o[e];if(!n||!s||!a)return Ef.warn(`[buffer-controller]: Attempting to remove from the ${e} SourceBuffer, but it does not exist`),void i.shiftAndExecuteNext(e);const l=ff(n.duration)?n.duration:1/0,c=ff(s.duration)?s.duration:1/0,u=Math.max(0,t),d=Math.min(r,l,c);d>u&&!a.ending?(a.ended=!1,Ef.log(`[buffer-controller]: Removing [${u},${d}] from the ${e} SourceBuffer`),a.remove(u,d)):i.shiftAndExecuteNext(e)}appendExecutor(e,t){const{operationQueue:r,sourceBuffer:n}=this,s=n[t];if(!s)return Ef.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 Ef.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:Jv,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=Ef.log.bind(Ef,"[info]:"),this.warn=Ef.warn.bind(Ef,"[warning]:"),this.error=Ef.error.bind(Ef,"[error]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(pf.ERROR,this.onError,this),e.on(pf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(pf.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(pf.ERROR,this.onError,this),e.off(pf.ERROR,this.onErrorOut,this),e.off(pf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(pf.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)===og?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 mf.FRAG_LOAD_ERROR:case mf.FRAG_LOAD_TIMEOUT:case mf.KEY_LOAD_ERROR:case mf.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case mf.FRAG_PARSING_ERROR:if(null!=(r=t.frag)&&r.gap)return void(t.errorAction={action:Vg,flags:Yg});case mf.FRAG_GAP:case mf.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=zg);case mf.LEVEL_EMPTY_ERROR:case mf.LEVEL_PARSING_ERROR:{var o,a;const e=t.parent===og?t.level:s.loadLevel;t.details===mf.LEVEL_EMPTY_ERROR&&null!=(o=t.context)&&null!=(a=o.levelDetails)&&a.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case mf.LEVEL_LOAD_ERROR:case mf.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==i?void 0:i.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.level)));case mf.AUDIO_TRACK_LOAD_ERROR:case mf.AUDIO_TRACK_LOAD_TIMEOUT:case mf.SUBTITLE_LOAD_ERROR:case mf.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const e=s.levels[s.loadLevel];if(e&&(i.type===sg&&i.groupId===e.audioGroupId||i.type===ig&&i.groupId===e.textGroupId))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=zg,void(t.errorAction.flags=Qg)}return;case mf.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const e=s.levels[s.loadLevel],r=null==e?void 0:e.attrs["HDCP-LEVEL"];r&&(t.errorAction={action:zg,flags:Xg,hdcpLevel:r})}return;case mf.BUFFER_ADD_CODEC_ERROR:case mf.REMUX_ALLOC_ERROR:return void(t.errorAction=this.getLevelSwitchAction(t,null!=(n=t.level)?n:s.loadLevel));case mf.INTERNAL_EXCEPTION:case mf.BUFFER_APPENDING_ERROR:case mf.BUFFER_APPEND_ERROR:case mf.BUFFER_FULL_ERROR:case mf.LEVEL_SWITCH_ERROR:case mf.BUFFER_STALLED_ERROR:case mf.BUFFER_SEEK_OVER_HOLE:case mf.BUFFER_NUDGE_ON_STALL:return void(t.errorAction={action:Vg,flags:Yg})}if(t.type===gf.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=Ug(this.hls.config.playlistLoadPolicy,e),s=this.playlistError++,i=null==(r=e.response)?void 0:r.code;if($g(n,s,Ng(e),i))return{action:Wg,flags:Yg,retryConfig:n,retryCount:s};const o=this.getLevelSwitchAction(e,t);return n&&(o.retryConfig=n,o.retryCount=s),o}getFragRetryOrSwitchAction(e){const t=this.hls,r=this.getVariantLevelIndex(e.frag),n=t.levels[r],{fragLoadPolicy:s,keyLoadPolicy:i}=t.config,o=Ug(e.details.startsWith("key")?i:s,e),a=t.levels.reduce(((e,t)=>e+t.fragmentError),0);if(n){var l;e.details!==mf.FRAG_GAP&&n.fragmentError++;const t=null==(l=e.response)?void 0:l.code;if($g(o,a,Ng(e),t))return{action:Wg,flags:Yg,retryConfig:o,retryCount:a}}const c=this.getLevelSwitchAction(e,r);return o&&(c.retryConfig=o,c.retryCount=a),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:o,loadLevel:a,minAutoLevel:l,maxAutoLevel:c}=r,u=null==(s=e.frag)?void 0:s.type,{type:d,groupId:h}=null!=(i=e.context)?i:{};for(let r=o.length;r--;){const s=(r+a)%o.length;if(s!==a&&s>=l&&s<=c&&0===o[s].loadError){const r=o[s];if(e.details===mf.FRAG_GAP&&e.frag){const t=o[s].details;if(t){const r=Kg(e.frag,t.fragments,e.frag.start);if(null!=r&&r.gap)continue}}else{if(d===sg&&h===r.audioGroupId||d===ig&&h===r.textGroupId)continue;if(u===ag&&n.audioGroupId===r.audioGroupId||u===lg&&n.textGroupId===r.textGroupId)continue}t=s;break}}if(t>-1&&r.loadLevel!==t)return e.levelRetry=!0,this.playlistError=0,{action:zg,flags:Yg,nextAutoLevel:t}}return{action:zg,flags:Qg}}onErrorOut(e,t){var r;switch(null==(r=t.errorAction)?void 0:r.action){case Vg:break;case zg:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===mf.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 Yg:this.switchLevel(e,i);break;case Qg:r.resolved||(r.resolved=this.redundantFailover(e));break;case Xg:s&&(t.maxHdcpLevel=Cg[Cg.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===og?e.level:t.loadLevel,s=t.levels[n],i=s.url.length,o=e.frag?e.frag.urlId:s.urlId;s.urlId!==o||e.frag&&!s.details||this.penalizeRendition(s,e);for(let a=1;a<i;a++){const l=(o+a)%i,c=r[l];if(!c||Jg(c,e,r[o]))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(pf.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(pf.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,o=1e3*s/e,a=this.hls;if(a.trigger(pf.FPS_DROP,{currentDropped:s,currentDecoded:i,totalDroppedFrames:r}),o>0&&s>a.config.fpsDroppedMonitoringThreshold*i){let e=a.currentLevel;Ef.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===a.autoLevelCapping||a.autoLevelCapping>=e)&&(e-=1,a.trigger(pf.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:a.currentLevel}),a.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:zf,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:vb,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 qm{constructor(e,t,r){super(e,t,r,"[subtitle-stream-controller]",lg),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(pf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(pf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(pf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(pf.LEVEL_LOADED,this.onLevelLoaded,this),e.on(pf.ERROR,this.onError,this),e.on(pf.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(pf.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(pf.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(pf.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(pf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(pf.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(pf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(pf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(pf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(pf.LEVEL_LOADED,this.onLevelLoaded,this),e.off(pf.ERROR,this.onError,this),e.off(pf.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(pf.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(pf.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(pf.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(pf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(pf.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state=Dm,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=Dm,!n)return;const s=this.tracksBuffered[this.currentTrackId];if(!s)return;let i;const o=r.start;for(let e=0;e<s.length;e++)if(o>=s[e].start&&o<=s[e].end){i=s[e];break}const a=r.start+r.duration;i?i.end=a:(i={start:o,end:a},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,lg)}}onFragBuffered(e,t){var r;this.loadedmetadata||t.frag.type!==og||null!=(r=this.media)&&r.buffered.length&&(this.loadedmetadata=!0)}onError(e,t){const r=t.frag;(null==r?void 0:r.type)===lg&&(this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==Lm&&(this.state=Dm))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){Jy(this.levels,t)?this.levels=t.map((e=>new Rg(e))):(this.tracksBuffered=[],this.levels=t.map((e=>{const t=new Rg(e);return this.tracksBuffered[t.id]=[],t})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,lg),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:o}=this;if(!o.length)return;const a=o[i];if(s>=o.length||s!==i||!a)return;this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||null!=(r=a.details)&&r.live){const e=this.mainDetails;if(n.deltaUpdateFailed||!e)return;const t=e.fragments[0];a.details?(l=this.alignPlaylists(n,a.details),0===l&&t&&(l=t.start,Pg(n,l))):n.hasProgramDateTime&&e.hasProgramDateTime?(Cm(n,e),l=n.fragments[0].start):t&&(l=t.start,Pg(n,l))}if(a.details=n,this.levelLastLoaded=s,this.startFragRequested||!this.mainDetails&&n.live||this.setStartPosition(a.details,l),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===Dm){Kg(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),a.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(pf.ERROR,{type:gf.MEDIA_ERROR,details:mf.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e})).then((r=>{const n=performance.now();s.trigger(pf.FRAG_DECRYPTED,{frag:t,payload:r,stats:{tstart:e,tdecrypt:n}})})).catch((e=>{this.warn(`${e.name}: ${e.message}`),this.state=Dm}))}}doTick(){if(this.media){if(this.state===Dm){const{currentTrackId:e,levels:t}=this,r=t[e];if(!t.length||!r||!r.details)return;const{config:n}=this,s=this.getLoadPosition(),i=vm.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,n.maxBufferHole),{end:o,len:a}=i,l=this.getFwdBufferInfo(this.media,og),c=r.details;if(a>this.getMaxBufferLength(null==l?void 0:l.len)+c.levelTargetDuration)return;const u=c.fragments,d=u.length,h=c.edge;let f=null;const p=this.fragPrevious;if(o<h){const e=n.maxFragLookUpTolerance,t=o>h-e?0:e;f=Kg(p,u,Math.max(u[0].start,o),t),!f&&p&&p.start<u[0].start&&(f=u[0])}else f=u[d-1];if(!f)return;if(f=this.mapToInitFragWhenRequired(f),"initSegment"!==f.sn){const e=u[f.sn-c.startSN-1];e&&e.cc===f.cc&&this.fragmentTracker.getState(e)===sm&&(f=e)}this.fragmentTracker.getState(f)===sm&&this.loadFragment(f,r,o)}}else this.state=Dm}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 ev(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends Zg{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(pf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(pf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(pf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(pf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(pf.LEVEL_LOADING,this.onLevelLoading,this),e.on(pf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(pf.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(pf.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(pf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(pf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(pf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(pf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(pf.LEVEL_LOADING,this.onLevelLoading,this),e.off(pf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(pf.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(pf.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);tv(this.media.textTracks).forEach((e=>{pg(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 o=i.details;i.details=t.details,this.log(`subtitle track ${r} loaded [${n.startSN}-${n.endSN}]`),r===this.trackId&&this.playlistLoaded(r,t,o)}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(pf.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===ig&&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(pf.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=tv(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:o}=s;this.hls.trigger(pf.SUBTITLE_TRACK_SWITCH,{id:e,groupId:r,name:n,type:i,url:o});const a=this.switchParams(s.url,null==t?void 0:t.details);this.loadPlaylist(a)}else this.hls.trigger(pf.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=tv(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 Cv(this,"textTrack1"),t=new Cv(this,"textTrack2"),r=new Cv(this,"textTrack3"),n=new Cv(this,"textTrack4");this.cea608Parser1=new Ev(1,e,t),this.cea608Parser2=new Ev(3,r,n)}e.on(pf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(pf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(pf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(pf.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(pf.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(pf.FRAG_LOADING,this.onFragLoading,this),e.on(pf.FRAG_LOADED,this.onFragLoaded,this),e.on(pf.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(pf.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(pf.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(pf.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(pf.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(pf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(pf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(pf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(pf.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(pf.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(pf.FRAG_LOADING,this.onFragLoading,this),e.off(pf.FRAG_LOADED,this.onFragLoaded,this),e.off(pf.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(pf.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(pf.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(pf.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(pf.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],u=(o=n[0],a=n[1],l=t,c=r,Math.min(a,c)-Math.max(o,l));if(u>=0&&(n[0]=Math.min(n[0],t),n[1]=Math.max(n[1],r),i=!0,u/(r-t)>.5))return}var o,a,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(pf.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(pf.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],o=this.getExistingTrack(e);if(o)r[e]=o,pg(r[e]),hg(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(pf.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=>{pg(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++)pg(t[e])}onSubtitleTracksUpdated(e,t){const r=t.subtitleTracks||[],n=r.some((e=>e.textCodec===jv));if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(Jy(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(Xv(e[n],t)){r=e[n];break}r&&(n=r)}if(n)pg(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(pf.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===og){var o,a;const e=t.frag.sn,l=null!=(o=null==t||null==(a=t.part)?void 0:a.index)?o:-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===lg)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===jv?this._parseIMSC1(r,n):this._parseVTTs(t)}}else this.hls.trigger(pf.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const r=this.hls;Gv(t,this.initPTS[e.cc],(t=>{this._appendCues(t,e.level),r.trigger(pf.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})}),(t=>{Ef.log(`Failed to parse IMSC1: ${t}`),r.trigger(pf.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})}))}_parseVTTs(e){var t;const{frag:r,payload:n}=e,{initPTS:s,unparsedVttFrags:i}=this,o=s.length-1;if(!s[r.cc]&&-1===o)return void i.push(e);const a=this.hls;Bv(null!=(t=r.initSegment)&&t.data?kp(r.initSegment.data,new Uint8Array(n)):n,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,(e=>{this._appendCues(e,r.level),a.trigger(pf.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),Ef.log(`Failed to parse VTT cue: ${t}`),s&&o>r.cc||a.trigger(pf.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:t})}))}_fallbackToIMSC1(e,t){const r=this.tracks[e.level];r.textCodec||Gv(t,this.initPTS[e.cc],(()=>{r.textCodec=jv,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=>fg(r,e)))}else{const n=this.tracks[t];if(!n)return;const s=n.default?"default":"subtitles"+t;r.trigger(pf.CUES_PARSED,{type:"subtitles",cues:e,track:s})}}onFragDecrypted(e,t){const{frag:r}=t;r.type===lg&&this.onFragLoaded(pf.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!==og||"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=>gg(e[n],t,r)))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==n){const{textTracks:e}=this;Object.keys(e).forEach((r=>gg(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 qm{constructor(e,t,r){super(e,t,r,"[audio-stream-controller]",ag),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(pf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(pf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(pf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(pf.LEVEL_LOADED,this.onLevelLoaded,this),e.on(pf.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(pf.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(pf.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(pf.ERROR,this.onError,this),e.on(pf.BUFFER_RESET,this.onBufferReset,this),e.on(pf.BUFFER_CREATED,this.onBufferCreated,this),e.on(pf.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(pf.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(pf.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(pf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(pf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(pf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(pf.LEVEL_LOADED,this.onLevelLoaded,this),e.off(pf.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(pf.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(pf.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(pf.ERROR,this.onError,this),e.off(pf.BUFFER_RESET,this.onBufferReset,this),e.off(pf.BUFFER_CREATED,this.onBufferCreated,this),e.off(pf.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(pf.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(pf.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===jm&&this.tick()}}startLoad(e){if(!this.levels)return this.startPosition=e,void(this.state=Lm);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=Dm):(this.loadedmetadata=!1,this.state=Mm),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case Dm:this.doTickIdle();break;case Mm:{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=jm}break}case Pm:{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=Dm);break}case jm:{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=Om;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=vm.bufferInfo(this.mediaBuffer,e,this.config.maxBufferHole);Gg(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=Dm}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=Dm)}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],o=i.details;if(!o||o.live&&this.levelLastLoaded!==n||this.waitForCdnTuneIn(o))return void(this.state=Mm);const a=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&a&&(this.bufferFlushed=!1,this.afterBufferFlushed(a,If,ag));const l=this.getFwdBufferInfo(a,ag);if(null===l)return;const{bufferedTrack:c,switchingTrack:u}=this;if(!u&&this._streamEnded(l,o))return e.trigger(pf.BUFFER_EOS,{type:"audio"}),void(this.state=Um);const d=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,og),h=l.len,f=this.getMaxBufferLength(null==d?void 0:d.len);if(h>=f&&!u)return;const p=o.fragments[0].start;let g=l.end;if(u&&r){const e=this.getLoadPosition();c&&u.attrs!==c.attrs&&(g=e),o.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,o),y=!1;if(m&&this.isLoopLoading(m,g)&&(y=!!m.gap,m=this.getNextFragmentLoopLoading(m,o,l,og,f)),!m)return void(this.bufferFlushed=!0);const v=d&&m.start>d.end+o.targetduration;if(v||(null==d||!d.len)&&l.len){const e=this.getAppendedFrag(m.start,og);if(null===e)return;if(y||(y=!!e.gap||!!v&&0===d.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 Rg(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=Dm):(this.switchingTrack=null,this.bufferedTrack=t,this.state=Lm),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(pf.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 o=n[i];let a=0;if(s.live||null!=(r=o.details)&&r.live){const e=this.mainDetails;if(s.fragments[0]||(s.deltaUpdateFailed=!0),s.deltaUpdateFailed||!e)return;!o.details&&s.hasProgramDateTime&&e.hasProgramDateTime?(Cm(s,e),a=s.fragments[0].start):a=this.alignPlaylists(s,o.details)}o.details=s,this.levelLastLoaded=i,this.startFragRequested||!this.mainDetails&&s.live||this.setStartPosition(o.details,a),this.state!==Mm||this.waitForCdnTuneIn(s)||(this.state=Dm),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:r,part:n,payload:s}=e,{config:i,trackId:o,levels:a}=this;if(!a)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=a[o];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 u=i.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new Vy(this.hls,ag,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,o=new bm(r.level,r.sn,r.stats.chunkCount,s.byteLength,t,i);d.push(s,f,u,"",r,n,c.totalduration,e,o,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 ${o}`);const{cache:e}=this.waitingData=this.waitingData||{frag:r,part:n,cache:new Xy,complete:!1};e.push(new Uint8Array(s)),this.waitingVideoCC=this.videoTrackCC,this.state=jm}}_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===ag)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(pf.AUDIO_TRACK_SWITCHED,uf({},e)))}this.fragBufferedComplete(r,n)}else if(!this.loadedmetadata&&r.type===og){const e=this.videoBuffer||this.media;if(e){vm.getBuffered(e).length&&(this.loadedmetadata=!0)}}}onError(e,t){var r;if(t.fatal)this.state=Bm;else switch(t.details){case mf.FRAG_GAP:case mf.FRAG_PARSING_ERROR:case mf.FRAG_DECRYPT_ERROR:case mf.FRAG_LOAD_ERROR:case mf.FRAG_LOAD_TIMEOUT:case mf.KEY_LOAD_ERROR:case mf.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ag,t);break;case mf.AUDIO_TRACK_LOAD_ERROR:case mf.AUDIO_TRACK_LOAD_TIMEOUT:case mf.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==Mm||(null==(r=t.context)?void 0:r.type)!==sg||(this.state=Dm);break;case mf.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 mf.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushed(e,{type:t}){t===If&&(this.bufferFlushed=!0,this.state===Um&&(this.state=Dm))}_handleTransmuxComplete(e){var t;const r="audio",{hls:n}=this,{remuxResult:s,chunkMeta:i}=e,o=this.getCurrentContext(i);if(!o)return void this.resetWhenMissingContext(i);const{frag:a,part:l,level:c}=o,{details:u}=c,{audio:d,text:h,id3:f,initSegment:p}=s;if(!this.fragContextChanged(a)&&u){if(this.state=Fm,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),null!=p&&p.tracks){const e=a.initSegment||a;this._bufferInitSegment(p.tracks,e,i),n.trigger(pf.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:r,tracks:p.tracks})}if(d){const{startPTS:e,endPTS:t,startDTS:r,endDTS:n}=d;l&&(l.elementaryStreams[If]={startPTS:e,endPTS:t,startDTS:r,endDTS:n}),a.setElementaryStreamInfo(If,e,t,r,n),this.bufferFragmentData(d,a,l,i)}if(null!=f&&null!=(t=f.samples)&&t.length){const e=hf({id:r,frag:a,details:u},f);n.trigger(pf.FRAG_PARSING_METADATA,e)}if(h){const e=hf({id:r,frag:a,details:u},h);n.trigger(pf.FRAG_PARSING_USERDATA,e)}}else this.fragmentTracker.removeFragment(a)}_bufferInitSegment(e,t,r){if(this.state!==Fm)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(pf.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(pf.BUFFER_APPENDING,e)}this.tick()}loadFragment(e,t,r){const n=this.fragmentTracker.getState(e);var s;(this.fragCurrent=e,this.switchingTrack||n===sm||n===om)?"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=jm):(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(pf.AUDIO_TRACK_SWITCHED,uf({},e))}},audioTrackController:class extends Zg{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(pf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(pf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(pf.LEVEL_LOADING,this.onLevelLoading,this),e.on(pf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(pf.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(pf.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(pf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(pf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(pf.LEVEL_LOADING,this.onLevelLoading,this),e.off(pf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(pf.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(pf.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 o=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,o)}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(pf.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===sg&&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(pf.AUDIO_TRACK_SWITCHING,uf({},n)),n.details&&!n.details.live)return;const o=this.switchParams(n.url,null==r?void 0:r.details);this.loadPlaylist(o)}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(pf.ERROR,{type:gf.MEDIA_ERROR,details:mf.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(pf.AUDIO_TRACK_LOADING,{url:s,id:r,groupId:n,deliveryDirectives:e||null})}}},emeController:eb,cmcdController:lb,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=Ef.log.bind(Ef,"[content-steering]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(pf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(pf.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(pf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(pf.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(pf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(pf.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(pf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(pf.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)===zg&&r.flags===Qg){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,o=this.hls.levels[i];if(t=this.getLevelsForPathway(s),t.length>0){this.log(`Setting Pathway to "${s}"`),this.pathwayId=s,this.hls.trigger(pf.LEVELS_UPDATED,{levels:t});const e=this.hls.levels[i];o&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==o.bitrate&&this.log(`Unstable Pathways change from bitrate ${o.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":o}=e;if(t.some((e=>e.pathwayId===s)))return;const a=this.getLevelsForPathway(i).map((e=>{const t=hf({},e);t.details=void 0,t.url=ub(e.uri,e.attrs["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",o);const i=new Cf(e.attrs);i["PATHWAY-ID"]=s;const a=i.AUDIO&&`${i.AUDIO}_clone_${s}`,l=i.SUBTITLES&&`${i.SUBTITLES}_clone_${s}`;a&&(r[i.AUDIO]=a,i.AUDIO=a),l&&(n[i.SUBTITLES]=l,i.SUBTITLES=l),t.attrs=i;const c=new Rg(t);return rm(c,"audio",a),rm(c,"text",l),c}));t.push(...a),cb(this.audioTracks,r,o,s),cb(this.subtitleTracks,n,o,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,o=i.errorRetry||i.timeoutRetry||{},a={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.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":o,"PATHWAY-CLONES":a,"PATHWAY-PRIORITY":l}=i;if(o)try{this.uri=new self.URL(o,n).href}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${o}`)}this.scheduleRefresh(this.uri||r.url),a&&this.clonePathways(a),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,a,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){self.clearTimeout(this.reloadTimer),this.reloadTimer=self.setTimeout((()=>{this.loadSteeringManifest(e)}),t)}}});function wb(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(wb):Object.keys(e).reduce(((t,r)=>(t[r]=wb(e[r]),t)),{}):e}function Eb(e){const t=e.loader;if(t!==pb&&t!==hb)Ef.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=pb,e.progressive=!0,e.enableSoftwareAES=!0,Ef.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class Tb{static get version(){return"1.4.10"}static isSupported(){return function(){const e=Bp();if(!e)return!1;const t=Km(),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 pf}static get ErrorTypes(){return gf}static get ErrorDetails(){return mf}static get DefaultConfig(){return Tb.defaultConfig?Tb.defaultConfig:bb}static set DefaultConfig(e){Tb.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Gy,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){wf(e,"debug","log","info","warn","error");try{bf.log(`Debug logs enabled for "${t}" in hls.js version 1.4.10`)}catch(e){bf=vf}}else bf=vf}(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=wb(e),n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((e=>{const s=`${"level"===e?"playlist":e}LoadPolicy`,i=void 0===t[s],o=[];n.forEach((n=>{const a=`${e}Loading${n}`,l=t[a];if(void 0!==l&&i){o.push(a);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}}})),o.length&&Ef.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${s}": ${JSON.stringify(t[s])}`)})),uf(uf({},r),t)}(Tb.DefaultConfig,e);this.userConfig=e,this._autoLevelCapping=-1,t.progressive&&Eb(t);const{abrController:r,bufferController:n,capLevelController:s,errorController:i,fpsController:o}=t,a=new i(this),l=this.abrController=new r(this),c=this.bufferController=new n(this),u=this.capLevelController=new s(this),d=new o(this),h=new dg(this),f=new Tg(this),p=t.contentSteeringController,g=p?new p(this):null,m=this.levelController=new tm(this,g),y=new lm(this),v=new mm(this.config),b=this.streamController=new Wy(this,y,v);u.setStreamController(b),d.setStreamController(b);const w=[h,m,b];g&&w.splice(1,0,g),this.networkControllers=w;const E=[l,c,u,d,f,y];this.audioTrackController=this.createController(t.audioTrackController,w);const T=t.audioStreamController;T&&w.push(new T(this,y,v)),this.subtitleTrackController=this.createController(t.subtitleTrackController,w);const S=t.subtitleStreamController;S&&w.push(new S(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(Sg,E),this.coreComponents=E,w.push(a);const C=a.onErrorOut;"function"==typeof C&&this.on(pf.ERROR,C,a)}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){Ef.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),this.trigger(pf.ERROR,{type:gf.OTHER_ERROR,details:mf.INTERNAL_EXCEPTION,fatal:!1,event:e,error:t})}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){Ef.log("destroy"),this.trigger(pf.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){Ef.log("attachMedia"),this._media=e,this.trigger(pf.MEDIA_ATTACHING,{media:e})}detachMedia(){Ef.log("detachMedia"),this.trigger(pf.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const t=this.media,r=this.url,n=this.url=lf.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});Ef.log(`loadSource:${n}`),t&&r&&(r!==n||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(pf.MANIFEST_LOADING,{url:e})}startLoad(e=-1){Ef.log(`startLoad(${e})`),this.networkControllers.forEach((t=>{t.startLoad(e)}))}stopLoad(){Ef.log("stopLoad"),this.networkControllers.forEach((e=>{e.stopLoad()}))}swapAudioCodec(){Ef.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){Ef.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){Ef.log(`set currentLevel:${e}`),this.loadLevel=e,this.abrController.clearTimer(),this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){Ef.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){Ef.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){Ef.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){return this.levelController.startLevel}set startLevel(e){Ef.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&&(Ef.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e)}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){Cg.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}}Tb.defaultConfig=void 0;const Sb={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};function Cb(e){const t=new Uint8Array(e);let r="";return t.forEach((e=>{r+=String.fromCharCode(e)})),M(r)}function kb(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}(q(t));return crypto.subtle.importKey("pkcs8",r,Sb,!1,["sign"])}async function Ab({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=Ta.v4(),s=`nonceStr=${n}×tamp=${e}&data=${r}==`,i=(new TextEncoder).encode(s),o=await kb("-----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:Cb(await crypto.subtle.sign(Sb,o,i)),nonceStr:n}}({timestamp:r,streams:s});if(!i||!i.signature)throw new Error("Signature is undefined");const o={signature:i.signature,nonceStr:i.nonceStr,timestamp:r,streams:s},a=ye();return await a.http.post("/api/v3/user-event/video-streaming",o),t().length||e().length||n(),!0}catch(e){return s.forEach((e=>r(e))),!1}}class _b{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((()=>{Ab({bufferCurrentUsage:this.bufferCurrentUsage.bind(this),getActiveStreams:this.getActiveStreams.bind(this),updateUsage:this.updateUsage.bind(this),dispose:this.dispose.bind(this)})}),2e4)}}let Ib=null;class Rb{constructor(e,t){this.player=e,this.resolution=t,this._startTime=null,this._usageCollector=Ib||(Ib=new _b,Ib),this._usageCollector.registerStream(e.id),this._sessionId=String(Ta.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 Lb=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(!Tb.isSupported())throw new Error("This browswer does not support hls, unable to play stream");const{data:r}=await Wh(t),{watcherUrl:n,status:s,recordings:i=[],resolution:o}=r;if(!n.hls)throw new Error("This stream does not support hls. Unable to play");const a=document.createElement("video");a.id=t,a.controls=!0;const l=new Tb;if(l.attachMedia(a),"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");a.src=e.mp4.url}return new Rb(a,o).registerEvents(),a}});const Db=e=>{const t=(e=>{const t=ye(),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 La(t),t},xb=({payload:e,formData:t,isVideo:r=!1},n)=>{if(t){const s=t.get("files"),i=new FileReader;i.readAsDataURL(s),i.onload=()=>n(Db(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(Db(Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileData:null})})))},Ob=e=>{const{storyId:t,referenceId:r}=e;return r?Object.assign(Object.assign({},e),{syncState:"synced"}):Object.assign(Object.assign({},e),{syncState:"synced",referenceId:t})},Pb=e=>{const{stories:t}=e,r=t.map(Ob);return Object.assign(Object.assign({},e),{stories:r})},Mb=async e=>{const t=ye();t.log("post/createStory",e);const r=await t.http.post("/api/v4/stories",e),n=Pb(r.data);t.cache&&La(n),Ee(["story-sync-state",e.targetId],"synced"),Qe("story.created",n);const s=t.cache&&Date.now();return{data:n.stories.length>0?n.stories[0]:void 0,cachedAt:s}},Fb=e=>e?we(["story","get",e]):{data:void 0,cachedAt:void 0},Nb=async(e,t=!1)=>{const r=ye();let n;if(r.log("story/deleteStory",e),r.cache&&(n=Fb(e),null==n?void 0:n.data)){const{data:e}=n;Qe("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},Ub=async({targetType:e,targetId:t,options:r})=>{const n=ye();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"}}}),o=Pb(i.data);return n.cache&&(La(o),o.stories.forEach((e=>{const t=we(["story-expire",e.targetId]),r=new Date(e.expiresAt||0);r<new Date((null==t?void 0:t.data)||0)||Ee(["story-expire",e.targetId],r.toISOString())})),(e=>{e.forEach((e=>{Ee(["story-reference",e.storyId],e.referenceId)}))})(o.stories)),{data:o.stories,cachedAt:s,paging:{next:void 0,previous:void 0}}},Bb=e=>{const t=ye();return Ye(t,"onStoryDeleted","story.deleted",(async t=>{La(t),e(t.stories)}))},jb=e=>{const t=ye();return Ye(t,"onStoryError","story.error",(async t=>{La(t),e(t.stories)}))},$b=async e=>{const t=ye();t.log("story/getStoryByStoryId",e);const r=we(["story-reference",e]);if(null==r?void 0:r.data){const{data:e}=r;Ol("story",e)}let n;try{n=(await t.http.get(`/api/v4/stories/${e}`)).data}catch(t){throw S(null==t?void 0:t.code)&&Da("story",e),t}const s=t.cache&&Date.now();return t.cache&&La(n,{cachedAt:s}),{data:n.stories[0],cachedAt:s}};$b.locally=e=>{const t=ye();t.log("story/getStorybyStoryId",e);const r=we(["story-reference",e]);if(null==r?void 0:r.data){const{data:e}=r;Ol("story",e)}const n=t.cache&&Date.now(),s=we(["story","get",e]);if(s)return{data:s.data,cachedAt:n}};const qb=e=>t=>e((e=>t(e[0]))),Kb=async e=>{const t=ye();t.log("story/getTargetsByTargetIds",e);const r=await t.http.get("/api/v4/stories/seen",{params:{targets:e}}),{data:n}=r;return t.cache&&La(r.data),{data:n.storyTargets,cachedAt:Date.now()}};var Gb=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 o={data:{text:"",fileId:void 0,fileData:null,imageDisplayMode:s},syncState:"syncing",referenceId:Sa(),dataType:"image",items:i,targetType:e,targetId:t,metadata:n};Ee(["story-sync-state",t],"syncing"),xb({payload:o,formData:r},(e=>{Qe("story.created",e)}));try{const{data:e}=await Pu(r);if(0===e.length)throw new Error("Failed to upload image");const{fileId:t}=e[0];o=Object.assign(Object.assign({},o),{data:Object.assign(Object.assign({},o.data),{fileId:t})}),xb({payload:o,formData:r},(e=>{Qe("story.created",e)}));const n=await Mb(o);return n.data?Object.assign(Object.assign({},n),{data:el.story(n.data)}):n}catch(e){throw Ee(["story-sync-state",t],"error"),xb({payload:Object.assign(Object.assign({},o),{syncState:"error"}),formData:r},(e=>{Qe("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:Sa(),dataType:"video",items:s,targetType:e,targetId:t,metadata:n};Ee(["story-sync-state",t],"syncing"),xb({payload:i,formData:r,isVideo:!0},(e=>{Qe("story.created",e)}));try{const{data:e}=await Ou(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}})}),xb({payload:i,formData:r,isVideo:!0},(e=>{Qe("story.created",e)}));const n=await Mb(i);return n.data?Object.assign(Object.assign({},n),{data:el.story(n.data)}):n}catch(e){throw Ee(["story-sync-state",t],"error"),xb({payload:Object.assign(Object.assign({},i),{syncState:"error"}),formData:r,isVideo:!0},(e=>{Qe("story.error",e)})),e}},hardDeleteStory:async e=>await Nb(e,!0),softDeleteStory:async e=>await Nb(e),getActiveStoriesByTarget:(e,t)=>{const{log:r,cache:n}=ye(),s=[],i=["story-target","collection",e],o=Date.now();r(`getActiveStoriesByTarget(tmpid: ${o}) > listen`),n||console.log(p);const a=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(Me):t.sort(Fe):"asc"===i?t.sort(Ne):t.sort(Ue)},l=e=>{var r;const n=e.data.map((e=>{const t=Fb(e);if(null==t?void 0:t.data)return el.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=a(e.get("error")||[]);s.push(...t)}if(e.has("syncing")){const t=a(e.get("syncing")||[]);s.push(...t)}if(e.has("synced")){const t=a(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=!1,r=!1,n=!1)=>{const s=we(i),o={loading:r,error:n,params:{page:void 0},data:(null==s?void 0:s.data)||[]};e&&(o.data=t?e.map(ce("story")):[...new Set([...o.data,...e.map(ce("story"))])]),Ee(i,o.data),l(o)},u=e=>e=>{c(e)};return(t=>{const r=se(Ub,e);oe(r,(({data:e,error:r,loading:n})=>{c(e,t,n,r)}))})(!0),s.push((e=>{const t=ye();return Ye(t,"onStoryCreated","story.created",(async t=>{La(t),e(t.stories)}))})(u()),(e=>{const t=ye();return Ye(t,"onStoryUpdated","story.updated",(async t=>{La(t),e(t.stories)}))})(u()),Bb(u()),jb(u()),(e=>{const t=ye();return Ye(t,"onStoryLocalDataUpdated","local.story.updated",(t=>{e(t)}))})((e=>{const t=we(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)})),(()=>Ce(i))),()=>{r(`getActiveStoriesByTarget(tmpid: ${o}) > dispose`),s.forEach((e=>e()))}},getStoryByStoryId:(e,t)=>Tc(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:el.story(e.data)})):t(e)}),"storyId",$b,[qb(Bb),qb(jb)]),getTargetById:(e,t)=>Tc(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:el.storyTarget(e.data[0])})):t(e)}),"query",(e=>Kb([e])),[]),getTargetsByTargetIds:(e,t)=>{const{log:r,cache:n}=ye(),s=[],i=["storyTargets","collection",e],o=Date.now();r(`getTargetsByTargetIds(tmpid: ${o}) > listen`),n||console.log(p);const a=(e,r=!1,n=!1,s=!1)=>{const o=we(i),a={loading:n,error:s,params:{page:void 0},data:[]};e&&(a.data=r?e.map(ce("storyTarget")):[...new Set([...(null==o?void 0:o.data)||[],...e.map(ce("storyTarget"))])]),Ee(i,a.data),(e=>{var r;const n=e.data.map((e=>{const t=we(["storyTarget","get",e]);if(null==t?void 0:t.data)return el.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})})(a)};return(t=>{const r=se(Kb,e);oe(r,(({data:e,error:r,loading:n})=>{a(e,t,n,r)}))})(!0),s.push((()=>Ce(i))),()=>{r(`getTargetsByTargetIds(tmpid: ${o}) > dispose`),s.forEach((e=>e()))}}});return e.API_REGIONS=St,e.CategoryRepository=Mh,e.ChannelRepository=Pd,e.Client=ru,e.CommentRepository=zh,e.CommunityPostSettingMaps=o,e.CommunityPostSettings=i,e.CommunityRepository=xh,e.ContentFeedType=l,e.DefaultCommunityPostSetting=a,e.FeedRepository=Uh,e.FileRepository=Mu,e.FileType=t,e.LiveStreamPlayer=Lb,e.MessageContentType=c,e.MessageRepository=Wd,e.PollRepository=sf,e.PostContentType=u,e.PostRepository=qh,e.ReactionRepository=hd,e.StoryRepository=Gb,e.StreamRepository=ef,e.SubChannelRepository=eh,e.UserRepository=Du,e.VERSION=d,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}=ye();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=se,e.createReport=async(e,t)=>{const r=ye();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}=fd[e];return`/api/v3/${r}/${encodeURIComponent(t)}/flag`})());if(r.cache)if("message"===e){const e=await Cl(n);La(e)}else La("post"===e?Pa(n,"communityUsers"):n);return Qe(`${e}.flagged`,n),!!n},e.createUserToken=async(e,t,r)=>{const n=await ka(),s=Aa(),i=cn(kt("http",t)),{data:o}=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:o.accessToken}},e.deleteReport=async(e,t)=>{const r=ye();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}=fd[e];return`/api/v3/${r}/${encodeURIComponent(t)}/unflag`})());if(r.cache)if("message"===e){const e=await Cl(n);La(e)}else La("post"===e?Pa(n,"communityUsers"):n);return Qe(`${e}.unflagged`,n),!!n},e.disableCache=()=>{const e=ye();e.cache&&(e.log("cache/api/disableCache"),delete e.cache)},e.dropFromCache=Ce,e.enableCache=(e={},t)=>{const r=ye();r.cache||(r.log("cache/api/enableCache"),r.cache={data:e,persistIf:t})},e.filterByChannelMembership=Ie,e.filterByCommunityMembership=Le,e.filterByFeedType=Re,e.filterByPostDataTypes=De,e.filterByPropEquality=ke,e.filterByPropInclusion=(e,t,r)=>void 0!==r?e.filter((e=>r.includes(e[t]))):e,e.filterByPropIntersection=_e,e.filterBySearchTerm=xe,e.filterByStringComparePartially=Ae,e.getChannelTopic=e=>`${e.path}/#`,e.getCommentTopic=({path:e})=>e,e.getCommunityTopic=({path:t},r=e.SubscriptionLevels.COMMUNITY)=>tt(t,r),e.getMarkedMessageTopic=st,e.getMessageTopic=e=>e.path,e.getMyFollowersTopic=()=>{const e=$e();return`${rt(e)}/membership/${e._id}/+/+`},e.getMyFollowingsTopic=()=>{const e=$e();return`${rt(e)}/membership/+/${e._id}/+`},e.getNetworkTopic=it,e.getPostTopic=({path:t},r=e.SubscriptionLevels.POST)=>"comment"===r?`${t}/comment/+`:t,e.getRole=Nu,e.getSmartFeedChannelTopic=ot,e.getSmartFeedMessageTopic=lt,e.getSmartFeedSubChannelTopic=at,e.getSubChannelTopic=e=>`${e.path}/#`,e.getUserTopic=nt,e.isAfterBefore=z,e.isAfterBeforeRaw=W,e.isCachable=re,e.isFetcher=Z,e.isFresh=ne,e.isLocal=e=>re(e)&&-1===(null==e?void 0:e.cachedAt),e.isMutator=ee,e.isOffline=te,e.isPaged=Y,e.isReportedByMe=async(e,t)=>{var r;const n=ye();n.log("report/isReportedByMe",{referenceType:e,referenceId:t});const{domainName:s}=fd[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:o,isFlagByMe:a}=null!=i?i:{};return null!==(r=null!=o?o:a)&&void 0!==r&&r},e.isSkip=V,e.mergeInCache=Te,e.onChannelMarkerFetched=fc,e.onFeedMarkerFetched=e=>{const t=ye();return Ye(t,"feedMarker/onFeedMarkerFetched","local.feedMarker.fetched",(t=>{e(t.feedMarkers[0])}))},e.onFeedMarkerUpdated=mc,e.onMessageMarked=bc,e.onMessageMarkerFetched=vc,e.onSubChannelMarkerFetched=pc,e.onSubChannelMarkerUpdated=gc,e.onUserMarkerFetched=yc,e.pullFromCache=we,e.pushToCache=Ee,e.queryCache=be,e.queryOptions=ie,e.queryRoles=Fu,e.restoreCache=async(e="amitySdk")=>{var t;const r=ye();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=Oe,e.sortByFirstCreated=Me,e.sortByFirstUpdated=Ne,e.sortByLastActivity=Be,e.sortByLastCreated=Fe,e.sortByLastUpdated=Ue,e.sortByName=Pe,e.sortBySegmentNumber=({segmentNumber:e},{segmentNumber:t})=>e-t,e.subscribeTopic=ct,e.toPage=X,e.toPageRaw=J,e.toToken=Q,e.upsertInCache=Se,e.wipeCache=async(e="amitySdk")=>{const{log:t,cache:r,userId:n}=ye();return!!r&&(t("cache/api/wipeCache",{storageKey:e}),r.data={},localStorage&&await localStorage.setItem(`${e}#${n}`,"{}"),!0)},Object.defineProperty(e,"__esModule",{value:!0}),e}({});
|