@amityco/ts-sdk-react-native 7.23.0 → 7.23.1-c573a00.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.cjs.js +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.umd.js +3 -3
- package/package.json +1 -1
package/dist/index.umd.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var Amity=function(e,t,n,a,r,s,o,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,g,y=h(n),v=h(a),b=h(r),w=h(s),I=h(o),C=h(i),S=h(c),O=h(d),T=h(u);e.MembershipAcceptanceTypeEnum=void 0,(p=e.MembershipAcceptanceTypeEnum||(e.MembershipAcceptanceTypeEnum={})).AUTOMATIC="automatic",p.INVITATION="invitation",e.AmityAutoSubscription=void 0,(f=e.AmityAutoSubscription||(e.AmityAutoSubscription={})).CHAT="chat",f.NETWORK="network",f.LIVESTREAM="livestream",f.BLOCK="block",e.UserTypeEnum=void 0,(m=e.UserTypeEnum||(e.UserTypeEnum={})).SIGNED_IN="signed-in",m.VISITOR="visitor",m.BOT="bot",e.SearchUsersByEnum=void 0,(g=e.SearchUsersByEnum||(e.SearchUsersByEnum={})).DISPLAY_NAME="displayName",g.PROFILE_HANDLE="profileHandle",g.USER_ID="userId";const k=Object.freeze({FILE:"file",IMAGE:"image",VIDEO:"video",CLIP:"clip",AUDIO:"audio"}),A=Object.freeze({"1080P":"1080p","720P":"720p","480P":"480p","360P":"360p",ORIGINAL:"original"}),_=Object.freeze({UPLOADED:"uploaded",TRANSCODING:"transcoding",TRANSCODED:"transcoded",TRANSCODE_FAILED:"transcodeFailed"}),E=Object.freeze({LOW:"low",MEDIUM:"medium",HIGH:"high",ORIGINAL:"original"});var R,P;e.FileAccessTypeEnum=void 0,(R=e.FileAccessTypeEnum||(e.FileAccessTypeEnum={})).PUBLIC="public",R.NETWORK="network",e.AmityChannelNotificationModeEnum=void 0,(P=e.AmityChannelNotificationModeEnum||(e.AmityChannelNotificationModeEnum={})).Default="default",P.Silent="silent",P.Subscribe="subscribe";const M=Object.freeze({ONLY_ADMIN_CAN_POST:"ONLY_ADMIN_CAN_POST",ADMIN_REVIEW_POST_REQUIRED:"ADMIN_REVIEW_POST_REQUIRED",ANYONE_CAN_POST:"ANYONE_CAN_POST"}),j=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}}),U="ONLY_ADMIN_CAN_POST";var D;e.AmityCommunityType=void 0,(D=e.AmityCommunityType||(e.AmityCommunityType={})).Default="default",D.Event="event";const x=Object.freeze({STORY:"story",CLIP:"clip",CHAT:"chat",POST:"post",MESSAGE:"message"});var q;e.ContentFlagReasonEnum=void 0,(q=e.ContentFlagReasonEnum||(e.ContentFlagReasonEnum={})).CommunityGuidelines="Against community guidelines",q.HarassmentOrBullying="Harassment or bullying",q.SelfHarmOrSuicide="Self-harm or suicide",q.ViolenceOrThreateningContent="Violence or threatening content",q.SellingRestrictedItems="Selling and promoting restricted items",q.SexualContentOrNudity="Sexual content or nudity",q.SpamOrScams="Spam or scams",q.FalseInformation="False information or misinformation",q.Others="Others";const N=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",AUDIO:"audio",CUSTOM:"custom"}),B=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",LIVESTREAM:"liveStream",POLL:"poll",CLIP:"clip",AUDIO:"audio",ROOM:"room"}),L=Object.freeze({TEXT:"text",IMAGE:"image",VIDEO:"video",FILE:"file",AUDIO:"audio",MIXED:"mixed"});var F,K,$,Q,z,V,H,J,W,G,Y,X,Z,ee,te,ne,ae,re,se,oe,ie,ce;e.InvitationTypeEnum=void 0,(F=e.InvitationTypeEnum||(e.InvitationTypeEnum={})).CommunityMemberInvite="communityMemberInvite",F.LivestreamCohostInvite="livestreamCohostInvite",e.InvitationStatusEnum=void 0,(K=e.InvitationStatusEnum||(e.InvitationStatusEnum={})).Pending="pending",K.Approved="approved",K.Rejected="rejected",K.Cancelled="cancelled",e.InvitationSortByEnum=void 0,($=e.InvitationSortByEnum||(e.InvitationSortByEnum={})).FirstCreated="firstCreated",$.LastCreated="lastCreated",e.InvitationTargetTypeEnum=void 0,(Q=e.InvitationTargetTypeEnum||(e.InvitationTargetTypeEnum={})).Community="community",Q.Room="room",e.JoinRequestStatusEnum=void 0,(z=e.JoinRequestStatusEnum||(e.JoinRequestStatusEnum={})).Pending="pending",z.Approved="approved",z.Rejected="rejected",z.Cancelled="cancelled",e.JoinResultStatusEnum=void 0,(V=e.JoinResultStatusEnum||(e.JoinResultStatusEnum={})).Success="success",V.Pending="pending",e.FeedDataTypeEnum=void 0,(H=e.FeedDataTypeEnum||(e.FeedDataTypeEnum={})).Text="text",H.Video="video",H.Image="image",H.File="file",H.Audio="audio",H.LiveStream="liveStream",H.Clip="clip",H.Poll="poll",H.Room="room",e.FeedSortByEnum=void 0,(J=e.FeedSortByEnum||(e.FeedSortByEnum={})).LastCreated="lastCreated",J.FirstCreated="firstCreated",J.LastUpdated="lastUpdated",J.FirstUpdated="firstUpdated",e.FeedSourceEnum=void 0,(W=e.FeedSourceEnum||(e.FeedSourceEnum={})).Community="community",W.User="user",e.FeedTypeEnum=void 0,(G=e.FeedTypeEnum||(e.FeedTypeEnum={})).Reviewing="reviewing",G.Published="published",G.Declined="declined",e.AmityEventType=void 0,(Y=e.AmityEventType||(e.AmityEventType={})).Virtual="virtual",Y.InPerson="in_person",e.AmityEventOriginType=void 0,(X=e.AmityEventOriginType||(e.AmityEventOriginType={})).Community="community",X.User="user",e.AmityEventStatus=void 0,(Z=e.AmityEventStatus||(e.AmityEventStatus={})).Scheduled="scheduled",Z.Live="live",Z.Ended="ended",Z.Cancelled="cancelled",e.AmityEventResponseStatus=void 0,(ee=e.AmityEventResponseStatus||(e.AmityEventResponseStatus={})).Going="going",ee.NotGoing="not_going",e.AmityEventSortOption=void 0,(te=e.AmityEventSortOption||(e.AmityEventSortOption={})).StartTime="startTime",te.CreatedAt="createdAt",e.AmityEventOrderOption=void 0,(ne=e.AmityEventOrderOption||(e.AmityEventOrderOption={})).Ascending="asc",ne.Descending="desc",e.AmitySharableContentType=void 0,(ae=e.AmitySharableContentType||(e.AmitySharableContentType={})).POST="post",ae.COMMUNITY="community",ae.USER="user",ae.LIVESTREAM="livestream",ae.EVENT="event",e.AnalyticsSourceTypeEnum=void 0,(re=e.AnalyticsSourceTypeEnum||(e.AnalyticsSourceTypeEnum={})).POST="post",re.ROOM="room",e.UserNotificationModuleNameEnum=void 0,(se=e.UserNotificationModuleNameEnum||(e.UserNotificationModuleNameEnum={})).CHAT="chat",se.SOCIAL="social",se.VIDEO_STREAMING="video-streaming",e.CommunityNotificationEventNameEnum=void 0,(oe=e.CommunityNotificationEventNameEnum||(e.CommunityNotificationEventNameEnum={})).POST_CREATED="post.created",oe.POST_REACTED="post.reacted",oe.COMMENT_CREATED="comment.created",oe.COMMENT_REPLIED="comment.replied",oe.COMMENT_REACTED="comment.reacted",oe.STORY_CREATED="story.created",oe.STORY_REACTED="story.reacted",oe.STORY_COMMENT_CREATED="story-comment.created",oe.LIVESTREAM_START="video-streaming.didStart",e.NotificationSettingsLevelEnum=void 0,(ie=e.NotificationSettingsLevelEnum||(e.NotificationSettingsLevelEnum={})).USER="user",ie.COMMUNITY="community",ie.CHANNEL="channel",e.NotificationRolesFilterTypeEnum=void 0,(ce=e.NotificationRolesFilterTypeEnum||(e.NotificationRolesFilterTypeEnum={})).ALL="all",ce.ONLY="only";const le=function(){try{return"v7.23.0-umd"}catch(e){return"__dev__"}}(),de=5,ue=20,he="cache_then_server",pe="For using Live Collection feature you need to enable Cache!",fe="Observing unsynced object is not supported by Live Object.",me=-5,ge=1e3,ye=6e5,ve="/api/v1/feeds/for-you",be="dead",we=6e4,Ie=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})),Ce=e=>JSON.parse(e),Se=(e,t)=>e===t||!(!e||!t)&&("object"==typeof e&&Object.keys(e).every((n=>Se(e[n],t[n])))),Oe=e=>[400400,400300].includes(e),Te=e=>["skip"].some((t=>t in e)),ke=e=>["after","before","first","last","limit"].some((t=>t in e)),Ae=e=>"limit"in e,_e=e=>(null==e?void 0:e.hasOwnProperty("data"))&&(null==e?void 0:e.hasOwnProperty("nextPage"))&&(null==e?void 0:e.hasOwnProperty("prevPage")),Ee=(e,n)=>{var a;if(!e||!Object.keys(e).length)return;let r={};return"skiplimit"===n?r={skip:null!==(a=e.after)&&void 0!==a?a:0,limit:e.limit}:"afterbefore"===n&&ke(e)?((null==e?void 0:e.before)&&(r=Object.assign(Object.assign({},r),{before:e.before})),(null==e?void 0:e.after)&&(r=Object.assign(Object.assign({},r),{after:e.after})),Number.isNaN(Number(null==e?void 0:e.limit))||(r=Object.assign(Object.assign({},r),{limit:e.limit}))):"afterbeforeraw"===n&&(r=e),Object.keys(r).length?t.encode(JSON.stringify(r)):void 0},Re=e=>{if(!e)return;const n=JSON.parse(t.decode(e));if(Te(n))return{after:n.skip,limit:n.limit};if(ke(n)){if("before"in n)return{before:n.before,limit:n.last};if("after"in n)return{after:n.after,limit:n.first}}},Pe=e=>"locally"in e,Me=e=>"optimistically"in e,je=e=>Pe(e)||Me(e),Ue=e=>null==e?void 0:e.hasOwnProperty("cachedAt"),De=(e,t=6e4)=>{var n;return Date.now()-(null!==(n=null==e?void 0:e.cachedAt)&&void 0!==n?n:0)<=t},xe=(e,...t)=>({func:e,args:t}),qe=(e,t=6e4)=>"cache_only"===e?{lifeSpan:1/0}:{lifeSpan:t<we?we:t},Ne=({func:e,args:t},n,a=qe("cache_then_server"))=>{let r;const{lifeSpan:s}=qe("cache_then_server",a.lifeSpan);if(je(e)){try{r=Me(e)?e.optimistically(...t):e.locally(...t)}catch(e){null==n||n(Be(void 0,{origin:"local",loading:!1,error:e}))}const a=Ue(r)&&De(r,s);if(null==n||n(Be(r,{origin:"local",loading:!(Pe(e)&&a)})),a)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 _e(e)||Ue(e)?Object.assign(Object.assign({},t),e):Object.assign(Object.assign({},t),{data:e})}class Le 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,Le)}}class Fe extends Le{constructor(e,t,n){super(e,t,n)}}class Ke extends Le{constructor(e=8e5,t="fatal"){super("Unexpected error",e,t)}}class $e extends Le{constructor(e,t="SDK client is having connection issues"){super(`${t} (${e})`,"disconnected"===e?800211:800210,"error"),this.event=e}}class Qe extends Le{constructor(e){super(e,800110,"error")}}let ze=null;const Ve=()=>{if(!ze)throw new Le("There is no active client",8e5,"fatal");return ze},He=e=>{ze=e},Je={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}`,archivedChannel:({channelId:e})=>e,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,viewer:({userId:e})=>e,event:({eventId:e})=>e,eventResponse:({userId:e})=>e,product:({productId:e})=>e,feedMetadata:({postId:e})=>e},We=e=>Je[e],Ge={users:"user",files:"file",roles:"role",stories:"story",storyTargets:"storyTarget",channels:"channel",messageFeeds:"subChannel",channelUsers:"channelUsers",archives:"archivedChannel",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",events:"event",viewers:"viewer",eventResponses:"eventResponse",products:"product",feedMetadata:"feedMetadata"};function Ye(e=(new Date).toISOString()){return new Date(new Date(e).getTime()+1).toISOString()}const Xe=e=>{const{log:t,cache:n}=Ve();if(n)return t("cache/api/queryCache",{key:e}),Object.keys(n.data).filter((t=>{const n=Ce(t);return Se(e,n)})).map((e=>n.data[e]))},Ze=e=>{const{log:t,cache:n}=Ve();if(!n)return;t("cache/api/pullFromCache",e);const a=Ie(e);return n.data[a]?n.data[a]:void 0},et=(e,t,n={cachedAt:Date.now()})=>{const{log:a,cache:r}=Ve();if(!r)return!1;a("cache/api/pushToCache",{key:e,data:t,options:n}),!(null==n?void 0:n.hasOwnProperty("offline"))&&r.persistIf&&(n.offline=r.persistIf(e,t));const s=Ie(e);return r.data[s]=Object.assign({key:e,data:t},n),!0},tt=(e,t,n)=>{const{log:a,cache:r}=Ve();if(!r)return!1;a("cache/api/mergeInCache",{key:e,mutation:t});const s=Ze(e);if(!s)return!1;const o="function"==typeof t?t(s.data):Object.assign(Object.assign({},s.data),t);return i=s.data,!("updatedAt"in(c=o)&&"updatedAt"in i&&new Date(c.updatedAt)<new Date(i.updatedAt))&&(et(e,o,n),!0);var i,c},nt=(e,t,n={cachedAt:Date.now()})=>{const{log:a,cache:r}=Ve();if(!r)return!1;a("cache/api/upsertInCache",{key:e,data:t,options:n});return Ze(e)?tt(e,t,n):et(e,t,n)},at=(e,t=!1)=>{const{log:n,cache:a}=Ve();if(!a)return!1;if(n("cache/api/dropFromCache",{key:e,exact:t}),!t)return Object.keys(a.data).map((e=>Ce(e))).filter((t=>Se(e,t))).map((e=>at(e,!0))).every((e=>e));const r=Ie(e);return r in a.data&&(delete a.data[r],!0)},rt=(e,t,n)=>void 0!==n?e.filter((e=>JSON.stringify(e[t])===JSON.stringify(n))):e,st=(e,t,n)=>void 0!==n?e.filter((e=>"string"==typeof e[t]&&"string"==typeof n&&String(e[t]).toLowerCase().match(n.toLowerCase()))):e,ot=(e,t,n)=>(null==n?void 0:n.length)?e.filter((e=>Array.isArray(e[t])&&n.some((n=>e[t].includes(n))))):e,it=(e,t,n)=>"all"===t?e:e.filter((e=>{var a;if("community"===e.type)return!0;const r=We("channelUsers")({channelId:e.channelPublicId,userId:n}),s=null===(a=Ze(["channelUsers","get",r]))||void 0===a?void 0:a.data;return"member"===t?s&&"none"!==s.membership:!s||"none"===s.membership})),ct=(e,t)=>e.filter((({targetId:e,feedId:n})=>{var a;const r=null===(a=Ze(["feed","get",We("feed")({targetId:e,feedId:n})]))||void 0===a?void 0:a.data;return r&&r.feedType===t})),lt=(e,t,n)=>"all"===t?e:e.filter((e=>{var a;const r=We("communityUsers")({communityId:e.communityId,userId:n}),s=null===(a=Ze(["communityUsers","get",r]))||void 0===a?void 0:a.data;return"member"===t?s&&"member"===s.communityMembership:!s||"none"!==s.communityMembership})),dt=(e,t)=>e.reduce(((e,n)=>{var a;if(null==t?void 0:t.includes(n.dataType))return[...e,n];if(((null==n?void 0:n.children)||[]).length>0){const r=null===(a=Ze(["post","get",n.children[0]]))||void 0===a?void 0:a.data;return(null==t?void 0:t.includes(null==r?void 0:r.dataType))?e:[...e,n]}return e}),[]),ut=(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))}))},ht=()=>{var e;const{userId:t}=Ve(),n=new Set;return(null!==(e=Xe(["follow","get"]))&&void 0!==e?e:[]).map((e=>e.data)).filter((e=>"blocked"===(null==e?void 0:e.status)&&(e.from===t||e.to===t))).forEach((e=>{n.add(e.from===t?e.to:e.from)})),n},pt=e=>{const t=ht();return 0===t.size?e:e.filter((e=>{var n,a;if(t.has(e.postedUserId))return!1;return!(null!==(a=null===(n=e.mentionees)||void 0===n?void 0:n.flatMap((e=>"user"===e.type?e.userIds:[])))&&void 0!==a?a:[]).some((e=>t.has(e)))}))},ft=e=>{const t=ht();return 0===t.size?e:e.filter((e=>!t.has(e.userId)))},mt=({displayName:e},{displayName:t})=>e&&t?e.localeCompare(t):e?-1:1,gt=({name:e},{name:t})=>e&&t?e.localeCompare(t):e?-1:1,yt=({createdAt:e},{createdAt:t})=>new Date(e).valueOf()-new Date(t).valueOf(),vt=({localSortingDate:e},{localSortingDate:t})=>new Date(t).getTime()-new Date(e).getTime(),bt=({createdAt:e},{createdAt:t})=>new Date(t).valueOf()-new Date(e).valueOf(),wt=({updatedAt:e=0},{updatedAt:t=0})=>new Date(e).valueOf()-new Date(t).valueOf(),It=({updatedAt:e=0},{updatedAt:t=0})=>new Date(t).valueOf()-new Date(e).valueOf(),Ct=({lastActivity:e},{lastActivity:t})=>new Date(t).valueOf()-new Date(e).valueOf(),St=e=>{if(void 0===e)return;const t=new Date(e).valueOf();if(!Number.isNaN(t))return e;console.warn("untilAt is an invalid Date — ignoring, pagination will not be bounded")},Ot=(e,t,n)=>{const a=new Date(e).valueOf(),r=new Date(t).valueOf();return"firstCreated"===n?a>=r:a<=r};let Tt=null;const kt=()=>{if(!Tt)throw new Le("Connect client first",8e5,"fatal");return Tt},At=e=>{Tt={_id:e._id,userId:e.userId,path:e.path}};let _t,Et=[];const Rt=e=>{clearTimeout(_t),Et.push(e),_t=setTimeout((()=>{Et.forEach((e=>e())),Et=[]}),0)},Pt=["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"],Mt=(e,t,n,a)=>{const{log:r,emitter:s}=e,o=Date.now();r(`${t}(tmpid: ${o}) > listen`);const i=(...e)=>{r(`${t}(tmpid: ${o}) > trigger`,e);try{a(...e)}catch(e){r(`${t}(tmpid: ${o}) > error`,e)}};return s.on(n,i),()=>{r(`${t}(tmpid: ${o}) > dispose`),s.off(n,i)}},jt=(e,t)=>{const{emitter:n}=Ve();Rt((()=>{n.emit(e,t)}))};let Ut,Dt;async function xt(){var e;const{mqtt:t,emitter:n,token:a}=Ve();if(!t)return;const r=null!==(e=null==a?void 0:a.accessToken)&&void 0!==e?e:"",s=kt();Ut===r&&Dt===s._id||(Ut=r,Dt=s._id,await t.connect({accessToken:Ut,userId:Dt}),((e,t)=>{Pt.forEach((n=>{null==e||e.on(n,((...e)=>{t.emit(n,1===e.length?e[0]:e)}))})),e.on("message",((e,n)=>{const a=JSON.parse(n.toString());t.emit(a.eventType,a.data)}))})(t,n))}const qt=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=Ze(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),Nt=()=>{var e;const t=Ve();if(!t)throw new Le("Connect client first",8e5,"fatal");const n=null===(e=Ze(["user","get",t.userId]))||void 0===e?void 0:e.data;return n?qt(n):null};var Bt;e.SubscriptionLevels=void 0,(Bt=e.SubscriptionLevels||(e.SubscriptionLevels={})).COMMUNITY="community",Bt.POST="post",Bt.COMMENT="comment",Bt.POST_AND_COMMENT="post_and_comment",Bt.USER="user";const Lt=(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],Kt=()=>{const e=kt();return`${Ft(e)}/membership/${e._id}/+/+`},$t=()=>{const e=kt();return`${Ft(e)}/membership/+/${e._id}/+`},Qt=({channelId:e,subChannelId:t})=>{const n=kt();return`${Ft(n)}/marker/channel/${e}/message/${t}`},zt=()=>Ft(kt()),Vt=()=>{const e=kt();return`${Ft(e)}/smartfeed/${e._id}/channels`},Ht=()=>{const e=kt();return`${Ft(e)}/smartfeed/${e._id}/messagefeeds`},Jt=()=>{const e=kt();return`${Ft(e)}/smartfeed/${e._id}/messages`},Wt=()=>{const e=kt();return`${Ft(e)}/videostreaming`};function Gt(e,t){const{mqtt:n}=Ve();return n?(xt(),n.subscribe(e,t)):()=>null}var Yt;const Xt="object"==typeof globalThis?globalThis:"object"==typeof global?global:window,{process:Zt={}}=Xt,en="production"===(null===(Yt=Zt.env)||void 0===Yt?void 0:Yt.NODE_ENV),tn={EU:"eu",SG:"sg",US:"us"},nn={http:"https://apix.{region}.amity.co",upload:"https://upload.{region}.amity.co",mqtt:"wss://sse.{region}.amity.co:443/mqtt"};function an(e,t){return nn[e].replace("{region}",t)}class rn{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 sn;var on,cn=()=>(sn||(sn=new rn),sn);!function(e){e.UserDeleted="User Deleted",e.UserGlobalBanned="User Global Banned",e.TokenExpired="Token Expired"}(on||(on={}));let ln=new AbortController;const dn=e=>{switch(e){case on.UserGlobalBanned:throw new Le(e,400312,"fatal");case on.UserDeleted:throw new Le(e,400100,"fatal");case on.TokenExpired:throw jt("tokenExpired","tokenExpired"),new Le(e,800403,"fatal");default:throw new Le("Request Aborted",8e5,"error")}};let un=0;const hn=e=>{const t={maxSockets:100,maxFreeSockets:10,timeout:6e4,freeSocketTimeout:3e4},n=b.default.create({baseURL:e,httpAgent:new w.default(t),httpsAgent:new s.HttpsAgent(t),signal:ln.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:a}=e.metadata;n&&(ln.abort(),dn(on.UserGlobalBanned)),a&&(ln.abort(),dn(on.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 a=(e.config.baseURL||"")+(e.config.url||""),r=null===(t=e.config.method)||void 0===t?void 0:t.toUpperCase(),s={method:r,headers:e.config.headers};return"GET"!==r&&"HEAD"!==r&&(s.body=e.config.data),cn().setNetworkActivities(new Request(a,s),{data:e.data,status:e.status,statusText:e.statusText,headers:n}),e}),(e=>{var t,n,a;const{response:r}=e;if(400100===(null==r?void 0:r.data.code)&&jt("tokenTerminated","terminated"),400323===(null===(t=null==r?void 0:r.data)||void 0===t?void 0:t.code))throw function(){const e=Date.now();e-un<2e3||(un=e,jt("visitorUsageLimitReached",void 0))}(),new Le("Visitor usage limit exceeded",400323,"error");if((null===(n=null==r?void 0:r.data)||void 0===n?void 0:n.status)&&(e=>{if("success"===e.status)return e.data;if("fail"===e.status)throw new Ke(e.code);if("error"===e.status)throw new Fe(e.message,e.code,"error")})(null==r?void 0:r.data),ln.signal.aborted)throw e;throw new Error(null!==(a=null==r?void 0:r.data)&&void 0!==a?a:e)})),n.defaults.paramsSerializer={encode:e=>encodeURIComponent(e)},n};var pn="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function fn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function mn(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 gn={exports:{}};gn.exports=function(){function e(t,n,a){function r(o,i){if(!n[o]){if(!t[o]){if(!i&&mn)return mn(o);if(s)return s(o,!0);var c=new Error("Cannot find module '"+o+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[o]={exports:{}};t[o][0].call(l.exports,(function(e){return r(t[o][1][e]||e)}),l,l.exports,e,t,n,a)}return n[o].exports}for(var s=mn,o=0;o<a.length;o++)r(a[o]);return r}return e}()({1:[function(e,t,n){(function(n,a){(function(){const r=e("events").EventEmitter,s=e("./store"),o=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=a.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"],I={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 C(){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 a=t.topic.toString();if(e.topicAliasSend)if(n){if(0!==a.length&&(g("applyTopicAlias :: register topic: %s - alias: %d",a,n),!e.topicAliasSend.put(a,n)))return g("applyTopicAlias :: error out of range. topic: %s - alias: %d",a,n),new Error("Sending Topic Alias out of range")}else 0!==a.length&&(e.options.autoAssignTopicAlias?(n=e.topicAliasSend.getAliasByTopic(a),n?(t.topic="",t.properties={...t.properties,topicAlias:n},g("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",a,n)):(n=e.topicAliasSend.getLruAlias(),e.topicAliasSend.put(a,n),t.properties={...t.properties,topicAlias:n},g("applyTopicAlias :: auto assign topic: %s - alias: %d",a,n))):e.options.autoUseTopicAlias&&(n=e.topicAliasSend.getAliasByTopic(a),n&&(t.topic="",t.properties={...t.properties,topicAlias:n},g("applyTopicAlias :: auto use topic: %s - alias: %d",a,n))));else if(n)return g("applyTopicAlias :: error out of range. topic: %s - alias: %d",a,n),new Error("Sending Topic Alias out of range")}}function O(e,t){let n;t.properties&&(n=t.properties.topicAlias);let a=t.topic.toString();if(0===a.length){if(void 0===n)return new Error("Unregistered Topic Alias");if(a=e.topicAliasSend.getTopicByAlias(n),void 0===a)return new Error("Unregistered Topic Alias");t.topic=a}n&&delete t.properties.topicAlias}function T(e,t,n){g("sendPacket :: packet: %O",t),g("sendPacket :: emitting `packetsend`"),e.emit("packetsend",t),g("sendPacket :: writing to stream");const a=c.writeToStream(t,e.stream,e.options);g("sendPacket :: writeToStream result %s",a),!a&&n&&n!==E?(g("sendPacket :: handle events on `drain` once through callback."),e.stream.once("drain",n)):n&&(g("sendPacket :: invoking cb"),n())}function k(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 A(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,t,n,a){g("storeAndSend :: store packet with cmd %s to outgoingStore",t.cmd);let r,s=t;if("publish"===s.cmd&&(s=p(t),r=O(e,s),r))return n&&n(r);e.outgoingStore.put(s,(function(r){if(r)return n&&n(r);a(),T(e,t,n)}))}function E(e){g("nop ::",e)}function R(e,t){let n;const a=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:C(),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 s,this.incomingStore=t.incomingStore||new s,this.queueQoSZero=void 0===t.queueQoSZero||t.queueQoSZero,this._resubscribeTopics={},this.messageIdToTopic={},this.pingTimer=null,this.connected=!1,this.disconnecting=!1,this.queue=[],this.connackTimer=null,this.reconnectTimer=null,this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={},this._storeProcessingQueue=[],this.outgoing={},this._firstConnection=!0,t.topicAliasMaximum>0&&(t.topicAliasMaximum>65535?g("MqttClient :: options.topicAliasMaximum is out of range"):this.topicAliasRecv=new o(t.topicAliasMaximum)),this.on("connect",(function(){const e=this.queue;function t(){const n=e.shift();g("deliver :: entry %o",n);let r=null;if(!n)return void a._resubscribe();r=n.packet,g("deliver :: call _sendPacket for %o",r);let s=!0;r.messageId&&0!==r.messageId&&(a.messageIdProvider.register(r.messageId)||(s=!1)),s?a._sendPacket(r,(function(e){n.cb&&n.cb(e),t()})):(g("messageId: %d has already used. The message is skipped and removed.",r.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!==a.pingTimer&&(a.pingTimer.clear(),a.pingTimer=null),this.topicAliasRecv&&this.topicAliasRecv.clear(),g("close :: calling _setupReconnect"),this._setupReconnect()})),r.call(this),g("MqttClient :: setting up stream"),this._setupStream()}u(R,r),R.prototype._setupStream=function(){const e=this,t=new d,n=c.parser(this.options);let a=null;const r=[];function s(){if(r.length)y(o);else{const e=a;a=null,e()}}function o(){g("work :: getting next packet in queue");const t=r.shift();if(t)g("work :: packet pulled from queue"),e._handlePacket(t,s);else{g("work :: no packets in queue");const e=a;a=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)):E(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."),r.push(e)})),t._write=function(e,t,r){a=r,g("writable stream :: parsing buffer"),n.parse(e),o()},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),A(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)),T(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&&T(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!==E?e(new Error("client disconnecting")):this.emit("error",new Error("client disconnecting"))),this.disconnecting},R.prototype.publish=function(e,t,n,a){g("publish :: message `%s` to topic `%s`",t,e);const r=this.options;if("function"==typeof n&&(a=n,n=null),n=m({qos:0,retain:!1,dup:!1},n),this._checkDisconnecting(a))return this;const s=this,o=function(){let o=0;if((1===n.qos||2===n.qos)&&(o=s._nextId(),null===o))return g("No messageId left"),!1;const i={cmd:"publish",topic:e,payload:t,qos:n.qos,retain:n.retain,messageId:o,dup:n.dup};switch(5===r.protocolVersion&&(i.properties=n.properties),g("publish :: qos",n.qos),n.qos){case 1:case 2:s.outgoing[i.messageId]={volatile:!1,cb:a||E},g("MqttClient:publish: packet cmd: %s",i.cmd),s._sendPacket(i,void 0,n.cbStorePut);break;default:g("MqttClient:publish: packet cmd: %s",i.cmd),s._sendPacket(i,a,n.cbStorePut)}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!o())&&this._storeProcessingQueue.push({invoke:o,cbStorePut:n.cbStorePut,callback:a}),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 a=t.shift();const r=a.resubscribe;let s=t.pop()||E,o=t.pop();const i=this.options.protocolVersion;delete a.resubscribe,"string"==typeof a&&(a=[a]),"function"!=typeof s&&(o=s,s=E);const c=f.validateTopics(a);if(null!==c)return v(s,new Error("Invalid topic "+c)),this;if(this._checkDisconnecting(s))return g("subscribe: discconecting true"),this;const l={qos:0};if(5===i&&(l.nl=!1,l.rap=!1,l.rh=0),o=m(l,o),Array.isArray(a)?a.forEach((function(t){if(g("subscribe: array topic %s",t),!Object.prototype.hasOwnProperty.call(e._resubscribeTopics,t)||e._resubscribeTopics[t].qos<o.qos||r){const e={topic:t,qos:o.qos};5===i&&(e.nl=o.nl,e.rap=o.rap,e.rh=o.rh,e.properties=o.properties),g("subscribe: pushing topic `%s` and qos `%s` to subs list",e.topic,e.qos),n.push(e)}})):Object.keys(a).forEach((function(t){if(g("subscribe: object topic %s",t),!Object.prototype.hasOwnProperty.call(e._resubscribeTopics,t)||e._resubscribeTopics[t].qos<a[t].qos||r){const e={topic:t,qos:a[t].qos};5===i&&(e.nl=a[t].nl,e.rap=a[t].rap,e.rh=a[t].rh,e.properties=o.properties),g("subscribe: pushing `%s` to subs list",e),n.push(e)}})),!n.length)return s(null,[]),this;const d=function(){const t=e._nextId();if(null===t)return g("No messageId left"),!1;const a={cmd:"subscribe",subscriptions:n,qos:1,retain:!1,dup:!1,messageId:t};if(o.properties&&(a.properties=o.properties),e.options.resubscribe){g("subscribe :: resubscribe true");const t=[];n.forEach((function(n){if(e.options.reconnectPeriod>0){const a={qos:n.qos};5===i&&(a.nl=n.nl||!1,a.rap=n.rap||!1,a.rh=n.rh||0,a.properties=n.properties),e._resubscribeTopics[n.topic]=a,t.push(n.topic)}})),e.messageIdToTopic[a.messageId]=t}return e.outgoing[a.messageId]={volatile:!0,cb:function(e,t){if(!e){const e=t.granted;for(let t=0;t<e.length;t+=1)n[t].qos=e[t]}s(e,n)}},g("subscribe :: call _sendPacket"),e._sendPacket(a),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!d())&&this._storeProcessingQueue.push({invoke:d,callback:s}),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(),a=t.pop()||E,r=t.pop();"string"==typeof n&&(n=[n]),"function"!=typeof a&&(r=a,a=E);const s=f.validateTopics(n);if(null!==s)return v(a,new Error("Invalid topic "+s)),this;if(e._checkDisconnecting(a))return this;const o=function(){const t=e._nextId();if(null===t)return g("No messageId left"),!1;const s={cmd:"unsubscribe",qos:1,messageId:t};return"string"==typeof n?s.unsubscriptions=[n]:Array.isArray(n)&&(s.unsubscriptions=n),e.options.resubscribe&&s.unsubscriptions.forEach((function(t){delete e._resubscribeTopics[t]})),"object"==typeof r&&r.properties&&(s.properties=r.properties),e.outgoing[s.messageId]={volatile:!0,cb:a},g("unsubscribe: call _sendPacket"),e._sendPacket(s),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!o())&&this._storeProcessingQueue.push({invoke:o,callback:a}),this},R.prototype.end=function(e,t,n){const a=this;function r(){g("end :: closeStores: closing incoming and outgoing stores"),a.disconnected=!0,a.incomingStore.close((function(e){a.outgoingStore.close((function(t){if(g("end :: closeStores: emitting end"),a.emit("end"),n){const a=e||t;g("end :: closeStores: invoking callback with args"),n(a)}}))})),a._deferredReconnect&&a._deferredReconnect()}function s(){g("end :: (%s) :: finish :: calling _cleanUp with force %s",a.options.clientId,e),a._cleanUp(e,(()=>{g("end :: finish :: calling process.nextTick on closeStores"),y(r.bind(a))}),t)}return g("end :: (%s)",this.options.clientId),null!=e&&"boolean"==typeof e||(n=t||E,t=e,e=!1,"object"!=typeof t&&(n=t,t=null,"function"!=typeof n&&(n=E))),"object"!=typeof t&&(n=t,t=null),g("end :: cb? %s",!!n),n=n||E,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",a.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,s,10))):(g("end :: (%s) :: immediately calling finish",a.options.clientId),s()),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 s,t.outgoingStore=t.options.outgoingStore||new s,t.disconnecting=!1,t.disconnected=!1,t._deferredReconnect=null,t._reconnect()};return this.disconnecting&&!this.disconnected?this._deferredReconnect=n:n(),this},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&&k(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||E,t=t||E;const a=S(this,e);if(a)t(a);else{if(!this.connected)return"auth"===e.cmd?(this._shiftPingInterval(),void T(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 _(this,e,t,n);default:return void T(this,e,t)}switch(e.qos){case 2:case 1:_(this,e,t,n);break;default:T(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||E;let a=e;if("publish"===a.cmd){a=p(e);const n=O(this,a);if(n)return t&&t(n)}0===(a.qos||0)&&this.queueQoSZero||"publish"!==a.cmd?this.queue.push({packet:a,cb:t}):a.qos>0?(t=this.outgoing[a.messageId]?this.outgoing[a.messageId].cb:null,this.outgoingStore.put(a,(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: "+I[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 a=this;this.handleAuth(e,(function(e,t){if(e)a.emit("error",e);else if(24===n)a.reconnecting=!1,a._sendPacket(t);else{const t=new Error("Connection refused: "+I[n]);e.code=n,a.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:E;let n=e.topic.toString();const a=e.payload,r=e.qos,s=e.messageId,o=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",r),r){case 2:i.customHandleAcks(n,a,e,(function(n,a){return n instanceof Error||(a=n,n=null),n?o.emit("error",n):-1===c.indexOf(a)?o.emit("error",new Error("Wrong reason code for pubrec")):void(a?o._sendPacket({cmd:"pubrec",messageId:s,reasonCode:a},t):o.incomingStore.put(e,(function(){o._sendPacket({cmd:"pubrec",messageId:s},t)})))}));break;case 1:i.customHandleAcks(n,a,e,(function(r,i){return r instanceof Error||(i=r,r=null),r?o.emit("error",r):-1===c.indexOf(i)?o.emit("error",new Error("Wrong reason code for puback")):(i||o.emit("message",n,a,e),void o.handleMessage(e,(function(e){if(e)return t&&t(e);o._sendPacket({cmd:"puback",messageId:s,reasonCode:i},t)})))}));break;case 0:this.emit("message",n,a,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 a=null;const r=this.outgoing[t]?this.outgoing[t].cb:null,s=this;let o;if(r){switch(g("_handleAck :: packet type",n),n){case"pubcomp":case"puback":{const n=e.reasonCode;n&&n>0&&16!==n&&(o=new Error("Publish error: "+I[n]),o.code=n,r(o,e)),delete this.outgoing[t],this.outgoingStore.del(e,r),this.messageIdProvider.deallocate(t),this._invokeStoreProcessingQueue();break}case"pubrec":{a={cmd:"pubrel",qos:2,messageId:t};const n=e.reasonCode;n&&n>0&&16!==n?(o=new Error("Publish error: "+I[n]),o.code=n,r(o,e)):this._sendPacket(a);break}case"suback":delete this.outgoing[t],this.messageIdProvider.deallocate(t);for(let n=0;n<e.granted.length;n++)if(0!=(128&e.granted[n])){const e=this.messageIdToTopic[t];e&&e.forEach((function(e){delete s._resubscribeTopics[e]}))}this._invokeStoreProcessingQueue(),r(null,e);break;case"unsuback":delete this.outgoing[t],this.messageIdProvider.deallocate(t),this._invokeStoreProcessingQueue(),r(null);break;default:s.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:E;const n=e.messageId,a=this,r={cmd:"pubcomp",messageId:n};a.incomingStore.get(e,(function(e,n){e?a._sendPacket(r,t):(a.emit("message",n.topic,n.payload,n),a.handleMessage(n,(function(e){if(e)return t(e);a.incomingStore.del(n,E),a._sendPacket(r,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 a=t.outgoingStore.createStream();function r(){t._storeProcessing=!1,t._packetIdsDuringStoreProcessing={}}function s(){a.destroy(),a=null,t._flushStoreProcessingQueue(),r()}function o(){if(!a)return;t._storeProcessing=!0;const e=a.read(1);let n;e?t._packetIdsDuringStoreProcessing[e.messageId]?o():t.disconnecting||t.reconnectTimer?a.destroy&&a.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),o()}},t._packetIdsDuringStoreProcessing[e.messageId]=!0,t.messageIdProvider.register(e.messageId)?t._sendPacket(e):g("messageId: %d has already used.",e.messageId)):a.once("readable",o)}t.once("close",s),a.on("error",(function(e){r(),t._flushStoreProcessingQueue(),t.removeListener("close",s),t.emit("error",e)})),a.on("end",(function(){let a=!0;for(const e in t._packetIdsDuringStoreProcessing)if(!t._packetIdsDuringStoreProcessing[e]){a=!1;break}a?(r(),t.removeListener("close",s),t._invokeAllStoreProcessingQueue(),t.emit("connect",e)):n()})),o()}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!==pn?pn:"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:a}=e("buffer"),r=e("readable-stream").Transform,s=e("duplexify");let o,i,c,l=!1;function d(){const e=new r;return e._write=function(e,t,n){o.sendSocketMessage({data:e.buffer,success:function(){n()},fail:function(){n(new Error)}})},e._flush=function(e){o.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 a=n+"://"+e.hostname+e.path;return e.port&&80!==e.port&&443!==e.port&&(a=n+"://"+e.hostname+":"+e.port+e.path),"function"==typeof e.transformWsUrl&&(a=e.transformWsUrl(a,e,t)),a}function p(){l||(l=!0,o.onSocketOpen((function(){c.setReadable(i),c.setWritable(i),c.emit("connect")})),o.onSocketMessage((function(e){if("string"==typeof e.data){const t=a.from(e.data,"base64");i.push(t)}else{const t=new FileReader;t.addEventListener("load",(function(){let e=t.result;e=e instanceof ArrayBuffer?a.from(e):a.from(e,"utf8"),i.push(e)})),t.readAsArrayBuffer(e.data)}})),o.onSocketClose((function(){c.end(),c.destroy()})),o.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 a=h(t,e);return o=t.my,o.connectSocket({url:a,protocols:n}),i=d(),c=s.obj(),p(),c}t.exports=f},{buffer:17,duplexify:20,"readable-stream":69}],3:[function(e,t,n){const a=e("net"),r=e("debug")("mqttjs:tcp");function s(e,t){t.port=t.port||1883,t.hostname=t.hostname||t.host||"localhost";const n=t.port,s=t.hostname;return r("port %d and host %s",n,s),a.createConnection(n,s)}t.exports=s},{debug:18,net:16}],4:[function(e,t,n){const a=e("tls"),r=e("net"),s=e("debug")("mqttjs:tls");function o(e,t){t.port=t.port||8883,t.host=t.hostname||t.host||"localhost",0===r.isIP(t.host)&&(t.servername=t.host),t.rejectUnauthorized=!1!==t.rejectUnauthorized,delete t.path,s("port %d host %s rejectUnauthorized %b",t.port,t.host,t.rejectUnauthorized);const n=a.connect(t);function o(a){t.rejectUnauthorized&&e.emit("error",a),n.end()}return n.on("secureConnect",(function(){t.rejectUnauthorized&&!n.authorized?n.emit("error",new Error("TLS not authorized")):n.removeListener("error",o)})),n.on("error",o),n}t.exports=o},{debug:18,net:16,tls:16}],5:[function(e,t,n){(function(n){(function(){const{Buffer:a}=e("buffer"),r=e("ws"),s=e("debug")("mqttjs:ws"),o=e("duplexify"),i=e("readable-stream").Transform,c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"],l=void 0!==n&&"browser"===n.title||"function"==typeof __webpack_require__;function d(e,t){let n=e.protocol+"://"+e.hostname+":"+e.port+e.path;return"function"==typeof e.transformWsUrl&&(n=e.transformWsUrl(n,e,t)),n}function u(e){const t=e;return e.hostname||(t.hostname="localhost"),e.port||("wss"===e.protocol?t.port=443:t.port=80),e.path||(t.path="/"),e.wsOptions||(t.wsOptions={}),l||"wss"!==e.protocol||c.forEach((function(n){Object.prototype.hasOwnProperty.call(e,n)&&!Object.prototype.hasOwnProperty.call(e.wsOptions,n)&&(t.wsOptions[n]=e[n])})),t}function h(e){const t=u(e);if(t.hostname||(t.hostname=t.host),!t.hostname){if("undefined"==typeof document)throw new Error("Could not determine host. Specify host manually.");const e=new URL(document.URL);t.hostname=e.hostname,t.port||(t.port=e.port)}return void 0===t.objectMode&&(t.objectMode=!(!0===t.binary||void 0===t.binary)),t}function p(e,t,n){s("createWebSocket"),s("protocol: "+n.protocolId+" "+n.protocolVersion);const a="MQIsdp"===n.protocolId&&3===n.protocolVersion?"mqttv3.1":"mqtt";return s("creating new Websocket for url: "+t+" and protocol: "+a),new r(t,[a],n.wsOptions)}function f(e,t){const n="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt",a=d(t,e),r=new WebSocket(a,[n]);return r.binaryType="arraybuffer",r}function m(e,t){s("streamBuilder");const n=u(t),a=d(n,e),o=p(e,a,n),i=r.createWebSocketStream(o,n.wsOptions);return i.url=a,o.on("close",(()=>{i.destroy()})),i}function g(e,t){let n;s("browserStreamBuilder");const r=h(t).browserBufferSize||524288,c=t.browserBufferTimeout||1e3,l=!t.objectMode,d=f(e,t),u=m(t,I,C);t.objectMode||(u._writev=w),u.on("close",(()=>{d.close()}));const p=void 0!==d.addEventListener;function m(e,t,n){const a=new i({objectModeMode:e.objectMode});return a._write=t,a._flush=n,a}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?a.from(t):a.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]=a.from(e[t],"utf8"):n[t]=e[t].chunk;this._write(a.concat(n),"binary",t)}function I(e,t,n){d.bufferedAmount>r&&setTimeout(I,c,e,t,n),l&&"string"==typeof e&&(e=a.from(e,"utf8"));try{d.send(e)}catch(e){return n(e)}n()}function C(e){d.close(),e()}return d.readyState===d.OPEN?n=u:(n=n=o(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:a}=e("buffer"),r=e("readable-stream").Transform,s=e("duplexify");let o,i,c;function l(){const e=new r;return e._write=function(e,t,n){o.send({data:e.buffer,success:function(){n()},fail:function(e){n(new Error(e))}})},e._flush=function(e){o.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 a=n+"://"+e.hostname+e.path;return e.port&&80!==e.port&&443!==e.port&&(a=n+"://"+e.hostname+":"+e.port+e.path),"function"==typeof e.transformWsUrl&&(a=e.transformWsUrl(a,e,t)),a}function h(){o.onOpen((function(){c.setReadable(i),c.setWritable(i),c.emit("connect")})),o.onMessage((function(e){let t=e.data;t=t instanceof ArrayBuffer?a.from(t):a.from(t,"utf8"),i.push(t)})),o.onClose((function(){c.end(),c.destroy()})),o.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 a=u(t,e);o=wx.connectSocket({url:a,protocols:[n]}),i=l(),c=s.obj(),c._destroy=function(e,t){o.close({success:function(){t&&t(e)}})};const r=c.destroy;return c.destroy=function(){c.destroy=r;const e=this;setTimeout((function(){o.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 a(){if(!(this instanceof a))return new a;this.nextId=Math.max(1,Math.floor(65535*Math.random()))}a.prototype.allocate=function(){const e=this.nextId++;return 65536===this.nextId&&(this.nextId=1),e},a.prototype.getLastAllocated=function(){return 1===this.nextId?65535:this.nextId-1},a.prototype.register=function(e){return!0},a.prototype.deallocate=function(e){},a.prototype.clear=function(){},t.exports=a},{}],8:[function(e,t,n){const a=e("xtend"),r=e("readable-stream").Readable,s={objectMode:!0},o={clean:!0};function i(e){if(!(this instanceof i))return new i(e);this.options=e||{},this.options=a(o,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 r(s),t=[];let n=!1,a=0;return this._inflights.forEach((function(e,n){t.push(e)})),e._read=function(){!n&&a<t.length?this.push(t[a++]):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 a(e){if(!(this instanceof a))return new a(e);this.aliasToTopic={},this.max=e}a.prototype.put=function(e,t){return!(0===t||t>this.max||(this.aliasToTopic[t]=e,this.length=Object.keys(this.aliasToTopic).length,0))},a.prototype.getTopicByAlias=function(e){return this.aliasToTopic[e]},a.prototype.clear=function(){this.aliasToTopic={}},t.exports=a},{}],10:[function(e,t,n){const a=e("lru-cache"),r=e("number-allocator").NumberAllocator;function s(e){if(!(this instanceof s))return new s(e);e>0&&(this.aliasToTopic=new a({max:e}),this.topicToAlias={},this.numberAllocator=new r(1,e),this.max=e,this.length=0)}s.prototype.put=function(e,t){if(0===t||t>this.max)return!1;const n=this.aliasToTopic.get(t);return n&&delete this.topicToAlias[n],this.aliasToTopic.set(t,e),this.topicToAlias[e]=t,this.numberAllocator.use(t),this.length=this.aliasToTopic.length,!0},s.prototype.getTopicByAlias=function(e){return this.aliasToTopic.get(e)},s.prototype.getAliasByTopic=function(e){const t=this.topicToAlias[e];return void 0!==t&&this.aliasToTopic.get(t),t},s.prototype.clear=function(){this.aliasToTopic.reset(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0},s.prototype.getLruAlias=function(){const e=this.numberAllocator.firstVacant();return e||this.aliasToTopic.keys()[this.aliasToTopic.length-1]},t.exports=s},{"lru-cache":37,"number-allocator":46}],11:[function(e,t,n){function a(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 r(e){if(0===e.length)return"empty_topic_list";for(let t=0;t<e.length;t++)if(!a(e[t]))return e[t];return null}t.exports={validateTopics:r}},{}],12:[function(e,t,n){(function(n){(function(){const a=e("../client"),r=e("../store"),s=e("url"),o=e("xtend"),i=e("debug")("mqttjs"),c={};function l(e){let t;e.auth&&(t=e.auth.match(/^(.+):(.+)$/),t?(e.username=t[1],e.password=t[2]):e.username=e.auth)}function d(e,t){if(i("connecting to an MQTT broker..."),"object"!=typeof e||t||(t=e,e=null),t=t||{},e){const n=s.parse(e,!0);if(null!=n.port&&(n.port=Number(n.port)),null===(t=o(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 r=new a(n,t);return r.on("error",(function(){})),r}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=a,t.exports.Store=r}).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 a=[],r=[],s="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,c=o.length;i<c;++i)a[i]=o[i],r[o.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],a=t[1];return 3*(n+a)/4-a}function u(e,t,n){return 3*(t+n)/4-n}function h(e){var t,n,a=l(e),o=a[0],i=a[1],c=new s(u(e,o,i)),d=0,h=i>0?o-4:o;for(n=0;n<h;n+=4)t=r[e.charCodeAt(n)]<<18|r[e.charCodeAt(n+1)]<<12|r[e.charCodeAt(n+2)]<<6|r[e.charCodeAt(n+3)],c[d++]=t>>16&255,c[d++]=t>>8&255,c[d++]=255&t;return 2===i&&(t=r[e.charCodeAt(n)]<<2|r[e.charCodeAt(n+1)]>>4,c[d++]=255&t),1===i&&(t=r[e.charCodeAt(n)]<<10|r[e.charCodeAt(n+1)]<<4|r[e.charCodeAt(n+2)]>>2,c[d++]=t>>8&255,c[d++]=255&t),c}function p(e){return a[e>>18&63]+a[e>>12&63]+a[e>>6&63]+a[63&e]}function f(e,t,n){for(var a,r=[],s=t;s<n;s+=3)a=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(255&e[s+2]),r.push(p(a));return r.join("")}function m(e){for(var t,n=e.length,r=n%3,s=[],o=16383,i=0,c=n-r;i<c;i+=o)s.push(f(e,i,i+o>c?c:i+o));return 1===r?(t=e[n-1],s.push(a[t>>2]+a[t<<4&63]+"==")):2===r&&(t=(e[n-2]<<8)+e[n-1],s.push(a[t>>10]+a[t>>4&63]+a[t<<2&63]+"=")),s.join("")}r["-".charCodeAt(0)]=62,r["_".charCodeAt(0)]=63},{}],14:[function(e,t,n){const{Buffer:a}=e("buffer"),r=Symbol.for("BufferList");function s(e){if(!(this instanceof s))return new s(e);s._init.call(this,e)}s._init=function(e){Object.defineProperty(this,r,{value:!0}),this._bufs=[],this.length=0,e&&this.append(e)},s.prototype._new=function(e){return new s(e)},s.prototype._offset=function(e){if(0===e)return[0,0];let t=0;for(let n=0;n<this._bufs.length;n++){const a=t+this._bufs[n].length;if(e<a||n===this._bufs.length-1)return[n,e-t];t=a}},s.prototype._reverseOffset=function(e){const t=e[0];let n=e[1];for(let e=0;e<t;e++)n+=this._bufs[e].length;return n},s.prototype.get=function(e){if(e>this.length||e<0)return;const t=this._offset(e);return this._bufs[t[0]][t[1]]},s.prototype.slice=function(e,t){return"number"==typeof e&&e<0&&(e+=this.length),"number"==typeof t&&t<0&&(t+=this.length),this.copy(null,0,e,t)},s.prototype.copy=function(e,t,n,r){if(("number"!=typeof n||n<0)&&(n=0),("number"!=typeof r||r>this.length)&&(r=this.length),n>=this.length)return e||a.alloc(0);if(r<=0)return e||a.alloc(0);const s=!!e,o=this._offset(n),i=r-n;let c=i,l=s&&t||0,d=o[1];if(0===n&&r===this.length){if(!s)return 1===this._bufs.length?this._bufs[0]:a.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[o[0]].length-d)return s?this._bufs[o[0]].copy(e,t,d,d+c):this._bufs[o[0]].slice(d,d+c);s||(e=a.allocUnsafe(i));for(let t=o[0];t<this._bufs.length;t++){const n=this._bufs[t].length-d;if(!(c>n)){this._bufs[t].copy(e,l,d,d+c),l+=n;break}this._bufs[t].copy(e,l,d),l+=n,c-=n,d&&(d=0)}return e.length>l?e.slice(0,l):e},s.prototype.shallowSlice=function(e,t){if(e=e||0,t="number"!=typeof t?this.length:t,e<0&&(e+=this.length),t<0&&(t+=this.length),e===t)return this._new();const n=this._offset(e),a=this._offset(t),r=this._bufs.slice(n[0],a[0]+1);return 0===a[1]?r.pop():r[r.length-1]=r[r.length-1].slice(0,a[1]),0!==n[1]&&(r[0]=r[0].slice(n[1])),this._new(r)},s.prototype.toString=function(e,t,n){return this.slice(t,n).toString(e)},s.prototype.consume=function(e){if(e=Math.trunc(e),Number.isNaN(e)||e<=0)return this;for(;this._bufs.length;){if(!(e>=this._bufs[0].length)){this._bufs[0]=this._bufs[0].slice(e),this.length-=e;break}e-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift()}return this},s.prototype.duplicate=function(){const e=this._new();for(let t=0;t<this._bufs.length;t++)e.append(this._bufs[t]);return e},s.prototype.append=function(e){if(null==e)return this;if(e.buffer)this._appendBuffer(a.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(a.from(e));return this},s.prototype._appendBuffer=function(e){this._bufs.push(e),this.length+=e.length},s.prototype.indexOf=function(e,t,n){if(void 0===n&&"string"==typeof t&&(n=t,t=void 0),"function"==typeof e||Array.isArray(e))throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');if("number"==typeof e?e=a.from([e]):"string"==typeof e?e=a.from(e,n):this._isBufferList(e)?e=e.slice():Array.isArray(e.buffer)?e=a.from(e.buffer,e.byteOffset,e.byteLength):a.isBuffer(e)||(e=a.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 r=this._offset(t);let s=r[0],o=r[1];for(;s<this._bufs.length;s++){const t=this._bufs[s];for(;o<t.length;)if(t.length-o>=e.length){const n=t.indexOf(e,o);if(-1!==n)return this._reverseOffset([s,n]);o=t.length-e.length+1}else{const t=this._reverseOffset([s,o]);if(this._match(t,e))return t;o++}o=0}return-1},s.prototype._match=function(e,t){if(this.length-e<t.length)return!1;for(let n=0;n<t.length;n++)if(this.get(e+n)!==t[n])return!1;return!0},function(){const e={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(const t in e)!function(t){null===e[t]?s.prototype[t]=function(e,n){return this.slice(e,e+n)[t](0,n)}:s.prototype[t]=function(n=0){return this.slice(n,n+e[t])[t](0)}}(t)}(),s.prototype._isBufferList=function(e){return e instanceof s||s.isBufferList(e)},s.isBufferList=function(e){return null!=e&&e[r]},t.exports=s},{buffer:17}],15:[function(e,t,n){const a=e("readable-stream").Duplex,r=e("inherits"),s=e("./BufferList");function o(e){if(!(this instanceof o))return new o(e);if("function"==typeof e){this._callback=e;const t=function(e){this._callback&&(this._callback(e),this._callback=null)}.bind(this);this.on("pipe",(function(e){e.on("error",t)})),this.on("unpipe",(function(e){e.removeListener("error",t)})),e=null}s._init.call(this,e),a.call(this)}r(o,a),Object.assign(o.prototype,s.prototype),o.prototype._new=function(e){return new o(e)},o.prototype._write=function(e,t,n){this._appendBuffer(e),"function"==typeof n&&n()},o.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)},o.prototype.end=function(e){a.prototype.end.call(this,e),this._callback&&(this._callback(null,this.slice()),this._callback=null)},o.prototype._destroy=function(e,t){this._bufs.length=0,this.length=0,t(e)},o.prototype._isBufferList=function(e){return e instanceof o||e instanceof s||o.isBufferList(e)},o.isBufferList=s.isBufferList,t.exports=o,t.exports.BufferListStream=o,t.exports.BufferList=s},{"./BufferList":14,inherits:24,"readable-stream":69}],16:[function(e,t,n){},{}],17:[function(e,t,n){(function(t){(function(){var t=e("base64-js"),a=e("ieee754");n.Buffer=i,n.SlowBuffer=y,n.INSPECT_MAX_BYTES=50;var r=2147483647;function s(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(e){return!1}}function o(e){if(e>r)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 a=e.valueOf&&e.valueOf();if(null!=a&&a!==e)return i.from(a,t,n);var r=m(e);if(r)return r;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?o(e):void 0!==t?"string"==typeof n?o(e).fill(t,n):o(e).fill(t):o(e)}function u(e){return l(e),o(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),a=o(n),r=a.write(e,t);return r!==n&&(a=a.slice(0,r)),a}function p(e){for(var t=e.length<0?0:0|g(e.length),n=o(t),a=0;a<t;a+=1)n[a]=255&e[a];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 a;return(a=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n)).__proto__=i.prototype,a}function m(e){if(i.isBuffer(e)){var t=0|g(e.length),n=o(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0!==e.length?"number"!=typeof e.length||Y(e.length)?o(0):p(e):"Buffer"===e.type&&Array.isArray(e.data)?p(e.data):void 0}function g(e){if(e>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.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,a=arguments.length>2&&!0===arguments[2];if(!a&&0===n)return 0;for(var r=!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(r)return a?-1:z(e).length;t=(""+t).toLowerCase(),r=!0}}function b(e,t,n){var a=!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 D(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 E(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return x(this,t,n);default:if(a)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),a=!0}}function w(e,t,n){var a=e[t];e[t]=e[n],e[n]=a}function I(e,t,n,a,r){if(0===e.length)return-1;if("string"==typeof n?(a=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),Y(n=+n)&&(n=r?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(r)return-1;n=e.length-1}else if(n<0){if(!r)return-1;n=0}if("string"==typeof t&&(t=i.from(t,a)),i.isBuffer(t))return 0===t.length?-1:C(e,t,n,a,r);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?r?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):C(e,[t],n,a,r);throw new TypeError("val must be string, number or Buffer")}function C(e,t,n,a,r){var s,o=1,i=e.length,c=t.length;if(void 0!==a&&("ucs2"===(a=String(a).toLowerCase())||"ucs-2"===a||"utf16le"===a||"utf-16le"===a)){if(e.length<2||t.length<2)return-1;o=2,i/=2,c/=2,n/=2}function l(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(r){var d=-1;for(s=n;s<i;s++)if(l(e,s)===l(t,-1===d?0:s-d)){if(-1===d&&(d=s),s-d+1===c)return d*o}else-1!==d&&(s-=s-d),d=-1}else for(n+c>i&&(n=i-c),s=n;s>=0;s--){for(var u=!0,h=0;h<c;h++)if(l(e,s+h)!==l(t,h)){u=!1;break}if(u)return s}return-1}function S(e,t,n,a){n=Number(n)||0;var r=e.length-n;a?(a=Number(a))>r&&(a=r):a=r;var s=t.length;a>s/2&&(a=s/2);for(var o=0;o<a;++o){var i=parseInt(t.substr(2*o,2),16);if(Y(i))return o;e[n+o]=i}return o}function O(e,t,n,a){return W(z(t,e.length-n),e,n,a)}function T(e,t,n,a){return W(V(t),e,n,a)}function k(e,t,n,a){return T(e,t,n,a)}function A(e,t,n,a){return W(J(t),e,n,a)}function _(e,t,n,a){return W(H(t,e.length-n),e,n,a)}function E(e,n,a){return 0===n&&a===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,a))}function R(e,t,n){n=Math.min(e.length,n);for(var a=[],r=t;r<n;){var s,o,i,c,l=e[r],d=null,u=l>239?4:l>223?3:l>191?2:1;if(r+u<=n)switch(u){case 1:l<128&&(d=l);break;case 2:128==(192&(s=e[r+1]))&&(c=(31&l)<<6|63&s)>127&&(d=c);break;case 3:s=e[r+1],o=e[r+2],128==(192&s)&&128==(192&o)&&(c=(15&l)<<12|(63&s)<<6|63&o)>2047&&(c<55296||c>57343)&&(d=c);break;case 4:s=e[r+1],o=e[r+2],i=e[r+3],128==(192&s)&&128==(192&o)&&128==(192&i)&&(c=(15&l)<<18|(63&s)<<12|(63&o)<<6|63&i)>65535&&c<1114112&&(d=c)}null===d?(d=65533,u=1):d>65535&&(d-=65536,a.push(d>>>10&1023|55296),d=56320|1023&d),a.push(d),r+=u}return M(a)}n.kMaxLength=r,i.TYPED_ARRAY_SUPPORT=s(),i.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(i.prototype,"parent",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.buffer}}),Object.defineProperty(i.prototype,"offset",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.byteOffset}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&i[Symbol.species]===i&&Object.defineProperty(i,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),i.poolSize=8192,i.from=function(e,t,n){return c(e,t,n)},i.prototype.__proto__=Uint8Array.prototype,i.__proto__=Uint8Array,i.alloc=function(e,t,n){return d(e,t,n)},i.allocUnsafe=function(e){return u(e)},i.allocUnsafeSlow=function(e){return u(e)},i.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==i.prototype},i.compare=function(e,t){if(G(e,Uint8Array)&&(e=i.from(e,e.offset,e.byteLength)),G(t,Uint8Array)&&(t=i.from(t,t.offset,t.byteLength)),!i.isBuffer(e)||!i.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var n=e.length,a=t.length,r=0,s=Math.min(n,a);r<s;++r)if(e[r]!==t[r]){n=e[r],a=t[r];break}return n<a?-1:a<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 a=i.allocUnsafe(t),r=0;for(n=0;n<e.length;++n){var s=e[n];if(G(s,Uint8Array)&&(s=i.from(s)),!i.isBuffer(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(a,r),r+=s.length}return a},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,a,r){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===a&&(a=0),void 0===r&&(r=this.length),t<0||n>e.length||a<0||r>this.length)throw new RangeError("out of range index");if(a>=r&&t>=n)return 0;if(a>=r)return-1;if(t>=n)return 1;if(this===e)return 0;for(var s=(r>>>=0)-(a>>>=0),o=(n>>>=0)-(t>>>=0),c=Math.min(s,o),l=this.slice(a,r),d=e.slice(t,n),u=0;u<c;++u)if(l[u]!==d[u]){s=l[u],o=d[u];break}return s<o?-1:o<s?1:0},i.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},i.prototype.indexOf=function(e,t,n){return I(this,e,t,n,!0)},i.prototype.lastIndexOf=function(e,t,n){return I(this,e,t,n,!1)},i.prototype.write=function(e,t,n,a){if(void 0===t)a="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)a=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===a&&(a="utf8")):(a=n,n=void 0)}var r=this.length-t;if((void 0===n||n>r)&&(n=r),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");a||(a="utf8");for(var s=!1;;)switch(a){case"hex":return S(this,e,t,n);case"utf8":case"utf-8":return O(this,e,t,n);case"ascii":return T(this,e,t,n);case"latin1":case"binary":return k(this,e,t,n);case"base64":return A(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+a);a=(""+a).toLowerCase(),s=!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="",a=0;a<t;)n+=String.fromCharCode.apply(String,e.slice(a,a+=P));return n}function j(e,t,n){var a="";n=Math.min(e.length,n);for(var r=t;r<n;++r)a+=String.fromCharCode(127&e[r]);return a}function U(e,t,n){var a="";n=Math.min(e.length,n);for(var r=t;r<n;++r)a+=String.fromCharCode(e[r]);return a}function D(e,t,n){var a=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>a)&&(n=a);for(var r="",s=t;s<n;++s)r+=Q(e[s]);return r}function x(e,t,n){for(var a=e.slice(t,n),r="",s=0;s<a.length;s+=2)r+=String.fromCharCode(a[s]+256*a[s+1]);return r}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,a,r,s){if(!i.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>r||t<s)throw new RangeError('"value" argument is out of bounds');if(n+a>e.length)throw new RangeError("Index out of range")}function B(e,t,n,a,r,s){if(n+a>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function L(e,t,n,r,s){return t=+t,n>>>=0,s||B(e,t,n,4),a.write(e,t,n,r,23,4),n+4}function F(e,t,n,r,s){return t=+t,n>>>=0,s||B(e,t,n,8),a.write(e,t,n,r,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 a=this.subarray(e,t);return a.__proto__=i.prototype,a},i.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||q(e,t,this.length);for(var a=this[e],r=1,s=0;++s<t&&(r*=256);)a+=this[e+s]*r;return a},i.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||q(e,t,this.length);for(var a=this[e+--t],r=1;t>0&&(r*=256);)a+=this[e+--t]*r;return a},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 a=this[e],r=1,s=0;++s<t&&(r*=256);)a+=this[e+s]*r;return a>=(r*=128)&&(a-=Math.pow(2,8*t)),a},i.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||q(e,t,this.length);for(var a=t,r=1,s=this[e+--a];a>0&&(r*=256);)s+=this[e+--a]*r;return s>=(r*=128)&&(s-=Math.pow(2,8*t)),s},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),a.read(this,e,!0,23,4)},i.prototype.readFloatBE=function(e,t){return e>>>=0,t||q(e,4,this.length),a.read(this,e,!1,23,4)},i.prototype.readDoubleLE=function(e,t){return e>>>=0,t||q(e,8,this.length),a.read(this,e,!0,52,8)},i.prototype.readDoubleBE=function(e,t){return e>>>=0,t||q(e,8,this.length),a.read(this,e,!1,52,8)},i.prototype.writeUIntLE=function(e,t,n,a){e=+e,t>>>=0,n>>>=0,a||N(this,e,t,n,Math.pow(2,8*n)-1,0);var r=1,s=0;for(this[t]=255&e;++s<n&&(r*=256);)this[t+s]=e/r&255;return t+n},i.prototype.writeUIntBE=function(e,t,n,a){e=+e,t>>>=0,n>>>=0,a||N(this,e,t,n,Math.pow(2,8*n)-1,0);var r=n-1,s=1;for(this[t+r]=255&e;--r>=0&&(s*=256);)this[t+r]=e/s&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,a){if(e=+e,t>>>=0,!a){var r=Math.pow(2,8*n-1);N(this,e,t,n,r-1,-r)}var s=0,o=1,i=0;for(this[t]=255&e;++s<n&&(o*=256);)e<0&&0===i&&0!==this[t+s-1]&&(i=1),this[t+s]=(e/o>>0)-i&255;return t+n},i.prototype.writeIntBE=function(e,t,n,a){if(e=+e,t>>>=0,!a){var r=Math.pow(2,8*n-1);N(this,e,t,n,r-1,-r)}var s=n-1,o=1,i=0;for(this[t+s]=255&e;--s>=0&&(o*=256);)e<0&&0===i&&0!==this[t+s+1]&&(i=1),this[t+s]=(e/o>>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,a){if(!i.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),a||0===a||(a=this.length),t>=e.length&&(t=e.length),t||(t=0),a>0&&a<n&&(a=n),a===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(a<0)throw new RangeError("sourceEnd out of bounds");a>this.length&&(a=this.length),e.length-t<a-n&&(a=e.length-t+n);var r=a-n;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,n,a);else if(this===e&&n<t&&t<a)for(var s=r-1;s>=0;--s)e[s+t]=this[s+n];else Uint8Array.prototype.set.call(e,this.subarray(n,a),t);return r},i.prototype.fill=function(e,t,n,a){if("string"==typeof e){if("string"==typeof t?(a=t,t=0,n=this.length):"string"==typeof n&&(a=n,n=this.length),void 0!==a&&"string"!=typeof a)throw new TypeError("encoding must be a string");if("string"==typeof a&&!i.isEncoding(a))throw new TypeError("Unknown encoding: "+a);if(1===e.length){var r=e.charCodeAt(0);("utf8"===a&&r<128||"latin1"===a)&&(e=r)}}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;var s;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(s=t;s<n;++s)this[s]=e;else{var o=i.isBuffer(e)?e:i.from(e,a),c=o.length;if(0===c)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(s=0;s<n-t;++s)this[s+t]=o[s%c]}return this};var K=/[^+/0-9A-Za-z-_]/g;function $(e){if((e=(e=e.split("=")[0]).trim().replace(K,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}function Q(e){return e<16?"0"+e.toString(16):e.toString(16)}function z(e,t){var n;t=t||1/0;for(var a=e.length,r=null,s=[],o=0;o<a;++o){if((n=e.charCodeAt(o))>55295&&n<57344){if(!r){if(n>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===a){(t-=3)>-1&&s.push(239,191,189);continue}r=n;continue}if(n<56320){(t-=3)>-1&&s.push(239,191,189),r=n;continue}n=65536+(r-55296<<10|n-56320)}else r&&(t-=3)>-1&&s.push(239,191,189);if(r=null,n<128){if((t-=1)<0)break;s.push(n)}else if(n<2048){if((t-=2)<0)break;s.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;s.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return s}function V(e){for(var t=[],n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}function H(e,t){for(var n,a,r,s=[],o=0;o<e.length&&!((t-=2)<0);++o)a=(n=e.charCodeAt(o))>>8,r=n%256,s.push(r),s.push(a);return s}function J(e){return t.toByteArray($(e))}function W(e,t,n,a){for(var r=0;r<a&&!(r+n>=t.length||r>=e.length);++r)t[r+n]=e[r];return r}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(a){(function(){function r(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))}function s(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;e.splice(1,0,n,"color: inherit");let a=0,r=0;e[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(a++,"%c"===e&&(r=a))})),e.splice(r,0,n)}function o(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!==a&&"env"in a&&(e=a.env.DEBUG),e}function c(){try{return localStorage}catch(e){}}n.formatArgs=s,n.save=o,n.load=i,n.useColors=r,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 a(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 a.colors[Math.abs(t)%a.colors.length]}function a(e){let t,n,s,o=null;function i(...e){if(!i.enabled)return;const n=i,r=Number(new Date),s=r-(t||r);n.diff=s,n.prev=t,n.curr=r,t=r,e[0]=a.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((t,r)=>{if("%%"===t)return"%";o++;const s=a.formatters[r];if("function"==typeof s){const a=e[o];t=s.call(n,a),e.splice(o,1),o--}return t})),a.formatArgs.call(n,e),(n.log||a.log).apply(n,e)}return i.namespace=e,i.useColors=a.useColors(),i.color=a.selectColor(e),i.extend=r,i.destroy=a.destroy,Object.defineProperty(i,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(n!==a.namespaces&&(n=a.namespaces,s=a.enabled(e)),s),set:e=>{o=e}}),"function"==typeof a.init&&a.init(i),i}function r(e,t){const n=a(this.namespace+(void 0===t?":":t)+e);return n.log=this.log,n}function s(e){let t;a.save(e),a.namespaces=e,a.names=[],a.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),r=n.length;for(t=0;t<r;t++)n[t]&&("-"===(e=n[t].replace(/\*/g,".*?"))[0]?a.skips.push(new RegExp("^"+e.substr(1)+"$")):a.names.push(new RegExp("^"+e+"$")))}function o(){const e=[...a.names.map(c),...a.skips.map(c).map((e=>"-"+e))].join(",");return a.enable(""),e}function i(e){if("*"===e[e.length-1])return!0;let t,n;for(t=0,n=a.skips.length;t<n;t++)if(a.skips[t].test(e))return!1;for(t=0,n=a.names.length;t<n;t++)if(a.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 a.debug=a,a.default=a,a.coerce=l,a.disable=o,a.enable=s,a.enabled=i,a.humanize=e("ms"),a.destroy=d,Object.keys(t).forEach((e=>{a[e]=t[e]})),a.names=[],a.skips=[],a.formatters={},a.selectColor=n,a.enable(a.load()),a}t.exports=a},{ms:45}],20:[function(e,t,n){(function(n,a){(function(){var r=e("readable-stream"),s=e("end-of-stream"),o=e("inherits"),i=e("stream-shift"),c=a.from&&a.from!==Uint8Array.from?a.from([0]):new a([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 r.Readable({objectMode:!0,highWaterMark:16}).wrap(e)},m=function(e,t,n){if(!(this instanceof m))return new m(e,t,n);r.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)};o(m,r.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,a=s(e,{writable:!0,readable:!1},u(this,this._forwardEnd)),r=function(){var e=t._ondrain;t._ondrain=null,e&&e()},o=function(){t._writable.removeListener("drain",r),a()};this._unwrite&&n.nextTick(r),this._writable=e,this._writable.on("drain",r),this._unwrite=o,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=s(e,{writable:!1,readable:!0},u(this)),a=function(){t._forward()},r=function(){t.push(null)},o=function(){t._readable2.removeListener("readable",a),t._readable2.removeListener("end",r),n()};this._drained=!0,this._readable=e,this._readable2=e._readableState?e:f(e),this._readable2.on("readable",a),this._readable2.on("end",r),this._unread=o,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 a=this;n.nextTick((function(){a._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),r.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 a=e("once"),r=function(){},s=function(e){return e.setHeader&&"function"==typeof e.abort},o=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=a(c||r);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"))},I=function(){e.req.on("finish",m)};return s(e)?(e.on("complete",m),e.on("abort",b),e.req?I():e.on("request",I)):h&&!l&&(e.on("end",f),e.on("close",f)),o(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",I),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 a=Object.create||O,r=Object.keys||T,s=Function.prototype.bind||k;function o(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=a(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}t.exports=o,o.EventEmitter=o,o.prototype._events=void 0,o.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?o.defaultMaxListeners:e._maxListeners}function u(e,t,n){if(t)e.call(n);else for(var a=e.length,r=C(e,a),s=0;s<a;++s)r[s].call(n)}function h(e,t,n,a){if(t)e.call(n,a);else for(var r=e.length,s=C(e,r),o=0;o<r;++o)s[o].call(n,a)}function p(e,t,n,a,r){if(t)e.call(n,a,r);else for(var s=e.length,o=C(e,s),i=0;i<s;++i)o[i].call(n,a,r)}function f(e,t,n,a,r,s){if(t)e.call(n,a,r,s);else for(var o=e.length,i=C(e,o),c=0;c<o;++c)i[c].call(n,a,r,s)}function m(e,t,n,a){if(t)e.apply(n,a);else for(var r=e.length,s=C(e,r),o=0;o<r;++o)s[o].apply(n,a)}function g(e,t,n,r){var s,o,i;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((o=e._events)?(o.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),o=e._events),i=o[t]):(o=e._events=a(null),e._eventsCount=0),i){if("function"==typeof i?i=o[t]=r?[n,i]:[i,n]:r?i.unshift(n):i.push(n),!i.warned&&(s=d(e))&&s>0&&i.length>s){i.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+i.length+' "'+String(t)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=i.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",c.name,c.message)}}else i=o[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 a={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},r=s.call(y,a);return r.listener=n,a.wrapFn=r,r}function b(e,t,n){var a=e._events;if(!a)return[];var r=a[t];return r?"function"==typeof r?n?[r.listener||r]:[r]:n?S(r):C(r,r.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 I(e,t){for(var n=t,a=n+1,r=e.length;a<r;n+=1,a+=1)e[n]=e[a];e.pop()}function C(e,t){for(var n=new Array(t),a=0;a<t;++a)n[a]=e[a];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 O(e){var t=function(){};return t.prototype=e,new t}function T(e){for(var t in e)Object.prototype.hasOwnProperty.call(e,t);return t}function k(e){var t=this;return function(){return t.apply(e,arguments)}}i?Object.defineProperty(o,"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}}):o.defaultMaxListeners=c,o.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},o.prototype.getMaxListeners=function(){return d(this)},o.prototype.emit=function(e){var t,n,a,r,s,o,i="error"===e;if(o=this._events)i=i&&null==o.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=o[e]))return!1;var l="function"==typeof n;switch(a=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(r=new Array(a-1),s=1;s<a;s++)r[s-1]=arguments[s];m(n,l,this,r)}return!0},o.prototype.addListener=function(e,t){return g(this,e,t,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(e,t){return g(this,e,t,!0)},o.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},o.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},o.prototype.removeListener=function(e,t){var n,r,s,o,i;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(r=this._events))return this;if(!(n=r[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=a(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){i=n[o].listener,s=o;break}if(s<0)return this;0===s?n.shift():I(n,s),1===n.length&&(r[e]=n[0]),r.removeListener&&this.emit("removeListener",e,i||t)}return this},o.prototype.removeAllListeners=function(e){var t,n,s;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=a(null),this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=a(null):delete n[e]),this;if(0===arguments.length){var o,i=r(n);for(s=0;s<i.length;++s)"removeListener"!==(o=i[s])&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=a(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(t)for(s=t.length-1;s>=0;s--)this.removeListener(e,t[s]);return this},o.prototype.listeners=function(e){return b(this,e,!0)},o.prototype.rawListeners=function(e){return b(this,e,!1)},o.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):w.call(e,t)},o.prototype.listenerCount=w,o.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}},{}],23:[function(e,t,n){
|
|
1
|
+
var Amity=function(e,t,n,a,r,s,o,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,g,y=h(n),v=h(a),b=h(r),w=h(s),I=h(o),C=h(i),S=h(c),O=h(d),T=h(u);e.MembershipAcceptanceTypeEnum=void 0,(p=e.MembershipAcceptanceTypeEnum||(e.MembershipAcceptanceTypeEnum={})).AUTOMATIC="automatic",p.INVITATION="invitation",e.AmityAutoSubscription=void 0,(f=e.AmityAutoSubscription||(e.AmityAutoSubscription={})).CHAT="chat",f.NETWORK="network",f.LIVESTREAM="livestream",f.BLOCK="block",e.UserTypeEnum=void 0,(m=e.UserTypeEnum||(e.UserTypeEnum={})).SIGNED_IN="signed-in",m.VISITOR="visitor",m.BOT="bot",e.SearchUsersByEnum=void 0,(g=e.SearchUsersByEnum||(e.SearchUsersByEnum={})).DISPLAY_NAME="displayName",g.PROFILE_HANDLE="profileHandle",g.USER_ID="userId";const k=Object.freeze({FILE:"file",IMAGE:"image",VIDEO:"video",CLIP:"clip",AUDIO:"audio"}),A=Object.freeze({"1080P":"1080p","720P":"720p","480P":"480p","360P":"360p",ORIGINAL:"original"}),_=Object.freeze({UPLOADED:"uploaded",TRANSCODING:"transcoding",TRANSCODED:"transcoded",TRANSCODE_FAILED:"transcodeFailed"}),E=Object.freeze({LOW:"low",MEDIUM:"medium",HIGH:"high",ORIGINAL:"original"});var R,P;e.FileAccessTypeEnum=void 0,(R=e.FileAccessTypeEnum||(e.FileAccessTypeEnum={})).PUBLIC="public",R.NETWORK="network",e.AmityChannelNotificationModeEnum=void 0,(P=e.AmityChannelNotificationModeEnum||(e.AmityChannelNotificationModeEnum={})).Default="default",P.Silent="silent",P.Subscribe="subscribe";const M=Object.freeze({ONLY_ADMIN_CAN_POST:"ONLY_ADMIN_CAN_POST",ADMIN_REVIEW_POST_REQUIRED:"ADMIN_REVIEW_POST_REQUIRED",ANYONE_CAN_POST:"ANYONE_CAN_POST"}),j=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}}),U="ONLY_ADMIN_CAN_POST";var D;e.AmityCommunityType=void 0,(D=e.AmityCommunityType||(e.AmityCommunityType={})).Default="default",D.Event="event";const x=Object.freeze({STORY:"story",CLIP:"clip",CHAT:"chat",POST:"post",MESSAGE:"message"});var q;e.ContentFlagReasonEnum=void 0,(q=e.ContentFlagReasonEnum||(e.ContentFlagReasonEnum={})).CommunityGuidelines="Against community guidelines",q.HarassmentOrBullying="Harassment or bullying",q.SelfHarmOrSuicide="Self-harm or suicide",q.ViolenceOrThreateningContent="Violence or threatening content",q.SellingRestrictedItems="Selling and promoting restricted items",q.SexualContentOrNudity="Sexual content or nudity",q.SpamOrScams="Spam or scams",q.FalseInformation="False information or misinformation",q.Others="Others";const N=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",AUDIO:"audio",CUSTOM:"custom"}),B=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",LIVESTREAM:"liveStream",POLL:"poll",CLIP:"clip",AUDIO:"audio",ROOM:"room"}),L=Object.freeze({TEXT:"text",IMAGE:"image",VIDEO:"video",FILE:"file",AUDIO:"audio",MIXED:"mixed"});var F,K,$,Q,V,z,H,J,W,G,Y,X,Z,ee,te,ne,ae,re,se,oe,ie,ce;e.InvitationTypeEnum=void 0,(F=e.InvitationTypeEnum||(e.InvitationTypeEnum={})).CommunityMemberInvite="communityMemberInvite",F.LivestreamCohostInvite="livestreamCohostInvite",e.InvitationStatusEnum=void 0,(K=e.InvitationStatusEnum||(e.InvitationStatusEnum={})).Pending="pending",K.Approved="approved",K.Rejected="rejected",K.Cancelled="cancelled",e.InvitationSortByEnum=void 0,($=e.InvitationSortByEnum||(e.InvitationSortByEnum={})).FirstCreated="firstCreated",$.LastCreated="lastCreated",e.InvitationTargetTypeEnum=void 0,(Q=e.InvitationTargetTypeEnum||(e.InvitationTargetTypeEnum={})).Community="community",Q.Room="room",e.JoinRequestStatusEnum=void 0,(V=e.JoinRequestStatusEnum||(e.JoinRequestStatusEnum={})).Pending="pending",V.Approved="approved",V.Rejected="rejected",V.Cancelled="cancelled",e.JoinResultStatusEnum=void 0,(z=e.JoinResultStatusEnum||(e.JoinResultStatusEnum={})).Success="success",z.Pending="pending",e.FeedDataTypeEnum=void 0,(H=e.FeedDataTypeEnum||(e.FeedDataTypeEnum={})).Text="text",H.Video="video",H.Image="image",H.File="file",H.Audio="audio",H.LiveStream="liveStream",H.Clip="clip",H.Poll="poll",H.Room="room",e.FeedSortByEnum=void 0,(J=e.FeedSortByEnum||(e.FeedSortByEnum={})).LastCreated="lastCreated",J.FirstCreated="firstCreated",J.LastUpdated="lastUpdated",J.FirstUpdated="firstUpdated",e.FeedSourceEnum=void 0,(W=e.FeedSourceEnum||(e.FeedSourceEnum={})).Community="community",W.User="user",e.FeedTypeEnum=void 0,(G=e.FeedTypeEnum||(e.FeedTypeEnum={})).Reviewing="reviewing",G.Published="published",G.Declined="declined",e.AmityEventType=void 0,(Y=e.AmityEventType||(e.AmityEventType={})).Virtual="virtual",Y.InPerson="in_person",e.AmityEventOriginType=void 0,(X=e.AmityEventOriginType||(e.AmityEventOriginType={})).Community="community",X.User="user",e.AmityEventStatus=void 0,(Z=e.AmityEventStatus||(e.AmityEventStatus={})).Scheduled="scheduled",Z.Live="live",Z.Ended="ended",Z.Cancelled="cancelled",e.AmityEventResponseStatus=void 0,(ee=e.AmityEventResponseStatus||(e.AmityEventResponseStatus={})).Going="going",ee.NotGoing="not_going",e.AmityEventSortOption=void 0,(te=e.AmityEventSortOption||(e.AmityEventSortOption={})).StartTime="startTime",te.CreatedAt="createdAt",e.AmityEventOrderOption=void 0,(ne=e.AmityEventOrderOption||(e.AmityEventOrderOption={})).Ascending="asc",ne.Descending="desc",e.AmitySharableContentType=void 0,(ae=e.AmitySharableContentType||(e.AmitySharableContentType={})).POST="post",ae.COMMUNITY="community",ae.USER="user",ae.LIVESTREAM="livestream",ae.EVENT="event",e.AnalyticsSourceTypeEnum=void 0,(re=e.AnalyticsSourceTypeEnum||(e.AnalyticsSourceTypeEnum={})).POST="post",re.ROOM="room",e.UserNotificationModuleNameEnum=void 0,(se=e.UserNotificationModuleNameEnum||(e.UserNotificationModuleNameEnum={})).CHAT="chat",se.SOCIAL="social",se.VIDEO_STREAMING="video-streaming",e.CommunityNotificationEventNameEnum=void 0,(oe=e.CommunityNotificationEventNameEnum||(e.CommunityNotificationEventNameEnum={})).POST_CREATED="post.created",oe.POST_REACTED="post.reacted",oe.COMMENT_CREATED="comment.created",oe.COMMENT_REPLIED="comment.replied",oe.COMMENT_REACTED="comment.reacted",oe.STORY_CREATED="story.created",oe.STORY_REACTED="story.reacted",oe.STORY_COMMENT_CREATED="story-comment.created",oe.LIVESTREAM_START="video-streaming.didStart",e.NotificationSettingsLevelEnum=void 0,(ie=e.NotificationSettingsLevelEnum||(e.NotificationSettingsLevelEnum={})).USER="user",ie.COMMUNITY="community",ie.CHANNEL="channel",e.NotificationRolesFilterTypeEnum=void 0,(ce=e.NotificationRolesFilterTypeEnum||(e.NotificationRolesFilterTypeEnum={})).ALL="all",ce.ONLY="only";const le=function(){try{return"v7.23.0-umd"}catch(e){return"__dev__"}}(),de=5,ue=20,he="cache_then_server",pe="For using Live Collection feature you need to enable Cache!",fe="Observing unsynced object is not supported by Live Object.",me=-5,ge=1e3,ye=6e5,ve="/api/v1/feeds/for-you",be="dead",we=6e4,Ie=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})),Ce=e=>JSON.parse(e),Se=(e,t)=>e===t||!(!e||!t)&&("object"==typeof e&&Object.keys(e).every((n=>Se(e[n],t[n])))),Oe=e=>[400400,400300].includes(e),Te=e=>["skip"].some((t=>t in e)),ke=e=>["after","before","first","last","limit"].some((t=>t in e)),Ae=e=>"limit"in e,_e=e=>(null==e?void 0:e.hasOwnProperty("data"))&&(null==e?void 0:e.hasOwnProperty("nextPage"))&&(null==e?void 0:e.hasOwnProperty("prevPage")),Ee=(e,n)=>{var a;if(!e||!Object.keys(e).length)return;let r={};return"skiplimit"===n?r={skip:null!==(a=e.after)&&void 0!==a?a:0,limit:e.limit}:"afterbefore"===n&&ke(e)?((null==e?void 0:e.before)&&(r=Object.assign(Object.assign({},r),{before:e.before})),(null==e?void 0:e.after)&&(r=Object.assign(Object.assign({},r),{after:e.after})),Number.isNaN(Number(null==e?void 0:e.limit))||(r=Object.assign(Object.assign({},r),{limit:e.limit}))):"afterbeforeraw"===n&&(r=e),Object.keys(r).length?t.encode(JSON.stringify(r)):void 0},Re=e=>{if(!e)return;const n=JSON.parse(t.decode(e));if(Te(n))return{after:n.skip,limit:n.limit};if(ke(n)){if("before"in n)return{before:n.before,limit:n.last};if("after"in n)return{after:n.after,limit:n.first}}},Pe=e=>"locally"in e,Me=e=>"optimistically"in e,je=e=>Pe(e)||Me(e),Ue=e=>null==e?void 0:e.hasOwnProperty("cachedAt"),De=(e,t=6e4)=>{var n;return Date.now()-(null!==(n=null==e?void 0:e.cachedAt)&&void 0!==n?n:0)<=t},xe=(e,...t)=>({func:e,args:t}),qe=(e,t=6e4)=>"cache_only"===e?{lifeSpan:1/0}:{lifeSpan:t<we?we:t},Ne=({func:e,args:t},n,a=qe("cache_then_server"))=>{let r;const{lifeSpan:s}=qe("cache_then_server",a.lifeSpan);if(je(e)){try{r=Me(e)?e.optimistically(...t):e.locally(...t)}catch(e){null==n||n(Be(void 0,{origin:"local",loading:!1,error:e}))}const a=Ue(r)&&De(r,s);if(null==n||n(Be(r,{origin:"local",loading:!(Pe(e)&&a)})),a)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 _e(e)||Ue(e)?Object.assign(Object.assign({},t),e):Object.assign(Object.assign({},t),{data:e})}class Le 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,Le)}}class Fe extends Le{constructor(e,t,n){super(e,t,n)}}class Ke extends Le{constructor(e=8e5,t="fatal"){super("Unexpected error",e,t)}}class $e extends Le{constructor(e,t="SDK client is having connection issues"){super(`${t} (${e})`,"disconnected"===e?800211:800210,"error"),this.event=e}}class Qe extends Le{constructor(e){super(e,800110,"error")}}let Ve=null;const ze=()=>{if(!Ve)throw new Le("There is no active client",8e5,"fatal");return Ve},He=e=>{Ve=e},Je={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}`,archivedChannel:({channelId:e})=>e,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,viewer:({userId:e})=>e,event:({eventId:e})=>e,eventResponse:({userId:e})=>e,product:({productId:e})=>e,feedMetadata:({postId:e})=>e},We=e=>Je[e],Ge={users:"user",files:"file",roles:"role",stories:"story",storyTargets:"storyTarget",channels:"channel",messageFeeds:"subChannel",channelUsers:"channelUsers",archives:"archivedChannel",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",events:"event",viewers:"viewer",eventResponses:"eventResponse",products:"product",feedMetadata:"feedMetadata"};function Ye(e=(new Date).toISOString()){return new Date(new Date(e).getTime()+1).toISOString()}const Xe=e=>{const{log:t,cache:n}=ze();if(n)return t("cache/api/queryCache",{key:e}),Object.keys(n.data).filter((t=>{const n=Ce(t);return Se(e,n)})).map((e=>n.data[e]))},Ze=e=>{const{log:t,cache:n}=ze();if(!n)return;t("cache/api/pullFromCache",e);const a=Ie(e);return n.data[a]?n.data[a]:void 0},et=(e,t,n={cachedAt:Date.now()})=>{const{log:a,cache:r}=ze();if(!r)return!1;a("cache/api/pushToCache",{key:e,data:t,options:n}),!(null==n?void 0:n.hasOwnProperty("offline"))&&r.persistIf&&(n.offline=r.persistIf(e,t));const s=Ie(e);return r.data[s]=Object.assign({key:e,data:t},n),!0},tt=(e,t,n)=>{const{log:a,cache:r}=ze();if(!r)return!1;a("cache/api/mergeInCache",{key:e,mutation:t});const s=Ze(e);if(!s)return!1;const o="function"==typeof t?t(s.data):Object.assign(Object.assign({},s.data),t);return i=s.data,!("updatedAt"in(c=o)&&"updatedAt"in i&&new Date(c.updatedAt)<new Date(i.updatedAt))&&(et(e,o,n),!0);var i,c},nt=(e,t,n={cachedAt:Date.now()})=>{const{log:a,cache:r}=ze();if(!r)return!1;a("cache/api/upsertInCache",{key:e,data:t,options:n});return Ze(e)?tt(e,t,n):et(e,t,n)},at=(e,t=!1)=>{const{log:n,cache:a}=ze();if(!a)return!1;if(n("cache/api/dropFromCache",{key:e,exact:t}),!t)return Object.keys(a.data).map((e=>Ce(e))).filter((t=>Se(e,t))).map((e=>at(e,!0))).every((e=>e));const r=Ie(e);return r in a.data&&(delete a.data[r],!0)},rt=(e,t,n)=>void 0!==n?e.filter((e=>JSON.stringify(e[t])===JSON.stringify(n))):e,st=(e,t,n)=>void 0!==n?e.filter((e=>"string"==typeof e[t]&&"string"==typeof n&&String(e[t]).toLowerCase().match(n.toLowerCase()))):e,ot=(e,t,n)=>(null==n?void 0:n.length)?e.filter((e=>Array.isArray(e[t])&&n.some((n=>e[t].includes(n))))):e,it=(e,t,n)=>"all"===t?e:e.filter((e=>{var a;if("community"===e.type)return!0;const r=We("channelUsers")({channelId:e.channelPublicId,userId:n}),s=null===(a=Ze(["channelUsers","get",r]))||void 0===a?void 0:a.data;return"member"===t?s&&"none"!==s.membership:!s||"none"===s.membership})),ct=(e,t)=>e.filter((({targetId:e,feedId:n})=>{var a;const r=null===(a=Ze(["feed","get",We("feed")({targetId:e,feedId:n})]))||void 0===a?void 0:a.data;return r&&r.feedType===t})),lt=(e,t,n)=>"all"===t?e:e.filter((e=>{var a;const r=We("communityUsers")({communityId:e.communityId,userId:n}),s=null===(a=Ze(["communityUsers","get",r]))||void 0===a?void 0:a.data;return"member"===t?s&&"member"===s.communityMembership:!s||"none"!==s.communityMembership})),dt=(e,t)=>e.reduce(((e,n)=>{var a;if(null==t?void 0:t.includes(n.dataType))return[...e,n];if(((null==n?void 0:n.children)||[]).length>0){const r=null===(a=Ze(["post","get",n.children[0]]))||void 0===a?void 0:a.data;return(null==t?void 0:t.includes(null==r?void 0:r.dataType))?e:[...e,n]}return e}),[]),ut=(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))}))},ht=()=>{var e;const{userId:t}=ze(),n=new Set;return(null!==(e=Xe(["follow","get"]))&&void 0!==e?e:[]).map((e=>e.data)).filter((e=>"blocked"===(null==e?void 0:e.status)&&(e.from===t||e.to===t))).forEach((e=>{n.add(e.from===t?e.to:e.from)})),n},pt=e=>{const t=ht();return 0===t.size?e:e.filter((e=>{var n,a;if(t.has(e.postedUserId))return!1;return!(null!==(a=null===(n=e.mentionees)||void 0===n?void 0:n.flatMap((e=>"user"===e.type?e.userIds:[])))&&void 0!==a?a:[]).some((e=>t.has(e)))}))},ft=e=>{const t=ht();return 0===t.size?e:e.filter((e=>!t.has(e.userId)))},mt=({displayName:e},{displayName:t})=>e&&t?e.localeCompare(t):e?-1:1,gt=({name:e},{name:t})=>e&&t?e.localeCompare(t):e?-1:1,yt=({createdAt:e},{createdAt:t})=>new Date(e).valueOf()-new Date(t).valueOf(),vt=({localSortingDate:e},{localSortingDate:t})=>new Date(t).getTime()-new Date(e).getTime(),bt=({createdAt:e},{createdAt:t})=>new Date(t).valueOf()-new Date(e).valueOf(),wt=({updatedAt:e=0},{updatedAt:t=0})=>new Date(e).valueOf()-new Date(t).valueOf(),It=({updatedAt:e=0},{updatedAt:t=0})=>new Date(t).valueOf()-new Date(e).valueOf(),Ct=({lastActivity:e},{lastActivity:t})=>new Date(t).valueOf()-new Date(e).valueOf(),St=e=>{if(void 0===e)return;const t=new Date(e).valueOf();if(!Number.isNaN(t))return e;console.warn("untilAt is an invalid Date — ignoring, pagination will not be bounded")},Ot=(e,t,n)=>{const a=new Date(e).valueOf(),r=new Date(t).valueOf();return"firstCreated"===n?a>=r:a<=r};let Tt=null;const kt=()=>{if(!Tt)throw new Le("Connect client first",8e5,"fatal");return Tt},At=e=>{Tt={_id:e._id,userId:e.userId,path:e.path}};let _t,Et=[];const Rt=e=>{clearTimeout(_t),Et.push(e),_t=setTimeout((()=>{Et.forEach((e=>e())),Et=[]}),0)},Pt=["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"],Mt=(e,t,n,a)=>{const{log:r,emitter:s}=e,o=Date.now();r(`${t}(tmpid: ${o}) > listen`);const i=(...e)=>{r(`${t}(tmpid: ${o}) > trigger`,e);try{a(...e)}catch(e){r(`${t}(tmpid: ${o}) > error`,e)}};return s.on(n,i),()=>{r(`${t}(tmpid: ${o}) > dispose`),s.off(n,i)}},jt=(e,t)=>{const{emitter:n}=ze();Rt((()=>{n.emit(e,t)}))};let Ut,Dt;async function xt(){var e;const{mqtt:t,emitter:n,token:a}=ze();if(!t)return;const r=null!==(e=null==a?void 0:a.accessToken)&&void 0!==e?e:"",s=kt();Ut===r&&Dt===s._id||(Ut=r,Dt=s._id,await t.connect({accessToken:Ut,userId:Dt}),((e,t)=>{Pt.forEach((n=>{null==e||e.on(n,((...e)=>{t.emit(n,1===e.length?e[0]:e)}))})),e.on("message",((e,n)=>{const a=JSON.parse(n.toString());t.emit(a.eventType,a.data)}))})(t,n))}const qt=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=Ze(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),Nt=()=>{var e;const t=ze();if(!t)throw new Le("Connect client first",8e5,"fatal");const n=null===(e=Ze(["user","get",t.userId]))||void 0===e?void 0:e.data;return n?qt(n):null};var Bt;e.SubscriptionLevels=void 0,(Bt=e.SubscriptionLevels||(e.SubscriptionLevels={})).COMMUNITY="community",Bt.POST="post",Bt.COMMENT="comment",Bt.POST_AND_COMMENT="post_and_comment",Bt.USER="user";const Lt=(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],Kt=()=>{const e=kt();return`${Ft(e)}/membership/${e._id}/+/+`},$t=()=>{const e=kt();return`${Ft(e)}/membership/+/${e._id}/+`},Qt=({channelId:e,subChannelId:t})=>{const n=kt();return`${Ft(n)}/marker/channel/${e}/message/${t}`},Vt=()=>Ft(kt()),zt=()=>{const e=kt();return`${Ft(e)}/smartfeed/${e._id}/channels`},Ht=()=>{const e=kt();return`${Ft(e)}/smartfeed/${e._id}/messagefeeds`},Jt=()=>{const e=kt();return`${Ft(e)}/smartfeed/${e._id}/messages`},Wt=()=>{const e=kt();return`${Ft(e)}/videostreaming`};function Gt(e,t){const{mqtt:n}=ze();return n?(xt(),n.subscribe(e,t)):()=>null}var Yt;const Xt="object"==typeof globalThis?globalThis:"object"==typeof global?global:window,{process:Zt={}}=Xt,en="production"===(null===(Yt=Zt.env)||void 0===Yt?void 0:Yt.NODE_ENV),tn={EU:"eu",SG:"sg",US:"us"},nn={http:"https://apix.{region}.amity.co",upload:"https://upload.{region}.amity.co",mqtt:"wss://sse.{region}.amity.co:443/mqtt"};function an(e,t){return nn[e].replace("{region}",t)}class rn{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 sn;var on,cn=()=>(sn||(sn=new rn),sn);!function(e){e.UserDeleted="User Deleted",e.UserGlobalBanned="User Global Banned",e.TokenExpired="Token Expired"}(on||(on={}));let ln=new AbortController;const dn=e=>{switch(e){case on.UserGlobalBanned:throw new Le(e,400312,"fatal");case on.UserDeleted:throw new Le(e,400100,"fatal");case on.TokenExpired:throw jt("tokenExpired","tokenExpired"),new Le(e,800403,"fatal");default:throw new Le("Request Aborted",8e5,"error")}};let un=0;const hn=e=>{const t={maxSockets:100,maxFreeSockets:10,timeout:6e4,freeSocketTimeout:3e4},n=b.default.create({baseURL:e,httpAgent:new w.default(t),httpsAgent:new s.HttpsAgent(t),signal:ln.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:a}=e.metadata;n&&(ln.abort(),dn(on.UserGlobalBanned)),a&&(ln.abort(),dn(on.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 a=(e.config.baseURL||"")+(e.config.url||""),r=null===(t=e.config.method)||void 0===t?void 0:t.toUpperCase(),s={method:r,headers:e.config.headers};return"GET"!==r&&"HEAD"!==r&&(s.body=e.config.data),cn().setNetworkActivities(new Request(a,s),{data:e.data,status:e.status,statusText:e.statusText,headers:n}),e}),(e=>{var t,n,a;const{response:r}=e;if(400100===(null==r?void 0:r.data.code)&&jt("tokenTerminated","terminated"),400323===(null===(t=null==r?void 0:r.data)||void 0===t?void 0:t.code))throw function(){const e=Date.now();e-un<2e3||(un=e,jt("visitorUsageLimitReached",void 0))}(),new Le("Visitor usage limit exceeded",400323,"error");if((null===(n=null==r?void 0:r.data)||void 0===n?void 0:n.status)&&(e=>{if("success"===e.status)return e.data;if("fail"===e.status)throw new Ke(e.code);if("error"===e.status)throw new Fe(e.message,e.code,"error")})(null==r?void 0:r.data),ln.signal.aborted)throw e;throw new Error(null!==(a=null==r?void 0:r.data)&&void 0!==a?a:e)})),n.defaults.paramsSerializer={encode:e=>encodeURIComponent(e)},n};var pn="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function fn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function mn(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 gn={exports:{}};gn.exports=function(){function e(t,n,a){function r(o,i){if(!n[o]){if(!t[o]){if(!i&&mn)return mn(o);if(s)return s(o,!0);var c=new Error("Cannot find module '"+o+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[o]={exports:{}};t[o][0].call(l.exports,(function(e){return r(t[o][1][e]||e)}),l,l.exports,e,t,n,a)}return n[o].exports}for(var s=mn,o=0;o<a.length;o++)r(a[o]);return r}return e}()({1:[function(e,t,n){(function(n,a){(function(){const r=e("events").EventEmitter,s=e("./store"),o=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=a.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"],I={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 C(){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 a=t.topic.toString();if(e.topicAliasSend)if(n){if(0!==a.length&&(g("applyTopicAlias :: register topic: %s - alias: %d",a,n),!e.topicAliasSend.put(a,n)))return g("applyTopicAlias :: error out of range. topic: %s - alias: %d",a,n),new Error("Sending Topic Alias out of range")}else 0!==a.length&&(e.options.autoAssignTopicAlias?(n=e.topicAliasSend.getAliasByTopic(a),n?(t.topic="",t.properties={...t.properties,topicAlias:n},g("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",a,n)):(n=e.topicAliasSend.getLruAlias(),e.topicAliasSend.put(a,n),t.properties={...t.properties,topicAlias:n},g("applyTopicAlias :: auto assign topic: %s - alias: %d",a,n))):e.options.autoUseTopicAlias&&(n=e.topicAliasSend.getAliasByTopic(a),n&&(t.topic="",t.properties={...t.properties,topicAlias:n},g("applyTopicAlias :: auto use topic: %s - alias: %d",a,n))));else if(n)return g("applyTopicAlias :: error out of range. topic: %s - alias: %d",a,n),new Error("Sending Topic Alias out of range")}}function O(e,t){let n;t.properties&&(n=t.properties.topicAlias);let a=t.topic.toString();if(0===a.length){if(void 0===n)return new Error("Unregistered Topic Alias");if(a=e.topicAliasSend.getTopicByAlias(n),void 0===a)return new Error("Unregistered Topic Alias");t.topic=a}n&&delete t.properties.topicAlias}function T(e,t,n){g("sendPacket :: packet: %O",t),g("sendPacket :: emitting `packetsend`"),e.emit("packetsend",t),g("sendPacket :: writing to stream");const a=c.writeToStream(t,e.stream,e.options);g("sendPacket :: writeToStream result %s",a),!a&&n&&n!==E?(g("sendPacket :: handle events on `drain` once through callback."),e.stream.once("drain",n)):n&&(g("sendPacket :: invoking cb"),n())}function k(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 A(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,t,n,a){g("storeAndSend :: store packet with cmd %s to outgoingStore",t.cmd);let r,s=t;if("publish"===s.cmd&&(s=p(t),r=O(e,s),r))return n&&n(r);e.outgoingStore.put(s,(function(r){if(r)return n&&n(r);a(),T(e,t,n)}))}function E(e){g("nop ::",e)}function R(e,t){let n;const a=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:C(),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 s,this.incomingStore=t.incomingStore||new s,this.queueQoSZero=void 0===t.queueQoSZero||t.queueQoSZero,this._resubscribeTopics={},this.messageIdToTopic={},this.pingTimer=null,this.connected=!1,this.disconnecting=!1,this.queue=[],this.connackTimer=null,this.reconnectTimer=null,this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={},this._storeProcessingQueue=[],this.outgoing={},this._firstConnection=!0,t.topicAliasMaximum>0&&(t.topicAliasMaximum>65535?g("MqttClient :: options.topicAliasMaximum is out of range"):this.topicAliasRecv=new o(t.topicAliasMaximum)),this.on("connect",(function(){const e=this.queue;function t(){const n=e.shift();g("deliver :: entry %o",n);let r=null;if(!n)return void a._resubscribe();r=n.packet,g("deliver :: call _sendPacket for %o",r);let s=!0;r.messageId&&0!==r.messageId&&(a.messageIdProvider.register(r.messageId)||(s=!1)),s?a._sendPacket(r,(function(e){n.cb&&n.cb(e),t()})):(g("messageId: %d has already used. The message is skipped and removed.",r.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!==a.pingTimer&&(a.pingTimer.clear(),a.pingTimer=null),this.topicAliasRecv&&this.topicAliasRecv.clear(),g("close :: calling _setupReconnect"),this._setupReconnect()})),r.call(this),g("MqttClient :: setting up stream"),this._setupStream()}u(R,r),R.prototype._setupStream=function(){const e=this,t=new d,n=c.parser(this.options);let a=null;const r=[];function s(){if(r.length)y(o);else{const e=a;a=null,e()}}function o(){g("work :: getting next packet in queue");const t=r.shift();if(t)g("work :: packet pulled from queue"),e._handlePacket(t,s);else{g("work :: no packets in queue");const e=a;a=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)):E(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."),r.push(e)})),t._write=function(e,t,r){a=r,g("writable stream :: parsing buffer"),n.parse(e),o()},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),A(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)),T(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&&T(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!==E?e(new Error("client disconnecting")):this.emit("error",new Error("client disconnecting"))),this.disconnecting},R.prototype.publish=function(e,t,n,a){g("publish :: message `%s` to topic `%s`",t,e);const r=this.options;if("function"==typeof n&&(a=n,n=null),n=m({qos:0,retain:!1,dup:!1},n),this._checkDisconnecting(a))return this;const s=this,o=function(){let o=0;if((1===n.qos||2===n.qos)&&(o=s._nextId(),null===o))return g("No messageId left"),!1;const i={cmd:"publish",topic:e,payload:t,qos:n.qos,retain:n.retain,messageId:o,dup:n.dup};switch(5===r.protocolVersion&&(i.properties=n.properties),g("publish :: qos",n.qos),n.qos){case 1:case 2:s.outgoing[i.messageId]={volatile:!1,cb:a||E},g("MqttClient:publish: packet cmd: %s",i.cmd),s._sendPacket(i,void 0,n.cbStorePut);break;default:g("MqttClient:publish: packet cmd: %s",i.cmd),s._sendPacket(i,a,n.cbStorePut)}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!o())&&this._storeProcessingQueue.push({invoke:o,cbStorePut:n.cbStorePut,callback:a}),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 a=t.shift();const r=a.resubscribe;let s=t.pop()||E,o=t.pop();const i=this.options.protocolVersion;delete a.resubscribe,"string"==typeof a&&(a=[a]),"function"!=typeof s&&(o=s,s=E);const c=f.validateTopics(a);if(null!==c)return v(s,new Error("Invalid topic "+c)),this;if(this._checkDisconnecting(s))return g("subscribe: discconecting true"),this;const l={qos:0};if(5===i&&(l.nl=!1,l.rap=!1,l.rh=0),o=m(l,o),Array.isArray(a)?a.forEach((function(t){if(g("subscribe: array topic %s",t),!Object.prototype.hasOwnProperty.call(e._resubscribeTopics,t)||e._resubscribeTopics[t].qos<o.qos||r){const e={topic:t,qos:o.qos};5===i&&(e.nl=o.nl,e.rap=o.rap,e.rh=o.rh,e.properties=o.properties),g("subscribe: pushing topic `%s` and qos `%s` to subs list",e.topic,e.qos),n.push(e)}})):Object.keys(a).forEach((function(t){if(g("subscribe: object topic %s",t),!Object.prototype.hasOwnProperty.call(e._resubscribeTopics,t)||e._resubscribeTopics[t].qos<a[t].qos||r){const e={topic:t,qos:a[t].qos};5===i&&(e.nl=a[t].nl,e.rap=a[t].rap,e.rh=a[t].rh,e.properties=o.properties),g("subscribe: pushing `%s` to subs list",e),n.push(e)}})),!n.length)return s(null,[]),this;const d=function(){const t=e._nextId();if(null===t)return g("No messageId left"),!1;const a={cmd:"subscribe",subscriptions:n,qos:1,retain:!1,dup:!1,messageId:t};if(o.properties&&(a.properties=o.properties),e.options.resubscribe){g("subscribe :: resubscribe true");const t=[];n.forEach((function(n){if(e.options.reconnectPeriod>0){const a={qos:n.qos};5===i&&(a.nl=n.nl||!1,a.rap=n.rap||!1,a.rh=n.rh||0,a.properties=n.properties),e._resubscribeTopics[n.topic]=a,t.push(n.topic)}})),e.messageIdToTopic[a.messageId]=t}return e.outgoing[a.messageId]={volatile:!0,cb:function(e,t){if(!e){const e=t.granted;for(let t=0;t<e.length;t+=1)n[t].qos=e[t]}s(e,n)}},g("subscribe :: call _sendPacket"),e._sendPacket(a),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!d())&&this._storeProcessingQueue.push({invoke:d,callback:s}),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(),a=t.pop()||E,r=t.pop();"string"==typeof n&&(n=[n]),"function"!=typeof a&&(r=a,a=E);const s=f.validateTopics(n);if(null!==s)return v(a,new Error("Invalid topic "+s)),this;if(e._checkDisconnecting(a))return this;const o=function(){const t=e._nextId();if(null===t)return g("No messageId left"),!1;const s={cmd:"unsubscribe",qos:1,messageId:t};return"string"==typeof n?s.unsubscriptions=[n]:Array.isArray(n)&&(s.unsubscriptions=n),e.options.resubscribe&&s.unsubscriptions.forEach((function(t){delete e._resubscribeTopics[t]})),"object"==typeof r&&r.properties&&(s.properties=r.properties),e.outgoing[s.messageId]={volatile:!0,cb:a},g("unsubscribe: call _sendPacket"),e._sendPacket(s),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!o())&&this._storeProcessingQueue.push({invoke:o,callback:a}),this},R.prototype.end=function(e,t,n){const a=this;function r(){g("end :: closeStores: closing incoming and outgoing stores"),a.disconnected=!0,a.incomingStore.close((function(e){a.outgoingStore.close((function(t){if(g("end :: closeStores: emitting end"),a.emit("end"),n){const a=e||t;g("end :: closeStores: invoking callback with args"),n(a)}}))})),a._deferredReconnect&&a._deferredReconnect()}function s(){g("end :: (%s) :: finish :: calling _cleanUp with force %s",a.options.clientId,e),a._cleanUp(e,(()=>{g("end :: finish :: calling process.nextTick on closeStores"),y(r.bind(a))}),t)}return g("end :: (%s)",this.options.clientId),null!=e&&"boolean"==typeof e||(n=t||E,t=e,e=!1,"object"!=typeof t&&(n=t,t=null,"function"!=typeof n&&(n=E))),"object"!=typeof t&&(n=t,t=null),g("end :: cb? %s",!!n),n=n||E,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",a.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,s,10))):(g("end :: (%s) :: immediately calling finish",a.options.clientId),s()),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 s,t.outgoingStore=t.options.outgoingStore||new s,t.disconnecting=!1,t.disconnected=!1,t._deferredReconnect=null,t._reconnect()};return this.disconnecting&&!this.disconnected?this._deferredReconnect=n:n(),this},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&&k(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||E,t=t||E;const a=S(this,e);if(a)t(a);else{if(!this.connected)return"auth"===e.cmd?(this._shiftPingInterval(),void T(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 _(this,e,t,n);default:return void T(this,e,t)}switch(e.qos){case 2:case 1:_(this,e,t,n);break;default:T(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||E;let a=e;if("publish"===a.cmd){a=p(e);const n=O(this,a);if(n)return t&&t(n)}0===(a.qos||0)&&this.queueQoSZero||"publish"!==a.cmd?this.queue.push({packet:a,cb:t}):a.qos>0?(t=this.outgoing[a.messageId]?this.outgoing[a.messageId].cb:null,this.outgoingStore.put(a,(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: "+I[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 a=this;this.handleAuth(e,(function(e,t){if(e)a.emit("error",e);else if(24===n)a.reconnecting=!1,a._sendPacket(t);else{const t=new Error("Connection refused: "+I[n]);e.code=n,a.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:E;let n=e.topic.toString();const a=e.payload,r=e.qos,s=e.messageId,o=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",r),r){case 2:i.customHandleAcks(n,a,e,(function(n,a){return n instanceof Error||(a=n,n=null),n?o.emit("error",n):-1===c.indexOf(a)?o.emit("error",new Error("Wrong reason code for pubrec")):void(a?o._sendPacket({cmd:"pubrec",messageId:s,reasonCode:a},t):o.incomingStore.put(e,(function(){o._sendPacket({cmd:"pubrec",messageId:s},t)})))}));break;case 1:i.customHandleAcks(n,a,e,(function(r,i){return r instanceof Error||(i=r,r=null),r?o.emit("error",r):-1===c.indexOf(i)?o.emit("error",new Error("Wrong reason code for puback")):(i||o.emit("message",n,a,e),void o.handleMessage(e,(function(e){if(e)return t&&t(e);o._sendPacket({cmd:"puback",messageId:s,reasonCode:i},t)})))}));break;case 0:this.emit("message",n,a,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 a=null;const r=this.outgoing[t]?this.outgoing[t].cb:null,s=this;let o;if(r){switch(g("_handleAck :: packet type",n),n){case"pubcomp":case"puback":{const n=e.reasonCode;n&&n>0&&16!==n&&(o=new Error("Publish error: "+I[n]),o.code=n,r(o,e)),delete this.outgoing[t],this.outgoingStore.del(e,r),this.messageIdProvider.deallocate(t),this._invokeStoreProcessingQueue();break}case"pubrec":{a={cmd:"pubrel",qos:2,messageId:t};const n=e.reasonCode;n&&n>0&&16!==n?(o=new Error("Publish error: "+I[n]),o.code=n,r(o,e)):this._sendPacket(a);break}case"suback":delete this.outgoing[t],this.messageIdProvider.deallocate(t);for(let n=0;n<e.granted.length;n++)if(0!=(128&e.granted[n])){const e=this.messageIdToTopic[t];e&&e.forEach((function(e){delete s._resubscribeTopics[e]}))}this._invokeStoreProcessingQueue(),r(null,e);break;case"unsuback":delete this.outgoing[t],this.messageIdProvider.deallocate(t),this._invokeStoreProcessingQueue(),r(null);break;default:s.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:E;const n=e.messageId,a=this,r={cmd:"pubcomp",messageId:n};a.incomingStore.get(e,(function(e,n){e?a._sendPacket(r,t):(a.emit("message",n.topic,n.payload,n),a.handleMessage(n,(function(e){if(e)return t(e);a.incomingStore.del(n,E),a._sendPacket(r,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 a=t.outgoingStore.createStream();function r(){t._storeProcessing=!1,t._packetIdsDuringStoreProcessing={}}function s(){a.destroy(),a=null,t._flushStoreProcessingQueue(),r()}function o(){if(!a)return;t._storeProcessing=!0;const e=a.read(1);let n;e?t._packetIdsDuringStoreProcessing[e.messageId]?o():t.disconnecting||t.reconnectTimer?a.destroy&&a.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),o()}},t._packetIdsDuringStoreProcessing[e.messageId]=!0,t.messageIdProvider.register(e.messageId)?t._sendPacket(e):g("messageId: %d has already used.",e.messageId)):a.once("readable",o)}t.once("close",s),a.on("error",(function(e){r(),t._flushStoreProcessingQueue(),t.removeListener("close",s),t.emit("error",e)})),a.on("end",(function(){let a=!0;for(const e in t._packetIdsDuringStoreProcessing)if(!t._packetIdsDuringStoreProcessing[e]){a=!1;break}a?(r(),t.removeListener("close",s),t._invokeAllStoreProcessingQueue(),t.emit("connect",e)):n()})),o()}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!==pn?pn:"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:a}=e("buffer"),r=e("readable-stream").Transform,s=e("duplexify");let o,i,c,l=!1;function d(){const e=new r;return e._write=function(e,t,n){o.sendSocketMessage({data:e.buffer,success:function(){n()},fail:function(){n(new Error)}})},e._flush=function(e){o.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 a=n+"://"+e.hostname+e.path;return e.port&&80!==e.port&&443!==e.port&&(a=n+"://"+e.hostname+":"+e.port+e.path),"function"==typeof e.transformWsUrl&&(a=e.transformWsUrl(a,e,t)),a}function p(){l||(l=!0,o.onSocketOpen((function(){c.setReadable(i),c.setWritable(i),c.emit("connect")})),o.onSocketMessage((function(e){if("string"==typeof e.data){const t=a.from(e.data,"base64");i.push(t)}else{const t=new FileReader;t.addEventListener("load",(function(){let e=t.result;e=e instanceof ArrayBuffer?a.from(e):a.from(e,"utf8"),i.push(e)})),t.readAsArrayBuffer(e.data)}})),o.onSocketClose((function(){c.end(),c.destroy()})),o.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 a=h(t,e);return o=t.my,o.connectSocket({url:a,protocols:n}),i=d(),c=s.obj(),p(),c}t.exports=f},{buffer:17,duplexify:20,"readable-stream":69}],3:[function(e,t,n){const a=e("net"),r=e("debug")("mqttjs:tcp");function s(e,t){t.port=t.port||1883,t.hostname=t.hostname||t.host||"localhost";const n=t.port,s=t.hostname;return r("port %d and host %s",n,s),a.createConnection(n,s)}t.exports=s},{debug:18,net:16}],4:[function(e,t,n){const a=e("tls"),r=e("net"),s=e("debug")("mqttjs:tls");function o(e,t){t.port=t.port||8883,t.host=t.hostname||t.host||"localhost",0===r.isIP(t.host)&&(t.servername=t.host),t.rejectUnauthorized=!1!==t.rejectUnauthorized,delete t.path,s("port %d host %s rejectUnauthorized %b",t.port,t.host,t.rejectUnauthorized);const n=a.connect(t);function o(a){t.rejectUnauthorized&&e.emit("error",a),n.end()}return n.on("secureConnect",(function(){t.rejectUnauthorized&&!n.authorized?n.emit("error",new Error("TLS not authorized")):n.removeListener("error",o)})),n.on("error",o),n}t.exports=o},{debug:18,net:16,tls:16}],5:[function(e,t,n){(function(n){(function(){const{Buffer:a}=e("buffer"),r=e("ws"),s=e("debug")("mqttjs:ws"),o=e("duplexify"),i=e("readable-stream").Transform,c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"],l=void 0!==n&&"browser"===n.title||"function"==typeof __webpack_require__;function d(e,t){let n=e.protocol+"://"+e.hostname+":"+e.port+e.path;return"function"==typeof e.transformWsUrl&&(n=e.transformWsUrl(n,e,t)),n}function u(e){const t=e;return e.hostname||(t.hostname="localhost"),e.port||("wss"===e.protocol?t.port=443:t.port=80),e.path||(t.path="/"),e.wsOptions||(t.wsOptions={}),l||"wss"!==e.protocol||c.forEach((function(n){Object.prototype.hasOwnProperty.call(e,n)&&!Object.prototype.hasOwnProperty.call(e.wsOptions,n)&&(t.wsOptions[n]=e[n])})),t}function h(e){const t=u(e);if(t.hostname||(t.hostname=t.host),!t.hostname){if("undefined"==typeof document)throw new Error("Could not determine host. Specify host manually.");const e=new URL(document.URL);t.hostname=e.hostname,t.port||(t.port=e.port)}return void 0===t.objectMode&&(t.objectMode=!(!0===t.binary||void 0===t.binary)),t}function p(e,t,n){s("createWebSocket"),s("protocol: "+n.protocolId+" "+n.protocolVersion);const a="MQIsdp"===n.protocolId&&3===n.protocolVersion?"mqttv3.1":"mqtt";return s("creating new Websocket for url: "+t+" and protocol: "+a),new r(t,[a],n.wsOptions)}function f(e,t){const n="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt",a=d(t,e),r=new WebSocket(a,[n]);return r.binaryType="arraybuffer",r}function m(e,t){s("streamBuilder");const n=u(t),a=d(n,e),o=p(e,a,n),i=r.createWebSocketStream(o,n.wsOptions);return i.url=a,o.on("close",(()=>{i.destroy()})),i}function g(e,t){let n;s("browserStreamBuilder");const r=h(t).browserBufferSize||524288,c=t.browserBufferTimeout||1e3,l=!t.objectMode,d=f(e,t),u=m(t,I,C);t.objectMode||(u._writev=w),u.on("close",(()=>{d.close()}));const p=void 0!==d.addEventListener;function m(e,t,n){const a=new i({objectModeMode:e.objectMode});return a._write=t,a._flush=n,a}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?a.from(t):a.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]=a.from(e[t],"utf8"):n[t]=e[t].chunk;this._write(a.concat(n),"binary",t)}function I(e,t,n){d.bufferedAmount>r&&setTimeout(I,c,e,t,n),l&&"string"==typeof e&&(e=a.from(e,"utf8"));try{d.send(e)}catch(e){return n(e)}n()}function C(e){d.close(),e()}return d.readyState===d.OPEN?n=u:(n=n=o(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:a}=e("buffer"),r=e("readable-stream").Transform,s=e("duplexify");let o,i,c;function l(){const e=new r;return e._write=function(e,t,n){o.send({data:e.buffer,success:function(){n()},fail:function(e){n(new Error(e))}})},e._flush=function(e){o.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 a=n+"://"+e.hostname+e.path;return e.port&&80!==e.port&&443!==e.port&&(a=n+"://"+e.hostname+":"+e.port+e.path),"function"==typeof e.transformWsUrl&&(a=e.transformWsUrl(a,e,t)),a}function h(){o.onOpen((function(){c.setReadable(i),c.setWritable(i),c.emit("connect")})),o.onMessage((function(e){let t=e.data;t=t instanceof ArrayBuffer?a.from(t):a.from(t,"utf8"),i.push(t)})),o.onClose((function(){c.end(),c.destroy()})),o.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 a=u(t,e);o=wx.connectSocket({url:a,protocols:[n]}),i=l(),c=s.obj(),c._destroy=function(e,t){o.close({success:function(){t&&t(e)}})};const r=c.destroy;return c.destroy=function(){c.destroy=r;const e=this;setTimeout((function(){o.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 a(){if(!(this instanceof a))return new a;this.nextId=Math.max(1,Math.floor(65535*Math.random()))}a.prototype.allocate=function(){const e=this.nextId++;return 65536===this.nextId&&(this.nextId=1),e},a.prototype.getLastAllocated=function(){return 1===this.nextId?65535:this.nextId-1},a.prototype.register=function(e){return!0},a.prototype.deallocate=function(e){},a.prototype.clear=function(){},t.exports=a},{}],8:[function(e,t,n){const a=e("xtend"),r=e("readable-stream").Readable,s={objectMode:!0},o={clean:!0};function i(e){if(!(this instanceof i))return new i(e);this.options=e||{},this.options=a(o,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 r(s),t=[];let n=!1,a=0;return this._inflights.forEach((function(e,n){t.push(e)})),e._read=function(){!n&&a<t.length?this.push(t[a++]):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 a(e){if(!(this instanceof a))return new a(e);this.aliasToTopic={},this.max=e}a.prototype.put=function(e,t){return!(0===t||t>this.max||(this.aliasToTopic[t]=e,this.length=Object.keys(this.aliasToTopic).length,0))},a.prototype.getTopicByAlias=function(e){return this.aliasToTopic[e]},a.prototype.clear=function(){this.aliasToTopic={}},t.exports=a},{}],10:[function(e,t,n){const a=e("lru-cache"),r=e("number-allocator").NumberAllocator;function s(e){if(!(this instanceof s))return new s(e);e>0&&(this.aliasToTopic=new a({max:e}),this.topicToAlias={},this.numberAllocator=new r(1,e),this.max=e,this.length=0)}s.prototype.put=function(e,t){if(0===t||t>this.max)return!1;const n=this.aliasToTopic.get(t);return n&&delete this.topicToAlias[n],this.aliasToTopic.set(t,e),this.topicToAlias[e]=t,this.numberAllocator.use(t),this.length=this.aliasToTopic.length,!0},s.prototype.getTopicByAlias=function(e){return this.aliasToTopic.get(e)},s.prototype.getAliasByTopic=function(e){const t=this.topicToAlias[e];return void 0!==t&&this.aliasToTopic.get(t),t},s.prototype.clear=function(){this.aliasToTopic.reset(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0},s.prototype.getLruAlias=function(){const e=this.numberAllocator.firstVacant();return e||this.aliasToTopic.keys()[this.aliasToTopic.length-1]},t.exports=s},{"lru-cache":37,"number-allocator":46}],11:[function(e,t,n){function a(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 r(e){if(0===e.length)return"empty_topic_list";for(let t=0;t<e.length;t++)if(!a(e[t]))return e[t];return null}t.exports={validateTopics:r}},{}],12:[function(e,t,n){(function(n){(function(){const a=e("../client"),r=e("../store"),s=e("url"),o=e("xtend"),i=e("debug")("mqttjs"),c={};function l(e){let t;e.auth&&(t=e.auth.match(/^(.+):(.+)$/),t?(e.username=t[1],e.password=t[2]):e.username=e.auth)}function d(e,t){if(i("connecting to an MQTT broker..."),"object"!=typeof e||t||(t=e,e=null),t=t||{},e){const n=s.parse(e,!0);if(null!=n.port&&(n.port=Number(n.port)),null===(t=o(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 r=new a(n,t);return r.on("error",(function(){})),r}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=a,t.exports.Store=r}).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 a=[],r=[],s="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,c=o.length;i<c;++i)a[i]=o[i],r[o.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],a=t[1];return 3*(n+a)/4-a}function u(e,t,n){return 3*(t+n)/4-n}function h(e){var t,n,a=l(e),o=a[0],i=a[1],c=new s(u(e,o,i)),d=0,h=i>0?o-4:o;for(n=0;n<h;n+=4)t=r[e.charCodeAt(n)]<<18|r[e.charCodeAt(n+1)]<<12|r[e.charCodeAt(n+2)]<<6|r[e.charCodeAt(n+3)],c[d++]=t>>16&255,c[d++]=t>>8&255,c[d++]=255&t;return 2===i&&(t=r[e.charCodeAt(n)]<<2|r[e.charCodeAt(n+1)]>>4,c[d++]=255&t),1===i&&(t=r[e.charCodeAt(n)]<<10|r[e.charCodeAt(n+1)]<<4|r[e.charCodeAt(n+2)]>>2,c[d++]=t>>8&255,c[d++]=255&t),c}function p(e){return a[e>>18&63]+a[e>>12&63]+a[e>>6&63]+a[63&e]}function f(e,t,n){for(var a,r=[],s=t;s<n;s+=3)a=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(255&e[s+2]),r.push(p(a));return r.join("")}function m(e){for(var t,n=e.length,r=n%3,s=[],o=16383,i=0,c=n-r;i<c;i+=o)s.push(f(e,i,i+o>c?c:i+o));return 1===r?(t=e[n-1],s.push(a[t>>2]+a[t<<4&63]+"==")):2===r&&(t=(e[n-2]<<8)+e[n-1],s.push(a[t>>10]+a[t>>4&63]+a[t<<2&63]+"=")),s.join("")}r["-".charCodeAt(0)]=62,r["_".charCodeAt(0)]=63},{}],14:[function(e,t,n){const{Buffer:a}=e("buffer"),r=Symbol.for("BufferList");function s(e){if(!(this instanceof s))return new s(e);s._init.call(this,e)}s._init=function(e){Object.defineProperty(this,r,{value:!0}),this._bufs=[],this.length=0,e&&this.append(e)},s.prototype._new=function(e){return new s(e)},s.prototype._offset=function(e){if(0===e)return[0,0];let t=0;for(let n=0;n<this._bufs.length;n++){const a=t+this._bufs[n].length;if(e<a||n===this._bufs.length-1)return[n,e-t];t=a}},s.prototype._reverseOffset=function(e){const t=e[0];let n=e[1];for(let e=0;e<t;e++)n+=this._bufs[e].length;return n},s.prototype.get=function(e){if(e>this.length||e<0)return;const t=this._offset(e);return this._bufs[t[0]][t[1]]},s.prototype.slice=function(e,t){return"number"==typeof e&&e<0&&(e+=this.length),"number"==typeof t&&t<0&&(t+=this.length),this.copy(null,0,e,t)},s.prototype.copy=function(e,t,n,r){if(("number"!=typeof n||n<0)&&(n=0),("number"!=typeof r||r>this.length)&&(r=this.length),n>=this.length)return e||a.alloc(0);if(r<=0)return e||a.alloc(0);const s=!!e,o=this._offset(n),i=r-n;let c=i,l=s&&t||0,d=o[1];if(0===n&&r===this.length){if(!s)return 1===this._bufs.length?this._bufs[0]:a.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[o[0]].length-d)return s?this._bufs[o[0]].copy(e,t,d,d+c):this._bufs[o[0]].slice(d,d+c);s||(e=a.allocUnsafe(i));for(let t=o[0];t<this._bufs.length;t++){const n=this._bufs[t].length-d;if(!(c>n)){this._bufs[t].copy(e,l,d,d+c),l+=n;break}this._bufs[t].copy(e,l,d),l+=n,c-=n,d&&(d=0)}return e.length>l?e.slice(0,l):e},s.prototype.shallowSlice=function(e,t){if(e=e||0,t="number"!=typeof t?this.length:t,e<0&&(e+=this.length),t<0&&(t+=this.length),e===t)return this._new();const n=this._offset(e),a=this._offset(t),r=this._bufs.slice(n[0],a[0]+1);return 0===a[1]?r.pop():r[r.length-1]=r[r.length-1].slice(0,a[1]),0!==n[1]&&(r[0]=r[0].slice(n[1])),this._new(r)},s.prototype.toString=function(e,t,n){return this.slice(t,n).toString(e)},s.prototype.consume=function(e){if(e=Math.trunc(e),Number.isNaN(e)||e<=0)return this;for(;this._bufs.length;){if(!(e>=this._bufs[0].length)){this._bufs[0]=this._bufs[0].slice(e),this.length-=e;break}e-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift()}return this},s.prototype.duplicate=function(){const e=this._new();for(let t=0;t<this._bufs.length;t++)e.append(this._bufs[t]);return e},s.prototype.append=function(e){if(null==e)return this;if(e.buffer)this._appendBuffer(a.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(a.from(e));return this},s.prototype._appendBuffer=function(e){this._bufs.push(e),this.length+=e.length},s.prototype.indexOf=function(e,t,n){if(void 0===n&&"string"==typeof t&&(n=t,t=void 0),"function"==typeof e||Array.isArray(e))throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');if("number"==typeof e?e=a.from([e]):"string"==typeof e?e=a.from(e,n):this._isBufferList(e)?e=e.slice():Array.isArray(e.buffer)?e=a.from(e.buffer,e.byteOffset,e.byteLength):a.isBuffer(e)||(e=a.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 r=this._offset(t);let s=r[0],o=r[1];for(;s<this._bufs.length;s++){const t=this._bufs[s];for(;o<t.length;)if(t.length-o>=e.length){const n=t.indexOf(e,o);if(-1!==n)return this._reverseOffset([s,n]);o=t.length-e.length+1}else{const t=this._reverseOffset([s,o]);if(this._match(t,e))return t;o++}o=0}return-1},s.prototype._match=function(e,t){if(this.length-e<t.length)return!1;for(let n=0;n<t.length;n++)if(this.get(e+n)!==t[n])return!1;return!0},function(){const e={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(const t in e)!function(t){null===e[t]?s.prototype[t]=function(e,n){return this.slice(e,e+n)[t](0,n)}:s.prototype[t]=function(n=0){return this.slice(n,n+e[t])[t](0)}}(t)}(),s.prototype._isBufferList=function(e){return e instanceof s||s.isBufferList(e)},s.isBufferList=function(e){return null!=e&&e[r]},t.exports=s},{buffer:17}],15:[function(e,t,n){const a=e("readable-stream").Duplex,r=e("inherits"),s=e("./BufferList");function o(e){if(!(this instanceof o))return new o(e);if("function"==typeof e){this._callback=e;const t=function(e){this._callback&&(this._callback(e),this._callback=null)}.bind(this);this.on("pipe",(function(e){e.on("error",t)})),this.on("unpipe",(function(e){e.removeListener("error",t)})),e=null}s._init.call(this,e),a.call(this)}r(o,a),Object.assign(o.prototype,s.prototype),o.prototype._new=function(e){return new o(e)},o.prototype._write=function(e,t,n){this._appendBuffer(e),"function"==typeof n&&n()},o.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)},o.prototype.end=function(e){a.prototype.end.call(this,e),this._callback&&(this._callback(null,this.slice()),this._callback=null)},o.prototype._destroy=function(e,t){this._bufs.length=0,this.length=0,t(e)},o.prototype._isBufferList=function(e){return e instanceof o||e instanceof s||o.isBufferList(e)},o.isBufferList=s.isBufferList,t.exports=o,t.exports.BufferListStream=o,t.exports.BufferList=s},{"./BufferList":14,inherits:24,"readable-stream":69}],16:[function(e,t,n){},{}],17:[function(e,t,n){(function(t){(function(){var t=e("base64-js"),a=e("ieee754");n.Buffer=i,n.SlowBuffer=y,n.INSPECT_MAX_BYTES=50;var r=2147483647;function s(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(e){return!1}}function o(e){if(e>r)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 a=e.valueOf&&e.valueOf();if(null!=a&&a!==e)return i.from(a,t,n);var r=m(e);if(r)return r;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?o(e):void 0!==t?"string"==typeof n?o(e).fill(t,n):o(e).fill(t):o(e)}function u(e){return l(e),o(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),a=o(n),r=a.write(e,t);return r!==n&&(a=a.slice(0,r)),a}function p(e){for(var t=e.length<0?0:0|g(e.length),n=o(t),a=0;a<t;a+=1)n[a]=255&e[a];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 a;return(a=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n)).__proto__=i.prototype,a}function m(e){if(i.isBuffer(e)){var t=0|g(e.length),n=o(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0!==e.length?"number"!=typeof e.length||Y(e.length)?o(0):p(e):"Buffer"===e.type&&Array.isArray(e.data)?p(e.data):void 0}function g(e){if(e>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.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,a=arguments.length>2&&!0===arguments[2];if(!a&&0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return V(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(r)return a?-1:V(e).length;t=(""+t).toLowerCase(),r=!0}}function b(e,t,n){var a=!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 D(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 E(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return x(this,t,n);default:if(a)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),a=!0}}function w(e,t,n){var a=e[t];e[t]=e[n],e[n]=a}function I(e,t,n,a,r){if(0===e.length)return-1;if("string"==typeof n?(a=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),Y(n=+n)&&(n=r?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(r)return-1;n=e.length-1}else if(n<0){if(!r)return-1;n=0}if("string"==typeof t&&(t=i.from(t,a)),i.isBuffer(t))return 0===t.length?-1:C(e,t,n,a,r);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?r?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):C(e,[t],n,a,r);throw new TypeError("val must be string, number or Buffer")}function C(e,t,n,a,r){var s,o=1,i=e.length,c=t.length;if(void 0!==a&&("ucs2"===(a=String(a).toLowerCase())||"ucs-2"===a||"utf16le"===a||"utf-16le"===a)){if(e.length<2||t.length<2)return-1;o=2,i/=2,c/=2,n/=2}function l(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(r){var d=-1;for(s=n;s<i;s++)if(l(e,s)===l(t,-1===d?0:s-d)){if(-1===d&&(d=s),s-d+1===c)return d*o}else-1!==d&&(s-=s-d),d=-1}else for(n+c>i&&(n=i-c),s=n;s>=0;s--){for(var u=!0,h=0;h<c;h++)if(l(e,s+h)!==l(t,h)){u=!1;break}if(u)return s}return-1}function S(e,t,n,a){n=Number(n)||0;var r=e.length-n;a?(a=Number(a))>r&&(a=r):a=r;var s=t.length;a>s/2&&(a=s/2);for(var o=0;o<a;++o){var i=parseInt(t.substr(2*o,2),16);if(Y(i))return o;e[n+o]=i}return o}function O(e,t,n,a){return W(V(t,e.length-n),e,n,a)}function T(e,t,n,a){return W(z(t),e,n,a)}function k(e,t,n,a){return T(e,t,n,a)}function A(e,t,n,a){return W(J(t),e,n,a)}function _(e,t,n,a){return W(H(t,e.length-n),e,n,a)}function E(e,n,a){return 0===n&&a===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,a))}function R(e,t,n){n=Math.min(e.length,n);for(var a=[],r=t;r<n;){var s,o,i,c,l=e[r],d=null,u=l>239?4:l>223?3:l>191?2:1;if(r+u<=n)switch(u){case 1:l<128&&(d=l);break;case 2:128==(192&(s=e[r+1]))&&(c=(31&l)<<6|63&s)>127&&(d=c);break;case 3:s=e[r+1],o=e[r+2],128==(192&s)&&128==(192&o)&&(c=(15&l)<<12|(63&s)<<6|63&o)>2047&&(c<55296||c>57343)&&(d=c);break;case 4:s=e[r+1],o=e[r+2],i=e[r+3],128==(192&s)&&128==(192&o)&&128==(192&i)&&(c=(15&l)<<18|(63&s)<<12|(63&o)<<6|63&i)>65535&&c<1114112&&(d=c)}null===d?(d=65533,u=1):d>65535&&(d-=65536,a.push(d>>>10&1023|55296),d=56320|1023&d),a.push(d),r+=u}return M(a)}n.kMaxLength=r,i.TYPED_ARRAY_SUPPORT=s(),i.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(i.prototype,"parent",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.buffer}}),Object.defineProperty(i.prototype,"offset",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.byteOffset}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&i[Symbol.species]===i&&Object.defineProperty(i,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),i.poolSize=8192,i.from=function(e,t,n){return c(e,t,n)},i.prototype.__proto__=Uint8Array.prototype,i.__proto__=Uint8Array,i.alloc=function(e,t,n){return d(e,t,n)},i.allocUnsafe=function(e){return u(e)},i.allocUnsafeSlow=function(e){return u(e)},i.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==i.prototype},i.compare=function(e,t){if(G(e,Uint8Array)&&(e=i.from(e,e.offset,e.byteLength)),G(t,Uint8Array)&&(t=i.from(t,t.offset,t.byteLength)),!i.isBuffer(e)||!i.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var n=e.length,a=t.length,r=0,s=Math.min(n,a);r<s;++r)if(e[r]!==t[r]){n=e[r],a=t[r];break}return n<a?-1:a<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 a=i.allocUnsafe(t),r=0;for(n=0;n<e.length;++n){var s=e[n];if(G(s,Uint8Array)&&(s=i.from(s)),!i.isBuffer(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(a,r),r+=s.length}return a},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,a,r){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===a&&(a=0),void 0===r&&(r=this.length),t<0||n>e.length||a<0||r>this.length)throw new RangeError("out of range index");if(a>=r&&t>=n)return 0;if(a>=r)return-1;if(t>=n)return 1;if(this===e)return 0;for(var s=(r>>>=0)-(a>>>=0),o=(n>>>=0)-(t>>>=0),c=Math.min(s,o),l=this.slice(a,r),d=e.slice(t,n),u=0;u<c;++u)if(l[u]!==d[u]){s=l[u],o=d[u];break}return s<o?-1:o<s?1:0},i.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},i.prototype.indexOf=function(e,t,n){return I(this,e,t,n,!0)},i.prototype.lastIndexOf=function(e,t,n){return I(this,e,t,n,!1)},i.prototype.write=function(e,t,n,a){if(void 0===t)a="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)a=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===a&&(a="utf8")):(a=n,n=void 0)}var r=this.length-t;if((void 0===n||n>r)&&(n=r),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");a||(a="utf8");for(var s=!1;;)switch(a){case"hex":return S(this,e,t,n);case"utf8":case"utf-8":return O(this,e,t,n);case"ascii":return T(this,e,t,n);case"latin1":case"binary":return k(this,e,t,n);case"base64":return A(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+a);a=(""+a).toLowerCase(),s=!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="",a=0;a<t;)n+=String.fromCharCode.apply(String,e.slice(a,a+=P));return n}function j(e,t,n){var a="";n=Math.min(e.length,n);for(var r=t;r<n;++r)a+=String.fromCharCode(127&e[r]);return a}function U(e,t,n){var a="";n=Math.min(e.length,n);for(var r=t;r<n;++r)a+=String.fromCharCode(e[r]);return a}function D(e,t,n){var a=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>a)&&(n=a);for(var r="",s=t;s<n;++s)r+=Q(e[s]);return r}function x(e,t,n){for(var a=e.slice(t,n),r="",s=0;s<a.length;s+=2)r+=String.fromCharCode(a[s]+256*a[s+1]);return r}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,a,r,s){if(!i.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>r||t<s)throw new RangeError('"value" argument is out of bounds');if(n+a>e.length)throw new RangeError("Index out of range")}function B(e,t,n,a,r,s){if(n+a>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function L(e,t,n,r,s){return t=+t,n>>>=0,s||B(e,t,n,4),a.write(e,t,n,r,23,4),n+4}function F(e,t,n,r,s){return t=+t,n>>>=0,s||B(e,t,n,8),a.write(e,t,n,r,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 a=this.subarray(e,t);return a.__proto__=i.prototype,a},i.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||q(e,t,this.length);for(var a=this[e],r=1,s=0;++s<t&&(r*=256);)a+=this[e+s]*r;return a},i.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||q(e,t,this.length);for(var a=this[e+--t],r=1;t>0&&(r*=256);)a+=this[e+--t]*r;return a},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 a=this[e],r=1,s=0;++s<t&&(r*=256);)a+=this[e+s]*r;return a>=(r*=128)&&(a-=Math.pow(2,8*t)),a},i.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||q(e,t,this.length);for(var a=t,r=1,s=this[e+--a];a>0&&(r*=256);)s+=this[e+--a]*r;return s>=(r*=128)&&(s-=Math.pow(2,8*t)),s},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),a.read(this,e,!0,23,4)},i.prototype.readFloatBE=function(e,t){return e>>>=0,t||q(e,4,this.length),a.read(this,e,!1,23,4)},i.prototype.readDoubleLE=function(e,t){return e>>>=0,t||q(e,8,this.length),a.read(this,e,!0,52,8)},i.prototype.readDoubleBE=function(e,t){return e>>>=0,t||q(e,8,this.length),a.read(this,e,!1,52,8)},i.prototype.writeUIntLE=function(e,t,n,a){e=+e,t>>>=0,n>>>=0,a||N(this,e,t,n,Math.pow(2,8*n)-1,0);var r=1,s=0;for(this[t]=255&e;++s<n&&(r*=256);)this[t+s]=e/r&255;return t+n},i.prototype.writeUIntBE=function(e,t,n,a){e=+e,t>>>=0,n>>>=0,a||N(this,e,t,n,Math.pow(2,8*n)-1,0);var r=n-1,s=1;for(this[t+r]=255&e;--r>=0&&(s*=256);)this[t+r]=e/s&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,a){if(e=+e,t>>>=0,!a){var r=Math.pow(2,8*n-1);N(this,e,t,n,r-1,-r)}var s=0,o=1,i=0;for(this[t]=255&e;++s<n&&(o*=256);)e<0&&0===i&&0!==this[t+s-1]&&(i=1),this[t+s]=(e/o>>0)-i&255;return t+n},i.prototype.writeIntBE=function(e,t,n,a){if(e=+e,t>>>=0,!a){var r=Math.pow(2,8*n-1);N(this,e,t,n,r-1,-r)}var s=n-1,o=1,i=0;for(this[t+s]=255&e;--s>=0&&(o*=256);)e<0&&0===i&&0!==this[t+s+1]&&(i=1),this[t+s]=(e/o>>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,a){if(!i.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),a||0===a||(a=this.length),t>=e.length&&(t=e.length),t||(t=0),a>0&&a<n&&(a=n),a===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(a<0)throw new RangeError("sourceEnd out of bounds");a>this.length&&(a=this.length),e.length-t<a-n&&(a=e.length-t+n);var r=a-n;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,n,a);else if(this===e&&n<t&&t<a)for(var s=r-1;s>=0;--s)e[s+t]=this[s+n];else Uint8Array.prototype.set.call(e,this.subarray(n,a),t);return r},i.prototype.fill=function(e,t,n,a){if("string"==typeof e){if("string"==typeof t?(a=t,t=0,n=this.length):"string"==typeof n&&(a=n,n=this.length),void 0!==a&&"string"!=typeof a)throw new TypeError("encoding must be a string");if("string"==typeof a&&!i.isEncoding(a))throw new TypeError("Unknown encoding: "+a);if(1===e.length){var r=e.charCodeAt(0);("utf8"===a&&r<128||"latin1"===a)&&(e=r)}}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;var s;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(s=t;s<n;++s)this[s]=e;else{var o=i.isBuffer(e)?e:i.from(e,a),c=o.length;if(0===c)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(s=0;s<n-t;++s)this[s+t]=o[s%c]}return this};var K=/[^+/0-9A-Za-z-_]/g;function $(e){if((e=(e=e.split("=")[0]).trim().replace(K,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}function Q(e){return e<16?"0"+e.toString(16):e.toString(16)}function V(e,t){var n;t=t||1/0;for(var a=e.length,r=null,s=[],o=0;o<a;++o){if((n=e.charCodeAt(o))>55295&&n<57344){if(!r){if(n>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===a){(t-=3)>-1&&s.push(239,191,189);continue}r=n;continue}if(n<56320){(t-=3)>-1&&s.push(239,191,189),r=n;continue}n=65536+(r-55296<<10|n-56320)}else r&&(t-=3)>-1&&s.push(239,191,189);if(r=null,n<128){if((t-=1)<0)break;s.push(n)}else if(n<2048){if((t-=2)<0)break;s.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;s.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return s}function z(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,a,r,s=[],o=0;o<e.length&&!((t-=2)<0);++o)a=(n=e.charCodeAt(o))>>8,r=n%256,s.push(r),s.push(a);return s}function J(e){return t.toByteArray($(e))}function W(e,t,n,a){for(var r=0;r<a&&!(r+n>=t.length||r>=e.length);++r)t[r+n]=e[r];return r}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(a){(function(){function r(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))}function s(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;e.splice(1,0,n,"color: inherit");let a=0,r=0;e[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(a++,"%c"===e&&(r=a))})),e.splice(r,0,n)}function o(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!==a&&"env"in a&&(e=a.env.DEBUG),e}function c(){try{return localStorage}catch(e){}}n.formatArgs=s,n.save=o,n.load=i,n.useColors=r,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 a(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 a.colors[Math.abs(t)%a.colors.length]}function a(e){let t,n,s,o=null;function i(...e){if(!i.enabled)return;const n=i,r=Number(new Date),s=r-(t||r);n.diff=s,n.prev=t,n.curr=r,t=r,e[0]=a.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((t,r)=>{if("%%"===t)return"%";o++;const s=a.formatters[r];if("function"==typeof s){const a=e[o];t=s.call(n,a),e.splice(o,1),o--}return t})),a.formatArgs.call(n,e),(n.log||a.log).apply(n,e)}return i.namespace=e,i.useColors=a.useColors(),i.color=a.selectColor(e),i.extend=r,i.destroy=a.destroy,Object.defineProperty(i,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(n!==a.namespaces&&(n=a.namespaces,s=a.enabled(e)),s),set:e=>{o=e}}),"function"==typeof a.init&&a.init(i),i}function r(e,t){const n=a(this.namespace+(void 0===t?":":t)+e);return n.log=this.log,n}function s(e){let t;a.save(e),a.namespaces=e,a.names=[],a.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),r=n.length;for(t=0;t<r;t++)n[t]&&("-"===(e=n[t].replace(/\*/g,".*?"))[0]?a.skips.push(new RegExp("^"+e.substr(1)+"$")):a.names.push(new RegExp("^"+e+"$")))}function o(){const e=[...a.names.map(c),...a.skips.map(c).map((e=>"-"+e))].join(",");return a.enable(""),e}function i(e){if("*"===e[e.length-1])return!0;let t,n;for(t=0,n=a.skips.length;t<n;t++)if(a.skips[t].test(e))return!1;for(t=0,n=a.names.length;t<n;t++)if(a.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 a.debug=a,a.default=a,a.coerce=l,a.disable=o,a.enable=s,a.enabled=i,a.humanize=e("ms"),a.destroy=d,Object.keys(t).forEach((e=>{a[e]=t[e]})),a.names=[],a.skips=[],a.formatters={},a.selectColor=n,a.enable(a.load()),a}t.exports=a},{ms:45}],20:[function(e,t,n){(function(n,a){(function(){var r=e("readable-stream"),s=e("end-of-stream"),o=e("inherits"),i=e("stream-shift"),c=a.from&&a.from!==Uint8Array.from?a.from([0]):new a([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 r.Readable({objectMode:!0,highWaterMark:16}).wrap(e)},m=function(e,t,n){if(!(this instanceof m))return new m(e,t,n);r.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)};o(m,r.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,a=s(e,{writable:!0,readable:!1},u(this,this._forwardEnd)),r=function(){var e=t._ondrain;t._ondrain=null,e&&e()},o=function(){t._writable.removeListener("drain",r),a()};this._unwrite&&n.nextTick(r),this._writable=e,this._writable.on("drain",r),this._unwrite=o,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=s(e,{writable:!1,readable:!0},u(this)),a=function(){t._forward()},r=function(){t.push(null)},o=function(){t._readable2.removeListener("readable",a),t._readable2.removeListener("end",r),n()};this._drained=!0,this._readable=e,this._readable2=e._readableState?e:f(e),this._readable2.on("readable",a),this._readable2.on("end",r),this._unread=o,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 a=this;n.nextTick((function(){a._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),r.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 a=e("once"),r=function(){},s=function(e){return e.setHeader&&"function"==typeof e.abort},o=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=a(c||r);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"))},I=function(){e.req.on("finish",m)};return s(e)?(e.on("complete",m),e.on("abort",b),e.req?I():e.on("request",I)):h&&!l&&(e.on("end",f),e.on("close",f)),o(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",I),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 a=Object.create||O,r=Object.keys||T,s=Function.prototype.bind||k;function o(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=a(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}t.exports=o,o.EventEmitter=o,o.prototype._events=void 0,o.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?o.defaultMaxListeners:e._maxListeners}function u(e,t,n){if(t)e.call(n);else for(var a=e.length,r=C(e,a),s=0;s<a;++s)r[s].call(n)}function h(e,t,n,a){if(t)e.call(n,a);else for(var r=e.length,s=C(e,r),o=0;o<r;++o)s[o].call(n,a)}function p(e,t,n,a,r){if(t)e.call(n,a,r);else for(var s=e.length,o=C(e,s),i=0;i<s;++i)o[i].call(n,a,r)}function f(e,t,n,a,r,s){if(t)e.call(n,a,r,s);else for(var o=e.length,i=C(e,o),c=0;c<o;++c)i[c].call(n,a,r,s)}function m(e,t,n,a){if(t)e.apply(n,a);else for(var r=e.length,s=C(e,r),o=0;o<r;++o)s[o].apply(n,a)}function g(e,t,n,r){var s,o,i;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((o=e._events)?(o.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),o=e._events),i=o[t]):(o=e._events=a(null),e._eventsCount=0),i){if("function"==typeof i?i=o[t]=r?[n,i]:[i,n]:r?i.unshift(n):i.push(n),!i.warned&&(s=d(e))&&s>0&&i.length>s){i.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+i.length+' "'+String(t)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=i.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",c.name,c.message)}}else i=o[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 a={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},r=s.call(y,a);return r.listener=n,a.wrapFn=r,r}function b(e,t,n){var a=e._events;if(!a)return[];var r=a[t];return r?"function"==typeof r?n?[r.listener||r]:[r]:n?S(r):C(r,r.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 I(e,t){for(var n=t,a=n+1,r=e.length;a<r;n+=1,a+=1)e[n]=e[a];e.pop()}function C(e,t){for(var n=new Array(t),a=0;a<t;++a)n[a]=e[a];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 O(e){var t=function(){};return t.prototype=e,new t}function T(e){for(var t in e)Object.prototype.hasOwnProperty.call(e,t);return t}function k(e){var t=this;return function(){return t.apply(e,arguments)}}i?Object.defineProperty(o,"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}}):o.defaultMaxListeners=c,o.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},o.prototype.getMaxListeners=function(){return d(this)},o.prototype.emit=function(e){var t,n,a,r,s,o,i="error"===e;if(o=this._events)i=i&&null==o.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=o[e]))return!1;var l="function"==typeof n;switch(a=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(r=new Array(a-1),s=1;s<a;s++)r[s-1]=arguments[s];m(n,l,this,r)}return!0},o.prototype.addListener=function(e,t){return g(this,e,t,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(e,t){return g(this,e,t,!0)},o.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},o.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},o.prototype.removeListener=function(e,t){var n,r,s,o,i;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(r=this._events))return this;if(!(n=r[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=a(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){i=n[o].listener,s=o;break}if(s<0)return this;0===s?n.shift():I(n,s),1===n.length&&(r[e]=n[0]),r.removeListener&&this.emit("removeListener",e,i||t)}return this},o.prototype.removeAllListeners=function(e){var t,n,s;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=a(null),this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=a(null):delete n[e]),this;if(0===arguments.length){var o,i=r(n);for(s=0;s<i.length;++s)"removeListener"!==(o=i[s])&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=a(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(t)for(s=t.length-1;s>=0;s--)this.removeListener(e,t[s]);return this},o.prototype.listeners=function(e){return b(this,e,!0)},o.prototype.rawListeners=function(e){return b(this,e,!1)},o.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):w.call(e,t)},o.prototype.listenerCount=w,o.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}},{}],23:[function(e,t,n){
|
|
2
2
|
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
|
|
3
|
-
n.read=function(e,t,n,a,r){var s,o,i=8*r-a-1,c=(1<<i)-1,l=c>>1,d=-7,u=n?r-1:0,h=n?-1:1,p=e[t+u];for(u+=h,s=p&(1<<-d)-1,p>>=-d,d+=i;d>0;s=256*s+e[t+u],u+=h,d-=8);for(o=s&(1<<-d)-1,s>>=-d,d+=a;d>0;o=256*o+e[t+u],u+=h,d-=8);if(0===s)s=1-l;else{if(s===c)return o?NaN:1/0*(p?-1:1);o+=Math.pow(2,a),s-=l}return(p?-1:1)*o*Math.pow(2,s-a)},n.write=function(e,t,n,a,r,s){var o,i,c,l=8*s-r-1,d=(1<<l)-1,u=d>>1,h=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,p=a?0:s-1,f=a?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,o=d):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-o))<1&&(o--,c*=2),(t+=o+u>=1?h/c:h*Math.pow(2,1-u))*c>=2&&(o++,c/=2),o+u>=d?(i=0,o=d):o+u>=1?(i=(t*c-1)*Math.pow(2,r),o+=u):(i=t*Math.pow(2,u-1)*Math.pow(2,r),o=0));r>=8;e[n+p]=255&i,p+=f,i/=256,r-=8);for(o=o<<r|i,l+=r;l>0;e[n+p]=255&o,p+=f,o/=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 a=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,a=this.rightChild;if(!a)throw new Error("unknown error");var r=a.leftChild,s=a.rightChild;return e&&(e.leftChild===this?e.leftChild=a:e.rightChild===this&&(e.rightChild=a)),a.parent=e,a.brother=t,a.leftChild=this,a.rightChild=s,t&&(t.brother=a),this.parent=a,this.brother=s,this.leftChild=n,this.rightChild=r,s&&(s.parent=a,s.brother=this),n&&(n.parent=this,n.brother=r),r&&(r.parent=this,r.brother=n),a},e.prototype.rotateRight=function(){var e=this.parent,t=this.brother,n=this.leftChild;if(!n)throw new Error("unknown error");var a=this.rightChild,r=n.leftChild,s=n.rightChild;return e&&(e.leftChild===this?e.leftChild=n:e.rightChild===this&&(e.rightChild=n)),n.parent=e,n.brother=t,n.leftChild=r,n.rightChild=this,t&&(t.brother=n),r&&(r.parent=n,r.brother=this),this.parent=n,this.brother=r,this.leftChild=s,this.rightChild=a,s&&(s.parent=this,s.brother=a),a&&(a.parent=this,a.brother=s),n},e.prototype.remove=function(){if(this.leftChild||this.rightChild)throw new Error("can only remove leaf node");this.parent&&(this===this.parent.leftChild?this.parent.leftChild=void 0:this===this.parent.rightChild&&(this.parent.rightChild=void 0)),this.brother&&(this.brother.brother=void 0),this.key=void 0,this.value=void 0,this.parent=void 0,this.brother=void 0},e.TreeNodeColorType={red:!0,black:!1},e}();Object.freeze(a),n.default=a},{}],26:[function(e,t,n){var a=this&&this.__generator||function(e,t){var n,a,r,s,o={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,a&&(r=2&s[0]?a.return:s[0]?a.throw||((r=a.return)&&r.call(a),0):a.next)&&!(r=r.call(a,s[1])).done)return r;switch(a=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,a=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((r=(r=o.trys).length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]<r[3])){o.label=s[1];break}if(6===s[0]&&o.label<r[1]){o.label=r[1],r=s;break}if(r&&o.label<r[2]){o.label=r[2],o.ops.push(s);break}r[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],a=0}finally{n=r=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}};function r(e){var t=this;void 0===e&&(e=[]);var n=[],s=0,o=0,i=0,c=0,l=0,d=0;this.size=function(){return d},this.empty=function(){return 0===d},this.clear=function(){s=i=o=c=l=d=0,h.call(this,r.bucketSize),d=0},this.front=function(){return n[s][o]},this.back=function(){return n[i][c]},this.forEach=function(e){if(!this.empty()){var t=0;if(s!==i){for(l=o;l<r.bucketSize;++l)e(n[s][l],t++);for(l=s+1;l<i;++l)for(var a=0;a<r.bucketSize;++a)e(n[l][a],t++);for(l=0;l<=c;++l)e(n[i][l],t++)}else for(var l=o;l<=c;++l)e(n[s][l],t++)}};var u=function(e){var t=s*r.bucketSize+o,n=t+e,a=i*r.bucketSize+c;if(n<t||n>a)throw new Error("pos should more than 0 and less than queue's size");return{curNodeBucketIndex:Math.floor(n/r.bucketSize),curNodePointerIndex:n%r.bucketSize}};this.getElementByPos=function(e){var t=u(e),a=t.curNodeBucketIndex,r=t.curNodePointerIndex;return n[a][r]},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=[],a=e+1;a<d;++a)n.push(this.getElementByPos(a));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,a=0;a<n;++a)this.setElementByPos(a,t[a]);this.cut(n-1)}};var h=function(e){for(var t=[],a=e*r.sigma,u=Math.max(Math.ceil(a/r.bucketSize),2),h=0;h<u;++h)t.push(new Array(r.bucketSize));var p=Math.ceil(e/r.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<r.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,s=f,o=0,i=m,c=g,l=u,d=e};this.pushBack=function(e){this.empty()||(i===l-1&&c===r.bucketSize-1&&h.call(this,this.size()),c<r.bucketSize-1?++c:i<l-1&&(++i,c=0)),++d,n[i][c]=e},this.popBack=function(){this.empty()||(1!==this.size()&&(c>0?--c:s<i&&(--i,c=r.bucketSize-1)),d>0&&--d)},this.setElementByPos=function(e,t){var a=u(e),r=a.curNodeBucketIndex,s=a.curNodePointerIndex;n[r][s]=t},this.insert=function(e,t,n){var a=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 r=[],s=e;s<d;++s)r.push(this.getElementByPos(s));for(this.cut(e-1),s=0;s<n;++s)this.pushBack(t);r.forEach((function(e){return a.pushBack(e)}))}},this.find=function(e){if(s===i){for(var t=o;t<=c;++t)if(n[s][t]===e)return!0;return!1}for(t=o;t<r.bucketSize;++t)if(n[s][t]===e)return!0;for(t=s+1;t<i;++t)for(var a=0;a<r.bucketSize;++a)if(n[t][a]===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,a){0!==a&&n===t||(e.push(n),t=n)}));for(var n=0;n<d;++n)this.setElementByPos(n,e[n]);this.cut(e.length-1)}},this.sort=function(e){var t=[];this.forEach((function(e){t.push(e)})),t.sort(e);for(var n=0;n<d;++n)this.setElementByPos(n,t[n])},this.pushFront=function(e){this.empty()||(0===s&&0===o&&h.call(this,this.size()),o>0?--o:s>0&&(--s,o=r.bucketSize-1)),++d,n[s][o]=e},this.popFront=function(){this.empty()||(1!==this.size()&&(o<r.bucketSize-1?++o:s<i&&(++s,o=0)),d>0&&--d)},this.shrinkToFit=function(){var e=this,t=[];this.forEach((function(e){t.push(e)}));var a=t.length;n=[];for(var s=Math.ceil(a/r.bucketSize),o=0;o<s;++o)n.push(new Array(r.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,a=t.curNodePointerIndex;i=n,c=a,d=e+1}},this[Symbol.iterator]=function(){return function(){var e,t;return a(this,(function(a){switch(a.label){case 0:if(0===d)return[2];if(s!==i)return[3,5];t=o,a.label=1;case 1:return t<=c?[4,n[s][t]]:[3,4];case 2:a.sent(),a.label=3;case 3:return++t,[3,1];case 4:return[2];case 5:t=o,a.label=6;case 6:return t<r.bucketSize?[4,n[s][t]]:[3,9];case 7:a.sent(),a.label=8;case 8:return++t,[3,6];case 9:t=s+1,a.label=10;case 10:if(!(t<i))return[3,15];e=0,a.label=11;case 11:return e<r.bucketSize?[4,n[t][e]]:[3,14];case 12:a.sent(),a.label=13;case 13:return++e,[3,11];case 14:return++t,[3,10];case 15:t=0,a.label=16;case 16:return t<=c?[4,n[i][t]]:[3,19];case 17:a.sent(),a.label=18;case 18:return++t,[3,16];case 19:return[2]}}))}()},function(){var a=r.bucketSize;e.size?a=e.size():e.length&&(a=e.length);var o=a*r.sigma;l=Math.ceil(o/r.bucketSize),l=Math.max(l,3);for(var c=0;c<l;++c)n.push(new Array(r.bucketSize));var d=Math.ceil(a/r.bucketSize);s=Math.floor(l/2)-Math.floor(d/2),i=s,e.forEach((function(e){return t.pushBack(e)}))}(),Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),r.sigma=3,r.bucketSize=5e3,Object.freeze(r),n.default=r},{}],27:[function(e,t,n){var a=this&&this.__generator||function(e,t){var n,a,r,s,o={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,a&&(r=2&s[0]?a.return:s[0]?a.throw||((r=a.return)&&r.call(a),0):a.next)&&!(r=r.call(a,s[1])).done)return r;switch(a=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,a=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((r=(r=o.trys).length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]<r[3])){o.label=s[1];break}if(6===s[0]&&o.label<r[1]){o.label=r[1],r=s;break}if(r&&o.label<r[2]){o.label=r[2],o.ops.push(s);break}r[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],a=0}finally{n=r=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},r=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],a=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&a>=e.length&&(e=void 0),{value:e&&e[a++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var s=e("../LinkList/LinkList"),o=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,a=0,s="";if("number"==typeof e)a=((a=Math.floor(e))<<5)-a,a&=a;else{s="string"!=typeof e?JSON.stringify(e):e;try{for(var o=r(s),i=o.next();!i.done;i=o.next())a=(a<<5)-a+i.value.charCodeAt(0),a&=a}catch(e){t={error:e}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}}return a^=a>>>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(a,r){if(!a.empty()){if(a instanceof s.default&&1===a.size()){var c=a.front(),l=c.key,h=c.value;t[n(l)&u-1]=new s.default([{key:l,value:h}])}else if(a instanceof o.default){var p=new s.default,f=new s.default;a.forEach((function(t){0==(n(t.key)&e)?p.pushBack(t):f.pushBack(t)})),p.size()>i.untreeifyThreshold?t[r]=new o.default(p):p.size()&&(t[r]=p),f.size()>i.untreeifyThreshold?t[r+e]=new o.default(f):f.size()&&(t[r+e]=f)}else{var m=new s.default,g=new s.default;a.forEach((function(t){0==(n(t.key)&e)?m.pushBack(t):g.pushBack(t)})),m.size()&&(t[r]=m),g.size()&&(t[r+e]=g)}d[r].clear()}})),d=t}};this.setElement=function(e,t){var a,c;if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(null!=t){var p=n(e)&u-1;if(d[p]){var f=d[p].size();if(d[p]instanceof s.default){try{for(var m=r(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){a={error:e}}finally{try{g&&!g.done&&(c=m.return)&&c.call(m)}finally{if(a)throw a.error}}d[p].pushBack({key:e,value:t}),d[p].size()>=i.treeifyThreshold&&(d[p]=new o.default(d[p]))}else d[p].setElement(e,t);var v=d[p].size();l+=v-f}else++l,d[p]=new s.default([{key:e,value:t}]);l>u*i.sigma&&h.call(this,u)}else this.eraseElementByKey(e)},this.getElementByKey=function(e){var t,a,s=n(e)&u-1;if(d[s]){if(d[s]instanceof o.default)return d[s].getElementByKey(e);try{for(var i=r(d[s]),c=i.next();!c.done;c=i.next()){var l=c.value;if(l.key===e)return l.value}}catch(e){t={error:e}}finally{try{c&&!c.done&&(a=i.return)&&a.call(i)}finally{if(t)throw t.error}}}},this.eraseElementByKey=function(e){var t,a,c=n(e)&u-1;if(d[c]){var h=d[c].size();if(d[c]instanceof o.default)d[c].eraseElementByKey(e),d[c].size()<=i.untreeifyThreshold&&(d[c]=new s.default(d[c]));else{var p=-1;try{for(var f=r(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&&(a=f.return)&&a.call(f)}finally{if(t)throw t.error}}}var y=d[c].size();l+=y-h}},this.find=function(e){var t,a,s=n(e)&u-1;if(!d[s])return!1;if(d[s]instanceof o.default)return d[s].find(e);try{for(var i=r(d[s]),c=i.next();!c.done;c=i.next())if(c.value.key===e)return!0}catch(e){t={error:e}}finally{try{c&&!c.done&&(a=i.return)&&a.call(i)}finally{if(t)throw t.error}}return!1},this[Symbol.iterator]=function(){return function(){var e,t,n,s,o,i;return a(this,(function(a){switch(a.label){case 0:e=0,a.label=1;case 1:if(!(e<u))return[3,10];for(;e<u&&!d[e];)++e;if(e>=u)return[3,10];a.label=2;case 2:a.trys.push([2,7,8,9]),o=void 0,t=r(d[e]),n=t.next(),a.label=3;case 3:return n.done?[3,6]:[4,n.value];case 4:a.sent(),a.label=5;case 5:return n=t.next(),[3,3];case 6:return[3,9];case 7:return s=a.sent(),o={error:s},[3,9];case 8:try{n&&!n.done&&(i=t.return)&&i.call(t)}finally{if(o)throw o.error}return[7];case 9:return++e,[3,1];case 10:return[2]}}))}()},e.forEach((function(e){var t=e.key,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 a=this&&this.__generator||function(e,t){var n,a,r,s,o={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,a&&(r=2&s[0]?a.return:s[0]?a.throw||((r=a.return)&&r.call(a),0):a.next)&&!(r=r.call(a,s[1])).done)return r;switch(a=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,a=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((r=(r=o.trys).length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]<r[3])){o.label=s[1];break}if(6===s[0]&&o.label<r[1]){o.label=r[1],r=s;break}if(r&&o.label<r[2]){o.label=r[2],o.ops.push(s);break}r[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],a=0}finally{n=r=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},r=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],a=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&a>=e.length&&(e=void 0),{value:e&&e[a++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var s=e("../Set/Set"),o=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 a=0;a<n.length;a++)t=(t<<5)-t+n.charCodeAt(a),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(a,r){if(!a.empty()){if(a instanceof o.default&&1===a.size()){var c=a.front();if(void 0===c)throw new Error("unknown error");t[n(c)&u-1]=new o.default([c])}else if(a instanceof s.default){var l=new o.default,h=new o.default;a.forEach((function(t){0==(n(t)&e)?l.pushBack(t):h.pushBack(t)})),l.size()>i.untreeifyThreshold?t[r]=new s.default(l):l.size()&&(t[r]=l),h.size()>i.untreeifyThreshold?t[r+e]=new s.default(h):h.size()&&(t[r+e]=h)}else{var p=new o.default,f=new o.default;a.forEach((function(t){0==(n(t)&e)?p.pushBack(t):f.pushBack(t)})),p.size()&&(t[r]=p),f.size()&&(t[r+e]=f)}d[r].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 a=d[t].size();if(d[t]instanceof o.default){if(d[t].find(e))return;d[t].pushBack(e),d[t].size()>=i.treeifyThreshold&&(d[t]=new s.default(d[t]))}else d[t].insert(e);var r=d[t].size();l+=r-a}else d[t]=new o.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 a=d[t].size();d[t].eraseElementByValue(e),d[t]instanceof s.default&&d[t].size()<=i.untreeifyThreshold&&(d[t]=new o.default(d[t]));var r=d[t].size();l+=r-a}},this.find=function(e){var t=n(e)&u-1;return!!d[t]&&d[t].find(e)},this[Symbol.iterator]=function(){return function(){var e,t,n,s,o,i;return a(this,(function(a){switch(a.label){case 0:e=0,a.label=1;case 1:if(!(e<u))return[3,10];for(;e<u&&!d[e];)++e;if(e>=u)return[3,10];a.label=2;case 2:a.trys.push([2,7,8,9]),o=void 0,t=r(d[e]),n=t.next(),a.label=3;case 3:return n.done?[3,6]:[4,n.value];case 4:a.sent(),a.label=5;case 5:return n=t.next(),[3,3];case 6:return[3,9];case 7:return s=a.sent(),o={error:s},[3,9];case 8:try{n&&!n.done&&(i=t.return)&&i.call(t)}finally{if(o)throw o.error}return[7];case 9:return++e,[3,1];case 10:return[2]}}))}()},e.forEach((function(e){return 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 a=this&&this.__generator||function(e,t){var n,a,r,s,o={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,a&&(r=2&s[0]?a.return:s[0]?a.throw||((r=a.return)&&r.call(a),0):a.next)&&!(r=r.call(a,s[1])).done)return r;switch(a=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,a=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((r=(r=o.trys).length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]<r[3])){o.label=s[1];break}if(6===s[0]&&o.label<r[1]){o.label=r[1],r=s;break}if(r&&o.label<r[2]){o.label=r[2],o.ops.push(s);break}r[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],a=0}finally{n=r=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}};Object.defineProperty(n,"__esModule",{value:!0});var r=function(){function e(e){this.value=void 0,this.pre=void 0,this.next=void 0,this.value=e}return e}();function s(e){var t=this;void 0===e&&(e=[]);var n=0,s=void 0,o=void 0;this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){s=o=void 0,n=0},this.front=function(){return null==s?void 0:s.value},this.back=function(){return null==o?void 0:o.value},this.forEach=function(e){for(var t=s,n=0;t;){if(void 0===t.value)throw new Error("unknown error");e(t.value,n++),t=t.next}},this.getElementByPos=function(e){if(e<0||e>=n)throw new Error("pos must more then 0 and less then the list length");for(var t=s;e--&&t;)t=t.next;if(!t||void 0===t.value)throw new Error("unknown error");return t.value},this.eraseElementByPos=function(e){if(e<0||e>=n)throw new Error("erase pos must more then 0 and less then the list length");if(0===e)this.popFront();else if(e===n-1)this.popBack();else{for(var t=s;e--;){if(!(null==t?void 0:t.next))throw new Error("unknown error");t=t.next}if(!t||!t.pre||!t.next)throw new Error("unknown error");var a=t.pre,r=t.next;r.pre=a,a.next=r,n>0&&--n}},this.eraseElementByValue=function(e){for(;s&&s.value===e;)this.popFront();for(;o&&o.value===e;)this.popBack();if(s)for(var t=s;t;){if(t.value===e){var a=t.pre,r=t.next;r&&(r.pre=a),a&&(a.next=r),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 r(e);o?(o.next=t,t.pre=o,o=t):s=o=t},this.popBack=function(){o&&(n>0&&--n,o&&(s===o?s=o=void 0:(o=o.pre)&&(o.next=void 0)))},this.setElementByPos=function(e,t){if(null==t)throw new Error("you can't set null or undefined here");if(e<0||e>=n)throw new Error("pos must more then 0 and less then the list length");for(var a=s;e--;){if(!a)throw new Error("unknown error");a=a.next}a&&(a.value=t)},this.insert=function(e,t,a){if(void 0===a&&(a=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(a<0)throw new Error("insert size must more than 0");if(0===e)for(;a--;)this.pushFront(t);else if(e===n)for(;a--;)this.pushBack(t);else{for(var o=s,i=1;i<e;++i){if(!(null==o?void 0:o.next))throw new Error("unknown error");o=null==o?void 0:o.next}if(!o)throw new Error("unknown error");var c=o.next;for(n+=a;a--;)o.next=new r(t),o.next.pre=o,o=o.next;o.next=c,c&&(c.pre=o)}},this.find=function(e){for(var t=s;t;){if(t.value===e)return!0;t=t.next}return!1},this.reverse=function(){for(var e=s,t=o,a=0;e&&t&&2*a<n;){var r=e.value;e.value=t.value,t.value=r,e=e.next,t=t.pre,++a}},this.unique=function(){for(var e=s;e;){for(var t=e;t&&t.next&&t.value===t.next.value;)t=t.next,n>0&&--n;e.next=t.next,e.next&&(e.next.pre=e),e=e.next}},this.sort=function(e){var t=[];this.forEach((function(e){t.push(e)})),t.sort(e);var n=s;t.forEach((function(e){n&&(n.value=e,n=n.next)}))},this.pushFront=function(e){if(null==e)throw new Error("you can't push null or undefined here");++n;var t=new r(e);s?(t.next=s,s.pre=t,s=t):s=o=t},this.popFront=function(){s&&(n>0&&--n,s&&(s===o?s=o=void 0:(s=s.next)&&(s.pre=void 0)))},this.merge=function(e){var t=this,a=s;e.forEach((function(e){for(;a&&void 0!==a.value&&a.value<=e;)a=a.next;if(void 0===a)t.pushBack(e),a=o;else if(a===s)t.pushFront(e),a=s;else{++n;var i=a.pre;i&&(i.next=new r(e),i.next.pre=i,i.next.next=a,a&&(a.pre=i.next))}}))},this[Symbol.iterator]=function(){return function(){var e;return a(this,(function(t){switch(t.label){case 0:e=s,t.label=1;case 1:if(void 0===e)return[3,3];if(!e.value)throw new Error("unknown error");return[4,e.value];case 2:return t.sent(),e=e.next,[3,1];case 3:return[2]}}))}()},e.forEach((function(e){return t.pushBack(e)})),Object.freeze(this)}Object.freeze(s),n.default=s},{}],30:[function(e,t,n){var a=this&&this.__generator||function(e,t){var n,a,r,s,o={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,a&&(r=2&s[0]?a.return:s[0]?a.throw||((r=a.return)&&r.call(a),0):a.next)&&!(r=r.call(a,s[1])).done)return r;switch(a=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,a=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((r=(r=o.trys).length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]<r[3])){o.label=s[1];break}if(6===s[0]&&o.label<r[1]){o.label=r[1],r=s;break}if(r&&o.label<r[2]){o.label=r[2],o.ops.push(s);break}r[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],a=0}finally{n=r=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},r=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],a=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&a>=e.length&&(e=void 0),{value:e&&e[a++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var s=e("../Base/TreeNode");function o(e,t){var n=this;void 0===e&&(e=[]),t=t||function(e,t){return e<t?-1:e>t?1:0};var o=0,i=new s.default;i.color=s.default.TreeNodeColorType.black,this.size=function(){return o},this.empty=function(){return 0===o},this.clear=function(){o=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,a=0;try{for(var s=r(this),o=s.next();!o.done;o=s.next())e(o.value,a++)}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}},this.getElementByPos=function(e){var t,n;if(e<0||e>=this.size())throw new Error("pos must more than 0 and less than set's size");var a=0;try{for(var s=r(this),o=s.next();!o.done;o=s.next()){var i=o.value;if(a===e)return i;++a}}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}throw new Error("unknown Error")};var d=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value){var a=t(e.key,n);return 0===a?{key:e.key,value:e.value}:a<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 a=t(e.key,n);return 0===a?{key:e.key,value:e.value}:a>0?h(e.leftChild,n):h(e.rightChild,n)||{key:e.key,value:e.value}}};this.reverseLowerBound=function(e){return h(i,e)};var p=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value)return t(e.key,n)>=0?p(e.leftChild,n):p(e.rightChild,n)||{key:e.key,value:e.value}};this.reverseUpperBound=function(e){return p(i,e)};var f=function(e){var t=e.parent;if(!t){if(e===i)return;throw new Error("unknown error")}if(e.color!==s.default.TreeNodeColorType.red){var n=e.brother;if(!n)throw new Error("unknown error");if(e===t.leftChild)if(n.color===s.default.TreeNodeColorType.red){n.color=s.default.TreeNodeColorType.black,t.color=s.default.TreeNodeColorType.red;var a=t.rotateLeft();i===t&&(i=a),f(e)}else n.color===s.default.TreeNodeColorType.black&&(n.rightChild&&n.rightChild.color===s.default.TreeNodeColorType.red?(n.color=t.color,t.color=s.default.TreeNodeColorType.black,n.rightChild&&(n.rightChild.color=s.default.TreeNodeColorType.black),a=t.rotateLeft(),i===t&&(i=a),e.color=s.default.TreeNodeColorType.black):n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||!n.leftChild||n.leftChild.color!==s.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||(n.color=s.default.TreeNodeColorType.red,f(t)):(n.color=s.default.TreeNodeColorType.red,n.leftChild&&(n.leftChild.color=s.default.TreeNodeColorType.black),a=n.rotateRight(),i===n&&(i=a),f(e)));else e===t.rightChild&&(n.color===s.default.TreeNodeColorType.red?(n.color=s.default.TreeNodeColorType.black,t.color=s.default.TreeNodeColorType.red,a=t.rotateRight(),i===t&&(i=a),f(e)):n.color===s.default.TreeNodeColorType.black&&(n.leftChild&&n.leftChild.color===s.default.TreeNodeColorType.red?(n.color=t.color,t.color=s.default.TreeNodeColorType.black,n.leftChild&&(n.leftChild.color=s.default.TreeNodeColorType.black),a=t.rotateRight(),i===t&&(i=a),e.color=s.default.TreeNodeColorType.black):n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||!n.rightChild||n.rightChild.color!==s.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||(n.color=s.default.TreeNodeColorType.red,f(t)):(n.color=s.default.TreeNodeColorType.red,n.rightChild&&(n.rightChild.color=s.default.TreeNodeColorType.black),a=n.rotateLeft(),i===n&&(i=a),f(e))))}else e.color=s.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 a=e.value;e.value=t.value,t.value=a,e=t}t.leftChild&&(t=l(t.leftChild),n=e.key,e.key=t.key,t.key=n,a=e.value,e.value=t.value,t.value=a,e=t)}f(t),t&&t.remove(),--o,i.color=s.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>=o)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 a=t(n,e.key);return a<0?e.leftChild?y(e.leftChild,n):(e.leftChild=new s.default,e.leftChild.parent=e,e.leftChild.brother=e.rightChild,e.rightChild&&(e.rightChild.brother=e.leftChild),e.leftChild):a>0?e.rightChild?y(e.rightChild,n):(e.rightChild=new s.default,e.rightChild.parent=e,e.rightChild.brother=e.leftChild,e.leftChild&&(e.leftChild.brother=e.rightChild),e.rightChild):e},v=function(e){var t=e.parent;if(!t){if(e===i)return;throw new Error("unknown error")}if(t.color!==s.default.TreeNodeColorType.black&&t.color===s.default.TreeNodeColorType.red){var n=t.brother,a=t.parent;if(!a)throw new Error("unknown error");if(n&&n.color===s.default.TreeNodeColorType.red)n.color=t.color=s.default.TreeNodeColorType.black,a.color=s.default.TreeNodeColorType.red,v(a);else if(!n||n.color===s.default.TreeNodeColorType.black)if(t===a.leftChild)if(e===t.leftChild){t.color=s.default.TreeNodeColorType.black,a.color=s.default.TreeNodeColorType.red;var r=a.rotateRight();a===i&&(i=r)}else e===t.rightChild&&(r=t.rotateLeft(),a===i&&(i=r),v(t));else t===a.rightChild&&(e===t.leftChild?(r=t.rotateRight(),a===i&&(i=r),v(t)):e===t.rightChild&&(t.color=s.default.TreeNodeColorType.black,a.color=s.default.TreeNodeColorType.red,r=a.rotateLeft(),a===i&&(i=r)))}};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++o,i.key=e,i.value=n,void(i.color=s.default.TreeNodeColorType.black);var a=y(i,e);void 0===a.key||0!==t(a.key,e)?(++o,a.key=e,a.value=n,v(a),i.color=s.default.TreeNodeColorType.black):a.value=n}else this.eraseElementByKey(e)};var b=function(e,n){if(e&&void 0!==e.key){var a=t(n,e.key);return a<0?b(e.leftChild,n):a>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,a=e.value;return t.setElement(n,a)}))},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 a(this,(function(t){switch(t.label){case 0:return e&&void 0!==e.key&&void 0!==e.value?[5,r(w(e.leftChild))]:[2];case 1:return t.sent(),[4,{key:e.key,value:e.value}];case 2:return t.sent(),[5,r(w(e.rightChild))];case 3:return t.sent(),[2]}}))};this[Symbol.iterator]=function(){return w(i)},e.forEach((function(e){var t=e.key,a=e.value;return n.setElement(t,a)})),Object.freeze(this)}Object.freeze(o),n.default=o},{"../Base/TreeNode":25}],31:[function(e,t,n){function a(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 a=n.length,r=function(e,t){if(e<0||e>=a)throw new Error("unknown error");if(t<0||t>=a)throw new Error("unknown error");var r=n[e];n[e]=n[t],n[t]=r},s=function(e){if(e<0||e>=a)throw new Error("unknown error");var s=2*e+1,o=2*e+2;s<a&&t(n[e],n[s])>0&&r(e,s),o<a&&t(n[e],n[o])>0&&r(e,o)};!function(){for(var e=Math.floor((a-1)/2);e>=0;--e)for(var s=e,o=2*s+1;o<a;){var i=o+1,c=o;if(i<a&&t(n[o],n[i])>0&&(c=i),t(n[s],n[c])<=0)break;r(s,c),o=2*(s=c)+1}}(),this.size=function(){return a},this.empty=function(){return 0===a},this.clear=function(){a=0,n.length=0},this.push=function(e){if(n.push(e),1!=++a)for(var r=a-1;r>0;){var o=Math.floor((r-1)/2);if(t(n[o],e)<=0)break;s(o),r=o}},this.pop=function(){if(!this.empty())if(1!==this.size()){var e=n[a-1];--a;for(var r=0;r<this.size();){var s=2*r+1,o=2*r+2;if(s>=this.size())break;var i=s;if(o<this.size()&&t(n[s],n[o])>0&&(i=o),t(n[i],e)>=0)break;n[r]=n[i],r=i}n[r]=e}else--a},this.top=function(){return n[0]},Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),Object.freeze(a),n.default=a},{}],32:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var a=e("../LinkList/LinkList");function r(e){void 0===e&&(e=[]);var t=new a.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(r),n.default=r},{"../LinkList/LinkList":29}],33:[function(e,t,n){var a=this&&this.__generator||function(e,t){var n,a,r,s,o={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,a&&(r=2&s[0]?a.return:s[0]?a.throw||((r=a.return)&&r.call(a),0):a.next)&&!(r=r.call(a,s[1])).done)return r;switch(a=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,a=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((r=(r=o.trys).length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]<r[3])){o.label=s[1];break}if(6===s[0]&&o.label<r[1]){o.label=r[1],r=s;break}if(r&&o.label<r[2]){o.label=r[2],o.ops.push(s);break}r[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],a=0}finally{n=r=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},r=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],a=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&a>=e.length&&(e=void 0),{value:e&&e[a++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var s=e("../Base/TreeNode");function o(e,t){var n=this;void 0===e&&(e=[]),t=t||function(e,t){return e<t?-1:e>t?1:0};var o=0,i=new s.default;i.color=s.default.TreeNodeColorType.black,this.size=function(){return o},this.empty=function(){return 0===o},this.clear=function(){o=0,i.key=void 0,i.leftChild=i.rightChild=i.brother=i.parent=void 0,i.color=s.default.TreeNodeColorType.black};var c=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.leftChild?c(e.leftChild):e},l=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.rightChild?l(e.rightChild):e};this.front=function(){if(!this.empty())return c(i).key},this.back=function(){if(!this.empty())return l(i).key},this.forEach=function(e){var t,n,a=0;try{for(var s=r(this),o=s.next();!o.done;o=s.next())e(o.value,a++)}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}},this.getElementByPos=function(e){var t,n;if(e<0||e>=this.size())throw new Error("pos must more than 0 and less than set's size");var a=0;try{for(var s=r(this),o=s.next();!o.done;o=s.next()){var i=o.value;if(a===e)return i;++a}}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}throw new Error("unknown error")};var d=function(e){var t=e.parent;if(!t){if(e===i)return;throw new Error("unknown error")}if(e.color!==s.default.TreeNodeColorType.red){var n=e.brother;if(!n)throw new Error("unknown error");if(e===t.leftChild)if(n.color===s.default.TreeNodeColorType.red){n.color=s.default.TreeNodeColorType.black,t.color=s.default.TreeNodeColorType.red;var a=t.rotateLeft();i===t&&(i=a),d(e)}else n.color===s.default.TreeNodeColorType.black&&(n.rightChild&&n.rightChild.color===s.default.TreeNodeColorType.red?(n.color=t.color,t.color=s.default.TreeNodeColorType.black,n.rightChild&&(n.rightChild.color=s.default.TreeNodeColorType.black),a=t.rotateLeft(),i===t&&(i=a),e.color=s.default.TreeNodeColorType.black):n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||!n.leftChild||n.leftChild.color!==s.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||(n.color=s.default.TreeNodeColorType.red,d(t)):(n.color=s.default.TreeNodeColorType.red,n.leftChild&&(n.leftChild.color=s.default.TreeNodeColorType.black),a=n.rotateRight(),i===n&&(i=a),d(e)));else e===t.rightChild&&(n.color===s.default.TreeNodeColorType.red?(n.color=s.default.TreeNodeColorType.black,t.color=s.default.TreeNodeColorType.red,a=t.rotateRight(),i===t&&(i=a),d(e)):n.color===s.default.TreeNodeColorType.black&&(n.leftChild&&n.leftChild.color===s.default.TreeNodeColorType.red?(n.color=t.color,t.color=s.default.TreeNodeColorType.black,n.leftChild&&(n.leftChild.color=s.default.TreeNodeColorType.black),a=t.rotateRight(),i===t&&(i=a),e.color=s.default.TreeNodeColorType.black):n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||!n.rightChild||n.rightChild.color!==s.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||(n.color=s.default.TreeNodeColorType.red,d(t)):(n.color=s.default.TreeNodeColorType.red,n.rightChild&&(n.rightChild.color=s.default.TreeNodeColorType.black),a=n.rotateLeft(),i===n&&(i=a),d(e))))}else e.color=s.default.TreeNodeColorType.black},u=function(e){for(var t=e;t.leftChild||t.rightChild;){if(t.rightChild){t=c(t.rightChild);var n=e.key;e.key=t.key,t.key=n,e=t}t.leftChild&&(t=l(t.leftChild),n=e.key,e.key=t.key,t.key=n,e=t)}d(t),t&&t.remove(),--o,i.color=s.default.TreeNodeColorType.black},h=function(e,t){return!(!e||void 0===e.key)&&(!!h(e.leftChild,t)||!!t(e)||h(e.rightChild,t))};this.eraseElementByPos=function(e){if(e<0||e>=o)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 a=t(n,e.key);return a<0?e.leftChild?p(e.leftChild,n):(e.leftChild=new s.default,e.leftChild.parent=e,e.leftChild.brother=e.rightChild,e.rightChild&&(e.rightChild.brother=e.leftChild),e.leftChild):a>0?e.rightChild?p(e.rightChild,n):(e.rightChild=new s.default,e.rightChild.parent=e,e.rightChild.brother=e.leftChild,e.leftChild&&(e.leftChild.brother=e.rightChild),e.rightChild):e},f=function(e){var t=e.parent;if(!t){if(e===i)return;throw new Error("unknown error")}if(t.color!==s.default.TreeNodeColorType.black&&t.color===s.default.TreeNodeColorType.red){var n=t.brother,a=t.parent;if(!a)throw new Error("unknown error");if(n&&n.color===s.default.TreeNodeColorType.red)n.color=t.color=s.default.TreeNodeColorType.black,a.color=s.default.TreeNodeColorType.red,f(a);else if(!n||n.color===s.default.TreeNodeColorType.black)if(t===a.leftChild)if(e===t.leftChild){t.color=s.default.TreeNodeColorType.black,a.color=s.default.TreeNodeColorType.red;var r=a.rotateRight();a===i&&(i=r)}else e===t.rightChild&&(r=t.rotateLeft(),a===i&&(i=r),f(t));else t===a.rightChild&&(e===t.leftChild?(r=t.rotateRight(),a===i&&(i=r),f(t)):e===t.rightChild&&(t.color=s.default.TreeNodeColorType.black,a.color=s.default.TreeNodeColorType.red,r=a.rotateLeft(),a===i&&(i=r)))}};this.insert=function(e){if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(this.empty())return++o,i.key=e,void(i.color=s.default.TreeNodeColorType.black);var n=p(i,e);void 0!==n.key&&0===t(n.key,e)||(++o,n.key=e,f(n),i.color=s.default.TreeNodeColorType.black)};var m=function(e,n){if(e&&void 0!==e.key){var a=t(n,e.key);return a<0?m(e.leftChild,n):a>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 a=t(e.key,n);if(0===a)return e.key;if(a<0)return g(e.rightChild,n);var r=g(e.leftChild,n);return void 0!==r?r: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 a=y(e.leftChild,n);return void 0!==a?a:e.key}};this.upperBound=function(e){return y(i,e)};var v=function(e,n){if(e&&void 0!==e.key){var a=t(e.key,n);if(0===a)return e.key;if(a>0)return v(e.leftChild,n);var r=v(e.rightChild,n);return void 0!==r?r: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 a=b(e.rightChild,n);return void 0!==a?a: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 a(this,(function(t){switch(t.label){case 0:return e&&void 0!==e.key?[5,r(w(e.leftChild))]:[2];case 1:return t.sent(),[4,e.key];case 2:return t.sent(),[5,r(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(o),n.default=o},{"../Base/TreeNode":25}],34:[function(e,t,n){function a(e){var t=this;void 0===e&&(e=[]);var n=0,a=[];this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){n=0,a.length=0},this.push=function(e){a.push(e),++n},this.pop=function(){a.pop(),n>0&&--n},this.top=function(){return a[n-1]},e.forEach((function(e){return t.push(e)})),Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),Object.freeze(a),n.default=a},{}],35:[function(e,t,n){var a=this&&this.__generator||function(e,t){var n,a,r,s,o={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,a&&(r=2&s[0]?a.return:s[0]?a.throw||((r=a.return)&&r.call(a),0):a.next)&&!(r=r.call(a,s[1])).done)return r;switch(a=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,a=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((r=(r=o.trys).length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]<r[3])){o.label=s[1];break}if(6===s[0]&&o.label<r[1]){o.label=r[1],r=s;break}if(r&&o.label<r[2]){o.label=r[2],o.ops.push(s);break}r[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],a=0}finally{n=r=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},r=this&&this.__read||function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var a,r,s=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(a=s.next()).done;)o.push(a.value)}catch(e){r={error:e}}finally{try{a&&!a.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}return o},s=this&&this.__spreadArray||function(e,t,n){if(n||2===arguments.length)for(var a,r=0,s=t.length;r<s;r++)!a&&r in t||(a||(a=Array.prototype.slice.call(t,0,r)),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))},o=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],a=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&a>=e.length&&(e=void 0),{value:e&&e[a++],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 a=t.length;n>a;)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,a){if(void 0===a&&(a=1),e<0||e>n)throw new Error("pos must more than 0 and less than or equal to vector's size");i.splice.apply(i,s([e,0],r(new Array(a).fill(t)),!1)),n+=a},this.find=function(e){return i.includes(e)},this.reverse=function(){i.reverse()},this.unique=function(){var e,t=[];this.forEach((function(n,a){0!==a&&n===e||(t.push(n),e=n)})),t.forEach((function(e,t){i[t]=e}));for(var a=t.length;n>a;)this.popBack()},this.sort=function(e){i.sort(e)},this[Symbol.iterator]=function(){return function(){return a(this,(function(e){switch(e.label){case 0:return[5,o(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 a=e("./Vector/Vector");n.Vector=a.default;var r=e("./Stack/Stack");n.Stack=r.default;var s=e("./Queue/Queue");n.Queue=s.default;var o=e("./LinkList/LinkList");n.LinkList=o.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 a=e("yallist"),r=Symbol("max"),s=Symbol("length"),o=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[r]=e.max||1/0;const t=e.length||f;if(this[o]="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[r]=e||1/0,v(this)}get max(){return this[r]}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[o]&&(this[o]=e,this[s]=0,this[u].forEach((e=>{e.length=this[o](e.value,e.key),this[s]+=e.length}))),v(this)}get lengthCalculator(){return this[o]}get length(){return this[s]}get itemCount(){return this[u].length}rforEach(e,t){t=t||this;for(let n=this[u].tail;null!==n;){const a=n.prev;I(this,e,n,t),n=a}}forEach(e,t){t=t||this;for(let n=this[u].head;null!==n;){const a=n.next;I(this,e,n,t),n=a}}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 a,this[s]=0}dump(){return this[u].map((e=>!y(this,e)&&{k:e.key,v:e.value,e:e.now+(e.maxAge||0)})).toArray().filter((e=>e))}dumpLru(){return this[u]}set(e,t,n){if((n=n||this[c])&&"number"!=typeof n)throw new TypeError("maxAge must be a number");const a=n?Date.now():0,i=this[o](t,e);if(this[h].has(e)){if(i>this[r])return b(this,this[h].get(e)),!1;const o=this[h].get(e).value;return this[l]&&(this[d]||this[l](e,o.value)),o.now=a,o.maxAge=n,o.value=t,this[s]+=i-o.length,o.length=i,this.get(e),v(this),!0}const p=new w(e,t,i,a,n);return p.length>this[r]?(this[l]&&this[l](e,t),!1):(this[s]+=p.length,this[u].unshift(p),this[h].set(e,this[u].head),v(this),!0)}has(e){if(!this[h].has(e))return!1;const t=this[h].get(e).value;return!y(this,t)}get(e){return 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 a=e[n],r=a.e||0;if(0===r)this.set(a.k,a.v);else{const e=r-t;e>0&&this.set(a.k,a.v,e)}}}prune(){this[h].forEach(((e,t)=>g(this,t,!1)))}}const g=(e,t,n)=>{const a=e[h].get(t);if(a){const t=a.value;if(y(e,t)){if(b(e,a),!e[i])return}else n&&(e[p]&&(a.value.now=Date.now()),e[u].unshiftNode(a));return t.value}},y=(e,t)=>{if(!t||!t.maxAge&&!e[c])return!1;const n=Date.now()-t.now;return t.maxAge?n>t.maxAge:e[c]&&n>e[c]},v=e=>{if(e[s]>e[r])for(let t=e[u].tail;e[s]>e[r]&&null!==t;){const n=t.prev;b(e,t),t=n}},b=(e,t)=>{if(t){const n=t.value;e[l]&&e[l](n.key,n.value),e[s]-=n.length,e[h].delete(n.key),e[u].removeNode(t)}};class w{constructor(e,t,n,a,r){this.key=e,this.value=t,this.length=n,this.now=a,this.maxAge=r||0}}const I=(e,t,n,a)=>{let r=n.value;y(e,r)&&(b(e,n),e[i]||(r=void 0)),r&&t.call(a,r.value,r.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 a(t){return[0,1,2].map((a=>[0,1].map((r=>[0,1].map((s=>{const o=e.alloc(1);return o.writeUInt8(n.codes[t]<<n.CMD_SHIFT|(r?n.DUP_MASK:0)|a<<n.QOS_SHIFT|s,0,!0),o}))))))}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=a("publish"),n.SUBSCRIBE_HEADER=a("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=a("unsubscribe"),n.ACKS={unsuback:a("unsuback"),puback:a("puback"),pubcomp:a("pubcomp"),pubrel:a("pubrel"),pubrec:a("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 a=e("./writeToStream"),r=e("events");function s(e,t){const n=new o;return a(e,n,t),n.concat()}class o extends r{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),a=this._array;let r,s=0;for(r=0;r<a.length&&void 0!==a[r];r++)"string"!=typeof a[r]?t[r]=a[r].length:t[r]=n.byteLength(a[r]),e+=t[r];const o=n.allocUnsafe(e);for(r=0;r<a.length&&void 0!==a[r];r++)"string"!=typeof a[r]?(a[r].copy(o,s),s+=t[r]):(o.write(a[r],s),s+=t[r]);return o}}t.exports=s}).call(this)}).call(this,e("buffer").Buffer)},{"./writeToStream":44,buffer:17,events:22}],40:[function(e,t,n){n.parser=e("./parser").parser,n.generate=e("./generate"),n.writeToStream=e("./writeToStream")},{"./generate":39,"./parser":43,"./writeToStream":44}],41:[function(e,t,n){(function(e){(function(){const n=65536,a={},r=e.isBuffer(e.from([1,2]).subarray(0,1));function s(t){const n=e.allocUnsafe(2);return n.writeUInt8(t>>8,0),n.writeUInt8(255&t,1),n}function o(){for(let e=0;e<n;e++)a[e]=s(e)}function i(t){const n=4;let a=0,s=0;const o=e.allocUnsafe(n);do{a=t%128|0,(t=t/128|0)>0&&(a|=128),o.writeUInt8(a,s++)}while(t>0&&s<n);return t>0&&(s=0),r?o.subarray(0,s):o.slice(0,s)}function c(t){const n=e.allocUnsafe(4);return n.writeUInt32BE(t,0),n}t.exports={cache:a,generateCache:o,generateNumber:s,genBufVariableByteInt:i,generate4ByteBuffer:c}}).call(this)}).call(this,e("buffer").Buffer)},{buffer:17}],42:[function(e,t,n){class a{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}}t.exports=a},{}],43:[function(e,t,n){const a=e("bl"),r=e("events"),s=e("./packet"),o=e("./constants"),i=e("debug")("mqtt-packet:parser");class c extends r{constructor(){super(),this.parser=this.constructor.parser}static parser(e){return this instanceof c?(this.settings=e||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):(new c).parser(e)}_resetState(){i("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new s,this.error=null,this._list=a(),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=o.types[e>>o.CMD_SHIFT],this.packet.retain=0!=(e&o.RETAIN_MASK),this.packet.qos=e>>o.QOS_SHIFT&o.QOS_MASK,this.packet.dup=0!=(e&o.DUP_MASK),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,a;i("_parseConnect");const r={},s=this.packet,c=this._parseString();if(null===c)return this._emitError(new Error("Cannot parse protocolId"));if("MQTT"!==c&&"MQIsdp"!==c)return this._emitError(new Error("Invalid protocolId"));if(s.protocolId=c,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(s.protocolVersion=this._list.readUInt8(this._pos),s.protocolVersion>=128&&(s.bridgeMode=!0,s.protocolVersion=s.protocolVersion-128),3!==s.protocolVersion&&4!==s.protocolVersion&&5!==s.protocolVersion)return this._emitError(new Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(r.username=this._list.readUInt8(this._pos)&o.USERNAME_MASK,r.password=this._list.readUInt8(this._pos)&o.PASSWORD_MASK,r.will=this._list.readUInt8(this._pos)&o.WILL_FLAG_MASK,r.will&&(s.will={},s.will.retain=0!=(this._list.readUInt8(this._pos)&o.WILL_RETAIN_MASK),s.will.qos=(this._list.readUInt8(this._pos)&o.WILL_QOS_MASK)>>o.WILL_QOS_SHIFT),s.clean=0!=(this._list.readUInt8(this._pos)&o.CLEAN_SESSION_MASK),this._pos++,s.keepalive=this._parseNum(),-1===s.keepalive)return this._emitError(new Error("Packet too short"));if(5===s.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(s.properties=e)}const l=this._parseString();if(null===l)return this._emitError(new Error("Packet too short"));if(s.clientId=l,i("_parseConnect: packet.clientId: %s",s.clientId),r.will){if(5===s.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(s.will.properties=e)}if(e=this._parseString(),null===e)return this._emitError(new Error("Cannot parse will topic"));if(s.will.topic=e,i("_parseConnect: packet.will.topic: %s",s.will.topic),t=this._parseBuffer(),null===t)return this._emitError(new Error("Cannot parse will payload"));s.will.payload=t,i("_parseConnect: packet.will.paylaod: %s",s.will.payload)}if(r.username){if(a=this._parseString(),null===a)return this._emitError(new Error("Cannot parse username"));s.username=a,i("_parseConnect: packet.username: %s",s.username)}if(r.password){if(n=this._parseBuffer(),null===n)return this._emitError(new Error("Cannot parse password"));s.password=n}return this.settings=s,i("_parseConnect: complete"),s}_parseConnack(){i("_parseConnack");const e=this.packet;if(this._list.length<1)return null;if(e.sessionPresent=!!(this._list.readUInt8(this._pos++)&o.SESSIONPRESENT_MASK),5===this.settings.protocolVersion)this._list.length>=2?e.reasonCode=this._list.readUInt8(this._pos++):e.reasonCode=0;else{if(this._list.length<2)return null;e.returnCode=this._list.readUInt8(this._pos++)}if(-1===e.returnCode||-1===e.reasonCode)return this._emitError(new Error("Cannot parse return code"));if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}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,a,r,s,c,l;if(1!==e.qos)return this._emitError(new Error("Wrong subscribe header"));if(e.subscriptions=[],this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}for(;this._pos<e.length;){if(t=this._parseString(),null===t)return this._emitError(new Error("Cannot parse topic"));if(this._pos>=e.length)return this._emitError(new Error("Malformed Subscribe Payload"));n=this._parseByte(),a=n&o.SUBSCRIBE_OPTIONS_QOS_MASK,c=0!=(n>>o.SUBSCRIBE_OPTIONS_NL_SHIFT&o.SUBSCRIBE_OPTIONS_NL_MASK),s=0!=(n>>o.SUBSCRIBE_OPTIONS_RAP_SHIFT&o.SUBSCRIBE_OPTIONS_RAP_MASK),r=n>>o.SUBSCRIBE_OPTIONS_RH_SHIFT&o.SUBSCRIBE_OPTIONS_RH_MASK,l={topic:t,qos:a},5===this.settings.protocolVersion?(l.nl=c,l.rap=s,l.rh=r):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 a=this._list.toString("utf8",this._pos,n);return this._pos+=t,i("_parseString: result: %s",a),a}_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,a=0,r=1,s=0,c=!1;const l=this._pos?this._pos:0;for(;a<t&&l+a<this._list.length;){if(n=this._list.readUInt8(l+a++),s+=r*(n&o.VARBYTEINT_MASK),r*=128,0==(n&o.VARBYTEINT_FIN_MASK)){c=!0;break}if(this._list.length<=a)break}return!c&&a===t&&this._list.length>=a&&this._emitError(new Error("Invalid variable byte integer")),l&&(this._pos+=a),c=!!c&&(e?{bytes:a,value:s}:s),i("_parseVarByteNum: result: %o",c),c}_parseByte(){let e;return this._pos<this._list.length&&(e=this._list.readUInt8(this._pos),this._pos++),i("_parseByte: result: %o",e),e}_parseByType(e){switch(i("_parseByType: type: %s",e),e){case"byte":return 0!==this._parseByte();case"int8":return this._parseByte();case"int16":return this._parseNum();case"int32":return this._parse4ByteNum();case"var":return this._parseVarByteNum();case"string":return this._parseString();case"pair":return this._parseStringPair();case"binary":return this._parseBuffer()}}_parseProperties(){i("_parseProperties");const e=this._parseVarByteNum(),t=this._pos+e,n={};for(;this._pos<t;){const e=this._parseByte();if(!e)return this._emitError(new Error("Cannot parse property code type")),!1;const t=o.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(o.propertiesTypes[t]))):n[t]=this._parseByType(o.propertiesTypes[t]);else{n[t]||(n[t]=Object.create(null));const e=this._parseByType(o.propertiesTypes[t]);if(n[t][e.name])if(Array.isArray(n[t][e.name]))n[t][e.name].push(e.value);else{const a=n[t][e.name];n[t][e.name]=[a],n[t][e.name].push(e.value)}else n[t][e.name]=e.value}}return n}_newPacket(){return i("_newPacket"),this.packet&&(this._list.consume(this.packet.length),i("_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d",this.packet.cmd,this.packet.payload,this.packet.length),this.emit("packet",this.packet)),i("_newPacket: new packet"),this.packet=new s,this._pos=0,!0}_emitError(e){i("_emitError"),this.error=e,this.emit("error",e)}}t.exports=c},{"./constants":38,"./packet":42,bl:15,debug:18,events:22}],44:[function(e,t,n){(function(n){(function(){const a=e("./constants"),r=n.allocUnsafe(0),s=n.from([0]),o=e("./numbers"),i=e("process-nextick-args").nextTick,c=e("debug")("mqtt-packet:writeToStream"),l=o.cache,d=o.generateNumber,u=o.generateCache,h=o.genBufVariableByteInt,p=o.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 I(e,t,n);case"subscribe":return C(e,t,n);case"suback":return S(e,t,n);case"unsubscribe":return O(e,t,n);case"unsuback":return T(e,t,n);case"pingreq":case"pingresp":return k(e,t);case"disconnect":return A(e,t,n);case"auth":return _(e,t,n);default:return t.emit("error",new Error("Unknown command")),!1}}function y(e){e.uncork()}function v(e,t,r){const s=e||{},o=s.protocolId||"MQTT";let i=s.protocolVersion||4;const c=s.will;let l=s.clean;const d=s.keepalive||0,u=s.clientId||"",h=s.username,p=s.password,m=s.properties;void 0===l&&(l=!0);let g=0;if(!o||"string"!=typeof o&&!n.isBuffer(o))return t.emit("error",new Error("Invalid protocolId")),!1;if(g+=o.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(a.CONNECT_HEADER),R(t,g),x(t,o),s.bridgeMode&&(i+=128),t.write(131===i?a.VERSION131:132===i?a.VERSION132:4===i?a.VERSION4:5===i?a.VERSION5:a.VERSION3);let w=0;return w|=null!=h?a.USERNAME_MASK:0,w|=null!=p?a.PASSWORD_MASK:0,w|=c&&c.retain?a.WILL_RETAIN_MASK:0,w|=c&&c.qos?c.qos<<a.WILL_QOS_SHIFT:0,w|=c?a.WILL_FLAG_MASK:0,w|=l?a.CLEAN_SESSION_MASK:0,t.write(n.from([w])),f(t,d),5===i&&y.write(),x(t,u),c&&(5===i&&v.write(),P(t,c.topic),x(t,c.payload)),null!=h&&x(t,h),null!=p&&x(t,p),!0}function b(e,t,r){const o=r?r.protocolVersion:4,i=e||{},c=5===o?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===o){if(u=q(t,l),!u)return!1;d+=u.length}return t.write(a.CONNACK_HEADER),R(t,d),t.write(i.sessionPresent?a.SESSIONPRESENT_HEADER:s),t.write(n.from([c])),null!=u&&u.write(),!0}function w(e,t,s){c("publish: packet: %o",e);const o=s?s.protocolVersion:4,i=e||{},l=i.qos||0,d=i.retain?a.RETAIN_MASK:0,u=i.topic,h=i.payload||r,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===o){if(y=q(t,m),!y)return!1;g+=y.length}return t.write(a.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 I(e,t,r){const s=r?r.protocolVersion:4,o=e||{},i=o.cmd||"puback",c=o.messageId,l=o.dup&&"pubrel"===i?a.DUP_MASK:0;let d=0;const u=o.reasonCode,h=o.properties;let p=5===s?3:2;if("pubrel"===i&&(d=1),"number"!=typeof c)return t.emit("error",new Error("Invalid messageId")),!1;let m=null;if(5===s&&"object"==typeof h){if(m=N(t,h,r,p),!m)return!1;p+=m.length}return t.write(a.ACKS[i][d][l][0]),R(t,p),f(t,c),5===s&&t.write(n.from([u])),null!==m&&m.write(),!0}function C(e,t,r){c("subscribe: packet: ");const s=r?r.protocolVersion:4,o=e||{},i=o.dup?a.DUP_MASK:0,l=o.messageId,d=o.subscriptions,u=o.properties;let h=0;if("number"!=typeof l)return t.emit("error",new Error("Invalid messageId")),!1;h+=2;let p=null;if(5===s){if(p=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 a=d[e].topic,r=d[e].qos;if("string"!=typeof a)return t.emit("error",new Error("Invalid subscriptions - invalid topic")),!1;if("number"!=typeof r)return t.emit("error",new Error("Invalid subscriptions - invalid qos")),!1;if(5===s){if("boolean"!=typeof(d[e].nl||!1))return t.emit("error",new Error("Invalid subscriptions - invalid No Local")),!1;if("boolean"!=typeof(d[e].rap||!1))return t.emit("error",new Error("Invalid subscriptions - invalid Retain as Published")),!1;const n=d[e].rh||0;if("number"!=typeof n||n>2)return t.emit("error",new Error("Invalid subscriptions - invalid Retain Handling")),!1}h+=n.byteLength(a)+2+1}c("subscribe: writing to stream: %o",a.SUBSCRIBE_HEADER),t.write(a.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 r=e.topic,o=e.qos,i=+e.nl,c=+e.rap,l=e.rh;let d;P(t,r),d=a.SUBSCRIBE_OPTIONS_QOS[o],5===s&&(d|=i?a.SUBSCRIBE_OPTIONS_NL:0,d|=c?a.SUBSCRIBE_OPTIONS_RAP:0,d|=l?a.SUBSCRIBE_OPTIONS_RH[l]:0),m=t.write(n.from([d]))}return m}function S(e,t,r){const s=r?r.protocolVersion:4,o=e||{},i=o.messageId,c=o.granted,l=o.properties;let d=0;if("number"!=typeof i)return t.emit("error",new Error("Invalid messageId")),!1;if(d+=2,"object"!=typeof c||!c.length)return t.emit("error",new Error("Invalid qos vector")),!1;for(let e=0;e<c.length;e+=1){if("number"!=typeof c[e])return t.emit("error",new Error("Invalid qos vector")),!1;d+=1}let u=null;if(5===s){if(u=N(t,l,r,d),!u)return!1;d+=u.length}return t.write(a.SUBACK_HEADER),R(t,d),f(t,i),null!==u&&u.write(),t.write(n.from(c))}function O(e,t,r){const s=r?r.protocolVersion:4,o=e||{},i=o.messageId,c=o.dup?a.DUP_MASK:0,l=o.unsubscriptions,d=o.properties;let u=0;if("number"!=typeof i)return t.emit("error",new Error("Invalid messageId")),!1;if(u+=2,"object"!=typeof l||!l.length)return t.emit("error",new Error("Invalid unsubscriptions")),!1;for(let e=0;e<l.length;e+=1){if("string"!=typeof l[e])return t.emit("error",new Error("Invalid unsubscriptions")),!1;u+=n.byteLength(l[e])+2}let h=null;if(5===s){if(h=q(t,d),!h)return!1;u+=h.length}t.write(a.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 T(e,t,r){const s=r?r.protocolVersion:4,o=e||{},i=o.messageId,c=o.dup?a.DUP_MASK:0,l=o.granted,d=o.properties,u=o.cmd,h=0;let p=2;if("number"!=typeof i)return t.emit("error",new Error("Invalid messageId")),!1;if(5===s){if("object"!=typeof l||!l.length)return t.emit("error",new Error("Invalid qos vector")),!1;for(let e=0;e<l.length;e+=1){if("number"!=typeof l[e])return t.emit("error",new Error("Invalid qos vector")),!1;p+=1}}let m=null;if(5===s){if(m=N(t,d,r,p),!m)return!1;p+=m.length}return t.write(a.ACKS[u][h][c][0]),R(t,p),f(t,i),null!==m&&m.write(),5===s&&t.write(n.from(l)),!0}function k(e,t,n){return t.write(a.EMPTY[e.cmd])}function A(e,t,r){const s=r?r.protocolVersion:4,o=e||{},i=o.reasonCode,c=o.properties;let l=5===s?1:0,d=null;if(5===s){if(d=N(t,c,r,l),!d)return!1;l+=d.length}return t.write(n.from([a.codes.disconnect<<4])),R(t,l),5===s&&t.write(n.from([i])),null!==d&&d.write(),!0}function _(e,t,r){const s=r?r.protocolVersion:4,o=e||{},i=o.reasonCode,c=o.properties;let l=5===s?1:0;5!==s&&t.emit("error",new Error("Invalid mqtt version for auth packet"));const d=N(t,c,r,l);return!!d&&(l+=d.length,t.write(n.from([a.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 E={};function R(e,t){if(t>a.VARBYTEINT_MAX)return e.emit("error",new Error(`Invalid variable byte integer: ${t}`)),!1;let n=E[t];return n||(n=h(t),t<16384&&(E[t]=n)),c("writeVarByteInt: writing to stream: %o",n),e.write(n)}function P(e,t){const a=n.byteLength(t);return f(e,a),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 D(e,t){const n=p(t);return c("write4ByteNumber: %o",n),e.write(n)}function x(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 r=0;function s(t,r){let s=0;switch(a.propertiesTypes[t]){case"byte":if("boolean"!=typeof r)return e.emit("error",new Error(`Invalid ${t}: ${r}`)),!1;s+=2;break;case"int8":if("number"!=typeof r||r<0||r>255)return e.emit("error",new Error(`Invalid ${t}: ${r}`)),!1;s+=2;break;case"binary":if(r&&null===r)return e.emit("error",new Error(`Invalid ${t}: ${r}`)),!1;s+=1+n.byteLength(r)+2;break;case"int16":if("number"!=typeof r||r<0||r>65535)return e.emit("error",new Error(`Invalid ${t}: ${r}`)),!1;s+=3;break;case"int32":if("number"!=typeof r||r<0||r>4294967295)return e.emit("error",new Error(`Invalid ${t}: ${r}`)),!1;s+=5;break;case"var":if("number"!=typeof r||r<0||r>268435455)return e.emit("error",new Error(`Invalid ${t}: ${r}`)),!1;s+=1+n.byteLength(h(r));break;case"string":if("string"!=typeof r)return e.emit("error",new Error(`Invalid ${t}: ${r}`)),!1;s+=3+n.byteLength(r.toString());break;case"pair":if("object"!=typeof r)return e.emit("error",new Error(`Invalid ${t}: ${r}`)),!1;s+=Object.getOwnPropertyNames(r).reduce(((e,t)=>{const a=r[t];return Array.isArray(a)?e+=a.reduce(((e,a)=>e+=3+n.byteLength(t.toString())+2+n.byteLength(a.toString())),0):e+=3+n.byteLength(t.toString())+2+n.byteLength(r[t].toString()),e}),0);break;default:return e.emit("error",new Error(`Invalid property ${t}: ${r}`)),!1}return s}if(t)for(const e in t){let n=0,a=0;const o=t[e];if(Array.isArray(o))for(let t=0;t<o.length;t++){if(a=s(e,o[t]),!a)return!1;n+=a}else{if(a=s(e,o),!a)return!1;n=a}if(!n)return!1;r+=n}return{length:n.byteLength(h(r))+r,write(){L(e,t,r)}}}function N(e,t,n,a){const r=["reasonString","userProperties"],s=n&&n.properties&&n.properties.maximumPacketSize?n.properties.maximumPacketSize:0;let o=q(e,t);if(s)for(;a+o.length>s;){const n=r.shift();if(!n||!t[n])return!1;delete t[n],o=q(e,t)}return o}function B(e,t,r){switch(a.propertiesTypes[t]){case"byte":e.write(n.from([a.properties[t]])),e.write(n.from([+r]));break;case"int8":e.write(n.from([a.properties[t]])),e.write(n.from([r]));break;case"binary":e.write(n.from([a.properties[t]])),x(e,r);break;case"int16":e.write(n.from([a.properties[t]])),f(e,r);break;case"int32":e.write(n.from([a.properties[t]])),D(e,r);break;case"var":e.write(n.from([a.properties[t]])),R(e,r);break;case"string":e.write(n.from([a.properties[t]])),P(e,r);break;case"pair":Object.getOwnPropertyNames(r).forEach((s=>{const o=r[s];Array.isArray(o)?o.forEach((r=>{e.write(n.from([a.properties[t]])),M(e,s.toString(),r.toString())})):(e.write(n.from([a.properties[t]])),M(e,s.toString(),o.toString()))}));break;default:return e.emit("error",new Error(`Invalid property ${t} value: ${r}`)),!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 a=t[n];if(Array.isArray(a))for(let t=0;t<a.length;t++)B(e,n,a[t]);else B(e,n,a)}}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 a=1e3,r=60*a,s=60*r,o=24*s,i=7*o,c=365.25*o;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*o;case"hours":case"hour":case"hrs":case"hr":case"h":return n*s;case"minutes":case"minute":case"mins":case"min":case"m":return n*r;case"seconds":case"second":case"secs":case"sec":case"s":return n*a;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function d(e){var t=Math.abs(e);return t>=o?Math.round(e/o)+"d":t>=s?Math.round(e/s)+"h":t>=r?Math.round(e/r)+"m":t>=a?Math.round(e/a)+"s":e+"ms"}function u(e){var t=Math.abs(e);return t>=o?h(e,t,o,"day"):t>=s?h(e,t,s,"hour"):t>=r?h(e,t,r,"minute"):t>=a?h(e,t,a,"second"):e+" ms"}function h(e,t,n,a){var r=t>=1.5*n;return Math.round(e/n)+" "+a+(r?"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 a=e("./lib/number-allocator.js");t.exports.NumberAllocator=a},{"./lib/number-allocator.js":47}],47:[function(e,t,n){const a=e("js-sdsl").Set,r=e("debug")("number-allocator:trace"),s=e("debug")("number-allocator:error");function o(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 a([],((e,t)=>e.compare(t))),r("Create"),this.clear()}o.prototype.equals=function(e){return this.low===e.low&&this.high===e.high},o.prototype.compare=function(e){return this.low<e.low&&this.high<e.low?-1:e.low<this.low&&e.high<this.low?1:0},i.prototype.firstVacant=function(){return 0===this.ss.size()?null:this.ss.front().low},i.prototype.alloc=function(){if(0===this.ss.size())return r("alloc():empty"),null;const e=this.ss.front(),t=e.low;return t+1<=e.high?++e.low:this.ss.eraseElementByPos(0),r("alloc():"+t),t},i.prototype.use=function(e){const t=new o(e,e),n=this.ss.lowerBound(t);if(n){if(n.equals(t))return this.ss.eraseElementByValue(n),r("use():"+e),!0;if(n.low>e)return!1;if(n.low===e)return++n.low,r("use():"+e),!0;if(n.high===e)return--n.high,r("use():"+e),!0;const a=n.low;return n.low=e+1,this.ss.insert(new o(a,e-1)),r("use():"+e),!0}return r("use():failed"),!1},i.prototype.free=function(e){if(e<this.min||e>this.max)return void s("free():"+e+" is out of range");const t=new o(e,e),n=this.ss.lowerBound(t);if(n){if(n.low<=e&&e<=n.high)return void s("free():"+e+" has already been vacant");if(n===this.ss.front())e+1===n.low?--n.low:this.ss.insert(t);else{const a=this.ss.reverseLowerBound(t);a.high+1===e?e+1===n.low?(this.ss.eraseElementByValue(a),n.low=a.low):a.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 a=this.ss.reverseLowerBound(t);a.high+1===e?a.high=e:this.ss.insert(t)}r("free():"+e)},i.prototype.clear=function(){r("clear()"),this.ss.clear(),this.ss.insert(new o(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 a=e("wrappy");function r(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function s(e){var t=function(){if(t.called)throw new Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)},n=e.name||"Function wrapped with `once`";return t.onceError=n+" shouldn't be called more than once",t.called=!1,t}t.exports=a(r),t.exports.strict=a(s),r.proto=r((function(){Object.defineProperty(Function.prototype,"once",{value:function(){return r(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return s(this)},configurable:!0})}))},{wrappy:79}],49:[function(e,t,n){(function(e){(function(){function n(t,n,a,r){if("function"!=typeof t)throw new TypeError('"callback" argument must be a function');var s,o,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,a)}));case 4:return e.nextTick((function(){t.call(null,n,a,r)}));default:for(s=new Array(i-1),o=0;o<s.length;)s[o++]=arguments[o];return e.nextTick((function(){t.apply(null,s)}))}}void 0===e||!e.version||0===e.version.indexOf("v0.")||0===e.version.indexOf("v1.")&&0!==e.version.indexOf("v1.8.")?t.exports={nextTick:n}:t.exports=e}).call(this)}).call(this,e("_process"))},{_process:50}],50:[function(e,t,n){var a,r,s=t.exports={};function o(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}function c(e){if(a===setTimeout)return setTimeout(e,0);if((a===o||!a)&&setTimeout)return a=setTimeout,setTimeout(e,0);try{return a(e,0)}catch(t){try{return a.call(null,e,0)}catch(t){return a.call(this,e,0)}}}function l(e){if(r===clearTimeout)return clearTimeout(e);if((r===i||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(e);try{return r(e)}catch(t){try{return r.call(null,e)}catch(t){return r.call(this,e)}}}!function(){try{a="function"==typeof setTimeout?setTimeout:o}catch(e){a=o}try{r="function"==typeof clearTimeout?clearTimeout:i}catch(e){r=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(){}s.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];u.push(new g(e,t)),1!==u.length||h||c(m)},g.prototype.run=function(){this.fun.apply(null,this.array)},s.title="browser",s.browser=!0,s.env={},s.argv=[],s.version="",s.versions={},s.on=y,s.addListener=y,s.once=y,s.off=y,s.removeListener=y,s.removeAllListeners=y,s.emit=y,s.prependListener=y,s.prependOnceListener=y,s.listeners=function(e){return[]},s.binding=function(e){throw new Error("process.binding is not supported")},s.cwd=function(){return"/"},s.chdir=function(e){throw new Error("process.chdir is not supported")},s.umask=function(){return 0}},{}],51:[function(e,t,n){(function(e){(function(){!function(a){var r="object"==typeof n&&n&&!n.nodeType&&n,s="object"==typeof t&&t&&!t.nodeType&&t,o="object"==typeof e&&e;o.global!==o&&o.window!==o&&o.self!==o||(a=o);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,I={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},C=d-u,S=Math.floor,O=String.fromCharCode;function T(e){throw new RangeError(I[e])}function k(e,t){for(var n=e.length,a=[];n--;)a[n]=t(e[n]);return a}function A(e,t){var n=e.split("@"),a="";return n.length>1&&(a=n[0]+"@",e=n[1]),a+k((e=e.replace(w,".")).split("."),t).join(".")}function _(e){for(var t,n,a=[],r=0,s=e.length;r<s;)(t=e.charCodeAt(r++))>=55296&&t<=56319&&r<s?56320==(64512&(n=e.charCodeAt(r++)))?a.push(((1023&t)<<10)+(1023&n)+65536):(a.push(t),r--):a.push(t);return a}function E(e){return k(e,(function(e){var t="";return e>65535&&(t+=O((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=O(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 a=0;for(e=n?S(e/f):e>>1,e+=S(e/t);e>C*h>>1;a+=d)e=S(e/C);return S(a+(C+1)*e/(e+p))}function j(e){var t,n,a,r,s,o,i,c,p,f,v=[],b=e.length,w=0,I=g,C=m;for((n=e.lastIndexOf(y))<0&&(n=0),a=0;a<n;++a)e.charCodeAt(a)>=128&&T("not-basic"),v.push(e.charCodeAt(a));for(r=n>0?n+1:0;r<b;){for(s=w,o=1,i=d;r>=b&&T("invalid-input"),((c=R(e.charCodeAt(r++)))>=d||c>S((l-w)/o))&&T("overflow"),w+=c*o,!(c<(p=i<=C?u:i>=C+h?h:i-C));i+=d)o>S(l/(f=d-p))&&T("overflow"),o*=f;C=M(w-s,t=v.length+1,0==s),S(w/t)>l-I&&T("overflow"),I+=S(w/t),w%=t,v.splice(w++,0,I)}return E(v)}function U(e){var t,n,a,r,s,o,i,c,p,f,v,b,w,I,C,k=[];for(b=(e=_(e)).length,t=g,n=0,s=m,o=0;o<b;++o)(v=e[o])<128&&k.push(O(v));for(a=r=k.length,r&&k.push(y);a<b;){for(i=l,o=0;o<b;++o)(v=e[o])>=t&&v<i&&(i=v);for(i-t>S((l-n)/(w=a+1))&&T("overflow"),n+=(i-t)*w,t=i,o=0;o<b;++o)if((v=e[o])<t&&++n>l&&T("overflow"),v==t){for(c=n,p=d;!(c<(f=p<=s?u:p>=s+h?h:p-s));p+=d)C=c-f,I=d-f,k.push(O(P(f+C%I,0))),c=S(C/I);k.push(O(P(c,0))),s=M(n,w,a==r),n=0,++a}++n,++t}return k.join("")}function D(e){return A(e,(function(e){return v.test(e)?j(e.slice(4).toLowerCase()):e}))}function x(e){return A(e,(function(e){return b.test(e)?"xn--"+U(e):e}))}if(i={version:"1.4.1",ucs2:{decode:_,encode:E},decode:j,encode:U,toASCII:x,toUnicode:D},r&&s)if(t.exports==r)s.exports=i;else for(c in i)i.hasOwnProperty(c)&&(r[c]=i[c]);else a.punycode=i}(this)}).call(this)}).call(this,void 0!==pn?pn:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],52:[function(e,t,n){function a(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.exports=function(e,t,n,s){t=t||"&",n=n||"=";var o={};if("string"!=typeof e||0===e.length)return o;var i=/\+/g;e=e.split(t);var c=1e3;s&&"number"==typeof s.maxKeys&&(c=s.maxKeys);var l=e.length;c>0&&l>c&&(l=c);for(var d=0;d<l;++d){var u,h,p,f,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),a(o,p)?r(o[p])?o[p].push(f):o[p]=[o[p],f]:o[p]=f}return o};var r=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],53:[function(e,t,n){var a=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,n,i){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"==typeof e?s(o(e),(function(o){var i=encodeURIComponent(a(o))+n;return r(e[o])?s(e[o],(function(e){return i+encodeURIComponent(a(e))})).join(t):i+encodeURIComponent(a(e[o]))})).join(t):i?encodeURIComponent(a(i))+n+encodeURIComponent(a(e)):""};var r=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function s(e,t){if(e.map)return e.map(t);for(var n=[],a=0;a<e.length;a++)n.push(t(e[a],a));return n}var o=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 a(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}var r={};function s(e,t,n){function s(e,n,a){return"string"==typeof t?t:t(e,n,a)}n||(n=Error);var o=function(e){function t(t,n,a){return e.call(this,s(t,n,a))||this}return a(t,e),t}(n);o.prototype.name=n.name,o.prototype.code=e,r[e]=o}function o(e,t){if(Array.isArray(e)){var n=e.length;return e=e.map((function(e){return String(e)})),n>2?"one of ".concat(t," ").concat(e.slice(0,n-1).join(", "),", or ")+e[n-1]:2===n?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}function i(e,t,n){return e.substr(!n||n<0?0:+n,t.length)===t}function c(e,t,n){return(void 0===n||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}function l(e,t,n){return"number"!=typeof n&&(n=0),!(n+t.length>e.length)&&-1!==e.indexOf(t,n)}s("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError),s("ERR_INVALID_ARG_TYPE",(function(e,t,n){var a,r;if("string"==typeof t&&i(t,"not ")?(a="must not be",t=t.replace(/^not /,"")):a="must be",c(e," argument"))r="The ".concat(e," ").concat(a," ").concat(o(t,"type"));else{var s=l(e,".")?"property":"argument";r='The "'.concat(e,'" ').concat(s," ").concat(a," ").concat(o(t,"type"))}return r+=". Received type ".concat(typeof n)}),TypeError),s("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),s("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"})),s("ERR_STREAM_PREMATURE_CLOSE","Premature close"),s("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"})),s("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),s("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),s("ERR_STREAM_WRITE_AFTER_END","write after end"),s("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),s("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError),s("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),t.exports.codes=r},{}],56:[function(e,t,n){(function(n){(function(){var a=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=l;var r=e("./_stream_readable"),s=e("./_stream_writable");e("inherits")(l,r);for(var o=a(s.prototype),i=0;i<o.length;i++){var c=o[i];l.prototype[c]||(l.prototype[c]=s.prototype[c])}function l(e){if(!(this instanceof l))return new l(e);r.call(this,e),s.call(this,e),this.allowHalfOpen=!0,e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",d)))}function d(){this._writableState.ended||n.nextTick(u,this)}function u(e){e.end()}Object.defineProperty(l.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(l.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(l.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(l.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&this._readableState.destroyed&&this._writableState.destroyed},set:function(e){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}})}).call(this)}).call(this,e("_process"))},{"./_stream_readable":58,"./_stream_writable":60,_process:50,inherits:24}],57:[function(e,t,n){t.exports=r;var a=e("./_stream_transform");function r(e){if(!(this instanceof r))return new r(e);a.call(this,e)}e("inherits")(r,a),r.prototype._transform=function(e,t,n){n(null,e)}},{"./_stream_transform":59,inherits:24}],58:[function(e,t,n){(function(n,a){(function(){var r;t.exports=_,_.ReadableState=A,e("events").EventEmitter;var s=function(e,t){return e.listeners(t).length},o=e("./internal/streams/stream"),i=e("buffer").Buffer,c=a.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,I=b.ERR_STREAM_PUSH_AFTER_EOF,C=b.ERR_METHOD_NOT_IMPLEMENTED,S=b.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;e("inherits")(_,o);var O=y.errorOrDestroy,T=["error","close","destroy","pause","resume"];function k(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 A(t,n,a){r=r||e("./_stream_duplex"),t=t||{},"boolean"!=typeof a&&(a=n instanceof r),this.objectMode=!!t.objectMode,a&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=v(this,t,"readableHighWaterMark",a),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 _(t){if(r=r||e("./_stream_duplex"),!(this instanceof _))return new _(t);var n=this instanceof r;this._readableState=new A(t,this,n),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),o.call(this)}function E(e,t,n,a,r){u("readableAddChunk",t);var s,o=e._readableState;if(null===t)o.reading=!1,D(e,o);else if(r||(s=P(o,t)),s)O(e,s);else if(o.objectMode||t&&t.length>0)if("string"==typeof t||o.objectMode||Object.getPrototypeOf(t)===i.prototype||(t=l(t)),a)o.endEmitted?O(e,new S):R(e,o,t,!0);else if(o.ended)O(e,new I);else{if(o.destroyed)return!1;o.reading=!1,o.decoder&&!n?(t=o.decoder.write(t),o.objectMode||0!==t.length?R(e,o,t,!1):N(e,o)):R(e,o,t,!1)}else a||(o.reading=!1,N(e,o));return!o.ended&&(o.length<o.highWaterMark||0===o.length)}function R(e,t,n,a){t.flowing&&0===t.length&&!t.sync?(t.awaitDrain=0,e.emit("data",n)):(t.length+=t.objectMode?1:n.length,a?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&x(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(_.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),_.prototype.destroy=y.destroy,_.prototype._undestroy=y.undestroy,_.prototype._destroy=function(e,t){t(e)},_.prototype.push=function(e,t){var n,a=this._readableState;return a.objectMode?n=!0:"string"==typeof e&&((t=t||a.defaultEncoding)!==a.encoding&&(e=i.from(e,t),t=""),n=!0),E(this,e,t,!1,n)},_.prototype.unshift=function(e){return E(this,e,null,!0,!1)},_.prototype.isPaused=function(){return!1===this._readableState.flowing},_.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 a=this._readableState.buffer.head,r="";null!==a;)r+=n.write(a.data),a=a.next;return this._readableState.buffer.clear(),""!==r&&this._readableState.buffer.push(r),this._readableState.length=r.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 D(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?x(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,q(e)))}}function x(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&&s(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,a=e.length;n<a;n++)if(e[n]===t)return n;return-1}_.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):x(this),null;if(0===(e=U(e,t))&&t.ended)return 0===t.length&&H(this),null;var a,r=t.needReadable;return u("need readable",r),(0===t.length||t.length-e<t.highWaterMark)&&u("length less than watermark",r=!0),t.ended||t.reading?u("reading or ended",r=!1):r&&(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===(a=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!==a&&this.emit("data",a),a},_.prototype._read=function(e){O(this,new C("_read()"))},_.prototype.pipe=function(e,t){var a=this,r=this._readableState;switch(r.pipesCount){case 0:r.pipes=e;break;case 1:r.pipes=[r.pipes,e];break;default:r.pipes.push(e)}r.pipesCount+=1,u("pipe count=%d opts=%j",r.pipesCount,t);var o=t&&!1===t.end||e===n.stdout||e===n.stderr?y:c;function i(e,t){u("onunpipe"),e===a&&t&&!1===t.hasUnpiped&&(t.hasUnpiped=!0,h())}function c(){u("onend"),e.end()}r.endEmitted?n.nextTick(o):a.once("end",o),e.on("unpipe",i);var l=L(a);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),a.removeListener("end",c),a.removeListener("end",y),a.removeListener("data",p),d=!0,!r.awaitDrain||e._writableState&&!e._writableState.needDrain||l()}function p(t){u("ondata");var n=e.write(t);u("dest.write",n),!1===n&&((1===r.pipesCount&&r.pipes===e||r.pipesCount>1&&-1!==W(r.pipes,e))&&!d&&(u("false write response, pause",r.awaitDrain),r.awaitDrain++),a.pause())}function f(t){u("onerror",t),y(),e.removeListener("error",f),0===s(e,"error")&&O(e,t)}function m(){e.removeListener("finish",g),y()}function g(){u("onfinish"),e.removeListener("close",m),y()}function y(){u("unpipe"),a.unpipe(e)}return a.on("data",p),k(e,"error",f),e.once("close",m),e.once("finish",g),e.emit("pipe",a),r.flowing||(u("pipe resume"),a.resume()),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 a=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var s=0;s<r;s++)a[s].emit("unpipe",this,{hasUnpiped:!1});return this}var o=W(t.pipes,e);return-1===o||(t.pipes.splice(o,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,n)),this},_.prototype.on=function(e,t){var a=o.prototype.on.call(this,e,t),r=this._readableState;return"data"===e?(r.readableListening=this.listenerCount("readable")>0,!1!==r.flowing&&this.resume()):"readable"===e&&(r.endEmitted||r.readableListening||(r.readableListening=r.needReadable=!0,r.flowing=!1,r.emittedReadable=!1,u("on readable",r.length,r.reading),r.length?x(this):r.reading||n.nextTick(K,this))),a},_.prototype.addListener=_.prototype.on,_.prototype.removeListener=function(e,t){var a=o.prototype.removeListener.call(this,e,t);return"readable"===e&&n.nextTick(F,this),a},_.prototype.removeAllListeners=function(e){var t=o.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||n.nextTick(F,this),t},_.prototype.resume=function(){var e=this._readableState;return e.flowing||(u("resume"),e.flowing=!e.readableListening,$(this,e)),e.paused=!1,this},_.prototype.pause=function(){return u("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(u("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},_.prototype.wrap=function(e){var t=this,n=this._readableState,a=!1;for(var r 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(r){u("wrapped data"),n.decoder&&(r=n.decoder.write(r)),n.objectMode&&null==r||(n.objectMode||r&&r.length)&&(t.push(r)||(a=!0,e.pause()))})),e)void 0===this[r]&&"function"==typeof e[r]&&(this[r]=function(t){return function(){return e[t].apply(e,arguments)}}(r));for(var s=0;s<T.length;s++)e.on(T[s],this.emit.bind(this,T[s]));return this._read=function(t){u("wrapped _read",t),a&&(a=!1,e.resume())},this},"function"==typeof Symbol&&(_.prototype[Symbol.asyncIterator]=function(){return void 0===f&&(f=e("./internal/streams/async_iterator")),f(this)}),Object.defineProperty(_.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(_.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(_.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),_._fromList=V,Object.defineProperty(_.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(_.from=function(t,n){return void 0===m&&(m=e("./internal/streams/from")),m(_,t,n)})}).call(this)}).call(this,e("_process"),void 0!==pn?pn:"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 a=e("../errors").codes,r=a.ERR_METHOD_NOT_IMPLEMENTED,s=a.ERR_MULTIPLE_CALLBACK,o=a.ERR_TRANSFORM_ALREADY_TRANSFORMING,i=a.ERR_TRANSFORM_WITH_LENGTH_0,c=e("./_stream_duplex");function l(e,t){var n=this._transformState;n.transforming=!1;var a=n.writecb;if(null===a)return this.emit("error",new s);n.writechunk=null,n.writecb=null,null!=t&&this.push(t),a(e);var r=this._readableState;r.reading=!1,(r.needReadable||r.length<r.highWaterMark)&&this._read(r.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 o;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 r("_transform()"))},d.prototype._write=function(e,t,n){var a=this._transformState;if(a.writecb=n,a.writechunk=e,a.writeencoding=t,!a.transforming){var r=this._readableState;(a.needTransform||r.needReadable||r.length<r.highWaterMark)&&this._read(r.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,a){(function(){function r(e){var t=this;this.next=null,this.entry=null,this.finish=function(){Q(t,e)}}var s;t.exports=A,A.WritableState=k;var o={deprecate:e("util-deprecate")},i=e("./internal/streams/stream"),c=e("buffer").Buffer,l=a.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,I=m.ERR_STREAM_NULL_VALUES,C=m.ERR_STREAM_WRITE_AFTER_END,S=m.ERR_UNKNOWN_ENCODING,O=p.errorOrDestroy;function T(){}function k(t,n,a){s=s||e("./_stream_duplex"),t=t||{},"boolean"!=typeof a&&(a=n instanceof s),this.objectMode=!!t.objectMode,a&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=f(this,t,"writableHighWaterMark",a),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var o=!1===t.decodeStrings;this.decodeStrings=!o,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){D(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 r(this)}function A(t){var n=this instanceof(s=s||e("./_stream_duplex"));if(!n&&!h.call(A,this))return new A(t);this._writableState=new k(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,t){var a=new C;O(e,a),n.nextTick(t,a)}function E(e,t,a,r){var s;return null===a?s=new I:"string"==typeof a||t.objectMode||(s=new g("chunk",["string","Buffer"],a)),!s||(O(e,s),n.nextTick(r,s),!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,a,r,s){if(!n){var o=R(t,a,r);a!==o&&(n=!0,r="buffer",a=o)}var i=t.objectMode?1:a.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:a,encoding:r,isBuf:n,callback:s,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else M(e,t,!1,i,a,r,s);return c}function M(e,t,n,a,r,s,o){t.writelen=a,t.writecb=o,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new w("write")):n?e._writev(r,t.onwrite):e._write(r,s,t.onwrite),t.sync=!1}function j(e,t,a,r,s){--t.pendingcb,a?(n.nextTick(s,r),n.nextTick(K,e,t),e._writableState.errorEmitted=!0,O(e,r)):(s(r),e._writableState.errorEmitted=!0,O(e,r),K(e,t))}function U(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function D(e,t){var a=e._writableState,r=a.sync,s=a.writecb;if("function"!=typeof s)throw new v;if(U(a),t)j(e,a,r,t,s);else{var o=B(a)||e.destroyed;o||a.corked||a.bufferProcessing||!a.bufferedRequest||N(e,a),r?n.nextTick(x,e,a,o,s):x(e,a,o,s)}}function x(e,t,n,a){n||q(e,t),t.pendingcb--,a(),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 a=t.bufferedRequestCount,s=new Array(a),o=t.corkedRequestsFree;o.entry=n;for(var i=0,c=!0;n;)s[i]=n,n.isBuf||(c=!1),n=n.next,i+=1;s.allBuffers=c,M(e,t,!0,t.length,s,"",o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new r(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&&O(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 a=e._readableState;(!a||a.autoDestroy&&a.endEmitted)&&e.destroy()}return n}function $(e,t,a){t.ending=!0,K(e,t),a&&(t.finished?n.nextTick(a):e.once("finish",a)),t.ended=!0,e.writable=!1}function Q(e,t,n){var a=e.entry;for(e.entry=null;a;){var r=a.callback;t.pendingcb--,r(n),a=a.next}t.corkedRequestsFree.next=e}e("inherits")(A,i),k.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(k.prototype,"buffer",{get:o.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(h=Function.prototype[Symbol.hasInstance],Object.defineProperty(A,Symbol.hasInstance,{value:function(e){return!!h.call(this,e)||this===A&&e&&e._writableState instanceof k}})):h=function(e){return e instanceof this},A.prototype.pipe=function(){O(this,new b)},A.prototype.write=function(e,t,n){var a=this._writableState,r=!1,s=!a.objectMode&&u(e);return s&&!c.isBuffer(e)&&(e=d(e)),"function"==typeof t&&(n=t,t=null),s?t="buffer":t||(t=a.defaultEncoding),"function"!=typeof n&&(n=T),a.ending?_(this,n):(s||E(this,a,e,n))&&(a.pendingcb++,r=P(this,a,s,e,t,n)),r},A.prototype.cork=function(){this._writableState.corked++},A.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.bufferProcessing||!e.bufferedRequest||N(this,e))},A.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(A.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(A.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),A.prototype._write=function(e,t,n){n(new y("_write()"))},A.prototype._writev=null,A.prototype.end=function(e,t,n){var a=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),a.corked&&(a.corked=1,this.uncork()),a.ending||$(this,a,n),this},Object.defineProperty(A.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(A.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),A.prototype.destroy=p.destroy,A.prototype._undestroy=p.undestroy,A.prototype._destroy=function(e,t){t(e)}}).call(this)}).call(this,e("_process"),void 0!==pn?pn:"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 a;function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var s=e("./end-of-stream"),o=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[o];if(null!==t){var n=e[h].read();null!==n&&(e[d]=null,e[o]=null,e[i]=null,t(p(n,!1)))}}function m(e){n.nextTick(f,e)}function g(e,t){return function(n,a){e.then((function(){t[l]?n(p(void 0,!0)):t[u](n,a)}),a)}}var y=Object.getPrototypeOf((function(){})),v=Object.setPrototypeOf((r(a={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,a){n.nextTick((function(){e[c]?a(e[c]):t(p(void 0,!0))}))}));var a,r=this[d];if(r)a=new Promise(g(r,this));else{var s=this[h].read();if(null!==s)return Promise.resolve(p(s,!1));a=new Promise(this[u])}return this[d]=a,a}},Symbol.asyncIterator,(function(){return this})),r(a,"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))}))}))})),a),y),b=function(e){var t,n=Object.create(v,(r(t={},h,{value:e,writable:!0}),r(t,o,{value:null,writable:!0}),r(t,i,{value:null,writable:!0}),r(t,c,{value:null,writable:!0}),r(t,l,{value:e._readableState.endEmitted,writable:!0}),r(t,u,{value:function(e,t){var a=n[h].read();a?(n[d]=null,n[o]=null,n[i]=null,e(p(a,!1))):(n[o]=e,n[i]=t)},writable:!0}),t));return n[d]=null,s(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=n[i];return null!==t&&(n[d]=null,n[o]=null,n[i]=null,t(e)),void(n[c]=e)}var a=n[o];null!==a&&(n[d]=null,n[o]=null,n[i]=null,a(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 a(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,a)}return n}function r(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?a(Object(n),!0).forEach((function(t){s(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):a(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(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 a=t[n];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(e,a.key,a)}}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(){o(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,a=0;n;)h(n.data,t,a),a+=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,a=t.data;for(e-=a.length;t=t.next;){var r=t.data,s=e>r.length?r.length:e;if(s===r.length?a+=r:a+=r.slice(0,e),0==(e-=s)){s===r.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=r.slice(s));break}++n}return this.length-=n,a}},{key:"_getBuffer",value:function(e){var t=l.allocUnsafe(e),n=this.head,a=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var r=n.data,s=e>r.length?r.length:e;if(r.copy(t,t.length-e,0,s),0==(e-=s)){s===r.length?(++a,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=r.slice(s));break}++a}return this.length-=a,t}},{key:u,value:function(e,t){return d(this,r({},t,{depth:0,customInspect:!1}))}}]),e}()},{buffer:17,util:16}],63:[function(e,t,n){(function(e){(function(){function n(t,n){var s=this,i=this._readableState&&this._readableState.destroyed,c=this._writableState&&this._writableState.destroyed;return i||c?(n?n(t):t&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,e.nextTick(o,this,t)):e.nextTick(o,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,(function(t){!n&&t?s._writableState?s._writableState.errorEmitted?e.nextTick(r,s):(s._writableState.errorEmitted=!0,e.nextTick(a,s,t)):e.nextTick(a,s,t):n?(e.nextTick(r,s),n(t)):e.nextTick(r,s)})),this)}function a(e,t){o(e,t),r(e)}function r(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function s(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function o(e,t){e.emit("error",t)}function i(e,t){var n=e._readableState,a=e._writableState;n&&n.autoDestroy||a&&a.autoDestroy?e.destroy(t):e.emit("error",t)}t.exports={destroy:n,undestroy:s,errorOrDestroy:i}}).call(this)}).call(this,e("_process"))},{_process:50}],64:[function(e,t,n){var a=e("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;function r(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,a=new Array(n),r=0;r<n;r++)a[r]=arguments[r];e.apply(this,a)}}}function s(){}function o(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=r(n||s);var c=t.readable||!1!==t.readable&&e.readable,l=t.writable||!1!==t.writable&&e.writable,d=function(){e.writable||h()},u=e._writableState&&e._writableState.finished,h=function(){l=!1,u=!0,c||n.call(e)},p=e._readableState&&e._readableState.endEmitted,f=function(){c=!1,p=!0,l||n.call(e)},m=function(t){n.call(e,t)},g=function(){var t;return c&&!p?(e._readableState&&e._readableState.ended||(t=new a),n.call(e,t)):l&&!u?(e._writableState&&e._writableState.ended||(t=new a),n.call(e,t)):void 0},y=function(){e.req.on("finish",h)};return o(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 a;function r(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var s=e("../../../errors").codes,o=s.ERR_MISSING_ARGS,i=s.ERR_STREAM_DESTROYED;function c(e){if(e)throw e}function l(e){return e.setHeader&&"function"==typeof e.abort}function d(t,n,s,o){o=r(o);var c=!1;t.on("close",(function(){c=!0})),void 0===a&&(a=e("./end-of-stream")),a(t,{readable:n,writable:s},(function(e){if(e)return o(e);c=!0,o()}));var d=!1;return function(e){if(!c&&!d)return d=!0,l(t)?t.abort():"function"==typeof t.destroy?t.destroy():void o(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 a,r=p(t);if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new o("streams");var s=t.map((function(e,n){var o=n<t.length-1;return d(e,o,n>0,(function(e){a||(a=e),e&&s.forEach(u),o||(s.forEach(u),r(a))}))}));return t.reduce(h)}t.exports=f},{"../../../errors":55,"./end-of-stream":64}],67:[function(e,t,n){var a=e("../../../errors").codes.ERR_INVALID_OPT_VALUE;function r(e,t,n){return null!=e.highWaterMark?e.highWaterMark:t?e[n]:null}function s(e,t,n,s){var o=r(t,s,n);if(null!=o){if(!isFinite(o)||Math.floor(o)!==o||o<0)throw new a(s?n:"highWaterMark",o);return Math.floor(o)}return e.objectMode?16:16384}t.exports={getHighWaterMark:s}},{"../../../errors":55}],68:[function(e,t,n){t.exports=e("events").EventEmitter},{events:22}],69:[function(e,t,n){(n=t.exports=e("./lib/_stream_readable.js")).Stream=n,n.Readable=n,n.Writable=e("./lib/_stream_writable.js"),n.Duplex=e("./lib/_stream_duplex.js"),n.Transform=e("./lib/_stream_transform.js"),n.PassThrough=e("./lib/_stream_passthrough.js"),n.finished=e("./lib/internal/streams/end-of-stream.js"),n.pipeline=e("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":56,"./lib/_stream_passthrough.js":57,"./lib/_stream_readable.js":58,"./lib/_stream_transform.js":59,"./lib/_stream_writable.js":60,"./lib/internal/streams/end-of-stream.js":64,"./lib/internal/streams/pipeline.js":66}],70:[function(e,t,n){function a(e,t,n){var a=this;this._callback=e,this._args=n,this._interval=setInterval(e,t,this._args),this.reschedule=function(e){e||(e=a._interval),a._interval&&clearInterval(a._interval),a._interval=setInterval(a._callback,e,a._args)},this.clear=function(){a._interval&&(clearInterval(a._interval),a._interval=void 0)},this.destroy=function(){a._interval&&clearInterval(a._interval),a._callback=void 0,a._interval=void 0,a._args=void 0}}function r(){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 a(arguments[0],arguments[1],e)}t.exports=r},{}],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 a(e){return(e=e||{}).circles?r(e):e.proto?s:a;function t(e,t){for(var a=Object.keys(e),r=new Array(a.length),s=0;s<a.length;s++){var o=a[s],i=e[o];"object"!=typeof i||null===i?r[o]=i:i instanceof Date?r[o]=new Date(i):ArrayBuffer.isView(i)?r[o]=n(i):r[o]=t(i)}return r}function a(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return t(e,a);if(e instanceof Map)return new Map(t(Array.from(e),a));if(e instanceof Set)return new Set(t(Array.from(e),a));var r={};for(var s in e)if(!1!==Object.hasOwnProperty.call(e,s)){var o=e[s];"object"!=typeof o||null===o?r[s]=o:o instanceof Date?r[s]=new Date(o):o instanceof Map?r[s]=new Map(t(Array.from(o),a)):o instanceof Set?r[s]=new Set(t(Array.from(o),a)):ArrayBuffer.isView(o)?r[s]=n(o):r[s]=a(o)}return r}function s(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return t(e,s);if(e instanceof Map)return new Map(t(Array.from(e),s));if(e instanceof Set)return new Set(t(Array.from(e),s));var a={};for(var r in e){var o=e[r];"object"!=typeof o||null===o?a[r]=o:o instanceof Date?a[r]=new Date(o):o instanceof Map?a[r]=new Map(t(Array.from(o),s)):o instanceof Set?a[r]=new Set(t(Array.from(o),s)):ArrayBuffer.isView(o)?a[r]=n(o):a[r]=s(o)}return a}}function r(e){var t=[],a=[];return e.proto?o:s;function r(e,r){for(var s=Object.keys(e),o=new Array(s.length),i=0;i<s.length;i++){var c=s[i],l=e[c];if("object"!=typeof l||null===l)o[c]=l;else if(l instanceof Date)o[c]=new Date(l);else if(ArrayBuffer.isView(l))o[c]=n(l);else{var d=t.indexOf(l);o[c]=-1!==d?a[d]:r(l)}}return o}function s(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return r(e,s);if(e instanceof Map)return new Map(r(Array.from(e),s));if(e instanceof Set)return new Set(r(Array.from(e),s));var o={};for(var i in t.push(e),a.push(o),e)if(!1!==Object.hasOwnProperty.call(e,i)){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(r(Array.from(c),s));else if(c instanceof Set)o[i]=new Set(r(Array.from(c),s));else if(ArrayBuffer.isView(c))o[i]=n(c);else{var l=t.indexOf(c);o[i]=-1!==l?a[l]:s(c)}}return t.pop(),a.pop(),o}function o(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return r(e,o);if(e instanceof Map)return new Map(r(Array.from(e),o));if(e instanceof Set)return new Set(r(Array.from(e),o));var s={};for(var i in t.push(e),a.push(s),e){var c=e[i];if("object"!=typeof c||null===c)s[i]=c;else if(c instanceof Date)s[i]=new Date(c);else if(c instanceof Map)s[i]=new Map(r(Array.from(c),o));else if(c instanceof Set)s[i]=new Set(r(Array.from(c),o));else if(ArrayBuffer.isView(c))s[i]=n(c);else{var l=t.indexOf(c);s[i]=-1!==l?a[l]:o(c)}}return t.pop(),a.pop(),s}}t.exports=a}).call(this)}).call(this,e("buffer").Buffer)},{buffer:17}],73:[function(e,t,n){
|
|
3
|
+
n.read=function(e,t,n,a,r){var s,o,i=8*r-a-1,c=(1<<i)-1,l=c>>1,d=-7,u=n?r-1:0,h=n?-1:1,p=e[t+u];for(u+=h,s=p&(1<<-d)-1,p>>=-d,d+=i;d>0;s=256*s+e[t+u],u+=h,d-=8);for(o=s&(1<<-d)-1,s>>=-d,d+=a;d>0;o=256*o+e[t+u],u+=h,d-=8);if(0===s)s=1-l;else{if(s===c)return o?NaN:1/0*(p?-1:1);o+=Math.pow(2,a),s-=l}return(p?-1:1)*o*Math.pow(2,s-a)},n.write=function(e,t,n,a,r,s){var o,i,c,l=8*s-r-1,d=(1<<l)-1,u=d>>1,h=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,p=a?0:s-1,f=a?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,o=d):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-o))<1&&(o--,c*=2),(t+=o+u>=1?h/c:h*Math.pow(2,1-u))*c>=2&&(o++,c/=2),o+u>=d?(i=0,o=d):o+u>=1?(i=(t*c-1)*Math.pow(2,r),o+=u):(i=t*Math.pow(2,u-1)*Math.pow(2,r),o=0));r>=8;e[n+p]=255&i,p+=f,i/=256,r-=8);for(o=o<<r|i,l+=r;l>0;e[n+p]=255&o,p+=f,o/=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 a=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,a=this.rightChild;if(!a)throw new Error("unknown error");var r=a.leftChild,s=a.rightChild;return e&&(e.leftChild===this?e.leftChild=a:e.rightChild===this&&(e.rightChild=a)),a.parent=e,a.brother=t,a.leftChild=this,a.rightChild=s,t&&(t.brother=a),this.parent=a,this.brother=s,this.leftChild=n,this.rightChild=r,s&&(s.parent=a,s.brother=this),n&&(n.parent=this,n.brother=r),r&&(r.parent=this,r.brother=n),a},e.prototype.rotateRight=function(){var e=this.parent,t=this.brother,n=this.leftChild;if(!n)throw new Error("unknown error");var a=this.rightChild,r=n.leftChild,s=n.rightChild;return e&&(e.leftChild===this?e.leftChild=n:e.rightChild===this&&(e.rightChild=n)),n.parent=e,n.brother=t,n.leftChild=r,n.rightChild=this,t&&(t.brother=n),r&&(r.parent=n,r.brother=this),this.parent=n,this.brother=r,this.leftChild=s,this.rightChild=a,s&&(s.parent=this,s.brother=a),a&&(a.parent=this,a.brother=s),n},e.prototype.remove=function(){if(this.leftChild||this.rightChild)throw new Error("can only remove leaf node");this.parent&&(this===this.parent.leftChild?this.parent.leftChild=void 0:this===this.parent.rightChild&&(this.parent.rightChild=void 0)),this.brother&&(this.brother.brother=void 0),this.key=void 0,this.value=void 0,this.parent=void 0,this.brother=void 0},e.TreeNodeColorType={red:!0,black:!1},e}();Object.freeze(a),n.default=a},{}],26:[function(e,t,n){var a=this&&this.__generator||function(e,t){var n,a,r,s,o={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,a&&(r=2&s[0]?a.return:s[0]?a.throw||((r=a.return)&&r.call(a),0):a.next)&&!(r=r.call(a,s[1])).done)return r;switch(a=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,a=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((r=(r=o.trys).length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]<r[3])){o.label=s[1];break}if(6===s[0]&&o.label<r[1]){o.label=r[1],r=s;break}if(r&&o.label<r[2]){o.label=r[2],o.ops.push(s);break}r[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],a=0}finally{n=r=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}};function r(e){var t=this;void 0===e&&(e=[]);var n=[],s=0,o=0,i=0,c=0,l=0,d=0;this.size=function(){return d},this.empty=function(){return 0===d},this.clear=function(){s=i=o=c=l=d=0,h.call(this,r.bucketSize),d=0},this.front=function(){return n[s][o]},this.back=function(){return n[i][c]},this.forEach=function(e){if(!this.empty()){var t=0;if(s!==i){for(l=o;l<r.bucketSize;++l)e(n[s][l],t++);for(l=s+1;l<i;++l)for(var a=0;a<r.bucketSize;++a)e(n[l][a],t++);for(l=0;l<=c;++l)e(n[i][l],t++)}else for(var l=o;l<=c;++l)e(n[s][l],t++)}};var u=function(e){var t=s*r.bucketSize+o,n=t+e,a=i*r.bucketSize+c;if(n<t||n>a)throw new Error("pos should more than 0 and less than queue's size");return{curNodeBucketIndex:Math.floor(n/r.bucketSize),curNodePointerIndex:n%r.bucketSize}};this.getElementByPos=function(e){var t=u(e),a=t.curNodeBucketIndex,r=t.curNodePointerIndex;return n[a][r]},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=[],a=e+1;a<d;++a)n.push(this.getElementByPos(a));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,a=0;a<n;++a)this.setElementByPos(a,t[a]);this.cut(n-1)}};var h=function(e){for(var t=[],a=e*r.sigma,u=Math.max(Math.ceil(a/r.bucketSize),2),h=0;h<u;++h)t.push(new Array(r.bucketSize));var p=Math.ceil(e/r.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<r.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,s=f,o=0,i=m,c=g,l=u,d=e};this.pushBack=function(e){this.empty()||(i===l-1&&c===r.bucketSize-1&&h.call(this,this.size()),c<r.bucketSize-1?++c:i<l-1&&(++i,c=0)),++d,n[i][c]=e},this.popBack=function(){this.empty()||(1!==this.size()&&(c>0?--c:s<i&&(--i,c=r.bucketSize-1)),d>0&&--d)},this.setElementByPos=function(e,t){var a=u(e),r=a.curNodeBucketIndex,s=a.curNodePointerIndex;n[r][s]=t},this.insert=function(e,t,n){var a=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 r=[],s=e;s<d;++s)r.push(this.getElementByPos(s));for(this.cut(e-1),s=0;s<n;++s)this.pushBack(t);r.forEach((function(e){return a.pushBack(e)}))}},this.find=function(e){if(s===i){for(var t=o;t<=c;++t)if(n[s][t]===e)return!0;return!1}for(t=o;t<r.bucketSize;++t)if(n[s][t]===e)return!0;for(t=s+1;t<i;++t)for(var a=0;a<r.bucketSize;++a)if(n[t][a]===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,a){0!==a&&n===t||(e.push(n),t=n)}));for(var n=0;n<d;++n)this.setElementByPos(n,e[n]);this.cut(e.length-1)}},this.sort=function(e){var t=[];this.forEach((function(e){t.push(e)})),t.sort(e);for(var n=0;n<d;++n)this.setElementByPos(n,t[n])},this.pushFront=function(e){this.empty()||(0===s&&0===o&&h.call(this,this.size()),o>0?--o:s>0&&(--s,o=r.bucketSize-1)),++d,n[s][o]=e},this.popFront=function(){this.empty()||(1!==this.size()&&(o<r.bucketSize-1?++o:s<i&&(++s,o=0)),d>0&&--d)},this.shrinkToFit=function(){var e=this,t=[];this.forEach((function(e){t.push(e)}));var a=t.length;n=[];for(var s=Math.ceil(a/r.bucketSize),o=0;o<s;++o)n.push(new Array(r.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,a=t.curNodePointerIndex;i=n,c=a,d=e+1}},this[Symbol.iterator]=function(){return function(){var e,t;return a(this,(function(a){switch(a.label){case 0:if(0===d)return[2];if(s!==i)return[3,5];t=o,a.label=1;case 1:return t<=c?[4,n[s][t]]:[3,4];case 2:a.sent(),a.label=3;case 3:return++t,[3,1];case 4:return[2];case 5:t=o,a.label=6;case 6:return t<r.bucketSize?[4,n[s][t]]:[3,9];case 7:a.sent(),a.label=8;case 8:return++t,[3,6];case 9:t=s+1,a.label=10;case 10:if(!(t<i))return[3,15];e=0,a.label=11;case 11:return e<r.bucketSize?[4,n[t][e]]:[3,14];case 12:a.sent(),a.label=13;case 13:return++e,[3,11];case 14:return++t,[3,10];case 15:t=0,a.label=16;case 16:return t<=c?[4,n[i][t]]:[3,19];case 17:a.sent(),a.label=18;case 18:return++t,[3,16];case 19:return[2]}}))}()},function(){var a=r.bucketSize;e.size?a=e.size():e.length&&(a=e.length);var o=a*r.sigma;l=Math.ceil(o/r.bucketSize),l=Math.max(l,3);for(var c=0;c<l;++c)n.push(new Array(r.bucketSize));var d=Math.ceil(a/r.bucketSize);s=Math.floor(l/2)-Math.floor(d/2),i=s,e.forEach((function(e){return t.pushBack(e)}))}(),Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),r.sigma=3,r.bucketSize=5e3,Object.freeze(r),n.default=r},{}],27:[function(e,t,n){var a=this&&this.__generator||function(e,t){var n,a,r,s,o={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,a&&(r=2&s[0]?a.return:s[0]?a.throw||((r=a.return)&&r.call(a),0):a.next)&&!(r=r.call(a,s[1])).done)return r;switch(a=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,a=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((r=(r=o.trys).length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]<r[3])){o.label=s[1];break}if(6===s[0]&&o.label<r[1]){o.label=r[1],r=s;break}if(r&&o.label<r[2]){o.label=r[2],o.ops.push(s);break}r[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],a=0}finally{n=r=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},r=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],a=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&a>=e.length&&(e=void 0),{value:e&&e[a++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var s=e("../LinkList/LinkList"),o=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,a=0,s="";if("number"==typeof e)a=((a=Math.floor(e))<<5)-a,a&=a;else{s="string"!=typeof e?JSON.stringify(e):e;try{for(var o=r(s),i=o.next();!i.done;i=o.next())a=(a<<5)-a+i.value.charCodeAt(0),a&=a}catch(e){t={error:e}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}}return a^=a>>>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(a,r){if(!a.empty()){if(a instanceof s.default&&1===a.size()){var c=a.front(),l=c.key,h=c.value;t[n(l)&u-1]=new s.default([{key:l,value:h}])}else if(a instanceof o.default){var p=new s.default,f=new s.default;a.forEach((function(t){0==(n(t.key)&e)?p.pushBack(t):f.pushBack(t)})),p.size()>i.untreeifyThreshold?t[r]=new o.default(p):p.size()&&(t[r]=p),f.size()>i.untreeifyThreshold?t[r+e]=new o.default(f):f.size()&&(t[r+e]=f)}else{var m=new s.default,g=new s.default;a.forEach((function(t){0==(n(t.key)&e)?m.pushBack(t):g.pushBack(t)})),m.size()&&(t[r]=m),g.size()&&(t[r+e]=g)}d[r].clear()}})),d=t}};this.setElement=function(e,t){var a,c;if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(null!=t){var p=n(e)&u-1;if(d[p]){var f=d[p].size();if(d[p]instanceof s.default){try{for(var m=r(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){a={error:e}}finally{try{g&&!g.done&&(c=m.return)&&c.call(m)}finally{if(a)throw a.error}}d[p].pushBack({key:e,value:t}),d[p].size()>=i.treeifyThreshold&&(d[p]=new o.default(d[p]))}else d[p].setElement(e,t);var v=d[p].size();l+=v-f}else++l,d[p]=new s.default([{key:e,value:t}]);l>u*i.sigma&&h.call(this,u)}else this.eraseElementByKey(e)},this.getElementByKey=function(e){var t,a,s=n(e)&u-1;if(d[s]){if(d[s]instanceof o.default)return d[s].getElementByKey(e);try{for(var i=r(d[s]),c=i.next();!c.done;c=i.next()){var l=c.value;if(l.key===e)return l.value}}catch(e){t={error:e}}finally{try{c&&!c.done&&(a=i.return)&&a.call(i)}finally{if(t)throw t.error}}}},this.eraseElementByKey=function(e){var t,a,c=n(e)&u-1;if(d[c]){var h=d[c].size();if(d[c]instanceof o.default)d[c].eraseElementByKey(e),d[c].size()<=i.untreeifyThreshold&&(d[c]=new s.default(d[c]));else{var p=-1;try{for(var f=r(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&&(a=f.return)&&a.call(f)}finally{if(t)throw t.error}}}var y=d[c].size();l+=y-h}},this.find=function(e){var t,a,s=n(e)&u-1;if(!d[s])return!1;if(d[s]instanceof o.default)return d[s].find(e);try{for(var i=r(d[s]),c=i.next();!c.done;c=i.next())if(c.value.key===e)return!0}catch(e){t={error:e}}finally{try{c&&!c.done&&(a=i.return)&&a.call(i)}finally{if(t)throw t.error}}return!1},this[Symbol.iterator]=function(){return function(){var e,t,n,s,o,i;return a(this,(function(a){switch(a.label){case 0:e=0,a.label=1;case 1:if(!(e<u))return[3,10];for(;e<u&&!d[e];)++e;if(e>=u)return[3,10];a.label=2;case 2:a.trys.push([2,7,8,9]),o=void 0,t=r(d[e]),n=t.next(),a.label=3;case 3:return n.done?[3,6]:[4,n.value];case 4:a.sent(),a.label=5;case 5:return n=t.next(),[3,3];case 6:return[3,9];case 7:return s=a.sent(),o={error:s},[3,9];case 8:try{n&&!n.done&&(i=t.return)&&i.call(t)}finally{if(o)throw o.error}return[7];case 9:return++e,[3,1];case 10:return[2]}}))}()},e.forEach((function(e){var t=e.key,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 a=this&&this.__generator||function(e,t){var n,a,r,s,o={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,a&&(r=2&s[0]?a.return:s[0]?a.throw||((r=a.return)&&r.call(a),0):a.next)&&!(r=r.call(a,s[1])).done)return r;switch(a=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,a=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((r=(r=o.trys).length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]<r[3])){o.label=s[1];break}if(6===s[0]&&o.label<r[1]){o.label=r[1],r=s;break}if(r&&o.label<r[2]){o.label=r[2],o.ops.push(s);break}r[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],a=0}finally{n=r=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},r=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],a=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&a>=e.length&&(e=void 0),{value:e&&e[a++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var s=e("../Set/Set"),o=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 a=0;a<n.length;a++)t=(t<<5)-t+n.charCodeAt(a),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(a,r){if(!a.empty()){if(a instanceof o.default&&1===a.size()){var c=a.front();if(void 0===c)throw new Error("unknown error");t[n(c)&u-1]=new o.default([c])}else if(a instanceof s.default){var l=new o.default,h=new o.default;a.forEach((function(t){0==(n(t)&e)?l.pushBack(t):h.pushBack(t)})),l.size()>i.untreeifyThreshold?t[r]=new s.default(l):l.size()&&(t[r]=l),h.size()>i.untreeifyThreshold?t[r+e]=new s.default(h):h.size()&&(t[r+e]=h)}else{var p=new o.default,f=new o.default;a.forEach((function(t){0==(n(t)&e)?p.pushBack(t):f.pushBack(t)})),p.size()&&(t[r]=p),f.size()&&(t[r+e]=f)}d[r].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 a=d[t].size();if(d[t]instanceof o.default){if(d[t].find(e))return;d[t].pushBack(e),d[t].size()>=i.treeifyThreshold&&(d[t]=new s.default(d[t]))}else d[t].insert(e);var r=d[t].size();l+=r-a}else d[t]=new o.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 a=d[t].size();d[t].eraseElementByValue(e),d[t]instanceof s.default&&d[t].size()<=i.untreeifyThreshold&&(d[t]=new o.default(d[t]));var r=d[t].size();l+=r-a}},this.find=function(e){var t=n(e)&u-1;return!!d[t]&&d[t].find(e)},this[Symbol.iterator]=function(){return function(){var e,t,n,s,o,i;return a(this,(function(a){switch(a.label){case 0:e=0,a.label=1;case 1:if(!(e<u))return[3,10];for(;e<u&&!d[e];)++e;if(e>=u)return[3,10];a.label=2;case 2:a.trys.push([2,7,8,9]),o=void 0,t=r(d[e]),n=t.next(),a.label=3;case 3:return n.done?[3,6]:[4,n.value];case 4:a.sent(),a.label=5;case 5:return n=t.next(),[3,3];case 6:return[3,9];case 7:return s=a.sent(),o={error:s},[3,9];case 8:try{n&&!n.done&&(i=t.return)&&i.call(t)}finally{if(o)throw o.error}return[7];case 9:return++e,[3,1];case 10:return[2]}}))}()},e.forEach((function(e){return 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 a=this&&this.__generator||function(e,t){var n,a,r,s,o={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,a&&(r=2&s[0]?a.return:s[0]?a.throw||((r=a.return)&&r.call(a),0):a.next)&&!(r=r.call(a,s[1])).done)return r;switch(a=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,a=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((r=(r=o.trys).length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]<r[3])){o.label=s[1];break}if(6===s[0]&&o.label<r[1]){o.label=r[1],r=s;break}if(r&&o.label<r[2]){o.label=r[2],o.ops.push(s);break}r[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],a=0}finally{n=r=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}};Object.defineProperty(n,"__esModule",{value:!0});var r=function(){function e(e){this.value=void 0,this.pre=void 0,this.next=void 0,this.value=e}return e}();function s(e){var t=this;void 0===e&&(e=[]);var n=0,s=void 0,o=void 0;this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){s=o=void 0,n=0},this.front=function(){return null==s?void 0:s.value},this.back=function(){return null==o?void 0:o.value},this.forEach=function(e){for(var t=s,n=0;t;){if(void 0===t.value)throw new Error("unknown error");e(t.value,n++),t=t.next}},this.getElementByPos=function(e){if(e<0||e>=n)throw new Error("pos must more then 0 and less then the list length");for(var t=s;e--&&t;)t=t.next;if(!t||void 0===t.value)throw new Error("unknown error");return t.value},this.eraseElementByPos=function(e){if(e<0||e>=n)throw new Error("erase pos must more then 0 and less then the list length");if(0===e)this.popFront();else if(e===n-1)this.popBack();else{for(var t=s;e--;){if(!(null==t?void 0:t.next))throw new Error("unknown error");t=t.next}if(!t||!t.pre||!t.next)throw new Error("unknown error");var a=t.pre,r=t.next;r.pre=a,a.next=r,n>0&&--n}},this.eraseElementByValue=function(e){for(;s&&s.value===e;)this.popFront();for(;o&&o.value===e;)this.popBack();if(s)for(var t=s;t;){if(t.value===e){var a=t.pre,r=t.next;r&&(r.pre=a),a&&(a.next=r),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 r(e);o?(o.next=t,t.pre=o,o=t):s=o=t},this.popBack=function(){o&&(n>0&&--n,o&&(s===o?s=o=void 0:(o=o.pre)&&(o.next=void 0)))},this.setElementByPos=function(e,t){if(null==t)throw new Error("you can't set null or undefined here");if(e<0||e>=n)throw new Error("pos must more then 0 and less then the list length");for(var a=s;e--;){if(!a)throw new Error("unknown error");a=a.next}a&&(a.value=t)},this.insert=function(e,t,a){if(void 0===a&&(a=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(a<0)throw new Error("insert size must more than 0");if(0===e)for(;a--;)this.pushFront(t);else if(e===n)for(;a--;)this.pushBack(t);else{for(var o=s,i=1;i<e;++i){if(!(null==o?void 0:o.next))throw new Error("unknown error");o=null==o?void 0:o.next}if(!o)throw new Error("unknown error");var c=o.next;for(n+=a;a--;)o.next=new r(t),o.next.pre=o,o=o.next;o.next=c,c&&(c.pre=o)}},this.find=function(e){for(var t=s;t;){if(t.value===e)return!0;t=t.next}return!1},this.reverse=function(){for(var e=s,t=o,a=0;e&&t&&2*a<n;){var r=e.value;e.value=t.value,t.value=r,e=e.next,t=t.pre,++a}},this.unique=function(){for(var e=s;e;){for(var t=e;t&&t.next&&t.value===t.next.value;)t=t.next,n>0&&--n;e.next=t.next,e.next&&(e.next.pre=e),e=e.next}},this.sort=function(e){var t=[];this.forEach((function(e){t.push(e)})),t.sort(e);var n=s;t.forEach((function(e){n&&(n.value=e,n=n.next)}))},this.pushFront=function(e){if(null==e)throw new Error("you can't push null or undefined here");++n;var t=new r(e);s?(t.next=s,s.pre=t,s=t):s=o=t},this.popFront=function(){s&&(n>0&&--n,s&&(s===o?s=o=void 0:(s=s.next)&&(s.pre=void 0)))},this.merge=function(e){var t=this,a=s;e.forEach((function(e){for(;a&&void 0!==a.value&&a.value<=e;)a=a.next;if(void 0===a)t.pushBack(e),a=o;else if(a===s)t.pushFront(e),a=s;else{++n;var i=a.pre;i&&(i.next=new r(e),i.next.pre=i,i.next.next=a,a&&(a.pre=i.next))}}))},this[Symbol.iterator]=function(){return function(){var e;return a(this,(function(t){switch(t.label){case 0:e=s,t.label=1;case 1:if(void 0===e)return[3,3];if(!e.value)throw new Error("unknown error");return[4,e.value];case 2:return t.sent(),e=e.next,[3,1];case 3:return[2]}}))}()},e.forEach((function(e){return t.pushBack(e)})),Object.freeze(this)}Object.freeze(s),n.default=s},{}],30:[function(e,t,n){var a=this&&this.__generator||function(e,t){var n,a,r,s,o={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,a&&(r=2&s[0]?a.return:s[0]?a.throw||((r=a.return)&&r.call(a),0):a.next)&&!(r=r.call(a,s[1])).done)return r;switch(a=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,a=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((r=(r=o.trys).length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]<r[3])){o.label=s[1];break}if(6===s[0]&&o.label<r[1]){o.label=r[1],r=s;break}if(r&&o.label<r[2]){o.label=r[2],o.ops.push(s);break}r[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],a=0}finally{n=r=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},r=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],a=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&a>=e.length&&(e=void 0),{value:e&&e[a++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var s=e("../Base/TreeNode");function o(e,t){var n=this;void 0===e&&(e=[]),t=t||function(e,t){return e<t?-1:e>t?1:0};var o=0,i=new s.default;i.color=s.default.TreeNodeColorType.black,this.size=function(){return o},this.empty=function(){return 0===o},this.clear=function(){o=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,a=0;try{for(var s=r(this),o=s.next();!o.done;o=s.next())e(o.value,a++)}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}},this.getElementByPos=function(e){var t,n;if(e<0||e>=this.size())throw new Error("pos must more than 0 and less than set's size");var a=0;try{for(var s=r(this),o=s.next();!o.done;o=s.next()){var i=o.value;if(a===e)return i;++a}}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}throw new Error("unknown Error")};var d=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value){var a=t(e.key,n);return 0===a?{key:e.key,value:e.value}:a<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 a=t(e.key,n);return 0===a?{key:e.key,value:e.value}:a>0?h(e.leftChild,n):h(e.rightChild,n)||{key:e.key,value:e.value}}};this.reverseLowerBound=function(e){return h(i,e)};var p=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value)return t(e.key,n)>=0?p(e.leftChild,n):p(e.rightChild,n)||{key:e.key,value:e.value}};this.reverseUpperBound=function(e){return p(i,e)};var f=function(e){var t=e.parent;if(!t){if(e===i)return;throw new Error("unknown error")}if(e.color!==s.default.TreeNodeColorType.red){var n=e.brother;if(!n)throw new Error("unknown error");if(e===t.leftChild)if(n.color===s.default.TreeNodeColorType.red){n.color=s.default.TreeNodeColorType.black,t.color=s.default.TreeNodeColorType.red;var a=t.rotateLeft();i===t&&(i=a),f(e)}else n.color===s.default.TreeNodeColorType.black&&(n.rightChild&&n.rightChild.color===s.default.TreeNodeColorType.red?(n.color=t.color,t.color=s.default.TreeNodeColorType.black,n.rightChild&&(n.rightChild.color=s.default.TreeNodeColorType.black),a=t.rotateLeft(),i===t&&(i=a),e.color=s.default.TreeNodeColorType.black):n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||!n.leftChild||n.leftChild.color!==s.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||(n.color=s.default.TreeNodeColorType.red,f(t)):(n.color=s.default.TreeNodeColorType.red,n.leftChild&&(n.leftChild.color=s.default.TreeNodeColorType.black),a=n.rotateRight(),i===n&&(i=a),f(e)));else e===t.rightChild&&(n.color===s.default.TreeNodeColorType.red?(n.color=s.default.TreeNodeColorType.black,t.color=s.default.TreeNodeColorType.red,a=t.rotateRight(),i===t&&(i=a),f(e)):n.color===s.default.TreeNodeColorType.black&&(n.leftChild&&n.leftChild.color===s.default.TreeNodeColorType.red?(n.color=t.color,t.color=s.default.TreeNodeColorType.black,n.leftChild&&(n.leftChild.color=s.default.TreeNodeColorType.black),a=t.rotateRight(),i===t&&(i=a),e.color=s.default.TreeNodeColorType.black):n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||!n.rightChild||n.rightChild.color!==s.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||(n.color=s.default.TreeNodeColorType.red,f(t)):(n.color=s.default.TreeNodeColorType.red,n.rightChild&&(n.rightChild.color=s.default.TreeNodeColorType.black),a=n.rotateLeft(),i===n&&(i=a),f(e))))}else e.color=s.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 a=e.value;e.value=t.value,t.value=a,e=t}t.leftChild&&(t=l(t.leftChild),n=e.key,e.key=t.key,t.key=n,a=e.value,e.value=t.value,t.value=a,e=t)}f(t),t&&t.remove(),--o,i.color=s.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>=o)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 a=t(n,e.key);return a<0?e.leftChild?y(e.leftChild,n):(e.leftChild=new s.default,e.leftChild.parent=e,e.leftChild.brother=e.rightChild,e.rightChild&&(e.rightChild.brother=e.leftChild),e.leftChild):a>0?e.rightChild?y(e.rightChild,n):(e.rightChild=new s.default,e.rightChild.parent=e,e.rightChild.brother=e.leftChild,e.leftChild&&(e.leftChild.brother=e.rightChild),e.rightChild):e},v=function(e){var t=e.parent;if(!t){if(e===i)return;throw new Error("unknown error")}if(t.color!==s.default.TreeNodeColorType.black&&t.color===s.default.TreeNodeColorType.red){var n=t.brother,a=t.parent;if(!a)throw new Error("unknown error");if(n&&n.color===s.default.TreeNodeColorType.red)n.color=t.color=s.default.TreeNodeColorType.black,a.color=s.default.TreeNodeColorType.red,v(a);else if(!n||n.color===s.default.TreeNodeColorType.black)if(t===a.leftChild)if(e===t.leftChild){t.color=s.default.TreeNodeColorType.black,a.color=s.default.TreeNodeColorType.red;var r=a.rotateRight();a===i&&(i=r)}else e===t.rightChild&&(r=t.rotateLeft(),a===i&&(i=r),v(t));else t===a.rightChild&&(e===t.leftChild?(r=t.rotateRight(),a===i&&(i=r),v(t)):e===t.rightChild&&(t.color=s.default.TreeNodeColorType.black,a.color=s.default.TreeNodeColorType.red,r=a.rotateLeft(),a===i&&(i=r)))}};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++o,i.key=e,i.value=n,void(i.color=s.default.TreeNodeColorType.black);var a=y(i,e);void 0===a.key||0!==t(a.key,e)?(++o,a.key=e,a.value=n,v(a),i.color=s.default.TreeNodeColorType.black):a.value=n}else this.eraseElementByKey(e)};var b=function(e,n){if(e&&void 0!==e.key){var a=t(n,e.key);return a<0?b(e.leftChild,n):a>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,a=e.value;return t.setElement(n,a)}))},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 a(this,(function(t){switch(t.label){case 0:return e&&void 0!==e.key&&void 0!==e.value?[5,r(w(e.leftChild))]:[2];case 1:return t.sent(),[4,{key:e.key,value:e.value}];case 2:return t.sent(),[5,r(w(e.rightChild))];case 3:return t.sent(),[2]}}))};this[Symbol.iterator]=function(){return w(i)},e.forEach((function(e){var t=e.key,a=e.value;return n.setElement(t,a)})),Object.freeze(this)}Object.freeze(o),n.default=o},{"../Base/TreeNode":25}],31:[function(e,t,n){function a(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 a=n.length,r=function(e,t){if(e<0||e>=a)throw new Error("unknown error");if(t<0||t>=a)throw new Error("unknown error");var r=n[e];n[e]=n[t],n[t]=r},s=function(e){if(e<0||e>=a)throw new Error("unknown error");var s=2*e+1,o=2*e+2;s<a&&t(n[e],n[s])>0&&r(e,s),o<a&&t(n[e],n[o])>0&&r(e,o)};!function(){for(var e=Math.floor((a-1)/2);e>=0;--e)for(var s=e,o=2*s+1;o<a;){var i=o+1,c=o;if(i<a&&t(n[o],n[i])>0&&(c=i),t(n[s],n[c])<=0)break;r(s,c),o=2*(s=c)+1}}(),this.size=function(){return a},this.empty=function(){return 0===a},this.clear=function(){a=0,n.length=0},this.push=function(e){if(n.push(e),1!=++a)for(var r=a-1;r>0;){var o=Math.floor((r-1)/2);if(t(n[o],e)<=0)break;s(o),r=o}},this.pop=function(){if(!this.empty())if(1!==this.size()){var e=n[a-1];--a;for(var r=0;r<this.size();){var s=2*r+1,o=2*r+2;if(s>=this.size())break;var i=s;if(o<this.size()&&t(n[s],n[o])>0&&(i=o),t(n[i],e)>=0)break;n[r]=n[i],r=i}n[r]=e}else--a},this.top=function(){return n[0]},Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),Object.freeze(a),n.default=a},{}],32:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var a=e("../LinkList/LinkList");function r(e){void 0===e&&(e=[]);var t=new a.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(r),n.default=r},{"../LinkList/LinkList":29}],33:[function(e,t,n){var a=this&&this.__generator||function(e,t){var n,a,r,s,o={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,a&&(r=2&s[0]?a.return:s[0]?a.throw||((r=a.return)&&r.call(a),0):a.next)&&!(r=r.call(a,s[1])).done)return r;switch(a=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,a=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((r=(r=o.trys).length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]<r[3])){o.label=s[1];break}if(6===s[0]&&o.label<r[1]){o.label=r[1],r=s;break}if(r&&o.label<r[2]){o.label=r[2],o.ops.push(s);break}r[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],a=0}finally{n=r=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},r=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],a=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&a>=e.length&&(e=void 0),{value:e&&e[a++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var s=e("../Base/TreeNode");function o(e,t){var n=this;void 0===e&&(e=[]),t=t||function(e,t){return e<t?-1:e>t?1:0};var o=0,i=new s.default;i.color=s.default.TreeNodeColorType.black,this.size=function(){return o},this.empty=function(){return 0===o},this.clear=function(){o=0,i.key=void 0,i.leftChild=i.rightChild=i.brother=i.parent=void 0,i.color=s.default.TreeNodeColorType.black};var c=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.leftChild?c(e.leftChild):e},l=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.rightChild?l(e.rightChild):e};this.front=function(){if(!this.empty())return c(i).key},this.back=function(){if(!this.empty())return l(i).key},this.forEach=function(e){var t,n,a=0;try{for(var s=r(this),o=s.next();!o.done;o=s.next())e(o.value,a++)}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}},this.getElementByPos=function(e){var t,n;if(e<0||e>=this.size())throw new Error("pos must more than 0 and less than set's size");var a=0;try{for(var s=r(this),o=s.next();!o.done;o=s.next()){var i=o.value;if(a===e)return i;++a}}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}throw new Error("unknown error")};var d=function(e){var t=e.parent;if(!t){if(e===i)return;throw new Error("unknown error")}if(e.color!==s.default.TreeNodeColorType.red){var n=e.brother;if(!n)throw new Error("unknown error");if(e===t.leftChild)if(n.color===s.default.TreeNodeColorType.red){n.color=s.default.TreeNodeColorType.black,t.color=s.default.TreeNodeColorType.red;var a=t.rotateLeft();i===t&&(i=a),d(e)}else n.color===s.default.TreeNodeColorType.black&&(n.rightChild&&n.rightChild.color===s.default.TreeNodeColorType.red?(n.color=t.color,t.color=s.default.TreeNodeColorType.black,n.rightChild&&(n.rightChild.color=s.default.TreeNodeColorType.black),a=t.rotateLeft(),i===t&&(i=a),e.color=s.default.TreeNodeColorType.black):n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||!n.leftChild||n.leftChild.color!==s.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||(n.color=s.default.TreeNodeColorType.red,d(t)):(n.color=s.default.TreeNodeColorType.red,n.leftChild&&(n.leftChild.color=s.default.TreeNodeColorType.black),a=n.rotateRight(),i===n&&(i=a),d(e)));else e===t.rightChild&&(n.color===s.default.TreeNodeColorType.red?(n.color=s.default.TreeNodeColorType.black,t.color=s.default.TreeNodeColorType.red,a=t.rotateRight(),i===t&&(i=a),d(e)):n.color===s.default.TreeNodeColorType.black&&(n.leftChild&&n.leftChild.color===s.default.TreeNodeColorType.red?(n.color=t.color,t.color=s.default.TreeNodeColorType.black,n.leftChild&&(n.leftChild.color=s.default.TreeNodeColorType.black),a=t.rotateRight(),i===t&&(i=a),e.color=s.default.TreeNodeColorType.black):n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||!n.rightChild||n.rightChild.color!==s.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||(n.color=s.default.TreeNodeColorType.red,d(t)):(n.color=s.default.TreeNodeColorType.red,n.rightChild&&(n.rightChild.color=s.default.TreeNodeColorType.black),a=n.rotateLeft(),i===n&&(i=a),d(e))))}else e.color=s.default.TreeNodeColorType.black},u=function(e){for(var t=e;t.leftChild||t.rightChild;){if(t.rightChild){t=c(t.rightChild);var n=e.key;e.key=t.key,t.key=n,e=t}t.leftChild&&(t=l(t.leftChild),n=e.key,e.key=t.key,t.key=n,e=t)}d(t),t&&t.remove(),--o,i.color=s.default.TreeNodeColorType.black},h=function(e,t){return!(!e||void 0===e.key)&&(!!h(e.leftChild,t)||!!t(e)||h(e.rightChild,t))};this.eraseElementByPos=function(e){if(e<0||e>=o)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 a=t(n,e.key);return a<0?e.leftChild?p(e.leftChild,n):(e.leftChild=new s.default,e.leftChild.parent=e,e.leftChild.brother=e.rightChild,e.rightChild&&(e.rightChild.brother=e.leftChild),e.leftChild):a>0?e.rightChild?p(e.rightChild,n):(e.rightChild=new s.default,e.rightChild.parent=e,e.rightChild.brother=e.leftChild,e.leftChild&&(e.leftChild.brother=e.rightChild),e.rightChild):e},f=function(e){var t=e.parent;if(!t){if(e===i)return;throw new Error("unknown error")}if(t.color!==s.default.TreeNodeColorType.black&&t.color===s.default.TreeNodeColorType.red){var n=t.brother,a=t.parent;if(!a)throw new Error("unknown error");if(n&&n.color===s.default.TreeNodeColorType.red)n.color=t.color=s.default.TreeNodeColorType.black,a.color=s.default.TreeNodeColorType.red,f(a);else if(!n||n.color===s.default.TreeNodeColorType.black)if(t===a.leftChild)if(e===t.leftChild){t.color=s.default.TreeNodeColorType.black,a.color=s.default.TreeNodeColorType.red;var r=a.rotateRight();a===i&&(i=r)}else e===t.rightChild&&(r=t.rotateLeft(),a===i&&(i=r),f(t));else t===a.rightChild&&(e===t.leftChild?(r=t.rotateRight(),a===i&&(i=r),f(t)):e===t.rightChild&&(t.color=s.default.TreeNodeColorType.black,a.color=s.default.TreeNodeColorType.red,r=a.rotateLeft(),a===i&&(i=r)))}};this.insert=function(e){if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(this.empty())return++o,i.key=e,void(i.color=s.default.TreeNodeColorType.black);var n=p(i,e);void 0!==n.key&&0===t(n.key,e)||(++o,n.key=e,f(n),i.color=s.default.TreeNodeColorType.black)};var m=function(e,n){if(e&&void 0!==e.key){var a=t(n,e.key);return a<0?m(e.leftChild,n):a>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 a=t(e.key,n);if(0===a)return e.key;if(a<0)return g(e.rightChild,n);var r=g(e.leftChild,n);return void 0!==r?r: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 a=y(e.leftChild,n);return void 0!==a?a:e.key}};this.upperBound=function(e){return y(i,e)};var v=function(e,n){if(e&&void 0!==e.key){var a=t(e.key,n);if(0===a)return e.key;if(a>0)return v(e.leftChild,n);var r=v(e.rightChild,n);return void 0!==r?r: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 a=b(e.rightChild,n);return void 0!==a?a: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 a(this,(function(t){switch(t.label){case 0:return e&&void 0!==e.key?[5,r(w(e.leftChild))]:[2];case 1:return t.sent(),[4,e.key];case 2:return t.sent(),[5,r(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(o),n.default=o},{"../Base/TreeNode":25}],34:[function(e,t,n){function a(e){var t=this;void 0===e&&(e=[]);var n=0,a=[];this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){n=0,a.length=0},this.push=function(e){a.push(e),++n},this.pop=function(){a.pop(),n>0&&--n},this.top=function(){return a[n-1]},e.forEach((function(e){return t.push(e)})),Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),Object.freeze(a),n.default=a},{}],35:[function(e,t,n){var a=this&&this.__generator||function(e,t){var n,a,r,s,o={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,a&&(r=2&s[0]?a.return:s[0]?a.throw||((r=a.return)&&r.call(a),0):a.next)&&!(r=r.call(a,s[1])).done)return r;switch(a=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,a=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((r=(r=o.trys).length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]<r[3])){o.label=s[1];break}if(6===s[0]&&o.label<r[1]){o.label=r[1],r=s;break}if(r&&o.label<r[2]){o.label=r[2],o.ops.push(s);break}r[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],a=0}finally{n=r=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},r=this&&this.__read||function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var a,r,s=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(a=s.next()).done;)o.push(a.value)}catch(e){r={error:e}}finally{try{a&&!a.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}return o},s=this&&this.__spreadArray||function(e,t,n){if(n||2===arguments.length)for(var a,r=0,s=t.length;r<s;r++)!a&&r in t||(a||(a=Array.prototype.slice.call(t,0,r)),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))},o=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],a=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&a>=e.length&&(e=void 0),{value:e&&e[a++],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 a=t.length;n>a;)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,a){if(void 0===a&&(a=1),e<0||e>n)throw new Error("pos must more than 0 and less than or equal to vector's size");i.splice.apply(i,s([e,0],r(new Array(a).fill(t)),!1)),n+=a},this.find=function(e){return i.includes(e)},this.reverse=function(){i.reverse()},this.unique=function(){var e,t=[];this.forEach((function(n,a){0!==a&&n===e||(t.push(n),e=n)})),t.forEach((function(e,t){i[t]=e}));for(var a=t.length;n>a;)this.popBack()},this.sort=function(e){i.sort(e)},this[Symbol.iterator]=function(){return function(){return a(this,(function(e){switch(e.label){case 0:return[5,o(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 a=e("./Vector/Vector");n.Vector=a.default;var r=e("./Stack/Stack");n.Stack=r.default;var s=e("./Queue/Queue");n.Queue=s.default;var o=e("./LinkList/LinkList");n.LinkList=o.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 a=e("yallist"),r=Symbol("max"),s=Symbol("length"),o=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[r]=e.max||1/0;const t=e.length||f;if(this[o]="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[r]=e||1/0,v(this)}get max(){return this[r]}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[o]&&(this[o]=e,this[s]=0,this[u].forEach((e=>{e.length=this[o](e.value,e.key),this[s]+=e.length}))),v(this)}get lengthCalculator(){return this[o]}get length(){return this[s]}get itemCount(){return this[u].length}rforEach(e,t){t=t||this;for(let n=this[u].tail;null!==n;){const a=n.prev;I(this,e,n,t),n=a}}forEach(e,t){t=t||this;for(let n=this[u].head;null!==n;){const a=n.next;I(this,e,n,t),n=a}}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 a,this[s]=0}dump(){return this[u].map((e=>!y(this,e)&&{k:e.key,v:e.value,e:e.now+(e.maxAge||0)})).toArray().filter((e=>e))}dumpLru(){return this[u]}set(e,t,n){if((n=n||this[c])&&"number"!=typeof n)throw new TypeError("maxAge must be a number");const a=n?Date.now():0,i=this[o](t,e);if(this[h].has(e)){if(i>this[r])return b(this,this[h].get(e)),!1;const o=this[h].get(e).value;return this[l]&&(this[d]||this[l](e,o.value)),o.now=a,o.maxAge=n,o.value=t,this[s]+=i-o.length,o.length=i,this.get(e),v(this),!0}const p=new w(e,t,i,a,n);return p.length>this[r]?(this[l]&&this[l](e,t),!1):(this[s]+=p.length,this[u].unshift(p),this[h].set(e,this[u].head),v(this),!0)}has(e){if(!this[h].has(e))return!1;const t=this[h].get(e).value;return!y(this,t)}get(e){return 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 a=e[n],r=a.e||0;if(0===r)this.set(a.k,a.v);else{const e=r-t;e>0&&this.set(a.k,a.v,e)}}}prune(){this[h].forEach(((e,t)=>g(this,t,!1)))}}const g=(e,t,n)=>{const a=e[h].get(t);if(a){const t=a.value;if(y(e,t)){if(b(e,a),!e[i])return}else n&&(e[p]&&(a.value.now=Date.now()),e[u].unshiftNode(a));return t.value}},y=(e,t)=>{if(!t||!t.maxAge&&!e[c])return!1;const n=Date.now()-t.now;return t.maxAge?n>t.maxAge:e[c]&&n>e[c]},v=e=>{if(e[s]>e[r])for(let t=e[u].tail;e[s]>e[r]&&null!==t;){const n=t.prev;b(e,t),t=n}},b=(e,t)=>{if(t){const n=t.value;e[l]&&e[l](n.key,n.value),e[s]-=n.length,e[h].delete(n.key),e[u].removeNode(t)}};class w{constructor(e,t,n,a,r){this.key=e,this.value=t,this.length=n,this.now=a,this.maxAge=r||0}}const I=(e,t,n,a)=>{let r=n.value;y(e,r)&&(b(e,n),e[i]||(r=void 0)),r&&t.call(a,r.value,r.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 a(t){return[0,1,2].map((a=>[0,1].map((r=>[0,1].map((s=>{const o=e.alloc(1);return o.writeUInt8(n.codes[t]<<n.CMD_SHIFT|(r?n.DUP_MASK:0)|a<<n.QOS_SHIFT|s,0,!0),o}))))))}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=a("publish"),n.SUBSCRIBE_HEADER=a("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=a("unsubscribe"),n.ACKS={unsuback:a("unsuback"),puback:a("puback"),pubcomp:a("pubcomp"),pubrel:a("pubrel"),pubrec:a("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 a=e("./writeToStream"),r=e("events");function s(e,t){const n=new o;return a(e,n,t),n.concat()}class o extends r{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),a=this._array;let r,s=0;for(r=0;r<a.length&&void 0!==a[r];r++)"string"!=typeof a[r]?t[r]=a[r].length:t[r]=n.byteLength(a[r]),e+=t[r];const o=n.allocUnsafe(e);for(r=0;r<a.length&&void 0!==a[r];r++)"string"!=typeof a[r]?(a[r].copy(o,s),s+=t[r]):(o.write(a[r],s),s+=t[r]);return o}}t.exports=s}).call(this)}).call(this,e("buffer").Buffer)},{"./writeToStream":44,buffer:17,events:22}],40:[function(e,t,n){n.parser=e("./parser").parser,n.generate=e("./generate"),n.writeToStream=e("./writeToStream")},{"./generate":39,"./parser":43,"./writeToStream":44}],41:[function(e,t,n){(function(e){(function(){const n=65536,a={},r=e.isBuffer(e.from([1,2]).subarray(0,1));function s(t){const n=e.allocUnsafe(2);return n.writeUInt8(t>>8,0),n.writeUInt8(255&t,1),n}function o(){for(let e=0;e<n;e++)a[e]=s(e)}function i(t){const n=4;let a=0,s=0;const o=e.allocUnsafe(n);do{a=t%128|0,(t=t/128|0)>0&&(a|=128),o.writeUInt8(a,s++)}while(t>0&&s<n);return t>0&&(s=0),r?o.subarray(0,s):o.slice(0,s)}function c(t){const n=e.allocUnsafe(4);return n.writeUInt32BE(t,0),n}t.exports={cache:a,generateCache:o,generateNumber:s,genBufVariableByteInt:i,generate4ByteBuffer:c}}).call(this)}).call(this,e("buffer").Buffer)},{buffer:17}],42:[function(e,t,n){class a{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}}t.exports=a},{}],43:[function(e,t,n){const a=e("bl"),r=e("events"),s=e("./packet"),o=e("./constants"),i=e("debug")("mqtt-packet:parser");class c extends r{constructor(){super(),this.parser=this.constructor.parser}static parser(e){return this instanceof c?(this.settings=e||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):(new c).parser(e)}_resetState(){i("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new s,this.error=null,this._list=a(),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=o.types[e>>o.CMD_SHIFT],this.packet.retain=0!=(e&o.RETAIN_MASK),this.packet.qos=e>>o.QOS_SHIFT&o.QOS_MASK,this.packet.dup=0!=(e&o.DUP_MASK),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,a;i("_parseConnect");const r={},s=this.packet,c=this._parseString();if(null===c)return this._emitError(new Error("Cannot parse protocolId"));if("MQTT"!==c&&"MQIsdp"!==c)return this._emitError(new Error("Invalid protocolId"));if(s.protocolId=c,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(s.protocolVersion=this._list.readUInt8(this._pos),s.protocolVersion>=128&&(s.bridgeMode=!0,s.protocolVersion=s.protocolVersion-128),3!==s.protocolVersion&&4!==s.protocolVersion&&5!==s.protocolVersion)return this._emitError(new Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(r.username=this._list.readUInt8(this._pos)&o.USERNAME_MASK,r.password=this._list.readUInt8(this._pos)&o.PASSWORD_MASK,r.will=this._list.readUInt8(this._pos)&o.WILL_FLAG_MASK,r.will&&(s.will={},s.will.retain=0!=(this._list.readUInt8(this._pos)&o.WILL_RETAIN_MASK),s.will.qos=(this._list.readUInt8(this._pos)&o.WILL_QOS_MASK)>>o.WILL_QOS_SHIFT),s.clean=0!=(this._list.readUInt8(this._pos)&o.CLEAN_SESSION_MASK),this._pos++,s.keepalive=this._parseNum(),-1===s.keepalive)return this._emitError(new Error("Packet too short"));if(5===s.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(s.properties=e)}const l=this._parseString();if(null===l)return this._emitError(new Error("Packet too short"));if(s.clientId=l,i("_parseConnect: packet.clientId: %s",s.clientId),r.will){if(5===s.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(s.will.properties=e)}if(e=this._parseString(),null===e)return this._emitError(new Error("Cannot parse will topic"));if(s.will.topic=e,i("_parseConnect: packet.will.topic: %s",s.will.topic),t=this._parseBuffer(),null===t)return this._emitError(new Error("Cannot parse will payload"));s.will.payload=t,i("_parseConnect: packet.will.paylaod: %s",s.will.payload)}if(r.username){if(a=this._parseString(),null===a)return this._emitError(new Error("Cannot parse username"));s.username=a,i("_parseConnect: packet.username: %s",s.username)}if(r.password){if(n=this._parseBuffer(),null===n)return this._emitError(new Error("Cannot parse password"));s.password=n}return this.settings=s,i("_parseConnect: complete"),s}_parseConnack(){i("_parseConnack");const e=this.packet;if(this._list.length<1)return null;if(e.sessionPresent=!!(this._list.readUInt8(this._pos++)&o.SESSIONPRESENT_MASK),5===this.settings.protocolVersion)this._list.length>=2?e.reasonCode=this._list.readUInt8(this._pos++):e.reasonCode=0;else{if(this._list.length<2)return null;e.returnCode=this._list.readUInt8(this._pos++)}if(-1===e.returnCode||-1===e.reasonCode)return this._emitError(new Error("Cannot parse return code"));if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}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,a,r,s,c,l;if(1!==e.qos)return this._emitError(new Error("Wrong subscribe header"));if(e.subscriptions=[],this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}for(;this._pos<e.length;){if(t=this._parseString(),null===t)return this._emitError(new Error("Cannot parse topic"));if(this._pos>=e.length)return this._emitError(new Error("Malformed Subscribe Payload"));n=this._parseByte(),a=n&o.SUBSCRIBE_OPTIONS_QOS_MASK,c=0!=(n>>o.SUBSCRIBE_OPTIONS_NL_SHIFT&o.SUBSCRIBE_OPTIONS_NL_MASK),s=0!=(n>>o.SUBSCRIBE_OPTIONS_RAP_SHIFT&o.SUBSCRIBE_OPTIONS_RAP_MASK),r=n>>o.SUBSCRIBE_OPTIONS_RH_SHIFT&o.SUBSCRIBE_OPTIONS_RH_MASK,l={topic:t,qos:a},5===this.settings.protocolVersion?(l.nl=c,l.rap=s,l.rh=r):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 a=this._list.toString("utf8",this._pos,n);return this._pos+=t,i("_parseString: result: %s",a),a}_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,a=0,r=1,s=0,c=!1;const l=this._pos?this._pos:0;for(;a<t&&l+a<this._list.length;){if(n=this._list.readUInt8(l+a++),s+=r*(n&o.VARBYTEINT_MASK),r*=128,0==(n&o.VARBYTEINT_FIN_MASK)){c=!0;break}if(this._list.length<=a)break}return!c&&a===t&&this._list.length>=a&&this._emitError(new Error("Invalid variable byte integer")),l&&(this._pos+=a),c=!!c&&(e?{bytes:a,value:s}:s),i("_parseVarByteNum: result: %o",c),c}_parseByte(){let e;return this._pos<this._list.length&&(e=this._list.readUInt8(this._pos),this._pos++),i("_parseByte: result: %o",e),e}_parseByType(e){switch(i("_parseByType: type: %s",e),e){case"byte":return 0!==this._parseByte();case"int8":return this._parseByte();case"int16":return this._parseNum();case"int32":return this._parse4ByteNum();case"var":return this._parseVarByteNum();case"string":return this._parseString();case"pair":return this._parseStringPair();case"binary":return this._parseBuffer()}}_parseProperties(){i("_parseProperties");const e=this._parseVarByteNum(),t=this._pos+e,n={};for(;this._pos<t;){const e=this._parseByte();if(!e)return this._emitError(new Error("Cannot parse property code type")),!1;const t=o.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(o.propertiesTypes[t]))):n[t]=this._parseByType(o.propertiesTypes[t]);else{n[t]||(n[t]=Object.create(null));const e=this._parseByType(o.propertiesTypes[t]);if(n[t][e.name])if(Array.isArray(n[t][e.name]))n[t][e.name].push(e.value);else{const a=n[t][e.name];n[t][e.name]=[a],n[t][e.name].push(e.value)}else n[t][e.name]=e.value}}return n}_newPacket(){return i("_newPacket"),this.packet&&(this._list.consume(this.packet.length),i("_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d",this.packet.cmd,this.packet.payload,this.packet.length),this.emit("packet",this.packet)),i("_newPacket: new packet"),this.packet=new s,this._pos=0,!0}_emitError(e){i("_emitError"),this.error=e,this.emit("error",e)}}t.exports=c},{"./constants":38,"./packet":42,bl:15,debug:18,events:22}],44:[function(e,t,n){(function(n){(function(){const a=e("./constants"),r=n.allocUnsafe(0),s=n.from([0]),o=e("./numbers"),i=e("process-nextick-args").nextTick,c=e("debug")("mqtt-packet:writeToStream"),l=o.cache,d=o.generateNumber,u=o.generateCache,h=o.genBufVariableByteInt,p=o.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 I(e,t,n);case"subscribe":return C(e,t,n);case"suback":return S(e,t,n);case"unsubscribe":return O(e,t,n);case"unsuback":return T(e,t,n);case"pingreq":case"pingresp":return k(e,t);case"disconnect":return A(e,t,n);case"auth":return _(e,t,n);default:return t.emit("error",new Error("Unknown command")),!1}}function y(e){e.uncork()}function v(e,t,r){const s=e||{},o=s.protocolId||"MQTT";let i=s.protocolVersion||4;const c=s.will;let l=s.clean;const d=s.keepalive||0,u=s.clientId||"",h=s.username,p=s.password,m=s.properties;void 0===l&&(l=!0);let g=0;if(!o||"string"!=typeof o&&!n.isBuffer(o))return t.emit("error",new Error("Invalid protocolId")),!1;if(g+=o.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(a.CONNECT_HEADER),R(t,g),x(t,o),s.bridgeMode&&(i+=128),t.write(131===i?a.VERSION131:132===i?a.VERSION132:4===i?a.VERSION4:5===i?a.VERSION5:a.VERSION3);let w=0;return w|=null!=h?a.USERNAME_MASK:0,w|=null!=p?a.PASSWORD_MASK:0,w|=c&&c.retain?a.WILL_RETAIN_MASK:0,w|=c&&c.qos?c.qos<<a.WILL_QOS_SHIFT:0,w|=c?a.WILL_FLAG_MASK:0,w|=l?a.CLEAN_SESSION_MASK:0,t.write(n.from([w])),f(t,d),5===i&&y.write(),x(t,u),c&&(5===i&&v.write(),P(t,c.topic),x(t,c.payload)),null!=h&&x(t,h),null!=p&&x(t,p),!0}function b(e,t,r){const o=r?r.protocolVersion:4,i=e||{},c=5===o?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===o){if(u=q(t,l),!u)return!1;d+=u.length}return t.write(a.CONNACK_HEADER),R(t,d),t.write(i.sessionPresent?a.SESSIONPRESENT_HEADER:s),t.write(n.from([c])),null!=u&&u.write(),!0}function w(e,t,s){c("publish: packet: %o",e);const o=s?s.protocolVersion:4,i=e||{},l=i.qos||0,d=i.retain?a.RETAIN_MASK:0,u=i.topic,h=i.payload||r,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===o){if(y=q(t,m),!y)return!1;g+=y.length}return t.write(a.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 I(e,t,r){const s=r?r.protocolVersion:4,o=e||{},i=o.cmd||"puback",c=o.messageId,l=o.dup&&"pubrel"===i?a.DUP_MASK:0;let d=0;const u=o.reasonCode,h=o.properties;let p=5===s?3:2;if("pubrel"===i&&(d=1),"number"!=typeof c)return t.emit("error",new Error("Invalid messageId")),!1;let m=null;if(5===s&&"object"==typeof h){if(m=N(t,h,r,p),!m)return!1;p+=m.length}return t.write(a.ACKS[i][d][l][0]),R(t,p),f(t,c),5===s&&t.write(n.from([u])),null!==m&&m.write(),!0}function C(e,t,r){c("subscribe: packet: ");const s=r?r.protocolVersion:4,o=e||{},i=o.dup?a.DUP_MASK:0,l=o.messageId,d=o.subscriptions,u=o.properties;let h=0;if("number"!=typeof l)return t.emit("error",new Error("Invalid messageId")),!1;h+=2;let p=null;if(5===s){if(p=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 a=d[e].topic,r=d[e].qos;if("string"!=typeof a)return t.emit("error",new Error("Invalid subscriptions - invalid topic")),!1;if("number"!=typeof r)return t.emit("error",new Error("Invalid subscriptions - invalid qos")),!1;if(5===s){if("boolean"!=typeof(d[e].nl||!1))return t.emit("error",new Error("Invalid subscriptions - invalid No Local")),!1;if("boolean"!=typeof(d[e].rap||!1))return t.emit("error",new Error("Invalid subscriptions - invalid Retain as Published")),!1;const n=d[e].rh||0;if("number"!=typeof n||n>2)return t.emit("error",new Error("Invalid subscriptions - invalid Retain Handling")),!1}h+=n.byteLength(a)+2+1}c("subscribe: writing to stream: %o",a.SUBSCRIBE_HEADER),t.write(a.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 r=e.topic,o=e.qos,i=+e.nl,c=+e.rap,l=e.rh;let d;P(t,r),d=a.SUBSCRIBE_OPTIONS_QOS[o],5===s&&(d|=i?a.SUBSCRIBE_OPTIONS_NL:0,d|=c?a.SUBSCRIBE_OPTIONS_RAP:0,d|=l?a.SUBSCRIBE_OPTIONS_RH[l]:0),m=t.write(n.from([d]))}return m}function S(e,t,r){const s=r?r.protocolVersion:4,o=e||{},i=o.messageId,c=o.granted,l=o.properties;let d=0;if("number"!=typeof i)return t.emit("error",new Error("Invalid messageId")),!1;if(d+=2,"object"!=typeof c||!c.length)return t.emit("error",new Error("Invalid qos vector")),!1;for(let e=0;e<c.length;e+=1){if("number"!=typeof c[e])return t.emit("error",new Error("Invalid qos vector")),!1;d+=1}let u=null;if(5===s){if(u=N(t,l,r,d),!u)return!1;d+=u.length}return t.write(a.SUBACK_HEADER),R(t,d),f(t,i),null!==u&&u.write(),t.write(n.from(c))}function O(e,t,r){const s=r?r.protocolVersion:4,o=e||{},i=o.messageId,c=o.dup?a.DUP_MASK:0,l=o.unsubscriptions,d=o.properties;let u=0;if("number"!=typeof i)return t.emit("error",new Error("Invalid messageId")),!1;if(u+=2,"object"!=typeof l||!l.length)return t.emit("error",new Error("Invalid unsubscriptions")),!1;for(let e=0;e<l.length;e+=1){if("string"!=typeof l[e])return t.emit("error",new Error("Invalid unsubscriptions")),!1;u+=n.byteLength(l[e])+2}let h=null;if(5===s){if(h=q(t,d),!h)return!1;u+=h.length}t.write(a.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 T(e,t,r){const s=r?r.protocolVersion:4,o=e||{},i=o.messageId,c=o.dup?a.DUP_MASK:0,l=o.granted,d=o.properties,u=o.cmd,h=0;let p=2;if("number"!=typeof i)return t.emit("error",new Error("Invalid messageId")),!1;if(5===s){if("object"!=typeof l||!l.length)return t.emit("error",new Error("Invalid qos vector")),!1;for(let e=0;e<l.length;e+=1){if("number"!=typeof l[e])return t.emit("error",new Error("Invalid qos vector")),!1;p+=1}}let m=null;if(5===s){if(m=N(t,d,r,p),!m)return!1;p+=m.length}return t.write(a.ACKS[u][h][c][0]),R(t,p),f(t,i),null!==m&&m.write(),5===s&&t.write(n.from(l)),!0}function k(e,t,n){return t.write(a.EMPTY[e.cmd])}function A(e,t,r){const s=r?r.protocolVersion:4,o=e||{},i=o.reasonCode,c=o.properties;let l=5===s?1:0,d=null;if(5===s){if(d=N(t,c,r,l),!d)return!1;l+=d.length}return t.write(n.from([a.codes.disconnect<<4])),R(t,l),5===s&&t.write(n.from([i])),null!==d&&d.write(),!0}function _(e,t,r){const s=r?r.protocolVersion:4,o=e||{},i=o.reasonCode,c=o.properties;let l=5===s?1:0;5!==s&&t.emit("error",new Error("Invalid mqtt version for auth packet"));const d=N(t,c,r,l);return!!d&&(l+=d.length,t.write(n.from([a.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 E={};function R(e,t){if(t>a.VARBYTEINT_MAX)return e.emit("error",new Error(`Invalid variable byte integer: ${t}`)),!1;let n=E[t];return n||(n=h(t),t<16384&&(E[t]=n)),c("writeVarByteInt: writing to stream: %o",n),e.write(n)}function P(e,t){const a=n.byteLength(t);return f(e,a),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 D(e,t){const n=p(t);return c("write4ByteNumber: %o",n),e.write(n)}function x(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 r=0;function s(t,r){let s=0;switch(a.propertiesTypes[t]){case"byte":if("boolean"!=typeof r)return e.emit("error",new Error(`Invalid ${t}: ${r}`)),!1;s+=2;break;case"int8":if("number"!=typeof r||r<0||r>255)return e.emit("error",new Error(`Invalid ${t}: ${r}`)),!1;s+=2;break;case"binary":if(r&&null===r)return e.emit("error",new Error(`Invalid ${t}: ${r}`)),!1;s+=1+n.byteLength(r)+2;break;case"int16":if("number"!=typeof r||r<0||r>65535)return e.emit("error",new Error(`Invalid ${t}: ${r}`)),!1;s+=3;break;case"int32":if("number"!=typeof r||r<0||r>4294967295)return e.emit("error",new Error(`Invalid ${t}: ${r}`)),!1;s+=5;break;case"var":if("number"!=typeof r||r<0||r>268435455)return e.emit("error",new Error(`Invalid ${t}: ${r}`)),!1;s+=1+n.byteLength(h(r));break;case"string":if("string"!=typeof r)return e.emit("error",new Error(`Invalid ${t}: ${r}`)),!1;s+=3+n.byteLength(r.toString());break;case"pair":if("object"!=typeof r)return e.emit("error",new Error(`Invalid ${t}: ${r}`)),!1;s+=Object.getOwnPropertyNames(r).reduce(((e,t)=>{const a=r[t];return Array.isArray(a)?e+=a.reduce(((e,a)=>e+=3+n.byteLength(t.toString())+2+n.byteLength(a.toString())),0):e+=3+n.byteLength(t.toString())+2+n.byteLength(r[t].toString()),e}),0);break;default:return e.emit("error",new Error(`Invalid property ${t}: ${r}`)),!1}return s}if(t)for(const e in t){let n=0,a=0;const o=t[e];if(Array.isArray(o))for(let t=0;t<o.length;t++){if(a=s(e,o[t]),!a)return!1;n+=a}else{if(a=s(e,o),!a)return!1;n=a}if(!n)return!1;r+=n}return{length:n.byteLength(h(r))+r,write(){L(e,t,r)}}}function N(e,t,n,a){const r=["reasonString","userProperties"],s=n&&n.properties&&n.properties.maximumPacketSize?n.properties.maximumPacketSize:0;let o=q(e,t);if(s)for(;a+o.length>s;){const n=r.shift();if(!n||!t[n])return!1;delete t[n],o=q(e,t)}return o}function B(e,t,r){switch(a.propertiesTypes[t]){case"byte":e.write(n.from([a.properties[t]])),e.write(n.from([+r]));break;case"int8":e.write(n.from([a.properties[t]])),e.write(n.from([r]));break;case"binary":e.write(n.from([a.properties[t]])),x(e,r);break;case"int16":e.write(n.from([a.properties[t]])),f(e,r);break;case"int32":e.write(n.from([a.properties[t]])),D(e,r);break;case"var":e.write(n.from([a.properties[t]])),R(e,r);break;case"string":e.write(n.from([a.properties[t]])),P(e,r);break;case"pair":Object.getOwnPropertyNames(r).forEach((s=>{const o=r[s];Array.isArray(o)?o.forEach((r=>{e.write(n.from([a.properties[t]])),M(e,s.toString(),r.toString())})):(e.write(n.from([a.properties[t]])),M(e,s.toString(),o.toString()))}));break;default:return e.emit("error",new Error(`Invalid property ${t} value: ${r}`)),!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 a=t[n];if(Array.isArray(a))for(let t=0;t<a.length;t++)B(e,n,a[t]);else B(e,n,a)}}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 a=1e3,r=60*a,s=60*r,o=24*s,i=7*o,c=365.25*o;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*o;case"hours":case"hour":case"hrs":case"hr":case"h":return n*s;case"minutes":case"minute":case"mins":case"min":case"m":return n*r;case"seconds":case"second":case"secs":case"sec":case"s":return n*a;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function d(e){var t=Math.abs(e);return t>=o?Math.round(e/o)+"d":t>=s?Math.round(e/s)+"h":t>=r?Math.round(e/r)+"m":t>=a?Math.round(e/a)+"s":e+"ms"}function u(e){var t=Math.abs(e);return t>=o?h(e,t,o,"day"):t>=s?h(e,t,s,"hour"):t>=r?h(e,t,r,"minute"):t>=a?h(e,t,a,"second"):e+" ms"}function h(e,t,n,a){var r=t>=1.5*n;return Math.round(e/n)+" "+a+(r?"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 a=e("./lib/number-allocator.js");t.exports.NumberAllocator=a},{"./lib/number-allocator.js":47}],47:[function(e,t,n){const a=e("js-sdsl").Set,r=e("debug")("number-allocator:trace"),s=e("debug")("number-allocator:error");function o(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 a([],((e,t)=>e.compare(t))),r("Create"),this.clear()}o.prototype.equals=function(e){return this.low===e.low&&this.high===e.high},o.prototype.compare=function(e){return this.low<e.low&&this.high<e.low?-1:e.low<this.low&&e.high<this.low?1:0},i.prototype.firstVacant=function(){return 0===this.ss.size()?null:this.ss.front().low},i.prototype.alloc=function(){if(0===this.ss.size())return r("alloc():empty"),null;const e=this.ss.front(),t=e.low;return t+1<=e.high?++e.low:this.ss.eraseElementByPos(0),r("alloc():"+t),t},i.prototype.use=function(e){const t=new o(e,e),n=this.ss.lowerBound(t);if(n){if(n.equals(t))return this.ss.eraseElementByValue(n),r("use():"+e),!0;if(n.low>e)return!1;if(n.low===e)return++n.low,r("use():"+e),!0;if(n.high===e)return--n.high,r("use():"+e),!0;const a=n.low;return n.low=e+1,this.ss.insert(new o(a,e-1)),r("use():"+e),!0}return r("use():failed"),!1},i.prototype.free=function(e){if(e<this.min||e>this.max)return void s("free():"+e+" is out of range");const t=new o(e,e),n=this.ss.lowerBound(t);if(n){if(n.low<=e&&e<=n.high)return void s("free():"+e+" has already been vacant");if(n===this.ss.front())e+1===n.low?--n.low:this.ss.insert(t);else{const a=this.ss.reverseLowerBound(t);a.high+1===e?e+1===n.low?(this.ss.eraseElementByValue(a),n.low=a.low):a.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 a=this.ss.reverseLowerBound(t);a.high+1===e?a.high=e:this.ss.insert(t)}r("free():"+e)},i.prototype.clear=function(){r("clear()"),this.ss.clear(),this.ss.insert(new o(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 a=e("wrappy");function r(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function s(e){var t=function(){if(t.called)throw new Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)},n=e.name||"Function wrapped with `once`";return t.onceError=n+" shouldn't be called more than once",t.called=!1,t}t.exports=a(r),t.exports.strict=a(s),r.proto=r((function(){Object.defineProperty(Function.prototype,"once",{value:function(){return r(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return s(this)},configurable:!0})}))},{wrappy:79}],49:[function(e,t,n){(function(e){(function(){function n(t,n,a,r){if("function"!=typeof t)throw new TypeError('"callback" argument must be a function');var s,o,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,a)}));case 4:return e.nextTick((function(){t.call(null,n,a,r)}));default:for(s=new Array(i-1),o=0;o<s.length;)s[o++]=arguments[o];return e.nextTick((function(){t.apply(null,s)}))}}void 0===e||!e.version||0===e.version.indexOf("v0.")||0===e.version.indexOf("v1.")&&0!==e.version.indexOf("v1.8.")?t.exports={nextTick:n}:t.exports=e}).call(this)}).call(this,e("_process"))},{_process:50}],50:[function(e,t,n){var a,r,s=t.exports={};function o(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}function c(e){if(a===setTimeout)return setTimeout(e,0);if((a===o||!a)&&setTimeout)return a=setTimeout,setTimeout(e,0);try{return a(e,0)}catch(t){try{return a.call(null,e,0)}catch(t){return a.call(this,e,0)}}}function l(e){if(r===clearTimeout)return clearTimeout(e);if((r===i||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(e);try{return r(e)}catch(t){try{return r.call(null,e)}catch(t){return r.call(this,e)}}}!function(){try{a="function"==typeof setTimeout?setTimeout:o}catch(e){a=o}try{r="function"==typeof clearTimeout?clearTimeout:i}catch(e){r=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(){}s.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];u.push(new g(e,t)),1!==u.length||h||c(m)},g.prototype.run=function(){this.fun.apply(null,this.array)},s.title="browser",s.browser=!0,s.env={},s.argv=[],s.version="",s.versions={},s.on=y,s.addListener=y,s.once=y,s.off=y,s.removeListener=y,s.removeAllListeners=y,s.emit=y,s.prependListener=y,s.prependOnceListener=y,s.listeners=function(e){return[]},s.binding=function(e){throw new Error("process.binding is not supported")},s.cwd=function(){return"/"},s.chdir=function(e){throw new Error("process.chdir is not supported")},s.umask=function(){return 0}},{}],51:[function(e,t,n){(function(e){(function(){!function(a){var r="object"==typeof n&&n&&!n.nodeType&&n,s="object"==typeof t&&t&&!t.nodeType&&t,o="object"==typeof e&&e;o.global!==o&&o.window!==o&&o.self!==o||(a=o);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,I={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},C=d-u,S=Math.floor,O=String.fromCharCode;function T(e){throw new RangeError(I[e])}function k(e,t){for(var n=e.length,a=[];n--;)a[n]=t(e[n]);return a}function A(e,t){var n=e.split("@"),a="";return n.length>1&&(a=n[0]+"@",e=n[1]),a+k((e=e.replace(w,".")).split("."),t).join(".")}function _(e){for(var t,n,a=[],r=0,s=e.length;r<s;)(t=e.charCodeAt(r++))>=55296&&t<=56319&&r<s?56320==(64512&(n=e.charCodeAt(r++)))?a.push(((1023&t)<<10)+(1023&n)+65536):(a.push(t),r--):a.push(t);return a}function E(e){return k(e,(function(e){var t="";return e>65535&&(t+=O((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=O(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 a=0;for(e=n?S(e/f):e>>1,e+=S(e/t);e>C*h>>1;a+=d)e=S(e/C);return S(a+(C+1)*e/(e+p))}function j(e){var t,n,a,r,s,o,i,c,p,f,v=[],b=e.length,w=0,I=g,C=m;for((n=e.lastIndexOf(y))<0&&(n=0),a=0;a<n;++a)e.charCodeAt(a)>=128&&T("not-basic"),v.push(e.charCodeAt(a));for(r=n>0?n+1:0;r<b;){for(s=w,o=1,i=d;r>=b&&T("invalid-input"),((c=R(e.charCodeAt(r++)))>=d||c>S((l-w)/o))&&T("overflow"),w+=c*o,!(c<(p=i<=C?u:i>=C+h?h:i-C));i+=d)o>S(l/(f=d-p))&&T("overflow"),o*=f;C=M(w-s,t=v.length+1,0==s),S(w/t)>l-I&&T("overflow"),I+=S(w/t),w%=t,v.splice(w++,0,I)}return E(v)}function U(e){var t,n,a,r,s,o,i,c,p,f,v,b,w,I,C,k=[];for(b=(e=_(e)).length,t=g,n=0,s=m,o=0;o<b;++o)(v=e[o])<128&&k.push(O(v));for(a=r=k.length,r&&k.push(y);a<b;){for(i=l,o=0;o<b;++o)(v=e[o])>=t&&v<i&&(i=v);for(i-t>S((l-n)/(w=a+1))&&T("overflow"),n+=(i-t)*w,t=i,o=0;o<b;++o)if((v=e[o])<t&&++n>l&&T("overflow"),v==t){for(c=n,p=d;!(c<(f=p<=s?u:p>=s+h?h:p-s));p+=d)C=c-f,I=d-f,k.push(O(P(f+C%I,0))),c=S(C/I);k.push(O(P(c,0))),s=M(n,w,a==r),n=0,++a}++n,++t}return k.join("")}function D(e){return A(e,(function(e){return v.test(e)?j(e.slice(4).toLowerCase()):e}))}function x(e){return A(e,(function(e){return b.test(e)?"xn--"+U(e):e}))}if(i={version:"1.4.1",ucs2:{decode:_,encode:E},decode:j,encode:U,toASCII:x,toUnicode:D},r&&s)if(t.exports==r)s.exports=i;else for(c in i)i.hasOwnProperty(c)&&(r[c]=i[c]);else a.punycode=i}(this)}).call(this)}).call(this,void 0!==pn?pn:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],52:[function(e,t,n){function a(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.exports=function(e,t,n,s){t=t||"&",n=n||"=";var o={};if("string"!=typeof e||0===e.length)return o;var i=/\+/g;e=e.split(t);var c=1e3;s&&"number"==typeof s.maxKeys&&(c=s.maxKeys);var l=e.length;c>0&&l>c&&(l=c);for(var d=0;d<l;++d){var u,h,p,f,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),a(o,p)?r(o[p])?o[p].push(f):o[p]=[o[p],f]:o[p]=f}return o};var r=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],53:[function(e,t,n){var a=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,n,i){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"==typeof e?s(o(e),(function(o){var i=encodeURIComponent(a(o))+n;return r(e[o])?s(e[o],(function(e){return i+encodeURIComponent(a(e))})).join(t):i+encodeURIComponent(a(e[o]))})).join(t):i?encodeURIComponent(a(i))+n+encodeURIComponent(a(e)):""};var r=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function s(e,t){if(e.map)return e.map(t);for(var n=[],a=0;a<e.length;a++)n.push(t(e[a],a));return n}var o=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 a(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}var r={};function s(e,t,n){function s(e,n,a){return"string"==typeof t?t:t(e,n,a)}n||(n=Error);var o=function(e){function t(t,n,a){return e.call(this,s(t,n,a))||this}return a(t,e),t}(n);o.prototype.name=n.name,o.prototype.code=e,r[e]=o}function o(e,t){if(Array.isArray(e)){var n=e.length;return e=e.map((function(e){return String(e)})),n>2?"one of ".concat(t," ").concat(e.slice(0,n-1).join(", "),", or ")+e[n-1]:2===n?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}function i(e,t,n){return e.substr(!n||n<0?0:+n,t.length)===t}function c(e,t,n){return(void 0===n||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}function l(e,t,n){return"number"!=typeof n&&(n=0),!(n+t.length>e.length)&&-1!==e.indexOf(t,n)}s("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError),s("ERR_INVALID_ARG_TYPE",(function(e,t,n){var a,r;if("string"==typeof t&&i(t,"not ")?(a="must not be",t=t.replace(/^not /,"")):a="must be",c(e," argument"))r="The ".concat(e," ").concat(a," ").concat(o(t,"type"));else{var s=l(e,".")?"property":"argument";r='The "'.concat(e,'" ').concat(s," ").concat(a," ").concat(o(t,"type"))}return r+=". Received type ".concat(typeof n)}),TypeError),s("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),s("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"})),s("ERR_STREAM_PREMATURE_CLOSE","Premature close"),s("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"})),s("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),s("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),s("ERR_STREAM_WRITE_AFTER_END","write after end"),s("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),s("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError),s("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),t.exports.codes=r},{}],56:[function(e,t,n){(function(n){(function(){var a=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=l;var r=e("./_stream_readable"),s=e("./_stream_writable");e("inherits")(l,r);for(var o=a(s.prototype),i=0;i<o.length;i++){var c=o[i];l.prototype[c]||(l.prototype[c]=s.prototype[c])}function l(e){if(!(this instanceof l))return new l(e);r.call(this,e),s.call(this,e),this.allowHalfOpen=!0,e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",d)))}function d(){this._writableState.ended||n.nextTick(u,this)}function u(e){e.end()}Object.defineProperty(l.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(l.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(l.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(l.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&this._readableState.destroyed&&this._writableState.destroyed},set:function(e){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}})}).call(this)}).call(this,e("_process"))},{"./_stream_readable":58,"./_stream_writable":60,_process:50,inherits:24}],57:[function(e,t,n){t.exports=r;var a=e("./_stream_transform");function r(e){if(!(this instanceof r))return new r(e);a.call(this,e)}e("inherits")(r,a),r.prototype._transform=function(e,t,n){n(null,e)}},{"./_stream_transform":59,inherits:24}],58:[function(e,t,n){(function(n,a){(function(){var r;t.exports=_,_.ReadableState=A,e("events").EventEmitter;var s=function(e,t){return e.listeners(t).length},o=e("./internal/streams/stream"),i=e("buffer").Buffer,c=a.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,I=b.ERR_STREAM_PUSH_AFTER_EOF,C=b.ERR_METHOD_NOT_IMPLEMENTED,S=b.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;e("inherits")(_,o);var O=y.errorOrDestroy,T=["error","close","destroy","pause","resume"];function k(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 A(t,n,a){r=r||e("./_stream_duplex"),t=t||{},"boolean"!=typeof a&&(a=n instanceof r),this.objectMode=!!t.objectMode,a&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=v(this,t,"readableHighWaterMark",a),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 _(t){if(r=r||e("./_stream_duplex"),!(this instanceof _))return new _(t);var n=this instanceof r;this._readableState=new A(t,this,n),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),o.call(this)}function E(e,t,n,a,r){u("readableAddChunk",t);var s,o=e._readableState;if(null===t)o.reading=!1,D(e,o);else if(r||(s=P(o,t)),s)O(e,s);else if(o.objectMode||t&&t.length>0)if("string"==typeof t||o.objectMode||Object.getPrototypeOf(t)===i.prototype||(t=l(t)),a)o.endEmitted?O(e,new S):R(e,o,t,!0);else if(o.ended)O(e,new I);else{if(o.destroyed)return!1;o.reading=!1,o.decoder&&!n?(t=o.decoder.write(t),o.objectMode||0!==t.length?R(e,o,t,!1):N(e,o)):R(e,o,t,!1)}else a||(o.reading=!1,N(e,o));return!o.ended&&(o.length<o.highWaterMark||0===o.length)}function R(e,t,n,a){t.flowing&&0===t.length&&!t.sync?(t.awaitDrain=0,e.emit("data",n)):(t.length+=t.objectMode?1:n.length,a?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&x(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(_.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),_.prototype.destroy=y.destroy,_.prototype._undestroy=y.undestroy,_.prototype._destroy=function(e,t){t(e)},_.prototype.push=function(e,t){var n,a=this._readableState;return a.objectMode?n=!0:"string"==typeof e&&((t=t||a.defaultEncoding)!==a.encoding&&(e=i.from(e,t),t=""),n=!0),E(this,e,t,!1,n)},_.prototype.unshift=function(e){return E(this,e,null,!0,!1)},_.prototype.isPaused=function(){return!1===this._readableState.flowing},_.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 a=this._readableState.buffer.head,r="";null!==a;)r+=n.write(a.data),a=a.next;return this._readableState.buffer.clear(),""!==r&&this._readableState.buffer.push(r),this._readableState.length=r.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 D(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?x(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,q(e)))}}function x(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,V(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&&s(e,"data")&&(t.flowing=!0,V(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"),V(e),t.flowing&&!t.reading&&e.read(0)}function V(e){var t=e._readableState;for(u("flow",t.flowing);t.flowing&&null!==e.read(););}function z(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,a=e.length;n<a;n++)if(e[n]===t)return n;return-1}_.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):x(this),null;if(0===(e=U(e,t))&&t.ended)return 0===t.length&&H(this),null;var a,r=t.needReadable;return u("need readable",r),(0===t.length||t.length-e<t.highWaterMark)&&u("length less than watermark",r=!0),t.ended||t.reading?u("reading or ended",r=!1):r&&(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===(a=e>0?z(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!==a&&this.emit("data",a),a},_.prototype._read=function(e){O(this,new C("_read()"))},_.prototype.pipe=function(e,t){var a=this,r=this._readableState;switch(r.pipesCount){case 0:r.pipes=e;break;case 1:r.pipes=[r.pipes,e];break;default:r.pipes.push(e)}r.pipesCount+=1,u("pipe count=%d opts=%j",r.pipesCount,t);var o=t&&!1===t.end||e===n.stdout||e===n.stderr?y:c;function i(e,t){u("onunpipe"),e===a&&t&&!1===t.hasUnpiped&&(t.hasUnpiped=!0,h())}function c(){u("onend"),e.end()}r.endEmitted?n.nextTick(o):a.once("end",o),e.on("unpipe",i);var l=L(a);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),a.removeListener("end",c),a.removeListener("end",y),a.removeListener("data",p),d=!0,!r.awaitDrain||e._writableState&&!e._writableState.needDrain||l()}function p(t){u("ondata");var n=e.write(t);u("dest.write",n),!1===n&&((1===r.pipesCount&&r.pipes===e||r.pipesCount>1&&-1!==W(r.pipes,e))&&!d&&(u("false write response, pause",r.awaitDrain),r.awaitDrain++),a.pause())}function f(t){u("onerror",t),y(),e.removeListener("error",f),0===s(e,"error")&&O(e,t)}function m(){e.removeListener("finish",g),y()}function g(){u("onfinish"),e.removeListener("close",m),y()}function y(){u("unpipe"),a.unpipe(e)}return a.on("data",p),k(e,"error",f),e.once("close",m),e.once("finish",g),e.emit("pipe",a),r.flowing||(u("pipe resume"),a.resume()),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 a=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var s=0;s<r;s++)a[s].emit("unpipe",this,{hasUnpiped:!1});return this}var o=W(t.pipes,e);return-1===o||(t.pipes.splice(o,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,n)),this},_.prototype.on=function(e,t){var a=o.prototype.on.call(this,e,t),r=this._readableState;return"data"===e?(r.readableListening=this.listenerCount("readable")>0,!1!==r.flowing&&this.resume()):"readable"===e&&(r.endEmitted||r.readableListening||(r.readableListening=r.needReadable=!0,r.flowing=!1,r.emittedReadable=!1,u("on readable",r.length,r.reading),r.length?x(this):r.reading||n.nextTick(K,this))),a},_.prototype.addListener=_.prototype.on,_.prototype.removeListener=function(e,t){var a=o.prototype.removeListener.call(this,e,t);return"readable"===e&&n.nextTick(F,this),a},_.prototype.removeAllListeners=function(e){var t=o.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||n.nextTick(F,this),t},_.prototype.resume=function(){var e=this._readableState;return e.flowing||(u("resume"),e.flowing=!e.readableListening,$(this,e)),e.paused=!1,this},_.prototype.pause=function(){return u("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(u("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},_.prototype.wrap=function(e){var t=this,n=this._readableState,a=!1;for(var r 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(r){u("wrapped data"),n.decoder&&(r=n.decoder.write(r)),n.objectMode&&null==r||(n.objectMode||r&&r.length)&&(t.push(r)||(a=!0,e.pause()))})),e)void 0===this[r]&&"function"==typeof e[r]&&(this[r]=function(t){return function(){return e[t].apply(e,arguments)}}(r));for(var s=0;s<T.length;s++)e.on(T[s],this.emit.bind(this,T[s]));return this._read=function(t){u("wrapped _read",t),a&&(a=!1,e.resume())},this},"function"==typeof Symbol&&(_.prototype[Symbol.asyncIterator]=function(){return void 0===f&&(f=e("./internal/streams/async_iterator")),f(this)}),Object.defineProperty(_.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(_.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(_.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),_._fromList=z,Object.defineProperty(_.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(_.from=function(t,n){return void 0===m&&(m=e("./internal/streams/from")),m(_,t,n)})}).call(this)}).call(this,e("_process"),void 0!==pn?pn:"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 a=e("../errors").codes,r=a.ERR_METHOD_NOT_IMPLEMENTED,s=a.ERR_MULTIPLE_CALLBACK,o=a.ERR_TRANSFORM_ALREADY_TRANSFORMING,i=a.ERR_TRANSFORM_WITH_LENGTH_0,c=e("./_stream_duplex");function l(e,t){var n=this._transformState;n.transforming=!1;var a=n.writecb;if(null===a)return this.emit("error",new s);n.writechunk=null,n.writecb=null,null!=t&&this.push(t),a(e);var r=this._readableState;r.reading=!1,(r.needReadable||r.length<r.highWaterMark)&&this._read(r.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 o;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 r("_transform()"))},d.prototype._write=function(e,t,n){var a=this._transformState;if(a.writecb=n,a.writechunk=e,a.writeencoding=t,!a.transforming){var r=this._readableState;(a.needTransform||r.needReadable||r.length<r.highWaterMark)&&this._read(r.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,a){(function(){function r(e){var t=this;this.next=null,this.entry=null,this.finish=function(){Q(t,e)}}var s;t.exports=A,A.WritableState=k;var o={deprecate:e("util-deprecate")},i=e("./internal/streams/stream"),c=e("buffer").Buffer,l=a.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,I=m.ERR_STREAM_NULL_VALUES,C=m.ERR_STREAM_WRITE_AFTER_END,S=m.ERR_UNKNOWN_ENCODING,O=p.errorOrDestroy;function T(){}function k(t,n,a){s=s||e("./_stream_duplex"),t=t||{},"boolean"!=typeof a&&(a=n instanceof s),this.objectMode=!!t.objectMode,a&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=f(this,t,"writableHighWaterMark",a),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var o=!1===t.decodeStrings;this.decodeStrings=!o,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){D(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 r(this)}function A(t){var n=this instanceof(s=s||e("./_stream_duplex"));if(!n&&!h.call(A,this))return new A(t);this._writableState=new k(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,t){var a=new C;O(e,a),n.nextTick(t,a)}function E(e,t,a,r){var s;return null===a?s=new I:"string"==typeof a||t.objectMode||(s=new g("chunk",["string","Buffer"],a)),!s||(O(e,s),n.nextTick(r,s),!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,a,r,s){if(!n){var o=R(t,a,r);a!==o&&(n=!0,r="buffer",a=o)}var i=t.objectMode?1:a.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:a,encoding:r,isBuf:n,callback:s,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else M(e,t,!1,i,a,r,s);return c}function M(e,t,n,a,r,s,o){t.writelen=a,t.writecb=o,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new w("write")):n?e._writev(r,t.onwrite):e._write(r,s,t.onwrite),t.sync=!1}function j(e,t,a,r,s){--t.pendingcb,a?(n.nextTick(s,r),n.nextTick(K,e,t),e._writableState.errorEmitted=!0,O(e,r)):(s(r),e._writableState.errorEmitted=!0,O(e,r),K(e,t))}function U(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function D(e,t){var a=e._writableState,r=a.sync,s=a.writecb;if("function"!=typeof s)throw new v;if(U(a),t)j(e,a,r,t,s);else{var o=B(a)||e.destroyed;o||a.corked||a.bufferProcessing||!a.bufferedRequest||N(e,a),r?n.nextTick(x,e,a,o,s):x(e,a,o,s)}}function x(e,t,n,a){n||q(e,t),t.pendingcb--,a(),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 a=t.bufferedRequestCount,s=new Array(a),o=t.corkedRequestsFree;o.entry=n;for(var i=0,c=!0;n;)s[i]=n,n.isBuf||(c=!1),n=n.next,i+=1;s.allBuffers=c,M(e,t,!0,t.length,s,"",o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new r(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&&O(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 a=e._readableState;(!a||a.autoDestroy&&a.endEmitted)&&e.destroy()}return n}function $(e,t,a){t.ending=!0,K(e,t),a&&(t.finished?n.nextTick(a):e.once("finish",a)),t.ended=!0,e.writable=!1}function Q(e,t,n){var a=e.entry;for(e.entry=null;a;){var r=a.callback;t.pendingcb--,r(n),a=a.next}t.corkedRequestsFree.next=e}e("inherits")(A,i),k.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(k.prototype,"buffer",{get:o.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(h=Function.prototype[Symbol.hasInstance],Object.defineProperty(A,Symbol.hasInstance,{value:function(e){return!!h.call(this,e)||this===A&&e&&e._writableState instanceof k}})):h=function(e){return e instanceof this},A.prototype.pipe=function(){O(this,new b)},A.prototype.write=function(e,t,n){var a=this._writableState,r=!1,s=!a.objectMode&&u(e);return s&&!c.isBuffer(e)&&(e=d(e)),"function"==typeof t&&(n=t,t=null),s?t="buffer":t||(t=a.defaultEncoding),"function"!=typeof n&&(n=T),a.ending?_(this,n):(s||E(this,a,e,n))&&(a.pendingcb++,r=P(this,a,s,e,t,n)),r},A.prototype.cork=function(){this._writableState.corked++},A.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.bufferProcessing||!e.bufferedRequest||N(this,e))},A.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(A.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(A.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),A.prototype._write=function(e,t,n){n(new y("_write()"))},A.prototype._writev=null,A.prototype.end=function(e,t,n){var a=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),a.corked&&(a.corked=1,this.uncork()),a.ending||$(this,a,n),this},Object.defineProperty(A.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(A.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),A.prototype.destroy=p.destroy,A.prototype._undestroy=p.undestroy,A.prototype._destroy=function(e,t){t(e)}}).call(this)}).call(this,e("_process"),void 0!==pn?pn:"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 a;function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var s=e("./end-of-stream"),o=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[o];if(null!==t){var n=e[h].read();null!==n&&(e[d]=null,e[o]=null,e[i]=null,t(p(n,!1)))}}function m(e){n.nextTick(f,e)}function g(e,t){return function(n,a){e.then((function(){t[l]?n(p(void 0,!0)):t[u](n,a)}),a)}}var y=Object.getPrototypeOf((function(){})),v=Object.setPrototypeOf((r(a={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,a){n.nextTick((function(){e[c]?a(e[c]):t(p(void 0,!0))}))}));var a,r=this[d];if(r)a=new Promise(g(r,this));else{var s=this[h].read();if(null!==s)return Promise.resolve(p(s,!1));a=new Promise(this[u])}return this[d]=a,a}},Symbol.asyncIterator,(function(){return this})),r(a,"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))}))}))})),a),y),b=function(e){var t,n=Object.create(v,(r(t={},h,{value:e,writable:!0}),r(t,o,{value:null,writable:!0}),r(t,i,{value:null,writable:!0}),r(t,c,{value:null,writable:!0}),r(t,l,{value:e._readableState.endEmitted,writable:!0}),r(t,u,{value:function(e,t){var a=n[h].read();a?(n[d]=null,n[o]=null,n[i]=null,e(p(a,!1))):(n[o]=e,n[i]=t)},writable:!0}),t));return n[d]=null,s(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=n[i];return null!==t&&(n[d]=null,n[o]=null,n[i]=null,t(e)),void(n[c]=e)}var a=n[o];null!==a&&(n[d]=null,n[o]=null,n[i]=null,a(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 a(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,a)}return n}function r(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?a(Object(n),!0).forEach((function(t){s(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):a(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(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 a=t[n];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(e,a.key,a)}}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(){o(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,a=0;n;)h(n.data,t,a),a+=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,a=t.data;for(e-=a.length;t=t.next;){var r=t.data,s=e>r.length?r.length:e;if(s===r.length?a+=r:a+=r.slice(0,e),0==(e-=s)){s===r.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=r.slice(s));break}++n}return this.length-=n,a}},{key:"_getBuffer",value:function(e){var t=l.allocUnsafe(e),n=this.head,a=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var r=n.data,s=e>r.length?r.length:e;if(r.copy(t,t.length-e,0,s),0==(e-=s)){s===r.length?(++a,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=r.slice(s));break}++a}return this.length-=a,t}},{key:u,value:function(e,t){return d(this,r({},t,{depth:0,customInspect:!1}))}}]),e}()},{buffer:17,util:16}],63:[function(e,t,n){(function(e){(function(){function n(t,n){var s=this,i=this._readableState&&this._readableState.destroyed,c=this._writableState&&this._writableState.destroyed;return i||c?(n?n(t):t&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,e.nextTick(o,this,t)):e.nextTick(o,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,(function(t){!n&&t?s._writableState?s._writableState.errorEmitted?e.nextTick(r,s):(s._writableState.errorEmitted=!0,e.nextTick(a,s,t)):e.nextTick(a,s,t):n?(e.nextTick(r,s),n(t)):e.nextTick(r,s)})),this)}function a(e,t){o(e,t),r(e)}function r(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function s(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function o(e,t){e.emit("error",t)}function i(e,t){var n=e._readableState,a=e._writableState;n&&n.autoDestroy||a&&a.autoDestroy?e.destroy(t):e.emit("error",t)}t.exports={destroy:n,undestroy:s,errorOrDestroy:i}}).call(this)}).call(this,e("_process"))},{_process:50}],64:[function(e,t,n){var a=e("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;function r(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,a=new Array(n),r=0;r<n;r++)a[r]=arguments[r];e.apply(this,a)}}}function s(){}function o(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=r(n||s);var c=t.readable||!1!==t.readable&&e.readable,l=t.writable||!1!==t.writable&&e.writable,d=function(){e.writable||h()},u=e._writableState&&e._writableState.finished,h=function(){l=!1,u=!0,c||n.call(e)},p=e._readableState&&e._readableState.endEmitted,f=function(){c=!1,p=!0,l||n.call(e)},m=function(t){n.call(e,t)},g=function(){var t;return c&&!p?(e._readableState&&e._readableState.ended||(t=new a),n.call(e,t)):l&&!u?(e._writableState&&e._writableState.ended||(t=new a),n.call(e,t)):void 0},y=function(){e.req.on("finish",h)};return o(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 a;function r(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var s=e("../../../errors").codes,o=s.ERR_MISSING_ARGS,i=s.ERR_STREAM_DESTROYED;function c(e){if(e)throw e}function l(e){return e.setHeader&&"function"==typeof e.abort}function d(t,n,s,o){o=r(o);var c=!1;t.on("close",(function(){c=!0})),void 0===a&&(a=e("./end-of-stream")),a(t,{readable:n,writable:s},(function(e){if(e)return o(e);c=!0,o()}));var d=!1;return function(e){if(!c&&!d)return d=!0,l(t)?t.abort():"function"==typeof t.destroy?t.destroy():void o(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 a,r=p(t);if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new o("streams");var s=t.map((function(e,n){var o=n<t.length-1;return d(e,o,n>0,(function(e){a||(a=e),e&&s.forEach(u),o||(s.forEach(u),r(a))}))}));return t.reduce(h)}t.exports=f},{"../../../errors":55,"./end-of-stream":64}],67:[function(e,t,n){var a=e("../../../errors").codes.ERR_INVALID_OPT_VALUE;function r(e,t,n){return null!=e.highWaterMark?e.highWaterMark:t?e[n]:null}function s(e,t,n,s){var o=r(t,s,n);if(null!=o){if(!isFinite(o)||Math.floor(o)!==o||o<0)throw new a(s?n:"highWaterMark",o);return Math.floor(o)}return e.objectMode?16:16384}t.exports={getHighWaterMark:s}},{"../../../errors":55}],68:[function(e,t,n){t.exports=e("events").EventEmitter},{events:22}],69:[function(e,t,n){(n=t.exports=e("./lib/_stream_readable.js")).Stream=n,n.Readable=n,n.Writable=e("./lib/_stream_writable.js"),n.Duplex=e("./lib/_stream_duplex.js"),n.Transform=e("./lib/_stream_transform.js"),n.PassThrough=e("./lib/_stream_passthrough.js"),n.finished=e("./lib/internal/streams/end-of-stream.js"),n.pipeline=e("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":56,"./lib/_stream_passthrough.js":57,"./lib/_stream_readable.js":58,"./lib/_stream_transform.js":59,"./lib/_stream_writable.js":60,"./lib/internal/streams/end-of-stream.js":64,"./lib/internal/streams/pipeline.js":66}],70:[function(e,t,n){function a(e,t,n){var a=this;this._callback=e,this._args=n,this._interval=setInterval(e,t,this._args),this.reschedule=function(e){e||(e=a._interval),a._interval&&clearInterval(a._interval),a._interval=setInterval(a._callback,e,a._args)},this.clear=function(){a._interval&&(clearInterval(a._interval),a._interval=void 0)},this.destroy=function(){a._interval&&clearInterval(a._interval),a._callback=void 0,a._interval=void 0,a._args=void 0}}function r(){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 a(arguments[0],arguments[1],e)}t.exports=r},{}],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 a(e){return(e=e||{}).circles?r(e):e.proto?s:a;function t(e,t){for(var a=Object.keys(e),r=new Array(a.length),s=0;s<a.length;s++){var o=a[s],i=e[o];"object"!=typeof i||null===i?r[o]=i:i instanceof Date?r[o]=new Date(i):ArrayBuffer.isView(i)?r[o]=n(i):r[o]=t(i)}return r}function a(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return t(e,a);if(e instanceof Map)return new Map(t(Array.from(e),a));if(e instanceof Set)return new Set(t(Array.from(e),a));var r={};for(var s in e)if(!1!==Object.hasOwnProperty.call(e,s)){var o=e[s];"object"!=typeof o||null===o?r[s]=o:o instanceof Date?r[s]=new Date(o):o instanceof Map?r[s]=new Map(t(Array.from(o),a)):o instanceof Set?r[s]=new Set(t(Array.from(o),a)):ArrayBuffer.isView(o)?r[s]=n(o):r[s]=a(o)}return r}function s(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return t(e,s);if(e instanceof Map)return new Map(t(Array.from(e),s));if(e instanceof Set)return new Set(t(Array.from(e),s));var a={};for(var r in e){var o=e[r];"object"!=typeof o||null===o?a[r]=o:o instanceof Date?a[r]=new Date(o):o instanceof Map?a[r]=new Map(t(Array.from(o),s)):o instanceof Set?a[r]=new Set(t(Array.from(o),s)):ArrayBuffer.isView(o)?a[r]=n(o):a[r]=s(o)}return a}}function r(e){var t=[],a=[];return e.proto?o:s;function r(e,r){for(var s=Object.keys(e),o=new Array(s.length),i=0;i<s.length;i++){var c=s[i],l=e[c];if("object"!=typeof l||null===l)o[c]=l;else if(l instanceof Date)o[c]=new Date(l);else if(ArrayBuffer.isView(l))o[c]=n(l);else{var d=t.indexOf(l);o[c]=-1!==d?a[d]:r(l)}}return o}function s(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return r(e,s);if(e instanceof Map)return new Map(r(Array.from(e),s));if(e instanceof Set)return new Set(r(Array.from(e),s));var o={};for(var i in t.push(e),a.push(o),e)if(!1!==Object.hasOwnProperty.call(e,i)){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(r(Array.from(c),s));else if(c instanceof Set)o[i]=new Set(r(Array.from(c),s));else if(ArrayBuffer.isView(c))o[i]=n(c);else{var l=t.indexOf(c);o[i]=-1!==l?a[l]:s(c)}}return t.pop(),a.pop(),o}function o(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return r(e,o);if(e instanceof Map)return new Map(r(Array.from(e),o));if(e instanceof Set)return new Set(r(Array.from(e),o));var s={};for(var i in t.push(e),a.push(s),e){var c=e[i];if("object"!=typeof c||null===c)s[i]=c;else if(c instanceof Date)s[i]=new Date(c);else if(c instanceof Map)s[i]=new Map(r(Array.from(c),o));else if(c instanceof Set)s[i]=new Set(r(Array.from(c),o));else if(ArrayBuffer.isView(c))s[i]=n(c);else{var l=t.indexOf(c);s[i]=-1!==l?a[l]:o(c)}}return t.pop(),a.pop(),s}}t.exports=a}).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 a=e("buffer"),r=a.Buffer;function s(e,t){for(var n in e)t[n]=e[n]}function o(e,t,n){return r(e,t,n)}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?t.exports=a:(s(a,n),n.Buffer=o),o.prototype=Object.create(r.prototype),s(r,o),o.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return r(e,t,n)},o.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var a=r(e);return void 0!==t?"string"==typeof n?a.fill(t,n):a.fill(t):a.fill(0),a},o.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r(e)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return a.SlowBuffer(e)}},{buffer:17}],74:[function(e,t,n){function a(e){var t=e._readableState;return t?t.objectMode||"number"==typeof e._duplexState?e.read():e.read(r(t)):null}function r(e){return e.buffer.length?e.buffer.head?e.buffer.head.data.length:e.buffer[0].length:e.length}t.exports=a},{}],75:[function(e,t,n){var a=e("safe-buffer").Buffer,r=a.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function s(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}function o(e){var t=s(e);if("string"!=typeof t&&(a.isEncoding===r||!r(e)))throw new Error("Unknown encoding: "+e);return t||e}function i(e){var t;switch(this.encoding=o(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=a.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 a=t.length-1;if(a<n)return 0;var r=c(t[a]);return r>=0?(r>0&&(e.lastNeed=r-1),r):--a<n||-2===r?0:(r=c(t[a]))>=0?(r>0&&(e.lastNeed=r-2),r):--a<n||-2===r?0:(r=c(t[a]))>=0?(r>0&&(2===r?r=0:e.lastNeed=r-3),r):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 a=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,a),e.toString("utf8",t,a)}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 a=n.charCodeAt(n.length-1);if(a>=55296&&a<=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 a=e("punycode"),r=e("./util");function s(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}n.parse=w,n.resolve=C,n.resolveObject=S,n.format=I,n.Url=s;var o=/^([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&&r.isObject(e)&&e instanceof s)return e;var a=new s;return a.parse(e,t,n),a}function I(e){return r.isString(e)&&(e=w(e)),e instanceof s?e.format():s.prototype.format.call(e)}function C(e,t){return w(e,!1,!0).resolve(t)}function S(e,t){return e?w(e,!1,!0).resolveObject(t):t}s.prototype.parse=function(e,t,n){if(!r.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var s=e.indexOf("?"),i=-1!==s&&s<e.indexOf("#")?"?":"#",l=e.split(i),w=/\\/g;l[0]=l[0].replace(w,"/");var I=e=l.join(i);if(I=I.trim(),!n&&1===e.split("#").length){var C=c.exec(I);if(C)return this.path=I,this.href=I,this.pathname=C[1],C[2]?(this.search=C[2],this.query=t?b.parse(this.search.substr(1)):this.search.substr(1)):t&&(this.search="",this.query={}),this}var S=o.exec(I);if(S){var O=(S=S[0]).toLowerCase();this.protocol=O,I=I.substr(S.length)}if(n||S||I.match(/^\/\/[^@\/]+@[^@\/]+/)){var T="//"===I.substr(0,2);!T||S&&y[S]||(I=I.substr(2),this.slashes=!0)}if(!y[S]&&(T||S&&!v[S])){for(var k,A,_=-1,E=0;E<h.length;E++)-1!==(R=I.indexOf(h[E]))&&(-1===_||R<_)&&(_=R);for(-1!==(A=-1===_?I.lastIndexOf("@"):I.lastIndexOf("@",_))&&(k=I.slice(0,A),I=I.slice(A+1),this.auth=decodeURIComponent(k)),_=-1,E=0;E<u.length;E++){var R;-1!==(R=I.indexOf(u[E]))&&(-1===_||R<_)&&(_=R)}-1===_&&(_=I.length),this.host=I.slice(0,_),I=I.slice(_),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=(E=0,M.length);E<j;E++){var U=M[E];if(U&&!U.match(f)){for(var D="",x=0,q=U.length;x<q;x++)U.charCodeAt(x)>127?D+="x":D+=U[x];if(!D.match(f)){var N=M.slice(0,E),B=M.slice(E+1),L=U.match(m);L&&(N.push(L[1]),B.unshift(L[2])),B.length&&(I="/"+B.join(".")+I),this.hostname=N.join(".");break}}}this.hostname.length>p?this.hostname="":this.hostname=this.hostname.toLowerCase(),P||(this.hostname=a.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),"/"!==I[0]&&(I="/"+I))}if(!g[O])for(E=0,j=d.length;E<j;E++){var $=d[E];if(-1!==I.indexOf($)){var Q=encodeURIComponent($);Q===$&&(Q=escape($)),I=I.split($).join(Q)}}var z=I.indexOf("#");-1!==z&&(this.hash=I.substr(z),I=I.slice(0,z));var V=I.indexOf("?");if(-1!==V?(this.search=I.substr(V),this.query=I.substr(V+1),t&&(this.query=b.parse(this.query)),I=I.slice(0,V)):t&&(this.search="",this.query={}),I&&(this.pathname=I),v[O]&&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},s.prototype.format=function(){var e=this.auth||"";e&&(e=(e=encodeURIComponent(e)).replace(/%3A/i,":"),e+="@");var t=this.protocol||"",n=this.pathname||"",a=this.hash||"",s=!1,o="";this.host?s=e+this.host:this.hostname&&(s=e+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(s+=":"+this.port)),this.query&&r.isObject(this.query)&&Object.keys(this.query).length&&(o=b.stringify(this.query));var i=this.search||o&&"?"+o||"";return t&&":"!==t.substr(-1)&&(t+=":"),this.slashes||(!t||v[t])&&!1!==s?(s="//"+(s||""),n&&"/"!==n.charAt(0)&&(n="/"+n)):s||(s=""),a&&"#"!==a.charAt(0)&&(a="#"+a),i&&"?"!==i.charAt(0)&&(i="?"+i),t+s+(n=n.replace(/[?#]/g,(function(e){return encodeURIComponent(e)})))+(i=i.replace("#","%23"))+a},s.prototype.resolve=function(e){return this.resolveObject(w(e,!1,!0)).format()},s.prototype.resolveObject=function(e){if(r.isString(e)){var t=new s;t.parse(e,!1,!0),e=t}for(var n=new s,a=Object.keys(this),o=0;o<a.length;o++){var i=a[o];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),I=w||b||n.host&&e.pathname,C=I,S=n.pathname&&n.pathname.split("/")||[],O=(f=e.pathname&&e.pathname.split("/")||[],n.protocol&&!v[n.protocol]);if(O&&(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),I=I&&(""===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(!r.isNullOrUndefined(e.search))return O&&(n.hostname=n.host=S.shift(),(E=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=E.shift(),n.host=n.hostname=E.shift())),n.search=e.search,n.query=e.query,r.isNull(n.pathname)&&r.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 T=S.slice(-1)[0],k=(n.host||e.host||S.length>1)&&("."===T||".."===T)||""===T,A=0,_=S.length;_>=0;_--)"."===(T=S[_])?S.splice(_,1):".."===T?(S.splice(_,1),A++):A&&(S.splice(_,1),A--);if(!I&&!C)for(;A--;A)S.unshift("..");!I||""===S[0]||S[0]&&"/"===S[0].charAt(0)||S.unshift(""),k&&"/"!==S.join("/").substr(-1)&&S.push("");var E,R=""===S[0]||S[0]&&"/"===S[0].charAt(0);return O&&(n.hostname=n.host=R?"":S.length?S.shift():"",(E=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=E.shift(),n.host=n.hostname=E.shift())),(I=I||n.host&&S.length)&&!R&&S.unshift(""),S.length?n.pathname=S.join("/"):(n.pathname=null,n.path=null),r.isNull(n.pathname)&&r.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n},s.prototype.parseHost=function(){var e=this.host,t=i.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},{"./util":77,punycode:51,querystring:54}],77:[function(e,t,n){t.exports={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}}},{}],78:[function(e,t,n){(function(e){(function(){function n(e,t){if(a("noDeprecation"))return e;var n=!1;function r(){if(!n){if(a("throwDeprecation"))throw new Error(t);a("traceDeprecation")?console.trace(t):console.warn(t),n=!0}return e.apply(this,arguments)}return r}function a(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!==pn?pn:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],79:[function(e,t,n){function a(e,t){if(e&&t)return a(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 a=e.apply(this,t),r=t[t.length-1];return"function"==typeof a&&a!==r&&Object.keys(r).forEach((function(e){a[e]=r[e]})),a}}t.exports=a},{}],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=r;var a=Object.prototype.hasOwnProperty;function r(){for(var e={},t=0;t<arguments.length;t++){var n=arguments[t];for(var r in n)a.call(n,r)&&(e[r]=n[r])}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 a(e){var t=this;if(t instanceof a||(t=new a),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,r=arguments.length;n<r;n++)t.push(arguments[n]);return t}function r(e,t,n){var a=t===e.head?new i(n,null,t,e):new i(n,t,t.next,e);return null===a.next&&(e.tail=a),null===a.prev&&(e.head=a),e.length++,a}function s(e,t){e.tail=new i(t,e.tail,null,e),e.head||(e.head=e.tail),e.length++}function o(e,t){e.head=new i(t,null,e.head,e),e.tail||(e.tail=e.head),e.length++}function i(e,t,n,a){if(!(this instanceof i))return new i(e,t,n,a);this.list=a,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=a,a.Node=i,a.create=a,a.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},a.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++}},a.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++}},a.prototype.push=function(){for(var e=0,t=arguments.length;e<t;e++)s(this,arguments[e]);return this.length},a.prototype.unshift=function(){for(var e=0,t=arguments.length;e<t;e++)o(this,arguments[e]);return this.length},a.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}},a.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}},a.prototype.forEach=function(e,t){t=t||this;for(var n=this.head,a=0;null!==n;a++)e.call(t,n.value,a,this),n=n.next},a.prototype.forEachReverse=function(e,t){t=t||this;for(var n=this.tail,a=this.length-1;null!==n;a--)e.call(t,n.value,a,this),n=n.prev},a.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},a.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},a.prototype.map=function(e,t){t=t||this;for(var n=new a,r=this.head;null!==r;)n.push(e.call(t,r.value,this)),r=r.next;return n},a.prototype.mapReverse=function(e,t){t=t||this;for(var n=new a,r=this.tail;null!==r;)n.push(e.call(t,r.value,this)),r=r.prev;return n},a.prototype.reduce=function(e,t){var n,a=this.head;if(arguments.length>1)n=t;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");a=this.head.next,n=this.head.value}for(var r=0;null!==a;r++)n=e(n,a.value,r),a=a.next;return n},a.prototype.reduceReverse=function(e,t){var n,a=this.tail;if(arguments.length>1)n=t;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");a=this.tail.prev,n=this.tail.value}for(var r=this.length-1;null!==a;r--)n=e(n,a.value,r),a=a.prev;return n},a.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},a.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},a.prototype.slice=function(e,t){(t=t||this.length)<0&&(t+=this.length),(e=e||0)<0&&(e+=this.length);var n=new a;if(t<e||t<0)return n;e<0&&(e=0),t>this.length&&(t=this.length);for(var r=0,s=this.head;null!==s&&r<e;r++)s=s.next;for(;null!==s&&r<t;r++,s=s.next)n.push(s.value);return n},a.prototype.sliceReverse=function(e,t){(t=t||this.length)<0&&(t+=this.length),(e=e||0)<0&&(e+=this.length);var n=new a;if(t<e||t<0)return n;e<0&&(e=0),t>this.length&&(t=this.length);for(var r=this.length,s=this.tail;null!==s&&r>t;r--)s=s.prev;for(;null!==s&&r>e;r--,s=s.prev)n.push(s.value);return n},a.prototype.splice=function(e,t,...n){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);for(var a=0,s=this.head;null!==s&&a<e;a++)s=s.next;var o=[];for(a=0;s&&a<t;a++)o.push(s.value),s=this.removeNode(s);for(null===s&&(s=this.tail),s!==this.head&&s!==this.tail&&(s=s.prev),a=0;a<n.length;a++)s=r(this,s,n[a]);return o},a.prototype.reverse=function(){for(var e=this.head,t=this.tail,n=e;null!==n;n=n.prev){var a=n.prev;n.prev=n.next,n.next=a}return this.head=t,this.tail=e,this};try{e("./iterator.js")(a)}catch(e){}},{"./iterator.js":82}]},{},[12])(12);var yn=fn(gn.exports);class vn{constructor(){this._sessionState="notLoggedIn",this._listener=new Map}onSessionStateChange(e){return this._listener.set(e,e),()=>{this._listener.delete(e)}}setSessionState(e,t){this._sessionState!==e&&(this._sessionState=e,this._listener.forEach((n=>n(e,t))))}destroy(){this._listener.clear()}}let bn;var wn=()=>(bn||(bn=new vn),bn);const In=e=>wn().onSessionStateChange(e),Cn={[e.AmityAutoSubscription.NETWORK]:[zt],[e.AmityAutoSubscription.CHAT]:[Vt,Ht,Jt],[e.AmityAutoSubscription.LIVESTREAM]:[Wt],[e.AmityAutoSubscription.BLOCK]:[Kt,$t]},Sn=[e.AmityAutoSubscription.CHAT,e.AmityAutoSubscription.NETWORK,e.AmityAutoSubscription.LIVESTREAM,e.AmityAutoSubscription.BLOCK],On=Object.values(e.AmityAutoSubscription);class Tn{constructor(){this.refCountByFeature=new Map,this.disposers=new Map,this.seed()}seed(){this.refCountByFeature.clear(),Sn.forEach((e=>this.refCountByFeature.set(e,1)))}isActive(e){var t;return(null!==(t=this.refCountByFeature.get(e))&&void 0!==t?t:0)>0}subscribeTopics(e){this.unsubscribeTopics(e),this.disposers.set(e,Cn[e].map((e=>Gt(e()))))}unsubscribeTopics(e){var t;(null!==(t=this.disposers.get(e))&&void 0!==t?t:[]).forEach((e=>e())),this.disposers.delete(e)}initialize(){On.forEach((e=>{this.isActive(e)&&this.subscribeTopics(e)}))}subscribe(e){var t;const n=(null!==(t=this.refCountByFeature.get(e))&&void 0!==t?t:0)+1;this.refCountByFeature.set(e,n),1===n&&this.subscribeTopics(e)}unsubscribe(e){var t;const n=Math.max(0,(null!==(t=this.refCountByFeature.get(e))&&void 0!==t?t:0)-1);this.refCountByFeature.set(e,n),0===n&&this.unsubscribeTopics(e)}subscriptions(){return On.map((e=>({feature:e,isActive:this.isActive(e),isSystem:!0,topicCount:Cn[e].length})))}reset(){On.forEach((e=>this.unsubscribeTopics(e))),this.disposers.clear(),this.seed()}}let kn=null;const An=()=>(kn||(kn=new Tn),kn);class _n{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 En=()=>"undefined"!=typeof window&&window.localStorage?window:{localStorage:new _n},Rn=async(e,t)=>"undefined"!=typeof navigator&&"ReactNative"===navigator.product?(await I.default.setItem(e,t),!0):new Promise((n=>{En().localStorage.setItem(e,t),n(!0)})),Pn=async e=>{if("undefined"!=typeof navigator&&"ReactNative"===navigator.product){return await I.default.getItem(e)}return new Promise((t=>{t(En().localStorage.getItem(e))}))},Mn=()=>C.default.v4().toString();let jn=0;if("undefined"!=typeof BroadcastChannel&&"undefined"!=typeof window){const e=Mn(),t={},n=new BroadcastChannel("amity_ts_sdk");let a;n.postMessage({type:"startup",tabId:e}),n.onmessage=({data:r})=>{r.tabId!==e&&("startup"===r.type&&n.postMessage({type:"identify",tabId:e,tabIndex:jn}),"identify"===r.type&&void 0!==r.tabIndex&&r.tabId&&(t[r.tabId]=r.tabIndex,a||(a=setTimeout((()=>{const e=Object.values(t).sort();e&&0!==e.length&&(jn=e.reduce(((e,t)=>e<t?e:t+1),0))}),15))))}}const Un=async()=>{var e;const t=`${null!==(e=Ve().prefixDeviceIdKey)&&void 0!==e?e:""}#deviceId`,n=await Pn(t);if(n)return n;const a=`ascWebSdk#${Mn()}`;return await Rn(t,a),a},Dn=()=>{const e=(()=>{var e,t;return(null===(e=Zt.versions)||void 0===e?void 0:e.node)?Zt.versions.node:navigator?`${navigator.product.toLowerCase()}#${null!==(t=navigator.userAgent)&&void 0!==t?t:"unknown_agent"}`:"unknown_model"})();return{kind:"web",model:e,sdkVersion:le}},xn=1e3;var qn;!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"}(qn||(qn={}));const Nn=e=>{let t,n="disconnected";const a=new Set,r=e=>{n!==e&&(n=e,a.forEach((t=>{t(e)})))},s=new Map;function o(e,n,a){const r=(t,r)=>{var i;if(t||128===(null===(i=r[0])||void 0===i?void 0:i.qos))if(n<2){const t=Math.min(2**n*1e3,5e3);console.warn(`Failed to subscribe to topic ${e} (attempt ${n+1}/3). Retrying in ${t}ms.`);const r=setTimeout((()=>{o(e,n+1,a)}),t);s.set(e,{timer:r,callback:a})}else{s.delete(e);const n=t?new Le(t.message,8e5,"error"):new Ke(8e5,"error");console.warn(`Failed to subscribe to topic ${e} after 3 attempts`,n),null==a||a(n)}else s.delete(e),console.log(`Subscribed to topic ${e}`),null==a||a()};t?t.subscribe(e,{qos:0},r):r(new Error("No connection to broker"),[])}return{connect:async function(n){const a=await(async e=>`mqttjs_${await Un()}_${e}_${jn}`)(n.userId);return r("connecting"),t&&(r("disconnecting"),t.removeAllListeners(),t.end(!0)),t=yn.connect(e,function(e){return Object.assign({clean:!1,clientId:`mqttjs_ + ${Math.random().toString(16).substring(2,10)}`,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:xn,resubscribe:!0},e)}({username:n.userId,password:n.accessToken,clientId:a})),t.on("connect",(()=>{t.options.reconnectPeriod=xn,r("connected"),An().initialize()})),t.on("error",(e=>{switch(e.code){case 2:case 134:case 135:t.end(),r("disconnected")}})),t.on("reconnect",(()=>{r("reconnecting"),t.options.reconnectPeriod=Math.min(2*(t.options.reconnectPeriod||xn),8e3)})),t.on("close",(()=>{s.forEach((({timer:e})=>clearTimeout(e))),s.clear()})),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=>(a.add(e),n&&e(n),()=>{a.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,t){return o(e,0,t),()=>this.unsubscribe(e)},unsubscribe(e){var n;const a=s.get(e);if(void 0!==a){clearTimeout(a.timer),s.delete(e);const t=new Le("Subscription retry cancelled due to unsubscribe call",8e5,"error");null===(n=a.callback)||void 0===n||n.call(a,t)}null==t||t.unsubscribe(e)}}},Bn=async()=>{const e=Ve(),{data:t}=await e.http.get("/api/v3/network-settings/chat");return t},Ln=(e={},t,n=!0)=>{Object.entries(e).forEach((([e,a])=>{const r=Ge[e];if(!r)return;const s=We(r);s&&a&&a.forEach((e=>{(n?et:nt)([r,"get",s(e)],e,t)}))}))},Fn=(e,t)=>{const{log:n,cache:a}=Ve(),r=[e,be,t],s={cachedAt:Date.now()};a&&(n("cache/api/pushToTombstone",{cacheKey:r,data:s}),at([e,"get",t],!0),et(r,s))};function Kn(e,t){var n={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&t.indexOf(a)<0&&(n[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(a=Object.getOwnPropertySymbols(e);r<a.length;r++)t.indexOf(a[r])<0&&Object.prototype.propertyIsEnumerable.call(e,a[r])&&(n[a[r]]=e[a[r]])}return n}const $n=(e,t="userId",n="user")=>{var a;return null!==(a=null==e?void 0:e.map((e=>((e,t="userId",n="user")=>e[n]?e:Object.assign({get[n](){var n;if(!Ve().cache)return;return(null===(n=Ze(["user","get",e[t]]))||void 0===n?void 0:n.data)||void 0}},e))(e,t,n))))&&void 0!==a?a:e},Qn=(e,t,n="userId",a="user")=>{const r=e,s=t,o=r[s],i=Kn(r,["symbol"==typeof s?s:s+""]),c=$n(o,n,a);return Object.assign(Object.assign({},i),{[t]:c})};function zn(e){return e.map((e=>{var{isMentioned:t}=e,n=Kn(e,["isMentioned"]);return Object.assign({hasMentioned:t},n)}))}function Vn(e){return zn(e)}function Hn(e){return zn(e)}const Jn=e=>{var t,n;return null!==(n=null===(t=Ze(["messagePreviewChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},Wn=e=>new Date(e).getTime(),Gn=e=>{var t,n;return null!==(n=null===(t=Ze(["messagePreviewSubChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},Yn=e=>{var t;const n=e.messagePreviewId?Gn(e.subChannelId):null,a=n?Object.assign(Object.assign({},n),{user:null===(t=Ze(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data}):null;return Object.assign(Object.assign({},e),{messagePreview:a})},Xn=e=>{var t,n;const a={messagePreviewSubChannel:null!==(n=null===(t=e.messages)||void 0===t?void 0:t.map((t=>(t=>{var n;const a=null===(n=e.messageFeeds)||void 0===n?void 0:n.find((e=>e.messageFeedId===t.messageFeedId)),{channelPublicId:r,messageFeedId:s,messageId:o,creatorPublicId:i,data:c,dataType:l,isDeleted:d,segment:u,createdAt:h,updatedAt:p}=t;return{messagePreviewId:o,channelId:r,subChannelId:s,data:c,dataType:l,isDeleted:d,segment:u,creatorId:i,createdAt:h,updatedAt:p,subChannelName:null==a?void 0:a.name,subChannelUpdatedAt:null==a?void 0:a.updatedAt}})(t))))&&void 0!==n?n:[]};Ln(a)};function Zn(e,t){return Object.create(Object.getPrototypeOf(e),Object.assign(Object.assign({},Object.getOwnPropertyDescriptors(e)),Object.getOwnPropertyDescriptors(t)))}function ea(e,t,n){et(["subChannel","get",e],Zn(t,n))}const ta=(e,t)=>{const{log:n,cache:a}=Ve(),r=[e,be,t];if(!a)return;n("cache/api/isInTombstone",r);const s=Ze(r),{lifeSpan:o}=qe("cache_then_server",18e4);if(s&&De(s.data,o))throw new Fe("Item not found!",400400,"error")},na=e=>{var t;const n=["channelUnreadInfo","get",e],a=null===(t=Ze(n))||void 0===t?void 0:t.data,r=Xe(["subChannelUnreadInfo","get"]);let s=0,o=!1;if(r&&(null==r?void 0:r.length)>0){const t=null==r?void 0:r.filter((({data:t})=>t.channelId===e&&!t.isDeleted));s=t.map((({data:e})=>e.unreadCount)).reduce(((e,t)=>e+t),0),o=t.some((({data:e})=>e.isMentioned))}const i=Object.assign(Object.assign({},null!=a?a:{channelId:e,createdAt:(new Date).toISOString()}),{updatedAt:(new Date).toISOString(),unreadCount:s,isMentioned:o});return et(n,i),i},aa=e=>{const{feedMarkers:t,userFeedMarkers:n}=e;if(t.length>0&&n.length>0){const e=[],a=new Map(t.map((e=>[e.feedId,e])));n.forEach((t=>{const n=a.get(t.feedId);if(n&&n.feedId===t.feedId){const a=n.lastSegment-t.readToSegment,r={subChannelId:n.feedId,channelId:n.entityId,readToSegment:t.readToSegment,lastSegment:n.lastSegment,lastMentionSegment:t.lastMentionSegment,unreadCount:Math.max(0,a),isMentioned:t.isMentioned,isDeleted:n.isDeleted,createdAt:t.createdAt,updatedAt:t.updatedAt};Ln({subChannelUnreadInfo:[r]}),e.includes(n.entityId)||e.push(n.entityId)}})),e.forEach((e=>{na(e)}))}},ra=async()=>{const e=Ve();e.log("channel/getUserMarker");const{data:t}=await e.http.get("/api/v1/markers/userMarker"),{userMarkers:n}=t,a=e.cache&&Date.now();e.cache&&Ln({userMarkers:n},{cachedAt:a}),jt("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:a}},sa=e=>{var t,n;const a=null===(t=Ze(["message","get",e]))||void 0===t?void 0:t.data;if(a)return a;const r=Xe(["message","get"]);return null===(n=null==r?void 0:r.find((({data:t})=>t.messageId===e)))||void 0===n?void 0:n.data},oa=e=>!0===e&&void 0;function ia(e,t,n){var a,r;if(n)return n.hasMentioned;const s=Ve();if(s.isUnreadCountEnabled&&s.getMarkerSyncConsistentMode()){const e=null===(a=Ze(["subChannelUnreadInfo","get",t]))||void 0===a?void 0:a.data;return!!e&&e.isMentioned}const o={entityId:e,feedId:t,userId:kt()._id},i=null===(r=Ze(["subChannelMarker","get",We("subChannelMarker")(o)]))||void 0===r?void 0:r.data;return!!i&&i.hasMentioned}const ca=["broadcast","conversation","community"],la=({channelType:e})=>ca.includes(e);function da(e){var{channelId:t,channelPublicId:n,channelType:a,childCount:r,creatorId:s,creatorPublicId:o,lastMessageId:i,lastMessageTimestamp:c,messageFeedId:l,name:d}=e,u=Kn(e,["channelId","channelPublicId","channelType","childCount","creatorId","creatorPublicId","lastMessageId","lastMessageTimestamp","messageFeedId","name"]);return Object.assign(Object.assign({get unreadCount(){return function(e,t,n){var a,r;if(n)return n.unreadCount;const s=Ve();if(s.isUnreadCountEnabled&&s.getMarkerSyncConsistentMode()){const e=null===(a=Ze(["subChannelUnreadInfo","get",t]))||void 0===a?void 0:a.data;return e?e.isDeleted?0:e.unreadCount:0}const o={entityId:e,feedId:t,userId:kt()._id},i=null===(r=Ze(["subChannelMarker","get",We("subChannelMarker")(o)]))||void 0===r?void 0:r.data;return i?i.unreadCount:0}(t,l)},get hasMentioned(){return ia(t,l)},get isMentioned(){return ia(t,l)}},u),{channelId:n,creatorId:o,displayName:d,lastActivity:c,latestMessageId:i,messageCount:r,subChannelId:l,isUnreadCountSupport:la({channelType:a})})}function ua(e,t,n){var a;const r=(e=>{var t,n,a;const r=null===(n=null===(t=Xe(["message","get"]))||void 0===t?void 0:t.find((({data:t})=>t.messageId===e.messageId)))||void 0===n?void 0:n.data;return r?Object.assign(Object.assign(Object.assign({},r),e),{referenceId:null!==(a=r.referenceId)&&void 0!==a?a:e.referenceId}):e})(e),{channelPublicId:s,childCount:o,creatorPublicId:i,mentionedUsers:c,messageFeedId:l,myReactions:d,reactionCount:u,reactions:h,referenceId:p,segment:f,messageId:m,creatorId:g}=r,y=Kn(r,["channelPublicId","childCount","creatorPublicId","mentionedUsers","messageFeedId","myReactions","reactionCount","reactions","referenceId","segment","messageId","creatorId"]);let v;p&&(v=Ze(["message","get",p])),v||(v=Ze(["message","get",m]));const b=Object.assign(Object.assign({},y),{messageId:m,channelId:s,channelSegment:f,childrenNumber:o,creatorId:i,creatorPrivateId:e.creatorId,reactions:null!=h?h:{},myReactions:d||(null!==(a=null==v?void 0:v.data.myReactions)&&void 0!==a?a:[]),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 a=Ve(),r=sa(e.messageId),s=(null==r?void 0:r.myReactions)||[];Object.assign(e,{myReactions:s});const o=t[0];o&&o.userId===a.userId&&("message.reactionAdded"!==n||s.includes(o.reactionName)||Object.assign(e,{myReactions:[...s,o.reactionName]}),"message.reactionRemoved"===n&&s.includes(o.reactionName)&&Object.assign(e,{myReactions:s.filter((e=>e!==o.reactionName))}))})(b,t,n),b}const ha={},pa=async(e,t)=>{const n=e.messages.map((({messageId:e})=>e));if(n.length>0){Ln({messages:(a=e).messages.map((e=>ua(e,a.reactions)))});const t=n.join("");ha[t]&&clearTimeout(ha[t]),ha[t]=setTimeout((()=>{try{(async e=>{const t=Ve();t.log("channel/getMessageMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/messages",{params:{messageIds:e}}),{contentMarkers:a,feedMarkers:r,userMarkers:s}=n,o=t.cache&&Date.now();t.cache&&Ln({contentMarkers:a,feedMarkers:r,userMarkers:s},{cachedAt:o}),jt("local.feedMarker.fetched",{feedMarkers:r}),jt("local.messageMarker.fetched",{contentMarkers:a}),jt("local.userMarker.fetched",{userMarkers:s})})(n)}catch(e){}}),2e3)}var a;const{messageFeeds:r}=e,s=Kn(e,["messageFeeds"]);return r&&r.length>0&&(null==r||r.forEach((e=>{var t,n;const a=null!==(n=null===(t=Ze(["subChannel","get",e.messageFeedId]))||void 0===t?void 0:t.data)&&void 0!==n?n:{},r=Kn(da(e),["unreadCount","isMentioned"]);ea(e.messageFeedId,a,r)}))),Object.assign(Object.assign({},s),{messages:e.messages.map((n=>ua(n,e.reactions,t)))})};function fa(e){var{subChannelId:t,mentionees:n,dataType:a,data:r}=e,s=Kn(e,["subChannelId","mentionees","dataType","data"]);return a===N.IMAGE||a===N.FILE?Object.assign({messageFeedId:t,mentionedUsers:n,dataType:a,data:Object.assign({caption:""},r)},s):Object.assign({messageFeedId:t,mentionedUsers:n,dataType:a,data:r},s)}function ma(e){var{sortBy:t,subChannelId:n,includingTags:a,excludingTags:r,includeDeleted:s,aroundMessageId:o,limit:i,type:c}=e,l=Kn(e,["sortBy","subChannelId","includingTags","excludingTags","includeDeleted","aroundMessageId","limit","type"]);const d=Object.assign(Object.assign({},l),{messageFeedId:n,isDeleted:oa(s),options:{sortBy:t,limit:i||de,around:o}});return a&&(d.includeTags=a),c&&(d.dataType=c),r&&(d.excludeTags=r),d}function ga(e){return Object.assign(Object.assign({},e),{isGlobalBanned:(null==e?void 0:e.isGlobalBan)||!1})}const ya=["broadcast","conversation","community"],va=({channelType:e})=>ya.includes(e),ba=async e=>{const t=e.messageFeeds.filter(va).map((({messageFeedId:e})=>e));if(t.length>0){(e=>{Ln({messageFeeds:e.messageFeeds.map((e=>da(e)))})})(e);try{await(async(e,t={limit:100})=>{const n=Ve();n.log("channel/getSubChannelMarkers",e,t);const{data:a}=await n.http.get("/api/v1/markers/message-feeds",{params:{messageFeedIds:e,options:{token:Ee(t,"skiplimit")}}}),{paging:r}=a,s=Kn(a,["paging"]),{userEntityMarkers:o,userFeedMarkers:i,userMarkers:c,feedMarkers:l}=s;n.isUnreadCountEnabled&&n.getMarkerSyncConsistentMode()&&aa({feedMarkers:l,userFeedMarkers:i});const d=Vn(o),u=Hn(i),h=n.cache&&Date.now();n.cache&&Ln({userEntityMarkers:d,userFeedMarkers:u,userMarkers:c},{cachedAt:h}),jt("local.channelMarker.fetched",{userEntityMarkers:d}),jt("local.subChannelMarker.fetched",{userFeedMarkers:u}),jt("local.userMarker.fetched",{userMarkers:c});const p=Re(r.next);return{data:u,cachedAt:h,prevPage:Re(r.previous),nextPage:p}})(t)}catch(e){}}Xn(e);const n=e.messageFeeds.map(da),a=e.messages.map((e=>ua(e))),r=e.users.map(ga);return Object.assign(Object.assign({},e),{messageFeeds:n,messages:a,users:r})};const wa=async e=>{const t=Ve();t.log("channel/getSubChannel",e),ta("subChannel",e);try{const n=await t.http.get(`/api/v5/message-feeds/${encodeURIComponent(e)}`),a=await ba(n.data),r=t.cache&&Date.now();return t.cache&&Ln(a,{cachedAt:r}),jt("local.message-feed.fetched",a),{data:a.messageFeeds[0],cachedAt:r}}catch(t){throw Oe(null==t?void 0:t.code)&&Fn("subChannel",e),t}};wa.locally=e=>{const t=Ve();if(t.log("channel/getSubChannel.locally",e),!t.cache)return;const n=Ze(["subChannel","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Ia=async e=>{var t;let n=null===(t=Ze(["subChannel","get",e]))||void 0===t?void 0:t.data;return n||(n=(await wa(e)).data),n},Ca=async e=>{const t=await(async()=>Ve().getMessagePreviewSetting(!1))(),{channelId:n,messageId:a,creatorId:r,createdAt:s,updatedAt:o,data:i,dataType:c,subChannelId:l,channelSegment:d,isDeleted:u}=e,h=await Ia(l);"no-message-preview"!==t?(e=>{var t;const n=null===(t=Ze(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;return!n||n.segment<=e.channelSegment||Wn(n.createdAt)<=Wn(e.createdAt)})(e)&&(et(["messagePreviewSubChannel","get",e.subChannelId],{channelId:n,creatorId:r,messagePreviewId:a,createdAt:s,updatedAt:o,subChannelId:l,data:i,dataType:c,segment:d,isDeleted:u,subChannelUpdatedAt:null==h?void 0:h.updatedAt,subChannelName:null==h?void 0:h.displayName}),ea(e.subChannelId,h,{lastActivity:s,messagePreviewId:a})):Wn(h.lastActivity)<Wn(s)&&ea(e.subChannelId,h,{lastActivity:s})},Sa=async e=>{var t;const{channelId:n,messageId:a,creatorId:r,createdAt:s,updatedAt:o,data:i,dataType:c,subChannelId:l,channelSegment:d,isDeleted:u}=e,h=null===(t=Ze(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await Ia(l);et(["messagePreviewSubChannel","get",e.subChannelId],{channelId:n,creatorId:r,messagePreviewId:a,createdAt:s,updatedAt:o,subChannelId:l,data:i,dataType:c,segment:d,isDeleted:u,subChannelUpdatedAt:t.updatedAt,subChannelName:h.subChannelName})}},Oa=async e=>{const{channelId:t,messageId:n,creatorId:a,createdAt:r,updatedAt:s,data:o,dataType:i,subChannelId:c,channelSegment:l,isDeleted:d}=e;if((e=>{var t;const n=null===(t=Ze(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;return!n||Wn(n.createdAt)<=Wn(e.createdAt)})(e)){const u=await Ia(c);et(["messagePreviewChannel","get",e.channelId],{channelId:t,creatorId:a,messagePreviewId:n,createdAt:r,updatedAt:s,subChannelId:c,data:o,dataType:i,segment:l,isDeleted:d,subChannelUpdatedAt:null==u?void 0:u.updatedAt,subChannelName:null==u?void 0:u.displayName})}},Ta=async e=>{var t;const{channelId:n,messageId:a,creatorId:r,createdAt:s,updatedAt:o,data:i,dataType:c,subChannelId:l,channelSegment:d,isDeleted:u}=e,h=null===(t=Ze(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await Ia(l);et(["messagePreviewChannel","get",e.channelId],{channelId:n,creatorId:r,messagePreviewId:a,createdAt:s,updatedAt:o,subChannelId:l,data:i,dataType:c,segment:d,isDeleted:u,subChannelUpdatedAt:t.updatedAt,subChannelName:h.subChannelName})}},ka=async e=>{var t,n,a,r;const{channelId:s,subChannelId:o}=e,i=null===(t=Ze(["messagePreviewChannel","get",s]))||void 0===t?void 0:t.data;if((null==i?void 0:i.subChannelId)===o){const e=null===(n=Ze(["subChannel","get",o]))||void 0===n?void 0:n.data;et(["messagePreviewChannel","get",s],Object.assign(Object.assign({},i),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}const c=null===(a=Ze(["messagePreviewSubChannel","get",o]))||void 0===a?void 0:a.data;if(c&&new Date(c.updatedAt).valueOf()>new Date(e.updatedAt).valueOf()){const e=null===(r=Ze(["subChannel","get",o]))||void 0===r?void 0:r.data;et(["messagePreviewSubChannel","get",o],Object.assign(Object.assign({},c),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}},Aa=["broadcast","conversation","community"],_a=({type:e})=>Aa.includes(e);function Ea(e,t={isMessagePreviewUpdated:!0}){var n;let{messagePreviewId:a}=e;const r=null===(n=Ze(["messagePreviewChannel","get",e.channelId]))||void 0===n?void 0:n.data;return(null==r?void 0:r.messagePreviewId)&&!t.isMessagePreviewUpdated&&(a=r.messagePreviewId),Object.assign(Object.assign({},e),{defaultSubChannelId:e.channelInternalId,isUnreadCountSupport:_a(e),messagePreviewId:a})}const Ra=(e,t={isMessagePreviewUpdated:!0})=>{Ln({channels:e.channels.map((e=>Ea(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated})))})},Pa=async(e,t={isMessagePreviewUpdated:!0})=>{const n=Ve(),a=await n.getMessagePreviewSetting(!1);if(t.isMessagePreviewUpdated&&"no-message-preview"!==a&&e.messagePreviews&&e.messagePreviews.length>0&&(e=>{var t;const n=(null!==(t=e.messagePreviews)&&void 0!==t?t:[]).map((t=>{var n;const a=null===(n=e.messageFeedsInfo)||void 0===n?void 0:n.find((e=>e.messageFeedId===t.messageFeedId)),{channelPublicId:r,messageFeedId:s,data:o,dataType:i,isDeleted:c,segment:l,creatorPublicId:d,createdAt:u,updatedAt:h}=t;return{channelId:r,subChannelId:s,data:o,dataType:i,isDeleted:c,segment:l,creatorId:d,createdAt:u,updatedAt:h,subChannelName:null==a?void 0:a.name,messagePreviewId:null==a?void 0:a.messagePreviewId,subChannelUpdatedAt:null==a?void 0:a.updatedAt}})).filter((e=>{var t;const n=null===(t=Ze(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;return!n||Wn(n.createdAt)<=Wn(e.createdAt)}));0!==n.length&&Ln({messagePreviewChannel:n})})(e),n.useLegacyUnreadCount)(({currentUserId:e,channels:t,channelUsers:n})=>{var a,r;const s=[];for(let o=0;o<t.length;o+=1)if(_a(t[o])){const i=["channelUnread","get",t[o].channelId],c=n.find((n=>n.channelId===t[o].channelId&&n.userId===e)),l=null===(a=Ze(i))||void 0===a?void 0:a.data,d=Math.max(null!==(r=null==l?void 0:l.lastSegment)&&void 0!==r?r:0,t[o].messageCount);let u=null,h=null,p=0,f=!1;if(c){const e=c.readToSegment,t=c.lastMentionedSegment;u="number"==typeof(null==l?void 0:l.readToSegment)&&("number"!=typeof e||l.readToSegment>e)?l.readToSegment:null!=e?e:null,h="number"==typeof(null==l?void 0:l.lastMentionedSegment)&&("number"!=typeof t||l.lastMentionedSegment>t)?l.lastMentionedSegment:null!=t?t:null;const n=null!=u?u:0;p=Math.max(d-n,0),f="number"==typeof h&&n<h}const m={channelId:t[o].channelId,lastSegment:d,readToSegment:u,lastMentionedSegment:h,unreadCount:p,isMentioned:f,isDeleted:t[o].isDeleted||!1};et(i,m),s.push(m)}s.length>0&&jt("local.channelUnread.updated",s)})({channels:e.channels,channelUsers:e.channelUsers,currentUserId:n.userId});else{const n=e.channels.filter(_a).map((({channelInternalId:e})=>e));if(n.length>0){Ra(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated});try{await(async e=>{const t=Ve();t.log("channel/getChannelMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/channels",{params:{channelIds:e}}),{userEntityMarkers:a,userMarkers:r}=n,s=Vn(a),o=t.cache&&Date.now();return t.cache&&Ln({userEntityMarkers:s,userMarkers:r},{cachedAt:o}),jt("local.channelMarker.fetched",{userEntityMarkers:s}),jt("local.userMarker.fetched",{userMarkers:r}),{data:s,cachedAt:o}})(n)}catch(e){}}}const r=e.channels.map((e=>Ea(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated}))),s=e.channelUsers.map((e=>{return t=e,Object.assign(Object.assign({},t),{get user(){var e;if(Ve().cache)return(null===(e=Ze(["user","get",t.userId]))||void 0===e?void 0:e.data)||void 0}});var t})),o=e.users.map(ga),i=Kn(e,["messageFeedsInfo","messagePreviews"]);return Object.assign(Object.assign({},i),{users:o,channels:r,channelUsers:s})},Ma=async e=>{const t=Ve();t.log("channel/getUserMessageFeedMakers",e);const{data:n}=await t.http.get("/api/v1/markers/user-message-feed",{params:{channelIds:e}});return jt("local.userMessageFeedMarker.fetched",{userMessageFeedMarker:n}),n},ja=async e=>{const t=Ve(),n=await Ma(e.channels.map((({channelInternalId:e})=>e))),{feedMarkers:a,userFeedMarkers:r}=n;aa({feedMarkers:a,userFeedMarkers:r}),t.log("channel/prepareUnreadCountInfo",e.channels)},Ua=(e,t)=>{var n,a,r,s;const o=Ve();return o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()?null!==(a=null===(n=(e=>{var t;return null===(t=Ze(["channelUnreadInfo","get",e]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===n?void 0:n.isMentioned)&&void 0!==a&&a:void 0!==(null==t?void 0:t.hasMentioned)?null==t?void 0:t.hasMentioned:null!==(s=null===(r=(e=>{var t;const n={entityId:e,userId:kt()._id};return null===(t=Ze(["channelMarker","get",We("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===r?void 0:r.hasMentioned)&&void 0!==s&&s},Da=(e,t)=>{var n,a,r,s,o;const i=Ve();return i.isUnreadCountEnabled&&i.getMarkerSyncConsistentMode()?null!==(a=null===(n=(e=>{var t;return null===(t=Ze(["channelUnreadInfo","get",e]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===n?void 0:n.unreadCount)&&void 0!==a?a:0:(null==t?void 0:t.isDeleted)?0:null!==(o=null!==(r=null==t?void 0:t.unreadCount)&&void 0!==r?r:null===(s=(e=>{var t;const n={entityId:e,userId:kt()._id};return null===(t=Ze(["channelMarker","get",We("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===s?void 0:s.unreadCount)&&void 0!==o?o:0},xa=e=>{var t;return null===(t=Ze(["channelUnread","get",e]))||void 0===t?void 0:t.data},qa=e=>{const t=Ve(),n=Kn(e,["messageCount"]);return Zn(n,{get unreadCount(){var e,t;return null!==(t=null===(e=xa(n.channelId))||void 0===e?void 0:e.unreadCount)&&void 0!==t?t:0},get subChannelsUnreadCount(){return Da(n)},get isMentioned(){var e,a;return t.useLegacyUnreadCount?null!==(a=null===(e=xa(n.channelId))||void 0===e?void 0:e.isMentioned)&&void 0!==a&&a:Ua(n)}})},Na=e=>Object.assign(Object.assign({},e),{get user(){return(()=>{var t;const n=["user","get",e.userId],a=null===(t=Ze(n))||void 0===t?void 0:t.data;return a?qt(a):void 0})()}}),Ba=e=>{const t=Ve();t.log("channel/getMyMembership.locally");const n=Ze(["channelUsers","get",`${e}#${t.userId}`]);if(!n)throw new Fe("Item not found!",400400,"error");return{data:n.data,cachedAt:n.cachedAt}};function La(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(!La(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=>La(e[n],t[n])))}const Fa=[];let Ka=null;const $a=e=>{if(0===Fa.length){const e=Ve();Ka=Mt(e,"onChannelCreated","channel.created",(async e=>{const t=await Pa(e);Ln(t),Fa.forEach((e=>e(t.channels[0])))}))}return Fa.push(e),()=>(e=>{const t=Fa.indexOf(e);t>-1&&Fa.splice(t,1),0===Fa.length&&(null==Ka||Ka())})(e)},Qa=[],za=[],Va=e=>{const t=Ve();if(0===Qa.length){const e=async e=>{const t=await Pa(e);Ln(t),Qa.forEach((e=>e(t.channels[0])))};za.push(Mt(t,"onChannelUpdated","channel.updated",e)),za.push(Mt(t,"onChannelUpdated","local.channel.updated",(e=>Qa.forEach((t=>t(e.channels[0]))))))}return Qa.push(e),()=>(e=>{const t=Qa.indexOf(e);t>-1&&Qa.splice(t,1),0===Qa.length&&za.forEach((e=>e()))})(e)},Ha=e=>{const t=Xe(["subChannelUnreadInfo","get"]);if(t){(null==t?void 0:t.filter((({data:t})=>t.channelId===e))).forEach((({key:e,data:t})=>{et(e,Object.assign(Object.assign({},t),{isDeleted:!0}))}))}},Ja=e=>{var t;const n=["channelUnreadInfo","get",e];(null===(t=Ze(n))||void 0===t?void 0:t.data)&&at(n)},Wa=[];let Ga=null;const Ya=e=>{if(0===Wa.length){const e=Ve(),t=async t=>{const n=await Pa(t),a=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,r=e.useLegacyUnreadCount;n.channels.forEach((e=>{if(a)Ha(e.channelId),Ja(e.channelId);else if(r){const t=["channelUnread","get",e.channelId],n=Ze(t);n&&et(t,Object.assign(Object.assign({},n),{isDeleted:!0}))}})),Ln(n),Wa.forEach((e=>e(n.channels[0])))};Ga=Mt(e,"onChannelDeleted","channel.deleted",t)}return Wa.push(e),()=>(e=>{const t=Wa.indexOf(e);t>-1&&Wa.splice(t,1),0===Wa.length&&(null==Ga||Ga())})(e)},Xa=[];let Za=null;const er=e=>{if(0===Xa.length){const e=Ve();Za=Mt(e,"onChannelJoined","channel.joined",(async e=>{const t=await Pa(e),{channels:n,channelUsers:a}=t;Ln(t),Xa.forEach((e=>e(n[0],a[0])))}))}return Xa.push(e),()=>(e=>{const t=Xa.indexOf(e);t>-1&&Xa.splice(t,1),0===Xa.length&&(null==Za||Za())})(e)},tr=[];let nr=null;const ar=e=>{if(0===tr.length){const e=Ve(),t=async t=>{const{userId:n}=Ve(),{channelUsers:a}=t,r=a.some((e=>e.userId===n)),s=await Pa(t,{isMessagePreviewUpdated:r}),o=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,i=e.useLegacyUnreadCount;r&&s.channels.forEach((e=>{o?(Ha(e.channelId),Ja(e.channelId)):i&&at(["channelUnread","get",e.channelId])}));const{channels:c,channelUsers:l}=s;Ln(s),tr.forEach((e=>e(c[0],l[0])))};nr=Mt(e,"onChannelLeft","channel.left",t)}return tr.push(e),()=>(e=>{const t=tr.indexOf(e);t>-1&&tr.splice(t,1),0===tr.length&&(null==nr||nr())})(e)},rr=[];let sr=null;const or=e=>{if(0===rr.length){const e=Ve(),t=async e=>{var t;nt(["channel","get",e.channelId],{isMuted:Date.parse(e.muteTimeout)>Date.now()});const n=null===(t=Ze(["channel","get",e.channelId]))||void 0===t?void 0:t.data;n&&rr.forEach((e=>e(n)))};sr=Mt(e,"onChannelMute","channel.setMuted",t)}return rr.push(e),()=>(e=>{const t=rr.indexOf(e);t>-1&&rr.splice(t,1),0===rr.length&&(null==sr||sr())})(e)},ir=[];let cr=null;const lr=e=>{if(0===ir.length){const e=Ve();cr=Mt(e,"onChannelMemberAdded","channel.membersAdded",(async e=>{const t=await Pa(e),{channels:n,channelUsers:a}=t;Ln(t),ir.forEach((e=>e(n[0],a.find((e=>"member"===e.membership)))))}))}return ir.push(e),()=>(e=>{const t=ir.indexOf(e);t>-1&&ir.splice(t,1),0===ir.length&&(null==cr||cr())})(e)},dr=[];let ur=null;const hr=e=>{if(0===dr.length){const e=Ve();ur=Mt(e,"onChannelMemberRemoved","channel.membersRemoved",(async e=>{const t=await Pa(e),{channels:n,channelUsers:a}=t;Ln(t),dr.forEach((e=>e(n[0],a[0])))}))}return dr.push(e),()=>(e=>{const t=dr.indexOf(e);t>-1&&dr.splice(t,1),0===dr.length&&(null==ur||ur())})(e)},pr=[];let fr=null;const mr=e=>{const t=Ve();return fr=Mt(t,"onChannelMemberBanned","channel.banned",(async e=>{const n=await Pa(e),{channels:a,channelUsers:r}=n,s=r.some((e=>"banned"===e.membership&&e.userId===t.userId));t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&s&&n.channels.forEach((e=>{Ha(e.channelId),Ja(e.channelId)})),Ln(n),pr.forEach((e=>e(a[0],r.find((e=>"banned"===e.membership)))))})),pr.push(e),()=>(e=>{const t=pr.indexOf(e);t>-1&&pr.splice(t,1),0===pr.length&&(null==fr||fr())})(e)},gr=[];let yr=null;const vr=e=>{if(0===gr.length){const e=Ve();yr=Mt(e,"onChannelMemberUnbanned","channel.unbanned",(async e=>{const t=await Pa(e),{channels:n,channelUsers:a}=t;Ln(t),gr.forEach((e=>e(n[0],a.find((e=>"none"===e.membership)))))}))}return gr.push(e),()=>(e=>{const t=gr.indexOf(e);t>-1&&gr.splice(t,1),0===gr.length&&(null==yr||yr())})(e)},br=[];let wr=null;const Ir=e=>{if(0===br.length){const e=Ve();wr=Mt(e,"onChannelMemberRoleAdded","local.channel-moderator.role-added",(async e=>{const{channels:t,channelUsers:n}=e;br.forEach((e=>e(t[0],n.find((e=>"member"===e.membership)))))}))}return br.push(e),()=>(e=>{const t=br.indexOf(e);t>-1&&br.splice(t,1),0===br.length&&(null==wr||wr())})(e)},Cr=[];let Sr=null;const Or=e=>{if(0===Cr.length){const e=Ve();Sr=Mt(e,"onChannelMemberRoleRemoved","local.channel-moderator.role-removed",(async e=>{const{channels:t,channelUsers:n}=e;Cr.forEach((e=>e(t[0],n.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==Sr||Sr())})(e)},Tr=e=>{const t=Ve();return Mt(t,"onChannelArchived","local.channel.archived",(async t=>{e(t)}))},kr=e=>{const t=Ve();return Mt(t,"onChannelUnarchived","local.channel.unarchived",(async t=>{e(t)}))},Ar=[];let _r=null;const Er=e=>{if(0===Ar.length){const e=Ve(),t=async e=>{var t,n,a;e.userIds.forEach((t=>nt(["channelUsers","get",`${e.channelId}#${t}`],{isMuted:Date.parse(e.muteTimeout)>Date.now()})));const r=null===(n=null===(t=Xe(["channel","get"]))||void 0===t?void 0:t.find((({data:t})=>t.channelPublicId===e.channelId)))||void 0===n?void 0:n.data,s=null===(a=Ze(["channelUsers","get",`${e.channelId}#${e.userIds[0]}`]))||void 0===a?void 0:a.data;r&&s&&Ar.forEach((e=>e(r,s)))};_r=Mt(e,"onChannelUserMute","channel.setMutedUsers",t)}return Ar.push(e),()=>(e=>{const t=Ar.indexOf(e);t>-1&&Ar.splice(t,1),0===Ar.length&&(null==_r||_r())})(e)},Rr=e=>{var t;let n=[];if(["conversation","community"].includes(e.type)){const a=Xe(["channelUsers","get"]);a&&(null==a?void 0:a.length)>0&&(n=(null!==(t=null==a?void 0:a.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})=>Na(e))))}return Zn(e,{markAsRead:()=>(async e=>{const t=Ve();t.log("channel/markAsRead",e);const{data:n}=await t.http.put(`/api/v1/markers/channels/${e}/mark-read`),{userMarkers:a,userEntityMarkers:r,userFeedMarkers:s}=n,o=Kn(n,["userMarkers","userEntityMarkers","userFeedMarkers"]),i=t.cache&&Date.now(),c=Vn(r),l=Hn(s);return t.cache&&Ln(Object.assign({userMarkers:a,userEntityMarkers:c,userFeedMarkers:l},o),{cachedAt:i}),jt("local.channelMarker.updated",{userEntityMarkers:c}),jt("local.subChannelMarker.updated",{userFeedMarkers:l}),!0})(e.channelInternalId),previewMembers:n,myMembership:t=>((e,t)=>{const{_id:n}=kt();if(!n)throw new Le("The _id has not been defined in ActiveUser",8e5,"error");const{log:a,cache:r}=Ve();r||console.log("This observable object need the cache data!"),a(`liveMymembership(tmpid: ${Date.now()}) > listen`);const s=[];let o=!1;const i=e=>{t(Object.assign(Object.assign({},e),{data:e.data?Na(e.data):e.data}))},c=(t,n)=>{const{data:a}=Ba(e);La(void 0,a)||i({loading:!1,data:a})};return s.push(mr(c)),s.push(vr(c)),s.push(Er(c)),(()=>{const t=xe((async()=>Ba(e)));Ne(t,(({error:e,data:t,loading:n,origin:a,cachedAt:r})=>{r===me?(i({data:t,origin:a,loading:!1,error:new Fe(fe,800800,"error")}),o=!0,s.forEach((e=>e()))):o||i({loading:n,data:t,origin:a,error:e}),e&&s.forEach((e=>e()))}))})(),()=>{s.forEach((e=>e()))}})(e.channelId,t),get avatar(){var t;if(!e.avatarFileId)return;return null===(t=Ze(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}})},Pr=e=>Rr(qa((e=>{var t;const n=e.messagePreviewId?Jn(e.channelId):null,a=null===(t=Ze(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data,r=n?Object.assign(Object.assign({},n),{user:a?qt(a):void 0}):null;return Object.assign(Object.assign({},e),{messagePreview:r})})(e))),Mr=async e=>{const t=Ve();t.log("channel/getChannelByIds",e);const n=e.map((e=>encodeURIComponent(e)));let a;try{a=(await t.http.get("/api/v3/channels/list",{params:{channelIds:n}})).data}catch(t){throw e.forEach((e=>{Oe(null==t?void 0:t.code)&&Fn("channel",e)})),t}const r=await Pa(a);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await ja(a);const s=t.cache&&Date.now();return t.cache&&Ln(r,{cachedAt:s}),jt("local.channel.fetched",r.channels),{data:r.channels.map((e=>Pr(e))),cachedAt:s}};Mr.locally=e=>{var t,n;const a=Ve();if(a.log("channel/getChannelByIds.locally",e),!a.cache)return;const r=null===(t=Xe(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!r||(null==r?void 0:r.length)<e.length)return;const s=r.map((({data:e})=>e)),o=null===(n=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0];return{data:s.map((e=>Pr(e))),cachedAt:o.cachedAt}};const jr=(e,t)=>{const n=setInterval(e,t);return()=>clearInterval(n)};let Ur=!1;const Dr={},xr=async()=>{const e=Object.entries(Dr).filter((([,e])=>e)).map((([e])=>e));return 0!==e.length&&(async e=>{const t=Ve();t.log("subChannel/readingAPI",e);const{data:n}=await t.http.post("/api/v1/markers/message-feeds/reading",{messageFeedIds:e}),{userEntityMarkers:a,userFeedMarkers:r,feedMarkers:s,userMarkers:o}=n,i=Vn(a),c=Hn(r),l=t.cache&&Date.now();return t.cache&&Ln({userEntityMarkers:i,userFeedMarkers:c,feedMarkers:s,userMarkers:o},{cachedAt:l}),jt("local.feedMarker.fetched",{feedMarkers:s}),jt("local.channelMarker.fetched",{userEntityMarkers:i}),jt("local.subChannelMarker.fetched",{userFeedMarkers:c}),jt("local.userMarker.fetched",{userMarkers:o}),!0})(e)},qr=()=>{Ur=!1},Nr=()=>(Ur=!0,In((e=>{"notLoggedIn"===e&&qr()})),()=>{qr()});jr((async()=>{Ur&&await xr()}),3e4);const Br=async e=>{const t=Ve();t.log("channel/getSubChannels",e);const n=await t.http.get("/api/v5/message-feeds/list",{params:{messageFeedIds:e.map(encodeURIComponent)}}),a=await ba(n.data),r=t.cache&&Date.now();return t.cache&&Ln(a,{cachedAt:r}),jt("local.message-feed.fetched",a),{data:a.messageFeeds,cachedAt:r}};Br.locally=e=>{var t;const n=Ve();if(n.log("channel/getSubChannels.locally",e),!n.cache)return;const a=e.map((e=>Ze(["subChannel","get",e]))).filter(Boolean);if((null==a?void 0:a.length)<e.length)return;return{data:a.map((({data:e})=>e)),cachedAt:(null===(t=a.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0]).cachedAt}};const Lr=async(e=!0)=>{var t;const n=null===(t=Ze(["MessagePreviewSetting"]))||void 0===t?void 0:t.data;if(!e&&n)return n;const a=await Bn();var r;return(r=a).messagePreview.enabled?r.messagePreview.isIncludeDeleted?"message-preview-include-deleted":"message-preview-not-include-deleted":"no-message-preview"},Fr=async()=>{var e;const t=await Lr();if(t===(null===(e=Ze(["MessagePreviewSetting"]))||void 0===e?void 0:e.data))return;et(["MessagePreviewSetting"],t);const n=[],a=[];if("no-message-preview"===t){const e=Xe(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{at(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&a.push(t.subChannelId)}))}else if("message-preview-not-include-deleted"===t){const e=Xe(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{(null==t?void 0:t.isDeleted)&&(at(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&a.push(t.subChannelId))})),0!==n.length&&await Mr(n),0!==a.length&&await Br(a)}},Kr=async()=>{const e=Ve(),{data:t}=await e.http.get("/api/v3/network-settings/social");return t.socialNetworkSetting},$r=async()=>{const e=Ve(),{data:t}=await e.http.get("/api/v3/network-settings/users");return t},Qr=async()=>{const e=Ve(),{data:t}=await e.http.get("/api/v3/network-settings/product");return t},zr=async()=>{var e,t;const n=Ve(),{data:a}=await n.http.get("/api/v3/network-settings/for-you-feed");return{forYouFeed:{enabled:null!==(t=null===(e=a.forYouFeed)||void 0===e?void 0:e.enabled)&&void 0!==t&&t}}},Vr=(e,t)=>{var n;const a=null===(n=Ze(["user","get",e]))||void 0===n?void 0:n.data;return!!a&&a.permissions.some((e=>e===t))},Hr=e=>{const{userId:t}=Ve();return{currentUser:()=>Vr(t,e),community:n=>((e,t,n)=>{var a;if(!e)return!1;const r=null===(a=Ze(["communityUsers","get",`${n}#${e}`]))||void 0===a?void 0:a.data;return!!r&&(!!r.permissions.some((e=>e===t))||Vr(e,t))})(t,e,n),channel:n=>((e,t,n)=>{var a;if(!e)return!1;const r=null===(a=Ze(["channelUsers","get",`${n}#${e}`]))||void 0===a?void 0:a.data;return!!r&&(!!r.permissions.some((e=>e===t))||Vr(e,t))})(t,e,n)}},Jr=async e=>{const t=Ve();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},Wr=async e=>{const t=Ve();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},Gr=async()=>{const e=Ve(),{data:t}=await e.http.get("/api/v3/network-settings/feed-setting");return Object.fromEntries(t.feedSettings.map((({feedType:e,contentSettings:t})=>[e,t])))},Yr={notLoggedIn:["establishing"],terminated:["establishing"],establishing:["notLoggedIn","established"],established:["notLoggedIn","terminated","tokenExpired","establishing"],tokenExpired:["establishing"]},Xr=(e,t)=>{const n=Ve();n.log("client/api/setSessionState",e,t);const{sessionState:a}=n;if(a===e)return!1;if(!((e,t)=>Yr[e].includes(t))(a,e))throw new Le(`Session state cannot change from ${a} to ${e}`,8e5,"error");return n.sessionState=e,wn().setSessionState(e,t),!0};function Zr(e){return{users:e.users.map(ga),files:e.files}}const es=async e=>{const t=Ve();Xr("establishing");const{accessToken:n,users:a,expiresAt:r,issuedAt:s,userType:o,files:i}=await(async({params:e,options:t})=>{const n=Ve();n.log("client/api/getToken",e);const a=Dn(),{data:r}=await n.http.post("/api/v5/sessions",Object.assign(Object.assign({},e),{deviceInfo:a}),{headers:{"X-API-Key":n.apiKey,"set-access-token-cookie":(null==t?void 0:t.setAccessTokenCookie)||!1}});return r})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:r,isGlobalBanned:!1,isUserDeleted:!1},t.upload.defaults.headers.common.Authorization=`Bearer ${n}`,t.upload.defaults.metadata={tokenExpiry:r,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:s,expiresAt:r},Xr("established"),Ln(Zr({users:a,files:i})),{accessToken:n,users:a,userType:o}},ts=async e=>{const t=Ve();Xr("establishing");const{accessToken:n,users:a,expiresAt:r,issuedAt:s,userType:o,files:i}=await(async({params:e,options:t})=>{const n=Ve();n.log("client/api/getVisitorToken",e);const a=Dn(),{data:r}=await n.http.post("/api/v5/sessions/visitor",Object.assign(Object.assign({},e),{deviceInfo:a}),{headers:{"X-API-Key":n.apiKey,"set-access-token-cookie":(null==t?void 0:t.setAccessTokenCookie)||!1}});return r})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:r,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:s,expiresAt:r},Xr("established"),Ln(Zr({users:a,files:i})),{accessToken:n,users:a,userType:o}},ns=async()=>{var e;const t=Ve();return t.log("client/api/disconnectClient"),t.mqtt&&t.mqtt.connected&&t.mqtt.disconnect(),"established"===t.sessionState&&Xr("notLoggedIn"),t.emitter.all.clear(),null===(e=t.mqtt)||void 0===e||e.removeAllListeners(),t.userId=void 0,t.token=void 0,t.loginType=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},as=e=>{const t=Ve();Xr("terminated",e),t.http.defaults.metadata&&("globalBan"===e&&(t.http.defaults.metadata.isGlobalBanned=!0),"userDeleted"===e&&(t.http.defaults.metadata.isUserDeleted=!0)),t.sessionHandler=void 0,ns()};let rs=null;const ss=e=>{rs=e},os=({user:e,userType:t})=>{At(e),ss(t)},is=(e,t)=>{const n=Ve();return Mt(n,e,e,(e=>{const a=Zr(e);n.cache&&Ln(a),t(a.users[0])}))},cs=e=>is("user.deleted",e),ls=["analytic","normal-priority"],ds=["analytic","high-priority"],us=async e=>{const t=Ve(),n={activities:e};await t.http.post("/api/v1/analytics/activities",n)};class hs{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=Ze(ls);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await us(t),at(ls)}catch(e){this.stop(),at(ls)}}async syncHighPriorityCapturedEvent(){try{const e=Ze(ds);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await us(t),at(ds)}catch(e){this.stop(),at(ds)}}}class ps{constructor(){this._expireTime=5e3,this._poolLimit=1e3,this._recentViewed={},this._recentHighPriorityViewed={},this._throttleStoryTimer=void 0,this._bufferNewSeenStoryReferenceIds=[]}isAbleToEnqueue({uniqueId:e,expireTime:t,isHighPriority:n=!1}){const a=new Date,r=n?this._recentHighPriorityViewed[e]:this._recentViewed[e];if(!r)return!0;return!(a.getTime()-r.getTime()<t)}markAs({uniqueId:e,contentId:t,contentType:n,activityType:a,metadata:r}){if(!this.isAbleToEnqueue({uniqueId:e,expireTime:this._expireTime}))return;const s=new Date,o={event:[]},i=Ze(ls);(null==i?void 0:i.data)&&(o.event=i.data.event),o.event.length>=this._poolLimit&&o.event.shift();const c={contentId:t,contentType:n,activityType:a,timestamp:s.toISOString()};r&&(c.metadata=r),o.event.push(c),nt(ls,o),this._recentViewed[e]=s}markPostAsViewed(e){this.markAs({uniqueId:`post.${e}`,contentId:e,contentType:"post",activityType:"view"})}markPostAsMeaningfullyViewed(e,t){var n;const a=null===(n=Ze(["feedMetadata","get",e]))||void 0===n?void 0:n.data,r={};void 0!==t&&(r.feedRenderPosition=t),a&&(r.feedSnapshotPosition=a.feedSnapshotPosition,r.feedInjectionType=a.feedInjectionType,r.feedRelevanceScore=a.feedRelevanceScore,r.feedPopularityScore=a.feedPopularityScore,r.feedFreshnessScore=a.feedFreshnessScore,r.feedAffinityScore=a.feedAffinityScore,r.feedFinalScore=a.feedFinalScore,r.feedMmrPenalty=a.feedMmrPenalty),this.markAs({uniqueId:`post.${e}.meaningfulView`,contentId:e,contentType:"post",activityType:"meaningfulView",metadata:Object.keys(r).length>0?r:void 0})}markStory(e,t){if(!e.expiresAt)return;const n=new Date,a=new Date(e.expiresAt);if(!this.isAbleToEnqueue({uniqueId:e.storyId,expireTime:a.getTime(),isHighPriority:!0}))return;const r={event:[]},s=Ze(ds);if((null==s?void 0:s.data)&&(r.event=s.data.event),r.event.length>=this._poolLimit&&r.event.shift(),r.event.push({contentId:e.storyId,contentType:"story",activityType:t,timestamp:n.toISOString()}),nt(ds,r),this._recentHighPriorityViewed[e.storyId]=n,"linkClicked"===t)return;et(["story-seen","get",e.storyId],(new Date).toISOString());const o=Ze(["story-last-seen",e.targetId]);(null==o?void 0:o.data)?new Date(o.data).getTime()<new Date(e.expiresAt).getTime()&&et(["story-last-seen",e.targetId],e.expiresAt):et(["story-last-seen",e.targetId],e.expiresAt),this._bufferNewSeenStoryReferenceIds.push(e.referenceId),this._throttleStoryTimer||(this._throttleStoryTimer=setTimeout((()=>{clearTimeout(this._throttleStoryTimer),jt("local.story.reload",{referenceIds:this._bufferNewSeenStoryReferenceIds}),this._bufferNewSeenStoryReferenceIds=[]}),300))}resetAllBuckets(){this._recentViewed={},this._recentHighPriorityViewed={},at(ls),at(ds)}markStoryAsViewed(e){this.markStory(e,"view")}markStoryAsClicked(e){this.markStory(e,"linkClicked")}markAdAsViewed(e,t){const n={placement:t},a="view";this.markAs({uniqueId:`${e.adId}.view.${t}`,contentId:e.adId,contentType:"ad",activityType:a,metadata:n})}markAdAsClicked(e,t){const n={placement:t},a="linkClicked";this.markAs({uniqueId:`${e.adId}.linkClicked.${t}`,contentId:e.adId,contentType:"ad",activityType:a,metadata:n})}markProductAsClicked(e,t,n,a){const r={location:t,sourceType:n,sourceId:a},s="linkClicked";this.markAs({uniqueId:`${e.productId}.linkClicked.${t}`,contentId:e.productId,contentType:"product",activityType:s,metadata:r})}markProductAsViewed(e,t,n,a){const r={location:t,sourceType:n,sourceId:a},s="view";this.markAs({uniqueId:`${e.productId}.view.${t}`,contentId:e.productId,contentType:"product",activityType:s,metadata:r})}}class fs{constructor(){this._client=Ve(),this._eventCapturer=new ps,this._eventSyncer=new hs}markPostAsViewed(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markPostAsViewed(e)}markPostAsMeaningfullyViewed(e,t){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markPostAsMeaningfullyViewed(e,t)}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)}markProductAsClicked(e,t,n,a){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markProductAsClicked(e,t,n,a)}markProductAsViewed(e,t,n,a){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markProductAsViewed(e,t,n,a)}established(){this._eventSyncer.start()}handleTokenExpired(){this._stopAndDestroy()}destroy(){this._stopAndDestroy()}_stopAndDestroy(){this._eventSyncer.stop(),this._eventCapturer.resetAllBuckets()}}let ms;var gs=()=>(ms||(ms=new fs),ms),ys=()=>{const e=gs();return e.established(),In((t=>{"established"===t?e.established():e.handleTokenExpired()})),()=>{e.destroy()}};class vs{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=Ve(),this.getUnsyncJobs()}startSyncReadReceipt(){this.timer=setInterval((()=>{this.syncReadReceipts()}),1e3*this.RECEIPT_SYNC_INTERVAL)}syncReadReceipts(){if(0===this.jobQueue.length||!1===this.isActive)return;const e=this.getReadReceipts();e&&this.markReadApi(e)}getUnsyncJobs(){var e;const t=null===(e=Xe(["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=Ze(["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=Ve();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 a=["readReceipt",e[n].channelId],r=null===(t=Ze(a))||void 0===t?void 0:t.data;et(a,Object.assign(Object.assign({},r),{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 a=["channelUnread","get",e],r=null===(n=Ze(a))||void 0===n?void 0:n.data;r&&("number"!=typeof r.readToSegment||t>r.readToSegment)&&(r.readToSegment=t,r.unreadCount=Math.max(r.lastSegment-t,0),et(a,r),jt("local.channelUnread.updated",[r])),this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const a=null===(n=Ze(["readReceipt",e]))||void 0===n?void 0:n.data;if(a){if(a.latestSegment<t)et(["readReceipt",e],Object.assign(Object.assign({},a),{latestSegment:t}));else if(a.latestSyncSegment>=t)return}else{et(["readReceipt",e],{channelId:e,latestSegment:t,latestSyncSegment:0})}let r=this.getSyncJob(e);null===r||"syncing"===r.syncState?(r={channelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(r)):r.segment<t&&(r.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 bs=null;var ws=()=>(bs||(bs=new vs),bs),Is=()=>{const e=ws();return e.startSyncReadReceipt(),In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};class Cs{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=Ve(),this.getUnsyncJobs()}startSyncReadReceipt(){this.timer=setInterval((()=>{this.syncReadReceipts()}),1e3*this.RECEIPT_SYNC_INTERVAL)}syncReadReceipts(){if(0===this.jobQueue.length||!1===this.isActive)return;const e=this.getReadReceipt();e&&this.markReadApi(e)}getUnsyncJobs(){var e;const t=null===(e=Xe(["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=Ze(["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:a,segment:r}=n,s=await(async({subChannelId:e,readToSegment:t})=>{const n=Ve();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:a,readToSegment:r});if(s){this.removeSynedReceipt(e.subChannelId,e.segment);const n=null===(t=Ze(["legacyReadReceipt",a]))||void 0===t?void 0:t.data;et(["legacyReadReceipt",a],Object.assign(Object.assign({},n),{latestSyncSegment:r}))}else s||(n.retryCount>this.MAX_RETRY?this.removeJobFromQueue(n):(n.retryCount+=1,n.syncState="create"))}removeSynedReceipt(e,t){this.jobQueue.forEach((n=>{n.subChannelId===e&&n.segment<=t&&this.removeJobFromQueue(n)}))}startObservingReadReceiptQueue(){this.client.isUnreadCountEnabled&&(this.isActive=!0,this.startSyncReadReceipt())}stopObservingReadReceiptQueue(){this.isActive=!1;this.jobQueue.map((e=>"syncing"===e.syncState?Object.assign(Object.assign({},e),{syncState:"create"}):e)),this.timer&&clearInterval(this.timer)}onSessionEstablished(){this.startObservingReadReceiptQueue()}onSessionDestroyed(){this.stopObservingReadReceiptQueue(),this.jobQueue=[]}onTokenExpired(){this.stopObservingReadReceiptQueue()}onNetworkOffline(){this.stopObservingReadReceiptQueue()}onNetworkOnline(){this.startObservingReadReceiptQueue()}markRead(e,t){var n;const a=["subChannelUnreadInfo","get",e],r=null===(n=Ze(a))||void 0===n?void 0:n.data;if(r&&t>r.readToSegment){r.readToSegment=t,r.unreadCount=Math.max(r.lastSegment-t,0);const e=na(r.channelId);jt("local.channelUnreadInfo.updated",e),et(a,r),jt("local.subChannelUnread.updated",r)}this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const a=null===(n=Ze(["legacyReadReceipt",e]))||void 0===n?void 0:n.data;if(a){if(a.latestSegment<t)et(["legacyReadReceipt",e],Object.assign(Object.assign({},a),{latestSegment:t}));else if(a.latestSyncSegment>=t)return}else{et(["legacyReadReceipt",e],{subChannelId:e,latestSegment:t,latestSyncSegment:0})}let r=this.getSyncJob(e);null===r||"syncing"===r.syncState?(r={subChannelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(r)):r.segment<t&&(r.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 Ss=null;var Os=()=>(Ss||(Ss=new Cs),Ss),Ts=()=>{const e=Os();return e.startSyncReadReceipt(),In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};const ks=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")},As=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")},_s=async e=>{const t=Ve();t.log("channel/getChannelByIds",e);const n=e.map((e=>encodeURIComponent(e)));let a;try{a=(await t.http.get("/api/v3/channels/list",{params:{channelIds:n}})).data}catch(t){throw e.forEach((e=>{Oe(null==t?void 0:t.code)&&Fn("channel",e)})),t}const r=await Pa(a);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await ja(a);const s=t.cache&&Date.now();return t.cache&&Ln(r,{cachedAt:s}),jt("local.channel.fetched",r.channels),{data:r.channels,cachedAt:s}};_s.locally=e=>{var t,n;const a=Ve();if(a.log("channel/getChannelByIds.locally",e),!a.cache)return;const r=null===(t=Xe(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!r||(null==r?void 0:r.length)<e.length)return;return{data:r.map((({data:e})=>e)),cachedAt:(null===(n=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0]).cachedAt}};class Es{constructor(){this.TIMER_INTERVAL_MS=ge,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(ks((()=>{this.isConnected=!0}))),this.connectionListener.push(As((()=>{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,a;await _s(e);const r=null!==(a=null===(n=null===(t=Xe(["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!==a?a:[];jt("local.channel.resolved",r)})(e),t.length>0&&(async e=>{const t=await Ma(e),{feedMarkers:n,userFeedMarkers:a}=t;aa({feedMarkers:n,userFeedMarkers:a}),jt("local.userMessageFeedMarkers.resolved",{feedMarkers:n,userFeedMarkers:a})})(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 Rs=null;var Ps=()=>(Rs||(Rs=new Es),Rs),Ms=()=>{const e=Ps();return e.startResolver(),In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};class js{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(ks((()=>{this.isConnected=!0}))),this.connectionListener.push(As((()=>{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{roomId:n,streamId:a}=t,r=Kn(t,["roomId","streamId"]),s=a?"liveStream":"room",o=null!=a?a:n;return e[o]||(e[o]={referenceType:s,reactions:[]}),e[o].reactions.push(r),e}),{});Object.entries(t).forEach((([t,n])=>{(async({reactions:e,liveStreamId:t,roomId:n})=>{const a=Ve();a.log("live_reaction/addReaction",e);const{data:r}=await a.http.post("/api/v1/reactions/live",{liveStreamId:t,reactions:e,roomId:n})})({["room"===n.referenceType?"roomId":"liveStreamId"]:t,reactions:e})})),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 Us;var Ds=()=>(Us||(Us=new js),Us);function xs(e){const{users:t,follows:n}=e,a=Kn(e,["users","follows"]);return Object.assign(Object.assign({},a),{follows:n.map((e=>{const n=t.find((t=>t.userId===e.from));return Object.assign(Object.assign({},e),{user:ga(n)})})),users:t.map(ga)})}class qs{constructor(){this.lastFetchedAt=null}onSessionEstablished(){}onSessionDestroyed(){this.lastFetchedAt=null}onTokenExpired(){}isCacheExpired(){return null===this.lastFetchedAt||Date.now()-this.lastFetchedAt>3e5}async ensureFetched(){if(!this.isCacheExpired())return;const e=Ve(),{data:t}=await e.http.get("/api/v4/me/user-blocks",{params:{options:{limit:100},isDeleted:!1}}),n=e.cache&&Date.now(),a=xs(t);e.cache&&Ln(a,{cachedAt:n}),this.lastFetchedAt=Date.now()}getCachedUsers(){var e;const t=Ve();if(!t.cache)return[];const{userId:n}=t;return(null!==(e=Xe(["follow","get"]))&&void 0!==e?e:[]).map((e=>e.data)).filter((e=>"blocked"===(null==e?void 0:e.status)&&e.from===n)).sort(((e,t)=>{var n,a;return(null!==(n=e.updatedAt)&&void 0!==n?n:"")<(null!==(a=t.updatedAt)&&void 0!==a?a:"")?1:-1})).map((e=>{var t;return null===(t=Ze(["user","get",e.to]))||void 0===t?void 0:t.data})).filter((e=>null!=e&&!0!==e.isDeleted)).slice(0,100).map(qt)}}let Ns=null;var Bs=()=>(Ns||(Ns=new qs),Ns);function Ls(e){const{users:t,follows:n}=e,a=Kn(e,["users","follows"]);return Object.assign(Object.assign({},a),{follows:n.map((e=>{const n=t.find((t=>t.userId===e.from));return Object.assign(Object.assign({},e),{user:ga(n)})})),users:t.map(ga)})}class Fs{constructor(){this.lastFetchedAt=null}onSessionEstablished(){}onSessionDestroyed(){this.lastFetchedAt=null}onTokenExpired(){}isCacheExpired(){return null===this.lastFetchedAt||Date.now()-this.lastFetchedAt>3e5}async ensureFetched(){if(!this.isCacheExpired())return;const e=Ve(),{data:t}=await e.http.get("/api/v4/me/blockers",{params:{options:{limit:100},isDeleted:!1}}),n=e.cache&&Date.now(),a=Ls(t);e.cache&&Ln(a,{cachedAt:n}),this.lastFetchedAt=Date.now()}getCachedUsers(){var e;const t=Ve();if(!t.cache)return[];const{userId:n}=t;return(null!==(e=Xe(["follow","get"]))&&void 0!==e?e:[]).map((e=>e.data)).filter((e=>"blocked"===(null==e?void 0:e.status)&&e.to===n)).sort(((e,t)=>{var n,a;return(null!==(n=e.updatedAt)&&void 0!==n?n:"")<(null!==(a=t.updatedAt)&&void 0!==a?a:"")?1:-1})).map((e=>{var t;return null===(t=Ze(["user","get",e.from]))||void 0===t?void 0:t.data})).filter((e=>null!=e&&!0!==e.isDeleted)).slice(0,100).map(qt)}}let Ks=null;var $s=()=>(Ks||(Ks=new Fs),Ks);function Qs(e){const{users:t,follows:n}=e,a=Kn(e,["users","follows"]);return Object.assign(Object.assign({},a),{follows:n,users:t.map(ga)})}function zs(e){const{users:t,follows:n}=e,a=Kn(e,["users","follows"]);return Object.assign(Object.assign({},a),{follows:n,users:t.map(ga)})}function Vs(e){const{follows:t}=e,n=Kn(e,["follows"]);return Object.assign(Object.assign({},n),{follows:t})}const Hs=(e,t)=>{const n=Ve();return Mt(n,e,e,(e=>{const a=Qs(e);n.cache&&Ln(a),t(a.follows[0])}))},Js=e=>Hs("user.didBlock",e),Ws=e=>Hs("user.didUnblock",e);class Gs{constructor(e,t){this.networkId=e,this.userId=t}static current(){try{const e=Nt();if(!e)return null;const t=Ft(e),{userId:n}=e;return t&&n?new Gs(t,n):null}catch(e){return null}}static isExpired(e){return Date.now()>=e}static clearOnLogout(){return In((e=>{var t;"terminated"===e&&(null===(t=Gs.current())||void 0===t||t.clear())}))}get key(){return`amity:forYouFeed:cursor:${this.networkId}:${this.userId}`}async get(){const e=await Pn(this.key);if(!e)return null;try{const t=JSON.parse(e);return"string"!=typeof(null==t?void 0:t.cursor)||"number"!=typeof(null==t?void 0:t.expiredAt)?null:{cursor:t.cursor,expiredAt:t.expiredAt,reachedEndOfFeed:!0===t.reachedEndOfFeed}}catch(e){return null}}async set(e){await Rn(this.key,JSON.stringify(e))}async markReachedEndOfFeed(e){var t;const n=await this.get();await this.set({cursor:null!==(t=null==n?void 0:n.cursor)&&void 0!==t?t:"",expiredAt:e,reachedEndOfFeed:!0})}async clear(){await Rn(this.key,"")}}const Ys=["disconnected","error","connect_error","reconnect_error","reconnect_failed"],Xs=e=>{const t=Ve(),n=Ys.map((n=>Mt(t,`client/onConnectionError(${n})`,n,(t=>{const a=(null==t?void 0:t.code)?new Le(t.message,t.code,"fatal"):new $e(n);e(a)}))));return()=>{n.forEach((e=>e()))}},Zs=e=>{const t=Ve();return Mt(t,"client/onConnectionError(user.didGlobalBan)","user.didGlobalBan",e)},eo=e=>{const t=Ve();return Mt(t,"client/onTokenExpired","tokenExpired",e)},to=e=>{const t=Ve();return Mt(t,"client/onTokenTerminated","tokenTerminated",e)},no=e=>{const t=We("channelMarker")({userId:kt()._id,entityId:e.channelId});at(["channelMarker","get",t],!0)},ao=e=>{const t=Ve(),n=[];return n.push(Zs((t=>{as("globalBan"),n.forEach((e=>e())),e()})),to((t=>{as(),n.forEach((e=>e())),e()})),cs((a=>{a.userId===t.userId&&(as("userDeleted"),n.forEach((e=>e())),e())})),eo((e=>{wn().setSessionState(e),ns(),n.forEach((e=>e()))})),Ya(no),mr(no),Nr(),ys(),Ms(),(()=>{const e=Ds();return e.startReactionsSync(),In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=Bs();return In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=$s();return In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=[Js((()=>{})),Ws((()=>{}))];return()=>e.forEach((e=>e()))})(),In((e=>{"established"!==e&&An().reset()})),Gs.clearOnLogout()),t.useLegacyUnreadCount?n.push(Is()):n.push(Ts()),n};let ro=[];const so=async(e,t,n)=>{const a=Ve();let r;a.log("client/api/connectClient",Object.assign({apiKey:a.apiKey,sessionState:a.sessionState},e)),a.userId&&a.userId!==e.userId&&(await ns(),ro.forEach((e=>e())),ro=[]);const s=await Un();try{const{users:n,userType:o}=await es({params:Object.assign(Object.assign({},e),{displayName:null==e?void 0:e.displayName,deviceId:(null==e?void 0:e.deviceId)||s}),options:{setAccessTokenCookie:!0}}),i=n.find((t=>t.userId===e.userId));if(null==i)throw new Le(`${e.userId} has not been founded`,8e5,"error");if(i.isDeleted)return as("userDeleted"),!1;if(i.isGlobalBan)return as("globalBan"),!1;a.userId=i.userId,a.sessionHandler=t,a.loginType="userId",r=a.accessTokenExpiryWatcher(),os({user:i,userType:o})}catch(e){throw wn().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await xt()}(),await Fr(),0===ro.length&&(ro=ao(r)),!0},oo=[],io=async e=>{const t=Ve();let n;t.log("client/api/connectClient",Object.assign({apiKey:t.apiKey,sessionState:t.sessionState},e));const a=await Un();let r;try{const{users:s,userType:o}=await ts({params:Object.assign(Object.assign({},e),{deviceId:a}),options:{setAccessTokenCookie:!0}});[r]=s,t.userId=r.userId,t.sessionHandler=e.sessionHandler,t.loginType="userId",n=t.accessTokenExpiryWatcher(),os({user:r,userType:o})}catch(e){throw wn().setSessionState("notLoggedIn"),e}return await Fr(),0===oo.length&&oo.push(to((e=>{as(),oo.forEach((e=>e())),n()})),eo((e=>{wn().setSessionState(e),ns(),oo.forEach((e=>e()))}))),!0},co=()=>{let e,t=!1;const n=Ve();n.log("initiating access token renewal");const a=async a=>{const{userId:r,displayName:s}=kt(),o={userId:r,displayName:s,authToken:a,deviceId:await Un()};"tokenExpired"===n.sessionState&&n.sessionHandler?await so(o,n.sessionHandler):await es({params:o,options:{setAccessTokenCookie:!0}}),t=!0,e&&clearTimeout(e)};return{renew:()=>{t?console.log("'renew' method can be called only once per renewal instance"):a()},renewWithAuthToken:e=>{t?console.log("'renewWithAuthToken' method can be called only once per renewal instance"):a(e)},unableToRetrieveAuthToken:()=>{e=setTimeout((()=>{var e;null===(e=n.sessionHandler)||void 0===e||e.sessionWillRenewAccessToken(co())}),ye)},renewWithAuthSignature:a=>{t?console.log("'renew' method can be called only once per renewal instance"):(async({authSignature:a,authSignatureExpiresAt:r})=>{const s=await Un();"tokenExpired"===n.sessionState&&n.sessionHandler?await io({sessionHandler:n.sessionHandler}):await ts({params:{authSignature:a,authSignatureExpiresAt:r,deviceId:s},options:{setAccessTokenCookie:!0}}),t=!0,e&&clearTimeout(e)})(a)},unableToRetrieveAuthSignature:()=>{e=setTimeout((()=>{var e;null===(e=n.sessionHandler)||void 0===e||e.sessionWillRenewAccessToken(co())}),ye)}}},lo=async({token:e,userId:t})=>{const n=Ve();await n.http.get("/api/v3/sessions",{headers:{Authorization:`Bearer ${e.accessToken}`}});const{data:{users:a}}=await n.http.get(`/api/v3/users/${t}`,{headers:{Authorization:`Bearer ${e.accessToken}`}}),r=a.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,r},uo=e=>{var t;const n=Ve(),a=S.default(e);return(null===(t=null==a?void 0:a.user)||void 0===t?void 0:t.publicUserId)===n.userId};let ho=[];const po=async e=>{var t,n;const a=Ve();let r,s;if(a.log("client/api/loginWithAccessToken",{apiKey:a.apiKey,sessionState:a.sessionState}),!e||"string"!=typeof e||""===e.trim())throw new Le("Access token must be a non-empty string",8e5,"error");try{s=S.default(e)}catch(e){throw new Le("Invalid access token format",400100,"error")}const o=(null===(t=null==s?void 0:s.user)||void 0===t?void 0:t.publicUserId)||(null===(n=null==s?void 0:s.user)||void 0===n?void 0:n.userId);if(!o)throw new Le("Access token does not contain userId",400100,"error");if(a.userId){uo(e)||await ns()}try{Xr("establishing");const t={accessToken:e,issuedAt:s.iat?new Date(1e3*s.iat).toISOString():(new Date).toISOString(),expiresAt:new Date(1e3*s.exp).toISOString()},n=await lo({token:t,userId:o});if(null==n)throw Xr("notLoggedIn"),new Le(`User ${o} has not been found`,8e5,"error");if(n.isDeleted)throw Xr("notLoggedIn"),new Le(`User ${o} has been deleted`,8e5,"error");if(n.isGlobalBanned)throw Xr("notLoggedIn"),new Le(`User ${o} is globally banned`,8e5,"error");a.userId=n.userId,a.loginType="accessToken",At(n),r=a.accessTokenExpiryWatcher(),Xr("established")}catch(e){if(Xr("notLoggedIn"),e instanceof Le)throw e;throw new Le((e instanceof Error?e.message:void 0)||"Login with access token failed",400100,"error")}return async function(){await xt()}(),await Fr(),0===ho.length&&(ho=ao(r)),!0},fo=async e=>{var t,n;const a=Ve();if(a.log("initiating access token renewal"),!e||"string"!=typeof e||""===e.trim())throw new Le("Access token must be a non-empty string",8e5,"error");let r;try{r=S.default(e)}catch(e){throw new Le("Invalid access token format",400100,"error")}const s=(null===(t=null==r?void 0:r.user)||void 0===t?void 0:t.publicUserId)||(null===(n=null==r?void 0:r.user)||void 0===n?void 0:n.userId);if(!s)throw new Le("Access token does not contain userId",400100,"error");if(a.userId){uo(e)||await ns()}const o={accessToken:e,issuedAt:r.iat?new Date(1e3*r.iat).toISOString():(new Date).toISOString(),expiresAt:new Date(1e3*r.exp).toISOString()};"tokenExpired"===a.sessionState&&a.sessionHandler?await po(e):await lo({token:o,userId:s})},mo=async({useScheduledTask:e=!1})=>{const t=Ve();if(t.userId&&t.accessTokenHandler)try{const n=await t.accessTokenHandler.onTokenRenew(t.userId);e?Rt((()=>fo(n))):fo(n)}catch(e){t.log("Proactive token renewal failed, will retry when token expires",e)}},go=3e5,yo=()=>{const e=setInterval((async()=>{const e=Ve(),{sessionHandler:t,accessTokenHandler:n,loginType:a}=e;if(!e.token||!e.userId)return;const{issuedAt:r,expiresAt:s}=e.token;if((e=>Date.now()>Date.parse(e)-go)(s))return jt("tokenExpired","tokenExpired"),void("accessToken"===a&&n?await mo({useScheduledTask:!1}):"userId"===a&&t&&Rt((()=>t.sessionWillRenewAccessToken(co()))));(e=>{const{expiresAt:t,issuedAt:n}=e,a=Date.parse(t),r=Date.parse(n),s=Date.now();return s>r+.8*(a-r-go)&&s<a})({expiresAt:s,issuedAt:r})&&("accessToken"===a&&n?await mo({useScheduledTask:!1}):"userId"===a&&t&&t.sessionWillRenewAccessToken(co()))}),ye);return()=>clearInterval(e)},vo=e=>{if(Ve().useLegacyUnreadCount){ws().markRead(e.channelId,e.channelSegment)}else{Os().markRead(e.subChannelId,e.channelSegment)}},bo=e=>{const t=Ve(),n=kt(),a=[Mt(t,"message/onMessageCreated","message.created",(async a=>{const r=await pa(a);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&a.messages.forEach((e=>{(e=>{var t;const n=Ve(),a=["subChannelUnreadInfo","get",e.messageFeedId],r=null===(t=Ze(a))||void 0===t?void 0:t.data;if(!r)return;const s=r.lastSegment<e.segment?e.segment:r.lastSegment,o=s-r.readToSegment;let{lastMentionSegment:i}=r;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({},r),{lastMentionSegment:i,lastSegment:s,isMentioned:!(r.readToSegment>=i),unreadCount:Math.max(o,0)});et(a,c)})(e),na(e.channelId)})),t.useLegacyUnreadCount&&a.messages.forEach((e=>{var n,a,r;const s=null===(n=Ze(["channelUnread","get",e.channelId]))||void 0===n?void 0:n.data;if(!s||s.lastSegment>=e.segment)return;const o=e.segment,i=(null===(a=e.mentionedUsers)||void 0===a?void 0:a.some((e=>"channel"===e.type||"user"===e.type&&t.userId&&e.userPublicIds.includes(t.userId))))?e.segment:s.lastMentionedSegment,c=null!==(r=s.readToSegment)&&void 0!==r?r:0,l=Object.assign(Object.assign({},s),{lastSegment:o,unreadCount:Math.max(o-c,0),lastMentionedSegment:i,isMentioned:"number"==typeof i&&c<i});et(["channelUnread","get",e.channelId],l),jt("local.channelUnread.updated",[l])})),Ln(r),r.messages.forEach((t=>{t.creatorPrivateId===n._id&&vo(t),e(t)}))}))];return()=>{a.forEach((e=>e()))}},wo=e=>{const t=Ve(),n=[Mt(t,"message/onMessageCreated","local.message.created",(async t=>(Ln(t),t.messages.forEach((t=>{e(t)})))))];return()=>{n.forEach((e=>e()))}},Io=e=>{const t=Ve();return Mt(t,"onSubChannelCreated","message-feed.created",(async n=>{const a=await ba(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&n.messageFeeds.forEach((e=>{(e=>{const{channelId:t,subChannelId:n,createdAt:a,updatedAt:r}=e,s={channelId:t,subChannelId:n,unreadCount:0,readToSegment:0,lastMentionSegment:0,lastSegment:0,isMentioned:!1,isDeleted:!1,createdAt:a,updatedAt:r};et(["subChannelUnreadInfo","get",s.subChannelId],s)})({channelId:e.channelId,subChannelId:e.messageFeedId,createdAt:e.createdAt,updatedAt:e.updatedAt})})),Ln(a),e(a.messageFeeds[0])}))},Co=e=>{const t=Ve(),n=[Mt(t,"onSubChannelDeleted","message-feed.deleted",(async n=>{const a=await ba(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&a.messageFeeds.forEach((e=>{(e=>{var t;const n=["subChannelUnreadInfo","get",e],a=null===(t=Ze(n))||void 0===t?void 0:t.data;a&&et(n,Object.assign(Object.assign({},a),{isDeleted:!0}))})(e.subChannelId),na(e.channelId)})),Ln(a),e(a.messageFeeds[0])})),Mt(t,"local.message-feed.deleted","local.message-feed.deleted",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}},So=async e=>{const t=Ve();t.log("channel/markerSync");const{data:n}=await t.http.post("/api/v1/markers/sync",{deviceLastSyncAt:e}),{userEntityMarkers:a,userFeedMarkers:r,feedMarkers:s,userMarkers:o}=n,i=Vn(a),c=Hn(r),l=t.cache&&Date.now();return t.cache&&Ln({userEntityMarkers:i,userFeedMarkers:c,feedMarkers:s,userMarkers:o},{cachedAt:l}),jt("local.feedMarker.fetched",{feedMarkers:s}),jt("local.channelMarker.fetched",{userEntityMarkers:i}),jt("local.subChannelMarker.fetched",{userFeedMarkers:c}),jt("local.userMarker.fetched",{userMarkers:o}),{data:n,hasMore:n.feedMarkers.length>0}};let Oo=!1,To=[],ko=!1;let Ao=null;let _o=[];const Eo=e=>{_o=e},Ro=async()=>{var e;if(!ko&&0!==_o.length)try{ko=!0,_o=[];const t=await So((null==Ao?new Date:Ao).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)&&(!Ao||e.getTime()>Ao.getTime())&&(Ao=e),t.hasMore&&_o.push("has_more")}catch(e){}finally{ko&&(ko=!1)}};jr((async()=>{Oo&&await Ro()}),2e3);const Po=()=>true,Mo=e=>{var t;const n=Ve();if(n.mqtt)return null===(t=n.mqtt)||void 0===t?void 0:t.listen(e)},jo=async()=>{const e=Ve(),t=await Un(),{data:{status:n,error:a}}=await e.http.delete("/v1/notification",{params:{deviceId:t},headers:{"X-API-Key":e.apiKey}});if(a)throw new Fe(a,5e5,"error");return"success"===n};let Uo=[];var Do;class xo{constructor(){Do.set(this,e.FileAccessTypeEnum.PUBLIC)}setFileAccessType(e){!function(e,t,n,a,r){if("m"===a)throw new TypeError("Private method is not writable");if("a"===a&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===a?r.call(e,n):r?r.value=n:t.set(e,n)}(this,Do,e,"f")}getFileAccessType(){return function(e,t,n,a){if("a"===n&&!a)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!a:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?a:"a"===n?a.call(e):a?a.value:t.get(e)}(this,Do,"f")}}let qo;Do=new WeakMap;var No=()=>(qo||(qo=new xo),qo);const Bo={[e.AmitySharableContentType.POST]:{key:"posts",placeholder:"postId"},[e.AmitySharableContentType.COMMUNITY]:{key:"communities",placeholder:"communityId"},[e.AmitySharableContentType.USER]:{key:"users",placeholder:"userId"},[e.AmitySharableContentType.LIVESTREAM]:{key:"livestream",placeholder:"livestream"},[e.AmitySharableContentType.EVENT]:{key:"events",placeholder:"eventId"}},Lo=async e=>{const t=Ve();Xr("establishing");const{accessToken:n,users:a,expiresAt:r,issuedAt:s,userType:o,files:i}=await(async({params:e,options:t})=>{const n=Ve();n.log("client/api/getBotToken");const a=Dn(),{data:r}=await n.http.post("/api/v5/sessions/bot",Object.assign(Object.assign({},e),{deviceInfo:a}),{headers:{"X-API-Key":n.apiKey,"set-access-token-cookie":(null==t?void 0:t.setAccessTokenCookie)||!1}});return r})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:r,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:s,expiresAt:r},Xr("established"),Ln(Zr({users:a,files:i})),{accessToken:n,users:a,userType:o}},Fo=[];function Ko(t,n){return n&&n.length>0?{type:"not",roleIds:n}:t&&t.length>0?{type:e.NotificationRolesFilterTypeEnum.ONLY,roleIds:t}:{type:e.NotificationRolesFilterTypeEnum.ALL}}function $o(t){return(null==t?void 0:t.type)===e.NotificationRolesFilterTypeEnum.ONLY?{listenFromRoleIds:t.roleIds}:{listenFromRoleIds:[]}}class Qo{constructor(e){this.channelId=e}async enable(){const t=Ve(),n={level:e.NotificationSettingsLevelEnum.CHANNEL,channelId:this.channelId,isPushNotifiable:!0};await t.http.post("/api/v3/notification/setting",n)}async disable(){const t=Ve(),n={level:e.NotificationSettingsLevelEnum.CHANNEL,channelId:this.channelId,isPushNotifiable:!1};await t.http.post("/api/v3/notification/setting",n)}async getSettings(){const t=Ve(),{data:n}=await t.http.get(`/api/v3/notification/setting?level=${e.NotificationSettingsLevelEnum.CHANNEL}&channelId=${encodeURIComponent(this.channelId)}`);return{isEnabled:n.isPushNotifiable}}}class zo{async enable(t){var n;const a=Ve(),r=null!==(n=null==t?void 0:t.map((e=>Object.assign({moduleName:e.moduleName,isPushNotifiable:e.isEnabled},$o(e.rolesFilter)))))&&void 0!==n?n:[],s={level:e.NotificationSettingsLevelEnum.USER,isPushNotifiable:!0,notifiableEvents:r};await a.http.post("/api/v3/notification/setting",s)}async disableAllNotifications(){const t=Ve(),n={level:e.NotificationSettingsLevelEnum.USER,isPushNotifiable:!1,notifiableEvents:[]};await t.http.post("/api/v3/notification/setting",n)}async getSettings(){var t;const n=Ve(),{data:a}=await n.http.get(`/api/v3/notification/setting?level=${e.NotificationSettingsLevelEnum.USER}`),r=Object.values(e.UserNotificationModuleNameEnum),s=(null!==(t=a.notifiableEvents)&&void 0!==t?t:[]).filter((e=>null!=e.moduleName&&r.includes(e.moduleName))).map((e=>({moduleName:e.moduleName,isEnabled:e.isPushNotifiable,rolesFilter:Ko(e.listenFromRoleIds,e.ignoreFromRoleIds)})));return{isEnabled:a.isPushNotifiable,modules:s}}}class Vo{constructor(e){this.communityId=e}async enable(t){var n;const a=Ve(),r=null!==(n=null==t?void 0:t.map((t=>Object.assign({moduleName:e.UserNotificationModuleNameEnum.SOCIAL,name:t.eventName,isPushNotifiable:t.isEnabled},$o(t.rolesFilter)))))&&void 0!==n?n:[],s={level:e.NotificationSettingsLevelEnum.COMMUNITY,communityId:this.communityId,isPushNotifiable:!0,notifiableEvents:r};await a.http.post("/api/v3/notification/setting",s)}async disable(){const t=Ve(),n={level:e.NotificationSettingsLevelEnum.COMMUNITY,communityId:this.communityId,isPushNotifiable:!1,notifiableEvents:[]};await t.http.post("/api/v3/notification/setting",n)}async getSettings(){var t;const n=Ve(),{data:a}=await n.http.get(`/api/v3/notification/setting?level=${e.NotificationSettingsLevelEnum.COMMUNITY}&communityId=${encodeURIComponent(this.communityId)}`),r=Object.values(e.CommunityNotificationEventNameEnum),s=(null!==(t=a.notifiableEvents)&&void 0!==t?t:[]).filter((e=>null!=e.name&&r.includes(e.name))).map((e=>({eventName:e.name,isEnabled:e.isPushNotifiable,isNetworkEnabled:e.isNetworkEnabled,rolesFilter:Ko(e.listenFromRoleIds,e.ignoreFromRoleIds)})));return{isEnabled:a.isPushNotifiable,events:s}}}class Ho{user(){return new zo}community(e){return new Vo(e)}channel(e){return new Qo(e)}}const Jo=e=>{const t=Ve();return Mt(t,"channelMarker/onChannelMarkerFetched","local.channelMarker.fetched",(t=>{t.userEntityMarkers.forEach((t=>{e(t)}))}))},Wo=e=>{const t=Ve();return Mt(t,"subChannelMarker/onSubChannelMarkerFetched","local.subChannelMarker.fetched",(t=>{t.userFeedMarkers.forEach(e)}))},Go=e=>{const t=Ve();return Mt(t,"subChannelMarker/onSubChannelMarkerUpdated","local.subChannelMarker.updated",(t=>{e(t.userFeedMarkers)}))},Yo=e=>{const t=Ve();return Mt(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers)}))},Xo=e=>{const t=Ve();return Mt(t,"messageMarker/onMessageMarkerFetched","local.messageMarker.fetched",(t=>{e(t.contentMarkers[0])}))},Zo=e=>{const t=Ve();return Mt(t,"messageMarker/onMessageMarked","marker.marked-message",(t=>{var n,a,r;Ln(t);const s=Xe(["message","collection"]),{contentMarkers:o,feedMarkers:i}=t;if(s&&(null==s?void 0:s.length)>0&&(null==i?void 0:i.length)>0){const e=s.filter((e=>{var t,n;return(null===(n=null===(t=e.data)||void 0===t?void 0:t.query)||void 0===n?void 0:n.subChannelId)===i[0].feedId}));if(e.length>0&&(null==o?void 0:o.length)>0){(null!==(r=null===(a=null===(n=e[0].data)||void 0===n?void 0:n.data)||void 0===a?void 0:a.map((e=>Ze(["message","get",e]))).map((({data:e})=>e)).filter(Boolean))&&void 0!==r?r:[]).forEach((e=>{var t,n;const a=["messageMarker","get",We("messageMarker")({creatorId:e.creatorPrivateId,feedId:e.subChannelId,contentId:e.messageId})],r=null===(t=Ze(a))||void 0===t?void 0:t.data;if(!r)return;const s=o[0].feedId===r.feedId,i=o[0].readCount>r.readCount,c=(null===(n=o[0])||void 0===n?void 0:n.deliveredCount)>r.deliveredCount;if(s){const e=Object.assign(Object.assign({},r),{readCount:i?o[0].readCount:r.readCount,deliveredCount:c?o[0].deliveredCount:r.deliveredCount});et(a,e)}}))}}e(t.contentMarkers[0])}))};function ei(e){return"object"==typeof e&&null!==e}const ti=e=>{if(!ei(e))return e;const t=Object.entries(e).map((([t,n])=>{const a=Object.getOwnPropertyDescriptor(e,t);return"function"==typeof(null==a?void 0:a.get)?[t,a.get.call(e)]:[t,n]}));return Object.fromEntries(t)},ni=e=>{if(!ei(e))return e;const t=Object.entries(e).map((([e,t])=>"function"==typeof t?[e,void 0]:[e,t]));return Object.fromEntries(t)};var ai=Object.freeze({__proto__:null,getActiveClient:Ve,getActiveUser:kt,setActiveUser:At,createClient:(e,t=tn.SG,{debugSession:n="amity",apiEndpoint:a,prefixDeviceIdKey:r,rteEnabled:s=!0}={})=>{var o,i,c;const l=(e=>{const t=`${null==e?void 0:e.trim()}`.length>0&&!en,n=v.default(e),a=(e,...a)=>{t&&n(e,a)};return a.__instance__=n,a})(n);l("client/api/createClient",{apiKey:e.replace(/.{5}$/g,"xxxxx"),apiRegion:t});const d=null!==(o=null==a?void 0:a.http)&&void 0!==o?o:an("http",t),u=null!==(i=null==a?void 0:a.upload)&&void 0!==i?i:an("upload",t),h=null!==(c=null==a?void 0:a.mqtt)&&void 0!==c?c:an("mqtt",t),p=hn(d),f=hn(u);let m;s&&(m=Nn(h));const g=y.default(),b={version:`${le}`,apiKey:e,log:l,cache:{data:{}},http:p,ws:undefined,mqtt:m,upload:f,emitter:g,sessionState:"notLoggedIn",accessTokenExpiryWatcher:yo,sessionHandler:undefined,hasPermission:Hr,validateUrls:Jr,validateTexts:Wr,getFeedSettings:Gr,getCoreUserSettings:$r,getSocialSettings:Kr,getChatSettings:Bn,getVisitorDeviceId:Un,getMessagePreviewSetting:Lr,onRTEConnectionStateChange:Mo,use:()=>He(b),isUnreadCountEnabled:!1,useLegacyUnreadCount:!0,getMarkerSyncConsistentMode:Po,getProductCatalogueSetting:Qr,getForYouFeedSetting:zr,prefixDeviceIdKey:r};try{const t=Ve();if(t.apiKey===e)return t;He(b)}catch(e){He(b)}return b},login:so,loginWithAccessToken:po,logout:ns,secureLogout:async()=>{const e=Ve();try{await jo()}catch(t){e.log("client/api/secureLogout: failed to unregister push notification",t)}const{data:{success:t}}=await e.http.delete("/api/v4/sessions");if(!t)throw new Error("Failed to logout");return ns()},resumeSession:async(e,t,n)=>{const a=Ve();let r;a.log("client/api/resumeSession",Object.assign({apiKey:a.apiKey,sessionState:a.sessionState},e)),a.userId&&(a.userId===e.userId&&uo(e.token.accessToken)?(a.mqtt&&a.mqtt.connected&&a.mqtt.disconnect(),Uo.forEach((e=>e())),Uo=[]):(await ns(),Uo.forEach((e=>e())),Uo=[]));try{Xr("establishing");const n=await lo(e);if(null==n)throw new Le(`${e.userId} has not been found`,8e5,"error");if(n.isDeleted)return as("userDeleted"),!1;if(n.isGlobalBanned)return as("globalBan"),!1;a.userId=n.userId,a.sessionHandler=t,r=a.accessTokenExpiryWatcher(t),At(n)}catch(e){throw wn().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await xt()}(),await Fr(),0===Uo.length&&(Uo.push(Zs((e=>{as("globalBan"),Uo.forEach((e=>e())),r()})),to((e=>{as(),Uo.forEach((e=>e())),r()})),cs((e=>{e.userId===a.userId&&(as("userDeleted"),Uo.forEach((e=>e())),r())})),eo((e=>{wn().setSessionState(e),ns(),Uo.forEach((e=>e()))})),Ya(no),mr(no),Nr(),ys(),Ms()),a.useLegacyUnreadCount?Uo.push(Is()):Uo.push(Ts())),!0},isConnected:()=>{var e,t;const n=Ve();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:Gr,renewal:co,markerSync:So,enableUnreadCount:()=>!0,setUploadedFileAccessType:function(e){No().setFileAccessType(e)},registerPushNotification:async e=>{const t=Ve();let n;if("ios"!==l.Platform.OS&&"android"!==l.Platform.OS)throw new Qe("Unsupported platform");n=l.Platform.OS;const a=await Un(),{data:{status:r,error:s}}=await t.http.post("/v1/notification",{userId:t.userId,deviceId:a,platform:n,token:e},{headers:{"X-API-Key":t.apiKey}});if(s)throw new Fe(s,5e5,"error");return"success"===r},unregisterPushNotification:jo,onRTEConnectionStateChange:Mo,fetchLinkPreview:async e=>{const t=Ve();let n=e;/^https?:\/\//i.test(e)||(n=`https://${e}`);const{data:a}=await t.http.get(`/api/v1/link-preview?url=${encodeURIComponent(n)}`);return a},getLinkPreviewMetadata:async e=>{const t=Ve(),{data:n}=await t.http.get(`/api/v1/link-preview?url=${e}`);return n},getSocialSettings:Kr,getShareableLinkConfiguration:async()=>{var e,t;const n=Ve(),{data:a}=await n.http.get("/api/v3/network-settings/shareable-deep-links"),r=null!==(e=a.domain)&&void 0!==e?e:"",s=null!==(t=a.patterns)&&void 0!==t?t:{};return{domain:r,patterns:s,isEnabled(e){const{key:t}=Bo[e];return!!r&&!!s[t]},getPattern(e){const{key:t}=Bo[e];return s[t]||null},generateLink(e,t){const{key:n,placeholder:a}=Bo[e];return r&&s[n]?r+s[n].replace(`{${a}}`,t):null}}},getProductCatalogueSetting:Qr,getForYouFeedSetting:zr,loginAsVisitor:io,loginAsBot:async e=>{const t=Ve();let n;t.log("client/api/connectClient",{apiKey:t.apiKey,sessionState:t.sessionState});const a=await Un();let r;try{const{users:s,userType:o}=await Lo({params:{deviceId:a},options:{setAccessTokenCookie:!0}});[r]=s,t.userId=r.userId,t.sessionHandler=e.sessionHandler,t.loginType="userId",n=t.accessTokenExpiryWatcher(),os({user:r,userType:o})}catch(e){throw wn().setSessionState("notLoggedIn"),e}return await Fr(),0===Fo.length&&Fo.push(to((e=>{as(),Fo.forEach((e=>e())),n()})),eo((e=>{wn().setSessionState(e),ns(),Fo.forEach((e=>e()))}))),!0},getCurrentUser:Nt,getCurrentUserType:()=>{if(!rs)throw new Le("Connect client first",8e5,"fatal");return rs},setCurrentUserType:ss,setAccessTokenHandler:e=>{const t=Ve();if(t.log("client/api/setAccessTokenHandler",{apiKey:t.apiKey,sessionState:t.sessionState,hasOnTokenRenew:"function"==typeof(null==e?void 0:e.onTokenRenew)}),!e||"function"!=typeof e.onTokenRenew)throw new Error("AccessTokenHandler must implement onTokenRenew() method");t.accessTokenHandler=e},getChatSettings:Bn,getCoreUserSettings:$r,notifications:()=>new Ho,enableAutoSubscriptions:e=>{const t=An();e.forEach((e=>t.subscribe(e)))},disableAutoSubscriptions:e=>{const t=An();e.forEach((e=>t.unsubscribe(e)))},autoSubscriptions:()=>An().subscriptions(),onConnectionError:Xs,onClientDisconnected:e=>Xs((({code:t})=>{800211===t&&e()})),onClientBanned:Zs,onSessionStateChange:In,onNetworkActivities:e=>cn().onNetworkActivities(e),onVisitorUsageLimitReached:e=>{const t=Ve();return Mt(t,"client/onVisitorUsageLimitReached","visitorUsageLimitReached",e)},getUserUnread:e=>{const{_id:t}=kt();if(!t)throw new Le("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:a}=Ve();a||console.log("For using Live Object feature you need to enable Cache!");n(`liveUserUnread(tmpid: ${Date.now()}) > listen`);const r=[];let s,o=!1;const i=t=>{const{data:n}=t,a=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;s=a?ti(a):a,e({data:a?Object.assign(Object.assign({},a),{isMentioned:a.isMentioned}):a,loading:t.loading,error:t.error})};return r.push(Yo((e=>(e=>{var n;const a=e.filter((e=>t===e.userId)),r=a.reduce(((e,t)=>null==e||new Date(t.lastSyncAt).getTime()>new Date(e.lastSyncAt).getTime()?t:e),null),o={unreadCount:null!==(n=null==r?void 0:r.unreadCount)&&void 0!==n?n:0,isMentioned:a.some((e=>!!e.isMentioned))};La(s,o)||i({loading:!1,data:o})})(e)))),(()=>{const e=xe(ra);Ne(e,(({error:e,data:t,loading:n,origin:a,cachedAt:s})=>{!function(e){return null!=e&&null!=e}(t)?i({loading:n,data:void 0,origin:a,error:e}):(s===me?(i({data:t,origin:a,loading:!1,error:new Fe(fe,800800,"error")}),o=!0,r.forEach((e=>e()))):o||i({loading:n,data:t,origin:a,error:e}),e&&r.forEach((e=>e())))}))})(),()=>{r.forEach((e=>e()))}},getMarkerSyncEvents:()=>_o,setMarkerSyncEvents:Eo,pushMarkerSyncEvent:e=>_o.push(e),markerSyncTrigger:Ro,startMarkerSync:async()=>Promise.resolve(),startUnreadSync:async()=>Promise.resolve(),stopUnreadSync:()=>{Oo=!1,Eo([]),To.forEach((e=>e())),To=[]},getMarkerSyncConsistentMode:Po});const ri=(e,t)=>{const n=Ve();return Mt(n,e,e,(e=>{const a=Qs(e);n.cache?(Ln(a),t(a.follows[0])):t(a.follows[0])}))},si=(e,t)=>{const n=Ve();return Mt(n,e,e,(e=>{const a=Vs(e);n.cache?(Ln(a),t(a.follows[0])):t(a.follows[0])}))},oi=e=>ri("follow.created",e),ii=e=>ri("follow.unfollowed",e),ci=e=>ri("follow.followerDeleted",e),li=e=>ri("follow.requested",e),di=e=>ri("follow.requestCanceled",e),ui=e=>ri("follow.accepted",e),hi=e=>ri("follow.requestDeclined",e),pi=async e=>{var t,n;const a=Ve();a.log("follow/getFollowInfo",e);const{data:r}=await a.http.get(a.userId===e?"/api/v4/me/followInfo":`/api/v5/users/${e}/followInfo`),s=a.cache&&Date.now(),o="follows"in r?Object.assign(Object.assign({},r.followCounts[0]),{status:null===(n=null===(t=r.follows)||void 0===t?void 0:t[0])||void 0===n?void 0:n.status}):r.followCounts[0];return a.cache&&et(["followInfo","get",e],o,{cachedAt:s}),{data:o,cachedAt:s}};pi.locally=e=>{const t=Ve();if(t.log("follow/getFollowInfo.locally",e),!t.cache)return;const n=Ze(["followInfo","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const fi=e=>{const t=async t=>{const[{data:n},{data:a}]=await Promise.all([pi(t.from),pi(t.to)]);e(n),e(a)},n=[ri("follow.created",t),ri("follow.requested",t),ri("follow.accepted",t),ri("follow.unfollowed",t),ri("follow.requestCanceled",t),ri("follow.requestDeclined",t),ri("follow.followerDeleted",t),si("local.follow.created",t),si("local.follow.requested",t),si("local.follow.accepted",t),si("local.follow.unfollowed",t),si("local.follow.requestDeclined",t)];return()=>{n.forEach((e=>e()))}},mi=e=>si("local.follow.created",e),gi=e=>si("local.follow.unfollowed",e),yi=e=>si("local.follow.requested",e),vi=e=>si("local.follow.accepted",e),bi=e=>si("local.follow.requestDeclined",e);class wi{constructor(e){const{http:t}=Ve();this.queryParams=e,this.http=t}loadFirstPage(){return this.onFetch("first")}loadNextPage(){return this.onFetch("next")}loadPreviousPage(){return this.onFetch("prev")}async onFetch(e="first"){var t,n,a,r;if("prev"===e&&!this.previousToken)return;if("next"===e&&!this.nextToken)return;let s;"prev"===e&&(s=this.previousToken),"next"===e&&(s=this.nextToken);const o=await this.getRequest(this.queryParams,s);return"first"===e&&(this.nextToken=null===(t=o.paging)||void 0===t?void 0:t.next,this.previousToken=null===(n=o.paging)||void 0===n?void 0:n.previous),"prev"===e&&(this.previousToken=null===(a=o.paging)||void 0===a?void 0:a.previous),"next"===e&&(this.nextToken=null===(r=o.paging)||void 0===r?void 0:r.next),o}getNextToken(){return this.nextToken}getPrevToken(){return this.previousToken}}class Ii extends wi{async getRequest(e,t){const{limit:n=de,userId:a}=e,r=Kn(e,["limit","userId"]),s=t?{token:t}:{limit:n},o=Ve().userId===a?"/api/v4/me/followers":`/api/v4/users/${a}/followers`,{data:i}=await this.http.get(o,{params:Object.assign(Object.assign({},r),{options:s,isDeleted:!1})});return i}}class Ci{constructor(e,t){this.query=e,this.cacheKey=t}}var Si;!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"}(Si||(Si={}));class Oi extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.follows.map(We("follow"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(We("follow"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.to&&a){switch(e){case Si.OnDeclined:case Si.OnCanceled:case Si.OnUnfollowed:case Si.OnDeleted:a.data=a.data.filter((e=>e!==We("follow")(t)));break;case Si.OnRequested:case Si.OnAccepted:case Si.OnFollowed:a.data=[...new Set([We("follow")(t),...a.data])]}et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Ti{constructor(e){const{http:t}=Ve();this.queryParams=e,this.http=t}async onFetch(){return await this.getRequest(this.queryParams)}}class ki{constructor(e,t,n,a){this.paginationController=e,this.queryStreamId=t,this.cacheKey=n,this.callback=a}async refresh(){try{let e;if(e=this.paginationController instanceof Ti?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 Ti)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 Ti)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(ti).map(ni);return!La(this.snapshot,t)&&(this.snapshot=t,!0)}getCacheKey(){return this.cacheKey}}function Ai(e){return null!=e}const _i=({userId:e})=>t=>{const n=Ve();return Mt(n,"user.deleted","user.deleted",(n=>{const a=Zr(n);Ln(a);const r=Ze(["follow","get",We("follow")({from:a.users[0].userId,to:e})]);r&&t(null==r?void 0:r.data)}))};class Ei extends ki{constructor(e,t){const n=O.default(Object.assign(Object.assign({},e),{type:"follower"})),a=["follow","collection",n];super(new Ii(e),n,a,t),this.query=e,this.queryStreamController=new Oi(this.query,this.cacheKey,this.notifyChange.bind(this),Qs),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:oi,action:Si.OnFollowed},{fn:ii,action:Si.OnUnfollowed},{fn:ui,action:Si.OnAccepted},{fn:hi,action:Si.OnDeclined},{fn:di,action:Si.OnCanceled},{fn:ci,action:Si.OnDeleted},{fn:vi,action:Si.OnAccepted},{fn:bi,action:Si.OnDeclined},{fn:mi,action:Si.OnFollowed},{fn:gi,action:Si.OnUnfollowed},{fn:_i({userId:this.query.userId}),action:Si.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["follow","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]);(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;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=Ze(["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 Ri extends wi{async getRequest(e,t){const{limit:n=de,userId:a}=e,r=Kn(e,["limit","userId"]),s=t?{token:t}:{limit:n},o=Ve().userId===a?"/api/v4/me/following":`/api/v4/users/${a}/following`,{data:i}=await this.http.get(o,{params:Object.assign(Object.assign({},r),{options:s,isDeleted:!1})});return i}}class Pi extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.follows.map(We("follow"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(We("follow"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.from&&a){switch(e){case Si.OnDeclined:case Si.OnCanceled:case Si.OnUnfollowed:case Si.OnDeleted:a.data=a.data.filter((e=>e!==We("follow")(t)));break;case Si.OnRequested:case Si.OnAccepted:case Si.OnFollowed:a.data=[...new Set([We("follow")(t),...a.data])]}et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Mi=({userId:e})=>t=>{const n=Ve();return Mt(n,"user.deleted","user.deleted",(n=>{const a=Zr(n);Ln(a);const r=Ze(["follow","get",We("follow")({from:e,to:a.users[0].userId})]);r&&t(null==r?void 0:r.data)}))};class ji extends ki{constructor(e,t){const n=O.default(Object.assign(Object.assign({},e),{type:"following"})),a=["follow","collection",n];super(new Ri(e),n,a,t),this.query=e,this.queryStreamController=new Pi(this.query,this.cacheKey,this.notifyChange.bind(this),zs),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:li,action:Si.OnRequested},{fn:ui,action:Si.OnAccepted},{fn:hi,action:Si.OnDeclined},{fn:di,action:Si.OnCanceled},{fn:oi,action:Si.OnFollowed},{fn:ii,action:Si.OnUnfollowed},{fn:ci,action:Si.OnDeleted},{fn:yi,action:Si.OnRequested},{fn:vi,action:Si.OnAccepted},{fn:bi,action:Si.OnDeclined},{fn:mi,action:Si.OnFollowed},{fn:gi,action:Si.OnUnfollowed},{fn:Mi({userId:this.query.userId}),action:Si.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["follow","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]);(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;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=Ze(["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 Ui=(e,t,n,a,r,s)=>{const{forceDispatch:o,callbackDataSelector:i,callbackFilter:c}=Object.assign({forceDispatch:!1,callbackDataSelector:e=>e},s),{cache:l}=Ve();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,a=Kn(e,["data"]);c&&!c(n,d)||t(Object.assign({data:i(n)},a)),d=ti(n)};return h.push(...r.map((t=>t((t=>((t,a=!1)=>{e===t[n]&&(d&&!a&&La(d,t)||p({loading:!1,data:t,origin:"event"}))})(t,o)))))),(()=>{const t=xe(a,e,!0);Ne(t,(({error:e,data:t,loading:n,origin:a,cachedAt:r})=>{r===me?(p({data:t,origin:a,loading:!1,error:new Fe(fe,800800,"error")}),u=!0,h.forEach((e=>e()))):u||p({loading:n,data:t,origin:a,error:e}),e&&h.forEach((e=>e()))}))})(),()=>{h.forEach((e=>e()))}};var Di=Object.freeze({__proto__:null,blockUser:async e=>{const t=Ve();t.log("user/blockUser",e);const{data:n}=await t.http.post(`/api/v4/me/user-blocks/${e}`),a=t.cache&&Date.now(),{follows:r,followCounts:s}=n,o={follows:r};t.cache&&(Ln(o,{cachedAt:a}),nt(["followInfo","get",e],s[0],{cachedAt:a}));const i={follows:r.map((e=>{const t=Object.assign(Object.assign({},e),{to:e.from,from:e.to,status:"none"});return"blocked"===e.status?t:e}))},c=Vs(i);return jt("local.follow.unfollowed",c),n},unBlockUser:async e=>{const t=Ve();t.log("user/unBlockUser",e);const{data:n}=await t.http.delete(`/api/v4/me/user-blocks/${e}`),a=t.cache&&Date.now(),{follows:r,followCounts:s}=n,o={follows:r};t.cache&&(Ln(o,{cachedAt:a}),nt(["followInfo","get",e],s[0],{cachedAt:a}));const i=Vs(o);return jt("local.follow.created",i),n},onUserDidBlock:Js,onUserDidUnblock:Ws,follow:async e=>{const t=Ve();t.log("follow/follow",e);const{data:n}=await t.http.post(`/api/v4/me/following/${e}`),a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a});const r=Vs(n);return"accepted"===n.follows[0].status?jt("local.follow.created",r):jt("local.follow.requested",r),{data:n.follows[0],cachedAt:a}},unfollow:async e=>{const t=Ve();t.log("follow/unfollow",e);const{data:n}=await t.http.delete(`/api/v4/me/following/${e}`);t.cache&&Ln(n);const a=Vs(n);return jt("local.follow.unfollowed",a),!0},acceptMyFollower:async e=>{const t=Ve();t.log("follow/acceptMyFollower",e);const{data:n}=await t.http.post(`/api/v4/me/followers/${e}`);t.cache&&Ln(n);const a=Vs(n);return jt("local.follow.accepted",a),!0},declineMyFollower:async e=>{const t=Ve();t.log("follow/declineMyFollower",e);const{data:n}=await t.http.delete(`/api/v4/me/followers/${e}`);t.cache&&Ln(n);const a=Vs(n);return jt("local.follow.requestDeclined",a),!0},onUserFollowed:oi,onUserUnfollowed:ii,onFollowerDeleted:ci,onFollowerRequested:li,onFollowRequestCanceled:di,onFollowRequestAccepted:ui,onFollowRequestDeclined:hi,onFollowInfoUpdated:fi,onLocalUserFollowed:mi,onLocalUserUnfollowed:gi,onLocalFollowerRequested:yi,onLocalFollowRequestAccepted:vi,onLocalFollowRequestDeclined:bi,getFollowers:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`getFollowers(tmpid: ${s}) > listen`);const o=new Ei(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getFollowers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getFollowings:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log("For using Live Collection feature you need to enable Cache!");const s=Date.now();a(`getFollowings(tmpid: ${s}) > listen`);const o=new ji(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getFollowings(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getFollowInfo:(e,t)=>Ui(e,t,"userId",pi,[fi],{forceDispatch:!0}),getMyFollowInfo:e=>{const{userId:t}=kt();return Ui(t,e,"userId",pi,[fi],{forceDispatch:!0})}});class xi{constructor(e,t,n){this._syncingStoriesCount=0,this._errorStoriesCount=0,this._targetId=e,this._lastStoryExpiresAt=t,this._lastStorySeenExpiresAt=n,this.cacheStoryExpireTime=Ze(["story-expire",this._targetId]),this.cacheStoreSeenTime=Ze(["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=Ze(["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 Ze(["story-sync-state",this._targetId]),this.isContainUnSyncedStory?this.localLastStoryExpires>e&&this.localLastStoryExpires>t:this.lastStoryExpiresAt>e&&this.lastStoryExpiresAt>t}getTotalStoryByStatus(){const e=Xe(["story","get"]);if(!e)return this._errorStoriesCount=0,void(this._syncingStoriesCount=0);const t=e.reduce(((e,t)=>{const{data:{targetId:n,syncState:a,isDeleted:r}}=t;return n!==this._targetId||r||(e[a]+=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 qi=e=>{const{targetType:t,targetId:n,lastStoryExpiresAt:a,lastStorySeenExpiresAt:r,targetUpdatedAt:s,localFilter:o}=e,i=new xi(n,a,r);return{targetType:t,targetId:n,lastStoryExpiresAt:a,updatedAt:s,hasUnseen:i.getHasUnseenFlag(),syncingStoriesCount:i.syncingStoriesCount,failedStoriesCount:i.failedStoriesCount,localFilter:o,localLastExpires:i.localLastStoryExpires,localLastSeen:i.localLastStorySeenExpiresAt,localSortingDate:i.getLocalLastSortingDate()}},Ni=async e=>{const t=Ve();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:a}=e,r=Kn(e,["isPublic"]);n=await t.http.post("/api/v3/channels",Object.assign(Object.assign({},r),{isPublic:"community"===(null==e?void 0:e.type)?a:void 0}))}const a=await Pa(n.data),r=t.cache&&Date.now();t.cache&&Ln(a,{cachedAt:r});const{channels:s}=a;return{data:Pr(s[0]),cachedAt:r}},Bi=async e=>{const t=Ve();let n;t.log("channel/getChannel",e),ta("channel",e);try{const{data:a}=await t.http.get(`/api/v3/channels/${encodeURIComponent(e)}`);n=await Pa(a),t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&ja(a)}catch(t){throw Oe(null==t?void 0:t.code)&&Fn("channel",e),t}const a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a});const{channels:r}=n;return{data:r.find((t=>t.channelId===e)),cachedAt:a}};Bi.locally=e=>{var t;const n=Ve();if(n.log("channel/getChannel.locally",e),!n.cache)return;const a=null===(t=Xe(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.channelPublicId===e));return a&&0!==(null==a?void 0:a.length)?{data:a[0].data,cachedAt:a[0].cachedAt}:void 0};const Li=Symbol("getWatcherUrls"),Fi=e=>Object.assign(Object.assign({},e),{get moderation(){var t;return null===(t=Ze(["streamModeration","get",e.streamId]))||void 0===t?void 0:t.data},get post(){var t;if("post"===e.referenceType)return null===(t=Ze(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=Ze(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;return null===(t=Ze(["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=Ze(["stream","get",e]))||void 0===t?void 0:t.data;if(n)return Fi(n)})).filter(Ai):[]},getLiveChat:()=>(async e=>{var t;const n=Ve();if(n.log("stream/getLiveChat",e.streamId),e.channelId){const n=null===(t=Ze(["channel","get",e.channelId]))||void 0===t?void 0:t.data;if(n)return Rr(Pr(n));const{data:a}=await Bi(e.channelId);return Rr(Pr(a))}if(e.userId===n.userId){const{data:t}=await Ni({type:"live",postId:e.postId,videoStreamId:e.streamId});return tt(["stream","get",e.streamId],{channelId:t.channelId}),t}})(e),isBanned:!e.watcherUrl,watcherUrl:null,get[Li](){return e.watcherUrl}}),Ki=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=Ze(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),$i=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=Ze(["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=Ze(["user","get",e.userId]);if(null==t?void 0:t.data)return qt(t.data)},get childrenComment(){return e.children.map((e=>{const t=Ze(["comment","get",e]);if(null==t?void 0:t.data)return null==t?void 0:t.data})).filter(Ai).map((e=>$i(e)))}});function Qi(e){return!!(e.data&&"string"!=typeof e.data&&"videoFileId"in e.data&&"thumbnailFileId"in e.data&&"video"===e.dataType)}function zi(e){return!(!e.data||"string"==typeof e.data||!("streamId"in e.data)||"liveStream"!==e.dataType)}const Vi=e=>Object.assign(Object.assign({},e),{createdById:e.createdBy}),Hi=e=>Object.assign(Object.assign({},e),{invitations:e.invitations.map(Vi),users:e.users.map(ga)}),Ji=async e=>{const t=Ve();t.log("invitation/createInvitations",e);const{data:n}=await t.http.post("/api/v1/invitations",e),a=Hi(n),r=t.cache&&Date.now();return t.cache&&Ln(a,{cachedAt:r}),jt("local.invitation.created",a.invitations),{data:a.invitations,cachedAt:r}},Wi=e=>Object.assign(Object.assign({},e),{users:e.users.map(ga),invitations:e.invitations.map(Vi)}),Gi=e=>Object.assign(Object.assign({},e),{get user(){const t=Ze(["user","get",e.invitedUserPublicId]);if(null==t?void 0:t.data)return qt(t.data)},get createdBy(){const t=Ze(["user","get",e.inviterUserPublicId]);if(null==t?void 0:t.data)return qt(t.data)},get target(){if("community"===e.targetType){const t=Ze(["community","get",e.targetId]);return(null==t?void 0:t.data)?t.data:void 0}},accept:async()=>{await(async e=>{var t;const n=Ve();n.log("invitation/acceptInvitation",e);const{data:a}=await n.http.post(`/api/v1/invitations/${e}/accept`),r=null===(t=Ze(["invitation","get",e]))||void 0===t?void 0:t.data;return r&&(nt(["invitation","get",e],{status:"approved"}),jt("local.invitation.updated",[r])),a.success})(e._id)},reject:async()=>{await(async e=>{var t;const n=Ve();n.log("invitation/rejectInvitation",e);const{data:a}=await n.http.post(`/api/v1/invitations/${e}/reject`),r=null===(t=Ze(["invitation","get",e]))||void 0===t?void 0:t.data;return r&&(nt(["invitation","get",e],{status:"rejected"}),jt("local.invitation.updated",[r])),a.success})(e._id)}}),Yi=async e=>{const t=Ve();t.log("invitation/getInvitation",e.targetType,e.targetId,e.type);const{data:n}=await t.http.get("/api/v1/invitations/me",{params:e}),a=Wi(n),r=t.cache&&Date.now();return t.cache&&Ln(a,{cachedAt:r}),{data:a.invitations[0]?Gi(a.invitations[0]):void 0,cachedAt:r}};class Xi{constructor(){this.sessions=new Map}addSession(e){this.sessions.set(e.sessionId,e)}getSession(e){return this.sessions.get(e)}updateSession(e,t){const n=this.sessions.get(e);n&&this.sessions.set(e,Object.assign(Object.assign({},n),t))}getSessionsByState(e){return Array.from(this.sessions.values()).filter((t=>t.syncState===e))}deleteSession(e){this.sessions.delete(e)}getPendingSessions(){return this.getSessionsByState("PENDING")}getSyncingSessions(){return this.getSessionsByState("SYNCING")}}let Zi=null;const ec=()=>(Zi||(Zi=new Xi),Zi),tc={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},nc="-----BEGIN PRIVATE KEY-----";function ac(e){const n=new Uint8Array(e);let a="";return n.forEach((e=>{a+=String.fromCharCode(e)})),t.btoa(a)}function rc(e){return e<128?new Uint8Array([e]):e<256?new Uint8Array([129,e]):new Uint8Array([130,e>>8&255,255&e])}async function sc(e){let n=e;n=e.includes(nc)?e.substring(nc.length,e.length-"-----END PRIVATE KEY-----".length).replace(/\s/g,""):e.replace(/\s/g,"");const a=t.atob(n),r=new Uint8Array(a.length);for(let e=0;e<a.length;e+=1)r[e]=a.charCodeAt(e);const s=function(e){const t=new Uint8Array([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]),n=new Uint8Array([2,1,0]),a=rc(e.length),r=n.length+t.length+1+a.length+e.length,s=rc(r),o=new Uint8Array(1+s.length+r);let i=0;return o[i]=48,i+=1,o.set(s,i),i+=s.length,o.set(n,i),i+=n.length,o.set(t,i),i+=t.length,o[i]=4,i+=1,o.set(a,i),i+=a.length,o.set(e,i),o}(r);return await crypto.subtle.importKey("pkcs8",s.buffer,tc,!1,["sign"])}async function oc({timestamp:e,rooms:t}){const n=t.map((e=>Object.keys(e).sort().map((t=>`${t}=${e[t]}`)).join("&"))).join(";"),a=C.default.v4(),r=`nonceStr=${a}×tamp=${e}&data=${n}==`,s=(new TextEncoder).encode(r),o=await sc("-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDHo80SecH7FuF2\nhFYnb+l26/VN8UMLXAQFLnxciNTEwkGVFMpdezlH8rU2HtUJL4RETogbAOLVY0XM\njs6sPn8G1nALmh9qeDpUtVqFOVtBHxEZ910TLOtQiunjqJKO5nWdqZ71EC3OFluR\niGQkO84BiIFbv37ub7xl3S8XarbtKoLcyVpkDHi+1wx1pgCAn6gtBUgckPL5NR8j\nLseabl3HAXQfhTCKo4tmOFM2Dxwl1IUMmIJrJg/aIU/U0tj/1Eoo7mG0JcNWX19l\nW3EecCbi0ncCJOrkUdwlBrcjaMayaX/ubEwyUeTGiLdyc4L3GRLHjyK8xgVNXRMH\nbZWJ2a5NAgMBAAECggEASxuE+35zTFO/XydKgmvIGcWL9FbgMlXb7Vcf0nBoG945\nbiz0NVc2paraIhJXc608xbYF3qLmtAE1MVBI0ORyRdBHNxY024l/6H6SH60Ed+uI\nM4ysp5ourY6Vj+DLwpdRiI9YDjqYAQDIUmhNxJP7XPhOMoZI6st+xZQBM34ic/bv\nAMSJm9OZphSp3+qXVkFZztr2mxD2EZSJJLYxi8BCdgM2qhazalbcJ6zDKHCZWVWm\n8RRxDGldyMb/237JxETzP40tAlzOZDmBAbUgEnurDJ93RVDIE3rbZUshwgeQd18a\nem096mWgvB1AIKYgsTAR3pw+V19YWAjq/glP6fz8wQKBgQD/oQq+ukKF0PRgBeM5\ngeTjSwsdGppQLmf5ndujvoiz/TpdjDEPu6R8kigQr1rG2t4K/yfdZoI8RdmJD1al\n3Q7N9hofooSy4rj6E3txzWZCHJjHad2cnCp/O26HiReGAl7wTcfTmNdiFHhZQzm5\nJBkvWAiwuvQMNfEbnXxw6/vIDwKBgQDH7fX8gsc77JLvAWgp1MaQN/sbqVb6JeT1\nFQfR8E/WFCSmzQBtNzd5KgYuCeelwr/8DyYytvN2BzCYZXp73gI1jF3YlW5jVn74\nOY6TwQ095digwo6Z0yuxopdIOApKgAkL9PRKgNrqAf3NAyMua6lOGifzjDojC3KU\nfylQmxMn4wKBgHp2B9O/H0dEBw5JQ8W0+JX6yWQz7mEjGiR2/1W+XXb8hQ1zr709\nw1r6Gb+EghRpnZ3fBpYGGbYOMFx8wKHM+N6qW3F0ReX8v2juFGE8aRSa5oYBrWzt\nU16Idjbv8hj84cZ1PJmdyvDtpYn9rpWHOZl4rxEbPvbqkIsOMyNVqdT5AoGAOSge\nmwIIU2le2FVeohbibXiToWTYKMuMmURZ5/r72AgKMmWJKbAPe+Q3wBG01/7FRBpQ\noU8Ma0HC8s6QJbliiEyIx9JwrJWd1vkdecBHONrtA4ibm/5zD2WcOllLF+FitLhi\n3qnX6+6F0IaFGFBPJrTzlv0P4dTz/OAdv52V7GECgYEA2TttOKBAqWllgOaZOkql\nLVMJVmgR7s6tLi1+cEP8ZcapV9aRbRzTAKXm4f8AEhtlG9F9kCOvHYCYGi6JaiWJ\nZkHjeex3T+eE6Di6y5Bm/Ift5jtVhJ4jCVwHOKTMej79NPUFTJfv8hCo29haBDv6\nRXFrv+T21KCcw8k3sJeJWWQ=\n-----END PRIVATE KEY-----");return{signature:ac(await crypto.subtle.sign(tc,o,s)),nonceStr:a}}async function ic(){const e=ec(),t=e.getPendingSessions();if(0===t.length)return!0;try{const n=(new Date).toISOString(),a=t.map((e=>({sessionId:e.sessionId,roomId:e.roomId,watchSeconds:e.watchSeconds,startTime:e.startTime.toISOString(),endTime:e.endTime?e.endTime.toISOString():""}))),r=await oc({timestamp:n,rooms:a});if(!r||!r.signature)throw new Error("Signature is undefined");t.forEach((t=>{e.updateSession(t.sessionId,{syncState:"SYNCING"})}));const s={signature:r.signature,nonceStr:r.nonceStr,timestamp:n,rooms:a},o=Ve();return await o.http.post("/api/v3/user-event/room",s),t.forEach((t=>{e.updateSession(t.sessionId,{syncState:"SYNCED",syncedAt:new Date})})),!0}catch(n){return console.error("[SDK syncWatchSessions] ERROR caught:",(null==n?void 0:n.message)||n),t.forEach((t=>{const n=e.getSession(t.sessionId);if(n){const a=n.retryCount+1;a>=3?e.deleteSession(t.sessionId):e.updateSession(t.sessionId,{syncState:"PENDING",retryCount:a})}})),!1}}const cc=["live","recorded"];class lc{constructor(e){this.storage=ec(),this.client=Ve(),this.room=e}async createWatchSession(e){if(!cc.includes(this.room.status))throw new Fe("room is not in watchable state",5e5,"error");const t=("live"===this.room.status?"room_":"room_playback_")+C.default.v4(),n={sessionId:t,roomId:this.room.roomId,watchSeconds:0,startTime:e,endTime:null,syncState:"PENDING",syncedAt:null,retryCount:0};return this.storage.addSession(n),t}async updateWatchSession(e,t,n){if(!this.storage.getSession(e))throw new Error(`Watch session ${e} not found`);this.storage.updateSession(e,{watchSeconds:t,endTime:n})}syncPendingWatchSessions(){const e=Math.floor(25001*Math.random())+5e3;this.client.log("room/RoomAnalytics: syncPendingWatchSessions called, jitter delay:",`${e}ms`),setTimeout((async()=>{this.client.log("room/RoomAnalytics: Jitter delay completed, starting sync process");try{const e=this.storage.getSyncingSessions();this.client.log("room/RoomAnalytics: SYNCING sessions to reset:",e.length),e.forEach((e=>{this.storage.updateSession(e.sessionId,{syncState:"PENDING"})})),await((e=6e4)=>new Promise((t=>{if("undefined"==typeof navigator||void 0===navigator.onLine)return void t();const n=Date.now(),a=()=>{navigator.onLine||Date.now()-n>=e?t():setTimeout(a,1e3)};a()})))(6e4),this.client.log("room/RoomAnalytics: Network available"),this.client.log("room/RoomAnalytics: Calling syncWatchSessions()"),await ic(),this.client.log("room/RoomAnalytics: syncWatchSessions completed")}catch(e){console.error("Failed to sync watch sessions:",e)}}),e)}}const dc=e=>Object.assign(Object.assign({},e),{get post(){var t;if("post"===e.referenceType)return null===(t=Ze(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=Ze(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;const n=null===(t=Ze(["user","get",e.createdBy]))||void 0===t?void 0:t.data;return n?qt(n):n},get childRooms(){return e.childRoomIds&&0!==e.childRoomIds.length?e.childRoomIds.map((e=>{var t;const n=null===(t=Ze(["room","get",e]))||void 0===t?void 0:t.data;if(n)return dc(n)})).filter(Ai):[]},participants:e.participants.map((e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=Ze(["user","get",e.userId]))||void 0===t?void 0:t.data;return n?qt(n):n}}))),getLiveChat:()=>(async e=>{var t;const n=Ve();if(n.log("room/getLiveChat",e.roomId),e.liveChannelId){const n=null===(t=Ze(["channel","get",e.liveChannelId]))||void 0===t?void 0:t.data;if(n)return Rr(Pr(n));const{data:a}=await Bi(e.liveChannelId);return Rr(Pr(a))}if(e.createdBy===n.userId){const{data:t}=await Ni({type:"live",postId:e.referenceId,roomId:e.roomId});return tt(["room","get",e.roomId],{liveChannelId:t.channelId}),t}})(e),createInvitation:t=>Ji({type:"livestreamCohostInvite",targetType:"room",targetId:e.roomId,userIds:[t]}),getInvitations:async()=>{const{data:t}=await Yi({targetId:e.roomId,targetType:"room",type:"livestreamCohostInvite"});return t},analytics(){return new lc(this)}}),uc=e=>Object.assign(Object.assign({},e),{answers:e.answers.map((e=>Object.assign(Object.assign({},e),{get image(){var t;if(e.fileId)return null===(t=Ze(["file","get",e.fileId]))||void 0===t?void 0:t.data}})))});function hc(e,t){return e.map((e=>{const n=Ze(["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 a=void 0!==e.isJoined?e.isJoined:t.some((t=>function(e,t){const{userId:n}=kt();return e.communityId===t.communityId&&t.userId===n}(e,t)&&"none"!==t.communityMembership));return Object.assign(Object.assign({},e),{isJoined:a})}))}const pc=e=>{var t;return null!==(t=Object.keys(j).find((t=>e.needApprovalOnPostCreation===j[t].needApprovalOnPostCreation&&e.onlyAdminCanPost===j[t].onlyAdminCanPost)))&&void 0!==t?t:U};function fc({communities:e}){return e.map((e=>{var{needApprovalOnPostCreation:t,onlyAdminCanPost:n}=e,a=Kn(e,["needApprovalOnPostCreation","onlyAdminCanPost"]);return Object.assign({postSetting:pc({needApprovalOnPostCreation:t,onlyAdminCanPost:n})},a)}))}const mc=e=>{const t=fc({communities:e.communities}),n=e.users.map(ga),a=e.communityUsers.map((e=>{const t=n.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),r=hc(t,a);return Object.assign(Object.assign({},e),{users:e.users.map(ga),communities:r,communityUsers:a})},gc=e=>{const t=e.joinRequests.map((e=>Object.assign(Object.assign({},e),{joinRequestId:e._id}))),n=e.users.map(ga);return Object.assign(Object.assign({},e),{joinRequests:t,users:n})},yc=e=>{const t=fc({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})})),a=hc(t,n);return Object.assign(Object.assign({},e),{communities:a,communityUsers:n})},vc=e=>{const{postSetting:t,storySetting:n}=e,a=Kn(e,["postSetting","storySetting"]);return Object.assign(Object.assign(Object.assign({},a),t?j[t]:void 0),{allowCommentInStory:"boolean"!=typeof(null==n?void 0:n.enableComment)||n.enableComment})},bc=e=>{var t=Kn(e,["searchResult"]);const n=mc(t);return Object.assign({},n)},wc=e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=Ze(["user","get",e.requestorPublicId]))||void 0===t?void 0:t.data;if(n)return qt(n)},cancel:async()=>{await(async e=>{var t;const n=Ve();n.log("joinRequest/cancelJoinRequest",e.joinRequestId);const{data:a}=await n.http.delete(`/api/v4/communities/${e.targetId}/join`),r=null===(t=Ze(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return r&&(nt(["joinRequest","get",e.joinRequestId],{status:"cancelled"}),jt("local.joinRequest.deleted",[r])),a.success})(e)},approve:async()=>{await(async e=>{var t;const n=Ve();n.log("joinRequest/approveJoinRequest",e.joinRequestId);const{data:a}=await n.http.post(`/api/v4/communities/${e.targetId}/join/approve`,{userId:e.requestorInternalId}),r=null===(t=Ze(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return r&&(nt(["joinRequest","get",e.joinRequestId],{status:"approved"}),jt("local.joinRequest.updated",[r])),a.success})(e)},reject:async()=>{await(async e=>{var t;const n=Ve();n.log("joinRequest/rejectJoinRequest",e.joinRequestId);const{data:a}=await n.http.post(`/api/v4/communities/${e.targetId}/join/reject`,{userId:e.requestorInternalId}),r=null===(t=Ze(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return r&&(nt(["joinRequest","get",e.joinRequestId],{status:"rejected"}),jt("local.joinRequest.updated",[r])),a.success})(e)}});class Ic extends wi{async getRequest(e,t){const{limit:n=20,communityId:a}=e,r=Kn(e,["limit","communityId"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get(`/api/v4/communities/${a}/join`,{params:Object.assign(Object.assign({},r),{options:s})});return o}}var Cc;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(Cc||(Cc={}));class Sc extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.joinRequests.map((e=>We("joinRequest")({joinRequestId:e._id})))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>We("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===Cc.OnLocalJoinRequestUpdated){if(!a.data.find((e=>e===t[0].joinRequestId)))return}e===Cc.OnLocalJoinRequestCreated&&(a.data=[...new Set([...t.map((e=>e.joinRequestId)),...a.data])]),e===Cc.OnLocalJoinRequestDeleted&&(a.data=a.data.filter((e=>e!==t[0].joinRequestId))),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Oc=e=>{const t=Ve(),n=[Mt(t,"onJoinRequestCreated","local.joinRequest.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Tc=e=>{const t=Ve(),n=[Mt(t,"onJoinRequestUpdated","local.joinRequest.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},kc=e=>{const t=Ve(),n=[Mt(t,"onJoinRequestDeleted","local.joinRequest.deleted",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class Ac extends ki{constructor(e,t){const n=O.default(e),a=["joinRequest","collection",n];super(new Ic(e),n,a,t),this.query=e,this.queryStreamController=new Sc(this.query,this.cacheKey,this.notifyChange.bind(this),gc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){const a=e;this.queryStreamController.appendToQueryStream(a,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Oc,action:Cc.OnLocalJoinRequestCreated},{fn:Tc,action:Cc.OnLocalJoinRequestUpdated},{fn:kc,action:Cc.OnLocalJoinRequestDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a;const r=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!r)return;const s=this.applyFilter(r.data.map((e=>Ze(["joinRequest","get",e]))).filter(Ai).map((({data:e})=>e)).map(wc));(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.status&&(t=t.filter((e=>e.status===this.query.status)));const n=(()=>"firstCreated"===this.query.sortBy?yt:bt)();return t=t.sort(n),t}}var _c;!function(e){e.OnLocalInvitationCreated="onLocalInvitationCreated",e.OnLocalInvitationUpdated="onLocalInvitationUpdated",e.OnLocalInvitationCanceled="onLocalInvitationCanceled"}(_c||(_c={}));class Ec extends wi{async getRequest(e,t){const{limit:n=de}=e,a=Kn(e,["limit"]),r=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v1/invitations",{params:Object.assign(Object.assign({},a),{options:r})});return s}}class Rc extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.invitations.map(We("invitation"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(We("invitation"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===_c.OnLocalInvitationUpdated){if(!a.data.find((e=>e===t[0].invitationId)))return}e===_c.OnLocalInvitationCreated&&(a.data=[...new Set([...t.map((e=>e.invitationId)),...a.data])]),e===_c.OnLocalInvitationDeleted&&(a.data=a.data.filter((e=>e!==t[0].invitationId))),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Pc=e=>{const t=Ve(),n=[Mt(t,"onLocalInvitationCreated","local.invitation.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Mc=e=>{const t=Ve(),n=[Mt(t,"onLocalInvitationUpdated","local.invitation.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},jc=e=>{const t=Ve(),n=[Mt(t,"onLocalInvitationCanceled","local.invitation.canceled",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class Uc extends ki{constructor(e,t){const n=O.default(e),a=["invitation","collection",n];super(new Ec(e),n,a,t),this.query=e,this.queryStreamController=new Rc(this.query,this.cacheKey,this.notifyChange.bind(this),Hi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:Pc,action:_c.OnLocalInvitationCreated},{fn:Mc,action:_c.OnLocalInvitationUpdated},{fn:jc,action:_c.OnLocalInvitationCanceled}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["invitation","get",e]))).filter(Ai).map((({data:e})=>Gi(e))))&&void 0!==r?r:[]);(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.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?yt:bt)();return t=t.sort(n),t}}const Dc=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=Ze(["category","get",e]);if(null==t?void 0:t.data)return Ki(t.data)})).filter((e=>!!e))},get avatar(){var t;if(!e.avatarFileId)return;return null===(t=Ze(["file","get",e.avatarFileId]))||void 0===t?void 0:t.data},createInvitations:async t=>{await Ji({type:"communityMemberInvite",targetType:"community",targetId:e.communityId,userIds:t})},getMemberInvitations:(t,n)=>((e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`getInvitations: (tmpid: ${s}) > listen`);const o=new Uc(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{at(c)})),()=>{a(`getInvitations (tmpid: ${s}) > dispose`),i.forEach((e=>e()))}})(Object.assign(Object.assign({},t),{targetId:e.communityId,targetType:"community",type:"communityMemberInvite"}),n),getInvitation:async()=>{const{data:t}=await Yi({targetType:"community",targetId:e.communityId});return t},join:async()=>(async e=>{var t;const n=Ve();n.log("community/joinRequest",e);const{data:a}=await n.http.post(`/api/v4/communities/${e}/join`),r=gc(a),s=n.cache&&Date.now();n.cache&&Ln(r,{cachedAt:s});const o="approved"===r.joinRequests[0].status?"success":"pending";if("success"===o&&n.cache){const n=null===(t=Ze(["community","get",e]))||void 0===t?void 0:t.data;if(n){const t=Object.assign(Object.assign({},n),{isJoined:!0});nt(["community","get",e],t)}}return jt("v4.local.community.joined",r.joinRequests),"success"===o?{status:o}:{status:o,request:wc(r.joinRequests[0])}})(e.communityId),getJoinRequests:(t,n)=>((e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`getJoinRequests: (tmpid: ${s}) > listen`);const o=new Ac(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{at(c)})),()=>{a(`getJoinRequests (tmpid: ${s}) > dispose`),i.forEach((e=>e()))}})(Object.assign(Object.assign({},t),{communityId:e.communityId}),n),getMyJoinRequest:async()=>{const{data:t}=await(async e=>{const t=Ve();t.log("community/myJoinRequest",e);const{data:n}=await t.http.get(`/api/v4/communities/${e}/join/me`),a=gc(n),r=t.cache&&Date.now();return t.cache&&Ln(a,{cachedAt:r}),{data:a.joinRequests[0]?wc(a.joinRequests[0]):void 0,cachedAt:r}})(e.communityId);return t}}),xc=e=>{const t=gs();return Object.assign(Object.assign({},e),{analytics:{markAsClicked:(n,a,r)=>{t.markProductAsClicked(e,n,a,r)},markAsViewed:(n,a,r)=>{t.markProductAsViewed(e,n,a,r)}}})},qc=e=>Zn(e,{childrenPosts:e.children.map((e=>{var t;return null===(t=Ze(["post","get",e]))||void 0===t?void 0:t.data})).filter(Ai).map(qc),analytics:{markAsViewed:()=>{gs().markPostAsViewed(e.postId)},markAsMeaningfullyViewed:t=>{gs().markPostAsMeaningfullyViewed(e.postId,t)}},get productTags(){var t,n;return null!==(n=null===(t=e.productTags)||void 0===t?void 0:t.map((e=>(e=>{var t;const n=null===(t=Ze(["product","get",e.productId]))||void 0===t?void 0:t.data;return Object.assign(Object.assign({},e),{product:n?xc(n):void 0})})(e))))&&void 0!==n?n:[]},get latestComments(){return e.comments&&e.comments.map((e=>{var t;const n=null===(t=Ze(["comment","get",e]))||void 0===t?void 0:t.data;return n?$i(n):null})).filter(Boolean)||[]},get creator(){const t=Ze(["user","get",e.postedUserId]);if(null==t?void 0:t.data)return qt(t.data)},get targetCommunity(){var t;const n=null===(t=Ze(["community","get",e.targetId]))||void 0===t?void 0:t.data;if(n)return Dc(n)},getImageInfo(){var t,n;return function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"image"!==e.dataType)}(e)?null===(n=Ze(["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,a;return Qi(e)?null===(a=Ze(["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===a?void 0:a.data:void 0},getVideoThumbnailInfo(){var t,n;return Qi(e)?null===(n=Ze(["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=Ze(["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(!zi(e))return;const a=null===(n=Ze(["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 a?Fi(a):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 a=null===(n=Ze(["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 a?uc(a):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=Ze(["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=Ze(["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 a=null===(n=Ze(["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 a?dc(a):void 0}}),Nc=(e,t)=>{"message"===e?jt("local.message.updated",{messages:[t]}):"post"===e?jt("post.updated",{posts:[t]}):"comment"===e?jt("comment.updated",{comments:[t]}):"story"===e&&jt("story.updated",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[t]})},Bc=async(e,t,n,a)=>{var r,s,o;const i=Ve();if(i.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Fe("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:a});if(i.cache){const a=Ze([e,"get",t]);if(!a||(null===(r=a.data.myReactions)||void 0===r?void 0:r.includes(n)))return!0;const l=Object.assign(Object.assign({},a.data),{reactionsCount:a.data.reactionsCount+1,myReactions:[...null!==(s=a.data.myReactions)&&void 0!==s?s:[],n],reactions:Object.assign(Object.assign({},a.data.reactions),{[n]:(null!==(o=a.data.reactions[n])&&void 0!==o?o:0)+1}),updatedAt:(new Date).toISOString()});if("comment"===e)return jt("local.comment.addReaction",{comment:l,reactor:{userId:i.userId,reactionName:n,reactionId:c.addedId}}),!0;if("post"===e)return jt("local.post.addReaction",{post:l,reactor:{userId:i.userId,reactionName:n,reactionId:c.addedId}}),!0;if("story"===e)return jt("local.story.reactionAdded",{story:l,reactor:{userId:i.userId,reactionName:n,reactionId:c.addedId}}),!0;if("message"===e)return nt(["message","get",t],l),jt("local.message.updated",{messages:[l]}),!0}return!0};Bc.optimistically=(e,t,n)=>{var a,r,s,o,i;const c=Ve();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const l=Ze([e,"get",t]);if(!(null==l?void 0:l.data)||(null===(a=l.data.myReactions)||void 0===a?void 0:a.includes(n)))return;const d=Object.assign(Object.assign({},l.data),{reactionsCount:l.data.reactionsCount+1,myReactions:[...null!==(r=l.data.myReactions)&&void 0!==r?r:[],n],reactions:Object.assign(Object.assign({},l.data.reactions),{[n]:(null!==(s=l.data.reactions[n])&&void 0!==s?s:0)+1})});return nt([e,"get",t],d,{cachedAt:me}),Nc(e,d),null!==(i=null===(o=null==d?void 0:d.myReactions)||void 0===o?void 0:o.includes(n))&&void 0!==i&&i};const Lc=(e,t)=>{var n;return null!==(n=null!=t?t:(e=>{var t,n;const a={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=Ze(["messageMarker","get",We("messageMarker")(a)]))||void 0===n?void 0:n.data})(e))&&void 0!==n?n:{readCount:0,deliveredCount:0}},Fc=(e,t)=>{const n=t.publicId!==t.messageId;return(async(e,t,n,a)=>{var r,s;const o=Ve();if(o.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Fe("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:i}=await o.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:a}});if(o.cache){const a=Ze([e,"get",t]);if(!a)return!0;const c=Object.assign(Object.assign({},a.data),{reactionsCount:Math.max(0,a.data.reactionsCount-1),myReactions:(null!==(r=a.data.myReactions)&&void 0!==r?r:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},a.data.reactions),{[n]:Math.max(0,(null!==(s=a.data.reactions[n])&&void 0!==s?s:0)-1)}),updatedAt:(new Date).toISOString()});if("comment"===e)return jt("local.comment.removeReaction",{comment:c,reactor:{reactionId:i.removedId,reactionName:n,userId:o.userId}}),!0;if("post"===e)return jt("local.post.removeReaction",{post:c,reactor:{reactionId:i.removedId,reactionName:n,userId:o.userId}}),!0;if("story"===e)return jt("local.story.reactionRemoved",{story:c,reactor:{userId:o.userId,reactionName:n,reactionId:i.removedId}}),!0;if("message"===e)return nt(["message","get",t],c),jt("local.message.updated",{messages:[c]}),!0}return!0})("message",n?t.publicId:t.messageId,e,n?3:5)},Kc=e=>Object.assign(Object.assign({},e),{users:e.users.map(ga)}),$c=e=>Object.assign(Object.assign({},e),{get status(){return e.status},get userId(){return e.userId},get eventId(){return e.eventId},get respondedAt(){return e.respondedAt},get event(){const t=Ze(["event","get",e.eventId]);if(null==t?void 0:t.data)return t.data},get user(){const t=Ze(["user","get",e.userId]);if(null==t?void 0:t.data)return qt(t.data)}}),Qc=e=>Object.assign(Object.assign({},e),{users:e.users.map(ga)}),zc=(e,t)=>{const n=Ve();return Mt(n,e,e,(e=>{const a=Qc(e);if(n.cache){Ln(a);const e=Ze(["event","get",a.events[0].eventId]);t(e.data)}else t(a.events[0])}))},Vc=(e,t)=>{const n=Ve();return Mt(n,e,e,(e=>{const a=Kc(e);if(n.cache){Ln(a);const e=Ze(["eventResponse","get",a.eventResponses[0].userId]);t(e.data)}else t(a.eventResponses[0])}))},Hc=async e=>{const t=Ve();t.log("event/getMyRSVP",e);const{data:n}=await t.http.get(`/api/v1/events/${e}/me/rsvp`),a=Kc(n),r=t.cache&&Date.now();return t.cache&&Ln(a,{cachedAt:r}),{data:$c(a.eventResponses[0]),cachedAt:r}};var Jc;Hc.locally=e=>{const t=Ve();if(t.log("event/getMyRSVP.locally",e),!t.cache)return;const n=Ze(["event","getMyRSVP",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0},function(e){e.OnEventCreated="onEventCreated",e.OnEventUpdated="onEventUpdated",e.OnEventDeleted="onEventDeleted",e.OnRSVPCreated="onRSVPCreated",e.OnRSVPUpdated="onRSVPUpdated"}(Jc||(Jc={}));class Wc extends wi{async getRequest(e,t){const{limit:n=de,eventId:a}=e,r=Kn(e,["limit","eventId"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get(`/api/v1/events/${a}/rsvp`,{params:Object.assign(Object.assign({},r),{options:s})});return o}}class Gc extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.eventResponses.map(We("eventResponse"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.eventResponses.map(We("eventResponse"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===Jc.OnRSVPCreated&&(a.data=[...new Set([t.userId,...a.data])]),e===Jc.OnEventDeleted&&(a.data=a.data.filter((e=>e!==t.eventId))),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Yc=e=>zc("event.created",e),Xc=e=>zc("event.updated",e),Zc=e=>zc("event.deleted",e),el=e=>zc("local.event.created",e),tl=e=>zc("local.event.updated",e),nl=e=>zc("local.event.deleted",e),al=e=>Vc("event.rsvp.created",e),rl=e=>Vc("event.rsvp.updated",e),sl=e=>Vc("local.rsvp.created",e),ol=e=>Vc("local.rsvp.updated",e);class il extends ki{constructor(e,t){const n=O.default(e),a=["eventResponse","collection",n];super(new Wc(e),n,a,t),this.query=e,this.queryStreamController=new Gc(this.query,this.cacheKey,this.notifyChange.bind(this),Kc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:al,action:Jc.OnRSVPCreated},{fn:rl,action:Jc.OnRSVPUpdated},{fn:sl,action:Jc.OnRSVPCreated},{fn:ol,action:Jc.OnRSVPUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a;const r=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!r)return;const s=r.data.map((e=>Ze(["eventResponse","get",e]))).filter(Ai).map((({data:e})=>$c(e)));(this.shouldNotify(s)||"event"!==e)&&this.callback({data:s,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}const cl=(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`getRSVPs: (tmpid: ${s}) > listen`);const o=new il(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getRSVPs (tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},ll=e=>Object.assign(Object.assign({},e),{get creator(){const t=Ze(["user","get",e.userId]);if(null==t?void 0:t.data)return qt(t.data)},get targetCommunity(){if(!e.originId)return;const t=Ze(["community","get",e.originId]);return(null==t?void 0:t.data)?Dc(t.data):void 0},get coverImage(){if(!e.coverImageFileId)return;const t=Ze(["file","get",e.coverImageFileId]);return(null==t?void 0:t.data)?t.data:void 0},get post(){if(!e.postId)return;const t=Ze(["post","get",e.postId]);return(null==t?void 0:t.data)?qc(t.data):void 0},get room(){var t;if(!e.postId)return;const n=null===(t=Xe(["room","get"]))||void 0===t?void 0:t.filter((t=>t.data.referenceId===e.postId));return(null==n?void 0:n.length)&&n[0].data?dc(n[0].data):void 0},createRSVP:async t=>{const{data:n}=await(async(e,t)=>{const n=Ve();n.log("event/createRSVP",e,t);const{data:a}=await n.http.post(`/api/v1/events/${e}/rsvp`,{status:t});jt("local.rsvp.created",a);const r=Kc(a),s=n.cache&&Date.now();return n.cache&&Ln(r,{cachedAt:s}),{data:$c(r.eventResponses[0]),cachedAt:s}})(e.eventId,t);return n},updateRSVP:async t=>{const{data:n}=await(async(e,t)=>{const n=Ve();n.log("event/updateRSVP",e,t);const{data:a}=await n.http.put(`/api/v1/events/${e}/rsvp`,{status:t});jt("local.rsvp.updated",a);const r=Kc(a),s=n.cache&&Date.now();return n.cache&&Ln(r,{cachedAt:s}),{data:$c(r.eventResponses[0]),cachedAt:s}})(e.eventId,t);return n},getMyRSVP:async()=>{const{data:t}=await Hc(e.eventId);return t},getRSVPs:(t,n)=>cl(Object.assign({eventId:e.eventId},t),n)}),dl={ad:e=>{const t=gs(),{image9_16:n,image1_1:a}=e,r=Kn(e,["image9_16","image1_1"]);return Object.assign(Object.assign({},r),{analytics:{markAsSeen:n=>{t.markAdAsViewed(e,n)},markLinkAsClicked:n=>{t.markAdAsClicked(e,n)}},get advertiser(){var t,n;const a=null===(t=Ze(["advertiser","get",e.advertiserId]))||void 0===t?void 0:t.data;if(!a)return;const r=null===(n=Ze(["file","get",a.avatarFileId]))||void 0===n?void 0:n.data;return Object.assign(Object.assign({},a),{avatar:r})},get image1_1(){const e=Ze(["file","get",a]);if(e)return e.data||void 0},get image9_16(){const e=Ze(["file","get",n]);if(e)return e.data||void 0}})},comment:$i,post:qc,user:qt,category:Ki,stream:Fi,story:e=>{const t=gs(),n=Ze(["storyTarget","get",e.targetId]),a=Ze(["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 a=Ze(["file","get",null===(n=null===(t=e.data)||void 0===t?void 0:t.videoFileId)||void 0===n?void 0:n.original]);if(!a)return;const{data:r}=a;return r||void 0},get imageData(){var t,n;if(!(null===(t=e.data)||void 0===t?void 0:t.fileId))return;const a=Ze(["file","get",null===(n=e.data)||void 0===n?void 0:n.fileId]);if(!a)return;const{data:r}=a;return r?Object.assign(Object.assign({},r),{fileUrl:`${r.fileUrl}?size=full`}):void 0},get community(){if("community"===e.targetType&&a)return(null==a?void 0:a.data)||void 0},get communityCategories(){if("community"!==e.targetType)return;if(!a)return;const{data:{categoryIds:t}}=a;return 0!==t.length?t.map((e=>{const t=Ze(["category","get",e]);return(null==t?void 0:t.data)||void 0})).filter((e=>void 0!==e)):void 0},get creator(){const t=Ze(["user","get",e.creatorPublicId]);if(null==t?void 0:t.data)return qt(t.data)},get storyTarget(){if(null==n?void 0:n.data)return qi(n.data)},get isSeen(){const t=Ze(["story-last-seen",e.targetId]);if(!(null==n?void 0:n.data))return!1;const a=(null==t?void 0:t.data)?new Date(t.data).getTime():0,r=new Date(null==n?void 0:n.data.lastStorySeenExpiresAt).getTime()||0,s=new Date(e.expiresAt).getTime();return Math.max(a,r)>=s}})},storyTarget:qi,message:e=>{const t=Kn(e,["creatorPrivateId"]);return Object.assign(Object.assign({},t),{get readCount(){return Lc(e).readCount},get deliveredCount(){return Lc(e).deliveredCount},get creator(){var t;return null===(t=Ze(["user","get",e.creatorId]))||void 0===t?void 0:t.data},markRead:()=>vo(e),addReaction:t=>((e,t)=>{const n=t.publicId!==t.messageId;return Bc("message",n?t.publicId:t.messageId,e,n?3:5)})(t,e),removeReaction:t=>Fc(t,e)})},reactor:e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=Ze(["user","get",e.userId]))||void 0===t?void 0:t.data;if(n)return qt(n)}}),channel:Rr,pinnedPost:e=>{var t;const n=Ze(["post","get",e.referenceId]),a=null===(t=Xe(["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:a,get post(){if(null==n?void 0:n.data)return qc(n.data)},get target(){const e=Ze(["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})=>Ze(["user","get",e]))).filter(Ai).map((({data:e})=>e)).map((e=>qt(e))),get event(){const t=Ze(["event","get",e.actionReferenceId]);if(null==t?void 0:t.data)return t.data}}),community:Dc,invitation:Gi,joinRequest:wc,channelMember:Na,room:dc,event:ll,eventResponse:$c,product:xc,poll:uc},ul=async e=>{const t=Ve();t.log("user/getUsers",e);const n=e.map((e=>encodeURIComponent(e))),{data:a}=await t.http.get("/api/v3/users/list",{params:{userIds:n}}),r=Zr(a),s=t.cache&&Date.now();return t.cache&&Ln(r,{cachedAt:s}),jt("user.fetched",a),{data:r.users.map((e=>dl.user(e))),cachedAt:s}};ul.locally=e=>{var t;const n=Ve();if(n.log("user/getUsers.locally",e),!n.cache)return;const a=e.map((e=>Ze(["user","get",e]))).filter(Boolean),r=a.map((({data:e})=>dl.user(e))),s=null===(t=a.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==a?void 0:a.length)<e.length?void 0:{data:r,cachedAt:s.cachedAt}};const hl=e=>is("user.updated",e),pl=e=>is("user.flagged",e),fl=e=>is("user.unflagged",e),ml=e=>is("user.flagCleared",e),gl=e=>is("user.fetched",e),yl=async e=>{const t=Ve();t.log("user/getUser",e),ta("user",e);try{const{data:n}=await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`),a=t.cache&&Date.now(),r=Zr(n);return t.cache&&Ln(r,{cachedAt:a}),jt("user.fetched",n),{data:r.users.find((t=>t.userId===e)),cachedAt:a}}catch(t){throw Oe(null==t?void 0:t.code)&&Fn("user",e),t}};yl.locally=e=>{const t=Ve();if(t.log("user/getUser.locally",e),!t.cache)return;const n=Ze(["user","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class vl extends wi{async getRequest(e,t){const{limit:n=de}=e,a=Kn(e,["limit"]),r=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},a),{options:r,isDeleted:!1})});return s}}class bl extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.users.map(We("user"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(We("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Ze(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],et(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var wl;!function(e){e.OnUserDeleted="onUserDeleted",e.OnUserUpdated="onUserUpdated",e.OnUserFlagged="onUserFlagged",e.OnUserUnflagged="onUserUnflagged",e.OnUserFlagCleared="onUserFlagCleared"}(wl||(wl={}));class Il extends ki{constructor(e,t){const n=O.default(e),a=["user","collection",n];super(new vl(e),n,a,t),this.query=e,this.queryStreamController=new bl(this.query,this.cacheKey,this.notifyChange.bind(this),Zr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:cs,action:wl.OnUserDeleted},{fn:hl,action:wl.OnUserUpdated},{fn:pl,action:wl.OnUserFlagged},{fn:fl,action:wl.OnUserUnflagged},{fn:ml,action:wl.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["user","get",e]))).filter(Ai).map((({data:e})=>e)).map(dl.user))&&void 0!==r?r:[]);(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;const n=(()=>"firstCreated"===this.query.sortBy?yt:bt)();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 Cl extends wi{async getRequest(e,t){const{limit:n=de}=e,a=Kn(e,["limit"]),r=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v4/me/user-blocks",{params:Object.assign(Object.assign({},a),{options:r,isDeleted:!1})});return s}}var Sl;!function(e){e.OnBlocked="onBlocked",e.OnUnblocked="onUnblocked"}(Sl||(Sl={}));class Ol extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.users.map(We("user"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(We("user"))])]}))}}reactor(e){return t=>{var n,a;const r=e===Si.OnFollowed||e===Sl.OnUnblocked,s=e===Sl.OnBlocked;if(r||s){const e=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data,r=null!==(a=null==e?void 0:e.data)&&void 0!==a?a:[],o=s?[...new Set([...r,t.userId])]:r.filter((e=>e!==t.userId));et(this.cacheKey,Object.assign(Object.assign({},e),{data:o}))}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Tl=(e,t,n)=>a=>e((e=>{var r;if(!e)return e;const s=[n,"get",`${e[t]}`],o=null===(r=Ze(s))||void 0===r?void 0:r.data;return o?a(o):void 0}));class kl extends ki{constructor(e,t){const n=O.default(e),a=["blockedUsers","collection",n];super(new Cl(e),n,a,t),this.query=e,this.queryStreamController=new Ol(this.query,this.cacheKey,this.notifyChange.bind(this),xs),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:cs,action:wl.OnUserDeleted},{fn:Tl(mi,"to","user"),action:Si.OnFollowed},{fn:Tl(oi,"to","user"),action:Si.OnFollowed},{fn:e=>Js((t=>{var n;if(t.from!==Ve().userId)return;const a=null===(n=Ze(["user","get",t.to]))||void 0===n?void 0:n.data;a&&e(a)})),action:Sl.OnBlocked},{fn:e=>Ws((t=>{var n;if(t.from!==Ve().userId)return;const a=null===(n=Ze(["user","get",t.to]))||void 0===n?void 0:n.data;a&&e(a)})),action:Sl.OnUnblocked}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["user","get",e]))).filter(Ai).map((({data:e})=>e)).map(dl.user))&&void 0!==r?r:[]);(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;return t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}class Al extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.users.map(We("user"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(We("user"))])]}))}}reactor(e){return t=>{var n,a;if(t&&(e===Sl.OnBlocked||e===Sl.OnUnblocked)){const r=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data,s=null!==(a=null==r?void 0:r.data)&&void 0!==a?a:[],o=e===Sl.OnBlocked?[...new Set([...s,t.userId])]:s.filter((e=>e!==t.userId));et(this.cacheKey,Object.assign(Object.assign({},r),{data:o}))}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class _l extends wi{async getRequest(e,t){const{limit:n=ue}=e,a=Kn(e,["limit"]),r=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v4/me/blockers",{params:Object.assign(Object.assign({},a),{options:r,isDeleted:!1})});return s}}class El extends ki{constructor(e){const t=`blocking-users-${Ve().userId}`,n={},a=["blockingUsers","collection",t];super(new _l(n),t,a,e),this.queryStreamController=new Al(n,this.cacheKey,this.notifyChange.bind(this),Ls),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:cs,action:wl.OnUserDeleted},{fn:e=>Js((t=>{var n;if(t.to!==Ve().userId)return;const a=null===(n=Ze(["user","get",t.from]))||void 0===n?void 0:n.data;a&&e(a)})),action:Sl.OnBlocked},{fn:e=>Ws((t=>{var n;if(t.to!==Ve().userId)return;const a=null===(n=Ze(["user","get",t.from]))||void 0===n?void 0:n.data;a&&e(a)})),action:Sl.OnUnblocked}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["user","get",e]))).filter(Ai).map((({data:e})=>e)).map(dl.user))&&void 0!==r?r:[]);(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;return t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}class Rl extends wi{async getRequest(e,t){const{limit:n=de,displayName:a}=e,r=Kn(e,["limit","displayName"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},r),{keyword:a,options:s,isDeleted:!1})});return o}}class Pl extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.users.map(We("user"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(We("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Ze(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],et(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Ml extends ki{constructor(e,t){var n;const a=O.default(e),r=["user","collection",a];super(new Rl(e),a,r,t),this.query=Object.assign(Object.assign({},e),{filter:null!==(n=e.filter)&&void 0!==n?n:"all"}),this.queryStreamController=new Pl(this.query,this.cacheKey,this.notifyChange.bind(this),Zr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:cs,action:wl.OnUserDeleted},{fn:hl,action:wl.OnUserUpdated},{fn:pl,action:wl.OnUserFlagged},{fn:fl,action:wl.OnUserUnflagged},{fn:ml,action:wl.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["user","get",e]))).filter(Ai).map((({data:e})=>e)).map(dl.user))&&void 0!==r?r:[]);(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;return"flagged"===this.query.filter&&(t=t.filter((e=>!!e.hashFlag))),t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}const jl=async({viewId:e,viewedType:t,limit:n,token:a})=>{const r=Ve(),s={};a?s.token=a:s.limit=n;const o=`/api/v1/analytics/views/${"post"===t?"posts":"stories"}/${e}/users`,i=await r.http.get(o,{params:s});return Ln(i.data),i.data};var Ul;!function(e){e.DEFAULT="default",e.PARTIAL="partial"}(Ul||(Ul={}));var Dl=Object.freeze({__proto__:null,Relationship:Di,getUserByIds:ul,updateUser:async(e,t)=>{const n=Ve();n.log("user/updateUser",e,t);const{data:a}=await n.http.put("/api/v3/users/",Object.assign(Object.assign({userId:e},t),{createNewUserWhenNotFound:!1})),r=Zr(a),s=n.cache&&Date.now();return n.cache&&Ln(r,{cachedAt:s}),jt("user.updated",a),{data:r.users.find((t=>t.userId===e)),cachedAt:s}},flagUser:async e=>{const t=Ve();t.log("user/flagUser",e);const{data:n}=await t.http.post(`api/v4/me/flags/${encodeURIComponent(e)}`),a=Zr(n);return t.cache&&Ln(a),jt("user.flagged",n),!!a},unflagUser:async e=>{const t=Ve();t.log("user/unflag",e);const{data:n}=await t.http.delete(`/api/v4/me/flags/${encodeURIComponent(e)}`),a=Zr(n);return t.cache&&Ln(a),jt("user.unflagged",n),!!a},isUserFlaggedByMe:async e=>{const t=Ve();t.log("user/isUserFlaggedByMe",e);const{data:{isFlagByMe:n}}=await t.http.get(`/api/v3/users/${e}/isFlagByMe`);return n},getAllBlockedUsers:async()=>{Ve().log("user/getAllBlockedUsers");const e=Bs();return await e.ensureFetched(),e.getCachedUsers()},getAllBlockingUsers:async()=>{Ve().log("user/getAllBlockingUsers");const e=$s();return await e.ensureFetched(),e.getCachedUsers()},onUserUpdated:hl,onUserDeleted:cs,onUserFlagged:pl,onUserUnflagged:fl,onUserFlagCleared:ml,getUser:(e,t)=>Ui(e,(e=>t(Object.assign(Object.assign({},e),{data:e.data?dl.user(e.data):e.data}))),"userId",yl,[gl,hl,cs,pl,fl,ml]),getUsers:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`liveUsers(tmpid: ${s}) > listen`);const o=new Il(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`liveUsers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getBlockedUsers:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`getBlockedUsers(tmpid: ${s}) > listen`);const o=new kl(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getBlockedUsers(tmpid: ${s}) > dispose`),i.forEach((e=>e())),at(c)}},getBlockingUsers:e=>{const{log:t,cache:n}=Ve();n||console.log(pe);const a=Date.now();t(`getBlockingUsers(tmpid: ${a}) > listen`);const r=new El(e),s=r.startSubscription(),o=r.getCacheKey();return s.push((()=>at(o))),()=>{t(`getBlockingUsers(tmpid: ${a}) > dispose`),s.forEach((e=>e())),at(o)}},searchUserByDisplayName:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`liveSearchUsers(tmpid: ${s}) > listen`);const o=new Ml(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`liveSearchUsers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getReachedUsers:(e,t)=>{let n=(e=!1)=>{};const{log:a,cache:r}=Ve(),s=["viewedUsers","collection",{viewId:e.viewId,viewedType:e.viewedType}];r||console.log(pe);const o=Date.now();a(`getReachUsers(tmpid: ${o}) > listen`);const{limit:i,viewId:c,viewedType:l}=e;return n=(e=!1)=>{var a,r,o;const d=null===(a=Ze(s))||void 0===a?void 0:a.data,u=null!==(r=null==d?void 0:d.data)&&void 0!==r?r:[];if(!e&&u.length>0&&!(null==d?void 0:d.params.page))return;const h=xe(jl,{viewId:c,viewedType:l,limit:i||10,token:e||null===(o=null==d?void 0:d.params.page)||void 0===o?void 0:o.next});Ne(h,(e=>{var a,r,o,i,c;let l=null!==(o=null===(r=null===(a=Ze(s))||void 0===a?void 0:a.data)||void 0===r?void 0:r.data)&&void 0!==o?o:[];(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||[]};et(s,d),(e=>{var a,r;let s=[];(null==e?void 0:e.data)&&(s=e.data.map((e=>Ze(["user","get",e]))).filter(Boolean).map((e=>null==e?void 0:e.data))||[]),t({onNextPage:n,data:s,hasNextPage:!!(null===(r=null===(a=e.params)||void 0===a?void 0:a.page)||void 0===r?void 0:r.next),loading:e.loading||!1})})(d)}),qe(he,2e3))},n(!0),()=>{a(`getReachUsers(tmpid: ${o}) > dispose`),at(s)}},get AmityUserSearchMatchType(){return Ul}});const xl=async e=>{const t=Ve();t.log("file/getFile",e);const{data:n}=await t.http.get(`/api/v3/files/${e}`),a=t.cache&&Date.now();return t.cache&&Ln({files:[n]},{cachedAt:a}),{data:n,cachedAt:a}};xl.locally=e=>{const t=Ve();if(t.log("file/getFile.locally",e),!t.cache)return;const n=Ze(["file","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const ql=async(e,t,n)=>{const a=Ve();a.log("file/uploadVideo",e);const r=e.getAll("files");if(!r.length)throw new Error("The formData object must have a `files` key.");const s=No().getFileAccessType();e.append("accessType",s),e.append("preferredFilename",r[0].name),t&&e.append("feedType",t);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await a.upload.post("/api/v4/videos",e,{headers:o,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),c=a.cache&&Date.now();return a.cache&&Ln({files:i},{cachedAt:c}),{data:i,cachedAt:c}},Nl=async(e,t,n)=>{const a=Ve();a.log("file/uploadImage",e);const r=e.getAll("files");if(null==r?void 0:r.length)console.warn("Deprecation Warning: `files` is deprecated, please use `file` instead."),e.append("preferredFilename",r[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 s=No().getFileAccessType();e.append("accessType",s);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await a.upload.post("/api/v4/images",e,{headers:o,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),c=a.cache&&Date.now();return a.cache&&Ln({files:i},{cachedAt:c}),{data:i,cachedAt:c}};var Bl=Object.freeze({__proto__:null,getFile:xl,uploadFile:async(e,t)=>{const n=Ve();n.log("file/uploadFile",e);const a=e.getAll("files");if(!a.length)throw new Error("The formData object must have a `files` key.");const r=No().getFileAccessType();e.append("accessType",r),e.append("preferredFilename",a[0].name);const s="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:o}=await n.upload.post("/api/v4/files",e,{headers:s,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),i=n.cache&&Date.now();return n.cache&&Ln({files:o},{cachedAt:i}),{data:o,cachedAt:i}},deleteFile:async e=>{const t=Ve();return t.log("file/deleteFile",e),await t.http.delete(`/api/v3/files/${e}`),at(["file","get",e],!0),{success:!0}},fileUrlWithSize:(e,t)=>`${e}?size=${t}`,uploadVideo:ql,uploadImage:Nl,updateAltText:async(e,t)=>{const n=Ve();n.log("file/updateAltText",t);const{data:a}=await n.http.put(`/api/v3/files/${e}`,{altText:t}),r=n.cache&&Date.now();return n.cache&&Ln({files:[a]},{cachedAt:r}),!0},uploadClip:async(e,t,n)=>{const a=Ve();a.log("file/uploadClip",e);const r=e.get("files");if(!r)throw new Error("The formData object must have a `files` key.");const s=No().getFileAccessType();e.append("accessType",s),e.append("preferredFilename",r.name),t&&e.append("feedType",t);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await a.upload.post("/api/v4/clips",e,{headers:o,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),c=a.cache&&Date.now();return a.cache&&Ln({files:i},{cachedAt:c}),{data:i,cachedAt:c}},uploadAudio:async(e,t)=>{const n=Ve();n.log("file/uploadAudio",e);const a=e.getAll("file");if(0===a.length)throw new Error("The formData object must have a `file` key with audio file.");const r=a[0],s=No().getFileAccessType();e.append("accessType",s),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))}}),i=n.cache&&Date.now();return n.cache&&Ln({files:o},{cachedAt:i}),{data:o,cachedAt:i}}});const Ll=async e=>{const t=Ve();t.log("role/queryRoles",e);const n=null!=e?e:{},{limit:a=10,queryToken:r,displayName:s,sortBy:o}=n,i=Kn(n,["limit","queryToken","displayName","sortBy"]),c=r?{token:r}:a?{limit:a}:void 0,{data:l}=await t.http.get("/api/v3/roles",{params:Object.assign(Object.assign({},i),{keyword:s,sortBy:o,options:c})}),{paging:d}=l,u=Kn(l,["paging"]),{roles:h}=u,p=t.cache&&Date.now();t.cache&&Ln(u,{cachedAt:p});const f=Re(d.next);return{data:h,cachedAt:p,prevPage:Re(d.previous),nextPage:f,paging:d}};Ll.locally=e=>{Ve().log("role/queryRoles.locally",e)};const Fl=async e=>{const t=Ve();t.log("role/getRole",e);const{data:n}=await t.http.get(`/api/v3/roles/${e}`),a=t.cache&&Date.now();return t.cache&&Ln({roles:n},{cachedAt:a}),{data:n.find((t=>t.roleId===e)),cachedAt:a}};Fl.locally=e=>{const t=Ve();if(t.log("role/getRole.locally",e),!t.cache)return;const n=Ze(["role","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Kl=async(e,t=!1)=>{const n=Ve();let a;n.log("message/getMessage",e),ta("message",e);try{const{data:t}=await n.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);a=await pa(t)}catch(t){throw Oe(null==t?void 0:t.code)&&Fn("message",e),t}const r=n.cache&&Date.now();n.cache&&Ln(a,{cachedAt:r});const{messages:s}=a;return jt("local.message.fetched",{messages:s}),{data:s.find((t=>t.messageId===e)),cachedAt:r}};Kl.locally=e=>{const t=Ve();if(t.log("message/getMessage.locally",e),!t.cache)return;const n=Ze(["message","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class $l{constructor(e,t,n){this.postId=e,this.latestCreatedAt=t,this.serverCommentCount=n}}class Ql{constructor(e,t,n){this.postId=e,this.commentId=t,this.createdAt=n}}class zl{constructor(e,t){this.postId=e,this.commentId=t}}class Vl{constructor(e,t){this.latestCommentCreatedAt=e,this.serverCommentCount=t,this.createdCommentIds=new Set,this.deletedCommentIds=new Set}}class Hl{constructor(){this.isProcessing=!1,this.tasks=[],this.commentChangeTracker=new Map}queueCommentChangeTask(e){this.tasks.push(e),this.isProcessing||this.processCommentChangeTask()}processCommentChangeTask(){if(this.isProcessing)return;if(this.isProcessing=!0,0===this.tasks.length)return void(this.isProcessing=!1);const e=this.tasks.splice(0,Hl.BATCH_SIZE),t=new Set;e.forEach((e=>{let n=!1;e instanceof $l?n=this.processResetTaskInternal(e):e instanceof Ql?n=this.processCreateTaskInternal(e):e instanceof zl&&(n=this.processDeleteTaskInternal(e)),n&&t.add(e.postId)})),t.forEach((e=>{const t=this.computeCommentCount(e);Hl.publishUpdate(e,t)})),this.isProcessing=!1,this.tasks.length>0&&this.processCommentChangeTask()}processResetTaskInternal(e){return this.commentChangeTracker.set(e.postId,new Vl(e.latestCreatedAt,e.serverCommentCount)),!0}processCreateTaskInternal(e){const t=this.commentChangeTracker.get(e.postId);return!!t&&(!t.createdCommentIds.has(e.commentId)&&(!(e.createdAt<=t.latestCommentCreatedAt)&&(t.createdCommentIds.add(e.commentId),!0)))}processDeleteTaskInternal(e){const t=this.commentChangeTracker.get(e.postId);return!!t&&(!t.deletedCommentIds.has(e.commentId)&&(t.deletedCommentIds.add(e.commentId),!0))}computeCommentCount(e){const t=this.commentChangeTracker.get(e);if(!t)return 0;const n=t.serverCommentCount+t.createdCommentIds.size-t.deletedCommentIds.size;return Math.max(0,n)}static publishUpdate(e,t){var n;const a=["post","get",e];tt(a,{localCommentCount:t});const r=null===(n=Ze(a))||void 0===n?void 0:n.data;r&&jt("local.post.updated",{posts:[r]})}}let Jl;Hl.BATCH_SIZE=50;var Wl=()=>(Jl||(Jl=new Hl),Jl);const Gl=e=>{const{posts:t,postChildren:n,videoStreamings:a}=e,r=Kn(e,["posts","postChildren","videoStreamings"]),s=fc({communities:r.communities}),o=r.communityUsers.map((e=>{const t=r.users.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),i=hc(s,o);let c=[];const l=t.map((t=>{var n,s,o,i;const l=null===(n=r.feeds.find((e=>e.feedId===t.feedId)))||void 0===n?void 0:n.feedType,d=e.postChildren.filter((e=>e.parentPostId===t.postId));var u,h,p;d.length>0&&zi(d[0])&&(u=a,h=null===(s=d[0].data)||void 0===s?void 0:s.streamId,p=t.postId,c=h?u.map((e=>e.streamId===h?Object.assign(Object.assign({},e),{referenceType:"post",referenceId:p,postId:p}):e)):u);const f=(e.comments||[]).filter((e=>"post"===e.referenceType&&e.referenceId===t.postId)),m=0===f.length?(new Date).toISOString():f.map((e=>e.createdAt)).sort().at(-1);return Wl().queueCommentChangeTask(new $l(t.postId,m,null!==(o=t.commentsCount)&&void 0!==o?o:0)),Object.assign(Object.assign({},t),{childPosts:d,feedType:l,localCommentCount:null!==(i=t.localCommentCount)&&void 0!==i?i:t.commentsCount,pinnedProductId:null==t?void 0:t.pinnedProductId})}));return Object.assign(Object.assign({},r),{postChildren:n,videoStreamings:c,posts:l,communities:i,communityUsers:o})},Yl=e=>{var{searchResult:t,polls:n}=e,a=Kn(e,["searchResult","polls"]);const r=Gl(a);return Object.assign(Object.assign({},r),{polls:n})},Xl=async e=>{const t=Ve();let n;t.log("post/getPost",e),ta("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw Oe(null==t?void 0:t.code)&&Fn("post",e),t}const a=Gl(n),r=t.cache&&Date.now();t.cache&&Ln(a,{cachedAt:r});const{posts:s}=a;return{data:s.find((t=>t.postId===e)),cachedAt:r}};Xl.locally=e=>{const t=Ve();if(t.log("post/getPost.locally",e),!t.cache)return;const n=Ze(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Zl=async e=>{const t=Ve();let n;t.log("comment/getComment",e),ta("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw Oe(null==t?void 0:t.code)&&Fn("comment",e),t}const a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a});const{comments:r}=n;return{data:dl.comment(r.find((t=>t.commentId===e))),cachedAt:a}};Zl.locally=e=>{const t=Ve();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=Ze(["comment","get",e]);return n?{data:dl.comment(n.data),cachedAt:n.cachedAt}:void 0};const ed=(e,t)=>{var n,a;let r,s;if("post"===t)s="post",r=e.posts[0].postId;else if("comment"===t)s="comment",r=e.comments[0].commentId;else{if("story"!==t)throw new Error("Unknown event type");s="story",r=e.stories[0].referenceId}return(null===(a=null===(n=Ze([s,"get",r]))||void 0===n?void 0:n.data)||void 0===a?void 0:a.myReactions)||[]},td=(e,t,n)=>{const[a]=e[t];return Object.assign(Object.assign({},e),{[t]:[Object.assign(Object.assign({},a),{myReactions:n})]})},nd=(e,t,n,a=[])=>{const r=e.split(".")[1];let s=a;if(Ve().userId===t)if(["addReaction","reactionAdded"].includes(r))s.includes(n)||s.push(n);else{if(!["removeReaction","reactionRemoved"].includes(r))throw new Error(`Unknown event type: ${r}`);s=s.filter((e=>e!==n))}return s},ad=(e,t)=>{const n=e.split(".")[0],a=ed(t,n),r=nd(e,t.reactor.userId,t.reactor.reactionName,a);return td(t,`${n}s`,r)},rd=(e,t)=>{var n,a;const r=e.split(".")[0];let s=ed(t,r);(null==t?void 0:t.reactions)&&t.reactions.length>0&&(s=nd(e,null===(n=t.reactions[0])||void 0===n?void 0:n.userId,null===(a=t.reactions[0])||void 0===a?void 0:a.reactionName,s));const o=td(t,"stories",s);if(!(null==t?void 0:t.communities)||!(null==t?void 0:t.communityUsers))return o;const i=hc(t.communities,t.communityUsers);return Object.assign(Object.assign({},o),{communities:i})},sd=async(e,t,n)=>{var a,r,s;const o=Ve();if(o.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Fe("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:i}=await o.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0});if(o.cache){const c=Ze([e,"get",t]);if(!c||(null===(a=c.data.myReactions)||void 0===a?void 0:a.includes(n)))return!0;const l=Object.assign(Object.assign({},c.data),{reactionsCount:c.data.reactionsCount+1,myReactions:[...null!==(r=c.data.myReactions)&&void 0!==r?r:[],n],reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:(null!==(s=c.data.reactions[n])&&void 0!==s?s:0)+1}),updatedAt:(new Date).toISOString()});if("comment"===e)return jt("local.comment.addReaction",{comment:l,reactor:{userId:o.userId,reactionName:n,reactionId:i.addedId}}),!0;if("post"===e)return jt("local.post.addReaction",{post:l,reactor:{userId:o.userId,reactionName:n,reactionId:i.addedId}}),!0;if("story"===e)return jt("local.story.reactionAdded",{story:l,reactor:{userId:o.userId,reactionName:n,reactionId:i.addedId}}),!0}return!0};sd.optimistically=(e,t,n)=>{var a,r,s,o,i;const c=Ve();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const l=Ze([e,"get",t]);if(!(null==l?void 0:l.data)||(null===(a=l.data.myReactions)||void 0===a?void 0:a.includes(n)))return;const d=Object.assign(Object.assign({},l.data),{reactionsCount:l.data.reactionsCount+1,myReactions:[...null!==(r=l.data.myReactions)&&void 0!==r?r:[],n],reactions:Object.assign(Object.assign({},l.data.reactions),{[n]:(null!==(s=l.data.reactions[n])&&void 0!==s?s:0)+1})});return nt([e,"get",t],d,{cachedAt:me}),Nc(e,d),null!==(i=null===(o=null==d?void 0:d.myReactions)||void 0===o?void 0:o.includes(n))&&void 0!==i&&i};const od=async(e,t,n)=>{var a,r;const s=Ve();if(s.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Fe("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:o}=await s.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0}});if(s.cache){const i=Ze([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!==(a=i.data.myReactions)&&void 0!==a?a:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},i.data.reactions),{[n]:Math.max(0,(null!==(r=i.data.reactions[n])&&void 0!==r?r:0)-1)}),updatedAt:(new Date).toISOString()});if("comment"===e)return jt("local.comment.removeReaction",{comment:c,reactor:{reactionId:o.removedId,reactionName:n,userId:s.userId}}),!0;if("post"===e)return jt("local.post.removeReaction",{post:c,reactor:{reactionId:o.removedId,reactionName:n,userId:s.userId}}),!0;if("story"===e)return jt("local.story.reactionRemoved",{story:c,reactor:{userId:s.userId,reactionName:n,reactionId:o.removedId}}),!0}return!0};od.optimistically=(e,t,n)=>{var a,r,s,o;const i=Ve();if(i.log("reaction/removeReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!i.cache)return;const c=Ze([e,"get",t]);if(!(null==c?void 0:c.data)||!(null===(a=c.data.myReactions)||void 0===a?void 0:a.includes(n)))return;const l=Object.assign(Object.assign({},c.data),{reactionsCount:Math.max(0,c.data.reactionsCount-1),myReactions:(null!==(r=c.data.myReactions)&&void 0!==r?r:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:Math.max(0,(null!==(s=c.data.reactions[n])&&void 0!==s?s:0)-1)})});return nt([e,"get",t],l,{cachedAt:me}),Nc(e,l),!(null===(o=null==l?void 0:l.myReactions)||void 0===o?void 0:o.includes(n))};const id=e=>{var t;const n=e.posts[0];if(n.parentId){const e=null===(t=Ze(["post","get",n.parentPostId]))||void 0===t?void 0:t.data;if(!e)return;et(["post","get",e.postId],Object.assign(Object.assign({},e),{children:e.children.filter((e=>e!==n.postId))}))}else n.children.forEach((e=>tt(["post","get",e],{isDeleted:!0})))},cd=(e,t)=>{const n=Ve();return Mt(n,e,e,(a=>{var r;if(n.cache){const s=Gl(a),{communities:o}=s;if(Ln(s,void 0,!1),(null==o?void 0:o[0])&&!["post.updated"].includes(e)&&jt("community.updated",{communities:o,categories:[],communityUsers:s.communityUsers,feeds:[],files:[],users:[]}),"post.deleted"===e){const{postId:e,postedUserId:r}=a.posts[0];id(a);try{ta("post",e)}catch(e){return}return r!==n.userId&&at(["post","get",e]),t(a.posts[0])}const i=Ze(["post","get",a.posts[0].postId]);if(["post.created","post.approved","post.declined"].includes(e)){let t=null===(r=Xe(["post","query"]))||void 0===r?void 0:r.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})=>nt(e,t,{cachedAt:-1})))}"post.created"===e&&(e=>{var t;const n=e.posts[0];if(!n.parentId)return;const a=null===(t=Ze(["post","get",n.parentPostId]))||void 0===t?void 0:t.data;a&&et(["post","get",a.postId],Object.assign(Object.assign({},a),{children:[...new Set([n.postId,...a.children])]}))})(a),t(i.data)}else t(a.posts[0])}))},ld=(e,t)=>{const n=Ve();return Mt(n,e,e,(a=>{if(n.cache){const{communities:n}=a;(null==n?void 0:n[0])&&!["local.post.updated"].includes(e)&&jt("community.updated",{communities:n,categories:[],communityUsers:a.communityUsers,feeds:[],files:[],users:[]});const r=Ze(["post","get",a.posts[0].postId]);"local.post.deleted"===e&&id(a),t(r.data)}else t(a.posts[0])}))},dd=e=>cd("post.created",e),ud=e=>cd("post.updated",e),hd=e=>cd("post.deleted",e),pd=e=>cd("post.approved",e),fd=e=>cd("post.declined",e),md=e=>cd("post.flagged",e),gd=e=>cd("post.unflagged",e),yd=e=>{const t=Ve();return Mt(t,"post.addReaction","post.addReaction",(n=>{if(t.cache){const t=Kn(ad("post.addReaction",n),["reactor"]);Ln(t);const a=Ze(["post","get",n.posts[0].postId]);e(a.data)}else e(n.posts[0])}))},vd=e=>{const t=Ve();return Mt(t,"post.removeReaction","post.removeReaction",(n=>{if(t.cache){const t=Kn(ad("post.removeReaction",n),["reactor"]);Ln(t);const a=Ze(["post","get",n.posts[0].postId]);e(a.data)}else e(n.posts[0])}))},bd=(e,t)=>{const n=Ve();return Mt(n,e,e,(a=>{var r;if(n.cache){const n=["comment.flagged","comment.unflagged"].includes(e)?(e=>{const t=ed(e,"comment");return td(e,"comments",t)})(a):a;Ln(n,void 0,!1);const{comments:s}=n;if(s.length>0){const n=Ze(["comment","get",s[0].commentId]);if(["comment.created"].includes(e)&&s[0].parentId){const e=Ze(["comment","get",s[0].parentId]);(null==e?void 0:e.data)&&(e.data.children.includes(s[0].commentId)||et(["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(s[0].parentId){const e=Ze(["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))])]});et(["comment","get",s[0].parentId],t)}}const e=null===(r=Xe(["comment","query"]))||void 0===r?void 0:r.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})=>nt(e,t,{cachedAt:-1})))}t(dl.comment(n.data))}}else t(dl.comment(a.comments[0]))}))},wd=(e,t)=>{const n=Ve();return Mt(n,e,e,(a=>{var r,s,o,i,c;if(n.cache){const n=a;Ln(n);const{comments:l}=n;if(l.length>0){const n=Ze(["comment","get",l[0].commentId]);if(["local.comment.created"].includes(e)){if(l[0].parentId){const e=Ze(["comment","get",l[0].parentId]);if((null==e?void 0:e.data)&&!e.data.children.includes(l[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,l[0].commentId])]});et(["comment","get",l[0].parentId],t),setTimeout((()=>{jt("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}else{const e=["post","get",l[0].referenceId],t=null===(r=Ze(e))||void 0===r?void 0:r.data;if(t){const n=Object.assign(Object.assign({},t),{comments:[...t.comments,null===(s=l[0])||void 0===s?void 0:s.commentId]});et(e,n)}}const e=null===(o=Xe(["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})=>nt(e,t,{cachedAt:-1})))}if(["local.comment.deleted"].includes(e)){if(l[0].parentId){const e=Ze(["comment","get",l[0].parentId]);if((null==e?void 0:e.data)&&e.data.children.includes(l[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber-1,children:[...new Set([...e.data.children.filter((e=>e!==l[0].commentId))])]});et(["comment","get",l[0].parentId],t),setTimeout((()=>{jt("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}else{const e=["post","get",l[0].referenceId],t=null===(i=Ze(e))||void 0===i?void 0:i.data;if(t){const n=Object.assign(Object.assign({},t),{comments:null==t?void 0:t.comments.filter((e=>{var t;return e!==(null===(t=l[0])||void 0===t?void 0:t.commentId)}))});et(e,n)}}const e=null===(c=Xe(["comment","query"]))||void 0===c?void 0:c.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})=>nt(e,t,{cachedAt:-1})))}t(dl.comment(n.data))}}else t(dl.comment(a.comments[0]))}))},Id=e=>bd("comment.created",e),Cd=e=>bd("comment.updated",e),Sd=e=>bd("comment.deleted",e),Od=e=>bd("comment.flagged",e),Td=e=>bd("comment.unflagged",e),kd=e=>{const t=Ve();return Mt(t,"comment.addReaction","comment.addReaction",(n=>{if(t.cache){const t=Kn(ad("comment.addReaction",n),["reactor"]);Ln(t);const a=Ze(["comment","get",n.comments[0].commentId]);e(dl.comment(a.data))}else e(dl.comment(n.comments[0]))}))},Ad=e=>{const t=Ve();return Mt(t,"comment.removeReaction","comment.removeReaction",(n=>{if(t.cache){const t=Kn(ad("comment.removeReaction",n),["reactor"]);Ln(t);const a=Ze(["comment","get",n.comments[0].commentId]);e(dl.comment(a.data))}else e(dl.comment(n.comments[0]))}))},_d=(e,t,n)=>{const a=Ve(),r=(a,r,s)=>{a===e&&r===t&&n(s)};if("message"===e){return Mt(a,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await pa(e);t.reactions[0]&&(Ln(t),Ln({reactors:t.reactions}),r("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return Mt(a,"post.addReaction","post.addReaction",(e=>{const{reactor:t}=e,n=Kn(e,["reactor"]);Ln(n),Ln({reactions:[t]}),r("post",e.posts[0].postId,t)}))}if("story"===e){return Mt(a,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=Kn(e,["reactions"]);Ln(n),Ln({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&r("story",e.stories[0].storyId,e.reactions[0])}))}return Mt(a,"comment.addReaction","comment.addReaction",(e=>{const{reactor:t}=e,n=Kn(e,["reactor"]);Ln(n),Ln({reactions:[t]}),r("comment",e.comments[0].commentId,t)}))},Ed=(e,t,n)=>{const a=Ve(),r=(a,r,s)=>{a===e&&r===t&&n(s)};if("message"===e){return Mt(a,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await pa(e);t.reactions[0]&&(Ln(t),r("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return Mt(a,"post.removeReaction","post.removeReaction",(e=>{const{reactor:t}=e,n=Kn(e,["reactor"]);Ln(n),Ln({reactions:[t]}),r("post",e.posts[0].postId,t)}))}if("story"===e){return Mt(a,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=Kn(e,["reactions"]);Ln(n),Ln({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&r("story",e.stories[0].storyId,e.reactions[0])}))}return Mt(a,"comment.removeReaction","comment.removeReaction",(e=>{const{reactor:t}=e,n=Kn(e,["reactor"]);Ln(n),Ln({reactions:[t]}),r("comment",e.comments[0].commentId,t)}))};class Rd extends wi{async getRequest(e,t){const{limit:n=de,referenceType:a}=e,r=Kn(e,["limit","referenceType"]),s=t?{token:t}:{limit:n};Ve().log("reaction/queryReactions",e);if(!["post","comment","story","message"].includes(a))throw new Fe("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:o}=await this.http.get("/api/v3/reactions",{params:Object.assign(Object.assign({},r),{referenceType:a,referenceVersion:"message"===a?5:void 0,options:s})});return o}}class Pd extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){var t;const n=await this.preparePayload(e),a=Ve(),r=a.cache&&Date.now();if(a.cache){const{reactions:e}=n,a=Kn(n,["reactions"]);Ln(Object.assign(Object.assign({},a),{reactions:e,reactors:null===(t=e[0])||void 0===t?void 0:t.reactors}),{cachedAt:r})}}appendToQueryStream(e,t,n=!1){var a,r,s,o;const i=null!==(r=null===(a=e.reactions[0])||void 0===a?void 0:a.reactors)&&void 0!==r?r:[];if(n)et(this.cacheKey,{data:i.map(We("reactor"))});else{const e=null===(s=Ze(this.cacheKey))||void 0===s?void 0:s.data,t=null!==(o=null==e?void 0:e.data)&&void 0!==o?o:[];et(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...i.map(We("reactor"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;a&&("onAdded"===e?a.data=[...new Set([t.reactionId,...a.data])]:"onRemoved"===e&&(a.data=a.data.filter((e=>e!==t.reactionId))),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Md extends ki{constructor(e,t){const n=O.default(e),a=["reaction","collection",n];super(new Rd(e),n,a,t),this.query=e,this.queryStreamController=new Pd(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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=>_d(this.query.referenceType,this.query.referenceId,e),action:"onAdded"},{fn:e=>Ed(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const a=Ve(),r=(a,r,s)=>{a===e&&r===t&&n(s)};if("message"===e)return Mt(a,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await pa(e);t.reactions[0]&&(Ln(t),r("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return Mt(a,"local.post.removeReaction","local.post.removeReaction",(e=>{r("post",e.post.postId,e.reactor)}));if("story"===e)return Mt(a,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=Kn(e,["reactions"]);Ln(n),Ln({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&r("story",e.stories[0].storyId,e.reactions[0])}));return Mt(a,"local.comment.removeReaction","local.comment.removeReaction",(e=>{r("comment",e.comment.commentId,e.reactor)}))})(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const a=Ve(),r=(a,r,s)=>{a===e&&r===t&&n(s)};if("message"===e)return Mt(a,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await pa(e);t.reactions[0]&&(Ln(t),Ln({reactors:t.reactions}),r("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return Mt(a,"local.post.addReaction","local.post.addReaction",(e=>{r("post",e.post.postId,e.reactor)}));if("story"===e)return Mt(a,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=Kn(e,["reactions"]);Ln(n),Ln({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&r("story",e.stories[0].storyId,e.reactions[0])}));return Mt(a,"local.comment.addReaction","local.comment.addReaction",(e=>{r("comment",e.comment.commentId,e.reactor)}))})(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=null!==(r=s.data.map((e=>Ze(["reactor","get",e]))).filter(Boolean).map((({data:e})=>dl.reactor(e))))&&void 0!==r?r:[];(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var jd=Object.freeze({__proto__:null,addReaction:sd,removeReaction:od,onReactionAdded:(e,t,n)=>{const a=a=>{We(e)(a)===t&&n(a)};if("message"===e){const e=Ve(),t=async e=>{var t;const n=await pa(e),r=Ze(["message","get",n.messages[0].messageId]),s=(null===(t=null==r?void 0:r.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Ln(n),s&&a(n.messages[0])};return Mt(e,"reaction/onReactionAdded","message.updated",t)}return"post"===e?yd(a):kd(a)},onReactionRemoved:(e,t,n)=>{const a=a=>{We(e)(a)===t&&n(a)};if("message"===e){const e=Ve(),t=async e=>{var t;const n=await pa(e),r=Ze(["message","get",n.messages[0].messageId]),s=(null===(t=null==r?void 0:r.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Ln(n),s&&a(n.messages[0])};return Mt(e,"reaction/onReactionRemoved","message.updated",t)}return"post"===e?vd(a):Ad(a)},onReactorAdded:_d,onReactorRemoved:Ed,getReactions:(e,t,n)=>{const{log:a,cache:r}=Ve(),s=Date.now();a(`getReactions(tmpid: ${s}) > listen`);const o=new Md(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{at(c)})),()=>{a(`getReactions(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}}});function Ud(e){const{comments:t}=e;return Object.assign(Object.assign({},e),{comments:t.map((e=>e.hasOwnProperty("myReactions")?e:Object.assign({myReactions:[]},e)))})}const Dd=async()=>{var e;const t=Ve();t.log("channel/getArchivedChannelIds");const{data:n}=await t.http.get("/api/v1/archives/channels"),a=null!==(e=n.archives)&&void 0!==e?e:[];return t.cache&&(at(["archivedChannel","get"]),a.forEach((e=>{e.channelId&&et(["archivedChannel","get",e.channelId],e)}))),a.map((e=>e.channelId)).filter((e=>!!e))},xd=e=>{const t=Ve(),n=[Mt(t,"onMessageUpdated","message.updated",(async t=>{const n=await pa(t);Ln(n),e(n.messages[0])})),Mt(t,"onMessageUpdated","local.message.updated",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},qd=e=>{const t=Ve(),n=[Mt(t,"message/onMessageDeleted","message.deleted",(async t=>{const n=await pa(t);Ln(n),e(n.messages[0])})),Mt(t,"message/onMessageDeleted","local.message.deleted",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},Nd=e=>{const t=Ve(),n=[Mt(t,"onSubChannelUpdated","message-feed.updated",(async t=>{const n=await ba(t);Ln(n),e(n.messageFeeds[0])})),Mt(t,"onSubChannelUpdated","local.message-feed.updated",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}};function Bd(e,t){et(["channel","get",e.channelId],Zn(e,t))}const Ld=e=>{const t=Ve();return Mt(t,"channelMarker/onChannelMarkerUpdated","local.channelMarker.updated",(t=>{e(t.userEntityMarkers[0])}))},Fd=async(e,t=!1)=>{const n=Ve(),a=await wa(e);await n.http.delete(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{params:{permanent:t}});const r=Object.assign(Object.assign({},a.data),{isDeleted:!0,updatedAt:Ye(a.data.updatedAt)});return t?setTimeout((()=>{Fn("subChannel",e)}),0):nt(["subChannel","get",e],r),jt("local.message-feed.deleted",{messageFeeds:[r]}),r},Kd=e=>Mt(Ve(),"onSubChannelFetched","local.message-feed.fetched",(t=>e(t.messageFeeds[0]))),$d=()=>`LOCAL_${Mn()}`;let Qd;const zd=async(e,t)=>{const n=Ve();n.log("message/updateMessage",t),console.warn("MessageRepository.updateMessage will be replaced with MessageRepository.editMessage");const{data:a}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,fa(t)),r=await pa(a),s=n.cache&&Date.now();n.cache&&Ln(r,{cachedAt:s});const{messages:o}=r;return jt("local.message.updated",{messages:o}),{data:dl.message(o.find((t=>t.messageId===e))),cachedAt:s}};zd.optimistically=(e,t)=>{const n=Ve();if(n.log("message/updateMessage.optimistically",t),!n.cache)return;const a=Ze(["message","get",e]);if(!a)return;const r=Object.assign(Object.assign(Object.assign({},a.data),t),{updatedAt:(new Date).toISOString()});return nt(["message","get",e],r,{cachedAt:-1}),jt("local.message.updated",{messages:[r]}),{data:dl.message(r),cachedAt:-1}};const Vd=async(e,t)=>{const n=Ve();n.log("message/editMessage",t);const{data:a}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,fa(t)),r=await pa(a),s=n.cache&&Date.now();n.cache&&Ln(r,{cachedAt:s});const{messages:o}=r;return jt("local.message.updated",{messages:o}),{data:dl.message(o.find((t=>t.messageId===e))),cachedAt:s}};Vd.optimistically=(e,t)=>{const n=Ve();if(n.log("message/editMessage.optimistically",t),!n.cache)return;const a=Ze(["message","get",e]);if(!a)return;const r=Object.assign(Object.assign(Object.assign({},a.data),t),{updatedAt:(new Date).toISOString()});return nt(["message","get",e],r,{cachedAt:-1}),jt("local.message.updated",{messages:[r]}),{data:dl.message(r),cachedAt:-1}};const Hd=async e=>{var t;const n=Ve();if(n.log("message/deleteMessage",e),e.includes("LOCAL_")){const n=null===(t=Ze(["message","get",e]))||void 0===t?void 0:t.data;if(!n)throw Error("messageId not found");const a=Object.assign(Object.assign({},n),{isDeleted:!0});return jt("local.message.deleted",{messages:[a]}),dl.message(a)}const{data:a}=await n.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`),r=await pa(a);return jt("local.message.deleted",{messages:[r.messages[0]]}),dl.message(r.messages[0])};Hd.optimistically=e=>{Ve().log("message/deleteMessage.optimistically",e);const t=Ze(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return nt(["message","get",e],n,{cachedAt:-1}),jt("local.message.deleted",{messages:[n]}),{data:dl.message(n),cachedAt:-1}};const Jd=async e=>{const t=Ve();t.log("message/softDeleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const n=await Kl(e);return jt("local.message.deleted",{messages:[n.data]}),dl.message(n.data)};Jd.optimistically=e=>{Ve().log("message/softDeleteMessage.optimistically",e);const t=Ze(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return nt(["message","get",e],n,{cachedAt:-1}),jt("local.message.deleted",{messages:[n]}),{data:dl.message(n),cachedAt:-1}};const Wd=async e=>{const t=Ve();t.log("user/getReadUsers",e);const{page:n,messageId:a}=e,r=Kn(e,["page","messageId"]),{data:s}=await t.http.get(`/api/v1/markers/messages/${a}/read-users`,{params:Object.assign(Object.assign({},r),{options:{token:Ee(n,"afterbeforeraw")}})}),{paging:o,publicUserIds:i,userFeedMarkers:c}=s,l=Kn(s,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Ln(Object.assign(Object.assign({},l),{userFeedMarkers:Hn(c)}),{cachedAt:d});const e=["read-user","query",Object.assign(Object.assign({messageId:a},r),{options:Object.assign({},n)})];et(e,{users:i,paging:o})}let u=[];i.length>0&&({data:u}=await ul(i));return{data:u,cachedAt:d,prevPage:Re(o.previous),nextPage:Re(o.next)}};Wd.locally=e=>{var t;const n=Ve();if(n.log("user/getReadUsers.locally",e),!n.cache)return;const{page:a}=e,r=Kn(e,["page"]),s=["read-user","query",Object.assign(Object.assign({},r),{options:Object.assign({},a)})],{data:o,cachedAt:i}=null!==(t=Ze(s))&&void 0!==t?t:{},c=null==o?void 0:o.users.map((e=>{var t;return null===(t=Ze(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:i,prevPage:Re(null==o?void 0:o.paging.previous),nextPage:Re(null==o?void 0:o.paging.next)}};const Gd=async e=>{const t=Ve();t.log("user/getDeliveredUsers",e);const{page:n,messageId:a}=e,r=Kn(e,["page","messageId"]),{data:s}=await t.http.get(`/api/v1/markers/messages/${a}/delivered-users`,{params:Object.assign(Object.assign({},r),{options:{token:Ee(n,"afterbeforeraw")}})}),{paging:o,publicUserIds:i,userFeedMarkers:c}=s,l=Kn(s,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Ln(Object.assign(Object.assign({},l),{userFeedMarkers:Hn(c)}),{cachedAt:d});const e=["delivered-user","query",Object.assign(Object.assign({messageId:a},r),{options:Object.assign({},n)})];et(e,{users:i,paging:o})}let u=[];i.length>0&&({data:u}=await ul(i));return{data:u,cachedAt:d,prevPage:Re(o.previous),nextPage:Re(o.next)}};Gd.locally=e=>{var t;const n=Ve();if(n.log("user/getDeliveredUsers.locally",e),!n.cache)return;const{page:a}=e,r=Kn(e,["page"]),s=["delivered-user","query",Object.assign(Object.assign({},r),{options:Object.assign({},a)})],{data:o,cachedAt:i}=null!==(t=Ze(s))&&void 0!==t?t:{},c=null==o?void 0:o.users.map((e=>{var t;return null===(t=Ze(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:i,prevPage:Re(null==o?void 0:o.paging.previous),nextPage:Re(null==o?void 0:o.paging.next)}};const Yd=e=>{const t=Ve();return Mt(t,"onMessageFlagged","message.flagged",(async t=>{const n=await pa(t);Ln(n),e(n.messages[0])}))},Xd=e=>{const t=Ve();return Mt(t,"onMessageUnflagged","message.unflagged",(async t=>{const n=await pa(t);Ln(n),e(n.messages[0])}))},Zd=e=>{const t=Ve();return Mt(t,"onMessageFlagCleared","message.flagCleared",(async t=>{const n=await pa(t);Ln(n),e(n.messages[0])}))},eu=e=>{const t=Ve();return Mt(t,"onMessageReactionAdded","message.reactionAdded",(async t=>{const n=await pa(t,"message.reactionAdded");Ln(n),e(n.messages[0])}))},tu=e=>{const t=Ve();return Mt(t,"onMessageReactionRemoved","message.reactionRemoved",(async t=>{const n=await pa(t,"message.reactionRemoved");Ln(n),e(n.messages[0])}))},nu=e=>{const t=Ve();return Mt(t,"message/onMessageFetched","local.message.fetched",(t=>{Ln(t),e(t.messages[0])}))},au=e=>{const t=Ve();return Mt(t,"stream/onStreamViewerDidBan","video-streaming.viewerDidBan",(t=>{var n;const{list:a}=t;a.forEach((e=>{var t;tt(["stream","get",e.streamId],{watcherUrl:null});const n=null===(t=Xe(["message","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.creatorId===e.userId));null==n||n.forEach((e=>{tt(e.key,{isDeleted:!0})}))}));const r=null===(n=Ze(["stream","get",a[0].streamId]))||void 0===n?void 0:n.data;r&&e(r)}))};class ru extends Ci{constructor(e,t,n,a,r){super(e,t),this.notifyChange=n,this.preparePayload=a,this.paginationController=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.messages.map(We("message")),query:this.query});else{const n=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,s=null!==(r=null==n?void 0:n.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},n),{data:"next"===t?[...new Set([...s,...e.messages.map(We("message"))])]:[...new Set([...e.messages.map(We("message")),...s])]}))}}reactor(e){return t=>{var n,a,r,s;if("onCreate"===e){const e=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data,{referenceId:s}=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===(a=this.query.excludingTags)||void 0===a?void 0:a.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===(r=this.query.includingTags)||void 0===r?void 0:r.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!=s?s:t.messageId,...e.data])]),"segmentAsc"!==this.query.sortBy||this.paginationController.getNextToken()||(e.data=[...new Set([...e.data,null!=s?s:t.messageId])]),et(this.cacheKey,e)}if("onDelete"===e&&"error"===t.syncState){const e=null===(s=Ze(this.cacheKey))||void 0===s?void 0:s.data;if(!e)return;if(e.data.includes(t.messageId)){const n=e.data.filter((e=>e!==t.messageId));et(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 su extends wi{async getRequest(e,t){const n=ma(e),{data:a}=await this.http.get("/api/v5/messages",{params:Object.assign(Object.assign({},n),{options:t?{token:t}:Object.assign({},n.options)})});return a}}class ou extends ki{constructor(e,t){const n=O.default(e),a=["message","collection",n];super(new su(e),n,a,t),this.query=e,this.queryStreamController=new ru(this.query,this.cacheKey,this.notifyChange.bind(this),pa,this.paginationController),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:bo,action:"onCreate"},{fn:wo,action:"onCreate"},{fn:qd,action:"onDelete"},{fn:xd,action:"onUpdate"},{fn:Yd,action:"onFlagged"},{fn:Xd,action:"onUnflagged"},{fn:Zd,action:"onFlagCleared"},{fn:eu,action:"onReactionAdded"},{fn:tu,action:"onReactionRemoved"},{fn:Tl(Xo,"contentId","message"),action:"onUpdate"},{fn:Tl(Zo,"contentId","message"),action:"onUpdate"},{fn:Tl(au,"channelId","message"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>sa(e))).filter(Boolean).map((e=>dl.message(e))))&&void 0!==r?r:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),onPrevPage:()=>this.loadPage({direction:"prev"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),hasPrevPage:!!this.paginationController.getPrevToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.includeDeleted||(t=rt(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=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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)}}class iu extends wi{async getRequest(e,t){const{query:n,exactMatch:a,channelId:r,messageFeedId:s,userIds:o,tags:i,types:c,sortBy:l,orderBy:d,limit:u=de}=e,h=t?{token:t}:{limit:u,sortBy:l,orderBy:d},{data:p}=await this.http.get("/api/v2/search/messages",{params:{query:n,exactMatch:a,channelId:r,messageFeedId:s,userIds:o,tags:i,types:c,options:h}});return p}}class cu extends Ci{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){var t;const n=await pa(e),a=Ve(),r=a.cache&&Date.now();a.cache&&(Ln(n,{cachedAt:r}),(null===(t=e.channels)||void 0===t?void 0:t.length)&&e.channels.forEach((e=>{et(["channel","get",e.channelId],e,{cachedAt:r})})))}appendToQueryStream(e,t,n=!1){var a,r;if(n)return void et(this.cacheKey,{data:e.messages.map(We("message"))});const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,o=null!==(r=null==s?void 0:s.data)&&void 0!==r?r:[],i=e.messages.map(We("message"));et(this.cacheKey,Object.assign(Object.assign({},s),{data:"prev"===t?[...new Set([...i,...o])]:[...new Set([...o,...i])]}))}}class lu extends ki{constructor(e,t){const n=O.default(e),a=["message","search",n];super(new iu(e),n,a,t),this.queryStreamController=new cu(e,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return[]}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=null!==(r=s.data.map((e=>sa(e))).filter(Ai).map((e=>dl.message(e))))&&void 0!==r?r:[];(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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)}}var du=Object.freeze({__proto__:null,createMessage:async e=>{const t=Ve();t.log("message/createMessage",e);const n=(e=>{var t,n;const a=Ve();if(!a.cache)return;Qd=e.referenceId||$d();const r=Object.assign({messageId:Qd,uniqueId:Qd},e);a.log("message/createMessage.optimistically",r);const s=Ze(["subChannel","get",e.subChannelId]);if(s&&(nt(["subChannel","get",e.subChannelId],Object.assign(Object.assign({},s.data),{messageCount:s.data.messageCount+1})),s.data.channelId===s.data.subChannelId)){const e=Ze(["channel","get",s.data.channelId]);(null==e?void 0:e.data)&&nt(["channel","get",s.data.channelId],Object.assign(Object.assign({},e.data),{messageCount:(null!==(t=e.data.messageCount)&&void 0!==t?t:0)+1}))}const o=(new Date).toISOString(),i=Object.assign({creatorId:a.userId,creatorPrivateId:kt()._id,channelSegment:(null!==(n=null==s?void 0:s.data.messageCount)&&void 0!==n?n:0)+1,childrenNumber:0,createdAt:o,updatedAt:o,syncState:"syncing",isDeleted:!1},r);return et(["message","get",i.messageId],i,{cachedAt:-5}),jt("local.message.created",{messages:[i]}),i})(e),a=e.referenceId||Qd||$d();Qd=void 0;try{const{data:n}=await t.http.post("/api/v5/messages",Object.assign(Object.assign({},fa(e)),{referenceId:a})),r=await pa(n),{messages:s}=r,o=t.cache&&Date.now();return t.cache&&Ln(r,{cachedAt:o}),jt("local.message.created",{messages:[Object.assign(Object.assign({},s[0]),{syncState:"synced"})]}),{data:dl.message(s[0]),cachedAt:o}}catch(e){throw jt("local.message.created",{messages:[Object.assign(Object.assign({},n),{syncState:"error"})]}),e}},updateMessage:zd,editMessage:Vd,deleteMessage:Hd,softDeleteMessage:Jd,markAsDelivered:async(e,t)=>{const n=Ve();n.log("message/markAsDelivered",e,t);const{data:a}=await n.http.put(`/api/v1/markers/message-feeds/${e}/mark-delivering`,{messageId:t}),{userMarkers:r,userEntityMarkers:s,userFeedMarkers:o}=a,i=Kn(a,["userMarkers","userEntityMarkers","userFeedMarkers"]),c=n.cache&&Date.now();return n.cache&&Ln(Object.assign({userMarkers:r,userEntityMarkers:Vn(s),userFeedMarkers:Hn(o)},i),{cachedAt:c}),!0},getReadUsers:Wd,getDeliveredUsers:Gd,flagMessage:async(t,n)=>{const a=Ve();a.log("message/flag",t);const r=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,a])=>t!==e.ContentFlagReasonEnum.Others&&a===n)),s={reason:r?n:e.ContentFlagReasonEnum.Others,detail:r?"":n},{data:o}=await a.http.post(`/api/v5/messages/${encodeURIComponent(t)}/flags`,s);if(a.cache){const e=await pa(o);Ln(e)}return jt("message.flagged",o),!!o},unflagMessage:async e=>{const t=Ve();t.log("message/unflag",e);const{data:n}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await pa(n);Ln(e)}return jt("message.unflagged",n),!!n},isMessageFlaggedByMe:async e=>{const t=Ve();t.log("message/isMessageFlaggedByMe",e);const{data:n}=await t.http.get(`/api/v5/messages/${encodeURIComponent(e)}/flags`);return n.result},onMessageCreatedMqtt:bo,onMessageCreatedLocal:wo,onMessageUpdated:xd,onMessageDeleted:qd,onMessageFlagged:Yd,onMessageUnflagged:Xd,onMessageFlagCleared:Zd,onMessageReactionAdded:eu,onMessageReactionRemoved:tu,onMessageFetched:nu,getMessage:(e,t)=>Ui(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?dl.message(e.data):n}))}),"messageId",Kl,[nu,xd,qd,Yd,Xd,Zd,eu,tu,Tl(Xo,"contentId","message"),Tl(Zo,"contentId","message"),Tl(au,"channelId","message")]),getMessages:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`getMessages(tmpid: ${s}) > listen`);const o=new ou(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{at(c)})),()=>{a(`getMessages(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},searchMessage:(e,t)=>{if(!e.query||0===e.query.trim().length)throw new Error("Query is required for message search");const{log:n,cache:a}=Ve();a||console.log(pe);const r=Date.now();n(`searchMessage(tmpid: ${r}) > listen`);const s=new lu(e,t),o=s.startSubscription(),i=s.getCacheKey();return o.push((()=>{at(i)})),()=>{n(`searchMessage(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},convertFromRaw:ua,prepareMessagePayload:pa,convertParams:fa,convertQueryParams:ma});const uu=e=>{const t=Ve();return Mt(t,"subChannelMarker/onSubChannelUnreadUpdatedLocal","local.subChannelUnread.updated",(t=>{e(t)}))};class hu extends wi{async getRequest(e,t){var n;const{limit:a=de}=e,r=null!==(n=function(e){var{excludeDefaultSubChannel:t}=e,n=Kn(e,["excludeDefaultSubChannel"]);const a=Object.assign({},n);return void 0!==t&&(a.excludeDefaultMessageFeed=t),a}(Kn(e,["limit"])))&&void 0!==n?n:{},{channelId:s,includeDeleted:o}=r,i=Kn(r,["channelId","includeDeleted"]),c=t?{token:t}:{limit:a},{data:l}=await this.http.get(`/api/v5/message-feeds/channel/${s}`,{params:Object.assign(Object.assign({},i),{isDeleted:oa(o),options:c})});return l}}class pu extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.messageFeeds.map((({messageFeedId:e})=>e))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.messageFeeds.map((({messageFeedId:e})=>e))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(!Array.isArray(t)){if(this.query.channelId!==t.channelId)return;"onCreate"===e&&(a.data=[...new Set([t.subChannelId,...a.data])]),et(this.cacheKey,a)}this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class fu extends ki{constructor(e,t){const n=O.default(e),a=["subChannel","collection",n];super(new hu(e),n,a,t),this.query=e,this.queryStreamController=new pu(this.query,this.cacheKey,this.notifyChange.bind(this),ba),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:Kd,action:"onCreate"},{fn:Io,action:"onCreate"},{fn:Co,action:"onDelete"},{fn:e=>Nd((async t=>{if(!this.isRelatedCollection(t.subChannelId))return;const n=Ve();if("no-message-preview"!==await n.getMessagePreviewSetting(!1)){const e=Gn(t.subChannelId);(null==e?void 0:e.subChannelId)===t.subChannelId&&Wn(t.updatedAt)>Wn(e.subChannelUpdatedAt)&&et(["messagePreviewSubChannel","get",t.subChannelId],Object.assign(Object.assign({},e),{subChannelName:t.displayName,subChannelUpdatedAt:t.updatedAt}))}e(t)})),action:"onUpdate"},{fn:Tl((e=>bo((async t=>{this.isRelatedCollection(t.subChannelId)&&(await Ca(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Tl((e=>wo((async t=>{this.isRelatedCollection(t.subChannelId)&&(await Ca(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:e=>Go((t=>{var n;const a=null!==(n=t.map((({feedId:e})=>Ze(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];0!==a.length&&e(a)})),action:"onUpdate"},{fn:Tl(Wo,"feedId","subChannel"),action:"onUpdate"},{fn:Tl((e=>xd((async t=>{var n;const a=Ve();if("no-message-preview"===await a.getMessagePreviewSetting(!1))return;const r=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;r&&r.data.includes(t.subChannelId)&&(Sa(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Tl((e=>qd((async t=>{const n=Ve(),a=await n.getMessagePreviewSetting(!1);"no-message-preview"!==a&&this.isRelatedCollection(t.subChannelId)&&("message-preview-not-include-deleted"===a?await wa(t.subChannelId):await Sa(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Tl(uu,"subChannelId","subChannel"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(Yn))&&void 0!==r?r:[]);(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;return this.query.includeDeleted||(t=rt(e,"isDeleted",!1)),t.sort(Ct),t}isRelatedCollection(e){var t;const n=null===(t=Ze(this.cacheKey))||void 0===t?void 0:t.data;return n&&n.data.includes(e)}}const mu={},gu=async e=>{const t=await(async e=>{const t=wa.locally(e);if(t)return t.data.channelId;const{data:n}=await wa(e);return n.channelId})(e),n=Qt({channelId:t,subChannelId:e});mu[e]=Gt(n)};var yu=Object.freeze({__proto__:null,getSubChannelByIds:Br,createSubChannel:async e=>{const t=Ve();t.log("user/createSubChannel",e);const n=await t.http.post("/api/v5/message-feeds",{channelId:e.channelId,name:e.displayName}),a=await ba(n.data),r=t.cache&&Date.now();return t.cache&&Ln(a,{cachedAt:r}),jt("message-feed.created",n.data),{data:a.messageFeeds[0],cachedAt:r}},updateSubChannel:async(e,t)=>{const n=Ve();n.log("channel/updateSubChannel",e,t);const a=await n.http.put(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{name:t.displayName}),r=await ba(a.data),s=n.cache&&Date.now();return n.cache&&Ln(r,{cachedAt:s}),jt("message-feed.updated",a.data),{data:r.messageFeeds[0],cachedAt:s}},deleteSubChannel:Fd,hardDeleteSubChannel:async e=>{Ve().log("channel/hardDeleteSubChannel",e);return await Fd(e,!0)},softDeleteSubChannel:async e=>{Ve().log("channel/softDeleteSubChannel",e);return await Fd(e,!1)},onSubChannelCreated:Io,onSubChannelUpdated:Nd,onSubChannelDeleted:Co,getSubChannel:(e,t)=>{const n=Ve();let a;return Ui(e,(e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:Yn(e.data)}),r=Kn(n,["origin"]);return La(a,r)?void 0:(a=r,t(n))}),"subChannelId",wa,[Kd,t=>Nd((async a=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(ka(a),a.subChannelId===e&&t(a))})),Co,Tl(Wo,"feedId","subChannel"),t=>Go((n=>{var a;if(!n.find((({feedId:t})=>t===e)))return;const r=null===(a=Ze(["subChannel","get",e]))||void 0===a?void 0:a.data;r&&t(r)})),Tl((t=>bo((async n=>{n.subChannelId===e&&(await Ca(n),t(n))}))),"subChannelId","subChannel"),Tl((t=>wo((async n=>{n.subChannelId===e&&(await Ca(n),t(n))}))),"subChannelId","subChannel"),Tl((t=>xd((async a=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&a.subChannelId===e&&(Sa(a),t(a))}))),"subChannelId","subChannel"),Tl((t=>qd((async a=>{const r=await n.getMessagePreviewSetting(!1);"no-message-preview"!==r&&a.subChannelId===e&&("message-preview-include-deleted"===r&&await Sa(a),"message-preview-not-include-deleted"===r&&await wa(a.subChannelId),t(a))}))),"subChannelId","subChannel"),Tl(uu,"subChannelId","subChannel")],{forceDispatch:!0})},getSubChannels:(e,t,n)=>{const{log:a,cache:r}=Ve(),s=Date.now();a(`getSubChannels(tmpid: ${s}) > listen`),r||console.log(pe);const o=new fu(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{at(c)})),()=>{a(`getSubChannels(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},markReadEngineOnLoginHandler:Nr,startMessageReceiptSync:async e=>(await gu(e),!0),stopMessageReceiptSync:e=>(mu[e]&&mu[e](),!0)});const vu=e=>{const t=Ve();return Mt(t,"channelMarker/onChannelUnreadInfoUpdatedLocal","local.channelUnreadInfo.updated",(t=>{e(t)}))},bu=e=>{const t=Ve();return Mt(t,"channel/onChannelUnreadUpdatedLocal","local.channelUnread.updated",(t=>{e(t)}))};class wu extends wi{async getRequest(e,t){const{limit:n=de,displayName:a,membership:r}=e,s=Kn(e,["limit","displayName","membership"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/channels",{params:Object.assign(Object.assign({},s),{keyword:a,filter:r,options:o})});return i}}class Iu extends Ti{async getRequest(e){const{data:t}=await this.http.get("/api/v3/channels/list",{params:Object.assign({},e)});return t}}class Cu extends Ci{constructor(e,t,n,a,r){super(e,t),this.notifyChange=n,this.preparePayload=a,this.paginationController=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.channels.map(We("channel"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channels.map(We("channel"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(this.paginationController instanceof Iu)return this.notifyChange({origin:"event",loading:!1});if(["onCreate","onJoin","onResolveChannel","onUnarchived"].includes(e)&&(Array.isArray(t)?a.data=[...new Set([...t.map(We("channel")),...a.data])]:a.data=[...new Set([t.channelInternalId,...a.data])]),"onArchived"===e){const e=Array.isArray(t)?t.map(We("channel")):[We("channel")(t)];a.data=a.data.filter((t=>!e.includes(t)))}et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Su=e=>{const t=Ve();if(t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()){Ps().resolve(e.channelId,"userMessageFeedMarker")}},Ou=e=>{const t=Ve();return Mt(t,"onChannelResolved","local.channel.resolved",(async t=>{e(t)}))},Tu=e=>{const t=Ve();return Mt(t,"userMessageFeedMarker/onUserMessageFeedMarkerResolved","local.userMessageFeedMarkers.resolved",(t=>{e(t)}))};class ku extends ki{constructor(e,t){const n=O.default(e),a=["channel","collection",n],r=ku.getPaginationController(e);super(r,n,a,t),this.query=e,this.queryStreamController=new Cu(this.query,this.cacheKey,this.notifyChange.bind(this),(async e=>{try{const t=Ve();t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await ja(e)}catch(e){console.error("Error while preparing unread count info",e)}return Pa(e)}),r),this.paginationController=r,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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 a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;let o=null!==(r=s.data.map((e=>Ze(["channel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(Pr))&&void 0!==r?r:[];this.paginationController instanceof wu&&(o=this.applyFilter(o)),(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:this.paginationController instanceof wu?()=>this.loadPage({direction:"next"}):void 0,data:o,hasNextPage:this.paginationController instanceof wu&&!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Ve();let n=e;switch(n=rt(n,"isDeleted",this.query.isDeleted),n=st(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=it(n,this.query.membership,t)),this.query.sortBy){case"firstCreated":n=n.sort(yt);break;case"lastCreated":n=n.sort(bt);break;case"displayName":n=n.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(mt);break;default:n=n.sort(Ct)}return n}shouldAbort(e){var t,n;const a=null===(t=Ze(this.cacheKey))||void 0===t?void 0:t.data;if(!a)return!0;return!(null===(n=null==a?void 0:a.data)||void 0===n?void 0:n.find((t=>t===e)))}static getMessagePreviewSetting(){return Ve().getMessagePreviewSetting(!1)}static getPaginationController(e){return e.channelIds&&e.channelIds.length>0?new Iu(e):new wu(e)}getSubscriptions(){const e=[{fn:Tl((e=>bo((t=>{var n,a;const r=Ps();(null===(n=Ze(["subChannelUnreadInfo","get",t.subChannelId]))||void 0===n?void 0:n.data)||r.resolve(t.subChannelId,"userMessageFeedMarker");const s=null===(a=Ze(["channel","get",t.channelId]))||void 0===a?void 0:a.data;s?(Bd(s,{lastActivity:t.createdAt}),e(t)):r.resolve(t.channelId,"channel")}))),"channelId","channel"),action:"onUpdate"},{fn:Tl((e=>wo((t=>{var n;const a=null===(n=Ze(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Bd(a,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ya,action:"onDelete"},{fn:Va,action:"onUpdate"},{fn:or,action:"onMute"},{fn:e=>er((t=>{Su(t),e(t)})),action:"onJoin"},{fn:e=>ar(((t,n)=>{var a,r;const{userId:s}=Ve();if("member"===this.query.membership&&s===n.userId){const e=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;et(this.cacheKey,Object.assign(Object.assign({},e),{data:null!==(r=null==e?void 0:e.data.filter((e=>e!==t.channelId)))&&void 0!==r?r:[]}))}return e(t)})),action:"onLeft"},{fn:lr,action:"onMemberAdded"},{fn:hr,action:"onMemberRemoved"},{fn:e=>Tr((t=>{const n=t.archives.map((e=>{var t;return null===(t=Ze(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onArchived"},{fn:e=>kr((t=>{const n=t.archives.map((e=>{var t;return null===(t=Ze(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onUnarchived"},{fn:Tl(Jo,"entityId","channel"),action:"onUpdate"},{fn:Tl(Ld,"entityId","channel"),action:"onUpdate"},{fn:Tl((e=>bo((async t=>{var n;if("no-message-preview"===await ku.getMessagePreviewSetting())return;if(Oa(t),this.shouldAbort(t.channelId))return;const a=null===(n=Ze(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Bd(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Tl((e=>wo((async t=>{var n;if("no-message-preview"===await ku.getMessagePreviewSetting())return;if(Oa(t),this.shouldAbort(t.channelId))return;const a=null===(n=Ze(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Bd(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Tl((e=>xd((async t=>{"no-message-preview"!==await ku.getMessagePreviewSetting()&&(Ta(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Tl((e=>qd((async t=>{const n=await ku.getMessagePreviewSetting();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await Ta(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&await Bi(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:Tl((e=>Co((async t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(!a)return;a.data.find((e=>{const n=Jn(e);return(null==n?void 0:n.subChannelId)===t.subChannelId}))&&(await Bi(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Tl((e=>Nd((async t=>{var n;if("no-message-preview"===await ku.getMessagePreviewSetting())return;(null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data)&&(await ka(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Tl(Io,"channelId","channel"),action:"onUpdate"},{fn:Ou,action:"onResolveChannel"},{fn:e=>Tu((async t=>{if(t.feedMarkers){const n=t.feedMarkers.map((e=>{var t;return null===(t=Ze(["channel","get",e.entityId]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"OnResolveUnread"},{fn:Tl(vu,"channelId","channel"),action:"onUpdate"},{fn:Tl((e=>bu((t=>{t.forEach(e)}))),"channelId","channel"),action:"onUpdate"}];return this.paginationController instanceof wi?[...e,{fn:e=>$a((t=>{Su(t),e(t)})),action:"onCreate"}]:e}}const Au=()=>{var e;const t=Ve();t.log("channel/getTotalChannelsUnread.locally");const n=(null===(e=Xe(["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 _u extends wi{async getRequest(e,t){var n,a;const r=null!==(n=e.limit)&&void 0!==n?n:de,s=t?Number.parseInt(t,10):0;0===s&&await Dd();const o=(null!==(a=Xe(["archivedChannel","get"]))&&void 0!==a?a:[]).map((e=>e.data)).slice().sort(((e,t)=>Number(new Date(t.archivedAt))-Number(new Date(e.archivedAt)))),i=s*r,c=i+r,l=o.slice(i,c),d=c<o.length;return l.length>0&&await Mr(l.map((e=>e.channelId))),{archives:l,paging:{next:d?String(s+1):void 0,previous:void 0}}}}class Eu extends Ci{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){}appendToQueryStream(e,t,n=!1){var a,r;const s=e.archives.map((e=>e.channelId));if(n)return void et(this.cacheKey,{data:s,params:{}});const o=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,i=null!==(r=null==o?void 0:o.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},o),{data:"prev"===t?[...new Set([...s,...i])]:[...new Set([...i,...s])]}))}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(a){if("onArchived"===e){const e=a.data.filter((e=>!t.includes(e)));a.data=[...t,...e]}"onUnarchived"!==e&&"onDelete"!==e||(a.data=a.data.filter((e=>!t.includes(e)))),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Ru extends ki{constructor(e,t){const n=O.default(e),a=["archivedChannel","collection",n];super(new _u(e),n,a,t),this.queryStreamController=new Eu(e,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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=>Tr((t=>e(t.archives.map((e=>e.channelId))))),action:"onArchived"},{fn:e=>kr((t=>e(t.archives.map((e=>e.channelId))))),action:"onUnarchived"},{fn:e=>Va((t=>e([t.channelId]))),action:"onUpdate"},{fn:e=>Ya((t=>e([t.channelId]))),action:"onDelete"}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=null!==(r=s.data.map((e=>Ze(["channel","get",e]))).filter((e=>Boolean(e))).map((({data:e})=>e)).map(Pr))&&void 0!==r?r:[];(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class Pu extends wi{async getRequest(e,t){const{query:n,exactMatch:a,isMemberOnly:r,types:s,tags:o,sortBy:i,orderBy:c,limit:l=ue}=e,d=t?{token:t}:{limit:Math.min(100,Math.max(1,l))},{data:u}=await this.http.get("/api/v2/search/channels",{params:{query:n,exactMatch:a,isMemberOnly:r,types:s,tags:o,sortBy:i,orderBy:c,options:d}});return u}}class Mu extends Ci{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){const t=await Pa(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)return void et(this.cacheKey,{data:e.channels.map(We("channel"))});const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,o=null!==(r=null==s?void 0:s.data)&&void 0!==r?r:[],i=e.channels.map(We("channel"));et(this.cacheKey,Object.assign(Object.assign({},s),{data:"prev"===t?[...new Set([...i,...o])]:[...new Set([...o,...i])]}))}reactor(){return()=>this.notifyChange({origin:"event",loading:!1})}subscribeRTE(e){return e.map((e=>e.fn(this.reactor())))}}const ju=()=>Ve().getMessagePreviewSetting(!1);class Uu extends ki{constructor(e,t){const n=O.default(e),a=["channel","search",n];super(new Pu(e),n,a,t),this.queryStreamController=new Mu(e,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return this.queryStreamController.subscribeRTE(this.getSubscriptions())}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=null!==(r=s.data.map((e=>Ze(["channel","get",e]))).filter(Boolean).map((e=>Pr(e.data))))&&void 0!==r?r:[];(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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)}shouldAbort(e){var t;const n=null===(t=Ze(this.cacheKey))||void 0===t?void 0:t.data;return!n||!n.data.find((t=>t===e))}getSubscriptions(){return[{fn:Tl((e=>bo((t=>{var n;const a=null===(n=Ze(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Bd(a,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Tl((e=>wo((t=>{var n;const a=null===(n=Ze(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Bd(a,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ya,action:"onDelete"},{fn:Va,action:"onUpdate"},{fn:or,action:"onMute"},{fn:e=>Tr((t=>{const n=t.archives.map((e=>{var t;return null===(t=Ze(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onArchived"},{fn:e=>kr((t=>{const n=t.archives.map((e=>{var t;return null===(t=Ze(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onUnarchived"},{fn:Tl(Jo,"entityId","channel"),action:"onUpdate"},{fn:Tl(Ld,"entityId","channel"),action:"onUpdate"},{fn:Tl((e=>bo((async t=>{var n;if("no-message-preview"===await ju())return;if(Oa(t),this.shouldAbort(t.channelId))return;const a=null===(n=Ze(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Bd(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Tl((e=>wo((async t=>{var n;if("no-message-preview"===await ju())return;if(Oa(t),this.shouldAbort(t.channelId))return;const a=null===(n=Ze(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Bd(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Tl((e=>xd((async t=>{"no-message-preview"!==await ju()&&(Ta(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Tl((e=>qd((async t=>{const n=await ju();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await Ta(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&await Bi(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:Tl((e=>Co((async t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(!a)return;a.data.find((e=>{const n=Jn(e);return(null==n?void 0:n.subChannelId)===t.subChannelId}))&&(await Bi(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Tl((e=>Nd((async t=>{var n;if("no-message-preview"===await ju())return;(null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data)&&(await ka(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:e=>Tu((async t=>{if(t.feedMarkers){const n=t.feedMarkers.map((e=>{var t;return null===(t=Ze(["channel","get",e.entityId]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"OnResolveUnread"},{fn:Tl(vu,"channelId","channel"),action:"onUpdate"},{fn:Tl((e=>bu((t=>{t.forEach(e)}))),"channelId","channel"),action:"onUpdate"}]}}class Du extends wi{async getRequest(e,t){const{limit:n=de,includeDeleted:a}=e,r=Kn(e,["limit","includeDeleted"]),s=t?{token:t}:{limit:n},o=!1!==a&&void 0,{data:i}=await this.http.get(`/api/v4/channels/${encodeURIComponent(r.channelId)}/users`,{params:Object.assign(Object.assign({},r),{options:s,isDeleted:o})});return i}}class xu extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.channelUsers.map((({channelId:e,userId:t})=>We("channelUsers")({channelId:e,userId:t})))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channelUsers.map((({channelId:e,userId:t})=>We("channelUsers")({channelId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;if(this.query.channelId!==t.channelId)return;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(!a)return;const r=We("channelUsers")({channelId:this.query.channelId,userId:t.userId}),s=this.query.memberships,o=!s||s.includes(t.membership);"none"!==t.membership&&o?a.data.includes(r)||(a.data=[r,...a.data]):a.data=a.data.filter((e=>e!==r)),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class qu extends ki{constructor(e,t){const n=O.default(e),a=["channelUsers","collection",n];super(new Du(e),n,a,t),this.query=e,this.queryStreamController=new xu(this.query,this.cacheKey,this.notifyChange.bind(this),Pa),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:er,action:"onJoin"},{fn:ar,action:"onLeft"},{fn:lr,action:"onMemberAdded"},{fn:hr,action:"onMemberRemoved"},{fn:mr,action:"onChannelMemberBanned"},{fn:vr,action:"onChannelMemberUnbanned"},{fn:Ir,action:"onChannelMemberRoleAdded"},{fn:Or,action:"onChannelMemberRoleRemoved"},{fn:Er,action:"onChannelSetUserMuted"},{fn:(e=this.query.channelId,t=>{const n=Ve();return Mt(n,"user.deleted","user.deleted",(n=>{var a,r;const s=Zr(n);if(0===s.users.length)return;const o=s.users[0];Ln(s);const i=We("channelUsers")({channelId:e,userId:o.userId}),c=null===(a=Ze(["channelUsers","get",i]))||void 0===a?void 0:a.data;nt(["channelUsers","get",i],Object.assign(Object.assign({},c),{user:o}));const l=null===(r=Ze(["channel","get",e]))||void 0===r?void 0:r.data;l&&t(l,c)}))}),action:"onChannelMemberChanged"}]);var e}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["channelUsers","get",e]))).filter(Boolean).map((({data:e})=>e)).map(dl.channelMember))&&void 0!==r?r:[]);(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=ot(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?bt:yt),t}}const Nu=(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`getMembers(tmpid: ${s}) > listen`);const o=new qu(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{at(c)})),()=>{a(`getMembers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}};var Bu=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=Ve();n.log("channel/addMembers",e,t);const{data:a}=await n.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users`,{channelId:e,userIds:t});t.forEach((e=>jt("channel.membersAdded",Object.assign(Object.assign({},a),{channelUsers:a.channelUsers.filter((t=>t.userId===e))}))));const r=await Pa(a);n.cache&&Ln(r);const{channelUsers:s}=r;return!!s.find((t=>t.channelId===e&&"member"===t.membership))},removeMembers:async(e,t)=>{const n=Ve();n.log("channel/removeMembers",e,t);const{data:a}=await n.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users`,{data:{channelId:e,userIds:t}});t.forEach((e=>jt("channel.membersRemoved",Object.assign(Object.assign({},a),{channelUsers:a.channelUsers.filter((t=>t.userId===e))}))));const r=await Pa(a);n.cache&&Ln(r);const{channelUsers:s}=r;return!!s.find((t=>t.channelId===e&&"member"!==t.membership))},applyFilter:(e,t)=>{let n=ot(e,"roles",t.roles);t.memberships&&(n=n.filter((e=>!(!t.memberships.includes("muted")||!e.isMuted)||t.memberships.includes(e.membership))));const a=t.sortBy?t.sortBy:"lastCreated";return n=n.sort("lastCreated"===a?bt:yt),n},getMembers:Nu,searchMembers:(e,t,n)=>Nu(e,t)});var Lu=Object.freeze({__proto__:null,addRole:async(e,t,n)=>{const a=Ve();a.log("channel/addRole",e,t,n);const{data:r}=await a.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{channelId:e,role:t,userIds:n}),s=await Pa(r);a.cache&&Ln(s),jt("local.channel-moderator.role-added",s);const{channelUsers:o}=s;return!!o.find((n=>n.channelId===e&&n.roles.includes(t)))},removeRole:async(e,t,n)=>{const a=Ve();a.log("channel/removeRole",e,t,n);const{data:r}=await a.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{data:{channelId:e,role:t,userIds:n}}),s=await Pa(r);a.cache&&Ln(s),jt("local.channel-moderator.role-removed",s);const{channelUsers:o}=s;return!!o.find((n=>n.channelId===e&&!n.roles.includes(t)))},banMembers:async(e,t)=>{const n=Ve();n.log("channel/banMembers",{userIds:t,channelId:e});const{data:a}=await n.http.put(`/api/v3/channels/${e}/users/ban`,{userIds:t}),r=await Pa(a),{channelUsers:s}=r,o=n.cache&&Date.now();return n.cache&&Ln(r,{cachedAt:o}),jt("channel.banned",a),{data:null==s?void 0:s.filter((e=>"banned"===e.membership)),cachedAt:o}},unbanMembers:async(e,t)=>{const n=Ve();n.log("channel/unbanMembers",{userIds:t,channelId:e});const{data:a}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}/users/unban`,{userIds:t}),r=await Pa(a),s=n.cache&&Date.now();n.cache&&Ln(r,{cachedAt:s}),jt("channel.unbanned",a);const{channelUsers:o}=r;return{data:null==o?void 0:o.filter((e=>"member"===e.membership)),cachedAt:s}},muteMembers:async(e,t,n=-1)=>{var a;const r=Ve();r.log("channel/muteMembers",{userIds:t,channelId:e,mutePeriod:n});const{data:s}=await r.http.put(`/api/v2/channel/${e}/users/mute`,{userIds:t,mutePeriod:-1===n?n:1e3*n}),{success:o}=s,i=-1===n?new Date("9999-12-31T23:59:59.999Z").toISOString():new Date(Date.now()+1e3*n).toISOString();return jt("channel.setMutedUsers",{channelId:e,userIds:t,muteTimeout:i,actor:null!==(a=r.userId)&&void 0!==a?a:""}),o},unmuteMembers:async(e,t)=>{var n;const a=Ve();a.log("channel/unmuteMembers",{userIds:t,channelId:e});const{data:r}=await a.http.put(`/api/v2/channel/${encodeURIComponent(e)}/users/mute`,{userIds:t,mutePeriod:0}),{success:s}=r;return jt("channel.setMutedUsers",{channelId:e,userIds:t,muteTimeout:new Date(0).toISOString(),actor:null!==(n=a.userId)&&void 0!==n?n:""}),s}}),Fu=Object.freeze({__proto__:null,Membership:Bu,Moderation:Lu,getChannelByIds:Mr,createChannel:Ni,updateChannel:async(e,t)=>{const n=Ve();n.log("channel/updateChannel",e,t);const{data:a}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}`,t),r=await Pa(a),s=n.cache&&Date.now();n.cache&&Ln(r,{cachedAt:s});const{channels:o}=r;return{data:qa(o.find((t=>t.channelId===e))),cachedAt:s}},deleteChannel:async e=>{const t=Ve();t.log("channel/deleteChannel",e),await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}`);const n=await Bi(e);return qa(n.data)},joinChannel:async e=>{const t=Ve();t.log("channel/joinChannel",e);const{data:n}=await t.http.post(`/api/v3/channels/${encodeURIComponent(e)}/join`),a=await Pa(n);t.cache&&Ln(a);const{channelUsers:r}=a;return!!r.find((t=>t.channelId===e&&"member"===t.membership))},leaveChannel:async e=>{const t=Ve();t.log("channel/leaveChannel",e);const{data:n}=await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/leave`),a=await Pa(n);t.cache&&Ln(a);const{channelUsers:r}=a;return!!r.find((t=>t.channelId===e&&"member"!==t.membership))},muteChannel:async(e,t=-1)=>{const n=Ve();if(n.log("channel/muteChannel",e),-1!==t&&t<0)throw new Le("Mute Period can only be positive numbers or -1(mute forever)",800110,"error");const{data:a}=await n.http.put(`/api/v2/channel/${encodeURIComponent(e)}/mute`,{mutePeriod:t}),{success:r}=a;return r},unmuteChannel:async e=>{const t=Ve();t.log("channel/unmuteChannel",e);const{data:n}=await t.http.put(`/api/v2/channel/${encodeURIComponent(e)}/mute`,{mutePeriod:0}),{success:a}=n;return a},archiveChannel:async e=>{const t=Ve();t.log("channel/archiveChannel",e),await t.http.post(`/api/v1/archives/channels/${encodeURIComponent(e)}`);const n={channelId:e,archivedAt:(new Date).toISOString()};t.cache&&et(["archivedChannel","get",We("archivedChannel")(n)],n),jt("local.channel.archived",{archives:[n]})},unarchiveChannel:async e=>{var t;const n=Ve();n.log("channel/unarchiveChannel",e),await n.http.delete(`/api/v1/archives/channels/${encodeURIComponent(e)}`);const a=null===(t=Ze(["archivedChannel","get",e]))||void 0===t?void 0:t.data,r=null!=a?a:{channelId:e,archivedAt:(new Date).toISOString()};n.cache&&at(["archivedChannel","get",e],!0),jt("local.channel.unarchived",{archives:[r]})},getArchivedChannelIds:Dd,onChannelCreated:$a,onChannelUpdated:Va,onChannelDeleted:Ya,onChannelJoined:er,onChannelLeft:ar,onChannelSetMuted:or,onChannelMemberAdded:lr,onChannelMemberRemoved:hr,onChannelMemberBanned:mr,onChannelMemberUnbanned:vr,onChannelMemberRoleAdded:Ir,onChannelMemberRoleRemoved:Or,onChannelArchived:Tr,onChannelUnarchived:kr,getChannel:(e,t)=>{const n=Ve();let a;return Ui(e,(async e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:Pr(e.data)}),r=Kn(n,["origin"]);return La(a,r)?void 0:(a=r,t(n))}),"channelId",Bi,[Va,Ya,er,ar,lr,hr,mr,vr,or,Tl(Jo,"entityId","channel"),Tl(Ld,"entityId","channel"),Tl((t=>bo((async a=>{await(async a=>{var r;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Oa(a),a.channelId!==e)return;const s=null===(r=Ze(["channel","get",e]))||void 0===r?void 0:r.data;s&&(Bd(s,{messagePreviewId:a.messageId}),t(a))})(a),t(a)}))),"channelId","channel"),Tl((t=>wo((async a=>{var r;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Oa(a),a.channelId!==e)return;const s=null===(r=Ze(["channel","get",e]))||void 0===r?void 0:r.data;s&&(Bd(s,{messagePreviewId:a.messageId}),t(a))}))),"channelId","channel"),Tl((t=>xd((async a=>{var r;const s=null===(r=Ze(["channel","get",e]))||void 0===r?void 0:r.data;if(!s||s.messagePreviewId!==a.messageId)return;"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(await Ta(a),t(a))}))),"channelId","channel"),Tl((t=>qd((async a=>{var r;const s=null===(r=Ze(["channel","get",e]))||void 0===r?void 0:r.data;if(!s||s.messagePreviewId!==a.messageId)return;const o=await n.getMessagePreviewSetting(!1);"no-message-preview"!==o&&("message-preview-not-include-deleted"===o?(at(["messagePreviewChannel","get",e]),await Bi(a.channelId)):await Ta(a),t(a))}))),"channelId","channel"),Tl((e=>Co((async t=>{var a,r;const{channelId:s,subChannelId:o}=t,i=null===(a=Ze(["messagePreviewChannel","get",s]))||void 0===a?void 0:a.data;if(!i||i.subChannelId!==o)return;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;await Bi(s);(null===(r=Ze(["channel","get",s]))||void 0===r?void 0:r.data)&&e(t)}))),"channelId","channel"),Tl((t=>Nd((async a=>{var r,s;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;ka(a);const o=null===(r=Ze(["messagePreviewChannel","get",e]))||void 0===r?void 0:r.data;if(!o||o.subChannelId!==a.subChannelId)return;(null===(s=Ze(["channel","get",e]))||void 0===s?void 0:s.data)&&t(a)}))),"channelId","channel"),Tl(Io,"channelId","channel"),Tl(vu,"channelId","channel"),Tl((e=>bu((t=>{t.forEach(e)}))),"channelId","channel")],{forceDispatch:!0})},getChannels:(e,t,n)=>{const{log:a,cache:r,userId:s}=Ve();r||console.log(pe);const o=Date.now();a(`getChannels(tmpid: ${o}) > listen`);const i=new ku(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{at(l)})),()=>{a(`getChannels(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}},getTotalChannelsUnread:e=>{const{_id:t}=kt();if(!t)throw new Le("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:a}=Ve();a||console.log("For using Live Object feature you need to enable Cache!");n(`liveTotalChannelsUnread(tmpid: ${Date.now()}) > listen`);const r=[];let s,o=!1;const i=t=>{const{data:n}=t,a=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;s=a?ti(a):a,e({data:a?Object.assign(Object.assign({},a),{isMentioned:a.isMentioned}):a,loading:t.loading,error:t.error})};return r.push(bu((e=>{const{data:t}=Au();La(s,t)||i({loading:!1,data:t})}))),(()=>{const e=xe((async()=>Au()));Ne(e,(({error:e,data:t,loading:n,origin:a,cachedAt:s})=>{s===me?(i({data:t,origin:a,loading:!1,error:new Fe(fe,800800,"error")}),o=!0,r.forEach((e=>e()))):o||i({loading:n,data:t,origin:a,error:e}),e&&r.forEach((e=>e()))}))})(),()=>{r.forEach((e=>e()))}},getArchivedChannels:(e,t)=>{const{log:n,cache:a}=Ve();a||console.log(pe);const r=Date.now();n(`getArchivedChannels(tmpid: ${r}) > listen`);const s=new Ru(e,t),o=s.startSubscription(),i=s.getCacheKey();return o.push((()=>{at(i)})),()=>{n(`getArchivedChannels(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},searchChannels:(e,t)=>{const{log:n,cache:a}=Ve();a||console.log(pe);const r=Date.now();n(`searchChannels(tmpid: ${r}) > listen`);const s=new Uu(e,t),o=s.startSubscription(),i=s.getCacheKey();return o.push((()=>{at(i)})),()=>{n(`searchChannels(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},MARKER_INCLUDED_CHANNEL_TYPE:Aa,isUnreadCountSupport:_a,convertFromRaw:Ea,preUpdateChannelCache:Ra,prepareChannelPayload:Pa});const Ku=(e,t)=>{0!==e.length&&0!==t.length&&e.forEach((({communityId:e})=>{const n=t.filter((({communityId:t})=>e===t));et(["communityUsers","collection",e],n)}))},$u=async(e,t)=>{const n=Ve();n.log("community/getCommunities",e);const a=e.map((e=>encodeURIComponent(e))),{data:r}=await n.http.get("/api/v3/communities/list",{params:{communityIds:a,includeDiscoverablePrivateCommunity:null==t||t}}),s=mc(r),o=n.cache&&Date.now();return n.cache&&(Ln(s,{cachedAt:o}),Ku(s.communities,s.communityUsers)),{data:s.communities.map((e=>dl.community(e))),cachedAt:o}};$u.locally=e=>{const t=Ve();if(t.log("community/getCommunities.locally",e),!t.cache)return;const n=e.map((e=>Ze(["community","get",e]))).filter(Boolean),a=n.map((({data:e})=>e)),r=n.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1))[0];return n.length<e.length?void 0:{data:a,cachedAt:r.cachedAt}};const Qu=async e=>{const t=Ve();t.log("community/getCommunity",e);const{data:n}=await t.http.get(`/api/v3/communities/${e}`),a=mc(n),r=t.cache&&Date.now();t.cache&&(Ln(a,{cachedAt:r}),Ku(a.communities,a.communityUsers));const{communities:s}=a;return{data:s.find((t=>t.communityId===e)),cachedAt:r}};Qu.locally=e=>{const t=Ve();if(t.log("community/getCommunity.locally",e),!t.cache)return;const n=Ze(["community","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const zu=(e,t)=>{const n=Ve();return Mt(n,e,e,(e=>{const a=mc(e);if(n.cache){Ln(a);const e=Ze(["community","get",a.communities[0].communityId]);t(e.data)}else t(a.communities[0])}))},Vu=e=>zu("community.created",e),Hu=e=>zu("community.updated",e),Ju=e=>zu("community.deleted",e);class Wu extends wi{async getRequest(e,t){var n;const{limit:a=de}=e,r=Kn(e,["limit"]),s=t?{token:t}:{limit:a},{data:o}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},r),{isDeleted:oa(r.includeDeleted),keyword:r.displayName,filter:r.membership,includeDiscoverablePrivateCommunity:null===(n=r.includeDiscoverablePrivateCommunity)||void 0===n||n,options:s})});return o}}class Gu extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.communities.map(We("community"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(We("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Ze(this.cacheKey))||void 0===t?void 0:t.data;n&&(et(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Yu,Xu;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Yu||(Yu={})),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"}(Xu||(Xu={}));class Zu extends wi{async getRequest(e,t){const{limit:n=de,includeDeleted:a,excludingRoles:r}=e,s=Kn(e,["limit","includeDeleted","excludingRoles"]),o=t?{token:t}:{limit:n},i=!1!==a&&void 0,{data:c}=await this.http.get(`/api/v3/communities/${s.communityId}/users`,{params:Object.assign(Object.assign({},s),{options:o,isDeleted:i})});return c}}class eh extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>We("communityUsers")({communityId:e,userId:t})))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>We("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;a&&(t.forEach((e=>{var t;const n=We("communityUsers")({communityId:this.query.communityId,userId:e.userId});if("none"===e.communityMembership)a.data=a.data.filter((e=>e!==n));else if(!a.data.includes(n)){if(null===(t=this.query.excludingRoles)||void 0===t?void 0:t.length){if((e.roles||[]).some((e=>this.query.excludingRoles.includes(e))))return}a.data=[n,...a.data]}})),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}function th(e,t,n){return!!e.permissions.some((e=>e===n))||t.communityUsers.find((t=>t.userId===e.userId)).permissions.some((e=>e===n))}function nh(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=>!th(e,t,"BAN_COMMUNITY_USER"))):t.communityUsers.filter((e=>!th(e,t,"ADD_COMMUNITY_USER")))}const ah=(e,t)=>{const n=Ve();return Mt(n,e,e,(a=>{const r=mc(a),{communities:s,communityUsers:o}=r,i=hc(s,o);if(r.communities=i,n.cache){Ln(r,void 0,!1);const n=Ze(["community","get",r.communities[0].communityId]),a=nh(e,r).map((e=>{const t=Ze(["communityUsers","get",We("communityUsers")(e)]);return null==t?void 0:t.data})).filter(Ai);t(n.data,a)}else t(r.communities[0],nh(e,r))}))},rh=(e,t)=>{const n=Ve();return Mt(n,e,e,(a=>{const r=mc(a),{communities:s,communityUsers:o}=r,i=hc(s,o);if(r.communities=i,n.cache){Ln(r,void 0,!1);const n=Ze(["community","get",r.communities[0].communityId]),a=nh(e,r).map((e=>{const t=Ze(["communityUsers","get",We("communityUsers")(e)]);return null==t?void 0:t.data})).filter(Ai);t(n.data,a)}else t(r.communities[0],nh(e,r))}))},sh=e=>ah("community.userBanned",e),oh=e=>ah("community.userChanged",e),ih=e=>ah("community.userUnbanned",e),ch=e=>ah("community.roleAdded",e),lh=e=>ah("community.roleRemoved",e),dh=e=>rh("local.community.userAdded",e),uh=e=>rh("local.community.userRemoved",e),hh=e=>ah("community.joined",e),ph=e=>ah("community.left",e),fh=e=>rh("local.community.joined",e),mh=e=>rh("local.community.left",e),gh=e=>{const t=Ve(),n=[Mt(t,"onCommunityUpdate","v4.local.community.joined",(async t=>{e(t[0])}))];return()=>{n.forEach((e=>e()))}},yh=e=>{const t=Ve();return Mt(t,"onLocalCommunityRoleRemoved","local.community.roleRemoved",(async t=>{const{communities:n,communityUsers:a}=t;e(n[0],a.filter((e=>"member"===e.communityMembership)))}))},vh=e=>{const t=Ve();return Mt(t,"onLocalCommunityRoleAdded","local.community.roleAdded",(async t=>{const{communities:n,communityUsers:a}=t;e(n[0],a.filter((e=>"member"===e.communityMembership)))}))},bh=e=>t=>{const n=Ve();return Mt(n,"user.deleted","user.deleted",(n=>{var a,r;const s=Zr(n);if(0===s.users.length)return;const o=s.users[0];Ln(s);const i=We("communityUsers")({communityId:e,userId:o.userId}),c=null===(a=Ze(["communityUsers","get",i]))||void 0===a?void 0:a.data;et(["communityUsers","get",i],Object.assign(Object.assign({},c),{user:o}));const l=null===(r=Ze(["community","get",e]))||void 0===r?void 0:r.data;t(l,[Object.assign(Object.assign({},c),{user:o})])}))};class wh extends ki{constructor(e,t){const n=O.default(e),a=["communityUsers","collection",n];super(new Zu(e),n,a,t),this.query=e,this.queryStreamController=new eh(this.query,this.cacheKey,this.notifyChange.bind(this),mc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:hh,action:Xu.OnCommunityJoined},{fn:fh,action:Xu.OnCommunityJoined},{fn:ph,action:Xu.OnCommunityLeft},{fn:mh,action:Xu.OnCommunityLeft},{fn:sh,action:Xu.OnCommunityUserBanned},{fn:oh,action:Xu.OnCommunityUserChanged},{fn:ch,action:Xu.OnCommunityUserRoleAdded},{fn:lh,action:Xu.OnCommunityUserRoleRemoved},{fn:vh,action:Xu.OnCommunityUserRoleAdded},{fn:yh,action:Xu.OnCommunityUserRoleRemoved},{fn:ih,action:Xu.OnCommunityUserUnbanned},{fn:dh,action:Xu.OnCommunityUserAdded},{fn:uh,action:Xu.onCommunityUserRemoved},{fn:bh(this.query.communityId),action:Xu.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["communityUsers","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=ot(e,"roles",this.query.roles);if(this.query.memberships&&(n=n.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),(null===(t=this.query.excludingRoles)||void 0===t?void 0:t.length)&&(n=n.filter((e=>!(e.roles||[]).some((e=>this.query.excludingRoles.includes(e)))))),!1===this.query.includeDeleted&&(n=n.filter((({user:e})=>!0!==(null==e?void 0:e.isDeleted)))),"firstCreated"===this.query.sortBy)n=n.sort(yt);else n=n.sort(bt);return n}}class Ih extends wi{async getRequest(e,t){const{limit:n=de,includeDeleted:a,excludingRoles:r}=e,s=Kn(e,["limit","includeDeleted","excludingRoles"]),o=t?{token:t}:{limit:n},i=!1!==a&&void 0,{data:c}=await this.http.get(`/api/v3/communities/${s.communityId}/users`,{params:Object.assign(Object.assign({},s),{options:o,isDeleted:i})});return c}}class Ch extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>We("communityUsers")({communityId:e,userId:t})))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>We("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;a&&(t.forEach((e=>{const t=We("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership&&(a.data=a.data.filter((e=>e!==t)))})),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Sh;!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"}(Sh||(Sh={}));class Oh extends ki{constructor(e,t){const n=O.default(e),a=["communityUsers","collection",n];super(new Ih(e),n,a,t),this.query=e,this.queryStreamController=new Ch(this.query,this.cacheKey,this.notifyChange.bind(this),mc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:hh,action:Sh.OnCommunityJoined},{fn:fh,action:Sh.OnCommunityJoined},{fn:ph,action:Sh.OnCommunityLeft},{fn:mh,action:Sh.OnCommunityLeft},{fn:sh,action:Sh.OnCommunityUserBanned},{fn:oh,action:Sh.OnCommunityUserChanged},{fn:yh,action:Sh.OnCommunityUserRoleRemoved},{fn:lh,action:Sh.OnCommunityUserRoleRemoved},{fn:ih,action:Sh.OnCommunityUserUnbanned},{fn:bh(this.query.communityId),action:Sh.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["communityUsers","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=ot(e,"roles",this.query.roles);return this.query.memberships&&(n=n.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),this.query.search&&(n=ut(n,this.query.search)),(null===(t=this.query.excludingRoles)||void 0===t?void 0:t.length)&&(n=n.filter((e=>!(e.roles||[]).some((e=>this.query.excludingRoles.includes(e)))))),!1===this.query.includeDeleted&&(n=n.filter((({user:e})=>!0!==(null==e?void 0:e.isDeleted)))),n}}var Th=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=Ve();n.log("community/moderation/addMembers",e,t);const{data:a}=await n.http.post(`/api/v3/communities/${e}/users`,{communityId:e,userIds:t});jt("local.community.userAdded",a);const r=Qn(a,"communityUsers");n.cache&&Ln(r);const{communityUsers:s}=r;return!!s.find((t=>t.communityId===e&&"member"===t.communityMembership))},removeMembers:async(e,t)=>{const n=Ve();n.log("community/moderation/removeMembers",e,t);const{data:a}=await n.http.delete(`/api/v3/communities/${e}/users`,{data:{communityId:e,userIds:t}});jt("local.community.userRemoved",a);const r=Qn(a,"communityUsers");n.cache&&Ln(r);const{communityUsers:s}=r;return!!s.find((t=>t.communityId===e&&"member"!==t.communityMembership))},applyFilter:(e,t)=>{var n;let a=ot(e,"roles",t.roles);t.memberships&&(a=a.filter((({communityMembership:e})=>t.memberships.includes(e)))),(null===(n=t.excludingRoles)||void 0===n?void 0:n.length)&&(a=a.filter((e=>!(e.roles||[]).some((e=>t.excludingRoles.includes(e))))));const r=t.sortBy?t.sortBy:"lastCreated";return a=a.sort("lastCreated"===r?bt:yt),a},getMembers:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`getMembers(tmpid: ${s}) > listen`);const o=new wh(e,(e=>{t(e)})),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{at(c)})),()=>{a(`getMembers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},searchMembers:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`getMembers(tmpid: ${s}) > listen`);const o=new Oh(e,(e=>{t(e)})),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{at(c)})),()=>{a(`getMembers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},onCommunityUserAdded:e=>ah("community.userAdded",e),onCommunityUserRemoved:e=>ah("community.userRemoved",e),onCommunityUserBanned:sh,onCommunityUserChanged:oh,onCommunityUserUnbanned:ih,onCommunityUserRoleAdded:ch,onCommunityUserRoleRemoved:lh,onLocalCommunityUserAdded:dh,onLocalCommunityUserRemoved:uh,onCommunityJoined:hh,onCommunityLeft:ph,onLocalCommunityJoined:fh,onLocalCommunityLeft:mh,onLocalCommunityJoin:gh});class kh extends ki{constructor(e,t){const n=O.default(e),a=["community","collection",n];super(new Wu(e),n,a,t),this.query=e,this.queryStreamController=new Gu(this.query,this.cacheKey,this.notifyChange.bind(this),mc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:Ju,action:Yu.OnCommunityDeleted},{fn:Hu,action:Yu.OnCommunityUpdated},{fn:hh,action:Xu.OnCommunityJoined},{fn:ph,action:Xu.OnCommunityLeft},{fn:oh,action:Xu.OnMemberCountChanged},{fn:fh,action:Xu.OnCommunityJoined},{fn:mh,action:Xu.OnCommunityLeft},{fn:Tl(gh,"targetId","community"),action:Yu.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["community","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Ve();let n=e;return this.query.includeDeleted||(n=rt(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=lt(n,this.query.membership,t)),n}}class Ah extends wi{async getRequest(e,t){var n;const{limit:a=de}=e,r=Kn(e,["limit"]),s=t?{token:t}:{limit:a},{data:o}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},r),{isDeleted:oa(r.includeDeleted),filter:r.membership,includeDiscoverablePrivateCommunity:null===(n=r.includeDiscoverablePrivateCommunity)||void 0===n||n,options:s})});return o}}class _h extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&(Ln(t,{cachedAt:a}),Ku(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.communities.map(We("community"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(We("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Ze(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],et(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Eh;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Eh||(Eh={}));class Rh extends ki{constructor(e,t){const n=O.default(e),a=["community","collection",n];super(new Ah(e),n,a,t),this.query=e,this.queryStreamController=new _h(this.query,this.cacheKey,this.notifyChange.bind(this),mc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:Vu,action:Eh.OnCommunityCreated},{fn:Ju,action:Eh.OnCommunityDeleted},{fn:Hu,action:Eh.OnCommunityUpdated},{fn:hh,action:Xu.OnCommunityJoined},{fn:ph,action:Xu.OnCommunityLeft},{fn:oh,action:Xu.OnMemberCountChanged},{fn:fh,action:Xu.OnCommunityJoined},{fn:mh,action:Xu.OnCommunityLeft},{fn:Tl(gh,"targetId","community"),action:Eh.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=null!==(r=s.data.map((e=>Ze(["community","get",e]))).filter(Ai).map((({data:e})=>Dc(e))))&&void 0!==r?r:[];(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Ve();let n=e;this.query.includeDeleted||(n=rt(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=lt(n,this.query.membership,t));const a=(()=>"firstCreated"===this.query.sortBy?yt:bt)();return n=n.sort(a),n}}class Ph extends wi{async getRequest(e,t){const{limit:n=de,includeDiscoverablePrivateCommunity:a}=e,r=Kn(e,["limit","includeDiscoverablePrivateCommunity"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v3/communities/top-trending",{params:Object.assign(Object.assign({},r),{options:s,includeDiscoverablePrivateCommunity:null==a||a})});return o}}class Mh extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&(Ln(t,{cachedAt:a}),Ku(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.communities.map(We("community"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(We("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Ze(this.cacheKey))||void 0===t?void 0:t.data;n&&(et(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var jh;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(jh||(jh={}));class Uh extends ki{constructor(e,t){const n=O.default(e),a=["trendingCommunity","collection",n];super(new Ph(e),n,a,t),this.query=e,this.queryStreamController=new Mh(this.query,this.cacheKey,this.notifyChange.bind(this),mc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:Ju,action:jh.OnCommunityDeleted},{fn:Hu,action:jh.OnCommunityUpdated},{fn:hh,action:Xu.OnCommunityJoined},{fn:ph,action:Xu.OnCommunityLeft},{fn:oh,action:Xu.OnMemberCountChanged},{fn:fh,action:Xu.OnCommunityJoined},{fn:mh,action:Xu.OnCommunityLeft},{fn:Tl(gh,"targetId","community"),action:jh.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=null!==(r=s.data.map((e=>Ze(["community","get",e]))).filter(Ai).map((({data:e})=>Dc(e))))&&void 0!==r?r:[];(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class Dh extends wi{async getRequest(e,t){const{limit:n=de,includeDiscoverablePrivateCommunity:a}=e,r=Kn(e,["limit","includeDiscoverablePrivateCommunity"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v3/communities/recommended",{params:Object.assign(Object.assign({},r),{options:s,includeDiscoverablePrivateCommunity:null==a||a})});return o}}class xh extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&(Ln(t,{cachedAt:a}),Ku(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.communities.map(We("community"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(We("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Ze(this.cacheKey))||void 0===t?void 0:t.data;n&&(et(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var qh;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated",e.OnLocalCommunityJoin="onLocalCommunityJoin"}(qh||(qh={}));class Nh extends ki{constructor(e,t){const n=O.default(e),a=["community","collection",n];super(new Dh(e),n,a,t),this.query=e,this.queryStreamController=new xh(this.query,this.cacheKey,this.notifyChange.bind(this),mc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:Ju,action:qh.OnCommunityDeleted},{fn:Hu,action:qh.OnCommunityUpdated},{fn:hh,action:Xu.OnCommunityJoined},{fn:ph,action:Xu.OnCommunityLeft},{fn:oh,action:Xu.OnMemberCountChanged},{fn:fh,action:Xu.OnCommunityJoined},{fn:mh,action:Xu.OnCommunityLeft},{fn:Tl(gh,"targetId","community"),action:qh.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=null!==(r=s.data.map((e=>Ze(["community","get",e]))).filter(Ai).map((({data:e})=>Dc(e))))&&void 0!==r?r:[];(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class Bh extends wi{async getRequest(e,t){var n;const{limit:a=de,communityMembershipStatus:r}=e,s=Kn(e,["limit","communityMembershipStatus"]),o={type:e.limit?"pagination":void 0},i=t?Object.assign(Object.assign({},o),{token:t}):Object.assign(Object.assign({},o),{limit:a}),{data:c}=await this.http.get("/api/v1/semantic-search/communities",{params:Object.assign(Object.assign({},s),{filter:null!=r?r:"all",options:i,includeDiscoverablePrivateCommunity:null===(n=s.includeDiscoverablePrivateCommunity)||void 0===n||n})});return c}}function Lh(e){return e.communities.map((t=>{const n=e.searchResult.find((e=>e.communityId===t.communityId));return`${t.communityId}:${n}`}))}class Fh extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:Lh(e)});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...Lh(e)])]}))}}reactor(e){return e=>{var t;const n=null===(t=Ze(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],et(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Kh;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Kh||(Kh={}));class $h extends ki{constructor(e,t){const n=O.default(e),a=["community","collection",n];super(new Bh(e),n,a,t),this.query=e,this.queryStreamController=new Fh(this.query,this.cacheKey,this.notifyChange.bind(this),bc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:Vu,action:Kh.OnCommunityCreated},{fn:Ju,action:Kh.OnCommunityDeleted},{fn:Hu,action:Kh.OnCommunityUpdated},{fn:hh,action:Xu.OnCommunityJoined},{fn:ph,action:Xu.OnCommunityLeft},{fn:oh,action:Xu.OnMemberCountChanged},{fn:fh,action:Xu.OnCommunityJoined},{fn:mh,action:Xu.OnCommunityLeft},{fn:Tl(gh,"targetId","community"),action:Kh.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>{const[t,n]=e.split(":");return{communityId:t,score:parseFloat(n)}})).sort(((e,t)=>t.score-e.score)).map((({communityId:e})=>Ze(["community","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Ve();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=lt(n,this.query.communityMembershipStatus,t)),n}}class Qh extends wi{async getRequest(e,t){const{limit:n=de,communityIds:a}=e,r=Kn(e,["limit","communityIds"]),s=t?{token:t}:{limit:n},o=a.map((e=>encodeURIComponent(e))),{data:i}=await this.http.get("/api/v4/communities/join/requests",{params:Object.assign(Object.assign({},r),{options:s,communityIds:o})});return i}}var zh;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(zh||(zh={}));class Vh extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.joinRequests.map((e=>We("joinRequest")({joinRequestId:e._id})))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>We("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(!a)return;const r=(Array.isArray(t)?t:[t]).map((e=>e.joinRequestId));if(e===zh.OnLocalJoinRequestUpdated){if(!a.data.find((e=>r.includes(e))))return}e===zh.OnLocalJoinRequestCreated&&(a.data=[...new Set([...r,...a.data])]),e===zh.OnLocalJoinRequestDeleted&&(a.data=a.data.filter((e=>!r.includes(e)))),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Hh extends ki{constructor(e,t){const n=O.default(e),a=["joinRequestList","collection",n];super(new Qh(e),n,a,t),this.query=e,this.queryStreamController=new Vh(this.query,this.cacheKey,this.notifyChange.bind(this),gc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){const a=e;this.queryStreamController.appendToQueryStream(a,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Oc,action:zh.OnLocalJoinRequestCreated},{fn:Tc,action:zh.OnLocalJoinRequestUpdated},{fn:kc,action:zh.OnLocalJoinRequestUpdated},{fn:gh,action:zh.OnLocalJoinRequestUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a;const r=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!r)return;const s=this.applyFilter(r.data.map((e=>Ze(["joinRequest","get",e]))).filter(Ai).map((({data:e})=>e)).map(wc));(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.communityIds&&this.query.communityIds.length>0&&(t=t.filter((e=>this.query.communityIds.some((t=>t===e.targetId)))));const n=(()=>"firstCreated"===this.query.sortBy?yt:bt)();return t=t.sort(n),t}}var Jh;!function(e){e.ALL="all",e.MEMBER="member",e.NOT_MEMBER="notMember"}(Jh||(Jh={}));var Wh=Object.freeze({__proto__:null,addRoles:async(e,t,n)=>{const a=Ve();a.log("community/moderation/addRoles",e,t,n);const{data:r}=await a.http.post(`/api/v4/communities/${e}/users/roles`,{communityId:e,roles:t,userIds:n}),s=yc(r);a.cache&&Ln(s),jt("local.community.roleAdded",s);const{communityUsers:o}=s;return!!o.find((n=>n.communityId===e&&t.some((e=>n.roles.includes(e)))))},removeRoles:async(e,t,n)=>{const a=Ve();a.log("community/moderation/removeRoles",e,t,n);const{data:r}=await a.http.delete(`/api/v4/communities/${e}/users/roles`,{data:{communityId:e,roles:t,userIds:n}}),s=yc(r);a.cache&&Ln(s),jt("local.community.roleRemoved",s);const{communityUsers:o}=s;return!!o.find((n=>n.communityId===e&&!t.some((e=>n.roles.includes(e)))))},banMembers:async(e,t)=>{const n=Ve();n.log("community/banMembers",{userIds:t,communityId:e});const{data:a}=await n.http.put(`/api/v3/communities/${e}/users/ban`,{userIds:t}),r=Qn(a,"communityUsers"),s=n.cache&&Date.now();n.cache&&Ln(r,{cachedAt:s});const{communityUsers:o}=r;return{data:o.filter((e=>t.includes(e.userId))),cachedAt:s}},unbanMembers:async(e,t)=>{const n=Ve();n.log("community/unbanMembers",{userIds:t,communityId:e});const{data:a}=await n.http.put(`/api/v3/communities/${e}/users/unban`,{userIds:t}),r=Qn(a,"communityUsers"),s=n.cache&&Date.now();n.cache&&Ln(r,{cachedAt:s});const{communityUsers:o}=r;return{data:o.filter((e=>t.includes(e.userId))),cachedAt:s}}}),Gh=Object.freeze({__proto__:null,Moderation:Wh,Membership:Th,getCommunityByIds:$u,createCommunity:async e=>{const t=Ve();t.log("user/createCommunity",e);const{data:n}=await t.http.post("/api/v3/communities/",vc(e));jt("community.created",n);const a=mc(n),r=t.cache&&Date.now();t.cache&&(Ln(a,{cachedAt:r}),Ku(a.communities,a.communityUsers));const{communities:s}=a;return{data:dl.community(s[0]),cachedAt:r}},updateCommunity:async(e,t)=>{const n=Ve();n.log("community/updateCommunity",e,t);const{data:a}=await n.http.put(`/api/v3/communities/${e}`,vc(t));jt("community.updated",a);const r=mc(a),s=n.cache&&Date.now();n.cache&&(Ln(r,{cachedAt:s}),Ku(r.communities,r.communityUsers));const{communities:o}=r;return{data:dl.community(o.find((t=>t.communityId===e))),cachedAt:s}},deleteCommunity:async e=>{const t=Ve();t.log("community/deleteCommunity",e),await t.http.delete(`/api/v3/communities/${e}`);const n=await Qu(e);return jt("community.deleted",{communities:[n.data],categories:[],communityUsers:[],feeds:[],files:[],users:[]}),dl.community(n.data)},joinCommunity:async e=>{const t=Ve();t.log("community/joinCommunity",e);const{data:n}=await t.http.post(`/api/v3/communities/${e}/join`);jt("local.community.joined",n);const a=mc(n),r=t.cache&&Date.now();t.cache&&Ln(a,{cachedAt:r});const{communityUsers:s}=a;return!!s.find((t=>t.communityId===e&&"member"===t.communityMembership))},leaveCommunity:async e=>{const t=Ve();t.log("community/leaveCommunity",e);const{data:n}=await t.http.delete(`/api/v3/communities/${e}/leave`);jt("local.community.left",n);const a=mc(n),r=t.cache&&Date.now();t.cache&&Ln(a,{cachedAt:r});const{communityUsers:s}=a;return!!s.find((t=>t.communityId===e&&"member"!==t.communityMembership))},onCommunityCreated:Vu,onCommunityUpdated:Hu,onCommunityDeleted:Ju,searchCommunities:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`searchCommunities(tmpid: ${s}) > listen`);const o=new kh(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`searchCommunities(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getCommunities:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`getCommunities(tmpid: ${s}) > listen`);const o=new Rh(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getCommunities(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getCommunity:(e,t)=>Ui(e,t,"communityId",Qu,[Hu,Ju,hh,ph,fh,mh,sh,ih,oh,Tl(gh,"targetId","community")],{callbackDataSelector:e=>e?dl.community(e):e}),getTrendingCommunities:(e,t,n)=>{const{log:a,cache:r,userId:s}=Ve();r||console.log(pe);const o=Date.now();a(`getTrendingCommunities(tmpid: ${o}) > listen`);const i=new Uh(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>at(l))),()=>{a(`getTrendingCommunities(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}},getRecommendedCommunities:(e,t,n)=>{const{log:a,cache:r,userId:s}=Ve();r||console.log(pe);const o=Date.now();a(`getRecommendedCommunities(tmpid: ${o}) > listen`);const i=new Nh(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>at(l))),()=>{a(`getRecommendedCommunities(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}},semanticSearchCommunities:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`semanticSearchCommunities(tmpid: ${s}) > listen`);const o=new $h(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`semanticSearchCommunities(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getJoinRequestList:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`getJoinRequestList: (tmpid: ${s}) > listen`);const o=new Hh(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{at(c)})),()=>{a(`getJoinRequestList (tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},get AmityCommunityMemberStatusFilter(){return Jh}});const Yh=async e=>{const t=Ve();t.log("category/getCategory",e);const{data:n}=await t.http.get(`/api/v3/community-categories/${encodeURIComponent(e)}`),a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a});const{categories:r}=n;return{data:dl.category((null!=r?r:[]).find((t=>t.categoryId===e))),cachedAt:a}};Yh.locally=e=>{const t=Ve();if(t.log("category/getCategory.locally",e),!t.cache)return;const n=Ze(["category","get",e]);return n?{data:dl.category(n.data),cachedAt:n.cachedAt}:void 0};const Xh=async e=>{const t=Ve();t.log("category/queryCategories",e);const n=null!=e?e:{},{page:a,limit:r,includeDeleted:s}=n,o=Kn(n,["page","limit","includeDeleted"]),i=a?{token:a}:r?{limit:r}:void 0,{data:c}=await t.http.get("/api/v3/community-categories",{params:Object.assign(Object.assign({},o),{isDeleted:oa(s),options:i})}),{paging:l}=c,d=Kn(c,["paging"]),{categories:u}=d,h=t.cache&&Date.now();if(t.cache){Ln(d,{cachedAt:h});const e=["category","query",Object.assign(Object.assign({},o),{includeDeleted:s,options:i})];et(e,{categories:null==u?void 0:u.map(We("category")),paging:l})}return{data:null!=u?u:[],cachedAt:h,paging:l}};Xh.locally=e=>{var t,n;const a=Ve();if(a.log("category/queryCategories.locally",e),!a.cache)return;const r=null!=e?e:{},{page:s,limit:o=10}=r,i=Kn(r,["page","limit"]),c=s?{token:s}:o?{limit:o}:void 0,l=["category","query",Object.assign(Object.assign({},i),{options:c})],{data:d,cachedAt:u}=null!==(t=Ze(l))&&void 0!==t?t:{};if(!(null==d?void 0:d.categories.length))return;const h=d.categories.map((e=>Ze(["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 Zh=Object.freeze({__proto__:null,getCategory:Yh,getCategories:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`getCategories(tmpid: ${s}) > listen`);const{limit:o}=e,i=Kn(e,["limit"]),c=null!=o?o:de,{policy:l=he}=null!=n?n:{},d=[],u=["category","collection",{}],h=(n=!1)=>{var a,r;const s=null===(a=Ze(u))||void 0===a?void 0:a.data,o=null!==(r=null==s?void 0:s.data)&&void 0!==r?r:[];if(!n&&o.length>0&&!(null==s?void 0:s.params.page))return;const d=xe(Xh,Object.assign(Object.assign({},i),{limit:n?c:void 0,page:n||null==s?void 0:s.params.page}));Ne(d,(({data:n,error:a,loading:r,paging:s})=>{const i={loading:r,error:a,params:{page:null==s?void 0:s.next},data:o};n&&(i.data=[...new Set([...o,...n.map(We("category"))])]),et(u,i),(n=>{var a,r;let s=null!==(a=n.data.map((e=>Ze(["category","get",e]))).filter(Boolean).map((({data:e})=>dl.category(e))))&&void 0!==a?a:[];switch(e.includeDeleted||(s=rt(s,"isDeleted",!1)),e.sortBy){case"firstCreated":s=s.sort(yt);break;case"lastCreated":s=s.sort(bt);break;default:s=s.sort(gt)}t({onNextPage:h,data:s,hasNextPage:!!(null===(r=n.params)||void 0===r?void 0:r.page),loading:n.loading,error:n.error})})(i)}),qe(l))};return d.push((()=>{})),h(!0),()=>{a(`getCategories(tmpid: ${s}) > dispose`),d.forEach((e=>e()))}}});const ep=async e=>{const t=Ve();t.log("feed/queryGlobalFeed",e);const n=null!=e?e:{},{queryToken:a,dataTypes:r}=n,s=Kn(n,["queryToken","dataTypes"]),o=(()=>{if(a)return{token:a}})(),{data:i}=await t.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},s),{dataTypes:r,resolveParent:!!(r&&r.length>0)||void 0,options:o})}),{paging:c}=i,l=Kn(i,["paging"]),d=Qn(l,"communityUsers"),{posts:u}=d,{communities:h}=mc(d),p=t.cache&&Date.now();if(t.cache){Ln(Object.assign(Object.assign({},d),{communitis:h}));const e=["globalFeed","query",Object.assign(Object.assign({},s),{options:o})];et(e,{posts:u.map(We("post")),paging:c})}return{data:u.map(dl.post),cachedAt:p,paging:c}};ep.locally=e=>{var t;const n=Ve();if(n.log("post/queryGlobalFeed.locally",e),!n.cache)return;const a=Kn(null!=e?e:{},[]),r=["globalFeed","query",Object.assign({},a)],{data:s,cachedAt:o}=null!==(t=Ze(r))&&void 0!==t?t:{};if(!(null==s?void 0:s.posts.length))return;const i=s.posts.map((e=>Ze(["post","get",e]))).filter(Boolean).map((({data:e})=>e)).map(dl.post),{paging:c}=s;return i.length===s.posts.length?{data:i,cachedAt:o,paging:c}:void 0};class tp extends wi{async getRequest(e,t){const{limit:n}=e,a=Kn(e,["limit"]),r=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v5/me/global-feeds",{params:Object.assign(Object.assign({},a),{options:r})});return s}}var np;!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",e.OnPostPinProduct="onPostPinProduct",e.OnPostUnpinProduct="onPostUnpinProduct",e.OnPostUpdateProductTags="onPostUpdateProductTags"}(np||(np={}));class ap extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.posts.map(We("post"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(We("post"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(a&&(!t.parentPostId||a.data.includes(t.parentPostId))){if(e===np.OnPostDeleted&&(a.data=a.data.filter((e=>e!==t.postId))),e===np.OnPostCreated||e===np.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])]}e===np.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const rp=async e=>{const t=Ve();t.log("comment/getCommentByIds",e);const n=e.map((e=>encodeURIComponent(e)));let a;try{a=(await t.http.get("/api/v3/comments/list",{params:{commentIds:n}})).data}catch(t){throw e.forEach((e=>{Oe(null==t?void 0:t.code)&&Fn("comment",e)})),t}const r=t.cache&&Date.now();return t.cache&&Ln(a,{cachedAt:r}),{data:a.comments.map((e=>dl.comment(e))),cachedAt:r}};rp.locally=e=>{var t;const n=Ve();if(n.log("comment/getCommentByIds.locally",e),!n.cache)return;const a=e.map((e=>Ze(["comment","get",e]))).filter(Boolean),r=a.map((({data:e})=>e)),s=null===(t=a.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==a?void 0:a.length)<e.length?void 0:{data:r.map((e=>dl.comment(e))),cachedAt:s.cachedAt}};const sp=e=>{const t=Ve();if(!t.cache)return;const n=Mn();t.log("comment/createComment.optimistically",Object.assign({commentId:n},e));const a=(new Date).toISOString(),r={commentId:n,userId:t.userId,parentId:e.parentId,rootId:e.parentId||n,childrenNumber:0,children:[],segmentNumber:0,editedAt:a,referenceId:e.referenceId,referenceType:e.referenceType,data:e.data,metadata:e.metadata,mentionees:e.mentionees,attachments:e.attachments,links:e.links,createdAt:a,updatedAt:a,isDeleted:!1,flagCount:0,hashFlag:null,reactions:{},reactionsCount:0,myReactions:[],path:"",targetId:"",targetType:"community",dataType:"text",syncState:"syncing"};return et(["comment","get",r.commentId],r,{cachedAt:-5}),jt("local.comment.created",{comments:[r],commentChildren:[],users:[],files:[],communityUsers:[]}),r},op=(e,t=!1)=>{const{stories:n}=e,a=n.map((e=>((e,t=!1)=>{const{storyId:n,referenceId:a}=e;return!t&&a?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:a})},ip=async e=>{const t=Ve();t.log("story/getStoryByStoryId",e);const n=Ze(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;ta("story",e)}let a;try{const n=await t.http.get(`/api/v4/stories/${e}`);a=op(n.data)}catch(t){throw Oe(null==t?void 0:t.code)&&Fn("story",e),t}const r=t.cache&&Date.now();return t.cache&&Ln(a,{cachedAt:r}),{data:a.stories[0],cachedAt:r}};ip.locally=e=>{const t=Ve();t.log("story/getStorybyStoryId",e);const n=Ze(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;ta("story",e)}const a=t.cache&&Date.now(),r=Ze(["story","get",e]);if(r)return{data:r.data,cachedAt:a}};const cp=async(e,t=!1)=>{var n,a,r;const s=Ve(),o=null===(n=Ze(["comment","get",e]))||void 0===n?void 0:n.data;if("error"===(null==o?void 0:o.syncState)){const t=Object.assign(Object.assign({},o),{isDeleted:!0});return at(["comment","get",e]),jt("local.comment.deleted",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]}),t}const i=await Zl(e);await s.http.delete(`/api/v4/comments/${encodeURIComponent(e)}`,{params:{commentId:e,permanent:t}});const c=Object.assign(Object.assign({},i.data),{isDeleted:!0});if(t?Rt((()=>Fn("comment",e))):nt(["comment","get",e],{isDeleted:!0}),"story"===i.data.referenceType){const e=await ip(i.data.referenceId);jt("local.story.updated",{stories:[e.data],categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[]})}else{const t=null===(a=Ze(["post","get",i.data.referenceId]))||void 0===a?void 0:a.data;if(t){const n=Wl();n.queueCommentChangeTask(new zl(t.postId,e)),!c.parentId&&(null===(r=c.children)||void 0===r?void 0:r.length)>0&&c.children.forEach((e=>{n.queueCommentChangeTask(new zl(t.postId,e))}))}}return jt("local.comment.deleted",{comments:[c],commentChildren:[],files:[],users:[],communityUsers:[]}),c},lp=async e=>{const t=Ve();let n;t.log("comment/getComment",e),ta("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw Oe(null==t?void 0:t.code)&&Fn("comment",e),t}const a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a});const{comments:r}=n;return{data:r.find((t=>t.commentId===e)),cachedAt:a}};lp.locally=e=>{const t=Ve();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=Ze(["comment","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const dp=e=>wd("local.comment.deleted",e),up=e=>{const t=Ve();return Mt(t,"local.comment.addReaction","local.comment.addReaction",(({comment:n})=>{t.cache?(nt(["comment","get",n.commentId],n),e($i(n))):e(n)}))},hp=e=>{const t=Ve();return Mt(t,"local.comment.removeReaction","local.comment.removeReaction",(({comment:n})=>{t.cache?(nt(["comment","get",n.commentId],n),e($i(n))):e(n)}))};class pp extends wi{async getRequest(e,t){var n;const{pageSize:a,limit:r,includeDeleted:s}=e,o=Kn(e,["pageSize","limit","includeDeleted"]),i=null!==(n=null!=a?a:r)&&void 0!==n?n:de,c={type:o.sortBy||e.limit||e.pageSize?"pagination":void 0},l=t?Object.assign(Object.assign({},c),{token:t}):Object.assign(Object.assign({},c),{pageSize:i,limit:i}),{data:d}=await this.http.get("/api/v3/comments",{params:Object.assign(Object.assign({},o),{isDeleted:oa(s),options:l})});return d}}var fp;!function(e){e.OnCommentCreated="onCommentCreated",e.OnCommentUpdated="onCommentUpdated",e.OnCommentDeleted="onCommentDeleted",e.OnCommentFlagged="onCommentFlagged",e.OnCommentUnflagged="onCommentUnflagged",e.OnCommentReactionAdded="onCommentReactionAdded",e.OnCommentReactionRemoved="onCommentReactionRemoved"}(fp||(fp={}));class mp extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.comments.map(We("comment"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.comments.map(We("comment"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;this.query.referenceId===t.referenceId&&this.query.referenceType===t.referenceType&&a&&(this.query.parentId&&this.query.parentId!==t.parentId||!this.query.parentId&&t.parentId||(e===fp.OnCommentCreated&&(a.data=[...new Set([t.commentId,...a.data])]),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const gp=e=>wd("local.comment.created",e);class yp extends ki{constructor(e,t){const n=O.default(e),a=["comments","collection",n];super(new pp(e),n,a,t),this.query=e,this.queryStreamController=new mp(this.query,this.cacheKey,this.notifyChange.bind(this),Ud),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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(){const e=this.queryStreamController.subscribeRTE([{fn:gp,action:fp.OnCommentCreated},{fn:dp,action:fp.OnCommentDeleted},{fn:Id,action:fp.OnCommentCreated},{fn:Cd,action:fp.OnCommentUpdated},{fn:Sd,action:fp.OnCommentDeleted},{fn:Od,action:fp.OnCommentFlagged},{fn:Td,action:fp.OnCommentUnflagged},{fn:kd,action:fp.OnCommentReactionAdded},{fn:Ad,action:fp.OnCommentReactionRemoved},{fn:up,action:fp.OnCommentReactionAdded},{fn:hp,action:fp.OnCommentReactionRemoved}]);if(this.query.excludeBlockUserComments){const t=()=>this.notifyChange({origin:"event",loading:!1});e.push(Js(t),Ws(t))}return e}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["comment","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.comment);(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;if(this.query.includeDeleted||(t=rt(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 a=(null===(t=this.query.dataTypes)||void 0===t?void 0:t.values.sort())||[],r=(null===(n=e.dataTypes)||void 0===n?void 0:n.sort())||[];return r.length===a.length&&a.every(((e,t)=>e===r[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)}))})))),this.query.excludeBlockUserComments&&(t=ft(t)),"firstCreated"===this.query.sortBy)t=t.sort(yt);else t=t.sort(bt);return t}}var vp=Object.freeze({__proto__:null,getCommentByIds:rp,createComment:async e=>{const t=Ve();t.log("comment/createComment",e);const n=sp(e),a=null==n?void 0:n.commentId;try{const{data:n}=await t.http.post("/api/v3/comments",Object.assign(Object.assign({},e),{commentId:a})),{comments:r}=n;if(0===r.length)throw new Error("Comment not created");const s=t.cache&&Date.now();if(t.cache&&Ln(n,{cachedAt:s}),["post","content"].includes(e.referenceType))Wl().queueCommentChangeTask(new Ql(e.referenceId,r[0].commentId,n.comments[0].createdAt));else if("story"===e.referenceType){const t=Ze(["story-reference",e.referenceId]);if(null==t?void 0:t.data){const e=Ze(["story","get",t.data]);(null==e?void 0:e.data)&&jt("story.updated",{stories:[Object.assign(Object.assign({},e.data),{commentsCount:e.data.commentsCount+1,comments:[...new Set([...e.data.comments,r[0].commentId])]})],categories:[],comments:r,communities:[],communityUsers:n.communityUsers,files:n.files,users:n.users})}}return jt("local.comment.created",{comments:[Object.assign(Object.assign({},r[0]),{syncState:"synced"})],commentChildren:n.commentChildren,users:n.users,files:n.files,communityUsers:n.communityUsers}),{data:dl.comment(r[0]),cachedAt:s}}catch(e){throw n&&jt("local.comment.created",{comments:[Object.assign(Object.assign({},n),{syncState:"error"})],commentChildren:[],users:[],files:[],communityUsers:[]}),e}},updateComment:async(e,t)=>{const n=Ve();n.log("user/updateComment",t);const{data:a}=await n.http.put(`/api/v3/comments/${encodeURIComponent(e)}`,t),r=n.cache&&Date.now();n.cache&&Ln(a,{cachedAt:r}),jt("comment.updated",a);const{comments:s}=a;return{data:dl.comment(s.find((t=>t.commentId===e))),cachedAt:r}},deleteComment:cp,softDeleteComment:async e=>{Ve().log("comment/softDeleteComment",e);return cp(e)},hardDeleteComment:async e=>{Ve().log("comment/hardDeleteComment",e);return cp(e,!0)},flagComment:async(t,n)=>{const a=Ve();a.log("comment/flagComment",t);const r=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,a])=>t!==e.ContentFlagReasonEnum.Others&&a===n)),s={reason:n&&r?n:e.ContentFlagReasonEnum.Others,detail:n&&!r?n:""},{data:o}=await a.http.post(`/api/v3/comments/${encodeURIComponent(t)}/flag`,s);return a.cache&&Ln(o),jt("comment.flagged",o),!!o},unflagComment:async e=>{const t=Ve();t.log("comment/unflagComment",e);const{data:n}=await t.http.delete(`/api/v3/comments/${encodeURIComponent(e)}/unflag`);return t.cache&&Ln(n),jt("comment.unflagged",n),!!n},isCommentFlaggedByMe:async e=>{const t=Ve();t.log("comment/isCommentFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/comments/${e}/isflagbyme`);return n},onCommentCreated:Id,onCommentUpdated:Cd,onCommentDeleted:Sd,onCommentFlagged:Od,onCommentUnflagged:Td,onCommentReactionAdded:kd,onCommentReactionRemoved:Ad,getComment:(e,t)=>Ui(e,t,"commentId",lp,[dp,Sd,Od,kd,Ad,Td,Cd,up,hp]),getComments:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log("For using Live Collection feature you need to enable Cache!");const s=Date.now();a(`getComments(tmpid: ${s}) > listen`);const o=new yp(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getComments(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}}});const bp=e=>ld("local.post.deleted",e),wp=e=>{const t=Ve();return Mt(t,"local.post.addReaction","local.post.addReaction",(({post:n})=>{t.cache?(nt(["post","get",n.postId],n),e(n)):e(n)}))},Ip=e=>{const t=Ve();return Mt(t,"local.post.removeReaction","local.post.removeReaction",(({post:n})=>{t.cache?(nt(["post","get",n.postId],n),e(n)):e(n)}))},Cp=e=>ld("local.post.updated",e),Sp=e=>[Id,Sd,gp,dp].map((t=>({fn:Tl((n=>((e,t,n)=>t((async t=>{var a;const r=null===(a=Ze(n))||void 0===a?void 0:a.data;r&&r.data.includes(t.referenceId)&&e(t)})))(n,t,e)),"referenceId","post"),action:np.OnPostUpdated}))),Op=e=>[{fn:dd,action:np.OnPostCreated},{fn:ud,action:np.OnPostUpdated},{fn:Cp,action:np.OnPostUpdated},{fn:hd,action:np.OnPostDeleted},{fn:md,action:np.OnPostFlagged},{fn:gd,action:np.OnPostUnflagged},{fn:pd,action:np.OnPostApproved},{fn:fd,action:np.OnPostDeclined},{fn:yd,action:np.OnPostReactionAdded},{fn:vd,action:np.OnPostReactionRemoved},{fn:wp,action:np.OnPostReactionAdded},{fn:Ip,action:np.OnPostReactionRemoved},{fn:bp,action:np.OnPostDeleted},...Sp(e)];class Tp extends ki{constructor(e,t){const n=O.default(e),a=["customRankingGlobalFeed","collection",n];super(new tp(e),n,a,t),this.query=e,this.queryStreamController=new ap(this.query,this.cacheKey,this.notifyChange.bind(this),Gl),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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(Op(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=(null!==(r=s.data.map((e=>Ze(["post","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.post);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class kp extends wi{async getRequest(e,t){const{limit:n,dataTypes:a}=e,r=Kn(e,["limit","dataTypes"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},r),{dataTypes:a,resolveParent:!!(a&&a.length>0)||void 0,options:s})});return o}}class Ap extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.posts.map(We("post"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(We("post"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(a&&(!t.parentPostId||a.data.includes(t.parentPostId))){if(e===np.OnPostDeleted&&(a.data=a.data.filter((e=>e!==t.postId))),e===np.OnPostCreated||e===np.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])]}e===np.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class _p extends ki{constructor(e,t){const n=O.default(e),a=["globalFeed","collection",n];super(new kp(e),n,a,t),this.query=e,this.queryStreamController=new Ap(this.query,this.cacheKey,this.notifyChange.bind(this),Gl),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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(Op(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=(null!==(r=s.data.map((e=>Ze(["post","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.post);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class Ep extends wi{async getRequest(e,t){const{userId:n,feedSources:a,dataTypes:r,includeDeleted:s,matchingOnlyParentPost:o,limit:i=de,untilAt:c}=e,l=Kn(e,["userId","feedSources","dataTypes","includeDeleted","matchingOnlyParentPost","limit","untilAt"]),d=t?{token:t}:{limit:i},{data:u}=await this.http.get(`/api/v4/user-feeds/${n}`,{params:Object.assign(Object.assign({},l),{options:d,dataTypes:(null==r?void 0:r.length)?r:void 0,includePostedFeed:a,isDeleted:oa(s),matchingOnlyParentPost:null!=o?o:!(null==r?void 0:r.length)})});return u}}class Rp extends Ci{constructor(e,t,n,a){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=a,this.validatedUntilAt=e.untilAt?St(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;let s=e.posts;if(n&&(this.boundaryReached=!1),void 0!==this.validatedUntilAt){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated",t=s.filter((t=>!Ot(t.createdAt,this.validatedUntilAt,e)));t.length<s.length&&(this.boundaryReached=!0),s=t}if(n)et(this.cacheKey,{data:s.map(We("post"))});else{const e=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,t=null!==(r=null==e?void 0:e.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...s.map(We("post"))])]}))}}reactor(e){return t=>{var n,a;const r=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(r&&(this.query.dataTypes&&0!==this.query.dataTypes.length||r.data.includes(t.parentPostId?t.parentPostId:t.postId))){if(void 0!==this.validatedUntilAt&&(e===np.OnPostCreated||e===np.OnPostApproved||e===np.OnPostUpdated)){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";if(Ot(t.createdAt,this.validatedUntilAt,e))return}if(e===np.OnPostDeleted&&(r.data=r.data.filter((e=>e!==t.postId))),t.parentPostId&&t.isDeleted){const e=null===(a=Ze(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),et(["post","get",e.postId],e)}if(e===np.OnPostDeclined&&(r.data=r.data.filter((e=>e!==t.postId))),e===np.OnPostCreated||e===np.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])]}et(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}hasBoundaryReached(){return this.boundaryReached}}const Pp=async e=>{const t=Ve();let n;t.log("post/getPost",e),ta("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw Oe(null==t?void 0:t.code)&&Fn("post",e),t}const a=Qn(n,"communityUsers"),r=t.cache&&Date.now();t.cache&&Ln(a,{cachedAt:r});const{posts:s}=a;return{data:s.find((t=>t.postId===e)),cachedAt:r}};Pp.locally=e=>{const t=Ve();if(t.log("post/getPost.locally",e),!t.cache)return;const n=Ze(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class Mp extends ki{constructor(e,t){const n=O.default(e),a=["userFeed","collection",n];super(new Ep(e),n,a,t),this.query=e,this.queryStreamController=new Rp(this.query,this.cacheKey,this.notifyChange.bind(this),Gl),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:dd,action:np.OnPostCreated},{fn:ud,action:np.OnPostUpdated},{fn:Cp,action:np.OnPostUpdated},{fn:hd,action:np.OnPostDeleted},{fn:md,action:np.OnPostFlagged},{fn:gd,action:np.OnPostUnflagged},{fn:pd,action:np.OnPostApproved},{fn:fd,action:np.OnPostDeclined},{fn:yd,action:np.OnPostReactionAdded},{fn:vd,action:np.OnPostReactionRemoved},{fn:wp,action:np.OnPostReactionAdded},{fn:Ip,action:np.OnPostReactionRemoved},{fn:bp,action:np.OnPostDeleted},{fn:Tl((e=>Id((async t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await Pp(t.referenceId),e(t))}))),"referenceId","post"),action:np.OnPostUpdated},{fn:Tl((e=>Sd((async t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await Pp(t.referenceId),e(t))}))),"referenceId","post"),action:np.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=null!==(r=s.data.map((e=>Ze(["post","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[],i=this.applyFilter(o).map(dl.post);if(!this.shouldNotify(i)&&"event"===e)return;const c=!this.queryStreamController.hasBoundaryReached()&&!!this.paginationController.getNextToken();this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:c,loading:t,error:n})}applyFilter(e){var t;let n=e;if(this.query.includeDeleted||(n=rt(n,"isDeleted",!1)),(null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=dt(n,this.query.dataTypes)),this.query.untilAt){const e=St(this.query.untilAt),t="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";n=n.filter((n=>!Ot(n.createdAt,e,t)))}if("firstCreated"===this.query.sortBy)n=n.sort(yt);else n=n.sort(bt);return n}}class jp extends wi{async getRequest(e,t){const{limit:n=de,includeDeleted:a,communityId:r,untilAt:s}=e,o=Kn(e,["limit","includeDeleted","communityId","untilAt"]),i=t?{token:t}:{limit:n},{data:c}=await this.http.get("/api/v5/posts",{params:Object.assign(Object.assign({},o),{targetId:r,targetType:"community",isDeleted:oa(a),matchingOnlyParentPost:!0,options:i})});return c}}class Up extends Ci{constructor(e,t,n,a){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=a,this.validatedUntilAt=e.untilAt?St(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;let s=e.posts;if(n&&(this.boundaryReached=!1),void 0!==this.validatedUntilAt&&"firstUpdated"!==this.query.sortBy&&"lastUpdated"!==this.query.sortBy){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated",t=s.filter((t=>!Ot(t.createdAt,this.validatedUntilAt,e)));t.length<s.length&&(this.boundaryReached=!0),s=t}if(n)et(this.cacheKey,{data:s.map(We("post"))});else{const e=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,t=null!==(r=null==e?void 0:e.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...s.map(We("post"))])]}))}}reactor(e){return t=>{var n,a;const r=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(void 0!==this.validatedUntilAt&&(e===np.OnPostCreated||e===np.OnPostApproved)&&"firstUpdated"!==this.query.sortBy&&"lastUpdated"!==this.query.sortBy){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";if(Ot(t.createdAt,this.validatedUntilAt,e))return}if(e===np.OnPostDeleted&&(r.data=r.data.filter((e=>e!==t.postId))),t.parentPostId&&t.isDeleted){const e=null===(a=Ze(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),et(["post","get",e.postId],e)}e===np.OnPostDeclined&&(r.data=r.data.filter((e=>e!==t.postId))),e!==np.OnPostCreated&&e!==np.OnPostApproved||(r.data=[...new Set([t.postId,...r.data])]),et(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}hasBoundaryReached(){return this.boundaryReached}}const Dp=({cacheKey:e,resolveId:t})=>[Id,Sd,gp,dp].map((n=>({fn:Tl((a=>((e,t,n,a)=>t((async t=>{var r;const s=null===(r=Ze(n))||void 0===r?void 0:r.data;s&&s.data.includes(a?a(t.referenceId):t.referenceId)&&e(t)})))(a,n,e,t)),"referenceId","post"),action:np.OnPostUpdated}))),xp=e=>[{fn:dd,action:np.OnPostCreated},{fn:ud,action:np.OnPostUpdated},{fn:Cp,action:np.OnPostUpdated},{fn:hd,action:np.OnPostDeleted},{fn:md,action:np.OnPostFlagged},{fn:gd,action:np.OnPostUnflagged},{fn:pd,action:np.OnPostApproved},{fn:fd,action:np.OnPostDeclined},{fn:yd,action:np.OnPostReactionAdded},{fn:vd,action:np.OnPostReactionRemoved},{fn:wp,action:np.OnPostReactionAdded},{fn:Ip,action:np.OnPostReactionRemoved},{fn:bp,action:np.OnPostDeleted},...Dp({cacheKey:e})],qp=(e,t)=>{var n;return null!==(n=e.map((e=>{const n=t.find((t=>t.postId===e.referenceId));return n?We("post")({postId:null==n?void 0:n.postId}):void 0})).filter(Ai))&&void 0!==n?n:[]};class Np extends ki{constructor(e,t){const n=O.default(e),a=["communityFeed","collection",n];super(new jp(e),n,a,t),this.query=e,this.queryStreamController=new Up(this.query,this.cacheKey,this.notifyChange.bind(this),Gl),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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(xp(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["post","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.post);if(!this.shouldNotify(o)&&"event"===e)return;const i=!this.queryStreamController.hasBoundaryReached()&&!!this.paginationController.getNextToken();this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:i,loading:t,error:n})}applyFilter(e){let t=e;if(this.query.includeDeleted||(t=rt(t,"isDeleted",!1)),this.query.tags&&(t=t.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.untilAt&&"firstUpdated"!==this.query.sortBy&&"lastUpdated"!==this.query.sortBy){const e=St(this.query.untilAt),n="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";t=t.filter((t=>!Ot(t.createdAt,e,n)))}switch(this.query.sortBy){case"firstCreated":t=t.sort(yt);break;case"firstUpdated":t=t.sort(wt);break;case"lastUpdated":t=t.sort(It);break;default:t=t.sort(bt)}return t}}class Bp extends Fe{constructor(e="For You feed is not enabled for this network"){super(e,400400,"error"),this.type="AmityForYouFeedDisabledError"}}class Lp extends wi{constructor(e){super(e),this.checkedDisk=!1,this.hasDeliveredPost=!1,this.cursor=Gs.current()}async getRequest(e,t){var n,a,r,s,o;const i=void 0===t;let c=null;if(i&&!this.checkedDisk&&this.cursor&&(this.checkedDisk=!0,c=await this.cursor.get(),c&&Gs.isExpired(c.expiredAt)&&(await this.cursor.clear(),c=null)),i&&(null==c?void 0:c.reachedEndOfFeed)){const e=await this.fetch(),t=Date.parse(null!==(a=null===(n=e.paging)||void 0===n?void 0:n.expiredAt)&&void 0!==a?a:"");return!Number.isNaN(t)&&t!==c.expiredAt?(await this.persistCursor(e),e.posts.length>0&&(this.hasDeliveredPost=!0),e):Object.assign(Object.assign({},e),{posts:[],paging:{}})}const l=i&&c?c.cursor:t,d=await this.fetch(l);if(d.posts.length>0&&(this.hasDeliveredPost=!0),null===(r=d.paging)||void 0===r?void 0:r.next)await this.persistCursor(d);else if(this.hasDeliveredPost&&this.cursor){const e=Date.parse(null!==(o=null===(s=d.paging)||void 0===s?void 0:s.expiredAt)&&void 0!==o?o:"");Number.isNaN(e)||await this.cursor.markReachedEndOfFeed(e)}return d}async fetch(e){const t={limit:ue};e&&(t.token=e);try{const{data:e}=await this.http.get(ve,{params:{options:t}});return e}catch(t){if(t instanceof Fe&&400300===t.code)throw new Bp;if(t instanceof Fe&&400322===t.code&&void 0!==e){this.cursor&&await this.cursor.clear();const{data:e}=await this.http.get(ve,{params:{options:{limit:ue}}});return e}throw t}}async persistCursor(e){var t,n;if(!this.cursor)return;const a=null===(t=e.paging)||void 0===t?void 0:t.next,r=null===(n=e.paging)||void 0===n?void 0:n.expiredAt;if(!a||!r)return;const s=Date.parse(r);Number.isNaN(s)||await this.cursor.set({cursor:a,expiredAt:s})}}class Fp extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.posts.map(We("post"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(We("post"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;a&&(t.parentPostId&&!a.data.includes(t.parentPostId)||(e!==np.OnPostDeleted&&e!==np.OnPostDeclined||(a.data=a.data.filter((e=>e!==t.postId))),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Kp=["forYouFeed","collection"];class $p extends ki{constructor(e){const t=`for-you-feed-${Ve().userId}`,n={};super(new Lp(n),t,Kp,e),this.queryStreamController=new Fp(n,this.cacheKey,this.notifyChange.bind(this),Gl),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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(Op(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=(null!==(r=s.data.map((e=>Ze(["post","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.post);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var Qp=Object.freeze({__proto__:null,queryGlobalFeed:ep,getCustomRankingGlobalFeed:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`getCustomRankingGlobalFeed(tmpid: ${s}) > listen`);const o=new Tp(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getCustomRankingGlobalFeed(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getGlobalFeed:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`getGlobalFeed(tmpid: ${s}) > listen`);const o=new _p(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getGlobalFeed(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getUserFeed:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`getUserFeed(tmpid: ${s}) > listen`);const o=new Mp(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getUserFeed(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getCommunityFeed:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`getCommunityFeed(tmpid: ${s}) > listen`);const o=new Np(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getCommunityFeed(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getForYouFeed:e=>{const{log:t,cache:n}=Ve();n||console.log(pe);const a=Date.now();t(`getForYouFeed(tmpid: ${a}) > listen`);const r=new $p(e),s=r.startSubscription(),o=r.getCacheKey();return s.push((()=>at(o))),()=>{t(`getForYouFeed(tmpid: ${a}) > dispose`),s.forEach((e=>e()))}},AmityForYouFeedDisabledError:Bp});const zp=async e=>{const t=Ve();t.log("post/getPostByIds",e);const n=e.map((e=>encodeURIComponent(e)));let a;try{a=(await t.http.get("/api/v3/posts/list",{params:{postIds:n}})).data}catch(t){throw e.forEach((e=>{Oe(null==t?void 0:t.code)&&Fn("post",e)})),t}const r=Qn(a,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Ln(r,{cachedAt:s}),{data:r.posts.map(dl.post),cachedAt:s}};zp.locally=e=>{var t;const n=Ve();if(n.log("post/getPostByIds.locally",e),!n.cache)return;const a=e.map((e=>Ze(["post","get",e]))).filter(Boolean),r=a.map((({data:e})=>e)),s=null===(t=a.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==a?void 0:a.length)<e.length?void 0:{data:r.map(dl.post),cachedAt:s.cachedAt}};const Vp=async(e,t=!1)=>{var n;const a=Ve(),r=await Xl(e);if(await a.http.delete(`/api/v4/posts/${encodeURIComponent(e)}`,{params:{postId:e,permanent:t}}),"community"===r.data.targetType){const e=await Qu(r.data.targetId),t=(null!==(n=Xe(["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));jt("community.updated",{communities:[e.data],categories:[],communityUsers:t,feeds:[],files:[],users:[]})}const s=Object.assign(Object.assign({},r.data),{isDeleted:!0});return t?setTimeout((()=>{Fn("post",e)}),0):nt(["post","get",e],{isDeleted:!0}),jt("local.post.deleted",{posts:[s],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[],videoStreamings:[]}),dl.post(s)};class Hp extends wi{async getRequest(e,t){const{limit:n=de,includeDeleted:a,matchingOnlyParentPost:r,untilAt:s}=e,o=Kn(e,["limit","includeDeleted","matchingOnlyParentPost","untilAt"]),{dataTypes:i}=o,c={type:o.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/v5/posts",{params:Object.assign(Object.assign({},o),{isDeleted:oa(a),matchingOnlyParentPost:null!=r?r:!(null==i?void 0:i.length),options:l})});return d}}class Jp extends Ci{constructor(e,t,n,a){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=a,this.validatedUntilAt=e.untilAt?St(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;let s=e.posts;if(n&&(this.boundaryReached=!1),void 0!==this.validatedUntilAt){const e=this.query.sortBy||"lastCreated",t=s.filter((t=>!Ot(t.createdAt,this.validatedUntilAt,e)));t.length<s.length&&(this.boundaryReached=!0),s=t}if(n)et(this.cacheKey,{data:s.map(We("post"))});else{const e=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,t=null!==(r=null==e?void 0:e.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...s.map(We("post"))])]}))}}reactor(e){return t=>{var n,a;const r=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(void 0!==this.validatedUntilAt&&(e===np.OnPostCreated||e===np.OnPostApproved)){const e=this.query.sortBy||"lastCreated";if(Ot(t.createdAt,this.validatedUntilAt,e))return}if(t.parentPostId&&t.isDeleted){const e=null===(a=Ze(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e||(null==e?void 0:e.targetId)!==this.query.targetId)return;e.children=e.children.filter((e=>e!==t.postId)),et(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===np.OnPostDeclined&&(r.data=r.data.filter((e=>e!==t.postId))),e!==np.OnPostCreated&&e!==np.OnPostApproved||(r.data=[...new Set([t.postId,...r.data])]),et(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}hasBoundaryReached(){return this.boundaryReached}}class Wp extends ki{constructor(e,t){const n=O.default(e),a=["posts","collection",n];super(new Hp(e),n,a,t),this.query=e,this.queryStreamController=new Jp(this.query,this.cacheKey,this.notifyChange.bind(this),Gl),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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(){const e=this.queryStreamController.subscribeRTE(xp(this.cacheKey));if(this.query.excludeBlockUserPosts){const t=()=>this.notifyChange({origin:"event",loading:!1});e.push(Js(t),Ws(t))}return e}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["post","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.post);if(!this.shouldNotify(o)&&"event"===e)return;const i=!this.queryStreamController.hasBoundaryReached()&&!!this.paginationController.getNextToken();this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:i,loading:t,error:n})}applyFilter(e){var t;let n=e;if(this.query.includeDeleted||(n=rt(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=ct(n,this.query.feedType)),(null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=dt(n,this.query.dataTypes)),this.query.untilAt){const e=St(this.query.untilAt),t=this.query.sortBy||"lastCreated";n=n.filter((n=>!Ot(n.createdAt,e,t)))}if(this.query.excludeBlockUserPosts&&(n=pt(n)),"firstCreated"===this.query.sortBy)n=n.sort(yt);else n=n.sort(bt);return n}}class Gp extends wi{async getRequest(e,t){const n=Kn(e,["limit"]),{communityId:a,placement:r}=n,s=Kn(n,["communityId","placement"]),o=r?`/api/v1/pinned-posts/communities/${a}/${r}`:`/api/v1/pinned-posts/communities/${a}`,{data:i}=await this.http.get(o,{params:Object.assign({},s)});return i}}class Yp extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=Ve(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users?e.users.map(ga):[]});Ln(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.pins.map(We("pin"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(We("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===np.OnPostDeleted&&(a.data=a.data.filter((e=>e!==`global#${t.postId}`))),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Xp extends ki{constructor(e,t){const n=O.default(e),a=["pinnedPosts","collection",n];super(new Gp(e),n,a,t),this.query=e,this.queryStreamController=new Yp(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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(Dp({cacheKey:this.cacheKey,resolveId:e=>`${this.query.placement}#${e}`}))}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;let o=(null!==(r=s.data.map((e=>Ze(["pin","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.pinnedPost);o=this.applyFilter(o),(this.shouldNotify(o)||"event"!==e)&&this.callback({data:o,loading:t,error:n})}applyFilter(e){let t=e;if("lastCreated"===this.query.sortBy)t=t.sort((({post:e},{post:t})=>bt({createdAt:null==e?void 0:e.createdAt},{createdAt:null==t?void 0:t.createdAt})));return t}}class Zp extends wi{async getRequest(e,t){const n=Kn(e,["limit"]),{data:a}=await this.http.get("/api/v1/pinned-posts/global",{params:Object.assign({},n)});return a}}class ef extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=Ve(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users.map(ga)});Ln(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.pins.map(We("pin"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(We("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===np.OnPostDeleted&&(a.data=a.data.filter((e=>e!==`global#${t.postId}`))),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class tf extends ki{constructor(e,t){const n=O.default(e),a=["pinnedPosts","collection",n];super(new Zp(e),n,a,t),this.query=e,this.queryStreamController=new ef(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:bp,action:np.OnPostDeleted},{fn:hd,action:np.OnPostDeleted},...Dp({cacheKey:this.cacheKey,resolveId:e=>`global#${e}`})])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=(null!==(r=s.data.map((e=>Ze(["pin","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.pinnedPost);(this.shouldNotify(o)||"event"!==e)&&this.callback({data:o,loading:t,error:n})}}class nf extends wi{async getRequest(e,t){const{limit:n=de}=e,a=Kn(e,["limit"]),r={type:e.limit?"pagination":void 0},s=t?Object.assign(Object.assign({},r),{token:t}):Object.assign(Object.assign({},r),{limit:n}),{data:o}=await this.http.get("/api/v1/semantic-search/posts",{params:Object.assign(Object.assign({},a),{options:s})});return o}}function af(e){return e.posts.map((t=>{const n=e.searchResult.find((e=>e.postId===t.postId));return`${t.postId}:${n.score}`}))}function rf(e){return(null!=e?e:[]).map((e=>e.split(":")[0]))}class sf extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:af(e)});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...af(e)])]}))}}reactor(e){return t=>{var n,a;const r=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(t.parentPostId&&t.isDeleted){const e=null===(a=Ze(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e||(null==e?void 0:e.targetId)!==this.query.targetId)return;e.children=e.children.filter((e=>e!==t.postId)),et(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===np.OnPostDeclined&&(r.data=r.data.filter((e=>e!==t.postId))),e!==np.OnPostCreated&&e!==np.OnPostApproved||(r.data=[...new Set([t.postId,...r.data])]),et(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class of extends ki{constructor(e,t){const n=Object.assign(Object.assign({},e),{matchingOnlyParentPost:null==e.matchingOnlyParentPost||e.matchingOnlyParentPost,dataTypes:null==e.dataTypes?["text","image"]:e.dataTypes}),a=O.default(n),r=["posts","collection",a];super(new nf(n),a,r,t),this.query=n,this.queryStreamController=new sf(this.query,this.cacheKey,this.notifyChange.bind(this),Yl),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:ud,action:np.OnPostUpdated},{fn:hd,action:np.OnPostDeleted},{fn:md,action:np.OnPostFlagged},{fn:gd,action:np.OnPostUnflagged},{fn:pd,action:np.OnPostApproved},{fn:fd,action:np.OnPostDeclined},{fn:yd,action:np.OnPostReactionAdded},{fn:vd,action:np.OnPostReactionRemoved},{fn:Tl((e=>Id((async t=>{const n=Ze(this.cacheKey);rf(null==n?void 0:n.data).includes(t.referenceId)||(await Xl(t.referenceId),e(t))}))),"referenceId","post"),action:np.OnPostUpdated},{fn:Tl((e=>Sd((async t=>{const n=Ze(this.cacheKey);rf(null==n?void 0:n.data).includes(t.referenceId)||(await Xl(t.referenceId),e(t))}))),"referenceId","post"),action:np.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>{const[t,n]=e.split(":");return{postId:t,score:parseFloat(n)}})).sort(((e,t)=>t.score-e.score)).map((({postId:e})=>Ze(["post","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.post);(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;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=dt(t,this.query.dataTypes)),t}}class cf extends wi{async getRequest(e,t){const{limit:n=de,matchingOnlyParentPost:a,hashtags:r,dataTypes:s,targetType:o="all"}=e,i=Kn(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:r,dataTypes:s,targetType:o,matchingOnlyParentPost:null!=a?a:!(null==s?void 0:s.length),options:l})});return d}}class lf extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.posts.map(We("post"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(We("post"))])]}))}}reactor(e){return t=>{var n,a;const r=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(t.parentPostId&&t.isDeleted){const e=null===(a=Ze(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),et(["post","get",e.postId],e)}e===np.OnPostDeclined&&(r.data=r.data.filter((e=>e!==t.postId))),e!==np.OnPostCreated&&e!==np.OnPostApproved||(r.data=[...new Set([t.postId,...r.data])]),et(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class df extends ki{constructor(e,t){const n=O.default(e),a=["posts","collection",n];super(new cf(e),n,a,t),this.query=e,this.queryStreamController=new lf(this.query,this.cacheKey,this.notifyChange.bind(this),Gl),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:dd,action:np.OnPostCreated},{fn:ud,action:np.OnPostUpdated},{fn:Cp,action:np.OnPostUpdated},{fn:hd,action:np.OnPostDeleted},{fn:md,action:np.OnPostFlagged},{fn:gd,action:np.OnPostUnflagged},{fn:pd,action:np.OnPostApproved},{fn:fd,action:np.OnPostDeclined},{fn:yd,action:np.OnPostReactionAdded},{fn:vd,action:np.OnPostReactionRemoved},{fn:wp,action:np.OnPostReactionAdded},{fn:Ip,action:np.OnPostReactionRemoved},{fn:bp,action:np.OnPostDeleted},{fn:Tl((e=>Id((async t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await Pp(t.referenceId),e(t))}))),"referenceId","post"),action:np.OnPostUpdated},{fn:Tl((e=>Sd((async t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await Pp(t.referenceId),e(t))}))),"referenceId","post"),action:np.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["post","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.post);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,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=dt(n,this.query.dataTypes)),"firstCreated"===this.query.sortBy)n=n.sort(yt);else n=n.sort(bt);return n}}class uf extends Ti{async getRequest(e){const{limit:t=100}=e,{data:n}=await this.http.get("/api/v1/rooms/lives",{params:{targetTypes:["all"],options:{limit:t,sortBy:"lastCreated"}}});return n}}class hf extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:qp(e.rooms,e.posts)});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...qp(e.rooms,e.posts)])]}))}}reactor(e){return e=>{var t;const n=null===(t=Ze(this.cacheKey))||void 0===t?void 0:t.data;n&&("ended"===e.status&&et(this.cacheKey,Object.assign(Object.assign({},n),{data:n.data.filter((t=>e.referenceId!==t))})),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const pf=e=>{const t=Ve();return Mt(t,"room/onRoomStartBroadcasting","room.startBroadcasting",(t=>{Ln(t),e(t.rooms[0])}))},ff=e=>{const t=Ve();return Mt(t,"room/onRoomWaitingReconnect","room.waitingReconnect",(t=>{Ln(t),e(t.rooms[0])}))},mf=e=>{const t=Ve();return Mt(t,"room/onRoomEndBroadcasting","room.endBroadcasting",(t=>{Ln(t),e(t.rooms[0])}))},gf=e=>{const t=Ve();return Mt(t,"room/onRoomRecordedAvailable","room.recordedAvailable",(t=>{Ln(t),e(t.rooms[0])}))},yf=e=>{const t=Ve();return Mt(t,"room/onRoomCoHostInvited","room.didCohostInvite",(t=>{const n=Wi(t);Ln(n),e(n.invitations)}))},vf=async e=>{const t=Ve();let n;t.log("room/getRoomById",e),ta("room",e);try{n=(await t.http.get(`/api/v1/rooms/${e}`)).data}catch(t){throw Oe(null==t?void 0:t.code)&&Fn("room",e),t}const a=t.cache&&Date.now();return t.cache&&Ln(n,{cachedAt:a}),{data:n.rooms[0],cachedAt:a}};vf.locally=e=>{const t=Ve();t.log("room/getRoomById.locally",e),ta("room",e);const n=t.cache&&Date.now(),a=Ze(["room","get",e]);if(a)return{data:a.data,cachedAt:n}};const bf=e=>{const t=Ve();return Mt(t,"room/onRoomCoHostInviteAccepted","room.didCohostInviteAccept",(async t=>{var n;const a=Wi(t);await vf(null===(n=a.invitations)||void 0===n?void 0:n[0].targetId),Ln(a),e(a.invitations[0])}))},wf=e=>{const t=Ve();return Mt(t,"room/onRoomCoHostInviteRejected","room.didCohostInviteReject",(t=>{const n=Wi(t);Ln(n),e(n.invitations)}))},If=e=>{const t=Ve();return Mt(t,"room/onRoomCoHostInviteCanceled","room.didCohostInviteCancel",(t=>{const n=Wi(t);Ln(n),e(n.invitations)}))},Cf=e=>{const t=Ve();return Mt(t,"room/onRoomParticipantJoined","room.participantJoined",(t=>{const{rooms:n,users:a}=t;Ln({rooms:n,users:a}),e({room:dc(n[0]),actorInternalId:t.eventActor.userInternalId})}))},Sf=e=>{const t=Ve();return Mt(t,"room/onRoomParticipantLeft","room.participantLeft",(t=>{const{rooms:n,users:a}=t;Ln({rooms:n,users:a}),e({room:dc(n[0]),actorInternalId:t.eventActor.userInternalId})}))},Of=e=>{const t=Ve();return Mt(t,"room/onRoomParticipantStageJoined","room.participantStageJoined",(t=>{const{rooms:n,users:a}=t;Ln({rooms:n,users:a}),e({room:dc(n[0]),actorInternalId:t.eventActor.userInternalId})}))},Tf=e=>{const t=Ve();return Mt(t,"room/onRoomTerminated","room.terminated",(t=>{Ln(t),e(t.rooms[0])}))},kf=e=>{const t=Ve();return Mt(t,"room/onRoomDidUpdate","local.room.didUpdate",(t=>{Ln(t),e(t.rooms[0])}))},Af=e=>{const t=Ve();return Mt(t,"room/onRoomParticipantRemoved","room.participantRemoved",(t=>{const{rooms:n,users:a}=t;Ln({rooms:n,users:a}),e({room:dc(n[0]),actorInternalId:t.eventActor.userInternalId})}))},_f=e=>{const t=Ve();return Mt(t,"room/onLocalRoomDidUpdate","room.didUpdate",(t=>{Ln(t),e(t.rooms[0])}))},Ef=e=>{const t=Ve();return Mt(t,"room/onRoomParticipantRemoved","local.room.participantRemoved",(t=>{Ln(t),e(t.rooms[0])}))};var Rf;!function(e){e.OnRoomCreated="OnRoomCreated",e.OnRoomUpdated="OnRoomUpdated",e.OnRoomDeleted="OnRoomDeleted",e.OnRoomStartBroadcasting="OnRoomStartBroadcasting",e.OnRoomEndBroadcasting="OnRoomEndBroadcasting",e.OnRoomParticipantJoined="OnRoomParticipantJoined",e.OnRoomParticipantLeft="OnRoomParticipantLeft",e.OnRoomDidUpdate="OnRoomDidUpdate"}(Rf||(Rf={}));const Pf=e=>t=>e((e=>{t(e.room)}));class Mf extends wi{async getRequest(e,t){const{limit:n=de,includeDeleted:a}=e,r=Kn(e,["limit","includeDeleted"]),s={type:r.sortBy||e.limit?"pagination":void 0},o=t?Object.assign(Object.assign({},s),{token:t}):Object.assign(Object.assign({},s),{limit:n}),{data:i}=await this.http.get("/api/v1/rooms",{params:Object.assign(Object.assign({},r),{isDeleted:oa(a),options:o})});return i}}class jf extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.rooms.map(We("room"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.rooms.map(We("room"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===Rf.OnRoomDeleted&&(a.data=a.data.filter((e=>e!==t._id))),e===Rf.OnRoomCreated&&(a.data=[...new Set([t._id,...a.data])]),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Uf extends ki{constructor(e,t){const n=O.default(e),a=["rooms","collection",n];super(new Mf(e),n,a,t),this.query=e,this.queryStreamController=new jf(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:pf,action:Rf.OnRoomStartBroadcasting},{fn:mf,action:Rf.OnRoomEndBroadcasting},{fn:gf,action:Rf.OnRoomUpdated},{fn:ff,action:Rf.OnRoomUpdated},{fn:Tf,action:Rf.OnRoomUpdated},{fn:Pf(Cf),action:Rf.OnRoomUpdated},{fn:Pf(Sf),action:Rf.OnRoomUpdated},{fn:Pf(Af),action:Rf.OnRoomUpdated},{fn:Ef,action:Rf.OnRoomUpdated},{fn:Pf(Of),action:Rf.OnRoomUpdated},{fn:Tl(bf,"targetId","room"),action:Rf.OnRoomUpdated},{fn:kf,action:Rf.OnRoomDidUpdate},{fn:_f,action:Rf.OnRoomDidUpdate}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["room","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dc);(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;if(this.query.includeDeleted||(t=rt(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=rt(t,"type",this.query.type)),"firstCreated"===this.query.sortBy)t=t.sort(yt);else t=t.sort(bt);return t}}var Df=Object.freeze({__proto__:null,createRoom:async e=>{const t=Ve();t.log("room/createRoom",e);const{data:n}=await t.http.post("/api/v1/rooms",e);jt("local.room.created",n);const a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a});const{rooms:r}=n;return{data:dc(r[0]),cachedAt:a}},updateRoom:async(e,t)=>{const n=Ve();n.log("room/updateRoom",{roomId:e,bundle:t});const{data:a}=await n.http.put(`/api/v1/rooms/${e}`,t);jt("local.room.updated",a);const r=n.cache&&Date.now();n.cache&&Ln(a,{cachedAt:r});const{rooms:s}=a;return{data:dc(s[0]),cachedAt:r}},deleteRoom:async e=>{const t=Ve();t.log("room/deleteRoom",{roomId:e}),await t.http.delete(`/api/v1/rooms/${e}`),jt("local.room.deleted",{rooms:[{_id:e}]})},stopRoom:async e=>{const t=Ve();t.log("room/stopRoom",{roomId:e});const{data:n}=await t.http.post(`/api/v1/rooms/${e}/stop`);jt("local.room.stopped",n);const a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a});const{rooms:r}=n;return{data:r[0],cachedAt:a}},getBroadcasterData:async e=>{const t=Ve();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=Ve();t.log("room/getRecordedUrl",{roomId:e});const{data:n}=await t.http.get(`/api/v1/rooms/${e}/recorded`);return n},removeParticipant:async(e,t)=>{const n=Ve();n.log("room/removeParticipant",{roomId:e,participantUserId:t}),await n.http.delete(`/api/v1/rooms/${e}/participants/${t}`),jt("local.room.participantRemoved",{rooms:[{_id:e}],users:[{_id:t}]})},leaveRoom:async e=>{const t=Ve();t.log("room/leaveRoom",{roomId:e}),await t.http.post(`/api/v1/rooms/${e}/leave`),jt("local.room.left",{rooms:[{_id:e}]})},AmityRoomAnalytics:lc,WatchSessionStorage:Xi,getWatchSessionStorage:ec,syncWatchSessions:ic,updateCohostPermission:async(e,t,n)=>{const a=Ve();a.log("room/updatedCoHostPermission",{roomId:e,cohostId:t,canManageProductTags:n});const{data:r}=await a.http.put(`/api/v1/rooms/${e}/participants/${t}`,{canManageProductTags:n});jt("local.room.didUpdate",r);const s=a.cache&&Date.now();a.cache&&Ln(r,{cachedAt:s});const{rooms:o}=r;return{data:dc(o[0]),cachedAt:s}},onRoomStartBroadcasting:pf,onRoomWaitingReconnect:ff,onRoomEndBroadcasting:mf,onRoomRecordedAvailable:gf,onRoomCoHostInvited:yf,onRoomCoHostInviteAccepted:bf,onRoomCoHostInviteRejected:wf,onRoomCoHostInviteCanceled:If,onRoomParticipantJoined:Cf,onRoomParticipantLeft:Sf,onRoomParticipantStageLeft:e=>{const t=Ve();return Mt(t,"room/onRoomParticipantStageLeft","room.participantStageLeft",(t=>{const{rooms:n,users:a}=t;Ln({rooms:n,users:a}),e({room:dc(n[0]),actorInternalId:t.eventActor.userInternalId})}))},onRoomParticipantStageJoined:Of,onRoomTerminated:Tf,onRoomDidUpdate:kf,onRoomCreated:e=>{const t=Ve();return Mt(t,"room/onRoomCreated","local.room.created",(t=>{Ln(t),e(t.rooms[0])}))},onRoomUpdated:e=>{const t=Ve();return Mt(t,"room/onRoomUpdated","local.room.updated",(t=>{Ln(t),e(t.rooms[0])}))},onRoomDeleted:e=>{const t=Ve();return Mt(t,"room/onRoomDeleted","local.room.deleted",(t=>{Ln(t),e(t.rooms[0])}))},onRoomStopped:e=>{const t=Ve();return Mt(t,"room/onRoomStopped","local.room.stopped",(t=>{Ln(t),e(t.rooms[0])}))},onRoomParticipantRemoved:Af,onRoomLeft:e=>{const t=Ve();return Mt(t,"room/onRoomLeft","local.room.left",(t=>{Ln(t),e(t.rooms[0])}))},onLocalRoomDidUpdate:_f,getRoom:(e,t)=>Ui(e,t,"_id",vf,[mf,pf,ff,Tf,gf,Pf(Cf),Pf(Sf),Pf(Af),Ef,Pf(Of),Tl(bf,"targetId","room"),kf,_f],{callbackDataSelector:e=>e?dl.room(e):e}),getRooms:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`getRooms(tmpid: ${s}) > listen`);const o=new Uf(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getRooms(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}}});class xf extends ki{constructor(e){const t={limit:100},n=O.default(t),a=["liveRoomPosts","collection",n];super(new uf(t),n,a,e),this.query=t,this.queryStreamController=new hf(this.query,this.cacheKey,this.notifyChange.bind(this),Gl),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:mf,action:np.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["post","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.post);(this.shouldNotify(o)||"event"!==e)&&this.callback({data:o,loading:t,error:n})}applyFilter(e){return e}}class qf extends Ti{async getRequest(e){const{limit:t=100,communityIds:n}=e,{data:a}=await this.http.get("/api/v1/rooms/lives",{params:{targetTypes:["community"],targetIds:n,options:{limit:t,sortBy:"lastCreated"}}});return a}}class Nf extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:qp(e.rooms,e.posts)});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...qp(e.rooms,e.posts)])]}))}}reactor(e){return e=>{var t;const n=null===(t=Ze(this.cacheKey))||void 0===t?void 0:t.data;n&&("ended"===e.status&&et(this.cacheKey,Object.assign(Object.assign({},n),{data:n.data.filter((t=>e.referenceId!==t))})),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Bf extends ki{constructor(e,t){const n=O.default(e),a=["communityLiveRoomPosts","collection",n];super(new qf(e),n,a,t),this.query=e,this.queryStreamController=new Nf(this.query,this.cacheKey,this.notifyChange.bind(this),Gl),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:mf,action:np.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["post","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.post);(this.shouldNotify(o)||"event"!==e)&&this.callback({data:o,loading:t,error:n})}applyFilter(e){return e}}var Lf=Object.freeze({__proto__:null,getPostByIds:zp,createPost:async e=>{const t=Ve();t.log("post/createPost",e),e.dataType&&!["text","image","file","video"].includes(e.dataType)||delete e.dataType;const{attachments:n,attachmentProductTags:a}=e,r=Kn(e,["attachments","attachmentProductTags"]),s=n&&n.length>0&&e.attachmentProductTags?n.map((t=>{var n;const a=null===(n=e.attachmentProductTags)||void 0===n?void 0:n.get(t.fileId);return a?Object.assign(Object.assign({},t),{productTags:a}):t})):n,{data:o}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},r),{attachments:s}));jt("post.created",o);const i=Gl(o),c=t.cache&&Date.now();t.cache&&Ln(i,{cachedAt:c});const{posts:l}=i;return{data:dl.post(l[0]),cachedAt:c}},editPost:async(e,t)=>{const n=Ve();n.log("user/editPost",t);const{attachments:a}=t,r=a&&a.length>0&&t.attachmentProductTags?a.map((e=>{var n;const a=null===(n=t.attachmentProductTags)||void 0===n?void 0:n.get(e.fileId);return a?Object.assign(Object.assign({},e),{productTags:a}):e})):a,{data:s}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,Object.assign(Object.assign({},t),{attachments:r})),o=Qn(s,"communityUsers"),i=n.cache&&Date.now();n.cache&&Ln(o,{cachedAt:i}),jt("local.post.updated",o);const{posts:c}=o;return{data:dl.post(c.find((t=>t.postId===e))),cachedAt:i}},deletePost:Vp,softDeletePost:async e=>{Ve().log("post/softDeletePost",e);const t=await Vp(e,!1);return dl.post(t)},hardDeletePost:async e=>{Ve().log("post/hardDeletePost",e);const t=await Vp(e,!0);return dl.post(t)},approvePost:async e=>{const t=Ve();t.log("post/approvePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/approve`);jt("post.approved",n),"community"===n.posts[0].targetType&&jt("community.updated",n);const a=Qn(n,"communityUsers"),r=t.cache&&Date.now();return t.cache&&Ln(a,{cachedAt:r}),{data:dl.post(a.posts.find((t=>t.postId===e))),cachedAt:r}},declinePost:async e=>{const t=Ve();t.log("post/declinePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/decline`);"community"===n.posts[0].targetType&&jt("community.updated",n),jt("post.declined",n);const a=Qn(n,"communityUsers"),r=t.cache&&Date.now();return t.cache&&Ln(a,{cachedAt:r}),{data:dl.post(n.posts.find((t=>t.postId===e))),cachedAt:r}},flagPost:async(t,n)=>{const a=Ve();a.log("post/flagPost",t);const r=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,a])=>t!==e.ContentFlagReasonEnum.Others&&a===n)),s={reason:n&&r?n:e.ContentFlagReasonEnum.Others,detail:n&&!r?n:""},{data:o}=await a.http.post(`/api/v3/posts/${encodeURIComponent(t)}/flag`,s);return a.cache&&Ln(Qn(o,"communityUsers")),jt("post.flagged",o),!!o},unflagPost:async e=>{const t=Ve();t.log("post/unflagPost",e);const{data:n}=await t.http.delete(`/api/v3/posts/${encodeURIComponent(e)}/unflag`);return t.cache&&Ln(Qn(n,"communityUsers")),jt("post.unflagged",n),!!n},isPostFlaggedByMe:async e=>{const t=Ve();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=Ve();t.log("post/createPost",e);const{attachments:n,attachmentProductTags:a}=e,r=Kn(e,["attachments","attachmentProductTags"]),s=n&&n.length>0&&e.attachmentProductTags?n.map((t=>{var n;const a=null===(n=e.attachmentProductTags)||void 0===n?void 0:n.get(t.fileId);return a?Object.assign(Object.assign({},t),{productTags:a}):t})):n,{data:o}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},r),{attachments:s}));jt("post.created",o);const i=Qn(o,"communityUsers"),c=t.cache&&Date.now();t.cache&&Ln(i,{cachedAt:c});const{posts:l}=i;return{data:dl.post(l[0]),cachedAt:c}},createAudioPost:async e=>{const t=Ve();t.log("post/createAudioPost",e);const{attachments:n,attachmentProductTags:a}=e,r=Kn(e,["attachments","attachmentProductTags"]),s=n&&n.length>0&&a?n.map((e=>{const t=null==a?void 0:a.get(e.fileId);return t?Object.assign(Object.assign({},e),{productTags:t}):e})):n,{data:o}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},r),{attachments:s}));jt("post.created",o);const i=Gl(o),c=t.cache&&Date.now();return t.cache&&Ln(i,{cachedAt:c}),{data:qc(null==i?void 0:i.posts[0]),cachedAt:c}},createMixedMediaPost:async e=>{var t;const n=Ve();n.log("post/createMixedMediaPost",e);const{attachments:a,attachmentProductTags:r}=e,s=Kn(e,["attachments","attachmentProductTags"]),o=a&&a.length>0&&e.attachmentProductTags?a.map((t=>{var n;const a=null===(n=e.attachmentProductTags)||void 0===n?void 0:n.get(t.fileId);return a?Object.assign(Object.assign({},t),{productTags:a}):t})):a,{data:i}=await n.http.post("/api/v4/posts",Object.assign(Object.assign({},s),{attachments:o}));jt("post.created",i);const c=Gl(i),l=n.cache&&Date.now();return n.cache&&Ln(c,{cachedAt:l}),{data:qc(null===(t=null==c?void 0:c.posts)||void 0===t?void 0:t[0]),cachedAt:l}},createRoomPost:async e=>{const t=Ve();t.log("post/createRoomPost",e);const{data:n}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},e),{dataType:"room"}));jt("post.created",n);const a=Gl(n),r=t.cache&&Date.now();t.cache&&Ln(a,{cachedAt:r});const{posts:s}=a;return{data:dl.post(s[0]),cachedAt:r}},pinProduct:async(e,t)=>{const n=Ve();n.log("post/pinProduct",e);const{data:a}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{pinnedProductId:t}),r=Gl(a),s=n.cache&&Date.now();return n.cache&&Ln(a,{cachedAt:s}),jt("local.post.updated",a),{data:qc(null==r?void 0:r.posts[0]),cachedAt:s}},unpinProduct:async e=>{const t=Ve();t.log("post/unpinProduct",e);const{data:n}=await t.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{pinnedProductId:null}),a=Gl(n),r=t.cache&&Date.now();return t.cache&&Ln(n,{cachedAt:r}),jt("local.post.updated",n),{data:qc(null==a?void 0:a.posts[0]),cachedAt:r}},updateProductTags:async(e,t)=>{const n=Ve();n.log("post/updateProductTags",e);const{data:a}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{productTags:t}),r=Gl(a),s=n.cache&&Date.now();return n.cache&&Ln(a,{cachedAt:s}),jt("local.post.updated",a),{data:qc(null==r?void 0:r.posts[0]),cachedAt:s}},onPostCreated:dd,onPostUpdated:ud,onPostDeleted:hd,onPostApproved:pd,onPostDeclined:fd,onPostFlagged:md,onPostUnflagged:gd,onPostReactionAdded:yd,onPostReactionRemoved:vd,getPost:(e,t)=>Ui(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?dl.post(e.data):n}))}),"postId",Xl,[pd,fd,wp,Ip,t=>hd((n=>{var a;let r=n;if(n.parentPostId===e&&n.isDeleted){const e=null===(a=Ze(["post","get",n.parentPostId]))||void 0===a?void 0:a.data;e&&(e.children=e.children.filter((e=>e!==n.postId)),et(["post","get",e.postId],e),r=e)}t(r)})),md,e=>yd((t=>{e(t)})),e=>vd((t=>{e(t)})),gd,ud,Cp,bp,Tl((t=>Id((async n=>{n.referenceId===e&&(await Xl(e),t(n))}))),"referenceId","post"),Tl((t=>Sd((async n=>{n.referenceId===e&&(await Xl(e),t(n))}))),"referenceId","post")]),getPosts:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`getPosts(tmpid: ${s}) > listen`);const o=new Wp(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getPosts(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getPinnedPosts:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`getPinnedPosts(tmpid: ${s}) > listen`);const o=new Xp(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getPinnedPosts(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getGlobalPinnedPosts:(e,t,n)=>{const{log:a,cache:r}=Ve(),s=Date.now();a(`getGlobalPinnedPosts(tmpid: ${s}) > listen`);const o=new tf(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getGlobalPinnedPosts(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},semanticSearchPosts:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`semanticSearchPosts(tmpid: ${s}) > listen`);const o=new of(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`semanticSearchPosts(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},searchPostsByHashtag:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`searchPostsByHashtag(tmpid: ${s}) > listen`);const o=new df(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`searchPostsByHashtag(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getLiveRoomPosts:e=>{const{log:t,cache:n}=Ve();n||console.log(pe);const a=Date.now();t(`getLiveRoomPosts(tmpid: ${a}) > listen`);const r=new xf(e),s=r.startSubscription(),o=r.getCacheKey();return s.push((()=>at(o))),()=>{t(`getLiveRoomPosts(tmpid: ${a}) > dispose`),s.forEach((e=>e()))}},getCommunityLiveRoomPosts:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`getCommunityLiveRoomPosts(tmpid: ${s}) > listen`);const o=new Bf(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getCommunityLiveRoomPosts(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}}});const Ff=async e=>{const t=Ve();t.log("stream/getStream",e);const{data:n}=await t.http.get(`/api/v3/video-streaming/${e}`),a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a});const{videoStreamings:r}=n;return{data:r.find((t=>t.streamId===e)),cachedAt:a}};Ff.locally=e=>{const t=Ve();if(t.log("stream/getStream",e),!t.cache)return;const n=Ze(["stream","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Kf=e=>{const t=Ve();return Mt(t,"stream/onStreamStarted","video-streaming.didStart",(t=>{Ln(t),e(t.videoStreamings[0])}))},$f=e=>{const t=Ve();return Mt(t,"stream/onStreamStropped","video-streaming.didStop",(t=>{Ln(t),e(t.videoStreamings[0])}))},Qf=e=>{const t=Ve();return Mt(t,"stream/onStreamRecorded","video-streaming.didRecord",(t=>{Ln(t),e(t.videoStreamings[0])}))},zf=e=>{const t=Ve();return Mt(t,"stream/onStreamFlagged","video-streaming.didFlag",(t=>{Ln(t),e(t.videoStreamings[0])}))},Vf=e=>{const t=Ve();return Mt(t,"stream/onStreamTerminated","video-streaming.didTerminate",(t=>{Ln(t),e(t.videoStreamings[0])}))},Hf=(e,t)=>Ui(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?dl.stream(e.data):n}))}),"streamId",Ff,[Qf,Kf,$f,zf,Vf,au]);Hf.locally=e=>{const t=Ve();if(t.log("stream/getStreamById",e),!t.cache)return;const n=Ze(["stream","get",e]);return n?{data:dl.stream(n.data),cachedAt:n.cachedAt}:void 0};const Jf=async e=>{const t=Ve();t.log("stream/queryStreams",e);const n=null!=e?e:{},{page:a,limit:r}=n,s=Kn(n,["page","limit"]),o=a?{token:a}:r?{limit:r}:void 0,{data:i}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},s),{options:o})}),{paging:c,results:l}=i,{videoStreamings:d}=l,u=t.cache&&Date.now();return t.cache&&Ln(l,{cachedAt:u}),{data:d,cachedAt:u,paging:c}};var Wf=Object.freeze({__proto__:null,createStream:async e=>{const t=Ve();t.log("stream/createStream",e);const{data:n}=await t.http.post("/api/v3/video-streaming",e),a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a});const{videoStreamings:r}=n;return{data:dl.stream(r[0]),cachedAt:a}},updateStream:async(e,t)=>{const n=Ve();n.log("stream/updateStream",e,t);const{data:a}=await n.http.put(`/api/v3/video-streaming/${e}`,t),r=n.cache&&Date.now();n.cache&&Ln(a,{cachedAt:r});const{videoStreamings:s}=a;return{data:dl.stream(s.find((t=>t.streamId===e))),cachedAt:r}},deleteStream:async e=>{const t=Ve();t.log("stream/deleteStream",e);const n=await Ff(e),{data:a}=await t.http.delete(`/api/v3/video-streaming/${e}`),{success:r}=a,s=Object.assign(Object.assign({},n.data),{isDeleted:!0});return nt(["stream","get",e],s),r},disposeStream:async e=>{const t=Ve();t.log("stream/disposeStream",e);const{data:n}=await t.http.delete(`/api/v3/video-streaming/${e}/streaming-url`),a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a});const{videoStreamings:r}=n;return{data:r.find((t=>t.streamId===e)),cachedAt:a}},editStream:async(e,t)=>{const n=Ve();n.log("stream/updateStream",e,t);const{data:a}=await n.http.put(`/api/v3/video-streaming/${e}`,t),r=n.cache&&Date.now();n.cache&&Ln(a,{cachedAt:r});const{videoStreamings:s}=a;return{data:dl.stream(s.find((t=>t.streamId===e))),cachedAt:r}},onStreamStarted:Kf,onStreamStopped:$f,onStreamRecorded:Qf,onStreamFlagged:zf,onStreamTerminated:Vf,onStreamViewerBanned:au,onStreamViewerUnbanned:e=>{const t=Ve();return Mt(t,"stream/onStreamViewerDidUnban","video-streaming.viewerDidUnban",(async t=>{var n;const{list:a}=t;await Promise.all(a.map((({streamId:e})=>Ff(e))));const r=null===(n=Ze(["stream","get",a[0].streamId]))||void 0===n?void 0:n.data;r&&e(r)}))},getStreamById:Hf,getStreams:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`getStreams(tmpid: ${s}) > listen`);const{limit:o}=e,i=Kn(e,["limit"]),c=null!=o?o:de,{policy:l=he}=null!=n?n:{},d=[],u=["streams","collection",e],h=t=>{let n=rt(t,"isDeleted",e.isDeleted);return n=n.sort("lastCreated"===e.sortBy?bt:yt),n},p=(e,n=!1)=>{var a,r;const s=null!==(a=e.data.map((e=>Ze(["stream","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==a?a:[];t({onNextPage:m,data:n?h(s):s,hasNextPage:!!(null===(r=e.params)||void 0===r?void 0:r.page),loading:e.loading,error:e.error})},f=e=>e=>{var t;const n=null===(t=Ze(u))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.streamId,...n.data])],et(u,n),p(n,!0))},m=(e=!1)=>{var t,n;const a=null===(t=Ze(u))||void 0===t?void 0:t.data,r=null!==(n=null==a?void 0:a.data)&&void 0!==n?n:[];if(!e&&r.length>0&&!(null==a?void 0:a.params.page))return;const s=xe(Jf,Object.assign(Object.assign({},i),{limit:e?c:void 0,page:e||null==a?void 0:a.params.page}));Ne(s,(({data:e,error:t,loading:n,paging:a})=>{const s={loading:n,error:t,params:{page:null==a?void 0:a.next},data:r};e&&(s.data=[...new Set([...r,...e.map(We("stream"))])]),et(u,s),p(s)}),qe(l))};return d.push(Qf(f()),Kf(f()),$f(f())),m(!0),()=>{a(`getStreams(tmpid: ${s}) > dispose`),d.forEach((e=>e()))}}});const Gf=async()=>{const e=Ve();e.log("presence/getPresenceSetting");const{data:t}=await e.http.get("/api/v1/presence/settings");return et(["get","presenceSetting"],t),t};class Yf{constructor(e){this.isEnabled=!1,this.config={heartbeatInterval:3e4},this.roomId=e,this.initializeConfig().catch((e=>{console.error("Failed to initialize RoomPresenceSyncEngine config in constructor:",e)}))}async initializeConfig(){try{const e=await Yf.getPresenceSettingWithRetry();e?this.config={heartbeatInterval:60*(e.network.heartbeatInterval||5)*1e3}:this.config.heartbeatInterval=3e5}catch(e){console.error("Failed to initialize RoomPresenceSyncEngine config:",e),this.config.heartbeatInterval=3e5}}static async getPresenceSettingWithRetry(e=5){for(let t=0;t<e;t+=1)try{return await Gf()}catch(n){if(t>=e-1)return console.error(`Failed to get presence setting after ${e} attempts:`,n),null;const a=2e4+5e3*Math.random();console.warn(`Failed to get presence setting (attempt ${t+1}/${e}), retrying in ${Math.round(a/1e3)}s:`,n),await new Promise((e=>{setTimeout(e,a)}))}return null}start(){this.isEnabled||(this.isEnabled=!0,this.sendHeartbeat(),this.heartbeatTimer=setInterval((()=>{this.sendHeartbeat()}),this.config.heartbeatInterval))}stop(){this.isEnabled=!1,this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0)}async sendHeartbeat(){try{const e=Ve();await e.http.post(`/api/v1/presence/rooms/${this.roomId}/heartbeat`)}catch(e){console.error(`Heartbeat failed for room ${this.roomId}:`,e)}}getRoomId(){return this.roomId}isActive(){return this.isEnabled}destroy(){this.stop()}onSessionDestroyed(){this.destroy()}onTokenExpired(){this.stop()}}const Xf=new Map,Zf=e=>{let t=Xf.get(e);return t||(t=new Yf(e),Xf.set(e,t)),t};var em=Object.freeze({__proto__:null,getRoomOnlineUsers:async e=>{var t,n,a;const r=Ve();r.log("room/getWatchingUsers",{roomId:e});const{data:s}=await r.http.get(`/api/v1/presence/rooms/${e}/users`),o=null!==(t=null==s?void 0:s.viewers.map((e=>e.userId)))&&void 0!==t?t:[],i=[];for(let e=0;e<o.length;e+=100)i.push(o.slice(e,e+100));const c=await Promise.all(i.map((e=>ul(e)))),l=[];return c.forEach((e=>{e.data&&l.push(...e.data)})),{data:l,cachedAt:null!==(a=null===(n=c[0])||void 0===n?void 0:n.cachedAt)&&void 0!==a?a:Date.now()}},getRoomUserCount:async e=>{const t=Ve();t.log("roomPresence/getRoomUserCount",{roomId:e});const{data:n}=await t.http.get(`/api/v1/presence/rooms/${e}/users/count`);return et(["get","watchingCount",e],n),n},startHeartbeat:e=>{Zf(e).start()},stopHeartbeat:e=>{Zf(e).stop(),(e=>{const t=Xf.get(e);t&&(t.destroy(),Xf.delete(e))})(e)}});const tm=async e=>{const t=Ve();t.log("poll/getPoll",e);const{data:n}=await t.http.get(`/api/v3/polls/${e}`),a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a});const{polls:r}=n,s=r.find((t=>t.pollId===e));return{data:uc(s),cachedAt:a}};tm.locally=e=>{const t=Ve();if(t.log("poll/getPoll",e),!t.cache)return;const n=Ze(["poll","get",e]);return n?{data:uc(n.data),cachedAt:n.cachedAt}:void 0};const nm=e=>{const t=Ve();return Mt(t,"poll/onPollUpdated","poll.updated",(n=>{t.cache&&Ln(n),e(n.polls[0])}))},am=e=>{const t=Ve();return Mt(t,"poll/onPollDeleted","poll.deleted",(n=>{t.cache&&Ln(n),e(n.polls[0])}))};var rm=Object.freeze({__proto__:null,createPoll:async e=>{const t=Ve();t.log("post/createPoll",e);const{data:n}=await t.http.post("/api/v3/polls",e),a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a});const{polls:r}=n;return{data:uc(r[0]),cachedAt:a}},closePoll:async e=>{const t=Ve();t.log("user/closePoll",e);const{data:n}=await t.http.put(`/api/v3/polls/${encodeURIComponent(e)}`,{status:"closed"}),a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a}),jt("poll.updated",n);const{polls:r}=n,s=r.find((t=>t.pollId===e));return{data:uc(s),cachedAt:a}},deletePoll:async e=>{const t=Ve();t.log("poll/deletePoll",e);const n=await tm(e),{data:a}=await t.http.delete(`/api/v3/polls/${e}`),{success:r}=a,s=Object.assign(Object.assign({},n.data),{isDeleted:!0});return nt(["poll","get",e],s),jt("poll.deleted",{polls:[s],users:[]}),r},votePoll:async(e,t)=>{const n=Ve();n.log("user/votePoll",e);const{data:a}=await n.http.post(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:t}),r=n.cache&&Date.now();n.cache&&Ln(a,{cachedAt:r});const{polls:s}=a,o=s.find((t=>t.pollId===e));return jt("poll.updated",a),{data:uc(o),cachedAt:r}},unvotePoll:async e=>{const t=Ve();t.log("user/unvotePoll",e);const{data:n}=await t.http.put(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:[]}),a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a}),jt("poll.updated",n)},onPollUpdated:nm,onPollDeleted:am,getPoll:(e,t)=>Ui(e,t,"pollId",tm,[nm,am])});class sm{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((()=>{!async function({bufferCurrentUsage:e,getActiveStreams:t,updateUsage:n,dispose:a}){const r=e();if(r.length)try{const n=(new Date).toISOString(),s=await oc({timestamp:n,streams:r});if(!s||!s.signature)throw new Error("Signature is undefined");const o={signature:s.signature,nonceStr:s.nonceStr,timestamp:n,streams:r},i=Ve();await i.http.post("/api/v3/user-event/video-streaming",o),t().length||e().length||a()}catch(e){return r.forEach((e=>n(e))),!1}}({bufferCurrentUsage:this.bufferCurrentUsage.bind(this),getActiveStreams:this.getActiveStreams.bind(this),updateUsage:this.updateUsage.bind(this),dispose:this.dispose.bind(this)})}),2e4)}}let om=null;class im{constructor(e,t,n){this._SDKUnsubscribers=[],this.player=e,this.resolution=t,this._startTime=null,this._usageCollector=om||(om=new sm,om),this._usageCollector.registerStream(e.id),this._sessionId=String(C.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(au((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 cm=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(!T.default.isSupported())throw new Error("This browswer does not support hls, unable to play stream");const{data:n}=await Ff(t),{watcherUrl:a,status:r,recordings:s=[],resolution:o}=n;if(!a.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 T.default;if(c.attachMedia(i),"recorded"!==r){let{url:e}=a.hls;e=e.replace("http:","https:"),c.loadSource(e)}else{const e=s.find((e=>!!e.mp4));if(!e||!e.mp4)throw new Error("No playable recording available");i.src=e.mp4.url}return new im(i,o,t).registerEvents(),i}});const lm=e=>{const t=(e=>{var t;const n=Ve(),a=new Date,r=a.getTime()+31536e6,s=new Date(r).toISOString();let o=null===(t=Ze(["storyTarget","get",e.targetId]))||void 0===t?void 0:t.data;return o||(o={targetType:e.targetType,targetId:e.targetId,lastStoryExpiresAt:s,targetPublicId:e.targetId,targetUpdatedAt:a.toISOString()},Ln({storyTargets:[o]})),{stories:[Object.assign({createdAt:a.toISOString(),updatedAt:a.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(r).toISOString()},e)],categories:[],communityUsers:[],comments:[],files:[],users:[],communities:[]}})(e);return Ln(t),t},dm=({payload:e,formData:t,isVideo:n=!1},a)=>{if(t){const r=t.getAll("files")[0]||void 0;if(!r)return;const s=Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileId:void 0,fileData:r.uri})});return n&&(s.data.videoFileId={original:void 0}),a(lm(s))}return a(lm(Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileData:null})})))},um=async e=>{const t=Ve();t.log("post/createStory",e);const n=await t.http.post("/api/v4/stories",e),a=op(n.data);t.cache&&Ln(a),et(["story-sync-state",e.targetId],"synced"),jt("local.story.created",a);const r=t.cache&&Date.now();return{data:a.stories.length>0?a.stories[0]:void 0,cachedAt:r}},hm=async({targetId:e,targetType:t})=>{var n,a;if(!Ze(["storyTarget","get",e])){let r={targetId:e,targetType:t};if("community"===t){const t=await Qu(e);r=Object.assign(Object.assign({},r),{targetPublicId:t.data.communityId,targetUpdatedAt:null!==(n=t.data.updatedAt)&&void 0!==n?n:(new Date).toISOString()})}if("user"===t){const t=await yl(e);r=Object.assign(Object.assign({},r),{targetPublicId:t.data.userPublicId,targetUpdatedAt:null!==(a=t.data.updatedAt)&&void 0!==a?a:(new Date).toISOString()})}et(["storyTarget","get",e],r)}},pm=e=>e?Ze(["story","get",e]):{data:void 0,cachedAt:void 0},fm=async(e,t=!1)=>{var n,a,r;const s=Ve();let o;if(s.log("story/deleteStory",e),s.cache&&(o=pm(e),null==o?void 0:o.data)){const{data:s}=o;if(jt("local.story.deleted",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[Object.assign(Object.assign({},s),{isDeleted:!0})]}),"synced"!==s.syncState){t?at(["story","get",e]):et(["story","get",e],Object.assign(Object.assign({},o.data),{isDeleted:!0}));const a=null===(n=Xe(["story","get"]))||void 0===n?void 0:n.filter((e=>"synced"!==e.data.syncState&&e.data.targetId===s.targetId&&!0!==e.data.isDeleted));if(a&&a.length>0){const e=a.reduce(((e,t)=>{const n=new Date(t.data.expiresAt||0);return n>e?n:e}),new Date(0));et(["story-expire",o.data.targetId],e.toISOString())}else at(["story-expire",o.data.targetId]);return!0}const i=null===(a=Ze(["storyTarget","get",s.targetId]))||void 0===a?void 0:a.data,c=null===(r=Xe(["story","get"]))||void 0===r?void 0:r.filter((e=>"synced"===e.data.syncState&&e.data.targetId===s.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&&et(["storyTarget","get",s.targetId],Object.assign(Object.assign({},i),{lastStoryExpiresAt:l}))}return(await s.http.delete(`/api/v4/stories/${e}`,{params:{permanent:t}})).data.success},mm=e=>{const t=Ve(),n=[Mt(t,"onStoryUpdated","story.updated",(async t=>{const n=op(t);Ln(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},gm=e=>{const t=Ve(),n=[Mt(t,"onStoryUpdated","local.story.updated",(async t=>{Ln(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},ym=e=>{const t=Ve(),n=[Mt(t,"onStoryReactionAdded","story.reactionAdded",(async t=>{const{reactions:n}=t,a=Kn(t,["reactions"]),r=op(a),s=rd("story.reactionAdded",Object.assign(Object.assign({},r),{reactions:n}));Ln(s),e(s.stories)}))];return()=>{n.forEach((e=>e()))}},vm=e=>{const t=Ve(),n=[Mt(t,"onStoryReactionAdded","local.story.reactionAdded",(async t=>{Ln({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},bm=e=>{const t=Ve(),n=[Mt(t,"onStoryReactionRemoved","story.reactionRemoved",(async t=>{const{reactions:n}=t,a=Kn(t,["reactions"]),r=op(a),s=rd("story.reactionRemoved",Object.assign(Object.assign({},r),{reactions:n}));Ln(s),e(s.stories)}))];return()=>{n.forEach((e=>e()))}},wm=e=>{const t=Ve(),n=[Mt(t,"onStoryReactionRemoved","local.story.reactionRemoved",(async t=>{Ln({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},Im=e=>{e.forEach((e=>{const t=Ze(["story-expire",e.targetId]),n=new Date(e.expiresAt||0);n<new Date((null==t?void 0:t.data)||0)||et(["story-expire",e.targetId],n.toISOString())}))},Cm=e=>{e.forEach((e=>{et(["story-reference",e.storyId],e.referenceId)}))},Sm=async({targetType:e,targetId:t,options:n})=>{const a=Ve();a.log("story/getActiveStoriesByTarget");const r=a.cache&&Date.now(),s=await a.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"}}}),o=op(s.data);return a.cache&&(Ln(o),Im(o.stories),Cm(o.stories)),{data:o.stories,cachedAt:r,paging:{next:void 0,previous:void 0}}},Om=e=>{const t=Ve(),n=[Mt(t,"onStoryCreated","story.created",(async t=>{const n=op(t,!0);Ln(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Tm=e=>{const t=Ve(),n=[Mt(t,"onStoryCreated","local.story.created",(async t=>{Ln(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},km=e=>{const t=Ve(),n=[Mt(t,"onStoryDeleted","story.deleted",(async t=>{const n=op(t);Ln(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Am=e=>{const t=Ve(),n=[Mt(t,"onStoryDeleted","local.story.deleted",(async t=>{Ln(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},_m=e=>{const t=Ve();return Mt(t,"onStoryError","local.story.error",(async t=>{Ln(t),e(t.stories)}))},Em=e=>t=>e((e=>t(e[0]))),Rm=async e=>{const t=Ve();t.log("story/getTargetsByTargetIds",e);const n=await t.http.get("/api/v4/stories/seen",{params:{targets:e}}),{data:a}=n;return t.cache&&Ln(n.data),{data:a.storyTargets,cachedAt:Date.now()}};class Pm extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.paginationController=a}saveToMainDB(e){const t=Ve(),n=t.cache&&Date.now(),a=op(e);t.cache&&(Ln(a,{cachedAt:n}),Im(a.stories),Cm(a.stories))}getStoryReferenceIds(e){return(null==e?void 0:e.referenceId)?e.referenceId:e.storyId}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.stories.map(this.getStoryReferenceIds)});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(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=Ze(this.cacheKey))||void 0===t?void 0:t.data;if(!n)return;const a=e.map((({referenceId:e})=>e));n.data=[...new Set([...a,...n.data])],et(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Mm extends Ti{async getRequest(e){const{data:t}=await this.http.get("/api/v4/stories-by-targets",{params:Object.assign({},e)});return t}}class jm extends ki{constructor(e,t){const n=O.default(e),a=["story-target-ids","collection",n],r=new Mm(e);super(r,n,a,t),this.query=e,this.queryStreamController=new Pm(this.query,this.cacheKey,this.notifyChange.bind(this),r),this.paginationController=r,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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 a;const r=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!r)return;let s=r.data.map((e=>Ze(["story","get",e]))).filter(Boolean).map((e=>dl.story(e.data)));(this.shouldNotify(s)||"event"!==e)&&(s=this.applyFilter(s),this.callback({onNextPage:void 0,data:s,hasNextPage:!1,loading:t,error:n}))}applyFilter(e){var t,n;const a=e;return"asc"===((null===(n=null===(t=this.query)||void 0===t?void 0:t.options)||void 0===n?void 0:n.orderBy)||"desc")?a.sort(yt):a.sort(bt)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Om,action:"onCreate"},{fn:mm,action:"onUpdate"},{fn:km,action:"onDelete"},{fn:_m,action:"onError"}])}}const Um=(e,t)=>{var n,a;const r=null===(n=Ze(e))||void 0===n?void 0:n.data,s=null!==(a=null==r?void 0:r.data)&&void 0!==a?a:[];et(e,Object.assign(Object.assign({},r),{data:[...new Set([...s,...t])]}))};class Dm extends Ci{constructor(e,t,n,a,r){super(e,t),this.notifyChange=n,this.paginationController=a,this.preparePayload=r}saveToMainDB(e){const t=Ve(),n=t.cache&&Date.now(),a=this.preparePayload(e);t.cache&&Ln(a,{cachedAt:n})}appendToQueryStream(e,t,n=!1){n?et(this.cacheKey,{data:e.storyTargets.map((({targetId:e})=>e))}):Um(this.cacheKey,e.storyTargets.map((({targetId:e})=>e)))}reactor(e){return t=>{"onCreate"===e&&"seen"!==this.query.seenState&&Um(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 xm extends wi{constructor(){super(...arguments),this.smartFilterState="unseen"}async getRequest(e,t){var n;const{limit:a=10,seenState:r="unseen"}=e,s=await this.createRequest({seenState:"smart"===r?this.smartFilterState:r,limit:a,token:t});if(null===(n=s.paging)||void 0===n?void 0:n.next)return s;if("smart"!==r)return s;if("seen"===this.smartFilterState)return s;this.smartFilterState="seen";const o=await this.createRequest({seenState:this.smartFilterState,limit:a});return c=o,{categories:(i=s).categories.concat(c.categories),communities:i.communities.concat(c.communities),communityUsers:i.communityUsers.concat(c.communityUsers),files:i.files.concat(c.files),storyTargets:i.storyTargets.concat(c.storyTargets),users:i.users.concat(c.users),paging:c.paging};var i,c}async createRequest(e){const{data:t}=await this.http.get("/api/v5/me/global-story-targets",{params:e});return n=t,a=e.seenState,Object.assign(Object.assign({},n),{storyTargets:n.storyTargets.map((e=>Object.assign(Object.assign({},e),{localFilter:a})))||[]});var n,a}}class qm extends ki{constructor(e,t){const n=O.default(e),a=["story-global-feed","collection",n],r=new xm(e);super(r,n,a,t),this.query=e,this.queryStreamController=new Dm(this.query,this.cacheKey,this.notifyChange.bind(this),r,(e=>{const t=Kn(mc(Object.assign(Object.assign({},e),{feeds:[]})),["feeds"]);return Object.assign(Object.assign({},e),t)})),this.paginationController=r,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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 a;const r=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!r)return;const s=r.data,o=Xe(["storyTarget"]);o&&(null==o?void 0:o.length)>0&&(null==o||o.forEach((({key:e})=>{r.data.includes(e[2])||s.push(e[2])})));let i=s.map((e=>Ze(["storyTarget","get",e]))).filter(Boolean).map((e=>dl.storyTarget(e.data)));(this.shouldNotify(i)||"event"!==e)&&(i=this.applyFilter(i).filter((({localSortingDate:e})=>!!e)).map((e=>Kn(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(vt);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(vt)||[],a=t.unseen.sort(vt)||[],r=t.seen.sort(vt)||[];return n.concat(a,r)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Om,action:"onCreate"},{fn:mm,action:"onUpdate"},{fn:km,action:"onDelete"},{fn:Tm,action:"onCreate"},{fn:gm,action:"onUpdate"},{fn:Am,action:"onDelete"},{fn:_m,action:"onError"}])}}var Nm=Object.freeze({__proto__:null,createImageStory:async(e,t,n,a={},r="fit",s=[])=>{if(!n.getAll("files").length)throw new Error("The formData object must have a `files` key.");let o={data:{text:"",fileId:void 0,fileData:null,imageDisplayMode:r},syncState:"syncing",referenceId:Mn(),dataType:"image",items:s,targetType:e,targetId:t,metadata:a};const i=new Date;et(["story-sync-state",t],"syncing"),et(["story-expire",t],new Date(i.setFullYear(i.getFullYear()+1))),dm({payload:o,formData:n},(e=>{jt("local.story.created",e)}));try{const{data:a}=await Nl(n);if(0===a.length)throw new Error("Failed to upload image");const{fileId:r}=a[0];o=Object.assign(Object.assign({},o),{data:Object.assign(Object.assign({},o.data),{fileId:r})}),hm({targetId:t,targetType:e}),dm({payload:o,formData:n},(e=>{jt("local.story.created",e)}));const s=await um(o);return s.data?Object.assign(Object.assign({},s),{data:dl.story(s.data)}):s}catch(e){throw et(["story-sync-state",t],"error"),dm({payload:Object.assign(Object.assign({},o),{syncState:"error"}),formData:n},(e=>{jt("local.story.error",e)})),e}},createVideoStory:async(e,t,n,a={},r=[])=>{if(!n.getAll("files").length)throw new Error("The formData object must have a `files` key.");let s={data:{text:"",fileId:void 0,fileData:null},syncState:"syncing",referenceId:Mn(),dataType:"video",items:r,targetType:e,targetId:t,metadata:a};const o=new Date;et(["story-sync-state",t],"syncing"),et(["story-expire",t],new Date(o.setFullYear(o.getFullYear()+1))),hm({targetId:t,targetType:e}),dm({payload:s,formData:n,isVideo:!0},(e=>{jt("local.story.created",e)}));try{const{data:e}=await ql(n,x.STORY);if(0===e.length)throw new Error("Failed to upload video");const{fileId:t}=e[0];s=Object.assign(Object.assign({},s),{data:Object.assign(Object.assign({},s.data),{fileId:t,videoFileId:{original:t}})}),dm({payload:s,formData:n,isVideo:!0},(e=>{jt("local.story.created",e)}));const a=await um(s);return a.data?Object.assign(Object.assign({},a),{data:dl.story(a.data)}):a}catch(e){throw et(["story-sync-state",t],"error"),dm({payload:Object.assign(Object.assign({},s),{syncState:"error"}),formData:n,isVideo:!0},(e=>{jt("local.story.error",e)})),e}},hardDeleteStory:async e=>await fm(e,!0),softDeleteStory:async e=>await fm(e),getActiveStoriesByTarget:(e,t)=>{const{log:n,cache:a}=Ve(),r=[],s=["story-target","collection",e],o=Date.now();n(`getActiveStoriesByTarget(tmpid: ${o}) > listen`),a||console.log(pe);const i=t=>{var n,a;const r=(null===(n=e.options)||void 0===n?void 0:n.sortBy)||"createdAt",s=(null===(a=e.options)||void 0===a?void 0:a.orderBy)||"desc";return 0===t.length?[]:"createdAt"===r?"asc"===s?t.sort(yt):t.sort(bt):"asc"===s?t.sort(wt):t.sort(It)},c=e=>{var n;const a=e.data.map((e=>{const t=pm(e);if(null==t?void 0:t.data)return dl.story(t.data)})).filter(Boolean).filter((e=>!!e&&!e.isDeleted)),r=[];if(a.length>0){const e=a.reduce(((e,t)=>{if(!t)return e;const{syncState:n}=t;if(!n)return e;let a=e.get(n);return a||(a=[]),a.push(t),e.set(n,a),e}),new Map);if(e.has("error")){const t=i(e.get("error")||[]);r.push(...t)}if(e.has("syncing")){const t=i(e.get("syncing")||[]);r.push(...t)}if(e.has("synced")){const t=i(e.get("synced")||[]);r.push(...t)}}t({onNextPage:()=>!1,data:r||a,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading||!1})},l=(t,n,a=!1,r=!1,o=!1)=>{var i;const l=Ze(s),d={loading:r,error:o,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=a?t.map(We("story")):[...new Set([...d.data,...t.map(We("story"))])];const u=null===(i=Xe(["story","get"]))||void 0===i?void 0:i.filter((t=>t.data.targetId===e.targetId&&"synced"!==t.data.syncState)).map((e=>We("story")(e.data)));u&&(null==u?void 0:u.length)>0&&u.forEach((e=>{d.data.includes(e)||d.data.push(e)})),et(s,d.data),c(d)},d=e=>t=>{l(t,e)};return(t=>{const n=xe(Sm,e);Ne(n,(({data:e,error:n,loading:a})=>{l(e,"fetch",t,a,n)}))})(!0),r.push(Om(d("onCreate")),mm(d("onUpdate")),km(d("onDelete")),ym(d("onReactionAdded")),bm(d("onReactionRemoved")),_m(d("onError")),Tm(d("onCreate")),gm(d("onUpdate")),Am(d("onDelete")),vm(d("onReactionAdded")),wm(d("onReactionRemoved")),(e=>{const t=Ve();return Mt(t,"onStoryLocalDataUpdated","local.story.reload",(t=>{e(t)}))})((e=>{const t=Ze(s);if(!t)return;if(0===e.referenceIds.length||0===(null==t?void 0:t.data.length))return;if(!(null==t?void 0:t.data.find((t=>e.referenceIds.includes(t)))))return;const n={loading:!1,error:!1,params:{page:void 0},data:(null==t?void 0:t.data)||[]};c(n)})),(()=>at(s))),()=>{n(`getActiveStoriesByTarget(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getStoryByStoryId:(e,t)=>Ui(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:dl.story(e.data)})):t(e)}),"storyId",ip,[Em(mm),Em(km),Em(ym),Em(bm),Em(_m),Em(gm),Em(Am),Em(vm),Em(wm)]),getTargetById:(e,t)=>Ui(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:dl.storyTarget(e.data[0])})):t(e)}),"query",(e=>Rm([e])),[]),getTargetsByTargetIds:(e,t)=>{const{log:n,cache:a}=Ve(),r=[],s=["storyTargets","collection",e],o=Date.now();n(`getTargetsByTargetIds(tmpid: ${o}) > listen`),a||console.log(pe);const i=(e,n=!1,a=!1,r=!1)=>{const o=Ze(s),i={loading:a,error:r,params:{page:void 0},data:[]};e&&(i.data=n?e.map(We("storyTarget")):[...new Set([...(null==o?void 0:o.data)||[],...e.map(We("storyTarget"))])]),et(s,i.data),(e=>{var n;const a=e.data.map((e=>{const t=Ze(["storyTarget","get",e]);if(null==t?void 0:t.data)return dl.storyTarget(t.data)})).filter(Boolean);t({onNextPage:void 0,data:a,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading||!1})})(i)};return(t=>{const n=xe(Rm,e);Ne(n,(({data:e,error:n,loading:a})=>{i(e,t,a,n)}))})(!0),r.push((()=>at(s))),()=>{n(`getTargetsByTargetIds(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getStoriesByTargetIds:(e,t,n)=>{const{log:a,cache:r,userId:s}=Ve();r||console.log(pe);const o=Date.now();a(`getStoriesByTargetIds(tmpid: ${o}) > listen`);const i=new jm(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{at(l)})),()=>{a(`getStoriesByTargetIds(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}},getGlobalStoryTargets:(e,t,n)=>{const{log:a,cache:r,userId:s}=Ve();r||console.log(pe);const o=Date.now();a(`getGlobalStoryTarget(tmpid: ${o}) > listen`);const i=new qm(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{at(l)})),()=>{a(`getGlobalStoryTarget(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}}});const Bm=e=>Object.assign(Object.assign({},e),{endAt:e.endAt?e.endAt:null}),Lm=e=>Object.assign({},e);var Fm=Object.freeze({__proto__:null,getNetworkAds:async()=>{const e=Ve(),{data:t}=await e.http.get("/api/v1/ads/me"),n=t.ads.map(Bm),a=t.advertisers.map(Lm);return Ln({ads:n,advertisers:a,files:t.files}),et(["ad","setting"],t.settings),{ads:n.map(dl.ad),settings:t.settings}}});const Km=async()=>{const e=Ve();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];et(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}};Km.locally=()=>{var e;const t=Ve();if(t.log("notificationTray/getNotificationTraySeen.locally",{}),!t.cache)return;const{data:n,cachedAt:a}=null!==(e=Ze(["notificationTraySeen","get"]))&&void 0!==e?e:{};return n?{data:n,cachedAt:a}:void 0};const $m=e=>{const t=Ve(),n=[Mt(t,"onNotificationTraySeenUpdated","local.notificationTraySeen.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class Qm extends wi{async getRequest(e,t){const{limit:n=de}=e,a=Kn(e,["limit"]),r=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v1/notification-tray",{params:Object.assign(Object.assign({},a),{options:r})});return s}}class zm extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.notificationTrayItems.map(We("notificationTrayItem"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.notificationTrayItems.map(We("notificationTrayItem"))])]}))}}}const Vm=e=>{const t=e.users.map(ga);return Object.assign(Object.assign({},e),{users:t})};class Hm extends ki{constructor(e,t){const n=O.default(e),a=["notificationTrayItem","collection",n];super(new Qm(e),n,a,t),this.query=e,this.queryStreamController=new zm(this.query,this.cacheKey,this.notifyChange.bind(this),Vm),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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 a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=(null!==(r=s.data.map((e=>Ze(["notificationTrayItem","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.notificationTray);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var Jm=Object.freeze({__proto__:null,getNotificationTraySeen:e=>{const{userId:t}=kt();return Ui(t,e,"userId",Km,[$m],{callbackDataSelector:e=>{let t=!0;return(null==e?void 0:e.lastTrayOccurredAt)&&(t=!!e.lastTraySeenAt&&Wn(e.lastTraySeenAt)>Wn(e.lastTrayOccurredAt)),{lastTrayOccurredAt:null==e?void 0:e.lastTrayOccurredAt,lastTraySeenAt:null==e?void 0:e.lastTraySeenAt,isSeen:t}}})},getNotificationTrayItems:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`getNotificationTrayItems(tmpid: ${s}) > listen`);const o=new Hm(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getNotificationTrayItems(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},markItemsSeen:async e=>{const t=Ve();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})))}),a=n.trayItems.map((e=>{var n;const a=null===(n=Ze(["notificationTrayItem","get",e.id]))||void 0===n?void 0:n.data;if(!a)return;const r=Object.assign(Object.assign({},a),{lastSeenAt:e.lastSeenAt});if(t.cache){const e=Date.now();et(["notificationTrayItem","get"],r,{cachedAt:e})}return r})).filter(Boolean);jt("local.notificationTrayItem.updated",{notificationTrayItems:a})},markTraySeen:async e=>{var t;const n=Ve();n.log("notificationTray/markTraySeen",{});const{data:a}=await n.http.post("api/v1/notification-tray/tray/seen",{lastSeenAt:e}),r=null===(t=Ze(["notificationTraySeen","get"]))||void 0===t?void 0:t.data,s={userId:n.userId,lastTraySeenAt:a.lastSeenAt},o=Object.assign(Object.assign({},r),s),i=n.cache&&Date.now();return n.cache&&et(["notificationTraySeen","get",n.userId],o,{cachedAt:i}),jt("local.notificationTraySeen.updated",s),{data:a,cachedAt:i}},onNotificationTraySeenUpdated:$m});class Wm extends wi{async getRequest(e,t){const{limit:n=de}=e,a=Kn(e,["limit"]),r=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v1/invitations/me",{params:Object.assign(Object.assign({},a),{options:r})}),o=s.invitations.filter((e=>"community"===e.targetType&&!!e.communityId)).map((e=>e.communityId));return(null==o?void 0:o.length)>0&&await $u(o),s}}class Gm extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.invitations.map(We("invitation"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(We("invitation"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===_c.OnLocalInvitationUpdated){if(!a.data.find((e=>e===t[0].invitationId)))return}if(e===_c.OnLocalInvitationCreated){const e=Ve(),n=t.filter((t=>t.invitedUserId===e.userId));a.data=[...new Set([...n.map((e=>e.invitationId)),...a.data])]}e===_c.OnLocalInvitationCanceled&&(a.data=a.data.filter((e=>e!==t[0].invitationId))),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Ym extends ki{constructor(e,t){const n=O.default(e),a=["invitation","collection",n];super(new Wm(e),n,a,t),this.query=e,this.queryStreamController=new Gm(this.query,this.cacheKey,this.notifyChange.bind(this),Wi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:Pc,action:_c.OnLocalInvitationCreated},{fn:Mc,action:_c.OnLocalInvitationUpdated},{fn:jc,action:_c.OnLocalInvitationCanceled}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["invitation","get",e]))).filter(Ai).map((({data:e})=>Gi(e))))&&void 0!==r?r:[]);(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.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?yt:bt)();return t=t.sort(n),t}}var Xm=Object.freeze({__proto__:null,cancelInvitation:async e=>{var t;const n=Ve();n.log("invitation/cancelInvitation",e);const{data:a}=await n.http.delete(`/api/v1/invitations/${e}`),r=null===(t=Ze(["invitation","get",e]))||void 0===t?void 0:t.data;return Fn("invitation",e),r&&jt("local.invitation.canceled",[r]),a.success},onLocalInvitationCreated:Pc,onLocalInvitationUpdated:Mc,onLocalInvitationCanceled:jc,getMyCommunityInvitations:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`getMyCommunityInvitations: (tmpid: ${s}) > listen`);const o=new Ym(Object.assign(Object.assign({},e),{targetType:"community",statuses:["pending"]}),t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{at(c)})),()=>{a(`getInvitations (tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getInvitations:(e,t)=>{const{_id:n}=Nt();if(!n)throw new Le("The _id has not been defined in ActiveUser",8e5,"error");const{log:a}=Ve(),{targetId:r,targetType:s}=e,o=Date.now();a(`observeInvitations(tmpid: ${o}) > listen for ${s}: ${r}`);const i=[],c=n=>{const a=(Array.isArray(n)?n:[n]).filter((({targetId:t,targetType:n})=>t===e.targetId&&n===e.targetType));(e=>{t(e.map(dl.invitation))})(a)};return"room"===s&&(i.push(yf(c)),i.push(bf(c)),i.push(wf(c)),i.push(If(c))),()=>{a(`getInvitations(tmpid: ${o}) > dispose for ${s}: ${r}`),i.forEach((e=>e()))}}});const Zm=e=>{const t=Ve();return Mt(t,"live_reaction/onLiveReactionCreated","liveReaction.created",(n=>{if(n.reactions.length>0){const a=n.reactions.filter((({userId:e})=>e!==t.userId));e(a)}}))};var eg=Object.freeze({__proto__:null,createReaction:async({referenceId:e,referenceType:t,reactionName:n,streamId:a,roomId:r})=>{const s=Ve();if(s.log("live_reaction/createReaction",{referenceId:e,referenceType:t,reactionName:n,streamId:a,roomId:r}),!a&&!r)throw new Le("You have to specify either streamId or roomId",800110,"error");const o=Ds(),i={reactionName:n,referencePublicId:e,referenceType:t,roomId:r,streamId:a,occurredAt:(new Date).toISOString()};return o.createLiveReaction(i),jt("local.liveReaction.created",[Object.assign(Object.assign({},i),{userId:s.userId,referenceId:e})]),!0},onLiveReactionCreated:Zm,getReactions:(e,t)=>{const{_id:n}=kt();if(!n)throw new Le("The _id has not been defined in ActiveUser",8e5,"error");const{log:a}=Ve();a(`getReactions(tmpid: ${Date.now()}) > listen`);const r=[],s=n=>{(e=>{t(e)})(n.filter((({referenceId:t})=>t===e)))};return r.push(Zm(s)),r.push((e=>{const t=Ve();return Mt(t,"live_reaction/onLiveReactionCreated","local.liveReaction.created",e)})(s)),()=>{r.forEach((e=>e()))}}});const tg=async e=>{const t=Ve();t.log("event/getEvent",e);try{const{data:n}=await t.http.get(`/api/v1/events/${e}`),a=Qc(n),r=t.cache&&Date.now();return t.cache&&Ln(a,{cachedAt:r}),{data:a.events.find((t=>t.eventId===e)),cachedAt:r}}catch(n){if(Oe(null==n?void 0:n.code)){const a=tg.locally(e);if(!a)throw n;const r=Object.assign(Object.assign({},null==a?void 0:a.data),{isDeleted:!0});nt(["event","get",e],r);return{data:r,cachedAt:t.cache&&Date.now()}}throw n}};tg.locally=e=>{const t=Ve();if(t.log("event/getEvent.locally",e),!t.cache)return;const n=Ze(["event","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class ng extends wi{async getRequest(e,t){const{limit:n=de}=e,a=Kn(e,["limit"]),r=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v1/events",{params:Object.assign(Object.assign({},a),{options:r})});return s}}class ag extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.events.map(We("event"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.events.map(We("event"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===Jc.OnEventCreated&&(a.data=[...new Set([t.eventId,...a.data])]),e===Jc.OnEventDeleted&&(a.data=a.data.filter((e=>e!==t.eventId))),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class rg extends ki{constructor(e,t){const n=O.default(e),a=["event","collection",n];super(new ng(e),n,a,t),this.query=e,this.queryStreamController=new ag(this.query,this.cacheKey,this.notifyChange.bind(this),Qc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Yc,action:Jc.OnEventCreated},{fn:Xc,action:Jc.OnEventUpdated},{fn:Zc,action:Jc.OnEventDeleted},{fn:el,action:Jc.OnEventCreated},{fn:tl,action:Jc.OnEventUpdated},{fn:nl,action:Jc.OnEventDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=(null!==(r=s.data.map((e=>Ze(["event","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.event);(this.shouldNotify(o)||"event"!==e)&&this.callback({data:o,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}class sg extends wi{async getRequest(e,t){const{limit:n=de}=e,a=Kn(e,["limit"]),r=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v1/events/me/rsvps",{params:Object.assign(Object.assign({},a),{options:r})});return s}}class og extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ve(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.events.map(We("event"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.events.map(We("event"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===Jc.OnEventCreated){if(Ve().userId!==t.userId)return;a.data=[...new Set([t.eventId,...a.data])]}e===Jc.OnEventDeleted&&(a.data=a.data.filter((e=>e!==t.eventId))),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class ig extends ki{constructor(e,t){const n=O.default(e),a=["event","collection",n];super(new sg(e),n,a,t),this.query=e,this.queryStreamController=new og(this.query,this.cacheKey,this.notifyChange.bind(this),Qc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Yc,action:Jc.OnEventCreated},{fn:Xc,action:Jc.OnEventUpdated},{fn:Zc,action:Jc.OnEventDeleted},{fn:el,action:Jc.OnEventCreated},{fn:tl,action:Jc.OnEventUpdated},{fn:nl,action:Jc.OnEventDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=(null!==(r=s.data.map((e=>Ze(["event","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.event);(this.shouldNotify(o)||"event"!==e)&&this.callback({data:o,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}var cg=Object.freeze({__proto__:null,createEvent:async e=>{const t=Ve();t.log("event/createEvent",e);const{data:n}=await t.http.post("/api/v1/events",e);jt("local.event.created",n);const a=Qc(n),r=t.cache&&Date.now();return t.cache&&Ln(a,{cachedAt:r}),{data:ll(a.events[0]),cachedAt:r}},updateEvent:async(e,t)=>{const n=Ve();n.log("event/updateEvent",e,t);const{data:a}=await n.http.put(`/api/v1/events/${e}`,t);jt("local.event.updated",a);const r=Qc(a),s=n.cache&&Date.now();return n.cache&&Ln(r,{cachedAt:s}),{data:ll(r.events.find((t=>t.eventId===e))),cachedAt:s}},deleteEvent:async e=>{const t=Ve();t.log("event/deleteEvent",e);const n=await tg(e);await t.http.delete(`/api/v1/events/${e}`);const a=Object.assign(Object.assign({},n.data),{isDeleted:!0});nt(["event","get",e],a),jt("local.event.deleted",{users:[],files:[],communities:[],posts:[],rooms:[],events:[a]})},onEventCreated:Yc,onEventUpdated:Xc,onEventDeleted:Zc,onLocalEventCreated:el,onLocalEventUpdated:tl,onLocalEventDeleted:nl,onRSVPCreated:al,onRSVPUpdated:rl,onLocalRSVPCreated:sl,onLocalRSVPUpdated:ol,getEvent:(e,t)=>Ui(e,t,"eventId",tg,[Xc,Zc,tl,nl],{callbackDataSelector:e=>e?ll(e):e}),getEvents:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`getEvents: (tmpid: ${s}) > listen`);const o=new rg(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getEvents (tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getMyEvents:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`getMyEvents: (tmpid: ${s}) > listen`);const o=new ig(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getMyEvents (tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getRSVPs:cl});const lg=async e=>{const t=Ve();let n;t.log("product/getProduct",e),ta("product",e);try{n=(await t.http.get(`/api/v1/products/${encodeURIComponent(e)}`)).data}catch(t){throw Oe(null==t?void 0:t.code)&&Fn("product",e),t}const a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a});const{products:r}=n;return{data:r.find((t=>t.productId===e)),cachedAt:a}};lg.locally=e=>{const t=Ve();if(t.log("product/getProduct.locally",e),!t.cache)return;const n=Ze(["product","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class dg extends wi{async getRequest(e,t){const{limit:n=de}=e,a=Kn(e,["limit"]),r=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v1/products/search",{params:Object.assign(Object.assign({},a),{options:r})});return s}}class ug extends Ci{constructor(e,t,n){super(e,t),this.notifyChange=n}saveToMainDB(e){const t=Ve(),n=t.cache&&Date.now();t.cache&&Ln(e,{cachedAt:n})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.products.map(We("product"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.products.map(We("product"))])]}))}}}class hg extends ki{constructor(e,t){const n=O.default(e),a=["products","collection",n];super(new dg(e),n,a,t),this.query=e,this.queryStreamController=new ug(this.query,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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 a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=null!==(r=s.data.map((e=>Ze(["product","get",e]))).filter(Ai).map((({data:e})=>e)).map(dl.product))&&void 0!==r?r:[];(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var pg=Object.freeze({__proto__:null,getProduct:(e,t)=>Ui(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?dl.product(n):n}))}),"productId",lg,[]),searchProducts:(e,t,n)=>{const{log:a,cache:r}=Ve();r||console.log(pe);const s=Date.now();a(`searchProducts(tmpid: ${s}) > listen`);const o=new hg(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`searchProducts(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}}});return e.API_REGIONS=tn,e.AdRepository=Fm,e.AmityAttachmentProductTags=class{constructor(){this.map=new Map}get(e){return this.map.get(e)||[]}set(e,t){this.map.set(e,t)}},e.CategoryRepository=Zh,e.ChannelRepository=Fu,e.Client=ai,e.CommentRepository=vp,e.CommunityPostSettingMaps=j,e.CommunityPostSettings=M,e.CommunityRepository=Gh,e.ContentFeedType=x,e.DefaultCommunityPostSetting=U,e.EventRepository=cg,e.FeedRepository=Qp,e.FileRepository=Bl,e.FileType=k,e.GET_WATCHER_URLS=Li,e.InvitationRepository=Xm,e.LiveReactionRepository=eg,e.LiveStreamPlayer=cm,e.MessageContentType=N,e.MessageRepository=du,e.PollRepository=rm,e.PostContentType=B,e.PostRepository=Lf,e.PostStructureType=L,e.ProductRepository=pg,e.ReactionRepository=jd,e.RoomPresenceRepository=em,e.RoomRepository=Df,e.StoryRepository=Nm,e.StreamRepository=Wf,e.SubChannelRepository=yu,e.UserRepository=Dl,e.VERSION=le,e.VideoResolution=A,e.VideoSize=E,e.VideoTranscodingStatus=_,e.backupCache=async(e="amitySdk",t=(e=>e.offline))=>{const{log:n,cache:a,userId:r}=Ve();if(!a)return!1;n("cache/api/backupCache",{storageKey:e});const s=Object.fromEntries(Object.entries(a.data).filter((([e,n])=>t(n))));return!!Object.keys(s).length&&(localStorage&&await localStorage.setItem(`${e}#${r}`,JSON.stringify(s)),!0)},e.createQuery=xe,e.createReport=async(e,t)=>{const n=Ve();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 Zr(n);Ln(e)}return jt("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 pa(n);Ln(e)}return jt("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 Gl(n);Ln(e)}return jt("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 Ud(n);Ln(e)}return jt("comment.flagged",n),!!n})({client:n,referenceId:t})},e.createUserToken=async(e,t,n)=>{const a=await Un(),r=Dn(),s=hn(an("http",t)),{data:o}=await s.post("/api/v5/sessions",Object.assign(Object.assign({},n),{deviceId:a,deviceInfo:Object.assign(Object.assign({},r),{model:"token management API on TS-SDK"})}),{headers:{"X-API-Key":e}});return{accessToken:o.accessToken}},e.deleteReport=async(e,t)=>{const n=Ve();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 Zr(n);Ln(e)}return jt("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 pa(n);Ln(e)}return jt("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 Gl(n);Ln(e)}return jt("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 Ud(n);Ln(e)}return jt("comment.unflagged",n),!!n})({client:n,referenceId:t})},e.disableCache=()=>{const e=Ve();e.cache&&(e.log("cache/api/disableCache"),delete e.cache)},e.dropFromCache=at,e.enableCache=(e={},t)=>{const n=Ve();n.cache||(n.log("cache/api/enableCache"),n.cache={data:e,persistIf:t})},e.exceedsUntilAtBoundary=Ot,e.filterByChannelMembership=it,e.filterByCommunityMembership=lt,e.filterByFeedType=ct,e.filterByPostDataTypes=dt,e.filterByPropEquality=rt,e.filterByPropInclusion=(e,t,n)=>void 0!==n?e.filter((e=>n.includes(e[t]))):e,e.filterByPropIntersection=ot,e.filterBySearchTerm=ut,e.filterByStringComparePartially=st,e.filterByUntilAt=(e,t,n)=>{const a=new Date(t).valueOf();return"firstCreated"===n?e.filter((e=>new Date(e.createdAt).valueOf()<a)):e.filter((e=>new Date(e.createdAt).valueOf()>a))},e.filterCommentsByBlockUsers=ft,e.filterPostsByBlockUsers=pt,e.getBlockUsersId=ht,e.getChannelTopic=e=>`${e.path}/#`,e.getCommentTopic=({path:e})=>e,e.getCommunityStoriesTopic=({targetId:e,targetType:t})=>{const n=kt();return`${Ft(n)}/social/${t}/${e}/story/#`},e.getCommunityTopic=({path:t},n=e.SubscriptionLevels.COMMUNITY)=>Lt(t,n),e.getLiveReactionTopic=e=>`${e.path}/liveReaction`,e.getLiveStreamTopic=Wt,e.getMarkedMessageTopic=Qt,e.getMarkerUserFeedTopic=()=>{const e=kt();return`${Ft(e)}/marker/user/${e._id}`},e.getMessageTopic=e=>e.path,e.getMyFollowersTopic=Kt,e.getMyFollowingsTopic=$t,e.getNetworkId=Ft,e.getNetworkTopic=zt,e.getPostTopic=({path:t},n=e.SubscriptionLevels.POST)=>"comment"===n?`${t}/comment/+`:t,e.getRole=Fl,e.getRoomStreamerTopic=e=>{const t=Nt();return`${Ft(t)}/room/${e.roomId}/streamer`},e.getRoomWatcherTopic=e=>{const t=Nt();return`${Ft(t)}/room/${e._id}`},e.getSmartFeedChannelTopic=Vt,e.getSmartFeedMessageTopic=Jt,e.getSmartFeedSubChannelTopic=Ht,e.getStoryTopic=({targetId:e,targetType:t,storyId:n})=>{const a=kt();return`${Ft(a)}/social/${t}/${e}/story/${n}/#`},e.getSubChannelTopic=e=>`${e.path}/#`,e.getUserTopic=({path:t},n=e.SubscriptionLevels.USER)=>Lt(n===e.SubscriptionLevels.USER?t:t.replace(/^(\w*)/,"$1/social"),n),e.isAfterBefore=ke,e.isAfterBeforeRaw=Ae,e.isCachable=Ue,e.isFetcher=Pe,e.isFresh=De,e.isLocal=e=>Ue(e)&&-1===(null==e?void 0:e.cachedAt),e.isMutator=Me,e.isOffline=je,e.isPaged=_e,e.isReportedByMe=async(e,t)=>{const n=Ve();return n.log("report/isReportedByMe",{referenceType:e,referenceId:t}),"user"===e?(async({client:e,referenceId:t})=>{var n;const{data:a}=await e.http.get(`/api/v3/users/${t}/isflagbyme`),{result:r,isFlagByMe:s}=null!=a?a:{};return null!==(n=null!=r?r:s)&&void 0!==n&&n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{var n;const{data:a}=await e.http.get(`/api/v5/messages/${encodeURIComponent(t)}/flags`),{result:r,isFlagByMe:s}=null!=a?a:{};return null!==(n=null!=r?r:s)&&void 0!==n&&n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{var n;const{data:a}=await e.http.get(`/api/v3/posts/${t}/isflagbyme`),{result:r,isFlagByMe:s}=null!=a?a:{};return null!==(n=null!=r?r:s)&&void 0!==n&&n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{var n;const{data:a}=await e.http.get(`/api/v3/comments/${t}/isflagbyme`),{result:r,isFlagByMe:s}=null!=a?a:{};return null!==(n=null!=r?r:s)&&void 0!==n&&n})({client:n,referenceId:t})},e.isSkip=Te,e.mergeInCache=tt,e.notificationTray=Jm,e.onChannelMarkerFetched=Jo,e.onFeedMarkerFetched=e=>{const t=Ve();return Mt(t,"feedMarker/onFeedMarkerFetched","local.feedMarker.fetched",(t=>{e(t.feedMarkers[0])}))},e.onFeedMarkerUpdated=e=>{const t=Ve();return Mt(t,"feedMarker/onFeedMarkerUpdated","marker.feed-updated",(t=>{Ln(t),e(t.feedMarkers[0])}))},e.onMessageMarked=Zo,e.onMessageMarkerFetched=Xo,e.onSubChannelMarkerFetched=Wo,e.onSubChannelMarkerUpdated=Go,e.onUserMarkerFetched=Yo,e.onUserMarkerFetchedLegacy=e=>{const t=Ve();return Mt(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers[0])}))},e.pullFromCache=Ze,e.pushToCache=et,e.queryCache=Xe,e.queryOptions=qe,e.queryRoles=Ll,e.restoreCache=async(e="amitySdk")=>{var t;const n=Ve();if(!n.cache)return!1;n.log("cache/api/restoreCache",{storageKey:e});const a=localStorage&&null!==(t=await localStorage.getItem(`${e}#${n.userId}`))&&void 0!==t?t:"{}";let r={};try{r=JSON.parse(a)}catch(e){}return n.cache.data=Object.assign(Object.assign({},r),n.cache.data),!0},e.runQuery=Ne,e.sortByChannelSegment=({channelSegment:e},{channelSegment:t})=>e-t,e.sortByDisplayName=mt,e.sortByFirstCreated=yt,e.sortByFirstUpdated=wt,e.sortByLastActivity=Ct,e.sortByLastCreated=bt,e.sortByLastUpdated=It,e.sortByLocalSortingDate=vt,e.sortByName=gt,e.sortBySegmentNumber=({segmentNumber:e},{segmentNumber:t})=>e-t,e.subscribeTopic=Gt,e.toPage=Re,e.toPageRaw=e=>{if(!e)return;const n=JSON.parse(t.decode(e));return Ae(n)?n:void 0},e.toToken=Ee,e.upsertInCache=nt,e.validateUntilAt=St,e.wipeCache=async(e="amitySdk")=>{const{log:t,cache:n,userId:a}=Ve();return!!n&&(t("cache/api/wipeCache",{storageKey:e}),n.data={},localStorage&&await localStorage.setItem(`${e}#${a}`,"{}"),!0)},Object.defineProperty(e,"__esModule",{value:!0}),e}({},jsBase64,mitt,debug,axios,HttpAgent,AsyncStorage,uuid$1,jwtDecode,reactNative,hash,Hls);
|
|
5
|
+
var a=e("buffer"),r=a.Buffer;function s(e,t){for(var n in e)t[n]=e[n]}function o(e,t,n){return r(e,t,n)}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?t.exports=a:(s(a,n),n.Buffer=o),o.prototype=Object.create(r.prototype),s(r,o),o.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return r(e,t,n)},o.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var a=r(e);return void 0!==t?"string"==typeof n?a.fill(t,n):a.fill(t):a.fill(0),a},o.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r(e)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return a.SlowBuffer(e)}},{buffer:17}],74:[function(e,t,n){function a(e){var t=e._readableState;return t?t.objectMode||"number"==typeof e._duplexState?e.read():e.read(r(t)):null}function r(e){return e.buffer.length?e.buffer.head?e.buffer.head.data.length:e.buffer[0].length:e.length}t.exports=a},{}],75:[function(e,t,n){var a=e("safe-buffer").Buffer,r=a.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function s(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}function o(e){var t=s(e);if("string"!=typeof t&&(a.isEncoding===r||!r(e)))throw new Error("Unknown encoding: "+e);return t||e}function i(e){var t;switch(this.encoding=o(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=a.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 a=t.length-1;if(a<n)return 0;var r=c(t[a]);return r>=0?(r>0&&(e.lastNeed=r-1),r):--a<n||-2===r?0:(r=c(t[a]))>=0?(r>0&&(e.lastNeed=r-2),r):--a<n||-2===r?0:(r=c(t[a]))>=0?(r>0&&(2===r?r=0:e.lastNeed=r-3),r):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 a=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,a),e.toString("utf8",t,a)}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 a=n.charCodeAt(n.length-1);if(a>=55296&&a<=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 a=e("punycode"),r=e("./util");function s(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}n.parse=w,n.resolve=C,n.resolveObject=S,n.format=I,n.Url=s;var o=/^([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&&r.isObject(e)&&e instanceof s)return e;var a=new s;return a.parse(e,t,n),a}function I(e){return r.isString(e)&&(e=w(e)),e instanceof s?e.format():s.prototype.format.call(e)}function C(e,t){return w(e,!1,!0).resolve(t)}function S(e,t){return e?w(e,!1,!0).resolveObject(t):t}s.prototype.parse=function(e,t,n){if(!r.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var s=e.indexOf("?"),i=-1!==s&&s<e.indexOf("#")?"?":"#",l=e.split(i),w=/\\/g;l[0]=l[0].replace(w,"/");var I=e=l.join(i);if(I=I.trim(),!n&&1===e.split("#").length){var C=c.exec(I);if(C)return this.path=I,this.href=I,this.pathname=C[1],C[2]?(this.search=C[2],this.query=t?b.parse(this.search.substr(1)):this.search.substr(1)):t&&(this.search="",this.query={}),this}var S=o.exec(I);if(S){var O=(S=S[0]).toLowerCase();this.protocol=O,I=I.substr(S.length)}if(n||S||I.match(/^\/\/[^@\/]+@[^@\/]+/)){var T="//"===I.substr(0,2);!T||S&&y[S]||(I=I.substr(2),this.slashes=!0)}if(!y[S]&&(T||S&&!v[S])){for(var k,A,_=-1,E=0;E<h.length;E++)-1!==(R=I.indexOf(h[E]))&&(-1===_||R<_)&&(_=R);for(-1!==(A=-1===_?I.lastIndexOf("@"):I.lastIndexOf("@",_))&&(k=I.slice(0,A),I=I.slice(A+1),this.auth=decodeURIComponent(k)),_=-1,E=0;E<u.length;E++){var R;-1!==(R=I.indexOf(u[E]))&&(-1===_||R<_)&&(_=R)}-1===_&&(_=I.length),this.host=I.slice(0,_),I=I.slice(_),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=(E=0,M.length);E<j;E++){var U=M[E];if(U&&!U.match(f)){for(var D="",x=0,q=U.length;x<q;x++)U.charCodeAt(x)>127?D+="x":D+=U[x];if(!D.match(f)){var N=M.slice(0,E),B=M.slice(E+1),L=U.match(m);L&&(N.push(L[1]),B.unshift(L[2])),B.length&&(I="/"+B.join(".")+I),this.hostname=N.join(".");break}}}this.hostname.length>p?this.hostname="":this.hostname=this.hostname.toLowerCase(),P||(this.hostname=a.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),"/"!==I[0]&&(I="/"+I))}if(!g[O])for(E=0,j=d.length;E<j;E++){var $=d[E];if(-1!==I.indexOf($)){var Q=encodeURIComponent($);Q===$&&(Q=escape($)),I=I.split($).join(Q)}}var V=I.indexOf("#");-1!==V&&(this.hash=I.substr(V),I=I.slice(0,V));var z=I.indexOf("?");if(-1!==z?(this.search=I.substr(z),this.query=I.substr(z+1),t&&(this.query=b.parse(this.query)),I=I.slice(0,z)):t&&(this.search="",this.query={}),I&&(this.pathname=I),v[O]&&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},s.prototype.format=function(){var e=this.auth||"";e&&(e=(e=encodeURIComponent(e)).replace(/%3A/i,":"),e+="@");var t=this.protocol||"",n=this.pathname||"",a=this.hash||"",s=!1,o="";this.host?s=e+this.host:this.hostname&&(s=e+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(s+=":"+this.port)),this.query&&r.isObject(this.query)&&Object.keys(this.query).length&&(o=b.stringify(this.query));var i=this.search||o&&"?"+o||"";return t&&":"!==t.substr(-1)&&(t+=":"),this.slashes||(!t||v[t])&&!1!==s?(s="//"+(s||""),n&&"/"!==n.charAt(0)&&(n="/"+n)):s||(s=""),a&&"#"!==a.charAt(0)&&(a="#"+a),i&&"?"!==i.charAt(0)&&(i="?"+i),t+s+(n=n.replace(/[?#]/g,(function(e){return encodeURIComponent(e)})))+(i=i.replace("#","%23"))+a},s.prototype.resolve=function(e){return this.resolveObject(w(e,!1,!0)).format()},s.prototype.resolveObject=function(e){if(r.isString(e)){var t=new s;t.parse(e,!1,!0),e=t}for(var n=new s,a=Object.keys(this),o=0;o<a.length;o++){var i=a[o];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),I=w||b||n.host&&e.pathname,C=I,S=n.pathname&&n.pathname.split("/")||[],O=(f=e.pathname&&e.pathname.split("/")||[],n.protocol&&!v[n.protocol]);if(O&&(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),I=I&&(""===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(!r.isNullOrUndefined(e.search))return O&&(n.hostname=n.host=S.shift(),(E=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=E.shift(),n.host=n.hostname=E.shift())),n.search=e.search,n.query=e.query,r.isNull(n.pathname)&&r.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 T=S.slice(-1)[0],k=(n.host||e.host||S.length>1)&&("."===T||".."===T)||""===T,A=0,_=S.length;_>=0;_--)"."===(T=S[_])?S.splice(_,1):".."===T?(S.splice(_,1),A++):A&&(S.splice(_,1),A--);if(!I&&!C)for(;A--;A)S.unshift("..");!I||""===S[0]||S[0]&&"/"===S[0].charAt(0)||S.unshift(""),k&&"/"!==S.join("/").substr(-1)&&S.push("");var E,R=""===S[0]||S[0]&&"/"===S[0].charAt(0);return O&&(n.hostname=n.host=R?"":S.length?S.shift():"",(E=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=E.shift(),n.host=n.hostname=E.shift())),(I=I||n.host&&S.length)&&!R&&S.unshift(""),S.length?n.pathname=S.join("/"):(n.pathname=null,n.path=null),r.isNull(n.pathname)&&r.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n},s.prototype.parseHost=function(){var e=this.host,t=i.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},{"./util":77,punycode:51,querystring:54}],77:[function(e,t,n){t.exports={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}}},{}],78:[function(e,t,n){(function(e){(function(){function n(e,t){if(a("noDeprecation"))return e;var n=!1;function r(){if(!n){if(a("throwDeprecation"))throw new Error(t);a("traceDeprecation")?console.trace(t):console.warn(t),n=!0}return e.apply(this,arguments)}return r}function a(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!==pn?pn:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],79:[function(e,t,n){function a(e,t){if(e&&t)return a(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 a=e.apply(this,t),r=t[t.length-1];return"function"==typeof a&&a!==r&&Object.keys(r).forEach((function(e){a[e]=r[e]})),a}}t.exports=a},{}],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=r;var a=Object.prototype.hasOwnProperty;function r(){for(var e={},t=0;t<arguments.length;t++){var n=arguments[t];for(var r in n)a.call(n,r)&&(e[r]=n[r])}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 a(e){var t=this;if(t instanceof a||(t=new a),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,r=arguments.length;n<r;n++)t.push(arguments[n]);return t}function r(e,t,n){var a=t===e.head?new i(n,null,t,e):new i(n,t,t.next,e);return null===a.next&&(e.tail=a),null===a.prev&&(e.head=a),e.length++,a}function s(e,t){e.tail=new i(t,e.tail,null,e),e.head||(e.head=e.tail),e.length++}function o(e,t){e.head=new i(t,null,e.head,e),e.tail||(e.tail=e.head),e.length++}function i(e,t,n,a){if(!(this instanceof i))return new i(e,t,n,a);this.list=a,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=a,a.Node=i,a.create=a,a.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},a.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++}},a.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++}},a.prototype.push=function(){for(var e=0,t=arguments.length;e<t;e++)s(this,arguments[e]);return this.length},a.prototype.unshift=function(){for(var e=0,t=arguments.length;e<t;e++)o(this,arguments[e]);return this.length},a.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}},a.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}},a.prototype.forEach=function(e,t){t=t||this;for(var n=this.head,a=0;null!==n;a++)e.call(t,n.value,a,this),n=n.next},a.prototype.forEachReverse=function(e,t){t=t||this;for(var n=this.tail,a=this.length-1;null!==n;a--)e.call(t,n.value,a,this),n=n.prev},a.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},a.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},a.prototype.map=function(e,t){t=t||this;for(var n=new a,r=this.head;null!==r;)n.push(e.call(t,r.value,this)),r=r.next;return n},a.prototype.mapReverse=function(e,t){t=t||this;for(var n=new a,r=this.tail;null!==r;)n.push(e.call(t,r.value,this)),r=r.prev;return n},a.prototype.reduce=function(e,t){var n,a=this.head;if(arguments.length>1)n=t;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");a=this.head.next,n=this.head.value}for(var r=0;null!==a;r++)n=e(n,a.value,r),a=a.next;return n},a.prototype.reduceReverse=function(e,t){var n,a=this.tail;if(arguments.length>1)n=t;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");a=this.tail.prev,n=this.tail.value}for(var r=this.length-1;null!==a;r--)n=e(n,a.value,r),a=a.prev;return n},a.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},a.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},a.prototype.slice=function(e,t){(t=t||this.length)<0&&(t+=this.length),(e=e||0)<0&&(e+=this.length);var n=new a;if(t<e||t<0)return n;e<0&&(e=0),t>this.length&&(t=this.length);for(var r=0,s=this.head;null!==s&&r<e;r++)s=s.next;for(;null!==s&&r<t;r++,s=s.next)n.push(s.value);return n},a.prototype.sliceReverse=function(e,t){(t=t||this.length)<0&&(t+=this.length),(e=e||0)<0&&(e+=this.length);var n=new a;if(t<e||t<0)return n;e<0&&(e=0),t>this.length&&(t=this.length);for(var r=this.length,s=this.tail;null!==s&&r>t;r--)s=s.prev;for(;null!==s&&r>e;r--,s=s.prev)n.push(s.value);return n},a.prototype.splice=function(e,t,...n){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);for(var a=0,s=this.head;null!==s&&a<e;a++)s=s.next;var o=[];for(a=0;s&&a<t;a++)o.push(s.value),s=this.removeNode(s);for(null===s&&(s=this.tail),s!==this.head&&s!==this.tail&&(s=s.prev),a=0;a<n.length;a++)s=r(this,s,n[a]);return o},a.prototype.reverse=function(){for(var e=this.head,t=this.tail,n=e;null!==n;n=n.prev){var a=n.prev;n.prev=n.next,n.next=a}return this.head=t,this.tail=e,this};try{e("./iterator.js")(a)}catch(e){}},{"./iterator.js":82}]},{},[12])(12);var yn=fn(gn.exports);class vn{constructor(){this._sessionState="notLoggedIn",this._listener=new Map}onSessionStateChange(e){return this._listener.set(e,e),()=>{this._listener.delete(e)}}setSessionState(e,t){this._sessionState!==e&&(this._sessionState=e,this._listener.forEach((n=>n(e,t))))}destroy(){this._listener.clear()}}let bn;var wn=()=>(bn||(bn=new vn),bn);const In=e=>wn().onSessionStateChange(e),Cn={[e.AmityAutoSubscription.NETWORK]:[Vt],[e.AmityAutoSubscription.CHAT]:[zt,Ht,Jt],[e.AmityAutoSubscription.LIVESTREAM]:[Wt],[e.AmityAutoSubscription.BLOCK]:[Kt,$t]},Sn=[e.AmityAutoSubscription.CHAT,e.AmityAutoSubscription.NETWORK,e.AmityAutoSubscription.LIVESTREAM,e.AmityAutoSubscription.BLOCK],On=Object.values(e.AmityAutoSubscription);class Tn{constructor(){this.refCountByFeature=new Map,this.disposers=new Map,this.seed()}seed(){this.refCountByFeature.clear(),Sn.forEach((e=>this.refCountByFeature.set(e,1)))}isActive(e){var t;return(null!==(t=this.refCountByFeature.get(e))&&void 0!==t?t:0)>0}subscribeTopics(e){this.unsubscribeTopics(e),this.disposers.set(e,Cn[e].map((e=>Gt(e()))))}unsubscribeTopics(e){var t;(null!==(t=this.disposers.get(e))&&void 0!==t?t:[]).forEach((e=>e())),this.disposers.delete(e)}initialize(){On.forEach((e=>{this.isActive(e)&&this.subscribeTopics(e)}))}subscribe(e){var t;const n=(null!==(t=this.refCountByFeature.get(e))&&void 0!==t?t:0)+1;this.refCountByFeature.set(e,n),1===n&&this.subscribeTopics(e)}unsubscribe(e){var t;const n=Math.max(0,(null!==(t=this.refCountByFeature.get(e))&&void 0!==t?t:0)-1);this.refCountByFeature.set(e,n),0===n&&this.unsubscribeTopics(e)}subscriptions(){return On.map((e=>({feature:e,isActive:this.isActive(e),isSystem:!0,topicCount:Cn[e].length})))}reset(){On.forEach((e=>this.unsubscribeTopics(e))),this.disposers.clear(),this.seed()}}let kn=null;const An=()=>(kn||(kn=new Tn),kn);class _n{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 En=()=>"undefined"!=typeof window&&window.localStorage?window:{localStorage:new _n},Rn=async(e,t)=>"undefined"!=typeof navigator&&"ReactNative"===navigator.product?(await I.default.setItem(e,t),!0):new Promise((n=>{En().localStorage.setItem(e,t),n(!0)})),Pn=async e=>{if("undefined"!=typeof navigator&&"ReactNative"===navigator.product){return await I.default.getItem(e)}return new Promise((t=>{t(En().localStorage.getItem(e))}))},Mn=()=>C.default.v4().toString();let jn=0;if("undefined"!=typeof BroadcastChannel&&"undefined"!=typeof window){const e=Mn(),t={},n=new BroadcastChannel("amity_ts_sdk");let a;n.postMessage({type:"startup",tabId:e}),n.onmessage=({data:r})=>{r.tabId!==e&&("startup"===r.type&&n.postMessage({type:"identify",tabId:e,tabIndex:jn}),"identify"===r.type&&void 0!==r.tabIndex&&r.tabId&&(t[r.tabId]=r.tabIndex,a||(a=setTimeout((()=>{const e=Object.values(t).sort();e&&0!==e.length&&(jn=e.reduce(((e,t)=>e<t?e:t+1),0))}),15))))}}const Un=async()=>{var e;const t=`${null!==(e=ze().prefixDeviceIdKey)&&void 0!==e?e:""}#deviceId`,n=await Pn(t);if(n)return n;const a=`ascWebSdk#${Mn()}`;return await Rn(t,a),a},Dn=()=>{const e=(()=>{var e,t;return(null===(e=Zt.versions)||void 0===e?void 0:e.node)?Zt.versions.node:navigator?`${navigator.product.toLowerCase()}#${null!==(t=navigator.userAgent)&&void 0!==t?t:"unknown_agent"}`:"unknown_model"})();return{kind:"web",model:e,sdkVersion:le}},xn=1e3;var qn;!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"}(qn||(qn={}));const Nn=e=>{let t,n="disconnected";const a=new Set,r=e=>{n!==e&&(n=e,a.forEach((t=>{t(e)})))},s=new Map;function o(e,n,a){const r=(t,r)=>{var i;if(t||128===(null===(i=r[0])||void 0===i?void 0:i.qos))if(n<2){const t=Math.min(2**n*1e3,5e3);console.warn(`Failed to subscribe to topic ${e} (attempt ${n+1}/3). Retrying in ${t}ms.`);const r=setTimeout((()=>{o(e,n+1,a)}),t);s.set(e,{timer:r,callback:a})}else{s.delete(e);const n=t?new Le(t.message,8e5,"error"):new Ke(8e5,"error");console.warn(`Failed to subscribe to topic ${e} after 3 attempts`,n),null==a||a(n)}else s.delete(e),console.log(`Subscribed to topic ${e}`),null==a||a()};t?t.subscribe(e,{qos:0},r):r(new Error("No connection to broker"),[])}return{connect:async function(n){const a=await(async e=>`mqttjs_${await Un()}_${e}_${jn}`)(n.userId);return r("connecting"),t&&(r("disconnecting"),t.removeAllListeners(),t.end(!0)),t=yn.connect(e,function(e){return Object.assign({clean:!1,clientId:`mqttjs_ + ${Math.random().toString(16).substring(2,10)}`,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:xn,resubscribe:!0},e)}({username:n.userId,password:n.accessToken,clientId:a})),t.on("connect",(()=>{t.options.reconnectPeriod=xn,r("connected"),An().initialize()})),t.on("error",(e=>{switch(e.code){case 2:case 134:case 135:t.end(),r("disconnected")}})),t.on("reconnect",(()=>{r("reconnecting"),t.options.reconnectPeriod=Math.min(2*(t.options.reconnectPeriod||xn),8e3)})),t.on("close",(()=>{s.forEach((({timer:e})=>clearTimeout(e))),s.clear()})),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=>(a.add(e),n&&e(n),()=>{a.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,t){return o(e,0,t),()=>this.unsubscribe(e)},unsubscribe(e){var n;const a=s.get(e);if(void 0!==a){clearTimeout(a.timer),s.delete(e);const t=new Le("Subscription retry cancelled due to unsubscribe call",8e5,"error");null===(n=a.callback)||void 0===n||n.call(a,t)}null==t||t.unsubscribe(e)}}},Bn=async()=>{const e=ze(),{data:t}=await e.http.get("/api/v3/network-settings/chat");return t},Ln=(e={},t,n=!0)=>{Object.entries(e).forEach((([e,a])=>{const r=Ge[e];if(!r)return;const s=We(r);s&&a&&a.forEach((e=>{(n?et:nt)([r,"get",s(e)],e,t)}))}))},Fn=(e,t)=>{const{log:n,cache:a}=ze(),r=[e,be,t],s={cachedAt:Date.now()};a&&(n("cache/api/pushToTombstone",{cacheKey:r,data:s}),at([e,"get",t],!0),et(r,s))};function Kn(e,t){var n={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&t.indexOf(a)<0&&(n[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(a=Object.getOwnPropertySymbols(e);r<a.length;r++)t.indexOf(a[r])<0&&Object.prototype.propertyIsEnumerable.call(e,a[r])&&(n[a[r]]=e[a[r]])}return n}const $n=(e,t="userId",n="user")=>{var a;return null!==(a=null==e?void 0:e.map((e=>((e,t="userId",n="user")=>e[n]?e:Object.assign({get[n](){var n;if(!ze().cache)return;return(null===(n=Ze(["user","get",e[t]]))||void 0===n?void 0:n.data)||void 0}},e))(e,t,n))))&&void 0!==a?a:e},Qn=(e,t,n="userId",a="user")=>{const r=e,s=t,o=r[s],i=Kn(r,["symbol"==typeof s?s:s+""]),c=$n(o,n,a);return Object.assign(Object.assign({},i),{[t]:c})};function Vn(e){return e.map((e=>{var{isMentioned:t}=e,n=Kn(e,["isMentioned"]);return Object.assign({hasMentioned:t},n)}))}function zn(e){return Vn(e)}function Hn(e){return Vn(e)}const Jn=e=>{var t,n;return null!==(n=null===(t=Ze(["messagePreviewChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},Wn=e=>new Date(e).getTime(),Gn=e=>{var t,n;return null!==(n=null===(t=Ze(["messagePreviewSubChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},Yn=e=>{var t;const n=e.messagePreviewId?Gn(e.subChannelId):null,a=n?Object.assign(Object.assign({},n),{user:null===(t=Ze(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data}):null;return Object.assign(Object.assign({},e),{messagePreview:a})},Xn=e=>{var t,n;const a={messagePreviewSubChannel:null!==(n=null===(t=e.messages)||void 0===t?void 0:t.map((t=>(t=>{var n;const a=null===(n=e.messageFeeds)||void 0===n?void 0:n.find((e=>e.messageFeedId===t.messageFeedId)),{channelPublicId:r,messageFeedId:s,messageId:o,creatorPublicId:i,data:c,dataType:l,isDeleted:d,segment:u,createdAt:h,updatedAt:p}=t;return{messagePreviewId:o,channelId:r,subChannelId:s,data:c,dataType:l,isDeleted:d,segment:u,creatorId:i,createdAt:h,updatedAt:p,subChannelName:null==a?void 0:a.name,subChannelUpdatedAt:null==a?void 0:a.updatedAt}})(t))))&&void 0!==n?n:[]};Ln(a)};function Zn(e,t){return Object.create(Object.getPrototypeOf(e),Object.assign(Object.assign({},Object.getOwnPropertyDescriptors(e)),Object.getOwnPropertyDescriptors(t)))}function ea(e,t,n){et(["subChannel","get",e],Zn(t,n))}const ta=(e,t)=>{const{log:n,cache:a}=ze(),r=[e,be,t];if(!a)return;n("cache/api/isInTombstone",r);const s=Ze(r),{lifeSpan:o}=qe("cache_then_server",18e4);if(s&&De(s.data,o))throw new Fe("Item not found!",400400,"error")},na=e=>{var t;const n=["channelUnreadInfo","get",e],a=null===(t=Ze(n))||void 0===t?void 0:t.data,r=Xe(["subChannelUnreadInfo","get"]);let s=0,o=!1;if(r&&(null==r?void 0:r.length)>0){const t=null==r?void 0:r.filter((({data:t})=>t.channelId===e&&!t.isDeleted));s=t.map((({data:e})=>e.unreadCount)).reduce(((e,t)=>e+t),0),o=t.some((({data:e})=>e.isMentioned))}const i=Object.assign(Object.assign({},null!=a?a:{channelId:e,createdAt:(new Date).toISOString()}),{updatedAt:(new Date).toISOString(),unreadCount:s,isMentioned:o});return et(n,i),i},aa=e=>{const{feedMarkers:t,userFeedMarkers:n}=e;if(t.length>0&&n.length>0){const e=[],a=new Map(t.map((e=>[e.feedId,e])));n.forEach((t=>{const n=a.get(t.feedId);if(n&&n.feedId===t.feedId){const a=n.lastSegment-t.readToSegment,r={subChannelId:n.feedId,channelId:n.entityId,readToSegment:t.readToSegment,lastSegment:n.lastSegment,lastMentionSegment:t.lastMentionSegment,unreadCount:Math.max(0,a),isMentioned:t.isMentioned,isDeleted:n.isDeleted,createdAt:t.createdAt,updatedAt:t.updatedAt};Ln({subChannelUnreadInfo:[r]}),e.includes(n.entityId)||e.push(n.entityId)}})),e.forEach((e=>{na(e)}))}},ra=async()=>{const e=ze();e.log("channel/getUserMarker");const{data:t}=await e.http.get("/api/v1/markers/userMarker"),{userMarkers:n}=t,a=e.cache&&Date.now();e.cache&&Ln({userMarkers:n},{cachedAt:a}),jt("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:a}},sa=e=>{var t,n;const a=null===(t=Ze(["message","get",e]))||void 0===t?void 0:t.data;if(a)return a;const r=Xe(["message","get"]);return null===(n=null==r?void 0:r.find((({data:t})=>t.messageId===e)))||void 0===n?void 0:n.data},oa=e=>!0===e&&void 0;function ia(e,t,n){var a,r;if(n)return n.hasMentioned;const s=ze();if(s.isUnreadCountEnabled&&s.getMarkerSyncConsistentMode()){const e=null===(a=Ze(["subChannelUnreadInfo","get",t]))||void 0===a?void 0:a.data;return!!e&&e.isMentioned}const o={entityId:e,feedId:t,userId:kt()._id},i=null===(r=Ze(["subChannelMarker","get",We("subChannelMarker")(o)]))||void 0===r?void 0:r.data;return!!i&&i.hasMentioned}const ca=["broadcast","conversation","community"],la=({channelType:e})=>ca.includes(e);function da(e){var{channelId:t,channelPublicId:n,channelType:a,childCount:r,creatorId:s,creatorPublicId:o,lastMessageId:i,lastMessageTimestamp:c,messageFeedId:l,name:d}=e,u=Kn(e,["channelId","channelPublicId","channelType","childCount","creatorId","creatorPublicId","lastMessageId","lastMessageTimestamp","messageFeedId","name"]);return Object.assign(Object.assign({get unreadCount(){return function(e,t,n){var a,r;if(n)return n.unreadCount;const s=ze();if(s.isUnreadCountEnabled&&s.getMarkerSyncConsistentMode()){const e=null===(a=Ze(["subChannelUnreadInfo","get",t]))||void 0===a?void 0:a.data;return e?e.isDeleted?0:e.unreadCount:0}const o={entityId:e,feedId:t,userId:kt()._id},i=null===(r=Ze(["subChannelMarker","get",We("subChannelMarker")(o)]))||void 0===r?void 0:r.data;return i?i.unreadCount:0}(t,l)},get hasMentioned(){return ia(t,l)},get isMentioned(){return ia(t,l)}},u),{channelId:n,creatorId:o,displayName:d,lastActivity:c,latestMessageId:i,messageCount:r,subChannelId:l,isUnreadCountSupport:la({channelType:a})})}function ua(e,t,n){var a;const r=(e=>{var t,n,a;const r=null===(n=null===(t=Xe(["message","get"]))||void 0===t?void 0:t.find((({data:t})=>t.messageId===e.messageId)))||void 0===n?void 0:n.data;return r?Object.assign(Object.assign(Object.assign({},r),e),{referenceId:null!==(a=r.referenceId)&&void 0!==a?a:e.referenceId}):e})(e),{channelPublicId:s,childCount:o,creatorPublicId:i,mentionedUsers:c,messageFeedId:l,myReactions:d,reactionCount:u,reactions:h,referenceId:p,segment:f,messageId:m,creatorId:g}=r,y=Kn(r,["channelPublicId","childCount","creatorPublicId","mentionedUsers","messageFeedId","myReactions","reactionCount","reactions","referenceId","segment","messageId","creatorId"]);let v;p&&(v=Ze(["message","get",p])),v||(v=Ze(["message","get",m]));const b=Object.assign(Object.assign({},y),{messageId:m,channelId:s,channelSegment:f,childrenNumber:o,creatorId:i,creatorPrivateId:e.creatorId,reactions:null!=h?h:{},myReactions:d||(null!==(a=null==v?void 0:v.data.myReactions)&&void 0!==a?a:[]),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 a=ze(),r=sa(e.messageId),s=(null==r?void 0:r.myReactions)||[];Object.assign(e,{myReactions:s});const o=t[0];o&&o.userId===a.userId&&("message.reactionAdded"!==n||s.includes(o.reactionName)||Object.assign(e,{myReactions:[...s,o.reactionName]}),"message.reactionRemoved"===n&&s.includes(o.reactionName)&&Object.assign(e,{myReactions:s.filter((e=>e!==o.reactionName))}))})(b,t,n),b}const ha={},pa=async(e,t)=>{const n=e.messages.map((({messageId:e})=>e));if(n.length>0){Ln({messages:(a=e).messages.map((e=>ua(e,a.reactions)))});const t=n.join("");ha[t]&&clearTimeout(ha[t]),ha[t]=setTimeout((()=>{try{(async e=>{const t=ze();t.log("channel/getMessageMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/messages",{params:{messageIds:e}}),{contentMarkers:a,feedMarkers:r,userMarkers:s}=n,o=t.cache&&Date.now();t.cache&&Ln({contentMarkers:a,feedMarkers:r,userMarkers:s},{cachedAt:o}),jt("local.feedMarker.fetched",{feedMarkers:r}),jt("local.messageMarker.fetched",{contentMarkers:a}),jt("local.userMarker.fetched",{userMarkers:s})})(n)}catch(e){}}),2e3)}var a;const{messageFeeds:r}=e,s=Kn(e,["messageFeeds"]);return r&&r.length>0&&(null==r||r.forEach((e=>{var t,n;const a=null!==(n=null===(t=Ze(["subChannel","get",e.messageFeedId]))||void 0===t?void 0:t.data)&&void 0!==n?n:{},r=Kn(da(e),["unreadCount","isMentioned"]);ea(e.messageFeedId,a,r)}))),Object.assign(Object.assign({},s),{messages:e.messages.map((n=>ua(n,e.reactions,t)))})};function fa(e){var{subChannelId:t,mentionees:n,dataType:a,data:r}=e,s=Kn(e,["subChannelId","mentionees","dataType","data"]);return a===N.IMAGE||a===N.FILE?Object.assign({messageFeedId:t,mentionedUsers:n,dataType:a,data:Object.assign({caption:""},r)},s):Object.assign({messageFeedId:t,mentionedUsers:n,dataType:a,data:r},s)}function ma(e){var{sortBy:t,subChannelId:n,includingTags:a,excludingTags:r,includeDeleted:s,aroundMessageId:o,limit:i,type:c}=e,l=Kn(e,["sortBy","subChannelId","includingTags","excludingTags","includeDeleted","aroundMessageId","limit","type"]);const d=Object.assign(Object.assign({},l),{messageFeedId:n,isDeleted:oa(s),options:{sortBy:t,limit:i||de,around:o}});return a&&(d.includeTags=a),c&&(d.dataType=c),r&&(d.excludeTags=r),d}function ga(e){return Object.assign(Object.assign({},e),{isGlobalBanned:(null==e?void 0:e.isGlobalBan)||!1})}const ya=["broadcast","conversation","community"],va=({channelType:e})=>ya.includes(e),ba=async e=>{const t=e.messageFeeds.filter(va).map((({messageFeedId:e})=>e));if(t.length>0){(e=>{Ln({messageFeeds:e.messageFeeds.map((e=>da(e)))})})(e);try{await(async(e,t={limit:100})=>{const n=ze();n.log("channel/getSubChannelMarkers",e,t);const{data:a}=await n.http.get("/api/v1/markers/message-feeds",{params:{messageFeedIds:e,options:{token:Ee(t,"skiplimit")}}}),{paging:r}=a,s=Kn(a,["paging"]),{userEntityMarkers:o,userFeedMarkers:i,userMarkers:c,feedMarkers:l}=s;n.isUnreadCountEnabled&&n.getMarkerSyncConsistentMode()&&aa({feedMarkers:l,userFeedMarkers:i});const d=zn(o),u=Hn(i),h=n.cache&&Date.now();n.cache&&Ln({userEntityMarkers:d,userFeedMarkers:u,userMarkers:c},{cachedAt:h}),jt("local.channelMarker.fetched",{userEntityMarkers:d}),jt("local.subChannelMarker.fetched",{userFeedMarkers:u}),jt("local.userMarker.fetched",{userMarkers:c});const p=Re(r.next);return{data:u,cachedAt:h,prevPage:Re(r.previous),nextPage:p}})(t)}catch(e){}}Xn(e);const n=e.messageFeeds.map(da),a=e.messages.map((e=>ua(e))),r=e.users.map(ga);return Object.assign(Object.assign({},e),{messageFeeds:n,messages:a,users:r})};const wa=async e=>{const t=ze();t.log("channel/getSubChannel",e),ta("subChannel",e);try{const n=await t.http.get(`/api/v5/message-feeds/${encodeURIComponent(e)}`),a=await ba(n.data),r=t.cache&&Date.now();return t.cache&&Ln(a,{cachedAt:r}),jt("local.message-feed.fetched",a),{data:a.messageFeeds[0],cachedAt:r}}catch(t){throw Oe(null==t?void 0:t.code)&&Fn("subChannel",e),t}};wa.locally=e=>{const t=ze();if(t.log("channel/getSubChannel.locally",e),!t.cache)return;const n=Ze(["subChannel","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Ia=async e=>{var t;let n=null===(t=Ze(["subChannel","get",e]))||void 0===t?void 0:t.data;return n||(n=(await wa(e)).data),n},Ca=async e=>{const t=await(async()=>ze().getMessagePreviewSetting(!1))(),{channelId:n,messageId:a,creatorId:r,createdAt:s,updatedAt:o,data:i,dataType:c,subChannelId:l,channelSegment:d,isDeleted:u}=e,h=await Ia(l);"no-message-preview"!==t?(e=>{var t;const n=null===(t=Ze(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;return!n||n.segment<=e.channelSegment||Wn(n.createdAt)<=Wn(e.createdAt)})(e)&&(et(["messagePreviewSubChannel","get",e.subChannelId],{channelId:n,creatorId:r,messagePreviewId:a,createdAt:s,updatedAt:o,subChannelId:l,data:i,dataType:c,segment:d,isDeleted:u,subChannelUpdatedAt:null==h?void 0:h.updatedAt,subChannelName:null==h?void 0:h.displayName}),ea(e.subChannelId,h,{lastActivity:s,messagePreviewId:a})):Wn(h.lastActivity)<Wn(s)&&ea(e.subChannelId,h,{lastActivity:s})},Sa=async e=>{var t;const{channelId:n,messageId:a,creatorId:r,createdAt:s,updatedAt:o,data:i,dataType:c,subChannelId:l,channelSegment:d,isDeleted:u}=e,h=null===(t=Ze(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await Ia(l);et(["messagePreviewSubChannel","get",e.subChannelId],{channelId:n,creatorId:r,messagePreviewId:a,createdAt:s,updatedAt:o,subChannelId:l,data:i,dataType:c,segment:d,isDeleted:u,subChannelUpdatedAt:t.updatedAt,subChannelName:h.subChannelName})}},Oa=async e=>{const{channelId:t,messageId:n,creatorId:a,createdAt:r,updatedAt:s,data:o,dataType:i,subChannelId:c,channelSegment:l,isDeleted:d}=e;if((e=>{var t;const n=null===(t=Ze(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;return!n||Wn(n.createdAt)<=Wn(e.createdAt)})(e)){const u=await Ia(c);et(["messagePreviewChannel","get",e.channelId],{channelId:t,creatorId:a,messagePreviewId:n,createdAt:r,updatedAt:s,subChannelId:c,data:o,dataType:i,segment:l,isDeleted:d,subChannelUpdatedAt:null==u?void 0:u.updatedAt,subChannelName:null==u?void 0:u.displayName})}},Ta=async e=>{var t;const{channelId:n,messageId:a,creatorId:r,createdAt:s,updatedAt:o,data:i,dataType:c,subChannelId:l,channelSegment:d,isDeleted:u}=e,h=null===(t=Ze(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await Ia(l);et(["messagePreviewChannel","get",e.channelId],{channelId:n,creatorId:r,messagePreviewId:a,createdAt:s,updatedAt:o,subChannelId:l,data:i,dataType:c,segment:d,isDeleted:u,subChannelUpdatedAt:t.updatedAt,subChannelName:h.subChannelName})}},ka=async e=>{var t,n,a,r;const{channelId:s,subChannelId:o}=e,i=null===(t=Ze(["messagePreviewChannel","get",s]))||void 0===t?void 0:t.data;if((null==i?void 0:i.subChannelId)===o){const e=null===(n=Ze(["subChannel","get",o]))||void 0===n?void 0:n.data;et(["messagePreviewChannel","get",s],Object.assign(Object.assign({},i),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}const c=null===(a=Ze(["messagePreviewSubChannel","get",o]))||void 0===a?void 0:a.data;if(c&&new Date(c.updatedAt).valueOf()>new Date(e.updatedAt).valueOf()){const e=null===(r=Ze(["subChannel","get",o]))||void 0===r?void 0:r.data;et(["messagePreviewSubChannel","get",o],Object.assign(Object.assign({},c),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}},Aa=["broadcast","conversation","community"],_a=({type:e})=>Aa.includes(e);function Ea(e,t={isMessagePreviewUpdated:!0}){var n;let{messagePreviewId:a}=e;const r=null===(n=Ze(["messagePreviewChannel","get",e.channelId]))||void 0===n?void 0:n.data;return(null==r?void 0:r.messagePreviewId)&&!t.isMessagePreviewUpdated&&(a=r.messagePreviewId),Object.assign(Object.assign({},e),{defaultSubChannelId:e.channelInternalId,isUnreadCountSupport:_a(e),messagePreviewId:a})}const Ra=(e,t={isMessagePreviewUpdated:!0})=>{Ln({channels:e.channels.map((e=>Ea(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated})))})},Pa=async(e,t={isMessagePreviewUpdated:!0})=>{const n=ze(),a=await n.getMessagePreviewSetting(!1);if(t.isMessagePreviewUpdated&&"no-message-preview"!==a&&e.messagePreviews&&e.messagePreviews.length>0&&(e=>{var t;const n=(null!==(t=e.messagePreviews)&&void 0!==t?t:[]).map((t=>{var n;const a=null===(n=e.messageFeedsInfo)||void 0===n?void 0:n.find((e=>e.messageFeedId===t.messageFeedId)),{channelPublicId:r,messageFeedId:s,data:o,dataType:i,isDeleted:c,segment:l,creatorPublicId:d,createdAt:u,updatedAt:h}=t;return{channelId:r,subChannelId:s,data:o,dataType:i,isDeleted:c,segment:l,creatorId:d,createdAt:u,updatedAt:h,subChannelName:null==a?void 0:a.name,messagePreviewId:null==a?void 0:a.messagePreviewId,subChannelUpdatedAt:null==a?void 0:a.updatedAt}})).filter((e=>{var t;const n=null===(t=Ze(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;return!n||Wn(n.createdAt)<=Wn(e.createdAt)}));0!==n.length&&Ln({messagePreviewChannel:n})})(e),n.useLegacyUnreadCount)(({currentUserId:e,channels:t,channelUsers:n})=>{var a,r;const s=[];for(let o=0;o<t.length;o+=1)if(_a(t[o])){const i=["channelUnread","get",t[o].channelId],c=n.find((n=>n.channelId===t[o].channelId&&n.userId===e)),l=null===(a=Ze(i))||void 0===a?void 0:a.data,d=Math.max(null!==(r=null==l?void 0:l.lastSegment)&&void 0!==r?r:0,t[o].messageCount);let u=null,h=null,p=0,f=!1;if(c){const e=c.readToSegment,t=c.lastMentionedSegment;u="number"==typeof(null==l?void 0:l.readToSegment)&&("number"!=typeof e||l.readToSegment>e)?l.readToSegment:null!=e?e:null,h="number"==typeof(null==l?void 0:l.lastMentionedSegment)&&("number"!=typeof t||l.lastMentionedSegment>t)?l.lastMentionedSegment:null!=t?t:null;const n=null!=u?u:0;p=Math.max(d-n,0),f="number"==typeof h&&n<h}const m={channelId:t[o].channelId,lastSegment:d,readToSegment:u,lastMentionedSegment:h,unreadCount:p,isMentioned:f,isDeleted:t[o].isDeleted||!1};et(i,m),s.push(m)}s.length>0&&jt("local.channelUnread.updated",s)})({channels:e.channels,channelUsers:e.channelUsers,currentUserId:n.userId});else{const n=e.channels.filter(_a).map((({channelInternalId:e})=>e));if(n.length>0){Ra(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated});try{await(async e=>{const t=ze();t.log("channel/getChannelMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/channels",{params:{channelIds:e}}),{userEntityMarkers:a,userMarkers:r}=n,s=zn(a),o=t.cache&&Date.now();return t.cache&&Ln({userEntityMarkers:s,userMarkers:r},{cachedAt:o}),jt("local.channelMarker.fetched",{userEntityMarkers:s}),jt("local.userMarker.fetched",{userMarkers:r}),{data:s,cachedAt:o}})(n)}catch(e){}}}const r=e.channels.map((e=>Ea(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated}))),s=e.channelUsers.map((e=>{return t=e,Object.assign(Object.assign({},t),{get user(){var e;if(ze().cache)return(null===(e=Ze(["user","get",t.userId]))||void 0===e?void 0:e.data)||void 0}});var t})),o=e.users.map(ga),i=Kn(e,["messageFeedsInfo","messagePreviews"]);return Object.assign(Object.assign({},i),{users:o,channels:r,channelUsers:s})},Ma=async e=>{const t=ze();t.log("channel/getUserMessageFeedMakers",e);const{data:n}=await t.http.get("/api/v1/markers/user-message-feed",{params:{channelIds:e}});return jt("local.userMessageFeedMarker.fetched",{userMessageFeedMarker:n}),n},ja=async e=>{const t=ze(),n=await Ma(e.channels.map((({channelInternalId:e})=>e))),{feedMarkers:a,userFeedMarkers:r}=n;aa({feedMarkers:a,userFeedMarkers:r}),t.log("channel/prepareUnreadCountInfo",e.channels)},Ua=(e,t)=>{var n,a,r,s;const o=ze();return o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()?null!==(a=null===(n=(e=>{var t;return null===(t=Ze(["channelUnreadInfo","get",e]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===n?void 0:n.isMentioned)&&void 0!==a&&a:void 0!==(null==t?void 0:t.hasMentioned)?null==t?void 0:t.hasMentioned:null!==(s=null===(r=(e=>{var t;const n={entityId:e,userId:kt()._id};return null===(t=Ze(["channelMarker","get",We("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===r?void 0:r.hasMentioned)&&void 0!==s&&s},Da=(e,t)=>{var n,a,r,s,o;const i=ze();return i.isUnreadCountEnabled&&i.getMarkerSyncConsistentMode()?null!==(a=null===(n=(e=>{var t;return null===(t=Ze(["channelUnreadInfo","get",e]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===n?void 0:n.unreadCount)&&void 0!==a?a:0:(null==t?void 0:t.isDeleted)?0:null!==(o=null!==(r=null==t?void 0:t.unreadCount)&&void 0!==r?r:null===(s=(e=>{var t;const n={entityId:e,userId:kt()._id};return null===(t=Ze(["channelMarker","get",We("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===s?void 0:s.unreadCount)&&void 0!==o?o:0},xa=e=>{var t;return null===(t=Ze(["channelUnread","get",e]))||void 0===t?void 0:t.data},qa=e=>{const t=ze(),n=Kn(e,["messageCount"]);return Zn(n,{get unreadCount(){var e,t;return null!==(t=null===(e=xa(n.channelId))||void 0===e?void 0:e.unreadCount)&&void 0!==t?t:0},get subChannelsUnreadCount(){return Da(n)},get isMentioned(){var e,a;return t.useLegacyUnreadCount?null!==(a=null===(e=xa(n.channelId))||void 0===e?void 0:e.isMentioned)&&void 0!==a&&a:Ua(n)}})},Na=e=>Object.assign(Object.assign({},e),{get user(){return(()=>{var t;const n=["user","get",e.userId],a=null===(t=Ze(n))||void 0===t?void 0:t.data;return a?qt(a):void 0})()}}),Ba=e=>{const t=ze();t.log("channel/getMyMembership.locally");const n=Ze(["channelUsers","get",`${e}#${t.userId}`]);if(!n)throw new Fe("Item not found!",400400,"error");return{data:n.data,cachedAt:n.cachedAt}};function La(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(!La(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=>La(e[n],t[n])))}const Fa=[];let Ka=null;const $a=e=>{if(0===Fa.length){const e=ze();Ka=Mt(e,"onChannelCreated","channel.created",(async e=>{const t=await Pa(e);Ln(t),Fa.forEach((e=>e(t.channels[0])))}))}return Fa.push(e),()=>(e=>{const t=Fa.indexOf(e);t>-1&&Fa.splice(t,1),0===Fa.length&&(null==Ka||Ka())})(e)},Qa=[],Va=[],za=e=>{const t=ze();if(0===Qa.length){const e=async e=>{const t=await Pa(e);Ln(t),Qa.forEach((e=>e(t.channels[0])))};Va.push(Mt(t,"onChannelUpdated","channel.updated",e)),Va.push(Mt(t,"onChannelUpdated","local.channel.updated",(e=>Qa.forEach((t=>t(e.channels[0]))))))}return Qa.push(e),()=>(e=>{const t=Qa.indexOf(e);t>-1&&Qa.splice(t,1),0===Qa.length&&Va.forEach((e=>e()))})(e)},Ha=e=>{const t=Xe(["subChannelUnreadInfo","get"]);if(t){(null==t?void 0:t.filter((({data:t})=>t.channelId===e))).forEach((({key:e,data:t})=>{et(e,Object.assign(Object.assign({},t),{isDeleted:!0}))}))}},Ja=e=>{var t;const n=["channelUnreadInfo","get",e];(null===(t=Ze(n))||void 0===t?void 0:t.data)&&at(n)},Wa=[];let Ga=null;const Ya=e=>{if(0===Wa.length){const e=ze(),t=async t=>{const n=await Pa(t),a=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,r=e.useLegacyUnreadCount;n.channels.forEach((e=>{if(a)Ha(e.channelId),Ja(e.channelId);else if(r){const t=["channelUnread","get",e.channelId],n=Ze(t);n&&et(t,Object.assign(Object.assign({},n),{isDeleted:!0}))}})),Ln(n),Wa.forEach((e=>e(n.channels[0])))};Ga=Mt(e,"onChannelDeleted","channel.deleted",t)}return Wa.push(e),()=>(e=>{const t=Wa.indexOf(e);t>-1&&Wa.splice(t,1),0===Wa.length&&(null==Ga||Ga())})(e)},Xa=[];let Za=null;const er=e=>{if(0===Xa.length){const e=ze();Za=Mt(e,"onChannelJoined","channel.joined",(async e=>{const t=await Pa(e),{channels:n,channelUsers:a}=t;Ln(t),Xa.forEach((e=>e(n[0],a[0])))}))}return Xa.push(e),()=>(e=>{const t=Xa.indexOf(e);t>-1&&Xa.splice(t,1),0===Xa.length&&(null==Za||Za())})(e)},tr=[];let nr=null;const ar=e=>{if(0===tr.length){const e=ze(),t=async t=>{const{userId:n}=ze(),{channelUsers:a}=t,r=a.some((e=>e.userId===n)),s=await Pa(t,{isMessagePreviewUpdated:r}),o=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,i=e.useLegacyUnreadCount;r&&s.channels.forEach((e=>{o?(Ha(e.channelId),Ja(e.channelId)):i&&at(["channelUnread","get",e.channelId])}));const{channels:c,channelUsers:l}=s;Ln(s),tr.forEach((e=>e(c[0],l[0])))};nr=Mt(e,"onChannelLeft","channel.left",t)}return tr.push(e),()=>(e=>{const t=tr.indexOf(e);t>-1&&tr.splice(t,1),0===tr.length&&(null==nr||nr())})(e)},rr=[];let sr=null;const or=e=>{if(0===rr.length){const e=ze(),t=async e=>{var t;nt(["channel","get",e.channelId],{isMuted:Date.parse(e.muteTimeout)>Date.now()});const n=null===(t=Ze(["channel","get",e.channelId]))||void 0===t?void 0:t.data;n&&rr.forEach((e=>e(n)))};sr=Mt(e,"onChannelMute","channel.setMuted",t)}return rr.push(e),()=>(e=>{const t=rr.indexOf(e);t>-1&&rr.splice(t,1),0===rr.length&&(null==sr||sr())})(e)},ir=[];let cr=null;const lr=e=>{if(0===ir.length){const e=ze();cr=Mt(e,"onChannelMemberAdded","channel.membersAdded",(async e=>{const t=await Pa(e),{channels:n,channelUsers:a}=t;Ln(t),ir.forEach((e=>e(n[0],a.find((e=>"member"===e.membership)))))}))}return ir.push(e),()=>(e=>{const t=ir.indexOf(e);t>-1&&ir.splice(t,1),0===ir.length&&(null==cr||cr())})(e)},dr=[];let ur=null;const hr=e=>{if(0===dr.length){const e=ze();ur=Mt(e,"onChannelMemberRemoved","channel.membersRemoved",(async e=>{const t=await Pa(e),{channels:n,channelUsers:a}=t;Ln(t),dr.forEach((e=>e(n[0],a[0])))}))}return dr.push(e),()=>(e=>{const t=dr.indexOf(e);t>-1&&dr.splice(t,1),0===dr.length&&(null==ur||ur())})(e)},pr=[];let fr=null;const mr=e=>{const t=ze();return fr=Mt(t,"onChannelMemberBanned","channel.banned",(async e=>{const n=await Pa(e),{channels:a,channelUsers:r}=n,s=r.some((e=>"banned"===e.membership&&e.userId===t.userId));t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&s&&n.channels.forEach((e=>{Ha(e.channelId),Ja(e.channelId)})),Ln(n),pr.forEach((e=>e(a[0],r.find((e=>"banned"===e.membership)))))})),pr.push(e),()=>(e=>{const t=pr.indexOf(e);t>-1&&pr.splice(t,1),0===pr.length&&(null==fr||fr())})(e)},gr=[];let yr=null;const vr=e=>{if(0===gr.length){const e=ze();yr=Mt(e,"onChannelMemberUnbanned","channel.unbanned",(async e=>{const t=await Pa(e),{channels:n,channelUsers:a}=t;Ln(t),gr.forEach((e=>e(n[0],a.find((e=>"none"===e.membership)))))}))}return gr.push(e),()=>(e=>{const t=gr.indexOf(e);t>-1&&gr.splice(t,1),0===gr.length&&(null==yr||yr())})(e)},br=[];let wr=null;const Ir=e=>{if(0===br.length){const e=ze();wr=Mt(e,"onChannelMemberRoleAdded","local.channel-moderator.role-added",(async e=>{const{channels:t,channelUsers:n}=e;br.forEach((e=>e(t[0],n.find((e=>"member"===e.membership)))))}))}return br.push(e),()=>(e=>{const t=br.indexOf(e);t>-1&&br.splice(t,1),0===br.length&&(null==wr||wr())})(e)},Cr=[];let Sr=null;const Or=e=>{if(0===Cr.length){const e=ze();Sr=Mt(e,"onChannelMemberRoleRemoved","local.channel-moderator.role-removed",(async e=>{const{channels:t,channelUsers:n}=e;Cr.forEach((e=>e(t[0],n.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==Sr||Sr())})(e)},Tr=e=>{const t=ze();return Mt(t,"onChannelArchived","local.channel.archived",(async t=>{e(t)}))},kr=e=>{const t=ze();return Mt(t,"onChannelUnarchived","local.channel.unarchived",(async t=>{e(t)}))},Ar=[];let _r=null;const Er=e=>{if(0===Ar.length){const e=ze(),t=async e=>{var t,n,a;e.userIds.forEach((t=>nt(["channelUsers","get",`${e.channelId}#${t}`],{isMuted:Date.parse(e.muteTimeout)>Date.now()})));const r=null===(n=null===(t=Xe(["channel","get"]))||void 0===t?void 0:t.find((({data:t})=>t.channelPublicId===e.channelId)))||void 0===n?void 0:n.data,s=null===(a=Ze(["channelUsers","get",`${e.channelId}#${e.userIds[0]}`]))||void 0===a?void 0:a.data;r&&s&&Ar.forEach((e=>e(r,s)))};_r=Mt(e,"onChannelUserMute","channel.setMutedUsers",t)}return Ar.push(e),()=>(e=>{const t=Ar.indexOf(e);t>-1&&Ar.splice(t,1),0===Ar.length&&(null==_r||_r())})(e)},Rr=e=>{var t;let n=[];if(["conversation","community"].includes(e.type)){const a=Xe(["channelUsers","get"]);a&&(null==a?void 0:a.length)>0&&(n=(null!==(t=null==a?void 0:a.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})=>Na(e))))}return Zn(e,{markAsRead:()=>(async e=>{const t=ze();t.log("channel/markAsRead",e);const{data:n}=await t.http.put(`/api/v1/markers/channels/${e}/mark-read`),{userMarkers:a,userEntityMarkers:r,userFeedMarkers:s}=n,o=Kn(n,["userMarkers","userEntityMarkers","userFeedMarkers"]),i=t.cache&&Date.now(),c=zn(r),l=Hn(s);return t.cache&&Ln(Object.assign({userMarkers:a,userEntityMarkers:c,userFeedMarkers:l},o),{cachedAt:i}),jt("local.channelMarker.updated",{userEntityMarkers:c}),jt("local.subChannelMarker.updated",{userFeedMarkers:l}),!0})(e.channelInternalId),previewMembers:n,myMembership:t=>((e,t)=>{const{_id:n}=kt();if(!n)throw new Le("The _id has not been defined in ActiveUser",8e5,"error");const{log:a,cache:r}=ze();r||console.log("This observable object need the cache data!"),a(`liveMymembership(tmpid: ${Date.now()}) > listen`);const s=[];let o=!1;const i=e=>{t(Object.assign(Object.assign({},e),{data:e.data?Na(e.data):e.data}))},c=(t,n)=>{const{data:a}=Ba(e);La(void 0,a)||i({loading:!1,data:a})};return s.push(mr(c)),s.push(vr(c)),s.push(Er(c)),(()=>{const t=xe((async()=>Ba(e)));Ne(t,(({error:e,data:t,loading:n,origin:a,cachedAt:r})=>{r===me?(i({data:t,origin:a,loading:!1,error:new Fe(fe,800800,"error")}),o=!0,s.forEach((e=>e()))):o||i({loading:n,data:t,origin:a,error:e}),e&&s.forEach((e=>e()))}))})(),()=>{s.forEach((e=>e()))}})(e.channelId,t),get avatar(){var t;if(!e.avatarFileId)return;return null===(t=Ze(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}})},Pr=e=>Rr(qa((e=>{var t;const n=e.messagePreviewId?Jn(e.channelId):null,a=null===(t=Ze(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data,r=n?Object.assign(Object.assign({},n),{user:a?qt(a):void 0}):null;return Object.assign(Object.assign({},e),{messagePreview:r})})(e))),Mr=async e=>{const t=ze();t.log("channel/getChannelByIds",e);const n=e.map((e=>encodeURIComponent(e)));let a;try{a=(await t.http.get("/api/v3/channels/list",{params:{channelIds:n}})).data}catch(t){throw e.forEach((e=>{Oe(null==t?void 0:t.code)&&Fn("channel",e)})),t}const r=await Pa(a);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await ja(a);const s=t.cache&&Date.now();return t.cache&&Ln(r,{cachedAt:s}),jt("local.channel.fetched",r.channels),{data:r.channels.map((e=>Pr(e))),cachedAt:s}};Mr.locally=e=>{var t,n;const a=ze();if(a.log("channel/getChannelByIds.locally",e),!a.cache)return;const r=null===(t=Xe(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!r||(null==r?void 0:r.length)<e.length)return;const s=r.map((({data:e})=>e)),o=null===(n=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0];return{data:s.map((e=>Pr(e))),cachedAt:o.cachedAt}};const jr=(e,t)=>{const n=setInterval(e,t);return()=>clearInterval(n)};let Ur=!1;const Dr={},xr=async()=>{const e=Object.entries(Dr).filter((([,e])=>e)).map((([e])=>e));return 0!==e.length&&(async e=>{const t=ze();t.log("subChannel/readingAPI",e);const{data:n}=await t.http.post("/api/v1/markers/message-feeds/reading",{messageFeedIds:e}),{userEntityMarkers:a,userFeedMarkers:r,feedMarkers:s,userMarkers:o}=n,i=zn(a),c=Hn(r),l=t.cache&&Date.now();return t.cache&&Ln({userEntityMarkers:i,userFeedMarkers:c,feedMarkers:s,userMarkers:o},{cachedAt:l}),jt("local.feedMarker.fetched",{feedMarkers:s}),jt("local.channelMarker.fetched",{userEntityMarkers:i}),jt("local.subChannelMarker.fetched",{userFeedMarkers:c}),jt("local.userMarker.fetched",{userMarkers:o}),!0})(e)},qr=()=>{Ur=!1},Nr=()=>(Ur=!0,In((e=>{"notLoggedIn"===e&&qr()})),()=>{qr()});jr((async()=>{Ur&&await xr()}),3e4);const Br=async e=>{const t=ze();t.log("channel/getSubChannels",e);const n=await t.http.get("/api/v5/message-feeds/list",{params:{messageFeedIds:e.map(encodeURIComponent)}}),a=await ba(n.data),r=t.cache&&Date.now();return t.cache&&Ln(a,{cachedAt:r}),jt("local.message-feed.fetched",a),{data:a.messageFeeds,cachedAt:r}};Br.locally=e=>{var t;const n=ze();if(n.log("channel/getSubChannels.locally",e),!n.cache)return;const a=e.map((e=>Ze(["subChannel","get",e]))).filter(Boolean);if((null==a?void 0:a.length)<e.length)return;return{data:a.map((({data:e})=>e)),cachedAt:(null===(t=a.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0]).cachedAt}};const Lr=async(e=!0)=>{var t;const n=null===(t=Ze(["MessagePreviewSetting"]))||void 0===t?void 0:t.data;if(!e&&n)return n;const a=await Bn();var r;return(r=a).messagePreview.enabled?r.messagePreview.isIncludeDeleted?"message-preview-include-deleted":"message-preview-not-include-deleted":"no-message-preview"},Fr=async()=>{var e;const t=await Lr();if(t===(null===(e=Ze(["MessagePreviewSetting"]))||void 0===e?void 0:e.data))return;et(["MessagePreviewSetting"],t);const n=[],a=[];if("no-message-preview"===t){const e=Xe(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{at(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&a.push(t.subChannelId)}))}else if("message-preview-not-include-deleted"===t){const e=Xe(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{(null==t?void 0:t.isDeleted)&&(at(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&a.push(t.subChannelId))})),0!==n.length&&await Mr(n),0!==a.length&&await Br(a)}},Kr=async()=>{const e=ze(),{data:t}=await e.http.get("/api/v3/network-settings/social");return t.socialNetworkSetting},$r=async()=>{const e=ze(),{data:t}=await e.http.get("/api/v3/network-settings/users");return t},Qr=async()=>{const e=ze(),{data:t}=await e.http.get("/api/v3/network-settings/product");return t},Vr=async()=>{var e,t;const n=ze(),{data:a}=await n.http.get("/api/v3/network-settings/for-you-feed");return{forYouFeed:{enabled:null!==(t=null===(e=a.forYouFeed)||void 0===e?void 0:e.enabled)&&void 0!==t&&t}}},zr=(e,t)=>{var n;const a=null===(n=Ze(["user","get",e]))||void 0===n?void 0:n.data;return!!a&&a.permissions.some((e=>e===t))},Hr=e=>{const{userId:t}=ze();return{currentUser:()=>zr(t,e),community:n=>((e,t,n)=>{var a;if(!e)return!1;const r=null===(a=Ze(["communityUsers","get",`${n}#${e}`]))||void 0===a?void 0:a.data;return!!r&&(!!r.permissions.some((e=>e===t))||zr(e,t))})(t,e,n),channel:n=>((e,t,n)=>{var a;if(!e)return!1;const r=null===(a=Ze(["channelUsers","get",`${n}#${e}`]))||void 0===a?void 0:a.data;return!!r&&(!!r.permissions.some((e=>e===t))||zr(e,t))})(t,e,n)}},Jr=async e=>{const t=ze();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},Wr=async e=>{const t=ze();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},Gr=async()=>{const e=ze(),{data:t}=await e.http.get("/api/v3/network-settings/feed-setting");return Object.fromEntries(t.feedSettings.map((({feedType:e,contentSettings:t})=>[e,t])))},Yr={notLoggedIn:["establishing"],terminated:["establishing"],establishing:["notLoggedIn","established"],established:["notLoggedIn","terminated","tokenExpired","establishing"],tokenExpired:["establishing"]},Xr=(e,t)=>{const n=ze();n.log("client/api/setSessionState",e,t);const{sessionState:a}=n;if(a===e)return!1;if(!((e,t)=>Yr[e].includes(t))(a,e))throw new Le(`Session state cannot change from ${a} to ${e}`,8e5,"error");return n.sessionState=e,wn().setSessionState(e,t),!0};function Zr(e){return{users:e.users.map(ga),files:e.files}}const es=async e=>{const t=ze();Xr("establishing");const{accessToken:n,users:a,expiresAt:r,issuedAt:s,userType:o,files:i}=await(async({params:e,options:t})=>{const n=ze();n.log("client/api/getToken",e);const a=Dn(),{data:r}=await n.http.post("/api/v5/sessions",Object.assign(Object.assign({},e),{deviceInfo:a}),{headers:{"X-API-Key":n.apiKey,"set-access-token-cookie":(null==t?void 0:t.setAccessTokenCookie)||!1}});return r})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:r,isGlobalBanned:!1,isUserDeleted:!1},t.upload.defaults.headers.common.Authorization=`Bearer ${n}`,t.upload.defaults.metadata={tokenExpiry:r,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:s,expiresAt:r},Xr("established"),Ln(Zr({users:a,files:i})),{accessToken:n,users:a,userType:o}},ts=async e=>{const t=ze();Xr("establishing");const{accessToken:n,users:a,expiresAt:r,issuedAt:s,userType:o,files:i}=await(async({params:e,options:t})=>{const n=ze();n.log("client/api/getVisitorToken",e);const a=Dn(),{data:r}=await n.http.post("/api/v5/sessions/visitor",Object.assign(Object.assign({},e),{deviceInfo:a}),{headers:{"X-API-Key":n.apiKey,"set-access-token-cookie":(null==t?void 0:t.setAccessTokenCookie)||!1}});return r})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:r,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:s,expiresAt:r},Xr("established"),Ln(Zr({users:a,files:i})),{accessToken:n,users:a,userType:o}},ns=async()=>{var e;const t=ze();return t.log("client/api/disconnectClient"),t.mqtt&&t.mqtt.connected&&t.mqtt.disconnect(),"established"===t.sessionState&&Xr("notLoggedIn"),t.emitter.all.clear(),null===(e=t.mqtt)||void 0===e||e.removeAllListeners(),t.userId=void 0,t.token=void 0,t.loginType=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},as=e=>{const t=ze();Xr("terminated",e),t.http.defaults.metadata&&("globalBan"===e&&(t.http.defaults.metadata.isGlobalBanned=!0),"userDeleted"===e&&(t.http.defaults.metadata.isUserDeleted=!0)),t.sessionHandler=void 0,ns()};let rs=null;const ss=e=>{rs=e},os=({user:e,userType:t})=>{At(e),ss(t)},is=(e,t)=>{const n=ze();return Mt(n,e,e,(e=>{const a=Zr(e);n.cache&&Ln(a),t(a.users[0])}))},cs=e=>is("user.deleted",e),ls=["analytic","normal-priority"],ds=["analytic","high-priority"],us=async e=>{const t=ze(),n={activities:e};await t.http.post("/api/v1/analytics/activities",n)};class hs{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=Ze(ls);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await us(t),at(ls)}catch(e){this.stop(),at(ls)}}async syncHighPriorityCapturedEvent(){try{const e=Ze(ds);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await us(t),at(ds)}catch(e){this.stop(),at(ds)}}}class ps{constructor(){this._expireTime=5e3,this._poolLimit=1e3,this._recentViewed={},this._recentHighPriorityViewed={},this._throttleStoryTimer=void 0,this._bufferNewSeenStoryReferenceIds=[]}isAbleToEnqueue({uniqueId:e,expireTime:t,isHighPriority:n=!1}){const a=new Date,r=n?this._recentHighPriorityViewed[e]:this._recentViewed[e];if(!r)return!0;return!(a.getTime()-r.getTime()<t)}markAs({uniqueId:e,contentId:t,contentType:n,activityType:a,metadata:r}){if(!this.isAbleToEnqueue({uniqueId:e,expireTime:this._expireTime}))return;const s=new Date,o={event:[]},i=Ze(ls);(null==i?void 0:i.data)&&(o.event=i.data.event),o.event.length>=this._poolLimit&&o.event.shift();const c={contentId:t,contentType:n,activityType:a,timestamp:s.toISOString()};r&&(c.metadata=r),o.event.push(c),nt(ls,o),this._recentViewed[e]=s}markPostAsViewed(e){this.markAs({uniqueId:`post.${e}`,contentId:e,contentType:"post",activityType:"view"})}markPostAsMeaningfullyViewed(e,t){var n;const a=null===(n=Ze(["feedMetadata","get",e]))||void 0===n?void 0:n.data,r={};void 0!==t&&(r.feedRenderPosition=t),a&&(r.feedSnapshotPosition=a.feedSnapshotPosition,r.feedInjectionType=a.feedInjectionType,r.feedRelevanceScore=a.feedRelevanceScore,r.feedPopularityScore=a.feedPopularityScore,r.feedFreshnessScore=a.feedFreshnessScore,r.feedAffinityScore=a.feedAffinityScore,r.feedFinalScore=a.feedFinalScore,r.feedMmrPenalty=a.feedMmrPenalty),this.markAs({uniqueId:`post.${e}.meaningfulView`,contentId:e,contentType:"post",activityType:"meaningfulView",metadata:Object.keys(r).length>0?r:void 0})}markStory(e,t){if(!e.expiresAt)return;const n=new Date,a=new Date(e.expiresAt);if(!this.isAbleToEnqueue({uniqueId:e.storyId,expireTime:a.getTime(),isHighPriority:!0}))return;const r={event:[]},s=Ze(ds);if((null==s?void 0:s.data)&&(r.event=s.data.event),r.event.length>=this._poolLimit&&r.event.shift(),r.event.push({contentId:e.storyId,contentType:"story",activityType:t,timestamp:n.toISOString()}),nt(ds,r),this._recentHighPriorityViewed[e.storyId]=n,"linkClicked"===t)return;et(["story-seen","get",e.storyId],(new Date).toISOString());const o=Ze(["story-last-seen",e.targetId]);(null==o?void 0:o.data)?new Date(o.data).getTime()<new Date(e.expiresAt).getTime()&&et(["story-last-seen",e.targetId],e.expiresAt):et(["story-last-seen",e.targetId],e.expiresAt),this._bufferNewSeenStoryReferenceIds.push(e.referenceId),this._throttleStoryTimer||(this._throttleStoryTimer=setTimeout((()=>{clearTimeout(this._throttleStoryTimer),jt("local.story.reload",{referenceIds:this._bufferNewSeenStoryReferenceIds}),this._bufferNewSeenStoryReferenceIds=[]}),300))}resetAllBuckets(){this._recentViewed={},this._recentHighPriorityViewed={},at(ls),at(ds)}markStoryAsViewed(e){this.markStory(e,"view")}markStoryAsClicked(e){this.markStory(e,"linkClicked")}markAdAsViewed(e,t){const n={placement:t},a="view";this.markAs({uniqueId:`${e.adId}.view.${t}`,contentId:e.adId,contentType:"ad",activityType:a,metadata:n})}markAdAsClicked(e,t){const n={placement:t},a="linkClicked";this.markAs({uniqueId:`${e.adId}.linkClicked.${t}`,contentId:e.adId,contentType:"ad",activityType:a,metadata:n})}markProductAsClicked(e,t,n,a){const r={location:t,sourceType:n,sourceId:a},s="linkClicked";this.markAs({uniqueId:`${e.productId}.linkClicked.${t}`,contentId:e.productId,contentType:"product",activityType:s,metadata:r})}markProductAsViewed(e,t,n,a){const r={location:t,sourceType:n,sourceId:a},s="view";this.markAs({uniqueId:`${e.productId}.view.${t}`,contentId:e.productId,contentType:"product",activityType:s,metadata:r})}}class fs{constructor(){this._client=ze(),this._eventCapturer=new ps,this._eventSyncer=new hs}markPostAsViewed(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markPostAsViewed(e)}markPostAsMeaningfullyViewed(e,t){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markPostAsMeaningfullyViewed(e,t)}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)}markProductAsClicked(e,t,n,a){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markProductAsClicked(e,t,n,a)}markProductAsViewed(e,t,n,a){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markProductAsViewed(e,t,n,a)}established(){this._eventSyncer.start()}handleTokenExpired(){this._stopAndDestroy()}destroy(){this._stopAndDestroy()}_stopAndDestroy(){this._eventSyncer.stop(),this._eventCapturer.resetAllBuckets()}}let ms;var gs=()=>(ms||(ms=new fs),ms),ys=()=>{const e=gs();return e.established(),In((t=>{"established"===t?e.established():e.handleTokenExpired()})),()=>{e.destroy()}};class vs{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=ze(),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=Xe(["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=Ze(["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=ze();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 a=["readReceipt",e[n].channelId],r=null===(t=Ze(a))||void 0===t?void 0:t.data;et(a,Object.assign(Object.assign({},r),{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 a=["channelUnread","get",e],r=null===(n=Ze(a))||void 0===n?void 0:n.data;r&&("number"!=typeof r.readToSegment||t>r.readToSegment)&&(r.readToSegment=t,r.unreadCount=Math.max(r.lastSegment-t,0),et(a,r),jt("local.channelUnread.updated",[r])),this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const a=null===(n=Ze(["readReceipt",e]))||void 0===n?void 0:n.data;if(a){if(a.latestSegment<t)et(["readReceipt",e],Object.assign(Object.assign({},a),{latestSegment:t}));else if(a.latestSyncSegment>=t)return}else{et(["readReceipt",e],{channelId:e,latestSegment:t,latestSyncSegment:0})}let r=this.getSyncJob(e);null===r||"syncing"===r.syncState?(r={channelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(r)):r.segment<t&&(r.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 bs=null;var ws=()=>(bs||(bs=new vs),bs),Is=()=>{const e=ws();return e.startSyncReadReceipt(),In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};class Cs{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=ze(),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=Xe(["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=Ze(["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:a,segment:r}=n,s=await(async({subChannelId:e,readToSegment:t})=>{const n=ze();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:a,readToSegment:r});if(s){this.removeSynedReceipt(e.subChannelId,e.segment);const n=null===(t=Ze(["legacyReadReceipt",a]))||void 0===t?void 0:t.data;et(["legacyReadReceipt",a],Object.assign(Object.assign({},n),{latestSyncSegment:r}))}else s||(n.retryCount>this.MAX_RETRY?this.removeJobFromQueue(n):(n.retryCount+=1,n.syncState="create"))}removeSynedReceipt(e,t){this.jobQueue.forEach((n=>{n.subChannelId===e&&n.segment<=t&&this.removeJobFromQueue(n)}))}startObservingReadReceiptQueue(){this.client.isUnreadCountEnabled&&(this.isActive=!0,this.startSyncReadReceipt())}stopObservingReadReceiptQueue(){this.isActive=!1;this.jobQueue.map((e=>"syncing"===e.syncState?Object.assign(Object.assign({},e),{syncState:"create"}):e)),this.timer&&clearInterval(this.timer)}onSessionEstablished(){this.startObservingReadReceiptQueue()}onSessionDestroyed(){this.stopObservingReadReceiptQueue(),this.jobQueue=[]}onTokenExpired(){this.stopObservingReadReceiptQueue()}onNetworkOffline(){this.stopObservingReadReceiptQueue()}onNetworkOnline(){this.startObservingReadReceiptQueue()}markRead(e,t){var n;const a=["subChannelUnreadInfo","get",e],r=null===(n=Ze(a))||void 0===n?void 0:n.data;if(r&&t>r.readToSegment){r.readToSegment=t,r.unreadCount=Math.max(r.lastSegment-t,0);const e=na(r.channelId);jt("local.channelUnreadInfo.updated",e),et(a,r),jt("local.subChannelUnread.updated",r)}this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const a=null===(n=Ze(["legacyReadReceipt",e]))||void 0===n?void 0:n.data;if(a){if(a.latestSegment<t)et(["legacyReadReceipt",e],Object.assign(Object.assign({},a),{latestSegment:t}));else if(a.latestSyncSegment>=t)return}else{et(["legacyReadReceipt",e],{subChannelId:e,latestSegment:t,latestSyncSegment:0})}let r=this.getSyncJob(e);null===r||"syncing"===r.syncState?(r={subChannelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(r)):r.segment<t&&(r.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 Ss=null;var Os=()=>(Ss||(Ss=new Cs),Ss),Ts=()=>{const e=Os();return e.startSyncReadReceipt(),In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};const ks=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")},As=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")},_s=async e=>{const t=ze();t.log("channel/getChannelByIds",e);const n=e.map((e=>encodeURIComponent(e)));let a;try{a=(await t.http.get("/api/v3/channels/list",{params:{channelIds:n}})).data}catch(t){throw e.forEach((e=>{Oe(null==t?void 0:t.code)&&Fn("channel",e)})),t}const r=await Pa(a);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await ja(a);const s=t.cache&&Date.now();return t.cache&&Ln(r,{cachedAt:s}),jt("local.channel.fetched",r.channels),{data:r.channels,cachedAt:s}};_s.locally=e=>{var t,n;const a=ze();if(a.log("channel/getChannelByIds.locally",e),!a.cache)return;const r=null===(t=Xe(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!r||(null==r?void 0:r.length)<e.length)return;return{data:r.map((({data:e})=>e)),cachedAt:(null===(n=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0]).cachedAt}};class Es{constructor(){this.TIMER_INTERVAL_MS=ge,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(ks((()=>{this.isConnected=!0}))),this.connectionListener.push(As((()=>{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,a;await _s(e);const r=null!==(a=null===(n=null===(t=Xe(["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!==a?a:[];jt("local.channel.resolved",r)})(e),t.length>0&&(async e=>{const t=await Ma(e),{feedMarkers:n,userFeedMarkers:a}=t;aa({feedMarkers:n,userFeedMarkers:a}),jt("local.userMessageFeedMarkers.resolved",{feedMarkers:n,userFeedMarkers:a})})(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 Rs=null;var Ps=()=>(Rs||(Rs=new Es),Rs),Ms=()=>{const e=Ps();return e.startResolver(),In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};class js{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(ks((()=>{this.isConnected=!0}))),this.connectionListener.push(As((()=>{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{roomId:n,streamId:a}=t,r=Kn(t,["roomId","streamId"]),s=a?"liveStream":"room",o=null!=a?a:n;return e[o]||(e[o]={referenceType:s,reactions:[]}),e[o].reactions.push(r),e}),{});Object.entries(t).forEach((([t,n])=>{(async({reactions:e,liveStreamId:t,roomId:n})=>{const a=ze();a.log("live_reaction/addReaction",e);const{data:r}=await a.http.post("/api/v1/reactions/live",{liveStreamId:t,reactions:e,roomId:n})})({["room"===n.referenceType?"roomId":"liveStreamId"]:t,reactions:e})})),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 Us;var Ds=()=>(Us||(Us=new js),Us);function xs(e){const{users:t,follows:n}=e,a=Kn(e,["users","follows"]);return Object.assign(Object.assign({},a),{follows:n.map((e=>{const n=t.find((t=>t.userId===e.from));return Object.assign(Object.assign({},e),{user:ga(n)})})),users:t.map(ga)})}class qs{constructor(){this.lastFetchedAt=null}onSessionEstablished(){}onSessionDestroyed(){this.lastFetchedAt=null}onTokenExpired(){}isCacheExpired(){return null===this.lastFetchedAt||Date.now()-this.lastFetchedAt>3e5}async ensureFetched(){if(!this.isCacheExpired())return;const e=ze(),{data:t}=await e.http.get("/api/v4/me/user-blocks",{params:{options:{limit:100},isDeleted:!1}}),n=e.cache&&Date.now(),a=xs(t);e.cache&&Ln(a,{cachedAt:n}),this.lastFetchedAt=Date.now()}getCachedUsers(){var e;const t=ze();if(!t.cache)return[];const{userId:n}=t;return(null!==(e=Xe(["follow","get"]))&&void 0!==e?e:[]).map((e=>e.data)).filter((e=>"blocked"===(null==e?void 0:e.status)&&e.from===n)).sort(((e,t)=>{var n,a;return(null!==(n=e.updatedAt)&&void 0!==n?n:"")<(null!==(a=t.updatedAt)&&void 0!==a?a:"")?1:-1})).map((e=>{var t;return null===(t=Ze(["user","get",e.to]))||void 0===t?void 0:t.data})).filter((e=>null!=e&&!0!==e.isDeleted)).slice(0,100).map(qt)}}let Ns=null;var Bs=()=>(Ns||(Ns=new qs),Ns);function Ls(e){const{users:t,follows:n}=e,a=Kn(e,["users","follows"]);return Object.assign(Object.assign({},a),{follows:n.map((e=>{const n=t.find((t=>t.userId===e.from));return Object.assign(Object.assign({},e),{user:ga(n)})})),users:t.map(ga)})}class Fs{constructor(){this.lastFetchedAt=null}onSessionEstablished(){}onSessionDestroyed(){this.lastFetchedAt=null}onTokenExpired(){}isCacheExpired(){return null===this.lastFetchedAt||Date.now()-this.lastFetchedAt>3e5}async ensureFetched(){if(!this.isCacheExpired())return;const e=ze(),{data:t}=await e.http.get("/api/v4/me/blockers",{params:{options:{limit:100},isDeleted:!1}}),n=e.cache&&Date.now(),a=Ls(t);e.cache&&Ln(a,{cachedAt:n}),this.lastFetchedAt=Date.now()}getCachedUsers(){var e;const t=ze();if(!t.cache)return[];const{userId:n}=t;return(null!==(e=Xe(["follow","get"]))&&void 0!==e?e:[]).map((e=>e.data)).filter((e=>"blocked"===(null==e?void 0:e.status)&&e.to===n)).sort(((e,t)=>{var n,a;return(null!==(n=e.updatedAt)&&void 0!==n?n:"")<(null!==(a=t.updatedAt)&&void 0!==a?a:"")?1:-1})).map((e=>{var t;return null===(t=Ze(["user","get",e.from]))||void 0===t?void 0:t.data})).filter((e=>null!=e&&!0!==e.isDeleted)).slice(0,100).map(qt)}}let Ks=null;var $s=()=>(Ks||(Ks=new Fs),Ks);function Qs(e){const{users:t,follows:n}=e,a=Kn(e,["users","follows"]);return Object.assign(Object.assign({},a),{follows:n,users:t.map(ga)})}function Vs(e){const{users:t,follows:n}=e,a=Kn(e,["users","follows"]);return Object.assign(Object.assign({},a),{follows:n,users:t.map(ga)})}function zs(e){const{follows:t}=e,n=Kn(e,["follows"]);return Object.assign(Object.assign({},n),{follows:t})}const Hs=(e,t)=>{const n=ze();return Mt(n,e,e,(e=>{const a=Qs(e);n.cache&&Ln(a),t(a.follows[0])}))},Js=e=>Hs("user.didBlock",e),Ws=e=>Hs("user.didUnblock",e);class Gs{constructor(e,t){this.networkId=e,this.userId=t}static current(){try{const e=Nt();if(!e)return null;const t=Ft(e),{userId:n}=e;return t&&n?new Gs(t,n):null}catch(e){return null}}static isExpired(e){return Date.now()>=e}static clearOnLogout(){return In((e=>{var t;"terminated"===e&&(null===(t=Gs.current())||void 0===t||t.clear())}))}get key(){return`amity:forYouFeed:cursor:${this.networkId}:${this.userId}`}async get(){const e=await Pn(this.key);if(!e)return null;try{const t=JSON.parse(e);return"string"!=typeof(null==t?void 0:t.cursor)||"number"!=typeof(null==t?void 0:t.expiredAt)?null:{cursor:t.cursor,expiredAt:t.expiredAt,reachedEndOfFeed:!0===t.reachedEndOfFeed}}catch(e){return null}}async set(e){await Rn(this.key,JSON.stringify(e))}async markReachedEndOfFeed(e){var t;const n=await this.get();await this.set({cursor:null!==(t=null==n?void 0:n.cursor)&&void 0!==t?t:"",expiredAt:e,reachedEndOfFeed:!0})}async clear(){await Rn(this.key,"")}}const Ys=["disconnected","error","connect_error","reconnect_error","reconnect_failed"],Xs=e=>{const t=ze(),n=Ys.map((n=>Mt(t,`client/onConnectionError(${n})`,n,(t=>{const a=(null==t?void 0:t.code)?new Le(t.message,t.code,"fatal"):new $e(n);e(a)}))));return()=>{n.forEach((e=>e()))}},Zs=e=>{const t=ze();return Mt(t,"client/onConnectionError(user.didGlobalBan)","user.didGlobalBan",e)},eo=e=>{const t=ze();return Mt(t,"client/onTokenExpired","tokenExpired",e)},to=e=>{const t=ze();return Mt(t,"client/onTokenTerminated","tokenTerminated",e)},no=e=>{const t=We("channelMarker")({userId:kt()._id,entityId:e.channelId});at(["channelMarker","get",t],!0)},ao=e=>{const t=ze(),n=[];return n.push(Zs((t=>{as("globalBan"),n.forEach((e=>e())),e()})),to((t=>{as(),n.forEach((e=>e())),e()})),cs((a=>{a.userId===t.userId&&(as("userDeleted"),n.forEach((e=>e())),e())})),eo((e=>{wn().setSessionState(e),ns(),n.forEach((e=>e()))})),Ya(no),mr(no),Nr(),ys(),Ms(),(()=>{const e=Ds();return e.startReactionsSync(),In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=Bs();return In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=$s();return In((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=[Js((()=>{})),Ws((()=>{}))];return()=>e.forEach((e=>e()))})(),In((e=>{"established"!==e&&An().reset()})),Gs.clearOnLogout()),t.useLegacyUnreadCount?n.push(Is()):n.push(Ts()),n};let ro=[];const so=async(e,t,n)=>{const a=ze();let r;a.log("client/api/connectClient",Object.assign({apiKey:a.apiKey,sessionState:a.sessionState},e)),a.userId&&a.userId!==e.userId&&(await ns(),ro.forEach((e=>e())),ro=[]);const s=await Un();try{const{users:n,userType:o}=await es({params:Object.assign(Object.assign({},e),{displayName:null==e?void 0:e.displayName,deviceId:(null==e?void 0:e.deviceId)||s}),options:{setAccessTokenCookie:!0}}),i=n.find((t=>t.userId===e.userId));if(null==i)throw new Le(`${e.userId} has not been founded`,8e5,"error");if(i.isDeleted)return as("userDeleted"),!1;if(i.isGlobalBan)return as("globalBan"),!1;a.userId=i.userId,a.sessionHandler=t,a.loginType="userId",r=a.accessTokenExpiryWatcher(),os({user:i,userType:o})}catch(e){throw wn().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await xt()}(),await Fr(),0===ro.length&&(ro=ao(r)),!0},oo=[],io=async e=>{const t=ze();let n;t.log("client/api/connectClient",Object.assign({apiKey:t.apiKey,sessionState:t.sessionState},e));const a=await Un();let r;try{const{users:s,userType:o}=await ts({params:Object.assign(Object.assign({},e),{deviceId:a}),options:{setAccessTokenCookie:!0}});[r]=s,t.userId=r.userId,t.sessionHandler=e.sessionHandler,t.loginType="userId",n=t.accessTokenExpiryWatcher(),os({user:r,userType:o})}catch(e){throw wn().setSessionState("notLoggedIn"),e}return await Fr(),0===oo.length&&oo.push(to((e=>{as(),oo.forEach((e=>e())),n()})),eo((e=>{wn().setSessionState(e),ns(),oo.forEach((e=>e()))}))),!0},co=()=>{let e,t=!1;const n=ze();n.log("initiating access token renewal");const a=async a=>{const{userId:r,displayName:s}=kt(),o={userId:r,displayName:s,authToken:a,deviceId:await Un()};"tokenExpired"===n.sessionState&&n.sessionHandler?await so(o,n.sessionHandler):await es({params:o,options:{setAccessTokenCookie:!0}}),t=!0,e&&clearTimeout(e)};return{renew:()=>{t?console.log("'renew' method can be called only once per renewal instance"):a()},renewWithAuthToken:e=>{t?console.log("'renewWithAuthToken' method can be called only once per renewal instance"):a(e)},unableToRetrieveAuthToken:()=>{e=setTimeout((()=>{var e;null===(e=n.sessionHandler)||void 0===e||e.sessionWillRenewAccessToken(co())}),ye)},renewWithAuthSignature:a=>{t?console.log("'renew' method can be called only once per renewal instance"):(async({authSignature:a,authSignatureExpiresAt:r})=>{const s=await Un();"tokenExpired"===n.sessionState&&n.sessionHandler?await io({sessionHandler:n.sessionHandler}):await ts({params:{authSignature:a,authSignatureExpiresAt:r,deviceId:s},options:{setAccessTokenCookie:!0}}),t=!0,e&&clearTimeout(e)})(a)},unableToRetrieveAuthSignature:()=>{e=setTimeout((()=>{var e;null===(e=n.sessionHandler)||void 0===e||e.sessionWillRenewAccessToken(co())}),ye)}}},lo=async({token:e,userId:t})=>{const n=ze();await n.http.get("/api/v3/sessions",{headers:{Authorization:`Bearer ${e.accessToken}`}});const{data:{users:a}}=await n.http.get(`/api/v3/users/${t}`,{headers:{Authorization:`Bearer ${e.accessToken}`}}),r=a.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,r},uo=e=>{var t;const n=ze(),a=S.default(e);return(null===(t=null==a?void 0:a.user)||void 0===t?void 0:t.publicUserId)===n.userId};let ho=[];const po=async e=>{var t,n;const a=ze();let r,s;if(a.log("client/api/loginWithAccessToken",{apiKey:a.apiKey,sessionState:a.sessionState}),!e||"string"!=typeof e||""===e.trim())throw new Le("Access token must be a non-empty string",8e5,"error");try{s=S.default(e)}catch(e){throw new Le("Invalid access token format",400100,"error")}const o=(null===(t=null==s?void 0:s.user)||void 0===t?void 0:t.publicUserId)||(null===(n=null==s?void 0:s.user)||void 0===n?void 0:n.userId);if(!o)throw new Le("Access token does not contain userId",400100,"error");if(a.userId){uo(e)||await ns()}try{Xr("establishing");const t={accessToken:e,issuedAt:s.iat?new Date(1e3*s.iat).toISOString():(new Date).toISOString(),expiresAt:new Date(1e3*s.exp).toISOString()},n=await lo({token:t,userId:o});if(null==n)throw Xr("notLoggedIn"),new Le(`User ${o} has not been found`,8e5,"error");if(n.isDeleted)throw Xr("notLoggedIn"),new Le(`User ${o} has been deleted`,8e5,"error");if(n.isGlobalBanned)throw Xr("notLoggedIn"),new Le(`User ${o} is globally banned`,8e5,"error");a.userId=n.userId,a.loginType="accessToken",At(n),r=a.accessTokenExpiryWatcher(),Xr("established")}catch(e){if(Xr("notLoggedIn"),e instanceof Le)throw e;throw new Le((e instanceof Error?e.message:void 0)||"Login with access token failed",400100,"error")}return async function(){await xt()}(),await Fr(),0===ho.length&&(ho=ao(r)),!0},fo=async e=>{var t,n;const a=ze();if(a.log("initiating access token renewal"),!e||"string"!=typeof e||""===e.trim())throw new Le("Access token must be a non-empty string",8e5,"error");let r;try{r=S.default(e)}catch(e){throw new Le("Invalid access token format",400100,"error")}const s=(null===(t=null==r?void 0:r.user)||void 0===t?void 0:t.publicUserId)||(null===(n=null==r?void 0:r.user)||void 0===n?void 0:n.userId);if(!s)throw new Le("Access token does not contain userId",400100,"error");if(a.userId){uo(e)||await ns()}const o={accessToken:e,issuedAt:r.iat?new Date(1e3*r.iat).toISOString():(new Date).toISOString(),expiresAt:new Date(1e3*r.exp).toISOString()};"tokenExpired"===a.sessionState&&a.sessionHandler?await po(e):await lo({token:o,userId:s})},mo=async({useScheduledTask:e=!1})=>{const t=ze();if(t.userId&&t.accessTokenHandler)try{const n=await t.accessTokenHandler.onTokenRenew(t.userId);e?Rt((()=>fo(n))):fo(n)}catch(e){t.log("Proactive token renewal failed, will retry when token expires",e)}},go=3e5,yo=()=>{const e=setInterval((async()=>{const e=ze(),{sessionHandler:t,accessTokenHandler:n,loginType:a}=e;if(!e.token||!e.userId)return;const{issuedAt:r,expiresAt:s}=e.token;if((e=>Date.now()>Date.parse(e)-go)(s))return jt("tokenExpired","tokenExpired"),void("accessToken"===a&&n?await mo({useScheduledTask:!1}):"userId"===a&&t&&Rt((()=>t.sessionWillRenewAccessToken(co()))));(e=>{const{expiresAt:t,issuedAt:n}=e,a=Date.parse(t),r=Date.parse(n),s=Date.now();return s>r+.8*(a-r-go)&&s<a})({expiresAt:s,issuedAt:r})&&("accessToken"===a&&n?await mo({useScheduledTask:!1}):"userId"===a&&t&&t.sessionWillRenewAccessToken(co()))}),ye);return()=>clearInterval(e)},vo=e=>{if(ze().useLegacyUnreadCount){ws().markRead(e.channelId,e.channelSegment)}else{Os().markRead(e.subChannelId,e.channelSegment)}},bo=e=>{const t=ze(),n=kt(),a=[Mt(t,"message/onMessageCreated","message.created",(async a=>{const r=await pa(a);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&a.messages.forEach((e=>{(e=>{var t;const n=ze(),a=["subChannelUnreadInfo","get",e.messageFeedId],r=null===(t=Ze(a))||void 0===t?void 0:t.data;if(!r)return;const s=r.lastSegment<e.segment?e.segment:r.lastSegment,o=s-r.readToSegment;let{lastMentionSegment:i}=r;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({},r),{lastMentionSegment:i,lastSegment:s,isMentioned:!(r.readToSegment>=i),unreadCount:Math.max(o,0)});et(a,c)})(e),na(e.channelId)})),t.useLegacyUnreadCount&&a.messages.forEach((e=>{var n,a,r;const s=null===(n=Ze(["channelUnread","get",e.channelId]))||void 0===n?void 0:n.data;if(!s||s.lastSegment>=e.segment)return;const o=e.segment,i=(null===(a=e.mentionedUsers)||void 0===a?void 0:a.some((e=>"channel"===e.type||"user"===e.type&&t.userId&&e.userPublicIds.includes(t.userId))))?e.segment:s.lastMentionedSegment,c=null!==(r=s.readToSegment)&&void 0!==r?r:0,l=Object.assign(Object.assign({},s),{lastSegment:o,unreadCount:Math.max(o-c,0),lastMentionedSegment:i,isMentioned:"number"==typeof i&&c<i});et(["channelUnread","get",e.channelId],l),jt("local.channelUnread.updated",[l])})),Ln(r),r.messages.forEach((t=>{t.creatorPrivateId===n._id&&vo(t),e(t)}))}))];return()=>{a.forEach((e=>e()))}},wo=e=>{const t=ze(),n=[Mt(t,"message/onMessageCreated","local.message.created",(async t=>(Ln(t),t.messages.forEach((t=>{e(t)})))))];return()=>{n.forEach((e=>e()))}},Io=e=>{const t=ze();return Mt(t,"onSubChannelCreated","message-feed.created",(async n=>{const a=await ba(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&n.messageFeeds.forEach((e=>{(e=>{const{channelId:t,subChannelId:n,createdAt:a,updatedAt:r}=e,s={channelId:t,subChannelId:n,unreadCount:0,readToSegment:0,lastMentionSegment:0,lastSegment:0,isMentioned:!1,isDeleted:!1,createdAt:a,updatedAt:r};et(["subChannelUnreadInfo","get",s.subChannelId],s)})({channelId:e.channelId,subChannelId:e.messageFeedId,createdAt:e.createdAt,updatedAt:e.updatedAt})})),Ln(a),e(a.messageFeeds[0])}))},Co=e=>{const t=ze(),n=[Mt(t,"onSubChannelDeleted","message-feed.deleted",(async n=>{const a=await ba(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&a.messageFeeds.forEach((e=>{(e=>{var t;const n=["subChannelUnreadInfo","get",e],a=null===(t=Ze(n))||void 0===t?void 0:t.data;a&&et(n,Object.assign(Object.assign({},a),{isDeleted:!0}))})(e.subChannelId),na(e.channelId)})),Ln(a),e(a.messageFeeds[0])})),Mt(t,"local.message-feed.deleted","local.message-feed.deleted",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}},So=async e=>{const t=ze();t.log("channel/markerSync");const{data:n}=await t.http.post("/api/v1/markers/sync",{deviceLastSyncAt:e}),{userEntityMarkers:a,userFeedMarkers:r,feedMarkers:s,userMarkers:o}=n,i=zn(a),c=Hn(r),l=t.cache&&Date.now();return t.cache&&Ln({userEntityMarkers:i,userFeedMarkers:c,feedMarkers:s,userMarkers:o},{cachedAt:l}),jt("local.feedMarker.fetched",{feedMarkers:s}),jt("local.channelMarker.fetched",{userEntityMarkers:i}),jt("local.subChannelMarker.fetched",{userFeedMarkers:c}),jt("local.userMarker.fetched",{userMarkers:o}),{data:n,hasMore:n.feedMarkers.length>0}};let Oo=!1,To=[],ko=!1;let Ao=null;let _o=[];const Eo=e=>{_o=e},Ro=async()=>{var e;if(!ko&&0!==_o.length)try{ko=!0,_o=[];const t=await So((null==Ao?new Date:Ao).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)&&(!Ao||e.getTime()>Ao.getTime())&&(Ao=e),t.hasMore&&_o.push("has_more")}catch(e){}finally{ko&&(ko=!1)}};jr((async()=>{Oo&&await Ro()}),2e3);const Po=()=>true,Mo=e=>{var t;const n=ze();if(n.mqtt)return null===(t=n.mqtt)||void 0===t?void 0:t.listen(e)},jo=async()=>{const e=ze(),t=await Un(),{data:{status:n,error:a}}=await e.http.delete("/v1/notification",{params:{deviceId:t},headers:{"X-API-Key":e.apiKey}});if(a)throw new Fe(a,5e5,"error");return"success"===n};let Uo=[];var Do;class xo{constructor(){Do.set(this,e.FileAccessTypeEnum.PUBLIC)}setFileAccessType(e){!function(e,t,n,a,r){if("m"===a)throw new TypeError("Private method is not writable");if("a"===a&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===a?r.call(e,n):r?r.value=n:t.set(e,n)}(this,Do,e,"f")}getFileAccessType(){return function(e,t,n,a){if("a"===n&&!a)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!a:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?a:"a"===n?a.call(e):a?a.value:t.get(e)}(this,Do,"f")}}let qo;Do=new WeakMap;var No=()=>(qo||(qo=new xo),qo);const Bo={[e.AmitySharableContentType.POST]:{key:"posts",placeholder:"postId"},[e.AmitySharableContentType.COMMUNITY]:{key:"communities",placeholder:"communityId"},[e.AmitySharableContentType.USER]:{key:"users",placeholder:"userId"},[e.AmitySharableContentType.LIVESTREAM]:{key:"livestream",placeholder:"livestream"},[e.AmitySharableContentType.EVENT]:{key:"events",placeholder:"eventId"}},Lo=async e=>{const t=ze();Xr("establishing");const{accessToken:n,users:a,expiresAt:r,issuedAt:s,userType:o,files:i}=await(async({params:e,options:t})=>{const n=ze();n.log("client/api/getBotToken");const a=Dn(),{data:r}=await n.http.post("/api/v5/sessions/bot",Object.assign(Object.assign({},e),{deviceInfo:a}),{headers:{"X-API-Key":n.apiKey,"set-access-token-cookie":(null==t?void 0:t.setAccessTokenCookie)||!1}});return r})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:r,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:s,expiresAt:r},Xr("established"),Ln(Zr({users:a,files:i})),{accessToken:n,users:a,userType:o}},Fo=[];function Ko(t,n){return n&&n.length>0?{type:"not",roleIds:n}:t&&t.length>0?{type:e.NotificationRolesFilterTypeEnum.ONLY,roleIds:t}:{type:e.NotificationRolesFilterTypeEnum.ALL}}function $o(t){return(null==t?void 0:t.type)===e.NotificationRolesFilterTypeEnum.ONLY?{listenFromRoleIds:t.roleIds}:{listenFromRoleIds:[]}}class Qo{constructor(e){this.channelId=e}async enable(){const t=ze(),n={level:e.NotificationSettingsLevelEnum.CHANNEL,channelId:this.channelId,isPushNotifiable:!0};await t.http.post("/api/v3/notification/setting",n)}async disable(){const t=ze(),n={level:e.NotificationSettingsLevelEnum.CHANNEL,channelId:this.channelId,isPushNotifiable:!1};await t.http.post("/api/v3/notification/setting",n)}async getSettings(){const t=ze(),{data:n}=await t.http.get(`/api/v3/notification/setting?level=${e.NotificationSettingsLevelEnum.CHANNEL}&channelId=${encodeURIComponent(this.channelId)}`);return{isEnabled:n.isPushNotifiable}}}class Vo{async enable(t){var n;const a=ze(),r=null!==(n=null==t?void 0:t.map((e=>Object.assign({moduleName:e.moduleName,isPushNotifiable:e.isEnabled},$o(e.rolesFilter)))))&&void 0!==n?n:[],s={level:e.NotificationSettingsLevelEnum.USER,isPushNotifiable:!0,notifiableEvents:r};await a.http.post("/api/v3/notification/setting",s)}async disableAllNotifications(){const t=ze(),n={level:e.NotificationSettingsLevelEnum.USER,isPushNotifiable:!1,notifiableEvents:[]};await t.http.post("/api/v3/notification/setting",n)}async getSettings(){var t;const n=ze(),{data:a}=await n.http.get(`/api/v3/notification/setting?level=${e.NotificationSettingsLevelEnum.USER}`),r=Object.values(e.UserNotificationModuleNameEnum),s=(null!==(t=a.notifiableEvents)&&void 0!==t?t:[]).filter((e=>null!=e.moduleName&&r.includes(e.moduleName))).map((e=>({moduleName:e.moduleName,isEnabled:e.isPushNotifiable,rolesFilter:Ko(e.listenFromRoleIds,e.ignoreFromRoleIds)})));return{isEnabled:a.isPushNotifiable,modules:s}}}class zo{constructor(e){this.communityId=e}async enable(t){var n;const a=ze(),r=null!==(n=null==t?void 0:t.map((t=>Object.assign({moduleName:e.UserNotificationModuleNameEnum.SOCIAL,name:t.eventName,isPushNotifiable:t.isEnabled},$o(t.rolesFilter)))))&&void 0!==n?n:[],s={level:e.NotificationSettingsLevelEnum.COMMUNITY,communityId:this.communityId,isPushNotifiable:!0,notifiableEvents:r};await a.http.post("/api/v3/notification/setting",s)}async disable(){const t=ze(),n={level:e.NotificationSettingsLevelEnum.COMMUNITY,communityId:this.communityId,isPushNotifiable:!1,notifiableEvents:[]};await t.http.post("/api/v3/notification/setting",n)}async getSettings(){var t;const n=ze(),{data:a}=await n.http.get(`/api/v3/notification/setting?level=${e.NotificationSettingsLevelEnum.COMMUNITY}&communityId=${encodeURIComponent(this.communityId)}`),r=Object.values(e.CommunityNotificationEventNameEnum),s=(null!==(t=a.notifiableEvents)&&void 0!==t?t:[]).filter((e=>null!=e.name&&r.includes(e.name))).map((e=>({eventName:e.name,isEnabled:e.isPushNotifiable,isNetworkEnabled:e.isNetworkEnabled,rolesFilter:Ko(e.listenFromRoleIds,e.ignoreFromRoleIds)})));return{isEnabled:a.isPushNotifiable,events:s}}}class Ho{user(){return new Vo}community(e){return new zo(e)}channel(e){return new Qo(e)}}const Jo=e=>{const t=ze();return Mt(t,"channelMarker/onChannelMarkerFetched","local.channelMarker.fetched",(t=>{t.userEntityMarkers.forEach((t=>{e(t)}))}))},Wo=e=>{const t=ze();return Mt(t,"subChannelMarker/onSubChannelMarkerFetched","local.subChannelMarker.fetched",(t=>{t.userFeedMarkers.forEach(e)}))},Go=e=>{const t=ze();return Mt(t,"subChannelMarker/onSubChannelMarkerUpdated","local.subChannelMarker.updated",(t=>{e(t.userFeedMarkers)}))},Yo=e=>{const t=ze();return Mt(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers)}))},Xo=e=>{const t=ze();return Mt(t,"messageMarker/onMessageMarkerFetched","local.messageMarker.fetched",(t=>{e(t.contentMarkers[0])}))},Zo=e=>{const t=ze();return Mt(t,"messageMarker/onMessageMarked","marker.marked-message",(t=>{var n,a,r;Ln(t);const s=Xe(["message","collection"]),{contentMarkers:o,feedMarkers:i}=t;if(s&&(null==s?void 0:s.length)>0&&(null==i?void 0:i.length)>0){const e=s.filter((e=>{var t,n;return(null===(n=null===(t=e.data)||void 0===t?void 0:t.query)||void 0===n?void 0:n.subChannelId)===i[0].feedId}));if(e.length>0&&(null==o?void 0:o.length)>0){(null!==(r=null===(a=null===(n=e[0].data)||void 0===n?void 0:n.data)||void 0===a?void 0:a.map((e=>Ze(["message","get",e]))).map((({data:e})=>e)).filter(Boolean))&&void 0!==r?r:[]).forEach((e=>{var t,n;const a=["messageMarker","get",We("messageMarker")({creatorId:e.creatorPrivateId,feedId:e.subChannelId,contentId:e.messageId})],r=null===(t=Ze(a))||void 0===t?void 0:t.data;if(!r)return;const s=o[0].feedId===r.feedId,i=o[0].readCount>r.readCount,c=(null===(n=o[0])||void 0===n?void 0:n.deliveredCount)>r.deliveredCount;if(s){const e=Object.assign(Object.assign({},r),{readCount:i?o[0].readCount:r.readCount,deliveredCount:c?o[0].deliveredCount:r.deliveredCount});et(a,e)}}))}}e(t.contentMarkers[0])}))};function ei(e){return"object"==typeof e&&null!==e}const ti=e=>{if(!ei(e))return e;const t=Object.entries(e).map((([t,n])=>{const a=Object.getOwnPropertyDescriptor(e,t);return"function"==typeof(null==a?void 0:a.get)?[t,a.get.call(e)]:[t,n]}));return Object.fromEntries(t)},ni=e=>{if(!ei(e))return e;const t=Object.entries(e).map((([e,t])=>"function"==typeof t?[e,void 0]:[e,t]));return Object.fromEntries(t)};var ai=Object.freeze({__proto__:null,getActiveClient:ze,getActiveUser:kt,setActiveUser:At,createClient:(e,t=tn.SG,{debugSession:n="amity",apiEndpoint:a,prefixDeviceIdKey:r,rteEnabled:s=!0}={})=>{var o,i,c;const l=(e=>{const t=`${null==e?void 0:e.trim()}`.length>0&&!en,n=v.default(e),a=(e,...a)=>{t&&n(e,a)};return a.__instance__=n,a})(n);l("client/api/createClient",{apiKey:e.replace(/.{5}$/g,"xxxxx"),apiRegion:t});const d=null!==(o=null==a?void 0:a.http)&&void 0!==o?o:an("http",t),u=null!==(i=null==a?void 0:a.upload)&&void 0!==i?i:an("upload",t),h=null!==(c=null==a?void 0:a.mqtt)&&void 0!==c?c:an("mqtt",t),p=hn(d),f=hn(u);let m;s&&(m=Nn(h));const g=y.default(),b={version:`${le}`,apiKey:e,log:l,cache:{data:{}},http:p,ws:undefined,mqtt:m,upload:f,emitter:g,sessionState:"notLoggedIn",accessTokenExpiryWatcher:yo,sessionHandler:undefined,hasPermission:Hr,validateUrls:Jr,validateTexts:Wr,getFeedSettings:Gr,getCoreUserSettings:$r,getSocialSettings:Kr,getChatSettings:Bn,getVisitorDeviceId:Un,getMessagePreviewSetting:Lr,onRTEConnectionStateChange:Mo,use:()=>He(b),isUnreadCountEnabled:!1,useLegacyUnreadCount:!0,getMarkerSyncConsistentMode:Po,getProductCatalogueSetting:Qr,getForYouFeedSetting:Vr,prefixDeviceIdKey:r};try{const t=ze();if(t.apiKey===e)return t;He(b)}catch(e){He(b)}return b},login:so,loginWithAccessToken:po,logout:ns,secureLogout:async()=>{const e=ze();try{await jo()}catch(t){e.log("client/api/secureLogout: failed to unregister push notification",t)}const{data:{success:t}}=await e.http.delete("/api/v4/sessions");if(!t)throw new Error("Failed to logout");return ns()},resumeSession:async(e,t,n)=>{const a=ze();let r;a.log("client/api/resumeSession",Object.assign({apiKey:a.apiKey,sessionState:a.sessionState},e)),a.userId&&(a.userId===e.userId&&uo(e.token.accessToken)?(a.mqtt&&a.mqtt.connected&&a.mqtt.disconnect(),Uo.forEach((e=>e())),Uo=[]):(await ns(),Uo.forEach((e=>e())),Uo=[]));try{Xr("establishing");const n=await lo(e);if(null==n)throw new Le(`${e.userId} has not been found`,8e5,"error");if(n.isDeleted)return as("userDeleted"),!1;if(n.isGlobalBanned)return as("globalBan"),!1;a.userId=n.userId,a.sessionHandler=t,r=a.accessTokenExpiryWatcher(t),At(n)}catch(e){throw wn().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await xt()}(),await Fr(),0===Uo.length&&(Uo.push(Zs((e=>{as("globalBan"),Uo.forEach((e=>e())),r()})),to((e=>{as(),Uo.forEach((e=>e())),r()})),cs((e=>{e.userId===a.userId&&(as("userDeleted"),Uo.forEach((e=>e())),r())})),eo((e=>{wn().setSessionState(e),ns(),Uo.forEach((e=>e()))})),Ya(no),mr(no),Nr(),ys(),Ms()),a.useLegacyUnreadCount?Uo.push(Is()):Uo.push(Ts())),!0},isConnected:()=>{var e,t;const n=ze();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:Gr,renewal:co,markerSync:So,enableUnreadCount:()=>!0,setUploadedFileAccessType:function(e){No().setFileAccessType(e)},registerPushNotification:async e=>{const t=ze();let n;if("ios"!==l.Platform.OS&&"android"!==l.Platform.OS)throw new Qe("Unsupported platform");n=l.Platform.OS;const a=await Un(),{data:{status:r,error:s}}=await t.http.post("/v1/notification",{userId:t.userId,deviceId:a,platform:n,token:e},{headers:{"X-API-Key":t.apiKey}});if(s)throw new Fe(s,5e5,"error");return"success"===r},unregisterPushNotification:jo,onRTEConnectionStateChange:Mo,fetchLinkPreview:async e=>{const t=ze();let n=e;/^https?:\/\//i.test(e)||(n=`https://${e}`);const{data:a}=await t.http.get(`/api/v1/link-preview?url=${encodeURIComponent(n)}`);return a},getLinkPreviewMetadata:async e=>{const t=ze(),{data:n}=await t.http.get(`/api/v1/link-preview?url=${e}`);return n},getSocialSettings:Kr,getShareableLinkConfiguration:async()=>{var e,t;const n=ze(),{data:a}=await n.http.get("/api/v3/network-settings/shareable-deep-links"),r=null!==(e=a.domain)&&void 0!==e?e:"",s=null!==(t=a.patterns)&&void 0!==t?t:{};return{domain:r,patterns:s,isEnabled(e){const{key:t}=Bo[e];return!!r&&!!s[t]},getPattern(e){const{key:t}=Bo[e];return s[t]||null},generateLink(e,t){const{key:n,placeholder:a}=Bo[e];return r&&s[n]?r+s[n].replace(`{${a}}`,t):null}}},getProductCatalogueSetting:Qr,getForYouFeedSetting:Vr,loginAsVisitor:io,loginAsBot:async e=>{const t=ze();let n;t.log("client/api/connectClient",{apiKey:t.apiKey,sessionState:t.sessionState});const a=await Un();let r;try{const{users:s,userType:o}=await Lo({params:{deviceId:a},options:{setAccessTokenCookie:!0}});[r]=s,t.userId=r.userId,t.sessionHandler=e.sessionHandler,t.loginType="userId",n=t.accessTokenExpiryWatcher(),os({user:r,userType:o})}catch(e){throw wn().setSessionState("notLoggedIn"),e}return await Fr(),0===Fo.length&&Fo.push(to((e=>{as(),Fo.forEach((e=>e())),n()})),eo((e=>{wn().setSessionState(e),ns(),Fo.forEach((e=>e()))}))),!0},getCurrentUser:Nt,getCurrentUserType:()=>{if(!rs)throw new Le("Connect client first",8e5,"fatal");return rs},setCurrentUserType:ss,setAccessTokenHandler:e=>{const t=ze();if(t.log("client/api/setAccessTokenHandler",{apiKey:t.apiKey,sessionState:t.sessionState,hasOnTokenRenew:"function"==typeof(null==e?void 0:e.onTokenRenew)}),!e||"function"!=typeof e.onTokenRenew)throw new Error("AccessTokenHandler must implement onTokenRenew() method");t.accessTokenHandler=e},getChatSettings:Bn,getCoreUserSettings:$r,notifications:()=>new Ho,enableAutoSubscriptions:e=>{const t=An();e.forEach((e=>t.subscribe(e)))},disableAutoSubscriptions:e=>{const t=An();e.forEach((e=>t.unsubscribe(e)))},autoSubscriptions:()=>An().subscriptions(),onConnectionError:Xs,onClientDisconnected:e=>Xs((({code:t})=>{800211===t&&e()})),onClientBanned:Zs,onSessionStateChange:In,onNetworkActivities:e=>cn().onNetworkActivities(e),onVisitorUsageLimitReached:e=>{const t=ze();return Mt(t,"client/onVisitorUsageLimitReached","visitorUsageLimitReached",e)},getUserUnread:e=>{const{_id:t}=kt();if(!t)throw new Le("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:a}=ze();a||console.log("For using Live Object feature you need to enable Cache!");n(`liveUserUnread(tmpid: ${Date.now()}) > listen`);const r=[];let s,o=!1;const i=t=>{const{data:n}=t,a=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;s=a?ti(a):a,e({data:a?Object.assign(Object.assign({},a),{isMentioned:a.isMentioned}):a,loading:t.loading,error:t.error})};return r.push(Yo((e=>(e=>{var n;const a=e.filter((e=>t===e.userId)),r=a.reduce(((e,t)=>null==e||new Date(t.lastSyncAt).getTime()>new Date(e.lastSyncAt).getTime()?t:e),null),o={unreadCount:null!==(n=null==r?void 0:r.unreadCount)&&void 0!==n?n:0,isMentioned:a.some((e=>!!e.isMentioned))};La(s,o)||i({loading:!1,data:o})})(e)))),(()=>{const e=xe(ra);Ne(e,(({error:e,data:t,loading:n,origin:a,cachedAt:s})=>{!function(e){return null!=e&&null!=e}(t)?i({loading:n,data:void 0,origin:a,error:e}):(s===me?(i({data:t,origin:a,loading:!1,error:new Fe(fe,800800,"error")}),o=!0,r.forEach((e=>e()))):o||i({loading:n,data:t,origin:a,error:e}),e&&r.forEach((e=>e())))}))})(),()=>{r.forEach((e=>e()))}},getMarkerSyncEvents:()=>_o,setMarkerSyncEvents:Eo,pushMarkerSyncEvent:e=>_o.push(e),markerSyncTrigger:Ro,startMarkerSync:async()=>Promise.resolve(),startUnreadSync:async()=>Promise.resolve(),stopUnreadSync:()=>{Oo=!1,Eo([]),To.forEach((e=>e())),To=[]},getMarkerSyncConsistentMode:Po});const ri=(e,t)=>{const n=ze();return Mt(n,e,e,(e=>{const a=Qs(e);n.cache?(Ln(a),t(a.follows[0])):t(a.follows[0])}))},si=(e,t)=>{const n=ze();return Mt(n,e,e,(e=>{const a=zs(e);n.cache?(Ln(a),t(a.follows[0])):t(a.follows[0])}))},oi=e=>ri("follow.created",e),ii=e=>ri("follow.unfollowed",e),ci=e=>ri("follow.followerDeleted",e),li=e=>ri("follow.requested",e),di=e=>ri("follow.requestCanceled",e),ui=e=>ri("follow.accepted",e),hi=e=>ri("follow.requestDeclined",e),pi=async e=>{var t,n;const a=ze();a.log("follow/getFollowInfo",e);const{data:r}=await a.http.get(a.userId===e?"/api/v4/me/followInfo":`/api/v5/users/${e}/followInfo`),s=a.cache&&Date.now(),o="follows"in r?Object.assign(Object.assign({},r.followCounts[0]),{status:null===(n=null===(t=r.follows)||void 0===t?void 0:t[0])||void 0===n?void 0:n.status}):r.followCounts[0];return a.cache&&et(["followInfo","get",e],o,{cachedAt:s}),{data:o,cachedAt:s}};pi.locally=e=>{const t=ze();if(t.log("follow/getFollowInfo.locally",e),!t.cache)return;const n=Ze(["followInfo","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const fi=e=>{const t=async t=>{const[{data:n},{data:a}]=await Promise.all([pi(t.from),pi(t.to)]);e(n),e(a)},n=[ri("follow.created",t),ri("follow.requested",t),ri("follow.accepted",t),ri("follow.unfollowed",t),ri("follow.requestCanceled",t),ri("follow.requestDeclined",t),ri("follow.followerDeleted",t),si("local.follow.created",t),si("local.follow.requested",t),si("local.follow.accepted",t),si("local.follow.unfollowed",t),si("local.follow.requestDeclined",t)];return()=>{n.forEach((e=>e()))}},mi=e=>si("local.follow.created",e),gi=e=>si("local.follow.unfollowed",e),yi=e=>si("local.follow.requested",e),vi=e=>si("local.follow.accepted",e),bi=e=>si("local.follow.requestDeclined",e);class wi{constructor(e){const{http:t}=ze();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,a,r;if("prev"===e&&!this.previousToken)return;if("next"===e&&!this.nextToken)return;let s;"prev"===e&&(s=this.previousToken),"next"===e&&(s=this.nextToken);const o=await this.getRequest(this.queryParams,s);return"first"===e&&(this.nextToken=null===(t=o.paging)||void 0===t?void 0:t.next,this.previousToken=null===(n=o.paging)||void 0===n?void 0:n.previous),"prev"===e&&(this.previousToken=null===(a=o.paging)||void 0===a?void 0:a.previous),"next"===e&&(this.nextToken=null===(r=o.paging)||void 0===r?void 0:r.next),o}getNextToken(){return this.nextToken}getPrevToken(){return this.previousToken}}class Ii extends wi{async getRequest(e,t){const{limit:n=de,userId:a}=e,r=Kn(e,["limit","userId"]),s=t?{token:t}:{limit:n},o=ze().userId===a?"/api/v4/me/followers":`/api/v4/users/${a}/followers`,{data:i}=await this.http.get(o,{params:Object.assign(Object.assign({},r),{options:s,isDeleted:!1})});return i}}class Ci{constructor(e,t){this.query=e,this.cacheKey=t}}var Si;!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"}(Si||(Si={}));class Oi extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.follows.map(We("follow"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(We("follow"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.to&&a){switch(e){case Si.OnDeclined:case Si.OnCanceled:case Si.OnUnfollowed:case Si.OnDeleted:a.data=a.data.filter((e=>e!==We("follow")(t)));break;case Si.OnRequested:case Si.OnAccepted:case Si.OnFollowed:a.data=[...new Set([We("follow")(t),...a.data])]}et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Ti{constructor(e){const{http:t}=ze();this.queryParams=e,this.http=t}async onFetch(){return await this.getRequest(this.queryParams)}}class ki{constructor(e,t,n,a){this.paginationController=e,this.queryStreamId=t,this.cacheKey=n,this.callback=a}async refresh(){try{let e;if(e=this.paginationController instanceof Ti?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 Ti)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 Ti)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(ti).map(ni);return!La(this.snapshot,t)&&(this.snapshot=t,!0)}getCacheKey(){return this.cacheKey}}function Ai(e){return null!=e}const _i=({userId:e})=>t=>{const n=ze();return Mt(n,"user.deleted","user.deleted",(n=>{const a=Zr(n);Ln(a);const r=Ze(["follow","get",We("follow")({from:a.users[0].userId,to:e})]);r&&t(null==r?void 0:r.data)}))};class Ei extends ki{constructor(e,t){const n=O.default(Object.assign(Object.assign({},e),{type:"follower"})),a=["follow","collection",n];super(new Ii(e),n,a,t),this.query=e,this.queryStreamController=new Oi(this.query,this.cacheKey,this.notifyChange.bind(this),Qs),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:oi,action:Si.OnFollowed},{fn:ii,action:Si.OnUnfollowed},{fn:ui,action:Si.OnAccepted},{fn:hi,action:Si.OnDeclined},{fn:di,action:Si.OnCanceled},{fn:ci,action:Si.OnDeleted},{fn:vi,action:Si.OnAccepted},{fn:bi,action:Si.OnDeclined},{fn:mi,action:Si.OnFollowed},{fn:gi,action:Si.OnUnfollowed},{fn:_i({userId:this.query.userId}),action:Si.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["follow","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]);(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;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=Ze(["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 Ri extends wi{async getRequest(e,t){const{limit:n=de,userId:a}=e,r=Kn(e,["limit","userId"]),s=t?{token:t}:{limit:n},o=ze().userId===a?"/api/v4/me/following":`/api/v4/users/${a}/following`,{data:i}=await this.http.get(o,{params:Object.assign(Object.assign({},r),{options:s,isDeleted:!1})});return i}}class Pi extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.follows.map(We("follow"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(We("follow"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.from&&a){switch(e){case Si.OnDeclined:case Si.OnCanceled:case Si.OnUnfollowed:case Si.OnDeleted:a.data=a.data.filter((e=>e!==We("follow")(t)));break;case Si.OnRequested:case Si.OnAccepted:case Si.OnFollowed:a.data=[...new Set([We("follow")(t),...a.data])]}et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Mi=({userId:e})=>t=>{const n=ze();return Mt(n,"user.deleted","user.deleted",(n=>{const a=Zr(n);Ln(a);const r=Ze(["follow","get",We("follow")({from:e,to:a.users[0].userId})]);r&&t(null==r?void 0:r.data)}))};class ji extends ki{constructor(e,t){const n=O.default(Object.assign(Object.assign({},e),{type:"following"})),a=["follow","collection",n];super(new Ri(e),n,a,t),this.query=e,this.queryStreamController=new Pi(this.query,this.cacheKey,this.notifyChange.bind(this),Vs),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:li,action:Si.OnRequested},{fn:ui,action:Si.OnAccepted},{fn:hi,action:Si.OnDeclined},{fn:di,action:Si.OnCanceled},{fn:oi,action:Si.OnFollowed},{fn:ii,action:Si.OnUnfollowed},{fn:ci,action:Si.OnDeleted},{fn:yi,action:Si.OnRequested},{fn:vi,action:Si.OnAccepted},{fn:bi,action:Si.OnDeclined},{fn:mi,action:Si.OnFollowed},{fn:gi,action:Si.OnUnfollowed},{fn:Mi({userId:this.query.userId}),action:Si.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["follow","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]);(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;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=Ze(["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 Ui=(e,t,n,a,r,s)=>{const{forceDispatch:o,callbackDataSelector:i,callbackFilter:c}=Object.assign({forceDispatch:!1,callbackDataSelector:e=>e},s),{cache:l}=ze();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,a=Kn(e,["data"]);c&&!c(n,d)||t(Object.assign({data:i(n)},a)),d=ti(n)};return h.push(...r.map((t=>t((t=>((t,a=!1)=>{e===t[n]&&(d&&!a&&La(d,t)||p({loading:!1,data:t,origin:"event"}))})(t,o)))))),(()=>{const t=xe(a,e,!0);Ne(t,(({error:e,data:t,loading:n,origin:a,cachedAt:r})=>{r===me?(p({data:t,origin:a,loading:!1,error:new Fe(fe,800800,"error")}),u=!0,h.forEach((e=>e()))):u||p({loading:n,data:t,origin:a,error:e}),e&&h.forEach((e=>e()))}))})(),()=>{h.forEach((e=>e()))}};var Di=Object.freeze({__proto__:null,blockUser:async e=>{const t=ze();t.log("user/blockUser",e);const{data:n}=await t.http.post(`/api/v4/me/user-blocks/${e}`),a=t.cache&&Date.now(),{follows:r,followCounts:s}=n,o={follows:r};t.cache&&(Ln(o,{cachedAt:a}),nt(["followInfo","get",e],s[0],{cachedAt:a}));const i={follows:r.map((e=>{const t=Object.assign(Object.assign({},e),{to:e.from,from:e.to,status:"none"});return"blocked"===e.status?t:e}))},c=zs(i);return jt("local.follow.unfollowed",c),n},unBlockUser:async e=>{const t=ze();t.log("user/unBlockUser",e);const{data:n}=await t.http.delete(`/api/v4/me/user-blocks/${e}`),a=t.cache&&Date.now(),{follows:r,followCounts:s}=n,o={follows:r};t.cache&&(Ln(o,{cachedAt:a}),nt(["followInfo","get",e],s[0],{cachedAt:a}));const i=zs(o);return jt("local.follow.created",i),n},onUserDidBlock:Js,onUserDidUnblock:Ws,follow:async e=>{const t=ze();t.log("follow/follow",e);const{data:n}=await t.http.post(`/api/v4/me/following/${e}`),a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a});const r=zs(n);return"accepted"===n.follows[0].status?jt("local.follow.created",r):jt("local.follow.requested",r),{data:n.follows[0],cachedAt:a}},unfollow:async e=>{const t=ze();t.log("follow/unfollow",e);const{data:n}=await t.http.delete(`/api/v4/me/following/${e}`);t.cache&&Ln(n);const a=zs(n);return jt("local.follow.unfollowed",a),!0},acceptMyFollower:async e=>{const t=ze();t.log("follow/acceptMyFollower",e);const{data:n}=await t.http.post(`/api/v4/me/followers/${e}`);t.cache&&Ln(n);const a=zs(n);return jt("local.follow.accepted",a),!0},declineMyFollower:async e=>{const t=ze();t.log("follow/declineMyFollower",e);const{data:n}=await t.http.delete(`/api/v4/me/followers/${e}`);t.cache&&Ln(n);const a=zs(n);return jt("local.follow.requestDeclined",a),!0},onUserFollowed:oi,onUserUnfollowed:ii,onFollowerDeleted:ci,onFollowerRequested:li,onFollowRequestCanceled:di,onFollowRequestAccepted:ui,onFollowRequestDeclined:hi,onFollowInfoUpdated:fi,onLocalUserFollowed:mi,onLocalUserUnfollowed:gi,onLocalFollowerRequested:yi,onLocalFollowRequestAccepted:vi,onLocalFollowRequestDeclined:bi,getFollowers:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`getFollowers(tmpid: ${s}) > listen`);const o=new Ei(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getFollowers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getFollowings:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log("For using Live Collection feature you need to enable Cache!");const s=Date.now();a(`getFollowings(tmpid: ${s}) > listen`);const o=new ji(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getFollowings(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getFollowInfo:(e,t)=>Ui(e,t,"userId",pi,[fi],{forceDispatch:!0}),getMyFollowInfo:e=>{const{userId:t}=kt();return Ui(t,e,"userId",pi,[fi],{forceDispatch:!0})}});class xi{constructor(e,t,n){this._syncingStoriesCount=0,this._errorStoriesCount=0,this._targetId=e,this._lastStoryExpiresAt=t,this._lastStorySeenExpiresAt=n,this.cacheStoryExpireTime=Ze(["story-expire",this._targetId]),this.cacheStoreSeenTime=Ze(["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=Ze(["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 Ze(["story-sync-state",this._targetId]),this.isContainUnSyncedStory?this.localLastStoryExpires>e&&this.localLastStoryExpires>t:this.lastStoryExpiresAt>e&&this.lastStoryExpiresAt>t}getTotalStoryByStatus(){const e=Xe(["story","get"]);if(!e)return this._errorStoriesCount=0,void(this._syncingStoriesCount=0);const t=e.reduce(((e,t)=>{const{data:{targetId:n,syncState:a,isDeleted:r}}=t;return n!==this._targetId||r||(e[a]+=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 qi=e=>{const{targetType:t,targetId:n,lastStoryExpiresAt:a,lastStorySeenExpiresAt:r,targetUpdatedAt:s,localFilter:o}=e,i=new xi(n,a,r);return{targetType:t,targetId:n,lastStoryExpiresAt:a,updatedAt:s,hasUnseen:i.getHasUnseenFlag(),syncingStoriesCount:i.syncingStoriesCount,failedStoriesCount:i.failedStoriesCount,localFilter:o,localLastExpires:i.localLastStoryExpires,localLastSeen:i.localLastStorySeenExpiresAt,localSortingDate:i.getLocalLastSortingDate()}},Ni=async e=>{const t=ze();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:a}=e,r=Kn(e,["isPublic"]);n=await t.http.post("/api/v3/channels",Object.assign(Object.assign({},r),{isPublic:"community"===(null==e?void 0:e.type)?a:void 0}))}const a=await Pa(n.data),r=t.cache&&Date.now();t.cache&&Ln(a,{cachedAt:r});const{channels:s}=a;return{data:Pr(s[0]),cachedAt:r}},Bi=async e=>{const t=ze();let n;t.log("channel/getChannel",e),ta("channel",e);try{const{data:a}=await t.http.get(`/api/v3/channels/${encodeURIComponent(e)}`);n=await Pa(a),t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&ja(a)}catch(t){throw Oe(null==t?void 0:t.code)&&Fn("channel",e),t}const a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a});const{channels:r}=n;return{data:r.find((t=>t.channelId===e)),cachedAt:a}};Bi.locally=e=>{var t;const n=ze();if(n.log("channel/getChannel.locally",e),!n.cache)return;const a=null===(t=Xe(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.channelPublicId===e));return a&&0!==(null==a?void 0:a.length)?{data:a[0].data,cachedAt:a[0].cachedAt}:void 0};const Li=Symbol("getWatcherUrls"),Fi=e=>Object.assign(Object.assign({},e),{get moderation(){var t;return null===(t=Ze(["streamModeration","get",e.streamId]))||void 0===t?void 0:t.data},get post(){var t;if("post"===e.referenceType)return null===(t=Ze(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=Ze(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;return null===(t=Ze(["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=Ze(["stream","get",e]))||void 0===t?void 0:t.data;if(n)return Fi(n)})).filter(Ai):[]},getLiveChat:()=>(async e=>{var t;const n=ze();if(n.log("stream/getLiveChat",e.streamId),e.channelId){const n=null===(t=Ze(["channel","get",e.channelId]))||void 0===t?void 0:t.data;if(n)return Rr(Pr(n));const{data:a}=await Bi(e.channelId);return Rr(Pr(a))}if(e.userId===n.userId){const{data:t}=await Ni({type:"live",postId:e.postId,videoStreamId:e.streamId});return tt(["stream","get",e.streamId],{channelId:t.channelId}),t}})(e),isBanned:!e.watcherUrl,watcherUrl:null,get[Li](){return e.watcherUrl}}),Ki=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=Ze(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),$i=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=Ze(["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=Ze(["user","get",e.userId]);if(null==t?void 0:t.data)return qt(t.data)},get childrenComment(){return e.children.map((e=>{const t=Ze(["comment","get",e]);if(null==t?void 0:t.data)return null==t?void 0:t.data})).filter(Ai).map((e=>$i(e)))}});function Qi(e){return!!(e.data&&"string"!=typeof e.data&&"videoFileId"in e.data&&"thumbnailFileId"in e.data&&"video"===e.dataType)}function Vi(e){return!(!e.data||"string"==typeof e.data||!("streamId"in e.data)||"liveStream"!==e.dataType)}const zi=e=>Object.assign(Object.assign({},e),{createdById:e.createdBy}),Hi=e=>Object.assign(Object.assign({},e),{invitations:e.invitations.map(zi),users:e.users.map(ga)}),Ji=async e=>{const t=ze();t.log("invitation/createInvitations",e);const{data:n}=await t.http.post("/api/v1/invitations",e),a=Hi(n),r=t.cache&&Date.now();return t.cache&&Ln(a,{cachedAt:r}),jt("local.invitation.created",a.invitations),{data:a.invitations,cachedAt:r}},Wi=e=>Object.assign(Object.assign({},e),{users:e.users.map(ga),invitations:e.invitations.map(zi)}),Gi=e=>Object.assign(Object.assign({},e),{get user(){const t=Ze(["user","get",e.invitedUserPublicId]);if(null==t?void 0:t.data)return qt(t.data)},get createdBy(){const t=Ze(["user","get",e.inviterUserPublicId]);if(null==t?void 0:t.data)return qt(t.data)},get target(){if("community"===e.targetType){const t=Ze(["community","get",e.targetId]);return(null==t?void 0:t.data)?t.data:void 0}},accept:async()=>{await(async e=>{var t;const n=ze();n.log("invitation/acceptInvitation",e);const{data:a}=await n.http.post(`/api/v1/invitations/${e}/accept`),r=null===(t=Ze(["invitation","get",e]))||void 0===t?void 0:t.data;return r&&(nt(["invitation","get",e],{status:"approved"}),jt("local.invitation.updated",[r])),a.success})(e._id)},reject:async()=>{await(async e=>{var t;const n=ze();n.log("invitation/rejectInvitation",e);const{data:a}=await n.http.post(`/api/v1/invitations/${e}/reject`),r=null===(t=Ze(["invitation","get",e]))||void 0===t?void 0:t.data;return r&&(nt(["invitation","get",e],{status:"rejected"}),jt("local.invitation.updated",[r])),a.success})(e._id)}}),Yi=async e=>{const t=ze();t.log("invitation/getInvitation",e.targetType,e.targetId,e.type);const{data:n}=await t.http.get("/api/v1/invitations/me",{params:e}),a=Wi(n),r=t.cache&&Date.now();return t.cache&&Ln(a,{cachedAt:r}),{data:a.invitations[0]?Gi(a.invitations[0]):void 0,cachedAt:r}};class Xi{constructor(){this.sessions=new Map}addSession(e){this.sessions.set(e.sessionId,e)}getSession(e){return this.sessions.get(e)}updateSession(e,t){const n=this.sessions.get(e);n&&this.sessions.set(e,Object.assign(Object.assign({},n),t))}getSessionsByState(e){return Array.from(this.sessions.values()).filter((t=>t.syncState===e))}deleteSession(e){this.sessions.delete(e)}getPendingSessions(){return this.getSessionsByState("PENDING")}getSyncingSessions(){return this.getSessionsByState("SYNCING")}}let Zi=null;const ec=()=>(Zi||(Zi=new Xi),Zi),tc={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},nc="-----BEGIN PRIVATE KEY-----";function ac(e){const n=new Uint8Array(e);let a="";return n.forEach((e=>{a+=String.fromCharCode(e)})),t.btoa(a)}function rc(e){return e<128?new Uint8Array([e]):e<256?new Uint8Array([129,e]):new Uint8Array([130,e>>8&255,255&e])}async function sc(e){let n=e;n=e.includes(nc)?e.substring(nc.length,e.length-"-----END PRIVATE KEY-----".length).replace(/\s/g,""):e.replace(/\s/g,"");const a=t.atob(n),r=new Uint8Array(a.length);for(let e=0;e<a.length;e+=1)r[e]=a.charCodeAt(e);const s=function(e){const t=new Uint8Array([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]),n=new Uint8Array([2,1,0]),a=rc(e.length),r=n.length+t.length+1+a.length+e.length,s=rc(r),o=new Uint8Array(1+s.length+r);let i=0;return o[i]=48,i+=1,o.set(s,i),i+=s.length,o.set(n,i),i+=n.length,o.set(t,i),i+=t.length,o[i]=4,i+=1,o.set(a,i),i+=a.length,o.set(e,i),o}(r);return await crypto.subtle.importKey("pkcs8",s.buffer,tc,!1,["sign"])}async function oc({timestamp:e,rooms:t}){const n=t.map((e=>Object.keys(e).sort().map((t=>`${t}=${e[t]}`)).join("&"))).join(";"),a=C.default.v4(),r=`nonceStr=${a}×tamp=${e}&data=${n}==`,s=(new TextEncoder).encode(r),o=await sc("-----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:ac(await crypto.subtle.sign(tc,o,s)),nonceStr:a}}async function ic(){const e=ec(),t=e.getPendingSessions();if(0===t.length)return!0;try{const n=(new Date).toISOString(),a=t.map((e=>({sessionId:e.sessionId,roomId:e.roomId,watchSeconds:e.watchSeconds,startTime:e.startTime.toISOString(),endTime:e.endTime?e.endTime.toISOString():""}))),r=await oc({timestamp:n,rooms:a});if(!r||!r.signature)throw new Error("Signature is undefined");t.forEach((t=>{e.updateSession(t.sessionId,{syncState:"SYNCING"})}));const s={signature:r.signature,nonceStr:r.nonceStr,timestamp:n,rooms:a},o=ze();return await o.http.post("/api/v3/user-event/room",s),t.forEach((t=>{e.updateSession(t.sessionId,{syncState:"SYNCED",syncedAt:new Date})})),!0}catch(n){return console.error("[SDK syncWatchSessions] ERROR caught:",(null==n?void 0:n.message)||n),t.forEach((t=>{const n=e.getSession(t.sessionId);if(n){const a=n.retryCount+1;a>=3?e.deleteSession(t.sessionId):e.updateSession(t.sessionId,{syncState:"PENDING",retryCount:a})}})),!1}}const cc=["live","recorded"];class lc{constructor(e){this.storage=ec(),this.client=ze(),this.room=e}async createWatchSession(e){if(!cc.includes(this.room.status))throw new Fe("room is not in watchable state",5e5,"error");const t=("live"===this.room.status?"room_":"room_playback_")+C.default.v4(),n={sessionId:t,roomId:this.room.roomId,watchSeconds:0,startTime:e,endTime:null,syncState:"PENDING",syncedAt:null,retryCount:0};return this.storage.addSession(n),t}async updateWatchSession(e,t,n){if(!this.storage.getSession(e))throw new Error(`Watch session ${e} not found`);this.storage.updateSession(e,{watchSeconds:t,endTime:n})}syncPendingWatchSessions(){const e=Math.floor(25001*Math.random())+5e3;this.client.log("room/RoomAnalytics: syncPendingWatchSessions called, jitter delay:",`${e}ms`),setTimeout((async()=>{this.client.log("room/RoomAnalytics: Jitter delay completed, starting sync process");try{const e=this.storage.getSyncingSessions();this.client.log("room/RoomAnalytics: SYNCING sessions to reset:",e.length),e.forEach((e=>{this.storage.updateSession(e.sessionId,{syncState:"PENDING"})})),await((e=6e4)=>new Promise((t=>{if("undefined"==typeof navigator||void 0===navigator.onLine)return void t();const n=Date.now(),a=()=>{navigator.onLine||Date.now()-n>=e?t():setTimeout(a,1e3)};a()})))(6e4),this.client.log("room/RoomAnalytics: Network available"),this.client.log("room/RoomAnalytics: Calling syncWatchSessions()"),await ic(),this.client.log("room/RoomAnalytics: syncWatchSessions completed")}catch(e){console.error("Failed to sync watch sessions:",e)}}),e)}}const dc=e=>Object.assign(Object.assign({},e),{get post(){var t;if("post"===e.referenceType)return null===(t=Ze(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=Ze(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;const n=null===(t=Ze(["user","get",e.createdBy]))||void 0===t?void 0:t.data;return n?qt(n):n},get childRooms(){return e.childRoomIds&&0!==e.childRoomIds.length?e.childRoomIds.map((e=>{var t;const n=null===(t=Ze(["room","get",e]))||void 0===t?void 0:t.data;if(n)return dc(n)})).filter(Ai):[]},participants:e.participants.map((e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=Ze(["user","get",e.userId]))||void 0===t?void 0:t.data;return n?qt(n):n}}))),getLiveChat:()=>(async e=>{var t;const n=ze();if(n.log("room/getLiveChat",e.roomId),e.liveChannelId){const n=null===(t=Ze(["channel","get",e.liveChannelId]))||void 0===t?void 0:t.data;if(n)return Rr(Pr(n));const{data:a}=await Bi(e.liveChannelId);return Rr(Pr(a))}if(e.createdBy===n.userId){const{data:t}=await Ni({type:"live",postId:e.referenceId,roomId:e.roomId});return tt(["room","get",e.roomId],{liveChannelId:t.channelId}),t}})(e),createInvitation:t=>Ji({type:"livestreamCohostInvite",targetType:"room",targetId:e.roomId,userIds:[t]}),getInvitations:async()=>{const{data:t}=await Yi({targetId:e.roomId,targetType:"room",type:"livestreamCohostInvite"});return t},analytics(){return new lc(this)}}),uc=e=>Object.assign(Object.assign({},e),{answers:e.answers.map((e=>Object.assign(Object.assign({},e),{get image(){var t;if(e.fileId)return null===(t=Ze(["file","get",e.fileId]))||void 0===t?void 0:t.data}})))});function hc(e,t){return e.map((e=>{const n=Ze(["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 a=void 0!==e.isJoined?e.isJoined:t.some((t=>function(e,t){const{userId:n}=kt();return e.communityId===t.communityId&&t.userId===n}(e,t)&&"none"!==t.communityMembership));return Object.assign(Object.assign({},e),{isJoined:a})}))}const pc=e=>{var t;return null!==(t=Object.keys(j).find((t=>e.needApprovalOnPostCreation===j[t].needApprovalOnPostCreation&&e.onlyAdminCanPost===j[t].onlyAdminCanPost)))&&void 0!==t?t:U};function fc({communities:e}){return e.map((e=>{var{needApprovalOnPostCreation:t,onlyAdminCanPost:n}=e,a=Kn(e,["needApprovalOnPostCreation","onlyAdminCanPost"]);return Object.assign({postSetting:pc({needApprovalOnPostCreation:t,onlyAdminCanPost:n})},a)}))}const mc=e=>{const t=fc({communities:e.communities}),n=e.users.map(ga),a=e.communityUsers.map((e=>{const t=n.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),r=hc(t,a);return Object.assign(Object.assign({},e),{users:e.users.map(ga),communities:r,communityUsers:a})},gc=e=>{const t=e.joinRequests.map((e=>Object.assign(Object.assign({},e),{joinRequestId:e._id}))),n=e.users.map(ga);return Object.assign(Object.assign({},e),{joinRequests:t,users:n})},yc=e=>{const t=fc({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})})),a=hc(t,n);return Object.assign(Object.assign({},e),{communities:a,communityUsers:n})},vc=e=>{const{postSetting:t,storySetting:n}=e,a=Kn(e,["postSetting","storySetting"]);return Object.assign(Object.assign(Object.assign({},a),t?j[t]:void 0),{allowCommentInStory:"boolean"!=typeof(null==n?void 0:n.enableComment)||n.enableComment})},bc=e=>{var t=Kn(e,["searchResult"]);const n=mc(t);return Object.assign({},n)},wc=e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=Ze(["user","get",e.requestorPublicId]))||void 0===t?void 0:t.data;if(n)return qt(n)},cancel:async()=>{await(async e=>{var t;const n=ze();n.log("joinRequest/cancelJoinRequest",e.joinRequestId);const{data:a}=await n.http.delete(`/api/v4/communities/${e.targetId}/join`),r=null===(t=Ze(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return r&&(nt(["joinRequest","get",e.joinRequestId],{status:"cancelled"}),jt("local.joinRequest.deleted",[r])),a.success})(e)},approve:async()=>{await(async e=>{var t;const n=ze();n.log("joinRequest/approveJoinRequest",e.joinRequestId);const{data:a}=await n.http.post(`/api/v4/communities/${e.targetId}/join/approve`,{userId:e.requestorInternalId}),r=null===(t=Ze(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return r&&(nt(["joinRequest","get",e.joinRequestId],{status:"approved"}),jt("local.joinRequest.updated",[r])),a.success})(e)},reject:async()=>{await(async e=>{var t;const n=ze();n.log("joinRequest/rejectJoinRequest",e.joinRequestId);const{data:a}=await n.http.post(`/api/v4/communities/${e.targetId}/join/reject`,{userId:e.requestorInternalId}),r=null===(t=Ze(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return r&&(nt(["joinRequest","get",e.joinRequestId],{status:"rejected"}),jt("local.joinRequest.updated",[r])),a.success})(e)}});class Ic extends wi{async getRequest(e,t){const{limit:n=20,communityId:a}=e,r=Kn(e,["limit","communityId"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get(`/api/v4/communities/${a}/join`,{params:Object.assign(Object.assign({},r),{options:s})});return o}}var Cc;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(Cc||(Cc={}));class Sc extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.joinRequests.map((e=>We("joinRequest")({joinRequestId:e._id})))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>We("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===Cc.OnLocalJoinRequestUpdated){if(!a.data.find((e=>e===t[0].joinRequestId)))return}e===Cc.OnLocalJoinRequestCreated&&(a.data=[...new Set([...t.map((e=>e.joinRequestId)),...a.data])]),e===Cc.OnLocalJoinRequestDeleted&&(a.data=a.data.filter((e=>e!==t[0].joinRequestId))),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Oc=e=>{const t=ze(),n=[Mt(t,"onJoinRequestCreated","local.joinRequest.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Tc=e=>{const t=ze(),n=[Mt(t,"onJoinRequestUpdated","local.joinRequest.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},kc=e=>{const t=ze(),n=[Mt(t,"onJoinRequestDeleted","local.joinRequest.deleted",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class Ac extends ki{constructor(e,t){const n=O.default(e),a=["joinRequest","collection",n];super(new Ic(e),n,a,t),this.query=e,this.queryStreamController=new Sc(this.query,this.cacheKey,this.notifyChange.bind(this),gc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){const a=e;this.queryStreamController.appendToQueryStream(a,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Oc,action:Cc.OnLocalJoinRequestCreated},{fn:Tc,action:Cc.OnLocalJoinRequestUpdated},{fn:kc,action:Cc.OnLocalJoinRequestDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a;const r=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!r)return;const s=this.applyFilter(r.data.map((e=>Ze(["joinRequest","get",e]))).filter(Ai).map((({data:e})=>e)).map(wc));(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.status&&(t=t.filter((e=>e.status===this.query.status)));const n=(()=>"firstCreated"===this.query.sortBy?yt:bt)();return t=t.sort(n),t}}var _c;!function(e){e.OnLocalInvitationCreated="onLocalInvitationCreated",e.OnLocalInvitationUpdated="onLocalInvitationUpdated",e.OnLocalInvitationCanceled="onLocalInvitationCanceled"}(_c||(_c={}));class Ec extends wi{async getRequest(e,t){const{limit:n=de}=e,a=Kn(e,["limit"]),r=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v1/invitations",{params:Object.assign(Object.assign({},a),{options:r})});return s}}class Rc extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.invitations.map(We("invitation"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(We("invitation"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===_c.OnLocalInvitationUpdated){if(!a.data.find((e=>e===t[0].invitationId)))return}e===_c.OnLocalInvitationCreated&&(a.data=[...new Set([...t.map((e=>e.invitationId)),...a.data])]),e===_c.OnLocalInvitationDeleted&&(a.data=a.data.filter((e=>e!==t[0].invitationId))),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Pc=e=>{const t=ze(),n=[Mt(t,"onLocalInvitationCreated","local.invitation.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Mc=e=>{const t=ze(),n=[Mt(t,"onLocalInvitationUpdated","local.invitation.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},jc=e=>{const t=ze(),n=[Mt(t,"onLocalInvitationCanceled","local.invitation.canceled",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class Uc extends ki{constructor(e,t){const n=O.default(e),a=["invitation","collection",n];super(new Ec(e),n,a,t),this.query=e,this.queryStreamController=new Rc(this.query,this.cacheKey,this.notifyChange.bind(this),Hi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:Pc,action:_c.OnLocalInvitationCreated},{fn:Mc,action:_c.OnLocalInvitationUpdated},{fn:jc,action:_c.OnLocalInvitationCanceled}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["invitation","get",e]))).filter(Ai).map((({data:e})=>Gi(e))))&&void 0!==r?r:[]);(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.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?yt:bt)();return t=t.sort(n),t}}const Dc=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=Ze(["category","get",e]);if(null==t?void 0:t.data)return Ki(t.data)})).filter((e=>!!e))},get avatar(){var t;if(!e.avatarFileId)return;return null===(t=Ze(["file","get",e.avatarFileId]))||void 0===t?void 0:t.data},createInvitations:async t=>{await Ji({type:"communityMemberInvite",targetType:"community",targetId:e.communityId,userIds:t})},getMemberInvitations:(t,n)=>((e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`getInvitations: (tmpid: ${s}) > listen`);const o=new Uc(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{at(c)})),()=>{a(`getInvitations (tmpid: ${s}) > dispose`),i.forEach((e=>e()))}})(Object.assign(Object.assign({},t),{targetId:e.communityId,targetType:"community",type:"communityMemberInvite"}),n),getInvitation:async()=>{const{data:t}=await Yi({targetType:"community",targetId:e.communityId});return t},join:async()=>(async e=>{var t;const n=ze();n.log("community/joinRequest",e);const{data:a}=await n.http.post(`/api/v4/communities/${e}/join`),r=gc(a),s=n.cache&&Date.now();n.cache&&Ln(r,{cachedAt:s});const o="approved"===r.joinRequests[0].status?"success":"pending";if("success"===o&&n.cache){const n=null===(t=Ze(["community","get",e]))||void 0===t?void 0:t.data;if(n){const t=Object.assign(Object.assign({},n),{isJoined:!0});nt(["community","get",e],t)}}return jt("v4.local.community.joined",r.joinRequests),"success"===o?{status:o}:{status:o,request:wc(r.joinRequests[0])}})(e.communityId),getJoinRequests:(t,n)=>((e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`getJoinRequests: (tmpid: ${s}) > listen`);const o=new Ac(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{at(c)})),()=>{a(`getJoinRequests (tmpid: ${s}) > dispose`),i.forEach((e=>e()))}})(Object.assign(Object.assign({},t),{communityId:e.communityId}),n),getMyJoinRequest:async()=>{const{data:t}=await(async e=>{const t=ze();t.log("community/myJoinRequest",e);const{data:n}=await t.http.get(`/api/v4/communities/${e}/join/me`),a=gc(n),r=t.cache&&Date.now();return t.cache&&Ln(a,{cachedAt:r}),{data:a.joinRequests[0]?wc(a.joinRequests[0]):void 0,cachedAt:r}})(e.communityId);return t}}),xc=e=>{const t=gs();return Object.assign(Object.assign({},e),{analytics:{markAsClicked:(n,a,r)=>{t.markProductAsClicked(e,n,a,r)},markAsViewed:(n,a,r)=>{t.markProductAsViewed(e,n,a,r)}}})},qc=e=>Zn(e,{childrenPosts:e.children.map((e=>{var t;return null===(t=Ze(["post","get",e]))||void 0===t?void 0:t.data})).filter(Ai).map(qc),analytics:{markAsViewed:()=>{gs().markPostAsViewed(e.postId)},markAsMeaningfullyViewed:t=>{gs().markPostAsMeaningfullyViewed(e.postId,t)}},get productTags(){var t,n;return null!==(n=null===(t=e.productTags)||void 0===t?void 0:t.map((e=>(e=>{var t;const n=null===(t=Ze(["product","get",e.productId]))||void 0===t?void 0:t.data;return Object.assign(Object.assign({},e),{product:n?xc(n):void 0})})(e))))&&void 0!==n?n:[]},get latestComments(){return e.comments&&e.comments.map((e=>{var t;const n=null===(t=Ze(["comment","get",e]))||void 0===t?void 0:t.data;return n?$i(n):null})).filter(Boolean)||[]},get creator(){const t=Ze(["user","get",e.postedUserId]);if(null==t?void 0:t.data)return qt(t.data)},get targetCommunity(){var t;const n=null===(t=Ze(["community","get",e.targetId]))||void 0===t?void 0:t.data;if(n)return Dc(n)},getImageInfo(){var t,n;return function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"image"!==e.dataType)}(e)?null===(n=Ze(["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,a;return Qi(e)?null===(a=Ze(["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===a?void 0:a.data:void 0},getVideoThumbnailInfo(){var t,n;return Qi(e)?null===(n=Ze(["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=Ze(["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(!Vi(e))return;const a=null===(n=Ze(["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 a?Fi(a):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 a=null===(n=Ze(["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 a?uc(a):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=Ze(["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=Ze(["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 a=null===(n=Ze(["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 a?dc(a):void 0}}),Nc=(e,t)=>{"message"===e?jt("local.message.updated",{messages:[t]}):"post"===e?jt("post.updated",{posts:[t]}):"comment"===e?jt("comment.updated",{comments:[t]}):"story"===e&&jt("story.updated",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[t]})},Bc=async(e,t,n,a)=>{var r,s,o;const i=ze();if(i.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Fe("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:a});if(i.cache){const a=Ze([e,"get",t]);if(!a||(null===(r=a.data.myReactions)||void 0===r?void 0:r.includes(n)))return!0;const l=Object.assign(Object.assign({},a.data),{reactionsCount:a.data.reactionsCount+1,myReactions:[...null!==(s=a.data.myReactions)&&void 0!==s?s:[],n],reactions:Object.assign(Object.assign({},a.data.reactions),{[n]:(null!==(o=a.data.reactions[n])&&void 0!==o?o:0)+1}),updatedAt:(new Date).toISOString()});if("comment"===e)return jt("local.comment.addReaction",{comment:l,reactor:{userId:i.userId,reactionName:n,reactionId:c.addedId}}),!0;if("post"===e)return jt("local.post.addReaction",{post:l,reactor:{userId:i.userId,reactionName:n,reactionId:c.addedId}}),!0;if("story"===e)return jt("local.story.reactionAdded",{story:l,reactor:{userId:i.userId,reactionName:n,reactionId:c.addedId}}),!0;if("message"===e)return nt(["message","get",t],l),jt("local.message.updated",{messages:[l]}),!0}return!0};Bc.optimistically=(e,t,n)=>{var a,r,s,o,i;const c=ze();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const l=Ze([e,"get",t]);if(!(null==l?void 0:l.data)||(null===(a=l.data.myReactions)||void 0===a?void 0:a.includes(n)))return;const d=Object.assign(Object.assign({},l.data),{reactionsCount:l.data.reactionsCount+1,myReactions:[...null!==(r=l.data.myReactions)&&void 0!==r?r:[],n],reactions:Object.assign(Object.assign({},l.data.reactions),{[n]:(null!==(s=l.data.reactions[n])&&void 0!==s?s:0)+1})});return nt([e,"get",t],d,{cachedAt:me}),Nc(e,d),null!==(i=null===(o=null==d?void 0:d.myReactions)||void 0===o?void 0:o.includes(n))&&void 0!==i&&i};const Lc=(e,t)=>{var n;return null!==(n=null!=t?t:(e=>{var t,n;const a={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=Ze(["messageMarker","get",We("messageMarker")(a)]))||void 0===n?void 0:n.data})(e))&&void 0!==n?n:{readCount:0,deliveredCount:0}},Fc=(e,t)=>{const n=t.publicId!==t.messageId;return(async(e,t,n,a)=>{var r,s;const o=ze();if(o.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Fe("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:i}=await o.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:a}});if(o.cache){const a=Ze([e,"get",t]);if(!a)return!0;const c=Object.assign(Object.assign({},a.data),{reactionsCount:Math.max(0,a.data.reactionsCount-1),myReactions:(null!==(r=a.data.myReactions)&&void 0!==r?r:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},a.data.reactions),{[n]:Math.max(0,(null!==(s=a.data.reactions[n])&&void 0!==s?s:0)-1)}),updatedAt:(new Date).toISOString()});if("comment"===e)return jt("local.comment.removeReaction",{comment:c,reactor:{reactionId:i.removedId,reactionName:n,userId:o.userId}}),!0;if("post"===e)return jt("local.post.removeReaction",{post:c,reactor:{reactionId:i.removedId,reactionName:n,userId:o.userId}}),!0;if("story"===e)return jt("local.story.reactionRemoved",{story:c,reactor:{userId:o.userId,reactionName:n,reactionId:i.removedId}}),!0;if("message"===e)return nt(["message","get",t],c),jt("local.message.updated",{messages:[c]}),!0}return!0})("message",n?t.publicId:t.messageId,e,n?3:5)},Kc=e=>Object.assign(Object.assign({},e),{users:e.users.map(ga)}),$c=e=>Object.assign(Object.assign({},e),{get status(){return e.status},get userId(){return e.userId},get eventId(){return e.eventId},get respondedAt(){return e.respondedAt},get event(){const t=Ze(["event","get",e.eventId]);if(null==t?void 0:t.data)return t.data},get user(){const t=Ze(["user","get",e.userId]);if(null==t?void 0:t.data)return qt(t.data)}}),Qc=e=>Object.assign(Object.assign({},e),{users:e.users.map(ga)}),Vc=(e,t)=>{const n=ze();return Mt(n,e,e,(e=>{const a=Qc(e);if(n.cache){Ln(a);const e=Ze(["event","get",a.events[0].eventId]);t(e.data)}else t(a.events[0])}))},zc=(e,t)=>{const n=ze();return Mt(n,e,e,(e=>{const a=Kc(e);if(n.cache){Ln(a);const e=Ze(["eventResponse","get",a.eventResponses[0].userId]);t(e.data)}else t(a.eventResponses[0])}))},Hc=async e=>{const t=ze();t.log("event/getMyRSVP",e);const{data:n}=await t.http.get(`/api/v1/events/${e}/me/rsvp`),a=Kc(n),r=t.cache&&Date.now();return t.cache&&Ln(a,{cachedAt:r}),{data:$c(a.eventResponses[0]),cachedAt:r}};var Jc;Hc.locally=e=>{const t=ze();if(t.log("event/getMyRSVP.locally",e),!t.cache)return;const n=Ze(["event","getMyRSVP",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0},function(e){e.OnEventCreated="onEventCreated",e.OnEventUpdated="onEventUpdated",e.OnEventDeleted="onEventDeleted",e.OnRSVPCreated="onRSVPCreated",e.OnRSVPUpdated="onRSVPUpdated"}(Jc||(Jc={}));class Wc extends wi{async getRequest(e,t){const{limit:n=de,eventId:a}=e,r=Kn(e,["limit","eventId"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get(`/api/v1/events/${a}/rsvp`,{params:Object.assign(Object.assign({},r),{options:s})});return o}}class Gc extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.eventResponses.map(We("eventResponse"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.eventResponses.map(We("eventResponse"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===Jc.OnRSVPCreated&&(a.data=[...new Set([t.userId,...a.data])]),e===Jc.OnEventDeleted&&(a.data=a.data.filter((e=>e!==t.eventId))),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Yc=e=>Vc("event.created",e),Xc=e=>Vc("event.updated",e),Zc=e=>Vc("event.deleted",e),el=e=>Vc("local.event.created",e),tl=e=>Vc("local.event.updated",e),nl=e=>Vc("local.event.deleted",e),al=e=>zc("event.rsvp.created",e),rl=e=>zc("event.rsvp.updated",e),sl=e=>zc("local.rsvp.created",e),ol=e=>zc("local.rsvp.updated",e);class il extends ki{constructor(e,t){const n=O.default(e),a=["eventResponse","collection",n];super(new Wc(e),n,a,t),this.query=e,this.queryStreamController=new Gc(this.query,this.cacheKey,this.notifyChange.bind(this),Kc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:al,action:Jc.OnRSVPCreated},{fn:rl,action:Jc.OnRSVPUpdated},{fn:sl,action:Jc.OnRSVPCreated},{fn:ol,action:Jc.OnRSVPUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a;const r=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!r)return;const s=r.data.map((e=>Ze(["eventResponse","get",e]))).filter(Ai).map((({data:e})=>$c(e)));(this.shouldNotify(s)||"event"!==e)&&this.callback({data:s,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}const cl=(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`getRSVPs: (tmpid: ${s}) > listen`);const o=new il(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getRSVPs (tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},ll=e=>Object.assign(Object.assign({},e),{get creator(){const t=Ze(["user","get",e.userId]);if(null==t?void 0:t.data)return qt(t.data)},get targetCommunity(){if(!e.originId)return;const t=Ze(["community","get",e.originId]);return(null==t?void 0:t.data)?Dc(t.data):void 0},get coverImage(){if(!e.coverImageFileId)return;const t=Ze(["file","get",e.coverImageFileId]);return(null==t?void 0:t.data)?t.data:void 0},get post(){if(!e.postId)return;const t=Ze(["post","get",e.postId]);return(null==t?void 0:t.data)?qc(t.data):void 0},get room(){var t;if(!e.postId)return;const n=null===(t=Xe(["room","get"]))||void 0===t?void 0:t.filter((t=>t.data.referenceId===e.postId));return(null==n?void 0:n.length)&&n[0].data?dc(n[0].data):void 0},createRSVP:async t=>{const{data:n}=await(async(e,t)=>{const n=ze();n.log("event/createRSVP",e,t);const{data:a}=await n.http.post(`/api/v1/events/${e}/rsvp`,{status:t});jt("local.rsvp.created",a);const r=Kc(a),s=n.cache&&Date.now();return n.cache&&Ln(r,{cachedAt:s}),{data:$c(r.eventResponses[0]),cachedAt:s}})(e.eventId,t);return n},updateRSVP:async t=>{const{data:n}=await(async(e,t)=>{const n=ze();n.log("event/updateRSVP",e,t);const{data:a}=await n.http.put(`/api/v1/events/${e}/rsvp`,{status:t});jt("local.rsvp.updated",a);const r=Kc(a),s=n.cache&&Date.now();return n.cache&&Ln(r,{cachedAt:s}),{data:$c(r.eventResponses[0]),cachedAt:s}})(e.eventId,t);return n},getMyRSVP:async()=>{const{data:t}=await Hc(e.eventId);return t},getRSVPs:(t,n)=>cl(Object.assign({eventId:e.eventId},t),n)}),dl={ad:e=>{const t=gs(),{image9_16:n,image1_1:a}=e,r=Kn(e,["image9_16","image1_1"]);return Object.assign(Object.assign({},r),{analytics:{markAsSeen:n=>{t.markAdAsViewed(e,n)},markLinkAsClicked:n=>{t.markAdAsClicked(e,n)}},get advertiser(){var t,n;const a=null===(t=Ze(["advertiser","get",e.advertiserId]))||void 0===t?void 0:t.data;if(!a)return;const r=null===(n=Ze(["file","get",a.avatarFileId]))||void 0===n?void 0:n.data;return Object.assign(Object.assign({},a),{avatar:r})},get image1_1(){const e=Ze(["file","get",a]);if(e)return e.data||void 0},get image9_16(){const e=Ze(["file","get",n]);if(e)return e.data||void 0}})},comment:$i,post:qc,user:qt,category:Ki,stream:Fi,story:e=>{const t=gs(),n=Ze(["storyTarget","get",e.targetId]),a=Ze(["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 a=Ze(["file","get",null===(n=null===(t=e.data)||void 0===t?void 0:t.videoFileId)||void 0===n?void 0:n.original]);if(!a)return;const{data:r}=a;return r||void 0},get imageData(){var t,n;if(!(null===(t=e.data)||void 0===t?void 0:t.fileId))return;const a=Ze(["file","get",null===(n=e.data)||void 0===n?void 0:n.fileId]);if(!a)return;const{data:r}=a;return r?Object.assign(Object.assign({},r),{fileUrl:`${r.fileUrl}?size=full`}):void 0},get community(){if("community"===e.targetType&&a)return(null==a?void 0:a.data)||void 0},get communityCategories(){if("community"!==e.targetType)return;if(!a)return;const{data:{categoryIds:t}}=a;return 0!==t.length?t.map((e=>{const t=Ze(["category","get",e]);return(null==t?void 0:t.data)||void 0})).filter((e=>void 0!==e)):void 0},get creator(){const t=Ze(["user","get",e.creatorPublicId]);if(null==t?void 0:t.data)return qt(t.data)},get storyTarget(){if(null==n?void 0:n.data)return qi(n.data)},get isSeen(){const t=Ze(["story-last-seen",e.targetId]);if(!(null==n?void 0:n.data))return!1;const a=(null==t?void 0:t.data)?new Date(t.data).getTime():0,r=new Date(null==n?void 0:n.data.lastStorySeenExpiresAt).getTime()||0,s=new Date(e.expiresAt).getTime();return Math.max(a,r)>=s}})},storyTarget:qi,message:e=>{const t=Kn(e,["creatorPrivateId"]);return Object.assign(Object.assign({},t),{get readCount(){return Lc(e).readCount},get deliveredCount(){return Lc(e).deliveredCount},get creator(){var t;return null===(t=Ze(["user","get",e.creatorId]))||void 0===t?void 0:t.data},markRead:()=>vo(e),addReaction:t=>((e,t)=>{const n=t.publicId!==t.messageId;return Bc("message",n?t.publicId:t.messageId,e,n?3:5)})(t,e),removeReaction:t=>Fc(t,e)})},reactor:e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=Ze(["user","get",e.userId]))||void 0===t?void 0:t.data;if(n)return qt(n)}}),channel:Rr,pinnedPost:e=>{var t;const n=Ze(["post","get",e.referenceId]),a=null===(t=Xe(["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:a,get post(){if(null==n?void 0:n.data)return qc(n.data)},get target(){const e=Ze(["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})=>Ze(["user","get",e]))).filter(Ai).map((({data:e})=>e)).map((e=>qt(e))),get event(){const t=Ze(["event","get",e.actionReferenceId]);if(null==t?void 0:t.data)return t.data}}),community:Dc,invitation:Gi,joinRequest:wc,channelMember:Na,room:dc,event:ll,eventResponse:$c,product:xc,poll:uc},ul=async e=>{const t=ze();t.log("user/getUsers",e);const n=e.map((e=>encodeURIComponent(e))),{data:a}=await t.http.get("/api/v3/users/list",{params:{userIds:n}}),r=Zr(a),s=t.cache&&Date.now();return t.cache&&Ln(r,{cachedAt:s}),jt("user.fetched",a),{data:r.users.map((e=>dl.user(e))),cachedAt:s}};ul.locally=e=>{var t;const n=ze();if(n.log("user/getUsers.locally",e),!n.cache)return;const a=e.map((e=>Ze(["user","get",e]))).filter(Boolean),r=a.map((({data:e})=>dl.user(e))),s=null===(t=a.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==a?void 0:a.length)<e.length?void 0:{data:r,cachedAt:s.cachedAt}};const hl=e=>is("user.updated",e),pl=e=>is("user.flagged",e),fl=e=>is("user.unflagged",e),ml=e=>is("user.flagCleared",e),gl=e=>is("user.fetched",e),yl=async e=>{const t=ze();t.log("user/getUser",e),ta("user",e);try{const{data:n}=await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`),a=t.cache&&Date.now(),r=Zr(n);return t.cache&&Ln(r,{cachedAt:a}),jt("user.fetched",n),{data:r.users.find((t=>t.userId===e)),cachedAt:a}}catch(t){throw Oe(null==t?void 0:t.code)&&Fn("user",e),t}};yl.locally=e=>{const t=ze();if(t.log("user/getUser.locally",e),!t.cache)return;const n=Ze(["user","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class vl extends wi{async getRequest(e,t){const{limit:n=de}=e,a=Kn(e,["limit"]),r=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},a),{options:r,isDeleted:!1})});return s}}class bl extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.users.map(We("user"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(We("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Ze(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],et(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var wl;!function(e){e.OnUserDeleted="onUserDeleted",e.OnUserUpdated="onUserUpdated",e.OnUserFlagged="onUserFlagged",e.OnUserUnflagged="onUserUnflagged",e.OnUserFlagCleared="onUserFlagCleared"}(wl||(wl={}));class Il extends ki{constructor(e,t){const n=O.default(e),a=["user","collection",n];super(new vl(e),n,a,t),this.query=e,this.queryStreamController=new bl(this.query,this.cacheKey,this.notifyChange.bind(this),Zr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:cs,action:wl.OnUserDeleted},{fn:hl,action:wl.OnUserUpdated},{fn:pl,action:wl.OnUserFlagged},{fn:fl,action:wl.OnUserUnflagged},{fn:ml,action:wl.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["user","get",e]))).filter(Ai).map((({data:e})=>e)).map(dl.user))&&void 0!==r?r:[]);(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;const n=(()=>"firstCreated"===this.query.sortBy?yt:bt)();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 Cl extends wi{async getRequest(e,t){const{limit:n=de}=e,a=Kn(e,["limit"]),r=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v4/me/user-blocks",{params:Object.assign(Object.assign({},a),{options:r,isDeleted:!1})});return s}}var Sl;!function(e){e.OnBlocked="onBlocked",e.OnUnblocked="onUnblocked"}(Sl||(Sl={}));class Ol extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.users.map(We("user"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(We("user"))])]}))}}reactor(e){return t=>{var n,a;const r=e===Si.OnFollowed||e===Sl.OnUnblocked,s=e===Sl.OnBlocked;if(r||s){const e=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data,r=null!==(a=null==e?void 0:e.data)&&void 0!==a?a:[],o=s?[...new Set([...r,t.userId])]:r.filter((e=>e!==t.userId));et(this.cacheKey,Object.assign(Object.assign({},e),{data:o}))}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Tl=(e,t,n)=>a=>e((e=>{var r;if(!e)return e;const s=[n,"get",`${e[t]}`],o=null===(r=Ze(s))||void 0===r?void 0:r.data;return o?a(o):void 0}));class kl extends ki{constructor(e,t){const n=O.default(e),a=["blockedUsers","collection",n];super(new Cl(e),n,a,t),this.query=e,this.queryStreamController=new Ol(this.query,this.cacheKey,this.notifyChange.bind(this),xs),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:cs,action:wl.OnUserDeleted},{fn:Tl(mi,"to","user"),action:Si.OnFollowed},{fn:Tl(oi,"to","user"),action:Si.OnFollowed},{fn:e=>Js((t=>{var n;if(t.from!==ze().userId)return;const a=null===(n=Ze(["user","get",t.to]))||void 0===n?void 0:n.data;a&&e(a)})),action:Sl.OnBlocked},{fn:e=>Ws((t=>{var n;if(t.from!==ze().userId)return;const a=null===(n=Ze(["user","get",t.to]))||void 0===n?void 0:n.data;a&&e(a)})),action:Sl.OnUnblocked}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["user","get",e]))).filter(Ai).map((({data:e})=>e)).map(dl.user))&&void 0!==r?r:[]);(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;return t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}class Al extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.users.map(We("user"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(We("user"))])]}))}}reactor(e){return t=>{var n,a;if(t&&(e===Sl.OnBlocked||e===Sl.OnUnblocked)){const r=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data,s=null!==(a=null==r?void 0:r.data)&&void 0!==a?a:[],o=e===Sl.OnBlocked?[...new Set([...s,t.userId])]:s.filter((e=>e!==t.userId));et(this.cacheKey,Object.assign(Object.assign({},r),{data:o}))}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class _l extends wi{async getRequest(e,t){const{limit:n=ue}=e,a=Kn(e,["limit"]),r=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v4/me/blockers",{params:Object.assign(Object.assign({},a),{options:r,isDeleted:!1})});return s}}class El extends ki{constructor(e){const t=`blocking-users-${ze().userId}`,n={},a=["blockingUsers","collection",t];super(new _l(n),t,a,e),this.queryStreamController=new Al(n,this.cacheKey,this.notifyChange.bind(this),Ls),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:cs,action:wl.OnUserDeleted},{fn:e=>Js((t=>{var n;if(t.to!==ze().userId)return;const a=null===(n=Ze(["user","get",t.from]))||void 0===n?void 0:n.data;a&&e(a)})),action:Sl.OnBlocked},{fn:e=>Ws((t=>{var n;if(t.to!==ze().userId)return;const a=null===(n=Ze(["user","get",t.from]))||void 0===n?void 0:n.data;a&&e(a)})),action:Sl.OnUnblocked}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["user","get",e]))).filter(Ai).map((({data:e})=>e)).map(dl.user))&&void 0!==r?r:[]);(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;return t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}class Rl extends wi{async getRequest(e,t){const{limit:n=de,displayName:a}=e,r=Kn(e,["limit","displayName"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},r),{keyword:a,options:s,isDeleted:!1})});return o}}class Pl extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.users.map(We("user"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(We("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Ze(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],et(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Ml extends ki{constructor(e,t){var n;const a=O.default(e),r=["user","collection",a];super(new Rl(e),a,r,t),this.query=Object.assign(Object.assign({},e),{filter:null!==(n=e.filter)&&void 0!==n?n:"all"}),this.queryStreamController=new Pl(this.query,this.cacheKey,this.notifyChange.bind(this),Zr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:cs,action:wl.OnUserDeleted},{fn:hl,action:wl.OnUserUpdated},{fn:pl,action:wl.OnUserFlagged},{fn:fl,action:wl.OnUserUnflagged},{fn:ml,action:wl.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["user","get",e]))).filter(Ai).map((({data:e})=>e)).map(dl.user))&&void 0!==r?r:[]);(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;return"flagged"===this.query.filter&&(t=t.filter((e=>!!e.hashFlag))),t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}const jl=async({viewId:e,viewedType:t,limit:n,token:a})=>{const r=ze(),s={};a?s.token=a:s.limit=n;const o=`/api/v1/analytics/views/${"post"===t?"posts":"stories"}/${e}/users`,i=await r.http.get(o,{params:s});return Ln(i.data),i.data};var Ul;!function(e){e.DEFAULT="default",e.PARTIAL="partial"}(Ul||(Ul={}));var Dl=Object.freeze({__proto__:null,Relationship:Di,getUserByIds:ul,updateUser:async(e,t)=>{const n=ze();n.log("user/updateUser",e,t);const{data:a}=await n.http.put("/api/v3/users/",Object.assign(Object.assign({userId:e},t),{createNewUserWhenNotFound:!1})),r=Zr(a),s=n.cache&&Date.now();return n.cache&&Ln(r,{cachedAt:s}),jt("user.updated",a),{data:r.users.find((t=>t.userId===e)),cachedAt:s}},flagUser:async e=>{const t=ze();t.log("user/flagUser",e);const{data:n}=await t.http.post(`api/v4/me/flags/${encodeURIComponent(e)}`),a=Zr(n);return t.cache&&Ln(a),jt("user.flagged",n),!!a},unflagUser:async e=>{const t=ze();t.log("user/unflag",e);const{data:n}=await t.http.delete(`/api/v4/me/flags/${encodeURIComponent(e)}`),a=Zr(n);return t.cache&&Ln(a),jt("user.unflagged",n),!!a},isUserFlaggedByMe:async e=>{const t=ze();t.log("user/isUserFlaggedByMe",e);const{data:{isFlagByMe:n}}=await t.http.get(`/api/v3/users/${e}/isFlagByMe`);return n},getAllBlockedUsers:async()=>{ze().log("user/getAllBlockedUsers");const e=Bs();return await e.ensureFetched(),e.getCachedUsers()},getAllBlockingUsers:async()=>{ze().log("user/getAllBlockingUsers");const e=$s();return await e.ensureFetched(),e.getCachedUsers()},onUserUpdated:hl,onUserDeleted:cs,onUserFlagged:pl,onUserUnflagged:fl,onUserFlagCleared:ml,getUser:(e,t)=>Ui(e,(e=>t(Object.assign(Object.assign({},e),{data:e.data?dl.user(e.data):e.data}))),"userId",yl,[gl,hl,cs,pl,fl,ml]),getUsers:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`liveUsers(tmpid: ${s}) > listen`);const o=new Il(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`liveUsers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getBlockedUsers:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`getBlockedUsers(tmpid: ${s}) > listen`);const o=new kl(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getBlockedUsers(tmpid: ${s}) > dispose`),i.forEach((e=>e())),at(c)}},getBlockingUsers:e=>{const{log:t,cache:n}=ze();n||console.log(pe);const a=Date.now();t(`getBlockingUsers(tmpid: ${a}) > listen`);const r=new El(e),s=r.startSubscription(),o=r.getCacheKey();return s.push((()=>at(o))),()=>{t(`getBlockingUsers(tmpid: ${a}) > dispose`),s.forEach((e=>e())),at(o)}},searchUserByDisplayName:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`liveSearchUsers(tmpid: ${s}) > listen`);const o=new Ml(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`liveSearchUsers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getReachedUsers:(e,t)=>{let n=(e=!1)=>{};const{log:a,cache:r}=ze(),s=["viewedUsers","collection",{viewId:e.viewId,viewedType:e.viewedType}];r||console.log(pe);const o=Date.now();a(`getReachUsers(tmpid: ${o}) > listen`);const{limit:i,viewId:c,viewedType:l}=e;return n=(e=!1)=>{var a,r,o;const d=null===(a=Ze(s))||void 0===a?void 0:a.data,u=null!==(r=null==d?void 0:d.data)&&void 0!==r?r:[];if(!e&&u.length>0&&!(null==d?void 0:d.params.page))return;const h=xe(jl,{viewId:c,viewedType:l,limit:i||10,token:e||null===(o=null==d?void 0:d.params.page)||void 0===o?void 0:o.next});Ne(h,(e=>{var a,r,o,i,c;let l=null!==(o=null===(r=null===(a=Ze(s))||void 0===a?void 0:a.data)||void 0===r?void 0:r.data)&&void 0!==o?o:[];(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||[]};et(s,d),(e=>{var a,r;let s=[];(null==e?void 0:e.data)&&(s=e.data.map((e=>Ze(["user","get",e]))).filter(Boolean).map((e=>null==e?void 0:e.data))||[]),t({onNextPage:n,data:s,hasNextPage:!!(null===(r=null===(a=e.params)||void 0===a?void 0:a.page)||void 0===r?void 0:r.next),loading:e.loading||!1})})(d)}),qe(he,2e3))},n(!0),()=>{a(`getReachUsers(tmpid: ${o}) > dispose`),at(s)}},get AmityUserSearchMatchType(){return Ul}});const xl=async e=>{const t=ze();t.log("file/getFile",e);const{data:n}=await t.http.get(`/api/v3/files/${e}`),a=t.cache&&Date.now();return t.cache&&Ln({files:[n]},{cachedAt:a}),{data:n,cachedAt:a}};xl.locally=e=>{const t=ze();if(t.log("file/getFile.locally",e),!t.cache)return;const n=Ze(["file","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const ql=async(e,t,n)=>{const a=ze();a.log("file/uploadVideo",e);const r=e.getAll("files");if(!r.length)throw new Error("The formData object must have a `files` key.");const s=No().getFileAccessType();e.append("accessType",s),e.append("preferredFilename",r[0].name),t&&e.append("feedType",t);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await a.upload.post("/api/v4/videos",e,{headers:o,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),c=a.cache&&Date.now();return a.cache&&Ln({files:i},{cachedAt:c}),{data:i,cachedAt:c}},Nl=async(e,t,n)=>{const a=ze();a.log("file/uploadImage",e);const r=e.getAll("files");if(null==r?void 0:r.length)console.warn("Deprecation Warning: `files` is deprecated, please use `file` instead."),e.append("preferredFilename",r[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 s=No().getFileAccessType();e.append("accessType",s);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await a.upload.post("/api/v4/images",e,{headers:o,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),c=a.cache&&Date.now();return a.cache&&Ln({files:i},{cachedAt:c}),{data:i,cachedAt:c}};var Bl=Object.freeze({__proto__:null,getFile:xl,uploadFile:async(e,t)=>{const n=ze();n.log("file/uploadFile",e);const a=e.getAll("files");if(!a.length)throw new Error("The formData object must have a `files` key.");const r=No().getFileAccessType();e.append("accessType",r),e.append("preferredFilename",a[0].name);const s="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:o}=await n.upload.post("/api/v4/files",e,{headers:s,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),i=n.cache&&Date.now();return n.cache&&Ln({files:o},{cachedAt:i}),{data:o,cachedAt:i}},deleteFile:async e=>{const t=ze();return t.log("file/deleteFile",e),await t.http.delete(`/api/v3/files/${e}`),at(["file","get",e],!0),{success:!0}},fileUrlWithSize:(e,t)=>`${e}?size=${t}`,uploadVideo:ql,uploadImage:Nl,updateAltText:async(e,t)=>{const n=ze();n.log("file/updateAltText",t);const{data:a}=await n.http.put(`/api/v3/files/${e}`,{altText:t}),r=n.cache&&Date.now();return n.cache&&Ln({files:[a]},{cachedAt:r}),!0},uploadClip:async(e,t,n)=>{const a=ze();a.log("file/uploadClip",e);const r=e.get("files");if(!r)throw new Error("The formData object must have a `files` key.");const s=No().getFileAccessType();e.append("accessType",s),e.append("preferredFilename",r.name),t&&e.append("feedType",t);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await a.upload.post("/api/v4/clips",e,{headers:o,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),c=a.cache&&Date.now();return a.cache&&Ln({files:i},{cachedAt:c}),{data:i,cachedAt:c}},uploadAudio:async(e,t)=>{const n=ze();n.log("file/uploadAudio",e);const a=e.getAll("file");if(0===a.length)throw new Error("The formData object must have a `file` key with audio file.");const r=a[0],s=No().getFileAccessType();e.append("accessType",s),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))}}),i=n.cache&&Date.now();return n.cache&&Ln({files:o},{cachedAt:i}),{data:o,cachedAt:i}}});const Ll=async e=>{const t=ze();t.log("role/queryRoles",e);const n=null!=e?e:{},{limit:a=10,queryToken:r,displayName:s,sortBy:o}=n,i=Kn(n,["limit","queryToken","displayName","sortBy"]),c=r?{token:r}:a?{limit:a}:void 0,{data:l}=await t.http.get("/api/v3/roles",{params:Object.assign(Object.assign({},i),{keyword:s,sortBy:o,options:c})}),{paging:d}=l,u=Kn(l,["paging"]),{roles:h}=u,p=t.cache&&Date.now();t.cache&&Ln(u,{cachedAt:p});const f=Re(d.next);return{data:h,cachedAt:p,prevPage:Re(d.previous),nextPage:f,paging:d}};Ll.locally=e=>{ze().log("role/queryRoles.locally",e)};const Fl=async e=>{const t=ze();t.log("role/getRole",e);const{data:n}=await t.http.get(`/api/v3/roles/${e}`),a=t.cache&&Date.now();return t.cache&&Ln({roles:n},{cachedAt:a}),{data:n.find((t=>t.roleId===e)),cachedAt:a}};Fl.locally=e=>{const t=ze();if(t.log("role/getRole.locally",e),!t.cache)return;const n=Ze(["role","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Kl=async(e,t=!1)=>{const n=ze();let a;n.log("message/getMessage",e),ta("message",e);try{const{data:t}=await n.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);a=await pa(t)}catch(t){throw Oe(null==t?void 0:t.code)&&Fn("message",e),t}const r=n.cache&&Date.now();n.cache&&Ln(a,{cachedAt:r});const{messages:s}=a;return jt("local.message.fetched",{messages:s}),{data:s.find((t=>t.messageId===e)),cachedAt:r}};Kl.locally=e=>{const t=ze();if(t.log("message/getMessage.locally",e),!t.cache)return;const n=Ze(["message","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class $l{constructor(e,t,n){this.postId=e,this.latestCreatedAt=t,this.serverCommentCount=n}}class Ql{constructor(e,t,n){this.postId=e,this.commentId=t,this.createdAt=n}}class Vl{constructor(e,t){this.postId=e,this.commentId=t}}class zl{constructor(e,t){this.latestCommentCreatedAt=e,this.serverCommentCount=t,this.createdCommentIds=new Set,this.deletedCommentIds=new Set}}class Hl{constructor(){this.isProcessing=!1,this.tasks=[],this.commentChangeTracker=new Map}queueCommentChangeTask(e){this.tasks.push(e),this.isProcessing||this.processCommentChangeTask()}processCommentChangeTask(){if(this.isProcessing)return;if(this.isProcessing=!0,0===this.tasks.length)return void(this.isProcessing=!1);const e=this.tasks.splice(0,Hl.BATCH_SIZE),t=new Set;e.forEach((e=>{let n=!1;e instanceof $l?n=this.processResetTaskInternal(e):e instanceof Ql?n=this.processCreateTaskInternal(e):e instanceof Vl&&(n=this.processDeleteTaskInternal(e)),n&&t.add(e.postId)})),t.forEach((e=>{const t=this.computeCommentCount(e);Hl.publishUpdate(e,t)})),this.isProcessing=!1,this.tasks.length>0&&this.processCommentChangeTask()}processResetTaskInternal(e){return this.commentChangeTracker.set(e.postId,new zl(e.latestCreatedAt,e.serverCommentCount)),!0}processCreateTaskInternal(e){const t=this.commentChangeTracker.get(e.postId);return!!t&&(!t.createdCommentIds.has(e.commentId)&&(!(e.createdAt<=t.latestCommentCreatedAt)&&(t.createdCommentIds.add(e.commentId),!0)))}processDeleteTaskInternal(e){const t=this.commentChangeTracker.get(e.postId);return!!t&&(!t.deletedCommentIds.has(e.commentId)&&(t.deletedCommentIds.add(e.commentId),!0))}computeCommentCount(e){const t=this.commentChangeTracker.get(e);if(!t)return 0;const n=t.serverCommentCount+t.createdCommentIds.size-t.deletedCommentIds.size;return Math.max(0,n)}static publishUpdate(e,t){var n;const a=["post","get",e];tt(a,{localCommentCount:t});const r=null===(n=Ze(a))||void 0===n?void 0:n.data;r&&jt("local.post.updated",{posts:[r]})}}let Jl;Hl.BATCH_SIZE=50;var Wl=()=>(Jl||(Jl=new Hl),Jl);const Gl=e=>{const{posts:t,postChildren:n,videoStreamings:a}=e,r=Kn(e,["posts","postChildren","videoStreamings"]),s=fc({communities:r.communities}),o=r.communityUsers.map((e=>{const t=r.users.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),i=hc(s,o);let c=[];const l=t.map((t=>{var n,s,o,i;const l=null===(n=r.feeds.find((e=>e.feedId===t.feedId)))||void 0===n?void 0:n.feedType,d=e.postChildren.filter((e=>e.parentPostId===t.postId));var u,h,p;d.length>0&&Vi(d[0])&&(u=a,h=null===(s=d[0].data)||void 0===s?void 0:s.streamId,p=t.postId,c=h?u.map((e=>e.streamId===h?Object.assign(Object.assign({},e),{referenceType:"post",referenceId:p,postId:p}):e)):u);const f=(e.comments||[]).filter((e=>"post"===e.referenceType&&e.referenceId===t.postId)),m=0===f.length?(new Date).toISOString():f.map((e=>e.createdAt)).sort().at(-1);return Wl().queueCommentChangeTask(new $l(t.postId,m,null!==(o=t.commentsCount)&&void 0!==o?o:0)),Object.assign(Object.assign({},t),{childPosts:d,feedType:l,localCommentCount:null!==(i=t.localCommentCount)&&void 0!==i?i:t.commentsCount,pinnedProductId:null==t?void 0:t.pinnedProductId})}));return Object.assign(Object.assign({},r),{postChildren:n,videoStreamings:c,posts:l,communities:i,communityUsers:o})},Yl=e=>{var{searchResult:t,polls:n}=e,a=Kn(e,["searchResult","polls"]);const r=Gl(a);return Object.assign(Object.assign({},r),{polls:n})},Xl=async e=>{const t=ze();let n;t.log("post/getPost",e),ta("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw Oe(null==t?void 0:t.code)&&Fn("post",e),t}const a=Gl(n),r=t.cache&&Date.now();t.cache&&Ln(a,{cachedAt:r});const{posts:s}=a;return{data:s.find((t=>t.postId===e)),cachedAt:r}};Xl.locally=e=>{const t=ze();if(t.log("post/getPost.locally",e),!t.cache)return;const n=Ze(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Zl=async e=>{const t=ze();let n;t.log("comment/getComment",e),ta("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw Oe(null==t?void 0:t.code)&&Fn("comment",e),t}const a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a});const{comments:r}=n;return{data:dl.comment(r.find((t=>t.commentId===e))),cachedAt:a}};Zl.locally=e=>{const t=ze();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=Ze(["comment","get",e]);return n?{data:dl.comment(n.data),cachedAt:n.cachedAt}:void 0};const ed=(e,t)=>{var n,a;let r,s;if("post"===t)s="post",r=e.posts[0].postId;else if("comment"===t)s="comment",r=e.comments[0].commentId;else{if("story"!==t)throw new Error("Unknown event type");s="story",r=e.stories[0].referenceId}return(null===(a=null===(n=Ze([s,"get",r]))||void 0===n?void 0:n.data)||void 0===a?void 0:a.myReactions)||[]},td=(e,t,n)=>{const[a]=e[t];return Object.assign(Object.assign({},e),{[t]:[Object.assign(Object.assign({},a),{myReactions:n})]})},nd=(e,t,n,a=[])=>{const r=e.split(".")[1];let s=a;if(ze().userId===t)if(["addReaction","reactionAdded"].includes(r))s.includes(n)||s.push(n);else{if(!["removeReaction","reactionRemoved"].includes(r))throw new Error(`Unknown event type: ${r}`);s=s.filter((e=>e!==n))}return s},ad=(e,t)=>{const n=e.split(".")[0],a=ed(t,n),r=nd(e,t.reactor.userId,t.reactor.reactionName,a);return td(t,`${n}s`,r)},rd=(e,t)=>{var n,a;const r=e.split(".")[0];let s=ed(t,r);(null==t?void 0:t.reactions)&&t.reactions.length>0&&(s=nd(e,null===(n=t.reactions[0])||void 0===n?void 0:n.userId,null===(a=t.reactions[0])||void 0===a?void 0:a.reactionName,s));const o=td(t,"stories",s);if(!(null==t?void 0:t.communities)||!(null==t?void 0:t.communityUsers))return o;const i=hc(t.communities,t.communityUsers);return Object.assign(Object.assign({},o),{communities:i})},sd=async(e,t,n)=>{var a,r,s;const o=ze();if(o.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Fe("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:i}=await o.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0});if(o.cache){const c=Ze([e,"get",t]);if(!c||(null===(a=c.data.myReactions)||void 0===a?void 0:a.includes(n)))return!0;const l=Object.assign(Object.assign({},c.data),{reactionsCount:c.data.reactionsCount+1,myReactions:[...null!==(r=c.data.myReactions)&&void 0!==r?r:[],n],reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:(null!==(s=c.data.reactions[n])&&void 0!==s?s:0)+1}),updatedAt:(new Date).toISOString()});if("comment"===e)return jt("local.comment.addReaction",{comment:l,reactor:{userId:o.userId,reactionName:n,reactionId:i.addedId}}),!0;if("post"===e)return jt("local.post.addReaction",{post:l,reactor:{userId:o.userId,reactionName:n,reactionId:i.addedId}}),!0;if("story"===e)return jt("local.story.reactionAdded",{story:l,reactor:{userId:o.userId,reactionName:n,reactionId:i.addedId}}),!0}return!0};sd.optimistically=(e,t,n)=>{var a,r,s,o,i;const c=ze();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const l=Ze([e,"get",t]);if(!(null==l?void 0:l.data)||(null===(a=l.data.myReactions)||void 0===a?void 0:a.includes(n)))return;const d=Object.assign(Object.assign({},l.data),{reactionsCount:l.data.reactionsCount+1,myReactions:[...null!==(r=l.data.myReactions)&&void 0!==r?r:[],n],reactions:Object.assign(Object.assign({},l.data.reactions),{[n]:(null!==(s=l.data.reactions[n])&&void 0!==s?s:0)+1})});return nt([e,"get",t],d,{cachedAt:me}),Nc(e,d),null!==(i=null===(o=null==d?void 0:d.myReactions)||void 0===o?void 0:o.includes(n))&&void 0!==i&&i};const od=async(e,t,n)=>{var a,r;const s=ze();if(s.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Fe("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:o}=await s.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0}});if(s.cache){const i=Ze([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!==(a=i.data.myReactions)&&void 0!==a?a:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},i.data.reactions),{[n]:Math.max(0,(null!==(r=i.data.reactions[n])&&void 0!==r?r:0)-1)}),updatedAt:(new Date).toISOString()});if("comment"===e)return jt("local.comment.removeReaction",{comment:c,reactor:{reactionId:o.removedId,reactionName:n,userId:s.userId}}),!0;if("post"===e)return jt("local.post.removeReaction",{post:c,reactor:{reactionId:o.removedId,reactionName:n,userId:s.userId}}),!0;if("story"===e)return jt("local.story.reactionRemoved",{story:c,reactor:{userId:s.userId,reactionName:n,reactionId:o.removedId}}),!0}return!0};od.optimistically=(e,t,n)=>{var a,r,s,o;const i=ze();if(i.log("reaction/removeReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!i.cache)return;const c=Ze([e,"get",t]);if(!(null==c?void 0:c.data)||!(null===(a=c.data.myReactions)||void 0===a?void 0:a.includes(n)))return;const l=Object.assign(Object.assign({},c.data),{reactionsCount:Math.max(0,c.data.reactionsCount-1),myReactions:(null!==(r=c.data.myReactions)&&void 0!==r?r:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:Math.max(0,(null!==(s=c.data.reactions[n])&&void 0!==s?s:0)-1)})});return nt([e,"get",t],l,{cachedAt:me}),Nc(e,l),!(null===(o=null==l?void 0:l.myReactions)||void 0===o?void 0:o.includes(n))};const id=e=>{var t;const n=e.posts[0];if(n.parentId){const e=null===(t=Ze(["post","get",n.parentPostId]))||void 0===t?void 0:t.data;if(!e)return;et(["post","get",e.postId],Object.assign(Object.assign({},e),{children:e.children.filter((e=>e!==n.postId))}))}else n.children.forEach((e=>tt(["post","get",e],{isDeleted:!0})))},cd=(e,t)=>{const n=ze();return Mt(n,e,e,(a=>{var r;if(n.cache){const s=Gl(a),{communities:o}=s;if(Ln(s,void 0,!1),(null==o?void 0:o[0])&&!["post.updated"].includes(e)&&jt("community.updated",{communities:o,categories:[],communityUsers:s.communityUsers,feeds:[],files:[],users:[]}),"post.deleted"===e){const{postId:e,postedUserId:r}=a.posts[0];id(a);try{ta("post",e)}catch(e){return}return r!==n.userId&&at(["post","get",e]),t(a.posts[0])}const i=Ze(["post","get",a.posts[0].postId]);if(["post.created","post.approved","post.declined"].includes(e)){let t=null===(r=Xe(["post","query"]))||void 0===r?void 0:r.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})=>nt(e,t,{cachedAt:-1})))}"post.created"===e&&(e=>{var t;const n=e.posts[0];if(!n.parentId)return;const a=null===(t=Ze(["post","get",n.parentPostId]))||void 0===t?void 0:t.data;a&&et(["post","get",a.postId],Object.assign(Object.assign({},a),{children:[...new Set([n.postId,...a.children])]}))})(a),t(i.data)}else t(a.posts[0])}))},ld=(e,t)=>{const n=ze();return Mt(n,e,e,(a=>{if(n.cache){const{communities:n}=a;(null==n?void 0:n[0])&&!["local.post.updated"].includes(e)&&jt("community.updated",{communities:n,categories:[],communityUsers:a.communityUsers,feeds:[],files:[],users:[]});const r=Ze(["post","get",a.posts[0].postId]);"local.post.deleted"===e&&id(a),t(r.data)}else t(a.posts[0])}))},dd=e=>cd("post.created",e),ud=e=>cd("post.updated",e),hd=e=>cd("post.deleted",e),pd=e=>cd("post.approved",e),fd=e=>cd("post.declined",e),md=e=>cd("post.flagged",e),gd=e=>cd("post.unflagged",e),yd=e=>{const t=ze();return Mt(t,"post.addReaction","post.addReaction",(n=>{if(t.cache){const t=Kn(ad("post.addReaction",n),["reactor"]);Ln(t);const a=Ze(["post","get",n.posts[0].postId]);e(a.data)}else e(n.posts[0])}))},vd=e=>{const t=ze();return Mt(t,"post.removeReaction","post.removeReaction",(n=>{if(t.cache){const t=Kn(ad("post.removeReaction",n),["reactor"]);Ln(t);const a=Ze(["post","get",n.posts[0].postId]);e(a.data)}else e(n.posts[0])}))},bd=(e,t)=>{const n=ze();return Mt(n,e,e,(a=>{var r;if(n.cache){const n=["comment.flagged","comment.unflagged"].includes(e)?(e=>{const t=ed(e,"comment");return td(e,"comments",t)})(a):a;Ln(n,void 0,!1);const{comments:s}=n;if(s.length>0){const n=Ze(["comment","get",s[0].commentId]);if(["comment.created"].includes(e)&&s[0].parentId){const e=Ze(["comment","get",s[0].parentId]);(null==e?void 0:e.data)&&(e.data.children.includes(s[0].commentId)||et(["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(s[0].parentId){const e=Ze(["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))])]});et(["comment","get",s[0].parentId],t)}}const e=null===(r=Xe(["comment","query"]))||void 0===r?void 0:r.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})=>nt(e,t,{cachedAt:-1})))}t(dl.comment(n.data))}}else t(dl.comment(a.comments[0]))}))},wd=(e,t)=>{const n=ze();return Mt(n,e,e,(a=>{var r,s,o,i,c;if(n.cache){const n=a;Ln(n);const{comments:l}=n;if(l.length>0){const n=Ze(["comment","get",l[0].commentId]);if(["local.comment.created"].includes(e)){if(l[0].parentId){const e=Ze(["comment","get",l[0].parentId]);if((null==e?void 0:e.data)&&!e.data.children.includes(l[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,l[0].commentId])]});et(["comment","get",l[0].parentId],t),setTimeout((()=>{jt("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}else{const e=["post","get",l[0].referenceId],t=null===(r=Ze(e))||void 0===r?void 0:r.data;if(t){const n=Object.assign(Object.assign({},t),{comments:[...t.comments,null===(s=l[0])||void 0===s?void 0:s.commentId]});et(e,n)}}const e=null===(o=Xe(["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})=>nt(e,t,{cachedAt:-1})))}if(["local.comment.deleted"].includes(e)){if(l[0].parentId){const e=Ze(["comment","get",l[0].parentId]);if((null==e?void 0:e.data)&&e.data.children.includes(l[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber-1,children:[...new Set([...e.data.children.filter((e=>e!==l[0].commentId))])]});et(["comment","get",l[0].parentId],t),setTimeout((()=>{jt("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}else{const e=["post","get",l[0].referenceId],t=null===(i=Ze(e))||void 0===i?void 0:i.data;if(t){const n=Object.assign(Object.assign({},t),{comments:null==t?void 0:t.comments.filter((e=>{var t;return e!==(null===(t=l[0])||void 0===t?void 0:t.commentId)}))});et(e,n)}}const e=null===(c=Xe(["comment","query"]))||void 0===c?void 0:c.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})=>nt(e,t,{cachedAt:-1})))}t(dl.comment(n.data))}}else t(dl.comment(a.comments[0]))}))},Id=e=>bd("comment.created",e),Cd=e=>bd("comment.updated",e),Sd=e=>bd("comment.deleted",e),Od=e=>bd("comment.flagged",e),Td=e=>bd("comment.unflagged",e),kd=e=>{const t=ze();return Mt(t,"comment.addReaction","comment.addReaction",(n=>{if(t.cache){const t=Kn(ad("comment.addReaction",n),["reactor"]);Ln(t);const a=Ze(["comment","get",n.comments[0].commentId]);e(dl.comment(a.data))}else e(dl.comment(n.comments[0]))}))},Ad=e=>{const t=ze();return Mt(t,"comment.removeReaction","comment.removeReaction",(n=>{if(t.cache){const t=Kn(ad("comment.removeReaction",n),["reactor"]);Ln(t);const a=Ze(["comment","get",n.comments[0].commentId]);e(dl.comment(a.data))}else e(dl.comment(n.comments[0]))}))},_d=(e,t,n)=>{const a=ze(),r=(a,r,s)=>{a===e&&r===t&&n(s)};if("message"===e){return Mt(a,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await pa(e);t.reactions[0]&&(Ln(t),Ln({reactors:t.reactions}),r("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return Mt(a,"post.addReaction","post.addReaction",(e=>{const{reactor:t}=e,n=Kn(e,["reactor"]);Ln(n),Ln({reactions:[t]}),r("post",e.posts[0].postId,t)}))}if("story"===e){return Mt(a,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=Kn(e,["reactions"]);Ln(n),Ln({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&r("story",e.stories[0].storyId,e.reactions[0])}))}return Mt(a,"comment.addReaction","comment.addReaction",(e=>{const{reactor:t}=e,n=Kn(e,["reactor"]);Ln(n),Ln({reactions:[t]}),r("comment",e.comments[0].commentId,t)}))},Ed=(e,t,n)=>{const a=ze(),r=(a,r,s)=>{a===e&&r===t&&n(s)};if("message"===e){return Mt(a,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await pa(e);t.reactions[0]&&(Ln(t),r("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return Mt(a,"post.removeReaction","post.removeReaction",(e=>{const{reactor:t}=e,n=Kn(e,["reactor"]);Ln(n),Ln({reactions:[t]}),r("post",e.posts[0].postId,t)}))}if("story"===e){return Mt(a,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=Kn(e,["reactions"]);Ln(n),Ln({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&r("story",e.stories[0].storyId,e.reactions[0])}))}return Mt(a,"comment.removeReaction","comment.removeReaction",(e=>{const{reactor:t}=e,n=Kn(e,["reactor"]);Ln(n),Ln({reactions:[t]}),r("comment",e.comments[0].commentId,t)}))};class Rd extends wi{async getRequest(e,t){const{limit:n=de,referenceType:a}=e,r=Kn(e,["limit","referenceType"]),s=t?{token:t}:{limit:n};ze().log("reaction/queryReactions",e);if(!["post","comment","story","message"].includes(a))throw new Fe("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:o}=await this.http.get("/api/v3/reactions",{params:Object.assign(Object.assign({},r),{referenceType:a,referenceVersion:"message"===a?5:void 0,options:s})});return o}}class Pd extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){var t;const n=await this.preparePayload(e),a=ze(),r=a.cache&&Date.now();if(a.cache){const{reactions:e}=n,a=Kn(n,["reactions"]);Ln(Object.assign(Object.assign({},a),{reactions:e,reactors:null===(t=e[0])||void 0===t?void 0:t.reactors}),{cachedAt:r})}}appendToQueryStream(e,t,n=!1){var a,r,s,o;const i=null!==(r=null===(a=e.reactions[0])||void 0===a?void 0:a.reactors)&&void 0!==r?r:[];if(n)et(this.cacheKey,{data:i.map(We("reactor"))});else{const e=null===(s=Ze(this.cacheKey))||void 0===s?void 0:s.data,t=null!==(o=null==e?void 0:e.data)&&void 0!==o?o:[];et(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...i.map(We("reactor"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;a&&("onAdded"===e?a.data=[...new Set([t.reactionId,...a.data])]:"onRemoved"===e&&(a.data=a.data.filter((e=>e!==t.reactionId))),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Md extends ki{constructor(e,t){const n=O.default(e),a=["reaction","collection",n];super(new Rd(e),n,a,t),this.query=e,this.queryStreamController=new Pd(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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=>_d(this.query.referenceType,this.query.referenceId,e),action:"onAdded"},{fn:e=>Ed(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const a=ze(),r=(a,r,s)=>{a===e&&r===t&&n(s)};if("message"===e)return Mt(a,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await pa(e);t.reactions[0]&&(Ln(t),r("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return Mt(a,"local.post.removeReaction","local.post.removeReaction",(e=>{r("post",e.post.postId,e.reactor)}));if("story"===e)return Mt(a,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=Kn(e,["reactions"]);Ln(n),Ln({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&r("story",e.stories[0].storyId,e.reactions[0])}));return Mt(a,"local.comment.removeReaction","local.comment.removeReaction",(e=>{r("comment",e.comment.commentId,e.reactor)}))})(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const a=ze(),r=(a,r,s)=>{a===e&&r===t&&n(s)};if("message"===e)return Mt(a,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await pa(e);t.reactions[0]&&(Ln(t),Ln({reactors:t.reactions}),r("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return Mt(a,"local.post.addReaction","local.post.addReaction",(e=>{r("post",e.post.postId,e.reactor)}));if("story"===e)return Mt(a,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=Kn(e,["reactions"]);Ln(n),Ln({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&r("story",e.stories[0].storyId,e.reactions[0])}));return Mt(a,"local.comment.addReaction","local.comment.addReaction",(e=>{r("comment",e.comment.commentId,e.reactor)}))})(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=null!==(r=s.data.map((e=>Ze(["reactor","get",e]))).filter(Boolean).map((({data:e})=>dl.reactor(e))))&&void 0!==r?r:[];(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var jd=Object.freeze({__proto__:null,addReaction:sd,removeReaction:od,onReactionAdded:(e,t,n)=>{const a=a=>{We(e)(a)===t&&n(a)};if("message"===e){const e=ze(),t=async e=>{var t;const n=await pa(e),r=Ze(["message","get",n.messages[0].messageId]),s=(null===(t=null==r?void 0:r.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Ln(n),s&&a(n.messages[0])};return Mt(e,"reaction/onReactionAdded","message.updated",t)}return"post"===e?yd(a):kd(a)},onReactionRemoved:(e,t,n)=>{const a=a=>{We(e)(a)===t&&n(a)};if("message"===e){const e=ze(),t=async e=>{var t;const n=await pa(e),r=Ze(["message","get",n.messages[0].messageId]),s=(null===(t=null==r?void 0:r.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Ln(n),s&&a(n.messages[0])};return Mt(e,"reaction/onReactionRemoved","message.updated",t)}return"post"===e?vd(a):Ad(a)},onReactorAdded:_d,onReactorRemoved:Ed,getReactions:(e,t,n)=>{const{log:a,cache:r}=ze(),s=Date.now();a(`getReactions(tmpid: ${s}) > listen`);const o=new Md(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{at(c)})),()=>{a(`getReactions(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}}});function Ud(e){const{comments:t}=e;return Object.assign(Object.assign({},e),{comments:t.map((e=>e.hasOwnProperty("myReactions")?e:Object.assign({myReactions:[]},e)))})}const Dd=async()=>{var e;const t=ze();t.log("channel/getArchivedChannelIds");const{data:n}=await t.http.get("/api/v1/archives/channels"),a=null!==(e=n.archives)&&void 0!==e?e:[];return t.cache&&(at(["archivedChannel","get"]),a.forEach((e=>{e.channelId&&et(["archivedChannel","get",e.channelId],e)}))),a.map((e=>e.channelId)).filter((e=>!!e))},xd=e=>{const t=ze(),n=[Mt(t,"onMessageUpdated","message.updated",(async t=>{const n=await pa(t);Ln(n),e(n.messages[0])})),Mt(t,"onMessageUpdated","local.message.updated",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},qd=e=>{const t=ze(),n=[Mt(t,"message/onMessageDeleted","message.deleted",(async t=>{const n=await pa(t);Ln(n),e(n.messages[0])})),Mt(t,"message/onMessageDeleted","local.message.deleted",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},Nd=e=>{const t=ze(),n=[Mt(t,"onSubChannelUpdated","message-feed.updated",(async t=>{const n=await ba(t);Ln(n),e(n.messageFeeds[0])})),Mt(t,"onSubChannelUpdated","local.message-feed.updated",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}};function Bd(e,t){et(["channel","get",e.channelId],Zn(e,t))}const Ld=e=>{const t=ze();return Mt(t,"channelMarker/onChannelMarkerUpdated","local.channelMarker.updated",(t=>{e(t.userEntityMarkers[0])}))},Fd=async(e,t=!1)=>{const n=ze(),a=await wa(e);await n.http.delete(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{params:{permanent:t}});const r=Object.assign(Object.assign({},a.data),{isDeleted:!0,updatedAt:Ye(a.data.updatedAt)});return t?setTimeout((()=>{Fn("subChannel",e)}),0):nt(["subChannel","get",e],r),jt("local.message-feed.deleted",{messageFeeds:[r]}),r},Kd=e=>Mt(ze(),"onSubChannelFetched","local.message-feed.fetched",(t=>e(t.messageFeeds[0]))),$d=()=>`LOCAL_${Mn()}`;let Qd;const Vd=async(e,t)=>{const n=ze();n.log("message/updateMessage",t),console.warn("MessageRepository.updateMessage will be replaced with MessageRepository.editMessage");const{data:a}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,fa(t)),r=await pa(a),s=n.cache&&Date.now();n.cache&&Ln(r,{cachedAt:s});const{messages:o}=r;return jt("local.message.updated",{messages:o}),{data:dl.message(o.find((t=>t.messageId===e))),cachedAt:s}};Vd.optimistically=(e,t)=>{const n=ze();if(n.log("message/updateMessage.optimistically",t),!n.cache)return;const a=Ze(["message","get",e]);if(!a)return;const r=Object.assign(Object.assign(Object.assign({},a.data),t),{updatedAt:(new Date).toISOString()});return nt(["message","get",e],r,{cachedAt:-1}),jt("local.message.updated",{messages:[r]}),{data:dl.message(r),cachedAt:-1}};const zd=async(e,t)=>{const n=ze();n.log("message/editMessage",t);const{data:a}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,fa(t)),r=await pa(a),s=n.cache&&Date.now();n.cache&&Ln(r,{cachedAt:s});const{messages:o}=r;return jt("local.message.updated",{messages:o}),{data:dl.message(o.find((t=>t.messageId===e))),cachedAt:s}};zd.optimistically=(e,t)=>{const n=ze();if(n.log("message/editMessage.optimistically",t),!n.cache)return;const a=Ze(["message","get",e]);if(!a)return;const r=Object.assign(Object.assign(Object.assign({},a.data),t),{updatedAt:(new Date).toISOString()});return nt(["message","get",e],r,{cachedAt:-1}),jt("local.message.updated",{messages:[r]}),{data:dl.message(r),cachedAt:-1}};const Hd=async e=>{var t;const n=ze();if(n.log("message/deleteMessage",e),e.includes("LOCAL_")){const n=null===(t=Ze(["message","get",e]))||void 0===t?void 0:t.data;if(!n)throw Error("messageId not found");const a=Object.assign(Object.assign({},n),{isDeleted:!0});return jt("local.message.deleted",{messages:[a]}),dl.message(a)}const{data:a}=await n.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`),r=await pa(a);return jt("local.message.deleted",{messages:[r.messages[0]]}),dl.message(r.messages[0])};Hd.optimistically=e=>{ze().log("message/deleteMessage.optimistically",e);const t=Ze(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return nt(["message","get",e],n,{cachedAt:-1}),jt("local.message.deleted",{messages:[n]}),{data:dl.message(n),cachedAt:-1}};const Jd=async e=>{const t=ze();t.log("message/softDeleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const n=await Kl(e);return jt("local.message.deleted",{messages:[n.data]}),dl.message(n.data)};Jd.optimistically=e=>{ze().log("message/softDeleteMessage.optimistically",e);const t=Ze(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return nt(["message","get",e],n,{cachedAt:-1}),jt("local.message.deleted",{messages:[n]}),{data:dl.message(n),cachedAt:-1}};const Wd=async e=>{const t=ze();t.log("user/getReadUsers",e);const{page:n,messageId:a}=e,r=Kn(e,["page","messageId"]),{data:s}=await t.http.get(`/api/v1/markers/messages/${a}/read-users`,{params:Object.assign(Object.assign({},r),{options:{token:Ee(n,"afterbeforeraw")}})}),{paging:o,publicUserIds:i,userFeedMarkers:c}=s,l=Kn(s,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Ln(Object.assign(Object.assign({},l),{userFeedMarkers:Hn(c)}),{cachedAt:d});const e=["read-user","query",Object.assign(Object.assign({messageId:a},r),{options:Object.assign({},n)})];et(e,{users:i,paging:o})}let u=[];i.length>0&&({data:u}=await ul(i));return{data:u,cachedAt:d,prevPage:Re(o.previous),nextPage:Re(o.next)}};Wd.locally=e=>{var t;const n=ze();if(n.log("user/getReadUsers.locally",e),!n.cache)return;const{page:a}=e,r=Kn(e,["page"]),s=["read-user","query",Object.assign(Object.assign({},r),{options:Object.assign({},a)})],{data:o,cachedAt:i}=null!==(t=Ze(s))&&void 0!==t?t:{},c=null==o?void 0:o.users.map((e=>{var t;return null===(t=Ze(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:i,prevPage:Re(null==o?void 0:o.paging.previous),nextPage:Re(null==o?void 0:o.paging.next)}};const Gd=async e=>{const t=ze();t.log("user/getDeliveredUsers",e);const{page:n,messageId:a}=e,r=Kn(e,["page","messageId"]),{data:s}=await t.http.get(`/api/v1/markers/messages/${a}/delivered-users`,{params:Object.assign(Object.assign({},r),{options:{token:Ee(n,"afterbeforeraw")}})}),{paging:o,publicUserIds:i,userFeedMarkers:c}=s,l=Kn(s,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Ln(Object.assign(Object.assign({},l),{userFeedMarkers:Hn(c)}),{cachedAt:d});const e=["delivered-user","query",Object.assign(Object.assign({messageId:a},r),{options:Object.assign({},n)})];et(e,{users:i,paging:o})}let u=[];i.length>0&&({data:u}=await ul(i));return{data:u,cachedAt:d,prevPage:Re(o.previous),nextPage:Re(o.next)}};Gd.locally=e=>{var t;const n=ze();if(n.log("user/getDeliveredUsers.locally",e),!n.cache)return;const{page:a}=e,r=Kn(e,["page"]),s=["delivered-user","query",Object.assign(Object.assign({},r),{options:Object.assign({},a)})],{data:o,cachedAt:i}=null!==(t=Ze(s))&&void 0!==t?t:{},c=null==o?void 0:o.users.map((e=>{var t;return null===(t=Ze(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:i,prevPage:Re(null==o?void 0:o.paging.previous),nextPage:Re(null==o?void 0:o.paging.next)}};const Yd=e=>{const t=ze();return Mt(t,"onMessageFlagged","message.flagged",(async t=>{const n=await pa(t);Ln(n),e(n.messages[0])}))},Xd=e=>{const t=ze();return Mt(t,"onMessageUnflagged","message.unflagged",(async t=>{const n=await pa(t);Ln(n),e(n.messages[0])}))},Zd=e=>{const t=ze();return Mt(t,"onMessageFlagCleared","message.flagCleared",(async t=>{const n=await pa(t);Ln(n),e(n.messages[0])}))},eu=e=>{const t=ze();return Mt(t,"onMessageReactionAdded","message.reactionAdded",(async t=>{const n=await pa(t,"message.reactionAdded");Ln(n),e(n.messages[0])}))},tu=e=>{const t=ze();return Mt(t,"onMessageReactionRemoved","message.reactionRemoved",(async t=>{const n=await pa(t,"message.reactionRemoved");Ln(n),e(n.messages[0])}))},nu=e=>{const t=ze();return Mt(t,"message/onMessageFetched","local.message.fetched",(t=>{Ln(t),e(t.messages[0])}))},au=e=>{const t=ze();return Mt(t,"stream/onStreamViewerDidBan","video-streaming.viewerDidBan",(t=>{var n;const{list:a}=t;a.forEach((e=>{var t;tt(["stream","get",e.streamId],{watcherUrl:null});const n=null===(t=Xe(["message","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.creatorId===e.userId));null==n||n.forEach((e=>{tt(e.key,{isDeleted:!0})}))}));const r=null===(n=Ze(["stream","get",a[0].streamId]))||void 0===n?void 0:n.data;r&&e(r)}))};class ru extends Ci{constructor(e,t,n,a,r){super(e,t),this.notifyChange=n,this.preparePayload=a,this.paginationController=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.messages.map(We("message")),query:this.query});else{const n=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,s=null!==(r=null==n?void 0:n.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},n),{data:"next"===t?[...new Set([...s,...e.messages.map(We("message"))])]:[...new Set([...e.messages.map(We("message")),...s])]}))}}reactor(e){return t=>{var n,a,r,s;if("onCreate"===e){const e=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data,{referenceId:s}=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===(a=this.query.excludingTags)||void 0===a?void 0:a.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===(r=this.query.includingTags)||void 0===r?void 0:r.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!=s?s:t.messageId,...e.data])]),"segmentAsc"!==this.query.sortBy||this.paginationController.getNextToken()||(e.data=[...new Set([...e.data,null!=s?s:t.messageId])]),et(this.cacheKey,e)}if("onDelete"===e&&"error"===t.syncState){const e=null===(s=Ze(this.cacheKey))||void 0===s?void 0:s.data;if(!e)return;if(e.data.includes(t.messageId)){const n=e.data.filter((e=>e!==t.messageId));et(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 su extends wi{async getRequest(e,t){const n=ma(e),{data:a}=await this.http.get("/api/v5/messages",{params:Object.assign(Object.assign({},n),{options:t?{token:t}:Object.assign({},n.options)})});return a}}class ou extends ki{constructor(e,t){const n=O.default(e),a=["message","collection",n];super(new su(e),n,a,t),this.query=e,this.queryStreamController=new ru(this.query,this.cacheKey,this.notifyChange.bind(this),pa,this.paginationController),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:bo,action:"onCreate"},{fn:wo,action:"onCreate"},{fn:qd,action:"onDelete"},{fn:xd,action:"onUpdate"},{fn:Yd,action:"onFlagged"},{fn:Xd,action:"onUnflagged"},{fn:Zd,action:"onFlagCleared"},{fn:eu,action:"onReactionAdded"},{fn:tu,action:"onReactionRemoved"},{fn:Tl(Xo,"contentId","message"),action:"onUpdate"},{fn:Tl(Zo,"contentId","message"),action:"onUpdate"},{fn:Tl(au,"channelId","message"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>sa(e))).filter(Boolean).map((e=>dl.message(e))))&&void 0!==r?r:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),onPrevPage:()=>this.loadPage({direction:"prev"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),hasPrevPage:!!this.paginationController.getPrevToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.includeDeleted||(t=rt(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=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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)}}class iu extends wi{async getRequest(e,t){const{query:n,exactMatch:a,channelId:r,messageFeedId:s,userIds:o,tags:i,types:c,sortBy:l,orderBy:d,limit:u=de}=e,h=t?{token:t}:{limit:u,sortBy:l,orderBy:d},{data:p}=await this.http.get("/api/v2/search/messages",{params:{query:n,exactMatch:a,channelId:r,messageFeedId:s,userIds:o,tags:i,types:c,options:h}});return p}}class cu extends Ci{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){var t;const n=await pa(e),a=ze(),r=a.cache&&Date.now();a.cache&&(Ln(n,{cachedAt:r}),(null===(t=e.channels)||void 0===t?void 0:t.length)&&e.channels.forEach((e=>{et(["channel","get",e.channelId],e,{cachedAt:r})})))}appendToQueryStream(e,t,n=!1){var a,r;if(n)return void et(this.cacheKey,{data:e.messages.map(We("message"))});const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,o=null!==(r=null==s?void 0:s.data)&&void 0!==r?r:[],i=e.messages.map(We("message"));et(this.cacheKey,Object.assign(Object.assign({},s),{data:"prev"===t?[...new Set([...i,...o])]:[...new Set([...o,...i])]}))}}class lu extends ki{constructor(e,t){const n=O.default(e),a=["message","search",n];super(new iu(e),n,a,t),this.queryStreamController=new cu(e,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return[]}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=null!==(r=s.data.map((e=>sa(e))).filter(Ai).map((e=>dl.message(e))))&&void 0!==r?r:[];(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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)}}var du=Object.freeze({__proto__:null,createMessage:async e=>{const t=ze();t.log("message/createMessage",e);const n=(e=>{var t,n;const a=ze();if(!a.cache)return;Qd=e.referenceId||$d();const r=Object.assign({messageId:Qd,uniqueId:Qd},e);a.log("message/createMessage.optimistically",r);const s=Ze(["subChannel","get",e.subChannelId]);if(s&&(nt(["subChannel","get",e.subChannelId],Object.assign(Object.assign({},s.data),{messageCount:s.data.messageCount+1})),s.data.channelId===s.data.subChannelId)){const e=Ze(["channel","get",s.data.channelId]);(null==e?void 0:e.data)&&nt(["channel","get",s.data.channelId],Object.assign(Object.assign({},e.data),{messageCount:(null!==(t=e.data.messageCount)&&void 0!==t?t:0)+1}))}const o=(new Date).toISOString(),i=Object.assign({creatorId:a.userId,creatorPrivateId:kt()._id,channelSegment:(null!==(n=null==s?void 0:s.data.messageCount)&&void 0!==n?n:0)+1,childrenNumber:0,createdAt:o,updatedAt:o,syncState:"syncing",isDeleted:!1},r);return et(["message","get",i.messageId],i,{cachedAt:-5}),jt("local.message.created",{messages:[i]}),i})(e),a=e.referenceId||Qd||$d();Qd=void 0;try{const{data:n}=await t.http.post("/api/v5/messages",Object.assign(Object.assign({},fa(e)),{referenceId:a})),r=await pa(n),{messages:s}=r,o=t.cache&&Date.now();return t.cache&&Ln(r,{cachedAt:o}),jt("local.message.created",{messages:[Object.assign(Object.assign({},s[0]),{syncState:"synced"})]}),{data:dl.message(s[0]),cachedAt:o}}catch(e){throw jt("local.message.created",{messages:[Object.assign(Object.assign({},n),{syncState:"error"})]}),e}},updateMessage:Vd,editMessage:zd,deleteMessage:Hd,softDeleteMessage:Jd,markAsDelivered:async(e,t)=>{const n=ze();n.log("message/markAsDelivered",e,t);const{data:a}=await n.http.put(`/api/v1/markers/message-feeds/${e}/mark-delivering`,{messageId:t}),{userMarkers:r,userEntityMarkers:s,userFeedMarkers:o}=a,i=Kn(a,["userMarkers","userEntityMarkers","userFeedMarkers"]),c=n.cache&&Date.now();return n.cache&&Ln(Object.assign({userMarkers:r,userEntityMarkers:zn(s),userFeedMarkers:Hn(o)},i),{cachedAt:c}),!0},getReadUsers:Wd,getDeliveredUsers:Gd,flagMessage:async(t,n)=>{const a=ze();a.log("message/flag",t);const r=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,a])=>t!==e.ContentFlagReasonEnum.Others&&a===n)),s={reason:r?n:e.ContentFlagReasonEnum.Others,detail:r?"":n},{data:o}=await a.http.post(`/api/v5/messages/${encodeURIComponent(t)}/flags`,s);if(a.cache){const e=await pa(o);Ln(e)}return jt("message.flagged",o),!!o},unflagMessage:async e=>{const t=ze();t.log("message/unflag",e);const{data:n}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await pa(n);Ln(e)}return jt("message.unflagged",n),!!n},isMessageFlaggedByMe:async e=>{const t=ze();t.log("message/isMessageFlaggedByMe",e);const{data:n}=await t.http.get(`/api/v5/messages/${encodeURIComponent(e)}/flags`);return n.result},onMessageCreatedMqtt:bo,onMessageCreatedLocal:wo,onMessageUpdated:xd,onMessageDeleted:qd,onMessageFlagged:Yd,onMessageUnflagged:Xd,onMessageFlagCleared:Zd,onMessageReactionAdded:eu,onMessageReactionRemoved:tu,onMessageFetched:nu,getMessage:(e,t)=>Ui(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?dl.message(e.data):n}))}),"messageId",Kl,[nu,xd,qd,Yd,Xd,Zd,eu,tu,Tl(Xo,"contentId","message"),Tl(Zo,"contentId","message"),Tl(au,"channelId","message")]),getMessages:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`getMessages(tmpid: ${s}) > listen`);const o=new ou(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{at(c)})),()=>{a(`getMessages(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},searchMessage:(e,t)=>{if(!e.query||0===e.query.trim().length)throw new Error("Query is required for message search");const{log:n,cache:a}=ze();a||console.log(pe);const r=Date.now();n(`searchMessage(tmpid: ${r}) > listen`);const s=new lu(e,t),o=s.startSubscription(),i=s.getCacheKey();return o.push((()=>{at(i)})),()=>{n(`searchMessage(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},convertFromRaw:ua,prepareMessagePayload:pa,convertParams:fa,convertQueryParams:ma});const uu=e=>{const t=ze();return Mt(t,"subChannelMarker/onSubChannelUnreadUpdatedLocal","local.subChannelUnread.updated",(t=>{e(t)}))};class hu extends wi{async getRequest(e,t){var n;const{limit:a=de}=e,r=null!==(n=function(e){var{excludeDefaultSubChannel:t}=e,n=Kn(e,["excludeDefaultSubChannel"]);const a=Object.assign({},n);return void 0!==t&&(a.excludeDefaultMessageFeed=t),a}(Kn(e,["limit"])))&&void 0!==n?n:{},{channelId:s,includeDeleted:o}=r,i=Kn(r,["channelId","includeDeleted"]),c=t?{token:t}:{limit:a},{data:l}=await this.http.get(`/api/v5/message-feeds/channel/${s}`,{params:Object.assign(Object.assign({},i),{isDeleted:oa(o),options:c})});return l}}class pu extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.messageFeeds.map((({messageFeedId:e})=>e))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.messageFeeds.map((({messageFeedId:e})=>e))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(!Array.isArray(t)){if(this.query.channelId!==t.channelId)return;"onCreate"===e&&(a.data=[...new Set([t.subChannelId,...a.data])]),et(this.cacheKey,a)}this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class fu extends ki{constructor(e,t){const n=O.default(e),a=["subChannel","collection",n];super(new hu(e),n,a,t),this.query=e,this.queryStreamController=new pu(this.query,this.cacheKey,this.notifyChange.bind(this),ba),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:Kd,action:"onCreate"},{fn:Io,action:"onCreate"},{fn:Co,action:"onDelete"},{fn:e=>Nd((async t=>{if(!this.isRelatedCollection(t.subChannelId))return;const n=ze();if("no-message-preview"!==await n.getMessagePreviewSetting(!1)){const e=Gn(t.subChannelId);(null==e?void 0:e.subChannelId)===t.subChannelId&&Wn(t.updatedAt)>Wn(e.subChannelUpdatedAt)&&et(["messagePreviewSubChannel","get",t.subChannelId],Object.assign(Object.assign({},e),{subChannelName:t.displayName,subChannelUpdatedAt:t.updatedAt}))}e(t)})),action:"onUpdate"},{fn:Tl((e=>bo((async t=>{this.isRelatedCollection(t.subChannelId)&&(await Ca(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Tl((e=>wo((async t=>{this.isRelatedCollection(t.subChannelId)&&(await Ca(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:e=>Go((t=>{var n;const a=null!==(n=t.map((({feedId:e})=>Ze(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];0!==a.length&&e(a)})),action:"onUpdate"},{fn:Tl(Wo,"feedId","subChannel"),action:"onUpdate"},{fn:Tl((e=>xd((async t=>{var n;const a=ze();if("no-message-preview"===await a.getMessagePreviewSetting(!1))return;const r=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;r&&r.data.includes(t.subChannelId)&&(Sa(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Tl((e=>qd((async t=>{const n=ze(),a=await n.getMessagePreviewSetting(!1);"no-message-preview"!==a&&this.isRelatedCollection(t.subChannelId)&&("message-preview-not-include-deleted"===a?await wa(t.subChannelId):await Sa(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Tl(uu,"subChannelId","subChannel"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(Yn))&&void 0!==r?r:[]);(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;return this.query.includeDeleted||(t=rt(e,"isDeleted",!1)),t.sort(Ct),t}isRelatedCollection(e){var t;const n=null===(t=Ze(this.cacheKey))||void 0===t?void 0:t.data;return n&&n.data.includes(e)}}const mu={},gu=async e=>{const t=await(async e=>{const t=wa.locally(e);if(t)return t.data.channelId;const{data:n}=await wa(e);return n.channelId})(e),n=Qt({channelId:t,subChannelId:e});mu[e]=Gt(n)};var yu=Object.freeze({__proto__:null,getSubChannelByIds:Br,createSubChannel:async e=>{const t=ze();t.log("user/createSubChannel",e);const n=await t.http.post("/api/v5/message-feeds",{channelId:e.channelId,name:e.displayName}),a=await ba(n.data),r=t.cache&&Date.now();return t.cache&&Ln(a,{cachedAt:r}),jt("message-feed.created",n.data),{data:a.messageFeeds[0],cachedAt:r}},updateSubChannel:async(e,t)=>{const n=ze();n.log("channel/updateSubChannel",e,t);const a=await n.http.put(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{name:t.displayName}),r=await ba(a.data),s=n.cache&&Date.now();return n.cache&&Ln(r,{cachedAt:s}),jt("message-feed.updated",a.data),{data:r.messageFeeds[0],cachedAt:s}},deleteSubChannel:Fd,hardDeleteSubChannel:async e=>{ze().log("channel/hardDeleteSubChannel",e);return await Fd(e,!0)},softDeleteSubChannel:async e=>{ze().log("channel/softDeleteSubChannel",e);return await Fd(e,!1)},onSubChannelCreated:Io,onSubChannelUpdated:Nd,onSubChannelDeleted:Co,getSubChannel:(e,t)=>{const n=ze();let a;return Ui(e,(e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:Yn(e.data)}),r=Kn(n,["origin"]);return La(a,r)?void 0:(a=r,t(n))}),"subChannelId",wa,[Kd,t=>Nd((async a=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(ka(a),a.subChannelId===e&&t(a))})),Co,Tl(Wo,"feedId","subChannel"),t=>Go((n=>{var a;if(!n.find((({feedId:t})=>t===e)))return;const r=null===(a=Ze(["subChannel","get",e]))||void 0===a?void 0:a.data;r&&t(r)})),Tl((t=>bo((async n=>{n.subChannelId===e&&(await Ca(n),t(n))}))),"subChannelId","subChannel"),Tl((t=>wo((async n=>{n.subChannelId===e&&(await Ca(n),t(n))}))),"subChannelId","subChannel"),Tl((t=>xd((async a=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&a.subChannelId===e&&(Sa(a),t(a))}))),"subChannelId","subChannel"),Tl((t=>qd((async a=>{const r=await n.getMessagePreviewSetting(!1);"no-message-preview"!==r&&a.subChannelId===e&&("message-preview-include-deleted"===r&&await Sa(a),"message-preview-not-include-deleted"===r&&await wa(a.subChannelId),t(a))}))),"subChannelId","subChannel"),Tl(uu,"subChannelId","subChannel")],{forceDispatch:!0})},getSubChannels:(e,t,n)=>{const{log:a,cache:r}=ze(),s=Date.now();a(`getSubChannels(tmpid: ${s}) > listen`),r||console.log(pe);const o=new fu(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{at(c)})),()=>{a(`getSubChannels(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},markReadEngineOnLoginHandler:Nr,startMessageReceiptSync:async e=>(await gu(e),!0),stopMessageReceiptSync:e=>(mu[e]&&mu[e](),!0)});const vu=e=>{const t=ze();return Mt(t,"channelMarker/onChannelUnreadInfoUpdatedLocal","local.channelUnreadInfo.updated",(t=>{e(t)}))},bu=e=>{const t=ze();return Mt(t,"channel/onChannelUnreadUpdatedLocal","local.channelUnread.updated",(t=>{e(t)}))};class wu extends wi{async getRequest(e,t){const{limit:n=de,displayName:a,membership:r}=e,s=Kn(e,["limit","displayName","membership"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/channels",{params:Object.assign(Object.assign({},s),{keyword:a,filter:r,options:o})});return i}}class Iu extends Ti{async getRequest(e){const{data:t}=await this.http.get("/api/v3/channels/list",{params:Object.assign({},e)});return t}}class Cu extends Ci{constructor(e,t,n,a,r){super(e,t),this.notifyChange=n,this.preparePayload=a,this.paginationController=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.channels.map(We("channel"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channels.map(We("channel"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(this.paginationController instanceof Iu)return this.notifyChange({origin:"event",loading:!1});if(["onCreate","onJoin","onResolveChannel","onUnarchived"].includes(e)&&(Array.isArray(t)?a.data=[...new Set([...t.map(We("channel")),...a.data])]:a.data=[...new Set([t.channelInternalId,...a.data])]),"onArchived"===e){const e=Array.isArray(t)?t.map(We("channel")):[We("channel")(t)];a.data=a.data.filter((t=>!e.includes(t)))}et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Su=e=>{const t=ze();if(t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()){Ps().resolve(e.channelId,"userMessageFeedMarker")}},Ou=e=>{const t=ze();return Mt(t,"onChannelResolved","local.channel.resolved",(async t=>{e(t)}))},Tu=e=>{const t=ze();return Mt(t,"userMessageFeedMarker/onUserMessageFeedMarkerResolved","local.userMessageFeedMarkers.resolved",(t=>{e(t)}))};class ku extends ki{constructor(e,t){const n=O.default(e),a=["channel","collection",n],r=ku.getPaginationController(e);super(r,n,a,t),this.query=e,this.queryStreamController=new Cu(this.query,this.cacheKey,this.notifyChange.bind(this),(async e=>{try{const t=ze();t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await ja(e)}catch(e){console.error("Error while preparing unread count info",e)}return Pa(e)}),r),this.paginationController=r,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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 a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;let o=null!==(r=s.data.map((e=>Ze(["channel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(Pr))&&void 0!==r?r:[];this.paginationController instanceof wu&&(o=this.applyFilter(o)),(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:this.paginationController instanceof wu?()=>this.loadPage({direction:"next"}):void 0,data:o,hasNextPage:this.paginationController instanceof wu&&!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=ze();let n=e;switch(n=rt(n,"isDeleted",this.query.isDeleted),n=st(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=it(n,this.query.membership,t)),this.query.sortBy){case"firstCreated":n=n.sort(yt);break;case"lastCreated":n=n.sort(bt);break;case"displayName":n=n.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(mt);break;default:n=n.sort(Ct)}return n}shouldAbort(e){var t,n;const a=null===(t=Ze(this.cacheKey))||void 0===t?void 0:t.data;if(!a)return!0;return!(null===(n=null==a?void 0:a.data)||void 0===n?void 0:n.find((t=>t===e)))}static getMessagePreviewSetting(){return ze().getMessagePreviewSetting(!1)}static getPaginationController(e){return e.channelIds&&e.channelIds.length>0?new Iu(e):new wu(e)}getSubscriptions(){const e=[{fn:Tl((e=>bo((t=>{var n,a;const r=Ps();(null===(n=Ze(["subChannelUnreadInfo","get",t.subChannelId]))||void 0===n?void 0:n.data)||r.resolve(t.subChannelId,"userMessageFeedMarker");const s=null===(a=Ze(["channel","get",t.channelId]))||void 0===a?void 0:a.data;s?(Bd(s,{lastActivity:t.createdAt}),e(t)):r.resolve(t.channelId,"channel")}))),"channelId","channel"),action:"onUpdate"},{fn:Tl((e=>wo((t=>{var n;const a=null===(n=Ze(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Bd(a,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ya,action:"onDelete"},{fn:za,action:"onUpdate"},{fn:or,action:"onMute"},{fn:e=>er((t=>{Su(t),e(t)})),action:"onJoin"},{fn:e=>ar(((t,n)=>{var a,r;const{userId:s}=ze();if("member"===this.query.membership&&s===n.userId){const e=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;et(this.cacheKey,Object.assign(Object.assign({},e),{data:null!==(r=null==e?void 0:e.data.filter((e=>e!==t.channelId)))&&void 0!==r?r:[]}))}return e(t)})),action:"onLeft"},{fn:lr,action:"onMemberAdded"},{fn:hr,action:"onMemberRemoved"},{fn:e=>Tr((t=>{const n=t.archives.map((e=>{var t;return null===(t=Ze(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onArchived"},{fn:e=>kr((t=>{const n=t.archives.map((e=>{var t;return null===(t=Ze(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onUnarchived"},{fn:Tl(Jo,"entityId","channel"),action:"onUpdate"},{fn:Tl(Ld,"entityId","channel"),action:"onUpdate"},{fn:Tl((e=>bo((async t=>{var n;if("no-message-preview"===await ku.getMessagePreviewSetting())return;if(Oa(t),this.shouldAbort(t.channelId))return;const a=null===(n=Ze(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Bd(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Tl((e=>wo((async t=>{var n;if("no-message-preview"===await ku.getMessagePreviewSetting())return;if(Oa(t),this.shouldAbort(t.channelId))return;const a=null===(n=Ze(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Bd(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Tl((e=>xd((async t=>{"no-message-preview"!==await ku.getMessagePreviewSetting()&&(Ta(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Tl((e=>qd((async t=>{const n=await ku.getMessagePreviewSetting();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await Ta(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&await Bi(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:Tl((e=>Co((async t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(!a)return;a.data.find((e=>{const n=Jn(e);return(null==n?void 0:n.subChannelId)===t.subChannelId}))&&(await Bi(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Tl((e=>Nd((async t=>{var n;if("no-message-preview"===await ku.getMessagePreviewSetting())return;(null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data)&&(await ka(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Tl(Io,"channelId","channel"),action:"onUpdate"},{fn:Ou,action:"onResolveChannel"},{fn:e=>Tu((async t=>{if(t.feedMarkers){const n=t.feedMarkers.map((e=>{var t;return null===(t=Ze(["channel","get",e.entityId]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"OnResolveUnread"},{fn:Tl(vu,"channelId","channel"),action:"onUpdate"},{fn:Tl((e=>bu((t=>{t.forEach(e)}))),"channelId","channel"),action:"onUpdate"}];return this.paginationController instanceof wi?[...e,{fn:e=>$a((t=>{Su(t),e(t)})),action:"onCreate"}]:e}}const Au=()=>{var e;const t=ze();t.log("channel/getTotalChannelsUnread.locally");const n=(null===(e=Xe(["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 _u extends wi{async getRequest(e,t){var n,a;const r=null!==(n=e.limit)&&void 0!==n?n:de,s=t?Number.parseInt(t,10):0;0===s&&await Dd();const o=(null!==(a=Xe(["archivedChannel","get"]))&&void 0!==a?a:[]).map((e=>e.data)).slice().sort(((e,t)=>Number(new Date(t.archivedAt))-Number(new Date(e.archivedAt)))),i=s*r,c=i+r,l=o.slice(i,c),d=c<o.length;return l.length>0&&await Mr(l.map((e=>e.channelId))),{archives:l,paging:{next:d?String(s+1):void 0,previous:void 0}}}}class Eu extends Ci{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){}appendToQueryStream(e,t,n=!1){var a,r;const s=e.archives.map((e=>e.channelId));if(n)return void et(this.cacheKey,{data:s,params:{}});const o=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,i=null!==(r=null==o?void 0:o.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},o),{data:"prev"===t?[...new Set([...s,...i])]:[...new Set([...i,...s])]}))}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(a){if("onArchived"===e){const e=a.data.filter((e=>!t.includes(e)));a.data=[...t,...e]}"onUnarchived"!==e&&"onDelete"!==e||(a.data=a.data.filter((e=>!t.includes(e)))),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Ru extends ki{constructor(e,t){const n=O.default(e),a=["archivedChannel","collection",n];super(new _u(e),n,a,t),this.queryStreamController=new Eu(e,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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=>Tr((t=>e(t.archives.map((e=>e.channelId))))),action:"onArchived"},{fn:e=>kr((t=>e(t.archives.map((e=>e.channelId))))),action:"onUnarchived"},{fn:e=>za((t=>e([t.channelId]))),action:"onUpdate"},{fn:e=>Ya((t=>e([t.channelId]))),action:"onDelete"}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=null!==(r=s.data.map((e=>Ze(["channel","get",e]))).filter((e=>Boolean(e))).map((({data:e})=>e)).map(Pr))&&void 0!==r?r:[];(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class Pu extends wi{async getRequest(e,t){const{query:n,exactMatch:a,isMemberOnly:r,types:s,tags:o,sortBy:i,orderBy:c,limit:l=ue}=e,d=t?{token:t}:{limit:Math.min(100,Math.max(1,l))},{data:u}=await this.http.get("/api/v2/search/channels",{params:{query:n,exactMatch:a,isMemberOnly:r,types:s,tags:o,sortBy:i,orderBy:c,options:d}});return u}}class Mu extends Ci{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){const t=await Pa(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)return void et(this.cacheKey,{data:e.channels.map(We("channel"))});const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,o=null!==(r=null==s?void 0:s.data)&&void 0!==r?r:[],i=e.channels.map(We("channel"));et(this.cacheKey,Object.assign(Object.assign({},s),{data:"prev"===t?[...new Set([...i,...o])]:[...new Set([...o,...i])]}))}reactor(){return()=>this.notifyChange({origin:"event",loading:!1})}subscribeRTE(e){return e.map((e=>e.fn(this.reactor())))}}const ju=()=>ze().getMessagePreviewSetting(!1);class Uu extends ki{constructor(e,t){const n=O.default(e),a=["channel","search",n];super(new Pu(e),n,a,t),this.queryStreamController=new Mu(e,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return this.queryStreamController.subscribeRTE(this.getSubscriptions())}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=null!==(r=s.data.map((e=>Ze(["channel","get",e]))).filter(Boolean).map((e=>Pr(e.data))))&&void 0!==r?r:[];(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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)}shouldAbort(e){var t;const n=null===(t=Ze(this.cacheKey))||void 0===t?void 0:t.data;return!n||!n.data.find((t=>t===e))}getSubscriptions(){return[{fn:Tl((e=>bo((t=>{var n;const a=null===(n=Ze(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Bd(a,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Tl((e=>wo((t=>{var n;const a=null===(n=Ze(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Bd(a,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ya,action:"onDelete"},{fn:za,action:"onUpdate"},{fn:or,action:"onMute"},{fn:e=>Tr((t=>{const n=t.archives.map((e=>{var t;return null===(t=Ze(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onArchived"},{fn:e=>kr((t=>{const n=t.archives.map((e=>{var t;return null===(t=Ze(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onUnarchived"},{fn:Tl(Jo,"entityId","channel"),action:"onUpdate"},{fn:Tl(Ld,"entityId","channel"),action:"onUpdate"},{fn:Tl((e=>bo((async t=>{var n;if("no-message-preview"===await ju())return;if(Oa(t),this.shouldAbort(t.channelId))return;const a=null===(n=Ze(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Bd(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Tl((e=>wo((async t=>{var n;if("no-message-preview"===await ju())return;if(Oa(t),this.shouldAbort(t.channelId))return;const a=null===(n=Ze(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Bd(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Tl((e=>xd((async t=>{"no-message-preview"!==await ju()&&(Ta(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Tl((e=>qd((async t=>{const n=await ju();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await Ta(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&await Bi(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:Tl((e=>Co((async t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(!a)return;a.data.find((e=>{const n=Jn(e);return(null==n?void 0:n.subChannelId)===t.subChannelId}))&&(await Bi(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Tl((e=>Nd((async t=>{var n;if("no-message-preview"===await ju())return;(null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data)&&(await ka(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:e=>Tu((async t=>{if(t.feedMarkers){const n=t.feedMarkers.map((e=>{var t;return null===(t=Ze(["channel","get",e.entityId]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"OnResolveUnread"},{fn:Tl(vu,"channelId","channel"),action:"onUpdate"},{fn:Tl((e=>bu((t=>{t.forEach(e)}))),"channelId","channel"),action:"onUpdate"}]}}class Du extends wi{async getRequest(e,t){const{limit:n=de,includeDeleted:a}=e,r=Kn(e,["limit","includeDeleted"]),s=t?{token:t}:{limit:n},o=!1!==a&&void 0,{data:i}=await this.http.get(`/api/v4/channels/${encodeURIComponent(r.channelId)}/users`,{params:Object.assign(Object.assign({},r),{options:s,isDeleted:o})});return i}}class xu extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.channelUsers.map((({channelId:e,userId:t})=>We("channelUsers")({channelId:e,userId:t})))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channelUsers.map((({channelId:e,userId:t})=>We("channelUsers")({channelId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;if(this.query.channelId!==t.channelId)return;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(!a)return;const r=We("channelUsers")({channelId:this.query.channelId,userId:t.userId}),s=this.query.memberships,o=!s||s.includes(t.membership);"none"!==t.membership&&o?a.data.includes(r)||(a.data=[r,...a.data]):a.data=a.data.filter((e=>e!==r)),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class qu extends ki{constructor(e,t){const n=O.default(e),a=["channelUsers","collection",n];super(new Du(e),n,a,t),this.query=e,this.queryStreamController=new xu(this.query,this.cacheKey,this.notifyChange.bind(this),Pa),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:er,action:"onJoin"},{fn:ar,action:"onLeft"},{fn:lr,action:"onMemberAdded"},{fn:hr,action:"onMemberRemoved"},{fn:mr,action:"onChannelMemberBanned"},{fn:vr,action:"onChannelMemberUnbanned"},{fn:Ir,action:"onChannelMemberRoleAdded"},{fn:Or,action:"onChannelMemberRoleRemoved"},{fn:Er,action:"onChannelSetUserMuted"},{fn:(e=this.query.channelId,t=>{const n=ze();return Mt(n,"user.deleted","user.deleted",(n=>{var a,r;const s=Zr(n);if(0===s.users.length)return;const o=s.users[0];Ln(s);const i=We("channelUsers")({channelId:e,userId:o.userId}),c=null===(a=Ze(["channelUsers","get",i]))||void 0===a?void 0:a.data;nt(["channelUsers","get",i],Object.assign(Object.assign({},c),{user:o}));const l=null===(r=Ze(["channel","get",e]))||void 0===r?void 0:r.data;l&&t(l,c)}))}),action:"onChannelMemberChanged"}]);var e}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["channelUsers","get",e]))).filter(Boolean).map((({data:e})=>e)).map(dl.channelMember))&&void 0!==r?r:[]);(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=ot(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?bt:yt),t}}const Nu=(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`getMembers(tmpid: ${s}) > listen`);const o=new qu(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{at(c)})),()=>{a(`getMembers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}};var Bu=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=ze();n.log("channel/addMembers",e,t);const{data:a}=await n.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users`,{channelId:e,userIds:t});t.forEach((e=>jt("channel.membersAdded",Object.assign(Object.assign({},a),{channelUsers:a.channelUsers.filter((t=>t.userId===e))}))));const r=await Pa(a);n.cache&&Ln(r);const{channelUsers:s}=r;return!!s.find((t=>t.channelId===e&&"member"===t.membership))},removeMembers:async(e,t)=>{const n=ze();n.log("channel/removeMembers",e,t);const{data:a}=await n.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users`,{data:{channelId:e,userIds:t}});t.forEach((e=>jt("channel.membersRemoved",Object.assign(Object.assign({},a),{channelUsers:a.channelUsers.filter((t=>t.userId===e))}))));const r=await Pa(a);n.cache&&Ln(r);const{channelUsers:s}=r;return!!s.find((t=>t.channelId===e&&"member"!==t.membership))},applyFilter:(e,t)=>{let n=ot(e,"roles",t.roles);t.memberships&&(n=n.filter((e=>!(!t.memberships.includes("muted")||!e.isMuted)||t.memberships.includes(e.membership))));const a=t.sortBy?t.sortBy:"lastCreated";return n=n.sort("lastCreated"===a?bt:yt),n},getMembers:Nu,searchMembers:(e,t,n)=>Nu(e,t)});var Lu=Object.freeze({__proto__:null,addRole:async(e,t,n)=>{const a=ze();a.log("channel/addRole",e,t,n);const{data:r}=await a.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{channelId:e,role:t,userIds:n}),s=await Pa(r);a.cache&&Ln(s),jt("local.channel-moderator.role-added",s);const{channelUsers:o}=s;return!!o.find((n=>n.channelId===e&&n.roles.includes(t)))},removeRole:async(e,t,n)=>{const a=ze();a.log("channel/removeRole",e,t,n);const{data:r}=await a.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{data:{channelId:e,role:t,userIds:n}}),s=await Pa(r);a.cache&&Ln(s),jt("local.channel-moderator.role-removed",s);const{channelUsers:o}=s;return!!o.find((n=>n.channelId===e&&!n.roles.includes(t)))},banMembers:async(e,t)=>{const n=ze();n.log("channel/banMembers",{userIds:t,channelId:e});const{data:a}=await n.http.put(`/api/v3/channels/${e}/users/ban`,{userIds:t}),r=await Pa(a),{channelUsers:s}=r,o=n.cache&&Date.now();return n.cache&&Ln(r,{cachedAt:o}),jt("channel.banned",a),{data:null==s?void 0:s.filter((e=>"banned"===e.membership)),cachedAt:o}},unbanMembers:async(e,t)=>{const n=ze();n.log("channel/unbanMembers",{userIds:t,channelId:e});const{data:a}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}/users/unban`,{userIds:t}),r=await Pa(a),s=n.cache&&Date.now();n.cache&&Ln(r,{cachedAt:s}),jt("channel.unbanned",a);const{channelUsers:o}=r;return{data:null==o?void 0:o.filter((e=>"member"===e.membership)),cachedAt:s}},muteMembers:async(e,t,n=-1)=>{var a;const r=ze();r.log("channel/muteMembers",{userIds:t,channelId:e,mutePeriod:n});const{data:s}=await r.http.put(`/api/v2/channel/${e}/users/mute`,{userIds:t,mutePeriod:-1===n?n:1e3*n}),{success:o}=s,i=-1===n?new Date("9999-12-31T23:59:59.999Z").toISOString():new Date(Date.now()+1e3*n).toISOString();return jt("channel.setMutedUsers",{channelId:e,userIds:t,muteTimeout:i,actor:null!==(a=r.userId)&&void 0!==a?a:""}),o},unmuteMembers:async(e,t)=>{var n;const a=ze();a.log("channel/unmuteMembers",{userIds:t,channelId:e});const{data:r}=await a.http.put(`/api/v2/channel/${encodeURIComponent(e)}/users/mute`,{userIds:t,mutePeriod:0}),{success:s}=r;return jt("channel.setMutedUsers",{channelId:e,userIds:t,muteTimeout:new Date(0).toISOString(),actor:null!==(n=a.userId)&&void 0!==n?n:""}),s}}),Fu=Object.freeze({__proto__:null,Membership:Bu,Moderation:Lu,getChannelByIds:Mr,createChannel:Ni,updateChannel:async(e,t)=>{const n=ze();n.log("channel/updateChannel",e,t);const{data:a}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}`,t),r=await Pa(a),s=n.cache&&Date.now();n.cache&&Ln(r,{cachedAt:s});const{channels:o}=r;return{data:qa(o.find((t=>t.channelId===e))),cachedAt:s}},deleteChannel:async e=>{const t=ze();t.log("channel/deleteChannel",e),await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}`);const n=await Bi(e);return qa(n.data)},joinChannel:async e=>{const t=ze();t.log("channel/joinChannel",e);const{data:n}=await t.http.post(`/api/v3/channels/${encodeURIComponent(e)}/join`),a=await Pa(n);t.cache&&Ln(a);const{channelUsers:r}=a;return!!r.find((t=>t.channelId===e&&"member"===t.membership))},leaveChannel:async e=>{const t=ze();t.log("channel/leaveChannel",e);const{data:n}=await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/leave`),a=await Pa(n);t.cache&&Ln(a);const{channelUsers:r}=a;return!!r.find((t=>t.channelId===e&&"member"!==t.membership))},muteChannel:async(e,t=-1)=>{const n=ze();if(n.log("channel/muteChannel",e),-1!==t&&t<0)throw new Le("Mute Period can only be positive numbers or -1(mute forever)",800110,"error");const{data:a}=await n.http.put(`/api/v2/channel/${encodeURIComponent(e)}/mute`,{mutePeriod:t}),{success:r}=a;return r},unmuteChannel:async e=>{const t=ze();t.log("channel/unmuteChannel",e);const{data:n}=await t.http.put(`/api/v2/channel/${encodeURIComponent(e)}/mute`,{mutePeriod:0}),{success:a}=n;return a},archiveChannel:async e=>{const t=ze();t.log("channel/archiveChannel",e),await t.http.post(`/api/v1/archives/channels/${encodeURIComponent(e)}`);const n={channelId:e,archivedAt:(new Date).toISOString()};t.cache&&et(["archivedChannel","get",We("archivedChannel")(n)],n),jt("local.channel.archived",{archives:[n]})},unarchiveChannel:async e=>{var t;const n=ze();n.log("channel/unarchiveChannel",e),await n.http.delete(`/api/v1/archives/channels/${encodeURIComponent(e)}`);const a=null===(t=Ze(["archivedChannel","get",e]))||void 0===t?void 0:t.data,r=null!=a?a:{channelId:e,archivedAt:(new Date).toISOString()};n.cache&&at(["archivedChannel","get",e],!0),jt("local.channel.unarchived",{archives:[r]})},getArchivedChannelIds:Dd,onChannelCreated:$a,onChannelUpdated:za,onChannelDeleted:Ya,onChannelJoined:er,onChannelLeft:ar,onChannelSetMuted:or,onChannelMemberAdded:lr,onChannelMemberRemoved:hr,onChannelMemberBanned:mr,onChannelMemberUnbanned:vr,onChannelMemberRoleAdded:Ir,onChannelMemberRoleRemoved:Or,onChannelArchived:Tr,onChannelUnarchived:kr,getChannel:(e,t)=>{const n=ze();let a;return Ui(e,(async e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:Pr(e.data)}),r=Kn(n,["origin"]);return La(a,r)?void 0:(a=r,t(n))}),"channelId",Bi,[za,Ya,er,ar,lr,hr,mr,vr,or,Tl(Jo,"entityId","channel"),Tl(Ld,"entityId","channel"),Tl((t=>bo((async a=>{await(async a=>{var r;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Oa(a),a.channelId!==e)return;const s=null===(r=Ze(["channel","get",e]))||void 0===r?void 0:r.data;s&&(Bd(s,{messagePreviewId:a.messageId}),t(a))})(a),t(a)}))),"channelId","channel"),Tl((t=>wo((async a=>{var r;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Oa(a),a.channelId!==e)return;const s=null===(r=Ze(["channel","get",e]))||void 0===r?void 0:r.data;s&&(Bd(s,{messagePreviewId:a.messageId}),t(a))}))),"channelId","channel"),Tl((t=>xd((async a=>{var r;const s=null===(r=Ze(["channel","get",e]))||void 0===r?void 0:r.data;if(!s||s.messagePreviewId!==a.messageId)return;"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(await Ta(a),t(a))}))),"channelId","channel"),Tl((t=>qd((async a=>{var r;const s=null===(r=Ze(["channel","get",e]))||void 0===r?void 0:r.data;if(!s||s.messagePreviewId!==a.messageId)return;const o=await n.getMessagePreviewSetting(!1);"no-message-preview"!==o&&("message-preview-not-include-deleted"===o?(at(["messagePreviewChannel","get",e]),await Bi(a.channelId)):await Ta(a),t(a))}))),"channelId","channel"),Tl((e=>Co((async t=>{var a,r;const{channelId:s,subChannelId:o}=t,i=null===(a=Ze(["messagePreviewChannel","get",s]))||void 0===a?void 0:a.data;if(!i||i.subChannelId!==o)return;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;await Bi(s);(null===(r=Ze(["channel","get",s]))||void 0===r?void 0:r.data)&&e(t)}))),"channelId","channel"),Tl((t=>Nd((async a=>{var r,s;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;ka(a);const o=null===(r=Ze(["messagePreviewChannel","get",e]))||void 0===r?void 0:r.data;if(!o||o.subChannelId!==a.subChannelId)return;(null===(s=Ze(["channel","get",e]))||void 0===s?void 0:s.data)&&t(a)}))),"channelId","channel"),Tl(Io,"channelId","channel"),Tl(vu,"channelId","channel"),Tl((e=>bu((t=>{t.forEach(e)}))),"channelId","channel")],{forceDispatch:!0})},getChannels:(e,t,n)=>{const{log:a,cache:r,userId:s}=ze();r||console.log(pe);const o=Date.now();a(`getChannels(tmpid: ${o}) > listen`);const i=new ku(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{at(l)})),()=>{a(`getChannels(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}},getTotalChannelsUnread:e=>{const{_id:t}=kt();if(!t)throw new Le("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:a}=ze();a||console.log("For using Live Object feature you need to enable Cache!");n(`liveTotalChannelsUnread(tmpid: ${Date.now()}) > listen`);const r=[];let s,o=!1;const i=t=>{const{data:n}=t,a=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;s=a?ti(a):a,e({data:a?Object.assign(Object.assign({},a),{isMentioned:a.isMentioned}):a,loading:t.loading,error:t.error})};return r.push(bu((e=>{const{data:t}=Au();La(s,t)||i({loading:!1,data:t})}))),(()=>{const e=xe((async()=>Au()));Ne(e,(({error:e,data:t,loading:n,origin:a,cachedAt:s})=>{s===me?(i({data:t,origin:a,loading:!1,error:new Fe(fe,800800,"error")}),o=!0,r.forEach((e=>e()))):o||i({loading:n,data:t,origin:a,error:e}),e&&r.forEach((e=>e()))}))})(),()=>{r.forEach((e=>e()))}},getArchivedChannels:(e,t)=>{const{log:n,cache:a}=ze();a||console.log(pe);const r=Date.now();n(`getArchivedChannels(tmpid: ${r}) > listen`);const s=new Ru(e,t),o=s.startSubscription(),i=s.getCacheKey();return o.push((()=>{at(i)})),()=>{n(`getArchivedChannels(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},searchChannels:(e,t)=>{const{log:n,cache:a}=ze();a||console.log(pe);const r=Date.now();n(`searchChannels(tmpid: ${r}) > listen`);const s=new Uu(e,t),o=s.startSubscription(),i=s.getCacheKey();return o.push((()=>{at(i)})),()=>{n(`searchChannels(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},MARKER_INCLUDED_CHANNEL_TYPE:Aa,isUnreadCountSupport:_a,convertFromRaw:Ea,preUpdateChannelCache:Ra,prepareChannelPayload:Pa});const Ku=(e,t)=>{0!==e.length&&0!==t.length&&e.forEach((({communityId:e})=>{const n=t.filter((({communityId:t})=>e===t));et(["communityUsers","collection",e],n)}))},$u=async(e,t)=>{const n=ze();n.log("community/getCommunities",e);const a=e.map((e=>encodeURIComponent(e))),{data:r}=await n.http.get("/api/v3/communities/list",{params:{communityIds:a,includeDiscoverablePrivateCommunity:null==t||t}}),s=mc(r),o=n.cache&&Date.now();return n.cache&&(Ln(s,{cachedAt:o}),Ku(s.communities,s.communityUsers)),{data:s.communities.map((e=>dl.community(e))),cachedAt:o}};$u.locally=e=>{const t=ze();if(t.log("community/getCommunities.locally",e),!t.cache)return;const n=e.map((e=>Ze(["community","get",e]))).filter(Boolean),a=n.map((({data:e})=>e)),r=n.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1))[0];return n.length<e.length?void 0:{data:a,cachedAt:r.cachedAt}};const Qu=async e=>{const t=ze();t.log("community/getCommunity",e);const{data:n}=await t.http.get(`/api/v3/communities/${e}`),a=mc(n),r=t.cache&&Date.now();t.cache&&(Ln(a,{cachedAt:r}),Ku(a.communities,a.communityUsers));const{communities:s}=a;return{data:s.find((t=>t.communityId===e)),cachedAt:r}};Qu.locally=e=>{const t=ze();if(t.log("community/getCommunity.locally",e),!t.cache)return;const n=Ze(["community","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Vu=(e,t)=>{const n=ze();return Mt(n,e,e,(e=>{const a=mc(e);if(n.cache){Ln(a);const e=Ze(["community","get",a.communities[0].communityId]);t(e.data)}else t(a.communities[0])}))},zu=e=>Vu("community.created",e),Hu=e=>Vu("community.updated",e),Ju=e=>Vu("community.deleted",e);class Wu extends wi{async getRequest(e,t){var n;const{limit:a=de}=e,r=Kn(e,["limit"]),s=t?{token:t}:{limit:a},{data:o}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},r),{isDeleted:oa(r.includeDeleted),keyword:r.displayName,filter:r.membership,includeDiscoverablePrivateCommunity:null===(n=r.includeDiscoverablePrivateCommunity)||void 0===n||n,options:s})});return o}}class Gu extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.communities.map(We("community"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(We("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Ze(this.cacheKey))||void 0===t?void 0:t.data;n&&(et(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Yu,Xu;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Yu||(Yu={})),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"}(Xu||(Xu={}));class Zu extends wi{async getRequest(e,t){const{limit:n=de,includeDeleted:a,excludingRoles:r}=e,s=Kn(e,["limit","includeDeleted","excludingRoles"]),o=t?{token:t}:{limit:n},i=!1!==a&&void 0,{data:c}=await this.http.get(`/api/v3/communities/${s.communityId}/users`,{params:Object.assign(Object.assign({},s),{options:o,isDeleted:i})});return c}}class eh extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>We("communityUsers")({communityId:e,userId:t})))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>We("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;a&&(t.forEach((e=>{var t;const n=We("communityUsers")({communityId:this.query.communityId,userId:e.userId});if("none"===e.communityMembership)a.data=a.data.filter((e=>e!==n));else if(!a.data.includes(n)){if(null===(t=this.query.excludingRoles)||void 0===t?void 0:t.length){if((e.roles||[]).some((e=>this.query.excludingRoles.includes(e))))return}a.data=[n,...a.data]}})),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}function th(e,t,n){return!!e.permissions.some((e=>e===n))||t.communityUsers.find((t=>t.userId===e.userId)).permissions.some((e=>e===n))}function nh(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=>!th(e,t,"BAN_COMMUNITY_USER"))):t.communityUsers.filter((e=>!th(e,t,"ADD_COMMUNITY_USER")))}const ah=(e,t)=>{const n=ze();return Mt(n,e,e,(a=>{const r=mc(a),{communities:s,communityUsers:o}=r,i=hc(s,o);if(r.communities=i,n.cache){Ln(r,void 0,!1);const n=Ze(["community","get",r.communities[0].communityId]),a=nh(e,r).map((e=>{const t=Ze(["communityUsers","get",We("communityUsers")(e)]);return null==t?void 0:t.data})).filter(Ai);t(n.data,a)}else t(r.communities[0],nh(e,r))}))},rh=(e,t)=>{const n=ze();return Mt(n,e,e,(a=>{const r=mc(a),{communities:s,communityUsers:o}=r,i=hc(s,o);if(r.communities=i,n.cache){Ln(r,void 0,!1);const n=Ze(["community","get",r.communities[0].communityId]),a=nh(e,r).map((e=>{const t=Ze(["communityUsers","get",We("communityUsers")(e)]);return null==t?void 0:t.data})).filter(Ai);t(n.data,a)}else t(r.communities[0],nh(e,r))}))},sh=e=>ah("community.userBanned",e),oh=e=>ah("community.userChanged",e),ih=e=>ah("community.userUnbanned",e),ch=e=>ah("community.roleAdded",e),lh=e=>ah("community.roleRemoved",e),dh=e=>rh("local.community.userAdded",e),uh=e=>rh("local.community.userRemoved",e),hh=e=>ah("community.joined",e),ph=e=>ah("community.left",e),fh=e=>rh("local.community.joined",e),mh=e=>rh("local.community.left",e),gh=e=>{const t=ze(),n=[Mt(t,"onCommunityUpdate","v4.local.community.joined",(async t=>{e(t[0])}))];return()=>{n.forEach((e=>e()))}},yh=e=>{const t=ze();return Mt(t,"onLocalCommunityRoleRemoved","local.community.roleRemoved",(async t=>{const{communities:n,communityUsers:a}=t;e(n[0],a.filter((e=>"member"===e.communityMembership)))}))},vh=e=>{const t=ze();return Mt(t,"onLocalCommunityRoleAdded","local.community.roleAdded",(async t=>{const{communities:n,communityUsers:a}=t;e(n[0],a.filter((e=>"member"===e.communityMembership)))}))},bh=e=>t=>{const n=ze();return Mt(n,"user.deleted","user.deleted",(n=>{var a,r;const s=Zr(n);if(0===s.users.length)return;const o=s.users[0];Ln(s);const i=We("communityUsers")({communityId:e,userId:o.userId}),c=null===(a=Ze(["communityUsers","get",i]))||void 0===a?void 0:a.data;et(["communityUsers","get",i],Object.assign(Object.assign({},c),{user:o}));const l=null===(r=Ze(["community","get",e]))||void 0===r?void 0:r.data;t(l,[Object.assign(Object.assign({},c),{user:o})])}))};class wh extends ki{constructor(e,t){const n=O.default(e),a=["communityUsers","collection",n];super(new Zu(e),n,a,t),this.query=e,this.queryStreamController=new eh(this.query,this.cacheKey,this.notifyChange.bind(this),mc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:hh,action:Xu.OnCommunityJoined},{fn:fh,action:Xu.OnCommunityJoined},{fn:ph,action:Xu.OnCommunityLeft},{fn:mh,action:Xu.OnCommunityLeft},{fn:sh,action:Xu.OnCommunityUserBanned},{fn:oh,action:Xu.OnCommunityUserChanged},{fn:ch,action:Xu.OnCommunityUserRoleAdded},{fn:lh,action:Xu.OnCommunityUserRoleRemoved},{fn:vh,action:Xu.OnCommunityUserRoleAdded},{fn:yh,action:Xu.OnCommunityUserRoleRemoved},{fn:ih,action:Xu.OnCommunityUserUnbanned},{fn:dh,action:Xu.OnCommunityUserAdded},{fn:uh,action:Xu.onCommunityUserRemoved},{fn:bh(this.query.communityId),action:Xu.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["communityUsers","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=ot(e,"roles",this.query.roles);if(this.query.memberships&&(n=n.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),(null===(t=this.query.excludingRoles)||void 0===t?void 0:t.length)&&(n=n.filter((e=>!(e.roles||[]).some((e=>this.query.excludingRoles.includes(e)))))),!1===this.query.includeDeleted&&(n=n.filter((({user:e})=>!0!==(null==e?void 0:e.isDeleted)))),"firstCreated"===this.query.sortBy)n=n.sort(yt);else n=n.sort(bt);return n}}class Ih extends wi{async getRequest(e,t){const{limit:n=de,includeDeleted:a,excludingRoles:r}=e,s=Kn(e,["limit","includeDeleted","excludingRoles"]),o=t?{token:t}:{limit:n},i=!1!==a&&void 0,{data:c}=await this.http.get(`/api/v3/communities/${s.communityId}/users`,{params:Object.assign(Object.assign({},s),{options:o,isDeleted:i})});return c}}class Ch extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>We("communityUsers")({communityId:e,userId:t})))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>We("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;a&&(t.forEach((e=>{const t=We("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership&&(a.data=a.data.filter((e=>e!==t)))})),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Sh;!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"}(Sh||(Sh={}));class Oh extends ki{constructor(e,t){const n=O.default(e),a=["communityUsers","collection",n];super(new Ih(e),n,a,t),this.query=e,this.queryStreamController=new Ch(this.query,this.cacheKey,this.notifyChange.bind(this),mc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:hh,action:Sh.OnCommunityJoined},{fn:fh,action:Sh.OnCommunityJoined},{fn:ph,action:Sh.OnCommunityLeft},{fn:mh,action:Sh.OnCommunityLeft},{fn:sh,action:Sh.OnCommunityUserBanned},{fn:oh,action:Sh.OnCommunityUserChanged},{fn:yh,action:Sh.OnCommunityUserRoleRemoved},{fn:lh,action:Sh.OnCommunityUserRoleRemoved},{fn:ih,action:Sh.OnCommunityUserUnbanned},{fn:bh(this.query.communityId),action:Sh.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["communityUsers","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=ot(e,"roles",this.query.roles);return this.query.memberships&&(n=n.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),this.query.search&&(n=ut(n,this.query.search)),(null===(t=this.query.excludingRoles)||void 0===t?void 0:t.length)&&(n=n.filter((e=>!(e.roles||[]).some((e=>this.query.excludingRoles.includes(e)))))),!1===this.query.includeDeleted&&(n=n.filter((({user:e})=>!0!==(null==e?void 0:e.isDeleted)))),n}}var Th=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=ze();n.log("community/moderation/addMembers",e,t);const{data:a}=await n.http.post(`/api/v3/communities/${e}/users`,{communityId:e,userIds:t});jt("local.community.userAdded",a);const r=Qn(a,"communityUsers");n.cache&&Ln(r);const{communityUsers:s}=r;return!!s.find((t=>t.communityId===e&&"member"===t.communityMembership))},removeMembers:async(e,t)=>{const n=ze();n.log("community/moderation/removeMembers",e,t);const{data:a}=await n.http.delete(`/api/v3/communities/${e}/users`,{data:{communityId:e,userIds:t}});jt("local.community.userRemoved",a);const r=Qn(a,"communityUsers");n.cache&&Ln(r);const{communityUsers:s}=r;return!!s.find((t=>t.communityId===e&&"member"!==t.communityMembership))},applyFilter:(e,t)=>{var n;let a=ot(e,"roles",t.roles);t.memberships&&(a=a.filter((({communityMembership:e})=>t.memberships.includes(e)))),(null===(n=t.excludingRoles)||void 0===n?void 0:n.length)&&(a=a.filter((e=>!(e.roles||[]).some((e=>t.excludingRoles.includes(e))))));const r=t.sortBy?t.sortBy:"lastCreated";return a=a.sort("lastCreated"===r?bt:yt),a},getMembers:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`getMembers(tmpid: ${s}) > listen`);const o=new wh(e,(e=>{t(e)})),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{at(c)})),()=>{a(`getMembers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},searchMembers:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`getMembers(tmpid: ${s}) > listen`);const o=new Oh(e,(e=>{t(e)})),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{at(c)})),()=>{a(`getMembers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},onCommunityUserAdded:e=>ah("community.userAdded",e),onCommunityUserRemoved:e=>ah("community.userRemoved",e),onCommunityUserBanned:sh,onCommunityUserChanged:oh,onCommunityUserUnbanned:ih,onCommunityUserRoleAdded:ch,onCommunityUserRoleRemoved:lh,onLocalCommunityUserAdded:dh,onLocalCommunityUserRemoved:uh,onCommunityJoined:hh,onCommunityLeft:ph,onLocalCommunityJoined:fh,onLocalCommunityLeft:mh,onLocalCommunityJoin:gh});class kh extends ki{constructor(e,t){const n=O.default(e),a=["community","collection",n];super(new Wu(e),n,a,t),this.query=e,this.queryStreamController=new Gu(this.query,this.cacheKey,this.notifyChange.bind(this),mc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:Ju,action:Yu.OnCommunityDeleted},{fn:Hu,action:Yu.OnCommunityUpdated},{fn:hh,action:Xu.OnCommunityJoined},{fn:ph,action:Xu.OnCommunityLeft},{fn:oh,action:Xu.OnMemberCountChanged},{fn:fh,action:Xu.OnCommunityJoined},{fn:mh,action:Xu.OnCommunityLeft},{fn:Tl(gh,"targetId","community"),action:Yu.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["community","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=ze();let n=e;return this.query.includeDeleted||(n=rt(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=lt(n,this.query.membership,t)),n}}class Ah extends wi{async getRequest(e,t){var n;const{limit:a=de}=e,r=Kn(e,["limit"]),s=t?{token:t}:{limit:a},{data:o}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},r),{isDeleted:oa(r.includeDeleted),filter:r.membership,includeDiscoverablePrivateCommunity:null===(n=r.includeDiscoverablePrivateCommunity)||void 0===n||n,options:s})});return o}}class _h extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&(Ln(t,{cachedAt:a}),Ku(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.communities.map(We("community"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(We("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Ze(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],et(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Eh;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Eh||(Eh={}));class Rh extends ki{constructor(e,t){const n=O.default(e),a=["community","collection",n];super(new Ah(e),n,a,t),this.query=e,this.queryStreamController=new _h(this.query,this.cacheKey,this.notifyChange.bind(this),mc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:zu,action:Eh.OnCommunityCreated},{fn:Ju,action:Eh.OnCommunityDeleted},{fn:Hu,action:Eh.OnCommunityUpdated},{fn:hh,action:Xu.OnCommunityJoined},{fn:ph,action:Xu.OnCommunityLeft},{fn:oh,action:Xu.OnMemberCountChanged},{fn:fh,action:Xu.OnCommunityJoined},{fn:mh,action:Xu.OnCommunityLeft},{fn:Tl(gh,"targetId","community"),action:Eh.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=null!==(r=s.data.map((e=>Ze(["community","get",e]))).filter(Ai).map((({data:e})=>Dc(e))))&&void 0!==r?r:[];(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=ze();let n=e;this.query.includeDeleted||(n=rt(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=lt(n,this.query.membership,t));const a=(()=>"firstCreated"===this.query.sortBy?yt:bt)();return n=n.sort(a),n}}class Ph extends wi{async getRequest(e,t){const{limit:n=de,includeDiscoverablePrivateCommunity:a}=e,r=Kn(e,["limit","includeDiscoverablePrivateCommunity"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v3/communities/top-trending",{params:Object.assign(Object.assign({},r),{options:s,includeDiscoverablePrivateCommunity:null==a||a})});return o}}class Mh extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&(Ln(t,{cachedAt:a}),Ku(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.communities.map(We("community"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(We("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Ze(this.cacheKey))||void 0===t?void 0:t.data;n&&(et(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var jh;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(jh||(jh={}));class Uh extends ki{constructor(e,t){const n=O.default(e),a=["trendingCommunity","collection",n];super(new Ph(e),n,a,t),this.query=e,this.queryStreamController=new Mh(this.query,this.cacheKey,this.notifyChange.bind(this),mc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:Ju,action:jh.OnCommunityDeleted},{fn:Hu,action:jh.OnCommunityUpdated},{fn:hh,action:Xu.OnCommunityJoined},{fn:ph,action:Xu.OnCommunityLeft},{fn:oh,action:Xu.OnMemberCountChanged},{fn:fh,action:Xu.OnCommunityJoined},{fn:mh,action:Xu.OnCommunityLeft},{fn:Tl(gh,"targetId","community"),action:jh.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=null!==(r=s.data.map((e=>Ze(["community","get",e]))).filter(Ai).map((({data:e})=>Dc(e))))&&void 0!==r?r:[];(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class Dh extends wi{async getRequest(e,t){const{limit:n=de,includeDiscoverablePrivateCommunity:a}=e,r=Kn(e,["limit","includeDiscoverablePrivateCommunity"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v3/communities/recommended",{params:Object.assign(Object.assign({},r),{options:s,includeDiscoverablePrivateCommunity:null==a||a})});return o}}class xh extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&(Ln(t,{cachedAt:a}),Ku(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.communities.map(We("community"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(We("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Ze(this.cacheKey))||void 0===t?void 0:t.data;n&&(et(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var qh;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated",e.OnLocalCommunityJoin="onLocalCommunityJoin"}(qh||(qh={}));class Nh extends ki{constructor(e,t){const n=O.default(e),a=["community","collection",n];super(new Dh(e),n,a,t),this.query=e,this.queryStreamController=new xh(this.query,this.cacheKey,this.notifyChange.bind(this),mc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:Ju,action:qh.OnCommunityDeleted},{fn:Hu,action:qh.OnCommunityUpdated},{fn:hh,action:Xu.OnCommunityJoined},{fn:ph,action:Xu.OnCommunityLeft},{fn:oh,action:Xu.OnMemberCountChanged},{fn:fh,action:Xu.OnCommunityJoined},{fn:mh,action:Xu.OnCommunityLeft},{fn:Tl(gh,"targetId","community"),action:qh.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=null!==(r=s.data.map((e=>Ze(["community","get",e]))).filter(Ai).map((({data:e})=>Dc(e))))&&void 0!==r?r:[];(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class Bh extends wi{async getRequest(e,t){var n;const{limit:a=de,communityMembershipStatus:r}=e,s=Kn(e,["limit","communityMembershipStatus"]),o={type:e.limit?"pagination":void 0},i=t?Object.assign(Object.assign({},o),{token:t}):Object.assign(Object.assign({},o),{limit:a}),{data:c}=await this.http.get("/api/v1/semantic-search/communities",{params:Object.assign(Object.assign({},s),{filter:null!=r?r:"all",options:i,includeDiscoverablePrivateCommunity:null===(n=s.includeDiscoverablePrivateCommunity)||void 0===n||n})});return c}}function Lh(e){return e.communities.map((t=>{const n=e.searchResult.find((e=>e.communityId===t.communityId));return`${t.communityId}:${n}`}))}class Fh extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:Lh(e)});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...Lh(e)])]}))}}reactor(e){return e=>{var t;const n=null===(t=Ze(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],et(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Kh;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Kh||(Kh={}));class $h extends ki{constructor(e,t){const n=O.default(e),a=["community","collection",n];super(new Bh(e),n,a,t),this.query=e,this.queryStreamController=new Fh(this.query,this.cacheKey,this.notifyChange.bind(this),bc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:zu,action:Kh.OnCommunityCreated},{fn:Ju,action:Kh.OnCommunityDeleted},{fn:Hu,action:Kh.OnCommunityUpdated},{fn:hh,action:Xu.OnCommunityJoined},{fn:ph,action:Xu.OnCommunityLeft},{fn:oh,action:Xu.OnMemberCountChanged},{fn:fh,action:Xu.OnCommunityJoined},{fn:mh,action:Xu.OnCommunityLeft},{fn:Tl(gh,"targetId","community"),action:Kh.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>{const[t,n]=e.split(":");return{communityId:t,score:parseFloat(n)}})).sort(((e,t)=>t.score-e.score)).map((({communityId:e})=>Ze(["community","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=ze();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=lt(n,this.query.communityMembershipStatus,t)),n}}class Qh extends wi{async getRequest(e,t){const{limit:n=de,communityIds:a}=e,r=Kn(e,["limit","communityIds"]),s=t?{token:t}:{limit:n},o=a.map((e=>encodeURIComponent(e))),{data:i}=await this.http.get("/api/v4/communities/join/requests",{params:Object.assign(Object.assign({},r),{options:s,communityIds:o})});return i}}var Vh;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(Vh||(Vh={}));class zh extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.joinRequests.map((e=>We("joinRequest")({joinRequestId:e._id})))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>We("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(!a)return;const r=(Array.isArray(t)?t:[t]).map((e=>e.joinRequestId));if(e===Vh.OnLocalJoinRequestUpdated){if(!a.data.find((e=>r.includes(e))))return}e===Vh.OnLocalJoinRequestCreated&&(a.data=[...new Set([...r,...a.data])]),e===Vh.OnLocalJoinRequestDeleted&&(a.data=a.data.filter((e=>!r.includes(e)))),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Hh extends ki{constructor(e,t){const n=O.default(e),a=["joinRequestList","collection",n];super(new Qh(e),n,a,t),this.query=e,this.queryStreamController=new zh(this.query,this.cacheKey,this.notifyChange.bind(this),gc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){const a=e;this.queryStreamController.appendToQueryStream(a,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Oc,action:Vh.OnLocalJoinRequestCreated},{fn:Tc,action:Vh.OnLocalJoinRequestUpdated},{fn:kc,action:Vh.OnLocalJoinRequestUpdated},{fn:gh,action:Vh.OnLocalJoinRequestUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a;const r=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!r)return;const s=this.applyFilter(r.data.map((e=>Ze(["joinRequest","get",e]))).filter(Ai).map((({data:e})=>e)).map(wc));(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.communityIds&&this.query.communityIds.length>0&&(t=t.filter((e=>this.query.communityIds.some((t=>t===e.targetId)))));const n=(()=>"firstCreated"===this.query.sortBy?yt:bt)();return t=t.sort(n),t}}var Jh;!function(e){e.ALL="all",e.MEMBER="member",e.NOT_MEMBER="notMember"}(Jh||(Jh={}));var Wh=Object.freeze({__proto__:null,addRoles:async(e,t,n)=>{const a=ze();a.log("community/moderation/addRoles",e,t,n);const{data:r}=await a.http.post(`/api/v4/communities/${e}/users/roles`,{communityId:e,roles:t,userIds:n}),s=yc(r);a.cache&&Ln(s),jt("local.community.roleAdded",s);const{communityUsers:o}=s;return!!o.find((n=>n.communityId===e&&t.some((e=>n.roles.includes(e)))))},removeRoles:async(e,t,n)=>{const a=ze();a.log("community/moderation/removeRoles",e,t,n);const{data:r}=await a.http.delete(`/api/v4/communities/${e}/users/roles`,{data:{communityId:e,roles:t,userIds:n}}),s=yc(r);a.cache&&Ln(s),jt("local.community.roleRemoved",s);const{communityUsers:o}=s;return!!o.find((n=>n.communityId===e&&!t.some((e=>n.roles.includes(e)))))},banMembers:async(e,t)=>{const n=ze();n.log("community/banMembers",{userIds:t,communityId:e});const{data:a}=await n.http.put(`/api/v3/communities/${e}/users/ban`,{userIds:t}),r=Qn(a,"communityUsers"),s=n.cache&&Date.now();n.cache&&Ln(r,{cachedAt:s});const{communityUsers:o}=r;return{data:o.filter((e=>t.includes(e.userId))),cachedAt:s}},unbanMembers:async(e,t)=>{const n=ze();n.log("community/unbanMembers",{userIds:t,communityId:e});const{data:a}=await n.http.put(`/api/v3/communities/${e}/users/unban`,{userIds:t}),r=Qn(a,"communityUsers"),s=n.cache&&Date.now();n.cache&&Ln(r,{cachedAt:s});const{communityUsers:o}=r;return{data:o.filter((e=>t.includes(e.userId))),cachedAt:s}}}),Gh=Object.freeze({__proto__:null,Moderation:Wh,Membership:Th,getCommunityByIds:$u,createCommunity:async e=>{const t=ze();t.log("user/createCommunity",e);const{data:n}=await t.http.post("/api/v3/communities/",vc(e));jt("community.created",n);const a=mc(n),r=t.cache&&Date.now();t.cache&&(Ln(a,{cachedAt:r}),Ku(a.communities,a.communityUsers));const{communities:s}=a;return{data:dl.community(s[0]),cachedAt:r}},updateCommunity:async(e,t)=>{const n=ze();n.log("community/updateCommunity",e,t);const{data:a}=await n.http.put(`/api/v3/communities/${e}`,vc(t));jt("community.updated",a);const r=mc(a),s=n.cache&&Date.now();n.cache&&(Ln(r,{cachedAt:s}),Ku(r.communities,r.communityUsers));const{communities:o}=r;return{data:dl.community(o.find((t=>t.communityId===e))),cachedAt:s}},deleteCommunity:async e=>{const t=ze();t.log("community/deleteCommunity",e),await t.http.delete(`/api/v3/communities/${e}`);const n=await Qu(e);return jt("community.deleted",{communities:[n.data],categories:[],communityUsers:[],feeds:[],files:[],users:[]}),dl.community(n.data)},joinCommunity:async e=>{const t=ze();t.log("community/joinCommunity",e);const{data:n}=await t.http.post(`/api/v3/communities/${e}/join`);jt("local.community.joined",n);const a=mc(n),r=t.cache&&Date.now();t.cache&&Ln(a,{cachedAt:r});const{communityUsers:s}=a;return!!s.find((t=>t.communityId===e&&"member"===t.communityMembership))},leaveCommunity:async e=>{const t=ze();t.log("community/leaveCommunity",e);const{data:n}=await t.http.delete(`/api/v3/communities/${e}/leave`);jt("local.community.left",n);const a=mc(n),r=t.cache&&Date.now();t.cache&&Ln(a,{cachedAt:r});const{communityUsers:s}=a;return!!s.find((t=>t.communityId===e&&"member"!==t.communityMembership))},onCommunityCreated:zu,onCommunityUpdated:Hu,onCommunityDeleted:Ju,searchCommunities:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`searchCommunities(tmpid: ${s}) > listen`);const o=new kh(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`searchCommunities(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getCommunities:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`getCommunities(tmpid: ${s}) > listen`);const o=new Rh(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getCommunities(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getCommunity:(e,t)=>Ui(e,t,"communityId",Qu,[Hu,Ju,hh,ph,fh,mh,sh,ih,oh,Tl(gh,"targetId","community")],{callbackDataSelector:e=>e?dl.community(e):e}),getTrendingCommunities:(e,t,n)=>{const{log:a,cache:r,userId:s}=ze();r||console.log(pe);const o=Date.now();a(`getTrendingCommunities(tmpid: ${o}) > listen`);const i=new Uh(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>at(l))),()=>{a(`getTrendingCommunities(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}},getRecommendedCommunities:(e,t,n)=>{const{log:a,cache:r,userId:s}=ze();r||console.log(pe);const o=Date.now();a(`getRecommendedCommunities(tmpid: ${o}) > listen`);const i=new Nh(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>at(l))),()=>{a(`getRecommendedCommunities(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}},semanticSearchCommunities:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`semanticSearchCommunities(tmpid: ${s}) > listen`);const o=new $h(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`semanticSearchCommunities(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getJoinRequestList:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`getJoinRequestList: (tmpid: ${s}) > listen`);const o=new Hh(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{at(c)})),()=>{a(`getJoinRequestList (tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},get AmityCommunityMemberStatusFilter(){return Jh}});const Yh=async e=>{const t=ze();t.log("category/getCategory",e);const{data:n}=await t.http.get(`/api/v3/community-categories/${encodeURIComponent(e)}`),a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a});const{categories:r}=n;return{data:dl.category((null!=r?r:[]).find((t=>t.categoryId===e))),cachedAt:a}};Yh.locally=e=>{const t=ze();if(t.log("category/getCategory.locally",e),!t.cache)return;const n=Ze(["category","get",e]);return n?{data:dl.category(n.data),cachedAt:n.cachedAt}:void 0};const Xh=async e=>{const t=ze();t.log("category/queryCategories",e);const n=null!=e?e:{},{page:a,limit:r,includeDeleted:s}=n,o=Kn(n,["page","limit","includeDeleted"]),i=a?{token:a}:r?{limit:r}:void 0,{data:c}=await t.http.get("/api/v3/community-categories",{params:Object.assign(Object.assign({},o),{isDeleted:oa(s),options:i})}),{paging:l}=c,d=Kn(c,["paging"]),{categories:u}=d,h=t.cache&&Date.now();if(t.cache){Ln(d,{cachedAt:h});const e=["category","query",Object.assign(Object.assign({},o),{includeDeleted:s,options:i})];et(e,{categories:null==u?void 0:u.map(We("category")),paging:l})}return{data:null!=u?u:[],cachedAt:h,paging:l}};Xh.locally=e=>{var t,n;const a=ze();if(a.log("category/queryCategories.locally",e),!a.cache)return;const r=null!=e?e:{},{page:s,limit:o=10}=r,i=Kn(r,["page","limit"]),c=s?{token:s}:o?{limit:o}:void 0,l=["category","query",Object.assign(Object.assign({},i),{options:c})],{data:d,cachedAt:u}=null!==(t=Ze(l))&&void 0!==t?t:{};if(!(null==d?void 0:d.categories.length))return;const h=d.categories.map((e=>Ze(["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 Zh=Object.freeze({__proto__:null,getCategory:Yh,getCategories:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`getCategories(tmpid: ${s}) > listen`);const{limit:o}=e,i=Kn(e,["limit"]),c=null!=o?o:de,{policy:l=he}=null!=n?n:{},d=[],u=["category","collection",{}],h=(n=!1)=>{var a,r;const s=null===(a=Ze(u))||void 0===a?void 0:a.data,o=null!==(r=null==s?void 0:s.data)&&void 0!==r?r:[];if(!n&&o.length>0&&!(null==s?void 0:s.params.page))return;const d=xe(Xh,Object.assign(Object.assign({},i),{limit:n?c:void 0,page:n||null==s?void 0:s.params.page}));Ne(d,(({data:n,error:a,loading:r,paging:s})=>{const i={loading:r,error:a,params:{page:null==s?void 0:s.next},data:o};n&&(i.data=[...new Set([...o,...n.map(We("category"))])]),et(u,i),(n=>{var a,r;let s=null!==(a=n.data.map((e=>Ze(["category","get",e]))).filter(Boolean).map((({data:e})=>dl.category(e))))&&void 0!==a?a:[];switch(e.includeDeleted||(s=rt(s,"isDeleted",!1)),e.sortBy){case"firstCreated":s=s.sort(yt);break;case"lastCreated":s=s.sort(bt);break;default:s=s.sort(gt)}t({onNextPage:h,data:s,hasNextPage:!!(null===(r=n.params)||void 0===r?void 0:r.page),loading:n.loading,error:n.error})})(i)}),qe(l))};return d.push((()=>{})),h(!0),()=>{a(`getCategories(tmpid: ${s}) > dispose`),d.forEach((e=>e()))}}});const ep=async e=>{const t=ze();t.log("feed/queryGlobalFeed",e);const n=null!=e?e:{},{queryToken:a,dataTypes:r}=n,s=Kn(n,["queryToken","dataTypes"]),o=(()=>{if(a)return{token:a}})(),{data:i}=await t.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},s),{dataTypes:r,resolveParent:!!(r&&r.length>0)||void 0,options:o})}),{paging:c}=i,l=Kn(i,["paging"]),d=Qn(l,"communityUsers"),{posts:u}=d,{communities:h}=mc(d),p=t.cache&&Date.now();if(t.cache){Ln(Object.assign(Object.assign({},d),{communitis:h}));const e=["globalFeed","query",Object.assign(Object.assign({},s),{options:o})];et(e,{posts:u.map(We("post")),paging:c})}return{data:u.map(dl.post),cachedAt:p,paging:c}};ep.locally=e=>{var t;const n=ze();if(n.log("post/queryGlobalFeed.locally",e),!n.cache)return;const a=Kn(null!=e?e:{},[]),r=["globalFeed","query",Object.assign({},a)],{data:s,cachedAt:o}=null!==(t=Ze(r))&&void 0!==t?t:{};if(!(null==s?void 0:s.posts.length))return;const i=s.posts.map((e=>Ze(["post","get",e]))).filter(Boolean).map((({data:e})=>e)).map(dl.post),{paging:c}=s;return i.length===s.posts.length?{data:i,cachedAt:o,paging:c}:void 0};class tp extends wi{async getRequest(e,t){const{limit:n}=e,a=Kn(e,["limit"]),r=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v5/me/global-feeds",{params:Object.assign(Object.assign({},a),{options:r})});return s}}var np;!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",e.OnPostPinProduct="onPostPinProduct",e.OnPostUnpinProduct="onPostUnpinProduct",e.OnPostUpdateProductTags="onPostUpdateProductTags"}(np||(np={}));class ap extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.posts.map(We("post"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(We("post"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(a&&(!t.parentPostId||a.data.includes(t.parentPostId))){if(e===np.OnPostDeleted&&(a.data=a.data.filter((e=>e!==t.postId))),e===np.OnPostCreated||e===np.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])]}e===np.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const rp=async e=>{const t=ze();t.log("comment/getCommentByIds",e);const n=e.map((e=>encodeURIComponent(e)));let a;try{a=(await t.http.get("/api/v3/comments/list",{params:{commentIds:n}})).data}catch(t){throw e.forEach((e=>{Oe(null==t?void 0:t.code)&&Fn("comment",e)})),t}const r=t.cache&&Date.now();return t.cache&&Ln(a,{cachedAt:r}),{data:a.comments.map((e=>dl.comment(e))),cachedAt:r}};rp.locally=e=>{var t;const n=ze();if(n.log("comment/getCommentByIds.locally",e),!n.cache)return;const a=e.map((e=>Ze(["comment","get",e]))).filter(Boolean),r=a.map((({data:e})=>e)),s=null===(t=a.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==a?void 0:a.length)<e.length?void 0:{data:r.map((e=>dl.comment(e))),cachedAt:s.cachedAt}};const sp=e=>{const t=ze();if(!t.cache)return;const n=Mn();t.log("comment/createComment.optimistically",Object.assign({commentId:n},e));const a=(new Date).toISOString(),r={commentId:n,userId:t.userId,parentId:e.parentId,rootId:e.parentId||n,childrenNumber:0,children:[],segmentNumber:0,editedAt:a,referenceId:e.referenceId,referenceType:e.referenceType,data:e.data,metadata:e.metadata,mentionees:e.mentionees,attachments:e.attachments,links:e.links,createdAt:a,updatedAt:a,isDeleted:!1,flagCount:0,hashFlag:null,reactions:{},reactionsCount:0,myReactions:[],path:"",targetId:"",targetType:"community",dataType:"text",syncState:"syncing"};return et(["comment","get",r.commentId],r,{cachedAt:-5}),jt("local.comment.created",{comments:[r],commentChildren:[],users:[],files:[],communityUsers:[]}),r},op=(e,t=!1)=>{const{stories:n}=e,a=n.map((e=>((e,t=!1)=>{const{storyId:n,referenceId:a}=e;return!t&&a?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:a})},ip=async e=>{const t=ze();t.log("story/getStoryByStoryId",e);const n=Ze(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;ta("story",e)}let a;try{const n=await t.http.get(`/api/v4/stories/${e}`);a=op(n.data)}catch(t){throw Oe(null==t?void 0:t.code)&&Fn("story",e),t}const r=t.cache&&Date.now();return t.cache&&Ln(a,{cachedAt:r}),{data:a.stories[0],cachedAt:r}};ip.locally=e=>{const t=ze();t.log("story/getStorybyStoryId",e);const n=Ze(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;ta("story",e)}const a=t.cache&&Date.now(),r=Ze(["story","get",e]);if(r)return{data:r.data,cachedAt:a}};const cp=async(e,t=!1)=>{var n,a,r;const s=ze(),o=null===(n=Ze(["comment","get",e]))||void 0===n?void 0:n.data;if("error"===(null==o?void 0:o.syncState)){const t=Object.assign(Object.assign({},o),{isDeleted:!0});return at(["comment","get",e]),jt("local.comment.deleted",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]}),t}const i=await Zl(e);await s.http.delete(`/api/v4/comments/${encodeURIComponent(e)}`,{params:{commentId:e,permanent:t}});const c=Object.assign(Object.assign({},i.data),{isDeleted:!0});if(t?Rt((()=>Fn("comment",e))):nt(["comment","get",e],{isDeleted:!0}),"story"===i.data.referenceType){const e=await ip(i.data.referenceId);jt("local.story.updated",{stories:[e.data],categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[]})}else{const t=null===(a=Ze(["post","get",i.data.referenceId]))||void 0===a?void 0:a.data;if(t){const n=Wl();n.queueCommentChangeTask(new Vl(t.postId,e)),!c.parentId&&(null===(r=c.children)||void 0===r?void 0:r.length)>0&&c.children.forEach((e=>{n.queueCommentChangeTask(new Vl(t.postId,e))}))}}return jt("local.comment.deleted",{comments:[c],commentChildren:[],files:[],users:[],communityUsers:[]}),c},lp=async e=>{const t=ze();let n;t.log("comment/getComment",e),ta("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw Oe(null==t?void 0:t.code)&&Fn("comment",e),t}const a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a});const{comments:r}=n;return{data:r.find((t=>t.commentId===e)),cachedAt:a}};lp.locally=e=>{const t=ze();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=Ze(["comment","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const dp=e=>wd("local.comment.deleted",e),up=e=>{const t=ze();return Mt(t,"local.comment.addReaction","local.comment.addReaction",(({comment:n})=>{t.cache?(nt(["comment","get",n.commentId],n),e($i(n))):e(n)}))},hp=e=>{const t=ze();return Mt(t,"local.comment.removeReaction","local.comment.removeReaction",(({comment:n})=>{t.cache?(nt(["comment","get",n.commentId],n),e($i(n))):e(n)}))};class pp extends wi{async getRequest(e,t){var n;const{pageSize:a,limit:r,includeDeleted:s}=e,o=Kn(e,["pageSize","limit","includeDeleted"]),i=null!==(n=null!=a?a:r)&&void 0!==n?n:de,c={type:o.sortBy||e.limit||e.pageSize?"pagination":void 0},l=t?Object.assign(Object.assign({},c),{token:t}):Object.assign(Object.assign({},c),{pageSize:i,limit:i}),{data:d}=await this.http.get("/api/v3/comments",{params:Object.assign(Object.assign({},o),{isDeleted:oa(s),options:l})});return d}}var fp;!function(e){e.OnCommentCreated="onCommentCreated",e.OnCommentUpdated="onCommentUpdated",e.OnCommentDeleted="onCommentDeleted",e.OnCommentFlagged="onCommentFlagged",e.OnCommentUnflagged="onCommentUnflagged",e.OnCommentReactionAdded="onCommentReactionAdded",e.OnCommentReactionRemoved="onCommentReactionRemoved"}(fp||(fp={}));class mp extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.comments.map(We("comment"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.comments.map(We("comment"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;this.query.referenceId===t.referenceId&&this.query.referenceType===t.referenceType&&a&&(this.query.parentId&&this.query.parentId!==t.parentId||!this.query.parentId&&t.parentId||(e===fp.OnCommentCreated&&(a.data=[...new Set([t.commentId,...a.data])]),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const gp=e=>wd("local.comment.created",e);class yp extends ki{constructor(e,t){const n=O.default(e),a=["comments","collection",n];super(new pp(e),n,a,t),this.query=e,this.queryStreamController=new mp(this.query,this.cacheKey,this.notifyChange.bind(this),Ud),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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(){const e=this.queryStreamController.subscribeRTE([{fn:gp,action:fp.OnCommentCreated},{fn:dp,action:fp.OnCommentDeleted},{fn:Id,action:fp.OnCommentCreated},{fn:Cd,action:fp.OnCommentUpdated},{fn:Sd,action:fp.OnCommentDeleted},{fn:Od,action:fp.OnCommentFlagged},{fn:Td,action:fp.OnCommentUnflagged},{fn:kd,action:fp.OnCommentReactionAdded},{fn:Ad,action:fp.OnCommentReactionRemoved},{fn:up,action:fp.OnCommentReactionAdded},{fn:hp,action:fp.OnCommentReactionRemoved}]);if(this.query.excludeBlockUserComments){const t=()=>this.notifyChange({origin:"event",loading:!1});e.push(Js(t),Ws(t))}return e}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["comment","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.comment);(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;if(this.query.includeDeleted||(t=rt(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 a=(null===(t=this.query.dataTypes)||void 0===t?void 0:t.values.sort())||[],r=(null===(n=e.dataTypes)||void 0===n?void 0:n.sort())||[];return r.length===a.length&&a.every(((e,t)=>e===r[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)}))})))),this.query.excludeBlockUserComments&&(t=ft(t)),"firstCreated"===this.query.sortBy)t=t.sort(yt);else t=t.sort(bt);return t}}var vp=Object.freeze({__proto__:null,getCommentByIds:rp,createComment:async e=>{const t=ze();t.log("comment/createComment",e);const n=sp(e),a=null==n?void 0:n.commentId;try{const{data:n}=await t.http.post("/api/v3/comments",Object.assign(Object.assign({},e),{commentId:a})),{comments:r}=n;if(0===r.length)throw new Error("Comment not created");const s=t.cache&&Date.now();if(t.cache&&Ln(n,{cachedAt:s}),["post","content"].includes(e.referenceType))Wl().queueCommentChangeTask(new Ql(e.referenceId,r[0].commentId,n.comments[0].createdAt));else if("story"===e.referenceType){const t=Ze(["story-reference",e.referenceId]);if(null==t?void 0:t.data){const e=Ze(["story","get",t.data]);(null==e?void 0:e.data)&&jt("story.updated",{stories:[Object.assign(Object.assign({},e.data),{commentsCount:e.data.commentsCount+1,comments:[...new Set([...e.data.comments,r[0].commentId])]})],categories:[],comments:r,communities:[],communityUsers:n.communityUsers,files:n.files,users:n.users})}}return jt("local.comment.created",{comments:[Object.assign(Object.assign({},r[0]),{syncState:"synced"})],commentChildren:n.commentChildren,users:n.users,files:n.files,communityUsers:n.communityUsers}),{data:dl.comment(r[0]),cachedAt:s}}catch(e){throw n&&jt("local.comment.created",{comments:[Object.assign(Object.assign({},n),{syncState:"error"})],commentChildren:[],users:[],files:[],communityUsers:[]}),e}},updateComment:async(e,t)=>{const n=ze();n.log("user/updateComment",t);const{data:a}=await n.http.put(`/api/v3/comments/${encodeURIComponent(e)}`,t),r=n.cache&&Date.now();n.cache&&Ln(a,{cachedAt:r}),jt("comment.updated",a);const{comments:s}=a;return{data:dl.comment(s.find((t=>t.commentId===e))),cachedAt:r}},deleteComment:cp,softDeleteComment:async e=>{ze().log("comment/softDeleteComment",e);return cp(e)},hardDeleteComment:async e=>{ze().log("comment/hardDeleteComment",e);return cp(e,!0)},flagComment:async(t,n)=>{const a=ze();a.log("comment/flagComment",t);const r=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,a])=>t!==e.ContentFlagReasonEnum.Others&&a===n)),s={reason:n&&r?n:e.ContentFlagReasonEnum.Others,detail:n&&!r?n:""},{data:o}=await a.http.post(`/api/v3/comments/${encodeURIComponent(t)}/flag`,s);return a.cache&&Ln(o),jt("comment.flagged",o),!!o},unflagComment:async e=>{const t=ze();t.log("comment/unflagComment",e);const{data:n}=await t.http.delete(`/api/v3/comments/${encodeURIComponent(e)}/unflag`);return t.cache&&Ln(n),jt("comment.unflagged",n),!!n},isCommentFlaggedByMe:async e=>{const t=ze();t.log("comment/isCommentFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/comments/${e}/isflagbyme`);return n},onCommentCreated:Id,onCommentUpdated:Cd,onCommentDeleted:Sd,onCommentFlagged:Od,onCommentUnflagged:Td,onCommentReactionAdded:kd,onCommentReactionRemoved:Ad,getComment:(e,t)=>Ui(e,t,"commentId",lp,[dp,Sd,Od,kd,Ad,Td,Cd,up,hp]),getComments:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log("For using Live Collection feature you need to enable Cache!");const s=Date.now();a(`getComments(tmpid: ${s}) > listen`);const o=new yp(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getComments(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}}});const bp=e=>ld("local.post.deleted",e),wp=e=>{const t=ze();return Mt(t,"local.post.addReaction","local.post.addReaction",(({post:n})=>{t.cache?(nt(["post","get",n.postId],n),e(n)):e(n)}))},Ip=e=>{const t=ze();return Mt(t,"local.post.removeReaction","local.post.removeReaction",(({post:n})=>{t.cache?(nt(["post","get",n.postId],n),e(n)):e(n)}))},Cp=e=>ld("local.post.updated",e),Sp=e=>[Id,Sd,gp,dp].map((t=>({fn:Tl((n=>((e,t,n)=>t((async t=>{var a;const r=null===(a=Ze(n))||void 0===a?void 0:a.data;r&&r.data.includes(t.referenceId)&&e(t)})))(n,t,e)),"referenceId","post"),action:np.OnPostUpdated}))),Op=e=>[{fn:dd,action:np.OnPostCreated},{fn:ud,action:np.OnPostUpdated},{fn:Cp,action:np.OnPostUpdated},{fn:hd,action:np.OnPostDeleted},{fn:md,action:np.OnPostFlagged},{fn:gd,action:np.OnPostUnflagged},{fn:pd,action:np.OnPostApproved},{fn:fd,action:np.OnPostDeclined},{fn:yd,action:np.OnPostReactionAdded},{fn:vd,action:np.OnPostReactionRemoved},{fn:wp,action:np.OnPostReactionAdded},{fn:Ip,action:np.OnPostReactionRemoved},{fn:bp,action:np.OnPostDeleted},...Sp(e)];class Tp extends ki{constructor(e,t){const n=O.default(e),a=["customRankingGlobalFeed","collection",n];super(new tp(e),n,a,t),this.query=e,this.queryStreamController=new ap(this.query,this.cacheKey,this.notifyChange.bind(this),Gl),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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(Op(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=(null!==(r=s.data.map((e=>Ze(["post","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.post);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class kp extends wi{async getRequest(e,t){const{limit:n,dataTypes:a}=e,r=Kn(e,["limit","dataTypes"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},r),{dataTypes:a,resolveParent:!!(a&&a.length>0)||void 0,options:s})});return o}}class Ap extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.posts.map(We("post"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(We("post"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(a&&(!t.parentPostId||a.data.includes(t.parentPostId))){if(e===np.OnPostDeleted&&(a.data=a.data.filter((e=>e!==t.postId))),e===np.OnPostCreated||e===np.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])]}e===np.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class _p extends ki{constructor(e,t){const n=O.default(e),a=["globalFeed","collection",n];super(new kp(e),n,a,t),this.query=e,this.queryStreamController=new Ap(this.query,this.cacheKey,this.notifyChange.bind(this),Gl),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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(Op(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=(null!==(r=s.data.map((e=>Ze(["post","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.post);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class Ep extends wi{async getRequest(e,t){const{userId:n,feedSources:a,dataTypes:r,includeDeleted:s,matchingOnlyParentPost:o,limit:i=de,untilAt:c}=e,l=Kn(e,["userId","feedSources","dataTypes","includeDeleted","matchingOnlyParentPost","limit","untilAt"]),d=t?{token:t}:{limit:i},{data:u}=await this.http.get(`/api/v4/user-feeds/${n}`,{params:Object.assign(Object.assign({},l),{options:d,dataTypes:(null==r?void 0:r.length)?r:void 0,includePostedFeed:a,isDeleted:oa(s),matchingOnlyParentPost:null!=o?o:!(null==r?void 0:r.length)})});return u}}class Rp extends Ci{constructor(e,t,n,a){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=a,this.validatedUntilAt=e.untilAt?St(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;let s=e.posts;if(n&&(this.boundaryReached=!1),void 0!==this.validatedUntilAt){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated",t=s.filter((t=>!Ot(t.createdAt,this.validatedUntilAt,e)));t.length<s.length&&(this.boundaryReached=!0),s=t}if(n)et(this.cacheKey,{data:s.map(We("post"))});else{const e=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,t=null!==(r=null==e?void 0:e.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...s.map(We("post"))])]}))}}reactor(e){return t=>{var n,a;const r=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(r&&(this.query.dataTypes&&0!==this.query.dataTypes.length||r.data.includes(t.parentPostId?t.parentPostId:t.postId))){if(void 0!==this.validatedUntilAt&&(e===np.OnPostCreated||e===np.OnPostApproved||e===np.OnPostUpdated)){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";if(Ot(t.createdAt,this.validatedUntilAt,e))return}if(e===np.OnPostDeleted&&(r.data=r.data.filter((e=>e!==t.postId))),t.parentPostId&&t.isDeleted){const e=null===(a=Ze(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),et(["post","get",e.postId],e)}if(e===np.OnPostDeclined&&(r.data=r.data.filter((e=>e!==t.postId))),e===np.OnPostCreated||e===np.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])]}et(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}hasBoundaryReached(){return this.boundaryReached}}const Pp=async e=>{const t=ze();let n;t.log("post/getPost",e),ta("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw Oe(null==t?void 0:t.code)&&Fn("post",e),t}const a=Qn(n,"communityUsers"),r=t.cache&&Date.now();t.cache&&Ln(a,{cachedAt:r});const{posts:s}=a;return{data:s.find((t=>t.postId===e)),cachedAt:r}};Pp.locally=e=>{const t=ze();if(t.log("post/getPost.locally",e),!t.cache)return;const n=Ze(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class Mp extends ki{constructor(e,t){const n=O.default(e),a=["userFeed","collection",n];super(new Ep(e),n,a,t),this.query=e,this.queryStreamController=new Rp(this.query,this.cacheKey,this.notifyChange.bind(this),Gl),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:dd,action:np.OnPostCreated},{fn:ud,action:np.OnPostUpdated},{fn:Cp,action:np.OnPostUpdated},{fn:hd,action:np.OnPostDeleted},{fn:md,action:np.OnPostFlagged},{fn:gd,action:np.OnPostUnflagged},{fn:pd,action:np.OnPostApproved},{fn:fd,action:np.OnPostDeclined},{fn:yd,action:np.OnPostReactionAdded},{fn:vd,action:np.OnPostReactionRemoved},{fn:wp,action:np.OnPostReactionAdded},{fn:Ip,action:np.OnPostReactionRemoved},{fn:bp,action:np.OnPostDeleted},{fn:Tl((e=>Id((async t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await Pp(t.referenceId),e(t))}))),"referenceId","post"),action:np.OnPostUpdated},{fn:Tl((e=>Sd((async t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await Pp(t.referenceId),e(t))}))),"referenceId","post"),action:np.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=null!==(r=s.data.map((e=>Ze(["post","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[],i=this.applyFilter(o).map(dl.post);if(!this.shouldNotify(i)&&"event"===e)return;const c=!this.queryStreamController.hasBoundaryReached()&&!!this.paginationController.getNextToken();this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:c,loading:t,error:n})}applyFilter(e){var t;let n=e;if(this.query.includeDeleted||(n=rt(n,"isDeleted",!1)),(null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=dt(n,this.query.dataTypes)),this.query.untilAt){const e=St(this.query.untilAt),t="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";n=n.filter((n=>!Ot(n.createdAt,e,t)))}if("firstCreated"===this.query.sortBy)n=n.sort(yt);else n=n.sort(bt);return n}}class jp extends wi{async getRequest(e,t){const{limit:n=de,includeDeleted:a,communityId:r,untilAt:s}=e,o=Kn(e,["limit","includeDeleted","communityId","untilAt"]),i=t?{token:t}:{limit:n},{data:c}=await this.http.get("/api/v5/posts",{params:Object.assign(Object.assign({},o),{targetId:r,targetType:"community",isDeleted:oa(a),matchingOnlyParentPost:!0,options:i})});return c}}class Up extends Ci{constructor(e,t,n,a){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=a,this.validatedUntilAt=e.untilAt?St(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;let s=e.posts;if(n&&(this.boundaryReached=!1),void 0!==this.validatedUntilAt&&"firstUpdated"!==this.query.sortBy&&"lastUpdated"!==this.query.sortBy){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated",t=s.filter((t=>!Ot(t.createdAt,this.validatedUntilAt,e)));t.length<s.length&&(this.boundaryReached=!0),s=t}if(n)et(this.cacheKey,{data:s.map(We("post"))});else{const e=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,t=null!==(r=null==e?void 0:e.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...s.map(We("post"))])]}))}}reactor(e){return t=>{var n,a;const r=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(void 0!==this.validatedUntilAt&&(e===np.OnPostCreated||e===np.OnPostApproved)&&"firstUpdated"!==this.query.sortBy&&"lastUpdated"!==this.query.sortBy){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";if(Ot(t.createdAt,this.validatedUntilAt,e))return}if(e===np.OnPostDeleted&&(r.data=r.data.filter((e=>e!==t.postId))),t.parentPostId&&t.isDeleted){const e=null===(a=Ze(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),et(["post","get",e.postId],e)}e===np.OnPostDeclined&&(r.data=r.data.filter((e=>e!==t.postId))),e!==np.OnPostCreated&&e!==np.OnPostApproved||(r.data=[...new Set([t.postId,...r.data])]),et(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}hasBoundaryReached(){return this.boundaryReached}}const Dp=({cacheKey:e,resolveId:t})=>[Id,Sd,gp,dp].map((n=>({fn:Tl((a=>((e,t,n,a)=>t((async t=>{var r;const s=null===(r=Ze(n))||void 0===r?void 0:r.data;s&&s.data.includes(a?a(t.referenceId):t.referenceId)&&e(t)})))(a,n,e,t)),"referenceId","post"),action:np.OnPostUpdated}))),xp=e=>[{fn:dd,action:np.OnPostCreated},{fn:ud,action:np.OnPostUpdated},{fn:Cp,action:np.OnPostUpdated},{fn:hd,action:np.OnPostDeleted},{fn:md,action:np.OnPostFlagged},{fn:gd,action:np.OnPostUnflagged},{fn:pd,action:np.OnPostApproved},{fn:fd,action:np.OnPostDeclined},{fn:yd,action:np.OnPostReactionAdded},{fn:vd,action:np.OnPostReactionRemoved},{fn:wp,action:np.OnPostReactionAdded},{fn:Ip,action:np.OnPostReactionRemoved},{fn:bp,action:np.OnPostDeleted},...Dp({cacheKey:e})],qp=(e,t)=>{var n;return null!==(n=e.map((e=>{const n=t.find((t=>t.postId===e.referenceId));return n?We("post")({postId:null==n?void 0:n.postId}):void 0})).filter(Ai))&&void 0!==n?n:[]};class Np extends ki{constructor(e,t){const n=O.default(e),a=["communityFeed","collection",n];super(new jp(e),n,a,t),this.query=e,this.queryStreamController=new Up(this.query,this.cacheKey,this.notifyChange.bind(this),Gl),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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(xp(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["post","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.post);if(!this.shouldNotify(o)&&"event"===e)return;const i=!this.queryStreamController.hasBoundaryReached()&&!!this.paginationController.getNextToken();this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:i,loading:t,error:n})}applyFilter(e){let t=e;if(this.query.includeDeleted||(t=rt(t,"isDeleted",!1)),this.query.tags&&(t=t.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.untilAt&&"firstUpdated"!==this.query.sortBy&&"lastUpdated"!==this.query.sortBy){const e=St(this.query.untilAt),n="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";t=t.filter((t=>!Ot(t.createdAt,e,n)))}switch(this.query.sortBy){case"firstCreated":t=t.sort(yt);break;case"firstUpdated":t=t.sort(wt);break;case"lastUpdated":t=t.sort(It);break;default:t=t.sort(bt)}return t}}class Bp extends Fe{constructor(e="For You feed is not enabled for this network"){super(e,400400,"error"),this.type="AmityForYouFeedDisabledError"}}class Lp extends wi{constructor(e){super(e),this.checkedDisk=!1,this.hasDeliveredPost=!1,this.cursor=Gs.current()}async getRequest(e,t){var n,a,r,s,o;const i=void 0===t;let c=null;if(i&&!this.checkedDisk&&this.cursor&&(this.checkedDisk=!0,c=await this.cursor.get(),c&&Gs.isExpired(c.expiredAt)&&(await this.cursor.clear(),c=null)),i&&(null==c?void 0:c.reachedEndOfFeed)){const e=await this.fetch(),t=Date.parse(null!==(a=null===(n=e.paging)||void 0===n?void 0:n.expiredAt)&&void 0!==a?a:"");return!Number.isNaN(t)&&t!==c.expiredAt?(await this.persistCursor(e),e.posts.length>0&&(this.hasDeliveredPost=!0),e):Object.assign(Object.assign({},e),{posts:[],paging:{}})}const l=i&&c?c.cursor:t,d=await this.fetch(l);if(d.posts.length>0&&(this.hasDeliveredPost=!0),null===(r=d.paging)||void 0===r?void 0:r.next)await this.persistCursor(d);else if(this.hasDeliveredPost&&this.cursor){const e=Date.parse(null!==(o=null===(s=d.paging)||void 0===s?void 0:s.expiredAt)&&void 0!==o?o:"");Number.isNaN(e)||await this.cursor.markReachedEndOfFeed(e)}return d}async fetch(e){const t={limit:ue};e&&(t.token=e);try{const{data:e}=await this.http.get(ve,{params:{options:t}});return e}catch(t){if(t instanceof Fe&&400300===t.code)throw new Bp;if(t instanceof Fe&&400322===t.code&&void 0!==e){this.cursor&&await this.cursor.clear();const{data:e}=await this.http.get(ve,{params:{options:{limit:ue}}});return e}throw t}}async persistCursor(e){var t,n;if(!this.cursor)return;const a=null===(t=e.paging)||void 0===t?void 0:t.next,r=null===(n=e.paging)||void 0===n?void 0:n.expiredAt;if(!a||!r)return;const s=Date.parse(r);Number.isNaN(s)||await this.cursor.set({cursor:a,expiredAt:s})}}class Fp extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.posts.map(We("post"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(We("post"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;a&&(t.parentPostId&&!a.data.includes(t.parentPostId)||(e!==np.OnPostDeleted&&e!==np.OnPostDeclined||(a.data=a.data.filter((e=>e!==t.postId))),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Kp=["forYouFeed","collection"];class $p extends ki{constructor(e){const t=`for-you-feed-${ze().userId}`,n={};super(new Lp(n),t,Kp,e),this.queryStreamController=new Fp(n,this.cacheKey,this.notifyChange.bind(this),Gl),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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(Op(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=(null!==(r=s.data.map((e=>Ze(["post","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.post);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var Qp=Object.freeze({__proto__:null,queryGlobalFeed:ep,getCustomRankingGlobalFeed:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`getCustomRankingGlobalFeed(tmpid: ${s}) > listen`);const o=new Tp(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getCustomRankingGlobalFeed(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getGlobalFeed:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`getGlobalFeed(tmpid: ${s}) > listen`);const o=new _p(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getGlobalFeed(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getUserFeed:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`getUserFeed(tmpid: ${s}) > listen`);const o=new Mp(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getUserFeed(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getCommunityFeed:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`getCommunityFeed(tmpid: ${s}) > listen`);const o=new Np(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getCommunityFeed(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getForYouFeed:e=>{const{log:t,cache:n}=ze();n||console.log(pe);const a=Date.now();t(`getForYouFeed(tmpid: ${a}) > listen`);const r=new $p(e),s=r.startSubscription(),o=r.getCacheKey();return s.push((()=>at(o))),()=>{t(`getForYouFeed(tmpid: ${a}) > dispose`),s.forEach((e=>e()))}},AmityForYouFeedDisabledError:Bp});const Vp=async e=>{const t=ze();t.log("post/getPostByIds",e);const n=e.map((e=>encodeURIComponent(e)));let a;try{a=(await t.http.get("/api/v3/posts/list",{params:{postIds:n}})).data}catch(t){throw e.forEach((e=>{Oe(null==t?void 0:t.code)&&Fn("post",e)})),t}const r=Qn(a,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Ln(r,{cachedAt:s}),{data:r.posts.map(dl.post),cachedAt:s}};Vp.locally=e=>{var t;const n=ze();if(n.log("post/getPostByIds.locally",e),!n.cache)return;const a=e.map((e=>Ze(["post","get",e]))).filter(Boolean),r=a.map((({data:e})=>e)),s=null===(t=a.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==a?void 0:a.length)<e.length?void 0:{data:r.map(dl.post),cachedAt:s.cachedAt}};const zp=async(e,t=!1)=>{var n;const a=ze(),r=await Xl(e);if(await a.http.delete(`/api/v4/posts/${encodeURIComponent(e)}`,{params:{postId:e,permanent:t}}),"community"===r.data.targetType){const e=await Qu(r.data.targetId),t=(null!==(n=Xe(["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));jt("community.updated",{communities:[e.data],categories:[],communityUsers:t,feeds:[],files:[],users:[]})}const s=Object.assign(Object.assign({},r.data),{isDeleted:!0});return t?setTimeout((()=>{Fn("post",e)}),0):nt(["post","get",e],{isDeleted:!0}),jt("local.post.deleted",{posts:[s],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[],videoStreamings:[]}),dl.post(s)};class Hp extends wi{async getRequest(e,t){const{limit:n=de,includeDeleted:a,matchingOnlyParentPost:r,untilAt:s}=e,o=Kn(e,["limit","includeDeleted","matchingOnlyParentPost","untilAt"]),{dataTypes:i}=o,c={type:o.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/v5/posts",{params:Object.assign(Object.assign({},o),{isDeleted:oa(a),matchingOnlyParentPost:null!=r?r:!(null==i?void 0:i.length),options:l})});return d}}class Jp extends Ci{constructor(e,t,n,a){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=a,this.validatedUntilAt=e.untilAt?St(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;let s=e.posts;if(n&&(this.boundaryReached=!1),void 0!==this.validatedUntilAt){const e=this.query.sortBy||"lastCreated",t=s.filter((t=>!Ot(t.createdAt,this.validatedUntilAt,e)));t.length<s.length&&(this.boundaryReached=!0),s=t}if(n)et(this.cacheKey,{data:s.map(We("post"))});else{const e=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,t=null!==(r=null==e?void 0:e.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...s.map(We("post"))])]}))}}reactor(e){return t=>{var n,a;const r=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(void 0!==this.validatedUntilAt&&(e===np.OnPostCreated||e===np.OnPostApproved)){const e=this.query.sortBy||"lastCreated";if(Ot(t.createdAt,this.validatedUntilAt,e))return}if(t.parentPostId&&t.isDeleted){const e=null===(a=Ze(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e||(null==e?void 0:e.targetId)!==this.query.targetId)return;e.children=e.children.filter((e=>e!==t.postId)),et(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===np.OnPostDeclined&&(r.data=r.data.filter((e=>e!==t.postId))),e!==np.OnPostCreated&&e!==np.OnPostApproved||(r.data=[...new Set([t.postId,...r.data])]),et(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}hasBoundaryReached(){return this.boundaryReached}}class Wp extends ki{constructor(e,t){const n=O.default(e),a=["posts","collection",n];super(new Hp(e),n,a,t),this.query=e,this.queryStreamController=new Jp(this.query,this.cacheKey,this.notifyChange.bind(this),Gl),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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(){const e=this.queryStreamController.subscribeRTE(xp(this.cacheKey));if(this.query.excludeBlockUserPosts){const t=()=>this.notifyChange({origin:"event",loading:!1});e.push(Js(t),Ws(t))}return e}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["post","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.post);if(!this.shouldNotify(o)&&"event"===e)return;const i=!this.queryStreamController.hasBoundaryReached()&&!!this.paginationController.getNextToken();this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:i,loading:t,error:n})}applyFilter(e){var t;let n=e;if(this.query.includeDeleted||(n=rt(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=ct(n,this.query.feedType)),(null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=dt(n,this.query.dataTypes)),this.query.untilAt){const e=St(this.query.untilAt),t=this.query.sortBy||"lastCreated";n=n.filter((n=>!Ot(n.createdAt,e,t)))}if(this.query.excludeBlockUserPosts&&(n=pt(n)),"firstCreated"===this.query.sortBy)n=n.sort(yt);else n=n.sort(bt);return n}}class Gp extends wi{async getRequest(e,t){const n=Kn(e,["limit"]),{communityId:a,placement:r}=n,s=Kn(n,["communityId","placement"]),o=r?`/api/v1/pinned-posts/communities/${a}/${r}`:`/api/v1/pinned-posts/communities/${a}`,{data:i}=await this.http.get(o,{params:Object.assign({},s)});return i}}class Yp extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=ze(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users?e.users.map(ga):[]});Ln(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.pins.map(We("pin"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(We("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===np.OnPostDeleted&&(a.data=a.data.filter((e=>e!==`global#${t.postId}`))),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Xp extends ki{constructor(e,t){const n=O.default(e),a=["pinnedPosts","collection",n];super(new Gp(e),n,a,t),this.query=e,this.queryStreamController=new Yp(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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(Dp({cacheKey:this.cacheKey,resolveId:e=>`${this.query.placement}#${e}`}))}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;let o=(null!==(r=s.data.map((e=>Ze(["pin","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.pinnedPost);o=this.applyFilter(o),(this.shouldNotify(o)||"event"!==e)&&this.callback({data:o,loading:t,error:n})}applyFilter(e){let t=e;if("lastCreated"===this.query.sortBy)t=t.sort((({post:e},{post:t})=>bt({createdAt:null==e?void 0:e.createdAt},{createdAt:null==t?void 0:t.createdAt})));return t}}class Zp extends wi{async getRequest(e,t){const n=Kn(e,["limit"]),{data:a}=await this.http.get("/api/v1/pinned-posts/global",{params:Object.assign({},n)});return a}}class ef extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=ze(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users.map(ga)});Ln(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.pins.map(We("pin"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(We("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===np.OnPostDeleted&&(a.data=a.data.filter((e=>e!==`global#${t.postId}`))),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class tf extends ki{constructor(e,t){const n=O.default(e),a=["pinnedPosts","collection",n];super(new Zp(e),n,a,t),this.query=e,this.queryStreamController=new ef(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:bp,action:np.OnPostDeleted},{fn:hd,action:np.OnPostDeleted},...Dp({cacheKey:this.cacheKey,resolveId:e=>`global#${e}`})])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=(null!==(r=s.data.map((e=>Ze(["pin","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.pinnedPost);(this.shouldNotify(o)||"event"!==e)&&this.callback({data:o,loading:t,error:n})}}class nf extends wi{async getRequest(e,t){const{limit:n=de}=e,a=Kn(e,["limit"]),r={type:e.limit?"pagination":void 0},s=t?Object.assign(Object.assign({},r),{token:t}):Object.assign(Object.assign({},r),{limit:n}),{data:o}=await this.http.get("/api/v1/semantic-search/posts",{params:Object.assign(Object.assign({},a),{options:s})});return o}}function af(e){return e.posts.map((t=>{const n=e.searchResult.find((e=>e.postId===t.postId));return`${t.postId}:${n.score}`}))}function rf(e){return(null!=e?e:[]).map((e=>e.split(":")[0]))}class sf extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:af(e)});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...af(e)])]}))}}reactor(e){return t=>{var n,a;const r=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(t.parentPostId&&t.isDeleted){const e=null===(a=Ze(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e||(null==e?void 0:e.targetId)!==this.query.targetId)return;e.children=e.children.filter((e=>e!==t.postId)),et(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===np.OnPostDeclined&&(r.data=r.data.filter((e=>e!==t.postId))),e!==np.OnPostCreated&&e!==np.OnPostApproved||(r.data=[...new Set([t.postId,...r.data])]),et(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class of extends ki{constructor(e,t){const n=Object.assign(Object.assign({},e),{matchingOnlyParentPost:null==e.matchingOnlyParentPost||e.matchingOnlyParentPost,dataTypes:null==e.dataTypes?["text","image"]:e.dataTypes}),a=O.default(n),r=["posts","collection",a];super(new nf(n),a,r,t),this.query=n,this.queryStreamController=new sf(this.query,this.cacheKey,this.notifyChange.bind(this),Yl),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:ud,action:np.OnPostUpdated},{fn:hd,action:np.OnPostDeleted},{fn:md,action:np.OnPostFlagged},{fn:gd,action:np.OnPostUnflagged},{fn:pd,action:np.OnPostApproved},{fn:fd,action:np.OnPostDeclined},{fn:yd,action:np.OnPostReactionAdded},{fn:vd,action:np.OnPostReactionRemoved},{fn:Tl((e=>Id((async t=>{const n=Ze(this.cacheKey);rf(null==n?void 0:n.data).includes(t.referenceId)||(await Xl(t.referenceId),e(t))}))),"referenceId","post"),action:np.OnPostUpdated},{fn:Tl((e=>Sd((async t=>{const n=Ze(this.cacheKey);rf(null==n?void 0:n.data).includes(t.referenceId)||(await Xl(t.referenceId),e(t))}))),"referenceId","post"),action:np.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>{const[t,n]=e.split(":");return{postId:t,score:parseFloat(n)}})).sort(((e,t)=>t.score-e.score)).map((({postId:e})=>Ze(["post","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.post);(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;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=dt(t,this.query.dataTypes)),t}}class cf extends wi{async getRequest(e,t){const{limit:n=de,matchingOnlyParentPost:a,hashtags:r,dataTypes:s,targetType:o="all"}=e,i=Kn(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:r,dataTypes:s,targetType:o,matchingOnlyParentPost:null!=a?a:!(null==s?void 0:s.length),options:l})});return d}}class lf extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.posts.map(We("post"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(We("post"))])]}))}}reactor(e){return t=>{var n,a;const r=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(t.parentPostId&&t.isDeleted){const e=null===(a=Ze(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),et(["post","get",e.postId],e)}e===np.OnPostDeclined&&(r.data=r.data.filter((e=>e!==t.postId))),e!==np.OnPostCreated&&e!==np.OnPostApproved||(r.data=[...new Set([t.postId,...r.data])]),et(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class df extends ki{constructor(e,t){const n=O.default(e),a=["posts","collection",n];super(new cf(e),n,a,t),this.query=e,this.queryStreamController=new lf(this.query,this.cacheKey,this.notifyChange.bind(this),Gl),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:dd,action:np.OnPostCreated},{fn:ud,action:np.OnPostUpdated},{fn:Cp,action:np.OnPostUpdated},{fn:hd,action:np.OnPostDeleted},{fn:md,action:np.OnPostFlagged},{fn:gd,action:np.OnPostUnflagged},{fn:pd,action:np.OnPostApproved},{fn:fd,action:np.OnPostDeclined},{fn:yd,action:np.OnPostReactionAdded},{fn:vd,action:np.OnPostReactionRemoved},{fn:wp,action:np.OnPostReactionAdded},{fn:Ip,action:np.OnPostReactionRemoved},{fn:bp,action:np.OnPostDeleted},{fn:Tl((e=>Id((async t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await Pp(t.referenceId),e(t))}))),"referenceId","post"),action:np.OnPostUpdated},{fn:Tl((e=>Sd((async t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await Pp(t.referenceId),e(t))}))),"referenceId","post"),action:np.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["post","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.post);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,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=dt(n,this.query.dataTypes)),"firstCreated"===this.query.sortBy)n=n.sort(yt);else n=n.sort(bt);return n}}class uf extends Ti{async getRequest(e){const{limit:t=100}=e,{data:n}=await this.http.get("/api/v1/rooms/lives",{params:{targetTypes:["all"],options:{limit:t,sortBy:"lastCreated"}}});return n}}class hf extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:qp(e.rooms,e.posts)});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...qp(e.rooms,e.posts)])]}))}}reactor(e){return e=>{var t;const n=null===(t=Ze(this.cacheKey))||void 0===t?void 0:t.data;n&&("ended"===e.status&&et(this.cacheKey,Object.assign(Object.assign({},n),{data:n.data.filter((t=>e.referenceId!==t))})),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const pf=e=>{const t=ze();return Mt(t,"room/onRoomStartBroadcasting","room.startBroadcasting",(t=>{Ln(t),e(t.rooms[0])}))},ff=e=>{const t=ze();return Mt(t,"room/onRoomWaitingReconnect","room.waitingReconnect",(t=>{Ln(t),e(t.rooms[0])}))},mf=e=>{const t=ze();return Mt(t,"room/onRoomEndBroadcasting","room.endBroadcasting",(t=>{Ln(t),e(t.rooms[0])}))},gf=e=>{const t=ze();return Mt(t,"room/onRoomRecordedAvailable","room.recordedAvailable",(t=>{Ln(t),e(t.rooms[0])}))},yf=e=>{const t=ze();return Mt(t,"room/onRoomCoHostInvited","room.didCohostInvite",(t=>{const n=Wi(t);Ln(n),e(n.invitations)}))},vf=async e=>{const t=ze();let n;t.log("room/getRoomById",e),ta("room",e);try{n=(await t.http.get(`/api/v1/rooms/${e}`)).data}catch(t){throw Oe(null==t?void 0:t.code)&&Fn("room",e),t}const a=t.cache&&Date.now();return t.cache&&Ln(n,{cachedAt:a}),{data:n.rooms[0],cachedAt:a}};vf.locally=e=>{const t=ze();t.log("room/getRoomById.locally",e),ta("room",e);const n=t.cache&&Date.now(),a=Ze(["room","get",e]);if(a)return{data:a.data,cachedAt:n}};const bf=e=>{const t=ze();return Mt(t,"room/onRoomCoHostInviteAccepted","room.didCohostInviteAccept",(async t=>{var n;const a=Wi(t);await vf(null===(n=a.invitations)||void 0===n?void 0:n[0].targetId),Ln(a),e(a.invitations[0])}))},wf=e=>{const t=ze();return Mt(t,"room/onRoomCoHostInviteRejected","room.didCohostInviteReject",(t=>{const n=Wi(t);Ln(n),e(n.invitations)}))},If=e=>{const t=ze();return Mt(t,"room/onRoomCoHostInviteCanceled","room.didCohostInviteCancel",(t=>{const n=Wi(t);Ln(n),e(n.invitations)}))},Cf=e=>{const t=ze();return Mt(t,"room/onRoomParticipantJoined","room.participantJoined",(t=>{const{rooms:n,users:a}=t;Ln({rooms:n,users:a}),e({room:dc(n[0]),actorInternalId:t.eventActor.userInternalId})}))},Sf=e=>{const t=ze();return Mt(t,"room/onRoomParticipantLeft","room.participantLeft",(t=>{const{rooms:n,users:a}=t;Ln({rooms:n,users:a}),e({room:dc(n[0]),actorInternalId:t.eventActor.userInternalId})}))},Of=e=>{const t=ze();return Mt(t,"room/onRoomParticipantStageJoined","room.participantStageJoined",(t=>{const{rooms:n,users:a}=t;Ln({rooms:n,users:a}),e({room:dc(n[0]),actorInternalId:t.eventActor.userInternalId})}))},Tf=e=>{const t=ze();return Mt(t,"room/onRoomTerminated","room.terminated",(t=>{Ln(t),e(t.rooms[0])}))},kf=e=>{const t=ze();return Mt(t,"room/onRoomDidUpdate","local.room.didUpdate",(t=>{Ln(t),e(t.rooms[0])}))},Af=e=>{const t=ze();return Mt(t,"room/onRoomParticipantRemoved","room.participantRemoved",(t=>{const{rooms:n,users:a}=t;Ln({rooms:n,users:a}),e({room:dc(n[0]),actorInternalId:t.eventActor.userInternalId})}))},_f=e=>{const t=ze();return Mt(t,"room/onLocalRoomDidUpdate","room.didUpdate",(t=>{Ln(t),e(t.rooms[0])}))},Ef=e=>{const t=ze();return Mt(t,"room/onRoomParticipantRemoved","local.room.participantRemoved",(t=>{Ln(t),e(t.rooms[0])}))};var Rf;!function(e){e.OnRoomCreated="OnRoomCreated",e.OnRoomUpdated="OnRoomUpdated",e.OnRoomDeleted="OnRoomDeleted",e.OnRoomStartBroadcasting="OnRoomStartBroadcasting",e.OnRoomEndBroadcasting="OnRoomEndBroadcasting",e.OnRoomParticipantJoined="OnRoomParticipantJoined",e.OnRoomParticipantLeft="OnRoomParticipantLeft",e.OnRoomDidUpdate="OnRoomDidUpdate"}(Rf||(Rf={}));const Pf=e=>t=>e((e=>{t(e.room)}));class Mf extends wi{async getRequest(e,t){const{limit:n=de,includeDeleted:a}=e,r=Kn(e,["limit","includeDeleted"]),s={type:r.sortBy||e.limit?"pagination":void 0},o=t?Object.assign(Object.assign({},s),{token:t}):Object.assign(Object.assign({},s),{limit:n}),{data:i}=await this.http.get("/api/v1/rooms",{params:Object.assign(Object.assign({},r),{isDeleted:oa(a),options:o})});return i}}class jf extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.rooms.map(We("room"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.rooms.map(We("room"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===Rf.OnRoomDeleted&&(a.data=a.data.filter((e=>e!==t._id))),e===Rf.OnRoomCreated&&(a.data=[...new Set([t._id,...a.data])]),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Uf extends ki{constructor(e,t){const n=O.default(e),a=["rooms","collection",n];super(new Mf(e),n,a,t),this.query=e,this.queryStreamController=new jf(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:pf,action:Rf.OnRoomStartBroadcasting},{fn:mf,action:Rf.OnRoomEndBroadcasting},{fn:gf,action:Rf.OnRoomUpdated},{fn:ff,action:Rf.OnRoomUpdated},{fn:Tf,action:Rf.OnRoomUpdated},{fn:Pf(Cf),action:Rf.OnRoomUpdated},{fn:Pf(Sf),action:Rf.OnRoomUpdated},{fn:Pf(Af),action:Rf.OnRoomUpdated},{fn:Ef,action:Rf.OnRoomUpdated},{fn:Pf(Of),action:Rf.OnRoomUpdated},{fn:Tl(bf,"targetId","room"),action:Rf.OnRoomUpdated},{fn:kf,action:Rf.OnRoomDidUpdate},{fn:_f,action:Rf.OnRoomDidUpdate}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["room","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dc);(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;if(this.query.includeDeleted||(t=rt(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=rt(t,"type",this.query.type)),"firstCreated"===this.query.sortBy)t=t.sort(yt);else t=t.sort(bt);return t}}var Df=Object.freeze({__proto__:null,createRoom:async e=>{const t=ze();t.log("room/createRoom",e);const{data:n}=await t.http.post("/api/v1/rooms",e);jt("local.room.created",n);const a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a});const{rooms:r}=n;return{data:dc(r[0]),cachedAt:a}},updateRoom:async(e,t)=>{const n=ze();n.log("room/updateRoom",{roomId:e,bundle:t});const{data:a}=await n.http.put(`/api/v1/rooms/${e}`,t);jt("local.room.updated",a);const r=n.cache&&Date.now();n.cache&&Ln(a,{cachedAt:r});const{rooms:s}=a;return{data:dc(s[0]),cachedAt:r}},deleteRoom:async e=>{const t=ze();t.log("room/deleteRoom",{roomId:e}),await t.http.delete(`/api/v1/rooms/${e}`),jt("local.room.deleted",{rooms:[{_id:e}]})},stopRoom:async e=>{const t=ze();t.log("room/stopRoom",{roomId:e});const{data:n}=await t.http.post(`/api/v1/rooms/${e}/stop`);jt("local.room.stopped",n);const a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a});const{rooms:r}=n;return{data:r[0],cachedAt:a}},getBroadcasterData:async e=>{const t=ze();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=ze();t.log("room/getRecordedUrl",{roomId:e});const{data:n}=await t.http.get(`/api/v1/rooms/${e}/recorded`);return n},removeParticipant:async(e,t)=>{const n=ze();n.log("room/removeParticipant",{roomId:e,participantUserId:t}),await n.http.delete(`/api/v1/rooms/${e}/participants/${t}`),jt("local.room.participantRemoved",{rooms:[{_id:e}],users:[{_id:t}]})},leaveRoom:async e=>{const t=ze();t.log("room/leaveRoom",{roomId:e}),await t.http.post(`/api/v1/rooms/${e}/leave`),jt("local.room.left",{rooms:[{_id:e}]})},AmityRoomAnalytics:lc,WatchSessionStorage:Xi,getWatchSessionStorage:ec,syncWatchSessions:ic,updateCohostPermission:async(e,t,n)=>{const a=ze();a.log("room/updatedCoHostPermission",{roomId:e,cohostId:t,canManageProductTags:n});const{data:r}=await a.http.put(`/api/v1/rooms/${e}/participants/${t}`,{canManageProductTags:n});jt("local.room.didUpdate",r);const s=a.cache&&Date.now();a.cache&&Ln(r,{cachedAt:s});const{rooms:o}=r;return{data:dc(o[0]),cachedAt:s}},onRoomStartBroadcasting:pf,onRoomWaitingReconnect:ff,onRoomEndBroadcasting:mf,onRoomRecordedAvailable:gf,onRoomCoHostInvited:yf,onRoomCoHostInviteAccepted:bf,onRoomCoHostInviteRejected:wf,onRoomCoHostInviteCanceled:If,onRoomParticipantJoined:Cf,onRoomParticipantLeft:Sf,onRoomParticipantStageLeft:e=>{const t=ze();return Mt(t,"room/onRoomParticipantStageLeft","room.participantStageLeft",(t=>{const{rooms:n,users:a}=t;Ln({rooms:n,users:a}),e({room:dc(n[0]),actorInternalId:t.eventActor.userInternalId})}))},onRoomParticipantStageJoined:Of,onRoomTerminated:Tf,onRoomDidUpdate:kf,onRoomCreated:e=>{const t=ze();return Mt(t,"room/onRoomCreated","local.room.created",(t=>{Ln(t),e(t.rooms[0])}))},onRoomUpdated:e=>{const t=ze();return Mt(t,"room/onRoomUpdated","local.room.updated",(t=>{Ln(t),e(t.rooms[0])}))},onRoomDeleted:e=>{const t=ze();return Mt(t,"room/onRoomDeleted","local.room.deleted",(t=>{Ln(t),e(t.rooms[0])}))},onRoomStopped:e=>{const t=ze();return Mt(t,"room/onRoomStopped","local.room.stopped",(t=>{Ln(t),e(t.rooms[0])}))},onRoomParticipantRemoved:Af,onRoomLeft:e=>{const t=ze();return Mt(t,"room/onRoomLeft","local.room.left",(t=>{Ln(t),e(t.rooms[0])}))},onLocalRoomDidUpdate:_f,getRoom:(e,t)=>Ui(e,t,"_id",vf,[mf,pf,ff,Tf,gf,Pf(Cf),Pf(Sf),Pf(Af),Ef,Pf(Of),Tl(bf,"targetId","room"),kf,_f],{callbackDataSelector:e=>e?dl.room(e):e}),getRooms:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`getRooms(tmpid: ${s}) > listen`);const o=new Uf(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getRooms(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}}});class xf extends ki{constructor(e){const t={limit:100},n=O.default(t),a=["liveRoomPosts","collection",n];super(new uf(t),n,a,e),this.query=t,this.queryStreamController=new hf(this.query,this.cacheKey,this.notifyChange.bind(this),Gl),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:mf,action:np.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["post","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.post);(this.shouldNotify(o)||"event"!==e)&&this.callback({data:o,loading:t,error:n})}applyFilter(e){return e}}class qf extends Ti{async getRequest(e){const{limit:t=100,communityIds:n}=e,{data:a}=await this.http.get("/api/v1/rooms/lives",{params:{targetTypes:["community"],targetIds:n,options:{limit:t,sortBy:"lastCreated"}}});return a}}class Nf extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:qp(e.rooms,e.posts)});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...qp(e.rooms,e.posts)])]}))}}reactor(e){return e=>{var t;const n=null===(t=Ze(this.cacheKey))||void 0===t?void 0:t.data;n&&("ended"===e.status&&et(this.cacheKey,Object.assign(Object.assign({},n),{data:n.data.filter((t=>e.referenceId!==t))})),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Bf extends ki{constructor(e,t){const n=O.default(e),a=["communityLiveRoomPosts","collection",n];super(new qf(e),n,a,t),this.query=e,this.queryStreamController=new Nf(this.query,this.cacheKey,this.notifyChange.bind(this),Gl),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:mf,action:np.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["post","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.post);(this.shouldNotify(o)||"event"!==e)&&this.callback({data:o,loading:t,error:n})}applyFilter(e){return e}}var Lf=Object.freeze({__proto__:null,getPostByIds:Vp,createPost:async e=>{const t=ze();t.log("post/createPost",e),e.dataType&&!["text","image","file","video"].includes(e.dataType)||delete e.dataType;const{attachments:n,attachmentProductTags:a}=e,r=Kn(e,["attachments","attachmentProductTags"]),s=n&&n.length>0&&e.attachmentProductTags?n.map((t=>{var n;const a=null===(n=e.attachmentProductTags)||void 0===n?void 0:n.get(t.fileId);return a?Object.assign(Object.assign({},t),{productTags:a}):t})):n,{data:o}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},r),{attachments:s}));jt("post.created",o);const i=Gl(o),c=t.cache&&Date.now();t.cache&&Ln(i,{cachedAt:c});const{posts:l}=i;return{data:dl.post(l[0]),cachedAt:c}},editPost:async(e,t)=>{const n=ze();n.log("user/editPost",t);const{attachments:a}=t,r=a&&a.length>0&&t.attachmentProductTags?a.map((e=>{var n;const a=null===(n=t.attachmentProductTags)||void 0===n?void 0:n.get(e.fileId);return a?Object.assign(Object.assign({},e),{productTags:a}):e})):a,{data:s}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,Object.assign(Object.assign({},t),{attachments:r})),o=Qn(s,"communityUsers"),i=n.cache&&Date.now();n.cache&&Ln(o,{cachedAt:i}),jt("local.post.updated",o);const{posts:c}=o;return{data:dl.post(c.find((t=>t.postId===e))),cachedAt:i}},deletePost:zp,softDeletePost:async e=>{ze().log("post/softDeletePost",e);const t=await zp(e,!1);return dl.post(t)},hardDeletePost:async e=>{ze().log("post/hardDeletePost",e);const t=await zp(e,!0);return dl.post(t)},approvePost:async e=>{const t=ze();t.log("post/approvePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/approve`);jt("post.approved",n),"community"===n.posts[0].targetType&&jt("community.updated",n);const a=Qn(n,"communityUsers"),r=t.cache&&Date.now();return t.cache&&Ln(a,{cachedAt:r}),{data:dl.post(a.posts.find((t=>t.postId===e))),cachedAt:r}},declinePost:async e=>{const t=ze();t.log("post/declinePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/decline`);"community"===n.posts[0].targetType&&jt("community.updated",n),jt("post.declined",n);const a=Qn(n,"communityUsers"),r=t.cache&&Date.now();return t.cache&&Ln(a,{cachedAt:r}),{data:dl.post(n.posts.find((t=>t.postId===e))),cachedAt:r}},flagPost:async(t,n)=>{const a=ze();a.log("post/flagPost",t);const r=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,a])=>t!==e.ContentFlagReasonEnum.Others&&a===n)),s={reason:n&&r?n:e.ContentFlagReasonEnum.Others,detail:n&&!r?n:""},{data:o}=await a.http.post(`/api/v3/posts/${encodeURIComponent(t)}/flag`,s);return a.cache&&Ln(Qn(o,"communityUsers")),jt("post.flagged",o),!!o},unflagPost:async e=>{const t=ze();t.log("post/unflagPost",e);const{data:n}=await t.http.delete(`/api/v3/posts/${encodeURIComponent(e)}/unflag`);return t.cache&&Ln(Qn(n,"communityUsers")),jt("post.unflagged",n),!!n},isPostFlaggedByMe:async e=>{const t=ze();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=ze();t.log("post/createPost",e);const{attachments:n,attachmentProductTags:a}=e,r=Kn(e,["attachments","attachmentProductTags"]),s=n&&n.length>0&&e.attachmentProductTags?n.map((t=>{var n;const a=null===(n=e.attachmentProductTags)||void 0===n?void 0:n.get(t.fileId);return a?Object.assign(Object.assign({},t),{productTags:a}):t})):n,{data:o}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},r),{attachments:s}));jt("post.created",o);const i=Qn(o,"communityUsers"),c=t.cache&&Date.now();t.cache&&Ln(i,{cachedAt:c});const{posts:l}=i;return{data:dl.post(l[0]),cachedAt:c}},createAudioPost:async e=>{const t=ze();t.log("post/createAudioPost",e);const{attachments:n,attachmentProductTags:a}=e,r=Kn(e,["attachments","attachmentProductTags"]),s=n&&n.length>0&&a?n.map((e=>{const t=null==a?void 0:a.get(e.fileId);return t?Object.assign(Object.assign({},e),{productTags:t}):e})):n,{data:o}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},r),{attachments:s}));jt("post.created",o);const i=Gl(o),c=t.cache&&Date.now();return t.cache&&Ln(i,{cachedAt:c}),{data:qc(null==i?void 0:i.posts[0]),cachedAt:c}},createMixedMediaPost:async e=>{var t;const n=ze();n.log("post/createMixedMediaPost",e);const{attachments:a,attachmentProductTags:r}=e,s=Kn(e,["attachments","attachmentProductTags"]),o=a&&a.length>0&&e.attachmentProductTags?a.map((t=>{var n;const a=null===(n=e.attachmentProductTags)||void 0===n?void 0:n.get(t.fileId);return a?Object.assign(Object.assign({},t),{productTags:a}):t})):a,{data:i}=await n.http.post("/api/v4/posts",Object.assign(Object.assign({},s),{attachments:o}));jt("post.created",i);const c=Gl(i),l=n.cache&&Date.now();return n.cache&&Ln(c,{cachedAt:l}),{data:qc(null===(t=null==c?void 0:c.posts)||void 0===t?void 0:t[0]),cachedAt:l}},createRoomPost:async e=>{const t=ze();t.log("post/createRoomPost",e);const{data:n}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},e),{dataType:"room"}));jt("post.created",n);const a=Gl(n),r=t.cache&&Date.now();t.cache&&Ln(a,{cachedAt:r});const{posts:s}=a;return{data:dl.post(s[0]),cachedAt:r}},pinProduct:async(e,t)=>{const n=ze();n.log("post/pinProduct",e);const{data:a}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{pinnedProductId:t}),r=Gl(a),s=n.cache&&Date.now();return n.cache&&Ln(a,{cachedAt:s}),jt("local.post.updated",a),{data:qc(null==r?void 0:r.posts[0]),cachedAt:s}},unpinProduct:async e=>{const t=ze();t.log("post/unpinProduct",e);const{data:n}=await t.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{pinnedProductId:null}),a=Gl(n),r=t.cache&&Date.now();return t.cache&&Ln(n,{cachedAt:r}),jt("local.post.updated",n),{data:qc(null==a?void 0:a.posts[0]),cachedAt:r}},updateProductTags:async(e,t)=>{const n=ze();n.log("post/updateProductTags",e);const{data:a}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{productTags:t}),r=Gl(a),s=n.cache&&Date.now();return n.cache&&Ln(a,{cachedAt:s}),jt("local.post.updated",a),{data:qc(null==r?void 0:r.posts[0]),cachedAt:s}},onPostCreated:dd,onPostUpdated:ud,onPostDeleted:hd,onPostApproved:pd,onPostDeclined:fd,onPostFlagged:md,onPostUnflagged:gd,onPostReactionAdded:yd,onPostReactionRemoved:vd,getPost:(e,t)=>Ui(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?dl.post(e.data):n}))}),"postId",Xl,[pd,fd,wp,Ip,t=>hd((n=>{var a;let r=n;if(n.parentPostId===e&&n.isDeleted){const e=null===(a=Ze(["post","get",n.parentPostId]))||void 0===a?void 0:a.data;e&&(e.children=e.children.filter((e=>e!==n.postId)),et(["post","get",e.postId],e),r=e)}t(r)})),md,e=>yd((t=>{e(t)})),e=>vd((t=>{e(t)})),gd,ud,Cp,bp,Tl((t=>Id((async n=>{n.referenceId===e&&(await Xl(e),t(n))}))),"referenceId","post"),Tl((t=>Sd((async n=>{n.referenceId===e&&(await Xl(e),t(n))}))),"referenceId","post")]),getPosts:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`getPosts(tmpid: ${s}) > listen`);const o=new Wp(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getPosts(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getPinnedPosts:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`getPinnedPosts(tmpid: ${s}) > listen`);const o=new Xp(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getPinnedPosts(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getGlobalPinnedPosts:(e,t,n)=>{const{log:a,cache:r}=ze(),s=Date.now();a(`getGlobalPinnedPosts(tmpid: ${s}) > listen`);const o=new tf(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getGlobalPinnedPosts(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},semanticSearchPosts:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`semanticSearchPosts(tmpid: ${s}) > listen`);const o=new of(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`semanticSearchPosts(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},searchPostsByHashtag:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`searchPostsByHashtag(tmpid: ${s}) > listen`);const o=new df(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`searchPostsByHashtag(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getLiveRoomPosts:e=>{const{log:t,cache:n}=ze();n||console.log(pe);const a=Date.now();t(`getLiveRoomPosts(tmpid: ${a}) > listen`);const r=new xf(e),s=r.startSubscription(),o=r.getCacheKey();return s.push((()=>at(o))),()=>{t(`getLiveRoomPosts(tmpid: ${a}) > dispose`),s.forEach((e=>e()))}},getCommunityLiveRoomPosts:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`getCommunityLiveRoomPosts(tmpid: ${s}) > listen`);const o=new Bf(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getCommunityLiveRoomPosts(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}}});const Ff=async e=>{const t=ze();t.log("stream/getStream",e);const{data:n}=await t.http.get(`/api/v3/video-streaming/${e}`),a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a});const{videoStreamings:r}=n;return{data:r.find((t=>t.streamId===e)),cachedAt:a}};Ff.locally=e=>{const t=ze();if(t.log("stream/getStream",e),!t.cache)return;const n=Ze(["stream","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Kf=e=>{const t=ze();return Mt(t,"stream/onStreamStarted","video-streaming.didStart",(t=>{Ln(t),e(t.videoStreamings[0])}))},$f=e=>{const t=ze();return Mt(t,"stream/onStreamStropped","video-streaming.didStop",(t=>{Ln(t),e(t.videoStreamings[0])}))},Qf=e=>{const t=ze();return Mt(t,"stream/onStreamRecorded","video-streaming.didRecord",(t=>{Ln(t),e(t.videoStreamings[0])}))},Vf=e=>{const t=ze();return Mt(t,"stream/onStreamFlagged","video-streaming.didFlag",(t=>{Ln(t),e(t.videoStreamings[0])}))},zf=e=>{const t=ze();return Mt(t,"stream/onStreamTerminated","video-streaming.didTerminate",(t=>{Ln(t),e(t.videoStreamings[0])}))},Hf=(e,t)=>Ui(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?dl.stream(e.data):n}))}),"streamId",Ff,[Qf,Kf,$f,Vf,zf,au]);Hf.locally=e=>{const t=ze();if(t.log("stream/getStreamById",e),!t.cache)return;const n=Ze(["stream","get",e]);return n?{data:dl.stream(n.data),cachedAt:n.cachedAt}:void 0};const Jf=async e=>{const t=ze();t.log("stream/queryStreams",e);const n=null!=e?e:{},{page:a,limit:r}=n,s=Kn(n,["page","limit"]),o=a?{token:a}:r?{limit:r}:void 0,{data:i}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},s),{options:o})}),{paging:c,results:l}=i,{videoStreamings:d}=l,u=t.cache&&Date.now();return t.cache&&Ln(l,{cachedAt:u}),{data:d,cachedAt:u,paging:c}};var Wf=Object.freeze({__proto__:null,createStream:async e=>{const t=ze();t.log("stream/createStream",e);const{data:n}=await t.http.post("/api/v3/video-streaming",e),a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a});const{videoStreamings:r}=n;return{data:dl.stream(r[0]),cachedAt:a}},updateStream:async(e,t)=>{const n=ze();n.log("stream/updateStream",e,t);const{data:a}=await n.http.put(`/api/v3/video-streaming/${e}`,t),r=n.cache&&Date.now();n.cache&&Ln(a,{cachedAt:r});const{videoStreamings:s}=a;return{data:dl.stream(s.find((t=>t.streamId===e))),cachedAt:r}},deleteStream:async e=>{const t=ze();t.log("stream/deleteStream",e);const n=await Ff(e),{data:a}=await t.http.delete(`/api/v3/video-streaming/${e}`),{success:r}=a,s=Object.assign(Object.assign({},n.data),{isDeleted:!0});return nt(["stream","get",e],s),r},disposeStream:async e=>{const t=ze();t.log("stream/disposeStream",e);const{data:n}=await t.http.delete(`/api/v3/video-streaming/${e}/streaming-url`),a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a});const{videoStreamings:r}=n;return{data:r.find((t=>t.streamId===e)),cachedAt:a}},editStream:async(e,t)=>{const n=ze();n.log("stream/updateStream",e,t);const{data:a}=await n.http.put(`/api/v3/video-streaming/${e}`,t),r=n.cache&&Date.now();n.cache&&Ln(a,{cachedAt:r});const{videoStreamings:s}=a;return{data:dl.stream(s.find((t=>t.streamId===e))),cachedAt:r}},onStreamStarted:Kf,onStreamStopped:$f,onStreamRecorded:Qf,onStreamFlagged:Vf,onStreamTerminated:zf,onStreamViewerBanned:au,onStreamViewerUnbanned:e=>{const t=ze();return Mt(t,"stream/onStreamViewerDidUnban","video-streaming.viewerDidUnban",(async t=>{var n;const{list:a}=t;await Promise.all(a.map((({streamId:e})=>Ff(e))));const r=null===(n=Ze(["stream","get",a[0].streamId]))||void 0===n?void 0:n.data;r&&e(r)}))},getStreamById:Hf,getStreams:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`getStreams(tmpid: ${s}) > listen`);const{limit:o}=e,i=Kn(e,["limit"]),c=null!=o?o:de,{policy:l=he}=null!=n?n:{},d=[],u=["streams","collection",e],h=t=>{let n=rt(t,"isDeleted",e.isDeleted);return n=n.sort("lastCreated"===e.sortBy?bt:yt),n},p=(e,n=!1)=>{var a,r;const s=null!==(a=e.data.map((e=>Ze(["stream","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==a?a:[];t({onNextPage:m,data:n?h(s):s,hasNextPage:!!(null===(r=e.params)||void 0===r?void 0:r.page),loading:e.loading,error:e.error})},f=e=>e=>{var t;const n=null===(t=Ze(u))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.streamId,...n.data])],et(u,n),p(n,!0))},m=(e=!1)=>{var t,n;const a=null===(t=Ze(u))||void 0===t?void 0:t.data,r=null!==(n=null==a?void 0:a.data)&&void 0!==n?n:[];if(!e&&r.length>0&&!(null==a?void 0:a.params.page))return;const s=xe(Jf,Object.assign(Object.assign({},i),{limit:e?c:void 0,page:e||null==a?void 0:a.params.page}));Ne(s,(({data:e,error:t,loading:n,paging:a})=>{const s={loading:n,error:t,params:{page:null==a?void 0:a.next},data:r};e&&(s.data=[...new Set([...r,...e.map(We("stream"))])]),et(u,s),p(s)}),qe(l))};return d.push(Qf(f()),Kf(f()),$f(f())),m(!0),()=>{a(`getStreams(tmpid: ${s}) > dispose`),d.forEach((e=>e()))}}});const Gf=async()=>{const e=ze();e.log("presence/getPresenceSetting");const{data:t}=await e.http.get("/api/v1/presence/settings");return et(["get","presenceSetting"],t),t};class Yf{constructor(e){this.isEnabled=!1,this.config={heartbeatInterval:3e4},this.roomId=e,this.initializeConfig().catch((e=>{console.error("Failed to initialize RoomPresenceSyncEngine config in constructor:",e)}))}async initializeConfig(){try{const e=await Yf.getPresenceSettingWithRetry();e?this.config={heartbeatInterval:60*(e.network.heartbeatInterval||5)*1e3}:this.config.heartbeatInterval=3e5}catch(e){console.error("Failed to initialize RoomPresenceSyncEngine config:",e),this.config.heartbeatInterval=3e5}}static async getPresenceSettingWithRetry(e=5){for(let t=0;t<e;t+=1)try{return await Gf()}catch(n){if(t>=e-1)return console.error(`Failed to get presence setting after ${e} attempts:`,n),null;const a=2e4+5e3*Math.random();console.warn(`Failed to get presence setting (attempt ${t+1}/${e}), retrying in ${Math.round(a/1e3)}s:`,n),await new Promise((e=>{setTimeout(e,a)}))}return null}start(){this.isEnabled||(this.isEnabled=!0,this.sendHeartbeat(),this.heartbeatTimer=setInterval((()=>{this.sendHeartbeat()}),this.config.heartbeatInterval))}stop(){this.isEnabled=!1,this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0)}async sendHeartbeat(){try{const e=ze();await e.http.post(`/api/v1/presence/rooms/${this.roomId}/heartbeat`)}catch(e){console.error(`Heartbeat failed for room ${this.roomId}:`,e)}}getRoomId(){return this.roomId}isActive(){return this.isEnabled}destroy(){this.stop()}onSessionDestroyed(){this.destroy()}onTokenExpired(){this.stop()}}const Xf=new Map,Zf=e=>{let t=Xf.get(e);return t||(t=new Yf(e),Xf.set(e,t)),t};var em=Object.freeze({__proto__:null,getRoomOnlineUsers:async e=>{var t,n,a;const r=ze();r.log("room/getWatchingUsers",{roomId:e});const{data:s}=await r.http.get(`/api/v1/presence/rooms/${e}/users`),o=null!==(t=null==s?void 0:s.viewers.map((e=>e.userId)))&&void 0!==t?t:[],i=[];for(let e=0;e<o.length;e+=100)i.push(o.slice(e,e+100));const c=await Promise.all(i.map((e=>ul(e)))),l=[];return c.forEach((e=>{e.data&&l.push(...e.data)})),{data:l,cachedAt:null!==(a=null===(n=c[0])||void 0===n?void 0:n.cachedAt)&&void 0!==a?a:Date.now()}},getRoomUserCount:async e=>{const t=ze();t.log("roomPresence/getRoomUserCount",{roomId:e});const{data:n}=await t.http.get(`/api/v1/presence/rooms/${e}/users/count`);return et(["get","watchingCount",e],n),n},startHeartbeat:e=>{Zf(e).start()},stopHeartbeat:e=>{Zf(e).stop(),(e=>{const t=Xf.get(e);t&&(t.destroy(),Xf.delete(e))})(e)}});const tm=async e=>{const t=ze();t.log("poll/getPoll",e);const{data:n}=await t.http.get(`/api/v3/polls/${e}`),a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a});const{polls:r}=n,s=r.find((t=>t.pollId===e));return{data:uc(s),cachedAt:a}};tm.locally=e=>{const t=ze();if(t.log("poll/getPoll",e),!t.cache)return;const n=Ze(["poll","get",e]);return n?{data:uc(n.data),cachedAt:n.cachedAt}:void 0};const nm=e=>{const t=ze();return Mt(t,"poll/onPollUpdated","poll.updated",(n=>{t.cache&&Ln(n),e(n.polls[0])}))},am=e=>{const t=ze();return Mt(t,"poll/onPollDeleted","poll.deleted",(n=>{t.cache&&Ln(n),e(n.polls[0])}))};var rm=Object.freeze({__proto__:null,createPoll:async e=>{const t=ze();t.log("post/createPoll",e);const{data:n}=await t.http.post("/api/v3/polls",e),a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a});const{polls:r}=n;return{data:uc(r[0]),cachedAt:a}},closePoll:async e=>{const t=ze();t.log("user/closePoll",e);const{data:n}=await t.http.put(`/api/v3/polls/${encodeURIComponent(e)}`,{status:"closed"}),a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a}),jt("poll.updated",n);const{polls:r}=n,s=r.find((t=>t.pollId===e));return{data:uc(s),cachedAt:a}},deletePoll:async e=>{const t=ze();t.log("poll/deletePoll",e);const n=await tm(e),{data:a}=await t.http.delete(`/api/v3/polls/${e}`),{success:r}=a,s=Object.assign(Object.assign({},n.data),{isDeleted:!0});return nt(["poll","get",e],s),jt("poll.deleted",{polls:[s],users:[]}),r},votePoll:async(e,t)=>{const n=ze();n.log("user/votePoll",e);const{data:a}=await n.http.post(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:t}),r=n.cache&&Date.now();n.cache&&Ln(a,{cachedAt:r});const{polls:s}=a,o=s.find((t=>t.pollId===e));return jt("poll.updated",a),{data:uc(o),cachedAt:r}},unvotePoll:async e=>{const t=ze();t.log("user/unvotePoll",e);const{data:n}=await t.http.put(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:[]}),a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a}),jt("poll.updated",n)},onPollUpdated:nm,onPollDeleted:am,getPoll:(e,t)=>Ui(e,t,"pollId",tm,[nm,am])});class sm{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((()=>{!async function({bufferCurrentUsage:e,getActiveStreams:t,updateUsage:n,dispose:a}){const r=e();if(r.length)try{const n=(new Date).toISOString(),s=await oc({timestamp:n,streams:r});if(!s||!s.signature)throw new Error("Signature is undefined");const o={signature:s.signature,nonceStr:s.nonceStr,timestamp:n,streams:r},i=ze();await i.http.post("/api/v3/user-event/video-streaming",o),t().length||e().length||a()}catch(e){return r.forEach((e=>n(e))),!1}}({bufferCurrentUsage:this.bufferCurrentUsage.bind(this),getActiveStreams:this.getActiveStreams.bind(this),updateUsage:this.updateUsage.bind(this),dispose:this.dispose.bind(this)})}),2e4)}}let om=null;class im{constructor(e,t,n){this._SDKUnsubscribers=[],this.player=e,this.resolution=t,this._startTime=null,this._usageCollector=om||(om=new sm,om),this._usageCollector.registerStream(e.id),this._sessionId=String(C.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(au((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 cm=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(!T.default.isSupported())throw new Error("This browswer does not support hls, unable to play stream");const{data:n}=await Ff(t),{watcherUrl:a,status:r,recordings:s=[],resolution:o}=n;if(!a.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 T.default;if(c.attachMedia(i),"recorded"!==r){let{url:e}=a.hls;e=e.replace("http:","https:"),c.loadSource(e)}else{const e=s.find((e=>!!e.mp4));if(!e||!e.mp4)throw new Error("No playable recording available");i.src=e.mp4.url}return new im(i,o,t).registerEvents(),i}});const lm=e=>{const t=(e=>{var t;const n=ze(),a=new Date,r=a.getTime()+31536e6,s=new Date(r).toISOString();let o=null===(t=Ze(["storyTarget","get",e.targetId]))||void 0===t?void 0:t.data;return o||(o={targetType:e.targetType,targetId:e.targetId,lastStoryExpiresAt:s,targetPublicId:e.targetId,targetUpdatedAt:a.toISOString()},Ln({storyTargets:[o]})),{stories:[Object.assign({createdAt:a.toISOString(),updatedAt:a.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(r).toISOString()},e)],categories:[],communityUsers:[],comments:[],files:[],users:[],communities:[]}})(e);return Ln(t),t},dm=({payload:e,formData:t,isVideo:n=!1},a)=>{if(t){const r=t.getAll("files")[0]||void 0;if(!r)return;const s=Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileId:void 0,fileData:r.uri})});return n&&(s.data.videoFileId={original:void 0}),a(lm(s))}return a(lm(Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileData:null})})))},um=async e=>{const t=ze();t.log("post/createStory",e);const n=await t.http.post("/api/v4/stories",e),a=op(n.data);t.cache&&Ln(a),et(["story-sync-state",e.targetId],"synced"),jt("local.story.created",a);const r=t.cache&&Date.now();return{data:a.stories.length>0?a.stories[0]:void 0,cachedAt:r}},hm=async({targetId:e,targetType:t})=>{var n,a;if(!Ze(["storyTarget","get",e])){let r={targetId:e,targetType:t};if("community"===t){const t=await Qu(e);r=Object.assign(Object.assign({},r),{targetPublicId:t.data.communityId,targetUpdatedAt:null!==(n=t.data.updatedAt)&&void 0!==n?n:(new Date).toISOString()})}if("user"===t){const t=await yl(e);r=Object.assign(Object.assign({},r),{targetPublicId:t.data.userPublicId,targetUpdatedAt:null!==(a=t.data.updatedAt)&&void 0!==a?a:(new Date).toISOString()})}et(["storyTarget","get",e],r)}},pm=e=>e?Ze(["story","get",e]):{data:void 0,cachedAt:void 0},fm=async(e,t=!1)=>{var n,a,r;const s=ze();let o;if(s.log("story/deleteStory",e),s.cache&&(o=pm(e),null==o?void 0:o.data)){const{data:s}=o;if(jt("local.story.deleted",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[Object.assign(Object.assign({},s),{isDeleted:!0})]}),"synced"!==s.syncState){t?at(["story","get",e]):et(["story","get",e],Object.assign(Object.assign({},o.data),{isDeleted:!0}));const a=null===(n=Xe(["story","get"]))||void 0===n?void 0:n.filter((e=>"synced"!==e.data.syncState&&e.data.targetId===s.targetId&&!0!==e.data.isDeleted));if(a&&a.length>0){const e=a.reduce(((e,t)=>{const n=new Date(t.data.expiresAt||0);return n>e?n:e}),new Date(0));et(["story-expire",o.data.targetId],e.toISOString())}else at(["story-expire",o.data.targetId]);return!0}const i=null===(a=Ze(["storyTarget","get",s.targetId]))||void 0===a?void 0:a.data,c=null===(r=Xe(["story","get"]))||void 0===r?void 0:r.filter((e=>"synced"===e.data.syncState&&e.data.targetId===s.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&&et(["storyTarget","get",s.targetId],Object.assign(Object.assign({},i),{lastStoryExpiresAt:l}))}return(await s.http.delete(`/api/v4/stories/${e}`,{params:{permanent:t}})).data.success},mm=e=>{const t=ze(),n=[Mt(t,"onStoryUpdated","story.updated",(async t=>{const n=op(t);Ln(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},gm=e=>{const t=ze(),n=[Mt(t,"onStoryUpdated","local.story.updated",(async t=>{Ln(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},ym=e=>{const t=ze(),n=[Mt(t,"onStoryReactionAdded","story.reactionAdded",(async t=>{const{reactions:n}=t,a=Kn(t,["reactions"]),r=op(a),s=rd("story.reactionAdded",Object.assign(Object.assign({},r),{reactions:n}));Ln(s),e(s.stories)}))];return()=>{n.forEach((e=>e()))}},vm=e=>{const t=ze(),n=[Mt(t,"onStoryReactionAdded","local.story.reactionAdded",(async t=>{Ln({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},bm=e=>{const t=ze(),n=[Mt(t,"onStoryReactionRemoved","story.reactionRemoved",(async t=>{const{reactions:n}=t,a=Kn(t,["reactions"]),r=op(a),s=rd("story.reactionRemoved",Object.assign(Object.assign({},r),{reactions:n}));Ln(s),e(s.stories)}))];return()=>{n.forEach((e=>e()))}},wm=e=>{const t=ze(),n=[Mt(t,"onStoryReactionRemoved","local.story.reactionRemoved",(async t=>{Ln({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},Im=e=>{e.forEach((e=>{const t=Ze(["story-expire",e.targetId]),n=new Date(e.expiresAt||0);n<new Date((null==t?void 0:t.data)||0)||et(["story-expire",e.targetId],n.toISOString())}))},Cm=e=>{e.forEach((e=>{et(["story-reference",e.storyId],e.referenceId)}))},Sm=async({targetType:e,targetId:t,options:n})=>{const a=ze();a.log("story/getActiveStoriesByTarget");const r=a.cache&&Date.now(),s=await a.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"}}}),o=op(s.data);return a.cache&&(Ln(o),Im(o.stories),Cm(o.stories)),{data:o.stories,cachedAt:r,paging:{next:void 0,previous:void 0}}},Om=e=>{const t=ze(),n=[Mt(t,"onStoryCreated","story.created",(async t=>{const n=op(t,!0);Ln(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Tm=e=>{const t=ze(),n=[Mt(t,"onStoryCreated","local.story.created",(async t=>{Ln(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},km=e=>{const t=ze(),n=[Mt(t,"onStoryDeleted","story.deleted",(async t=>{const n=op(t);Ln(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Am=e=>{const t=ze(),n=[Mt(t,"onStoryDeleted","local.story.deleted",(async t=>{Ln(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},_m=e=>{const t=ze();return Mt(t,"onStoryError","local.story.error",(async t=>{Ln(t),e(t.stories)}))},Em=e=>t=>e((e=>t(e[0]))),Rm=async e=>{const t=ze();t.log("story/getTargetsByTargetIds",e);const n=await t.http.get("/api/v4/stories/seen",{params:{targets:e}}),{data:a}=n;return t.cache&&Ln(n.data),{data:a.storyTargets,cachedAt:Date.now()}};class Pm extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.paginationController=a}saveToMainDB(e){const t=ze(),n=t.cache&&Date.now(),a=op(e);t.cache&&(Ln(a,{cachedAt:n}),Im(a.stories),Cm(a.stories))}getStoryReferenceIds(e){return(null==e?void 0:e.referenceId)?e.referenceId:e.storyId}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.stories.map(this.getStoryReferenceIds)});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(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=Ze(this.cacheKey))||void 0===t?void 0:t.data;if(!n)return;const a=e.map((({referenceId:e})=>e));n.data=[...new Set([...a,...n.data])],et(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Mm extends Ti{async getRequest(e){const{data:t}=await this.http.get("/api/v4/stories-by-targets",{params:Object.assign({},e)});return t}}class jm extends ki{constructor(e,t){const n=O.default(e),a=["story-target-ids","collection",n],r=new Mm(e);super(r,n,a,t),this.query=e,this.queryStreamController=new Pm(this.query,this.cacheKey,this.notifyChange.bind(this),r),this.paginationController=r,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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 a;const r=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!r)return;let s=r.data.map((e=>Ze(["story","get",e]))).filter(Boolean).map((e=>dl.story(e.data)));(this.shouldNotify(s)||"event"!==e)&&(s=this.applyFilter(s),this.callback({onNextPage:void 0,data:s,hasNextPage:!1,loading:t,error:n}))}applyFilter(e){var t,n;const a=e;return"asc"===((null===(n=null===(t=this.query)||void 0===t?void 0:t.options)||void 0===n?void 0:n.orderBy)||"desc")?a.sort(yt):a.sort(bt)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Om,action:"onCreate"},{fn:mm,action:"onUpdate"},{fn:km,action:"onDelete"},{fn:_m,action:"onError"}])}}const Um=(e,t)=>{var n,a;const r=null===(n=Ze(e))||void 0===n?void 0:n.data,s=null!==(a=null==r?void 0:r.data)&&void 0!==a?a:[];et(e,Object.assign(Object.assign({},r),{data:[...new Set([...s,...t])]}))};class Dm extends Ci{constructor(e,t,n,a,r){super(e,t),this.notifyChange=n,this.paginationController=a,this.preparePayload=r}saveToMainDB(e){const t=ze(),n=t.cache&&Date.now(),a=this.preparePayload(e);t.cache&&Ln(a,{cachedAt:n})}appendToQueryStream(e,t,n=!1){n?et(this.cacheKey,{data:e.storyTargets.map((({targetId:e})=>e))}):Um(this.cacheKey,e.storyTargets.map((({targetId:e})=>e)))}reactor(e){return t=>{"onCreate"===e&&"seen"!==this.query.seenState&&Um(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 xm extends wi{constructor(){super(...arguments),this.smartFilterState="unseen"}async getRequest(e,t){var n;const{limit:a=10,seenState:r="unseen"}=e,s=await this.createRequest({seenState:"smart"===r?this.smartFilterState:r,limit:a,token:t});if(null===(n=s.paging)||void 0===n?void 0:n.next)return s;if("smart"!==r)return s;if("seen"===this.smartFilterState)return s;this.smartFilterState="seen";const o=await this.createRequest({seenState:this.smartFilterState,limit:a});return c=o,{categories:(i=s).categories.concat(c.categories),communities:i.communities.concat(c.communities),communityUsers:i.communityUsers.concat(c.communityUsers),files:i.files.concat(c.files),storyTargets:i.storyTargets.concat(c.storyTargets),users:i.users.concat(c.users),paging:c.paging};var i,c}async createRequest(e){const{data:t}=await this.http.get("/api/v5/me/global-story-targets",{params:e});return n=t,a=e.seenState,Object.assign(Object.assign({},n),{storyTargets:n.storyTargets.map((e=>Object.assign(Object.assign({},e),{localFilter:a})))||[]});var n,a}}class qm extends ki{constructor(e,t){const n=O.default(e),a=["story-global-feed","collection",n],r=new xm(e);super(r,n,a,t),this.query=e,this.queryStreamController=new Dm(this.query,this.cacheKey,this.notifyChange.bind(this),r,(e=>{const t=Kn(mc(Object.assign(Object.assign({},e),{feeds:[]})),["feeds"]);return Object.assign(Object.assign({},e),t)})),this.paginationController=r,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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 a;const r=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!r)return;const s=r.data,o=Xe(["storyTarget"]);o&&(null==o?void 0:o.length)>0&&(null==o||o.forEach((({key:e})=>{r.data.includes(e[2])||s.push(e[2])})));let i=s.map((e=>Ze(["storyTarget","get",e]))).filter(Boolean).map((e=>dl.storyTarget(e.data)));(this.shouldNotify(i)||"event"!==e)&&(i=this.applyFilter(i).filter((({localSortingDate:e})=>!!e)).map((e=>Kn(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(vt);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(vt)||[],a=t.unseen.sort(vt)||[],r=t.seen.sort(vt)||[];return n.concat(a,r)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Om,action:"onCreate"},{fn:mm,action:"onUpdate"},{fn:km,action:"onDelete"},{fn:Tm,action:"onCreate"},{fn:gm,action:"onUpdate"},{fn:Am,action:"onDelete"},{fn:_m,action:"onError"}])}}var Nm=Object.freeze({__proto__:null,createImageStory:async(e,t,n,a={},r="fit",s=[])=>{if(!n.getAll("files").length)throw new Error("The formData object must have a `files` key.");let o={data:{text:"",fileId:void 0,fileData:null,imageDisplayMode:r},syncState:"syncing",referenceId:Mn(),dataType:"image",items:s,targetType:e,targetId:t,metadata:a};const i=new Date;et(["story-sync-state",t],"syncing"),et(["story-expire",t],new Date(i.setFullYear(i.getFullYear()+1))),dm({payload:o,formData:n},(e=>{jt("local.story.created",e)}));try{const{data:a}=await Nl(n);if(0===a.length)throw new Error("Failed to upload image");const{fileId:r}=a[0];o=Object.assign(Object.assign({},o),{data:Object.assign(Object.assign({},o.data),{fileId:r})}),hm({targetId:t,targetType:e}),dm({payload:o,formData:n},(e=>{jt("local.story.created",e)}));const s=await um(o);return s.data?Object.assign(Object.assign({},s),{data:dl.story(s.data)}):s}catch(e){throw et(["story-sync-state",t],"error"),dm({payload:Object.assign(Object.assign({},o),{syncState:"error"}),formData:n},(e=>{jt("local.story.error",e)})),e}},createVideoStory:async(e,t,n,a={},r=[])=>{if(!n.getAll("files").length)throw new Error("The formData object must have a `files` key.");let s={data:{text:"",fileId:void 0,fileData:null},syncState:"syncing",referenceId:Mn(),dataType:"video",items:r,targetType:e,targetId:t,metadata:a};const o=new Date;et(["story-sync-state",t],"syncing"),et(["story-expire",t],new Date(o.setFullYear(o.getFullYear()+1))),hm({targetId:t,targetType:e}),dm({payload:s,formData:n,isVideo:!0},(e=>{jt("local.story.created",e)}));try{const{data:e}=await ql(n,x.STORY);if(0===e.length)throw new Error("Failed to upload video");const{fileId:t}=e[0];s=Object.assign(Object.assign({},s),{data:Object.assign(Object.assign({},s.data),{fileId:t,videoFileId:{original:t}})}),dm({payload:s,formData:n,isVideo:!0},(e=>{jt("local.story.created",e)}));const a=await um(s);return a.data?Object.assign(Object.assign({},a),{data:dl.story(a.data)}):a}catch(e){throw et(["story-sync-state",t],"error"),dm({payload:Object.assign(Object.assign({},s),{syncState:"error"}),formData:n,isVideo:!0},(e=>{jt("local.story.error",e)})),e}},hardDeleteStory:async e=>await fm(e,!0),softDeleteStory:async e=>await fm(e),getActiveStoriesByTarget:(e,t)=>{const{log:n,cache:a}=ze(),r=[],s=["story-target","collection",e],o=Date.now();n(`getActiveStoriesByTarget(tmpid: ${o}) > listen`),a||console.log(pe);const i=t=>{var n,a;const r=(null===(n=e.options)||void 0===n?void 0:n.sortBy)||"createdAt",s=(null===(a=e.options)||void 0===a?void 0:a.orderBy)||"desc";return 0===t.length?[]:"createdAt"===r?"asc"===s?t.sort(yt):t.sort(bt):"asc"===s?t.sort(wt):t.sort(It)},c=e=>{var n;const a=e.data.map((e=>{const t=pm(e);if(null==t?void 0:t.data)return dl.story(t.data)})).filter(Boolean).filter((e=>!!e&&!e.isDeleted)),r=[];if(a.length>0){const e=a.reduce(((e,t)=>{if(!t)return e;const{syncState:n}=t;if(!n)return e;let a=e.get(n);return a||(a=[]),a.push(t),e.set(n,a),e}),new Map);if(e.has("error")){const t=i(e.get("error")||[]);r.push(...t)}if(e.has("syncing")){const t=i(e.get("syncing")||[]);r.push(...t)}if(e.has("synced")){const t=i(e.get("synced")||[]);r.push(...t)}}t({onNextPage:()=>!1,data:r||a,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading||!1})},l=(t,n,a=!1,r=!1,o=!1)=>{var i;const l=Ze(s),d={loading:r,error:o,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=a?t.map(We("story")):[...new Set([...d.data,...t.map(We("story"))])];const u=null===(i=Xe(["story","get"]))||void 0===i?void 0:i.filter((t=>t.data.targetId===e.targetId&&"synced"!==t.data.syncState)).map((e=>We("story")(e.data)));u&&(null==u?void 0:u.length)>0&&u.forEach((e=>{d.data.includes(e)||d.data.push(e)})),et(s,d.data),c(d)},d=e=>t=>{l(t,e)};return(t=>{const n=xe(Sm,e);Ne(n,(({data:e,error:n,loading:a})=>{l(e,"fetch",t,a,n)}))})(!0),r.push(Om(d("onCreate")),mm(d("onUpdate")),km(d("onDelete")),ym(d("onReactionAdded")),bm(d("onReactionRemoved")),_m(d("onError")),Tm(d("onCreate")),gm(d("onUpdate")),Am(d("onDelete")),vm(d("onReactionAdded")),wm(d("onReactionRemoved")),(e=>{const t=ze();return Mt(t,"onStoryLocalDataUpdated","local.story.reload",(t=>{e(t)}))})((e=>{const t=Ze(s);if(!t)return;if(0===e.referenceIds.length||0===(null==t?void 0:t.data.length))return;if(!(null==t?void 0:t.data.find((t=>e.referenceIds.includes(t)))))return;const n={loading:!1,error:!1,params:{page:void 0},data:(null==t?void 0:t.data)||[]};c(n)})),(()=>at(s))),()=>{n(`getActiveStoriesByTarget(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getStoryByStoryId:(e,t)=>Ui(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:dl.story(e.data)})):t(e)}),"storyId",ip,[Em(mm),Em(km),Em(ym),Em(bm),Em(_m),Em(gm),Em(Am),Em(vm),Em(wm)]),getTargetById:(e,t)=>Ui(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:dl.storyTarget(e.data[0])})):t(e)}),"query",(e=>Rm([e])),[]),getTargetsByTargetIds:(e,t)=>{const{log:n,cache:a}=ze(),r=[],s=["storyTargets","collection",e],o=Date.now();n(`getTargetsByTargetIds(tmpid: ${o}) > listen`),a||console.log(pe);const i=(e,n=!1,a=!1,r=!1)=>{const o=Ze(s),i={loading:a,error:r,params:{page:void 0},data:[]};e&&(i.data=n?e.map(We("storyTarget")):[...new Set([...(null==o?void 0:o.data)||[],...e.map(We("storyTarget"))])]),et(s,i.data),(e=>{var n;const a=e.data.map((e=>{const t=Ze(["storyTarget","get",e]);if(null==t?void 0:t.data)return dl.storyTarget(t.data)})).filter(Boolean);t({onNextPage:void 0,data:a,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading||!1})})(i)};return(t=>{const n=xe(Rm,e);Ne(n,(({data:e,error:n,loading:a})=>{i(e,t,a,n)}))})(!0),r.push((()=>at(s))),()=>{n(`getTargetsByTargetIds(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getStoriesByTargetIds:(e,t,n)=>{const{log:a,cache:r,userId:s}=ze();r||console.log(pe);const o=Date.now();a(`getStoriesByTargetIds(tmpid: ${o}) > listen`);const i=new jm(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{at(l)})),()=>{a(`getStoriesByTargetIds(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}},getGlobalStoryTargets:(e,t,n)=>{const{log:a,cache:r,userId:s}=ze();r||console.log(pe);const o=Date.now();a(`getGlobalStoryTarget(tmpid: ${o}) > listen`);const i=new qm(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{at(l)})),()=>{a(`getGlobalStoryTarget(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}}});const Bm=e=>Object.assign(Object.assign({},e),{endAt:e.endAt?e.endAt:null}),Lm=e=>Object.assign({},e);var Fm=Object.freeze({__proto__:null,getNetworkAds:async()=>{const e=ze(),{data:t}=await e.http.get("/api/v1/ads/me"),n=t.ads.map(Bm),a=t.advertisers.map(Lm);return Ln({ads:n,advertisers:a,files:t.files}),et(["ad","setting"],t.settings),{ads:n.map(dl.ad),settings:t.settings}}});const Km=async()=>{const e=ze();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];et(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}};Km.locally=()=>{var e;const t=ze();if(t.log("notificationTray/getNotificationTraySeen.locally",{}),!t.cache)return;const{data:n,cachedAt:a}=null!==(e=Ze(["notificationTraySeen","get"]))&&void 0!==e?e:{};return n?{data:n,cachedAt:a}:void 0};const $m=e=>{const t=ze(),n=[Mt(t,"onNotificationTraySeenUpdated","local.notificationTraySeen.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class Qm extends wi{async getRequest(e,t){const{limit:n=de}=e,a=Kn(e,["limit"]),r=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v1/notification-tray",{params:Object.assign(Object.assign({},a),{options:r})});return s}}class Vm extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.notificationTrayItems.map(We("notificationTrayItem"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.notificationTrayItems.map(We("notificationTrayItem"))])]}))}}}const zm=e=>{const t=e.users.map(ga);return Object.assign(Object.assign({},e),{users:t})};class Hm extends ki{constructor(e,t){const n=O.default(e),a=["notificationTrayItem","collection",n];super(new Qm(e),n,a,t),this.query=e,this.queryStreamController=new Vm(this.query,this.cacheKey,this.notifyChange.bind(this),zm),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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 a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=(null!==(r=s.data.map((e=>Ze(["notificationTrayItem","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.notificationTray);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var Jm=Object.freeze({__proto__:null,getNotificationTraySeen:e=>{const{userId:t}=kt();return Ui(t,e,"userId",Km,[$m],{callbackDataSelector:e=>{let t=!0;return(null==e?void 0:e.lastTrayOccurredAt)&&(t=!!e.lastTraySeenAt&&Wn(e.lastTraySeenAt)>Wn(e.lastTrayOccurredAt)),{lastTrayOccurredAt:null==e?void 0:e.lastTrayOccurredAt,lastTraySeenAt:null==e?void 0:e.lastTraySeenAt,isSeen:t}}})},getNotificationTrayItems:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`getNotificationTrayItems(tmpid: ${s}) > listen`);const o=new Hm(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getNotificationTrayItems(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},markItemsSeen:async e=>{const t=ze();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})))}),a=n.trayItems.map((e=>{var n;const a=null===(n=Ze(["notificationTrayItem","get",e.id]))||void 0===n?void 0:n.data;if(!a)return;const r=Object.assign(Object.assign({},a),{lastSeenAt:e.lastSeenAt});if(t.cache){const e=Date.now();et(["notificationTrayItem","get"],r,{cachedAt:e})}return r})).filter(Boolean);jt("local.notificationTrayItem.updated",{notificationTrayItems:a})},markTraySeen:async e=>{var t;const n=ze();n.log("notificationTray/markTraySeen",{});const{data:a}=await n.http.post("api/v1/notification-tray/tray/seen",{lastSeenAt:e}),r=null===(t=Ze(["notificationTraySeen","get"]))||void 0===t?void 0:t.data,s={userId:n.userId,lastTraySeenAt:a.lastSeenAt},o=Object.assign(Object.assign({},r),s),i=n.cache&&Date.now();return n.cache&&et(["notificationTraySeen","get",n.userId],o,{cachedAt:i}),jt("local.notificationTraySeen.updated",s),{data:a,cachedAt:i}},onNotificationTraySeenUpdated:$m});class Wm extends wi{async getRequest(e,t){const{limit:n=de}=e,a=Kn(e,["limit"]),r=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v1/invitations/me",{params:Object.assign(Object.assign({},a),{options:r})}),o=s.invitations.filter((e=>"community"===e.targetType&&!!e.communityId)).map((e=>e.communityId));return(null==o?void 0:o.length)>0&&await $u(o),s}}class Gm extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.invitations.map(We("invitation"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(We("invitation"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===_c.OnLocalInvitationUpdated){if(!a.data.find((e=>e===t[0].invitationId)))return}if(e===_c.OnLocalInvitationCreated){const e=ze(),n=t.filter((t=>t.invitedUserId===e.userId));a.data=[...new Set([...n.map((e=>e.invitationId)),...a.data])]}e===_c.OnLocalInvitationCanceled&&(a.data=a.data.filter((e=>e!==t[0].invitationId))),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Ym extends ki{constructor(e,t){const n=O.default(e),a=["invitation","collection",n];super(new Wm(e),n,a,t),this.query=e,this.queryStreamController=new Gm(this.query,this.cacheKey,this.notifyChange.bind(this),Wi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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:Pc,action:_c.OnLocalInvitationCreated},{fn:Mc,action:_c.OnLocalInvitationUpdated},{fn:jc,action:_c.OnLocalInvitationCanceled}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(null!==(r=s.data.map((e=>Ze(["invitation","get",e]))).filter(Ai).map((({data:e})=>Gi(e))))&&void 0!==r?r:[]);(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.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?yt:bt)();return t=t.sort(n),t}}var Xm=Object.freeze({__proto__:null,cancelInvitation:async e=>{var t;const n=ze();n.log("invitation/cancelInvitation",e);const{data:a}=await n.http.delete(`/api/v1/invitations/${e}`),r=null===(t=Ze(["invitation","get",e]))||void 0===t?void 0:t.data;return Fn("invitation",e),r&&jt("local.invitation.canceled",[r]),a.success},onLocalInvitationCreated:Pc,onLocalInvitationUpdated:Mc,onLocalInvitationCanceled:jc,getMyCommunityInvitations:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`getMyCommunityInvitations: (tmpid: ${s}) > listen`);const o=new Ym(Object.assign(Object.assign({},e),{targetType:"community",statuses:["pending"]}),t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{at(c)})),()=>{a(`getInvitations (tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getInvitations:(e,t)=>{const{_id:n}=Nt();if(!n)throw new Le("The _id has not been defined in ActiveUser",8e5,"error");const{log:a}=ze(),{targetId:r,targetType:s}=e,o=Date.now();a(`observeInvitations(tmpid: ${o}) > listen for ${s}: ${r}`);const i=[],c=n=>{const a=(Array.isArray(n)?n:[n]).filter((({targetId:t,targetType:n})=>t===e.targetId&&n===e.targetType));(e=>{t(e.map(dl.invitation))})(a)};return"room"===s&&(i.push(yf(c)),i.push(bf(c)),i.push(wf(c)),i.push(If(c))),()=>{a(`getInvitations(tmpid: ${o}) > dispose for ${s}: ${r}`),i.forEach((e=>e()))}}});const Zm=e=>{const t=ze();return Mt(t,"live_reaction/onLiveReactionCreated","liveReaction.created",(n=>{if(n.reactions.length>0){const a=n.reactions.filter((({userId:e})=>e!==t.userId));e(a)}}))};var eg=Object.freeze({__proto__:null,createReaction:async({referenceId:e,referenceType:t,reactionName:n,streamId:a,roomId:r})=>{const s=ze();if(s.log("live_reaction/createReaction",{referenceId:e,referenceType:t,reactionName:n,streamId:a,roomId:r}),!a&&!r)throw new Le("You have to specify either streamId or roomId",800110,"error");const o=Ds(),i={reactionName:n,referencePublicId:e,referenceType:t,roomId:r,streamId:a,occurredAt:(new Date).toISOString()};return o.createLiveReaction(i),jt("local.liveReaction.created",[Object.assign(Object.assign({},i),{userId:s.userId,referenceId:e})]),!0},onLiveReactionCreated:Zm,getReactions:(e,t)=>{const{_id:n}=kt();if(!n)throw new Le("The _id has not been defined in ActiveUser",8e5,"error");const{log:a}=ze();a(`getReactions(tmpid: ${Date.now()}) > listen`);const r=[],s=n=>{(e=>{t(e)})(n.filter((({referenceId:t})=>t===e)))};return r.push(Zm(s)),r.push((e=>{const t=ze();return Mt(t,"live_reaction/onLiveReactionCreated","local.liveReaction.created",e)})(s)),()=>{r.forEach((e=>e()))}}});const tg=async e=>{const t=ze();t.log("event/getEvent",e);try{const{data:n}=await t.http.get(`/api/v1/events/${e}`),a=Qc(n),r=t.cache&&Date.now();return t.cache&&Ln(a,{cachedAt:r}),{data:a.events.find((t=>t.eventId===e)),cachedAt:r}}catch(n){if(Oe(null==n?void 0:n.code)){const a=tg.locally(e);if(!a)throw n;const r=Object.assign(Object.assign({},null==a?void 0:a.data),{isDeleted:!0});nt(["event","get",e],r);return{data:r,cachedAt:t.cache&&Date.now()}}throw n}};tg.locally=e=>{const t=ze();if(t.log("event/getEvent.locally",e),!t.cache)return;const n=Ze(["event","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class ng extends wi{async getRequest(e,t){const{limit:n=de}=e,a=Kn(e,["limit"]),r=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v1/events",{params:Object.assign(Object.assign({},a),{options:r})});return s}}class ag extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.events.map(We("event"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.events.map(We("event"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===Jc.OnEventCreated&&(a.data=[...new Set([t.eventId,...a.data])]),e===Jc.OnEventDeleted&&(a.data=a.data.filter((e=>e!==t.eventId))),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class rg extends ki{constructor(e,t){const n=O.default(e),a=["event","collection",n];super(new ng(e),n,a,t),this.query=e,this.queryStreamController=new ag(this.query,this.cacheKey,this.notifyChange.bind(this),Qc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Yc,action:Jc.OnEventCreated},{fn:Xc,action:Jc.OnEventUpdated},{fn:Zc,action:Jc.OnEventDeleted},{fn:el,action:Jc.OnEventCreated},{fn:tl,action:Jc.OnEventUpdated},{fn:nl,action:Jc.OnEventDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=(null!==(r=s.data.map((e=>Ze(["event","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.event);(this.shouldNotify(o)||"event"!==e)&&this.callback({data:o,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}class sg extends wi{async getRequest(e,t){const{limit:n=de}=e,a=Kn(e,["limit"]),r=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v1/events/me/rsvps",{params:Object.assign(Object.assign({},a),{options:r})});return s}}class og extends Ci{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=ze(),a=n.cache&&Date.now();n.cache&&Ln(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.events.map(We("event"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.events.map(We("event"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=Ze(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===Jc.OnEventCreated){if(ze().userId!==t.userId)return;a.data=[...new Set([t.eventId,...a.data])]}e===Jc.OnEventDeleted&&(a.data=a.data.filter((e=>e!==t.eventId))),et(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class ig extends ki{constructor(e,t){const n=O.default(e),a=["event","collection",n];super(new sg(e),n,a,t),this.query=e,this.queryStreamController=new og(this.query,this.cacheKey,this.notifyChange.bind(this),Qc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Yc,action:Jc.OnEventCreated},{fn:Xc,action:Jc.OnEventUpdated},{fn:Zc,action:Jc.OnEventDeleted},{fn:el,action:Jc.OnEventCreated},{fn:tl,action:Jc.OnEventUpdated},{fn:nl,action:Jc.OnEventDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=(null!==(r=s.data.map((e=>Ze(["event","get",e]))).filter(Ai).map((({data:e})=>e)))&&void 0!==r?r:[]).map(dl.event);(this.shouldNotify(o)||"event"!==e)&&this.callback({data:o,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}var cg=Object.freeze({__proto__:null,createEvent:async e=>{const t=ze();t.log("event/createEvent",e);const{data:n}=await t.http.post("/api/v1/events",e);jt("local.event.created",n);const a=Qc(n),r=t.cache&&Date.now();return t.cache&&Ln(a,{cachedAt:r}),{data:ll(a.events[0]),cachedAt:r}},updateEvent:async(e,t)=>{const n=ze();n.log("event/updateEvent",e,t);const{data:a}=await n.http.put(`/api/v1/events/${e}`,t);jt("local.event.updated",a);const r=Qc(a),s=n.cache&&Date.now();return n.cache&&Ln(r,{cachedAt:s}),{data:ll(r.events.find((t=>t.eventId===e))),cachedAt:s}},deleteEvent:async e=>{const t=ze();t.log("event/deleteEvent",e);const n=await tg(e);await t.http.delete(`/api/v1/events/${e}`);const a=Object.assign(Object.assign({},n.data),{isDeleted:!0});nt(["event","get",e],a),jt("local.event.deleted",{users:[],files:[],communities:[],posts:[],rooms:[],events:[a]})},onEventCreated:Yc,onEventUpdated:Xc,onEventDeleted:Zc,onLocalEventCreated:el,onLocalEventUpdated:tl,onLocalEventDeleted:nl,onRSVPCreated:al,onRSVPUpdated:rl,onLocalRSVPCreated:sl,onLocalRSVPUpdated:ol,getEvent:(e,t)=>Ui(e,t,"eventId",tg,[Xc,Zc,tl,nl],{callbackDataSelector:e=>e?ll(e):e}),getEvents:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`getEvents: (tmpid: ${s}) > listen`);const o=new rg(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getEvents (tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getMyEvents:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`getMyEvents: (tmpid: ${s}) > listen`);const o=new ig(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`getMyEvents (tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getRSVPs:cl});const lg=async e=>{const t=ze();let n;t.log("product/getProduct",e),ta("product",e);try{n=(await t.http.get(`/api/v1/products/${encodeURIComponent(e)}`)).data}catch(t){throw Oe(null==t?void 0:t.code)&&Fn("product",e),t}const a=t.cache&&Date.now();t.cache&&Ln(n,{cachedAt:a});const{products:r}=n;return{data:r.find((t=>t.productId===e)),cachedAt:a}};lg.locally=e=>{const t=ze();if(t.log("product/getProduct.locally",e),!t.cache)return;const n=Ze(["product","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class dg extends wi{async getRequest(e,t){const{limit:n=de}=e,a=Kn(e,["limit"]),r=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v1/products/search",{params:Object.assign(Object.assign({},a),{options:r})});return s}}class ug extends Ci{constructor(e,t,n){super(e,t),this.notifyChange=n}saveToMainDB(e){const t=ze(),n=t.cache&&Date.now();t.cache&&Ln(e,{cachedAt:n})}appendToQueryStream(e,t,n=!1){var a,r;if(n)et(this.cacheKey,{data:e.products.map(We("product"))});else{const t=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(r=null==t?void 0:t.data)&&void 0!==r?r:[];et(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.products.map(We("product"))])]}))}}}class hg extends ki{constructor(e,t){const n=O.default(e),a=["products","collection",n];super(new dg(e),n,a,t),this.query=e,this.queryStreamController=new ug(this.query,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ze(this.cacheKey))||void 0===e?void 0:e.data)||et(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 a,r;const s=null===(a=Ze(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=null!==(r=s.data.map((e=>Ze(["product","get",e]))).filter(Ai).map((({data:e})=>e)).map(dl.product))&&void 0!==r?r:[];(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var pg=Object.freeze({__proto__:null,getProduct:(e,t)=>Ui(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?dl.product(n):n}))}),"productId",lg,[]),searchProducts:(e,t,n)=>{const{log:a,cache:r}=ze();r||console.log(pe);const s=Date.now();a(`searchProducts(tmpid: ${s}) > listen`);const o=new hg(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>at(c))),()=>{a(`searchProducts(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}}});return e.API_REGIONS=tn,e.AdRepository=Fm,e.AmityAttachmentProductTags=class{constructor(){this.map=new Map}get(e){return this.map.get(e)||[]}set(e,t){this.map.set(e,t)}},e.CategoryRepository=Zh,e.ChannelRepository=Fu,e.Client=ai,e.CommentRepository=vp,e.CommunityPostSettingMaps=j,e.CommunityPostSettings=M,e.CommunityRepository=Gh,e.ContentFeedType=x,e.DefaultCommunityPostSetting=U,e.EventRepository=cg,e.FeedRepository=Qp,e.FileRepository=Bl,e.FileType=k,e.GET_WATCHER_URLS=Li,e.InvitationRepository=Xm,e.LiveReactionRepository=eg,e.LiveStreamPlayer=cm,e.MessageContentType=N,e.MessageRepository=du,e.PollRepository=rm,e.PostContentType=B,e.PostRepository=Lf,e.PostStructureType=L,e.ProductRepository=pg,e.ReactionRepository=jd,e.RoomPresenceRepository=em,e.RoomRepository=Df,e.StoryRepository=Nm,e.StreamRepository=Wf,e.SubChannelRepository=yu,e.UserRepository=Dl,e.VERSION=le,e.VideoResolution=A,e.VideoSize=E,e.VideoTranscodingStatus=_,e.backupCache=async(e="amitySdk",t=(e=>e.offline))=>{const{log:n,cache:a,userId:r}=ze();if(!a)return!1;n("cache/api/backupCache",{storageKey:e});const s=Object.fromEntries(Object.entries(a.data).filter((([e,n])=>t(n))));return!!Object.keys(s).length&&(localStorage&&await localStorage.setItem(`${e}#${r}`,JSON.stringify(s)),!0)},e.createQuery=xe,e.createReport=async(e,t)=>{const n=ze();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 Zr(n);Ln(e)}return jt("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 pa(n);Ln(e)}return jt("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 Gl(n);Ln(e)}return jt("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 Ud(n);Ln(e)}return jt("comment.flagged",n),!!n})({client:n,referenceId:t})},e.createUserToken=async(e,t,n)=>{const a=await Un(),r=Dn(),s=hn(an("http",t)),{data:o}=await s.post("/api/v5/sessions",Object.assign(Object.assign({},n),{deviceId:a,deviceInfo:Object.assign(Object.assign({},r),{model:"token management API on TS-SDK"})}),{headers:{"X-API-Key":e}});return{accessToken:o.accessToken}},e.deleteReport=async(e,t)=>{const n=ze();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 Zr(n);Ln(e)}return jt("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 pa(n);Ln(e)}return jt("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 Gl(n);Ln(e)}return jt("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 Ud(n);Ln(e)}return jt("comment.unflagged",n),!!n})({client:n,referenceId:t})},e.disableCache=()=>{const e=ze();e.cache&&(e.log("cache/api/disableCache"),delete e.cache)},e.dropFromCache=at,e.enableCache=(e={},t)=>{const n=ze();n.cache||(n.log("cache/api/enableCache"),n.cache={data:e,persistIf:t})},e.exceedsUntilAtBoundary=Ot,e.filterByChannelMembership=it,e.filterByCommunityMembership=lt,e.filterByFeedType=ct,e.filterByPostDataTypes=dt,e.filterByPropEquality=rt,e.filterByPropInclusion=(e,t,n)=>void 0!==n?e.filter((e=>n.includes(e[t]))):e,e.filterByPropIntersection=ot,e.filterBySearchTerm=ut,e.filterByStringComparePartially=st,e.filterByUntilAt=(e,t,n)=>{const a=new Date(t).valueOf();return"firstCreated"===n?e.filter((e=>new Date(e.createdAt).valueOf()<a)):e.filter((e=>new Date(e.createdAt).valueOf()>a))},e.filterCommentsByBlockUsers=ft,e.filterPostsByBlockUsers=pt,e.getBlockUsersId=ht,e.getChannelTopic=e=>`${e.path}/#`,e.getCommentTopic=({path:e})=>e,e.getCommunityStoriesTopic=({targetId:e,targetType:t})=>{const n=kt();return`${Ft(n)}/social/${t}/${e}/story/#`},e.getCommunityTopic=({path:t},n=e.SubscriptionLevels.COMMUNITY)=>Lt(t,n),e.getLiveReactionTopic=e=>`${e.path}/liveReaction`,e.getLiveStreamTopic=Wt,e.getMarkedMessageTopic=Qt,e.getMarkerUserFeedTopic=()=>{const e=kt();return`${Ft(e)}/marker/user/${e._id}`},e.getMessageTopic=e=>e.path,e.getMyFollowersTopic=Kt,e.getMyFollowingsTopic=$t,e.getNetworkId=Ft,e.getNetworkTopic=Vt,e.getPostTopic=({path:t},n=e.SubscriptionLevels.POST)=>"comment"===n?`${t}/comment/+`:t,e.getRole=Fl,e.getRoomStreamerTopic=e=>{const t=Nt();return`${Ft(t)}/room/${e.roomId}/streamer`},e.getRoomWatcherTopic=e=>{const t=Nt();return`${Ft(t)}/room/${e._id}`},e.getSmartFeedChannelTopic=zt,e.getSmartFeedMessageTopic=Jt,e.getSmartFeedSubChannelTopic=Ht,e.getStoryTopic=({targetId:e,targetType:t,storyId:n})=>{const a=kt();return`${Ft(a)}/social/${t}/${e}/story/${n}/#`},e.getSubChannelTopic=e=>`${e.path}/#`,e.getUserTopic=({path:t},n=e.SubscriptionLevels.USER)=>Lt(n===e.SubscriptionLevels.USER?t:t.replace(/^(\w*)/,"$1/social"),n),e.isAfterBefore=ke,e.isAfterBeforeRaw=Ae,e.isCachable=Ue,e.isFetcher=Pe,e.isFresh=De,e.isLocal=e=>Ue(e)&&-1===(null==e?void 0:e.cachedAt),e.isMutator=Me,e.isOffline=je,e.isPaged=_e,e.isReportedByMe=async(e,t)=>{const n=ze();return n.log("report/isReportedByMe",{referenceType:e,referenceId:t}),"user"===e?(async({client:e,referenceId:t})=>{var n;const{data:a}=await e.http.get(`/api/v3/users/${t}/isflagbyme`),{result:r,isFlagByMe:s}=null!=a?a:{};return null!==(n=null!=r?r:s)&&void 0!==n&&n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{var n;const{data:a}=await e.http.get(`/api/v5/messages/${encodeURIComponent(t)}/flags`),{result:r,isFlagByMe:s}=null!=a?a:{};return null!==(n=null!=r?r:s)&&void 0!==n&&n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{var n;const{data:a}=await e.http.get(`/api/v3/posts/${t}/isflagbyme`),{result:r,isFlagByMe:s}=null!=a?a:{};return null!==(n=null!=r?r:s)&&void 0!==n&&n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{var n;const{data:a}=await e.http.get(`/api/v3/comments/${t}/isflagbyme`),{result:r,isFlagByMe:s}=null!=a?a:{};return null!==(n=null!=r?r:s)&&void 0!==n&&n})({client:n,referenceId:t})},e.isSkip=Te,e.mergeInCache=tt,e.notificationTray=Jm,e.onChannelMarkerFetched=Jo,e.onFeedMarkerFetched=e=>{const t=ze();return Mt(t,"feedMarker/onFeedMarkerFetched","local.feedMarker.fetched",(t=>{e(t.feedMarkers[0])}))},e.onFeedMarkerUpdated=e=>{const t=ze();return Mt(t,"feedMarker/onFeedMarkerUpdated","marker.feed-updated",(t=>{Ln(t),e(t.feedMarkers[0])}))},e.onMessageMarked=Zo,e.onMessageMarkerFetched=Xo,e.onSubChannelMarkerFetched=Wo,e.onSubChannelMarkerUpdated=Go,e.onUserMarkerFetched=Yo,e.onUserMarkerFetchedLegacy=e=>{const t=ze();return Mt(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers[0])}))},e.pullFromCache=Ze,e.pushToCache=et,e.queryCache=Xe,e.queryOptions=qe,e.queryRoles=Ll,e.restoreCache=async(e="amitySdk")=>{var t;const n=ze();if(!n.cache)return!1;n.log("cache/api/restoreCache",{storageKey:e});const a=localStorage&&null!==(t=await localStorage.getItem(`${e}#${n.userId}`))&&void 0!==t?t:"{}";let r={};try{r=JSON.parse(a)}catch(e){}return n.cache.data=Object.assign(Object.assign({},r),n.cache.data),!0},e.runQuery=Ne,e.sortByChannelSegment=({channelSegment:e},{channelSegment:t})=>e-t,e.sortByDisplayName=mt,e.sortByFirstCreated=yt,e.sortByFirstUpdated=wt,e.sortByLastActivity=Ct,e.sortByLastCreated=bt,e.sortByLastUpdated=It,e.sortByLocalSortingDate=vt,e.sortByName=gt,e.sortBySegmentNumber=({segmentNumber:e},{segmentNumber:t})=>e-t,e.subscribeTopic=Gt,e.toPage=Re,e.toPageRaw=e=>{if(!e)return;const n=JSON.parse(t.decode(e));return Ae(n)?n:void 0},e.toToken=Ee,e.upsertInCache=nt,e.validateUntilAt=St,e.wipeCache=async(e="amitySdk")=>{const{log:t,cache:n,userId:a}=ze();return!!n&&(t("cache/api/wipeCache",{storageKey:e}),n.data={},localStorage&&await localStorage.setItem(`${e}#${a}`,"{}"),!0)},Object.defineProperty(e,"__esModule",{value:!0}),e}({},jsBase64,mitt,debug,axios,HttpAgent,AsyncStorage,uuid$1,jwtDecode,reactNative,hash,Hls);
|