@amityco/ts-sdk-react-native 7.11.1-d5cedc38.0 → 7.11.1-fee58395.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/dist/index.umd.js CHANGED
@@ -1,5 +1,5 @@
1
- var Amity=function(e,t,n,r,a,o,s,i,c,l,d,u){"use strict";function h(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var p,f,m=h(n),g=h(r),y=h(a),v=h(o),b=h(s),w=h(i),C=h(c),I=h(d),S=h(u);e.MembershipAcceptanceTypeEnum=void 0,(p=e.MembershipAcceptanceTypeEnum||(e.MembershipAcceptanceTypeEnum={})).AUTOMATIC="automatic",p.INVITATION="invitation",e.UserTypeEnum=void 0,(f=e.UserTypeEnum||(e.UserTypeEnum={})).SIGNED_IN="signed-in",f.VISITOR="visitor",f.BOT="bot";const _=Object.freeze({FILE:"file",IMAGE:"image",VIDEO:"video",CLIP:"clip",AUDIO:"audio"}),k=Object.freeze({"1080P":"1080p","720P":"720p","480P":"480p","360P":"360p",ORIGINAL:"original"}),O=Object.freeze({UPLOADED:"uploaded",TRANSCODING:"transcoding",TRANSCODED:"transcoded",TRANSCODE_FAILED:"transcodeFailed"}),T=Object.freeze({LOW:"low",MEDIUM:"medium",HIGH:"high",ORIGINAL:"original"});var E;e.FileAccessTypeEnum=void 0,(E=e.FileAccessTypeEnum||(e.FileAccessTypeEnum={})).PUBLIC="public",E.NETWORK="network";const A=Object.freeze({ONLY_ADMIN_CAN_POST:"ONLY_ADMIN_CAN_POST",ADMIN_REVIEW_POST_REQUIRED:"ADMIN_REVIEW_POST_REQUIRED",ANYONE_CAN_POST:"ANYONE_CAN_POST"}),R=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}}),P="ONLY_ADMIN_CAN_POST",M=Object.freeze({STORY:"story",CLIP:"clip",CHAT:"chat",POST:"post",MESSAGE:"message"});var j;e.ContentFlagReasonEnum=void 0,(j=e.ContentFlagReasonEnum||(e.ContentFlagReasonEnum={})).CommunityGuidelines="Against community guidelines",j.HarassmentOrBullying="Harassment or bullying",j.SelfHarmOrSuicide="Self-harm or suicide",j.ViolenceOrThreateningContent="Violence or threatening content",j.SellingRestrictedItems="Selling and promoting restricted items",j.SexualContentOrNudity="Sexual message or nudity",j.SpamOrScams="Spam or scams",j.FalseInformation="False information or misinformation",j.Others="Others";const U=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",AUDIO:"audio",CUSTOM:"custom"}),x=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",LIVESTREAM:"liveStream",POLL:"poll",CLIP:"clip",AUDIO:"audio",ROOM:"room"}),D=Object.freeze({TEXT:"text",IMAGE:"image",VIDEO:"video",FILE:"file",AUDIO:"audio",MIXED:"mixed"});var q,N,B,L,F,K,$,Q;e.InvitationTypeEnum=void 0,(q=e.InvitationTypeEnum||(e.InvitationTypeEnum={})).CommunityMemberInvite="communityMemberInvite",q.LivestreamInvite="livestreamInvite",e.InvitationStatusEnum=void 0,(N=e.InvitationStatusEnum||(e.InvitationStatusEnum={})).Pending="pending",N.Approved="approved",N.Rejected="rejected",N.Cancelled="cancelled",e.InvitationSortByEnum=void 0,(B=e.InvitationSortByEnum||(e.InvitationSortByEnum={})).FirstCreated="firstCreated",B.LastCreated="lastCreated",e.JoinRequestStatusEnum=void 0,(L=e.JoinRequestStatusEnum||(e.JoinRequestStatusEnum={})).Pending="pending",L.Approved="approved",L.Rejected="rejected",L.Cancelled="cancelled",e.JoinResultStatusEnum=void 0,(F=e.JoinResultStatusEnum||(e.JoinResultStatusEnum={})).Success="success",F.Pending="pending",e.FeedDataTypeEnum=void 0,(K=e.FeedDataTypeEnum||(e.FeedDataTypeEnum={})).Text="text",K.Video="video",K.Image="image",K.File="file",K.Audio="audio",K.LiveStream="liveStream",K.Clip="clip",K.Poll="poll",e.FeedSortByEnum=void 0,($=e.FeedSortByEnum||(e.FeedSortByEnum={})).LastCreated="lastCreated",$.FirstCreated="firstCreated",$.LastUpdated="lastUpdated",$.FirstUpdated="firstUpdated",e.FeedSourceEnum=void 0,(Q=e.FeedSourceEnum||(e.FeedSourceEnum={})).Community="community",Q.User="user";const z=function(){try{return"v7.11.0-umd"}catch(e){return"__dev__"}}(),V=5,H="cache_then_server",J="For using Live Collection feature you need to enable Cache!",W="Observing unsynced object is not supported by Live Object.",G=-5,Y=1e3,X=6e5,Z="dead",ee=6e4,te=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})),ne=e=>JSON.parse(e),re=(e,t)=>e===t||!(!e||!t)&&("object"==typeof e&&Object.keys(e).every((n=>re(e[n],t[n])))),ae=e=>[400400,400300].includes(e),oe=e=>["skip"].some((t=>t in e)),se=e=>["after","before","first","last","limit"].some((t=>t in e)),ie=e=>"limit"in e,ce=e=>(null==e?void 0:e.hasOwnProperty("data"))&&(null==e?void 0:e.hasOwnProperty("nextPage"))&&(null==e?void 0:e.hasOwnProperty("prevPage")),le=(e,n)=>{var r;if(!e||!Object.keys(e).length)return;let a={};return"skiplimit"===n?a={skip:null!==(r=e.after)&&void 0!==r?r:0,limit:e.limit}:"afterbefore"===n&&se(e)?((null==e?void 0:e.before)&&(a=Object.assign(Object.assign({},a),{before:e.before})),(null==e?void 0:e.after)&&(a=Object.assign(Object.assign({},a),{after:e.after})),Number.isNaN(Number(null==e?void 0:e.limit))||(a=Object.assign(Object.assign({},a),{limit:e.limit}))):"afterbeforeraw"===n&&(a=e),Object.keys(a).length?t.encode(JSON.stringify(a)):void 0},de=e=>{if(!e)return;const n=JSON.parse(t.decode(e));if(oe(n))return{after:n.skip,limit:n.limit};if(se(n)){if("before"in n)return{before:n.before,limit:n.last};if("after"in n)return{after:n.after,limit:n.first}}},ue=e=>"locally"in e,he=e=>"optimistically"in e,pe=e=>ue(e)||he(e),fe=e=>null==e?void 0:e.hasOwnProperty("cachedAt"),me=(e,t=6e4)=>{var n;return Date.now()-(null!==(n=null==e?void 0:e.cachedAt)&&void 0!==n?n:0)<=t},ge=(e,...t)=>({func:e,args:t}),ye=(e,t=6e4)=>"cache_only"===e?{lifeSpan:1/0}:{lifeSpan:t<ee?ee:t},ve=({func:e,args:t},n,r=ye("cache_then_server"))=>{let a;const{lifeSpan:o}=ye("cache_then_server",r.lifeSpan);if(pe(e)){try{a=he(e)?e.optimistically(...t):e.locally(...t)}catch(e){null==n||n(be(void 0,{origin:"local",loading:!1,error:e}))}const r=fe(a)&&me(a,o);if(null==n||n(be(a,{origin:"local",loading:!(ue(e)&&r)})),r)return}else null==n||n(be(void 0,{origin:"local",loading:!0}));e(...t).then((e=>{null==n||n(be(e,{origin:"server",loading:!1}))})).catch((e=>{null==n||n(be(void 0,{origin:"server",loading:!1,error:e}))}))};function be(e,t){return ce(e)||fe(e)?Object.assign(Object.assign({},t),e):Object.assign(Object.assign({},t),{data:e})}const we={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,channelUnread:({channelId: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,notificationTrayItem:({_id:e})=>e,notificationTraySeen:({userId:e})=>e,invitation:({_id:e})=>e,joinRequest:({joinRequestId:e})=>e,room:({roomId:e})=>e},Ce=e=>we[e],Ie={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",videoStreamingChildren:"stream",videoStreamModerations:"streamModeration",follows:"follow",followCounts:"followCount",feeds:"feed",ads:"ad",advertisers:"advertiser",pinTargets:"pinTarget",pins:"pin",notificationTrayItems:"notificationTrayItem",invitations:"invitation",joinRequests:"joinRequest",rooms:"room"};function Se(e=(new Date).toISOString()){return new Date(new Date(e).getTime()+1).toISOString()}class _e 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,_e)}}class ke extends _e{constructor(e,t,n){super(e,t,n)}}class Oe extends _e{constructor(e=8e5,t="fatal"){super("Unexpected error",e,t)}}class Te extends _e{constructor(e,t="SDK client is having connection issues"){super(`${t} (${e})`,"disconnected"===e?800211:800210,"error"),this.event=e}}class Ee extends _e{constructor(e){super(e,800110,"error")}}let Ae=null;const Re=()=>{if(!Ae)throw new _e("There is no active client",8e5,"fatal");return Ae},Pe=e=>{Ae=e},Me=e=>{const{log:t,cache:n}=Re();if(n)return t("cache/api/queryCache",{key:e}),Object.keys(n.data).filter((t=>{const n=ne(t);return re(e,n)})).map((e=>n.data[e]))},je=e=>{const{log:t,cache:n}=Re();if(!n)return;t("cache/api/pullFromCache",e);const r=te(e);return n.data[r]?n.data[r]:void 0},Ue=(e,t,n={cachedAt:Date.now()})=>{const{log:r,cache:a}=Re();if(!a)return!1;r("cache/api/pushToCache",{key:e,data:t,options:n}),!(null==n?void 0:n.hasOwnProperty("offline"))&&a.persistIf&&(n.offline=a.persistIf(e,t));const o=te(e);return a.data[o]=Object.assign({key:e,data:t},n),!0},xe=(e,t,n)=>{const{log:r,cache:a}=Re();if(!a)return!1;r("cache/api/mergeInCache",{key:e,mutation:t});const o=je(e);if(!o)return!1;const s="function"==typeof t?t(o.data):Object.assign(Object.assign({},o.data),t);return i=o.data,!("updatedAt"in(c=s)&&"updatedAt"in i&&new Date(c.updatedAt)<new Date(i.updatedAt))&&(Ue(e,s,n),!0);var i,c},De=(e,t,n={cachedAt:Date.now()})=>{const{log:r,cache:a}=Re();if(!a)return!1;r("cache/api/upsertInCache",{key:e,data:t,options:n});return je(e)?xe(e,t,n):Ue(e,t,n)},qe=(e,t=!1)=>{const{log:n,cache:r}=Re();if(!r)return!1;if(n("cache/api/dropFromCache",{key:e,exact:t}),!t)return Object.keys(r.data).map((e=>ne(e))).filter((t=>re(e,t))).map((e=>qe(e,!0))).every((e=>e));const a=te(e);return a in r.data&&(delete r.data[a],!0)},Ne=(e,t,n)=>void 0!==n?e.filter((e=>JSON.stringify(e[t])===JSON.stringify(n))):e,Be=(e,t,n)=>void 0!==n?e.filter((e=>"string"==typeof e[t]&&"string"==typeof n&&String(e[t]).toLowerCase().match(n.toLowerCase()))):e,Le=(e,t,n)=>(null==n?void 0:n.length)?e.filter((e=>Array.isArray(e[t])&&n.some((n=>e[t].includes(n))))):e,Fe=(e,t,n)=>"all"===t?e:e.filter((e=>{var r;if("community"===e.type)return!0;const a=Ce("channelUsers")({channelId:e.channelPublicId,userId:n}),o=null===(r=je(["channelUsers","get",a]))||void 0===r?void 0:r.data;return"member"===t?o&&"none"!==o.membership:!o||"none"===o.membership})),Ke=(e,t)=>e.filter((({targetId:e,feedId:n})=>{var r;const a=null===(r=je(["feed","get",Ce("feed")({targetId:e,feedId:n})]))||void 0===r?void 0:r.data;return a&&a.feedType===t})),$e=(e,t,n)=>"all"===t?e:e.filter((e=>{var r;const a=Ce("communityUsers")({communityId:e.communityId,userId:n}),o=null===(r=je(["communityUsers","get",a]))||void 0===r?void 0:r.data;return"member"===t?o&&"member"===o.communityMembership:!o||"none"!==o.communityMembership})),Qe=(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 a=null===(r=je(["post","get",n.children[0]]))||void 0===r?void 0:r.data;return(null==t?void 0:t.includes(null==a?void 0:a.dataType))?e:[...e,n]}return e}),[]),ze=(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))}))},Ve=({displayName:e},{displayName:t})=>e&&t?e.localeCompare(t):e?-1:1,He=({name:e},{name:t})=>e&&t?e.localeCompare(t):e?-1:1,Je=({createdAt:e},{createdAt:t})=>new Date(e).valueOf()-new Date(t).valueOf(),We=({localSortingDate:e},{localSortingDate:t})=>new Date(t).getTime()-new Date(e).getTime(),Ge=({createdAt:e},{createdAt:t})=>new Date(t).valueOf()-new Date(e).valueOf(),Ye=({updatedAt:e=0},{updatedAt:t=0})=>new Date(e).valueOf()-new Date(t).valueOf(),Xe=({updatedAt:e=0},{updatedAt:t=0})=>new Date(t).valueOf()-new Date(e).valueOf(),Ze=({lastActivity:e},{lastActivity:t})=>new Date(t).valueOf()-new Date(e).valueOf();let et=null;const tt=()=>{if(!et)throw new _e("Connect client first",8e5,"fatal");return et},nt=e=>{et={_id:e._id,userId:e.userId,path:e.path}};let rt,at=[];const ot=e=>{clearTimeout(rt),at.push(e),rt=setTimeout((()=>{at.forEach((e=>e())),at=[]}),0)},st=["connect","message","disconnect","error","close","end","reconnect","video-streaming.didStart","video-streaming.didRecord","video-streaming.didStop","video-streaming.didFlag","video-streaming.didTerminate","video-streaming.viewerDidBan","video-streaming.viewerDidUnban","liveReaction.created"],it=(e,t,n,r)=>{const{log:a,emitter:o}=e,s=Date.now();a(`${t}(tmpid: ${s}) > listen`);const i=(...e)=>{a(`${t}(tmpid: ${s}) > trigger`,e);try{r(...e)}catch(e){a(`${t}(tmpid: ${s}) > error`,e)}};return o.on(n,i),()=>{a(`${t}(tmpid: ${s}) > dispose`),o.off(n,i)}},ct=(e,t)=>{const{emitter:n}=Re();ot((()=>{n.emit(e,t)}))};let lt,dt;async function ut(){var e;const{mqtt:t,emitter:n,token:r}=Re();if(!t)return;const a=null!==(e=null==r?void 0:r.accessToken)&&void 0!==e?e:"",o=tt();lt===a&&dt===o._id||(lt=a,dt=o._id,await t.connect({accessToken:lt,userId:dt}),((e,t)=>{st.forEach((n=>{null==e||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 ht;e.SubscriptionLevels=void 0,(ht=e.SubscriptionLevels||(e.SubscriptionLevels={})).COMMUNITY="community",ht.POST="post",ht.COMMENT="comment",ht.POST_AND_COMMENT="post_and_comment",ht.USER="user";const pt=(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}},ft=e=>e.path.split("/user/")[0],mt=({path:t},n=e.SubscriptionLevels.USER)=>pt(n===e.SubscriptionLevels.USER?t:t.replace(/^(\w*)/,"$1/social"),n),gt=({channelId:e,subChannelId:t})=>{const n=tt();return`${ft(n)}/marker/channel/${e}/message/${t}`},yt=()=>{const e=tt();return`${ft(e)}/marker/user/${e._id}`},vt=()=>ft(tt()),bt=()=>{const e=tt();return`${ft(e)}/smartfeed/${e._id}/channels`},wt=()=>{const e=tt();return`${ft(e)}/smartfeed/${e._id}/messagefeeds`},Ct=()=>{const e=tt();return`${ft(e)}/smartfeed/${e._id}/messages`},It=()=>{const e=tt();return`${ft(e)}/videostreaming`};function St(e,t){const{mqtt:n}=Re();return n?(ut(),n.subscribe(e,t)):()=>null}var _t;const kt="object"==typeof globalThis?globalThis:"object"==typeof global?global:window,{process:Ot={}}=kt,Tt="production"===(null===(_t=Ot.env)||void 0===_t?void 0:_t.NODE_ENV),Et={EU:"eu",SG:"sg",US:"us"},At={http:"https://apix.{region}.amity.co",upload:"https://upload.{region}.amity.co",mqtt:"wss://sse.{region}.amity.co:443/mqtt"};function Rt(e,t){return At[e].replace("{region}",t)}class Pt{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 Mt;var jt,Ut=()=>(Mt||(Mt=new Pt),Mt);!function(e){e.UserDeleted="User Deleted",e.UserGlobalBanned="User Global Banned",e.TokenExpired="Token Expired"}(jt||(jt={}));const xt=new AbortController,Dt=e=>{switch(e){case jt.UserGlobalBanned:throw new _e(e,400312,"fatal");case jt.UserDeleted:throw new _e(e,400100,"fatal");case jt.TokenExpired:throw ct("tokenExpired","tokenExpired"),new _e(e,800403,"fatal");default:throw new _e("Request Aborted",8e5,"error")}},qt=e=>{const t={maxSockets:100,maxFreeSockets:10,timeout:6e4,freeSocketTimeout:3e4},n=y.default.create({baseURL:e,httpAgent:new v.default(t),httpsAgent:new o.HttpsAgent(t),signal:xt.signal});return n.defaults.withCredentials=!1,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&&(xt.abort(),Dt(jt.UserGlobalBanned)),r&&(xt.abort(),Dt(jt.UserDeleted))}return e})),n.interceptors.response.use((e=>{var t;const n=new Headers;Object.entries(e.headers).forEach((([e,t])=>{"string"==typeof t&&n.append(e,t)}));const r=(e.config.baseURL||"")+(e.config.url||""),a=null===(t=e.config.method)||void 0===t?void 0:t.toUpperCase(),o={method:a,headers:e.config.headers};return"GET"!==a&&"HEAD"!==a&&(o.body=e.config.data),Ut().setNetworkActivities(new Request(r,o),{data:e.data,status:e.status,statusText:e.statusText,headers:n}),e}),(e=>{var t,n;const{response:r}=e;if(400100===(null==r?void 0:r.data.code)&&ct("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 Oe(e.code);if("error"===e.status)throw new ke(e.message,e.code,"error")})(null==r?void 0:r.data),xt.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 Nt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Bt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Lt(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 Ft={exports:{}};Ft.exports=function(){function e(t,n,r){function a(s,i){if(!n[s]){if(!t[s]){if(!i&&Lt)return Lt(s);if(o)return o(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[s]={exports:{}};t[s][0].call(l.exports,(function(e){return a(t[s][1][e]||e)}),l,l.exports,e,t,n,r)}return n[s].exports}for(var o=Lt,s=0;s<r.length;s++)a(r[s]);return a}return e}()({1:[function(e,t,n){(function(n,r){(function(){const a=e("events").EventEmitter,o=e("./store"),s=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"),m=e("xtend"),g=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&&(g("applyTopicAlias :: register topic: %s - alias: %d",r,n),!e.topicAliasSend.put(r,n)))return g("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},g("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},g("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},g("applyTopicAlias :: auto use topic: %s - alias: %d",r,n))));else if(n)return g("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){g("sendPacket :: packet: %O",t),g("sendPacket :: emitting `packetsend`"),e.emit("packetsend",t),g("sendPacket :: writing to stream");const r=c.writeToStream(t,e.stream,e.options);g("sendPacket :: writeToStream result %s",r),!r&&n&&n!==A?(g("sendPacket :: handle events on `drain` once through callback."),e.stream.once("drain",n)):n&&(g("sendPacket :: invoking cb"),n())}function O(e){e&&(g("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&&(g("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){g("storeAndSend :: store packet with cmd %s to outgoingStore",t.cmd);let a,o=t;if("publish"===o.cmd&&(o=p(t),a=_(e,o),a))return n&&n(a);e.outgoingStore.put(o,(function(a){if(a)return n&&n(a);r(),k(e,t,n)}))}function A(e){g("nop ::",e)}function R(e,t){let n;const r=this;if(!(this instanceof R))return new R(e,t);for(n in this.options=t||{},b)void 0===this.options[n]?this.options[n]=b[n]:this.options[n]=t[n];g("MqttClient :: options.protocol",t.protocol),g("MqttClient :: options.protocolVersion",t.protocolVersion),g("MqttClient :: options.username",t.username),g("MqttClient :: options.keepalive",t.keepalive),g("MqttClient :: options.reconnectPeriod",t.reconnectPeriod),g("MqttClient :: options.rejectUnauthorized",t.rejectUnauthorized),g("MqttClient :: options.topicAliasMaximum",t.topicAliasMaximum),this.options.clientId="string"==typeof t.clientId?t.clientId:I(),g("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?g("MqttClient :: options.topicAliasMaximum is out of range"):this.topicAliasRecv=new s(t.topicAliasMaximum)),this.on("connect",(function(){const e=this.queue;function t(){const n=e.shift();g("deliver :: entry %o",n);let a=null;if(!n)return void r._resubscribe();a=n.packet,g("deliver :: call _sendPacket for %o",a);let o=!0;a.messageId&&0!==a.messageId&&(r.messageIdProvider.register(a.messageId)||(o=!1)),o?r._sendPacket(a,(function(e){n.cb&&n.cb(e),t()})):(g("messageId: %d has already used. The message is skipped and removed.",a.messageId),t())}g("connect :: sending queued packets"),t()})),this.on("close",(function(){g("close :: connected set to `false`"),this.connected=!1,g("close :: clearing connackTimer"),clearTimeout(this.connackTimer),g("close :: clearing ping timer"),null!==r.pingTimer&&(r.pingTimer.clear(),r.pingTimer=null),this.topicAliasRecv&&this.topicAliasRecv.clear(),g("close :: calling _setupReconnect"),this._setupReconnect()})),a.call(this),g("MqttClient :: setting up stream"),this._setupStream()}u(R,a),R.prototype._setupStream=function(){const e=this,t=new d,n=c.parser(this.options);let r=null;const a=[];function o(){if(a.length)y(s);else{const e=r;r=null,e()}}function s(){g("work :: getting next packet in queue");const t=a.shift();if(t)g("work :: packet pulled from queue"),e._handlePacket(t,o);else{g("work :: no packets in queue");const e=r;r=null,g("work :: done flag is %s",!!e),e&&e()}}function i(t){g("streamErrorHandler :: error",t.message),w.includes(t.code)?(g("streamErrorHandler :: emitting error"),e.emit("error",t)):A(t)}g("_setupStream :: calling method to clear reconnect"),this._clearReconnect(),g("_setupStream :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),n.on("packet",(function(e){g("parser :: on packet push to packets array."),a.push(e)})),t._write=function(e,t,a){r=a,g("writable stream :: parsing buffer"),n.parse(e),s()},g("_setupStream :: pipe stream to writable stream"),this.stream.pipe(t),this.stream.on("error",i),this.stream.on("close",(function(){g("(%s)stream :: on close",e.options.clientId),T(e.outgoing),g("stream: emit close to MqttClient"),e.emit("close")})),g("_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,m({cmd:"auth",reasonCode:0},this.options.authPacket))}this.stream.setMaxListeners(1e3),clearTimeout(this.connackTimer),this.connackTimer=setTimeout((function(){g("!!connectTimeout hit!! Calling _cleanUp with force `true`"),e._cleanUp(!0)}),this.options.connectTimeout)},R.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(g("_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()}},R.prototype._checkDisconnecting=function(e){return this.disconnecting&&(e&&e!==A?e(new Error("client disconnecting")):this.emit("error",new Error("client disconnecting"))),this.disconnecting},R.prototype.publish=function(e,t,n,r){g("publish :: message `%s` to topic `%s`",t,e);const a=this.options;if("function"==typeof n&&(r=n,n=null),n=m({qos:0,retain:!1,dup:!1},n),this._checkDisconnecting(r))return this;const o=this,s=function(){let s=0;if((1===n.qos||2===n.qos)&&(s=o._nextId(),null===s))return g("No messageId left"),!1;const i={cmd:"publish",topic:e,payload:t,qos:n.qos,retain:n.retain,messageId:s,dup:n.dup};switch(5===a.protocolVersion&&(i.properties=n.properties),g("publish :: qos",n.qos),n.qos){case 1:case 2:o.outgoing[i.messageId]={volatile:!1,cb:r||A},g("MqttClient:publish: packet cmd: %s",i.cmd),o._sendPacket(i,void 0,n.cbStorePut);break;default:g("MqttClient:publish: packet cmd: %s",i.cmd),o._sendPacket(i,r,n.cbStorePut)}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!s())&&this._storeProcessingQueue.push({invoke:s,cbStorePut:n.cbStorePut,callback:r}),this},R.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 a=r.resubscribe;let o=t.pop()||A,s=t.pop();const i=this.options.protocolVersion;delete r.resubscribe,"string"==typeof r&&(r=[r]),"function"!=typeof o&&(s=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 g("subscribe: discconecting true"),this;const l={qos:0};if(5===i&&(l.nl=!1,l.rap=!1,l.rh=0),s=m(l,s),Array.isArray(r)?r.forEach((function(t){if(g("subscribe: array topic %s",t),!Object.prototype.hasOwnProperty.call(e._resubscribeTopics,t)||e._resubscribeTopics[t].qos<s.qos||a){const e={topic:t,qos:s.qos};5===i&&(e.nl=s.nl,e.rap=s.rap,e.rh=s.rh,e.properties=s.properties),g("subscribe: pushing topic `%s` and qos `%s` to subs list",e.topic,e.qos),n.push(e)}})):Object.keys(r).forEach((function(t){if(g("subscribe: object topic %s",t),!Object.prototype.hasOwnProperty.call(e._resubscribeTopics,t)||e._resubscribeTopics[t].qos<r[t].qos||a){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=s.properties),g("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 g("No messageId left"),!1;const r={cmd:"subscribe",subscriptions:n,qos:1,retain:!1,dup:!1,messageId:t};if(s.properties&&(r.properties=s.properties),e.options.resubscribe){g("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)}},g("subscribe :: call _sendPacket"),e._sendPacket(r),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!d())&&this._storeProcessingQueue.push({invoke:d,callback:o}),this},R.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,a=t.pop();"string"==typeof n&&(n=[n]),"function"!=typeof r&&(a=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 s=function(){const t=e._nextId();if(null===t)return g("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 a&&a.properties&&(o.properties=a.properties),e.outgoing[o.messageId]={volatile:!0,cb:r},g("unsubscribe: call _sendPacket"),e._sendPacket(o),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!s())&&this._storeProcessingQueue.push({invoke:s,callback:r}),this},R.prototype.end=function(e,t,n){const r=this;function a(){g("end :: closeStores: closing incoming and outgoing stores"),r.disconnected=!0,r.incomingStore.close((function(e){r.outgoingStore.close((function(t){if(g("end :: closeStores: emitting end"),r.emit("end"),n){const r=e||t;g("end :: closeStores: invoking callback with args"),n(r)}}))})),r._deferredReconnect&&r._deferredReconnect()}function o(){g("end :: (%s) :: finish :: calling _cleanUp with force %s",r.options.clientId,e),r._cleanUp(e,(()=>{g("end :: finish :: calling process.nextTick on closeStores"),y(a.bind(r))}),t)}return g("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),g("end :: cb? %s",!!n),n=n||A,this.disconnecting?(n(),this):(this._clearReconnect(),this.disconnecting=!0,!e&&Object.keys(this.outgoing).length>0?(g("end :: (%s) :: calling finish in 10ms once outgoing is empty",r.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,o,10))):(g("end :: (%s) :: immediately calling finish",r.options.clientId),o()),this)},R.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},R.prototype.reconnect=function(e){g("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},R.prototype._reconnect=function(){g("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected?(this.end((()=>{this._setupStream()})),g("client already connected. disconnecting first.")):(g("_reconnect: calling _setupStream"),this._setupStream())},R.prototype._setupReconnect=function(){const e=this;!e.disconnecting&&!e.reconnectTimer&&e.options.reconnectPeriod>0?(this.reconnecting||(g("_setupReconnect :: emit `offline` state"),this.emit("offline"),g("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0),g("_setupReconnect :: setting reconnectTimer for %d ms",e.options.reconnectPeriod),e.reconnectTimer=setInterval((function(){g("reconnectTimer :: reconnect triggered!"),e._reconnect()}),e.options.reconnectPeriod)):g("_setupReconnect :: doing nothing...")},R.prototype._clearReconnect=function(){g("_clearReconnect : clearing reconnect timer"),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null)},R.prototype._cleanUp=function(e,t){const n=arguments[2];if(t&&(g("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",t)),g("_cleanUp :: forced? %s",e),e)0===this.options.reconnectPeriod&&this.options.clean&&O(this.outgoing),g("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{const e=m({cmd:"disconnect"},n);g("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(e,v.bind(null,this.stream.end.bind(this.stream)))}this.disconnecting||(g("_cleanUp :: client not disconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect()),null!==this.pingTimer&&(g("_cleanUp :: clearing pingTimer"),this.pingTimer.clear(),this.pingTimer=null),t&&!this.connected&&(g("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",t),t())},R.prototype._sendPacket=function(e,t,n){g("_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)):(g("_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)}g("_sendPacket :: (%s) :: end",this.options.clientId)}},R.prototype._storePacket=function(e,t,n){g("_storePacket :: packet: %o",e),g("_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"))},R.prototype._setupPingTimer=function(){g("_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))},R.prototype._shiftPingInterval=function(){this.pingTimer&&this.options.keepalive&&this.options.reschedulePings&&this.pingTimer.reschedule(1e3*this.options.keepalive)},R.prototype._checkPing=function(){g("_checkPing :: checking ping..."),this.pingResp?(g("_checkPing :: ping response received. Clearing flag and sending `pingreq`"),this.pingResp=!1,this._sendPacket({cmd:"pingreq"})):(g("_checkPing :: calling _cleanUp with force true"),this._cleanUp(!0))},R.prototype._handlePingresp=function(){this.pingResp=!0},R.prototype._handleConnack=function(e){g("_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)}},R.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)}}))},R.prototype.handleAuth=function(e,t){t()},R.prototype._handlePublish=function(e,t){g("_handlePublish: packet %o",e),t=void 0!==t?t:A;let n=e.topic.toString();const r=e.payload,a=e.qos,o=e.messageId,s=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 g("_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 g("_handlePublish :: unregistered topic alias. alias: %d",t),void this.emit("error",new Error("Received unregistered Topic Alias"));n=e,g("_handlePublish :: topic complemented by alias. topic: %s - alias: %d",n,t)}}else{if(!this.topicAliasRecv.put(n,t))return g("_handlePublish :: topic alias out of range. alias: %d",t),void this.emit("error",new Error("Received Topic Alias is out of range"));g("_handlePublish :: registered topic: %s - alias: %d",n,t)}}switch(g("_handlePublish: qos %d",a),a){case 2:i.customHandleAcks(n,r,e,(function(n,r){return n instanceof Error||(r=n,n=null),n?s.emit("error",n):-1===c.indexOf(r)?s.emit("error",new Error("Wrong reason code for pubrec")):void(r?s._sendPacket({cmd:"pubrec",messageId:o,reasonCode:r},t):s.incomingStore.put(e,(function(){s._sendPacket({cmd:"pubrec",messageId:o},t)})))}));break;case 1:i.customHandleAcks(n,r,e,(function(a,i){return a instanceof Error||(i=a,a=null),a?s.emit("error",a):-1===c.indexOf(i)?s.emit("error",new Error("Wrong reason code for puback")):(i||s.emit("message",n,r,e),void s.handleMessage(e,(function(e){if(e)return t&&t(e);s._sendPacket({cmd:"puback",messageId:o,reasonCode:i},t)})))}));break;case 0:this.emit("message",n,r,e),this.handleMessage(e,t);break;default:g("_handlePublish: unknown QoS. Doing nothing.")}},R.prototype.handleMessage=function(e,t){t()},R.prototype._handleAck=function(e){const t=e.messageId,n=e.cmd;let r=null;const a=this.outgoing[t]?this.outgoing[t].cb:null,o=this;let s;if(a){switch(g("_handleAck :: packet type",n),n){case"pubcomp":case"puback":{const n=e.reasonCode;n&&n>0&&16!==n&&(s=new Error("Publish error: "+C[n]),s.code=n,a(s,e)),delete this.outgoing[t],this.outgoingStore.del(e,a),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?(s=new Error("Publish error: "+C[n]),s.code=n,a(s,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(),a(null,e);break;case"unsuback":delete this.outgoing[t],this.messageIdProvider.deallocate(t),this._invokeStoreProcessingQueue(),a(null);break;default:o.emit("error",new Error("unrecognized packet type"))}this.disconnecting&&0===Object.keys(this.outgoing).length&&this.emit("outgoingEmpty")}else g("_handleAck :: Server sent an ack in error. Ignoring.")},R.prototype._handlePubrel=function(e,t){g("handling pubrel packet"),t=void 0!==t?t:A;const n=e.messageId,r=this,a={cmd:"pubcomp",messageId:n};r.incomingStore.get(e,(function(e,n){e?r._sendPacket(a,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(a,t)})))}))},R.prototype._handleDisconnect=function(e){this.emit("disconnect",e)},R.prototype._nextId=function(){return this.messageIdProvider.allocate()},R.prototype.getLastMessageId=function(){return this.messageIdProvider.getLastAllocated()},R.prototype._resubscribe=function(){g("_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){g("_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},R.prototype._onConnect=function(e){if(this.disconnected)return void this.emit("connect",e);const t=this;function n(){let r=t.outgoingStore.createStream();function a(){t._storeProcessing=!1,t._packetIdsDuringStoreProcessing={}}function o(){r.destroy(),r=null,t._flushStoreProcessingQueue(),a()}function s(){if(!r)return;t._storeProcessing=!0;const e=r.read(1);let n;e?t._packetIdsDuringStoreProcessing[e.messageId]?s():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),s()}},t._packetIdsDuringStoreProcessing[e.messageId]=!0,t.messageIdProvider.register(e.messageId)?t._sendPacket(e):g("messageId: %d has already used.",e.messageId)):r.once("readable",s)}t.once("close",o),r.on("error",(function(e){a(),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?(a(),t.removeListener("close",o),t._invokeAllStoreProcessingQueue(),t.emit("connect",e)):n()})),s()}this.connackPacket=e,this.messageIdProvider.clear(),this._setupPingTimer(),this.connected=!0,n()},R.prototype._invokeStoreProcessingQueue=function(){if(this._storeProcessingQueue.length>0){const e=this._storeProcessingQueue[0];if(e&&e.invoke())return this._storeProcessingQueue.shift(),!0}return!1},R.prototype._invokeAllStoreProcessingQueue=function(){for(;this._invokeStoreProcessingQueue(););},R.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=R}).call(this)}).call(this,e("_process"),void 0!==Nt?Nt:"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"),a=e("readable-stream").Transform,o=e("duplexify");let s,i,c,l=!1;function d(){const e=new a;return e._write=function(e,t,n){s.sendSocketMessage({data:e.buffer,success:function(){n()},fail:function(){n(new Error)}})},e._flush=function(e){s.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,s.onSocketOpen((function(){c.setReadable(i),c.setWritable(i),c.emit("connect")})),s.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)}})),s.onSocketClose((function(){c.end(),c.destroy()})),s.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 s=t.my,s.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"),a=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 a("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"),a=e("net"),o=e("debug")("mqttjs:tls");function s(e,t){t.port=t.port||8883,t.host=t.hostname||t.host||"localhost",0===a.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 s(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",s)})),n.on("error",s),n}t.exports=s},{debug:18,net:16,tls:16}],5:[function(e,t,n){(function(n){(function(){const{Buffer:r}=e("buffer"),a=e("ws"),o=e("debug")("mqttjs:ws"),s=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 a(t,[r],n.wsOptions)}function f(e,t){const n="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt",r=d(t,e),a=new WebSocket(r,[n]);return a.binaryType="arraybuffer",a}function m(e,t){o("streamBuilder");const n=u(t),r=d(n,e),s=p(e,r,n),i=a.createWebSocketStream(s,n.wsOptions);return i.url=r,s.on("close",(()=>{i.destroy()})),i}function g(e,t){let n;o("browserStreamBuilder");const a=h(t).browserBufferSize||524288,c=t.browserBufferTimeout||1e3,l=!t.objectMode,d=f(e,t),u=m(t,C,I);t.objectMode||(u._writev=w),u.on("close",(()=>{d.close()}));const p=void 0!==d.addEventListener;function m(e,t,n){const r=new i({objectModeMode:e.objectMode});return r._write=t,r._flush=n,r}function g(){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>a&&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=s(void 0,void 0,t),t.objectMode||(n._writev=w),p?d.addEventListener("open",g):d.onopen=g),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?g:m}).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"),a=e("readable-stream").Transform,o=e("duplexify");let s,i,c;function l(){const e=new a;return e._write=function(e,t,n){s.send({data:e.buffer,success:function(){n()},fail:function(e){n(new Error(e))}})},e._flush=function(e){s.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(){s.onOpen((function(){c.setReadable(i),c.setWritable(i),c.emit("connect")})),s.onMessage((function(e){let t=e.data;t=t instanceof ArrayBuffer?r.from(t):r.from(t,"utf8"),i.push(t)})),s.onClose((function(){c.end(),c.destroy()})),s.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);s=wx.connectSocket({url:r,protocols:[n]}),i=l(),c=o.obj(),c._destroy=function(e,t){s.close({success:function(){t&&t(e)}})};const a=c.destroy;return c.destroy=function(){c.destroy=a;const e=this;setTimeout((function(){s.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"),a=e("readable-stream").Readable,o={objectMode:!0},s={clean:!0};function i(e){if(!(this instanceof i))return new i(e);this.options=e||{},this.options=r(s,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 a(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"),a=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 a(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 a(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:a}},{}],12:[function(e,t,n){(function(n){(function(){const r=e("../client"),a=e("../store"),o=e("url"),s=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=s(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 a=new r(n,t);return a.on("error",(function(){})),a}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=a}).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=m;for(var r=[],a=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,c=s.length;i<c;++i)r[i]=s[i],a[s.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),s=r[0],i=r[1],c=new o(u(e,s,i)),d=0,h=i>0?s-4:s;for(n=0;n<h;n+=4)t=a[e.charCodeAt(n)]<<18|a[e.charCodeAt(n+1)]<<12|a[e.charCodeAt(n+2)]<<6|a[e.charCodeAt(n+3)],c[d++]=t>>16&255,c[d++]=t>>8&255,c[d++]=255&t;return 2===i&&(t=a[e.charCodeAt(n)]<<2|a[e.charCodeAt(n+1)]>>4,c[d++]=255&t),1===i&&(t=a[e.charCodeAt(n)]<<10|a[e.charCodeAt(n+1)]<<4|a[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,a=[],o=t;o<n;o+=3)r=(e[o]<<16&16711680)+(e[o+1]<<8&65280)+(255&e[o+2]),a.push(p(r));return a.join("")}function m(e){for(var t,n=e.length,a=n%3,o=[],s=16383,i=0,c=n-a;i<c;i+=s)o.push(f(e,i,i+s>c?c:i+s));return 1===a?(t=e[n-1],o.push(r[t>>2]+r[t<<4&63]+"==")):2===a&&(t=(e[n-2]<<8)+e[n-1],o.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"=")),o.join("")}a["-".charCodeAt(0)]=62,a["_".charCodeAt(0)]=63},{}],14:[function(e,t,n){const{Buffer:r}=e("buffer"),a=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,a,{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,a){if(("number"!=typeof n||n<0)&&(n=0),("number"!=typeof a||a>this.length)&&(a=this.length),n>=this.length)return e||r.alloc(0);if(a<=0)return e||r.alloc(0);const o=!!e,s=this._offset(n),i=a-n;let c=i,l=o&&t||0,d=s[1];if(0===n&&a===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[s[0]].length-d)return o?this._bufs[s[0]].copy(e,t,d,d+c):this._bufs[s[0]].slice(d,d+c);o||(e=r.allocUnsafe(i));for(let t=s[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),a=this._bufs.slice(n[0],r[0]+1);return 0===r[1]?a.pop():a[a.length-1]=a[a.length-1].slice(0,r[1]),0!==n[1]&&(a[0]=a[0].slice(n[1])),this._new(a)},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 a=this._offset(t);let o=a[0],s=a[1];for(;o<this._bufs.length;o++){const t=this._bufs[o];for(;s<t.length;)if(t.length-s>=e.length){const n=t.indexOf(e,s);if(-1!==n)return this._reverseOffset([o,n]);s=t.length-e.length+1}else{const t=this._reverseOffset([o,s]);if(this._match(t,e))return t;s++}s=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[a]},t.exports=o},{buffer:17}],15:[function(e,t,n){const r=e("readable-stream").Duplex,a=e("inherits"),o=e("./BufferList");function s(e){if(!(this instanceof s))return new s(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)}a(s,r),Object.assign(s.prototype,o.prototype),s.prototype._new=function(e){return new s(e)},s.prototype._write=function(e,t,n){this._appendBuffer(e),"function"==typeof n&&n()},s.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)},s.prototype.end=function(e){r.prototype.end.call(this,e),this._callback&&(this._callback(null,this.slice()),this._callback=null)},s.prototype._destroy=function(e,t){this._bufs.length=0,this.length=0,t(e)},s.prototype._isBufferList=function(e){return e instanceof s||e instanceof o||s.isBufferList(e)},s.isBufferList=o.isBufferList,t.exports=s,t.exports.BufferListStream=s,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 a=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 s(e){if(e>a)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 a=m(e);if(a)return a;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?s(e):void 0!==t?"string"==typeof n?s(e).fill(t,n):s(e).fill(t):s(e)}function u(e){return l(e),s(e<0?0:0|g(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=s(n),a=r.write(e,t);return a!==n&&(r=r.slice(0,a)),r}function p(e){for(var t=e.length<0?0:0|g(e.length),n=s(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 m(e){if(i.isBuffer(e)){var t=0|g(e.length),n=s(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0!==e.length?"number"!=typeof e.length||Y(e.length)?s(0):p(e):"Buffer"===e.type&&Array.isArray(e.data)?p(e.data):void 0}function g(e){if(e>=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.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 a=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return z(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return J(e).length;default:if(a)return r?-1:z(e).length;t=(""+t).toLowerCase(),a=!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 R(this,t,n);case"ascii":return j(this,t,n);case"latin1":case"binary":return U(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,a){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=a?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(a)return-1;n=e.length-1}else if(n<0){if(!a)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,a);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):I(e,[t],n,r,a);throw new TypeError("val must be string, number or Buffer")}function I(e,t,n,r,a){var o,s=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;s=2,i/=2,c/=2,n/=2}function l(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(a){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*s}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 a=e.length-n;r?(r=Number(r))>a&&(r=a):r=a;var o=t.length;r>o/2&&(r=o/2);for(var s=0;s<r;++s){var i=parseInt(t.substr(2*s,2),16);if(Y(i))return s;e[n+s]=i}return s}function _(e,t,n,r){return W(z(t,e.length-n),e,n,r)}function k(e,t,n,r){return W(V(t),e,n,r)}function O(e,t,n,r){return k(e,t,n,r)}function T(e,t,n,r){return W(J(t),e,n,r)}function E(e,t,n,r){return W(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 R(e,t,n){n=Math.min(e.length,n);for(var r=[],a=t;a<n;){var o,s,i,c,l=e[a],d=null,u=l>239?4:l>223?3:l>191?2:1;if(a+u<=n)switch(u){case 1:l<128&&(d=l);break;case 2:128==(192&(o=e[a+1]))&&(c=(31&l)<<6|63&o)>127&&(d=c);break;case 3:o=e[a+1],s=e[a+2],128==(192&o)&&128==(192&s)&&(c=(15&l)<<12|(63&o)<<6|63&s)>2047&&(c<55296||c>57343)&&(d=c);break;case 4:o=e[a+1],s=e[a+2],i=e[a+3],128==(192&o)&&128==(192&s)&&128==(192&i)&&(c=(15&l)<<18|(63&o)<<12|(63&s)<<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),a+=u}return M(r)}n.kMaxLength=a,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,a=0,o=Math.min(n,r);a<o;++a)if(e[a]!==t[a]){n=e[a],r=t[a];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),a=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,a),a+=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?R(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,a){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===a&&(a=this.length),t<0||n>e.length||r<0||a>this.length)throw new RangeError("out of range index");if(r>=a&&t>=n)return 0;if(r>=a)return-1;if(t>=n)return 1;if(this===e)return 0;for(var o=(a>>>=0)-(r>>>=0),s=(n>>>=0)-(t>>>=0),c=Math.min(o,s),l=this.slice(r,a),d=e.slice(t,n),u=0;u<c;++u)if(l[u]!==d[u]){o=l[u],s=d[u];break}return o<s?-1:s<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 a=this.length-t;if((void 0===n||n>a)&&(n=a),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 M(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 j(e,t,n){var r="";n=Math.min(e.length,n);for(var a=t;a<n;++a)r+=String.fromCharCode(127&e[a]);return r}function U(e,t,n){var r="";n=Math.min(e.length,n);for(var a=t;a<n;++a)r+=String.fromCharCode(e[a]);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 a="",o=t;o<n;++o)a+=Q(e[o]);return a}function D(e,t,n){for(var r=e.slice(t,n),a="",o=0;o<r.length;o+=2)a+=String.fromCharCode(r[o]+256*r[o+1]);return a}function q(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 N(e,t,n,r,a,o){if(!i.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>a||t<o)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function B(e,t,n,r,a,o){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function L(e,t,n,a,o){return t=+t,n>>>=0,o||B(e,t,n,4),r.write(e,t,n,a,23,4),n+4}function F(e,t,n,a,o){return t=+t,n>>>=0,o||B(e,t,n,8),r.write(e,t,n,a,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||q(e,t,this.length);for(var r=this[e],a=1,o=0;++o<t&&(a*=256);)r+=this[e+o]*a;return r},i.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||q(e,t,this.length);for(var r=this[e+--t],a=1;t>0&&(a*=256);)r+=this[e+--t]*a;return r},i.prototype.readUInt8=function(e,t){return e>>>=0,t||q(e,1,this.length),this[e]},i.prototype.readUInt16LE=function(e,t){return e>>>=0,t||q(e,2,this.length),this[e]|this[e+1]<<8},i.prototype.readUInt16BE=function(e,t){return e>>>=0,t||q(e,2,this.length),this[e]<<8|this[e+1]},i.prototype.readUInt32LE=function(e,t){return e>>>=0,t||q(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||q(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||q(e,t,this.length);for(var r=this[e],a=1,o=0;++o<t&&(a*=256);)r+=this[e+o]*a;return r>=(a*=128)&&(r-=Math.pow(2,8*t)),r},i.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||q(e,t,this.length);for(var r=t,a=1,o=this[e+--r];r>0&&(a*=256);)o+=this[e+--r]*a;return o>=(a*=128)&&(o-=Math.pow(2,8*t)),o},i.prototype.readInt8=function(e,t){return e>>>=0,t||q(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},i.prototype.readInt16LE=function(e,t){e>>>=0,t||q(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||q(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||q(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||q(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||q(e,4,this.length),r.read(this,e,!0,23,4)},i.prototype.readFloatBE=function(e,t){return e>>>=0,t||q(e,4,this.length),r.read(this,e,!1,23,4)},i.prototype.readDoubleLE=function(e,t){return e>>>=0,t||q(e,8,this.length),r.read(this,e,!0,52,8)},i.prototype.readDoubleBE=function(e,t){return e>>>=0,t||q(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||N(this,e,t,n,Math.pow(2,8*n)-1,0);var a=1,o=0;for(this[t]=255&e;++o<n&&(a*=256);)this[t+o]=e/a&255;return t+n},i.prototype.writeUIntBE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||N(this,e,t,n,Math.pow(2,8*n)-1,0);var a=n-1,o=1;for(this[t+a]=255&e;--a>=0&&(o*=256);)this[t+a]=e/o&255;return t+n},i.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||N(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||N(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||N(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||N(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},i.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var a=Math.pow(2,8*n-1);N(this,e,t,n,a-1,-a)}var o=0,s=1,i=0;for(this[t]=255&e;++o<n&&(s*=256);)e<0&&0===i&&0!==this[t+o-1]&&(i=1),this[t+o]=(e/s>>0)-i&255;return t+n},i.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var a=Math.pow(2,8*n-1);N(this,e,t,n,a-1,-a)}var o=n-1,s=1,i=0;for(this[t+o]=255&e;--o>=0&&(s*=256);)e<0&&0===i&&0!==this[t+o+1]&&(i=1),this[t+o]=(e/s>>0)-i&255;return t+n},i.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||N(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||N(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||N(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||N(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},i.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeFloatLE=function(e,t,n){return L(this,e,t,!0,n)},i.prototype.writeFloatBE=function(e,t,n){return L(this,e,t,!1,n)},i.prototype.writeDoubleLE=function(e,t,n){return F(this,e,t,!0,n)},i.prototype.writeDoubleBE=function(e,t,n){return F(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 a=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=a-1;o>=0;--o)e[o+t]=this[o+n];else Uint8Array.prototype.set.call(e,this.subarray(n,r),t);return a},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 a=e.charCodeAt(0);("utf8"===r&&a<128||"latin1"===r)&&(e=a)}}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 s=i.isBuffer(e)?e:i.from(e,r),c=s.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]=s[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 Q(e){return e<16?"0"+e.toString(16):e.toString(16)}function z(e,t){var n;t=t||1/0;for(var r=e.length,a=null,o=[],s=0;s<r;++s){if((n=e.charCodeAt(s))>55295&&n<57344){if(!a){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&o.push(239,191,189);continue}a=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),a=n;continue}n=65536+(a-55296<<10|n-56320)}else a&&(t-=3)>-1&&o.push(239,191,189);if(a=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,a,o=[],s=0;s<e.length&&!((t-=2)<0);++s)r=(n=e.charCodeAt(s))>>8,a=n%256,o.push(a),o.push(r);return o}function J(e){return t.toByteArray($(e))}function W(e,t,n,r){for(var a=0;a<r&&!(a+n>=t.length||a>=e.length);++a)t[a+n]=e[a];return a}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 a(){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,a=0;e[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(a=r))})),e.splice(a,0,n)}function s(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=s,n.load=i,n.useColors=a,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,s=null;function i(...e){if(!i.enabled)return;const n=i,a=Number(new Date),o=a-(t||a);n.diff=o,n.prev=t,n.curr=a,t=a,e[0]=r.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let s=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((t,a)=>{if("%%"===t)return"%";s++;const o=r.formatters[a];if("function"==typeof o){const r=e[s];t=o.call(n,r),e.splice(s,1),s--}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=a,i.destroy=r.destroy,Object.defineProperty(i,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==s?s:(n!==r.namespaces&&(n=r.namespaces,o=r.enabled(e)),o),set:e=>{s=e}}),"function"==typeof r.init&&r.init(i),i}function a(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,]+/),a=n.length;for(t=0;t<a;t++)n[t]&&("-"===(e=n[t].replace(/\*/g,".*?"))[0]?r.skips.push(new RegExp("^"+e.substr(1)+"$")):r.names.push(new RegExp("^"+e+"$")))}function s(){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=s,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 a=e("readable-stream"),o=e("end-of-stream"),s=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 a.Readable({objectMode:!0,highWaterMark:16}).wrap(e)},m=function(e,t,n){if(!(this instanceof m))return new m(e,t,n);a.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)};s(m,a.Duplex),m.obj=function(e,t,n){return n||(n={}),n.objectMode=!0,n.highWaterMark=16,new m(e,t,n)},m.prototype.cork=function(){1==++this._corked&&this.emit("cork")},m.prototype.uncork=function(){this._corked&&0==--this._corked&&this.emit("uncork")},m.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)),a=function(){var e=t._ondrain;t._ondrain=null,e&&e()},s=function(){t._writable.removeListener("drain",a),r()};this._unwrite&&n.nextTick(a),this._writable=e,this._writable.on("drain",a),this._unwrite=s,this.uncork()}else this.end()},m.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()},a=function(){t.push(null)},s=function(){t._readable2.removeListener("readable",r),t._readable2.removeListener("end",a),n()};this._drained=!0,this._readable=e,this._readable2=e._readableState?e:f(e),this._readable2.on("readable",r),this._readable2.on("end",a),this._unread=s,this._forward()}},m.prototype._read=function(){this._drained=!0,this._forward()},m.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}},m.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)}))},m.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")},m.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()},m.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)}))}))},m.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),a.Writable.prototype.end.call(this,n))},t.exports=m}).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"),a=function(){},o=function(e){return e.setHeader&&"function"==typeof e.abort},s=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||a);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||m()},m=function(){h=!1,u||c.call(e)},g=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",m)};return o(e)?(e.on("complete",m),e.on("abort",b),e.req?C():e.on("request",C)):h&&!l&&(e.on("end",f),e.on("close",f)),s(e)&&e.on("exit",y),e.on("end",g),e.on("finish",m),!1!==t.error&&e.on("error",v),e.on("close",b),function(){p=!0,e.removeListener("complete",m),e.removeListener("abort",b),e.removeListener("request",C),e.req&&e.req.removeListener("finish",m),e.removeListener("end",f),e.removeListener("close",f),e.removeListener("finish",m),e.removeListener("exit",y),e.removeListener("end",g),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||_,a=Object.keys||k,o=Function.prototype.bind||O;function s(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=r(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}t.exports=s,s.EventEmitter=s,s.prototype._events=void 0,s.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?s.defaultMaxListeners:e._maxListeners}function u(e,t,n){if(t)e.call(n);else for(var r=e.length,a=I(e,r),o=0;o<r;++o)a[o].call(n)}function h(e,t,n,r){if(t)e.call(n,r);else for(var a=e.length,o=I(e,a),s=0;s<a;++s)o[s].call(n,r)}function p(e,t,n,r,a){if(t)e.call(n,r,a);else for(var o=e.length,s=I(e,o),i=0;i<o;++i)s[i].call(n,r,a)}function f(e,t,n,r,a,o){if(t)e.call(n,r,a,o);else for(var s=e.length,i=I(e,s),c=0;c<s;++c)i[c].call(n,r,a,o)}function m(e,t,n,r){if(t)e.apply(n,r);else for(var a=e.length,o=I(e,a),s=0;s<a;++s)o[s].apply(n,r)}function g(e,t,n,a){var o,s,i;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((s=e._events)?(s.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),s=e._events),i=s[t]):(s=e._events=r(null),e._eventsCount=0),i){if("function"==typeof i?i=s[t]=a?[n,i]:[i,n]:a?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=s[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},a=o.call(y,r);return a.listener=n,r.wrapFn=a,a}function b(e,t,n){var r=e._events;if(!r)return[];var a=r[t];return a?"function"==typeof a?n?[a.listener||a]:[a]:n?S(a):I(a,a.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,a=e.length;r<a;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(s,"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}}):s.defaultMaxListeners=c,s.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},s.prototype.getMaxListeners=function(){return d(this)},s.prototype.emit=function(e){var t,n,r,a,o,s,i="error"===e;if(s=this._events)i=i&&null==s.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=s[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(a=new Array(r-1),o=1;o<r;o++)a[o-1]=arguments[o];m(n,l,this,a)}return!0},s.prototype.addListener=function(e,t){return g(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return g(this,e,t,!0)},s.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},s.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},s.prototype.removeListener=function(e,t){var n,a,o,s,i;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(a=this._events))return this;if(!(n=a[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=r(null):(delete a[e],a.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(o=-1,s=n.length-1;s>=0;s--)if(n[s]===t||n[s].listener===t){i=n[s].listener,o=s;break}if(o<0)return this;0===o?n.shift():C(n,o),1===n.length&&(a[e]=n[0]),a.removeListener&&this.emit("removeListener",e,i||t)}return this},s.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 s,i=a(n);for(o=0;o<i.length;++o)"removeListener"!==(s=i[o])&&this.removeAllListeners(s);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},s.prototype.listeners=function(e){return b(this,e,!0)},s.prototype.rawListeners=function(e){return b(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):w.call(e,t)},s.prototype.listenerCount=w,s.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}},{}],23:[function(e,t,n){
1
+ var Amity=function(e,t,n,r,a,o,s,i,c,l,d,u){"use strict";function h(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var p,f,m=h(n),g=h(r),y=h(a),v=h(o),b=h(s),w=h(i),C=h(c),I=h(d),S=h(u);e.MembershipAcceptanceTypeEnum=void 0,(p=e.MembershipAcceptanceTypeEnum||(e.MembershipAcceptanceTypeEnum={})).AUTOMATIC="automatic",p.INVITATION="invitation",e.UserTypeEnum=void 0,(f=e.UserTypeEnum||(e.UserTypeEnum={})).SIGNED_IN="signed-in",f.VISITOR="visitor",f.BOT="bot";const _=Object.freeze({FILE:"file",IMAGE:"image",VIDEO:"video",CLIP:"clip",AUDIO:"audio"}),k=Object.freeze({"1080P":"1080p","720P":"720p","480P":"480p","360P":"360p",ORIGINAL:"original"}),O=Object.freeze({UPLOADED:"uploaded",TRANSCODING:"transcoding",TRANSCODED:"transcoded",TRANSCODE_FAILED:"transcodeFailed"}),T=Object.freeze({LOW:"low",MEDIUM:"medium",HIGH:"high",ORIGINAL:"original"});var E;e.FileAccessTypeEnum=void 0,(E=e.FileAccessTypeEnum||(e.FileAccessTypeEnum={})).PUBLIC="public",E.NETWORK="network";const A=Object.freeze({ONLY_ADMIN_CAN_POST:"ONLY_ADMIN_CAN_POST",ADMIN_REVIEW_POST_REQUIRED:"ADMIN_REVIEW_POST_REQUIRED",ANYONE_CAN_POST:"ANYONE_CAN_POST"}),R=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}}),P="ONLY_ADMIN_CAN_POST",M=Object.freeze({STORY:"story",CLIP:"clip",CHAT:"chat",POST:"post",MESSAGE:"message"});var j;e.ContentFlagReasonEnum=void 0,(j=e.ContentFlagReasonEnum||(e.ContentFlagReasonEnum={})).CommunityGuidelines="Against community guidelines",j.HarassmentOrBullying="Harassment or bullying",j.SelfHarmOrSuicide="Self-harm or suicide",j.ViolenceOrThreateningContent="Violence or threatening content",j.SellingRestrictedItems="Selling and promoting restricted items",j.SexualContentOrNudity="Sexual message or nudity",j.SpamOrScams="Spam or scams",j.FalseInformation="False information or misinformation",j.Others="Others";const U=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",AUDIO:"audio",CUSTOM:"custom"}),x=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",LIVESTREAM:"liveStream",POLL:"poll",CLIP:"clip",AUDIO:"audio",ROOM:"room"}),D=Object.freeze({TEXT:"text",IMAGE:"image",VIDEO:"video",FILE:"file",AUDIO:"audio",MIXED:"mixed"});var q,N,B,L,F,K,$,Q;e.InvitationTypeEnum=void 0,(q=e.InvitationTypeEnum||(e.InvitationTypeEnum={})).CommunityMemberInvite="communityMemberInvite",q.LivestreamInvite="livestreamInvite",e.InvitationStatusEnum=void 0,(N=e.InvitationStatusEnum||(e.InvitationStatusEnum={})).Pending="pending",N.Approved="approved",N.Rejected="rejected",N.Cancelled="cancelled",e.InvitationSortByEnum=void 0,(B=e.InvitationSortByEnum||(e.InvitationSortByEnum={})).FirstCreated="firstCreated",B.LastCreated="lastCreated",e.JoinRequestStatusEnum=void 0,(L=e.JoinRequestStatusEnum||(e.JoinRequestStatusEnum={})).Pending="pending",L.Approved="approved",L.Rejected="rejected",L.Cancelled="cancelled",e.JoinResultStatusEnum=void 0,(F=e.JoinResultStatusEnum||(e.JoinResultStatusEnum={})).Success="success",F.Pending="pending",e.FeedDataTypeEnum=void 0,(K=e.FeedDataTypeEnum||(e.FeedDataTypeEnum={})).Text="text",K.Video="video",K.Image="image",K.File="file",K.Audio="audio",K.LiveStream="liveStream",K.Clip="clip",K.Poll="poll",K.Room="room",e.FeedSortByEnum=void 0,($=e.FeedSortByEnum||(e.FeedSortByEnum={})).LastCreated="lastCreated",$.FirstCreated="firstCreated",$.LastUpdated="lastUpdated",$.FirstUpdated="firstUpdated",e.FeedSourceEnum=void 0,(Q=e.FeedSourceEnum||(e.FeedSourceEnum={})).Community="community",Q.User="user";const z=function(){try{return"v7.11.0-umd"}catch(e){return"__dev__"}}(),V=5,H="cache_then_server",J="For using Live Collection feature you need to enable Cache!",W="Observing unsynced object is not supported by Live Object.",G=-5,Y=1e3,X=6e5,Z="dead",ee=6e4,te=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})),ne=e=>JSON.parse(e),re=(e,t)=>e===t||!(!e||!t)&&("object"==typeof e&&Object.keys(e).every((n=>re(e[n],t[n])))),ae=e=>[400400,400300].includes(e),oe=e=>["skip"].some((t=>t in e)),se=e=>["after","before","first","last","limit"].some((t=>t in e)),ie=e=>"limit"in e,ce=e=>(null==e?void 0:e.hasOwnProperty("data"))&&(null==e?void 0:e.hasOwnProperty("nextPage"))&&(null==e?void 0:e.hasOwnProperty("prevPage")),le=(e,n)=>{var r;if(!e||!Object.keys(e).length)return;let a={};return"skiplimit"===n?a={skip:null!==(r=e.after)&&void 0!==r?r:0,limit:e.limit}:"afterbefore"===n&&se(e)?((null==e?void 0:e.before)&&(a=Object.assign(Object.assign({},a),{before:e.before})),(null==e?void 0:e.after)&&(a=Object.assign(Object.assign({},a),{after:e.after})),Number.isNaN(Number(null==e?void 0:e.limit))||(a=Object.assign(Object.assign({},a),{limit:e.limit}))):"afterbeforeraw"===n&&(a=e),Object.keys(a).length?t.encode(JSON.stringify(a)):void 0},de=e=>{if(!e)return;const n=JSON.parse(t.decode(e));if(oe(n))return{after:n.skip,limit:n.limit};if(se(n)){if("before"in n)return{before:n.before,limit:n.last};if("after"in n)return{after:n.after,limit:n.first}}},ue=e=>"locally"in e,he=e=>"optimistically"in e,pe=e=>ue(e)||he(e),fe=e=>null==e?void 0:e.hasOwnProperty("cachedAt"),me=(e,t=6e4)=>{var n;return Date.now()-(null!==(n=null==e?void 0:e.cachedAt)&&void 0!==n?n:0)<=t},ge=(e,...t)=>({func:e,args:t}),ye=(e,t=6e4)=>"cache_only"===e?{lifeSpan:1/0}:{lifeSpan:t<ee?ee:t},ve=({func:e,args:t},n,r=ye("cache_then_server"))=>{let a;const{lifeSpan:o}=ye("cache_then_server",r.lifeSpan);if(pe(e)){try{a=he(e)?e.optimistically(...t):e.locally(...t)}catch(e){null==n||n(be(void 0,{origin:"local",loading:!1,error:e}))}const r=fe(a)&&me(a,o);if(null==n||n(be(a,{origin:"local",loading:!(ue(e)&&r)})),r)return}else null==n||n(be(void 0,{origin:"local",loading:!0}));e(...t).then((e=>{null==n||n(be(e,{origin:"server",loading:!1}))})).catch((e=>{null==n||n(be(void 0,{origin:"server",loading:!1,error:e}))}))};function be(e,t){return ce(e)||fe(e)?Object.assign(Object.assign({},t),e):Object.assign(Object.assign({},t),{data:e})}const we={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,channelUnread:({channelId: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,notificationTrayItem:({_id:e})=>e,notificationTraySeen:({userId:e})=>e,invitation:({_id:e})=>e,joinRequest:({joinRequestId:e})=>e,room:({roomId:e})=>e},Ce=e=>we[e],Ie={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",videoStreamingChildren:"stream",videoStreamModerations:"streamModeration",follows:"follow",followCounts:"followCount",feeds:"feed",ads:"ad",advertisers:"advertiser",pinTargets:"pinTarget",pins:"pin",notificationTrayItems:"notificationTrayItem",invitations:"invitation",joinRequests:"joinRequest",rooms:"room"};function Se(e=(new Date).toISOString()){return new Date(new Date(e).getTime()+1).toISOString()}class _e 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,_e)}}class ke extends _e{constructor(e,t,n){super(e,t,n)}}class Oe extends _e{constructor(e=8e5,t="fatal"){super("Unexpected error",e,t)}}class Te extends _e{constructor(e,t="SDK client is having connection issues"){super(`${t} (${e})`,"disconnected"===e?800211:800210,"error"),this.event=e}}class Ee extends _e{constructor(e){super(e,800110,"error")}}let Ae=null;const Re=()=>{if(!Ae)throw new _e("There is no active client",8e5,"fatal");return Ae},Pe=e=>{Ae=e},Me=e=>{const{log:t,cache:n}=Re();if(n)return t("cache/api/queryCache",{key:e}),Object.keys(n.data).filter((t=>{const n=ne(t);return re(e,n)})).map((e=>n.data[e]))},je=e=>{const{log:t,cache:n}=Re();if(!n)return;t("cache/api/pullFromCache",e);const r=te(e);return n.data[r]?n.data[r]:void 0},Ue=(e,t,n={cachedAt:Date.now()})=>{const{log:r,cache:a}=Re();if(!a)return!1;r("cache/api/pushToCache",{key:e,data:t,options:n}),!(null==n?void 0:n.hasOwnProperty("offline"))&&a.persistIf&&(n.offline=a.persistIf(e,t));const o=te(e);return a.data[o]=Object.assign({key:e,data:t},n),!0},xe=(e,t,n)=>{const{log:r,cache:a}=Re();if(!a)return!1;r("cache/api/mergeInCache",{key:e,mutation:t});const o=je(e);if(!o)return!1;const s="function"==typeof t?t(o.data):Object.assign(Object.assign({},o.data),t);return i=o.data,!("updatedAt"in(c=s)&&"updatedAt"in i&&new Date(c.updatedAt)<new Date(i.updatedAt))&&(Ue(e,s,n),!0);var i,c},De=(e,t,n={cachedAt:Date.now()})=>{const{log:r,cache:a}=Re();if(!a)return!1;r("cache/api/upsertInCache",{key:e,data:t,options:n});return je(e)?xe(e,t,n):Ue(e,t,n)},qe=(e,t=!1)=>{const{log:n,cache:r}=Re();if(!r)return!1;if(n("cache/api/dropFromCache",{key:e,exact:t}),!t)return Object.keys(r.data).map((e=>ne(e))).filter((t=>re(e,t))).map((e=>qe(e,!0))).every((e=>e));const a=te(e);return a in r.data&&(delete r.data[a],!0)},Ne=(e,t,n)=>void 0!==n?e.filter((e=>JSON.stringify(e[t])===JSON.stringify(n))):e,Be=(e,t,n)=>void 0!==n?e.filter((e=>"string"==typeof e[t]&&"string"==typeof n&&String(e[t]).toLowerCase().match(n.toLowerCase()))):e,Le=(e,t,n)=>(null==n?void 0:n.length)?e.filter((e=>Array.isArray(e[t])&&n.some((n=>e[t].includes(n))))):e,Fe=(e,t,n)=>"all"===t?e:e.filter((e=>{var r;if("community"===e.type)return!0;const a=Ce("channelUsers")({channelId:e.channelPublicId,userId:n}),o=null===(r=je(["channelUsers","get",a]))||void 0===r?void 0:r.data;return"member"===t?o&&"none"!==o.membership:!o||"none"===o.membership})),Ke=(e,t)=>e.filter((({targetId:e,feedId:n})=>{var r;const a=null===(r=je(["feed","get",Ce("feed")({targetId:e,feedId:n})]))||void 0===r?void 0:r.data;return a&&a.feedType===t})),$e=(e,t,n)=>"all"===t?e:e.filter((e=>{var r;const a=Ce("communityUsers")({communityId:e.communityId,userId:n}),o=null===(r=je(["communityUsers","get",a]))||void 0===r?void 0:r.data;return"member"===t?o&&"member"===o.communityMembership:!o||"none"!==o.communityMembership})),Qe=(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 a=null===(r=je(["post","get",n.children[0]]))||void 0===r?void 0:r.data;return(null==t?void 0:t.includes(null==a?void 0:a.dataType))?e:[...e,n]}return e}),[]),ze=(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))}))},Ve=({displayName:e},{displayName:t})=>e&&t?e.localeCompare(t):e?-1:1,He=({name:e},{name:t})=>e&&t?e.localeCompare(t):e?-1:1,Je=({createdAt:e},{createdAt:t})=>new Date(e).valueOf()-new Date(t).valueOf(),We=({localSortingDate:e},{localSortingDate:t})=>new Date(t).getTime()-new Date(e).getTime(),Ge=({createdAt:e},{createdAt:t})=>new Date(t).valueOf()-new Date(e).valueOf(),Ye=({updatedAt:e=0},{updatedAt:t=0})=>new Date(e).valueOf()-new Date(t).valueOf(),Xe=({updatedAt:e=0},{updatedAt:t=0})=>new Date(t).valueOf()-new Date(e).valueOf(),Ze=({lastActivity:e},{lastActivity:t})=>new Date(t).valueOf()-new Date(e).valueOf();let et=null;const tt=()=>{if(!et)throw new _e("Connect client first",8e5,"fatal");return et},nt=e=>{et={_id:e._id,userId:e.userId,path:e.path}};let rt,at=[];const ot=e=>{clearTimeout(rt),at.push(e),rt=setTimeout((()=>{at.forEach((e=>e())),at=[]}),0)},st=["connect","message","disconnect","error","close","end","reconnect","video-streaming.didStart","video-streaming.didRecord","video-streaming.didStop","video-streaming.didFlag","video-streaming.didTerminate","video-streaming.viewerDidBan","video-streaming.viewerDidUnban","liveReaction.created"],it=(e,t,n,r)=>{const{log:a,emitter:o}=e,s=Date.now();a(`${t}(tmpid: ${s}) > listen`);const i=(...e)=>{a(`${t}(tmpid: ${s}) > trigger`,e);try{r(...e)}catch(e){a(`${t}(tmpid: ${s}) > error`,e)}};return o.on(n,i),()=>{a(`${t}(tmpid: ${s}) > dispose`),o.off(n,i)}},ct=(e,t)=>{const{emitter:n}=Re();ot((()=>{n.emit(e,t)}))};let lt,dt;async function ut(){var e;const{mqtt:t,emitter:n,token:r}=Re();if(!t)return;const a=null!==(e=null==r?void 0:r.accessToken)&&void 0!==e?e:"",o=tt();lt===a&&dt===o._id||(lt=a,dt=o._id,await t.connect({accessToken:lt,userId:dt}),((e,t)=>{st.forEach((n=>{null==e||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 ht;e.SubscriptionLevels=void 0,(ht=e.SubscriptionLevels||(e.SubscriptionLevels={})).COMMUNITY="community",ht.POST="post",ht.COMMENT="comment",ht.POST_AND_COMMENT="post_and_comment",ht.USER="user";const pt=(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}},ft=e=>e.path.split("/user/")[0],mt=({path:t},n=e.SubscriptionLevels.USER)=>pt(n===e.SubscriptionLevels.USER?t:t.replace(/^(\w*)/,"$1/social"),n),gt=({channelId:e,subChannelId:t})=>{const n=tt();return`${ft(n)}/marker/channel/${e}/message/${t}`},yt=()=>{const e=tt();return`${ft(e)}/marker/user/${e._id}`},vt=()=>ft(tt()),bt=()=>{const e=tt();return`${ft(e)}/smartfeed/${e._id}/channels`},wt=()=>{const e=tt();return`${ft(e)}/smartfeed/${e._id}/messagefeeds`},Ct=()=>{const e=tt();return`${ft(e)}/smartfeed/${e._id}/messages`},It=()=>{const e=tt();return`${ft(e)}/videostreaming`};function St(e,t){const{mqtt:n}=Re();return n?(ut(),n.subscribe(e,t)):()=>null}var _t;const kt="object"==typeof globalThis?globalThis:"object"==typeof global?global:window,{process:Ot={}}=kt,Tt="production"===(null===(_t=Ot.env)||void 0===_t?void 0:_t.NODE_ENV),Et={EU:"eu",SG:"sg",US:"us"},At={http:"https://apix.{region}.amity.co",upload:"https://upload.{region}.amity.co",mqtt:"wss://sse.{region}.amity.co:443/mqtt"};function Rt(e,t){return At[e].replace("{region}",t)}class Pt{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 Mt;var jt,Ut=()=>(Mt||(Mt=new Pt),Mt);!function(e){e.UserDeleted="User Deleted",e.UserGlobalBanned="User Global Banned",e.TokenExpired="Token Expired"}(jt||(jt={}));const xt=new AbortController,Dt=e=>{switch(e){case jt.UserGlobalBanned:throw new _e(e,400312,"fatal");case jt.UserDeleted:throw new _e(e,400100,"fatal");case jt.TokenExpired:throw ct("tokenExpired","tokenExpired"),new _e(e,800403,"fatal");default:throw new _e("Request Aborted",8e5,"error")}},qt=e=>{const t={maxSockets:100,maxFreeSockets:10,timeout:6e4,freeSocketTimeout:3e4},n=y.default.create({baseURL:e,httpAgent:new v.default(t),httpsAgent:new o.HttpsAgent(t),signal:xt.signal});return n.defaults.withCredentials=!1,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&&(xt.abort(),Dt(jt.UserGlobalBanned)),r&&(xt.abort(),Dt(jt.UserDeleted))}return e})),n.interceptors.response.use((e=>{var t;const n=new Headers;Object.entries(e.headers).forEach((([e,t])=>{"string"==typeof t&&n.append(e,t)}));const r=(e.config.baseURL||"")+(e.config.url||""),a=null===(t=e.config.method)||void 0===t?void 0:t.toUpperCase(),o={method:a,headers:e.config.headers};return"GET"!==a&&"HEAD"!==a&&(o.body=e.config.data),Ut().setNetworkActivities(new Request(r,o),{data:e.data,status:e.status,statusText:e.statusText,headers:n}),e}),(e=>{var t,n;const{response:r}=e;if(400100===(null==r?void 0:r.data.code)&&ct("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 Oe(e.code);if("error"===e.status)throw new ke(e.message,e.code,"error")})(null==r?void 0:r.data),xt.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 Nt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Bt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Lt(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 Ft={exports:{}};Ft.exports=function(){function e(t,n,r){function a(s,i){if(!n[s]){if(!t[s]){if(!i&&Lt)return Lt(s);if(o)return o(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[s]={exports:{}};t[s][0].call(l.exports,(function(e){return a(t[s][1][e]||e)}),l,l.exports,e,t,n,r)}return n[s].exports}for(var o=Lt,s=0;s<r.length;s++)a(r[s]);return a}return e}()({1:[function(e,t,n){(function(n,r){(function(){const a=e("events").EventEmitter,o=e("./store"),s=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"),m=e("xtend"),g=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&&(g("applyTopicAlias :: register topic: %s - alias: %d",r,n),!e.topicAliasSend.put(r,n)))return g("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},g("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},g("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},g("applyTopicAlias :: auto use topic: %s - alias: %d",r,n))));else if(n)return g("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){g("sendPacket :: packet: %O",t),g("sendPacket :: emitting `packetsend`"),e.emit("packetsend",t),g("sendPacket :: writing to stream");const r=c.writeToStream(t,e.stream,e.options);g("sendPacket :: writeToStream result %s",r),!r&&n&&n!==A?(g("sendPacket :: handle events on `drain` once through callback."),e.stream.once("drain",n)):n&&(g("sendPacket :: invoking cb"),n())}function O(e){e&&(g("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&&(g("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){g("storeAndSend :: store packet with cmd %s to outgoingStore",t.cmd);let a,o=t;if("publish"===o.cmd&&(o=p(t),a=_(e,o),a))return n&&n(a);e.outgoingStore.put(o,(function(a){if(a)return n&&n(a);r(),k(e,t,n)}))}function A(e){g("nop ::",e)}function R(e,t){let n;const r=this;if(!(this instanceof R))return new R(e,t);for(n in this.options=t||{},b)void 0===this.options[n]?this.options[n]=b[n]:this.options[n]=t[n];g("MqttClient :: options.protocol",t.protocol),g("MqttClient :: options.protocolVersion",t.protocolVersion),g("MqttClient :: options.username",t.username),g("MqttClient :: options.keepalive",t.keepalive),g("MqttClient :: options.reconnectPeriod",t.reconnectPeriod),g("MqttClient :: options.rejectUnauthorized",t.rejectUnauthorized),g("MqttClient :: options.topicAliasMaximum",t.topicAliasMaximum),this.options.clientId="string"==typeof t.clientId?t.clientId:I(),g("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?g("MqttClient :: options.topicAliasMaximum is out of range"):this.topicAliasRecv=new s(t.topicAliasMaximum)),this.on("connect",(function(){const e=this.queue;function t(){const n=e.shift();g("deliver :: entry %o",n);let a=null;if(!n)return void r._resubscribe();a=n.packet,g("deliver :: call _sendPacket for %o",a);let o=!0;a.messageId&&0!==a.messageId&&(r.messageIdProvider.register(a.messageId)||(o=!1)),o?r._sendPacket(a,(function(e){n.cb&&n.cb(e),t()})):(g("messageId: %d has already used. The message is skipped and removed.",a.messageId),t())}g("connect :: sending queued packets"),t()})),this.on("close",(function(){g("close :: connected set to `false`"),this.connected=!1,g("close :: clearing connackTimer"),clearTimeout(this.connackTimer),g("close :: clearing ping timer"),null!==r.pingTimer&&(r.pingTimer.clear(),r.pingTimer=null),this.topicAliasRecv&&this.topicAliasRecv.clear(),g("close :: calling _setupReconnect"),this._setupReconnect()})),a.call(this),g("MqttClient :: setting up stream"),this._setupStream()}u(R,a),R.prototype._setupStream=function(){const e=this,t=new d,n=c.parser(this.options);let r=null;const a=[];function o(){if(a.length)y(s);else{const e=r;r=null,e()}}function s(){g("work :: getting next packet in queue");const t=a.shift();if(t)g("work :: packet pulled from queue"),e._handlePacket(t,o);else{g("work :: no packets in queue");const e=r;r=null,g("work :: done flag is %s",!!e),e&&e()}}function i(t){g("streamErrorHandler :: error",t.message),w.includes(t.code)?(g("streamErrorHandler :: emitting error"),e.emit("error",t)):A(t)}g("_setupStream :: calling method to clear reconnect"),this._clearReconnect(),g("_setupStream :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),n.on("packet",(function(e){g("parser :: on packet push to packets array."),a.push(e)})),t._write=function(e,t,a){r=a,g("writable stream :: parsing buffer"),n.parse(e),s()},g("_setupStream :: pipe stream to writable stream"),this.stream.pipe(t),this.stream.on("error",i),this.stream.on("close",(function(){g("(%s)stream :: on close",e.options.clientId),T(e.outgoing),g("stream: emit close to MqttClient"),e.emit("close")})),g("_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,m({cmd:"auth",reasonCode:0},this.options.authPacket))}this.stream.setMaxListeners(1e3),clearTimeout(this.connackTimer),this.connackTimer=setTimeout((function(){g("!!connectTimeout hit!! Calling _cleanUp with force `true`"),e._cleanUp(!0)}),this.options.connectTimeout)},R.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(g("_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()}},R.prototype._checkDisconnecting=function(e){return this.disconnecting&&(e&&e!==A?e(new Error("client disconnecting")):this.emit("error",new Error("client disconnecting"))),this.disconnecting},R.prototype.publish=function(e,t,n,r){g("publish :: message `%s` to topic `%s`",t,e);const a=this.options;if("function"==typeof n&&(r=n,n=null),n=m({qos:0,retain:!1,dup:!1},n),this._checkDisconnecting(r))return this;const o=this,s=function(){let s=0;if((1===n.qos||2===n.qos)&&(s=o._nextId(),null===s))return g("No messageId left"),!1;const i={cmd:"publish",topic:e,payload:t,qos:n.qos,retain:n.retain,messageId:s,dup:n.dup};switch(5===a.protocolVersion&&(i.properties=n.properties),g("publish :: qos",n.qos),n.qos){case 1:case 2:o.outgoing[i.messageId]={volatile:!1,cb:r||A},g("MqttClient:publish: packet cmd: %s",i.cmd),o._sendPacket(i,void 0,n.cbStorePut);break;default:g("MqttClient:publish: packet cmd: %s",i.cmd),o._sendPacket(i,r,n.cbStorePut)}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!s())&&this._storeProcessingQueue.push({invoke:s,cbStorePut:n.cbStorePut,callback:r}),this},R.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 a=r.resubscribe;let o=t.pop()||A,s=t.pop();const i=this.options.protocolVersion;delete r.resubscribe,"string"==typeof r&&(r=[r]),"function"!=typeof o&&(s=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 g("subscribe: discconecting true"),this;const l={qos:0};if(5===i&&(l.nl=!1,l.rap=!1,l.rh=0),s=m(l,s),Array.isArray(r)?r.forEach((function(t){if(g("subscribe: array topic %s",t),!Object.prototype.hasOwnProperty.call(e._resubscribeTopics,t)||e._resubscribeTopics[t].qos<s.qos||a){const e={topic:t,qos:s.qos};5===i&&(e.nl=s.nl,e.rap=s.rap,e.rh=s.rh,e.properties=s.properties),g("subscribe: pushing topic `%s` and qos `%s` to subs list",e.topic,e.qos),n.push(e)}})):Object.keys(r).forEach((function(t){if(g("subscribe: object topic %s",t),!Object.prototype.hasOwnProperty.call(e._resubscribeTopics,t)||e._resubscribeTopics[t].qos<r[t].qos||a){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=s.properties),g("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 g("No messageId left"),!1;const r={cmd:"subscribe",subscriptions:n,qos:1,retain:!1,dup:!1,messageId:t};if(s.properties&&(r.properties=s.properties),e.options.resubscribe){g("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)}},g("subscribe :: call _sendPacket"),e._sendPacket(r),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!d())&&this._storeProcessingQueue.push({invoke:d,callback:o}),this},R.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,a=t.pop();"string"==typeof n&&(n=[n]),"function"!=typeof r&&(a=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 s=function(){const t=e._nextId();if(null===t)return g("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 a&&a.properties&&(o.properties=a.properties),e.outgoing[o.messageId]={volatile:!0,cb:r},g("unsubscribe: call _sendPacket"),e._sendPacket(o),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!s())&&this._storeProcessingQueue.push({invoke:s,callback:r}),this},R.prototype.end=function(e,t,n){const r=this;function a(){g("end :: closeStores: closing incoming and outgoing stores"),r.disconnected=!0,r.incomingStore.close((function(e){r.outgoingStore.close((function(t){if(g("end :: closeStores: emitting end"),r.emit("end"),n){const r=e||t;g("end :: closeStores: invoking callback with args"),n(r)}}))})),r._deferredReconnect&&r._deferredReconnect()}function o(){g("end :: (%s) :: finish :: calling _cleanUp with force %s",r.options.clientId,e),r._cleanUp(e,(()=>{g("end :: finish :: calling process.nextTick on closeStores"),y(a.bind(r))}),t)}return g("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),g("end :: cb? %s",!!n),n=n||A,this.disconnecting?(n(),this):(this._clearReconnect(),this.disconnecting=!0,!e&&Object.keys(this.outgoing).length>0?(g("end :: (%s) :: calling finish in 10ms once outgoing is empty",r.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,o,10))):(g("end :: (%s) :: immediately calling finish",r.options.clientId),o()),this)},R.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},R.prototype.reconnect=function(e){g("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},R.prototype._reconnect=function(){g("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected?(this.end((()=>{this._setupStream()})),g("client already connected. disconnecting first.")):(g("_reconnect: calling _setupStream"),this._setupStream())},R.prototype._setupReconnect=function(){const e=this;!e.disconnecting&&!e.reconnectTimer&&e.options.reconnectPeriod>0?(this.reconnecting||(g("_setupReconnect :: emit `offline` state"),this.emit("offline"),g("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0),g("_setupReconnect :: setting reconnectTimer for %d ms",e.options.reconnectPeriod),e.reconnectTimer=setInterval((function(){g("reconnectTimer :: reconnect triggered!"),e._reconnect()}),e.options.reconnectPeriod)):g("_setupReconnect :: doing nothing...")},R.prototype._clearReconnect=function(){g("_clearReconnect : clearing reconnect timer"),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null)},R.prototype._cleanUp=function(e,t){const n=arguments[2];if(t&&(g("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",t)),g("_cleanUp :: forced? %s",e),e)0===this.options.reconnectPeriod&&this.options.clean&&O(this.outgoing),g("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{const e=m({cmd:"disconnect"},n);g("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(e,v.bind(null,this.stream.end.bind(this.stream)))}this.disconnecting||(g("_cleanUp :: client not disconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect()),null!==this.pingTimer&&(g("_cleanUp :: clearing pingTimer"),this.pingTimer.clear(),this.pingTimer=null),t&&!this.connected&&(g("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",t),t())},R.prototype._sendPacket=function(e,t,n){g("_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)):(g("_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)}g("_sendPacket :: (%s) :: end",this.options.clientId)}},R.prototype._storePacket=function(e,t,n){g("_storePacket :: packet: %o",e),g("_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"))},R.prototype._setupPingTimer=function(){g("_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))},R.prototype._shiftPingInterval=function(){this.pingTimer&&this.options.keepalive&&this.options.reschedulePings&&this.pingTimer.reschedule(1e3*this.options.keepalive)},R.prototype._checkPing=function(){g("_checkPing :: checking ping..."),this.pingResp?(g("_checkPing :: ping response received. Clearing flag and sending `pingreq`"),this.pingResp=!1,this._sendPacket({cmd:"pingreq"})):(g("_checkPing :: calling _cleanUp with force true"),this._cleanUp(!0))},R.prototype._handlePingresp=function(){this.pingResp=!0},R.prototype._handleConnack=function(e){g("_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)}},R.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)}}))},R.prototype.handleAuth=function(e,t){t()},R.prototype._handlePublish=function(e,t){g("_handlePublish: packet %o",e),t=void 0!==t?t:A;let n=e.topic.toString();const r=e.payload,a=e.qos,o=e.messageId,s=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 g("_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 g("_handlePublish :: unregistered topic alias. alias: %d",t),void this.emit("error",new Error("Received unregistered Topic Alias"));n=e,g("_handlePublish :: topic complemented by alias. topic: %s - alias: %d",n,t)}}else{if(!this.topicAliasRecv.put(n,t))return g("_handlePublish :: topic alias out of range. alias: %d",t),void this.emit("error",new Error("Received Topic Alias is out of range"));g("_handlePublish :: registered topic: %s - alias: %d",n,t)}}switch(g("_handlePublish: qos %d",a),a){case 2:i.customHandleAcks(n,r,e,(function(n,r){return n instanceof Error||(r=n,n=null),n?s.emit("error",n):-1===c.indexOf(r)?s.emit("error",new Error("Wrong reason code for pubrec")):void(r?s._sendPacket({cmd:"pubrec",messageId:o,reasonCode:r},t):s.incomingStore.put(e,(function(){s._sendPacket({cmd:"pubrec",messageId:o},t)})))}));break;case 1:i.customHandleAcks(n,r,e,(function(a,i){return a instanceof Error||(i=a,a=null),a?s.emit("error",a):-1===c.indexOf(i)?s.emit("error",new Error("Wrong reason code for puback")):(i||s.emit("message",n,r,e),void s.handleMessage(e,(function(e){if(e)return t&&t(e);s._sendPacket({cmd:"puback",messageId:o,reasonCode:i},t)})))}));break;case 0:this.emit("message",n,r,e),this.handleMessage(e,t);break;default:g("_handlePublish: unknown QoS. Doing nothing.")}},R.prototype.handleMessage=function(e,t){t()},R.prototype._handleAck=function(e){const t=e.messageId,n=e.cmd;let r=null;const a=this.outgoing[t]?this.outgoing[t].cb:null,o=this;let s;if(a){switch(g("_handleAck :: packet type",n),n){case"pubcomp":case"puback":{const n=e.reasonCode;n&&n>0&&16!==n&&(s=new Error("Publish error: "+C[n]),s.code=n,a(s,e)),delete this.outgoing[t],this.outgoingStore.del(e,a),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?(s=new Error("Publish error: "+C[n]),s.code=n,a(s,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(),a(null,e);break;case"unsuback":delete this.outgoing[t],this.messageIdProvider.deallocate(t),this._invokeStoreProcessingQueue(),a(null);break;default:o.emit("error",new Error("unrecognized packet type"))}this.disconnecting&&0===Object.keys(this.outgoing).length&&this.emit("outgoingEmpty")}else g("_handleAck :: Server sent an ack in error. Ignoring.")},R.prototype._handlePubrel=function(e,t){g("handling pubrel packet"),t=void 0!==t?t:A;const n=e.messageId,r=this,a={cmd:"pubcomp",messageId:n};r.incomingStore.get(e,(function(e,n){e?r._sendPacket(a,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(a,t)})))}))},R.prototype._handleDisconnect=function(e){this.emit("disconnect",e)},R.prototype._nextId=function(){return this.messageIdProvider.allocate()},R.prototype.getLastMessageId=function(){return this.messageIdProvider.getLastAllocated()},R.prototype._resubscribe=function(){g("_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){g("_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},R.prototype._onConnect=function(e){if(this.disconnected)return void this.emit("connect",e);const t=this;function n(){let r=t.outgoingStore.createStream();function a(){t._storeProcessing=!1,t._packetIdsDuringStoreProcessing={}}function o(){r.destroy(),r=null,t._flushStoreProcessingQueue(),a()}function s(){if(!r)return;t._storeProcessing=!0;const e=r.read(1);let n;e?t._packetIdsDuringStoreProcessing[e.messageId]?s():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),s()}},t._packetIdsDuringStoreProcessing[e.messageId]=!0,t.messageIdProvider.register(e.messageId)?t._sendPacket(e):g("messageId: %d has already used.",e.messageId)):r.once("readable",s)}t.once("close",o),r.on("error",(function(e){a(),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?(a(),t.removeListener("close",o),t._invokeAllStoreProcessingQueue(),t.emit("connect",e)):n()})),s()}this.connackPacket=e,this.messageIdProvider.clear(),this._setupPingTimer(),this.connected=!0,n()},R.prototype._invokeStoreProcessingQueue=function(){if(this._storeProcessingQueue.length>0){const e=this._storeProcessingQueue[0];if(e&&e.invoke())return this._storeProcessingQueue.shift(),!0}return!1},R.prototype._invokeAllStoreProcessingQueue=function(){for(;this._invokeStoreProcessingQueue(););},R.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=R}).call(this)}).call(this,e("_process"),void 0!==Nt?Nt:"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"),a=e("readable-stream").Transform,o=e("duplexify");let s,i,c,l=!1;function d(){const e=new a;return e._write=function(e,t,n){s.sendSocketMessage({data:e.buffer,success:function(){n()},fail:function(){n(new Error)}})},e._flush=function(e){s.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,s.onSocketOpen((function(){c.setReadable(i),c.setWritable(i),c.emit("connect")})),s.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)}})),s.onSocketClose((function(){c.end(),c.destroy()})),s.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 s=t.my,s.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"),a=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 a("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"),a=e("net"),o=e("debug")("mqttjs:tls");function s(e,t){t.port=t.port||8883,t.host=t.hostname||t.host||"localhost",0===a.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 s(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",s)})),n.on("error",s),n}t.exports=s},{debug:18,net:16,tls:16}],5:[function(e,t,n){(function(n){(function(){const{Buffer:r}=e("buffer"),a=e("ws"),o=e("debug")("mqttjs:ws"),s=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 a(t,[r],n.wsOptions)}function f(e,t){const n="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt",r=d(t,e),a=new WebSocket(r,[n]);return a.binaryType="arraybuffer",a}function m(e,t){o("streamBuilder");const n=u(t),r=d(n,e),s=p(e,r,n),i=a.createWebSocketStream(s,n.wsOptions);return i.url=r,s.on("close",(()=>{i.destroy()})),i}function g(e,t){let n;o("browserStreamBuilder");const a=h(t).browserBufferSize||524288,c=t.browserBufferTimeout||1e3,l=!t.objectMode,d=f(e,t),u=m(t,C,I);t.objectMode||(u._writev=w),u.on("close",(()=>{d.close()}));const p=void 0!==d.addEventListener;function m(e,t,n){const r=new i({objectModeMode:e.objectMode});return r._write=t,r._flush=n,r}function g(){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>a&&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=s(void 0,void 0,t),t.objectMode||(n._writev=w),p?d.addEventListener("open",g):d.onopen=g),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?g:m}).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"),a=e("readable-stream").Transform,o=e("duplexify");let s,i,c;function l(){const e=new a;return e._write=function(e,t,n){s.send({data:e.buffer,success:function(){n()},fail:function(e){n(new Error(e))}})},e._flush=function(e){s.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(){s.onOpen((function(){c.setReadable(i),c.setWritable(i),c.emit("connect")})),s.onMessage((function(e){let t=e.data;t=t instanceof ArrayBuffer?r.from(t):r.from(t,"utf8"),i.push(t)})),s.onClose((function(){c.end(),c.destroy()})),s.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);s=wx.connectSocket({url:r,protocols:[n]}),i=l(),c=o.obj(),c._destroy=function(e,t){s.close({success:function(){t&&t(e)}})};const a=c.destroy;return c.destroy=function(){c.destroy=a;const e=this;setTimeout((function(){s.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"),a=e("readable-stream").Readable,o={objectMode:!0},s={clean:!0};function i(e){if(!(this instanceof i))return new i(e);this.options=e||{},this.options=r(s,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 a(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"),a=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 a(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 a(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:a}},{}],12:[function(e,t,n){(function(n){(function(){const r=e("../client"),a=e("../store"),o=e("url"),s=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=s(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 a=new r(n,t);return a.on("error",(function(){})),a}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=a}).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=m;for(var r=[],a=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,c=s.length;i<c;++i)r[i]=s[i],a[s.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),s=r[0],i=r[1],c=new o(u(e,s,i)),d=0,h=i>0?s-4:s;for(n=0;n<h;n+=4)t=a[e.charCodeAt(n)]<<18|a[e.charCodeAt(n+1)]<<12|a[e.charCodeAt(n+2)]<<6|a[e.charCodeAt(n+3)],c[d++]=t>>16&255,c[d++]=t>>8&255,c[d++]=255&t;return 2===i&&(t=a[e.charCodeAt(n)]<<2|a[e.charCodeAt(n+1)]>>4,c[d++]=255&t),1===i&&(t=a[e.charCodeAt(n)]<<10|a[e.charCodeAt(n+1)]<<4|a[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,a=[],o=t;o<n;o+=3)r=(e[o]<<16&16711680)+(e[o+1]<<8&65280)+(255&e[o+2]),a.push(p(r));return a.join("")}function m(e){for(var t,n=e.length,a=n%3,o=[],s=16383,i=0,c=n-a;i<c;i+=s)o.push(f(e,i,i+s>c?c:i+s));return 1===a?(t=e[n-1],o.push(r[t>>2]+r[t<<4&63]+"==")):2===a&&(t=(e[n-2]<<8)+e[n-1],o.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"=")),o.join("")}a["-".charCodeAt(0)]=62,a["_".charCodeAt(0)]=63},{}],14:[function(e,t,n){const{Buffer:r}=e("buffer"),a=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,a,{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,a){if(("number"!=typeof n||n<0)&&(n=0),("number"!=typeof a||a>this.length)&&(a=this.length),n>=this.length)return e||r.alloc(0);if(a<=0)return e||r.alloc(0);const o=!!e,s=this._offset(n),i=a-n;let c=i,l=o&&t||0,d=s[1];if(0===n&&a===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[s[0]].length-d)return o?this._bufs[s[0]].copy(e,t,d,d+c):this._bufs[s[0]].slice(d,d+c);o||(e=r.allocUnsafe(i));for(let t=s[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),a=this._bufs.slice(n[0],r[0]+1);return 0===r[1]?a.pop():a[a.length-1]=a[a.length-1].slice(0,r[1]),0!==n[1]&&(a[0]=a[0].slice(n[1])),this._new(a)},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 a=this._offset(t);let o=a[0],s=a[1];for(;o<this._bufs.length;o++){const t=this._bufs[o];for(;s<t.length;)if(t.length-s>=e.length){const n=t.indexOf(e,s);if(-1!==n)return this._reverseOffset([o,n]);s=t.length-e.length+1}else{const t=this._reverseOffset([o,s]);if(this._match(t,e))return t;s++}s=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[a]},t.exports=o},{buffer:17}],15:[function(e,t,n){const r=e("readable-stream").Duplex,a=e("inherits"),o=e("./BufferList");function s(e){if(!(this instanceof s))return new s(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)}a(s,r),Object.assign(s.prototype,o.prototype),s.prototype._new=function(e){return new s(e)},s.prototype._write=function(e,t,n){this._appendBuffer(e),"function"==typeof n&&n()},s.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)},s.prototype.end=function(e){r.prototype.end.call(this,e),this._callback&&(this._callback(null,this.slice()),this._callback=null)},s.prototype._destroy=function(e,t){this._bufs.length=0,this.length=0,t(e)},s.prototype._isBufferList=function(e){return e instanceof s||e instanceof o||s.isBufferList(e)},s.isBufferList=o.isBufferList,t.exports=s,t.exports.BufferListStream=s,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 a=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 s(e){if(e>a)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 a=m(e);if(a)return a;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?s(e):void 0!==t?"string"==typeof n?s(e).fill(t,n):s(e).fill(t):s(e)}function u(e){return l(e),s(e<0?0:0|g(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=s(n),a=r.write(e,t);return a!==n&&(r=r.slice(0,a)),r}function p(e){for(var t=e.length<0?0:0|g(e.length),n=s(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 m(e){if(i.isBuffer(e)){var t=0|g(e.length),n=s(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0!==e.length?"number"!=typeof e.length||Y(e.length)?s(0):p(e):"Buffer"===e.type&&Array.isArray(e.data)?p(e.data):void 0}function g(e){if(e>=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.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 a=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return z(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return J(e).length;default:if(a)return r?-1:z(e).length;t=(""+t).toLowerCase(),a=!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 R(this,t,n);case"ascii":return j(this,t,n);case"latin1":case"binary":return U(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,a){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=a?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(a)return-1;n=e.length-1}else if(n<0){if(!a)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,a);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):I(e,[t],n,r,a);throw new TypeError("val must be string, number or Buffer")}function I(e,t,n,r,a){var o,s=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;s=2,i/=2,c/=2,n/=2}function l(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(a){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*s}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 a=e.length-n;r?(r=Number(r))>a&&(r=a):r=a;var o=t.length;r>o/2&&(r=o/2);for(var s=0;s<r;++s){var i=parseInt(t.substr(2*s,2),16);if(Y(i))return s;e[n+s]=i}return s}function _(e,t,n,r){return W(z(t,e.length-n),e,n,r)}function k(e,t,n,r){return W(V(t),e,n,r)}function O(e,t,n,r){return k(e,t,n,r)}function T(e,t,n,r){return W(J(t),e,n,r)}function E(e,t,n,r){return W(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 R(e,t,n){n=Math.min(e.length,n);for(var r=[],a=t;a<n;){var o,s,i,c,l=e[a],d=null,u=l>239?4:l>223?3:l>191?2:1;if(a+u<=n)switch(u){case 1:l<128&&(d=l);break;case 2:128==(192&(o=e[a+1]))&&(c=(31&l)<<6|63&o)>127&&(d=c);break;case 3:o=e[a+1],s=e[a+2],128==(192&o)&&128==(192&s)&&(c=(15&l)<<12|(63&o)<<6|63&s)>2047&&(c<55296||c>57343)&&(d=c);break;case 4:o=e[a+1],s=e[a+2],i=e[a+3],128==(192&o)&&128==(192&s)&&128==(192&i)&&(c=(15&l)<<18|(63&o)<<12|(63&s)<<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),a+=u}return M(r)}n.kMaxLength=a,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,a=0,o=Math.min(n,r);a<o;++a)if(e[a]!==t[a]){n=e[a],r=t[a];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),a=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,a),a+=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?R(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,a){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===a&&(a=this.length),t<0||n>e.length||r<0||a>this.length)throw new RangeError("out of range index");if(r>=a&&t>=n)return 0;if(r>=a)return-1;if(t>=n)return 1;if(this===e)return 0;for(var o=(a>>>=0)-(r>>>=0),s=(n>>>=0)-(t>>>=0),c=Math.min(o,s),l=this.slice(r,a),d=e.slice(t,n),u=0;u<c;++u)if(l[u]!==d[u]){o=l[u],s=d[u];break}return o<s?-1:s<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 a=this.length-t;if((void 0===n||n>a)&&(n=a),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 M(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 j(e,t,n){var r="";n=Math.min(e.length,n);for(var a=t;a<n;++a)r+=String.fromCharCode(127&e[a]);return r}function U(e,t,n){var r="";n=Math.min(e.length,n);for(var a=t;a<n;++a)r+=String.fromCharCode(e[a]);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 a="",o=t;o<n;++o)a+=Q(e[o]);return a}function D(e,t,n){for(var r=e.slice(t,n),a="",o=0;o<r.length;o+=2)a+=String.fromCharCode(r[o]+256*r[o+1]);return a}function q(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 N(e,t,n,r,a,o){if(!i.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>a||t<o)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function B(e,t,n,r,a,o){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function L(e,t,n,a,o){return t=+t,n>>>=0,o||B(e,t,n,4),r.write(e,t,n,a,23,4),n+4}function F(e,t,n,a,o){return t=+t,n>>>=0,o||B(e,t,n,8),r.write(e,t,n,a,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||q(e,t,this.length);for(var r=this[e],a=1,o=0;++o<t&&(a*=256);)r+=this[e+o]*a;return r},i.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||q(e,t,this.length);for(var r=this[e+--t],a=1;t>0&&(a*=256);)r+=this[e+--t]*a;return r},i.prototype.readUInt8=function(e,t){return e>>>=0,t||q(e,1,this.length),this[e]},i.prototype.readUInt16LE=function(e,t){return e>>>=0,t||q(e,2,this.length),this[e]|this[e+1]<<8},i.prototype.readUInt16BE=function(e,t){return e>>>=0,t||q(e,2,this.length),this[e]<<8|this[e+1]},i.prototype.readUInt32LE=function(e,t){return e>>>=0,t||q(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||q(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||q(e,t,this.length);for(var r=this[e],a=1,o=0;++o<t&&(a*=256);)r+=this[e+o]*a;return r>=(a*=128)&&(r-=Math.pow(2,8*t)),r},i.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||q(e,t,this.length);for(var r=t,a=1,o=this[e+--r];r>0&&(a*=256);)o+=this[e+--r]*a;return o>=(a*=128)&&(o-=Math.pow(2,8*t)),o},i.prototype.readInt8=function(e,t){return e>>>=0,t||q(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},i.prototype.readInt16LE=function(e,t){e>>>=0,t||q(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||q(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||q(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||q(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||q(e,4,this.length),r.read(this,e,!0,23,4)},i.prototype.readFloatBE=function(e,t){return e>>>=0,t||q(e,4,this.length),r.read(this,e,!1,23,4)},i.prototype.readDoubleLE=function(e,t){return e>>>=0,t||q(e,8,this.length),r.read(this,e,!0,52,8)},i.prototype.readDoubleBE=function(e,t){return e>>>=0,t||q(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||N(this,e,t,n,Math.pow(2,8*n)-1,0);var a=1,o=0;for(this[t]=255&e;++o<n&&(a*=256);)this[t+o]=e/a&255;return t+n},i.prototype.writeUIntBE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||N(this,e,t,n,Math.pow(2,8*n)-1,0);var a=n-1,o=1;for(this[t+a]=255&e;--a>=0&&(o*=256);)this[t+a]=e/o&255;return t+n},i.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||N(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||N(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||N(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||N(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},i.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var a=Math.pow(2,8*n-1);N(this,e,t,n,a-1,-a)}var o=0,s=1,i=0;for(this[t]=255&e;++o<n&&(s*=256);)e<0&&0===i&&0!==this[t+o-1]&&(i=1),this[t+o]=(e/s>>0)-i&255;return t+n},i.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var a=Math.pow(2,8*n-1);N(this,e,t,n,a-1,-a)}var o=n-1,s=1,i=0;for(this[t+o]=255&e;--o>=0&&(s*=256);)e<0&&0===i&&0!==this[t+o+1]&&(i=1),this[t+o]=(e/s>>0)-i&255;return t+n},i.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||N(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||N(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||N(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||N(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},i.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeFloatLE=function(e,t,n){return L(this,e,t,!0,n)},i.prototype.writeFloatBE=function(e,t,n){return L(this,e,t,!1,n)},i.prototype.writeDoubleLE=function(e,t,n){return F(this,e,t,!0,n)},i.prototype.writeDoubleBE=function(e,t,n){return F(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 a=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=a-1;o>=0;--o)e[o+t]=this[o+n];else Uint8Array.prototype.set.call(e,this.subarray(n,r),t);return a},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 a=e.charCodeAt(0);("utf8"===r&&a<128||"latin1"===r)&&(e=a)}}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 s=i.isBuffer(e)?e:i.from(e,r),c=s.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]=s[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 Q(e){return e<16?"0"+e.toString(16):e.toString(16)}function z(e,t){var n;t=t||1/0;for(var r=e.length,a=null,o=[],s=0;s<r;++s){if((n=e.charCodeAt(s))>55295&&n<57344){if(!a){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&o.push(239,191,189);continue}a=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),a=n;continue}n=65536+(a-55296<<10|n-56320)}else a&&(t-=3)>-1&&o.push(239,191,189);if(a=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,a,o=[],s=0;s<e.length&&!((t-=2)<0);++s)r=(n=e.charCodeAt(s))>>8,a=n%256,o.push(a),o.push(r);return o}function J(e){return t.toByteArray($(e))}function W(e,t,n,r){for(var a=0;a<r&&!(a+n>=t.length||a>=e.length);++a)t[a+n]=e[a];return a}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 a(){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,a=0;e[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(a=r))})),e.splice(a,0,n)}function s(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=s,n.load=i,n.useColors=a,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,s=null;function i(...e){if(!i.enabled)return;const n=i,a=Number(new Date),o=a-(t||a);n.diff=o,n.prev=t,n.curr=a,t=a,e[0]=r.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let s=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((t,a)=>{if("%%"===t)return"%";s++;const o=r.formatters[a];if("function"==typeof o){const r=e[s];t=o.call(n,r),e.splice(s,1),s--}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=a,i.destroy=r.destroy,Object.defineProperty(i,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==s?s:(n!==r.namespaces&&(n=r.namespaces,o=r.enabled(e)),o),set:e=>{s=e}}),"function"==typeof r.init&&r.init(i),i}function a(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,]+/),a=n.length;for(t=0;t<a;t++)n[t]&&("-"===(e=n[t].replace(/\*/g,".*?"))[0]?r.skips.push(new RegExp("^"+e.substr(1)+"$")):r.names.push(new RegExp("^"+e+"$")))}function s(){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=s,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 a=e("readable-stream"),o=e("end-of-stream"),s=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 a.Readable({objectMode:!0,highWaterMark:16}).wrap(e)},m=function(e,t,n){if(!(this instanceof m))return new m(e,t,n);a.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)};s(m,a.Duplex),m.obj=function(e,t,n){return n||(n={}),n.objectMode=!0,n.highWaterMark=16,new m(e,t,n)},m.prototype.cork=function(){1==++this._corked&&this.emit("cork")},m.prototype.uncork=function(){this._corked&&0==--this._corked&&this.emit("uncork")},m.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)),a=function(){var e=t._ondrain;t._ondrain=null,e&&e()},s=function(){t._writable.removeListener("drain",a),r()};this._unwrite&&n.nextTick(a),this._writable=e,this._writable.on("drain",a),this._unwrite=s,this.uncork()}else this.end()},m.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()},a=function(){t.push(null)},s=function(){t._readable2.removeListener("readable",r),t._readable2.removeListener("end",a),n()};this._drained=!0,this._readable=e,this._readable2=e._readableState?e:f(e),this._readable2.on("readable",r),this._readable2.on("end",a),this._unread=s,this._forward()}},m.prototype._read=function(){this._drained=!0,this._forward()},m.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}},m.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)}))},m.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")},m.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()},m.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)}))}))},m.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),a.Writable.prototype.end.call(this,n))},t.exports=m}).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"),a=function(){},o=function(e){return e.setHeader&&"function"==typeof e.abort},s=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||a);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||m()},m=function(){h=!1,u||c.call(e)},g=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",m)};return o(e)?(e.on("complete",m),e.on("abort",b),e.req?C():e.on("request",C)):h&&!l&&(e.on("end",f),e.on("close",f)),s(e)&&e.on("exit",y),e.on("end",g),e.on("finish",m),!1!==t.error&&e.on("error",v),e.on("close",b),function(){p=!0,e.removeListener("complete",m),e.removeListener("abort",b),e.removeListener("request",C),e.req&&e.req.removeListener("finish",m),e.removeListener("end",f),e.removeListener("close",f),e.removeListener("finish",m),e.removeListener("exit",y),e.removeListener("end",g),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||_,a=Object.keys||k,o=Function.prototype.bind||O;function s(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=r(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}t.exports=s,s.EventEmitter=s,s.prototype._events=void 0,s.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?s.defaultMaxListeners:e._maxListeners}function u(e,t,n){if(t)e.call(n);else for(var r=e.length,a=I(e,r),o=0;o<r;++o)a[o].call(n)}function h(e,t,n,r){if(t)e.call(n,r);else for(var a=e.length,o=I(e,a),s=0;s<a;++s)o[s].call(n,r)}function p(e,t,n,r,a){if(t)e.call(n,r,a);else for(var o=e.length,s=I(e,o),i=0;i<o;++i)s[i].call(n,r,a)}function f(e,t,n,r,a,o){if(t)e.call(n,r,a,o);else for(var s=e.length,i=I(e,s),c=0;c<s;++c)i[c].call(n,r,a,o)}function m(e,t,n,r){if(t)e.apply(n,r);else for(var a=e.length,o=I(e,a),s=0;s<a;++s)o[s].apply(n,r)}function g(e,t,n,a){var o,s,i;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((s=e._events)?(s.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),s=e._events),i=s[t]):(s=e._events=r(null),e._eventsCount=0),i){if("function"==typeof i?i=s[t]=a?[n,i]:[i,n]:a?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=s[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},a=o.call(y,r);return a.listener=n,r.wrapFn=a,a}function b(e,t,n){var r=e._events;if(!r)return[];var a=r[t];return a?"function"==typeof a?n?[a.listener||a]:[a]:n?S(a):I(a,a.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,a=e.length;r<a;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(s,"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}}):s.defaultMaxListeners=c,s.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},s.prototype.getMaxListeners=function(){return d(this)},s.prototype.emit=function(e){var t,n,r,a,o,s,i="error"===e;if(s=this._events)i=i&&null==s.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=s[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(a=new Array(r-1),o=1;o<r;o++)a[o-1]=arguments[o];m(n,l,this,a)}return!0},s.prototype.addListener=function(e,t){return g(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return g(this,e,t,!0)},s.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},s.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},s.prototype.removeListener=function(e,t){var n,a,o,s,i;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(a=this._events))return this;if(!(n=a[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=r(null):(delete a[e],a.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(o=-1,s=n.length-1;s>=0;s--)if(n[s]===t||n[s].listener===t){i=n[s].listener,o=s;break}if(o<0)return this;0===o?n.shift():C(n,o),1===n.length&&(a[e]=n[0]),a.removeListener&&this.emit("removeListener",e,i||t)}return this},s.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 s,i=a(n);for(o=0;o<i.length;++o)"removeListener"!==(s=i[o])&&this.removeAllListeners(s);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},s.prototype.listeners=function(e){return b(this,e,!0)},s.prototype.rawListeners=function(e){return b(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):w.call(e,t)},s.prototype.listenerCount=w,s.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
3
  n.read=function(e,t,n,r,a){var o,s,i=8*a-r-1,c=(1<<i)-1,l=c>>1,d=-7,u=n?a-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(s=o&(1<<-d)-1,o>>=-d,d+=r;d>0;s=256*s+e[t+u],u+=h,d-=8);if(0===o)o=1-l;else{if(o===c)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,r),o-=l}return(p?-1:1)*s*Math.pow(2,o-r)},n.write=function(e,t,n,r,a,o){var s,i,c,l=8*o-a-1,d=(1<<l)-1,u=d>>1,h=23===a?Math.pow(2,-24)-Math.pow(2,-77):0,p=r?0:o-1,f=r?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(i=isNaN(t)?1:0,s=d):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+u>=1?h/c:h*Math.pow(2,1-u))*c>=2&&(s++,c/=2),s+u>=d?(i=0,s=d):s+u>=1?(i=(t*c-1)*Math.pow(2,a),s+=u):(i=t*Math.pow(2,u-1)*Math.pow(2,a),s=0));a>=8;e[n+p]=255&i,p+=f,i/=256,a-=8);for(s=s<<a|i,l+=a;l>0;e[n+p]=255&s,p+=f,s/=256,l-=8);e[n+p-f]|=128*m}},{}],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 a=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=a,o&&(o.parent=r,o.brother=this),n&&(n.parent=this,n.brother=a),a&&(a.parent=this,a.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,a=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=a,n.rightChild=this,t&&(t.brother=n),a&&(a.parent=n,a.brother=this),this.parent=n,this.brother=a,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,a,o,s={label:0,sent:function(){if(1&a[0])throw a[1];return a[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(;s;)try{if(n=1,r&&(a=2&o[0]?r.return:o[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,o[1])).done)return a;switch(r=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!((a=(a=s.trys).length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){s.label=o[1];break}if(6===o[0]&&s.label<a[1]){s.label=a[1],a=o;break}if(a&&s.label<a[2]){s.label=a[2],s.ops.push(o);break}a[2]&&s.ops.pop(),s.trys.pop();continue}o=t.call(e,s)}catch(e){o=[6,e],r=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}};function a(e){var t=this;void 0===e&&(e=[]);var n=[],o=0,s=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=s=c=l=d=0,h.call(this,a.bucketSize),d=0},this.front=function(){return n[o][s]},this.back=function(){return n[i][c]},this.forEach=function(e){if(!this.empty()){var t=0;if(o!==i){for(l=s;l<a.bucketSize;++l)e(n[o][l],t++);for(l=o+1;l<i;++l)for(var r=0;r<a.bucketSize;++r)e(n[l][r],t++);for(l=0;l<=c;++l)e(n[i][l],t++)}else for(var l=s;l<=c;++l)e(n[o][l],t++)}};var u=function(e){var t=o*a.bucketSize+s,n=t+e,r=i*a.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/a.bucketSize),curNodePointerIndex:n%a.bucketSize}};this.getElementByPos=function(e){var t=u(e),r=t.curNodeBucketIndex,a=t.curNodePointerIndex;return n[r][a]},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*a.sigma,u=Math.max(Math.ceil(r/a.bucketSize),2),h=0;h<u;++h)t.push(new Array(a.bucketSize));var p=Math.ceil(e/a.bucketSize),f=Math.floor(u/2)-Math.floor(p/2),m=f,g=0;if(this.size())for(h=0;h<p;++h){for(var y=0;y<a.bucketSize;++y)if(t[f+h][y]=this.front(),this.popFront(),this.empty()){m=f+h,g=y;break}if(this.empty())break}n=t,o=f,s=0,i=m,c=g,l=u,d=e};this.pushBack=function(e){this.empty()||(i===l-1&&c===a.bucketSize-1&&h.call(this,this.size()),c<a.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=a.bucketSize-1)),d>0&&--d)},this.setElementByPos=function(e,t){var r=u(e),a=r.curNodeBucketIndex,o=r.curNodePointerIndex;n[a][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 a=[],o=e;o<d;++o)a.push(this.getElementByPos(o));for(this.cut(e-1),o=0;o<n;++o)this.pushBack(t);a.forEach((function(e){return r.pushBack(e)}))}},this.find=function(e){if(o===i){for(var t=s;t<=c;++t)if(n[o][t]===e)return!0;return!1}for(t=s;t<a.bucketSize;++t)if(n[o][t]===e)return!0;for(t=o+1;t<i;++t)for(var r=0;r<a.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===s&&h.call(this,this.size()),s>0?--s:o>0&&(--o,s=a.bucketSize-1)),++d,n[o][s]=e},this.popFront=function(){this.empty()||(1!==this.size()&&(s<a.bucketSize-1?++s:o<i&&(++o,s=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/a.bucketSize),s=0;s<o;++s)n.push(new Array(a.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=s,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=s,r.label=6;case 6:return t<a.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<a.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=a.bucketSize;e.size?r=e.size():e.length&&(r=e.length);var s=r*a.sigma;l=Math.ceil(s/a.bucketSize),l=Math.max(l,3);for(var c=0;c<l;++c)n.push(new Array(a.bucketSize));var d=Math.ceil(r/a.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}),a.sigma=3,a.bucketSize=5e3,Object.freeze(a),n.default=a},{}],27:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,a,o,s={label:0,sent:function(){if(1&a[0])throw a[1];return a[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(;s;)try{if(n=1,r&&(a=2&o[0]?r.return:o[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,o[1])).done)return a;switch(r=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!((a=(a=s.trys).length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){s.label=o[1];break}if(6===o[0]&&s.label<a[1]){s.label=a[1],a=o;break}if(a&&s.label<a[2]){s.label=a[2],s.ops.push(o);break}a[2]&&s.ops.pop(),s.trys.pop();continue}o=t.call(e,s)}catch(e){o=[6,e],r=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}},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.")};Object.defineProperty(n,"__esModule",{value:!0});var o=e("../LinkList/LinkList"),s=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 s=a(o),i=s.next();!i.done;i=s.next())r=(r<<5)-r+i.value.charCodeAt(0),r&=r}catch(e){t={error:e}}finally{try{i&&!i.done&&(n=s.return)&&n.call(s)}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,a){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 s.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[a]=new s.default(p):p.size()&&(t[a]=p),f.size()>i.untreeifyThreshold?t[a+e]=new s.default(f):f.size()&&(t[a+e]=f)}else{var m=new o.default,g=new o.default;r.forEach((function(t){0==(n(t.key)&e)?m.pushBack(t):g.pushBack(t)})),m.size()&&(t[a]=m),g.size()&&(t[a+e]=g)}d[a].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 m=a(d[p]),g=m.next();!g.done;g=m.next()){var y=g.value;if(y.key===e)return void(y.value=t)}}catch(e){r={error:e}}finally{try{g&&!g.done&&(c=m.return)&&c.call(m)}finally{if(r)throw r.error}}d[p].pushBack({key:e,value:t}),d[p].size()>=i.treeifyThreshold&&(d[p]=new s.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 s.default)return d[o].getElementByKey(e);try{for(var i=a(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 s.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=a(d[c]),m=f.next();!m.done;m=f.next()){var g=m.value;if(++p,g.key===e){d[c].eraseElementByPos(p);break}}}catch(e){t={error:e}}finally{try{m&&!m.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 s.default)return d[o].find(e);try{for(var i=a(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,s,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]),s=void 0,t=a(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(),s={error:o},[3,9];case 8:try{n&&!n.done&&(i=t.return)&&i.call(t)}finally{if(s)throw s.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,a,o,s={label:0,sent:function(){if(1&a[0])throw a[1];return a[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(;s;)try{if(n=1,r&&(a=2&o[0]?r.return:o[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,o[1])).done)return a;switch(r=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!((a=(a=s.trys).length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){s.label=o[1];break}if(6===o[0]&&s.label<a[1]){s.label=a[1],a=o;break}if(a&&s.label<a[2]){s.label=a[2],s.ops.push(o);break}a[2]&&s.ops.pop(),s.trys.pop();continue}o=t.call(e,s)}catch(e){o=[6,e],r=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}},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.")};Object.defineProperty(n,"__esModule",{value:!0});var o=e("../Set/Set"),s=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,a){if(!r.empty()){if(r instanceof s.default&&1===r.size()){var c=r.front();if(void 0===c)throw new Error("unknown error");t[n(c)&u-1]=new s.default([c])}else if(r instanceof o.default){var l=new s.default,h=new s.default;r.forEach((function(t){0==(n(t)&e)?l.pushBack(t):h.pushBack(t)})),l.size()>i.untreeifyThreshold?t[a]=new o.default(l):l.size()&&(t[a]=l),h.size()>i.untreeifyThreshold?t[a+e]=new o.default(h):h.size()&&(t[a+e]=h)}else{var p=new s.default,f=new s.default;r.forEach((function(t){0==(n(t)&e)?p.pushBack(t):f.pushBack(t)})),p.size()&&(t[a]=p),f.size()&&(t[a+e]=f)}d[a].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 s.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 a=d[t].size();l+=a-r}else d[t]=new s.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 s.default(d[t]));var a=d[t].size();l+=a-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,s,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]),s=void 0,t=a(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(),s={error:o},[3,9];case 8:try{n&&!n.done&&(i=t.return)&&i.call(t)}finally{if(s)throw s.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,a,o,s={label:0,sent:function(){if(1&a[0])throw a[1];return a[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(;s;)try{if(n=1,r&&(a=2&o[0]?r.return:o[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,o[1])).done)return a;switch(r=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!((a=(a=s.trys).length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){s.label=o[1];break}if(6===o[0]&&s.label<a[1]){s.label=a[1],a=o;break}if(a&&s.label<a[2]){s.label=a[2],s.ops.push(o);break}a[2]&&s.ops.pop(),s.trys.pop();continue}o=t.call(e,s)}catch(e){o=[6,e],r=0}finally{n=a=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 a=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,s=void 0;this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){o=s=void 0,n=0},this.front=function(){return null==o?void 0:o.value},this.back=function(){return null==s?void 0:s.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,a=t.next;a.pre=r,r.next=a,n>0&&--n}},this.eraseElementByValue=function(e){for(;o&&o.value===e;)this.popFront();for(;s&&s.value===e;)this.popBack();if(o)for(var t=o;t;){if(t.value===e){var r=t.pre,a=t.next;a&&(a.pre=r),r&&(r.next=a),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 a(e);s?(s.next=t,t.pre=s,s=t):o=s=t},this.popBack=function(){s&&(n>0&&--n,s&&(o===s?o=s=void 0:(s=s.pre)&&(s.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 s=o,i=1;i<e;++i){if(!(null==s?void 0:s.next))throw new Error("unknown error");s=null==s?void 0:s.next}if(!s)throw new Error("unknown error");var c=s.next;for(n+=r;r--;)s.next=new a(t),s.next.pre=s,s=s.next;s.next=c,c&&(c.pre=s)}},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=s,r=0;e&&t&&2*r<n;){var a=e.value;e.value=t.value,t.value=a,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 a(e);o?(t.next=o,o.pre=t,o=t):o=s=t},this.popFront=function(){o&&(n>0&&--n,o&&(o===s?o=s=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=s;else if(r===o)t.pushFront(e),r=o;else{++n;var i=r.pre;i&&(i.next=new a(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,a,o,s={label:0,sent:function(){if(1&a[0])throw a[1];return a[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(;s;)try{if(n=1,r&&(a=2&o[0]?r.return:o[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,o[1])).done)return a;switch(r=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!((a=(a=s.trys).length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){s.label=o[1];break}if(6===o[0]&&s.label<a[1]){s.label=a[1],a=o;break}if(a&&s.label<a[2]){s.label=a[2],s.ops.push(o);break}a[2]&&s.ops.pop(),s.trys.pop();continue}o=t.call(e,s)}catch(e){o=[6,e],r=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}},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.")};Object.defineProperty(n,"__esModule",{value:!0});var o=e("../Base/TreeNode");function s(e,t){var n=this;void 0===e&&(e=[]),t=t||function(e,t){return e<t?-1:e>t?1:0};var s=0,i=new o.default;i.color=o.default.TreeNodeColorType.black,this.size=function(){return s},this.empty=function(){return 0===s},this.clear=function(){s=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=a(this),s=o.next();!s.done;s=o.next())e(s.value,r++)}catch(e){t={error:e}}finally{try{s&&!s.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=a(this),s=o.next();!s.done;s=o.next()){var i=s.value;if(r===e)return i;++r}}catch(e){t={error:e}}finally{try{s&&!s.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},m=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(),--s,i.color=o.default.TreeNodeColorType.black},g=function(e,t){return!(!e||void 0===e.key)&&(!!g(e.leftChild,t)||!!t(e)||g(e.rightChild,t))};this.eraseElementByPos=function(e){if(e<0||e>=s)throw new Error("pos must more than 0 and less than set's size");var t=0;g(i,(function(n){return e===t?(m(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)&&m(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 a=r.rotateRight();r===i&&(i=a)}else e===t.rightChild&&(a=t.rotateLeft(),r===i&&(i=a),v(t));else t===r.rightChild&&(e===t.leftChild?(a=t.rotateRight(),r===i&&(i=a),v(t)):e===t.rightChild&&(t.color=o.default.TreeNodeColorType.black,r.color=o.default.TreeNodeColorType.red,a=r.rotateLeft(),r===i&&(i=a)))}};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++s,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)?(++s,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,a(w(e.leftChild))]:[2];case 1:return t.sent(),[4,{key:e.key,value:e.value}];case 2:return t.sent(),[5,a(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(s),n.default=s},{"../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,a=function(e,t){if(e<0||e>=r)throw new Error("unknown error");if(t<0||t>=r)throw new Error("unknown error");var a=n[e];n[e]=n[t],n[t]=a},o=function(e){if(e<0||e>=r)throw new Error("unknown error");var o=2*e+1,s=2*e+2;o<r&&t(n[e],n[o])>0&&a(e,o),s<r&&t(n[e],n[s])>0&&a(e,s)};!function(){for(var e=Math.floor((r-1)/2);e>=0;--e)for(var o=e,s=2*o+1;s<r;){var i=s+1,c=s;if(i<r&&t(n[s],n[i])>0&&(c=i),t(n[o],n[c])<=0)break;a(o,c),s=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 a=r-1;a>0;){var s=Math.floor((a-1)/2);if(t(n[s],e)<=0)break;o(s),a=s}},this.pop=function(){if(!this.empty())if(1!==this.size()){var e=n[r-1];--r;for(var a=0;a<this.size();){var o=2*a+1,s=2*a+2;if(o>=this.size())break;var i=o;if(s<this.size()&&t(n[o],n[s])>0&&(i=s),t(n[i],e)>=0)break;n[a]=n[i],a=i}n[a]=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 a(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(a),n.default=a},{"../LinkList/LinkList":29}],33:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,a,o,s={label:0,sent:function(){if(1&a[0])throw a[1];return a[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(;s;)try{if(n=1,r&&(a=2&o[0]?r.return:o[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,o[1])).done)return a;switch(r=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!((a=(a=s.trys).length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){s.label=o[1];break}if(6===o[0]&&s.label<a[1]){s.label=a[1],a=o;break}if(a&&s.label<a[2]){s.label=a[2],s.ops.push(o);break}a[2]&&s.ops.pop(),s.trys.pop();continue}o=t.call(e,s)}catch(e){o=[6,e],r=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}},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.")};Object.defineProperty(n,"__esModule",{value:!0});var o=e("../Base/TreeNode");function s(e,t){var n=this;void 0===e&&(e=[]),t=t||function(e,t){return e<t?-1:e>t?1:0};var s=0,i=new o.default;i.color=o.default.TreeNodeColorType.black,this.size=function(){return s},this.empty=function(){return 0===s},this.clear=function(){s=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=a(this),s=o.next();!s.done;s=o.next())e(s.value,r++)}catch(e){t={error:e}}finally{try{s&&!s.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=a(this),s=o.next();!s.done;s=o.next()){var i=s.value;if(r===e)return i;++r}}catch(e){t={error:e}}finally{try{s&&!s.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(),--s,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>=s)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=m(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 a=r.rotateRight();r===i&&(i=a)}else e===t.rightChild&&(a=t.rotateLeft(),r===i&&(i=a),f(t));else t===r.rightChild&&(e===t.leftChild?(a=t.rotateRight(),r===i&&(i=a),f(t)):e===t.rightChild&&(t.color=o.default.TreeNodeColorType.black,r.color=o.default.TreeNodeColorType.red,a=r.rotateLeft(),r===i&&(i=a)))}};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++s,i.key=e,void(i.color=o.default.TreeNodeColorType.black);var n=p(i,e);void 0!==n.key&&0===t(n.key,e)||(++s,n.key=e,f(n),i.color=o.default.TreeNodeColorType.black)};var m=function(e,n){if(e&&void 0!==e.key){var r=t(n,e.key);return r<0?m(e.leftChild,n):r>0?m(e.rightChild,n):e}};this.find=function(e){var n=m(i,e);return void 0!==n&&void 0!==n.key&&0===t(n.key,e)};var g=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 g(e.rightChild,n);var a=g(e.leftChild,n);return void 0!==a?a:e.key}};this.lowerBound=function(e){return g(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 a=v(e.rightChild,n);return void 0!==a?a: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,a(w(e.leftChild))]:[2];case 1:return t.sent(),[4,e.key];case 2:return t.sent(),[5,a(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(s),n.default=s},{"../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,a,o,s={label:0,sent:function(){if(1&a[0])throw a[1];return a[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(;s;)try{if(n=1,r&&(a=2&o[0]?r.return:o[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,o[1])).done)return a;switch(r=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!((a=(a=s.trys).length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){s.label=o[1];break}if(6===o[0]&&s.label<a[1]){s.label=a[1],a=o;break}if(a&&s.label<a[2]){s.label=a[2],s.ops.push(o);break}a[2]&&s.ops.pop(),s.trys.pop();continue}o=t.call(e,s)}catch(e){o=[6,e],r=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}},a=this&&this.__read||function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,a,o=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){a={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(a)throw a.error}}return s},o=this&&this.__spreadArray||function(e,t,n){if(n||2===arguments.length)for(var r,a=0,o=t.length;a<o;a++)!r&&a in t||(r||(r=Array.prototype.slice.call(t,0,a)),r[a]=t[a]);return e.concat(r||Array.prototype.slice.call(t))},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.")};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],a(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,s(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 a=e("./Stack/Stack");n.Stack=a.default;var o=e("./Queue/Queue");n.Queue=o.default;var s=e("./LinkList/LinkList");n.LinkList=s.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"),a=Symbol("max"),o=Symbol("length"),s=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 m{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[a]=e.max||1/0;const t=e.length||f;if(this[s]="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[a]=e||1/0,v(this)}get max(){return this[a]}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[s]&&(this[s]=e,this[o]=0,this[u].forEach((e=>{e.length=this[s](e.value,e.key),this[o]+=e.length}))),v(this)}get lengthCalculator(){return this[s]}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[s](t,e);if(this[h].has(e)){if(i>this[a])return b(this,this[h].get(e)),!1;const s=this[h].get(e).value;return this[l]&&(this[d]||this[l](e,s.value)),s.now=r,s.maxAge=n,s.value=t,this[o]+=i-s.length,s.length=i,this.get(e),v(this),!0}const p=new w(e,t,i,r,n);return p.length>this[a]?(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 g(this,e,!0)}peek(e){return g(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],a=r.e||0;if(0===a)this.set(r.k,r.v);else{const e=a-t;e>0&&this.set(r.k,r.v,e)}}}prune(){this[h].forEach(((e,t)=>g(this,t,!1)))}}const g=(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[a])for(let t=e[u].tail;e[o]>e[a]&&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,a){this.key=e,this.value=t,this.length=n,this.now=r,this.maxAge=a||0}}const C=(e,t,n,r)=>{let a=n.value;y(e,a)&&(b(e,n),e[i]||(a=void 0)),a&&t.call(r,a.value,a.key,e)};t.exports=m},{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((a=>[0,1].map((o=>{const s=e.alloc(1);return s.writeUInt8(n.codes[t]<<n.CMD_SHIFT|(a?n.DUP_MASK:0)|r<<n.QOS_SHIFT|o,0,!0),s}))))))}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"),a=e("events");function o(e,t){const n=new s;return r(e,n,t),n.concat()}class s extends a{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 a,o=0;for(a=0;a<r.length&&void 0!==r[a];a++)"string"!=typeof r[a]?t[a]=r[a].length:t[a]=n.byteLength(r[a]),e+=t[a];const s=n.allocUnsafe(e);for(a=0;a<r.length&&void 0!==r[a];a++)"string"!=typeof r[a]?(r[a].copy(s,o),o+=t[a]):(s.write(r[a],o),o+=t[a]);return s}}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={},a=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 s(){for(let e=0;e<n;e++)r[e]=o(e)}function i(t){const n=4;let r=0,o=0;const s=e.allocUnsafe(n);do{r=t%128|0,(t=t/128|0)>0&&(r|=128),s.writeUInt8(r,o++)}while(t>0&&o<n);return t>0&&(o=0),a?s.subarray(0,o):s.slice(0,o)}function c(t){const n=e.allocUnsafe(4);return n.writeUInt32BE(t,0),n}t.exports={cache:r,generateCache:s,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"),a=e("events"),o=e("./packet"),s=e("./constants"),i=e("debug")("mqtt-packet:parser");class c extends a{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=s.types[e>>s.CMD_SHIFT],this.packet.retain=0!=(e&s.RETAIN_MASK),this.packet.qos=e>>s.QOS_SHIFT&s.QOS_MASK,this.packet.dup=0!=(e&s.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 a={},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(a.username=this._list.readUInt8(this._pos)&s.USERNAME_MASK,a.password=this._list.readUInt8(this._pos)&s.PASSWORD_MASK,a.will=this._list.readUInt8(this._pos)&s.WILL_FLAG_MASK,a.will&&(o.will={},o.will.retain=0!=(this._list.readUInt8(this._pos)&s.WILL_RETAIN_MASK),o.will.qos=(this._list.readUInt8(this._pos)&s.WILL_QOS_MASK)>>s.WILL_QOS_SHIFT),o.clean=0!=(this._list.readUInt8(this._pos)&s.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),a.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(a.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(a.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++)&s.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,a,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&s.SUBSCRIBE_OPTIONS_QOS_MASK,c=0!=(n>>s.SUBSCRIBE_OPTIONS_NL_SHIFT&s.SUBSCRIBE_OPTIONS_NL_MASK),o=0!=(n>>s.SUBSCRIBE_OPTIONS_RAP_SHIFT&s.SUBSCRIBE_OPTIONS_RAP_MASK),a=n>>s.SUBSCRIBE_OPTIONS_RH_SHIFT&s.SUBSCRIBE_OPTIONS_RH_MASK,l={topic:t,qos:r},5===this.settings.protocolVersion?(l.nl=c,l.rap=o,l.rh=a):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,a=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+=a*(n&s.VARBYTEINT_MASK),a*=128,0==(n&s.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=s.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(s.propertiesTypes[t]))):n[t]=this._parseByType(s.propertiesTypes[t]);else{n[t]||(n[t]=Object.create(null));const e=this._parseByType(s.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"),a=n.allocUnsafe(0),o=n.from([0]),s=e("./numbers"),i=e("process-nextick-args").nextTick,c=e("debug")("mqtt-packet:writeToStream"),l=s.cache,d=s.generateNumber,u=s.generateCache,h=s.genBufVariableByteInt,p=s.generate4ByteBuffer;let f=j,m=!0;function g(e,t,n){switch(c("generate called"),t.cork&&(t.cork(),i(y,t)),m&&(m=!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,a){const o=e||{},s=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,m=o.properties;void 0===l&&(l=!0);let g=0;if(!s||"string"!=typeof s&&!n.isBuffer(s))return t.emit("error",new Error("Invalid protocolId")),!1;if(g+=s.length+2,3!==i&&4!==i&&5!==i)return t.emit("error",new Error("Invalid protocol version")),!1;if(g+=1,("string"==typeof u||n.isBuffer(u))&&(u||i>=4)&&(u||l))g+=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(g+=2,g+=1,5===i){var y=q(t,m);if(!y)return!1;g+=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(g+=n.byteLength(c.topic)+2,g+=2,c.payload){if(!(c.payload.length>=0))return t.emit("error",new Error("Invalid will payload")),!1;"string"==typeof c.payload?g+=n.byteLength(c.payload):g+=c.payload.length}var v={};if(5===i){if(!(v=q(t,c.properties)))return!1;g+=v.length}}let b=!1;if(null!=h){if(!K(h))return t.emit("error",new Error("Invalid username")),!1;b=!0,g+=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;g+=F(p)+2}t.write(r.CONNECT_HEADER),R(t,g),D(t,s),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,a){const s=a?a.protocolVersion:4,i=e||{},c=5===s?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===s){if(u=q(t,l),!u)return!1;d+=u.length}return t.write(r.CONNACK_HEADER),R(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 s=o?o.protocolVersion:4,i=e||{},l=i.qos||0,d=i.retain?r.RETAIN_MASK:0,u=i.topic,h=i.payload||a,p=i.messageId,m=i.properties;let g=0;if("string"==typeof u)g+=n.byteLength(u)+2;else{if(!n.isBuffer(u))return t.emit("error",new Error("Invalid topic")),!1;g+=u.length+2}if(n.isBuffer(h)?g+=h.length:g+=n.byteLength(h),l&&"number"!=typeof p)return t.emit("error",new Error("Invalid messageId")),!1;l&&(g+=2);let y=null;if(5===s){if(y=q(t,m),!y)return!1;g+=y.length}return t.write(r.PUBLISH_HEADER[l][i.dup?1:0][d?1:0]),R(t,g),f(t,F(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,a){const o=a?a.protocolVersion:4,s=e||{},i=s.cmd||"puback",c=s.messageId,l=s.dup&&"pubrel"===i?r.DUP_MASK:0;let d=0;const u=s.reasonCode,h=s.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 m=null;if(5===o&&"object"==typeof h){if(m=N(t,h,a,p),!m)return!1;p+=m.length}return t.write(r.ACKS[i][d][l][0]),R(t,p),f(t,c),5===o&&t.write(n.from([u])),null!==m&&m.write(),!0}function I(e,t,a){c("subscribe: packet: ");const o=a?a.protocolVersion:4,s=e||{},i=s.dup?r.DUP_MASK:0,l=s.messageId,d=s.subscriptions,u=s.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=q(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,a=d[e].qos;if("string"!=typeof r)return t.emit("error",new Error("Invalid subscriptions - invalid topic")),!1;if("number"!=typeof a)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]),R(t,h),f(t,l),null!==p&&p.write();let m=!0;for(const e of d){const a=e.topic,s=e.qos,i=+e.nl,c=+e.rap,l=e.rh;let d;P(t,a),d=r.SUBSCRIBE_OPTIONS_QOS[s],5===o&&(d|=i?r.SUBSCRIBE_OPTIONS_NL:0,d|=c?r.SUBSCRIBE_OPTIONS_RAP:0,d|=l?r.SUBSCRIBE_OPTIONS_RH[l]:0),m=t.write(n.from([d]))}return m}function S(e,t,a){const o=a?a.protocolVersion:4,s=e||{},i=s.messageId,c=s.granted,l=s.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=N(t,l,a,d),!u)return!1;d+=u.length}return t.write(r.SUBACK_HEADER),R(t,d),f(t,i),null!==u&&u.write(),t.write(n.from(c))}function _(e,t,a){const o=a?a.protocolVersion:4,s=e||{},i=s.messageId,c=s.dup?r.DUP_MASK:0,l=s.unsubscriptions,d=s.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=q(t,d),!h)return!1;u+=h.length}t.write(r.UNSUBSCRIBE_HEADER[1][c?1:0][0]),R(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,a){const o=a?a.protocolVersion:4,s=e||{},i=s.messageId,c=s.dup?r.DUP_MASK:0,l=s.granted,d=s.properties,u=s.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 m=null;if(5===o){if(m=N(t,d,a,p),!m)return!1;p+=m.length}return t.write(r.ACKS[u][h][c][0]),R(t,p),f(t,i),null!==m&&m.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,a){const o=a?a.protocolVersion:4,s=e||{},i=s.reasonCode,c=s.properties;let l=5===o?1:0,d=null;if(5===o){if(d=N(t,c,a,l),!d)return!1;l+=d.length}return t.write(n.from([r.codes.disconnect<<4])),R(t,l),5===o&&t.write(n.from([i])),null!==d&&d.write(),!0}function E(e,t,a){const o=a?a.protocolVersion:4,s=e||{},i=s.reasonCode,c=s.properties;let l=5===o?1:0;5!==o&&t.emit("error",new Error("Invalid mqtt version for auth packet"));const d=N(t,c,a,l);return!!d&&(l+=d.length,t.write(n.from([r.codes.auth<<4])),R(t,l),t.write(n.from([i])),null!==d&&d.write(),!0)}Object.defineProperty(g,"cacheNumbers",{get:()=>f===j,set(e){e?(l&&0!==Object.keys(l).length||(m=!0),f=j):(m=!1,f=U)}});const A={};function R(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 M(e,t,n){P(e,t),P(e,n)}function j(e,t){return c("writeNumberCached: number: %d",t),c("writeNumberCached: %o",l[t]),e.write(l[t])}function U(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 q(e,t){if("object"!=typeof t||null!=t.length)return{length:1,write(){L(e,{},0)}};let a=0;function o(t,a){let o=0;switch(r.propertiesTypes[t]){case"byte":if("boolean"!=typeof a)return e.emit("error",new Error(`Invalid ${t}: ${a}`)),!1;o+=2;break;case"int8":if("number"!=typeof a||a<0||a>255)return e.emit("error",new Error(`Invalid ${t}: ${a}`)),!1;o+=2;break;case"binary":if(a&&null===a)return e.emit("error",new Error(`Invalid ${t}: ${a}`)),!1;o+=1+n.byteLength(a)+2;break;case"int16":if("number"!=typeof a||a<0||a>65535)return e.emit("error",new Error(`Invalid ${t}: ${a}`)),!1;o+=3;break;case"int32":if("number"!=typeof a||a<0||a>4294967295)return e.emit("error",new Error(`Invalid ${t}: ${a}`)),!1;o+=5;break;case"var":if("number"!=typeof a||a<0||a>268435455)return e.emit("error",new Error(`Invalid ${t}: ${a}`)),!1;o+=1+n.byteLength(h(a));break;case"string":if("string"!=typeof a)return e.emit("error",new Error(`Invalid ${t}: ${a}`)),!1;o+=3+n.byteLength(a.toString());break;case"pair":if("object"!=typeof a)return e.emit("error",new Error(`Invalid ${t}: ${a}`)),!1;o+=Object.getOwnPropertyNames(a).reduce(((e,t)=>{const r=a[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(a[t].toString()),e}),0);break;default:return e.emit("error",new Error(`Invalid property ${t}: ${a}`)),!1}return o}if(t)for(const e in t){let n=0,r=0;const s=t[e];if(Array.isArray(s))for(let t=0;t<s.length;t++){if(r=o(e,s[t]),!r)return!1;n+=r}else{if(r=o(e,s),!r)return!1;n=r}if(!n)return!1;a+=n}return{length:n.byteLength(h(a))+a,write(){L(e,t,a)}}}function N(e,t,n,r){const a=["reasonString","userProperties"],o=n&&n.properties&&n.properties.maximumPacketSize?n.properties.maximumPacketSize:0;let s=q(e,t);if(o)for(;r+s.length>o;){const n=a.shift();if(!n||!t[n])return!1;delete t[n],s=q(e,t)}return s}function B(e,t,a){switch(r.propertiesTypes[t]){case"byte":e.write(n.from([r.properties[t]])),e.write(n.from([+a]));break;case"int8":e.write(n.from([r.properties[t]])),e.write(n.from([a]));break;case"binary":e.write(n.from([r.properties[t]])),D(e,a);break;case"int16":e.write(n.from([r.properties[t]])),f(e,a);break;case"int32":e.write(n.from([r.properties[t]])),x(e,a);break;case"var":e.write(n.from([r.properties[t]])),R(e,a);break;case"string":e.write(n.from([r.properties[t]])),P(e,a);break;case"pair":Object.getOwnPropertyNames(a).forEach((o=>{const s=a[o];Array.isArray(s)?s.forEach((a=>{e.write(n.from([r.properties[t]])),M(e,o.toString(),a.toString())})):(e.write(n.from([r.properties[t]])),M(e,o.toString(),s.toString()))}));break;default:return e.emit("error",new Error(`Invalid property ${t} value: ${a}`)),!1}}function L(e,t,n){R(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++)B(e,n,r[t]);else B(e,n,r)}}function F(e){return e?e instanceof n?e.length:n.byteLength(e):0}function K(e){return"string"==typeof e||e instanceof n}t.exports=g}).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,a=60*r,o=60*a,s=24*o,i=7*s,c=365.25*s;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*s;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*a;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>=s?Math.round(e/s)+"d":t>=o?Math.round(e/o)+"h":t>=a?Math.round(e/a)+"m":t>=r?Math.round(e/r)+"s":e+"ms"}function u(e){var t=Math.abs(e);return t>=s?h(e,t,s,"day"):t>=o?h(e,t,o,"hour"):t>=a?h(e,t,a,"minute"):t>=r?h(e,t,r,"second"):e+" ms"}function h(e,t,n,r){var a=t>=1.5*n;return Math.round(e/n)+" "+r+(a?"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,a=e("debug")("number-allocator:trace"),o=e("debug")("number-allocator:error");function s(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))),a("Create"),this.clear()}s.prototype.equals=function(e){return this.low===e.low&&this.high===e.high},s.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 a("alloc():empty"),null;const e=this.ss.front(),t=e.low;return t+1<=e.high?++e.low:this.ss.eraseElementByPos(0),a("alloc():"+t),t},i.prototype.use=function(e){const t=new s(e,e),n=this.ss.lowerBound(t);if(n){if(n.equals(t))return this.ss.eraseElementByValue(n),a("use():"+e),!0;if(n.low>e)return!1;if(n.low===e)return++n.low,a("use():"+e),!0;if(n.high===e)return--n.high,a("use():"+e),!0;const r=n.low;return n.low=e+1,this.ss.insert(new s(r,e-1)),a("use():"+e),!0}return a("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 s(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)}a("free():"+e)},i.prototype.clear=function(){a("clear()"),this.ss.clear(),this.ss.insert(new s(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 a(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(a),t.exports.strict=r(o),a.proto=a((function(){Object.defineProperty(Function.prototype,"once",{value:function(){return a(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,a){if("function"!=typeof t)throw new TypeError('"callback" argument must be a function');var o,s,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,a)}));default:for(o=new Array(i-1),s=0;s<o.length;)o[s++]=arguments[s];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,a,o=t.exports={};function s(){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===s||!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(a===clearTimeout)return clearTimeout(e);if((a===i||!a)&&clearTimeout)return a=clearTimeout,clearTimeout(e);try{return a(e)}catch(t){try{return a.call(null,e)}catch(t){return a.call(this,e)}}}!function(){try{r="function"==typeof setTimeout?setTimeout:s}catch(e){r=s}try{a="function"==typeof clearTimeout?clearTimeout:i}catch(e){a=i}}();var d,u=[],h=!1,p=-1;function f(){h&&d&&(h=!1,d.length?u=d.concat(u):p=-1,u.length&&m())}function m(){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 g(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 g(e,t)),1!==u.length||h||c(m)},g.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 a="object"==typeof n&&n&&!n.nodeType&&n,o="object"==typeof t&&t&&!t.nodeType&&t,s="object"==typeof e&&e;s.global!==s&&s.window!==s&&s.self!==s||(r=s);var i,c,l=2147483647,d=36,u=1,h=26,p=38,f=700,m=72,g=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=[],a=0,o=e.length;a<o;)(t=e.charCodeAt(a++))>=55296&&t<=56319&&a<o?56320==(64512&(n=e.charCodeAt(a++)))?r.push(((1023&t)<<10)+(1023&n)+65536):(r.push(t),a--):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 R(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 M(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 j(e){var t,n,r,a,o,s,i,c,p,f,v=[],b=e.length,w=0,C=g,I=m;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(a=n>0?n+1:0;a<b;){for(o=w,s=1,i=d;a>=b&&k("invalid-input"),((c=R(e.charCodeAt(a++)))>=d||c>S((l-w)/s))&&k("overflow"),w+=c*s,!(c<(p=i<=I?u:i>=I+h?h:i-I));i+=d)s>S(l/(f=d-p))&&k("overflow"),s*=f;I=M(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 U(e){var t,n,r,a,o,s,i,c,p,f,v,b,w,C,I,O=[];for(b=(e=E(e)).length,t=g,n=0,o=m,s=0;s<b;++s)(v=e[s])<128&&O.push(_(v));for(r=a=O.length,a&&O.push(y);r<b;){for(i=l,s=0;s<b;++s)(v=e[s])>=t&&v<i&&(i=v);for(i-t>S((l-n)/(w=r+1))&&k("overflow"),n+=(i-t)*w,t=i,s=0;s<b;++s)if((v=e[s])<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=M(n,w,r==a),n=0,++r}++n,++t}return O.join("")}function x(e){return T(e,(function(e){return v.test(e)?j(e.slice(4).toLowerCase()):e}))}function D(e){return T(e,(function(e){return b.test(e)?"xn--"+U(e):e}))}if(i={version:"1.4.1",ucs2:{decode:E,encode:A},decode:j,encode:U,toASCII:D,toUnicode:x},a&&o)if(t.exports==a)o.exports=i;else for(c in i)i.hasOwnProperty(c)&&(a[c]=i[c]);else r.punycode=i}(this)}).call(this)}).call(this,void 0!==Nt?Nt:"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 s={};if("string"!=typeof e||0===e.length)return s;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,m=e[d].replace(i,"%20"),g=m.indexOf(n);g>=0?(u=m.substr(0,g),h=m.substr(g+1)):(u=m,h=""),p=decodeURIComponent(u),f=decodeURIComponent(h),r(s,p)?a(s[p])?s[p].push(f):s[p]=[s[p],f]:s[p]=f}return s};var a=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(s(e),(function(s){var i=encodeURIComponent(r(s))+n;return a(e[s])?o(e[s],(function(e){return i+encodeURIComponent(r(e))})).join(t):i+encodeURIComponent(r(e[s]))})).join(t):i?encodeURIComponent(r(i))+n+encodeURIComponent(r(e)):""};var a=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 s=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 a={};function o(e,t,n){function o(e,n,r){return"string"==typeof t?t:t(e,n,r)}n||(n=Error);var s=function(e){function t(t,n,r){return e.call(this,o(t,n,r))||this}return r(t,e),t}(n);s.prototype.name=n.name,s.prototype.code=e,a[e]=s}function s(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,a;if("string"==typeof t&&i(t,"not ")?(r="must not be",t=t.replace(/^not /,"")):r="must be",c(e," argument"))a="The ".concat(e," ").concat(r," ").concat(s(t,"type"));else{var o=l(e,".")?"property":"argument";a='The "'.concat(e,'" ').concat(o," ").concat(r," ").concat(s(t,"type"))}return a+=". 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=a},{}],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 a=e("./_stream_readable"),o=e("./_stream_writable");e("inherits")(l,a);for(var s=r(o.prototype),i=0;i<s.length;i++){var c=s[i];l.prototype[c]||(l.prototype[c]=o.prototype[c])}function l(e){if(!(this instanceof l))return new l(e);a.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=a;var r=e("./_stream_transform");function a(e){if(!(this instanceof a))return new a(e);r.call(this,e)}e("inherits")(a,r),a.prototype._transform=function(e,t,n){n(null,e)}},{"./_stream_transform":59,inherits:24}],58:[function(e,t,n){(function(n,r){(function(){var a;t.exports=E,E.ReadableState=T,e("events").EventEmitter;var o=function(e,t){return e.listeners(t).length},s=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,m,g=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,s);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){a=a||e("./_stream_duplex"),t=t||{},"boolean"!=typeof r&&(r=n instanceof a),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=v(this,t,"readableHighWaterMark",r),this.buffer=new g,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(a=a||e("./_stream_duplex"),!(this instanceof E))return new E(t);var n=this instanceof a;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)),s.call(this)}function A(e,t,n,r,a){u("readableAddChunk",t);var o,s=e._readableState;if(null===t)s.reading=!1,x(e,s);else if(a||(o=P(s,t)),o)_(e,o);else if(s.objectMode||t&&t.length>0)if("string"==typeof t||s.objectMode||Object.getPrototypeOf(t)===i.prototype||(t=l(t)),r)s.endEmitted?_(e,new S):R(e,s,t,!0);else if(s.ended)_(e,new C);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!n?(t=s.decoder.write(t),s.objectMode||0!==t.length?R(e,s,t,!1):N(e,s)):R(e,s,t,!1)}else r||(s.reading=!1,N(e,s));return!s.ended&&(s.length<s.highWaterMark||0===s.length)}function R(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)),N(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,a="";null!==r;)a+=n.write(r.data),r=r.next;return this._readableState.buffer.clear(),""!==a&&this._readableState.buffer.push(a),this._readableState.length=a.length,this};var M=1073741824;function j(e){return e>=M?e=M:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function U(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=j(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,q(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(q,e))}function q(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,z(e)}function N(e,t){t.readingMore||(t.readingMore=!0,n.nextTick(B,e,t))}function B(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 L(e){return function(){var t=e._readableState;u("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&o(e,"data")&&(t.flowing=!0,z(e))}}function F(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(Q,e,t))}function Q(e,t){u("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),z(e),t.flowing&&!t.reading&&e.read(0)}function z(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(J,t,e))}function J(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 W(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=U(e,t))&&t.ended)return 0===t.length&&H(this),null;var r,a=t.needReadable;return u("need readable",a),(0===t.length||t.length-e<t.highWaterMark)&&u("length less than watermark",a=!0),t.ended||t.reading?u("reading or ended",a=!1):a&&(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=U(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,a=this._readableState;switch(a.pipesCount){case 0:a.pipes=e;break;case 1:a.pipes=[a.pipes,e];break;default:a.pipes.push(e)}a.pipesCount+=1,u("pipe count=%d opts=%j",a.pipesCount,t);var s=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()}a.endEmitted?n.nextTick(s):r.once("end",s),e.on("unpipe",i);var l=L(r);e.on("drain",l);var d=!1;function h(){u("cleanup"),e.removeListener("close",m),e.removeListener("finish",g),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,!a.awaitDrain||e._writableState&&!e._writableState.needDrain||l()}function p(t){u("ondata");var n=e.write(t);u("dest.write",n),!1===n&&((1===a.pipesCount&&a.pipes===e||a.pipesCount>1&&-1!==W(a.pipes,e))&&!d&&(u("false write response, pause",a.awaitDrain),a.awaitDrain++),r.pause())}function f(t){u("onerror",t),y(),e.removeListener("error",f),0===o(e,"error")&&_(e,t)}function m(){e.removeListener("finish",g),y()}function g(){u("onfinish"),e.removeListener("close",m),y()}function y(){u("unpipe"),r.unpipe(e)}return r.on("data",p),O(e,"error",f),e.once("close",m),e.once("finish",g),e.emit("pipe",r),a.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,a=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o<a;o++)r[o].emit("unpipe",this,{hasUnpiped:!1});return this}var s=W(t.pipes,e);return-1===s||(t.pipes.splice(s,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=s.prototype.on.call(this,e,t),a=this._readableState;return"data"===e?(a.readableListening=this.listenerCount("readable")>0,!1!==a.flowing&&this.resume()):"readable"===e&&(a.endEmitted||a.readableListening||(a.readableListening=a.needReadable=!0,a.flowing=!1,a.emittedReadable=!1,u("on readable",a.length,a.reading),a.length?D(this):a.reading||n.nextTick(K,this))),r},E.prototype.addListener=E.prototype.on,E.prototype.removeListener=function(e,t){var r=s.prototype.removeListener.call(this,e,t);return"readable"===e&&n.nextTick(F,this),r},E.prototype.removeAllListeners=function(e){var t=s.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||n.nextTick(F,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 a 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(a){u("wrapped data"),n.decoder&&(a=n.decoder.write(a)),n.objectMode&&null==a||(n.objectMode||a&&a.length)&&(t.push(a)||(r=!0,e.pause()))})),e)void 0===this[a]&&"function"==typeof e[a]&&(this[a]=function(t){return function(){return e[t].apply(e,arguments)}}(a));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===m&&(m=e("./internal/streams/from")),m(E,t,n)})}).call(this)}).call(this,e("_process"),void 0!==Nt?Nt:"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,a=r.ERR_METHOD_NOT_IMPLEMENTED,o=r.ERR_MULTIPLE_CALLBACK,s=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 a=this._readableState;a.reading=!1,(a.needReadable||a.length<a.highWaterMark)&&this._read(a.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 s;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 a("_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 a=this._readableState;(r.needTransform||a.needReadable||a.length<a.highWaterMark)&&this._read(a.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 a(e){var t=this;this.next=null,this.entry=null,this.finish=function(){Q(t,e)}}var o;t.exports=T,T.WritableState=O;var s={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,m=e("../errors").codes,g=m.ERR_INVALID_ARG_TYPE,y=m.ERR_METHOD_NOT_IMPLEMENTED,v=m.ERR_MULTIPLE_CALLBACK,b=m.ERR_STREAM_CANNOT_PIPE,w=m.ERR_STREAM_DESTROYED,C=m.ERR_STREAM_NULL_VALUES,I=m.ERR_STREAM_WRITE_AFTER_END,S=m.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 s=!1===t.decodeStrings;this.decodeStrings=!s,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 a(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,a){var o;return null===r?o=new C:"string"==typeof r||t.objectMode||(o=new g("chunk",["string","Buffer"],r)),!o||(_(e,o),n.nextTick(a,o),!1)}function R(e,t,n){return e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=c.from(t,n)),t}function P(e,t,n,r,a,o){if(!n){var s=R(t,r,a);r!==s&&(n=!0,a="buffer",r=s)}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:a,isBuf:n,callback:o,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else M(e,t,!1,i,r,a,o);return c}function M(e,t,n,r,a,o,s){t.writelen=r,t.writecb=s,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new w("write")):n?e._writev(a,t.onwrite):e._write(a,o,t.onwrite),t.sync=!1}function j(e,t,r,a,o){--t.pendingcb,r?(n.nextTick(o,a),n.nextTick(K,e,t),e._writableState.errorEmitted=!0,_(e,a)):(o(a),e._writableState.errorEmitted=!0,_(e,a),K(e,t))}function U(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function x(e,t){var r=e._writableState,a=r.sync,o=r.writecb;if("function"!=typeof o)throw new v;if(U(r),t)j(e,r,a,t,o);else{var s=B(r)||e.destroyed;s||r.corked||r.bufferProcessing||!r.bufferedRequest||N(e,r),a?n.nextTick(D,e,r,s,o):D(e,r,s,o)}}function D(e,t,n,r){n||q(e,t),t.pendingcb--,r(),K(e,t)}function q(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}function N(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var r=t.bufferedRequestCount,o=new Array(r),s=t.corkedRequestsFree;s.entry=n;for(var i=0,c=!0;n;)o[i]=n,n.isBuf||(c=!1),n=n.next,i+=1;o.allBuffers=c,M(e,t,!0,t.length,o,"",s.finish),t.pendingcb++,t.lastBufferedRequest=null,s.next?(t.corkedRequestsFree=s.next,s.next=null):t.corkedRequestsFree=new a(t),t.bufferedRequestCount=0}else{for(;n;){var l=n.chunk,d=n.encoding,u=n.callback;if(M(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 B(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function L(e,t){e._final((function(n){t.pendingcb--,n&&_(e,n),t.prefinished=!0,e.emit("prefinish"),K(e,t)}))}function F(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(L,e,t)))}function K(e,t){var n=B(t);if(n&&(F(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 Q(e,t,n){var r=e.entry;for(e.entry=null;r;){var a=r.callback;t.pendingcb--,a(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:s.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,a=!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++,a=P(this,r,o,e,t,n)),a},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||N(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!==Nt?Nt:"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 a(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"),s=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[s];if(null!==t){var n=e[h].read();null!==n&&(e[d]=null,e[s]=null,e[i]=null,t(p(n,!1)))}}function m(e){n.nextTick(f,e)}function g(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((a(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,a=this[d];if(a)r=new Promise(g(a,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})),a(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,(a(t={},h,{value:e,writable:!0}),a(t,s,{value:null,writable:!0}),a(t,i,{value:null,writable:!0}),a(t,c,{value:null,writable:!0}),a(t,l,{value:e._readableState.endEmitted,writable:!0}),a(t,u,{value:function(e,t){var r=n[h].read();r?(n[d]=null,n[s]=null,n[i]=null,e(p(r,!1))):(n[s]=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[s]=null,n[i]=null,t(e)),void(n[c]=e)}var r=n[s];null!==r&&(n[d]=null,n[s]=null,n[i]=null,r(p(void 0,!0))),n[l]=!0})),e.on("readable",m.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 a(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 s(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(){s(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 a=t.data,o=e>a.length?a.length:e;if(o===a.length?r+=a:r+=a.slice(0,e),0==(e-=o)){o===a.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=a.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 a=n.data,o=e>a.length?a.length:e;if(a.copy(t,t.length-e,0,o),0==(e-=o)){o===a.length?(++r,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=a.slice(o));break}++r}return this.length-=r,t}},{key:u,value:function(e,t){return d(this,a({},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(s,this,t)):e.nextTick(s,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(a,o):(o._writableState.errorEmitted=!0,e.nextTick(r,o,t)):e.nextTick(r,o,t):n?(e.nextTick(a,o),n(t)):e.nextTick(a,o)})),this)}function r(e,t){s(e,t),a(e)}function a(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 s(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 a(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=new Array(n),a=0;a<n;a++)r[a]=arguments[a];e.apply(this,r)}}}function o(){}function s(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=a(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)},m=function(t){n.call(e,t)},g=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 s(e)?(e.on("complete",h),e.on("abort",g),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",m),e.on("close",g),function(){e.removeListener("complete",h),e.removeListener("abort",g),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",m),e.removeListener("close",g)}}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 a(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var o=e("../../../errors").codes,s=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,s){s=a(s);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 s(e);c=!0,s()}));var d=!1;return function(e){if(!c&&!d)return d=!0,l(t)?t.abort():"function"==typeof t.destroy?t.destroy():void s(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,a=p(t);if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new s("streams");var o=t.map((function(e,n){var s=n<t.length-1;return d(e,s,n>0,(function(e){r||(r=e),e&&o.forEach(u),s||(o.forEach(u),a(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 a(e,t,n){return null!=e.highWaterMark?e.highWaterMark:t?e[n]:null}function o(e,t,n,o){var s=a(t,o,n);if(null!=s){if(!isFinite(s)||Math.floor(s)!==s||s<0)throw new r(o?n:"highWaterMark",s);return Math.floor(s)}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 a(){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=a},{}],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?a(e):e.proto?o:r;function t(e,t){for(var r=Object.keys(e),a=new Array(r.length),o=0;o<r.length;o++){var s=r[o],i=e[s];"object"!=typeof i||null===i?a[s]=i:i instanceof Date?a[s]=new Date(i):ArrayBuffer.isView(i)?a[s]=n(i):a[s]=t(i)}return a}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 a={};for(var o in e)if(!1!==Object.hasOwnProperty.call(e,o)){var s=e[o];"object"!=typeof s||null===s?a[o]=s:s instanceof Date?a[o]=new Date(s):s instanceof Map?a[o]=new Map(t(Array.from(s),r)):s instanceof Set?a[o]=new Set(t(Array.from(s),r)):ArrayBuffer.isView(s)?a[o]=n(s):a[o]=r(s)}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 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 a in e){var s=e[a];"object"!=typeof s||null===s?r[a]=s:s instanceof Date?r[a]=new Date(s):s instanceof Map?r[a]=new Map(t(Array.from(s),o)):s instanceof Set?r[a]=new Set(t(Array.from(s),o)):ArrayBuffer.isView(s)?r[a]=n(s):r[a]=o(s)}return r}}function a(e){var t=[],r=[];return e.proto?s:o;function a(e,a){for(var o=Object.keys(e),s=new Array(o.length),i=0;i<o.length;i++){var c=o[i],l=e[c];if("object"!=typeof l||null===l)s[c]=l;else if(l instanceof Date)s[c]=new Date(l);else if(ArrayBuffer.isView(l))s[c]=n(l);else{var d=t.indexOf(l);s[c]=-1!==d?r[d]:a(l)}}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 a(e,o);if(e instanceof Map)return new Map(a(Array.from(e),o));if(e instanceof Set)return new Set(a(Array.from(e),o));var s={};for(var i in t.push(e),r.push(s),e)if(!1!==Object.hasOwnProperty.call(e,i)){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(a(Array.from(c),o));else if(c instanceof Set)s[i]=new Set(a(Array.from(c),o));else if(ArrayBuffer.isView(c))s[i]=n(c);else{var l=t.indexOf(c);s[i]=-1!==l?r[l]:o(c)}}return t.pop(),r.pop(),s}function s(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return a(e,s);if(e instanceof Map)return new Map(a(Array.from(e),s));if(e instanceof Set)return new Set(a(Array.from(e),s));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(a(Array.from(c),s));else if(c instanceof Set)o[i]=new Set(a(Array.from(c),s));else if(ArrayBuffer.isView(c))o[i]=n(c);else{var l=t.indexOf(c);o[i]=-1!==l?r[l]:s(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"),a=r.Buffer;function o(e,t){for(var n in e)t[n]=e[n]}function s(e,t,n){return a(e,t,n)}a.from&&a.alloc&&a.allocUnsafe&&a.allocUnsafeSlow?t.exports=r:(o(r,n),n.Buffer=s),s.prototype=Object.create(a.prototype),o(a,s),s.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return a(e,t,n)},s.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=a(e);return void 0!==t?"string"==typeof n?r.fill(t,n):r.fill(t):r.fill(0),r},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return a(e)},s.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(a(t)):null}function a(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,a=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 s(e){var t=o(e);if("string"!=typeof t&&(r.isEncoding===a||!a(e)))throw new Error("Unknown encoding: "+e);return t||e}function i(e){var t;switch(this.encoding=s(e),this.encoding){case"utf16le":this.text=f,this.end=m,t=4;break;case"utf8":this.fillLast=u,t=4;break;case"base64":this.text=g,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 a=c(t[r]);return a>=0?(a>0&&(e.lastNeed=a-1),a):--r<n||-2===a?0:(a=c(t[r]))>=0?(a>0&&(e.lastNeed=a-2),a):--r<n||-2===a?0:(a=c(t[r]))>=0?(a>0&&(2===a?a=0:e.lastNeed=a-3),a):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 m(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 g(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"),a=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 s=/^([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}$/,m=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,g={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&&a.isObject(e)&&e instanceof o)return e;var r=new o;return r.parse(e,t,n),r}function C(e){return a.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(!a.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=s.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!==(R=C.indexOf(h[A]))&&(-1===E||R<E)&&(E=R);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 R;-1!==(R=C.indexOf(u[A]))&&(-1===E||R<E)&&(E=R)}-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 M=this.hostname.split(/\./),j=(A=0,M.length);A<j;A++){var U=M[A];if(U&&!U.match(f)){for(var x="",D=0,q=U.length;D<q;D++)U.charCodeAt(D)>127?x+="x":x+=U[D];if(!x.match(f)){var N=M.slice(0,A),B=M.slice(A+1),L=U.match(m);L&&(N.push(L[1]),B.unshift(L[2])),B.length&&(C="/"+B.join(".")+C),this.hostname=N.join(".");break}}}this.hostname.length>p?this.hostname="":this.hostname=this.hostname.toLowerCase(),P||(this.hostname=r.toASCII(this.hostname));var F=this.port?":"+this.port:"",K=this.hostname||"";this.host=K+F,this.href+=this.host,P&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==C[0]&&(C="/"+C))}if(!g[_])for(A=0,j=d.length;A<j;A++){var $=d[A];if(-1!==C.indexOf($)){var Q=encodeURIComponent($);Q===$&&(Q=escape($)),C=C.split($).join(Q)}}var z=C.indexOf("#");-1!==z&&(this.hash=C.substr(z),C=C.slice(0,z));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){F=this.pathname||"";var H=this.search||"";this.path=F+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,s="";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&&a.isObject(this.query)&&Object.keys(this.query).length&&(s=b.stringify(this.query));var i=this.search||s&&"?"+s||"";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(a.isString(e)){var t=new o;t.parse(e,!1,!0),e=t}for(var n=new o,r=Object.keys(this),s=0;s<r.length;s++){var i=r[s];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 m=n.pathname||"",g=n.search||"";n.path=m+g}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(!a.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,a.isNull(n.pathname)&&a.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,R=""===S[0]||S[0]&&"/"===S[0].charAt(0);return _&&(n.hostname=n.host=R?"":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)&&!R&&S.unshift(""),S.length?n.pathname=S.join("/"):(n.pathname=null,n.path=null),a.isNull(n.pathname)&&a.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 a(){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 a}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!==Nt?Nt:"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),a=t[t.length-1];return"function"==typeof r&&r!==a&&Object.keys(a).forEach((function(e){r[e]=a[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=a;var r=Object.prototype.hasOwnProperty;function a(){for(var e={},t=0;t<arguments.length;t++){var n=arguments[t];for(var a in n)r.call(n,a)&&(e[a]=n[a])}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,a=arguments.length;n<a;n++)t.push(arguments[n]);return t}function a(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 s(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++)s(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,a=this.head;null!==a;)n.push(e.call(t,a.value,this)),a=a.next;return n},r.prototype.mapReverse=function(e,t){t=t||this;for(var n=new r,a=this.tail;null!==a;)n.push(e.call(t,a.value,this)),a=a.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 a=0;null!==r;a++)n=e(n,r.value,a),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 a=this.length-1;null!==r;a--)n=e(n,r.value,a),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 a=0,o=this.head;null!==o&&a<e;a++)o=o.next;for(;null!==o&&a<t;a++,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 a=this.length,o=this.tail;null!==o&&a>t;a--)o=o.prev;for(;null!==o&&a>e;a--,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 s=[];for(r=0;o&&r<t;r++)s.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=a(this,o,n[r]);return s},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 Kt=Bt(Ft.exports);class $t{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 Qt=()=>"undefined"!=typeof window&&window.localStorage?window:{localStorage:new $t},zt=()=>w.default.v4().toString();let Vt=0;if("undefined"!=typeof BroadcastChannel&&"undefined"!=typeof window){const e=zt(),t={},n=new BroadcastChannel("amity_ts_sdk");let r;n.postMessage({type:"startup",tabId:e}),n.onmessage=({data:a})=>{a.tabId!==e&&("startup"===a.type&&n.postMessage({type:"identify",tabId:e,tabIndex:Vt}),"identify"===a.type&&void 0!==a.tabIndex&&a.tabId&&(t[a.tabId]=a.tabIndex,r||(r=setTimeout((()=>{const e=Object.values(t).sort();e&&0!==e.length&&(Vt=e.reduce(((e,t)=>e<t?e:t+1),0))}),15))))}}const Ht=async()=>{var e;const t=`${null!==(e=Re().prefixDeviceIdKey)&&void 0!==e?e:""}#deviceId`,n=await(async e=>{if("undefined"!=typeof navigator&&"ReactNative"===navigator.product)return await b.default.getItem(e);return new Promise((t=>{t(Qt().localStorage.getItem(e))}))})(t);if(n)return n;const r=`ascWebSdk#${zt()}`;return await(async(e,t)=>"undefined"!=typeof navigator&&"ReactNative"===navigator.product?(await b.default.setItem(e,t),!0):new Promise((n=>{Qt().localStorage.setItem(e,t),n(!0)})))(t,r),r},Jt=()=>{const e=(()=>{var e,t;return(null===(e=Ot.versions)||void 0===e?void 0:e.node)?Ot.versions.node:navigator?`${navigator.product.toLowerCase()}#${null!==(t=navigator.userAgent)&&void 0!==t?t:"unknown_agent"}`:"unknown_model"})();return{kind:"web",model:e,sdkVersion:z}},Wt=1e3;var Gt;!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"}(Gt||(Gt={}));const Yt=e=>{let t,n="disconnected";const r=new Set,a=e=>{n!==e&&(n=e,r.forEach((t=>{t(e)})))};return{connect:async function(n){const r=await(async e=>`mqttjs_${await Ht()}_${e}_${Vt}`)(n.userId);return a("connecting"),t&&(a("disconnecting"),t.removeAllListeners(),t.end(!0)),t=Kt.connect(e,function(e){return Object.assign({clean:!1,clientId:`mqttjs_ + ${Math.random().toString(16).substring(2,10)}`,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:Wt,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=Wt,a("connected"),(()=>{const e=[St(vt()),St(bt()),St(wt()),St(Ct()),St(mt(tt())),St(yt()),St(It())]})()})),t.on("error",(e=>{switch(e.code){case 2:case 134:case 135:t.end(),a("disconnected")}})),t.on("reconnect",(()=>{a("reconnecting"),t.options.reconnectPeriod=Math.min(2*(t.options.reconnectPeriod||Wt),8e3)})),t.on("close",(()=>{a("disconnected")})),t.on("disconnect",(()=>{a("disconnected")})),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()))))},reconnect:async()=>new Promise((e=>{null==t||t.reconnect(),e()})),listen:e=>(r.add(e),n&&e(n),()=>{r.delete(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 a;if(t||128===(null===(a=r[0])||void 0===a?void 0:a.qos)){const r=t?new _e(t.message,8e5,"error"):new Oe(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)}}},Xt=(e={},t,n=!0)=>{Object.entries(e).forEach((([e,r])=>{const a=Ie[e];if(!a)return;const o=Ce(a);o&&r.forEach((e=>{(n?Ue:De)([a,"get",o(e)],e,t)}))}))},Zt=(e,t)=>{const{log:n,cache:r}=Re(),a=[e,Z,t],o={cachedAt:Date.now()};r&&(n("cache/api/pushToTombstone",{cacheKey:a,data:o}),qe([e,"get",t],!0),Ue(a,o))};function en(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 a=0;for(r=Object.getOwnPropertySymbols(e);a<r.length;a++)t.indexOf(r[a])<0&&Object.prototype.propertyIsEnumerable.call(e,r[a])&&(n[r[a]]=e[r[a]])}return n}const tn=(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(!Re().cache)return;return(null===(n=je(["user","get",e[t]]))||void 0===n?void 0:n.data)||void 0}},e))(e,t,n))))&&void 0!==r?r:e},nn=(e,t,n="userId",r="user")=>{const a=e,o=t,s=a[o],i=en(a,["symbol"==typeof o?o:o+""]),c=tn(s,n,r);return Object.assign(Object.assign({},i),{[t]:c})};function rn(e){return e.map((e=>{var{isMentioned:t}=e,n=en(e,["isMentioned"]);return Object.assign({hasMentioned:t},n)}))}function an(e){return rn(e)}function on(e){return rn(e)}const sn=e=>{var t,n;return null!==(n=null===(t=je(["messagePreviewChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},cn=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=je(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),ln=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:a,messageFeedId:o,data:s,dataType:i,isDeleted:c,segment:l,creatorPublicId:d,createdAt:u,updatedAt:h}=t;return{channelId:a,subChannelId:o,data:s,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:[]};Xt(r)},dn=e=>{var t,n;return null!==(n=null===(t=je(["messagePreviewSubChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},un=e=>{var t;const n=e.messagePreviewId?dn(e.subChannelId):null,r=n?Object.assign(Object.assign({},n),{user:null===(t=je(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data}):null;return Object.assign(Object.assign({},e),{messagePreview:r})},hn=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:a,messageFeedId:o,messageId:s,creatorPublicId:i,data:c,dataType:l,isDeleted:d,segment:u,createdAt:h,updatedAt:p}=t;return{messagePreviewId:s,channelId:a,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:[]};Xt(r)};function pn(e,t){return Object.create(Object.getPrototypeOf(e),Object.assign(Object.assign({},Object.getOwnPropertyDescriptors(e)),Object.getOwnPropertyDescriptors(t)))}function fn(e,t,n){Ue(["subChannel","get",e],pn(t,n))}const mn=(e,t)=>{const{log:n,cache:r}=Re(),a=[e,Z,t];if(!r)return;n("cache/api/isInTombstone",a);const o=je(a),{lifeSpan:s}=ye("cache_then_server",18e4);if(o&&me(o.data,s))throw new ke("Item not found!",400400,"error")},gn=e=>{var t;const n=["channelUnreadInfo","get",e],r=null===(t=je(n))||void 0===t?void 0:t.data,a=Me(["subChannelUnreadInfo","get"]);let o=0,s=!1;if(a&&(null==a?void 0:a.length)>0){const t=null==a?void 0:a.filter((({data:t})=>t.channelId===e&&!t.isDeleted));o=t.map((({data:e})=>e.unreadCount)).reduce(((e,t)=>e+t),0),s=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:s});return Ue(n,i),i},yn=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,a={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};Xt({subChannelUnreadInfo:[a]}),e.includes(n.entityId)||e.push(n.entityId)}})),e.forEach((e=>{gn(e)}))}},vn=async()=>{const e=Re();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&&Xt({userMarkers:n},{cachedAt:r}),ct("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}},bn=e=>!0===e&&void 0;function wn(e,t,n){var r,a;if(n)return n.hasMentioned;const o=Re();if(o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()){const e=null===(r=je(["subChannelUnreadInfo","get",t]))||void 0===r?void 0:r.data;return!!e&&e.isMentioned}const s={entityId:e,feedId:t,userId:tt()._id},i=null===(a=je(["subChannelMarker","get",Ce("subChannelMarker")(s)]))||void 0===a?void 0:a.data;return!!i&&i.hasMentioned}const Cn=["broadcast","conversation","community"],In=({channelType:e})=>Cn.includes(e);function Sn(e){var{channelId:t,channelPublicId:n,channelType:r,childCount:a,creatorId:o,creatorPublicId:s,lastMessageId:i,lastMessageTimestamp:c,messageFeedId:l,name:d}=e,u=en(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,a;if(n)return n.unreadCount;const o=Re();if(o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()){const e=null===(r=je(["subChannelUnreadInfo","get",t]))||void 0===r?void 0:r.data;return e?e.isDeleted?0:e.unreadCount:0}const s={entityId:e,feedId:t,userId:tt()._id},i=null===(a=je(["subChannelMarker","get",Ce("subChannelMarker")(s)]))||void 0===a?void 0:a.data;return i?i.unreadCount:0}(t,l)},get hasMentioned(){return wn(t,l)},get isMentioned(){return wn(t,l)}},u),{channelId:n,creatorId:s,displayName:d,lastActivity:c,latestMessageId:i,messageCount:a,subChannelId:l,isUnreadCountSupport:In({channelType:r})})}function _n(e,t,n){var r;const a=(e=>{var t,n,r;const a=null===(n=null===(t=Me(["message","get"]))||void 0===t?void 0:t.find((({data:t})=>t.messageId===e.messageId)))||void 0===n?void 0:n.data;return a?Object.assign(Object.assign(Object.assign({},a),e),{referenceId:null!==(r=a.referenceId)&&void 0!==r?r:e.referenceId}):e})(e),{channelPublicId:o,childCount:s,creatorPublicId:i,mentionedUsers:c,messageFeedId:l,myReactions:d,reactionCount:u,reactions:h,referenceId:p,segment:f,messageId:m,creatorId:g}=a,y=en(a,["channelPublicId","childCount","creatorPublicId","mentionedUsers","messageFeedId","myReactions","reactionCount","reactions","referenceId","segment","messageId","creatorId"]);let v;p&&(v=je(["message","get",p])),v||(v=je(["message","get",m]));const b=Object.assign(Object.assign({},y),{messageId:m,channelId:o,channelSegment:f,childrenNumber:s,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:m,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=Re(),a=je(["message","get",e.messageId]),o=(null==a?void 0:a.data.myReactions)||[];Object.assign(e,{myReactions:o});const s=t[0];s&&s.userId===r.userId&&("message.reactionAdded"!==n||o.includes(s.reactionName)||Object.assign(e,{myReactions:[...o,s.reactionName]}),"message.reactionRemoved"===n&&o.includes(s.reactionName)&&Object.assign(e,{myReactions:o.filter((e=>e!==s.reactionName))}))})(b,t,n),b}const kn={},On=async(e,t)=>{const n=e.messages.map((({messageId:e})=>e));if(n.length>0){Xt({messages:(r=e).messages.map((e=>_n(e,r.reactions)))});const t=n.join("");kn[t]&&clearTimeout(kn[t]),kn[t]=setTimeout((()=>{try{(async e=>{const t=Re();t.log("channel/getMessageMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/messages",{params:{messageIds:e}}),{contentMarkers:r,feedMarkers:a,userMarkers:o}=n,s=t.cache&&Date.now();t.cache&&Xt({contentMarkers:r,feedMarkers:a,userMarkers:o},{cachedAt:s}),ct("local.feedMarker.fetched",{feedMarkers:a}),ct("local.messageMarker.fetched",{contentMarkers:r}),ct("local.userMarker.fetched",{userMarkers:o})})(n)}catch(e){}}),2e3)}var r;const{messageFeeds:a}=e,o=en(e,["messageFeeds"]);return a&&a.length>0&&(null==a||a.forEach((e=>{var t,n;const r=null!==(n=null===(t=je(["subChannel","get",e.messageFeedId]))||void 0===t?void 0:t.data)&&void 0!==n?n:{},a=en(Sn(e),["unreadCount","isMentioned"]);fn(e.messageFeedId,r,a)}))),Object.assign(Object.assign({},o),{messages:e.messages.map((n=>_n(n,e.reactions,t)))})};function Tn(e){var{subChannelId:t,mentionees:n,dataType:r,data:a}=e,o=en(e,["subChannelId","mentionees","dataType","data"]);return r===U.IMAGE||r===U.FILE?Object.assign({messageFeedId:t,mentionedUsers:n,dataType:r,data:Object.assign({caption:""},a)},o):Object.assign({messageFeedId:t,mentionedUsers:n,dataType:r,data:a},o)}function En(e){var{sortBy:t,subChannelId:n,includingTags:r,excludingTags:a,includeDeleted:o,aroundMessageId:s,limit:i,type:c}=e,l=en(e,["sortBy","subChannelId","includingTags","excludingTags","includeDeleted","aroundMessageId","limit","type"]);const d=Object.assign(Object.assign({},l),{messageFeedId:n,isDeleted:bn(o),options:{sortBy:t,limit:i||V,around:s}});return r&&(d.includeTags=r),c&&(d.dataType=c),a&&(d.excludeTags=a),d}function An(e){return Object.assign(Object.assign({},e),{isGlobalBanned:(null==e?void 0:e.isGlobalBan)||!1})}const Rn=["broadcast","conversation","community"],Pn=({channelType:e})=>Rn.includes(e),Mn=async e=>{const t=e.messageFeeds.filter(Pn).map((({messageFeedId:e})=>e));if(t.length>0){(e=>{Xt({messageFeeds:e.messageFeeds.map((e=>Sn(e)))})})(e);try{await(async(e,t={limit:100})=>{const n=Re();n.log("channel/getSubChannelMarkers",e,t);const{data:r}=await n.http.get("/api/v1/markers/message-feeds",{params:{messageFeedIds:e,options:{token:le(t,"skiplimit")}}}),{paging:a}=r,o=en(r,["paging"]),{userEntityMarkers:s,userFeedMarkers:i,userMarkers:c,feedMarkers:l}=o;n.isUnreadCountEnabled&&n.getMarkerSyncConsistentMode()&&yn({feedMarkers:l,userFeedMarkers:i});const d=an(s),u=on(i),h=n.cache&&Date.now();n.cache&&Xt({userEntityMarkers:d,userFeedMarkers:u,userMarkers:c},{cachedAt:h}),ct("local.channelMarker.fetched",{userEntityMarkers:d}),ct("local.subChannelMarker.fetched",{userFeedMarkers:u}),ct("local.userMarker.fetched",{userMarkers:c});const p=de(a.next);return{data:u,cachedAt:h,prevPage:de(a.previous),nextPage:p}})(t)}catch(e){}}hn(e);const n=e.messageFeeds.map(Sn),r=e.messages.map((e=>_n(e))),a=e.users.map(An);return Object.assign(Object.assign({},e),{messageFeeds:n,messages:r,users:a})};const jn=async e=>{const t=Re();t.log("channel/getSubChannel",e),mn("subChannel",e);try{const n=await t.http.get(`/api/v5/message-feeds/${encodeURIComponent(e)}`),r=await Mn(n.data),a=t.cache&&Date.now();return t.cache&&Xt(r,{cachedAt:a}),ct("local.message-feed.fetched",r),{data:r.messageFeeds[0],cachedAt:a}}catch(t){throw ae(null==t?void 0:t.code)&&Zt("subChannel",e),t}};jn.locally=e=>{const t=Re();if(t.log("channel/getSubChannel.locally",e),!t.cache)return;const n=je(["subChannel","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Un=e=>new Date(e).getTime(),xn=async e=>{var t;let n=null===(t=je(["subChannel","get",e]))||void 0===t?void 0:t.data;return n||(n=(await jn(e)).data),n},Dn=async e=>{const t=await(async()=>Re().getMessagePreviewSetting(!1))(),{channelId:n,messageId:r,creatorId:a,createdAt:o,updatedAt:s,data:i,dataType:c,subChannelId:l,channelSegment:d,isDeleted:u}=e,h=await xn(l);"no-message-preview"!==t?(e=>{var t;const n=null===(t=je(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;return!n||n.segment<=e.channelSegment||Un(n.createdAt)<=Un(e.createdAt)})(e)&&(Ue(["messagePreviewSubChannel","get",e.subChannelId],{channelId:n,creatorId:a,messagePreviewId:r,createdAt:o,updatedAt:s,subChannelId:l,data:i,dataType:c,segment:d,isDeleted:u,subChannelUpdatedAt:null==h?void 0:h.updatedAt,subChannelName:null==h?void 0:h.displayName}),fn(e.subChannelId,h,{lastActivity:o,messagePreviewId:r})):Un(h.lastActivity)<Un(o)&&fn(e.subChannelId,h,{lastActivity:o})},qn=async e=>{var t;const{channelId:n,messageId:r,creatorId:a,createdAt:o,updatedAt:s,data:i,dataType:c,subChannelId:l,channelSegment:d,isDeleted:u}=e,h=null===(t=je(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await xn(l);Ue(["messagePreviewSubChannel","get",e.subChannelId],{channelId:n,creatorId:a,messagePreviewId:r,createdAt:o,updatedAt:s,subChannelId:l,data:i,dataType:c,segment:d,isDeleted:u,subChannelUpdatedAt:t.updatedAt,subChannelName:h.subChannelName})}},Nn=async e=>{const{channelId:t,messageId:n,creatorId:r,createdAt:a,updatedAt:o,data:s,dataType:i,subChannelId:c,channelSegment:l,isDeleted:d}=e;if((e=>{var t;const n=null===(t=je(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;return!n||Un(n.createdAt)<=Un(e.createdAt)})(e)){const u=await xn(c);Ue(["messagePreviewChannel","get",e.channelId],{channelId:t,creatorId:r,messagePreviewId:n,createdAt:a,updatedAt:o,subChannelId:c,data:s,dataType:i,segment:l,isDeleted:d,subChannelUpdatedAt:null==u?void 0:u.updatedAt,subChannelName:null==u?void 0:u.displayName})}},Bn=async e=>{var t;const{channelId:n,messageId:r,creatorId:a,createdAt:o,updatedAt:s,data:i,dataType:c,subChannelId:l,channelSegment:d,isDeleted:u}=e,h=null===(t=je(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await xn(l);Ue(["messagePreviewChannel","get",e.channelId],{channelId:n,creatorId:a,messagePreviewId:r,createdAt:o,updatedAt:s,subChannelId:l,data:i,dataType:c,segment:d,isDeleted:u,subChannelUpdatedAt:t.updatedAt,subChannelName:h.subChannelName})}},Ln=async e=>{var t,n,r,a;const{channelId:o,subChannelId:s}=e,i=null===(t=je(["messagePreviewChannel","get",o]))||void 0===t?void 0:t.data;if((null==i?void 0:i.subChannelId)===s){const e=null===(n=je(["subChannel","get",s]))||void 0===n?void 0:n.data;Ue(["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=je(["messagePreviewSubChannel","get",s]))||void 0===r?void 0:r.data;if(c&&new Date(c.updatedAt).valueOf()>new Date(e.updatedAt).valueOf()){const e=null===(a=je(["subChannel","get",s]))||void 0===a?void 0:a.data;Ue(["messagePreviewSubChannel","get",s],Object.assign(Object.assign({},c),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}},Fn=["broadcast","conversation","community"],Kn=({type:e})=>Fn.includes(e);function $n(e,t={isMessagePreviewUpdated:!0}){var n;let{messagePreviewId:r}=e;const a=null===(n=je(["messagePreviewChannel","get",e.channelId]))||void 0===n?void 0:n.data;return(null==a?void 0:a.messagePreviewId)&&!t.isMessagePreviewUpdated&&(r=a.messagePreviewId),Object.assign(Object.assign({},e),{defaultSubChannelId:e.channelInternalId,isUnreadCountSupport:Kn(e),messagePreviewId:r})}const Qn=(e,t={isMessagePreviewUpdated:!0})=>{Xt({channels:e.channels.map((e=>$n(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated})))})},zn=async(e,t={isMessagePreviewUpdated:!0})=>{const n=Re(),r=await n.getMessagePreviewSetting(!1);if(t.isMessagePreviewUpdated&&"no-message-preview"!==r&&e.messagePreviews&&e.messagePreviews.length>0&&ln(e),n.useLegacyUnreadCount)(({currentUserId:e,channels:t,channelUsers:n})=>{const r=[];for(let a=0;a<t.length;a+=1){const o=["channelUnread","get",t[a].channelId],s=n.find((n=>n.channelId===t[a].channelId&&n.userId===e));let i=0,c=null,l=null,d=!1;s&&(c=s.readToSegment,l=s.lastMentionedSegment,i=Math.max(t[a].messageCount-c,0),d=l>c);const u={channelId:t[a].channelId,lastSegment:t[a].messageCount,readToSegment:c,lastMentionedSegment:l,unreadCount:i,isMentioned:d,isDeleted:t[a].isDeleted||!1};Ue(o,u),r.push(u)}ct("local.channelUnread.updated",r)})({channels:e.channels,channelUsers:e.channelUsers,currentUserId:n.userId});else{const n=e.channels.filter(Kn).map((({channelInternalId:e})=>e));if(n.length>0){Qn(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated});try{await(async e=>{const t=Re();t.log("channel/getChannelMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/channels",{params:{channelIds:e}}),{userEntityMarkers:r,userMarkers:a}=n,o=an(r),s=t.cache&&Date.now();return t.cache&&Xt({userEntityMarkers:o,userMarkers:a},{cachedAt:s}),ct("local.channelMarker.fetched",{userEntityMarkers:o}),ct("local.userMarker.fetched",{userMarkers:a}),{data:o,cachedAt:s}})(n)}catch(e){}}}const a=e.channels.map((e=>$n(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated}))),o=e.channelUsers.map((e=>{return t=e,Object.assign(Object.assign({},t),{get user(){var e;if(Re().cache)return(null===(e=je(["user","get",t.userId]))||void 0===e?void 0:e.data)||void 0}});var t})),s=e.users.map(An),i=en(e,["messageFeedsInfo","messagePreviews"]);return Object.assign(Object.assign({},i),{users:s,channels:a,channelUsers:o})},Vn=async e=>{const t=Re();t.log("channel/getUserMessageFeedMakers",e);const{data:n}=await t.http.get("/api/v1/markers/user-message-feed",{params:{channelIds:e}});return ct("local.userMessageFeedMarker.fetched",{userMessageFeedMarker:n}),n},Hn=async e=>{const t=Re(),n=await Vn(e.channels.map((({channelInternalId:e})=>e))),{feedMarkers:r,userFeedMarkers:a}=n;yn({feedMarkers:r,userFeedMarkers:a}),t.log("channel/prepareUnreadCountInfo",e.channels)},Jn=(e,t)=>{var n,r,a,o;const s=Re();return s.isUnreadCountEnabled&&s.getMarkerSyncConsistentMode()?null!==(r=null===(n=(e=>{var t;return null===(t=je(["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===(a=(e=>{var t;const n={entityId:e,userId:tt()._id};return null===(t=je(["channelMarker","get",Ce("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===a?void 0:a.hasMentioned)&&void 0!==o&&o},Wn=(e,t)=>{var n,r,a,o,s;const i=Re();return i.isUnreadCountEnabled&&i.getMarkerSyncConsistentMode()?null!==(r=null===(n=(e=>{var t;return null===(t=je(["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!==(s=null!==(a=null==t?void 0:t.unreadCount)&&void 0!==a?a:null===(o=(e=>{var t;const n={entityId:e,userId:tt()._id};return null===(t=je(["channelMarker","get",Ce("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===o?void 0:o.unreadCount)&&void 0!==s?s:0},Gn=e=>{var t;return null===(t=je(["channelUnread","get",e]))||void 0===t?void 0:t.data},Yn=e=>{const t=Re(),n=en(e,["messageCount"]);return pn(n,{get unreadCount(){var e,t;return null!==(t=null===(e=Gn(n.channelId))||void 0===e?void 0:e.unreadCount)&&void 0!==t?t:0},get subChannelsUnreadCount(){return Wn(n)},get isMentioned(){var e,r;return t.useLegacyUnreadCount?null!==(r=null===(e=Gn(n.channelId))||void 0===e?void 0:e.isMentioned)&&void 0!==r&&r:Jn(n)}})},Xn=e=>Object.assign(Object.assign({},e),{get user(){return(()=>{var t;const n=["user","get",e.userId],r=null===(t=je(n))||void 0===t?void 0:t.data;return r?cn(r):void 0})()}}),Zn=e=>{const t=Re();t.log("channel/getMyMembership.locally");const n=je(["channelUsers","get",`${e}#${t.userId}`]);if(!n)throw new ke("Item not found!",400400,"error");return{data:n.data,cachedAt:n.cachedAt}};function er(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(!er(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=>er(e[n],t[n])))}const tr=[];let nr=null;const rr=e=>{if(0===tr.length){const e=Re();nr=it(e,"onChannelCreated","channel.created",(async e=>{const t=await zn(e);Xt(t),tr.forEach((e=>e(t.channels[0])))}))}return tr.push(e),()=>(e=>{const t=tr.indexOf(e);t>-1&&tr.splice(t,1),0===tr.length&&(null==nr||nr())})(e)},ar=[],or=[],sr=e=>{const t=Re();if(0===ar.length){const e=async e=>{const t=await zn(e);Xt(t),ar.forEach((e=>e(t.channels[0])))};or.push(it(t,"onChannelUpdated","channel.updated",e)),or.push(it(t,"onChannelUpdated","local.channel.updated",(e=>ar.forEach((t=>t(e.channels[0]))))))}return ar.push(e),()=>(e=>{const t=ar.indexOf(e);t>-1&&ar.splice(t,1),0===ar.length&&or.forEach((e=>e()))})(e)},ir=e=>{const t=Me(["subChannelUnreadInfo","get"]);if(t){(null==t?void 0:t.filter((({data:t})=>t.channelId===e))).forEach((({key:e,data:t})=>{Ue(e,Object.assign(Object.assign({},t),{isDeleted:!0}))}))}},cr=e=>{var t;const n=["channelUnreadInfo","get",e];(null===(t=je(n))||void 0===t?void 0:t.data)&&qe(n)},lr=[];let dr=null;const ur=e=>{if(0===lr.length){const e=Re(),t=async t=>{const n=await zn(t),r=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,a=e.useLegacyUnreadCount;n.channels.forEach((e=>{if(r)ir(e.channelId),cr(e.channelId);else if(a){const t=["channelUnread","get",e.channelId],n=je(t);n&&Ue(t,Object.assign(Object.assign({},n),{isDeleted:!0}))}})),Xt(n),lr.forEach((e=>e(n.channels[0])))};dr=it(e,"onChannelDeleted","channel.deleted",t)}return lr.push(e),()=>(e=>{const t=lr.indexOf(e);t>-1&&lr.splice(t,1),0===lr.length&&(null==dr||dr())})(e)},hr=[];let pr=null;const fr=e=>{if(0===hr.length){const e=Re();pr=it(e,"onChannelJoined","channel.joined",(async e=>{const t=await zn(e),{channels:n,channelUsers:r}=t;Xt(t),hr.forEach((e=>e(n[0],r[0])))}))}return hr.push(e),()=>(e=>{const t=hr.indexOf(e);t>-1&&hr.splice(t,1),0===hr.length&&(null==pr||pr())})(e)},mr=[];let gr=null;const yr=e=>{if(0===mr.length){const e=Re(),t=async t=>{const{userId:n}=Re(),{channelUsers:r}=t,a=r.some((e=>e.userId===n)),o=await zn(t,{isMessagePreviewUpdated:a}),s=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,i=e.useLegacyUnreadCount;a&&o.channels.forEach((e=>{s?(ir(e.channelId),cr(e.channelId)):i&&qe(["channelUnread","get",e.channelId])}));const{channels:c,channelUsers:l}=o;Xt(o),mr.forEach((e=>e(c[0],l[0])))};gr=it(e,"onChannelLeft","channel.left",t)}return mr.push(e),()=>(e=>{const t=mr.indexOf(e);t>-1&&mr.splice(t,1),0===mr.length&&(null==gr||gr())})(e)},vr=[];let br=null;const wr=e=>{if(0===vr.length){const e=Re(),t=async e=>{var t;De(["channel","get",e.channelId],{isMuted:Date.parse(e.muteTimeout)>Date.now()});const n=null===(t=je(["channel","get",e.channelId]))||void 0===t?void 0:t.data;n&&vr.forEach((e=>e(n)))};br=it(e,"onChannelMute","channel.setMuted",t)}return vr.push(e),()=>(e=>{const t=vr.indexOf(e);t>-1&&vr.splice(t,1),0===vr.length&&(null==br||br())})(e)},Cr=[];let Ir=null;const Sr=e=>{if(0===Cr.length){const e=Re();Ir=it(e,"onChannelMemberAdded","channel.membersAdded",(async e=>{const t=await zn(e),{channels:n,channelUsers:r}=t;Xt(t),Cr.forEach((e=>e(n[0],r.find((e=>"member"===e.membership)))))}))}return Cr.push(e),()=>(e=>{const t=Cr.indexOf(e);t>-1&&Cr.splice(t,1),0===Cr.length&&(null==Ir||Ir())})(e)},_r=[];let kr=null;const Or=e=>{if(0===_r.length){const e=Re();kr=it(e,"onChannelMemberRemoved","channel.membersRemoved",(async e=>{const t=await zn(e),{channels:n,channelUsers:r}=t;Xt(t),_r.forEach((e=>e(n[0],r[0])))}))}return _r.push(e),()=>(e=>{const t=_r.indexOf(e);t>-1&&_r.splice(t,1),0===_r.length&&(null==kr||kr())})(e)},Tr=[];let Er=null;const Ar=e=>{const t=Re();return Er=it(t,"onChannelMemberBanned","channel.banned",(async e=>{const n=await zn(e),{channels:r,channelUsers:a}=n,o=a.some((e=>"banned"===e.membership&&e.userId===t.userId));t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&o&&n.channels.forEach((e=>{ir(e.channelId),cr(e.channelId)})),Xt(n),Tr.forEach((e=>e(r[0],a.find((e=>"banned"===e.membership)))))})),Tr.push(e),()=>(e=>{const t=Tr.indexOf(e);t>-1&&Tr.splice(t,1),0===Tr.length&&(null==Er||Er())})(e)},Rr=[];let Pr=null;const Mr=e=>{if(0===Rr.length){const e=Re();Pr=it(e,"onChannelMemberUnbanned","channel.unbanned",(async e=>{const t=await zn(e),{channels:n,channelUsers:r}=t;Xt(t),Rr.forEach((e=>e(n[0],r.find((e=>"none"===e.membership)))))}))}return Rr.push(e),()=>(e=>{const t=Rr.indexOf(e);t>-1&&Rr.splice(t,1),0===Rr.length&&(null==Pr||Pr())})(e)},jr=[];let Ur=null;const xr=e=>{if(0===jr.length){const e=Re();Ur=it(e,"onChannelMemberRoleAdded","local.channel-moderator.role-added",(async e=>{const{channels:t,channelUsers:n}=e;jr.forEach((e=>e(t[0],n.find((e=>"member"===e.membership)))))}))}return jr.push(e),()=>(e=>{const t=jr.indexOf(e);t>-1&&jr.splice(t,1),0===jr.length&&(null==Ur||Ur())})(e)},Dr=[];let qr=null;const Nr=e=>{if(0===Dr.length){const t=Re();qr=it(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 Dr.push(e),()=>(e=>{const t=Dr.indexOf(e);t>-1&&Dr.splice(t,1),0===Dr.length&&(null==qr||qr())})(e)},Br=[];let Lr=null;const Fr=e=>{if(0===Br.length){const e=Re(),t=async e=>{var t,n;e.userIds.forEach((t=>De(["channelUsers","get",`${e.channelId}#${t}`],{isMuted:Date.parse(e.muteTimeout)>Date.now()})));const r=null===(t=je(["channel","get",e.channelId]))||void 0===t?void 0:t.data,a=null===(n=je(["channelUsers","get",`${e.channelId}#${e.userIds[0]}`]))||void 0===n?void 0:n.data;r&&a&&Br.forEach((e=>e(r,a)))};Lr=it(e,"onChannelUserMute","channel.setMutedUsers",t)}return Br.push(e),()=>(e=>{const t=Br.indexOf(e);t>-1&&Br.splice(t,1),0===Br.length&&(null==Lr||Lr())})(e)},Kr=e=>{var t;let n=[];if(["conversation","community"].includes(e.type)){const r=Me(["channelUsers","get"]);r&&(null==r?void 0:r.length)>0&&(n=(null!==(t=null==r?void 0:r.filter((({data:t})=>t.channelId===e.channelId&&"none"!==t.membership)))&&void 0!==t?t:[]).sort(((e,t)=>e.data.userInternalId.localeCompare(t.data.userInternalId))).slice(0,4).map((({data:e})=>Xn(e))))}return pn(e,{markAsRead:()=>(async e=>{const t=Re();t.log("channel/markAsRead",e);const{data:n}=await t.http.put(`/api/v1/markers/channels/${e}/mark-read`),{userMarkers:r,userEntityMarkers:a,userFeedMarkers:o}=n,s=en(n,["userMarkers","userEntityMarkers","userFeedMarkers"]),i=t.cache&&Date.now(),c=an(a),l=on(o);return t.cache&&Xt(Object.assign({userMarkers:r,userEntityMarkers:c,userFeedMarkers:l},s),{cachedAt:i}),ct("local.channelMarker.updated",{userEntityMarkers:c}),ct("local.subChannelMarker.updated",{userFeedMarkers:l}),!0})(e.channelInternalId),previewMembers:n,myMembership:t=>((e,t)=>{const{_id:n}=tt();if(!n)throw new _e("The _id has not been defined in ActiveUser",8e5,"error");const{log:r,cache:a}=Re();a||console.log("This observable object need the cache data!"),r(`liveMymembership(tmpid: ${Date.now()}) > listen`);const o=[];let s=!1;const i=e=>{t(Object.assign(Object.assign({},e),{data:e.data?Xn(e.data):e.data}))},c=(t,n)=>{const{data:r}=Zn(e);er(void 0,r)||i({loading:!1,data:r})};return o.push(Ar(c)),o.push(Mr(c)),o.push(Fr(c)),(()=>{const t=ge((async()=>Zn(e)));ve(t,(({error:e,data:t,loading:n,origin:r,cachedAt:a})=>{a===G?(i({data:t,origin:r,loading:!1,error:new ke(W,800800,"error")}),s=!0,o.forEach((e=>e()))):s||i({loading:n,data:t,origin:r,error:e}),e&&o.forEach((e=>e()))}))})(),()=>{o.forEach((e=>e()))}})(e.channelId,t)})},$r=e=>Kr(Yn((e=>{var t;const n=e.messagePreviewId?sn(e.channelId):null,r=null===(t=je(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data,a=n?Object.assign(Object.assign({},n),{user:r?cn(r):void 0}):null;return Object.assign(Object.assign({},e),{messagePreview:a})})(e))),Qr=async e=>{const t=Re();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=>{ae(null==t?void 0:t.code)&&Zt("channel",e)})),t}const a=await zn(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await Hn(r);const o=t.cache&&Date.now();return t.cache&&Xt(a,{cachedAt:o}),ct("local.channel.fetched",a.channels),{data:a.channels.map((e=>$r(e))),cachedAt:o}};Qr.locally=e=>{var t,n;const r=Re();if(r.log("channel/getChannelByIds.locally",e),!r.cache)return;const a=null===(t=Me(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!a||(null==a?void 0:a.length)<e.length)return;const o=a.map((({data:e})=>e)),s=null===(n=a.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0];return{data:o.map((e=>$r(e))),cachedAt:s.cachedAt}};class zr{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 Vr;var Hr=()=>(Vr||(Vr=new zr),Vr);const Jr=e=>Hr().onSessionStateChange(e),Wr=(e,t)=>{const n=setInterval(e,t);return()=>clearInterval(n)};let Gr=!1;const Yr={},Xr=async()=>{const e=Object.entries(Yr).filter((([,e])=>e)).map((([e])=>e));return 0!==e.length&&(async e=>{const t=Re();t.log("subChannel/readingAPI",e);const{data:n}=await t.http.post("/api/v1/markers/message-feeds/reading",{messageFeedIds:e}),{userEntityMarkers:r,userFeedMarkers:a,feedMarkers:o,userMarkers:s}=n,i=an(r),c=on(a),l=t.cache&&Date.now();return t.cache&&Xt({userEntityMarkers:i,userFeedMarkers:c,feedMarkers:o,userMarkers:s},{cachedAt:l}),ct("local.feedMarker.fetched",{feedMarkers:o}),ct("local.channelMarker.fetched",{userEntityMarkers:i}),ct("local.subChannelMarker.fetched",{userFeedMarkers:c}),ct("local.userMarker.fetched",{userMarkers:s}),!0})(e)},Zr=()=>{Gr=!1},ea=()=>(Gr=!0,Jr((e=>{"notLoggedIn"===e&&Zr()})),()=>{Zr()});Wr((async()=>{Gr&&await Xr()}),3e4);const ta=async e=>{const t=Re();t.log("channel/getSubChannels",e);const n=await t.http.get("/api/v5/message-feeds/list",{params:{messageFeedIds:e.map(encodeURIComponent)}}),r=await Mn(n.data),a=t.cache&&Date.now();return t.cache&&Xt(r,{cachedAt:a}),ct("local.message-feed.fetched",r),{data:r.messageFeeds,cachedAt:a}};ta.locally=e=>{var t;const n=Re();if(n.log("channel/getSubChannels.locally",e),!n.cache)return;const r=e.map((e=>je(["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 na=async(e=!0)=>{var t;const n=null===(t=je(["MessagePreviewSetting"]))||void 0===t?void 0:t.data;if(!e&&n)return n;const r=await(async()=>{const e=Re(),{data:t}=await e.http.get("/api/v3/network-settings/chat");return t})();var a;return(a=r).messagePreview.enabled?a.messagePreview.isIncludeDeleted?"message-preview-include-deleted":"message-preview-not-include-deleted":"no-message-preview"},ra=async()=>{var e;const t=await na();if(t===(null===(e=je(["MessagePreviewSetting"]))||void 0===e?void 0:e.data))return;Ue(["MessagePreviewSetting"],t);const n=[],r=[];if("no-message-preview"===t){const e=Me(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{qe(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=Me(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{(null==t?void 0:t.isDeleted)&&(qe(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&r.push(t.subChannelId))})),0!==n.length&&await Qr(n),0!==r.length&&await ta(r)}},aa=async()=>{const e=Re(),{data:t}=await e.http.get("/api/v3/network-settings/social");return t.socialNetworkSetting},oa=(e,t)=>{var n;const r=null===(n=je(["user","get",e]))||void 0===n?void 0:n.data;return!!r&&r.permissions.some((e=>e===t))},sa=e=>{const{userId:t}=Re();return{currentUser:()=>oa(t,e),community:n=>((e,t,n)=>{var r;if(!e)return!1;const a=null===(r=je(["communityUsers","get",`${n}#${e}`]))||void 0===r?void 0:r.data;return!!a&&(!!a.permissions.some((e=>e===t))||oa(e,t))})(t,e,n),channel:n=>((e,t,n)=>{var r;if(!e)return!1;const a=null===(r=je(["channelUsers","get",`${n}#${e}`]))||void 0===r?void 0:r.data;return!!a&&(!!a.permissions.some((e=>e===t))||oa(e,t))})(t,e,n)}},ia=async e=>{const t=Re();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},ca=async e=>{const t=Re();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},la=async()=>{const e=Re(),{data:t}=await e.http.get("/api/v3/network-settings/feed-setting");return Object.fromEntries(t.feedSettings.map((({feedType:e,contentSettings:t})=>[e,t])))},da={notLoggedIn:["establishing"],terminated:["establishing"],establishing:["notLoggedIn","established"],established:["notLoggedIn","terminated","tokenExpired","establishing"],tokenExpired:["establishing"]},ua=e=>{const t=Re();t.log("client/api/setSessionState",e);const{sessionState:n}=t;if(n===e)return!1;if(!((e,t)=>da[e].includes(t))(n,e))throw new _e(`Session state cannot change from ${n} to ${e}`,8e5,"error");return t.sessionState=e,Hr().setSessionState(e),!0},ha=async e=>{const t=Re();ua("establishing");const{accessToken:n,users:r,expiresAt:a,issuedAt:o,userType:s}=await(async({params:e,options:t})=>{const n=Re();n.log("client/api/getToken",e);const r=Jt(),{data:a}=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 a})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:a,isGlobalBanned:!1,isUserDeleted:!1},t.upload.defaults.headers.common.Authorization=`Bearer ${n}`,t.upload.defaults.metadata={tokenExpiry:a,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:o,expiresAt:a},ua("established"),{accessToken:n,users:r,userType:s}},pa=async e=>{const t=Re();ua("establishing");const{accessToken:n,users:r,expiresAt:a,issuedAt:o,userType:s}=await(async({params:e,options:t})=>{const n=Re();n.log("client/api/getVisitorToken",e);const r=Jt(),{data:a}=await n.http.post("/api/v5/sessions/visitor",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 a})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:a,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:o,expiresAt:a},ua("established"),{accessToken:n,users:r,userType:s}};function fa(e){return{users:e.users.map(An),files:e.files}}const ma=(e,t)=>{const n=Re();return it(n,e,e,(e=>{const r=fa(e);n.cache&&Xt(r),t(r.users[0])}))},ga=e=>ma("user.deleted",e),ya=["analytic","normal-priority"],va=["analytic","high-priority"],ba=async e=>{const t=Re(),n={activities:e};await t.http.post("/api/v1/analytics/activities",n)};class wa{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=je(ya);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await ba(t),qe(ya)}catch(e){this.stop(),qe(ya)}}async syncHighPriorityCapturedEvent(){try{const e=je(va);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await ba(t),qe(va)}catch(e){this.stop(),qe(va)}}}class Ca{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,a=n?this._recentHighPriorityViewed[e]:this._recentViewed[e];if(!a)return!0;return!(r.getTime()-a.getTime()<t)}markAs({uniqueId:e,contentId:t,contentType:n,activityType:r,metadata:a}){if(!this.isAbleToEnqueue({uniqueId:e,expireTime:this._expireTime}))return;const o=new Date,s={event:[]},i=je(ya);(null==i?void 0:i.data)&&(s.event=i.data.event),s.event.length>=this._poolLimit&&s.event.shift();const c={contentId:t,contentType:n,activityType:r,timestamp:o.toISOString()};a&&(c.metadata=a),s.event.push(c),De(ya,s),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 a={event:[]},o=je(va);if((null==o?void 0:o.data)&&(a.event=o.data.event),a.event.length>=this._poolLimit&&a.event.shift(),a.event.push({contentId:e.storyId,contentType:"story",activityType:t,timestamp:n.toISOString()}),De(va,a),this._recentHighPriorityViewed[e.storyId]=n,"linkClicked"===t)return;Ue(["story-seen","get",e.storyId],(new Date).toISOString());const s=je(["story-last-seen",e.targetId]);(null==s?void 0:s.data)?new Date(s.data).getTime()<new Date(e.expiresAt).getTime()&&Ue(["story-last-seen",e.targetId],e.expiresAt):Ue(["story-last-seen",e.targetId],e.expiresAt),this._bufferNewSeenStoryReferenceIds.push(e.referenceId),this._throttleStoryTimer||(this._throttleStoryTimer=setTimeout((()=>{clearTimeout(this._throttleStoryTimer),ct("local.story.reload",{referenceIds:this._bufferNewSeenStoryReferenceIds}),this._bufferNewSeenStoryReferenceIds=[]}),300))}resetAllBuckets(){this._recentViewed={},this._recentHighPriorityViewed={},qe(ya),qe(va)}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 Ia{constructor(){this._client=Re(),this._eventCapturer=new Ca,this._eventSyncer=new wa}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 Sa;var _a=()=>(Sa||(Sa=new Ia),Sa),ka=()=>{const e=_a();return e.established(),Jr((t=>{"established"===t?e.established():e.handleTokenExpired()})),()=>{e.destroy()}};class Oa{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=Re(),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.getReadReceipts();e&&this.markReadApi(e)}getUnsyncJobs(){var e;const t=null===(e=Me(["readReceipt"]))||void 0===e?void 0:e.filter((({data:e})=>e.latestSyncSegment<e.latestSegment));null==t||t.forEach((({data:e})=>{this.enqueueReadReceipt(e.channelId,e.latestSegment)}))}getReadReceipts(){const e=this.jobQueue.splice(0,this.jobQueue.length);if(0!==e.length)return e.filter((e=>{var t;const n=null===(t=je(["readReceipt",e.channelId]))||void 0===t?void 0:t.data;return!!n&&n.latestSegment>n.latestSyncSegment}))}async markReadApi(e){var t;const n=e.map((e=>({channelId:e.channelId,readToSegment:e.segment})));if(await(async e=>{const t=Re();try{return await t.http.post("api/v3/channels/seen",{channels:e}),!0}catch(e){return!1}})(n))for(let n=0;n<e.length;n+=1){const r=["readReceipt",e[n].channelId],a=null===(t=je(r))||void 0===t?void 0:t.data;Ue(r,Object.assign(Object.assign({},a),{latestSyncSegment:e[n].segment}))}else for(let t=0;t<e.length;t+=1){if(e[t].retryCount>=this.MAX_RETRY)return;const n=Object.assign(Object.assign({},e[t]),{syncState:"create",retryCount:e[t].retryCount+1});this.enqueueJob(n)}}startObservingReadReceiptQueue(){this.client.useLegacyUnreadCount&&(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=["channelUnread","get",e],a=null===(n=je(r))||void 0===n?void 0:n.data;"number"==typeof(null==a?void 0:a.readToSegment)&&a&&t>a.readToSegment&&(a.readToSegment=t,a.unreadCount=Math.max(a.lastSegment-t,0),Ue(r,a),ct("local.channelUnread.updated",[a])),this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const r=null===(n=je(["readReceipt",e]))||void 0===n?void 0:n.data;if(r){if(r.latestSegment<t)Ue(["readReceipt",e],Object.assign(Object.assign({},r),{latestSegment:t}));else if(r.latestSyncSegment>=t)return}else{Ue(["readReceipt",e],{channelId:e,latestSegment:t,latestSyncSegment:0})}let a=this.getSyncJob(e);null===a||"syncing"===a.syncState?(a={channelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(a)):a.segment<t&&(a.segment=t)}getSyncJob(e){const{jobQueue:t}=this;return t.find((t=>t.channelId===e))||null}enqueueJob(e){this.jobQueue.length<this.JOB_QUEUE_SIZE||this.jobQueue.shift(),this.jobQueue.push(e)}}let Ta=null;var Ea=()=>(Ta||(Ta=new Oa),Ta),Aa=()=>{const e=Ea();return e.startSyncReadReceipt(),Jr((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};class Ra{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=Re(),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=Me(["legacyReadReceipt"]))||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=je(["legacyReadReceipt",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:a}=n,o=await(async({subChannelId:e,readToSegment:t})=>{const n=Re();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:a});if(o){this.removeSynedReceipt(e.subChannelId,e.segment);const n=null===(t=je(["legacyReadReceipt",r]))||void 0===t?void 0:t.data;Ue(["legacyReadReceipt",r],Object.assign(Object.assign({},n),{latestSyncSegment:a}))}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],a=null===(n=je(r))||void 0===n?void 0:n.data;if(a&&t>a.readToSegment){a.readToSegment=t,a.unreadCount=Math.max(a.lastSegment-t,0);const e=gn(a.channelId);ct("local.channelUnreadInfo.updated",e),Ue(r,a),ct("local.subChannelUnread.updated",a)}this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const r=null===(n=je(["legacyReadReceipt",e]))||void 0===n?void 0:n.data;if(r){if(r.latestSegment<t)Ue(["legacyReadReceipt",e],Object.assign(Object.assign({},r),{latestSegment:t}));else if(r.latestSyncSegment>=t)return}else{Ue(["legacyReadReceipt",e],{subChannelId:e,latestSegment:t,latestSyncSegment:0})}let a=this.getSyncJob(e);null===a||"syncing"===a.syncState?(a={subChannelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(a)):a.segment<t&&(a.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 Pa=null;var Ma=()=>(Pa||(Pa=new Ra),Pa),ja=()=>{const e=Ma();return e.startSyncReadReceipt(),Jr((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};const Ua=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")},xa=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")},Da=async e=>{const t=Re();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=>{ae(null==t?void 0:t.code)&&Zt("channel",e)})),t}const a=await zn(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await Hn(r);const o=t.cache&&Date.now();return t.cache&&Xt(a,{cachedAt:o}),ct("local.channel.fetched",a.channels),{data:a.channels,cachedAt:o}};Da.locally=e=>{var t,n;const r=Re();if(r.log("channel/getChannelByIds.locally",e),!r.cache)return;const a=null===(t=Me(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!a||(null==a?void 0:a.length)<e.length)return;return{data:a.map((({data:e})=>e)),cachedAt:(null===(n=a.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0]).cachedAt}};class qa{constructor(){this.TIMER_INTERVAL_MS=Y,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(Ua((()=>{this.isConnected=!0}))),this.connectionListener.push(xa((()=>{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=>{var t,n,r;await Da(e);const a=null!==(r=null===(n=null===(t=Me(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.channelPublicId&&e.includes(t.channelPublicId))))||void 0===n?void 0:n.map((({data:e})=>e)))&&void 0!==r?r:[];ct("local.channel.resolved",a)})(e),t.length>0&&(async e=>{const t=await Vn(e),{feedMarkers:n,userFeedMarkers:r}=t;yn({feedMarkers:n,userFeedMarkers:r}),ct("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 Na=null;var Ba=()=>(Na||(Na=new qa),Na),La=()=>{const e=Ba();return e.startResolver(),Jr((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};class Fa{constructor(){this.TIMER_INTERVAL_MS=1e3,this.buffer=[],this.isSyncing=!1,this.connectionListener=[],this.isConnected=!0,this.addConnectionListener()}startReactionsSync(){this.timer||(this.timer=setInterval((()=>{this.isConnected&&this.syncLiveReactions()}),this.TIMER_INTERVAL_MS))}stopReactionsSync(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}createLiveReaction(e){this.buffer.push(e)}addConnectionListener(){this.connectionListener.length>0||(this.connectionListener.push(Ua((()=>{this.isConnected=!0}))),this.connectionListener.push(xa((()=>{this.isConnected=!1}))))}removeConnectionListener(){this.connectionListener.length>0&&(this.connectionListener.forEach((e=>e())),this.connectionListener=[])}syncLiveReactions(){if(this.isSyncing)return;this.isSyncing=!0;const e=this.buffer;this.clearBuffer();const t=e.reduce(((e,t)=>{const{streamId:n}=t,r=en(t,["streamId"]);return e[n]?e[n].push(r):e[n]=[r],e}),{});Object.entries(t).forEach((([e,t])=>{(async({reactions:e,liveStreamId:t})=>{const n=Re();n.log("live_reaction/addReaction",e);const{data:r}=await n.http.post("/api/v1/reactions/live",{liveStreamId:t,reactions:e})})({liveStreamId:e,reactions:t})})),this.isSyncing=!1}clearBuffer(){this.buffer=[]}onSessionEstablished(){this.startReactionsSync(),this.addConnectionListener()}onSessionDestroyed(){this.stopReactionsSync(),this.clearBuffer(),this.isSyncing=!1,this.removeConnectionListener()}onTokenExpired(){this.stopReactionsSync()}}let Ka;var $a=()=>(Ka||(Ka=new Fa),Ka);const Qa=async()=>{var e;const t=Re();return t.log("client/api/disconnectClient"),t.mqtt&&t.mqtt.connected&&t.mqtt.disconnect(),"established"===t.sessionState&&ua("notLoggedIn"),t.emitter.all.clear(),null===(e=t.mqtt)||void 0===e||e.removeAllListeners(),t.userId=void 0,t.token=void 0,t.http.defaults.headers.common.Authorization="",t.http.defaults.metadata={tokenExpiry:"",isGlobalBanned:!1,isUserDeleted:!1},"undefined"!=typeof document&&(document.cookie="_ascSession=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"),"tokenExpired"!==t.sessionState&&t.cache&&(t.cache={data:{}}),!0},za=e=>{const t=Re();ua("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,Qa()},Va=["disconnected","error","connect_error","reconnect_error","reconnect_failed"],Ha=e=>{const t=Re(),n=Va.map((n=>it(t,`client/onConnectionError(${n})`,n,(t=>{const r=(null==t?void 0:t.code)?new _e(t.message,t.code,"fatal"):new Te(n);e(r)}))));return()=>{n.forEach((e=>e()))}},Ja=e=>{const t=Re();return it(t,"client/onConnectionError(user.didGlobalBan)","user.didGlobalBan",e)},Wa=e=>{const t=Re();return it(t,"client/onTokenExpired","tokenExpired",e)},Ga=e=>{const t=Re();return it(t,"client/onTokenTerminated","tokenTerminated",e)},Ya=e=>{const t=Ce("channelMarker")({userId:tt()._id,entityId:e.channelId});qe(["channelMarker","get",t],!0)};let Xa=null;const Za=e=>{Xa=e},eo=({user:e,userType:t})=>{nt(e),Za(t),Ue(["user","get",e.userId],e)};let to=[];const no=async(e,t,n)=>{const r=Re();let a;r.log("client/api/connectClient",Object.assign({apiKey:r.apiKey,sessionState:r.sessionState},e)),r.userId&&r.userId!==e.userId&&(await Qa(),to.forEach((e=>e())),to=[]);const o=await Ht();try{const{users:n,userType:s}=await ha({params:Object.assign(Object.assign({},e),{displayName:null==e?void 0:e.displayName,deviceId:(null==e?void 0:e.deviceId)||o}),options:{setAccessTokenCookie:!0}}),i=n.find((t=>t.userId===e.userId));if(null==i)throw new _e(`${e.userId} has not been founded`,8e5,"error");if(i.isDeleted)return za("userDeleted"),!1;if(i.isGlobalBan)return za("globalBan"),!1;r.userId=i.userId,r.sessionHandler=t,a=r.accessTokenExpiryWatcher(t),eo({user:i,userType:s})}catch(e){throw Hr().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await ut()}(),await ra(),0===to.length&&(to.push(Ja((e=>{za("globalBan"),to.forEach((e=>e())),a()})),Ga((e=>{za(),to.forEach((e=>e())),a()})),ga((e=>{e.userId===r.userId&&(za("userDeleted"),to.forEach((e=>e())),a())})),Wa((e=>{Hr().setSessionState(e),Qa(),to.forEach((e=>e()))})),ur(Ya),Ar(Ya),ea(),ka(),La(),(()=>{const e=$a();return e.startReactionsSync(),Jr((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})()),r.useLegacyUnreadCount?to.push(Aa()):to.push(ja())),!0},ro=[],ao=async e=>{const t=Re();let n;t.log("client/api/connectClient",Object.assign({apiKey:t.apiKey,sessionState:t.sessionState},e));const r=await Ht();let a;try{const{users:o,userType:s}=await pa({params:Object.assign(Object.assign({},e),{deviceId:r}),options:{setAccessTokenCookie:!0}});[a]=o,t.userId=a.userId,t.sessionHandler=e.sessionHandler,n=t.accessTokenExpiryWatcher(e.sessionHandler),eo({user:a,userType:s})}catch(e){throw Hr().setSessionState("notLoggedIn"),e}return await ra(),0===ro.length&&ro.push(Ga((e=>{za(),ro.forEach((e=>e())),n()})),Wa((e=>{Hr().setSessionState(e),Qa(),ro.forEach((e=>e()))}))),!0},oo=()=>{var e;const t=Re();if(!t)throw new _e("Connect client first",8e5,"fatal");const n=null===(e=je(["user","get",t.userId]))||void 0===e?void 0:e.data;if(!n)throw new _e("Connect client first",8e5,"fatal");return cn(n)},so=()=>{let e,t=!1;const n=Re();n.log("initiating access token renewal");const r=async r=>{const{userId:a,displayName:o}=oo(),s={userId:a,displayName:o,authToken:r,deviceId:await Ht()};"tokenExpired"===n.sessionState&&n.sessionHandler?await no(s,n.sessionHandler):await ha({params:s,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(so())}),X)},renewWithAuthSignature:r=>{t?console.log("'renew' method can be called only once per renewal instance"):(async({authSignature:r,authSignatureExpiresAt:a})=>{const o=await Ht();"tokenExpired"===n.sessionState&&n.sessionHandler?await ao({sessionHandler:n.sessionHandler}):await pa({params:{authSignature:r,authSignatureExpiresAt:a,deviceId:o},options:{setAccessTokenCookie:!0}}),t=!0,e&&clearTimeout(e)})(r)},unableToRetrieveAuthSignature:()=>{e=setTimeout((()=>{var e;null===(e=n.sessionHandler)||void 0===e||e.sessionWillRenewAccessToken(so())}),X)}}},io=3e5,co=e=>{const t=setInterval((()=>{const t=Re();if(!t.token)return;const{issuedAt:n,expiresAt:r}=t.token;if((e=>Date.now()>Date.parse(e)-io)(r))return ct("tokenExpired","tokenExpired"),void ot((()=>e.sessionWillRenewAccessToken(so())));(e=>{const{expiresAt:t,issuedAt:n}=e,r=Date.parse(t),a=Date.parse(n),o=Date.now();return o>a+.8*(r-a-io)&&o<r})({expiresAt:r,issuedAt:n})&&e.sessionWillRenewAccessToken(so())}),X);return()=>clearInterval(t)},lo=e=>{if(Re().useLegacyUnreadCount){Ea().markRead(e.channelId,e.channelSegment)}else{Ma().markRead(e.subChannelId,e.channelSegment)}},uo=e=>{const t=Re(),n=tt(),r=[it(t,"message/onMessageCreated","message.created",(async r=>{const a=await On(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&r.messages.forEach((e=>{(e=>{var t;const n=Re(),r=["subChannelUnreadInfo","get",e.messageFeedId],a=null===(t=je(r))||void 0===t?void 0:t.data;if(!a)return;const o=a.lastSegment<e.segment?e.segment:a.lastSegment,s=o-a.readToSegment;let{lastMentionSegment:i}=a;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({},a),{lastMentionSegment:i,lastSegment:o,isMentioned:!(a.readToSegment>=i),unreadCount:Math.max(s,0)});Ue(r,c)})(e),gn(e.channelId)})),t.useLegacyUnreadCount&&r.messages.forEach((e=>{var n,r;const a=null===(n=je(["channelUnread","get",e.channelId]))||void 0===n?void 0:n.data;if(!a||a.lastSegment>=e.segment||"number"!=typeof a.readToSegment||"number"!=typeof a.lastMentionedSegment)return;const o=e.segment,s=(null===(r=e.mentionedUsers)||void 0===r?void 0:r.some((e=>"channel"===e.type||"user"===e.type&&t.userId&&e.userPublicIds.includes(t.userId))))?e.segment:a.lastMentionedSegment,i=Object.assign(Object.assign({},a),{lastSegment:o,unreadCount:Math.max(o-a.readToSegment,0),lastMentionedSegment:s,isMentioned:!(a.readToSegment>=s)});Ue(["channelUnread","get",e.channelId],i),ct("local.channelUnread.updated",[i])})),Xt(a),a.messages.forEach((t=>{t.creatorPrivateId===n._id&&lo(t),e(t)}))}))];return()=>{r.forEach((e=>e()))}},ho=e=>{const t=Re(),n=[it(t,"message/onMessageCreated","local.message.created",(async t=>(Xt(t),t.messages.forEach((t=>{e(t)})))))];return()=>{n.forEach((e=>e()))}},po=e=>{const t=Re();return it(t,"onSubChannelCreated","message-feed.created",(async n=>{const r=await Mn(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&n.messageFeeds.forEach((e=>{(e=>{const{channelId:t,subChannelId:n,createdAt:r,updatedAt:a}=e,o={channelId:t,subChannelId:n,unreadCount:0,readToSegment:0,lastMentionSegment:0,lastSegment:0,isMentioned:!1,isDeleted:!1,createdAt:r,updatedAt:a};Ue(["subChannelUnreadInfo","get",o.subChannelId],o)})({channelId:e.channelId,subChannelId:e.messageFeedId,createdAt:e.createdAt,updatedAt:e.updatedAt})})),Xt(r),e(r.messageFeeds[0])}))},fo=e=>{const t=Re(),n=[it(t,"onSubChannelDeleted","message-feed.deleted",(async n=>{const r=await Mn(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&r.messageFeeds.forEach((e=>{(e=>{var t;const n=["subChannelUnreadInfo","get",e],r=null===(t=je(n))||void 0===t?void 0:t.data;r&&Ue(n,Object.assign(Object.assign({},r),{isDeleted:!0}))})(e.subChannelId),gn(e.channelId)})),Xt(r),e(r.messageFeeds[0])})),it(t,"local.message-feed.deleted","local.message-feed.deleted",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}},mo=async e=>{const t=Re();t.log("channel/markerSync");const{data:n}=await t.http.post("/api/v1/markers/sync",{deviceLastSyncAt:e}),{userEntityMarkers:r,userFeedMarkers:a,feedMarkers:o,userMarkers:s}=n,i=an(r),c=on(a),l=t.cache&&Date.now();return t.cache&&Xt({userEntityMarkers:i,userFeedMarkers:c,feedMarkers:o,userMarkers:s},{cachedAt:l}),ct("local.feedMarker.fetched",{feedMarkers:o}),ct("local.channelMarker.fetched",{userEntityMarkers:i}),ct("local.subChannelMarker.fetched",{userFeedMarkers:c}),ct("local.userMarker.fetched",{userMarkers:s}),{data:n,hasMore:n.feedMarkers.length>0}};let go=!1,yo=[],vo=!1;let bo=null;let wo=[];const Co=e=>{wo=e},Io=async()=>{var e;if(!vo&&0!==wo.length)try{vo=!0,wo=[];const t=await mo((null==bo?new Date:bo).toISOString()),n=t.data.userMarkers.reduce(((e,t)=>null==e||e.getTime()<new Date(t.lastSyncAt).getTime()?new Date(t.lastSyncAt):e),null);null!=(e=n)&&(!bo||e.getTime()>bo.getTime())&&(bo=e),t.hasMore&&wo.push("has_more")}catch(e){}finally{vo&&(vo=!1)}};Wr((async()=>{go&&await Io()}),2e3);const So=()=>true,_o=e=>{var t;const n=Re();if(n.mqtt)return null===(t=n.mqtt)||void 0===t?void 0:t.listen(e)};let ko=[];var Oo;class To{constructor(){Oo.set(this,e.FileAccessTypeEnum.PUBLIC)}setFileAccessType(e){!function(e,t,n,r,a){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!a)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!a:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===r?a.call(e,n):a?a.value=n:t.set(e,n)}(this,Oo,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,Oo,"f")}}let Eo;Oo=new WeakMap;var Ao=()=>(Eo||(Eo=new To),Eo);const Ro=async e=>{const t=Re();ua("establishing");const{accessToken:n,users:r,expiresAt:a,issuedAt:o,userType:s}=await(async({params:e,options:t})=>{const n=Re();n.log("client/api/getBotToken");const r=Jt(),{data:a}=await n.http.post("/api/v5/sessions/bot",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 a})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:a,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:o,expiresAt:a},ua("established"),{accessToken:n,users:r,userType:s}},Po=[],Mo=e=>{const t=Re();return it(t,"channelMarker/onChannelMarkerFetched","local.channelMarker.fetched",(t=>{t.userEntityMarkers.forEach((t=>{e(t)}))}))},jo=e=>{const t=Re();return it(t,"subChannelMarker/onSubChannelMarkerFetched","local.subChannelMarker.fetched",(t=>{t.userFeedMarkers.forEach(e)}))},Uo=e=>{const t=Re();return it(t,"subChannelMarker/onSubChannelMarkerUpdated","local.subChannelMarker.updated",(t=>{e(t.userFeedMarkers)}))},xo=e=>{const t=Re();return it(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers)}))},Do=e=>{const t=Re();return it(t,"messageMarker/onMessageMarkerFetched","local.messageMarker.fetched",(t=>{e(t.contentMarkers[0])}))},qo=e=>{const t=Re();return it(t,"messageMarker/onMessageMarked","marker.marked-message",(t=>{var n,r,a;Xt(t);const o=Me(["message","collection"]),{contentMarkers:s,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==s?void 0:s.length)>0){(null!==(a=null===(r=null===(n=e[0].data)||void 0===n?void 0:n.data)||void 0===r?void 0:r.map((e=>je(["message","get",e]))).map((({data:e})=>e)).filter(Boolean))&&void 0!==a?a:[]).forEach((e=>{var t,n;const r=["messageMarker","get",Ce("messageMarker")({creatorId:e.creatorPrivateId,feedId:e.subChannelId,contentId:e.messageId})],a=null===(t=je(r))||void 0===t?void 0:t.data;if(!a)return;const o=s[0].feedId===a.feedId,i=s[0].readCount>a.readCount,c=(null===(n=s[0])||void 0===n?void 0:n.deliveredCount)>a.deliveredCount;if(o){const e=Object.assign(Object.assign({},a),{readCount:i?s[0].readCount:a.readCount,deliveredCount:c?s[0].deliveredCount:a.deliveredCount});Ue(r,e)}}))}}e(t.contentMarkers[0])}))};function No(e){return"object"==typeof e&&null!==e}const Bo=e=>{if(!No(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)},Lo=e=>{if(!No(e))return e;const t=Object.entries(e).map((([e,t])=>"function"==typeof t?[e,void 0]:[e,t]));return Object.fromEntries(t)};var Fo=Object.freeze({__proto__:null,getActiveClient:Re,getActiveUser:tt,setActiveUser:nt,createClient:(e,t=Et.SG,{debugSession:n="amity",apiEndpoint:r,prefixDeviceIdKey:a,rteEnabled:o=!0}={})=>{var s,i,c;const l=(e=>{const t=`${null==e?void 0:e.trim()}`.length>0&&!Tt,n=g.default(e),r=(e,...r)=>{t&&n(e,r)};return r.__instance__=n,r})(n);l("client/api/createClient",{apiKey:e.replace(/.{5}$/g,"xxxxx"),apiRegion:t});const d=null!==(s=null==r?void 0:r.http)&&void 0!==s?s:Rt("http",t),u=null!==(i=null==r?void 0:r.upload)&&void 0!==i?i:Rt("upload",t),h=null!==(c=null==r?void 0:r.mqtt)&&void 0!==c?c:Rt("mqtt",t),p=qt(d),f=qt(u);let y;o&&(y=Yt(h));const v=m.default(),b={version:`${z}`,apiKey:e,log:l,cache:{data:{}},http:p,ws:undefined,mqtt:y,upload:f,emitter:v,sessionState:"notLoggedIn",accessTokenExpiryWatcher:co,sessionHandler:undefined,hasPermission:sa,validateUrls:ia,validateTexts:ca,getFeedSettings:la,getSocialSettings:aa,getVisitorDeviceId:Ht,getMessagePreviewSetting:na,onRTEConnectionStateChange:_o,use:()=>Pe(b),isUnreadCountEnabled:!1,useLegacyUnreadCount:!0,getMarkerSyncConsistentMode:So,prefixDeviceIdKey:a};try{const t=Re();if(t.apiKey===e)return t;Pe(b)}catch(e){Pe(b)}return b},login:no,logout:Qa,secureLogout:async()=>{const e=Re(),{data:{success:t}}=await e.http.delete("/api/v4/sessions");if(!t)throw new Error("Failed to logout");return await Qa()},resumeSession:async(e,t,n)=>{const r=Re();let a;r.log("client/api/resumeSession",Object.assign({apiKey:r.apiKey,sessionState:r.sessionState},e)),r.userId&&(r.userId===e.userId&&(e=>{var t;const n=Re(),r=C.default(e);return(null===(t=null==r?void 0:r.user)||void 0===t?void 0:t.publicUserId)===n.userId})(e.token.accessToken)?(r.mqtt&&r.mqtt.connected&&r.mqtt.disconnect(),ko.forEach((e=>e())),ko=[]):(await Qa(),ko.forEach((e=>e())),ko=[]));try{const n=await(async({token:e,userId:t})=>{const n=Re();ua("establishing");const{data:{users:r}}=await n.http.get(`/api/v3/users/${t}`,{headers:{Authorization:`Bearer ${e.accessToken}`}}),a=r.find((e=>e.userId===t));return n.http.defaults.headers.common.Authorization=`Bearer ${e.accessToken}`,n.http.defaults.metadata={tokenExpiry:e.expiresAt,isGlobalBanned:!1,isUserDeleted:!1},n.upload.defaults.headers.common.Authorization=`Bearer ${e.accessToken}`,n.upload.defaults.metadata={tokenExpiry:e.expiresAt,isGlobalBanned:!1,isUserDeleted:!1},n.token=e,ua("established"),a})(e);if(null==n)throw new _e(`${e.userId} has not been found`,8e5,"error");if(n.isDeleted)return za("userDeleted"),!1;if(n.isGlobalBanned)return za("globalBan"),!1;r.userId=n.userId,r.sessionHandler=t,a=r.accessTokenExpiryWatcher(t),nt(n)}catch(e){throw Hr().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await ut()}(),await ra(),0===ko.length&&(ko.push(Ja((e=>{za("globalBan"),ko.forEach((e=>e())),a()})),Ga((e=>{za(),ko.forEach((e=>e())),a()})),ga((e=>{e.userId===r.userId&&(za("userDeleted"),ko.forEach((e=>e())),a())})),Wa((e=>{Hr().setSessionState(e),Qa(),ko.forEach((e=>e()))})),ur(Ya),Ar(Ya),ea(),ka(),La()),r.useLegacyUnreadCount?ko.push(Aa()):ko.push(ja())),!0},isConnected:()=>{var e,t;const n=Re();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))},getFeedSettings:la,renewal:so,markerSync:mo,enableUnreadCount:()=>!0,setUploadedFileAccessType:function(e){Ao().setFileAccessType(e)},registerPushNotification:async e=>{const t=Re();let n;if("ios"!==l.Platform.OS&&"android"!==l.Platform.OS)throw new Ee("Unsupported platform");n=l.Platform.OS;const r=await Ht(),{data:{status:a,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 ke(o,5e5,"error");return"success"===a},unregisterPushNotification:async()=>{const e=Re(),t=Ht(),{data:{status:n,error:r}}=await e.http.delete("/v1/notification",{data:{deviceId:t},headers:{"X-API-Key":e.apiKey}});if(r)throw new ke(r,5e5,"error");return"success"===n},onRTEConnectionStateChange:_o,fetchLinkPreview:async e=>{const t=Re();let n=e;/^https?:\/\//i.test(e)||(n=`https://${e}`);const{data:r}=await t.http.get(`/api/v1/link-preview?url=${encodeURIComponent(n)}`);return r},getSocialSettings:aa,getShareableLinkConfiguration:async()=>{const e=Re(),{data:t}=await e.http.get("/api/v3/network-settings/shareable-deep-links");return t},loginAsVisitor:ao,loginAsBot:async e=>{const t=Re();let n;t.log("client/api/connectClient",{apiKey:t.apiKey,sessionState:t.sessionState});const r=await Ht();let a;try{const{users:o,userType:s}=await Ro({params:{deviceId:r},options:{setAccessTokenCookie:!0}});[a]=o,t.userId=a.userId,t.sessionHandler=e.sessionHandler,n=t.accessTokenExpiryWatcher(e.sessionHandler),eo({user:a,userType:s})}catch(e){throw Hr().setSessionState("notLoggedIn"),e}return await ra(),0===Po.length&&Po.push(Ga((e=>{za(),Po.forEach((e=>e())),n()})),Wa((e=>{Hr().setSessionState(e),Qa(),Po.forEach((e=>e()))}))),!0},getCurrentUser:oo,getCurrentUserType:()=>{if(!Xa)throw new _e("Connect client first",8e5,"fatal");return Xa},setCurrentUserType:Za,onConnectionError:Ha,onClientDisconnected:e=>Ha((({code:t})=>{800211===t&&e()})),onClientBanned:Ja,onSessionStateChange:Jr,onNetworkActivities:e=>Ut().onNetworkActivities(e),getUserUnread:e=>{const{_id:t}=tt();if(!t)throw new _e("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:r}=Re();r||console.log("For using Live Object feature you need to enable Cache!");n(`liveUserUnread(tmpid: ${Date.now()}) > listen`);const a=[];let o,s=!1;const i=t=>{const{data:n}=t,r=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;o=r?Bo(r):r,e({data:r?Object.assign(Object.assign({},r),{isMentioned:r.isMentioned}):r,loading:t.loading,error:t.error})};return a.push(xo((e=>(e=>{var n;const r=e.filter((e=>t===e.userId)),a=r.reduce(((e,t)=>null==e||new Date(t.lastSyncAt).getTime()>new Date(e.lastSyncAt).getTime()?t:e),null),s={unreadCount:null!==(n=null==a?void 0:a.unreadCount)&&void 0!==n?n:0,isMentioned:r.some((e=>!!e.isMentioned))};er(o,s)||i({loading:!1,data:s})})(e)))),(()=>{const e=ge(vn);ve(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}):(o===G?(i({data:t,origin:r,loading:!1,error:new ke(W,800800,"error")}),s=!0,a.forEach((e=>e()))):s||i({loading:n,data:t,origin:r,error:e}),e&&a.forEach((e=>e())))}))})(),()=>{a.forEach((e=>e()))}},getMarkerSyncEvents:()=>wo,setMarkerSyncEvents:Co,pushMarkerSyncEvent:e=>wo.push(e),markerSyncTrigger:Io,startMarkerSync:async()=>Promise.resolve(),startUnreadSync:async()=>Promise.resolve(),stopUnreadSync:()=>{go=!1,Co([]),yo.forEach((e=>e())),yo=[]},getMarkerSyncConsistentMode:So});function Ko(e){const{users:t,follows:n}=e,r=en(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n,users:t.map(An)})}function $o(e){const{users:t,follows:n}=e,r=en(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n,users:t.map(An)})}function Qo(e){const{follows:t}=e,n=en(e,["follows"]);return Object.assign(Object.assign({},n),{follows:t})}const zo=(e,t)=>{const n=Re();return it(n,e,e,(e=>{const r=Ko(e);n.cache?(Xt(r),t(r.follows[0])):t(r.follows[0])}))},Vo=(e,t)=>{const n=Re();return it(n,e,e,(e=>{const r=Qo(e);n.cache?(Xt(r),t(r.follows[0])):t(r.follows[0])}))},Ho=e=>zo("follow.created",e),Jo=e=>zo("follow.unfollowed",e),Wo=e=>zo("follow.followerDeleted",e),Go=e=>zo("follow.requested",e),Yo=e=>zo("follow.requestCanceled",e),Xo=e=>zo("follow.accepted",e),Zo=e=>zo("follow.requestDeclined",e),es=async e=>{var t,n;const r=Re();r.log("follow/getFollowInfo",e);const{data:a}=await r.http.get(r.userId===e?"/api/v4/me/followInfo":`/api/v5/users/${e}/followInfo`),o=r.cache&&Date.now(),s="follows"in a?Object.assign(Object.assign({},a.followCounts[0]),{status:null===(n=null===(t=a.follows)||void 0===t?void 0:t[0])||void 0===n?void 0:n.status}):a.followCounts[0];return r.cache&&Ue(["followInfo","get",e],s,{cachedAt:o}),{data:s,cachedAt:o}};es.locally=e=>{const t=Re();if(t.log("follow/getFollowInfo.locally",e),!t.cache)return;const n=je(["followInfo","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const ts=e=>{const t=async t=>{const[{data:n},{data:r}]=await Promise.all([es(t.from),es(t.to)]);e(n),e(r)},n=[zo("follow.created",t),zo("follow.requested",t),zo("follow.accepted",t),zo("follow.unfollowed",t),zo("follow.requestCanceled",t),zo("follow.requestDeclined",t),zo("follow.followerDeleted",t),Vo("local.follow.created",t),Vo("local.follow.requested",t),Vo("local.follow.accepted",t),Vo("local.follow.unfollowed",t),Vo("local.follow.requestDeclined",t)];return()=>{n.forEach((e=>e()))}},ns=e=>Vo("local.follow.created",e),rs=e=>Vo("local.follow.unfollowed",e),as=e=>Vo("local.follow.requested",e),os=e=>Vo("local.follow.accepted",e),ss=e=>Vo("local.follow.requestDeclined",e);class is{constructor(e){const{http:t}=Re();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,a;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 s=await this.getRequest(this.queryParams,o);return"first"===e&&(this.nextToken=null===(t=s.paging)||void 0===t?void 0:t.next,this.previousToken=null===(n=s.paging)||void 0===n?void 0:n.previous),"prev"===e&&(this.previousToken=null===(r=s.paging)||void 0===r?void 0:r.previous),"next"===e&&(this.nextToken=null===(a=s.paging)||void 0===a?void 0:a.next),s}getNextToken(){return this.nextToken}getPrevToken(){return this.previousToken}}class cs extends is{async getRequest(e,t){const{limit:n=V,userId:r}=e,a=en(e,["limit","userId"]),o=t?{token:t}:{limit:n},s=Re().userId===r?"/api/v4/me/followers":`/api/v4/users/${r}/followers`,{data:i}=await this.http.get(s,{params:Object.assign(Object.assign({},a),{options:o,isDeleted:!1})});return i}}class ls{constructor(e,t){this.query=e,this.cacheKey=t}}var ds;!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"}(ds||(ds={}));class us extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.follows.map(Ce("follow"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(Ce("follow"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.to&&r){switch(e){case ds.OnDeclined:case ds.OnCanceled:case ds.OnUnfollowed:case ds.OnDeleted:r.data=r.data.filter((e=>e!==Ce("follow")(t)));break;case ds.OnRequested:case ds.OnAccepted:case ds.OnFollowed:r.data=[...new Set([Ce("follow")(t),...r.data])]}Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class hs{constructor(e){const{http:t}=Re();this.queryParams=e,this.http=t}async onFetch(){return await this.getRequest(this.queryParams)}}class ps{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 hs?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 hs)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 hs)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(Bo).map(Lo);return!er(this.snapshot,t)&&(this.snapshot=t,!0)}getCacheKey(){return this.cacheKey}}function fs(e){return null!=e}const ms=({userId:e})=>t=>{const n=Re();return it(n,"user.deleted","user.deleted",(n=>{const r=fa(n);Xt(r);const a=je(["follow","get",Ce("follow")({from:r.users[0].userId,to:e})]);a&&t(null==a?void 0:a.data)}))};class gs extends ps{constructor(e,t){const n=I.default(Object.assign(Object.assign({},e),{type:"follower"})),r=["follow","collection",n];super(new cs(e),n,r,t),this.query=e,this.queryStreamController=new us(this.query,this.cacheKey,this.notifyChange.bind(this),Ko),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:Ho,action:ds.OnFollowed},{fn:Jo,action:ds.OnUnfollowed},{fn:Xo,action:ds.OnAccepted},{fn:Zo,action:ds.OnDeclined},{fn:Yo,action:ds.OnCanceled},{fn:Wo,action:ds.OnDeleted},{fn:os,action:ds.OnAccepted},{fn:ss,action:ds.OnDeclined},{fn:ns,action:ds.OnFollowed},{fn:rs,action:ds.OnUnfollowed},{fn:ms({userId:this.query.userId}),action:ds.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["follow","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,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=je(["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 ys extends is{async getRequest(e,t){const{limit:n=V,userId:r}=e,a=en(e,["limit","userId"]),o=t?{token:t}:{limit:n},s=Re().userId===r?"/api/v4/me/following":`/api/v4/users/${r}/following`,{data:i}=await this.http.get(s,{params:Object.assign(Object.assign({},a),{options:o,isDeleted:!1})});return i}}class vs extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.follows.map(Ce("follow"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(Ce("follow"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.from&&r){switch(e){case ds.OnDeclined:case ds.OnCanceled:case ds.OnUnfollowed:case ds.OnDeleted:r.data=r.data.filter((e=>e!==Ce("follow")(t)));break;case ds.OnRequested:case ds.OnAccepted:case ds.OnFollowed:r.data=[...new Set([Ce("follow")(t),...r.data])]}Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const bs=({userId:e})=>t=>{const n=Re();return it(n,"user.deleted","user.deleted",(n=>{const r=fa(n);Xt(r);const a=je(["follow","get",Ce("follow")({from:e,to:r.users[0].userId})]);a&&t(null==a?void 0:a.data)}))};class ws extends ps{constructor(e,t){const n=I.default(Object.assign(Object.assign({},e),{type:"following"})),r=["follow","collection",n];super(new ys(e),n,r,t),this.query=e,this.queryStreamController=new vs(this.query,this.cacheKey,this.notifyChange.bind(this),$o),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:Go,action:ds.OnRequested},{fn:Xo,action:ds.OnAccepted},{fn:Zo,action:ds.OnDeclined},{fn:Yo,action:ds.OnCanceled},{fn:Ho,action:ds.OnFollowed},{fn:Jo,action:ds.OnUnfollowed},{fn:Wo,action:ds.OnDeleted},{fn:as,action:ds.OnRequested},{fn:os,action:ds.OnAccepted},{fn:ss,action:ds.OnDeclined},{fn:ns,action:ds.OnFollowed},{fn:rs,action:ds.OnUnfollowed},{fn:bs({userId:this.query.userId}),action:ds.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["follow","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,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=je(["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}}const Cs=(e,t,n,r,a,o)=>{const{forceDispatch:s,callbackDataSelector:i,callbackFilter:c}=Object.assign({forceDispatch:!1,callbackDataSelector:e=>e},o),{cache:l}=Re();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=en(e,["data"]);c&&!c(n,d)||t(Object.assign({data:i(n)},r)),d=Bo(n)};return h.push(...a.map((t=>t((t=>((t,r=!1)=>{e===t[n]&&(d&&!r&&er(d,t)||p({loading:!1,data:t,origin:"event"}))})(t,s)))))),(()=>{const t=ge(r,e,!0);ve(t,(({error:e,data:t,loading:n,origin:r,cachedAt:a})=>{a===G?(p({data:t,origin:r,loading:!1,error:new ke(W,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 Is=Object.freeze({__proto__:null,blockUser:async e=>{const t=Re();t.log("user/blockUser",e);const{data:n}=await t.http.post(`/api/v4/me/user-blocks/${e}`),r=t.cache&&Date.now(),{follows:a,followCounts:o}=n,s={follows:a};t.cache&&(Xt(s,{cachedAt:r}),De(["followInfo","get",e],o[0],{cachedAt:r}));const i=Qo(s);return ct("local.follow.unfollowed",i),n},unBlockUser:async e=>{const t=Re();t.log("user/unBlockUser",e);const{data:n}=await t.http.delete(`/api/v4/me/user-blocks/${e}`),r=t.cache&&Date.now(),{follows:a,followCounts:o}=n,s={follows:a};t.cache&&(Xt(s,{cachedAt:r}),De(["followInfo","get",e],o[0],{cachedAt:r}));const i=Qo(s);return ct("local.follow.created",i),n},follow:async e=>{const t=Re();t.log("follow/follow",e);const{data:n}=await t.http.post(`/api/v4/me/following/${e}`),r=t.cache&&Date.now();t.cache&&Xt(n,{cachedAt:r});const a=Qo(n);return"accepted"===n.follows[0].status?ct("local.follow.created",a):ct("local.follow.requested",a),{data:n.follows[0],cachedAt:r}},unfollow:async e=>{const t=Re();t.log("follow/unfollow",e);const{data:n}=await t.http.delete(`/api/v4/me/following/${e}`);t.cache&&Xt(n);const r=Qo(n);return ct("local.follow.unfollowed",r),!0},acceptMyFollower:async e=>{const t=Re();t.log("follow/acceptMyFollower",e);const{data:n}=await t.http.post(`/api/v4/me/followers/${e}`);t.cache&&Xt(n);const r=Qo(n);return ct("local.follow.accepted",r),!0},declineMyFollower:async e=>{const t=Re();t.log("follow/declineMyFollower",e);const{data:n}=await t.http.delete(`/api/v4/me/followers/${e}`);t.cache&&Xt(n);const r=Qo(n);return ct("local.follow.requestDeclined",r),!0},onUserFollowed:Ho,onUserUnfollowed:Jo,onFollowerDeleted:Wo,onFollowerRequested:Go,onFollowRequestCanceled:Yo,onFollowRequestAccepted:Xo,onFollowRequestDeclined:Zo,onFollowInfoUpdated:ts,onLocalUserFollowed:ns,onLocalUserUnfollowed:rs,onLocalFollowerRequested:as,onLocalFollowRequestAccepted:os,onLocalFollowRequestDeclined:ss,getFollowers:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getFollowers(tmpid: ${o}) > listen`);const s=new gs(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`getFollowers(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getFollowings:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log("For using Live Collection feature you need to enable Cache!");const o=Date.now();r(`getFollowings(tmpid: ${o}) > listen`);const s=new ws(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`getFollowings(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getFollowInfo:(e,t)=>Cs(e,t,"userId",es,[ts],{forceDispatch:!0}),getMyFollowInfo:e=>{const{userId:t}=tt();return Cs(t,e,"userId",es,[ts],{forceDispatch:!0})}});class Ss{constructor(e,t,n){this._syncingStoriesCount=0,this._errorStoriesCount=0,this._targetId=e,this._lastStoryExpiresAt=t,this._lastStorySeenExpiresAt=n,this.cacheStoryExpireTime=je(["story-expire",this._targetId]),this.cacheStoreSeenTime=je(["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=je(["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 je(["story-sync-state",this._targetId]),this.isContainUnSyncedStory?this.localLastStoryExpires>e&&this.localLastStoryExpires>t:this.lastStoryExpiresAt>e&&this.lastStoryExpiresAt>t}getTotalStoryByStatus(){const e=Me(["story","get"]);if(!e)return this._errorStoriesCount=0,void(this._syncingStoriesCount=0);const t=e.reduce(((e,t)=>{const{data:{targetId:n,syncState:r,isDeleted:a}}=t;return n!==this._targetId||a||(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 _s=e=>{const{targetType:t,targetId:n,lastStoryExpiresAt:r,lastStorySeenExpiresAt:a,targetUpdatedAt:o,localFilter:s}=e,i=new Ss(n,r,a);return{targetType:t,targetId:n,lastStoryExpiresAt:r,updatedAt:o,hasUnseen:i.getHasUnseenFlag(),syncingStoriesCount:i.syncingStoriesCount,failedStoriesCount:i.failedStoriesCount,localFilter:s,localLastExpires:i.localLastStoryExpires,localLastSeen:i.localLastStorySeenExpiresAt,localSortingDate:i.getLocalLastSortingDate()}},ks=async e=>{const t=Re();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,a=en(e,["isPublic"]);n=await t.http.post("/api/v3/channels",Object.assign(Object.assign({},a),{isPublic:"community"===(null==e?void 0:e.type)?r:void 0}))}const r=await zn(n.data),a=t.cache&&Date.now();t.cache&&Xt(r,{cachedAt:a});const{channels:o}=r;return{data:$r(o[0]),cachedAt:a}},Os=async e=>{const t=Re();let n;t.log("channel/getChannel",e),mn("channel",e);try{const{data:r}=await t.http.get(`/api/v3/channels/${encodeURIComponent(e)}`);n=await zn(r),t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&Hn(r)}catch(t){throw ae(null==t?void 0:t.code)&&Zt("channel",e),t}const r=t.cache&&Date.now();t.cache&&Xt(n,{cachedAt:r});const{channels:a}=n;return{data:a.find((t=>t.channelId===e)),cachedAt:r}};Os.locally=e=>{var t;const n=Re();if(n.log("channel/getChannel.locally",e),!n.cache)return;const r=null===(t=Me(["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 Ts=Symbol("getWatcherUrls"),Es=e=>Object.assign(Object.assign({},e),{get moderation(){var t;return null===(t=je(["streamModeration","get",e.streamId]))||void 0===t?void 0:t.data},get post(){var t;if("post"===e.referenceType)return null===(t=je(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=je(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;return null===(t=je(["user","get",e.userId]))||void 0===t?void 0:t.data},get childStreams(){return e.childStreamIds&&0!==e.childStreamIds.length?e.childStreamIds.map((e=>{var t;const n=null===(t=je(["stream","get",e]))||void 0===t?void 0:t.data;if(n)return Es(n)})).filter(fs):[]},getLiveChat:()=>(async e=>{var t;const n=Re();if(n.log("stream/getLiveChat",e.streamId),e.channelId){const n=null===(t=je(["channel","get",e.channelId]))||void 0===t?void 0:t.data;if(n)return Kr($r(n));const{data:r}=await Os(e.channelId);return Kr($r(r))}if(e.userId===n.userId){const{data:t}=await ks({type:"live",postId:e.postId,videoStreamId:e.streamId});return xe(["stream","get",e.streamId],{channelId:t.channelId}),t}})(e),isBanned:!e.watcherUrl,watcherUrl:null,get[Ts](){return e.watcherUrl}}),As=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=je(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),Rs=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=je(["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=je(["user","get",e.userId]);if(null==t?void 0:t.data)return cn(t.data)},get childrenComment(){return e.children.map((e=>{const t=je(["comment","get",e]);if(null==t?void 0:t.data)return null==t?void 0:t.data})).filter(fs).map((e=>Rs(e)))}});function Ps(e){return!!(e.data&&"string"!=typeof e.data&&"videoFileId"in e.data&&"thumbnailFileId"in e.data&&"video"===e.dataType)}function Ms(e){return!(!e.data||"string"==typeof e.data||!("streamId"in e.data)||"liveStream"!==e.dataType)}const js=e=>pn(e,{childrenPosts:e.children.map((e=>{var t;return null===(t=je(["post","get",e]))||void 0===t?void 0:t.data})).filter(fs).map(js),analytics:{markAsViewed:()=>{_a().markPostAsViewed(e.postId)}},get latestComments(){return e.comments&&e.comments.map((e=>{var t;const n=null===(t=je(["comment","get",e]))||void 0===t?void 0:t.data;return n?Rs(n):null})).filter(Boolean)||[]},get creator(){const t=je(["user","get",e.postedUserId]);if(null==t?void 0:t.data)return cn(t.data)},getImageInfo(){var t,n;return function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"image"!==e.dataType)}(e)?null===(n=je(["file","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.fileId]))||void 0===n?void 0:n.data:void 0},getVideoInfo(){var t,n,r;return Ps(e)?null===(r=je(["file","get",null===(n=null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.videoFileId)||void 0===n?void 0:n.original]))||void 0===r?void 0:r.data:void 0},getVideoThumbnailInfo(){var t,n;return Ps(e)?null===(n=je(["file","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.thumbnailFileId]))||void 0===n?void 0:n.data:void 0},getFileInfo(){var t,n;return function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"file"!==e.dataType)}(e)?null===(n=je(["file","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.fileId]))||void 0===n?void 0:n.data:void 0},getLivestreamInfo(){var t,n;if(!Ms(e))return;const r=null===(n=je(["stream","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.streamId]))||void 0===n?void 0:n.data;return r?Es(r):void 0},getPollInfo(){var t,n;if(!function(e){return!(!e.data||"string"==typeof e.data||!("pollId"in e.data)||"poll"!==e.dataType)}(e))return;const r=null===(n=je(["poll","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.pollId]))||void 0===n?void 0:n.data;return r||void 0},getClipInfo(){var t,n;return function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"clip"!==e.dataType)}(e)?null===(n=je(["file","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.fileId]))||void 0===n?void 0:n.data:void 0},getAudioInfo(){var t,n;return function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"audio"!==e.dataType)}(e)?null===(n=je(["file","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.fileId]))||void 0===n?void 0:n.data:void 0},getRoomInfo(){var t,n;if(function(e){return!(!e.data||"string"==typeof e.data||!("roomId"in e.data)||"room"!==e.dataType)}(e))return null===(n=je(["room","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.roomId]))||void 0===n?void 0:n.data}}),Us=(e,t)=>{"message"===e?ct("local.message.updated",{messages:[t]}):"post"===e?ct("post.updated",{posts:[t]}):"comment"===e?ct("comment.updated",{comments:[t]}):"story"===e&&ct("story.updated",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[t]})},xs=async(e,t,n,r)=>{var a,o,s;const i=Re();if(i.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new ke("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:c}=await i.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:r});if(i.cache){const r=je([e,"get",t]);if(!r||(null===(a=r.data.myReactions)||void 0===a?void 0:a.includes(n)))return!0;const l=Object.assign(Object.assign({},r.data),{reactionsCount:r.data.reactionsCount+1,myReactions:[...null!==(o=r.data.myReactions)&&void 0!==o?o:[],n],reactions:Object.assign(Object.assign({},r.data.reactions),{[n]:(null!==(s=r.data.reactions[n])&&void 0!==s?s:0)+1}),updatedAt:(new Date).toISOString()});if("comment"===e)return ct("local.comment.addReaction",{comment:l,reactor:{userId:i.userId,reactionName:n,reactionId:c.addedId}}),!0;if("post"===e)return ct("local.post.addReaction",{post:l,reactor:{userId:i.userId,reactionName:n,reactionId:c.addedId}}),!0;if("story"===e)return ct("local.story.reactionAdded",{story:l,reactor:{userId:i.userId,reactionName:n,reactionId:c.addedId}}),!0}return!0};xs.optimistically=(e,t,n)=>{var r,a,o,s,i;const c=Re();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const l=je([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!==(a=l.data.myReactions)&&void 0!==a?a:[],n],reactions:Object.assign(Object.assign({},l.data.reactions),{[n]:(null!==(o=l.data.reactions[n])&&void 0!==o?o:0)+1})});return De([e,"get",t],d,{cachedAt:G}),Us(e,d),null!==(i=null===(s=null==d?void 0:d.myReactions)||void 0===s?void 0:s.includes(n))&&void 0!==i&&i};const Ds=(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=je(["messageMarker","get",Ce("messageMarker")(r)]))||void 0===n?void 0:n.data})(e))&&void 0!==n?n:{readCount:0,deliveredCount:0}},qs=(e,t)=>{const n=t.publicId!==t.messageId;return(async(e,t,n,r)=>{var a,o;const s=Re();if(s.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new ke("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:i}=await s.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:r}});if(s.cache){const r=je([e,"get",t]);if(!r)return!0;const c=Object.assign(Object.assign({},r.data),{reactionsCount:Math.max(0,r.data.reactionsCount-1),myReactions:(null!==(a=r.data.myReactions)&&void 0!==a?a:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},r.data.reactions),{[n]:Math.max(0,(null!==(o=r.data.reactions[n])&&void 0!==o?o:0)-1)}),updatedAt:(new Date).toISOString()});if("comment"===e)return ct("local.comment.removeReaction",{comment:c,reactor:{reactionId:i.removedId,reactionName:n,userId:s.userId}}),!0;if("post"===e)return ct("local.post.removeReaction",{post:c,reactor:{reactionId:i.removedId,reactionName:n,userId:s.userId}}),!0;if("story"===e)return ct("local.story.reactionAdded",{story:c,reactor:{userId:s.userId,reactionName:n,reactionId:i.removedId}}),!0}return!0})("message",n?t.publicId:t.messageId,e,n?3:5)};function Ns(e,t){return e.map((e=>{const n=je(["community","get",e.communityId]);if((null==n?void 0:n.data)&&(null==n?void 0:n.data.hasOwnProperty("isJoined")))return Object.assign(Object.assign({},n.data),e);const r=t.some((t=>function(e,t){const{userId:n}=tt();return e.communityId===t.communityId&&t.userId===n}(e,t)&&"none"!==t.communityMembership));return Object.assign(Object.assign({},e),{isJoined:r})}))}const Bs=e=>{var t;return null!==(t=Object.keys(R).find((t=>e.needApprovalOnPostCreation===R[t].needApprovalOnPostCreation&&e.onlyAdminCanPost===R[t].onlyAdminCanPost)))&&void 0!==t?t:P};function Ls({communities:e}){return e.map((e=>{var{needApprovalOnPostCreation:t,onlyAdminCanPost:n}=e,r=en(e,["needApprovalOnPostCreation","onlyAdminCanPost"]);return Object.assign({postSetting:Bs({needApprovalOnPostCreation:t,onlyAdminCanPost:n})},r)}))}const Fs=e=>{const t=Ls({communities:e.communities}),n=e.users.map(An),r=e.communityUsers.map((e=>{const t=n.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),a=Ns(t,r);return Object.assign(Object.assign({},e),{users:e.users.map(An),communities:a,communityUsers:r})},Ks=e=>{const t=e.joinRequests.map((e=>Object.assign(Object.assign({},e),{joinRequestId:e._id}))),n=e.users.map(An);return Object.assign(Object.assign({},e),{joinRequests:t,users:n})},$s=e=>{const t=Ls({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=Ns(t,n);return Object.assign(Object.assign({},e),{communities:r,communityUsers:n})},Qs=e=>{const{postSetting:t,storySetting:n}=e,r=en(e,["postSetting","storySetting"]);return Object.assign(Object.assign(Object.assign({},r),t?R[t]:void 0),{allowCommentInStory:"boolean"!=typeof(null==n?void 0:n.enableComment)||n.enableComment})},zs=e=>{var t=en(e,["searchResult"]);const n=Fs(t);return Object.assign({},n)},Vs=e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=je(["user","get",e.requestorPublicId]))||void 0===t?void 0:t.data;if(n)return cn(n)},cancel:async()=>{await(async e=>{var t;const n=Re();n.log("joinRequest/cancelJoinRequest",e.joinRequestId);const{data:r}=await n.http.delete(`/api/v4/communities/${e.targetId}/join`),a=null===(t=je(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return a&&(De(["joinRequest","get",e.joinRequestId],{status:"cancelled"}),ct("local.joinRequest.deleted",[a])),r.success})(e)},approve:async()=>{await(async e=>{var t;const n=Re();n.log("joinRequest/approveJoinRequest",e.joinRequestId);const{data:r}=await n.http.post(`/api/v4/communities/${e.targetId}/join/approve`,{userId:e.requestorInternalId}),a=null===(t=je(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return a&&(De(["joinRequest","get",e.joinRequestId],{status:"approved"}),ct("local.joinRequest.updated",[a])),r.success})(e)},reject:async()=>{await(async e=>{var t;const n=Re();n.log("joinRequest/rejectJoinRequest",e.joinRequestId);const{data:r}=await n.http.post(`/api/v4/communities/${e.targetId}/join/reject`,{userId:e.requestorInternalId}),a=null===(t=je(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return a&&(De(["joinRequest","get",e.joinRequestId],{status:"rejected"}),ct("local.joinRequest.updated",[a])),r.success})(e)}});class Hs extends is{async getRequest(e,t){const{limit:n=20,communityId:r}=e,a=en(e,["limit","communityId"]),o=t?{token:t}:{limit:n},{data:s}=await this.http.get(`/api/v4/communities/${r}/join`,{params:Object.assign(Object.assign({},a),{options:o})});return s}}var Js;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(Js||(Js={}));class Ws extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.joinRequests.map((e=>Ce("joinRequest")({joinRequestId:e._id})))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>Ce("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(e===Js.OnLocalJoinRequestUpdated){if(!r.data.find((e=>e===t[0].joinRequestId)))return}e===Js.OnLocalJoinRequestCreated&&(r.data=[...new Set([...t.map((e=>e.joinRequestId)),...r.data])]),e===Js.OnLocalJoinRequestDeleted&&(r.data=r.data.filter((e=>e!==t[0].joinRequestId))),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Gs=e=>{const t=Re(),n=[it(t,"onJoinRequestCreated","local.joinRequest.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Ys=e=>{const t=Re(),n=[it(t,"onJoinRequestUpdated","local.joinRequest.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Xs=e=>{const t=Re(),n=[it(t,"onJoinRequestDeleted","local.joinRequest.deleted",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class Zs extends ps{constructor(e,t){const n=I.default(e),r=["joinRequest","collection",n];super(new Hs(e),n,r,t),this.query=e,this.queryStreamController=new Ws(this.query,this.cacheKey,this.notifyChange.bind(this),Ks),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){const r=e;this.queryStreamController.appendToQueryStream(r,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Gs,action:Js.OnLocalJoinRequestCreated},{fn:Ys,action:Js.OnLocalJoinRequestUpdated},{fn:Xs,action:Js.OnLocalJoinRequestDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r;const a=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const o=this.applyFilter(a.data.map((e=>je(["joinRequest","get",e]))).filter(fs).map((({data:e})=>e)).map(Vs));(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;this.query.status&&(t=t.filter((e=>e.status===this.query.status)));const n=(()=>"firstCreated"===this.query.sortBy?Je:Ge)();return t=t.sort(n),t}}const ei=e=>Object.assign(Object.assign({},e),{createdById:e.createdBy}),ti=e=>Object.assign(Object.assign({},e),{invitations:e.invitations.map(ei),users:e.users.map(An)}),ni=e=>Object.assign(Object.assign({},e),{users:e.users.map(An),invitations:e.invitations.map(ei)}),ri=e=>Object.assign(Object.assign({},e),{get user(){const t=je(["user","get",e.invitedUserPublicId]);if(null==t?void 0:t.data)return cn(t.data)},get createdBy(){const t=je(["user","get",e.inviterUserPublicId]);if(null==t?void 0:t.data)return cn(t.data)},get target(){if("community"===e.targetType){const t=je(["community","get",e.targetId]);return(null==t?void 0:t.data)?t.data:void 0}},accept:async()=>{await(async e=>{var t;const n=Re();n.log("invitation/acceptInvitation",e);const{data:r}=await n.http.post(`/api/v1/invitations/${e}/accept`),a=null===(t=je(["invitation","get",e]))||void 0===t?void 0:t.data;return a&&(De(["invitation","get",e],{status:"approved"}),ct("local.invitation.updated",[a])),r.success})(e._id)},reject:async()=>{await(async e=>{var t;const n=Re();n.log("invitation/rejectInvitation",e);const{data:r}=await n.http.post(`/api/v1/invitations/${e}/reject`),a=null===(t=je(["invitation","get",e]))||void 0===t?void 0:t.data;return a&&(De(["invitation","get",e],{status:"rejected"}),ct("local.invitation.updated",[a])),r.success})(e._id)}});var ai;!function(e){e.OnLocalInvitationCreated="onLocalInvitationCreated",e.OnLocalInvitationUpdated="onLocalInvitationUpdated",e.OnLocalInvitationDeleted="onLocalInvitationDeleted"}(ai||(ai={}));class oi extends is{async getRequest(e,t){const{limit:n=V}=e,r=en(e,["limit"]),a=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/invitations",{params:Object.assign(Object.assign({},r),{options:a})});return o}}class si extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.invitations.map(Ce("invitation"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(Ce("invitation"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(e===ai.OnLocalInvitationUpdated){if(!r.data.find((e=>e===t[0].invitationId)))return}e===ai.OnLocalInvitationCreated&&(r.data=[...new Set([...t.map((e=>e.invitationId)),...r.data])]),e===ai.OnLocalInvitationDeleted&&(r.data=r.data.filter((e=>e!==t[0].invitationId))),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const ii=e=>{const t=Re(),n=[it(t,"onLocalInvitationCreated","local.invitation.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},ci=e=>{const t=Re(),n=[it(t,"onLocalInvitationUpdated","local.invitation.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},li=e=>{const t=Re(),n=[it(t,"onLocalInvitationDeleted","local.invitation.deleted",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class di extends ps{constructor(e,t){const n=I.default(e),r=["invitation","collection",n];super(new oi(e),n,r,t),this.query=e,this.queryStreamController=new si(this.query,this.cacheKey,this.notifyChange.bind(this),ti),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(this.cacheKey,{data:[],params:this.query})}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:ai.OnLocalInvitationCreated},{fn:ci,action:ai.OnLocalInvitationUpdated},{fn:li,action:ai.OnLocalInvitationDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["invitation","get",e]))).filter(fs).map((({data:e})=>ri(e))))&&void 0!==a?a:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;this.query.targetId&&(t=t.filter((e=>e.targetId===this.query.targetId))),this.query.statuses&&(t=t.filter((e=>{var t;return null===(t=this.query.statuses)||void 0===t?void 0:t.includes(e.status)}))),this.query.targetType&&(t=t.filter((e=>e.targetType===this.query.targetType))),this.query.type&&(t=t.filter((e=>e.type===this.query.type)));const n=(()=>"firstCreated"===this.query.sortBy?Je:Ge)();return t=t.sort(n),t}}const ui=e=>Object.assign(Object.assign({},e),{get categories(){var t;return(null!==(t=null==e?void 0:e.categoryIds)&&void 0!==t?t:[]).map((e=>{const t=je(["category","get",e]);if(null==t?void 0:t.data)return As(t.data)})).filter((e=>!!e))},createInvitations:async t=>{await(async e=>{const t=Re();t.log("invitation/createInvitations",e);const{data:n}=await t.http.post("/api/v1/invitations",e),r=ti(n),a=t.cache&&Date.now();return t.cache&&Xt(r,{cachedAt:a}),ct("local.invitation.created",r.invitations),{data:r.invitations,cachedAt:a}})({type:"communityMemberInvite",targetType:"community",targetId:e.communityId,userIds:t})},getMemberInvitations:(t,n)=>((e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getInvitations: (tmpid: ${o}) > listen`);const s=new di(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>{qe(c)})),()=>{r(`getInvitations (tmpid: ${o}) > dispose`),i.forEach((e=>e()))}})(Object.assign(Object.assign({},t),{targetId:e.communityId,targetType:"community",type:"communityMemberInvite"}),n),getInvitation:async()=>{const{data:t}=await(async(e,t)=>{const n=Re();n.log("invitation/getInvitation",e,t);const{data:r}=await n.http.get("/api/v1/invitations/me",{params:{targetType:e,targetId:t}}),a=ni(r),o=n.cache&&Date.now();return n.cache&&Xt(a,{cachedAt:o}),{data:a.invitations[0]?ri(a.invitations[0]):void 0,cachedAt:o}})("community",e.communityId);return t},join:async()=>(async e=>{var t;const n=Re();n.log("community/joinRequest",e);const{data:r}=await n.http.post(`/api/v4/communities/${e}/join`),a=Ks(r),o=n.cache&&Date.now();n.cache&&Xt(a,{cachedAt:o});const s="approved"===a.joinRequests[0].status?"success":"pending";if("success"===s&&n.cache){const n=null===(t=je(["community","get",e]))||void 0===t?void 0:t.data;if(n){const t=Object.assign(Object.assign({},n),{isJoined:!0});De(["community","get",e],t)}}return ct("v4.local.community.joined",a.joinRequests),"success"===s?{status:s}:{status:s,request:Vs(a.joinRequests[0])}})(e.communityId),getJoinRequests:(t,n)=>((e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getJoinRequests: (tmpid: ${o}) > listen`);const s=new Zs(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>{qe(c)})),()=>{r(`getJoinRequests (tmpid: ${o}) > dispose`),i.forEach((e=>e()))}})(Object.assign(Object.assign({},t),{communityId:e.communityId}),n),getMyJoinRequest:async()=>{const{data:t}=await(async e=>{const t=Re();t.log("community/myJoinRequest",e);const{data:n}=await t.http.get(`/api/v4/communities/${e}/join/me`),r=Ks(n),a=t.cache&&Date.now();return t.cache&&Xt(r,{cachedAt:a}),{data:r.joinRequests[0]?Vs(r.joinRequests[0]):void 0,cachedAt:a}})(e.communityId);return t}}),hi={ad:e=>{const t=_a(),{image9_16:n,image1_1:r}=e,a=en(e,["image9_16","image1_1"]);return Object.assign(Object.assign({},a),{analytics:{markAsSeen:n=>{t.markAdAsViewed(e,n)},markLinkAsClicked:n=>{t.markAdAsClicked(e,n)}},get advertiser(){var t,n;const r=null===(t=je(["advertiser","get",e.advertiserId]))||void 0===t?void 0:t.data;if(!r)return;const a=null===(n=je(["file","get",r.avatarFileId]))||void 0===n?void 0:n.data;return Object.assign(Object.assign({},r),{avatar:a})},get image1_1(){const e=je(["file","get",r]);if(e)return e.data||void 0},get image9_16(){const e=je(["file","get",n]);if(e)return e.data||void 0}})},comment:Rs,post:js,user:cn,category:As,stream:Es,story:e=>{const t=_a(),n=je(["storyTarget","get",e.targetId]),r=je(["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=je(["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:a}=r;return a||void 0},get imageData(){var t,n;if(!(null===(t=e.data)||void 0===t?void 0:t.fileId))return;const r=je(["file","get",null===(n=e.data)||void 0===n?void 0:n.fileId]);if(!r)return;const{data:a}=r;return a?Object.assign(Object.assign({},a),{fileUrl:`${a.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=je(["category","get",e]);return(null==t?void 0:t.data)||void 0})).filter((e=>void 0!==e)):void 0},get creator(){const t=je(["user","get",e.creatorPublicId]);if(null==t?void 0:t.data)return cn(t.data)},get storyTarget(){if(null==n?void 0:n.data)return _s(n.data)},get isSeen(){const t=je(["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,a=new Date(null==n?void 0:n.data.lastStorySeenExpiresAt).getTime()||0,o=new Date(e.expiresAt).getTime();return Math.max(r,a)>=o}})},storyTarget:_s,message:e=>{const t=en(e,["creatorPrivateId"]);return Object.assign(Object.assign({},t),{get readCount(){return Ds(e).readCount},get deliveredCount(){return Ds(e).deliveredCount},get creator(){var t;return null===(t=je(["user","get",e.creatorId]))||void 0===t?void 0:t.data},markRead:()=>lo(e),addReaction:t=>((e,t)=>{const n=t.publicId!==t.messageId;return xs("message",n?t.publicId:t.messageId,e,n?3:5)})(t,e),removeReaction:t=>qs(t,e)})},reactor:e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=je(["user","get",e.userId]))||void 0===t?void 0:t.data;if(n)return cn(n)}}),channel:Kr,pinnedPost:e=>{var t;const n=je(["post","get",e.referenceId]),r=null===(t=Me(["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 js(n.data)},get target(){const e=je(["pinTarget","get",null==n?void 0:n.data.targetId]);if(null==e?void 0:e.data)return null==e?void 0:e.data}})},notificationTray:e=>Object.assign(Object.assign({},e),{isSeen:e.lastSeenAt>e.lastOccurredAt,isRecent:new Date(e.lastOccurredAt).getTime()>=Date.now()-6048e5,users:e.actors.map((({publicId:e})=>je(["user","get",e]))).filter(fs).map((({data:e})=>e)).map((e=>cn(e)))}),community:ui,invitation:ri,joinRequest:Vs,channelMember:Xn},pi=async e=>{const t=Re();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}}),a=fa(r),o=t.cache&&Date.now();return t.cache&&Xt(a,{cachedAt:o}),ct("user.fetched",r),{data:a.users.map((e=>hi.user(e))),cachedAt:o}};pi.locally=e=>{var t;const n=Re();if(n.log("user/getUsers.locally",e),!n.cache)return;const r=e.map((e=>je(["user","get",e]))).filter(Boolean),a=r.map((({data:e})=>hi.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:a,cachedAt:o.cachedAt}};const fi=e=>ma("user.updated",e),mi=e=>ma("user.flagged",e),gi=e=>ma("user.unflagged",e),yi=e=>ma("user.flagCleared",e),vi=e=>ma("user.fetched",e),bi=async e=>{const t=Re();t.log("user/getUser",e),mn("user",e);try{const{data:n}=await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`),r=t.cache&&Date.now(),a=fa(n);return t.cache&&Xt(a,{cachedAt:r}),ct("user.fetched",n),{data:a.users.find((t=>t.userId===e)),cachedAt:r}}catch(t){throw ae(null==t?void 0:t.code)&&Zt("user",e),t}};bi.locally=e=>{const t=Re();if(t.log("user/getUser.locally",e),!t.cache)return;const n=je(["user","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class wi extends is{async getRequest(e,t){const{limit:n=V}=e,r=en(e,["limit"]),a=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},r),{options:a,isDeleted:!1})});return o}}class Ci extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.users.map(Ce("user"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Ce("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=je(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],Ue(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Ii;!function(e){e.OnUserDeleted="onUserDeleted",e.OnUserUpdated="onUserUpdated",e.OnUserFlagged="onUserFlagged",e.OnUserUnflagged="onUserUnflagged",e.OnUserFlagCleared="onUserFlagCleared"}(Ii||(Ii={}));class Si extends ps{constructor(e,t){const n=I.default(e),r=["user","collection",n];super(new wi(e),n,r,t),this.query=e,this.queryStreamController=new Ci(this.query,this.cacheKey,this.notifyChange.bind(this),fa),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:ga,action:Ii.OnUserDeleted},{fn:fi,action:Ii.OnUserUpdated},{fn:mi,action:Ii.OnUserFlagged},{fn:gi,action:Ii.OnUserUnflagged},{fn:yi,action:Ii.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["user","get",e]))).filter(fs).map((({data:e})=>e)).map(hi.user))&&void 0!==a?a:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;const n=(()=>"firstCreated"===this.query.sortBy?Je:Ge)();return t=t.sort(n),"flagged"===this.query.filter&&(t=t.filter((e=>!!e.hashFlag))),t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}class _i extends is{async getRequest(e,t){const{limit:n=V}=e,r=en(e,["limit"]),a=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v4/me/user-blocks",{params:Object.assign(Object.assign({},r),{options:a,isDeleted:!1})});return o}}class ki extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.users.map(Ce("user"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Ce("user"))])]}))}}reactor(e){return t=>{var n;if(e===ds.OnFollowed){const e=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data,r=null==e?void 0:e.data.filter((e=>e!==t.userId));Ue(this.cacheKey,Object.assign(Object.assign({},e),{data:r}))}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}function Oi(e){const{users:t,follows:n}=e,r=en(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:An(n)})})),users:t.map(An)})}const Ti=(e,t,n)=>r=>e((e=>{var a;if(!e)return e;const o=[n,"get",`${e[t]}`],s=null===(a=je(o))||void 0===a?void 0:a.data;return s?r(s):void 0}));class Ei extends ps{constructor(e,t){const n=I.default(e),r=["blockedUsers","collection",n];super(new _i(e),n,r,t),this.query=e,this.queryStreamController=new ki(this.query,this.cacheKey,this.notifyChange.bind(this),Oi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:ga,action:Ii.OnUserDeleted},{fn:Ti(ns,"to","user"),action:ds.OnFollowed},{fn:Ti(Ho,"to","user"),action:ds.OnFollowed}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["user","get",e]))).filter(fs).map((({data:e})=>e)).map(hi.user))&&void 0!==a?a:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,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}}class Ai extends is{async getRequest(e,t){const{limit:n=V,displayName:r}=e,a=en(e,["limit","displayName"]),o=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},a),{keyword:null==r?void 0:r.toLocaleLowerCase(),options:o,isDeleted:!1})});return s}}class Ri extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.users.map(Ce("user"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Ce("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=je(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],Ue(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Pi extends ps{constructor(e,t){var n;const r=I.default(e),a=["user","collection",r];super(new Ai(e),r,a,t),this.query=Object.assign(Object.assign({},e),{filter:null!==(n=e.filter)&&void 0!==n?n:"all"}),this.queryStreamController=new Ri(this.query,this.cacheKey,this.notifyChange.bind(this),fa),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:ga,action:Ii.OnUserDeleted},{fn:fi,action:Ii.OnUserUpdated},{fn:mi,action:Ii.OnUserFlagged},{fn:gi,action:Ii.OnUserUnflagged},{fn:yi,action:Ii.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["user","get",e]))).filter(fs).map((({data:e})=>e)).map(hi.user))&&void 0!==a?a:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,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 Mi=async({viewId:e,viewedType:t,limit:n,token:r})=>{const a=Re(),o={};r?o.token=r:o.limit=n;const s=`/api/v1/analytics/views/${"post"===t?"posts":"stories"}/${e}/users`,i=await a.http.get(s,{params:o});return Xt(i.data),i.data};var ji;!function(e){e.DEFAULT="default",e.PARTIAL="partial"}(ji||(ji={}));var Ui=Object.freeze({__proto__:null,Relationship:Is,getUserByIds:pi,updateUser:async(e,t)=>{const n=Re();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})),a=fa(r),o=n.cache&&Date.now();return n.cache&&Xt(a,{cachedAt:o}),ct("user.updated",r),{data:a.users.find((t=>t.userId===e)),cachedAt:o}},flagUser:async e=>{const t=Re();t.log("user/flagUser",e);const{data:n}=await t.http.post(`api/v4/me/flags/${encodeURIComponent(e)}`),r=fa(n);return t.cache&&Xt(r),ct("user.flagged",n),!!r},unflagUser:async e=>{const t=Re();t.log("user/unflag",e);const{data:n}=await t.http.delete(`/api/v4/me/flags/${encodeURIComponent(e)}`),r=fa(n);return t.cache&&Xt(r),ct("user.unflagged",n),!!r},isUserFlaggedByMe:async e=>{const t=Re();t.log("user/isUserFlaggedByMe",e);const{data:{isFlagByMe:n}}=await t.http.get(`/api/v3/users/${e}/isFlagByMe`);return n},onUserUpdated:fi,onUserDeleted:ga,onUserFlagged:mi,onUserUnflagged:gi,onUserFlagCleared:yi,getUser:(e,t)=>Cs(e,(e=>t(Object.assign(Object.assign({},e),{data:e.data?hi.user(e.data):e.data}))),"userId",bi,[vi,fi,ga,mi,gi,yi]),getUsers:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`liveUsers(tmpid: ${o}) > listen`);const s=new Si(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`liveUsers(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getBlockedUsers:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getBlockedUsers(tmpid: ${o}) > listen`);const s=new Ei(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`getBlockedUsers(tmpid: ${o}) > dispose`),i.forEach((e=>e())),qe(c)}},searchUserByDisplayName:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`liveSearchUsers(tmpid: ${o}) > listen`);const s=new Pi(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`liveSearchUsers(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getReachedUsers:(e,t)=>{let n=(e=!1)=>{};const{log:r,cache:a}=Re(),o=["viewedUsers","collection",{viewId:e.viewId,viewedType:e.viewedType}];a||console.log(J);const s=Date.now();r(`getReachUsers(tmpid: ${s}) > listen`);const{limit:i,viewId:c,viewedType:l}=e;return n=(e=!1)=>{var r,a,s;const d=null===(r=je(o))||void 0===r?void 0:r.data,u=null!==(a=null==d?void 0:d.data)&&void 0!==a?a:[];if(!e&&u.length>0&&!(null==d?void 0:d.params.page))return;const h=ge(Mi,{viewId:c,viewedType:l,limit:i||10,token:e||null===(s=null==d?void 0:d.params.page)||void 0===s?void 0:s.next});ve(h,(e=>{var r,a,s,i,c;let l=null!==(s=null===(a=null===(r=je(o))||void 0===r?void 0:r.data)||void 0===a?void 0:a.data)&&void 0!==s?s:[];(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||[]};Ue(o,d),(e=>{var r,a;let o=[];(null==e?void 0:e.data)&&(o=e.data.map((e=>je(["user","get",e]))).filter(Boolean).map((e=>null==e?void 0:e.data))||[]),t({onNextPage:n,data:o,hasNextPage:!!(null===(a=null===(r=e.params)||void 0===r?void 0:r.page)||void 0===a?void 0:a.next),loading:e.loading||!1})})(d)}),ye(H,2e3))},n(!0),()=>{r(`getReachUsers(tmpid: ${s}) > dispose`),qe(o)}},get AmityUserSearchMatchType(){return ji}});const xi=async e=>{const t=Re();t.log("file/getFile",e);const{data:n}=await t.http.get(`/api/v3/files/${e}`),r=t.cache&&Date.now();return t.cache&&Xt({files:[n]},{cachedAt:r}),{data:n,cachedAt:r}};xi.locally=e=>{const t=Re();if(t.log("file/getFile.locally",e),!t.cache)return;const n=je(["file","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Di=async(e,t,n)=>{const r=Re();r.log("file/uploadVideo",e);const a=e.getAll("files");if(!a.length)throw new Error("The formData object must have a `files` key.");const o=Ao().getFileAccessType();e.append("accessType",o),e.append("preferredFilename",a[0].name),t&&e.append("feedType",t);const s="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await r.upload.post("/api/v4/videos",e,{headers:s,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),c=r.cache&&Date.now();return r.cache&&Xt({files:i},{cachedAt:c}),{data:i,cachedAt:c}},qi=async(e,t,n)=>{const r=Re();r.log("file/uploadImage",e);const a=e.getAll("files");if(null==a?void 0:a.length)console.warn("Deprecation Warning: `files` is deprecated, please use `file` instead."),e.append("preferredFilename",a[0].name);else{const t=e.get("file");if(!t)throw new Error("The formData object must have a `file` or `files` key");e.append("preferredFilename",t.name),n&&e.append("altText",n)}const o=Ao().getFileAccessType();e.append("accessType",o);const s="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await r.upload.post("/api/v4/images",e,{headers:s,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),c=r.cache&&Date.now();return r.cache&&Xt({files:i},{cachedAt:c}),{data:i,cachedAt:c}};var Ni=Object.freeze({__proto__:null,getFile:xi,uploadFile:async(e,t)=>{const n=Re();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 a=Ao().getFileAccessType();e.append("accessType",a),e.append("preferredFilename",r[0].name);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:s}=await n.upload.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&&Xt({files:s},{cachedAt:i}),{data:s,cachedAt:i}},deleteFile:async e=>{const t=Re();return t.log("file/deleteFile",e),await t.http.delete(`/api/v3/files/${e}`),qe(["file","get",e],!0),{success:!0}},fileUrlWithSize:(e,t)=>`${e}?size=${t}`,uploadVideo:Di,uploadImage:qi,updateAltText:async(e,t)=>{const n=Re();n.log("file/updateAltText",t);const{data:r}=await n.http.put(`/api/v3/files/${e}`,{altText:t}),a=n.cache&&Date.now();return n.cache&&Xt({files:[r]},{cachedAt:a}),!0},uploadClip:async(e,t,n)=>{const r=Re();r.log("file/uploadClip",e);const a=e.get("files");if(!a)throw new Error("The formData object must have a `files` key.");const o=Ao().getFileAccessType();e.append("accessType",o),e.append("preferredFilename",a.name),t&&e.append("feedType",t);const s="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await r.upload.post("/api/v4/clips",e,{headers:s,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),c=r.cache&&Date.now();return r.cache&&Xt({files:i},{cachedAt:c}),{data:i,cachedAt:c}},uploadAudio:async(e,t)=>{const n=Re();n.log("file/uploadAudio",e);const r=e.get("file");if(!r)throw new Error("The formData object must have a `file` key with audio file.");const a=Ao().getFileAccessType();e.append("accessType",a),e.append("preferredFilename",r.name);const{data:o}=await n.upload.post("/api/v4/audios",e,{headers:{"content-type":"multipart/form-data"},onUploadProgress({loaded:e,total:n=100}){null==t||t(Math.round(100*e/n))}}),s=n.cache&&Date.now();return n.cache&&Xt({files:o},{cachedAt:s}),{data:o,cachedAt:s}}});const Bi=async e=>{const t=Re();t.log("role/queryRoles",e);const n=null!=e?e:{},{limit:r=10,queryToken:a,displayName:o,sortBy:s}=n,i=en(n,["limit","queryToken","displayName","sortBy"]),c=a?{token:a}:r?{limit:r}:void 0,{data:l}=await t.http.get("/api/v3/roles",{params:Object.assign(Object.assign({},i),{keyword:o,sortBy:s,options:c})}),{paging:d}=l,u=en(l,["paging"]),{roles:h}=u,p=t.cache&&Date.now();t.cache&&Xt(u,{cachedAt:p});const f=de(d.next);return{data:h,cachedAt:p,prevPage:de(d.previous),nextPage:f,paging:d}};Bi.locally=e=>{Re().log("role/queryRoles.locally",e)};const Li=async e=>{const t=Re();t.log("role/getRole",e);const{data:n}=await t.http.get(`/api/v3/roles/${e}`),r=t.cache&&Date.now();return t.cache&&Xt({roles:n},{cachedAt:r}),{data:n.find((t=>t.roleId===e)),cachedAt:r}};Li.locally=e=>{const t=Re();if(t.log("role/getRole.locally",e),!t.cache)return;const n=je(["role","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Fi=async(e,t=!1)=>{const n=Re();let r;n.log("message/getMessage",e),mn("message",e);try{const{data:t}=await n.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);r=await On(t)}catch(t){throw ae(null==t?void 0:t.code)&&Zt("message",e),t}const a=n.cache&&Date.now();n.cache&&Xt(r,{cachedAt:a});const{messages:o}=r;return ct("local.message.fetched",{messages:o}),{data:o.find((t=>t.messageId===e)),cachedAt:a}};Fi.locally=e=>{const t=Re();if(t.log("message/getMessage.locally",e),!t.cache)return;const n=je(["message","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Ki=async e=>{const t=Re();let n;t.log("post/getPost",e),mn("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw ae(null==t?void 0:t.code)&&Zt("post",e),t}const r=nn(n,"communityUsers"),a=t.cache&&Date.now();t.cache&&Xt(r,{cachedAt:a});const{posts:o}=r;return{data:o.find((t=>t.postId===e)),cachedAt:a}};Ki.locally=e=>{const t=Re();if(t.log("post/getPost.locally",e),!t.cache)return;const n=je(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const $i=async e=>{const t=Re();let n;t.log("comment/getComment",e),mn("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw ae(null==t?void 0:t.code)&&Zt("comment",e),t}const r=t.cache&&Date.now();t.cache&&Xt(n,{cachedAt:r});const{comments:a}=n;return{data:hi.comment(a.find((t=>t.commentId===e))),cachedAt:r}};$i.locally=e=>{const t=Re();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=je(["comment","get",e]);return n?{data:hi.comment(n.data),cachedAt:n.cachedAt}:void 0};const Qi=(e,t)=>{var n,r;let a,o;if("post"===t)o="post",a=e.posts[0].postId;else if("comment"===t)o="comment",a=e.comments[0].commentId;else{if("story"!==t)throw new Error("Unknown event type");o="story",a=e.stories[0].referenceId}return(null===(r=null===(n=je([o,"get",a]))||void 0===n?void 0:n.data)||void 0===r?void 0:r.myReactions)||[]},zi=(e,t,n)=>{const[r]=e[t];return Object.assign(Object.assign({},e),{[t]:[Object.assign(Object.assign({},r),{myReactions:n})]})},Vi=(e,t,n,r=[])=>{const a=e.split(".")[1];let o=r;if(Re().userId===t)if(["addReaction","reactionAdded"].includes(a))o.includes(n)||o.push(n);else{if(!["removeReaction","reactionRemoved"].includes(a))throw new Error(`Unknown event type: ${a}`);o=o.filter((e=>e!==n))}return o},Hi=(e,t)=>{const n=e.split(".")[0],r=Qi(t,n),a=Vi(e,t.reactor.userId,t.reactor.reactionName,r);return zi(t,`${n}s`,a)},Ji=(e,t)=>{var n,r;const a=e.split(".")[0];let o=Qi(t,a);(null==t?void 0:t.reactions)&&t.reactions.length>0&&(o=Vi(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 s=zi(t,"stories",o);if(!(null==t?void 0:t.communities)||!(null==t?void 0:t.communityUsers))return s;const i=Ns(t.communities,t.communityUsers);return Object.assign(Object.assign({},s),{communities:i})},Wi=async(e,t,n)=>{var r,a,o;const s=Re();if(s.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new ke("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:i}=await s.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0});if(s.cache){const c=je([e,"get",t]);if(!c||(null===(r=c.data.myReactions)||void 0===r?void 0:r.includes(n)))return!0;const l=Object.assign(Object.assign({},c.data),{reactionsCount:c.data.reactionsCount+1,myReactions:[...null!==(a=c.data.myReactions)&&void 0!==a?a:[],n],reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:(null!==(o=c.data.reactions[n])&&void 0!==o?o:0)+1}),updatedAt:(new Date).toISOString()});if("comment"===e)return ct("local.comment.addReaction",{comment:l,reactor:{userId:s.userId,reactionName:n,reactionId:i.addedId}}),!0;if("post"===e)return ct("local.post.addReaction",{post:l,reactor:{userId:s.userId,reactionName:n,reactionId:i.addedId}}),!0;if("story"===e)return ct("local.story.reactionAdded",{story:l,reactor:{userId:s.userId,reactionName:n,reactionId:i.addedId}}),!0}return!0};Wi.optimistically=(e,t,n)=>{var r,a,o,s,i;const c=Re();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const l=je([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!==(a=l.data.myReactions)&&void 0!==a?a:[],n],reactions:Object.assign(Object.assign({},l.data.reactions),{[n]:(null!==(o=l.data.reactions[n])&&void 0!==o?o:0)+1})});return De([e,"get",t],d,{cachedAt:G}),Us(e,d),null!==(i=null===(s=null==d?void 0:d.myReactions)||void 0===s?void 0:s.includes(n))&&void 0!==i&&i};const Gi=async(e,t,n)=>{var r,a;const o=Re();if(o.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new ke("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:s}=await o.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0}});if(o.cache){const i=je([e,"get",t]);if(!i)return!0;const c=Object.assign(Object.assign({},i.data),{reactionsCount:Math.max(0,i.data.reactionsCount-1),myReactions:(null!==(r=i.data.myReactions)&&void 0!==r?r:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},i.data.reactions),{[n]:Math.max(0,(null!==(a=i.data.reactions[n])&&void 0!==a?a:0)-1)}),updatedAt:(new Date).toISOString()});if("comment"===e)return ct("local.comment.removeReaction",{comment:c,reactor:{reactionId:s.removedId,reactionName:n,userId:o.userId}}),!0;if("post"===e)return ct("local.post.removeReaction",{post:c,reactor:{reactionId:s.removedId,reactionName:n,userId:o.userId}}),!0;if("story"===e)return ct("local.story.reactionAdded",{story:c,reactor:{userId:o.userId,reactionName:n,reactionId:s.removedId}}),!0}return!0};Gi.optimistically=(e,t,n)=>{var r,a,o,s;const i=Re();if(i.log("reaction/removeReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!i.cache)return;const c=je([e,"get",t]);if(!(null==c?void 0:c.data)||!(null===(r=c.data.myReactions)||void 0===r?void 0:r.includes(n)))return;const l=Object.assign(Object.assign({},c.data),{reactionsCount:Math.max(0,c.data.reactionsCount-1),myReactions:(null!==(a=c.data.myReactions)&&void 0!==a?a:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:Math.max(0,(null!==(o=c.data.reactions[n])&&void 0!==o?o:0)-1)})});return De([e,"get",t],l,{cachedAt:G}),Us(e,l),!(null===(s=null==l?void 0:l.myReactions)||void 0===s?void 0:s.includes(n))};const Yi=e=>{const{posts:t,postChildren:n,videoStreamings:r}=e,a=en(e,["posts","postChildren","videoStreamings"]),o=Ls({communities:a.communities}),s=a.communityUsers.map((e=>{const t=a.users.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),i=Ns(o,s);let c=[];const l=t.map((t=>{var n,o;const s=null===(n=a.feeds.find((e=>e.feedId===t.feedId)))||void 0===n?void 0:n.feedType,i=e.postChildren.filter((e=>e.parentPostId===t.postId));var l,d,u;return i.length>0&&Ms(i[0])&&(l=r,d=null===(o=i[0].data)||void 0===o?void 0:o.streamId,u=t.postId,c=d?l.map((e=>e.streamId===d?Object.assign(Object.assign({},e),{referenceType:"post",referenceId:u,postId:u}):e)):l),Object.assign(Object.assign({},t),{childPosts:i,feedType:s})}));return Object.assign(Object.assign({},a),{postChildren:n,videoStreamings:c,posts:l,communities:i,communityUsers:s})},Xi=e=>{var{searchResult:t,polls:n}=e,r=en(e,["searchResult","polls"]);const a=Yi(r);return Object.assign(Object.assign({},a),{polls:n})},Zi=e=>{var t;const n=e.posts[0];if(n.parentId){const e=null===(t=je(["post","get",n.parentPostId]))||void 0===t?void 0:t.data;if(!e)return;Ue(["post","get",e.postId],Object.assign(Object.assign({},e),{children:e.children.filter((e=>e!==n.postId))}))}else n.children.forEach((e=>xe(["post","get",e],{isDeleted:!0})))},ec=(e,t)=>{const n=Re();return it(n,e,e,(r=>{var a;if(n.cache){const o=Yi(r),{communities:s}=o;if(Xt(o,void 0,!1),(null==s?void 0:s[0])&&!["post.updated"].includes(e)&&ct("community.updated",{communities:s,categories:[],communityUsers:o.communityUsers,feeds:[],files:[],users:[]}),"post.deleted"===e){const{postId:e,postedUserId:a}=r.posts[0];Zi(r);try{mn("post",e)}catch(e){return}return a!==n.userId&&qe(["post","get",e]),t(r.posts[0])}const i=je(["post","get",r.posts[0].postId]);if(["post.created","post.approved","post.declined"].includes(e)){let t=null===(a=Me(["post","query"]))||void 0===a?void 0:a.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})=>De(e,t,{cachedAt:-1})))}"post.created"===e&&(e=>{var t;const n=e.posts[0];if(!n.parentId)return;const r=null===(t=je(["post","get",n.parentPostId]))||void 0===t?void 0:t.data;r&&Ue(["post","get",r.postId],Object.assign(Object.assign({},r),{children:[...new Set([n.postId,...r.children])]}))})(r),t(i.data)}else t(r.posts[0])}))},tc=(e,t)=>{const n=Re();return it(n,e,e,(r=>{if(n.cache){const n=Yi(r),{communities:a}=n;Xt(n),(null==a?void 0:a[0])&&!["local.post.updated"].includes(e)&&ct("community.updated",{communities:a,categories:[],communityUsers:n.communityUsers,feeds:[],files:[],users:[]});const o=je(["post","get",r.posts[0].postId]);"local.post.deleted"===e&&Zi(r),t(o.data)}else t(r.posts[0])}))},nc=e=>ec("post.created",e),rc=e=>ec("post.updated",e),ac=e=>ec("post.deleted",e),oc=e=>ec("post.approved",e),sc=e=>ec("post.declined",e),ic=e=>ec("post.flagged",e),cc=e=>ec("post.unflagged",e),lc=e=>{const t=Re();return it(t,"post.addReaction","post.addReaction",(n=>{if(t.cache){const t=en(Hi("post.addReaction",n),["reactor"]);Xt(t);const r=je(["post","get",n.posts[0].postId]);e(r.data)}else e(n.posts[0])}))},dc=e=>{const t=Re();return it(t,"post.removeReaction","post.removeReaction",(n=>{if(t.cache){const t=en(Hi("post.removeReaction",n),["reactor"]);Xt(t);const r=je(["post","get",n.posts[0].postId]);e(r.data)}else e(n.posts[0])}))},uc=(e,t)=>{const n=Re();return it(n,e,e,(r=>{var a;if(n.cache){const o=["comment.flagged","comment.unflagged"].includes(e)?(e=>{const t=Qi(e,"comment");return zi(e,"comments",t)})(r):r;Xt(o,void 0,!1);const{comments:s}=o;if(s.length>0){const r=je(["comment","get",s[0].commentId]);if(["comment.created"].includes(e)){if("comment.created"===e&&r.data.userId===n.userId)return;if(s[0].parentId){const e=je(["comment","get",s[0].parentId]);(null==e?void 0:e.data)&&(e.data.children.includes(s[0].commentId)||Ue(["comment","get",s[0].parentId],Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,s[0].commentId])]})))}}if(["comment.deleted"].includes(e)){if("comment.deleted"===e&&r.data.userId===n.userId)return;if(s[0].parentId){const e=je(["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.filter((e=>e!==s[0].commentId))])]});Ue(["comment","get",s[0].parentId],t)}}const t=null===(a=Me(["comment","query"]))||void 0===a?void 0:a.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})=>De(e,t,{cachedAt:-1})))}t(hi.comment(r.data))}}else t(hi.comment(r.comments[0]))}))},hc=(e,t)=>{const n=Re();return it(n,e,e,(r=>{var a,o;if(n.cache){const n=r;Xt(n);const{comments:s}=n;if(s.length>0){const n=je(["comment","get",s[0].commentId]);if(["local.comment.created"].includes(e)){if(s[0].parentId){const e=je(["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])]});Ue(["comment","get",s[0].parentId],t),setTimeout((()=>{ct("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}const e=null===(a=Me(["comment","query"]))||void 0===a?void 0:a.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})=>De(e,t,{cachedAt:-1})))}if(["local.comment.deleted"].includes(e)){if(s[0].parentId){const e=je(["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.filter((e=>e!==s[0].commentId))])]});Ue(["comment","get",s[0].parentId],t),setTimeout((()=>{ct("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}const e=null===(o=Me(["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})=>De(e,t,{cachedAt:-1})))}t(hi.comment(n.data))}}else t(hi.comment(r.comments[0]))}))},pc=e=>uc("comment.created",e),fc=e=>uc("comment.updated",e),mc=e=>uc("comment.deleted",e),gc=e=>uc("comment.flagged",e),yc=e=>uc("comment.unflagged",e),vc=e=>{const t=Re();return it(t,"comment.addReaction","comment.addReaction",(n=>{if(t.cache){const t=en(Hi("comment.addReaction",n),["reactor"]);Xt(t);const r=je(["comment","get",n.comments[0].commentId]);e(hi.comment(r.data))}else e(hi.comment(n.comments[0]))}))},bc=e=>{const t=Re();return it(t,"comment.removeReaction","comment.removeReaction",(n=>{if(t.cache){const t=en(Hi("comment.removeReaction",n),["reactor"]);Xt(t);const r=je(["comment","get",n.comments[0].commentId]);e(hi.comment(r.data))}else e(hi.comment(n.comments[0]))}))},wc=(e,t,n)=>{const r=Re(),a=(r,a,o)=>{r===e&&a===t&&n(o)};if("message"===e){return it(r,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await On(e);t.reactions[0]&&(Xt(t),Xt({reactors:t.reactions}),a("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return it(r,"post.addReaction","post.addReaction",(e=>{const{reactor:t}=e,n=en(e,["reactor"]);Xt(n),Xt({reactions:[t]}),a("post",e.posts[0].postId,t)}))}if("story"===e){return it(r,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=en(e,["reactions"]);Xt(n),Xt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&a("story",e.stories[0].storyId,e.reactions[0])}))}return it(r,"comment.addReaction","comment.addReaction",(e=>{const{reactor:t}=e,n=en(e,["reactor"]);Xt(n),Xt({reactions:[t]}),a("comment",e.comments[0].commentId,t)}))},Cc=(e,t,n)=>{const r=Re(),a=(r,a,o)=>{r===e&&a===t&&n(o)};if("message"===e){return it(r,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await On(e);t.reactions[0]&&(Xt(t),a("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return it(r,"post.removeReaction","post.removeReaction",(e=>{const{reactor:t}=e,n=en(e,["reactor"]);Xt(n),Xt({reactions:[t]}),a("post",e.posts[0].postId,t)}))}if("story"===e){return it(r,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=en(e,["reactions"]);Xt(n),Xt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&a("story",e.stories[0].storyId,e.reactions[0])}))}return it(r,"comment.removeReaction","comment.removeReaction",(e=>{const{reactor:t}=e,n=en(e,["reactor"]);Xt(n),Xt({reactions:[t]}),a("comment",e.comments[0].commentId,t)}))};class Ic extends is{async getRequest(e,t){const{limit:n=V,referenceType:r}=e,a=en(e,["limit","referenceType"]),o=t?{token:t}:{limit:n};Re().log("reaction/queryReactions",e);if(!["post","comment","story","message"].includes(r))throw new ke("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:s}=await this.http.get("/api/v3/reactions",{params:Object.assign(Object.assign({},a),{referenceType:r,referenceVersion:"message"===r?5:void 0,options:o})});return s}}class Sc extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){var t;const n=await this.preparePayload(e),r=Re(),a=r.cache&&Date.now();if(r.cache){const{reactions:e}=n,r=en(n,["reactions"]);Xt(Object.assign(Object.assign({},r),{reactions:e,reactors:null===(t=e[0])||void 0===t?void 0:t.reactors}),{cachedAt:a})}}appendToQueryStream(e,t,n=!1){var r,a,o,s;const i=null!==(a=null===(r=e.reactions[0])||void 0===r?void 0:r.reactors)&&void 0!==a?a:[];if(n)Ue(this.cacheKey,{data:i.map(Ce("reactor"))});else{const e=null===(o=je(this.cacheKey))||void 0===o?void 0:o.data,t=null!==(s=null==e?void 0:e.data)&&void 0!==s?s:[];Ue(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...i.map(Ce("reactor"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=je(this.cacheKey))||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))),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class _c extends ps{constructor(e,t){const n=I.default(e),r=["reaction","collection",n];super(new Ic(e),n,r,t),this.query=e,this.queryStreamController=new Sc(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:e=>wc(this.query.referenceType,this.query.referenceId,e),action:"onAdded"},{fn:e=>Cc(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const r=Re(),a=(r,a,o)=>{r===e&&a===t&&n(o)};if("message"===e)return it(r,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await On(e);t.reactions[0]&&(Xt(t),a("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return it(r,"local.post.removeReaction","local.post.removeReaction",(e=>{a("post",e.post.postId,e.reactor)}));if("story"===e)return it(r,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=en(e,["reactions"]);Xt(n),Xt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&a("story",e.stories[0].storyId,e.reactions[0])}));return it(r,"local.comment.removeReaction","local.comment.removeReaction",(e=>{a("comment",e.comment.commentId,e.reactor)}))})(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const r=Re(),a=(r,a,o)=>{r===e&&a===t&&n(o)};if("message"===e)return it(r,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await On(e);t.reactions[0]&&(Xt(t),Xt({reactors:t.reactions}),a("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return it(r,"local.post.addReaction","local.post.addReaction",(e=>{a("post",e.post.postId,e.reactor)}));if("story"===e)return it(r,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=en(e,["reactions"]);Xt(n),Xt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&a("story",e.stories[0].storyId,e.reactions[0])}));return it(r,"local.comment.addReaction","local.comment.addReaction",(e=>{a("comment",e.comment.commentId,e.reactor)}))})(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=null!==(a=o.data.map((e=>je(["reactor","get",e]))).filter(Boolean).map((({data:e})=>hi.reactor(e))))&&void 0!==a?a:[];(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var kc=Object.freeze({__proto__:null,addReaction:Wi,removeReaction:Gi,onReactionAdded:(e,t,n)=>{const r=r=>{Ce(e)(r)===t&&n(r)};if("message"===e){const e=Re(),t=async e=>{var t;const n=await On(e),a=je(["message","get",n.messages[0].messageId]),o=(null===(t=null==a?void 0:a.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Xt(n),o&&r(n.messages[0])};return it(e,"reaction/onReactionAdded","message.updated",t)}return"post"===e?lc(r):vc(r)},onReactionRemoved:(e,t,n)=>{const r=r=>{Ce(e)(r)===t&&n(r)};if("message"===e){const e=Re(),t=async e=>{var t;const n=await On(e),a=je(["message","get",n.messages[0].messageId]),o=(null===(t=null==a?void 0:a.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Xt(n),o&&r(n.messages[0])};return it(e,"reaction/onReactionRemoved","message.updated",t)}return"post"===e?dc(r):bc(r)},onReactorAdded:wc,onReactorRemoved:Cc,getReactions:(e,t,n)=>{const{log:r,cache:a}=Re(),o=Date.now();r(`getReactions(tmpid: ${o}) > listen`);const s=new _c(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>{qe(c)})),()=>{r(`getReactions(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}}});function Oc(e){const{comments:t}=e;return Object.assign(Object.assign({},e),{comments:t.map((e=>e.hasOwnProperty("myReactions")?e:Object.assign({myReactions:[]},e)))})}const Tc=e=>{const t=Re(),n=[it(t,"onMessageUpdated","message.updated",(async t=>{const n=await On(t);Xt(n),e(n.messages[0])})),it(t,"onMessageUpdated","local.message.updated",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},Ec=e=>{const t=Re(),n=[it(t,"message/onMessageDeleted","message.deleted",(async t=>{const n=await On(t);Xt(n),e(n.messages[0])})),it(t,"message/onMessageDeleted","local.message.deleted",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},Ac=e=>{const t=Re(),n=[it(t,"onSubChannelUpdated","message-feed.updated",(async t=>{const n=await Mn(t);Xt(n),e(n.messageFeeds[0])})),it(t,"onSubChannelUpdated","local.message-feed.updated",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}};function Rc(e,t){Ue(["channel","get",e.channelId],pn(e,t))}const Pc=e=>{const t=Re();return it(t,"channelMarker/onChannelMarkerUpdated","local.channelMarker.updated",(t=>{e(t.userEntityMarkers[0])}))},Mc=async(e,t=!1)=>{const n=Re(),r=await jn(e);await n.http.delete(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{params:{permanent:t}});const a=Object.assign(Object.assign({},r.data),{isDeleted:!0,updatedAt:Se(r.data.updatedAt)});return t?setTimeout((()=>{Zt("subChannel",e)}),0):De(["subChannel","get",e],a),ct("local.message-feed.deleted",{messageFeeds:[a]}),a},jc=e=>it(Re(),"onSubChannelFetched","local.message-feed.fetched",(t=>e(t.messageFeeds[0]))),Uc=()=>`LOCAL_${zt()}`;let xc;const Dc=async(e,t)=>{const n=Re();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)}`,Tn(t)),a=await On(r),o=n.cache&&Date.now();n.cache&&Xt(a,{cachedAt:o});const{messages:s}=a;return ct("local.message.updated",{messages:s}),{data:hi.message(s.find((t=>t.messageId===e))),cachedAt:o}};Dc.optimistically=(e,t)=>{const n=Re();if(n.log("message/updateMessage.optimistically",t),!n.cache)return;const r=je(["message","get",e]);if(!r)return;const a=Object.assign(Object.assign(Object.assign({},r.data),t),{updatedAt:(new Date).toISOString()});return De(["message","get",e],a,{cachedAt:-1}),ct("local.message.updated",{messages:[a]}),{data:hi.message(a),cachedAt:-1}};const qc=async(e,t)=>{const n=Re();n.log("message/editMessage",t);const{data:r}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,Tn(t)),a=await On(r),o=n.cache&&Date.now();n.cache&&Xt(a,{cachedAt:o});const{messages:s}=a;return ct("local.message.updated",{messages:s}),{data:hi.message(s.find((t=>t.messageId===e))),cachedAt:o}};qc.optimistically=(e,t)=>{const n=Re();if(n.log("message/editMessage.optimistically",t),!n.cache)return;const r=je(["message","get",e]);if(!r)return;const a=Object.assign(Object.assign(Object.assign({},r.data),t),{updatedAt:(new Date).toISOString()});return De(["message","get",e],a,{cachedAt:-1}),ct("local.message.updated",{messages:[a]}),{data:hi.message(a),cachedAt:-1}};const Nc=async e=>{var t;const n=Re();if(n.log("message/deleteMessage",e),e.includes("LOCAL_")){const n=null===(t=je(["message","get",e]))||void 0===t?void 0:t.data;if(!n)throw Error("messageId not found");const r=Object.assign(Object.assign({},n),{isDeleted:!0});return ct("local.message.deleted",{messages:[r]}),hi.message(r)}const{data:r}=await n.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`),a=await On(r);return ct("local.message.deleted",{messages:[a.messages[0]]}),hi.message(a.messages[0])};Nc.optimistically=e=>{Re().log("message/deleteMessage.optimistically",e);const t=je(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return De(["message","get",e],n,{cachedAt:-1}),ct("local.message.deleted",{messages:[n]}),{data:hi.message(n),cachedAt:-1}};const Bc=async e=>{const t=Re();t.log("message/softDeleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const n=await Fi(e);return ct("local.message.deleted",{messages:[n.data]}),hi.message(n.data)};Bc.optimistically=e=>{Re().log("message/softDeleteMessage.optimistically",e);const t=je(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return De(["message","get",e],n,{cachedAt:-1}),ct("local.message.deleted",{messages:[n]}),{data:hi.message(n),cachedAt:-1}};const Lc=async e=>{const t=Re();t.log("user/getReadUsers",e);const{page:n,messageId:r}=e,a=en(e,["page","messageId"]),{data:o}=await t.http.get(`/api/v1/markers/messages/${r}/read-users`,{params:Object.assign(Object.assign({},a),{options:{token:le(n,"afterbeforeraw")}})}),{paging:s,publicUserIds:i,userFeedMarkers:c}=o,l=en(o,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Xt(Object.assign(Object.assign({},l),{userFeedMarkers:on(c)}),{cachedAt:d});const e=["read-user","query",Object.assign(Object.assign({messageId:r},a),{options:Object.assign({},n)})];Ue(e,{users:i,paging:s})}let u=[];i.length>0&&({data:u}=await pi(i));return{data:u,cachedAt:d,prevPage:de(s.previous),nextPage:de(s.next)}};Lc.locally=e=>{var t;const n=Re();if(n.log("user/getReadUsers.locally",e),!n.cache)return;const{page:r}=e,a=en(e,["page"]),o=["read-user","query",Object.assign(Object.assign({},a),{options:Object.assign({},r)})],{data:s,cachedAt:i}=null!==(t=je(o))&&void 0!==t?t:{},c=null==s?void 0:s.users.map((e=>{var t;return null===(t=je(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:i,prevPage:de(null==s?void 0:s.paging.previous),nextPage:de(null==s?void 0:s.paging.next)}};const Fc=async e=>{const t=Re();t.log("user/getDeliveredUsers",e);const{page:n,messageId:r}=e,a=en(e,["page","messageId"]),{data:o}=await t.http.get(`/api/v1/markers/messages/${r}/delivered-users`,{params:Object.assign(Object.assign({},a),{options:{token:le(n,"afterbeforeraw")}})}),{paging:s,publicUserIds:i,userFeedMarkers:c}=o,l=en(o,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Xt(Object.assign(Object.assign({},l),{userFeedMarkers:on(c)}),{cachedAt:d});const e=["delivered-user","query",Object.assign(Object.assign({messageId:r},a),{options:Object.assign({},n)})];Ue(e,{users:i,paging:s})}let u=[];i.length>0&&({data:u}=await pi(i));return{data:u,cachedAt:d,prevPage:de(s.previous),nextPage:de(s.next)}};Fc.locally=e=>{var t;const n=Re();if(n.log("user/getDeliveredUsers.locally",e),!n.cache)return;const{page:r}=e,a=en(e,["page"]),o=["delivered-user","query",Object.assign(Object.assign({},a),{options:Object.assign({},r)})],{data:s,cachedAt:i}=null!==(t=je(o))&&void 0!==t?t:{},c=null==s?void 0:s.users.map((e=>{var t;return null===(t=je(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:i,prevPage:de(null==s?void 0:s.paging.previous),nextPage:de(null==s?void 0:s.paging.next)}};const Kc=e=>{const t=Re();return it(t,"onMessageFlagged","message.flagged",(async t=>{const n=await On(t);Xt(n),e(n.messages[0])}))},$c=e=>{const t=Re();return it(t,"onMessageUnflagged","message.unflagged",(async t=>{const n=await On(t);Xt(n),e(n.messages[0])}))},Qc=e=>{const t=Re();return it(t,"onMessageFlagCleared","message.flagCleared",(async t=>{const n=await On(t);Xt(n),e(n.messages[0])}))},zc=e=>{const t=Re();return it(t,"onMessageReactionAdded","message.reactionAdded",(async t=>{const n=await On(t,"message.reactionAdded");Xt(n),e(n.messages[0])}))},Vc=e=>{const t=Re();return it(t,"onMessageReactionRemoved","message.reactionRemoved",(async t=>{const n=await On(t,"message.reactionRemoved");Xt(n),e(n.messages[0])}))},Hc=e=>{const t=Re();return it(t,"message/onMessageFetched","local.message.fetched",(t=>{Xt(t),e(t.messages[0])}))},Jc=e=>{const t=Re();return it(t,"stream/onStreamViewerDidBan","video-streaming.viewerDidBan",(t=>{var n;const{list:r}=t;r.forEach((e=>{var t;xe(["stream","get",e.streamId],{watcherUrl:null});const n=null===(t=Me(["message","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.creatorId===e.userId));null==n||n.forEach((e=>{xe(e.key,{isDeleted:!0})}))}));const a=null===(n=je(["stream","get",r[0].streamId]))||void 0===n?void 0:n.data;a&&e(a)}))};class Wc extends ls{constructor(e,t,n,r,a){super(e,t),this.notifyChange=n,this.preparePayload=r,this.paginationController=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.messages.map(Ce("message")),query:this.query});else{const n=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,o=null!==(a=null==n?void 0:n.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},n),{data:"next"===t?[...new Set([...o,...e.messages.map(Ce("message"))])]:[...new Set([...e.messages.map(Ce("message")),...o])]}))}}reactor(e){return t=>{var n,r,a,o;if("onCreate"===e){const e=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data,{referenceId:o}=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.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.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===(a=this.query.includingTags)||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!=o?o:t.messageId,...e.data])]),"segmentAsc"!==this.query.sortBy||this.paginationController.getNextToken()||(e.data=[...new Set([...e.data,null!=o?o:t.messageId])]),Ue(this.cacheKey,e)}if("onDelete"===e&&"error"===t.syncState){const e=null===(o=je(this.cacheKey))||void 0===o?void 0:o.data;if(!e)return;if(e.data.includes(t.messageId)){const n=e.data.filter((e=>e!==t.messageId));Ue(this.cacheKey,Object.assign(Object.assign({},e),{data:n}))}}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Gc extends is{async getRequest(e,t){const n=En(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 Yc extends ps{constructor(e,t){const n=I.default(e),r=["message","collection",n];super(new Gc(e),n,r,t),this.query=e,this.queryStreamController=new Wc(this.query,this.cacheKey,this.notifyChange.bind(this),On,this.paginationController),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:uo,action:"onCreate"},{fn:ho,action:"onCreate"},{fn:Ec,action:"onDelete"},{fn:Tc,action:"onUpdate"},{fn:Kc,action:"onFlagged"},{fn:$c,action:"onUnflagged"},{fn:Qc,action:"onFlagCleared"},{fn:zc,action:"onReactionAdded"},{fn:Vc,action:"onReactionRemoved"},{fn:Ti(Do,"contentId","message"),action:"onUpdate"},{fn:Ti(qo,"contentId","message"),action:"onUpdate"},{fn:Ti(Jc,"channelId","message"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>(e=>{var t,n;const r=null===(t=je(["message","get",e]))||void 0===t?void 0:t.data;if(r)return r;const a=Me(["message","get"]);return null===(n=null==a?void 0:a.find((({data:t})=>t.messageId===e)))||void 0===n?void 0:n.data})(e))).filter(Boolean).map((e=>hi.message(e))))&&void 0!==a?a:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),onPrevPage:()=>this.loadPage({direction:"prev"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),hasPrevPage:!!this.paginationController.getPrevToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.includeDeleted||(t=Ne(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=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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)}}var Xc=Object.freeze({__proto__:null,createMessage:async e=>{const t=Re();t.log("message/createMessage",e);const n=(e=>{var t,n;const r=Re();if(!r.cache)return;xc=e.referenceId||Uc();const a=Object.assign({messageId:xc,uniqueId:xc},e);r.log("message/createMessage.optimistically",a);const o=je(["subChannel","get",e.subChannelId]);if(o&&(De(["subChannel","get",e.subChannelId],Object.assign(Object.assign({},o.data),{messageCount:o.data.messageCount+1})),o.data.channelId===o.data.subChannelId)){const e=je(["channel","get",o.data.channelId]);(null==e?void 0:e.data)&&De(["channel","get",o.data.channelId],Object.assign(Object.assign({},e.data),{messageCount:(null!==(t=e.data.messageCount)&&void 0!==t?t:0)+1}))}const s=(new Date).toISOString(),i=Object.assign({creatorId:r.userId,creatorPrivateId:tt()._id,channelSegment:(null!==(n=null==o?void 0:o.data.messageCount)&&void 0!==n?n:0)+1,childrenNumber:0,createdAt:s,updatedAt:s,syncState:"syncing",isDeleted:!1},a);return Ue(["message","get",i.messageId],i,{cachedAt:-5}),ct("local.message.created",{messages:[i]}),i})(e),r=e.referenceId||xc||Uc();xc=void 0;try{const{data:n}=await t.http.post("/api/v5/messages",Object.assign(Object.assign({},Tn(e)),{referenceId:r})),a=await On(n),{messages:o}=a,s=t.cache&&Date.now();return t.cache&&Xt(a,{cachedAt:s}),ct("local.message.created",{messages:[Object.assign(Object.assign({},o[0]),{syncState:"synced"})]}),{data:hi.message(o[0]),cachedAt:s}}catch(e){throw ct("local.message.created",{messages:[Object.assign(Object.assign({},n),{syncState:"error"})]}),e}},updateMessage:Dc,editMessage:qc,deleteMessage:Nc,softDeleteMessage:Bc,markAsDelivered:async(e,t)=>{const n=Re();n.log("message/markAsDelivered",e,t);const{data:r}=await n.http.put(`/api/v1/markers/message-feeds/${e}/mark-delivering`,{messageId:t}),{userMarkers:a,userEntityMarkers:o,userFeedMarkers:s}=r,i=en(r,["userMarkers","userEntityMarkers","userFeedMarkers"]),c=n.cache&&Date.now();return n.cache&&Xt(Object.assign({userMarkers:a,userEntityMarkers:an(o),userFeedMarkers:on(s)},i),{cachedAt:c}),!0},getReadUsers:Lc,getDeliveredUsers:Fc,flagMessage:async(t,n)=>{const r=Re();r.log("message/flag",t);const a=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,r])=>t!==e.ContentFlagReasonEnum.Others&&r===n)),o={reason:a?n:e.ContentFlagReasonEnum.Others,detail:a?"":n},{data:s}=await r.http.post(`/api/v5/messages/${encodeURIComponent(t)}/flags`,o);if(r.cache){const e=await On(s);Xt(e)}return ct("message.flagged",s),!!s},unflagMessage:async e=>{const t=Re();t.log("message/unflag",e);const{data:n}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await On(n);Xt(e)}return ct("message.unflagged",n),!!n},isMessageFlaggedByMe:async e=>{const t=Re();t.log("message/isMessageFlaggedByMe",e);const{data:n}=await t.http.get(`/api/v5/messages/${encodeURIComponent(e)}/flags`);return n.result},onMessageCreatedMqtt:uo,onMessageCreatedLocal:ho,onMessageUpdated:Tc,onMessageDeleted:Ec,onMessageFlagged:Kc,onMessageUnflagged:$c,onMessageFlagCleared:Qc,onMessageReactionAdded:zc,onMessageReactionRemoved:Vc,onMessageFetched:Hc,getMessage:(e,t)=>Cs(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?hi.message(e.data):n}))}),"messageId",Fi,[Hc,Tc,Ec,Kc,$c,Qc,zc,Vc,Ti(Do,"contentId","message"),Ti(qo,"contentId","message"),Ti(Jc,"channelId","message")]),getMessages:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getMessages(tmpid: ${o}) > listen`);const s=new Yc(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>{qe(c)})),()=>{r(`getMessages(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},convertFromRaw:_n,prepareMessagePayload:On,convertParams:Tn,convertQueryParams:En});const Zc=e=>{const t=Re();return it(t,"subChannelMarker/onSubChannelUnreadUpdatedLocal","local.subChannelUnread.updated",(t=>{e(t)}))};class el extends is{async getRequest(e,t){var n;const{limit:r=V}=e,a=null!==(n=function(e){var{excludeDefaultSubChannel:t}=e,n=en(e,["excludeDefaultSubChannel"]);const r=Object.assign({},n);return void 0!==t&&(r.excludeDefaultMessageFeed=t),r}(en(e,["limit"])))&&void 0!==n?n:{},{channelId:o,includeDeleted:s}=a,i=en(a,["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:bn(s),options:c})});return l}}class tl extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.messageFeeds.map((({messageFeedId:e})=>e))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(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=je(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])]),Ue(this.cacheKey,r)}this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class nl extends ps{constructor(e,t){const n=I.default(e),r=["subChannel","collection",n];super(new el(e),n,r,t),this.query=e,this.queryStreamController=new tl(this.query,this.cacheKey,this.notifyChange.bind(this),Mn),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:jc,action:"onCreate"},{fn:po,action:"onCreate"},{fn:fo,action:"onDelete"},{fn:e=>Ac((async t=>{if(!this.isRelatedCollection(t.subChannelId))return;const n=Re();if("no-message-preview"!==await n.getMessagePreviewSetting(!1)){const e=dn(t.subChannelId);(null==e?void 0:e.subChannelId)===t.subChannelId&&Un(t.updatedAt)>Un(e.subChannelUpdatedAt)&&Ue(["messagePreviewSubChannel","get",t.subChannelId],Object.assign(Object.assign({},e),{subChannelName:t.displayName,subChannelUpdatedAt:t.updatedAt}))}e(t)})),action:"onUpdate"},{fn:Ti((e=>uo((async t=>{this.isRelatedCollection(t.subChannelId)&&(await Dn(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Ti((e=>ho((async t=>{this.isRelatedCollection(t.subChannelId)&&(await Dn(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:e=>Uo((t=>{var n;const r=null!==(n=t.map((({feedId:e})=>je(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];0!==r.length&&e(r)})),action:"onUpdate"},{fn:Ti(jo,"feedId","subChannel"),action:"onUpdate"},{fn:Ti((e=>Tc((async t=>{var n;const r=Re();if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;const a=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;a&&a.data.includes(t.subChannelId)&&(qn(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Ti((e=>Ec((async t=>{const n=Re(),r=await n.getMessagePreviewSetting(!1);"no-message-preview"!==r&&this.isRelatedCollection(t.subChannelId)&&("message-preview-not-include-deleted"===r?await jn(t.subChannelId):await qn(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Ti(Zc,"subChannelId","subChannel"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(un))&&void 0!==a?a:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.includeDeleted||(t=Ne(e,"isDeleted",!1)),t.sort(Ze),t}isRelatedCollection(e){var t;const n=null===(t=je(this.cacheKey))||void 0===t?void 0:t.data;return n&&n.data.includes(e)}}const rl={},al=async e=>{const t=await(async e=>{const t=jn.locally(e);if(t)return t.data.channelId;const{data:n}=await jn(e);return n.channelId})(e),n=gt({channelId:t,subChannelId:e});rl[e]=St(n)};var ol=Object.freeze({__proto__:null,getSubChannelByIds:ta,createSubChannel:async e=>{const t=Re();t.log("user/createSubChannel",e);const n=await t.http.post("/api/v5/message-feeds",{channelId:e.channelId,name:e.displayName}),r=await Mn(n.data),a=t.cache&&Date.now();return t.cache&&Xt(r,{cachedAt:a}),ct("message-feed.created",n.data),{data:r.messageFeeds[0],cachedAt:a}},updateSubChannel:async(e,t)=>{const n=Re();n.log("channel/updateSubChannel",e,t);const r=await n.http.put(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{name:t.displayName}),a=await Mn(r.data),o=n.cache&&Date.now();return n.cache&&Xt(a,{cachedAt:o}),ct("message-feed.updated",r.data),{data:a.messageFeeds[0],cachedAt:o}},deleteSubChannel:Mc,hardDeleteSubChannel:async e=>{Re().log("channel/hardDeleteSubChannel",e);return await Mc(e,!0)},softDeleteSubChannel:async e=>{Re().log("channel/softDeleteSubChannel",e);return await Mc(e,!1)},onSubChannelCreated:po,onSubChannelUpdated:Ac,onSubChannelDeleted:fo,getSubChannel:(e,t)=>{const n=Re();let r;return Cs(e,(e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:un(e.data)}),a=en(n,["origin"]);return er(r,a)?void 0:(r=a,t(n))}),"subChannelId",jn,[jc,t=>Ac((async r=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(Ln(r),r.subChannelId===e&&t(r))})),fo,Ti(jo,"feedId","subChannel"),t=>Uo((n=>{var r;if(!n.find((({feedId:t})=>t===e)))return;const a=null===(r=je(["subChannel","get",e]))||void 0===r?void 0:r.data;a&&t(a)})),Ti((t=>uo((async n=>{n.subChannelId===e&&(await Dn(n),t(n))}))),"subChannelId","subChannel"),Ti((t=>ho((async n=>{n.subChannelId===e&&(await Dn(n),t(n))}))),"subChannelId","subChannel"),Ti((t=>Tc((async r=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&r.subChannelId===e&&(qn(r),t(r))}))),"subChannelId","subChannel"),Ti((t=>Ec((async r=>{const a=await n.getMessagePreviewSetting(!1);"no-message-preview"!==a&&r.subChannelId===e&&("message-preview-include-deleted"===a&&await qn(r),"message-preview-not-include-deleted"===a&&await jn(r.subChannelId),t(r))}))),"subChannelId","subChannel"),Ti(Zc,"subChannelId","subChannel")],{forceDispatch:!0})},getSubChannels:(e,t,n)=>{const{log:r,cache:a}=Re(),o=Date.now();r(`getSubChannels(tmpid: ${o}) > listen`),a||console.log(J);const s=new nl(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>{qe(c)})),()=>{r(`getSubChannels(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},markReadEngineOnLoginHandler:ea,startMessageReceiptSync:async e=>(await al(e),!0),stopMessageReceiptSync:e=>(rl[e]&&rl[e](),!0)});const sl=e=>{const t=Re();return it(t,"channelMarker/onChannelUnreadInfoUpdatedLocal","local.channelUnreadInfo.updated",(t=>{e(t)}))},il=e=>{const t=Re();return it(t,"channel/onChannelUnreadUpdatedLocal","local.channelUnread.updated",(t=>{e(t)}))};class cl extends is{async getRequest(e,t){const{limit:n=V,displayName:r,membership:a}=e,o=en(e,["limit","displayName","membership"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/channels",{params:Object.assign(Object.assign({},o),{keyword:r,filter:a,options:s})});return i}}class ll extends hs{async getRequest(e){const{data:t}=await this.http.get("/api/v3/channels/list",{params:Object.assign({},e)});return t}}class dl extends ls{constructor(e,t,n,r,a){super(e,t),this.notifyChange=n,this.preparePayload=r,this.paginationController=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.channels.map(Ce("channel"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channels.map(Ce("channel"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(this.paginationController instanceof ll)return this.notifyChange({origin:"event",loading:!1});["onCreate","onJoin","onResolveChannel"].includes(e)&&(Array.isArray(t)?r.data=[...new Set([...t.map(Ce("channel")),...r.data])]:r.data=[...new Set([t.channelInternalId,...r.data])]),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const ul=e=>{const t=Re();if(t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()){Ba().resolve(e.channelId,"userMessageFeedMarker")}},hl=e=>{const t=Re();return it(t,"onChannelResolved","local.channel.resolved",(async t=>{e(t)}))};class pl extends ps{constructor(e,t){const n=I.default(e),r=["channel","collection",n],a=pl.getPaginationController(e);super(a,n,r,t),this.query=e,this.queryStreamController=new dl(this.query,this.cacheKey,this.notifyChange.bind(this),(async e=>{try{const t=Re();t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await Hn(e)}catch(e){console.error("Error while preparing unread count info",e)}return zn(e)}),a),this.paginationController=a,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;let s=null!==(a=o.data.map((e=>je(["channel","get",e]))).filter(Boolean).map((({data:e})=>e)).map($r))&&void 0!==a?a:[];this.paginationController instanceof cl&&(s=this.applyFilter(s)),(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:this.paginationController instanceof cl?()=>this.loadPage({direction:"next"}):void 0,data:s,hasNextPage:this.paginationController instanceof cl&&!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Re();let n=e;switch(n=Ne(n,"isDeleted",this.query.isDeleted),n=Be(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=Fe(n,this.query.membership,t)),this.query.sortBy){case"firstCreated":n=n.sort(Je);break;case"lastCreated":n=n.sort(Ge);break;case"displayName":n=n.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Ve);break;default:n=n.sort(Ze)}return n}shouldAbort(e){var t,n;const r=null===(t=je(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 Re().getMessagePreviewSetting(!1)}static getPaginationController(e){return e.channelIds&&e.channelIds.length>0?new ll(e):new cl(e)}getSubscriptions(){const e=[{fn:Ti((e=>uo((t=>{var n,r;const a=Ba();(null===(n=je(["subChannelUnreadInfo","get",t.subChannelId]))||void 0===n?void 0:n.data)||a.resolve(t.subChannelId,"userMessageFeedMarker");const o=null===(r=je(["channel","get",t.channelId]))||void 0===r?void 0:r.data;o?(Rc(o,{lastActivity:t.createdAt}),e(t)):a.resolve(t.channelId,"channel")}))),"channelId","channel"),action:"onUpdate"},{fn:Ti((e=>ho((t=>{var n;const r=null===(n=je(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(Rc(r,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:ur,action:"onDelete"},{fn:sr,action:"onUpdate"},{fn:wr,action:"onMute"},{fn:e=>fr((t=>{ul(t),e(t)})),action:"onJoin"},{fn:e=>yr(((t,n)=>{var r,a;const{userId:o}=Re();if("member"===this.query.membership&&o===n.userId){const e=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;Ue(this.cacheKey,Object.assign(Object.assign({},e),{data:null!==(a=null==e?void 0:e.data.filter((e=>e!==t.channelId)))&&void 0!==a?a:[]}))}return e(t)})),action:"onLeft"},{fn:Sr,action:"onMemberAdded"},{fn:Or,action:"onMemberRemoved"},{fn:Ti(Mo,"entityId","channel"),action:"onUpdate"},{fn:Ti(Pc,"entityId","channel"),action:"onUpdate"},{fn:Ti((e=>uo((async t=>{var n;if("no-message-preview"===await pl.getMessagePreviewSetting())return;if(Nn(t),this.shouldAbort(t.channelId))return;const r=null===(n=je(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(Rc(r,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ti((e=>ho((async t=>{var n;if("no-message-preview"===await pl.getMessagePreviewSetting())return;if(Nn(t),this.shouldAbort(t.channelId))return;const r=null===(n=je(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(Rc(r,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ti((e=>Tc((async t=>{"no-message-preview"!==await pl.getMessagePreviewSetting()&&(Bn(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ti((e=>Ec((async t=>{const n=await pl.getMessagePreviewSetting();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await Bn(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&await Os(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:Ti((e=>fo((async t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;r.data.find((e=>{const n=sn(e);return(null==n?void 0:n.subChannelId)===t.subChannelId}))&&(await Os(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ti((e=>Ac((async t=>{var n;if("no-message-preview"===await pl.getMessagePreviewSetting())return;(null===(n=je(this.cacheKey))||void 0===n?void 0:n.data)&&(await Ln(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ti(po,"channelId","channel"),action:"onUpdate"},{fn:hl,action:"onResolveChannel"},{fn:e=>(e=>{const t=Re();return it(t,"userMessageFeedMarker/onUserMessageFeedMarkerResolved","local.userMessageFeedMarkers.resolved",(t=>{e(t)}))})((async t=>{if(t.feedMarkers){const n=t.feedMarkers.map((e=>{var t;return null===(t=je(["channel","get",e.entityId]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"OnResolveUnread"},{fn:Ti(sl,"channelId","channel"),action:"onUpdate"},{fn:Ti((e=>il((t=>{t.forEach(e)}))),"channelId","channel"),action:"onUpdate"}];return this.paginationController instanceof is?[...e,{fn:e=>rr((t=>{ul(t),e(t)})),action:"onCreate"}]:e}}const fl=()=>{var e;const t=Re();t.log("channel/getTotalChannelsUnread.locally");const n=(null===(e=Me(["channelUnread","get"]))||void 0===e?void 0:e.filter((({data:e})=>!e.isDeleted)))||[];return{data:(null==n?void 0:n.reduce(((e,{data:t})=>(e.unreadCount+=t.unreadCount,e.isMentioned=e.isMentioned||t.isMentioned,e)),{unreadCount:0,isMentioned:!1}))||{unreadCount:0,isMentioned:!1},cachedAt:t.cache&&Date.now()}};class ml extends is{async getRequest(e,t){const{limit:n=V,includeDeleted:r}=e,a=en(e,["limit","includeDeleted"]),o=t?{token:t}:{limit:n},s=!1!==r&&void 0,{data:i}=await this.http.get(`/api/v4/channels/${encodeURIComponent(a.channelId)}/users`,{params:Object.assign(Object.assign({},a),{options:o,isDeleted:s})});return i}}class gl extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.channelUsers.map((({channelId:e,userId:t})=>Ce("channelUsers")({channelId:e,userId:t})))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channelUsers.map((({channelId:e,userId:t})=>Ce("channelUsers")({channelId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;if(this.query.channelId!==t.channelId)return;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;const a=Ce("channelUsers")({channelId:this.query.channelId,userId:t.userId});"none"===t.membership?r.data=r.data.filter((e=>e!==a)):r.data.includes(a)||(r.data=[a,...r.data]),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class yl extends ps{constructor(e,t){const n=I.default(e),r=["channelUsers","collection",n];super(new ml(e),n,r,t),this.query=e,this.queryStreamController=new gl(this.query,this.cacheKey,this.notifyChange.bind(this),zn),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:fr,action:"onJoin"},{fn:yr,action:"onLeft"},{fn:Sr,action:"onMemberAdded"},{fn:Or,action:"onMemberRemoved"},{fn:Ar,action:"onChannelMemberBanned"},{fn:Mr,action:"onChannelMemberUnbanned"},{fn:xr,action:"onChannelMemberRoleAdded"},{fn:Nr,action:"onChannelMemberRoleRemoved"},{fn:Fr,action:"onChannelSetUserMuted"},{fn:(e=this.query.channelId,t=>{const n=Re();return it(n,"user.deleted","user.deleted",(n=>{var r,a;const o=fa(n);if(0===o.users.length)return;const s=o.users[0];Xt(o);const i=Ce("channelUsers")({channelId:e,userId:s.userId}),c=null===(r=je(["channelUsers","get",i]))||void 0===r?void 0:r.data;De(["channelUsers","get",i],Object.assign(Object.assign({},c),{user:s}));const l=null===(a=je(["channel","get",e]))||void 0===a?void 0:a.data;l&&t(l,c)}))}),action:"onChannelMemberChanged"}]);var e}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["channelUsers","get",e]))).filter(Boolean).map((({data:e})=>e)).map(hi.channelMember))&&void 0!==a?a:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=Le(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))}))),!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?Ge:Je),t}}const vl=(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getMembers(tmpid: ${o}) > listen`);const s=new yl(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>{qe(c)})),()=>{r(`getMembers(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}};var bl=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=Re();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=>ct("channel.membersAdded",Object.assign(Object.assign({},r),{channelUsers:r.channelUsers.filter((t=>t.userId===e))}))));const a=await zn(r);n.cache&&Xt(a);const{channelUsers:o}=a;return!!o.find((t=>t.channelId===e&&"member"===t.membership))},removeMembers:async(e,t)=>{const n=Re();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=>ct("channel.membersRemoved",Object.assign(Object.assign({},r),{channelUsers:r.channelUsers.filter((t=>t.userId===e))}))));const a=await zn(r);n.cache&&Xt(a);const{channelUsers:o}=a;return!!o.find((t=>t.channelId===e&&"member"!==t.membership))},applyFilter:(e,t)=>{let n=Le(e,"roles",t.roles);t.memberships&&(n=n.filter((e=>!(!t.memberships.includes("muted")||!e.isMuted)||t.memberships.includes(e.membership))));const r=t.sortBy?t.sortBy:"lastCreated";return n=n.sort("lastCreated"===r?Ge:Je),n},getMembers:vl,searchMembers:(e,t,n)=>vl(e,t)});var wl=Object.freeze({__proto__:null,addRole:async(e,t,n)=>{const r=Re();r.log("channel/addRole",e,t,n);const{data:a}=await r.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{channelId:e,role:t,userIds:n}),o=await zn(a);r.cache&&Xt(o),ct("local.channel-moderator.role-added",o);const{channelUsers:s}=o;return!!s.find((n=>n.channelId===e&&n.roles.includes(t)))},removeRole:async(e,t,n)=>{const r=Re();r.log("channel/removeRole",e,t,n);const{data:a}=await r.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{data:{channelId:e,role:t,userIds:n}}),o=await zn(a);r.cache&&Xt(o),ct("local.channel-moderator.role-removed",o);const{channelUsers:s}=o;return!!s.find((n=>n.channelId===e&&!n.roles.includes(t)))},banMembers:async(e,t)=>{const n=Re();n.log("channel/banMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v3/channels/${e}/users/ban`,{userIds:t}),a=await zn(r),{channelUsers:o}=a,s=n.cache&&Date.now();return n.cache&&Xt(a,{cachedAt:s}),{data:null==o?void 0:o.filter((e=>"banned"===e.membership)),cachedAt:s}},unbanMembers:async(e,t)=>{const n=Re();n.log("channel/unbanMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}/users/unban`,{userIds:t}),a=await zn(r),o=n.cache&&Date.now();n.cache&&Xt(a,{cachedAt:o});const{channelUsers:s}=a;return{data:null==s?void 0:s.filter((e=>"member"===e.membership)),cachedAt:o}},muteMembers:async(e,t,n=-1)=>{const r=Re();r.log("channel/muteMembers",{userIds:t,channelId:e,mutePeriod:n});const{data:a}=await r.http.put(`/api/v2/channel/${e}/users/mute`,{userIds:t,mutePeriod:-1===n?n:1e3*n}),{success:o}=a;return o},unmuteMembers:async(e,t)=>{const n=Re();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:a}=r;return a}}),Cl=Object.freeze({__proto__:null,Membership:bl,Moderation:wl,getChannelByIds:Qr,createChannel:ks,updateChannel:async(e,t)=>{const n=Re();n.log("channel/updateChannel",e,t);const{data:r}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}`,t),a=await zn(r),o=n.cache&&Date.now();n.cache&&Xt(a,{cachedAt:o});const{channels:s}=a;return{data:Yn(s.find((t=>t.channelId===e))),cachedAt:o}},deleteChannel:async e=>{const t=Re();t.log("channel/deleteChannel",e),await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}`);const n=await Os(e);return Yn(n.data)},joinChannel:async e=>{const t=Re();t.log("channel/joinChannel",e);const{data:n}=await t.http.post(`/api/v3/channels/${encodeURIComponent(e)}/join`),r=await zn(n);t.cache&&Xt(r);const{channelUsers:a}=r;return!!a.find((t=>t.channelId===e&&"member"===t.membership))},leaveChannel:async e=>{const t=Re();t.log("channel/leaveChannel",e);const{data:n}=await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/leave`),r=await zn(n);t.cache&&Xt(r);const{channelUsers:a}=r;return!!a.find((t=>t.channelId===e&&"member"!==t.membership))},muteChannel:async(e,t=-1)=>{const n=Re();if(n.log("channel/muteChannel",e),-1!==t&&t<0)throw new _e("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:a}=r;return a},unmuteChannel:async e=>{const t=Re();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},onChannelCreated:rr,onChannelUpdated:sr,onChannelDeleted:ur,onChannelJoined:fr,onChannelLeft:yr,onChannelSetMuted:wr,onChannelMemberAdded:Sr,onChannelMemberRemoved:Or,onChannelMemberBanned:Ar,onChannelMemberUnbanned:Mr,onChannelMemberRoleAdded:xr,onChannelMemberRoleRemoved:Nr,getChannel:(e,t)=>{const n=Re();let r;return Cs(e,(async e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:$r(e.data)}),a=en(n,["origin"]);return er(r,a)?void 0:(r=a,t(n))}),"channelId",Os,[sr,ur,fr,yr,Sr,Or,Ar,Mr,wr,Ti(Mo,"entityId","channel"),Ti(Pc,"entityId","channel"),Ti((t=>uo((async r=>{await(async r=>{var a;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Nn(r),r.channelId!==e)return;const o=null===(a=je(["channel","get",e]))||void 0===a?void 0:a.data;o&&(Rc(o,{messagePreviewId:r.messageId}),t(r))})(r),t(r)}))),"channelId","channel"),Ti((t=>ho((async r=>{var a;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Nn(r),r.channelId!==e)return;const o=null===(a=je(["channel","get",e]))||void 0===a?void 0:a.data;o&&(Rc(o,{messagePreviewId:r.messageId}),t(r))}))),"channelId","channel"),Ti((t=>Tc((async r=>{var a;const o=null===(a=je(["channel","get",e]))||void 0===a?void 0:a.data;if(!o||o.messagePreviewId!==r.messageId)return;"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(await Bn(r),t(r))}))),"channelId","channel"),Ti((t=>Ec((async r=>{var a;const o=null===(a=je(["channel","get",e]))||void 0===a?void 0:a.data;if(!o||o.messagePreviewId!==r.messageId)return;const s=await n.getMessagePreviewSetting(!1);"no-message-preview"!==s&&("message-preview-not-include-deleted"===s?(qe(["messagePreviewChannel","get",e]),await Os(r.channelId)):await Bn(r),t(r))}))),"channelId","channel"),Ti((e=>fo((async t=>{var r,a;const{channelId:o,subChannelId:s}=t,i=null===(r=je(["messagePreviewChannel","get",o]))||void 0===r?void 0:r.data;if(!i||i.subChannelId!==s)return;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;await Os(o);(null===(a=je(["channel","get",o]))||void 0===a?void 0:a.data)&&e(t)}))),"channelId","channel"),Ti((t=>Ac((async r=>{var a,o;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;Ln(r);const s=null===(a=je(["messagePreviewChannel","get",e]))||void 0===a?void 0:a.data;if(!s||s.subChannelId!==r.subChannelId)return;(null===(o=je(["channel","get",e]))||void 0===o?void 0:o.data)&&t(r)}))),"channelId","channel"),Ti(po,"channelId","channel"),Ti(sl,"channelId","channel"),Ti((e=>il((t=>{t.forEach(e)}))),"channelId","channel")],{forceDispatch:!0})},getChannels:(e,t,n)=>{const{log:r,cache:a,userId:o}=Re();a||console.log(J);const s=Date.now();r(`getChannels(tmpid: ${s}) > listen`);const i=new pl(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{qe(l)})),()=>{r(`getChannels(tmpid: ${s}) > dispose`),c.forEach((e=>e()))}},getTotalChannelsUnread:e=>{const{_id:t}=tt();if(!t)throw new _e("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:r}=Re();r||console.log("For using Live Object feature you need to enable Cache!");n(`liveTotalChannelsUnread(tmpid: ${Date.now()}) > listen`);const a=[];let o,s=!1;const i=t=>{const{data:n}=t,r=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;o=r?Bo(r):r,e({data:r?Object.assign(Object.assign({},r),{isMentioned:r.isMentioned}):r,loading:t.loading,error:t.error})};return a.push(il((e=>{const{data:t}=fl();er(o,t)||i({loading:!1,data:t})}))),(()=>{const e=ge((async()=>fl()));ve(e,(({error:e,data:t,loading:n,origin:r,cachedAt:o})=>{o===G?(i({data:t,origin:r,loading:!1,error:new ke(W,800800,"error")}),s=!0,a.forEach((e=>e()))):s||i({loading:n,data:t,origin:r,error:e}),e&&a.forEach((e=>e()))}))})(),()=>{a.forEach((e=>e()))}},MARKER_INCLUDED_CHANNEL_TYPE:Fn,isUnreadCountSupport:Kn,convertFromRaw:$n,preUpdateChannelCache:Qn,prepareChannelPayload:zn});const Il=(e,t)=>{0!==e.length&&0!==t.length&&e.forEach((({communityId:e})=>{const n=t.filter((({communityId:t})=>e===t));Ue(["communityUsers","collection",e],n)}))},Sl=async(e,t)=>{const n=Re();n.log("community/getCommunities",e);const r=e.map((e=>encodeURIComponent(e))),{data:a}=await n.http.get("/api/v3/communities/list",{params:{communityIds:r,includeDiscoverablePrivateCommunity:null==t||t}}),o=Fs(a),s=n.cache&&Date.now();return n.cache&&(Xt(o,{cachedAt:s}),Il(o.communities,o.communityUsers)),{data:o.communities.map((e=>hi.community(e))),cachedAt:s}};Sl.locally=e=>{var t;const n=Re();if(n.log("community/getCommunities.locally",e),!n.cache)return;const r=e.map((e=>je(["community","get",e]))).filter(Boolean),a=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:a,cachedAt:o.cachedAt}};const _l=async e=>{const t=Re();t.log("community/getCommunity",e);const{data:n}=await t.http.get(`/api/v3/communities/${e}`),r=Fs(n),a=t.cache&&Date.now();t.cache&&(Xt(r,{cachedAt:a}),Il(r.communities,r.communityUsers));const{communities:o}=r;return{data:o.find((t=>t.communityId===e)),cachedAt:a}};_l.locally=e=>{const t=Re();if(t.log("community/getCommunity.locally",e),!t.cache)return;const n=je(["community","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const kl=(e,t)=>{const n=Re();return it(n,e,e,(e=>{const r=Fs(e);if(n.cache){Xt(r);const e=je(["community","get",r.communities[0].communityId]);t(e.data)}else t(r.communities[0])}))},Ol=e=>kl("community.created",e),Tl=e=>kl("community.updated",e),El=e=>kl("community.deleted",e);class Al extends is{async getRequest(e,t){var n;const{limit:r=V}=e,a=en(e,["limit"]),o=t?{token:t}:{limit:r},{data:s}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},a),{isDeleted:bn(a.includeDeleted),keyword:a.displayName,filter:a.membership,includeDiscoverablePrivateCommunity:null===(n=a.includeDiscoverablePrivateCommunity)||void 0===n||n,options:o})});return s}}class Rl extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.communities.map(Ce("community"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Ce("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=je(this.cacheKey))||void 0===t?void 0:t.data;n&&(Ue(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Pl,Ml;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Pl||(Pl={})),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",e.OnLocalCommunityJoin="OnLocalCommunityJoin"}(Ml||(Ml={}));class jl extends is{async getRequest(e,t){const{limit:n=V,includeDeleted:r}=e,a=en(e,["limit","includeDeleted"]),o=t?{token:t}:{limit:n},s=!1!==r&&void 0,{data:i}=await this.http.get(`/api/v3/communities/${a.communityId}/users`,{params:Object.assign(Object.assign({},a),{options:o,isDeleted:s})});return i}}class Ul extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>Ce("communityUsers")({communityId:e,userId:t})))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>Ce("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;r&&(t.forEach((e=>{const t=Ce("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership?r.data=r.data.filter((e=>e!==t)):r.data.includes(t)||(r.data=[t,...r.data])})),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}function xl(e,t,n){return!!e.permissions.some((e=>e===n))||t.communityUsers.find((t=>t.userId===e.userId)).permissions.some((e=>e===n))}function Dl(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=>!xl(e,t,"BAN_COMMUNITY_USER"))):t.communityUsers.filter((e=>!xl(e,t,"ADD_COMMUNITY_USER")))}const ql=(e,t)=>{const n=Re();return it(n,e,e,(r=>{const a=Fs(r),{communities:o,communityUsers:s}=a,i=Ns(o,s);if(a.communities=i,n.cache){Xt(a,void 0,!1);const n=je(["community","get",a.communities[0].communityId]),r=Dl(e,a).map((e=>{const t=je(["communityUsers","get",Ce("communityUsers")(e)]);return null==t?void 0:t.data})).filter(fs);t(n.data,r)}else t(a.communities[0],Dl(e,a))}))},Nl=(e,t)=>{const n=Re();return it(n,e,e,(r=>{const a=Fs(r),{communities:o,communityUsers:s}=a,i=Ns(o,s);if(a.communities=i,n.cache){Xt(a,void 0,!1);const n=je(["community","get",a.communities[0].communityId]),r=Dl(e,a).map((e=>{const t=je(["communityUsers","get",Ce("communityUsers")(e)]);return null==t?void 0:t.data})).filter(fs);t(n.data,r)}else t(a.communities[0],Dl(e,a))}))},Bl=e=>ql("community.userBanned",e),Ll=e=>ql("community.userChanged",e),Fl=e=>ql("community.userUnbanned",e),Kl=e=>ql("community.roleAdded",e),$l=e=>ql("community.roleRemoved",e),Ql=e=>Nl("local.community.userAdded",e),zl=e=>Nl("local.community.userRemoved",e),Vl=e=>ql("community.joined",e),Hl=e=>ql("community.left",e),Jl=e=>Nl("local.community.joined",e),Wl=e=>Nl("local.community.left",e),Gl=e=>{const t=Re(),n=[it(t,"onCommunityUpdate","v4.local.community.joined",(async t=>{e(t[0])}))];return()=>{n.forEach((e=>e()))}},Yl=e=>{const t=Re();return it(t,"onLocalCommunityRoleRemoved","local.community.roleRemoved",(async t=>{const{communities:n,communityUsers:r}=t;e(n[0],r.filter((e=>"member"===e.communityMembership)))}))},Xl=e=>{const t=Re();return it(t,"onLocalCommunityRoleAdded","local.community.roleAdded",(async t=>{const{communities:n,communityUsers:r}=t;e(n[0],r.filter((e=>"member"===e.communityMembership)))}))},Zl=e=>t=>{const n=Re();return it(n,"user.deleted","user.deleted",(n=>{var r,a;const o=fa(n);if(0===o.users.length)return;const s=o.users[0];Xt(o);const i=Ce("communityUsers")({communityId:e,userId:s.userId}),c=null===(r=je(["communityUsers","get",i]))||void 0===r?void 0:r.data;Ue(["communityUsers","get",i],Object.assign(Object.assign({},c),{user:s}));const l=null===(a=je(["community","get",e]))||void 0===a?void 0:a.data;t(l,[Object.assign(Object.assign({},c),{user:s})])}))};class ed extends ps{constructor(e,t){const n=I.default(e),r=["communityUsers","collection",n];super(new jl(e),n,r,t),this.query=e,this.queryStreamController=new Ul(this.query,this.cacheKey,this.notifyChange.bind(this),Fs),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:Vl,action:Ml.OnCommunityJoined},{fn:Jl,action:Ml.OnCommunityJoined},{fn:Hl,action:Ml.OnCommunityLeft},{fn:Wl,action:Ml.OnCommunityLeft},{fn:Bl,action:Ml.OnCommunityUserBanned},{fn:Ll,action:Ml.OnCommunityUserChanged},{fn:Kl,action:Ml.OnCommunityUserRoleAdded},{fn:$l,action:Ml.OnCommunityUserRoleRemoved},{fn:Xl,action:Ml.OnCommunityUserRoleAdded},{fn:Yl,action:Ml.OnCommunityUserRoleRemoved},{fn:Fl,action:Ml.OnCommunityUserUnbanned},{fn:Ql,action:Ml.OnCommunityUserAdded},{fn:zl,action:Ml.onCommunityUserRemoved},{fn:Zl(this.query.communityId),action:Ml.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["communityUsers","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=Le(e,"roles",this.query.roles);if(this.query.memberships&&(t=t.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),!1===this.query.includeDeleted&&(t=t.filter((({user:e})=>!0!==(null==e?void 0:e.isDeleted)))),"firstCreated"===this.query.sortBy)t=t.sort(Je);else t=t.sort(Ge);return t}}class td extends is{async getRequest(e,t){const{limit:n=V,includeDeleted:r}=e,a=en(e,["limit","includeDeleted"]),o=t?{token:t}:{limit:n},s=!1!==r&&void 0,{data:i}=await this.http.get(`/api/v3/communities/${a.communityId}/users`,{params:Object.assign(Object.assign({},a),{options:o,isDeleted:s})});return i}}class nd extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>Ce("communityUsers")({communityId:e,userId:t})))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>Ce("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;r&&(t.forEach((e=>{const t=Ce("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership&&(r.data=r.data.filter((e=>e!==t)))})),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var rd;!function(e){e.OnCommunityJoined="onCommunityJoined",e.OnLocalCommunityJoin="onLocalCommunityJoin",e.OnCommunityLeft="onCommunityLeft",e.OnCommunityUserBanned="onCommunityUserBanned",e.OnCommunityUserChanged="onCommunityUserChanged",e.OnCommunityUserRoleAdded="onCommunityUserRoleAdded",e.OnCommunityUserRoleRemoved="onCommunityUserRoleRemoved",e.OnCommunityUserUnbanned="onCommunityUserUnbanned"}(rd||(rd={}));class ad extends ps{constructor(e,t){const n=I.default(e),r=["communityUsers","collection",n];super(new td(e),n,r,t),this.query=e,this.queryStreamController=new nd(this.query,this.cacheKey,this.notifyChange.bind(this),Fs),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:Vl,action:rd.OnCommunityJoined},{fn:Jl,action:rd.OnCommunityJoined},{fn:Hl,action:rd.OnCommunityLeft},{fn:Wl,action:rd.OnCommunityLeft},{fn:Bl,action:rd.OnCommunityUserBanned},{fn:Ll,action:rd.OnCommunityUserChanged},{fn:Yl,action:rd.OnCommunityUserRoleRemoved},{fn:$l,action:rd.OnCommunityUserRoleRemoved},{fn:Fl,action:rd.OnCommunityUserUnbanned},{fn:Zl(this.query.communityId),action:rd.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["communityUsers","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=Le(e,"roles",this.query.roles);return this.query.memberships&&(t=t.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),this.query.search&&(t=ze(t,this.query.search)),!1===this.query.includeDeleted&&(t=t.filter((({user:e})=>!0!==(null==e?void 0:e.isDeleted)))),t}}var od=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=Re();n.log("community/moderation/addMembers",e,t);const{data:r}=await n.http.post(`/api/v3/communities/${e}/users`,{communityId:e,userIds:t});ct("local.community.userAdded",r);const a=nn(r,"communityUsers");n.cache&&Xt(a);const{communityUsers:o}=a;return!!o.find((t=>t.communityId===e&&"member"===t.communityMembership))},removeMembers:async(e,t)=>{const n=Re();n.log("community/moderation/removeMembers",e,t);const{data:r}=await n.http.delete(`/api/v3/communities/${e}/users`,{data:{communityId:e,userIds:t}});ct("local.community.userRemoved",r);const a=nn(r,"communityUsers");n.cache&&Xt(a);const{communityUsers:o}=a;return!!o.find((t=>t.communityId===e&&"member"!==t.communityMembership))},applyFilter:(e,t)=>{let n=Le(e,"roles",t.roles);t.memberships&&(n=n.filter((({communityMembership:e})=>t.memberships.includes(e))));const r=t.sortBy?t.sortBy:"lastCreated";return n=n.sort("lastCreated"===r?Ge:Je),n},getMembers:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getMembers(tmpid: ${o}) > listen`);const s=new ed(e,(e=>{t(e)})),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>{qe(c)})),()=>{r(`getMembers(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},searchMembers:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getMembers(tmpid: ${o}) > listen`);const s=new ad(e,(e=>{t(e)})),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>{qe(c)})),()=>{r(`getMembers(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},onCommunityUserAdded:e=>ql("community.userAdded",e),onCommunityUserRemoved:e=>ql("community.userRemoved",e),onCommunityUserBanned:Bl,onCommunityUserChanged:Ll,onCommunityUserUnbanned:Fl,onCommunityUserRoleAdded:Kl,onCommunityUserRoleRemoved:$l,onLocalCommunityUserAdded:Ql,onLocalCommunityUserRemoved:zl,onCommunityJoined:Vl,onCommunityLeft:Hl,onLocalCommunityJoined:Jl,onLocalCommunityLeft:Wl,onLocalCommunityJoin:Gl});class sd extends ps{constructor(e,t){const n=I.default(e),r=["community","collection",n];super(new Al(e),n,r,t),this.query=e,this.queryStreamController=new Rl(this.query,this.cacheKey,this.notifyChange.bind(this),Fs),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:El,action:Pl.OnCommunityDeleted},{fn:Tl,action:Pl.OnCommunityUpdated},{fn:Vl,action:Ml.OnCommunityJoined},{fn:Hl,action:Ml.OnCommunityLeft},{fn:Ll,action:Ml.OnMemberCountChanged},{fn:Jl,action:Ml.OnCommunityJoined},{fn:Wl,action:Ml.OnCommunityLeft},{fn:Ti(Gl,"targetId","community"),action:Pl.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["community","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Re();let n=e;return this.query.includeDeleted||(n=Ne(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=$e(n,this.query.membership,t)),n}}class id extends is{async getRequest(e,t){var n;const{limit:r=V}=e,a=en(e,["limit"]),o=t?{token:t}:{limit:r},{data:s}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},a),{isDeleted:bn(a.includeDeleted),filter:a.membership,includeDiscoverablePrivateCommunity:null===(n=a.includeDiscoverablePrivateCommunity)||void 0===n||n,options:o})});return s}}class cd extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&(Xt(t,{cachedAt:r}),Il(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.communities.map(Ce("community"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Ce("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=je(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],Ue(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var ld;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(ld||(ld={}));class dd extends ps{constructor(e,t){const n=I.default(e),r=["community","collection",n];super(new id(e),n,r,t),this.query=e,this.queryStreamController=new cd(this.query,this.cacheKey,this.notifyChange.bind(this),Fs),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:Ol,action:ld.OnCommunityCreated},{fn:El,action:ld.OnCommunityDeleted},{fn:Tl,action:ld.OnCommunityUpdated},{fn:Vl,action:Ml.OnCommunityJoined},{fn:Hl,action:Ml.OnCommunityLeft},{fn:Ll,action:Ml.OnMemberCountChanged},{fn:Jl,action:Ml.OnCommunityJoined},{fn:Wl,action:Ml.OnCommunityLeft},{fn:Ti(Gl,"targetId","community"),action:ld.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=null!==(a=o.data.map((e=>je(["community","get",e]))).filter(fs).map((({data:e})=>ui(e))))&&void 0!==a?a:[];(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Re();let n=e;this.query.includeDeleted||(n=Ne(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=$e(n,this.query.membership,t));const r=(()=>"firstCreated"===this.query.sortBy?Je:Ge)();return n=n.sort(r),n}}class ud extends is{async getRequest(e,t){const{limit:n=V,includeDiscoverablePrivateCommunity:r}=e,a=en(e,["limit","includeDiscoverablePrivateCommunity"]),o=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v3/communities/top-trending",{params:Object.assign(Object.assign({},a),{options:o,includeDiscoverablePrivateCommunity:null==r||r})});return s}}class hd extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&(Xt(t,{cachedAt:r}),Il(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.communities.map(Ce("community"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Ce("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=je(this.cacheKey))||void 0===t?void 0:t.data;n&&(Ue(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var pd;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(pd||(pd={}));class fd extends ps{constructor(e,t){const n=I.default(e),r=["trendingCommunity","collection",n];super(new ud(e),n,r,t),this.query=e,this.queryStreamController=new hd(this.query,this.cacheKey,this.notifyChange.bind(this),Fs),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:El,action:pd.OnCommunityDeleted},{fn:Tl,action:pd.OnCommunityUpdated},{fn:Vl,action:Ml.OnCommunityJoined},{fn:Hl,action:Ml.OnCommunityLeft},{fn:Ll,action:Ml.OnMemberCountChanged},{fn:Jl,action:Ml.OnCommunityJoined},{fn:Wl,action:Ml.OnCommunityLeft},{fn:Ti(Gl,"targetId","community"),action:pd.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=null!==(a=o.data.map((e=>je(["community","get",e]))).filter(fs).map((({data:e})=>ui(e))))&&void 0!==a?a:[];(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class md extends is{async getRequest(e,t){const{limit:n=V,includeDiscoverablePrivateCommunity:r}=e,a=en(e,["limit","includeDiscoverablePrivateCommunity"]),o=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v3/communities/recommended",{params:Object.assign(Object.assign({},a),{options:o,includeDiscoverablePrivateCommunity:null==r||r})});return s}}class gd extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&(Xt(t,{cachedAt:r}),Il(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.communities.map(Ce("community"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Ce("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=je(this.cacheKey))||void 0===t?void 0:t.data;n&&(Ue(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var yd;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated",e.OnLocalCommunityJoin="onLocalCommunityJoin"}(yd||(yd={}));class vd extends ps{constructor(e,t){const n=I.default(e),r=["community","collection",n];super(new md(e),n,r,t),this.query=e,this.queryStreamController=new gd(this.query,this.cacheKey,this.notifyChange.bind(this),Fs),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:El,action:yd.OnCommunityDeleted},{fn:Tl,action:yd.OnCommunityUpdated},{fn:Vl,action:Ml.OnCommunityJoined},{fn:Hl,action:Ml.OnCommunityLeft},{fn:Ll,action:Ml.OnMemberCountChanged},{fn:Jl,action:Ml.OnCommunityJoined},{fn:Wl,action:Ml.OnCommunityLeft},{fn:Ti(Gl,"targetId","community"),action:yd.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=null!==(a=o.data.map((e=>je(["community","get",e]))).filter(fs).map((({data:e})=>ui(e))))&&void 0!==a?a:[];(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class bd extends is{async getRequest(e,t){var n;const{limit:r=V,communityMembershipStatus:a}=e,o=en(e,["limit","communityMembershipStatus"]),s={type:e.limit?"pagination":void 0},i=t?Object.assign(Object.assign({},s),{token:t}):Object.assign(Object.assign({},s),{limit:r}),{data:c}=await this.http.get("/api/v1/semantic-search/communities",{params:Object.assign(Object.assign({},o),{filter:null!=a?a:"all",options:i,includeDiscoverablePrivateCommunity:null===(n=o.includeDiscoverablePrivateCommunity)||void 0===n||n})});return c}}function wd(e){return e.communities.map((t=>{const n=e.searchResult.find((e=>e.communityId===t.communityId));return`${t.communityId}:${n}`}))}class Cd extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:wd(e)});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...wd(e)])]}))}}reactor(e){return e=>{var t;const n=null===(t=je(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],Ue(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Id;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Id||(Id={}));class Sd extends ps{constructor(e,t){const n=I.default(e),r=["community","collection",n];super(new bd(e),n,r,t),this.query=e,this.queryStreamController=new Cd(this.query,this.cacheKey,this.notifyChange.bind(this),zs),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:Ol,action:Id.OnCommunityCreated},{fn:El,action:Id.OnCommunityDeleted},{fn:Tl,action:Id.OnCommunityUpdated},{fn:Vl,action:Ml.OnCommunityJoined},{fn:Hl,action:Ml.OnCommunityLeft},{fn:Ll,action:Ml.OnMemberCountChanged},{fn:Jl,action:Ml.OnCommunityJoined},{fn:Wl,action:Ml.OnCommunityLeft},{fn:Ti(Gl,"targetId","community"),action:Id.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>{const[t,n]=e.split(":");return{communityId:t,score:parseFloat(n)}})).sort(((e,t)=>t.score-e.score)).map((({communityId:e})=>je(["community","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Re();let n=e;return this.query.categoryIds&&(n=n.filter((e=>{var t;return null===(t=e.categoryIds)||void 0===t?void 0:t.some((e=>!this.query.categoryIds||(0===this.query.categoryIds.length||this.query.categoryIds.includes(e))))}))),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.communityMembershipStatus&&t&&(n=$e(n,this.query.communityMembershipStatus,t)),n}}class _d extends is{async getRequest(e,t){const{limit:n=V,communityIds:r}=e,a=en(e,["limit","communityIds"]),o=t?{token:t}:{limit:n},s=r.map((e=>encodeURIComponent(e))),{data:i}=await this.http.get("/api/v4/communities/join/requests",{params:Object.assign(Object.assign({},a),{options:o,communityIds:s})});return i}}var kd;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(kd||(kd={}));class Od extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.joinRequests.map((e=>Ce("joinRequest")({joinRequestId:e._id})))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>Ce("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;const a=(Array.isArray(t)?t:[t]).map((e=>e.joinRequestId));if(e===kd.OnLocalJoinRequestUpdated){if(!r.data.find((e=>a.includes(e))))return}e===kd.OnLocalJoinRequestCreated&&(r.data=[...new Set([...a,...r.data])]),e===kd.OnLocalJoinRequestDeleted&&(r.data=r.data.filter((e=>!a.includes(e)))),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Td extends ps{constructor(e,t){const n=I.default(e),r=["joinRequestList","collection",n];super(new _d(e),n,r,t),this.query=e,this.queryStreamController=new Od(this.query,this.cacheKey,this.notifyChange.bind(this),Ks),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){const r=e;this.queryStreamController.appendToQueryStream(r,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Gs,action:kd.OnLocalJoinRequestCreated},{fn:Ys,action:kd.OnLocalJoinRequestUpdated},{fn:Xs,action:kd.OnLocalJoinRequestUpdated},{fn:Gl,action:kd.OnLocalJoinRequestUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r;const a=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const o=this.applyFilter(a.data.map((e=>je(["joinRequest","get",e]))).filter(fs).map((({data:e})=>e)).map(Vs));(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;this.query.communityIds&&this.query.communityIds.length>0&&(t=t.filter((e=>this.query.communityIds.some((t=>t===e.targetId)))));const n=(()=>"firstCreated"===this.query.sortBy?Je:Ge)();return t=t.sort(n),t}}var Ed;!function(e){e.ALL="all",e.MEMBER="member",e.NOT_MEMBER="notMember"}(Ed||(Ed={}));var Ad=Object.freeze({__proto__:null,addRoles:async(e,t,n)=>{const r=Re();r.log("community/moderation/addRoles",e,t,n);const{data:a}=await r.http.post(`/api/v4/communities/${e}/users/roles`,{communityId:e,roles:t,userIds:n}),o=$s(a);r.cache&&Xt(o),ct("local.community.roleAdded",o);const{communityUsers:s}=o;return!!s.find((n=>n.communityId===e&&t.some((e=>n.roles.includes(e)))))},removeRoles:async(e,t,n)=>{const r=Re();r.log("community/moderation/removeRoles",e,t,n);const{data:a}=await r.http.delete(`/api/v4/communities/${e}/users/roles`,{data:{communityId:e,roles:t,userIds:n}}),o=$s(a);r.cache&&Xt(o),ct("local.community.roleRemoved",o);const{communityUsers:s}=o;return!!s.find((n=>n.communityId===e&&!t.some((e=>n.roles.includes(e)))))},banMembers:async(e,t)=>{const n=Re();n.log("community/banMembers",{userIds:t,communityId:e});const{data:r}=await n.http.put(`/api/v3/communities/${e}/users/ban`,{userIds:t}),a=nn(r,"communityUsers"),o=n.cache&&Date.now();n.cache&&Xt(a,{cachedAt:o});const{communityUsers:s}=a;return{data:s.filter((e=>t.includes(e.userId))),cachedAt:o}},unbanMembers:async(e,t)=>{const n=Re();n.log("community/unbanMembers",{userIds:t,communityId:e});const{data:r}=await n.http.put(`/api/v3/communities/${e}/users/unban`,{userIds:t}),a=nn(r,"communityUsers"),o=n.cache&&Date.now();n.cache&&Xt(a,{cachedAt:o});const{communityUsers:s}=a;return{data:s.filter((e=>t.includes(e.userId))),cachedAt:o}}}),Rd=Object.freeze({__proto__:null,Moderation:Ad,Membership:od,getCommunityByIds:Sl,createCommunity:async e=>{const t=Re();t.log("user/createCommunity",e);const{data:n}=await t.http.post("/api/v3/communities/",Qs(e));ct("community.created",n);const r=Fs(n),a=t.cache&&Date.now();t.cache&&(Xt(r,{cachedAt:a}),Il(r.communities,r.communityUsers));const{communities:o}=r;return{data:hi.community(o[0]),cachedAt:a}},updateCommunity:async(e,t)=>{const n=Re();n.log("community/updateCommunity",e,t);const{data:r}=await n.http.put(`/api/v3/communities/${e}`,Qs(t));ct("community.updated",r);const a=Fs(r),o=n.cache&&Date.now();n.cache&&(Xt(a,{cachedAt:o}),Il(a.communities,a.communityUsers));const{communities:s}=a;return{data:hi.community(s.find((t=>t.communityId===e))),cachedAt:o}},deleteCommunity:async e=>{const t=Re();t.log("community/deleteCommunity",e),await t.http.delete(`/api/v3/communities/${e}`);const n=await _l(e);return ct("community.deleted",{communities:[n.data],categories:[],communityUsers:[],feeds:[],files:[],users:[]}),hi.community(n.data)},joinCommunity:async e=>{const t=Re();t.log("community/joinCommunity",e);const{data:n}=await t.http.post(`/api/v3/communities/${e}/join`);ct("local.community.joined",n);const r=Fs(n),a=t.cache&&Date.now();t.cache&&Xt(r,{cachedAt:a});const{communityUsers:o}=r;return!!o.find((t=>t.communityId===e&&"member"===t.communityMembership))},leaveCommunity:async e=>{const t=Re();t.log("community/leaveCommunity",e);const{data:n}=await t.http.delete(`/api/v3/communities/${e}/leave`);ct("local.community.left",n);const r=Fs(n),a=t.cache&&Date.now();t.cache&&Xt(r,{cachedAt:a});const{communityUsers:o}=r;return!!o.find((t=>t.communityId===e&&"member"!==t.communityMembership))},onCommunityCreated:Ol,onCommunityUpdated:Tl,onCommunityDeleted:El,searchCommunities:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`searchCommunities(tmpid: ${o}) > listen`);const s=new sd(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`searchCommunities(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getCommunities:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getCommunities(tmpid: ${o}) > listen`);const s=new dd(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`getCommunities(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getCommunity:(e,t)=>Cs(e,t,"communityId",_l,[Tl,El,Vl,Hl,Jl,Wl,Bl,Fl,Ll,Ti(Gl,"targetId","community")],{callbackDataSelector:e=>e?hi.community(e):e}),getTrendingCommunities:(e,t,n)=>{const{log:r,cache:a,userId:o}=Re();a||console.log(J);const s=Date.now();r(`getTrendingCommunities(tmpid: ${s}) > listen`);const i=new fd(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>qe(l))),()=>{r(`getTrendingCommunities(tmpid: ${s}) > dispose`),c.forEach((e=>e()))}},getRecommendedCommunities:(e,t,n)=>{const{log:r,cache:a,userId:o}=Re();a||console.log(J);const s=Date.now();r(`getRecommendedCommunities(tmpid: ${s}) > listen`);const i=new vd(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>qe(l))),()=>{r(`getRecommendedCommunities(tmpid: ${s}) > dispose`),c.forEach((e=>e()))}},semanticSearchCommunities:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`semanticSearchCommunities(tmpid: ${o}) > listen`);const s=new Sd(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`semanticSearchCommunities(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getJoinRequestList:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getJoinRequestList: (tmpid: ${o}) > listen`);const s=new Td(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>{qe(c)})),()=>{r(`getJoinRequestList (tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},get AmityCommunityMemberStatusFilter(){return Ed}});const Pd=async e=>{const t=Re();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&&Xt(n,{cachedAt:r});const{categories:a}=n;return{data:hi.category((null!=a?a:[]).find((t=>t.categoryId===e))),cachedAt:r}};Pd.locally=e=>{const t=Re();if(t.log("category/getCategory.locally",e),!t.cache)return;const n=je(["category","get",e]);return n?{data:hi.category(n.data),cachedAt:n.cachedAt}:void 0};const Md=async e=>{const t=Re();t.log("category/queryCategories",e);const n=null!=e?e:{},{page:r,limit:a,includeDeleted:o}=n,s=en(n,["page","limit","includeDeleted"]),i=r?{token:r}:a?{limit:a}:void 0,{data:c}=await t.http.get("/api/v3/community-categories",{params:Object.assign(Object.assign({},s),{isDeleted:bn(o),options:i})}),{paging:l}=c,d=en(c,["paging"]),{categories:u}=d,h=t.cache&&Date.now();if(t.cache){Xt(d,{cachedAt:h});const e=["category","query",Object.assign(Object.assign({},s),{includeDeleted:o,options:i})];Ue(e,{categories:null==u?void 0:u.map(Ce("category")),paging:l})}return{data:null!=u?u:[],cachedAt:h,paging:l}};Md.locally=e=>{var t,n;const r=Re();if(r.log("category/queryCategories.locally",e),!r.cache)return;const a=null!=e?e:{},{page:o,limit:s=10}=a,i=en(a,["page","limit"]),c=o?{token:o}:s?{limit:s}:void 0,l=["category","query",Object.assign(Object.assign({},i),{options:c})],{data:d,cachedAt:u}=null!==(t=je(l))&&void 0!==t?t:{};if(!(null==d?void 0:d.categories.length))return;const h=d.categories.map((e=>je(["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 jd=Object.freeze({__proto__:null,getCategory:Pd,getCategories:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getCategories(tmpid: ${o}) > listen`);const{limit:s}=e,i=en(e,["limit"]),c=null!=s?s:V,{policy:l=H}=null!=n?n:{},d=[],u=["category","collection",{}],h=(n=!1)=>{var r,a;const o=null===(r=je(u))||void 0===r?void 0:r.data,s=null!==(a=null==o?void 0:o.data)&&void 0!==a?a:[];if(!n&&s.length>0&&!(null==o?void 0:o.params.page))return;const d=ge(Md,Object.assign(Object.assign({},i),{limit:n?c:void 0,page:n||null==o?void 0:o.params.page}));ve(d,(({data:n,error:r,loading:a,paging:o})=>{const i={loading:a,error:r,params:{page:null==o?void 0:o.next},data:s};n&&(i.data=[...new Set([...s,...n.map(Ce("category"))])]),Ue(u,i),(n=>{var r,a;let o=null!==(r=n.data.map((e=>je(["category","get",e]))).filter(Boolean).map((({data:e})=>hi.category(e))))&&void 0!==r?r:[];switch(e.includeDeleted||(o=Ne(o,"isDeleted",!1)),e.sortBy){case"firstCreated":o=o.sort(Je);break;case"lastCreated":o=o.sort(Ge);break;default:o=o.sort(He)}t({onNextPage:h,data:o,hasNextPage:!!(null===(a=n.params)||void 0===a?void 0:a.page),loading:n.loading,error:n.error})})(i)}),ye(l))};return d.push((()=>{})),h(!0),()=>{r(`getCategories(tmpid: ${o}) > dispose`),d.forEach((e=>e()))}}});const Ud=async e=>{const t=Re();t.log("feed/queryGlobalFeed",e);const n=null!=e?e:{},{queryToken:r,dataTypes:a}=n,o=en(n,["queryToken","dataTypes"]),s=(()=>{if(r)return{token:r}})(),{data:i}=await t.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},o),{dataTypes:a,resolveParent:!!(a&&a.length>0)||void 0,options:s})}),{paging:c}=i,l=en(i,["paging"]),d=nn(l,"communityUsers"),{posts:u}=d,{communities:h}=Fs(d),p=t.cache&&Date.now();if(t.cache){Xt(Object.assign(Object.assign({},d),{communitis:h}));const e=["globalFeed","query",Object.assign(Object.assign({},o),{options:s})];Ue(e,{posts:u.map(Ce("post")),paging:c})}return{data:u.map(hi.post),cachedAt:p,paging:c}};Ud.locally=e=>{var t,n;const r=Re();if(r.log("post/queryGlobalFeed.locally",e),!r.cache)return;const a=en(null!=e?e:{},[]),o=["globalFeed","query",Object.assign({},a)],{data:s,cachedAt:i}=null!==(t=je(o))&&void 0!==t?t:{};if(!(null==s?void 0:s.posts.length))return;const c=s.posts.map((e=>je(["post","get",e]))).filter(Boolean).map((({data:e})=>e)).map(hi.post),{paging:l}=s;return c.length===(null===(n=null==s?void 0:s.posts)||void 0===n?void 0:n.length)?{data:c,cachedAt:i,paging:l}:void 0};class xd extends is{async getRequest(e,t){const{limit:n}=e,r=en(e,["limit"]),a=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v5/me/global-feeds",{params:Object.assign(Object.assign({},r),{options:a})});return o}}var Dd;!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"}(Dd||(Dd={}));class qd extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.posts.map(Ce("post"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Ce("post"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(r&&(!t.parentPostId||r.data.includes(t.parentPostId))){if(e===Dd.OnPostDeleted&&(r.data=r.data.filter((e=>e!==t.postId))),e===Dd.OnPostCreated||e===Dd.OnPostApproved){if(this.query.dataTypes&&this.query.dataTypes.length>0&&!this.query.dataTypes.includes(t.dataType))return;r.data=[...new Set([t.postId,...r.data])]}e===Dd.OnPostDeclined&&(r.data=r.data.filter((e=>e!==t.postId))),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Nd=async e=>{const t=Re();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=>{ae(null==t?void 0:t.code)&&Zt("comment",e)})),t}const a=t.cache&&Date.now();return t.cache&&Xt(r,{cachedAt:a}),{data:r.comments.map((e=>hi.comment(e))),cachedAt:a}};Nd.locally=e=>{var t;const n=Re();if(n.log("comment/getCommentByIds.locally",e),!n.cache)return;const r=e.map((e=>je(["comment","get",e]))).filter(Boolean),a=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:a.map((e=>hi.comment(e))),cachedAt:o.cachedAt}};const Bd=(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})},Ld=async e=>{const t=Re();t.log("story/getStoryByStoryId",e);const n=je(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;mn("story",e)}let r;try{const n=await t.http.get(`/api/v4/stories/${e}`);r=Bd(n.data)}catch(t){throw ae(null==t?void 0:t.code)&&Zt("story",e),t}const a=t.cache&&Date.now();return t.cache&&Xt(r,{cachedAt:a}),{data:r.stories[0],cachedAt:a}};Ld.locally=e=>{const t=Re();t.log("story/getStorybyStoryId",e);const n=je(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;mn("story",e)}const r=t.cache&&Date.now(),a=je(["story","get",e]);if(a)return{data:a.data,cachedAt:r}};const Fd=async(e,t=!1)=>{var n;const r=Re(),a=await $i(e);await r.http.delete(`/api/v4/comments/${encodeURIComponent(e)}`,{params:{commentId:e,permanent:t}});const o=Object.assign(Object.assign({},a.data),{isDeleted:!0});if(t?ot((()=>Zt("comment",e))):De(["comment","get",e],{isDeleted:!0}),"story"===a.data.referenceType){const e=await Ld(a.data.referenceId);ct("local.story.updated",{stories:[e.data],categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[]})}else{const e=null===(n=je(["post","get",a.data.referenceId]))||void 0===n?void 0:n.data;if(e){let t;t=o.parentId?1:o.childrenNumber+1,e.commentsCount-=t,ct("local.post.updated",{posts:[e],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[],videoStreamings:[]})}}return ct("local.comment.deleted",{comments:[o],commentChildren:[],files:[],users:[],communityUsers:[]}),o},Kd=async e=>{const t=Re();let n;t.log("comment/getComment",e),mn("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw ae(null==t?void 0:t.code)&&Zt("comment",e),t}const r=t.cache&&Date.now();t.cache&&Xt(n,{cachedAt:r});const{comments:a}=n;return{data:a.find((t=>t.commentId===e)),cachedAt:r}};Kd.locally=e=>{const t=Re();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=je(["comment","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const $d=e=>hc("local.comment.deleted",e),Qd=e=>{const t=Re();return it(t,"local.comment.addReaction","local.comment.addReaction",(({comment:n})=>{t.cache?(De(["comment","get",n.commentId],n),e(Rs(n))):e(n)}))},zd=e=>{const t=Re();return it(t,"local.comment.removeReaction","local.comment.removeReaction",(({comment:n})=>{t.cache?(De(["comment","get",n.commentId],n),e(Rs(n))):e(n)}))};class Vd extends is{async getRequest(e,t){const{limit:n=V,includeDeleted:r}=e,a=en(e,["limit","includeDeleted"]),o={type:a.sortBy||e.limit?"pagination":void 0},s=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({},a),{isDeleted:bn(r),options:s})});return i}}var Hd;!function(e){e.OnCommentCreated="onCommentCreated",e.OnCommentUpdated="onCommentUpdated",e.OnCommentDeleted="onCommentDeleted",e.OnCommentFlagged="onCommentFlagged",e.OnCommentUnflagged="onCommentUnflagged",e.OnCommentReactionAdded="onCommentReactionAdded",e.OnCommentReactionRemoved="onCommentReactionRemoved"}(Hd||(Hd={}));class Jd extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.comments.map(Ce("comment"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.comments.map(Ce("comment"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=je(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===Hd.OnCommentCreated&&(r.data=[...new Set([t.commentId,...r.data])]),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Wd=e=>hc("local.comment.created",e);class Gd extends ps{constructor(e,t){const n=I.default(e),r=["comments","collection",n];super(new Vd(e),n,r,t),this.query=e,this.queryStreamController=new Jd(this.query,this.cacheKey,this.notifyChange.bind(this),Oc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:Wd,action:Hd.OnCommentCreated},{fn:$d,action:Hd.OnCommentDeleted},{fn:pc,action:Hd.OnCommentCreated},{fn:fc,action:Hd.OnCommentUpdated},{fn:mc,action:Hd.OnCommentDeleted},{fn:gc,action:Hd.OnCommentFlagged},{fn:yc,action:Hd.OnCommentUnflagged},{fn:vc,action:Hd.OnCommentReactionAdded},{fn:bc,action:Hd.OnCommentReactionRemoved},{fn:Qd,action:Hd.OnCommentReactionAdded},{fn:zd,action:Hd.OnCommentReactionRemoved}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["comment","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]).map(hi.comment);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;if(this.query.includeDeleted||(t=Ne(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())||[],a=(null===(n=e.dataTypes)||void 0===n?void 0:n.sort())||[];return a.length===r.length&&r.every(((e,t)=>e===a[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(Je);else t=t.sort(Ge);return t}}var Yd=Object.freeze({__proto__:null,getCommentByIds:Nd,createComment:async e=>{var t;const n=Re();n.log("comment/createComment",e);const{data:r}=await n.http.post("/api/v3/comments",e),{comments:a}=r;if(0===a.length)throw new Error("Comment not created");const o=n.cache&&Date.now();if(n.cache&&Xt(r,{cachedAt:o}),["post","content"].includes(e.referenceType)){const n=null===(t=je(["post","get",e.referenceId]))||void 0===t?void 0:t.data;n&&(n.commentsCount+=1,ct("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=je(["story-reference",e.referenceId]);if(null==t?void 0:t.data){const e=je(["story","get",t.data]);(null==e?void 0:e.data)&&ct("story.updated",{stories:[Object.assign(Object.assign({},e.data),{commentsCount:e.data.commentsCount+1,comments:[...new Set([...e.data.comments,a[0].commentId])]})],categories:[],comments:a,communities:[],communityUsers:r.communityUsers,files:r.files,users:r.users})}}return ct("local.comment.created",r),{data:hi.comment(a[0]),cachedAt:o}},updateComment:async(e,t)=>{const n=Re();n.log("user/updateComment",t);const{data:r}=await n.http.put(`/api/v3/comments/${encodeURIComponent(e)}`,t),a=n.cache&&Date.now();n.cache&&Xt(r,{cachedAt:a}),ct("comment.updated",r);const{comments:o}=r;return{data:hi.comment(o.find((t=>t.commentId===e))),cachedAt:a}},deleteComment:Fd,softDeleteComment:async e=>{Re().log("comment/softDeleteComment",e);return Fd(e)},hardDeleteComment:async e=>{Re().log("comment/hardDeleteComment",e);return Fd(e,!0)},flagComment:async(t,n)=>{const r=Re();r.log("comment/flagComment",t);const a=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,r])=>t!==e.ContentFlagReasonEnum.Others&&r===n)),o={reason:n&&a?n:e.ContentFlagReasonEnum.Others,detail:n&&!a?n:""},{data:s}=await r.http.post(`/api/v3/comments/${encodeURIComponent(t)}/flag`,o);return r.cache&&Xt(s),ct("comment.flagged",s),!!s},unflagComment:async e=>{const t=Re();t.log("comment/unflagComment",e);const{data:n}=await t.http.delete(`/api/v3/comments/${encodeURIComponent(e)}/unflag`);return t.cache&&Xt(n),ct("comment.unflagged",n),!!n},isCommentFlaggedByMe:async e=>{const t=Re();t.log("comment/isCommentFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/comments/${e}/isflagbyme`);return n},onCommentCreated:pc,onCommentUpdated:fc,onCommentDeleted:mc,onCommentFlagged:gc,onCommentUnflagged:yc,onCommentReactionAdded:vc,onCommentReactionRemoved:bc,getComment:(e,t)=>Cs(e,t,"commentId",Kd,[$d,mc,gc,vc,bc,yc,fc,Qd,zd]),getComments:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log("For using Live Collection feature you need to enable Cache!");const o=Date.now();r(`getComments(tmpid: ${o}) > listen`);const s=new Gd(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`getComments(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}}});const Xd=async e=>{const t=Re();let n;t.log("post/getPost",e),mn("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw ae(null==t?void 0:t.code)&&Zt("post",e),t}const r=nn(n,"communityUsers"),a=t.cache&&Date.now();t.cache&&Xt(r,{cachedAt:a});const{posts:o}=r;return{data:o.find((t=>t.postId===e)),cachedAt:a}};Xd.locally=e=>{const t=Re();if(t.log("post/getPost.locally",e),!t.cache)return;const n=je(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Zd=e=>tc("local.post.deleted",e),eu=e=>{const t=Re();return it(t,"local.post.addReaction","local.post.addReaction",(({post:n})=>{t.cache?(De(["post","get",n.postId],n),e(n)):e(n)}))},tu=e=>{const t=Re();return it(t,"local.post.removeReaction","local.post.removeReaction",(({post:n})=>{t.cache?(De(["post","get",n.postId],n),e(n)):e(n)}))},nu=e=>tc("local.post.updated",e),ru=e=>[pc,mc,vc,bc,Wd,$d,Qd,zd].map((t=>({fn:Ti((n=>((e,t,n)=>t((async t=>{var r;const a=null===(r=je(n))||void 0===r?void 0:r.data;a&&a.data.includes(t.referenceId)&&(await Xd(t.referenceId),e(t))})))(n,t,e)),"referenceId","post"),action:Dd.OnPostUpdated}))),au=e=>[{fn:nc,action:Dd.OnPostCreated},{fn:rc,action:Dd.OnPostUpdated},{fn:nu,action:Dd.OnPostUpdated},{fn:ac,action:Dd.OnPostDeleted},{fn:ic,action:Dd.OnPostFlagged},{fn:cc,action:Dd.OnPostUnflagged},{fn:oc,action:Dd.OnPostApproved},{fn:sc,action:Dd.OnPostDeclined},{fn:lc,action:Dd.OnPostReactionAdded},{fn:dc,action:Dd.OnPostReactionRemoved},{fn:eu,action:Dd.OnPostReactionAdded},{fn:tu,action:Dd.OnPostReactionRemoved},{fn:Zd,action:Dd.OnPostDeleted},...ru(e)];class ou extends ps{constructor(e,t){const n=I.default(e),r=["customRankingGlobalFeed","collection",n];super(new xd(e),n,r,t),this.query=e,this.queryStreamController=new qd(this.query,this.cacheKey,this.notifyChange.bind(this),Yi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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(au(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=(null!==(a=o.data.map((e=>je(["post","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]).map(hi.post);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class su extends is{async getRequest(e,t){const{limit:n,dataTypes:r}=e,a=en(e,["limit","dataTypes"]),o=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},a),{dataTypes:r,resolveParent:!!(r&&r.length>0)||void 0,options:o})});return s}}class iu extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.posts.map(Ce("post"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Ce("post"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(r&&(!t.parentPostId||r.data.includes(t.parentPostId))){if(e===Dd.OnPostDeleted&&(r.data=r.data.filter((e=>e!==t.postId))),e===Dd.OnPostCreated||e===Dd.OnPostApproved){if(this.query.dataTypes&&this.query.dataTypes.length>0&&!this.query.dataTypes.includes(t.dataType))return;r.data=[...new Set([t.postId,...r.data])]}e===Dd.OnPostDeclined&&(r.data=r.data.filter((e=>e!==t.postId))),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class cu extends ps{constructor(e,t){const n=I.default(e),r=["globalFeed","collection",n];super(new su(e),n,r,t),this.query=e,this.queryStreamController=new iu(this.query,this.cacheKey,this.notifyChange.bind(this),Yi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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(au(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=(null!==(a=o.data.map((e=>je(["post","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]).map(hi.post);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class lu extends is{async getRequest(e,t){const{userId:n,feedSources:r,dataTypes:a,includeDeleted:o,matchingOnlyParentPost:s,limit:i=V}=e,c=en(e,["userId","feedSources","dataTypes","includeDeleted","matchingOnlyParentPost","limit"]),l=t?{token:t}:{limit:i},{data:d}=await this.http.get(`/api/v4/user-feeds/${n}`,{params:Object.assign(Object.assign({},c),{options:l,dataTypes:(null==a?void 0:a.length)?a:void 0,includePostedFeed:r,isDeleted:bn(o),matchingOnlyParentPost:null!=s?s:!(null==a?void 0:a.length)})});return d}}class du extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.posts.map(Ce("post"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Ce("post"))])]}))}}reactor(e){return t=>{var n,r;const a=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(a&&(this.query.dataTypes&&0!==this.query.dataTypes.length||a.data.includes(t.parentPostId?t.parentPostId:t.postId))){if(e===Dd.OnPostDeleted&&(a.data=a.data.filter((e=>e!==t.postId))),t.parentPostId&&t.isDeleted){const e=null===(r=je(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),Ue(["post","get",e.postId],e)}if(e===Dd.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),e===Dd.OnPostCreated||e===Dd.OnPostApproved){if(this.query.dataTypes&&this.query.dataTypes.length>0&&!this.query.dataTypes.includes(t.dataType))return;a.data=[...new Set([t.postId,...a.data])]}Ue(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class uu extends ps{constructor(e,t){const n=I.default(e),r=["userFeed","collection",n];super(new lu(e),n,r,t),this.query=e,this.queryStreamController=new du(this.query,this.cacheKey,this.notifyChange.bind(this),Yi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:nc,action:Dd.OnPostCreated},{fn:rc,action:Dd.OnPostUpdated},{fn:nu,action:Dd.OnPostUpdated},{fn:ac,action:Dd.OnPostDeleted},{fn:ic,action:Dd.OnPostFlagged},{fn:cc,action:Dd.OnPostUnflagged},{fn:oc,action:Dd.OnPostApproved},{fn:sc,action:Dd.OnPostDeclined},{fn:lc,action:Dd.OnPostReactionAdded},{fn:dc,action:Dd.OnPostReactionRemoved},{fn:eu,action:Dd.OnPostReactionAdded},{fn:tu,action:Dd.OnPostReactionRemoved},{fn:Zd,action:Dd.OnPostDeleted},{fn:Ti((e=>pc((async t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await Xd(t.referenceId),e(t))}))),"referenceId","post"),action:Dd.OnPostUpdated},{fn:Ti((e=>mc((async t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await Xd(t.referenceId),e(t))}))),"referenceId","post"),action:Dd.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=(null!==(a=o.data.map((e=>je(["post","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]).map(hi.post);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var hu=Object.freeze({__proto__:null,queryGlobalFeed:Ud,getCustomRankingGlobalFeed:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getCustomRankingGlobalFeed(tmpid: ${o}) > listen`);const s=new ou(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`getCustomRankingGlobalFeed(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getGlobalFeed:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getGlobalFeed(tmpid: ${o}) > listen`);const s=new cu(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`getGlobalFeed(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getUserFeed:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getUserFeed(tmpid: ${o}) > listen`);const s=new uu(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`getUserFeed(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}}});const pu=async e=>{const t=Re();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=>{ae(null==t?void 0:t.code)&&Zt("post",e)})),t}const a=nn(r,"communityUsers"),o=t.cache&&Date.now();return t.cache&&Xt(a,{cachedAt:o}),{data:a.posts.map(hi.post),cachedAt:o}};pu.locally=e=>{var t;const n=Re();if(n.log("post/getPostByIds.locally",e),!n.cache)return;const r=e.map((e=>je(["post","get",e]))).filter(Boolean),a=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:a.map(hi.post),cachedAt:o.cachedAt}};const fu=async(e,t=!1)=>{var n;const r=Re(),a=await Ki(e);if(await r.http.delete(`/api/v4/posts/${encodeURIComponent(e)}`,{params:{postId:e,permanent:t}}),"community"===a.data.targetType){const e=await _l(a.data.targetId),t=(null!==(n=Me(["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));ct("community.updated",{communities:[e.data],categories:[],communityUsers:t,feeds:[],files:[],users:[]})}const o=Object.assign(Object.assign({},a.data),{isDeleted:!0});return t?setTimeout((()=>{Zt("post",e)}),0):De(["post","get",e],{isDeleted:!0}),ct("local.post.deleted",{posts:[o],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[],videoStreamings:[]}),hi.post(o)};class mu extends is{async getRequest(e,t){const{limit:n=V,includeDeleted:r,matchingOnlyParentPost:a}=e,o=en(e,["limit","includeDeleted","matchingOnlyParentPost"]),{dataTypes:s}=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/v5/posts",{params:Object.assign(Object.assign({},o),{isDeleted:bn(r),matchingOnlyParentPost:null!=a?a:!(null==s?void 0:s.length),options:c})});return l}}class gu extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.posts.map(Ce("post"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Ce("post"))])]}))}}reactor(e){return t=>{var n,r;const a=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(t.parentPostId&&t.isDeleted){const e=null===(r=je(["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)),Ue(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===Dd.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),e!==Dd.OnPostCreated&&e!==Dd.OnPostApproved||(a.data=[...new Set([t.postId,...a.data])]),Ue(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const yu=({cacheKey:e,resolveId:t})=>[pc,mc,vc,bc,Wd,$d,Qd,zd].map((n=>({fn:Ti((r=>((e,t,n,r)=>t((async t=>{var a;const o=null===(a=je(n))||void 0===a?void 0:a.data;o&&o.data.includes(r?r(t.referenceId):t.referenceId)&&(await Xd(t.referenceId),e(t))})))(r,n,e,t)),"referenceId","post"),action:Dd.OnPostUpdated})));class vu extends ps{constructor(e,t){const n=I.default(e),r=["posts","collection",n];super(new mu(e),n,r,t),this.query=e,this.queryStreamController=new gu(this.query,this.cacheKey,this.notifyChange.bind(this),Yi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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((e=this.cacheKey,[{fn:nc,action:Dd.OnPostCreated},{fn:rc,action:Dd.OnPostUpdated},{fn:nu,action:Dd.OnPostUpdated},{fn:ac,action:Dd.OnPostDeleted},{fn:ic,action:Dd.OnPostFlagged},{fn:cc,action:Dd.OnPostUnflagged},{fn:oc,action:Dd.OnPostApproved},{fn:sc,action:Dd.OnPostDeclined},{fn:lc,action:Dd.OnPostReactionAdded},{fn:dc,action:Dd.OnPostReactionRemoved},{fn:eu,action:Dd.OnPostReactionAdded},{fn:tu,action:Dd.OnPostReactionRemoved},{fn:Zd,action:Dd.OnPostDeleted},...yu({cacheKey:e})]));var e}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["post","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]).map(hi.post);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=e;if(this.query.includeDeleted||(n=Ne(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=Ke(n,this.query.feedType)),(null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=Qe(n,this.query.dataTypes)),"firstCreated"===this.query.sortBy)n=n.sort(Je);else n=n.sort(Ge);return n}}class bu extends is{async getRequest(e,t){const n=en(e,["limit"]),{communityId:r,placement:a}=n,o=en(n,["communityId","placement"]),s=a?`/api/v1/pinned-posts/communities/${r}/${a}`:`/api/v1/pinned-posts/communities/${r}`,{data:i}=await this.http.get(s,{params:Object.assign({},o)});return i}}class wu extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=Re(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users?e.users.map(An):[]});Xt(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.pins.map(Ce("pin"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(Ce("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;r&&(e===Dd.OnPostDeleted&&(r.data=r.data.filter((e=>e!==`global#${t.postId}`))),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Cu extends ps{constructor(e,t){const n=I.default(e),r=["pinnedPosts","collection",n];super(new bu(e),n,r,t),this.query=e,this.queryStreamController=new wu(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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(yu({cacheKey:this.cacheKey,resolveId:e=>`${this.query.placement}#${e}`}))}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;let s=(null!==(a=o.data.map((e=>je(["pin","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]).map(hi.pinnedPost);s=this.applyFilter(s),(this.shouldNotify(s)||"event"!==e)&&this.callback({data:s,loading:t,error:n})}applyFilter(e){let t=e;if("lastCreated"===this.query.sortBy)t=t.sort((({post:e},{post:t})=>Ge({createdAt:null==e?void 0:e.createdAt},{createdAt:null==t?void 0:t.createdAt})));return t}}class Iu extends is{async getRequest(e,t){const n=en(e,["limit"]),{data:r}=await this.http.get("/api/v1/pinned-posts/global",{params:Object.assign({},n)});return r}}class Su extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=Re(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users.map(An)});Xt(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.pins.map(Ce("pin"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(Ce("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;r&&(e===Dd.OnPostDeleted&&(r.data=r.data.filter((e=>e!==`global#${t.postId}`))),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class _u extends ps{constructor(e,t){const n=I.default(e),r=["pinnedPosts","collection",n];super(new Iu(e),n,r,t),this.query=e,this.queryStreamController=new Su(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:Zd,action:Dd.OnPostDeleted},{fn:ac,action:Dd.OnPostDeleted},...yu({cacheKey:this.cacheKey,resolveId:e=>`global#${e}`})])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=(null!==(a=o.data.map((e=>je(["pin","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]).map(hi.pinnedPost);(this.shouldNotify(s)||"event"!==e)&&this.callback({data:s,loading:t,error:n})}}class ku extends is{async getRequest(e,t){const{limit:n=V}=e,r=en(e,["limit"]),a={type:e.limit?"pagination":void 0},o=t?Object.assign(Object.assign({},a),{token:t}):Object.assign(Object.assign({},a),{limit:n}),{data:s}=await this.http.get("/api/v1/semantic-search/posts",{params:Object.assign(Object.assign({},r),{options:o})});return s}}function Ou(e){return e.posts.map((t=>{const n=e.searchResult.find((e=>e.postId===t.postId));return`${t.postId}:${n.score}`}))}function Tu(e){return(null!=e?e:[]).map((e=>e.split(":")[0]))}class Eu extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:Ou(e)});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...Ou(e)])]}))}}reactor(e){return t=>{var n,r;const a=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(t.parentPostId&&t.isDeleted){const e=null===(r=je(["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)),Ue(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===Dd.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),e!==Dd.OnPostCreated&&e!==Dd.OnPostApproved||(a.data=[...new Set([t.postId,...a.data])]),Ue(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Au extends ps{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=I.default(n),a=["posts","collection",r];super(new ku(n),r,a,t),this.query=n,this.queryStreamController=new Eu(this.query,this.cacheKey,this.notifyChange.bind(this),Xi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:rc,action:Dd.OnPostUpdated},{fn:ac,action:Dd.OnPostDeleted},{fn:ic,action:Dd.OnPostFlagged},{fn:cc,action:Dd.OnPostUnflagged},{fn:oc,action:Dd.OnPostApproved},{fn:sc,action:Dd.OnPostDeclined},{fn:lc,action:Dd.OnPostReactionAdded},{fn:dc,action:Dd.OnPostReactionRemoved},{fn:Ti((e=>pc((async t=>{const n=je(this.cacheKey);Tu(null==n?void 0:n.data).includes(t.referenceId)||(await Ki(t.referenceId),e(t))}))),"referenceId","post"),action:Dd.OnPostUpdated},{fn:Ti((e=>mc((async t=>{const n=je(this.cacheKey);Tu(null==n?void 0:n.data).includes(t.referenceId)||(await Ki(t.referenceId),e(t))}))),"referenceId","post"),action:Dd.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=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})=>je(["post","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]).map(hi.post);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,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=Qe(t,this.query.dataTypes)),t}}class Ru extends is{async getRequest(e,t){const{limit:n=V,matchingOnlyParentPost:r,hashtags:a,dataTypes:o,targetType:s="all"}=e,i=en(e,["limit","matchingOnlyParentPost","hashtags","dataTypes","targetType"]),c={type:i.sortBy||e.limit?"pagination":void 0},l=t?Object.assign(Object.assign({},c),{token:t}):Object.assign(Object.assign({},c),{limit:n}),{data:d}=await this.http.get("/api/v1/search/posts",{params:Object.assign(Object.assign({},i),{hashtags:a,dataTypes:o,targetType:s,matchingOnlyParentPost:null!=r?r:!(null==o?void 0:o.length),options:l})});return d}}class Pu extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.posts.map(Ce("post"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Ce("post"))])]}))}}reactor(e){return t=>{var n,r;const a=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(t.parentPostId&&t.isDeleted){const e=null===(r=je(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),Ue(["post","get",e.postId],e)}e===Dd.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),e!==Dd.OnPostCreated&&e!==Dd.OnPostApproved||(a.data=[...new Set([t.postId,...a.data])]),Ue(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Mu extends ps{constructor(e,t){const n=I.default(e),r=["posts","collection",n];super(new Ru(e),n,r,t),this.query=e,this.queryStreamController=new Pu(this.query,this.cacheKey,this.notifyChange.bind(this),Yi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:nc,action:Dd.OnPostCreated},{fn:rc,action:Dd.OnPostUpdated},{fn:nu,action:Dd.OnPostUpdated},{fn:ac,action:Dd.OnPostDeleted},{fn:ic,action:Dd.OnPostFlagged},{fn:cc,action:Dd.OnPostUnflagged},{fn:oc,action:Dd.OnPostApproved},{fn:sc,action:Dd.OnPostDeclined},{fn:lc,action:Dd.OnPostReactionAdded},{fn:dc,action:Dd.OnPostReactionRemoved},{fn:eu,action:Dd.OnPostReactionAdded},{fn:tu,action:Dd.OnPostReactionRemoved},{fn:Zd,action:Dd.OnPostDeleted},{fn:Ti((e=>pc((async t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await Xd(t.referenceId),e(t))}))),"referenceId","post"),action:Dd.OnPostUpdated},{fn:Ti((e=>mc((async t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await Xd(t.referenceId),e(t))}))),"referenceId","post"),action:Dd.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["post","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]).map(hi.post);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=e;if((null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=Qe(n,this.query.dataTypes)),"firstCreated"===this.query.sortBy)n=n.sort(Je);else n=n.sort(Ge);return n}}var ju=Object.freeze({__proto__:null,getPostByIds:pu,createPost:async e=>{const t=Re();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);ct("post.created",n);const r=Yi(n),a=t.cache&&Date.now();t.cache&&Xt(r,{cachedAt:a});const{posts:o}=r;return{data:hi.post(o[0]),cachedAt:a}},editPost:async(e,t)=>{const n=Re();n.log("user/editPost",t);const{data:r}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,t),a=nn(r,"communityUsers"),o=n.cache&&Date.now();n.cache&&Xt(a,{cachedAt:o}),ct("local.post.updated",a);const{posts:s}=a;return{data:hi.post(s.find((t=>t.postId===e))),cachedAt:o}},deletePost:fu,softDeletePost:async e=>{Re().log("post/softDeletePost",e);const t=await fu(e,!1);return hi.post(t)},hardDeletePost:async e=>{Re().log("post/hardDeletePost",e);const t=await fu(e,!0);return hi.post(t)},approvePost:async e=>{const t=Re();t.log("post/approvePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/approve`);ct("post.approved",n),"community"===n.posts[0].targetType&&ct("community.updated",n);const r=nn(n,"communityUsers"),a=t.cache&&Date.now();return t.cache&&Xt(r,{cachedAt:a}),{data:hi.post(r.posts.find((t=>t.postId===e))),cachedAt:a}},declinePost:async e=>{const t=Re();t.log("post/declinePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/decline`);"community"===n.posts[0].targetType&&ct("community.updated",n),ct("post.declined",n);const r=nn(n,"communityUsers"),a=t.cache&&Date.now();return t.cache&&Xt(r,{cachedAt:a}),{data:hi.post(n.posts.find((t=>t.postId===e))),cachedAt:a}},flagPost:async(t,n)=>{const r=Re();r.log("post/flagPost",t);const a=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,r])=>t!==e.ContentFlagReasonEnum.Others&&r===n)),o={reason:n&&a?n:e.ContentFlagReasonEnum.Others,detail:n&&!a?n:""},{data:s}=await r.http.post(`/api/v3/posts/${encodeURIComponent(t)}/flag`,o);return r.cache&&Xt(nn(s,"communityUsers")),ct("post.flagged",s),!!s},unflagPost:async e=>{const t=Re();t.log("post/unflagPost",e);const{data:n}=await t.http.delete(`/api/v3/posts/${encodeURIComponent(e)}/unflag`);return t.cache&&Xt(nn(n,"communityUsers")),ct("post.unflagged",n),!!n},isPostFlaggedByMe:async e=>{const t=Re();t.log("post/isPostFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/posts/${e}/isflagbyme`);return n},createClipPost:async e=>{const t=Re();t.log("post/createPost",e);const{data:n}=await t.http.post("/api/v4/posts",e);ct("post.created",n);const r=nn(n,"communityUsers"),a=t.cache&&Date.now();t.cache&&Xt(r,{cachedAt:a});const{posts:o}=r;return{data:hi.post(o[0]),cachedAt:a}},createAudioPost:async e=>{const t=Re();t.log("post/createAudioPost",e);const{data:n}=await t.http.post("/api/v4/posts",e);ct("post.created",n);const r=Yi(n),a=t.cache&&Date.now();return t.cache&&Xt(r,{cachedAt:a}),{data:js(null==r?void 0:r.posts[0]),cachedAt:a}},createMixedMediaPost:async e=>{var t;const n=Re();n.log("post/createMixedMediaPost",e);const{data:r}=await n.http.post("/api/v4/posts",e);ct("post.created",r);const a=Yi(r),o=n.cache&&Date.now();return n.cache&&Xt(a,{cachedAt:o}),{data:js(null===(t=null==a?void 0:a.posts)||void 0===t?void 0:t[0]),cachedAt:o}},onPostCreated:nc,onPostUpdated:rc,onPostDeleted:ac,onPostApproved:oc,onPostDeclined:sc,onPostFlagged:ic,onPostUnflagged:cc,onPostReactionAdded:lc,onPostReactionRemoved:dc,getPost:(e,t)=>Cs(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?hi.post(e.data):n}))}),"postId",Ki,[oc,sc,eu,tu,t=>ac((n=>{var r;let a=n;if(n.parentPostId===e&&n.isDeleted){const e=null===(r=je(["post","get",n.parentPostId]))||void 0===r?void 0:r.data;e&&(e.children=e.children.filter((e=>e!==n.postId)),Ue(["post","get",e.postId],e),a=e)}t(a)})),ic,e=>lc((t=>{e(t)})),e=>dc((t=>{e(t)})),cc,rc,nu,Zd,Ti((t=>pc((async n=>{n.referenceId===e&&(await Ki(e),t(n))}))),"referenceId","post"),Ti((t=>mc((async n=>{n.referenceId===e&&(await Ki(e),t(n))}))),"referenceId","post")]),getPosts:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getPosts(tmpid: ${o}) > listen`);const s=new vu(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`getPosts(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getPinnedPosts:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getPinnedPosts(tmpid: ${o}) > listen`);const s=new Cu(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`getPinnedPosts(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getGlobalPinnedPosts:(e,t,n)=>{const{log:r,cache:a}=Re(),o=Date.now();r(`getGlobalPinnedPosts(tmpid: ${o}) > listen`);const s=new _u(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`getGlobalPinnedPosts(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},semanticSearchPosts:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`semanticSearchPosts(tmpid: ${o}) > listen`);const s=new Au(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`semanticSearchPosts(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},searchPostsByHashtag:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`searchPostsByHashtag(tmpid: ${o}) > listen`);const s=new Mu(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`searchPostsByHashtag(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}}});const Uu=async e=>{const t=Re();t.log("stream/getStream",e);const{data:n}=await t.http.get(`/api/v3/video-streaming/${e}`),r=t.cache&&Date.now();t.cache&&Xt(n,{cachedAt:r});const{videoStreamings:a}=n;return{data:a.find((t=>t.streamId===e)),cachedAt:r}};Uu.locally=e=>{const t=Re();if(t.log("stream/getStream",e),!t.cache)return;const n=je(["stream","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const xu=e=>{const t=Re();return it(t,"stream/onStreamStarted","video-streaming.didStart",(t=>{Xt(t),e(t.videoStreamings[0])}))},Du=e=>{const t=Re();return it(t,"stream/onStreamStropped","video-streaming.didStop",(t=>{Xt(t),e(t.videoStreamings[0])}))},qu=e=>{const t=Re();return it(t,"stream/onStreamRecorded","video-streaming.didRecord",(t=>{Xt(t),e(t.videoStreamings[0])}))},Nu=e=>{const t=Re();return it(t,"stream/onStreamFlagged","video-streaming.didFlag",(t=>{Xt(t),e(t.videoStreamings[0])}))},Bu=e=>{const t=Re();return it(t,"stream/onStreamTerminated","video-streaming.didTerminate",(t=>{Xt(t),e(t.videoStreamings[0])}))},Lu=(e,t)=>Cs(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?hi.stream(e.data):n}))}),"streamId",Uu,[qu,xu,Du,Nu,Bu,Jc]);Lu.locally=e=>{const t=Re();if(t.log("stream/getStreamById",e),!t.cache)return;const n=je(["stream","get",e]);return n?{data:hi.stream(n.data),cachedAt:n.cachedAt}:void 0};const Fu=async e=>{const t=Re();t.log("stream/queryStreams",e);const n=null!=e?e:{},{page:r,limit:a}=n,o=en(n,["page","limit"]),s=r?{token:r}:a?{limit:a}:void 0,{data:i}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},o),{options:s})}),{paging:c,results:l}=i,{videoStreamings:d}=l,u=t.cache&&Date.now();return t.cache&&Xt(l,{cachedAt:u}),{data:d,cachedAt:u,paging:c}};var Ku=Object.freeze({__proto__:null,createStream:async e=>{const t=Re();t.log("stream/createStream",e);const{data:n}=await t.http.post("/api/v3/video-streaming",e),r=t.cache&&Date.now();t.cache&&Xt(n,{cachedAt:r});const{videoStreamings:a}=n;return{data:hi.stream(a[0]),cachedAt:r}},updateStream:async(e,t)=>{const n=Re();n.log("stream/updateStream",e,t);const{data:r}=await n.http.put(`/api/v3/video-streaming/${e}`,t),a=n.cache&&Date.now();n.cache&&Xt(r,{cachedAt:a});const{videoStreamings:o}=r;return{data:hi.stream(o.find((t=>t.streamId===e))),cachedAt:a}},deleteStream:async e=>{const t=Re();t.log("stream/deleteStream",e);const n=await Uu(e),{data:r}=await t.http.delete(`/api/v3/video-streaming/${e}`),{success:a}=r,o=Object.assign(Object.assign({},n.data),{isDeleted:!0});return De(["stream","get",e],o),a},disposeStream:async e=>{const t=Re();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&&Xt(n,{cachedAt:r});const{videoStreamings:a}=n;return{data:a.find((t=>t.streamId===e)),cachedAt:r}},editStream:async(e,t)=>{const n=Re();n.log("stream/updateStream",e,t);const{data:r}=await n.http.put(`/api/v3/video-streaming/${e}`,t),a=n.cache&&Date.now();n.cache&&Xt(r,{cachedAt:a});const{videoStreamings:o}=r;return{data:hi.stream(o.find((t=>t.streamId===e))),cachedAt:a}},onStreamStarted:xu,onStreamStopped:Du,onStreamRecorded:qu,onStreamFlagged:Nu,onStreamTerminated:Bu,onStreamViewerBanned:Jc,onStreamViewerUnbanned:e=>{const t=Re();return it(t,"stream/onStreamViewerDidUnban","video-streaming.viewerDidUnban",(async t=>{var n;const{list:r}=t;await Promise.all(r.map((({streamId:e})=>Uu(e))));const a=null===(n=je(["stream","get",r[0].streamId]))||void 0===n?void 0:n.data;a&&e(a)}))},getStreamById:Lu,getStreams:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getStreams(tmpid: ${o}) > listen`);const{limit:s}=e,i=en(e,["limit"]),c=null!=s?s:V,{policy:l=H}=null!=n?n:{},d=[],u=["streams","collection",e],h=t=>{let n=Ne(t,"isDeleted",e.isDeleted);return n=n.sort("lastCreated"===e.sortBy?Ge:Je),n},p=(e,n=!1)=>{var r,a;const o=null!==(r=e.data.map((e=>je(["stream","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];t({onNextPage:m,data:n?h(o):o,hasNextPage:!!(null===(a=e.params)||void 0===a?void 0:a.page),loading:e.loading,error:e.error})},f=e=>e=>{var t;const n=null===(t=je(u))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.streamId,...n.data])],Ue(u,n),p(n,!0))},m=(e=!1)=>{var t,n;const r=null===(t=je(u))||void 0===t?void 0:t.data,a=null!==(n=null==r?void 0:r.data)&&void 0!==n?n:[];if(!e&&a.length>0&&!(null==r?void 0:r.params.page))return;const o=ge(Fu,Object.assign(Object.assign({},i),{limit:e?c:void 0,page:e||null==r?void 0:r.params.page}));ve(o,(({data:e,error:t,loading:n,paging:r})=>{const o={loading:n,error:t,params:{page:null==r?void 0:r.next},data:a};e&&(o.data=[...new Set([...a,...e.map(Ce("stream"))])]),Ue(u,o),p(o)}),ye(l))};return d.push(qu(f()),xu(f()),Du(f())),m(!0),()=>{r(`getStreams(tmpid: ${o}) > dispose`),d.forEach((e=>e()))}}});const $u=e=>{const t=Re();return it(t,"room/onRoomStartBroadcasting","room.startBroadcasting",(t=>{Xt(t),e(t.rooms[0])}))},Qu=e=>{const t=Re();return it(t,"room/onRoomWaitingReconnect","room.waitingReconnect",(t=>{Xt(t),e(t.rooms[0])}))},zu=e=>{const t=Re();return it(t,"room/onRoomEndBroadcasting","room.endBroadcasting",(t=>{Xt(t),e(t.rooms[0])}))},Vu=e=>{const t=Re();return it(t,"room/onRoomRecordedAvailable","room.recordedAvailable",(t=>{Xt(t),e(t.rooms[0])}))},Hu=async e=>{const t=Re();let n;t.log("room/getRoomById",e),mn("room",e);try{n=(await t.http.get(`/api/v1/rooms/${e}`)).data}catch(t){throw ae(null==t?void 0:t.code)&&Zt("room",e),t}const r=t.cache&&Date.now();return t.cache&&Xt(n,{cachedAt:r}),{data:n.rooms[0],cachedAt:r}};Hu.locally=e=>{const t=Re();t.log("room/getRoomById.locally",e),mn("room",e);const n=t.cache&&Date.now(),r=je(["room","get",e]);if(r)return{data:r.data,cachedAt:n}};class Ju extends is{async getRequest(e,t){const{limit:n=V,includeDeleted:r}=e,a=en(e,["limit","includeDeleted"]),o={type:a.sortBy||e.limit?"pagination":void 0},s=t?Object.assign(Object.assign({},o),{token:t}):Object.assign(Object.assign({},o),{limit:n}),{data:i}=await this.http.get("/api/v1/rooms",{params:Object.assign(Object.assign({},a),{isDeleted:bn(r),options:s})});return i}}var Wu;!function(e){e.OnRoomCreated="OnRoomCreated",e.OnRoomUpdated="OnRoomUpdated",e.OnRoomDeleted="OnRoomDeleted",e.OnRoomStartBroadcasting="OnRoomStartBroadcasting",e.OnRoomEndBroadcasting="OnRoomEndBroadcasting",e.OnRoomParticipantJoined="OnRoomParticipantJoined",e.OnRoomParticipantLeft="OnRoomParticipantLeft"}(Wu||(Wu={}));class Gu extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.rooms.map(Ce("room"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.rooms.map(Ce("room"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;r&&(e===Wu.OnRoomDeleted&&(r.data=r.data.filter((e=>e!==t._id))),e===Wu.OnRoomCreated&&(r.data=[...new Set([t._id,...r.data])]),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Yu extends ps{constructor(e,t){const n=I.default(e),r=["rooms","collection",n];super(new Ju(e),n,r,t),this.query=e,this.queryStreamController=new Gu(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:$u,action:Wu.OnRoomStartBroadcasting},{fn:zu,action:Wu.OnRoomEndBroadcasting},{fn:Vu,action:Wu.OnRoomUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["room","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]).map((e=>e));(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;if(this.query.includeDeleted||(t=Ne(t,"isDeleted",!1)),this.query.statuses&&this.query.statuses.length>0&&(t=t.filter((e=>{var t;return null===(t=this.query.statuses)||void 0===t?void 0:t.includes(e.status)}))),this.query.type&&(t=Ne(t,"type",this.query.type)),"firstCreated"===this.query.sortBy)t=t.sort(Je);else t=t.sort(Ge);return t}}var Xu=Object.freeze({__proto__:null,createRoom:async e=>{const t=Re();t.log("room/createRoom",e);const{data:n}=await t.http.post("/api/v1/rooms",e);ct("local.room.created",n);const r=t.cache&&Date.now();t.cache&&Xt(n,{cachedAt:r});const{rooms:a}=n;return{data:a[0],cachedAt:r}},updateRoom:async(e,t)=>{const n=Re();n.log("room/updateRoom",{roomId:e,bundle:t});const{data:r}=await n.http.put(`/api/v1/rooms/${e}`,t);ct("local.room.updated",r);const a=n.cache&&Date.now();n.cache&&Xt(r,{cachedAt:a});const{rooms:o}=r;return{data:o[0],cachedAt:a}},deleteRoom:async e=>{const t=Re();t.log("room/deleteRoom",{roomId:e}),await t.http.delete(`/api/v1/rooms/${e}`),ct("local.room.deleted",{rooms:[{_id:e}]})},stopRoom:async e=>{const t=Re();t.log("room/stopRoom",{roomId:e});const{data:n}=await t.http.post(`/api/v1/rooms/${e}/stop`);ct("local.room.stopped",n);const r=t.cache&&Date.now();t.cache&&Xt(n,{cachedAt:r});const{rooms:a}=n;return{data:a[0],cachedAt:r}},getRoomToken:async e=>{const t=Re();t.log("room/getRoomToken",{roomId:e});const{data:n}=await t.http.get(`/api/v1/rooms/${e}/token`);return n},getRecordedUrl:async e=>{const t=Re();t.log("room/getRecordedUrl",{roomId:e});const{data:n}=await t.http.get(`/api/v1/rooms/${e}/recorded`);return n},onRoomStartBroadcasting:$u,onRoomWaitingReconnect:Qu,onRoomEndBroadcasting:zu,onRoomRecordedAvailable:Vu,onRoomParticipantInviting:e=>{const t=Re();return it(t,"room/onRoomParticipantInviting","room.participantInviting",(t=>{Xt(t),e(t.rooms[0])}))},onRoomParticipantJoined:e=>{const t=Re();return it(t,"room/onRoomParticipantJoined","room.participantJoined",(t=>{Xt(t),e(t.rooms[0])}))},onRoomParticipantLeft:e=>{const t=Re();return it(t,"room/onRoomParticipantLeft","room.participantLeft",(t=>{Xt(t),e(t.rooms[0])}))},onRoomCreated:e=>{const t=Re();return it(t,"room/onRoomCreated","local.room.created",(t=>{Xt(t),e(t.rooms[0])}))},onRoomUpdated:e=>{const t=Re();return it(t,"room/onRoomUpdated","local.room.updated",(t=>{Xt(t),e(t.rooms[0])}))},onRoomDeleted:e=>{const t=Re();return it(t,"room/onRoomDeleted","local.room.deleted",(t=>{Xt(t),e(t.rooms[0])}))},onRoomStopped:e=>{const t=Re();return it(t,"room/onRoomStopped","local.room.stopped",(t=>{Xt(t),e(t.rooms[0])}))},getRoom:(e,t)=>Cs(e,t,"_id",Hu,[zu,$u,Qu,Vu]),getRooms:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getRooms(tmpid: ${o}) > listen`);const s=new Yu(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`getRooms(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}}});const Zu=async e=>{const t=Re();t.log("poll/getPoll",e);const{data:n}=await t.http.get(`/api/v3/polls/${e}`),r=t.cache&&Date.now();t.cache&&Xt(n,{cachedAt:r});const{polls:a}=n;return{data:a.find((t=>t.pollId===e)),cachedAt:r}};Zu.locally=e=>{const t=Re();if(t.log("poll/getPoll",e),!t.cache)return;const n=je(["poll","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const eh=e=>{const t=Re();return it(t,"poll/onPollUpdated","poll.updated",(n=>{t.cache&&Xt(n),e(n.polls[0])}))},th=e=>{const t=Re();return it(t,"poll/onPollDeleted","poll.deleted",(n=>{t.cache&&Xt(n),e(n.polls[0])}))};var nh=Object.freeze({__proto__:null,createPoll:async e=>{const t=Re();t.log("post/createPoll",e);const{data:n}=await t.http.post("/api/v3/polls",e),r=t.cache&&Date.now();t.cache&&Xt(n,{cachedAt:r});const{polls:a}=n;return{data:a[0],cachedAt:r}},closePoll:async e=>{const t=Re();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&&Xt(n,{cachedAt:r}),ct("poll.updated",n);const{polls:a}=n;return{data:a.find((t=>t.pollId===e)),cachedAt:r}},deletePoll:async e=>{const t=Re();t.log("poll/deletePoll",e);const n=await Zu(e),{data:r}=await t.http.delete(`/api/v3/polls/${e}`),{success:a}=r,o=Object.assign(Object.assign({},n.data),{isDeleted:!0});return De(["poll","get",e],o),ct("poll.deleted",{polls:[o],users:[]}),a},votePoll:async(e,t)=>{const n=Re();n.log("user/votePoll",e);const{data:r}=await n.http.post(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:t}),a=n.cache&&Date.now();n.cache&&Xt(r,{cachedAt:a});const{polls:o}=r;return ct("poll.updated",r),{data:o.find((t=>t.pollId===e)),cachedAt:a}},unvotePoll:async e=>{const t=Re();t.log("user/unvotePoll",e);const{data:n}=await t.http.put(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:[]}),r=t.cache&&Date.now();t.cache&&Xt(n,{cachedAt:r}),ct("poll.updated",n)},onPollUpdated:eh,onPollDeleted:th,getPoll:(e,t)=>Cs(e,t,"pollId",Zu,[eh,th])});const rh={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};function ah(e){const n=new Uint8Array(e);let r="";return n.forEach((e=>{r+=String.fromCharCode(e)})),t.btoa(r)}function oh(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,rh,!1,["sign"])}async function sh({bufferCurrentUsage:e,getActiveStreams:t,updateUsage:n,dispose:r}){const a=e();if(a.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=w.default.v4(),a=`nonceStr=${r}&timestamp=${e}&data=${n}==`,o=(new TextEncoder).encode(a),s=await oh("-----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:ah(await crypto.subtle.sign(rh,s,o)),nonceStr:r}}({timestamp:n,streams:a});if(!o||!o.signature)throw new Error("Signature is undefined");const s={signature:o.signature,nonceStr:o.nonceStr,timestamp:n,streams:a},i=Re();return await i.http.post("/api/v3/user-event/video-streaming",s),t().length||e().length||r(),!0}catch(e){return a.forEach((e=>n(e))),!1}}class ih{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((()=>{sh({bufferCurrentUsage:this.bufferCurrentUsage.bind(this),getActiveStreams:this.getActiveStreams.bind(this),updateUsage:this.updateUsage.bind(this),dispose:this.dispose.bind(this)})}),2e4)}}let ch=null;class lh{constructor(e,t,n){this._SDKUnsubscribers=[],this.player=e,this.resolution=t,this._startTime=null,this._usageCollector=ch||(ch=new ih,ch),this._usageCollector.registerStream(e.id),this._sessionId=String(w.default.v4()),this._controller=new AbortController,this._observer=new MutationObserver((t=>{t.forEach((t=>{t.removedNodes.forEach((t=>{t===e&&(this._unregisterEvents(),this._SDKUnsubscribers.forEach((e=>null==e?void 0:e())))}))}))})),this._SDKUnsubscribers.push(Jc((e=>{e.watcherUrl||(this.player.pause(),this.player.removeAttribute("src"),this.player.load(),this.player.remove())})))}_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 dh=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(!S.default.isSupported())throw new Error("This browswer does not support hls, unable to play stream");const{data:n}=await Uu(t),{watcherUrl:r,status:a,recordings:o=[],resolution:s}=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 S.default;if(c.attachMedia(i),"recorded"!==a){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 lh(i,s,t).registerEvents(),i}});const uh=e=>{const t=(e=>{var t;const n=Re(),r=new Date,a=r.getTime()+31536e6,o=new Date(a).toISOString();let s=null===(t=je(["storyTarget","get",e.targetId]))||void 0===t?void 0:t.data;return s||(s={targetType:e.targetType,targetId:e.targetId,lastStoryExpiresAt:o,targetPublicId:e.targetId,targetUpdatedAt:r.toISOString()},Xt({storyTargets:[s]})),{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(a).toISOString()},e)],categories:[],communityUsers:[],comments:[],files:[],users:[],communities:[]}})(e);return Xt(t),t},hh=({payload:e,formData:t,isVideo:n=!1},r)=>{if(t){const a=t.getAll("files")[0]||void 0;if(!a)return;const o=Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileId:void 0,fileData:a.uri})});return n&&(o.data.videoFileId={original:void 0}),r(uh(o))}return r(uh(Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileData:null})})))},ph=async e=>{const t=Re();t.log("post/createStory",e);const n=await t.http.post("/api/v4/stories",e),r=Bd(n.data);t.cache&&Xt(r),Ue(["story-sync-state",e.targetId],"synced"),ct("local.story.created",r);const a=t.cache&&Date.now();return{data:r.stories.length>0?r.stories[0]:void 0,cachedAt:a}},fh=async({targetId:e,targetType:t})=>{var n,r;if(!je(["storyTarget","get",e])){let a={targetId:e,targetType:t};if("community"===t){const t=await _l(e);a=Object.assign(Object.assign({},a),{targetPublicId:t.data.communityId,targetUpdatedAt:null!==(n=t.data.updatedAt)&&void 0!==n?n:(new Date).toISOString()})}if("user"===t){const t=await bi(e);a=Object.assign(Object.assign({},a),{targetPublicId:t.data.userPublicId,targetUpdatedAt:null!==(r=t.data.updatedAt)&&void 0!==r?r:(new Date).toISOString()})}Ue(["storyTarget","get",e],a)}},mh=e=>e?je(["story","get",e]):{data:void 0,cachedAt:void 0},gh=async(e,t=!1)=>{var n,r,a;const o=Re();let s;if(o.log("story/deleteStory",e),o.cache&&(s=mh(e),null==s?void 0:s.data)){const{data:o}=s;if(ct("local.story.deleted",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[Object.assign(Object.assign({},o),{isDeleted:!0})]}),"synced"!==o.syncState){t?qe(["story","get",e]):Ue(["story","get",e],Object.assign(Object.assign({},s.data),{isDeleted:!0}));const r=null===(n=Me(["story","get"]))||void 0===n?void 0:n.filter((e=>"synced"!==e.data.syncState&&e.data.targetId===o.targetId&&!0!==e.data.isDeleted));if(r&&r.length>0){const e=r.reduce(((e,t)=>{const n=new Date(t.data.expiresAt||0);return n>e?n:e}),new Date(0));Ue(["story-expire",s.data.targetId],e.toISOString())}else qe(["story-expire",s.data.targetId]);return!0}const i=null===(r=je(["storyTarget","get",o.targetId]))||void 0===r?void 0:r.data,c=null===(a=Me(["story","get"]))||void 0===a?void 0:a.filter((e=>"synced"===e.data.syncState&&e.data.targetId===o.targetId&&!0!==e.data.isDeleted));let l;c&&c.length>0&&(l=null==c?void 0:c.reduce(((e,t)=>{const n=new Date(t.data.expiresAt||0);return n>e?n:e}),new Date(0))),i&&Ue(["storyTarget","get",o.targetId],Object.assign(Object.assign({},i),{lastStoryExpiresAt:l}))}return(await o.http.delete(`/api/v4/stories/${e}`,{params:{permanent:t}})).data.success},yh=e=>{const t=Re(),n=[it(t,"onStoryUpdated","story.updated",(async t=>{const n=Bd(t);Xt(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},vh=e=>{const t=Re(),n=[it(t,"onStoryUpdated","local.story.updated",(async t=>{Xt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},bh=e=>{const t=Re(),n=[it(t,"onStoryReactionAdded","story.reactionAdded",(async t=>{const{reactions:n}=t,r=en(t,["reactions"]),a=Bd(r),o=Ji("story.reactionAdded",Object.assign(Object.assign({},a),{reactions:n}));Xt(o),e(o.stories)}))];return()=>{n.forEach((e=>e()))}},wh=e=>{const t=Re(),n=[it(t,"onStoryReactionAdded","local.story.reactionAdded",(async t=>{Xt({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},Ch=e=>{const t=Re(),n=[it(t,"onStoryReactionRemoved","story.reactionRemoved",(async t=>{const{reactions:n}=t,r=en(t,["reactions"]),a=Bd(r),o=Ji("story.reactionRemoved",Object.assign(Object.assign({},a),{reactions:n}));Xt(o),e(o.stories)}))];return()=>{n.forEach((e=>e()))}},Ih=e=>{const t=Re(),n=[it(t,"onStoryReactionRemoved","local.story.reactionRemoved",(async t=>{Xt({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},Sh=e=>{e.forEach((e=>{const t=je(["story-expire",e.targetId]),n=new Date(e.expiresAt||0);n<new Date((null==t?void 0:t.data)||0)||Ue(["story-expire",e.targetId],n.toISOString())}))},_h=e=>{e.forEach((e=>{Ue(["story-reference",e.storyId],e.referenceId)}))},kh=async({targetType:e,targetId:t,options:n})=>{const r=Re();r.log("story/getActiveStoriesByTarget");const a=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"}}}),s=Bd(o.data);return r.cache&&(Xt(s),Sh(s.stories),_h(s.stories)),{data:s.stories,cachedAt:a,paging:{next:void 0,previous:void 0}}},Oh=e=>{const t=Re(),n=[it(t,"onStoryCreated","story.created",(async t=>{const n=Bd(t,!0);Xt(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Th=e=>{const t=Re(),n=[it(t,"onStoryCreated","local.story.created",(async t=>{Xt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},Eh=e=>{const t=Re(),n=[it(t,"onStoryDeleted","story.deleted",(async t=>{const n=Bd(t);Xt(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Ah=e=>{const t=Re(),n=[it(t,"onStoryDeleted","local.story.deleted",(async t=>{Xt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},Rh=e=>{const t=Re();return it(t,"onStoryError","local.story.error",(async t=>{Xt(t),e(t.stories)}))},Ph=e=>t=>e((e=>t(e[0]))),Mh=async e=>{const t=Re();t.log("story/getTargetsByTargetIds",e);const n=await t.http.get("/api/v4/stories/seen",{params:{targets:e}}),{data:r}=n;return t.cache&&Xt(n.data),{data:r.storyTargets,cachedAt:Date.now()}};class jh extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.paginationController=r}saveToMainDB(e){const t=Re(),n=t.cache&&Date.now(),r=Bd(e);t.cache&&(Xt(r,{cachedAt:n}),Sh(r.stories),_h(r.stories))}getStoryReferenceIds(e){return(null==e?void 0:e.referenceId)?e.referenceId:e.storyId}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.stories.map(this.getStoryReferenceIds)});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(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=je(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])],Ue(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Uh extends hs{async getRequest(e){const{data:t}=await this.http.get("/api/v4/stories-by-targets",{params:Object.assign({},e)});return t}}class xh extends ps{constructor(e,t){const n=I.default(e),r=["story-target-ids","collection",n],a=new Uh(e);super(a,n,r,t),this.query=e,this.queryStreamController=new jh(this.query,this.cacheKey,this.notifyChange.bind(this),a),this.paginationController=a,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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 a=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;let o=a.data.map((e=>je(["story","get",e]))).filter(Boolean).map((e=>hi.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(Je):r.sort(Ge)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Oh,action:"onCreate"},{fn:yh,action:"onUpdate"},{fn:Eh,action:"onDelete"},{fn:Rh,action:"onError"}])}}const Dh=(e,t)=>{var n,r;const a=null===(n=je(e))||void 0===n?void 0:n.data,o=null!==(r=null==a?void 0:a.data)&&void 0!==r?r:[];Ue(e,Object.assign(Object.assign({},a),{data:[...new Set([...o,...t])]}))};class qh extends ls{constructor(e,t,n,r,a){super(e,t),this.notifyChange=n,this.paginationController=r,this.preparePayload=a}saveToMainDB(e){const t=Re(),n=t.cache&&Date.now(),r=this.preparePayload(e);t.cache&&Xt(r,{cachedAt:n})}appendToQueryStream(e,t,n=!1){n?Ue(this.cacheKey,{data:e.storyTargets.map((({targetId:e})=>e))}):Dh(this.cacheKey,e.storyTargets.map((({targetId:e})=>e)))}reactor(e){return t=>{"onCreate"===e&&"seen"!==this.query.seenState&&Dh(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 Nh extends is{constructor(){super(...arguments),this.smartFilterState="unseen"}async getRequest(e,t){var n;const{limit:r=10,seenState:a="unseen"}=e,o=await this.createRequest({seenState:"smart"===a?this.smartFilterState:a,limit:r,token:t});if(null===(n=o.paging)||void 0===n?void 0:n.next)return o;if("smart"!==a)return o;if("seen"===this.smartFilterState)return o;this.smartFilterState="seen";const s=await this.createRequest({seenState:this.smartFilterState,limit:r});return c=s,{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 Bh extends ps{constructor(e,t){const n=I.default(e),r=["story-global-feed","collection",n],a=new Nh(e);super(a,n,r,t),this.query=e,this.queryStreamController=new qh(this.query,this.cacheKey,this.notifyChange.bind(this),a,(e=>{const t=en(Fs(Object.assign(Object.assign({},e),{feeds:[]})),["feeds"]);return Object.assign(Object.assign({},e),t)})),this.paginationController=a,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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 a=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const o=a.data,s=Me(["storyTarget"]);s&&(null==s?void 0:s.length)>0&&(null==s||s.forEach((({key:e})=>{a.data.includes(e[2])||o.push(e[2])})));let i=o.map((e=>je(["storyTarget","get",e]))).filter(Boolean).map((e=>hi.storyTarget(e.data)));(this.shouldNotify(i)||"event"!==e)&&(i=this.applyFilter(i).filter((({localSortingDate:e})=>!!e)).map((e=>en(e,["localFilter","localLastExpires","localLastSeen","localSortingDate"]))),this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,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(We);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(We)||[],r=t.unseen.sort(We)||[],a=t.seen.sort(We)||[];return n.concat(r,a)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Oh,action:"onCreate"},{fn:yh,action:"onUpdate"},{fn:Eh,action:"onDelete"},{fn:Th,action:"onCreate"},{fn:vh,action:"onUpdate"},{fn:Ah,action:"onDelete"},{fn:Rh,action:"onError"}])}}var Lh=Object.freeze({__proto__:null,createImageStory:async(e,t,n,r={},a="fit",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,imageDisplayMode:a},syncState:"syncing",referenceId:zt(),dataType:"image",items:o,targetType:e,targetId:t,metadata:r};const i=new Date;Ue(["story-sync-state",t],"syncing"),Ue(["story-expire",t],new Date(i.setFullYear(i.getFullYear()+1))),hh({payload:s,formData:n},(e=>{ct("local.story.created",e)}));try{const{data:r}=await qi(n);if(0===r.length)throw new Error("Failed to upload image");const{fileId:a}=r[0];s=Object.assign(Object.assign({},s),{data:Object.assign(Object.assign({},s.data),{fileId:a})}),fh({targetId:t,targetType:e}),hh({payload:s,formData:n},(e=>{ct("local.story.created",e)}));const o=await ph(s);return o.data?Object.assign(Object.assign({},o),{data:hi.story(o.data)}):o}catch(e){throw Ue(["story-sync-state",t],"error"),hh({payload:Object.assign(Object.assign({},s),{syncState:"error"}),formData:n},(e=>{ct("local.story.error",e)})),e}},createVideoStory:async(e,t,n,r={},a=[])=>{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:zt(),dataType:"video",items:a,targetType:e,targetId:t,metadata:r};const s=new Date;Ue(["story-sync-state",t],"syncing"),Ue(["story-expire",t],new Date(s.setFullYear(s.getFullYear()+1))),fh({targetId:t,targetType:e}),hh({payload:o,formData:n,isVideo:!0},(e=>{ct("local.story.created",e)}));try{const{data:e}=await Di(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}})}),hh({payload:o,formData:n,isVideo:!0},(e=>{ct("local.story.created",e)}));const r=await ph(o);return r.data?Object.assign(Object.assign({},r),{data:hi.story(r.data)}):r}catch(e){throw Ue(["story-sync-state",t],"error"),hh({payload:Object.assign(Object.assign({},o),{syncState:"error"}),formData:n,isVideo:!0},(e=>{ct("local.story.error",e)})),e}},hardDeleteStory:async e=>await gh(e,!0),softDeleteStory:async e=>await gh(e),getActiveStoriesByTarget:(e,t)=>{const{log:n,cache:r}=Re(),a=[],o=["story-target","collection",e],s=Date.now();n(`getActiveStoriesByTarget(tmpid: ${s}) > listen`),r||console.log(J);const i=t=>{var n,r;const a=(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"===a?"asc"===o?t.sort(Je):t.sort(Ge):"asc"===o?t.sort(Ye):t.sort(Xe)},c=e=>{var n;const r=e.data.map((e=>{const t=mh(e);if(null==t?void 0:t.data)return hi.story(t.data)})).filter(Boolean).filter((e=>!!e&&!e.isDeleted)),a=[];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")||[]);a.push(...t)}if(e.has("syncing")){const t=i(e.get("syncing")||[]);a.push(...t)}if(e.has("synced")){const t=i(e.get("synced")||[]);a.push(...t)}}t({onNextPage:()=>!1,data:a||r,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading||!1})},l=(t,n,r=!1,a=!1,s=!1)=>{var i;const l=je(o),d={loading:a,error:s,params:{page:void 0},data:(null==l?void 0:l.data)||[]};if(t)if("onDelete"===n){const e=t.map((({referenceId:e})=>e));d.data=d.data.filter((t=>!e.includes(t)))||[]}else d.data=r?t.map(Ce("story")):[...new Set([...d.data,...t.map(Ce("story"))])];const u=null===(i=Me(["story","get"]))||void 0===i?void 0:i.filter((t=>t.data.targetId===e.targetId&&"synced"!==t.data.syncState)).map((e=>Ce("story")(e.data)));u&&(null==u?void 0:u.length)>0&&u.forEach((e=>{d.data.includes(e)||d.data.push(e)})),Ue(o,d.data),c(d)},d=e=>t=>{l(t,e)};return(t=>{const n=ge(kh,e);ve(n,(({data:e,error:n,loading:r})=>{l(e,"fetch",t,r,n)}))})(!0),a.push(Oh(d("onCreate")),yh(d("onUpdate")),Eh(d("onDelete")),bh(d("onReactionAdded")),Ch(d("onReactionRemoved")),Rh(d("onError")),Th(d("onCreate")),vh(d("onUpdate")),Ah(d("onDelete")),wh(d("onReactionAdded")),Ih(d("onReactionRemoved")),(e=>{const t=Re();return it(t,"onStoryLocalDataUpdated","local.story.reload",(t=>{e(t)}))})((e=>{const t=je(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)})),(()=>qe(o))),()=>{n(`getActiveStoriesByTarget(tmpid: ${s}) > dispose`),a.forEach((e=>e()))}},getStoryByStoryId:(e,t)=>Cs(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:hi.story(e.data)})):t(e)}),"storyId",Ld,[Ph(yh),Ph(Eh),Ph(bh),Ph(Ch),Ph(Rh),Ph(vh),Ph(Ah),Ph(wh),Ph(Ih)]),getTargetById:(e,t)=>Cs(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:hi.storyTarget(e.data[0])})):t(e)}),"query",(e=>Mh([e])),[]),getTargetsByTargetIds:(e,t)=>{const{log:n,cache:r}=Re(),a=[],o=["storyTargets","collection",e],s=Date.now();n(`getTargetsByTargetIds(tmpid: ${s}) > listen`),r||console.log(J);const i=(e,n=!1,r=!1,a=!1)=>{const s=je(o),i={loading:r,error:a,params:{page:void 0},data:[]};e&&(i.data=n?e.map(Ce("storyTarget")):[...new Set([...(null==s?void 0:s.data)||[],...e.map(Ce("storyTarget"))])]),Ue(o,i.data),(e=>{var n;const r=e.data.map((e=>{const t=je(["storyTarget","get",e]);if(null==t?void 0:t.data)return hi.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=ge(Mh,e);ve(n,(({data:e,error:n,loading:r})=>{i(e,t,r,n)}))})(!0),a.push((()=>qe(o))),()=>{n(`getTargetsByTargetIds(tmpid: ${s}) > dispose`),a.forEach((e=>e()))}},getStoriesByTargetIds:(e,t,n)=>{const{log:r,cache:a,userId:o}=Re();a||console.log(J);const s=Date.now();r(`getStoriesByTargetIds(tmpid: ${s}) > listen`);const i=new xh(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{qe(l)})),()=>{r(`getStoriesByTargetIds(tmpid: ${s}) > dispose`),c.forEach((e=>e()))}},getGlobalStoryTargets:(e,t,n)=>{const{log:r,cache:a,userId:o}=Re();a||console.log(J);const s=Date.now();r(`getGlobalStoryTarget(tmpid: ${s}) > listen`);const i=new Bh(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{qe(l)})),()=>{r(`getGlobalStoryTarget(tmpid: ${s}) > dispose`),c.forEach((e=>e()))}}});const Fh=e=>Object.assign(Object.assign({},e),{endAt:e.endAt?e.endAt:null}),Kh=e=>Object.assign({},e);var $h=Object.freeze({__proto__:null,getNetworkAds:async()=>{const e=Re(),{data:t}=await e.http.get("/api/v1/ads/me"),n=t.ads.map(Fh),r=t.advertisers.map(Kh);return Xt({ads:n,advertisers:r,files:t.files}),Ue(["ad","setting"],t.settings),{ads:n.map(hi.ad),settings:t.settings}}});const Qh=async()=>{const e=Re();e.log("notificationTray/getNotificationTraySeen",{});const{data:t}=await e.http.get("api/v1/notification-tray/tray/seen"),n=e.cache&&Date.now();if(e.cache){const n=["notificationTraySeen","get",e.userId];Ue(n,{userId:e.userId,lastTraySeenAt:t.lastTraySeenAt,lastTrayOccuredAt:t.lastTrayOccurredAt})}return{data:{userId:e.userId,lastTraySeenAt:t.lastTraySeenAt,lastTrayOccurredAt:t.lastTrayOccurredAt,isSeen:t.lastTraySeenAt>t.lastTrayOccurredAt},cachedAt:n}};Qh.locally=()=>{var e;const t=Re();if(t.log("notificationTray/getNotificationTraySeen.locally",{}),!t.cache)return;const{data:n,cachedAt:r}=null!==(e=je(["notificationTraySeen","get"]))&&void 0!==e?e:{};return n?{data:n,cachedAt:r}:void 0};const zh=e=>{const t=Re(),n=[it(t,"onNotificationTraySeenUpdated","local.notificationTraySeen.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class Vh extends is{async getRequest(e,t){const{limit:n=V}=e,r=en(e,["limit"]),a=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/notification-tray",{params:Object.assign(Object.assign({},r),{options:a})});return o}}class Hh extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.notificationTrayItems.map(Ce("notificationTrayItem"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.notificationTrayItems.map(Ce("notificationTrayItem"))])]}))}}}const Jh=e=>{const t=e.users.map(An);return Object.assign(Object.assign({},e),{users:t})};class Wh extends ps{constructor(e,t){const n=I.default(e),r=["notificationTrayItem","collection",n];super(new Vh(e),n,r,t),this.query=e,this.queryStreamController=new Hh(this.query,this.cacheKey,this.notifyChange.bind(this),Jh),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=(null!==(a=o.data.map((e=>je(["notificationTrayItem","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]).map(hi.notificationTray);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var Gh=Object.freeze({__proto__:null,getNotificationTraySeen:e=>{const{userId:t}=tt();return Cs(t,e,"userId",Qh,[zh],{callbackDataSelector:e=>{let t=!0;return(null==e?void 0:e.lastTrayOccurredAt)&&(t=!!e.lastTraySeenAt&&Un(e.lastTraySeenAt)>Un(e.lastTrayOccurredAt)),{lastTrayOccurredAt:null==e?void 0:e.lastTrayOccurredAt,lastTraySeenAt:null==e?void 0:e.lastTraySeenAt,isSeen:t}}})},getNotificationTrayItems:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getNotificationTrayItems(tmpid: ${o}) > listen`);const s=new Wh(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`getNotificationTrayItems(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},markItemsSeen:async e=>{const t=Re();t.log("notificationTray/markItemsSeen",{});const{data:n}=await t.http.post("api/v1/notification-tray/items/seen",{trayItems:e.map((e=>({id:e.id,lastSeenAt:e.lastSeenAt})))}),r=n.trayItems.map((e=>{var n;const r=null===(n=je(["notificationTrayItem","get",e.id]))||void 0===n?void 0:n.data;if(!r)return;const a=Object.assign(Object.assign({},r),{lastSeenAt:e.lastSeenAt});if(t.cache){const e=Date.now();Ue(["notificationTrayItem","get"],a,{cachedAt:e})}return a})).filter(Boolean);ct("local.notificationTrayItem.updated",{notificationTrayItems:r})},markTraySeen:async e=>{var t;const n=Re();n.log("notificationTray/markTraySeen",{});const{data:r}=await n.http.post("api/v1/notification-tray/tray/seen",{lastSeenAt:e}),a=null===(t=je(["notificationTraySeen","get"]))||void 0===t?void 0:t.data,o={userId:n.userId,lastTraySeenAt:r.lastSeenAt},s=Object.assign(Object.assign({},a),o),i=n.cache&&Date.now();return n.cache&&Ue(["notificationTraySeen","get",n.userId],s,{cachedAt:i}),ct("local.notificationTraySeen.updated",o),{data:r,cachedAt:i}},onNotificationTraySeenUpdated:zh});class Yh extends is{async getRequest(e,t){const{limit:n=V}=e,r=en(e,["limit"]),a=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/invitations/me",{params:Object.assign(Object.assign({},r),{options:a})});return await Sl(o.invitations.map((e=>e.communityId))),o}}class Xh extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.invitations.map(Ce("invitation"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(Ce("invitation"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(e===ai.OnLocalInvitationUpdated){if(!r.data.find((e=>e===t[0].invitationId)))return}if(e===ai.OnLocalInvitationCreated){const e=Re(),n=t.filter((t=>t.invitedUserId===e.userId));r.data=[...new Set([...n.map((e=>e.invitationId)),...r.data])]}e===ai.OnLocalInvitationDeleted&&(r.data=r.data.filter((e=>e!==t[0].invitationId))),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Zh extends ps{constructor(e,t){const n=I.default(e),r=["invitation","collection",n];super(new Yh(e),n,r,t),this.query=e,this.queryStreamController=new Xh(this.query,this.cacheKey,this.notifyChange.bind(this),ni),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(this.cacheKey,{data:[],params:this.query})}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:ai.OnLocalInvitationCreated},{fn:ci,action:ai.OnLocalInvitationUpdated},{fn:li,action:ai.OnLocalInvitationDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["invitation","get",e]))).filter(fs).map((({data:e})=>ri(e))))&&void 0!==a?a:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;this.query.targetId&&(t=t.filter((e=>e.targetId===this.query.targetId))),this.query.statuses&&(t=t.filter((e=>{var t;return null===(t=this.query.statuses)||void 0===t?void 0:t.includes(e.status)}))),this.query.targetType&&(t=t.filter((e=>e.targetType===this.query.targetType))),this.query.type&&(t=t.filter((e=>e.type===this.query.type)));const n=(()=>"firstCreated"===this.query.sortBy?Je:Ge)();return t=t.sort(n),t}}var ep=Object.freeze({__proto__:null,onLocalInvitationCreated:ii,onLocalInvitationUpdated:ci,onLocalInvitationDeleted:li,getMyCommunityInvitations:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getMyCommunityInvitations: (tmpid: ${o}) > listen`);const s=new Zh(Object.assign(Object.assign({},e),{targetType:"community",statuses:["pending"]}),t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>{qe(c)})),()=>{r(`getInvitations (tmpid: ${o}) > dispose`),i.forEach((e=>e()))}}});const tp=e=>{const t=Re();return it(t,"live_reaction/onLiveReactionCreated","liveReaction.created",(n=>{if(n.reactions.length>0){const r=n.reactions.filter((({userId:e})=>e!==t.userId));e(r)}}))};var np=Object.freeze({__proto__:null,createReaction:async({referenceId:e,referenceType:t,reactionName:n,streamId:r})=>{const a=Re();a.log("live_reaction/createReaction",{referenceId:e,referenceType:t,reactionName:n});const o=$a(),s={reactionName:n,referencePublicId:e,referenceType:t,streamId:r,occurredAt:(new Date).toISOString()};return o.createLiveReaction(s),ct("local.liveReaction.created",[Object.assign(Object.assign({},s),{userId:a.userId,referenceId:e})]),!0},onLiveReactionCreated:tp,getReactions:(e,t)=>{const{_id:n}=tt();if(!n)throw new _e("The _id has not been defined in ActiveUser",8e5,"error");const{log:r}=Re();r(`getReactions(tmpid: ${Date.now()}) > listen`);const a=[],o=n=>{(e=>{t(e)})(n.filter((({referenceId:t})=>t===e)))};return a.push(tp(o)),a.push((e=>{const t=Re();return it(t,"live_reaction/onLiveReactionCreated","local.liveReaction.created",e)})(o)),()=>{a.forEach((e=>e()))}}});return e.API_REGIONS=Et,e.AdRepository=$h,e.CategoryRepository=jd,e.ChannelRepository=Cl,e.Client=Fo,e.CommentRepository=Yd,e.CommunityPostSettingMaps=R,e.CommunityPostSettings=A,e.CommunityRepository=Rd,e.ContentFeedType=M,e.DefaultCommunityPostSetting=P,e.FeedRepository=hu,e.FileRepository=Ni,e.FileType=_,e.GET_WATCHER_URLS=Ts,e.InvitationRepository=ep,e.LiveReactionRepository=np,e.LiveStreamPlayer=dh,e.MessageContentType=U,e.MessageRepository=Xc,e.PollRepository=nh,e.PostContentType=x,e.PostRepository=ju,e.PostStructureType=D,e.ReactionRepository=kc,e.RoomRepository=Xu,e.StoryRepository=Lh,e.StreamRepository=Ku,e.SubChannelRepository=ol,e.UserRepository=Ui,e.VERSION=z,e.VideoResolution=k,e.VideoSize=T,e.VideoTranscodingStatus=O,e.backupCache=async(e="amitySdk",t=(e=>e.offline))=>{const{log:n,cache:r,userId:a}=Re();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}#${a}`,JSON.stringify(o)),!0)},e.createQuery=ge,e.createReport=async(e,t)=>{const n=Re();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 fa(n);Xt(e)}return ct("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 On(n);Xt(e)}return ct("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 Yi(n);Xt(e)}return ct("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 Oc(n);Xt(e)}return ct("comment.flagged",n),!!n})({client:n,referenceId:t})},e.createUserToken=async(e,t,n)=>{const r=await Ht(),a=Jt(),o=qt(Rt("http",t)),{data:s}=await o.post("/api/v5/sessions",Object.assign(Object.assign({},n),{deviceId:r,deviceInfo:Object.assign(Object.assign({},a),{model:"token management API on TS-SDK"})}),{headers:{"X-API-Key":e}});return{accessToken:s.accessToken}},e.deleteReport=async(e,t)=>{const n=Re();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 fa(n);Xt(e)}return ct("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 On(n);Xt(e)}return ct("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 Yi(n);Xt(e)}return ct("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 Oc(n);Xt(e)}return ct("comment.unflagged",n),!!n})({client:n,referenceId:t})},e.disableCache=()=>{const e=Re();e.cache&&(e.log("cache/api/disableCache"),delete e.cache)},e.dropFromCache=qe,e.enableCache=(e={},t)=>{const n=Re();n.cache||(n.log("cache/api/enableCache"),n.cache={data:e,persistIf:t})},e.filterByChannelMembership=Fe,e.filterByCommunityMembership=$e,e.filterByFeedType=Ke,e.filterByPostDataTypes=Qe,e.filterByPropEquality=Ne,e.filterByPropInclusion=(e,t,n)=>void 0!==n?e.filter((e=>n.includes(e[t]))):e,e.filterByPropIntersection=Le,e.filterBySearchTerm=ze,e.filterByStringComparePartially=Be,e.getChannelTopic=e=>`${e.path}/#`,e.getCommentTopic=({path:e})=>e,e.getCommunityStoriesTopic=({targetId:e,targetType:t})=>{const n=tt();return`${ft(n)}/social/${t}/${e}/story/#`},e.getCommunityTopic=({path:t},n=e.SubscriptionLevels.COMMUNITY)=>pt(t,n),e.getLiveReactionTopic=e=>`${e.path}/liveReaction`,e.getLiveStreamTopic=It,e.getMarkedMessageTopic=gt,e.getMarkerUserFeedTopic=yt,e.getMessageTopic=e=>e.path,e.getMyFollowersTopic=()=>{const e=tt();return`${ft(e)}/membership/${e._id}/+/+`},e.getMyFollowingsTopic=()=>{const e=tt();return`${ft(e)}/membership/+/${e._id}/+`},e.getNetworkTopic=vt,e.getPostTopic=({path:t},n=e.SubscriptionLevels.POST)=>"comment"===n?`${t}/comment/+`:t,e.getRole=Li,e.getSmartFeedChannelTopic=bt,e.getSmartFeedMessageTopic=Ct,e.getSmartFeedSubChannelTopic=wt,e.getStoryTopic=({targetId:e,targetType:t,storyId:n})=>{const r=tt();return`${ft(r)}/social/${t}/${e}/story/${n}/#`},e.getSubChannelTopic=e=>`${e.path}/#`,e.getUserTopic=mt,e.isAfterBefore=se,e.isAfterBeforeRaw=ie,e.isCachable=fe,e.isFetcher=ue,e.isFresh=me,e.isLocal=e=>fe(e)&&-1===(null==e?void 0:e.cachedAt),e.isMutator=he,e.isOffline=pe,e.isPaged=ce,e.isReportedByMe=async(e,t)=>{const n=Re();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:a,isFlagByMe:o}=null!=r?r:{};return null!==(n=null!=a?a: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:a,isFlagByMe:o}=null!=r?r:{};return null!==(n=null!=a?a: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:a,isFlagByMe:o}=null!=r?r:{};return null!==(n=null!=a?a: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:a,isFlagByMe:o}=null!=r?r:{};return null!==(n=null!=a?a:o)&&void 0!==n&&n})({client:n,referenceId:t})},e.isSkip=oe,e.mergeInCache=xe,e.notificationTray=Gh,e.onChannelMarkerFetched=Mo,e.onFeedMarkerFetched=e=>{const t=Re();return it(t,"feedMarker/onFeedMarkerFetched","local.feedMarker.fetched",(t=>{e(t.feedMarkers[0])}))},e.onFeedMarkerUpdated=e=>{const t=Re();return it(t,"feedMarker/onFeedMarkerUpdated","marker.feed-updated",(t=>{Xt(t),e(t.feedMarkers[0])}))},e.onMessageMarked=qo,e.onMessageMarkerFetched=Do,e.onSubChannelMarkerFetched=jo,e.onSubChannelMarkerUpdated=Uo,e.onUserMarkerFetched=xo,e.onUserMarkerFetchedLegacy=e=>{const t=Re();return it(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers[0])}))},e.pullFromCache=je,e.pushToCache=Ue,e.queryCache=Me,e.queryOptions=ye,e.queryRoles=Bi,e.restoreCache=async(e="amitySdk")=>{var t;const n=Re();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 a={};try{a=JSON.parse(r)}catch(e){}return n.cache.data=Object.assign(Object.assign({},a),n.cache.data),!0},e.runQuery=ve,e.sortByChannelSegment=({channelSegment:e},{channelSegment:t})=>e-t,e.sortByDisplayName=Ve,e.sortByFirstCreated=Je,e.sortByFirstUpdated=Ye,e.sortByLastActivity=Ze,e.sortByLastCreated=Ge,e.sortByLastUpdated=Xe,e.sortByLocalSortingDate=We,e.sortByName=He,e.sortBySegmentNumber=({segmentNumber:e},{segmentNumber:t})=>e-t,e.subscribeTopic=St,e.toPage=de,e.toPageRaw=e=>{if(!e)return;const n=JSON.parse(t.decode(e));return ie(n)?n:void 0},e.toToken=le,e.upsertInCache=De,e.wipeCache=async(e="amitySdk")=>{const{log:t,cache:n,userId:r}=Re();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,AsyncStorage,uuid$1,jwtDecode,reactNative,hash,Hls);
5
+ var r=e("buffer"),a=r.Buffer;function o(e,t){for(var n in e)t[n]=e[n]}function s(e,t,n){return a(e,t,n)}a.from&&a.alloc&&a.allocUnsafe&&a.allocUnsafeSlow?t.exports=r:(o(r,n),n.Buffer=s),s.prototype=Object.create(a.prototype),o(a,s),s.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return a(e,t,n)},s.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=a(e);return void 0!==t?"string"==typeof n?r.fill(t,n):r.fill(t):r.fill(0),r},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return a(e)},s.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(a(t)):null}function a(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,a=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 s(e){var t=o(e);if("string"!=typeof t&&(r.isEncoding===a||!a(e)))throw new Error("Unknown encoding: "+e);return t||e}function i(e){var t;switch(this.encoding=s(e),this.encoding){case"utf16le":this.text=f,this.end=m,t=4;break;case"utf8":this.fillLast=u,t=4;break;case"base64":this.text=g,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 a=c(t[r]);return a>=0?(a>0&&(e.lastNeed=a-1),a):--r<n||-2===a?0:(a=c(t[r]))>=0?(a>0&&(e.lastNeed=a-2),a):--r<n||-2===a?0:(a=c(t[r]))>=0?(a>0&&(2===a?a=0:e.lastNeed=a-3),a):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 m(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 g(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"),a=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 s=/^([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}$/,m=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,g={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&&a.isObject(e)&&e instanceof o)return e;var r=new o;return r.parse(e,t,n),r}function C(e){return a.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(!a.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=s.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!==(R=C.indexOf(h[A]))&&(-1===E||R<E)&&(E=R);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 R;-1!==(R=C.indexOf(u[A]))&&(-1===E||R<E)&&(E=R)}-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 M=this.hostname.split(/\./),j=(A=0,M.length);A<j;A++){var U=M[A];if(U&&!U.match(f)){for(var x="",D=0,q=U.length;D<q;D++)U.charCodeAt(D)>127?x+="x":x+=U[D];if(!x.match(f)){var N=M.slice(0,A),B=M.slice(A+1),L=U.match(m);L&&(N.push(L[1]),B.unshift(L[2])),B.length&&(C="/"+B.join(".")+C),this.hostname=N.join(".");break}}}this.hostname.length>p?this.hostname="":this.hostname=this.hostname.toLowerCase(),P||(this.hostname=r.toASCII(this.hostname));var F=this.port?":"+this.port:"",K=this.hostname||"";this.host=K+F,this.href+=this.host,P&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==C[0]&&(C="/"+C))}if(!g[_])for(A=0,j=d.length;A<j;A++){var $=d[A];if(-1!==C.indexOf($)){var Q=encodeURIComponent($);Q===$&&(Q=escape($)),C=C.split($).join(Q)}}var z=C.indexOf("#");-1!==z&&(this.hash=C.substr(z),C=C.slice(0,z));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){F=this.pathname||"";var H=this.search||"";this.path=F+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,s="";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&&a.isObject(this.query)&&Object.keys(this.query).length&&(s=b.stringify(this.query));var i=this.search||s&&"?"+s||"";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(a.isString(e)){var t=new o;t.parse(e,!1,!0),e=t}for(var n=new o,r=Object.keys(this),s=0;s<r.length;s++){var i=r[s];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 m=n.pathname||"",g=n.search||"";n.path=m+g}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(!a.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,a.isNull(n.pathname)&&a.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,R=""===S[0]||S[0]&&"/"===S[0].charAt(0);return _&&(n.hostname=n.host=R?"":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)&&!R&&S.unshift(""),S.length?n.pathname=S.join("/"):(n.pathname=null,n.path=null),a.isNull(n.pathname)&&a.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 a(){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 a}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!==Nt?Nt:"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),a=t[t.length-1];return"function"==typeof r&&r!==a&&Object.keys(a).forEach((function(e){r[e]=a[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=a;var r=Object.prototype.hasOwnProperty;function a(){for(var e={},t=0;t<arguments.length;t++){var n=arguments[t];for(var a in n)r.call(n,a)&&(e[a]=n[a])}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,a=arguments.length;n<a;n++)t.push(arguments[n]);return t}function a(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 s(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++)s(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,a=this.head;null!==a;)n.push(e.call(t,a.value,this)),a=a.next;return n},r.prototype.mapReverse=function(e,t){t=t||this;for(var n=new r,a=this.tail;null!==a;)n.push(e.call(t,a.value,this)),a=a.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 a=0;null!==r;a++)n=e(n,r.value,a),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 a=this.length-1;null!==r;a--)n=e(n,r.value,a),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 a=0,o=this.head;null!==o&&a<e;a++)o=o.next;for(;null!==o&&a<t;a++,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 a=this.length,o=this.tail;null!==o&&a>t;a--)o=o.prev;for(;null!==o&&a>e;a--,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 s=[];for(r=0;o&&r<t;r++)s.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=a(this,o,n[r]);return s},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 Kt=Bt(Ft.exports);class $t{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 Qt=()=>"undefined"!=typeof window&&window.localStorage?window:{localStorage:new $t},zt=()=>w.default.v4().toString();let Vt=0;if("undefined"!=typeof BroadcastChannel&&"undefined"!=typeof window){const e=zt(),t={},n=new BroadcastChannel("amity_ts_sdk");let r;n.postMessage({type:"startup",tabId:e}),n.onmessage=({data:a})=>{a.tabId!==e&&("startup"===a.type&&n.postMessage({type:"identify",tabId:e,tabIndex:Vt}),"identify"===a.type&&void 0!==a.tabIndex&&a.tabId&&(t[a.tabId]=a.tabIndex,r||(r=setTimeout((()=>{const e=Object.values(t).sort();e&&0!==e.length&&(Vt=e.reduce(((e,t)=>e<t?e:t+1),0))}),15))))}}const Ht=async()=>{var e;const t=`${null!==(e=Re().prefixDeviceIdKey)&&void 0!==e?e:""}#deviceId`,n=await(async e=>{if("undefined"!=typeof navigator&&"ReactNative"===navigator.product)return await b.default.getItem(e);return new Promise((t=>{t(Qt().localStorage.getItem(e))}))})(t);if(n)return n;const r=`ascWebSdk#${zt()}`;return await(async(e,t)=>"undefined"!=typeof navigator&&"ReactNative"===navigator.product?(await b.default.setItem(e,t),!0):new Promise((n=>{Qt().localStorage.setItem(e,t),n(!0)})))(t,r),r},Jt=()=>{const e=(()=>{var e,t;return(null===(e=Ot.versions)||void 0===e?void 0:e.node)?Ot.versions.node:navigator?`${navigator.product.toLowerCase()}#${null!==(t=navigator.userAgent)&&void 0!==t?t:"unknown_agent"}`:"unknown_model"})();return{kind:"web",model:e,sdkVersion:z}},Wt=1e3;var Gt;!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"}(Gt||(Gt={}));const Yt=e=>{let t,n="disconnected";const r=new Set,a=e=>{n!==e&&(n=e,r.forEach((t=>{t(e)})))};return{connect:async function(n){const r=await(async e=>`mqttjs_${await Ht()}_${e}_${Vt}`)(n.userId);return a("connecting"),t&&(a("disconnecting"),t.removeAllListeners(),t.end(!0)),t=Kt.connect(e,function(e){return Object.assign({clean:!1,clientId:`mqttjs_ + ${Math.random().toString(16).substring(2,10)}`,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:Wt,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=Wt,a("connected"),(()=>{const e=[St(vt()),St(bt()),St(wt()),St(Ct()),St(mt(tt())),St(yt()),St(It())]})()})),t.on("error",(e=>{switch(e.code){case 2:case 134:case 135:t.end(),a("disconnected")}})),t.on("reconnect",(()=>{a("reconnecting"),t.options.reconnectPeriod=Math.min(2*(t.options.reconnectPeriod||Wt),8e3)})),t.on("close",(()=>{a("disconnected")})),t.on("disconnect",(()=>{a("disconnected")})),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()))))},reconnect:async()=>new Promise((e=>{null==t||t.reconnect(),e()})),listen:e=>(r.add(e),n&&e(n),()=>{r.delete(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 a;if(t||128===(null===(a=r[0])||void 0===a?void 0:a.qos)){const r=t?new _e(t.message,8e5,"error"):new Oe(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)}}},Xt=(e={},t,n=!0)=>{Object.entries(e).forEach((([e,r])=>{const a=Ie[e];if(!a)return;const o=Ce(a);o&&r.forEach((e=>{(n?Ue:De)([a,"get",o(e)],e,t)}))}))},Zt=(e,t)=>{const{log:n,cache:r}=Re(),a=[e,Z,t],o={cachedAt:Date.now()};r&&(n("cache/api/pushToTombstone",{cacheKey:a,data:o}),qe([e,"get",t],!0),Ue(a,o))};function en(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 a=0;for(r=Object.getOwnPropertySymbols(e);a<r.length;a++)t.indexOf(r[a])<0&&Object.prototype.propertyIsEnumerable.call(e,r[a])&&(n[r[a]]=e[r[a]])}return n}const tn=(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(!Re().cache)return;return(null===(n=je(["user","get",e[t]]))||void 0===n?void 0:n.data)||void 0}},e))(e,t,n))))&&void 0!==r?r:e},nn=(e,t,n="userId",r="user")=>{const a=e,o=t,s=a[o],i=en(a,["symbol"==typeof o?o:o+""]),c=tn(s,n,r);return Object.assign(Object.assign({},i),{[t]:c})};function rn(e){return e.map((e=>{var{isMentioned:t}=e,n=en(e,["isMentioned"]);return Object.assign({hasMentioned:t},n)}))}function an(e){return rn(e)}function on(e){return rn(e)}const sn=e=>{var t,n;return null!==(n=null===(t=je(["messagePreviewChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},cn=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=je(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),ln=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:a,messageFeedId:o,data:s,dataType:i,isDeleted:c,segment:l,creatorPublicId:d,createdAt:u,updatedAt:h}=t;return{channelId:a,subChannelId:o,data:s,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:[]};Xt(r)},dn=e=>{var t,n;return null!==(n=null===(t=je(["messagePreviewSubChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},un=e=>{var t;const n=e.messagePreviewId?dn(e.subChannelId):null,r=n?Object.assign(Object.assign({},n),{user:null===(t=je(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data}):null;return Object.assign(Object.assign({},e),{messagePreview:r})},hn=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:a,messageFeedId:o,messageId:s,creatorPublicId:i,data:c,dataType:l,isDeleted:d,segment:u,createdAt:h,updatedAt:p}=t;return{messagePreviewId:s,channelId:a,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:[]};Xt(r)};function pn(e,t){return Object.create(Object.getPrototypeOf(e),Object.assign(Object.assign({},Object.getOwnPropertyDescriptors(e)),Object.getOwnPropertyDescriptors(t)))}function fn(e,t,n){Ue(["subChannel","get",e],pn(t,n))}const mn=(e,t)=>{const{log:n,cache:r}=Re(),a=[e,Z,t];if(!r)return;n("cache/api/isInTombstone",a);const o=je(a),{lifeSpan:s}=ye("cache_then_server",18e4);if(o&&me(o.data,s))throw new ke("Item not found!",400400,"error")},gn=e=>{var t;const n=["channelUnreadInfo","get",e],r=null===(t=je(n))||void 0===t?void 0:t.data,a=Me(["subChannelUnreadInfo","get"]);let o=0,s=!1;if(a&&(null==a?void 0:a.length)>0){const t=null==a?void 0:a.filter((({data:t})=>t.channelId===e&&!t.isDeleted));o=t.map((({data:e})=>e.unreadCount)).reduce(((e,t)=>e+t),0),s=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:s});return Ue(n,i),i},yn=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,a={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};Xt({subChannelUnreadInfo:[a]}),e.includes(n.entityId)||e.push(n.entityId)}})),e.forEach((e=>{gn(e)}))}},vn=async()=>{const e=Re();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&&Xt({userMarkers:n},{cachedAt:r}),ct("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}},bn=e=>!0===e&&void 0;function wn(e,t,n){var r,a;if(n)return n.hasMentioned;const o=Re();if(o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()){const e=null===(r=je(["subChannelUnreadInfo","get",t]))||void 0===r?void 0:r.data;return!!e&&e.isMentioned}const s={entityId:e,feedId:t,userId:tt()._id},i=null===(a=je(["subChannelMarker","get",Ce("subChannelMarker")(s)]))||void 0===a?void 0:a.data;return!!i&&i.hasMentioned}const Cn=["broadcast","conversation","community"],In=({channelType:e})=>Cn.includes(e);function Sn(e){var{channelId:t,channelPublicId:n,channelType:r,childCount:a,creatorId:o,creatorPublicId:s,lastMessageId:i,lastMessageTimestamp:c,messageFeedId:l,name:d}=e,u=en(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,a;if(n)return n.unreadCount;const o=Re();if(o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()){const e=null===(r=je(["subChannelUnreadInfo","get",t]))||void 0===r?void 0:r.data;return e?e.isDeleted?0:e.unreadCount:0}const s={entityId:e,feedId:t,userId:tt()._id},i=null===(a=je(["subChannelMarker","get",Ce("subChannelMarker")(s)]))||void 0===a?void 0:a.data;return i?i.unreadCount:0}(t,l)},get hasMentioned(){return wn(t,l)},get isMentioned(){return wn(t,l)}},u),{channelId:n,creatorId:s,displayName:d,lastActivity:c,latestMessageId:i,messageCount:a,subChannelId:l,isUnreadCountSupport:In({channelType:r})})}function _n(e,t,n){var r;const a=(e=>{var t,n,r;const a=null===(n=null===(t=Me(["message","get"]))||void 0===t?void 0:t.find((({data:t})=>t.messageId===e.messageId)))||void 0===n?void 0:n.data;return a?Object.assign(Object.assign(Object.assign({},a),e),{referenceId:null!==(r=a.referenceId)&&void 0!==r?r:e.referenceId}):e})(e),{channelPublicId:o,childCount:s,creatorPublicId:i,mentionedUsers:c,messageFeedId:l,myReactions:d,reactionCount:u,reactions:h,referenceId:p,segment:f,messageId:m,creatorId:g}=a,y=en(a,["channelPublicId","childCount","creatorPublicId","mentionedUsers","messageFeedId","myReactions","reactionCount","reactions","referenceId","segment","messageId","creatorId"]);let v;p&&(v=je(["message","get",p])),v||(v=je(["message","get",m]));const b=Object.assign(Object.assign({},y),{messageId:m,channelId:o,channelSegment:f,childrenNumber:s,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:m,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=Re(),a=je(["message","get",e.messageId]),o=(null==a?void 0:a.data.myReactions)||[];Object.assign(e,{myReactions:o});const s=t[0];s&&s.userId===r.userId&&("message.reactionAdded"!==n||o.includes(s.reactionName)||Object.assign(e,{myReactions:[...o,s.reactionName]}),"message.reactionRemoved"===n&&o.includes(s.reactionName)&&Object.assign(e,{myReactions:o.filter((e=>e!==s.reactionName))}))})(b,t,n),b}const kn={},On=async(e,t)=>{const n=e.messages.map((({messageId:e})=>e));if(n.length>0){Xt({messages:(r=e).messages.map((e=>_n(e,r.reactions)))});const t=n.join("");kn[t]&&clearTimeout(kn[t]),kn[t]=setTimeout((()=>{try{(async e=>{const t=Re();t.log("channel/getMessageMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/messages",{params:{messageIds:e}}),{contentMarkers:r,feedMarkers:a,userMarkers:o}=n,s=t.cache&&Date.now();t.cache&&Xt({contentMarkers:r,feedMarkers:a,userMarkers:o},{cachedAt:s}),ct("local.feedMarker.fetched",{feedMarkers:a}),ct("local.messageMarker.fetched",{contentMarkers:r}),ct("local.userMarker.fetched",{userMarkers:o})})(n)}catch(e){}}),2e3)}var r;const{messageFeeds:a}=e,o=en(e,["messageFeeds"]);return a&&a.length>0&&(null==a||a.forEach((e=>{var t,n;const r=null!==(n=null===(t=je(["subChannel","get",e.messageFeedId]))||void 0===t?void 0:t.data)&&void 0!==n?n:{},a=en(Sn(e),["unreadCount","isMentioned"]);fn(e.messageFeedId,r,a)}))),Object.assign(Object.assign({},o),{messages:e.messages.map((n=>_n(n,e.reactions,t)))})};function Tn(e){var{subChannelId:t,mentionees:n,dataType:r,data:a}=e,o=en(e,["subChannelId","mentionees","dataType","data"]);return r===U.IMAGE||r===U.FILE?Object.assign({messageFeedId:t,mentionedUsers:n,dataType:r,data:Object.assign({caption:""},a)},o):Object.assign({messageFeedId:t,mentionedUsers:n,dataType:r,data:a},o)}function En(e){var{sortBy:t,subChannelId:n,includingTags:r,excludingTags:a,includeDeleted:o,aroundMessageId:s,limit:i,type:c}=e,l=en(e,["sortBy","subChannelId","includingTags","excludingTags","includeDeleted","aroundMessageId","limit","type"]);const d=Object.assign(Object.assign({},l),{messageFeedId:n,isDeleted:bn(o),options:{sortBy:t,limit:i||V,around:s}});return r&&(d.includeTags=r),c&&(d.dataType=c),a&&(d.excludeTags=a),d}function An(e){return Object.assign(Object.assign({},e),{isGlobalBanned:(null==e?void 0:e.isGlobalBan)||!1})}const Rn=["broadcast","conversation","community"],Pn=({channelType:e})=>Rn.includes(e),Mn=async e=>{const t=e.messageFeeds.filter(Pn).map((({messageFeedId:e})=>e));if(t.length>0){(e=>{Xt({messageFeeds:e.messageFeeds.map((e=>Sn(e)))})})(e);try{await(async(e,t={limit:100})=>{const n=Re();n.log("channel/getSubChannelMarkers",e,t);const{data:r}=await n.http.get("/api/v1/markers/message-feeds",{params:{messageFeedIds:e,options:{token:le(t,"skiplimit")}}}),{paging:a}=r,o=en(r,["paging"]),{userEntityMarkers:s,userFeedMarkers:i,userMarkers:c,feedMarkers:l}=o;n.isUnreadCountEnabled&&n.getMarkerSyncConsistentMode()&&yn({feedMarkers:l,userFeedMarkers:i});const d=an(s),u=on(i),h=n.cache&&Date.now();n.cache&&Xt({userEntityMarkers:d,userFeedMarkers:u,userMarkers:c},{cachedAt:h}),ct("local.channelMarker.fetched",{userEntityMarkers:d}),ct("local.subChannelMarker.fetched",{userFeedMarkers:u}),ct("local.userMarker.fetched",{userMarkers:c});const p=de(a.next);return{data:u,cachedAt:h,prevPage:de(a.previous),nextPage:p}})(t)}catch(e){}}hn(e);const n=e.messageFeeds.map(Sn),r=e.messages.map((e=>_n(e))),a=e.users.map(An);return Object.assign(Object.assign({},e),{messageFeeds:n,messages:r,users:a})};const jn=async e=>{const t=Re();t.log("channel/getSubChannel",e),mn("subChannel",e);try{const n=await t.http.get(`/api/v5/message-feeds/${encodeURIComponent(e)}`),r=await Mn(n.data),a=t.cache&&Date.now();return t.cache&&Xt(r,{cachedAt:a}),ct("local.message-feed.fetched",r),{data:r.messageFeeds[0],cachedAt:a}}catch(t){throw ae(null==t?void 0:t.code)&&Zt("subChannel",e),t}};jn.locally=e=>{const t=Re();if(t.log("channel/getSubChannel.locally",e),!t.cache)return;const n=je(["subChannel","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Un=e=>new Date(e).getTime(),xn=async e=>{var t;let n=null===(t=je(["subChannel","get",e]))||void 0===t?void 0:t.data;return n||(n=(await jn(e)).data),n},Dn=async e=>{const t=await(async()=>Re().getMessagePreviewSetting(!1))(),{channelId:n,messageId:r,creatorId:a,createdAt:o,updatedAt:s,data:i,dataType:c,subChannelId:l,channelSegment:d,isDeleted:u}=e,h=await xn(l);"no-message-preview"!==t?(e=>{var t;const n=null===(t=je(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;return!n||n.segment<=e.channelSegment||Un(n.createdAt)<=Un(e.createdAt)})(e)&&(Ue(["messagePreviewSubChannel","get",e.subChannelId],{channelId:n,creatorId:a,messagePreviewId:r,createdAt:o,updatedAt:s,subChannelId:l,data:i,dataType:c,segment:d,isDeleted:u,subChannelUpdatedAt:null==h?void 0:h.updatedAt,subChannelName:null==h?void 0:h.displayName}),fn(e.subChannelId,h,{lastActivity:o,messagePreviewId:r})):Un(h.lastActivity)<Un(o)&&fn(e.subChannelId,h,{lastActivity:o})},qn=async e=>{var t;const{channelId:n,messageId:r,creatorId:a,createdAt:o,updatedAt:s,data:i,dataType:c,subChannelId:l,channelSegment:d,isDeleted:u}=e,h=null===(t=je(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await xn(l);Ue(["messagePreviewSubChannel","get",e.subChannelId],{channelId:n,creatorId:a,messagePreviewId:r,createdAt:o,updatedAt:s,subChannelId:l,data:i,dataType:c,segment:d,isDeleted:u,subChannelUpdatedAt:t.updatedAt,subChannelName:h.subChannelName})}},Nn=async e=>{const{channelId:t,messageId:n,creatorId:r,createdAt:a,updatedAt:o,data:s,dataType:i,subChannelId:c,channelSegment:l,isDeleted:d}=e;if((e=>{var t;const n=null===(t=je(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;return!n||Un(n.createdAt)<=Un(e.createdAt)})(e)){const u=await xn(c);Ue(["messagePreviewChannel","get",e.channelId],{channelId:t,creatorId:r,messagePreviewId:n,createdAt:a,updatedAt:o,subChannelId:c,data:s,dataType:i,segment:l,isDeleted:d,subChannelUpdatedAt:null==u?void 0:u.updatedAt,subChannelName:null==u?void 0:u.displayName})}},Bn=async e=>{var t;const{channelId:n,messageId:r,creatorId:a,createdAt:o,updatedAt:s,data:i,dataType:c,subChannelId:l,channelSegment:d,isDeleted:u}=e,h=null===(t=je(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await xn(l);Ue(["messagePreviewChannel","get",e.channelId],{channelId:n,creatorId:a,messagePreviewId:r,createdAt:o,updatedAt:s,subChannelId:l,data:i,dataType:c,segment:d,isDeleted:u,subChannelUpdatedAt:t.updatedAt,subChannelName:h.subChannelName})}},Ln=async e=>{var t,n,r,a;const{channelId:o,subChannelId:s}=e,i=null===(t=je(["messagePreviewChannel","get",o]))||void 0===t?void 0:t.data;if((null==i?void 0:i.subChannelId)===s){const e=null===(n=je(["subChannel","get",s]))||void 0===n?void 0:n.data;Ue(["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=je(["messagePreviewSubChannel","get",s]))||void 0===r?void 0:r.data;if(c&&new Date(c.updatedAt).valueOf()>new Date(e.updatedAt).valueOf()){const e=null===(a=je(["subChannel","get",s]))||void 0===a?void 0:a.data;Ue(["messagePreviewSubChannel","get",s],Object.assign(Object.assign({},c),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}},Fn=["broadcast","conversation","community"],Kn=({type:e})=>Fn.includes(e);function $n(e,t={isMessagePreviewUpdated:!0}){var n;let{messagePreviewId:r}=e;const a=null===(n=je(["messagePreviewChannel","get",e.channelId]))||void 0===n?void 0:n.data;return(null==a?void 0:a.messagePreviewId)&&!t.isMessagePreviewUpdated&&(r=a.messagePreviewId),Object.assign(Object.assign({},e),{defaultSubChannelId:e.channelInternalId,isUnreadCountSupport:Kn(e),messagePreviewId:r})}const Qn=(e,t={isMessagePreviewUpdated:!0})=>{Xt({channels:e.channels.map((e=>$n(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated})))})},zn=async(e,t={isMessagePreviewUpdated:!0})=>{const n=Re(),r=await n.getMessagePreviewSetting(!1);if(t.isMessagePreviewUpdated&&"no-message-preview"!==r&&e.messagePreviews&&e.messagePreviews.length>0&&ln(e),n.useLegacyUnreadCount)(({currentUserId:e,channels:t,channelUsers:n})=>{const r=[];for(let a=0;a<t.length;a+=1){const o=["channelUnread","get",t[a].channelId],s=n.find((n=>n.channelId===t[a].channelId&&n.userId===e));let i=0,c=null,l=null,d=!1;s&&(c=s.readToSegment,l=s.lastMentionedSegment,i=Math.max(t[a].messageCount-c,0),d=l>c);const u={channelId:t[a].channelId,lastSegment:t[a].messageCount,readToSegment:c,lastMentionedSegment:l,unreadCount:i,isMentioned:d,isDeleted:t[a].isDeleted||!1};Ue(o,u),r.push(u)}ct("local.channelUnread.updated",r)})({channels:e.channels,channelUsers:e.channelUsers,currentUserId:n.userId});else{const n=e.channels.filter(Kn).map((({channelInternalId:e})=>e));if(n.length>0){Qn(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated});try{await(async e=>{const t=Re();t.log("channel/getChannelMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/channels",{params:{channelIds:e}}),{userEntityMarkers:r,userMarkers:a}=n,o=an(r),s=t.cache&&Date.now();return t.cache&&Xt({userEntityMarkers:o,userMarkers:a},{cachedAt:s}),ct("local.channelMarker.fetched",{userEntityMarkers:o}),ct("local.userMarker.fetched",{userMarkers:a}),{data:o,cachedAt:s}})(n)}catch(e){}}}const a=e.channels.map((e=>$n(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated}))),o=e.channelUsers.map((e=>{return t=e,Object.assign(Object.assign({},t),{get user(){var e;if(Re().cache)return(null===(e=je(["user","get",t.userId]))||void 0===e?void 0:e.data)||void 0}});var t})),s=e.users.map(An),i=en(e,["messageFeedsInfo","messagePreviews"]);return Object.assign(Object.assign({},i),{users:s,channels:a,channelUsers:o})},Vn=async e=>{const t=Re();t.log("channel/getUserMessageFeedMakers",e);const{data:n}=await t.http.get("/api/v1/markers/user-message-feed",{params:{channelIds:e}});return ct("local.userMessageFeedMarker.fetched",{userMessageFeedMarker:n}),n},Hn=async e=>{const t=Re(),n=await Vn(e.channels.map((({channelInternalId:e})=>e))),{feedMarkers:r,userFeedMarkers:a}=n;yn({feedMarkers:r,userFeedMarkers:a}),t.log("channel/prepareUnreadCountInfo",e.channels)},Jn=(e,t)=>{var n,r,a,o;const s=Re();return s.isUnreadCountEnabled&&s.getMarkerSyncConsistentMode()?null!==(r=null===(n=(e=>{var t;return null===(t=je(["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===(a=(e=>{var t;const n={entityId:e,userId:tt()._id};return null===(t=je(["channelMarker","get",Ce("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===a?void 0:a.hasMentioned)&&void 0!==o&&o},Wn=(e,t)=>{var n,r,a,o,s;const i=Re();return i.isUnreadCountEnabled&&i.getMarkerSyncConsistentMode()?null!==(r=null===(n=(e=>{var t;return null===(t=je(["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!==(s=null!==(a=null==t?void 0:t.unreadCount)&&void 0!==a?a:null===(o=(e=>{var t;const n={entityId:e,userId:tt()._id};return null===(t=je(["channelMarker","get",Ce("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===o?void 0:o.unreadCount)&&void 0!==s?s:0},Gn=e=>{var t;return null===(t=je(["channelUnread","get",e]))||void 0===t?void 0:t.data},Yn=e=>{const t=Re(),n=en(e,["messageCount"]);return pn(n,{get unreadCount(){var e,t;return null!==(t=null===(e=Gn(n.channelId))||void 0===e?void 0:e.unreadCount)&&void 0!==t?t:0},get subChannelsUnreadCount(){return Wn(n)},get isMentioned(){var e,r;return t.useLegacyUnreadCount?null!==(r=null===(e=Gn(n.channelId))||void 0===e?void 0:e.isMentioned)&&void 0!==r&&r:Jn(n)}})},Xn=e=>Object.assign(Object.assign({},e),{get user(){return(()=>{var t;const n=["user","get",e.userId],r=null===(t=je(n))||void 0===t?void 0:t.data;return r?cn(r):void 0})()}}),Zn=e=>{const t=Re();t.log("channel/getMyMembership.locally");const n=je(["channelUsers","get",`${e}#${t.userId}`]);if(!n)throw new ke("Item not found!",400400,"error");return{data:n.data,cachedAt:n.cachedAt}};function er(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(!er(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=>er(e[n],t[n])))}const tr=[];let nr=null;const rr=e=>{if(0===tr.length){const e=Re();nr=it(e,"onChannelCreated","channel.created",(async e=>{const t=await zn(e);Xt(t),tr.forEach((e=>e(t.channels[0])))}))}return tr.push(e),()=>(e=>{const t=tr.indexOf(e);t>-1&&tr.splice(t,1),0===tr.length&&(null==nr||nr())})(e)},ar=[],or=[],sr=e=>{const t=Re();if(0===ar.length){const e=async e=>{const t=await zn(e);Xt(t),ar.forEach((e=>e(t.channels[0])))};or.push(it(t,"onChannelUpdated","channel.updated",e)),or.push(it(t,"onChannelUpdated","local.channel.updated",(e=>ar.forEach((t=>t(e.channels[0]))))))}return ar.push(e),()=>(e=>{const t=ar.indexOf(e);t>-1&&ar.splice(t,1),0===ar.length&&or.forEach((e=>e()))})(e)},ir=e=>{const t=Me(["subChannelUnreadInfo","get"]);if(t){(null==t?void 0:t.filter((({data:t})=>t.channelId===e))).forEach((({key:e,data:t})=>{Ue(e,Object.assign(Object.assign({},t),{isDeleted:!0}))}))}},cr=e=>{var t;const n=["channelUnreadInfo","get",e];(null===(t=je(n))||void 0===t?void 0:t.data)&&qe(n)},lr=[];let dr=null;const ur=e=>{if(0===lr.length){const e=Re(),t=async t=>{const n=await zn(t),r=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,a=e.useLegacyUnreadCount;n.channels.forEach((e=>{if(r)ir(e.channelId),cr(e.channelId);else if(a){const t=["channelUnread","get",e.channelId],n=je(t);n&&Ue(t,Object.assign(Object.assign({},n),{isDeleted:!0}))}})),Xt(n),lr.forEach((e=>e(n.channels[0])))};dr=it(e,"onChannelDeleted","channel.deleted",t)}return lr.push(e),()=>(e=>{const t=lr.indexOf(e);t>-1&&lr.splice(t,1),0===lr.length&&(null==dr||dr())})(e)},hr=[];let pr=null;const fr=e=>{if(0===hr.length){const e=Re();pr=it(e,"onChannelJoined","channel.joined",(async e=>{const t=await zn(e),{channels:n,channelUsers:r}=t;Xt(t),hr.forEach((e=>e(n[0],r[0])))}))}return hr.push(e),()=>(e=>{const t=hr.indexOf(e);t>-1&&hr.splice(t,1),0===hr.length&&(null==pr||pr())})(e)},mr=[];let gr=null;const yr=e=>{if(0===mr.length){const e=Re(),t=async t=>{const{userId:n}=Re(),{channelUsers:r}=t,a=r.some((e=>e.userId===n)),o=await zn(t,{isMessagePreviewUpdated:a}),s=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,i=e.useLegacyUnreadCount;a&&o.channels.forEach((e=>{s?(ir(e.channelId),cr(e.channelId)):i&&qe(["channelUnread","get",e.channelId])}));const{channels:c,channelUsers:l}=o;Xt(o),mr.forEach((e=>e(c[0],l[0])))};gr=it(e,"onChannelLeft","channel.left",t)}return mr.push(e),()=>(e=>{const t=mr.indexOf(e);t>-1&&mr.splice(t,1),0===mr.length&&(null==gr||gr())})(e)},vr=[];let br=null;const wr=e=>{if(0===vr.length){const e=Re(),t=async e=>{var t;De(["channel","get",e.channelId],{isMuted:Date.parse(e.muteTimeout)>Date.now()});const n=null===(t=je(["channel","get",e.channelId]))||void 0===t?void 0:t.data;n&&vr.forEach((e=>e(n)))};br=it(e,"onChannelMute","channel.setMuted",t)}return vr.push(e),()=>(e=>{const t=vr.indexOf(e);t>-1&&vr.splice(t,1),0===vr.length&&(null==br||br())})(e)},Cr=[];let Ir=null;const Sr=e=>{if(0===Cr.length){const e=Re();Ir=it(e,"onChannelMemberAdded","channel.membersAdded",(async e=>{const t=await zn(e),{channels:n,channelUsers:r}=t;Xt(t),Cr.forEach((e=>e(n[0],r.find((e=>"member"===e.membership)))))}))}return Cr.push(e),()=>(e=>{const t=Cr.indexOf(e);t>-1&&Cr.splice(t,1),0===Cr.length&&(null==Ir||Ir())})(e)},_r=[];let kr=null;const Or=e=>{if(0===_r.length){const e=Re();kr=it(e,"onChannelMemberRemoved","channel.membersRemoved",(async e=>{const t=await zn(e),{channels:n,channelUsers:r}=t;Xt(t),_r.forEach((e=>e(n[0],r[0])))}))}return _r.push(e),()=>(e=>{const t=_r.indexOf(e);t>-1&&_r.splice(t,1),0===_r.length&&(null==kr||kr())})(e)},Tr=[];let Er=null;const Ar=e=>{const t=Re();return Er=it(t,"onChannelMemberBanned","channel.banned",(async e=>{const n=await zn(e),{channels:r,channelUsers:a}=n,o=a.some((e=>"banned"===e.membership&&e.userId===t.userId));t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&o&&n.channels.forEach((e=>{ir(e.channelId),cr(e.channelId)})),Xt(n),Tr.forEach((e=>e(r[0],a.find((e=>"banned"===e.membership)))))})),Tr.push(e),()=>(e=>{const t=Tr.indexOf(e);t>-1&&Tr.splice(t,1),0===Tr.length&&(null==Er||Er())})(e)},Rr=[];let Pr=null;const Mr=e=>{if(0===Rr.length){const e=Re();Pr=it(e,"onChannelMemberUnbanned","channel.unbanned",(async e=>{const t=await zn(e),{channels:n,channelUsers:r}=t;Xt(t),Rr.forEach((e=>e(n[0],r.find((e=>"none"===e.membership)))))}))}return Rr.push(e),()=>(e=>{const t=Rr.indexOf(e);t>-1&&Rr.splice(t,1),0===Rr.length&&(null==Pr||Pr())})(e)},jr=[];let Ur=null;const xr=e=>{if(0===jr.length){const e=Re();Ur=it(e,"onChannelMemberRoleAdded","local.channel-moderator.role-added",(async e=>{const{channels:t,channelUsers:n}=e;jr.forEach((e=>e(t[0],n.find((e=>"member"===e.membership)))))}))}return jr.push(e),()=>(e=>{const t=jr.indexOf(e);t>-1&&jr.splice(t,1),0===jr.length&&(null==Ur||Ur())})(e)},Dr=[];let qr=null;const Nr=e=>{if(0===Dr.length){const t=Re();qr=it(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 Dr.push(e),()=>(e=>{const t=Dr.indexOf(e);t>-1&&Dr.splice(t,1),0===Dr.length&&(null==qr||qr())})(e)},Br=[];let Lr=null;const Fr=e=>{if(0===Br.length){const e=Re(),t=async e=>{var t,n;e.userIds.forEach((t=>De(["channelUsers","get",`${e.channelId}#${t}`],{isMuted:Date.parse(e.muteTimeout)>Date.now()})));const r=null===(t=je(["channel","get",e.channelId]))||void 0===t?void 0:t.data,a=null===(n=je(["channelUsers","get",`${e.channelId}#${e.userIds[0]}`]))||void 0===n?void 0:n.data;r&&a&&Br.forEach((e=>e(r,a)))};Lr=it(e,"onChannelUserMute","channel.setMutedUsers",t)}return Br.push(e),()=>(e=>{const t=Br.indexOf(e);t>-1&&Br.splice(t,1),0===Br.length&&(null==Lr||Lr())})(e)},Kr=e=>{var t;let n=[];if(["conversation","community"].includes(e.type)){const r=Me(["channelUsers","get"]);r&&(null==r?void 0:r.length)>0&&(n=(null!==(t=null==r?void 0:r.filter((({data:t})=>t.channelId===e.channelId&&"none"!==t.membership)))&&void 0!==t?t:[]).sort(((e,t)=>e.data.userInternalId.localeCompare(t.data.userInternalId))).slice(0,4).map((({data:e})=>Xn(e))))}return pn(e,{markAsRead:()=>(async e=>{const t=Re();t.log("channel/markAsRead",e);const{data:n}=await t.http.put(`/api/v1/markers/channels/${e}/mark-read`),{userMarkers:r,userEntityMarkers:a,userFeedMarkers:o}=n,s=en(n,["userMarkers","userEntityMarkers","userFeedMarkers"]),i=t.cache&&Date.now(),c=an(a),l=on(o);return t.cache&&Xt(Object.assign({userMarkers:r,userEntityMarkers:c,userFeedMarkers:l},s),{cachedAt:i}),ct("local.channelMarker.updated",{userEntityMarkers:c}),ct("local.subChannelMarker.updated",{userFeedMarkers:l}),!0})(e.channelInternalId),previewMembers:n,myMembership:t=>((e,t)=>{const{_id:n}=tt();if(!n)throw new _e("The _id has not been defined in ActiveUser",8e5,"error");const{log:r,cache:a}=Re();a||console.log("This observable object need the cache data!"),r(`liveMymembership(tmpid: ${Date.now()}) > listen`);const o=[];let s=!1;const i=e=>{t(Object.assign(Object.assign({},e),{data:e.data?Xn(e.data):e.data}))},c=(t,n)=>{const{data:r}=Zn(e);er(void 0,r)||i({loading:!1,data:r})};return o.push(Ar(c)),o.push(Mr(c)),o.push(Fr(c)),(()=>{const t=ge((async()=>Zn(e)));ve(t,(({error:e,data:t,loading:n,origin:r,cachedAt:a})=>{a===G?(i({data:t,origin:r,loading:!1,error:new ke(W,800800,"error")}),s=!0,o.forEach((e=>e()))):s||i({loading:n,data:t,origin:r,error:e}),e&&o.forEach((e=>e()))}))})(),()=>{o.forEach((e=>e()))}})(e.channelId,t)})},$r=e=>Kr(Yn((e=>{var t;const n=e.messagePreviewId?sn(e.channelId):null,r=null===(t=je(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data,a=n?Object.assign(Object.assign({},n),{user:r?cn(r):void 0}):null;return Object.assign(Object.assign({},e),{messagePreview:a})})(e))),Qr=async e=>{const t=Re();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=>{ae(null==t?void 0:t.code)&&Zt("channel",e)})),t}const a=await zn(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await Hn(r);const o=t.cache&&Date.now();return t.cache&&Xt(a,{cachedAt:o}),ct("local.channel.fetched",a.channels),{data:a.channels.map((e=>$r(e))),cachedAt:o}};Qr.locally=e=>{var t,n;const r=Re();if(r.log("channel/getChannelByIds.locally",e),!r.cache)return;const a=null===(t=Me(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!a||(null==a?void 0:a.length)<e.length)return;const o=a.map((({data:e})=>e)),s=null===(n=a.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0];return{data:o.map((e=>$r(e))),cachedAt:s.cachedAt}};class zr{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 Vr;var Hr=()=>(Vr||(Vr=new zr),Vr);const Jr=e=>Hr().onSessionStateChange(e),Wr=(e,t)=>{const n=setInterval(e,t);return()=>clearInterval(n)};let Gr=!1;const Yr={},Xr=async()=>{const e=Object.entries(Yr).filter((([,e])=>e)).map((([e])=>e));return 0!==e.length&&(async e=>{const t=Re();t.log("subChannel/readingAPI",e);const{data:n}=await t.http.post("/api/v1/markers/message-feeds/reading",{messageFeedIds:e}),{userEntityMarkers:r,userFeedMarkers:a,feedMarkers:o,userMarkers:s}=n,i=an(r),c=on(a),l=t.cache&&Date.now();return t.cache&&Xt({userEntityMarkers:i,userFeedMarkers:c,feedMarkers:o,userMarkers:s},{cachedAt:l}),ct("local.feedMarker.fetched",{feedMarkers:o}),ct("local.channelMarker.fetched",{userEntityMarkers:i}),ct("local.subChannelMarker.fetched",{userFeedMarkers:c}),ct("local.userMarker.fetched",{userMarkers:s}),!0})(e)},Zr=()=>{Gr=!1},ea=()=>(Gr=!0,Jr((e=>{"notLoggedIn"===e&&Zr()})),()=>{Zr()});Wr((async()=>{Gr&&await Xr()}),3e4);const ta=async e=>{const t=Re();t.log("channel/getSubChannels",e);const n=await t.http.get("/api/v5/message-feeds/list",{params:{messageFeedIds:e.map(encodeURIComponent)}}),r=await Mn(n.data),a=t.cache&&Date.now();return t.cache&&Xt(r,{cachedAt:a}),ct("local.message-feed.fetched",r),{data:r.messageFeeds,cachedAt:a}};ta.locally=e=>{var t;const n=Re();if(n.log("channel/getSubChannels.locally",e),!n.cache)return;const r=e.map((e=>je(["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 na=async(e=!0)=>{var t;const n=null===(t=je(["MessagePreviewSetting"]))||void 0===t?void 0:t.data;if(!e&&n)return n;const r=await(async()=>{const e=Re(),{data:t}=await e.http.get("/api/v3/network-settings/chat");return t})();var a;return(a=r).messagePreview.enabled?a.messagePreview.isIncludeDeleted?"message-preview-include-deleted":"message-preview-not-include-deleted":"no-message-preview"},ra=async()=>{var e;const t=await na();if(t===(null===(e=je(["MessagePreviewSetting"]))||void 0===e?void 0:e.data))return;Ue(["MessagePreviewSetting"],t);const n=[],r=[];if("no-message-preview"===t){const e=Me(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{qe(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=Me(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{(null==t?void 0:t.isDeleted)&&(qe(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&r.push(t.subChannelId))})),0!==n.length&&await Qr(n),0!==r.length&&await ta(r)}},aa=async()=>{const e=Re(),{data:t}=await e.http.get("/api/v3/network-settings/social");return t.socialNetworkSetting},oa=(e,t)=>{var n;const r=null===(n=je(["user","get",e]))||void 0===n?void 0:n.data;return!!r&&r.permissions.some((e=>e===t))},sa=e=>{const{userId:t}=Re();return{currentUser:()=>oa(t,e),community:n=>((e,t,n)=>{var r;if(!e)return!1;const a=null===(r=je(["communityUsers","get",`${n}#${e}`]))||void 0===r?void 0:r.data;return!!a&&(!!a.permissions.some((e=>e===t))||oa(e,t))})(t,e,n),channel:n=>((e,t,n)=>{var r;if(!e)return!1;const a=null===(r=je(["channelUsers","get",`${n}#${e}`]))||void 0===r?void 0:r.data;return!!a&&(!!a.permissions.some((e=>e===t))||oa(e,t))})(t,e,n)}},ia=async e=>{const t=Re();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},ca=async e=>{const t=Re();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},la=async()=>{const e=Re(),{data:t}=await e.http.get("/api/v3/network-settings/feed-setting");return Object.fromEntries(t.feedSettings.map((({feedType:e,contentSettings:t})=>[e,t])))},da={notLoggedIn:["establishing"],terminated:["establishing"],establishing:["notLoggedIn","established"],established:["notLoggedIn","terminated","tokenExpired","establishing"],tokenExpired:["establishing"]},ua=e=>{const t=Re();t.log("client/api/setSessionState",e);const{sessionState:n}=t;if(n===e)return!1;if(!((e,t)=>da[e].includes(t))(n,e))throw new _e(`Session state cannot change from ${n} to ${e}`,8e5,"error");return t.sessionState=e,Hr().setSessionState(e),!0},ha=async e=>{const t=Re();ua("establishing");const{accessToken:n,users:r,expiresAt:a,issuedAt:o,userType:s}=await(async({params:e,options:t})=>{const n=Re();n.log("client/api/getToken",e);const r=Jt(),{data:a}=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 a})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:a,isGlobalBanned:!1,isUserDeleted:!1},t.upload.defaults.headers.common.Authorization=`Bearer ${n}`,t.upload.defaults.metadata={tokenExpiry:a,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:o,expiresAt:a},ua("established"),{accessToken:n,users:r,userType:s}},pa=async e=>{const t=Re();ua("establishing");const{accessToken:n,users:r,expiresAt:a,issuedAt:o,userType:s}=await(async({params:e,options:t})=>{const n=Re();n.log("client/api/getVisitorToken",e);const r=Jt(),{data:a}=await n.http.post("/api/v5/sessions/visitor",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 a})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:a,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:o,expiresAt:a},ua("established"),{accessToken:n,users:r,userType:s}};function fa(e){return{users:e.users.map(An),files:e.files}}const ma=(e,t)=>{const n=Re();return it(n,e,e,(e=>{const r=fa(e);n.cache&&Xt(r),t(r.users[0])}))},ga=e=>ma("user.deleted",e),ya=["analytic","normal-priority"],va=["analytic","high-priority"],ba=async e=>{const t=Re(),n={activities:e};await t.http.post("/api/v1/analytics/activities",n)};class wa{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=je(ya);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await ba(t),qe(ya)}catch(e){this.stop(),qe(ya)}}async syncHighPriorityCapturedEvent(){try{const e=je(va);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await ba(t),qe(va)}catch(e){this.stop(),qe(va)}}}class Ca{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,a=n?this._recentHighPriorityViewed[e]:this._recentViewed[e];if(!a)return!0;return!(r.getTime()-a.getTime()<t)}markAs({uniqueId:e,contentId:t,contentType:n,activityType:r,metadata:a}){if(!this.isAbleToEnqueue({uniqueId:e,expireTime:this._expireTime}))return;const o=new Date,s={event:[]},i=je(ya);(null==i?void 0:i.data)&&(s.event=i.data.event),s.event.length>=this._poolLimit&&s.event.shift();const c={contentId:t,contentType:n,activityType:r,timestamp:o.toISOString()};a&&(c.metadata=a),s.event.push(c),De(ya,s),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 a={event:[]},o=je(va);if((null==o?void 0:o.data)&&(a.event=o.data.event),a.event.length>=this._poolLimit&&a.event.shift(),a.event.push({contentId:e.storyId,contentType:"story",activityType:t,timestamp:n.toISOString()}),De(va,a),this._recentHighPriorityViewed[e.storyId]=n,"linkClicked"===t)return;Ue(["story-seen","get",e.storyId],(new Date).toISOString());const s=je(["story-last-seen",e.targetId]);(null==s?void 0:s.data)?new Date(s.data).getTime()<new Date(e.expiresAt).getTime()&&Ue(["story-last-seen",e.targetId],e.expiresAt):Ue(["story-last-seen",e.targetId],e.expiresAt),this._bufferNewSeenStoryReferenceIds.push(e.referenceId),this._throttleStoryTimer||(this._throttleStoryTimer=setTimeout((()=>{clearTimeout(this._throttleStoryTimer),ct("local.story.reload",{referenceIds:this._bufferNewSeenStoryReferenceIds}),this._bufferNewSeenStoryReferenceIds=[]}),300))}resetAllBuckets(){this._recentViewed={},this._recentHighPriorityViewed={},qe(ya),qe(va)}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 Ia{constructor(){this._client=Re(),this._eventCapturer=new Ca,this._eventSyncer=new wa}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 Sa;var _a=()=>(Sa||(Sa=new Ia),Sa),ka=()=>{const e=_a();return e.established(),Jr((t=>{"established"===t?e.established():e.handleTokenExpired()})),()=>{e.destroy()}};class Oa{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=Re(),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.getReadReceipts();e&&this.markReadApi(e)}getUnsyncJobs(){var e;const t=null===(e=Me(["readReceipt"]))||void 0===e?void 0:e.filter((({data:e})=>e.latestSyncSegment<e.latestSegment));null==t||t.forEach((({data:e})=>{this.enqueueReadReceipt(e.channelId,e.latestSegment)}))}getReadReceipts(){const e=this.jobQueue.splice(0,this.jobQueue.length);if(0!==e.length)return e.filter((e=>{var t;const n=null===(t=je(["readReceipt",e.channelId]))||void 0===t?void 0:t.data;return!!n&&n.latestSegment>n.latestSyncSegment}))}async markReadApi(e){var t;const n=e.map((e=>({channelId:e.channelId,readToSegment:e.segment})));if(await(async e=>{const t=Re();try{return await t.http.post("api/v3/channels/seen",{channels:e}),!0}catch(e){return!1}})(n))for(let n=0;n<e.length;n+=1){const r=["readReceipt",e[n].channelId],a=null===(t=je(r))||void 0===t?void 0:t.data;Ue(r,Object.assign(Object.assign({},a),{latestSyncSegment:e[n].segment}))}else for(let t=0;t<e.length;t+=1){if(e[t].retryCount>=this.MAX_RETRY)return;const n=Object.assign(Object.assign({},e[t]),{syncState:"create",retryCount:e[t].retryCount+1});this.enqueueJob(n)}}startObservingReadReceiptQueue(){this.client.useLegacyUnreadCount&&(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=["channelUnread","get",e],a=null===(n=je(r))||void 0===n?void 0:n.data;"number"==typeof(null==a?void 0:a.readToSegment)&&a&&t>a.readToSegment&&(a.readToSegment=t,a.unreadCount=Math.max(a.lastSegment-t,0),Ue(r,a),ct("local.channelUnread.updated",[a])),this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const r=null===(n=je(["readReceipt",e]))||void 0===n?void 0:n.data;if(r){if(r.latestSegment<t)Ue(["readReceipt",e],Object.assign(Object.assign({},r),{latestSegment:t}));else if(r.latestSyncSegment>=t)return}else{Ue(["readReceipt",e],{channelId:e,latestSegment:t,latestSyncSegment:0})}let a=this.getSyncJob(e);null===a||"syncing"===a.syncState?(a={channelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(a)):a.segment<t&&(a.segment=t)}getSyncJob(e){const{jobQueue:t}=this;return t.find((t=>t.channelId===e))||null}enqueueJob(e){this.jobQueue.length<this.JOB_QUEUE_SIZE||this.jobQueue.shift(),this.jobQueue.push(e)}}let Ta=null;var Ea=()=>(Ta||(Ta=new Oa),Ta),Aa=()=>{const e=Ea();return e.startSyncReadReceipt(),Jr((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};class Ra{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=Re(),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=Me(["legacyReadReceipt"]))||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=je(["legacyReadReceipt",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:a}=n,o=await(async({subChannelId:e,readToSegment:t})=>{const n=Re();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:a});if(o){this.removeSynedReceipt(e.subChannelId,e.segment);const n=null===(t=je(["legacyReadReceipt",r]))||void 0===t?void 0:t.data;Ue(["legacyReadReceipt",r],Object.assign(Object.assign({},n),{latestSyncSegment:a}))}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],a=null===(n=je(r))||void 0===n?void 0:n.data;if(a&&t>a.readToSegment){a.readToSegment=t,a.unreadCount=Math.max(a.lastSegment-t,0);const e=gn(a.channelId);ct("local.channelUnreadInfo.updated",e),Ue(r,a),ct("local.subChannelUnread.updated",a)}this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const r=null===(n=je(["legacyReadReceipt",e]))||void 0===n?void 0:n.data;if(r){if(r.latestSegment<t)Ue(["legacyReadReceipt",e],Object.assign(Object.assign({},r),{latestSegment:t}));else if(r.latestSyncSegment>=t)return}else{Ue(["legacyReadReceipt",e],{subChannelId:e,latestSegment:t,latestSyncSegment:0})}let a=this.getSyncJob(e);null===a||"syncing"===a.syncState?(a={subChannelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(a)):a.segment<t&&(a.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 Pa=null;var Ma=()=>(Pa||(Pa=new Ra),Pa),ja=()=>{const e=Ma();return e.startSyncReadReceipt(),Jr((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};const Ua=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")},xa=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")},Da=async e=>{const t=Re();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=>{ae(null==t?void 0:t.code)&&Zt("channel",e)})),t}const a=await zn(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await Hn(r);const o=t.cache&&Date.now();return t.cache&&Xt(a,{cachedAt:o}),ct("local.channel.fetched",a.channels),{data:a.channels,cachedAt:o}};Da.locally=e=>{var t,n;const r=Re();if(r.log("channel/getChannelByIds.locally",e),!r.cache)return;const a=null===(t=Me(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!a||(null==a?void 0:a.length)<e.length)return;return{data:a.map((({data:e})=>e)),cachedAt:(null===(n=a.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0]).cachedAt}};class qa{constructor(){this.TIMER_INTERVAL_MS=Y,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(Ua((()=>{this.isConnected=!0}))),this.connectionListener.push(xa((()=>{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=>{var t,n,r;await Da(e);const a=null!==(r=null===(n=null===(t=Me(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.channelPublicId&&e.includes(t.channelPublicId))))||void 0===n?void 0:n.map((({data:e})=>e)))&&void 0!==r?r:[];ct("local.channel.resolved",a)})(e),t.length>0&&(async e=>{const t=await Vn(e),{feedMarkers:n,userFeedMarkers:r}=t;yn({feedMarkers:n,userFeedMarkers:r}),ct("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 Na=null;var Ba=()=>(Na||(Na=new qa),Na),La=()=>{const e=Ba();return e.startResolver(),Jr((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};class Fa{constructor(){this.TIMER_INTERVAL_MS=1e3,this.buffer=[],this.isSyncing=!1,this.connectionListener=[],this.isConnected=!0,this.addConnectionListener()}startReactionsSync(){this.timer||(this.timer=setInterval((()=>{this.isConnected&&this.syncLiveReactions()}),this.TIMER_INTERVAL_MS))}stopReactionsSync(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}createLiveReaction(e){this.buffer.push(e)}addConnectionListener(){this.connectionListener.length>0||(this.connectionListener.push(Ua((()=>{this.isConnected=!0}))),this.connectionListener.push(xa((()=>{this.isConnected=!1}))))}removeConnectionListener(){this.connectionListener.length>0&&(this.connectionListener.forEach((e=>e())),this.connectionListener=[])}syncLiveReactions(){if(this.isSyncing)return;this.isSyncing=!0;const e=this.buffer;this.clearBuffer();const t=e.reduce(((e,t)=>{const{streamId:n}=t,r=en(t,["streamId"]);return e[n]?e[n].push(r):e[n]=[r],e}),{});Object.entries(t).forEach((([e,t])=>{(async({reactions:e,liveStreamId:t})=>{const n=Re();n.log("live_reaction/addReaction",e);const{data:r}=await n.http.post("/api/v1/reactions/live",{liveStreamId:t,reactions:e})})({liveStreamId:e,reactions:t})})),this.isSyncing=!1}clearBuffer(){this.buffer=[]}onSessionEstablished(){this.startReactionsSync(),this.addConnectionListener()}onSessionDestroyed(){this.stopReactionsSync(),this.clearBuffer(),this.isSyncing=!1,this.removeConnectionListener()}onTokenExpired(){this.stopReactionsSync()}}let Ka;var $a=()=>(Ka||(Ka=new Fa),Ka);const Qa=async()=>{var e;const t=Re();return t.log("client/api/disconnectClient"),t.mqtt&&t.mqtt.connected&&t.mqtt.disconnect(),"established"===t.sessionState&&ua("notLoggedIn"),t.emitter.all.clear(),null===(e=t.mqtt)||void 0===e||e.removeAllListeners(),t.userId=void 0,t.token=void 0,t.http.defaults.headers.common.Authorization="",t.http.defaults.metadata={tokenExpiry:"",isGlobalBanned:!1,isUserDeleted:!1},"undefined"!=typeof document&&(document.cookie="_ascSession=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"),"tokenExpired"!==t.sessionState&&t.cache&&(t.cache={data:{}}),!0},za=e=>{const t=Re();ua("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,Qa()},Va=["disconnected","error","connect_error","reconnect_error","reconnect_failed"],Ha=e=>{const t=Re(),n=Va.map((n=>it(t,`client/onConnectionError(${n})`,n,(t=>{const r=(null==t?void 0:t.code)?new _e(t.message,t.code,"fatal"):new Te(n);e(r)}))));return()=>{n.forEach((e=>e()))}},Ja=e=>{const t=Re();return it(t,"client/onConnectionError(user.didGlobalBan)","user.didGlobalBan",e)},Wa=e=>{const t=Re();return it(t,"client/onTokenExpired","tokenExpired",e)},Ga=e=>{const t=Re();return it(t,"client/onTokenTerminated","tokenTerminated",e)},Ya=e=>{const t=Ce("channelMarker")({userId:tt()._id,entityId:e.channelId});qe(["channelMarker","get",t],!0)};let Xa=null;const Za=e=>{Xa=e},eo=({user:e,userType:t})=>{nt(e),Za(t),Ue(["user","get",e.userId],e)};let to=[];const no=async(e,t,n)=>{const r=Re();let a;r.log("client/api/connectClient",Object.assign({apiKey:r.apiKey,sessionState:r.sessionState},e)),r.userId&&r.userId!==e.userId&&(await Qa(),to.forEach((e=>e())),to=[]);const o=await Ht();try{const{users:n,userType:s}=await ha({params:Object.assign(Object.assign({},e),{displayName:null==e?void 0:e.displayName,deviceId:(null==e?void 0:e.deviceId)||o}),options:{setAccessTokenCookie:!0}}),i=n.find((t=>t.userId===e.userId));if(null==i)throw new _e(`${e.userId} has not been founded`,8e5,"error");if(i.isDeleted)return za("userDeleted"),!1;if(i.isGlobalBan)return za("globalBan"),!1;r.userId=i.userId,r.sessionHandler=t,a=r.accessTokenExpiryWatcher(t),eo({user:i,userType:s})}catch(e){throw Hr().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await ut()}(),await ra(),0===to.length&&(to.push(Ja((e=>{za("globalBan"),to.forEach((e=>e())),a()})),Ga((e=>{za(),to.forEach((e=>e())),a()})),ga((e=>{e.userId===r.userId&&(za("userDeleted"),to.forEach((e=>e())),a())})),Wa((e=>{Hr().setSessionState(e),Qa(),to.forEach((e=>e()))})),ur(Ya),Ar(Ya),ea(),ka(),La(),(()=>{const e=$a();return e.startReactionsSync(),Jr((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})()),r.useLegacyUnreadCount?to.push(Aa()):to.push(ja())),!0},ro=[],ao=async e=>{const t=Re();let n;t.log("client/api/connectClient",Object.assign({apiKey:t.apiKey,sessionState:t.sessionState},e));const r=await Ht();let a;try{const{users:o,userType:s}=await pa({params:Object.assign(Object.assign({},e),{deviceId:r}),options:{setAccessTokenCookie:!0}});[a]=o,t.userId=a.userId,t.sessionHandler=e.sessionHandler,n=t.accessTokenExpiryWatcher(e.sessionHandler),eo({user:a,userType:s})}catch(e){throw Hr().setSessionState("notLoggedIn"),e}return await ra(),0===ro.length&&ro.push(Ga((e=>{za(),ro.forEach((e=>e())),n()})),Wa((e=>{Hr().setSessionState(e),Qa(),ro.forEach((e=>e()))}))),!0},oo=()=>{var e;const t=Re();if(!t)throw new _e("Connect client first",8e5,"fatal");const n=null===(e=je(["user","get",t.userId]))||void 0===e?void 0:e.data;if(!n)throw new _e("Connect client first",8e5,"fatal");return cn(n)},so=()=>{let e,t=!1;const n=Re();n.log("initiating access token renewal");const r=async r=>{const{userId:a,displayName:o}=oo(),s={userId:a,displayName:o,authToken:r,deviceId:await Ht()};"tokenExpired"===n.sessionState&&n.sessionHandler?await no(s,n.sessionHandler):await ha({params:s,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(so())}),X)},renewWithAuthSignature:r=>{t?console.log("'renew' method can be called only once per renewal instance"):(async({authSignature:r,authSignatureExpiresAt:a})=>{const o=await Ht();"tokenExpired"===n.sessionState&&n.sessionHandler?await ao({sessionHandler:n.sessionHandler}):await pa({params:{authSignature:r,authSignatureExpiresAt:a,deviceId:o},options:{setAccessTokenCookie:!0}}),t=!0,e&&clearTimeout(e)})(r)},unableToRetrieveAuthSignature:()=>{e=setTimeout((()=>{var e;null===(e=n.sessionHandler)||void 0===e||e.sessionWillRenewAccessToken(so())}),X)}}},io=3e5,co=e=>{const t=setInterval((()=>{const t=Re();if(!t.token)return;const{issuedAt:n,expiresAt:r}=t.token;if((e=>Date.now()>Date.parse(e)-io)(r))return ct("tokenExpired","tokenExpired"),void ot((()=>e.sessionWillRenewAccessToken(so())));(e=>{const{expiresAt:t,issuedAt:n}=e,r=Date.parse(t),a=Date.parse(n),o=Date.now();return o>a+.8*(r-a-io)&&o<r})({expiresAt:r,issuedAt:n})&&e.sessionWillRenewAccessToken(so())}),X);return()=>clearInterval(t)},lo=e=>{if(Re().useLegacyUnreadCount){Ea().markRead(e.channelId,e.channelSegment)}else{Ma().markRead(e.subChannelId,e.channelSegment)}},uo=e=>{const t=Re(),n=tt(),r=[it(t,"message/onMessageCreated","message.created",(async r=>{const a=await On(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&r.messages.forEach((e=>{(e=>{var t;const n=Re(),r=["subChannelUnreadInfo","get",e.messageFeedId],a=null===(t=je(r))||void 0===t?void 0:t.data;if(!a)return;const o=a.lastSegment<e.segment?e.segment:a.lastSegment,s=o-a.readToSegment;let{lastMentionSegment:i}=a;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({},a),{lastMentionSegment:i,lastSegment:o,isMentioned:!(a.readToSegment>=i),unreadCount:Math.max(s,0)});Ue(r,c)})(e),gn(e.channelId)})),t.useLegacyUnreadCount&&r.messages.forEach((e=>{var n,r;const a=null===(n=je(["channelUnread","get",e.channelId]))||void 0===n?void 0:n.data;if(!a||a.lastSegment>=e.segment||"number"!=typeof a.readToSegment||"number"!=typeof a.lastMentionedSegment)return;const o=e.segment,s=(null===(r=e.mentionedUsers)||void 0===r?void 0:r.some((e=>"channel"===e.type||"user"===e.type&&t.userId&&e.userPublicIds.includes(t.userId))))?e.segment:a.lastMentionedSegment,i=Object.assign(Object.assign({},a),{lastSegment:o,unreadCount:Math.max(o-a.readToSegment,0),lastMentionedSegment:s,isMentioned:!(a.readToSegment>=s)});Ue(["channelUnread","get",e.channelId],i),ct("local.channelUnread.updated",[i])})),Xt(a),a.messages.forEach((t=>{t.creatorPrivateId===n._id&&lo(t),e(t)}))}))];return()=>{r.forEach((e=>e()))}},ho=e=>{const t=Re(),n=[it(t,"message/onMessageCreated","local.message.created",(async t=>(Xt(t),t.messages.forEach((t=>{e(t)})))))];return()=>{n.forEach((e=>e()))}},po=e=>{const t=Re();return it(t,"onSubChannelCreated","message-feed.created",(async n=>{const r=await Mn(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&n.messageFeeds.forEach((e=>{(e=>{const{channelId:t,subChannelId:n,createdAt:r,updatedAt:a}=e,o={channelId:t,subChannelId:n,unreadCount:0,readToSegment:0,lastMentionSegment:0,lastSegment:0,isMentioned:!1,isDeleted:!1,createdAt:r,updatedAt:a};Ue(["subChannelUnreadInfo","get",o.subChannelId],o)})({channelId:e.channelId,subChannelId:e.messageFeedId,createdAt:e.createdAt,updatedAt:e.updatedAt})})),Xt(r),e(r.messageFeeds[0])}))},fo=e=>{const t=Re(),n=[it(t,"onSubChannelDeleted","message-feed.deleted",(async n=>{const r=await Mn(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&r.messageFeeds.forEach((e=>{(e=>{var t;const n=["subChannelUnreadInfo","get",e],r=null===(t=je(n))||void 0===t?void 0:t.data;r&&Ue(n,Object.assign(Object.assign({},r),{isDeleted:!0}))})(e.subChannelId),gn(e.channelId)})),Xt(r),e(r.messageFeeds[0])})),it(t,"local.message-feed.deleted","local.message-feed.deleted",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}},mo=async e=>{const t=Re();t.log("channel/markerSync");const{data:n}=await t.http.post("/api/v1/markers/sync",{deviceLastSyncAt:e}),{userEntityMarkers:r,userFeedMarkers:a,feedMarkers:o,userMarkers:s}=n,i=an(r),c=on(a),l=t.cache&&Date.now();return t.cache&&Xt({userEntityMarkers:i,userFeedMarkers:c,feedMarkers:o,userMarkers:s},{cachedAt:l}),ct("local.feedMarker.fetched",{feedMarkers:o}),ct("local.channelMarker.fetched",{userEntityMarkers:i}),ct("local.subChannelMarker.fetched",{userFeedMarkers:c}),ct("local.userMarker.fetched",{userMarkers:s}),{data:n,hasMore:n.feedMarkers.length>0}};let go=!1,yo=[],vo=!1;let bo=null;let wo=[];const Co=e=>{wo=e},Io=async()=>{var e;if(!vo&&0!==wo.length)try{vo=!0,wo=[];const t=await mo((null==bo?new Date:bo).toISOString()),n=t.data.userMarkers.reduce(((e,t)=>null==e||e.getTime()<new Date(t.lastSyncAt).getTime()?new Date(t.lastSyncAt):e),null);null!=(e=n)&&(!bo||e.getTime()>bo.getTime())&&(bo=e),t.hasMore&&wo.push("has_more")}catch(e){}finally{vo&&(vo=!1)}};Wr((async()=>{go&&await Io()}),2e3);const So=()=>true,_o=e=>{var t;const n=Re();if(n.mqtt)return null===(t=n.mqtt)||void 0===t?void 0:t.listen(e)};let ko=[];var Oo;class To{constructor(){Oo.set(this,e.FileAccessTypeEnum.PUBLIC)}setFileAccessType(e){!function(e,t,n,r,a){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!a)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!a:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===r?a.call(e,n):a?a.value=n:t.set(e,n)}(this,Oo,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,Oo,"f")}}let Eo;Oo=new WeakMap;var Ao=()=>(Eo||(Eo=new To),Eo);const Ro=async e=>{const t=Re();ua("establishing");const{accessToken:n,users:r,expiresAt:a,issuedAt:o,userType:s}=await(async({params:e,options:t})=>{const n=Re();n.log("client/api/getBotToken");const r=Jt(),{data:a}=await n.http.post("/api/v5/sessions/bot",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 a})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:a,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:o,expiresAt:a},ua("established"),{accessToken:n,users:r,userType:s}},Po=[],Mo=e=>{const t=Re();return it(t,"channelMarker/onChannelMarkerFetched","local.channelMarker.fetched",(t=>{t.userEntityMarkers.forEach((t=>{e(t)}))}))},jo=e=>{const t=Re();return it(t,"subChannelMarker/onSubChannelMarkerFetched","local.subChannelMarker.fetched",(t=>{t.userFeedMarkers.forEach(e)}))},Uo=e=>{const t=Re();return it(t,"subChannelMarker/onSubChannelMarkerUpdated","local.subChannelMarker.updated",(t=>{e(t.userFeedMarkers)}))},xo=e=>{const t=Re();return it(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers)}))},Do=e=>{const t=Re();return it(t,"messageMarker/onMessageMarkerFetched","local.messageMarker.fetched",(t=>{e(t.contentMarkers[0])}))},qo=e=>{const t=Re();return it(t,"messageMarker/onMessageMarked","marker.marked-message",(t=>{var n,r,a;Xt(t);const o=Me(["message","collection"]),{contentMarkers:s,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==s?void 0:s.length)>0){(null!==(a=null===(r=null===(n=e[0].data)||void 0===n?void 0:n.data)||void 0===r?void 0:r.map((e=>je(["message","get",e]))).map((({data:e})=>e)).filter(Boolean))&&void 0!==a?a:[]).forEach((e=>{var t,n;const r=["messageMarker","get",Ce("messageMarker")({creatorId:e.creatorPrivateId,feedId:e.subChannelId,contentId:e.messageId})],a=null===(t=je(r))||void 0===t?void 0:t.data;if(!a)return;const o=s[0].feedId===a.feedId,i=s[0].readCount>a.readCount,c=(null===(n=s[0])||void 0===n?void 0:n.deliveredCount)>a.deliveredCount;if(o){const e=Object.assign(Object.assign({},a),{readCount:i?s[0].readCount:a.readCount,deliveredCount:c?s[0].deliveredCount:a.deliveredCount});Ue(r,e)}}))}}e(t.contentMarkers[0])}))};function No(e){return"object"==typeof e&&null!==e}const Bo=e=>{if(!No(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)},Lo=e=>{if(!No(e))return e;const t=Object.entries(e).map((([e,t])=>"function"==typeof t?[e,void 0]:[e,t]));return Object.fromEntries(t)};var Fo=Object.freeze({__proto__:null,getActiveClient:Re,getActiveUser:tt,setActiveUser:nt,createClient:(e,t=Et.SG,{debugSession:n="amity",apiEndpoint:r,prefixDeviceIdKey:a,rteEnabled:o=!0}={})=>{var s,i,c;const l=(e=>{const t=`${null==e?void 0:e.trim()}`.length>0&&!Tt,n=g.default(e),r=(e,...r)=>{t&&n(e,r)};return r.__instance__=n,r})(n);l("client/api/createClient",{apiKey:e.replace(/.{5}$/g,"xxxxx"),apiRegion:t});const d=null!==(s=null==r?void 0:r.http)&&void 0!==s?s:Rt("http",t),u=null!==(i=null==r?void 0:r.upload)&&void 0!==i?i:Rt("upload",t),h=null!==(c=null==r?void 0:r.mqtt)&&void 0!==c?c:Rt("mqtt",t),p=qt(d),f=qt(u);let y;o&&(y=Yt(h));const v=m.default(),b={version:`${z}`,apiKey:e,log:l,cache:{data:{}},http:p,ws:undefined,mqtt:y,upload:f,emitter:v,sessionState:"notLoggedIn",accessTokenExpiryWatcher:co,sessionHandler:undefined,hasPermission:sa,validateUrls:ia,validateTexts:ca,getFeedSettings:la,getSocialSettings:aa,getVisitorDeviceId:Ht,getMessagePreviewSetting:na,onRTEConnectionStateChange:_o,use:()=>Pe(b),isUnreadCountEnabled:!1,useLegacyUnreadCount:!0,getMarkerSyncConsistentMode:So,prefixDeviceIdKey:a};try{const t=Re();if(t.apiKey===e)return t;Pe(b)}catch(e){Pe(b)}return b},login:no,logout:Qa,secureLogout:async()=>{const e=Re(),{data:{success:t}}=await e.http.delete("/api/v4/sessions");if(!t)throw new Error("Failed to logout");return await Qa()},resumeSession:async(e,t,n)=>{const r=Re();let a;r.log("client/api/resumeSession",Object.assign({apiKey:r.apiKey,sessionState:r.sessionState},e)),r.userId&&(r.userId===e.userId&&(e=>{var t;const n=Re(),r=C.default(e);return(null===(t=null==r?void 0:r.user)||void 0===t?void 0:t.publicUserId)===n.userId})(e.token.accessToken)?(r.mqtt&&r.mqtt.connected&&r.mqtt.disconnect(),ko.forEach((e=>e())),ko=[]):(await Qa(),ko.forEach((e=>e())),ko=[]));try{const n=await(async({token:e,userId:t})=>{const n=Re();ua("establishing");const{data:{users:r}}=await n.http.get(`/api/v3/users/${t}`,{headers:{Authorization:`Bearer ${e.accessToken}`}}),a=r.find((e=>e.userId===t));return n.http.defaults.headers.common.Authorization=`Bearer ${e.accessToken}`,n.http.defaults.metadata={tokenExpiry:e.expiresAt,isGlobalBanned:!1,isUserDeleted:!1},n.upload.defaults.headers.common.Authorization=`Bearer ${e.accessToken}`,n.upload.defaults.metadata={tokenExpiry:e.expiresAt,isGlobalBanned:!1,isUserDeleted:!1},n.token=e,ua("established"),a})(e);if(null==n)throw new _e(`${e.userId} has not been found`,8e5,"error");if(n.isDeleted)return za("userDeleted"),!1;if(n.isGlobalBanned)return za("globalBan"),!1;r.userId=n.userId,r.sessionHandler=t,a=r.accessTokenExpiryWatcher(t),nt(n)}catch(e){throw Hr().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await ut()}(),await ra(),0===ko.length&&(ko.push(Ja((e=>{za("globalBan"),ko.forEach((e=>e())),a()})),Ga((e=>{za(),ko.forEach((e=>e())),a()})),ga((e=>{e.userId===r.userId&&(za("userDeleted"),ko.forEach((e=>e())),a())})),Wa((e=>{Hr().setSessionState(e),Qa(),ko.forEach((e=>e()))})),ur(Ya),Ar(Ya),ea(),ka(),La()),r.useLegacyUnreadCount?ko.push(Aa()):ko.push(ja())),!0},isConnected:()=>{var e,t;const n=Re();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))},getFeedSettings:la,renewal:so,markerSync:mo,enableUnreadCount:()=>!0,setUploadedFileAccessType:function(e){Ao().setFileAccessType(e)},registerPushNotification:async e=>{const t=Re();let n;if("ios"!==l.Platform.OS&&"android"!==l.Platform.OS)throw new Ee("Unsupported platform");n=l.Platform.OS;const r=await Ht(),{data:{status:a,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 ke(o,5e5,"error");return"success"===a},unregisterPushNotification:async()=>{const e=Re(),t=Ht(),{data:{status:n,error:r}}=await e.http.delete("/v1/notification",{data:{deviceId:t},headers:{"X-API-Key":e.apiKey}});if(r)throw new ke(r,5e5,"error");return"success"===n},onRTEConnectionStateChange:_o,fetchLinkPreview:async e=>{const t=Re();let n=e;/^https?:\/\//i.test(e)||(n=`https://${e}`);const{data:r}=await t.http.get(`/api/v1/link-preview?url=${encodeURIComponent(n)}`);return r},getSocialSettings:aa,getShareableLinkConfiguration:async()=>{const e=Re(),{data:t}=await e.http.get("/api/v3/network-settings/shareable-deep-links");return t},loginAsVisitor:ao,loginAsBot:async e=>{const t=Re();let n;t.log("client/api/connectClient",{apiKey:t.apiKey,sessionState:t.sessionState});const r=await Ht();let a;try{const{users:o,userType:s}=await Ro({params:{deviceId:r},options:{setAccessTokenCookie:!0}});[a]=o,t.userId=a.userId,t.sessionHandler=e.sessionHandler,n=t.accessTokenExpiryWatcher(e.sessionHandler),eo({user:a,userType:s})}catch(e){throw Hr().setSessionState("notLoggedIn"),e}return await ra(),0===Po.length&&Po.push(Ga((e=>{za(),Po.forEach((e=>e())),n()})),Wa((e=>{Hr().setSessionState(e),Qa(),Po.forEach((e=>e()))}))),!0},getCurrentUser:oo,getCurrentUserType:()=>{if(!Xa)throw new _e("Connect client first",8e5,"fatal");return Xa},setCurrentUserType:Za,onConnectionError:Ha,onClientDisconnected:e=>Ha((({code:t})=>{800211===t&&e()})),onClientBanned:Ja,onSessionStateChange:Jr,onNetworkActivities:e=>Ut().onNetworkActivities(e),getUserUnread:e=>{const{_id:t}=tt();if(!t)throw new _e("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:r}=Re();r||console.log("For using Live Object feature you need to enable Cache!");n(`liveUserUnread(tmpid: ${Date.now()}) > listen`);const a=[];let o,s=!1;const i=t=>{const{data:n}=t,r=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;o=r?Bo(r):r,e({data:r?Object.assign(Object.assign({},r),{isMentioned:r.isMentioned}):r,loading:t.loading,error:t.error})};return a.push(xo((e=>(e=>{var n;const r=e.filter((e=>t===e.userId)),a=r.reduce(((e,t)=>null==e||new Date(t.lastSyncAt).getTime()>new Date(e.lastSyncAt).getTime()?t:e),null),s={unreadCount:null!==(n=null==a?void 0:a.unreadCount)&&void 0!==n?n:0,isMentioned:r.some((e=>!!e.isMentioned))};er(o,s)||i({loading:!1,data:s})})(e)))),(()=>{const e=ge(vn);ve(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}):(o===G?(i({data:t,origin:r,loading:!1,error:new ke(W,800800,"error")}),s=!0,a.forEach((e=>e()))):s||i({loading:n,data:t,origin:r,error:e}),e&&a.forEach((e=>e())))}))})(),()=>{a.forEach((e=>e()))}},getMarkerSyncEvents:()=>wo,setMarkerSyncEvents:Co,pushMarkerSyncEvent:e=>wo.push(e),markerSyncTrigger:Io,startMarkerSync:async()=>Promise.resolve(),startUnreadSync:async()=>Promise.resolve(),stopUnreadSync:()=>{go=!1,Co([]),yo.forEach((e=>e())),yo=[]},getMarkerSyncConsistentMode:So});function Ko(e){const{users:t,follows:n}=e,r=en(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n,users:t.map(An)})}function $o(e){const{users:t,follows:n}=e,r=en(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n,users:t.map(An)})}function Qo(e){const{follows:t}=e,n=en(e,["follows"]);return Object.assign(Object.assign({},n),{follows:t})}const zo=(e,t)=>{const n=Re();return it(n,e,e,(e=>{const r=Ko(e);n.cache?(Xt(r),t(r.follows[0])):t(r.follows[0])}))},Vo=(e,t)=>{const n=Re();return it(n,e,e,(e=>{const r=Qo(e);n.cache?(Xt(r),t(r.follows[0])):t(r.follows[0])}))},Ho=e=>zo("follow.created",e),Jo=e=>zo("follow.unfollowed",e),Wo=e=>zo("follow.followerDeleted",e),Go=e=>zo("follow.requested",e),Yo=e=>zo("follow.requestCanceled",e),Xo=e=>zo("follow.accepted",e),Zo=e=>zo("follow.requestDeclined",e),es=async e=>{var t,n;const r=Re();r.log("follow/getFollowInfo",e);const{data:a}=await r.http.get(r.userId===e?"/api/v4/me/followInfo":`/api/v5/users/${e}/followInfo`),o=r.cache&&Date.now(),s="follows"in a?Object.assign(Object.assign({},a.followCounts[0]),{status:null===(n=null===(t=a.follows)||void 0===t?void 0:t[0])||void 0===n?void 0:n.status}):a.followCounts[0];return r.cache&&Ue(["followInfo","get",e],s,{cachedAt:o}),{data:s,cachedAt:o}};es.locally=e=>{const t=Re();if(t.log("follow/getFollowInfo.locally",e),!t.cache)return;const n=je(["followInfo","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const ts=e=>{const t=async t=>{const[{data:n},{data:r}]=await Promise.all([es(t.from),es(t.to)]);e(n),e(r)},n=[zo("follow.created",t),zo("follow.requested",t),zo("follow.accepted",t),zo("follow.unfollowed",t),zo("follow.requestCanceled",t),zo("follow.requestDeclined",t),zo("follow.followerDeleted",t),Vo("local.follow.created",t),Vo("local.follow.requested",t),Vo("local.follow.accepted",t),Vo("local.follow.unfollowed",t),Vo("local.follow.requestDeclined",t)];return()=>{n.forEach((e=>e()))}},ns=e=>Vo("local.follow.created",e),rs=e=>Vo("local.follow.unfollowed",e),as=e=>Vo("local.follow.requested",e),os=e=>Vo("local.follow.accepted",e),ss=e=>Vo("local.follow.requestDeclined",e);class is{constructor(e){const{http:t}=Re();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,a;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 s=await this.getRequest(this.queryParams,o);return"first"===e&&(this.nextToken=null===(t=s.paging)||void 0===t?void 0:t.next,this.previousToken=null===(n=s.paging)||void 0===n?void 0:n.previous),"prev"===e&&(this.previousToken=null===(r=s.paging)||void 0===r?void 0:r.previous),"next"===e&&(this.nextToken=null===(a=s.paging)||void 0===a?void 0:a.next),s}getNextToken(){return this.nextToken}getPrevToken(){return this.previousToken}}class cs extends is{async getRequest(e,t){const{limit:n=V,userId:r}=e,a=en(e,["limit","userId"]),o=t?{token:t}:{limit:n},s=Re().userId===r?"/api/v4/me/followers":`/api/v4/users/${r}/followers`,{data:i}=await this.http.get(s,{params:Object.assign(Object.assign({},a),{options:o,isDeleted:!1})});return i}}class ls{constructor(e,t){this.query=e,this.cacheKey=t}}var ds;!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"}(ds||(ds={}));class us extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.follows.map(Ce("follow"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(Ce("follow"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.to&&r){switch(e){case ds.OnDeclined:case ds.OnCanceled:case ds.OnUnfollowed:case ds.OnDeleted:r.data=r.data.filter((e=>e!==Ce("follow")(t)));break;case ds.OnRequested:case ds.OnAccepted:case ds.OnFollowed:r.data=[...new Set([Ce("follow")(t),...r.data])]}Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class hs{constructor(e){const{http:t}=Re();this.queryParams=e,this.http=t}async onFetch(){return await this.getRequest(this.queryParams)}}class ps{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 hs?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 hs)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 hs)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(Bo).map(Lo);return!er(this.snapshot,t)&&(this.snapshot=t,!0)}getCacheKey(){return this.cacheKey}}function fs(e){return null!=e}const ms=({userId:e})=>t=>{const n=Re();return it(n,"user.deleted","user.deleted",(n=>{const r=fa(n);Xt(r);const a=je(["follow","get",Ce("follow")({from:r.users[0].userId,to:e})]);a&&t(null==a?void 0:a.data)}))};class gs extends ps{constructor(e,t){const n=I.default(Object.assign(Object.assign({},e),{type:"follower"})),r=["follow","collection",n];super(new cs(e),n,r,t),this.query=e,this.queryStreamController=new us(this.query,this.cacheKey,this.notifyChange.bind(this),Ko),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:Ho,action:ds.OnFollowed},{fn:Jo,action:ds.OnUnfollowed},{fn:Xo,action:ds.OnAccepted},{fn:Zo,action:ds.OnDeclined},{fn:Yo,action:ds.OnCanceled},{fn:Wo,action:ds.OnDeleted},{fn:os,action:ds.OnAccepted},{fn:ss,action:ds.OnDeclined},{fn:ns,action:ds.OnFollowed},{fn:rs,action:ds.OnUnfollowed},{fn:ms({userId:this.query.userId}),action:ds.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["follow","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,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=je(["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 ys extends is{async getRequest(e,t){const{limit:n=V,userId:r}=e,a=en(e,["limit","userId"]),o=t?{token:t}:{limit:n},s=Re().userId===r?"/api/v4/me/following":`/api/v4/users/${r}/following`,{data:i}=await this.http.get(s,{params:Object.assign(Object.assign({},a),{options:o,isDeleted:!1})});return i}}class vs extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.follows.map(Ce("follow"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(Ce("follow"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.from&&r){switch(e){case ds.OnDeclined:case ds.OnCanceled:case ds.OnUnfollowed:case ds.OnDeleted:r.data=r.data.filter((e=>e!==Ce("follow")(t)));break;case ds.OnRequested:case ds.OnAccepted:case ds.OnFollowed:r.data=[...new Set([Ce("follow")(t),...r.data])]}Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const bs=({userId:e})=>t=>{const n=Re();return it(n,"user.deleted","user.deleted",(n=>{const r=fa(n);Xt(r);const a=je(["follow","get",Ce("follow")({from:e,to:r.users[0].userId})]);a&&t(null==a?void 0:a.data)}))};class ws extends ps{constructor(e,t){const n=I.default(Object.assign(Object.assign({},e),{type:"following"})),r=["follow","collection",n];super(new ys(e),n,r,t),this.query=e,this.queryStreamController=new vs(this.query,this.cacheKey,this.notifyChange.bind(this),$o),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:Go,action:ds.OnRequested},{fn:Xo,action:ds.OnAccepted},{fn:Zo,action:ds.OnDeclined},{fn:Yo,action:ds.OnCanceled},{fn:Ho,action:ds.OnFollowed},{fn:Jo,action:ds.OnUnfollowed},{fn:Wo,action:ds.OnDeleted},{fn:as,action:ds.OnRequested},{fn:os,action:ds.OnAccepted},{fn:ss,action:ds.OnDeclined},{fn:ns,action:ds.OnFollowed},{fn:rs,action:ds.OnUnfollowed},{fn:bs({userId:this.query.userId}),action:ds.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["follow","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,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=je(["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}}const Cs=(e,t,n,r,a,o)=>{const{forceDispatch:s,callbackDataSelector:i,callbackFilter:c}=Object.assign({forceDispatch:!1,callbackDataSelector:e=>e},o),{cache:l}=Re();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=en(e,["data"]);c&&!c(n,d)||t(Object.assign({data:i(n)},r)),d=Bo(n)};return h.push(...a.map((t=>t((t=>((t,r=!1)=>{e===t[n]&&(d&&!r&&er(d,t)||p({loading:!1,data:t,origin:"event"}))})(t,s)))))),(()=>{const t=ge(r,e,!0);ve(t,(({error:e,data:t,loading:n,origin:r,cachedAt:a})=>{a===G?(p({data:t,origin:r,loading:!1,error:new ke(W,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 Is=Object.freeze({__proto__:null,blockUser:async e=>{const t=Re();t.log("user/blockUser",e);const{data:n}=await t.http.post(`/api/v4/me/user-blocks/${e}`),r=t.cache&&Date.now(),{follows:a,followCounts:o}=n,s={follows:a};t.cache&&(Xt(s,{cachedAt:r}),De(["followInfo","get",e],o[0],{cachedAt:r}));const i=Qo(s);return ct("local.follow.unfollowed",i),n},unBlockUser:async e=>{const t=Re();t.log("user/unBlockUser",e);const{data:n}=await t.http.delete(`/api/v4/me/user-blocks/${e}`),r=t.cache&&Date.now(),{follows:a,followCounts:o}=n,s={follows:a};t.cache&&(Xt(s,{cachedAt:r}),De(["followInfo","get",e],o[0],{cachedAt:r}));const i=Qo(s);return ct("local.follow.created",i),n},follow:async e=>{const t=Re();t.log("follow/follow",e);const{data:n}=await t.http.post(`/api/v4/me/following/${e}`),r=t.cache&&Date.now();t.cache&&Xt(n,{cachedAt:r});const a=Qo(n);return"accepted"===n.follows[0].status?ct("local.follow.created",a):ct("local.follow.requested",a),{data:n.follows[0],cachedAt:r}},unfollow:async e=>{const t=Re();t.log("follow/unfollow",e);const{data:n}=await t.http.delete(`/api/v4/me/following/${e}`);t.cache&&Xt(n);const r=Qo(n);return ct("local.follow.unfollowed",r),!0},acceptMyFollower:async e=>{const t=Re();t.log("follow/acceptMyFollower",e);const{data:n}=await t.http.post(`/api/v4/me/followers/${e}`);t.cache&&Xt(n);const r=Qo(n);return ct("local.follow.accepted",r),!0},declineMyFollower:async e=>{const t=Re();t.log("follow/declineMyFollower",e);const{data:n}=await t.http.delete(`/api/v4/me/followers/${e}`);t.cache&&Xt(n);const r=Qo(n);return ct("local.follow.requestDeclined",r),!0},onUserFollowed:Ho,onUserUnfollowed:Jo,onFollowerDeleted:Wo,onFollowerRequested:Go,onFollowRequestCanceled:Yo,onFollowRequestAccepted:Xo,onFollowRequestDeclined:Zo,onFollowInfoUpdated:ts,onLocalUserFollowed:ns,onLocalUserUnfollowed:rs,onLocalFollowerRequested:as,onLocalFollowRequestAccepted:os,onLocalFollowRequestDeclined:ss,getFollowers:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getFollowers(tmpid: ${o}) > listen`);const s=new gs(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`getFollowers(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getFollowings:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log("For using Live Collection feature you need to enable Cache!");const o=Date.now();r(`getFollowings(tmpid: ${o}) > listen`);const s=new ws(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`getFollowings(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getFollowInfo:(e,t)=>Cs(e,t,"userId",es,[ts],{forceDispatch:!0}),getMyFollowInfo:e=>{const{userId:t}=tt();return Cs(t,e,"userId",es,[ts],{forceDispatch:!0})}});class Ss{constructor(e,t,n){this._syncingStoriesCount=0,this._errorStoriesCount=0,this._targetId=e,this._lastStoryExpiresAt=t,this._lastStorySeenExpiresAt=n,this.cacheStoryExpireTime=je(["story-expire",this._targetId]),this.cacheStoreSeenTime=je(["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=je(["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 je(["story-sync-state",this._targetId]),this.isContainUnSyncedStory?this.localLastStoryExpires>e&&this.localLastStoryExpires>t:this.lastStoryExpiresAt>e&&this.lastStoryExpiresAt>t}getTotalStoryByStatus(){const e=Me(["story","get"]);if(!e)return this._errorStoriesCount=0,void(this._syncingStoriesCount=0);const t=e.reduce(((e,t)=>{const{data:{targetId:n,syncState:r,isDeleted:a}}=t;return n!==this._targetId||a||(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 _s=e=>{const{targetType:t,targetId:n,lastStoryExpiresAt:r,lastStorySeenExpiresAt:a,targetUpdatedAt:o,localFilter:s}=e,i=new Ss(n,r,a);return{targetType:t,targetId:n,lastStoryExpiresAt:r,updatedAt:o,hasUnseen:i.getHasUnseenFlag(),syncingStoriesCount:i.syncingStoriesCount,failedStoriesCount:i.failedStoriesCount,localFilter:s,localLastExpires:i.localLastStoryExpires,localLastSeen:i.localLastStorySeenExpiresAt,localSortingDate:i.getLocalLastSortingDate()}},ks=async e=>{const t=Re();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,a=en(e,["isPublic"]);n=await t.http.post("/api/v3/channels",Object.assign(Object.assign({},a),{isPublic:"community"===(null==e?void 0:e.type)?r:void 0}))}const r=await zn(n.data),a=t.cache&&Date.now();t.cache&&Xt(r,{cachedAt:a});const{channels:o}=r;return{data:$r(o[0]),cachedAt:a}},Os=async e=>{const t=Re();let n;t.log("channel/getChannel",e),mn("channel",e);try{const{data:r}=await t.http.get(`/api/v3/channels/${encodeURIComponent(e)}`);n=await zn(r),t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&Hn(r)}catch(t){throw ae(null==t?void 0:t.code)&&Zt("channel",e),t}const r=t.cache&&Date.now();t.cache&&Xt(n,{cachedAt:r});const{channels:a}=n;return{data:a.find((t=>t.channelId===e)),cachedAt:r}};Os.locally=e=>{var t;const n=Re();if(n.log("channel/getChannel.locally",e),!n.cache)return;const r=null===(t=Me(["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 Ts=Symbol("getWatcherUrls"),Es=e=>Object.assign(Object.assign({},e),{get moderation(){var t;return null===(t=je(["streamModeration","get",e.streamId]))||void 0===t?void 0:t.data},get post(){var t;if("post"===e.referenceType)return null===(t=je(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=je(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;return null===(t=je(["user","get",e.userId]))||void 0===t?void 0:t.data},get childStreams(){return e.childStreamIds&&0!==e.childStreamIds.length?e.childStreamIds.map((e=>{var t;const n=null===(t=je(["stream","get",e]))||void 0===t?void 0:t.data;if(n)return Es(n)})).filter(fs):[]},getLiveChat:()=>(async e=>{var t;const n=Re();if(n.log("stream/getLiveChat",e.streamId),e.channelId){const n=null===(t=je(["channel","get",e.channelId]))||void 0===t?void 0:t.data;if(n)return Kr($r(n));const{data:r}=await Os(e.channelId);return Kr($r(r))}if(e.userId===n.userId){const{data:t}=await ks({type:"live",postId:e.postId,videoStreamId:e.streamId});return xe(["stream","get",e.streamId],{channelId:t.channelId}),t}})(e),isBanned:!e.watcherUrl,watcherUrl:null,get[Ts](){return e.watcherUrl}}),As=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=je(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),Rs=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=je(["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=je(["user","get",e.userId]);if(null==t?void 0:t.data)return cn(t.data)},get childrenComment(){return e.children.map((e=>{const t=je(["comment","get",e]);if(null==t?void 0:t.data)return null==t?void 0:t.data})).filter(fs).map((e=>Rs(e)))}});function Ps(e){return!!(e.data&&"string"!=typeof e.data&&"videoFileId"in e.data&&"thumbnailFileId"in e.data&&"video"===e.dataType)}function Ms(e){return!(!e.data||"string"==typeof e.data||!("streamId"in e.data)||"liveStream"!==e.dataType)}const js=e=>Object.assign(Object.assign({},e),{get moderation(){var t;return null===(t=je(["roomModeration","get",e.roomId]))||void 0===t?void 0:t.data},get post(){var t;if("post"===e.referenceType)return null===(t=je(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=je(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;return null===(t=je(["user","get",e.createdBy]))||void 0===t?void 0:t.data},get childRooms(){return e.childRoomIds&&0!==e.childRoomIds.length?e.childRoomIds.map((e=>{var t;const n=null===(t=je(["room","get",e]))||void 0===t?void 0:t.data;if(n)return js(n)})).filter(fs):[]},getLiveChat:()=>(async e=>{var t;const n=Re();if(n.log("room/getLiveChat",e.roomId),e.liveChannelId){const n=null===(t=je(["channel","get",e.liveChannelId]))||void 0===t?void 0:t.data;if(n)return Kr($r(n));const{data:r}=await Os(e.liveChannelId);return Kr($r(r))}if(e.createdBy===n.userId){const{data:t}=await ks({type:"live",postId:e.referenceId,roomId:e.roomId});return xe(["room","get",e.roomId],{liveChannelId:t.channelId}),t}})(e)}),Us=e=>pn(e,{childrenPosts:e.children.map((e=>{var t;return null===(t=je(["post","get",e]))||void 0===t?void 0:t.data})).filter(fs).map(Us),analytics:{markAsViewed:()=>{_a().markPostAsViewed(e.postId)}},get latestComments(){return e.comments&&e.comments.map((e=>{var t;const n=null===(t=je(["comment","get",e]))||void 0===t?void 0:t.data;return n?Rs(n):null})).filter(Boolean)||[]},get creator(){const t=je(["user","get",e.postedUserId]);if(null==t?void 0:t.data)return cn(t.data)},getImageInfo(){var t,n;return function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"image"!==e.dataType)}(e)?null===(n=je(["file","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.fileId]))||void 0===n?void 0:n.data:void 0},getVideoInfo(){var t,n,r;return Ps(e)?null===(r=je(["file","get",null===(n=null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.videoFileId)||void 0===n?void 0:n.original]))||void 0===r?void 0:r.data:void 0},getVideoThumbnailInfo(){var t,n;return Ps(e)?null===(n=je(["file","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.thumbnailFileId]))||void 0===n?void 0:n.data:void 0},getFileInfo(){var t,n;return function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"file"!==e.dataType)}(e)?null===(n=je(["file","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.fileId]))||void 0===n?void 0:n.data:void 0},getLivestreamInfo(){var t,n;if(!Ms(e))return;const r=null===(n=je(["stream","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.streamId]))||void 0===n?void 0:n.data;return r?Es(r):void 0},getPollInfo(){var t,n;if(!function(e){return!(!e.data||"string"==typeof e.data||!("pollId"in e.data)||"poll"!==e.dataType)}(e))return;const r=null===(n=je(["poll","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.pollId]))||void 0===n?void 0:n.data;return r||void 0},getClipInfo(){var t,n;return function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"clip"!==e.dataType)}(e)?null===(n=je(["file","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.fileId]))||void 0===n?void 0:n.data:void 0},getAudioInfo(){var t,n;return function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"audio"!==e.dataType)}(e)?null===(n=je(["file","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.fileId]))||void 0===n?void 0:n.data:void 0},getRoomInfo(){var t,n;if(!function(e){return!(!e.data||"string"==typeof e.data||!("roomId"in e.data)||"room"!==e.dataType)}(e))return;const r=null===(n=je(["room","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.roomId]))||void 0===n?void 0:n.data;return r?js(r):void 0}}),xs=(e,t)=>{"message"===e?ct("local.message.updated",{messages:[t]}):"post"===e?ct("post.updated",{posts:[t]}):"comment"===e?ct("comment.updated",{comments:[t]}):"story"===e&&ct("story.updated",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[t]})},Ds=async(e,t,n,r)=>{var a,o,s;const i=Re();if(i.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new ke("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:c}=await i.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:r});if(i.cache){const r=je([e,"get",t]);if(!r||(null===(a=r.data.myReactions)||void 0===a?void 0:a.includes(n)))return!0;const l=Object.assign(Object.assign({},r.data),{reactionsCount:r.data.reactionsCount+1,myReactions:[...null!==(o=r.data.myReactions)&&void 0!==o?o:[],n],reactions:Object.assign(Object.assign({},r.data.reactions),{[n]:(null!==(s=r.data.reactions[n])&&void 0!==s?s:0)+1}),updatedAt:(new Date).toISOString()});if("comment"===e)return ct("local.comment.addReaction",{comment:l,reactor:{userId:i.userId,reactionName:n,reactionId:c.addedId}}),!0;if("post"===e)return ct("local.post.addReaction",{post:l,reactor:{userId:i.userId,reactionName:n,reactionId:c.addedId}}),!0;if("story"===e)return ct("local.story.reactionAdded",{story:l,reactor:{userId:i.userId,reactionName:n,reactionId:c.addedId}}),!0}return!0};Ds.optimistically=(e,t,n)=>{var r,a,o,s,i;const c=Re();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const l=je([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!==(a=l.data.myReactions)&&void 0!==a?a:[],n],reactions:Object.assign(Object.assign({},l.data.reactions),{[n]:(null!==(o=l.data.reactions[n])&&void 0!==o?o:0)+1})});return De([e,"get",t],d,{cachedAt:G}),xs(e,d),null!==(i=null===(s=null==d?void 0:d.myReactions)||void 0===s?void 0:s.includes(n))&&void 0!==i&&i};const qs=(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=je(["messageMarker","get",Ce("messageMarker")(r)]))||void 0===n?void 0:n.data})(e))&&void 0!==n?n:{readCount:0,deliveredCount:0}},Ns=(e,t)=>{const n=t.publicId!==t.messageId;return(async(e,t,n,r)=>{var a,o;const s=Re();if(s.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new ke("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:i}=await s.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:r}});if(s.cache){const r=je([e,"get",t]);if(!r)return!0;const c=Object.assign(Object.assign({},r.data),{reactionsCount:Math.max(0,r.data.reactionsCount-1),myReactions:(null!==(a=r.data.myReactions)&&void 0!==a?a:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},r.data.reactions),{[n]:Math.max(0,(null!==(o=r.data.reactions[n])&&void 0!==o?o:0)-1)}),updatedAt:(new Date).toISOString()});if("comment"===e)return ct("local.comment.removeReaction",{comment:c,reactor:{reactionId:i.removedId,reactionName:n,userId:s.userId}}),!0;if("post"===e)return ct("local.post.removeReaction",{post:c,reactor:{reactionId:i.removedId,reactionName:n,userId:s.userId}}),!0;if("story"===e)return ct("local.story.reactionAdded",{story:c,reactor:{userId:s.userId,reactionName:n,reactionId:i.removedId}}),!0}return!0})("message",n?t.publicId:t.messageId,e,n?3:5)};function Bs(e,t){return e.map((e=>{const n=je(["community","get",e.communityId]);if((null==n?void 0:n.data)&&(null==n?void 0:n.data.hasOwnProperty("isJoined")))return Object.assign(Object.assign({},n.data),e);const r=t.some((t=>function(e,t){const{userId:n}=tt();return e.communityId===t.communityId&&t.userId===n}(e,t)&&"none"!==t.communityMembership));return Object.assign(Object.assign({},e),{isJoined:r})}))}const Ls=e=>{var t;return null!==(t=Object.keys(R).find((t=>e.needApprovalOnPostCreation===R[t].needApprovalOnPostCreation&&e.onlyAdminCanPost===R[t].onlyAdminCanPost)))&&void 0!==t?t:P};function Fs({communities:e}){return e.map((e=>{var{needApprovalOnPostCreation:t,onlyAdminCanPost:n}=e,r=en(e,["needApprovalOnPostCreation","onlyAdminCanPost"]);return Object.assign({postSetting:Ls({needApprovalOnPostCreation:t,onlyAdminCanPost:n})},r)}))}const Ks=e=>{const t=Fs({communities:e.communities}),n=e.users.map(An),r=e.communityUsers.map((e=>{const t=n.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),a=Bs(t,r);return Object.assign(Object.assign({},e),{users:e.users.map(An),communities:a,communityUsers:r})},$s=e=>{const t=e.joinRequests.map((e=>Object.assign(Object.assign({},e),{joinRequestId:e._id}))),n=e.users.map(An);return Object.assign(Object.assign({},e),{joinRequests:t,users:n})},Qs=e=>{const t=Fs({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=Bs(t,n);return Object.assign(Object.assign({},e),{communities:r,communityUsers:n})},zs=e=>{const{postSetting:t,storySetting:n}=e,r=en(e,["postSetting","storySetting"]);return Object.assign(Object.assign(Object.assign({},r),t?R[t]:void 0),{allowCommentInStory:"boolean"!=typeof(null==n?void 0:n.enableComment)||n.enableComment})},Vs=e=>{var t=en(e,["searchResult"]);const n=Ks(t);return Object.assign({},n)},Hs=e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=je(["user","get",e.requestorPublicId]))||void 0===t?void 0:t.data;if(n)return cn(n)},cancel:async()=>{await(async e=>{var t;const n=Re();n.log("joinRequest/cancelJoinRequest",e.joinRequestId);const{data:r}=await n.http.delete(`/api/v4/communities/${e.targetId}/join`),a=null===(t=je(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return a&&(De(["joinRequest","get",e.joinRequestId],{status:"cancelled"}),ct("local.joinRequest.deleted",[a])),r.success})(e)},approve:async()=>{await(async e=>{var t;const n=Re();n.log("joinRequest/approveJoinRequest",e.joinRequestId);const{data:r}=await n.http.post(`/api/v4/communities/${e.targetId}/join/approve`,{userId:e.requestorInternalId}),a=null===(t=je(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return a&&(De(["joinRequest","get",e.joinRequestId],{status:"approved"}),ct("local.joinRequest.updated",[a])),r.success})(e)},reject:async()=>{await(async e=>{var t;const n=Re();n.log("joinRequest/rejectJoinRequest",e.joinRequestId);const{data:r}=await n.http.post(`/api/v4/communities/${e.targetId}/join/reject`,{userId:e.requestorInternalId}),a=null===(t=je(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return a&&(De(["joinRequest","get",e.joinRequestId],{status:"rejected"}),ct("local.joinRequest.updated",[a])),r.success})(e)}});class Js extends is{async getRequest(e,t){const{limit:n=20,communityId:r}=e,a=en(e,["limit","communityId"]),o=t?{token:t}:{limit:n},{data:s}=await this.http.get(`/api/v4/communities/${r}/join`,{params:Object.assign(Object.assign({},a),{options:o})});return s}}var Ws;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(Ws||(Ws={}));class Gs extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.joinRequests.map((e=>Ce("joinRequest")({joinRequestId:e._id})))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>Ce("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(e===Ws.OnLocalJoinRequestUpdated){if(!r.data.find((e=>e===t[0].joinRequestId)))return}e===Ws.OnLocalJoinRequestCreated&&(r.data=[...new Set([...t.map((e=>e.joinRequestId)),...r.data])]),e===Ws.OnLocalJoinRequestDeleted&&(r.data=r.data.filter((e=>e!==t[0].joinRequestId))),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Ys=e=>{const t=Re(),n=[it(t,"onJoinRequestCreated","local.joinRequest.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Xs=e=>{const t=Re(),n=[it(t,"onJoinRequestUpdated","local.joinRequest.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Zs=e=>{const t=Re(),n=[it(t,"onJoinRequestDeleted","local.joinRequest.deleted",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class ei extends ps{constructor(e,t){const n=I.default(e),r=["joinRequest","collection",n];super(new Js(e),n,r,t),this.query=e,this.queryStreamController=new Gs(this.query,this.cacheKey,this.notifyChange.bind(this),$s),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){const r=e;this.queryStreamController.appendToQueryStream(r,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Ys,action:Ws.OnLocalJoinRequestCreated},{fn:Xs,action:Ws.OnLocalJoinRequestUpdated},{fn:Zs,action:Ws.OnLocalJoinRequestDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r;const a=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const o=this.applyFilter(a.data.map((e=>je(["joinRequest","get",e]))).filter(fs).map((({data:e})=>e)).map(Hs));(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;this.query.status&&(t=t.filter((e=>e.status===this.query.status)));const n=(()=>"firstCreated"===this.query.sortBy?Je:Ge)();return t=t.sort(n),t}}const ti=e=>Object.assign(Object.assign({},e),{createdById:e.createdBy}),ni=e=>Object.assign(Object.assign({},e),{invitations:e.invitations.map(ti),users:e.users.map(An)}),ri=e=>Object.assign(Object.assign({},e),{users:e.users.map(An),invitations:e.invitations.map(ti)}),ai=e=>Object.assign(Object.assign({},e),{get user(){const t=je(["user","get",e.invitedUserPublicId]);if(null==t?void 0:t.data)return cn(t.data)},get createdBy(){const t=je(["user","get",e.inviterUserPublicId]);if(null==t?void 0:t.data)return cn(t.data)},get target(){if("community"===e.targetType){const t=je(["community","get",e.targetId]);return(null==t?void 0:t.data)?t.data:void 0}},accept:async()=>{await(async e=>{var t;const n=Re();n.log("invitation/acceptInvitation",e);const{data:r}=await n.http.post(`/api/v1/invitations/${e}/accept`),a=null===(t=je(["invitation","get",e]))||void 0===t?void 0:t.data;return a&&(De(["invitation","get",e],{status:"approved"}),ct("local.invitation.updated",[a])),r.success})(e._id)},reject:async()=>{await(async e=>{var t;const n=Re();n.log("invitation/rejectInvitation",e);const{data:r}=await n.http.post(`/api/v1/invitations/${e}/reject`),a=null===(t=je(["invitation","get",e]))||void 0===t?void 0:t.data;return a&&(De(["invitation","get",e],{status:"rejected"}),ct("local.invitation.updated",[a])),r.success})(e._id)}});var oi;!function(e){e.OnLocalInvitationCreated="onLocalInvitationCreated",e.OnLocalInvitationUpdated="onLocalInvitationUpdated",e.OnLocalInvitationDeleted="onLocalInvitationDeleted"}(oi||(oi={}));class si extends is{async getRequest(e,t){const{limit:n=V}=e,r=en(e,["limit"]),a=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/invitations",{params:Object.assign(Object.assign({},r),{options:a})});return o}}class ii extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.invitations.map(Ce("invitation"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(Ce("invitation"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(e===oi.OnLocalInvitationUpdated){if(!r.data.find((e=>e===t[0].invitationId)))return}e===oi.OnLocalInvitationCreated&&(r.data=[...new Set([...t.map((e=>e.invitationId)),...r.data])]),e===oi.OnLocalInvitationDeleted&&(r.data=r.data.filter((e=>e!==t[0].invitationId))),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const ci=e=>{const t=Re(),n=[it(t,"onLocalInvitationCreated","local.invitation.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},li=e=>{const t=Re(),n=[it(t,"onLocalInvitationUpdated","local.invitation.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},di=e=>{const t=Re(),n=[it(t,"onLocalInvitationDeleted","local.invitation.deleted",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class ui extends ps{constructor(e,t){const n=I.default(e),r=["invitation","collection",n];super(new si(e),n,r,t),this.query=e,this.queryStreamController=new ii(this.query,this.cacheKey,this.notifyChange.bind(this),ni),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(this.cacheKey,{data:[],params:this.query})}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:ci,action:oi.OnLocalInvitationCreated},{fn:li,action:oi.OnLocalInvitationUpdated},{fn:di,action:oi.OnLocalInvitationDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["invitation","get",e]))).filter(fs).map((({data:e})=>ai(e))))&&void 0!==a?a:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;this.query.targetId&&(t=t.filter((e=>e.targetId===this.query.targetId))),this.query.statuses&&(t=t.filter((e=>{var t;return null===(t=this.query.statuses)||void 0===t?void 0:t.includes(e.status)}))),this.query.targetType&&(t=t.filter((e=>e.targetType===this.query.targetType))),this.query.type&&(t=t.filter((e=>e.type===this.query.type)));const n=(()=>"firstCreated"===this.query.sortBy?Je:Ge)();return t=t.sort(n),t}}const hi=e=>Object.assign(Object.assign({},e),{get categories(){var t;return(null!==(t=null==e?void 0:e.categoryIds)&&void 0!==t?t:[]).map((e=>{const t=je(["category","get",e]);if(null==t?void 0:t.data)return As(t.data)})).filter((e=>!!e))},createInvitations:async t=>{await(async e=>{const t=Re();t.log("invitation/createInvitations",e);const{data:n}=await t.http.post("/api/v1/invitations",e),r=ni(n),a=t.cache&&Date.now();return t.cache&&Xt(r,{cachedAt:a}),ct("local.invitation.created",r.invitations),{data:r.invitations,cachedAt:a}})({type:"communityMemberInvite",targetType:"community",targetId:e.communityId,userIds:t})},getMemberInvitations:(t,n)=>((e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getInvitations: (tmpid: ${o}) > listen`);const s=new ui(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>{qe(c)})),()=>{r(`getInvitations (tmpid: ${o}) > dispose`),i.forEach((e=>e()))}})(Object.assign(Object.assign({},t),{targetId:e.communityId,targetType:"community",type:"communityMemberInvite"}),n),getInvitation:async()=>{const{data:t}=await(async(e,t)=>{const n=Re();n.log("invitation/getInvitation",e,t);const{data:r}=await n.http.get("/api/v1/invitations/me",{params:{targetType:e,targetId:t}}),a=ri(r),o=n.cache&&Date.now();return n.cache&&Xt(a,{cachedAt:o}),{data:a.invitations[0]?ai(a.invitations[0]):void 0,cachedAt:o}})("community",e.communityId);return t},join:async()=>(async e=>{var t;const n=Re();n.log("community/joinRequest",e);const{data:r}=await n.http.post(`/api/v4/communities/${e}/join`),a=$s(r),o=n.cache&&Date.now();n.cache&&Xt(a,{cachedAt:o});const s="approved"===a.joinRequests[0].status?"success":"pending";if("success"===s&&n.cache){const n=null===(t=je(["community","get",e]))||void 0===t?void 0:t.data;if(n){const t=Object.assign(Object.assign({},n),{isJoined:!0});De(["community","get",e],t)}}return ct("v4.local.community.joined",a.joinRequests),"success"===s?{status:s}:{status:s,request:Hs(a.joinRequests[0])}})(e.communityId),getJoinRequests:(t,n)=>((e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getJoinRequests: (tmpid: ${o}) > listen`);const s=new ei(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>{qe(c)})),()=>{r(`getJoinRequests (tmpid: ${o}) > dispose`),i.forEach((e=>e()))}})(Object.assign(Object.assign({},t),{communityId:e.communityId}),n),getMyJoinRequest:async()=>{const{data:t}=await(async e=>{const t=Re();t.log("community/myJoinRequest",e);const{data:n}=await t.http.get(`/api/v4/communities/${e}/join/me`),r=$s(n),a=t.cache&&Date.now();return t.cache&&Xt(r,{cachedAt:a}),{data:r.joinRequests[0]?Hs(r.joinRequests[0]):void 0,cachedAt:a}})(e.communityId);return t}}),pi={ad:e=>{const t=_a(),{image9_16:n,image1_1:r}=e,a=en(e,["image9_16","image1_1"]);return Object.assign(Object.assign({},a),{analytics:{markAsSeen:n=>{t.markAdAsViewed(e,n)},markLinkAsClicked:n=>{t.markAdAsClicked(e,n)}},get advertiser(){var t,n;const r=null===(t=je(["advertiser","get",e.advertiserId]))||void 0===t?void 0:t.data;if(!r)return;const a=null===(n=je(["file","get",r.avatarFileId]))||void 0===n?void 0:n.data;return Object.assign(Object.assign({},r),{avatar:a})},get image1_1(){const e=je(["file","get",r]);if(e)return e.data||void 0},get image9_16(){const e=je(["file","get",n]);if(e)return e.data||void 0}})},comment:Rs,post:Us,user:cn,category:As,stream:Es,story:e=>{const t=_a(),n=je(["storyTarget","get",e.targetId]),r=je(["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=je(["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:a}=r;return a||void 0},get imageData(){var t,n;if(!(null===(t=e.data)||void 0===t?void 0:t.fileId))return;const r=je(["file","get",null===(n=e.data)||void 0===n?void 0:n.fileId]);if(!r)return;const{data:a}=r;return a?Object.assign(Object.assign({},a),{fileUrl:`${a.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=je(["category","get",e]);return(null==t?void 0:t.data)||void 0})).filter((e=>void 0!==e)):void 0},get creator(){const t=je(["user","get",e.creatorPublicId]);if(null==t?void 0:t.data)return cn(t.data)},get storyTarget(){if(null==n?void 0:n.data)return _s(n.data)},get isSeen(){const t=je(["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,a=new Date(null==n?void 0:n.data.lastStorySeenExpiresAt).getTime()||0,o=new Date(e.expiresAt).getTime();return Math.max(r,a)>=o}})},storyTarget:_s,message:e=>{const t=en(e,["creatorPrivateId"]);return Object.assign(Object.assign({},t),{get readCount(){return qs(e).readCount},get deliveredCount(){return qs(e).deliveredCount},get creator(){var t;return null===(t=je(["user","get",e.creatorId]))||void 0===t?void 0:t.data},markRead:()=>lo(e),addReaction:t=>((e,t)=>{const n=t.publicId!==t.messageId;return Ds("message",n?t.publicId:t.messageId,e,n?3:5)})(t,e),removeReaction:t=>Ns(t,e)})},reactor:e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=je(["user","get",e.userId]))||void 0===t?void 0:t.data;if(n)return cn(n)}}),channel:Kr,pinnedPost:e=>{var t;const n=je(["post","get",e.referenceId]),r=null===(t=Me(["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 Us(n.data)},get target(){const e=je(["pinTarget","get",null==n?void 0:n.data.targetId]);if(null==e?void 0:e.data)return null==e?void 0:e.data}})},notificationTray:e=>Object.assign(Object.assign({},e),{isSeen:e.lastSeenAt>e.lastOccurredAt,isRecent:new Date(e.lastOccurredAt).getTime()>=Date.now()-6048e5,users:e.actors.map((({publicId:e})=>je(["user","get",e]))).filter(fs).map((({data:e})=>e)).map((e=>cn(e)))}),community:hi,invitation:ai,joinRequest:Hs,channelMember:Xn},fi=async e=>{const t=Re();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}}),a=fa(r),o=t.cache&&Date.now();return t.cache&&Xt(a,{cachedAt:o}),ct("user.fetched",r),{data:a.users.map((e=>pi.user(e))),cachedAt:o}};fi.locally=e=>{var t;const n=Re();if(n.log("user/getUsers.locally",e),!n.cache)return;const r=e.map((e=>je(["user","get",e]))).filter(Boolean),a=r.map((({data:e})=>pi.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:a,cachedAt:o.cachedAt}};const mi=e=>ma("user.updated",e),gi=e=>ma("user.flagged",e),yi=e=>ma("user.unflagged",e),vi=e=>ma("user.flagCleared",e),bi=e=>ma("user.fetched",e),wi=async e=>{const t=Re();t.log("user/getUser",e),mn("user",e);try{const{data:n}=await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`),r=t.cache&&Date.now(),a=fa(n);return t.cache&&Xt(a,{cachedAt:r}),ct("user.fetched",n),{data:a.users.find((t=>t.userId===e)),cachedAt:r}}catch(t){throw ae(null==t?void 0:t.code)&&Zt("user",e),t}};wi.locally=e=>{const t=Re();if(t.log("user/getUser.locally",e),!t.cache)return;const n=je(["user","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class Ci extends is{async getRequest(e,t){const{limit:n=V}=e,r=en(e,["limit"]),a=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},r),{options:a,isDeleted:!1})});return o}}class Ii extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.users.map(Ce("user"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Ce("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=je(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],Ue(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Si;!function(e){e.OnUserDeleted="onUserDeleted",e.OnUserUpdated="onUserUpdated",e.OnUserFlagged="onUserFlagged",e.OnUserUnflagged="onUserUnflagged",e.OnUserFlagCleared="onUserFlagCleared"}(Si||(Si={}));class _i extends ps{constructor(e,t){const n=I.default(e),r=["user","collection",n];super(new Ci(e),n,r,t),this.query=e,this.queryStreamController=new Ii(this.query,this.cacheKey,this.notifyChange.bind(this),fa),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:ga,action:Si.OnUserDeleted},{fn:mi,action:Si.OnUserUpdated},{fn:gi,action:Si.OnUserFlagged},{fn:yi,action:Si.OnUserUnflagged},{fn:vi,action:Si.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["user","get",e]))).filter(fs).map((({data:e})=>e)).map(pi.user))&&void 0!==a?a:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;const n=(()=>"firstCreated"===this.query.sortBy?Je:Ge)();return t=t.sort(n),"flagged"===this.query.filter&&(t=t.filter((e=>!!e.hashFlag))),t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}class ki extends is{async getRequest(e,t){const{limit:n=V}=e,r=en(e,["limit"]),a=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v4/me/user-blocks",{params:Object.assign(Object.assign({},r),{options:a,isDeleted:!1})});return o}}class Oi extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.users.map(Ce("user"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Ce("user"))])]}))}}reactor(e){return t=>{var n;if(e===ds.OnFollowed){const e=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data,r=null==e?void 0:e.data.filter((e=>e!==t.userId));Ue(this.cacheKey,Object.assign(Object.assign({},e),{data:r}))}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}function Ti(e){const{users:t,follows:n}=e,r=en(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:An(n)})})),users:t.map(An)})}const Ei=(e,t,n)=>r=>e((e=>{var a;if(!e)return e;const o=[n,"get",`${e[t]}`],s=null===(a=je(o))||void 0===a?void 0:a.data;return s?r(s):void 0}));class Ai extends ps{constructor(e,t){const n=I.default(e),r=["blockedUsers","collection",n];super(new ki(e),n,r,t),this.query=e,this.queryStreamController=new Oi(this.query,this.cacheKey,this.notifyChange.bind(this),Ti),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:ga,action:Si.OnUserDeleted},{fn:Ei(ns,"to","user"),action:ds.OnFollowed},{fn:Ei(Ho,"to","user"),action:ds.OnFollowed}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["user","get",e]))).filter(fs).map((({data:e})=>e)).map(pi.user))&&void 0!==a?a:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,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}}class Ri extends is{async getRequest(e,t){const{limit:n=V,displayName:r}=e,a=en(e,["limit","displayName"]),o=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},a),{keyword:null==r?void 0:r.toLocaleLowerCase(),options:o,isDeleted:!1})});return s}}class Pi extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.users.map(Ce("user"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Ce("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=je(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],Ue(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Mi extends ps{constructor(e,t){var n;const r=I.default(e),a=["user","collection",r];super(new Ri(e),r,a,t),this.query=Object.assign(Object.assign({},e),{filter:null!==(n=e.filter)&&void 0!==n?n:"all"}),this.queryStreamController=new Pi(this.query,this.cacheKey,this.notifyChange.bind(this),fa),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:ga,action:Si.OnUserDeleted},{fn:mi,action:Si.OnUserUpdated},{fn:gi,action:Si.OnUserFlagged},{fn:yi,action:Si.OnUserUnflagged},{fn:vi,action:Si.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["user","get",e]))).filter(fs).map((({data:e})=>e)).map(pi.user))&&void 0!==a?a:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,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 ji=async({viewId:e,viewedType:t,limit:n,token:r})=>{const a=Re(),o={};r?o.token=r:o.limit=n;const s=`/api/v1/analytics/views/${"post"===t?"posts":"stories"}/${e}/users`,i=await a.http.get(s,{params:o});return Xt(i.data),i.data};var Ui;!function(e){e.DEFAULT="default",e.PARTIAL="partial"}(Ui||(Ui={}));var xi=Object.freeze({__proto__:null,Relationship:Is,getUserByIds:fi,updateUser:async(e,t)=>{const n=Re();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})),a=fa(r),o=n.cache&&Date.now();return n.cache&&Xt(a,{cachedAt:o}),ct("user.updated",r),{data:a.users.find((t=>t.userId===e)),cachedAt:o}},flagUser:async e=>{const t=Re();t.log("user/flagUser",e);const{data:n}=await t.http.post(`api/v4/me/flags/${encodeURIComponent(e)}`),r=fa(n);return t.cache&&Xt(r),ct("user.flagged",n),!!r},unflagUser:async e=>{const t=Re();t.log("user/unflag",e);const{data:n}=await t.http.delete(`/api/v4/me/flags/${encodeURIComponent(e)}`),r=fa(n);return t.cache&&Xt(r),ct("user.unflagged",n),!!r},isUserFlaggedByMe:async e=>{const t=Re();t.log("user/isUserFlaggedByMe",e);const{data:{isFlagByMe:n}}=await t.http.get(`/api/v3/users/${e}/isFlagByMe`);return n},onUserUpdated:mi,onUserDeleted:ga,onUserFlagged:gi,onUserUnflagged:yi,onUserFlagCleared:vi,getUser:(e,t)=>Cs(e,(e=>t(Object.assign(Object.assign({},e),{data:e.data?pi.user(e.data):e.data}))),"userId",wi,[bi,mi,ga,gi,yi,vi]),getUsers:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`liveUsers(tmpid: ${o}) > listen`);const s=new _i(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`liveUsers(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getBlockedUsers:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getBlockedUsers(tmpid: ${o}) > listen`);const s=new Ai(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`getBlockedUsers(tmpid: ${o}) > dispose`),i.forEach((e=>e())),qe(c)}},searchUserByDisplayName:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`liveSearchUsers(tmpid: ${o}) > listen`);const s=new Mi(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`liveSearchUsers(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getReachedUsers:(e,t)=>{let n=(e=!1)=>{};const{log:r,cache:a}=Re(),o=["viewedUsers","collection",{viewId:e.viewId,viewedType:e.viewedType}];a||console.log(J);const s=Date.now();r(`getReachUsers(tmpid: ${s}) > listen`);const{limit:i,viewId:c,viewedType:l}=e;return n=(e=!1)=>{var r,a,s;const d=null===(r=je(o))||void 0===r?void 0:r.data,u=null!==(a=null==d?void 0:d.data)&&void 0!==a?a:[];if(!e&&u.length>0&&!(null==d?void 0:d.params.page))return;const h=ge(ji,{viewId:c,viewedType:l,limit:i||10,token:e||null===(s=null==d?void 0:d.params.page)||void 0===s?void 0:s.next});ve(h,(e=>{var r,a,s,i,c;let l=null!==(s=null===(a=null===(r=je(o))||void 0===r?void 0:r.data)||void 0===a?void 0:a.data)&&void 0!==s?s:[];(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||[]};Ue(o,d),(e=>{var r,a;let o=[];(null==e?void 0:e.data)&&(o=e.data.map((e=>je(["user","get",e]))).filter(Boolean).map((e=>null==e?void 0:e.data))||[]),t({onNextPage:n,data:o,hasNextPage:!!(null===(a=null===(r=e.params)||void 0===r?void 0:r.page)||void 0===a?void 0:a.next),loading:e.loading||!1})})(d)}),ye(H,2e3))},n(!0),()=>{r(`getReachUsers(tmpid: ${s}) > dispose`),qe(o)}},get AmityUserSearchMatchType(){return Ui}});const Di=async e=>{const t=Re();t.log("file/getFile",e);const{data:n}=await t.http.get(`/api/v3/files/${e}`),r=t.cache&&Date.now();return t.cache&&Xt({files:[n]},{cachedAt:r}),{data:n,cachedAt:r}};Di.locally=e=>{const t=Re();if(t.log("file/getFile.locally",e),!t.cache)return;const n=je(["file","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const qi=async(e,t,n)=>{const r=Re();r.log("file/uploadVideo",e);const a=e.getAll("files");if(!a.length)throw new Error("The formData object must have a `files` key.");const o=Ao().getFileAccessType();e.append("accessType",o),e.append("preferredFilename",a[0].name),t&&e.append("feedType",t);const s="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await r.upload.post("/api/v4/videos",e,{headers:s,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),c=r.cache&&Date.now();return r.cache&&Xt({files:i},{cachedAt:c}),{data:i,cachedAt:c}},Ni=async(e,t,n)=>{const r=Re();r.log("file/uploadImage",e);const a=e.getAll("files");if(null==a?void 0:a.length)console.warn("Deprecation Warning: `files` is deprecated, please use `file` instead."),e.append("preferredFilename",a[0].name);else{const t=e.get("file");if(!t)throw new Error("The formData object must have a `file` or `files` key");e.append("preferredFilename",t.name),n&&e.append("altText",n)}const o=Ao().getFileAccessType();e.append("accessType",o);const s="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await r.upload.post("/api/v4/images",e,{headers:s,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),c=r.cache&&Date.now();return r.cache&&Xt({files:i},{cachedAt:c}),{data:i,cachedAt:c}};var Bi=Object.freeze({__proto__:null,getFile:Di,uploadFile:async(e,t)=>{const n=Re();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 a=Ao().getFileAccessType();e.append("accessType",a),e.append("preferredFilename",r[0].name);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:s}=await n.upload.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&&Xt({files:s},{cachedAt:i}),{data:s,cachedAt:i}},deleteFile:async e=>{const t=Re();return t.log("file/deleteFile",e),await t.http.delete(`/api/v3/files/${e}`),qe(["file","get",e],!0),{success:!0}},fileUrlWithSize:(e,t)=>`${e}?size=${t}`,uploadVideo:qi,uploadImage:Ni,updateAltText:async(e,t)=>{const n=Re();n.log("file/updateAltText",t);const{data:r}=await n.http.put(`/api/v3/files/${e}`,{altText:t}),a=n.cache&&Date.now();return n.cache&&Xt({files:[r]},{cachedAt:a}),!0},uploadClip:async(e,t,n)=>{const r=Re();r.log("file/uploadClip",e);const a=e.get("files");if(!a)throw new Error("The formData object must have a `files` key.");const o=Ao().getFileAccessType();e.append("accessType",o),e.append("preferredFilename",a.name),t&&e.append("feedType",t);const s="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await r.upload.post("/api/v4/clips",e,{headers:s,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),c=r.cache&&Date.now();return r.cache&&Xt({files:i},{cachedAt:c}),{data:i,cachedAt:c}},uploadAudio:async(e,t)=>{const n=Re();n.log("file/uploadAudio",e);const r=e.get("file");if(!r)throw new Error("The formData object must have a `file` key with audio file.");const a=Ao().getFileAccessType();e.append("accessType",a),e.append("preferredFilename",r.name);const{data:o}=await n.upload.post("/api/v4/audios",e,{headers:{"content-type":"multipart/form-data"},onUploadProgress({loaded:e,total:n=100}){null==t||t(Math.round(100*e/n))}}),s=n.cache&&Date.now();return n.cache&&Xt({files:o},{cachedAt:s}),{data:o,cachedAt:s}}});const Li=async e=>{const t=Re();t.log("role/queryRoles",e);const n=null!=e?e:{},{limit:r=10,queryToken:a,displayName:o,sortBy:s}=n,i=en(n,["limit","queryToken","displayName","sortBy"]),c=a?{token:a}:r?{limit:r}:void 0,{data:l}=await t.http.get("/api/v3/roles",{params:Object.assign(Object.assign({},i),{keyword:o,sortBy:s,options:c})}),{paging:d}=l,u=en(l,["paging"]),{roles:h}=u,p=t.cache&&Date.now();t.cache&&Xt(u,{cachedAt:p});const f=de(d.next);return{data:h,cachedAt:p,prevPage:de(d.previous),nextPage:f,paging:d}};Li.locally=e=>{Re().log("role/queryRoles.locally",e)};const Fi=async e=>{const t=Re();t.log("role/getRole",e);const{data:n}=await t.http.get(`/api/v3/roles/${e}`),r=t.cache&&Date.now();return t.cache&&Xt({roles:n},{cachedAt:r}),{data:n.find((t=>t.roleId===e)),cachedAt:r}};Fi.locally=e=>{const t=Re();if(t.log("role/getRole.locally",e),!t.cache)return;const n=je(["role","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Ki=async(e,t=!1)=>{const n=Re();let r;n.log("message/getMessage",e),mn("message",e);try{const{data:t}=await n.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);r=await On(t)}catch(t){throw ae(null==t?void 0:t.code)&&Zt("message",e),t}const a=n.cache&&Date.now();n.cache&&Xt(r,{cachedAt:a});const{messages:o}=r;return ct("local.message.fetched",{messages:o}),{data:o.find((t=>t.messageId===e)),cachedAt:a}};Ki.locally=e=>{const t=Re();if(t.log("message/getMessage.locally",e),!t.cache)return;const n=je(["message","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const $i=async e=>{const t=Re();let n;t.log("post/getPost",e),mn("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw ae(null==t?void 0:t.code)&&Zt("post",e),t}const r=nn(n,"communityUsers"),a=t.cache&&Date.now();t.cache&&Xt(r,{cachedAt:a});const{posts:o}=r;return{data:o.find((t=>t.postId===e)),cachedAt:a}};$i.locally=e=>{const t=Re();if(t.log("post/getPost.locally",e),!t.cache)return;const n=je(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Qi=async e=>{const t=Re();let n;t.log("comment/getComment",e),mn("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw ae(null==t?void 0:t.code)&&Zt("comment",e),t}const r=t.cache&&Date.now();t.cache&&Xt(n,{cachedAt:r});const{comments:a}=n;return{data:pi.comment(a.find((t=>t.commentId===e))),cachedAt:r}};Qi.locally=e=>{const t=Re();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=je(["comment","get",e]);return n?{data:pi.comment(n.data),cachedAt:n.cachedAt}:void 0};const zi=(e,t)=>{var n,r;let a,o;if("post"===t)o="post",a=e.posts[0].postId;else if("comment"===t)o="comment",a=e.comments[0].commentId;else{if("story"!==t)throw new Error("Unknown event type");o="story",a=e.stories[0].referenceId}return(null===(r=null===(n=je([o,"get",a]))||void 0===n?void 0:n.data)||void 0===r?void 0:r.myReactions)||[]},Vi=(e,t,n)=>{const[r]=e[t];return Object.assign(Object.assign({},e),{[t]:[Object.assign(Object.assign({},r),{myReactions:n})]})},Hi=(e,t,n,r=[])=>{const a=e.split(".")[1];let o=r;if(Re().userId===t)if(["addReaction","reactionAdded"].includes(a))o.includes(n)||o.push(n);else{if(!["removeReaction","reactionRemoved"].includes(a))throw new Error(`Unknown event type: ${a}`);o=o.filter((e=>e!==n))}return o},Ji=(e,t)=>{const n=e.split(".")[0],r=zi(t,n),a=Hi(e,t.reactor.userId,t.reactor.reactionName,r);return Vi(t,`${n}s`,a)},Wi=(e,t)=>{var n,r;const a=e.split(".")[0];let o=zi(t,a);(null==t?void 0:t.reactions)&&t.reactions.length>0&&(o=Hi(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 s=Vi(t,"stories",o);if(!(null==t?void 0:t.communities)||!(null==t?void 0:t.communityUsers))return s;const i=Bs(t.communities,t.communityUsers);return Object.assign(Object.assign({},s),{communities:i})},Gi=async(e,t,n)=>{var r,a,o;const s=Re();if(s.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new ke("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:i}=await s.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0});if(s.cache){const c=je([e,"get",t]);if(!c||(null===(r=c.data.myReactions)||void 0===r?void 0:r.includes(n)))return!0;const l=Object.assign(Object.assign({},c.data),{reactionsCount:c.data.reactionsCount+1,myReactions:[...null!==(a=c.data.myReactions)&&void 0!==a?a:[],n],reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:(null!==(o=c.data.reactions[n])&&void 0!==o?o:0)+1}),updatedAt:(new Date).toISOString()});if("comment"===e)return ct("local.comment.addReaction",{comment:l,reactor:{userId:s.userId,reactionName:n,reactionId:i.addedId}}),!0;if("post"===e)return ct("local.post.addReaction",{post:l,reactor:{userId:s.userId,reactionName:n,reactionId:i.addedId}}),!0;if("story"===e)return ct("local.story.reactionAdded",{story:l,reactor:{userId:s.userId,reactionName:n,reactionId:i.addedId}}),!0}return!0};Gi.optimistically=(e,t,n)=>{var r,a,o,s,i;const c=Re();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const l=je([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!==(a=l.data.myReactions)&&void 0!==a?a:[],n],reactions:Object.assign(Object.assign({},l.data.reactions),{[n]:(null!==(o=l.data.reactions[n])&&void 0!==o?o:0)+1})});return De([e,"get",t],d,{cachedAt:G}),xs(e,d),null!==(i=null===(s=null==d?void 0:d.myReactions)||void 0===s?void 0:s.includes(n))&&void 0!==i&&i};const Yi=async(e,t,n)=>{var r,a;const o=Re();if(o.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new ke("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:s}=await o.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0}});if(o.cache){const i=je([e,"get",t]);if(!i)return!0;const c=Object.assign(Object.assign({},i.data),{reactionsCount:Math.max(0,i.data.reactionsCount-1),myReactions:(null!==(r=i.data.myReactions)&&void 0!==r?r:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},i.data.reactions),{[n]:Math.max(0,(null!==(a=i.data.reactions[n])&&void 0!==a?a:0)-1)}),updatedAt:(new Date).toISOString()});if("comment"===e)return ct("local.comment.removeReaction",{comment:c,reactor:{reactionId:s.removedId,reactionName:n,userId:o.userId}}),!0;if("post"===e)return ct("local.post.removeReaction",{post:c,reactor:{reactionId:s.removedId,reactionName:n,userId:o.userId}}),!0;if("story"===e)return ct("local.story.reactionAdded",{story:c,reactor:{userId:o.userId,reactionName:n,reactionId:s.removedId}}),!0}return!0};Yi.optimistically=(e,t,n)=>{var r,a,o,s;const i=Re();if(i.log("reaction/removeReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!i.cache)return;const c=je([e,"get",t]);if(!(null==c?void 0:c.data)||!(null===(r=c.data.myReactions)||void 0===r?void 0:r.includes(n)))return;const l=Object.assign(Object.assign({},c.data),{reactionsCount:Math.max(0,c.data.reactionsCount-1),myReactions:(null!==(a=c.data.myReactions)&&void 0!==a?a:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:Math.max(0,(null!==(o=c.data.reactions[n])&&void 0!==o?o:0)-1)})});return De([e,"get",t],l,{cachedAt:G}),xs(e,l),!(null===(s=null==l?void 0:l.myReactions)||void 0===s?void 0:s.includes(n))};const Xi=e=>{const{posts:t,postChildren:n,videoStreamings:r}=e,a=en(e,["posts","postChildren","videoStreamings"]),o=Fs({communities:a.communities}),s=a.communityUsers.map((e=>{const t=a.users.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),i=Bs(o,s);let c=[];const l=t.map((t=>{var n,o;const s=null===(n=a.feeds.find((e=>e.feedId===t.feedId)))||void 0===n?void 0:n.feedType,i=e.postChildren.filter((e=>e.parentPostId===t.postId));var l,d,u;return i.length>0&&Ms(i[0])&&(l=r,d=null===(o=i[0].data)||void 0===o?void 0:o.streamId,u=t.postId,c=d?l.map((e=>e.streamId===d?Object.assign(Object.assign({},e),{referenceType:"post",referenceId:u,postId:u}):e)):l),Object.assign(Object.assign({},t),{childPosts:i,feedType:s})}));return Object.assign(Object.assign({},a),{postChildren:n,videoStreamings:c,posts:l,communities:i,communityUsers:s})},Zi=e=>{var{searchResult:t,polls:n}=e,r=en(e,["searchResult","polls"]);const a=Xi(r);return Object.assign(Object.assign({},a),{polls:n})},ec=e=>{var t;const n=e.posts[0];if(n.parentId){const e=null===(t=je(["post","get",n.parentPostId]))||void 0===t?void 0:t.data;if(!e)return;Ue(["post","get",e.postId],Object.assign(Object.assign({},e),{children:e.children.filter((e=>e!==n.postId))}))}else n.children.forEach((e=>xe(["post","get",e],{isDeleted:!0})))},tc=(e,t)=>{const n=Re();return it(n,e,e,(r=>{var a;if(n.cache){const o=Xi(r),{communities:s}=o;if(Xt(o,void 0,!1),(null==s?void 0:s[0])&&!["post.updated"].includes(e)&&ct("community.updated",{communities:s,categories:[],communityUsers:o.communityUsers,feeds:[],files:[],users:[]}),"post.deleted"===e){const{postId:e,postedUserId:a}=r.posts[0];ec(r);try{mn("post",e)}catch(e){return}return a!==n.userId&&qe(["post","get",e]),t(r.posts[0])}const i=je(["post","get",r.posts[0].postId]);if(["post.created","post.approved","post.declined"].includes(e)){let t=null===(a=Me(["post","query"]))||void 0===a?void 0:a.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})=>De(e,t,{cachedAt:-1})))}"post.created"===e&&(e=>{var t;const n=e.posts[0];if(!n.parentId)return;const r=null===(t=je(["post","get",n.parentPostId]))||void 0===t?void 0:t.data;r&&Ue(["post","get",r.postId],Object.assign(Object.assign({},r),{children:[...new Set([n.postId,...r.children])]}))})(r),t(i.data)}else t(r.posts[0])}))},nc=(e,t)=>{const n=Re();return it(n,e,e,(r=>{if(n.cache){const n=Xi(r),{communities:a}=n;Xt(n),(null==a?void 0:a[0])&&!["local.post.updated"].includes(e)&&ct("community.updated",{communities:a,categories:[],communityUsers:n.communityUsers,feeds:[],files:[],users:[]});const o=je(["post","get",r.posts[0].postId]);"local.post.deleted"===e&&ec(r),t(o.data)}else t(r.posts[0])}))},rc=e=>tc("post.created",e),ac=e=>tc("post.updated",e),oc=e=>tc("post.deleted",e),sc=e=>tc("post.approved",e),ic=e=>tc("post.declined",e),cc=e=>tc("post.flagged",e),lc=e=>tc("post.unflagged",e),dc=e=>{const t=Re();return it(t,"post.addReaction","post.addReaction",(n=>{if(t.cache){const t=en(Ji("post.addReaction",n),["reactor"]);Xt(t);const r=je(["post","get",n.posts[0].postId]);e(r.data)}else e(n.posts[0])}))},uc=e=>{const t=Re();return it(t,"post.removeReaction","post.removeReaction",(n=>{if(t.cache){const t=en(Ji("post.removeReaction",n),["reactor"]);Xt(t);const r=je(["post","get",n.posts[0].postId]);e(r.data)}else e(n.posts[0])}))},hc=(e,t)=>{const n=Re();return it(n,e,e,(r=>{var a;if(n.cache){const o=["comment.flagged","comment.unflagged"].includes(e)?(e=>{const t=zi(e,"comment");return Vi(e,"comments",t)})(r):r;Xt(o,void 0,!1);const{comments:s}=o;if(s.length>0){const r=je(["comment","get",s[0].commentId]);if(["comment.created"].includes(e)){if("comment.created"===e&&r.data.userId===n.userId)return;if(s[0].parentId){const e=je(["comment","get",s[0].parentId]);(null==e?void 0:e.data)&&(e.data.children.includes(s[0].commentId)||Ue(["comment","get",s[0].parentId],Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,s[0].commentId])]})))}}if(["comment.deleted"].includes(e)){if("comment.deleted"===e&&r.data.userId===n.userId)return;if(s[0].parentId){const e=je(["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.filter((e=>e!==s[0].commentId))])]});Ue(["comment","get",s[0].parentId],t)}}const t=null===(a=Me(["comment","query"]))||void 0===a?void 0:a.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})=>De(e,t,{cachedAt:-1})))}t(pi.comment(r.data))}}else t(pi.comment(r.comments[0]))}))},pc=(e,t)=>{const n=Re();return it(n,e,e,(r=>{var a,o;if(n.cache){const n=r;Xt(n);const{comments:s}=n;if(s.length>0){const n=je(["comment","get",s[0].commentId]);if(["local.comment.created"].includes(e)){if(s[0].parentId){const e=je(["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])]});Ue(["comment","get",s[0].parentId],t),setTimeout((()=>{ct("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}const e=null===(a=Me(["comment","query"]))||void 0===a?void 0:a.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})=>De(e,t,{cachedAt:-1})))}if(["local.comment.deleted"].includes(e)){if(s[0].parentId){const e=je(["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.filter((e=>e!==s[0].commentId))])]});Ue(["comment","get",s[0].parentId],t),setTimeout((()=>{ct("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}const e=null===(o=Me(["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})=>De(e,t,{cachedAt:-1})))}t(pi.comment(n.data))}}else t(pi.comment(r.comments[0]))}))},fc=e=>hc("comment.created",e),mc=e=>hc("comment.updated",e),gc=e=>hc("comment.deleted",e),yc=e=>hc("comment.flagged",e),vc=e=>hc("comment.unflagged",e),bc=e=>{const t=Re();return it(t,"comment.addReaction","comment.addReaction",(n=>{if(t.cache){const t=en(Ji("comment.addReaction",n),["reactor"]);Xt(t);const r=je(["comment","get",n.comments[0].commentId]);e(pi.comment(r.data))}else e(pi.comment(n.comments[0]))}))},wc=e=>{const t=Re();return it(t,"comment.removeReaction","comment.removeReaction",(n=>{if(t.cache){const t=en(Ji("comment.removeReaction",n),["reactor"]);Xt(t);const r=je(["comment","get",n.comments[0].commentId]);e(pi.comment(r.data))}else e(pi.comment(n.comments[0]))}))},Cc=(e,t,n)=>{const r=Re(),a=(r,a,o)=>{r===e&&a===t&&n(o)};if("message"===e){return it(r,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await On(e);t.reactions[0]&&(Xt(t),Xt({reactors:t.reactions}),a("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return it(r,"post.addReaction","post.addReaction",(e=>{const{reactor:t}=e,n=en(e,["reactor"]);Xt(n),Xt({reactions:[t]}),a("post",e.posts[0].postId,t)}))}if("story"===e){return it(r,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=en(e,["reactions"]);Xt(n),Xt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&a("story",e.stories[0].storyId,e.reactions[0])}))}return it(r,"comment.addReaction","comment.addReaction",(e=>{const{reactor:t}=e,n=en(e,["reactor"]);Xt(n),Xt({reactions:[t]}),a("comment",e.comments[0].commentId,t)}))},Ic=(e,t,n)=>{const r=Re(),a=(r,a,o)=>{r===e&&a===t&&n(o)};if("message"===e){return it(r,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await On(e);t.reactions[0]&&(Xt(t),a("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return it(r,"post.removeReaction","post.removeReaction",(e=>{const{reactor:t}=e,n=en(e,["reactor"]);Xt(n),Xt({reactions:[t]}),a("post",e.posts[0].postId,t)}))}if("story"===e){return it(r,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=en(e,["reactions"]);Xt(n),Xt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&a("story",e.stories[0].storyId,e.reactions[0])}))}return it(r,"comment.removeReaction","comment.removeReaction",(e=>{const{reactor:t}=e,n=en(e,["reactor"]);Xt(n),Xt({reactions:[t]}),a("comment",e.comments[0].commentId,t)}))};class Sc extends is{async getRequest(e,t){const{limit:n=V,referenceType:r}=e,a=en(e,["limit","referenceType"]),o=t?{token:t}:{limit:n};Re().log("reaction/queryReactions",e);if(!["post","comment","story","message"].includes(r))throw new ke("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:s}=await this.http.get("/api/v3/reactions",{params:Object.assign(Object.assign({},a),{referenceType:r,referenceVersion:"message"===r?5:void 0,options:o})});return s}}class _c extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){var t;const n=await this.preparePayload(e),r=Re(),a=r.cache&&Date.now();if(r.cache){const{reactions:e}=n,r=en(n,["reactions"]);Xt(Object.assign(Object.assign({},r),{reactions:e,reactors:null===(t=e[0])||void 0===t?void 0:t.reactors}),{cachedAt:a})}}appendToQueryStream(e,t,n=!1){var r,a,o,s;const i=null!==(a=null===(r=e.reactions[0])||void 0===r?void 0:r.reactors)&&void 0!==a?a:[];if(n)Ue(this.cacheKey,{data:i.map(Ce("reactor"))});else{const e=null===(o=je(this.cacheKey))||void 0===o?void 0:o.data,t=null!==(s=null==e?void 0:e.data)&&void 0!==s?s:[];Ue(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...i.map(Ce("reactor"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=je(this.cacheKey))||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))),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class kc extends ps{constructor(e,t){const n=I.default(e),r=["reaction","collection",n];super(new Sc(e),n,r,t),this.query=e,this.queryStreamController=new _c(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:e=>Cc(this.query.referenceType,this.query.referenceId,e),action:"onAdded"},{fn:e=>Ic(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const r=Re(),a=(r,a,o)=>{r===e&&a===t&&n(o)};if("message"===e)return it(r,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await On(e);t.reactions[0]&&(Xt(t),a("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return it(r,"local.post.removeReaction","local.post.removeReaction",(e=>{a("post",e.post.postId,e.reactor)}));if("story"===e)return it(r,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=en(e,["reactions"]);Xt(n),Xt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&a("story",e.stories[0].storyId,e.reactions[0])}));return it(r,"local.comment.removeReaction","local.comment.removeReaction",(e=>{a("comment",e.comment.commentId,e.reactor)}))})(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const r=Re(),a=(r,a,o)=>{r===e&&a===t&&n(o)};if("message"===e)return it(r,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await On(e);t.reactions[0]&&(Xt(t),Xt({reactors:t.reactions}),a("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return it(r,"local.post.addReaction","local.post.addReaction",(e=>{a("post",e.post.postId,e.reactor)}));if("story"===e)return it(r,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=en(e,["reactions"]);Xt(n),Xt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&a("story",e.stories[0].storyId,e.reactions[0])}));return it(r,"local.comment.addReaction","local.comment.addReaction",(e=>{a("comment",e.comment.commentId,e.reactor)}))})(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=null!==(a=o.data.map((e=>je(["reactor","get",e]))).filter(Boolean).map((({data:e})=>pi.reactor(e))))&&void 0!==a?a:[];(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var Oc=Object.freeze({__proto__:null,addReaction:Gi,removeReaction:Yi,onReactionAdded:(e,t,n)=>{const r=r=>{Ce(e)(r)===t&&n(r)};if("message"===e){const e=Re(),t=async e=>{var t;const n=await On(e),a=je(["message","get",n.messages[0].messageId]),o=(null===(t=null==a?void 0:a.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Xt(n),o&&r(n.messages[0])};return it(e,"reaction/onReactionAdded","message.updated",t)}return"post"===e?dc(r):bc(r)},onReactionRemoved:(e,t,n)=>{const r=r=>{Ce(e)(r)===t&&n(r)};if("message"===e){const e=Re(),t=async e=>{var t;const n=await On(e),a=je(["message","get",n.messages[0].messageId]),o=(null===(t=null==a?void 0:a.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Xt(n),o&&r(n.messages[0])};return it(e,"reaction/onReactionRemoved","message.updated",t)}return"post"===e?uc(r):wc(r)},onReactorAdded:Cc,onReactorRemoved:Ic,getReactions:(e,t,n)=>{const{log:r,cache:a}=Re(),o=Date.now();r(`getReactions(tmpid: ${o}) > listen`);const s=new kc(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>{qe(c)})),()=>{r(`getReactions(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}}});function Tc(e){const{comments:t}=e;return Object.assign(Object.assign({},e),{comments:t.map((e=>e.hasOwnProperty("myReactions")?e:Object.assign({myReactions:[]},e)))})}const Ec=e=>{const t=Re(),n=[it(t,"onMessageUpdated","message.updated",(async t=>{const n=await On(t);Xt(n),e(n.messages[0])})),it(t,"onMessageUpdated","local.message.updated",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},Ac=e=>{const t=Re(),n=[it(t,"message/onMessageDeleted","message.deleted",(async t=>{const n=await On(t);Xt(n),e(n.messages[0])})),it(t,"message/onMessageDeleted","local.message.deleted",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},Rc=e=>{const t=Re(),n=[it(t,"onSubChannelUpdated","message-feed.updated",(async t=>{const n=await Mn(t);Xt(n),e(n.messageFeeds[0])})),it(t,"onSubChannelUpdated","local.message-feed.updated",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}};function Pc(e,t){Ue(["channel","get",e.channelId],pn(e,t))}const Mc=e=>{const t=Re();return it(t,"channelMarker/onChannelMarkerUpdated","local.channelMarker.updated",(t=>{e(t.userEntityMarkers[0])}))},jc=async(e,t=!1)=>{const n=Re(),r=await jn(e);await n.http.delete(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{params:{permanent:t}});const a=Object.assign(Object.assign({},r.data),{isDeleted:!0,updatedAt:Se(r.data.updatedAt)});return t?setTimeout((()=>{Zt("subChannel",e)}),0):De(["subChannel","get",e],a),ct("local.message-feed.deleted",{messageFeeds:[a]}),a},Uc=e=>it(Re(),"onSubChannelFetched","local.message-feed.fetched",(t=>e(t.messageFeeds[0]))),xc=()=>`LOCAL_${zt()}`;let Dc;const qc=async(e,t)=>{const n=Re();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)}`,Tn(t)),a=await On(r),o=n.cache&&Date.now();n.cache&&Xt(a,{cachedAt:o});const{messages:s}=a;return ct("local.message.updated",{messages:s}),{data:pi.message(s.find((t=>t.messageId===e))),cachedAt:o}};qc.optimistically=(e,t)=>{const n=Re();if(n.log("message/updateMessage.optimistically",t),!n.cache)return;const r=je(["message","get",e]);if(!r)return;const a=Object.assign(Object.assign(Object.assign({},r.data),t),{updatedAt:(new Date).toISOString()});return De(["message","get",e],a,{cachedAt:-1}),ct("local.message.updated",{messages:[a]}),{data:pi.message(a),cachedAt:-1}};const Nc=async(e,t)=>{const n=Re();n.log("message/editMessage",t);const{data:r}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,Tn(t)),a=await On(r),o=n.cache&&Date.now();n.cache&&Xt(a,{cachedAt:o});const{messages:s}=a;return ct("local.message.updated",{messages:s}),{data:pi.message(s.find((t=>t.messageId===e))),cachedAt:o}};Nc.optimistically=(e,t)=>{const n=Re();if(n.log("message/editMessage.optimistically",t),!n.cache)return;const r=je(["message","get",e]);if(!r)return;const a=Object.assign(Object.assign(Object.assign({},r.data),t),{updatedAt:(new Date).toISOString()});return De(["message","get",e],a,{cachedAt:-1}),ct("local.message.updated",{messages:[a]}),{data:pi.message(a),cachedAt:-1}};const Bc=async e=>{var t;const n=Re();if(n.log("message/deleteMessage",e),e.includes("LOCAL_")){const n=null===(t=je(["message","get",e]))||void 0===t?void 0:t.data;if(!n)throw Error("messageId not found");const r=Object.assign(Object.assign({},n),{isDeleted:!0});return ct("local.message.deleted",{messages:[r]}),pi.message(r)}const{data:r}=await n.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`),a=await On(r);return ct("local.message.deleted",{messages:[a.messages[0]]}),pi.message(a.messages[0])};Bc.optimistically=e=>{Re().log("message/deleteMessage.optimistically",e);const t=je(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return De(["message","get",e],n,{cachedAt:-1}),ct("local.message.deleted",{messages:[n]}),{data:pi.message(n),cachedAt:-1}};const Lc=async e=>{const t=Re();t.log("message/softDeleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const n=await Ki(e);return ct("local.message.deleted",{messages:[n.data]}),pi.message(n.data)};Lc.optimistically=e=>{Re().log("message/softDeleteMessage.optimistically",e);const t=je(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return De(["message","get",e],n,{cachedAt:-1}),ct("local.message.deleted",{messages:[n]}),{data:pi.message(n),cachedAt:-1}};const Fc=async e=>{const t=Re();t.log("user/getReadUsers",e);const{page:n,messageId:r}=e,a=en(e,["page","messageId"]),{data:o}=await t.http.get(`/api/v1/markers/messages/${r}/read-users`,{params:Object.assign(Object.assign({},a),{options:{token:le(n,"afterbeforeraw")}})}),{paging:s,publicUserIds:i,userFeedMarkers:c}=o,l=en(o,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Xt(Object.assign(Object.assign({},l),{userFeedMarkers:on(c)}),{cachedAt:d});const e=["read-user","query",Object.assign(Object.assign({messageId:r},a),{options:Object.assign({},n)})];Ue(e,{users:i,paging:s})}let u=[];i.length>0&&({data:u}=await fi(i));return{data:u,cachedAt:d,prevPage:de(s.previous),nextPage:de(s.next)}};Fc.locally=e=>{var t;const n=Re();if(n.log("user/getReadUsers.locally",e),!n.cache)return;const{page:r}=e,a=en(e,["page"]),o=["read-user","query",Object.assign(Object.assign({},a),{options:Object.assign({},r)})],{data:s,cachedAt:i}=null!==(t=je(o))&&void 0!==t?t:{},c=null==s?void 0:s.users.map((e=>{var t;return null===(t=je(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:i,prevPage:de(null==s?void 0:s.paging.previous),nextPage:de(null==s?void 0:s.paging.next)}};const Kc=async e=>{const t=Re();t.log("user/getDeliveredUsers",e);const{page:n,messageId:r}=e,a=en(e,["page","messageId"]),{data:o}=await t.http.get(`/api/v1/markers/messages/${r}/delivered-users`,{params:Object.assign(Object.assign({},a),{options:{token:le(n,"afterbeforeraw")}})}),{paging:s,publicUserIds:i,userFeedMarkers:c}=o,l=en(o,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Xt(Object.assign(Object.assign({},l),{userFeedMarkers:on(c)}),{cachedAt:d});const e=["delivered-user","query",Object.assign(Object.assign({messageId:r},a),{options:Object.assign({},n)})];Ue(e,{users:i,paging:s})}let u=[];i.length>0&&({data:u}=await fi(i));return{data:u,cachedAt:d,prevPage:de(s.previous),nextPage:de(s.next)}};Kc.locally=e=>{var t;const n=Re();if(n.log("user/getDeliveredUsers.locally",e),!n.cache)return;const{page:r}=e,a=en(e,["page"]),o=["delivered-user","query",Object.assign(Object.assign({},a),{options:Object.assign({},r)})],{data:s,cachedAt:i}=null!==(t=je(o))&&void 0!==t?t:{},c=null==s?void 0:s.users.map((e=>{var t;return null===(t=je(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:i,prevPage:de(null==s?void 0:s.paging.previous),nextPage:de(null==s?void 0:s.paging.next)}};const $c=e=>{const t=Re();return it(t,"onMessageFlagged","message.flagged",(async t=>{const n=await On(t);Xt(n),e(n.messages[0])}))},Qc=e=>{const t=Re();return it(t,"onMessageUnflagged","message.unflagged",(async t=>{const n=await On(t);Xt(n),e(n.messages[0])}))},zc=e=>{const t=Re();return it(t,"onMessageFlagCleared","message.flagCleared",(async t=>{const n=await On(t);Xt(n),e(n.messages[0])}))},Vc=e=>{const t=Re();return it(t,"onMessageReactionAdded","message.reactionAdded",(async t=>{const n=await On(t,"message.reactionAdded");Xt(n),e(n.messages[0])}))},Hc=e=>{const t=Re();return it(t,"onMessageReactionRemoved","message.reactionRemoved",(async t=>{const n=await On(t,"message.reactionRemoved");Xt(n),e(n.messages[0])}))},Jc=e=>{const t=Re();return it(t,"message/onMessageFetched","local.message.fetched",(t=>{Xt(t),e(t.messages[0])}))},Wc=e=>{const t=Re();return it(t,"stream/onStreamViewerDidBan","video-streaming.viewerDidBan",(t=>{var n;const{list:r}=t;r.forEach((e=>{var t;xe(["stream","get",e.streamId],{watcherUrl:null});const n=null===(t=Me(["message","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.creatorId===e.userId));null==n||n.forEach((e=>{xe(e.key,{isDeleted:!0})}))}));const a=null===(n=je(["stream","get",r[0].streamId]))||void 0===n?void 0:n.data;a&&e(a)}))};class Gc extends ls{constructor(e,t,n,r,a){super(e,t),this.notifyChange=n,this.preparePayload=r,this.paginationController=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.messages.map(Ce("message")),query:this.query});else{const n=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,o=null!==(a=null==n?void 0:n.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},n),{data:"next"===t?[...new Set([...o,...e.messages.map(Ce("message"))])]:[...new Set([...e.messages.map(Ce("message")),...o])]}))}}reactor(e){return t=>{var n,r,a,o;if("onCreate"===e){const e=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data,{referenceId:o}=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.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.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===(a=this.query.includingTags)||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!=o?o:t.messageId,...e.data])]),"segmentAsc"!==this.query.sortBy||this.paginationController.getNextToken()||(e.data=[...new Set([...e.data,null!=o?o:t.messageId])]),Ue(this.cacheKey,e)}if("onDelete"===e&&"error"===t.syncState){const e=null===(o=je(this.cacheKey))||void 0===o?void 0:o.data;if(!e)return;if(e.data.includes(t.messageId)){const n=e.data.filter((e=>e!==t.messageId));Ue(this.cacheKey,Object.assign(Object.assign({},e),{data:n}))}}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Yc extends is{async getRequest(e,t){const n=En(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 Xc extends ps{constructor(e,t){const n=I.default(e),r=["message","collection",n];super(new Yc(e),n,r,t),this.query=e,this.queryStreamController=new Gc(this.query,this.cacheKey,this.notifyChange.bind(this),On,this.paginationController),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:uo,action:"onCreate"},{fn:ho,action:"onCreate"},{fn:Ac,action:"onDelete"},{fn:Ec,action:"onUpdate"},{fn:$c,action:"onFlagged"},{fn:Qc,action:"onUnflagged"},{fn:zc,action:"onFlagCleared"},{fn:Vc,action:"onReactionAdded"},{fn:Hc,action:"onReactionRemoved"},{fn:Ei(Do,"contentId","message"),action:"onUpdate"},{fn:Ei(qo,"contentId","message"),action:"onUpdate"},{fn:Ei(Wc,"channelId","message"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>(e=>{var t,n;const r=null===(t=je(["message","get",e]))||void 0===t?void 0:t.data;if(r)return r;const a=Me(["message","get"]);return null===(n=null==a?void 0:a.find((({data:t})=>t.messageId===e)))||void 0===n?void 0:n.data})(e))).filter(Boolean).map((e=>pi.message(e))))&&void 0!==a?a:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),onPrevPage:()=>this.loadPage({direction:"prev"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),hasPrevPage:!!this.paginationController.getPrevToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.includeDeleted||(t=Ne(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=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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)}}var Zc=Object.freeze({__proto__:null,createMessage:async e=>{const t=Re();t.log("message/createMessage",e);const n=(e=>{var t,n;const r=Re();if(!r.cache)return;Dc=e.referenceId||xc();const a=Object.assign({messageId:Dc,uniqueId:Dc},e);r.log("message/createMessage.optimistically",a);const o=je(["subChannel","get",e.subChannelId]);if(o&&(De(["subChannel","get",e.subChannelId],Object.assign(Object.assign({},o.data),{messageCount:o.data.messageCount+1})),o.data.channelId===o.data.subChannelId)){const e=je(["channel","get",o.data.channelId]);(null==e?void 0:e.data)&&De(["channel","get",o.data.channelId],Object.assign(Object.assign({},e.data),{messageCount:(null!==(t=e.data.messageCount)&&void 0!==t?t:0)+1}))}const s=(new Date).toISOString(),i=Object.assign({creatorId:r.userId,creatorPrivateId:tt()._id,channelSegment:(null!==(n=null==o?void 0:o.data.messageCount)&&void 0!==n?n:0)+1,childrenNumber:0,createdAt:s,updatedAt:s,syncState:"syncing",isDeleted:!1},a);return Ue(["message","get",i.messageId],i,{cachedAt:-5}),ct("local.message.created",{messages:[i]}),i})(e),r=e.referenceId||Dc||xc();Dc=void 0;try{const{data:n}=await t.http.post("/api/v5/messages",Object.assign(Object.assign({},Tn(e)),{referenceId:r})),a=await On(n),{messages:o}=a,s=t.cache&&Date.now();return t.cache&&Xt(a,{cachedAt:s}),ct("local.message.created",{messages:[Object.assign(Object.assign({},o[0]),{syncState:"synced"})]}),{data:pi.message(o[0]),cachedAt:s}}catch(e){throw ct("local.message.created",{messages:[Object.assign(Object.assign({},n),{syncState:"error"})]}),e}},updateMessage:qc,editMessage:Nc,deleteMessage:Bc,softDeleteMessage:Lc,markAsDelivered:async(e,t)=>{const n=Re();n.log("message/markAsDelivered",e,t);const{data:r}=await n.http.put(`/api/v1/markers/message-feeds/${e}/mark-delivering`,{messageId:t}),{userMarkers:a,userEntityMarkers:o,userFeedMarkers:s}=r,i=en(r,["userMarkers","userEntityMarkers","userFeedMarkers"]),c=n.cache&&Date.now();return n.cache&&Xt(Object.assign({userMarkers:a,userEntityMarkers:an(o),userFeedMarkers:on(s)},i),{cachedAt:c}),!0},getReadUsers:Fc,getDeliveredUsers:Kc,flagMessage:async(t,n)=>{const r=Re();r.log("message/flag",t);const a=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,r])=>t!==e.ContentFlagReasonEnum.Others&&r===n)),o={reason:a?n:e.ContentFlagReasonEnum.Others,detail:a?"":n},{data:s}=await r.http.post(`/api/v5/messages/${encodeURIComponent(t)}/flags`,o);if(r.cache){const e=await On(s);Xt(e)}return ct("message.flagged",s),!!s},unflagMessage:async e=>{const t=Re();t.log("message/unflag",e);const{data:n}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await On(n);Xt(e)}return ct("message.unflagged",n),!!n},isMessageFlaggedByMe:async e=>{const t=Re();t.log("message/isMessageFlaggedByMe",e);const{data:n}=await t.http.get(`/api/v5/messages/${encodeURIComponent(e)}/flags`);return n.result},onMessageCreatedMqtt:uo,onMessageCreatedLocal:ho,onMessageUpdated:Ec,onMessageDeleted:Ac,onMessageFlagged:$c,onMessageUnflagged:Qc,onMessageFlagCleared:zc,onMessageReactionAdded:Vc,onMessageReactionRemoved:Hc,onMessageFetched:Jc,getMessage:(e,t)=>Cs(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?pi.message(e.data):n}))}),"messageId",Ki,[Jc,Ec,Ac,$c,Qc,zc,Vc,Hc,Ei(Do,"contentId","message"),Ei(qo,"contentId","message"),Ei(Wc,"channelId","message")]),getMessages:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getMessages(tmpid: ${o}) > listen`);const s=new Xc(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>{qe(c)})),()=>{r(`getMessages(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},convertFromRaw:_n,prepareMessagePayload:On,convertParams:Tn,convertQueryParams:En});const el=e=>{const t=Re();return it(t,"subChannelMarker/onSubChannelUnreadUpdatedLocal","local.subChannelUnread.updated",(t=>{e(t)}))};class tl extends is{async getRequest(e,t){var n;const{limit:r=V}=e,a=null!==(n=function(e){var{excludeDefaultSubChannel:t}=e,n=en(e,["excludeDefaultSubChannel"]);const r=Object.assign({},n);return void 0!==t&&(r.excludeDefaultMessageFeed=t),r}(en(e,["limit"])))&&void 0!==n?n:{},{channelId:o,includeDeleted:s}=a,i=en(a,["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:bn(s),options:c})});return l}}class nl extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.messageFeeds.map((({messageFeedId:e})=>e))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(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=je(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])]),Ue(this.cacheKey,r)}this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class rl extends ps{constructor(e,t){const n=I.default(e),r=["subChannel","collection",n];super(new tl(e),n,r,t),this.query=e,this.queryStreamController=new nl(this.query,this.cacheKey,this.notifyChange.bind(this),Mn),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:Uc,action:"onCreate"},{fn:po,action:"onCreate"},{fn:fo,action:"onDelete"},{fn:e=>Rc((async t=>{if(!this.isRelatedCollection(t.subChannelId))return;const n=Re();if("no-message-preview"!==await n.getMessagePreviewSetting(!1)){const e=dn(t.subChannelId);(null==e?void 0:e.subChannelId)===t.subChannelId&&Un(t.updatedAt)>Un(e.subChannelUpdatedAt)&&Ue(["messagePreviewSubChannel","get",t.subChannelId],Object.assign(Object.assign({},e),{subChannelName:t.displayName,subChannelUpdatedAt:t.updatedAt}))}e(t)})),action:"onUpdate"},{fn:Ei((e=>uo((async t=>{this.isRelatedCollection(t.subChannelId)&&(await Dn(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Ei((e=>ho((async t=>{this.isRelatedCollection(t.subChannelId)&&(await Dn(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:e=>Uo((t=>{var n;const r=null!==(n=t.map((({feedId:e})=>je(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];0!==r.length&&e(r)})),action:"onUpdate"},{fn:Ei(jo,"feedId","subChannel"),action:"onUpdate"},{fn:Ei((e=>Ec((async t=>{var n;const r=Re();if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;const a=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;a&&a.data.includes(t.subChannelId)&&(qn(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Ei((e=>Ac((async t=>{const n=Re(),r=await n.getMessagePreviewSetting(!1);"no-message-preview"!==r&&this.isRelatedCollection(t.subChannelId)&&("message-preview-not-include-deleted"===r?await jn(t.subChannelId):await qn(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Ei(el,"subChannelId","subChannel"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(un))&&void 0!==a?a:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.includeDeleted||(t=Ne(e,"isDeleted",!1)),t.sort(Ze),t}isRelatedCollection(e){var t;const n=null===(t=je(this.cacheKey))||void 0===t?void 0:t.data;return n&&n.data.includes(e)}}const al={},ol=async e=>{const t=await(async e=>{const t=jn.locally(e);if(t)return t.data.channelId;const{data:n}=await jn(e);return n.channelId})(e),n=gt({channelId:t,subChannelId:e});al[e]=St(n)};var sl=Object.freeze({__proto__:null,getSubChannelByIds:ta,createSubChannel:async e=>{const t=Re();t.log("user/createSubChannel",e);const n=await t.http.post("/api/v5/message-feeds",{channelId:e.channelId,name:e.displayName}),r=await Mn(n.data),a=t.cache&&Date.now();return t.cache&&Xt(r,{cachedAt:a}),ct("message-feed.created",n.data),{data:r.messageFeeds[0],cachedAt:a}},updateSubChannel:async(e,t)=>{const n=Re();n.log("channel/updateSubChannel",e,t);const r=await n.http.put(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{name:t.displayName}),a=await Mn(r.data),o=n.cache&&Date.now();return n.cache&&Xt(a,{cachedAt:o}),ct("message-feed.updated",r.data),{data:a.messageFeeds[0],cachedAt:o}},deleteSubChannel:jc,hardDeleteSubChannel:async e=>{Re().log("channel/hardDeleteSubChannel",e);return await jc(e,!0)},softDeleteSubChannel:async e=>{Re().log("channel/softDeleteSubChannel",e);return await jc(e,!1)},onSubChannelCreated:po,onSubChannelUpdated:Rc,onSubChannelDeleted:fo,getSubChannel:(e,t)=>{const n=Re();let r;return Cs(e,(e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:un(e.data)}),a=en(n,["origin"]);return er(r,a)?void 0:(r=a,t(n))}),"subChannelId",jn,[Uc,t=>Rc((async r=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(Ln(r),r.subChannelId===e&&t(r))})),fo,Ei(jo,"feedId","subChannel"),t=>Uo((n=>{var r;if(!n.find((({feedId:t})=>t===e)))return;const a=null===(r=je(["subChannel","get",e]))||void 0===r?void 0:r.data;a&&t(a)})),Ei((t=>uo((async n=>{n.subChannelId===e&&(await Dn(n),t(n))}))),"subChannelId","subChannel"),Ei((t=>ho((async n=>{n.subChannelId===e&&(await Dn(n),t(n))}))),"subChannelId","subChannel"),Ei((t=>Ec((async r=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&r.subChannelId===e&&(qn(r),t(r))}))),"subChannelId","subChannel"),Ei((t=>Ac((async r=>{const a=await n.getMessagePreviewSetting(!1);"no-message-preview"!==a&&r.subChannelId===e&&("message-preview-include-deleted"===a&&await qn(r),"message-preview-not-include-deleted"===a&&await jn(r.subChannelId),t(r))}))),"subChannelId","subChannel"),Ei(el,"subChannelId","subChannel")],{forceDispatch:!0})},getSubChannels:(e,t,n)=>{const{log:r,cache:a}=Re(),o=Date.now();r(`getSubChannels(tmpid: ${o}) > listen`),a||console.log(J);const s=new rl(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>{qe(c)})),()=>{r(`getSubChannels(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},markReadEngineOnLoginHandler:ea,startMessageReceiptSync:async e=>(await ol(e),!0),stopMessageReceiptSync:e=>(al[e]&&al[e](),!0)});const il=e=>{const t=Re();return it(t,"channelMarker/onChannelUnreadInfoUpdatedLocal","local.channelUnreadInfo.updated",(t=>{e(t)}))},cl=e=>{const t=Re();return it(t,"channel/onChannelUnreadUpdatedLocal","local.channelUnread.updated",(t=>{e(t)}))};class ll extends is{async getRequest(e,t){const{limit:n=V,displayName:r,membership:a}=e,o=en(e,["limit","displayName","membership"]),s=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/channels",{params:Object.assign(Object.assign({},o),{keyword:r,filter:a,options:s})});return i}}class dl extends hs{async getRequest(e){const{data:t}=await this.http.get("/api/v3/channels/list",{params:Object.assign({},e)});return t}}class ul extends ls{constructor(e,t,n,r,a){super(e,t),this.notifyChange=n,this.preparePayload=r,this.paginationController=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.channels.map(Ce("channel"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channels.map(Ce("channel"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(this.paginationController instanceof dl)return this.notifyChange({origin:"event",loading:!1});["onCreate","onJoin","onResolveChannel"].includes(e)&&(Array.isArray(t)?r.data=[...new Set([...t.map(Ce("channel")),...r.data])]:r.data=[...new Set([t.channelInternalId,...r.data])]),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const hl=e=>{const t=Re();if(t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()){Ba().resolve(e.channelId,"userMessageFeedMarker")}},pl=e=>{const t=Re();return it(t,"onChannelResolved","local.channel.resolved",(async t=>{e(t)}))};class fl extends ps{constructor(e,t){const n=I.default(e),r=["channel","collection",n],a=fl.getPaginationController(e);super(a,n,r,t),this.query=e,this.queryStreamController=new ul(this.query,this.cacheKey,this.notifyChange.bind(this),(async e=>{try{const t=Re();t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await Hn(e)}catch(e){console.error("Error while preparing unread count info",e)}return zn(e)}),a),this.paginationController=a,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;let s=null!==(a=o.data.map((e=>je(["channel","get",e]))).filter(Boolean).map((({data:e})=>e)).map($r))&&void 0!==a?a:[];this.paginationController instanceof ll&&(s=this.applyFilter(s)),(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:this.paginationController instanceof ll?()=>this.loadPage({direction:"next"}):void 0,data:s,hasNextPage:this.paginationController instanceof ll&&!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Re();let n=e;switch(n=Ne(n,"isDeleted",this.query.isDeleted),n=Be(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=Fe(n,this.query.membership,t)),this.query.sortBy){case"firstCreated":n=n.sort(Je);break;case"lastCreated":n=n.sort(Ge);break;case"displayName":n=n.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Ve);break;default:n=n.sort(Ze)}return n}shouldAbort(e){var t,n;const r=null===(t=je(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 Re().getMessagePreviewSetting(!1)}static getPaginationController(e){return e.channelIds&&e.channelIds.length>0?new dl(e):new ll(e)}getSubscriptions(){const e=[{fn:Ei((e=>uo((t=>{var n,r;const a=Ba();(null===(n=je(["subChannelUnreadInfo","get",t.subChannelId]))||void 0===n?void 0:n.data)||a.resolve(t.subChannelId,"userMessageFeedMarker");const o=null===(r=je(["channel","get",t.channelId]))||void 0===r?void 0:r.data;o?(Pc(o,{lastActivity:t.createdAt}),e(t)):a.resolve(t.channelId,"channel")}))),"channelId","channel"),action:"onUpdate"},{fn:Ei((e=>ho((t=>{var n;const r=null===(n=je(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(Pc(r,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:ur,action:"onDelete"},{fn:sr,action:"onUpdate"},{fn:wr,action:"onMute"},{fn:e=>fr((t=>{hl(t),e(t)})),action:"onJoin"},{fn:e=>yr(((t,n)=>{var r,a;const{userId:o}=Re();if("member"===this.query.membership&&o===n.userId){const e=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;Ue(this.cacheKey,Object.assign(Object.assign({},e),{data:null!==(a=null==e?void 0:e.data.filter((e=>e!==t.channelId)))&&void 0!==a?a:[]}))}return e(t)})),action:"onLeft"},{fn:Sr,action:"onMemberAdded"},{fn:Or,action:"onMemberRemoved"},{fn:Ei(Mo,"entityId","channel"),action:"onUpdate"},{fn:Ei(Mc,"entityId","channel"),action:"onUpdate"},{fn:Ei((e=>uo((async t=>{var n;if("no-message-preview"===await fl.getMessagePreviewSetting())return;if(Nn(t),this.shouldAbort(t.channelId))return;const r=null===(n=je(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(Pc(r,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ei((e=>ho((async t=>{var n;if("no-message-preview"===await fl.getMessagePreviewSetting())return;if(Nn(t),this.shouldAbort(t.channelId))return;const r=null===(n=je(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(Pc(r,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ei((e=>Ec((async t=>{"no-message-preview"!==await fl.getMessagePreviewSetting()&&(Bn(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ei((e=>Ac((async t=>{const n=await fl.getMessagePreviewSetting();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await Bn(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&await Os(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:Ei((e=>fo((async t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;r.data.find((e=>{const n=sn(e);return(null==n?void 0:n.subChannelId)===t.subChannelId}))&&(await Os(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ei((e=>Rc((async t=>{var n;if("no-message-preview"===await fl.getMessagePreviewSetting())return;(null===(n=je(this.cacheKey))||void 0===n?void 0:n.data)&&(await Ln(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ei(po,"channelId","channel"),action:"onUpdate"},{fn:pl,action:"onResolveChannel"},{fn:e=>(e=>{const t=Re();return it(t,"userMessageFeedMarker/onUserMessageFeedMarkerResolved","local.userMessageFeedMarkers.resolved",(t=>{e(t)}))})((async t=>{if(t.feedMarkers){const n=t.feedMarkers.map((e=>{var t;return null===(t=je(["channel","get",e.entityId]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"OnResolveUnread"},{fn:Ei(il,"channelId","channel"),action:"onUpdate"},{fn:Ei((e=>cl((t=>{t.forEach(e)}))),"channelId","channel"),action:"onUpdate"}];return this.paginationController instanceof is?[...e,{fn:e=>rr((t=>{hl(t),e(t)})),action:"onCreate"}]:e}}const ml=()=>{var e;const t=Re();t.log("channel/getTotalChannelsUnread.locally");const n=(null===(e=Me(["channelUnread","get"]))||void 0===e?void 0:e.filter((({data:e})=>!e.isDeleted)))||[];return{data:(null==n?void 0:n.reduce(((e,{data:t})=>(e.unreadCount+=t.unreadCount,e.isMentioned=e.isMentioned||t.isMentioned,e)),{unreadCount:0,isMentioned:!1}))||{unreadCount:0,isMentioned:!1},cachedAt:t.cache&&Date.now()}};class gl extends is{async getRequest(e,t){const{limit:n=V,includeDeleted:r}=e,a=en(e,["limit","includeDeleted"]),o=t?{token:t}:{limit:n},s=!1!==r&&void 0,{data:i}=await this.http.get(`/api/v4/channels/${encodeURIComponent(a.channelId)}/users`,{params:Object.assign(Object.assign({},a),{options:o,isDeleted:s})});return i}}class yl extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.channelUsers.map((({channelId:e,userId:t})=>Ce("channelUsers")({channelId:e,userId:t})))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channelUsers.map((({channelId:e,userId:t})=>Ce("channelUsers")({channelId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;if(this.query.channelId!==t.channelId)return;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;const a=Ce("channelUsers")({channelId:this.query.channelId,userId:t.userId});"none"===t.membership?r.data=r.data.filter((e=>e!==a)):r.data.includes(a)||(r.data=[a,...r.data]),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class vl extends ps{constructor(e,t){const n=I.default(e),r=["channelUsers","collection",n];super(new gl(e),n,r,t),this.query=e,this.queryStreamController=new yl(this.query,this.cacheKey,this.notifyChange.bind(this),zn),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:fr,action:"onJoin"},{fn:yr,action:"onLeft"},{fn:Sr,action:"onMemberAdded"},{fn:Or,action:"onMemberRemoved"},{fn:Ar,action:"onChannelMemberBanned"},{fn:Mr,action:"onChannelMemberUnbanned"},{fn:xr,action:"onChannelMemberRoleAdded"},{fn:Nr,action:"onChannelMemberRoleRemoved"},{fn:Fr,action:"onChannelSetUserMuted"},{fn:(e=this.query.channelId,t=>{const n=Re();return it(n,"user.deleted","user.deleted",(n=>{var r,a;const o=fa(n);if(0===o.users.length)return;const s=o.users[0];Xt(o);const i=Ce("channelUsers")({channelId:e,userId:s.userId}),c=null===(r=je(["channelUsers","get",i]))||void 0===r?void 0:r.data;De(["channelUsers","get",i],Object.assign(Object.assign({},c),{user:s}));const l=null===(a=je(["channel","get",e]))||void 0===a?void 0:a.data;l&&t(l,c)}))}),action:"onChannelMemberChanged"}]);var e}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["channelUsers","get",e]))).filter(Boolean).map((({data:e})=>e)).map(pi.channelMember))&&void 0!==a?a:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=Le(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))}))),!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?Ge:Je),t}}const bl=(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getMembers(tmpid: ${o}) > listen`);const s=new vl(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>{qe(c)})),()=>{r(`getMembers(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}};var wl=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=Re();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=>ct("channel.membersAdded",Object.assign(Object.assign({},r),{channelUsers:r.channelUsers.filter((t=>t.userId===e))}))));const a=await zn(r);n.cache&&Xt(a);const{channelUsers:o}=a;return!!o.find((t=>t.channelId===e&&"member"===t.membership))},removeMembers:async(e,t)=>{const n=Re();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=>ct("channel.membersRemoved",Object.assign(Object.assign({},r),{channelUsers:r.channelUsers.filter((t=>t.userId===e))}))));const a=await zn(r);n.cache&&Xt(a);const{channelUsers:o}=a;return!!o.find((t=>t.channelId===e&&"member"!==t.membership))},applyFilter:(e,t)=>{let n=Le(e,"roles",t.roles);t.memberships&&(n=n.filter((e=>!(!t.memberships.includes("muted")||!e.isMuted)||t.memberships.includes(e.membership))));const r=t.sortBy?t.sortBy:"lastCreated";return n=n.sort("lastCreated"===r?Ge:Je),n},getMembers:bl,searchMembers:(e,t,n)=>bl(e,t)});var Cl=Object.freeze({__proto__:null,addRole:async(e,t,n)=>{const r=Re();r.log("channel/addRole",e,t,n);const{data:a}=await r.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{channelId:e,role:t,userIds:n}),o=await zn(a);r.cache&&Xt(o),ct("local.channel-moderator.role-added",o);const{channelUsers:s}=o;return!!s.find((n=>n.channelId===e&&n.roles.includes(t)))},removeRole:async(e,t,n)=>{const r=Re();r.log("channel/removeRole",e,t,n);const{data:a}=await r.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{data:{channelId:e,role:t,userIds:n}}),o=await zn(a);r.cache&&Xt(o),ct("local.channel-moderator.role-removed",o);const{channelUsers:s}=o;return!!s.find((n=>n.channelId===e&&!n.roles.includes(t)))},banMembers:async(e,t)=>{const n=Re();n.log("channel/banMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v3/channels/${e}/users/ban`,{userIds:t}),a=await zn(r),{channelUsers:o}=a,s=n.cache&&Date.now();return n.cache&&Xt(a,{cachedAt:s}),{data:null==o?void 0:o.filter((e=>"banned"===e.membership)),cachedAt:s}},unbanMembers:async(e,t)=>{const n=Re();n.log("channel/unbanMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}/users/unban`,{userIds:t}),a=await zn(r),o=n.cache&&Date.now();n.cache&&Xt(a,{cachedAt:o});const{channelUsers:s}=a;return{data:null==s?void 0:s.filter((e=>"member"===e.membership)),cachedAt:o}},muteMembers:async(e,t,n=-1)=>{const r=Re();r.log("channel/muteMembers",{userIds:t,channelId:e,mutePeriod:n});const{data:a}=await r.http.put(`/api/v2/channel/${e}/users/mute`,{userIds:t,mutePeriod:-1===n?n:1e3*n}),{success:o}=a;return o},unmuteMembers:async(e,t)=>{const n=Re();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:a}=r;return a}}),Il=Object.freeze({__proto__:null,Membership:wl,Moderation:Cl,getChannelByIds:Qr,createChannel:ks,updateChannel:async(e,t)=>{const n=Re();n.log("channel/updateChannel",e,t);const{data:r}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}`,t),a=await zn(r),o=n.cache&&Date.now();n.cache&&Xt(a,{cachedAt:o});const{channels:s}=a;return{data:Yn(s.find((t=>t.channelId===e))),cachedAt:o}},deleteChannel:async e=>{const t=Re();t.log("channel/deleteChannel",e),await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}`);const n=await Os(e);return Yn(n.data)},joinChannel:async e=>{const t=Re();t.log("channel/joinChannel",e);const{data:n}=await t.http.post(`/api/v3/channels/${encodeURIComponent(e)}/join`),r=await zn(n);t.cache&&Xt(r);const{channelUsers:a}=r;return!!a.find((t=>t.channelId===e&&"member"===t.membership))},leaveChannel:async e=>{const t=Re();t.log("channel/leaveChannel",e);const{data:n}=await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/leave`),r=await zn(n);t.cache&&Xt(r);const{channelUsers:a}=r;return!!a.find((t=>t.channelId===e&&"member"!==t.membership))},muteChannel:async(e,t=-1)=>{const n=Re();if(n.log("channel/muteChannel",e),-1!==t&&t<0)throw new _e("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:a}=r;return a},unmuteChannel:async e=>{const t=Re();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},onChannelCreated:rr,onChannelUpdated:sr,onChannelDeleted:ur,onChannelJoined:fr,onChannelLeft:yr,onChannelSetMuted:wr,onChannelMemberAdded:Sr,onChannelMemberRemoved:Or,onChannelMemberBanned:Ar,onChannelMemberUnbanned:Mr,onChannelMemberRoleAdded:xr,onChannelMemberRoleRemoved:Nr,getChannel:(e,t)=>{const n=Re();let r;return Cs(e,(async e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:$r(e.data)}),a=en(n,["origin"]);return er(r,a)?void 0:(r=a,t(n))}),"channelId",Os,[sr,ur,fr,yr,Sr,Or,Ar,Mr,wr,Ei(Mo,"entityId","channel"),Ei(Mc,"entityId","channel"),Ei((t=>uo((async r=>{await(async r=>{var a;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Nn(r),r.channelId!==e)return;const o=null===(a=je(["channel","get",e]))||void 0===a?void 0:a.data;o&&(Pc(o,{messagePreviewId:r.messageId}),t(r))})(r),t(r)}))),"channelId","channel"),Ei((t=>ho((async r=>{var a;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Nn(r),r.channelId!==e)return;const o=null===(a=je(["channel","get",e]))||void 0===a?void 0:a.data;o&&(Pc(o,{messagePreviewId:r.messageId}),t(r))}))),"channelId","channel"),Ei((t=>Ec((async r=>{var a;const o=null===(a=je(["channel","get",e]))||void 0===a?void 0:a.data;if(!o||o.messagePreviewId!==r.messageId)return;"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(await Bn(r),t(r))}))),"channelId","channel"),Ei((t=>Ac((async r=>{var a;const o=null===(a=je(["channel","get",e]))||void 0===a?void 0:a.data;if(!o||o.messagePreviewId!==r.messageId)return;const s=await n.getMessagePreviewSetting(!1);"no-message-preview"!==s&&("message-preview-not-include-deleted"===s?(qe(["messagePreviewChannel","get",e]),await Os(r.channelId)):await Bn(r),t(r))}))),"channelId","channel"),Ei((e=>fo((async t=>{var r,a;const{channelId:o,subChannelId:s}=t,i=null===(r=je(["messagePreviewChannel","get",o]))||void 0===r?void 0:r.data;if(!i||i.subChannelId!==s)return;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;await Os(o);(null===(a=je(["channel","get",o]))||void 0===a?void 0:a.data)&&e(t)}))),"channelId","channel"),Ei((t=>Rc((async r=>{var a,o;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;Ln(r);const s=null===(a=je(["messagePreviewChannel","get",e]))||void 0===a?void 0:a.data;if(!s||s.subChannelId!==r.subChannelId)return;(null===(o=je(["channel","get",e]))||void 0===o?void 0:o.data)&&t(r)}))),"channelId","channel"),Ei(po,"channelId","channel"),Ei(il,"channelId","channel"),Ei((e=>cl((t=>{t.forEach(e)}))),"channelId","channel")],{forceDispatch:!0})},getChannels:(e,t,n)=>{const{log:r,cache:a,userId:o}=Re();a||console.log(J);const s=Date.now();r(`getChannels(tmpid: ${s}) > listen`);const i=new fl(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{qe(l)})),()=>{r(`getChannels(tmpid: ${s}) > dispose`),c.forEach((e=>e()))}},getTotalChannelsUnread:e=>{const{_id:t}=tt();if(!t)throw new _e("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:r}=Re();r||console.log("For using Live Object feature you need to enable Cache!");n(`liveTotalChannelsUnread(tmpid: ${Date.now()}) > listen`);const a=[];let o,s=!1;const i=t=>{const{data:n}=t,r=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;o=r?Bo(r):r,e({data:r?Object.assign(Object.assign({},r),{isMentioned:r.isMentioned}):r,loading:t.loading,error:t.error})};return a.push(cl((e=>{const{data:t}=ml();er(o,t)||i({loading:!1,data:t})}))),(()=>{const e=ge((async()=>ml()));ve(e,(({error:e,data:t,loading:n,origin:r,cachedAt:o})=>{o===G?(i({data:t,origin:r,loading:!1,error:new ke(W,800800,"error")}),s=!0,a.forEach((e=>e()))):s||i({loading:n,data:t,origin:r,error:e}),e&&a.forEach((e=>e()))}))})(),()=>{a.forEach((e=>e()))}},MARKER_INCLUDED_CHANNEL_TYPE:Fn,isUnreadCountSupport:Kn,convertFromRaw:$n,preUpdateChannelCache:Qn,prepareChannelPayload:zn});const Sl=(e,t)=>{0!==e.length&&0!==t.length&&e.forEach((({communityId:e})=>{const n=t.filter((({communityId:t})=>e===t));Ue(["communityUsers","collection",e],n)}))},_l=async(e,t)=>{const n=Re();n.log("community/getCommunities",e);const r=e.map((e=>encodeURIComponent(e))),{data:a}=await n.http.get("/api/v3/communities/list",{params:{communityIds:r,includeDiscoverablePrivateCommunity:null==t||t}}),o=Ks(a),s=n.cache&&Date.now();return n.cache&&(Xt(o,{cachedAt:s}),Sl(o.communities,o.communityUsers)),{data:o.communities.map((e=>pi.community(e))),cachedAt:s}};_l.locally=e=>{var t;const n=Re();if(n.log("community/getCommunities.locally",e),!n.cache)return;const r=e.map((e=>je(["community","get",e]))).filter(Boolean),a=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:a,cachedAt:o.cachedAt}};const kl=async e=>{const t=Re();t.log("community/getCommunity",e);const{data:n}=await t.http.get(`/api/v3/communities/${e}`),r=Ks(n),a=t.cache&&Date.now();t.cache&&(Xt(r,{cachedAt:a}),Sl(r.communities,r.communityUsers));const{communities:o}=r;return{data:o.find((t=>t.communityId===e)),cachedAt:a}};kl.locally=e=>{const t=Re();if(t.log("community/getCommunity.locally",e),!t.cache)return;const n=je(["community","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Ol=(e,t)=>{const n=Re();return it(n,e,e,(e=>{const r=Ks(e);if(n.cache){Xt(r);const e=je(["community","get",r.communities[0].communityId]);t(e.data)}else t(r.communities[0])}))},Tl=e=>Ol("community.created",e),El=e=>Ol("community.updated",e),Al=e=>Ol("community.deleted",e);class Rl extends is{async getRequest(e,t){var n;const{limit:r=V}=e,a=en(e,["limit"]),o=t?{token:t}:{limit:r},{data:s}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},a),{isDeleted:bn(a.includeDeleted),keyword:a.displayName,filter:a.membership,includeDiscoverablePrivateCommunity:null===(n=a.includeDiscoverablePrivateCommunity)||void 0===n||n,options:o})});return s}}class Pl extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.communities.map(Ce("community"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Ce("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=je(this.cacheKey))||void 0===t?void 0:t.data;n&&(Ue(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Ml,jl;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Ml||(Ml={})),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",e.OnLocalCommunityJoin="OnLocalCommunityJoin"}(jl||(jl={}));class Ul extends is{async getRequest(e,t){const{limit:n=V,includeDeleted:r}=e,a=en(e,["limit","includeDeleted"]),o=t?{token:t}:{limit:n},s=!1!==r&&void 0,{data:i}=await this.http.get(`/api/v3/communities/${a.communityId}/users`,{params:Object.assign(Object.assign({},a),{options:o,isDeleted:s})});return i}}class xl extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>Ce("communityUsers")({communityId:e,userId:t})))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>Ce("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;r&&(t.forEach((e=>{const t=Ce("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership?r.data=r.data.filter((e=>e!==t)):r.data.includes(t)||(r.data=[t,...r.data])})),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}function Dl(e,t,n){return!!e.permissions.some((e=>e===n))||t.communityUsers.find((t=>t.userId===e.userId)).permissions.some((e=>e===n))}function ql(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=>!Dl(e,t,"BAN_COMMUNITY_USER"))):t.communityUsers.filter((e=>!Dl(e,t,"ADD_COMMUNITY_USER")))}const Nl=(e,t)=>{const n=Re();return it(n,e,e,(r=>{const a=Ks(r),{communities:o,communityUsers:s}=a,i=Bs(o,s);if(a.communities=i,n.cache){Xt(a,void 0,!1);const n=je(["community","get",a.communities[0].communityId]),r=ql(e,a).map((e=>{const t=je(["communityUsers","get",Ce("communityUsers")(e)]);return null==t?void 0:t.data})).filter(fs);t(n.data,r)}else t(a.communities[0],ql(e,a))}))},Bl=(e,t)=>{const n=Re();return it(n,e,e,(r=>{const a=Ks(r),{communities:o,communityUsers:s}=a,i=Bs(o,s);if(a.communities=i,n.cache){Xt(a,void 0,!1);const n=je(["community","get",a.communities[0].communityId]),r=ql(e,a).map((e=>{const t=je(["communityUsers","get",Ce("communityUsers")(e)]);return null==t?void 0:t.data})).filter(fs);t(n.data,r)}else t(a.communities[0],ql(e,a))}))},Ll=e=>Nl("community.userBanned",e),Fl=e=>Nl("community.userChanged",e),Kl=e=>Nl("community.userUnbanned",e),$l=e=>Nl("community.roleAdded",e),Ql=e=>Nl("community.roleRemoved",e),zl=e=>Bl("local.community.userAdded",e),Vl=e=>Bl("local.community.userRemoved",e),Hl=e=>Nl("community.joined",e),Jl=e=>Nl("community.left",e),Wl=e=>Bl("local.community.joined",e),Gl=e=>Bl("local.community.left",e),Yl=e=>{const t=Re(),n=[it(t,"onCommunityUpdate","v4.local.community.joined",(async t=>{e(t[0])}))];return()=>{n.forEach((e=>e()))}},Xl=e=>{const t=Re();return it(t,"onLocalCommunityRoleRemoved","local.community.roleRemoved",(async t=>{const{communities:n,communityUsers:r}=t;e(n[0],r.filter((e=>"member"===e.communityMembership)))}))},Zl=e=>{const t=Re();return it(t,"onLocalCommunityRoleAdded","local.community.roleAdded",(async t=>{const{communities:n,communityUsers:r}=t;e(n[0],r.filter((e=>"member"===e.communityMembership)))}))},ed=e=>t=>{const n=Re();return it(n,"user.deleted","user.deleted",(n=>{var r,a;const o=fa(n);if(0===o.users.length)return;const s=o.users[0];Xt(o);const i=Ce("communityUsers")({communityId:e,userId:s.userId}),c=null===(r=je(["communityUsers","get",i]))||void 0===r?void 0:r.data;Ue(["communityUsers","get",i],Object.assign(Object.assign({},c),{user:s}));const l=null===(a=je(["community","get",e]))||void 0===a?void 0:a.data;t(l,[Object.assign(Object.assign({},c),{user:s})])}))};class td extends ps{constructor(e,t){const n=I.default(e),r=["communityUsers","collection",n];super(new Ul(e),n,r,t),this.query=e,this.queryStreamController=new xl(this.query,this.cacheKey,this.notifyChange.bind(this),Ks),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:Hl,action:jl.OnCommunityJoined},{fn:Wl,action:jl.OnCommunityJoined},{fn:Jl,action:jl.OnCommunityLeft},{fn:Gl,action:jl.OnCommunityLeft},{fn:Ll,action:jl.OnCommunityUserBanned},{fn:Fl,action:jl.OnCommunityUserChanged},{fn:$l,action:jl.OnCommunityUserRoleAdded},{fn:Ql,action:jl.OnCommunityUserRoleRemoved},{fn:Zl,action:jl.OnCommunityUserRoleAdded},{fn:Xl,action:jl.OnCommunityUserRoleRemoved},{fn:Kl,action:jl.OnCommunityUserUnbanned},{fn:zl,action:jl.OnCommunityUserAdded},{fn:Vl,action:jl.onCommunityUserRemoved},{fn:ed(this.query.communityId),action:jl.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["communityUsers","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=Le(e,"roles",this.query.roles);if(this.query.memberships&&(t=t.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),!1===this.query.includeDeleted&&(t=t.filter((({user:e})=>!0!==(null==e?void 0:e.isDeleted)))),"firstCreated"===this.query.sortBy)t=t.sort(Je);else t=t.sort(Ge);return t}}class nd extends is{async getRequest(e,t){const{limit:n=V,includeDeleted:r}=e,a=en(e,["limit","includeDeleted"]),o=t?{token:t}:{limit:n},s=!1!==r&&void 0,{data:i}=await this.http.get(`/api/v3/communities/${a.communityId}/users`,{params:Object.assign(Object.assign({},a),{options:o,isDeleted:s})});return i}}class rd extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>Ce("communityUsers")({communityId:e,userId:t})))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>Ce("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;r&&(t.forEach((e=>{const t=Ce("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership&&(r.data=r.data.filter((e=>e!==t)))})),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var ad;!function(e){e.OnCommunityJoined="onCommunityJoined",e.OnLocalCommunityJoin="onLocalCommunityJoin",e.OnCommunityLeft="onCommunityLeft",e.OnCommunityUserBanned="onCommunityUserBanned",e.OnCommunityUserChanged="onCommunityUserChanged",e.OnCommunityUserRoleAdded="onCommunityUserRoleAdded",e.OnCommunityUserRoleRemoved="onCommunityUserRoleRemoved",e.OnCommunityUserUnbanned="onCommunityUserUnbanned"}(ad||(ad={}));class od extends ps{constructor(e,t){const n=I.default(e),r=["communityUsers","collection",n];super(new nd(e),n,r,t),this.query=e,this.queryStreamController=new rd(this.query,this.cacheKey,this.notifyChange.bind(this),Ks),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:Hl,action:ad.OnCommunityJoined},{fn:Wl,action:ad.OnCommunityJoined},{fn:Jl,action:ad.OnCommunityLeft},{fn:Gl,action:ad.OnCommunityLeft},{fn:Ll,action:ad.OnCommunityUserBanned},{fn:Fl,action:ad.OnCommunityUserChanged},{fn:Xl,action:ad.OnCommunityUserRoleRemoved},{fn:Ql,action:ad.OnCommunityUserRoleRemoved},{fn:Kl,action:ad.OnCommunityUserUnbanned},{fn:ed(this.query.communityId),action:ad.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["communityUsers","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=Le(e,"roles",this.query.roles);return this.query.memberships&&(t=t.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),this.query.search&&(t=ze(t,this.query.search)),!1===this.query.includeDeleted&&(t=t.filter((({user:e})=>!0!==(null==e?void 0:e.isDeleted)))),t}}var sd=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=Re();n.log("community/moderation/addMembers",e,t);const{data:r}=await n.http.post(`/api/v3/communities/${e}/users`,{communityId:e,userIds:t});ct("local.community.userAdded",r);const a=nn(r,"communityUsers");n.cache&&Xt(a);const{communityUsers:o}=a;return!!o.find((t=>t.communityId===e&&"member"===t.communityMembership))},removeMembers:async(e,t)=>{const n=Re();n.log("community/moderation/removeMembers",e,t);const{data:r}=await n.http.delete(`/api/v3/communities/${e}/users`,{data:{communityId:e,userIds:t}});ct("local.community.userRemoved",r);const a=nn(r,"communityUsers");n.cache&&Xt(a);const{communityUsers:o}=a;return!!o.find((t=>t.communityId===e&&"member"!==t.communityMembership))},applyFilter:(e,t)=>{let n=Le(e,"roles",t.roles);t.memberships&&(n=n.filter((({communityMembership:e})=>t.memberships.includes(e))));const r=t.sortBy?t.sortBy:"lastCreated";return n=n.sort("lastCreated"===r?Ge:Je),n},getMembers:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getMembers(tmpid: ${o}) > listen`);const s=new td(e,(e=>{t(e)})),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>{qe(c)})),()=>{r(`getMembers(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},searchMembers:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getMembers(tmpid: ${o}) > listen`);const s=new od(e,(e=>{t(e)})),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>{qe(c)})),()=>{r(`getMembers(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},onCommunityUserAdded:e=>Nl("community.userAdded",e),onCommunityUserRemoved:e=>Nl("community.userRemoved",e),onCommunityUserBanned:Ll,onCommunityUserChanged:Fl,onCommunityUserUnbanned:Kl,onCommunityUserRoleAdded:$l,onCommunityUserRoleRemoved:Ql,onLocalCommunityUserAdded:zl,onLocalCommunityUserRemoved:Vl,onCommunityJoined:Hl,onCommunityLeft:Jl,onLocalCommunityJoined:Wl,onLocalCommunityLeft:Gl,onLocalCommunityJoin:Yl});class id extends ps{constructor(e,t){const n=I.default(e),r=["community","collection",n];super(new Rl(e),n,r,t),this.query=e,this.queryStreamController=new Pl(this.query,this.cacheKey,this.notifyChange.bind(this),Ks),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:Al,action:Ml.OnCommunityDeleted},{fn:El,action:Ml.OnCommunityUpdated},{fn:Hl,action:jl.OnCommunityJoined},{fn:Jl,action:jl.OnCommunityLeft},{fn:Fl,action:jl.OnMemberCountChanged},{fn:Wl,action:jl.OnCommunityJoined},{fn:Gl,action:jl.OnCommunityLeft},{fn:Ei(Yl,"targetId","community"),action:Ml.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["community","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Re();let n=e;return this.query.includeDeleted||(n=Ne(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=$e(n,this.query.membership,t)),n}}class cd extends is{async getRequest(e,t){var n;const{limit:r=V}=e,a=en(e,["limit"]),o=t?{token:t}:{limit:r},{data:s}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},a),{isDeleted:bn(a.includeDeleted),filter:a.membership,includeDiscoverablePrivateCommunity:null===(n=a.includeDiscoverablePrivateCommunity)||void 0===n||n,options:o})});return s}}class ld extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&(Xt(t,{cachedAt:r}),Sl(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.communities.map(Ce("community"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Ce("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=je(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],Ue(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var dd;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(dd||(dd={}));class ud extends ps{constructor(e,t){const n=I.default(e),r=["community","collection",n];super(new cd(e),n,r,t),this.query=e,this.queryStreamController=new ld(this.query,this.cacheKey,this.notifyChange.bind(this),Ks),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:Tl,action:dd.OnCommunityCreated},{fn:Al,action:dd.OnCommunityDeleted},{fn:El,action:dd.OnCommunityUpdated},{fn:Hl,action:jl.OnCommunityJoined},{fn:Jl,action:jl.OnCommunityLeft},{fn:Fl,action:jl.OnMemberCountChanged},{fn:Wl,action:jl.OnCommunityJoined},{fn:Gl,action:jl.OnCommunityLeft},{fn:Ei(Yl,"targetId","community"),action:dd.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=null!==(a=o.data.map((e=>je(["community","get",e]))).filter(fs).map((({data:e})=>hi(e))))&&void 0!==a?a:[];(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Re();let n=e;this.query.includeDeleted||(n=Ne(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=$e(n,this.query.membership,t));const r=(()=>"firstCreated"===this.query.sortBy?Je:Ge)();return n=n.sort(r),n}}class hd extends is{async getRequest(e,t){const{limit:n=V,includeDiscoverablePrivateCommunity:r}=e,a=en(e,["limit","includeDiscoverablePrivateCommunity"]),o=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v3/communities/top-trending",{params:Object.assign(Object.assign({},a),{options:o,includeDiscoverablePrivateCommunity:null==r||r})});return s}}class pd extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&(Xt(t,{cachedAt:r}),Sl(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.communities.map(Ce("community"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Ce("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=je(this.cacheKey))||void 0===t?void 0:t.data;n&&(Ue(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var fd;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(fd||(fd={}));class md extends ps{constructor(e,t){const n=I.default(e),r=["trendingCommunity","collection",n];super(new hd(e),n,r,t),this.query=e,this.queryStreamController=new pd(this.query,this.cacheKey,this.notifyChange.bind(this),Ks),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:Al,action:fd.OnCommunityDeleted},{fn:El,action:fd.OnCommunityUpdated},{fn:Hl,action:jl.OnCommunityJoined},{fn:Jl,action:jl.OnCommunityLeft},{fn:Fl,action:jl.OnMemberCountChanged},{fn:Wl,action:jl.OnCommunityJoined},{fn:Gl,action:jl.OnCommunityLeft},{fn:Ei(Yl,"targetId","community"),action:fd.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=null!==(a=o.data.map((e=>je(["community","get",e]))).filter(fs).map((({data:e})=>hi(e))))&&void 0!==a?a:[];(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class gd extends is{async getRequest(e,t){const{limit:n=V,includeDiscoverablePrivateCommunity:r}=e,a=en(e,["limit","includeDiscoverablePrivateCommunity"]),o=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v3/communities/recommended",{params:Object.assign(Object.assign({},a),{options:o,includeDiscoverablePrivateCommunity:null==r||r})});return s}}class yd extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&(Xt(t,{cachedAt:r}),Sl(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.communities.map(Ce("community"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Ce("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=je(this.cacheKey))||void 0===t?void 0:t.data;n&&(Ue(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var vd;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated",e.OnLocalCommunityJoin="onLocalCommunityJoin"}(vd||(vd={}));class bd extends ps{constructor(e,t){const n=I.default(e),r=["community","collection",n];super(new gd(e),n,r,t),this.query=e,this.queryStreamController=new yd(this.query,this.cacheKey,this.notifyChange.bind(this),Ks),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:Al,action:vd.OnCommunityDeleted},{fn:El,action:vd.OnCommunityUpdated},{fn:Hl,action:jl.OnCommunityJoined},{fn:Jl,action:jl.OnCommunityLeft},{fn:Fl,action:jl.OnMemberCountChanged},{fn:Wl,action:jl.OnCommunityJoined},{fn:Gl,action:jl.OnCommunityLeft},{fn:Ei(Yl,"targetId","community"),action:vd.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=null!==(a=o.data.map((e=>je(["community","get",e]))).filter(fs).map((({data:e})=>hi(e))))&&void 0!==a?a:[];(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class wd extends is{async getRequest(e,t){var n;const{limit:r=V,communityMembershipStatus:a}=e,o=en(e,["limit","communityMembershipStatus"]),s={type:e.limit?"pagination":void 0},i=t?Object.assign(Object.assign({},s),{token:t}):Object.assign(Object.assign({},s),{limit:r}),{data:c}=await this.http.get("/api/v1/semantic-search/communities",{params:Object.assign(Object.assign({},o),{filter:null!=a?a:"all",options:i,includeDiscoverablePrivateCommunity:null===(n=o.includeDiscoverablePrivateCommunity)||void 0===n||n})});return c}}function Cd(e){return e.communities.map((t=>{const n=e.searchResult.find((e=>e.communityId===t.communityId));return`${t.communityId}:${n}`}))}class Id extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:Cd(e)});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...Cd(e)])]}))}}reactor(e){return e=>{var t;const n=null===(t=je(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],Ue(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Sd;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Sd||(Sd={}));class _d extends ps{constructor(e,t){const n=I.default(e),r=["community","collection",n];super(new wd(e),n,r,t),this.query=e,this.queryStreamController=new Id(this.query,this.cacheKey,this.notifyChange.bind(this),Vs),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:Tl,action:Sd.OnCommunityCreated},{fn:Al,action:Sd.OnCommunityDeleted},{fn:El,action:Sd.OnCommunityUpdated},{fn:Hl,action:jl.OnCommunityJoined},{fn:Jl,action:jl.OnCommunityLeft},{fn:Fl,action:jl.OnMemberCountChanged},{fn:Wl,action:jl.OnCommunityJoined},{fn:Gl,action:jl.OnCommunityLeft},{fn:Ei(Yl,"targetId","community"),action:Sd.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>{const[t,n]=e.split(":");return{communityId:t,score:parseFloat(n)}})).sort(((e,t)=>t.score-e.score)).map((({communityId:e})=>je(["community","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Re();let n=e;return this.query.categoryIds&&(n=n.filter((e=>{var t;return null===(t=e.categoryIds)||void 0===t?void 0:t.some((e=>!this.query.categoryIds||(0===this.query.categoryIds.length||this.query.categoryIds.includes(e))))}))),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.communityMembershipStatus&&t&&(n=$e(n,this.query.communityMembershipStatus,t)),n}}class kd extends is{async getRequest(e,t){const{limit:n=V,communityIds:r}=e,a=en(e,["limit","communityIds"]),o=t?{token:t}:{limit:n},s=r.map((e=>encodeURIComponent(e))),{data:i}=await this.http.get("/api/v4/communities/join/requests",{params:Object.assign(Object.assign({},a),{options:o,communityIds:s})});return i}}var Od;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(Od||(Od={}));class Td extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.joinRequests.map((e=>Ce("joinRequest")({joinRequestId:e._id})))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>Ce("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;const a=(Array.isArray(t)?t:[t]).map((e=>e.joinRequestId));if(e===Od.OnLocalJoinRequestUpdated){if(!r.data.find((e=>a.includes(e))))return}e===Od.OnLocalJoinRequestCreated&&(r.data=[...new Set([...a,...r.data])]),e===Od.OnLocalJoinRequestDeleted&&(r.data=r.data.filter((e=>!a.includes(e)))),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Ed extends ps{constructor(e,t){const n=I.default(e),r=["joinRequestList","collection",n];super(new kd(e),n,r,t),this.query=e,this.queryStreamController=new Td(this.query,this.cacheKey,this.notifyChange.bind(this),$s),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){const r=e;this.queryStreamController.appendToQueryStream(r,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Ys,action:Od.OnLocalJoinRequestCreated},{fn:Xs,action:Od.OnLocalJoinRequestUpdated},{fn:Zs,action:Od.OnLocalJoinRequestUpdated},{fn:Yl,action:Od.OnLocalJoinRequestUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r;const a=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const o=this.applyFilter(a.data.map((e=>je(["joinRequest","get",e]))).filter(fs).map((({data:e})=>e)).map(Hs));(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;this.query.communityIds&&this.query.communityIds.length>0&&(t=t.filter((e=>this.query.communityIds.some((t=>t===e.targetId)))));const n=(()=>"firstCreated"===this.query.sortBy?Je:Ge)();return t=t.sort(n),t}}var Ad;!function(e){e.ALL="all",e.MEMBER="member",e.NOT_MEMBER="notMember"}(Ad||(Ad={}));var Rd=Object.freeze({__proto__:null,addRoles:async(e,t,n)=>{const r=Re();r.log("community/moderation/addRoles",e,t,n);const{data:a}=await r.http.post(`/api/v4/communities/${e}/users/roles`,{communityId:e,roles:t,userIds:n}),o=Qs(a);r.cache&&Xt(o),ct("local.community.roleAdded",o);const{communityUsers:s}=o;return!!s.find((n=>n.communityId===e&&t.some((e=>n.roles.includes(e)))))},removeRoles:async(e,t,n)=>{const r=Re();r.log("community/moderation/removeRoles",e,t,n);const{data:a}=await r.http.delete(`/api/v4/communities/${e}/users/roles`,{data:{communityId:e,roles:t,userIds:n}}),o=Qs(a);r.cache&&Xt(o),ct("local.community.roleRemoved",o);const{communityUsers:s}=o;return!!s.find((n=>n.communityId===e&&!t.some((e=>n.roles.includes(e)))))},banMembers:async(e,t)=>{const n=Re();n.log("community/banMembers",{userIds:t,communityId:e});const{data:r}=await n.http.put(`/api/v3/communities/${e}/users/ban`,{userIds:t}),a=nn(r,"communityUsers"),o=n.cache&&Date.now();n.cache&&Xt(a,{cachedAt:o});const{communityUsers:s}=a;return{data:s.filter((e=>t.includes(e.userId))),cachedAt:o}},unbanMembers:async(e,t)=>{const n=Re();n.log("community/unbanMembers",{userIds:t,communityId:e});const{data:r}=await n.http.put(`/api/v3/communities/${e}/users/unban`,{userIds:t}),a=nn(r,"communityUsers"),o=n.cache&&Date.now();n.cache&&Xt(a,{cachedAt:o});const{communityUsers:s}=a;return{data:s.filter((e=>t.includes(e.userId))),cachedAt:o}}}),Pd=Object.freeze({__proto__:null,Moderation:Rd,Membership:sd,getCommunityByIds:_l,createCommunity:async e=>{const t=Re();t.log("user/createCommunity",e);const{data:n}=await t.http.post("/api/v3/communities/",zs(e));ct("community.created",n);const r=Ks(n),a=t.cache&&Date.now();t.cache&&(Xt(r,{cachedAt:a}),Sl(r.communities,r.communityUsers));const{communities:o}=r;return{data:pi.community(o[0]),cachedAt:a}},updateCommunity:async(e,t)=>{const n=Re();n.log("community/updateCommunity",e,t);const{data:r}=await n.http.put(`/api/v3/communities/${e}`,zs(t));ct("community.updated",r);const a=Ks(r),o=n.cache&&Date.now();n.cache&&(Xt(a,{cachedAt:o}),Sl(a.communities,a.communityUsers));const{communities:s}=a;return{data:pi.community(s.find((t=>t.communityId===e))),cachedAt:o}},deleteCommunity:async e=>{const t=Re();t.log("community/deleteCommunity",e),await t.http.delete(`/api/v3/communities/${e}`);const n=await kl(e);return ct("community.deleted",{communities:[n.data],categories:[],communityUsers:[],feeds:[],files:[],users:[]}),pi.community(n.data)},joinCommunity:async e=>{const t=Re();t.log("community/joinCommunity",e);const{data:n}=await t.http.post(`/api/v3/communities/${e}/join`);ct("local.community.joined",n);const r=Ks(n),a=t.cache&&Date.now();t.cache&&Xt(r,{cachedAt:a});const{communityUsers:o}=r;return!!o.find((t=>t.communityId===e&&"member"===t.communityMembership))},leaveCommunity:async e=>{const t=Re();t.log("community/leaveCommunity",e);const{data:n}=await t.http.delete(`/api/v3/communities/${e}/leave`);ct("local.community.left",n);const r=Ks(n),a=t.cache&&Date.now();t.cache&&Xt(r,{cachedAt:a});const{communityUsers:o}=r;return!!o.find((t=>t.communityId===e&&"member"!==t.communityMembership))},onCommunityCreated:Tl,onCommunityUpdated:El,onCommunityDeleted:Al,searchCommunities:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`searchCommunities(tmpid: ${o}) > listen`);const s=new id(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`searchCommunities(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getCommunities:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getCommunities(tmpid: ${o}) > listen`);const s=new ud(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`getCommunities(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getCommunity:(e,t)=>Cs(e,t,"communityId",kl,[El,Al,Hl,Jl,Wl,Gl,Ll,Kl,Fl,Ei(Yl,"targetId","community")],{callbackDataSelector:e=>e?pi.community(e):e}),getTrendingCommunities:(e,t,n)=>{const{log:r,cache:a,userId:o}=Re();a||console.log(J);const s=Date.now();r(`getTrendingCommunities(tmpid: ${s}) > listen`);const i=new md(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>qe(l))),()=>{r(`getTrendingCommunities(tmpid: ${s}) > dispose`),c.forEach((e=>e()))}},getRecommendedCommunities:(e,t,n)=>{const{log:r,cache:a,userId:o}=Re();a||console.log(J);const s=Date.now();r(`getRecommendedCommunities(tmpid: ${s}) > listen`);const i=new bd(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>qe(l))),()=>{r(`getRecommendedCommunities(tmpid: ${s}) > dispose`),c.forEach((e=>e()))}},semanticSearchCommunities:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`semanticSearchCommunities(tmpid: ${o}) > listen`);const s=new _d(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`semanticSearchCommunities(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getJoinRequestList:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getJoinRequestList: (tmpid: ${o}) > listen`);const s=new Ed(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>{qe(c)})),()=>{r(`getJoinRequestList (tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},get AmityCommunityMemberStatusFilter(){return Ad}});const Md=async e=>{const t=Re();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&&Xt(n,{cachedAt:r});const{categories:a}=n;return{data:pi.category((null!=a?a:[]).find((t=>t.categoryId===e))),cachedAt:r}};Md.locally=e=>{const t=Re();if(t.log("category/getCategory.locally",e),!t.cache)return;const n=je(["category","get",e]);return n?{data:pi.category(n.data),cachedAt:n.cachedAt}:void 0};const jd=async e=>{const t=Re();t.log("category/queryCategories",e);const n=null!=e?e:{},{page:r,limit:a,includeDeleted:o}=n,s=en(n,["page","limit","includeDeleted"]),i=r?{token:r}:a?{limit:a}:void 0,{data:c}=await t.http.get("/api/v3/community-categories",{params:Object.assign(Object.assign({},s),{isDeleted:bn(o),options:i})}),{paging:l}=c,d=en(c,["paging"]),{categories:u}=d,h=t.cache&&Date.now();if(t.cache){Xt(d,{cachedAt:h});const e=["category","query",Object.assign(Object.assign({},s),{includeDeleted:o,options:i})];Ue(e,{categories:null==u?void 0:u.map(Ce("category")),paging:l})}return{data:null!=u?u:[],cachedAt:h,paging:l}};jd.locally=e=>{var t,n;const r=Re();if(r.log("category/queryCategories.locally",e),!r.cache)return;const a=null!=e?e:{},{page:o,limit:s=10}=a,i=en(a,["page","limit"]),c=o?{token:o}:s?{limit:s}:void 0,l=["category","query",Object.assign(Object.assign({},i),{options:c})],{data:d,cachedAt:u}=null!==(t=je(l))&&void 0!==t?t:{};if(!(null==d?void 0:d.categories.length))return;const h=d.categories.map((e=>je(["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 Ud=Object.freeze({__proto__:null,getCategory:Md,getCategories:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getCategories(tmpid: ${o}) > listen`);const{limit:s}=e,i=en(e,["limit"]),c=null!=s?s:V,{policy:l=H}=null!=n?n:{},d=[],u=["category","collection",{}],h=(n=!1)=>{var r,a;const o=null===(r=je(u))||void 0===r?void 0:r.data,s=null!==(a=null==o?void 0:o.data)&&void 0!==a?a:[];if(!n&&s.length>0&&!(null==o?void 0:o.params.page))return;const d=ge(jd,Object.assign(Object.assign({},i),{limit:n?c:void 0,page:n||null==o?void 0:o.params.page}));ve(d,(({data:n,error:r,loading:a,paging:o})=>{const i={loading:a,error:r,params:{page:null==o?void 0:o.next},data:s};n&&(i.data=[...new Set([...s,...n.map(Ce("category"))])]),Ue(u,i),(n=>{var r,a;let o=null!==(r=n.data.map((e=>je(["category","get",e]))).filter(Boolean).map((({data:e})=>pi.category(e))))&&void 0!==r?r:[];switch(e.includeDeleted||(o=Ne(o,"isDeleted",!1)),e.sortBy){case"firstCreated":o=o.sort(Je);break;case"lastCreated":o=o.sort(Ge);break;default:o=o.sort(He)}t({onNextPage:h,data:o,hasNextPage:!!(null===(a=n.params)||void 0===a?void 0:a.page),loading:n.loading,error:n.error})})(i)}),ye(l))};return d.push((()=>{})),h(!0),()=>{r(`getCategories(tmpid: ${o}) > dispose`),d.forEach((e=>e()))}}});const xd=async e=>{const t=Re();t.log("feed/queryGlobalFeed",e);const n=null!=e?e:{},{queryToken:r,dataTypes:a}=n,o=en(n,["queryToken","dataTypes"]),s=(()=>{if(r)return{token:r}})(),{data:i}=await t.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},o),{dataTypes:a,resolveParent:!!(a&&a.length>0)||void 0,options:s})}),{paging:c}=i,l=en(i,["paging"]),d=nn(l,"communityUsers"),{posts:u}=d,{communities:h}=Ks(d),p=t.cache&&Date.now();if(t.cache){Xt(Object.assign(Object.assign({},d),{communitis:h}));const e=["globalFeed","query",Object.assign(Object.assign({},o),{options:s})];Ue(e,{posts:u.map(Ce("post")),paging:c})}return{data:u.map(pi.post),cachedAt:p,paging:c}};xd.locally=e=>{var t,n;const r=Re();if(r.log("post/queryGlobalFeed.locally",e),!r.cache)return;const a=en(null!=e?e:{},[]),o=["globalFeed","query",Object.assign({},a)],{data:s,cachedAt:i}=null!==(t=je(o))&&void 0!==t?t:{};if(!(null==s?void 0:s.posts.length))return;const c=s.posts.map((e=>je(["post","get",e]))).filter(Boolean).map((({data:e})=>e)).map(pi.post),{paging:l}=s;return c.length===(null===(n=null==s?void 0:s.posts)||void 0===n?void 0:n.length)?{data:c,cachedAt:i,paging:l}:void 0};class Dd extends is{async getRequest(e,t){const{limit:n}=e,r=en(e,["limit"]),a=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v5/me/global-feeds",{params:Object.assign(Object.assign({},r),{options:a})});return o}}var qd;!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"}(qd||(qd={}));class Nd extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.posts.map(Ce("post"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Ce("post"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(r&&(!t.parentPostId||r.data.includes(t.parentPostId))){if(e===qd.OnPostDeleted&&(r.data=r.data.filter((e=>e!==t.postId))),e===qd.OnPostCreated||e===qd.OnPostApproved){if(this.query.dataTypes&&this.query.dataTypes.length>0&&!this.query.dataTypes.includes(t.dataType))return;r.data=[...new Set([t.postId,...r.data])]}e===qd.OnPostDeclined&&(r.data=r.data.filter((e=>e!==t.postId))),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Bd=async e=>{const t=Re();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=>{ae(null==t?void 0:t.code)&&Zt("comment",e)})),t}const a=t.cache&&Date.now();return t.cache&&Xt(r,{cachedAt:a}),{data:r.comments.map((e=>pi.comment(e))),cachedAt:a}};Bd.locally=e=>{var t;const n=Re();if(n.log("comment/getCommentByIds.locally",e),!n.cache)return;const r=e.map((e=>je(["comment","get",e]))).filter(Boolean),a=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:a.map((e=>pi.comment(e))),cachedAt:o.cachedAt}};const Ld=(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})},Fd=async e=>{const t=Re();t.log("story/getStoryByStoryId",e);const n=je(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;mn("story",e)}let r;try{const n=await t.http.get(`/api/v4/stories/${e}`);r=Ld(n.data)}catch(t){throw ae(null==t?void 0:t.code)&&Zt("story",e),t}const a=t.cache&&Date.now();return t.cache&&Xt(r,{cachedAt:a}),{data:r.stories[0],cachedAt:a}};Fd.locally=e=>{const t=Re();t.log("story/getStorybyStoryId",e);const n=je(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;mn("story",e)}const r=t.cache&&Date.now(),a=je(["story","get",e]);if(a)return{data:a.data,cachedAt:r}};const Kd=async(e,t=!1)=>{var n;const r=Re(),a=await Qi(e);await r.http.delete(`/api/v4/comments/${encodeURIComponent(e)}`,{params:{commentId:e,permanent:t}});const o=Object.assign(Object.assign({},a.data),{isDeleted:!0});if(t?ot((()=>Zt("comment",e))):De(["comment","get",e],{isDeleted:!0}),"story"===a.data.referenceType){const e=await Fd(a.data.referenceId);ct("local.story.updated",{stories:[e.data],categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[]})}else{const e=null===(n=je(["post","get",a.data.referenceId]))||void 0===n?void 0:n.data;if(e){let t;t=o.parentId?1:o.childrenNumber+1,e.commentsCount-=t,ct("local.post.updated",{posts:[e],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[],videoStreamings:[]})}}return ct("local.comment.deleted",{comments:[o],commentChildren:[],files:[],users:[],communityUsers:[]}),o},$d=async e=>{const t=Re();let n;t.log("comment/getComment",e),mn("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw ae(null==t?void 0:t.code)&&Zt("comment",e),t}const r=t.cache&&Date.now();t.cache&&Xt(n,{cachedAt:r});const{comments:a}=n;return{data:a.find((t=>t.commentId===e)),cachedAt:r}};$d.locally=e=>{const t=Re();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=je(["comment","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Qd=e=>pc("local.comment.deleted",e),zd=e=>{const t=Re();return it(t,"local.comment.addReaction","local.comment.addReaction",(({comment:n})=>{t.cache?(De(["comment","get",n.commentId],n),e(Rs(n))):e(n)}))},Vd=e=>{const t=Re();return it(t,"local.comment.removeReaction","local.comment.removeReaction",(({comment:n})=>{t.cache?(De(["comment","get",n.commentId],n),e(Rs(n))):e(n)}))};class Hd extends is{async getRequest(e,t){const{limit:n=V,includeDeleted:r}=e,a=en(e,["limit","includeDeleted"]),o={type:a.sortBy||e.limit?"pagination":void 0},s=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({},a),{isDeleted:bn(r),options:s})});return i}}var Jd;!function(e){e.OnCommentCreated="onCommentCreated",e.OnCommentUpdated="onCommentUpdated",e.OnCommentDeleted="onCommentDeleted",e.OnCommentFlagged="onCommentFlagged",e.OnCommentUnflagged="onCommentUnflagged",e.OnCommentReactionAdded="onCommentReactionAdded",e.OnCommentReactionRemoved="onCommentReactionRemoved"}(Jd||(Jd={}));class Wd extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.comments.map(Ce("comment"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.comments.map(Ce("comment"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=je(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===Jd.OnCommentCreated&&(r.data=[...new Set([t.commentId,...r.data])]),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Gd=e=>pc("local.comment.created",e);class Yd extends ps{constructor(e,t){const n=I.default(e),r=["comments","collection",n];super(new Hd(e),n,r,t),this.query=e,this.queryStreamController=new Wd(this.query,this.cacheKey,this.notifyChange.bind(this),Tc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:Gd,action:Jd.OnCommentCreated},{fn:Qd,action:Jd.OnCommentDeleted},{fn:fc,action:Jd.OnCommentCreated},{fn:mc,action:Jd.OnCommentUpdated},{fn:gc,action:Jd.OnCommentDeleted},{fn:yc,action:Jd.OnCommentFlagged},{fn:vc,action:Jd.OnCommentUnflagged},{fn:bc,action:Jd.OnCommentReactionAdded},{fn:wc,action:Jd.OnCommentReactionRemoved},{fn:zd,action:Jd.OnCommentReactionAdded},{fn:Vd,action:Jd.OnCommentReactionRemoved}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["comment","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]).map(pi.comment);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;if(this.query.includeDeleted||(t=Ne(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())||[],a=(null===(n=e.dataTypes)||void 0===n?void 0:n.sort())||[];return a.length===r.length&&r.every(((e,t)=>e===a[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(Je);else t=t.sort(Ge);return t}}var Xd=Object.freeze({__proto__:null,getCommentByIds:Bd,createComment:async e=>{var t;const n=Re();n.log("comment/createComment",e);const{data:r}=await n.http.post("/api/v3/comments",e),{comments:a}=r;if(0===a.length)throw new Error("Comment not created");const o=n.cache&&Date.now();if(n.cache&&Xt(r,{cachedAt:o}),["post","content"].includes(e.referenceType)){const n=null===(t=je(["post","get",e.referenceId]))||void 0===t?void 0:t.data;n&&(n.commentsCount+=1,ct("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=je(["story-reference",e.referenceId]);if(null==t?void 0:t.data){const e=je(["story","get",t.data]);(null==e?void 0:e.data)&&ct("story.updated",{stories:[Object.assign(Object.assign({},e.data),{commentsCount:e.data.commentsCount+1,comments:[...new Set([...e.data.comments,a[0].commentId])]})],categories:[],comments:a,communities:[],communityUsers:r.communityUsers,files:r.files,users:r.users})}}return ct("local.comment.created",r),{data:pi.comment(a[0]),cachedAt:o}},updateComment:async(e,t)=>{const n=Re();n.log("user/updateComment",t);const{data:r}=await n.http.put(`/api/v3/comments/${encodeURIComponent(e)}`,t),a=n.cache&&Date.now();n.cache&&Xt(r,{cachedAt:a}),ct("comment.updated",r);const{comments:o}=r;return{data:pi.comment(o.find((t=>t.commentId===e))),cachedAt:a}},deleteComment:Kd,softDeleteComment:async e=>{Re().log("comment/softDeleteComment",e);return Kd(e)},hardDeleteComment:async e=>{Re().log("comment/hardDeleteComment",e);return Kd(e,!0)},flagComment:async(t,n)=>{const r=Re();r.log("comment/flagComment",t);const a=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,r])=>t!==e.ContentFlagReasonEnum.Others&&r===n)),o={reason:n&&a?n:e.ContentFlagReasonEnum.Others,detail:n&&!a?n:""},{data:s}=await r.http.post(`/api/v3/comments/${encodeURIComponent(t)}/flag`,o);return r.cache&&Xt(s),ct("comment.flagged",s),!!s},unflagComment:async e=>{const t=Re();t.log("comment/unflagComment",e);const{data:n}=await t.http.delete(`/api/v3/comments/${encodeURIComponent(e)}/unflag`);return t.cache&&Xt(n),ct("comment.unflagged",n),!!n},isCommentFlaggedByMe:async e=>{const t=Re();t.log("comment/isCommentFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/comments/${e}/isflagbyme`);return n},onCommentCreated:fc,onCommentUpdated:mc,onCommentDeleted:gc,onCommentFlagged:yc,onCommentUnflagged:vc,onCommentReactionAdded:bc,onCommentReactionRemoved:wc,getComment:(e,t)=>Cs(e,t,"commentId",$d,[Qd,gc,yc,bc,wc,vc,mc,zd,Vd]),getComments:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log("For using Live Collection feature you need to enable Cache!");const o=Date.now();r(`getComments(tmpid: ${o}) > listen`);const s=new Yd(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`getComments(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}}});const Zd=async e=>{const t=Re();let n;t.log("post/getPost",e),mn("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw ae(null==t?void 0:t.code)&&Zt("post",e),t}const r=nn(n,"communityUsers"),a=t.cache&&Date.now();t.cache&&Xt(r,{cachedAt:a});const{posts:o}=r;return{data:o.find((t=>t.postId===e)),cachedAt:a}};Zd.locally=e=>{const t=Re();if(t.log("post/getPost.locally",e),!t.cache)return;const n=je(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const eu=e=>nc("local.post.deleted",e),tu=e=>{const t=Re();return it(t,"local.post.addReaction","local.post.addReaction",(({post:n})=>{t.cache?(De(["post","get",n.postId],n),e(n)):e(n)}))},nu=e=>{const t=Re();return it(t,"local.post.removeReaction","local.post.removeReaction",(({post:n})=>{t.cache?(De(["post","get",n.postId],n),e(n)):e(n)}))},ru=e=>nc("local.post.updated",e),au=e=>[fc,gc,bc,wc,Gd,Qd,zd,Vd].map((t=>({fn:Ei((n=>((e,t,n)=>t((async t=>{var r;const a=null===(r=je(n))||void 0===r?void 0:r.data;a&&a.data.includes(t.referenceId)&&(await Zd(t.referenceId),e(t))})))(n,t,e)),"referenceId","post"),action:qd.OnPostUpdated}))),ou=e=>[{fn:rc,action:qd.OnPostCreated},{fn:ac,action:qd.OnPostUpdated},{fn:ru,action:qd.OnPostUpdated},{fn:oc,action:qd.OnPostDeleted},{fn:cc,action:qd.OnPostFlagged},{fn:lc,action:qd.OnPostUnflagged},{fn:sc,action:qd.OnPostApproved},{fn:ic,action:qd.OnPostDeclined},{fn:dc,action:qd.OnPostReactionAdded},{fn:uc,action:qd.OnPostReactionRemoved},{fn:tu,action:qd.OnPostReactionAdded},{fn:nu,action:qd.OnPostReactionRemoved},{fn:eu,action:qd.OnPostDeleted},...au(e)];class su extends ps{constructor(e,t){const n=I.default(e),r=["customRankingGlobalFeed","collection",n];super(new Dd(e),n,r,t),this.query=e,this.queryStreamController=new Nd(this.query,this.cacheKey,this.notifyChange.bind(this),Xi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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(ou(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=(null!==(a=o.data.map((e=>je(["post","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]).map(pi.post);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class iu extends is{async getRequest(e,t){const{limit:n,dataTypes:r}=e,a=en(e,["limit","dataTypes"]),o=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},a),{dataTypes:r,resolveParent:!!(r&&r.length>0)||void 0,options:o})});return s}}class cu extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.posts.map(Ce("post"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Ce("post"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(r&&(!t.parentPostId||r.data.includes(t.parentPostId))){if(e===qd.OnPostDeleted&&(r.data=r.data.filter((e=>e!==t.postId))),e===qd.OnPostCreated||e===qd.OnPostApproved){if(this.query.dataTypes&&this.query.dataTypes.length>0&&!this.query.dataTypes.includes(t.dataType))return;r.data=[...new Set([t.postId,...r.data])]}e===qd.OnPostDeclined&&(r.data=r.data.filter((e=>e!==t.postId))),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class lu extends ps{constructor(e,t){const n=I.default(e),r=["globalFeed","collection",n];super(new iu(e),n,r,t),this.query=e,this.queryStreamController=new cu(this.query,this.cacheKey,this.notifyChange.bind(this),Xi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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(ou(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=(null!==(a=o.data.map((e=>je(["post","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]).map(pi.post);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class du extends is{async getRequest(e,t){const{userId:n,feedSources:r,dataTypes:a,includeDeleted:o,matchingOnlyParentPost:s,limit:i=V}=e,c=en(e,["userId","feedSources","dataTypes","includeDeleted","matchingOnlyParentPost","limit"]),l=t?{token:t}:{limit:i},{data:d}=await this.http.get(`/api/v4/user-feeds/${n}`,{params:Object.assign(Object.assign({},c),{options:l,dataTypes:(null==a?void 0:a.length)?a:void 0,includePostedFeed:r,isDeleted:bn(o),matchingOnlyParentPost:null!=s?s:!(null==a?void 0:a.length)})});return d}}class uu extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.posts.map(Ce("post"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Ce("post"))])]}))}}reactor(e){return t=>{var n,r;const a=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(a&&(this.query.dataTypes&&0!==this.query.dataTypes.length||a.data.includes(t.parentPostId?t.parentPostId:t.postId))){if(e===qd.OnPostDeleted&&(a.data=a.data.filter((e=>e!==t.postId))),t.parentPostId&&t.isDeleted){const e=null===(r=je(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),Ue(["post","get",e.postId],e)}if(e===qd.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),e===qd.OnPostCreated||e===qd.OnPostApproved){if(this.query.dataTypes&&this.query.dataTypes.length>0&&!this.query.dataTypes.includes(t.dataType))return;a.data=[...new Set([t.postId,...a.data])]}Ue(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class hu extends ps{constructor(e,t){const n=I.default(e),r=["userFeed","collection",n];super(new du(e),n,r,t),this.query=e,this.queryStreamController=new uu(this.query,this.cacheKey,this.notifyChange.bind(this),Xi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:rc,action:qd.OnPostCreated},{fn:ac,action:qd.OnPostUpdated},{fn:ru,action:qd.OnPostUpdated},{fn:oc,action:qd.OnPostDeleted},{fn:cc,action:qd.OnPostFlagged},{fn:lc,action:qd.OnPostUnflagged},{fn:sc,action:qd.OnPostApproved},{fn:ic,action:qd.OnPostDeclined},{fn:dc,action:qd.OnPostReactionAdded},{fn:uc,action:qd.OnPostReactionRemoved},{fn:tu,action:qd.OnPostReactionAdded},{fn:nu,action:qd.OnPostReactionRemoved},{fn:eu,action:qd.OnPostDeleted},{fn:Ei((e=>fc((async t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await Zd(t.referenceId),e(t))}))),"referenceId","post"),action:qd.OnPostUpdated},{fn:Ei((e=>gc((async t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await Zd(t.referenceId),e(t))}))),"referenceId","post"),action:qd.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=(null!==(a=o.data.map((e=>je(["post","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]).map(pi.post);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var pu=Object.freeze({__proto__:null,queryGlobalFeed:xd,getCustomRankingGlobalFeed:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getCustomRankingGlobalFeed(tmpid: ${o}) > listen`);const s=new su(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`getCustomRankingGlobalFeed(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getGlobalFeed:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getGlobalFeed(tmpid: ${o}) > listen`);const s=new lu(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`getGlobalFeed(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getUserFeed:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getUserFeed(tmpid: ${o}) > listen`);const s=new hu(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`getUserFeed(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}}});const fu=async e=>{const t=Re();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=>{ae(null==t?void 0:t.code)&&Zt("post",e)})),t}const a=nn(r,"communityUsers"),o=t.cache&&Date.now();return t.cache&&Xt(a,{cachedAt:o}),{data:a.posts.map(pi.post),cachedAt:o}};fu.locally=e=>{var t;const n=Re();if(n.log("post/getPostByIds.locally",e),!n.cache)return;const r=e.map((e=>je(["post","get",e]))).filter(Boolean),a=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:a.map(pi.post),cachedAt:o.cachedAt}};const mu=async(e,t=!1)=>{var n;const r=Re(),a=await $i(e);if(await r.http.delete(`/api/v4/posts/${encodeURIComponent(e)}`,{params:{postId:e,permanent:t}}),"community"===a.data.targetType){const e=await kl(a.data.targetId),t=(null!==(n=Me(["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));ct("community.updated",{communities:[e.data],categories:[],communityUsers:t,feeds:[],files:[],users:[]})}const o=Object.assign(Object.assign({},a.data),{isDeleted:!0});return t?setTimeout((()=>{Zt("post",e)}),0):De(["post","get",e],{isDeleted:!0}),ct("local.post.deleted",{posts:[o],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[],videoStreamings:[]}),pi.post(o)};class gu extends is{async getRequest(e,t){const{limit:n=V,includeDeleted:r,matchingOnlyParentPost:a}=e,o=en(e,["limit","includeDeleted","matchingOnlyParentPost"]),{dataTypes:s}=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/v5/posts",{params:Object.assign(Object.assign({},o),{isDeleted:bn(r),matchingOnlyParentPost:null!=a?a:!(null==s?void 0:s.length),options:c})});return l}}class yu extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.posts.map(Ce("post"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Ce("post"))])]}))}}reactor(e){return t=>{var n,r;const a=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(t.parentPostId&&t.isDeleted){const e=null===(r=je(["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)),Ue(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===qd.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),e!==qd.OnPostCreated&&e!==qd.OnPostApproved||(a.data=[...new Set([t.postId,...a.data])]),Ue(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const vu=({cacheKey:e,resolveId:t})=>[fc,gc,bc,wc,Gd,Qd,zd,Vd].map((n=>({fn:Ei((r=>((e,t,n,r)=>t((async t=>{var a;const o=null===(a=je(n))||void 0===a?void 0:a.data;o&&o.data.includes(r?r(t.referenceId):t.referenceId)&&(await Zd(t.referenceId),e(t))})))(r,n,e,t)),"referenceId","post"),action:qd.OnPostUpdated})));class bu extends ps{constructor(e,t){const n=I.default(e),r=["posts","collection",n];super(new gu(e),n,r,t),this.query=e,this.queryStreamController=new yu(this.query,this.cacheKey,this.notifyChange.bind(this),Xi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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((e=this.cacheKey,[{fn:rc,action:qd.OnPostCreated},{fn:ac,action:qd.OnPostUpdated},{fn:ru,action:qd.OnPostUpdated},{fn:oc,action:qd.OnPostDeleted},{fn:cc,action:qd.OnPostFlagged},{fn:lc,action:qd.OnPostUnflagged},{fn:sc,action:qd.OnPostApproved},{fn:ic,action:qd.OnPostDeclined},{fn:dc,action:qd.OnPostReactionAdded},{fn:uc,action:qd.OnPostReactionRemoved},{fn:tu,action:qd.OnPostReactionAdded},{fn:nu,action:qd.OnPostReactionRemoved},{fn:eu,action:qd.OnPostDeleted},...vu({cacheKey:e})]));var e}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["post","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]).map(pi.post);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=e;if(this.query.includeDeleted||(n=Ne(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=Ke(n,this.query.feedType)),(null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=Qe(n,this.query.dataTypes)),"firstCreated"===this.query.sortBy)n=n.sort(Je);else n=n.sort(Ge);return n}}class wu extends is{async getRequest(e,t){const n=en(e,["limit"]),{communityId:r,placement:a}=n,o=en(n,["communityId","placement"]),s=a?`/api/v1/pinned-posts/communities/${r}/${a}`:`/api/v1/pinned-posts/communities/${r}`,{data:i}=await this.http.get(s,{params:Object.assign({},o)});return i}}class Cu extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=Re(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users?e.users.map(An):[]});Xt(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.pins.map(Ce("pin"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(Ce("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;r&&(e===qd.OnPostDeleted&&(r.data=r.data.filter((e=>e!==`global#${t.postId}`))),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Iu extends ps{constructor(e,t){const n=I.default(e),r=["pinnedPosts","collection",n];super(new wu(e),n,r,t),this.query=e,this.queryStreamController=new Cu(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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(vu({cacheKey:this.cacheKey,resolveId:e=>`${this.query.placement}#${e}`}))}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;let s=(null!==(a=o.data.map((e=>je(["pin","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]).map(pi.pinnedPost);s=this.applyFilter(s),(this.shouldNotify(s)||"event"!==e)&&this.callback({data:s,loading:t,error:n})}applyFilter(e){let t=e;if("lastCreated"===this.query.sortBy)t=t.sort((({post:e},{post:t})=>Ge({createdAt:null==e?void 0:e.createdAt},{createdAt:null==t?void 0:t.createdAt})));return t}}class Su extends is{async getRequest(e,t){const n=en(e,["limit"]),{data:r}=await this.http.get("/api/v1/pinned-posts/global",{params:Object.assign({},n)});return r}}class _u extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=Re(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users.map(An)});Xt(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.pins.map(Ce("pin"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(Ce("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;r&&(e===qd.OnPostDeleted&&(r.data=r.data.filter((e=>e!==`global#${t.postId}`))),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class ku extends ps{constructor(e,t){const n=I.default(e),r=["pinnedPosts","collection",n];super(new Su(e),n,r,t),this.query=e,this.queryStreamController=new _u(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:eu,action:qd.OnPostDeleted},{fn:oc,action:qd.OnPostDeleted},...vu({cacheKey:this.cacheKey,resolveId:e=>`global#${e}`})])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=(null!==(a=o.data.map((e=>je(["pin","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]).map(pi.pinnedPost);(this.shouldNotify(s)||"event"!==e)&&this.callback({data:s,loading:t,error:n})}}class Ou extends is{async getRequest(e,t){const{limit:n=V}=e,r=en(e,["limit"]),a={type:e.limit?"pagination":void 0},o=t?Object.assign(Object.assign({},a),{token:t}):Object.assign(Object.assign({},a),{limit:n}),{data:s}=await this.http.get("/api/v1/semantic-search/posts",{params:Object.assign(Object.assign({},r),{options:o})});return s}}function Tu(e){return e.posts.map((t=>{const n=e.searchResult.find((e=>e.postId===t.postId));return`${t.postId}:${n.score}`}))}function Eu(e){return(null!=e?e:[]).map((e=>e.split(":")[0]))}class Au extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:Tu(e)});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...Tu(e)])]}))}}reactor(e){return t=>{var n,r;const a=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(t.parentPostId&&t.isDeleted){const e=null===(r=je(["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)),Ue(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===qd.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),e!==qd.OnPostCreated&&e!==qd.OnPostApproved||(a.data=[...new Set([t.postId,...a.data])]),Ue(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Ru extends ps{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=I.default(n),a=["posts","collection",r];super(new Ou(n),r,a,t),this.query=n,this.queryStreamController=new Au(this.query,this.cacheKey,this.notifyChange.bind(this),Zi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:ac,action:qd.OnPostUpdated},{fn:oc,action:qd.OnPostDeleted},{fn:cc,action:qd.OnPostFlagged},{fn:lc,action:qd.OnPostUnflagged},{fn:sc,action:qd.OnPostApproved},{fn:ic,action:qd.OnPostDeclined},{fn:dc,action:qd.OnPostReactionAdded},{fn:uc,action:qd.OnPostReactionRemoved},{fn:Ei((e=>fc((async t=>{const n=je(this.cacheKey);Eu(null==n?void 0:n.data).includes(t.referenceId)||(await $i(t.referenceId),e(t))}))),"referenceId","post"),action:qd.OnPostUpdated},{fn:Ei((e=>gc((async t=>{const n=je(this.cacheKey);Eu(null==n?void 0:n.data).includes(t.referenceId)||(await $i(t.referenceId),e(t))}))),"referenceId","post"),action:qd.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=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})=>je(["post","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]).map(pi.post);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,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=Qe(t,this.query.dataTypes)),t}}class Pu extends is{async getRequest(e,t){const{limit:n=V,matchingOnlyParentPost:r,hashtags:a,dataTypes:o,targetType:s="all"}=e,i=en(e,["limit","matchingOnlyParentPost","hashtags","dataTypes","targetType"]),c={type:i.sortBy||e.limit?"pagination":void 0},l=t?Object.assign(Object.assign({},c),{token:t}):Object.assign(Object.assign({},c),{limit:n}),{data:d}=await this.http.get("/api/v1/search/posts",{params:Object.assign(Object.assign({},i),{hashtags:a,dataTypes:o,targetType:s,matchingOnlyParentPost:null!=r?r:!(null==o?void 0:o.length),options:l})});return d}}class Mu extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.posts.map(Ce("post"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Ce("post"))])]}))}}reactor(e){return t=>{var n,r;const a=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(t.parentPostId&&t.isDeleted){const e=null===(r=je(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),Ue(["post","get",e.postId],e)}e===qd.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),e!==qd.OnPostCreated&&e!==qd.OnPostApproved||(a.data=[...new Set([t.postId,...a.data])]),Ue(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class ju extends ps{constructor(e,t){const n=I.default(e),r=["posts","collection",n];super(new Pu(e),n,r,t),this.query=e,this.queryStreamController=new Mu(this.query,this.cacheKey,this.notifyChange.bind(this),Xi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:rc,action:qd.OnPostCreated},{fn:ac,action:qd.OnPostUpdated},{fn:ru,action:qd.OnPostUpdated},{fn:oc,action:qd.OnPostDeleted},{fn:cc,action:qd.OnPostFlagged},{fn:lc,action:qd.OnPostUnflagged},{fn:sc,action:qd.OnPostApproved},{fn:ic,action:qd.OnPostDeclined},{fn:dc,action:qd.OnPostReactionAdded},{fn:uc,action:qd.OnPostReactionRemoved},{fn:tu,action:qd.OnPostReactionAdded},{fn:nu,action:qd.OnPostReactionRemoved},{fn:eu,action:qd.OnPostDeleted},{fn:Ei((e=>fc((async t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await Zd(t.referenceId),e(t))}))),"referenceId","post"),action:qd.OnPostUpdated},{fn:Ei((e=>gc((async t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await Zd(t.referenceId),e(t))}))),"referenceId","post"),action:qd.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["post","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]).map(pi.post);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=e;if((null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=Qe(n,this.query.dataTypes)),"firstCreated"===this.query.sortBy)n=n.sort(Je);else n=n.sort(Ge);return n}}var Uu=Object.freeze({__proto__:null,getPostByIds:fu,createPost:async e=>{const t=Re();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);ct("post.created",n);const r=Xi(n),a=t.cache&&Date.now();t.cache&&Xt(r,{cachedAt:a});const{posts:o}=r;return{data:pi.post(o[0]),cachedAt:a}},editPost:async(e,t)=>{const n=Re();n.log("user/editPost",t);const{data:r}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,t),a=nn(r,"communityUsers"),o=n.cache&&Date.now();n.cache&&Xt(a,{cachedAt:o}),ct("local.post.updated",a);const{posts:s}=a;return{data:pi.post(s.find((t=>t.postId===e))),cachedAt:o}},deletePost:mu,softDeletePost:async e=>{Re().log("post/softDeletePost",e);const t=await mu(e,!1);return pi.post(t)},hardDeletePost:async e=>{Re().log("post/hardDeletePost",e);const t=await mu(e,!0);return pi.post(t)},approvePost:async e=>{const t=Re();t.log("post/approvePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/approve`);ct("post.approved",n),"community"===n.posts[0].targetType&&ct("community.updated",n);const r=nn(n,"communityUsers"),a=t.cache&&Date.now();return t.cache&&Xt(r,{cachedAt:a}),{data:pi.post(r.posts.find((t=>t.postId===e))),cachedAt:a}},declinePost:async e=>{const t=Re();t.log("post/declinePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/decline`);"community"===n.posts[0].targetType&&ct("community.updated",n),ct("post.declined",n);const r=nn(n,"communityUsers"),a=t.cache&&Date.now();return t.cache&&Xt(r,{cachedAt:a}),{data:pi.post(n.posts.find((t=>t.postId===e))),cachedAt:a}},flagPost:async(t,n)=>{const r=Re();r.log("post/flagPost",t);const a=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,r])=>t!==e.ContentFlagReasonEnum.Others&&r===n)),o={reason:n&&a?n:e.ContentFlagReasonEnum.Others,detail:n&&!a?n:""},{data:s}=await r.http.post(`/api/v3/posts/${encodeURIComponent(t)}/flag`,o);return r.cache&&Xt(nn(s,"communityUsers")),ct("post.flagged",s),!!s},unflagPost:async e=>{const t=Re();t.log("post/unflagPost",e);const{data:n}=await t.http.delete(`/api/v3/posts/${encodeURIComponent(e)}/unflag`);return t.cache&&Xt(nn(n,"communityUsers")),ct("post.unflagged",n),!!n},isPostFlaggedByMe:async e=>{const t=Re();t.log("post/isPostFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/posts/${e}/isflagbyme`);return n},createClipPost:async e=>{const t=Re();t.log("post/createPost",e);const{data:n}=await t.http.post("/api/v4/posts",e);ct("post.created",n);const r=nn(n,"communityUsers"),a=t.cache&&Date.now();t.cache&&Xt(r,{cachedAt:a});const{posts:o}=r;return{data:pi.post(o[0]),cachedAt:a}},createAudioPost:async e=>{const t=Re();t.log("post/createAudioPost",e);const{data:n}=await t.http.post("/api/v4/posts",e);ct("post.created",n);const r=Xi(n),a=t.cache&&Date.now();return t.cache&&Xt(r,{cachedAt:a}),{data:Us(null==r?void 0:r.posts[0]),cachedAt:a}},createMixedMediaPost:async e=>{var t;const n=Re();n.log("post/createMixedMediaPost",e);const{data:r}=await n.http.post("/api/v4/posts",e);ct("post.created",r);const a=Xi(r),o=n.cache&&Date.now();return n.cache&&Xt(a,{cachedAt:o}),{data:Us(null===(t=null==a?void 0:a.posts)||void 0===t?void 0:t[0]),cachedAt:o}},onPostCreated:rc,onPostUpdated:ac,onPostDeleted:oc,onPostApproved:sc,onPostDeclined:ic,onPostFlagged:cc,onPostUnflagged:lc,onPostReactionAdded:dc,onPostReactionRemoved:uc,getPost:(e,t)=>Cs(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?pi.post(e.data):n}))}),"postId",$i,[sc,ic,tu,nu,t=>oc((n=>{var r;let a=n;if(n.parentPostId===e&&n.isDeleted){const e=null===(r=je(["post","get",n.parentPostId]))||void 0===r?void 0:r.data;e&&(e.children=e.children.filter((e=>e!==n.postId)),Ue(["post","get",e.postId],e),a=e)}t(a)})),cc,e=>dc((t=>{e(t)})),e=>uc((t=>{e(t)})),lc,ac,ru,eu,Ei((t=>fc((async n=>{n.referenceId===e&&(await $i(e),t(n))}))),"referenceId","post"),Ei((t=>gc((async n=>{n.referenceId===e&&(await $i(e),t(n))}))),"referenceId","post")]),getPosts:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getPosts(tmpid: ${o}) > listen`);const s=new bu(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`getPosts(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getPinnedPosts:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getPinnedPosts(tmpid: ${o}) > listen`);const s=new Iu(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`getPinnedPosts(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},getGlobalPinnedPosts:(e,t,n)=>{const{log:r,cache:a}=Re(),o=Date.now();r(`getGlobalPinnedPosts(tmpid: ${o}) > listen`);const s=new ku(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`getGlobalPinnedPosts(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},semanticSearchPosts:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`semanticSearchPosts(tmpid: ${o}) > listen`);const s=new Ru(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`semanticSearchPosts(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},searchPostsByHashtag:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`searchPostsByHashtag(tmpid: ${o}) > listen`);const s=new ju(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`searchPostsByHashtag(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}}});const xu=async e=>{const t=Re();t.log("stream/getStream",e);const{data:n}=await t.http.get(`/api/v3/video-streaming/${e}`),r=t.cache&&Date.now();t.cache&&Xt(n,{cachedAt:r});const{videoStreamings:a}=n;return{data:a.find((t=>t.streamId===e)),cachedAt:r}};xu.locally=e=>{const t=Re();if(t.log("stream/getStream",e),!t.cache)return;const n=je(["stream","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Du=e=>{const t=Re();return it(t,"stream/onStreamStarted","video-streaming.didStart",(t=>{Xt(t),e(t.videoStreamings[0])}))},qu=e=>{const t=Re();return it(t,"stream/onStreamStropped","video-streaming.didStop",(t=>{Xt(t),e(t.videoStreamings[0])}))},Nu=e=>{const t=Re();return it(t,"stream/onStreamRecorded","video-streaming.didRecord",(t=>{Xt(t),e(t.videoStreamings[0])}))},Bu=e=>{const t=Re();return it(t,"stream/onStreamFlagged","video-streaming.didFlag",(t=>{Xt(t),e(t.videoStreamings[0])}))},Lu=e=>{const t=Re();return it(t,"stream/onStreamTerminated","video-streaming.didTerminate",(t=>{Xt(t),e(t.videoStreamings[0])}))},Fu=(e,t)=>Cs(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?pi.stream(e.data):n}))}),"streamId",xu,[Nu,Du,qu,Bu,Lu,Wc]);Fu.locally=e=>{const t=Re();if(t.log("stream/getStreamById",e),!t.cache)return;const n=je(["stream","get",e]);return n?{data:pi.stream(n.data),cachedAt:n.cachedAt}:void 0};const Ku=async e=>{const t=Re();t.log("stream/queryStreams",e);const n=null!=e?e:{},{page:r,limit:a}=n,o=en(n,["page","limit"]),s=r?{token:r}:a?{limit:a}:void 0,{data:i}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},o),{options:s})}),{paging:c,results:l}=i,{videoStreamings:d}=l,u=t.cache&&Date.now();return t.cache&&Xt(l,{cachedAt:u}),{data:d,cachedAt:u,paging:c}};var $u=Object.freeze({__proto__:null,createStream:async e=>{const t=Re();t.log("stream/createStream",e);const{data:n}=await t.http.post("/api/v3/video-streaming",e),r=t.cache&&Date.now();t.cache&&Xt(n,{cachedAt:r});const{videoStreamings:a}=n;return{data:pi.stream(a[0]),cachedAt:r}},updateStream:async(e,t)=>{const n=Re();n.log("stream/updateStream",e,t);const{data:r}=await n.http.put(`/api/v3/video-streaming/${e}`,t),a=n.cache&&Date.now();n.cache&&Xt(r,{cachedAt:a});const{videoStreamings:o}=r;return{data:pi.stream(o.find((t=>t.streamId===e))),cachedAt:a}},deleteStream:async e=>{const t=Re();t.log("stream/deleteStream",e);const n=await xu(e),{data:r}=await t.http.delete(`/api/v3/video-streaming/${e}`),{success:a}=r,o=Object.assign(Object.assign({},n.data),{isDeleted:!0});return De(["stream","get",e],o),a},disposeStream:async e=>{const t=Re();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&&Xt(n,{cachedAt:r});const{videoStreamings:a}=n;return{data:a.find((t=>t.streamId===e)),cachedAt:r}},editStream:async(e,t)=>{const n=Re();n.log("stream/updateStream",e,t);const{data:r}=await n.http.put(`/api/v3/video-streaming/${e}`,t),a=n.cache&&Date.now();n.cache&&Xt(r,{cachedAt:a});const{videoStreamings:o}=r;return{data:pi.stream(o.find((t=>t.streamId===e))),cachedAt:a}},onStreamStarted:Du,onStreamStopped:qu,onStreamRecorded:Nu,onStreamFlagged:Bu,onStreamTerminated:Lu,onStreamViewerBanned:Wc,onStreamViewerUnbanned:e=>{const t=Re();return it(t,"stream/onStreamViewerDidUnban","video-streaming.viewerDidUnban",(async t=>{var n;const{list:r}=t;await Promise.all(r.map((({streamId:e})=>xu(e))));const a=null===(n=je(["stream","get",r[0].streamId]))||void 0===n?void 0:n.data;a&&e(a)}))},getStreamById:Fu,getStreams:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getStreams(tmpid: ${o}) > listen`);const{limit:s}=e,i=en(e,["limit"]),c=null!=s?s:V,{policy:l=H}=null!=n?n:{},d=[],u=["streams","collection",e],h=t=>{let n=Ne(t,"isDeleted",e.isDeleted);return n=n.sort("lastCreated"===e.sortBy?Ge:Je),n},p=(e,n=!1)=>{var r,a;const o=null!==(r=e.data.map((e=>je(["stream","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];t({onNextPage:m,data:n?h(o):o,hasNextPage:!!(null===(a=e.params)||void 0===a?void 0:a.page),loading:e.loading,error:e.error})},f=e=>e=>{var t;const n=null===(t=je(u))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.streamId,...n.data])],Ue(u,n),p(n,!0))},m=(e=!1)=>{var t,n;const r=null===(t=je(u))||void 0===t?void 0:t.data,a=null!==(n=null==r?void 0:r.data)&&void 0!==n?n:[];if(!e&&a.length>0&&!(null==r?void 0:r.params.page))return;const o=ge(Ku,Object.assign(Object.assign({},i),{limit:e?c:void 0,page:e||null==r?void 0:r.params.page}));ve(o,(({data:e,error:t,loading:n,paging:r})=>{const o={loading:n,error:t,params:{page:null==r?void 0:r.next},data:a};e&&(o.data=[...new Set([...a,...e.map(Ce("stream"))])]),Ue(u,o),p(o)}),ye(l))};return d.push(Nu(f()),Du(f()),qu(f())),m(!0),()=>{r(`getStreams(tmpid: ${o}) > dispose`),d.forEach((e=>e()))}}});const Qu=e=>{const t=Re();return it(t,"room/onRoomStartBroadcasting","room.startBroadcasting",(t=>{Xt(t),e(t.rooms[0])}))},zu=e=>{const t=Re();return it(t,"room/onRoomWaitingReconnect","room.waitingReconnect",(t=>{Xt(t),e(t.rooms[0])}))},Vu=e=>{const t=Re();return it(t,"room/onRoomEndBroadcasting","room.endBroadcasting",(t=>{Xt(t),e(t.rooms[0])}))},Hu=e=>{const t=Re();return it(t,"room/onRoomRecordedAvailable","room.recordedAvailable",(t=>{Xt(t),e(t.rooms[0])}))},Ju=async e=>{const t=Re();let n;t.log("room/getRoomById",e),mn("room",e);try{n=(await t.http.get(`/api/v1/rooms/${e}`)).data}catch(t){throw ae(null==t?void 0:t.code)&&Zt("room",e),t}const r=t.cache&&Date.now();return t.cache&&Xt(n,{cachedAt:r}),{data:n.rooms[0],cachedAt:r}};Ju.locally=e=>{const t=Re();t.log("room/getRoomById.locally",e),mn("room",e);const n=t.cache&&Date.now(),r=je(["room","get",e]);if(r)return{data:r.data,cachedAt:n}};class Wu extends is{async getRequest(e,t){const{limit:n=V,includeDeleted:r}=e,a=en(e,["limit","includeDeleted"]),o={type:a.sortBy||e.limit?"pagination":void 0},s=t?Object.assign(Object.assign({},o),{token:t}):Object.assign(Object.assign({},o),{limit:n}),{data:i}=await this.http.get("/api/v1/rooms",{params:Object.assign(Object.assign({},a),{isDeleted:bn(r),options:s})});return i}}var Gu;!function(e){e.OnRoomCreated="OnRoomCreated",e.OnRoomUpdated="OnRoomUpdated",e.OnRoomDeleted="OnRoomDeleted",e.OnRoomStartBroadcasting="OnRoomStartBroadcasting",e.OnRoomEndBroadcasting="OnRoomEndBroadcasting",e.OnRoomParticipantJoined="OnRoomParticipantJoined",e.OnRoomParticipantLeft="OnRoomParticipantLeft"}(Gu||(Gu={}));class Yu extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.rooms.map(Ce("room"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.rooms.map(Ce("room"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;r&&(e===Gu.OnRoomDeleted&&(r.data=r.data.filter((e=>e!==t._id))),e===Gu.OnRoomCreated&&(r.data=[...new Set([t._id,...r.data])]),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Xu extends ps{constructor(e,t){const n=I.default(e),r=["rooms","collection",n];super(new Wu(e),n,r,t),this.query=e,this.queryStreamController=new Yu(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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:Qu,action:Gu.OnRoomStartBroadcasting},{fn:Vu,action:Gu.OnRoomEndBroadcasting},{fn:Hu,action:Gu.OnRoomUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["room","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]).map((e=>e));(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;if(this.query.includeDeleted||(t=Ne(t,"isDeleted",!1)),this.query.statuses&&this.query.statuses.length>0&&(t=t.filter((e=>{var t;return null===(t=this.query.statuses)||void 0===t?void 0:t.includes(e.status)}))),this.query.type&&(t=Ne(t,"type",this.query.type)),"firstCreated"===this.query.sortBy)t=t.sort(Je);else t=t.sort(Ge);return t}}var Zu=Object.freeze({__proto__:null,createRoom:async e=>{const t=Re();t.log("room/createRoom",e);const{data:n}=await t.http.post("/api/v1/rooms",e);ct("local.room.created",n);const r=t.cache&&Date.now();t.cache&&Xt(n,{cachedAt:r});const{rooms:a}=n;return{data:js(a[0]),cachedAt:r}},updateRoom:async(e,t)=>{const n=Re();n.log("room/updateRoom",{roomId:e,bundle:t});const{data:r}=await n.http.put(`/api/v1/rooms/${e}`,t);ct("local.room.updated",r);const a=n.cache&&Date.now();n.cache&&Xt(r,{cachedAt:a});const{rooms:o}=r;return{data:o[0],cachedAt:a}},deleteRoom:async e=>{const t=Re();t.log("room/deleteRoom",{roomId:e}),await t.http.delete(`/api/v1/rooms/${e}`),ct("local.room.deleted",{rooms:[{_id:e}]})},stopRoom:async e=>{const t=Re();t.log("room/stopRoom",{roomId:e});const{data:n}=await t.http.post(`/api/v1/rooms/${e}/stop`);ct("local.room.stopped",n);const r=t.cache&&Date.now();t.cache&&Xt(n,{cachedAt:r});const{rooms:a}=n;return{data:a[0],cachedAt:r}},getBroadcasterData:async e=>{const t=Re();t.log("room/getBroadcasterData",{roomId:e});const{data:n}=await t.http.get(`/api/v1/rooms/${e}/token`);return n},getRecordedUrl:async e=>{const t=Re();t.log("room/getRecordedUrl",{roomId:e});const{data:n}=await t.http.get(`/api/v1/rooms/${e}/recorded`);return n},onRoomStartBroadcasting:Qu,onRoomWaitingReconnect:zu,onRoomEndBroadcasting:Vu,onRoomRecordedAvailable:Hu,onRoomParticipantInviting:e=>{const t=Re();return it(t,"room/onRoomParticipantInviting","room.participantInviting",(t=>{Xt(t),e(t.rooms[0])}))},onRoomParticipantJoined:e=>{const t=Re();return it(t,"room/onRoomParticipantJoined","room.participantJoined",(t=>{Xt(t),e(t.rooms[0])}))},onRoomParticipantLeft:e=>{const t=Re();return it(t,"room/onRoomParticipantLeft","room.participantLeft",(t=>{Xt(t),e(t.rooms[0])}))},onRoomCreated:e=>{const t=Re();return it(t,"room/onRoomCreated","local.room.created",(t=>{Xt(t),e(t.rooms[0])}))},onRoomUpdated:e=>{const t=Re();return it(t,"room/onRoomUpdated","local.room.updated",(t=>{Xt(t),e(t.rooms[0])}))},onRoomDeleted:e=>{const t=Re();return it(t,"room/onRoomDeleted","local.room.deleted",(t=>{Xt(t),e(t.rooms[0])}))},onRoomStopped:e=>{const t=Re();return it(t,"room/onRoomStopped","local.room.stopped",(t=>{Xt(t),e(t.rooms[0])}))},getRoom:(e,t)=>Cs(e,t,"_id",Ju,[Vu,Qu,zu,Hu]),getRooms:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getRooms(tmpid: ${o}) > listen`);const s=new Xu(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`getRooms(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}}});const eh=async e=>{const t=Re();t.log("poll/getPoll",e);const{data:n}=await t.http.get(`/api/v3/polls/${e}`),r=t.cache&&Date.now();t.cache&&Xt(n,{cachedAt:r});const{polls:a}=n;return{data:a.find((t=>t.pollId===e)),cachedAt:r}};eh.locally=e=>{const t=Re();if(t.log("poll/getPoll",e),!t.cache)return;const n=je(["poll","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const th=e=>{const t=Re();return it(t,"poll/onPollUpdated","poll.updated",(n=>{t.cache&&Xt(n),e(n.polls[0])}))},nh=e=>{const t=Re();return it(t,"poll/onPollDeleted","poll.deleted",(n=>{t.cache&&Xt(n),e(n.polls[0])}))};var rh=Object.freeze({__proto__:null,createPoll:async e=>{const t=Re();t.log("post/createPoll",e);const{data:n}=await t.http.post("/api/v3/polls",e),r=t.cache&&Date.now();t.cache&&Xt(n,{cachedAt:r});const{polls:a}=n;return{data:a[0],cachedAt:r}},closePoll:async e=>{const t=Re();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&&Xt(n,{cachedAt:r}),ct("poll.updated",n);const{polls:a}=n;return{data:a.find((t=>t.pollId===e)),cachedAt:r}},deletePoll:async e=>{const t=Re();t.log("poll/deletePoll",e);const n=await eh(e),{data:r}=await t.http.delete(`/api/v3/polls/${e}`),{success:a}=r,o=Object.assign(Object.assign({},n.data),{isDeleted:!0});return De(["poll","get",e],o),ct("poll.deleted",{polls:[o],users:[]}),a},votePoll:async(e,t)=>{const n=Re();n.log("user/votePoll",e);const{data:r}=await n.http.post(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:t}),a=n.cache&&Date.now();n.cache&&Xt(r,{cachedAt:a});const{polls:o}=r;return ct("poll.updated",r),{data:o.find((t=>t.pollId===e)),cachedAt:a}},unvotePoll:async e=>{const t=Re();t.log("user/unvotePoll",e);const{data:n}=await t.http.put(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:[]}),r=t.cache&&Date.now();t.cache&&Xt(n,{cachedAt:r}),ct("poll.updated",n)},onPollUpdated:th,onPollDeleted:nh,getPoll:(e,t)=>Cs(e,t,"pollId",eh,[th,nh])});const ah={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};function oh(e){const n=new Uint8Array(e);let r="";return n.forEach((e=>{r+=String.fromCharCode(e)})),t.btoa(r)}function sh(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,ah,!1,["sign"])}async function ih({bufferCurrentUsage:e,getActiveStreams:t,updateUsage:n,dispose:r}){const a=e();if(a.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=w.default.v4(),a=`nonceStr=${r}&timestamp=${e}&data=${n}==`,o=(new TextEncoder).encode(a),s=await sh("-----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:oh(await crypto.subtle.sign(ah,s,o)),nonceStr:r}}({timestamp:n,streams:a});if(!o||!o.signature)throw new Error("Signature is undefined");const s={signature:o.signature,nonceStr:o.nonceStr,timestamp:n,streams:a},i=Re();return await i.http.post("/api/v3/user-event/video-streaming",s),t().length||e().length||r(),!0}catch(e){return a.forEach((e=>n(e))),!1}}class ch{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((()=>{ih({bufferCurrentUsage:this.bufferCurrentUsage.bind(this),getActiveStreams:this.getActiveStreams.bind(this),updateUsage:this.updateUsage.bind(this),dispose:this.dispose.bind(this)})}),2e4)}}let lh=null;class dh{constructor(e,t,n){this._SDKUnsubscribers=[],this.player=e,this.resolution=t,this._startTime=null,this._usageCollector=lh||(lh=new ch,lh),this._usageCollector.registerStream(e.id),this._sessionId=String(w.default.v4()),this._controller=new AbortController,this._observer=new MutationObserver((t=>{t.forEach((t=>{t.removedNodes.forEach((t=>{t===e&&(this._unregisterEvents(),this._SDKUnsubscribers.forEach((e=>null==e?void 0:e())))}))}))})),this._SDKUnsubscribers.push(Wc((e=>{e.watcherUrl||(this.player.pause(),this.player.removeAttribute("src"),this.player.load(),this.player.remove())})))}_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 uh=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(!S.default.isSupported())throw new Error("This browswer does not support hls, unable to play stream");const{data:n}=await xu(t),{watcherUrl:r,status:a,recordings:o=[],resolution:s}=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 S.default;if(c.attachMedia(i),"recorded"!==a){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 dh(i,s,t).registerEvents(),i}});const hh=e=>{const t=(e=>{var t;const n=Re(),r=new Date,a=r.getTime()+31536e6,o=new Date(a).toISOString();let s=null===(t=je(["storyTarget","get",e.targetId]))||void 0===t?void 0:t.data;return s||(s={targetType:e.targetType,targetId:e.targetId,lastStoryExpiresAt:o,targetPublicId:e.targetId,targetUpdatedAt:r.toISOString()},Xt({storyTargets:[s]})),{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(a).toISOString()},e)],categories:[],communityUsers:[],comments:[],files:[],users:[],communities:[]}})(e);return Xt(t),t},ph=({payload:e,formData:t,isVideo:n=!1},r)=>{if(t){const a=t.getAll("files")[0]||void 0;if(!a)return;const o=Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileId:void 0,fileData:a.uri})});return n&&(o.data.videoFileId={original:void 0}),r(hh(o))}return r(hh(Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileData:null})})))},fh=async e=>{const t=Re();t.log("post/createStory",e);const n=await t.http.post("/api/v4/stories",e),r=Ld(n.data);t.cache&&Xt(r),Ue(["story-sync-state",e.targetId],"synced"),ct("local.story.created",r);const a=t.cache&&Date.now();return{data:r.stories.length>0?r.stories[0]:void 0,cachedAt:a}},mh=async({targetId:e,targetType:t})=>{var n,r;if(!je(["storyTarget","get",e])){let a={targetId:e,targetType:t};if("community"===t){const t=await kl(e);a=Object.assign(Object.assign({},a),{targetPublicId:t.data.communityId,targetUpdatedAt:null!==(n=t.data.updatedAt)&&void 0!==n?n:(new Date).toISOString()})}if("user"===t){const t=await wi(e);a=Object.assign(Object.assign({},a),{targetPublicId:t.data.userPublicId,targetUpdatedAt:null!==(r=t.data.updatedAt)&&void 0!==r?r:(new Date).toISOString()})}Ue(["storyTarget","get",e],a)}},gh=e=>e?je(["story","get",e]):{data:void 0,cachedAt:void 0},yh=async(e,t=!1)=>{var n,r,a;const o=Re();let s;if(o.log("story/deleteStory",e),o.cache&&(s=gh(e),null==s?void 0:s.data)){const{data:o}=s;if(ct("local.story.deleted",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[Object.assign(Object.assign({},o),{isDeleted:!0})]}),"synced"!==o.syncState){t?qe(["story","get",e]):Ue(["story","get",e],Object.assign(Object.assign({},s.data),{isDeleted:!0}));const r=null===(n=Me(["story","get"]))||void 0===n?void 0:n.filter((e=>"synced"!==e.data.syncState&&e.data.targetId===o.targetId&&!0!==e.data.isDeleted));if(r&&r.length>0){const e=r.reduce(((e,t)=>{const n=new Date(t.data.expiresAt||0);return n>e?n:e}),new Date(0));Ue(["story-expire",s.data.targetId],e.toISOString())}else qe(["story-expire",s.data.targetId]);return!0}const i=null===(r=je(["storyTarget","get",o.targetId]))||void 0===r?void 0:r.data,c=null===(a=Me(["story","get"]))||void 0===a?void 0:a.filter((e=>"synced"===e.data.syncState&&e.data.targetId===o.targetId&&!0!==e.data.isDeleted));let l;c&&c.length>0&&(l=null==c?void 0:c.reduce(((e,t)=>{const n=new Date(t.data.expiresAt||0);return n>e?n:e}),new Date(0))),i&&Ue(["storyTarget","get",o.targetId],Object.assign(Object.assign({},i),{lastStoryExpiresAt:l}))}return(await o.http.delete(`/api/v4/stories/${e}`,{params:{permanent:t}})).data.success},vh=e=>{const t=Re(),n=[it(t,"onStoryUpdated","story.updated",(async t=>{const n=Ld(t);Xt(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},bh=e=>{const t=Re(),n=[it(t,"onStoryUpdated","local.story.updated",(async t=>{Xt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},wh=e=>{const t=Re(),n=[it(t,"onStoryReactionAdded","story.reactionAdded",(async t=>{const{reactions:n}=t,r=en(t,["reactions"]),a=Ld(r),o=Wi("story.reactionAdded",Object.assign(Object.assign({},a),{reactions:n}));Xt(o),e(o.stories)}))];return()=>{n.forEach((e=>e()))}},Ch=e=>{const t=Re(),n=[it(t,"onStoryReactionAdded","local.story.reactionAdded",(async t=>{Xt({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},Ih=e=>{const t=Re(),n=[it(t,"onStoryReactionRemoved","story.reactionRemoved",(async t=>{const{reactions:n}=t,r=en(t,["reactions"]),a=Ld(r),o=Wi("story.reactionRemoved",Object.assign(Object.assign({},a),{reactions:n}));Xt(o),e(o.stories)}))];return()=>{n.forEach((e=>e()))}},Sh=e=>{const t=Re(),n=[it(t,"onStoryReactionRemoved","local.story.reactionRemoved",(async t=>{Xt({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},_h=e=>{e.forEach((e=>{const t=je(["story-expire",e.targetId]),n=new Date(e.expiresAt||0);n<new Date((null==t?void 0:t.data)||0)||Ue(["story-expire",e.targetId],n.toISOString())}))},kh=e=>{e.forEach((e=>{Ue(["story-reference",e.storyId],e.referenceId)}))},Oh=async({targetType:e,targetId:t,options:n})=>{const r=Re();r.log("story/getActiveStoriesByTarget");const a=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"}}}),s=Ld(o.data);return r.cache&&(Xt(s),_h(s.stories),kh(s.stories)),{data:s.stories,cachedAt:a,paging:{next:void 0,previous:void 0}}},Th=e=>{const t=Re(),n=[it(t,"onStoryCreated","story.created",(async t=>{const n=Ld(t,!0);Xt(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Eh=e=>{const t=Re(),n=[it(t,"onStoryCreated","local.story.created",(async t=>{Xt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},Ah=e=>{const t=Re(),n=[it(t,"onStoryDeleted","story.deleted",(async t=>{const n=Ld(t);Xt(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Rh=e=>{const t=Re(),n=[it(t,"onStoryDeleted","local.story.deleted",(async t=>{Xt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},Ph=e=>{const t=Re();return it(t,"onStoryError","local.story.error",(async t=>{Xt(t),e(t.stories)}))},Mh=e=>t=>e((e=>t(e[0]))),jh=async e=>{const t=Re();t.log("story/getTargetsByTargetIds",e);const n=await t.http.get("/api/v4/stories/seen",{params:{targets:e}}),{data:r}=n;return t.cache&&Xt(n.data),{data:r.storyTargets,cachedAt:Date.now()}};class Uh extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.paginationController=r}saveToMainDB(e){const t=Re(),n=t.cache&&Date.now(),r=Ld(e);t.cache&&(Xt(r,{cachedAt:n}),_h(r.stories),kh(r.stories))}getStoryReferenceIds(e){return(null==e?void 0:e.referenceId)?e.referenceId:e.storyId}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.stories.map(this.getStoryReferenceIds)});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(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=je(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])],Ue(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class xh extends hs{async getRequest(e){const{data:t}=await this.http.get("/api/v4/stories-by-targets",{params:Object.assign({},e)});return t}}class Dh extends ps{constructor(e,t){const n=I.default(e),r=["story-target-ids","collection",n],a=new xh(e);super(a,n,r,t),this.query=e,this.queryStreamController=new Uh(this.query,this.cacheKey,this.notifyChange.bind(this),a),this.paginationController=a,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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 a=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;let o=a.data.map((e=>je(["story","get",e]))).filter(Boolean).map((e=>pi.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(Je):r.sort(Ge)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Th,action:"onCreate"},{fn:vh,action:"onUpdate"},{fn:Ah,action:"onDelete"},{fn:Ph,action:"onError"}])}}const qh=(e,t)=>{var n,r;const a=null===(n=je(e))||void 0===n?void 0:n.data,o=null!==(r=null==a?void 0:a.data)&&void 0!==r?r:[];Ue(e,Object.assign(Object.assign({},a),{data:[...new Set([...o,...t])]}))};class Nh extends ls{constructor(e,t,n,r,a){super(e,t),this.notifyChange=n,this.paginationController=r,this.preparePayload=a}saveToMainDB(e){const t=Re(),n=t.cache&&Date.now(),r=this.preparePayload(e);t.cache&&Xt(r,{cachedAt:n})}appendToQueryStream(e,t,n=!1){n?Ue(this.cacheKey,{data:e.storyTargets.map((({targetId:e})=>e))}):qh(this.cacheKey,e.storyTargets.map((({targetId:e})=>e)))}reactor(e){return t=>{"onCreate"===e&&"seen"!==this.query.seenState&&qh(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 Bh extends is{constructor(){super(...arguments),this.smartFilterState="unseen"}async getRequest(e,t){var n;const{limit:r=10,seenState:a="unseen"}=e,o=await this.createRequest({seenState:"smart"===a?this.smartFilterState:a,limit:r,token:t});if(null===(n=o.paging)||void 0===n?void 0:n.next)return o;if("smart"!==a)return o;if("seen"===this.smartFilterState)return o;this.smartFilterState="seen";const s=await this.createRequest({seenState:this.smartFilterState,limit:r});return c=s,{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 Lh extends ps{constructor(e,t){const n=I.default(e),r=["story-global-feed","collection",n],a=new Bh(e);super(a,n,r,t),this.query=e,this.queryStreamController=new Nh(this.query,this.cacheKey,this.notifyChange.bind(this),a,(e=>{const t=en(Ks(Object.assign(Object.assign({},e),{feeds:[]})),["feeds"]);return Object.assign(Object.assign({},e),t)})),this.paginationController=a,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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 a=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const o=a.data,s=Me(["storyTarget"]);s&&(null==s?void 0:s.length)>0&&(null==s||s.forEach((({key:e})=>{a.data.includes(e[2])||o.push(e[2])})));let i=o.map((e=>je(["storyTarget","get",e]))).filter(Boolean).map((e=>pi.storyTarget(e.data)));(this.shouldNotify(i)||"event"!==e)&&(i=this.applyFilter(i).filter((({localSortingDate:e})=>!!e)).map((e=>en(e,["localFilter","localLastExpires","localLastSeen","localSortingDate"]))),this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,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(We);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(We)||[],r=t.unseen.sort(We)||[],a=t.seen.sort(We)||[];return n.concat(r,a)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Th,action:"onCreate"},{fn:vh,action:"onUpdate"},{fn:Ah,action:"onDelete"},{fn:Eh,action:"onCreate"},{fn:bh,action:"onUpdate"},{fn:Rh,action:"onDelete"},{fn:Ph,action:"onError"}])}}var Fh=Object.freeze({__proto__:null,createImageStory:async(e,t,n,r={},a="fit",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,imageDisplayMode:a},syncState:"syncing",referenceId:zt(),dataType:"image",items:o,targetType:e,targetId:t,metadata:r};const i=new Date;Ue(["story-sync-state",t],"syncing"),Ue(["story-expire",t],new Date(i.setFullYear(i.getFullYear()+1))),ph({payload:s,formData:n},(e=>{ct("local.story.created",e)}));try{const{data:r}=await Ni(n);if(0===r.length)throw new Error("Failed to upload image");const{fileId:a}=r[0];s=Object.assign(Object.assign({},s),{data:Object.assign(Object.assign({},s.data),{fileId:a})}),mh({targetId:t,targetType:e}),ph({payload:s,formData:n},(e=>{ct("local.story.created",e)}));const o=await fh(s);return o.data?Object.assign(Object.assign({},o),{data:pi.story(o.data)}):o}catch(e){throw Ue(["story-sync-state",t],"error"),ph({payload:Object.assign(Object.assign({},s),{syncState:"error"}),formData:n},(e=>{ct("local.story.error",e)})),e}},createVideoStory:async(e,t,n,r={},a=[])=>{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:zt(),dataType:"video",items:a,targetType:e,targetId:t,metadata:r};const s=new Date;Ue(["story-sync-state",t],"syncing"),Ue(["story-expire",t],new Date(s.setFullYear(s.getFullYear()+1))),mh({targetId:t,targetType:e}),ph({payload:o,formData:n,isVideo:!0},(e=>{ct("local.story.created",e)}));try{const{data:e}=await qi(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}})}),ph({payload:o,formData:n,isVideo:!0},(e=>{ct("local.story.created",e)}));const r=await fh(o);return r.data?Object.assign(Object.assign({},r),{data:pi.story(r.data)}):r}catch(e){throw Ue(["story-sync-state",t],"error"),ph({payload:Object.assign(Object.assign({},o),{syncState:"error"}),formData:n,isVideo:!0},(e=>{ct("local.story.error",e)})),e}},hardDeleteStory:async e=>await yh(e,!0),softDeleteStory:async e=>await yh(e),getActiveStoriesByTarget:(e,t)=>{const{log:n,cache:r}=Re(),a=[],o=["story-target","collection",e],s=Date.now();n(`getActiveStoriesByTarget(tmpid: ${s}) > listen`),r||console.log(J);const i=t=>{var n,r;const a=(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"===a?"asc"===o?t.sort(Je):t.sort(Ge):"asc"===o?t.sort(Ye):t.sort(Xe)},c=e=>{var n;const r=e.data.map((e=>{const t=gh(e);if(null==t?void 0:t.data)return pi.story(t.data)})).filter(Boolean).filter((e=>!!e&&!e.isDeleted)),a=[];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")||[]);a.push(...t)}if(e.has("syncing")){const t=i(e.get("syncing")||[]);a.push(...t)}if(e.has("synced")){const t=i(e.get("synced")||[]);a.push(...t)}}t({onNextPage:()=>!1,data:a||r,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading||!1})},l=(t,n,r=!1,a=!1,s=!1)=>{var i;const l=je(o),d={loading:a,error:s,params:{page:void 0},data:(null==l?void 0:l.data)||[]};if(t)if("onDelete"===n){const e=t.map((({referenceId:e})=>e));d.data=d.data.filter((t=>!e.includes(t)))||[]}else d.data=r?t.map(Ce("story")):[...new Set([...d.data,...t.map(Ce("story"))])];const u=null===(i=Me(["story","get"]))||void 0===i?void 0:i.filter((t=>t.data.targetId===e.targetId&&"synced"!==t.data.syncState)).map((e=>Ce("story")(e.data)));u&&(null==u?void 0:u.length)>0&&u.forEach((e=>{d.data.includes(e)||d.data.push(e)})),Ue(o,d.data),c(d)},d=e=>t=>{l(t,e)};return(t=>{const n=ge(Oh,e);ve(n,(({data:e,error:n,loading:r})=>{l(e,"fetch",t,r,n)}))})(!0),a.push(Th(d("onCreate")),vh(d("onUpdate")),Ah(d("onDelete")),wh(d("onReactionAdded")),Ih(d("onReactionRemoved")),Ph(d("onError")),Eh(d("onCreate")),bh(d("onUpdate")),Rh(d("onDelete")),Ch(d("onReactionAdded")),Sh(d("onReactionRemoved")),(e=>{const t=Re();return it(t,"onStoryLocalDataUpdated","local.story.reload",(t=>{e(t)}))})((e=>{const t=je(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)})),(()=>qe(o))),()=>{n(`getActiveStoriesByTarget(tmpid: ${s}) > dispose`),a.forEach((e=>e()))}},getStoryByStoryId:(e,t)=>Cs(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:pi.story(e.data)})):t(e)}),"storyId",Fd,[Mh(vh),Mh(Ah),Mh(wh),Mh(Ih),Mh(Ph),Mh(bh),Mh(Rh),Mh(Ch),Mh(Sh)]),getTargetById:(e,t)=>Cs(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:pi.storyTarget(e.data[0])})):t(e)}),"query",(e=>jh([e])),[]),getTargetsByTargetIds:(e,t)=>{const{log:n,cache:r}=Re(),a=[],o=["storyTargets","collection",e],s=Date.now();n(`getTargetsByTargetIds(tmpid: ${s}) > listen`),r||console.log(J);const i=(e,n=!1,r=!1,a=!1)=>{const s=je(o),i={loading:r,error:a,params:{page:void 0},data:[]};e&&(i.data=n?e.map(Ce("storyTarget")):[...new Set([...(null==s?void 0:s.data)||[],...e.map(Ce("storyTarget"))])]),Ue(o,i.data),(e=>{var n;const r=e.data.map((e=>{const t=je(["storyTarget","get",e]);if(null==t?void 0:t.data)return pi.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=ge(jh,e);ve(n,(({data:e,error:n,loading:r})=>{i(e,t,r,n)}))})(!0),a.push((()=>qe(o))),()=>{n(`getTargetsByTargetIds(tmpid: ${s}) > dispose`),a.forEach((e=>e()))}},getStoriesByTargetIds:(e,t,n)=>{const{log:r,cache:a,userId:o}=Re();a||console.log(J);const s=Date.now();r(`getStoriesByTargetIds(tmpid: ${s}) > listen`);const i=new Dh(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{qe(l)})),()=>{r(`getStoriesByTargetIds(tmpid: ${s}) > dispose`),c.forEach((e=>e()))}},getGlobalStoryTargets:(e,t,n)=>{const{log:r,cache:a,userId:o}=Re();a||console.log(J);const s=Date.now();r(`getGlobalStoryTarget(tmpid: ${s}) > listen`);const i=new Lh(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{qe(l)})),()=>{r(`getGlobalStoryTarget(tmpid: ${s}) > dispose`),c.forEach((e=>e()))}}});const Kh=e=>Object.assign(Object.assign({},e),{endAt:e.endAt?e.endAt:null}),$h=e=>Object.assign({},e);var Qh=Object.freeze({__proto__:null,getNetworkAds:async()=>{const e=Re(),{data:t}=await e.http.get("/api/v1/ads/me"),n=t.ads.map(Kh),r=t.advertisers.map($h);return Xt({ads:n,advertisers:r,files:t.files}),Ue(["ad","setting"],t.settings),{ads:n.map(pi.ad),settings:t.settings}}});const zh=async()=>{const e=Re();e.log("notificationTray/getNotificationTraySeen",{});const{data:t}=await e.http.get("api/v1/notification-tray/tray/seen"),n=e.cache&&Date.now();if(e.cache){const n=["notificationTraySeen","get",e.userId];Ue(n,{userId:e.userId,lastTraySeenAt:t.lastTraySeenAt,lastTrayOccuredAt:t.lastTrayOccurredAt})}return{data:{userId:e.userId,lastTraySeenAt:t.lastTraySeenAt,lastTrayOccurredAt:t.lastTrayOccurredAt,isSeen:t.lastTraySeenAt>t.lastTrayOccurredAt},cachedAt:n}};zh.locally=()=>{var e;const t=Re();if(t.log("notificationTray/getNotificationTraySeen.locally",{}),!t.cache)return;const{data:n,cachedAt:r}=null!==(e=je(["notificationTraySeen","get"]))&&void 0!==e?e:{};return n?{data:n,cachedAt:r}:void 0};const Vh=e=>{const t=Re(),n=[it(t,"onNotificationTraySeenUpdated","local.notificationTraySeen.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class Hh extends is{async getRequest(e,t){const{limit:n=V}=e,r=en(e,["limit"]),a=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/notification-tray",{params:Object.assign(Object.assign({},r),{options:a})});return o}}class Jh extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.notificationTrayItems.map(Ce("notificationTrayItem"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.notificationTrayItems.map(Ce("notificationTrayItem"))])]}))}}}const Wh=e=>{const t=e.users.map(An);return Object.assign(Object.assign({},e),{users:t})};class Gh extends ps{constructor(e,t){const n=I.default(e),r=["notificationTrayItem","collection",n];super(new Hh(e),n,r,t),this.query=e,this.queryStreamController=new Jh(this.query,this.cacheKey,this.notifyChange.bind(this),Wh),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(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,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=(null!==(a=o.data.map((e=>je(["notificationTrayItem","get",e]))).filter(fs).map((({data:e})=>e)))&&void 0!==a?a:[]).map(pi.notificationTray);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var Yh=Object.freeze({__proto__:null,getNotificationTraySeen:e=>{const{userId:t}=tt();return Cs(t,e,"userId",zh,[Vh],{callbackDataSelector:e=>{let t=!0;return(null==e?void 0:e.lastTrayOccurredAt)&&(t=!!e.lastTraySeenAt&&Un(e.lastTraySeenAt)>Un(e.lastTrayOccurredAt)),{lastTrayOccurredAt:null==e?void 0:e.lastTrayOccurredAt,lastTraySeenAt:null==e?void 0:e.lastTraySeenAt,isSeen:t}}})},getNotificationTrayItems:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getNotificationTrayItems(tmpid: ${o}) > listen`);const s=new Gh(e,t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>qe(c))),()=>{r(`getNotificationTrayItems(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},markItemsSeen:async e=>{const t=Re();t.log("notificationTray/markItemsSeen",{});const{data:n}=await t.http.post("api/v1/notification-tray/items/seen",{trayItems:e.map((e=>({id:e.id,lastSeenAt:e.lastSeenAt})))}),r=n.trayItems.map((e=>{var n;const r=null===(n=je(["notificationTrayItem","get",e.id]))||void 0===n?void 0:n.data;if(!r)return;const a=Object.assign(Object.assign({},r),{lastSeenAt:e.lastSeenAt});if(t.cache){const e=Date.now();Ue(["notificationTrayItem","get"],a,{cachedAt:e})}return a})).filter(Boolean);ct("local.notificationTrayItem.updated",{notificationTrayItems:r})},markTraySeen:async e=>{var t;const n=Re();n.log("notificationTray/markTraySeen",{});const{data:r}=await n.http.post("api/v1/notification-tray/tray/seen",{lastSeenAt:e}),a=null===(t=je(["notificationTraySeen","get"]))||void 0===t?void 0:t.data,o={userId:n.userId,lastTraySeenAt:r.lastSeenAt},s=Object.assign(Object.assign({},a),o),i=n.cache&&Date.now();return n.cache&&Ue(["notificationTraySeen","get",n.userId],s,{cachedAt:i}),ct("local.notificationTraySeen.updated",o),{data:r,cachedAt:i}},onNotificationTraySeenUpdated:Vh});class Xh extends is{async getRequest(e,t){const{limit:n=V}=e,r=en(e,["limit"]),a=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/invitations/me",{params:Object.assign(Object.assign({},r),{options:a})});return await _l(o.invitations.map((e=>e.communityId))),o}}class Zh extends ls{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Re(),r=n.cache&&Date.now();n.cache&&Xt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Ue(this.cacheKey,{data:e.invitations.map(Ce("invitation"))});else{const t=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Ue(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(Ce("invitation"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=je(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(e===oi.OnLocalInvitationUpdated){if(!r.data.find((e=>e===t[0].invitationId)))return}if(e===oi.OnLocalInvitationCreated){const e=Re(),n=t.filter((t=>t.invitedUserId===e.userId));r.data=[...new Set([...n.map((e=>e.invitationId)),...r.data])]}e===oi.OnLocalInvitationDeleted&&(r.data=r.data.filter((e=>e!==t[0].invitationId))),Ue(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class ep extends ps{constructor(e,t){const n=I.default(e),r=["invitation","collection",n];super(new Xh(e),n,r,t),this.query=e,this.queryStreamController=new Zh(this.query,this.cacheKey,this.notifyChange.bind(this),ri),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=je(this.cacheKey))||void 0===e?void 0:e.data)||Ue(this.cacheKey,{data:[],params:this.query})}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:ci,action:oi.OnLocalInvitationCreated},{fn:li,action:oi.OnLocalInvitationUpdated},{fn:di,action:oi.OnLocalInvitationDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const o=null===(r=je(this.cacheKey))||void 0===r?void 0:r.data;if(!o)return;const s=this.applyFilter(null!==(a=o.data.map((e=>je(["invitation","get",e]))).filter(fs).map((({data:e})=>ai(e))))&&void 0!==a?a:[]);(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;this.query.targetId&&(t=t.filter((e=>e.targetId===this.query.targetId))),this.query.statuses&&(t=t.filter((e=>{var t;return null===(t=this.query.statuses)||void 0===t?void 0:t.includes(e.status)}))),this.query.targetType&&(t=t.filter((e=>e.targetType===this.query.targetType))),this.query.type&&(t=t.filter((e=>e.type===this.query.type)));const n=(()=>"firstCreated"===this.query.sortBy?Je:Ge)();return t=t.sort(n),t}}var tp=Object.freeze({__proto__:null,onLocalInvitationCreated:ci,onLocalInvitationUpdated:li,onLocalInvitationDeleted:di,getMyCommunityInvitations:(e,t,n)=>{const{log:r,cache:a}=Re();a||console.log(J);const o=Date.now();r(`getMyCommunityInvitations: (tmpid: ${o}) > listen`);const s=new ep(Object.assign(Object.assign({},e),{targetType:"community",statuses:["pending"]}),t),i=s.startSubscription(),c=s.getCacheKey();return i.push((()=>{qe(c)})),()=>{r(`getInvitations (tmpid: ${o}) > dispose`),i.forEach((e=>e()))}}});const np=e=>{const t=Re();return it(t,"live_reaction/onLiveReactionCreated","liveReaction.created",(n=>{if(n.reactions.length>0){const r=n.reactions.filter((({userId:e})=>e!==t.userId));e(r)}}))};var rp=Object.freeze({__proto__:null,createReaction:async({referenceId:e,referenceType:t,reactionName:n,streamId:r})=>{const a=Re();a.log("live_reaction/createReaction",{referenceId:e,referenceType:t,reactionName:n});const o=$a(),s={reactionName:n,referencePublicId:e,referenceType:t,streamId:r,occurredAt:(new Date).toISOString()};return o.createLiveReaction(s),ct("local.liveReaction.created",[Object.assign(Object.assign({},s),{userId:a.userId,referenceId:e})]),!0},onLiveReactionCreated:np,getReactions:(e,t)=>{const{_id:n}=tt();if(!n)throw new _e("The _id has not been defined in ActiveUser",8e5,"error");const{log:r}=Re();r(`getReactions(tmpid: ${Date.now()}) > listen`);const a=[],o=n=>{(e=>{t(e)})(n.filter((({referenceId:t})=>t===e)))};return a.push(np(o)),a.push((e=>{const t=Re();return it(t,"live_reaction/onLiveReactionCreated","local.liveReaction.created",e)})(o)),()=>{a.forEach((e=>e()))}}});return e.API_REGIONS=Et,e.AdRepository=Qh,e.CategoryRepository=Ud,e.ChannelRepository=Il,e.Client=Fo,e.CommentRepository=Xd,e.CommunityPostSettingMaps=R,e.CommunityPostSettings=A,e.CommunityRepository=Pd,e.ContentFeedType=M,e.DefaultCommunityPostSetting=P,e.FeedRepository=pu,e.FileRepository=Bi,e.FileType=_,e.GET_WATCHER_URLS=Ts,e.InvitationRepository=tp,e.LiveReactionRepository=rp,e.LiveStreamPlayer=uh,e.MessageContentType=U,e.MessageRepository=Zc,e.PollRepository=rh,e.PostContentType=x,e.PostRepository=Uu,e.PostStructureType=D,e.ReactionRepository=Oc,e.RoomRepository=Zu,e.StoryRepository=Fh,e.StreamRepository=$u,e.SubChannelRepository=sl,e.UserRepository=xi,e.VERSION=z,e.VideoResolution=k,e.VideoSize=T,e.VideoTranscodingStatus=O,e.backupCache=async(e="amitySdk",t=(e=>e.offline))=>{const{log:n,cache:r,userId:a}=Re();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}#${a}`,JSON.stringify(o)),!0)},e.createQuery=ge,e.createReport=async(e,t)=>{const n=Re();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 fa(n);Xt(e)}return ct("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 On(n);Xt(e)}return ct("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 Xi(n);Xt(e)}return ct("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 Tc(n);Xt(e)}return ct("comment.flagged",n),!!n})({client:n,referenceId:t})},e.createUserToken=async(e,t,n)=>{const r=await Ht(),a=Jt(),o=qt(Rt("http",t)),{data:s}=await o.post("/api/v5/sessions",Object.assign(Object.assign({},n),{deviceId:r,deviceInfo:Object.assign(Object.assign({},a),{model:"token management API on TS-SDK"})}),{headers:{"X-API-Key":e}});return{accessToken:s.accessToken}},e.deleteReport=async(e,t)=>{const n=Re();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 fa(n);Xt(e)}return ct("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 On(n);Xt(e)}return ct("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 Xi(n);Xt(e)}return ct("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 Tc(n);Xt(e)}return ct("comment.unflagged",n),!!n})({client:n,referenceId:t})},e.disableCache=()=>{const e=Re();e.cache&&(e.log("cache/api/disableCache"),delete e.cache)},e.dropFromCache=qe,e.enableCache=(e={},t)=>{const n=Re();n.cache||(n.log("cache/api/enableCache"),n.cache={data:e,persistIf:t})},e.filterByChannelMembership=Fe,e.filterByCommunityMembership=$e,e.filterByFeedType=Ke,e.filterByPostDataTypes=Qe,e.filterByPropEquality=Ne,e.filterByPropInclusion=(e,t,n)=>void 0!==n?e.filter((e=>n.includes(e[t]))):e,e.filterByPropIntersection=Le,e.filterBySearchTerm=ze,e.filterByStringComparePartially=Be,e.getChannelTopic=e=>`${e.path}/#`,e.getCommentTopic=({path:e})=>e,e.getCommunityStoriesTopic=({targetId:e,targetType:t})=>{const n=tt();return`${ft(n)}/social/${t}/${e}/story/#`},e.getCommunityTopic=({path:t},n=e.SubscriptionLevels.COMMUNITY)=>pt(t,n),e.getLiveReactionTopic=e=>`${e.path}/liveReaction`,e.getLiveStreamTopic=It,e.getMarkedMessageTopic=gt,e.getMarkerUserFeedTopic=yt,e.getMessageTopic=e=>e.path,e.getMyFollowersTopic=()=>{const e=tt();return`${ft(e)}/membership/${e._id}/+/+`},e.getMyFollowingsTopic=()=>{const e=tt();return`${ft(e)}/membership/+/${e._id}/+`},e.getNetworkTopic=vt,e.getPostTopic=({path:t},n=e.SubscriptionLevels.POST)=>"comment"===n?`${t}/comment/+`:t,e.getRole=Fi,e.getSmartFeedChannelTopic=bt,e.getSmartFeedMessageTopic=Ct,e.getSmartFeedSubChannelTopic=wt,e.getStoryTopic=({targetId:e,targetType:t,storyId:n})=>{const r=tt();return`${ft(r)}/social/${t}/${e}/story/${n}/#`},e.getSubChannelTopic=e=>`${e.path}/#`,e.getUserTopic=mt,e.isAfterBefore=se,e.isAfterBeforeRaw=ie,e.isCachable=fe,e.isFetcher=ue,e.isFresh=me,e.isLocal=e=>fe(e)&&-1===(null==e?void 0:e.cachedAt),e.isMutator=he,e.isOffline=pe,e.isPaged=ce,e.isReportedByMe=async(e,t)=>{const n=Re();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:a,isFlagByMe:o}=null!=r?r:{};return null!==(n=null!=a?a: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:a,isFlagByMe:o}=null!=r?r:{};return null!==(n=null!=a?a: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:a,isFlagByMe:o}=null!=r?r:{};return null!==(n=null!=a?a: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:a,isFlagByMe:o}=null!=r?r:{};return null!==(n=null!=a?a:o)&&void 0!==n&&n})({client:n,referenceId:t})},e.isSkip=oe,e.mergeInCache=xe,e.notificationTray=Yh,e.onChannelMarkerFetched=Mo,e.onFeedMarkerFetched=e=>{const t=Re();return it(t,"feedMarker/onFeedMarkerFetched","local.feedMarker.fetched",(t=>{e(t.feedMarkers[0])}))},e.onFeedMarkerUpdated=e=>{const t=Re();return it(t,"feedMarker/onFeedMarkerUpdated","marker.feed-updated",(t=>{Xt(t),e(t.feedMarkers[0])}))},e.onMessageMarked=qo,e.onMessageMarkerFetched=Do,e.onSubChannelMarkerFetched=jo,e.onSubChannelMarkerUpdated=Uo,e.onUserMarkerFetched=xo,e.onUserMarkerFetchedLegacy=e=>{const t=Re();return it(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers[0])}))},e.pullFromCache=je,e.pushToCache=Ue,e.queryCache=Me,e.queryOptions=ye,e.queryRoles=Li,e.restoreCache=async(e="amitySdk")=>{var t;const n=Re();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 a={};try{a=JSON.parse(r)}catch(e){}return n.cache.data=Object.assign(Object.assign({},a),n.cache.data),!0},e.runQuery=ve,e.sortByChannelSegment=({channelSegment:e},{channelSegment:t})=>e-t,e.sortByDisplayName=Ve,e.sortByFirstCreated=Je,e.sortByFirstUpdated=Ye,e.sortByLastActivity=Ze,e.sortByLastCreated=Ge,e.sortByLastUpdated=Xe,e.sortByLocalSortingDate=We,e.sortByName=He,e.sortBySegmentNumber=({segmentNumber:e},{segmentNumber:t})=>e-t,e.subscribeTopic=St,e.toPage=de,e.toPageRaw=e=>{if(!e)return;const n=JSON.parse(t.decode(e));return ie(n)?n:void 0},e.toToken=le,e.upsertInCache=De,e.wipeCache=async(e="amitySdk")=>{const{log:t,cache:n,userId:r}=Re();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,AsyncStorage,uuid$1,jwtDecode,reactNative,hash,Hls);