@amityco/ts-sdk-react-native 6.32.0 → 6.32.2-3476a95.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/index.cjs.js +3 -3
- package/dist/index.esm.js +3 -3
- package/dist/index.umd.js +3 -3
- package/package.json +2 -2
package/dist/index.umd.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var Amity=function(e,t,n,r,o,s,a,i,c,l,d,u){"use strict";function h(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var p=h(n),f=h(r),g=h(o),m=h(s),y=h(a),v=h(i),b=h(c),w=h(d),C=h(u);const I=Object.freeze({FILE:"file",IMAGE:"image",VIDEO:"video"}),S=Object.freeze({"1080P":"1080p","720P":"720p","480P":"480p","360P":"360p",ORIGINAL:"original"}),_=Object.freeze({UPLOADED:"uploaded",TRANSCODING:"transcoding",TRANSCODED:"transcoded",TRANSCODE_FAILED:"transcodeFailed"}),k=Object.freeze({LOW:"low",MEDIUM:"medium",HIGH:"high",ORIGINAL:"original"});var O;e.FileAccessTypeEnum=void 0,(O=e.FileAccessTypeEnum||(e.FileAccessTypeEnum={})).PUBLIC="public",O.NETWORK="network";const T=Object.freeze({ONLY_ADMIN_CAN_POST:"ONLY_ADMIN_CAN_POST",ADMIN_REVIEW_POST_REQUIRED:"ADMIN_REVIEW_POST_REQUIRED",ANYONE_CAN_POST:"ANYONE_CAN_POST"}),A=Object.freeze({ONLY_ADMIN_CAN_POST:{needApprovalOnPostCreation:!1,onlyAdminCanPost:!0},ADMIN_REVIEW_POST_REQUIRED:{needApprovalOnPostCreation:!0,onlyAdminCanPost:!1},ANYONE_CAN_POST:{needApprovalOnPostCreation:!1,onlyAdminCanPost:!1}}),E="ONLY_ADMIN_CAN_POST",M=Object.freeze({STORY:"story",CLIP:"clip",CHAT:"chat",POST:"post",MESSAGE:"message"}),P=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",AUDIO:"audio",CUSTOM:"custom"}),R=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",LIVESTREAM:"liveStream",POLL:"poll"});const U=function(){try{return"v6.32.0-umd"}catch(e){return"__dev__"}}(),j=5,x="cache_then_server",D="For using Live Collection feature you need to enable Cache!",N="Observing unsynced object is not supported by Live Object.",B=1e3,q=864e5,F=6e5,L="dead",K=6e4,$=e=>JSON.stringify(e,((e,t)=>{return"object"==typeof t?(n=t,Object.keys(n).sort().reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:n[t]})),{})):t;var n})),z=e=>JSON.parse(e),Q=(e,t)=>e===t||!(!e||!t)&&("object"==typeof e&&Object.keys(e).every((n=>Q(e[n],t[n])))),V=e=>[400400,400300].includes(e),H=e=>["skip"].some((t=>t in e)),W=e=>["after","before","first","last","limit"].some((t=>t in e)),J=e=>"limit"in e,G=e=>(null==e?void 0:e.hasOwnProperty("data"))&&(null==e?void 0:e.hasOwnProperty("nextPage"))&&(null==e?void 0:e.hasOwnProperty("prevPage")),Y=(e,n)=>{var r;if(!e||!Object.keys(e).length)return;let o={};return"skiplimit"===n?o={skip:null!==(r=e.after)&&void 0!==r?r:0,limit:e.limit}:"afterbefore"===n&&W(e)?((null==e?void 0:e.before)&&(o=Object.assign(Object.assign({},o),{before:e.before})),(null==e?void 0:e.after)&&(o=Object.assign(Object.assign({},o),{after:e.after})),Number.isNaN(Number(null==e?void 0:e.limit))||(o=Object.assign(Object.assign({},o),{limit:e.limit}))):"afterbeforeraw"===n&&(o=e),Object.keys(o).length?t.encode(JSON.stringify(o)):void 0},Z=e=>{if(!e)return;const n=JSON.parse(t.decode(e));if(H(n))return{after:n.skip,limit:n.limit};if(W(n)){if("before"in n)return{before:n.before,limit:n.last};if("after"in n)return{after:n.after,limit:n.first}}},X=e=>{if(!e)return;const n=JSON.parse(t.decode(e));return J(n)?n:void 0},ee=e=>"locally"in e,te=e=>"optimistically"in e,ne=e=>ee(e)||te(e),re=e=>null==e?void 0:e.hasOwnProperty("cachedAt"),oe=(e,t=6e4)=>{var n;return Date.now()-(null!==(n=null==e?void 0:e.cachedAt)&&void 0!==n?n:0)<=t},se=(e,...t)=>({func:e,args:t}),ae=(e,t=6e4)=>"cache_only"===e?{lifeSpan:1/0}:{lifeSpan:t<K?K:t},ie=({func:e,args:t},n,r=ae("cache_then_server"))=>{let o;const{lifeSpan:s}=ae("cache_then_server",r.lifeSpan);if(ne(e)){try{o=te(e)?e.optimistically(...t):e.locally(...t)}catch(e){null==n||n(ce(void 0,{origin:"local",loading:!1,error:e}))}const r=re(o)&&oe(o,s);if(null==n||n(ce(o,{origin:"local",loading:!(ee(e)&&r)})),r)return}else null==n||n(ce(void 0,{origin:"local",loading:!0}));e(...t).then((e=>{null==n||n(ce(e,{origin:"server",loading:!1}))})).catch((e=>{null==n||n(ce(void 0,{origin:"server",loading:!1,error:e}))}))};function ce(e,t){return G(e)||re(e)?Object.assign(Object.assign({},t),e):Object.assign(Object.assign({},t),{data:e})}const le={user:({userId:e})=>e,file:({fileId:e})=>e,role:({roleId:e})=>e,channel:({channelInternalId:e})=>e,subChannel:({subChannelId:e})=>e,channelUsers:({channelId:e,userId:t})=>`${e}#${t}`,message:({messageId:e,referenceId:t})=>null!=t?t:e,messagePreviewChannel:({channelId:e})=>`${e}`,messagePreviewSubChannel:({subChannelId:e})=>`${e}`,channelUnreadInfo:({channelId:e})=>e,subChannelUnreadInfo:({subChannelId:e})=>e,channelMarker:({entityId:e,userId:t})=>`${e}#${t}`,subChannelMarker:({entityId:e,feedId:t,userId:n})=>`${e}#${t}#${n}`,messageMarker:({feedId:e,contentId:t,creatorId:n})=>`${e}#${t}#${n}`,feedMarker:({feedId:e,entityId:t})=>`${e}#${t}`,userMarker:({userId:e})=>e,community:({communityId:e})=>e,category:({categoryId:e})=>e,communityUsers:({communityId:e,userId:t})=>`${e}#${t}`,post:({postId:e})=>e,comment:({commentId:e})=>e,commentChildren:({commentId:e})=>e,poll:({pollId:e})=>e,reaction:({referenceType:e,referenceId:t})=>`${e}#${t}`,reactor:({reactionId:e})=>e,stream:({streamId:e})=>e,streamModeration:({streamId:e})=>e,follow:({from:e,to:t})=>`${e}#${t}`,followInfo:({userId:e})=>e,followCount:({userId:e})=>e,feed:({targetId:e,feedId:t})=>`${e}#${t}`,story:({referenceId:e})=>e,storyTarget:({targetId:e})=>e,ad:({adId:e})=>e,advertiser:({advertiserId:e})=>e,pin:({placement:e,referenceId:t})=>`${e}#${t}`,pinTarget:({targetId:e})=>e},de=e=>le[e],ue=e=>e.startsWith("LOCAL_"),he={users:"user",files:"file",roles:"role",stories:"story",storyTargets:"storyTarget",channels:"channel",messageFeeds:"subChannel",channelUsers:"channelUsers",messages:"message",messagePreviewChannel:"messagePreviewChannel",messagePreviewSubChannel:"messagePreviewSubChannel",channelUnreadInfo:"channelUnreadInfo",subChannelUnreadInfo:"subChannelUnreadInfo",userEntityMarkers:"channelMarker",userFeedMarkers:"subChannelMarker",contentMarkers:"messageMarker",feedMarkers:"feedMarker",userMarkers:"userMarker",communities:"community",categories:"category",communityUsers:"communityUsers",posts:"post",postChildren:"post",comments:"comment",commentChildren:"comment",polls:"poll",reactors:"reactor",reactions:"reaction",videoStreamings:"stream",videoStreamModerations:"streamModeration",follows:"follow",followCounts:"followCount",feeds:"feed",ads:"ad",advertisers:"advertiser",pinTargets:"pinTarget",pins:"pin"};function pe(e=(new Date).toISOString()){return new Date(new Date(e).getTime()+1).toISOString()}class fe extends Error{constructor(e,t,n){super(`Amity SDK (${t}): ${e}`),this.code=t,this.level=n,this.type="ASC",this.timestamp=Date.now(),Error.captureStackTrace&&Error.captureStackTrace(this,fe)}}class ge extends fe{constructor(e,t,n){super(e,t,n)}}class me extends fe{constructor(e=8e5,t="fatal"){super("Unexpected error",e,t)}}class ye extends fe{constructor(e,t="SDK client is having connection issues"){super(`${t} (${e})`,"disconnected"===e?800211:800210,"error"),this.event=e}}class ve extends fe{constructor(e){super(e,800110,"error")}}let be=null;const we=()=>{if(!be)throw new fe("There is no active client",8e5,"fatal");return be},Ce=e=>{be=e},Ie=e=>{const{log:t,cache:n}=we();if(n)return t("cache/api/queryCache",{key:e}),Object.keys(n.data).filter((t=>{const n=z(t);return Q(e,n)})).map((e=>n.data[e]))},Se=e=>{const{log:t,cache:n}=we();if(!n)return;t("cache/api/pullFromCache",e);const r=$(e);return n.data[r]?n.data[r]:void 0},_e=(e,t,n={cachedAt:Date.now()})=>{const{log:r,cache:o}=we();if(!o)return!1;r("cache/api/pushToCache",{key:e,data:t,options:n}),!(null==n?void 0:n.hasOwnProperty("offline"))&&o.persistIf&&(n.offline=o.persistIf(e,t));const s=$(e);return o.data[s]=Object.assign({key:e,data:t},n),!0},ke=(e,t,n)=>{const{log:r,cache:o}=we();if(!o)return!1;r("cache/api/mergeInCache",{key:e,mutation:t});const s=Se(e);if(!s)return!1;const a="function"==typeof t?t(s.data):Object.assign(Object.assign({},s.data),t);return i=s.data,!("updatedAt"in(c=a)&&"updatedAt"in c&&new Date(c.updatedAt)<new Date(i.updatedAt))&&(_e(e,a,n),!0);var i,c},Oe=(e,t,n={cachedAt:Date.now()})=>{const{log:r,cache:o}=we();if(!o)return!1;r("cache/api/upsertInCache",{key:e,data:t,options:n});return Se(e)?ke(e,t,n):_e(e,t,n)},Te=(e,t=!1)=>{const{log:n,cache:r}=we();if(!r)return!1;if(n("cache/api/dropFromCache",{key:e,exact:t}),!t)return Object.keys(r.data).map((e=>z(e))).filter((t=>Q(e,t))).map((e=>Te(e,!0))).every((e=>e));const o=$(e);return o in r.data&&(delete r.data[o],!0)},Ae=(e,t,n)=>void 0!==n?e.filter((e=>JSON.stringify(e[t])===JSON.stringify(n))):e,Ee=(e,t,n)=>void 0!==n?e.filter((e=>"string"==typeof e[t]&&"string"==typeof n&&String(e[t]).toLowerCase().match(n.toLowerCase()))):e,Me=(e,t,n)=>(null==n?void 0:n.length)?e.filter((e=>Array.isArray(e[t])&&n.some((n=>e[t].includes(n))))):e,Pe=(e,t,n)=>"all"===t?e:e.filter((e=>{var r;if("community"===e.type)return!0;const o=de("channelUsers")({channelId:e.channelPublicId,userId:n}),s=null===(r=Se(["channelUsers","get",o]))||void 0===r?void 0:r.data;return"member"===t?s&&"none"!==s.membership:!s||"none"===s.membership})),Re=(e,t)=>e.filter((({targetId:e,feedId:n})=>{var r;const o=null===(r=Se(["feed","get",de("feed")({targetId:e,feedId:n})]))||void 0===r?void 0:r.data;return o&&o.feedType===t})),Ue=(e,t,n)=>"all"===t?e:e.filter((e=>{var r;const o=de("communityUsers")({communityId:e.communityId,userId:n}),s=null===(r=Se(["communityUsers","get",o]))||void 0===r?void 0:r.data;return"member"===t?s&&"member"===s.communityMembership:!s||"none"!==s.communityMembership})),je=(e,t)=>e.reduce(((e,n)=>{var r;if(null==t?void 0:t.includes(n.dataType))return[...e,n];if(((null==n?void 0:n.children)||[]).length>0){const o=null===(r=Se(["post","get",n.children[0]]))||void 0===r?void 0:r.data;return(null==t?void 0:t.includes(null==o?void 0:o.dataType))?e:[...e,n]}return e}),[]),xe=(e,t)=>{const n=new RegExp(t,"i");return e.filter((e=>{var t;return!!e.userId.match(n)||e.user&&(null===(t=e.user.displayName)||void 0===t?void 0:t.match(n))}))},De=({displayName:e},{displayName:t})=>e&&t?e.localeCompare(t):e?-1:1,Ne=({name:e},{name:t})=>e&&t?e.localeCompare(t):e?-1:1,Be=({createdAt:e},{createdAt:t})=>new Date(e).valueOf()-new Date(t).valueOf(),qe=({localSortingDate:e},{localSortingDate:t})=>new Date(t).getTime()-new Date(e).getTime(),Fe=({createdAt:e},{createdAt:t})=>new Date(t).valueOf()-new Date(e).valueOf(),Le=({updatedAt:e=0},{updatedAt:t=0})=>new Date(e).valueOf()-new Date(t).valueOf(),Ke=({updatedAt:e=0},{updatedAt:t=0})=>new Date(t).valueOf()-new Date(e).valueOf(),$e=({lastActivity:e},{lastActivity:t})=>new Date(t).valueOf()-new Date(e).valueOf();let ze=null;const Qe=()=>{if(!ze)throw new fe("Connect client first",8e5,"fatal");return ze},Ve=e=>{ze={_id:e._id,userId:e.userId,path:e.path}};let He,We=[];const Je=e=>{clearTimeout(He),We.push(e),He=setTimeout((()=>{We.forEach((e=>e())),We=[]}),0)},Ge=["disconnected","error","connect_error","reconnect_error","reconnect_failed","sessionStateChange","tokenExpired","v3.video-streaming.didRecord","v3.video-streaming.didStart","v3.video-streaming.didStop"],Ye=["connect","message","disconnect","error","close","end","reconnect","user.didGlobalBan"],Ze=(e,t,n,r)=>{const{log:o,emitter:s}=e,a=Date.now();o(`${t}(tmpid: ${a}) > listen`);const i=(...e)=>{o(`${t}(tmpid: ${a}) > trigger`,e);try{r(...e)}catch(e){o(`${t}(tmpid: ${a}) > error`,e)}};return s.on(n,i),()=>{o(`${t}(tmpid: ${a}) > dispose`),s.off(n,i)}},Xe=(e,t)=>{const{emitter:n}=we();Je((()=>{n.emit(e,t)}))};let et,tt;async function nt(){var e;const{mqtt:t,emitter:n,token:r}=we(),o=null!==(e=null==r?void 0:r.accessToken)&&void 0!==e?e:"",s=Qe();et===o&&tt===s._id||(et=o,tt=s._id,await t.connect({accessToken:et,userId:tt}),((e,t)=>{Ye.forEach((n=>{e.on(n,((...e)=>{t.emit(n,1===e.length?e[0]:e)}))})),e.on("message",((e,n)=>{const r=JSON.parse(n.toString());t.emit(r.eventType,r.data)}))})(t,n))}var rt;e.SubscriptionLevels=void 0,(rt=e.SubscriptionLevels||(e.SubscriptionLevels={})).COMMUNITY="community",rt.POST="post",rt.COMMENT="comment",rt.POST_AND_COMMENT="post_and_comment",rt.USER="user";const ot=(e,t)=>{switch(t){case"post":return`${e}/post/+`;case"comment":return`${e}/post/+/comment/+`;case"post_and_comment":return`${e}/post/#`;default:return e}},st=e=>e.path.split("/user/")[0],at=({path:t},n=e.SubscriptionLevels.USER)=>ot(n===e.SubscriptionLevels.USER?t:t.replace(/^(\w*)/,"$1/social"),n),it=({channelId:e,subChannelId:t})=>{const n=Qe();return`${st(n)}/marker/channel/${e}/message/${t}`},ct=()=>{const e=Qe();return`${st(e)}/marker/user/${e._id}`},lt=()=>st(Qe()),dt=()=>{const e=Qe();return`${st(e)}/smartfeed/${e._id}/channels`},ut=()=>{const e=Qe();return`${st(e)}/smartfeed/${e._id}/messagefeeds`},ht=()=>{const e=Qe();return`${st(e)}/smartfeed/${e._id}/messages`};function pt(e,t){const{mqtt:n}=we();return nt(),n.subscribe(e,t)}var ft;const gt="object"==typeof globalThis?globalThis:"object"==typeof global?global:window,{process:mt={}}=gt,yt="production"===(null===(ft=mt.env)||void 0===ft?void 0:ft.NODE_ENV),vt={EU:"eu",SG:"sg",US:"us"},bt={http:"https://api.{region}.amity.co",mqtt:"wss://sse.{region}.amity.co:443/mqtt"};function wt(e,t){return bt[e].replace("{region}",t)}class Ct{constructor(){this._listener=new Map}onNetworkActivities(e){return this._listener.set(e,e),()=>{this._listener.delete(e)}}setNetworkActivities(e,t){this._listener.forEach((n=>n(e,t)))}destroy(){this._listener.clear()}}let It;var St,_t=()=>(It||(It=new Ct),It);!function(e){e.UserDeleted="User Deleted",e.UserGlobalBanned="User Global Banned",e.TokenExpired="Token Expired"}(St||(St={}));const kt=new AbortController,Ot=e=>{switch(e){case St.UserGlobalBanned:throw new fe(e,400312,"fatal");case St.UserDeleted:throw new fe(e,400100,"fatal");case St.TokenExpired:throw Xe("tokenExpired","tokenExpired"),new fe(e,800403,"fatal");default:throw new fe("Request Aborted",8e5,"error")}},Tt=e=>{const t={maxSockets:100,maxFreeSockets:10,timeout:6e4,freeSocketTimeout:3e4},n=g.default.create({baseURL:e,httpAgent:new m.default(t),httpsAgent:new s.HttpsAgent(t),signal:kt.signal});return n.interceptors.request.use((e=>{if("/api/v5/sessions"===e.url)return e;if(e.metadata){const{tokenExpiry:t,isGlobalBanned:n,isUserDeleted:r}=e.metadata;n&&(kt.abort(),Ot(St.UserGlobalBanned)),r&&(kt.abort(),Ot(St.UserDeleted)),t&&Date.now()>=Date.parse(t)&&(kt.abort(St.UserDeleted),Ot(St.TokenExpired))}return e})),n.interceptors.response.use((e=>{const t=new Headers;return Object.entries(e.headers).forEach((([e,n])=>{"string"==typeof n&&t.append(e,n)})),_t().setNetworkActivities(new Request(e.request.url,{method:e.request.method,headers:e.request.headers,body:e.request.data}),{data:e.data,status:e.status,statusText:e.statusText,headers:t}),e}),(e=>{var t,n;const{response:r}=e;if(400100===(null==r?void 0:r.data.code)&&Xe("tokenTerminated","terminated"),(null===(t=null==r?void 0:r.data)||void 0===t?void 0:t.status)&&(e=>{if("success"===e.status)return e.data;if("fail"===e.status)throw new me(e.code);if("error"===e.status)throw new ge(e.message,e.code,"error")})(null==r?void 0:r.data),kt.signal.aborted)throw e;throw new Error(null!==(n=null==r?void 0:r.data)&&void 0!==n?n:e)})),n.defaults.paramsSerializer={encode:e=>encodeURIComponent(e)},n};var At="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Et(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Mt(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Pt={exports:{}};Pt.exports=function(){function e(t,n,r){function o(a,i){if(!n[a]){if(!t[a]){if(!i&&Mt)return Mt(a);if(s)return s(a,!0);var c=new Error("Cannot find module '"+a+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[a]={exports:{}};t[a][0].call(l.exports,(function(e){return o(t[a][1][e]||e)}),l,l.exports,e,t,n,r)}return n[a].exports}for(var s=Mt,a=0;a<r.length;a++)o(r[a]);return o}return e}()({1:[function(e,t,n){(function(n,r){(function(){const o=e("events").EventEmitter,s=e("./store"),a=e("./topic-alias-recv"),i=e("./topic-alias-send"),c=e("mqtt-packet"),l=e("./default-message-id-provider"),d=e("readable-stream").Writable,u=e("inherits"),h=e("reinterval"),p=e("rfdc/default"),f=e("./validations"),g=e("xtend"),m=e("debug")("mqttjs:client"),y=n?n.nextTick:function(e){setTimeout(e,0)},v=r.setImmediate||function(e){y(e)},b={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1e3,connectTimeout:3e4,clean:!0,resubscribe:!0},w=["ECONNREFUSED","EADDRINUSE","ECONNRESET","ENOTFOUND"],C={0:"",1:"Unacceptable protocol version",2:"Identifier rejected",3:"Server unavailable",4:"Bad username or password",5:"Not authorized",16:"No matching subscribers",17:"No subscription existed",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",132:"Unsupported Protocol Version",133:"Client Identifier not valid",134:"Bad User Name or Password",135:"Not authorized",136:"Server unavailable",137:"Server busy",138:"Banned",139:"Server shutting down",140:"Bad authentication method",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",145:"Packet identifier in use",146:"Packet Identifier not found",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};function I(){return"mqttjs_"+Math.random().toString(16).substr(2,8)}function S(e,t){if(5===e.options.protocolVersion&&"publish"===t.cmd){let n;t.properties&&(n=t.properties.topicAlias);const r=t.topic.toString();if(e.topicAliasSend)if(n){if(0!==r.length&&(m("applyTopicAlias :: register topic: %s - alias: %d",r,n),!e.topicAliasSend.put(r,n)))return m("applyTopicAlias :: error out of range. topic: %s - alias: %d",r,n),new Error("Sending Topic Alias out of range")}else 0!==r.length&&(e.options.autoAssignTopicAlias?(n=e.topicAliasSend.getAliasByTopic(r),n?(t.topic="",t.properties={...t.properties,topicAlias:n},m("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",r,n)):(n=e.topicAliasSend.getLruAlias(),e.topicAliasSend.put(r,n),t.properties={...t.properties,topicAlias:n},m("applyTopicAlias :: auto assign topic: %s - alias: %d",r,n))):e.options.autoUseTopicAlias&&(n=e.topicAliasSend.getAliasByTopic(r),n&&(t.topic="",t.properties={...t.properties,topicAlias:n},m("applyTopicAlias :: auto use topic: %s - alias: %d",r,n))));else if(n)return m("applyTopicAlias :: error out of range. topic: %s - alias: %d",r,n),new Error("Sending Topic Alias out of range")}}function _(e,t){let n;t.properties&&(n=t.properties.topicAlias);let r=t.topic.toString();if(0===r.length){if(void 0===n)return new Error("Unregistered Topic Alias");if(r=e.topicAliasSend.getTopicByAlias(n),void 0===r)return new Error("Unregistered Topic Alias");t.topic=r}n&&delete t.properties.topicAlias}function k(e,t,n){m("sendPacket :: packet: %O",t),m("sendPacket :: emitting `packetsend`"),e.emit("packetsend",t),m("sendPacket :: writing to stream");const r=c.writeToStream(t,e.stream,e.options);m("sendPacket :: writeToStream result %s",r),!r&&n&&n!==E?(m("sendPacket :: handle events on `drain` once through callback."),e.stream.once("drain",n)):n&&(m("sendPacket :: invoking cb"),n())}function O(e){e&&(m("flush: queue exists? %b",!!e),Object.keys(e).forEach((function(t){"function"==typeof e[t].cb&&(e[t].cb(new Error("Connection closed")),delete e[t])})))}function T(e){e&&(m("flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(e).forEach((function(t){e[t].volatile&&"function"==typeof e[t].cb&&(e[t].cb(new Error("Connection closed")),delete e[t])})))}function A(e,t,n,r){m("storeAndSend :: store packet with cmd %s to outgoingStore",t.cmd);let o,s=t;if("publish"===s.cmd&&(s=p(t),o=_(e,s),o))return n&&n(o);e.outgoingStore.put(s,(function(o){if(o)return n&&n(o);r(),k(e,t,n)}))}function E(e){m("nop ::",e)}function M(e,t){let n;const r=this;if(!(this instanceof M))return new M(e,t);for(n in this.options=t||{},b)void 0===this.options[n]?this.options[n]=b[n]:this.options[n]=t[n];m("MqttClient :: options.protocol",t.protocol),m("MqttClient :: options.protocolVersion",t.protocolVersion),m("MqttClient :: options.username",t.username),m("MqttClient :: options.keepalive",t.keepalive),m("MqttClient :: options.reconnectPeriod",t.reconnectPeriod),m("MqttClient :: options.rejectUnauthorized",t.rejectUnauthorized),m("MqttClient :: options.topicAliasMaximum",t.topicAliasMaximum),this.options.clientId="string"==typeof t.clientId?t.clientId:I(),m("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=5===t.protocolVersion&&t.customHandleAcks?t.customHandleAcks:function(){arguments[3](0)},this.streamBuilder=e,this.messageIdProvider=void 0===this.options.messageIdProvider?new l:this.options.messageIdProvider,this.outgoingStore=t.outgoingStore||new s,this.incomingStore=t.incomingStore||new s,this.queueQoSZero=void 0===t.queueQoSZero||t.queueQoSZero,this._resubscribeTopics={},this.messageIdToTopic={},this.pingTimer=null,this.connected=!1,this.disconnecting=!1,this.queue=[],this.connackTimer=null,this.reconnectTimer=null,this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={},this._storeProcessingQueue=[],this.outgoing={},this._firstConnection=!0,t.topicAliasMaximum>0&&(t.topicAliasMaximum>65535?m("MqttClient :: options.topicAliasMaximum is out of range"):this.topicAliasRecv=new a(t.topicAliasMaximum)),this.on("connect",(function(){const e=this.queue;function t(){const n=e.shift();m("deliver :: entry %o",n);let o=null;if(!n)return void r._resubscribe();o=n.packet,m("deliver :: call _sendPacket for %o",o);let s=!0;o.messageId&&0!==o.messageId&&(r.messageIdProvider.register(o.messageId)||(s=!1)),s?r._sendPacket(o,(function(e){n.cb&&n.cb(e),t()})):(m("messageId: %d has already used. The message is skipped and removed.",o.messageId),t())}m("connect :: sending queued packets"),t()})),this.on("close",(function(){m("close :: connected set to `false`"),this.connected=!1,m("close :: clearing connackTimer"),clearTimeout(this.connackTimer),m("close :: clearing ping timer"),null!==r.pingTimer&&(r.pingTimer.clear(),r.pingTimer=null),this.topicAliasRecv&&this.topicAliasRecv.clear(),m("close :: calling _setupReconnect"),this._setupReconnect()})),o.call(this),m("MqttClient :: setting up stream"),this._setupStream()}u(M,o),M.prototype._setupStream=function(){const e=this,t=new d,n=c.parser(this.options);let r=null;const o=[];function s(){if(o.length)y(a);else{const e=r;r=null,e()}}function a(){m("work :: getting next packet in queue");const t=o.shift();if(t)m("work :: packet pulled from queue"),e._handlePacket(t,s);else{m("work :: no packets in queue");const e=r;r=null,m("work :: done flag is %s",!!e),e&&e()}}function i(t){m("streamErrorHandler :: error",t.message),w.includes(t.code)?(m("streamErrorHandler :: emitting error"),e.emit("error",t)):E(t)}m("_setupStream :: calling method to clear reconnect"),this._clearReconnect(),m("_setupStream :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),n.on("packet",(function(e){m("parser :: on packet push to packets array."),o.push(e)})),t._write=function(e,t,o){r=o,m("writable stream :: parsing buffer"),n.parse(e),a()},m("_setupStream :: pipe stream to writable stream"),this.stream.pipe(t),this.stream.on("error",i),this.stream.on("close",(function(){m("(%s)stream :: on close",e.options.clientId),T(e.outgoing),m("stream: emit close to MqttClient"),e.emit("close")})),m("_setupStream: sending packet `connect`");const l=Object.create(this.options);if(l.cmd="connect",this.topicAliasRecv&&(l.properties||(l.properties={}),this.topicAliasRecv&&(l.properties.topicAliasMaximum=this.topicAliasRecv.max)),k(this,l),n.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return e.end((()=>this.emit("error",new Error("Packet has no Authentication Method")))),this;this.options.properties.authenticationMethod&&this.options.authPacket&&"object"==typeof this.options.authPacket&&k(this,g({cmd:"auth",reasonCode:0},this.options.authPacket))}this.stream.setMaxListeners(1e3),clearTimeout(this.connackTimer),this.connackTimer=setTimeout((function(){m("!!connectTimeout hit!! Calling _cleanUp with force `true`"),e._cleanUp(!0)}),this.options.connectTimeout)},M.prototype._handlePacket=function(e,t){const n=this.options;if(5===n.protocolVersion&&n.properties&&n.properties.maximumPacketSize&&n.properties.maximumPacketSize<e.length)return this.emit("error",new Error("exceeding packets size "+e.cmd)),this.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}}),this;switch(m("_handlePacket :: emitting packetreceive"),this.emit("packetreceive",e),e.cmd){case"publish":this._handlePublish(e,t);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":this._handleAck(e),t();break;case"pubrel":this._handlePubrel(e,t);break;case"connack":this._handleConnack(e),t();break;case"auth":this._handleAuth(e),t();break;case"pingresp":this._handlePingresp(e),t();break;case"disconnect":this._handleDisconnect(e),t()}},M.prototype._checkDisconnecting=function(e){return this.disconnecting&&(e&&e!==E?e(new Error("client disconnecting")):this.emit("error",new Error("client disconnecting"))),this.disconnecting},M.prototype.publish=function(e,t,n,r){m("publish :: message `%s` to topic `%s`",t,e);const o=this.options;if("function"==typeof n&&(r=n,n=null),n=g({qos:0,retain:!1,dup:!1},n),this._checkDisconnecting(r))return this;const s=this,a=function(){let a=0;if((1===n.qos||2===n.qos)&&(a=s._nextId(),null===a))return m("No messageId left"),!1;const i={cmd:"publish",topic:e,payload:t,qos:n.qos,retain:n.retain,messageId:a,dup:n.dup};switch(5===o.protocolVersion&&(i.properties=n.properties),m("publish :: qos",n.qos),n.qos){case 1:case 2:s.outgoing[i.messageId]={volatile:!1,cb:r||E},m("MqttClient:publish: packet cmd: %s",i.cmd),s._sendPacket(i,void 0,n.cbStorePut);break;default:m("MqttClient:publish: packet cmd: %s",i.cmd),s._sendPacket(i,r,n.cbStorePut)}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!a())&&this._storeProcessingQueue.push({invoke:a,cbStorePut:n.cbStorePut,callback:r}),this},M.prototype.subscribe=function(){const e=this,t=new Array(arguments.length);for(let e=0;e<arguments.length;e++)t[e]=arguments[e];const n=[];let r=t.shift();const o=r.resubscribe;let s=t.pop()||E,a=t.pop();const i=this.options.protocolVersion;delete r.resubscribe,"string"==typeof r&&(r=[r]),"function"!=typeof s&&(a=s,s=E);const c=f.validateTopics(r);if(null!==c)return v(s,new Error("Invalid topic "+c)),this;if(this._checkDisconnecting(s))return m("subscribe: discconecting true"),this;const l={qos:0};if(5===i&&(l.nl=!1,l.rap=!1,l.rh=0),a=g(l,a),Array.isArray(r)?r.forEach((function(t){if(m("subscribe: array topic %s",t),!Object.prototype.hasOwnProperty.call(e._resubscribeTopics,t)||e._resubscribeTopics[t].qos<a.qos||o){const e={topic:t,qos:a.qos};5===i&&(e.nl=a.nl,e.rap=a.rap,e.rh=a.rh,e.properties=a.properties),m("subscribe: pushing topic `%s` and qos `%s` to subs list",e.topic,e.qos),n.push(e)}})):Object.keys(r).forEach((function(t){if(m("subscribe: object topic %s",t),!Object.prototype.hasOwnProperty.call(e._resubscribeTopics,t)||e._resubscribeTopics[t].qos<r[t].qos||o){const e={topic:t,qos:r[t].qos};5===i&&(e.nl=r[t].nl,e.rap=r[t].rap,e.rh=r[t].rh,e.properties=a.properties),m("subscribe: pushing `%s` to subs list",e),n.push(e)}})),!n.length)return s(null,[]),this;const d=function(){const t=e._nextId();if(null===t)return m("No messageId left"),!1;const r={cmd:"subscribe",subscriptions:n,qos:1,retain:!1,dup:!1,messageId:t};if(a.properties&&(r.properties=a.properties),e.options.resubscribe){m("subscribe :: resubscribe true");const t=[];n.forEach((function(n){if(e.options.reconnectPeriod>0){const r={qos:n.qos};5===i&&(r.nl=n.nl||!1,r.rap=n.rap||!1,r.rh=n.rh||0,r.properties=n.properties),e._resubscribeTopics[n.topic]=r,t.push(n.topic)}})),e.messageIdToTopic[r.messageId]=t}return e.outgoing[r.messageId]={volatile:!0,cb:function(e,t){if(!e){const e=t.granted;for(let t=0;t<e.length;t+=1)n[t].qos=e[t]}s(e,n)}},m("subscribe :: call _sendPacket"),e._sendPacket(r),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!d())&&this._storeProcessingQueue.push({invoke:d,callback:s}),this},M.prototype.unsubscribe=function(){const e=this,t=new Array(arguments.length);for(let e=0;e<arguments.length;e++)t[e]=arguments[e];let n=t.shift(),r=t.pop()||E,o=t.pop();"string"==typeof n&&(n=[n]),"function"!=typeof r&&(o=r,r=E);const s=f.validateTopics(n);if(null!==s)return v(r,new Error("Invalid topic "+s)),this;if(e._checkDisconnecting(r))return this;const a=function(){const t=e._nextId();if(null===t)return m("No messageId left"),!1;const s={cmd:"unsubscribe",qos:1,messageId:t};return"string"==typeof n?s.unsubscriptions=[n]:Array.isArray(n)&&(s.unsubscriptions=n),e.options.resubscribe&&s.unsubscriptions.forEach((function(t){delete e._resubscribeTopics[t]})),"object"==typeof o&&o.properties&&(s.properties=o.properties),e.outgoing[s.messageId]={volatile:!0,cb:r},m("unsubscribe: call _sendPacket"),e._sendPacket(s),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!a())&&this._storeProcessingQueue.push({invoke:a,callback:r}),this},M.prototype.end=function(e,t,n){const r=this;function o(){m("end :: closeStores: closing incoming and outgoing stores"),r.disconnected=!0,r.incomingStore.close((function(e){r.outgoingStore.close((function(t){if(m("end :: closeStores: emitting end"),r.emit("end"),n){const r=e||t;m("end :: closeStores: invoking callback with args"),n(r)}}))})),r._deferredReconnect&&r._deferredReconnect()}function s(){m("end :: (%s) :: finish :: calling _cleanUp with force %s",r.options.clientId,e),r._cleanUp(e,(()=>{m("end :: finish :: calling process.nextTick on closeStores"),y(o.bind(r))}),t)}return m("end :: (%s)",this.options.clientId),null!=e&&"boolean"==typeof e||(n=t||E,t=e,e=!1,"object"!=typeof t&&(n=t,t=null,"function"!=typeof n&&(n=E))),"object"!=typeof t&&(n=t,t=null),m("end :: cb? %s",!!n),n=n||E,this.disconnecting?(n(),this):(this._clearReconnect(),this.disconnecting=!0,!e&&Object.keys(this.outgoing).length>0?(m("end :: (%s) :: calling finish in 10ms once outgoing is empty",r.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,s,10))):(m("end :: (%s) :: immediately calling finish",r.options.clientId),s()),this)},M.prototype.removeOutgoingMessage=function(e){const t=this.outgoing[e]?this.outgoing[e].cb:null;return delete this.outgoing[e],this.outgoingStore.del({messageId:e},(function(){t(new Error("Message removed"))})),this},M.prototype.reconnect=function(e){m("client reconnect");const t=this,n=function(){e?(t.options.incomingStore=e.incomingStore,t.options.outgoingStore=e.outgoingStore):(t.options.incomingStore=null,t.options.outgoingStore=null),t.incomingStore=t.options.incomingStore||new s,t.outgoingStore=t.options.outgoingStore||new s,t.disconnecting=!1,t.disconnected=!1,t._deferredReconnect=null,t._reconnect()};return this.disconnecting&&!this.disconnected?this._deferredReconnect=n:n(),this},M.prototype._reconnect=function(){m("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected?(this.end((()=>{this._setupStream()})),m("client already connected. disconnecting first.")):(m("_reconnect: calling _setupStream"),this._setupStream())},M.prototype._setupReconnect=function(){const e=this;!e.disconnecting&&!e.reconnectTimer&&e.options.reconnectPeriod>0?(this.reconnecting||(m("_setupReconnect :: emit `offline` state"),this.emit("offline"),m("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0),m("_setupReconnect :: setting reconnectTimer for %d ms",e.options.reconnectPeriod),e.reconnectTimer=setInterval((function(){m("reconnectTimer :: reconnect triggered!"),e._reconnect()}),e.options.reconnectPeriod)):m("_setupReconnect :: doing nothing...")},M.prototype._clearReconnect=function(){m("_clearReconnect : clearing reconnect timer"),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null)},M.prototype._cleanUp=function(e,t){const n=arguments[2];if(t&&(m("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",t)),m("_cleanUp :: forced? %s",e),e)0===this.options.reconnectPeriod&&this.options.clean&&O(this.outgoing),m("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{const e=g({cmd:"disconnect"},n);m("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(e,v.bind(null,this.stream.end.bind(this.stream)))}this.disconnecting||(m("_cleanUp :: client not disconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect()),null!==this.pingTimer&&(m("_cleanUp :: clearing pingTimer"),this.pingTimer.clear(),this.pingTimer=null),t&&!this.connected&&(m("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",t),t())},M.prototype._sendPacket=function(e,t,n){m("_sendPacket :: (%s) :: start",this.options.clientId),n=n||E,t=t||E;const r=S(this,e);if(r)t(r);else{if(!this.connected)return"auth"===e.cmd?(this._shiftPingInterval(),void k(this,e,t)):(m("_sendPacket :: client not connected. Storing packet offline."),void this._storePacket(e,t,n));switch(this._shiftPingInterval(),e.cmd){case"publish":break;case"pubrel":return void A(this,e,t,n);default:return void k(this,e,t)}switch(e.qos){case 2:case 1:A(this,e,t,n);break;default:k(this,e,t)}m("_sendPacket :: (%s) :: end",this.options.clientId)}},M.prototype._storePacket=function(e,t,n){m("_storePacket :: packet: %o",e),m("_storePacket :: cb? %s",!!t),n=n||E;let r=e;if("publish"===r.cmd){r=p(e);const n=_(this,r);if(n)return t&&t(n)}0===(r.qos||0)&&this.queueQoSZero||"publish"!==r.cmd?this.queue.push({packet:r,cb:t}):r.qos>0?(t=this.outgoing[r.messageId]?this.outgoing[r.messageId].cb:null,this.outgoingStore.put(r,(function(e){if(e)return t&&t(e);n()}))):t&&t(new Error("No connection to broker"))},M.prototype._setupPingTimer=function(){m("_setupPingTimer :: keepalive %d (seconds)",this.options.keepalive);const e=this;!this.pingTimer&&this.options.keepalive&&(this.pingResp=!0,this.pingTimer=h((function(){e._checkPing()}),1e3*this.options.keepalive))},M.prototype._shiftPingInterval=function(){this.pingTimer&&this.options.keepalive&&this.options.reschedulePings&&this.pingTimer.reschedule(1e3*this.options.keepalive)},M.prototype._checkPing=function(){m("_checkPing :: checking ping..."),this.pingResp?(m("_checkPing :: ping response received. Clearing flag and sending `pingreq`"),this.pingResp=!1,this._sendPacket({cmd:"pingreq"})):(m("_checkPing :: calling _cleanUp with force true"),this._cleanUp(!0))},M.prototype._handlePingresp=function(){this.pingResp=!0},M.prototype._handleConnack=function(e){m("_handleConnack");const t=this.options,n=5===t.protocolVersion?e.reasonCode:e.returnCode;if(clearTimeout(this.connackTimer),delete this.topicAliasSend,e.properties){if(e.properties.topicAliasMaximum){if(e.properties.topicAliasMaximum>65535)return void this.emit("error",new Error("topicAliasMaximum from broker is out of range"));e.properties.topicAliasMaximum>0&&(this.topicAliasSend=new i(e.properties.topicAliasMaximum))}e.properties.serverKeepAlive&&t.keepalive&&(t.keepalive=e.properties.serverKeepAlive,this._shiftPingInterval()),e.properties.maximumPacketSize&&(t.properties||(t.properties={}),t.properties.maximumPacketSize=e.properties.maximumPacketSize)}if(0===n)this.reconnecting=!1,this._onConnect(e);else if(n>0){const e=new Error("Connection refused: "+C[n]);e.code=n,this.emit("error",e)}},M.prototype._handleAuth=function(e){const t=this.options.protocolVersion,n=5===t?e.reasonCode:e.returnCode;if(5!==t){const e=new Error("Protocol error: Auth packets are only supported in MQTT 5. Your version:"+t);return e.code=n,void this.emit("error",e)}const r=this;this.handleAuth(e,(function(e,t){if(e)r.emit("error",e);else if(24===n)r.reconnecting=!1,r._sendPacket(t);else{const t=new Error("Connection refused: "+C[n]);e.code=n,r.emit("error",t)}}))},M.prototype.handleAuth=function(e,t){t()},M.prototype._handlePublish=function(e,t){m("_handlePublish: packet %o",e),t=void 0!==t?t:E;let n=e.topic.toString();const r=e.payload,o=e.qos,s=e.messageId,a=this,i=this.options,c=[0,16,128,131,135,144,145,151,153];if(5===this.options.protocolVersion){let t;if(e.properties&&(t=e.properties.topicAlias),void 0!==t)if(0===n.length){if(!(t>0&&t<=65535))return m("_handlePublish :: topic alias out of range. alias: %d",t),void this.emit("error",new Error("Received Topic Alias is out of range"));{const e=this.topicAliasRecv.getTopicByAlias(t);if(!e)return m("_handlePublish :: unregistered topic alias. alias: %d",t),void this.emit("error",new Error("Received unregistered Topic Alias"));n=e,m("_handlePublish :: topic complemented by alias. topic: %s - alias: %d",n,t)}}else{if(!this.topicAliasRecv.put(n,t))return m("_handlePublish :: topic alias out of range. alias: %d",t),void this.emit("error",new Error("Received Topic Alias is out of range"));m("_handlePublish :: registered topic: %s - alias: %d",n,t)}}switch(m("_handlePublish: qos %d",o),o){case 2:i.customHandleAcks(n,r,e,(function(n,r){return n instanceof Error||(r=n,n=null),n?a.emit("error",n):-1===c.indexOf(r)?a.emit("error",new Error("Wrong reason code for pubrec")):void(r?a._sendPacket({cmd:"pubrec",messageId:s,reasonCode:r},t):a.incomingStore.put(e,(function(){a._sendPacket({cmd:"pubrec",messageId:s},t)})))}));break;case 1:i.customHandleAcks(n,r,e,(function(o,i){return o instanceof Error||(i=o,o=null),o?a.emit("error",o):-1===c.indexOf(i)?a.emit("error",new Error("Wrong reason code for puback")):(i||a.emit("message",n,r,e),void a.handleMessage(e,(function(e){if(e)return t&&t(e);a._sendPacket({cmd:"puback",messageId:s,reasonCode:i},t)})))}));break;case 0:this.emit("message",n,r,e),this.handleMessage(e,t);break;default:m("_handlePublish: unknown QoS. Doing nothing.")}},M.prototype.handleMessage=function(e,t){t()},M.prototype._handleAck=function(e){const t=e.messageId,n=e.cmd;let r=null;const o=this.outgoing[t]?this.outgoing[t].cb:null,s=this;let a;if(o){switch(m("_handleAck :: packet type",n),n){case"pubcomp":case"puback":{const n=e.reasonCode;n&&n>0&&16!==n&&(a=new Error("Publish error: "+C[n]),a.code=n,o(a,e)),delete this.outgoing[t],this.outgoingStore.del(e,o),this.messageIdProvider.deallocate(t),this._invokeStoreProcessingQueue();break}case"pubrec":{r={cmd:"pubrel",qos:2,messageId:t};const n=e.reasonCode;n&&n>0&&16!==n?(a=new Error("Publish error: "+C[n]),a.code=n,o(a,e)):this._sendPacket(r);break}case"suback":delete this.outgoing[t],this.messageIdProvider.deallocate(t);for(let n=0;n<e.granted.length;n++)if(0!=(128&e.granted[n])){const e=this.messageIdToTopic[t];e&&e.forEach((function(e){delete s._resubscribeTopics[e]}))}this._invokeStoreProcessingQueue(),o(null,e);break;case"unsuback":delete this.outgoing[t],this.messageIdProvider.deallocate(t),this._invokeStoreProcessingQueue(),o(null);break;default:s.emit("error",new Error("unrecognized packet type"))}this.disconnecting&&0===Object.keys(this.outgoing).length&&this.emit("outgoingEmpty")}else m("_handleAck :: Server sent an ack in error. Ignoring.")},M.prototype._handlePubrel=function(e,t){m("handling pubrel packet"),t=void 0!==t?t:E;const n=e.messageId,r=this,o={cmd:"pubcomp",messageId:n};r.incomingStore.get(e,(function(e,n){e?r._sendPacket(o,t):(r.emit("message",n.topic,n.payload,n),r.handleMessage(n,(function(e){if(e)return t(e);r.incomingStore.del(n,E),r._sendPacket(o,t)})))}))},M.prototype._handleDisconnect=function(e){this.emit("disconnect",e)},M.prototype._nextId=function(){return this.messageIdProvider.allocate()},M.prototype.getLastMessageId=function(){return this.messageIdProvider.getLastAllocated()},M.prototype._resubscribe=function(){m("_resubscribe");const e=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||5===this.options.protocolVersion&&!this.connackPacket.sessionPresent)&&e.length>0)if(this.options.resubscribe)if(5===this.options.protocolVersion){m("_resubscribe: protocolVersion 5");for(let t=0;t<e.length;t++){const n={};n[e[t]]=this._resubscribeTopics[e[t]],n.resubscribe=!0,this.subscribe(n,{properties:n[e[t]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1},M.prototype._onConnect=function(e){if(this.disconnected)return void this.emit("connect",e);const t=this;function n(){let r=t.outgoingStore.createStream();function o(){t._storeProcessing=!1,t._packetIdsDuringStoreProcessing={}}function s(){r.destroy(),r=null,t._flushStoreProcessingQueue(),o()}function a(){if(!r)return;t._storeProcessing=!0;const e=r.read(1);let n;e?t._packetIdsDuringStoreProcessing[e.messageId]?a():t.disconnecting||t.reconnectTimer?r.destroy&&r.destroy():(n=t.outgoing[e.messageId]?t.outgoing[e.messageId].cb:null,t.outgoing[e.messageId]={volatile:!1,cb:function(e,t){n&&n(e,t),a()}},t._packetIdsDuringStoreProcessing[e.messageId]=!0,t.messageIdProvider.register(e.messageId)?t._sendPacket(e):m("messageId: %d has already used.",e.messageId)):r.once("readable",a)}t.once("close",s),r.on("error",(function(e){o(),t._flushStoreProcessingQueue(),t.removeListener("close",s),t.emit("error",e)})),r.on("end",(function(){let r=!0;for(const e in t._packetIdsDuringStoreProcessing)if(!t._packetIdsDuringStoreProcessing[e]){r=!1;break}r?(o(),t.removeListener("close",s),t._invokeAllStoreProcessingQueue(),t.emit("connect",e)):n()})),a()}this.connackPacket=e,this.messageIdProvider.clear(),this._setupPingTimer(),this.connected=!0,n()},M.prototype._invokeStoreProcessingQueue=function(){if(this._storeProcessingQueue.length>0){const e=this._storeProcessingQueue[0];if(e&&e.invoke())return this._storeProcessingQueue.shift(),!0}return!1},M.prototype._invokeAllStoreProcessingQueue=function(){for(;this._invokeStoreProcessingQueue(););},M.prototype._flushStoreProcessingQueue=function(){for(const e of this._storeProcessingQueue)e.cbStorePut&&e.cbStorePut(new Error("Connection closed")),e.callback&&e.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)},t.exports=M}).call(this)}).call(this,e("_process"),void 0!==At?At:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./default-message-id-provider":7,"./store":8,"./topic-alias-recv":9,"./topic-alias-send":10,"./validations":11,_process:50,debug:18,events:22,inherits:24,"mqtt-packet":40,"readable-stream":69,reinterval:70,"rfdc/default":71,xtend:81}],2:[function(e,t,n){const{Buffer:r}=e("buffer"),o=e("readable-stream").Transform,s=e("duplexify");let a,i,c,l=!1;function d(){const e=new o;return e._write=function(e,t,n){a.sendSocketMessage({data:e.buffer,success:function(){n()},fail:function(){n(new Error)}})},e._flush=function(e){a.closeSocket({success:function(){e()}})},e}function u(e){e.hostname||(e.hostname="localhost"),e.path||(e.path="/"),e.wsOptions||(e.wsOptions={})}function h(e,t){const n="alis"===e.protocol?"wss":"ws";let r=n+"://"+e.hostname+e.path;return e.port&&80!==e.port&&443!==e.port&&(r=n+"://"+e.hostname+":"+e.port+e.path),"function"==typeof e.transformWsUrl&&(r=e.transformWsUrl(r,e,t)),r}function p(){l||(l=!0,a.onSocketOpen((function(){c.setReadable(i),c.setWritable(i),c.emit("connect")})),a.onSocketMessage((function(e){if("string"==typeof e.data){const t=r.from(e.data,"base64");i.push(t)}else{const t=new FileReader;t.addEventListener("load",(function(){let e=t.result;e=e instanceof ArrayBuffer?r.from(e):r.from(e,"utf8"),i.push(e)})),t.readAsArrayBuffer(e.data)}})),a.onSocketClose((function(){c.end(),c.destroy()})),a.onSocketError((function(e){c.destroy(e)})))}function f(e,t){if(t.hostname=t.hostname||t.host,!t.hostname)throw new Error("Could not determine host. Specify host manually.");const n="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt";u(t);const r=h(t,e);return a=t.my,a.connectSocket({url:r,protocols:n}),i=d(),c=s.obj(),p(),c}t.exports=f},{buffer:17,duplexify:20,"readable-stream":69}],3:[function(e,t,n){const r=e("net"),o=e("debug")("mqttjs:tcp");function s(e,t){t.port=t.port||1883,t.hostname=t.hostname||t.host||"localhost";const n=t.port,s=t.hostname;return o("port %d and host %s",n,s),r.createConnection(n,s)}t.exports=s},{debug:18,net:16}],4:[function(e,t,n){const r=e("tls"),o=e("net"),s=e("debug")("mqttjs:tls");function a(e,t){t.port=t.port||8883,t.host=t.hostname||t.host||"localhost",0===o.isIP(t.host)&&(t.servername=t.host),t.rejectUnauthorized=!1!==t.rejectUnauthorized,delete t.path,s("port %d host %s rejectUnauthorized %b",t.port,t.host,t.rejectUnauthorized);const n=r.connect(t);function a(r){t.rejectUnauthorized&&e.emit("error",r),n.end()}return n.on("secureConnect",(function(){t.rejectUnauthorized&&!n.authorized?n.emit("error",new Error("TLS not authorized")):n.removeListener("error",a)})),n.on("error",a),n}t.exports=a},{debug:18,net:16,tls:16}],5:[function(e,t,n){(function(n){(function(){const{Buffer:r}=e("buffer"),o=e("ws"),s=e("debug")("mqttjs:ws"),a=e("duplexify"),i=e("readable-stream").Transform,c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"],l=void 0!==n&&"browser"===n.title||"function"==typeof __webpack_require__;function d(e,t){let n=e.protocol+"://"+e.hostname+":"+e.port+e.path;return"function"==typeof e.transformWsUrl&&(n=e.transformWsUrl(n,e,t)),n}function u(e){const t=e;return e.hostname||(t.hostname="localhost"),e.port||("wss"===e.protocol?t.port=443:t.port=80),e.path||(t.path="/"),e.wsOptions||(t.wsOptions={}),l||"wss"!==e.protocol||c.forEach((function(n){Object.prototype.hasOwnProperty.call(e,n)&&!Object.prototype.hasOwnProperty.call(e.wsOptions,n)&&(t.wsOptions[n]=e[n])})),t}function h(e){const t=u(e);if(t.hostname||(t.hostname=t.host),!t.hostname){if("undefined"==typeof document)throw new Error("Could not determine host. Specify host manually.");const e=new URL(document.URL);t.hostname=e.hostname,t.port||(t.port=e.port)}return void 0===t.objectMode&&(t.objectMode=!(!0===t.binary||void 0===t.binary)),t}function p(e,t,n){s("createWebSocket"),s("protocol: "+n.protocolId+" "+n.protocolVersion);const r="MQIsdp"===n.protocolId&&3===n.protocolVersion?"mqttv3.1":"mqtt";return s("creating new Websocket for url: "+t+" and protocol: "+r),new o(t,[r],n.wsOptions)}function f(e,t){const n="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt",r=d(t,e),o=new WebSocket(r,[n]);return o.binaryType="arraybuffer",o}function g(e,t){s("streamBuilder");const n=u(t),r=d(n,e),a=p(e,r,n),i=o.createWebSocketStream(a,n.wsOptions);return i.url=r,a.on("close",(()=>{i.destroy()})),i}function m(e,t){let n;s("browserStreamBuilder");const o=h(t).browserBufferSize||524288,c=t.browserBufferTimeout||1e3,l=!t.objectMode,d=f(e,t),u=g(t,C,I);t.objectMode||(u._writev=w),u.on("close",(()=>{d.close()}));const p=void 0!==d.addEventListener;function g(e,t,n){const r=new i({objectModeMode:e.objectMode});return r._write=t,r._flush=n,r}function m(){n.setReadable(u),n.setWritable(u),n.emit("connect")}function y(){n.end(),n.destroy()}function v(e){n.destroy(e)}function b(e){let t=e.data;t=t instanceof ArrayBuffer?r.from(t):r.from(t,"utf8"),u.push(t)}function w(e,t){const n=new Array(e.length);for(let t=0;t<e.length;t++)"string"==typeof e[t].chunk?n[t]=r.from(e[t],"utf8"):n[t]=e[t].chunk;this._write(r.concat(n),"binary",t)}function C(e,t,n){d.bufferedAmount>o&&setTimeout(C,c,e,t,n),l&&"string"==typeof e&&(e=r.from(e,"utf8"));try{d.send(e)}catch(e){return n(e)}n()}function I(e){d.close(),e()}return d.readyState===d.OPEN?n=u:(n=n=a(void 0,void 0,t),t.objectMode||(n._writev=w),p?d.addEventListener("open",m):d.onopen=m),n.socket=d,p?(d.addEventListener("close",y),d.addEventListener("error",v),d.addEventListener("message",b)):(d.onclose=y,d.onerror=v,d.onmessage=b),n}t.exports=l?m:g}).call(this)}).call(this,e("_process"))},{_process:50,buffer:17,debug:18,duplexify:20,"readable-stream":69,ws:80}],6:[function(e,t,n){const{Buffer:r}=e("buffer"),o=e("readable-stream").Transform,s=e("duplexify");let a,i,c;function l(){const e=new o;return e._write=function(e,t,n){a.send({data:e.buffer,success:function(){n()},fail:function(e){n(new Error(e))}})},e._flush=function(e){a.close({success:function(){e()}})},e}function d(e){e.hostname||(e.hostname="localhost"),e.path||(e.path="/"),e.wsOptions||(e.wsOptions={})}function u(e,t){const n="wxs"===e.protocol?"wss":"ws";let r=n+"://"+e.hostname+e.path;return e.port&&80!==e.port&&443!==e.port&&(r=n+"://"+e.hostname+":"+e.port+e.path),"function"==typeof e.transformWsUrl&&(r=e.transformWsUrl(r,e,t)),r}function h(){a.onOpen((function(){c.setReadable(i),c.setWritable(i),c.emit("connect")})),a.onMessage((function(e){let t=e.data;t=t instanceof ArrayBuffer?r.from(t):r.from(t,"utf8"),i.push(t)})),a.onClose((function(){c.end(),c.destroy()})),a.onError((function(e){c.destroy(new Error(e.errMsg))}))}function p(e,t){if(t.hostname=t.hostname||t.host,!t.hostname)throw new Error("Could not determine host. Specify host manually.");const n="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt";d(t);const r=u(t,e);a=wx.connectSocket({url:r,protocols:[n]}),i=l(),c=s.obj(),c._destroy=function(e,t){a.close({success:function(){t&&t(e)}})};const o=c.destroy;return c.destroy=function(){c.destroy=o;const e=this;setTimeout((function(){a.close({fail:function(){e._destroy(new Error)}})}),0)}.bind(c),h(),c}t.exports=p},{buffer:17,duplexify:20,"readable-stream":69}],7:[function(e,t,n){function r(){if(!(this instanceof r))return new r;this.nextId=Math.max(1,Math.floor(65535*Math.random()))}r.prototype.allocate=function(){const e=this.nextId++;return 65536===this.nextId&&(this.nextId=1),e},r.prototype.getLastAllocated=function(){return 1===this.nextId?65535:this.nextId-1},r.prototype.register=function(e){return!0},r.prototype.deallocate=function(e){},r.prototype.clear=function(){},t.exports=r},{}],8:[function(e,t,n){const r=e("xtend"),o=e("readable-stream").Readable,s={objectMode:!0},a={clean:!0};function i(e){if(!(this instanceof i))return new i(e);this.options=e||{},this.options=r(a,e),this._inflights=new Map}i.prototype.put=function(e,t){return this._inflights.set(e.messageId,e),t&&t(),this},i.prototype.createStream=function(){const e=new o(s),t=[];let n=!1,r=0;return this._inflights.forEach((function(e,n){t.push(e)})),e._read=function(){!n&&r<t.length?this.push(t[r++]):this.push(null)},e.destroy=function(){if(n)return;const e=this;n=!0,setTimeout((function(){e.emit("close")}),0)},e},i.prototype.del=function(e,t){return(e=this._inflights.get(e.messageId))?(this._inflights.delete(e.messageId),t(null,e)):t&&t(new Error("missing packet")),this},i.prototype.get=function(e,t){return(e=this._inflights.get(e.messageId))?t(null,e):t&&t(new Error("missing packet")),this},i.prototype.close=function(e){this.options.clean&&(this._inflights=null),e&&e()},t.exports=i},{"readable-stream":69,xtend:81}],9:[function(e,t,n){function r(e){if(!(this instanceof r))return new r(e);this.aliasToTopic={},this.max=e}r.prototype.put=function(e,t){return!(0===t||t>this.max||(this.aliasToTopic[t]=e,this.length=Object.keys(this.aliasToTopic).length,0))},r.prototype.getTopicByAlias=function(e){return this.aliasToTopic[e]},r.prototype.clear=function(){this.aliasToTopic={}},t.exports=r},{}],10:[function(e,t,n){const r=e("lru-cache"),o=e("number-allocator").NumberAllocator;function s(e){if(!(this instanceof s))return new s(e);e>0&&(this.aliasToTopic=new r({max:e}),this.topicToAlias={},this.numberAllocator=new o(1,e),this.max=e,this.length=0)}s.prototype.put=function(e,t){if(0===t||t>this.max)return!1;const n=this.aliasToTopic.get(t);return n&&delete this.topicToAlias[n],this.aliasToTopic.set(t,e),this.topicToAlias[e]=t,this.numberAllocator.use(t),this.length=this.aliasToTopic.length,!0},s.prototype.getTopicByAlias=function(e){return this.aliasToTopic.get(e)},s.prototype.getAliasByTopic=function(e){const t=this.topicToAlias[e];return void 0!==t&&this.aliasToTopic.get(t),t},s.prototype.clear=function(){this.aliasToTopic.reset(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0},s.prototype.getLruAlias=function(){const e=this.numberAllocator.firstVacant();return e||this.aliasToTopic.keys()[this.aliasToTopic.length-1]},t.exports=s},{"lru-cache":37,"number-allocator":46}],11:[function(e,t,n){function r(e){const t=e.split("/");for(let e=0;e<t.length;e++)if("+"!==t[e]){if("#"===t[e])return e===t.length-1;if(-1!==t[e].indexOf("+")||-1!==t[e].indexOf("#"))return!1}return!0}function o(e){if(0===e.length)return"empty_topic_list";for(let t=0;t<e.length;t++)if(!r(e[t]))return e[t];return null}t.exports={validateTopics:o}},{}],12:[function(e,t,n){(function(n){(function(){const r=e("../client"),o=e("../store"),s=e("url"),a=e("xtend"),i=e("debug")("mqttjs"),c={};function l(e){let t;e.auth&&(t=e.auth.match(/^(.+):(.+)$/),t?(e.username=t[1],e.password=t[2]):e.username=e.auth)}function d(e,t){if(i("connecting to an MQTT broker..."),"object"!=typeof e||t||(t=e,e=null),t=t||{},e){const n=s.parse(e,!0);if(null!=n.port&&(n.port=Number(n.port)),null===(t=a(n,t)).protocol)throw new Error("Missing protocol");t.protocol=t.protocol.replace(/:$/,"")}if(l(t),t.query&&"string"==typeof t.query.clientId&&(t.clientId=t.query.clientId),t.cert&&t.key){if(!t.protocol)throw new Error("Missing secure protocol key");if(-1===["mqtts","wss","wxs","alis"].indexOf(t.protocol))switch(t.protocol){case"mqtt":t.protocol="mqtts";break;case"ws":t.protocol="wss";break;case"wx":t.protocol="wxs";break;case"ali":t.protocol="alis";break;default:throw new Error('Unknown protocol for secure connection: "'+t.protocol+'"!')}}if(!c[t.protocol]){const e=-1!==["mqtts","wss"].indexOf(t.protocol);t.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((function(t,n){return(!e||n%2!=0)&&"function"==typeof c[t]}))[0]}if(!1===t.clean&&!t.clientId)throw new Error("Missing clientId for unclean clients");function n(e){return t.servers&&(e._reconnectCount&&e._reconnectCount!==t.servers.length||(e._reconnectCount=0),t.host=t.servers[e._reconnectCount].host,t.port=t.servers[e._reconnectCount].port,t.protocol=t.servers[e._reconnectCount].protocol?t.servers[e._reconnectCount].protocol:t.defaultProtocol,t.hostname=t.host,e._reconnectCount++),i("calling streambuilder for",t.protocol),c[t.protocol](e,t)}t.protocol&&(t.defaultProtocol=t.protocol);const o=new r(n,t);return o.on("error",(function(){})),o}void 0!==n&&"browser"!==n.title||"function"!=typeof __webpack_require__?(c.mqtt=e("./tcp"),c.tcp=e("./tcp"),c.ssl=e("./tls"),c.tls=e("./tls"),c.mqtts=e("./tls")):(c.wx=e("./wx"),c.wxs=e("./wx"),c.ali=e("./ali"),c.alis=e("./ali")),c.ws=e("./ws"),c.wss=e("./ws"),t.exports=d,t.exports.connect=d,t.exports.MqttClient=r,t.exports.Store=o}).call(this)}).call(this,e("_process"))},{"../client":1,"../store":8,"./ali":2,"./tcp":3,"./tls":4,"./ws":5,"./wx":6,_process:50,debug:18,url:76,xtend:81}],13:[function(e,t,n){n.byteLength=d,n.toByteArray=h,n.fromByteArray=g;for(var r=[],o=[],s="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,c=a.length;i<c;++i)r[i]=a[i],o[a.charCodeAt(i)]=i;function l(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function d(e){var t=l(e),n=t[0],r=t[1];return 3*(n+r)/4-r}function u(e,t,n){return 3*(t+n)/4-n}function h(e){var t,n,r=l(e),a=r[0],i=r[1],c=new s(u(e,a,i)),d=0,h=i>0?a-4:a;for(n=0;n<h;n+=4)t=o[e.charCodeAt(n)]<<18|o[e.charCodeAt(n+1)]<<12|o[e.charCodeAt(n+2)]<<6|o[e.charCodeAt(n+3)],c[d++]=t>>16&255,c[d++]=t>>8&255,c[d++]=255&t;return 2===i&&(t=o[e.charCodeAt(n)]<<2|o[e.charCodeAt(n+1)]>>4,c[d++]=255&t),1===i&&(t=o[e.charCodeAt(n)]<<10|o[e.charCodeAt(n+1)]<<4|o[e.charCodeAt(n+2)]>>2,c[d++]=t>>8&255,c[d++]=255&t),c}function p(e){return r[e>>18&63]+r[e>>12&63]+r[e>>6&63]+r[63&e]}function f(e,t,n){for(var r,o=[],s=t;s<n;s+=3)r=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(255&e[s+2]),o.push(p(r));return o.join("")}function g(e){for(var t,n=e.length,o=n%3,s=[],a=16383,i=0,c=n-o;i<c;i+=a)s.push(f(e,i,i+a>c?c:i+a));return 1===o?(t=e[n-1],s.push(r[t>>2]+r[t<<4&63]+"==")):2===o&&(t=(e[n-2]<<8)+e[n-1],s.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"=")),s.join("")}o["-".charCodeAt(0)]=62,o["_".charCodeAt(0)]=63},{}],14:[function(e,t,n){const{Buffer:r}=e("buffer"),o=Symbol.for("BufferList");function s(e){if(!(this instanceof s))return new s(e);s._init.call(this,e)}s._init=function(e){Object.defineProperty(this,o,{value:!0}),this._bufs=[],this.length=0,e&&this.append(e)},s.prototype._new=function(e){return new s(e)},s.prototype._offset=function(e){if(0===e)return[0,0];let t=0;for(let n=0;n<this._bufs.length;n++){const r=t+this._bufs[n].length;if(e<r||n===this._bufs.length-1)return[n,e-t];t=r}},s.prototype._reverseOffset=function(e){const t=e[0];let n=e[1];for(let e=0;e<t;e++)n+=this._bufs[e].length;return n},s.prototype.get=function(e){if(e>this.length||e<0)return;const t=this._offset(e);return this._bufs[t[0]][t[1]]},s.prototype.slice=function(e,t){return"number"==typeof e&&e<0&&(e+=this.length),"number"==typeof t&&t<0&&(t+=this.length),this.copy(null,0,e,t)},s.prototype.copy=function(e,t,n,o){if(("number"!=typeof n||n<0)&&(n=0),("number"!=typeof o||o>this.length)&&(o=this.length),n>=this.length)return e||r.alloc(0);if(o<=0)return e||r.alloc(0);const s=!!e,a=this._offset(n),i=o-n;let c=i,l=s&&t||0,d=a[1];if(0===n&&o===this.length){if(!s)return 1===this._bufs.length?this._bufs[0]:r.concat(this._bufs,this.length);for(let t=0;t<this._bufs.length;t++)this._bufs[t].copy(e,l),l+=this._bufs[t].length;return e}if(c<=this._bufs[a[0]].length-d)return s?this._bufs[a[0]].copy(e,t,d,d+c):this._bufs[a[0]].slice(d,d+c);s||(e=r.allocUnsafe(i));for(let t=a[0];t<this._bufs.length;t++){const n=this._bufs[t].length-d;if(!(c>n)){this._bufs[t].copy(e,l,d,d+c),l+=n;break}this._bufs[t].copy(e,l,d),l+=n,c-=n,d&&(d=0)}return e.length>l?e.slice(0,l):e},s.prototype.shallowSlice=function(e,t){if(e=e||0,t="number"!=typeof t?this.length:t,e<0&&(e+=this.length),t<0&&(t+=this.length),e===t)return this._new();const n=this._offset(e),r=this._offset(t),o=this._bufs.slice(n[0],r[0]+1);return 0===r[1]?o.pop():o[o.length-1]=o[o.length-1].slice(0,r[1]),0!==n[1]&&(o[0]=o[0].slice(n[1])),this._new(o)},s.prototype.toString=function(e,t,n){return this.slice(t,n).toString(e)},s.prototype.consume=function(e){if(e=Math.trunc(e),Number.isNaN(e)||e<=0)return this;for(;this._bufs.length;){if(!(e>=this._bufs[0].length)){this._bufs[0]=this._bufs[0].slice(e),this.length-=e;break}e-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift()}return this},s.prototype.duplicate=function(){const e=this._new();for(let t=0;t<this._bufs.length;t++)e.append(this._bufs[t]);return e},s.prototype.append=function(e){if(null==e)return this;if(e.buffer)this._appendBuffer(r.from(e.buffer,e.byteOffset,e.byteLength));else if(Array.isArray(e))for(let t=0;t<e.length;t++)this.append(e[t]);else if(this._isBufferList(e))for(let t=0;t<e._bufs.length;t++)this.append(e._bufs[t]);else"number"==typeof e&&(e=e.toString()),this._appendBuffer(r.from(e));return this},s.prototype._appendBuffer=function(e){this._bufs.push(e),this.length+=e.length},s.prototype.indexOf=function(e,t,n){if(void 0===n&&"string"==typeof t&&(n=t,t=void 0),"function"==typeof e||Array.isArray(e))throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');if("number"==typeof e?e=r.from([e]):"string"==typeof e?e=r.from(e,n):this._isBufferList(e)?e=e.slice():Array.isArray(e.buffer)?e=r.from(e.buffer,e.byteOffset,e.byteLength):r.isBuffer(e)||(e=r.from(e)),t=Number(t||0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),0===e.length)return t>this.length?this.length:t;const o=this._offset(t);let s=o[0],a=o[1];for(;s<this._bufs.length;s++){const t=this._bufs[s];for(;a<t.length;)if(t.length-a>=e.length){const n=t.indexOf(e,a);if(-1!==n)return this._reverseOffset([s,n]);a=t.length-e.length+1}else{const t=this._reverseOffset([s,a]);if(this._match(t,e))return t;a++}a=0}return-1},s.prototype._match=function(e,t){if(this.length-e<t.length)return!1;for(let n=0;n<t.length;n++)if(this.get(e+n)!==t[n])return!1;return!0},function(){const e={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(const t in e)!function(t){null===e[t]?s.prototype[t]=function(e,n){return this.slice(e,e+n)[t](0,n)}:s.prototype[t]=function(n=0){return this.slice(n,n+e[t])[t](0)}}(t)}(),s.prototype._isBufferList=function(e){return e instanceof s||s.isBufferList(e)},s.isBufferList=function(e){return null!=e&&e[o]},t.exports=s},{buffer:17}],15:[function(e,t,n){const r=e("readable-stream").Duplex,o=e("inherits"),s=e("./BufferList");function a(e){if(!(this instanceof a))return new a(e);if("function"==typeof e){this._callback=e;const t=function(e){this._callback&&(this._callback(e),this._callback=null)}.bind(this);this.on("pipe",(function(e){e.on("error",t)})),this.on("unpipe",(function(e){e.removeListener("error",t)})),e=null}s._init.call(this,e),r.call(this)}o(a,r),Object.assign(a.prototype,s.prototype),a.prototype._new=function(e){return new a(e)},a.prototype._write=function(e,t,n){this._appendBuffer(e),"function"==typeof n&&n()},a.prototype._read=function(e){if(!this.length)return this.push(null);e=Math.min(e,this.length),this.push(this.slice(0,e)),this.consume(e)},a.prototype.end=function(e){r.prototype.end.call(this,e),this._callback&&(this._callback(null,this.slice()),this._callback=null)},a.prototype._destroy=function(e,t){this._bufs.length=0,this.length=0,t(e)},a.prototype._isBufferList=function(e){return e instanceof a||e instanceof s||a.isBufferList(e)},a.isBufferList=s.isBufferList,t.exports=a,t.exports.BufferListStream=a,t.exports.BufferList=s},{"./BufferList":14,inherits:24,"readable-stream":69}],16:[function(e,t,n){},{}],17:[function(e,t,n){(function(t){(function(){var t=e("base64-js"),r=e("ieee754");n.Buffer=i,n.SlowBuffer=y,n.INSPECT_MAX_BYTES=50;var o=2147483647;function s(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(e){return!1}}function a(e){if(e>o)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=i.prototype,t}function i(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return u(e)}return c(e,t,n)}function c(e,t,n){if("string"==typeof e)return h(e,t);if(ArrayBuffer.isView(e))return p(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(G(e,ArrayBuffer)||e&&G(e.buffer,ArrayBuffer))return f(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return i.from(r,t,n);var o=g(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return i.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function l(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function d(e,t,n){return l(e),e<=0?a(e):void 0!==t?"string"==typeof n?a(e).fill(t,n):a(e).fill(t):a(e)}function u(e){return l(e),a(e<0?0:0|m(e))}function h(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!i.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var n=0|v(e,t),r=a(n),o=r.write(e,t);return o!==n&&(r=r.slice(0,o)),r}function p(e){for(var t=e.length<0?0:0|m(e.length),n=a(t),r=0;r<t;r+=1)n[r]=255&e[r];return n}function f(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');var r;return(r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n)).__proto__=i.prototype,r}function g(e){if(i.isBuffer(e)){var t=0|m(e.length),n=a(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0!==e.length?"number"!=typeof e.length||Y(e.length)?a(0):p(e):"Buffer"===e.type&&Array.isArray(e.data)?p(e.data):void 0}function m(e){if(e>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function y(e){return+e!=e&&(e=0),i.alloc(+e)}function v(e,t){if(i.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||G(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var n=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===n)return 0;for(var o=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return Q(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return W(e).length;default:if(o)return r?-1:Q(e).length;t=(""+t).toLowerCase(),o=!0}}function b(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return x(this,t,n);case"utf8":case"utf-8":return M(this,t,n);case"ascii":return U(this,t,n);case"latin1":case"binary":return j(this,t,n);case"base64":return E(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return D(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function w(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function C(e,t,n,r,o){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),Y(n=+n)&&(n=o?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(o)return-1;n=e.length-1}else if(n<0){if(!o)return-1;n=0}if("string"==typeof t&&(t=i.from(t,r)),i.isBuffer(t))return 0===t.length?-1:I(e,t,n,r,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):I(e,[t],n,r,o);throw new TypeError("val must be string, number or Buffer")}function I(e,t,n,r,o){var s,a=1,i=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;a=2,i/=2,c/=2,n/=2}function l(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(o){var d=-1;for(s=n;s<i;s++)if(l(e,s)===l(t,-1===d?0:s-d)){if(-1===d&&(d=s),s-d+1===c)return d*a}else-1!==d&&(s-=s-d),d=-1}else for(n+c>i&&(n=i-c),s=n;s>=0;s--){for(var u=!0,h=0;h<c;h++)if(l(e,s+h)!==l(t,h)){u=!1;break}if(u)return s}return-1}function S(e,t,n,r){n=Number(n)||0;var o=e.length-n;r?(r=Number(r))>o&&(r=o):r=o;var s=t.length;r>s/2&&(r=s/2);for(var a=0;a<r;++a){var i=parseInt(t.substr(2*a,2),16);if(Y(i))return a;e[n+a]=i}return a}function _(e,t,n,r){return J(Q(t,e.length-n),e,n,r)}function k(e,t,n,r){return J(V(t),e,n,r)}function O(e,t,n,r){return k(e,t,n,r)}function T(e,t,n,r){return J(W(t),e,n,r)}function A(e,t,n,r){return J(H(t,e.length-n),e,n,r)}function E(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function M(e,t,n){n=Math.min(e.length,n);for(var r=[],o=t;o<n;){var s,a,i,c,l=e[o],d=null,u=l>239?4:l>223?3:l>191?2:1;if(o+u<=n)switch(u){case 1:l<128&&(d=l);break;case 2:128==(192&(s=e[o+1]))&&(c=(31&l)<<6|63&s)>127&&(d=c);break;case 3:s=e[o+1],a=e[o+2],128==(192&s)&&128==(192&a)&&(c=(15&l)<<12|(63&s)<<6|63&a)>2047&&(c<55296||c>57343)&&(d=c);break;case 4:s=e[o+1],a=e[o+2],i=e[o+3],128==(192&s)&&128==(192&a)&&128==(192&i)&&(c=(15&l)<<18|(63&s)<<12|(63&a)<<6|63&i)>65535&&c<1114112&&(d=c)}null===d?(d=65533,u=1):d>65535&&(d-=65536,r.push(d>>>10&1023|55296),d=56320|1023&d),r.push(d),o+=u}return R(r)}n.kMaxLength=o,i.TYPED_ARRAY_SUPPORT=s(),i.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(i.prototype,"parent",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.buffer}}),Object.defineProperty(i.prototype,"offset",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.byteOffset}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&i[Symbol.species]===i&&Object.defineProperty(i,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),i.poolSize=8192,i.from=function(e,t,n){return c(e,t,n)},i.prototype.__proto__=Uint8Array.prototype,i.__proto__=Uint8Array,i.alloc=function(e,t,n){return d(e,t,n)},i.allocUnsafe=function(e){return u(e)},i.allocUnsafeSlow=function(e){return u(e)},i.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==i.prototype},i.compare=function(e,t){if(G(e,Uint8Array)&&(e=i.from(e,e.offset,e.byteLength)),G(t,Uint8Array)&&(t=i.from(t,t.offset,t.byteLength)),!i.isBuffer(e)||!i.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var n=e.length,r=t.length,o=0,s=Math.min(n,r);o<s;++o)if(e[o]!==t[o]){n=e[o],r=t[o];break}return n<r?-1:r<n?1:0},i.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},i.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return i.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=i.allocUnsafe(t),o=0;for(n=0;n<e.length;++n){var s=e[n];if(G(s,Uint8Array)&&(s=i.from(s)),!i.isBuffer(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(r,o),o+=s.length}return r},i.byteLength=v,i.prototype._isBuffer=!0,i.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)w(this,t,t+1);return this},i.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)w(this,t,t+3),w(this,t+1,t+2);return this},i.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)w(this,t,t+7),w(this,t+1,t+6),w(this,t+2,t+5),w(this,t+3,t+4);return this},i.prototype.toString=function(){var e=this.length;return 0===e?"":0===arguments.length?M(this,0,e):b.apply(this,arguments)},i.prototype.toLocaleString=i.prototype.toString,i.prototype.equals=function(e){if(!i.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===i.compare(this,e)},i.prototype.inspect=function(){var e="",t=n.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),"<Buffer "+e+">"},i.prototype.compare=function(e,t,n,r,o){if(G(e,Uint8Array)&&(e=i.from(e,e.offset,e.byteLength)),!i.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===o&&(o=this.length),t<0||n>e.length||r<0||o>this.length)throw new RangeError("out of range index");if(r>=o&&t>=n)return 0;if(r>=o)return-1;if(t>=n)return 1;if(this===e)return 0;for(var s=(o>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0),c=Math.min(s,a),l=this.slice(r,o),d=e.slice(t,n),u=0;u<c;++u)if(l[u]!==d[u]){s=l[u],a=d[u];break}return s<a?-1:a<s?1:0},i.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},i.prototype.indexOf=function(e,t,n){return C(this,e,t,n,!0)},i.prototype.lastIndexOf=function(e,t,n){return C(this,e,t,n,!1)},i.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var o=this.length-t;if((void 0===n||n>o)&&(n=o),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var s=!1;;)switch(r){case"hex":return S(this,e,t,n);case"utf8":case"utf-8":return _(this,e,t,n);case"ascii":return k(this,e,t,n);case"latin1":case"binary":return O(this,e,t,n);case"base64":return T(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var P=4096;function R(e){var t=e.length;if(t<=P)return String.fromCharCode.apply(String,e);for(var n="",r=0;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=P));return n}function U(e,t,n){var r="";n=Math.min(e.length,n);for(var o=t;o<n;++o)r+=String.fromCharCode(127&e[o]);return r}function j(e,t,n){var r="";n=Math.min(e.length,n);for(var o=t;o<n;++o)r+=String.fromCharCode(e[o]);return r}function x(e,t,n){var r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);for(var o="",s=t;s<n;++s)o+=z(e[s]);return o}function D(e,t,n){for(var r=e.slice(t,n),o="",s=0;s<r.length;s+=2)o+=String.fromCharCode(r[s]+256*r[s+1]);return o}function N(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function B(e,t,n,r,o,s){if(!i.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||t<s)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function q(e,t,n,r,o,s){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function F(e,t,n,o,s){return t=+t,n>>>=0,s||q(e,t,n,4),r.write(e,t,n,o,23,4),n+4}function L(e,t,n,o,s){return t=+t,n>>>=0,s||q(e,t,n,8),r.write(e,t,n,o,52,8),n+8}i.prototype.slice=function(e,t){var n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);var r=this.subarray(e,t);return r.__proto__=i.prototype,r},i.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||N(e,t,this.length);for(var r=this[e],o=1,s=0;++s<t&&(o*=256);)r+=this[e+s]*o;return r},i.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||N(e,t,this.length);for(var r=this[e+--t],o=1;t>0&&(o*=256);)r+=this[e+--t]*o;return r},i.prototype.readUInt8=function(e,t){return e>>>=0,t||N(e,1,this.length),this[e]},i.prototype.readUInt16LE=function(e,t){return e>>>=0,t||N(e,2,this.length),this[e]|this[e+1]<<8},i.prototype.readUInt16BE=function(e,t){return e>>>=0,t||N(e,2,this.length),this[e]<<8|this[e+1]},i.prototype.readUInt32LE=function(e,t){return e>>>=0,t||N(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},i.prototype.readUInt32BE=function(e,t){return e>>>=0,t||N(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},i.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||N(e,t,this.length);for(var r=this[e],o=1,s=0;++s<t&&(o*=256);)r+=this[e+s]*o;return r>=(o*=128)&&(r-=Math.pow(2,8*t)),r},i.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||N(e,t,this.length);for(var r=t,o=1,s=this[e+--r];r>0&&(o*=256);)s+=this[e+--r]*o;return s>=(o*=128)&&(s-=Math.pow(2,8*t)),s},i.prototype.readInt8=function(e,t){return e>>>=0,t||N(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},i.prototype.readInt16LE=function(e,t){e>>>=0,t||N(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},i.prototype.readInt16BE=function(e,t){e>>>=0,t||N(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},i.prototype.readInt32LE=function(e,t){return e>>>=0,t||N(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},i.prototype.readInt32BE=function(e,t){return e>>>=0,t||N(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},i.prototype.readFloatLE=function(e,t){return e>>>=0,t||N(e,4,this.length),r.read(this,e,!0,23,4)},i.prototype.readFloatBE=function(e,t){return e>>>=0,t||N(e,4,this.length),r.read(this,e,!1,23,4)},i.prototype.readDoubleLE=function(e,t){return e>>>=0,t||N(e,8,this.length),r.read(this,e,!0,52,8)},i.prototype.readDoubleBE=function(e,t){return e>>>=0,t||N(e,8,this.length),r.read(this,e,!1,52,8)},i.prototype.writeUIntLE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||B(this,e,t,n,Math.pow(2,8*n)-1,0);var o=1,s=0;for(this[t]=255&e;++s<n&&(o*=256);)this[t+s]=e/o&255;return t+n},i.prototype.writeUIntBE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||B(this,e,t,n,Math.pow(2,8*n)-1,0);var o=n-1,s=1;for(this[t+o]=255&e;--o>=0&&(s*=256);)this[t+o]=e/s&255;return t+n},i.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,1,255,0),this[t]=255&e,t+1},i.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},i.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},i.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},i.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var o=Math.pow(2,8*n-1);B(this,e,t,n,o-1,-o)}var s=0,a=1,i=0;for(this[t]=255&e;++s<n&&(a*=256);)e<0&&0===i&&0!==this[t+s-1]&&(i=1),this[t+s]=(e/a>>0)-i&255;return t+n},i.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var o=Math.pow(2,8*n-1);B(this,e,t,n,o-1,-o)}var s=n-1,a=1,i=0;for(this[t+s]=255&e;--s>=0&&(a*=256);)e<0&&0===i&&0!==this[t+s+1]&&(i=1),this[t+s]=(e/a>>0)-i&255;return t+n},i.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},i.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},i.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},i.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},i.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeFloatLE=function(e,t,n){return F(this,e,t,!0,n)},i.prototype.writeFloatBE=function(e,t,n){return F(this,e,t,!1,n)},i.prototype.writeDoubleLE=function(e,t,n){return L(this,e,t,!0,n)},i.prototype.writeDoubleBE=function(e,t,n){return L(this,e,t,!1,n)},i.prototype.copy=function(e,t,n,r){if(!i.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);var o=r-n;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,n,r);else if(this===e&&n<t&&t<r)for(var s=o-1;s>=0;--s)e[s+t]=this[s+n];else Uint8Array.prototype.set.call(e,this.subarray(n,r),t);return o},i.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!i.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){var o=e.charCodeAt(0);("utf8"===r&&o<128||"latin1"===r)&&(e=o)}}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;var s;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(s=t;s<n;++s)this[s]=e;else{var a=i.isBuffer(e)?e:i.from(e,r),c=a.length;if(0===c)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(s=0;s<n-t;++s)this[s+t]=a[s%c]}return this};var K=/[^+/0-9A-Za-z-_]/g;function $(e){if((e=(e=e.split("=")[0]).trim().replace(K,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}function z(e){return e<16?"0"+e.toString(16):e.toString(16)}function Q(e,t){var n;t=t||1/0;for(var r=e.length,o=null,s=[],a=0;a<r;++a){if((n=e.charCodeAt(a))>55295&&n<57344){if(!o){if(n>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(a+1===r){(t-=3)>-1&&s.push(239,191,189);continue}o=n;continue}if(n<56320){(t-=3)>-1&&s.push(239,191,189),o=n;continue}n=65536+(o-55296<<10|n-56320)}else o&&(t-=3)>-1&&s.push(239,191,189);if(o=null,n<128){if((t-=1)<0)break;s.push(n)}else if(n<2048){if((t-=2)<0)break;s.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;s.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return s}function V(e){for(var t=[],n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}function H(e,t){for(var n,r,o,s=[],a=0;a<e.length&&!((t-=2)<0);++a)r=(n=e.charCodeAt(a))>>8,o=n%256,s.push(o),s.push(r);return s}function W(e){return t.toByteArray($(e))}function J(e,t,n,r){for(var o=0;o<r&&!(o+n>=t.length||o>=e.length);++o)t[o+n]=e[o];return o}function G(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Y(e){return e!=e}}).call(this)}).call(this,e("buffer").Buffer)},{"base64-js":13,buffer:17,ieee754:23}],18:[function(e,t,n){(function(r){(function(){function o(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))}function s(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;e.splice(1,0,n,"color: inherit");let r=0,o=0;e[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(o=r))})),e.splice(o,0,n)}function a(e){try{e?n.storage.setItem("debug",e):n.storage.removeItem("debug")}catch(e){}}function i(){let e;try{e=n.storage.getItem("debug")}catch(e){}return!e&&void 0!==r&&"env"in r&&(e=r.env.DEBUG),e}function c(){try{return localStorage}catch(e){}}n.formatArgs=s,n.save=a,n.load=i,n.useColors=o,n.storage=c(),n.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),n.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],n.log=console.debug||console.log||(()=>{}),t.exports=e("./common")(n);const{formatters:l}=t.exports;l.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}).call(this)}).call(this,e("_process"))},{"./common":19,_process:50}],19:[function(e,t,n){function r(t){function n(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return r.colors[Math.abs(t)%r.colors.length]}function r(e){let t,n,s,a=null;function i(...e){if(!i.enabled)return;const n=i,o=Number(new Date),s=o-(t||o);n.diff=s,n.prev=t,n.curr=o,t=o,e[0]=r.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((t,o)=>{if("%%"===t)return"%";a++;const s=r.formatters[o];if("function"==typeof s){const r=e[a];t=s.call(n,r),e.splice(a,1),a--}return t})),r.formatArgs.call(n,e),(n.log||r.log).apply(n,e)}return i.namespace=e,i.useColors=r.useColors(),i.color=r.selectColor(e),i.extend=o,i.destroy=r.destroy,Object.defineProperty(i,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(n!==r.namespaces&&(n=r.namespaces,s=r.enabled(e)),s),set:e=>{a=e}}),"function"==typeof r.init&&r.init(i),i}function o(e,t){const n=r(this.namespace+(void 0===t?":":t)+e);return n.log=this.log,n}function s(e){let t;r.save(e),r.namespaces=e,r.names=[],r.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),o=n.length;for(t=0;t<o;t++)n[t]&&("-"===(e=n[t].replace(/\*/g,".*?"))[0]?r.skips.push(new RegExp("^"+e.substr(1)+"$")):r.names.push(new RegExp("^"+e+"$")))}function a(){const e=[...r.names.map(c),...r.skips.map(c).map((e=>"-"+e))].join(",");return r.enable(""),e}function i(e){if("*"===e[e.length-1])return!0;let t,n;for(t=0,n=r.skips.length;t<n;t++)if(r.skips[t].test(e))return!1;for(t=0,n=r.names.length;t<n;t++)if(r.names[t].test(e))return!0;return!1}function c(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}function l(e){return e instanceof Error?e.stack||e.message:e}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.debug=r,r.default=r,r.coerce=l,r.disable=a,r.enable=s,r.enabled=i,r.humanize=e("ms"),r.destroy=d,Object.keys(t).forEach((e=>{r[e]=t[e]})),r.names=[],r.skips=[],r.formatters={},r.selectColor=n,r.enable(r.load()),r}t.exports=r},{ms:45}],20:[function(e,t,n){(function(n,r){(function(){var o=e("readable-stream"),s=e("end-of-stream"),a=e("inherits"),i=e("stream-shift"),c=r.from&&r.from!==Uint8Array.from?r.from([0]):new r([0]),l=function(e,t){e._corked?e.once("uncork",t):t()},d=function(e,t){e._autoDestroy&&e.destroy(t)},u=function(e,t){return function(n){n?d(e,"premature close"===n.message?null:n):t&&!e._ended&&e.end()}},h=function(e,t){return e?e._writableState&&e._writableState.finished?t():e._writableState?e.end(t):(e.end(),void t()):t()},p=function(){},f=function(e){return new o.Readable({objectMode:!0,highWaterMark:16}).wrap(e)},g=function(e,t,n){if(!(this instanceof g))return new g(e,t,n);o.Duplex.call(this,n),this._writable=null,this._readable=null,this._readable2=null,this._autoDestroy=!n||!1!==n.autoDestroy,this._forwardDestroy=!n||!1!==n.destroy,this._forwardEnd=!n||!1!==n.end,this._corked=1,this._ondrain=null,this._drained=!1,this._forwarding=!1,this._unwrite=null,this._unread=null,this._ended=!1,this.destroyed=!1,e&&this.setWritable(e),t&&this.setReadable(t)};a(g,o.Duplex),g.obj=function(e,t,n){return n||(n={}),n.objectMode=!0,n.highWaterMark=16,new g(e,t,n)},g.prototype.cork=function(){1==++this._corked&&this.emit("cork")},g.prototype.uncork=function(){this._corked&&0==--this._corked&&this.emit("uncork")},g.prototype.setWritable=function(e){if(this._unwrite&&this._unwrite(),this.destroyed)e&&e.destroy&&e.destroy();else if(null!==e&&!1!==e){var t=this,r=s(e,{writable:!0,readable:!1},u(this,this._forwardEnd)),o=function(){var e=t._ondrain;t._ondrain=null,e&&e()},a=function(){t._writable.removeListener("drain",o),r()};this._unwrite&&n.nextTick(o),this._writable=e,this._writable.on("drain",o),this._unwrite=a,this.uncork()}else this.end()},g.prototype.setReadable=function(e){if(this._unread&&this._unread(),this.destroyed)e&&e.destroy&&e.destroy();else{if(null===e||!1===e)return this.push(null),void this.resume();var t=this,n=s(e,{writable:!1,readable:!0},u(this)),r=function(){t._forward()},o=function(){t.push(null)},a=function(){t._readable2.removeListener("readable",r),t._readable2.removeListener("end",o),n()};this._drained=!0,this._readable=e,this._readable2=e._readableState?e:f(e),this._readable2.on("readable",r),this._readable2.on("end",o),this._unread=a,this._forward()}},g.prototype._read=function(){this._drained=!0,this._forward()},g.prototype._forward=function(){if(!this._forwarding&&this._readable2&&this._drained){var e;for(this._forwarding=!0;this._drained&&null!==(e=i(this._readable2));)this.destroyed||(this._drained=this.push(e));this._forwarding=!1}},g.prototype.destroy=function(e,t){if(t||(t=p),this.destroyed)return t(null);this.destroyed=!0;var r=this;n.nextTick((function(){r._destroy(e),t(null)}))},g.prototype._destroy=function(e){if(e){var t=this._ondrain;this._ondrain=null,t?t(e):this.emit("error",e)}this._forwardDestroy&&(this._readable&&this._readable.destroy&&this._readable.destroy(),this._writable&&this._writable.destroy&&this._writable.destroy()),this.emit("close")},g.prototype._write=function(e,t,n){if(!this.destroyed)return this._corked?l(this,this._write.bind(this,e,t,n)):e===c?this._finish(n):this._writable?void(!1===this._writable.write(e)?this._ondrain=n:this.destroyed||n()):n()},g.prototype._finish=function(e){var t=this;this.emit("preend"),l(this,(function(){h(t._forwardEnd&&t._writable,(function(){!1===t._writableState.prefinished&&(t._writableState.prefinished=!0),t.emit("prefinish"),l(t,e)}))}))},g.prototype.end=function(e,t,n){return"function"==typeof e?this.end(null,null,e):"function"==typeof t?this.end(e,null,t):(this._ended=!0,e&&this.write(e),this._writableState.ending||this._writableState.destroyed||this.write(c),o.Writable.prototype.end.call(this,n))},t.exports=g}).call(this)}).call(this,e("_process"),e("buffer").Buffer)},{_process:50,buffer:17,"end-of-stream":21,inherits:24,"readable-stream":69,"stream-shift":74}],21:[function(e,t,n){(function(n){(function(){var r=e("once"),o=function(){},s=function(e){return e.setHeader&&"function"==typeof e.abort},a=function(e){return e.stdio&&Array.isArray(e.stdio)&&3===e.stdio.length},i=function(e,t,c){if("function"==typeof t)return i(e,null,t);t||(t={}),c=r(c||o);var l=e._writableState,d=e._readableState,u=t.readable||!1!==t.readable&&e.readable,h=t.writable||!1!==t.writable&&e.writable,p=!1,f=function(){e.writable||g()},g=function(){h=!1,u||c.call(e)},m=function(){u=!1,h||c.call(e)},y=function(t){c.call(e,t?new Error("exited with error code: "+t):null)},v=function(t){c.call(e,t)},b=function(){n.nextTick(w)},w=function(){if(!p)return(!u||d&&d.ended&&!d.destroyed)&&(!h||l&&l.ended&&!l.destroyed)?void 0:c.call(e,new Error("premature close"))},C=function(){e.req.on("finish",g)};return s(e)?(e.on("complete",g),e.on("abort",b),e.req?C():e.on("request",C)):h&&!l&&(e.on("end",f),e.on("close",f)),a(e)&&e.on("exit",y),e.on("end",m),e.on("finish",g),!1!==t.error&&e.on("error",v),e.on("close",b),function(){p=!0,e.removeListener("complete",g),e.removeListener("abort",b),e.removeListener("request",C),e.req&&e.req.removeListener("finish",g),e.removeListener("end",f),e.removeListener("close",f),e.removeListener("finish",g),e.removeListener("exit",y),e.removeListener("end",m),e.removeListener("error",v),e.removeListener("close",b)}};t.exports=i}).call(this)}).call(this,e("_process"))},{_process:50,once:48}],22:[function(e,t,n){var r=Object.create||_,o=Object.keys||k,s=Function.prototype.bind||O;function a(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=r(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}t.exports=a,a.EventEmitter=a,a.prototype._events=void 0,a.prototype._maxListeners=void 0;var i,c=10;try{var l={};Object.defineProperty&&Object.defineProperty(l,"x",{value:0}),i=0===l.x}catch(e){i=!1}function d(e){return void 0===e._maxListeners?a.defaultMaxListeners:e._maxListeners}function u(e,t,n){if(t)e.call(n);else for(var r=e.length,o=I(e,r),s=0;s<r;++s)o[s].call(n)}function h(e,t,n,r){if(t)e.call(n,r);else for(var o=e.length,s=I(e,o),a=0;a<o;++a)s[a].call(n,r)}function p(e,t,n,r,o){if(t)e.call(n,r,o);else for(var s=e.length,a=I(e,s),i=0;i<s;++i)a[i].call(n,r,o)}function f(e,t,n,r,o,s){if(t)e.call(n,r,o,s);else for(var a=e.length,i=I(e,a),c=0;c<a;++c)i[c].call(n,r,o,s)}function g(e,t,n,r){if(t)e.apply(n,r);else for(var o=e.length,s=I(e,o),a=0;a<o;++a)s[a].apply(n,r)}function m(e,t,n,o){var s,a,i;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((a=e._events)?(a.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),a=e._events),i=a[t]):(a=e._events=r(null),e._eventsCount=0),i){if("function"==typeof i?i=a[t]=o?[n,i]:[i,n]:o?i.unshift(n):i.push(n),!i.warned&&(s=d(e))&&s>0&&i.length>s){i.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+i.length+' "'+String(t)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=i.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",c.name,c.message)}}else i=a[t]=n,++e._eventsCount;return e}function y(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var e=new Array(arguments.length),t=0;t<e.length;++t)e[t]=arguments[t];this.listener.apply(this.target,e)}}function v(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},o=s.call(y,r);return o.listener=n,r.wrapFn=o,o}function b(e,t,n){var r=e._events;if(!r)return[];var o=r[t];return o?"function"==typeof o?n?[o.listener||o]:[o]:n?S(o):I(o,o.length):[]}function w(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function C(e,t){for(var n=t,r=n+1,o=e.length;r<o;n+=1,r+=1)e[n]=e[r];e.pop()}function I(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}function S(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function _(e){var t=function(){};return t.prototype=e,new t}function k(e){for(var t in e)Object.prototype.hasOwnProperty.call(e,t);return t}function O(e){var t=this;return function(){return t.apply(e,arguments)}}i?Object.defineProperty(a,"defaultMaxListeners",{enumerable:!0,get:function(){return c},set:function(e){if("number"!=typeof e||e<0||e!=e)throw new TypeError('"defaultMaxListeners" must be a positive number');c=e}}):a.defaultMaxListeners=c,a.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},a.prototype.getMaxListeners=function(){return d(this)},a.prototype.emit=function(e){var t,n,r,o,s,a,i="error"===e;if(a=this._events)i=i&&null==a.error;else if(!i)return!1;if(i){if(arguments.length>1&&(t=arguments[1]),t instanceof Error)throw t;var c=new Error('Unhandled "error" event. ('+t+")");throw c.context=t,c}if(!(n=a[e]))return!1;var l="function"==typeof n;switch(r=arguments.length){case 1:u(n,l,this);break;case 2:h(n,l,this,arguments[1]);break;case 3:p(n,l,this,arguments[1],arguments[2]);break;case 4:f(n,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(o=new Array(r-1),s=1;s<r;s++)o[s-1]=arguments[s];g(n,l,this,o)}return!0},a.prototype.addListener=function(e,t){return m(this,e,t,!1)},a.prototype.on=a.prototype.addListener,a.prototype.prependListener=function(e,t){return m(this,e,t,!0)},a.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,v(this,e,t)),this},a.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,v(this,e,t)),this},a.prototype.removeListener=function(e,t){var n,o,s,a,i;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(o=this._events))return this;if(!(n=o[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=r(null):(delete o[e],o.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(s=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){i=n[a].listener,s=a;break}if(s<0)return this;0===s?n.shift():C(n,s),1===n.length&&(o[e]=n[0]),o.removeListener&&this.emit("removeListener",e,i||t)}return this},a.prototype.removeAllListeners=function(e){var t,n,s;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=r(null),this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=r(null):delete n[e]),this;if(0===arguments.length){var a,i=o(n);for(s=0;s<i.length;++s)"removeListener"!==(a=i[s])&&this.removeAllListeners(a);return this.removeAllListeners("removeListener"),this._events=r(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(t)for(s=t.length-1;s>=0;s--)this.removeListener(e,t[s]);return this},a.prototype.listeners=function(e){return b(this,e,!0)},a.prototype.rawListeners=function(e){return b(this,e,!1)},a.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):w.call(e,t)},a.prototype.listenerCount=w,a.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}},{}],23:[function(e,t,n){
|
|
1
|
+
var Amity=function(e,t,n,r,s,o,a,i,c,l,d,u){"use strict";function h(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var p=h(n),f=h(r),g=h(s),m=h(o),y=h(a),v=h(i),b=h(c),w=h(d),C=h(u);const I=Object.freeze({FILE:"file",IMAGE:"image",VIDEO:"video"}),S=Object.freeze({"1080P":"1080p","720P":"720p","480P":"480p","360P":"360p",ORIGINAL:"original"}),_=Object.freeze({UPLOADED:"uploaded",TRANSCODING:"transcoding",TRANSCODED:"transcoded",TRANSCODE_FAILED:"transcodeFailed"}),k=Object.freeze({LOW:"low",MEDIUM:"medium",HIGH:"high",ORIGINAL:"original"});var O;e.FileAccessTypeEnum=void 0,(O=e.FileAccessTypeEnum||(e.FileAccessTypeEnum={})).PUBLIC="public",O.NETWORK="network";const T=Object.freeze({ONLY_ADMIN_CAN_POST:"ONLY_ADMIN_CAN_POST",ADMIN_REVIEW_POST_REQUIRED:"ADMIN_REVIEW_POST_REQUIRED",ANYONE_CAN_POST:"ANYONE_CAN_POST"}),E=Object.freeze({ONLY_ADMIN_CAN_POST:{needApprovalOnPostCreation:!1,onlyAdminCanPost:!0},ADMIN_REVIEW_POST_REQUIRED:{needApprovalOnPostCreation:!0,onlyAdminCanPost:!1},ANYONE_CAN_POST:{needApprovalOnPostCreation:!1,onlyAdminCanPost:!1}}),A="ONLY_ADMIN_CAN_POST",M=Object.freeze({STORY:"story",CLIP:"clip",CHAT:"chat",POST:"post",MESSAGE:"message"}),P=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",AUDIO:"audio",CUSTOM:"custom"}),R=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",LIVESTREAM:"liveStream",POLL:"poll"});const U=function(){try{return"v6.32.1-umd"}catch(e){return"__dev__"}}(),j=5,x="cache_then_server",D="For using Live Collection feature you need to enable Cache!",N="Observing unsynced object is not supported by Live Object.",B=1e3,q=864e5,F=6e5,L="dead",K=6e4,$=e=>JSON.stringify(e,((e,t)=>{return"object"==typeof t?(n=t,Object.keys(n).sort().reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:n[t]})),{})):t;var n})),z=e=>JSON.parse(e),Q=(e,t)=>e===t||!(!e||!t)&&("object"==typeof e&&Object.keys(e).every((n=>Q(e[n],t[n])))),V=e=>[400400,400300].includes(e),H=e=>["skip"].some((t=>t in e)),W=e=>["after","before","first","last","limit"].some((t=>t in e)),J=e=>"limit"in e,G=e=>(null==e?void 0:e.hasOwnProperty("data"))&&(null==e?void 0:e.hasOwnProperty("nextPage"))&&(null==e?void 0:e.hasOwnProperty("prevPage")),Y=(e,n)=>{var r;if(!e||!Object.keys(e).length)return;let s={};return"skiplimit"===n?s={skip:null!==(r=e.after)&&void 0!==r?r:0,limit:e.limit}:"afterbefore"===n&&W(e)?((null==e?void 0:e.before)&&(s=Object.assign(Object.assign({},s),{before:e.before})),(null==e?void 0:e.after)&&(s=Object.assign(Object.assign({},s),{after:e.after})),Number.isNaN(Number(null==e?void 0:e.limit))||(s=Object.assign(Object.assign({},s),{limit:e.limit}))):"afterbeforeraw"===n&&(s=e),Object.keys(s).length?t.encode(JSON.stringify(s)):void 0},X=e=>{if(!e)return;const n=JSON.parse(t.decode(e));if(H(n))return{after:n.skip,limit:n.limit};if(W(n)){if("before"in n)return{before:n.before,limit:n.last};if("after"in n)return{after:n.after,limit:n.first}}},Z=e=>{if(!e)return;const n=JSON.parse(t.decode(e));return J(n)?n:void 0},ee=e=>"locally"in e,te=e=>"optimistically"in e,ne=e=>ee(e)||te(e),re=e=>null==e?void 0:e.hasOwnProperty("cachedAt"),se=(e,t=6e4)=>{var n;return Date.now()-(null!==(n=null==e?void 0:e.cachedAt)&&void 0!==n?n:0)<=t},oe=(e,...t)=>({func:e,args:t}),ae=(e,t=6e4)=>"cache_only"===e?{lifeSpan:1/0}:{lifeSpan:t<K?K:t},ie=({func:e,args:t},n,r=ae("cache_then_server"))=>{let s;const{lifeSpan:o}=ae("cache_then_server",r.lifeSpan);if(ne(e)){try{s=te(e)?e.optimistically(...t):e.locally(...t)}catch(e){null==n||n(ce(void 0,{origin:"local",loading:!1,error:e}))}const r=re(s)&&se(s,o);if(null==n||n(ce(s,{origin:"local",loading:!(ee(e)&&r)})),r)return}else null==n||n(ce(void 0,{origin:"local",loading:!0}));e(...t).then((e=>{null==n||n(ce(e,{origin:"server",loading:!1}))})).catch((e=>{null==n||n(ce(void 0,{origin:"server",loading:!1,error:e}))}))};function ce(e,t){return G(e)||re(e)?Object.assign(Object.assign({},t),e):Object.assign(Object.assign({},t),{data:e})}const le={user:({userId:e})=>e,file:({fileId:e})=>e,role:({roleId:e})=>e,channel:({channelInternalId:e})=>e,subChannel:({subChannelId:e})=>e,channelUsers:({channelId:e,userId:t})=>`${e}#${t}`,message:({messageId:e,referenceId:t})=>null!=t?t:e,messagePreviewChannel:({channelId:e})=>`${e}`,messagePreviewSubChannel:({subChannelId:e})=>`${e}`,channelUnreadInfo:({channelId:e})=>e,subChannelUnreadInfo:({subChannelId:e})=>e,channelMarker:({entityId:e,userId:t})=>`${e}#${t}`,subChannelMarker:({entityId:e,feedId:t,userId:n})=>`${e}#${t}#${n}`,messageMarker:({feedId:e,contentId:t,creatorId:n})=>`${e}#${t}#${n}`,feedMarker:({feedId:e,entityId:t})=>`${e}#${t}`,userMarker:({userId:e})=>e,community:({communityId:e})=>e,category:({categoryId:e})=>e,communityUsers:({communityId:e,userId:t})=>`${e}#${t}`,post:({postId:e})=>e,comment:({commentId:e})=>e,commentChildren:({commentId:e})=>e,poll:({pollId:e})=>e,reaction:({referenceType:e,referenceId:t})=>`${e}#${t}`,reactor:({reactionId:e})=>e,stream:({streamId:e})=>e,streamModeration:({streamId:e})=>e,follow:({from:e,to:t})=>`${e}#${t}`,followInfo:({userId:e})=>e,followCount:({userId:e})=>e,feed:({targetId:e,feedId:t})=>`${e}#${t}`,story:({referenceId:e})=>e,storyTarget:({targetId:e})=>e,ad:({adId:e})=>e,advertiser:({advertiserId:e})=>e,pin:({placement:e,referenceId:t})=>`${e}#${t}`,pinTarget:({targetId:e})=>e},de=e=>le[e],ue=e=>e.startsWith("LOCAL_"),he={users:"user",files:"file",roles:"role",stories:"story",storyTargets:"storyTarget",channels:"channel",messageFeeds:"subChannel",channelUsers:"channelUsers",messages:"message",messagePreviewChannel:"messagePreviewChannel",messagePreviewSubChannel:"messagePreviewSubChannel",channelUnreadInfo:"channelUnreadInfo",subChannelUnreadInfo:"subChannelUnreadInfo",userEntityMarkers:"channelMarker",userFeedMarkers:"subChannelMarker",contentMarkers:"messageMarker",feedMarkers:"feedMarker",userMarkers:"userMarker",communities:"community",categories:"category",communityUsers:"communityUsers",posts:"post",postChildren:"post",comments:"comment",commentChildren:"comment",polls:"poll",reactors:"reactor",reactions:"reaction",videoStreamings:"stream",videoStreamModerations:"streamModeration",follows:"follow",followCounts:"followCount",feeds:"feed",ads:"ad",advertisers:"advertiser",pinTargets:"pinTarget",pins:"pin"};function pe(e=(new Date).toISOString()){return new Date(new Date(e).getTime()+1).toISOString()}class fe extends Error{constructor(e,t,n){super(`Amity SDK (${t}): ${e}`),this.code=t,this.level=n,this.type="ASC",this.timestamp=Date.now(),Error.captureStackTrace&&Error.captureStackTrace(this,fe)}}class ge extends fe{constructor(e,t,n){super(e,t,n)}}class me extends fe{constructor(e=8e5,t="fatal"){super("Unexpected error",e,t)}}class ye extends fe{constructor(e,t="SDK client is having connection issues"){super(`${t} (${e})`,"disconnected"===e?800211:800210,"error"),this.event=e}}class ve extends fe{constructor(e){super(e,800110,"error")}}let be=null;const we=()=>{if(!be)throw new fe("There is no active client",8e5,"fatal");return be},Ce=e=>{be=e},Ie=e=>{const{log:t,cache:n}=we();if(n)return t("cache/api/queryCache",{key:e}),Object.keys(n.data).filter((t=>{const n=z(t);return Q(e,n)})).map((e=>n.data[e]))},Se=e=>{const{log:t,cache:n}=we();if(!n)return;t("cache/api/pullFromCache",e);const r=$(e);return n.data[r]?n.data[r]:void 0},_e=(e,t,n={cachedAt:Date.now()})=>{const{log:r,cache:s}=we();if(!s)return!1;r("cache/api/pushToCache",{key:e,data:t,options:n}),!(null==n?void 0:n.hasOwnProperty("offline"))&&s.persistIf&&(n.offline=s.persistIf(e,t));const o=$(e);return s.data[o]=Object.assign({key:e,data:t},n),!0},ke=(e,t,n)=>{const{log:r,cache:s}=we();if(!s)return!1;r("cache/api/mergeInCache",{key:e,mutation:t});const o=Se(e);if(!o)return!1;const a="function"==typeof t?t(o.data):Object.assign(Object.assign({},o.data),t);return i=o.data,!("updatedAt"in(c=a)&&"updatedAt"in c&&new Date(c.updatedAt)<new Date(i.updatedAt))&&(_e(e,a,n),!0);var i,c},Oe=(e,t,n={cachedAt:Date.now()})=>{const{log:r,cache:s}=we();if(!s)return!1;r("cache/api/upsertInCache",{key:e,data:t,options:n});return Se(e)?ke(e,t,n):_e(e,t,n)},Te=(e,t=!1)=>{const{log:n,cache:r}=we();if(!r)return!1;if(n("cache/api/dropFromCache",{key:e,exact:t}),!t)return Object.keys(r.data).map((e=>z(e))).filter((t=>Q(e,t))).map((e=>Te(e,!0))).every((e=>e));const s=$(e);return s in r.data&&(delete r.data[s],!0)},Ee=(e,t,n)=>void 0!==n?e.filter((e=>JSON.stringify(e[t])===JSON.stringify(n))):e,Ae=(e,t,n)=>void 0!==n?e.filter((e=>"string"==typeof e[t]&&"string"==typeof n&&String(e[t]).toLowerCase().match(n.toLowerCase()))):e,Me=(e,t,n)=>(null==n?void 0:n.length)?e.filter((e=>Array.isArray(e[t])&&n.some((n=>e[t].includes(n))))):e,Pe=(e,t,n)=>"all"===t?e:e.filter((e=>{var r;if("community"===e.type)return!0;const s=de("channelUsers")({channelId:e.channelPublicId,userId:n}),o=null===(r=Se(["channelUsers","get",s]))||void 0===r?void 0:r.data;return"member"===t?o&&"none"!==o.membership:!o||"none"===o.membership})),Re=(e,t)=>e.filter((({targetId:e,feedId:n})=>{var r;const s=null===(r=Se(["feed","get",de("feed")({targetId:e,feedId:n})]))||void 0===r?void 0:r.data;return s&&s.feedType===t})),Ue=(e,t,n)=>"all"===t?e:e.filter((e=>{var r;const s=de("communityUsers")({communityId:e.communityId,userId:n}),o=null===(r=Se(["communityUsers","get",s]))||void 0===r?void 0:r.data;return"member"===t?o&&"member"===o.communityMembership:!o||"none"!==o.communityMembership})),je=(e,t)=>e.reduce(((e,n)=>{var r;if(null==t?void 0:t.includes(n.dataType))return[...e,n];if(((null==n?void 0:n.children)||[]).length>0){const s=null===(r=Se(["post","get",n.children[0]]))||void 0===r?void 0:r.data;return(null==t?void 0:t.includes(null==s?void 0:s.dataType))?e:[...e,n]}return e}),[]),xe=(e,t)=>{const n=new RegExp(t,"i");return e.filter((e=>{var t;return!!e.userId.match(n)||e.user&&(null===(t=e.user.displayName)||void 0===t?void 0:t.match(n))}))},De=({displayName:e},{displayName:t})=>e&&t?e.localeCompare(t):e?-1:1,Ne=({name:e},{name:t})=>e&&t?e.localeCompare(t):e?-1:1,Be=({createdAt:e},{createdAt:t})=>new Date(e).valueOf()-new Date(t).valueOf(),qe=({localSortingDate:e},{localSortingDate:t})=>new Date(t).getTime()-new Date(e).getTime(),Fe=({createdAt:e},{createdAt:t})=>new Date(t).valueOf()-new Date(e).valueOf(),Le=({updatedAt:e=0},{updatedAt:t=0})=>new Date(e).valueOf()-new Date(t).valueOf(),Ke=({updatedAt:e=0},{updatedAt:t=0})=>new Date(t).valueOf()-new Date(e).valueOf(),$e=({lastActivity:e},{lastActivity:t})=>new Date(t).valueOf()-new Date(e).valueOf();let ze=null;const Qe=()=>{if(!ze)throw new fe("Connect client first",8e5,"fatal");return ze},Ve=e=>{ze={_id:e._id,userId:e.userId,path:e.path}};let He,We=[];const Je=e=>{clearTimeout(He),We.push(e),He=setTimeout((()=>{We.forEach((e=>e())),We=[]}),0)},Ge=["disconnected","error","connect_error","reconnect_error","reconnect_failed","sessionStateChange","tokenExpired","v3.video-streaming.didRecord","v3.video-streaming.didStart","v3.video-streaming.didStop"],Ye=["connect","message","disconnect","error","close","end","reconnect","user.didGlobalBan"],Xe=(e,t,n,r)=>{const{log:s,emitter:o}=e,a=Date.now();s(`${t}(tmpid: ${a}) > listen`);const i=(...e)=>{s(`${t}(tmpid: ${a}) > trigger`,e);try{r(...e)}catch(e){s(`${t}(tmpid: ${a}) > error`,e)}};return o.on(n,i),()=>{s(`${t}(tmpid: ${a}) > dispose`),o.off(n,i)}},Ze=(e,t)=>{const{emitter:n}=we();Je((()=>{n.emit(e,t)}))};let et,tt;async function nt(){var e;const{mqtt:t,emitter:n,token:r}=we(),s=null!==(e=null==r?void 0:r.accessToken)&&void 0!==e?e:"",o=Qe();et===s&&tt===o._id||(et=s,tt=o._id,await t.connect({accessToken:et,userId:tt}),((e,t)=>{Ye.forEach((n=>{e.on(n,((...e)=>{t.emit(n,1===e.length?e[0]:e)}))})),e.on("message",((e,n)=>{const r=JSON.parse(n.toString());t.emit(r.eventType,r.data)}))})(t,n))}var rt;e.SubscriptionLevels=void 0,(rt=e.SubscriptionLevels||(e.SubscriptionLevels={})).COMMUNITY="community",rt.POST="post",rt.COMMENT="comment",rt.POST_AND_COMMENT="post_and_comment",rt.USER="user";const st=(e,t)=>{switch(t){case"post":return`${e}/post/+`;case"comment":return`${e}/post/+/comment/+`;case"post_and_comment":return`${e}/post/#`;default:return e}},ot=e=>e.path.split("/user/")[0],at=({path:t},n=e.SubscriptionLevels.USER)=>st(n===e.SubscriptionLevels.USER?t:t.replace(/^(\w*)/,"$1/social"),n),it=({channelId:e,subChannelId:t})=>{const n=Qe();return`${ot(n)}/marker/channel/${e}/message/${t}`},ct=()=>{const e=Qe();return`${ot(e)}/marker/user/${e._id}`},lt=()=>ot(Qe()),dt=()=>{const e=Qe();return`${ot(e)}/smartfeed/${e._id}/channels`},ut=()=>{const e=Qe();return`${ot(e)}/smartfeed/${e._id}/messagefeeds`},ht=()=>{const e=Qe();return`${ot(e)}/smartfeed/${e._id}/messages`};function pt(e,t){const{mqtt:n}=we();return nt(),n.subscribe(e,t)}var ft;const gt="object"==typeof globalThis?globalThis:"object"==typeof global?global:window,{process:mt={}}=gt,yt="production"===(null===(ft=mt.env)||void 0===ft?void 0:ft.NODE_ENV),vt={EU:"eu",SG:"sg",US:"us"},bt={http:"https://api.{region}.amity.co",mqtt:"wss://sse.{region}.amity.co:443/mqtt"};function wt(e,t){return bt[e].replace("{region}",t)}class Ct{constructor(){this._listener=new Map}onNetworkActivities(e){return this._listener.set(e,e),()=>{this._listener.delete(e)}}setNetworkActivities(e,t){this._listener.forEach((n=>n(e,t)))}destroy(){this._listener.clear()}}let It;var St,_t=()=>(It||(It=new Ct),It);!function(e){e.UserDeleted="User Deleted",e.UserGlobalBanned="User Global Banned",e.TokenExpired="Token Expired"}(St||(St={}));const kt=new AbortController,Ot=e=>{switch(e){case St.UserGlobalBanned:throw new fe(e,400312,"fatal");case St.UserDeleted:throw new fe(e,400100,"fatal");case St.TokenExpired:throw Ze("tokenExpired","tokenExpired"),new fe(e,800403,"fatal");default:throw new fe("Request Aborted",8e5,"error")}},Tt=e=>{const t={maxSockets:100,maxFreeSockets:10,timeout:6e4,freeSocketTimeout:3e4},n=g.default.create({baseURL:e,httpAgent:new m.default(t),httpsAgent:new o.HttpsAgent(t),signal:kt.signal});return n.interceptors.request.use((e=>{if("/api/v5/sessions"===e.url)return e;if(e.metadata){const{tokenExpiry:t,isGlobalBanned:n,isUserDeleted:r}=e.metadata;n&&(kt.abort(),Ot(St.UserGlobalBanned)),r&&(kt.abort(),Ot(St.UserDeleted)),t&&Date.now()>=Date.parse(t)&&(kt.abort(St.UserDeleted),Ot(St.TokenExpired))}return e})),n.interceptors.response.use((e=>{const t=new Headers;return Object.entries(e.headers).forEach((([e,n])=>{"string"==typeof n&&t.append(e,n)})),_t().setNetworkActivities(new Request(e.request.url,{method:e.request.method,headers:e.request.headers,body:e.request.data}),{data:e.data,status:e.status,statusText:e.statusText,headers:t}),e}),(e=>{var t,n;const{response:r}=e;if(400100===(null==r?void 0:r.data.code)&&Ze("tokenTerminated","terminated"),(null===(t=null==r?void 0:r.data)||void 0===t?void 0:t.status)&&(e=>{if("success"===e.status)return e.data;if("fail"===e.status)throw new me(e.code);if("error"===e.status)throw new ge(e.message,e.code,"error")})(null==r?void 0:r.data),kt.signal.aborted)throw e;throw new Error(null!==(n=null==r?void 0:r.data)&&void 0!==n?n:e)})),n.defaults.paramsSerializer={encode:e=>encodeURIComponent(e)},n};var Et="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function At(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Mt(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Pt={exports:{}};Pt.exports=function(){function e(t,n,r){function s(a,i){if(!n[a]){if(!t[a]){if(!i&&Mt)return Mt(a);if(o)return o(a,!0);var c=new Error("Cannot find module '"+a+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[a]={exports:{}};t[a][0].call(l.exports,(function(e){return s(t[a][1][e]||e)}),l,l.exports,e,t,n,r)}return n[a].exports}for(var o=Mt,a=0;a<r.length;a++)s(r[a]);return s}return e}()({1:[function(e,t,n){(function(n,r){(function(){const s=e("events").EventEmitter,o=e("./store"),a=e("./topic-alias-recv"),i=e("./topic-alias-send"),c=e("mqtt-packet"),l=e("./default-message-id-provider"),d=e("readable-stream").Writable,u=e("inherits"),h=e("reinterval"),p=e("rfdc/default"),f=e("./validations"),g=e("xtend"),m=e("debug")("mqttjs:client"),y=n?n.nextTick:function(e){setTimeout(e,0)},v=r.setImmediate||function(e){y(e)},b={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1e3,connectTimeout:3e4,clean:!0,resubscribe:!0},w=["ECONNREFUSED","EADDRINUSE","ECONNRESET","ENOTFOUND"],C={0:"",1:"Unacceptable protocol version",2:"Identifier rejected",3:"Server unavailable",4:"Bad username or password",5:"Not authorized",16:"No matching subscribers",17:"No subscription existed",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",132:"Unsupported Protocol Version",133:"Client Identifier not valid",134:"Bad User Name or Password",135:"Not authorized",136:"Server unavailable",137:"Server busy",138:"Banned",139:"Server shutting down",140:"Bad authentication method",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",145:"Packet identifier in use",146:"Packet Identifier not found",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};function I(){return"mqttjs_"+Math.random().toString(16).substr(2,8)}function S(e,t){if(5===e.options.protocolVersion&&"publish"===t.cmd){let n;t.properties&&(n=t.properties.topicAlias);const r=t.topic.toString();if(e.topicAliasSend)if(n){if(0!==r.length&&(m("applyTopicAlias :: register topic: %s - alias: %d",r,n),!e.topicAliasSend.put(r,n)))return m("applyTopicAlias :: error out of range. topic: %s - alias: %d",r,n),new Error("Sending Topic Alias out of range")}else 0!==r.length&&(e.options.autoAssignTopicAlias?(n=e.topicAliasSend.getAliasByTopic(r),n?(t.topic="",t.properties={...t.properties,topicAlias:n},m("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",r,n)):(n=e.topicAliasSend.getLruAlias(),e.topicAliasSend.put(r,n),t.properties={...t.properties,topicAlias:n},m("applyTopicAlias :: auto assign topic: %s - alias: %d",r,n))):e.options.autoUseTopicAlias&&(n=e.topicAliasSend.getAliasByTopic(r),n&&(t.topic="",t.properties={...t.properties,topicAlias:n},m("applyTopicAlias :: auto use topic: %s - alias: %d",r,n))));else if(n)return m("applyTopicAlias :: error out of range. topic: %s - alias: %d",r,n),new Error("Sending Topic Alias out of range")}}function _(e,t){let n;t.properties&&(n=t.properties.topicAlias);let r=t.topic.toString();if(0===r.length){if(void 0===n)return new Error("Unregistered Topic Alias");if(r=e.topicAliasSend.getTopicByAlias(n),void 0===r)return new Error("Unregistered Topic Alias");t.topic=r}n&&delete t.properties.topicAlias}function k(e,t,n){m("sendPacket :: packet: %O",t),m("sendPacket :: emitting `packetsend`"),e.emit("packetsend",t),m("sendPacket :: writing to stream");const r=c.writeToStream(t,e.stream,e.options);m("sendPacket :: writeToStream result %s",r),!r&&n&&n!==A?(m("sendPacket :: handle events on `drain` once through callback."),e.stream.once("drain",n)):n&&(m("sendPacket :: invoking cb"),n())}function O(e){e&&(m("flush: queue exists? %b",!!e),Object.keys(e).forEach((function(t){"function"==typeof e[t].cb&&(e[t].cb(new Error("Connection closed")),delete e[t])})))}function T(e){e&&(m("flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(e).forEach((function(t){e[t].volatile&&"function"==typeof e[t].cb&&(e[t].cb(new Error("Connection closed")),delete e[t])})))}function E(e,t,n,r){m("storeAndSend :: store packet with cmd %s to outgoingStore",t.cmd);let s,o=t;if("publish"===o.cmd&&(o=p(t),s=_(e,o),s))return n&&n(s);e.outgoingStore.put(o,(function(s){if(s)return n&&n(s);r(),k(e,t,n)}))}function A(e){m("nop ::",e)}function M(e,t){let n;const r=this;if(!(this instanceof M))return new M(e,t);for(n in this.options=t||{},b)void 0===this.options[n]?this.options[n]=b[n]:this.options[n]=t[n];m("MqttClient :: options.protocol",t.protocol),m("MqttClient :: options.protocolVersion",t.protocolVersion),m("MqttClient :: options.username",t.username),m("MqttClient :: options.keepalive",t.keepalive),m("MqttClient :: options.reconnectPeriod",t.reconnectPeriod),m("MqttClient :: options.rejectUnauthorized",t.rejectUnauthorized),m("MqttClient :: options.topicAliasMaximum",t.topicAliasMaximum),this.options.clientId="string"==typeof t.clientId?t.clientId:I(),m("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=5===t.protocolVersion&&t.customHandleAcks?t.customHandleAcks:function(){arguments[3](0)},this.streamBuilder=e,this.messageIdProvider=void 0===this.options.messageIdProvider?new l:this.options.messageIdProvider,this.outgoingStore=t.outgoingStore||new o,this.incomingStore=t.incomingStore||new o,this.queueQoSZero=void 0===t.queueQoSZero||t.queueQoSZero,this._resubscribeTopics={},this.messageIdToTopic={},this.pingTimer=null,this.connected=!1,this.disconnecting=!1,this.queue=[],this.connackTimer=null,this.reconnectTimer=null,this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={},this._storeProcessingQueue=[],this.outgoing={},this._firstConnection=!0,t.topicAliasMaximum>0&&(t.topicAliasMaximum>65535?m("MqttClient :: options.topicAliasMaximum is out of range"):this.topicAliasRecv=new a(t.topicAliasMaximum)),this.on("connect",(function(){const e=this.queue;function t(){const n=e.shift();m("deliver :: entry %o",n);let s=null;if(!n)return void r._resubscribe();s=n.packet,m("deliver :: call _sendPacket for %o",s);let o=!0;s.messageId&&0!==s.messageId&&(r.messageIdProvider.register(s.messageId)||(o=!1)),o?r._sendPacket(s,(function(e){n.cb&&n.cb(e),t()})):(m("messageId: %d has already used. The message is skipped and removed.",s.messageId),t())}m("connect :: sending queued packets"),t()})),this.on("close",(function(){m("close :: connected set to `false`"),this.connected=!1,m("close :: clearing connackTimer"),clearTimeout(this.connackTimer),m("close :: clearing ping timer"),null!==r.pingTimer&&(r.pingTimer.clear(),r.pingTimer=null),this.topicAliasRecv&&this.topicAliasRecv.clear(),m("close :: calling _setupReconnect"),this._setupReconnect()})),s.call(this),m("MqttClient :: setting up stream"),this._setupStream()}u(M,s),M.prototype._setupStream=function(){const e=this,t=new d,n=c.parser(this.options);let r=null;const s=[];function o(){if(s.length)y(a);else{const e=r;r=null,e()}}function a(){m("work :: getting next packet in queue");const t=s.shift();if(t)m("work :: packet pulled from queue"),e._handlePacket(t,o);else{m("work :: no packets in queue");const e=r;r=null,m("work :: done flag is %s",!!e),e&&e()}}function i(t){m("streamErrorHandler :: error",t.message),w.includes(t.code)?(m("streamErrorHandler :: emitting error"),e.emit("error",t)):A(t)}m("_setupStream :: calling method to clear reconnect"),this._clearReconnect(),m("_setupStream :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),n.on("packet",(function(e){m("parser :: on packet push to packets array."),s.push(e)})),t._write=function(e,t,s){r=s,m("writable stream :: parsing buffer"),n.parse(e),a()},m("_setupStream :: pipe stream to writable stream"),this.stream.pipe(t),this.stream.on("error",i),this.stream.on("close",(function(){m("(%s)stream :: on close",e.options.clientId),T(e.outgoing),m("stream: emit close to MqttClient"),e.emit("close")})),m("_setupStream: sending packet `connect`");const l=Object.create(this.options);if(l.cmd="connect",this.topicAliasRecv&&(l.properties||(l.properties={}),this.topicAliasRecv&&(l.properties.topicAliasMaximum=this.topicAliasRecv.max)),k(this,l),n.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return e.end((()=>this.emit("error",new Error("Packet has no Authentication Method")))),this;this.options.properties.authenticationMethod&&this.options.authPacket&&"object"==typeof this.options.authPacket&&k(this,g({cmd:"auth",reasonCode:0},this.options.authPacket))}this.stream.setMaxListeners(1e3),clearTimeout(this.connackTimer),this.connackTimer=setTimeout((function(){m("!!connectTimeout hit!! Calling _cleanUp with force `true`"),e._cleanUp(!0)}),this.options.connectTimeout)},M.prototype._handlePacket=function(e,t){const n=this.options;if(5===n.protocolVersion&&n.properties&&n.properties.maximumPacketSize&&n.properties.maximumPacketSize<e.length)return this.emit("error",new Error("exceeding packets size "+e.cmd)),this.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}}),this;switch(m("_handlePacket :: emitting packetreceive"),this.emit("packetreceive",e),e.cmd){case"publish":this._handlePublish(e,t);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":this._handleAck(e),t();break;case"pubrel":this._handlePubrel(e,t);break;case"connack":this._handleConnack(e),t();break;case"auth":this._handleAuth(e),t();break;case"pingresp":this._handlePingresp(e),t();break;case"disconnect":this._handleDisconnect(e),t()}},M.prototype._checkDisconnecting=function(e){return this.disconnecting&&(e&&e!==A?e(new Error("client disconnecting")):this.emit("error",new Error("client disconnecting"))),this.disconnecting},M.prototype.publish=function(e,t,n,r){m("publish :: message `%s` to topic `%s`",t,e);const s=this.options;if("function"==typeof n&&(r=n,n=null),n=g({qos:0,retain:!1,dup:!1},n),this._checkDisconnecting(r))return this;const o=this,a=function(){let a=0;if((1===n.qos||2===n.qos)&&(a=o._nextId(),null===a))return m("No messageId left"),!1;const i={cmd:"publish",topic:e,payload:t,qos:n.qos,retain:n.retain,messageId:a,dup:n.dup};switch(5===s.protocolVersion&&(i.properties=n.properties),m("publish :: qos",n.qos),n.qos){case 1:case 2:o.outgoing[i.messageId]={volatile:!1,cb:r||A},m("MqttClient:publish: packet cmd: %s",i.cmd),o._sendPacket(i,void 0,n.cbStorePut);break;default:m("MqttClient:publish: packet cmd: %s",i.cmd),o._sendPacket(i,r,n.cbStorePut)}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!a())&&this._storeProcessingQueue.push({invoke:a,cbStorePut:n.cbStorePut,callback:r}),this},M.prototype.subscribe=function(){const e=this,t=new Array(arguments.length);for(let e=0;e<arguments.length;e++)t[e]=arguments[e];const n=[];let r=t.shift();const s=r.resubscribe;let o=t.pop()||A,a=t.pop();const i=this.options.protocolVersion;delete r.resubscribe,"string"==typeof r&&(r=[r]),"function"!=typeof o&&(a=o,o=A);const c=f.validateTopics(r);if(null!==c)return v(o,new Error("Invalid topic "+c)),this;if(this._checkDisconnecting(o))return m("subscribe: discconecting true"),this;const l={qos:0};if(5===i&&(l.nl=!1,l.rap=!1,l.rh=0),a=g(l,a),Array.isArray(r)?r.forEach((function(t){if(m("subscribe: array topic %s",t),!Object.prototype.hasOwnProperty.call(e._resubscribeTopics,t)||e._resubscribeTopics[t].qos<a.qos||s){const e={topic:t,qos:a.qos};5===i&&(e.nl=a.nl,e.rap=a.rap,e.rh=a.rh,e.properties=a.properties),m("subscribe: pushing topic `%s` and qos `%s` to subs list",e.topic,e.qos),n.push(e)}})):Object.keys(r).forEach((function(t){if(m("subscribe: object topic %s",t),!Object.prototype.hasOwnProperty.call(e._resubscribeTopics,t)||e._resubscribeTopics[t].qos<r[t].qos||s){const e={topic:t,qos:r[t].qos};5===i&&(e.nl=r[t].nl,e.rap=r[t].rap,e.rh=r[t].rh,e.properties=a.properties),m("subscribe: pushing `%s` to subs list",e),n.push(e)}})),!n.length)return o(null,[]),this;const d=function(){const t=e._nextId();if(null===t)return m("No messageId left"),!1;const r={cmd:"subscribe",subscriptions:n,qos:1,retain:!1,dup:!1,messageId:t};if(a.properties&&(r.properties=a.properties),e.options.resubscribe){m("subscribe :: resubscribe true");const t=[];n.forEach((function(n){if(e.options.reconnectPeriod>0){const r={qos:n.qos};5===i&&(r.nl=n.nl||!1,r.rap=n.rap||!1,r.rh=n.rh||0,r.properties=n.properties),e._resubscribeTopics[n.topic]=r,t.push(n.topic)}})),e.messageIdToTopic[r.messageId]=t}return e.outgoing[r.messageId]={volatile:!0,cb:function(e,t){if(!e){const e=t.granted;for(let t=0;t<e.length;t+=1)n[t].qos=e[t]}o(e,n)}},m("subscribe :: call _sendPacket"),e._sendPacket(r),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!d())&&this._storeProcessingQueue.push({invoke:d,callback:o}),this},M.prototype.unsubscribe=function(){const e=this,t=new Array(arguments.length);for(let e=0;e<arguments.length;e++)t[e]=arguments[e];let n=t.shift(),r=t.pop()||A,s=t.pop();"string"==typeof n&&(n=[n]),"function"!=typeof r&&(s=r,r=A);const o=f.validateTopics(n);if(null!==o)return v(r,new Error("Invalid topic "+o)),this;if(e._checkDisconnecting(r))return this;const a=function(){const t=e._nextId();if(null===t)return m("No messageId left"),!1;const o={cmd:"unsubscribe",qos:1,messageId:t};return"string"==typeof n?o.unsubscriptions=[n]:Array.isArray(n)&&(o.unsubscriptions=n),e.options.resubscribe&&o.unsubscriptions.forEach((function(t){delete e._resubscribeTopics[t]})),"object"==typeof s&&s.properties&&(o.properties=s.properties),e.outgoing[o.messageId]={volatile:!0,cb:r},m("unsubscribe: call _sendPacket"),e._sendPacket(o),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!a())&&this._storeProcessingQueue.push({invoke:a,callback:r}),this},M.prototype.end=function(e,t,n){const r=this;function s(){m("end :: closeStores: closing incoming and outgoing stores"),r.disconnected=!0,r.incomingStore.close((function(e){r.outgoingStore.close((function(t){if(m("end :: closeStores: emitting end"),r.emit("end"),n){const r=e||t;m("end :: closeStores: invoking callback with args"),n(r)}}))})),r._deferredReconnect&&r._deferredReconnect()}function o(){m("end :: (%s) :: finish :: calling _cleanUp with force %s",r.options.clientId,e),r._cleanUp(e,(()=>{m("end :: finish :: calling process.nextTick on closeStores"),y(s.bind(r))}),t)}return m("end :: (%s)",this.options.clientId),null!=e&&"boolean"==typeof e||(n=t||A,t=e,e=!1,"object"!=typeof t&&(n=t,t=null,"function"!=typeof n&&(n=A))),"object"!=typeof t&&(n=t,t=null),m("end :: cb? %s",!!n),n=n||A,this.disconnecting?(n(),this):(this._clearReconnect(),this.disconnecting=!0,!e&&Object.keys(this.outgoing).length>0?(m("end :: (%s) :: calling finish in 10ms once outgoing is empty",r.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,o,10))):(m("end :: (%s) :: immediately calling finish",r.options.clientId),o()),this)},M.prototype.removeOutgoingMessage=function(e){const t=this.outgoing[e]?this.outgoing[e].cb:null;return delete this.outgoing[e],this.outgoingStore.del({messageId:e},(function(){t(new Error("Message removed"))})),this},M.prototype.reconnect=function(e){m("client reconnect");const t=this,n=function(){e?(t.options.incomingStore=e.incomingStore,t.options.outgoingStore=e.outgoingStore):(t.options.incomingStore=null,t.options.outgoingStore=null),t.incomingStore=t.options.incomingStore||new o,t.outgoingStore=t.options.outgoingStore||new o,t.disconnecting=!1,t.disconnected=!1,t._deferredReconnect=null,t._reconnect()};return this.disconnecting&&!this.disconnected?this._deferredReconnect=n:n(),this},M.prototype._reconnect=function(){m("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected?(this.end((()=>{this._setupStream()})),m("client already connected. disconnecting first.")):(m("_reconnect: calling _setupStream"),this._setupStream())},M.prototype._setupReconnect=function(){const e=this;!e.disconnecting&&!e.reconnectTimer&&e.options.reconnectPeriod>0?(this.reconnecting||(m("_setupReconnect :: emit `offline` state"),this.emit("offline"),m("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0),m("_setupReconnect :: setting reconnectTimer for %d ms",e.options.reconnectPeriod),e.reconnectTimer=setInterval((function(){m("reconnectTimer :: reconnect triggered!"),e._reconnect()}),e.options.reconnectPeriod)):m("_setupReconnect :: doing nothing...")},M.prototype._clearReconnect=function(){m("_clearReconnect : clearing reconnect timer"),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null)},M.prototype._cleanUp=function(e,t){const n=arguments[2];if(t&&(m("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",t)),m("_cleanUp :: forced? %s",e),e)0===this.options.reconnectPeriod&&this.options.clean&&O(this.outgoing),m("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{const e=g({cmd:"disconnect"},n);m("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(e,v.bind(null,this.stream.end.bind(this.stream)))}this.disconnecting||(m("_cleanUp :: client not disconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect()),null!==this.pingTimer&&(m("_cleanUp :: clearing pingTimer"),this.pingTimer.clear(),this.pingTimer=null),t&&!this.connected&&(m("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",t),t())},M.prototype._sendPacket=function(e,t,n){m("_sendPacket :: (%s) :: start",this.options.clientId),n=n||A,t=t||A;const r=S(this,e);if(r)t(r);else{if(!this.connected)return"auth"===e.cmd?(this._shiftPingInterval(),void k(this,e,t)):(m("_sendPacket :: client not connected. Storing packet offline."),void this._storePacket(e,t,n));switch(this._shiftPingInterval(),e.cmd){case"publish":break;case"pubrel":return void E(this,e,t,n);default:return void k(this,e,t)}switch(e.qos){case 2:case 1:E(this,e,t,n);break;default:k(this,e,t)}m("_sendPacket :: (%s) :: end",this.options.clientId)}},M.prototype._storePacket=function(e,t,n){m("_storePacket :: packet: %o",e),m("_storePacket :: cb? %s",!!t),n=n||A;let r=e;if("publish"===r.cmd){r=p(e);const n=_(this,r);if(n)return t&&t(n)}0===(r.qos||0)&&this.queueQoSZero||"publish"!==r.cmd?this.queue.push({packet:r,cb:t}):r.qos>0?(t=this.outgoing[r.messageId]?this.outgoing[r.messageId].cb:null,this.outgoingStore.put(r,(function(e){if(e)return t&&t(e);n()}))):t&&t(new Error("No connection to broker"))},M.prototype._setupPingTimer=function(){m("_setupPingTimer :: keepalive %d (seconds)",this.options.keepalive);const e=this;!this.pingTimer&&this.options.keepalive&&(this.pingResp=!0,this.pingTimer=h((function(){e._checkPing()}),1e3*this.options.keepalive))},M.prototype._shiftPingInterval=function(){this.pingTimer&&this.options.keepalive&&this.options.reschedulePings&&this.pingTimer.reschedule(1e3*this.options.keepalive)},M.prototype._checkPing=function(){m("_checkPing :: checking ping..."),this.pingResp?(m("_checkPing :: ping response received. Clearing flag and sending `pingreq`"),this.pingResp=!1,this._sendPacket({cmd:"pingreq"})):(m("_checkPing :: calling _cleanUp with force true"),this._cleanUp(!0))},M.prototype._handlePingresp=function(){this.pingResp=!0},M.prototype._handleConnack=function(e){m("_handleConnack");const t=this.options,n=5===t.protocolVersion?e.reasonCode:e.returnCode;if(clearTimeout(this.connackTimer),delete this.topicAliasSend,e.properties){if(e.properties.topicAliasMaximum){if(e.properties.topicAliasMaximum>65535)return void this.emit("error",new Error("topicAliasMaximum from broker is out of range"));e.properties.topicAliasMaximum>0&&(this.topicAliasSend=new i(e.properties.topicAliasMaximum))}e.properties.serverKeepAlive&&t.keepalive&&(t.keepalive=e.properties.serverKeepAlive,this._shiftPingInterval()),e.properties.maximumPacketSize&&(t.properties||(t.properties={}),t.properties.maximumPacketSize=e.properties.maximumPacketSize)}if(0===n)this.reconnecting=!1,this._onConnect(e);else if(n>0){const e=new Error("Connection refused: "+C[n]);e.code=n,this.emit("error",e)}},M.prototype._handleAuth=function(e){const t=this.options.protocolVersion,n=5===t?e.reasonCode:e.returnCode;if(5!==t){const e=new Error("Protocol error: Auth packets are only supported in MQTT 5. Your version:"+t);return e.code=n,void this.emit("error",e)}const r=this;this.handleAuth(e,(function(e,t){if(e)r.emit("error",e);else if(24===n)r.reconnecting=!1,r._sendPacket(t);else{const t=new Error("Connection refused: "+C[n]);e.code=n,r.emit("error",t)}}))},M.prototype.handleAuth=function(e,t){t()},M.prototype._handlePublish=function(e,t){m("_handlePublish: packet %o",e),t=void 0!==t?t:A;let n=e.topic.toString();const r=e.payload,s=e.qos,o=e.messageId,a=this,i=this.options,c=[0,16,128,131,135,144,145,151,153];if(5===this.options.protocolVersion){let t;if(e.properties&&(t=e.properties.topicAlias),void 0!==t)if(0===n.length){if(!(t>0&&t<=65535))return m("_handlePublish :: topic alias out of range. alias: %d",t),void this.emit("error",new Error("Received Topic Alias is out of range"));{const e=this.topicAliasRecv.getTopicByAlias(t);if(!e)return m("_handlePublish :: unregistered topic alias. alias: %d",t),void this.emit("error",new Error("Received unregistered Topic Alias"));n=e,m("_handlePublish :: topic complemented by alias. topic: %s - alias: %d",n,t)}}else{if(!this.topicAliasRecv.put(n,t))return m("_handlePublish :: topic alias out of range. alias: %d",t),void this.emit("error",new Error("Received Topic Alias is out of range"));m("_handlePublish :: registered topic: %s - alias: %d",n,t)}}switch(m("_handlePublish: qos %d",s),s){case 2:i.customHandleAcks(n,r,e,(function(n,r){return n instanceof Error||(r=n,n=null),n?a.emit("error",n):-1===c.indexOf(r)?a.emit("error",new Error("Wrong reason code for pubrec")):void(r?a._sendPacket({cmd:"pubrec",messageId:o,reasonCode:r},t):a.incomingStore.put(e,(function(){a._sendPacket({cmd:"pubrec",messageId:o},t)})))}));break;case 1:i.customHandleAcks(n,r,e,(function(s,i){return s instanceof Error||(i=s,s=null),s?a.emit("error",s):-1===c.indexOf(i)?a.emit("error",new Error("Wrong reason code for puback")):(i||a.emit("message",n,r,e),void a.handleMessage(e,(function(e){if(e)return t&&t(e);a._sendPacket({cmd:"puback",messageId:o,reasonCode:i},t)})))}));break;case 0:this.emit("message",n,r,e),this.handleMessage(e,t);break;default:m("_handlePublish: unknown QoS. Doing nothing.")}},M.prototype.handleMessage=function(e,t){t()},M.prototype._handleAck=function(e){const t=e.messageId,n=e.cmd;let r=null;const s=this.outgoing[t]?this.outgoing[t].cb:null,o=this;let a;if(s){switch(m("_handleAck :: packet type",n),n){case"pubcomp":case"puback":{const n=e.reasonCode;n&&n>0&&16!==n&&(a=new Error("Publish error: "+C[n]),a.code=n,s(a,e)),delete this.outgoing[t],this.outgoingStore.del(e,s),this.messageIdProvider.deallocate(t),this._invokeStoreProcessingQueue();break}case"pubrec":{r={cmd:"pubrel",qos:2,messageId:t};const n=e.reasonCode;n&&n>0&&16!==n?(a=new Error("Publish error: "+C[n]),a.code=n,s(a,e)):this._sendPacket(r);break}case"suback":delete this.outgoing[t],this.messageIdProvider.deallocate(t);for(let n=0;n<e.granted.length;n++)if(0!=(128&e.granted[n])){const e=this.messageIdToTopic[t];e&&e.forEach((function(e){delete o._resubscribeTopics[e]}))}this._invokeStoreProcessingQueue(),s(null,e);break;case"unsuback":delete this.outgoing[t],this.messageIdProvider.deallocate(t),this._invokeStoreProcessingQueue(),s(null);break;default:o.emit("error",new Error("unrecognized packet type"))}this.disconnecting&&0===Object.keys(this.outgoing).length&&this.emit("outgoingEmpty")}else m("_handleAck :: Server sent an ack in error. Ignoring.")},M.prototype._handlePubrel=function(e,t){m("handling pubrel packet"),t=void 0!==t?t:A;const n=e.messageId,r=this,s={cmd:"pubcomp",messageId:n};r.incomingStore.get(e,(function(e,n){e?r._sendPacket(s,t):(r.emit("message",n.topic,n.payload,n),r.handleMessage(n,(function(e){if(e)return t(e);r.incomingStore.del(n,A),r._sendPacket(s,t)})))}))},M.prototype._handleDisconnect=function(e){this.emit("disconnect",e)},M.prototype._nextId=function(){return this.messageIdProvider.allocate()},M.prototype.getLastMessageId=function(){return this.messageIdProvider.getLastAllocated()},M.prototype._resubscribe=function(){m("_resubscribe");const e=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||5===this.options.protocolVersion&&!this.connackPacket.sessionPresent)&&e.length>0)if(this.options.resubscribe)if(5===this.options.protocolVersion){m("_resubscribe: protocolVersion 5");for(let t=0;t<e.length;t++){const n={};n[e[t]]=this._resubscribeTopics[e[t]],n.resubscribe=!0,this.subscribe(n,{properties:n[e[t]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1},M.prototype._onConnect=function(e){if(this.disconnected)return void this.emit("connect",e);const t=this;function n(){let r=t.outgoingStore.createStream();function s(){t._storeProcessing=!1,t._packetIdsDuringStoreProcessing={}}function o(){r.destroy(),r=null,t._flushStoreProcessingQueue(),s()}function a(){if(!r)return;t._storeProcessing=!0;const e=r.read(1);let n;e?t._packetIdsDuringStoreProcessing[e.messageId]?a():t.disconnecting||t.reconnectTimer?r.destroy&&r.destroy():(n=t.outgoing[e.messageId]?t.outgoing[e.messageId].cb:null,t.outgoing[e.messageId]={volatile:!1,cb:function(e,t){n&&n(e,t),a()}},t._packetIdsDuringStoreProcessing[e.messageId]=!0,t.messageIdProvider.register(e.messageId)?t._sendPacket(e):m("messageId: %d has already used.",e.messageId)):r.once("readable",a)}t.once("close",o),r.on("error",(function(e){s(),t._flushStoreProcessingQueue(),t.removeListener("close",o),t.emit("error",e)})),r.on("end",(function(){let r=!0;for(const e in t._packetIdsDuringStoreProcessing)if(!t._packetIdsDuringStoreProcessing[e]){r=!1;break}r?(s(),t.removeListener("close",o),t._invokeAllStoreProcessingQueue(),t.emit("connect",e)):n()})),a()}this.connackPacket=e,this.messageIdProvider.clear(),this._setupPingTimer(),this.connected=!0,n()},M.prototype._invokeStoreProcessingQueue=function(){if(this._storeProcessingQueue.length>0){const e=this._storeProcessingQueue[0];if(e&&e.invoke())return this._storeProcessingQueue.shift(),!0}return!1},M.prototype._invokeAllStoreProcessingQueue=function(){for(;this._invokeStoreProcessingQueue(););},M.prototype._flushStoreProcessingQueue=function(){for(const e of this._storeProcessingQueue)e.cbStorePut&&e.cbStorePut(new Error("Connection closed")),e.callback&&e.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)},t.exports=M}).call(this)}).call(this,e("_process"),void 0!==Et?Et:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./default-message-id-provider":7,"./store":8,"./topic-alias-recv":9,"./topic-alias-send":10,"./validations":11,_process:50,debug:18,events:22,inherits:24,"mqtt-packet":40,"readable-stream":69,reinterval:70,"rfdc/default":71,xtend:81}],2:[function(e,t,n){const{Buffer:r}=e("buffer"),s=e("readable-stream").Transform,o=e("duplexify");let a,i,c,l=!1;function d(){const e=new s;return e._write=function(e,t,n){a.sendSocketMessage({data:e.buffer,success:function(){n()},fail:function(){n(new Error)}})},e._flush=function(e){a.closeSocket({success:function(){e()}})},e}function u(e){e.hostname||(e.hostname="localhost"),e.path||(e.path="/"),e.wsOptions||(e.wsOptions={})}function h(e,t){const n="alis"===e.protocol?"wss":"ws";let r=n+"://"+e.hostname+e.path;return e.port&&80!==e.port&&443!==e.port&&(r=n+"://"+e.hostname+":"+e.port+e.path),"function"==typeof e.transformWsUrl&&(r=e.transformWsUrl(r,e,t)),r}function p(){l||(l=!0,a.onSocketOpen((function(){c.setReadable(i),c.setWritable(i),c.emit("connect")})),a.onSocketMessage((function(e){if("string"==typeof e.data){const t=r.from(e.data,"base64");i.push(t)}else{const t=new FileReader;t.addEventListener("load",(function(){let e=t.result;e=e instanceof ArrayBuffer?r.from(e):r.from(e,"utf8"),i.push(e)})),t.readAsArrayBuffer(e.data)}})),a.onSocketClose((function(){c.end(),c.destroy()})),a.onSocketError((function(e){c.destroy(e)})))}function f(e,t){if(t.hostname=t.hostname||t.host,!t.hostname)throw new Error("Could not determine host. Specify host manually.");const n="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt";u(t);const r=h(t,e);return a=t.my,a.connectSocket({url:r,protocols:n}),i=d(),c=o.obj(),p(),c}t.exports=f},{buffer:17,duplexify:20,"readable-stream":69}],3:[function(e,t,n){const r=e("net"),s=e("debug")("mqttjs:tcp");function o(e,t){t.port=t.port||1883,t.hostname=t.hostname||t.host||"localhost";const n=t.port,o=t.hostname;return s("port %d and host %s",n,o),r.createConnection(n,o)}t.exports=o},{debug:18,net:16}],4:[function(e,t,n){const r=e("tls"),s=e("net"),o=e("debug")("mqttjs:tls");function a(e,t){t.port=t.port||8883,t.host=t.hostname||t.host||"localhost",0===s.isIP(t.host)&&(t.servername=t.host),t.rejectUnauthorized=!1!==t.rejectUnauthorized,delete t.path,o("port %d host %s rejectUnauthorized %b",t.port,t.host,t.rejectUnauthorized);const n=r.connect(t);function a(r){t.rejectUnauthorized&&e.emit("error",r),n.end()}return n.on("secureConnect",(function(){t.rejectUnauthorized&&!n.authorized?n.emit("error",new Error("TLS not authorized")):n.removeListener("error",a)})),n.on("error",a),n}t.exports=a},{debug:18,net:16,tls:16}],5:[function(e,t,n){(function(n){(function(){const{Buffer:r}=e("buffer"),s=e("ws"),o=e("debug")("mqttjs:ws"),a=e("duplexify"),i=e("readable-stream").Transform,c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"],l=void 0!==n&&"browser"===n.title||"function"==typeof __webpack_require__;function d(e,t){let n=e.protocol+"://"+e.hostname+":"+e.port+e.path;return"function"==typeof e.transformWsUrl&&(n=e.transformWsUrl(n,e,t)),n}function u(e){const t=e;return e.hostname||(t.hostname="localhost"),e.port||("wss"===e.protocol?t.port=443:t.port=80),e.path||(t.path="/"),e.wsOptions||(t.wsOptions={}),l||"wss"!==e.protocol||c.forEach((function(n){Object.prototype.hasOwnProperty.call(e,n)&&!Object.prototype.hasOwnProperty.call(e.wsOptions,n)&&(t.wsOptions[n]=e[n])})),t}function h(e){const t=u(e);if(t.hostname||(t.hostname=t.host),!t.hostname){if("undefined"==typeof document)throw new Error("Could not determine host. Specify host manually.");const e=new URL(document.URL);t.hostname=e.hostname,t.port||(t.port=e.port)}return void 0===t.objectMode&&(t.objectMode=!(!0===t.binary||void 0===t.binary)),t}function p(e,t,n){o("createWebSocket"),o("protocol: "+n.protocolId+" "+n.protocolVersion);const r="MQIsdp"===n.protocolId&&3===n.protocolVersion?"mqttv3.1":"mqtt";return o("creating new Websocket for url: "+t+" and protocol: "+r),new s(t,[r],n.wsOptions)}function f(e,t){const n="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt",r=d(t,e),s=new WebSocket(r,[n]);return s.binaryType="arraybuffer",s}function g(e,t){o("streamBuilder");const n=u(t),r=d(n,e),a=p(e,r,n),i=s.createWebSocketStream(a,n.wsOptions);return i.url=r,a.on("close",(()=>{i.destroy()})),i}function m(e,t){let n;o("browserStreamBuilder");const s=h(t).browserBufferSize||524288,c=t.browserBufferTimeout||1e3,l=!t.objectMode,d=f(e,t),u=g(t,C,I);t.objectMode||(u._writev=w),u.on("close",(()=>{d.close()}));const p=void 0!==d.addEventListener;function g(e,t,n){const r=new i({objectModeMode:e.objectMode});return r._write=t,r._flush=n,r}function m(){n.setReadable(u),n.setWritable(u),n.emit("connect")}function y(){n.end(),n.destroy()}function v(e){n.destroy(e)}function b(e){let t=e.data;t=t instanceof ArrayBuffer?r.from(t):r.from(t,"utf8"),u.push(t)}function w(e,t){const n=new Array(e.length);for(let t=0;t<e.length;t++)"string"==typeof e[t].chunk?n[t]=r.from(e[t],"utf8"):n[t]=e[t].chunk;this._write(r.concat(n),"binary",t)}function C(e,t,n){d.bufferedAmount>s&&setTimeout(C,c,e,t,n),l&&"string"==typeof e&&(e=r.from(e,"utf8"));try{d.send(e)}catch(e){return n(e)}n()}function I(e){d.close(),e()}return d.readyState===d.OPEN?n=u:(n=n=a(void 0,void 0,t),t.objectMode||(n._writev=w),p?d.addEventListener("open",m):d.onopen=m),n.socket=d,p?(d.addEventListener("close",y),d.addEventListener("error",v),d.addEventListener("message",b)):(d.onclose=y,d.onerror=v,d.onmessage=b),n}t.exports=l?m:g}).call(this)}).call(this,e("_process"))},{_process:50,buffer:17,debug:18,duplexify:20,"readable-stream":69,ws:80}],6:[function(e,t,n){const{Buffer:r}=e("buffer"),s=e("readable-stream").Transform,o=e("duplexify");let a,i,c;function l(){const e=new s;return e._write=function(e,t,n){a.send({data:e.buffer,success:function(){n()},fail:function(e){n(new Error(e))}})},e._flush=function(e){a.close({success:function(){e()}})},e}function d(e){e.hostname||(e.hostname="localhost"),e.path||(e.path="/"),e.wsOptions||(e.wsOptions={})}function u(e,t){const n="wxs"===e.protocol?"wss":"ws";let r=n+"://"+e.hostname+e.path;return e.port&&80!==e.port&&443!==e.port&&(r=n+"://"+e.hostname+":"+e.port+e.path),"function"==typeof e.transformWsUrl&&(r=e.transformWsUrl(r,e,t)),r}function h(){a.onOpen((function(){c.setReadable(i),c.setWritable(i),c.emit("connect")})),a.onMessage((function(e){let t=e.data;t=t instanceof ArrayBuffer?r.from(t):r.from(t,"utf8"),i.push(t)})),a.onClose((function(){c.end(),c.destroy()})),a.onError((function(e){c.destroy(new Error(e.errMsg))}))}function p(e,t){if(t.hostname=t.hostname||t.host,!t.hostname)throw new Error("Could not determine host. Specify host manually.");const n="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt";d(t);const r=u(t,e);a=wx.connectSocket({url:r,protocols:[n]}),i=l(),c=o.obj(),c._destroy=function(e,t){a.close({success:function(){t&&t(e)}})};const s=c.destroy;return c.destroy=function(){c.destroy=s;const e=this;setTimeout((function(){a.close({fail:function(){e._destroy(new Error)}})}),0)}.bind(c),h(),c}t.exports=p},{buffer:17,duplexify:20,"readable-stream":69}],7:[function(e,t,n){function r(){if(!(this instanceof r))return new r;this.nextId=Math.max(1,Math.floor(65535*Math.random()))}r.prototype.allocate=function(){const e=this.nextId++;return 65536===this.nextId&&(this.nextId=1),e},r.prototype.getLastAllocated=function(){return 1===this.nextId?65535:this.nextId-1},r.prototype.register=function(e){return!0},r.prototype.deallocate=function(e){},r.prototype.clear=function(){},t.exports=r},{}],8:[function(e,t,n){const r=e("xtend"),s=e("readable-stream").Readable,o={objectMode:!0},a={clean:!0};function i(e){if(!(this instanceof i))return new i(e);this.options=e||{},this.options=r(a,e),this._inflights=new Map}i.prototype.put=function(e,t){return this._inflights.set(e.messageId,e),t&&t(),this},i.prototype.createStream=function(){const e=new s(o),t=[];let n=!1,r=0;return this._inflights.forEach((function(e,n){t.push(e)})),e._read=function(){!n&&r<t.length?this.push(t[r++]):this.push(null)},e.destroy=function(){if(n)return;const e=this;n=!0,setTimeout((function(){e.emit("close")}),0)},e},i.prototype.del=function(e,t){return(e=this._inflights.get(e.messageId))?(this._inflights.delete(e.messageId),t(null,e)):t&&t(new Error("missing packet")),this},i.prototype.get=function(e,t){return(e=this._inflights.get(e.messageId))?t(null,e):t&&t(new Error("missing packet")),this},i.prototype.close=function(e){this.options.clean&&(this._inflights=null),e&&e()},t.exports=i},{"readable-stream":69,xtend:81}],9:[function(e,t,n){function r(e){if(!(this instanceof r))return new r(e);this.aliasToTopic={},this.max=e}r.prototype.put=function(e,t){return!(0===t||t>this.max||(this.aliasToTopic[t]=e,this.length=Object.keys(this.aliasToTopic).length,0))},r.prototype.getTopicByAlias=function(e){return this.aliasToTopic[e]},r.prototype.clear=function(){this.aliasToTopic={}},t.exports=r},{}],10:[function(e,t,n){const r=e("lru-cache"),s=e("number-allocator").NumberAllocator;function o(e){if(!(this instanceof o))return new o(e);e>0&&(this.aliasToTopic=new r({max:e}),this.topicToAlias={},this.numberAllocator=new s(1,e),this.max=e,this.length=0)}o.prototype.put=function(e,t){if(0===t||t>this.max)return!1;const n=this.aliasToTopic.get(t);return n&&delete this.topicToAlias[n],this.aliasToTopic.set(t,e),this.topicToAlias[e]=t,this.numberAllocator.use(t),this.length=this.aliasToTopic.length,!0},o.prototype.getTopicByAlias=function(e){return this.aliasToTopic.get(e)},o.prototype.getAliasByTopic=function(e){const t=this.topicToAlias[e];return void 0!==t&&this.aliasToTopic.get(t),t},o.prototype.clear=function(){this.aliasToTopic.reset(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0},o.prototype.getLruAlias=function(){const e=this.numberAllocator.firstVacant();return e||this.aliasToTopic.keys()[this.aliasToTopic.length-1]},t.exports=o},{"lru-cache":37,"number-allocator":46}],11:[function(e,t,n){function r(e){const t=e.split("/");for(let e=0;e<t.length;e++)if("+"!==t[e]){if("#"===t[e])return e===t.length-1;if(-1!==t[e].indexOf("+")||-1!==t[e].indexOf("#"))return!1}return!0}function s(e){if(0===e.length)return"empty_topic_list";for(let t=0;t<e.length;t++)if(!r(e[t]))return e[t];return null}t.exports={validateTopics:s}},{}],12:[function(e,t,n){(function(n){(function(){const r=e("../client"),s=e("../store"),o=e("url"),a=e("xtend"),i=e("debug")("mqttjs"),c={};function l(e){let t;e.auth&&(t=e.auth.match(/^(.+):(.+)$/),t?(e.username=t[1],e.password=t[2]):e.username=e.auth)}function d(e,t){if(i("connecting to an MQTT broker..."),"object"!=typeof e||t||(t=e,e=null),t=t||{},e){const n=o.parse(e,!0);if(null!=n.port&&(n.port=Number(n.port)),null===(t=a(n,t)).protocol)throw new Error("Missing protocol");t.protocol=t.protocol.replace(/:$/,"")}if(l(t),t.query&&"string"==typeof t.query.clientId&&(t.clientId=t.query.clientId),t.cert&&t.key){if(!t.protocol)throw new Error("Missing secure protocol key");if(-1===["mqtts","wss","wxs","alis"].indexOf(t.protocol))switch(t.protocol){case"mqtt":t.protocol="mqtts";break;case"ws":t.protocol="wss";break;case"wx":t.protocol="wxs";break;case"ali":t.protocol="alis";break;default:throw new Error('Unknown protocol for secure connection: "'+t.protocol+'"!')}}if(!c[t.protocol]){const e=-1!==["mqtts","wss"].indexOf(t.protocol);t.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((function(t,n){return(!e||n%2!=0)&&"function"==typeof c[t]}))[0]}if(!1===t.clean&&!t.clientId)throw new Error("Missing clientId for unclean clients");function n(e){return t.servers&&(e._reconnectCount&&e._reconnectCount!==t.servers.length||(e._reconnectCount=0),t.host=t.servers[e._reconnectCount].host,t.port=t.servers[e._reconnectCount].port,t.protocol=t.servers[e._reconnectCount].protocol?t.servers[e._reconnectCount].protocol:t.defaultProtocol,t.hostname=t.host,e._reconnectCount++),i("calling streambuilder for",t.protocol),c[t.protocol](e,t)}t.protocol&&(t.defaultProtocol=t.protocol);const s=new r(n,t);return s.on("error",(function(){})),s}void 0!==n&&"browser"!==n.title||"function"!=typeof __webpack_require__?(c.mqtt=e("./tcp"),c.tcp=e("./tcp"),c.ssl=e("./tls"),c.tls=e("./tls"),c.mqtts=e("./tls")):(c.wx=e("./wx"),c.wxs=e("./wx"),c.ali=e("./ali"),c.alis=e("./ali")),c.ws=e("./ws"),c.wss=e("./ws"),t.exports=d,t.exports.connect=d,t.exports.MqttClient=r,t.exports.Store=s}).call(this)}).call(this,e("_process"))},{"../client":1,"../store":8,"./ali":2,"./tcp":3,"./tls":4,"./ws":5,"./wx":6,_process:50,debug:18,url:76,xtend:81}],13:[function(e,t,n){n.byteLength=d,n.toByteArray=h,n.fromByteArray=g;for(var r=[],s=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,c=a.length;i<c;++i)r[i]=a[i],s[a.charCodeAt(i)]=i;function l(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function d(e){var t=l(e),n=t[0],r=t[1];return 3*(n+r)/4-r}function u(e,t,n){return 3*(t+n)/4-n}function h(e){var t,n,r=l(e),a=r[0],i=r[1],c=new o(u(e,a,i)),d=0,h=i>0?a-4:a;for(n=0;n<h;n+=4)t=s[e.charCodeAt(n)]<<18|s[e.charCodeAt(n+1)]<<12|s[e.charCodeAt(n+2)]<<6|s[e.charCodeAt(n+3)],c[d++]=t>>16&255,c[d++]=t>>8&255,c[d++]=255&t;return 2===i&&(t=s[e.charCodeAt(n)]<<2|s[e.charCodeAt(n+1)]>>4,c[d++]=255&t),1===i&&(t=s[e.charCodeAt(n)]<<10|s[e.charCodeAt(n+1)]<<4|s[e.charCodeAt(n+2)]>>2,c[d++]=t>>8&255,c[d++]=255&t),c}function p(e){return r[e>>18&63]+r[e>>12&63]+r[e>>6&63]+r[63&e]}function f(e,t,n){for(var r,s=[],o=t;o<n;o+=3)r=(e[o]<<16&16711680)+(e[o+1]<<8&65280)+(255&e[o+2]),s.push(p(r));return s.join("")}function g(e){for(var t,n=e.length,s=n%3,o=[],a=16383,i=0,c=n-s;i<c;i+=a)o.push(f(e,i,i+a>c?c:i+a));return 1===s?(t=e[n-1],o.push(r[t>>2]+r[t<<4&63]+"==")):2===s&&(t=(e[n-2]<<8)+e[n-1],o.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"=")),o.join("")}s["-".charCodeAt(0)]=62,s["_".charCodeAt(0)]=63},{}],14:[function(e,t,n){const{Buffer:r}=e("buffer"),s=Symbol.for("BufferList");function o(e){if(!(this instanceof o))return new o(e);o._init.call(this,e)}o._init=function(e){Object.defineProperty(this,s,{value:!0}),this._bufs=[],this.length=0,e&&this.append(e)},o.prototype._new=function(e){return new o(e)},o.prototype._offset=function(e){if(0===e)return[0,0];let t=0;for(let n=0;n<this._bufs.length;n++){const r=t+this._bufs[n].length;if(e<r||n===this._bufs.length-1)return[n,e-t];t=r}},o.prototype._reverseOffset=function(e){const t=e[0];let n=e[1];for(let e=0;e<t;e++)n+=this._bufs[e].length;return n},o.prototype.get=function(e){if(e>this.length||e<0)return;const t=this._offset(e);return this._bufs[t[0]][t[1]]},o.prototype.slice=function(e,t){return"number"==typeof e&&e<0&&(e+=this.length),"number"==typeof t&&t<0&&(t+=this.length),this.copy(null,0,e,t)},o.prototype.copy=function(e,t,n,s){if(("number"!=typeof n||n<0)&&(n=0),("number"!=typeof s||s>this.length)&&(s=this.length),n>=this.length)return e||r.alloc(0);if(s<=0)return e||r.alloc(0);const o=!!e,a=this._offset(n),i=s-n;let c=i,l=o&&t||0,d=a[1];if(0===n&&s===this.length){if(!o)return 1===this._bufs.length?this._bufs[0]:r.concat(this._bufs,this.length);for(let t=0;t<this._bufs.length;t++)this._bufs[t].copy(e,l),l+=this._bufs[t].length;return e}if(c<=this._bufs[a[0]].length-d)return o?this._bufs[a[0]].copy(e,t,d,d+c):this._bufs[a[0]].slice(d,d+c);o||(e=r.allocUnsafe(i));for(let t=a[0];t<this._bufs.length;t++){const n=this._bufs[t].length-d;if(!(c>n)){this._bufs[t].copy(e,l,d,d+c),l+=n;break}this._bufs[t].copy(e,l,d),l+=n,c-=n,d&&(d=0)}return e.length>l?e.slice(0,l):e},o.prototype.shallowSlice=function(e,t){if(e=e||0,t="number"!=typeof t?this.length:t,e<0&&(e+=this.length),t<0&&(t+=this.length),e===t)return this._new();const n=this._offset(e),r=this._offset(t),s=this._bufs.slice(n[0],r[0]+1);return 0===r[1]?s.pop():s[s.length-1]=s[s.length-1].slice(0,r[1]),0!==n[1]&&(s[0]=s[0].slice(n[1])),this._new(s)},o.prototype.toString=function(e,t,n){return this.slice(t,n).toString(e)},o.prototype.consume=function(e){if(e=Math.trunc(e),Number.isNaN(e)||e<=0)return this;for(;this._bufs.length;){if(!(e>=this._bufs[0].length)){this._bufs[0]=this._bufs[0].slice(e),this.length-=e;break}e-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift()}return this},o.prototype.duplicate=function(){const e=this._new();for(let t=0;t<this._bufs.length;t++)e.append(this._bufs[t]);return e},o.prototype.append=function(e){if(null==e)return this;if(e.buffer)this._appendBuffer(r.from(e.buffer,e.byteOffset,e.byteLength));else if(Array.isArray(e))for(let t=0;t<e.length;t++)this.append(e[t]);else if(this._isBufferList(e))for(let t=0;t<e._bufs.length;t++)this.append(e._bufs[t]);else"number"==typeof e&&(e=e.toString()),this._appendBuffer(r.from(e));return this},o.prototype._appendBuffer=function(e){this._bufs.push(e),this.length+=e.length},o.prototype.indexOf=function(e,t,n){if(void 0===n&&"string"==typeof t&&(n=t,t=void 0),"function"==typeof e||Array.isArray(e))throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');if("number"==typeof e?e=r.from([e]):"string"==typeof e?e=r.from(e,n):this._isBufferList(e)?e=e.slice():Array.isArray(e.buffer)?e=r.from(e.buffer,e.byteOffset,e.byteLength):r.isBuffer(e)||(e=r.from(e)),t=Number(t||0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),0===e.length)return t>this.length?this.length:t;const s=this._offset(t);let o=s[0],a=s[1];for(;o<this._bufs.length;o++){const t=this._bufs[o];for(;a<t.length;)if(t.length-a>=e.length){const n=t.indexOf(e,a);if(-1!==n)return this._reverseOffset([o,n]);a=t.length-e.length+1}else{const t=this._reverseOffset([o,a]);if(this._match(t,e))return t;a++}a=0}return-1},o.prototype._match=function(e,t){if(this.length-e<t.length)return!1;for(let n=0;n<t.length;n++)if(this.get(e+n)!==t[n])return!1;return!0},function(){const e={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(const t in e)!function(t){null===e[t]?o.prototype[t]=function(e,n){return this.slice(e,e+n)[t](0,n)}:o.prototype[t]=function(n=0){return this.slice(n,n+e[t])[t](0)}}(t)}(),o.prototype._isBufferList=function(e){return e instanceof o||o.isBufferList(e)},o.isBufferList=function(e){return null!=e&&e[s]},t.exports=o},{buffer:17}],15:[function(e,t,n){const r=e("readable-stream").Duplex,s=e("inherits"),o=e("./BufferList");function a(e){if(!(this instanceof a))return new a(e);if("function"==typeof e){this._callback=e;const t=function(e){this._callback&&(this._callback(e),this._callback=null)}.bind(this);this.on("pipe",(function(e){e.on("error",t)})),this.on("unpipe",(function(e){e.removeListener("error",t)})),e=null}o._init.call(this,e),r.call(this)}s(a,r),Object.assign(a.prototype,o.prototype),a.prototype._new=function(e){return new a(e)},a.prototype._write=function(e,t,n){this._appendBuffer(e),"function"==typeof n&&n()},a.prototype._read=function(e){if(!this.length)return this.push(null);e=Math.min(e,this.length),this.push(this.slice(0,e)),this.consume(e)},a.prototype.end=function(e){r.prototype.end.call(this,e),this._callback&&(this._callback(null,this.slice()),this._callback=null)},a.prototype._destroy=function(e,t){this._bufs.length=0,this.length=0,t(e)},a.prototype._isBufferList=function(e){return e instanceof a||e instanceof o||a.isBufferList(e)},a.isBufferList=o.isBufferList,t.exports=a,t.exports.BufferListStream=a,t.exports.BufferList=o},{"./BufferList":14,inherits:24,"readable-stream":69}],16:[function(e,t,n){},{}],17:[function(e,t,n){(function(t){(function(){var t=e("base64-js"),r=e("ieee754");n.Buffer=i,n.SlowBuffer=y,n.INSPECT_MAX_BYTES=50;var s=2147483647;function o(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(e){return!1}}function a(e){if(e>s)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=i.prototype,t}function i(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return u(e)}return c(e,t,n)}function c(e,t,n){if("string"==typeof e)return h(e,t);if(ArrayBuffer.isView(e))return p(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(G(e,ArrayBuffer)||e&&G(e.buffer,ArrayBuffer))return f(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return i.from(r,t,n);var s=g(e);if(s)return s;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return i.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function l(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function d(e,t,n){return l(e),e<=0?a(e):void 0!==t?"string"==typeof n?a(e).fill(t,n):a(e).fill(t):a(e)}function u(e){return l(e),a(e<0?0:0|m(e))}function h(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!i.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var n=0|v(e,t),r=a(n),s=r.write(e,t);return s!==n&&(r=r.slice(0,s)),r}function p(e){for(var t=e.length<0?0:0|m(e.length),n=a(t),r=0;r<t;r+=1)n[r]=255&e[r];return n}function f(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');var r;return(r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n)).__proto__=i.prototype,r}function g(e){if(i.isBuffer(e)){var t=0|m(e.length),n=a(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0!==e.length?"number"!=typeof e.length||Y(e.length)?a(0):p(e):"Buffer"===e.type&&Array.isArray(e.data)?p(e.data):void 0}function m(e){if(e>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|e}function y(e){return+e!=e&&(e=0),i.alloc(+e)}function v(e,t){if(i.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||G(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var n=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===n)return 0;for(var s=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return Q(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return W(e).length;default:if(s)return r?-1:Q(e).length;t=(""+t).toLowerCase(),s=!0}}function b(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return x(this,t,n);case"utf8":case"utf-8":return M(this,t,n);case"ascii":return U(this,t,n);case"latin1":case"binary":return j(this,t,n);case"base64":return A(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return D(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function w(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function C(e,t,n,r,s){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),Y(n=+n)&&(n=s?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(s)return-1;n=e.length-1}else if(n<0){if(!s)return-1;n=0}if("string"==typeof t&&(t=i.from(t,r)),i.isBuffer(t))return 0===t.length?-1:I(e,t,n,r,s);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):I(e,[t],n,r,s);throw new TypeError("val must be string, number or Buffer")}function I(e,t,n,r,s){var o,a=1,i=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;a=2,i/=2,c/=2,n/=2}function l(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(s){var d=-1;for(o=n;o<i;o++)if(l(e,o)===l(t,-1===d?0:o-d)){if(-1===d&&(d=o),o-d+1===c)return d*a}else-1!==d&&(o-=o-d),d=-1}else for(n+c>i&&(n=i-c),o=n;o>=0;o--){for(var u=!0,h=0;h<c;h++)if(l(e,o+h)!==l(t,h)){u=!1;break}if(u)return o}return-1}function S(e,t,n,r){n=Number(n)||0;var s=e.length-n;r?(r=Number(r))>s&&(r=s):r=s;var o=t.length;r>o/2&&(r=o/2);for(var a=0;a<r;++a){var i=parseInt(t.substr(2*a,2),16);if(Y(i))return a;e[n+a]=i}return a}function _(e,t,n,r){return J(Q(t,e.length-n),e,n,r)}function k(e,t,n,r){return J(V(t),e,n,r)}function O(e,t,n,r){return k(e,t,n,r)}function T(e,t,n,r){return J(W(t),e,n,r)}function E(e,t,n,r){return J(H(t,e.length-n),e,n,r)}function A(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function M(e,t,n){n=Math.min(e.length,n);for(var r=[],s=t;s<n;){var o,a,i,c,l=e[s],d=null,u=l>239?4:l>223?3:l>191?2:1;if(s+u<=n)switch(u){case 1:l<128&&(d=l);break;case 2:128==(192&(o=e[s+1]))&&(c=(31&l)<<6|63&o)>127&&(d=c);break;case 3:o=e[s+1],a=e[s+2],128==(192&o)&&128==(192&a)&&(c=(15&l)<<12|(63&o)<<6|63&a)>2047&&(c<55296||c>57343)&&(d=c);break;case 4:o=e[s+1],a=e[s+2],i=e[s+3],128==(192&o)&&128==(192&a)&&128==(192&i)&&(c=(15&l)<<18|(63&o)<<12|(63&a)<<6|63&i)>65535&&c<1114112&&(d=c)}null===d?(d=65533,u=1):d>65535&&(d-=65536,r.push(d>>>10&1023|55296),d=56320|1023&d),r.push(d),s+=u}return R(r)}n.kMaxLength=s,i.TYPED_ARRAY_SUPPORT=o(),i.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(i.prototype,"parent",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.buffer}}),Object.defineProperty(i.prototype,"offset",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.byteOffset}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&i[Symbol.species]===i&&Object.defineProperty(i,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),i.poolSize=8192,i.from=function(e,t,n){return c(e,t,n)},i.prototype.__proto__=Uint8Array.prototype,i.__proto__=Uint8Array,i.alloc=function(e,t,n){return d(e,t,n)},i.allocUnsafe=function(e){return u(e)},i.allocUnsafeSlow=function(e){return u(e)},i.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==i.prototype},i.compare=function(e,t){if(G(e,Uint8Array)&&(e=i.from(e,e.offset,e.byteLength)),G(t,Uint8Array)&&(t=i.from(t,t.offset,t.byteLength)),!i.isBuffer(e)||!i.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var n=e.length,r=t.length,s=0,o=Math.min(n,r);s<o;++s)if(e[s]!==t[s]){n=e[s],r=t[s];break}return n<r?-1:r<n?1:0},i.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},i.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return i.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=i.allocUnsafe(t),s=0;for(n=0;n<e.length;++n){var o=e[n];if(G(o,Uint8Array)&&(o=i.from(o)),!i.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(r,s),s+=o.length}return r},i.byteLength=v,i.prototype._isBuffer=!0,i.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)w(this,t,t+1);return this},i.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)w(this,t,t+3),w(this,t+1,t+2);return this},i.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)w(this,t,t+7),w(this,t+1,t+6),w(this,t+2,t+5),w(this,t+3,t+4);return this},i.prototype.toString=function(){var e=this.length;return 0===e?"":0===arguments.length?M(this,0,e):b.apply(this,arguments)},i.prototype.toLocaleString=i.prototype.toString,i.prototype.equals=function(e){if(!i.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===i.compare(this,e)},i.prototype.inspect=function(){var e="",t=n.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),"<Buffer "+e+">"},i.prototype.compare=function(e,t,n,r,s){if(G(e,Uint8Array)&&(e=i.from(e,e.offset,e.byteLength)),!i.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===s&&(s=this.length),t<0||n>e.length||r<0||s>this.length)throw new RangeError("out of range index");if(r>=s&&t>=n)return 0;if(r>=s)return-1;if(t>=n)return 1;if(this===e)return 0;for(var o=(s>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0),c=Math.min(o,a),l=this.slice(r,s),d=e.slice(t,n),u=0;u<c;++u)if(l[u]!==d[u]){o=l[u],a=d[u];break}return o<a?-1:a<o?1:0},i.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},i.prototype.indexOf=function(e,t,n){return C(this,e,t,n,!0)},i.prototype.lastIndexOf=function(e,t,n){return C(this,e,t,n,!1)},i.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var s=this.length-t;if((void 0===n||n>s)&&(n=s),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var o=!1;;)switch(r){case"hex":return S(this,e,t,n);case"utf8":case"utf-8":return _(this,e,t,n);case"ascii":return k(this,e,t,n);case"latin1":case"binary":return O(this,e,t,n);case"base64":return T(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var P=4096;function R(e){var t=e.length;if(t<=P)return String.fromCharCode.apply(String,e);for(var n="",r=0;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=P));return n}function U(e,t,n){var r="";n=Math.min(e.length,n);for(var s=t;s<n;++s)r+=String.fromCharCode(127&e[s]);return r}function j(e,t,n){var r="";n=Math.min(e.length,n);for(var s=t;s<n;++s)r+=String.fromCharCode(e[s]);return r}function x(e,t,n){var r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);for(var s="",o=t;o<n;++o)s+=z(e[o]);return s}function D(e,t,n){for(var r=e.slice(t,n),s="",o=0;o<r.length;o+=2)s+=String.fromCharCode(r[o]+256*r[o+1]);return s}function N(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function B(e,t,n,r,s,o){if(!i.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>s||t<o)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function q(e,t,n,r,s,o){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function F(e,t,n,s,o){return t=+t,n>>>=0,o||q(e,t,n,4),r.write(e,t,n,s,23,4),n+4}function L(e,t,n,s,o){return t=+t,n>>>=0,o||q(e,t,n,8),r.write(e,t,n,s,52,8),n+8}i.prototype.slice=function(e,t){var n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);var r=this.subarray(e,t);return r.__proto__=i.prototype,r},i.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||N(e,t,this.length);for(var r=this[e],s=1,o=0;++o<t&&(s*=256);)r+=this[e+o]*s;return r},i.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||N(e,t,this.length);for(var r=this[e+--t],s=1;t>0&&(s*=256);)r+=this[e+--t]*s;return r},i.prototype.readUInt8=function(e,t){return e>>>=0,t||N(e,1,this.length),this[e]},i.prototype.readUInt16LE=function(e,t){return e>>>=0,t||N(e,2,this.length),this[e]|this[e+1]<<8},i.prototype.readUInt16BE=function(e,t){return e>>>=0,t||N(e,2,this.length),this[e]<<8|this[e+1]},i.prototype.readUInt32LE=function(e,t){return e>>>=0,t||N(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},i.prototype.readUInt32BE=function(e,t){return e>>>=0,t||N(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},i.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||N(e,t,this.length);for(var r=this[e],s=1,o=0;++o<t&&(s*=256);)r+=this[e+o]*s;return r>=(s*=128)&&(r-=Math.pow(2,8*t)),r},i.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||N(e,t,this.length);for(var r=t,s=1,o=this[e+--r];r>0&&(s*=256);)o+=this[e+--r]*s;return o>=(s*=128)&&(o-=Math.pow(2,8*t)),o},i.prototype.readInt8=function(e,t){return e>>>=0,t||N(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},i.prototype.readInt16LE=function(e,t){e>>>=0,t||N(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},i.prototype.readInt16BE=function(e,t){e>>>=0,t||N(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},i.prototype.readInt32LE=function(e,t){return e>>>=0,t||N(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},i.prototype.readInt32BE=function(e,t){return e>>>=0,t||N(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},i.prototype.readFloatLE=function(e,t){return e>>>=0,t||N(e,4,this.length),r.read(this,e,!0,23,4)},i.prototype.readFloatBE=function(e,t){return e>>>=0,t||N(e,4,this.length),r.read(this,e,!1,23,4)},i.prototype.readDoubleLE=function(e,t){return e>>>=0,t||N(e,8,this.length),r.read(this,e,!0,52,8)},i.prototype.readDoubleBE=function(e,t){return e>>>=0,t||N(e,8,this.length),r.read(this,e,!1,52,8)},i.prototype.writeUIntLE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||B(this,e,t,n,Math.pow(2,8*n)-1,0);var s=1,o=0;for(this[t]=255&e;++o<n&&(s*=256);)this[t+o]=e/s&255;return t+n},i.prototype.writeUIntBE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||B(this,e,t,n,Math.pow(2,8*n)-1,0);var s=n-1,o=1;for(this[t+s]=255&e;--s>=0&&(o*=256);)this[t+s]=e/o&255;return t+n},i.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,1,255,0),this[t]=255&e,t+1},i.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},i.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},i.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},i.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var s=Math.pow(2,8*n-1);B(this,e,t,n,s-1,-s)}var o=0,a=1,i=0;for(this[t]=255&e;++o<n&&(a*=256);)e<0&&0===i&&0!==this[t+o-1]&&(i=1),this[t+o]=(e/a>>0)-i&255;return t+n},i.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var s=Math.pow(2,8*n-1);B(this,e,t,n,s-1,-s)}var o=n-1,a=1,i=0;for(this[t+o]=255&e;--o>=0&&(a*=256);)e<0&&0===i&&0!==this[t+o+1]&&(i=1),this[t+o]=(e/a>>0)-i&255;return t+n},i.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},i.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},i.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},i.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},i.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeFloatLE=function(e,t,n){return F(this,e,t,!0,n)},i.prototype.writeFloatBE=function(e,t,n){return F(this,e,t,!1,n)},i.prototype.writeDoubleLE=function(e,t,n){return L(this,e,t,!0,n)},i.prototype.writeDoubleBE=function(e,t,n){return L(this,e,t,!1,n)},i.prototype.copy=function(e,t,n,r){if(!i.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);var s=r-n;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,n,r);else if(this===e&&n<t&&t<r)for(var o=s-1;o>=0;--o)e[o+t]=this[o+n];else Uint8Array.prototype.set.call(e,this.subarray(n,r),t);return s},i.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!i.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){var s=e.charCodeAt(0);("utf8"===r&&s<128||"latin1"===r)&&(e=s)}}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;var o;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(o=t;o<n;++o)this[o]=e;else{var a=i.isBuffer(e)?e:i.from(e,r),c=a.length;if(0===c)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(o=0;o<n-t;++o)this[o+t]=a[o%c]}return this};var K=/[^+/0-9A-Za-z-_]/g;function $(e){if((e=(e=e.split("=")[0]).trim().replace(K,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}function z(e){return e<16?"0"+e.toString(16):e.toString(16)}function Q(e,t){var n;t=t||1/0;for(var r=e.length,s=null,o=[],a=0;a<r;++a){if((n=e.charCodeAt(a))>55295&&n<57344){if(!s){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===r){(t-=3)>-1&&o.push(239,191,189);continue}s=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),s=n;continue}n=65536+(s-55296<<10|n-56320)}else s&&(t-=3)>-1&&o.push(239,191,189);if(s=null,n<128){if((t-=1)<0)break;o.push(n)}else if(n<2048){if((t-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function V(e){for(var t=[],n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}function H(e,t){for(var n,r,s,o=[],a=0;a<e.length&&!((t-=2)<0);++a)r=(n=e.charCodeAt(a))>>8,s=n%256,o.push(s),o.push(r);return o}function W(e){return t.toByteArray($(e))}function J(e,t,n,r){for(var s=0;s<r&&!(s+n>=t.length||s>=e.length);++s)t[s+n]=e[s];return s}function G(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Y(e){return e!=e}}).call(this)}).call(this,e("buffer").Buffer)},{"base64-js":13,buffer:17,ieee754:23}],18:[function(e,t,n){(function(r){(function(){function s(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))}function o(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;e.splice(1,0,n,"color: inherit");let r=0,s=0;e[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(s=r))})),e.splice(s,0,n)}function a(e){try{e?n.storage.setItem("debug",e):n.storage.removeItem("debug")}catch(e){}}function i(){let e;try{e=n.storage.getItem("debug")}catch(e){}return!e&&void 0!==r&&"env"in r&&(e=r.env.DEBUG),e}function c(){try{return localStorage}catch(e){}}n.formatArgs=o,n.save=a,n.load=i,n.useColors=s,n.storage=c(),n.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),n.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],n.log=console.debug||console.log||(()=>{}),t.exports=e("./common")(n);const{formatters:l}=t.exports;l.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}).call(this)}).call(this,e("_process"))},{"./common":19,_process:50}],19:[function(e,t,n){function r(t){function n(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return r.colors[Math.abs(t)%r.colors.length]}function r(e){let t,n,o,a=null;function i(...e){if(!i.enabled)return;const n=i,s=Number(new Date),o=s-(t||s);n.diff=o,n.prev=t,n.curr=s,t=s,e[0]=r.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((t,s)=>{if("%%"===t)return"%";a++;const o=r.formatters[s];if("function"==typeof o){const r=e[a];t=o.call(n,r),e.splice(a,1),a--}return t})),r.formatArgs.call(n,e),(n.log||r.log).apply(n,e)}return i.namespace=e,i.useColors=r.useColors(),i.color=r.selectColor(e),i.extend=s,i.destroy=r.destroy,Object.defineProperty(i,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(n!==r.namespaces&&(n=r.namespaces,o=r.enabled(e)),o),set:e=>{a=e}}),"function"==typeof r.init&&r.init(i),i}function s(e,t){const n=r(this.namespace+(void 0===t?":":t)+e);return n.log=this.log,n}function o(e){let t;r.save(e),r.namespaces=e,r.names=[],r.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),s=n.length;for(t=0;t<s;t++)n[t]&&("-"===(e=n[t].replace(/\*/g,".*?"))[0]?r.skips.push(new RegExp("^"+e.substr(1)+"$")):r.names.push(new RegExp("^"+e+"$")))}function a(){const e=[...r.names.map(c),...r.skips.map(c).map((e=>"-"+e))].join(",");return r.enable(""),e}function i(e){if("*"===e[e.length-1])return!0;let t,n;for(t=0,n=r.skips.length;t<n;t++)if(r.skips[t].test(e))return!1;for(t=0,n=r.names.length;t<n;t++)if(r.names[t].test(e))return!0;return!1}function c(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}function l(e){return e instanceof Error?e.stack||e.message:e}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.debug=r,r.default=r,r.coerce=l,r.disable=a,r.enable=o,r.enabled=i,r.humanize=e("ms"),r.destroy=d,Object.keys(t).forEach((e=>{r[e]=t[e]})),r.names=[],r.skips=[],r.formatters={},r.selectColor=n,r.enable(r.load()),r}t.exports=r},{ms:45}],20:[function(e,t,n){(function(n,r){(function(){var s=e("readable-stream"),o=e("end-of-stream"),a=e("inherits"),i=e("stream-shift"),c=r.from&&r.from!==Uint8Array.from?r.from([0]):new r([0]),l=function(e,t){e._corked?e.once("uncork",t):t()},d=function(e,t){e._autoDestroy&&e.destroy(t)},u=function(e,t){return function(n){n?d(e,"premature close"===n.message?null:n):t&&!e._ended&&e.end()}},h=function(e,t){return e?e._writableState&&e._writableState.finished?t():e._writableState?e.end(t):(e.end(),void t()):t()},p=function(){},f=function(e){return new s.Readable({objectMode:!0,highWaterMark:16}).wrap(e)},g=function(e,t,n){if(!(this instanceof g))return new g(e,t,n);s.Duplex.call(this,n),this._writable=null,this._readable=null,this._readable2=null,this._autoDestroy=!n||!1!==n.autoDestroy,this._forwardDestroy=!n||!1!==n.destroy,this._forwardEnd=!n||!1!==n.end,this._corked=1,this._ondrain=null,this._drained=!1,this._forwarding=!1,this._unwrite=null,this._unread=null,this._ended=!1,this.destroyed=!1,e&&this.setWritable(e),t&&this.setReadable(t)};a(g,s.Duplex),g.obj=function(e,t,n){return n||(n={}),n.objectMode=!0,n.highWaterMark=16,new g(e,t,n)},g.prototype.cork=function(){1==++this._corked&&this.emit("cork")},g.prototype.uncork=function(){this._corked&&0==--this._corked&&this.emit("uncork")},g.prototype.setWritable=function(e){if(this._unwrite&&this._unwrite(),this.destroyed)e&&e.destroy&&e.destroy();else if(null!==e&&!1!==e){var t=this,r=o(e,{writable:!0,readable:!1},u(this,this._forwardEnd)),s=function(){var e=t._ondrain;t._ondrain=null,e&&e()},a=function(){t._writable.removeListener("drain",s),r()};this._unwrite&&n.nextTick(s),this._writable=e,this._writable.on("drain",s),this._unwrite=a,this.uncork()}else this.end()},g.prototype.setReadable=function(e){if(this._unread&&this._unread(),this.destroyed)e&&e.destroy&&e.destroy();else{if(null===e||!1===e)return this.push(null),void this.resume();var t=this,n=o(e,{writable:!1,readable:!0},u(this)),r=function(){t._forward()},s=function(){t.push(null)},a=function(){t._readable2.removeListener("readable",r),t._readable2.removeListener("end",s),n()};this._drained=!0,this._readable=e,this._readable2=e._readableState?e:f(e),this._readable2.on("readable",r),this._readable2.on("end",s),this._unread=a,this._forward()}},g.prototype._read=function(){this._drained=!0,this._forward()},g.prototype._forward=function(){if(!this._forwarding&&this._readable2&&this._drained){var e;for(this._forwarding=!0;this._drained&&null!==(e=i(this._readable2));)this.destroyed||(this._drained=this.push(e));this._forwarding=!1}},g.prototype.destroy=function(e,t){if(t||(t=p),this.destroyed)return t(null);this.destroyed=!0;var r=this;n.nextTick((function(){r._destroy(e),t(null)}))},g.prototype._destroy=function(e){if(e){var t=this._ondrain;this._ondrain=null,t?t(e):this.emit("error",e)}this._forwardDestroy&&(this._readable&&this._readable.destroy&&this._readable.destroy(),this._writable&&this._writable.destroy&&this._writable.destroy()),this.emit("close")},g.prototype._write=function(e,t,n){if(!this.destroyed)return this._corked?l(this,this._write.bind(this,e,t,n)):e===c?this._finish(n):this._writable?void(!1===this._writable.write(e)?this._ondrain=n:this.destroyed||n()):n()},g.prototype._finish=function(e){var t=this;this.emit("preend"),l(this,(function(){h(t._forwardEnd&&t._writable,(function(){!1===t._writableState.prefinished&&(t._writableState.prefinished=!0),t.emit("prefinish"),l(t,e)}))}))},g.prototype.end=function(e,t,n){return"function"==typeof e?this.end(null,null,e):"function"==typeof t?this.end(e,null,t):(this._ended=!0,e&&this.write(e),this._writableState.ending||this._writableState.destroyed||this.write(c),s.Writable.prototype.end.call(this,n))},t.exports=g}).call(this)}).call(this,e("_process"),e("buffer").Buffer)},{_process:50,buffer:17,"end-of-stream":21,inherits:24,"readable-stream":69,"stream-shift":74}],21:[function(e,t,n){(function(n){(function(){var r=e("once"),s=function(){},o=function(e){return e.setHeader&&"function"==typeof e.abort},a=function(e){return e.stdio&&Array.isArray(e.stdio)&&3===e.stdio.length},i=function(e,t,c){if("function"==typeof t)return i(e,null,t);t||(t={}),c=r(c||s);var l=e._writableState,d=e._readableState,u=t.readable||!1!==t.readable&&e.readable,h=t.writable||!1!==t.writable&&e.writable,p=!1,f=function(){e.writable||g()},g=function(){h=!1,u||c.call(e)},m=function(){u=!1,h||c.call(e)},y=function(t){c.call(e,t?new Error("exited with error code: "+t):null)},v=function(t){c.call(e,t)},b=function(){n.nextTick(w)},w=function(){if(!p)return(!u||d&&d.ended&&!d.destroyed)&&(!h||l&&l.ended&&!l.destroyed)?void 0:c.call(e,new Error("premature close"))},C=function(){e.req.on("finish",g)};return o(e)?(e.on("complete",g),e.on("abort",b),e.req?C():e.on("request",C)):h&&!l&&(e.on("end",f),e.on("close",f)),a(e)&&e.on("exit",y),e.on("end",m),e.on("finish",g),!1!==t.error&&e.on("error",v),e.on("close",b),function(){p=!0,e.removeListener("complete",g),e.removeListener("abort",b),e.removeListener("request",C),e.req&&e.req.removeListener("finish",g),e.removeListener("end",f),e.removeListener("close",f),e.removeListener("finish",g),e.removeListener("exit",y),e.removeListener("end",m),e.removeListener("error",v),e.removeListener("close",b)}};t.exports=i}).call(this)}).call(this,e("_process"))},{_process:50,once:48}],22:[function(e,t,n){var r=Object.create||_,s=Object.keys||k,o=Function.prototype.bind||O;function a(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=r(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}t.exports=a,a.EventEmitter=a,a.prototype._events=void 0,a.prototype._maxListeners=void 0;var i,c=10;try{var l={};Object.defineProperty&&Object.defineProperty(l,"x",{value:0}),i=0===l.x}catch(e){i=!1}function d(e){return void 0===e._maxListeners?a.defaultMaxListeners:e._maxListeners}function u(e,t,n){if(t)e.call(n);else for(var r=e.length,s=I(e,r),o=0;o<r;++o)s[o].call(n)}function h(e,t,n,r){if(t)e.call(n,r);else for(var s=e.length,o=I(e,s),a=0;a<s;++a)o[a].call(n,r)}function p(e,t,n,r,s){if(t)e.call(n,r,s);else for(var o=e.length,a=I(e,o),i=0;i<o;++i)a[i].call(n,r,s)}function f(e,t,n,r,s,o){if(t)e.call(n,r,s,o);else for(var a=e.length,i=I(e,a),c=0;c<a;++c)i[c].call(n,r,s,o)}function g(e,t,n,r){if(t)e.apply(n,r);else for(var s=e.length,o=I(e,s),a=0;a<s;++a)o[a].apply(n,r)}function m(e,t,n,s){var o,a,i;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((a=e._events)?(a.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),a=e._events),i=a[t]):(a=e._events=r(null),e._eventsCount=0),i){if("function"==typeof i?i=a[t]=s?[n,i]:[i,n]:s?i.unshift(n):i.push(n),!i.warned&&(o=d(e))&&o>0&&i.length>o){i.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+i.length+' "'+String(t)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=i.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",c.name,c.message)}}else i=a[t]=n,++e._eventsCount;return e}function y(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var e=new Array(arguments.length),t=0;t<e.length;++t)e[t]=arguments[t];this.listener.apply(this.target,e)}}function v(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},s=o.call(y,r);return s.listener=n,r.wrapFn=s,s}function b(e,t,n){var r=e._events;if(!r)return[];var s=r[t];return s?"function"==typeof s?n?[s.listener||s]:[s]:n?S(s):I(s,s.length):[]}function w(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function C(e,t){for(var n=t,r=n+1,s=e.length;r<s;n+=1,r+=1)e[n]=e[r];e.pop()}function I(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}function S(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function _(e){var t=function(){};return t.prototype=e,new t}function k(e){for(var t in e)Object.prototype.hasOwnProperty.call(e,t);return t}function O(e){var t=this;return function(){return t.apply(e,arguments)}}i?Object.defineProperty(a,"defaultMaxListeners",{enumerable:!0,get:function(){return c},set:function(e){if("number"!=typeof e||e<0||e!=e)throw new TypeError('"defaultMaxListeners" must be a positive number');c=e}}):a.defaultMaxListeners=c,a.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},a.prototype.getMaxListeners=function(){return d(this)},a.prototype.emit=function(e){var t,n,r,s,o,a,i="error"===e;if(a=this._events)i=i&&null==a.error;else if(!i)return!1;if(i){if(arguments.length>1&&(t=arguments[1]),t instanceof Error)throw t;var c=new Error('Unhandled "error" event. ('+t+")");throw c.context=t,c}if(!(n=a[e]))return!1;var l="function"==typeof n;switch(r=arguments.length){case 1:u(n,l,this);break;case 2:h(n,l,this,arguments[1]);break;case 3:p(n,l,this,arguments[1],arguments[2]);break;case 4:f(n,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(s=new Array(r-1),o=1;o<r;o++)s[o-1]=arguments[o];g(n,l,this,s)}return!0},a.prototype.addListener=function(e,t){return m(this,e,t,!1)},a.prototype.on=a.prototype.addListener,a.prototype.prependListener=function(e,t){return m(this,e,t,!0)},a.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,v(this,e,t)),this},a.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,v(this,e,t)),this},a.prototype.removeListener=function(e,t){var n,s,o,a,i;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(s=this._events))return this;if(!(n=s[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=r(null):(delete s[e],s.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(o=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){i=n[a].listener,o=a;break}if(o<0)return this;0===o?n.shift():C(n,o),1===n.length&&(s[e]=n[0]),s.removeListener&&this.emit("removeListener",e,i||t)}return this},a.prototype.removeAllListeners=function(e){var t,n,o;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=r(null),this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=r(null):delete n[e]),this;if(0===arguments.length){var a,i=s(n);for(o=0;o<i.length;++o)"removeListener"!==(a=i[o])&&this.removeAllListeners(a);return this.removeAllListeners("removeListener"),this._events=r(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(t)for(o=t.length-1;o>=0;o--)this.removeListener(e,t[o]);return this},a.prototype.listeners=function(e){return b(this,e,!0)},a.prototype.rawListeners=function(e){return b(this,e,!1)},a.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):w.call(e,t)},a.prototype.listenerCount=w,a.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}},{}],23:[function(e,t,n){
|
|
2
2
|
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
|
|
3
|
-
n.read=function(e,t,n,r,o){var s,a,i=8*o-r-1,c=(1<<i)-1,l=c>>1,d=-7,u=n?o-1:0,h=n?-1:1,p=e[t+u];for(u+=h,s=p&(1<<-d)-1,p>>=-d,d+=i;d>0;s=256*s+e[t+u],u+=h,d-=8);for(a=s&(1<<-d)-1,s>>=-d,d+=r;d>0;a=256*a+e[t+u],u+=h,d-=8);if(0===s)s=1-l;else{if(s===c)return a?NaN:1/0*(p?-1:1);a+=Math.pow(2,r),s-=l}return(p?-1:1)*a*Math.pow(2,s-r)},n.write=function(e,t,n,r,o,s){var a,i,c,l=8*s-o-1,d=(1<<l)-1,u=d>>1,h=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,p=r?0:s-1,f=r?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(i=isNaN(t)?1:0,a=d):(a=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-a))<1&&(a--,c*=2),(t+=a+u>=1?h/c:h*Math.pow(2,1-u))*c>=2&&(a++,c/=2),a+u>=d?(i=0,a=d):a+u>=1?(i=(t*c-1)*Math.pow(2,o),a+=u):(i=t*Math.pow(2,u-1)*Math.pow(2,o),a=0));o>=8;e[n+p]=255&i,p+=f,i/=256,o-=8);for(a=a<<o|i,l+=o;l>0;e[n+p]=255&a,p+=f,a/=256,l-=8);e[n+p-f]|=128*g}},{}],24:[function(e,t,n){"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 n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}},{}],25:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var r=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,n=this.leftChild,r=this.rightChild;if(!r)throw new Error("unknown error");var o=r.leftChild,s=r.rightChild;return e&&(e.leftChild===this?e.leftChild=r:e.rightChild===this&&(e.rightChild=r)),r.parent=e,r.brother=t,r.leftChild=this,r.rightChild=s,t&&(t.brother=r),this.parent=r,this.brother=s,this.leftChild=n,this.rightChild=o,s&&(s.parent=r,s.brother=this),n&&(n.parent=this,n.brother=o),o&&(o.parent=this,o.brother=n),r},e.prototype.rotateRight=function(){var e=this.parent,t=this.brother,n=this.leftChild;if(!n)throw new Error("unknown error");var r=this.rightChild,o=n.leftChild,s=n.rightChild;return e&&(e.leftChild===this?e.leftChild=n:e.rightChild===this&&(e.rightChild=n)),n.parent=e,n.brother=t,n.leftChild=o,n.rightChild=this,t&&(t.brother=n),o&&(o.parent=n,o.brother=this),this.parent=n,this.brother=o,this.leftChild=s,this.rightChild=r,s&&(s.parent=this,s.brother=r),r&&(r.parent=this,r.brother=s),n},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(r),n.default=r},{}],26:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,o,s,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){a.label=s[1];break}if(6===s[0]&&a.label<o[1]){a.label=o[1],o=s;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(s);break}o[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}};function o(e){var t=this;void 0===e&&(e=[]);var n=[],s=0,a=0,i=0,c=0,l=0,d=0;this.size=function(){return d},this.empty=function(){return 0===d},this.clear=function(){s=i=a=c=l=d=0,h.call(this,o.bucketSize),d=0},this.front=function(){return n[s][a]},this.back=function(){return n[i][c]},this.forEach=function(e){if(!this.empty()){var t=0;if(s!==i){for(l=a;l<o.bucketSize;++l)e(n[s][l],t++);for(l=s+1;l<i;++l)for(var r=0;r<o.bucketSize;++r)e(n[l][r],t++);for(l=0;l<=c;++l)e(n[i][l],t++)}else for(var l=a;l<=c;++l)e(n[s][l],t++)}};var u=function(e){var t=s*o.bucketSize+a,n=t+e,r=i*o.bucketSize+c;if(n<t||n>r)throw new Error("pos should more than 0 and less than queue's size");return{curNodeBucketIndex:Math.floor(n/o.bucketSize),curNodePointerIndex:n%o.bucketSize}};this.getElementByPos=function(e){var t=u(e),r=t.curNodeBucketIndex,o=t.curNodePointerIndex;return n[r][o]},this.eraseElementByPos=function(e){var t=this;if(e<0||e>d)throw new Error("pos should more than 0 and less than queue's size");if(0===e)this.popFront();else if(e===this.size())this.popBack();else{for(var n=[],r=e+1;r<d;++r)n.push(this.getElementByPos(r));this.cut(e),this.popBack(),n.forEach((function(e){return t.pushBack(e)}))}},this.eraseElementByValue=function(e){if(!this.empty()){var t=[];this.forEach((function(n){n!==e&&t.push(n)}));for(var n=t.length,r=0;r<n;++r)this.setElementByPos(r,t[r]);this.cut(n-1)}};var h=function(e){for(var t=[],r=e*o.sigma,u=Math.max(Math.ceil(r/o.bucketSize),2),h=0;h<u;++h)t.push(new Array(o.bucketSize));var p=Math.ceil(e/o.bucketSize),f=Math.floor(u/2)-Math.floor(p/2),g=f,m=0;if(this.size())for(h=0;h<p;++h){for(var y=0;y<o.bucketSize;++y)if(t[f+h][y]=this.front(),this.popFront(),this.empty()){g=f+h,m=y;break}if(this.empty())break}n=t,s=f,a=0,i=g,c=m,l=u,d=e};this.pushBack=function(e){this.empty()||(i===l-1&&c===o.bucketSize-1&&h.call(this,this.size()),c<o.bucketSize-1?++c:i<l-1&&(++i,c=0)),++d,n[i][c]=e},this.popBack=function(){this.empty()||(1!==this.size()&&(c>0?--c:s<i&&(--i,c=o.bucketSize-1)),d>0&&--d)},this.setElementByPos=function(e,t){var r=u(e),o=r.curNodeBucketIndex,s=r.curNodePointerIndex;n[o][s]=t},this.insert=function(e,t,n){var r=this;if(void 0===n&&(n=1),0===e)for(;n--;)this.pushFront(t);else if(e===this.size())for(;n--;)this.pushBack(t);else{for(var o=[],s=e;s<d;++s)o.push(this.getElementByPos(s));for(this.cut(e-1),s=0;s<n;++s)this.pushBack(t);o.forEach((function(e){return r.pushBack(e)}))}},this.find=function(e){if(s===i){for(var t=a;t<=c;++t)if(n[s][t]===e)return!0;return!1}for(t=a;t<o.bucketSize;++t)if(n[s][t]===e)return!0;for(t=s+1;t<i;++t)for(var r=0;r<o.bucketSize;++r)if(n[t][r]===e)return!0;for(t=0;t<=c;++t)if(n[i][t]===e)return!0;return!1},this.reverse=function(){for(var e=0,t=d-1;e<t;){var n=this.getElementByPos(e);this.setElementByPos(e,this.getElementByPos(t)),this.setElementByPos(t,n),++e,--t}},this.unique=function(){if(!this.empty()){var e=[],t=this.front();this.forEach((function(n,r){0!==r&&n===t||(e.push(n),t=n)}));for(var n=0;n<d;++n)this.setElementByPos(n,e[n]);this.cut(e.length-1)}},this.sort=function(e){var t=[];this.forEach((function(e){t.push(e)})),t.sort(e);for(var n=0;n<d;++n)this.setElementByPos(n,t[n])},this.pushFront=function(e){this.empty()||(0===s&&0===a&&h.call(this,this.size()),a>0?--a:s>0&&(--s,a=o.bucketSize-1)),++d,n[s][a]=e},this.popFront=function(){this.empty()||(1!==this.size()&&(a<o.bucketSize-1?++a:s<i&&(++s,a=0)),d>0&&--d)},this.shrinkToFit=function(){var e=this,t=[];this.forEach((function(e){t.push(e)}));var r=t.length;n=[];for(var s=Math.ceil(r/o.bucketSize),a=0;a<s;++a)n.push(new Array(o.bucketSize));this.clear(),t.forEach((function(t){return e.pushBack(t)}))},this.cut=function(e){if(e<0)this.clear();else{var t=u(e),n=t.curNodeBucketIndex,r=t.curNodePointerIndex;i=n,c=r,d=e+1}},this[Symbol.iterator]=function(){return function(){var e,t;return r(this,(function(r){switch(r.label){case 0:if(0===d)return[2];if(s!==i)return[3,5];t=a,r.label=1;case 1:return t<=c?[4,n[s][t]]:[3,4];case 2:r.sent(),r.label=3;case 3:return++t,[3,1];case 4:return[2];case 5:t=a,r.label=6;case 6:return t<o.bucketSize?[4,n[s][t]]:[3,9];case 7:r.sent(),r.label=8;case 8:return++t,[3,6];case 9:t=s+1,r.label=10;case 10:if(!(t<i))return[3,15];e=0,r.label=11;case 11:return e<o.bucketSize?[4,n[t][e]]:[3,14];case 12:r.sent(),r.label=13;case 13:return++e,[3,11];case 14:return++t,[3,10];case 15:t=0,r.label=16;case 16:return t<=c?[4,n[i][t]]:[3,19];case 17:r.sent(),r.label=18;case 18:return++t,[3,16];case 19:return[2]}}))}()},function(){var r=o.bucketSize;e.size?r=e.size():e.length&&(r=e.length);var a=r*o.sigma;l=Math.ceil(a/o.bucketSize),l=Math.max(l,3);for(var c=0;c<l;++c)n.push(new Array(o.bucketSize));var d=Math.ceil(r/o.bucketSize);s=Math.floor(l/2)-Math.floor(d/2),i=s,e.forEach((function(e){return t.pushBack(e)}))}(),Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),o.sigma=3,o.bucketSize=5e3,Object.freeze(o),n.default=o},{}],27:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,o,s,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){a.label=s[1];break}if(6===s[0]&&a.label<o[1]){a.label=o[1],o=s;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(s);break}o[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},o=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var s=e("../LinkList/LinkList"),a=e("../Map/Map");function i(e,t,n){var c=this;if(void 0===e&&(e=[]),void 0===t&&(t=i.initSize),n=n||function(e){var t,n,r=0,s="";if("number"==typeof e)r=((r=Math.floor(e))<<5)-r,r&=r;else{s="string"!=typeof e?JSON.stringify(e):e;try{for(var a=o(s),i=a.next();!i.done;i=a.next())r=(r<<5)-r+i.value.charCodeAt(0),r&=r}catch(e){t={error:e}}finally{try{i&&!i.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}}return r^=r>>>16},0!=(t&t-1))throw new Error("initBucketNum must be 2 to the power of n");var l=0,d=[],u=Math.max(i.initSize,Math.min(i.maxSize,t));this.size=function(){return l},this.empty=function(){return 0===l},this.clear=function(){l=0,u=t,d=[]},this.forEach=function(e){var t=0;d.forEach((function(n){n.forEach((function(n){e(n,t++)}))}))};var h=function(e){if(!(e>=i.maxSize)){u=2*e;var t=[];d.forEach((function(r,o){if(!r.empty()){if(r instanceof s.default&&1===r.size()){var c=r.front(),l=c.key,h=c.value;t[n(l)&u-1]=new s.default([{key:l,value:h}])}else if(r instanceof a.default){var p=new s.default,f=new s.default;r.forEach((function(t){0==(n(t.key)&e)?p.pushBack(t):f.pushBack(t)})),p.size()>i.untreeifyThreshold?t[o]=new a.default(p):p.size()&&(t[o]=p),f.size()>i.untreeifyThreshold?t[o+e]=new a.default(f):f.size()&&(t[o+e]=f)}else{var g=new s.default,m=new s.default;r.forEach((function(t){0==(n(t.key)&e)?g.pushBack(t):m.pushBack(t)})),g.size()&&(t[o]=g),m.size()&&(t[o+e]=m)}d[o].clear()}})),d=t}};this.setElement=function(e,t){var r,c;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 p=n(e)&u-1;if(d[p]){var f=d[p].size();if(d[p]instanceof s.default){try{for(var g=o(d[p]),m=g.next();!m.done;m=g.next()){var y=m.value;if(y.key===e)return void(y.value=t)}}catch(e){r={error:e}}finally{try{m&&!m.done&&(c=g.return)&&c.call(g)}finally{if(r)throw r.error}}d[p].pushBack({key:e,value:t}),d[p].size()>=i.treeifyThreshold&&(d[p]=new a.default(d[p]))}else d[p].setElement(e,t);var v=d[p].size();l+=v-f}else++l,d[p]=new s.default([{key:e,value:t}]);l>u*i.sigma&&h.call(this,u)}else this.eraseElementByKey(e)},this.getElementByKey=function(e){var t,r,s=n(e)&u-1;if(d[s]){if(d[s]instanceof a.default)return d[s].getElementByKey(e);try{for(var i=o(d[s]),c=i.next();!c.done;c=i.next()){var l=c.value;if(l.key===e)return l.value}}catch(e){t={error:e}}finally{try{c&&!c.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}}},this.eraseElementByKey=function(e){var t,r,c=n(e)&u-1;if(d[c]){var h=d[c].size();if(d[c]instanceof a.default)d[c].eraseElementByKey(e),d[c].size()<=i.untreeifyThreshold&&(d[c]=new s.default(d[c]));else{var p=-1;try{for(var f=o(d[c]),g=f.next();!g.done;g=f.next()){var m=g.value;if(++p,m.key===e){d[c].eraseElementByPos(p);break}}}catch(e){t={error:e}}finally{try{g&&!g.done&&(r=f.return)&&r.call(f)}finally{if(t)throw t.error}}}var y=d[c].size();l+=y-h}},this.find=function(e){var t,r,s=n(e)&u-1;if(!d[s])return!1;if(d[s]instanceof a.default)return d[s].find(e);try{for(var i=o(d[s]),c=i.next();!c.done;c=i.next())if(c.value.key===e)return!0}catch(e){t={error:e}}finally{try{c&&!c.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return!1},this[Symbol.iterator]=function(){return function(){var e,t,n,s,a,i;return r(this,(function(r){switch(r.label){case 0:e=0,r.label=1;case 1:if(!(e<u))return[3,10];for(;e<u&&!d[e];)++e;if(e>=u)return[3,10];r.label=2;case 2:r.trys.push([2,7,8,9]),a=void 0,t=o(d[e]),n=t.next(),r.label=3;case 3:return n.done?[3,6]:[4,n.value];case 4:r.sent(),r.label=5;case 5:return n=t.next(),[3,3];case 6:return[3,9];case 7:return s=r.sent(),a={error:s},[3,9];case 8:try{n&&!n.done&&(i=t.return)&&i.call(t)}finally{if(a)throw a.error}return[7];case 9:return++e,[3,1];case 10:return[2]}}))}()},e.forEach((function(e){var t=e.key,n=e.value;return c.setElement(t,n)})),Object.freeze(this)}i.initSize=16,i.maxSize=1<<30,i.sigma=.75,i.treeifyThreshold=8,i.untreeifyThreshold=6,i.minTreeifySize=64,Object.freeze(i),n.default=i},{"../LinkList/LinkList":29,"../Map/Map":30}],28:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,o,s,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){a.label=s[1];break}if(6===s[0]&&a.label<o[1]){a.label=o[1],o=s;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(s);break}o[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},o=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var s=e("../Set/Set"),a=e("../LinkList/LinkList");function i(e,t,n){var c=this;if(void 0===e&&(e=[]),void 0===t&&(t=i.initSize),n=n||function(e){var t=0,n="";if("number"==typeof e)t=((t=Math.floor(e))<<5)-t,t&=t;else{n="string"!=typeof e?JSON.stringify(e):e;for(var r=0;r<n.length;r++)t=(t<<5)-t+n.charCodeAt(r),t&=t}return t^=t>>>16},0!=(t&t-1))throw new Error("initBucketNum must be 2 to the power of n");var l=0,d=[],u=Math.max(i.initSize,Math.min(i.maxSize,t));this.size=function(){return l},this.empty=function(){return 0===l},this.clear=function(){l=0,u=t,d=[]},this.forEach=function(e){var t=0;d.forEach((function(n){n.forEach((function(n){e(n,t++)}))}))};var h=function(e){if(!(e>=i.maxSize)){u=2*e;var t=[];d.forEach((function(r,o){if(!r.empty()){if(r instanceof a.default&&1===r.size()){var c=r.front();if(void 0===c)throw new Error("unknown error");t[n(c)&u-1]=new a.default([c])}else if(r instanceof s.default){var l=new a.default,h=new a.default;r.forEach((function(t){0==(n(t)&e)?l.pushBack(t):h.pushBack(t)})),l.size()>i.untreeifyThreshold?t[o]=new s.default(l):l.size()&&(t[o]=l),h.size()>i.untreeifyThreshold?t[o+e]=new s.default(h):h.size()&&(t[o+e]=h)}else{var p=new a.default,f=new a.default;r.forEach((function(t){0==(n(t)&e)?p.pushBack(t):f.pushBack(t)})),p.size()&&(t[o]=p),f.size()&&(t[o+e]=f)}d[o].clear()}})),d=t}};this.insert=function(e){if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");var t=n(e)&u-1;if(d[t]){var r=d[t].size();if(d[t]instanceof a.default){if(d[t].find(e))return;d[t].pushBack(e),d[t].size()>=i.treeifyThreshold&&(d[t]=new s.default(d[t]))}else d[t].insert(e);var o=d[t].size();l+=o-r}else d[t]=new a.default([e]),++l;l>u*i.sigma&&h.call(this,u)},this.eraseElementByValue=function(e){var t=n(e)&u-1;if(d[t]){var r=d[t].size();d[t].eraseElementByValue(e),d[t]instanceof s.default&&d[t].size()<=i.untreeifyThreshold&&(d[t]=new a.default(d[t]));var o=d[t].size();l+=o-r}},this.find=function(e){var t=n(e)&u-1;return!!d[t]&&d[t].find(e)},this[Symbol.iterator]=function(){return function(){var e,t,n,s,a,i;return r(this,(function(r){switch(r.label){case 0:e=0,r.label=1;case 1:if(!(e<u))return[3,10];for(;e<u&&!d[e];)++e;if(e>=u)return[3,10];r.label=2;case 2:r.trys.push([2,7,8,9]),a=void 0,t=o(d[e]),n=t.next(),r.label=3;case 3:return n.done?[3,6]:[4,n.value];case 4:r.sent(),r.label=5;case 5:return n=t.next(),[3,3];case 6:return[3,9];case 7:return s=r.sent(),a={error:s},[3,9];case 8:try{n&&!n.done&&(i=t.return)&&i.call(t)}finally{if(a)throw a.error}return[7];case 9:return++e,[3,1];case 10:return[2]}}))}()},e.forEach((function(e){return c.insert(e)})),Object.freeze(this)}i.initSize=16,i.maxSize=1<<30,i.sigma=.75,i.treeifyThreshold=8,i.untreeifyThreshold=6,i.minTreeifySize=64,Object.freeze(i),n.default=i},{"../LinkList/LinkList":29,"../Set/Set":33}],29:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,o,s,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){a.label=s[1];break}if(6===s[0]&&a.label<o[1]){a.label=o[1],o=s;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(s);break}o[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}};Object.defineProperty(n,"__esModule",{value:!0});var o=function(){function e(e){this.value=void 0,this.pre=void 0,this.next=void 0,this.value=e}return e}();function s(e){var t=this;void 0===e&&(e=[]);var n=0,s=void 0,a=void 0;this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){s=a=void 0,n=0},this.front=function(){return null==s?void 0:s.value},this.back=function(){return null==a?void 0:a.value},this.forEach=function(e){for(var t=s,n=0;t;){if(void 0===t.value)throw new Error("unknown error");e(t.value,n++),t=t.next}},this.getElementByPos=function(e){if(e<0||e>=n)throw new Error("pos must more then 0 and less then the list length");for(var t=s;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>=n)throw new Error("erase pos must more then 0 and less then the list length");if(0===e)this.popFront();else if(e===n-1)this.popBack();else{for(var t=s;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 r=t.pre,o=t.next;o.pre=r,r.next=o,n>0&&--n}},this.eraseElementByValue=function(e){for(;s&&s.value===e;)this.popFront();for(;a&&a.value===e;)this.popBack();if(s)for(var t=s;t;){if(t.value===e){var r=t.pre,o=t.next;o&&(o.pre=r),r&&(r.next=o),n>0&&--n}t=t.next}},this.pushBack=function(e){if(null==e)throw new Error("you can't push null or undefined here");++n;var t=new o(e);a?(a.next=t,t.pre=a,a=t):s=a=t},this.popBack=function(){a&&(n>0&&--n,a&&(s===a?s=a=void 0:(a=a.pre)&&(a.next=void 0)))},this.setElementByPos=function(e,t){if(null==t)throw new Error("you can't set null or undefined here");if(e<0||e>=n)throw new Error("pos must more then 0 and less then the list length");for(var r=s;e--;){if(!r)throw new Error("unknown error");r=r.next}r&&(r.value=t)},this.insert=function(e,t,r){if(void 0===r&&(r=1),null==t)throw new Error("you can't insert null or undefined here");if(e<0||e>n)throw new Error("insert pos must more then 0 and less then or equal to the list length");if(r<0)throw new Error("insert size must more than 0");if(0===e)for(;r--;)this.pushFront(t);else if(e===n)for(;r--;)this.pushBack(t);else{for(var a=s,i=1;i<e;++i){if(!(null==a?void 0:a.next))throw new Error("unknown error");a=null==a?void 0:a.next}if(!a)throw new Error("unknown error");var c=a.next;for(n+=r;r--;)a.next=new o(t),a.next.pre=a,a=a.next;a.next=c,c&&(c.pre=a)}},this.find=function(e){for(var t=s;t;){if(t.value===e)return!0;t=t.next}return!1},this.reverse=function(){for(var e=s,t=a,r=0;e&&t&&2*r<n;){var o=e.value;e.value=t.value,t.value=o,e=e.next,t=t.pre,++r}},this.unique=function(){for(var e=s;e;){for(var t=e;t&&t.next&&t.value===t.next.value;)t=t.next,n>0&&--n;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 n=s;t.forEach((function(e){n&&(n.value=e,n=n.next)}))},this.pushFront=function(e){if(null==e)throw new Error("you can't push null or undefined here");++n;var t=new o(e);s?(t.next=s,s.pre=t,s=t):s=a=t},this.popFront=function(){s&&(n>0&&--n,s&&(s===a?s=a=void 0:(s=s.next)&&(s.pre=void 0)))},this.merge=function(e){var t=this,r=s;e.forEach((function(e){for(;r&&void 0!==r.value&&r.value<=e;)r=r.next;if(void 0===r)t.pushBack(e),r=a;else if(r===s)t.pushFront(e),r=s;else{++n;var i=r.pre;i&&(i.next=new o(e),i.next.pre=i,i.next.next=r,r&&(r.pre=i.next))}}))},this[Symbol.iterator]=function(){return function(){var e;return r(this,(function(t){switch(t.label){case 0:e=s,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(s),n.default=s},{}],30:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,o,s,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){a.label=s[1];break}if(6===s[0]&&a.label<o[1]){a.label=o[1],o=s;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(s);break}o[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},o=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var s=e("../Base/TreeNode");function a(e,t){var n=this;void 0===e&&(e=[]),t=t||function(e,t){return e<t?-1:e>t?1:0};var a=0,i=new s.default;i.color=s.default.TreeNodeColorType.black,this.size=function(){return a},this.empty=function(){return 0===a},this.clear=function(){a=0,i.key=i.value=void 0,i.leftChild=i.rightChild=i.brother=void 0};var c=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.leftChild?c(e.leftChild):e},l=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.rightChild?l(e.rightChild):e};this.front=function(){if(!this.empty()){var e=c(i);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=l(i);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,n,r=0;try{for(var s=o(this),a=s.next();!a.done;a=s.next())e(a.value,r++)}catch(e){t={error:e}}finally{try{a&&!a.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}},this.getElementByPos=function(e){var t,n;if(e<0||e>=this.size())throw new Error("pos must more than 0 and less than set's size");var r=0;try{for(var s=o(this),a=s.next();!a.done;a=s.next()){var i=a.value;if(r===e)return i;++r}}catch(e){t={error:e}}finally{try{a&&!a.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}throw new Error("unknown Error")};var d=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value){var r=t(e.key,n);return 0===r?{key:e.key,value:e.value}:r<0?d(e.rightChild,n):d(e.leftChild,n)||{key:e.key,value:e.value}}};this.lowerBound=function(e){return d(i,e)};var u=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value)return t(e.key,n)<=0?u(e.rightChild,n):u(e.leftChild,n)||{key:e.key,value:e.value}};this.upperBound=function(e){return u(i,e)};var h=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value){var r=t(e.key,n);return 0===r?{key:e.key,value:e.value}:r>0?h(e.leftChild,n):h(e.rightChild,n)||{key:e.key,value:e.value}}};this.reverseLowerBound=function(e){return h(i,e)};var p=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value)return t(e.key,n)>=0?p(e.leftChild,n):p(e.rightChild,n)||{key:e.key,value:e.value}};this.reverseUpperBound=function(e){return p(i,e)};var f=function(e){var t=e.parent;if(!t){if(e===i)return;throw new Error("unknown error")}if(e.color!==s.default.TreeNodeColorType.red){var n=e.brother;if(!n)throw new Error("unknown error");if(e===t.leftChild)if(n.color===s.default.TreeNodeColorType.red){n.color=s.default.TreeNodeColorType.black,t.color=s.default.TreeNodeColorType.red;var r=t.rotateLeft();i===t&&(i=r),f(e)}else n.color===s.default.TreeNodeColorType.black&&(n.rightChild&&n.rightChild.color===s.default.TreeNodeColorType.red?(n.color=t.color,t.color=s.default.TreeNodeColorType.black,n.rightChild&&(n.rightChild.color=s.default.TreeNodeColorType.black),r=t.rotateLeft(),i===t&&(i=r),e.color=s.default.TreeNodeColorType.black):n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||!n.leftChild||n.leftChild.color!==s.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||(n.color=s.default.TreeNodeColorType.red,f(t)):(n.color=s.default.TreeNodeColorType.red,n.leftChild&&(n.leftChild.color=s.default.TreeNodeColorType.black),r=n.rotateRight(),i===n&&(i=r),f(e)));else e===t.rightChild&&(n.color===s.default.TreeNodeColorType.red?(n.color=s.default.TreeNodeColorType.black,t.color=s.default.TreeNodeColorType.red,r=t.rotateRight(),i===t&&(i=r),f(e)):n.color===s.default.TreeNodeColorType.black&&(n.leftChild&&n.leftChild.color===s.default.TreeNodeColorType.red?(n.color=t.color,t.color=s.default.TreeNodeColorType.black,n.leftChild&&(n.leftChild.color=s.default.TreeNodeColorType.black),r=t.rotateRight(),i===t&&(i=r),e.color=s.default.TreeNodeColorType.black):n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||!n.rightChild||n.rightChild.color!==s.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||(n.color=s.default.TreeNodeColorType.red,f(t)):(n.color=s.default.TreeNodeColorType.red,n.rightChild&&(n.rightChild.color=s.default.TreeNodeColorType.black),r=n.rotateLeft(),i===n&&(i=r),f(e))))}else e.color=s.default.TreeNodeColorType.black},g=function(e){for(var t=e;t.leftChild||t.rightChild;){if(t.rightChild){t=c(t.rightChild);var n=e.key;e.key=t.key,t.key=n;var r=e.value;e.value=t.value,t.value=r,e=t}t.leftChild&&(t=l(t.leftChild),n=e.key,e.key=t.key,t.key=n,r=e.value,e.value=t.value,t.value=r,e=t)}f(t),t&&t.remove(),--a,i.color=s.default.TreeNodeColorType.black},m=function(e,t){return!(!e||void 0===e.key)&&(!!m(e.leftChild,t)||!!t(e)||m(e.rightChild,t))};this.eraseElementByPos=function(e){if(e<0||e>=a)throw new Error("pos must more than 0 and less than set's size");var t=0;m(i,(function(n){return e===t?(g(n),!0):(++t,!1)}))},this.eraseElementByKey=function(e){if(!this.empty()){var n=b(i,e);void 0!==n&&void 0!==n.key&&0===t(n.key,e)&&g(n)}};var y=function(e,n){if(!e||void 0===e.key)throw new Error("unknown error");var r=t(n,e.key);return r<0?e.leftChild?y(e.leftChild,n):(e.leftChild=new s.default,e.leftChild.parent=e,e.leftChild.brother=e.rightChild,e.rightChild&&(e.rightChild.brother=e.leftChild),e.leftChild):r>0?e.rightChild?y(e.rightChild,n):(e.rightChild=new s.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===i)return;throw new Error("unknown error")}if(t.color!==s.default.TreeNodeColorType.black&&t.color===s.default.TreeNodeColorType.red){var n=t.brother,r=t.parent;if(!r)throw new Error("unknown error");if(n&&n.color===s.default.TreeNodeColorType.red)n.color=t.color=s.default.TreeNodeColorType.black,r.color=s.default.TreeNodeColorType.red,v(r);else if(!n||n.color===s.default.TreeNodeColorType.black)if(t===r.leftChild)if(e===t.leftChild){t.color=s.default.TreeNodeColorType.black,r.color=s.default.TreeNodeColorType.red;var o=r.rotateRight();r===i&&(i=o)}else e===t.rightChild&&(o=t.rotateLeft(),r===i&&(i=o),v(t));else t===r.rightChild&&(e===t.leftChild?(o=t.rotateRight(),r===i&&(i=o),v(t)):e===t.rightChild&&(t.color=s.default.TreeNodeColorType.black,r.color=s.default.TreeNodeColorType.red,o=r.rotateLeft(),r===i&&(i=o)))}};this.setElement=function(e,n){if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(null!=n){if(this.empty())return++a,i.key=e,i.value=n,void(i.color=s.default.TreeNodeColorType.black);var r=y(i,e);void 0===r.key||0!==t(r.key,e)?(++a,r.key=e,r.value=n,v(r),i.color=s.default.TreeNodeColorType.black):r.value=n}else this.eraseElementByKey(e)};var b=function(e,n){if(e&&void 0!==e.key){var r=t(n,e.key);return r<0?b(e.leftChild,n):r>0?b(e.rightChild,n):e}};this.find=function(e){return!!b(i,e)},this.getElementByKey=function(e){var t=b(i,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 n=e.key,r=e.value;return t.setElement(n,r)}))},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(i)};var w=function(e){return r(this,(function(t){switch(t.label){case 0:return e&&void 0!==e.key&&void 0!==e.value?[5,o(w(e.leftChild))]:[2];case 1:return t.sent(),[4,{key:e.key,value:e.value}];case 2:return t.sent(),[5,o(w(e.rightChild))];case 3:return t.sent(),[2]}}))};this[Symbol.iterator]=function(){return w(i)},e.forEach((function(e){var t=e.key,r=e.value;return n.setElement(t,r)})),Object.freeze(this)}Object.freeze(a),n.default=a},{"../Base/TreeNode":25}],31:[function(e,t,n){function r(e,t){void 0===e&&(e=[]),t=t||function(e,t){return e>t?-1:e<t?1:0};var n=[];e.forEach((function(e){return n.push(e)}));var r=n.length,o=function(e,t){if(e<0||e>=r)throw new Error("unknown error");if(t<0||t>=r)throw new Error("unknown error");var o=n[e];n[e]=n[t],n[t]=o},s=function(e){if(e<0||e>=r)throw new Error("unknown error");var s=2*e+1,a=2*e+2;s<r&&t(n[e],n[s])>0&&o(e,s),a<r&&t(n[e],n[a])>0&&o(e,a)};!function(){for(var e=Math.floor((r-1)/2);e>=0;--e)for(var s=e,a=2*s+1;a<r;){var i=a+1,c=a;if(i<r&&t(n[a],n[i])>0&&(c=i),t(n[s],n[c])<=0)break;o(s,c),a=2*(s=c)+1}}(),this.size=function(){return r},this.empty=function(){return 0===r},this.clear=function(){r=0,n.length=0},this.push=function(e){if(n.push(e),1!=++r)for(var o=r-1;o>0;){var a=Math.floor((o-1)/2);if(t(n[a],e)<=0)break;s(a),o=a}},this.pop=function(){if(!this.empty())if(1!==this.size()){var e=n[r-1];--r;for(var o=0;o<this.size();){var s=2*o+1,a=2*o+2;if(s>=this.size())break;var i=s;if(a<this.size()&&t(n[s],n[a])>0&&(i=a),t(n[i],e)>=0)break;n[o]=n[i],o=i}n[o]=e}else--r},this.top=function(){return n[0]},Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),Object.freeze(r),n.default=r},{}],32:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var r=e("../LinkList/LinkList");function o(e){void 0===e&&(e=[]);var t=new r.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(o),n.default=o},{"../LinkList/LinkList":29}],33:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,o,s,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){a.label=s[1];break}if(6===s[0]&&a.label<o[1]){a.label=o[1],o=s;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(s);break}o[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},o=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var s=e("../Base/TreeNode");function a(e,t){var n=this;void 0===e&&(e=[]),t=t||function(e,t){return e<t?-1:e>t?1:0};var a=0,i=new s.default;i.color=s.default.TreeNodeColorType.black,this.size=function(){return a},this.empty=function(){return 0===a},this.clear=function(){a=0,i.key=void 0,i.leftChild=i.rightChild=i.brother=i.parent=void 0,i.color=s.default.TreeNodeColorType.black};var c=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.leftChild?c(e.leftChild):e},l=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.rightChild?l(e.rightChild):e};this.front=function(){if(!this.empty())return c(i).key},this.back=function(){if(!this.empty())return l(i).key},this.forEach=function(e){var t,n,r=0;try{for(var s=o(this),a=s.next();!a.done;a=s.next())e(a.value,r++)}catch(e){t={error:e}}finally{try{a&&!a.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}},this.getElementByPos=function(e){var t,n;if(e<0||e>=this.size())throw new Error("pos must more than 0 and less than set's size");var r=0;try{for(var s=o(this),a=s.next();!a.done;a=s.next()){var i=a.value;if(r===e)return i;++r}}catch(e){t={error:e}}finally{try{a&&!a.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}throw new Error("unknown error")};var d=function(e){var t=e.parent;if(!t){if(e===i)return;throw new Error("unknown error")}if(e.color!==s.default.TreeNodeColorType.red){var n=e.brother;if(!n)throw new Error("unknown error");if(e===t.leftChild)if(n.color===s.default.TreeNodeColorType.red){n.color=s.default.TreeNodeColorType.black,t.color=s.default.TreeNodeColorType.red;var r=t.rotateLeft();i===t&&(i=r),d(e)}else n.color===s.default.TreeNodeColorType.black&&(n.rightChild&&n.rightChild.color===s.default.TreeNodeColorType.red?(n.color=t.color,t.color=s.default.TreeNodeColorType.black,n.rightChild&&(n.rightChild.color=s.default.TreeNodeColorType.black),r=t.rotateLeft(),i===t&&(i=r),e.color=s.default.TreeNodeColorType.black):n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||!n.leftChild||n.leftChild.color!==s.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||(n.color=s.default.TreeNodeColorType.red,d(t)):(n.color=s.default.TreeNodeColorType.red,n.leftChild&&(n.leftChild.color=s.default.TreeNodeColorType.black),r=n.rotateRight(),i===n&&(i=r),d(e)));else e===t.rightChild&&(n.color===s.default.TreeNodeColorType.red?(n.color=s.default.TreeNodeColorType.black,t.color=s.default.TreeNodeColorType.red,r=t.rotateRight(),i===t&&(i=r),d(e)):n.color===s.default.TreeNodeColorType.black&&(n.leftChild&&n.leftChild.color===s.default.TreeNodeColorType.red?(n.color=t.color,t.color=s.default.TreeNodeColorType.black,n.leftChild&&(n.leftChild.color=s.default.TreeNodeColorType.black),r=t.rotateRight(),i===t&&(i=r),e.color=s.default.TreeNodeColorType.black):n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||!n.rightChild||n.rightChild.color!==s.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||(n.color=s.default.TreeNodeColorType.red,d(t)):(n.color=s.default.TreeNodeColorType.red,n.rightChild&&(n.rightChild.color=s.default.TreeNodeColorType.black),r=n.rotateLeft(),i===n&&(i=r),d(e))))}else e.color=s.default.TreeNodeColorType.black},u=function(e){for(var t=e;t.leftChild||t.rightChild;){if(t.rightChild){t=c(t.rightChild);var n=e.key;e.key=t.key,t.key=n,e=t}t.leftChild&&(t=l(t.leftChild),n=e.key,e.key=t.key,t.key=n,e=t)}d(t),t&&t.remove(),--a,i.color=s.default.TreeNodeColorType.black},h=function(e,t){return!(!e||void 0===e.key)&&(!!h(e.leftChild,t)||!!t(e)||h(e.rightChild,t))};this.eraseElementByPos=function(e){if(e<0||e>=a)throw new Error("pos must more than 0 and less than set's size");var t=0;h(i,(function(n){return e===t?(u(n),!0):(++t,!1)}))},this.eraseElementByValue=function(e){if(!this.empty()){var n=g(i,e);void 0!==n&&void 0!==n.key&&0===t(n.key,e)&&u(n)}};var p=function(e,n){if(!e||void 0===e.key)throw new Error("unknown error");var r=t(n,e.key);return r<0?e.leftChild?p(e.leftChild,n):(e.leftChild=new s.default,e.leftChild.parent=e,e.leftChild.brother=e.rightChild,e.rightChild&&(e.rightChild.brother=e.leftChild),e.leftChild):r>0?e.rightChild?p(e.rightChild,n):(e.rightChild=new s.default,e.rightChild.parent=e,e.rightChild.brother=e.leftChild,e.leftChild&&(e.leftChild.brother=e.rightChild),e.rightChild):e},f=function(e){var t=e.parent;if(!t){if(e===i)return;throw new Error("unknown error")}if(t.color!==s.default.TreeNodeColorType.black&&t.color===s.default.TreeNodeColorType.red){var n=t.brother,r=t.parent;if(!r)throw new Error("unknown error");if(n&&n.color===s.default.TreeNodeColorType.red)n.color=t.color=s.default.TreeNodeColorType.black,r.color=s.default.TreeNodeColorType.red,f(r);else if(!n||n.color===s.default.TreeNodeColorType.black)if(t===r.leftChild)if(e===t.leftChild){t.color=s.default.TreeNodeColorType.black,r.color=s.default.TreeNodeColorType.red;var o=r.rotateRight();r===i&&(i=o)}else e===t.rightChild&&(o=t.rotateLeft(),r===i&&(i=o),f(t));else t===r.rightChild&&(e===t.leftChild?(o=t.rotateRight(),r===i&&(i=o),f(t)):e===t.rightChild&&(t.color=s.default.TreeNodeColorType.black,r.color=s.default.TreeNodeColorType.red,o=r.rotateLeft(),r===i&&(i=o)))}};this.insert=function(e){if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(this.empty())return++a,i.key=e,void(i.color=s.default.TreeNodeColorType.black);var n=p(i,e);void 0!==n.key&&0===t(n.key,e)||(++a,n.key=e,f(n),i.color=s.default.TreeNodeColorType.black)};var g=function(e,n){if(e&&void 0!==e.key){var r=t(n,e.key);return r<0?g(e.leftChild,n):r>0?g(e.rightChild,n):e}};this.find=function(e){var n=g(i,e);return void 0!==n&&void 0!==n.key&&0===t(n.key,e)};var m=function(e,n){if(e&&void 0!==e.key){var r=t(e.key,n);if(0===r)return e.key;if(r<0)return m(e.rightChild,n);var o=m(e.leftChild,n);return void 0!==o?o:e.key}};this.lowerBound=function(e){return m(i,e)};var y=function(e,n){if(e&&void 0!==e.key){if(t(e.key,n)<=0)return y(e.rightChild,n);var r=y(e.leftChild,n);return void 0!==r?r:e.key}};this.upperBound=function(e){return y(i,e)};var v=function(e,n){if(e&&void 0!==e.key){var r=t(e.key,n);if(0===r)return e.key;if(r>0)return v(e.leftChild,n);var o=v(e.rightChild,n);return void 0!==o?o:e.key}};this.reverseLowerBound=function(e){return v(i,e)};var b=function(e,n){if(e&&void 0!==e.key){if(t(e.key,n)>=0)return b(e.leftChild,n);var r=b(e.rightChild,n);return void 0!==r?r:e.key}};this.reverseUpperBound=function(e){return b(i,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(i)};var w=function(e){return r(this,(function(t){switch(t.label){case 0:return e&&void 0!==e.key?[5,o(w(e.leftChild))]:[2];case 1:return t.sent(),[4,e.key];case 2:return t.sent(),[5,o(w(e.rightChild))];case 3:return t.sent(),[2]}}))};this[Symbol.iterator]=function(){return w(i)},e.forEach((function(e){return n.insert(e)})),Object.freeze(this)}Object.freeze(a),n.default=a},{"../Base/TreeNode":25}],34:[function(e,t,n){function r(e){var t=this;void 0===e&&(e=[]);var n=0,r=[];this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){n=0,r.length=0},this.push=function(e){r.push(e),++n},this.pop=function(){r.pop(),n>0&&--n},this.top=function(){return r[n-1]},e.forEach((function(e){return t.push(e)})),Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),Object.freeze(r),n.default=r},{}],35:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,o,s,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){a.label=s[1];break}if(6===s[0]&&a.label<o[1]){a.label=o[1],o=s;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(s);break}o[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},o=this&&this.__read||function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,s=n.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(r=s.next()).done;)a.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(o)throw o.error}}return a},s=this&&this.__spreadArray||function(e,t,n){if(n||2===arguments.length)for(var r,o=0,s=t.length;o<s;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))},a=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};function i(e){var t=this;void 0===e&&(e=[]);var n=0,i=[];this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){n=0,i.length=0},this.front=function(){if(!this.empty())return i[0]},this.back=function(){if(!this.empty())return i[n-1]},this.forEach=function(e){i.forEach(e)},this.getElementByPos=function(e){if(e<0||e>=n)throw new Error("pos must more than 0 and less than vector's size");return i[e]},this.eraseElementByPos=function(e){if(e<0||e>=n)throw new Error("pos must more than 0 and less than vector's size");for(var t=e;t<n-1;++t)i[t]=i[t+1];this.popBack()},this.eraseElementByValue=function(e){var t=[];this.forEach((function(n){n!==e&&t.push(n)})),t.forEach((function(e,t){i[t]=e}));for(var r=t.length;n>r;)this.popBack()},this.pushBack=function(e){i.push(e),++n},this.popBack=function(){i.pop(),n>0&&--n},this.setElementByPos=function(e,t){if(e<0||e>=n)throw new Error("pos must more than 0 and less than vector's size");i[e]=t},this.insert=function(e,t,r){if(void 0===r&&(r=1),e<0||e>n)throw new Error("pos must more than 0 and less than or equal to vector's size");i.splice.apply(i,s([e,0],o(new Array(r).fill(t)),!1)),n+=r},this.find=function(e){return i.includes(e)},this.reverse=function(){i.reverse()},this.unique=function(){var e,t=[];this.forEach((function(n,r){0!==r&&n===e||(t.push(n),e=n)})),t.forEach((function(e,t){i[t]=e}));for(var r=t.length;n>r;)this.popBack()},this.sort=function(e){i.sort(e)},this[Symbol.iterator]=function(){return function(){return r(this,(function(e){switch(e.label){case 0:return[5,a(i)];case 1:return[2,e.sent()]}}))}()},e.forEach((function(e){return t.pushBack(e)})),Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),Object.freeze(i),n.default=i},{}],36:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0}),n.HashMap=n.HashSet=n.Map=n.Set=n.PriorityQueue=n.Deque=n.LinkList=n.Queue=n.Stack=n.Vector=void 0;var r=e("./Vector/Vector");n.Vector=r.default;var o=e("./Stack/Stack");n.Stack=o.default;var s=e("./Queue/Queue");n.Queue=s.default;var a=e("./LinkList/LinkList");n.LinkList=a.default;var i=e("./Deque/Deque");n.Deque=i.default;var c=e("./PriorityQueue/PriorityQueue");n.PriorityQueue=c.default;var l=e("./Set/Set");n.Set=l.default;var d=e("./Map/Map");n.Map=d.default;var u=e("./HashSet/HashSet");n.HashSet=u.default;var h=e("./HashMap/HashMap");n.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,n){const r=e("yallist"),o=Symbol("max"),s=Symbol("length"),a=Symbol("lengthCalculator"),i=Symbol("allowStale"),c=Symbol("maxAge"),l=Symbol("dispose"),d=Symbol("noDisposeOnSet"),u=Symbol("lruList"),h=Symbol("cache"),p=Symbol("updateAgeOnGet"),f=()=>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[o]=e.max||1/0;const t=e.length||f;if(this[a]="function"!=typeof t?f:t,this[i]=e.stale||!1,e.maxAge&&"number"!=typeof e.maxAge)throw new TypeError("maxAge must be a number");this[c]=e.maxAge||0,this[l]=e.dispose,this[d]=e.noDisposeOnSet||!1,this[p]=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[o]=e||1/0,v(this)}get max(){return this[o]}set allowStale(e){this[i]=!!e}get allowStale(){return this[i]}set maxAge(e){if("number"!=typeof e)throw new TypeError("maxAge must be a non-negative number");this[c]=e,v(this)}get maxAge(){return this[c]}set lengthCalculator(e){"function"!=typeof e&&(e=f),e!==this[a]&&(this[a]=e,this[s]=0,this[u].forEach((e=>{e.length=this[a](e.value,e.key),this[s]+=e.length}))),v(this)}get lengthCalculator(){return this[a]}get length(){return this[s]}get itemCount(){return this[u].length}rforEach(e,t){t=t||this;for(let n=this[u].tail;null!==n;){const r=n.prev;C(this,e,n,t),n=r}}forEach(e,t){t=t||this;for(let n=this[u].head;null!==n;){const r=n.next;C(this,e,n,t),n=r}}keys(){return this[u].toArray().map((e=>e.key))}values(){return this[u].toArray().map((e=>e.value))}reset(){this[l]&&this[u]&&this[u].length&&this[u].forEach((e=>this[l](e.key,e.value))),this[h]=new Map,this[u]=new r,this[s]=0}dump(){return this[u].map((e=>!y(this,e)&&{k:e.key,v:e.value,e:e.now+(e.maxAge||0)})).toArray().filter((e=>e))}dumpLru(){return this[u]}set(e,t,n){if((n=n||this[c])&&"number"!=typeof n)throw new TypeError("maxAge must be a number");const r=n?Date.now():0,i=this[a](t,e);if(this[h].has(e)){if(i>this[o])return b(this,this[h].get(e)),!1;const a=this[h].get(e).value;return this[l]&&(this[d]||this[l](e,a.value)),a.now=r,a.maxAge=n,a.value=t,this[s]+=i-a.length,a.length=i,this.get(e),v(this),!0}const p=new w(e,t,i,r,n);return p.length>this[o]?(this[l]&&this[l](e,t),!1):(this[s]+=p.length,this[u].unshift(p),this[h].set(e,this[u].head),v(this),!0)}has(e){if(!this[h].has(e))return!1;const t=this[h].get(e).value;return!y(this,t)}get(e){return m(this,e,!0)}peek(e){return m(this,e,!1)}pop(){const e=this[u].tail;return e?(b(this,e),e.value):null}del(e){b(this,this[h].get(e))}load(e){this.reset();const t=Date.now();for(let n=e.length-1;n>=0;n--){const r=e[n],o=r.e||0;if(0===o)this.set(r.k,r.v);else{const e=o-t;e>0&&this.set(r.k,r.v,e)}}}prune(){this[h].forEach(((e,t)=>m(this,t,!1)))}}const m=(e,t,n)=>{const r=e[h].get(t);if(r){const t=r.value;if(y(e,t)){if(b(e,r),!e[i])return}else n&&(e[p]&&(r.value.now=Date.now()),e[u].unshiftNode(r));return t.value}},y=(e,t)=>{if(!t||!t.maxAge&&!e[c])return!1;const n=Date.now()-t.now;return t.maxAge?n>t.maxAge:e[c]&&n>e[c]},v=e=>{if(e[s]>e[o])for(let t=e[u].tail;e[s]>e[o]&&null!==t;){const n=t.prev;b(e,t),t=n}},b=(e,t)=>{if(t){const n=t.value;e[l]&&e[l](n.key,n.value),e[s]-=n.length,e[h].delete(n.key),e[u].removeNode(t)}};class w{constructor(e,t,n,r,o){this.key=e,this.value=t,this.length=n,this.now=r,this.maxAge=o||0}}const C=(e,t,n,r)=>{let o=n.value;y(e,o)&&(b(e,n),e[i]||(o=void 0)),o&&t.call(r,o.value,o.key,e)};t.exports=g},{yallist:83}],38:[function(e,t,n){(function(e){(function(){const n=t.exports;n.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"},n.codes={};for(const e in n.types){const t=n.types[e];n.codes[t]=e}n.CMD_SHIFT=4,n.CMD_MASK=240,n.DUP_MASK=8,n.QOS_MASK=3,n.QOS_SHIFT=1,n.RETAIN_MASK=1,n.VARBYTEINT_MASK=127,n.VARBYTEINT_FIN_MASK=128,n.VARBYTEINT_MAX=268435455,n.SESSIONPRESENT_MASK=1,n.SESSIONPRESENT_HEADER=e.from([n.SESSIONPRESENT_MASK]),n.CONNACK_HEADER=e.from([n.codes.connack<<n.CMD_SHIFT]),n.USERNAME_MASK=128,n.PASSWORD_MASK=64,n.WILL_RETAIN_MASK=32,n.WILL_QOS_MASK=24,n.WILL_QOS_SHIFT=3,n.WILL_FLAG_MASK=4,n.CLEAN_SESSION_MASK=2,n.CONNECT_HEADER=e.from([n.codes.connect<<n.CMD_SHIFT]),n.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},n.propertiesCodes={};for(const e in n.properties){const t=n.properties[e];n.propertiesCodes[t]=e}function r(t){return[0,1,2].map((r=>[0,1].map((o=>[0,1].map((s=>{const a=e.alloc(1);return a.writeUInt8(n.codes[t]<<n.CMD_SHIFT|(o?n.DUP_MASK:0)|r<<n.QOS_SHIFT|s,0,!0),a}))))))}n.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"},n.PUBLISH_HEADER=r("publish"),n.SUBSCRIBE_HEADER=r("subscribe"),n.SUBSCRIBE_OPTIONS_QOS_MASK=3,n.SUBSCRIBE_OPTIONS_NL_MASK=1,n.SUBSCRIBE_OPTIONS_NL_SHIFT=2,n.SUBSCRIBE_OPTIONS_RAP_MASK=1,n.SUBSCRIBE_OPTIONS_RAP_SHIFT=3,n.SUBSCRIBE_OPTIONS_RH_MASK=3,n.SUBSCRIBE_OPTIONS_RH_SHIFT=4,n.SUBSCRIBE_OPTIONS_RH=[0,16,32],n.SUBSCRIBE_OPTIONS_NL=4,n.SUBSCRIBE_OPTIONS_RAP=8,n.SUBSCRIBE_OPTIONS_QOS=[0,1,2],n.UNSUBSCRIBE_HEADER=r("unsubscribe"),n.ACKS={unsuback:r("unsuback"),puback:r("puback"),pubcomp:r("pubcomp"),pubrel:r("pubrel"),pubrec:r("pubrec")},n.SUBACK_HEADER=e.from([n.codes.suback<<n.CMD_SHIFT]),n.VERSION3=e.from([3]),n.VERSION4=e.from([4]),n.VERSION5=e.from([5]),n.VERSION131=e.from([131]),n.VERSION132=e.from([132]),n.QOS=[0,1,2].map((t=>e.from([t]))),n.EMPTY={pingreq:e.from([n.codes.pingreq<<4,0]),pingresp:e.from([n.codes.pingresp<<4,0]),disconnect:e.from([n.codes.disconnect<<4,0])}}).call(this)}).call(this,e("buffer").Buffer)},{buffer:17}],39:[function(e,t,n){(function(n){(function(){const r=e("./writeToStream"),o=e("events");function s(e,t){const n=new a;return r(e,n,t),n.concat()}class a extends o{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),r=this._array;let o,s=0;for(o=0;o<r.length&&void 0!==r[o];o++)"string"!=typeof r[o]?t[o]=r[o].length:t[o]=n.byteLength(r[o]),e+=t[o];const a=n.allocUnsafe(e);for(o=0;o<r.length&&void 0!==r[o];o++)"string"!=typeof r[o]?(r[o].copy(a,s),s+=t[o]):(a.write(r[o],s),s+=t[o]);return a}}t.exports=s}).call(this)}).call(this,e("buffer").Buffer)},{"./writeToStream":44,buffer:17,events:22}],40:[function(e,t,n){n.parser=e("./parser").parser,n.generate=e("./generate"),n.writeToStream=e("./writeToStream")},{"./generate":39,"./parser":43,"./writeToStream":44}],41:[function(e,t,n){(function(e){(function(){const n=65536,r={},o=e.isBuffer(e.from([1,2]).subarray(0,1));function s(t){const n=e.allocUnsafe(2);return n.writeUInt8(t>>8,0),n.writeUInt8(255&t,1),n}function a(){for(let e=0;e<n;e++)r[e]=s(e)}function i(t){const n=4;let r=0,s=0;const a=e.allocUnsafe(n);do{r=t%128|0,(t=t/128|0)>0&&(r|=128),a.writeUInt8(r,s++)}while(t>0&&s<n);return t>0&&(s=0),o?a.subarray(0,s):a.slice(0,s)}function c(t){const n=e.allocUnsafe(4);return n.writeUInt32BE(t,0),n}t.exports={cache:r,generateCache:a,generateNumber:s,genBufVariableByteInt:i,generate4ByteBuffer:c}}).call(this)}).call(this,e("buffer").Buffer)},{buffer:17}],42:[function(e,t,n){class r{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}}t.exports=r},{}],43:[function(e,t,n){const r=e("bl"),o=e("events"),s=e("./packet"),a=e("./constants"),i=e("debug")("mqtt-packet:parser");class c extends o{constructor(){super(),this.parser=this.constructor.parser}static parser(e){return this instanceof c?(this.settings=e||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):(new c).parser(e)}_resetState(){i("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new s,this.error=null,this._list=r(),this._stateCounter=0}parse(e){for(this.error&&this._resetState(),this._list.append(e),i("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++,i("parse: state complete. _stateCounter is now: %d",this._stateCounter),i("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return i("parse: exited while loop. packet: %d, buffer list length: %d",this.packet.length,this._list.length),this._list.length}_parseHeader(){const e=this._list.readUInt8(0);return this.packet.cmd=a.types[e>>a.CMD_SHIFT],this.packet.retain=0!=(e&a.RETAIN_MASK),this.packet.qos=e>>a.QOS_SHIFT&a.QOS_MASK,this.packet.dup=0!=(e&a.DUP_MASK),i("_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)),i("_parseLength %d",e.value),!!e}_parsePayload(){i("_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 i("_parsePayload complete result: %s",e),e}_parseConnect(){let e,t,n,r;i("_parseConnect");const o={},s=this.packet,c=this._parseString();if(null===c)return this._emitError(new Error("Cannot parse protocolId"));if("MQTT"!==c&&"MQIsdp"!==c)return this._emitError(new Error("Invalid protocolId"));if(s.protocolId=c,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(s.protocolVersion=this._list.readUInt8(this._pos),s.protocolVersion>=128&&(s.bridgeMode=!0,s.protocolVersion=s.protocolVersion-128),3!==s.protocolVersion&&4!==s.protocolVersion&&5!==s.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(o.username=this._list.readUInt8(this._pos)&a.USERNAME_MASK,o.password=this._list.readUInt8(this._pos)&a.PASSWORD_MASK,o.will=this._list.readUInt8(this._pos)&a.WILL_FLAG_MASK,o.will&&(s.will={},s.will.retain=0!=(this._list.readUInt8(this._pos)&a.WILL_RETAIN_MASK),s.will.qos=(this._list.readUInt8(this._pos)&a.WILL_QOS_MASK)>>a.WILL_QOS_SHIFT),s.clean=0!=(this._list.readUInt8(this._pos)&a.CLEAN_SESSION_MASK),this._pos++,s.keepalive=this._parseNum(),-1===s.keepalive)return this._emitError(new Error("Packet too short"));if(5===s.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(s.properties=e)}const l=this._parseString();if(null===l)return this._emitError(new Error("Packet too short"));if(s.clientId=l,i("_parseConnect: packet.clientId: %s",s.clientId),o.will){if(5===s.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(s.will.properties=e)}if(e=this._parseString(),null===e)return this._emitError(new Error("Cannot parse will topic"));if(s.will.topic=e,i("_parseConnect: packet.will.topic: %s",s.will.topic),t=this._parseBuffer(),null===t)return this._emitError(new Error("Cannot parse will payload"));s.will.payload=t,i("_parseConnect: packet.will.paylaod: %s",s.will.payload)}if(o.username){if(r=this._parseString(),null===r)return this._emitError(new Error("Cannot parse username"));s.username=r,i("_parseConnect: packet.username: %s",s.username)}if(o.password){if(n=this._parseBuffer(),null===n)return this._emitError(new Error("Cannot parse password"));s.password=n}return this.settings=s,i("_parseConnect: complete"),s}_parseConnack(){i("_parseConnack");const e=this.packet;if(this._list.length<1)return null;if(e.sessionPresent=!!(this._list.readUInt8(this._pos++)&a.SESSIONPRESENT_MASK),5===this.settings.protocolVersion)this._list.length>=2?e.reasonCode=this._list.readUInt8(this._pos++):e.reasonCode=0;else{if(this._list.length<2)return null;e.returnCode=this._list.readUInt8(this._pos++)}if(-1===e.returnCode||-1===e.reasonCode)return this._emitError(new Error("Cannot parse return code"));if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}i("_parseConnack: complete")}_parsePublish(){i("_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),i("_parsePublish: payload from buffer list: %o",e.payload)}}_parseSubscribe(){i("_parseSubscribe");const e=this.packet;let t,n,r,o,s,c,l;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"));n=this._parseByte(),r=n&a.SUBSCRIBE_OPTIONS_QOS_MASK,c=0!=(n>>a.SUBSCRIBE_OPTIONS_NL_SHIFT&a.SUBSCRIBE_OPTIONS_NL_MASK),s=0!=(n>>a.SUBSCRIBE_OPTIONS_RAP_SHIFT&a.SUBSCRIBE_OPTIONS_RAP_MASK),o=n>>a.SUBSCRIBE_OPTIONS_RH_SHIFT&a.SUBSCRIBE_OPTIONS_RH_MASK,l={topic:t,qos:r},5===this.settings.protocolVersion?(l.nl=c,l.rap=s,l.rh=o):this.settings.bridgeMode&&(l.rh=0,l.rap=!0,l.nl=!0),i("_parseSubscribe: push subscription `%s` to subscription",l),e.subscriptions.push(l)}}}_parseSuback(){i("_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(){i("_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"));i("_parseUnsubscribe: push topic `%s` to unsubscriptions",t),e.unsubscriptions.push(t)}}}_parseUnsuback(){i("_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(){i("_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(),i("_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(i("_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 i("_parseDisconnect result: true"),!0}_parseAuth(){i("_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),i("_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):(i("_parseMessageId: packet.messageId %d",e.messageId),!0)}_parseString(e){const t=this._parseNum(),n=t+this._pos;if(-1===t||n>this._list.length||n>this.packet.length)return null;const r=this._list.toString("utf8",this._pos,n);return this._pos+=t,i("_parseString: result: %s",r),r}_parseStringPair(){return i("_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 n=this._list.slice(this._pos,t);return this._pos+=e,i("_parseBuffer: result: %o",n),n}_parseNum(){if(this._list.length-this._pos<2)return-1;const e=this._list.readUInt16BE(this._pos);return this._pos+=2,i("_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,i("_parse4ByteNum: result: %s",e),e}_parseVarByteNum(e){i("_parseVarByteNum");const t=4;let n,r=0,o=1,s=0,c=!1;const l=this._pos?this._pos:0;for(;r<t&&l+r<this._list.length;){if(n=this._list.readUInt8(l+r++),s+=o*(n&a.VARBYTEINT_MASK),o*=128,0==(n&a.VARBYTEINT_FIN_MASK)){c=!0;break}if(this._list.length<=r)break}return!c&&r===t&&this._list.length>=r&&this._emitError(new Error("Invalid variable byte integer")),l&&(this._pos+=r),c=!!c&&(e?{bytes:r,value:s}:s),i("_parseVarByteNum: result: %o",c),c}_parseByte(){let e;return this._pos<this._list.length&&(e=this._list.readUInt8(this._pos),this._pos++),i("_parseByte: result: %o",e),e}_parseByType(e){switch(i("_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(){i("_parseProperties");const e=this._parseVarByteNum(),t=this._pos+e,n={};for(;this._pos<t;){const e=this._parseByte();if(!e)return this._emitError(new Error("Cannot parse property code type")),!1;const t=a.propertiesCodes[e];if(!t)return this._emitError(new Error("Unknown property")),!1;if("userProperties"!==t)n[t]?(Array.isArray(n[t])||(n[t]=[n[t]]),n[t].push(this._parseByType(a.propertiesTypes[t]))):n[t]=this._parseByType(a.propertiesTypes[t]);else{n[t]||(n[t]=Object.create(null));const e=this._parseByType(a.propertiesTypes[t]);if(n[t][e.name])if(Array.isArray(n[t][e.name]))n[t][e.name].push(e.value);else{const r=n[t][e.name];n[t][e.name]=[r],n[t][e.name].push(e.value)}else n[t][e.name]=e.value}}return n}_newPacket(){return i("_newPacket"),this.packet&&(this._list.consume(this.packet.length),i("_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)),i("_newPacket: new packet"),this.packet=new s,this._pos=0,!0}_emitError(e){i("_emitError"),this.error=e,this.emit("error",e)}}t.exports=c},{"./constants":38,"./packet":42,bl:15,debug:18,events:22}],44:[function(e,t,n){(function(n){(function(){const r=e("./constants"),o=n.allocUnsafe(0),s=n.from([0]),a=e("./numbers"),i=e("process-nextick-args").nextTick,c=e("debug")("mqtt-packet:writeToStream"),l=a.cache,d=a.generateNumber,u=a.generateCache,h=a.genBufVariableByteInt,p=a.generate4ByteBuffer;let f=U,g=!0;function m(e,t,n){switch(c("generate called"),t.cork&&(t.cork(),i(y,t)),g&&(g=!1,u()),c("generate: packet.cmd: %s",e.cmd),e.cmd){case"connect":return v(e,t);case"connack":return b(e,t,n);case"publish":return w(e,t,n);case"puback":case"pubrec":case"pubrel":case"pubcomp":return C(e,t,n);case"subscribe":return I(e,t,n);case"suback":return S(e,t,n);case"unsubscribe":return _(e,t,n);case"unsuback":return k(e,t,n);case"pingreq":case"pingresp":return O(e,t);case"disconnect":return T(e,t,n);case"auth":return A(e,t,n);default:return t.emit("error",new Error("Unknown command")),!1}}function y(e){e.uncork()}function v(e,t,o){const s=e||{},a=s.protocolId||"MQTT";let i=s.protocolVersion||4;const c=s.will;let l=s.clean;const d=s.keepalive||0,u=s.clientId||"",h=s.username,p=s.password,g=s.properties;void 0===l&&(l=!0);let m=0;if(!a||"string"!=typeof a&&!n.isBuffer(a))return t.emit("error",new Error("Invalid protocolId")),!1;if(m+=a.length+2,3!==i&&4!==i&&5!==i)return t.emit("error",new Error("Invalid protocol version")),!1;if(m+=1,("string"==typeof u||n.isBuffer(u))&&(u||i>=4)&&(u||l))m+=n.byteLength(u)+2;else{if(i<4)return t.emit("error",new Error("clientId must be supplied before 3.1.1")),!1;if(1*l==0)return t.emit("error",new Error("clientId must be given if cleanSession set to 0")),!1}if("number"!=typeof d||d<0||d>65535||d%1!=0)return t.emit("error",new Error("Invalid keepalive")),!1;if(m+=2,m+=1,5===i){var y=N(t,g);if(!y)return!1;m+=y.length}if(c){if("object"!=typeof c)return t.emit("error",new Error("Invalid will")),!1;if(!c.topic||"string"!=typeof c.topic)return t.emit("error",new Error("Invalid will topic")),!1;if(m+=n.byteLength(c.topic)+2,m+=2,c.payload){if(!(c.payload.length>=0))return t.emit("error",new Error("Invalid will payload")),!1;"string"==typeof c.payload?m+=n.byteLength(c.payload):m+=c.payload.length}var v={};if(5===i){if(!(v=N(t,c.properties)))return!1;m+=v.length}}let b=!1;if(null!=h){if(!K(h))return t.emit("error",new Error("Invalid username")),!1;b=!0,m+=n.byteLength(h)+2}if(null!=p){if(!b)return t.emit("error",new Error("Username is required to use password")),!1;if(!K(p))return t.emit("error",new Error("Invalid password")),!1;m+=L(p)+2}t.write(r.CONNECT_HEADER),M(t,m),D(t,a),s.bridgeMode&&(i+=128),t.write(131===i?r.VERSION131:132===i?r.VERSION132:4===i?r.VERSION4:5===i?r.VERSION5:r.VERSION3);let w=0;return w|=null!=h?r.USERNAME_MASK:0,w|=null!=p?r.PASSWORD_MASK:0,w|=c&&c.retain?r.WILL_RETAIN_MASK:0,w|=c&&c.qos?c.qos<<r.WILL_QOS_SHIFT:0,w|=c?r.WILL_FLAG_MASK:0,w|=l?r.CLEAN_SESSION_MASK:0,t.write(n.from([w])),f(t,d),5===i&&y.write(),D(t,u),c&&(5===i&&v.write(),P(t,c.topic),D(t,c.payload)),null!=h&&D(t,h),null!=p&&D(t,p),!0}function b(e,t,o){const a=o?o.protocolVersion:4,i=e||{},c=5===a?i.reasonCode:i.returnCode,l=i.properties;let d=2;if("number"!=typeof c)return t.emit("error",new Error("Invalid return code")),!1;let u=null;if(5===a){if(u=N(t,l),!u)return!1;d+=u.length}return t.write(r.CONNACK_HEADER),M(t,d),t.write(i.sessionPresent?r.SESSIONPRESENT_HEADER:s),t.write(n.from([c])),null!=u&&u.write(),!0}function w(e,t,s){c("publish: packet: %o",e);const a=s?s.protocolVersion:4,i=e||{},l=i.qos||0,d=i.retain?r.RETAIN_MASK:0,u=i.topic,h=i.payload||o,p=i.messageId,g=i.properties;let m=0;if("string"==typeof u)m+=n.byteLength(u)+2;else{if(!n.isBuffer(u))return t.emit("error",new Error("Invalid topic")),!1;m+=u.length+2}if(n.isBuffer(h)?m+=h.length:m+=n.byteLength(h),l&&"number"!=typeof p)return t.emit("error",new Error("Invalid messageId")),!1;l&&(m+=2);let y=null;if(5===a){if(y=N(t,g),!y)return!1;m+=y.length}return t.write(r.PUBLISH_HEADER[l][i.dup?1:0][d?1:0]),M(t,m),f(t,L(u)),t.write(u),l>0&&f(t,p),null!=y&&y.write(),c("publish: payload: %o",h),t.write(h)}function C(e,t,o){const s=o?o.protocolVersion:4,a=e||{},i=a.cmd||"puback",c=a.messageId,l=a.dup&&"pubrel"===i?r.DUP_MASK:0;let d=0;const u=a.reasonCode,h=a.properties;let p=5===s?3:2;if("pubrel"===i&&(d=1),"number"!=typeof c)return t.emit("error",new Error("Invalid messageId")),!1;let g=null;if(5===s&&"object"==typeof h){if(g=B(t,h,o,p),!g)return!1;p+=g.length}return t.write(r.ACKS[i][d][l][0]),M(t,p),f(t,c),5===s&&t.write(n.from([u])),null!==g&&g.write(),!0}function I(e,t,o){c("subscribe: packet: ");const s=o?o.protocolVersion:4,a=e||{},i=a.dup?r.DUP_MASK:0,l=a.messageId,d=a.subscriptions,u=a.properties;let h=0;if("number"!=typeof l)return t.emit("error",new Error("Invalid messageId")),!1;h+=2;let p=null;if(5===s){if(p=N(t,u),!p)return!1;h+=p.length}if("object"!=typeof d||!d.length)return t.emit("error",new Error("Invalid subscriptions")),!1;for(let e=0;e<d.length;e+=1){const r=d[e].topic,o=d[e].qos;if("string"!=typeof r)return t.emit("error",new Error("Invalid subscriptions - invalid topic")),!1;if("number"!=typeof o)return t.emit("error",new Error("Invalid subscriptions - invalid qos")),!1;if(5===s){if("boolean"!=typeof(d[e].nl||!1))return t.emit("error",new Error("Invalid subscriptions - invalid No Local")),!1;if("boolean"!=typeof(d[e].rap||!1))return t.emit("error",new Error("Invalid subscriptions - invalid Retain as Published")),!1;const n=d[e].rh||0;if("number"!=typeof n||n>2)return t.emit("error",new Error("Invalid subscriptions - invalid Retain Handling")),!1}h+=n.byteLength(r)+2+1}c("subscribe: writing to stream: %o",r.SUBSCRIBE_HEADER),t.write(r.SUBSCRIBE_HEADER[1][i?1:0][0]),M(t,h),f(t,l),null!==p&&p.write();let g=!0;for(const e of d){const o=e.topic,a=e.qos,i=+e.nl,c=+e.rap,l=e.rh;let d;P(t,o),d=r.SUBSCRIBE_OPTIONS_QOS[a],5===s&&(d|=i?r.SUBSCRIBE_OPTIONS_NL:0,d|=c?r.SUBSCRIBE_OPTIONS_RAP:0,d|=l?r.SUBSCRIBE_OPTIONS_RH[l]:0),g=t.write(n.from([d]))}return g}function S(e,t,o){const s=o?o.protocolVersion:4,a=e||{},i=a.messageId,c=a.granted,l=a.properties;let d=0;if("number"!=typeof i)return t.emit("error",new Error("Invalid messageId")),!1;if(d+=2,"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;d+=1}let u=null;if(5===s){if(u=B(t,l,o,d),!u)return!1;d+=u.length}return t.write(r.SUBACK_HEADER),M(t,d),f(t,i),null!==u&&u.write(),t.write(n.from(c))}function _(e,t,o){const s=o?o.protocolVersion:4,a=e||{},i=a.messageId,c=a.dup?r.DUP_MASK:0,l=a.unsubscriptions,d=a.properties;let u=0;if("number"!=typeof i)return t.emit("error",new Error("Invalid messageId")),!1;if(u+=2,"object"!=typeof l||!l.length)return t.emit("error",new Error("Invalid unsubscriptions")),!1;for(let e=0;e<l.length;e+=1){if("string"!=typeof l[e])return t.emit("error",new Error("Invalid unsubscriptions")),!1;u+=n.byteLength(l[e])+2}let h=null;if(5===s){if(h=N(t,d),!h)return!1;u+=h.length}t.write(r.UNSUBSCRIBE_HEADER[1][c?1:0][0]),M(t,u),f(t,i),null!==h&&h.write();let p=!0;for(let e=0;e<l.length;e++)p=P(t,l[e]);return p}function k(e,t,o){const s=o?o.protocolVersion:4,a=e||{},i=a.messageId,c=a.dup?r.DUP_MASK:0,l=a.granted,d=a.properties,u=a.cmd,h=0;let p=2;if("number"!=typeof i)return t.emit("error",new Error("Invalid messageId")),!1;if(5===s){if("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;p+=1}}let g=null;if(5===s){if(g=B(t,d,o,p),!g)return!1;p+=g.length}return t.write(r.ACKS[u][h][c][0]),M(t,p),f(t,i),null!==g&&g.write(),5===s&&t.write(n.from(l)),!0}function O(e,t,n){return t.write(r.EMPTY[e.cmd])}function T(e,t,o){const s=o?o.protocolVersion:4,a=e||{},i=a.reasonCode,c=a.properties;let l=5===s?1:0,d=null;if(5===s){if(d=B(t,c,o,l),!d)return!1;l+=d.length}return t.write(n.from([r.codes.disconnect<<4])),M(t,l),5===s&&t.write(n.from([i])),null!==d&&d.write(),!0}function A(e,t,o){const s=o?o.protocolVersion:4,a=e||{},i=a.reasonCode,c=a.properties;let l=5===s?1:0;5!==s&&t.emit("error",new Error("Invalid mqtt version for auth packet"));const d=B(t,c,o,l);return!!d&&(l+=d.length,t.write(n.from([r.codes.auth<<4])),M(t,l),t.write(n.from([i])),null!==d&&d.write(),!0)}Object.defineProperty(m,"cacheNumbers",{get:()=>f===U,set(e){e?(l&&0!==Object.keys(l).length||(g=!0),f=U):(g=!1,f=j)}});const E={};function M(e,t){if(t>r.VARBYTEINT_MAX)return e.emit("error",new Error(`Invalid variable byte integer: ${t}`)),!1;let n=E[t];return n||(n=h(t),t<16384&&(E[t]=n)),c("writeVarByteInt: writing to stream: %o",n),e.write(n)}function P(e,t){const r=n.byteLength(t);return f(e,r),c("writeString: %s",t),e.write(t,"utf8")}function R(e,t,n){P(e,t),P(e,n)}function U(e,t){return c("writeNumberCached: number: %d",t),c("writeNumberCached: %o",l[t]),e.write(l[t])}function j(e,t){const n=d(t);return c("writeNumberGenerated: %o",n),e.write(n)}function x(e,t){const n=p(t);return c("write4ByteNumber: %o",n),e.write(n)}function D(e,t){"string"==typeof t?P(e,t):t?(f(e,t.length),e.write(t)):f(e,0)}function N(e,t){if("object"!=typeof t||null!=t.length)return{length:1,write(){F(e,{},0)}};let o=0;function s(t,o){let s=0;switch(r.propertiesTypes[t]){case"byte":if("boolean"!=typeof o)return e.emit("error",new Error(`Invalid ${t}: ${o}`)),!1;s+=2;break;case"int8":if("number"!=typeof o||o<0||o>255)return e.emit("error",new Error(`Invalid ${t}: ${o}`)),!1;s+=2;break;case"binary":if(o&&null===o)return e.emit("error",new Error(`Invalid ${t}: ${o}`)),!1;s+=1+n.byteLength(o)+2;break;case"int16":if("number"!=typeof o||o<0||o>65535)return e.emit("error",new Error(`Invalid ${t}: ${o}`)),!1;s+=3;break;case"int32":if("number"!=typeof o||o<0||o>4294967295)return e.emit("error",new Error(`Invalid ${t}: ${o}`)),!1;s+=5;break;case"var":if("number"!=typeof o||o<0||o>268435455)return e.emit("error",new Error(`Invalid ${t}: ${o}`)),!1;s+=1+n.byteLength(h(o));break;case"string":if("string"!=typeof o)return e.emit("error",new Error(`Invalid ${t}: ${o}`)),!1;s+=3+n.byteLength(o.toString());break;case"pair":if("object"!=typeof o)return e.emit("error",new Error(`Invalid ${t}: ${o}`)),!1;s+=Object.getOwnPropertyNames(o).reduce(((e,t)=>{const r=o[t];return Array.isArray(r)?e+=r.reduce(((e,r)=>e+=3+n.byteLength(t.toString())+2+n.byteLength(r.toString())),0):e+=3+n.byteLength(t.toString())+2+n.byteLength(o[t].toString()),e}),0);break;default:return e.emit("error",new Error(`Invalid property ${t}: ${o}`)),!1}return s}if(t)for(const e in t){let n=0,r=0;const a=t[e];if(Array.isArray(a))for(let t=0;t<a.length;t++){if(r=s(e,a[t]),!r)return!1;n+=r}else{if(r=s(e,a),!r)return!1;n=r}if(!n)return!1;o+=n}return{length:n.byteLength(h(o))+o,write(){F(e,t,o)}}}function B(e,t,n,r){const o=["reasonString","userProperties"],s=n&&n.properties&&n.properties.maximumPacketSize?n.properties.maximumPacketSize:0;let a=N(e,t);if(s)for(;r+a.length>s;){const n=o.shift();if(!n||!t[n])return!1;delete t[n],a=N(e,t)}return a}function q(e,t,o){switch(r.propertiesTypes[t]){case"byte":e.write(n.from([r.properties[t]])),e.write(n.from([+o]));break;case"int8":e.write(n.from([r.properties[t]])),e.write(n.from([o]));break;case"binary":e.write(n.from([r.properties[t]])),D(e,o);break;case"int16":e.write(n.from([r.properties[t]])),f(e,o);break;case"int32":e.write(n.from([r.properties[t]])),x(e,o);break;case"var":e.write(n.from([r.properties[t]])),M(e,o);break;case"string":e.write(n.from([r.properties[t]])),P(e,o);break;case"pair":Object.getOwnPropertyNames(o).forEach((s=>{const a=o[s];Array.isArray(a)?a.forEach((o=>{e.write(n.from([r.properties[t]])),R(e,s.toString(),o.toString())})):(e.write(n.from([r.properties[t]])),R(e,s.toString(),a.toString()))}));break;default:return e.emit("error",new Error(`Invalid property ${t} value: ${o}`)),!1}}function F(e,t,n){M(e,n);for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&null!==t[n]){const r=t[n];if(Array.isArray(r))for(let t=0;t<r.length;t++)q(e,n,r[t]);else q(e,n,r)}}function L(e){return e?e instanceof n?e.length:n.byteLength(e):0}function K(e){return"string"==typeof e||e instanceof n}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,n){var r=1e3,o=60*r,s=60*o,a=24*s,i=7*a,c=365.25*a;function l(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 n=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return n*c;case"weeks":case"week":case"w":return n*i;case"days":case"day":case"d":return n*a;case"hours":case"hour":case"hrs":case"hr":case"h":return n*s;case"minutes":case"minute":case"mins":case"min":case"m":return n*o;case"seconds":case"second":case"secs":case"sec":case"s":return n*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function d(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+"d":t>=s?Math.round(e/s)+"h":t>=o?Math.round(e/o)+"m":t>=r?Math.round(e/r)+"s":e+"ms"}function u(e){var t=Math.abs(e);return t>=a?h(e,t,a,"day"):t>=s?h(e,t,s,"hour"):t>=o?h(e,t,o,"minute"):t>=r?h(e,t,r,"second"):e+" ms"}function h(e,t,n,r){var o=t>=1.5*n;return Math.round(e/n)+" "+r+(o?"s":"")}t.exports=function(e,t){t=t||{};var n=typeof e;if("string"===n&&e.length>0)return l(e);if("number"===n&&isFinite(e))return t.long?u(e):d(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},{}],46:[function(e,t,n){const r=e("./lib/number-allocator.js");t.exports.NumberAllocator=r},{"./lib/number-allocator.js":47}],47:[function(e,t,n){const r=e("js-sdsl").Set,o=e("debug")("number-allocator:trace"),s=e("debug")("number-allocator:error");function a(e,t){this.low=e,this.high=t}function i(e,t){if(!(this instanceof i))return new i(e,t);this.min=e,this.max=t,this.ss=new r([],((e,t)=>e.compare(t))),o("Create"),this.clear()}a.prototype.equals=function(e){return this.low===e.low&&this.high===e.high},a.prototype.compare=function(e){return this.low<e.low&&this.high<e.low?-1:e.low<this.low&&e.high<this.low?1:0},i.prototype.firstVacant=function(){return 0===this.ss.size()?null:this.ss.front().low},i.prototype.alloc=function(){if(0===this.ss.size())return o("alloc():empty"),null;const e=this.ss.front(),t=e.low;return t+1<=e.high?++e.low:this.ss.eraseElementByPos(0),o("alloc():"+t),t},i.prototype.use=function(e){const t=new a(e,e),n=this.ss.lowerBound(t);if(n){if(n.equals(t))return this.ss.eraseElementByValue(n),o("use():"+e),!0;if(n.low>e)return!1;if(n.low===e)return++n.low,o("use():"+e),!0;if(n.high===e)return--n.high,o("use():"+e),!0;const r=n.low;return n.low=e+1,this.ss.insert(new a(r,e-1)),o("use():"+e),!0}return o("use():failed"),!1},i.prototype.free=function(e){if(e<this.min||e>this.max)return void s("free():"+e+" is out of range");const t=new a(e,e),n=this.ss.lowerBound(t);if(n){if(n.low<=e&&e<=n.high)return void s("free():"+e+" has already been vacant");if(n===this.ss.front())e+1===n.low?--n.low:this.ss.insert(t);else{const r=this.ss.reverseLowerBound(t);r.high+1===e?e+1===n.low?(this.ss.eraseElementByValue(r),n.low=r.low):r.high=e:e+1===n.low?n.low=e:this.ss.insert(t)}}else{if(n===this.ss.front())return void this.ss.insert(t);const r=this.ss.reverseLowerBound(t);r.high+1===e?r.high=e:this.ss.insert(t)}o("free():"+e)},i.prototype.clear=function(){o("clear()"),this.ss.clear(),this.ss.insert(new a(this.min,this.max))},i.prototype.intervalCount=function(){return this.ss.size()},i.prototype.dump=function(){console.log("length:"+this.ss.size());for(const e of this.ss)console.log(e)},t.exports=i},{debug:18,"js-sdsl":36}],48:[function(e,t,n){var r=e("wrappy");function o(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function s(e){var t=function(){if(t.called)throw new Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)},n=e.name||"Function wrapped with `once`";return t.onceError=n+" shouldn't be called more than once",t.called=!1,t}t.exports=r(o),t.exports.strict=r(s),o.proto=o((function(){Object.defineProperty(Function.prototype,"once",{value:function(){return o(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return s(this)},configurable:!0})}))},{wrappy:79}],49:[function(e,t,n){(function(e){(function(){function n(t,n,r,o){if("function"!=typeof t)throw new TypeError('"callback" argument must be a function');var s,a,i=arguments.length;switch(i){case 0:case 1:return e.nextTick(t);case 2:return e.nextTick((function(){t.call(null,n)}));case 3:return e.nextTick((function(){t.call(null,n,r)}));case 4:return e.nextTick((function(){t.call(null,n,r,o)}));default:for(s=new Array(i-1),a=0;a<s.length;)s[a++]=arguments[a];return e.nextTick((function(){t.apply(null,s)}))}}void 0===e||!e.version||0===e.version.indexOf("v0.")||0===e.version.indexOf("v1.")&&0!==e.version.indexOf("v1.8.")?t.exports={nextTick:n}:t.exports=e}).call(this)}).call(this,e("_process"))},{_process:50}],50:[function(e,t,n){var r,o,s=t.exports={};function a(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}function c(e){if(r===setTimeout)return setTimeout(e,0);if((r===a||!r)&&setTimeout)return r=setTimeout,setTimeout(e,0);try{return r(e,0)}catch(t){try{return r.call(null,e,0)}catch(t){return r.call(this,e,0)}}}function l(e){if(o===clearTimeout)return clearTimeout(e);if((o===i||!o)&&clearTimeout)return o=clearTimeout,clearTimeout(e);try{return o(e)}catch(t){try{return o.call(null,e)}catch(t){return o.call(this,e)}}}!function(){try{r="function"==typeof setTimeout?setTimeout:a}catch(e){r=a}try{o="function"==typeof clearTimeout?clearTimeout:i}catch(e){o=i}}();var d,u=[],h=!1,p=-1;function f(){h&&d&&(h=!1,d.length?u=d.concat(u):p=-1,u.length&&g())}function g(){if(!h){var e=c(f);h=!0;for(var t=u.length;t;){for(d=u,u=[];++p<t;)d&&d[p].run();p=-1,t=u.length}d=null,h=!1,l(e)}}function m(e,t){this.fun=e,this.array=t}function y(){}s.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];u.push(new m(e,t)),1!==u.length||h||c(g)},m.prototype.run=function(){this.fun.apply(null,this.array)},s.title="browser",s.browser=!0,s.env={},s.argv=[],s.version="",s.versions={},s.on=y,s.addListener=y,s.once=y,s.off=y,s.removeListener=y,s.removeAllListeners=y,s.emit=y,s.prependListener=y,s.prependOnceListener=y,s.listeners=function(e){return[]},s.binding=function(e){throw new Error("process.binding is not supported")},s.cwd=function(){return"/"},s.chdir=function(e){throw new Error("process.chdir is not supported")},s.umask=function(){return 0}},{}],51:[function(e,t,n){(function(e){(function(){!function(r){var o="object"==typeof n&&n&&!n.nodeType&&n,s="object"==typeof t&&t&&!t.nodeType&&t,a="object"==typeof e&&e;a.global!==a&&a.window!==a&&a.self!==a||(r=a);var i,c,l=2147483647,d=36,u=1,h=26,p=38,f=700,g=72,m=128,y="-",v=/^xn--/,b=/[^\x20-\x7E]/,w=/[\x2E\u3002\uFF0E\uFF61]/g,C={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},I=d-u,S=Math.floor,_=String.fromCharCode;function k(e){throw new RangeError(C[e])}function O(e,t){for(var n=e.length,r=[];n--;)r[n]=t(e[n]);return r}function T(e,t){var n=e.split("@"),r="";return n.length>1&&(r=n[0]+"@",e=n[1]),r+O((e=e.replace(w,".")).split("."),t).join(".")}function A(e){for(var t,n,r=[],o=0,s=e.length;o<s;)(t=e.charCodeAt(o++))>=55296&&t<=56319&&o<s?56320==(64512&(n=e.charCodeAt(o++)))?r.push(((1023&t)<<10)+(1023&n)+65536):(r.push(t),o--):r.push(t);return r}function E(e){return O(e,(function(e){var t="";return e>65535&&(t+=_((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=_(e)})).join("")}function M(e){return e-48<10?e-22:e-65<26?e-65:e-97<26?e-97:d}function P(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function R(e,t,n){var r=0;for(e=n?S(e/f):e>>1,e+=S(e/t);e>I*h>>1;r+=d)e=S(e/I);return S(r+(I+1)*e/(e+p))}function U(e){var t,n,r,o,s,a,i,c,p,f,v=[],b=e.length,w=0,C=m,I=g;for((n=e.lastIndexOf(y))<0&&(n=0),r=0;r<n;++r)e.charCodeAt(r)>=128&&k("not-basic"),v.push(e.charCodeAt(r));for(o=n>0?n+1:0;o<b;){for(s=w,a=1,i=d;o>=b&&k("invalid-input"),((c=M(e.charCodeAt(o++)))>=d||c>S((l-w)/a))&&k("overflow"),w+=c*a,!(c<(p=i<=I?u:i>=I+h?h:i-I));i+=d)a>S(l/(f=d-p))&&k("overflow"),a*=f;I=R(w-s,t=v.length+1,0==s),S(w/t)>l-C&&k("overflow"),C+=S(w/t),w%=t,v.splice(w++,0,C)}return E(v)}function j(e){var t,n,r,o,s,a,i,c,p,f,v,b,w,C,I,O=[];for(b=(e=A(e)).length,t=m,n=0,s=g,a=0;a<b;++a)(v=e[a])<128&&O.push(_(v));for(r=o=O.length,o&&O.push(y);r<b;){for(i=l,a=0;a<b;++a)(v=e[a])>=t&&v<i&&(i=v);for(i-t>S((l-n)/(w=r+1))&&k("overflow"),n+=(i-t)*w,t=i,a=0;a<b;++a)if((v=e[a])<t&&++n>l&&k("overflow"),v==t){for(c=n,p=d;!(c<(f=p<=s?u:p>=s+h?h:p-s));p+=d)I=c-f,C=d-f,O.push(_(P(f+I%C,0))),c=S(I/C);O.push(_(P(c,0))),s=R(n,w,r==o),n=0,++r}++n,++t}return O.join("")}function x(e){return T(e,(function(e){return v.test(e)?U(e.slice(4).toLowerCase()):e}))}function D(e){return T(e,(function(e){return b.test(e)?"xn--"+j(e):e}))}if(i={version:"1.4.1",ucs2:{decode:A,encode:E},decode:U,encode:j,toASCII:D,toUnicode:x},o&&s)if(t.exports==o)s.exports=i;else for(c in i)i.hasOwnProperty(c)&&(o[c]=i[c]);else r.punycode=i}(this)}).call(this)}).call(this,void 0!==At?At:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],52:[function(e,t,n){function r(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.exports=function(e,t,n,s){t=t||"&",n=n||"=";var a={};if("string"!=typeof e||0===e.length)return a;var i=/\+/g;e=e.split(t);var c=1e3;s&&"number"==typeof s.maxKeys&&(c=s.maxKeys);var l=e.length;c>0&&l>c&&(l=c);for(var d=0;d<l;++d){var u,h,p,f,g=e[d].replace(i,"%20"),m=g.indexOf(n);m>=0?(u=g.substr(0,m),h=g.substr(m+1)):(u=g,h=""),p=decodeURIComponent(u),f=decodeURIComponent(h),r(a,p)?o(a[p])?a[p].push(f):a[p]=[a[p],f]:a[p]=f}return a};var o=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],53:[function(e,t,n){var r=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,n,i){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"==typeof e?s(a(e),(function(a){var i=encodeURIComponent(r(a))+n;return o(e[a])?s(e[a],(function(e){return i+encodeURIComponent(r(e))})).join(t):i+encodeURIComponent(r(e[a]))})).join(t):i?encodeURIComponent(r(i))+n+encodeURIComponent(r(e)):""};var o=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function s(e,t){if(e.map)return e.map(t);for(var n=[],r=0;r<e.length;r++)n.push(t(e[r],r));return n}var a=Object.keys||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t}},{}],54:[function(e,t,n){n.decode=n.parse=e("./decode"),n.encode=n.stringify=e("./encode")},{"./decode":52,"./encode":53}],55:[function(e,t,n){function r(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}var o={};function s(e,t,n){function s(e,n,r){return"string"==typeof t?t:t(e,n,r)}n||(n=Error);var a=function(e){function t(t,n,r){return e.call(this,s(t,n,r))||this}return r(t,e),t}(n);a.prototype.name=n.name,a.prototype.code=e,o[e]=a}function a(e,t){if(Array.isArray(e)){var n=e.length;return e=e.map((function(e){return String(e)})),n>2?"one of ".concat(t," ").concat(e.slice(0,n-1).join(", "),", or ")+e[n-1]:2===n?"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 i(e,t,n){return e.substr(!n||n<0?0:+n,t.length)===t}function c(e,t,n){return(void 0===n||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}function l(e,t,n){return"number"!=typeof n&&(n=0),!(n+t.length>e.length)&&-1!==e.indexOf(t,n)}s("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError),s("ERR_INVALID_ARG_TYPE",(function(e,t,n){var r,o;if("string"==typeof t&&i(t,"not ")?(r="must not be",t=t.replace(/^not /,"")):r="must be",c(e," argument"))o="The ".concat(e," ").concat(r," ").concat(a(t,"type"));else{var s=l(e,".")?"property":"argument";o='The "'.concat(e,'" ').concat(s," ").concat(r," ").concat(a(t,"type"))}return o+=". Received type ".concat(typeof n)}),TypeError),s("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),s("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"})),s("ERR_STREAM_PREMATURE_CLOSE","Premature close"),s("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"})),s("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),s("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),s("ERR_STREAM_WRITE_AFTER_END","write after end"),s("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),s("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError),s("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),t.exports.codes=o},{}],56:[function(e,t,n){(function(n){(function(){var r=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=l;var o=e("./_stream_readable"),s=e("./_stream_writable");e("inherits")(l,o);for(var a=r(s.prototype),i=0;i<a.length;i++){var c=a[i];l.prototype[c]||(l.prototype[c]=s.prototype[c])}function l(e){if(!(this instanceof l))return new l(e);o.call(this,e),s.call(this,e),this.allowHalfOpen=!0,e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",d)))}function d(){this._writableState.ended||n.nextTick(u,this)}function u(e){e.end()}Object.defineProperty(l.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(l.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(l.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(l.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,n){t.exports=o;var r=e("./_stream_transform");function o(e){if(!(this instanceof o))return new o(e);r.call(this,e)}e("inherits")(o,r),o.prototype._transform=function(e,t,n){n(null,e)}},{"./_stream_transform":59,inherits:24}],58:[function(e,t,n){(function(n,r){(function(){var o;t.exports=A,A.ReadableState=T,e("events").EventEmitter;var s=function(e,t){return e.listeners(t).length},a=e("./internal/streams/stream"),i=e("buffer").Buffer,c=r.Uint8Array||function(){};function l(e){return i.from(e)}function d(e){return i.isBuffer(e)||e instanceof c}var u,h=e("util");u=h&&h.debuglog?h.debuglog("stream"):function(){};var p,f,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,C=b.ERR_STREAM_PUSH_AFTER_EOF,I=b.ERR_METHOD_NOT_IMPLEMENTED,S=b.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;e("inherits")(A,a);var _=y.errorOrDestroy,k=["error","close","destroy","pause","resume"];function O(e,t,n){if("function"==typeof e.prependListener)return e.prependListener(t,n);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}function T(t,n,r){o=o||e("./_stream_duplex"),t=t||{},"boolean"!=typeof r&&(r=n instanceof o),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=v(this,t,"readableHighWaterMark",r),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&&(p||(p=e("string_decoder/").StringDecoder),this.decoder=new p(t.encoding),this.encoding=t.encoding)}function A(t){if(o=o||e("./_stream_duplex"),!(this instanceof A))return new A(t);var n=this instanceof o;this._readableState=new T(t,this,n),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),a.call(this)}function E(e,t,n,r,o){u("readableAddChunk",t);var s,a=e._readableState;if(null===t)a.reading=!1,x(e,a);else if(o||(s=P(a,t)),s)_(e,s);else if(a.objectMode||t&&t.length>0)if("string"==typeof t||a.objectMode||Object.getPrototypeOf(t)===i.prototype||(t=l(t)),r)a.endEmitted?_(e,new S):M(e,a,t,!0);else if(a.ended)_(e,new C);else{if(a.destroyed)return!1;a.reading=!1,a.decoder&&!n?(t=a.decoder.write(t),a.objectMode||0!==t.length?M(e,a,t,!1):B(e,a)):M(e,a,t,!1)}else r||(a.reading=!1,B(e,a));return!a.ended&&(a.length<a.highWaterMark||0===a.length)}function M(e,t,n,r){t.flowing&&0===t.length&&!t.sync?(t.awaitDrain=0,e.emit("data",n)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&D(e)),B(e,t)}function P(e,t){var n;return d(t)||"string"==typeof t||void 0===t||e.objectMode||(n=new w("chunk",["string","Buffer","Uint8Array"],t)),n}Object.defineProperty(A.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),A.prototype.destroy=y.destroy,A.prototype._undestroy=y.undestroy,A.prototype._destroy=function(e,t){t(e)},A.prototype.push=function(e,t){var n,r=this._readableState;return r.objectMode?n=!0:"string"==typeof e&&((t=t||r.defaultEncoding)!==r.encoding&&(e=i.from(e,t),t=""),n=!0),E(this,e,t,!1,n)},A.prototype.unshift=function(e){return E(this,e,null,!0,!1)},A.prototype.isPaused=function(){return!1===this._readableState.flowing},A.prototype.setEncoding=function(t){p||(p=e("string_decoder/").StringDecoder);var n=new p(t);this._readableState.decoder=n,this._readableState.encoding=this._readableState.decoder.encoding;for(var r=this._readableState.buffer.head,o="";null!==r;)o+=n.write(r.data),r=r.next;return this._readableState.buffer.clear(),""!==o&&this._readableState.buffer.push(o),this._readableState.length=o.length,this};var R=1073741824;function U(e){return e>=R?e=R:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function j(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=U(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function x(e,t){if(u("onEofChunk"),!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?D(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,N(e)))}}function D(e){var t=e._readableState;u("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(u("emitReadable",t.flowing),t.emittedReadable=!0,n.nextTick(N,e))}function N(e){var t=e._readableState;u("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,Q(e)}function B(e,t){t.readingMore||(t.readingMore=!0,n.nextTick(q,e,t))}function q(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&0===t.length);){var n=t.length;if(u("maybeReadMore read 0"),e.read(0),n===t.length)break}t.readingMore=!1}function F(e){return function(){var t=e._readableState;u("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&s(e,"data")&&(t.flowing=!0,Q(e))}}function L(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 K(e){u("readable nexttick read 0"),e.read(0)}function $(e,t){t.resumeScheduled||(t.resumeScheduled=!0,n.nextTick(z,e,t))}function z(e,t){u("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),Q(e),t.flowing&&!t.reading&&e.read(0)}function Q(e){var t=e._readableState;for(u("flow",t.flowing);t.flowing&&null!==e.read(););}function V(e,t){return 0===t.length?null:(t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n);var n}function H(e){var t=e._readableState;u("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(W,t,e))}function W(e,t){if(u("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}function J(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}A.prototype.read=function(e){u("read",e),e=parseInt(e,10);var t=this._readableState,n=e;if(0!==e&&(t.emittedReadable=!1),0===e&&t.needReadable&&((0!==t.highWaterMark?t.length>=t.highWaterMark:t.length>0)||t.ended))return u("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?H(this):D(this),null;if(0===(e=j(e,t))&&t.ended)return 0===t.length&&H(this),null;var r,o=t.needReadable;return u("need readable",o),(0===t.length||t.length-e<t.highWaterMark)&&u("length less than watermark",o=!0),t.ended||t.reading?u("reading or ended",o=!1):o&&(u("do read"),t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=j(n,t))),null===(r=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),n!==e&&t.ended&&H(this)),null!==r&&this.emit("data",r),r},A.prototype._read=function(e){_(this,new I("_read()"))},A.prototype.pipe=function(e,t){var r=this,o=this._readableState;switch(o.pipesCount){case 0:o.pipes=e;break;case 1:o.pipes=[o.pipes,e];break;default:o.pipes.push(e)}o.pipesCount+=1,u("pipe count=%d opts=%j",o.pipesCount,t);var a=t&&!1===t.end||e===n.stdout||e===n.stderr?y:c;function i(e,t){u("onunpipe"),e===r&&t&&!1===t.hasUnpiped&&(t.hasUnpiped=!0,h())}function c(){u("onend"),e.end()}o.endEmitted?n.nextTick(a):r.once("end",a),e.on("unpipe",i);var l=F(r);e.on("drain",l);var d=!1;function h(){u("cleanup"),e.removeListener("close",g),e.removeListener("finish",m),e.removeListener("drain",l),e.removeListener("error",f),e.removeListener("unpipe",i),r.removeListener("end",c),r.removeListener("end",y),r.removeListener("data",p),d=!0,!o.awaitDrain||e._writableState&&!e._writableState.needDrain||l()}function p(t){u("ondata");var n=e.write(t);u("dest.write",n),!1===n&&((1===o.pipesCount&&o.pipes===e||o.pipesCount>1&&-1!==J(o.pipes,e))&&!d&&(u("false write response, pause",o.awaitDrain),o.awaitDrain++),r.pause())}function f(t){u("onerror",t),y(),e.removeListener("error",f),0===s(e,"error")&&_(e,t)}function g(){e.removeListener("finish",m),y()}function m(){u("onfinish"),e.removeListener("close",g),y()}function y(){u("unpipe"),r.unpipe(e)}return r.on("data",p),O(e,"error",f),e.once("close",g),e.once("finish",m),e.emit("pipe",r),o.flowing||(u("pipe resume"),r.resume()),e},A.prototype.unpipe=function(e){var t=this._readableState,n={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,n)),this;if(!e){var r=t.pipes,o=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var s=0;s<o;s++)r[s].emit("unpipe",this,{hasUnpiped:!1});return this}var a=J(t.pipes,e);return-1===a||(t.pipes.splice(a,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,n)),this},A.prototype.on=function(e,t){var r=a.prototype.on.call(this,e,t),o=this._readableState;return"data"===e?(o.readableListening=this.listenerCount("readable")>0,!1!==o.flowing&&this.resume()):"readable"===e&&(o.endEmitted||o.readableListening||(o.readableListening=o.needReadable=!0,o.flowing=!1,o.emittedReadable=!1,u("on readable",o.length,o.reading),o.length?D(this):o.reading||n.nextTick(K,this))),r},A.prototype.addListener=A.prototype.on,A.prototype.removeListener=function(e,t){var r=a.prototype.removeListener.call(this,e,t);return"readable"===e&&n.nextTick(L,this),r},A.prototype.removeAllListeners=function(e){var t=a.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||n.nextTick(L,this),t},A.prototype.resume=function(){var e=this._readableState;return e.flowing||(u("resume"),e.flowing=!e.readableListening,$(this,e)),e.paused=!1,this},A.prototype.pause=function(){return u("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(u("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},A.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var o in e.on("end",(function(){if(u("wrapped end"),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(o){u("wrapped data"),n.decoder&&(o=n.decoder.write(o)),n.objectMode&&null==o||(n.objectMode||o&&o.length)&&(t.push(o)||(r=!0,e.pause()))})),e)void 0===this[o]&&"function"==typeof e[o]&&(this[o]=function(t){return function(){return e[t].apply(e,arguments)}}(o));for(var s=0;s<k.length;s++)e.on(k[s],this.emit.bind(this,k[s]));return this._read=function(t){u("wrapped _read",t),r&&(r=!1,e.resume())},this},"function"==typeof Symbol&&(A.prototype[Symbol.asyncIterator]=function(){return void 0===f&&(f=e("./internal/streams/async_iterator")),f(this)}),Object.defineProperty(A.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(A.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(A.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),A._fromList=V,Object.defineProperty(A.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(A.from=function(t,n){return void 0===g&&(g=e("./internal/streams/from")),g(A,t,n)})}).call(this)}).call(this,e("_process"),void 0!==At?At:"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,n){t.exports=d;var r=e("../errors").codes,o=r.ERR_METHOD_NOT_IMPLEMENTED,s=r.ERR_MULTIPLE_CALLBACK,a=r.ERR_TRANSFORM_ALREADY_TRANSFORMING,i=r.ERR_TRANSFORM_WITH_LENGTH_0,c=e("./_stream_duplex");function l(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(null===r)return this.emit("error",new s);n.writechunk=null,n.writecb=null,null!=t&&this.push(t),r(e);var o=this._readableState;o.reading=!1,(o.needReadable||o.length<o.highWaterMark)&&this._read(o.highWaterMark)}function d(e){if(!(this instanceof d))return new d(e);c.call(this,e),this._transformState={afterTransform:l.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),this.on("prefinish",u)}function u(){var e=this;"function"!=typeof this._flush||this._readableState.destroyed?h(this,null,null):this._flush((function(t,n){h(e,t,n)}))}function h(e,t,n){if(t)return e.emit("error",t);if(null!=n&&e.push(n),e._writableState.length)throw new i;if(e._transformState.transforming)throw new a;return e.push(null)}e("inherits")(d,c),d.prototype.push=function(e,t){return this._transformState.needTransform=!1,c.prototype.push.call(this,e,t)},d.prototype._transform=function(e,t,n){n(new o("_transform()"))},d.prototype._write=function(e,t,n){var r=this._transformState;if(r.writecb=n,r.writechunk=e,r.writeencoding=t,!r.transforming){var o=this._readableState;(r.needTransform||o.needReadable||o.length<o.highWaterMark)&&this._read(o.highWaterMark)}},d.prototype._read=function(e){var t=this._transformState;null===t.writechunk||t.transforming?t.needTransform=!0:(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform))},d.prototype._destroy=function(e,t){c.prototype._destroy.call(this,e,(function(e){t(e)}))}},{"../errors":55,"./_stream_duplex":56,inherits:24}],60:[function(e,t,n){(function(n,r){(function(){function o(e){var t=this;this.next=null,this.entry=null,this.finish=function(){z(t,e)}}var s;t.exports=T,T.WritableState=O;var a={deprecate:e("util-deprecate")},i=e("./internal/streams/stream"),c=e("buffer").Buffer,l=r.Uint8Array||function(){};function d(e){return c.from(e)}function u(e){return c.isBuffer(e)||e instanceof l}var h,p=e("./internal/streams/destroy"),f=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,C=g.ERR_STREAM_NULL_VALUES,I=g.ERR_STREAM_WRITE_AFTER_END,S=g.ERR_UNKNOWN_ENCODING,_=p.errorOrDestroy;function k(){}function O(t,n,r){s=s||e("./_stream_duplex"),t=t||{},"boolean"!=typeof r&&(r=n instanceof s),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=f(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var a=!1===t.decodeStrings;this.decodeStrings=!a,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){x(n,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 o(this)}function T(t){var n=this instanceof(s=s||e("./_stream_duplex"));if(!n&&!h.call(T,this))return new T(t);this._writableState=new O(t,this,n),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)),i.call(this)}function A(e,t){var r=new I;_(e,r),n.nextTick(t,r)}function E(e,t,r,o){var s;return null===r?s=new C:"string"==typeof r||t.objectMode||(s=new m("chunk",["string","Buffer"],r)),!s||(_(e,s),n.nextTick(o,s),!1)}function M(e,t,n){return e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=c.from(t,n)),t}function P(e,t,n,r,o,s){if(!n){var a=M(t,r,o);r!==a&&(n=!0,o="buffer",r=a)}var i=t.objectMode?1:r.length;t.length+=i;var c=t.length<t.highWaterMark;if(c||(t.needDrain=!0),t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:o,isBuf:n,callback:s,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else R(e,t,!1,i,r,o,s);return c}function R(e,t,n,r,o,s,a){t.writelen=r,t.writecb=a,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new w("write")):n?e._writev(o,t.onwrite):e._write(o,s,t.onwrite),t.sync=!1}function U(e,t,r,o,s){--t.pendingcb,r?(n.nextTick(s,o),n.nextTick(K,e,t),e._writableState.errorEmitted=!0,_(e,o)):(s(o),e._writableState.errorEmitted=!0,_(e,o),K(e,t))}function j(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function x(e,t){var r=e._writableState,o=r.sync,s=r.writecb;if("function"!=typeof s)throw new v;if(j(r),t)U(e,r,o,t,s);else{var a=q(r)||e.destroyed;a||r.corked||r.bufferProcessing||!r.bufferedRequest||B(e,r),o?n.nextTick(D,e,r,a,s):D(e,r,a,s)}}function D(e,t,n,r){n||N(e,t),t.pendingcb--,r(),K(e,t)}function N(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}function B(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var r=t.bufferedRequestCount,s=new Array(r),a=t.corkedRequestsFree;a.entry=n;for(var i=0,c=!0;n;)s[i]=n,n.isBuf||(c=!1),n=n.next,i+=1;s.allBuffers=c,R(e,t,!0,t.length,s,"",a.finish),t.pendingcb++,t.lastBufferedRequest=null,a.next?(t.corkedRequestsFree=a.next,a.next=null):t.corkedRequestsFree=new o(t),t.bufferedRequestCount=0}else{for(;n;){var l=n.chunk,d=n.encoding,u=n.callback;if(R(e,t,!1,t.objectMode?1:l.length,l,d,u),n=n.next,t.bufferedRequestCount--,t.writing)break}null===n&&(t.lastBufferedRequest=null)}t.bufferedRequest=n,t.bufferProcessing=!1}function q(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function F(e,t){e._final((function(n){t.pendingcb--,n&&_(e,n),t.prefinished=!0,e.emit("prefinish"),K(e,t)}))}function L(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.pendingcb++,t.finalCalled=!0,n.nextTick(F,e,t)))}function K(e,t){var n=q(t);if(n&&(L(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"),t.autoDestroy))){var r=e._readableState;(!r||r.autoDestroy&&r.endEmitted)&&e.destroy()}return n}function $(e,t,r){t.ending=!0,K(e,t),r&&(t.finished?n.nextTick(r):e.once("finish",r)),t.ended=!0,e.writable=!1}function z(e,t,n){var r=e.entry;for(e.entry=null;r;){var o=r.callback;t.pendingcb--,o(n),r=r.next}t.corkedRequestsFree.next=e}e("inherits")(T,i),O.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(O.prototype,"buffer",{get:a.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(h=Function.prototype[Symbol.hasInstance],Object.defineProperty(T,Symbol.hasInstance,{value:function(e){return!!h.call(this,e)||this===T&&e&&e._writableState instanceof O}})):h=function(e){return e instanceof this},T.prototype.pipe=function(){_(this,new b)},T.prototype.write=function(e,t,n){var r=this._writableState,o=!1,s=!r.objectMode&&u(e);return s&&!c.isBuffer(e)&&(e=d(e)),"function"==typeof t&&(n=t,t=null),s?t="buffer":t||(t=r.defaultEncoding),"function"!=typeof n&&(n=k),r.ending?A(this,n):(s||E(this,r,e,n))&&(r.pendingcb++,o=P(this,r,s,e,t,n)),o},T.prototype.cork=function(){this._writableState.corked++},T.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.bufferProcessing||!e.bufferedRequest||B(this,e))},T.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(T.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(T.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),T.prototype._write=function(e,t,n){n(new y("_write()"))},T.prototype._writev=null,T.prototype.end=function(e,t,n){var r=this._writableState;return"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||$(this,r,n),this},Object.defineProperty(T.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(T.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),T.prototype.destroy=p.destroy,T.prototype._undestroy=p.undestroy,T.prototype._destroy=function(e,t){t(e)}}).call(this)}).call(this,e("_process"),void 0!==At?At:"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,n){(function(n){(function(){var r;function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var s=e("./end-of-stream"),a=Symbol("lastResolve"),i=Symbol("lastReject"),c=Symbol("error"),l=Symbol("ended"),d=Symbol("lastPromise"),u=Symbol("handlePromise"),h=Symbol("stream");function p(e,t){return{value:e,done:t}}function f(e){var t=e[a];if(null!==t){var n=e[h].read();null!==n&&(e[d]=null,e[a]=null,e[i]=null,t(p(n,!1)))}}function g(e){n.nextTick(f,e)}function m(e,t){return function(n,r){e.then((function(){t[l]?n(p(void 0,!0)):t[u](n,r)}),r)}}var y=Object.getPrototypeOf((function(){})),v=Object.setPrototypeOf((o(r={get stream(){return this[h]},next:function(){var e=this,t=this[c];if(null!==t)return Promise.reject(t);if(this[l])return Promise.resolve(p(void 0,!0));if(this[h].destroyed)return new Promise((function(t,r){n.nextTick((function(){e[c]?r(e[c]):t(p(void 0,!0))}))}));var r,o=this[d];if(o)r=new Promise(m(o,this));else{var s=this[h].read();if(null!==s)return Promise.resolve(p(s,!1));r=new Promise(this[u])}return this[d]=r,r}},Symbol.asyncIterator,(function(){return this})),o(r,"return",(function(){var e=this;return new Promise((function(t,n){e[h].destroy(null,(function(e){e?n(e):t(p(void 0,!0))}))}))})),r),y),b=function(e){var t,n=Object.create(v,(o(t={},h,{value:e,writable:!0}),o(t,a,{value:null,writable:!0}),o(t,i,{value:null,writable:!0}),o(t,c,{value:null,writable:!0}),o(t,l,{value:e._readableState.endEmitted,writable:!0}),o(t,u,{value:function(e,t){var r=n[h].read();r?(n[d]=null,n[a]=null,n[i]=null,e(p(r,!1))):(n[a]=e,n[i]=t)},writable:!0}),t));return n[d]=null,s(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=n[i];return null!==t&&(n[d]=null,n[a]=null,n[i]=null,t(e)),void(n[c]=e)}var r=n[a];null!==r&&(n[d]=null,n[a]=null,n[i]=null,r(p(void 0,!0))),n[l]=!0})),e.on("readable",g.bind(null,n)),n};t.exports=b}).call(this)}).call(this,e("_process"))},{"./end-of-stream":64,_process:50}],62:[function(e,t,n){function r(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function o(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?r(Object(n),!0).forEach((function(t){s(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function c(e,t,n){return t&&i(e.prototype,t),n&&i(e,n),e}var l=e("buffer").Buffer,d=e("util").inspect,u=d&&d.custom||"inspect";function h(e,t,n){l.prototype.copy.call(e,t,n)}t.exports=function(){function e(){a(this,e),this.head=null,this.tail=null,this.length=0}return c(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,n=""+t.data;t=t.next;)n+=e+t.data;return n}},{key:"concat",value:function(e){if(0===this.length)return l.alloc(0);for(var t=l.allocUnsafe(e>>>0),n=this.head,r=0;n;)h(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:"consume",value:function(e,t){var n;return e<this.head.data.length?(n=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):n=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),n}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(e){var t=this.head,n=1,r=t.data;for(e-=r.length;t=t.next;){var o=t.data,s=e>o.length?o.length:e;if(s===o.length?r+=o:r+=o.slice(0,e),0==(e-=s)){s===o.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=o.slice(s));break}++n}return this.length-=n,r}},{key:"_getBuffer",value:function(e){var t=l.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var o=n.data,s=e>o.length?o.length:e;if(o.copy(t,t.length-e,0,s),0==(e-=s)){s===o.length?(++r,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=o.slice(s));break}++r}return this.length-=r,t}},{key:u,value:function(e,t){return d(this,o({},t,{depth:0,customInspect:!1}))}}]),e}()},{buffer:17,util:16}],63:[function(e,t,n){(function(e){(function(){function n(t,n){var s=this,i=this._readableState&&this._readableState.destroyed,c=this._writableState&&this._writableState.destroyed;return i||c?(n?n(t):t&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,e.nextTick(a,this,t)):e.nextTick(a,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,(function(t){!n&&t?s._writableState?s._writableState.errorEmitted?e.nextTick(o,s):(s._writableState.errorEmitted=!0,e.nextTick(r,s,t)):e.nextTick(r,s,t):n?(e.nextTick(o,s),n(t)):e.nextTick(o,s)})),this)}function r(e,t){a(e,t),o(e)}function o(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function s(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function a(e,t){e.emit("error",t)}function i(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit("error",t)}t.exports={destroy:n,undestroy:s,errorOrDestroy:i}}).call(this)}).call(this,e("_process"))},{_process:50}],64:[function(e,t,n){var r=e("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;function o(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];e.apply(this,r)}}}function s(){}function a(e){return e.setHeader&&"function"==typeof e.abort}function i(e,t,n){if("function"==typeof t)return i(e,null,t);t||(t={}),n=o(n||s);var c=t.readable||!1!==t.readable&&e.readable,l=t.writable||!1!==t.writable&&e.writable,d=function(){e.writable||h()},u=e._writableState&&e._writableState.finished,h=function(){l=!1,u=!0,c||n.call(e)},p=e._readableState&&e._readableState.endEmitted,f=function(){c=!1,p=!0,l||n.call(e)},g=function(t){n.call(e,t)},m=function(){var t;return c&&!p?(e._readableState&&e._readableState.ended||(t=new r),n.call(e,t)):l&&!u?(e._writableState&&e._writableState.ended||(t=new r),n.call(e,t)):void 0},y=function(){e.req.on("finish",h)};return a(e)?(e.on("complete",h),e.on("abort",m),e.req?y():e.on("request",y)):l&&!e._writableState&&(e.on("end",d),e.on("close",d)),e.on("end",f),e.on("finish",h),!1!==t.error&&e.on("error",g),e.on("close",m),function(){e.removeListener("complete",h),e.removeListener("abort",m),e.removeListener("request",y),e.req&&e.req.removeListener("finish",h),e.removeListener("end",d),e.removeListener("close",d),e.removeListener("finish",h),e.removeListener("end",f),e.removeListener("error",g),e.removeListener("close",m)}}t.exports=i},{"../../../errors":55}],65:[function(e,t,n){t.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],66:[function(e,t,n){var r;function o(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var s=e("../../../errors").codes,a=s.ERR_MISSING_ARGS,i=s.ERR_STREAM_DESTROYED;function c(e){if(e)throw e}function l(e){return e.setHeader&&"function"==typeof e.abort}function d(t,n,s,a){a=o(a);var c=!1;t.on("close",(function(){c=!0})),void 0===r&&(r=e("./end-of-stream")),r(t,{readable:n,writable:s},(function(e){if(e)return a(e);c=!0,a()}));var d=!1;return function(e){if(!c&&!d)return d=!0,l(t)?t.abort():"function"==typeof t.destroy?t.destroy():void a(e||new i("pipe"))}}function u(e){e()}function h(e,t){return e.pipe(t)}function p(e){return e.length?"function"!=typeof e[e.length-1]?c:e.pop():c}function f(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];var r,o=p(t);if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new a("streams");var s=t.map((function(e,n){var a=n<t.length-1;return d(e,a,n>0,(function(e){r||(r=e),e&&s.forEach(u),a||(s.forEach(u),o(r))}))}));return t.reduce(h)}t.exports=f},{"../../../errors":55,"./end-of-stream":64}],67:[function(e,t,n){var r=e("../../../errors").codes.ERR_INVALID_OPT_VALUE;function o(e,t,n){return null!=e.highWaterMark?e.highWaterMark:t?e[n]:null}function s(e,t,n,s){var a=o(t,s,n);if(null!=a){if(!isFinite(a)||Math.floor(a)!==a||a<0)throw new r(s?n:"highWaterMark",a);return Math.floor(a)}return e.objectMode?16:16384}t.exports={getHighWaterMark:s}},{"../../../errors":55}],68:[function(e,t,n){t.exports=e("events").EventEmitter},{events:22}],69:[function(e,t,n){(n=t.exports=e("./lib/_stream_readable.js")).Stream=n,n.Readable=n,n.Writable=e("./lib/_stream_writable.js"),n.Duplex=e("./lib/_stream_duplex.js"),n.Transform=e("./lib/_stream_transform.js"),n.PassThrough=e("./lib/_stream_passthrough.js"),n.finished=e("./lib/internal/streams/end-of-stream.js"),n.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,n){function r(e,t,n){var r=this;this._callback=e,this._args=n,this._interval=setInterval(e,t,this._args),this.reschedule=function(e){e||(e=r._interval),r._interval&&clearInterval(r._interval),r._interval=setInterval(r._callback,e,r._args)},this.clear=function(){r._interval&&(clearInterval(r._interval),r._interval=void 0)},this.destroy=function(){r._interval&&clearInterval(r._interval),r._callback=void 0,r._interval=void 0,r._args=void 0}}function o(){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 r(arguments[0],arguments[1],e)}t.exports=o},{}],71:[function(e,t,n){t.exports=e("./index.js")()},{"./index.js":72}],72:[function(e,t,n){(function(e){(function(){function n(t){return t instanceof e?e.from(t):new t.constructor(t.buffer.slice(),t.byteOffset,t.length)}function r(e){return(e=e||{}).circles?o(e):e.proto?s:r;function t(e,t){for(var r=Object.keys(e),o=new Array(r.length),s=0;s<r.length;s++){var a=r[s],i=e[a];"object"!=typeof i||null===i?o[a]=i:i instanceof Date?o[a]=new Date(i):ArrayBuffer.isView(i)?o[a]=n(i):o[a]=t(i)}return o}function r(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return t(e,r);if(e instanceof Map)return new Map(t(Array.from(e),r));if(e instanceof Set)return new Set(t(Array.from(e),r));var o={};for(var s in e)if(!1!==Object.hasOwnProperty.call(e,s)){var a=e[s];"object"!=typeof a||null===a?o[s]=a:a instanceof Date?o[s]=new Date(a):a instanceof Map?o[s]=new Map(t(Array.from(a),r)):a instanceof Set?o[s]=new Set(t(Array.from(a),r)):ArrayBuffer.isView(a)?o[s]=n(a):o[s]=r(a)}return o}function s(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return t(e,s);if(e instanceof Map)return new Map(t(Array.from(e),s));if(e instanceof Set)return new Set(t(Array.from(e),s));var r={};for(var o in e){var a=e[o];"object"!=typeof a||null===a?r[o]=a:a instanceof Date?r[o]=new Date(a):a instanceof Map?r[o]=new Map(t(Array.from(a),s)):a instanceof Set?r[o]=new Set(t(Array.from(a),s)):ArrayBuffer.isView(a)?r[o]=n(a):r[o]=s(a)}return r}}function o(e){var t=[],r=[];return e.proto?a:s;function o(e,o){for(var s=Object.keys(e),a=new Array(s.length),i=0;i<s.length;i++){var c=s[i],l=e[c];if("object"!=typeof l||null===l)a[c]=l;else if(l instanceof Date)a[c]=new Date(l);else if(ArrayBuffer.isView(l))a[c]=n(l);else{var d=t.indexOf(l);a[c]=-1!==d?r[d]:o(l)}}return a}function s(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return o(e,s);if(e instanceof Map)return new Map(o(Array.from(e),s));if(e instanceof Set)return new Set(o(Array.from(e),s));var a={};for(var i in t.push(e),r.push(a),e)if(!1!==Object.hasOwnProperty.call(e,i)){var c=e[i];if("object"!=typeof c||null===c)a[i]=c;else if(c instanceof Date)a[i]=new Date(c);else if(c instanceof Map)a[i]=new Map(o(Array.from(c),s));else if(c instanceof Set)a[i]=new Set(o(Array.from(c),s));else if(ArrayBuffer.isView(c))a[i]=n(c);else{var l=t.indexOf(c);a[i]=-1!==l?r[l]:s(c)}}return t.pop(),r.pop(),a}function a(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return o(e,a);if(e instanceof Map)return new Map(o(Array.from(e),a));if(e instanceof Set)return new Set(o(Array.from(e),a));var s={};for(var i in t.push(e),r.push(s),e){var c=e[i];if("object"!=typeof c||null===c)s[i]=c;else if(c instanceof Date)s[i]=new Date(c);else if(c instanceof Map)s[i]=new Map(o(Array.from(c),a));else if(c instanceof Set)s[i]=new Set(o(Array.from(c),a));else if(ArrayBuffer.isView(c))s[i]=n(c);else{var l=t.indexOf(c);s[i]=-1!==l?r[l]:a(c)}}return t.pop(),r.pop(),s}}t.exports=r}).call(this)}).call(this,e("buffer").Buffer)},{buffer:17}],73:[function(e,t,n){
|
|
3
|
+
n.read=function(e,t,n,r,s){var o,a,i=8*s-r-1,c=(1<<i)-1,l=c>>1,d=-7,u=n?s-1:0,h=n?-1:1,p=e[t+u];for(u+=h,o=p&(1<<-d)-1,p>>=-d,d+=i;d>0;o=256*o+e[t+u],u+=h,d-=8);for(a=o&(1<<-d)-1,o>>=-d,d+=r;d>0;a=256*a+e[t+u],u+=h,d-=8);if(0===o)o=1-l;else{if(o===c)return a?NaN:1/0*(p?-1:1);a+=Math.pow(2,r),o-=l}return(p?-1:1)*a*Math.pow(2,o-r)},n.write=function(e,t,n,r,s,o){var a,i,c,l=8*o-s-1,d=(1<<l)-1,u=d>>1,h=23===s?Math.pow(2,-24)-Math.pow(2,-77):0,p=r?0:o-1,f=r?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(i=isNaN(t)?1:0,a=d):(a=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-a))<1&&(a--,c*=2),(t+=a+u>=1?h/c:h*Math.pow(2,1-u))*c>=2&&(a++,c/=2),a+u>=d?(i=0,a=d):a+u>=1?(i=(t*c-1)*Math.pow(2,s),a+=u):(i=t*Math.pow(2,u-1)*Math.pow(2,s),a=0));s>=8;e[n+p]=255&i,p+=f,i/=256,s-=8);for(a=a<<s|i,l+=s;l>0;e[n+p]=255&a,p+=f,a/=256,l-=8);e[n+p-f]|=128*g}},{}],24:[function(e,t,n){"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 n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}},{}],25:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var r=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,n=this.leftChild,r=this.rightChild;if(!r)throw new Error("unknown error");var s=r.leftChild,o=r.rightChild;return e&&(e.leftChild===this?e.leftChild=r:e.rightChild===this&&(e.rightChild=r)),r.parent=e,r.brother=t,r.leftChild=this,r.rightChild=o,t&&(t.brother=r),this.parent=r,this.brother=o,this.leftChild=n,this.rightChild=s,o&&(o.parent=r,o.brother=this),n&&(n.parent=this,n.brother=s),s&&(s.parent=this,s.brother=n),r},e.prototype.rotateRight=function(){var e=this.parent,t=this.brother,n=this.leftChild;if(!n)throw new Error("unknown error");var r=this.rightChild,s=n.leftChild,o=n.rightChild;return e&&(e.leftChild===this?e.leftChild=n:e.rightChild===this&&(e.rightChild=n)),n.parent=e,n.brother=t,n.leftChild=s,n.rightChild=this,t&&(t.brother=n),s&&(s.parent=n,s.brother=this),this.parent=n,this.brother=s,this.leftChild=o,this.rightChild=r,o&&(o.parent=this,o.brother=r),r&&(r.parent=this,r.brother=o),n},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(r),n.default=r},{}],26:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,s,o,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return o={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function i(e){return function(t){return c([e,t])}}function c(o){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(s=2&o[0]?r.return:o[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,o[1])).done)return s;switch(r=0,s&&(o=[2&o[0],s.value]),o[0]){case 0:case 1:s=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((s=(s=a.trys).length>0&&s[s.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!s||o[1]>s[0]&&o[1]<s[3])){a.label=o[1];break}if(6===o[0]&&a.label<s[1]){a.label=s[1],s=o;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(o);break}s[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],r=0}finally{n=s=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}};function s(e){var t=this;void 0===e&&(e=[]);var n=[],o=0,a=0,i=0,c=0,l=0,d=0;this.size=function(){return d},this.empty=function(){return 0===d},this.clear=function(){o=i=a=c=l=d=0,h.call(this,s.bucketSize),d=0},this.front=function(){return n[o][a]},this.back=function(){return n[i][c]},this.forEach=function(e){if(!this.empty()){var t=0;if(o!==i){for(l=a;l<s.bucketSize;++l)e(n[o][l],t++);for(l=o+1;l<i;++l)for(var r=0;r<s.bucketSize;++r)e(n[l][r],t++);for(l=0;l<=c;++l)e(n[i][l],t++)}else for(var l=a;l<=c;++l)e(n[o][l],t++)}};var u=function(e){var t=o*s.bucketSize+a,n=t+e,r=i*s.bucketSize+c;if(n<t||n>r)throw new Error("pos should more than 0 and less than queue's size");return{curNodeBucketIndex:Math.floor(n/s.bucketSize),curNodePointerIndex:n%s.bucketSize}};this.getElementByPos=function(e){var t=u(e),r=t.curNodeBucketIndex,s=t.curNodePointerIndex;return n[r][s]},this.eraseElementByPos=function(e){var t=this;if(e<0||e>d)throw new Error("pos should more than 0 and less than queue's size");if(0===e)this.popFront();else if(e===this.size())this.popBack();else{for(var n=[],r=e+1;r<d;++r)n.push(this.getElementByPos(r));this.cut(e),this.popBack(),n.forEach((function(e){return t.pushBack(e)}))}},this.eraseElementByValue=function(e){if(!this.empty()){var t=[];this.forEach((function(n){n!==e&&t.push(n)}));for(var n=t.length,r=0;r<n;++r)this.setElementByPos(r,t[r]);this.cut(n-1)}};var h=function(e){for(var t=[],r=e*s.sigma,u=Math.max(Math.ceil(r/s.bucketSize),2),h=0;h<u;++h)t.push(new Array(s.bucketSize));var p=Math.ceil(e/s.bucketSize),f=Math.floor(u/2)-Math.floor(p/2),g=f,m=0;if(this.size())for(h=0;h<p;++h){for(var y=0;y<s.bucketSize;++y)if(t[f+h][y]=this.front(),this.popFront(),this.empty()){g=f+h,m=y;break}if(this.empty())break}n=t,o=f,a=0,i=g,c=m,l=u,d=e};this.pushBack=function(e){this.empty()||(i===l-1&&c===s.bucketSize-1&&h.call(this,this.size()),c<s.bucketSize-1?++c:i<l-1&&(++i,c=0)),++d,n[i][c]=e},this.popBack=function(){this.empty()||(1!==this.size()&&(c>0?--c:o<i&&(--i,c=s.bucketSize-1)),d>0&&--d)},this.setElementByPos=function(e,t){var r=u(e),s=r.curNodeBucketIndex,o=r.curNodePointerIndex;n[s][o]=t},this.insert=function(e,t,n){var r=this;if(void 0===n&&(n=1),0===e)for(;n--;)this.pushFront(t);else if(e===this.size())for(;n--;)this.pushBack(t);else{for(var s=[],o=e;o<d;++o)s.push(this.getElementByPos(o));for(this.cut(e-1),o=0;o<n;++o)this.pushBack(t);s.forEach((function(e){return r.pushBack(e)}))}},this.find=function(e){if(o===i){for(var t=a;t<=c;++t)if(n[o][t]===e)return!0;return!1}for(t=a;t<s.bucketSize;++t)if(n[o][t]===e)return!0;for(t=o+1;t<i;++t)for(var r=0;r<s.bucketSize;++r)if(n[t][r]===e)return!0;for(t=0;t<=c;++t)if(n[i][t]===e)return!0;return!1},this.reverse=function(){for(var e=0,t=d-1;e<t;){var n=this.getElementByPos(e);this.setElementByPos(e,this.getElementByPos(t)),this.setElementByPos(t,n),++e,--t}},this.unique=function(){if(!this.empty()){var e=[],t=this.front();this.forEach((function(n,r){0!==r&&n===t||(e.push(n),t=n)}));for(var n=0;n<d;++n)this.setElementByPos(n,e[n]);this.cut(e.length-1)}},this.sort=function(e){var t=[];this.forEach((function(e){t.push(e)})),t.sort(e);for(var n=0;n<d;++n)this.setElementByPos(n,t[n])},this.pushFront=function(e){this.empty()||(0===o&&0===a&&h.call(this,this.size()),a>0?--a:o>0&&(--o,a=s.bucketSize-1)),++d,n[o][a]=e},this.popFront=function(){this.empty()||(1!==this.size()&&(a<s.bucketSize-1?++a:o<i&&(++o,a=0)),d>0&&--d)},this.shrinkToFit=function(){var e=this,t=[];this.forEach((function(e){t.push(e)}));var r=t.length;n=[];for(var o=Math.ceil(r/s.bucketSize),a=0;a<o;++a)n.push(new Array(s.bucketSize));this.clear(),t.forEach((function(t){return e.pushBack(t)}))},this.cut=function(e){if(e<0)this.clear();else{var t=u(e),n=t.curNodeBucketIndex,r=t.curNodePointerIndex;i=n,c=r,d=e+1}},this[Symbol.iterator]=function(){return function(){var e,t;return r(this,(function(r){switch(r.label){case 0:if(0===d)return[2];if(o!==i)return[3,5];t=a,r.label=1;case 1:return t<=c?[4,n[o][t]]:[3,4];case 2:r.sent(),r.label=3;case 3:return++t,[3,1];case 4:return[2];case 5:t=a,r.label=6;case 6:return t<s.bucketSize?[4,n[o][t]]:[3,9];case 7:r.sent(),r.label=8;case 8:return++t,[3,6];case 9:t=o+1,r.label=10;case 10:if(!(t<i))return[3,15];e=0,r.label=11;case 11:return e<s.bucketSize?[4,n[t][e]]:[3,14];case 12:r.sent(),r.label=13;case 13:return++e,[3,11];case 14:return++t,[3,10];case 15:t=0,r.label=16;case 16:return t<=c?[4,n[i][t]]:[3,19];case 17:r.sent(),r.label=18;case 18:return++t,[3,16];case 19:return[2]}}))}()},function(){var r=s.bucketSize;e.size?r=e.size():e.length&&(r=e.length);var a=r*s.sigma;l=Math.ceil(a/s.bucketSize),l=Math.max(l,3);for(var c=0;c<l;++c)n.push(new Array(s.bucketSize));var d=Math.ceil(r/s.bucketSize);o=Math.floor(l/2)-Math.floor(d/2),i=o,e.forEach((function(e){return t.pushBack(e)}))}(),Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),s.sigma=3,s.bucketSize=5e3,Object.freeze(s),n.default=s},{}],27:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,s,o,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return o={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function i(e){return function(t){return c([e,t])}}function c(o){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(s=2&o[0]?r.return:o[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,o[1])).done)return s;switch(r=0,s&&(o=[2&o[0],s.value]),o[0]){case 0:case 1:s=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((s=(s=a.trys).length>0&&s[s.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!s||o[1]>s[0]&&o[1]<s[3])){a.label=o[1];break}if(6===o[0]&&a.label<s[1]){a.label=s[1],s=o;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(o);break}s[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],r=0}finally{n=s=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}},s=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var o=e("../LinkList/LinkList"),a=e("../Map/Map");function i(e,t,n){var c=this;if(void 0===e&&(e=[]),void 0===t&&(t=i.initSize),n=n||function(e){var t,n,r=0,o="";if("number"==typeof e)r=((r=Math.floor(e))<<5)-r,r&=r;else{o="string"!=typeof e?JSON.stringify(e):e;try{for(var a=s(o),i=a.next();!i.done;i=a.next())r=(r<<5)-r+i.value.charCodeAt(0),r&=r}catch(e){t={error:e}}finally{try{i&&!i.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}}return r^=r>>>16},0!=(t&t-1))throw new Error("initBucketNum must be 2 to the power of n");var l=0,d=[],u=Math.max(i.initSize,Math.min(i.maxSize,t));this.size=function(){return l},this.empty=function(){return 0===l},this.clear=function(){l=0,u=t,d=[]},this.forEach=function(e){var t=0;d.forEach((function(n){n.forEach((function(n){e(n,t++)}))}))};var h=function(e){if(!(e>=i.maxSize)){u=2*e;var t=[];d.forEach((function(r,s){if(!r.empty()){if(r instanceof o.default&&1===r.size()){var c=r.front(),l=c.key,h=c.value;t[n(l)&u-1]=new o.default([{key:l,value:h}])}else if(r instanceof a.default){var p=new o.default,f=new o.default;r.forEach((function(t){0==(n(t.key)&e)?p.pushBack(t):f.pushBack(t)})),p.size()>i.untreeifyThreshold?t[s]=new a.default(p):p.size()&&(t[s]=p),f.size()>i.untreeifyThreshold?t[s+e]=new a.default(f):f.size()&&(t[s+e]=f)}else{var g=new o.default,m=new o.default;r.forEach((function(t){0==(n(t.key)&e)?g.pushBack(t):m.pushBack(t)})),g.size()&&(t[s]=g),m.size()&&(t[s+e]=m)}d[s].clear()}})),d=t}};this.setElement=function(e,t){var r,c;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 p=n(e)&u-1;if(d[p]){var f=d[p].size();if(d[p]instanceof o.default){try{for(var g=s(d[p]),m=g.next();!m.done;m=g.next()){var y=m.value;if(y.key===e)return void(y.value=t)}}catch(e){r={error:e}}finally{try{m&&!m.done&&(c=g.return)&&c.call(g)}finally{if(r)throw r.error}}d[p].pushBack({key:e,value:t}),d[p].size()>=i.treeifyThreshold&&(d[p]=new a.default(d[p]))}else d[p].setElement(e,t);var v=d[p].size();l+=v-f}else++l,d[p]=new o.default([{key:e,value:t}]);l>u*i.sigma&&h.call(this,u)}else this.eraseElementByKey(e)},this.getElementByKey=function(e){var t,r,o=n(e)&u-1;if(d[o]){if(d[o]instanceof a.default)return d[o].getElementByKey(e);try{for(var i=s(d[o]),c=i.next();!c.done;c=i.next()){var l=c.value;if(l.key===e)return l.value}}catch(e){t={error:e}}finally{try{c&&!c.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}}},this.eraseElementByKey=function(e){var t,r,c=n(e)&u-1;if(d[c]){var h=d[c].size();if(d[c]instanceof a.default)d[c].eraseElementByKey(e),d[c].size()<=i.untreeifyThreshold&&(d[c]=new o.default(d[c]));else{var p=-1;try{for(var f=s(d[c]),g=f.next();!g.done;g=f.next()){var m=g.value;if(++p,m.key===e){d[c].eraseElementByPos(p);break}}}catch(e){t={error:e}}finally{try{g&&!g.done&&(r=f.return)&&r.call(f)}finally{if(t)throw t.error}}}var y=d[c].size();l+=y-h}},this.find=function(e){var t,r,o=n(e)&u-1;if(!d[o])return!1;if(d[o]instanceof a.default)return d[o].find(e);try{for(var i=s(d[o]),c=i.next();!c.done;c=i.next())if(c.value.key===e)return!0}catch(e){t={error:e}}finally{try{c&&!c.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return!1},this[Symbol.iterator]=function(){return function(){var e,t,n,o,a,i;return r(this,(function(r){switch(r.label){case 0:e=0,r.label=1;case 1:if(!(e<u))return[3,10];for(;e<u&&!d[e];)++e;if(e>=u)return[3,10];r.label=2;case 2:r.trys.push([2,7,8,9]),a=void 0,t=s(d[e]),n=t.next(),r.label=3;case 3:return n.done?[3,6]:[4,n.value];case 4:r.sent(),r.label=5;case 5:return n=t.next(),[3,3];case 6:return[3,9];case 7:return o=r.sent(),a={error:o},[3,9];case 8:try{n&&!n.done&&(i=t.return)&&i.call(t)}finally{if(a)throw a.error}return[7];case 9:return++e,[3,1];case 10:return[2]}}))}()},e.forEach((function(e){var t=e.key,n=e.value;return c.setElement(t,n)})),Object.freeze(this)}i.initSize=16,i.maxSize=1<<30,i.sigma=.75,i.treeifyThreshold=8,i.untreeifyThreshold=6,i.minTreeifySize=64,Object.freeze(i),n.default=i},{"../LinkList/LinkList":29,"../Map/Map":30}],28:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,s,o,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return o={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function i(e){return function(t){return c([e,t])}}function c(o){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(s=2&o[0]?r.return:o[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,o[1])).done)return s;switch(r=0,s&&(o=[2&o[0],s.value]),o[0]){case 0:case 1:s=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((s=(s=a.trys).length>0&&s[s.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!s||o[1]>s[0]&&o[1]<s[3])){a.label=o[1];break}if(6===o[0]&&a.label<s[1]){a.label=s[1],s=o;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(o);break}s[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],r=0}finally{n=s=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}},s=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var o=e("../Set/Set"),a=e("../LinkList/LinkList");function i(e,t,n){var c=this;if(void 0===e&&(e=[]),void 0===t&&(t=i.initSize),n=n||function(e){var t=0,n="";if("number"==typeof e)t=((t=Math.floor(e))<<5)-t,t&=t;else{n="string"!=typeof e?JSON.stringify(e):e;for(var r=0;r<n.length;r++)t=(t<<5)-t+n.charCodeAt(r),t&=t}return t^=t>>>16},0!=(t&t-1))throw new Error("initBucketNum must be 2 to the power of n");var l=0,d=[],u=Math.max(i.initSize,Math.min(i.maxSize,t));this.size=function(){return l},this.empty=function(){return 0===l},this.clear=function(){l=0,u=t,d=[]},this.forEach=function(e){var t=0;d.forEach((function(n){n.forEach((function(n){e(n,t++)}))}))};var h=function(e){if(!(e>=i.maxSize)){u=2*e;var t=[];d.forEach((function(r,s){if(!r.empty()){if(r instanceof a.default&&1===r.size()){var c=r.front();if(void 0===c)throw new Error("unknown error");t[n(c)&u-1]=new a.default([c])}else if(r instanceof o.default){var l=new a.default,h=new a.default;r.forEach((function(t){0==(n(t)&e)?l.pushBack(t):h.pushBack(t)})),l.size()>i.untreeifyThreshold?t[s]=new o.default(l):l.size()&&(t[s]=l),h.size()>i.untreeifyThreshold?t[s+e]=new o.default(h):h.size()&&(t[s+e]=h)}else{var p=new a.default,f=new a.default;r.forEach((function(t){0==(n(t)&e)?p.pushBack(t):f.pushBack(t)})),p.size()&&(t[s]=p),f.size()&&(t[s+e]=f)}d[s].clear()}})),d=t}};this.insert=function(e){if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");var t=n(e)&u-1;if(d[t]){var r=d[t].size();if(d[t]instanceof a.default){if(d[t].find(e))return;d[t].pushBack(e),d[t].size()>=i.treeifyThreshold&&(d[t]=new o.default(d[t]))}else d[t].insert(e);var s=d[t].size();l+=s-r}else d[t]=new a.default([e]),++l;l>u*i.sigma&&h.call(this,u)},this.eraseElementByValue=function(e){var t=n(e)&u-1;if(d[t]){var r=d[t].size();d[t].eraseElementByValue(e),d[t]instanceof o.default&&d[t].size()<=i.untreeifyThreshold&&(d[t]=new a.default(d[t]));var s=d[t].size();l+=s-r}},this.find=function(e){var t=n(e)&u-1;return!!d[t]&&d[t].find(e)},this[Symbol.iterator]=function(){return function(){var e,t,n,o,a,i;return r(this,(function(r){switch(r.label){case 0:e=0,r.label=1;case 1:if(!(e<u))return[3,10];for(;e<u&&!d[e];)++e;if(e>=u)return[3,10];r.label=2;case 2:r.trys.push([2,7,8,9]),a=void 0,t=s(d[e]),n=t.next(),r.label=3;case 3:return n.done?[3,6]:[4,n.value];case 4:r.sent(),r.label=5;case 5:return n=t.next(),[3,3];case 6:return[3,9];case 7:return o=r.sent(),a={error:o},[3,9];case 8:try{n&&!n.done&&(i=t.return)&&i.call(t)}finally{if(a)throw a.error}return[7];case 9:return++e,[3,1];case 10:return[2]}}))}()},e.forEach((function(e){return c.insert(e)})),Object.freeze(this)}i.initSize=16,i.maxSize=1<<30,i.sigma=.75,i.treeifyThreshold=8,i.untreeifyThreshold=6,i.minTreeifySize=64,Object.freeze(i),n.default=i},{"../LinkList/LinkList":29,"../Set/Set":33}],29:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,s,o,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return o={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function i(e){return function(t){return c([e,t])}}function c(o){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(s=2&o[0]?r.return:o[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,o[1])).done)return s;switch(r=0,s&&(o=[2&o[0],s.value]),o[0]){case 0:case 1:s=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((s=(s=a.trys).length>0&&s[s.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!s||o[1]>s[0]&&o[1]<s[3])){a.label=o[1];break}if(6===o[0]&&a.label<s[1]){a.label=s[1],s=o;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(o);break}s[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],r=0}finally{n=s=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}};Object.defineProperty(n,"__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 o(e){var t=this;void 0===e&&(e=[]);var n=0,o=void 0,a=void 0;this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){o=a=void 0,n=0},this.front=function(){return null==o?void 0:o.value},this.back=function(){return null==a?void 0:a.value},this.forEach=function(e){for(var t=o,n=0;t;){if(void 0===t.value)throw new Error("unknown error");e(t.value,n++),t=t.next}},this.getElementByPos=function(e){if(e<0||e>=n)throw new Error("pos must more then 0 and less then the list length");for(var t=o;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>=n)throw new Error("erase pos must more then 0 and less then the list length");if(0===e)this.popFront();else if(e===n-1)this.popBack();else{for(var t=o;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 r=t.pre,s=t.next;s.pre=r,r.next=s,n>0&&--n}},this.eraseElementByValue=function(e){for(;o&&o.value===e;)this.popFront();for(;a&&a.value===e;)this.popBack();if(o)for(var t=o;t;){if(t.value===e){var r=t.pre,s=t.next;s&&(s.pre=r),r&&(r.next=s),n>0&&--n}t=t.next}},this.pushBack=function(e){if(null==e)throw new Error("you can't push null or undefined here");++n;var t=new s(e);a?(a.next=t,t.pre=a,a=t):o=a=t},this.popBack=function(){a&&(n>0&&--n,a&&(o===a?o=a=void 0:(a=a.pre)&&(a.next=void 0)))},this.setElementByPos=function(e,t){if(null==t)throw new Error("you can't set null or undefined here");if(e<0||e>=n)throw new Error("pos must more then 0 and less then the list length");for(var r=o;e--;){if(!r)throw new Error("unknown error");r=r.next}r&&(r.value=t)},this.insert=function(e,t,r){if(void 0===r&&(r=1),null==t)throw new Error("you can't insert null or undefined here");if(e<0||e>n)throw new Error("insert pos must more then 0 and less then or equal to the list length");if(r<0)throw new Error("insert size must more than 0");if(0===e)for(;r--;)this.pushFront(t);else if(e===n)for(;r--;)this.pushBack(t);else{for(var a=o,i=1;i<e;++i){if(!(null==a?void 0:a.next))throw new Error("unknown error");a=null==a?void 0:a.next}if(!a)throw new Error("unknown error");var c=a.next;for(n+=r;r--;)a.next=new s(t),a.next.pre=a,a=a.next;a.next=c,c&&(c.pre=a)}},this.find=function(e){for(var t=o;t;){if(t.value===e)return!0;t=t.next}return!1},this.reverse=function(){for(var e=o,t=a,r=0;e&&t&&2*r<n;){var s=e.value;e.value=t.value,t.value=s,e=e.next,t=t.pre,++r}},this.unique=function(){for(var e=o;e;){for(var t=e;t&&t.next&&t.value===t.next.value;)t=t.next,n>0&&--n;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 n=o;t.forEach((function(e){n&&(n.value=e,n=n.next)}))},this.pushFront=function(e){if(null==e)throw new Error("you can't push null or undefined here");++n;var t=new s(e);o?(t.next=o,o.pre=t,o=t):o=a=t},this.popFront=function(){o&&(n>0&&--n,o&&(o===a?o=a=void 0:(o=o.next)&&(o.pre=void 0)))},this.merge=function(e){var t=this,r=o;e.forEach((function(e){for(;r&&void 0!==r.value&&r.value<=e;)r=r.next;if(void 0===r)t.pushBack(e),r=a;else if(r===o)t.pushFront(e),r=o;else{++n;var i=r.pre;i&&(i.next=new s(e),i.next.pre=i,i.next.next=r,r&&(r.pre=i.next))}}))},this[Symbol.iterator]=function(){return function(){var e;return r(this,(function(t){switch(t.label){case 0:e=o,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(o),n.default=o},{}],30:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,s,o,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return o={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function i(e){return function(t){return c([e,t])}}function c(o){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(s=2&o[0]?r.return:o[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,o[1])).done)return s;switch(r=0,s&&(o=[2&o[0],s.value]),o[0]){case 0:case 1:s=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((s=(s=a.trys).length>0&&s[s.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!s||o[1]>s[0]&&o[1]<s[3])){a.label=o[1];break}if(6===o[0]&&a.label<s[1]){a.label=s[1],s=o;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(o);break}s[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],r=0}finally{n=s=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}},s=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var o=e("../Base/TreeNode");function a(e,t){var n=this;void 0===e&&(e=[]),t=t||function(e,t){return e<t?-1:e>t?1:0};var a=0,i=new o.default;i.color=o.default.TreeNodeColorType.black,this.size=function(){return a},this.empty=function(){return 0===a},this.clear=function(){a=0,i.key=i.value=void 0,i.leftChild=i.rightChild=i.brother=void 0};var c=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.leftChild?c(e.leftChild):e},l=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.rightChild?l(e.rightChild):e};this.front=function(){if(!this.empty()){var e=c(i);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=l(i);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,n,r=0;try{for(var o=s(this),a=o.next();!a.done;a=o.next())e(a.value,r++)}catch(e){t={error:e}}finally{try{a&&!a.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}},this.getElementByPos=function(e){var t,n;if(e<0||e>=this.size())throw new Error("pos must more than 0 and less than set's size");var r=0;try{for(var o=s(this),a=o.next();!a.done;a=o.next()){var i=a.value;if(r===e)return i;++r}}catch(e){t={error:e}}finally{try{a&&!a.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}throw new Error("unknown Error")};var d=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value){var r=t(e.key,n);return 0===r?{key:e.key,value:e.value}:r<0?d(e.rightChild,n):d(e.leftChild,n)||{key:e.key,value:e.value}}};this.lowerBound=function(e){return d(i,e)};var u=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value)return t(e.key,n)<=0?u(e.rightChild,n):u(e.leftChild,n)||{key:e.key,value:e.value}};this.upperBound=function(e){return u(i,e)};var h=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value){var r=t(e.key,n);return 0===r?{key:e.key,value:e.value}:r>0?h(e.leftChild,n):h(e.rightChild,n)||{key:e.key,value:e.value}}};this.reverseLowerBound=function(e){return h(i,e)};var p=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value)return t(e.key,n)>=0?p(e.leftChild,n):p(e.rightChild,n)||{key:e.key,value:e.value}};this.reverseUpperBound=function(e){return p(i,e)};var f=function(e){var t=e.parent;if(!t){if(e===i)return;throw new Error("unknown error")}if(e.color!==o.default.TreeNodeColorType.red){var n=e.brother;if(!n)throw new Error("unknown error");if(e===t.leftChild)if(n.color===o.default.TreeNodeColorType.red){n.color=o.default.TreeNodeColorType.black,t.color=o.default.TreeNodeColorType.red;var r=t.rotateLeft();i===t&&(i=r),f(e)}else n.color===o.default.TreeNodeColorType.black&&(n.rightChild&&n.rightChild.color===o.default.TreeNodeColorType.red?(n.color=t.color,t.color=o.default.TreeNodeColorType.black,n.rightChild&&(n.rightChild.color=o.default.TreeNodeColorType.black),r=t.rotateLeft(),i===t&&(i=r),e.color=o.default.TreeNodeColorType.black):n.rightChild&&n.rightChild.color!==o.default.TreeNodeColorType.black||!n.leftChild||n.leftChild.color!==o.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==o.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==o.default.TreeNodeColorType.black||(n.color=o.default.TreeNodeColorType.red,f(t)):(n.color=o.default.TreeNodeColorType.red,n.leftChild&&(n.leftChild.color=o.default.TreeNodeColorType.black),r=n.rotateRight(),i===n&&(i=r),f(e)));else e===t.rightChild&&(n.color===o.default.TreeNodeColorType.red?(n.color=o.default.TreeNodeColorType.black,t.color=o.default.TreeNodeColorType.red,r=t.rotateRight(),i===t&&(i=r),f(e)):n.color===o.default.TreeNodeColorType.black&&(n.leftChild&&n.leftChild.color===o.default.TreeNodeColorType.red?(n.color=t.color,t.color=o.default.TreeNodeColorType.black,n.leftChild&&(n.leftChild.color=o.default.TreeNodeColorType.black),r=t.rotateRight(),i===t&&(i=r),e.color=o.default.TreeNodeColorType.black):n.leftChild&&n.leftChild.color!==o.default.TreeNodeColorType.black||!n.rightChild||n.rightChild.color!==o.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==o.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==o.default.TreeNodeColorType.black||(n.color=o.default.TreeNodeColorType.red,f(t)):(n.color=o.default.TreeNodeColorType.red,n.rightChild&&(n.rightChild.color=o.default.TreeNodeColorType.black),r=n.rotateLeft(),i===n&&(i=r),f(e))))}else e.color=o.default.TreeNodeColorType.black},g=function(e){for(var t=e;t.leftChild||t.rightChild;){if(t.rightChild){t=c(t.rightChild);var n=e.key;e.key=t.key,t.key=n;var r=e.value;e.value=t.value,t.value=r,e=t}t.leftChild&&(t=l(t.leftChild),n=e.key,e.key=t.key,t.key=n,r=e.value,e.value=t.value,t.value=r,e=t)}f(t),t&&t.remove(),--a,i.color=o.default.TreeNodeColorType.black},m=function(e,t){return!(!e||void 0===e.key)&&(!!m(e.leftChild,t)||!!t(e)||m(e.rightChild,t))};this.eraseElementByPos=function(e){if(e<0||e>=a)throw new Error("pos must more than 0 and less than set's size");var t=0;m(i,(function(n){return e===t?(g(n),!0):(++t,!1)}))},this.eraseElementByKey=function(e){if(!this.empty()){var n=b(i,e);void 0!==n&&void 0!==n.key&&0===t(n.key,e)&&g(n)}};var y=function(e,n){if(!e||void 0===e.key)throw new Error("unknown error");var r=t(n,e.key);return r<0?e.leftChild?y(e.leftChild,n):(e.leftChild=new o.default,e.leftChild.parent=e,e.leftChild.brother=e.rightChild,e.rightChild&&(e.rightChild.brother=e.leftChild),e.leftChild):r>0?e.rightChild?y(e.rightChild,n):(e.rightChild=new o.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===i)return;throw new Error("unknown error")}if(t.color!==o.default.TreeNodeColorType.black&&t.color===o.default.TreeNodeColorType.red){var n=t.brother,r=t.parent;if(!r)throw new Error("unknown error");if(n&&n.color===o.default.TreeNodeColorType.red)n.color=t.color=o.default.TreeNodeColorType.black,r.color=o.default.TreeNodeColorType.red,v(r);else if(!n||n.color===o.default.TreeNodeColorType.black)if(t===r.leftChild)if(e===t.leftChild){t.color=o.default.TreeNodeColorType.black,r.color=o.default.TreeNodeColorType.red;var s=r.rotateRight();r===i&&(i=s)}else e===t.rightChild&&(s=t.rotateLeft(),r===i&&(i=s),v(t));else t===r.rightChild&&(e===t.leftChild?(s=t.rotateRight(),r===i&&(i=s),v(t)):e===t.rightChild&&(t.color=o.default.TreeNodeColorType.black,r.color=o.default.TreeNodeColorType.red,s=r.rotateLeft(),r===i&&(i=s)))}};this.setElement=function(e,n){if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(null!=n){if(this.empty())return++a,i.key=e,i.value=n,void(i.color=o.default.TreeNodeColorType.black);var r=y(i,e);void 0===r.key||0!==t(r.key,e)?(++a,r.key=e,r.value=n,v(r),i.color=o.default.TreeNodeColorType.black):r.value=n}else this.eraseElementByKey(e)};var b=function(e,n){if(e&&void 0!==e.key){var r=t(n,e.key);return r<0?b(e.leftChild,n):r>0?b(e.rightChild,n):e}};this.find=function(e){return!!b(i,e)},this.getElementByKey=function(e){var t=b(i,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 n=e.key,r=e.value;return t.setElement(n,r)}))},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(i)};var w=function(e){return r(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(i)},e.forEach((function(e){var t=e.key,r=e.value;return n.setElement(t,r)})),Object.freeze(this)}Object.freeze(a),n.default=a},{"../Base/TreeNode":25}],31:[function(e,t,n){function r(e,t){void 0===e&&(e=[]),t=t||function(e,t){return e>t?-1:e<t?1:0};var n=[];e.forEach((function(e){return n.push(e)}));var r=n.length,s=function(e,t){if(e<0||e>=r)throw new Error("unknown error");if(t<0||t>=r)throw new Error("unknown error");var s=n[e];n[e]=n[t],n[t]=s},o=function(e){if(e<0||e>=r)throw new Error("unknown error");var o=2*e+1,a=2*e+2;o<r&&t(n[e],n[o])>0&&s(e,o),a<r&&t(n[e],n[a])>0&&s(e,a)};!function(){for(var e=Math.floor((r-1)/2);e>=0;--e)for(var o=e,a=2*o+1;a<r;){var i=a+1,c=a;if(i<r&&t(n[a],n[i])>0&&(c=i),t(n[o],n[c])<=0)break;s(o,c),a=2*(o=c)+1}}(),this.size=function(){return r},this.empty=function(){return 0===r},this.clear=function(){r=0,n.length=0},this.push=function(e){if(n.push(e),1!=++r)for(var s=r-1;s>0;){var a=Math.floor((s-1)/2);if(t(n[a],e)<=0)break;o(a),s=a}},this.pop=function(){if(!this.empty())if(1!==this.size()){var e=n[r-1];--r;for(var s=0;s<this.size();){var o=2*s+1,a=2*s+2;if(o>=this.size())break;var i=o;if(a<this.size()&&t(n[o],n[a])>0&&(i=a),t(n[i],e)>=0)break;n[s]=n[i],s=i}n[s]=e}else--r},this.top=function(){return n[0]},Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),Object.freeze(r),n.default=r},{}],32:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var r=e("../LinkList/LinkList");function s(e){void 0===e&&(e=[]);var t=new r.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),n.default=s},{"../LinkList/LinkList":29}],33:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,s,o,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return o={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function i(e){return function(t){return c([e,t])}}function c(o){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(s=2&o[0]?r.return:o[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,o[1])).done)return s;switch(r=0,s&&(o=[2&o[0],s.value]),o[0]){case 0:case 1:s=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((s=(s=a.trys).length>0&&s[s.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!s||o[1]>s[0]&&o[1]<s[3])){a.label=o[1];break}if(6===o[0]&&a.label<s[1]){a.label=s[1],s=o;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(o);break}s[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],r=0}finally{n=s=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}},s=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var o=e("../Base/TreeNode");function a(e,t){var n=this;void 0===e&&(e=[]),t=t||function(e,t){return e<t?-1:e>t?1:0};var a=0,i=new o.default;i.color=o.default.TreeNodeColorType.black,this.size=function(){return a},this.empty=function(){return 0===a},this.clear=function(){a=0,i.key=void 0,i.leftChild=i.rightChild=i.brother=i.parent=void 0,i.color=o.default.TreeNodeColorType.black};var c=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.leftChild?c(e.leftChild):e},l=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.rightChild?l(e.rightChild):e};this.front=function(){if(!this.empty())return c(i).key},this.back=function(){if(!this.empty())return l(i).key},this.forEach=function(e){var t,n,r=0;try{for(var o=s(this),a=o.next();!a.done;a=o.next())e(a.value,r++)}catch(e){t={error:e}}finally{try{a&&!a.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}},this.getElementByPos=function(e){var t,n;if(e<0||e>=this.size())throw new Error("pos must more than 0 and less than set's size");var r=0;try{for(var o=s(this),a=o.next();!a.done;a=o.next()){var i=a.value;if(r===e)return i;++r}}catch(e){t={error:e}}finally{try{a&&!a.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}throw new Error("unknown error")};var d=function(e){var t=e.parent;if(!t){if(e===i)return;throw new Error("unknown error")}if(e.color!==o.default.TreeNodeColorType.red){var n=e.brother;if(!n)throw new Error("unknown error");if(e===t.leftChild)if(n.color===o.default.TreeNodeColorType.red){n.color=o.default.TreeNodeColorType.black,t.color=o.default.TreeNodeColorType.red;var r=t.rotateLeft();i===t&&(i=r),d(e)}else n.color===o.default.TreeNodeColorType.black&&(n.rightChild&&n.rightChild.color===o.default.TreeNodeColorType.red?(n.color=t.color,t.color=o.default.TreeNodeColorType.black,n.rightChild&&(n.rightChild.color=o.default.TreeNodeColorType.black),r=t.rotateLeft(),i===t&&(i=r),e.color=o.default.TreeNodeColorType.black):n.rightChild&&n.rightChild.color!==o.default.TreeNodeColorType.black||!n.leftChild||n.leftChild.color!==o.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==o.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==o.default.TreeNodeColorType.black||(n.color=o.default.TreeNodeColorType.red,d(t)):(n.color=o.default.TreeNodeColorType.red,n.leftChild&&(n.leftChild.color=o.default.TreeNodeColorType.black),r=n.rotateRight(),i===n&&(i=r),d(e)));else e===t.rightChild&&(n.color===o.default.TreeNodeColorType.red?(n.color=o.default.TreeNodeColorType.black,t.color=o.default.TreeNodeColorType.red,r=t.rotateRight(),i===t&&(i=r),d(e)):n.color===o.default.TreeNodeColorType.black&&(n.leftChild&&n.leftChild.color===o.default.TreeNodeColorType.red?(n.color=t.color,t.color=o.default.TreeNodeColorType.black,n.leftChild&&(n.leftChild.color=o.default.TreeNodeColorType.black),r=t.rotateRight(),i===t&&(i=r),e.color=o.default.TreeNodeColorType.black):n.leftChild&&n.leftChild.color!==o.default.TreeNodeColorType.black||!n.rightChild||n.rightChild.color!==o.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==o.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==o.default.TreeNodeColorType.black||(n.color=o.default.TreeNodeColorType.red,d(t)):(n.color=o.default.TreeNodeColorType.red,n.rightChild&&(n.rightChild.color=o.default.TreeNodeColorType.black),r=n.rotateLeft(),i===n&&(i=r),d(e))))}else e.color=o.default.TreeNodeColorType.black},u=function(e){for(var t=e;t.leftChild||t.rightChild;){if(t.rightChild){t=c(t.rightChild);var n=e.key;e.key=t.key,t.key=n,e=t}t.leftChild&&(t=l(t.leftChild),n=e.key,e.key=t.key,t.key=n,e=t)}d(t),t&&t.remove(),--a,i.color=o.default.TreeNodeColorType.black},h=function(e,t){return!(!e||void 0===e.key)&&(!!h(e.leftChild,t)||!!t(e)||h(e.rightChild,t))};this.eraseElementByPos=function(e){if(e<0||e>=a)throw new Error("pos must more than 0 and less than set's size");var t=0;h(i,(function(n){return e===t?(u(n),!0):(++t,!1)}))},this.eraseElementByValue=function(e){if(!this.empty()){var n=g(i,e);void 0!==n&&void 0!==n.key&&0===t(n.key,e)&&u(n)}};var p=function(e,n){if(!e||void 0===e.key)throw new Error("unknown error");var r=t(n,e.key);return r<0?e.leftChild?p(e.leftChild,n):(e.leftChild=new o.default,e.leftChild.parent=e,e.leftChild.brother=e.rightChild,e.rightChild&&(e.rightChild.brother=e.leftChild),e.leftChild):r>0?e.rightChild?p(e.rightChild,n):(e.rightChild=new o.default,e.rightChild.parent=e,e.rightChild.brother=e.leftChild,e.leftChild&&(e.leftChild.brother=e.rightChild),e.rightChild):e},f=function(e){var t=e.parent;if(!t){if(e===i)return;throw new Error("unknown error")}if(t.color!==o.default.TreeNodeColorType.black&&t.color===o.default.TreeNodeColorType.red){var n=t.brother,r=t.parent;if(!r)throw new Error("unknown error");if(n&&n.color===o.default.TreeNodeColorType.red)n.color=t.color=o.default.TreeNodeColorType.black,r.color=o.default.TreeNodeColorType.red,f(r);else if(!n||n.color===o.default.TreeNodeColorType.black)if(t===r.leftChild)if(e===t.leftChild){t.color=o.default.TreeNodeColorType.black,r.color=o.default.TreeNodeColorType.red;var s=r.rotateRight();r===i&&(i=s)}else e===t.rightChild&&(s=t.rotateLeft(),r===i&&(i=s),f(t));else t===r.rightChild&&(e===t.leftChild?(s=t.rotateRight(),r===i&&(i=s),f(t)):e===t.rightChild&&(t.color=o.default.TreeNodeColorType.black,r.color=o.default.TreeNodeColorType.red,s=r.rotateLeft(),r===i&&(i=s)))}};this.insert=function(e){if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(this.empty())return++a,i.key=e,void(i.color=o.default.TreeNodeColorType.black);var n=p(i,e);void 0!==n.key&&0===t(n.key,e)||(++a,n.key=e,f(n),i.color=o.default.TreeNodeColorType.black)};var g=function(e,n){if(e&&void 0!==e.key){var r=t(n,e.key);return r<0?g(e.leftChild,n):r>0?g(e.rightChild,n):e}};this.find=function(e){var n=g(i,e);return void 0!==n&&void 0!==n.key&&0===t(n.key,e)};var m=function(e,n){if(e&&void 0!==e.key){var r=t(e.key,n);if(0===r)return e.key;if(r<0)return m(e.rightChild,n);var s=m(e.leftChild,n);return void 0!==s?s:e.key}};this.lowerBound=function(e){return m(i,e)};var y=function(e,n){if(e&&void 0!==e.key){if(t(e.key,n)<=0)return y(e.rightChild,n);var r=y(e.leftChild,n);return void 0!==r?r:e.key}};this.upperBound=function(e){return y(i,e)};var v=function(e,n){if(e&&void 0!==e.key){var r=t(e.key,n);if(0===r)return e.key;if(r>0)return v(e.leftChild,n);var s=v(e.rightChild,n);return void 0!==s?s:e.key}};this.reverseLowerBound=function(e){return v(i,e)};var b=function(e,n){if(e&&void 0!==e.key){if(t(e.key,n)>=0)return b(e.leftChild,n);var r=b(e.rightChild,n);return void 0!==r?r:e.key}};this.reverseUpperBound=function(e){return b(i,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(i)};var w=function(e){return r(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(i)},e.forEach((function(e){return n.insert(e)})),Object.freeze(this)}Object.freeze(a),n.default=a},{"../Base/TreeNode":25}],34:[function(e,t,n){function r(e){var t=this;void 0===e&&(e=[]);var n=0,r=[];this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){n=0,r.length=0},this.push=function(e){r.push(e),++n},this.pop=function(){r.pop(),n>0&&--n},this.top=function(){return r[n-1]},e.forEach((function(e){return t.push(e)})),Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),Object.freeze(r),n.default=r},{}],35:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,s,o,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return o={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function i(e){return function(t){return c([e,t])}}function c(o){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(s=2&o[0]?r.return:o[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,o[1])).done)return s;switch(r=0,s&&(o=[2&o[0],s.value]),o[0]){case 0:case 1:s=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((s=(s=a.trys).length>0&&s[s.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!s||o[1]>s[0]&&o[1]<s[3])){a.label=o[1];break}if(6===o[0]&&a.label<s[1]){a.label=s[1],s=o;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(o);break}s[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],r=0}finally{n=s=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}},s=this&&this.__read||function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,s,o=n.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(r=o.next()).done;)a.push(r.value)}catch(e){s={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(s)throw s.error}}return a},o=this&&this.__spreadArray||function(e,t,n){if(n||2===arguments.length)for(var r,s=0,o=t.length;s<o;s++)!r&&s in t||(r||(r=Array.prototype.slice.call(t,0,s)),r[s]=t[s]);return e.concat(r||Array.prototype.slice.call(t))},a=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};function i(e){var t=this;void 0===e&&(e=[]);var n=0,i=[];this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){n=0,i.length=0},this.front=function(){if(!this.empty())return i[0]},this.back=function(){if(!this.empty())return i[n-1]},this.forEach=function(e){i.forEach(e)},this.getElementByPos=function(e){if(e<0||e>=n)throw new Error("pos must more than 0 and less than vector's size");return i[e]},this.eraseElementByPos=function(e){if(e<0||e>=n)throw new Error("pos must more than 0 and less than vector's size");for(var t=e;t<n-1;++t)i[t]=i[t+1];this.popBack()},this.eraseElementByValue=function(e){var t=[];this.forEach((function(n){n!==e&&t.push(n)})),t.forEach((function(e,t){i[t]=e}));for(var r=t.length;n>r;)this.popBack()},this.pushBack=function(e){i.push(e),++n},this.popBack=function(){i.pop(),n>0&&--n},this.setElementByPos=function(e,t){if(e<0||e>=n)throw new Error("pos must more than 0 and less than vector's size");i[e]=t},this.insert=function(e,t,r){if(void 0===r&&(r=1),e<0||e>n)throw new Error("pos must more than 0 and less than or equal to vector's size");i.splice.apply(i,o([e,0],s(new Array(r).fill(t)),!1)),n+=r},this.find=function(e){return i.includes(e)},this.reverse=function(){i.reverse()},this.unique=function(){var e,t=[];this.forEach((function(n,r){0!==r&&n===e||(t.push(n),e=n)})),t.forEach((function(e,t){i[t]=e}));for(var r=t.length;n>r;)this.popBack()},this.sort=function(e){i.sort(e)},this[Symbol.iterator]=function(){return function(){return r(this,(function(e){switch(e.label){case 0:return[5,a(i)];case 1:return[2,e.sent()]}}))}()},e.forEach((function(e){return t.pushBack(e)})),Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),Object.freeze(i),n.default=i},{}],36:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0}),n.HashMap=n.HashSet=n.Map=n.Set=n.PriorityQueue=n.Deque=n.LinkList=n.Queue=n.Stack=n.Vector=void 0;var r=e("./Vector/Vector");n.Vector=r.default;var s=e("./Stack/Stack");n.Stack=s.default;var o=e("./Queue/Queue");n.Queue=o.default;var a=e("./LinkList/LinkList");n.LinkList=a.default;var i=e("./Deque/Deque");n.Deque=i.default;var c=e("./PriorityQueue/PriorityQueue");n.PriorityQueue=c.default;var l=e("./Set/Set");n.Set=l.default;var d=e("./Map/Map");n.Map=d.default;var u=e("./HashSet/HashSet");n.HashSet=u.default;var h=e("./HashMap/HashMap");n.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,n){const r=e("yallist"),s=Symbol("max"),o=Symbol("length"),a=Symbol("lengthCalculator"),i=Symbol("allowStale"),c=Symbol("maxAge"),l=Symbol("dispose"),d=Symbol("noDisposeOnSet"),u=Symbol("lruList"),h=Symbol("cache"),p=Symbol("updateAgeOnGet"),f=()=>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||f;if(this[a]="function"!=typeof t?f:t,this[i]=e.stale||!1,e.maxAge&&"number"!=typeof e.maxAge)throw new TypeError("maxAge must be a number");this[c]=e.maxAge||0,this[l]=e.dispose,this[d]=e.noDisposeOnSet||!1,this[p]=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[i]=!!e}get allowStale(){return this[i]}set maxAge(e){if("number"!=typeof e)throw new TypeError("maxAge must be a non-negative number");this[c]=e,v(this)}get maxAge(){return this[c]}set lengthCalculator(e){"function"!=typeof e&&(e=f),e!==this[a]&&(this[a]=e,this[o]=0,this[u].forEach((e=>{e.length=this[a](e.value,e.key),this[o]+=e.length}))),v(this)}get lengthCalculator(){return this[a]}get length(){return this[o]}get itemCount(){return this[u].length}rforEach(e,t){t=t||this;for(let n=this[u].tail;null!==n;){const r=n.prev;C(this,e,n,t),n=r}}forEach(e,t){t=t||this;for(let n=this[u].head;null!==n;){const r=n.next;C(this,e,n,t),n=r}}keys(){return this[u].toArray().map((e=>e.key))}values(){return this[u].toArray().map((e=>e.value))}reset(){this[l]&&this[u]&&this[u].length&&this[u].forEach((e=>this[l](e.key,e.value))),this[h]=new Map,this[u]=new r,this[o]=0}dump(){return this[u].map((e=>!y(this,e)&&{k:e.key,v:e.value,e:e.now+(e.maxAge||0)})).toArray().filter((e=>e))}dumpLru(){return this[u]}set(e,t,n){if((n=n||this[c])&&"number"!=typeof n)throw new TypeError("maxAge must be a number");const r=n?Date.now():0,i=this[a](t,e);if(this[h].has(e)){if(i>this[s])return b(this,this[h].get(e)),!1;const a=this[h].get(e).value;return this[l]&&(this[d]||this[l](e,a.value)),a.now=r,a.maxAge=n,a.value=t,this[o]+=i-a.length,a.length=i,this.get(e),v(this),!0}const p=new w(e,t,i,r,n);return p.length>this[s]?(this[l]&&this[l](e,t),!1):(this[o]+=p.length,this[u].unshift(p),this[h].set(e,this[u].head),v(this),!0)}has(e){if(!this[h].has(e))return!1;const t=this[h].get(e).value;return!y(this,t)}get(e){return m(this,e,!0)}peek(e){return m(this,e,!1)}pop(){const e=this[u].tail;return e?(b(this,e),e.value):null}del(e){b(this,this[h].get(e))}load(e){this.reset();const t=Date.now();for(let n=e.length-1;n>=0;n--){const r=e[n],s=r.e||0;if(0===s)this.set(r.k,r.v);else{const e=s-t;e>0&&this.set(r.k,r.v,e)}}}prune(){this[h].forEach(((e,t)=>m(this,t,!1)))}}const m=(e,t,n)=>{const r=e[h].get(t);if(r){const t=r.value;if(y(e,t)){if(b(e,r),!e[i])return}else n&&(e[p]&&(r.value.now=Date.now()),e[u].unshiftNode(r));return t.value}},y=(e,t)=>{if(!t||!t.maxAge&&!e[c])return!1;const n=Date.now()-t.now;return t.maxAge?n>t.maxAge:e[c]&&n>e[c]},v=e=>{if(e[o]>e[s])for(let t=e[u].tail;e[o]>e[s]&&null!==t;){const n=t.prev;b(e,t),t=n}},b=(e,t)=>{if(t){const n=t.value;e[l]&&e[l](n.key,n.value),e[o]-=n.length,e[h].delete(n.key),e[u].removeNode(t)}};class w{constructor(e,t,n,r,s){this.key=e,this.value=t,this.length=n,this.now=r,this.maxAge=s||0}}const C=(e,t,n,r)=>{let s=n.value;y(e,s)&&(b(e,n),e[i]||(s=void 0)),s&&t.call(r,s.value,s.key,e)};t.exports=g},{yallist:83}],38:[function(e,t,n){(function(e){(function(){const n=t.exports;n.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"},n.codes={};for(const e in n.types){const t=n.types[e];n.codes[t]=e}n.CMD_SHIFT=4,n.CMD_MASK=240,n.DUP_MASK=8,n.QOS_MASK=3,n.QOS_SHIFT=1,n.RETAIN_MASK=1,n.VARBYTEINT_MASK=127,n.VARBYTEINT_FIN_MASK=128,n.VARBYTEINT_MAX=268435455,n.SESSIONPRESENT_MASK=1,n.SESSIONPRESENT_HEADER=e.from([n.SESSIONPRESENT_MASK]),n.CONNACK_HEADER=e.from([n.codes.connack<<n.CMD_SHIFT]),n.USERNAME_MASK=128,n.PASSWORD_MASK=64,n.WILL_RETAIN_MASK=32,n.WILL_QOS_MASK=24,n.WILL_QOS_SHIFT=3,n.WILL_FLAG_MASK=4,n.CLEAN_SESSION_MASK=2,n.CONNECT_HEADER=e.from([n.codes.connect<<n.CMD_SHIFT]),n.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},n.propertiesCodes={};for(const e in n.properties){const t=n.properties[e];n.propertiesCodes[t]=e}function r(t){return[0,1,2].map((r=>[0,1].map((s=>[0,1].map((o=>{const a=e.alloc(1);return a.writeUInt8(n.codes[t]<<n.CMD_SHIFT|(s?n.DUP_MASK:0)|r<<n.QOS_SHIFT|o,0,!0),a}))))))}n.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"},n.PUBLISH_HEADER=r("publish"),n.SUBSCRIBE_HEADER=r("subscribe"),n.SUBSCRIBE_OPTIONS_QOS_MASK=3,n.SUBSCRIBE_OPTIONS_NL_MASK=1,n.SUBSCRIBE_OPTIONS_NL_SHIFT=2,n.SUBSCRIBE_OPTIONS_RAP_MASK=1,n.SUBSCRIBE_OPTIONS_RAP_SHIFT=3,n.SUBSCRIBE_OPTIONS_RH_MASK=3,n.SUBSCRIBE_OPTIONS_RH_SHIFT=4,n.SUBSCRIBE_OPTIONS_RH=[0,16,32],n.SUBSCRIBE_OPTIONS_NL=4,n.SUBSCRIBE_OPTIONS_RAP=8,n.SUBSCRIBE_OPTIONS_QOS=[0,1,2],n.UNSUBSCRIBE_HEADER=r("unsubscribe"),n.ACKS={unsuback:r("unsuback"),puback:r("puback"),pubcomp:r("pubcomp"),pubrel:r("pubrel"),pubrec:r("pubrec")},n.SUBACK_HEADER=e.from([n.codes.suback<<n.CMD_SHIFT]),n.VERSION3=e.from([3]),n.VERSION4=e.from([4]),n.VERSION5=e.from([5]),n.VERSION131=e.from([131]),n.VERSION132=e.from([132]),n.QOS=[0,1,2].map((t=>e.from([t]))),n.EMPTY={pingreq:e.from([n.codes.pingreq<<4,0]),pingresp:e.from([n.codes.pingresp<<4,0]),disconnect:e.from([n.codes.disconnect<<4,0])}}).call(this)}).call(this,e("buffer").Buffer)},{buffer:17}],39:[function(e,t,n){(function(n){(function(){const r=e("./writeToStream"),s=e("events");function o(e,t){const n=new a;return r(e,n,t),n.concat()}class a extends s{constructor(){super(),this._array=new Array(20),this._i=0}write(e){return this._array[this._i++]=e,!0}concat(){let e=0;const t=new Array(this._array.length),r=this._array;let s,o=0;for(s=0;s<r.length&&void 0!==r[s];s++)"string"!=typeof r[s]?t[s]=r[s].length:t[s]=n.byteLength(r[s]),e+=t[s];const a=n.allocUnsafe(e);for(s=0;s<r.length&&void 0!==r[s];s++)"string"!=typeof r[s]?(r[s].copy(a,o),o+=t[s]):(a.write(r[s],o),o+=t[s]);return a}}t.exports=o}).call(this)}).call(this,e("buffer").Buffer)},{"./writeToStream":44,buffer:17,events:22}],40:[function(e,t,n){n.parser=e("./parser").parser,n.generate=e("./generate"),n.writeToStream=e("./writeToStream")},{"./generate":39,"./parser":43,"./writeToStream":44}],41:[function(e,t,n){(function(e){(function(){const n=65536,r={},s=e.isBuffer(e.from([1,2]).subarray(0,1));function o(t){const n=e.allocUnsafe(2);return n.writeUInt8(t>>8,0),n.writeUInt8(255&t,1),n}function a(){for(let e=0;e<n;e++)r[e]=o(e)}function i(t){const n=4;let r=0,o=0;const a=e.allocUnsafe(n);do{r=t%128|0,(t=t/128|0)>0&&(r|=128),a.writeUInt8(r,o++)}while(t>0&&o<n);return t>0&&(o=0),s?a.subarray(0,o):a.slice(0,o)}function c(t){const n=e.allocUnsafe(4);return n.writeUInt32BE(t,0),n}t.exports={cache:r,generateCache:a,generateNumber:o,genBufVariableByteInt:i,generate4ByteBuffer:c}}).call(this)}).call(this,e("buffer").Buffer)},{buffer:17}],42:[function(e,t,n){class r{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}}t.exports=r},{}],43:[function(e,t,n){const r=e("bl"),s=e("events"),o=e("./packet"),a=e("./constants"),i=e("debug")("mqtt-packet:parser");class c extends s{constructor(){super(),this.parser=this.constructor.parser}static parser(e){return this instanceof c?(this.settings=e||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):(new c).parser(e)}_resetState(){i("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new o,this.error=null,this._list=r(),this._stateCounter=0}parse(e){for(this.error&&this._resetState(),this._list.append(e),i("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++,i("parse: state complete. _stateCounter is now: %d",this._stateCounter),i("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return i("parse: exited while loop. packet: %d, buffer list length: %d",this.packet.length,this._list.length),this._list.length}_parseHeader(){const e=this._list.readUInt8(0);return this.packet.cmd=a.types[e>>a.CMD_SHIFT],this.packet.retain=0!=(e&a.RETAIN_MASK),this.packet.qos=e>>a.QOS_SHIFT&a.QOS_MASK,this.packet.dup=0!=(e&a.DUP_MASK),i("_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)),i("_parseLength %d",e.value),!!e}_parsePayload(){i("_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 i("_parsePayload complete result: %s",e),e}_parseConnect(){let e,t,n,r;i("_parseConnect");const s={},o=this.packet,c=this._parseString();if(null===c)return this._emitError(new Error("Cannot parse protocolId"));if("MQTT"!==c&&"MQIsdp"!==c)return this._emitError(new Error("Invalid protocolId"));if(o.protocolId=c,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(o.protocolVersion=this._list.readUInt8(this._pos),o.protocolVersion>=128&&(o.bridgeMode=!0,o.protocolVersion=o.protocolVersion-128),3!==o.protocolVersion&&4!==o.protocolVersion&&5!==o.protocolVersion)return this._emitError(new Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(s.username=this._list.readUInt8(this._pos)&a.USERNAME_MASK,s.password=this._list.readUInt8(this._pos)&a.PASSWORD_MASK,s.will=this._list.readUInt8(this._pos)&a.WILL_FLAG_MASK,s.will&&(o.will={},o.will.retain=0!=(this._list.readUInt8(this._pos)&a.WILL_RETAIN_MASK),o.will.qos=(this._list.readUInt8(this._pos)&a.WILL_QOS_MASK)>>a.WILL_QOS_SHIFT),o.clean=0!=(this._list.readUInt8(this._pos)&a.CLEAN_SESSION_MASK),this._pos++,o.keepalive=this._parseNum(),-1===o.keepalive)return this._emitError(new Error("Packet too short"));if(5===o.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(o.properties=e)}const l=this._parseString();if(null===l)return this._emitError(new Error("Packet too short"));if(o.clientId=l,i("_parseConnect: packet.clientId: %s",o.clientId),s.will){if(5===o.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(o.will.properties=e)}if(e=this._parseString(),null===e)return this._emitError(new Error("Cannot parse will topic"));if(o.will.topic=e,i("_parseConnect: packet.will.topic: %s",o.will.topic),t=this._parseBuffer(),null===t)return this._emitError(new Error("Cannot parse will payload"));o.will.payload=t,i("_parseConnect: packet.will.paylaod: %s",o.will.payload)}if(s.username){if(r=this._parseString(),null===r)return this._emitError(new Error("Cannot parse username"));o.username=r,i("_parseConnect: packet.username: %s",o.username)}if(s.password){if(n=this._parseBuffer(),null===n)return this._emitError(new Error("Cannot parse password"));o.password=n}return this.settings=o,i("_parseConnect: complete"),o}_parseConnack(){i("_parseConnack");const e=this.packet;if(this._list.length<1)return null;if(e.sessionPresent=!!(this._list.readUInt8(this._pos++)&a.SESSIONPRESENT_MASK),5===this.settings.protocolVersion)this._list.length>=2?e.reasonCode=this._list.readUInt8(this._pos++):e.reasonCode=0;else{if(this._list.length<2)return null;e.returnCode=this._list.readUInt8(this._pos++)}if(-1===e.returnCode||-1===e.reasonCode)return this._emitError(new Error("Cannot parse return code"));if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}i("_parseConnack: complete")}_parsePublish(){i("_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),i("_parsePublish: payload from buffer list: %o",e.payload)}}_parseSubscribe(){i("_parseSubscribe");const e=this.packet;let t,n,r,s,o,c,l;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"));n=this._parseByte(),r=n&a.SUBSCRIBE_OPTIONS_QOS_MASK,c=0!=(n>>a.SUBSCRIBE_OPTIONS_NL_SHIFT&a.SUBSCRIBE_OPTIONS_NL_MASK),o=0!=(n>>a.SUBSCRIBE_OPTIONS_RAP_SHIFT&a.SUBSCRIBE_OPTIONS_RAP_MASK),s=n>>a.SUBSCRIBE_OPTIONS_RH_SHIFT&a.SUBSCRIBE_OPTIONS_RH_MASK,l={topic:t,qos:r},5===this.settings.protocolVersion?(l.nl=c,l.rap=o,l.rh=s):this.settings.bridgeMode&&(l.rh=0,l.rap=!0,l.nl=!0),i("_parseSubscribe: push subscription `%s` to subscription",l),e.subscriptions.push(l)}}}_parseSuback(){i("_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(){i("_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"));i("_parseUnsubscribe: push topic `%s` to unsubscriptions",t),e.unsubscriptions.push(t)}}}_parseUnsuback(){i("_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(){i("_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(),i("_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(i("_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 i("_parseDisconnect result: true"),!0}_parseAuth(){i("_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),i("_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):(i("_parseMessageId: packet.messageId %d",e.messageId),!0)}_parseString(e){const t=this._parseNum(),n=t+this._pos;if(-1===t||n>this._list.length||n>this.packet.length)return null;const r=this._list.toString("utf8",this._pos,n);return this._pos+=t,i("_parseString: result: %s",r),r}_parseStringPair(){return i("_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 n=this._list.slice(this._pos,t);return this._pos+=e,i("_parseBuffer: result: %o",n),n}_parseNum(){if(this._list.length-this._pos<2)return-1;const e=this._list.readUInt16BE(this._pos);return this._pos+=2,i("_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,i("_parse4ByteNum: result: %s",e),e}_parseVarByteNum(e){i("_parseVarByteNum");const t=4;let n,r=0,s=1,o=0,c=!1;const l=this._pos?this._pos:0;for(;r<t&&l+r<this._list.length;){if(n=this._list.readUInt8(l+r++),o+=s*(n&a.VARBYTEINT_MASK),s*=128,0==(n&a.VARBYTEINT_FIN_MASK)){c=!0;break}if(this._list.length<=r)break}return!c&&r===t&&this._list.length>=r&&this._emitError(new Error("Invalid variable byte integer")),l&&(this._pos+=r),c=!!c&&(e?{bytes:r,value:o}:o),i("_parseVarByteNum: result: %o",c),c}_parseByte(){let e;return this._pos<this._list.length&&(e=this._list.readUInt8(this._pos),this._pos++),i("_parseByte: result: %o",e),e}_parseByType(e){switch(i("_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(){i("_parseProperties");const e=this._parseVarByteNum(),t=this._pos+e,n={};for(;this._pos<t;){const e=this._parseByte();if(!e)return this._emitError(new Error("Cannot parse property code type")),!1;const t=a.propertiesCodes[e];if(!t)return this._emitError(new Error("Unknown property")),!1;if("userProperties"!==t)n[t]?(Array.isArray(n[t])||(n[t]=[n[t]]),n[t].push(this._parseByType(a.propertiesTypes[t]))):n[t]=this._parseByType(a.propertiesTypes[t]);else{n[t]||(n[t]=Object.create(null));const e=this._parseByType(a.propertiesTypes[t]);if(n[t][e.name])if(Array.isArray(n[t][e.name]))n[t][e.name].push(e.value);else{const r=n[t][e.name];n[t][e.name]=[r],n[t][e.name].push(e.value)}else n[t][e.name]=e.value}}return n}_newPacket(){return i("_newPacket"),this.packet&&(this._list.consume(this.packet.length),i("_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)),i("_newPacket: new packet"),this.packet=new o,this._pos=0,!0}_emitError(e){i("_emitError"),this.error=e,this.emit("error",e)}}t.exports=c},{"./constants":38,"./packet":42,bl:15,debug:18,events:22}],44:[function(e,t,n){(function(n){(function(){const r=e("./constants"),s=n.allocUnsafe(0),o=n.from([0]),a=e("./numbers"),i=e("process-nextick-args").nextTick,c=e("debug")("mqtt-packet:writeToStream"),l=a.cache,d=a.generateNumber,u=a.generateCache,h=a.genBufVariableByteInt,p=a.generate4ByteBuffer;let f=U,g=!0;function m(e,t,n){switch(c("generate called"),t.cork&&(t.cork(),i(y,t)),g&&(g=!1,u()),c("generate: packet.cmd: %s",e.cmd),e.cmd){case"connect":return v(e,t);case"connack":return b(e,t,n);case"publish":return w(e,t,n);case"puback":case"pubrec":case"pubrel":case"pubcomp":return C(e,t,n);case"subscribe":return I(e,t,n);case"suback":return S(e,t,n);case"unsubscribe":return _(e,t,n);case"unsuback":return k(e,t,n);case"pingreq":case"pingresp":return O(e,t);case"disconnect":return T(e,t,n);case"auth":return E(e,t,n);default:return t.emit("error",new Error("Unknown command")),!1}}function y(e){e.uncork()}function v(e,t,s){const o=e||{},a=o.protocolId||"MQTT";let i=o.protocolVersion||4;const c=o.will;let l=o.clean;const d=o.keepalive||0,u=o.clientId||"",h=o.username,p=o.password,g=o.properties;void 0===l&&(l=!0);let m=0;if(!a||"string"!=typeof a&&!n.isBuffer(a))return t.emit("error",new Error("Invalid protocolId")),!1;if(m+=a.length+2,3!==i&&4!==i&&5!==i)return t.emit("error",new Error("Invalid protocol version")),!1;if(m+=1,("string"==typeof u||n.isBuffer(u))&&(u||i>=4)&&(u||l))m+=n.byteLength(u)+2;else{if(i<4)return t.emit("error",new Error("clientId must be supplied before 3.1.1")),!1;if(1*l==0)return t.emit("error",new Error("clientId must be given if cleanSession set to 0")),!1}if("number"!=typeof d||d<0||d>65535||d%1!=0)return t.emit("error",new Error("Invalid keepalive")),!1;if(m+=2,m+=1,5===i){var y=N(t,g);if(!y)return!1;m+=y.length}if(c){if("object"!=typeof c)return t.emit("error",new Error("Invalid will")),!1;if(!c.topic||"string"!=typeof c.topic)return t.emit("error",new Error("Invalid will topic")),!1;if(m+=n.byteLength(c.topic)+2,m+=2,c.payload){if(!(c.payload.length>=0))return t.emit("error",new Error("Invalid will payload")),!1;"string"==typeof c.payload?m+=n.byteLength(c.payload):m+=c.payload.length}var v={};if(5===i){if(!(v=N(t,c.properties)))return!1;m+=v.length}}let b=!1;if(null!=h){if(!K(h))return t.emit("error",new Error("Invalid username")),!1;b=!0,m+=n.byteLength(h)+2}if(null!=p){if(!b)return t.emit("error",new Error("Username is required to use password")),!1;if(!K(p))return t.emit("error",new Error("Invalid password")),!1;m+=L(p)+2}t.write(r.CONNECT_HEADER),M(t,m),D(t,a),o.bridgeMode&&(i+=128),t.write(131===i?r.VERSION131:132===i?r.VERSION132:4===i?r.VERSION4:5===i?r.VERSION5:r.VERSION3);let w=0;return w|=null!=h?r.USERNAME_MASK:0,w|=null!=p?r.PASSWORD_MASK:0,w|=c&&c.retain?r.WILL_RETAIN_MASK:0,w|=c&&c.qos?c.qos<<r.WILL_QOS_SHIFT:0,w|=c?r.WILL_FLAG_MASK:0,w|=l?r.CLEAN_SESSION_MASK:0,t.write(n.from([w])),f(t,d),5===i&&y.write(),D(t,u),c&&(5===i&&v.write(),P(t,c.topic),D(t,c.payload)),null!=h&&D(t,h),null!=p&&D(t,p),!0}function b(e,t,s){const a=s?s.protocolVersion:4,i=e||{},c=5===a?i.reasonCode:i.returnCode,l=i.properties;let d=2;if("number"!=typeof c)return t.emit("error",new Error("Invalid return code")),!1;let u=null;if(5===a){if(u=N(t,l),!u)return!1;d+=u.length}return t.write(r.CONNACK_HEADER),M(t,d),t.write(i.sessionPresent?r.SESSIONPRESENT_HEADER:o),t.write(n.from([c])),null!=u&&u.write(),!0}function w(e,t,o){c("publish: packet: %o",e);const a=o?o.protocolVersion:4,i=e||{},l=i.qos||0,d=i.retain?r.RETAIN_MASK:0,u=i.topic,h=i.payload||s,p=i.messageId,g=i.properties;let m=0;if("string"==typeof u)m+=n.byteLength(u)+2;else{if(!n.isBuffer(u))return t.emit("error",new Error("Invalid topic")),!1;m+=u.length+2}if(n.isBuffer(h)?m+=h.length:m+=n.byteLength(h),l&&"number"!=typeof p)return t.emit("error",new Error("Invalid messageId")),!1;l&&(m+=2);let y=null;if(5===a){if(y=N(t,g),!y)return!1;m+=y.length}return t.write(r.PUBLISH_HEADER[l][i.dup?1:0][d?1:0]),M(t,m),f(t,L(u)),t.write(u),l>0&&f(t,p),null!=y&&y.write(),c("publish: payload: %o",h),t.write(h)}function C(e,t,s){const o=s?s.protocolVersion:4,a=e||{},i=a.cmd||"puback",c=a.messageId,l=a.dup&&"pubrel"===i?r.DUP_MASK:0;let d=0;const u=a.reasonCode,h=a.properties;let p=5===o?3:2;if("pubrel"===i&&(d=1),"number"!=typeof c)return t.emit("error",new Error("Invalid messageId")),!1;let g=null;if(5===o&&"object"==typeof h){if(g=B(t,h,s,p),!g)return!1;p+=g.length}return t.write(r.ACKS[i][d][l][0]),M(t,p),f(t,c),5===o&&t.write(n.from([u])),null!==g&&g.write(),!0}function I(e,t,s){c("subscribe: packet: ");const o=s?s.protocolVersion:4,a=e||{},i=a.dup?r.DUP_MASK:0,l=a.messageId,d=a.subscriptions,u=a.properties;let h=0;if("number"!=typeof l)return t.emit("error",new Error("Invalid messageId")),!1;h+=2;let p=null;if(5===o){if(p=N(t,u),!p)return!1;h+=p.length}if("object"!=typeof d||!d.length)return t.emit("error",new Error("Invalid subscriptions")),!1;for(let e=0;e<d.length;e+=1){const r=d[e].topic,s=d[e].qos;if("string"!=typeof r)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===o){if("boolean"!=typeof(d[e].nl||!1))return t.emit("error",new Error("Invalid subscriptions - invalid No Local")),!1;if("boolean"!=typeof(d[e].rap||!1))return t.emit("error",new Error("Invalid subscriptions - invalid Retain as Published")),!1;const n=d[e].rh||0;if("number"!=typeof n||n>2)return t.emit("error",new Error("Invalid subscriptions - invalid Retain Handling")),!1}h+=n.byteLength(r)+2+1}c("subscribe: writing to stream: %o",r.SUBSCRIBE_HEADER),t.write(r.SUBSCRIBE_HEADER[1][i?1:0][0]),M(t,h),f(t,l),null!==p&&p.write();let g=!0;for(const e of d){const s=e.topic,a=e.qos,i=+e.nl,c=+e.rap,l=e.rh;let d;P(t,s),d=r.SUBSCRIBE_OPTIONS_QOS[a],5===o&&(d|=i?r.SUBSCRIBE_OPTIONS_NL:0,d|=c?r.SUBSCRIBE_OPTIONS_RAP:0,d|=l?r.SUBSCRIBE_OPTIONS_RH[l]:0),g=t.write(n.from([d]))}return g}function S(e,t,s){const o=s?s.protocolVersion:4,a=e||{},i=a.messageId,c=a.granted,l=a.properties;let d=0;if("number"!=typeof i)return t.emit("error",new Error("Invalid messageId")),!1;if(d+=2,"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;d+=1}let u=null;if(5===o){if(u=B(t,l,s,d),!u)return!1;d+=u.length}return t.write(r.SUBACK_HEADER),M(t,d),f(t,i),null!==u&&u.write(),t.write(n.from(c))}function _(e,t,s){const o=s?s.protocolVersion:4,a=e||{},i=a.messageId,c=a.dup?r.DUP_MASK:0,l=a.unsubscriptions,d=a.properties;let u=0;if("number"!=typeof i)return t.emit("error",new Error("Invalid messageId")),!1;if(u+=2,"object"!=typeof l||!l.length)return t.emit("error",new Error("Invalid unsubscriptions")),!1;for(let e=0;e<l.length;e+=1){if("string"!=typeof l[e])return t.emit("error",new Error("Invalid unsubscriptions")),!1;u+=n.byteLength(l[e])+2}let h=null;if(5===o){if(h=N(t,d),!h)return!1;u+=h.length}t.write(r.UNSUBSCRIBE_HEADER[1][c?1:0][0]),M(t,u),f(t,i),null!==h&&h.write();let p=!0;for(let e=0;e<l.length;e++)p=P(t,l[e]);return p}function k(e,t,s){const o=s?s.protocolVersion:4,a=e||{},i=a.messageId,c=a.dup?r.DUP_MASK:0,l=a.granted,d=a.properties,u=a.cmd,h=0;let p=2;if("number"!=typeof i)return t.emit("error",new Error("Invalid messageId")),!1;if(5===o){if("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;p+=1}}let g=null;if(5===o){if(g=B(t,d,s,p),!g)return!1;p+=g.length}return t.write(r.ACKS[u][h][c][0]),M(t,p),f(t,i),null!==g&&g.write(),5===o&&t.write(n.from(l)),!0}function O(e,t,n){return t.write(r.EMPTY[e.cmd])}function T(e,t,s){const o=s?s.protocolVersion:4,a=e||{},i=a.reasonCode,c=a.properties;let l=5===o?1:0,d=null;if(5===o){if(d=B(t,c,s,l),!d)return!1;l+=d.length}return t.write(n.from([r.codes.disconnect<<4])),M(t,l),5===o&&t.write(n.from([i])),null!==d&&d.write(),!0}function E(e,t,s){const o=s?s.protocolVersion:4,a=e||{},i=a.reasonCode,c=a.properties;let l=5===o?1:0;5!==o&&t.emit("error",new Error("Invalid mqtt version for auth packet"));const d=B(t,c,s,l);return!!d&&(l+=d.length,t.write(n.from([r.codes.auth<<4])),M(t,l),t.write(n.from([i])),null!==d&&d.write(),!0)}Object.defineProperty(m,"cacheNumbers",{get:()=>f===U,set(e){e?(l&&0!==Object.keys(l).length||(g=!0),f=U):(g=!1,f=j)}});const A={};function M(e,t){if(t>r.VARBYTEINT_MAX)return e.emit("error",new Error(`Invalid variable byte integer: ${t}`)),!1;let n=A[t];return n||(n=h(t),t<16384&&(A[t]=n)),c("writeVarByteInt: writing to stream: %o",n),e.write(n)}function P(e,t){const r=n.byteLength(t);return f(e,r),c("writeString: %s",t),e.write(t,"utf8")}function R(e,t,n){P(e,t),P(e,n)}function U(e,t){return c("writeNumberCached: number: %d",t),c("writeNumberCached: %o",l[t]),e.write(l[t])}function j(e,t){const n=d(t);return c("writeNumberGenerated: %o",n),e.write(n)}function x(e,t){const n=p(t);return c("write4ByteNumber: %o",n),e.write(n)}function D(e,t){"string"==typeof t?P(e,t):t?(f(e,t.length),e.write(t)):f(e,0)}function N(e,t){if("object"!=typeof t||null!=t.length)return{length:1,write(){F(e,{},0)}};let s=0;function o(t,s){let o=0;switch(r.propertiesTypes[t]){case"byte":if("boolean"!=typeof s)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;o+=2;break;case"int8":if("number"!=typeof s||s<0||s>255)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;o+=2;break;case"binary":if(s&&null===s)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;o+=1+n.byteLength(s)+2;break;case"int16":if("number"!=typeof s||s<0||s>65535)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;o+=3;break;case"int32":if("number"!=typeof s||s<0||s>4294967295)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;o+=5;break;case"var":if("number"!=typeof s||s<0||s>268435455)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;o+=1+n.byteLength(h(s));break;case"string":if("string"!=typeof s)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;o+=3+n.byteLength(s.toString());break;case"pair":if("object"!=typeof s)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;o+=Object.getOwnPropertyNames(s).reduce(((e,t)=>{const r=s[t];return Array.isArray(r)?e+=r.reduce(((e,r)=>e+=3+n.byteLength(t.toString())+2+n.byteLength(r.toString())),0):e+=3+n.byteLength(t.toString())+2+n.byteLength(s[t].toString()),e}),0);break;default:return e.emit("error",new Error(`Invalid property ${t}: ${s}`)),!1}return o}if(t)for(const e in t){let n=0,r=0;const a=t[e];if(Array.isArray(a))for(let t=0;t<a.length;t++){if(r=o(e,a[t]),!r)return!1;n+=r}else{if(r=o(e,a),!r)return!1;n=r}if(!n)return!1;s+=n}return{length:n.byteLength(h(s))+s,write(){F(e,t,s)}}}function B(e,t,n,r){const s=["reasonString","userProperties"],o=n&&n.properties&&n.properties.maximumPacketSize?n.properties.maximumPacketSize:0;let a=N(e,t);if(o)for(;r+a.length>o;){const n=s.shift();if(!n||!t[n])return!1;delete t[n],a=N(e,t)}return a}function q(e,t,s){switch(r.propertiesTypes[t]){case"byte":e.write(n.from([r.properties[t]])),e.write(n.from([+s]));break;case"int8":e.write(n.from([r.properties[t]])),e.write(n.from([s]));break;case"binary":e.write(n.from([r.properties[t]])),D(e,s);break;case"int16":e.write(n.from([r.properties[t]])),f(e,s);break;case"int32":e.write(n.from([r.properties[t]])),x(e,s);break;case"var":e.write(n.from([r.properties[t]])),M(e,s);break;case"string":e.write(n.from([r.properties[t]])),P(e,s);break;case"pair":Object.getOwnPropertyNames(s).forEach((o=>{const a=s[o];Array.isArray(a)?a.forEach((s=>{e.write(n.from([r.properties[t]])),R(e,o.toString(),s.toString())})):(e.write(n.from([r.properties[t]])),R(e,o.toString(),a.toString()))}));break;default:return e.emit("error",new Error(`Invalid property ${t} value: ${s}`)),!1}}function F(e,t,n){M(e,n);for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&null!==t[n]){const r=t[n];if(Array.isArray(r))for(let t=0;t<r.length;t++)q(e,n,r[t]);else q(e,n,r)}}function L(e){return e?e instanceof n?e.length:n.byteLength(e):0}function K(e){return"string"==typeof e||e instanceof n}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,n){var r=1e3,s=60*r,o=60*s,a=24*o,i=7*a,c=365.25*a;function l(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 n=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return n*c;case"weeks":case"week":case"w":return n*i;case"days":case"day":case"d":return n*a;case"hours":case"hour":case"hrs":case"hr":case"h":return n*o;case"minutes":case"minute":case"mins":case"min":case"m":return n*s;case"seconds":case"second":case"secs":case"sec":case"s":return n*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function d(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+"d":t>=o?Math.round(e/o)+"h":t>=s?Math.round(e/s)+"m":t>=r?Math.round(e/r)+"s":e+"ms"}function u(e){var t=Math.abs(e);return t>=a?h(e,t,a,"day"):t>=o?h(e,t,o,"hour"):t>=s?h(e,t,s,"minute"):t>=r?h(e,t,r,"second"):e+" ms"}function h(e,t,n,r){var s=t>=1.5*n;return Math.round(e/n)+" "+r+(s?"s":"")}t.exports=function(e,t){t=t||{};var n=typeof e;if("string"===n&&e.length>0)return l(e);if("number"===n&&isFinite(e))return t.long?u(e):d(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},{}],46:[function(e,t,n){const r=e("./lib/number-allocator.js");t.exports.NumberAllocator=r},{"./lib/number-allocator.js":47}],47:[function(e,t,n){const r=e("js-sdsl").Set,s=e("debug")("number-allocator:trace"),o=e("debug")("number-allocator:error");function a(e,t){this.low=e,this.high=t}function i(e,t){if(!(this instanceof i))return new i(e,t);this.min=e,this.max=t,this.ss=new r([],((e,t)=>e.compare(t))),s("Create"),this.clear()}a.prototype.equals=function(e){return this.low===e.low&&this.high===e.high},a.prototype.compare=function(e){return this.low<e.low&&this.high<e.low?-1:e.low<this.low&&e.high<this.low?1:0},i.prototype.firstVacant=function(){return 0===this.ss.size()?null:this.ss.front().low},i.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},i.prototype.use=function(e){const t=new a(e,e),n=this.ss.lowerBound(t);if(n){if(n.equals(t))return this.ss.eraseElementByValue(n),s("use():"+e),!0;if(n.low>e)return!1;if(n.low===e)return++n.low,s("use():"+e),!0;if(n.high===e)return--n.high,s("use():"+e),!0;const r=n.low;return n.low=e+1,this.ss.insert(new a(r,e-1)),s("use():"+e),!0}return s("use():failed"),!1},i.prototype.free=function(e){if(e<this.min||e>this.max)return void o("free():"+e+" is out of range");const t=new a(e,e),n=this.ss.lowerBound(t);if(n){if(n.low<=e&&e<=n.high)return void o("free():"+e+" has already been vacant");if(n===this.ss.front())e+1===n.low?--n.low:this.ss.insert(t);else{const r=this.ss.reverseLowerBound(t);r.high+1===e?e+1===n.low?(this.ss.eraseElementByValue(r),n.low=r.low):r.high=e:e+1===n.low?n.low=e:this.ss.insert(t)}}else{if(n===this.ss.front())return void this.ss.insert(t);const r=this.ss.reverseLowerBound(t);r.high+1===e?r.high=e:this.ss.insert(t)}s("free():"+e)},i.prototype.clear=function(){s("clear()"),this.ss.clear(),this.ss.insert(new a(this.min,this.max))},i.prototype.intervalCount=function(){return this.ss.size()},i.prototype.dump=function(){console.log("length:"+this.ss.size());for(const e of this.ss)console.log(e)},t.exports=i},{debug:18,"js-sdsl":36}],48:[function(e,t,n){var r=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 o(e){var t=function(){if(t.called)throw new Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)},n=e.name||"Function wrapped with `once`";return t.onceError=n+" shouldn't be called more than once",t.called=!1,t}t.exports=r(s),t.exports.strict=r(o),s.proto=s((function(){Object.defineProperty(Function.prototype,"once",{value:function(){return s(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return o(this)},configurable:!0})}))},{wrappy:79}],49:[function(e,t,n){(function(e){(function(){function n(t,n,r,s){if("function"!=typeof t)throw new TypeError('"callback" argument must be a function');var o,a,i=arguments.length;switch(i){case 0:case 1:return e.nextTick(t);case 2:return e.nextTick((function(){t.call(null,n)}));case 3:return e.nextTick((function(){t.call(null,n,r)}));case 4:return e.nextTick((function(){t.call(null,n,r,s)}));default:for(o=new Array(i-1),a=0;a<o.length;)o[a++]=arguments[a];return e.nextTick((function(){t.apply(null,o)}))}}void 0===e||!e.version||0===e.version.indexOf("v0.")||0===e.version.indexOf("v1.")&&0!==e.version.indexOf("v1.8.")?t.exports={nextTick:n}:t.exports=e}).call(this)}).call(this,e("_process"))},{_process:50}],50:[function(e,t,n){var r,s,o=t.exports={};function a(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}function c(e){if(r===setTimeout)return setTimeout(e,0);if((r===a||!r)&&setTimeout)return r=setTimeout,setTimeout(e,0);try{return r(e,0)}catch(t){try{return r.call(null,e,0)}catch(t){return r.call(this,e,0)}}}function l(e){if(s===clearTimeout)return clearTimeout(e);if((s===i||!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{r="function"==typeof setTimeout?setTimeout:a}catch(e){r=a}try{s="function"==typeof clearTimeout?clearTimeout:i}catch(e){s=i}}();var d,u=[],h=!1,p=-1;function f(){h&&d&&(h=!1,d.length?u=d.concat(u):p=-1,u.length&&g())}function g(){if(!h){var e=c(f);h=!0;for(var t=u.length;t;){for(d=u,u=[];++p<t;)d&&d[p].run();p=-1,t=u.length}d=null,h=!1,l(e)}}function m(e,t){this.fun=e,this.array=t}function y(){}o.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];u.push(new m(e,t)),1!==u.length||h||c(g)},m.prototype.run=function(){this.fun.apply(null,this.array)},o.title="browser",o.browser=!0,o.env={},o.argv=[],o.version="",o.versions={},o.on=y,o.addListener=y,o.once=y,o.off=y,o.removeListener=y,o.removeAllListeners=y,o.emit=y,o.prependListener=y,o.prependOnceListener=y,o.listeners=function(e){return[]},o.binding=function(e){throw new Error("process.binding is not supported")},o.cwd=function(){return"/"},o.chdir=function(e){throw new Error("process.chdir is not supported")},o.umask=function(){return 0}},{}],51:[function(e,t,n){(function(e){(function(){!function(r){var s="object"==typeof n&&n&&!n.nodeType&&n,o="object"==typeof t&&t&&!t.nodeType&&t,a="object"==typeof e&&e;a.global!==a&&a.window!==a&&a.self!==a||(r=a);var i,c,l=2147483647,d=36,u=1,h=26,p=38,f=700,g=72,m=128,y="-",v=/^xn--/,b=/[^\x20-\x7E]/,w=/[\x2E\u3002\uFF0E\uFF61]/g,C={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},I=d-u,S=Math.floor,_=String.fromCharCode;function k(e){throw new RangeError(C[e])}function O(e,t){for(var n=e.length,r=[];n--;)r[n]=t(e[n]);return r}function T(e,t){var n=e.split("@"),r="";return n.length>1&&(r=n[0]+"@",e=n[1]),r+O((e=e.replace(w,".")).split("."),t).join(".")}function E(e){for(var t,n,r=[],s=0,o=e.length;s<o;)(t=e.charCodeAt(s++))>=55296&&t<=56319&&s<o?56320==(64512&(n=e.charCodeAt(s++)))?r.push(((1023&t)<<10)+(1023&n)+65536):(r.push(t),s--):r.push(t);return r}function A(e){return O(e,(function(e){var t="";return e>65535&&(t+=_((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=_(e)})).join("")}function M(e){return e-48<10?e-22:e-65<26?e-65:e-97<26?e-97:d}function P(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function R(e,t,n){var r=0;for(e=n?S(e/f):e>>1,e+=S(e/t);e>I*h>>1;r+=d)e=S(e/I);return S(r+(I+1)*e/(e+p))}function U(e){var t,n,r,s,o,a,i,c,p,f,v=[],b=e.length,w=0,C=m,I=g;for((n=e.lastIndexOf(y))<0&&(n=0),r=0;r<n;++r)e.charCodeAt(r)>=128&&k("not-basic"),v.push(e.charCodeAt(r));for(s=n>0?n+1:0;s<b;){for(o=w,a=1,i=d;s>=b&&k("invalid-input"),((c=M(e.charCodeAt(s++)))>=d||c>S((l-w)/a))&&k("overflow"),w+=c*a,!(c<(p=i<=I?u:i>=I+h?h:i-I));i+=d)a>S(l/(f=d-p))&&k("overflow"),a*=f;I=R(w-o,t=v.length+1,0==o),S(w/t)>l-C&&k("overflow"),C+=S(w/t),w%=t,v.splice(w++,0,C)}return A(v)}function j(e){var t,n,r,s,o,a,i,c,p,f,v,b,w,C,I,O=[];for(b=(e=E(e)).length,t=m,n=0,o=g,a=0;a<b;++a)(v=e[a])<128&&O.push(_(v));for(r=s=O.length,s&&O.push(y);r<b;){for(i=l,a=0;a<b;++a)(v=e[a])>=t&&v<i&&(i=v);for(i-t>S((l-n)/(w=r+1))&&k("overflow"),n+=(i-t)*w,t=i,a=0;a<b;++a)if((v=e[a])<t&&++n>l&&k("overflow"),v==t){for(c=n,p=d;!(c<(f=p<=o?u:p>=o+h?h:p-o));p+=d)I=c-f,C=d-f,O.push(_(P(f+I%C,0))),c=S(I/C);O.push(_(P(c,0))),o=R(n,w,r==s),n=0,++r}++n,++t}return O.join("")}function x(e){return T(e,(function(e){return v.test(e)?U(e.slice(4).toLowerCase()):e}))}function D(e){return T(e,(function(e){return b.test(e)?"xn--"+j(e):e}))}if(i={version:"1.4.1",ucs2:{decode:E,encode:A},decode:U,encode:j,toASCII:D,toUnicode:x},s&&o)if(t.exports==s)o.exports=i;else for(c in i)i.hasOwnProperty(c)&&(s[c]=i[c]);else r.punycode=i}(this)}).call(this)}).call(this,void 0!==Et?Et:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],52:[function(e,t,n){function r(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.exports=function(e,t,n,o){t=t||"&",n=n||"=";var a={};if("string"!=typeof e||0===e.length)return a;var i=/\+/g;e=e.split(t);var c=1e3;o&&"number"==typeof o.maxKeys&&(c=o.maxKeys);var l=e.length;c>0&&l>c&&(l=c);for(var d=0;d<l;++d){var u,h,p,f,g=e[d].replace(i,"%20"),m=g.indexOf(n);m>=0?(u=g.substr(0,m),h=g.substr(m+1)):(u=g,h=""),p=decodeURIComponent(u),f=decodeURIComponent(h),r(a,p)?s(a[p])?a[p].push(f):a[p]=[a[p],f]:a[p]=f}return a};var s=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],53:[function(e,t,n){var r=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,n,i){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"==typeof e?o(a(e),(function(a){var i=encodeURIComponent(r(a))+n;return s(e[a])?o(e[a],(function(e){return i+encodeURIComponent(r(e))})).join(t):i+encodeURIComponent(r(e[a]))})).join(t):i?encodeURIComponent(r(i))+n+encodeURIComponent(r(e)):""};var s=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function o(e,t){if(e.map)return e.map(t);for(var n=[],r=0;r<e.length;r++)n.push(t(e[r],r));return n}var a=Object.keys||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t}},{}],54:[function(e,t,n){n.decode=n.parse=e("./decode"),n.encode=n.stringify=e("./encode")},{"./decode":52,"./encode":53}],55:[function(e,t,n){function r(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}var s={};function o(e,t,n){function o(e,n,r){return"string"==typeof t?t:t(e,n,r)}n||(n=Error);var a=function(e){function t(t,n,r){return e.call(this,o(t,n,r))||this}return r(t,e),t}(n);a.prototype.name=n.name,a.prototype.code=e,s[e]=a}function a(e,t){if(Array.isArray(e)){var n=e.length;return e=e.map((function(e){return String(e)})),n>2?"one of ".concat(t," ").concat(e.slice(0,n-1).join(", "),", or ")+e[n-1]:2===n?"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 i(e,t,n){return e.substr(!n||n<0?0:+n,t.length)===t}function c(e,t,n){return(void 0===n||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}function l(e,t,n){return"number"!=typeof n&&(n=0),!(n+t.length>e.length)&&-1!==e.indexOf(t,n)}o("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError),o("ERR_INVALID_ARG_TYPE",(function(e,t,n){var r,s;if("string"==typeof t&&i(t,"not ")?(r="must not be",t=t.replace(/^not /,"")):r="must be",c(e," argument"))s="The ".concat(e," ").concat(r," ").concat(a(t,"type"));else{var o=l(e,".")?"property":"argument";s='The "'.concat(e,'" ').concat(o," ").concat(r," ").concat(a(t,"type"))}return s+=". Received type ".concat(typeof n)}),TypeError),o("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),o("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"})),o("ERR_STREAM_PREMATURE_CLOSE","Premature close"),o("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"})),o("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),o("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),o("ERR_STREAM_WRITE_AFTER_END","write after end"),o("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),o("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError),o("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),t.exports.codes=s},{}],56:[function(e,t,n){(function(n){(function(){var r=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=l;var s=e("./_stream_readable"),o=e("./_stream_writable");e("inherits")(l,s);for(var a=r(o.prototype),i=0;i<a.length;i++){var c=a[i];l.prototype[c]||(l.prototype[c]=o.prototype[c])}function l(e){if(!(this instanceof l))return new l(e);s.call(this,e),o.call(this,e),this.allowHalfOpen=!0,e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",d)))}function d(){this._writableState.ended||n.nextTick(u,this)}function u(e){e.end()}Object.defineProperty(l.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(l.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(l.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(l.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,n){t.exports=s;var r=e("./_stream_transform");function s(e){if(!(this instanceof s))return new s(e);r.call(this,e)}e("inherits")(s,r),s.prototype._transform=function(e,t,n){n(null,e)}},{"./_stream_transform":59,inherits:24}],58:[function(e,t,n){(function(n,r){(function(){var s;t.exports=E,E.ReadableState=T,e("events").EventEmitter;var o=function(e,t){return e.listeners(t).length},a=e("./internal/streams/stream"),i=e("buffer").Buffer,c=r.Uint8Array||function(){};function l(e){return i.from(e)}function d(e){return i.isBuffer(e)||e instanceof c}var u,h=e("util");u=h&&h.debuglog?h.debuglog("stream"):function(){};var p,f,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,C=b.ERR_STREAM_PUSH_AFTER_EOF,I=b.ERR_METHOD_NOT_IMPLEMENTED,S=b.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;e("inherits")(E,a);var _=y.errorOrDestroy,k=["error","close","destroy","pause","resume"];function O(e,t,n){if("function"==typeof e.prependListener)return e.prependListener(t,n);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}function T(t,n,r){s=s||e("./_stream_duplex"),t=t||{},"boolean"!=typeof r&&(r=n instanceof s),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=v(this,t,"readableHighWaterMark",r),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&&(p||(p=e("string_decoder/").StringDecoder),this.decoder=new p(t.encoding),this.encoding=t.encoding)}function E(t){if(s=s||e("./_stream_duplex"),!(this instanceof E))return new E(t);var n=this instanceof s;this._readableState=new T(t,this,n),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),a.call(this)}function A(e,t,n,r,s){u("readableAddChunk",t);var o,a=e._readableState;if(null===t)a.reading=!1,x(e,a);else if(s||(o=P(a,t)),o)_(e,o);else if(a.objectMode||t&&t.length>0)if("string"==typeof t||a.objectMode||Object.getPrototypeOf(t)===i.prototype||(t=l(t)),r)a.endEmitted?_(e,new S):M(e,a,t,!0);else if(a.ended)_(e,new C);else{if(a.destroyed)return!1;a.reading=!1,a.decoder&&!n?(t=a.decoder.write(t),a.objectMode||0!==t.length?M(e,a,t,!1):B(e,a)):M(e,a,t,!1)}else r||(a.reading=!1,B(e,a));return!a.ended&&(a.length<a.highWaterMark||0===a.length)}function M(e,t,n,r){t.flowing&&0===t.length&&!t.sync?(t.awaitDrain=0,e.emit("data",n)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&D(e)),B(e,t)}function P(e,t){var n;return d(t)||"string"==typeof t||void 0===t||e.objectMode||(n=new w("chunk",["string","Buffer","Uint8Array"],t)),n}Object.defineProperty(E.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),E.prototype.destroy=y.destroy,E.prototype._undestroy=y.undestroy,E.prototype._destroy=function(e,t){t(e)},E.prototype.push=function(e,t){var n,r=this._readableState;return r.objectMode?n=!0:"string"==typeof e&&((t=t||r.defaultEncoding)!==r.encoding&&(e=i.from(e,t),t=""),n=!0),A(this,e,t,!1,n)},E.prototype.unshift=function(e){return A(this,e,null,!0,!1)},E.prototype.isPaused=function(){return!1===this._readableState.flowing},E.prototype.setEncoding=function(t){p||(p=e("string_decoder/").StringDecoder);var n=new p(t);this._readableState.decoder=n,this._readableState.encoding=this._readableState.decoder.encoding;for(var r=this._readableState.buffer.head,s="";null!==r;)s+=n.write(r.data),r=r.next;return this._readableState.buffer.clear(),""!==s&&this._readableState.buffer.push(s),this._readableState.length=s.length,this};var R=1073741824;function U(e){return e>=R?e=R:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function j(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=U(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function x(e,t){if(u("onEofChunk"),!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?D(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,N(e)))}}function D(e){var t=e._readableState;u("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(u("emitReadable",t.flowing),t.emittedReadable=!0,n.nextTick(N,e))}function N(e){var t=e._readableState;u("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,Q(e)}function B(e,t){t.readingMore||(t.readingMore=!0,n.nextTick(q,e,t))}function q(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&0===t.length);){var n=t.length;if(u("maybeReadMore read 0"),e.read(0),n===t.length)break}t.readingMore=!1}function F(e){return function(){var t=e._readableState;u("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&o(e,"data")&&(t.flowing=!0,Q(e))}}function L(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 K(e){u("readable nexttick read 0"),e.read(0)}function $(e,t){t.resumeScheduled||(t.resumeScheduled=!0,n.nextTick(z,e,t))}function z(e,t){u("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),Q(e),t.flowing&&!t.reading&&e.read(0)}function Q(e){var t=e._readableState;for(u("flow",t.flowing);t.flowing&&null!==e.read(););}function V(e,t){return 0===t.length?null:(t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n);var n}function H(e){var t=e._readableState;u("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(W,t,e))}function W(e,t){if(u("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}function J(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}E.prototype.read=function(e){u("read",e),e=parseInt(e,10);var t=this._readableState,n=e;if(0!==e&&(t.emittedReadable=!1),0===e&&t.needReadable&&((0!==t.highWaterMark?t.length>=t.highWaterMark:t.length>0)||t.ended))return u("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?H(this):D(this),null;if(0===(e=j(e,t))&&t.ended)return 0===t.length&&H(this),null;var r,s=t.needReadable;return u("need readable",s),(0===t.length||t.length-e<t.highWaterMark)&&u("length less than watermark",s=!0),t.ended||t.reading?u("reading or ended",s=!1):s&&(u("do read"),t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=j(n,t))),null===(r=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),n!==e&&t.ended&&H(this)),null!==r&&this.emit("data",r),r},E.prototype._read=function(e){_(this,new I("_read()"))},E.prototype.pipe=function(e,t){var r=this,s=this._readableState;switch(s.pipesCount){case 0:s.pipes=e;break;case 1:s.pipes=[s.pipes,e];break;default:s.pipes.push(e)}s.pipesCount+=1,u("pipe count=%d opts=%j",s.pipesCount,t);var a=t&&!1===t.end||e===n.stdout||e===n.stderr?y:c;function i(e,t){u("onunpipe"),e===r&&t&&!1===t.hasUnpiped&&(t.hasUnpiped=!0,h())}function c(){u("onend"),e.end()}s.endEmitted?n.nextTick(a):r.once("end",a),e.on("unpipe",i);var l=F(r);e.on("drain",l);var d=!1;function h(){u("cleanup"),e.removeListener("close",g),e.removeListener("finish",m),e.removeListener("drain",l),e.removeListener("error",f),e.removeListener("unpipe",i),r.removeListener("end",c),r.removeListener("end",y),r.removeListener("data",p),d=!0,!s.awaitDrain||e._writableState&&!e._writableState.needDrain||l()}function p(t){u("ondata");var n=e.write(t);u("dest.write",n),!1===n&&((1===s.pipesCount&&s.pipes===e||s.pipesCount>1&&-1!==J(s.pipes,e))&&!d&&(u("false write response, pause",s.awaitDrain),s.awaitDrain++),r.pause())}function f(t){u("onerror",t),y(),e.removeListener("error",f),0===o(e,"error")&&_(e,t)}function g(){e.removeListener("finish",m),y()}function m(){u("onfinish"),e.removeListener("close",g),y()}function y(){u("unpipe"),r.unpipe(e)}return r.on("data",p),O(e,"error",f),e.once("close",g),e.once("finish",m),e.emit("pipe",r),s.flowing||(u("pipe resume"),r.resume()),e},E.prototype.unpipe=function(e){var t=this._readableState,n={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,n)),this;if(!e){var r=t.pipes,s=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o<s;o++)r[o].emit("unpipe",this,{hasUnpiped:!1});return this}var a=J(t.pipes,e);return-1===a||(t.pipes.splice(a,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,n)),this},E.prototype.on=function(e,t){var r=a.prototype.on.call(this,e,t),s=this._readableState;return"data"===e?(s.readableListening=this.listenerCount("readable")>0,!1!==s.flowing&&this.resume()):"readable"===e&&(s.endEmitted||s.readableListening||(s.readableListening=s.needReadable=!0,s.flowing=!1,s.emittedReadable=!1,u("on readable",s.length,s.reading),s.length?D(this):s.reading||n.nextTick(K,this))),r},E.prototype.addListener=E.prototype.on,E.prototype.removeListener=function(e,t){var r=a.prototype.removeListener.call(this,e,t);return"readable"===e&&n.nextTick(L,this),r},E.prototype.removeAllListeners=function(e){var t=a.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||n.nextTick(L,this),t},E.prototype.resume=function(){var e=this._readableState;return e.flowing||(u("resume"),e.flowing=!e.readableListening,$(this,e)),e.paused=!1,this},E.prototype.pause=function(){return u("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(u("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},E.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var s in e.on("end",(function(){if(u("wrapped end"),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(s){u("wrapped data"),n.decoder&&(s=n.decoder.write(s)),n.objectMode&&null==s||(n.objectMode||s&&s.length)&&(t.push(s)||(r=!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 o=0;o<k.length;o++)e.on(k[o],this.emit.bind(this,k[o]));return this._read=function(t){u("wrapped _read",t),r&&(r=!1,e.resume())},this},"function"==typeof Symbol&&(E.prototype[Symbol.asyncIterator]=function(){return void 0===f&&(f=e("./internal/streams/async_iterator")),f(this)}),Object.defineProperty(E.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(E.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(E.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),E._fromList=V,Object.defineProperty(E.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(E.from=function(t,n){return void 0===g&&(g=e("./internal/streams/from")),g(E,t,n)})}).call(this)}).call(this,e("_process"),void 0!==Et?Et:"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,n){t.exports=d;var r=e("../errors").codes,s=r.ERR_METHOD_NOT_IMPLEMENTED,o=r.ERR_MULTIPLE_CALLBACK,a=r.ERR_TRANSFORM_ALREADY_TRANSFORMING,i=r.ERR_TRANSFORM_WITH_LENGTH_0,c=e("./_stream_duplex");function l(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(null===r)return this.emit("error",new o);n.writechunk=null,n.writecb=null,null!=t&&this.push(t),r(e);var s=this._readableState;s.reading=!1,(s.needReadable||s.length<s.highWaterMark)&&this._read(s.highWaterMark)}function d(e){if(!(this instanceof d))return new d(e);c.call(this,e),this._transformState={afterTransform:l.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),this.on("prefinish",u)}function u(){var e=this;"function"!=typeof this._flush||this._readableState.destroyed?h(this,null,null):this._flush((function(t,n){h(e,t,n)}))}function h(e,t,n){if(t)return e.emit("error",t);if(null!=n&&e.push(n),e._writableState.length)throw new i;if(e._transformState.transforming)throw new a;return e.push(null)}e("inherits")(d,c),d.prototype.push=function(e,t){return this._transformState.needTransform=!1,c.prototype.push.call(this,e,t)},d.prototype._transform=function(e,t,n){n(new s("_transform()"))},d.prototype._write=function(e,t,n){var r=this._transformState;if(r.writecb=n,r.writechunk=e,r.writeencoding=t,!r.transforming){var s=this._readableState;(r.needTransform||s.needReadable||s.length<s.highWaterMark)&&this._read(s.highWaterMark)}},d.prototype._read=function(e){var t=this._transformState;null===t.writechunk||t.transforming?t.needTransform=!0:(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform))},d.prototype._destroy=function(e,t){c.prototype._destroy.call(this,e,(function(e){t(e)}))}},{"../errors":55,"./_stream_duplex":56,inherits:24}],60:[function(e,t,n){(function(n,r){(function(){function s(e){var t=this;this.next=null,this.entry=null,this.finish=function(){z(t,e)}}var o;t.exports=T,T.WritableState=O;var a={deprecate:e("util-deprecate")},i=e("./internal/streams/stream"),c=e("buffer").Buffer,l=r.Uint8Array||function(){};function d(e){return c.from(e)}function u(e){return c.isBuffer(e)||e instanceof l}var h,p=e("./internal/streams/destroy"),f=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,C=g.ERR_STREAM_NULL_VALUES,I=g.ERR_STREAM_WRITE_AFTER_END,S=g.ERR_UNKNOWN_ENCODING,_=p.errorOrDestroy;function k(){}function O(t,n,r){o=o||e("./_stream_duplex"),t=t||{},"boolean"!=typeof r&&(r=n instanceof o),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=f(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var a=!1===t.decodeStrings;this.decodeStrings=!a,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){x(n,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(t){var n=this instanceof(o=o||e("./_stream_duplex"));if(!n&&!h.call(T,this))return new T(t);this._writableState=new O(t,this,n),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)),i.call(this)}function E(e,t){var r=new I;_(e,r),n.nextTick(t,r)}function A(e,t,r,s){var o;return null===r?o=new C:"string"==typeof r||t.objectMode||(o=new m("chunk",["string","Buffer"],r)),!o||(_(e,o),n.nextTick(s,o),!1)}function M(e,t,n){return e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=c.from(t,n)),t}function P(e,t,n,r,s,o){if(!n){var a=M(t,r,s);r!==a&&(n=!0,s="buffer",r=a)}var i=t.objectMode?1:r.length;t.length+=i;var c=t.length<t.highWaterMark;if(c||(t.needDrain=!0),t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:s,isBuf:n,callback:o,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else R(e,t,!1,i,r,s,o);return c}function R(e,t,n,r,s,o,a){t.writelen=r,t.writecb=a,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new w("write")):n?e._writev(s,t.onwrite):e._write(s,o,t.onwrite),t.sync=!1}function U(e,t,r,s,o){--t.pendingcb,r?(n.nextTick(o,s),n.nextTick(K,e,t),e._writableState.errorEmitted=!0,_(e,s)):(o(s),e._writableState.errorEmitted=!0,_(e,s),K(e,t))}function j(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function x(e,t){var r=e._writableState,s=r.sync,o=r.writecb;if("function"!=typeof o)throw new v;if(j(r),t)U(e,r,s,t,o);else{var a=q(r)||e.destroyed;a||r.corked||r.bufferProcessing||!r.bufferedRequest||B(e,r),s?n.nextTick(D,e,r,a,o):D(e,r,a,o)}}function D(e,t,n,r){n||N(e,t),t.pendingcb--,r(),K(e,t)}function N(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}function B(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var r=t.bufferedRequestCount,o=new Array(r),a=t.corkedRequestsFree;a.entry=n;for(var i=0,c=!0;n;)o[i]=n,n.isBuf||(c=!1),n=n.next,i+=1;o.allBuffers=c,R(e,t,!0,t.length,o,"",a.finish),t.pendingcb++,t.lastBufferedRequest=null,a.next?(t.corkedRequestsFree=a.next,a.next=null):t.corkedRequestsFree=new s(t),t.bufferedRequestCount=0}else{for(;n;){var l=n.chunk,d=n.encoding,u=n.callback;if(R(e,t,!1,t.objectMode?1:l.length,l,d,u),n=n.next,t.bufferedRequestCount--,t.writing)break}null===n&&(t.lastBufferedRequest=null)}t.bufferedRequest=n,t.bufferProcessing=!1}function q(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function F(e,t){e._final((function(n){t.pendingcb--,n&&_(e,n),t.prefinished=!0,e.emit("prefinish"),K(e,t)}))}function L(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.pendingcb++,t.finalCalled=!0,n.nextTick(F,e,t)))}function K(e,t){var n=q(t);if(n&&(L(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"),t.autoDestroy))){var r=e._readableState;(!r||r.autoDestroy&&r.endEmitted)&&e.destroy()}return n}function $(e,t,r){t.ending=!0,K(e,t),r&&(t.finished?n.nextTick(r):e.once("finish",r)),t.ended=!0,e.writable=!1}function z(e,t,n){var r=e.entry;for(e.entry=null;r;){var s=r.callback;t.pendingcb--,s(n),r=r.next}t.corkedRequestsFree.next=e}e("inherits")(T,i),O.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(O.prototype,"buffer",{get:a.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(h=Function.prototype[Symbol.hasInstance],Object.defineProperty(T,Symbol.hasInstance,{value:function(e){return!!h.call(this,e)||this===T&&e&&e._writableState instanceof O}})):h=function(e){return e instanceof this},T.prototype.pipe=function(){_(this,new b)},T.prototype.write=function(e,t,n){var r=this._writableState,s=!1,o=!r.objectMode&&u(e);return o&&!c.isBuffer(e)&&(e=d(e)),"function"==typeof t&&(n=t,t=null),o?t="buffer":t||(t=r.defaultEncoding),"function"!=typeof n&&(n=k),r.ending?E(this,n):(o||A(this,r,e,n))&&(r.pendingcb++,s=P(this,r,o,e,t,n)),s},T.prototype.cork=function(){this._writableState.corked++},T.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.bufferProcessing||!e.bufferedRequest||B(this,e))},T.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(T.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(T.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),T.prototype._write=function(e,t,n){n(new y("_write()"))},T.prototype._writev=null,T.prototype.end=function(e,t,n){var r=this._writableState;return"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||$(this,r,n),this},Object.defineProperty(T.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(T.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),T.prototype.destroy=p.destroy,T.prototype._undestroy=p.undestroy,T.prototype._destroy=function(e,t){t(e)}}).call(this)}).call(this,e("_process"),void 0!==Et?Et:"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,n){(function(n){(function(){var r;function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var o=e("./end-of-stream"),a=Symbol("lastResolve"),i=Symbol("lastReject"),c=Symbol("error"),l=Symbol("ended"),d=Symbol("lastPromise"),u=Symbol("handlePromise"),h=Symbol("stream");function p(e,t){return{value:e,done:t}}function f(e){var t=e[a];if(null!==t){var n=e[h].read();null!==n&&(e[d]=null,e[a]=null,e[i]=null,t(p(n,!1)))}}function g(e){n.nextTick(f,e)}function m(e,t){return function(n,r){e.then((function(){t[l]?n(p(void 0,!0)):t[u](n,r)}),r)}}var y=Object.getPrototypeOf((function(){})),v=Object.setPrototypeOf((s(r={get stream(){return this[h]},next:function(){var e=this,t=this[c];if(null!==t)return Promise.reject(t);if(this[l])return Promise.resolve(p(void 0,!0));if(this[h].destroyed)return new Promise((function(t,r){n.nextTick((function(){e[c]?r(e[c]):t(p(void 0,!0))}))}));var r,s=this[d];if(s)r=new Promise(m(s,this));else{var o=this[h].read();if(null!==o)return Promise.resolve(p(o,!1));r=new Promise(this[u])}return this[d]=r,r}},Symbol.asyncIterator,(function(){return this})),s(r,"return",(function(){var e=this;return new Promise((function(t,n){e[h].destroy(null,(function(e){e?n(e):t(p(void 0,!0))}))}))})),r),y),b=function(e){var t,n=Object.create(v,(s(t={},h,{value:e,writable:!0}),s(t,a,{value:null,writable:!0}),s(t,i,{value:null,writable:!0}),s(t,c,{value:null,writable:!0}),s(t,l,{value:e._readableState.endEmitted,writable:!0}),s(t,u,{value:function(e,t){var r=n[h].read();r?(n[d]=null,n[a]=null,n[i]=null,e(p(r,!1))):(n[a]=e,n[i]=t)},writable:!0}),t));return n[d]=null,o(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=n[i];return null!==t&&(n[d]=null,n[a]=null,n[i]=null,t(e)),void(n[c]=e)}var r=n[a];null!==r&&(n[d]=null,n[a]=null,n[i]=null,r(p(void 0,!0))),n[l]=!0})),e.on("readable",g.bind(null,n)),n};t.exports=b}).call(this)}).call(this,e("_process"))},{"./end-of-stream":64,_process:50}],62:[function(e,t,n){function r(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function s(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?r(Object(n),!0).forEach((function(t){o(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function c(e,t,n){return t&&i(e.prototype,t),n&&i(e,n),e}var l=e("buffer").Buffer,d=e("util").inspect,u=d&&d.custom||"inspect";function h(e,t,n){l.prototype.copy.call(e,t,n)}t.exports=function(){function e(){a(this,e),this.head=null,this.tail=null,this.length=0}return c(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,n=""+t.data;t=t.next;)n+=e+t.data;return n}},{key:"concat",value:function(e){if(0===this.length)return l.alloc(0);for(var t=l.allocUnsafe(e>>>0),n=this.head,r=0;n;)h(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:"consume",value:function(e,t){var n;return e<this.head.data.length?(n=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):n=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),n}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(e){var t=this.head,n=1,r=t.data;for(e-=r.length;t=t.next;){var s=t.data,o=e>s.length?s.length:e;if(o===s.length?r+=s:r+=s.slice(0,e),0==(e-=o)){o===s.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=s.slice(o));break}++n}return this.length-=n,r}},{key:"_getBuffer",value:function(e){var t=l.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var s=n.data,o=e>s.length?s.length:e;if(s.copy(t,t.length-e,0,o),0==(e-=o)){o===s.length?(++r,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=s.slice(o));break}++r}return this.length-=r,t}},{key:u,value:function(e,t){return d(this,s({},t,{depth:0,customInspect:!1}))}}]),e}()},{buffer:17,util:16}],63:[function(e,t,n){(function(e){(function(){function n(t,n){var o=this,i=this._readableState&&this._readableState.destroyed,c=this._writableState&&this._writableState.destroyed;return i||c?(n?n(t):t&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,e.nextTick(a,this,t)):e.nextTick(a,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,(function(t){!n&&t?o._writableState?o._writableState.errorEmitted?e.nextTick(s,o):(o._writableState.errorEmitted=!0,e.nextTick(r,o,t)):e.nextTick(r,o,t):n?(e.nextTick(s,o),n(t)):e.nextTick(s,o)})),this)}function r(e,t){a(e,t),s(e)}function s(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function o(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function a(e,t){e.emit("error",t)}function i(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit("error",t)}t.exports={destroy:n,undestroy:o,errorOrDestroy:i}}).call(this)}).call(this,e("_process"))},{_process:50}],64:[function(e,t,n){var r=e("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;function s(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=new Array(n),s=0;s<n;s++)r[s]=arguments[s];e.apply(this,r)}}}function o(){}function a(e){return e.setHeader&&"function"==typeof e.abort}function i(e,t,n){if("function"==typeof t)return i(e,null,t);t||(t={}),n=s(n||o);var c=t.readable||!1!==t.readable&&e.readable,l=t.writable||!1!==t.writable&&e.writable,d=function(){e.writable||h()},u=e._writableState&&e._writableState.finished,h=function(){l=!1,u=!0,c||n.call(e)},p=e._readableState&&e._readableState.endEmitted,f=function(){c=!1,p=!0,l||n.call(e)},g=function(t){n.call(e,t)},m=function(){var t;return c&&!p?(e._readableState&&e._readableState.ended||(t=new r),n.call(e,t)):l&&!u?(e._writableState&&e._writableState.ended||(t=new r),n.call(e,t)):void 0},y=function(){e.req.on("finish",h)};return a(e)?(e.on("complete",h),e.on("abort",m),e.req?y():e.on("request",y)):l&&!e._writableState&&(e.on("end",d),e.on("close",d)),e.on("end",f),e.on("finish",h),!1!==t.error&&e.on("error",g),e.on("close",m),function(){e.removeListener("complete",h),e.removeListener("abort",m),e.removeListener("request",y),e.req&&e.req.removeListener("finish",h),e.removeListener("end",d),e.removeListener("close",d),e.removeListener("finish",h),e.removeListener("end",f),e.removeListener("error",g),e.removeListener("close",m)}}t.exports=i},{"../../../errors":55}],65:[function(e,t,n){t.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],66:[function(e,t,n){var r;function s(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var o=e("../../../errors").codes,a=o.ERR_MISSING_ARGS,i=o.ERR_STREAM_DESTROYED;function c(e){if(e)throw e}function l(e){return e.setHeader&&"function"==typeof e.abort}function d(t,n,o,a){a=s(a);var c=!1;t.on("close",(function(){c=!0})),void 0===r&&(r=e("./end-of-stream")),r(t,{readable:n,writable:o},(function(e){if(e)return a(e);c=!0,a()}));var d=!1;return function(e){if(!c&&!d)return d=!0,l(t)?t.abort():"function"==typeof t.destroy?t.destroy():void a(e||new i("pipe"))}}function u(e){e()}function h(e,t){return e.pipe(t)}function p(e){return e.length?"function"!=typeof e[e.length-1]?c:e.pop():c}function f(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];var r,s=p(t);if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new a("streams");var o=t.map((function(e,n){var a=n<t.length-1;return d(e,a,n>0,(function(e){r||(r=e),e&&o.forEach(u),a||(o.forEach(u),s(r))}))}));return t.reduce(h)}t.exports=f},{"../../../errors":55,"./end-of-stream":64}],67:[function(e,t,n){var r=e("../../../errors").codes.ERR_INVALID_OPT_VALUE;function s(e,t,n){return null!=e.highWaterMark?e.highWaterMark:t?e[n]:null}function o(e,t,n,o){var a=s(t,o,n);if(null!=a){if(!isFinite(a)||Math.floor(a)!==a||a<0)throw new r(o?n:"highWaterMark",a);return Math.floor(a)}return e.objectMode?16:16384}t.exports={getHighWaterMark:o}},{"../../../errors":55}],68:[function(e,t,n){t.exports=e("events").EventEmitter},{events:22}],69:[function(e,t,n){(n=t.exports=e("./lib/_stream_readable.js")).Stream=n,n.Readable=n,n.Writable=e("./lib/_stream_writable.js"),n.Duplex=e("./lib/_stream_duplex.js"),n.Transform=e("./lib/_stream_transform.js"),n.PassThrough=e("./lib/_stream_passthrough.js"),n.finished=e("./lib/internal/streams/end-of-stream.js"),n.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,n){function r(e,t,n){var r=this;this._callback=e,this._args=n,this._interval=setInterval(e,t,this._args),this.reschedule=function(e){e||(e=r._interval),r._interval&&clearInterval(r._interval),r._interval=setInterval(r._callback,e,r._args)},this.clear=function(){r._interval&&(clearInterval(r._interval),r._interval=void 0)},this.destroy=function(){r._interval&&clearInterval(r._interval),r._callback=void 0,r._interval=void 0,r._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 r(arguments[0],arguments[1],e)}t.exports=s},{}],71:[function(e,t,n){t.exports=e("./index.js")()},{"./index.js":72}],72:[function(e,t,n){(function(e){(function(){function n(t){return t instanceof e?e.from(t):new t.constructor(t.buffer.slice(),t.byteOffset,t.length)}function r(e){return(e=e||{}).circles?s(e):e.proto?o:r;function t(e,t){for(var r=Object.keys(e),s=new Array(r.length),o=0;o<r.length;o++){var a=r[o],i=e[a];"object"!=typeof i||null===i?s[a]=i:i instanceof Date?s[a]=new Date(i):ArrayBuffer.isView(i)?s[a]=n(i):s[a]=t(i)}return s}function r(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return t(e,r);if(e instanceof Map)return new Map(t(Array.from(e),r));if(e instanceof Set)return new Set(t(Array.from(e),r));var s={};for(var o in e)if(!1!==Object.hasOwnProperty.call(e,o)){var a=e[o];"object"!=typeof a||null===a?s[o]=a:a instanceof Date?s[o]=new Date(a):a instanceof Map?s[o]=new Map(t(Array.from(a),r)):a instanceof Set?s[o]=new Set(t(Array.from(a),r)):ArrayBuffer.isView(a)?s[o]=n(a):s[o]=r(a)}return s}function o(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return t(e,o);if(e instanceof Map)return new Map(t(Array.from(e),o));if(e instanceof Set)return new Set(t(Array.from(e),o));var r={};for(var s in e){var a=e[s];"object"!=typeof a||null===a?r[s]=a:a instanceof Date?r[s]=new Date(a):a instanceof Map?r[s]=new Map(t(Array.from(a),o)):a instanceof Set?r[s]=new Set(t(Array.from(a),o)):ArrayBuffer.isView(a)?r[s]=n(a):r[s]=o(a)}return r}}function s(e){var t=[],r=[];return e.proto?a:o;function s(e,s){for(var o=Object.keys(e),a=new Array(o.length),i=0;i<o.length;i++){var c=o[i],l=e[c];if("object"!=typeof l||null===l)a[c]=l;else if(l instanceof Date)a[c]=new Date(l);else if(ArrayBuffer.isView(l))a[c]=n(l);else{var d=t.indexOf(l);a[c]=-1!==d?r[d]:s(l)}}return a}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 a={};for(var i in t.push(e),r.push(a),e)if(!1!==Object.hasOwnProperty.call(e,i)){var c=e[i];if("object"!=typeof c||null===c)a[i]=c;else if(c instanceof Date)a[i]=new Date(c);else if(c instanceof Map)a[i]=new Map(s(Array.from(c),o));else if(c instanceof Set)a[i]=new Set(s(Array.from(c),o));else if(ArrayBuffer.isView(c))a[i]=n(c);else{var l=t.indexOf(c);a[i]=-1!==l?r[l]:o(c)}}return t.pop(),r.pop(),a}function a(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return s(e,a);if(e instanceof Map)return new Map(s(Array.from(e),a));if(e instanceof Set)return new Set(s(Array.from(e),a));var o={};for(var i in t.push(e),r.push(o),e){var c=e[i];if("object"!=typeof c||null===c)o[i]=c;else if(c instanceof Date)o[i]=new Date(c);else if(c instanceof Map)o[i]=new Map(s(Array.from(c),a));else if(c instanceof Set)o[i]=new Set(s(Array.from(c),a));else if(ArrayBuffer.isView(c))o[i]=n(c);else{var l=t.indexOf(c);o[i]=-1!==l?r[l]:a(c)}}return t.pop(),r.pop(),o}}t.exports=r}).call(this)}).call(this,e("buffer").Buffer)},{buffer:17}],73:[function(e,t,n){
|
|
4
4
|
/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
|
|
5
|
-
var r=e("buffer"),o=r.Buffer;function s(e,t){for(var n in e)t[n]=e[n]}function a(e,t,n){return o(e,t,n)}o.from&&o.alloc&&o.allocUnsafe&&o.allocUnsafeSlow?t.exports=r:(s(r,n),n.Buffer=a),a.prototype=Object.create(o.prototype),s(o,a),a.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return o(e,t,n)},a.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=o(e);return void 0!==t?"string"==typeof n?r.fill(t,n):r.fill(t):r.fill(0),r},a.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return o(e)},a.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)}},{buffer:17}],74:[function(e,t,n){function r(e){var t=e._readableState;return t?t.objectMode||"number"==typeof e._duplexState?e.read():e.read(o(t)):null}function o(e){return e.buffer.length?e.buffer.head?e.buffer.head.data.length:e.buffer[0].length:e.length}t.exports=r},{}],75:[function(e,t,n){var r=e("safe-buffer").Buffer,o=r.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 s(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}function a(e){var t=s(e);if("string"!=typeof t&&(r.isEncoding===o||!o(e)))throw new Error("Unknown encoding: "+e);return t||e}function i(e){var t;switch(this.encoding=a(e),this.encoding){case"utf16le":this.text=f,this.end=g,t=4;break;case"utf8":this.fillLast=u,t=4;break;case"base64":this.text=m,this.end=y,t=3;break;default:return this.write=v,void(this.end=b)}this.lastNeed=0,this.lastTotal=0,this.lastChar=r.allocUnsafe(t)}function c(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function l(e,t,n){var r=t.length-1;if(r<n)return 0;var o=c(t[r]);return o>=0?(o>0&&(e.lastNeed=o-1),o):--r<n||-2===o?0:(o=c(t[r]))>=0?(o>0&&(e.lastNeed=o-2),o):--r<n||-2===o?0:(o=c(t[r]))>=0?(o>0&&(2===o?o=0:e.lastNeed=o-3),o):0}function d(e,t,n){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}function u(e){var t=this.lastTotal-this.lastNeed,n=d(this,e);return void 0!==n?n: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 n=l(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString("utf8",t,r)}function p(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t}function f(e,t){if((e.length-t)%2==0){var n=e.toString("utf16le",t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}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 n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function m(e,t){var n=(e.length-t)%3;return 0===n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1===n?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-n))}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):""}n.StringDecoder=i,i.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||""},i.prototype.end=p,i.prototype.text=h,i.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,n){var r=e("punycode"),o=e("./util");function s(){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}n.parse=w,n.resolve=I,n.resolveObject=S,n.format=C,n.Url=s;var a=/^([a-z0-9.+-]+:)/i,i=/:[0-9]*$/,c=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,l=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),d=["'"].concat(l),u=["%","/","?",";","#"].concat(d),h=["/","?","#"],p=255,f=/^[+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,n){if(e&&o.isObject(e)&&e instanceof s)return e;var r=new s;return r.parse(e,t,n),r}function C(e){return o.isString(e)&&(e=w(e)),e instanceof s?e.format():s.prototype.format.call(e)}function I(e,t){return w(e,!1,!0).resolve(t)}function S(e,t){return e?w(e,!1,!0).resolveObject(t):t}s.prototype.parse=function(e,t,n){if(!o.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var s=e.indexOf("?"),i=-1!==s&&s<e.indexOf("#")?"?":"#",l=e.split(i),w=/\\/g;l[0]=l[0].replace(w,"/");var C=e=l.join(i);if(C=C.trim(),!n&&1===e.split("#").length){var I=c.exec(C);if(I)return this.path=C,this.href=C,this.pathname=I[1],I[2]?(this.search=I[2],this.query=t?b.parse(this.search.substr(1)):this.search.substr(1)):t&&(this.search="",this.query={}),this}var S=a.exec(C);if(S){var _=(S=S[0]).toLowerCase();this.protocol=_,C=C.substr(S.length)}if(n||S||C.match(/^\/\/[^@\/]+@[^@\/]+/)){var k="//"===C.substr(0,2);!k||S&&y[S]||(C=C.substr(2),this.slashes=!0)}if(!y[S]&&(k||S&&!v[S])){for(var O,T,A=-1,E=0;E<h.length;E++)-1!==(M=C.indexOf(h[E]))&&(-1===A||M<A)&&(A=M);for(-1!==(T=-1===A?C.lastIndexOf("@"):C.lastIndexOf("@",A))&&(O=C.slice(0,T),C=C.slice(T+1),this.auth=decodeURIComponent(O)),A=-1,E=0;E<u.length;E++){var M;-1!==(M=C.indexOf(u[E]))&&(-1===A||M<A)&&(A=M)}-1===A&&(A=C.length),this.host=C.slice(0,A),C=C.slice(A),this.parseHost(),this.hostname=this.hostname||"";var P="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!P)for(var R=this.hostname.split(/\./),U=(E=0,R.length);E<U;E++){var j=R[E];if(j&&!j.match(f)){for(var x="",D=0,N=j.length;D<N;D++)j.charCodeAt(D)>127?x+="x":x+=j[D];if(!x.match(f)){var B=R.slice(0,E),q=R.slice(E+1),F=j.match(g);F&&(B.push(F[1]),q.unshift(F[2])),q.length&&(C="/"+q.join(".")+C),this.hostname=B.join(".");break}}}this.hostname.length>p?this.hostname="":this.hostname=this.hostname.toLowerCase(),P||(this.hostname=r.toASCII(this.hostname));var L=this.port?":"+this.port:"",K=this.hostname||"";this.host=K+L,this.href+=this.host,P&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==C[0]&&(C="/"+C))}if(!m[_])for(E=0,U=d.length;E<U;E++){var $=d[E];if(-1!==C.indexOf($)){var z=encodeURIComponent($);z===$&&(z=escape($)),C=C.split($).join(z)}}var Q=C.indexOf("#");-1!==Q&&(this.hash=C.substr(Q),C=C.slice(0,Q));var V=C.indexOf("?");if(-1!==V?(this.search=C.substr(V),this.query=C.substr(V+1),t&&(this.query=b.parse(this.query)),C=C.slice(0,V)):t&&(this.search="",this.query={}),C&&(this.pathname=C),v[_]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){L=this.pathname||"";var H=this.search||"";this.path=L+H}return this.href=this.format(),this},s.prototype.format=function(){var e=this.auth||"";e&&(e=(e=encodeURIComponent(e)).replace(/%3A/i,":"),e+="@");var t=this.protocol||"",n=this.pathname||"",r=this.hash||"",s=!1,a="";this.host?s=e+this.host:this.hostname&&(s=e+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(s+=":"+this.port)),this.query&&o.isObject(this.query)&&Object.keys(this.query).length&&(a=b.stringify(this.query));var i=this.search||a&&"?"+a||"";return t&&":"!==t.substr(-1)&&(t+=":"),this.slashes||(!t||v[t])&&!1!==s?(s="//"+(s||""),n&&"/"!==n.charAt(0)&&(n="/"+n)):s||(s=""),r&&"#"!==r.charAt(0)&&(r="#"+r),i&&"?"!==i.charAt(0)&&(i="?"+i),t+s+(n=n.replace(/[?#]/g,(function(e){return encodeURIComponent(e)})))+(i=i.replace("#","%23"))+r},s.prototype.resolve=function(e){return this.resolveObject(w(e,!1,!0)).format()},s.prototype.resolveObject=function(e){if(o.isString(e)){var t=new s;t.parse(e,!1,!0),e=t}for(var n=new s,r=Object.keys(this),a=0;a<r.length;a++){var i=r[a];n[i]=this[i]}if(n.hash=e.hash,""===e.href)return n.href=n.format(),n;if(e.slashes&&!e.protocol){for(var c=Object.keys(e),l=0;l<c.length;l++){var d=c[l];"protocol"!==d&&(n[d]=e[d])}return v[n.protocol]&&n.hostname&&!n.pathname&&(n.path=n.pathname="/"),n.href=n.format(),n}if(e.protocol&&e.protocol!==n.protocol){if(!v[e.protocol]){for(var u=Object.keys(e),h=0;h<u.length;h++){var p=u[h];n[p]=e[p]}return n.href=n.format(),n}if(n.protocol=e.protocol,e.host||y[e.protocol])n.pathname=e.pathname;else{for(var f=(e.pathname||"").split("/");f.length&&!(e.host=f.shift()););e.host||(e.host=""),e.hostname||(e.hostname=""),""!==f[0]&&f.unshift(""),f.length<2&&f.unshift(""),n.pathname=f.join("/")}if(n.search=e.search,n.query=e.query,n.host=e.host||"",n.auth=e.auth,n.hostname=e.hostname||e.host,n.port=e.port,n.pathname||n.search){var g=n.pathname||"",m=n.search||"";n.path=g+m}return n.slashes=n.slashes||e.slashes,n.href=n.format(),n}var b=n.pathname&&"/"===n.pathname.charAt(0),w=e.host||e.pathname&&"/"===e.pathname.charAt(0),C=w||b||n.host&&e.pathname,I=C,S=n.pathname&&n.pathname.split("/")||[],_=(f=e.pathname&&e.pathname.split("/")||[],n.protocol&&!v[n.protocol]);if(_&&(n.hostname="",n.port=null,n.host&&(""===S[0]?S[0]=n.host:S.unshift(n.host)),n.host="",e.protocol&&(e.hostname=null,e.port=null,e.host&&(""===f[0]?f[0]=e.host:f.unshift(e.host)),e.host=null),C=C&&(""===f[0]||""===S[0])),w)n.host=e.host||""===e.host?e.host:n.host,n.hostname=e.hostname||""===e.hostname?e.hostname:n.hostname,n.search=e.search,n.query=e.query,S=f;else if(f.length)S||(S=[]),S.pop(),S=S.concat(f),n.search=e.search,n.query=e.query;else if(!o.isNullOrUndefined(e.search))return _&&(n.hostname=n.host=S.shift(),(E=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=E.shift(),n.host=n.hostname=E.shift())),n.search=e.search,n.query=e.query,o.isNull(n.pathname)&&o.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n;if(!S.length)return n.pathname=null,n.search?n.path="/"+n.search:n.path=null,n.href=n.format(),n;for(var k=S.slice(-1)[0],O=(n.host||e.host||S.length>1)&&("."===k||".."===k)||""===k,T=0,A=S.length;A>=0;A--)"."===(k=S[A])?S.splice(A,1):".."===k?(S.splice(A,1),T++):T&&(S.splice(A,1),T--);if(!C&&!I)for(;T--;T)S.unshift("..");!C||""===S[0]||S[0]&&"/"===S[0].charAt(0)||S.unshift(""),O&&"/"!==S.join("/").substr(-1)&&S.push("");var E,M=""===S[0]||S[0]&&"/"===S[0].charAt(0);return _&&(n.hostname=n.host=M?"":S.length?S.shift():"",(E=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=E.shift(),n.host=n.hostname=E.shift())),(C=C||n.host&&S.length)&&!M&&S.unshift(""),S.length?n.pathname=S.join("/"):(n.pathname=null,n.path=null),o.isNull(n.pathname)&&o.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n},s.prototype.parseHost=function(){var e=this.host,t=i.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,n){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,n){(function(e){(function(){function n(e,t){if(r("noDeprecation"))return e;var n=!1;function o(){if(!n){if(r("throwDeprecation"))throw new Error(t);r("traceDeprecation")?console.trace(t):console.warn(t),n=!0}return e.apply(this,arguments)}return o}function r(t){try{if(!e.localStorage)return!1}catch(e){return!1}var n=e.localStorage[t];return null!=n&&"true"===String(n).toLowerCase()}t.exports=n}).call(this)}).call(this,void 0!==At?At:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],79:[function(e,t,n){function r(e,t){if(e&&t)return r(e)(t);if("function"!=typeof e)throw new TypeError("need wrapper function");return Object.keys(e).forEach((function(t){n[t]=e[t]})),n;function n(){for(var t=new Array(arguments.length),n=0;n<t.length;n++)t[n]=arguments[n];var r=e.apply(this,t),o=t[t.length-1];return"function"==typeof r&&r!==o&&Object.keys(o).forEach((function(e){r[e]=o[e]})),r}}t.exports=r},{}],80:[function(e,t,n){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,n){t.exports=o;var r=Object.prototype.hasOwnProperty;function o(){for(var e={},t=0;t<arguments.length;t++){var n=arguments[t];for(var o in n)r.call(n,o)&&(e[o]=n[o])}return e}},{}],82:[function(e,t,n){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,n){function r(e){var t=this;if(t instanceof r||(t=new r),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 n=0,o=arguments.length;n<o;n++)t.push(arguments[n]);return t}function o(e,t,n){var r=t===e.head?new i(n,null,t,e):new i(n,t,t.next,e);return null===r.next&&(e.tail=r),null===r.prev&&(e.head=r),e.length++,r}function s(e,t){e.tail=new i(t,e.tail,null,e),e.head||(e.head=e.tail),e.length++}function a(e,t){e.head=new i(t,null,e.head,e),e.tail||(e.tail=e.head),e.length++}function i(e,t,n,r){if(!(this instanceof i))return new i(e,t,n,r);this.list=r,this.value=e,t?(t.next=this,this.prev=t):this.prev=null,n?(n.prev=this,this.next=n):this.next=null}t.exports=r,r.Node=i,r.create=r,r.prototype.removeNode=function(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");var t=e.next,n=e.prev;return t&&(t.prev=n),n&&(n.next=t),e===this.head&&(this.head=t),e===this.tail&&(this.tail=n),e.list.length--,e.next=null,e.prev=null,e.list=null,t},r.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++}},r.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++}},r.prototype.push=function(){for(var e=0,t=arguments.length;e<t;e++)s(this,arguments[e]);return this.length},r.prototype.unshift=function(){for(var e=0,t=arguments.length;e<t;e++)a(this,arguments[e]);return this.length},r.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}},r.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}},r.prototype.forEach=function(e,t){t=t||this;for(var n=this.head,r=0;null!==n;r++)e.call(t,n.value,r,this),n=n.next},r.prototype.forEachReverse=function(e,t){t=t||this;for(var n=this.tail,r=this.length-1;null!==n;r--)e.call(t,n.value,r,this),n=n.prev},r.prototype.get=function(e){for(var t=0,n=this.head;null!==n&&t<e;t++)n=n.next;if(t===e&&null!==n)return n.value},r.prototype.getReverse=function(e){for(var t=0,n=this.tail;null!==n&&t<e;t++)n=n.prev;if(t===e&&null!==n)return n.value},r.prototype.map=function(e,t){t=t||this;for(var n=new r,o=this.head;null!==o;)n.push(e.call(t,o.value,this)),o=o.next;return n},r.prototype.mapReverse=function(e,t){t=t||this;for(var n=new r,o=this.tail;null!==o;)n.push(e.call(t,o.value,this)),o=o.prev;return n},r.prototype.reduce=function(e,t){var n,r=this.head;if(arguments.length>1)n=t;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");r=this.head.next,n=this.head.value}for(var o=0;null!==r;o++)n=e(n,r.value,o),r=r.next;return n},r.prototype.reduceReverse=function(e,t){var n,r=this.tail;if(arguments.length>1)n=t;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");r=this.tail.prev,n=this.tail.value}for(var o=this.length-1;null!==r;o--)n=e(n,r.value,o),r=r.prev;return n},r.prototype.toArray=function(){for(var e=new Array(this.length),t=0,n=this.head;null!==n;t++)e[t]=n.value,n=n.next;return e},r.prototype.toArrayReverse=function(){for(var e=new Array(this.length),t=0,n=this.tail;null!==n;t++)e[t]=n.value,n=n.prev;return e},r.prototype.slice=function(e,t){(t=t||this.length)<0&&(t+=this.length),(e=e||0)<0&&(e+=this.length);var n=new r;if(t<e||t<0)return n;e<0&&(e=0),t>this.length&&(t=this.length);for(var o=0,s=this.head;null!==s&&o<e;o++)s=s.next;for(;null!==s&&o<t;o++,s=s.next)n.push(s.value);return n},r.prototype.sliceReverse=function(e,t){(t=t||this.length)<0&&(t+=this.length),(e=e||0)<0&&(e+=this.length);var n=new r;if(t<e||t<0)return n;e<0&&(e=0),t>this.length&&(t=this.length);for(var o=this.length,s=this.tail;null!==s&&o>t;o--)s=s.prev;for(;null!==s&&o>e;o--,s=s.prev)n.push(s.value);return n},r.prototype.splice=function(e,t,...n){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);for(var r=0,s=this.head;null!==s&&r<e;r++)s=s.next;var a=[];for(r=0;s&&r<t;r++)a.push(s.value),s=this.removeNode(s);for(null===s&&(s=this.tail),s!==this.head&&s!==this.tail&&(s=s.prev),r=0;r<n.length;r++)s=o(this,s,n[r]);return a},r.prototype.reverse=function(){for(var e=this.head,t=this.tail,n=e;null!==n;n=n.prev){var r=n.prev;n.prev=n.next,n.next=r}return this.head=t,this.tail=e,this};try{e("./iterator.js")(r)}catch(e){}},{"./iterator.js":82}]},{},[12])(12);var Rt=Et(Pt.exports);class Ut{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 jt=()=>"undefined"!=typeof window&&window.localStorage?window:{localStorage:new Ut},xt=()=>b.default.v4().toString();let Dt=0;if("undefined"!=typeof BroadcastChannel&&"undefined"!=typeof window){const e=xt(),t={},n=new BroadcastChannel("amity_ts_sdk");let r;n.postMessage({type:"startup",tabId:e}),n.onmessage=({data:o})=>{o.tabId!==e&&("startup"===o.type&&n.postMessage({type:"identify",tabId:e,tabIndex:Dt}),"identify"===o.type&&void 0!==o.tabIndex&&o.tabId&&(t[o.tabId]=o.tabIndex,r||(r=setTimeout((()=>{const e=Object.values(t).sort();e&&0!==e.length&&(Dt=e.reduce(((e,t)=>e<t?e:t+1),0))}),15))))}}const Nt=async()=>{var e;const t=`${null!==(e=we().prefixDeviceIdKey)&&void 0!==e?e:""}#deviceId`,n=await(async e=>{if("undefined"!=typeof navigator&&"ReactNative"===navigator.product)return await v.default.getItem(e);return new Promise((t=>{t(jt().localStorage.getItem(e))}))})(t);if(n)return n;const r=`ascWebSdk#${xt()}`;return await(async(e,t)=>"undefined"!=typeof navigator&&"ReactNative"===navigator.product?(await v.default.setItem(e,t),!0):new Promise((n=>{jt().localStorage.setItem(e,t),n(!0)})))(t,r),r},Bt=()=>{const e=(()=>{var e,t;return(null===(e=mt.versions)||void 0===e?void 0:e.node)?mt.versions.node:navigator?`${navigator.product.toLowerCase()}#${null!==(t=navigator.userAgent)&&void 0!==t?t:"unknown_agent"}`:"unknown_model"})();return{kind:"web",model:e,sdkVersion:U}},qt=1e3;var Ft;!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"}(Ft||(Ft={}));const Lt=e=>{let t;return{connect:async function(n){const r=await(async e=>`mqttjs_${await Nt()}_${e}_${Dt}`)(n.userId);return t&&(t.removeAllListeners(),t.end(!0)),t=Rt.connect(e,function(e){return Object.assign({clean:!1,clientId:`mqttjs_ + ${Math.random().toString(16).substring(2,10)}`,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:qt,will:{topic:"WillMsg",payload:"Connection Closed abnormally..!",qos:0,retain:!1},resubscribe:!0},e)}({username:n.userId,password:n.accessToken,clientId:r})),t.on("connect",(()=>{t.options.reconnectPeriod=qt,(()=>{const e=[pt(lt()),pt(dt()),pt(ut()),pt(ht()),pt(at(Qe())),pt(ct())]})()})),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||qt),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,n){null==t||t.on(e,n)},once(e,n){null==t||t.once(e,n)},off(e,n){void 0!==n?null==t||t.off(e,n):null==t||t.removeAllListeners(e)},removeAllListeners(){null==t||t.removeAllListeners()},subscribe(e,n){const r=(t,r)=>{var o;if(t||128===(null===(o=r[0])||void 0===o?void 0:o.qos)){const r=t?new fe(t.message,8e5,"error"):new me(8e5,"error");console.warn(`Failed to subscribe to topic ${e}`,r),null==n||n(r)}else console.log(`Subscribed to topic ${e}`),null==n||n()};return t?t.subscribe(e,{qos:0},r):r(new Error("No connection to broker"),[]),()=>null==t?void 0:t.unsubscribe(e)},unsubscribe(e){null==t||t.unsubscribe(e)}}},Kt=(e={},t,n=!0)=>{Object.entries(e).forEach((([e,r])=>{const o=he[e];if(!o)return;const s=de(o);s&&r.forEach((e=>{(n?_e:Oe)([o,"get",s(e)],e,t)}))}))},$t=(e,t)=>{const{log:n,cache:r}=we(),o=[e,L,t],s={cachedAt:Date.now()};r&&(n("cache/api/pushToTombstone",{cacheKey:o,data:s}),Te([e,"get",t],!0),_e(o,s))};function zt(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n}const Qt=(e,t="userId",n="user")=>{var r;return null!==(r=null==e?void 0:e.map((e=>((e,t="userId",n="user")=>e[n]?e:Object.assign({get[n](){var n;if(!we().cache)return;return(null===(n=Se(["user","get",e[t]]))||void 0===n?void 0:n.data)||void 0}},e))(e,t,n))))&&void 0!==r?r:e},Vt=(e,t,n="userId",r="user")=>{const o=e,s=t,a=o[s],i=zt(o,["symbol"==typeof s?s:s+""]),c=Qt(a,n,r);return Object.assign(Object.assign({},i),{[t]:c})};function Ht(e){return e.map((e=>{var{isMentioned:t}=e,n=zt(e,["isMentioned"]);return Object.assign({hasMentioned:t},n)}))}function Wt(e){return Ht(e)}function Jt(e){return Ht(e)}const Gt=e=>{var t,n;return null!==(n=null===(t=Se(["messagePreviewChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},Yt=["analytic","normal-priority"],Zt=["analytic","high-priority"],Xt=async e=>{const t=we(),n={activities:e};await t.http.post("/api/v1/analytics/activities",n)};class en{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),this._high_priority_timer&&(clearInterval(this._high_priority_timer),this._high_priority_timer=void 0)}async syncCapturedEvent(){try{const e=Se(Yt);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await Xt(t),Te(Yt)}catch(e){this.stop(),Te(Yt)}}async syncHighPriorityCapturedEvent(){try{const e=Se(Zt);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await Xt(t),Te(Zt)}catch(e){this.stop(),Te(Zt)}}}class tn{constructor(){this._expireTime=3e5,this._poolLimit=1e3,this._recentViewed={},this._recentHighPriorityViewed={},this._throttleStoryTimer=void 0,this._bufferNewSeenStoryReferenceIds=[]}isAbleToEnqueue({uniqueId:e,expireTime:t,isHighPriority:n=!1}){const r=new Date,o=(()=>n?this._recentHighPriorityViewed[e]:this._recentViewed[e])()||new Date(-1*q);return!(r.getTime()-o.getTime()<t)}markAs({uniqueId:e,contentId:t,contentType:n,activityType:r,metadata:o}){if(!this.isAbleToEnqueue({uniqueId:e,expireTime:this._expireTime}))return;const s=new Date,a={event:[]},i=Se(Yt);(null==i?void 0:i.data)&&(a.event=i.data.event),a.event.length>=this._poolLimit&&a.event.shift();const c={contentId:t,contentType:n,activityType:r,timestamp:s.toISOString()};o&&(c.metadata=o),a.event.push(c),Oe(Yt,a),this._recentViewed[e]=s}markPostAsViewed(e){this.markAs({uniqueId:e,contentId:e,contentType:"post",activityType:"view"})}markStory(e,t){if(!e.expiresAt)return;const n=new Date,r=new Date(e.expiresAt);if(!this.isAbleToEnqueue({uniqueId:e.storyId,expireTime:r.getTime(),isHighPriority:!0}))return;const o={event:[]},s=Se(Zt);if((null==s?void 0:s.data)&&(o.event=s.data.event),o.event.length>=this._poolLimit&&o.event.shift(),o.event.push({contentId:e.storyId,contentType:"story",activityType:t,timestamp:n.toISOString()}),Oe(Zt,o),this._recentHighPriorityViewed[e.storyId]=n,"linkClicked"===t)return;_e(["story-seen","get",e.storyId],(new Date).toISOString());const a=Se(["story-last-seen",e.targetId]);(null==a?void 0:a.data)?new Date(a.data).getTime()<new Date(e.expiresAt).getTime()&&_e(["story-last-seen",e.targetId],e.expiresAt):_e(["story-last-seen",e.targetId],e.expiresAt),this._bufferNewSeenStoryReferenceIds.push(e.referenceId),this._throttleStoryTimer||(this._throttleStoryTimer=setTimeout((()=>{clearTimeout(this._throttleStoryTimer),Xe("local.story.reload",{referenceIds:this._bufferNewSeenStoryReferenceIds}),this._bufferNewSeenStoryReferenceIds=[]}),300))}resetAllBuckets(){this._recentViewed={},this._recentHighPriorityViewed={},Te(Yt),Te(Zt)}markStoryAsViewed(e){this.markStory(e,"view")}markStoryAsClicked(e){this.markStory(e,"linkClicked")}markAdAsViewed(e,t){const n={placement:t},r="view";this.markAs({uniqueId:`${e.adId}.view.${t}`,contentId:e.adId,contentType:"ad",activityType:r,metadata:n})}markAdAsClicked(e,t){const n={placement:t},r="linkClicked";this.markAs({uniqueId:`${e.adId}.linkClicked.${t}`,contentId:e.adId,contentType:"ad",activityType:r,metadata:n})}}class nn{constructor(){this._client=we(),this._eventCapturer=new tn,this._eventSyncer=new en}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)}markAdAsViewed(e,t){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markAdAsViewed(e,t)}markAdAsClicked(e,t){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markAdAsClicked(e,t)}markStoryAsClicked(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markStoryAsClicked(e)}established(){this._eventSyncer.start()}handleTokenExpired(){this._stopAndDestroy()}destroy(){this._stopAndDestroy()}_stopAndDestroy(){this._eventSyncer.stop(),this._eventCapturer.resetAllBuckets()}}let rn;var on=()=>(rn||(rn=new nn),rn);const sn=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=Se(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}});class an{constructor(e,t,n){this._syncingStoriesCount=0,this._errorStoriesCount=0,this._targetId=e,this._lastStoryExpiresAt=t,this._lastStorySeenExpiresAt=n,this.cacheStoryExpireTime=Se(["story-expire",this._targetId]),this.cacheStoreSeenTime=Se(["story-last-seen",this._targetId]),this.getTotalStoryByStatus()}get lastStoryExpiresAt(){return this._lastStoryExpiresAt?new Date(this._lastStoryExpiresAt).getTime():0}get lastStorySeenExpiresAt(){return this._lastStorySeenExpiresAt?new Date(this._lastStorySeenExpiresAt).getTime():0}get localLastStoryExpires(){var e,t;return(null===(e=this.cacheStoryExpireTime)||void 0===e?void 0:e.data)?new Date(null===(t=this.cacheStoryExpireTime)||void 0===t?void 0:t.data).getTime():0}get localLastStorySeenExpiresAt(){var e,t;return(null===(e=this.cacheStoreSeenTime)||void 0===e?void 0:e.data)?new Date(null===(t=this.cacheStoreSeenTime)||void 0===t?void 0:t.data).getTime():0}get isContainUnSyncedStory(){const e=Se(["story-sync-state",this._targetId]);return!!(null==e?void 0:e.data)&&["syncing","error"].includes(e.data)}getLocalLastSortingDate(){return this.isContainUnSyncedStory?this.localLastStoryExpires:this.lastStoryExpiresAt}getHasUnseenFlag(){const e=(new Date).getTime(),t=Math.max(this.lastStorySeenExpiresAt,this.localLastStorySeenExpiresAt);return Se(["story-sync-state",this._targetId]),this.isContainUnSyncedStory?this.localLastStoryExpires>e&&this.localLastStoryExpires>t:this.lastStoryExpiresAt>e&&this.lastStoryExpiresAt>t}getTotalStoryByStatus(){const e=Ie(["story","get"]);if(!e)return this._errorStoriesCount=0,void(this._syncingStoriesCount=0);const t=e.reduce(((e,t)=>{const{data:{targetId:n,syncState:r}}=t;return n===this._targetId&&(e[r]+=1),e}),{syncing:0,error:0,synced:0});this._errorStoriesCount=t.error,this._syncingStoriesCount=t.syncing}get syncingStoriesCount(){return this._syncingStoriesCount}get failedStoriesCount(){return this._errorStoriesCount}}const cn=e=>{const{targetType:t,targetId:n,lastStoryExpiresAt:r,lastStorySeenExpiresAt:o,targetUpdatedAt:s,localFilter:a}=e,i=new an(n,r,o);return{targetType:t,targetId:n,lastStoryExpiresAt:r,updatedAt:s,hasUnseen:i.getHasUnseenFlag(),syncingStoriesCount:i.syncingStoriesCount,failedStoriesCount:i.failedStoriesCount,localFilter:a,localLastExpires:i.localLastStoryExpires,localLastSeen:i.localLastStorySeenExpiresAt,localSortingDate:i.getLocalLastSortingDate()}};function ln(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 n=0;n<e.length;n+=1)if(!ln(e[n],t[n]))return!1;return!0}if(e instanceof Date)return!1;if(!(e instanceof Object))return!1;if(!(t instanceof Object))return!1;const n=Object.keys(e);return Object.keys(t).every((e=>-1!==n.indexOf(e)))&&n.every((n=>ln(e[n],t[n])))}function dn(e){return null!=e}const un=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 n=Se(["communityUsers","get",`${e.targetId}#${e.userId}`]);return Object.assign(Object.assign({},t),{communityId:e.targetId,creatorMember:null==n?void 0:n.data})}return{type:"unknown"}},get creator(){const t=Se(["user","get",e.userId]);if(null==t?void 0:t.data)return sn(t.data)},get childrenComment(){return e.children.map((e=>{const t=Se(["comment","get",e]);if(null==t?void 0:t.data)return null==t?void 0:t.data})).filter(dn).map((e=>un(e)))}}),hn=e=>Object.assign(Object.assign({},e),{analytics:{markAsViewed:()=>{on().markPostAsViewed(e.postId)}},get latestComments(){return e.comments&&e.comments.map((e=>{var t;const n=null===(t=Se(["comment","get",e]))||void 0===t?void 0:t.data;return n?un(n):null})).filter(Boolean)||[]},get creator(){const t=Se(["user","get",e.postedUserId]);if(null==t?void 0:t.data)return sn(t.data)}}),pn=(e,t)=>{var n;return null!==(n=null!=t?t:(e=>{var t,n;const r={creatorId:"creatorPrivateId"in e?e.creatorPrivateId:e.creatorId,feedId:null!==(t=e.messageFeedId)&&void 0!==t?t:e.subChannelId,contentId:e.messageId};return null===(n=Se(["messageMarker","get",de("messageMarker")(r)]))||void 0===n?void 0:n.data})(e))&&void 0!==n?n:{readCount:0,deliveredCount:0}},fn=e=>{var t;const n=["channelUnreadInfo","get",e],r=null===(t=Se(n))||void 0===t?void 0:t.data,o=Ie(["subChannelUnreadInfo","get"]);let s=0,a=!1;if(o&&(null==o?void 0:o.length)>0){const t=null==o?void 0:o.filter((({data:t})=>t.channelId===e&&!t.isDeleted));s=t.map((({data:e})=>e.unreadCount)).reduce(((e,t)=>e+t),0),a=t.some((({data:e})=>e.isMentioned))}const i=Object.assign(Object.assign({},null!=r?r:{channelId:e,createdAt:(new Date).toISOString()}),{updatedAt:(new Date).toISOString(),unreadCount:s,isMentioned:a});return _e(n,i),i};class gn{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=we(),this.getUnsyncJobs()}startSyncReadReceipt(){this.timer=setInterval((()=>{this.syncReadReceipts()}),1e3*this.RECEIPT_SYNC_INTERVAL)}syncReadReceipts(){if(0===this.jobQueue.length||!1===this.isActive)return;const e=this.getReadReceipt();e&&this.markReadApi(e)}getUnsyncJobs(){var e;const t=null===(e=Ie(["readReceipt"]))||void 0===e?void 0:e.filter((({data:e})=>e.latestSyncSegment<e.latestSegment));null==t||t.forEach((({data:e})=>{this.enqueueReadReceipt(e.subChannelId,e.latestSegment)}))}getReadReceipt(){var e;const t=this.jobQueue[0];if(!t)return;if("syncing"===t.syncState)return;const n=null===(e=Se(["readReceipt",t.subChannelId]))||void 0===e?void 0:e.data;return n?(null==n?void 0:n.latestSegment)>(null==n?void 0:n.latestSyncSegment)?(t.segment=n.latestSegment,t):(this.removeSynedReceipt(n.subChannelId,n.latestSegment),this.getReadReceipt()):void 0}async markReadApi(e){var t;const n=e;n.syncState="syncing";const{subChannelId:r,segment:o}=n,s=await(async({subChannelId:e,readToSegment:t})=>{const n=we();n.log("subChannel/markAsReadBySegment",e);try{return await n.http.put(`/api/v1/markers/message-feeds/${e}/mark-read`,{readToSegment:t}),!0}catch(e){return!1}})({subChannelId:r,readToSegment:o});if(s){this.removeSynedReceipt(e.subChannelId,e.segment);const n=null===(t=Se(["readReceipt",r]))||void 0===t?void 0:t.data;_e(["readReceipt",r],Object.assign(Object.assign({},n),{latestSyncSegment:o}))}else s||(n.retryCount>this.MAX_RETRY?this.removeJobFromQueue(n):(n.retryCount+=1,n.syncState="create"))}removeSynedReceipt(e,t){this.jobQueue.forEach((n=>{n.subChannelId===e&&n.segment<=t&&this.removeJobFromQueue(n)}))}startObservingReadReceiptQueue(){this.client.isUnreadCountEnabled&&(this.isActive=!0,this.startSyncReadReceipt())}stopObservingReadReceiptQueue(){this.isActive=!1;this.jobQueue.map((e=>"syncing"===e.syncState?Object.assign(Object.assign({},e),{syncState:"create"}):e)),this.timer&&clearInterval(this.timer)}onSessionEstablished(){this.startObservingReadReceiptQueue()}onSessionDestroyed(){this.stopObservingReadReceiptQueue(),this.jobQueue=[]}onTokenExpired(){this.stopObservingReadReceiptQueue()}onNetworkOffline(){this.stopObservingReadReceiptQueue()}onNetworkOnline(){this.startObservingReadReceiptQueue()}markRead(e,t){var n;const r=["subChannelUnreadInfo","get",e],o=null===(n=Se(r))||void 0===n?void 0:n.data;if(o&&t>o.readToSegment){o.readToSegment=t,o.unreadCount=Math.max(o.lastSegment-t,0);const e=fn(o.channelId);Xe("local.channelUnread.updated",e),_e(r,o),Xe("local.subChannelUnread.updated",o)}this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const r=null===(n=Se(["readReceipt",e]))||void 0===n?void 0:n.data;if(r){if(r.latestSegment<t)_e(["readReceipt",e],Object.assign(Object.assign({},r),{latestSegment:t}));else if(r.latestSyncSegment>=t)return}else{_e(["readReceipt",e],{subChannelId:e,latestSegment:t,latestSyncSegment:0})}let o=this.getSyncJob(e);null===o||"syncing"===o.syncState?(o={subChannelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(o)):o.segment<t&&(o.segment=t)}getSyncJob(e){return this.jobQueue.find((t=>t.subChannelId===e))||null}enqueueJob(e){this.jobQueue.length<this.JOB_QUEUE_SIZE||this.jobQueue.shift(),this.jobQueue.push(e)}removeJobFromQueue(e){const t=this.jobQueue.indexOf(e);t>-1&&this.jobQueue.splice(t,1)}}let mn=null;var yn=()=>(mn||(mn=new gn),mn);const vn=e=>{const{subChannelId:t,channelSegment:n}=e;yn().markRead(t,n)},bn=async e=>{const t=we();t.log("channel/markAsRead",e);const{data:n}=await t.http.put(`/api/v1/markers/channels/${e}/mark-read`),{userMarkers:r,userEntityMarkers:o,userFeedMarkers:s}=n,a=zt(n,["userMarkers","userEntityMarkers","userFeedMarkers"]),i=t.cache&&Date.now(),c=Wt(o),l=Jt(s);return t.cache&&Kt(Object.assign({userMarkers:r,userEntityMarkers:c,userFeedMarkers:l},a),{cachedAt:i}),Xe("local.channelMarker.updated",{userEntityMarkers:c}),Xe("local.subChannelMarker.updated",{userFeedMarkers:l}),!0},wn={ad:e=>{const t=on(),{image9_16:n,image1_1:r}=e,o=zt(e,["image9_16","image1_1"]);return Object.assign(Object.assign({},o),{analytics:{markAsSeen:n=>{t.markAdAsViewed(e,n)},markLinkAsClicked:n=>{t.markAdAsClicked(e,n)}},get advertiser(){var t,n;const r=null===(t=Se(["advertiser","get",e.advertiserId]))||void 0===t?void 0:t.data;if(!r)return;const o=null===(n=Se(["file","get",r.avatarFileId]))||void 0===n?void 0:n.data;return Object.assign(Object.assign({},r),{avatar:o})},get image1_1(){const e=Se(["file","get",r]);if(e)return e.data||void 0},get image9_16(){const e=Se(["file","get",n]);if(e)return e.data||void 0}})},comment:un,post:hn,user:sn,category:e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=Se(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),stream:e=>Object.assign(Object.assign({},e),{get moderation(){var t;return null===(t=Se(["streamModeration","get",e.streamId]))||void 0===t?void 0:t.data},get post(){var t;if("post"===e.referenceType)return null===(t=Se(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=Se(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;return null===(t=Se(["user","get",e.userId]))||void 0===t?void 0:t.data}}),story:e=>{const t=on(),n=Se(["storyTarget","get",e.targetId]),r=Se(["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,n;const r=Se(["file","get",null===(n=null===(t=e.data)||void 0===t?void 0:t.videoFileId)||void 0===n?void 0:n.original]);if(!r)return;const{data:o}=r;return o||void 0},get imageData(){var t,n;if(!(null===(t=e.data)||void 0===t?void 0:t.fileId))return;const r=Se(["file","get",null===(n=e.data)||void 0===n?void 0:n.fileId]);if(!r)return;const{data:o}=r;return o?Object.assign(Object.assign({},o),{fileUrl:`${o.fileUrl}?size=full`}):void 0},get community(){if("community"===e.targetType&&r)return(null==r?void 0:r.data)||void 0},get communityCategories(){if("community"!==e.targetType)return;if(!r)return;const{data:{categoryIds:t}}=r;return 0!==t.length?t.map((e=>{const t=Se(["category","get",e]);return(null==t?void 0:t.data)||void 0})).filter((e=>void 0!==e)):void 0},get creator(){const t=Se(["user","get",e.creatorPublicId]);if(null==t?void 0:t.data)return sn(t.data)},get storyTarget(){if(null==n?void 0:n.data)return cn(n.data)},get isSeen(){const t=Se(["story-last-seen",e.targetId]);if(!(null==n?void 0:n.data))return!1;const r=(null==t?void 0:t.data)?new Date(t.data).getTime():0,o=new Date(null==n?void 0:n.data.lastStorySeenExpiresAt).getTime()||0,s=new Date(e.expiresAt).getTime();return Math.max(r,o)>=s}})},storyTarget:cn,message:e=>{const t=zt(e,["creatorPrivateId"]);return Object.assign(Object.assign({},t),{get readCount(){return pn(e).readCount},get deliveredCount(){return pn(e).deliveredCount},markRead:()=>vn(e)})},reactor:e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=Se(["user","get",e.userId]))||void 0===t?void 0:t.data;if(n)return sn(n)}}),channel:e=>Object.assign(Object.assign({},e),{markAsRead:()=>bn(e.channelInternalId)}),pinnedPost:e=>{var t;const n=Se(["post","get",e.referenceId]),r=null===(t=Ie(["user","get"]).find((t=>{var n;return(null===(n=t.data)||void 0===n?void 0:n.userInternalId)===e.pinnedBy})))||void 0===t?void 0:t.data;return Object.assign(Object.assign({},e),{pinnedBy:r,get post(){if(null==n?void 0:n.data)return hn(n.data)},get target(){const e=Se(["pinTarget","get",null==n?void 0:n.data.targetId]);if(null==e?void 0:e.data)return null==e?void 0:e.data}})}},Cn=e=>{var t;const n=e.messagePreviewId?Gt(e.channelId):null,r=null===(t=Se(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data,o=n?Object.assign(Object.assign({},n),{user:r?wn.user(r):void 0}):null;return Object.assign(Object.assign({},e),{messagePreview:o})},In=e=>{var t,n;const r={messagePreviewChannel:null!==(n=null===(t=e.messagePreviews)||void 0===t?void 0:t.map((t=>(t=>{var n;const r=null===(n=e.messageFeedsInfo)||void 0===n?void 0:n.find((e=>e.messageFeedId===t.messageFeedId)),{channelPublicId:o,messageFeedId:s,data:a,dataType:i,isDeleted:c,segment:l,creatorPublicId:d,createdAt:u,updatedAt:h}=t;return{channelId:o,subChannelId:s,data:a,dataType:i,isDeleted:c,segment:l,creatorId:d,createdAt:u,updatedAt:h,subChannelName:null==r?void 0:r.name,messagePreviewId:null==r?void 0:r.messagePreviewId,subChannelUpdatedAt:null==r?void 0:r.updatedAt}})(t))))&&void 0!==n?n:[]};Kt(r)},Sn=e=>{var t,n;return null!==(n=null===(t=Se(["messagePreviewSubChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},_n=e=>{var t;const n=e.messagePreviewId?Sn(e.subChannelId):null,r=n?Object.assign(Object.assign({},n),{user:null===(t=Se(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data}):null;return Object.assign(Object.assign({},e),{messagePreview:r})},kn=e=>{var t,n;const r={messagePreviewSubChannel:null!==(n=null===(t=e.messages)||void 0===t?void 0:t.map((t=>(t=>{var n;const r=null===(n=e.messageFeeds)||void 0===n?void 0:n.find((e=>e.messageFeedId===t.messageFeedId)),{channelPublicId:o,messageFeedId:s,messageId:a,creatorPublicId:i,data:c,dataType:l,isDeleted:d,segment:u,createdAt:h,updatedAt:p}=t;return{messagePreviewId:a,channelId:o,subChannelId:s,data:c,dataType:l,isDeleted:d,segment:u,creatorId:i,createdAt:h,updatedAt:p,subChannelName:null==r?void 0:r.name,subChannelUpdatedAt:null==r?void 0:r.updatedAt}})(t))))&&void 0!==n?n:[]};Kt(r)};function On(e){const t=Object.create(Object.getPrototypeOf(e)),n=Object.getOwnPropertyDescriptors(e);return Object.defineProperties(t,n),t}function Tn(e,t,n){_e(["subChannel","get",e],Object.assign(On(t),n))}const An=async e=>{var t,n,r,o;const{channelId:s,messageId:a,creatorId:i,createdAt:c,updatedAt:l,data:d,dataType:u,subChannelId:h,channelSegment:p,isDeleted:f}=e,g=null===(t=Se(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(!g||g.segment<=e.channelSegment){const t=null===(n=Se(["subChannel","get",h]))||void 0===n?void 0:n.data;_e(["messagePreviewSubChannel","get",e.subChannelId],{channelId:s,creatorId:i,messagePreviewId:a,createdAt:c,updatedAt:l,subChannelId:h,data:d,dataType:u,segment:p,isDeleted:f,subChannelUpdatedAt:null==t?void 0:t.updatedAt,subChannelName:null==t?void 0:t.displayName}),Tn(e.subChannelId,t,{messagePreviewId:a})}const m=null===(r=Se(["messagePreviewChannel","get",e.channelId]))||void 0===r?void 0:r.data;if(!m||new Date(m.createdAt).valueOf()<=new Date(e.createdAt).valueOf()){const t=null===(o=Se(["subChannel","get",h]))||void 0===o?void 0:o.data;_e(["messagePreviewChannel","get",e.channelId],{channelId:s,creatorId:i,messagePreviewId:a,createdAt:c,updatedAt:l,subChannelId:h,data:d,dataType:u,segment:p,isDeleted:f,subChannelUpdatedAt:null==t?void 0:t.updatedAt,subChannelName:null==t?void 0:t.displayName})}},En=async e=>{var t,n,r,o;const{channelId:s,messageId:a,creatorId:i,createdAt:c,updatedAt:l,data:d,dataType:u,subChannelId:h,channelSegment:p,isDeleted:f}=e,g=null===(t=Se(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(g&&g.messagePreviewId===e.messageId){const t=null===(n=Se(["subChannel","get",h]))||void 0===n?void 0:n.data;Tn(e.subChannelId,t,{messagePreviewId:a}),_e(["messagePreviewSubChannel","get",e.subChannelId],{channelId:s,creatorId:i,messagePreviewId:a,createdAt:c,updatedAt:l,subChannelId:h,data:d,dataType:u,segment:p,isDeleted:f,subChannelUpdatedAt:null==e?void 0:e.updatedAt,subChannelName:null==t?void 0:t.displayName})}const m=null===(r=Se(["messagePreviewChannel","get",e.channelId]))||void 0===r?void 0:r.data;if(m&&m.messagePreviewId===e.messageId){const t=null===(o=Se(["subChannel","get",h]))||void 0===o?void 0:o.data;_e(["messagePreviewChannel","get",e.channelId],{channelId:s,creatorId:i,messagePreviewId:a,createdAt:c,updatedAt:l,subChannelId:h,data:d,dataType:u,segment:p,isDeleted:f,subChannelUpdatedAt:null==t?void 0:t.updatedAt,subChannelName:null==t?void 0:t.displayName})}},Mn=async e=>{var t,n,r,o;const{channelId:s,subChannelId:a}=e,i=null===(t=Se(["messagePreviewChannel","get",s]))||void 0===t?void 0:t.data;if((null==i?void 0:i.subChannelId)===a){const e=null===(n=Se(["subChannel","get",a]))||void 0===n?void 0:n.data;_e(["messagePreviewChannel","get",s],Object.assign(Object.assign({},i),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}const c=null===(r=Se(["messagePreviewSubChannel","get",a]))||void 0===r?void 0:r.data;if(c&&new Date(c.updatedAt).valueOf()>new Date(e.updatedAt).valueOf()){const e=null===(o=Se(["subChannel","get",a]))||void 0===o?void 0:o.data;_e(["messagePreviewSubChannel","get",a],Object.assign(Object.assign({},c),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}},Pn=(e,t)=>{var n,r,o,s,a;const i=we();return i.isUnreadCountEnabled&&i.getMarkerSyncConsistentMode()?null!==(r=null===(n=(e=>{var t;return null===(t=Se(["channelUnreadInfo","get",e]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===n?void 0:n.unreadCount)&&void 0!==r?r:0:(null==t?void 0:t.isDeleted)?0:null!==(a=null!==(o=null==t?void 0:t.unreadCount)&&void 0!==o?o:null===(s=(e=>{var t;const n={entityId:e,userId:Qe()._id};return null===(t=Se(["channelMarker","get",de("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===s?void 0:s.unreadCount)&&void 0!==a?a:0},Rn=(e,t)=>{var n,r,o,s;const a=we();return a.isUnreadCountEnabled&&a.getMarkerSyncConsistentMode()?null!==(r=null===(n=(e=>{var t;return null===(t=Se(["channelUnreadInfo","get",e]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===n?void 0:n.isMentioned)&&void 0!==r&&r:void 0!==(null==t?void 0:t.hasMentioned)?null==t?void 0:t.hasMentioned:null!==(s=null===(o=(e=>{var t;const n={entityId:e,userId:Qe()._id};return null===(t=Se(["channelMarker","get",de("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===o?void 0:o.hasMentioned)&&void 0!==s&&s};function Un(e){return Object.assign(Object.assign({},e),{isGlobalBanned:(null==e?void 0:e.isGlobalBan)||!1})}const jn=["broadcast","conversation","community"],xn=({type:e})=>jn.includes(e);function Dn(e,t={isMessagePreviewUpdated:!0}){var n;let{messagePreviewId:r}=e;const o=null===(n=Se(["messagePreviewChannel","get",e.channelId]))||void 0===n?void 0:n.data;return(null==o?void 0:o.messagePreviewId)&&!t.isMessagePreviewUpdated&&(r=o.messagePreviewId),Object.assign(Object.assign({get unreadCount(){return Pn(e)},get hasMentioned(){return Rn(e)},get isMentioned(){return Rn(e)},get subChannelsUnreadCount(){return Pn(e)}},e),{defaultSubChannelId:e.channelInternalId,isUnreadCountSupport:xn(e),messagePreviewId:r})}const Nn=(e,t={isMessagePreviewUpdated:!0})=>{Kt({channels:e.channels.map((e=>Dn(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated})))})},Bn=async(e,t={isMessagePreviewUpdated:!0})=>{const n=we(),r=await n.getMessagePreviewSetting(!1);t.isMessagePreviewUpdated&&"no-message-preview"!==r&&e.messagePreviews&&e.messagePreviews.length>0&&In(e);const o=e.channels.filter(xn).map((({channelInternalId:e})=>e));if(o.length>0){Nn(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated});try{await(async e=>{const t=we();t.log("channel/getChannelMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/channels",{params:{channelIds:e}}),{userEntityMarkers:r,userMarkers:o}=n,s=Wt(r),a=t.cache&&Date.now();return t.cache&&Kt({userEntityMarkers:s,userMarkers:o},{cachedAt:a}),Xe("local.channelMarker.fetched",{userEntityMarkers:s}),Xe("local.userMarker.fetched",{userMarkers:o}),{data:s,cachedAt:a}})(o)}catch(e){}}const s=e.channels.map((e=>Dn(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated}))),a=e.channelUsers.map((e=>{return t=e,Object.assign(Object.assign({},t),{get user(){var e;if(we().cache)return(null===(e=Se(["user","get",t.userId]))||void 0===e?void 0:e.data)||void 0}});var t})),i=e.users.map(Un),c=zt(e,["messageFeedsInfo","messagePreviews"]);return Object.assign(Object.assign({},c),{users:i,channels:s,channelUsers:a})},qn=async e=>{const t=we();t.log("channel/getUserMessageFeedMakers",e);const{data:n}=await t.http.get("/api/v1/markers/user-message-feed",{params:{channelIds:e}});return Xe("local.userMessageFeedMarker.fetched",{userMessageFeedMarker:n}),n},Fn=e=>{const{feedMarkers:t,userFeedMarkers:n}=e;if(t.length>0&&n.length>0){const e=[],r=new Map(t.map((e=>[e.feedId,e])));n.forEach((t=>{const n=r.get(t.feedId);if(n&&n.feedId===t.feedId){const r=n.lastSegment-t.readToSegment,o={subChannelId:n.feedId,channelId:n.entityId,readToSegment:t.readToSegment,lastSegment:n.lastSegment,lastMentionSegment:t.lastMentionSegment,unreadCount:Math.max(0,r),isMentioned:t.isMentioned,isDeleted:n.isDeleted,createdAt:t.createdAt,updatedAt:t.updatedAt};Kt({subChannelUnreadInfo:[o]}),e.includes(n.entityId)||e.push(n.entityId)}})),e.forEach((e=>{fn(e)}))}},Ln=async e=>{const t=we(),n=await qn(e.channels.map((({channelInternalId:e})=>e))),{feedMarkers:r,userFeedMarkers:o}=n;Fn({feedMarkers:r,userFeedMarkers:o}),t.log("channel/prepareUnreadCountInfo",e.channels)},Kn=async e=>{const t=we();t.log("channel/getChannelByIds",e);const n=e.map((e=>encodeURIComponent(e)));let r;try{r=(await t.http.get("/api/v3/channels/list",{params:{channelIds:n}})).data}catch(t){throw e.forEach((e=>{V(null==t?void 0:t.code)&&$t("channel",e)})),t}const o=await Bn(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await Ln(r);const s=t.cache&&Date.now();return t.cache&&Kt(o,{cachedAt:s}),Xe("local.channel.fetched",o.channels),{data:o.channels.map((e=>wn.channel(e))),cachedAt:s}};Kn.locally=e=>{var t,n;const r=we();if(r.log("channel/getChannelByIds.locally",e),!r.cache)return;const o=null===(t=Ie(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!o||(null==o?void 0:o.length)<e.length)return;const s=o.map((({data:e})=>e)),a=null===(n=o.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0];return{data:s.map((e=>wn.channel(e))),cachedAt:a.cachedAt}};const $n=async()=>{const e=we();e.log("channel/getUserMarker");const{data:t}=await e.http.get("/api/v1/markers/userMarker"),{userMarkers:n}=t,r=e.cache&&Date.now();e.cache&&Kt({userMarkers:n},{cachedAt:r}),Xe("local.userMarker.fetched",{userMarkers:n});return{data:n.reduce(((e,t)=>null==e||new Date(e.lastSyncAt).getTime()<new Date(t.lastSyncAt).getTime()?t:e),void 0),cachedAt:r}},zn=e=>!0===e&&void 0;function Qn(e,t,n){var r,o;if(n)return n.hasMentioned;const s=we();if(s.isUnreadCountEnabled&&s.getMarkerSyncConsistentMode()){const e=null===(r=Se(["subChannelUnreadInfo","get",t]))||void 0===r?void 0:r.data;return!!e&&e.isMentioned}const a={entityId:e,feedId:t,userId:Qe()._id},i=null===(o=Se(["subChannelMarker","get",de("subChannelMarker")(a)]))||void 0===o?void 0:o.data;return!!i&&i.hasMentioned}const Vn=["broadcast","conversation","community"],Hn=({channelType:e})=>Vn.includes(e);function Wn(e){var{channelId:t,channelPublicId:n,channelType:r,childCount:o,creatorId:s,creatorPublicId:a,lastMessageId:i,lastMessageTimestamp:c,messageFeedId:l,name:d}=e,u=zt(e,["channelId","channelPublicId","channelType","childCount","creatorId","creatorPublicId","lastMessageId","lastMessageTimestamp","messageFeedId","name"]);return Object.assign(Object.assign({get unreadCount(){return function(e,t,n){var r,o;if(n)return n.unreadCount;const s=we();if(s.isUnreadCountEnabled&&s.getMarkerSyncConsistentMode()){const e=null===(r=Se(["subChannelUnreadInfo","get",t]))||void 0===r?void 0:r.data;return e?e.isDeleted?0:e.unreadCount:0}const a={entityId:e,feedId:t,userId:Qe()._id},i=null===(o=Se(["subChannelMarker","get",de("subChannelMarker")(a)]))||void 0===o?void 0:o.data;return i?i.unreadCount:0}(t,l)},get hasMentioned(){return Qn(t,l)},get isMentioned(){return Qn(t,l)}},u),{channelId:n,creatorId:a,displayName:d,lastActivity:c,latestMessageId:i,messageCount:o,subChannelId:l,isUnreadCountSupport:Hn({channelType:r})})}function Jn(e,t,n){var r;const o=(e=>{const t=we(),{objectSyncMap:n}=t;return Object.assign(Object.assign({},e),{referenceId:ue(e.messageId)?e.messageId:n.get(e.messageId)})})(e),{channelPublicId:s,childCount:a,creatorPublicId:i,mentionedUsers:c,messageFeedId:l,myReactions:d,reactionCount:u,reactions:h,referenceId:p,segment:f,messageId:g,creatorId:m}=o,y=zt(o,["channelPublicId","childCount","creatorPublicId","mentionedUsers","messageFeedId","myReactions","reactionCount","reactions","referenceId","segment","messageId","creatorId"]);let v;p&&(v=Se(["message","get",p])),v||(v=Se(["message","get",g]));const b=Object.assign(Object.assign({},y),{messageId:g,channelId:s,channelSegment:f,childrenNumber:a,creatorId:i,creatorPrivateId:e.creatorId,reactions:null!=h?h:{},myReactions:d||(null!==(r=null==v?void 0:v.data.myReactions)&&void 0!==r?r:[]),reactionsCount:u,subChannelId:l,uniqueId:v?v.data.uniqueId:g,referenceId:p,syncState:"synced"});return c&&(b.mentionees=c.map((e=>"channel"===e.type?e:{type:"user",userIds:e.userPublicIds}))),t&&t.length&&n&&((e,t,n)=>{const r=we(),o=Se(["message","get",e.messageId]),s=(null==o?void 0:o.data.myReactions)||[];Object.assign(e,{myReactions:s});const a=t[0];a&&a.userId===r.userId&&("message.reactionAdded"!==n||s.includes(a.reactionName)||Object.assign(e,{myReactions:[...s,a.reactionName]}),"message.reactionRemoved"===n&&s.includes(a.reactionName)&&Object.assign(e,{myReactions:s.filter((e=>e!==a.reactionName))}))})(b,t,n),b}const Gn={},Yn=async(e,t)=>{const n=e.messages.map((({messageId:e})=>e));if(n.length>0){Kt({messages:(r=e).messages.map((e=>Jn(e,r.reactions)))});const t=n.join("");Gn[t]&&clearTimeout(Gn[t]),Gn[t]=setTimeout((()=>{try{(async e=>{const t=we();t.log("channel/getMessageMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/messages",{params:{messageIds:e}}),{contentMarkers:r,feedMarkers:o,userMarkers:s}=n,a=t.cache&&Date.now();t.cache&&Kt({contentMarkers:r,feedMarkers:o,userMarkers:s},{cachedAt:a}),Xe("local.feedMarker.fetched",{feedMarkers:o}),Xe("local.messageMarker.fetched",{contentMarkers:r}),Xe("local.userMarker.fetched",{userMarkers:s})})(n)}catch(e){}}),2e3)}var r;const{messageFeeds:o}=e,s=zt(e,["messageFeeds"]);return o&&o.length>0&&(null==o||o.forEach((e=>{var t,n;const r=null!==(n=null===(t=Se(["subChannel","get",e.messageFeedId]))||void 0===t?void 0:t.data)&&void 0!==n?n:{},o=zt(Wn(e),["unreadCount","hasMentioned","isMentioned"]);Tn(e.messageFeedId,r,o)}))),Object.assign(Object.assign({},s),{messages:e.messages.map((n=>Jn(n,e.reactions,t)))})};function Zn(e){var{subChannelId:t,mentionees:n,dataType:r,data:o}=e,s=zt(e,["subChannelId","mentionees","dataType","data"]);return r===P.IMAGE||r===P.FILE?Object.assign({messageFeedId:t,mentionedUsers:n,dataType:r,data:Object.assign({caption:""},o)},s):Object.assign({messageFeedId:t,mentionedUsers:n,dataType:r,data:o},s)}function Xn(e){var{sortBy:t,subChannelId:n,tags:r,includingTags:o,excludingTags:s,includeDeleted:a,aroundMessageId:i,limit:c,type:l}=e,d=zt(e,["sortBy","subChannelId","tags","includingTags","excludingTags","includeDeleted","aroundMessageId","limit","type"]);const u=Object.assign(Object.assign({},d),{messageFeedId:n,isDeleted:zn(a),options:{sortBy:t,limit:c||j,around:i}});return r&&(u.includeTags=r),o&&(u.includeTags=o),l&&(u.dataType=l),s&&(u.excludeTags=s),u}const er=["broadcast","conversation","community"],tr=({channelType:e})=>er.includes(e),nr=async e=>{const t=e.messageFeeds.filter(tr).map((({messageFeedId:e})=>e));if(t.length>0){(e=>{Kt({messageFeeds:e.messageFeeds.map((e=>Wn(e)))})})(e);try{await(async(e,t={limit:100})=>{const n=we();n.log("channel/getSubChannelMarkers",e,t);const{data:r}=await n.http.get("/api/v1/markers/message-feeds",{params:{messageFeedIds:e,options:{token:Y(t,"skiplimit")}}}),{paging:o}=r,s=zt(r,["paging"]),{userEntityMarkers:a,userFeedMarkers:i,userMarkers:c,feedMarkers:l}=s;n.isUnreadCountEnabled&&n.getMarkerSyncConsistentMode()&&Fn({feedMarkers:l,userFeedMarkers:i});const d=Wt(a),u=Jt(i),h=n.cache&&Date.now();n.cache&&Kt({userEntityMarkers:d,userFeedMarkers:u,userMarkers:c},{cachedAt:h}),Xe("local.channelMarker.fetched",{userEntityMarkers:d}),Xe("local.subChannelMarker.fetched",{userFeedMarkers:u}),Xe("local.userMarker.fetched",{userMarkers:c});const p=Z(o.next);return{data:u,cachedAt:h,prevPage:Z(o.previous),nextPage:p}})(t)}catch(e){}}kn(e);const n=e.messageFeeds.map(Wn),r=e.messages.map((e=>Jn(e)));return Object.assign(Object.assign({},e),{messageFeeds:n,messages:r})};class rr{constructor(){this._sessionState="notLoggedIn",this._listener=new Map}onSessionStateChange(e){return this._listener.set(e,e),()=>{this._listener.delete(e)}}setSessionState(e){this._sessionState!==e&&(this._sessionState=e,this._listener.forEach((t=>t(e))))}destroy(){this._listener.clear()}}let or;var sr=()=>(or||(or=new rr),or);const ar=e=>sr().onSessionStateChange(e),ir=(e,t)=>{const n=setInterval(e,t);return()=>clearInterval(n)},cr=e=>{if("undefined"!=typeof window&&window.addEventListener)return window.addEventListener("online",e),()=>window.removeEventListener("online",e);if("undefined"!=typeof document&&document.addEventListener)return document.addEventListener("online",e),()=>document.removeEventListener("online",e);if("undefined"!=typeof navigator&&"ReactNative"===navigator.product){let t=()=>{};return import("@react-native-community/netinfo").then((n=>{t=n.addEventListener((t=>{t.isConnected&&e()}))})),()=>{t()}}return console.error("Unsupported environment"),()=>console.error("Unsupported environment")},lr=(e,t)=>{const{log:n,cache:r}=we(),o=[e,L,t];if(!r)return;n("cache/api/isInTombstone",o);const s=Se(o),{lifeSpan:a}=ae("cache_then_server",18e4);if(s&&oe(s.data,a))throw new ge("Item not found!",400400,"error")},dr=async e=>{const t=we();t.log("channel/getSubChannel",e),lr("subChannel",e);try{const n=await t.http.get(`/api/v5/message-feeds/${encodeURIComponent(e)}`),r=await nr(n.data),o=t.cache&&Date.now();return t.cache&&Kt(r,{cachedAt:o}),Xe("local.message-feed.fetched",r),{data:r.messageFeeds[0],cachedAt:o}}catch(t){throw V(null==t?void 0:t.code)&&$t("subChannel",e),t}};dr.locally=e=>{const t=we();if(t.log("channel/getSubChannel.locally",e),!t.cache)return;const n=Se(["subChannel","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};let ur=!1,hr=[];const pr={},fr=async()=>{const e=Object.entries(pr).filter((([,e])=>e)).map((([e])=>e));return 0!==e.length&&(async e=>{const t=we();t.log("subChannel/readingAPI",e);const{data:n}=await t.http.post("/api/v1/markers/message-feeds/reading",{messageFeedIds:e}),{userEntityMarkers:r,userFeedMarkers:o,feedMarkers:s,userMarkers:a}=n,i=Wt(r),c=Jt(o),l=t.cache&&Date.now();return t.cache&&Kt({userEntityMarkers:i,userFeedMarkers:c,feedMarkers:s,userMarkers:a},{cachedAt:l}),Xe("local.feedMarker.fetched",{feedMarkers:s}),Xe("local.channelMarker.fetched",{userEntityMarkers:i}),Xe("local.subChannelMarker.fetched",{userFeedMarkers:c}),Xe("local.userMarker.fetched",{userMarkers:a}),!0})(e)},gr=()=>{ur=!1},mr=()=>(ur=!0,ar((e=>{"notLoggedIn"===e&&gr()})),()=>{gr()}),yr=async e=>{const t=await(async e=>{const t=dr.locally(e);if(t)return t.data.channelId;const{data:n}=await dr(e);return n.channelId})(e),n=it({channelId:t,subChannelId:e});hr.push(pt(n))};ir((async()=>{ur&&await fr()}),3e4);const vr=async e=>{const t=we();t.log("channel/getSubChannels",e);const n=await t.http.get("/api/v5/message-feeds/list",{params:{messageFeedIds:e.map(encodeURIComponent)}}),r=await nr(n.data),o=t.cache&&Date.now();return t.cache&&Kt(r,{cachedAt:o}),Xe("local.message-feed.fetched",r),{data:r.messageFeeds,cachedAt:o}};vr.locally=e=>{var t;const n=we();if(n.log("channel/getSubChannels.locally",e),!n.cache)return;const r=e.map((e=>Se(["subChannel","get",e]))).filter(Boolean);if((null==r?void 0:r.length)<e.length)return;return{data:r.map((({data:e})=>e)),cachedAt:(null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0]).cachedAt}};const br=async(e=!0)=>{var t;const n=null===(t=Se(["MessagePreviewSetting"]))||void 0===t?void 0:t.data;if(!e&&n)return n;const r=await(async()=>{const e=we(),{data:t}=await e.http.get("/api/v3/network-settings/chat");return t})();var o;return(o=r).messagePreview.enabled?o.messagePreview.isIncludeDeleted?"message-preview-include-deleted":"message-preview-not-include-deleted":"no-message-preview"},wr=async()=>{const e=we(),{data:t}=await e.http.get("/api/v3/network-settings/social");return t.socialNetworkSetting},Cr=(e,t)=>{var n;const r=null===(n=Se(["user","get",e]))||void 0===n?void 0:n.data;return!!r&&r.permissions.some((e=>e===t))},Ir=e=>{const{userId:t}=we();return{currentUser:()=>Cr(t,e),community:n=>((e,t,n)=>{var r;if(!e)return!1;const o=null===(r=Se(["communityUsers","get",`${n}#${e}`]))||void 0===r?void 0:r.data;return!!o&&(!!o.permissions.some((e=>e===t))||Cr(e,t))})(t,e,n),channel:n=>((e,t,n)=>{var r;if(!e)return!1;const o=null===(r=Se(["channelUsers","get",`${n}#${e}`]))||void 0===r?void 0:r.data;return!!o&&(!!o.permissions.some((e=>e===t))||Cr(e,t))})(t,e,n)}},Sr=async e=>{const t=we();if(t.log("channel/markerSync"),0===e.length)return!1;const{data:n}=await t.http.post("/api/v3/allowlists/verify",{data:e});return n.success},_r=async e=>{const t=we();if(t.log("channel/markerSync"),0===e.length)return!1;const{data:n}=await t.http.post("/api/v3/blocklists/verify",{data:e});return n.success},kr=async()=>{const e=we(),{data:t}=await e.http.get("/api/v3/network-settings/feed-setting");return Object.fromEntries(t.feedSettings.map((({feedType:e,contentSettings:t})=>[e,t])))},Or={notLoggedIn:["establishing"],terminated:["establishing"],establishing:["notLoggedIn","established"],established:["notLoggedIn","terminated","tokenExpired","establishing"],tokenExpired:["establishing"]},Tr=e=>{const t=we();t.log("client/api/setSessionState",e);const{sessionState:n}=t;if(n===e)return!1;if(!((e,t)=>Or[e].includes(t))(n,e))throw new fe(`Session state cannot change from ${n} to ${e}`,8e5,"error");return t.sessionState=e,sr().setSessionState(e),!0},Ar=async e=>{const t=we();Tr("establishing");const{accessToken:n,users:r,expiresAt:o,issuedAt:s}=await(async({params:e,options:t})=>{const n=we();n.log("client/api/getToken",e);const r=Bt(),{data:o}=await n.http.post("/api/v5/sessions",Object.assign(Object.assign({},e),{deviceInfo:r}),{headers:{"X-API-Key":n.apiKey,"set-access-token-cookie":(null==t?void 0:t.setAccessTokenCookie)||!1}});return o})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:o,isGlobalBanned:!1,isUserDeleted:!1},t.ws.io.opts.query={token:n},t.token={accessToken:n,issuedAt:s,expiresAt:o},Tr("established"),{accessToken:n,users:r}},Er=e=>{const t=Ie(["subChannelUnreadInfo","get"]);if(t){(null==t?void 0:t.filter((({data:t})=>t.channelId===e))).forEach((({key:e,data:t})=>{_e(e,Object.assign(Object.assign({},t),{isDeleted:!0}))}))}},Mr=e=>{var t;const n=["channelUnreadInfo","get",e];(null===(t=Se(n))||void 0===t?void 0:t.data)&&Te(n)},Pr=[];let Rr=null;const Ur=e=>{if(0===Pr.length){const e=we(),t=async t=>{const n=await Bn(t);e.isUnreadCountEnabled&&e.getMarkerSyncConsistentMode()&&n.channels.forEach((e=>{Er(e.channelId),Mr(e.channelId)})),Kt(n),Pr.forEach((e=>e(n.channels[0])))};Rr=Ze(e,"onChannelDeleted","channel.deleted",t)}return Pr.push(e),()=>(e=>{const t=Pr.indexOf(e);t>-1&&Pr.splice(t,1),0===Pr.length&&(null==Rr||Rr())})(e)},jr=[];let xr=null;const Dr=e=>{const t=we();return xr=Ze(t,"onChannelMemberBanned","channel.banned",(async e=>{const n=await Bn(e),{channels:r,channelUsers:o}=n,s=o.some((e=>"banned"===e.membership&&e.userId===t.userId));t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&s&&n.channels.forEach((e=>{Er(e.channelId),Mr(e.channelId)})),Kt(n),jr.forEach((e=>e(r[0],o.find((e=>"banned"===e.membership)))))})),jr.push(e),()=>(e=>{const t=jr.indexOf(e);t>-1&&jr.splice(t,1),0===jr.length&&(null==xr||xr())})(e)};function Nr(e){return{users:e.users.map(Un),files:e.files}}const Br=(e,t)=>{const n=we();return Ze(n,e,e,(e=>{const r=Nr(e);n.cache&&Kt(r),t(r.users[0])}))},qr=e=>Br("user.deleted",e);class Fr{constructor(){this.TIMER_INTERVAL_MS=B,this.BUFFER_ID_LIMIT=100,this.buffer={channel:[],userMessageFeedMarker:[]},this.isResolvingTask=!1,this.connectionListener=[],this.isConnected=!0,this.addConnectionListener()}startResolver(){this.timer||(this.timer=setInterval((()=>{this.isConnected&&this.resolveObjects()}),this.TIMER_INTERVAL_MS))}stopResolver(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}resolve(e,t){const n=this.getBuffer(t);n.includes(e)||(n.length>=this.BUFFER_ID_LIMIT&&n.shift(),n.push(e))}addConnectionListener(){this.connectionListener.length>0||(this.connectionListener.push(cr((()=>{this.isConnected=!0}))),this.connectionListener.push((e=>{if("undefined"!=typeof window&&window.addEventListener)return window.addEventListener("offline",e),()=>window.removeEventListener("offline",e);if("undefined"!=typeof document&&document.addEventListener)return document.addEventListener("offline",e),()=>document.removeEventListener("offline",e);if("undefined"!=typeof navigator&&"ReactNative"===navigator.product){let t=()=>{};return import("@react-native-community/netinfo").then((n=>{t=n.addEventListener((t=>{t.isConnected||e()}))})),()=>{t()}}return console.error("Unsupported environment"),()=>console.error("Unsupported environment")})((()=>{this.isConnected=!1}))))}removeConnectionListener(){this.connectionListener.length>0&&this.connectionListener.forEach((e=>e()))}resolveObjects(){if(this.isResolvingTask)return;this.isResolvingTask=!0;const e=this.getBuffer("channel"),t=this.getBuffer("userMessageFeedMarker");this.clearBuffer(),e.length>0&&(async e=>{const{data:t}=await Kn(e);Xe("local.channel.resolved",t)})(e),t.length>0&&(async e=>{const t=await qn(e),{feedMarkers:n,userFeedMarkers:r}=t;Fn({feedMarkers:n,userFeedMarkers:r}),Xe("local.userMessageFeedMarkers.resolved",{feedMarkers:n,userFeedMarkers:r})})(t),this.isResolvingTask=!1}clearBuffer(){this.buffer={channel:[],userMessageFeedMarker:[]}}getBuffer(e){return this.buffer[e]}onSessionEstablished(){this.startResolver(),this.addConnectionListener()}onSessionDestroyed(){this.stopResolver(),this.clearBuffer(),this.isResolvingTask=!1,this.removeConnectionListener()}onTokenExpired(){this.stopResolver()}}let Lr=null;var Kr=()=>(Lr||(Lr=new Fr),Lr);const $r=async()=>{const e=we();return e.log("client/api/disconnectClient"),e.mqtt.connected&&e.mqtt.disconnect(),e.ws.connected&&e.ws.disconnect(),"established"===e.sessionState&&Tr("notLoggedIn"),e.emitter.all.clear(),e.ws.removeAllListeners(),e.mqtt.removeAllListeners(),e.userId=void 0,e.token=void 0,e.http.defaults.headers.common.Authorization="",e.http.defaults.metadata={tokenExpiry:"",isGlobalBanned:!1,isUserDeleted:!1},e.ws.io.opts.query={token:""},"undefined"!=typeof document&&(document.cookie="_ascSession=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"),"tokenExpired"!==e.sessionState&&e.cache&&(e.cache={data:{}}),!0},zr=e=>{const t=we();Tr("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,$r()},Qr=["disconnected","error","connect_error","reconnect_error","reconnect_failed"],Vr=e=>{const t=we(),n=Qr.map((n=>Ze(t,`client/onConnectionError(${n})`,n,(t=>{const r=(null==t?void 0:t.code)?new fe(t.message,t.code,"fatal"):new ye(n);e(r)}))));return()=>{n.forEach((e=>e()))}},Hr=e=>{const t=we();return Ze(t,"client/onConnectionError(user.didGlobalBan)","user.didGlobalBan",e)},Wr=e=>{const t=de("channelMarker")({userId:Qe()._id,entityId:e.channelId});Te(["channelMarker","get",t],!0)},Jr=[];let Gr=null;const Yr=e=>{if(0===Jr.length){const e=we();Gr=Ze(e,"onChannelCreated","channel.created",(async e=>{const t=await Bn(e);Kt(t),Jr.forEach((e=>e(t.channels[0])))}))}return Jr.push(e),()=>(e=>{const t=Jr.indexOf(e);t>-1&&Jr.splice(t,1),0===Jr.length&&(null==Gr||Gr())})(e)},Zr=[],Xr=[],eo=e=>{const t=we();if(0===Zr.length){const e=async e=>{const t=await Bn(e);Kt(t),Zr.forEach((e=>e(t.channels[0])))};Xr.push(Ze(t,"onChannelUpdated","channel.updated",e)),Xr.push(Ze(t,"onChannelUpdated","local.channel.updated",(e=>Zr.forEach((t=>t(e.channels[0]))))))}return Zr.push(e),()=>(e=>{const t=Zr.indexOf(e);t>-1&&Zr.splice(t,1),0===Zr.length&&Xr.forEach((e=>e()))})(e)},to=[];let no=null;const ro=e=>{if(0===to.length){const e=we();no=Ze(e,"onChannelJoined","channel.joined",(async e=>{const t=await Bn(e),{channels:n,channelUsers:r}=t;Kt(t),to.forEach((e=>e(n[0],r[0])))}))}return to.push(e),()=>(e=>{const t=to.indexOf(e);t>-1&&to.splice(t,1),0===to.length&&(null==no||no())})(e)},oo=[];let so=null;const ao=e=>{if(0===oo.length){const e=we(),t=async t=>{const{userId:n}=we(),{channelUsers:r}=t,o=r.some((e=>e.userId===n)),s=await Bn(t,{isMessagePreviewUpdated:o});e.isUnreadCountEnabled&&e.getMarkerSyncConsistentMode()&&o&&s.channels.forEach((e=>{Er(e.channelId),Mr(e.channelId)}));const{channels:a,channelUsers:i}=s;Kt(s),oo.forEach((e=>e(a[0],i[0])))};so=Ze(e,"onChannelLeft","channel.left",t)}return oo.push(e),()=>(e=>{const t=oo.indexOf(e);t>-1&&oo.splice(t,1),0===oo.length&&(null==so||so())})(e)},io=[];let co=null;const lo=e=>{if(0===io.length){const e=we();co=Ze(e,"onChannelMuted","channel.setMuted",(async e=>{const t=await Bn(e);Kt(t),io.forEach((e=>e(t.channels[0])))}))}return io.push(e),()=>(e=>{const t=io.indexOf(e);t>-1&&io.splice(t,1),0===io.length&&(null==co||co())})(e)},uo=[];let ho=null;const po=e=>{if(0===uo.length){const e=we();ho=Ze(e,"onChannelMemberAdded","channel.membersAdded",(async e=>{const t=await Bn(e),{channels:n,channelUsers:r}=t;Kt(t),uo.forEach((e=>e(n[0],r.find((e=>"member"===e.membership)))))}))}return uo.push(e),()=>(e=>{const t=uo.indexOf(e);t>-1&&uo.splice(t,1),0===uo.length&&(null==ho||ho())})(e)},fo=[];let go=null;const mo=e=>{if(0===fo.length){const e=we();go=Ze(e,"onChannelMemberRemoved","channel.membersRemoved",(async e=>{const t=await Bn(e),{channels:n,channelUsers:r}=t;Kt(t),fo.forEach((e=>e(n[0],r[0])))}))}return fo.push(e),()=>(e=>{const t=fo.indexOf(e);t>-1&&fo.splice(t,1),0===fo.length&&(null==go||go())})(e)},yo=[];let vo=null;const bo=e=>{if(0===yo.length){const e=we();vo=Ze(e,"onChannelMemberUnbanned","channel.unbanned",(async e=>{const t=await Bn(e),{channels:n,channelUsers:r}=t;Kt(t),yo.forEach((e=>e(n[0],r.find((e=>"none"===e.membership)))))}))}return yo.push(e),()=>(e=>{const t=yo.indexOf(e);t>-1&&yo.splice(t,1),0===yo.length&&(null==vo||vo())})(e)},wo=[];let Co=null;const Io=e=>{if(0===wo.length){const e=we();Co=Ze(e,"onChannelMemberRoleAdded","local.channel-moderator.role-added",(async e=>{const{channels:t,channelUsers:n}=e;wo.forEach((e=>e(t[0],n.find((e=>"member"===e.membership)))))}))}return wo.push(e),()=>(e=>{const t=wo.indexOf(e);t>-1&&wo.splice(t,1),0===wo.length&&(null==Co||Co())})(e)},So=[];let _o=null;const ko=e=>{if(0===So.length){const t=we();_o=Ze(t,"onChannelMemberRoleRemoved","local.channel-moderator.role-removed",(async t=>{const{channels:n,channelUsers:r}=t;e(n[0],r.find((e=>"member"===e.membership)))}))}return So.push(e),()=>(e=>{const t=So.indexOf(e);t>-1&&So.splice(t,1),0===So.length&&(null==_o||_o())})(e)},Oo=e=>{const t=we();return Ze(t,"feedMarker/onFeedMarkerUpdated","marker.feed-updated",(t=>{Kt(t),e(t.feedMarkers[0])}))};function To(e){const t=we(),{objectSyncMap:n}=t;return e.map((e=>{var t;return ue(e.messageId)?e.messageId:null!==(t=n.get(e.messageId))&&void 0!==t?t:e.messageId})).filter(Boolean)}const Ao=e=>{const t=we(),n=Qe(),r=[Ze(t,"message/onMessageCreated","message.created",(async r=>{const o=await Yn(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&r.messages.forEach((e=>{(e=>{var t;const n=we(),r=["subChannelUnreadInfo","get",e.messageFeedId],o=null===(t=Se(r))||void 0===t?void 0:t.data;if(!o)return;const s=o.lastSegment<e.segment?e.segment:o.lastSegment,a=s-o.readToSegment;let{lastMentionSegment:i}=o;e.mentionedUsers&&e.mentionedUsers.length>0&&e.mentionedUsers.forEach((t=>{("channel"===t.type||"user"===t.type&&n.userId&&t.userPublicIds.includes(n.userId))&&(i=e.segment)}));const c=Object.assign(Object.assign({},o),{lastMentionSegment:i,lastSegment:s,isMentioned:!(o.readToSegment>=i),unreadCount:Math.max(a,0)});_e(r,c)})(e),fn(e.channelId)})),Kt(o),o.messages.forEach((t=>{t.creatorPrivateId===n._id&&vn(t),e(t)}))}))];return()=>{r.forEach((e=>e()))}},Eo=e=>{const t=we(),n=[Ze(t,"message/onMessageCreated","local.message.created",(async t=>(Kt(t),t.messages.forEach((t=>{e(t)})))))];return()=>{n.forEach((e=>e()))}},Mo=e=>{const t=we();return Ze(t,"onSubChannelCreated","message-feed.created",(async n=>{const r=await nr(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&n.messageFeeds.forEach((e=>{(e=>{const{channelId:t,subChannelId:n,createdAt:r,updatedAt:o}=e,s={channelId:t,subChannelId:n,unreadCount:0,readToSegment:0,lastMentionSegment:0,lastSegment:0,isMentioned:!1,isDeleted:!1,createdAt:r,updatedAt:o};_e(["subChannelUnreadInfo","get",s.subChannelId],s)})({channelId:e.channelId,subChannelId:e.messageFeedId,createdAt:e.createdAt,updatedAt:e.updatedAt})})),Kt(r),e(r.messageFeeds[0])}))},Po=e=>{const t=we(),n=[Ze(t,"onSubChannelDeleted","message-feed.deleted",(async n=>{const r=await nr(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&r.messageFeeds.forEach((e=>{(e=>{var t;const n=["subChannelUnreadInfo","get",e],r=null===(t=Se(n))||void 0===t?void 0:t.data;r&&_e(n,Object.assign(Object.assign({},r),{isDeleted:!0}))})(e.subChannelId),fn(e.channelId)})),Kt(r),e(r.messageFeeds[0])})),Ze(t,"local.message-feed.deleted","local.message-feed.deleted",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}},Ro=async e=>{const t=we();t.log("channel/markerSync");const{data:n}=await t.http.post("/api/v1/markers/sync",{deviceLastSyncAt:e}),{userEntityMarkers:r,userFeedMarkers:o,feedMarkers:s,userMarkers:a}=n,i=Wt(r),c=Jt(o),l=t.cache&&Date.now();return t.cache&&Kt({userEntityMarkers:i,userFeedMarkers:c,feedMarkers:s,userMarkers:a},{cachedAt:l}),Xe("local.feedMarker.fetched",{feedMarkers:s}),Xe("local.channelMarker.fetched",{userEntityMarkers:i}),Xe("local.subChannelMarker.fetched",{userFeedMarkers:c}),Xe("local.userMarker.fetched",{userMarkers:a}),{data:n,hasMore:n.feedMarkers.length>0}},Uo=()=>{const e=we();if(e.log("client/api/isUnreadCountEnabled",e.isUnreadCountEnabled),!e)throw new fe("There is no active client",8e5,"fatal");return!e.isUnreadCountEnabled&&(e.isUnreadCountEnabled=!0,e.emitter.emit("unreadCountEnabled",!0),!0)};let jo=!1,xo=[],Do=!1,No=!0,Bo=null;const qo=e=>{null!=e&&(!Bo||e.getTime()>Bo.getTime())&&(Bo=e)},Fo=async()=>{const{data:e}=await $n();null!=e&&qo(new Date(e.lastSyncAt))};let Lo=[];const Ko=e=>{Lo=e},$o=e=>Lo.push(e),zo=async()=>{if(!Do&&0!==Lo.length)try{Do=!0,Lo=[];const e=await Ro((null==Bo?new Date:Bo).toISOString()),t=e.data.userMarkers.reduce(((e,t)=>null==e||e.getTime()<new Date(t.lastSyncAt).getTime()?new Date(t.lastSyncAt):e),null);qo(t),e.hasMore&&Lo.push("has_more")}catch(e){}finally{Do&&(Do=!1)}},Qo=()=>{xo.length>0||xo.push(cr((()=>{Lo.push("resume")})),Ao((e=>{const t=we();tr(e)&&e.creatorId!==t.userId&&Lo.push("new message")})),Yr((()=>Lo.push("subchannel is created"))),Ur((()=>Lo.push("subchannel is deleted"))),ro((()=>Lo.push("subchannel is joined"))),ao((()=>Lo.push("subchannel is left"))),Mo((()=>Lo.push("subchannel is created"))),Po((()=>setTimeout((()=>Lo.push("subchannel is deleted")),2e3))),Oo((()=>Lo.push("feed marker updated"))),(e=>{const t=we();return Ze(t,"UserMarker/onUserMarkerSync","marker.user-sync",(t=>{const{userMarkers:n,userEntityMarkers:r,userFeedMarkers:o}=t,s=zt(t,["userMarkers","userEntityMarkers","userFeedMarkers"]),a=Wt(r),i=Jt(o);Kt(Object.assign({userMarkers:n,userEntityMarkers:a,userFeedMarker:i},s)),e(n[0])}))})((()=>Lo.push("feed marker updated"))),(e=>{const t=we();return Ze(t,"feedMarker/onUserFeedMarkerUpdated","marker.userFeed-updated",(t=>{t.feedMarkers.forEach((t=>{e(t)}))}))})((()=>Lo.push("feed marker updated"))))},Vo=()=>{xo.forEach((e=>e())),xo=[]},Ho=async()=>(await Fo(),$o("start syncing"),No=!0,jo=!0,Qo(),Vo),Wo=()=>{jo=!1,Ko([]),Vo()};ir((async()=>{jo&&await zo()}),2e3);const Jo=()=>No;let Go=[];const Yo=async(e,t,n)=>{const r=we();let o;r.log("client/api/connectClient",Object.assign({apiKey:r.apiKey,sessionState:r.sessionState},e)),r.userId&&r.userId!==e.userId&&(await $r(),Go.forEach((e=>e())),Go=[]);const s=await Nt();try{const{users:n}=await Ar({params:Object.assign(Object.assign({},e),{displayName:null==e?void 0:e.displayName,deviceId:(null==e?void 0:e.deviceId)||s}),options:{setAccessTokenCookie:!0}}),c=n.find((t=>t.userId===e.userId));if(null==c)throw new fe(`${e.userId} has not been founded`,8e5,"error");if(c.isDeleted)return zr("userDeleted"),!1;if(c.isGlobalBanned)return zr("globalBan"),!1;a=r.ws,i=r.emitter,Ge.forEach((e=>{a.on(e,(t=>{i.emit(e,t)}))})),r.ws.open(),r.userId=c.userId,r.sessionHandler=t,o=r.accessTokenExpiryWatcher(t),Ve(c)}catch(e){throw sr().setSessionState("notLoggedIn"),e}var a,i;if(!0!==(null==n?void 0:n.disableRTE)&&async function(){await nt()}(),await(async()=>{var e;const t=await br();if(t===(null===(e=Se(["MessagePreviewSetting"]))||void 0===e?void 0:e.data))return;_e(["MessagePreviewSetting"],t);const n=[],r=[];if("no-message-preview"===t){const e=Ie(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{Te(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&r.push(t.subChannelId)}))}else if("message-preview-not-include-deleted"===t){const e=Ie(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{(null==t?void 0:t.isDeleted)&&(Te(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&r.push(t.subChannelId))})),0!==n.length&&await Kn(n),0!==r.length&&await vr(r)}})(),0===Go.length){Go.push(Hr((e=>{zr("globalBan"),Go.forEach((e=>e())),o()})),(e=>{const t=we();return Ze(t,"client/onTokenTerminated","tokenTerminated",e)})((e=>{zr(),Go.forEach((e=>e())),o()})),qr((e=>{e.userId===r.userId&&(zr("userDeleted"),Go.forEach((e=>e())),o())})),(e=>{const t=we();return Ze(t,"client/onTokenExpired","tokenExpired",e)})((e=>{sr().setSessionState(e),$r(),Go.forEach((e=>e()))})),Ur(Wr),Dr(Wr),mr(),(()=>{const e=on();return e.established(),ar((t=>{"established"===t?e.established():e.handleTokenExpired()})),()=>{e.destroy()}})(),(()=>{const e=yn();return e.startSyncReadReceipt(),ar((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=Kr();return e.startResolver(),ar((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})());const e=await Ho();Go.push(e)}return!0},Zo=()=>{let e,t=!1;const n=we();n.log("initiating access token renewal");const r=async r=>{const{userId:o,displayName:s}=Qe(),a={userId:o,displayName:s,authToken:r,deviceId:await Nt()};"tokenExpired"===n.sessionState&&n.sessionHandler?await Yo(a,n.sessionHandler):await Ar({params:a,options:{setAccessTokenCookie:!0}}),t=!0,e&&clearTimeout(e)};return{renew:()=>{t?console.log("'renew' method can be called only once per renewal instance"):r()},renewWithAuthToken:e=>{t?console.log("'renewWithAuthToken' method can be called only once per renewal instance"):r(e)},unableToRetrieveAuthToken:()=>{e=setTimeout((()=>{var e;null===(e=n.sessionHandler)||void 0===e||e.sessionWillRenewAccessToken(Zo())}),F)}}},Xo=3e5,es=e=>{const t=setInterval((()=>{const t=we();if(!t.token)return;const{issuedAt:n,expiresAt:r}=t.token;if((e=>Date.now()>Date.parse(e)-Xo)(r))return Xe("tokenExpired","tokenExpired"),void Je((()=>e.sessionWillRenewAccessToken(Zo())));(e=>{const{expiresAt:t,issuedAt:n}=e,r=Date.parse(t),o=Date.parse(n),s=Date.now();return s>o+.8*(r-o-Xo)&&s<r})({expiresAt:r,issuedAt:n})&&e.sessionWillRenewAccessToken(Zo())}),F);return()=>clearInterval(t)};var ts;class ns{constructor(){ts.set(this,e.FileAccessTypeEnum.PUBLIC)}setFileAccessType(e){!function(e,t,n,r,o){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===r?o.call(e,n):o?o.value=n:t.set(e,n)}(this,ts,e,"f")}getFileAccessType(){return function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)}(this,ts,"f")}}let rs;ts=new WeakMap;var os=()=>(rs||(rs=new ns),rs);const ss=e=>{const t=we();return Ze(t,"channelMarker/onChannelMarkerFetched","local.channelMarker.fetched",(t=>{t.userEntityMarkers.forEach((t=>{e(t)}))}))},as=e=>{const t=we();return Ze(t,"subChannelMarker/onSubChannelMarkerFetched","local.subChannelMarker.fetched",(t=>{t.userFeedMarkers.forEach(e)}))},is=e=>{const t=we();return Ze(t,"subChannelMarker/onSubChannelMarkerUpdated","local.subChannelMarker.updated",(t=>{e(t.userFeedMarkers)}))},cs=e=>{const t=we();return Ze(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers)}))},ls=e=>{const t=we();return Ze(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers[0])}))},ds=e=>{const t=we();return Ze(t,"messageMarker/onMessageMarkerFetched","local.messageMarker.fetched",(t=>{e(t.contentMarkers[0])}))},us=e=>{const t=we();return Ze(t,"messageMarker/onMessageMarked","marker.marked-message",(t=>{var n,r,o;Kt(t);const s=Ie(["message","collection"]),{contentMarkers:a,feedMarkers:i}=t;if(s&&(null==s?void 0:s.length)>0&&(null==i?void 0:i.length)>0){const e=s.filter((e=>{var t,n;return(null===(n=null===(t=e.data)||void 0===t?void 0:t.query)||void 0===n?void 0:n.subChannelId)===i[0].feedId}));if(e.length>0&&(null==a?void 0:a.length)>0){(null!==(o=null===(r=null===(n=e[0].data)||void 0===n?void 0:n.data)||void 0===r?void 0:r.map((e=>Se(["message","get",e]))).map((({data:e})=>e)).filter(Boolean))&&void 0!==o?o:[]).forEach((e=>{var t,n;const r=["messageMarker","get",de("messageMarker")({creatorId:e.creatorPrivateId,feedId:e.subChannelId,contentId:e.messageId})],o=null===(t=Se(r))||void 0===t?void 0:t.data;if(!o)return;const s=a[0].feedId===o.feedId,i=a[0].readCount>o.readCount,c=(null===(n=a[0])||void 0===n?void 0:n.deliveredCount)>o.deliveredCount;if(s){const e=Object.assign(Object.assign({},o),{readCount:i?a[0].readCount:o.readCount,deliveredCount:c?a[0].deliveredCount:o.deliveredCount});_e(r,e)}}))}}e(t.contentMarkers[0])}))};function hs(e){return"object"==typeof e&&null!==e}const ps=e=>{if(!hs(e))return e;const t=Object.entries(e).map((([t,n])=>{const r=Object.getOwnPropertyDescriptor(e,t);return"function"==typeof(null==r?void 0:r.get)?[t,r.get.call(e)]:[t,n]}));return Object.fromEntries(t)},fs=e=>{if(!hs(e))return e;const t=Object.entries(e).map((([e,t])=>"function"==typeof t?[e,void 0]:[e,t]));return Object.fromEntries(t)},gs=(e,t,n,r,o,s)=>{const{forceDispatch:a,callbackDataSelector:i,callbackFilter:c}=Object.assign({forceDispatch:!1,callbackDataSelector:e=>e},s),{cache:l}=we();let d;l||console.log("For using Live Object feature you need to enable Cache!");let u=!1;const h=[],p=e=>{const{data:n}=e,r=zt(e,["data"]);c&&!c(n,d)||t(Object.assign({data:i(n)},r)),d=ps(n)};return h.push(...o.map((t=>t((t=>((t,r=!1)=>{e===t[n]&&(d&&!r&&ln(d,t)||p({loading:!1,data:t,origin:"event"}))})(t,a)))))),(()=>{const t=se(r,e,!0);ie(t,(({error:e,data:t,loading:n,origin:r,cachedAt:o})=>{-5===o?(p({data:t,origin:r,loading:!1,error:new ge(N,800800,"error")}),u=!0,h.forEach((e=>e()))):u||p({loading:n,data:t,origin:r,error:e}),e&&h.forEach((e=>e()))}))})(),()=>{h.forEach((e=>e()))}};var ms=Object.freeze({__proto__:null,getActiveClient:we,getActiveUser:Qe,setActiveUser:Ve,createClient:(e,t=vt.SG,{debugSession:n="amity",apiEndpoint:r,prefixDeviceIdKey:o}={})=>{var s,a;const i=(e=>{const t=`${null==e?void 0:e.trim()}`.length>0&&!yt,n=f.default(e),r=(e,...r)=>{t&&n(e,r)};return r.__instance__=n,r})(n);i("client/api/createClient",{apiKey:e.replace(/.{5}$/g,"xxxxx"),apiRegion:t});const c=null!==(s=null==r?void 0:r.http)&&void 0!==s?s:wt("http",t),l=null!==(a=null==r?void 0:r.mqtt)&&void 0!==a?a:wt("mqtt",t),d=Tt(c),u=(e=>{const t=y.default(e,{autoConnect:!1,reconnectionDelay:2e3,transports:["websocket"]});return t.on("disconnect",(e=>{"io server disconnect"===e&&t.connect()})),t})(c),h=Lt(l),g=p.default(),m=new Map,v={version:`${U}`,apiKey:e,log:i,cache:{data:{}},http:d,ws:u,mqtt:h,emitter:g,sessionState:"notLoggedIn",accessTokenExpiryWatcher:es,sessionHandler:undefined,hasPermission:Ir,validateUrls:Sr,validateTexts:_r,getFeedSettings:kr,getSocialSettings:wr,getMessagePreviewSetting:br,use:()=>Ce(v),isUnreadCountEnabled:!1,getMarkerSyncConsistentMode:Jo,prefixDeviceIdKey:o,objectSyncMap:m};try{const t=we();if(t.apiKey===e)return t;Ce(v)}catch(e){Ce(v)}return v},login:Yo,logout:$r,secureLogout:async()=>{const e=we(),{data:{success:t}}=await e.http.delete("/api/v4/sessions");if(!t)throw new Error("Failed to logout");return await $r()},isConnected:()=>{var e,t;const n=we();return n.log("client/api/isConnected",n),!!(n.userId&&(null===(t=String(null===(e=n.http.defaults.headers.common)||void 0===e?void 0:e.Authorization))||void 0===t?void 0:t.length)&&n.ws.connected)},getFeedSettings:kr,renewal:Zo,markerSync:Ro,enableUnreadCount:Uo,setUploadedFileAccessType:function(e){os().setFileAccessType(e)},registerPushNotification:async e=>{const t=we();let n;if("ios"!==l.Platform.OS&&"android"!==l.Platform.OS)throw new ve("Unsupported platform");n=l.Platform.OS;const r=await Nt(),{data:{status:o,error:s}}=await t.http.post("/v1/notification",{userId:t.userId,deviceId:r,platform:n,token:e},{headers:{"X-API-Key":t.apiKey}});if(s)throw new ge(s,5e5,"error");return"success"===o},unregisterPushNotification:async()=>{const e=we(),t=Nt(),{data:{status:n,error:r}}=await e.http.delete("/v1/notification",{data:{deviceId:t},headers:{"X-API-Key":e.apiKey}});if(r)throw new ge(r,5e5,"error");return"success"===n},onConnectionError:Vr,onClientDisconnected:e=>Vr((({code:t})=>{800211===t&&e()})),onClientBanned:Hr,onSessionStateChange:ar,onNetworkActivities:e=>_t().onNetworkActivities(e),getTotalUnreadCount:e=>{const{_id:t}=Qe();if(!t)throw new fe("The _id has not been defined in ActiveUser",8e5,"error");return gs(t,e,"userId",(async()=>{const{data:e,cachedAt:t}=await $n();return{data:e,cachedAt:t}}),[ls],{callbackDataSelector:e=>{var t;return null!==(t=null==e?void 0:e.unreadCount)&&void 0!==t?t:0}})},getUserUnread:e=>{const{_id:t}=Qe();if(!t)throw new fe("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:r}=we();r||console.log("For using Live Object feature you need to enable Cache!");n(`liveUserUnread(tmpid: ${Date.now()}) > listen`);const o=[];let s,a=!1;const i=t=>{const{data:n}=t,r=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;s=r?ps(r):r,e({data:r?Object.assign(Object.assign({},r),{hasMentioned:r.isMentioned}):r,loading:t.loading,error:t.error})};return o.push(cs((e=>(e=>{var n;const r=e.filter((e=>t===e.userId)),o=r.reduce(((e,t)=>null==e||new Date(t.lastSyncAt).getTime()>new Date(e.lastSyncAt).getTime()?t:e),null),a={unreadCount:null!==(n=null==o?void 0:o.unreadCount)&&void 0!==n?n:0,isMentioned:r.some((e=>!!e.isMentioned))};ln(s,a)||i({loading:!1,data:a})})(e)))),(()=>{const e=se($n);ie(e,(({error:e,data:t,loading:n,origin:r,cachedAt:s})=>{!function(e){return null!=e&&null!=e}(t)?i({loading:n,data:void 0,origin:r,error:e}):(-5===s?(i({data:t,origin:r,loading:!1,error:new ge(N,800800,"error")}),a=!0,o.forEach((e=>e()))):a||i({loading:n,data:t,origin:r,error:e}),e&&o.forEach((e=>e())))}))})(),()=>{o.forEach((e=>e()))}},getMarkerSyncEvents:()=>Lo,setMarkerSyncEvents:Ko,pushMarkerSyncEvent:$o,markerSyncTrigger:zo,startMarkerSync:Ho,startUnreadSync:async()=>{await Fo(),$o("start syncing"),Uo(),No=!1,jo=!0,Qo()},stopUnreadSync:Wo,stopUnreadSyncing:()=>(console.warn("`stopUnreadSyncing` has been deprecated, please use `stopUnreadSync` instead"),Wo()),getMarkerSyncConsistentMode:Jo});function ys(e){const{users:t,follows:n}=e,r=zt(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n,users:t.map(Un)})}function vs(e){const{users:t,follows:n}=e,r=zt(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n,users:t.map(Un)})}function bs(e){const{follows:t}=e,n=zt(e,["follows"]);return Object.assign(Object.assign({},n),{follows:t})}class ws{constructor(e){const{http:t}=we();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,n,r,o;if("prev"===e&&!this.previousToken)return;if("next"===e&&!this.nextToken)return;let s;"prev"===e&&(s=this.previousToken),"next"===e&&(s=this.nextToken);const a=await this.getRequest(this.queryParams,s);return"first"===e&&(this.nextToken=null===(t=a.paging)||void 0===t?void 0:t.next,this.previousToken=null===(n=a.paging)||void 0===n?void 0:n.previous),"prev"===e&&(this.previousToken=null===(r=a.paging)||void 0===r?void 0:r.previous),"next"===e&&(this.nextToken=null===(o=a.paging)||void 0===o?void 0:o.next),a}getNextToken(){return this.nextToken}getPrevToken(){return this.previousToken}}class Cs extends ws{async getRequest(e,t){const{limit:n=j}=e,r=zt(e,["limit"]),o=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v4/me/user-blocks",{params:Object.assign(Object.assign({},r),{options:o,isDeleted:!1})});return s}}class Is{constructor(e,t){this.query=e,this.cacheKey=t}}class Ss extends Is{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:e.users.map(de("user"))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(o=null==t?void 0:t.data)&&void 0!==o?o:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(de("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Se(this.cacheKey))||void 0===t?void 0:t.data;_e(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class _s{constructor(e){const{http:t}=we();this.queryParams=e,this.http=t}async onFetch(){return await this.getRequest(this.queryParams)}}class ks{constructor(e,t,n,r){this.paginationController=e,this.queryStreamId=t,this.cacheKey=n,this.callback=r}async refresh(){try{let e;if(e=this.paginationController instanceof _s?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({initial:e=!1,direction: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 _s)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 _s)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){const t=e.map(ps).map(fs);return!ln(this.snapshot,t)&&(this.snapshot=t,!0)}getCacheKey(){return this.cacheKey}}function Os(e){const{users:t,follows:n}=e,r=zt(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n.map((e=>{const n=t.find((t=>t.userId===e.from));return Object.assign(Object.assign({},e),{user:Un(n)})})),users:t.map(Un)})}const Ts=e=>Br("user.updated",e),As=e=>Br("user.flagged",e),Es=e=>Br("user.unflagged",e),Ms=e=>Br("user.flagCleared",e);var Ps;!function(e){e.OnUserDeleted="onUserDeleted",e.OnUserUpdated="onUserUpdated",e.OnUserFlagged="onUserFlagged",e.OnUserUnflagged="onUserUnflagged",e.OnUserFlagCleared="onUserFlagCleared"}(Ps||(Ps={}));class Rs extends ks{constructor(e,t){const n=w.default(e),r=["blockedUsers","collection",n];super(new Cs(e),n,r,t),this.query=e,this.queryStreamController=new Ss(this.query,this.cacheKey,this.notifyChange.bind(this),Os),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:qr,action:Ps.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,o;const s=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const a=this.applyFilter(null!==(o=s.data.map((e=>Se(["user","get",e]))).filter(dn).map((({data:e})=>e)).map(wn.user))&&void 0!==o?o:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}const Us=(e,t,n)=>{const{log:r,cache:o}=we();o||console.log(D);const s=Date.now();r(`getBlockedUsers(tmpid: ${s}) > listen`);const a=new Rs(e,t),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>Te(c))),()=>{r(`getBlockedUsers(tmpid: ${s}) > dispose`),i.forEach((e=>e())),Te(c)}},js=(e,t)=>{const n=we();return Ze(n,e,e,(e=>{const r=ys(e);n.cache?(Kt(r),t(r.follows[0])):t(r.follows[0])}))},xs=(e,t)=>{const n=we();return Ze(n,e,e,(e=>{const r=bs(e);n.cache?(Kt(r),t(r.follows[0])):t(r.follows[0])}))},Ds=e=>js("follow.created",e),Ns=e=>js("follow.unfollowed",e),Bs=e=>js("follow.followerDeleted",e),qs=e=>js("follow.requested",e),Fs=e=>js("follow.requestCanceled",e),Ls=e=>js("follow.accepted",e),Ks=e=>js("follow.requestDeclined",e),$s=async e=>{var t,n;const r=we();r.log("follow/getFollowInfo",e);const{data:o}=await r.http.get(r.userId===e?"/api/v4/me/followInfo":`/api/v5/users/${e}/followInfo`),s=r.cache&&Date.now(),a="follows"in o?Object.assign(Object.assign({},o.followCounts[0]),{status:null===(n=null===(t=o.follows)||void 0===t?void 0:t[0])||void 0===n?void 0:n.status}):o.followCounts[0];return r.cache&&_e(["followInfo","get",e],a,{cachedAt:s}),{data:a,cachedAt:s}};$s.locally=e=>{const t=we();if(t.log("follow/getFollowInfo.locally",e),!t.cache)return;const n=Se(["followInfo","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const zs=e=>{const t=async t=>{const[{data:n},{data:r}]=await Promise.all([$s(t.from),$s(t.to)]);e(n),e(r)},n=[js("follow.created",t),js("follow.requested",t),js("follow.accepted",t),js("follow.unfollowed",t),js("follow.requestCanceled",t),js("follow.requestDeclined",t),js("follow.followerDeleted",t),xs("local.follow.created",t),xs("local.follow.requested",t),xs("local.follow.accepted",t),xs("local.follow.unfollowed",t),xs("local.follow.requestDeclined",t)];return()=>{n.forEach((e=>e()))}},Qs=e=>xs("local.follow.created",e),Vs=e=>xs("local.follow.unfollowed",e),Hs=e=>xs("local.follow.requested",e),Ws=e=>xs("local.follow.accepted",e),Js=e=>xs("local.follow.requestDeclined",e);class Gs extends ws{async getRequest(e,t){const{limit:n=j,userId:r}=e,o=zt(e,["limit","userId"]),s=t?{token:t}:{limit:n},a=we().userId===r?"/api/v4/me/followers":`/api/v4/users/${r}/followers`,{data:i}=await this.http.get(a,{params:Object.assign(Object.assign({},o),{options:s,isDeleted:!1})});return i}}var Ys;!function(e){e.OnRequested="onRequested",e.OnAccepted="onAccepted",e.OnDeclined="onDeclined",e.OnCanceled="onCanceled",e.OnFollowed="onFollowed",e.OnUnfollowed="onUnfollowed",e.OnDeleted="onDeleted",e.OnUserDeleted="onUserDeleted"}(Ys||(Ys={}));class Zs extends Is{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:e.follows.map(de("follow"))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(o=null==t?void 0:t.data)&&void 0!==o?o:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(de("follow"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.to&&r){switch(e){case Ys.OnDeclined:case Ys.OnCanceled:case Ys.OnUnfollowed:case Ys.OnDeleted:r.data=r.data.filter((e=>e!==de("follow")(t)));break;case Ys.OnRequested:case Ys.OnAccepted:case Ys.OnFollowed:r.data=[...new Set([de("follow")(t),...r.data])]}_e(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Xs=({userId:e})=>t=>{const n=we();return Ze(n,"user.deleted","user.deleted",(n=>{const r=Nr(n);Kt(r);const o=Se(["follow","get",de("follow")({from:r.users[0].userId,to:e})]);o&&t(null==o?void 0:o.data)}))};class ea extends ks{constructor(e,t){const n=w.default(e),r=["follow","collection",n];super(new Gs(e),n,r,t),this.query=e,this.queryStreamController=new Zs(this.query,this.cacheKey,this.notifyChange.bind(this),ys),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Ds,action:Ys.OnFollowed},{fn:Ns,action:Ys.OnUnfollowed},{fn:Ls,action:Ys.OnAccepted},{fn:Ks,action:Ys.OnDeclined},{fn:Fs,action:Ys.OnCanceled},{fn:Bs,action:Ys.OnDeleted},{fn:Ws,action:Ys.OnAccepted},{fn:Js,action:Ys.OnDeclined},{fn:Qs,action:Ys.OnFollowed},{fn:Vs,action:Ys.OnUnfollowed},{fn:Xs({userId:this.query.userId}),action:Ys.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,o;const s=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const a=this.applyFilter(null!==(o=s.data.map((e=>Se(["follow","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==o?o:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.status&&"all"!==this.query.status&&(t=t.filter((e=>e.status===this.query.status))),t=t.filter((e=>{var t;const n=null===(t=Se(["user","get",e.from]))||void 0===t?void 0:t.data;return null==(null==n?void 0:n.isDeleted)||!1===(null==n?void 0:n.isDeleted)})),t}}class ta extends ws{async getRequest(e,t){const{limit:n=j,userId:r}=e,o=zt(e,["limit","userId"]),s=t?{token:t}:{limit:n},a=we().userId===r?"/api/v4/me/following":`/api/v4/users/${r}/following`,{data:i}=await this.http.get(a,{params:Object.assign(Object.assign({},o),{options:s,isDeleted:!1})});return i}}class na extends Is{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:e.follows.map(de("follow"))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(o=null==t?void 0:t.data)&&void 0!==o?o:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(de("follow"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.from&&r){switch(e){case Ys.OnDeclined:case Ys.OnCanceled:case Ys.OnUnfollowed:case Ys.OnDeleted:r.data=r.data.filter((e=>e!==de("follow")(t)));break;case Ys.OnRequested:case Ys.OnAccepted:case Ys.OnFollowed:r.data=[...new Set([de("follow")(t),...r.data])]}_e(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const ra=({userId:e})=>t=>{const n=we();return Ze(n,"user.deleted","user.deleted",(n=>{const r=Nr(n);Kt(r);const o=Se(["follow","get",de("follow")({from:e,to:r.users[0].userId})]);o&&t(null==o?void 0:o.data)}))};class oa extends ks{constructor(e,t){const n=w.default(e),r=["follow","collection",n];super(new ta(e),n,r,t),this.query=e,this.queryStreamController=new na(this.query,this.cacheKey,this.notifyChange.bind(this),vs),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:qs,action:Ys.OnRequested},{fn:Ls,action:Ys.OnAccepted},{fn:Ks,action:Ys.OnDeclined},{fn:Fs,action:Ys.OnCanceled},{fn:Ds,action:Ys.OnFollowed},{fn:Ns,action:Ys.OnUnfollowed},{fn:Bs,action:Ys.OnDeleted},{fn:Hs,action:Ys.OnRequested},{fn:Ws,action:Ys.OnAccepted},{fn:Js,action:Ys.OnDeclined},{fn:Qs,action:Ys.OnFollowed},{fn:Vs,action:Ys.OnUnfollowed},{fn:ra({userId:this.query.userId}),action:Ys.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,o;const s=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const a=this.applyFilter(null!==(o=s.data.map((e=>Se(["follow","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==o?o:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.status&&"all"!==this.query.status&&(t=t.filter((e=>e.status===this.query.status))),t=t.filter((e=>{var t;const n=null===(t=Se(["user","get",e.to]))||void 0===t?void 0:t.data;return null==(null==n?void 0:n.isDeleted)||!1===(null==n?void 0:n.isDeleted)})),t}}var sa=Object.freeze({__proto__:null,blockUser:async e=>{const t=we();t.log("user/blockUser",e);const{data:n}=await t.http.post(`/api/v4/me/user-blocks/${e}`),r=t.cache&&Date.now(),{follows:o,followCounts:s}=n,a={follows:o};t.cache&&(Kt(a,{cachedAt:r}),Oe(["followInfo","get",e],s[0],{cachedAt:r}));const i=bs(a);return Xe("local.follow.unfollowed",i),n},unBlockUser:async e=>{const t=we();t.log("user/unBlockUser",e);const{data:n}=await t.http.delete(`/api/v4/me/user-blocks/${e}`),r=t.cache&&Date.now(),{follows:o,followCounts:s}=n,a={follows:o};t.cache&&(Kt(a,{cachedAt:r}),Oe(["followInfo","get",e],s[0],{cachedAt:r}));const i=bs(a);return Xe("local.follow.created",i),n},getBlockedUsers:(e,t,n)=>(console.log("Deprecation Notice: UserRepository.Relationship.getBlockedUsers will be deprecated on 9th June 2023, please use UserRepository.getBlockedUsers instead."),Us(e,t)),follow:async e=>{const t=we();t.log("follow/follow",e);const{data:n}=await t.http.post(`/api/v4/me/following/${e}`),r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const o=bs(n);return"accepted"===n.follows[0].status?Xe("local.follow.created",o):Xe("local.follow.requested",o),{data:n.follows[0],cachedAt:r}},unfollow:async e=>{const t=we();t.log("follow/unfollow",e);const{data:n}=await t.http.delete(`/api/v4/me/following/${e}`);t.cache&&Kt(n);const r=bs(n);return Xe("local.follow.unfollowed",r),!0},acceptFollower:async e=>{const t=we();t.log("follow/acceptFollower",e);const{data:n}=await t.http.post(`/api/v4/me/followers/${e}`);t.cache&&Kt(n);const r=bs(n);return Xe("local.follow.accepted",r),!0},acceptMyFollower:async e=>{const t=we();t.log("follow/acceptMyFollower",e);const{data:n}=await t.http.post(`/api/v4/me/followers/${e}`);t.cache&&Kt(n);const r=bs(n);return Xe("local.follow.accepted",r),!0},declineFollower:async e=>{const t=we();t.log("follow/declineFollower",e);const{data:n}=await t.http.delete(`/api/v4/me/followers/${e}`);t.cache&&Kt(n);const r=bs(n);return Xe("local.follow.requestDeclined",r),!0},declineMyFollower:async e=>{const t=we();t.log("follow/declineMyFollower",e);const{data:n}=await t.http.delete(`/api/v4/me/followers/${e}`);t.cache&&Kt(n);const r=bs(n);return Xe("local.follow.requestDeclined",r),!0},onUserFollowed:Ds,onUserUnfollowed:Ns,onFollowerDeleted:Bs,onFollowerRequested:qs,onFollowRequestCanceled:Fs,onFollowRequestAccepted:Ls,onFollowRequestDeclined:Ks,onFollowInfoUpdated:zs,onLocalUserFollowed:Qs,onLocalUserUnfollowed:Vs,onLocalFollowerRequested:Hs,onLocalFollowRequestAccepted:Ws,onLocalFollowRequestDeclined:Js,observeFollowInfo:(e,t,n="cache_then_server")=>{const{log:r}=we(),o=Date.now();r(`observeFollowInfo(tmpid: ${o}) > listen`);const s=(e,n)=>{var r,o;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(o=t[n])||void 0===o||o.call(t,e)},a=[];return a.push(zs((t=>((t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.userId)===e&&s(t,n)})({data:t,loading:!1,origin:"event"},"onUpdate")))),ie(se($s,e),(e=>(e.data||e.error)&&s(e,"onFetch")),ae(n)),()=>{r(`observeFollowInfo(tmpid: ${o}) > dispose`),a.forEach((e=>e()))}},observeFollowers:(e,t)=>{const{log:n}=we(),r=Date.now();n(`observeFollowers(tmpid: ${r}) > listen`);const o=[],s=(e,n)=>{var r,o;if(t instanceof Function)return t(e);null===(r=t.onEvent)||void 0===r||r.call(t,n,e),null===(o=t[n])||void 0===o||o.call(t,e)};return o.push(qs((e=>s(e,"onRequested"))),Ls((e=>s(e,"onAccepted"))),Ks((e=>s(e,"onDeclined"))),Fs((e=>s(e,"onCanceled"))),Ds((e=>s(e,"onFollowed"))),Ns((e=>s(e,"onUnfollowed"))),Bs((e=>s(e,"onDeleted"))),Hs((e=>s(e,"onRequested"))),Ws((e=>s(e,"onAccepted"))),Js((e=>s(e,"onDeclined"))),Qs((e=>s(e,"onFollowed"))),Vs((e=>s(e,"onUnfollowed")))),()=>{n(`observeFollowers(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},observeFollowings:(e,t)=>{const{log:n}=we(),r=Date.now();n(`observeFollowings(tmpid: ${r}) > listen`);const o=[],s=(e,n)=>{var r,o;if(t instanceof Function)return t(e);null===(r=t.onEvent)||void 0===r||r.call(t,n,e),null===(o=t[n])||void 0===o||o.call(t,e)};return o.push(qs((e=>s(e,"onRequested"))),Ls((e=>s(e,"onAccepted"))),Ks((e=>s(e,"onDeclined"))),Fs((e=>s(e,"onCanceled"))),Ds((e=>s(e,"onFollowed"))),Ns((e=>s(e,"onUnfollowed"))),Bs((e=>s(e,"onDeleted"))),Hs((e=>s(e,"onRequested"))),Ws((e=>s(e,"onAccepted"))),Js((e=>s(e,"onDeclined"))),Qs((e=>s(e,"onFollowed"))),Vs((e=>s(e,"onUnfollowed")))),()=>{n(`observeFollowings(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},getFollowers:(e,t,n)=>{const{log:r,cache:o}=we();o||console.log(D);const s=Date.now();r(`getFollowers(tmpid: ${s}) > listen`);const a=new ea(e,t),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>Te(c))),()=>{r(`getFollowers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getFollowings:(e,t,n)=>{const{log:r,cache:o}=we();o||console.log("For using Live Collection feature you need to enable Cache!");const s=Date.now();r(`getFollowings(tmpid: ${s}) > listen`);const a=new oa(e,t),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>Te(c))),()=>{r(`getFollowings(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getFollowInfo:(e,t)=>gs(e,t,"userId",$s,[zs],{forceDispatch:!0}),getMyFollowInfo:e=>{const{userId:t}=Qe();return gs(t,e,"userId",$s,[zs],{forceDispatch:!0})}});const aa=async e=>{const t=we();t.log("user/getUsers",e);const n=e.map((e=>encodeURIComponent(e))),{data:r}=await t.http.get("/api/v3/users/list",{params:{userIds:n}}),o=Nr(r),s=t.cache&&Date.now();return t.cache&&Kt(o,{cachedAt:s}),Xe("user.fetched",r),{data:o.users.map((e=>wn.user(e))),cachedAt:s}};aa.locally=e=>{var t;const n=we();if(n.log("user/getUsers.locally",e),!n.cache)return;const r=e.map((e=>Se(["user","get",e]))).filter(Boolean),o=r.map((({data:e})=>wn.user(e))),s=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:o,cachedAt:s.cachedAt}};const ia=e=>Br("user.fetched",e),ca=async e=>{const t=we();t.log("user/getUser",e),lr("user",e);try{const{data:n}=await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`),r=t.cache&&Date.now(),o=Nr(n);return t.cache&&Kt(o,{cachedAt:r}),Xe("user.fetched",n),{data:o.users.find((t=>t.userId===e)),cachedAt:r}}catch(t){throw V(null==t?void 0:t.code)&&$t("user",e),t}};ca.locally=e=>{const t=we();if(t.log("user/getUser.locally",e),!t.cache)return;const n=Se(["user","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class la extends ws{async getRequest(e,t){const{limit:n=j,displayName:r}=e,o=zt(e,["limit","displayName"]),s=t?{token:t}:{limit:n},{data:a}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},o),{keyword:r,options:s,isDeleted:!1})});return a}}class da extends Is{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:e.users.map(de("user"))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(o=null==t?void 0:t.data)&&void 0!==o?o:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(de("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Se(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],_e(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class ua extends ks{constructor(e,t){const n=w.default(e),r=["user","collection",n];super(new la(e),n,r,t),this.query=e,this.queryStreamController=new da(this.query,this.cacheKey,this.notifyChange.bind(this),Nr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:qr,action:Ps.OnUserDeleted},{fn:Ts,action:Ps.OnUserUpdated},{fn:As,action:Ps.OnUserFlagged},{fn:Es,action:Ps.OnUserUnflagged},{fn:Ms,action:Ps.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var r,o;const s=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const a=this.applyFilter(null!==(o=s.data.map((e=>Se(["user","get",e]))).filter(dn).map((({data:e})=>e)).map(wn.user))&&void 0!==o?o:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;if(!this.query.displayName){const e=(()=>{switch(this.query.sortBy){case"firstCreated":return Be;case"lastCreated":default:return Fe;case"displayName":return De}})();t=t.sort(e)}return"flagged"===this.query.filter&&(t=t.filter((e=>!!e.hashFlag))),t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}const ha=async e=>{const{data:t,cachedAt:n}=await ca(e);return{data:wn.user(t),cachedAt:n}};ha.locally=e=>{const t=ca.locally(e);if(t)return{data:wn.user(t.data),cachedAt:t.cachedAt}};class pa extends ws{async getRequest(e,t){const{limit:n=j,displayName:r}=e,o=zt(e,["limit","displayName"]),s=t?{token:t}:{limit:n},{data:a}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},o),{keyword:r,options:s,isDeleted:!1})});return a}}class fa extends Is{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:e.users.map(de("user"))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(o=null==t?void 0:t.data)&&void 0!==o?o:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(de("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Se(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],_e(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class ga extends ks{constructor(e,t){var n;const r=w.default(e),o=["user","collection",r];super(new pa(e),r,o,t),this.query=Object.assign(Object.assign({},e),{filter:null!==(n=e.filter)&&void 0!==n?n:"all"}),this.queryStreamController=new fa(this.query,this.cacheKey,this.notifyChange.bind(this),Nr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:qr,action:Ps.OnUserDeleted},{fn:Ts,action:Ps.OnUserUpdated},{fn:As,action:Ps.OnUserFlagged},{fn:Es,action:Ps.OnUserUnflagged},{fn:Ms,action:Ps.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var r,o;const s=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const a=this.applyFilter(null!==(o=s.data.map((e=>Se(["user","get",e]))).filter(dn).map((({data:e})=>e)).map(wn.user))&&void 0!==o?o:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return"flagged"===this.query.filter&&(t=t.filter((e=>!!e.hashFlag))),t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}const ma=async({viewId:e,viewedType:t,limit:n,token:r})=>{const o=we(),s={};r?s.token=r:s.limit=n;const a=`/api/v1/analytics/views/${"post"===t?"posts":"stories"}/${e}/users`,i=await o.http.get(a,{params:s});return Kt(i.data),i.data};var ya=Object.freeze({__proto__:null,Relationship:sa,getUserByIds:aa,updateUser:async(e,t)=>{const n=we();n.log("user/updateUser",e,t);const{data:r}=await n.http.put("/api/v3/users/",Object.assign(Object.assign({userId:e},t),{createNewUserWhenNotFound:!1})),o=Nr(r),s=n.cache&&Date.now();return n.cache&&Kt(o,{cachedAt:s}),Xe("user.updated",r),{data:o.users.find((t=>t.userId===e)),cachedAt:s}},flagUser:async e=>{const t=we();t.log("user/flagUser",e);const{data:n}=await t.http.post(`api/v4/me/flags/${encodeURIComponent(e)}`),r=Nr(n);return t.cache&&Kt(r),Xe("user.flagged",n),!!r},unflagUser:async e=>{const t=we();t.log("user/unflag",e);const{data:n}=await t.http.delete(`/api/v4/me/flags/${encodeURIComponent(e)}`),r=Nr(n);return t.cache&&Kt(r),Xe("user.unflagged",n),!!r},isUserFlaggedByMe:async e=>{const t=we();t.log("user/isUserFlaggedByMe",e);const{data:{isFlagByMe:n}}=await t.http.get(`/api/v3/users/${e}/isFlagByMe`);return n},onUserUpdated:Ts,onUserDeleted:qr,onUserFlagged:As,onUserUnflagged:Es,onUserFlagCleared:Ms,getUser:(e,t)=>gs(e,(e=>t(Object.assign(Object.assign({},e),{data:e.data?wn.user(e.data):e.data}))),"userId",ca,[ia,Ts,qr,As,Es,Ms]),getUsers:(e,t,n)=>{const{log:r,cache:o}=we();o||console.log(D);const s=Date.now();r(`liveUsers(tmpid: ${s}) > listen`);const a=new ua(e,t),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>Te(c))),()=>{r(`liveUsers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},observeUser:(e,t)=>{const{log:n}=we(),r=Date.now();n(`observeUser(tmpid: ${r}) > listen`);const o=(n,r)=>{var o,s,a;if((null===(o=n.data)||void 0===o?void 0:o.userId)!==e)return;const i=Object.assign(Object.assign({},n),{data:wn.user(n.data)});if(t instanceof Function)return t(i);"onFetch"!==r&&(null===(s=t.onEvent)||void 0===s||s.call(t,r,i)),null===(a=t[r])||void 0===a||a.call(t,i)},s=[];return s.push(Ts((e=>o({data:e,loading:!1,origin:"event"},"onUpdate"))),qr((e=>o({data:e,loading:!1,origin:"event"},"onDelete"))),As((e=>o({data:e,loading:!1,origin:"event"},"onFlagged"))),Es((e=>o({data:e,loading:!1,origin:"event"},"onUnflagged"))),Ms((e=>o({data:e,loading:!1,origin:"event"},"onFlagCleared")))),ie(se(ha,e),(e=>e.data&&o(e,"onFetch"))),()=>{n(`observeUser(tmpid: ${r}) > dispose`),s.forEach((e=>e()))}},getBlockedUsers:Us,searchUserByDisplayName:(e,t,n)=>{const{log:r,cache:o}=we();o||console.log(D);const s=Date.now();r(`liveSearchUsers(tmpid: ${s}) > listen`);const a=new ga(e,t),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>Te(c))),()=>{r(`liveSearchUsers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getViewedUsers:(e,t)=>{const{log:n,cache:r}=we(),o=["postViewedUsers","collection",{postId:e.postId}];r||console.log(D);const s=Date.now();n(`getViewedUsers(tmpid: ${s}) > listen`);const{limit:a,postId:i}=e,c=(e=!1)=>{var n,r,s;const l=null===(n=Se(o))||void 0===n?void 0:n.data,d=null!==(r=null==l?void 0:l.data)&&void 0!==r?r:[];if(!e&&d.length>0&&!(null==l?void 0:l.params.page))return;const u=se(ma,{viewId:i,viewedType:"post",limit:a||10,token:e||null===(s=null==l?void 0:l.params.page)||void 0===s?void 0:s.next});ie(u,(e=>{var n,r,s,a,i;let l=null!==(s=null===(r=null===(n=Se(o))||void 0===n?void 0:n.data)||void 0===r?void 0:r.data)&&void 0!==s?s:[];(null===(a=e.data)||void 0===a?void 0:a.users)&&(l=[...new Set([...l,...e.data.users.map((({userId:e})=>e))])]);const d={loading:e.loading,params:{page:null===(i=e.data)||void 0===i?void 0:i.paging},data:l||[]};_e(o,d),(e=>{var n,r;let o=[];(null==e?void 0:e.data)&&(o=e.data.map((e=>Se(["user","get",e]))).filter(Boolean).map((e=>null==e?void 0:e.data))||[]),t({onNextPage:c,data:o,hasNextPage:!!(null===(r=null===(n=e.params)||void 0===n?void 0:n.page)||void 0===r?void 0:r.next),loading:e.loading||!1})})(d)}),ae(x,2e3))};return c(!0),()=>{n(`getViewedUsers(tmpid: ${s}) > dispose`),Te(o)}},getReachedUsers:(e,t)=>{let n=(e=!1)=>{};const{log:r,cache:o}=we(),s=["viewedUsers","collection",{viewId:e.viewId,viewedType:e.viewedType}];o||console.log(D);const a=Date.now();r(`getReachUsers(tmpid: ${a}) > listen`);const{limit:i,viewId:c,viewedType:l}=e;return n=(e=!1)=>{var r,o,a;const d=null===(r=Se(s))||void 0===r?void 0:r.data,u=null!==(o=null==d?void 0:d.data)&&void 0!==o?o:[];if(!e&&u.length>0&&!(null==d?void 0:d.params.page))return;const h=se(ma,{viewId:c,viewedType:l,limit:i||10,token:e||null===(a=null==d?void 0:d.params.page)||void 0===a?void 0:a.next});ie(h,(e=>{var r,o,a,i,c;let l=null!==(a=null===(o=null===(r=Se(s))||void 0===r?void 0:r.data)||void 0===o?void 0:o.data)&&void 0!==a?a:[];(null===(i=e.data)||void 0===i?void 0:i.users)&&(l=[...new Set([...l,...e.data.users.map((({userId:e})=>e))])]);const d={loading:e.loading,params:{page:null===(c=e.data)||void 0===c?void 0:c.paging},data:l||[]};_e(s,d),(e=>{var r,o;let s=[];(null==e?void 0:e.data)&&(s=e.data.map((e=>Se(["user","get",e]))).filter(Boolean).map((e=>null==e?void 0:e.data))||[]),t({onNextPage:n,data:s,hasNextPage:!!(null===(o=null===(r=e.params)||void 0===r?void 0:r.page)||void 0===o?void 0:o.next),loading:e.loading||!1})})(d)}),ae(x,2e3))},n(!0),()=>{r(`getReachUsers(tmpid: ${a}) > dispose`),Te(s)}}});const va=async e=>{const t=we();t.log("file/getFile",e);const{data:n}=await t.http.get(`/api/v3/files/${e}`),r=t.cache&&Date.now();return t.cache&&Kt({files:[n]},{cachedAt:r}),{data:n,cachedAt:r}};va.locally=e=>{const t=we();if(t.log("file/getFile.locally",e),!t.cache)return;const n=Se(["file","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const ba=async(e,t,n)=>{const r=we();r.log("file/uploadVideo",e);const o=e.getAll("files");if(!o.length)throw new Error("The formData object must have a `files` key.");const s=os().getFileAccessType();e.append("accessType",s),e.append("preferredFilename",o[0].name),t&&e.append("feedType",t);const a="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await r.http.post("/api/v4/videos",e,{headers:a,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),c=r.cache&&Date.now();return r.cache&&Kt({files:i},{cachedAt:c}),{data:i,cachedAt:c}},wa=async(e,t)=>{const n=we();n.log("file/uploadImage",e);const r=e.getAll("files");if(!r.length)throw new Error("The formData object must have a `files` key.");const o=os().getFileAccessType();e.append("accessType",o),e.append("preferredFilename",r[0].name);const s="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:a}=await n.http.post("/api/v4/images",e,{headers:s,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),i=n.cache&&Date.now();return n.cache&&Kt({files:a},{cachedAt:i}),{data:a,cachedAt:i}};var Ca=Object.freeze({__proto__:null,getFile:va,uploadFile:async(e,t)=>{const n=we();n.log("file/uploadFile",e);const r=e.getAll("files");if(!r.length)throw new Error("The formData object must have a `files` key.");const o=os().getFileAccessType();e.append("accessType",o),e.append("preferredFilename",r[0].name);const s="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:a}=await n.http.post("/api/v4/files",e,{headers:s,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),i=n.cache&&Date.now();return n.cache&&Kt({files:a},{cachedAt:i}),{data:a,cachedAt:i}},deleteFile:async e=>{const t=we();return t.log("file/deleteFile",e),await t.http.delete(`/api/v3/files/${e}`),Te(["file","get",e],!0),{success:!0}},fileUrlWithSize:(e,t)=>`${e}?size=${t}`,uploadVideo:ba,uploadImage:wa,createImage:async(e,t)=>{const n=we();n.log("file/createImage",e);const r=e.getAll("files");if(!r.length)throw new Error("The formData object must have a `files` key.");const o=os().getFileAccessType();e.append("accessType",o),e.append("preferredFilename",r[0].name);const s="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:a}=await n.http.post("/api/v4/images",e,{headers:s,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),i=n.cache&&Date.now();return n.cache&&Kt({files:a},{cachedAt:i}),{data:a,cachedAt:i}},createFile:async(e,t)=>{const n=we();n.log("file/createFile",e);const r=e.getAll("files");if(!r.length)throw new Error("The formData object must have a `files` key.");const o=os().getFileAccessType();e.append("accessType",o),e.append("preferredFilename",r[0].name);const s="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:a}=await n.http.post("/api/v4/files",e,{headers:s,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),i=n.cache&&Date.now();return n.cache&&Kt({files:a},{cachedAt:i}),{data:a,cachedAt:i}},createVideo:async(e,t,n)=>{const r=we();r.log("file/createVideo",e);const o=e.getAll("files");if(!o.length)throw new Error("The formData object must have a `files` key.");const s=os().getFileAccessType();e.append("accessType",s),e.append("preferredFilename",o[0].name),t&&e.append("feedType",t);const a="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await r.http.post("/api/v4/videos",e,{headers:a,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),c=r.cache&&Date.now();return r.cache&&Kt({files:i},{cachedAt:c}),{data:i,cachedAt:c}},observeFile:(e,t)=>{const{log:n}=we(),r=Date.now();n(`observeFile(tmpid: ${r}) > listen`);return ie(se(va,e),(n=>n.data&&((n,r)=>{var o,s,a;if((null===(o=n.data)||void 0===o?void 0:o.fileId)===e){if(t instanceof Function)return t(n);"onFetch"!==r&&(null===(s=t.onEvent)||void 0===s||s.call(t,r,n)),null===(a=t[r])||void 0===a||a.call(t,n)}})(n,"onFetch"))),()=>{n(`observeFile(tmpid: ${r}) > dispose`)}}});const Ia=async e=>{const t=we();t.log("role/queryRoles",e);const n=null!=e?e:{},{page:r,limit:o=10,queryToken:s,displayName:a,sortBy:i}=n,c=zt(n,["page","limit","queryToken","displayName","sortBy"]),l=s?{token:s}:o?{limit:o}:r?{token:Y(r,"skiplimit")}:void 0,{data:d}=await t.http.get("/api/v3/roles",{params:Object.assign(Object.assign({},c),{keyword:a,sortBy:i,options:l})}),{paging:u}=d,h=zt(d,["paging"]),{roles:p}=h,f=t.cache&&Date.now();t.cache&&Kt(h,{cachedAt:f});const g=Z(u.next);return{data:p,cachedAt:f,prevPage:Z(u.previous),nextPage:g,paging:u}};Ia.locally=e=>{we().log("role/queryRoles.locally",e)};const Sa=async e=>{const t=we();t.log("role/getRole",e);const{data:n}=await t.http.get(`/api/v3/roles/${e}`),r=t.cache&&Date.now();return t.cache&&Kt({roles:n},{cachedAt:r}),{data:n.find((t=>t.roleId===e)),cachedAt:r}};Sa.locally=e=>{const t=we();if(t.log("role/getRole.locally",e),!t.cache)return;const n=Se(["role","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const _a=(e,t)=>{"message"===e?Xe("local.message.updated",{messages:[t]}):"post"===e?Xe("post.updated",{posts:[t]}):"comment"===e?Xe("comment.updated",{comments:[t]}):"story"===e&&Xe("story.updated",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[t]})},ka=async(e,t=!1)=>{const n=we();let r;n.log("message/getMessage",e),t||console.log("getMessage will be deprecated on 15th November 2022, please use liveMessage instead."),lr("message",e);try{const{data:t}=await n.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);r=await Yn(t)}catch(t){throw V(null==t?void 0:t.code)&&$t("message",e),t}const o=n.cache&&Date.now();n.cache&&Kt(r,{cachedAt:o});const{messages:s}=r;return Xe("local.message.fetched",{messages:s}),{data:s.find((t=>t.messageId===e)),cachedAt:o}};ka.locally=e=>{const t=we();if(t.log("message/getMessage.locally",e),!t.cache)return;const n=Se(["message","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Oa=async e=>{const t=we();let n;t.log("post/getPost",e),lr("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw V(null==t?void 0:t.code)&&$t("post",e),t}const r=Vt(n,"communityUsers"),o=t.cache&&Date.now();t.cache&&Kt(r,{cachedAt:o});const{posts:s}=r,a=s.find((t=>t.postId===e));return{data:wn.post(a),cachedAt:o}};Oa.locally=e=>{const t=we();if(t.log("post/getPost.locally",e),!t.cache)return;const n=Se(["post","get",e]);return n?{data:wn.post(n.data),cachedAt:n.cachedAt}:void 0};const Ta=async e=>{const t=we();let n;t.log("comment/getComment",e),lr("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw V(null==t?void 0:t.code)&&$t("comment",e),t}const r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const{comments:o}=n;return{data:wn.comment(o.find((t=>t.commentId===e))),cachedAt:r}};function Aa(e,t){return e.map((e=>{if(null==e.isJoined){const n=t.some((t=>function(e,t){const{userId:n}=Qe();return e.communityId===t.communityId&&t.userId===n}(e,t)&&"none"!==t.communityMembership));return Object.assign(Object.assign({},e),{isJoined:n})}return e}))}Ta.locally=e=>{const t=we();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=Se(["comment","get",e]);return n?{data:wn.comment(n.data),cachedAt:n.cachedAt}:void 0};const Ea=(e,t)=>{var n,r;let o,s;if("post"===t)s="post",o=e.posts[0].postId;else if("comment"===t)s="comment",o=e.comments[0].commentId;else{if("story"!==t)throw new Error("Unknown event type");s="story",o=e.stories[0].referenceId}return(null===(r=null===(n=Se([s,"get",o]))||void 0===n?void 0:n.data)||void 0===r?void 0:r.myReactions)||[]},Ma=(e,t,n)=>{const[r]=e[t];return Object.assign(Object.assign({},e),{[t]:[Object.assign(Object.assign({},r),{myReactions:n})]})},Pa=(e,t,n,r=[])=>{const o=e.split(".")[1];let s=r;if(we().userId===t)if(["addReaction","reactionAdded"].includes(o))s.includes(n)||s.push(n);else{if(!["removeReaction","reactionRemoved"].includes(o))throw new Error(`Unknown event type: ${o}`);s=s.filter((e=>e!==n))}return s},Ra=(e,t)=>{const n=e.split(".")[0],r=Ea(t,n),o=Pa(e,t.reactor.userId,t.reactor.reactionName,r);return Ma(t,`${n}s`,o)},Ua=(e,t)=>{var n,r;const o=e.split(".")[0];let s=Ea(t,o);(null==t?void 0:t.reactions)&&t.reactions.length>0&&(s=Pa(e,null===(n=t.reactions[0])||void 0===n?void 0:n.userId,null===(r=t.reactions[0])||void 0===r?void 0:r.reactionName,s));const a=Ma(t,"stories",s);if(!(null==t?void 0:t.communities)||!(null==t?void 0:t.communityUsers))return a;const i=Aa(t.communities,t.communityUsers);return Object.assign(Object.assign({},a),{communities:i})},ja=async(e,t,n)=>{var r,o;const s=we();if(s.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),await s.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0}),s.cache){const s=Se([e,"get",t]);if(!s)return!0;const a=Object.assign(Object.assign({},s.data),{reactionsCount:s.data.reactionsCount+1,myReactions:[...null!==(r=s.data.myReactions)&&void 0!==r?r:[],n],reactions:Object.assign(Object.assign({},s.data.reactions),{[n]:(null!==(o=s.data.reactions[n])&&void 0!==o?o:0)+1})});if("comment"===e)return Xe("local.comment.addReaction",{comment:a}),!0;if("post"===e)return Xe("local.post.addReaction",{post:a}),!0}return!0};ja.optimistically=(e,t,n)=>{var r,o,s,a,i;const c=we();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const l=Se([e,"get",t]);if(!(null==l?void 0:l.data)||(null===(r=l.data.myReactions)||void 0===r?void 0:r.includes(n)))return;const d=Object.assign(Object.assign({},l.data),{reactionsCount:l.data.reactionsCount+1,myReactions:[...null!==(o=l.data.myReactions)&&void 0!==o?o:[],n],reactions:Object.assign(Object.assign({},l.data.reactions),{[n]:(null!==(s=l.data.reactions[n])&&void 0!==s?s:0)+1})});return Oe([e,"get",t],d,{cachedAt:-5}),_a(e,d),null!==(i=null===(a=null==d?void 0:d.myReactions)||void 0===a?void 0:a.includes(n))&&void 0!==i&&i};const xa=async(e,t,n)=>{var r,o;const s=we();if(s.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),await s.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0}}),s.cache){const s=Se([e,"get",t]);if(!s)return!0;const a=Object.assign(Object.assign({},s.data),{reactionsCount:Math.max(0,s.data.reactionsCount-1),myReactions:(null!==(r=s.data.myReactions)&&void 0!==r?r:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},s.data.reactions),{[n]:Math.max(0,(null!==(o=s.data.reactions[n])&&void 0!==o?o:0)-1)})});if("comment"===e)return Xe("local.comment.removeReaction",{comment:a}),!0;if("post"===e)return Xe("local.post.removeReaction",{post:a}),!0}return!0};xa.optimistically=(e,t,n)=>{var r,o,s,a,i;const c=we();if(c.log("reaction/removeReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const l=Se([e,"get",t]);if(!(null==l?void 0:l.data)||!(null===(r=l.data.myReactions)||void 0===r?void 0:r.includes(n)))return;const d=Object.assign(Object.assign({},l.data),{reactionsCount:Math.max(0,l.data.reactionsCount-1),myReactions:(null!==(o=l.data.myReactions)&&void 0!==o?o:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},l.data.reactions),{[n]:Math.max(0,(null!==(s=l.data.reactions[n])&&void 0!==s?s:0)-1)})});return Oe([e,"get",t],d,{cachedAt:-5}),_a(e,d),null!==(i=!(null===(a=null==d?void 0:d.myReactions)||void 0===a?void 0:a.includes(n)))&&void 0!==i&&i};const Da=e=>{var t;return null!==(t=Object.keys(A).find((t=>e.needApprovalOnPostCreation===A[t].needApprovalOnPostCreation&&e.onlyAdminCanPost===A[t].onlyAdminCanPost)))&&void 0!==t?t:E};function Na({communities:e}){return e.map((e=>{var{needApprovalOnPostCreation:t,onlyAdminCanPost:n}=e,r=zt(e,["needApprovalOnPostCreation","onlyAdminCanPost"]);return Object.assign({postSetting:Da({needApprovalOnPostCreation:t,onlyAdminCanPost:n})},r)}))}const Ba=e=>{const t=Na({communities:e.communities}),n=e.communityUsers.map((t=>{const n=e.users.find((e=>e.userId===t.userId));return Object.assign(Object.assign({},t),{user:n})})),r=Aa(t,n);return Object.assign(Object.assign({},e),{communities:r,communityUsers:n})},qa=e=>{const t=Na({communities:e.communities}),n=e.communityUsers.map((t=>{const n=e.users.find((e=>e.userId===t.userId));return Object.assign(Object.assign({},t),{user:n})})),r=Aa(t,n);return Object.assign(Object.assign({},e),{communities:r,communityUsers:n})},Fa=e=>{const{postSetting:t,storySetting:n}=e,r=zt(e,["postSetting","storySetting"]);return Object.assign(Object.assign(Object.assign({},r),t?A[t]:void 0),{allowCommentInStory:"boolean"!=typeof(null==n?void 0:n.enableComment)||n.enableComment})},La=e=>{const{posts:t}=e,n=zt(e,["posts"]),r=Na({communities:n.communities}),o=n.communityUsers.map((e=>{const t=n.users.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),s=Aa(r,o),a=t.map((e=>{var t;const r=null===(t=n.feeds.find((t=>t.feedId===e.feedId)))||void 0===t?void 0:t.feedType;return Object.assign(Object.assign({},e),{feedType:r})}));return Object.assign(Object.assign({},n),{posts:a,communities:s,communityUsers:o})},Ka=e=>{var{searchResult:t,polls:n}=e,r=zt(e,["searchResult","polls"]);const o=La(r);return Object.assign(Object.assign({},o),{polls:n})},$a=(e,t)=>{const n=we();return Ze(n,e,e,(r=>{var o;if(n.cache){const s=La(r),{communities:a}=s;if(Kt(s),(null==a?void 0:a[0])&&!["post.updated"].includes(e)&&Xe("community.updated",{communities:a,categories:[],communityUsers:s.communityUsers,feeds:[],files:[],users:[]}),"post.deleted"===e){const{postId:e,postedUserId:o}=r.posts[0];try{lr("post",e)}catch(e){return}return o!==n.userId&&Te(["post","get",e]),t(r.posts[0])}const i=Se(["post","get",r.posts[0].postId]);if(["post.created","post.approved","post.declined"].includes(e)){let t=null===(o=Ie(["post","query"]))||void 0===o?void 0:o.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.targetId)===i.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})=>Oe(e,t,{cachedAt:-1})))}t(i.data)}else t(r.posts[0])}))},za=(e,t)=>{const n=we();return Ze(n,e,e,(r=>{if(n.cache){const n=La(r),{communities:o}=n;Kt(n),(null==o?void 0:o[0])&&!["local.post.updated"].includes(e)&&Xe("community.updated",{communities:o,categories:[],communityUsers:n.communityUsers,feeds:[],files:[],users:[]});const s=Se(["post","get",r.posts[0].postId]);t(s.data)}else t(r.posts[0])}))},Qa=e=>$a("post.created",e),Va=e=>$a("post.updated",e),Ha=e=>$a("post.deleted",e),Wa=e=>$a("post.approved",e),Ja=e=>$a("post.declined",e),Ga=e=>$a("post.flagged",e),Ya=e=>$a("post.unflagged",e),Za=e=>{const t=we();return Ze(t,"post.addReaction","post.addReaction",(n=>{if(t.cache){const t=zt(Ra("post.addReaction",n),["reactor"]);Kt(t);const r=Se(["post","get",n.posts[0].postId]);e(r.data)}else e(n.posts[0])}))},Xa=e=>{const t=we();return Ze(t,"post.removeReaction","post.removeReaction",(n=>{if(t.cache){const t=zt(Ra("post.removeReaction",n),["reactor"]);Kt(t);const r=Se(["post","get",n.posts[0].postId]);e(r.data)}else e(n.posts[0])}))},ei=(e,t)=>{const n=we();return Ze(n,e,e,(r=>{var o;if(n.cache){const s=["comment.flagged","comment.unflagged"].includes(e)?(e=>{const t=Ea(e,"comment");return Ma(e,"comments",t)})(r):r;Kt(s);const{comments:a}=s;if(a.length>0){const r=Se(["comment","get",a[0].commentId]);if(["comment.created"].includes(e)){if("comment.created"===e&&r.data.userId===n.userId)return;if(a[0].parentId){const e=Se(["comment","get",a[0].parentId]);(null==e?void 0:e.data)&&(e.data.children.includes(a[0].commentId)||_e(["comment","get",a[0].parentId],Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,a[0].commentId])]})))}const t=null===(o=Ie(["comment","query"]))||void 0===o?void 0:o.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===r.data.referenceId}));null==t||t.map((({key:e,data:t})=>Oe(e,t,{cachedAt:-1})))}t(wn.comment(r.data))}}else t(wn.comment(r.comments[0]))}))},ti=(e,t)=>{const n=we();return Ze(n,e,e,(r=>{var o;if(n.cache){const n=r;Kt(n);const{comments:s}=n;if(s.length>0){const n=Se(["comment","get",s[0].commentId]);if(["local.comment.created"].includes(e)){if(s[0].parentId){const e=Se(["comment","get",s[0].parentId]);if((null==e?void 0:e.data)&&!e.data.children.includes(s[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,s[0].commentId])]});_e(["comment","get",s[0].parentId],t),setTimeout((()=>{Xe("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}const e=null===(o=Ie(["comment","query"]))||void 0===o?void 0:o.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})=>Oe(e,t,{cachedAt:-1})))}t(wn.comment(n.data))}}else t(wn.comment(r.comments[0]))}))},ni=e=>ei("comment.created",e),ri=e=>ei("comment.updated",e),oi=e=>ei("comment.deleted",e),si=e=>ei("comment.flagged",e),ai=e=>ei("comment.unflagged",e),ii=e=>{const t=we();return Ze(t,"comment.addReaction","comment.addReaction",(n=>{if(t.cache){const t=zt(Ra("comment.addReaction",n),["reactor"]);Kt(t);const r=Se(["comment","get",n.comments[0].commentId]);e(wn.comment(r.data))}else e(wn.comment(n.comments[0]))}))},ci=e=>{const t=we();return Ze(t,"comment.removeReaction","comment.removeReaction",(n=>{if(t.cache){const t=zt(Ra("comment.removeReaction",n),["reactor"]);Kt(t);const r=Se(["comment","get",n.comments[0].commentId]);e(wn.comment(r.data))}else e(wn.comment(n.comments[0]))}))},li=(e,t,n)=>{const r=we(),o=(r,o,s)=>{r===e&&o===t&&n(s)};if("message"===e){return Ze(r,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await Yn(e);t.reactions[0]&&(Kt(t),Kt({reactors:t.reactions}),o("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return Ze(r,"post.addReaction","post.addReaction",(e=>{const{reactor:t}=e,n=zt(e,["reactor"]);Kt(n),Kt({reactions:[t]}),o("post",e.posts[0].postId,t)}))}if("story"===e){return Ze(r,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=zt(e,["reactions"]);Kt(n),Kt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&o("story",e.stories[0].storyId,e.reactions[0])}))}return Ze(r,"comment.addReaction","comment.addReaction",(e=>{const{reactor:t}=e,n=zt(e,["reactor"]);Kt(n),Kt({reactions:[t]}),o("comment",e.comments[0].commentId,t)}))},di=(e,t,n)=>{const r=we(),o=(r,o,s)=>{r===e&&o===t&&n(s)};if("message"===e){return Ze(r,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await Yn(e);t.reactions[0]&&(Kt(t),o("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return Ze(r,"post.removeReaction","post.removeReaction",(e=>{const{reactor:t}=e,n=zt(e,["reactor"]);Kt(n),Kt({reactions:[t]}),o("post",e.posts[0].postId,t)}))}if("story"===e){return Ze(r,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=zt(e,["reactions"]);Kt(n),Kt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&o("story",e.stories[0].storyId,e.reactions[0])}))}return Ze(r,"comment.removeReaction","comment.removeReaction",(e=>{const{reactor:t}=e,n=zt(e,["reactor"]);Kt(n),Kt({reactions:[t]}),o("comment",e.comments[0].commentId,t)}))},ui=async e=>{we().log("reaction/queryReactor",e);const t=await(async e=>{const t=we();t.log("reaction/queryReactions",e);const n=null!=e?e:{},{page:r={limit:10}}=n,o=zt(n,["page"]),{data:s}=await t.http.get("/api/v3/reactions",{params:Object.assign(Object.assign({},o),{referenceVersion:5,options:{token:Y(r,"afterbeforeraw")}})}),{paging:a}=s,i=zt(s,["paging"]),{reactions:c}=i;Kt(Object.assign(Object.assign({},i),{reactions:c})),Kt(Object.assign(Object.assign({},i),{reactors:c[0].reactors}));const l=X(a.next);return{data:c,prevPage:X(a.previous),nextPage:l}})(e),{data:n}=t,r=zt(t,["data"]);return Object.assign(Object.assign({},r),{data:n[0].reactors})};var hi=Object.freeze({__proto__:null,addReaction:ja,removeReaction:xa,onReactionAdded:(e,t,n)=>{const r=r=>{de(e)(r)===t&&n(r)};if("message"===e){const e=we(),t=async e=>{var t;const n=await Yn(e),o=Se(["message","get",n.messages[0].messageId]),s=(null===(t=null==o?void 0:o.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Kt(n),s&&r(n.messages[0])};return Ze(e,"reaction/onReactionAdded","message.updated",t)}return"post"===e?Za(r):ii(r)},onReactionRemoved:(e,t,n)=>{const r=r=>{de(e)(r)===t&&n(r)};if("message"===e){const e=we(),t=async e=>{var t;const n=await Yn(e),o=Se(["message","get",n.messages[0].messageId]),s=(null===(t=null==o?void 0:o.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Kt(n),s&&r(n.messages[0])};return Ze(e,"reaction/onReactionRemoved","message.updated",t)}return"post"===e?Xa(r):ci(r)},onReactorAdded:li,onReactorRemoved:di,getReactions:(e,t,n)=>{const{log:r,cache:o}=we();o||console.log("For using Live Collection feature you need to enable Cache!");const s=Date.now();r(`liveReactions(tmpid: ${s}) > listen`);const{limit:a}=e,i=zt(e,["limit"]),c=null!=a?a:j,{policy:l=x}=null!=n?n:{},d=[],u=["reaction","collection",{referenceId:e.referenceId,referenceType:e.referenceType}],h=e=>{var n,r;const o=null!==(n=e.data.map((e=>Se(["reactor","get",e]))).filter(Boolean).map((({data:e})=>wn.reactor(e))))&&void 0!==n?n:[];t({onNextPage:f,data:o,hasNextPage:!!(null===(r=e.params)||void 0===r?void 0:r.page),loading:e.loading,error:e.error})},p=e=>t=>{var n;const r=null===(n=Se(u))||void 0===n?void 0:n.data;r&&("onAdded"===e?r.data=[...new Set([t.reactionId,...r.data])]:"onRemoved"===e&&(r.data=r.data.filter((e=>e!==t.reactionId))),_e(u,r),h(r))},f=(e=!1)=>{var t,n,r,o;const s=null===(t=Se(u))||void 0===t?void 0:t.data,a=null!==(n=null==s?void 0:s.data)&&void 0!==n?n:[];if(!e&&a.length>0&&!(null===(r=null==s?void 0:s.params)||void 0===r?void 0:r.page))return;const d=se(ui,Object.assign(Object.assign({},i),{page:null!==(o=e||null==s?void 0:s.params.page)&&void 0!==o?o:{limit:c}}));ie(d,(({data:e,error:t,loading:n,nextPage:r})=>{const o={loading:n,error:t,params:{page:r},data:a};e&&(o.data=[...new Set([...a,...e.map(de("reactor"))])]),_e(u,o),h(o)}),ae(l))};return d.push(li(i.referenceType,i.referenceId,p("onAdded")),di(i.referenceType,i.referenceId,p("onRemoved"))),f(!0),()=>{r(`liveReactions(tmpid: ${s}) > dispose`),d.forEach((e=>e()))}}});function pi(e){const{comments:t}=e;return Object.assign(Object.assign({},e),{comments:t.map((e=>e.hasOwnProperty("myReactions")?e:Object.assign({myReactions:[]},e)))})}const fi=async e=>{const t=we();let n;t.log("channel/getChannel",e),lr("channel",e);try{const{data:r}=await t.http.get(`/api/v3/channels/${encodeURIComponent(e)}`);n=await Bn(r),t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&Ln(r)}catch(t){throw V(null==t?void 0:t.code)&&$t("channel",e),t}const r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const{channels:o}=n;return{data:o.find((t=>t.channelId===e)),cachedAt:r}};fi.locally=e=>{var t;const n=we();if(n.log("channel/getChannel.locally",e),!n.cache)return;const r=null===(t=Ie(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.channelPublicId===e));return r&&0!==(null==r?void 0:r.length)?{data:r[0].data,cachedAt:r[0].cachedAt}:void 0};const gi=(e,t,n)=>r=>e((e=>{var o,s;if(!e)return e;const a=we(),{objectSyncMap:i}=a,c=ue(e[t])?e[t]:null!==(o=i.get(e[t]))&&void 0!==o?o:e[t],l=null===(s=Se([n,"get",`${c}`]))||void 0===s?void 0:s.data;return l?r(l):void 0})),mi=e=>{const t=we(),n=[Ze(t,"onMessageUpdated","message.updated",(async t=>{const n=await Yn(t);Kt(n),e(n.messages[0])})),Ze(t,"onMessageUpdated","local.message.updated",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},yi=e=>{const t=we(),n=[Ze(t,"message/onMessageDeleted","message.deleted",(async t=>{const n=await Yn(t);Kt(n),e(n.messages[0])})),Ze(t,"message/onMessageDeleted","local.message.deleted",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},vi=e=>{const t=we(),n=[Ze(t,"onSubChannelUpdated","message-feed.updated",(async t=>{const n=await nr(t);Kt(n),e(n.messageFeeds[0])})),Ze(t,"onSubChannelUpdated","local.message-feed.updated",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}};function bi(e,t){_e(["channel","get",e.channelId],Object.assign(On(e),t))}const wi=e=>{const t=we();return Ze(t,"channelMarker/onChannelMarkerUpdated","local.channelMarker.updated",(t=>{e(t.userEntityMarkers[0])}))},Ci=async(e,t=!1)=>{const n=we(),r=await dr(e);await n.http.delete(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{params:{permanent:t}});const o=Object.assign(Object.assign({},r.data),{isDeleted:!0,updatedAt:pe(r.data.updatedAt)});return t?setTimeout((()=>{$t("subChannel",e)}),0):Oe(["subChannel","get",e],o),Xe("local.message-feed.deleted",{messageFeeds:[o]}),o},Ii=e=>Ze(we(),"onSubChannelFetched","local.message-feed.fetched",(t=>e(t.messageFeeds[0]))),Si=async e=>{const t=we();t.log("message/getMessages",e);const{data:n}=await t.http.get("/api/v5/messages/list",{params:{messageIds:e.map(encodeURIComponent)}}),r=await Yn(n),o=t.cache&&Date.now();t.cache&&Kt(r,{cachedAt:o});const{messages:s}=r;return Xe("local.message.fetched",{messages:s}),{data:s.map((e=>wn.message(e))),cachedAt:o}};Si.locally=e=>{var t;const n=we();if(n.log("message/getMessages.locally",e),!n.cache)return;const r=e.map((e=>Se(["message","get",e]))).filter(Boolean),o=r.map((({data:e})=>e)),s=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:o,cachedAt:s.cachedAt}};const _i=()=>`LOCAL_${xt()}`;let ki;const Oi=async(e,t)=>{const n=we();n.log("message/updateMessage",t),console.warn("MessageRepository.updateMessage will be replaced with MessageRepository.editMessage");const{data:r}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,Zn(t)),o=await Yn(r),s=n.cache&&Date.now();n.cache&&Kt(o,{cachedAt:s});const{messages:a}=o;return Xe("local.message.updated",{messages:a}),{data:wn.message(a.find((t=>t.messageId===e))),cachedAt:s}};Oi.optimistically=(e,t)=>{const n=we();if(n.log("message/updateMessage.optimistically",t),!n.cache)return;const r=Se(["message","get",e]);if(!r)return;const o=Object.assign(Object.assign(Object.assign({},r.data),t),{updatedAt:(new Date).toISOString()});return Oe(["message","get",e],o,{cachedAt:-1}),Xe("local.message.updated",{messages:[o]}),{data:wn.message(o),cachedAt:-1}};const Ti=async(e,t)=>{const n=we();n.log("message/editMessage",t);const{data:r}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,Zn(t)),o=await Yn(r),s=n.cache&&Date.now();n.cache&&Kt(o,{cachedAt:s});const{messages:a}=o;return Xe("local.message.updated",{messages:a}),{data:wn.message(a.find((t=>t.messageId===e))),cachedAt:s}};Ti.optimistically=(e,t)=>{const n=we();if(n.log("message/editMessage.optimistically",t),!n.cache)return;const r=Se(["message","get",e]);if(!r)return;const o=Object.assign(Object.assign(Object.assign({},r.data),t),{updatedAt:(new Date).toISOString()});return Oe(["message","get",e],o,{cachedAt:-1}),Xe("local.message.updated",{messages:[o]}),{data:wn.message(o),cachedAt:-1}};const Ai=async e=>{const t=we();t.log("message/deleteMessage",e);const{data:n}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`),r=await Yn(n);return Xe("local.message.deleted",{messages:[r.messages[0]]}),wn.message(r.messages[0])};Ai.optimistically=e=>{we().log("message/deleteMessage.optimistically",e);const t=Se(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return Oe(["message","get",e],n,{cachedAt:-1}),Xe("local.message.deleted",{messages:[n]}),{data:wn.message(n),cachedAt:-1}};const Ei=async e=>{const t=we();t.log("message/softDeleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const n=await ka(e);return Xe("local.message.deleted",{messages:[n.data]}),wn.message(n.data)};Ei.optimistically=e=>{we().log("message/softDeleteMessage.optimistically",e);const t=Se(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return Oe(["message","get",e],n,{cachedAt:-1}),Xe("local.message.deleted",{messages:[n]}),{data:wn.message(n),cachedAt:-1}};const Mi=async e=>{const t=we();t.log("user/getReadUsers",e);const{page:n,messageId:r}=e,o=zt(e,["page","messageId"]),{data:s}=await t.http.get(`/api/v1/markers/messages/${r}/read-users`,{params:Object.assign(Object.assign({},o),{options:{token:Y(n,"afterbeforeraw")}})}),{paging:a,publicUserIds:i,userFeedMarkers:c}=s,l=zt(s,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Kt(Object.assign(Object.assign({},l),{userFeedMarkers:Jt(c)}),{cachedAt:d});const e=["read-user","query",Object.assign(Object.assign({messageId:r},o),{options:Object.assign({},n)})];_e(e,{users:i,paging:a})}let u=[];i.length>0&&({data:u}=await aa(i));return{data:u,cachedAt:d,prevPage:Z(a.previous),nextPage:Z(a.next)}};Mi.locally=e=>{var t;const n=we();if(n.log("user/getReadUsers.locally",e),!n.cache)return;const{page:r}=e,o=zt(e,["page"]),s=["read-user","query",Object.assign(Object.assign({},o),{options:Object.assign({},r)})],{data:a,cachedAt:i}=null!==(t=Se(s))&&void 0!==t?t:{},c=null==a?void 0:a.users.map((e=>{var t;return null===(t=Se(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:i,prevPage:Z(null==a?void 0:a.paging.previous),nextPage:Z(null==a?void 0:a.paging.next)}};const Pi=async e=>{const t=we();t.log("user/getDeliveredUsers",e);const{page:n,messageId:r}=e,o=zt(e,["page","messageId"]),{data:s}=await t.http.get(`/api/v1/markers/messages/${r}/delivered-users`,{params:Object.assign(Object.assign({},o),{options:{token:Y(n,"afterbeforeraw")}})}),{paging:a,publicUserIds:i,userFeedMarkers:c}=s,l=zt(s,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Kt(Object.assign(Object.assign({},l),{userFeedMarkers:Jt(c)}),{cachedAt:d});const e=["delivered-user","query",Object.assign(Object.assign({messageId:r},o),{options:Object.assign({},n)})];_e(e,{users:i,paging:a})}let u=[];i.length>0&&({data:u}=await aa(i));return{data:u,cachedAt:d,prevPage:Z(a.previous),nextPage:Z(a.next)}};Pi.locally=e=>{var t;const n=we();if(n.log("user/getDeliveredUsers.locally",e),!n.cache)return;const{page:r}=e,o=zt(e,["page"]),s=["delivered-user","query",Object.assign(Object.assign({},o),{options:Object.assign({},r)})],{data:a,cachedAt:i}=null!==(t=Se(s))&&void 0!==t?t:{},c=null==a?void 0:a.users.map((e=>{var t;return null===(t=Se(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:i,prevPage:Z(null==a?void 0:a.paging.previous),nextPage:Z(null==a?void 0:a.paging.next)}};const Ri=e=>{const t=we();return Ze(t,"onMessageFlagged","message.flagged",(async t=>{const n=await Yn(t);Kt(n),e(n.messages[0])}))},Ui=e=>{const t=we();return Ze(t,"onMessageUnflagged","message.unflagged",(async t=>{const n=await Yn(t);Kt(n),e(n.messages[0])}))},ji=e=>{const t=we();return Ze(t,"onMessageFlagCleared","message.flagCleared",(async t=>{const n=await Yn(t);Kt(n),e(n.messages[0])}))},xi=e=>{const t=we();return Ze(t,"onMessageReactionAdded","message.reactionAdded",(async t=>{const n=await Yn(t,"message.reactionAdded");Kt(n),e(n.messages[0])}))},Di=e=>{const t=we();return Ze(t,"onMessageReactionRemoved","message.reactionRemoved",(async t=>{const n=await Yn(t,"message.reactionRemoved");Kt(n),e(n.messages[0])}))},Ni=e=>{const t=we();return Ze(t,"message/onMessageFetched","local.message.fetched",(t=>{Kt(t),e(t.messages[0])}))};class Bi extends Is{constructor(e,t,n,r,o){super(e,t),this.notifyChange=n,this.preparePayload=r,this.paginationController=o}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:To(e.messages),query:this.query});else{const n=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,s=null!==(o=null==n?void 0:n.data)&&void 0!==o?o:[];_e(this.cacheKey,Object.assign(Object.assign({},n),{data:"next"===t?[...new Set([...s,...To(e.messages)])]:[...new Set([...To(e.messages),...s])]}))}}reactor(e){return t=>{var n,r,o,s,a;if("onCreate"===e){const e=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data,{referenceId:i}=t;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===(r=this.query.excludingTags)||void 0===r?void 0:r.some((e=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.includes(e)}))))return;if(this.query.excludeTags&&(null===(o=this.query.excludeTags)||void 0===o?void 0:o.some((e=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.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===(s=this.query.includingTags)||void 0===s?void 0:s.some((e=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.includes(e)}))))return;if(this.query.tags&&!(null===(a=this.query.tags)||void 0===a?void 0:a.some((e=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.includes(e)}))))return;this.query.sortBy&&"segmentDesc"!==this.query.sortBy||this.paginationController.getPrevToken()||(e.data=[...new Set([null!=i?i:t.messageId,...e.data])]),"segmentAsc"!==this.query.sortBy||this.paginationController.getNextToken()||(e.data=[...new Set([...e.data,null!=i?i:t.messageId])]),_e(this.cacheKey,e)}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class qi extends ws{async getRequest(e,t){const n=Xn(e),{data:r}=await this.http.get("/api/v5/messages",{params:Object.assign(Object.assign({},n),{options:t?{token:t}:Object.assign({},n.options)})});return r}}class Fi extends ks{constructor(e,t){const n=w.default(e),r=["message","collection",n];super(new qi(e),n,r,t),this.query=e,this.queryStreamController=new Bi(this.query,this.cacheKey,this.notifyChange.bind(this),Yn,this.paginationController),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Ao,action:"onCreate"},{fn:Eo,action:"onCreate"},{fn:yi,action:"onDelete"},{fn:mi,action:"onUpdate"},{fn:Ri,action:"onFlagged"},{fn:Ui,action:"onUnflagged"},{fn:ji,action:"onFlagCleared"},{fn:xi,action:"onReactionAdded"},{fn:Di,action:"onReactionRemoved"},{fn:gi(ds,"contentId","message"),action:"onUpdate"},{fn:gi(us,"contentId","message"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var r,o;const s=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const a=this.applyFilter(null!==(o=s.data.map((e=>(e=>{var t,n;const r=we(),{objectSyncMap:o}=r,s=ue(e)?e:null!==(t=o.get(e))&&void 0!==t?t:e;return null===(n=Se(["message","get",s]))||void 0===n?void 0:n.data})(e))).filter(Boolean).map((e=>wn.message(e))))&&void 0!==o?o:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),onPrevPage:()=>this.loadPage({direction:"prev"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),hasPrevPage:!!this.paginationController.getPrevToken(),loading:t,error:n})}applyFilter(e){let t=e;return t=t.filter((e=>!this.query.tags||this.query.tags.find((t=>!!e.tags&&e.tags.includes(t))))),t=t.filter((e=>!this.query.excludeTags||(this.query.excludeTags||[]).find((t=>!e.tags||!e.tags.includes(t))))),this.query.includeDeleted||(t=Ae(t,"isDeleted",!1)),t=t.sort(((e,t)=>"segmentAsc"===this.query.sortBy?e.channelSegment-t.channelSegment:"segmentDesc"===this.query.sortBy?t.channelSegment-e.channelSegment:0)),t}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],query:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}}const Li=async(e,t=!1)=>{const n=we();let r;n.log("message/getMessage",e),t||console.log("getMessage will be deprecated on 15th November 2022, please use liveMessage instead."),lr("message",e);try{const{data:t}=await n.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);r=await Yn(t)}catch(t){throw V(null==t?void 0:t.code)&&$t("message",e),t}const o=n.cache&&Date.now();n.cache&&Kt(r,{cachedAt:o});const{messages:s}=r;return Xe("local.message.fetched",{messages:s}),{data:wn.message(s.find((t=>t.messageId===e))),cachedAt:o}};Li.locally=e=>{const t=we();if(t.log("message/getMessage.locally",e),!t.cache)return;const n=Se(["message","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};var Ki=Object.freeze({__proto__:null,getMessageByIds:Si,createMessage:async e=>{const t=we(),{objectSyncMap:n}=t;t.log("message/createMessage",e);const r=(e=>{var t,n;const r=we(),{objectSyncMap:o}=r;if(!r.cache)return;ki=e.referenceId||_i();const s=Object.assign({messageId:ki,uniqueId:ki},e);r.log("message/createMessage.optimistically",s);const a=Se(["subChannel","get",e.subChannelId]);if(a&&(Oe(["subChannel","get",e.subChannelId],Object.assign(Object.assign({},a.data),{messageCount:a.data.messageCount+1})),a.data.channelId===a.data.subChannelId)){const e=Se(["channel","get",a.data.channelId]);(null==e?void 0:e.data)&&Oe(["channel","get",a.data.channelId],Object.assign(Object.assign({},e.data),{messageCount:(null!==(t=e.data.messageCount)&&void 0!==t?t:0)+1}))}const i=(new Date).toISOString(),c=Object.assign({creatorId:r.userId,creatorPrivateId:Qe()._id,channelSegment:(null!==(n=null==a?void 0:a.data.messageCount)&&void 0!==n?n:0)+1,childrenNumber:0,createdAt:i,updatedAt:i,syncState:"syncing",isDeleted:!1},s);return _e(["message","get",c.messageId],c,{cachedAt:-5}),o.set(c.messageId,void 0),Xe("local.message.created",{messages:[c]}),c})(e),o=e.referenceId||ki||_i();ki=void 0;try{const{data:r}=await t.http.post("/api/v5/messages",Object.assign(Object.assign({},Zn(e)),{referenceId:o}));n.set(o,r.messages[0].messageId),n.set(r.messages[0].messageId,o);const s=await Yn(r),{messages:a}=s,i=t.cache&&Date.now();return t.cache&&Kt(s,{cachedAt:i}),Xe("local.message.created",{messages:[Object.assign(Object.assign({},a[0]),{syncState:"synced"})]}),{data:wn.message(a[0]),cachedAt:i}}catch(e){throw Xe("local.message.created",{messages:[Object.assign(Object.assign({},r),{syncState:"error"})]}),e}},updateMessage:Oi,editMessage:Ti,deleteMessage:Ai,softDeleteMessage:Ei,markAsDelivered:async(e,t)=>{const n=we();n.log("message/markAsDelivered",e,t);const{data:r}=await n.http.put(`/api/v1/markers/message-feeds/${e}/mark-delivering`,{messageId:t}),{userMarkers:o,userEntityMarkers:s,userFeedMarkers:a}=r,i=zt(r,["userMarkers","userEntityMarkers","userFeedMarkers"]),c=n.cache&&Date.now();return n.cache&&Kt(Object.assign({userMarkers:o,userEntityMarkers:Wt(s),userFeedMarkers:Jt(a)},i),{cachedAt:c}),!0},getReadUsers:Mi,getDeliveredUsers:Pi,flagMessage:async e=>{const t=we();t.log("message/flag",e);const{data:n}=await t.http.post(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await Yn(n);Kt(e)}return Xe("message.flagged",n),!!n},unflagMessage:async e=>{const t=we();t.log("message/unflag",e);const{data:n}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await Yn(n);Kt(e)}return Xe("message.unflagged",n),!!n},isMessageFlaggedByMe:async e=>{const t=we();t.log("message/isMessageFlaggedByMe",e);const{data:n}=await t.http.get(`/api/v5/messages/${encodeURIComponent(e)}/flags`);return n.result},onMessageCreatedMqtt:Ao,onMessageCreatedLocal:Eo,onMessageUpdated:mi,onMessageDeleted:yi,onMessageFlagged:Ri,onMessageUnflagged:Ui,onMessageFlagCleared:ji,onMessageReactionAdded:xi,onMessageReactionRemoved:Di,onMessageFetched:Ni,getMessage:(e,t)=>gs(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?wn.message(e.data):n}))}),"messageId",ka,[Ni,mi,yi,Ri,Ui,ji,xi,Di,gi(ds,"contentId","message"),gi(us,"contentId","message")]),getMessages:(e,t,n)=>{const{log:r,cache:o}=we();o||console.log(D);const s=Date.now();r(`getMessages(tmpid: ${s}) > listen`);const a=new Fi(e,t),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>{Te(c)})),()=>{r(`getMessages(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},observeMessage:(e,t,n="cache_then_server")=>{const{log:r}=we(),o=Date.now();r(`observeMessage(tmpid: ${o}) > listen`),console.log("observeMessage will be deprecated on 15th November 2022, please use liveMessage instead.");const s=(n,r)=>{var o,s,a;if((null===(o=n.data)||void 0===o?void 0:o.messageId)===e){if(t instanceof Function)return t(n);"onFetch"!==r&&(null===(s=t.onEvent)||void 0===s||s.call(t,r,n)),null===(a=t[r])||void 0===a||a.call(t,n)}},a=[];return a.push(mi((e=>s({data:wn.message(e),loading:!1,origin:"event"},"onUpdate"))),yi((e=>s({data:wn.message(e),loading:!1,origin:"event"},"onDelete"))),gi(ds,"contentId","message")((e=>s({data:wn.message(e),loading:!1,origin:"event"},"onUpdate"))),gi(us,"contentId","message")((e=>s({data:wn.message(e),loading:!1,origin:"event"},"onUpdate")))),"no_fetch"!==n&&ie(se(Li,e),(e=>e.data&&s(e,"onFetch")),ae(n)),()=>{r(`observeMessages(tmpid: ${o}) > dispose`),a.forEach((e=>e()))}},observeMessages:(e,t)=>{const{log:n}=we(),r=Date.now();n(`observeMessages(tmpid: ${r}) > listen`);const o=[],s=(n,r)=>{var o,s,a;if((null===(o=n.data)||void 0===o?void 0:o.subChannelId)===e){if(t instanceof Function)return t(n);null===(s=t.onEvent)||void 0===s||s.call(t,r,n),null===(a=t[r])||void 0===a||a.call(t,n)}};return o.push(Ao((e=>s({data:wn.message(e),loading:!1,origin:"event"},"onCreate"))),Eo((e=>s({data:wn.message(e),loading:!1,origin:"event"},"onCreate"))),mi((e=>s({data:wn.message(e),loading:!1,origin:"event"},"onUpdate"))),yi((e=>s({data:wn.message(e),loading:!1,origin:"event"},"onDelete"))),gi(ds,"contentId","message")((e=>s({data:wn.message(e),loading:!1,origin:"event"},"onCreate"))),gi(us,"contentId","message")((e=>s({data:wn.message(e),loading:!1,origin:"event"},"onCreate")))),()=>{n(`observeMessages(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},convertFromRaw:Jn,prepareMessagePayload:Yn,convertParams:Zn,convertQueryParams:Xn,getMessageIdentifierIds:To});const $i=e=>{const t=we();return Ze(t,"subChannelMarker/onSubChannelUnreadUpdatedLocal","local.subChannelUnread.updated",(t=>{e(t)}))};class zi extends ws{async getRequest(e,t){var n;const{limit:r=j}=e,o=null!==(n=function(e){var{excludeDefaultSubChannel:t}=e,n=zt(e,["excludeDefaultSubChannel"]);const r=Object.assign({},n);return void 0!==t&&(r.excludeDefaultMessageFeed=t),r}(zt(e,["limit"])))&&void 0!==n?n:{},{channelId:s,includeDeleted:a}=o,i=zt(o,["channelId","includeDeleted"]),c=t?{token:t}:{limit:r},{data:l}=await this.http.get(`/api/v5/message-feeds/channel/${s}`,{params:Object.assign(Object.assign({},i),{isDeleted:zn(a),options:c})});return l}}class Qi extends Is{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:e.messageFeeds.map((({messageFeedId:e})=>e))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(o=null==t?void 0:t.data)&&void 0!==o?o:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.messageFeeds.map((({messageFeedId:e})=>e))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(!Array.isArray(t)){if(this.query.channelId!==t.channelId)return;"onCreate"===e&&(r.data=[...new Set([t.subChannelId,...r.data])]),_e(this.cacheKey,r)}this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Vi extends ks{constructor(e,t){const n=w.default(e),r=["subChannel","collection",n];super(new zi(e),n,r,t),this.query=e,this.queryStreamController=new Qi(this.query,this.cacheKey,this.notifyChange.bind(this),nr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[]})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Ii,action:"onCreate"},{fn:Mo,action:"onCreate"},{fn:Po,action:"onDelete"},{fn:e=>vi((async t=>{var n;const r=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;if(!r||!r.data.includes(t.subChannelId))return;const o=we();if("no-message-preview"!==await o.getMessagePreviewSetting(!1)){const e=Sn(t.subChannelId);(null==e?void 0:e.subChannelId)===t.subChannelId&&_e(["messagePreviewSubChannel","get",t.subChannelId],Object.assign(Object.assign({},e),{subChannelName:t.displayName,subChannelUpdatedAt:t.updatedAt}))}e(t)})),action:"onUpdate"},{fn:e=>Ao((async t=>{var n,r;const o=Se(["subChannel","get",t.subChannelId]);if(!o)return;const s=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;if(!s||!s.data.includes(t.subChannelId))return;await(async e=>{const t=we();"no-message-preview"!==await t.getMessagePreviewSetting(!1)&&An(e)})(t);const a=null===(r=Se(["subChannel","get",t.subChannelId]))||void 0===r?void 0:r.data;a&&(Tn(t.subChannelId,a,{lastActivity:t.createdAt,messagePreviewId:t.messageId}),e(Object.assign(Object.assign({},o.data),{messagePreviewId:t.messageId,subChannelId:t.subChannelId,lastActivity:t.createdAt})))})),action:"onUpdate"},{fn:e=>Eo((async t=>{var n,r;const o=Se(["subChannel","get",t.subChannelId]);if(!o)return;const s=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;if(!s||!s.data.includes(t.subChannelId))return;const a=we();if("no-message-preview"===await a.getMessagePreviewSetting(!1))return;An(t);const i=null===(r=Se(["subChannel","get",t.subChannelId]))||void 0===r?void 0:r.data;i&&(Tn(t.subChannelId,i,{lastActivity:t.createdAt,messagePreviewId:t.messageId}),e(Object.assign(Object.assign({},o.data),{messagePreviewId:t.messageId,subChannelId:t.subChannelId,lastActivity:t.createdAt})))})),action:"onUpdate"},{fn:e=>is((t=>{var n;const r=null!==(n=t.map((({feedId:e})=>Se(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];0!==r.length&&e(r)})),action:"onUpdate"},{fn:gi(as,"feedId","subChannel"),action:"onUpdate"},{fn:gi((e=>mi((async t=>{var n;const r=we();if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;const o=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;o&&o.data.includes(t.subChannelId)&&(En(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:gi((e=>yi((async t=>{var n;const r=we(),o=await r.getMessagePreviewSetting(!1);if("no-message-preview"===o)return;const s=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;s&&s.data.includes(t.subChannelId)&&("message-preview-not-include-deleted"===o?await dr(t.subChannelId):await En(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:gi($i,"subChannelId","subChannel"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var r,o;const s=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const a=this.applyFilter(null!==(o=s.data.map((e=>Se(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(_n))&&void 0!==o?o:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.includeDeleted||(t=Ae(e,"isDeleted",!1)),t.sort($e),t}}const Hi={},Wi=async e=>{const t=await(async e=>{const t=dr.locally(e);if(t)return t.data.channelId;const{data:n}=await dr(e);return n.channelId})(e),n=it({channelId:t,subChannelId:e});Hi[e]=pt(n)};var Ji=Object.freeze({__proto__:null,getSubChannelByIds:vr,createSubChannel:async e=>{const t=we();t.log("user/createSubChannel",e);const n=await t.http.post("/api/v5/message-feeds",{channelId:e.channelId,name:e.displayName}),r=await nr(n.data),o=t.cache&&Date.now();return t.cache&&Kt(r,{cachedAt:o}),Xe("message-feed.created",n.data),{data:r.messageFeeds[0],cachedAt:o}},updateSubChannel:async(e,t)=>{const n=we();n.log("channel/updateSubChannel",e,t);const r=await n.http.put(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{name:t.displayName}),o=await nr(r.data),s=n.cache&&Date.now();return n.cache&&Kt(o,{cachedAt:s}),Xe("message-feed.updated",r.data),{data:o.messageFeeds[0],cachedAt:s}},deleteSubChannel:Ci,hardDeleteSubChannel:async e=>{we().log("channel/hardDeleteSubChannel",e);return await Ci(e,!0)},softDeleteSubChannel:async e=>{we().log("channel/softDeleteSubChannel",e);return await Ci(e,!1)},onSubChannelCreated:Mo,onSubChannelUpdated:vi,onSubChannelDeleted:Po,getSubChannel:(e,t)=>{const n=we();let r;return gs(e,(e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:_n(e.data)}),o=zt(n,["origin"]);return ln(r,o)?void 0:(r=o,t(n))}),"subChannelId",dr,[Ii,t=>vi((async r=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(Mn(r),r.subChannelId===e&&t(r))})),Po,gi(as,"feedId","subChannel"),t=>is((n=>{var r;if(!n.find((({feedId:t})=>t===e)))return;const o=null===(r=Se(["subChannel","get",e]))||void 0===r?void 0:r.data;o&&t(o)})),gi((t=>Ao((async r=>{await(async t=>{var r;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await An(t),t.subChannelId!==e)return;const o=null===(r=Se(["subChannel","get",e]))||void 0===r?void 0:r.data;o&&Tn(t.subChannelId,o,{messagePreviewId:t.messageId})})(r),t(r)}))),"subChannelId","subChannel"),gi((t=>Eo((async r=>{await(async t=>{var r;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await An(t),t.subChannelId!==e)return;const o=null===(r=Se(["subChannel","get",e]))||void 0===r?void 0:r.data;o&&Tn(t.subChannelId,o,{messagePreviewId:t.messageId})})(r),t(r)}))),"subChannelId","subChannel"),gi((t=>mi((async r=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&r.subChannelId===e&&(En(r),t(r))}))),"subChannelId","subChannel"),gi((t=>yi((async r=>{const o=await n.getMessagePreviewSetting(!1);"no-message-preview"!==o&&r.subChannelId===e&&("message-preview-include-deleted"===o&&await En(r),"message-preview-not-include-deleted"===o&&await dr(r.subChannelId),t(r))}))),"subChannelId","subChannel"),gi($i,"subChannelId","subChannel")],{forceDispatch:!0})},getSubChannels:(e,t,n)=>{const{log:r,cache:o}=we(),s=Date.now();r(`getSubChannels(tmpid: ${s}) > listen`),o||console.log(D);const a=new Vi(e,t),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>{Te(c)})),()=>{r(`getSubChannels(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},markReadEngineOnLoginHandler:mr,startReading:async e=>{pr[e]=!0,0===hr.length&&(hr.length>0||hr.push(cr((()=>{fr()}))),yr(e));try{return await(async e=>{const t=we();t.log("subChannel/startReadingAPI",e);const{data:n}=await t.http.post(`/api/v1/markers/message-feeds/${e}/start-reading`),{userEntityMarkers:r,userFeedMarkers:o,feedMarkers:s,userMarkers:a}=n,i=Wt(r),c=Jt(o),l=t.cache&&Date.now();return t.cache&&Kt({userEntityMarkers:i,userFeedMarkers:c,feedMarkers:s,userMarkers:a},{cachedAt:l}),Xe("local.feedMarker.fetched",{feedMarkers:s}),Xe("local.channelMarker.fetched",{userEntityMarkers:i}),Xe("local.subChannelMarker.fetched",{userFeedMarkers:c}),Xe("local.userMarker.fetched",{userMarkers:a}),!0})(e)}catch(t){return pr[e]=!1,!1}},stopReading:e=>(pr[e]=!1,hr.forEach((e=>e())),hr=[],(async e=>{const t=we();t.log("channel/stopReadingAPI",e);const{data:n}=await t.http.post(`/api/v1/markers/message-feeds/${e}/stop-reading`),{userEntityMarkers:r,userFeedMarkers:o,feedMarkers:s,userMarkers:a}=n,i=Wt(r),c=Jt(o),l=t.cache&&Date.now();return t.cache&&Kt({userEntityMarkers:i,userFeedMarkers:c,feedMarkers:s,userMarkers:a},{cachedAt:l}),Xe("local.feedMarker.fetched",{feedMarkers:s}),Xe("local.channelMarker.fetched",{userEntityMarkers:i}),Xe("local.subChannelMarker.fetched",{userFeedMarkers:c}),Xe("local.userMarker.fetched",{userMarkers:a}),!0})(e)),startMessageReceiptSync:async e=>(await Wi(e),!0),stopMessageReceiptSync:e=>(Hi[e]&&Hi[e](),!0)});const Gi=e=>{const t=we();return Ze(t,"channelMarker/onChannelUnreadUpdatedLocal","local.channelUnread.updated",(t=>{e(t)}))};class Yi extends ws{async getRequest(e,t){const{limit:n=j,displayName:r,membership:o}=e,s=zt(e,["limit","displayName","membership"]),a=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/channels",{params:Object.assign(Object.assign({},s),{keyword:r,filter:o,options:a})});return i}}class Zi extends _s{async getRequest(e){const{data:t}=await this.http.get("/api/v3/channels/list",{params:Object.assign({},e)});return t}}class Xi extends Is{constructor(e,t,n,r,o){super(e,t),this.notifyChange=n,this.preparePayload=r,this.paginationController=o}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:e.channels.map(de("channel"))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(o=null==t?void 0:t.data)&&void 0!==o?o:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channels.map(de("channel"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(this.paginationController instanceof Zi)return this.notifyChange({origin:"event",loading:!1});["onCreate","onJoin","onResolve"].includes(e)&&(Array.isArray(t)?r.data=[...new Set([...t.map(de("channel")),...r.data])]:r.data=[...new Set([t.channelInternalId,...r.data])]),_e(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const ec=(e,t)=>{const n=we();if(n.isUnreadCountEnabled&&n.getMarkerSyncConsistentMode()){Kr().resolve(e.channelId,"userMessageFeedMarker")}else t(e)},tc=e=>{const t=we();return Ze(t,"onChannelResolved","local.channel.resolved",(async t=>{e(t)}))};class nc extends ks{constructor(e,t){const n=w.default(e),r=["channel","collection",n],o=nc.getPaginationController(e);super(o,n,r,t),this.query=e,this.queryStreamController=new Xi(this.query,this.cacheKey,this.notifyChange.bind(this),(async e=>{try{const t=we();t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await Ln(e)}catch(e){console.error("Error while preparing unread count info",e)}return Bn(e)}),o),this.paginationController=o,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE(this.getSubscriptions())}notifyChange({origin:e,loading:t,error:n}){var r,o;const s=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;let a=null!==(o=s.data.map((e=>Se(["channel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(Cn).map(wn.channel))&&void 0!==o?o:[];this.paginationController instanceof Yi&&(a=this.applyFilter(a)),(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:this.paginationController instanceof Yi?()=>this.loadPage({direction:"next"}):void 0,data:a,hasNextPage:this.paginationController instanceof Yi&&!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=we();let n=e;switch(n=Ae(n,"isDeleted",this.query.isDeleted),n=Ee(n,"displayName",this.query.displayName),this.query.types&&(n=n.filter((e=>{var t;return null===(t=this.query.types)||void 0===t?void 0:t.includes(e.type)}))),this.query.tags&&(n=n.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&&(n=n.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&&(n=Pe(n,this.query.membership,t)),this.query.sortBy){case"firstCreated":n=n.sort(Be);break;case"lastCreated":n=n.sort(Fe);break;case"displayName":n=n.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(De);break;default:n=n.sort($e)}return n}shouldAbort(e){var t,n;const r=null===(t=Se(this.cacheKey))||void 0===t?void 0:t.data;if(!r)return!0;return!(null===(n=null==r?void 0:r.data)||void 0===n?void 0:n.find((t=>t===e)))}static getMessagePreviewSetting(){return we().getMessagePreviewSetting(!1)}static getPaginationController(e){return e.channelIds&&e.channelIds.length>0?new Zi(e):new Yi(e)}getSubscriptions(){const e=[{fn:gi((e=>Ao((t=>{var n;const r=null===(n=Se(["channel","get",t.channelId]))||void 0===n?void 0:n.data;if(r)bi(r,{lastActivity:t.createdAt}),e(t);else{Kr().resolve(t.channelId,"channel")}}))),"messageId","channel"),action:"onUpdate"},{fn:gi((e=>Eo((t=>{var n;const r=null===(n=Se(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(bi(r,{lastActivity:t.createdAt}),e(t))}))),"messageId","channel"),action:"onUpdate"},{fn:Ur,action:"onDelete"},{fn:eo,action:"onUpdate"},{fn:lo,action:"onMute"},{fn:e=>ro((t=>{ec(t,e)})),action:"onJoin"},{fn:e=>ao(((t,n)=>{var r,o;const{userId:s}=we();if("member"===this.query.membership&&s===n.userId){const e=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;_e(this.cacheKey,Object.assign(Object.assign({},e),{data:null!==(o=null==e?void 0:e.data.filter((e=>e!==t.channelId)))&&void 0!==o?o:[]}))}return e(t)})),action:"onLeft"},{fn:po,action:"onMemberAdded"},{fn:mo,action:"onMemberRemoved"},{fn:gi(ss,"entityId","channel"),action:"onUpdate"},{fn:gi(wi,"entityId","channel"),action:"onUpdate"},{fn:gi((e=>Ao((async t=>{var n;if("no-message-preview"===await nc.getMessagePreviewSetting())return;if(An(t),this.shouldAbort(t.channelId))return;const r=null===(n=Se(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(bi(r,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:gi((e=>Eo((async t=>{var n;if("no-message-preview"===await nc.getMessagePreviewSetting())return;if(An(t),this.shouldAbort(t.channelId))return;const r=null===(n=Se(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(bi(r,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:gi((e=>mi((async t=>{"no-message-preview"!==await nc.getMessagePreviewSetting()&&(En(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:gi((e=>yi((async t=>{const n=await nc.getMessagePreviewSetting();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await En(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&await fi(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:gi((e=>Po((async t=>{var n;const r=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;r.data.find((e=>{const n=Gt(e);return(null==n?void 0:n.subChannelId)===t.subChannelId}))&&(await fi(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:gi((e=>vi((async t=>{var n;if("no-message-preview"===await nc.getMessagePreviewSetting())return;(null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data)&&(await Mn(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:gi(Mo,"channelId","channel"),action:"onUpdate"},{fn:tc,action:"onResolve"},{fn:e=>(e=>{const t=we();return Ze(t,"userMessageFeedMarker/onUserMessageFeedMarkerResolved","local.userMessageFeedMarkers.resolved",(t=>{e(t)}))})((async t=>{if(t.feedMarkers){const n=[...new Set(t.feedMarkers.map((e=>e.entityId)))].map((e=>{var t;return null===(t=Se(["channel","get",e]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"onResolve"},{fn:gi(Gi,"channelId","channel"),action:"onUpdate"}];return this.paginationController instanceof ws?[...e,{fn:e=>Yr((t=>{ec(t,e)})),action:"onCreate"}]:e}}class rc extends ws{async getRequest(e,t){const{limit:n=j,includeDeleted:r}=e,o=zt(e,["limit","includeDeleted"]),s=t?{token:t}:{limit:n},a=!1!==r&&void 0,{data:i}=await this.http.get(`/api/v4/channels/${encodeURIComponent(o.channelId)}/users`,{params:Object.assign(Object.assign({},o),{options:s,isDeleted:a})});return i}}class oc extends Is{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:e.channelUsers.map((({channelId:e,userId:t})=>de("channelUsers")({channelId:e,userId:t})))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(o=null==t?void 0:t.data)&&void 0!==o?o:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channelUsers.map((({channelId:e,userId:t})=>de("channelUsers")({channelId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;if(this.query.channelId!==t.channelId)return;const r=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;const o=de("channelUsers")({channelId:this.query.channelId,userId:t.userId});"none"===t.membership?r.data=r.data.filter((e=>e!==o)):r.data.includes(o)||(r.data=[o,...r.data]),_e(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class sc extends ks{constructor(e,t){const n=w.default(e),r=["channelUsers","collection",n];super(new rc(e),n,r,t),this.query=e,this.queryStreamController=new oc(this.query,this.cacheKey,this.notifyChange.bind(this),Bn),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:ro,action:"onJoin"},{fn:ao,action:"onLeft"},{fn:po,action:"onMemberAdded"},{fn:mo,action:"onMemberRemoved"},{fn:Dr,action:"onChannelMemberBanned"},{fn:bo,action:"onChannelMemberUnbanned"},{fn:Io,action:"onChannelMemberRoleAdded"},{fn:ko,action:"onChannelMemberRoleRemoved"},{fn:(e=this.query.channelId,t=>{const n=we();return Ze(n,"user.deleted","user.deleted",(n=>{var r,o;const s=Nr(n);if(0===s.users.length)return;const a=s.users[0];Kt(s);const i=de("channelUsers")({channelId:e,userId:a.userId}),c=null===(r=Se(["channelUsers","get",i]))||void 0===r?void 0:r.data;Oe(["channelUsers","get",i],Object.assign(Object.assign({},c),{user:a}));const l=null===(o=Se(["channel","get",e]))||void 0===o?void 0:o.data;l&&t(l,c)}))}),action:"onChannelMemberChanged"}]);var e}notifyChange({origin:e,loading:t,error:n}){var r,o;const s=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const a=this.applyFilter(null!==(o=s.data.map((e=>Se(["channelUsers","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==o?o:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=Me(e,"roles",this.query.roles);this.query.memberships&&(t=t.filter((e=>{var t,n;return!(!(null===(t=this.query.memberships)||void 0===t?void 0:t.includes("muted"))||!e.isMuted)||"none"!==e.membership&&(null===(n=this.query.memberships)||void 0===n?void 0:n.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)),!1===this.query.includeDeleted&&(t=t.filter((e=>{var t;return!0!==(null===(t=e.user)||void 0===t?void 0:t.isDeleted)})));const n=this.query.sortBy?this.query.sortBy:"lastCreated";return t=t.sort("lastCreated"===n?Fe:Be),t}}const ac=(e,t,n)=>{const{log:r,cache:o}=we();o||console.log(D);const s=Date.now();r(`getMembers(tmpid: ${s}) > listen`);const a=new sc(e,t),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>{Te(c)})),()=>{r(`getMembers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}};var ic=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=we();n.log("channel/addMembers",e,t);const{data:r}=await n.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users`,{channelId:e,userIds:t});t.forEach((e=>Xe("channel.membersAdded",Object.assign(Object.assign({},r),{channelUsers:r.channelUsers.filter((t=>t.userId===e))}))));const o=await Bn(r);n.cache&&Kt(o);const{channelUsers:s}=o;return!!s.find((t=>t.channelId===e&&"member"===t.membership))},removeMembers:async(e,t)=>{const n=we();n.log("channel/removeMembers",e,t);const{data:r}=await n.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users`,{data:{channelId:e,userIds:t}});t.forEach((e=>Xe("channel.membersRemoved",Object.assign(Object.assign({},r),{channelUsers:r.channelUsers.filter((t=>t.userId===e))}))));const o=await Bn(r);n.cache&&Kt(o);const{channelUsers:s}=o;return!!s.find((t=>t.channelId===e&&"member"!==t.membership))},applyFilter:(e,t)=>{let n=Me(e,"roles",t.roles);t.memberships&&(n=n.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."),n=xe(n,t.search));const r=t.sortBy?t.sortBy:"lastCreated";return n=n.sort("lastCreated"===r?Fe:Be),n},getMembers:ac,searchMembers:(e,t,n)=>ac(e,t)});var cc=Object.freeze({__proto__:null,addRole:async(e,t,n)=>{const r=we();r.log("channel/addRole",e,t,n);const{data:o}=await r.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{channelId:e,role:t,userIds:n}),s=await Bn(o);r.cache&&Kt(s),Xe("local.channel-moderator.role-added",s);const{channelUsers:a}=s;return!!a.find((n=>n.channelId===e&&n.roles.includes(t)))},removeRole:async(e,t,n)=>{const r=we();r.log("channel/removeRole",e,t,n);const{data:o}=await r.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{data:{channelId:e,role:t,userIds:n}}),s=await Bn(o);r.cache&&Kt(s),Xe("local.channel-moderator.role-removed",s);const{channelUsers:a}=s;return!!a.find((n=>n.channelId===e&&!n.roles.includes(t)))},banMembers:async(e,t)=>{const n=we();n.log("channel/banMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v3/channels/${e}/users/ban`,{userIds:t}),o=await Bn(r),{channelUsers:s}=o,a=n.cache&&Date.now();return n.cache&&Kt(o,{cachedAt:a}),{data:null==s?void 0:s.filter((e=>"banned"===e.membership)),cachedAt:a}},unbanMembers:async(e,t)=>{const n=we();n.log("channel/unbanMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}/users/unban`,{userIds:t}),o=await Bn(r),s=n.cache&&Date.now();n.cache&&Kt(o,{cachedAt:s});const{channelUsers:a}=o;return{data:null==a?void 0:a.filter((e=>"member"===e.membership)),cachedAt:s}},muteMembers:async(e,t,n=-1)=>{const r=we();r.log("channel/muteMembers",{userIds:t,channelId:e,mutePeriod:n});const{data:o}=await r.http.put(`/api/v2/channel/${e}/users/mute`,{userIds:t,mutePeriod:-1===n?n:1e3*n}),{success:s}=o;return s},unmuteMembers:async(e,t)=>{const n=we();n.log("channel/unmuteMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v2/channel/${encodeURIComponent(e)}/users/mute`,{userIds:t,mutePeriod:0}),{success:o}=r;return o}}),lc=Object.freeze({__proto__:null,Membership:ic,Moderation:cc,getChannelByIds:Kn,createChannel:async e=>{const t=we();let n;if(t.log("user/createChannel",e),"conversation"===(null==e?void 0:e.type))n=await t.http.post("/api/v3/channels/conversation",Object.assign(Object.assign({},e),{isDistinct:!0}));else{const{isPublic:r}=e,o=zt(e,["isPublic"]);n=await t.http.post("/api/v3/channels",Object.assign(Object.assign({},o),{isPublic:"community"===(null==e?void 0:e.type)?r:void 0}))}const r=await Bn(n.data),o=t.cache&&Date.now();t.cache&&Kt(r,{cachedAt:o});const{channels:s}=r;return{data:s[0],cachedAt:o}},updateChannel:async(e,t)=>{const n=we();n.log("channel/updateChannel",e,t);const{data:r}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}`,t),o=await Bn(r),s=n.cache&&Date.now();n.cache&&Kt(o,{cachedAt:s});const{channels:a}=o;return{data:a.find((t=>t.channelId===e)),cachedAt:s}},deleteChannel:async e=>{const t=we();t.log("channel/deleteChannel",e),await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}`);return(await fi(e)).data},joinChannel:async e=>{const t=we();t.log("channel/joinChannel",e);const{data:n}=await t.http.post(`/api/v3/channels/${encodeURIComponent(e)}/join`),r=await Bn(n);t.cache&&Kt(r);const{channelUsers:o}=r;return!!o.find((t=>t.channelId===e&&"member"===t.membership))},leaveChannel:async e=>{const t=we();t.log("channel/leaveChannel",e);const{data:n}=await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/leave`),r=await Bn(n);t.cache&&Kt(r);const{channelUsers:o}=r;return!!o.find((t=>t.channelId===e&&"member"!==t.membership))},muteChannel:async(e,t=-1)=>{const n=we();if(n.log("channel/muteChannel",e),-1!==t&&t<0)throw new fe("Mute Period can only be positive numbers or -1(mute forever)",800110,"error");const{data:r}=await n.http.put(`/api/v2/channel/${encodeURIComponent(e)}/mute`,{mutePeriod:t}),{success:o}=r;return o},unmuteChannel:async e=>{const t=we();t.log("channel/unmuteChannel",e);const{data:n}=await t.http.put(`/api/v2/channel/${encodeURIComponent(e)}/mute`,{mutePeriod:0}),{success:r}=n;return r},markAsRead:bn,onChannelCreated:Yr,onChannelUpdated:eo,onChannelDeleted:Ur,onChannelJoined:ro,onChannelLeft:ao,onChannelMuted:lo,onChannelMemberAdded:po,onChannelMemberRemoved:mo,onChannelMemberBanned:Dr,onChannelMemberUnbanned:bo,onChannelMemberRoleAdded:Io,onChannelMemberRoleRemoved:ko,observeChannel:(e,t)=>{const{log:n}=we(),r=Date.now();n(`observeChannel(tmpid: ${r}) > listen`);const o=(n,r)=>{var o,s,a;if((null===(o=n.data)||void 0===o?void 0:o.channelId)===e){if(t instanceof Function)return t(Object.assign(Object.assign({},n),{data:wn.channel(n.data)}));"onFetch"!==r&&(null===(s=t.onEvent)||void 0===s||s.call(t,r,Object.assign(Object.assign({},n),{data:wn.channel(n.data)}))),null===(a=t[r])||void 0===a||a.call(t,Object.assign(Object.assign({},n),{data:wn.channel(n.data)}))}},s=[];return s.push(eo((e=>o({data:e,loading:!1,origin:"event"},"onUpdate"))),Ur((e=>o({data:e,loading:!1,origin:"event"},"onDelete"))),ro((e=>o({data:e,loading:!1,origin:"event"},"onJoin"))),ao((e=>o({data:e,loading:!1,origin:"event"},"onLeft"))),lo((e=>o({data:e,loading:!1,origin:"event"},"onMute"))),po((e=>o({data:e,loading:!1,origin:"event"},"onMemberAdded"))),mo((e=>o({data:e,loading:!1,origin:"event"},"onMemberRemoved"))),gi(ss,"entityId","channel")((e=>o({data:e,loading:!1,origin:"event"},"onUpdate")))),ie(se(fi,e),(e=>e.data&&o(e,"onFetch"))),()=>{n(`observeChannel(tmpid: ${r}) > dispose`),s.forEach((e=>e()))}},observeChannels:e=>{const{log:t}=we(),n=Date.now();t(`observeChannels(tmpid: ${n}) > listen`);const r=[],o=(t,n)=>{var r,o;if(e instanceof Function)return e(wn.channel(t));null===(r=e.onEvent)||void 0===r||r.call(e,n,wn.channel(t)),null===(o=e[n])||void 0===o||o.call(e,wn.channel(t))};return r.push(Yr((e=>o(e,"onCreate"))),eo((e=>o(e,"onUpdate"))),Ur((e=>o(e,"onDelete"))),ro((e=>o(e,"onJoin"))),ao((e=>o(e,"onLeft"))),lo((e=>o(e,"onMute"))),po((e=>o(e,"onMemberAdded"))),mo((e=>o(e,"onMemberRemoved"))),gi(ss,"entityId","channel")((e=>o(e,"onUpdate")))),()=>{t(`observeChannels(tmpid: ${n}) > dispose`),r.forEach((e=>e()))}},getChannel:(e,t)=>{const n=we();let r;return gs(e,(async e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:wn.channel(Cn(e.data))}),o=zt(n,["origin"]);return ln(r,o)?void 0:(r=o,t(n))}),"channelId",fi,[eo,Ur,ro,ao,po,mo,Dr,bo,lo,gi(ss,"entityId","channel"),gi(wi,"entityId","channel"),gi((t=>Ao((async r=>{await(async r=>{var o;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await An(r),r.channelId!==e)return;const s=null===(o=Se(["channel","get",e]))||void 0===o?void 0:o.data;s&&(bi(s,{messagePreviewId:r.messageId}),t(r))})(r),t(r)}))),"channelId","channel"),gi((t=>Eo((async r=>{var o;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await An(r),r.channelId!==e)return;const s=null===(o=Se(["channel","get",e]))||void 0===o?void 0:o.data;s&&(bi(s,{messagePreviewId:r.messageId}),t(r))}))),"channelId","channel"),gi((t=>mi((async r=>{var o;const s=null===(o=Se(["channel","get",e]))||void 0===o?void 0:o.data;if(!s||s.messagePreviewId!==r.messageId)return;"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(await En(r),t(r))}))),"channelId","channel"),gi((t=>yi((async r=>{var o;const s=null===(o=Se(["channel","get",e]))||void 0===o?void 0:o.data;if(!s||s.messagePreviewId!==r.messageId)return;const a=await n.getMessagePreviewSetting(!1);"no-message-preview"!==a&&("message-preview-not-include-deleted"===a?(Te(["messagePreviewChannel","get",e]),await fi(r.channelId)):await En(r),t(r))}))),"channelId","channel"),gi((e=>Po((async t=>{var r,o;const{channelId:s,subChannelId:a}=t,i=null===(r=Se(["messagePreviewChannel","get",s]))||void 0===r?void 0:r.data;if(!i||i.subChannelId!==a)return;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;await fi(s);(null===(o=Se(["channel","get",s]))||void 0===o?void 0:o.data)&&e(t)}))),"channelId","channel"),gi((t=>vi((async r=>{var o,s;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;Mn(r);const a=null===(o=Se(["messagePreviewChannel","get",e]))||void 0===o?void 0:o.data;if(!a||a.subChannelId!==r.subChannelId)return;(null===(s=Se(["channel","get",e]))||void 0===s?void 0:s.data)&&t(r)}))),"channelId","channel"),gi(Mo,"channelId","channel"),gi(Gi,"channelId","channel")],{forceDispatch:!0})},getChannels:(e,t,n)=>{const{log:r,cache:o,userId:s}=we();o||console.log(D);const a=Date.now();r(`getChannels(tmpid: ${a}) > listen`);const i=new nc(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{Te(l)})),()=>{r(`getChannels(tmpid: ${a}) > dispose`),c.forEach((e=>e()))}},MARKER_INCLUDED_CHANNEL_TYPE:jn,isUnreadCountSupport:xn,convertFromRaw:Dn,preUpdateChannelCache:Nn,prepareChannelPayload:Bn});const dc=(e,t)=>{0!==e.length&&0!==t.length&&e.forEach((({communityId:e})=>{const n=t.filter((({communityId:t})=>e===t));_e(["communityUsers","collection",e],n)}))},uc=async e=>{const t=we();t.log("community/getCommunities",e);const{data:n}=await t.http.get("/api/v3/communities/list",{params:{communityIds:e}}),r=Ba(n),o=t.cache&&Date.now();return t.cache&&(Kt(r,{cachedAt:o}),dc(r.communities,r.communityUsers)),{data:r.communities,cachedAt:o}};uc.locally=e=>{var t;const n=we();if(n.log("community/getCommunities.locally",e),!n.cache)return;const r=e.map((e=>Se(["community","get",e]))).filter(Boolean),o=r.map((({data:e})=>e)),s=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:o,cachedAt:s.cachedAt}};const hc=async e=>{const t=we();t.log("community/getCommunity",e);const{data:n}=await t.http.get(`/api/v3/communities/${e}`),r=Ba(n),o=t.cache&&Date.now();t.cache&&(Kt(r,{cachedAt:o}),dc(r.communities,r.communityUsers));const{communities:s}=r;return{data:s.find((t=>t.communityId===e)),cachedAt:o}};hc.locally=e=>{const t=we();if(t.log("community/getCommunity.locally",e),!t.cache)return;const n=Se(["community","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const pc=async e=>{const t=we();t.log("channel/getTopTrendingCommunities",e);const{limit:n=5}=null!=e?e:{},{data:r}=await t.http.get("/api/v3/communities/top-trending",{params:{options:{limit:n}}}),o=Ba(r),{communities:s}=o,a=t.cache&&Date.now();if(t.cache){Kt(o,{cachedAt:a});_e(["community","top-trending",{params:{options:{limit:n}}}],{communities:s.map(de("community"))})}return{data:s,cachedAt:a}};pc.locally=e=>{var t,n;const r=we();if(r.log("community/getTopTrendingCommunities.locally",e),!r.cache)return;const{limit:o=5}=null!=e?e:{},s=["community","top-trending",{params:{options:{limit:o}}}],{data:a,cachedAt:i}=null!==(t=Se(s))&&void 0!==t?t:{};if(!(null==a?void 0:a.communities.length))return;const c=a.communities.map((e=>Se(["community","get",e]))).filter(Boolean).map((({data:e})=>e));return c.length===(null===(n=null==a?void 0:a.communities)||void 0===n?void 0:n.length)?{data:c,cachedAt:i}:void 0};const fc=(e,t)=>{const n=we();return Ze(n,e,e,(e=>{const r=Ba(e);if(n.cache){Kt(r);const e=Se(["community","get",r.communities[0].communityId]);t(e.data)}else t(r.communities[0])}))},gc=e=>fc("community.created",e),mc=e=>fc("community.updated",e),yc=e=>fc("community.deleted",e);function vc(e,t,n){return!!e.permissions.some((e=>e===n))||t.communityUsers.find((t=>t.userId===e.userId)).permissions.some((e=>e===n))}function bc(e,t){return"community.joined"===e||"community.left"===e?t.communityUsers:"community.userRemoved"===e||"local.community.userRemoved"===e?t.communityUsers.filter((e=>"none"===e.communityMembership)):"community.userBanned"===e?t.communityUsers.filter((e=>"banned"===e.communityMembership)):"community.userUnbanned"===e?t.communityUsers.filter((e=>!vc(e,t,"BAN_COMMUNITY_USER"))):t.communityUsers.filter((e=>!vc(e,t,"ADD_COMMUNITY_USER")))}const wc=(e,t)=>{const n=we();return Ze(n,e,e,(r=>{const o=Ba(r),{communities:s,communityUsers:a}=o,i=Aa(s,a);if(o.communities=i,n.cache){Kt(o);const n=Se(["community","get",o.communities[0].communityId]),r=bc(e,o).map((e=>{const t=Se(["communityUsers","get",de("communityUsers")(e)]);return null==t?void 0:t.data})).filter(dn);t(n.data,r)}else t(o.communities[0],bc(e,o))}))},Cc=(e,t)=>{const n=we();return Ze(n,e,e,(r=>{const o=Ba(r),{communities:s,communityUsers:a}=o,i=Aa(s,a);if(o.communities=i,n.cache){Kt(o);const n=Se(["community","get",o.communities[0].communityId]),r=bc(e,o).map((e=>{const t=Se(["communityUsers","get",de("communityUsers")(e)]);return null==t?void 0:t.data})).filter(dn);t(n.data,r)}else t(o.communities[0],bc(e,o))}))},Ic=e=>wc("community.userAdded",e),Sc=e=>wc("community.userRemoved",e),_c=e=>wc("community.userBanned",e),kc=e=>wc("community.userChanged",e),Oc=e=>wc("community.userUnbanned",e),Tc=e=>wc("community.roleAdded",e),Ac=e=>wc("community.roleRemoved",e),Ec=e=>Cc("local.community.userAdded",e),Mc=e=>Cc("local.community.userRemoved",e),Pc=e=>wc("community.joined",e),Rc=e=>wc("community.left",e),Uc=e=>Cc("local.community.joined",e),jc=e=>Cc("local.community.left",e);class xc extends ws{async getRequest(e,t){const{limit:n=j}=e,r=zt(e,["limit"]),o=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},r),{isDeleted:zn(r.includeDeleted),keyword:r.displayName,filter:r.membership,options:o})});return s}}class Dc extends Is{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:e.communities.map(de("community"))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(o=null==t?void 0:t.data)&&void 0!==o?o:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(de("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Se(this.cacheKey))||void 0===t?void 0:t.data;n&&(_e(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Nc,Bc;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Nc||(Nc={})),function(e){e.OnCommunityJoined="onCommunityJoined",e.OnCommunityLeft="onCommunityLeft",e.OnCommunityUserBanned="onCommunityUserBanned",e.OnCommunityUserChanged="onCommunityUserChanged",e.OnCommunityUserRoleAdded="onCommunityUserRoleAdded",e.OnCommunityUserRoleRemoved="onCommunityUserRoleRemoved",e.OnCommunityUserUnbanned="onCommunityUserUnbanned",e.OnMemberCountChanged="OnMemberCountChanged",e.OnCommunityUserAdded="OnCommunityUserAdded",e.onCommunityUserRemoved="onCommunityUserRemoved",e.OnUserDeleted="OnUserDeleted"}(Bc||(Bc={}));class qc extends ws{async getRequest(e,t){const{limit:n=j,includeDeleted:r}=e,o=zt(e,["limit","includeDeleted"]),s=t?{token:t}:{limit:n},a=!1!==r&&void 0,{data:i}=await this.http.get(`/api/v3/communities/${o.communityId}/users`,{params:Object.assign(Object.assign({},o),{options:s,isDeleted:a})});return i}}class Fc extends Is{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>de("communityUsers")({communityId:e,userId:t})))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(o=null==t?void 0:t.data)&&void 0!==o?o:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>de("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(t,n)=>{var r;const o=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;o&&(e===Bc.OnCommunityUserRoleAdded&&"displayName"===this.query.sortBy||(n.forEach((e=>{const t=de("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership?o.data=o.data.filter((e=>e!==t)):o.data.includes(t)||(o.data=[t,...o.data])})),_e(this.cacheKey,o),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Lc=e=>{const t=we();return Ze(t,"onLocalCommunityRoleRemoved","local.community.roleRemoved",(async t=>{const{communities:n,communityUsers:r}=t;e(n[0],r.filter((e=>"member"===e.communityMembership)))}))},Kc=e=>{const t=we();return Ze(t,"onLocalCommunityRoleAdded","local.community.roleAdded",(async t=>{const{communities:n,communityUsers:r}=t;e(n[0],r.filter((e=>"member"===e.communityMembership)))}))},$c=e=>t=>{const n=we();return Ze(n,"user.deleted","user.deleted",(n=>{var r,o;const s=Nr(n);if(0===s.users.length)return;const a=s.users[0];Kt(s);const i=de("communityUsers")({communityId:e,userId:a.userId}),c=null===(r=Se(["communityUsers","get",i]))||void 0===r?void 0:r.data;_e(["communityUsers","get",i],Object.assign(Object.assign({},c),{user:a}));const l=null===(o=Se(["community","get",e]))||void 0===o?void 0:o.data;t(l,[Object.assign(Object.assign({},c),{user:a})])}))};class zc extends ks{constructor(e,t){const n=w.default(e),r=["communityUsers","collection",n];super(new qc(e),n,r,t),this.query=e,this.queryStreamController=new Fc(this.query,this.cacheKey,this.notifyChange.bind(this),Ba),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Pc,action:Bc.OnCommunityJoined},{fn:Uc,action:Bc.OnCommunityJoined},{fn:Rc,action:Bc.OnCommunityLeft},{fn:jc,action:Bc.OnCommunityLeft},{fn:_c,action:Bc.OnCommunityUserBanned},{fn:kc,action:Bc.OnCommunityUserChanged},{fn:Tc,action:Bc.OnCommunityUserRoleAdded},{fn:Ac,action:Bc.OnCommunityUserRoleRemoved},{fn:Kc,action:Bc.OnCommunityUserRoleAdded},{fn:Lc,action:Bc.OnCommunityUserRoleRemoved},{fn:Oc,action:Bc.OnCommunityUserUnbanned},{fn:Ec,action:Bc.OnCommunityUserAdded},{fn:Mc,action:Bc.onCommunityUserRemoved},{fn:$c(this.query.communityId),action:Bc.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var r,o;const s=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const a=this.applyFilter(null!==(o=s.data.map((e=>Se(["communityUsers","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==o?o:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=Me(e,"roles",this.query.roles);switch(this.query.memberships&&(t=t.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),this.query.search&&(t=xe(t,this.query.search)),!1===this.query.includeDeleted&&(t=t.filter((({user:e})=>!0!==(null==e?void 0:e.isDeleted)))),this.query.sortBy){case"firstCreated":t=t.sort(Be);break;case"displayName":t=t.sort(((e,t)=>{var n,r,o,s;return(null===(n=null==e?void 0:e.user)||void 0===n?void 0:n.displayName)&&(null===(r=null==t?void 0:t.user)||void 0===r?void 0:r.displayName)?null===(o=null==e?void 0:e.user)||void 0===o?void 0:o.displayName.localeCompare(null===(s=null==t?void 0:t.user)||void 0===s?void 0:s.displayName):0}));break;default:t=t.sort(Fe)}return t}}class Qc extends ws{async getRequest(e,t){const{limit:n=j,includeDeleted:r}=e,o=zt(e,["limit","includeDeleted"]),s=t?{token:t}:{limit:n},a=!1!==r&&void 0,{data:i}=await this.http.get(`/api/v3/communities/${o.communityId}/users`,{params:Object.assign(Object.assign({},o),{options:s,isDeleted:a})});return i}}class Vc extends Is{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>de("communityUsers")({communityId:e,userId:t})))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(o=null==t?void 0:t.data)&&void 0!==o?o:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>de("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const r=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;r&&(t.forEach((e=>{const t=de("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership&&(r.data=r.data.filter((e=>e!==t)))})),_e(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Hc;!function(e){e.OnCommunityJoined="onCommunityJoined",e.OnCommunityLeft="onCommunityLeft",e.OnCommunityUserBanned="onCommunityUserBanned",e.OnCommunityUserChanged="onCommunityUserChanged",e.OnCommunityUserRoleAdded="onCommunityUserRoleAdded",e.OnCommunityUserRoleRemoved="onCommunityUserRoleRemoved",e.OnCommunityUserUnbanned="onCommunityUserUnbanned"}(Hc||(Hc={}));class Wc extends ks{constructor(e,t){const n=w.default(e),r=["communityUsers","collection",n];super(new Qc(e),n,r,t),this.query=e,this.queryStreamController=new Vc(this.query,this.cacheKey,this.notifyChange.bind(this),Ba),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Pc,action:Hc.OnCommunityJoined},{fn:Uc,action:Hc.OnCommunityJoined},{fn:Rc,action:Hc.OnCommunityLeft},{fn:jc,action:Hc.OnCommunityLeft},{fn:_c,action:Hc.OnCommunityUserBanned},{fn:kc,action:Hc.OnCommunityUserChanged},{fn:Lc,action:Hc.OnCommunityUserRoleRemoved},{fn:Ac,action:Hc.OnCommunityUserRoleRemoved},{fn:Oc,action:Hc.OnCommunityUserUnbanned},{fn:$c(this.query.communityId),action:Hc.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var r,o;const s=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const a=this.applyFilter(null!==(o=s.data.map((e=>Se(["communityUsers","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==o?o:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=Me(e,"roles",this.query.roles);return this.query.memberships&&(t=t.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),this.query.search&&(t=xe(t,this.query.search)),!1===this.query.includeDeleted&&(t=t.filter((({user:e})=>!0!==(null==e?void 0:e.isDeleted)))),t}}var Jc=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=we();n.log("community/moderation/addMembers",e,t);const{data:r}=await n.http.post(`/api/v3/communities/${e}/users`,{communityId:e,userIds:t});Xe("local.community.userAdded",r);const o=Vt(r,"communityUsers");n.cache&&Kt(o);const{communityUsers:s}=o;return!!s.find((t=>t.communityId===e&&"member"===t.communityMembership))},removeMembers:async(e,t)=>{const n=we();n.log("community/moderation/removeMembers",e,t);const{data:r}=await n.http.delete(`/api/v3/communities/${e}/users`,{data:{communityId:e,userIds:t}});Xe("local.community.userRemoved",r);const o=Vt(r,"communityUsers");n.cache&&Kt(o);const{communityUsers:s}=o;return!!s.find((t=>t.communityId===e&&"member"!==t.communityMembership))},applyFilter:(e,t)=>{let n=Me(e,"roles",t.roles);t.memberships&&(n=n.filter((({communityMembership:e})=>t.memberships.includes(e)))),t.search&&(n=xe(n,t.search));const r=t.sortBy?t.sortBy:"lastCreated";return n=n.sort("lastCreated"===r?Fe:Be),n},getMembers:(e,t,n)=>{const{log:r,cache:o}=we();o||console.log(D);const s=Date.now();r(`getMembers(tmpid: ${s}) > listen`);const a=new zc(e,(e=>{t(e)})),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>{Te(c)})),()=>{r(`getMembers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},searchMembers:(e,t,n)=>{const{log:r,cache:o}=we();o||console.log(D);const s=Date.now();r(`getMembers(tmpid: ${s}) > listen`);const a=new Wc(e,(e=>{t(e)})),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>{Te(c)})),()=>{r(`getMembers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},onCommunityUserAdded:Ic,onCommunityUserRemoved:Sc,onCommunityUserBanned:_c,onCommunityUserChanged:kc,onCommunityUserUnbanned:Oc,onCommunityUserRoleAdded:Tc,onCommunityUserRoleRemoved:Ac,onLocalCommunityUserAdded:Ec,onLocalCommunityUserRemoved:Mc,onCommunityJoined:Pc,onCommunityLeft:Rc,onLocalCommunityJoined:Uc,onLocalCommunityLeft:jc});class Gc extends ks{constructor(e,t){const n=w.default(e),r=["community","collection",n];super(new xc(e),n,r,t),this.query=e,this.queryStreamController=new Dc(this.query,this.cacheKey,this.notifyChange.bind(this),Ba),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:yc,action:Nc.OnCommunityDeleted},{fn:mc,action:Nc.OnCommunityUpdated},{fn:Pc,action:Bc.OnCommunityJoined},{fn:Rc,action:Bc.OnCommunityLeft},{fn:kc,action:Bc.OnMemberCountChanged},{fn:Uc,action:Bc.OnCommunityJoined},{fn:jc,action:Bc.OnCommunityLeft}])}notifyChange({origin:e,loading:t,error:n}){var r,o;const s=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const a=this.applyFilter(null!==(o=s.data.map((e=>Se(["community","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==o?o:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=we();let n=e;return this.query.includeDeleted||(n=Ae(n,"isDeleted",!1)),this.query.categoryId&&(n=n.filter((e=>{var t;return null===(t=e.categoryIds)||void 0===t?void 0:t.includes(this.query.categoryId)}))),this.query.tags&&(n=n.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.membership&&t&&(n=Ue(n,this.query.membership,t)),n}}class Yc extends ws{async getRequest(e,t){const{limit:n=j}=e,r=zt(e,["limit"]),o=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},r),{isDeleted:zn(r.includeDeleted),keyword:r.displayName,filter:r.membership,options:o})});return s}}var Zc;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Zc||(Zc={}));class Xc extends Is{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&(Kt(t,{cachedAt:r}),dc(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:e.communities.map(de("community"))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(o=null==t?void 0:t.data)&&void 0!==o?o:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(de("community"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;r&&(this.query.displayName&&e===Zc.OnCommunityCreated||(r.data=[...new Set([t.communityId,...r.data])],_e(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class el extends ks{constructor(e,t){const n=w.default(e),r=["community","collection",n];super(new Yc(e),n,r,t),this.query=e,this.queryStreamController=new Xc(this.query,this.cacheKey,this.notifyChange.bind(this),Ba),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:gc,action:Zc.OnCommunityCreated},{fn:yc,action:Zc.OnCommunityDeleted},{fn:mc,action:Zc.OnCommunityUpdated},{fn:Pc,action:Bc.OnCommunityJoined},{fn:Rc,action:Bc.OnCommunityLeft},{fn:kc,action:Bc.OnMemberCountChanged},{fn:Uc,action:Bc.OnCommunityJoined},{fn:jc,action:Bc.OnCommunityLeft}])}notifyChange({origin:e,loading:t,error:n}){var r,o;const s=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const a=this.applyFilter(null!==(o=s.data.map((e=>Se(["community","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==o?o:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=we();let n=e;if(this.query.includeDeleted||(n=Ae(n,"isDeleted",!1)),this.query.categoryId&&(n=n.filter((e=>{var t;return null===(t=e.categoryIds)||void 0===t?void 0:t.includes(this.query.categoryId)}))),this.query.tags&&(n=n.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.membership&&t&&(n=Ue(n,this.query.membership,t)),!this.query.displayName){const e=(()=>{switch(this.query.sortBy){case"firstCreated":return Be;case"lastCreated":default:return Fe;case"displayName":return De}})();n=n.sort(e)}return n}}class tl extends ws{async getRequest(e,t){const{limit:n=j}=e,r=zt(e,["limit"]),o=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v3/communities/top-trending",{params:Object.assign(Object.assign({},r),{options:o})});return s}}class nl extends Is{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&(Kt(t,{cachedAt:r}),dc(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:e.communities.map(de("community"))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(o=null==t?void 0:t.data)&&void 0!==o?o:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(de("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Se(this.cacheKey))||void 0===t?void 0:t.data;n&&(_e(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var rl;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(rl||(rl={}));class ol extends ks{constructor(e,t){const n=w.default(e),r=["trendingCommunity","collection",n];super(new tl(e),n,r,t),this.query=e,this.queryStreamController=new nl(this.query,this.cacheKey,this.notifyChange.bind(this),Ba),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:yc,action:rl.OnCommunityDeleted},{fn:mc,action:rl.OnCommunityUpdated},{fn:Pc,action:Bc.OnCommunityJoined},{fn:Rc,action:Bc.OnCommunityLeft},{fn:kc,action:Bc.OnMemberCountChanged},{fn:Uc,action:Bc.OnCommunityJoined},{fn:jc,action:Bc.OnCommunityLeft}])}notifyChange({origin:e,loading:t,error:n}){var r,o;const s=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const a=null!==(o=s.data.map((e=>Se(["community","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==o?o:[];(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class sl extends ws{async getRequest(e,t){const{limit:n=j}=e,r=zt(e,["limit"]),o=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v3/communities/recommended",{params:Object.assign(Object.assign({},r),{options:o})});return s}}class al extends Is{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&(Kt(t,{cachedAt:r}),dc(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:e.communities.map(de("community"))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(o=null==t?void 0:t.data)&&void 0!==o?o:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(de("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Se(this.cacheKey))||void 0===t?void 0:t.data;n&&(_e(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var il;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(il||(il={}));class cl extends ks{constructor(e,t){const n=w.default(e),r=["community","collection",n];super(new sl(e),n,r,t),this.query=e,this.queryStreamController=new al(this.query,this.cacheKey,this.notifyChange.bind(this),Ba),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:yc,action:il.OnCommunityDeleted},{fn:mc,action:il.OnCommunityUpdated},{fn:Pc,action:Bc.OnCommunityJoined},{fn:Rc,action:Bc.OnCommunityLeft},{fn:kc,action:Bc.OnMemberCountChanged},{fn:Uc,action:Bc.OnCommunityJoined},{fn:jc,action:Bc.OnCommunityLeft}])}notifyChange({origin:e,loading:t,error:n}){var r,o;const s=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const a=null!==(o=s.data.map((e=>Se(["community","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==o?o:[];(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var ll=Object.freeze({__proto__:null,addRoles:async(e,t,n)=>{const r=we();r.log("community/moderation/addRoles",e,t,n);const{data:o}=await r.http.post(`/api/v4/communities/${e}/users/roles`,{communityId:e,roles:t,userIds:n}),s=qa(o);r.cache&&Kt(s),Xe("local.community.roleAdded",s);const{communityUsers:a}=s;return!!a.find((n=>n.communityId===e&&t.some((e=>n.roles.includes(e)))))},removeRoles:async(e,t,n)=>{const r=we();r.log("community/moderation/removeRoles",e,t,n);const{data:o}=await r.http.delete(`/api/v4/communities/${e}/users/roles`,{data:{communityId:e,roles:t,userIds:n}}),s=qa(o);r.cache&&Kt(s),Xe("local.community.roleRemoved",s);const{communityUsers:a}=s;return!!a.find((n=>n.communityId===e&&!t.some((e=>n.roles.includes(e)))))},banMembers:async(e,t)=>{const n=we();n.log("community/banMembers",{userIds:t,communityId:e});const{data:r}=await n.http.put(`/api/v3/communities/${e}/users/ban`,{userIds:t}),o=Vt(r,"communityUsers"),s=n.cache&&Date.now();n.cache&&Kt(o,{cachedAt:s});const{communityUsers:a}=o;return{data:a.filter((e=>t.includes(e.userId))),cachedAt:s}},unbanMembers:async(e,t)=>{const n=we();n.log("community/unbanMembers",{userIds:t,communityId:e});const{data:r}=await n.http.put(`/api/v3/communities/${e}/users/unban`,{userIds:t}),o=Vt(r,"communityUsers"),s=n.cache&&Date.now();n.cache&&Kt(o,{cachedAt:s});const{communityUsers:a}=o;return{data:a.filter((e=>t.includes(e.userId))),cachedAt:s}}}),dl=Object.freeze({__proto__:null,Moderation:ll,Membership:Jc,getCommunityByIds:uc,createCommunity:async e=>{const t=we();t.log("user/createCommunity",e);const{data:n}=await t.http.post("/api/v3/communities/",Fa(e));Xe("community.created",n);const r=Ba(n),o=t.cache&&Date.now();t.cache&&(Kt(r,{cachedAt:o}),dc(r.communities,r.communityUsers));const{communities:s}=r;return{data:s[0],cachedAt:o}},updateCommunity:async(e,t)=>{const n=we();n.log("community/updateCommunity",e,t);const{data:r}=await n.http.put(`/api/v3/communities/${e}`,Fa(t));Xe("community.updated",r);const o=Ba(r),s=n.cache&&Date.now();n.cache&&(Kt(o,{cachedAt:s}),dc(o.communities,o.communityUsers));const{communities:a}=o;return{data:a.find((t=>t.communityId===e)),cachedAt:s}},deleteCommunity:async e=>{const t=we();t.log("community/deleteCommunity",e),await t.http.delete(`/api/v3/communities/${e}`);const n=await hc(e);return Xe("community.deleted",{communities:[n.data],categories:[],communityUsers:[],feeds:[],files:[],users:[]}),n.data},joinCommunity:async e=>{const t=we();t.log("community/joinCommunity",e);const{data:n}=await t.http.post(`/api/v3/communities/${e}/join`);Xe("local.community.joined",n);const r=Ba(n),o=t.cache&&Date.now();t.cache&&Kt(r,{cachedAt:o});const{communityUsers:s}=r;return!!s.find((t=>t.communityId===e&&"member"===t.communityMembership))},leaveCommunity:async e=>{const t=we();t.log("community/leaveCommunity",e);const{data:n}=await t.http.delete(`/api/v3/communities/${e}/leave`);Xe("local.community.left",n);const r=Ba(n),o=t.cache&&Date.now();t.cache&&Kt(r,{cachedAt:o});const{communityUsers:s}=r;return!!s.find((t=>t.communityId===e&&"member"!==t.communityMembership))},getTopTrendingCommunities:pc,onCommunityCreated:gc,onCommunityUpdated:mc,onCommunityDeleted:yc,observeCommunity:(e,t)=>{const{log:n}=we(),r=Date.now();n(`observeCommunity(tmpid: ${r}) > listen`);const o=(e,n)=>{var r,o;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(o=t[n])||void 0===o||o.call(t,e)},s=(t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.communityId)===e&&o(t,n)},a=[];return a.push(mc((e=>s({data:e,loading:!1,origin:"event"},"onUpdate"))),yc((e=>s({data:e,loading:!1,origin:"event"},"onDelete"))),Pc((e=>s({data:e,loading:!1,origin:"event"},"onJoin"))),Rc((e=>s({data:e,loading:!1,origin:"event"},"onLeft"))),Ic((e=>s({data:e,loading:!1,origin:"event"},"onUserAdded"))),Sc((e=>s({data:e,loading:!1,origin:"event"},"onUserRemoved"))),_c((e=>s({data:e,loading:!1,origin:"event"},"onUserBanned"))),Oc((e=>s({data:e,loading:!1,origin:"event"},"onUserUnbanned")))),ie(se(hc,e),(e=>(e.data||e.error)&&o(e,"onFetch"))),()=>{n(`observeCommunity(tmpid: ${r}) > dispose`),a.forEach((e=>e()))}},searchCommunities:(e,t,n)=>{const{log:r,cache:o}=we();o||console.log(D);const s=Date.now();r(`searchCommunities(tmpid: ${s}) > listen`);const a=new Gc(e,t),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>Te(c))),()=>{r(`searchCommunities(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getCommunities:(e,t,n)=>{const{log:r,cache:o}=we();o||console.log(D);const s=Date.now();r(`getCommunities(tmpid: ${s}) > listen`);const a=new el(e,t),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>Te(c))),()=>{r(`getCommunities(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getCommunity:(e,t)=>gs(e,t,"communityId",hc,[mc,yc,Pc,Rc,Uc,jc,_c,Oc,kc]),getTrendingCommunities:(e,t,n)=>{const{log:r,cache:o,userId:s}=we();o||console.log(D);const a=Date.now();r(`getTrendingCommunities(tmpid: ${a}) > listen`);const i=new ol(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>Te(l))),()=>{r(`getTrendingCommunities(tmpid: ${a}) > dispose`),c.forEach((e=>e()))}},getRecommendedCommunities:(e,t,n)=>{const{log:r,cache:o,userId:s}=we();o||console.log(D);const a=Date.now();r(`getRecommendedCommunities(tmpid: ${a}) > listen`);const i=new cl(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>Te(l))),()=>{r(`getRecommendedCommunities(tmpid: ${a}) > dispose`),c.forEach((e=>e()))}}});const ul=async e=>{const t=we();t.log("category/getCategory",e);const{data:n}=await t.http.get(`/api/v3/community-categories/${encodeURIComponent(e)}`),r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const{categories:o}=n;return{data:wn.category(o.find((t=>t.categoryId===e))),cachedAt:r}};ul.locally=e=>{const t=we();if(t.log("category/getCategory.locally",e),!t.cache)return;const n=Se(["category","get",e]);return n?{data:wn.category(n.data),cachedAt:n.cachedAt}:void 0};const hl=async e=>{const t=we();t.log("category/queryCategories",e);const n=null!=e?e:{},{page:r,limit:o,includeDeleted:s}=n,a=zt(n,["page","limit","includeDeleted"]),i=r?{token:r}:o?{limit:o}:void 0,{data:c}=await t.http.get("/api/v3/community-categories",{params:Object.assign(Object.assign({},a),{isDeleted:zn(s),options:i})}),{paging:l}=c,d=zt(c,["paging"]),{categories:u}=d,h=t.cache&&Date.now();if(t.cache){Kt(d,{cachedAt:h});const e=["category","query",Object.assign(Object.assign({},a),{includeDeleted:s,options:i})];_e(e,{categories:u.map(de("category")),paging:l})}return{data:u,cachedAt:h,paging:l}};hl.locally=e=>{var t,n;const r=we();if(r.log("category/queryCategories.locally",e),!r.cache)return;const o=null!=e?e:{},{page:s,limit:a=10}=o,i=zt(o,["page","limit"]),c=s?{token:s}:a?{limit:a}:void 0,l=["category","query",Object.assign(Object.assign({},i),{options:c})],{data:d,cachedAt:u}=null!==(t=Se(l))&&void 0!==t?t:{};if(!(null==d?void 0:d.categories.length))return;const h=d.categories.map((e=>Se(["category","get",e]))).filter(Boolean).map((({data:e})=>e)),{paging:p}=d;return h.length===(null===(n=null==d?void 0:d.categories)||void 0===n?void 0:n.length)?{data:h,cachedAt:u,paging:p}:void 0};var pl=Object.freeze({__proto__:null,getCategory:ul,getCategories:(e,t,n)=>{const{log:r,cache:o}=we();o||console.log(D);const s=Date.now();r(`getCategories(tmpid: ${s}) > listen`);const{limit:a}=e,i=zt(e,["limit"]),c=null!=a?a:j,{policy:l=x}=null!=n?n:{},d=[],u=["category","collection",{}],h=(n=!1)=>{var r,o;const s=null===(r=Se(u))||void 0===r?void 0:r.data,a=null!==(o=null==s?void 0:s.data)&&void 0!==o?o:[];if(!n&&a.length>0&&!(null==s?void 0:s.params.page))return;const d=se(hl,Object.assign(Object.assign({},i),{limit:n?c:void 0,page:n||null==s?void 0:s.params.page}));ie(d,(({data:n,error:r,loading:o,paging:s})=>{const i={loading:o,error:r,params:{page:null==s?void 0:s.next},data:a};n&&(i.data=[...new Set([...a,...n.map(de("category"))])]),_e(u,i),(n=>{var r,o;let s=null!==(r=n.data.map((e=>Se(["category","get",e]))).filter(Boolean).map((({data:e})=>wn.category(e))))&&void 0!==r?r:[];switch(e.includeDeleted||(s=Ae(s,"isDeleted",!1)),e.sortBy){case"firstCreated":s=s.sort(Be);break;case"lastCreated":s=s.sort(Fe);break;default:s=s.sort(Ne)}t({onNextPage:h,data:s,hasNextPage:!!(null===(o=n.params)||void 0===o?void 0:o.page),loading:n.loading,error:n.error})})(i)}),ae(l))};return d.push((()=>{})),h(!0),()=>{r(`getCategories(tmpid: ${s}) > dispose`),d.forEach((e=>e()))}}});const fl=async e=>{const t=we();t.log("feed/queryGlobalFeed",e);const n=null!=e?e:{},{useCustomRanking:r,page:o,queryToken:s}=n,a=zt(n,["useCustomRanking","page","queryToken"]);r&&console.warn('The param "useCustomRanking" has been deprecated. To get custom ranking feed use FeedRepository.getCustomRankingGlobalFeed instead'),o&&console.warn('The param "page" has been deprecated. Please use "queryToken" instead.');const i=s?{token:s}:o?{token:Y(o,"skiplimit")}:void 0,{data:c}=await t.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},a),{options:i})}),{paging:l}=c,d=zt(c,["paging"]),u=Vt(d,"communityUsers"),{posts:h}=u,p=t.cache&&Date.now();if(t.cache){Kt(u);const e=["globalFeed","query",Object.assign(Object.assign({},a),{options:Object.assign({},o)})];_e(e,{posts:h.map(de("post")),paging:l})}const f=Z(l.next),g=Z(l.previous);return{data:h.map(wn.post),cachedAt:p,prevPage:g,nextPage:f,paging:l}};fl.locally=e=>{var t,n;const r=we();if(r.log("post/queryGlobalFeed.locally",e),!r.cache)return;const o=null!=e?e:{},{page:s}=o,a=zt(o,["page"]),i=["globalFeed","query",Object.assign(Object.assign({},a),{options:Object.assign({},s)})],{data:c,cachedAt:l}=null!==(t=Se(i))&&void 0!==t?t:{};if(!(null==c?void 0:c.posts.length))return;const d=c.posts.map((e=>Se(["post","get",e]))).filter(Boolean).map((({data:e})=>e)).map(wn.post),{paging:u}=c,h=Z(null==c?void 0:c.paging.previous),p=Z(null==c?void 0:c.paging.next);return d.length===(null===(n=null==c?void 0:c.posts)||void 0===n?void 0:n.length)?{data:d,cachedAt:l,prevPage:h,nextPage:p,paging:u}:void 0};const gl=async e=>{const t=we();t.log("feed/getCustomRankingGlobalFeed",e);const n=null!=e?e:{},{page:r,queryToken:o,limit:s}=n,a=zt(n,["page","queryToken","limit"]),i=o?{token:o}:r?{token:Y(r,"skiplimit")}:void 0,{data:c}=await t.http.get("/api/v5/me/global-feeds",{params:Object.assign(Object.assign({},a),{limit:o?void 0:s,options:i})}),{paging:l}=c,d=zt(c,["paging"]),u=Vt(d,"communityUsers"),{posts:h}=u,p=t.cache&&Date.now();if(t.cache){Kt(u);const e=["customGlobalFeed","query",Object.assign(Object.assign({},a),{options:Object.assign({},r)})];_e(e,{posts:h.map(de("post")),paging:l})}const f=Z(l.next),g=Z(l.previous);return{data:h.map(wn.post),cachedAt:p,prevPage:g,nextPage:f,paging:l}};gl.locally=e=>{var t,n;const r=we();if(r.log("post/getCustomRankingGlobalFeed.locally",e),!r.cache)return;const o=null!=e?e:{},{page:s}=o,a=zt(o,["page"]),i=["customGlobalFeed","query",Object.assign(Object.assign({},a),{options:Object.assign({},s)})],{data:c,cachedAt:l}=null!==(t=Se(i))&&void 0!==t?t:{};if(!(null==c?void 0:c.posts.length))return;const d=c.posts.map((e=>Se(["post","get",e]))).filter(Boolean).map((({data:e})=>e)),u=Z(null==c?void 0:c.paging.previous),h=Z(null==c?void 0:c.paging.next),{paging:p}=c;return d.length===(null===(n=null==c?void 0:c.posts)||void 0===n?void 0:n.length)?{data:d.map(wn.post),cachedAt:l,prevPage:u,nextPage:h,paging:p}:void 0};var ml=Object.freeze({__proto__:null,queryGlobalFeed:fl,getCustomRankingGlobalFeed:gl});const yl=async e=>{const t=we();t.log("post/getPostByIds",e);const n=e.map((e=>encodeURIComponent(e)));let r;try{r=(await t.http.get("/api/v3/posts/list",{params:{postIds:n}})).data}catch(t){throw e.forEach((e=>{V(null==t?void 0:t.code)&&$t("post",e)})),t}const o=Vt(r,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Kt(o,{cachedAt:s}),{data:o.posts.map(wn.post),cachedAt:s}};yl.locally=e=>{var t;const n=we();if(n.log("post/getPostByIds.locally",e),!n.cache)return;const r=e.map((e=>Se(["post","get",e]))).filter(Boolean),o=r.map((({data:e})=>e)),s=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:o.map(wn.post),cachedAt:s.cachedAt}};const vl=async(e,t=!1)=>{var n;const r=we(),o=await Oa(e);if(await r.http.delete(`/api/v4/posts/${encodeURIComponent(e)}`,{params:{postId:e,permanent:t}}),"community"===o.data.targetType){const e=await hc(o.data.targetId),t=(null!==(n=Ie(["communityUsers","get"]))&&void 0!==n?n:[]).filter((({key:t})=>"communityUsers"===t[0]&&("get"===t[1]&&("string"==typeof t[2]&&t[2].includes(e.data.communityId))))).map((({data:e})=>e));Xe("community.updated",{communities:[e.data],categories:[],communityUsers:t,feeds:[],files:[],users:[]})}const s=Object.assign(Object.assign({},o.data),{isDeleted:!0});return t?setTimeout((()=>{$t("post",e)}),0):Oe(["post","get",e],{isDeleted:!0}),Xe("local.post.deleted",{posts:[s],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[],videoStreamings:[]}),wn.post(s)},bl=async e=>{const t=we();t.log("comment/getCommentByIds",e);const n=e.map((e=>encodeURIComponent(e)));let r;try{r=(await t.http.get("/api/v3/comments/list",{params:{commentIds:n}})).data}catch(t){throw e.forEach((e=>{V(null==t?void 0:t.code)&&$t("comment",e)})),t}const o=t.cache&&Date.now();return t.cache&&Kt(r,{cachedAt:o}),{data:r.comments.map((e=>wn.comment(e))),cachedAt:o}};bl.locally=e=>{var t;const n=we();if(n.log("comment/getCommentByIds.locally",e),!n.cache)return;const r=e.map((e=>Se(["comment","get",e]))).filter(Boolean),o=r.map((({data:e})=>e)),s=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:o.map((e=>wn.comment(e))),cachedAt:s.cachedAt}};const wl=(e,t=!1)=>{const{stories:n}=e,r=n.map((e=>((e,t=!1)=>{const{storyId:n,referenceId:r}=e;return!t&&r?Object.assign(Object.assign({},e),{syncState:"synced"}):Object.assign(Object.assign({},e),{syncState:"synced",referenceId:n})})(e,t)));return Object.assign(Object.assign({},e),{stories:r})},Cl=async e=>{const t=we();t.log("story/getStoryByStoryId",e);const n=Se(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;lr("story",e)}let r;try{const n=await t.http.get(`/api/v4/stories/${e}`);r=wl(n.data)}catch(t){throw V(null==t?void 0:t.code)&&$t("story",e),t}const o=t.cache&&Date.now();return t.cache&&Kt(r,{cachedAt:o}),{data:r.stories[0],cachedAt:o}};Cl.locally=e=>{const t=we();t.log("story/getStorybyStoryId",e);const n=Se(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;lr("story",e)}const r=t.cache&&Date.now(),o=Se(["story","get",e]);if(o)return{data:o.data,cachedAt:r}};const Il=async(e,t=!1)=>{var n;const r=we(),o=await Ta(e);await r.http.delete(`/api/v4/comments/${encodeURIComponent(e)}`,{params:{commentId:e,permanent:t}});const s=Object.assign(Object.assign({},o.data),{isDeleted:!0});if("story"===o.data.referenceType){const e=await Cl(o.data.referenceId);Xe("local.story.updated",{stories:[e.data],categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[]})}else{const e=null===(n=Se(["post","get",o.data.referenceId]))||void 0===n?void 0:n.data;if(e){let t;t=s.parentId?1:s.childrenNumber+1,e.commentsCount-=t,Xe("local.post.updated",{posts:[e],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[],videoStreamings:[]})}}return Xe("local.comment.deleted",{comments:[s],commentChildren:[],files:[],users:[],communityUsers:[]}),t?Je((()=>$t("comment",e))):Oe(["comment","get",e],{isDeleted:!0}),s},Sl=async e=>{const t=we();let n;t.log("comment/getComment",e),lr("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw V(null==t?void 0:t.code)&&$t("comment",e),t}const r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const{comments:o}=n;return{data:o.find((t=>t.commentId===e)),cachedAt:r}};Sl.locally=e=>{const t=we();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=Se(["comment","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const _l=e=>ti("local.comment.deleted",e),kl=e=>{const t=we();return Ze(t,"local.comment.addReaction","local.comment.addReaction",(({comment:n})=>{t.cache?(Oe(["comment","get",n.commentId],n),e(un(n))):e(n)}))},Ol=e=>{const t=we();return Ze(t,"local.comment.removeReaction","local.comment.removeReaction",(({comment:n})=>{t.cache?(Oe(["comment","get",n.commentId],n),e(un(n))):e(n)}))};class Tl extends ws{async getRequest(e,t){const{limit:n=j,includeDeleted:r}=e,o=zt(e,["limit","includeDeleted"]),s={type:o.sortBy||e.limit?"pagination":void 0},a=t?Object.assign(Object.assign({},s),{token:t}):Object.assign(Object.assign({},s),{limit:n}),{data:i}=await this.http.get("/api/v3/comments",{params:Object.assign(Object.assign({},o),{isDeleted:zn(r),options:a})});return i}}var Al;!function(e){e.OnCommentCreated="onCommentCreated",e.OnCommentUpdated="onCommentUpdated",e.OnCommentDeleted="onCommentDeleted",e.OnCommentFlagged="onCommentFlagged",e.OnCommentUnflagged="onCommentUnflagged",e.OnCommentReactionAdded="onCommentReactionAdded",e.OnCommentReactionRemoved="onCommentReactionRemoved"}(Al||(Al={}));class El extends Is{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:e.comments.map(de("comment"))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(o=null==t?void 0:t.data)&&void 0!==o?o:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.comments.map(de("comment"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;this.query.referenceId===t.referenceId&&this.query.referenceType===t.referenceType&&r&&(this.query.parentId&&this.query.parentId!==t.parentId||!this.query.parentId&&t.parentId||(e===Al.OnCommentCreated&&(r.data=[...new Set([t.commentId,...r.data])]),_e(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Ml=e=>ti("local.comment.created",e);class Pl extends ks{constructor(e,t){const n=w.default(e),r=["comments","collection",n];super(new Tl(e),n,r,t),this.query=e,this.queryStreamController=new El(this.query,this.cacheKey,this.notifyChange.bind(this),pi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Ml,action:Al.OnCommentCreated},{fn:_l,action:Al.OnCommentDeleted},{fn:ni,action:Al.OnCommentCreated},{fn:ri,action:Al.OnCommentUpdated},{fn:oi,action:Al.OnCommentDeleted},{fn:si,action:Al.OnCommentFlagged},{fn:ai,action:Al.OnCommentUnflagged},{fn:ii,action:Al.OnCommentReactionAdded},{fn:ci,action:Al.OnCommentReactionRemoved},{fn:kl,action:Al.OnCommentReactionAdded},{fn:Ol,action:Al.OnCommentReactionRemoved}])}notifyChange({origin:e,loading:t,error:n}){var r,o;const s=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const a=this.applyFilter(null!==(o=s.data.map((e=>Se(["comment","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==o?o:[]).map(wn.comment);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;if(this.query.includeDeleted||(t=Ae(t,"isDeleted",!1)),this.query.parentId&&(t=t.filter((e=>e.parentId===this.query.parentId))),"boolean"==typeof this.query.hasFlag&&(t=this.query.hasFlag?t.filter((e=>null!=e.hashFlag)):t.filter((e=>null==e.hashFlag))),this.query.dataTypes&&("exact"===this.query.dataTypes.matchType&&(t=t.filter((e=>{var t,n;const r=(null===(t=this.query.dataTypes)||void 0===t?void 0:t.values.sort())||[],o=(null===(n=e.dataTypes)||void 0===n?void 0:n.sort())||[];return o.length===r.length&&r.every(((e,t)=>e===o[t]))}))),"any"===this.query.dataTypes.matchType&&(t=t.filter((e=>{var t;return null===(t=this.query.dataTypes)||void 0===t?void 0:t.values.some((t=>{var n;return null===(n=e.dataTypes)||void 0===n?void 0:n.includes(t)}))})))),"firstCreated"===this.query.sortBy)t=t.sort(Be);else t=t.sort(Fe);return t}}var Rl=Object.freeze({__proto__:null,getCommentByIds:bl,createComment:async e=>{var t;const n=we();n.log("comment/createComment",e);const{data:r}=await n.http.post("/api/v3/comments",e),{comments:o}=r;if(0===o.length)throw new Error("Comment not created");const s=n.cache&&Date.now();if(n.cache&&Kt(r,{cachedAt:s}),["post","content"].includes(e.referenceType)){const n=null===(t=Se(["post","get",e.referenceId]))||void 0===t?void 0:t.data;n&&(n.commentsCount+=1,Xe("local.post.updated",{posts:[n],categories:[],comments:[],communities:[],communityUsers:r.communityUsers,feeds:[],files:r.files,postChildren:[],users:r.users,videoStreamings:[]}))}else if("story"===e.referenceType){const t=Se(["story-reference",e.referenceId]);if(null==t?void 0:t.data){const e=Se(["story","get",t.data]);(null==e?void 0:e.data)&&Xe("story.updated",{stories:[Object.assign(Object.assign({},e.data),{commentsCount:e.data.commentsCount+1,comments:[...new Set([...e.data.comments,o[0].commentId])]})],categories:[],comments:o,communities:[],communityUsers:r.communityUsers,files:r.files,users:r.users})}}return Xe("local.comment.created",r),{data:wn.comment(o[0]),cachedAt:s}},updateComment:async(e,t)=>{const n=we();n.log("user/updateComment",t);const{data:r}=await n.http.put(`/api/v3/comments/${encodeURIComponent(e)}`,t),o=n.cache&&Date.now();n.cache&&Kt(r,{cachedAt:o}),Xe("comment.updated",r);const{comments:s}=r;return{data:wn.comment(s.find((t=>t.commentId===e))),cachedAt:o}},deleteComment:Il,softDeleteComment:async e=>{we().log("comment/softDeleteComment",e);return Il(e)},hardDeleteComment:async e=>{we().log("comment/hardDeleteComment",e);return Il(e,!0)},flagComment:async e=>{const t=we();t.log("comment/flagComment",e);const{data:n}=await t.http.post(`/api/v3/comments/${encodeURIComponent(e)}/flag`);return t.cache&&Kt(n),Xe("comment.flagged",n),!!n},unflagComment:async e=>{const t=we();t.log("comment/unflagComment",e);const{data:n}=await t.http.delete(`/api/v3/comments/${encodeURIComponent(e)}/unflag`);return t.cache&&Kt(n),Xe("comment.unflagged",n),!!n},isCommentFlaggedByMe:async e=>{const t=we();t.log("comment/isCommentFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/comments/${e}/isflagbyme`);return n},onCommentCreated:ni,onCommentUpdated:ri,onCommentDeleted:oi,onCommentFlagged:si,onCommentUnflagged:ai,onCommentReactionAdded:ii,onCommentReactionRemoved:ci,observeComments:(e,t)=>{const{log:n}=we(),r=Date.now();n(`observeComments(tmpid: ${r}) > listen`);const o=[],s=(n,r)=>{var o,s;if(n.referenceId===e){if(t instanceof Function)return t(n);null===(o=t.onEvent)||void 0===o||o.call(t,r,n),null===(s=t[r])||void 0===s||s.call(t,n)}};return o.push(ni((e=>s(e,"onCreate"))),ri((e=>s(e,"onUpdate"))),oi((e=>s(e,"onDelete"))),si((e=>s(e,"onFlagged"))),ai((e=>s(e,"onUnflagged"))),ii((e=>s(e,"onReactionAdded"))),ci((e=>s(e,"onReactionRemoved")))),()=>{n(`observeComments(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},observeComment:(e,t,n="cache_then_server")=>{const{log:r}=we(),o=Date.now();r(`observeComment(tmpid: ${o}) > listen`);const s=(e,n)=>{var r,o;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(o=t[n])||void 0===o||o.call(t,e)},a=(t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.commentId)===e&&s(t,n)},i=[];return i.push(ri((e=>a({data:e,loading:!1,origin:"event"},"onUpdate"))),oi((e=>a({data:e,loading:!1,origin:"event"},"onDelete"))),si((e=>a({data:e,loading:!1,origin:"event"},"onFlagged"))),ai((e=>a({data:e,loading:!1,origin:"event"},"onUnflagged"))),ii((e=>a({data:e,loading:!1,origin:"event"},"onReactionAdded"))),ci((e=>a({data:e,loading:!1,origin:"event"},"onReactionRemoved")))),ie(se(Sl,e),(e=>(e.data||e.error)&&s(e,"onFetch")),ae(n)),()=>{r(`observeComment(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getComment:(e,t)=>gs(e,t,"commentId",Sl,[_l,oi,si,ii,ci,ai,ri,kl,Ol]),getComments:(e,t,n)=>{const{log:r,cache:o}=we();o||console.log("For using Live Collection feature you need to enable Cache!");const s=Date.now();r(`getComments(tmpid: ${s}) > listen`);const a=new Pl(e,t),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>Te(c))),()=>{r(`getComments(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}}});const Ul=e=>za("local.post.updated",e),jl=e=>{const t=we();return Ze(t,"local.post.addReaction","local.post.addReaction",(({post:n})=>{t.cache?(Oe(["post","get",n.postId],n),e(n)):e(n)}))},xl=e=>{const t=we();return Ze(t,"local.post.removeReaction","local.post.removeReaction",(({post:n})=>{t.cache?(Oe(["post","get",n.postId],n),e(n)):e(n)}))},Dl=e=>za("local.post.deleted",e);class Nl extends ws{async getRequest(e,t){const{limit:n=j,includeDeleted:r,matchingOnlyParentPost:o}=e,s=zt(e,["limit","includeDeleted","matchingOnlyParentPost"]),{dataTypes:a}=s,i={type:s.sortBy||e.limit?"pagination":void 0},c=t?Object.assign(Object.assign({},i),{token:t}):Object.assign(Object.assign({},i),{limit:n}),{data:l}=await this.http.get("/api/v4/posts",{params:Object.assign(Object.assign({},s),{isDeleted:zn(r),matchingOnlyParentPost:null!=o?o:!(null==a?void 0:a.length),options:c})});return l}}var Bl;!function(e){e.OnPostCreated="onPostCreated",e.OnPostUpdated="onPostUpdated",e.OnPostDeleted="onPostDeleted",e.OnPostFlagged="onPostFlagged",e.OnPostUnflagged="onPostUnflagged",e.OnPostReactionAdded="onPostReactionAdded",e.OnPostReactionRemoved="onPostReactionRemoved",e.OnPostApproved="onPostApproved",e.OnPostDeclined="onPostDeclined"}(Bl||(Bl={}));class ql extends Is{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:e.posts.map(de("post"))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(o=null==t?void 0:t.data)&&void 0!==o?o:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(de("post"))])]}))}}reactor(e){return t=>{var n,r;const o=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;if(o){if(t.parentPostId&&t.isDeleted){const e=null===(r=Se(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e||(null==e?void 0:e.targetId)!==this.query.targetId)return;e.children=e.children.filter((e=>e!==t.postId)),_e(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===Bl.OnPostDeclined&&(o.data=o.data.filter((e=>e!==t.postId))),e!==Bl.OnPostCreated&&e!==Bl.OnPostApproved||(o.data=[...new Set([t.postId,...o.data])]),_e(this.cacheKey,o),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Fl=async e=>{const t=we();let n;t.log("post/getPost",e),lr("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw V(null==t?void 0:t.code)&&$t("post",e),t}const r=Vt(n,"communityUsers"),o=t.cache&&Date.now();t.cache&&Kt(r,{cachedAt:o});const{posts:s}=r;return{data:s.find((t=>t.postId===e)),cachedAt:o}};Fl.locally=e=>{const t=we();if(t.log("post/getPost.locally",e),!t.cache)return;const n=Se(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class Ll extends ks{constructor(e,t){const n=w.default(e),r=["posts","collection",n];super(new Nl(e),n,r,t),this.query=e,this.queryStreamController=new ql(this.query,this.cacheKey,this.notifyChange.bind(this),La),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Qa,action:Bl.OnPostCreated},{fn:Va,action:Bl.OnPostUpdated},{fn:Ul,action:Bl.OnPostUpdated},{fn:Ha,action:Bl.OnPostDeleted},{fn:Ga,action:Bl.OnPostFlagged},{fn:Ya,action:Bl.OnPostUnflagged},{fn:Wa,action:Bl.OnPostApproved},{fn:Ja,action:Bl.OnPostDeclined},{fn:Za,action:Bl.OnPostReactionAdded},{fn:Xa,action:Bl.OnPostReactionRemoved},{fn:jl,action:Bl.OnPostReactionAdded},{fn:xl,action:Bl.OnPostReactionRemoved},{fn:Dl,action:Bl.OnPostDeleted},{fn:gi((e=>ni((async t=>{var n;const r=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await Fl(t.referenceId),e(t))}))),"referenceId","post"),action:Bl.OnPostUpdated},{fn:gi((e=>oi((async t=>{var n;const r=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await Fl(t.referenceId),e(t))}))),"referenceId","post"),action:Bl.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,o;const s=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const a=this.applyFilter(null!==(o=s.data.map((e=>Se(["post","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==o?o:[]).map(wn.post);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=e;if(this.query.includeDeleted||(n=Ae(n,"isDeleted",!1)),this.query.tags&&(n=n.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)}))}))),"community"===this.query.targetType&&this.query.feedType&&(n=Re(n,this.query.feedType)),(null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=je(n,this.query.dataTypes)),"firstCreated"===this.query.sortBy)n=n.sort(Be);else n=n.sort(Fe);return n}}class Kl extends ws{async getRequest(e,t){const n=zt(e,["limit"]),{communityId:r,placement:o}=n,s=o?`/api/v1/pinned-posts/communities/${r}/${o}`:`/api/v1/pinned-posts/communities/${r}`,{data:a}=await this.http.get(s);return a}}class $l extends Is{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=we(),n=t.cache&&Date.now();t.cache&&Kt(e,{cachedAt:n})}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:e.pins.map(de("pin"))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(o=null==t?void 0:t.data)&&void 0!==o?o:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(de("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}}class zl extends ks{constructor(e,t){const n=w.default(e),r=["pinnedPosts","collection",n];super(new Kl(e),n,r,t),this.query=e,this.queryStreamController=new $l(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return[]}notifyChange({origin:e,loading:t,error:n}){var r,o;const s=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;let a=(null!==(o=s.data.map((e=>Se(["pin","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==o?o:[]).map(wn.pinnedPost);a=this.applyFilter(a),(this.shouldNotify(a)||"event"!==e)&&this.callback({data:a,loading:t,error:n})}applyFilter(e){let t=e;if("lastCreated"===this.query.sortBy)t=t.sort((({post:e},{post:t})=>Fe({createdAt:null==e?void 0:e.createdAt},{createdAt:null==t?void 0:t.createdAt})));return t}}class Ql extends ws{async getRequest(e,t){const{limit:n=j}=e,r=zt(e,["limit"]),o={type:e.limit?"pagination":void 0},s=t?Object.assign(Object.assign({},o),{token:t}):Object.assign(Object.assign({},o),{limit:n}),{data:a}=await this.http.get("/api/v1/semantic-search/posts",{params:Object.assign(Object.assign({},r),{options:s})});return a}}function Vl(e){return e.posts.map((t=>{const n=e.searchResult.find((e=>e.postId===t.postId));return`${t.postId}:${n.score}`}))}function Hl(e){return(null!=e?e:[]).map((e=>e.split(":")[0]))}class Wl extends Is{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:Vl(e)});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(o=null==t?void 0:t.data)&&void 0!==o?o:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...Vl(e)])]}))}}reactor(e){return t=>{var n,r;const o=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;if(o){if(t.parentPostId&&t.isDeleted){const e=null===(r=Se(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e||(null==e?void 0:e.targetId)!==this.query.targetId)return;e.children=e.children.filter((e=>e!==t.postId)),_e(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===Bl.OnPostDeclined&&(o.data=o.data.filter((e=>e!==t.postId))),e!==Bl.OnPostCreated&&e!==Bl.OnPostApproved||(o.data=[...new Set([t.postId,...o.data])]),_e(this.cacheKey,o),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Jl extends ks{constructor(e,t){const n=Object.assign(Object.assign({},e),{matchingOnlyParentPost:null==e.matchingOnlyParentPost||e.matchingOnlyParentPost,dataTypes:null==e.dataTypes?["text","image"]:e.dataTypes}),r=w.default(n),o=["posts","collection",r];super(new Ql(n),r,o,t),this.query=n,this.queryStreamController=new Wl(this.query,this.cacheKey,this.notifyChange.bind(this),Ka),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Va,action:Bl.OnPostUpdated},{fn:Ha,action:Bl.OnPostDeleted},{fn:Ga,action:Bl.OnPostFlagged},{fn:Ya,action:Bl.OnPostUnflagged},{fn:Wa,action:Bl.OnPostApproved},{fn:Ja,action:Bl.OnPostDeclined},{fn:Za,action:Bl.OnPostReactionAdded},{fn:Xa,action:Bl.OnPostReactionRemoved},{fn:gi((e=>ni((async t=>{const n=Se(this.cacheKey);Hl(null==n?void 0:n.data).includes(t.referenceId)||(await Oa(t.referenceId),e(t))}))),"referenceId","post"),action:Bl.OnPostUpdated},{fn:gi((e=>oi((async t=>{const n=Se(this.cacheKey);Hl(null==n?void 0:n.data).includes(t.referenceId)||(await Oa(t.referenceId),e(t))}))),"referenceId","post"),action:Bl.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,o;const s=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const a=this.applyFilter(null!==(o=s.data.map((e=>{const[t,n]=e.split(":");return{postId:t,score:parseFloat(n)}})).sort(((e,t)=>t.score-e.score)).map((({postId:e})=>Se(["post","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==o?o:[]).map(wn.post);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.targetType&&(t=t.filter((e=>e.targetType===this.query.targetType))),this.query.targetId&&(t=t.filter((e=>e.targetId===this.query.targetId))),this.query.dataTypes&&this.query.dataTypes.length>0&&(t=je(t,this.query.dataTypes)),t}}var Gl=Object.freeze({__proto__:null,getPostByIds:yl,createPost:async e=>{const t=we();t.log("post/createPost",e),e.dataType&&!["text","image","file","video"].includes(e.dataType)||delete e.dataType;const{data:n}=await t.http.post("/api/v4/posts",e);Xe("post.created",n);const r=Vt(n,"communityUsers"),o=t.cache&&Date.now();t.cache&&Kt(r,{cachedAt:o});const{posts:s}=r;return{data:wn.post(s[0]),cachedAt:o}},updatePost:async(e,t)=>{const n=we();n.log("user/updatePost",t),console.warn("Deprecation: updatePost has been renamed to editPost. Update post API will be deprecated soon.");const{data:r}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,t),o=Vt(r,"communityUsers"),s=n.cache&&Date.now();n.cache&&Kt(o,{cachedAt:s}),Xe("local.post.updated",r);const{posts:a}=o;return{data:wn.post(a.find((t=>t.postId===e))),cachedAt:s}},editPost:async(e,t)=>{const n=we();n.log("user/editPost",t);const{data:r}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,t),o=Vt(r,"communityUsers"),s=n.cache&&Date.now();n.cache&&Kt(o,{cachedAt:s}),Xe("local.post.updated",o);const{posts:a}=o;return{data:wn.post(a.find((t=>t.postId===e))),cachedAt:s}},deletePost:vl,softDeletePost:async e=>{we().log("post/softDeletePost",e);const t=await vl(e,!1);return wn.post(t)},hardDeletePost:async e=>{we().log("post/hardDeletePost",e);const t=await vl(e,!0);return wn.post(t)},approvePost:async e=>{const t=we();t.log("post/approvePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/approve`);Xe("post.approved",n),"community"===n.posts[0].targetType&&Xe("community.updated",n);const r=Vt(n,"communityUsers"),o=t.cache&&Date.now();return t.cache&&Kt(r,{cachedAt:o}),{data:wn.post(r.posts.find((t=>t.postId===e))),cachedAt:o}},declinePost:async e=>{const t=we();t.log("post/declinePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/decline`);"community"===n.posts[0].targetType&&Xe("community.updated",n),Xe("post.declined",n);const r=Vt(n,"communityUsers"),o=t.cache&&Date.now();return t.cache&&Kt(r,{cachedAt:o}),{data:wn.post(n.posts.find((t=>t.postId===e))),cachedAt:o}},flagPost:async e=>{const t=we();t.log("post/flagPost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/flag`);return t.cache&&Kt(Vt(n,"communityUsers")),Xe("post.flagged",n),!!n},unflagPost:async e=>{const t=we();t.log("post/unflagPost",e);const{data:n}=await t.http.delete(`/api/v3/posts/${encodeURIComponent(e)}/unflag`);return t.cache&&Kt(Vt(n,"communityUsers")),Xe("post.unflagged",n),!!n},isPostFlaggedByMe:async e=>{const t=we();t.log("post/isPostFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/posts/${e}/isflagbyme`);return n},onPostCreated:Qa,onPostUpdated:Va,onPostDeleted:Ha,onPostApproved:Wa,onPostDeclined:Ja,onPostFlagged:Ga,onPostUnflagged:Ya,onPostReactionAdded:Za,onPostReactionRemoved:Xa,observePosts:(e,t)=>{const{log:n}=we(),r=Date.now();n(`observePosts(tmpid: ${r}) > listen`);const o=[],s=(n,r)=>{var o,s;if(e.targetId===n.targetId&&e.targetType===n.targetType){if(t instanceof Function)return t(wn.post(n));null===(o=t.onEvent)||void 0===o||o.call(t,r,wn.post(n)),null===(s=t[r])||void 0===s||s.call(t,wn.post(n))}};return o.push(Qa((e=>s(e,"onCreate"))),Va((e=>s(e,"onUpdate"))),Ha((e=>s(e,"onDelete"))),Wa((e=>s(e,"onApproved"))),Ja((e=>s(e,"onDeclined"))),Ga((e=>s(e,"onFlagged"))),Ya((e=>s(e,"onUnflagged"))),Za((e=>s(e,"onReactionAdded"))),Xa((e=>s(e,"onReactionRemoved")))),()=>{n(`observePosts(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},observePost:(e,t,n="cache_then_server")=>{const{log:r}=we(),o=Date.now();r(`observePost(tmpid: ${o}) > listen`);const s=(e,n)=>{var r,o;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(o=t[n])||void 0===o||o.call(t,e)},a=(t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.postId)===e&&s(Object.assign(Object.assign({},t),{data:t.data&&wn.post(t.data)}),n)},i=[];return i.push(Va((e=>a({data:e,loading:!1,origin:"event"},"onUpdate"))),Ha((e=>a({data:e,loading:!1,origin:"event"},"onDelete"))),Wa((e=>a({data:e,loading:!1,origin:"event"},"onApproved"))),Ja((e=>a({data:e,loading:!1,origin:"event"},"onDeclined"))),Ga((e=>a({data:e,loading:!1,origin:"event"},"onFlagged"))),Ya((e=>a({data:e,loading:!1,origin:"event"},"onUnflagged"))),Za((e=>a({data:e,loading:!1,origin:"event"},"onReactionAdded"))),Xa((e=>a({data:e,loading:!1,origin:"event"},"onReactionRemoved")))),ie(se(Oa,e),(e=>(e.data||e.error)&&s(Object.assign(Object.assign({},e),{data:e.data&&wn.post(e.data)}),"onFetch")),ae(n)),()=>{r(`observePosts(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getPost:(e,t)=>gs(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?wn.post(e.data):n}))}),"postId",Oa,[Wa,Ja,jl,xl,t=>Ha((n=>{var r;let o=n;if(n.parentPostId===e&&n.isDeleted){const e=null===(r=Se(["post","get",n.parentPostId]))||void 0===r?void 0:r.data;e&&(e.children=e.children.filter((e=>e!==n.postId)),_e(["post","get",e.postId],e),o=e)}t(o)})),Ga,e=>Za((t=>{e(wn.post(t))})),e=>Xa((t=>{e(wn.post(t))})),Ya,Va,Ul,Dl,gi((t=>ni((async n=>{n.referenceId===e&&(await Oa(e),t(n))}))),"referenceId","post"),gi((t=>oi((async n=>{n.referenceId===e&&(await Oa(e),t(n))}))),"referenceId","post")]),getPosts:(e,t,n)=>{const{log:r,cache:o}=we();o||console.log(D);const s=Date.now();r(`getPosts(tmpid: ${s}) > listen`);const a=new Ll(e,t),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>Te(c))),()=>{r(`getPosts(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getPinnedPosts:(e,t,n)=>{const{log:r,cache:o}=we();o||console.log(D);const s=Date.now();r(`getPinnedPosts(tmpid: ${s}) > listen`);const a=new zl(e,t),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>Te(c))),()=>{r(`getPinnedPosts(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},semanticSearchPosts:(e,t,n)=>{const{log:r,cache:o}=we();o||console.log(D);const s=Date.now();r(`semanticSearchPosts(tmpid: ${s}) > listen`);const a=new Jl(e,t),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>Te(c))),()=>{r(`semanticSearchPosts(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}}});const Yl=async e=>{const t=we();t.log("stream/getStream",e);const{data:n}=await t.http.get(`/api/v3/video-streaming/${e}`),r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const{videoStreamings:o}=n;return{data:o.find((t=>t.streamId===e)),cachedAt:r}};Yl.locally=e=>{const t=we();if(t.log("stream/getStream",e),!t.cache)return;const n=Se(["stream","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Zl=e=>{const t=we();return Ze(t,"stream/onStreamStarted","v3.video-streaming.didStart",(t=>{Kt(t),e(t.videoStreamings[0])}))},Xl=e=>{const t=we();return Ze(t,"stream/onStreamStropped","v3.video-streaming.didStop",(t=>{Kt(t),e(t.videoStreamings[0])}))},ed=e=>{const t=we();return Ze(t,"stream/onStreamRecorded","v3.video-streaming.didRecord",(t=>{Kt(t),e(t.videoStreamings[0])}))},td=e=>{const t=we();return Ze(t,"stream/onStreamFlagged","v3.video-streaming.didFlag",(t=>{Kt(t),e(t.videoStreamings[0])}))},nd=e=>{const t=we();return Ze(t,"stream/onStreamTerminated","v3.video-streaming.didTerminate",(t=>{Kt(t),e(t.videoStreamings[0])}))},rd=(e,t)=>gs(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?wn.stream(e.data):n}))}),"streamId",Yl,[ed,Zl,Xl,td,nd]);rd.locally=e=>{const t=we();if(t.log("stream/getStreamById",e),!t.cache)return;const n=Se(["stream","get",e]);return n?{data:wn.stream(n.data),cachedAt:n.cachedAt}:void 0};const od=async e=>{const t=we();t.log("stream/queryStreams",e);const n=null!=e?e:{},{page:r,limit:o}=n,s=zt(n,["page","limit"]),a=r?{token:r}:o?{limit:o}:void 0,{data:i}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},s),{options:a})}),{paging:c,results:l}=i,{videoStreamings:d}=l,u=t.cache&&Date.now();return t.cache&&Kt(l,{cachedAt:u}),{data:d,cachedAt:u,paging:c}};var sd=Object.freeze({__proto__:null,createStream:async e=>{const t=we();t.log("stream/createStream",e);const{data:n}=await t.http.post("/api/v3/video-streaming",e),r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const{videoStreamings:o}=n;return{data:wn.stream(o[0]),cachedAt:r}},updateStream:async(e,t)=>{const n=we();n.log("stream/updateStream",e,t);const{data:r}=await n.http.put(`/api/v3/video-streaming/${e}`,t),o=n.cache&&Date.now();n.cache&&Kt(r,{cachedAt:o});const{videoStreamings:s}=r;return{data:wn.stream(s.find((t=>t.streamId===e))),cachedAt:o}},deleteStream:async e=>{const t=we();t.log("stream/deleteStream",e);const n=await Yl(e),{data:r}=await t.http.delete(`/api/v3/video-streaming/${e}`),{success:o}=r,s=Object.assign(Object.assign({},n.data),{isDeleted:!0});return Oe(["stream","get",e],s),o},disposeStream:async e=>{const t=we();t.log("stream/disposeStream",e);const{data:n}=await t.http.delete(`/api/v3/video-streaming/${e}/streaming-url`),r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const{videoStreamings:o}=n;return{data:o.find((t=>t.streamId===e)),cachedAt:r}},queryStreams:async e=>{const t=we();t.log("stream/queryStreams",e);const n=null!=e?e:{},{page:r}=n,o=zt(n,["page"]),{data:s}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},o),{options:{token:Y(r,"skiplimit")}})}),{paging:a,results:i}=s,{videoStreamings:c}=i,l=t.cache&&Date.now();t.cache&&Kt(i,{cachedAt:l});const d=Z(a.next);return{data:c,cachedAt:l,prevPage:Z(a.previous),nextPage:d}},getStream:Yl,onStreamStarted:Zl,onStreamStopped:Xl,onStreamRecorded:ed,onStreamFlagged:td,onStreamTerminated:nd,getStreamById:rd,getStreams:(e,t,n)=>{const{log:r,cache:o}=we();o||console.log(D);const s=Date.now();r(`getStreams(tmpid: ${s}) > listen`);const{limit:a}=e,i=zt(e,["limit"]),c=null!=a?a:j,{policy:l=x}=null!=n?n:{},d=[],u=["streams","collection",e],h=t=>{let n=Ae(t,"isDeleted",e.isDeleted);return n=n.sort("lastCreated"===e.sortBy?Fe:Be),n},p=(e,n=!1)=>{var r,o;const s=null!==(r=e.data.map((e=>Se(["stream","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];t({onNextPage:g,data:n?h(s):s,hasNextPage:!!(null===(o=e.params)||void 0===o?void 0:o.page),loading:e.loading,error:e.error})},f=e=>e=>{var t;const n=null===(t=Se(u))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.streamId,...n.data])],_e(u,n),p(n,!0))},g=(e=!1)=>{var t,n;const r=null===(t=Se(u))||void 0===t?void 0:t.data,o=null!==(n=null==r?void 0:r.data)&&void 0!==n?n:[];if(!e&&o.length>0&&!(null==r?void 0:r.params.page))return;const s=se(od,Object.assign(Object.assign({},i),{limit:e?c:void 0,page:e||null==r?void 0:r.params.page}));ie(s,(({data:e,error:t,loading:n,paging:r})=>{const s={loading:n,error:t,params:{page:null==r?void 0:r.next},data:o};e&&(s.data=[...new Set([...o,...e.map(de("stream"))])]),_e(u,s),p(s)}),ae(l))};return d.push(ed(f()),Zl(f()),Xl(f())),g(!0),()=>{r(`getStreams(tmpid: ${s}) > dispose`),d.forEach((e=>e()))}}});const ad=async e=>{const t=we();t.log("poll/getPoll",e);const{data:n}=await t.http.get(`/api/v3/polls/${e}`),r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const{polls:o}=n;return{data:o.find((t=>t.pollId===e)),cachedAt:r}};ad.locally=e=>{const t=we();if(t.log("poll/getPoll",e),!t.cache)return;const n=Se(["poll","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const id=e=>{const t=we();return Ze(t,"poll/onPollUpdated","poll.updated",(n=>{t.cache&&Kt(n),e(n.polls[0])}))},cd=e=>{const t=we();return Ze(t,"poll/onPollDeleted","poll.deleted",(n=>{t.cache&&Kt(n),e(n.polls[0])}))};var ld=Object.freeze({__proto__:null,createPoll:async e=>{const t=we();t.log("post/createPoll",e);const{data:n}=await t.http.post("/api/v3/polls",e),r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const{polls:o}=n;return{data:o[0],cachedAt:r}},closePoll:async e=>{const t=we();t.log("user/closePoll",e);const{data:n}=await t.http.put(`/api/v3/polls/${encodeURIComponent(e)}`,{status:"closed"}),r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r}),Xe("poll.updated",n);const{polls:o}=n;return{data:o.find((t=>t.pollId===e)),cachedAt:r}},deletePoll:async e=>{const t=we();t.log("poll/deletePoll",e);const n=await ad(e),{data:r}=await t.http.delete(`/api/v3/polls/${e}`),{success:o}=r,s=Object.assign(Object.assign({},n.data),{isDeleted:!0});return Oe(["poll","get",e],s),Xe("poll.deleted",{polls:[s],users:[]}),o},votePoll:async(e,t)=>{const n=we();n.log("user/votePoll",e);const{data:r}=await n.http.post(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:t}),o=n.cache&&Date.now();n.cache&&Kt(r,{cachedAt:o});const{polls:s}=r;return Xe("poll.updated",r),{data:s.find((t=>t.pollId===e)),cachedAt:o}},onPollUpdated:id,onPollDeleted:cd,observePoll:(e,t,n="cache_then_server")=>{const{log:r}=we(),o=Date.now();r(`observePoll(tmpid: ${o}) > listen`);const s=(e,n)=>{var r,o;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(o=t[n])||void 0===o||o.call(t,e)},a=(t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.pollId)===e&&s(t,n)},i=[];return i.push(id((e=>a({data:e,loading:!1,origin:"event"},"onUpdate"))),cd((e=>a({data:e,loading:!1,origin:"event"},"onDelete")))),ie(se(ad,e),(e=>(e.data||e.error)&&s(e,"onFetch")),ae(n)),()=>{r(`observePoll(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getPoll:(e,t)=>gs(e,t,"pollId",ad,[id,cd])});const dd={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};function ud(e){const n=new Uint8Array(e);let r="";return n.forEach((e=>{r+=String.fromCharCode(e)})),t.btoa(r)}function hd(e){const n=e.substring("-----BEGIN PRIVATE KEY-----".length,e.length-"-----END PRIVATE KEY-----".length),r=function(e){const t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let t=0,r=e.length;t<r;t+=1)n[t]=e.charCodeAt(t);return t}(t.atob(n));return crypto.subtle.importKey("pkcs8",r,dd,!1,["sign"])}async function pd({bufferCurrentUsage:e,getActiveStreams:t,updateUsage:n,dispose:r}){const o=e();if(o.length)try{const n=(new Date).toISOString(),s=await async function({timestamp:e,streams:t}){const n=t.map((e=>Object.keys(e).sort().map((t=>`${t}=${e[t]}`)).join("&"))).join(";"),r=b.default.v4(),o=`nonceStr=${r}×tamp=${e}&data=${n}==`,s=(new TextEncoder).encode(o),a=await hd("-----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:ud(await crypto.subtle.sign(dd,a,s)),nonceStr:r}}({timestamp:n,streams:o});if(!s||!s.signature)throw new Error("Signature is undefined");const a={signature:s.signature,nonceStr:s.nonceStr,timestamp:n,streams:o},i=we();return await i.http.post("/api/v3/user-event/video-streaming",a),t().length||e().length||r(),!0}catch(e){return o.forEach((e=>n(e))),!1}}class fd{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((()=>{pd({bufferCurrentUsage:this.bufferCurrentUsage.bind(this),getActiveStreams:this.getActiveStreams.bind(this),updateUsage:this.updateUsage.bind(this),dispose:this.dispose.bind(this)})}),2e4)}}let gd=null;class md{constructor(e,t){this.player=e,this.resolution=t,this._startTime=null,this._usageCollector=gd||(gd=new fd,gd),this._usageCollector.registerStream(e.id),this._sessionId=String(b.default.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,n=Math.round(t/1e3);n&&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:n,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 yd=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(!C.default.isSupported())throw new Error("This browswer does not support hls, unable to play stream");const{data:n}=await Yl(t),{watcherUrl:r,status:o,recordings:s=[],resolution:a}=n;if(!r.hls)throw new Error("This stream does not support hls. Unable to play");const i=document.createElement("video");i.id=t,i.controls=!0;const c=new C.default;if(c.attachMedia(i),"recorded"!==o){let{url:e}=r.hls;e=e.replace("http:","https:"),c.loadSource(e)}else{const e=s.find((e=>!!e.mp4));if(!e||!e.mp4)throw new Error("No playable recording available");i.src=e.mp4.url}return new md(i,a).registerEvents(),i}});const vd=e=>{const t=(e=>{var t;const n=we(),r=new Date,o=r.getTime()+31536e6,s=new Date(o).toISOString();let a=null===(t=Se(["storyTarget","get",e.targetId]))||void 0===t?void 0:t.data;return a||(a={targetType:e.targetType,targetId:e.targetId,lastStoryExpiresAt:s,targetPublicId:e.targetId,targetUpdatedAt:r.toISOString()},Kt({storyTargets:[a]})),{stories:[Object.assign({createdAt:r.toISOString(),updatedAt:r.toISOString(),flagCount:0,hashFlag:null,reactions:{},reactionsCount:0,storyId:e.referenceId,path:"",creatorId:n.userId||"",creatorPublicId:n.userId||"",targetPublicId:e.targetId,comments:[],commentsCount:0,isDeleted:!1,hasFlaggedComment:!1,mentionedUsers:[],impression:0,reach:0,expiresAt:new Date(o).toISOString()},e)],categories:[],communityUsers:[],comments:[],files:[],users:[],communities:[]}})(e);return Kt(t),t},bd=({payload:e,formData:t,isVideo:n=!1},r)=>{if(t){const o=t.getAll("files")[0]||void 0;if(!o)return;const s=Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileId:void 0,fileData:o.uri})});return n&&(s.data.videoFileId={original:void 0}),r(vd(s))}return r(vd(Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileData:null})})))},wd=async e=>{const t=we();t.log("post/createStory",e);const n=await t.http.post("/api/v4/stories",e),r=wl(n.data);t.cache&&Kt(r),_e(["story-sync-state",e.targetId],"synced"),Xe("local.story.created",r);const o=t.cache&&Date.now();return{data:r.stories.length>0?r.stories[0]:void 0,cachedAt:o}},Cd=e=>e?Se(["story","get",e]):{data:void 0,cachedAt:void 0},Id=async(e,t=!1)=>{const n=we();let r;if(n.log("story/deleteStory",e),n.cache&&(r=Cd(e),null==r?void 0:r.data)){const{data:e}=r;Xe("local.story.deleted",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[Object.assign(Object.assign({},e),{isDeleted:!0})]})}return(await n.http.delete(`/api/v4/stories/${e}`,{params:{permanent:t}})).data.success},Sd=e=>{const t=we(),n=[Ze(t,"onStoryUpdated","story.updated",(async t=>{const n=wl(t);Kt(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},_d=e=>{const t=we(),n=[Ze(t,"onStoryUpdated","local.story.updated",(async t=>{Kt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},kd=e=>{const t=we(),n=[Ze(t,"onStoryReactionAdded","story.reactionAdded",(async t=>{const{reactions:n}=t,r=zt(t,["reactions"]),o=wl(r),s=Ua("story.reactionAdded",Object.assign(Object.assign({},o),{reactions:n}));Kt(s),e(s.stories)}))];return()=>{n.forEach((e=>e()))}},Od=e=>{const t=we(),n=[Ze(t,"onStoryReactionAdded","local.story.reactionAdded",(async t=>{Kt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},Td=e=>{const t=we(),n=[Ze(t,"onStoryReactionRemoved","story.reactionRemoved",(async t=>{const{reactions:n}=t,r=zt(t,["reactions"]),o=wl(r),s=Ua("story.reactionRemoved",Object.assign(Object.assign({},o),{reactions:n}));Kt(s),e(s.stories)}))];return()=>{n.forEach((e=>e()))}},Ad=e=>{const t=we(),n=[Ze(t,"onStoryReactionRemoved","local.story.reactionRemoved",(async t=>{Kt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},Ed=e=>{e.forEach((e=>{const t=Se(["story-expire",e.targetId]),n=new Date(e.expiresAt||0);n<new Date((null==t?void 0:t.data)||0)||_e(["story-expire",e.targetId],n.toISOString())}))},Md=e=>{e.forEach((e=>{_e(["story-reference",e.storyId],e.referenceId)}))},Pd=async({targetType:e,targetId:t,options:n})=>{const r=we();r.log("story/getActiveStoriesByTarget");const o=r.cache&&Date.now(),s=await r.http.get("/api/v4/stories",{params:{targetType:e,targetId:t,options:{sortBy:(null==n?void 0:n.sortBy)||"createdAt",orderBy:(null==n?void 0:n.orderBy)||"desc"}}}),a=wl(s.data);return r.cache&&(Kt(a),Ed(a.stories),Md(a.stories)),{data:a.stories,cachedAt:o,paging:{next:void 0,previous:void 0}}},Rd=e=>{const t=we(),n=[Ze(t,"onStoryCreated","story.created",(async t=>{const n=wl(t,!0);Kt(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Ud=e=>{const t=we(),n=[Ze(t,"onStoryCreated","local.story.created",(async t=>{Kt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},jd=e=>{const t=we(),n=[Ze(t,"onStoryDeleted","story.deleted",(async t=>{const n=wl(t);Kt(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},xd=e=>{const t=we(),n=[Ze(t,"onStoryDeleted","local.story.deleted",(async t=>{Kt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},Dd=e=>{const t=we();return Ze(t,"onStoryError","local.story.error",(async t=>{Kt(t),e(t.stories)}))},Nd=e=>t=>e((e=>t(e[0]))),Bd=async e=>{const t=we();t.log("story/getTargetsByTargetIds",e);const n=await t.http.get("/api/v4/stories/seen",{params:{targets:e}}),{data:r}=n;return t.cache&&Kt(n.data),{data:r.storyTargets,cachedAt:Date.now()}};class qd extends Is{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.paginationController=r}saveToMainDB(e){const t=we(),n=t.cache&&Date.now(),r=wl(e);t.cache&&(Kt(r,{cachedAt:n}),Ed(r.stories),Md(r.stories))}getStoryReferenceIds(e){return(null==e?void 0:e.referenceId)?e.referenceId:e.storyId}appendToQueryStream(e,t,n=!1){var r,o;if(n)_e(this.cacheKey,{data:e.stories.map(this.getStoryReferenceIds)});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(o=null==t?void 0:t.data)&&void 0!==o?o:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.stories.map(this.getStoryReferenceIds)])]}))}}reactor(e){return e=>{var t;const n=null===(t=Se(this.cacheKey))||void 0===t?void 0:t.data;if(!n)return;const r=e.map((({referenceId:e})=>e));n.data=[...new Set([...r,...n.data])],_e(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Fd extends _s{async getRequest(e){const{data:t}=await this.http.get("/api/v4/stories-by-targets",{params:Object.assign({},e)});return t}}class Ld extends ks{constructor(e,t){const n=w.default(e),r=["story-target-ids","collection",n],o=new Fd(e);super(o,n,r,t),this.query=e,this.queryStreamController=new qd(this.query,this.cacheKey,this.notifyChange.bind(this),o),this.paginationController=o,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}persistModel(e){this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}notifyChange({origin:e,loading:t,error:n}){var r;const o=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;let s=o.data.map((e=>Se(["story","get",e]))).filter(Boolean).map((e=>wn.story(e.data)));(this.shouldNotify(s)||"event"!==e)&&(s=this.applyFilter(s),this.callback({onNextPage:void 0,data:s,hasNextPage:!1,loading:t,error:n}))}applyFilter(e){var t,n;const r=e;return"asc"===((null===(n=null===(t=this.query)||void 0===t?void 0:t.options)||void 0===n?void 0:n.orderBy)||"desc")?r.sort(Be):r.sort(Fe)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Rd,action:"onCreate"},{fn:Sd,action:"onUpdate"},{fn:jd,action:"onDelete"},{fn:Dd,action:"onError"}])}}const Kd=(e,t)=>{var n,r;const o=null===(n=Se(e))||void 0===n?void 0:n.data,s=null!==(r=null==o?void 0:o.data)&&void 0!==r?r:[];_e(e,Object.assign(Object.assign({},o),{data:[...new Set([...s,...t])]}))};class $d extends Is{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.paginationController=r,this.preparePayload=e=>e}saveToMainDB(e){const t=we(),n=t.cache&&Date.now(),r=this.preparePayload(e);t.cache&&Kt(r,{cachedAt:n})}appendToQueryStream(e,t,n=!1){n?_e(this.cacheKey,{data:e.storyTargets.map((({targetId:e})=>e))}):Kd(this.cacheKey,e.storyTargets.map((({targetId:e})=>e)))}reactor(e){return t=>{"onCreate"===e&&"seen"!==this.query.seenState&&Kd(this.cacheKey,t.map((({targetId:e})=>e))),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class zd extends ws{constructor(){super(...arguments),this.smartFilterState="unseen"}async getRequest(e,t){var n;const{limit:r=10,seenState:o="unseen"}=e,s=await this.createRequest({seenState:"smart"===o?this.smartFilterState:o,limit:r,token:t});if(null===(n=s.paging)||void 0===n?void 0:n.next)return s;if("smart"!==o)return s;if("seen"===this.smartFilterState)return s;this.smartFilterState="seen";const a=await this.createRequest({seenState:this.smartFilterState,limit:r});return c=a,{categories:(i=s).categories.concat(c.categories),communities:i.communities.concat(c.communities),communityUsers:i.communityUsers.concat(c.communityUsers),files:i.files.concat(c.files),storyTargets:i.storyTargets.concat(c.storyTargets),users:i.users.concat(c.users),paging:c.paging};var i,c}async createRequest(e){const{data:t}=await this.http.get("/api/v5/me/global-story-targets",{params:e});return n=t,r=e.seenState,Object.assign(Object.assign({},n),{storyTargets:n.storyTargets.map((e=>Object.assign(Object.assign({},e),{localFilter:r})))||[]});var n,r}}class Qd extends ks{constructor(e,t){const n=w.default(e),r=["story-global-feed","collection",n],o=new zd(e);super(o,n,r,t),this.query=e,this.queryStreamController=new $d(this.query,this.cacheKey,this.notifyChange.bind(this),o),this.paginationController=o,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}persistModel(e){this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}notifyChange({origin:e,loading:t,error:n}){var r;const o=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;let s=o.data.map((e=>Se(["storyTarget","get",e]))).filter(Boolean).map((e=>wn.storyTarget(e.data)));(this.shouldNotify(s)||"event"!==e)&&(s=this.applyFilter(s).map((e=>zt(e,["localFilter","localLastExpires","localLastSeen","localSortingDate"]))),this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n}))}applyFilter(e){if("smart"!==this.query.seenState)return e.filter((({hasUnseen:e})=>"all"===this.query.seenState||("seen"===this.query.seenState&&!e||"unseen"===this.query.seenState&&e))).sort(qe);const t=e.reduce(((e,t)=>("unseen"===t.localFilter?e.unseen.push(t):"seen"===t.localFilter?e.seen.push(t):e.unknown.push(t),e)),{unseen:[],seen:[],unknown:[]}),n=t.unknown.sort(qe)||[],r=t.unseen.sort(qe)||[],o=t.seen.sort(qe)||[];return n.concat(r,o)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Rd,action:"onCreate"},{fn:Sd,action:"onUpdate"},{fn:jd,action:"onDelete"},{fn:Ud,action:"onCreate"},{fn:_d,action:"onUpdate"},{fn:xd,action:"onDelete"},{fn:Dd,action:"onError"}])}}var Vd=Object.freeze({__proto__:null,createImageStory:async(e,t,n,r={},o="fit",s=[])=>{if(!n.getAll("files").length)throw new Error("The formData object must have a `files` key.");let a={data:{text:"",fileId:void 0,fileData:null,imageDisplayMode:o},syncState:"syncing",referenceId:xt(),dataType:"image",items:s,targetType:e,targetId:t,metadata:r};const i=new Date;_e(["story-sync-state",t],"syncing"),_e(["story-expire",t],new Date(i.setFullYear(i.getFullYear()+1))),bd({payload:a,formData:n},(e=>{Xe("local.story.created",e)}));try{const{data:e}=await wa(n);if(0===e.length)throw new Error("Failed to upload image");const{fileId:t}=e[0];a=Object.assign(Object.assign({},a),{data:Object.assign(Object.assign({},a.data),{fileId:t})}),bd({payload:a,formData:n},(e=>{Xe("local.story.created",e)}));const r=await wd(a);return r.data?Object.assign(Object.assign({},r),{data:wn.story(r.data)}):r}catch(e){throw _e(["story-sync-state",t],"error"),bd({payload:Object.assign(Object.assign({},a),{syncState:"error"}),formData:n},(e=>{Xe("local.story.error",e)})),e}},createVideoStory:async(e,t,n,r={},o=[])=>{if(!n.getAll("files").length)throw new Error("The formData object must have a `files` key.");let s={data:{text:"",fileId:void 0,fileData:null},syncState:"syncing",referenceId:xt(),dataType:"video",items:o,targetType:e,targetId:t,metadata:r};const a=new Date;_e(["story-sync-state",t],"syncing"),_e(["story-expire",t],new Date(a.setFullYear(a.getFullYear()+1))),bd({payload:s,formData:n,isVideo:!0},(e=>{Xe("local.story.created",e)}));try{const{data:e}=await ba(n,M.STORY);if(0===e.length)throw new Error("Failed to upload video");const{fileId:t}=e[0];s=Object.assign(Object.assign({},s),{data:Object.assign(Object.assign({},s.data),{fileId:t,videoFileId:{original:t}})}),bd({payload:s,formData:n,isVideo:!0},(e=>{Xe("local.story.created",e)}));const r=await wd(s);return r.data?Object.assign(Object.assign({},r),{data:wn.story(r.data)}):r}catch(e){throw _e(["story-sync-state",t],"error"),bd({payload:Object.assign(Object.assign({},s),{syncState:"error"}),formData:n,isVideo:!0},(e=>{Xe("local.story.error",e)})),e}},hardDeleteStory:async e=>await Id(e,!0),softDeleteStory:async e=>await Id(e),getActiveStoriesByTarget:(e,t)=>{const{log:n,cache:r}=we(),o=[],s=["story-target","collection",e],a=Date.now();n(`getActiveStoriesByTarget(tmpid: ${a}) > listen`),r||console.log(D);const i=t=>{var n,r;const o=(null===(n=e.options)||void 0===n?void 0:n.sortBy)||"createdAt",s=(null===(r=e.options)||void 0===r?void 0:r.orderBy)||"desc";return 0===t.length?[]:"createdAt"===o?"asc"===s?t.sort(Be):t.sort(Fe):"asc"===s?t.sort(Le):t.sort(Ke)},c=e=>{var n;const r=e.data.map((e=>{const t=Cd(e);if(null==t?void 0:t.data)return wn.story(t.data)})).filter(Boolean).filter((e=>!!e&&!e.isDeleted)),o=[];if(r.length>0){const e=r.reduce(((e,t)=>{if(!t)return e;const{syncState:n}=t;if(!n)return e;let r=e.get(n);return r||(r=[]),r.push(t),e.set(n,r),e}),new Map);if(e.has("error")){const t=i(e.get("error")||[]);o.push(...t)}if(e.has("syncing")){const t=i(e.get("syncing")||[]);o.push(...t)}if(e.has("synced")){const t=i(e.get("synced")||[]);o.push(...t)}}t({onNextPage:()=>!1,data:o||r,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading||!1})},l=(e,t,n=!1,r=!1,o=!1)=>{const a=Se(s),i={loading:r,error:o,params:{page:void 0},data:(null==a?void 0:a.data)||[]};if(e)if("onDelete"===t){const t=e.map((({referenceId:e})=>e));i.data=i.data.filter((e=>!t.includes(e)))||[]}else i.data=n?e.map(de("story")):[...new Set([...i.data,...e.map(de("story"))])];_e(s,i.data),c(i)},d=e=>t=>{l(t,e)};return(t=>{const n=se(Pd,e);ie(n,(({data:e,error:n,loading:r})=>{l(e,"fetch",t,r,n)}))})(!0),o.push(Rd(d("onCreate")),Sd(d("onUpdate")),jd(d("onDelete")),kd(d("onReactionAdded")),Td(d("onReactionRemoved")),Dd(d("onError")),Ud(d("onCreate")),_d(d("onUpdate")),xd(d("onDelete")),Od(d("onReactionAdded")),Ad(d("onReactionRemoved")),(e=>{const t=we();return Ze(t,"onStoryLocalDataUpdated","local.story.reload",(t=>{e(t)}))})((e=>{const t=Se(s);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 n={loading:!1,error:!1,params:{page:void 0},data:(null==t?void 0:t.data)||[]};c(n)})),(()=>Te(s))),()=>{n(`getActiveStoriesByTarget(tmpid: ${a}) > dispose`),o.forEach((e=>e()))}},getStoryByStoryId:(e,t)=>gs(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:wn.story(e.data)})):t(e)}),"storyId",Cl,[Nd(Sd),Nd(jd),Nd(kd),Nd(Td),Nd(Dd),Nd(_d),Nd(xd),Nd(Od),Nd(Ad)]),getTargetById:(e,t)=>gs(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:wn.storyTarget(e.data[0])})):t(e)}),"query",(e=>Bd([e])),[]),getTargetsByTargetIds:(e,t)=>{const{log:n,cache:r}=we(),o=[],s=["storyTargets","collection",e],a=Date.now();n(`getTargetsByTargetIds(tmpid: ${a}) > listen`),r||console.log(D);const i=(e,n=!1,r=!1,o=!1)=>{const a=Se(s),i={loading:r,error:o,params:{page:void 0},data:[]};e&&(i.data=n?e.map(de("storyTarget")):[...new Set([...(null==a?void 0:a.data)||[],...e.map(de("storyTarget"))])]),_e(s,i.data),(e=>{var n;const r=e.data.map((e=>{const t=Se(["storyTarget","get",e]);if(null==t?void 0:t.data)return wn.storyTarget(t.data)})).filter(Boolean);t({onNextPage:void 0,data:r,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading||!1})})(i)};return(t=>{const n=se(Bd,e);ie(n,(({data:e,error:n,loading:r})=>{i(e,t,r,n)}))})(!0),o.push((()=>Te(s))),()=>{n(`getTargetsByTargetIds(tmpid: ${a}) > dispose`),o.forEach((e=>e()))}},getStoriesByTargetIds:(e,t,n)=>{const{log:r,cache:o,userId:s}=we();o||console.log(D);const a=Date.now();r(`getStoriesByTargetIds(tmpid: ${a}) > listen`);const i=new Ld(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{Te(l)})),()=>{r(`getStoriesByTargetIds(tmpid: ${a}) > dispose`),c.forEach((e=>e()))}},getGlobalStoryTargets:(e,t,n)=>{const{log:r,cache:o,userId:s}=we();o||console.log(D);const a=Date.now();r(`getGlobalStoryTarget(tmpid: ${a}) > listen`);const i=new Qd(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{Te(l)})),()=>{r(`getGlobalStoryTarget(tmpid: ${a}) > dispose`),c.forEach((e=>e()))}}});const Hd=e=>Object.assign(Object.assign({},e),{endAt:e.endAt?e.endAt:null}),Wd=e=>Object.assign({},e);var Jd=Object.freeze({__proto__:null,getNetworkAds:async()=>{const e=we(),{data:t}=await e.http.get("/api/v1/ads/me"),n=t.ads.map(Hd),r=t.advertisers.map(Wd);return Kt({ads:n,advertisers:r,files:t.files}),_e(["ad","setting"],t.settings),{ads:n.map(wn.ad),settings:t.settings}}});return e.API_REGIONS=vt,e.AdRepository=Jd,e.CategoryRepository=pl,e.ChannelRepository=lc,e.Client=ms,e.CommentRepository=Rl,e.CommunityPostSettingMaps=A,e.CommunityPostSettings=T,e.CommunityRepository=dl,e.ContentFeedType=M,e.DefaultCommunityPostSetting=E,e.FeedRepository=ml,e.FileRepository=Ca,e.FileType=I,e.LiveStreamPlayer=yd,e.MessageContentType=P,e.MessageRepository=Ki,e.PollRepository=ld,e.PostContentType=R,e.PostRepository=Gl,e.ReactionRepository=hi,e.StoryRepository=Vd,e.StreamRepository=sd,e.SubChannelRepository=Ji,e.UserRepository=ya,e.VERSION=U,e.VideoResolution=S,e.VideoSize=k,e.VideoTranscodingStatus=_,e.backupCache=async(e="amitySdk",t=(e=>e.offline))=>{const{log:n,cache:r,userId:o}=we();if(!r)return!1;n("cache/api/backupCache",{storageKey:e});const s=Object.fromEntries(Object.entries(r.data).filter((([e,n])=>t(n))));return!!Object.keys(s).length&&(localStorage&&await localStorage.setItem(`${e}#${o}`,JSON.stringify(s)),!0)},e.createQuery=se,e.createReport=async(e,t)=>{const n=we();return n.log("report/createReport",{referenceType:e,referenceId:t}),"user"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v4/me/flags/${encodeURIComponent(t)}`);if(e.cache){const e=await Nr(n);Kt(e)}return Xe("user.flagged",n),!!n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v5/messages/${encodeURIComponent(t)}/flags`);if(e.cache){const e=await Yn(n);Kt(e)}return Xe("message.flagged",n),!!n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v3/posts/${encodeURIComponent(t)}/flag`);if(e.cache){const e=await La(n);Kt(e)}return Xe("post.flagged",n),!!n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v3/comments/${encodeURIComponent(t)}/flag`);if(e.cache){const e=await pi(n);Kt(e)}return Xe("comment.flagged",n),!!n})({client:n,referenceId:t})},e.createUserToken=async(e,t,n)=>{const r=await Nt(),o=Bt(),s=Tt(wt("http",t)),{data:a}=await s.post("/api/v5/sessions",Object.assign(Object.assign({},n),{deviceId:r,deviceInfo:Object.assign(Object.assign({},o),{model:"token management API on TS-SDK"})}),{headers:{"X-API-Key":e}});return{accessToken:a.accessToken}},e.deleteReport=async(e,t)=>{const n=we();return n.log("report/deleteReport",{referenceType:e,referenceId:t}),"user"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v4/me/flags/${encodeURIComponent(t)}`);if(e.cache){const e=await Nr(n);Kt(e)}return Xe("user.unflagged",n),!!n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v5/messages/${encodeURIComponent(t)}/flags`);if(e.cache){const e=await Yn(n);Kt(e)}return Xe("message.unflagged",n),!!n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v3/posts/${encodeURIComponent(t)}/unflag`);if(e.cache){const e=await La(n);Kt(e)}return Xe("post.unflagged",n),!!n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v3/comments/${encodeURIComponent(t)}/unflag`);if(e.cache){const e=await pi(n);Kt(e)}return Xe("comment.unflagged",n),!!n})({client:n,referenceId:t})},e.disableCache=()=>{const e=we();e.cache&&(e.log("cache/api/disableCache"),delete e.cache)},e.dropFromCache=Te,e.enableCache=(e={},t)=>{const n=we();n.cache||(n.log("cache/api/enableCache"),n.cache={data:e,persistIf:t})},e.filterByChannelMembership=Pe,e.filterByCommunityMembership=Ue,e.filterByFeedType=Re,e.filterByPostDataTypes=je,e.filterByPropEquality=Ae,e.filterByPropInclusion=(e,t,n)=>void 0!==n?e.filter((e=>n.includes(e[t]))):e,e.filterByPropIntersection=Me,e.filterBySearchTerm=xe,e.filterByStringComparePartially=Ee,e.getChannelTopic=e=>`${e.path}/#`,e.getCommentTopic=({path:e})=>e,e.getCommunityStoriesTopic=({targetId:e,targetType:t})=>{const n=Qe();return`${st(n)}/social/${t}/${e}/story/#`},e.getCommunityTopic=({path:t},n=e.SubscriptionLevels.COMMUNITY)=>ot(t,n),e.getMarkedMessageTopic=it,e.getMarkerUserFeedTopic=ct,e.getMessageTopic=e=>e.path,e.getMyFollowersTopic=()=>{const e=Qe();return`${st(e)}/membership/${e._id}/+/+`},e.getMyFollowingsTopic=()=>{const e=Qe();return`${st(e)}/membership/+/${e._id}/+`},e.getNetworkTopic=lt,e.getPostTopic=({path:t},n=e.SubscriptionLevels.POST)=>"comment"===n?`${t}/comment/+`:t,e.getRole=Sa,e.getSmartFeedChannelTopic=dt,e.getSmartFeedMessageTopic=ht,e.getSmartFeedSubChannelTopic=ut,e.getStoryTopic=({targetId:e,targetType:t,storyId:n})=>{const r=Qe();return`${st(r)}/social/${t}/${e}/story/${n}/#`},e.getSubChannelTopic=e=>`${e.path}/#`,e.getUserTopic=at,e.isAfterBefore=W,e.isAfterBeforeRaw=J,e.isCachable=re,e.isFetcher=ee,e.isFresh=oe,e.isLocal=e=>re(e)&&-1===(null==e?void 0:e.cachedAt),e.isMutator=te,e.isOffline=ne,e.isPaged=G,e.isReportedByMe=async(e,t)=>{const n=we();return n.log("report/isReportedByMe",{referenceType:e,referenceId:t}),"user"===e?(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v3/users/${t}/isflagbyme`),{result:o,isFlagByMe:s}=null!=r?r:{};return null!==(n=null!=o?o:s)&&void 0!==n&&n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v5/messages/${encodeURIComponent(t)}/flags`),{result:o,isFlagByMe:s}=null!=r?r:{};return null!==(n=null!=o?o:s)&&void 0!==n&&n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v3/posts/${t}/isflagbyme`),{result:o,isFlagByMe:s}=null!=r?r:{};return null!==(n=null!=o?o:s)&&void 0!==n&&n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v3/comments/${t}/isflagbyme`),{result:o,isFlagByMe:s}=null!=r?r:{};return null!==(n=null!=o?o:s)&&void 0!==n&&n})({client:n,referenceId:t})},e.isSkip=H,e.mergeInCache=ke,e.onChannelMarkerFetched=ss,e.onFeedMarkerFetched=e=>{const t=we();return Ze(t,"feedMarker/onFeedMarkerFetched","local.feedMarker.fetched",(t=>{e(t.feedMarkers[0])}))},e.onFeedMarkerUpdated=Oo,e.onMessageMarked=us,e.onMessageMarkerFetched=ds,e.onSubChannelMarkerFetched=as,e.onSubChannelMarkerUpdated=is,e.onUserMarkerFetched=cs,e.onUserMarkerFetchedLegacy=ls,e.pullFromCache=Se,e.pushToCache=_e,e.queryCache=Ie,e.queryOptions=ae,e.queryRoles=Ia,e.restoreCache=async(e="amitySdk")=>{var t;const n=we();if(!n.cache)return!1;n.log("cache/api/restoreCache",{storageKey:e});const r=localStorage&&null!==(t=await localStorage.getItem(`${e}#${n.userId}`))&&void 0!==t?t:"{}";let o={};try{o=JSON.parse(r)}catch(e){}return n.cache.data=Object.assign(Object.assign({},o),n.cache.data),!0},e.runQuery=ie,e.sortByChannelSegment=({channelSegment:e},{channelSegment:t})=>e-t,e.sortByDisplayName=De,e.sortByFirstCreated=Be,e.sortByFirstUpdated=Le,e.sortByLastActivity=$e,e.sortByLastCreated=Fe,e.sortByLastUpdated=Ke,e.sortByLocalSortingDate=qe,e.sortByName=Ne,e.sortBySegmentNumber=({segmentNumber:e},{segmentNumber:t})=>e-t,e.subscribeTopic=pt,e.toPage=Z,e.toPageRaw=X,e.toToken=Y,e.upsertInCache=Oe,e.wipeCache=async(e="amitySdk")=>{const{log:t,cache:n,userId:r}=we();return!!n&&(t("cache/api/wipeCache",{storageKey:e}),n.data={},localStorage&&await localStorage.setItem(`${e}#${r}`,"{}"),!0)},Object.defineProperty(e,"__esModule",{value:!0}),e}({},jsBase64,mitt,debug,axios,HttpAgent,io,AsyncStorage,uuid$1,reactNative,hash,Hls);
|
|
5
|
+
var r=e("buffer"),s=r.Buffer;function o(e,t){for(var n in e)t[n]=e[n]}function a(e,t,n){return s(e,t,n)}s.from&&s.alloc&&s.allocUnsafe&&s.allocUnsafeSlow?t.exports=r:(o(r,n),n.Buffer=a),a.prototype=Object.create(s.prototype),o(s,a),a.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return s(e,t,n)},a.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=s(e);return void 0!==t?"string"==typeof n?r.fill(t,n):r.fill(t):r.fill(0),r},a.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return s(e)},a.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)}},{buffer:17}],74:[function(e,t,n){function r(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=r},{}],75:[function(e,t,n){var r=e("safe-buffer").Buffer,s=r.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 o(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}function a(e){var t=o(e);if("string"!=typeof t&&(r.isEncoding===s||!s(e)))throw new Error("Unknown encoding: "+e);return t||e}function i(e){var t;switch(this.encoding=a(e),this.encoding){case"utf16le":this.text=f,this.end=g,t=4;break;case"utf8":this.fillLast=u,t=4;break;case"base64":this.text=m,this.end=y,t=3;break;default:return this.write=v,void(this.end=b)}this.lastNeed=0,this.lastTotal=0,this.lastChar=r.allocUnsafe(t)}function c(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function l(e,t,n){var r=t.length-1;if(r<n)return 0;var s=c(t[r]);return s>=0?(s>0&&(e.lastNeed=s-1),s):--r<n||-2===s?0:(s=c(t[r]))>=0?(s>0&&(e.lastNeed=s-2),s):--r<n||-2===s?0:(s=c(t[r]))>=0?(s>0&&(2===s?s=0:e.lastNeed=s-3),s):0}function d(e,t,n){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}function u(e){var t=this.lastTotal-this.lastNeed,n=d(this,e);return void 0!==n?n: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 n=l(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString("utf8",t,r)}function p(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t}function f(e,t){if((e.length-t)%2==0){var n=e.toString("utf16le",t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}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 n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function m(e,t){var n=(e.length-t)%3;return 0===n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1===n?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-n))}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):""}n.StringDecoder=i,i.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||""},i.prototype.end=p,i.prototype.text=h,i.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,n){var r=e("punycode"),s=e("./util");function o(){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}n.parse=w,n.resolve=I,n.resolveObject=S,n.format=C,n.Url=o;var a=/^([a-z0-9.+-]+:)/i,i=/:[0-9]*$/,c=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,l=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),d=["'"].concat(l),u=["%","/","?",";","#"].concat(d),h=["/","?","#"],p=255,f=/^[+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,n){if(e&&s.isObject(e)&&e instanceof o)return e;var r=new o;return r.parse(e,t,n),r}function C(e){return s.isString(e)&&(e=w(e)),e instanceof o?e.format():o.prototype.format.call(e)}function I(e,t){return w(e,!1,!0).resolve(t)}function S(e,t){return e?w(e,!1,!0).resolveObject(t):t}o.prototype.parse=function(e,t,n){if(!s.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var o=e.indexOf("?"),i=-1!==o&&o<e.indexOf("#")?"?":"#",l=e.split(i),w=/\\/g;l[0]=l[0].replace(w,"/");var C=e=l.join(i);if(C=C.trim(),!n&&1===e.split("#").length){var I=c.exec(C);if(I)return this.path=C,this.href=C,this.pathname=I[1],I[2]?(this.search=I[2],this.query=t?b.parse(this.search.substr(1)):this.search.substr(1)):t&&(this.search="",this.query={}),this}var S=a.exec(C);if(S){var _=(S=S[0]).toLowerCase();this.protocol=_,C=C.substr(S.length)}if(n||S||C.match(/^\/\/[^@\/]+@[^@\/]+/)){var k="//"===C.substr(0,2);!k||S&&y[S]||(C=C.substr(2),this.slashes=!0)}if(!y[S]&&(k||S&&!v[S])){for(var O,T,E=-1,A=0;A<h.length;A++)-1!==(M=C.indexOf(h[A]))&&(-1===E||M<E)&&(E=M);for(-1!==(T=-1===E?C.lastIndexOf("@"):C.lastIndexOf("@",E))&&(O=C.slice(0,T),C=C.slice(T+1),this.auth=decodeURIComponent(O)),E=-1,A=0;A<u.length;A++){var M;-1!==(M=C.indexOf(u[A]))&&(-1===E||M<E)&&(E=M)}-1===E&&(E=C.length),this.host=C.slice(0,E),C=C.slice(E),this.parseHost(),this.hostname=this.hostname||"";var P="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!P)for(var R=this.hostname.split(/\./),U=(A=0,R.length);A<U;A++){var j=R[A];if(j&&!j.match(f)){for(var x="",D=0,N=j.length;D<N;D++)j.charCodeAt(D)>127?x+="x":x+=j[D];if(!x.match(f)){var B=R.slice(0,A),q=R.slice(A+1),F=j.match(g);F&&(B.push(F[1]),q.unshift(F[2])),q.length&&(C="/"+q.join(".")+C),this.hostname=B.join(".");break}}}this.hostname.length>p?this.hostname="":this.hostname=this.hostname.toLowerCase(),P||(this.hostname=r.toASCII(this.hostname));var L=this.port?":"+this.port:"",K=this.hostname||"";this.host=K+L,this.href+=this.host,P&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==C[0]&&(C="/"+C))}if(!m[_])for(A=0,U=d.length;A<U;A++){var $=d[A];if(-1!==C.indexOf($)){var z=encodeURIComponent($);z===$&&(z=escape($)),C=C.split($).join(z)}}var Q=C.indexOf("#");-1!==Q&&(this.hash=C.substr(Q),C=C.slice(0,Q));var V=C.indexOf("?");if(-1!==V?(this.search=C.substr(V),this.query=C.substr(V+1),t&&(this.query=b.parse(this.query)),C=C.slice(0,V)):t&&(this.search="",this.query={}),C&&(this.pathname=C),v[_]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){L=this.pathname||"";var H=this.search||"";this.path=L+H}return this.href=this.format(),this},o.prototype.format=function(){var e=this.auth||"";e&&(e=(e=encodeURIComponent(e)).replace(/%3A/i,":"),e+="@");var t=this.protocol||"",n=this.pathname||"",r=this.hash||"",o=!1,a="";this.host?o=e+this.host:this.hostname&&(o=e+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(o+=":"+this.port)),this.query&&s.isObject(this.query)&&Object.keys(this.query).length&&(a=b.stringify(this.query));var i=this.search||a&&"?"+a||"";return t&&":"!==t.substr(-1)&&(t+=":"),this.slashes||(!t||v[t])&&!1!==o?(o="//"+(o||""),n&&"/"!==n.charAt(0)&&(n="/"+n)):o||(o=""),r&&"#"!==r.charAt(0)&&(r="#"+r),i&&"?"!==i.charAt(0)&&(i="?"+i),t+o+(n=n.replace(/[?#]/g,(function(e){return encodeURIComponent(e)})))+(i=i.replace("#","%23"))+r},o.prototype.resolve=function(e){return this.resolveObject(w(e,!1,!0)).format()},o.prototype.resolveObject=function(e){if(s.isString(e)){var t=new o;t.parse(e,!1,!0),e=t}for(var n=new o,r=Object.keys(this),a=0;a<r.length;a++){var i=r[a];n[i]=this[i]}if(n.hash=e.hash,""===e.href)return n.href=n.format(),n;if(e.slashes&&!e.protocol){for(var c=Object.keys(e),l=0;l<c.length;l++){var d=c[l];"protocol"!==d&&(n[d]=e[d])}return v[n.protocol]&&n.hostname&&!n.pathname&&(n.path=n.pathname="/"),n.href=n.format(),n}if(e.protocol&&e.protocol!==n.protocol){if(!v[e.protocol]){for(var u=Object.keys(e),h=0;h<u.length;h++){var p=u[h];n[p]=e[p]}return n.href=n.format(),n}if(n.protocol=e.protocol,e.host||y[e.protocol])n.pathname=e.pathname;else{for(var f=(e.pathname||"").split("/");f.length&&!(e.host=f.shift()););e.host||(e.host=""),e.hostname||(e.hostname=""),""!==f[0]&&f.unshift(""),f.length<2&&f.unshift(""),n.pathname=f.join("/")}if(n.search=e.search,n.query=e.query,n.host=e.host||"",n.auth=e.auth,n.hostname=e.hostname||e.host,n.port=e.port,n.pathname||n.search){var g=n.pathname||"",m=n.search||"";n.path=g+m}return n.slashes=n.slashes||e.slashes,n.href=n.format(),n}var b=n.pathname&&"/"===n.pathname.charAt(0),w=e.host||e.pathname&&"/"===e.pathname.charAt(0),C=w||b||n.host&&e.pathname,I=C,S=n.pathname&&n.pathname.split("/")||[],_=(f=e.pathname&&e.pathname.split("/")||[],n.protocol&&!v[n.protocol]);if(_&&(n.hostname="",n.port=null,n.host&&(""===S[0]?S[0]=n.host:S.unshift(n.host)),n.host="",e.protocol&&(e.hostname=null,e.port=null,e.host&&(""===f[0]?f[0]=e.host:f.unshift(e.host)),e.host=null),C=C&&(""===f[0]||""===S[0])),w)n.host=e.host||""===e.host?e.host:n.host,n.hostname=e.hostname||""===e.hostname?e.hostname:n.hostname,n.search=e.search,n.query=e.query,S=f;else if(f.length)S||(S=[]),S.pop(),S=S.concat(f),n.search=e.search,n.query=e.query;else if(!s.isNullOrUndefined(e.search))return _&&(n.hostname=n.host=S.shift(),(A=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=A.shift(),n.host=n.hostname=A.shift())),n.search=e.search,n.query=e.query,s.isNull(n.pathname)&&s.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n;if(!S.length)return n.pathname=null,n.search?n.path="/"+n.search:n.path=null,n.href=n.format(),n;for(var k=S.slice(-1)[0],O=(n.host||e.host||S.length>1)&&("."===k||".."===k)||""===k,T=0,E=S.length;E>=0;E--)"."===(k=S[E])?S.splice(E,1):".."===k?(S.splice(E,1),T++):T&&(S.splice(E,1),T--);if(!C&&!I)for(;T--;T)S.unshift("..");!C||""===S[0]||S[0]&&"/"===S[0].charAt(0)||S.unshift(""),O&&"/"!==S.join("/").substr(-1)&&S.push("");var A,M=""===S[0]||S[0]&&"/"===S[0].charAt(0);return _&&(n.hostname=n.host=M?"":S.length?S.shift():"",(A=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=A.shift(),n.host=n.hostname=A.shift())),(C=C||n.host&&S.length)&&!M&&S.unshift(""),S.length?n.pathname=S.join("/"):(n.pathname=null,n.path=null),s.isNull(n.pathname)&&s.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n},o.prototype.parseHost=function(){var e=this.host,t=i.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,n){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,n){(function(e){(function(){function n(e,t){if(r("noDeprecation"))return e;var n=!1;function s(){if(!n){if(r("throwDeprecation"))throw new Error(t);r("traceDeprecation")?console.trace(t):console.warn(t),n=!0}return e.apply(this,arguments)}return s}function r(t){try{if(!e.localStorage)return!1}catch(e){return!1}var n=e.localStorage[t];return null!=n&&"true"===String(n).toLowerCase()}t.exports=n}).call(this)}).call(this,void 0!==Et?Et:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],79:[function(e,t,n){function r(e,t){if(e&&t)return r(e)(t);if("function"!=typeof e)throw new TypeError("need wrapper function");return Object.keys(e).forEach((function(t){n[t]=e[t]})),n;function n(){for(var t=new Array(arguments.length),n=0;n<t.length;n++)t[n]=arguments[n];var r=e.apply(this,t),s=t[t.length-1];return"function"==typeof r&&r!==s&&Object.keys(s).forEach((function(e){r[e]=s[e]})),r}}t.exports=r},{}],80:[function(e,t,n){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,n){t.exports=s;var r=Object.prototype.hasOwnProperty;function s(){for(var e={},t=0;t<arguments.length;t++){var n=arguments[t];for(var s in n)r.call(n,s)&&(e[s]=n[s])}return e}},{}],82:[function(e,t,n){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,n){function r(e){var t=this;if(t instanceof r||(t=new r),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 n=0,s=arguments.length;n<s;n++)t.push(arguments[n]);return t}function s(e,t,n){var r=t===e.head?new i(n,null,t,e):new i(n,t,t.next,e);return null===r.next&&(e.tail=r),null===r.prev&&(e.head=r),e.length++,r}function o(e,t){e.tail=new i(t,e.tail,null,e),e.head||(e.head=e.tail),e.length++}function a(e,t){e.head=new i(t,null,e.head,e),e.tail||(e.tail=e.head),e.length++}function i(e,t,n,r){if(!(this instanceof i))return new i(e,t,n,r);this.list=r,this.value=e,t?(t.next=this,this.prev=t):this.prev=null,n?(n.prev=this,this.next=n):this.next=null}t.exports=r,r.Node=i,r.create=r,r.prototype.removeNode=function(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");var t=e.next,n=e.prev;return t&&(t.prev=n),n&&(n.next=t),e===this.head&&(this.head=t),e===this.tail&&(this.tail=n),e.list.length--,e.next=null,e.prev=null,e.list=null,t},r.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++}},r.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++}},r.prototype.push=function(){for(var e=0,t=arguments.length;e<t;e++)o(this,arguments[e]);return this.length},r.prototype.unshift=function(){for(var e=0,t=arguments.length;e<t;e++)a(this,arguments[e]);return this.length},r.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}},r.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}},r.prototype.forEach=function(e,t){t=t||this;for(var n=this.head,r=0;null!==n;r++)e.call(t,n.value,r,this),n=n.next},r.prototype.forEachReverse=function(e,t){t=t||this;for(var n=this.tail,r=this.length-1;null!==n;r--)e.call(t,n.value,r,this),n=n.prev},r.prototype.get=function(e){for(var t=0,n=this.head;null!==n&&t<e;t++)n=n.next;if(t===e&&null!==n)return n.value},r.prototype.getReverse=function(e){for(var t=0,n=this.tail;null!==n&&t<e;t++)n=n.prev;if(t===e&&null!==n)return n.value},r.prototype.map=function(e,t){t=t||this;for(var n=new r,s=this.head;null!==s;)n.push(e.call(t,s.value,this)),s=s.next;return n},r.prototype.mapReverse=function(e,t){t=t||this;for(var n=new r,s=this.tail;null!==s;)n.push(e.call(t,s.value,this)),s=s.prev;return n},r.prototype.reduce=function(e,t){var n,r=this.head;if(arguments.length>1)n=t;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");r=this.head.next,n=this.head.value}for(var s=0;null!==r;s++)n=e(n,r.value,s),r=r.next;return n},r.prototype.reduceReverse=function(e,t){var n,r=this.tail;if(arguments.length>1)n=t;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");r=this.tail.prev,n=this.tail.value}for(var s=this.length-1;null!==r;s--)n=e(n,r.value,s),r=r.prev;return n},r.prototype.toArray=function(){for(var e=new Array(this.length),t=0,n=this.head;null!==n;t++)e[t]=n.value,n=n.next;return e},r.prototype.toArrayReverse=function(){for(var e=new Array(this.length),t=0,n=this.tail;null!==n;t++)e[t]=n.value,n=n.prev;return e},r.prototype.slice=function(e,t){(t=t||this.length)<0&&(t+=this.length),(e=e||0)<0&&(e+=this.length);var n=new r;if(t<e||t<0)return n;e<0&&(e=0),t>this.length&&(t=this.length);for(var s=0,o=this.head;null!==o&&s<e;s++)o=o.next;for(;null!==o&&s<t;s++,o=o.next)n.push(o.value);return n},r.prototype.sliceReverse=function(e,t){(t=t||this.length)<0&&(t+=this.length),(e=e||0)<0&&(e+=this.length);var n=new r;if(t<e||t<0)return n;e<0&&(e=0),t>this.length&&(t=this.length);for(var s=this.length,o=this.tail;null!==o&&s>t;s--)o=o.prev;for(;null!==o&&s>e;s--,o=o.prev)n.push(o.value);return n},r.prototype.splice=function(e,t,...n){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);for(var r=0,o=this.head;null!==o&&r<e;r++)o=o.next;var a=[];for(r=0;o&&r<t;r++)a.push(o.value),o=this.removeNode(o);for(null===o&&(o=this.tail),o!==this.head&&o!==this.tail&&(o=o.prev),r=0;r<n.length;r++)o=s(this,o,n[r]);return a},r.prototype.reverse=function(){for(var e=this.head,t=this.tail,n=e;null!==n;n=n.prev){var r=n.prev;n.prev=n.next,n.next=r}return this.head=t,this.tail=e,this};try{e("./iterator.js")(r)}catch(e){}},{"./iterator.js":82}]},{},[12])(12);var Rt=At(Pt.exports);class Ut{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 jt=()=>"undefined"!=typeof window&&window.localStorage?window:{localStorage:new Ut},xt=()=>b.default.v4().toString();let Dt=0;if("undefined"!=typeof BroadcastChannel&&"undefined"!=typeof window){const e=xt(),t={},n=new BroadcastChannel("amity_ts_sdk");let r;n.postMessage({type:"startup",tabId:e}),n.onmessage=({data:s})=>{s.tabId!==e&&("startup"===s.type&&n.postMessage({type:"identify",tabId:e,tabIndex:Dt}),"identify"===s.type&&void 0!==s.tabIndex&&s.tabId&&(t[s.tabId]=s.tabIndex,r||(r=setTimeout((()=>{const e=Object.values(t).sort();e&&0!==e.length&&(Dt=e.reduce(((e,t)=>e<t?e:t+1),0))}),15))))}}const Nt=async()=>{var e;const t=`${null!==(e=we().prefixDeviceIdKey)&&void 0!==e?e:""}#deviceId`,n=await(async e=>{if("undefined"!=typeof navigator&&"ReactNative"===navigator.product)return await v.default.getItem(e);return new Promise((t=>{t(jt().localStorage.getItem(e))}))})(t);if(n)return n;const r=`ascWebSdk#${xt()}`;return await(async(e,t)=>"undefined"!=typeof navigator&&"ReactNative"===navigator.product?(await v.default.setItem(e,t),!0):new Promise((n=>{jt().localStorage.setItem(e,t),n(!0)})))(t,r),r},Bt=()=>{const e=(()=>{var e,t;return(null===(e=mt.versions)||void 0===e?void 0:e.node)?mt.versions.node:navigator?`${navigator.product.toLowerCase()}#${null!==(t=navigator.userAgent)&&void 0!==t?t:"unknown_agent"}`:"unknown_model"})();return{kind:"web",model:e,sdkVersion:U}},qt=1e3;var Ft;!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"}(Ft||(Ft={}));const Lt=e=>{let t;return{connect:async function(n){const r=await(async e=>`mqttjs_${await Nt()}_${e}_${Dt}`)(n.userId);return t&&(t.removeAllListeners(),t.end(!0)),t=Rt.connect(e,function(e){return Object.assign({clean:!1,clientId:`mqttjs_ + ${Math.random().toString(16).substring(2,10)}`,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:qt,will:{topic:"WillMsg",payload:"Connection Closed abnormally..!",qos:0,retain:!1},resubscribe:!0},e)}({username:n.userId,password:n.accessToken,clientId:r})),t.on("connect",(()=>{t.options.reconnectPeriod=qt,(()=>{const e=[pt(lt()),pt(dt()),pt(ut()),pt(ht()),pt(at(Qe())),pt(ct())]})()})),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||qt),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,n){null==t||t.on(e,n)},once(e,n){null==t||t.once(e,n)},off(e,n){void 0!==n?null==t||t.off(e,n):null==t||t.removeAllListeners(e)},removeAllListeners(){null==t||t.removeAllListeners()},subscribe(e,n){const r=(t,r)=>{var s;if(t||128===(null===(s=r[0])||void 0===s?void 0:s.qos)){const r=t?new fe(t.message,8e5,"error"):new me(8e5,"error");console.warn(`Failed to subscribe to topic ${e}`,r),null==n||n(r)}else console.log(`Subscribed to topic ${e}`),null==n||n()};return t?t.subscribe(e,{qos:0},r):r(new Error("No connection to broker"),[]),()=>null==t?void 0:t.unsubscribe(e)},unsubscribe(e){null==t||t.unsubscribe(e)}}},Kt=(e={},t,n=!0)=>{Object.entries(e).forEach((([e,r])=>{const s=he[e];if(!s)return;const o=de(s);o&&r.forEach((e=>{(n?_e:Oe)([s,"get",o(e)],e,t)}))}))},$t=(e,t)=>{const{log:n,cache:r}=we(),s=[e,L,t],o={cachedAt:Date.now()};r&&(n("cache/api/pushToTombstone",{cacheKey:s,data:o}),Te([e,"get",t],!0),_e(s,o))};function zt(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(r=Object.getOwnPropertySymbols(e);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(e,r[s])&&(n[r[s]]=e[r[s]])}return n}const Qt=(e,t="userId",n="user")=>{var r;return null!==(r=null==e?void 0:e.map((e=>((e,t="userId",n="user")=>e[n]?e:Object.assign({get[n](){var n;if(!we().cache)return;return(null===(n=Se(["user","get",e[t]]))||void 0===n?void 0:n.data)||void 0}},e))(e,t,n))))&&void 0!==r?r:e},Vt=(e,t,n="userId",r="user")=>{const s=e,o=t,a=s[o],i=zt(s,["symbol"==typeof o?o:o+""]),c=Qt(a,n,r);return Object.assign(Object.assign({},i),{[t]:c})};function Ht(e){return e.map((e=>{var{isMentioned:t}=e,n=zt(e,["isMentioned"]);return Object.assign({hasMentioned:t},n)}))}function Wt(e){return Ht(e)}function Jt(e){return Ht(e)}const Gt=e=>{var t,n;return null!==(n=null===(t=Se(["messagePreviewChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},Yt=["analytic","normal-priority"],Xt=["analytic","high-priority"],Zt=async e=>{const t=we(),n={activities:e};await t.http.post("/api/v1/analytics/activities",n)};class en{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),this._high_priority_timer&&(clearInterval(this._high_priority_timer),this._high_priority_timer=void 0)}async syncCapturedEvent(){try{const e=Se(Yt);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await Zt(t),Te(Yt)}catch(e){this.stop(),Te(Yt)}}async syncHighPriorityCapturedEvent(){try{const e=Se(Xt);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await Zt(t),Te(Xt)}catch(e){this.stop(),Te(Xt)}}}class tn{constructor(){this._expireTime=3e5,this._poolLimit=1e3,this._recentViewed={},this._recentHighPriorityViewed={},this._throttleStoryTimer=void 0,this._bufferNewSeenStoryReferenceIds=[]}isAbleToEnqueue({uniqueId:e,expireTime:t,isHighPriority:n=!1}){const r=new Date,s=(()=>n?this._recentHighPriorityViewed[e]:this._recentViewed[e])()||new Date(-1*q);return!(r.getTime()-s.getTime()<t)}markAs({uniqueId:e,contentId:t,contentType:n,activityType:r,metadata:s}){if(!this.isAbleToEnqueue({uniqueId:e,expireTime:this._expireTime}))return;const o=new Date,a={event:[]},i=Se(Yt);(null==i?void 0:i.data)&&(a.event=i.data.event),a.event.length>=this._poolLimit&&a.event.shift();const c={contentId:t,contentType:n,activityType:r,timestamp:o.toISOString()};s&&(c.metadata=s),a.event.push(c),Oe(Yt,a),this._recentViewed[e]=o}markPostAsViewed(e){this.markAs({uniqueId:e,contentId:e,contentType:"post",activityType:"view"})}markStory(e,t){if(!e.expiresAt)return;const n=new Date,r=new Date(e.expiresAt);if(!this.isAbleToEnqueue({uniqueId:e.storyId,expireTime:r.getTime(),isHighPriority:!0}))return;const s={event:[]},o=Se(Xt);if((null==o?void 0:o.data)&&(s.event=o.data.event),s.event.length>=this._poolLimit&&s.event.shift(),s.event.push({contentId:e.storyId,contentType:"story",activityType:t,timestamp:n.toISOString()}),Oe(Xt,s),this._recentHighPriorityViewed[e.storyId]=n,"linkClicked"===t)return;_e(["story-seen","get",e.storyId],(new Date).toISOString());const a=Se(["story-last-seen",e.targetId]);(null==a?void 0:a.data)?new Date(a.data).getTime()<new Date(e.expiresAt).getTime()&&_e(["story-last-seen",e.targetId],e.expiresAt):_e(["story-last-seen",e.targetId],e.expiresAt),this._bufferNewSeenStoryReferenceIds.push(e.referenceId),this._throttleStoryTimer||(this._throttleStoryTimer=setTimeout((()=>{clearTimeout(this._throttleStoryTimer),Ze("local.story.reload",{referenceIds:this._bufferNewSeenStoryReferenceIds}),this._bufferNewSeenStoryReferenceIds=[]}),300))}resetAllBuckets(){this._recentViewed={},this._recentHighPriorityViewed={},Te(Yt),Te(Xt)}markStoryAsViewed(e){this.markStory(e,"view")}markStoryAsClicked(e){this.markStory(e,"linkClicked")}markAdAsViewed(e,t){const n={placement:t},r="view";this.markAs({uniqueId:`${e.adId}.view.${t}`,contentId:e.adId,contentType:"ad",activityType:r,metadata:n})}markAdAsClicked(e,t){const n={placement:t},r="linkClicked";this.markAs({uniqueId:`${e.adId}.linkClicked.${t}`,contentId:e.adId,contentType:"ad",activityType:r,metadata:n})}}class nn{constructor(){this._client=we(),this._eventCapturer=new tn,this._eventSyncer=new en}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)}markAdAsViewed(e,t){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markAdAsViewed(e,t)}markAdAsClicked(e,t){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markAdAsClicked(e,t)}markStoryAsClicked(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markStoryAsClicked(e)}established(){this._eventSyncer.start()}handleTokenExpired(){this._stopAndDestroy()}destroy(){this._stopAndDestroy()}_stopAndDestroy(){this._eventSyncer.stop(),this._eventCapturer.resetAllBuckets()}}let rn;var sn=()=>(rn||(rn=new nn),rn);const on=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=Se(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}});class an{constructor(e,t,n){this._syncingStoriesCount=0,this._errorStoriesCount=0,this._targetId=e,this._lastStoryExpiresAt=t,this._lastStorySeenExpiresAt=n,this.cacheStoryExpireTime=Se(["story-expire",this._targetId]),this.cacheStoreSeenTime=Se(["story-last-seen",this._targetId]),this.getTotalStoryByStatus()}get lastStoryExpiresAt(){return this._lastStoryExpiresAt?new Date(this._lastStoryExpiresAt).getTime():0}get lastStorySeenExpiresAt(){return this._lastStorySeenExpiresAt?new Date(this._lastStorySeenExpiresAt).getTime():0}get localLastStoryExpires(){var e,t;return(null===(e=this.cacheStoryExpireTime)||void 0===e?void 0:e.data)?new Date(null===(t=this.cacheStoryExpireTime)||void 0===t?void 0:t.data).getTime():0}get localLastStorySeenExpiresAt(){var e,t;return(null===(e=this.cacheStoreSeenTime)||void 0===e?void 0:e.data)?new Date(null===(t=this.cacheStoreSeenTime)||void 0===t?void 0:t.data).getTime():0}get isContainUnSyncedStory(){const e=Se(["story-sync-state",this._targetId]);return!!(null==e?void 0:e.data)&&["syncing","error"].includes(e.data)}getLocalLastSortingDate(){return this.isContainUnSyncedStory?this.localLastStoryExpires:this.lastStoryExpiresAt}getHasUnseenFlag(){const e=(new Date).getTime(),t=Math.max(this.lastStorySeenExpiresAt,this.localLastStorySeenExpiresAt);return Se(["story-sync-state",this._targetId]),this.isContainUnSyncedStory?this.localLastStoryExpires>e&&this.localLastStoryExpires>t:this.lastStoryExpiresAt>e&&this.lastStoryExpiresAt>t}getTotalStoryByStatus(){const e=Ie(["story","get"]);if(!e)return this._errorStoriesCount=0,void(this._syncingStoriesCount=0);const t=e.reduce(((e,t)=>{const{data:{targetId:n,syncState:r}}=t;return n===this._targetId&&(e[r]+=1),e}),{syncing:0,error:0,synced:0});this._errorStoriesCount=t.error,this._syncingStoriesCount=t.syncing}get syncingStoriesCount(){return this._syncingStoriesCount}get failedStoriesCount(){return this._errorStoriesCount}}const cn=e=>{const{targetType:t,targetId:n,lastStoryExpiresAt:r,lastStorySeenExpiresAt:s,targetUpdatedAt:o,localFilter:a}=e,i=new an(n,r,s);return{targetType:t,targetId:n,lastStoryExpiresAt:r,updatedAt:o,hasUnseen:i.getHasUnseenFlag(),syncingStoriesCount:i.syncingStoriesCount,failedStoriesCount:i.failedStoriesCount,localFilter:a,localLastExpires:i.localLastStoryExpires,localLastSeen:i.localLastStorySeenExpiresAt,localSortingDate:i.getLocalLastSortingDate()}};function ln(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 n=0;n<e.length;n+=1)if(!ln(e[n],t[n]))return!1;return!0}if(e instanceof Date)return!1;if(!(e instanceof Object))return!1;if(!(t instanceof Object))return!1;const n=Object.keys(e);return Object.keys(t).every((e=>-1!==n.indexOf(e)))&&n.every((n=>ln(e[n],t[n])))}function dn(e){return null!=e}const un=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 n=Se(["communityUsers","get",`${e.targetId}#${e.userId}`]);return Object.assign(Object.assign({},t),{communityId:e.targetId,creatorMember:null==n?void 0:n.data})}return{type:"unknown"}},get creator(){const t=Se(["user","get",e.userId]);if(null==t?void 0:t.data)return on(t.data)},get childrenComment(){return e.children.map((e=>{const t=Se(["comment","get",e]);if(null==t?void 0:t.data)return null==t?void 0:t.data})).filter(dn).map((e=>un(e)))}}),hn=e=>Object.assign(Object.assign({},e),{analytics:{markAsViewed:()=>{sn().markPostAsViewed(e.postId)}},get latestComments(){return e.comments&&e.comments.map((e=>{var t;const n=null===(t=Se(["comment","get",e]))||void 0===t?void 0:t.data;return n?un(n):null})).filter(Boolean)||[]},get creator(){const t=Se(["user","get",e.postedUserId]);if(null==t?void 0:t.data)return on(t.data)}}),pn=(e,t)=>{var n;return null!==(n=null!=t?t:(e=>{var t,n;const r={creatorId:"creatorPrivateId"in e?e.creatorPrivateId:e.creatorId,feedId:null!==(t=e.messageFeedId)&&void 0!==t?t:e.subChannelId,contentId:e.messageId};return null===(n=Se(["messageMarker","get",de("messageMarker")(r)]))||void 0===n?void 0:n.data})(e))&&void 0!==n?n:{readCount:0,deliveredCount:0}},fn=e=>{var t;const n=["channelUnreadInfo","get",e],r=null===(t=Se(n))||void 0===t?void 0:t.data,s=Ie(["subChannelUnreadInfo","get"]);let o=0,a=!1;if(s&&(null==s?void 0:s.length)>0){const t=null==s?void 0:s.filter((({data:t})=>t.channelId===e&&!t.isDeleted));o=t.map((({data:e})=>e.unreadCount)).reduce(((e,t)=>e+t),0),a=t.some((({data:e})=>e.isMentioned))}const i=Object.assign(Object.assign({},null!=r?r:{channelId:e,createdAt:(new Date).toISOString()}),{updatedAt:(new Date).toISOString(),unreadCount:o,isMentioned:a});return _e(n,i),i};class gn{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=we(),this.getUnsyncJobs()}startSyncReadReceipt(){this.timer=setInterval((()=>{this.syncReadReceipts()}),1e3*this.RECEIPT_SYNC_INTERVAL)}syncReadReceipts(){if(0===this.jobQueue.length||!1===this.isActive)return;const e=this.getReadReceipt();e&&this.markReadApi(e)}getUnsyncJobs(){var e;const t=null===(e=Ie(["readReceipt"]))||void 0===e?void 0:e.filter((({data:e})=>e.latestSyncSegment<e.latestSegment));null==t||t.forEach((({data:e})=>{this.enqueueReadReceipt(e.subChannelId,e.latestSegment)}))}getReadReceipt(){var e;const t=this.jobQueue[0];if(!t)return;if("syncing"===t.syncState)return;const n=null===(e=Se(["readReceipt",t.subChannelId]))||void 0===e?void 0:e.data;return n?(null==n?void 0:n.latestSegment)>(null==n?void 0:n.latestSyncSegment)?(t.segment=n.latestSegment,t):(this.removeSynedReceipt(n.subChannelId,n.latestSegment),this.getReadReceipt()):void 0}async markReadApi(e){var t;const n=e;n.syncState="syncing";const{subChannelId:r,segment:s}=n,o=await(async({subChannelId:e,readToSegment:t})=>{const n=we();n.log("subChannel/markAsReadBySegment",e);try{return await n.http.put(`/api/v1/markers/message-feeds/${e}/mark-read`,{readToSegment:t}),!0}catch(e){return!1}})({subChannelId:r,readToSegment:s});if(o){this.removeSynedReceipt(e.subChannelId,e.segment);const n=null===(t=Se(["readReceipt",r]))||void 0===t?void 0:t.data;_e(["readReceipt",r],Object.assign(Object.assign({},n),{latestSyncSegment:s}))}else o||(n.retryCount>this.MAX_RETRY?this.removeJobFromQueue(n):(n.retryCount+=1,n.syncState="create"))}removeSynedReceipt(e,t){this.jobQueue.forEach((n=>{n.subChannelId===e&&n.segment<=t&&this.removeJobFromQueue(n)}))}startObservingReadReceiptQueue(){this.client.isUnreadCountEnabled&&(this.isActive=!0,this.startSyncReadReceipt())}stopObservingReadReceiptQueue(){this.isActive=!1;this.jobQueue.map((e=>"syncing"===e.syncState?Object.assign(Object.assign({},e),{syncState:"create"}):e)),this.timer&&clearInterval(this.timer)}onSessionEstablished(){this.startObservingReadReceiptQueue()}onSessionDestroyed(){this.stopObservingReadReceiptQueue(),this.jobQueue=[]}onTokenExpired(){this.stopObservingReadReceiptQueue()}onNetworkOffline(){this.stopObservingReadReceiptQueue()}onNetworkOnline(){this.startObservingReadReceiptQueue()}markRead(e,t){var n;const r=["subChannelUnreadInfo","get",e],s=null===(n=Se(r))||void 0===n?void 0:n.data;if(s&&t>s.readToSegment){s.readToSegment=t,s.unreadCount=Math.max(s.lastSegment-t,0);const e=fn(s.channelId);Ze("local.channelUnread.updated",e),_e(r,s),Ze("local.subChannelUnread.updated",s)}this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const r=null===(n=Se(["readReceipt",e]))||void 0===n?void 0:n.data;if(r){if(r.latestSegment<t)_e(["readReceipt",e],Object.assign(Object.assign({},r),{latestSegment:t}));else if(r.latestSyncSegment>=t)return}else{_e(["readReceipt",e],{subChannelId:e,latestSegment:t,latestSyncSegment:0})}let s=this.getSyncJob(e);null===s||"syncing"===s.syncState?(s={subChannelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(s)):s.segment<t&&(s.segment=t)}getSyncJob(e){return this.jobQueue.find((t=>t.subChannelId===e))||null}enqueueJob(e){this.jobQueue.length<this.JOB_QUEUE_SIZE||this.jobQueue.shift(),this.jobQueue.push(e)}removeJobFromQueue(e){const t=this.jobQueue.indexOf(e);t>-1&&this.jobQueue.splice(t,1)}}let mn=null;var yn=()=>(mn||(mn=new gn),mn);const vn=e=>{const{subChannelId:t,channelSegment:n}=e;yn().markRead(t,n)},bn=async e=>{const t=we();t.log("channel/markAsRead",e);const{data:n}=await t.http.put(`/api/v1/markers/channels/${e}/mark-read`),{userMarkers:r,userEntityMarkers:s,userFeedMarkers:o}=n,a=zt(n,["userMarkers","userEntityMarkers","userFeedMarkers"]),i=t.cache&&Date.now(),c=Wt(s),l=Jt(o);return t.cache&&Kt(Object.assign({userMarkers:r,userEntityMarkers:c,userFeedMarkers:l},a),{cachedAt:i}),Ze("local.channelMarker.updated",{userEntityMarkers:c}),Ze("local.subChannelMarker.updated",{userFeedMarkers:l}),!0},wn={ad:e=>{const t=sn(),{image9_16:n,image1_1:r}=e,s=zt(e,["image9_16","image1_1"]);return Object.assign(Object.assign({},s),{analytics:{markAsSeen:n=>{t.markAdAsViewed(e,n)},markLinkAsClicked:n=>{t.markAdAsClicked(e,n)}},get advertiser(){var t,n;const r=null===(t=Se(["advertiser","get",e.advertiserId]))||void 0===t?void 0:t.data;if(!r)return;const s=null===(n=Se(["file","get",r.avatarFileId]))||void 0===n?void 0:n.data;return Object.assign(Object.assign({},r),{avatar:s})},get image1_1(){const e=Se(["file","get",r]);if(e)return e.data||void 0},get image9_16(){const e=Se(["file","get",n]);if(e)return e.data||void 0}})},comment:un,post:hn,user:on,category:e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=Se(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),stream:e=>Object.assign(Object.assign({},e),{get moderation(){var t;return null===(t=Se(["streamModeration","get",e.streamId]))||void 0===t?void 0:t.data},get post(){var t;if("post"===e.referenceType)return null===(t=Se(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=Se(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;return null===(t=Se(["user","get",e.userId]))||void 0===t?void 0:t.data}}),story:e=>{const t=sn(),n=Se(["storyTarget","get",e.targetId]),r=Se(["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,n;const r=Se(["file","get",null===(n=null===(t=e.data)||void 0===t?void 0:t.videoFileId)||void 0===n?void 0:n.original]);if(!r)return;const{data:s}=r;return s||void 0},get imageData(){var t,n;if(!(null===(t=e.data)||void 0===t?void 0:t.fileId))return;const r=Se(["file","get",null===(n=e.data)||void 0===n?void 0:n.fileId]);if(!r)return;const{data:s}=r;return s?Object.assign(Object.assign({},s),{fileUrl:`${s.fileUrl}?size=full`}):void 0},get community(){if("community"===e.targetType&&r)return(null==r?void 0:r.data)||void 0},get communityCategories(){if("community"!==e.targetType)return;if(!r)return;const{data:{categoryIds:t}}=r;return 0!==t.length?t.map((e=>{const t=Se(["category","get",e]);return(null==t?void 0:t.data)||void 0})).filter((e=>void 0!==e)):void 0},get creator(){const t=Se(["user","get",e.creatorPublicId]);if(null==t?void 0:t.data)return on(t.data)},get storyTarget(){if(null==n?void 0:n.data)return cn(n.data)},get isSeen(){const t=Se(["story-last-seen",e.targetId]);if(!(null==n?void 0:n.data))return!1;const r=(null==t?void 0:t.data)?new Date(t.data).getTime():0,s=new Date(null==n?void 0:n.data.lastStorySeenExpiresAt).getTime()||0,o=new Date(e.expiresAt).getTime();return Math.max(r,s)>=o}})},storyTarget:cn,message:e=>{const t=zt(e,["creatorPrivateId"]);return Object.assign(Object.assign({},t),{get readCount(){return pn(e).readCount},get deliveredCount(){return pn(e).deliveredCount},markRead:()=>vn(e)})},reactor:e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=Se(["user","get",e.userId]))||void 0===t?void 0:t.data;if(n)return on(n)}}),channel:e=>Object.assign(Object.assign({},e),{markAsRead:()=>bn(e.channelInternalId)}),pinnedPost:e=>{var t;const n=Se(["post","get",e.referenceId]),r=null===(t=Ie(["user","get"]).find((t=>{var n;return(null===(n=t.data)||void 0===n?void 0:n.userInternalId)===e.pinnedBy})))||void 0===t?void 0:t.data;return Object.assign(Object.assign({},e),{pinnedBy:r,get post(){if(null==n?void 0:n.data)return hn(n.data)},get target(){const e=Se(["pinTarget","get",null==n?void 0:n.data.targetId]);if(null==e?void 0:e.data)return null==e?void 0:e.data}})}},Cn=e=>{var t;const n=e.messagePreviewId?Gt(e.channelId):null,r=null===(t=Se(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data,s=n?Object.assign(Object.assign({},n),{user:r?wn.user(r):void 0}):null;return Object.assign(Object.assign({},e),{messagePreview:s})},In=e=>{var t,n;const r={messagePreviewChannel:null!==(n=null===(t=e.messagePreviews)||void 0===t?void 0:t.map((t=>(t=>{var n;const r=null===(n=e.messageFeedsInfo)||void 0===n?void 0:n.find((e=>e.messageFeedId===t.messageFeedId)),{channelPublicId:s,messageFeedId:o,data:a,dataType:i,isDeleted:c,segment:l,creatorPublicId:d,createdAt:u,updatedAt:h}=t;return{channelId:s,subChannelId:o,data:a,dataType:i,isDeleted:c,segment:l,creatorId:d,createdAt:u,updatedAt:h,subChannelName:null==r?void 0:r.name,messagePreviewId:null==r?void 0:r.messagePreviewId,subChannelUpdatedAt:null==r?void 0:r.updatedAt}})(t))))&&void 0!==n?n:[]};Kt(r)},Sn=e=>{var t,n;return null!==(n=null===(t=Se(["messagePreviewSubChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},_n=e=>{var t;const n=e.messagePreviewId?Sn(e.subChannelId):null,r=n?Object.assign(Object.assign({},n),{user:null===(t=Se(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data}):null;return Object.assign(Object.assign({},e),{messagePreview:r})},kn=e=>{var t,n;const r={messagePreviewSubChannel:null!==(n=null===(t=e.messages)||void 0===t?void 0:t.map((t=>(t=>{var n;const r=null===(n=e.messageFeeds)||void 0===n?void 0:n.find((e=>e.messageFeedId===t.messageFeedId)),{channelPublicId:s,messageFeedId:o,messageId:a,creatorPublicId:i,data:c,dataType:l,isDeleted:d,segment:u,createdAt:h,updatedAt:p}=t;return{messagePreviewId:a,channelId:s,subChannelId:o,data:c,dataType:l,isDeleted:d,segment:u,creatorId:i,createdAt:h,updatedAt:p,subChannelName:null==r?void 0:r.name,subChannelUpdatedAt:null==r?void 0:r.updatedAt}})(t))))&&void 0!==n?n:[]};Kt(r)};function On(e){const t=Object.create(Object.getPrototypeOf(e)),n=Object.getOwnPropertyDescriptors(e);return Object.defineProperties(t,n),t}function Tn(e,t,n){_e(["subChannel","get",e],Object.assign(On(t),n))}const En=async e=>{var t,n,r,s;const{channelId:o,messageId:a,creatorId:i,createdAt:c,updatedAt:l,data:d,dataType:u,subChannelId:h,channelSegment:p,isDeleted:f}=e,g=null===(t=Se(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(!g||g.segment<=e.channelSegment){const t=null===(n=Se(["subChannel","get",h]))||void 0===n?void 0:n.data;_e(["messagePreviewSubChannel","get",e.subChannelId],{channelId:o,creatorId:i,messagePreviewId:a,createdAt:c,updatedAt:l,subChannelId:h,data:d,dataType:u,segment:p,isDeleted:f,subChannelUpdatedAt:null==t?void 0:t.updatedAt,subChannelName:null==t?void 0:t.displayName}),Tn(e.subChannelId,t,{messagePreviewId:a})}const m=null===(r=Se(["messagePreviewChannel","get",e.channelId]))||void 0===r?void 0:r.data;if(!m||new Date(m.createdAt).valueOf()<=new Date(e.createdAt).valueOf()){const t=null===(s=Se(["subChannel","get",h]))||void 0===s?void 0:s.data;_e(["messagePreviewChannel","get",e.channelId],{channelId:o,creatorId:i,messagePreviewId:a,createdAt:c,updatedAt:l,subChannelId:h,data:d,dataType:u,segment:p,isDeleted:f,subChannelUpdatedAt:null==t?void 0:t.updatedAt,subChannelName:null==t?void 0:t.displayName})}},An=async e=>{var t,n,r,s;const{channelId:o,messageId:a,creatorId:i,createdAt:c,updatedAt:l,data:d,dataType:u,subChannelId:h,channelSegment:p,isDeleted:f}=e,g=null===(t=Se(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(g&&g.messagePreviewId===e.messageId){const t=null===(n=Se(["subChannel","get",h]))||void 0===n?void 0:n.data;Tn(e.subChannelId,t,{messagePreviewId:a}),_e(["messagePreviewSubChannel","get",e.subChannelId],{channelId:o,creatorId:i,messagePreviewId:a,createdAt:c,updatedAt:l,subChannelId:h,data:d,dataType:u,segment:p,isDeleted:f,subChannelUpdatedAt:null==e?void 0:e.updatedAt,subChannelName:null==t?void 0:t.displayName})}const m=null===(r=Se(["messagePreviewChannel","get",e.channelId]))||void 0===r?void 0:r.data;if(m&&m.messagePreviewId===e.messageId){const t=null===(s=Se(["subChannel","get",h]))||void 0===s?void 0:s.data;_e(["messagePreviewChannel","get",e.channelId],{channelId:o,creatorId:i,messagePreviewId:a,createdAt:c,updatedAt:l,subChannelId:h,data:d,dataType:u,segment:p,isDeleted:f,subChannelUpdatedAt:null==t?void 0:t.updatedAt,subChannelName:null==t?void 0:t.displayName})}},Mn=async e=>{var t,n,r,s;const{channelId:o,subChannelId:a}=e,i=null===(t=Se(["messagePreviewChannel","get",o]))||void 0===t?void 0:t.data;if((null==i?void 0:i.subChannelId)===a){const e=null===(n=Se(["subChannel","get",a]))||void 0===n?void 0:n.data;_e(["messagePreviewChannel","get",o],Object.assign(Object.assign({},i),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}const c=null===(r=Se(["messagePreviewSubChannel","get",a]))||void 0===r?void 0:r.data;if(c&&new Date(c.updatedAt).valueOf()>new Date(e.updatedAt).valueOf()){const e=null===(s=Se(["subChannel","get",a]))||void 0===s?void 0:s.data;_e(["messagePreviewSubChannel","get",a],Object.assign(Object.assign({},c),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}},Pn=(e,t)=>{var n,r,s,o,a;const i=we();return i.isUnreadCountEnabled&&i.getMarkerSyncConsistentMode()?null!==(r=null===(n=(e=>{var t;return null===(t=Se(["channelUnreadInfo","get",e]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===n?void 0:n.unreadCount)&&void 0!==r?r:0:(null==t?void 0:t.isDeleted)?0:null!==(a=null!==(s=null==t?void 0:t.unreadCount)&&void 0!==s?s:null===(o=(e=>{var t;const n={entityId:e,userId:Qe()._id};return null===(t=Se(["channelMarker","get",de("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===o?void 0:o.unreadCount)&&void 0!==a?a:0},Rn=(e,t)=>{var n,r,s,o;const a=we();return a.isUnreadCountEnabled&&a.getMarkerSyncConsistentMode()?null!==(r=null===(n=(e=>{var t;return null===(t=Se(["channelUnreadInfo","get",e]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===n?void 0:n.isMentioned)&&void 0!==r&&r:void 0!==(null==t?void 0:t.hasMentioned)?null==t?void 0:t.hasMentioned:null!==(o=null===(s=(e=>{var t;const n={entityId:e,userId:Qe()._id};return null===(t=Se(["channelMarker","get",de("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===s?void 0:s.hasMentioned)&&void 0!==o&&o};function Un(e){return Object.assign(Object.assign({},e),{isGlobalBanned:(null==e?void 0:e.isGlobalBan)||!1})}const jn=["broadcast","conversation","community"],xn=({type:e})=>jn.includes(e);function Dn(e,t={isMessagePreviewUpdated:!0}){var n;let{messagePreviewId:r}=e;const s=null===(n=Se(["messagePreviewChannel","get",e.channelId]))||void 0===n?void 0:n.data;return(null==s?void 0:s.messagePreviewId)&&!t.isMessagePreviewUpdated&&(r=s.messagePreviewId),Object.assign(Object.assign({get unreadCount(){return Pn(e)},get hasMentioned(){return Rn(e)},get isMentioned(){return Rn(e)},get subChannelsUnreadCount(){return Pn(e)}},e),{defaultSubChannelId:e.channelInternalId,isUnreadCountSupport:xn(e),messagePreviewId:r})}const Nn=(e,t={isMessagePreviewUpdated:!0})=>{Kt({channels:e.channels.map((e=>Dn(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated})))})},Bn=async(e,t={isMessagePreviewUpdated:!0})=>{const n=we(),r=await n.getMessagePreviewSetting(!1);t.isMessagePreviewUpdated&&"no-message-preview"!==r&&e.messagePreviews&&e.messagePreviews.length>0&&In(e);const s=e.channels.filter(xn).map((({channelInternalId:e})=>e));if(s.length>0){Nn(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated});try{await(async e=>{const t=we();t.log("channel/getChannelMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/channels",{params:{channelIds:e}}),{userEntityMarkers:r,userMarkers:s}=n,o=Wt(r),a=t.cache&&Date.now();return t.cache&&Kt({userEntityMarkers:o,userMarkers:s},{cachedAt:a}),Ze("local.channelMarker.fetched",{userEntityMarkers:o}),Ze("local.userMarker.fetched",{userMarkers:s}),{data:o,cachedAt:a}})(s)}catch(e){}}const o=e.channels.map((e=>Dn(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated}))),a=e.channelUsers.map((e=>{return t=e,Object.assign(Object.assign({},t),{get user(){var e;if(we().cache)return(null===(e=Se(["user","get",t.userId]))||void 0===e?void 0:e.data)||void 0}});var t})),i=e.users.map(Un),c=zt(e,["messageFeedsInfo","messagePreviews"]);return Object.assign(Object.assign({},c),{users:i,channels:o,channelUsers:a})},qn=async e=>{const t=we();t.log("channel/getUserMessageFeedMakers",e);const{data:n}=await t.http.get("/api/v1/markers/user-message-feed",{params:{channelIds:e}});return Ze("local.userMessageFeedMarker.fetched",{userMessageFeedMarker:n}),n},Fn=e=>{const{feedMarkers:t,userFeedMarkers:n}=e;if(t.length>0&&n.length>0){const e=[],r=new Map(t.map((e=>[e.feedId,e])));n.forEach((t=>{const n=r.get(t.feedId);if(n&&n.feedId===t.feedId){const r=n.lastSegment-t.readToSegment,s={subChannelId:n.feedId,channelId:n.entityId,readToSegment:t.readToSegment,lastSegment:n.lastSegment,lastMentionSegment:t.lastMentionSegment,unreadCount:Math.max(0,r),isMentioned:t.isMentioned,isDeleted:n.isDeleted,createdAt:t.createdAt,updatedAt:t.updatedAt};Kt({subChannelUnreadInfo:[s]}),e.includes(n.entityId)||e.push(n.entityId)}})),e.forEach((e=>{fn(e)}))}},Ln=async e=>{const t=we(),n=await qn(e.channels.map((({channelInternalId:e})=>e))),{feedMarkers:r,userFeedMarkers:s}=n;Fn({feedMarkers:r,userFeedMarkers:s}),t.log("channel/prepareUnreadCountInfo",e.channels)},Kn=async e=>{const t=we();t.log("channel/getChannelByIds",e);const n=e.map((e=>encodeURIComponent(e)));let r;try{r=(await t.http.get("/api/v3/channels/list",{params:{channelIds:n}})).data}catch(t){throw e.forEach((e=>{V(null==t?void 0:t.code)&&$t("channel",e)})),t}const s=await Bn(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await Ln(r);const o=t.cache&&Date.now();return t.cache&&Kt(s,{cachedAt:o}),Ze("local.channel.fetched",s.channels),{data:s.channels.map((e=>wn.channel(e))),cachedAt:o}};Kn.locally=e=>{var t,n;const r=we();if(r.log("channel/getChannelByIds.locally",e),!r.cache)return;const s=null===(t=Ie(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!s||(null==s?void 0:s.length)<e.length)return;const o=s.map((({data:e})=>e)),a=null===(n=s.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0];return{data:o.map((e=>wn.channel(e))),cachedAt:a.cachedAt}};const $n=async()=>{const e=we();e.log("channel/getUserMarker");const{data:t}=await e.http.get("/api/v1/markers/userMarker"),{userMarkers:n}=t,r=e.cache&&Date.now();e.cache&&Kt({userMarkers:n},{cachedAt:r}),Ze("local.userMarker.fetched",{userMarkers:n});return{data:n.reduce(((e,t)=>null==e||new Date(e.lastSyncAt).getTime()<new Date(t.lastSyncAt).getTime()?t:e),void 0),cachedAt:r}},zn=e=>!0===e&&void 0;function Qn(e,t,n){var r,s;if(n)return n.hasMentioned;const o=we();if(o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()){const e=null===(r=Se(["subChannelUnreadInfo","get",t]))||void 0===r?void 0:r.data;return!!e&&e.isMentioned}const a={entityId:e,feedId:t,userId:Qe()._id},i=null===(s=Se(["subChannelMarker","get",de("subChannelMarker")(a)]))||void 0===s?void 0:s.data;return!!i&&i.hasMentioned}const Vn=["broadcast","conversation","community"],Hn=({channelType:e})=>Vn.includes(e);function Wn(e){var{channelId:t,channelPublicId:n,channelType:r,childCount:s,creatorId:o,creatorPublicId:a,lastMessageId:i,lastMessageTimestamp:c,messageFeedId:l,name:d}=e,u=zt(e,["channelId","channelPublicId","channelType","childCount","creatorId","creatorPublicId","lastMessageId","lastMessageTimestamp","messageFeedId","name"]);return Object.assign(Object.assign({get unreadCount(){return function(e,t,n){var r,s;if(n)return n.unreadCount;const o=we();if(o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()){const e=null===(r=Se(["subChannelUnreadInfo","get",t]))||void 0===r?void 0:r.data;return e?e.isDeleted?0:e.unreadCount:0}const a={entityId:e,feedId:t,userId:Qe()._id},i=null===(s=Se(["subChannelMarker","get",de("subChannelMarker")(a)]))||void 0===s?void 0:s.data;return i?i.unreadCount:0}(t,l)},get hasMentioned(){return Qn(t,l)},get isMentioned(){return Qn(t,l)}},u),{channelId:n,creatorId:a,displayName:d,lastActivity:c,latestMessageId:i,messageCount:s,subChannelId:l,isUnreadCountSupport:Hn({channelType:r})})}function Jn(e,t,n){var r;const s=(e=>{const t=we(),{objectSyncMap:n}=t;return Object.assign(Object.assign({},e),{referenceId:ue(e.messageId)?e.messageId:n.get(e.messageId)})})(e),{channelPublicId:o,childCount:a,creatorPublicId:i,mentionedUsers:c,messageFeedId:l,myReactions:d,reactionCount:u,reactions:h,referenceId:p,segment:f,messageId:g,creatorId:m}=s,y=zt(s,["channelPublicId","childCount","creatorPublicId","mentionedUsers","messageFeedId","myReactions","reactionCount","reactions","referenceId","segment","messageId","creatorId"]);let v;p&&(v=Se(["message","get",p])),v||(v=Se(["message","get",g]));const b=Object.assign(Object.assign({},y),{messageId:g,channelId:o,channelSegment:f,childrenNumber:a,creatorId:i,creatorPrivateId:e.creatorId,reactions:null!=h?h:{},myReactions:d||(null!==(r=null==v?void 0:v.data.myReactions)&&void 0!==r?r:[]),reactionsCount:u,subChannelId:l,uniqueId:v?v.data.uniqueId:g,referenceId:p,syncState:"synced"});return c&&(b.mentionees=c.map((e=>"channel"===e.type?e:{type:"user",userIds:e.userPublicIds}))),t&&t.length&&n&&((e,t,n)=>{const r=we(),s=Se(["message","get",e.messageId]),o=(null==s?void 0:s.data.myReactions)||[];Object.assign(e,{myReactions:o});const a=t[0];a&&a.userId===r.userId&&("message.reactionAdded"!==n||o.includes(a.reactionName)||Object.assign(e,{myReactions:[...o,a.reactionName]}),"message.reactionRemoved"===n&&o.includes(a.reactionName)&&Object.assign(e,{myReactions:o.filter((e=>e!==a.reactionName))}))})(b,t,n),b}const Gn={},Yn=async(e,t)=>{const n=e.messages.map((({messageId:e})=>e));if(n.length>0){Kt({messages:(r=e).messages.map((e=>Jn(e,r.reactions)))});const t=n.join("");Gn[t]&&clearTimeout(Gn[t]),Gn[t]=setTimeout((()=>{try{(async e=>{const t=we();t.log("channel/getMessageMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/messages",{params:{messageIds:e}}),{contentMarkers:r,feedMarkers:s,userMarkers:o}=n,a=t.cache&&Date.now();t.cache&&Kt({contentMarkers:r,feedMarkers:s,userMarkers:o},{cachedAt:a}),Ze("local.feedMarker.fetched",{feedMarkers:s}),Ze("local.messageMarker.fetched",{contentMarkers:r}),Ze("local.userMarker.fetched",{userMarkers:o})})(n)}catch(e){}}),2e3)}var r;const{messageFeeds:s}=e,o=zt(e,["messageFeeds"]);return s&&s.length>0&&(null==s||s.forEach((e=>{var t,n;const r=null!==(n=null===(t=Se(["subChannel","get",e.messageFeedId]))||void 0===t?void 0:t.data)&&void 0!==n?n:{},s=zt(Wn(e),["unreadCount","hasMentioned","isMentioned"]);Tn(e.messageFeedId,r,s)}))),Object.assign(Object.assign({},o),{messages:e.messages.map((n=>Jn(n,e.reactions,t)))})};function Xn(e){var{subChannelId:t,mentionees:n,dataType:r,data:s}=e,o=zt(e,["subChannelId","mentionees","dataType","data"]);return r===P.IMAGE||r===P.FILE?Object.assign({messageFeedId:t,mentionedUsers:n,dataType:r,data:Object.assign({caption:""},s)},o):Object.assign({messageFeedId:t,mentionedUsers:n,dataType:r,data:s},o)}function Zn(e){var{sortBy:t,subChannelId:n,tags:r,includingTags:s,excludingTags:o,includeDeleted:a,aroundMessageId:i,limit:c,type:l}=e,d=zt(e,["sortBy","subChannelId","tags","includingTags","excludingTags","includeDeleted","aroundMessageId","limit","type"]);const u=Object.assign(Object.assign({},d),{messageFeedId:n,isDeleted:zn(a),options:{sortBy:t,limit:c||j,around:i}});return r&&(u.includeTags=r),s&&(u.includeTags=s),l&&(u.dataType=l),o&&(u.excludeTags=o),u}const er=["broadcast","conversation","community"],tr=({channelType:e})=>er.includes(e),nr=async e=>{const t=e.messageFeeds.filter(tr).map((({messageFeedId:e})=>e));if(t.length>0){(e=>{Kt({messageFeeds:e.messageFeeds.map((e=>Wn(e)))})})(e);try{await(async(e,t={limit:100})=>{const n=we();n.log("channel/getSubChannelMarkers",e,t);const{data:r}=await n.http.get("/api/v1/markers/message-feeds",{params:{messageFeedIds:e,options:{token:Y(t,"skiplimit")}}}),{paging:s}=r,o=zt(r,["paging"]),{userEntityMarkers:a,userFeedMarkers:i,userMarkers:c,feedMarkers:l}=o;n.isUnreadCountEnabled&&n.getMarkerSyncConsistentMode()&&Fn({feedMarkers:l,userFeedMarkers:i});const d=Wt(a),u=Jt(i),h=n.cache&&Date.now();n.cache&&Kt({userEntityMarkers:d,userFeedMarkers:u,userMarkers:c},{cachedAt:h}),Ze("local.channelMarker.fetched",{userEntityMarkers:d}),Ze("local.subChannelMarker.fetched",{userFeedMarkers:u}),Ze("local.userMarker.fetched",{userMarkers:c});const p=X(s.next);return{data:u,cachedAt:h,prevPage:X(s.previous),nextPage:p}})(t)}catch(e){}}kn(e);const n=e.messageFeeds.map(Wn),r=e.messages.map((e=>Jn(e)));return Object.assign(Object.assign({},e),{messageFeeds:n,messages:r})};class rr{constructor(){this._sessionState="notLoggedIn",this._listener=new Map}onSessionStateChange(e){return this._listener.set(e,e),()=>{this._listener.delete(e)}}setSessionState(e){this._sessionState!==e&&(this._sessionState=e,this._listener.forEach((t=>t(e))))}destroy(){this._listener.clear()}}let sr;var or=()=>(sr||(sr=new rr),sr);const ar=e=>or().onSessionStateChange(e),ir=(e,t)=>{const n=setInterval(e,t);return()=>clearInterval(n)},cr=e=>{if("undefined"!=typeof window&&window.addEventListener)return window.addEventListener("online",e),()=>window.removeEventListener("online",e);if("undefined"!=typeof document&&document.addEventListener)return document.addEventListener("online",e),()=>document.removeEventListener("online",e);if("undefined"!=typeof navigator&&"ReactNative"===navigator.product){let t=()=>{};return import("@react-native-community/netinfo").then((n=>{t=n.addEventListener((t=>{t.isConnected&&e()}))})),()=>{t()}}return console.error("Unsupported environment"),()=>console.error("Unsupported environment")},lr=(e,t)=>{const{log:n,cache:r}=we(),s=[e,L,t];if(!r)return;n("cache/api/isInTombstone",s);const o=Se(s),{lifeSpan:a}=ae("cache_then_server",18e4);if(o&&se(o.data,a))throw new ge("Item not found!",400400,"error")},dr=async e=>{const t=we();t.log("channel/getSubChannel",e),lr("subChannel",e);try{const n=await t.http.get(`/api/v5/message-feeds/${encodeURIComponent(e)}`),r=await nr(n.data),s=t.cache&&Date.now();return t.cache&&Kt(r,{cachedAt:s}),Ze("local.message-feed.fetched",r),{data:r.messageFeeds[0],cachedAt:s}}catch(t){throw V(null==t?void 0:t.code)&&$t("subChannel",e),t}};dr.locally=e=>{const t=we();if(t.log("channel/getSubChannel.locally",e),!t.cache)return;const n=Se(["subChannel","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};let ur=!1,hr=[];const pr={},fr=async()=>{const e=Object.entries(pr).filter((([,e])=>e)).map((([e])=>e));return 0!==e.length&&(async e=>{const t=we();t.log("subChannel/readingAPI",e);const{data:n}=await t.http.post("/api/v1/markers/message-feeds/reading",{messageFeedIds:e}),{userEntityMarkers:r,userFeedMarkers:s,feedMarkers:o,userMarkers:a}=n,i=Wt(r),c=Jt(s),l=t.cache&&Date.now();return t.cache&&Kt({userEntityMarkers:i,userFeedMarkers:c,feedMarkers:o,userMarkers:a},{cachedAt:l}),Ze("local.feedMarker.fetched",{feedMarkers:o}),Ze("local.channelMarker.fetched",{userEntityMarkers:i}),Ze("local.subChannelMarker.fetched",{userFeedMarkers:c}),Ze("local.userMarker.fetched",{userMarkers:a}),!0})(e)},gr=()=>{ur=!1},mr=()=>(ur=!0,ar((e=>{"notLoggedIn"===e&&gr()})),()=>{gr()}),yr=async e=>{const t=await(async e=>{const t=dr.locally(e);if(t)return t.data.channelId;const{data:n}=await dr(e);return n.channelId})(e),n=it({channelId:t,subChannelId:e});hr.push(pt(n))};ir((async()=>{ur&&await fr()}),3e4);const vr=async e=>{const t=we();t.log("channel/getSubChannels",e);const n=await t.http.get("/api/v5/message-feeds/list",{params:{messageFeedIds:e.map(encodeURIComponent)}}),r=await nr(n.data),s=t.cache&&Date.now();return t.cache&&Kt(r,{cachedAt:s}),Ze("local.message-feed.fetched",r),{data:r.messageFeeds,cachedAt:s}};vr.locally=e=>{var t;const n=we();if(n.log("channel/getSubChannels.locally",e),!n.cache)return;const r=e.map((e=>Se(["subChannel","get",e]))).filter(Boolean);if((null==r?void 0:r.length)<e.length)return;return{data:r.map((({data:e})=>e)),cachedAt:(null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0]).cachedAt}};const br=async(e=!0)=>{var t;const n=null===(t=Se(["MessagePreviewSetting"]))||void 0===t?void 0:t.data;if(!e&&n)return n;const r=await(async()=>{const e=we(),{data:t}=await e.http.get("/api/v3/network-settings/chat");return t})();var s;return(s=r).messagePreview.enabled?s.messagePreview.isIncludeDeleted?"message-preview-include-deleted":"message-preview-not-include-deleted":"no-message-preview"},wr=async()=>{const e=we(),{data:t}=await e.http.get("/api/v3/network-settings/social");return t.socialNetworkSetting},Cr=(e,t)=>{var n;const r=null===(n=Se(["user","get",e]))||void 0===n?void 0:n.data;return!!r&&r.permissions.some((e=>e===t))},Ir=e=>{const{userId:t}=we();return{currentUser:()=>Cr(t,e),community:n=>((e,t,n)=>{var r;if(!e)return!1;const s=null===(r=Se(["communityUsers","get",`${n}#${e}`]))||void 0===r?void 0:r.data;return!!s&&(!!s.permissions.some((e=>e===t))||Cr(e,t))})(t,e,n),channel:n=>((e,t,n)=>{var r;if(!e)return!1;const s=null===(r=Se(["channelUsers","get",`${n}#${e}`]))||void 0===r?void 0:r.data;return!!s&&(!!s.permissions.some((e=>e===t))||Cr(e,t))})(t,e,n)}},Sr=async e=>{const t=we();if(t.log("channel/markerSync"),0===e.length)return!1;const{data:n}=await t.http.post("/api/v3/allowlists/verify",{data:e});return n.success},_r=async e=>{const t=we();if(t.log("channel/markerSync"),0===e.length)return!1;const{data:n}=await t.http.post("/api/v3/blocklists/verify",{data:e});return n.success},kr=async()=>{const e=we(),{data:t}=await e.http.get("/api/v3/network-settings/feed-setting");return Object.fromEntries(t.feedSettings.map((({feedType:e,contentSettings:t})=>[e,t])))},Or={notLoggedIn:["establishing"],terminated:["establishing"],establishing:["notLoggedIn","established"],established:["notLoggedIn","terminated","tokenExpired","establishing"],tokenExpired:["establishing"]},Tr=e=>{const t=we();t.log("client/api/setSessionState",e);const{sessionState:n}=t;if(n===e)return!1;if(!((e,t)=>Or[e].includes(t))(n,e))throw new fe(`Session state cannot change from ${n} to ${e}`,8e5,"error");return t.sessionState=e,or().setSessionState(e),!0},Er=async e=>{const t=we();Tr("establishing");const{accessToken:n,users:r,expiresAt:s,issuedAt:o}=await(async({params:e,options:t})=>{const n=we();n.log("client/api/getToken",e);const r=Bt(),{data:s}=await n.http.post("/api/v5/sessions",Object.assign(Object.assign({},e),{deviceInfo:r}),{headers:{"X-API-Key":n.apiKey,"set-access-token-cookie":(null==t?void 0:t.setAccessTokenCookie)||!1}});return s})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.ws.io.opts.query={token:n},t.token={accessToken:n,issuedAt:o,expiresAt:s},Tr("established"),{accessToken:n,users:r}},Ar=e=>{const t=Ie(["subChannelUnreadInfo","get"]);if(t){(null==t?void 0:t.filter((({data:t})=>t.channelId===e))).forEach((({key:e,data:t})=>{_e(e,Object.assign(Object.assign({},t),{isDeleted:!0}))}))}},Mr=e=>{var t;const n=["channelUnreadInfo","get",e];(null===(t=Se(n))||void 0===t?void 0:t.data)&&Te(n)},Pr=[];let Rr=null;const Ur=e=>{if(0===Pr.length){const e=we(),t=async t=>{const n=await Bn(t);e.isUnreadCountEnabled&&e.getMarkerSyncConsistentMode()&&n.channels.forEach((e=>{Ar(e.channelId),Mr(e.channelId)})),Kt(n),Pr.forEach((e=>e(n.channels[0])))};Rr=Xe(e,"onChannelDeleted","channel.deleted",t)}return Pr.push(e),()=>(e=>{const t=Pr.indexOf(e);t>-1&&Pr.splice(t,1),0===Pr.length&&(null==Rr||Rr())})(e)},jr=[];let xr=null;const Dr=e=>{const t=we();return xr=Xe(t,"onChannelMemberBanned","channel.banned",(async e=>{const n=await Bn(e),{channels:r,channelUsers:s}=n,o=s.some((e=>"banned"===e.membership&&e.userId===t.userId));t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&o&&n.channels.forEach((e=>{Ar(e.channelId),Mr(e.channelId)})),Kt(n),jr.forEach((e=>e(r[0],s.find((e=>"banned"===e.membership)))))})),jr.push(e),()=>(e=>{const t=jr.indexOf(e);t>-1&&jr.splice(t,1),0===jr.length&&(null==xr||xr())})(e)};function Nr(e){return{users:e.users.map(Un),files:e.files}}const Br=(e,t)=>{const n=we();return Xe(n,e,e,(e=>{const r=Nr(e);n.cache&&Kt(r),t(r.users[0])}))},qr=e=>Br("user.deleted",e);class Fr{constructor(){this.TIMER_INTERVAL_MS=B,this.BUFFER_ID_LIMIT=100,this.buffer={channel:[],userMessageFeedMarker:[]},this.isResolvingTask=!1,this.connectionListener=[],this.isConnected=!0,this.addConnectionListener()}startResolver(){this.timer||(this.timer=setInterval((()=>{this.isConnected&&this.resolveObjects()}),this.TIMER_INTERVAL_MS))}stopResolver(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}resolve(e,t){const n=this.getBuffer(t);n.includes(e)||(n.length>=this.BUFFER_ID_LIMIT&&n.shift(),n.push(e))}addConnectionListener(){this.connectionListener.length>0||(this.connectionListener.push(cr((()=>{this.isConnected=!0}))),this.connectionListener.push((e=>{if("undefined"!=typeof window&&window.addEventListener)return window.addEventListener("offline",e),()=>window.removeEventListener("offline",e);if("undefined"!=typeof document&&document.addEventListener)return document.addEventListener("offline",e),()=>document.removeEventListener("offline",e);if("undefined"!=typeof navigator&&"ReactNative"===navigator.product){let t=()=>{};return import("@react-native-community/netinfo").then((n=>{t=n.addEventListener((t=>{t.isConnected||e()}))})),()=>{t()}}return console.error("Unsupported environment"),()=>console.error("Unsupported environment")})((()=>{this.isConnected=!1}))))}removeConnectionListener(){this.connectionListener.length>0&&this.connectionListener.forEach((e=>e()))}resolveObjects(){if(this.isResolvingTask)return;this.isResolvingTask=!0;const e=this.getBuffer("channel"),t=this.getBuffer("userMessageFeedMarker");this.clearBuffer(),e.length>0&&(async e=>{const{data:t}=await Kn(e);Ze("local.channel.resolved",t)})(e),t.length>0&&(async e=>{const t=await qn(e),{feedMarkers:n,userFeedMarkers:r}=t;Fn({feedMarkers:n,userFeedMarkers:r}),Ze("local.userMessageFeedMarkers.resolved",{feedMarkers:n,userFeedMarkers:r})})(t),this.isResolvingTask=!1}clearBuffer(){this.buffer={channel:[],userMessageFeedMarker:[]}}getBuffer(e){return this.buffer[e]}onSessionEstablished(){this.startResolver(),this.addConnectionListener()}onSessionDestroyed(){this.stopResolver(),this.clearBuffer(),this.isResolvingTask=!1,this.removeConnectionListener()}onTokenExpired(){this.stopResolver()}}let Lr=null;var Kr=()=>(Lr||(Lr=new Fr),Lr);const $r=async()=>{const e=we();return e.log("client/api/disconnectClient"),e.mqtt.connected&&e.mqtt.disconnect(),e.ws.connected&&e.ws.disconnect(),"established"===e.sessionState&&Tr("notLoggedIn"),e.emitter.all.clear(),e.ws.removeAllListeners(),e.mqtt.removeAllListeners(),e.userId=void 0,e.token=void 0,e.http.defaults.headers.common.Authorization="",e.http.defaults.metadata={tokenExpiry:"",isGlobalBanned:!1,isUserDeleted:!1},e.ws.io.opts.query={token:""},"undefined"!=typeof document&&(document.cookie="_ascSession=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"),"tokenExpired"!==e.sessionState&&e.cache&&(e.cache={data:{}}),!0},zr=e=>{const t=we();Tr("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,$r()},Qr=["disconnected","error","connect_error","reconnect_error","reconnect_failed"],Vr=e=>{const t=we(),n=Qr.map((n=>Xe(t,`client/onConnectionError(${n})`,n,(t=>{const r=(null==t?void 0:t.code)?new fe(t.message,t.code,"fatal"):new ye(n);e(r)}))));return()=>{n.forEach((e=>e()))}},Hr=e=>{const t=we();return Xe(t,"client/onConnectionError(user.didGlobalBan)","user.didGlobalBan",e)},Wr=e=>{const t=de("channelMarker")({userId:Qe()._id,entityId:e.channelId});Te(["channelMarker","get",t],!0)},Jr=[];let Gr=null;const Yr=e=>{if(0===Jr.length){const e=we();Gr=Xe(e,"onChannelCreated","channel.created",(async e=>{const t=await Bn(e);Kt(t),Jr.forEach((e=>e(t.channels[0])))}))}return Jr.push(e),()=>(e=>{const t=Jr.indexOf(e);t>-1&&Jr.splice(t,1),0===Jr.length&&(null==Gr||Gr())})(e)},Xr=[],Zr=[],es=e=>{const t=we();if(0===Xr.length){const e=async e=>{const t=await Bn(e);Kt(t),Xr.forEach((e=>e(t.channels[0])))};Zr.push(Xe(t,"onChannelUpdated","channel.updated",e)),Zr.push(Xe(t,"onChannelUpdated","local.channel.updated",(e=>Xr.forEach((t=>t(e.channels[0]))))))}return Xr.push(e),()=>(e=>{const t=Xr.indexOf(e);t>-1&&Xr.splice(t,1),0===Xr.length&&Zr.forEach((e=>e()))})(e)},ts=[];let ns=null;const rs=e=>{if(0===ts.length){const e=we();ns=Xe(e,"onChannelJoined","channel.joined",(async e=>{const t=await Bn(e),{channels:n,channelUsers:r}=t;Kt(t),ts.forEach((e=>e(n[0],r[0])))}))}return ts.push(e),()=>(e=>{const t=ts.indexOf(e);t>-1&&ts.splice(t,1),0===ts.length&&(null==ns||ns())})(e)},ss=[];let os=null;const as=e=>{if(0===ss.length){const e=we(),t=async t=>{const{userId:n}=we(),{channelUsers:r}=t,s=r.some((e=>e.userId===n)),o=await Bn(t,{isMessagePreviewUpdated:s});e.isUnreadCountEnabled&&e.getMarkerSyncConsistentMode()&&s&&o.channels.forEach((e=>{Ar(e.channelId),Mr(e.channelId)}));const{channels:a,channelUsers:i}=o;Kt(o),ss.forEach((e=>e(a[0],i[0])))};os=Xe(e,"onChannelLeft","channel.left",t)}return ss.push(e),()=>(e=>{const t=ss.indexOf(e);t>-1&&ss.splice(t,1),0===ss.length&&(null==os||os())})(e)},is=[];let cs=null;const ls=e=>{if(0===is.length){const e=we();cs=Xe(e,"onChannelMuted","channel.setMuted",(async e=>{const t=await Bn(e);Kt(t),is.forEach((e=>e(t.channels[0])))}))}return is.push(e),()=>(e=>{const t=is.indexOf(e);t>-1&&is.splice(t,1),0===is.length&&(null==cs||cs())})(e)},ds=[];let us=null;const hs=e=>{if(0===ds.length){const e=we();us=Xe(e,"onChannelMemberAdded","channel.membersAdded",(async e=>{const t=await Bn(e),{channels:n,channelUsers:r}=t;Kt(t),ds.forEach((e=>e(n[0],r.find((e=>"member"===e.membership)))))}))}return ds.push(e),()=>(e=>{const t=ds.indexOf(e);t>-1&&ds.splice(t,1),0===ds.length&&(null==us||us())})(e)},ps=[];let fs=null;const gs=e=>{if(0===ps.length){const e=we();fs=Xe(e,"onChannelMemberRemoved","channel.membersRemoved",(async e=>{const t=await Bn(e),{channels:n,channelUsers:r}=t;Kt(t),ps.forEach((e=>e(n[0],r[0])))}))}return ps.push(e),()=>(e=>{const t=ps.indexOf(e);t>-1&&ps.splice(t,1),0===ps.length&&(null==fs||fs())})(e)},ms=[];let ys=null;const vs=e=>{if(0===ms.length){const e=we();ys=Xe(e,"onChannelMemberUnbanned","channel.unbanned",(async e=>{const t=await Bn(e),{channels:n,channelUsers:r}=t;Kt(t),ms.forEach((e=>e(n[0],r.find((e=>"none"===e.membership)))))}))}return ms.push(e),()=>(e=>{const t=ms.indexOf(e);t>-1&&ms.splice(t,1),0===ms.length&&(null==ys||ys())})(e)},bs=[];let ws=null;const Cs=e=>{if(0===bs.length){const e=we();ws=Xe(e,"onChannelMemberRoleAdded","local.channel-moderator.role-added",(async e=>{const{channels:t,channelUsers:n}=e;bs.forEach((e=>e(t[0],n.find((e=>"member"===e.membership)))))}))}return bs.push(e),()=>(e=>{const t=bs.indexOf(e);t>-1&&bs.splice(t,1),0===bs.length&&(null==ws||ws())})(e)},Is=[];let Ss=null;const _s=e=>{if(0===Is.length){const t=we();Ss=Xe(t,"onChannelMemberRoleRemoved","local.channel-moderator.role-removed",(async t=>{const{channels:n,channelUsers:r}=t;e(n[0],r.find((e=>"member"===e.membership)))}))}return Is.push(e),()=>(e=>{const t=Is.indexOf(e);t>-1&&Is.splice(t,1),0===Is.length&&(null==Ss||Ss())})(e)},ks=e=>{const t=we();return Xe(t,"feedMarker/onFeedMarkerUpdated","marker.feed-updated",(t=>{Kt(t),e(t.feedMarkers[0])}))};function Os(e){const t=we(),{objectSyncMap:n}=t;return e.map((e=>{var t;return ue(e.messageId)?e.messageId:null!==(t=n.get(e.messageId))&&void 0!==t?t:e.messageId})).filter(Boolean)}const Ts=e=>{const t=we(),n=Qe(),r=[Xe(t,"message/onMessageCreated","message.created",(async r=>{const s=await Yn(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&r.messages.forEach((e=>{(e=>{var t;const n=we(),r=["subChannelUnreadInfo","get",e.messageFeedId],s=null===(t=Se(r))||void 0===t?void 0:t.data;if(!s)return;const o=s.lastSegment<e.segment?e.segment:s.lastSegment,a=o-s.readToSegment;let{lastMentionSegment:i}=s;e.mentionedUsers&&e.mentionedUsers.length>0&&e.mentionedUsers.forEach((t=>{("channel"===t.type||"user"===t.type&&n.userId&&t.userPublicIds.includes(n.userId))&&(i=e.segment)}));const c=Object.assign(Object.assign({},s),{lastMentionSegment:i,lastSegment:o,isMentioned:!(s.readToSegment>=i),unreadCount:Math.max(a,0)});_e(r,c)})(e),fn(e.channelId)})),Kt(s),s.messages.forEach((t=>{t.creatorPrivateId===n._id&&vn(t),e(t)}))}))];return()=>{r.forEach((e=>e()))}},Es=e=>{const t=we(),n=[Xe(t,"message/onMessageCreated","local.message.created",(async t=>(Kt(t),t.messages.forEach((t=>{e(t)})))))];return()=>{n.forEach((e=>e()))}},As=e=>{const t=we();return Xe(t,"onSubChannelCreated","message-feed.created",(async n=>{const r=await nr(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&n.messageFeeds.forEach((e=>{(e=>{const{channelId:t,subChannelId:n,createdAt:r,updatedAt:s}=e,o={channelId:t,subChannelId:n,unreadCount:0,readToSegment:0,lastMentionSegment:0,lastSegment:0,isMentioned:!1,isDeleted:!1,createdAt:r,updatedAt:s};_e(["subChannelUnreadInfo","get",o.subChannelId],o)})({channelId:e.channelId,subChannelId:e.messageFeedId,createdAt:e.createdAt,updatedAt:e.updatedAt})})),Kt(r),e(r.messageFeeds[0])}))},Ms=e=>{const t=we(),n=[Xe(t,"onSubChannelDeleted","message-feed.deleted",(async n=>{const r=await nr(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&r.messageFeeds.forEach((e=>{(e=>{var t;const n=["subChannelUnreadInfo","get",e],r=null===(t=Se(n))||void 0===t?void 0:t.data;r&&_e(n,Object.assign(Object.assign({},r),{isDeleted:!0}))})(e.subChannelId),fn(e.channelId)})),Kt(r),e(r.messageFeeds[0])})),Xe(t,"local.message-feed.deleted","local.message-feed.deleted",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}},Ps=async e=>{const t=we();t.log("channel/markerSync");const{data:n}=await t.http.post("/api/v1/markers/sync",{deviceLastSyncAt:e}),{userEntityMarkers:r,userFeedMarkers:s,feedMarkers:o,userMarkers:a}=n,i=Wt(r),c=Jt(s),l=t.cache&&Date.now();return t.cache&&Kt({userEntityMarkers:i,userFeedMarkers:c,feedMarkers:o,userMarkers:a},{cachedAt:l}),Ze("local.feedMarker.fetched",{feedMarkers:o}),Ze("local.channelMarker.fetched",{userEntityMarkers:i}),Ze("local.subChannelMarker.fetched",{userFeedMarkers:c}),Ze("local.userMarker.fetched",{userMarkers:a}),{data:n,hasMore:n.feedMarkers.length>0}},Rs=()=>{const e=we();if(e.log("client/api/isUnreadCountEnabled",e.isUnreadCountEnabled),!e)throw new fe("There is no active client",8e5,"fatal");return!e.isUnreadCountEnabled&&(e.isUnreadCountEnabled=!0,e.emitter.emit("unreadCountEnabled",!0),!0)};let Us=!1,js=[],xs=!1,Ds=!0,Ns=null;const Bs=e=>{null!=e&&(!Ns||e.getTime()>Ns.getTime())&&(Ns=e)},qs=async()=>{const{data:e}=await $n();null!=e&&Bs(new Date(e.lastSyncAt))};let Fs=[];const Ls=e=>{Fs=e},Ks=e=>Fs.push(e),$s=async()=>{if(!xs&&0!==Fs.length)try{xs=!0,Fs=[];const e=await Ps((null==Ns?new Date:Ns).toISOString()),t=e.data.userMarkers.reduce(((e,t)=>null==e||e.getTime()<new Date(t.lastSyncAt).getTime()?new Date(t.lastSyncAt):e),null);Bs(t),e.hasMore&&Fs.push("has_more")}catch(e){}finally{xs&&(xs=!1)}},zs=()=>{js.length>0||js.push(cr((()=>{Fs.push("resume")})),Ts((e=>{const t=we();tr(e)&&e.creatorId!==t.userId&&Fs.push("new message")})),Yr((()=>Fs.push("subchannel is created"))),Ur((()=>Fs.push("subchannel is deleted"))),rs((()=>Fs.push("subchannel is joined"))),as((()=>Fs.push("subchannel is left"))),As((()=>Fs.push("subchannel is created"))),Ms((()=>setTimeout((()=>Fs.push("subchannel is deleted")),2e3))),ks((()=>Fs.push("feed marker updated"))),(e=>{const t=we();return Xe(t,"UserMarker/onUserMarkerSync","marker.user-sync",(t=>{const{userMarkers:n,userEntityMarkers:r,userFeedMarkers:s}=t,o=zt(t,["userMarkers","userEntityMarkers","userFeedMarkers"]),a=Wt(r),i=Jt(s);Kt(Object.assign({userMarkers:n,userEntityMarkers:a,userFeedMarker:i},o)),e(n[0])}))})((()=>Fs.push("feed marker updated"))),(e=>{const t=we();return Xe(t,"feedMarker/onUserFeedMarkerUpdated","marker.userFeed-updated",(t=>{t.feedMarkers.forEach((t=>{e(t)}))}))})((()=>Fs.push("feed marker updated"))))},Qs=()=>{js.forEach((e=>e())),js=[]},Vs=async()=>(await qs(),Ks("start syncing"),Ds=!0,Us=!0,zs(),Qs),Hs=()=>{Us=!1,Ls([]),Qs()};ir((async()=>{Us&&await $s()}),2e3);const Ws=()=>Ds;let Js=[];const Gs=async(e,t,n)=>{const r=we();let s;r.log("client/api/connectClient",Object.assign({apiKey:r.apiKey,sessionState:r.sessionState},e)),r.userId&&r.userId!==e.userId&&(await $r(),Js.forEach((e=>e())),Js=[]);const o=await Nt();try{const{users:n}=await Er({params:Object.assign(Object.assign({},e),{displayName:null==e?void 0:e.displayName,deviceId:(null==e?void 0:e.deviceId)||o}),options:{setAccessTokenCookie:!0}}),c=n.find((t=>t.userId===e.userId));if(null==c)throw new fe(`${e.userId} has not been founded`,8e5,"error");if(c.isDeleted)return zr("userDeleted"),!1;if(c.isGlobalBanned)return zr("globalBan"),!1;a=r.ws,i=r.emitter,Ge.forEach((e=>{a.on(e,(t=>{i.emit(e,t)}))})),r.ws.open(),r.userId=c.userId,r.sessionHandler=t,s=r.accessTokenExpiryWatcher(t),Ve(c)}catch(e){throw or().setSessionState("notLoggedIn"),e}var a,i;if(!0!==(null==n?void 0:n.disableRTE)&&async function(){await nt()}(),await(async()=>{var e;const t=await br();if(t===(null===(e=Se(["MessagePreviewSetting"]))||void 0===e?void 0:e.data))return;_e(["MessagePreviewSetting"],t);const n=[],r=[];if("no-message-preview"===t){const e=Ie(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{Te(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&r.push(t.subChannelId)}))}else if("message-preview-not-include-deleted"===t){const e=Ie(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{(null==t?void 0:t.isDeleted)&&(Te(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&r.push(t.subChannelId))})),0!==n.length&&await Kn(n),0!==r.length&&await vr(r)}})(),0===Js.length){Js.push(Hr((e=>{zr("globalBan"),Js.forEach((e=>e())),s()})),(e=>{const t=we();return Xe(t,"client/onTokenTerminated","tokenTerminated",e)})((e=>{zr(),Js.forEach((e=>e())),s()})),qr((e=>{e.userId===r.userId&&(zr("userDeleted"),Js.forEach((e=>e())),s())})),(e=>{const t=we();return Xe(t,"client/onTokenExpired","tokenExpired",e)})((e=>{or().setSessionState(e),$r(),Js.forEach((e=>e()))})),Ur(Wr),Dr(Wr),mr(),(()=>{const e=sn();return e.established(),ar((t=>{"established"===t?e.established():e.handleTokenExpired()})),()=>{e.destroy()}})(),(()=>{const e=yn();return e.startSyncReadReceipt(),ar((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=Kr();return e.startResolver(),ar((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})());const e=await Vs();Js.push(e)}return!0},Ys=()=>{let e,t=!1;const n=we();n.log("initiating access token renewal");const r=async r=>{const{userId:s,displayName:o}=Qe(),a={userId:s,displayName:o,authToken:r,deviceId:await Nt()};"tokenExpired"===n.sessionState&&n.sessionHandler?await Gs(a,n.sessionHandler):await Er({params:a,options:{setAccessTokenCookie:!0}}),t=!0,e&&clearTimeout(e)};return{renew:()=>{t?console.log("'renew' method can be called only once per renewal instance"):r()},renewWithAuthToken:e=>{t?console.log("'renewWithAuthToken' method can be called only once per renewal instance"):r(e)},unableToRetrieveAuthToken:()=>{e=setTimeout((()=>{var e;null===(e=n.sessionHandler)||void 0===e||e.sessionWillRenewAccessToken(Ys())}),F)}}},Xs=3e5,Zs=e=>{const t=setInterval((()=>{const t=we();if(!t.token)return;const{issuedAt:n,expiresAt:r}=t.token;if((e=>Date.now()>Date.parse(e)-Xs)(r))return Ze("tokenExpired","tokenExpired"),void Je((()=>e.sessionWillRenewAccessToken(Ys())));(e=>{const{expiresAt:t,issuedAt:n}=e,r=Date.parse(t),s=Date.parse(n),o=Date.now();return o>s+.8*(r-s-Xs)&&o<r})({expiresAt:r,issuedAt:n})&&e.sessionWillRenewAccessToken(Ys())}),F);return()=>clearInterval(t)};var eo;class to{constructor(){eo.set(this,e.FileAccessTypeEnum.PUBLIC)}setFileAccessType(e){!function(e,t,n,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===r?s.call(e,n):s?s.value=n:t.set(e,n)}(this,eo,e,"f")}getFileAccessType(){return function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)}(this,eo,"f")}}let no;eo=new WeakMap;var ro=()=>(no||(no=new to),no);const so=e=>{const t=we();return Xe(t,"channelMarker/onChannelMarkerFetched","local.channelMarker.fetched",(t=>{t.userEntityMarkers.forEach((t=>{e(t)}))}))},oo=e=>{const t=we();return Xe(t,"subChannelMarker/onSubChannelMarkerFetched","local.subChannelMarker.fetched",(t=>{t.userFeedMarkers.forEach(e)}))},ao=e=>{const t=we();return Xe(t,"subChannelMarker/onSubChannelMarkerUpdated","local.subChannelMarker.updated",(t=>{e(t.userFeedMarkers)}))},io=e=>{const t=we();return Xe(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers)}))},co=e=>{const t=we();return Xe(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers[0])}))},lo=e=>{const t=we();return Xe(t,"messageMarker/onMessageMarkerFetched","local.messageMarker.fetched",(t=>{e(t.contentMarkers[0])}))},uo=e=>{const t=we();return Xe(t,"messageMarker/onMessageMarked","marker.marked-message",(t=>{var n,r,s;Kt(t);const o=Ie(["message","collection"]),{contentMarkers:a,feedMarkers:i}=t;if(o&&(null==o?void 0:o.length)>0&&(null==i?void 0:i.length)>0){const e=o.filter((e=>{var t,n;return(null===(n=null===(t=e.data)||void 0===t?void 0:t.query)||void 0===n?void 0:n.subChannelId)===i[0].feedId}));if(e.length>0&&(null==a?void 0:a.length)>0){(null!==(s=null===(r=null===(n=e[0].data)||void 0===n?void 0:n.data)||void 0===r?void 0:r.map((e=>Se(["message","get",e]))).map((({data:e})=>e)).filter(Boolean))&&void 0!==s?s:[]).forEach((e=>{var t,n;const r=["messageMarker","get",de("messageMarker")({creatorId:e.creatorPrivateId,feedId:e.subChannelId,contentId:e.messageId})],s=null===(t=Se(r))||void 0===t?void 0:t.data;if(!s)return;const o=a[0].feedId===s.feedId,i=a[0].readCount>s.readCount,c=(null===(n=a[0])||void 0===n?void 0:n.deliveredCount)>s.deliveredCount;if(o){const e=Object.assign(Object.assign({},s),{readCount:i?a[0].readCount:s.readCount,deliveredCount:c?a[0].deliveredCount:s.deliveredCount});_e(r,e)}}))}}e(t.contentMarkers[0])}))};function ho(e){return"object"==typeof e&&null!==e}const po=e=>{if(!ho(e))return e;const t=Object.entries(e).map((([t,n])=>{const r=Object.getOwnPropertyDescriptor(e,t);return"function"==typeof(null==r?void 0:r.get)?[t,r.get.call(e)]:[t,n]}));return Object.fromEntries(t)},fo=e=>{if(!ho(e))return e;const t=Object.entries(e).map((([e,t])=>"function"==typeof t?[e,void 0]:[e,t]));return Object.fromEntries(t)},go=(e,t,n,r,s,o)=>{const{forceDispatch:a,callbackDataSelector:i,callbackFilter:c}=Object.assign({forceDispatch:!1,callbackDataSelector:e=>e},o),{cache:l}=we();let d;l||console.log("For using Live Object feature you need to enable Cache!");let u=!1;const h=[],p=e=>{const{data:n}=e,r=zt(e,["data"]);c&&!c(n,d)||t(Object.assign({data:i(n)},r)),d=po(n)};return h.push(...s.map((t=>t((t=>((t,r=!1)=>{e===t[n]&&(d&&!r&&ln(d,t)||p({loading:!1,data:t,origin:"event"}))})(t,a)))))),(()=>{const t=oe(r,e,!0);ie(t,(({error:e,data:t,loading:n,origin:r,cachedAt:s})=>{-5===s?(p({data:t,origin:r,loading:!1,error:new ge(N,800800,"error")}),u=!0,h.forEach((e=>e()))):u||p({loading:n,data:t,origin:r,error:e}),e&&h.forEach((e=>e()))}))})(),()=>{h.forEach((e=>e()))}};var mo=Object.freeze({__proto__:null,getActiveClient:we,getActiveUser:Qe,setActiveUser:Ve,createClient:(e,t=vt.SG,{debugSession:n="amity",apiEndpoint:r,prefixDeviceIdKey:s}={})=>{var o,a;const i=(e=>{const t=`${null==e?void 0:e.trim()}`.length>0&&!yt,n=f.default(e),r=(e,...r)=>{t&&n(e,r)};return r.__instance__=n,r})(n);i("client/api/createClient",{apiKey:e.replace(/.{5}$/g,"xxxxx"),apiRegion:t});const c=null!==(o=null==r?void 0:r.http)&&void 0!==o?o:wt("http",t),l=null!==(a=null==r?void 0:r.mqtt)&&void 0!==a?a:wt("mqtt",t),d=Tt(c),u=(e=>{const t=y.default(e,{autoConnect:!1,reconnectionDelay:2e3,transports:["websocket"]});return t.on("disconnect",(e=>{"io server disconnect"===e&&t.connect()})),t})(c),h=Lt(l),g=p.default(),m=new Map,v={version:`${U}`,apiKey:e,log:i,cache:{data:{}},http:d,ws:u,mqtt:h,emitter:g,sessionState:"notLoggedIn",accessTokenExpiryWatcher:Zs,sessionHandler:undefined,hasPermission:Ir,validateUrls:Sr,validateTexts:_r,getFeedSettings:kr,getSocialSettings:wr,getMessagePreviewSetting:br,use:()=>Ce(v),isUnreadCountEnabled:!1,getMarkerSyncConsistentMode:Ws,prefixDeviceIdKey:s,objectSyncMap:m};try{const t=we();if(t.apiKey===e)return t;Ce(v)}catch(e){Ce(v)}return v},login:Gs,logout:$r,secureLogout:async()=>{const e=we(),{data:{success:t}}=await e.http.delete("/api/v4/sessions");if(!t)throw new Error("Failed to logout");return await $r()},isConnected:()=>{var e,t;const n=we();return n.log("client/api/isConnected",n),!!(n.userId&&(null===(t=String(null===(e=n.http.defaults.headers.common)||void 0===e?void 0:e.Authorization))||void 0===t?void 0:t.length)&&n.ws.connected)},getFeedSettings:kr,renewal:Ys,markerSync:Ps,enableUnreadCount:Rs,setUploadedFileAccessType:function(e){ro().setFileAccessType(e)},registerPushNotification:async e=>{const t=we();let n;if("ios"!==l.Platform.OS&&"android"!==l.Platform.OS)throw new ve("Unsupported platform");n=l.Platform.OS;const r=await Nt(),{data:{status:s,error:o}}=await t.http.post("/v1/notification",{userId:t.userId,deviceId:r,platform:n,token:e},{headers:{"X-API-Key":t.apiKey}});if(o)throw new ge(o,5e5,"error");return"success"===s},unregisterPushNotification:async()=>{const e=we(),t=Nt(),{data:{status:n,error:r}}=await e.http.delete("/v1/notification",{data:{deviceId:t},headers:{"X-API-Key":e.apiKey}});if(r)throw new ge(r,5e5,"error");return"success"===n},onConnectionError:Vr,onClientDisconnected:e=>Vr((({code:t})=>{800211===t&&e()})),onClientBanned:Hr,onSessionStateChange:ar,onNetworkActivities:e=>_t().onNetworkActivities(e),getTotalUnreadCount:e=>{const{_id:t}=Qe();if(!t)throw new fe("The _id has not been defined in ActiveUser",8e5,"error");return go(t,e,"userId",(async()=>{const{data:e,cachedAt:t}=await $n();return{data:e,cachedAt:t}}),[co],{callbackDataSelector:e=>{var t;return null!==(t=null==e?void 0:e.unreadCount)&&void 0!==t?t:0}})},getUserUnread:e=>{const{_id:t}=Qe();if(!t)throw new fe("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:r}=we();r||console.log("For using Live Object feature you need to enable Cache!");n(`liveUserUnread(tmpid: ${Date.now()}) > listen`);const s=[];let o,a=!1;const i=t=>{const{data:n}=t,r=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;o=r?po(r):r,e({data:r?Object.assign(Object.assign({},r),{hasMentioned:r.isMentioned}):r,loading:t.loading,error:t.error})};return s.push(io((e=>(e=>{var n;const r=e.filter((e=>t===e.userId)),s=r.reduce(((e,t)=>null==e||new Date(t.lastSyncAt).getTime()>new Date(e.lastSyncAt).getTime()?t:e),null),a={unreadCount:null!==(n=null==s?void 0:s.unreadCount)&&void 0!==n?n:0,isMentioned:r.some((e=>!!e.isMentioned))};ln(o,a)||i({loading:!1,data:a})})(e)))),(()=>{const e=oe($n);ie(e,(({error:e,data:t,loading:n,origin:r,cachedAt:o})=>{!function(e){return null!=e&&null!=e}(t)?i({loading:n,data:void 0,origin:r,error:e}):(-5===o?(i({data:t,origin:r,loading:!1,error:new ge(N,800800,"error")}),a=!0,s.forEach((e=>e()))):a||i({loading:n,data:t,origin:r,error:e}),e&&s.forEach((e=>e())))}))})(),()=>{s.forEach((e=>e()))}},getMarkerSyncEvents:()=>Fs,setMarkerSyncEvents:Ls,pushMarkerSyncEvent:Ks,markerSyncTrigger:$s,startMarkerSync:Vs,startUnreadSync:async()=>{await qs(),Ks("start syncing"),Rs(),Ds=!1,Us=!0,zs()},stopUnreadSync:Hs,stopUnreadSyncing:()=>(console.warn("`stopUnreadSyncing` has been deprecated, please use `stopUnreadSync` instead"),Hs()),getMarkerSyncConsistentMode:Ws});function yo(e){const{users:t,follows:n}=e,r=zt(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n,users:t.map(Un)})}function vo(e){const{users:t,follows:n}=e,r=zt(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n,users:t.map(Un)})}function bo(e){const{follows:t}=e,n=zt(e,["follows"]);return Object.assign(Object.assign({},n),{follows:t})}class wo{constructor(e){const{http:t}=we();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,n,r,s;if("prev"===e&&!this.previousToken)return;if("next"===e&&!this.nextToken)return;let o;"prev"===e&&(o=this.previousToken),"next"===e&&(o=this.nextToken);const a=await this.getRequest(this.queryParams,o);return"first"===e&&(this.nextToken=null===(t=a.paging)||void 0===t?void 0:t.next,this.previousToken=null===(n=a.paging)||void 0===n?void 0:n.previous),"prev"===e&&(this.previousToken=null===(r=a.paging)||void 0===r?void 0:r.previous),"next"===e&&(this.nextToken=null===(s=a.paging)||void 0===s?void 0:s.next),a}getNextToken(){return this.nextToken}getPrevToken(){return this.previousToken}}class Co extends wo{async getRequest(e,t){const{limit:n=j}=e,r=zt(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v4/me/user-blocks",{params:Object.assign(Object.assign({},r),{options:s,isDeleted:!1})});return o}}class Io{constructor(e,t){this.query=e,this.cacheKey=t}}class So extends Io{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)_e(this.cacheKey,{data:e.users.map(de("user"))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(de("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Se(this.cacheKey))||void 0===t?void 0:t.data;_e(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class _o{constructor(e){const{http:t}=we();this.queryParams=e,this.http=t}async onFetch(){return await this.getRequest(this.queryParams)}}class ko{constructor(e,t,n,r){this.paginationController=e,this.queryStreamId=t,this.cacheKey=n,this.callback=r}async refresh(){try{let e;if(e=this.paginationController instanceof _o?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({initial:e=!1,direction: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 _o)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 _o)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){const t=e.map(po).map(fo);return!ln(this.snapshot,t)&&(this.snapshot=t,!0)}getCacheKey(){return this.cacheKey}}function Oo(e){const{users:t,follows:n}=e,r=zt(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n.map((e=>{const n=t.find((t=>t.userId===e.from));return Object.assign(Object.assign({},e),{user:Un(n)})})),users:t.map(Un)})}const To=e=>Br("user.updated",e),Eo=e=>Br("user.flagged",e),Ao=e=>Br("user.unflagged",e),Mo=e=>Br("user.flagCleared",e);var Po;!function(e){e.OnUserDeleted="onUserDeleted",e.OnUserUpdated="onUserUpdated",e.OnUserFlagged="onUserFlagged",e.OnUserUnflagged="onUserUnflagged",e.OnUserFlagCleared="onUserFlagCleared"}(Po||(Po={}));class Ro extends ko{constructor(e,t){const n=w.default(e),r=["blockedUsers","collection",n];super(new Co(e),n,r,t),this.query=e,this.queryStreamController=new So(this.query,this.cacheKey,this.notifyChange.bind(this),Oo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:qr,action:Po.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const o=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const a=this.applyFilter(null!==(s=o.data.map((e=>Se(["user","get",e]))).filter(dn).map((({data:e})=>e)).map(wn.user))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}const Uo=(e,t,n)=>{const{log:r,cache:s}=we();s||console.log(D);const o=Date.now();r(`getBlockedUsers(tmpid: ${o}) > listen`);const a=new Ro(e,t),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>Te(c))),()=>{r(`getBlockedUsers(tmpid: ${o}) > dispose`),i.forEach((e=>e())),Te(c)}},jo=(e,t)=>{const n=we();return Xe(n,e,e,(e=>{const r=yo(e);n.cache?(Kt(r),t(r.follows[0])):t(r.follows[0])}))},xo=(e,t)=>{const n=we();return Xe(n,e,e,(e=>{const r=bo(e);n.cache?(Kt(r),t(r.follows[0])):t(r.follows[0])}))},Do=e=>jo("follow.created",e),No=e=>jo("follow.unfollowed",e),Bo=e=>jo("follow.followerDeleted",e),qo=e=>jo("follow.requested",e),Fo=e=>jo("follow.requestCanceled",e),Lo=e=>jo("follow.accepted",e),Ko=e=>jo("follow.requestDeclined",e),$o=async e=>{var t,n;const r=we();r.log("follow/getFollowInfo",e);const{data:s}=await r.http.get(r.userId===e?"/api/v4/me/followInfo":`/api/v5/users/${e}/followInfo`),o=r.cache&&Date.now(),a="follows"in s?Object.assign(Object.assign({},s.followCounts[0]),{status:null===(n=null===(t=s.follows)||void 0===t?void 0:t[0])||void 0===n?void 0:n.status}):s.followCounts[0];return r.cache&&_e(["followInfo","get",e],a,{cachedAt:o}),{data:a,cachedAt:o}};$o.locally=e=>{const t=we();if(t.log("follow/getFollowInfo.locally",e),!t.cache)return;const n=Se(["followInfo","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const zo=e=>{const t=async t=>{const[{data:n},{data:r}]=await Promise.all([$o(t.from),$o(t.to)]);e(n),e(r)},n=[jo("follow.created",t),jo("follow.requested",t),jo("follow.accepted",t),jo("follow.unfollowed",t),jo("follow.requestCanceled",t),jo("follow.requestDeclined",t),jo("follow.followerDeleted",t),xo("local.follow.created",t),xo("local.follow.requested",t),xo("local.follow.accepted",t),xo("local.follow.unfollowed",t),xo("local.follow.requestDeclined",t)];return()=>{n.forEach((e=>e()))}},Qo=e=>xo("local.follow.created",e),Vo=e=>xo("local.follow.unfollowed",e),Ho=e=>xo("local.follow.requested",e),Wo=e=>xo("local.follow.accepted",e),Jo=e=>xo("local.follow.requestDeclined",e);class Go extends wo{async getRequest(e,t){const{limit:n=j,userId:r}=e,s=zt(e,["limit","userId"]),o=t?{token:t}:{limit:n},a=we().userId===r?"/api/v4/me/followers":`/api/v4/users/${r}/followers`,{data:i}=await this.http.get(a,{params:Object.assign(Object.assign({},s),{options:o,isDeleted:!1})});return i}}var Yo;!function(e){e.OnRequested="onRequested",e.OnAccepted="onAccepted",e.OnDeclined="onDeclined",e.OnCanceled="onCanceled",e.OnFollowed="onFollowed",e.OnUnfollowed="onUnfollowed",e.OnDeleted="onDeleted",e.OnUserDeleted="onUserDeleted"}(Yo||(Yo={}));class Xo extends Io{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)_e(this.cacheKey,{data:e.follows.map(de("follow"))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(de("follow"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.to&&r){switch(e){case Yo.OnDeclined:case Yo.OnCanceled:case Yo.OnUnfollowed:case Yo.OnDeleted:r.data=r.data.filter((e=>e!==de("follow")(t)));break;case Yo.OnRequested:case Yo.OnAccepted:case Yo.OnFollowed:r.data=[...new Set([de("follow")(t),...r.data])]}_e(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Zo=({userId:e})=>t=>{const n=we();return Xe(n,"user.deleted","user.deleted",(n=>{const r=Nr(n);Kt(r);const s=Se(["follow","get",de("follow")({from:r.users[0].userId,to:e})]);s&&t(null==s?void 0:s.data)}))};class ea extends ko{constructor(e,t){const n=w.default(e),r=["follow","collection",n];super(new Go(e),n,r,t),this.query=e,this.queryStreamController=new Xo(this.query,this.cacheKey,this.notifyChange.bind(this),yo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Do,action:Yo.OnFollowed},{fn:No,action:Yo.OnUnfollowed},{fn:Lo,action:Yo.OnAccepted},{fn:Ko,action:Yo.OnDeclined},{fn:Fo,action:Yo.OnCanceled},{fn:Bo,action:Yo.OnDeleted},{fn:Wo,action:Yo.OnAccepted},{fn:Jo,action:Yo.OnDeclined},{fn:Qo,action:Yo.OnFollowed},{fn:Vo,action:Yo.OnUnfollowed},{fn:Zo({userId:this.query.userId}),action:Yo.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const o=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const a=this.applyFilter(null!==(s=o.data.map((e=>Se(["follow","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.status&&"all"!==this.query.status&&(t=t.filter((e=>e.status===this.query.status))),t=t.filter((e=>{var t;const n=null===(t=Se(["user","get",e.from]))||void 0===t?void 0:t.data;return null==(null==n?void 0:n.isDeleted)||!1===(null==n?void 0:n.isDeleted)})),t}}class ta extends wo{async getRequest(e,t){const{limit:n=j,userId:r}=e,s=zt(e,["limit","userId"]),o=t?{token:t}:{limit:n},a=we().userId===r?"/api/v4/me/following":`/api/v4/users/${r}/following`,{data:i}=await this.http.get(a,{params:Object.assign(Object.assign({},s),{options:o,isDeleted:!1})});return i}}class na extends Io{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)_e(this.cacheKey,{data:e.follows.map(de("follow"))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(de("follow"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.from&&r){switch(e){case Yo.OnDeclined:case Yo.OnCanceled:case Yo.OnUnfollowed:case Yo.OnDeleted:r.data=r.data.filter((e=>e!==de("follow")(t)));break;case Yo.OnRequested:case Yo.OnAccepted:case Yo.OnFollowed:r.data=[...new Set([de("follow")(t),...r.data])]}_e(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const ra=({userId:e})=>t=>{const n=we();return Xe(n,"user.deleted","user.deleted",(n=>{const r=Nr(n);Kt(r);const s=Se(["follow","get",de("follow")({from:e,to:r.users[0].userId})]);s&&t(null==s?void 0:s.data)}))};class sa extends ko{constructor(e,t){const n=w.default(e),r=["follow","collection",n];super(new ta(e),n,r,t),this.query=e,this.queryStreamController=new na(this.query,this.cacheKey,this.notifyChange.bind(this),vo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:qo,action:Yo.OnRequested},{fn:Lo,action:Yo.OnAccepted},{fn:Ko,action:Yo.OnDeclined},{fn:Fo,action:Yo.OnCanceled},{fn:Do,action:Yo.OnFollowed},{fn:No,action:Yo.OnUnfollowed},{fn:Bo,action:Yo.OnDeleted},{fn:Ho,action:Yo.OnRequested},{fn:Wo,action:Yo.OnAccepted},{fn:Jo,action:Yo.OnDeclined},{fn:Qo,action:Yo.OnFollowed},{fn:Vo,action:Yo.OnUnfollowed},{fn:ra({userId:this.query.userId}),action:Yo.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const o=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const a=this.applyFilter(null!==(s=o.data.map((e=>Se(["follow","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.status&&"all"!==this.query.status&&(t=t.filter((e=>e.status===this.query.status))),t=t.filter((e=>{var t;const n=null===(t=Se(["user","get",e.to]))||void 0===t?void 0:t.data;return null==(null==n?void 0:n.isDeleted)||!1===(null==n?void 0:n.isDeleted)})),t}}var oa=Object.freeze({__proto__:null,blockUser:async e=>{const t=we();t.log("user/blockUser",e);const{data:n}=await t.http.post(`/api/v4/me/user-blocks/${e}`),r=t.cache&&Date.now(),{follows:s,followCounts:o}=n,a={follows:s};t.cache&&(Kt(a,{cachedAt:r}),Oe(["followInfo","get",e],o[0],{cachedAt:r}));const i=bo(a);return Ze("local.follow.unfollowed",i),n},unBlockUser:async e=>{const t=we();t.log("user/unBlockUser",e);const{data:n}=await t.http.delete(`/api/v4/me/user-blocks/${e}`),r=t.cache&&Date.now(),{follows:s,followCounts:o}=n,a={follows:s};t.cache&&(Kt(a,{cachedAt:r}),Oe(["followInfo","get",e],o[0],{cachedAt:r}));const i=bo(a);return Ze("local.follow.created",i),n},getBlockedUsers:(e,t,n)=>(console.log("Deprecation Notice: UserRepository.Relationship.getBlockedUsers will be deprecated on 9th June 2023, please use UserRepository.getBlockedUsers instead."),Uo(e,t)),follow:async e=>{const t=we();t.log("follow/follow",e);const{data:n}=await t.http.post(`/api/v4/me/following/${e}`),r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const s=bo(n);return"accepted"===n.follows[0].status?Ze("local.follow.created",s):Ze("local.follow.requested",s),{data:n.follows[0],cachedAt:r}},unfollow:async e=>{const t=we();t.log("follow/unfollow",e);const{data:n}=await t.http.delete(`/api/v4/me/following/${e}`);t.cache&&Kt(n);const r=bo(n);return Ze("local.follow.unfollowed",r),!0},acceptFollower:async e=>{const t=we();t.log("follow/acceptFollower",e);const{data:n}=await t.http.post(`/api/v4/me/followers/${e}`);t.cache&&Kt(n);const r=bo(n);return Ze("local.follow.accepted",r),!0},acceptMyFollower:async e=>{const t=we();t.log("follow/acceptMyFollower",e);const{data:n}=await t.http.post(`/api/v4/me/followers/${e}`);t.cache&&Kt(n);const r=bo(n);return Ze("local.follow.accepted",r),!0},declineFollower:async e=>{const t=we();t.log("follow/declineFollower",e);const{data:n}=await t.http.delete(`/api/v4/me/followers/${e}`);t.cache&&Kt(n);const r=bo(n);return Ze("local.follow.requestDeclined",r),!0},declineMyFollower:async e=>{const t=we();t.log("follow/declineMyFollower",e);const{data:n}=await t.http.delete(`/api/v4/me/followers/${e}`);t.cache&&Kt(n);const r=bo(n);return Ze("local.follow.requestDeclined",r),!0},onUserFollowed:Do,onUserUnfollowed:No,onFollowerDeleted:Bo,onFollowerRequested:qo,onFollowRequestCanceled:Fo,onFollowRequestAccepted:Lo,onFollowRequestDeclined:Ko,onFollowInfoUpdated:zo,onLocalUserFollowed:Qo,onLocalUserUnfollowed:Vo,onLocalFollowerRequested:Ho,onLocalFollowRequestAccepted:Wo,onLocalFollowRequestDeclined:Jo,observeFollowInfo:(e,t,n="cache_then_server")=>{const{log:r}=we(),s=Date.now();r(`observeFollowInfo(tmpid: ${s}) > listen`);const o=(e,n)=>{var r,s;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(s=t[n])||void 0===s||s.call(t,e)},a=[];return a.push(zo((t=>((t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.userId)===e&&o(t,n)})({data:t,loading:!1,origin:"event"},"onUpdate")))),ie(oe($o,e),(e=>(e.data||e.error)&&o(e,"onFetch")),ae(n)),()=>{r(`observeFollowInfo(tmpid: ${s}) > dispose`),a.forEach((e=>e()))}},observeFollowers:(e,t)=>{const{log:n}=we(),r=Date.now();n(`observeFollowers(tmpid: ${r}) > listen`);const s=[],o=(e,n)=>{var r,s;if(t instanceof Function)return t(e);null===(r=t.onEvent)||void 0===r||r.call(t,n,e),null===(s=t[n])||void 0===s||s.call(t,e)};return s.push(qo((e=>o(e,"onRequested"))),Lo((e=>o(e,"onAccepted"))),Ko((e=>o(e,"onDeclined"))),Fo((e=>o(e,"onCanceled"))),Do((e=>o(e,"onFollowed"))),No((e=>o(e,"onUnfollowed"))),Bo((e=>o(e,"onDeleted"))),Ho((e=>o(e,"onRequested"))),Wo((e=>o(e,"onAccepted"))),Jo((e=>o(e,"onDeclined"))),Qo((e=>o(e,"onFollowed"))),Vo((e=>o(e,"onUnfollowed")))),()=>{n(`observeFollowers(tmpid: ${r}) > dispose`),s.forEach((e=>e()))}},observeFollowings:(e,t)=>{const{log:n}=we(),r=Date.now();n(`observeFollowings(tmpid: ${r}) > listen`);const s=[],o=(e,n)=>{var r,s;if(t instanceof Function)return t(e);null===(r=t.onEvent)||void 0===r||r.call(t,n,e),null===(s=t[n])||void 0===s||s.call(t,e)};return s.push(qo((e=>o(e,"onRequested"))),Lo((e=>o(e,"onAccepted"))),Ko((e=>o(e,"onDeclined"))),Fo((e=>o(e,"onCanceled"))),Do((e=>o(e,"onFollowed"))),No((e=>o(e,"onUnfollowed"))),Bo((e=>o(e,"onDeleted"))),Ho((e=>o(e,"onRequested"))),Wo((e=>o(e,"onAccepted"))),Jo((e=>o(e,"onDeclined"))),Qo((e=>o(e,"onFollowed"))),Vo((e=>o(e,"onUnfollowed")))),()=>{n(`observeFollowings(tmpid: ${r}) > dispose`),s.forEach((e=>e()))}},getFollowers:(e,t,n)=>{const{log:r,cache:s}=we();s||console.log(D);const o=Date.now();r(`getFollowers(tmpid: ${o}) > listen`);const a=new ea(e,t),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>Te(c))),()=>{r(`getFollowers(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getFollowings:(e,t,n)=>{const{log:r,cache:s}=we();s||console.log("For using Live Collection feature you need to enable Cache!");const o=Date.now();r(`getFollowings(tmpid: ${o}) > listen`);const a=new sa(e,t),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>Te(c))),()=>{r(`getFollowings(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getFollowInfo:(e,t)=>go(e,t,"userId",$o,[zo],{forceDispatch:!0}),getMyFollowInfo:e=>{const{userId:t}=Qe();return go(t,e,"userId",$o,[zo],{forceDispatch:!0})}});const aa=async e=>{const t=we();t.log("user/getUsers",e);const n=e.map((e=>encodeURIComponent(e))),{data:r}=await t.http.get("/api/v3/users/list",{params:{userIds:n}}),s=Nr(r),o=t.cache&&Date.now();return t.cache&&Kt(s,{cachedAt:o}),Ze("user.fetched",r),{data:s.users.map((e=>wn.user(e))),cachedAt:o}};aa.locally=e=>{var t;const n=we();if(n.log("user/getUsers.locally",e),!n.cache)return;const r=e.map((e=>Se(["user","get",e]))).filter(Boolean),s=r.map((({data:e})=>wn.user(e))),o=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:s,cachedAt:o.cachedAt}};const ia=e=>Br("user.fetched",e),ca=async e=>{const t=we();t.log("user/getUser",e),lr("user",e);try{const{data:n}=await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`),r=t.cache&&Date.now(),s=Nr(n);return t.cache&&Kt(s,{cachedAt:r}),Ze("user.fetched",n),{data:s.users.find((t=>t.userId===e)),cachedAt:r}}catch(t){throw V(null==t?void 0:t.code)&&$t("user",e),t}};ca.locally=e=>{const t=we();if(t.log("user/getUser.locally",e),!t.cache)return;const n=Se(["user","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class la extends wo{async getRequest(e,t){const{limit:n=j,displayName:r}=e,s=zt(e,["limit","displayName"]),o=t?{token:t}:{limit:n},{data:a}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},s),{keyword:r,options:o,isDeleted:!1})});return a}}class da extends Io{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)_e(this.cacheKey,{data:e.users.map(de("user"))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(de("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Se(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],_e(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class ua extends ko{constructor(e,t){const n=w.default(e),r=["user","collection",n];super(new la(e),n,r,t),this.query=e,this.queryStreamController=new da(this.query,this.cacheKey,this.notifyChange.bind(this),Nr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:qr,action:Po.OnUserDeleted},{fn:To,action:Po.OnUserUpdated},{fn:Eo,action:Po.OnUserFlagged},{fn:Ao,action:Po.OnUserUnflagged},{fn:Mo,action:Po.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const o=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const a=this.applyFilter(null!==(s=o.data.map((e=>Se(["user","get",e]))).filter(dn).map((({data:e})=>e)).map(wn.user))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;if(!this.query.displayName){const e=(()=>{switch(this.query.sortBy){case"firstCreated":return Be;case"lastCreated":default:return Fe;case"displayName":return De}})();t=t.sort(e)}return"flagged"===this.query.filter&&(t=t.filter((e=>!!e.hashFlag))),t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}const ha=async e=>{const{data:t,cachedAt:n}=await ca(e);return{data:wn.user(t),cachedAt:n}};ha.locally=e=>{const t=ca.locally(e);if(t)return{data:wn.user(t.data),cachedAt:t.cachedAt}};class pa extends wo{async getRequest(e,t){const{limit:n=j,displayName:r}=e,s=zt(e,["limit","displayName"]),o=t?{token:t}:{limit:n},{data:a}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},s),{keyword:r,options:o,isDeleted:!1})});return a}}class fa extends Io{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)_e(this.cacheKey,{data:e.users.map(de("user"))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(de("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Se(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],_e(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class ga extends ko{constructor(e,t){var n;const r=w.default(e),s=["user","collection",r];super(new pa(e),r,s,t),this.query=Object.assign(Object.assign({},e),{filter:null!==(n=e.filter)&&void 0!==n?n:"all"}),this.queryStreamController=new fa(this.query,this.cacheKey,this.notifyChange.bind(this),Nr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:qr,action:Po.OnUserDeleted},{fn:To,action:Po.OnUserUpdated},{fn:Eo,action:Po.OnUserFlagged},{fn:Ao,action:Po.OnUserUnflagged},{fn:Mo,action:Po.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const o=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const a=this.applyFilter(null!==(s=o.data.map((e=>Se(["user","get",e]))).filter(dn).map((({data:e})=>e)).map(wn.user))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return"flagged"===this.query.filter&&(t=t.filter((e=>!!e.hashFlag))),t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}const ma=async({viewId:e,viewedType:t,limit:n,token:r})=>{const s=we(),o={};r?o.token=r:o.limit=n;const a=`/api/v1/analytics/views/${"post"===t?"posts":"stories"}/${e}/users`,i=await s.http.get(a,{params:o});return Kt(i.data),i.data};var ya=Object.freeze({__proto__:null,Relationship:oa,getUserByIds:aa,updateUser:async(e,t)=>{const n=we();n.log("user/updateUser",e,t);const{data:r}=await n.http.put("/api/v3/users/",Object.assign(Object.assign({userId:e},t),{createNewUserWhenNotFound:!1})),s=Nr(r),o=n.cache&&Date.now();return n.cache&&Kt(s,{cachedAt:o}),Ze("user.updated",r),{data:s.users.find((t=>t.userId===e)),cachedAt:o}},flagUser:async e=>{const t=we();t.log("user/flagUser",e);const{data:n}=await t.http.post(`api/v4/me/flags/${encodeURIComponent(e)}`),r=Nr(n);return t.cache&&Kt(r),Ze("user.flagged",n),!!r},unflagUser:async e=>{const t=we();t.log("user/unflag",e);const{data:n}=await t.http.delete(`/api/v4/me/flags/${encodeURIComponent(e)}`),r=Nr(n);return t.cache&&Kt(r),Ze("user.unflagged",n),!!r},isUserFlaggedByMe:async e=>{const t=we();t.log("user/isUserFlaggedByMe",e);const{data:{isFlagByMe:n}}=await t.http.get(`/api/v3/users/${e}/isFlagByMe`);return n},onUserUpdated:To,onUserDeleted:qr,onUserFlagged:Eo,onUserUnflagged:Ao,onUserFlagCleared:Mo,getUser:(e,t)=>go(e,(e=>t(Object.assign(Object.assign({},e),{data:e.data?wn.user(e.data):e.data}))),"userId",ca,[ia,To,qr,Eo,Ao,Mo]),getUsers:(e,t,n)=>{const{log:r,cache:s}=we();s||console.log(D);const o=Date.now();r(`liveUsers(tmpid: ${o}) > listen`);const a=new ua(e,t),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>Te(c))),()=>{r(`liveUsers(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},observeUser:(e,t)=>{const{log:n}=we(),r=Date.now();n(`observeUser(tmpid: ${r}) > listen`);const s=(n,r)=>{var s,o,a;if((null===(s=n.data)||void 0===s?void 0:s.userId)!==e)return;const i=Object.assign(Object.assign({},n),{data:wn.user(n.data)});if(t instanceof Function)return t(i);"onFetch"!==r&&(null===(o=t.onEvent)||void 0===o||o.call(t,r,i)),null===(a=t[r])||void 0===a||a.call(t,i)},o=[];return o.push(To((e=>s({data:e,loading:!1,origin:"event"},"onUpdate"))),qr((e=>s({data:e,loading:!1,origin:"event"},"onDelete"))),Eo((e=>s({data:e,loading:!1,origin:"event"},"onFlagged"))),Ao((e=>s({data:e,loading:!1,origin:"event"},"onUnflagged"))),Mo((e=>s({data:e,loading:!1,origin:"event"},"onFlagCleared")))),ie(oe(ha,e),(e=>e.data&&s(e,"onFetch"))),()=>{n(`observeUser(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},getBlockedUsers:Uo,searchUserByDisplayName:(e,t,n)=>{const{log:r,cache:s}=we();s||console.log(D);const o=Date.now();r(`liveSearchUsers(tmpid: ${o}) > listen`);const a=new ga(e,t),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>Te(c))),()=>{r(`liveSearchUsers(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getViewedUsers:(e,t)=>{const{log:n,cache:r}=we(),s=["postViewedUsers","collection",{postId:e.postId}];r||console.log(D);const o=Date.now();n(`getViewedUsers(tmpid: ${o}) > listen`);const{limit:a,postId:i}=e,c=(e=!1)=>{var n,r,o;const l=null===(n=Se(s))||void 0===n?void 0:n.data,d=null!==(r=null==l?void 0:l.data)&&void 0!==r?r:[];if(!e&&d.length>0&&!(null==l?void 0:l.params.page))return;const u=oe(ma,{viewId:i,viewedType:"post",limit:a||10,token:e||null===(o=null==l?void 0:l.params.page)||void 0===o?void 0:o.next});ie(u,(e=>{var n,r,o,a,i;let l=null!==(o=null===(r=null===(n=Se(s))||void 0===n?void 0:n.data)||void 0===r?void 0:r.data)&&void 0!==o?o:[];(null===(a=e.data)||void 0===a?void 0:a.users)&&(l=[...new Set([...l,...e.data.users.map((({userId:e})=>e))])]);const d={loading:e.loading,params:{page:null===(i=e.data)||void 0===i?void 0:i.paging},data:l||[]};_e(s,d),(e=>{var n,r;let s=[];(null==e?void 0:e.data)&&(s=e.data.map((e=>Se(["user","get",e]))).filter(Boolean).map((e=>null==e?void 0:e.data))||[]),t({onNextPage:c,data:s,hasNextPage:!!(null===(r=null===(n=e.params)||void 0===n?void 0:n.page)||void 0===r?void 0:r.next),loading:e.loading||!1})})(d)}),ae(x,2e3))};return c(!0),()=>{n(`getViewedUsers(tmpid: ${o}) > dispose`),Te(s)}},getReachedUsers:(e,t)=>{let n=(e=!1)=>{};const{log:r,cache:s}=we(),o=["viewedUsers","collection",{viewId:e.viewId,viewedType:e.viewedType}];s||console.log(D);const a=Date.now();r(`getReachUsers(tmpid: ${a}) > listen`);const{limit:i,viewId:c,viewedType:l}=e;return n=(e=!1)=>{var r,s,a;const d=null===(r=Se(o))||void 0===r?void 0:r.data,u=null!==(s=null==d?void 0:d.data)&&void 0!==s?s:[];if(!e&&u.length>0&&!(null==d?void 0:d.params.page))return;const h=oe(ma,{viewId:c,viewedType:l,limit:i||10,token:e||null===(a=null==d?void 0:d.params.page)||void 0===a?void 0:a.next});ie(h,(e=>{var r,s,a,i,c;let l=null!==(a=null===(s=null===(r=Se(o))||void 0===r?void 0:r.data)||void 0===s?void 0:s.data)&&void 0!==a?a:[];(null===(i=e.data)||void 0===i?void 0:i.users)&&(l=[...new Set([...l,...e.data.users.map((({userId:e})=>e))])]);const d={loading:e.loading,params:{page:null===(c=e.data)||void 0===c?void 0:c.paging},data:l||[]};_e(o,d),(e=>{var r,s;let o=[];(null==e?void 0:e.data)&&(o=e.data.map((e=>Se(["user","get",e]))).filter(Boolean).map((e=>null==e?void 0:e.data))||[]),t({onNextPage:n,data:o,hasNextPage:!!(null===(s=null===(r=e.params)||void 0===r?void 0:r.page)||void 0===s?void 0:s.next),loading:e.loading||!1})})(d)}),ae(x,2e3))},n(!0),()=>{r(`getReachUsers(tmpid: ${a}) > dispose`),Te(o)}}});const va=async e=>{const t=we();t.log("file/getFile",e);const{data:n}=await t.http.get(`/api/v3/files/${e}`),r=t.cache&&Date.now();return t.cache&&Kt({files:[n]},{cachedAt:r}),{data:n,cachedAt:r}};va.locally=e=>{const t=we();if(t.log("file/getFile.locally",e),!t.cache)return;const n=Se(["file","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const ba=async(e,t,n)=>{const r=we();r.log("file/uploadVideo",e);const s=e.getAll("files");if(!s.length)throw new Error("The formData object must have a `files` key.");const o=ro().getFileAccessType();e.append("accessType",o),e.append("preferredFilename",s[0].name),t&&e.append("feedType",t);const a="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await r.http.post("/api/v4/videos",e,{headers:a,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),c=r.cache&&Date.now();return r.cache&&Kt({files:i},{cachedAt:c}),{data:i,cachedAt:c}},wa=async(e,t)=>{const n=we();n.log("file/uploadImage",e);const r=e.getAll("files");if(!r.length)throw new Error("The formData object must have a `files` key.");const s=ro().getFileAccessType();e.append("accessType",s),e.append("preferredFilename",r[0].name);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:a}=await n.http.post("/api/v4/images",e,{headers:o,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),i=n.cache&&Date.now();return n.cache&&Kt({files:a},{cachedAt:i}),{data:a,cachedAt:i}};var Ca=Object.freeze({__proto__:null,getFile:va,uploadFile:async(e,t)=>{const n=we();n.log("file/uploadFile",e);const r=e.getAll("files");if(!r.length)throw new Error("The formData object must have a `files` key.");const s=ro().getFileAccessType();e.append("accessType",s),e.append("preferredFilename",r[0].name);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:a}=await n.http.post("/api/v4/files",e,{headers:o,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),i=n.cache&&Date.now();return n.cache&&Kt({files:a},{cachedAt:i}),{data:a,cachedAt:i}},deleteFile:async e=>{const t=we();return t.log("file/deleteFile",e),await t.http.delete(`/api/v3/files/${e}`),Te(["file","get",e],!0),{success:!0}},fileUrlWithSize:(e,t)=>`${e}?size=${t}`,uploadVideo:ba,uploadImage:wa,createImage:async(e,t)=>{const n=we();n.log("file/createImage",e);const r=e.getAll("files");if(!r.length)throw new Error("The formData object must have a `files` key.");const s=ro().getFileAccessType();e.append("accessType",s),e.append("preferredFilename",r[0].name);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:a}=await n.http.post("/api/v4/images",e,{headers:o,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),i=n.cache&&Date.now();return n.cache&&Kt({files:a},{cachedAt:i}),{data:a,cachedAt:i}},createFile:async(e,t)=>{const n=we();n.log("file/createFile",e);const r=e.getAll("files");if(!r.length)throw new Error("The formData object must have a `files` key.");const s=ro().getFileAccessType();e.append("accessType",s),e.append("preferredFilename",r[0].name);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:a}=await n.http.post("/api/v4/files",e,{headers:o,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),i=n.cache&&Date.now();return n.cache&&Kt({files:a},{cachedAt:i}),{data:a,cachedAt:i}},createVideo:async(e,t,n)=>{const r=we();r.log("file/createVideo",e);const s=e.getAll("files");if(!s.length)throw new Error("The formData object must have a `files` key.");const o=ro().getFileAccessType();e.append("accessType",o),e.append("preferredFilename",s[0].name),t&&e.append("feedType",t);const a="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await r.http.post("/api/v4/videos",e,{headers:a,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),c=r.cache&&Date.now();return r.cache&&Kt({files:i},{cachedAt:c}),{data:i,cachedAt:c}},observeFile:(e,t)=>{const{log:n}=we(),r=Date.now();n(`observeFile(tmpid: ${r}) > listen`);return ie(oe(va,e),(n=>n.data&&((n,r)=>{var s,o,a;if((null===(s=n.data)||void 0===s?void 0:s.fileId)===e){if(t instanceof Function)return t(n);"onFetch"!==r&&(null===(o=t.onEvent)||void 0===o||o.call(t,r,n)),null===(a=t[r])||void 0===a||a.call(t,n)}})(n,"onFetch"))),()=>{n(`observeFile(tmpid: ${r}) > dispose`)}}});const Ia=async e=>{const t=we();t.log("role/queryRoles",e);const n=null!=e?e:{},{page:r,limit:s=10,queryToken:o,displayName:a,sortBy:i}=n,c=zt(n,["page","limit","queryToken","displayName","sortBy"]),l=o?{token:o}:s?{limit:s}:r?{token:Y(r,"skiplimit")}:void 0,{data:d}=await t.http.get("/api/v3/roles",{params:Object.assign(Object.assign({},c),{keyword:a,sortBy:i,options:l})}),{paging:u}=d,h=zt(d,["paging"]),{roles:p}=h,f=t.cache&&Date.now();t.cache&&Kt(h,{cachedAt:f});const g=X(u.next);return{data:p,cachedAt:f,prevPage:X(u.previous),nextPage:g,paging:u}};Ia.locally=e=>{we().log("role/queryRoles.locally",e)};const Sa=async e=>{const t=we();t.log("role/getRole",e);const{data:n}=await t.http.get(`/api/v3/roles/${e}`),r=t.cache&&Date.now();return t.cache&&Kt({roles:n},{cachedAt:r}),{data:n.find((t=>t.roleId===e)),cachedAt:r}};Sa.locally=e=>{const t=we();if(t.log("role/getRole.locally",e),!t.cache)return;const n=Se(["role","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const _a=(e,t)=>{"message"===e?Ze("local.message.updated",{messages:[t]}):"post"===e?Ze("post.updated",{posts:[t]}):"comment"===e?Ze("comment.updated",{comments:[t]}):"story"===e&&Ze("story.updated",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[t]})},ka=async(e,t=!1)=>{const n=we();let r;n.log("message/getMessage",e),t||console.log("getMessage will be deprecated on 15th November 2022, please use liveMessage instead."),lr("message",e);try{const{data:t}=await n.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);r=await Yn(t)}catch(t){throw V(null==t?void 0:t.code)&&$t("message",e),t}const s=n.cache&&Date.now();n.cache&&Kt(r,{cachedAt:s});const{messages:o}=r;return Ze("local.message.fetched",{messages:o}),{data:o.find((t=>t.messageId===e)),cachedAt:s}};ka.locally=e=>{const t=we();if(t.log("message/getMessage.locally",e),!t.cache)return;const n=Se(["message","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Oa=async e=>{const t=we();let n;t.log("post/getPost",e),lr("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw V(null==t?void 0:t.code)&&$t("post",e),t}const r=Vt(n,"communityUsers"),s=t.cache&&Date.now();t.cache&&Kt(r,{cachedAt:s});const{posts:o}=r,a=o.find((t=>t.postId===e));return{data:wn.post(a),cachedAt:s}};Oa.locally=e=>{const t=we();if(t.log("post/getPost.locally",e),!t.cache)return;const n=Se(["post","get",e]);return n?{data:wn.post(n.data),cachedAt:n.cachedAt}:void 0};const Ta=async e=>{const t=we();let n;t.log("comment/getComment",e),lr("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw V(null==t?void 0:t.code)&&$t("comment",e),t}const r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const{comments:s}=n;return{data:wn.comment(s.find((t=>t.commentId===e))),cachedAt:r}};function Ea(e,t){return e.map((e=>{if(null==e.isJoined){const n=t.some((t=>function(e,t){const{userId:n}=Qe();return e.communityId===t.communityId&&t.userId===n}(e,t)&&"none"!==t.communityMembership));return Object.assign(Object.assign({},e),{isJoined:n})}return e}))}Ta.locally=e=>{const t=we();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=Se(["comment","get",e]);return n?{data:wn.comment(n.data),cachedAt:n.cachedAt}:void 0};const Aa=(e,t)=>{var n,r;let s,o;if("post"===t)o="post",s=e.posts[0].postId;else if("comment"===t)o="comment",s=e.comments[0].commentId;else{if("story"!==t)throw new Error("Unknown event type");o="story",s=e.stories[0].referenceId}return(null===(r=null===(n=Se([o,"get",s]))||void 0===n?void 0:n.data)||void 0===r?void 0:r.myReactions)||[]},Ma=(e,t,n)=>{const[r]=e[t];return Object.assign(Object.assign({},e),{[t]:[Object.assign(Object.assign({},r),{myReactions:n})]})},Pa=(e,t,n,r=[])=>{const s=e.split(".")[1];let o=r;if(we().userId===t)if(["addReaction","reactionAdded"].includes(s))o.includes(n)||o.push(n);else{if(!["removeReaction","reactionRemoved"].includes(s))throw new Error(`Unknown event type: ${s}`);o=o.filter((e=>e!==n))}return o},Ra=(e,t)=>{const n=e.split(".")[0],r=Aa(t,n),s=Pa(e,t.reactor.userId,t.reactor.reactionName,r);return Ma(t,`${n}s`,s)},Ua=(e,t)=>{var n,r;const s=e.split(".")[0];let o=Aa(t,s);(null==t?void 0:t.reactions)&&t.reactions.length>0&&(o=Pa(e,null===(n=t.reactions[0])||void 0===n?void 0:n.userId,null===(r=t.reactions[0])||void 0===r?void 0:r.reactionName,o));const a=Ma(t,"stories",o);if(!(null==t?void 0:t.communities)||!(null==t?void 0:t.communityUsers))return a;const i=Ea(t.communities,t.communityUsers);return Object.assign(Object.assign({},a),{communities:i})},ja=async(e,t,n)=>{var r,s;const o=we();if(o.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),await o.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0}),o.cache){const o=Se([e,"get",t]);if(!o)return!0;const a=Object.assign(Object.assign({},o.data),{reactionsCount:o.data.reactionsCount+1,myReactions:[...null!==(r=o.data.myReactions)&&void 0!==r?r:[],n],reactions:Object.assign(Object.assign({},o.data.reactions),{[n]:(null!==(s=o.data.reactions[n])&&void 0!==s?s:0)+1})});if("comment"===e)return Ze("local.comment.addReaction",{comment:a}),!0;if("post"===e)return Ze("local.post.addReaction",{post:a}),!0}return!0};ja.optimistically=(e,t,n)=>{var r,s,o,a,i;const c=we();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const l=Se([e,"get",t]);if(!(null==l?void 0:l.data)||(null===(r=l.data.myReactions)||void 0===r?void 0:r.includes(n)))return;const d=Object.assign(Object.assign({},l.data),{reactionsCount:l.data.reactionsCount+1,myReactions:[...null!==(s=l.data.myReactions)&&void 0!==s?s:[],n],reactions:Object.assign(Object.assign({},l.data.reactions),{[n]:(null!==(o=l.data.reactions[n])&&void 0!==o?o:0)+1})});return Oe([e,"get",t],d,{cachedAt:-5}),_a(e,d),null!==(i=null===(a=null==d?void 0:d.myReactions)||void 0===a?void 0:a.includes(n))&&void 0!==i&&i};const xa=async(e,t,n)=>{var r,s;const o=we();if(o.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),await o.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0}}),o.cache){const o=Se([e,"get",t]);if(!o)return!0;const a=Object.assign(Object.assign({},o.data),{reactionsCount:Math.max(0,o.data.reactionsCount-1),myReactions:(null!==(r=o.data.myReactions)&&void 0!==r?r:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},o.data.reactions),{[n]:Math.max(0,(null!==(s=o.data.reactions[n])&&void 0!==s?s:0)-1)})});if("comment"===e)return Ze("local.comment.removeReaction",{comment:a}),!0;if("post"===e)return Ze("local.post.removeReaction",{post:a}),!0}return!0};xa.optimistically=(e,t,n)=>{var r,s,o,a,i;const c=we();if(c.log("reaction/removeReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const l=Se([e,"get",t]);if(!(null==l?void 0:l.data)||!(null===(r=l.data.myReactions)||void 0===r?void 0:r.includes(n)))return;const d=Object.assign(Object.assign({},l.data),{reactionsCount:Math.max(0,l.data.reactionsCount-1),myReactions:(null!==(s=l.data.myReactions)&&void 0!==s?s:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},l.data.reactions),{[n]:Math.max(0,(null!==(o=l.data.reactions[n])&&void 0!==o?o:0)-1)})});return Oe([e,"get",t],d,{cachedAt:-5}),_a(e,d),null!==(i=!(null===(a=null==d?void 0:d.myReactions)||void 0===a?void 0:a.includes(n)))&&void 0!==i&&i};const Da=e=>{var t;return null!==(t=Object.keys(E).find((t=>e.needApprovalOnPostCreation===E[t].needApprovalOnPostCreation&&e.onlyAdminCanPost===E[t].onlyAdminCanPost)))&&void 0!==t?t:A};function Na({communities:e}){return e.map((e=>{var{needApprovalOnPostCreation:t,onlyAdminCanPost:n}=e,r=zt(e,["needApprovalOnPostCreation","onlyAdminCanPost"]);return Object.assign({postSetting:Da({needApprovalOnPostCreation:t,onlyAdminCanPost:n})},r)}))}const Ba=e=>{const t=Na({communities:e.communities}),n=e.communityUsers.map((t=>{const n=e.users.find((e=>e.userId===t.userId));return Object.assign(Object.assign({},t),{user:n})})),r=Ea(t,n);return Object.assign(Object.assign({},e),{communities:r,communityUsers:n})},qa=e=>{const t=Na({communities:e.communities}),n=e.communityUsers.map((t=>{const n=e.users.find((e=>e.userId===t.userId));return Object.assign(Object.assign({},t),{user:n})})),r=Ea(t,n);return Object.assign(Object.assign({},e),{communities:r,communityUsers:n})},Fa=e=>{const{postSetting:t,storySetting:n}=e,r=zt(e,["postSetting","storySetting"]);return Object.assign(Object.assign(Object.assign({},r),t?E[t]:void 0),{allowCommentInStory:"boolean"!=typeof(null==n?void 0:n.enableComment)||n.enableComment})},La=e=>{const{posts:t}=e,n=zt(e,["posts"]),r=Na({communities:n.communities}),s=n.communityUsers.map((e=>{const t=n.users.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),o=Ea(r,s),a=t.map((e=>{var t;const r=null===(t=n.feeds.find((t=>t.feedId===e.feedId)))||void 0===t?void 0:t.feedType;return Object.assign(Object.assign({},e),{feedType:r})}));return Object.assign(Object.assign({},n),{posts:a,communities:o,communityUsers:s})},Ka=e=>{var{searchResult:t,polls:n}=e,r=zt(e,["searchResult","polls"]);const s=La(r);return Object.assign(Object.assign({},s),{polls:n})},$a=(e,t)=>{const n=we();return Xe(n,e,e,(r=>{var s;if(n.cache){const o=La(r),{communities:a}=o;if(Kt(o),(null==a?void 0:a[0])&&!["post.updated"].includes(e)&&Ze("community.updated",{communities:a,categories:[],communityUsers:o.communityUsers,feeds:[],files:[],users:[]}),"post.deleted"===e){const{postId:e,postedUserId:s}=r.posts[0];try{lr("post",e)}catch(e){return}return s!==n.userId&&Te(["post","get",e]),t(r.posts[0])}const i=Se(["post","get",r.posts[0].postId]);if(["post.created","post.approved","post.declined"].includes(e)){let t=null===(s=Ie(["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)===i.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})=>Oe(e,t,{cachedAt:-1})))}t(i.data)}else t(r.posts[0])}))},za=(e,t)=>{const n=we();return Xe(n,e,e,(r=>{if(n.cache){const n=La(r),{communities:s}=n;Kt(n),(null==s?void 0:s[0])&&!["local.post.updated"].includes(e)&&Ze("community.updated",{communities:s,categories:[],communityUsers:n.communityUsers,feeds:[],files:[],users:[]});const o=Se(["post","get",r.posts[0].postId]);t(o.data)}else t(r.posts[0])}))},Qa=e=>$a("post.created",e),Va=e=>$a("post.updated",e),Ha=e=>$a("post.deleted",e),Wa=e=>$a("post.approved",e),Ja=e=>$a("post.declined",e),Ga=e=>$a("post.flagged",e),Ya=e=>$a("post.unflagged",e),Xa=e=>{const t=we();return Xe(t,"post.addReaction","post.addReaction",(n=>{if(t.cache){const t=zt(Ra("post.addReaction",n),["reactor"]);Kt(t);const r=Se(["post","get",n.posts[0].postId]);e(r.data)}else e(n.posts[0])}))},Za=e=>{const t=we();return Xe(t,"post.removeReaction","post.removeReaction",(n=>{if(t.cache){const t=zt(Ra("post.removeReaction",n),["reactor"]);Kt(t);const r=Se(["post","get",n.posts[0].postId]);e(r.data)}else e(n.posts[0])}))},ei=(e,t)=>{const n=we();return Xe(n,e,e,(r=>{var s;if(n.cache){const o=["comment.flagged","comment.unflagged"].includes(e)?(e=>{const t=Aa(e,"comment");return Ma(e,"comments",t)})(r):r;Kt(o);const{comments:a}=o;if(a.length>0){const r=Se(["comment","get",a[0].commentId]);if(["comment.created"].includes(e)){if("comment.created"===e&&r.data.userId===n.userId)return;if(a[0].parentId){const e=Se(["comment","get",a[0].parentId]);(null==e?void 0:e.data)&&(e.data.children.includes(a[0].commentId)||_e(["comment","get",a[0].parentId],Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,a[0].commentId])]})))}const t=null===(s=Ie(["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)===r.data.referenceId}));null==t||t.map((({key:e,data:t})=>Oe(e,t,{cachedAt:-1})))}t(wn.comment(r.data))}}else t(wn.comment(r.comments[0]))}))},ti=(e,t)=>{const n=we();return Xe(n,e,e,(r=>{var s;if(n.cache){const n=r;Kt(n);const{comments:o}=n;if(o.length>0){const n=Se(["comment","get",o[0].commentId]);if(["local.comment.created"].includes(e)){if(o[0].parentId){const e=Se(["comment","get",o[0].parentId]);if((null==e?void 0:e.data)&&!e.data.children.includes(o[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,o[0].commentId])]});_e(["comment","get",o[0].parentId],t),setTimeout((()=>{Ze("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}const e=null===(s=Ie(["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})=>Oe(e,t,{cachedAt:-1})))}t(wn.comment(n.data))}}else t(wn.comment(r.comments[0]))}))},ni=e=>ei("comment.created",e),ri=e=>ei("comment.updated",e),si=e=>ei("comment.deleted",e),oi=e=>ei("comment.flagged",e),ai=e=>ei("comment.unflagged",e),ii=e=>{const t=we();return Xe(t,"comment.addReaction","comment.addReaction",(n=>{if(t.cache){const t=zt(Ra("comment.addReaction",n),["reactor"]);Kt(t);const r=Se(["comment","get",n.comments[0].commentId]);e(wn.comment(r.data))}else e(wn.comment(n.comments[0]))}))},ci=e=>{const t=we();return Xe(t,"comment.removeReaction","comment.removeReaction",(n=>{if(t.cache){const t=zt(Ra("comment.removeReaction",n),["reactor"]);Kt(t);const r=Se(["comment","get",n.comments[0].commentId]);e(wn.comment(r.data))}else e(wn.comment(n.comments[0]))}))},li=(e,t,n)=>{const r=we(),s=(r,s,o)=>{r===e&&s===t&&n(o)};if("message"===e){return Xe(r,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await Yn(e);t.reactions[0]&&(Kt(t),Kt({reactors:t.reactions}),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return Xe(r,"post.addReaction","post.addReaction",(e=>{const{reactor:t}=e,n=zt(e,["reactor"]);Kt(n),Kt({reactions:[t]}),s("post",e.posts[0].postId,t)}))}if("story"===e){return Xe(r,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=zt(e,["reactions"]);Kt(n),Kt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}))}return Xe(r,"comment.addReaction","comment.addReaction",(e=>{const{reactor:t}=e,n=zt(e,["reactor"]);Kt(n),Kt({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))},di=(e,t,n)=>{const r=we(),s=(r,s,o)=>{r===e&&s===t&&n(o)};if("message"===e){return Xe(r,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await Yn(e);t.reactions[0]&&(Kt(t),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return Xe(r,"post.removeReaction","post.removeReaction",(e=>{const{reactor:t}=e,n=zt(e,["reactor"]);Kt(n),Kt({reactions:[t]}),s("post",e.posts[0].postId,t)}))}if("story"===e){return Xe(r,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=zt(e,["reactions"]);Kt(n),Kt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}))}return Xe(r,"comment.removeReaction","comment.removeReaction",(e=>{const{reactor:t}=e,n=zt(e,["reactor"]);Kt(n),Kt({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))},ui=async e=>{we().log("reaction/queryReactor",e);const t=await(async e=>{const t=we();t.log("reaction/queryReactions",e);const n=null!=e?e:{},{page:r={limit:10}}=n,s=zt(n,["page"]),{data:o}=await t.http.get("/api/v3/reactions",{params:Object.assign(Object.assign({},s),{referenceVersion:5,options:{token:Y(r,"afterbeforeraw")}})}),{paging:a}=o,i=zt(o,["paging"]),{reactions:c}=i;Kt(Object.assign(Object.assign({},i),{reactions:c})),Kt(Object.assign(Object.assign({},i),{reactors:c[0].reactors}));const l=Z(a.next);return{data:c,prevPage:Z(a.previous),nextPage:l}})(e),{data:n}=t,r=zt(t,["data"]);return Object.assign(Object.assign({},r),{data:n[0].reactors})};var hi=Object.freeze({__proto__:null,addReaction:ja,removeReaction:xa,onReactionAdded:(e,t,n)=>{const r=r=>{de(e)(r)===t&&n(r)};if("message"===e){const e=we(),t=async e=>{var t;const n=await Yn(e),s=Se(["message","get",n.messages[0].messageId]),o=(null===(t=null==s?void 0:s.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Kt(n),o&&r(n.messages[0])};return Xe(e,"reaction/onReactionAdded","message.updated",t)}return"post"===e?Xa(r):ii(r)},onReactionRemoved:(e,t,n)=>{const r=r=>{de(e)(r)===t&&n(r)};if("message"===e){const e=we(),t=async e=>{var t;const n=await Yn(e),s=Se(["message","get",n.messages[0].messageId]),o=(null===(t=null==s?void 0:s.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Kt(n),o&&r(n.messages[0])};return Xe(e,"reaction/onReactionRemoved","message.updated",t)}return"post"===e?Za(r):ci(r)},onReactorAdded:li,onReactorRemoved:di,getReactions:(e,t,n)=>{const{log:r,cache:s}=we();s||console.log("For using Live Collection feature you need to enable Cache!");const o=Date.now();r(`liveReactions(tmpid: ${o}) > listen`);const{limit:a}=e,i=zt(e,["limit"]),c=null!=a?a:j,{policy:l=x}=null!=n?n:{},d=[],u=["reaction","collection",{referenceId:e.referenceId,referenceType:e.referenceType}],h=e=>{var n,r;const s=null!==(n=e.data.map((e=>Se(["reactor","get",e]))).filter(Boolean).map((({data:e})=>wn.reactor(e))))&&void 0!==n?n:[];t({onNextPage:f,data:s,hasNextPage:!!(null===(r=e.params)||void 0===r?void 0:r.page),loading:e.loading,error:e.error})},p=e=>t=>{var n;const r=null===(n=Se(u))||void 0===n?void 0:n.data;r&&("onAdded"===e?r.data=[...new Set([t.reactionId,...r.data])]:"onRemoved"===e&&(r.data=r.data.filter((e=>e!==t.reactionId))),_e(u,r),h(r))},f=(e=!1)=>{var t,n,r,s;const o=null===(t=Se(u))||void 0===t?void 0:t.data,a=null!==(n=null==o?void 0:o.data)&&void 0!==n?n:[];if(!e&&a.length>0&&!(null===(r=null==o?void 0:o.params)||void 0===r?void 0:r.page))return;const d=oe(ui,Object.assign(Object.assign({},i),{page:null!==(s=e||null==o?void 0:o.params.page)&&void 0!==s?s:{limit:c}}));ie(d,(({data:e,error:t,loading:n,nextPage:r})=>{const s={loading:n,error:t,params:{page:r},data:a};e&&(s.data=[...new Set([...a,...e.map(de("reactor"))])]),_e(u,s),h(s)}),ae(l))};return d.push(li(i.referenceType,i.referenceId,p("onAdded")),di(i.referenceType,i.referenceId,p("onRemoved"))),f(!0),()=>{r(`liveReactions(tmpid: ${o}) > dispose`),d.forEach((e=>e()))}}});function pi(e){const{comments:t}=e;return Object.assign(Object.assign({},e),{comments:t.map((e=>e.hasOwnProperty("myReactions")?e:Object.assign({myReactions:[]},e)))})}const fi=async e=>{const t=we();let n;t.log("channel/getChannel",e),lr("channel",e);try{const{data:r}=await t.http.get(`/api/v3/channels/${encodeURIComponent(e)}`);n=await Bn(r),t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&Ln(r)}catch(t){throw V(null==t?void 0:t.code)&&$t("channel",e),t}const r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const{channels:s}=n;return{data:s.find((t=>t.channelId===e)),cachedAt:r}};fi.locally=e=>{var t;const n=we();if(n.log("channel/getChannel.locally",e),!n.cache)return;const r=null===(t=Ie(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.channelPublicId===e));return r&&0!==(null==r?void 0:r.length)?{data:r[0].data,cachedAt:r[0].cachedAt}:void 0};const gi=(e,t,n)=>r=>e((e=>{var s,o;if(!e)return e;const a=we(),{objectSyncMap:i}=a,c=ue(e[t])?e[t]:null!==(s=i.get(e[t]))&&void 0!==s?s:e[t],l=null===(o=Se([n,"get",`${c}`]))||void 0===o?void 0:o.data;return l?r(l):void 0})),mi=e=>{const t=we(),n=[Xe(t,"onMessageUpdated","message.updated",(async t=>{const n=await Yn(t);Kt(n),e(n.messages[0])})),Xe(t,"onMessageUpdated","local.message.updated",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},yi=e=>{const t=we(),n=[Xe(t,"message/onMessageDeleted","message.deleted",(async t=>{const n=await Yn(t);Kt(n),e(n.messages[0])})),Xe(t,"message/onMessageDeleted","local.message.deleted",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},vi=e=>{const t=we(),n=[Xe(t,"onSubChannelUpdated","message-feed.updated",(async t=>{const n=await nr(t);Kt(n),e(n.messageFeeds[0])})),Xe(t,"onSubChannelUpdated","local.message-feed.updated",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}};function bi(e,t){_e(["channel","get",e.channelId],Object.assign(On(e),t))}const wi=e=>{const t=we();return Xe(t,"channelMarker/onChannelMarkerUpdated","local.channelMarker.updated",(t=>{e(t.userEntityMarkers[0])}))},Ci=async(e,t=!1)=>{const n=we(),r=await dr(e);await n.http.delete(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{params:{permanent:t}});const s=Object.assign(Object.assign({},r.data),{isDeleted:!0,updatedAt:pe(r.data.updatedAt)});return t?setTimeout((()=>{$t("subChannel",e)}),0):Oe(["subChannel","get",e],s),Ze("local.message-feed.deleted",{messageFeeds:[s]}),s},Ii=e=>Xe(we(),"onSubChannelFetched","local.message-feed.fetched",(t=>e(t.messageFeeds[0]))),Si=async e=>{const t=we();t.log("message/getMessages",e);const{data:n}=await t.http.get("/api/v5/messages/list",{params:{messageIds:e.map(encodeURIComponent)}}),r=await Yn(n),s=t.cache&&Date.now();t.cache&&Kt(r,{cachedAt:s});const{messages:o}=r;return Ze("local.message.fetched",{messages:o}),{data:o.map((e=>wn.message(e))),cachedAt:s}};Si.locally=e=>{var t;const n=we();if(n.log("message/getMessages.locally",e),!n.cache)return;const r=e.map((e=>Se(["message","get",e]))).filter(Boolean),s=r.map((({data:e})=>e)),o=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:s,cachedAt:o.cachedAt}};const _i=()=>`LOCAL_${xt()}`;let ki;const Oi=async(e,t)=>{const n=we();n.log("message/updateMessage",t),console.warn("MessageRepository.updateMessage will be replaced with MessageRepository.editMessage");const{data:r}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,Xn(t)),s=await Yn(r),o=n.cache&&Date.now();n.cache&&Kt(s,{cachedAt:o});const{messages:a}=s;return Ze("local.message.updated",{messages:a}),{data:wn.message(a.find((t=>t.messageId===e))),cachedAt:o}};Oi.optimistically=(e,t)=>{const n=we();if(n.log("message/updateMessage.optimistically",t),!n.cache)return;const r=Se(["message","get",e]);if(!r)return;const s=Object.assign(Object.assign(Object.assign({},r.data),t),{updatedAt:(new Date).toISOString()});return Oe(["message","get",e],s,{cachedAt:-1}),Ze("local.message.updated",{messages:[s]}),{data:wn.message(s),cachedAt:-1}};const Ti=async(e,t)=>{const n=we();n.log("message/editMessage",t);const{data:r}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,Xn(t)),s=await Yn(r),o=n.cache&&Date.now();n.cache&&Kt(s,{cachedAt:o});const{messages:a}=s;return Ze("local.message.updated",{messages:a}),{data:wn.message(a.find((t=>t.messageId===e))),cachedAt:o}};Ti.optimistically=(e,t)=>{const n=we();if(n.log("message/editMessage.optimistically",t),!n.cache)return;const r=Se(["message","get",e]);if(!r)return;const s=Object.assign(Object.assign(Object.assign({},r.data),t),{updatedAt:(new Date).toISOString()});return Oe(["message","get",e],s,{cachedAt:-1}),Ze("local.message.updated",{messages:[s]}),{data:wn.message(s),cachedAt:-1}};const Ei=async e=>{const t=we();t.log("message/deleteMessage",e);const{data:n}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`),r=await Yn(n);return Ze("local.message.deleted",{messages:[r.messages[0]]}),wn.message(r.messages[0])};Ei.optimistically=e=>{we().log("message/deleteMessage.optimistically",e);const t=Se(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return Oe(["message","get",e],n,{cachedAt:-1}),Ze("local.message.deleted",{messages:[n]}),{data:wn.message(n),cachedAt:-1}};const Ai=async e=>{const t=we();t.log("message/softDeleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const n=await ka(e);return Ze("local.message.deleted",{messages:[n.data]}),wn.message(n.data)};Ai.optimistically=e=>{we().log("message/softDeleteMessage.optimistically",e);const t=Se(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return Oe(["message","get",e],n,{cachedAt:-1}),Ze("local.message.deleted",{messages:[n]}),{data:wn.message(n),cachedAt:-1}};const Mi=async e=>{const t=we();t.log("user/getReadUsers",e);const{page:n,messageId:r}=e,s=zt(e,["page","messageId"]),{data:o}=await t.http.get(`/api/v1/markers/messages/${r}/read-users`,{params:Object.assign(Object.assign({},s),{options:{token:Y(n,"afterbeforeraw")}})}),{paging:a,publicUserIds:i,userFeedMarkers:c}=o,l=zt(o,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Kt(Object.assign(Object.assign({},l),{userFeedMarkers:Jt(c)}),{cachedAt:d});const e=["read-user","query",Object.assign(Object.assign({messageId:r},s),{options:Object.assign({},n)})];_e(e,{users:i,paging:a})}let u=[];i.length>0&&({data:u}=await aa(i));return{data:u,cachedAt:d,prevPage:X(a.previous),nextPage:X(a.next)}};Mi.locally=e=>{var t;const n=we();if(n.log("user/getReadUsers.locally",e),!n.cache)return;const{page:r}=e,s=zt(e,["page"]),o=["read-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},r)})],{data:a,cachedAt:i}=null!==(t=Se(o))&&void 0!==t?t:{},c=null==a?void 0:a.users.map((e=>{var t;return null===(t=Se(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:i,prevPage:X(null==a?void 0:a.paging.previous),nextPage:X(null==a?void 0:a.paging.next)}};const Pi=async e=>{const t=we();t.log("user/getDeliveredUsers",e);const{page:n,messageId:r}=e,s=zt(e,["page","messageId"]),{data:o}=await t.http.get(`/api/v1/markers/messages/${r}/delivered-users`,{params:Object.assign(Object.assign({},s),{options:{token:Y(n,"afterbeforeraw")}})}),{paging:a,publicUserIds:i,userFeedMarkers:c}=o,l=zt(o,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Kt(Object.assign(Object.assign({},l),{userFeedMarkers:Jt(c)}),{cachedAt:d});const e=["delivered-user","query",Object.assign(Object.assign({messageId:r},s),{options:Object.assign({},n)})];_e(e,{users:i,paging:a})}let u=[];i.length>0&&({data:u}=await aa(i));return{data:u,cachedAt:d,prevPage:X(a.previous),nextPage:X(a.next)}};Pi.locally=e=>{var t;const n=we();if(n.log("user/getDeliveredUsers.locally",e),!n.cache)return;const{page:r}=e,s=zt(e,["page"]),o=["delivered-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},r)})],{data:a,cachedAt:i}=null!==(t=Se(o))&&void 0!==t?t:{},c=null==a?void 0:a.users.map((e=>{var t;return null===(t=Se(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:i,prevPage:X(null==a?void 0:a.paging.previous),nextPage:X(null==a?void 0:a.paging.next)}};const Ri=e=>{const t=we();return Xe(t,"onMessageFlagged","message.flagged",(async t=>{const n=await Yn(t);Kt(n),e(n.messages[0])}))},Ui=e=>{const t=we();return Xe(t,"onMessageUnflagged","message.unflagged",(async t=>{const n=await Yn(t);Kt(n),e(n.messages[0])}))},ji=e=>{const t=we();return Xe(t,"onMessageFlagCleared","message.flagCleared",(async t=>{const n=await Yn(t);Kt(n),e(n.messages[0])}))},xi=e=>{const t=we();return Xe(t,"onMessageReactionAdded","message.reactionAdded",(async t=>{const n=await Yn(t,"message.reactionAdded");Kt(n),e(n.messages[0])}))},Di=e=>{const t=we();return Xe(t,"onMessageReactionRemoved","message.reactionRemoved",(async t=>{const n=await Yn(t,"message.reactionRemoved");Kt(n),e(n.messages[0])}))},Ni=e=>{const t=we();return Xe(t,"message/onMessageFetched","local.message.fetched",(t=>{Kt(t),e(t.messages[0])}))};class Bi extends Io{constructor(e,t,n,r,s){super(e,t),this.notifyChange=n,this.preparePayload=r,this.paginationController=s}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)_e(this.cacheKey,{data:Os(e.messages),query:this.query});else{const n=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,o=null!==(s=null==n?void 0:n.data)&&void 0!==s?s:[];_e(this.cacheKey,Object.assign(Object.assign({},n),{data:"next"===t?[...new Set([...o,...Os(e.messages)])]:[...new Set([...Os(e.messages),...o])]}))}}reactor(e){return t=>{var n,r,s,o,a;if("onCreate"===e){const e=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data,{referenceId:i}=t;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===(r=this.query.excludingTags)||void 0===r?void 0:r.some((e=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.includes(e)}))))return;if(this.query.excludeTags&&(null===(s=this.query.excludeTags)||void 0===s?void 0:s.some((e=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.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===(o=this.query.includingTags)||void 0===o?void 0:o.some((e=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.includes(e)}))))return;if(this.query.tags&&!(null===(a=this.query.tags)||void 0===a?void 0:a.some((e=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.includes(e)}))))return;this.query.sortBy&&"segmentDesc"!==this.query.sortBy||this.paginationController.getPrevToken()||(e.data=[...new Set([null!=i?i:t.messageId,...e.data])]),"segmentAsc"!==this.query.sortBy||this.paginationController.getNextToken()||(e.data=[...new Set([...e.data,null!=i?i:t.messageId])]),_e(this.cacheKey,e)}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class qi extends wo{async getRequest(e,t){const n=Zn(e),{data:r}=await this.http.get("/api/v5/messages",{params:Object.assign(Object.assign({},n),{options:t?{token:t}:Object.assign({},n.options)})});return r}}class Fi extends ko{constructor(e,t){const n=w.default(e),r=["message","collection",n];super(new qi(e),n,r,t),this.query=e,this.queryStreamController=new Bi(this.query,this.cacheKey,this.notifyChange.bind(this),Yn,this.paginationController),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Ts,action:"onCreate"},{fn:Es,action:"onCreate"},{fn:yi,action:"onDelete"},{fn:mi,action:"onUpdate"},{fn:Ri,action:"onFlagged"},{fn:Ui,action:"onUnflagged"},{fn:ji,action:"onFlagCleared"},{fn:xi,action:"onReactionAdded"},{fn:Di,action:"onReactionRemoved"},{fn:gi(lo,"contentId","message"),action:"onUpdate"},{fn:gi(uo,"contentId","message"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const o=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const a=this.applyFilter(null!==(s=o.data.map((e=>(e=>{var t,n;const r=we(),{objectSyncMap:s}=r,o=ue(e)?e:null!==(t=s.get(e))&&void 0!==t?t:e;return null===(n=Se(["message","get",o]))||void 0===n?void 0:n.data})(e))).filter(Boolean).map((e=>wn.message(e))))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),onPrevPage:()=>this.loadPage({direction:"prev"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),hasPrevPage:!!this.paginationController.getPrevToken(),loading:t,error:n})}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=Ee(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}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],query:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}}const Li=async(e,t=!1)=>{const n=we();let r;n.log("message/getMessage",e),t||console.log("getMessage will be deprecated on 15th November 2022, please use liveMessage instead."),lr("message",e);try{const{data:t}=await n.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);r=await Yn(t)}catch(t){throw V(null==t?void 0:t.code)&&$t("message",e),t}const s=n.cache&&Date.now();n.cache&&Kt(r,{cachedAt:s});const{messages:o}=r;return Ze("local.message.fetched",{messages:o}),{data:wn.message(o.find((t=>t.messageId===e))),cachedAt:s}};Li.locally=e=>{const t=we();if(t.log("message/getMessage.locally",e),!t.cache)return;const n=Se(["message","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};var Ki=Object.freeze({__proto__:null,getMessageByIds:Si,createMessage:async e=>{const t=we(),{objectSyncMap:n}=t;t.log("message/createMessage",e);const r=(e=>{var t,n;const r=we(),{objectSyncMap:s}=r;if(!r.cache)return;ki=e.referenceId||_i();const o=Object.assign({messageId:ki,uniqueId:ki},e);r.log("message/createMessage.optimistically",o);const a=Se(["subChannel","get",e.subChannelId]);if(a&&(Oe(["subChannel","get",e.subChannelId],Object.assign(Object.assign({},a.data),{messageCount:a.data.messageCount+1})),a.data.channelId===a.data.subChannelId)){const e=Se(["channel","get",a.data.channelId]);(null==e?void 0:e.data)&&Oe(["channel","get",a.data.channelId],Object.assign(Object.assign({},e.data),{messageCount:(null!==(t=e.data.messageCount)&&void 0!==t?t:0)+1}))}const i=(new Date).toISOString(),c=Object.assign({creatorId:r.userId,creatorPrivateId:Qe()._id,channelSegment:(null!==(n=null==a?void 0:a.data.messageCount)&&void 0!==n?n:0)+1,childrenNumber:0,createdAt:i,updatedAt:i,syncState:"syncing",isDeleted:!1},o);return _e(["message","get",c.messageId],c,{cachedAt:-5}),s.set(c.messageId,void 0),Ze("local.message.created",{messages:[c]}),c})(e),s=e.referenceId||ki||_i();ki=void 0;try{const{data:r}=await t.http.post("/api/v5/messages",Object.assign(Object.assign({},Xn(e)),{referenceId:s}));n.set(s,r.messages[0].messageId),n.set(r.messages[0].messageId,s);const o=await Yn(r),{messages:a}=o,i=t.cache&&Date.now();return t.cache&&Kt(o,{cachedAt:i}),Ze("local.message.created",{messages:[Object.assign(Object.assign({},a[0]),{syncState:"synced"})]}),{data:wn.message(a[0]),cachedAt:i}}catch(e){throw Ze("local.message.created",{messages:[Object.assign(Object.assign({},r),{syncState:"error"})]}),e}},updateMessage:Oi,editMessage:Ti,deleteMessage:Ei,softDeleteMessage:Ai,markAsDelivered:async(e,t)=>{const n=we();n.log("message/markAsDelivered",e,t);const{data:r}=await n.http.put(`/api/v1/markers/message-feeds/${e}/mark-delivering`,{messageId:t}),{userMarkers:s,userEntityMarkers:o,userFeedMarkers:a}=r,i=zt(r,["userMarkers","userEntityMarkers","userFeedMarkers"]),c=n.cache&&Date.now();return n.cache&&Kt(Object.assign({userMarkers:s,userEntityMarkers:Wt(o),userFeedMarkers:Jt(a)},i),{cachedAt:c}),!0},getReadUsers:Mi,getDeliveredUsers:Pi,flagMessage:async e=>{const t=we();t.log("message/flag",e);const{data:n}=await t.http.post(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await Yn(n);Kt(e)}return Ze("message.flagged",n),!!n},unflagMessage:async e=>{const t=we();t.log("message/unflag",e);const{data:n}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await Yn(n);Kt(e)}return Ze("message.unflagged",n),!!n},isMessageFlaggedByMe:async e=>{const t=we();t.log("message/isMessageFlaggedByMe",e);const{data:n}=await t.http.get(`/api/v5/messages/${encodeURIComponent(e)}/flags`);return n.result},onMessageCreatedMqtt:Ts,onMessageCreatedLocal:Es,onMessageUpdated:mi,onMessageDeleted:yi,onMessageFlagged:Ri,onMessageUnflagged:Ui,onMessageFlagCleared:ji,onMessageReactionAdded:xi,onMessageReactionRemoved:Di,onMessageFetched:Ni,getMessage:(e,t)=>go(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?wn.message(e.data):n}))}),"messageId",ka,[Ni,mi,yi,Ri,Ui,ji,xi,Di,gi(lo,"contentId","message"),gi(uo,"contentId","message")]),getMessages:(e,t,n)=>{const{log:r,cache:s}=we();s||console.log(D);const o=Date.now();r(`getMessages(tmpid: ${o}) > listen`);const a=new Fi(e,t),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>{Te(c)})),()=>{r(`getMessages(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},observeMessage:(e,t,n="cache_then_server")=>{const{log:r}=we(),s=Date.now();r(`observeMessage(tmpid: ${s}) > listen`),console.log("observeMessage will be deprecated on 15th November 2022, please use liveMessage instead.");const o=(n,r)=>{var s,o,a;if((null===(s=n.data)||void 0===s?void 0:s.messageId)===e){if(t instanceof Function)return t(n);"onFetch"!==r&&(null===(o=t.onEvent)||void 0===o||o.call(t,r,n)),null===(a=t[r])||void 0===a||a.call(t,n)}},a=[];return a.push(mi((e=>o({data:wn.message(e),loading:!1,origin:"event"},"onUpdate"))),yi((e=>o({data:wn.message(e),loading:!1,origin:"event"},"onDelete"))),gi(lo,"contentId","message")((e=>o({data:wn.message(e),loading:!1,origin:"event"},"onUpdate"))),gi(uo,"contentId","message")((e=>o({data:wn.message(e),loading:!1,origin:"event"},"onUpdate")))),"no_fetch"!==n&&ie(oe(Li,e),(e=>e.data&&o(e,"onFetch")),ae(n)),()=>{r(`observeMessages(tmpid: ${s}) > dispose`),a.forEach((e=>e()))}},observeMessages:(e,t)=>{const{log:n}=we(),r=Date.now();n(`observeMessages(tmpid: ${r}) > listen`);const s=[],o=(n,r)=>{var s,o,a;if((null===(s=n.data)||void 0===s?void 0:s.subChannelId)===e){if(t instanceof Function)return t(n);null===(o=t.onEvent)||void 0===o||o.call(t,r,n),null===(a=t[r])||void 0===a||a.call(t,n)}};return s.push(Ts((e=>o({data:wn.message(e),loading:!1,origin:"event"},"onCreate"))),Es((e=>o({data:wn.message(e),loading:!1,origin:"event"},"onCreate"))),mi((e=>o({data:wn.message(e),loading:!1,origin:"event"},"onUpdate"))),yi((e=>o({data:wn.message(e),loading:!1,origin:"event"},"onDelete"))),gi(lo,"contentId","message")((e=>o({data:wn.message(e),loading:!1,origin:"event"},"onCreate"))),gi(uo,"contentId","message")((e=>o({data:wn.message(e),loading:!1,origin:"event"},"onCreate")))),()=>{n(`observeMessages(tmpid: ${r}) > dispose`),s.forEach((e=>e()))}},convertFromRaw:Jn,prepareMessagePayload:Yn,convertParams:Xn,convertQueryParams:Zn,getMessageIdentifierIds:Os});const $i=e=>{const t=we();return Xe(t,"subChannelMarker/onSubChannelUnreadUpdatedLocal","local.subChannelUnread.updated",(t=>{e(t)}))};class zi extends wo{async getRequest(e,t){var n;const{limit:r=j}=e,s=null!==(n=function(e){var{excludeDefaultSubChannel:t}=e,n=zt(e,["excludeDefaultSubChannel"]);const r=Object.assign({},n);return void 0!==t&&(r.excludeDefaultMessageFeed=t),r}(zt(e,["limit"])))&&void 0!==n?n:{},{channelId:o,includeDeleted:a}=s,i=zt(s,["channelId","includeDeleted"]),c=t?{token:t}:{limit:r},{data:l}=await this.http.get(`/api/v5/message-feeds/channel/${o}`,{params:Object.assign(Object.assign({},i),{isDeleted:zn(a),options:c})});return l}}class Qi extends Io{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)_e(this.cacheKey,{data:e.messageFeeds.map((({messageFeedId:e})=>e))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.messageFeeds.map((({messageFeedId:e})=>e))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(!Array.isArray(t)){if(this.query.channelId!==t.channelId)return;"onCreate"===e&&(r.data=[...new Set([t.subChannelId,...r.data])]),_e(this.cacheKey,r)}this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Vi extends ko{constructor(e,t){const n=w.default(e),r=["subChannel","collection",n];super(new zi(e),n,r,t),this.query=e,this.queryStreamController=new Qi(this.query,this.cacheKey,this.notifyChange.bind(this),nr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[]})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Ii,action:"onCreate"},{fn:As,action:"onCreate"},{fn:Ms,action:"onDelete"},{fn:e=>vi((async t=>{var n;const r=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;if(!r||!r.data.includes(t.subChannelId))return;const s=we();if("no-message-preview"!==await s.getMessagePreviewSetting(!1)){const e=Sn(t.subChannelId);(null==e?void 0:e.subChannelId)===t.subChannelId&&_e(["messagePreviewSubChannel","get",t.subChannelId],Object.assign(Object.assign({},e),{subChannelName:t.displayName,subChannelUpdatedAt:t.updatedAt}))}e(t)})),action:"onUpdate"},{fn:e=>Ts((async t=>{var n,r;const s=Se(["subChannel","get",t.subChannelId]);if(!s)return;const o=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;if(!o||!o.data.includes(t.subChannelId))return;await(async e=>{const t=we();"no-message-preview"!==await t.getMessagePreviewSetting(!1)&&En(e)})(t);const a=null===(r=Se(["subChannel","get",t.subChannelId]))||void 0===r?void 0:r.data;a&&(Tn(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=>Es((async t=>{var n,r;const s=Se(["subChannel","get",t.subChannelId]);if(!s)return;const o=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;if(!o||!o.data.includes(t.subChannelId))return;const a=we();if("no-message-preview"===await a.getMessagePreviewSetting(!1))return;En(t);const i=null===(r=Se(["subChannel","get",t.subChannelId]))||void 0===r?void 0:r.data;i&&(Tn(t.subChannelId,i,{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=>ao((t=>{var n;const r=null!==(n=t.map((({feedId:e})=>Se(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];0!==r.length&&e(r)})),action:"onUpdate"},{fn:gi(oo,"feedId","subChannel"),action:"onUpdate"},{fn:gi((e=>mi((async t=>{var n;const r=we();if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;const s=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;s&&s.data.includes(t.subChannelId)&&(An(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:gi((e=>yi((async t=>{var n;const r=we(),s=await r.getMessagePreviewSetting(!1);if("no-message-preview"===s)return;const o=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;o&&o.data.includes(t.subChannelId)&&("message-preview-not-include-deleted"===s?await dr(t.subChannelId):await An(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:gi($i,"subChannelId","subChannel"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const o=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const a=this.applyFilter(null!==(s=o.data.map((e=>Se(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(_n))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.includeDeleted||(t=Ee(e,"isDeleted",!1)),t.sort($e),t}}const Hi={},Wi=async e=>{const t=await(async e=>{const t=dr.locally(e);if(t)return t.data.channelId;const{data:n}=await dr(e);return n.channelId})(e),n=it({channelId:t,subChannelId:e});Hi[e]=pt(n)};var Ji=Object.freeze({__proto__:null,getSubChannelByIds:vr,createSubChannel:async e=>{const t=we();t.log("user/createSubChannel",e);const n=await t.http.post("/api/v5/message-feeds",{channelId:e.channelId,name:e.displayName}),r=await nr(n.data),s=t.cache&&Date.now();return t.cache&&Kt(r,{cachedAt:s}),Ze("message-feed.created",n.data),{data:r.messageFeeds[0],cachedAt:s}},updateSubChannel:async(e,t)=>{const n=we();n.log("channel/updateSubChannel",e,t);const r=await n.http.put(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{name:t.displayName}),s=await nr(r.data),o=n.cache&&Date.now();return n.cache&&Kt(s,{cachedAt:o}),Ze("message-feed.updated",r.data),{data:s.messageFeeds[0],cachedAt:o}},deleteSubChannel:Ci,hardDeleteSubChannel:async e=>{we().log("channel/hardDeleteSubChannel",e);return await Ci(e,!0)},softDeleteSubChannel:async e=>{we().log("channel/softDeleteSubChannel",e);return await Ci(e,!1)},onSubChannelCreated:As,onSubChannelUpdated:vi,onSubChannelDeleted:Ms,getSubChannel:(e,t)=>{const n=we();let r;return go(e,(e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:_n(e.data)}),s=zt(n,["origin"]);return ln(r,s)?void 0:(r=s,t(n))}),"subChannelId",dr,[Ii,t=>vi((async r=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(Mn(r),r.subChannelId===e&&t(r))})),Ms,gi(oo,"feedId","subChannel"),t=>ao((n=>{var r;if(!n.find((({feedId:t})=>t===e)))return;const s=null===(r=Se(["subChannel","get",e]))||void 0===r?void 0:r.data;s&&t(s)})),gi((t=>Ts((async r=>{await(async t=>{var r;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await En(t),t.subChannelId!==e)return;const s=null===(r=Se(["subChannel","get",e]))||void 0===r?void 0:r.data;s&&Tn(t.subChannelId,s,{messagePreviewId:t.messageId})})(r),t(r)}))),"subChannelId","subChannel"),gi((t=>Es((async r=>{await(async t=>{var r;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await En(t),t.subChannelId!==e)return;const s=null===(r=Se(["subChannel","get",e]))||void 0===r?void 0:r.data;s&&Tn(t.subChannelId,s,{messagePreviewId:t.messageId})})(r),t(r)}))),"subChannelId","subChannel"),gi((t=>mi((async r=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&r.subChannelId===e&&(An(r),t(r))}))),"subChannelId","subChannel"),gi((t=>yi((async r=>{const s=await n.getMessagePreviewSetting(!1);"no-message-preview"!==s&&r.subChannelId===e&&("message-preview-include-deleted"===s&&await An(r),"message-preview-not-include-deleted"===s&&await dr(r.subChannelId),t(r))}))),"subChannelId","subChannel"),gi($i,"subChannelId","subChannel")],{forceDispatch:!0})},getSubChannels:(e,t,n)=>{const{log:r,cache:s}=we(),o=Date.now();r(`getSubChannels(tmpid: ${o}) > listen`),s||console.log(D);const a=new Vi(e,t),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>{Te(c)})),()=>{r(`getSubChannels(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},markReadEngineOnLoginHandler:mr,startReading:async e=>{pr[e]=!0,0===hr.length&&(hr.length>0||hr.push(cr((()=>{fr()}))),yr(e));try{return await(async e=>{const t=we();t.log("subChannel/startReadingAPI",e);const{data:n}=await t.http.post(`/api/v1/markers/message-feeds/${e}/start-reading`),{userEntityMarkers:r,userFeedMarkers:s,feedMarkers:o,userMarkers:a}=n,i=Wt(r),c=Jt(s),l=t.cache&&Date.now();return t.cache&&Kt({userEntityMarkers:i,userFeedMarkers:c,feedMarkers:o,userMarkers:a},{cachedAt:l}),Ze("local.feedMarker.fetched",{feedMarkers:o}),Ze("local.channelMarker.fetched",{userEntityMarkers:i}),Ze("local.subChannelMarker.fetched",{userFeedMarkers:c}),Ze("local.userMarker.fetched",{userMarkers:a}),!0})(e)}catch(t){return pr[e]=!1,!1}},stopReading:e=>(pr[e]=!1,hr.forEach((e=>e())),hr=[],(async e=>{const t=we();t.log("channel/stopReadingAPI",e);const{data:n}=await t.http.post(`/api/v1/markers/message-feeds/${e}/stop-reading`),{userEntityMarkers:r,userFeedMarkers:s,feedMarkers:o,userMarkers:a}=n,i=Wt(r),c=Jt(s),l=t.cache&&Date.now();return t.cache&&Kt({userEntityMarkers:i,userFeedMarkers:c,feedMarkers:o,userMarkers:a},{cachedAt:l}),Ze("local.feedMarker.fetched",{feedMarkers:o}),Ze("local.channelMarker.fetched",{userEntityMarkers:i}),Ze("local.subChannelMarker.fetched",{userFeedMarkers:c}),Ze("local.userMarker.fetched",{userMarkers:a}),!0})(e)),startMessageReceiptSync:async e=>(await Wi(e),!0),stopMessageReceiptSync:e=>(Hi[e]&&Hi[e](),!0)});const Gi=e=>{const t=we();return Xe(t,"channelMarker/onChannelUnreadUpdatedLocal","local.channelUnread.updated",(t=>{e(t)}))};class Yi extends wo{async getRequest(e,t){const{limit:n=j,displayName:r,membership:s}=e,o=zt(e,["limit","displayName","membership"]),a=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/channels",{params:Object.assign(Object.assign({},o),{keyword:r,filter:s,options:a})});return i}}class Xi extends _o{async getRequest(e){const{data:t}=await this.http.get("/api/v3/channels/list",{params:Object.assign({},e)});return t}}class Zi extends Io{constructor(e,t,n,r,s){super(e,t),this.notifyChange=n,this.preparePayload=r,this.paginationController=s}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)_e(this.cacheKey,{data:e.channels.map(de("channel"))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channels.map(de("channel"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(this.paginationController instanceof Xi)return this.notifyChange({origin:"event",loading:!1});["onCreate","onJoin","onResolve"].includes(e)&&(Array.isArray(t)?r.data=[...new Set([...t.map(de("channel")),...r.data])]:r.data=[...new Set([t.channelInternalId,...r.data])]),_e(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const ec=(e,t)=>{const n=we();if(n.isUnreadCountEnabled&&n.getMarkerSyncConsistentMode()){Kr().resolve(e.channelId,"userMessageFeedMarker")}else t(e)},tc=e=>{const t=we();return Xe(t,"onChannelResolved","local.channel.resolved",(async t=>{e(t)}))};class nc extends ko{constructor(e,t){const n=w.default(e),r=["channel","collection",n],s=nc.getPaginationController(e);super(s,n,r,t),this.query=e,this.queryStreamController=new Zi(this.query,this.cacheKey,this.notifyChange.bind(this),(async e=>{try{const t=we();t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await Ln(e)}catch(e){console.error("Error while preparing unread count info",e)}return Bn(e)}),s),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE(this.getSubscriptions())}notifyChange({origin:e,loading:t,error:n}){var r,s;const o=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;let a=null!==(s=o.data.map((e=>Se(["channel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(Cn).map(wn.channel))&&void 0!==s?s:[];this.paginationController instanceof Yi&&(a=this.applyFilter(a)),(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:this.paginationController instanceof Yi?()=>this.loadPage({direction:"next"}):void 0,data:a,hasNextPage:this.paginationController instanceof Yi&&!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=we();let n=e;switch(n=Ee(n,"isDeleted",this.query.isDeleted),n=Ae(n,"displayName",this.query.displayName),this.query.types&&(n=n.filter((e=>{var t;return null===(t=this.query.types)||void 0===t?void 0:t.includes(e.type)}))),this.query.tags&&(n=n.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&&(n=n.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&&(n=Pe(n,this.query.membership,t)),this.query.sortBy){case"firstCreated":n=n.sort(Be);break;case"lastCreated":n=n.sort(Fe);break;case"displayName":n=n.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(De);break;default:n=n.sort($e)}return n}shouldAbort(e){var t,n;const r=null===(t=Se(this.cacheKey))||void 0===t?void 0:t.data;if(!r)return!0;return!(null===(n=null==r?void 0:r.data)||void 0===n?void 0:n.find((t=>t===e)))}static getMessagePreviewSetting(){return we().getMessagePreviewSetting(!1)}static getPaginationController(e){return e.channelIds&&e.channelIds.length>0?new Xi(e):new Yi(e)}getSubscriptions(){const e=[{fn:gi((e=>Ts((t=>{var n;const r=null===(n=Se(["channel","get",t.channelId]))||void 0===n?void 0:n.data;if(r)bi(r,{lastActivity:t.createdAt}),e(t);else{Kr().resolve(t.channelId,"channel")}}))),"messageId","channel"),action:"onUpdate"},{fn:gi((e=>Es((t=>{var n;const r=null===(n=Se(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(bi(r,{lastActivity:t.createdAt}),e(t))}))),"messageId","channel"),action:"onUpdate"},{fn:Ur,action:"onDelete"},{fn:es,action:"onUpdate"},{fn:ls,action:"onMute"},{fn:e=>rs((t=>{ec(t,e)})),action:"onJoin"},{fn:e=>as(((t,n)=>{var r,s;const{userId:o}=we();if("member"===this.query.membership&&o===n.userId){const e=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;_e(this.cacheKey,Object.assign(Object.assign({},e),{data:null!==(s=null==e?void 0:e.data.filter((e=>e!==t.channelId)))&&void 0!==s?s:[]}))}return e(t)})),action:"onLeft"},{fn:hs,action:"onMemberAdded"},{fn:gs,action:"onMemberRemoved"},{fn:gi(so,"entityId","channel"),action:"onUpdate"},{fn:gi(wi,"entityId","channel"),action:"onUpdate"},{fn:gi((e=>Ts((async t=>{var n;if("no-message-preview"===await nc.getMessagePreviewSetting())return;if(En(t),this.shouldAbort(t.channelId))return;const r=null===(n=Se(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(bi(r,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:gi((e=>Es((async t=>{var n;if("no-message-preview"===await nc.getMessagePreviewSetting())return;if(En(t),this.shouldAbort(t.channelId))return;const r=null===(n=Se(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(bi(r,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:gi((e=>mi((async t=>{"no-message-preview"!==await nc.getMessagePreviewSetting()&&(An(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:gi((e=>yi((async t=>{const n=await nc.getMessagePreviewSetting();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await An(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&await fi(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:gi((e=>Ms((async t=>{var n;const r=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;r.data.find((e=>{const n=Gt(e);return(null==n?void 0:n.subChannelId)===t.subChannelId}))&&(await fi(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:gi((e=>vi((async t=>{var n;if("no-message-preview"===await nc.getMessagePreviewSetting())return;(null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data)&&(await Mn(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:gi(As,"channelId","channel"),action:"onUpdate"},{fn:tc,action:"onResolve"},{fn:e=>(e=>{const t=we();return Xe(t,"userMessageFeedMarker/onUserMessageFeedMarkerResolved","local.userMessageFeedMarkers.resolved",(t=>{e(t)}))})((async t=>{if(t.feedMarkers){const n=[...new Set(t.feedMarkers.map((e=>e.entityId)))].map((e=>{var t;return null===(t=Se(["channel","get",e]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"onResolve"},{fn:gi(Gi,"channelId","channel"),action:"onUpdate"}];return this.paginationController instanceof wo?[...e,{fn:e=>Yr((t=>{ec(t,e)})),action:"onCreate"}]:e}}class rc extends wo{async getRequest(e,t){const{limit:n=j,includeDeleted:r}=e,s=zt(e,["limit","includeDeleted"]),o=t?{token:t}:{limit:n},a=!1!==r&&void 0,{data:i}=await this.http.get(`/api/v4/channels/${encodeURIComponent(s.channelId)}/users`,{params:Object.assign(Object.assign({},s),{options:o,isDeleted:a})});return i}}class sc extends Io{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)_e(this.cacheKey,{data:e.channelUsers.map((({channelId:e,userId:t})=>de("channelUsers")({channelId:e,userId:t})))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channelUsers.map((({channelId:e,userId:t})=>de("channelUsers")({channelId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;if(this.query.channelId!==t.channelId)return;const r=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;const s=de("channelUsers")({channelId:this.query.channelId,userId:t.userId});"none"===t.membership?r.data=r.data.filter((e=>e!==s)):r.data.includes(s)||(r.data=[s,...r.data]),_e(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class oc extends ko{constructor(e,t){const n=w.default(e),r=["channelUsers","collection",n];super(new rc(e),n,r,t),this.query=e,this.queryStreamController=new sc(this.query,this.cacheKey,this.notifyChange.bind(this),Bn),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:rs,action:"onJoin"},{fn:as,action:"onLeft"},{fn:hs,action:"onMemberAdded"},{fn:gs,action:"onMemberRemoved"},{fn:Dr,action:"onChannelMemberBanned"},{fn:vs,action:"onChannelMemberUnbanned"},{fn:Cs,action:"onChannelMemberRoleAdded"},{fn:_s,action:"onChannelMemberRoleRemoved"},{fn:(e=this.query.channelId,t=>{const n=we();return Xe(n,"user.deleted","user.deleted",(n=>{var r,s;const o=Nr(n);if(0===o.users.length)return;const a=o.users[0];Kt(o);const i=de("channelUsers")({channelId:e,userId:a.userId}),c=null===(r=Se(["channelUsers","get",i]))||void 0===r?void 0:r.data;Oe(["channelUsers","get",i],Object.assign(Object.assign({},c),{user:a}));const l=null===(s=Se(["channel","get",e]))||void 0===s?void 0:s.data;l&&t(l,c)}))}),action:"onChannelMemberChanged"}]);var e}notifyChange({origin:e,loading:t,error:n}){var r,s;const o=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const a=this.applyFilter(null!==(s=o.data.map((e=>Se(["channelUsers","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=Me(e,"roles",this.query.roles);this.query.memberships&&(t=t.filter((e=>{var t,n;return!(!(null===(t=this.query.memberships)||void 0===t?void 0:t.includes("muted"))||!e.isMuted)||"none"!==e.membership&&(null===(n=this.query.memberships)||void 0===n?void 0:n.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)),!1===this.query.includeDeleted&&(t=t.filter((e=>{var t;return!0!==(null===(t=e.user)||void 0===t?void 0:t.isDeleted)})));const n=this.query.sortBy?this.query.sortBy:"lastCreated";return t=t.sort("lastCreated"===n?Fe:Be),t}}const ac=(e,t,n)=>{const{log:r,cache:s}=we();s||console.log(D);const o=Date.now();r(`getMembers(tmpid: ${o}) > listen`);const a=new oc(e,t),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>{Te(c)})),()=>{r(`getMembers(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}};var ic=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=we();n.log("channel/addMembers",e,t);const{data:r}=await n.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users`,{channelId:e,userIds:t});t.forEach((e=>Ze("channel.membersAdded",Object.assign(Object.assign({},r),{channelUsers:r.channelUsers.filter((t=>t.userId===e))}))));const s=await Bn(r);n.cache&&Kt(s);const{channelUsers:o}=s;return!!o.find((t=>t.channelId===e&&"member"===t.membership))},removeMembers:async(e,t)=>{const n=we();n.log("channel/removeMembers",e,t);const{data:r}=await n.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users`,{data:{channelId:e,userIds:t}});t.forEach((e=>Ze("channel.membersRemoved",Object.assign(Object.assign({},r),{channelUsers:r.channelUsers.filter((t=>t.userId===e))}))));const s=await Bn(r);n.cache&&Kt(s);const{channelUsers:o}=s;return!!o.find((t=>t.channelId===e&&"member"!==t.membership))},applyFilter:(e,t)=>{let n=Me(e,"roles",t.roles);t.memberships&&(n=n.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."),n=xe(n,t.search));const r=t.sortBy?t.sortBy:"lastCreated";return n=n.sort("lastCreated"===r?Fe:Be),n},getMembers:ac,searchMembers:(e,t,n)=>ac(e,t)});var cc=Object.freeze({__proto__:null,addRole:async(e,t,n)=>{const r=we();r.log("channel/addRole",e,t,n);const{data:s}=await r.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{channelId:e,role:t,userIds:n}),o=await Bn(s);r.cache&&Kt(o),Ze("local.channel-moderator.role-added",o);const{channelUsers:a}=o;return!!a.find((n=>n.channelId===e&&n.roles.includes(t)))},removeRole:async(e,t,n)=>{const r=we();r.log("channel/removeRole",e,t,n);const{data:s}=await r.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{data:{channelId:e,role:t,userIds:n}}),o=await Bn(s);r.cache&&Kt(o),Ze("local.channel-moderator.role-removed",o);const{channelUsers:a}=o;return!!a.find((n=>n.channelId===e&&!n.roles.includes(t)))},banMembers:async(e,t)=>{const n=we();n.log("channel/banMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v3/channels/${e}/users/ban`,{userIds:t}),s=await Bn(r),{channelUsers:o}=s,a=n.cache&&Date.now();return n.cache&&Kt(s,{cachedAt:a}),{data:null==o?void 0:o.filter((e=>"banned"===e.membership)),cachedAt:a}},unbanMembers:async(e,t)=>{const n=we();n.log("channel/unbanMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}/users/unban`,{userIds:t}),s=await Bn(r),o=n.cache&&Date.now();n.cache&&Kt(s,{cachedAt:o});const{channelUsers:a}=s;return{data:null==a?void 0:a.filter((e=>"member"===e.membership)),cachedAt:o}},muteMembers:async(e,t,n=-1)=>{const r=we();r.log("channel/muteMembers",{userIds:t,channelId:e,mutePeriod:n});const{data:s}=await r.http.put(`/api/v2/channel/${e}/users/mute`,{userIds:t,mutePeriod:-1===n?n:1e3*n}),{success:o}=s;return o},unmuteMembers:async(e,t)=>{const n=we();n.log("channel/unmuteMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v2/channel/${encodeURIComponent(e)}/users/mute`,{userIds:t,mutePeriod:0}),{success:s}=r;return s}}),lc=Object.freeze({__proto__:null,Membership:ic,Moderation:cc,getChannelByIds:Kn,createChannel:async e=>{const t=we();let n;if(t.log("user/createChannel",e),"conversation"===(null==e?void 0:e.type))n=await t.http.post("/api/v3/channels/conversation",Object.assign(Object.assign({},e),{isDistinct:!0}));else{const{isPublic:r}=e,s=zt(e,["isPublic"]);n=await t.http.post("/api/v3/channels",Object.assign(Object.assign({},s),{isPublic:"community"===(null==e?void 0:e.type)?r:void 0}))}const r=await Bn(n.data),s=t.cache&&Date.now();t.cache&&Kt(r,{cachedAt:s});const{channels:o}=r;return{data:o[0],cachedAt:s}},updateChannel:async(e,t)=>{const n=we();n.log("channel/updateChannel",e,t);const{data:r}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}`,t),s=await Bn(r),o=n.cache&&Date.now();n.cache&&Kt(s,{cachedAt:o});const{channels:a}=s;return{data:a.find((t=>t.channelId===e)),cachedAt:o}},deleteChannel:async e=>{const t=we();t.log("channel/deleteChannel",e),await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}`);return(await fi(e)).data},joinChannel:async e=>{const t=we();t.log("channel/joinChannel",e);const{data:n}=await t.http.post(`/api/v3/channels/${encodeURIComponent(e)}/join`),r=await Bn(n);t.cache&&Kt(r);const{channelUsers:s}=r;return!!s.find((t=>t.channelId===e&&"member"===t.membership))},leaveChannel:async e=>{const t=we();t.log("channel/leaveChannel",e);const{data:n}=await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/leave`),r=await Bn(n);t.cache&&Kt(r);const{channelUsers:s}=r;return!!s.find((t=>t.channelId===e&&"member"!==t.membership))},muteChannel:async(e,t=-1)=>{const n=we();if(n.log("channel/muteChannel",e),-1!==t&&t<0)throw new fe("Mute Period can only be positive numbers or -1(mute forever)",800110,"error");const{data:r}=await n.http.put(`/api/v2/channel/${encodeURIComponent(e)}/mute`,{mutePeriod:t}),{success:s}=r;return s},unmuteChannel:async e=>{const t=we();t.log("channel/unmuteChannel",e);const{data:n}=await t.http.put(`/api/v2/channel/${encodeURIComponent(e)}/mute`,{mutePeriod:0}),{success:r}=n;return r},markAsRead:bn,onChannelCreated:Yr,onChannelUpdated:es,onChannelDeleted:Ur,onChannelJoined:rs,onChannelLeft:as,onChannelMuted:ls,onChannelMemberAdded:hs,onChannelMemberRemoved:gs,onChannelMemberBanned:Dr,onChannelMemberUnbanned:vs,onChannelMemberRoleAdded:Cs,onChannelMemberRoleRemoved:_s,observeChannel:(e,t)=>{const{log:n}=we(),r=Date.now();n(`observeChannel(tmpid: ${r}) > listen`);const s=(n,r)=>{var s,o,a;if((null===(s=n.data)||void 0===s?void 0:s.channelId)===e){if(t instanceof Function)return t(Object.assign(Object.assign({},n),{data:wn.channel(n.data)}));"onFetch"!==r&&(null===(o=t.onEvent)||void 0===o||o.call(t,r,Object.assign(Object.assign({},n),{data:wn.channel(n.data)}))),null===(a=t[r])||void 0===a||a.call(t,Object.assign(Object.assign({},n),{data:wn.channel(n.data)}))}},o=[];return o.push(es((e=>s({data:e,loading:!1,origin:"event"},"onUpdate"))),Ur((e=>s({data:e,loading:!1,origin:"event"},"onDelete"))),rs((e=>s({data:e,loading:!1,origin:"event"},"onJoin"))),as((e=>s({data:e,loading:!1,origin:"event"},"onLeft"))),ls((e=>s({data:e,loading:!1,origin:"event"},"onMute"))),hs((e=>s({data:e,loading:!1,origin:"event"},"onMemberAdded"))),gs((e=>s({data:e,loading:!1,origin:"event"},"onMemberRemoved"))),gi(so,"entityId","channel")((e=>s({data:e,loading:!1,origin:"event"},"onUpdate")))),ie(oe(fi,e),(e=>e.data&&s(e,"onFetch"))),()=>{n(`observeChannel(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},observeChannels:e=>{const{log:t}=we(),n=Date.now();t(`observeChannels(tmpid: ${n}) > listen`);const r=[],s=(t,n)=>{var r,s;if(e instanceof Function)return e(wn.channel(t));null===(r=e.onEvent)||void 0===r||r.call(e,n,wn.channel(t)),null===(s=e[n])||void 0===s||s.call(e,wn.channel(t))};return r.push(Yr((e=>s(e,"onCreate"))),es((e=>s(e,"onUpdate"))),Ur((e=>s(e,"onDelete"))),rs((e=>s(e,"onJoin"))),as((e=>s(e,"onLeft"))),ls((e=>s(e,"onMute"))),hs((e=>s(e,"onMemberAdded"))),gs((e=>s(e,"onMemberRemoved"))),gi(so,"entityId","channel")((e=>s(e,"onUpdate")))),()=>{t(`observeChannels(tmpid: ${n}) > dispose`),r.forEach((e=>e()))}},getChannel:(e,t)=>{const n=we();let r;return go(e,(async e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:wn.channel(Cn(e.data))}),s=zt(n,["origin"]);return ln(r,s)?void 0:(r=s,t(n))}),"channelId",fi,[es,Ur,rs,as,hs,gs,Dr,vs,ls,gi(so,"entityId","channel"),gi(wi,"entityId","channel"),gi((t=>Ts((async r=>{await(async r=>{var s;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await En(r),r.channelId!==e)return;const o=null===(s=Se(["channel","get",e]))||void 0===s?void 0:s.data;o&&(bi(o,{messagePreviewId:r.messageId}),t(r))})(r),t(r)}))),"channelId","channel"),gi((t=>Es((async r=>{var s;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await En(r),r.channelId!==e)return;const o=null===(s=Se(["channel","get",e]))||void 0===s?void 0:s.data;o&&(bi(o,{messagePreviewId:r.messageId}),t(r))}))),"channelId","channel"),gi((t=>mi((async r=>{var s;const o=null===(s=Se(["channel","get",e]))||void 0===s?void 0:s.data;if(!o||o.messagePreviewId!==r.messageId)return;"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(await An(r),t(r))}))),"channelId","channel"),gi((t=>yi((async r=>{var s;const o=null===(s=Se(["channel","get",e]))||void 0===s?void 0:s.data;if(!o||o.messagePreviewId!==r.messageId)return;const a=await n.getMessagePreviewSetting(!1);"no-message-preview"!==a&&("message-preview-not-include-deleted"===a?(Te(["messagePreviewChannel","get",e]),await fi(r.channelId)):await An(r),t(r))}))),"channelId","channel"),gi((e=>Ms((async t=>{var r,s;const{channelId:o,subChannelId:a}=t,i=null===(r=Se(["messagePreviewChannel","get",o]))||void 0===r?void 0:r.data;if(!i||i.subChannelId!==a)return;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;await fi(o);(null===(s=Se(["channel","get",o]))||void 0===s?void 0:s.data)&&e(t)}))),"channelId","channel"),gi((t=>vi((async r=>{var s,o;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;Mn(r);const a=null===(s=Se(["messagePreviewChannel","get",e]))||void 0===s?void 0:s.data;if(!a||a.subChannelId!==r.subChannelId)return;(null===(o=Se(["channel","get",e]))||void 0===o?void 0:o.data)&&t(r)}))),"channelId","channel"),gi(As,"channelId","channel"),gi(Gi,"channelId","channel")],{forceDispatch:!0})},getChannels:(e,t,n)=>{const{log:r,cache:s,userId:o}=we();s||console.log(D);const a=Date.now();r(`getChannels(tmpid: ${a}) > listen`);const i=new nc(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{Te(l)})),()=>{r(`getChannels(tmpid: ${a}) > dispose`),c.forEach((e=>e()))}},MARKER_INCLUDED_CHANNEL_TYPE:jn,isUnreadCountSupport:xn,convertFromRaw:Dn,preUpdateChannelCache:Nn,prepareChannelPayload:Bn});const dc=(e,t)=>{0!==e.length&&0!==t.length&&e.forEach((({communityId:e})=>{const n=t.filter((({communityId:t})=>e===t));_e(["communityUsers","collection",e],n)}))},uc=async e=>{const t=we();t.log("community/getCommunities",e);const{data:n}=await t.http.get("/api/v3/communities/list",{params:{communityIds:e}}),r=Ba(n),s=t.cache&&Date.now();return t.cache&&(Kt(r,{cachedAt:s}),dc(r.communities,r.communityUsers)),{data:r.communities,cachedAt:s}};uc.locally=e=>{var t;const n=we();if(n.log("community/getCommunities.locally",e),!n.cache)return;const r=e.map((e=>Se(["community","get",e]))).filter(Boolean),s=r.map((({data:e})=>e)),o=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:s,cachedAt:o.cachedAt}};const hc=async e=>{const t=we();t.log("community/getCommunity",e);const{data:n}=await t.http.get(`/api/v3/communities/${e}`),r=Ba(n),s=t.cache&&Date.now();t.cache&&(Kt(r,{cachedAt:s}),dc(r.communities,r.communityUsers));const{communities:o}=r;return{data:o.find((t=>t.communityId===e)),cachedAt:s}};hc.locally=e=>{const t=we();if(t.log("community/getCommunity.locally",e),!t.cache)return;const n=Se(["community","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const pc=async e=>{const t=we();t.log("channel/getTopTrendingCommunities",e);const{limit:n=5}=null!=e?e:{},{data:r}=await t.http.get("/api/v3/communities/top-trending",{params:{options:{limit:n}}}),s=Ba(r),{communities:o}=s,a=t.cache&&Date.now();if(t.cache){Kt(s,{cachedAt:a});_e(["community","top-trending",{params:{options:{limit:n}}}],{communities:o.map(de("community"))})}return{data:o,cachedAt:a}};pc.locally=e=>{var t,n;const r=we();if(r.log("community/getTopTrendingCommunities.locally",e),!r.cache)return;const{limit:s=5}=null!=e?e:{},o=["community","top-trending",{params:{options:{limit:s}}}],{data:a,cachedAt:i}=null!==(t=Se(o))&&void 0!==t?t:{};if(!(null==a?void 0:a.communities.length))return;const c=a.communities.map((e=>Se(["community","get",e]))).filter(Boolean).map((({data:e})=>e));return c.length===(null===(n=null==a?void 0:a.communities)||void 0===n?void 0:n.length)?{data:c,cachedAt:i}:void 0};const fc=(e,t)=>{const n=we();return Xe(n,e,e,(e=>{const r=Ba(e);if(n.cache){Kt(r);const e=Se(["community","get",r.communities[0].communityId]);t(e.data)}else t(r.communities[0])}))},gc=e=>fc("community.created",e),mc=e=>fc("community.updated",e),yc=e=>fc("community.deleted",e);function vc(e,t,n){return!!e.permissions.some((e=>e===n))||t.communityUsers.find((t=>t.userId===e.userId)).permissions.some((e=>e===n))}function bc(e,t){return"community.joined"===e||"community.left"===e?t.communityUsers:"community.userRemoved"===e||"local.community.userRemoved"===e?t.communityUsers.filter((e=>"none"===e.communityMembership)):"community.userBanned"===e?t.communityUsers.filter((e=>"banned"===e.communityMembership)):"community.userUnbanned"===e?t.communityUsers.filter((e=>!vc(e,t,"BAN_COMMUNITY_USER"))):t.communityUsers.filter((e=>!vc(e,t,"ADD_COMMUNITY_USER")))}const wc=(e,t)=>{const n=we();return Xe(n,e,e,(r=>{const s=Ba(r),{communities:o,communityUsers:a}=s,i=Ea(o,a);if(s.communities=i,n.cache){Kt(s);const n=Se(["community","get",s.communities[0].communityId]),r=bc(e,s).map((e=>{const t=Se(["communityUsers","get",de("communityUsers")(e)]);return null==t?void 0:t.data})).filter(dn);t(n.data,r)}else t(s.communities[0],bc(e,s))}))},Cc=(e,t)=>{const n=we();return Xe(n,e,e,(r=>{const s=Ba(r),{communities:o,communityUsers:a}=s,i=Ea(o,a);if(s.communities=i,n.cache){Kt(s);const n=Se(["community","get",s.communities[0].communityId]),r=bc(e,s).map((e=>{const t=Se(["communityUsers","get",de("communityUsers")(e)]);return null==t?void 0:t.data})).filter(dn);t(n.data,r)}else t(s.communities[0],bc(e,s))}))},Ic=e=>wc("community.userAdded",e),Sc=e=>wc("community.userRemoved",e),_c=e=>wc("community.userBanned",e),kc=e=>wc("community.userChanged",e),Oc=e=>wc("community.userUnbanned",e),Tc=e=>wc("community.roleAdded",e),Ec=e=>wc("community.roleRemoved",e),Ac=e=>Cc("local.community.userAdded",e),Mc=e=>Cc("local.community.userRemoved",e),Pc=e=>wc("community.joined",e),Rc=e=>wc("community.left",e),Uc=e=>Cc("local.community.joined",e),jc=e=>Cc("local.community.left",e);class xc extends wo{async getRequest(e,t){const{limit:n=j}=e,r=zt(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},r),{isDeleted:zn(r.includeDeleted),keyword:r.displayName,filter:r.membership,options:s})});return o}}class Dc extends Io{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)_e(this.cacheKey,{data:e.communities.map(de("community"))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(de("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Se(this.cacheKey))||void 0===t?void 0:t.data;n&&(_e(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Nc,Bc;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Nc||(Nc={})),function(e){e.OnCommunityJoined="onCommunityJoined",e.OnCommunityLeft="onCommunityLeft",e.OnCommunityUserBanned="onCommunityUserBanned",e.OnCommunityUserChanged="onCommunityUserChanged",e.OnCommunityUserRoleAdded="onCommunityUserRoleAdded",e.OnCommunityUserRoleRemoved="onCommunityUserRoleRemoved",e.OnCommunityUserUnbanned="onCommunityUserUnbanned",e.OnMemberCountChanged="OnMemberCountChanged",e.OnCommunityUserAdded="OnCommunityUserAdded",e.onCommunityUserRemoved="onCommunityUserRemoved",e.OnUserDeleted="OnUserDeleted"}(Bc||(Bc={}));class qc extends wo{async getRequest(e,t){const{limit:n=j,includeDeleted:r}=e,s=zt(e,["limit","includeDeleted"]),o=t?{token:t}:{limit:n},a=!1!==r&&void 0,{data:i}=await this.http.get(`/api/v3/communities/${s.communityId}/users`,{params:Object.assign(Object.assign({},s),{options:o,isDeleted:a})});return i}}class Fc extends Io{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)_e(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>de("communityUsers")({communityId:e,userId:t})))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>de("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(t,n)=>{var r;const s=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;s&&(e===Bc.OnCommunityUserRoleAdded&&"displayName"===this.query.sortBy||(n.forEach((e=>{const t=de("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership?s.data=s.data.filter((e=>e!==t)):s.data.includes(t)||(s.data=[t,...s.data])})),_e(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Lc=e=>{const t=we();return Xe(t,"onLocalCommunityRoleRemoved","local.community.roleRemoved",(async t=>{const{communities:n,communityUsers:r}=t;e(n[0],r.filter((e=>"member"===e.communityMembership)))}))},Kc=e=>{const t=we();return Xe(t,"onLocalCommunityRoleAdded","local.community.roleAdded",(async t=>{const{communities:n,communityUsers:r}=t;e(n[0],r.filter((e=>"member"===e.communityMembership)))}))},$c=e=>t=>{const n=we();return Xe(n,"user.deleted","user.deleted",(n=>{var r,s;const o=Nr(n);if(0===o.users.length)return;const a=o.users[0];Kt(o);const i=de("communityUsers")({communityId:e,userId:a.userId}),c=null===(r=Se(["communityUsers","get",i]))||void 0===r?void 0:r.data;_e(["communityUsers","get",i],Object.assign(Object.assign({},c),{user:a}));const l=null===(s=Se(["community","get",e]))||void 0===s?void 0:s.data;t(l,[Object.assign(Object.assign({},c),{user:a})])}))};class zc extends ko{constructor(e,t){const n=w.default(e),r=["communityUsers","collection",n];super(new qc(e),n,r,t),this.query=e,this.queryStreamController=new Fc(this.query,this.cacheKey,this.notifyChange.bind(this),Ba),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Pc,action:Bc.OnCommunityJoined},{fn:Uc,action:Bc.OnCommunityJoined},{fn:Rc,action:Bc.OnCommunityLeft},{fn:jc,action:Bc.OnCommunityLeft},{fn:_c,action:Bc.OnCommunityUserBanned},{fn:kc,action:Bc.OnCommunityUserChanged},{fn:Tc,action:Bc.OnCommunityUserRoleAdded},{fn:Ec,action:Bc.OnCommunityUserRoleRemoved},{fn:Kc,action:Bc.OnCommunityUserRoleAdded},{fn:Lc,action:Bc.OnCommunityUserRoleRemoved},{fn:Oc,action:Bc.OnCommunityUserUnbanned},{fn:Ac,action:Bc.OnCommunityUserAdded},{fn:Mc,action:Bc.onCommunityUserRemoved},{fn:$c(this.query.communityId),action:Bc.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const o=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const a=this.applyFilter(null!==(s=o.data.map((e=>Se(["communityUsers","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=Me(e,"roles",this.query.roles);switch(this.query.memberships&&(t=t.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),this.query.search&&(t=xe(t,this.query.search)),!1===this.query.includeDeleted&&(t=t.filter((({user:e})=>!0!==(null==e?void 0:e.isDeleted)))),this.query.sortBy){case"firstCreated":t=t.sort(Be);break;case"displayName":t=t.sort(((e,t)=>{var n,r,s,o;return(null===(n=null==e?void 0:e.user)||void 0===n?void 0:n.displayName)&&(null===(r=null==t?void 0:t.user)||void 0===r?void 0:r.displayName)?null===(s=null==e?void 0:e.user)||void 0===s?void 0:s.displayName.localeCompare(null===(o=null==t?void 0:t.user)||void 0===o?void 0:o.displayName):0}));break;default:t=t.sort(Fe)}return t}}class Qc extends wo{async getRequest(e,t){const{limit:n=j,includeDeleted:r}=e,s=zt(e,["limit","includeDeleted"]),o=t?{token:t}:{limit:n},a=!1!==r&&void 0,{data:i}=await this.http.get(`/api/v3/communities/${s.communityId}/users`,{params:Object.assign(Object.assign({},s),{options:o,isDeleted:a})});return i}}class Vc extends Io{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)_e(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>de("communityUsers")({communityId:e,userId:t})))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>de("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const r=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;r&&(t.forEach((e=>{const t=de("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership&&(r.data=r.data.filter((e=>e!==t)))})),_e(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Hc;!function(e){e.OnCommunityJoined="onCommunityJoined",e.OnCommunityLeft="onCommunityLeft",e.OnCommunityUserBanned="onCommunityUserBanned",e.OnCommunityUserChanged="onCommunityUserChanged",e.OnCommunityUserRoleAdded="onCommunityUserRoleAdded",e.OnCommunityUserRoleRemoved="onCommunityUserRoleRemoved",e.OnCommunityUserUnbanned="onCommunityUserUnbanned"}(Hc||(Hc={}));class Wc extends ko{constructor(e,t){const n=w.default(e),r=["communityUsers","collection",n];super(new Qc(e),n,r,t),this.query=e,this.queryStreamController=new Vc(this.query,this.cacheKey,this.notifyChange.bind(this),Ba),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Pc,action:Hc.OnCommunityJoined},{fn:Uc,action:Hc.OnCommunityJoined},{fn:Rc,action:Hc.OnCommunityLeft},{fn:jc,action:Hc.OnCommunityLeft},{fn:_c,action:Hc.OnCommunityUserBanned},{fn:kc,action:Hc.OnCommunityUserChanged},{fn:Lc,action:Hc.OnCommunityUserRoleRemoved},{fn:Ec,action:Hc.OnCommunityUserRoleRemoved},{fn:Oc,action:Hc.OnCommunityUserUnbanned},{fn:$c(this.query.communityId),action:Hc.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const o=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const a=this.applyFilter(null!==(s=o.data.map((e=>Se(["communityUsers","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=Me(e,"roles",this.query.roles);return this.query.memberships&&(t=t.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),this.query.search&&(t=xe(t,this.query.search)),!1===this.query.includeDeleted&&(t=t.filter((({user:e})=>!0!==(null==e?void 0:e.isDeleted)))),t}}var Jc=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=we();n.log("community/moderation/addMembers",e,t);const{data:r}=await n.http.post(`/api/v3/communities/${e}/users`,{communityId:e,userIds:t});Ze("local.community.userAdded",r);const s=Vt(r,"communityUsers");n.cache&&Kt(s);const{communityUsers:o}=s;return!!o.find((t=>t.communityId===e&&"member"===t.communityMembership))},removeMembers:async(e,t)=>{const n=we();n.log("community/moderation/removeMembers",e,t);const{data:r}=await n.http.delete(`/api/v3/communities/${e}/users`,{data:{communityId:e,userIds:t}});Ze("local.community.userRemoved",r);const s=Vt(r,"communityUsers");n.cache&&Kt(s);const{communityUsers:o}=s;return!!o.find((t=>t.communityId===e&&"member"!==t.communityMembership))},applyFilter:(e,t)=>{let n=Me(e,"roles",t.roles);t.memberships&&(n=n.filter((({communityMembership:e})=>t.memberships.includes(e)))),t.search&&(n=xe(n,t.search));const r=t.sortBy?t.sortBy:"lastCreated";return n=n.sort("lastCreated"===r?Fe:Be),n},getMembers:(e,t,n)=>{const{log:r,cache:s}=we();s||console.log(D);const o=Date.now();r(`getMembers(tmpid: ${o}) > listen`);const a=new zc(e,(e=>{t(e)})),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>{Te(c)})),()=>{r(`getMembers(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},searchMembers:(e,t,n)=>{const{log:r,cache:s}=we();s||console.log(D);const o=Date.now();r(`getMembers(tmpid: ${o}) > listen`);const a=new Wc(e,(e=>{t(e)})),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>{Te(c)})),()=>{r(`getMembers(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},onCommunityUserAdded:Ic,onCommunityUserRemoved:Sc,onCommunityUserBanned:_c,onCommunityUserChanged:kc,onCommunityUserUnbanned:Oc,onCommunityUserRoleAdded:Tc,onCommunityUserRoleRemoved:Ec,onLocalCommunityUserAdded:Ac,onLocalCommunityUserRemoved:Mc,onCommunityJoined:Pc,onCommunityLeft:Rc,onLocalCommunityJoined:Uc,onLocalCommunityLeft:jc});class Gc extends ko{constructor(e,t){const n=w.default(e),r=["community","collection",n];super(new xc(e),n,r,t),this.query=e,this.queryStreamController=new Dc(this.query,this.cacheKey,this.notifyChange.bind(this),Ba),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:yc,action:Nc.OnCommunityDeleted},{fn:mc,action:Nc.OnCommunityUpdated},{fn:Pc,action:Bc.OnCommunityJoined},{fn:Rc,action:Bc.OnCommunityLeft},{fn:kc,action:Bc.OnMemberCountChanged},{fn:Uc,action:Bc.OnCommunityJoined},{fn:jc,action:Bc.OnCommunityLeft}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const o=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const a=this.applyFilter(null!==(s=o.data.map((e=>Se(["community","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=we();let n=e;return this.query.includeDeleted||(n=Ee(n,"isDeleted",!1)),this.query.categoryId&&(n=n.filter((e=>{var t;return null===(t=e.categoryIds)||void 0===t?void 0:t.includes(this.query.categoryId)}))),this.query.tags&&(n=n.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.membership&&t&&(n=Ue(n,this.query.membership,t)),n}}class Yc extends wo{async getRequest(e,t){const{limit:n=j}=e,r=zt(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},r),{isDeleted:zn(r.includeDeleted),keyword:r.displayName,filter:r.membership,options:s})});return o}}var Xc;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Xc||(Xc={}));class Zc extends Io{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&(Kt(t,{cachedAt:r}),dc(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,s;if(n)_e(this.cacheKey,{data:e.communities.map(de("community"))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(de("community"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;r&&(this.query.displayName&&e===Xc.OnCommunityCreated||(r.data=[...new Set([t.communityId,...r.data])],_e(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class el extends ko{constructor(e,t){const n=w.default(e),r=["community","collection",n];super(new Yc(e),n,r,t),this.query=e,this.queryStreamController=new Zc(this.query,this.cacheKey,this.notifyChange.bind(this),Ba),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:gc,action:Xc.OnCommunityCreated},{fn:yc,action:Xc.OnCommunityDeleted},{fn:mc,action:Xc.OnCommunityUpdated},{fn:Pc,action:Bc.OnCommunityJoined},{fn:Rc,action:Bc.OnCommunityLeft},{fn:kc,action:Bc.OnMemberCountChanged},{fn:Uc,action:Bc.OnCommunityJoined},{fn:jc,action:Bc.OnCommunityLeft}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const o=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const a=this.applyFilter(null!==(s=o.data.map((e=>Se(["community","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=we();let n=e;if(this.query.includeDeleted||(n=Ee(n,"isDeleted",!1)),this.query.categoryId&&(n=n.filter((e=>{var t;return null===(t=e.categoryIds)||void 0===t?void 0:t.includes(this.query.categoryId)}))),this.query.tags&&(n=n.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.membership&&t&&(n=Ue(n,this.query.membership,t)),!this.query.displayName){const e=(()=>{switch(this.query.sortBy){case"firstCreated":return Be;case"lastCreated":default:return Fe;case"displayName":return De}})();n=n.sort(e)}return n}}class tl extends wo{async getRequest(e,t){const{limit:n=j}=e,r=zt(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v3/communities/top-trending",{params:Object.assign(Object.assign({},r),{options:s})});return o}}class nl extends Io{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&(Kt(t,{cachedAt:r}),dc(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,s;if(n)_e(this.cacheKey,{data:e.communities.map(de("community"))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(de("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Se(this.cacheKey))||void 0===t?void 0:t.data;n&&(_e(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var rl;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(rl||(rl={}));class sl extends ko{constructor(e,t){const n=w.default(e),r=["trendingCommunity","collection",n];super(new tl(e),n,r,t),this.query=e,this.queryStreamController=new nl(this.query,this.cacheKey,this.notifyChange.bind(this),Ba),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:yc,action:rl.OnCommunityDeleted},{fn:mc,action:rl.OnCommunityUpdated},{fn:Pc,action:Bc.OnCommunityJoined},{fn:Rc,action:Bc.OnCommunityLeft},{fn:kc,action:Bc.OnMemberCountChanged},{fn:Uc,action:Bc.OnCommunityJoined},{fn:jc,action:Bc.OnCommunityLeft}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const o=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const a=null!==(s=o.data.map((e=>Se(["community","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==s?s:[];(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class ol extends wo{async getRequest(e,t){const{limit:n=j}=e,r=zt(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v3/communities/recommended",{params:Object.assign(Object.assign({},r),{options:s})});return o}}class al extends Io{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&(Kt(t,{cachedAt:r}),dc(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,s;if(n)_e(this.cacheKey,{data:e.communities.map(de("community"))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(de("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Se(this.cacheKey))||void 0===t?void 0:t.data;n&&(_e(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var il;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(il||(il={}));class cl extends ko{constructor(e,t){const n=w.default(e),r=["community","collection",n];super(new ol(e),n,r,t),this.query=e,this.queryStreamController=new al(this.query,this.cacheKey,this.notifyChange.bind(this),Ba),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:yc,action:il.OnCommunityDeleted},{fn:mc,action:il.OnCommunityUpdated},{fn:Pc,action:Bc.OnCommunityJoined},{fn:Rc,action:Bc.OnCommunityLeft},{fn:kc,action:Bc.OnMemberCountChanged},{fn:Uc,action:Bc.OnCommunityJoined},{fn:jc,action:Bc.OnCommunityLeft}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const o=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const a=null!==(s=o.data.map((e=>Se(["community","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==s?s:[];(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var ll=Object.freeze({__proto__:null,addRoles:async(e,t,n)=>{const r=we();r.log("community/moderation/addRoles",e,t,n);const{data:s}=await r.http.post(`/api/v4/communities/${e}/users/roles`,{communityId:e,roles:t,userIds:n}),o=qa(s);r.cache&&Kt(o),Ze("local.community.roleAdded",o);const{communityUsers:a}=o;return!!a.find((n=>n.communityId===e&&t.some((e=>n.roles.includes(e)))))},removeRoles:async(e,t,n)=>{const r=we();r.log("community/moderation/removeRoles",e,t,n);const{data:s}=await r.http.delete(`/api/v4/communities/${e}/users/roles`,{data:{communityId:e,roles:t,userIds:n}}),o=qa(s);r.cache&&Kt(o),Ze("local.community.roleRemoved",o);const{communityUsers:a}=o;return!!a.find((n=>n.communityId===e&&!t.some((e=>n.roles.includes(e)))))},banMembers:async(e,t)=>{const n=we();n.log("community/banMembers",{userIds:t,communityId:e});const{data:r}=await n.http.put(`/api/v3/communities/${e}/users/ban`,{userIds:t}),s=Vt(r,"communityUsers"),o=n.cache&&Date.now();n.cache&&Kt(s,{cachedAt:o});const{communityUsers:a}=s;return{data:a.filter((e=>t.includes(e.userId))),cachedAt:o}},unbanMembers:async(e,t)=>{const n=we();n.log("community/unbanMembers",{userIds:t,communityId:e});const{data:r}=await n.http.put(`/api/v3/communities/${e}/users/unban`,{userIds:t}),s=Vt(r,"communityUsers"),o=n.cache&&Date.now();n.cache&&Kt(s,{cachedAt:o});const{communityUsers:a}=s;return{data:a.filter((e=>t.includes(e.userId))),cachedAt:o}}}),dl=Object.freeze({__proto__:null,Moderation:ll,Membership:Jc,getCommunityByIds:uc,createCommunity:async e=>{const t=we();t.log("user/createCommunity",e);const{data:n}=await t.http.post("/api/v3/communities/",Fa(e));Ze("community.created",n);const r=Ba(n),s=t.cache&&Date.now();t.cache&&(Kt(r,{cachedAt:s}),dc(r.communities,r.communityUsers));const{communities:o}=r;return{data:o[0],cachedAt:s}},updateCommunity:async(e,t)=>{const n=we();n.log("community/updateCommunity",e,t);const{data:r}=await n.http.put(`/api/v3/communities/${e}`,Fa(t));Ze("community.updated",r);const s=Ba(r),o=n.cache&&Date.now();n.cache&&(Kt(s,{cachedAt:o}),dc(s.communities,s.communityUsers));const{communities:a}=s;return{data:a.find((t=>t.communityId===e)),cachedAt:o}},deleteCommunity:async e=>{const t=we();t.log("community/deleteCommunity",e),await t.http.delete(`/api/v3/communities/${e}`);const n=await hc(e);return Ze("community.deleted",{communities:[n.data],categories:[],communityUsers:[],feeds:[],files:[],users:[]}),n.data},joinCommunity:async e=>{const t=we();t.log("community/joinCommunity",e);const{data:n}=await t.http.post(`/api/v3/communities/${e}/join`);Ze("local.community.joined",n);const r=Ba(n),s=t.cache&&Date.now();t.cache&&Kt(r,{cachedAt:s});const{communityUsers:o}=r;return!!o.find((t=>t.communityId===e&&"member"===t.communityMembership))},leaveCommunity:async e=>{const t=we();t.log("community/leaveCommunity",e);const{data:n}=await t.http.delete(`/api/v3/communities/${e}/leave`);Ze("local.community.left",n);const r=Ba(n),s=t.cache&&Date.now();t.cache&&Kt(r,{cachedAt:s});const{communityUsers:o}=r;return!!o.find((t=>t.communityId===e&&"member"!==t.communityMembership))},getTopTrendingCommunities:pc,onCommunityCreated:gc,onCommunityUpdated:mc,onCommunityDeleted:yc,observeCommunity:(e,t)=>{const{log:n}=we(),r=Date.now();n(`observeCommunity(tmpid: ${r}) > listen`);const s=(e,n)=>{var r,s;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(s=t[n])||void 0===s||s.call(t,e)},o=(t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.communityId)===e&&s(t,n)},a=[];return a.push(mc((e=>o({data:e,loading:!1,origin:"event"},"onUpdate"))),yc((e=>o({data:e,loading:!1,origin:"event"},"onDelete"))),Pc((e=>o({data:e,loading:!1,origin:"event"},"onJoin"))),Rc((e=>o({data:e,loading:!1,origin:"event"},"onLeft"))),Ic((e=>o({data:e,loading:!1,origin:"event"},"onUserAdded"))),Sc((e=>o({data:e,loading:!1,origin:"event"},"onUserRemoved"))),_c((e=>o({data:e,loading:!1,origin:"event"},"onUserBanned"))),Oc((e=>o({data:e,loading:!1,origin:"event"},"onUserUnbanned")))),ie(oe(hc,e),(e=>(e.data||e.error)&&s(e,"onFetch"))),()=>{n(`observeCommunity(tmpid: ${r}) > dispose`),a.forEach((e=>e()))}},searchCommunities:(e,t,n)=>{const{log:r,cache:s}=we();s||console.log(D);const o=Date.now();r(`searchCommunities(tmpid: ${o}) > listen`);const a=new Gc(e,t),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>Te(c))),()=>{r(`searchCommunities(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getCommunities:(e,t,n)=>{const{log:r,cache:s}=we();s||console.log(D);const o=Date.now();r(`getCommunities(tmpid: ${o}) > listen`);const a=new el(e,t),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>Te(c))),()=>{r(`getCommunities(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getCommunity:(e,t)=>go(e,t,"communityId",hc,[mc,yc,Pc,Rc,Uc,jc,_c,Oc,kc]),getTrendingCommunities:(e,t,n)=>{const{log:r,cache:s,userId:o}=we();s||console.log(D);const a=Date.now();r(`getTrendingCommunities(tmpid: ${a}) > listen`);const i=new sl(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>Te(l))),()=>{r(`getTrendingCommunities(tmpid: ${a}) > dispose`),c.forEach((e=>e()))}},getRecommendedCommunities:(e,t,n)=>{const{log:r,cache:s,userId:o}=we();s||console.log(D);const a=Date.now();r(`getRecommendedCommunities(tmpid: ${a}) > listen`);const i=new cl(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>Te(l))),()=>{r(`getRecommendedCommunities(tmpid: ${a}) > dispose`),c.forEach((e=>e()))}}});const ul=async e=>{const t=we();t.log("category/getCategory",e);const{data:n}=await t.http.get(`/api/v3/community-categories/${encodeURIComponent(e)}`),r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const{categories:s}=n;return{data:wn.category(s.find((t=>t.categoryId===e))),cachedAt:r}};ul.locally=e=>{const t=we();if(t.log("category/getCategory.locally",e),!t.cache)return;const n=Se(["category","get",e]);return n?{data:wn.category(n.data),cachedAt:n.cachedAt}:void 0};const hl=async e=>{const t=we();t.log("category/queryCategories",e);const n=null!=e?e:{},{page:r,limit:s,includeDeleted:o}=n,a=zt(n,["page","limit","includeDeleted"]),i=r?{token:r}:s?{limit:s}:void 0,{data:c}=await t.http.get("/api/v3/community-categories",{params:Object.assign(Object.assign({},a),{isDeleted:zn(o),options:i})}),{paging:l}=c,d=zt(c,["paging"]),{categories:u}=d,h=t.cache&&Date.now();if(t.cache){Kt(d,{cachedAt:h});const e=["category","query",Object.assign(Object.assign({},a),{includeDeleted:o,options:i})];_e(e,{categories:u.map(de("category")),paging:l})}return{data:u,cachedAt:h,paging:l}};hl.locally=e=>{var t,n;const r=we();if(r.log("category/queryCategories.locally",e),!r.cache)return;const s=null!=e?e:{},{page:o,limit:a=10}=s,i=zt(s,["page","limit"]),c=o?{token:o}:a?{limit:a}:void 0,l=["category","query",Object.assign(Object.assign({},i),{options:c})],{data:d,cachedAt:u}=null!==(t=Se(l))&&void 0!==t?t:{};if(!(null==d?void 0:d.categories.length))return;const h=d.categories.map((e=>Se(["category","get",e]))).filter(Boolean).map((({data:e})=>e)),{paging:p}=d;return h.length===(null===(n=null==d?void 0:d.categories)||void 0===n?void 0:n.length)?{data:h,cachedAt:u,paging:p}:void 0};var pl=Object.freeze({__proto__:null,getCategory:ul,getCategories:(e,t,n)=>{const{log:r,cache:s}=we();s||console.log(D);const o=Date.now();r(`getCategories(tmpid: ${o}) > listen`);const{limit:a}=e,i=zt(e,["limit"]),c=null!=a?a:j,{policy:l=x}=null!=n?n:{},d=[],u=["category","collection",{}],h=(n=!1)=>{var r,s;const o=null===(r=Se(u))||void 0===r?void 0:r.data,a=null!==(s=null==o?void 0:o.data)&&void 0!==s?s:[];if(!n&&a.length>0&&!(null==o?void 0:o.params.page))return;const d=oe(hl,Object.assign(Object.assign({},i),{limit:n?c:void 0,page:n||null==o?void 0:o.params.page}));ie(d,(({data:n,error:r,loading:s,paging:o})=>{const i={loading:s,error:r,params:{page:null==o?void 0:o.next},data:a};n&&(i.data=[...new Set([...a,...n.map(de("category"))])]),_e(u,i),(n=>{var r,s;let o=null!==(r=n.data.map((e=>Se(["category","get",e]))).filter(Boolean).map((({data:e})=>wn.category(e))))&&void 0!==r?r:[];switch(e.includeDeleted||(o=Ee(o,"isDeleted",!1)),e.sortBy){case"firstCreated":o=o.sort(Be);break;case"lastCreated":o=o.sort(Fe);break;default:o=o.sort(Ne)}t({onNextPage:h,data:o,hasNextPage:!!(null===(s=n.params)||void 0===s?void 0:s.page),loading:n.loading,error:n.error})})(i)}),ae(l))};return d.push((()=>{})),h(!0),()=>{r(`getCategories(tmpid: ${o}) > dispose`),d.forEach((e=>e()))}}});const fl=async e=>{const t=we();t.log("feed/queryGlobalFeed",e);const n=null!=e?e:{},{useCustomRanking:r,page:s,queryToken:o}=n,a=zt(n,["useCustomRanking","page","queryToken"]);r&&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 i=o?{token:o}:s?{token:Y(s,"skiplimit")}:void 0,{data:c}=await t.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},a),{options:i})}),{paging:l}=c,d=zt(c,["paging"]),u=Vt(d,"communityUsers"),{posts:h}=u,p=t.cache&&Date.now();if(t.cache){Kt(u);const e=["globalFeed","query",Object.assign(Object.assign({},a),{options:Object.assign({},s)})];_e(e,{posts:h.map(de("post")),paging:l})}const f=X(l.next),g=X(l.previous);return{data:h.map(wn.post),cachedAt:p,prevPage:g,nextPage:f,paging:l}};fl.locally=e=>{var t,n;const r=we();if(r.log("post/queryGlobalFeed.locally",e),!r.cache)return;const s=null!=e?e:{},{page:o}=s,a=zt(s,["page"]),i=["globalFeed","query",Object.assign(Object.assign({},a),{options:Object.assign({},o)})],{data:c,cachedAt:l}=null!==(t=Se(i))&&void 0!==t?t:{};if(!(null==c?void 0:c.posts.length))return;const d=c.posts.map((e=>Se(["post","get",e]))).filter(Boolean).map((({data:e})=>e)).map(wn.post),{paging:u}=c,h=X(null==c?void 0:c.paging.previous),p=X(null==c?void 0:c.paging.next);return d.length===(null===(n=null==c?void 0:c.posts)||void 0===n?void 0:n.length)?{data:d,cachedAt:l,prevPage:h,nextPage:p,paging:u}:void 0};const gl=async e=>{const t=we();t.log("feed/getCustomRankingGlobalFeed",e);const n=null!=e?e:{},{page:r,queryToken:s,limit:o}=n,a=zt(n,["page","queryToken","limit"]),i=s?{token:s}:r?{token:Y(r,"skiplimit")}:void 0,{data:c}=await t.http.get("/api/v5/me/global-feeds",{params:Object.assign(Object.assign({},a),{limit:s?void 0:o,options:i})}),{paging:l}=c,d=zt(c,["paging"]),u=Vt(d,"communityUsers"),{posts:h}=u,p=t.cache&&Date.now();if(t.cache){Kt(u);const e=["customGlobalFeed","query",Object.assign(Object.assign({},a),{options:Object.assign({},r)})];_e(e,{posts:h.map(de("post")),paging:l})}const f=X(l.next),g=X(l.previous);return{data:h.map(wn.post),cachedAt:p,prevPage:g,nextPage:f,paging:l}};gl.locally=e=>{var t,n;const r=we();if(r.log("post/getCustomRankingGlobalFeed.locally",e),!r.cache)return;const s=null!=e?e:{},{page:o}=s,a=zt(s,["page"]),i=["customGlobalFeed","query",Object.assign(Object.assign({},a),{options:Object.assign({},o)})],{data:c,cachedAt:l}=null!==(t=Se(i))&&void 0!==t?t:{};if(!(null==c?void 0:c.posts.length))return;const d=c.posts.map((e=>Se(["post","get",e]))).filter(Boolean).map((({data:e})=>e)),u=X(null==c?void 0:c.paging.previous),h=X(null==c?void 0:c.paging.next),{paging:p}=c;return d.length===(null===(n=null==c?void 0:c.posts)||void 0===n?void 0:n.length)?{data:d.map(wn.post),cachedAt:l,prevPage:u,nextPage:h,paging:p}:void 0};var ml=Object.freeze({__proto__:null,queryGlobalFeed:fl,getCustomRankingGlobalFeed:gl});const yl=async e=>{const t=we();t.log("post/getPostByIds",e);const n=e.map((e=>encodeURIComponent(e)));let r;try{r=(await t.http.get("/api/v3/posts/list",{params:{postIds:n}})).data}catch(t){throw e.forEach((e=>{V(null==t?void 0:t.code)&&$t("post",e)})),t}const s=Vt(r,"communityUsers"),o=t.cache&&Date.now();return t.cache&&Kt(s,{cachedAt:o}),{data:s.posts.map(wn.post),cachedAt:o}};yl.locally=e=>{var t;const n=we();if(n.log("post/getPostByIds.locally",e),!n.cache)return;const r=e.map((e=>Se(["post","get",e]))).filter(Boolean),s=r.map((({data:e})=>e)),o=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:s.map(wn.post),cachedAt:o.cachedAt}};const vl=async(e,t=!1)=>{var n;const r=we(),s=await Oa(e);if(await r.http.delete(`/api/v4/posts/${encodeURIComponent(e)}`,{params:{postId:e,permanent:t}}),"community"===s.data.targetType){const e=await hc(s.data.targetId),t=(null!==(n=Ie(["communityUsers","get"]))&&void 0!==n?n:[]).filter((({key:t})=>"communityUsers"===t[0]&&("get"===t[1]&&("string"==typeof t[2]&&t[2].includes(e.data.communityId))))).map((({data:e})=>e));Ze("community.updated",{communities:[e.data],categories:[],communityUsers:t,feeds:[],files:[],users:[]})}const o=Object.assign(Object.assign({},s.data),{isDeleted:!0});return t?setTimeout((()=>{$t("post",e)}),0):Oe(["post","get",e],{isDeleted:!0}),Ze("local.post.deleted",{posts:[o],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[],videoStreamings:[]}),wn.post(o)},bl=async e=>{const t=we();t.log("comment/getCommentByIds",e);const n=e.map((e=>encodeURIComponent(e)));let r;try{r=(await t.http.get("/api/v3/comments/list",{params:{commentIds:n}})).data}catch(t){throw e.forEach((e=>{V(null==t?void 0:t.code)&&$t("comment",e)})),t}const s=t.cache&&Date.now();return t.cache&&Kt(r,{cachedAt:s}),{data:r.comments.map((e=>wn.comment(e))),cachedAt:s}};bl.locally=e=>{var t;const n=we();if(n.log("comment/getCommentByIds.locally",e),!n.cache)return;const r=e.map((e=>Se(["comment","get",e]))).filter(Boolean),s=r.map((({data:e})=>e)),o=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:s.map((e=>wn.comment(e))),cachedAt:o.cachedAt}};const wl=(e,t=!1)=>{const{stories:n}=e,r=n.map((e=>((e,t=!1)=>{const{storyId:n,referenceId:r}=e;return!t&&r?Object.assign(Object.assign({},e),{syncState:"synced"}):Object.assign(Object.assign({},e),{syncState:"synced",referenceId:n})})(e,t)));return Object.assign(Object.assign({},e),{stories:r})},Cl=async e=>{const t=we();t.log("story/getStoryByStoryId",e);const n=Se(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;lr("story",e)}let r;try{const n=await t.http.get(`/api/v4/stories/${e}`);r=wl(n.data)}catch(t){throw V(null==t?void 0:t.code)&&$t("story",e),t}const s=t.cache&&Date.now();return t.cache&&Kt(r,{cachedAt:s}),{data:r.stories[0],cachedAt:s}};Cl.locally=e=>{const t=we();t.log("story/getStorybyStoryId",e);const n=Se(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;lr("story",e)}const r=t.cache&&Date.now(),s=Se(["story","get",e]);if(s)return{data:s.data,cachedAt:r}};const Il=async(e,t=!1)=>{var n;const r=we(),s=await Ta(e);await r.http.delete(`/api/v4/comments/${encodeURIComponent(e)}`,{params:{commentId:e,permanent:t}});const o=Object.assign(Object.assign({},s.data),{isDeleted:!0});if("story"===s.data.referenceType){const e=await Cl(s.data.referenceId);Ze("local.story.updated",{stories:[e.data],categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[]})}else{const e=null===(n=Se(["post","get",s.data.referenceId]))||void 0===n?void 0:n.data;if(e){let t;t=o.parentId?1:o.childrenNumber+1,e.commentsCount-=t,Ze("local.post.updated",{posts:[e],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[],videoStreamings:[]})}}return Ze("local.comment.deleted",{comments:[o],commentChildren:[],files:[],users:[],communityUsers:[]}),t?Je((()=>$t("comment",e))):Oe(["comment","get",e],{isDeleted:!0}),o},Sl=async e=>{const t=we();let n;t.log("comment/getComment",e),lr("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw V(null==t?void 0:t.code)&&$t("comment",e),t}const r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const{comments:s}=n;return{data:s.find((t=>t.commentId===e)),cachedAt:r}};Sl.locally=e=>{const t=we();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=Se(["comment","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const _l=e=>ti("local.comment.deleted",e),kl=e=>{const t=we();return Xe(t,"local.comment.addReaction","local.comment.addReaction",(({comment:n})=>{t.cache?(Oe(["comment","get",n.commentId],n),e(un(n))):e(n)}))},Ol=e=>{const t=we();return Xe(t,"local.comment.removeReaction","local.comment.removeReaction",(({comment:n})=>{t.cache?(Oe(["comment","get",n.commentId],n),e(un(n))):e(n)}))};class Tl extends wo{async getRequest(e,t){const{limit:n=j,includeDeleted:r}=e,s=zt(e,["limit","includeDeleted"]),o={type:s.sortBy||e.limit?"pagination":void 0},a=t?Object.assign(Object.assign({},o),{token:t}):Object.assign(Object.assign({},o),{limit:n}),{data:i}=await this.http.get("/api/v3/comments",{params:Object.assign(Object.assign({},s),{isDeleted:zn(r),options:a})});return i}}var El;!function(e){e.OnCommentCreated="onCommentCreated",e.OnCommentUpdated="onCommentUpdated",e.OnCommentDeleted="onCommentDeleted",e.OnCommentFlagged="onCommentFlagged",e.OnCommentUnflagged="onCommentUnflagged",e.OnCommentReactionAdded="onCommentReactionAdded",e.OnCommentReactionRemoved="onCommentReactionRemoved"}(El||(El={}));class Al extends Io{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)_e(this.cacheKey,{data:e.comments.map(de("comment"))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.comments.map(de("comment"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;this.query.referenceId===t.referenceId&&this.query.referenceType===t.referenceType&&r&&(this.query.parentId&&this.query.parentId!==t.parentId||!this.query.parentId&&t.parentId||(e===El.OnCommentCreated&&(r.data=[...new Set([t.commentId,...r.data])]),_e(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Ml=e=>ti("local.comment.created",e);class Pl extends ko{constructor(e,t){const n=w.default(e),r=["comments","collection",n];super(new Tl(e),n,r,t),this.query=e,this.queryStreamController=new Al(this.query,this.cacheKey,this.notifyChange.bind(this),pi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Ml,action:El.OnCommentCreated},{fn:_l,action:El.OnCommentDeleted},{fn:ni,action:El.OnCommentCreated},{fn:ri,action:El.OnCommentUpdated},{fn:si,action:El.OnCommentDeleted},{fn:oi,action:El.OnCommentFlagged},{fn:ai,action:El.OnCommentUnflagged},{fn:ii,action:El.OnCommentReactionAdded},{fn:ci,action:El.OnCommentReactionRemoved},{fn:kl,action:El.OnCommentReactionAdded},{fn:Ol,action:El.OnCommentReactionRemoved}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const o=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const a=this.applyFilter(null!==(s=o.data.map((e=>Se(["comment","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==s?s:[]).map(wn.comment);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;if(this.query.includeDeleted||(t=Ee(t,"isDeleted",!1)),this.query.parentId&&(t=t.filter((e=>e.parentId===this.query.parentId))),"boolean"==typeof this.query.hasFlag&&(t=this.query.hasFlag?t.filter((e=>null!=e.hashFlag)):t.filter((e=>null==e.hashFlag))),this.query.dataTypes&&("exact"===this.query.dataTypes.matchType&&(t=t.filter((e=>{var t,n;const r=(null===(t=this.query.dataTypes)||void 0===t?void 0:t.values.sort())||[],s=(null===(n=e.dataTypes)||void 0===n?void 0:n.sort())||[];return s.length===r.length&&r.every(((e,t)=>e===s[t]))}))),"any"===this.query.dataTypes.matchType&&(t=t.filter((e=>{var t;return null===(t=this.query.dataTypes)||void 0===t?void 0:t.values.some((t=>{var n;return null===(n=e.dataTypes)||void 0===n?void 0:n.includes(t)}))})))),"firstCreated"===this.query.sortBy)t=t.sort(Be);else t=t.sort(Fe);return t}}var Rl=Object.freeze({__proto__:null,getCommentByIds:bl,createComment:async e=>{var t;const n=we();n.log("comment/createComment",e);const{data:r}=await n.http.post("/api/v3/comments",e),{comments:s}=r;if(0===s.length)throw new Error("Comment not created");const o=n.cache&&Date.now();if(n.cache&&Kt(r,{cachedAt:o}),["post","content"].includes(e.referenceType)){const n=null===(t=Se(["post","get",e.referenceId]))||void 0===t?void 0:t.data;n&&(n.commentsCount+=1,Ze("local.post.updated",{posts:[n],categories:[],comments:[],communities:[],communityUsers:r.communityUsers,feeds:[],files:r.files,postChildren:[],users:r.users,videoStreamings:[]}))}else if("story"===e.referenceType){const t=Se(["story-reference",e.referenceId]);if(null==t?void 0:t.data){const e=Se(["story","get",t.data]);(null==e?void 0:e.data)&&Ze("story.updated",{stories:[Object.assign(Object.assign({},e.data),{commentsCount:e.data.commentsCount+1,comments:[...new Set([...e.data.comments,s[0].commentId])]})],categories:[],comments:s,communities:[],communityUsers:r.communityUsers,files:r.files,users:r.users})}}return Ze("local.comment.created",r),{data:wn.comment(s[0]),cachedAt:o}},updateComment:async(e,t)=>{const n=we();n.log("user/updateComment",t);const{data:r}=await n.http.put(`/api/v3/comments/${encodeURIComponent(e)}`,t),s=n.cache&&Date.now();n.cache&&Kt(r,{cachedAt:s}),Ze("comment.updated",r);const{comments:o}=r;return{data:wn.comment(o.find((t=>t.commentId===e))),cachedAt:s}},deleteComment:Il,softDeleteComment:async e=>{we().log("comment/softDeleteComment",e);return Il(e)},hardDeleteComment:async e=>{we().log("comment/hardDeleteComment",e);return Il(e,!0)},flagComment:async e=>{const t=we();t.log("comment/flagComment",e);const{data:n}=await t.http.post(`/api/v3/comments/${encodeURIComponent(e)}/flag`);return t.cache&&Kt(n),Ze("comment.flagged",n),!!n},unflagComment:async e=>{const t=we();t.log("comment/unflagComment",e);const{data:n}=await t.http.delete(`/api/v3/comments/${encodeURIComponent(e)}/unflag`);return t.cache&&Kt(n),Ze("comment.unflagged",n),!!n},isCommentFlaggedByMe:async e=>{const t=we();t.log("comment/isCommentFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/comments/${e}/isflagbyme`);return n},onCommentCreated:ni,onCommentUpdated:ri,onCommentDeleted:si,onCommentFlagged:oi,onCommentUnflagged:ai,onCommentReactionAdded:ii,onCommentReactionRemoved:ci,observeComments:(e,t)=>{const{log:n}=we(),r=Date.now();n(`observeComments(tmpid: ${r}) > listen`);const s=[],o=(n,r)=>{var s,o;if(n.referenceId===e){if(t instanceof Function)return t(n);null===(s=t.onEvent)||void 0===s||s.call(t,r,n),null===(o=t[r])||void 0===o||o.call(t,n)}};return s.push(ni((e=>o(e,"onCreate"))),ri((e=>o(e,"onUpdate"))),si((e=>o(e,"onDelete"))),oi((e=>o(e,"onFlagged"))),ai((e=>o(e,"onUnflagged"))),ii((e=>o(e,"onReactionAdded"))),ci((e=>o(e,"onReactionRemoved")))),()=>{n(`observeComments(tmpid: ${r}) > dispose`),s.forEach((e=>e()))}},observeComment:(e,t,n="cache_then_server")=>{const{log:r}=we(),s=Date.now();r(`observeComment(tmpid: ${s}) > listen`);const o=(e,n)=>{var r,s;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(s=t[n])||void 0===s||s.call(t,e)},a=(t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.commentId)===e&&o(t,n)},i=[];return i.push(ri((e=>a({data:e,loading:!1,origin:"event"},"onUpdate"))),si((e=>a({data:e,loading:!1,origin:"event"},"onDelete"))),oi((e=>a({data:e,loading:!1,origin:"event"},"onFlagged"))),ai((e=>a({data:e,loading:!1,origin:"event"},"onUnflagged"))),ii((e=>a({data:e,loading:!1,origin:"event"},"onReactionAdded"))),ci((e=>a({data:e,loading:!1,origin:"event"},"onReactionRemoved")))),ie(oe(Sl,e),(e=>(e.data||e.error)&&o(e,"onFetch")),ae(n)),()=>{r(`observeComment(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getComment:(e,t)=>go(e,t,"commentId",Sl,[_l,si,oi,ii,ci,ai,ri,kl,Ol]),getComments:(e,t,n)=>{const{log:r,cache:s}=we();s||console.log("For using Live Collection feature you need to enable Cache!");const o=Date.now();r(`getComments(tmpid: ${o}) > listen`);const a=new Pl(e,t),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>Te(c))),()=>{r(`getComments(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}}});const Ul=e=>za("local.post.updated",e),jl=e=>{const t=we();return Xe(t,"local.post.addReaction","local.post.addReaction",(({post:n})=>{t.cache?(Oe(["post","get",n.postId],n),e(n)):e(n)}))},xl=e=>{const t=we();return Xe(t,"local.post.removeReaction","local.post.removeReaction",(({post:n})=>{t.cache?(Oe(["post","get",n.postId],n),e(n)):e(n)}))},Dl=e=>za("local.post.deleted",e);class Nl extends wo{async getRequest(e,t){const{limit:n=j,includeDeleted:r,matchingOnlyParentPost:s}=e,o=zt(e,["limit","includeDeleted","matchingOnlyParentPost"]),{dataTypes:a}=o,i={type:o.sortBy||e.limit?"pagination":void 0},c=t?Object.assign(Object.assign({},i),{token:t}):Object.assign(Object.assign({},i),{limit:n}),{data:l}=await this.http.get("/api/v4/posts",{params:Object.assign(Object.assign({},o),{isDeleted:zn(r),matchingOnlyParentPost:null!=s?s:!(null==a?void 0:a.length),options:c})});return l}}var Bl;!function(e){e.OnPostCreated="onPostCreated",e.OnPostUpdated="onPostUpdated",e.OnPostDeleted="onPostDeleted",e.OnPostFlagged="onPostFlagged",e.OnPostUnflagged="onPostUnflagged",e.OnPostReactionAdded="onPostReactionAdded",e.OnPostReactionRemoved="onPostReactionRemoved",e.OnPostApproved="onPostApproved",e.OnPostDeclined="onPostDeclined"}(Bl||(Bl={}));class ql extends Io{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)_e(this.cacheKey,{data:e.posts.map(de("post"))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(de("post"))])]}))}}reactor(e){return t=>{var n,r;const s=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(t.parentPostId&&t.isDeleted){const e=null===(r=Se(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e||(null==e?void 0:e.targetId)!==this.query.targetId)return;e.children=e.children.filter((e=>e!==t.postId)),_e(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===Bl.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==Bl.OnPostCreated&&e!==Bl.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),_e(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Fl=async e=>{const t=we();let n;t.log("post/getPost",e),lr("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw V(null==t?void 0:t.code)&&$t("post",e),t}const r=Vt(n,"communityUsers"),s=t.cache&&Date.now();t.cache&&Kt(r,{cachedAt:s});const{posts:o}=r;return{data:o.find((t=>t.postId===e)),cachedAt:s}};Fl.locally=e=>{const t=we();if(t.log("post/getPost.locally",e),!t.cache)return;const n=Se(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class Ll extends ko{constructor(e,t){const n=w.default(e),r=["posts","collection",n];super(new Nl(e),n,r,t),this.query=e,this.queryStreamController=new ql(this.query,this.cacheKey,this.notifyChange.bind(this),La),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Qa,action:Bl.OnPostCreated},{fn:Va,action:Bl.OnPostUpdated},{fn:Ul,action:Bl.OnPostUpdated},{fn:Ha,action:Bl.OnPostDeleted},{fn:Ga,action:Bl.OnPostFlagged},{fn:Ya,action:Bl.OnPostUnflagged},{fn:Wa,action:Bl.OnPostApproved},{fn:Ja,action:Bl.OnPostDeclined},{fn:Xa,action:Bl.OnPostReactionAdded},{fn:Za,action:Bl.OnPostReactionRemoved},{fn:jl,action:Bl.OnPostReactionAdded},{fn:xl,action:Bl.OnPostReactionRemoved},{fn:Dl,action:Bl.OnPostDeleted},{fn:gi((e=>ni((async t=>{var n;const r=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await Fl(t.referenceId),e(t))}))),"referenceId","post"),action:Bl.OnPostUpdated},{fn:gi((e=>si((async t=>{var n;const r=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await Fl(t.referenceId),e(t))}))),"referenceId","post"),action:Bl.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const o=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const a=this.applyFilter(null!==(s=o.data.map((e=>Se(["post","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==s?s:[]).map(wn.post);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=e;if(this.query.includeDeleted||(n=Ee(n,"isDeleted",!1)),this.query.tags&&(n=n.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)}))}))),"community"===this.query.targetType&&this.query.feedType&&(n=Re(n,this.query.feedType)),(null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=je(n,this.query.dataTypes)),"firstCreated"===this.query.sortBy)n=n.sort(Be);else n=n.sort(Fe);return n}}class Kl extends wo{async getRequest(e,t){const n=zt(e,["limit"]),{communityId:r,placement:s}=n,o=s?`/api/v1/pinned-posts/communities/${r}/${s}`:`/api/v1/pinned-posts/communities/${r}`,{data:a}=await this.http.get(o);return a}}class $l extends Io{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=we(),n=t.cache&&Date.now();t.cache&&Kt(e,{cachedAt:n})}appendToQueryStream(e,t,n=!1){var r,s;if(n)_e(this.cacheKey,{data:e.pins.map(de("pin"))});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(de("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}}class zl extends ko{constructor(e,t){const n=w.default(e),r=["pinnedPosts","collection",n];super(new Kl(e),n,r,t),this.query=e,this.queryStreamController=new $l(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return[]}notifyChange({origin:e,loading:t,error:n}){var r,s;const o=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;let a=(null!==(s=o.data.map((e=>Se(["pin","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==s?s:[]).map(wn.pinnedPost);a=this.applyFilter(a),(this.shouldNotify(a)||"event"!==e)&&this.callback({data:a,loading:t,error:n})}applyFilter(e){let t=e;if("lastCreated"===this.query.sortBy)t=t.sort((({post:e},{post:t})=>Fe({createdAt:null==e?void 0:e.createdAt},{createdAt:null==t?void 0:t.createdAt})));return t}}class Ql extends wo{async getRequest(e,t){const{limit:n=j}=e,r=zt(e,["limit"]),s={type:e.limit?"pagination":void 0},o=t?Object.assign(Object.assign({},s),{token:t}):Object.assign(Object.assign({},s),{limit:n}),{data:a}=await this.http.get("/api/v1/semantic-search/posts",{params:Object.assign(Object.assign({},r),{options:o})});return a}}function Vl(e){return e.posts.map((t=>{const n=e.searchResult.find((e=>e.postId===t.postId));return`${t.postId}:${n.score}`}))}function Hl(e){return(null!=e?e:[]).map((e=>e.split(":")[0]))}class Wl extends Io{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=this.preparePayload(e),n=we(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)_e(this.cacheKey,{data:Vl(e)});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...Vl(e)])]}))}}reactor(e){return t=>{var n,r;const s=null===(n=Se(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(t.parentPostId&&t.isDeleted){const e=null===(r=Se(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e||(null==e?void 0:e.targetId)!==this.query.targetId)return;e.children=e.children.filter((e=>e!==t.postId)),_e(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===Bl.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==Bl.OnPostCreated&&e!==Bl.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),_e(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Jl extends ko{constructor(e,t){const n=Object.assign(Object.assign({},e),{matchingOnlyParentPost:null==e.matchingOnlyParentPost||e.matchingOnlyParentPost,dataTypes:null==e.dataTypes?["text","image"]:e.dataTypes}),r=w.default(n),s=["posts","collection",r];super(new Ql(n),r,s,t),this.query=n,this.queryStreamController=new Wl(this.query,this.cacheKey,this.notifyChange.bind(this),Ka),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Va,action:Bl.OnPostUpdated},{fn:Ha,action:Bl.OnPostDeleted},{fn:Ga,action:Bl.OnPostFlagged},{fn:Ya,action:Bl.OnPostUnflagged},{fn:Wa,action:Bl.OnPostApproved},{fn:Ja,action:Bl.OnPostDeclined},{fn:Xa,action:Bl.OnPostReactionAdded},{fn:Za,action:Bl.OnPostReactionRemoved},{fn:gi((e=>ni((async t=>{const n=Se(this.cacheKey);Hl(null==n?void 0:n.data).includes(t.referenceId)||(await Oa(t.referenceId),e(t))}))),"referenceId","post"),action:Bl.OnPostUpdated},{fn:gi((e=>si((async t=>{const n=Se(this.cacheKey);Hl(null==n?void 0:n.data).includes(t.referenceId)||(await Oa(t.referenceId),e(t))}))),"referenceId","post"),action:Bl.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const o=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const a=this.applyFilter(null!==(s=o.data.map((e=>{const[t,n]=e.split(":");return{postId:t,score:parseFloat(n)}})).sort(((e,t)=>t.score-e.score)).map((({postId:e})=>Se(["post","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==s?s:[]).map(wn.post);(this.shouldNotify(a)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:a,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.targetType&&(t=t.filter((e=>e.targetType===this.query.targetType))),this.query.targetId&&(t=t.filter((e=>e.targetId===this.query.targetId))),this.query.dataTypes&&this.query.dataTypes.length>0&&(t=je(t,this.query.dataTypes)),t}}var Gl=Object.freeze({__proto__:null,getPostByIds:yl,createPost:async e=>{const t=we();t.log("post/createPost",e),e.dataType&&!["text","image","file","video"].includes(e.dataType)||delete e.dataType;const{data:n}=await t.http.post("/api/v4/posts",e);Ze("post.created",n);const r=Vt(n,"communityUsers"),s=t.cache&&Date.now();t.cache&&Kt(r,{cachedAt:s});const{posts:o}=r;return{data:wn.post(o[0]),cachedAt:s}},updatePost:async(e,t)=>{const n=we();n.log("user/updatePost",t),console.warn("Deprecation: updatePost has been renamed to editPost. Update post API will be deprecated soon.");const{data:r}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,t),s=Vt(r,"communityUsers"),o=n.cache&&Date.now();n.cache&&Kt(s,{cachedAt:o}),Ze("local.post.updated",r);const{posts:a}=s;return{data:wn.post(a.find((t=>t.postId===e))),cachedAt:o}},editPost:async(e,t)=>{const n=we();n.log("user/editPost",t);const{data:r}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,t),s=Vt(r,"communityUsers"),o=n.cache&&Date.now();n.cache&&Kt(s,{cachedAt:o}),Ze("local.post.updated",s);const{posts:a}=s;return{data:wn.post(a.find((t=>t.postId===e))),cachedAt:o}},deletePost:vl,softDeletePost:async e=>{we().log("post/softDeletePost",e);const t=await vl(e,!1);return wn.post(t)},hardDeletePost:async e=>{we().log("post/hardDeletePost",e);const t=await vl(e,!0);return wn.post(t)},approvePost:async e=>{const t=we();t.log("post/approvePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/approve`);Ze("post.approved",n),"community"===n.posts[0].targetType&&Ze("community.updated",n);const r=Vt(n,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Kt(r,{cachedAt:s}),{data:wn.post(r.posts.find((t=>t.postId===e))),cachedAt:s}},declinePost:async e=>{const t=we();t.log("post/declinePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/decline`);"community"===n.posts[0].targetType&&Ze("community.updated",n),Ze("post.declined",n);const r=Vt(n,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Kt(r,{cachedAt:s}),{data:wn.post(n.posts.find((t=>t.postId===e))),cachedAt:s}},flagPost:async e=>{const t=we();t.log("post/flagPost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/flag`);return t.cache&&Kt(Vt(n,"communityUsers")),Ze("post.flagged",n),!!n},unflagPost:async e=>{const t=we();t.log("post/unflagPost",e);const{data:n}=await t.http.delete(`/api/v3/posts/${encodeURIComponent(e)}/unflag`);return t.cache&&Kt(Vt(n,"communityUsers")),Ze("post.unflagged",n),!!n},isPostFlaggedByMe:async e=>{const t=we();t.log("post/isPostFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/posts/${e}/isflagbyme`);return n},onPostCreated:Qa,onPostUpdated:Va,onPostDeleted:Ha,onPostApproved:Wa,onPostDeclined:Ja,onPostFlagged:Ga,onPostUnflagged:Ya,onPostReactionAdded:Xa,onPostReactionRemoved:Za,observePosts:(e,t)=>{const{log:n}=we(),r=Date.now();n(`observePosts(tmpid: ${r}) > listen`);const s=[],o=(n,r)=>{var s,o;if(e.targetId===n.targetId&&e.targetType===n.targetType){if(t instanceof Function)return t(wn.post(n));null===(s=t.onEvent)||void 0===s||s.call(t,r,wn.post(n)),null===(o=t[r])||void 0===o||o.call(t,wn.post(n))}};return s.push(Qa((e=>o(e,"onCreate"))),Va((e=>o(e,"onUpdate"))),Ha((e=>o(e,"onDelete"))),Wa((e=>o(e,"onApproved"))),Ja((e=>o(e,"onDeclined"))),Ga((e=>o(e,"onFlagged"))),Ya((e=>o(e,"onUnflagged"))),Xa((e=>o(e,"onReactionAdded"))),Za((e=>o(e,"onReactionRemoved")))),()=>{n(`observePosts(tmpid: ${r}) > dispose`),s.forEach((e=>e()))}},observePost:(e,t,n="cache_then_server")=>{const{log:r}=we(),s=Date.now();r(`observePost(tmpid: ${s}) > listen`);const o=(e,n)=>{var r,s;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(s=t[n])||void 0===s||s.call(t,e)},a=(t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.postId)===e&&o(Object.assign(Object.assign({},t),{data:t.data&&wn.post(t.data)}),n)},i=[];return i.push(Va((e=>a({data:e,loading:!1,origin:"event"},"onUpdate"))),Ha((e=>a({data:e,loading:!1,origin:"event"},"onDelete"))),Wa((e=>a({data:e,loading:!1,origin:"event"},"onApproved"))),Ja((e=>a({data:e,loading:!1,origin:"event"},"onDeclined"))),Ga((e=>a({data:e,loading:!1,origin:"event"},"onFlagged"))),Ya((e=>a({data:e,loading:!1,origin:"event"},"onUnflagged"))),Xa((e=>a({data:e,loading:!1,origin:"event"},"onReactionAdded"))),Za((e=>a({data:e,loading:!1,origin:"event"},"onReactionRemoved")))),ie(oe(Oa,e),(e=>(e.data||e.error)&&o(Object.assign(Object.assign({},e),{data:e.data&&wn.post(e.data)}),"onFetch")),ae(n)),()=>{r(`observePosts(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getPost:(e,t)=>go(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?wn.post(e.data):n}))}),"postId",Oa,[Wa,Ja,jl,xl,t=>Ha((n=>{var r;let s=n;if(n.parentPostId===e&&n.isDeleted){const e=null===(r=Se(["post","get",n.parentPostId]))||void 0===r?void 0:r.data;e&&(e.children=e.children.filter((e=>e!==n.postId)),_e(["post","get",e.postId],e),s=e)}t(s)})),Ga,e=>Xa((t=>{e(wn.post(t))})),e=>Za((t=>{e(wn.post(t))})),Ya,Va,Ul,Dl,gi((t=>ni((async n=>{n.referenceId===e&&(await Oa(e),t(n))}))),"referenceId","post"),gi((t=>si((async n=>{n.referenceId===e&&(await Oa(e),t(n))}))),"referenceId","post")]),getPosts:(e,t,n)=>{const{log:r,cache:s}=we();s||console.log(D);const o=Date.now();r(`getPosts(tmpid: ${o}) > listen`);const a=new Ll(e,t),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>Te(c))),()=>{r(`getPosts(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getPinnedPosts:(e,t,n)=>{const{log:r,cache:s}=we();s||console.log(D);const o=Date.now();r(`getPinnedPosts(tmpid: ${o}) > listen`);const a=new zl(e,t),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>Te(c))),()=>{r(`getPinnedPosts(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},semanticSearchPosts:(e,t,n)=>{const{log:r,cache:s}=we();s||console.log(D);const o=Date.now();r(`semanticSearchPosts(tmpid: ${o}) > listen`);const a=new Jl(e,t),i=a.startSubscription(),c=a.getCacheKey();return i.push((()=>Te(c))),()=>{r(`semanticSearchPosts(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}}});const Yl=async e=>{const t=we();t.log("stream/getStream",e);const{data:n}=await t.http.get(`/api/v3/video-streaming/${e}`),r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const{videoStreamings:s}=n;return{data:s.find((t=>t.streamId===e)),cachedAt:r}};Yl.locally=e=>{const t=we();if(t.log("stream/getStream",e),!t.cache)return;const n=Se(["stream","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Xl=e=>{const t=we();return Xe(t,"stream/onStreamStarted","v3.video-streaming.didStart",(t=>{Kt(t),e(t.videoStreamings[0])}))},Zl=e=>{const t=we();return Xe(t,"stream/onStreamStropped","v3.video-streaming.didStop",(t=>{Kt(t),e(t.videoStreamings[0])}))},ed=e=>{const t=we();return Xe(t,"stream/onStreamRecorded","v3.video-streaming.didRecord",(t=>{Kt(t),e(t.videoStreamings[0])}))},td=e=>{const t=we();return Xe(t,"stream/onStreamFlagged","v3.video-streaming.didFlag",(t=>{Kt(t),e(t.videoStreamings[0])}))},nd=e=>{const t=we();return Xe(t,"stream/onStreamTerminated","v3.video-streaming.didTerminate",(t=>{Kt(t),e(t.videoStreamings[0])}))},rd=(e,t)=>go(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?wn.stream(e.data):n}))}),"streamId",Yl,[ed,Xl,Zl,td,nd]);rd.locally=e=>{const t=we();if(t.log("stream/getStreamById",e),!t.cache)return;const n=Se(["stream","get",e]);return n?{data:wn.stream(n.data),cachedAt:n.cachedAt}:void 0};const sd=async e=>{const t=we();t.log("stream/queryStreams",e);const n=null!=e?e:{},{page:r,limit:s}=n,o=zt(n,["page","limit"]),a=r?{token:r}:s?{limit:s}:void 0,{data:i}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},o),{options:a})}),{paging:c,results:l}=i,{videoStreamings:d}=l,u=t.cache&&Date.now();return t.cache&&Kt(l,{cachedAt:u}),{data:d,cachedAt:u,paging:c}};var od=Object.freeze({__proto__:null,createStream:async e=>{const t=we();t.log("stream/createStream",e);const{data:n}=await t.http.post("/api/v3/video-streaming",e),r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const{videoStreamings:s}=n;return{data:wn.stream(s[0]),cachedAt:r}},updateStream:async(e,t)=>{const n=we();n.log("stream/updateStream",e,t);const{data:r}=await n.http.put(`/api/v3/video-streaming/${e}`,t),s=n.cache&&Date.now();n.cache&&Kt(r,{cachedAt:s});const{videoStreamings:o}=r;return{data:wn.stream(o.find((t=>t.streamId===e))),cachedAt:s}},deleteStream:async e=>{const t=we();t.log("stream/deleteStream",e);const n=await Yl(e),{data:r}=await t.http.delete(`/api/v3/video-streaming/${e}`),{success:s}=r,o=Object.assign(Object.assign({},n.data),{isDeleted:!0});return Oe(["stream","get",e],o),s},disposeStream:async e=>{const t=we();t.log("stream/disposeStream",e);const{data:n}=await t.http.delete(`/api/v3/video-streaming/${e}/streaming-url`),r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const{videoStreamings:s}=n;return{data:s.find((t=>t.streamId===e)),cachedAt:r}},queryStreams:async e=>{const t=we();t.log("stream/queryStreams",e);const n=null!=e?e:{},{page:r}=n,s=zt(n,["page"]),{data:o}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},s),{options:{token:Y(r,"skiplimit")}})}),{paging:a,results:i}=o,{videoStreamings:c}=i,l=t.cache&&Date.now();t.cache&&Kt(i,{cachedAt:l});const d=X(a.next);return{data:c,cachedAt:l,prevPage:X(a.previous),nextPage:d}},getStream:Yl,onStreamStarted:Xl,onStreamStopped:Zl,onStreamRecorded:ed,onStreamFlagged:td,onStreamTerminated:nd,getStreamById:rd,getStreams:(e,t,n)=>{const{log:r,cache:s}=we();s||console.log(D);const o=Date.now();r(`getStreams(tmpid: ${o}) > listen`);const{limit:a}=e,i=zt(e,["limit"]),c=null!=a?a:j,{policy:l=x}=null!=n?n:{},d=[],u=["streams","collection",e],h=t=>{let n=Ee(t,"isDeleted",e.isDeleted);return n=n.sort("lastCreated"===e.sortBy?Fe:Be),n},p=(e,n=!1)=>{var r,s;const o=null!==(r=e.data.map((e=>Se(["stream","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];t({onNextPage:g,data:n?h(o):o,hasNextPage:!!(null===(s=e.params)||void 0===s?void 0:s.page),loading:e.loading,error:e.error})},f=e=>e=>{var t;const n=null===(t=Se(u))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.streamId,...n.data])],_e(u,n),p(n,!0))},g=(e=!1)=>{var t,n;const r=null===(t=Se(u))||void 0===t?void 0:t.data,s=null!==(n=null==r?void 0:r.data)&&void 0!==n?n:[];if(!e&&s.length>0&&!(null==r?void 0:r.params.page))return;const o=oe(sd,Object.assign(Object.assign({},i),{limit:e?c:void 0,page:e||null==r?void 0:r.params.page}));ie(o,(({data:e,error:t,loading:n,paging:r})=>{const o={loading:n,error:t,params:{page:null==r?void 0:r.next},data:s};e&&(o.data=[...new Set([...s,...e.map(de("stream"))])]),_e(u,o),p(o)}),ae(l))};return d.push(ed(f()),Xl(f()),Zl(f())),g(!0),()=>{r(`getStreams(tmpid: ${o}) > dispose`),d.forEach((e=>e()))}}});const ad=async e=>{const t=we();t.log("poll/getPoll",e);const{data:n}=await t.http.get(`/api/v3/polls/${e}`),r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const{polls:s}=n;return{data:s.find((t=>t.pollId===e)),cachedAt:r}};ad.locally=e=>{const t=we();if(t.log("poll/getPoll",e),!t.cache)return;const n=Se(["poll","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const id=e=>{const t=we();return Xe(t,"poll/onPollUpdated","poll.updated",(n=>{t.cache&&Kt(n),e(n.polls[0])}))},cd=e=>{const t=we();return Xe(t,"poll/onPollDeleted","poll.deleted",(n=>{t.cache&&Kt(n),e(n.polls[0])}))};var ld=Object.freeze({__proto__:null,createPoll:async e=>{const t=we();t.log("post/createPoll",e);const{data:n}=await t.http.post("/api/v3/polls",e),r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const{polls:s}=n;return{data:s[0],cachedAt:r}},closePoll:async e=>{const t=we();t.log("user/closePoll",e);const{data:n}=await t.http.put(`/api/v3/polls/${encodeURIComponent(e)}`,{status:"closed"}),r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r}),Ze("poll.updated",n);const{polls:s}=n;return{data:s.find((t=>t.pollId===e)),cachedAt:r}},deletePoll:async e=>{const t=we();t.log("poll/deletePoll",e);const n=await ad(e),{data:r}=await t.http.delete(`/api/v3/polls/${e}`),{success:s}=r,o=Object.assign(Object.assign({},n.data),{isDeleted:!0});return Oe(["poll","get",e],o),Ze("poll.deleted",{polls:[o],users:[]}),s},votePoll:async(e,t)=>{const n=we();n.log("user/votePoll",e);const{data:r}=await n.http.post(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:t}),s=n.cache&&Date.now();n.cache&&Kt(r,{cachedAt:s});const{polls:o}=r;return Ze("poll.updated",r),{data:o.find((t=>t.pollId===e)),cachedAt:s}},onPollUpdated:id,onPollDeleted:cd,observePoll:(e,t,n="cache_then_server")=>{const{log:r}=we(),s=Date.now();r(`observePoll(tmpid: ${s}) > listen`);const o=(e,n)=>{var r,s;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(s=t[n])||void 0===s||s.call(t,e)},a=(t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.pollId)===e&&o(t,n)},i=[];return i.push(id((e=>a({data:e,loading:!1,origin:"event"},"onUpdate"))),cd((e=>a({data:e,loading:!1,origin:"event"},"onDelete")))),ie(oe(ad,e),(e=>(e.data||e.error)&&o(e,"onFetch")),ae(n)),()=>{r(`observePoll(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getPoll:(e,t)=>go(e,t,"pollId",ad,[id,cd])});const dd={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};function ud(e){const n=new Uint8Array(e);let r="";return n.forEach((e=>{r+=String.fromCharCode(e)})),t.btoa(r)}function hd(e){const n=e.substring("-----BEGIN PRIVATE KEY-----".length,e.length-"-----END PRIVATE KEY-----".length),r=function(e){const t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let t=0,r=e.length;t<r;t+=1)n[t]=e.charCodeAt(t);return t}(t.atob(n));return crypto.subtle.importKey("pkcs8",r,dd,!1,["sign"])}async function pd({bufferCurrentUsage:e,getActiveStreams:t,updateUsage:n,dispose:r}){const s=e();if(s.length)try{const n=(new Date).toISOString(),o=await async function({timestamp:e,streams:t}){const n=t.map((e=>Object.keys(e).sort().map((t=>`${t}=${e[t]}`)).join("&"))).join(";"),r=b.default.v4(),s=`nonceStr=${r}×tamp=${e}&data=${n}==`,o=(new TextEncoder).encode(s),a=await hd("-----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:ud(await crypto.subtle.sign(dd,a,o)),nonceStr:r}}({timestamp:n,streams:s});if(!o||!o.signature)throw new Error("Signature is undefined");const a={signature:o.signature,nonceStr:o.nonceStr,timestamp:n,streams:s},i=we();return await i.http.post("/api/v3/user-event/video-streaming",a),t().length||e().length||r(),!0}catch(e){return s.forEach((e=>n(e))),!1}}class fd{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((()=>{pd({bufferCurrentUsage:this.bufferCurrentUsage.bind(this),getActiveStreams:this.getActiveStreams.bind(this),updateUsage:this.updateUsage.bind(this),dispose:this.dispose.bind(this)})}),2e4)}}let gd=null;class md{constructor(e,t){this.player=e,this.resolution=t,this._startTime=null,this._usageCollector=gd||(gd=new fd,gd),this._usageCollector.registerStream(e.id),this._sessionId=String(b.default.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,n=Math.round(t/1e3);n&&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:n,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 yd=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(!C.default.isSupported())throw new Error("This browswer does not support hls, unable to play stream");const{data:n}=await Yl(t),{watcherUrl:r,status:s,recordings:o=[],resolution:a}=n;if(!r.hls)throw new Error("This stream does not support hls. Unable to play");const i=document.createElement("video");i.id=t,i.controls=!0;const c=new C.default;if(c.attachMedia(i),"recorded"!==s){let{url:e}=r.hls;e=e.replace("http:","https:"),c.loadSource(e)}else{const e=o.find((e=>!!e.mp4));if(!e||!e.mp4)throw new Error("No playable recording available");i.src=e.mp4.url}return new md(i,a).registerEvents(),i}});const vd=e=>{const t=(e=>{var t;const n=we(),r=new Date,s=r.getTime()+31536e6,o=new Date(s).toISOString();let a=null===(t=Se(["storyTarget","get",e.targetId]))||void 0===t?void 0:t.data;return a||(a={targetType:e.targetType,targetId:e.targetId,lastStoryExpiresAt:o,targetPublicId:e.targetId,targetUpdatedAt:r.toISOString()},Kt({storyTargets:[a]})),{stories:[Object.assign({createdAt:r.toISOString(),updatedAt:r.toISOString(),flagCount:0,hashFlag:null,reactions:{},reactionsCount:0,storyId:e.referenceId,path:"",creatorId:n.userId||"",creatorPublicId:n.userId||"",targetPublicId:e.targetId,comments:[],commentsCount:0,isDeleted:!1,hasFlaggedComment:!1,mentionedUsers:[],impression:0,reach:0,expiresAt:new Date(s).toISOString()},e)],categories:[],communityUsers:[],comments:[],files:[],users:[],communities:[]}})(e);return Kt(t),t},bd=({payload:e,formData:t,isVideo:n=!1},r)=>{if(t){const s=t.getAll("files")[0]||void 0;if(!s)return;const o=Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileId:void 0,fileData:s.uri})});return n&&(o.data.videoFileId={original:void 0}),r(vd(o))}return r(vd(Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileData:null})})))},wd=async e=>{const t=we();t.log("post/createStory",e);const n=await t.http.post("/api/v4/stories",e),r=wl(n.data);t.cache&&Kt(r),_e(["story-sync-state",e.targetId],"synced"),Ze("local.story.created",r);const s=t.cache&&Date.now();return{data:r.stories.length>0?r.stories[0]:void 0,cachedAt:s}},Cd=e=>e?Se(["story","get",e]):{data:void 0,cachedAt:void 0},Id=async(e,t=!1)=>{const n=we();let r;if(n.log("story/deleteStory",e),n.cache&&(r=Cd(e),null==r?void 0:r.data)){const{data:e}=r;Ze("local.story.deleted",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[Object.assign(Object.assign({},e),{isDeleted:!0})]})}return(await n.http.delete(`/api/v4/stories/${e}`,{params:{permanent:t}})).data.success},Sd=e=>{const t=we(),n=[Xe(t,"onStoryUpdated","story.updated",(async t=>{const n=wl(t);Kt(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},_d=e=>{const t=we(),n=[Xe(t,"onStoryUpdated","local.story.updated",(async t=>{Kt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},kd=e=>{const t=we(),n=[Xe(t,"onStoryReactionAdded","story.reactionAdded",(async t=>{const{reactions:n}=t,r=zt(t,["reactions"]),s=wl(r),o=Ua("story.reactionAdded",Object.assign(Object.assign({},s),{reactions:n}));Kt(o),e(o.stories)}))];return()=>{n.forEach((e=>e()))}},Od=e=>{const t=we(),n=[Xe(t,"onStoryReactionAdded","local.story.reactionAdded",(async t=>{Kt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},Td=e=>{const t=we(),n=[Xe(t,"onStoryReactionRemoved","story.reactionRemoved",(async t=>{const{reactions:n}=t,r=zt(t,["reactions"]),s=wl(r),o=Ua("story.reactionRemoved",Object.assign(Object.assign({},s),{reactions:n}));Kt(o),e(o.stories)}))];return()=>{n.forEach((e=>e()))}},Ed=e=>{const t=we(),n=[Xe(t,"onStoryReactionRemoved","local.story.reactionRemoved",(async t=>{Kt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},Ad=e=>{e.forEach((e=>{const t=Se(["story-expire",e.targetId]),n=new Date(e.expiresAt||0);n<new Date((null==t?void 0:t.data)||0)||_e(["story-expire",e.targetId],n.toISOString())}))},Md=e=>{e.forEach((e=>{_e(["story-reference",e.storyId],e.referenceId)}))},Pd=async({targetType:e,targetId:t,options:n})=>{const r=we();r.log("story/getActiveStoriesByTarget");const s=r.cache&&Date.now(),o=await r.http.get("/api/v4/stories",{params:{targetType:e,targetId:t,options:{sortBy:(null==n?void 0:n.sortBy)||"createdAt",orderBy:(null==n?void 0:n.orderBy)||"desc"}}}),a=wl(o.data);return r.cache&&(Kt(a),Ad(a.stories),Md(a.stories)),{data:a.stories,cachedAt:s,paging:{next:void 0,previous:void 0}}},Rd=e=>{const t=we(),n=[Xe(t,"onStoryCreated","story.created",(async t=>{const n=wl(t,!0);Kt(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Ud=e=>{const t=we(),n=[Xe(t,"onStoryCreated","local.story.created",(async t=>{Kt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},jd=e=>{const t=we(),n=[Xe(t,"onStoryDeleted","story.deleted",(async t=>{const n=wl(t);Kt(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},xd=e=>{const t=we(),n=[Xe(t,"onStoryDeleted","local.story.deleted",(async t=>{Kt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},Dd=e=>{const t=we();return Xe(t,"onStoryError","local.story.error",(async t=>{Kt(t),e(t.stories)}))},Nd=e=>t=>e((e=>t(e[0]))),Bd=async e=>{const t=we();t.log("story/getTargetsByTargetIds",e);const n=await t.http.get("/api/v4/stories/seen",{params:{targets:e}}),{data:r}=n;return t.cache&&Kt(n.data),{data:r.storyTargets,cachedAt:Date.now()}};class qd extends Io{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.paginationController=r}saveToMainDB(e){const t=we(),n=t.cache&&Date.now(),r=wl(e);t.cache&&(Kt(r,{cachedAt:n}),Ad(r.stories),Md(r.stories))}getStoryReferenceIds(e){return(null==e?void 0:e.referenceId)?e.referenceId:e.storyId}appendToQueryStream(e,t,n=!1){var r,s;if(n)_e(this.cacheKey,{data:e.stories.map(this.getStoryReferenceIds)});else{const t=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];_e(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.stories.map(this.getStoryReferenceIds)])]}))}}reactor(e){return e=>{var t;const n=null===(t=Se(this.cacheKey))||void 0===t?void 0:t.data;if(!n)return;const r=e.map((({referenceId:e})=>e));n.data=[...new Set([...r,...n.data])],_e(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Fd extends _o{async getRequest(e){const{data:t}=await this.http.get("/api/v4/stories-by-targets",{params:Object.assign({},e)});return t}}class Ld extends ko{constructor(e,t){const n=w.default(e),r=["story-target-ids","collection",n],s=new Fd(e);super(s,n,r,t),this.query=e,this.queryStreamController=new qd(this.query,this.cacheKey,this.notifyChange.bind(this),s),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}persistModel(e){this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}notifyChange({origin:e,loading:t,error:n}){var r;const s=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;let o=s.data.map((e=>Se(["story","get",e]))).filter(Boolean).map((e=>wn.story(e.data)));(this.shouldNotify(o)||"event"!==e)&&(o=this.applyFilter(o),this.callback({onNextPage:void 0,data:o,hasNextPage:!1,loading:t,error:n}))}applyFilter(e){var t,n;const r=e;return"asc"===((null===(n=null===(t=this.query)||void 0===t?void 0:t.options)||void 0===n?void 0:n.orderBy)||"desc")?r.sort(Be):r.sort(Fe)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Rd,action:"onCreate"},{fn:Sd,action:"onUpdate"},{fn:jd,action:"onDelete"},{fn:Dd,action:"onError"}])}}const Kd=(e,t)=>{var n,r;const s=null===(n=Se(e))||void 0===n?void 0:n.data,o=null!==(r=null==s?void 0:s.data)&&void 0!==r?r:[];_e(e,Object.assign(Object.assign({},s),{data:[...new Set([...o,...t])]}))};class $d extends Io{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.paginationController=r,this.preparePayload=e=>e}saveToMainDB(e){const t=we(),n=t.cache&&Date.now(),r=this.preparePayload(e);t.cache&&Kt(r,{cachedAt:n})}appendToQueryStream(e,t,n=!1){n?_e(this.cacheKey,{data:e.storyTargets.map((({targetId:e})=>e))}):Kd(this.cacheKey,e.storyTargets.map((({targetId:e})=>e)))}reactor(e){return t=>{"onCreate"===e&&"seen"!==this.query.seenState&&Kd(this.cacheKey,t.map((({targetId:e})=>e))),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class zd extends wo{constructor(){super(...arguments),this.smartFilterState="unseen"}async getRequest(e,t){var n;const{limit:r=10,seenState:s="unseen"}=e,o=await this.createRequest({seenState:"smart"===s?this.smartFilterState:s,limit:r,token:t});if(null===(n=o.paging)||void 0===n?void 0:n.next)return o;if("smart"!==s)return o;if("seen"===this.smartFilterState)return o;this.smartFilterState="seen";const a=await this.createRequest({seenState:this.smartFilterState,limit:r});return c=a,{categories:(i=o).categories.concat(c.categories),communities:i.communities.concat(c.communities),communityUsers:i.communityUsers.concat(c.communityUsers),files:i.files.concat(c.files),storyTargets:i.storyTargets.concat(c.storyTargets),users:i.users.concat(c.users),paging:c.paging};var i,c}async createRequest(e){const{data:t}=await this.http.get("/api/v5/me/global-story-targets",{params:e});return n=t,r=e.seenState,Object.assign(Object.assign({},n),{storyTargets:n.storyTargets.map((e=>Object.assign(Object.assign({},e),{localFilter:r})))||[]});var n,r}}class Qd extends ko{constructor(e,t){const n=w.default(e),r=["story-global-feed","collection",n],s=new zd(e);super(s,n,r,t),this.query=e,this.queryStreamController=new $d(this.query,this.cacheKey,this.notifyChange.bind(this),s),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Se(this.cacheKey))||void 0===e?void 0:e.data)||_e(this.cacheKey,{data:[],params:{}})}persistModel(e){this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}notifyChange({origin:e,loading:t,error:n}){var r;const s=null===(r=Se(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;let o=s.data.map((e=>Se(["storyTarget","get",e]))).filter(Boolean).map((e=>wn.storyTarget(e.data)));(this.shouldNotify(o)||"event"!==e)&&(o=this.applyFilter(o).map((e=>zt(e,["localFilter","localLastExpires","localLastSeen","localSortingDate"]))),this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n}))}applyFilter(e){if("smart"!==this.query.seenState)return e.filter((({hasUnseen:e})=>"all"===this.query.seenState||("seen"===this.query.seenState&&!e||"unseen"===this.query.seenState&&e))).sort(qe);const t=e.reduce(((e,t)=>("unseen"===t.localFilter?e.unseen.push(t):"seen"===t.localFilter?e.seen.push(t):e.unknown.push(t),e)),{unseen:[],seen:[],unknown:[]}),n=t.unknown.sort(qe)||[],r=t.unseen.sort(qe)||[],s=t.seen.sort(qe)||[];return n.concat(r,s)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Rd,action:"onCreate"},{fn:Sd,action:"onUpdate"},{fn:jd,action:"onDelete"},{fn:Ud,action:"onCreate"},{fn:_d,action:"onUpdate"},{fn:xd,action:"onDelete"},{fn:Dd,action:"onError"}])}}var Vd=Object.freeze({__proto__:null,createImageStory:async(e,t,n,r={},s="fit",o=[])=>{if(!n.getAll("files").length)throw new Error("The formData object must have a `files` key.");let a={data:{text:"",fileId:void 0,fileData:null,imageDisplayMode:s},syncState:"syncing",referenceId:xt(),dataType:"image",items:o,targetType:e,targetId:t,metadata:r};const i=new Date;_e(["story-sync-state",t],"syncing"),_e(["story-expire",t],new Date(i.setFullYear(i.getFullYear()+1))),bd({payload:a,formData:n},(e=>{Ze("local.story.created",e)}));try{const{data:e}=await wa(n);if(0===e.length)throw new Error("Failed to upload image");const{fileId:t}=e[0];a=Object.assign(Object.assign({},a),{data:Object.assign(Object.assign({},a.data),{fileId:t})}),bd({payload:a,formData:n},(e=>{Ze("local.story.created",e)}));const r=await wd(a);return r.data?Object.assign(Object.assign({},r),{data:wn.story(r.data)}):r}catch(e){throw _e(["story-sync-state",t],"error"),bd({payload:Object.assign(Object.assign({},a),{syncState:"error"}),formData:n},(e=>{Ze("local.story.error",e)})),e}},createVideoStory:async(e,t,n,r={},s=[])=>{if(!n.getAll("files").length)throw new Error("The formData object must have a `files` key.");let o={data:{text:"",fileId:void 0,fileData:null},syncState:"syncing",referenceId:xt(),dataType:"video",items:s,targetType:e,targetId:t,metadata:r};const a=new Date;_e(["story-sync-state",t],"syncing"),_e(["story-expire",t],new Date(a.setFullYear(a.getFullYear()+1))),bd({payload:o,formData:n,isVideo:!0},(e=>{Ze("local.story.created",e)}));try{const{data:e}=await ba(n,M.STORY);if(0===e.length)throw new Error("Failed to upload video");const{fileId:t}=e[0];o=Object.assign(Object.assign({},o),{data:Object.assign(Object.assign({},o.data),{fileId:t,videoFileId:{original:t}})}),bd({payload:o,formData:n,isVideo:!0},(e=>{Ze("local.story.created",e)}));const r=await wd(o);return r.data?Object.assign(Object.assign({},r),{data:wn.story(r.data)}):r}catch(e){throw _e(["story-sync-state",t],"error"),bd({payload:Object.assign(Object.assign({},o),{syncState:"error"}),formData:n,isVideo:!0},(e=>{Ze("local.story.error",e)})),e}},hardDeleteStory:async e=>await Id(e,!0),softDeleteStory:async e=>await Id(e),getActiveStoriesByTarget:(e,t)=>{const{log:n,cache:r}=we(),s=[],o=["story-target","collection",e],a=Date.now();n(`getActiveStoriesByTarget(tmpid: ${a}) > listen`),r||console.log(D);const i=t=>{var n,r;const s=(null===(n=e.options)||void 0===n?void 0:n.sortBy)||"createdAt",o=(null===(r=e.options)||void 0===r?void 0:r.orderBy)||"desc";return 0===t.length?[]:"createdAt"===s?"asc"===o?t.sort(Be):t.sort(Fe):"asc"===o?t.sort(Le):t.sort(Ke)},c=e=>{var n;const r=e.data.map((e=>{const t=Cd(e);if(null==t?void 0:t.data)return wn.story(t.data)})).filter(Boolean).filter((e=>!!e&&!e.isDeleted)),s=[];if(r.length>0){const e=r.reduce(((e,t)=>{if(!t)return e;const{syncState:n}=t;if(!n)return e;let r=e.get(n);return r||(r=[]),r.push(t),e.set(n,r),e}),new Map);if(e.has("error")){const t=i(e.get("error")||[]);s.push(...t)}if(e.has("syncing")){const t=i(e.get("syncing")||[]);s.push(...t)}if(e.has("synced")){const t=i(e.get("synced")||[]);s.push(...t)}}t({onNextPage:()=>!1,data:s||r,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading||!1})},l=(e,t,n=!1,r=!1,s=!1)=>{const a=Se(o),i={loading:r,error:s,params:{page:void 0},data:(null==a?void 0:a.data)||[]};if(e)if("onDelete"===t){const t=e.map((({referenceId:e})=>e));i.data=i.data.filter((e=>!t.includes(e)))||[]}else i.data=n?e.map(de("story")):[...new Set([...i.data,...e.map(de("story"))])];_e(o,i.data),c(i)},d=e=>t=>{l(t,e)};return(t=>{const n=oe(Pd,e);ie(n,(({data:e,error:n,loading:r})=>{l(e,"fetch",t,r,n)}))})(!0),s.push(Rd(d("onCreate")),Sd(d("onUpdate")),jd(d("onDelete")),kd(d("onReactionAdded")),Td(d("onReactionRemoved")),Dd(d("onError")),Ud(d("onCreate")),_d(d("onUpdate")),xd(d("onDelete")),Od(d("onReactionAdded")),Ed(d("onReactionRemoved")),(e=>{const t=we();return Xe(t,"onStoryLocalDataUpdated","local.story.reload",(t=>{e(t)}))})((e=>{const t=Se(o);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 n={loading:!1,error:!1,params:{page:void 0},data:(null==t?void 0:t.data)||[]};c(n)})),(()=>Te(o))),()=>{n(`getActiveStoriesByTarget(tmpid: ${a}) > dispose`),s.forEach((e=>e()))}},getStoryByStoryId:(e,t)=>go(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:wn.story(e.data)})):t(e)}),"storyId",Cl,[Nd(Sd),Nd(jd),Nd(kd),Nd(Td),Nd(Dd),Nd(_d),Nd(xd),Nd(Od),Nd(Ed)]),getTargetById:(e,t)=>go(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:wn.storyTarget(e.data[0])})):t(e)}),"query",(e=>Bd([e])),[]),getTargetsByTargetIds:(e,t)=>{const{log:n,cache:r}=we(),s=[],o=["storyTargets","collection",e],a=Date.now();n(`getTargetsByTargetIds(tmpid: ${a}) > listen`),r||console.log(D);const i=(e,n=!1,r=!1,s=!1)=>{const a=Se(o),i={loading:r,error:s,params:{page:void 0},data:[]};e&&(i.data=n?e.map(de("storyTarget")):[...new Set([...(null==a?void 0:a.data)||[],...e.map(de("storyTarget"))])]),_e(o,i.data),(e=>{var n;const r=e.data.map((e=>{const t=Se(["storyTarget","get",e]);if(null==t?void 0:t.data)return wn.storyTarget(t.data)})).filter(Boolean);t({onNextPage:void 0,data:r,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading||!1})})(i)};return(t=>{const n=oe(Bd,e);ie(n,(({data:e,error:n,loading:r})=>{i(e,t,r,n)}))})(!0),s.push((()=>Te(o))),()=>{n(`getTargetsByTargetIds(tmpid: ${a}) > dispose`),s.forEach((e=>e()))}},getStoriesByTargetIds:(e,t,n)=>{const{log:r,cache:s,userId:o}=we();s||console.log(D);const a=Date.now();r(`getStoriesByTargetIds(tmpid: ${a}) > listen`);const i=new Ld(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{Te(l)})),()=>{r(`getStoriesByTargetIds(tmpid: ${a}) > dispose`),c.forEach((e=>e()))}},getGlobalStoryTargets:(e,t,n)=>{const{log:r,cache:s,userId:o}=we();s||console.log(D);const a=Date.now();r(`getGlobalStoryTarget(tmpid: ${a}) > listen`);const i=new Qd(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{Te(l)})),()=>{r(`getGlobalStoryTarget(tmpid: ${a}) > dispose`),c.forEach((e=>e()))}}});const Hd=e=>Object.assign(Object.assign({},e),{endAt:e.endAt?e.endAt:null}),Wd=e=>Object.assign({},e);var Jd=Object.freeze({__proto__:null,getNetworkAds:async()=>{const e=we(),{data:t}=await e.http.get("/api/v1/ads/me"),n=t.ads.map(Hd),r=t.advertisers.map(Wd);return Kt({ads:n,advertisers:r,files:t.files}),_e(["ad","setting"],t.settings),{ads:n.map(wn.ad),settings:t.settings}}});return e.API_REGIONS=vt,e.AdRepository=Jd,e.CategoryRepository=pl,e.ChannelRepository=lc,e.Client=mo,e.CommentRepository=Rl,e.CommunityPostSettingMaps=E,e.CommunityPostSettings=T,e.CommunityRepository=dl,e.ContentFeedType=M,e.DefaultCommunityPostSetting=A,e.FeedRepository=ml,e.FileRepository=Ca,e.FileType=I,e.LiveStreamPlayer=yd,e.MessageContentType=P,e.MessageRepository=Ki,e.PollRepository=ld,e.PostContentType=R,e.PostRepository=Gl,e.ReactionRepository=hi,e.StoryRepository=Vd,e.StreamRepository=od,e.SubChannelRepository=Ji,e.UserRepository=ya,e.VERSION=U,e.VideoResolution=S,e.VideoSize=k,e.VideoTranscodingStatus=_,e.backupCache=async(e="amitySdk",t=(e=>e.offline))=>{const{log:n,cache:r,userId:s}=we();if(!r)return!1;n("cache/api/backupCache",{storageKey:e});const o=Object.fromEntries(Object.entries(r.data).filter((([e,n])=>t(n))));return!!Object.keys(o).length&&(localStorage&&await localStorage.setItem(`${e}#${s}`,JSON.stringify(o)),!0)},e.createQuery=oe,e.createReport=async(e,t)=>{const n=we();return n.log("report/createReport",{referenceType:e,referenceId:t}),"user"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v4/me/flags/${encodeURIComponent(t)}`);if(e.cache){const e=await Nr(n);Kt(e)}return Ze("user.flagged",n),!!n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v5/messages/${encodeURIComponent(t)}/flags`);if(e.cache){const e=await Yn(n);Kt(e)}return Ze("message.flagged",n),!!n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v3/posts/${encodeURIComponent(t)}/flag`);if(e.cache){const e=await La(n);Kt(e)}return Ze("post.flagged",n),!!n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v3/comments/${encodeURIComponent(t)}/flag`);if(e.cache){const e=await pi(n);Kt(e)}return Ze("comment.flagged",n),!!n})({client:n,referenceId:t})},e.createUserToken=async(e,t,n)=>{const r=await Nt(),s=Bt(),o=Tt(wt("http",t)),{data:a}=await o.post("/api/v5/sessions",Object.assign(Object.assign({},n),{deviceId:r,deviceInfo:Object.assign(Object.assign({},s),{model:"token management API on TS-SDK"})}),{headers:{"X-API-Key":e}});return{accessToken:a.accessToken}},e.deleteReport=async(e,t)=>{const n=we();return n.log("report/deleteReport",{referenceType:e,referenceId:t}),"user"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v4/me/flags/${encodeURIComponent(t)}`);if(e.cache){const e=await Nr(n);Kt(e)}return Ze("user.unflagged",n),!!n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v5/messages/${encodeURIComponent(t)}/flags`);if(e.cache){const e=await Yn(n);Kt(e)}return Ze("message.unflagged",n),!!n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v3/posts/${encodeURIComponent(t)}/unflag`);if(e.cache){const e=await La(n);Kt(e)}return Ze("post.unflagged",n),!!n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v3/comments/${encodeURIComponent(t)}/unflag`);if(e.cache){const e=await pi(n);Kt(e)}return Ze("comment.unflagged",n),!!n})({client:n,referenceId:t})},e.disableCache=()=>{const e=we();e.cache&&(e.log("cache/api/disableCache"),delete e.cache)},e.dropFromCache=Te,e.enableCache=(e={},t)=>{const n=we();n.cache||(n.log("cache/api/enableCache"),n.cache={data:e,persistIf:t})},e.filterByChannelMembership=Pe,e.filterByCommunityMembership=Ue,e.filterByFeedType=Re,e.filterByPostDataTypes=je,e.filterByPropEquality=Ee,e.filterByPropInclusion=(e,t,n)=>void 0!==n?e.filter((e=>n.includes(e[t]))):e,e.filterByPropIntersection=Me,e.filterBySearchTerm=xe,e.filterByStringComparePartially=Ae,e.getChannelTopic=e=>`${e.path}/#`,e.getCommentTopic=({path:e})=>e,e.getCommunityStoriesTopic=({targetId:e,targetType:t})=>{const n=Qe();return`${ot(n)}/social/${t}/${e}/story/#`},e.getCommunityTopic=({path:t},n=e.SubscriptionLevels.COMMUNITY)=>st(t,n),e.getMarkedMessageTopic=it,e.getMarkerUserFeedTopic=ct,e.getMessageTopic=e=>e.path,e.getMyFollowersTopic=()=>{const e=Qe();return`${ot(e)}/membership/${e._id}/+/+`},e.getMyFollowingsTopic=()=>{const e=Qe();return`${ot(e)}/membership/+/${e._id}/+`},e.getNetworkTopic=lt,e.getPostTopic=({path:t},n=e.SubscriptionLevels.POST)=>"comment"===n?`${t}/comment/+`:t,e.getRole=Sa,e.getSmartFeedChannelTopic=dt,e.getSmartFeedMessageTopic=ht,e.getSmartFeedSubChannelTopic=ut,e.getStoryTopic=({targetId:e,targetType:t,storyId:n})=>{const r=Qe();return`${ot(r)}/social/${t}/${e}/story/${n}/#`},e.getSubChannelTopic=e=>`${e.path}/#`,e.getUserTopic=at,e.isAfterBefore=W,e.isAfterBeforeRaw=J,e.isCachable=re,e.isFetcher=ee,e.isFresh=se,e.isLocal=e=>re(e)&&-1===(null==e?void 0:e.cachedAt),e.isMutator=te,e.isOffline=ne,e.isPaged=G,e.isReportedByMe=async(e,t)=>{const n=we();return n.log("report/isReportedByMe",{referenceType:e,referenceId:t}),"user"===e?(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v3/users/${t}/isflagbyme`),{result:s,isFlagByMe:o}=null!=r?r:{};return null!==(n=null!=s?s:o)&&void 0!==n&&n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v5/messages/${encodeURIComponent(t)}/flags`),{result:s,isFlagByMe:o}=null!=r?r:{};return null!==(n=null!=s?s:o)&&void 0!==n&&n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v3/posts/${t}/isflagbyme`),{result:s,isFlagByMe:o}=null!=r?r:{};return null!==(n=null!=s?s:o)&&void 0!==n&&n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v3/comments/${t}/isflagbyme`),{result:s,isFlagByMe:o}=null!=r?r:{};return null!==(n=null!=s?s:o)&&void 0!==n&&n})({client:n,referenceId:t})},e.isSkip=H,e.mergeInCache=ke,e.onChannelMarkerFetched=so,e.onFeedMarkerFetched=e=>{const t=we();return Xe(t,"feedMarker/onFeedMarkerFetched","local.feedMarker.fetched",(t=>{e(t.feedMarkers[0])}))},e.onFeedMarkerUpdated=ks,e.onMessageMarked=uo,e.onMessageMarkerFetched=lo,e.onSubChannelMarkerFetched=oo,e.onSubChannelMarkerUpdated=ao,e.onUserMarkerFetched=io,e.onUserMarkerFetchedLegacy=co,e.pullFromCache=Se,e.pushToCache=_e,e.queryCache=Ie,e.queryOptions=ae,e.queryRoles=Ia,e.restoreCache=async(e="amitySdk")=>{var t;const n=we();if(!n.cache)return!1;n.log("cache/api/restoreCache",{storageKey:e});const r=localStorage&&null!==(t=await localStorage.getItem(`${e}#${n.userId}`))&&void 0!==t?t:"{}";let s={};try{s=JSON.parse(r)}catch(e){}return n.cache.data=Object.assign(Object.assign({},s),n.cache.data),!0},e.runQuery=ie,e.sortByChannelSegment=({channelSegment:e},{channelSegment:t})=>e-t,e.sortByDisplayName=De,e.sortByFirstCreated=Be,e.sortByFirstUpdated=Le,e.sortByLastActivity=$e,e.sortByLastCreated=Fe,e.sortByLastUpdated=Ke,e.sortByLocalSortingDate=qe,e.sortByName=Ne,e.sortBySegmentNumber=({segmentNumber:e},{segmentNumber:t})=>e-t,e.subscribeTopic=pt,e.toPage=X,e.toPageRaw=Z,e.toToken=Y,e.upsertInCache=Oe,e.wipeCache=async(e="amitySdk")=>{const{log:t,cache:n,userId:r}=we();return!!n&&(t("cache/api/wipeCache",{storageKey:e}),n.data={},localStorage&&await localStorage.setItem(`${e}#${r}`,"{}"),!0)},Object.defineProperty(e,"__esModule",{value:!0}),e}({},jsBase64,mitt,debug,axios,HttpAgent,io,AsyncStorage,uuid$1,reactNative,hash,Hls);
|