@amityco/ts-sdk-react-native 7.25.0 → 7.25.1-144f8feb.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -1 +1 @@
1
- var Amity=function(e,t,n,a,s,o,i,r,c,d,l,u,h){"use strict";function m(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var g,p,y,v,f,b=m(n),I=m(a),C=m(s),w=m(o),S=m(i),O=m(r),T=m(c),A=m(d),R=m(u),P=m(h);e.MembershipAcceptanceTypeEnum=void 0,(g=e.MembershipAcceptanceTypeEnum||(e.MembershipAcceptanceTypeEnum={})).AUTOMATIC="automatic",g.INVITATION="invitation",e.AmityAutoSubscription=void 0,(p=e.AmityAutoSubscription||(e.AmityAutoSubscription={})).CHAT="chat",p.NETWORK="network",p.LIVESTREAM="livestream",p.BLOCK="block",e.UserTypeEnum=void 0,(y=e.UserTypeEnum||(e.UserTypeEnum={})).SIGNED_IN="signed-in",y.VISITOR="visitor",y.BOT="bot",e.SearchUsersByEnum=void 0,(v=e.SearchUsersByEnum||(e.SearchUsersByEnum={})).DISPLAY_NAME="displayName",v.PROFILE_HANDLE="profileHandle",v.USER_ID="userId",e.UserReportTypeEnum=void 0,(f=e.UserReportTypeEnum||(e.UserReportTypeEnum={})).DISPLAY_NAME="displayName",f.DESCRIPTION="description",f.AVATAR="avatarFileId",f.BEHAVIOR="behavior";const D=Object.freeze({FILE:"file",IMAGE:"image",VIDEO:"video",CLIP:"clip",AUDIO:"audio"}),U=Object.freeze({"1080P":"1080p","720P":"720p","480P":"480p","360P":"360p",ORIGINAL:"original"}),k=Object.freeze({UPLOADED:"uploaded",TRANSCODING:"transcoding",TRANSCODED:"transcoded",TRANSCODE_FAILED:"transcodeFailed"}),j=Object.freeze({LOW:"low",MEDIUM:"medium",HIGH:"high",ORIGINAL:"original"});var E,M;e.FileAccessTypeEnum=void 0,(E=e.FileAccessTypeEnum||(e.FileAccessTypeEnum={})).PUBLIC="public",E.NETWORK="network",e.AmityChannelNotificationModeEnum=void 0,(M=e.AmityChannelNotificationModeEnum||(e.AmityChannelNotificationModeEnum={})).Default="default",M.Silent="silent",M.Subscribe="subscribe";const q=Object.freeze({ONLY_ADMIN_CAN_POST:"ONLY_ADMIN_CAN_POST",ADMIN_REVIEW_POST_REQUIRED:"ADMIN_REVIEW_POST_REQUIRED",ANYONE_CAN_POST:"ANYONE_CAN_POST"}),x=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}}),K="ONLY_ADMIN_CAN_POST";var N;e.AmityCommunityType=void 0,(N=e.AmityCommunityType||(e.AmityCommunityType={})).Default="default",N.Event="event";const F=Object.freeze({STORY:"story",CLIP:"clip",CHAT:"chat",POST:"post",MESSAGE:"message"});var _;e.ContentFlagReasonEnum=void 0,(_=e.ContentFlagReasonEnum||(e.ContentFlagReasonEnum={})).CommunityGuidelines="Against community guidelines",_.HarassmentOrBullying="Harassment or bullying",_.SelfHarmOrSuicide="Self-harm or suicide",_.ViolenceOrThreateningContent="Violence or threatening content",_.SellingRestrictedItems="Selling and promoting restricted items",_.SexualContentOrNudity="Sexual content or nudity",_.SpamOrScams="Spam or scams",_.FalseInformation="False information or misinformation",_.Others="Others";const B=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",AUDIO:"audio",CUSTOM:"custom"}),$=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 Q,J,V,H,z,G,Y,W,X,Z,ee,te,ne,ae,se,oe,ie,re,ce,de,le,ue;e.InvitationTypeEnum=void 0,(Q=e.InvitationTypeEnum||(e.InvitationTypeEnum={})).CommunityMemberInvite="communityMemberInvite",Q.LivestreamCohostInvite="livestreamCohostInvite",e.InvitationStatusEnum=void 0,(J=e.InvitationStatusEnum||(e.InvitationStatusEnum={})).Pending="pending",J.Approved="approved",J.Rejected="rejected",J.Cancelled="cancelled",e.InvitationSortByEnum=void 0,(V=e.InvitationSortByEnum||(e.InvitationSortByEnum={})).FirstCreated="firstCreated",V.LastCreated="lastCreated",e.InvitationTargetTypeEnum=void 0,(H=e.InvitationTargetTypeEnum||(e.InvitationTargetTypeEnum={})).Community="community",H.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,(G=e.JoinResultStatusEnum||(e.JoinResultStatusEnum={})).Success="success",G.Pending="pending",e.FeedDataTypeEnum=void 0,(Y=e.FeedDataTypeEnum||(e.FeedDataTypeEnum={})).Text="text",Y.Video="video",Y.Image="image",Y.File="file",Y.Audio="audio",Y.LiveStream="liveStream",Y.Clip="clip",Y.Poll="poll",Y.Room="room",e.FeedSortByEnum=void 0,(W=e.FeedSortByEnum||(e.FeedSortByEnum={})).LastCreated="lastCreated",W.FirstCreated="firstCreated",W.LastUpdated="lastUpdated",W.FirstUpdated="firstUpdated",e.FeedSourceEnum=void 0,(X=e.FeedSourceEnum||(e.FeedSourceEnum={})).Community="community",X.User="user",e.FeedTypeEnum=void 0,(Z=e.FeedTypeEnum||(e.FeedTypeEnum={})).Reviewing="reviewing",Z.Published="published",Z.Declined="declined",e.AmityEventType=void 0,(ee=e.AmityEventType||(e.AmityEventType={})).Virtual="virtual",ee.InPerson="in_person",e.AmityEventOriginType=void 0,(te=e.AmityEventOriginType||(e.AmityEventOriginType={})).Community="community",te.User="user",e.AmityEventStatus=void 0,(ne=e.AmityEventStatus||(e.AmityEventStatus={})).Scheduled="scheduled",ne.Live="live",ne.Ended="ended",ne.Cancelled="cancelled",e.AmityEventResponseStatus=void 0,(ae=e.AmityEventResponseStatus||(e.AmityEventResponseStatus={})).Going="going",ae.NotGoing="not_going",e.AmityEventSortOption=void 0,(se=e.AmityEventSortOption||(e.AmityEventSortOption={})).StartTime="startTime",se.CreatedAt="createdAt",e.AmityEventOrderOption=void 0,(oe=e.AmityEventOrderOption||(e.AmityEventOrderOption={})).Ascending="asc",oe.Descending="desc",e.AmitySharableContentType=void 0,(ie=e.AmitySharableContentType||(e.AmitySharableContentType={})).POST="post",ie.COMMUNITY="community",ie.USER="user",ie.LIVESTREAM="livestream",ie.EVENT="event",e.AnalyticsSourceTypeEnum=void 0,(re=e.AnalyticsSourceTypeEnum||(e.AnalyticsSourceTypeEnum={})).POST="post",re.ROOM="room",e.UserNotificationModuleNameEnum=void 0,(ce=e.UserNotificationModuleNameEnum||(e.UserNotificationModuleNameEnum={})).CHAT="chat",ce.SOCIAL="social",ce.VIDEO_STREAMING="video-streaming",e.CommunityNotificationEventNameEnum=void 0,(de=e.CommunityNotificationEventNameEnum||(e.CommunityNotificationEventNameEnum={})).POST_CREATED="post.created",de.POST_REACTED="post.reacted",de.COMMENT_CREATED="comment.created",de.COMMENT_REPLIED="comment.replied",de.COMMENT_REACTED="comment.reacted",de.STORY_CREATED="story.created",de.STORY_REACTED="story.reacted",de.STORY_COMMENT_CREATED="story-comment.created",de.LIVESTREAM_START="video-streaming.didStart",e.NotificationSettingsLevelEnum=void 0,(le=e.NotificationSettingsLevelEnum||(e.NotificationSettingsLevelEnum={})).USER="user",le.COMMUNITY="community",le.CHANNEL="channel",e.NotificationRolesFilterTypeEnum=void 0,(ue=e.NotificationRolesFilterTypeEnum||(e.NotificationRolesFilterTypeEnum={})).ALL="all",ue.ONLY="only";const he=function(){try{return"v7.25.0-umd"}catch(e){return"__dev__"}}(),me=5,ge=20,pe="cache_then_server",ye="For using Live Collection feature you need to enable Cache!",ve="Observing unsynced object is not supported by Live Object.",fe=-5,be=1e3,Ie=6e5,Ce="/api/v1/feeds/for-you",we="dead",Se=6e4,Oe=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})),Te=e=>JSON.parse(e),Ae=(e,t)=>e===t||!(!e||!t)&&("object"==typeof e&&Object.keys(e).every((n=>Ae(e[n],t[n])))),Re=e=>[400400,400300].includes(e),Pe=e=>["skip"].some((t=>t in e)),De=e=>["after","before","first","last","limit"].some((t=>t in e)),Ue=e=>"limit"in e,ke=e=>(null==e?void 0:e.hasOwnProperty("data"))&&(null==e?void 0:e.hasOwnProperty("nextPage"))&&(null==e?void 0:e.hasOwnProperty("prevPage")),je=(e,n)=>{var a;if(!e||!Object.keys(e).length)return;let s={};return"skiplimit"===n?s={skip:null!==(a=e.after)&&void 0!==a?a:0,limit:e.limit}:"afterbefore"===n&&De(e)?((null==e?void 0:e.before)&&(s=Object.assign(Object.assign({},s),{before:e.before})),(null==e?void 0:e.after)&&(s=Object.assign(Object.assign({},s),{after:e.after})),Number.isNaN(Number(null==e?void 0:e.limit))||(s=Object.assign(Object.assign({},s),{limit:e.limit}))):"afterbeforeraw"===n&&(s=e),Object.keys(s).length?t.encode(JSON.stringify(s)):void 0},Ee=e=>{if(!e)return;const n=JSON.parse(t.decode(e));if(Pe(n))return{after:n.skip,limit:n.limit};if(De(n)){if("before"in n)return{before:n.before,limit:n.last};if("after"in n)return{after:n.after,limit:n.first}}},Me=e=>"locally"in e,qe=e=>"optimistically"in e,xe=e=>Me(e)||qe(e),Ke=e=>null==e?void 0:e.hasOwnProperty("cachedAt"),Ne=(e,t=6e4)=>{var n;return Date.now()-(null!==(n=null==e?void 0:e.cachedAt)&&void 0!==n?n:0)<=t},Fe=(e,...t)=>({func:e,args:t}),_e=(e,t=6e4)=>"cache_only"===e?{lifeSpan:1/0}:{lifeSpan:t<Se?Se:t},Be=({func:e,args:t},n,a=_e("cache_then_server"))=>{let s;const{lifeSpan:o}=_e("cache_then_server",a.lifeSpan);if(xe(e)){try{s=qe(e)?e.optimistically(...t):e.locally(...t)}catch(e){null==n||n($e(void 0,{origin:"local",loading:!1,error:e}))}const a=Ke(s)&&Ne(s,o);if(null==n||n($e(s,{origin:"local",loading:!(Me(e)&&a)})),a)return}else null==n||n($e(void 0,{origin:"local",loading:!0}));e(...t).then((e=>{null==n||n($e(e,{origin:"server",loading:!1}))})).catch((e=>{null==n||n($e(void 0,{origin:"server",loading:!1,error:e}))}))};function $e(e,t){return ke(e)||Ke(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 Qe extends Le{constructor(e,t,n){super(e,t,n)}}class Je extends Le{constructor(e=8e5,t="fatal"){super("Unexpected error",e,t)}}class Ve extends Le{constructor(e,t="SDK client is having connection issues"){super(`${t} (${e})`,"disconnected"===e?800211:800210,"error"),this.event=e}}class He extends Le{constructor(e){super(e,800110,"error")}}let ze=null;const Ge=()=>{if(!ze)throw new Le("There is no active client",8e5,"fatal");return ze},Ye=e=>{ze=e},We={user:({userId:e})=>e,file:({fileId:e})=>e,role:({roleId:e})=>e,channel:({channelInternalId:e})=>e,subChannel:({subChannelId:e})=>e,channelUsers:({channelId:e,userId:t})=>`${e}#${t}`,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},Xe=e=>We[e],Ze={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 et(e=(new Date).toISOString()){return new Date(new Date(e).getTime()+1).toISOString()}const tt=e=>{const{log:t,cache:n}=Ge();if(n)return t("cache/api/queryCache",{key:e}),Object.keys(n.data).filter((t=>{const n=Te(t);return Ae(e,n)})).map((e=>n.data[e]))},nt=e=>{const{log:t,cache:n}=Ge();if(!n)return;t("cache/api/pullFromCache",e);const a=Oe(e);return n.data[a]?n.data[a]:void 0},at=(e,t,n={cachedAt:Date.now()})=>{const{log:a,cache:s}=Ge();if(!s)return!1;a("cache/api/pushToCache",{key:e,data:t,options:n}),!(null==n?void 0:n.hasOwnProperty("offline"))&&s.persistIf&&(n.offline=s.persistIf(e,t));const o=Oe(e);return s.data[o]=Object.assign({key:e,data:t},n),!0},st=(e,t,n)=>{const{log:a,cache:s}=Ge();if(!s)return!1;a("cache/api/mergeInCache",{key:e,mutation:t});const o=nt(e);if(!o)return!1;const i="function"==typeof t?t(o.data):Object.assign(Object.assign({},o.data),t);return r=o.data,!("updatedAt"in(c=i)&&"updatedAt"in r&&new Date(c.updatedAt)<new Date(r.updatedAt))&&(at(e,i,n),!0);var r,c},ot=(e,t,n={cachedAt:Date.now()})=>{const{log:a,cache:s}=Ge();if(!s)return!1;a("cache/api/upsertInCache",{key:e,data:t,options:n});return nt(e)?st(e,t,n):at(e,t,n)},it=(e,t=!1)=>{const{log:n,cache:a}=Ge();if(!a)return!1;if(n("cache/api/dropFromCache",{key:e,exact:t}),!t)return Object.keys(a.data).map((e=>Te(e))).filter((t=>Ae(e,t))).map((e=>it(e,!0))).every((e=>e));const s=Oe(e);return s in a.data&&(delete a.data[s],!0)},rt=(e,t,n)=>void 0!==n?e.filter((e=>JSON.stringify(e[t])===JSON.stringify(n))):e,ct=(e,t,n)=>void 0!==n?e.filter((e=>"string"==typeof e[t]&&"string"==typeof n&&String(e[t]).toLowerCase().match(n.toLowerCase()))):e,dt=(e,t,n)=>(null==n?void 0:n.length)?e.filter((e=>Array.isArray(e[t])&&n.some((n=>e[t].includes(n))))):e,lt=(e,t,n)=>"all"===t?e:e.filter((e=>{var a;if("community"===e.type)return!0;const s=Xe("channelUsers")({channelId:e.channelPublicId,userId:n}),o=null===(a=nt(["channelUsers","get",s]))||void 0===a?void 0:a.data;return"member"===t?o&&"none"!==o.membership:!o||"none"===o.membership})),ut=(e,t)=>e.filter((({targetId:e,feedId:n})=>{var a;const s=null===(a=nt(["feed","get",Xe("feed")({targetId:e,feedId:n})]))||void 0===a?void 0:a.data;return s&&s.feedType===t})),ht=(e,t,n)=>"all"===t?e:e.filter((e=>{var a;const s=Xe("communityUsers")({communityId:e.communityId,userId:n}),o=null===(a=nt(["communityUsers","get",s]))||void 0===a?void 0:a.data;return"member"===t?o&&"member"===o.communityMembership:!o||"none"!==o.communityMembership})),mt=(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 s=null===(a=nt(["post","get",n.children[0]]))||void 0===a?void 0:a.data;return(null==t?void 0:t.includes(null==s?void 0:s.dataType))?e:[...e,n]}return e}),[]),gt=(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))}))},pt=()=>{var e;const{userId:t}=Ge(),n=new Set;return(null!==(e=tt(["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},yt=e=>{const t=pt();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)))}))},vt=e=>{const t=pt();return 0===t.size?e:e.filter((e=>!t.has(e.userId)))},ft=({displayName:e},{displayName:t})=>e&&t?e.localeCompare(t):e?-1:1,bt=({name:e},{name:t})=>e&&t?e.localeCompare(t):e?-1:1,It=({createdAt:e},{createdAt:t})=>new Date(e).valueOf()-new Date(t).valueOf(),Ct=({localSortingDate:e},{localSortingDate:t})=>new Date(t).getTime()-new Date(e).getTime(),wt=({createdAt:e},{createdAt:t})=>new Date(t).valueOf()-new Date(e).valueOf(),St=({updatedAt:e=0},{updatedAt:t=0})=>new Date(e).valueOf()-new Date(t).valueOf(),Ot=({updatedAt:e=0},{updatedAt:t=0})=>new Date(t).valueOf()-new Date(e).valueOf(),Tt=({lastActivity:e},{lastActivity:t})=>new Date(t).valueOf()-new Date(e).valueOf(),At=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")},Rt=(e,t,n)=>{const a=new Date(e).valueOf(),s=new Date(t).valueOf();return"firstCreated"===n?a>=s:a<=s};let Pt=null;const Dt=()=>{if(!Pt)throw new Le("Connect client first",8e5,"fatal");return Pt},Ut=e=>{Pt={_id:e._id,userId:e.userId,path:e.path}};let kt,jt=[];const Et=e=>{clearTimeout(kt),jt.push(e),kt=setTimeout((()=>{jt.forEach((e=>e())),jt=[]}),0)},Mt=["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"],qt=(e,t,n,a)=>{const{log:s,emitter:o}=e,i=Date.now();s(`${t}(tmpid: ${i}) > listen`);const r=(...e)=>{s(`${t}(tmpid: ${i}) > trigger`,e);try{a(...e)}catch(e){s(`${t}(tmpid: ${i}) > error`,e)}};return o.on(n,r),()=>{s(`${t}(tmpid: ${i}) > dispose`),o.off(n,r)}},xt=(e,t)=>{const{emitter:n}=Ge();Et((()=>{n.emit(e,t)}))};let Kt,Nt;async function Ft(){var e;const{mqtt:t,emitter:n,token:a}=Ge();if(!t)return;const s=null!==(e=null==a?void 0:a.accessToken)&&void 0!==e?e:"",o=Dt();Kt===s&&Nt===o._id||(Kt=s,Nt=o._id,await t.connect({accessToken:Kt,userId:Nt}),((e,t)=>{Mt.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 _t=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=nt(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),Bt=()=>{var e;const t=Ge();if(!t)throw new Le("Connect client first",8e5,"fatal");const n=null===(e=nt(["user","get",t.userId]))||void 0===e?void 0:e.data;return n?_t(n):null};var $t;e.SubscriptionLevels=void 0,($t=e.SubscriptionLevels||(e.SubscriptionLevels={})).COMMUNITY="community",$t.POST="post",$t.COMMENT="comment",$t.POST_AND_COMMENT="post_and_comment",$t.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}},Qt=e=>e.path.split("/user/")[0],Jt=()=>{const e=Dt();return`${Qt(e)}/membership/${e._id}/+/+`},Vt=()=>{const e=Dt();return`${Qt(e)}/membership/+/${e._id}/+`},Ht=({channelId:e,subChannelId:t})=>{const n=Dt();return`${Qt(n)}/marker/channel/${e}/message/${t}`},zt=()=>Qt(Dt()),Gt=()=>{const e=Dt();return`${Qt(e)}/smartfeed/${e._id}/channels`},Yt=()=>{const e=Dt();return`${Qt(e)}/smartfeed/${e._id}/messagefeeds`},Wt=()=>{const e=Dt();return`${Qt(e)}/smartfeed/${e._id}/messages`},Xt=()=>{const e=Dt();return`${Qt(e)}/videostreaming`};function Zt(e,t){const{mqtt:n}=Ge();return n?(Ft(),n.subscribe(e,t)):()=>null}var en;const tn="object"==typeof globalThis?globalThis:"object"==typeof global?global:window,{process:nn={}}=tn,an="production"===(null===(en=nn.env)||void 0===en?void 0:en.NODE_ENV),sn={EU:"eu",SG:"sg",US:"us"},on={http:"https://apix.{region}.amity.co",upload:"https://upload.{region}.amity.co",mqtt:"wss://sse.{region}.amity.co:443/mqtt"};function rn(e,t){return on[e].replace("{region}",t)}class cn{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 dn;var ln,un=()=>(dn||(dn=new cn),dn);!function(e){e.UserDeleted="User Deleted",e.UserGlobalBanned="User Global Banned",e.TokenExpired="Token Expired"}(ln||(ln={}));let hn=new AbortController;const mn=e=>{switch(e){case ln.UserGlobalBanned:throw new Le(e,400312,"fatal");case ln.UserDeleted:throw new Le(e,400100,"fatal");case ln.TokenExpired:throw xt("tokenExpired","tokenExpired"),new Le(e,800403,"fatal");default:throw new Le("Request Aborted",8e5,"error")}};let gn=0;const pn=e=>{const t={maxSockets:100,maxFreeSockets:10,timeout:6e4,freeSocketTimeout:3e4},n=C.default.create({baseURL:e,httpAgent:new w.default(t),httpsAgent:new o.HttpsAgent(t),signal:hn.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&&(hn.abort(),mn(ln.UserGlobalBanned)),a&&(hn.abort(),mn(ln.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||""),s=null===(t=e.config.method)||void 0===t?void 0:t.toUpperCase(),o={method:s,headers:e.config.headers};return"GET"!==s&&"HEAD"!==s&&(o.body=e.config.data),un().setNetworkActivities(new Request(a,o),{data:e.data,status:e.status,statusText:e.statusText,headers:n}),e}),(e=>{var t,n,a;const{response:s}=e;if(400100===(null==s?void 0:s.data.code)&&xt("tokenTerminated","terminated"),400323===(null===(t=null==s?void 0:s.data)||void 0===t?void 0:t.code))throw function(){const e=Date.now();e-gn<2e3||(gn=e,xt("visitorUsageLimitReached",void 0))}(),new Le("Visitor usage limit exceeded",400323,"error");if((null===(n=null==s?void 0:s.data)||void 0===n?void 0:n.status)&&(e=>{if("success"===e.status)return e.data;if("fail"===e.status)throw new Je(e.code);if("error"===e.status)throw new Qe(e.message,e.code,"error")})(null==s?void 0:s.data),hn.signal.aborted)throw e;throw new Error(null!==(a=null==s?void 0:s.data)&&void 0!==a?a:e)})),n.defaults.paramsSerializer={encode:e=>encodeURIComponent(e)},n};class yn{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 vn;var fn=()=>(vn||(vn=new yn),vn);const bn=e=>fn().onSessionStateChange(e),In={[e.AmityAutoSubscription.NETWORK]:[zt],[e.AmityAutoSubscription.CHAT]:[Gt,Yt,Wt],[e.AmityAutoSubscription.LIVESTREAM]:[Xt],[e.AmityAutoSubscription.BLOCK]:[Jt,Vt]},Cn=[e.AmityAutoSubscription.CHAT,e.AmityAutoSubscription.NETWORK,e.AmityAutoSubscription.LIVESTREAM,e.AmityAutoSubscription.BLOCK],wn=Object.values(e.AmityAutoSubscription);class Sn{constructor(){this.refCountByFeature=new Map,this.disposers=new Map,this.seed()}seed(){this.refCountByFeature.clear(),Cn.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,In[e].map((e=>Zt(e()))))}unsubscribeTopics(e){var t;(null!==(t=this.disposers.get(e))&&void 0!==t?t:[]).forEach((e=>e())),this.disposers.delete(e)}initialize(){wn.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 wn.map((e=>({feature:e,isActive:this.isActive(e),isSystem:!0,topicCount:In[e].length})))}reset(){wn.forEach((e=>this.unsubscribeTopics(e))),this.disposers.clear(),this.seed()}}let On=null;const Tn=()=>(On||(On=new Sn),On);class An{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 Rn=()=>"undefined"!=typeof window&&window.localStorage?window:{localStorage:new An},Pn=async(e,t)=>"undefined"!=typeof navigator&&"ReactNative"===navigator.product?(await O.default.setItem(e,t),!0):new Promise((n=>{Rn().localStorage.setItem(e,t),n(!0)})),Dn=async e=>{if("undefined"!=typeof navigator&&"ReactNative"===navigator.product){return await O.default.getItem(e)}return new Promise((t=>{t(Rn().localStorage.getItem(e))}))},Un=()=>T.default.v4().toString();let kn=0;if("undefined"!=typeof BroadcastChannel&&"undefined"!=typeof window){const e=Un(),t={},n=new BroadcastChannel("amity_ts_sdk");let a;n.postMessage({type:"startup",tabId:e}),n.onmessage=({data:s})=>{s.tabId!==e&&("startup"===s.type&&n.postMessage({type:"identify",tabId:e,tabIndex:kn}),"identify"===s.type&&void 0!==s.tabIndex&&s.tabId&&(t[s.tabId]=s.tabIndex,a||(a=setTimeout((()=>{const e=Object.values(t).sort();e&&0!==e.length&&(kn=e.reduce(((e,t)=>e<t?e:t+1),0))}),15))))}}const jn=async()=>{var e;const t=`${null!==(e=Ge().prefixDeviceIdKey)&&void 0!==e?e:""}#deviceId`,n=await Dn(t);if(n)return n;const a=`ascWebSdk#${Un()}`;return await Pn(t,a),a},En=()=>{const e=(()=>{var e,t;return(null===(e=nn.versions)||void 0===e?void 0:e.node)?nn.versions.node:navigator?`${navigator.product.toLowerCase()}#${null!==(t=navigator.userAgent)&&void 0!==t?t:"unknown_agent"}`:"unknown_model"})();return{kind:"web",model:e,sdkVersion:he}},Mn=1e3;var qn;!function(e){e[e.IDENTIFIER_REJECTED=2]="IDENTIFIER_REJECTED",e[e.CLIENT_IDENTIFIER_NOT_VALID=133]="CLIENT_IDENTIFIER_NOT_VALID",e[e.BAD_USERNAME_OR_PASSWORD=134]="BAD_USERNAME_OR_PASSWORD",e[e.NOT_AUTHORIZED=135]="NOT_AUTHORIZED"}(qn||(qn={}));const xn=e=>{let t,n="disconnected";const a=new Set,s=e=>{n!==e&&(n=e,a.forEach((t=>{t(e)})))},o=new Map;function i(e,n,a){const s=(t,s)=>{var r;if(t||128===(null===(r=null==s?void 0:s[0])||void 0===r?void 0:r.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 s=setTimeout((()=>{i(e,n+1,a)}),t);o.set(e,{timer:s,callback:a})}else{o.delete(e);const n=t?new Le(t.message,8e5,"error"):new Je(8e5,"error");console.warn(`Failed to subscribe to topic ${e} after 3 attempts`,n),null==a||a(n)}else o.delete(e),console.log(`Subscribed to topic ${e}`),null==a||a()};t?t.subscribe(e,{qos:0},s):s(new Error("No connection to broker"),[])}return{connect:async function(n){const a=await(async e=>`mqttjs_${await jn()}_${e}_${kn}`)(n.userId);return s("connecting"),t&&(s("disconnecting"),t.removeAllListeners(),t.end(!0)),t=S.default.connect(e,function(e){return Object.assign({clean:!1,clientId:`mqttjs_ + ${Math.random().toString(16).substring(2,10)}`,protocolId:"MQTT",protocolVersion:5,reconnectPeriod:Mn,resubscribe:!0,keepalive:30,properties:{sessionExpiryInterval:4294967295}},e)}({username:n.userId,password:n.accessToken,clientId:a})),t.on("connect",(()=>{t.options.reconnectPeriod=Mn,s("connected"),Tn().initialize()})),t.on("error",(e=>{switch("code"in e?e.code:void 0){case 2:case 133:case 134:case 135:t.end(),s("disconnected")}})),t.on("reconnect",(()=>{s("reconnecting"),t.options.reconnectPeriod=Math.min(2*(t.options.reconnectPeriod||Mn),8e3)})),t.on("close",(()=>{o.forEach((({timer:e})=>clearTimeout(e))),o.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 i(e,0,t),()=>this.unsubscribe(e)},unsubscribe(e){var n;const a=o.get(e);if(void 0!==a){clearTimeout(a.timer),o.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)}}},Kn=async()=>{const e=Ge(),{data:t}=await e.http.get("/api/v3/network-settings/chat");return t},Nn=(e={},t,n=!0)=>{Object.entries(e).forEach((([e,a])=>{const s=Ze[e];if(!s)return;const o=Xe(s);o&&a&&a.forEach((e=>{(n?at:ot)([s,"get",o(e)],e,t)}))}))},Fn=(e,t)=>{const{log:n,cache:a}=Ge(),s=[e,we,t],o={cachedAt:Date.now()};a&&(n("cache/api/pushToTombstone",{cacheKey:s,data:o}),it([e,"get",t],!0),at(s,o))};function _n(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 s=0;for(a=Object.getOwnPropertySymbols(e);s<a.length;s++)t.indexOf(a[s])<0&&Object.prototype.propertyIsEnumerable.call(e,a[s])&&(n[a[s]]=e[a[s]])}return n}const Bn=(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(!Ge().cache)return;return(null===(n=nt(["user","get",e[t]]))||void 0===n?void 0:n.data)||void 0}},e))(e,t,n))))&&void 0!==a?a:e},$n=(e,t,n="userId",a="user")=>{const s=e,o=t,i=s[o],r=_n(s,["symbol"==typeof o?o:o+""]),c=Bn(i,n,a);return Object.assign(Object.assign({},r),{[t]:c})};function Ln(e){return e.map((e=>{var{isMentioned:t}=e,n=_n(e,["isMentioned"]);return Object.assign({hasMentioned:t},n)}))}function Qn(e){return Ln(e)}function Jn(e){return Ln(e)}const Vn=e=>{var t,n;return null!==(n=null===(t=nt(["messagePreviewChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},Hn=e=>new Date(e).getTime(),zn=e=>{var t,n;return null!==(n=null===(t=nt(["messagePreviewSubChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},Gn=e=>{var t;const n=e.messagePreviewId?zn(e.subChannelId):null,a=n?Object.assign(Object.assign({},n),{user:null===(t=nt(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data}):null;return Object.assign(Object.assign({},e),{messagePreview:a})},Yn=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:s,messageFeedId:o,messageId:i,creatorPublicId:r,data:c,dataType:d,isDeleted:l,segment:u,createdAt:h,updatedAt:m}=t;return{messagePreviewId:i,channelId:s,subChannelId:o,data:c,dataType:d,isDeleted:l,segment:u,creatorId:r,createdAt:h,updatedAt:m,subChannelName:null==a?void 0:a.name,subChannelUpdatedAt:null==a?void 0:a.updatedAt}})(t))))&&void 0!==n?n:[]};Nn(a)};function Wn(e,t){return Object.create(Object.getPrototypeOf(e),Object.assign(Object.assign({},Object.getOwnPropertyDescriptors(e)),Object.getOwnPropertyDescriptors(t)))}function Xn(e,t,n){at(["subChannel","get",e],Wn(t,n))}const Zn=(e,t)=>{const{log:n,cache:a}=Ge(),s=[e,we,t];if(!a)return;n("cache/api/isInTombstone",s);const o=nt(s),{lifeSpan:i}=_e("cache_then_server",18e4);if(o&&Ne(o.data,i))throw new Qe("Item not found!",400400,"error")},ea=e=>{var t;const n=["channelUnreadInfo","get",e],a=null===(t=nt(n))||void 0===t?void 0:t.data,s=tt(["subChannelUnreadInfo","get"]);let o=0,i=!1;if(s&&(null==s?void 0:s.length)>0){const t=null==s?void 0:s.filter((({data:t})=>t.channelId===e&&!t.isDeleted));o=t.map((({data:e})=>e.unreadCount)).reduce(((e,t)=>e+t),0),i=t.some((({data:e})=>e.isMentioned))}const r=Object.assign(Object.assign({},null!=a?a:{channelId:e,createdAt:(new Date).toISOString()}),{updatedAt:(new Date).toISOString(),unreadCount:o,isMentioned:i});return at(n,r),r},ta=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,s={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};Nn({subChannelUnreadInfo:[s]}),e.includes(n.entityId)||e.push(n.entityId)}})),e.forEach((e=>{ea(e)}))}},na=async()=>{const e=Ge();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&&Nn({userMarkers:n},{cachedAt:a}),xt("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}},aa=e=>{var t,n;const a=null===(t=nt(["message","get",e]))||void 0===t?void 0:t.data;if(a)return a;const s=tt(["message","get"]);return null===(n=null==s?void 0:s.find((({data:t})=>t.messageId===e)))||void 0===n?void 0:n.data},sa=e=>!0===e&&void 0;function oa(e,t,n){var a,s;if(n)return n.hasMentioned;const o=Ge();if(o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()){const e=null===(a=nt(["subChannelUnreadInfo","get",t]))||void 0===a?void 0:a.data;return!!e&&e.isMentioned}const i={entityId:e,feedId:t,userId:Dt()._id},r=null===(s=nt(["subChannelMarker","get",Xe("subChannelMarker")(i)]))||void 0===s?void 0:s.data;return!!r&&r.hasMentioned}const ia=["broadcast","conversation","community"],ra=({channelType:e})=>ia.includes(e);function ca(e){var{channelId:t,channelPublicId:n,channelType:a,childCount:s,creatorId:o,creatorPublicId:i,lastMessageId:r,lastMessageTimestamp:c,messageFeedId:d,name:l}=e,u=_n(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,s;if(n)return n.unreadCount;const o=Ge();if(o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()){const e=null===(a=nt(["subChannelUnreadInfo","get",t]))||void 0===a?void 0:a.data;return e?e.isDeleted?0:e.unreadCount:0}const i={entityId:e,feedId:t,userId:Dt()._id},r=null===(s=nt(["subChannelMarker","get",Xe("subChannelMarker")(i)]))||void 0===s?void 0:s.data;return r?r.unreadCount:0}(t,d)},get hasMentioned(){return oa(t,d)},get isMentioned(){return oa(t,d)}},u),{channelId:n,creatorId:i,displayName:l,lastActivity:c,latestMessageId:r,messageCount:s,subChannelId:d,isUnreadCountSupport:ra({channelType:a})})}function da(e,t,n){var a;const s=(e=>{var t,n,a;const s=null===(n=null===(t=tt(["message","get"]))||void 0===t?void 0:t.find((({data:t})=>t.messageId===e.messageId)))||void 0===n?void 0:n.data;return s?Object.assign(Object.assign(Object.assign({},s),e),{referenceId:null!==(a=s.referenceId)&&void 0!==a?a:e.referenceId}):e})(e),{channelPublicId:o,childCount:i,creatorPublicId:r,mentionedUsers:c,messageFeedId:d,myReactions:l,reactionCount:u,reactions:h,referenceId:m,segment:g,messageId:p,creatorId:y}=s,v=_n(s,["channelPublicId","childCount","creatorPublicId","mentionedUsers","messageFeedId","myReactions","reactionCount","reactions","referenceId","segment","messageId","creatorId"]);let f;m&&(f=nt(["message","get",m])),f||(f=nt(["message","get",p]));const b=Object.assign(Object.assign({},v),{messageId:p,channelId:o,channelSegment:g,childrenNumber:i,creatorId:r,creatorPrivateId:e.creatorId,reactions:null!=h?h:{},myReactions:l||(null!==(a=null==f?void 0:f.data.myReactions)&&void 0!==a?a:[]),reactionsCount:u,subChannelId:d,uniqueId:f?f.data.uniqueId:p,referenceId:m,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=Ge(),s=aa(e.messageId),o=(null==s?void 0:s.myReactions)||[];Object.assign(e,{myReactions:o});const i=t[0];i&&i.userId===a.userId&&("message.reactionAdded"!==n||o.includes(i.reactionName)||Object.assign(e,{myReactions:[...o,i.reactionName]}),"message.reactionRemoved"===n&&o.includes(i.reactionName)&&Object.assign(e,{myReactions:o.filter((e=>e!==i.reactionName))}))})(b,t,n),b}const la={},ua=async(e,t)=>{const n=e.messages.map((({messageId:e})=>e));if(n.length>0){Nn({messages:(a=e).messages.map((e=>da(e,a.reactions)))});const t=n.join("");la[t]&&clearTimeout(la[t]),la[t]=setTimeout((()=>{try{(async e=>{const t=Ge();t.log("channel/getMessageMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/messages",{params:{messageIds:e}}),{contentMarkers:a,feedMarkers:s,userMarkers:o}=n,i=t.cache&&Date.now();t.cache&&Nn({contentMarkers:a,feedMarkers:s,userMarkers:o},{cachedAt:i}),xt("local.feedMarker.fetched",{feedMarkers:s}),xt("local.messageMarker.fetched",{contentMarkers:a}),xt("local.userMarker.fetched",{userMarkers:o})})(n)}catch(e){}}),2e3)}var a;const{messageFeeds:s}=e,o=_n(e,["messageFeeds"]);return s&&s.length>0&&(null==s||s.forEach((e=>{var t,n;const a=null!==(n=null===(t=nt(["subChannel","get",e.messageFeedId]))||void 0===t?void 0:t.data)&&void 0!==n?n:{},s=_n(ca(e),["unreadCount","isMentioned"]);Xn(e.messageFeedId,a,s)}))),Object.assign(Object.assign({},o),{messages:e.messages.map((n=>da(n,e.reactions,t)))})};function ha(e){var{subChannelId:t,mentionees:n,dataType:a,data:s}=e,o=_n(e,["subChannelId","mentionees","dataType","data"]);return a===B.IMAGE||a===B.FILE?Object.assign({messageFeedId:t,mentionedUsers:n,dataType:a,data:Object.assign({caption:""},s)},o):Object.assign({messageFeedId:t,mentionedUsers:n,dataType:a,data:s},o)}function ma(e){var{sortBy:t,subChannelId:n,includingTags:a,excludingTags:s,includeDeleted:o,aroundMessageId:i,limit:r,type:c}=e,d=_n(e,["sortBy","subChannelId","includingTags","excludingTags","includeDeleted","aroundMessageId","limit","type"]);const l=Object.assign(Object.assign({},d),{messageFeedId:n,isDeleted:sa(o),options:{sortBy:t,limit:r||me,around:i}});return a&&(l.includeTags=a),c&&(l.dataType=c),s&&(l.excludeTags=s),l}function ga(e){return Object.assign(Object.assign({},e),{isGlobalBanned:(null==e?void 0:e.isGlobalBan)||!1})}const pa=["broadcast","conversation","community"],ya=({channelType:e})=>pa.includes(e),va=async e=>{const t=e.messageFeeds.filter(ya).map((({messageFeedId:e})=>e));if(t.length>0){(e=>{Nn({messageFeeds:e.messageFeeds.map((e=>ca(e)))})})(e);try{await(async(e,t={limit:100})=>{const n=Ge();n.log("channel/getSubChannelMarkers",e,t);const{data:a}=await n.http.get("/api/v1/markers/message-feeds",{params:{messageFeedIds:e,options:{token:je(t,"skiplimit")}}}),{paging:s}=a,o=_n(a,["paging"]),{userEntityMarkers:i,userFeedMarkers:r,userMarkers:c,feedMarkers:d}=o;n.isUnreadCountEnabled&&n.getMarkerSyncConsistentMode()&&ta({feedMarkers:d,userFeedMarkers:r});const l=Qn(i),u=Jn(r),h=n.cache&&Date.now();n.cache&&Nn({userEntityMarkers:l,userFeedMarkers:u,userMarkers:c},{cachedAt:h}),xt("local.channelMarker.fetched",{userEntityMarkers:l}),xt("local.subChannelMarker.fetched",{userFeedMarkers:u}),xt("local.userMarker.fetched",{userMarkers:c});const m=Ee(s.next);return{data:u,cachedAt:h,prevPage:Ee(s.previous),nextPage:m}})(t)}catch(e){}}Yn(e);const n=e.messageFeeds.map(ca),a=e.messages.map((e=>da(e))),s=e.users.map(ga);return Object.assign(Object.assign({},e),{messageFeeds:n,messages:a,users:s})};const fa=async e=>{const t=Ge();t.log("channel/getSubChannel",e),Zn("subChannel",e);try{const n=await t.http.get(`/api/v5/message-feeds/${encodeURIComponent(e)}`),a=await va(n.data),s=t.cache&&Date.now();return t.cache&&Nn(a,{cachedAt:s}),xt("local.message-feed.fetched",a),{data:a.messageFeeds[0],cachedAt:s}}catch(t){throw Re(null==t?void 0:t.code)&&Fn("subChannel",e),t}};fa.locally=e=>{const t=Ge();if(t.log("channel/getSubChannel.locally",e),!t.cache)return;const n=nt(["subChannel","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const ba=async e=>{var t;let n=null===(t=nt(["subChannel","get",e]))||void 0===t?void 0:t.data;return n||(n=(await fa(e)).data),n},Ia=async e=>{const t=await(async()=>Ge().getMessagePreviewSetting(!1))(),{channelId:n,messageId:a,creatorId:s,createdAt:o,updatedAt:i,data:r,dataType:c,subChannelId:d,channelSegment:l,isDeleted:u}=e,h=await ba(d);"no-message-preview"!==t?(e=>{var t;const n=null===(t=nt(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;return!n||n.segment<=e.channelSegment||Hn(n.createdAt)<=Hn(e.createdAt)})(e)&&(at(["messagePreviewSubChannel","get",e.subChannelId],{channelId:n,creatorId:s,messagePreviewId:a,createdAt:o,updatedAt:i,subChannelId:d,data:r,dataType:c,segment:l,isDeleted:u,subChannelUpdatedAt:null==h?void 0:h.updatedAt,subChannelName:null==h?void 0:h.displayName}),Xn(e.subChannelId,h,{lastActivity:o,messagePreviewId:a})):Hn(h.lastActivity)<Hn(o)&&Xn(e.subChannelId,h,{lastActivity:o})},Ca=async e=>{var t;const{channelId:n,messageId:a,creatorId:s,createdAt:o,updatedAt:i,data:r,dataType:c,subChannelId:d,channelSegment:l,isDeleted:u}=e,h=null===(t=nt(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await ba(d);at(["messagePreviewSubChannel","get",e.subChannelId],{channelId:n,creatorId:s,messagePreviewId:a,createdAt:o,updatedAt:i,subChannelId:d,data:r,dataType:c,segment:l,isDeleted:u,subChannelUpdatedAt:t.updatedAt,subChannelName:h.subChannelName})}},wa=async e=>{const{channelId:t,messageId:n,creatorId:a,createdAt:s,updatedAt:o,data:i,dataType:r,subChannelId:c,channelSegment:d,isDeleted:l}=e;if((e=>{var t;const n=null===(t=nt(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;return!n||Hn(n.createdAt)<=Hn(e.createdAt)})(e)){const u=await ba(c);at(["messagePreviewChannel","get",e.channelId],{channelId:t,creatorId:a,messagePreviewId:n,createdAt:s,updatedAt:o,subChannelId:c,data:i,dataType:r,segment:d,isDeleted:l,subChannelUpdatedAt:null==u?void 0:u.updatedAt,subChannelName:null==u?void 0:u.displayName})}},Sa=async e=>{var t;const{channelId:n,messageId:a,creatorId:s,createdAt:o,updatedAt:i,data:r,dataType:c,subChannelId:d,channelSegment:l,isDeleted:u}=e,h=null===(t=nt(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await ba(d);at(["messagePreviewChannel","get",e.channelId],{channelId:n,creatorId:s,messagePreviewId:a,createdAt:o,updatedAt:i,subChannelId:d,data:r,dataType:c,segment:l,isDeleted:u,subChannelUpdatedAt:t.updatedAt,subChannelName:h.subChannelName})}},Oa=async e=>{var t,n,a,s;const{channelId:o,subChannelId:i}=e,r=null===(t=nt(["messagePreviewChannel","get",o]))||void 0===t?void 0:t.data;if((null==r?void 0:r.subChannelId)===i){const e=null===(n=nt(["subChannel","get",i]))||void 0===n?void 0:n.data;at(["messagePreviewChannel","get",o],Object.assign(Object.assign({},r),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}const c=null===(a=nt(["messagePreviewSubChannel","get",i]))||void 0===a?void 0:a.data;if(c&&new Date(c.updatedAt).valueOf()>new Date(e.updatedAt).valueOf()){const e=null===(s=nt(["subChannel","get",i]))||void 0===s?void 0:s.data;at(["messagePreviewSubChannel","get",i],Object.assign(Object.assign({},c),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}},Ta=["broadcast","conversation","community"],Aa=({type:e})=>Ta.includes(e);function Ra(e,t={isMessagePreviewUpdated:!0}){var n;let{messagePreviewId:a}=e;const s=null===(n=nt(["messagePreviewChannel","get",e.channelId]))||void 0===n?void 0:n.data;return(null==s?void 0:s.messagePreviewId)&&!t.isMessagePreviewUpdated&&(a=s.messagePreviewId),Object.assign(Object.assign({},e),{defaultSubChannelId:e.channelInternalId,isUnreadCountSupport:Aa(e),messagePreviewId:a})}const Pa=(e,t={isMessagePreviewUpdated:!0})=>{Nn({channels:e.channels.map((e=>Ra(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated})))})},Da=async(e,t={isMessagePreviewUpdated:!0})=>{const n=Ge(),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:s,messageFeedId:o,data:i,dataType:r,isDeleted:c,segment:d,creatorPublicId:l,createdAt:u,updatedAt:h}=t;return{channelId:s,subChannelId:o,data:i,dataType:r,isDeleted:c,segment:d,creatorId:l,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=nt(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;return!n||Hn(n.createdAt)<=Hn(e.createdAt)}));0!==n.length&&Nn({messagePreviewChannel:n})})(e),n.useLegacyUnreadCount)(({currentUserId:e,channels:t,channelUsers:n})=>{var a,s;const o=[];for(let i=0;i<t.length;i+=1)if(Aa(t[i])){const r=["channelUnread","get",t[i].channelId],c=n.find((n=>n.channelId===t[i].channelId&&n.userId===e)),d=null===(a=nt(r))||void 0===a?void 0:a.data,l=Math.max(null!==(s=null==d?void 0:d.lastSegment)&&void 0!==s?s:0,t[i].messageCount);let u=null,h=null,m=0,g=!1;if(c){const e=c.readToSegment,t=c.lastMentionedSegment;u="number"==typeof(null==d?void 0:d.readToSegment)&&("number"!=typeof e||d.readToSegment>e)?d.readToSegment:null!=e?e:null,h="number"==typeof(null==d?void 0:d.lastMentionedSegment)&&("number"!=typeof t||d.lastMentionedSegment>t)?d.lastMentionedSegment:null!=t?t:null;const n=null!=u?u:0;m=Math.max(l-n,0),g="number"==typeof h&&n<h}const p={channelId:t[i].channelId,lastSegment:l,readToSegment:u,lastMentionedSegment:h,unreadCount:m,isMentioned:g,isDeleted:t[i].isDeleted||!1};at(r,p),o.push(p)}o.length>0&&xt("local.channelUnread.updated",o)})({channels:e.channels,channelUsers:e.channelUsers,currentUserId:n.userId});else{const n=e.channels.filter(Aa).map((({channelInternalId:e})=>e));if(n.length>0){Pa(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated});try{await(async e=>{const t=Ge();t.log("channel/getChannelMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/channels",{params:{channelIds:e}}),{userEntityMarkers:a,userMarkers:s}=n,o=Qn(a),i=t.cache&&Date.now();return t.cache&&Nn({userEntityMarkers:o,userMarkers:s},{cachedAt:i}),xt("local.channelMarker.fetched",{userEntityMarkers:o}),xt("local.userMarker.fetched",{userMarkers:s}),{data:o,cachedAt:i}})(n)}catch(e){}}}const s=e.channels.map((e=>Ra(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated}))),o=e.channelUsers.map((e=>{return t=e,Object.assign(Object.assign({},t),{get user(){var e;if(Ge().cache)return(null===(e=nt(["user","get",t.userId]))||void 0===e?void 0:e.data)||void 0}});var t})),i=e.users.map(ga),r=_n(e,["messageFeedsInfo","messagePreviews"]);return Object.assign(Object.assign({},r),{users:i,channels:s,channelUsers:o})},Ua=async e=>{const t=Ge();t.log("channel/getUserMessageFeedMakers",e);const{data:n}=await t.http.get("/api/v1/markers/user-message-feed",{params:{channelIds:e}});return xt("local.userMessageFeedMarker.fetched",{userMessageFeedMarker:n}),n},ka=async e=>{const t=Ge(),n=await Ua(e.channels.map((({channelInternalId:e})=>e))),{feedMarkers:a,userFeedMarkers:s}=n;ta({feedMarkers:a,userFeedMarkers:s}),t.log("channel/prepareUnreadCountInfo",e.channels)},ja=(e,t)=>{var n,a,s,o;const i=Ge();return i.isUnreadCountEnabled&&i.getMarkerSyncConsistentMode()?null!==(a=null===(n=(e=>{var t;return null===(t=nt(["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!==(o=null===(s=(e=>{var t;const n={entityId:e,userId:Dt()._id};return null===(t=nt(["channelMarker","get",Xe("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===s?void 0:s.hasMentioned)&&void 0!==o&&o},Ea=(e,t)=>{var n,a,s,o,i;const r=Ge();return r.isUnreadCountEnabled&&r.getMarkerSyncConsistentMode()?null!==(a=null===(n=(e=>{var t;return null===(t=nt(["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!==(i=null!==(s=null==t?void 0:t.unreadCount)&&void 0!==s?s:null===(o=(e=>{var t;const n={entityId:e,userId:Dt()._id};return null===(t=nt(["channelMarker","get",Xe("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===o?void 0:o.unreadCount)&&void 0!==i?i:0},Ma=e=>{var t;return null===(t=nt(["channelUnread","get",e]))||void 0===t?void 0:t.data},qa=e=>{const t=Ge(),n=_n(e,["messageCount"]);return Wn(n,{get unreadCount(){var e,t;return null!==(t=null===(e=Ma(n.channelId))||void 0===e?void 0:e.unreadCount)&&void 0!==t?t:0},get subChannelsUnreadCount(){return Ea(n)},get isMentioned(){var e,a;return t.useLegacyUnreadCount?null!==(a=null===(e=Ma(n.channelId))||void 0===e?void 0:e.isMentioned)&&void 0!==a&&a:ja(n)}})},xa=e=>Object.assign(Object.assign({},e),{get user(){return(()=>{var t;const n=["user","get",e.userId],a=null===(t=nt(n))||void 0===t?void 0:t.data;return a?_t(a):void 0})()}}),Ka=e=>{const t=Ge();t.log("channel/getMyMembership.locally");const n=nt(["channelUsers","get",`${e}#${t.userId}`]);if(!n)throw new Qe("Item not found!",400400,"error");return{data:n.data,cachedAt:n.cachedAt}};function Na(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(!Na(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=>Na(e[n],t[n])))}const Fa=[];let _a=null;const Ba=e=>{if(0===Fa.length){const e=Ge();_a=qt(e,"onChannelCreated","channel.created",(async e=>{const t=await Da(e);Nn(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==_a||_a())})(e)},$a=[],La=[],Qa=e=>{const t=Ge();if(0===$a.length){const e=async e=>{const t=await Da(e);Nn(t),$a.forEach((e=>e(t.channels[0])))};La.push(qt(t,"onChannelUpdated","channel.updated",e)),La.push(qt(t,"onChannelUpdated","local.channel.updated",(e=>$a.forEach((t=>t(e.channels[0]))))))}return $a.push(e),()=>(e=>{const t=$a.indexOf(e);t>-1&&$a.splice(t,1),0===$a.length&&La.forEach((e=>e()))})(e)},Ja=e=>{const t=tt(["subChannelUnreadInfo","get"]);if(t){(null==t?void 0:t.filter((({data:t})=>t.channelId===e))).forEach((({key:e,data:t})=>{at(e,Object.assign(Object.assign({},t),{isDeleted:!0}))}))}},Va=e=>{var t;const n=["channelUnreadInfo","get",e];(null===(t=nt(n))||void 0===t?void 0:t.data)&&it(n)},Ha=[];let za=null;const Ga=e=>{if(0===Ha.length){const e=Ge(),t=async t=>{const n=await Da(t),a=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,s=e.useLegacyUnreadCount;n.channels.forEach((e=>{if(a)Ja(e.channelId),Va(e.channelId);else if(s){const t=["channelUnread","get",e.channelId],n=nt(t);n&&at(t,Object.assign(Object.assign({},n),{isDeleted:!0}))}})),Nn(n),Ha.forEach((e=>e(n.channels[0])))};za=qt(e,"onChannelDeleted","channel.deleted",t)}return Ha.push(e),()=>(e=>{const t=Ha.indexOf(e);t>-1&&Ha.splice(t,1),0===Ha.length&&(null==za||za())})(e)},Ya=[];let Wa=null;const Xa=e=>{if(0===Ya.length){const e=Ge();Wa=qt(e,"onChannelJoined","channel.joined",(async e=>{const t=await Da(e),{channels:n,channelUsers:a}=t;Nn(t),Ya.forEach((e=>e(n[0],a[0])))}))}return Ya.push(e),()=>(e=>{const t=Ya.indexOf(e);t>-1&&Ya.splice(t,1),0===Ya.length&&(null==Wa||Wa())})(e)},Za=[];let es=null;const ts=e=>{if(0===Za.length){const e=Ge(),t=async t=>{const{userId:n}=Ge(),{channelUsers:a}=t,s=a.some((e=>e.userId===n)),o=await Da(t,{isMessagePreviewUpdated:s}),i=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,r=e.useLegacyUnreadCount;s&&o.channels.forEach((e=>{i?(Ja(e.channelId),Va(e.channelId)):r&&it(["channelUnread","get",e.channelId])}));const{channels:c,channelUsers:d}=o;Nn(o),Za.forEach((e=>e(c[0],d[0])))};es=qt(e,"onChannelLeft","channel.left",t)}return Za.push(e),()=>(e=>{const t=Za.indexOf(e);t>-1&&Za.splice(t,1),0===Za.length&&(null==es||es())})(e)},ns=[];let as=null;const ss=e=>{if(0===ns.length){const e=Ge(),t=async e=>{var t;ot(["channel","get",e.channelId],{isMuted:Date.parse(e.muteTimeout)>Date.now()});const n=null===(t=nt(["channel","get",e.channelId]))||void 0===t?void 0:t.data;n&&ns.forEach((e=>e(n)))};as=qt(e,"onChannelMute","channel.setMuted",t)}return ns.push(e),()=>(e=>{const t=ns.indexOf(e);t>-1&&ns.splice(t,1),0===ns.length&&(null==as||as())})(e)},os=[];let is=null;const rs=e=>{if(0===os.length){const e=Ge();is=qt(e,"onChannelMemberAdded","channel.membersAdded",(async e=>{const t=await Da(e),{channels:n,channelUsers:a}=t;Nn(t),os.forEach((e=>e(n[0],a.find((e=>"member"===e.membership)))))}))}return os.push(e),()=>(e=>{const t=os.indexOf(e);t>-1&&os.splice(t,1),0===os.length&&(null==is||is())})(e)},cs=[];let ds=null;const ls=e=>{if(0===cs.length){const e=Ge();ds=qt(e,"onChannelMemberRemoved","channel.membersRemoved",(async e=>{const t=await Da(e),{channels:n,channelUsers:a}=t;Nn(t),cs.forEach((e=>e(n[0],a[0])))}))}return cs.push(e),()=>(e=>{const t=cs.indexOf(e);t>-1&&cs.splice(t,1),0===cs.length&&(null==ds||ds())})(e)},us=[];let hs=null;const ms=e=>{const t=Ge();return hs=qt(t,"onChannelMemberBanned","channel.banned",(async e=>{const n=await Da(e),{channels:a,channelUsers:s}=n,o=s.some((e=>"banned"===e.membership&&e.userId===t.userId));t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&o&&n.channels.forEach((e=>{Ja(e.channelId),Va(e.channelId)})),Nn(n),us.forEach((e=>e(a[0],s.find((e=>"banned"===e.membership)))))})),us.push(e),()=>(e=>{const t=us.indexOf(e);t>-1&&us.splice(t,1),0===us.length&&(null==hs||hs())})(e)},gs=[];let ps=null;const ys=e=>{if(0===gs.length){const e=Ge();ps=qt(e,"onChannelMemberUnbanned","channel.unbanned",(async e=>{const t=await Da(e),{channels:n,channelUsers:a}=t;Nn(t),gs.forEach((e=>e(n[0],a.find((e=>"none"===e.membership)))))}))}return gs.push(e),()=>(e=>{const t=gs.indexOf(e);t>-1&&gs.splice(t,1),0===gs.length&&(null==ps||ps())})(e)},vs=[];let fs=null;const bs=e=>{if(0===vs.length){const e=Ge();fs=qt(e,"onChannelMemberRoleAdded","local.channel-moderator.role-added",(async e=>{const{channels:t,channelUsers:n}=e;vs.forEach((e=>e(t[0],n.find((e=>"member"===e.membership)))))}))}return vs.push(e),()=>(e=>{const t=vs.indexOf(e);t>-1&&vs.splice(t,1),0===vs.length&&(null==fs||fs())})(e)},Is=[];let Cs=null;const ws=e=>{if(0===Is.length){const e=Ge();Cs=qt(e,"onChannelMemberRoleRemoved","local.channel-moderator.role-removed",(async e=>{const{channels:t,channelUsers:n}=e;Is.forEach((e=>e(t[0],n.find((e=>"member"===e.membership)))))}))}return Is.push(e),()=>(e=>{const t=Is.indexOf(e);t>-1&&Is.splice(t,1),0===Is.length&&(null==Cs||Cs())})(e)},Ss=e=>{const t=Ge();return qt(t,"onChannelArchived","local.channel.archived",(async t=>{e(t)}))},Os=e=>{const t=Ge();return qt(t,"onChannelUnarchived","local.channel.unarchived",(async t=>{e(t)}))},Ts=[];let As=null;const Rs=e=>{if(0===Ts.length){const e=Ge(),t=async e=>{var t,n,a;e.userIds.forEach((t=>ot(["channelUsers","get",`${e.channelId}#${t}`],{isMuted:Date.parse(e.muteTimeout)>Date.now()})));const s=null===(n=null===(t=tt(["channel","get"]))||void 0===t?void 0:t.find((({data:t})=>t.channelPublicId===e.channelId)))||void 0===n?void 0:n.data,o=null===(a=nt(["channelUsers","get",`${e.channelId}#${e.userIds[0]}`]))||void 0===a?void 0:a.data;s&&o&&Ts.forEach((e=>e(s,o)))};As=qt(e,"onChannelUserMute","channel.setMutedUsers",t)}return Ts.push(e),()=>(e=>{const t=Ts.indexOf(e);t>-1&&Ts.splice(t,1),0===Ts.length&&(null==As||As())})(e)},Ps=e=>{var t;let n=[];if(["conversation","community"].includes(e.type)){const a=tt(["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})=>xa(e))))}return Wn(e,{markAsRead:()=>(async e=>{const t=Ge();t.log("channel/markAsRead",e);const{data:n}=await t.http.put(`/api/v1/markers/channels/${e}/mark-read`),{userMarkers:a,userEntityMarkers:s,userFeedMarkers:o}=n,i=_n(n,["userMarkers","userEntityMarkers","userFeedMarkers"]),r=t.cache&&Date.now(),c=Qn(s),d=Jn(o);return t.cache&&Nn(Object.assign({userMarkers:a,userEntityMarkers:c,userFeedMarkers:d},i),{cachedAt:r}),xt("local.channelMarker.updated",{userEntityMarkers:c}),xt("local.subChannelMarker.updated",{userFeedMarkers:d}),!0})(e.channelInternalId),previewMembers:n,myMembership:t=>((e,t)=>{const{_id:n}=Dt();if(!n)throw new Le("The _id has not been defined in ActiveUser",8e5,"error");const{log:a,cache:s}=Ge();s||console.log("This observable object need the cache data!"),a(`liveMymembership(tmpid: ${Date.now()}) > listen`);const o=[];let i=!1;const r=e=>{t(Object.assign(Object.assign({},e),{data:e.data?xa(e.data):e.data}))},c=(t,n)=>{const{data:a}=Ka(e);Na(void 0,a)||r({loading:!1,data:a})};return o.push(ms(c)),o.push(ys(c)),o.push(Rs(c)),(()=>{const t=Fe((async()=>Ka(e)));Be(t,(({error:e,data:t,loading:n,origin:a,cachedAt:s})=>{s===fe?(r({data:t,origin:a,loading:!1,error:new Qe(ve,800800,"error")}),i=!0,o.forEach((e=>e()))):i||r({loading:n,data:t,origin:a,error:e}),e&&o.forEach((e=>e()))}))})(),()=>{o.forEach((e=>e()))}})(e.channelId,t),get avatar(){var t;if(!e.avatarFileId)return;return null===(t=nt(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}})},Ds=e=>Ps(qa((e=>{var t;const n=e.messagePreviewId?Vn(e.channelId):null,a=null===(t=nt(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data,s=n?Object.assign(Object.assign({},n),{user:a?_t(a):void 0}):null;return Object.assign(Object.assign({},e),{messagePreview:s})})(e))),Us=async e=>{const t=Ge();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=>{Re(null==t?void 0:t.code)&&Fn("channel",e)})),t}const s=await Da(a);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await ka(a);const o=t.cache&&Date.now();return t.cache&&Nn(s,{cachedAt:o}),xt("local.channel.fetched",s.channels),{data:s.channels.map((e=>Ds(e))),cachedAt:o}};Us.locally=e=>{var t,n;const a=Ge();if(a.log("channel/getChannelByIds.locally",e),!a.cache)return;const s=null===(t=tt(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!s||(null==s?void 0:s.length)<e.length)return;const o=s.map((({data:e})=>e)),i=null===(n=s.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0];return{data:o.map((e=>Ds(e))),cachedAt:i.cachedAt}};const ks=(e,t)=>{const n=setInterval(e,t);return()=>clearInterval(n)};let js=!1;const Es={},Ms=async()=>{const e=Object.entries(Es).filter((([,e])=>e)).map((([e])=>e));return 0!==e.length&&(async e=>{const t=Ge();t.log("subChannel/readingAPI",e);const{data:n}=await t.http.post("/api/v1/markers/message-feeds/reading",{messageFeedIds:e}),{userEntityMarkers:a,userFeedMarkers:s,feedMarkers:o,userMarkers:i}=n,r=Qn(a),c=Jn(s),d=t.cache&&Date.now();return t.cache&&Nn({userEntityMarkers:r,userFeedMarkers:c,feedMarkers:o,userMarkers:i},{cachedAt:d}),xt("local.feedMarker.fetched",{feedMarkers:o}),xt("local.channelMarker.fetched",{userEntityMarkers:r}),xt("local.subChannelMarker.fetched",{userFeedMarkers:c}),xt("local.userMarker.fetched",{userMarkers:i}),!0})(e)},qs=()=>{js=!1},xs=()=>(js=!0,bn((e=>{"notLoggedIn"===e&&qs()})),()=>{qs()});ks((async()=>{js&&await Ms()}),3e4);const Ks=async e=>{const t=Ge();t.log("channel/getSubChannels",e);const n=await t.http.get("/api/v5/message-feeds/list",{params:{messageFeedIds:e.map(encodeURIComponent)}}),a=await va(n.data),s=t.cache&&Date.now();return t.cache&&Nn(a,{cachedAt:s}),xt("local.message-feed.fetched",a),{data:a.messageFeeds,cachedAt:s}};Ks.locally=e=>{var t;const n=Ge();if(n.log("channel/getSubChannels.locally",e),!n.cache)return;const a=e.map((e=>nt(["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 Ns=async(e=!0)=>{var t;const n=null===(t=nt(["MessagePreviewSetting"]))||void 0===t?void 0:t.data;if(!e&&n)return n;const a=await Kn();var s;return(s=a).messagePreview.enabled?s.messagePreview.isIncludeDeleted?"message-preview-include-deleted":"message-preview-not-include-deleted":"no-message-preview"},Fs=async()=>{var e;const t=await Ns();if(t===(null===(e=nt(["MessagePreviewSetting"]))||void 0===e?void 0:e.data))return;at(["MessagePreviewSetting"],t);const n=[],a=[];if("no-message-preview"===t){const e=tt(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{it(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=tt(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{(null==t?void 0:t.isDeleted)&&(it(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&a.push(t.subChannelId))})),0!==n.length&&await Us(n),0!==a.length&&await Ks(a)}},_s=async()=>{const e=Ge(),{data:t}=await e.http.get("/api/v3/network-settings/social");return t.socialNetworkSetting},Bs=async()=>{const e=Ge(),{data:t}=await e.http.get("/api/v3/network-settings/users");return t},$s=async()=>{const e=Ge(),{data:t}=await e.http.get("/api/v3/network-settings/product");return t},Ls=async()=>{var e,t;const n=Ge(),{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}}},Qs=(e,t)=>{var n;const a=null===(n=nt(["user","get",e]))||void 0===n?void 0:n.data;return!!a&&a.permissions.some((e=>e===t))},Js=e=>{const{userId:t}=Ge();return{currentUser:()=>Qs(t,e),community:n=>((e,t,n)=>{var a;if(!e)return!1;const s=null===(a=nt(["communityUsers","get",`${n}#${e}`]))||void 0===a?void 0:a.data;return!!s&&(!!s.permissions.some((e=>e===t))||Qs(e,t))})(t,e,n),channel:n=>((e,t,n)=>{var a;if(!e)return!1;const s=null===(a=nt(["channelUsers","get",`${n}#${e}`]))||void 0===a?void 0:a.data;return!!s&&(!!s.permissions.some((e=>e===t))||Qs(e,t))})(t,e,n)}},Vs=async e=>{const t=Ge();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},Hs=async e=>{const t=Ge();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},zs=async()=>{const e=Ge(),{data:t}=await e.http.get("/api/v3/network-settings/feed-setting");return Object.fromEntries(t.feedSettings.map((({feedType:e,contentSettings:t})=>[e,t])))},Gs={notLoggedIn:["establishing"],terminated:["establishing"],establishing:["notLoggedIn","established"],established:["notLoggedIn","terminated","tokenExpired","establishing"],tokenExpired:["establishing"]},Ys=(e,t)=>{const n=Ge();n.log("client/api/setSessionState",e,t);const{sessionState:a}=n;if(a===e)return!1;if(!((e,t)=>Gs[e].includes(t))(a,e))throw new Le(`Session state cannot change from ${a} to ${e}`,8e5,"error");return n.sessionState=e,fn().setSessionState(e,t),!0};function Ws(e){return{users:e.users.map(ga),files:e.files}}const Xs=async e=>{const t=Ge();Ys("establishing");const{accessToken:n,users:a,expiresAt:s,issuedAt:o,userType:i,files:r}=await(async({params:e,options:t})=>{const n=Ge();n.log("client/api/getToken",e);const a=En(),{data:s}=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 s})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.upload.defaults.headers.common.Authorization=`Bearer ${n}`,t.upload.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:o,expiresAt:s},Ys("established"),Nn(Ws({users:a,files:r})),{accessToken:n,users:a,userType:i}},Zs=async e=>{const t=Ge();Ys("establishing");const{accessToken:n,users:a,expiresAt:s,issuedAt:o,userType:i,files:r}=await(async({params:e,options:t})=>{const n=Ge();n.log("client/api/getVisitorToken",e);const a=En(),{data:s}=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 s})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:o,expiresAt:s},Ys("established"),Nn(Ws({users:a,files:r})),{accessToken:n,users:a,userType:i}},eo=async()=>{var e;const t=Ge();return t.log("client/api/disconnectClient"),t.mqtt&&t.mqtt.connected&&t.mqtt.disconnect(),"established"===t.sessionState&&Ys("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},to=e=>{const t=Ge();Ys("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,eo()};let no=null;const ao=e=>{no=e},so=({user:e,userType:t})=>{Ut(e),ao(t)},oo=(e,t)=>{const n=Ge();return qt(n,e,e,(e=>{const a=Ws(e);n.cache&&Nn(a),t(a.users[0])}))},io=e=>oo("user.deleted",e),ro=["analytic","normal-priority"],co=["analytic","high-priority"],lo=async e=>{const t=Ge(),n={activities:e};await t.http.post("/api/v1/analytics/activities",n)};class uo{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=nt(ro);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await lo(t),it(ro)}catch(e){this.stop(),it(ro)}}async syncHighPriorityCapturedEvent(){try{const e=nt(co);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await lo(t),it(co)}catch(e){this.stop(),it(co)}}}class ho{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,s=n?this._recentHighPriorityViewed[e]:this._recentViewed[e];if(!s)return!0;return!(a.getTime()-s.getTime()<t)}markAs({uniqueId:e,contentId:t,contentType:n,activityType:a,metadata:s}){if(!this.isAbleToEnqueue({uniqueId:e,expireTime:this._expireTime}))return;const o=new Date,i={event:[]},r=nt(ro);(null==r?void 0:r.data)&&(i.event=r.data.event),i.event.length>=this._poolLimit&&i.event.shift();const c={contentId:t,contentType:n,activityType:a,timestamp:o.toISOString()};s&&(c.metadata=s),i.event.push(c),ot(ro,i),this._recentViewed[e]=o}markPostAsViewed(e){this.markAs({uniqueId:`post.${e}`,contentId:e,contentType:"post",activityType:"view"})}markPostAsMeaningfullyViewed(e,t){var n;const a=null===(n=nt(["feedMetadata","get",e]))||void 0===n?void 0:n.data,s={};void 0!==t&&(s.feedRenderPosition=t),a&&(s.feedSnapshotPosition=a.feedSnapshotPosition,s.feedInjectionType=a.feedInjectionType,s.feedRelevanceScore=a.feedRelevanceScore,s.feedPopularityScore=a.feedPopularityScore,s.feedFreshnessScore=a.feedFreshnessScore,s.feedAffinityScore=a.feedAffinityScore,s.feedFinalScore=a.feedFinalScore,s.feedMmrPenalty=a.feedMmrPenalty),this.markAs({uniqueId:`post.${e}.meaningfulView`,contentId:e,contentType:"post",activityType:"meaningfulView",metadata:Object.keys(s).length>0?s: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 s={event:[]},o=nt(co);if((null==o?void 0:o.data)&&(s.event=o.data.event),s.event.length>=this._poolLimit&&s.event.shift(),s.event.push({contentId:e.storyId,contentType:"story",activityType:t,timestamp:n.toISOString()}),ot(co,s),this._recentHighPriorityViewed[e.storyId]=n,"linkClicked"===t)return;at(["story-seen","get",e.storyId],(new Date).toISOString());const i=nt(["story-last-seen",e.targetId]);(null==i?void 0:i.data)?new Date(i.data).getTime()<new Date(e.expiresAt).getTime()&&at(["story-last-seen",e.targetId],e.expiresAt):at(["story-last-seen",e.targetId],e.expiresAt),this._bufferNewSeenStoryReferenceIds.push(e.referenceId),this._throttleStoryTimer||(this._throttleStoryTimer=setTimeout((()=>{clearTimeout(this._throttleStoryTimer),xt("local.story.reload",{referenceIds:this._bufferNewSeenStoryReferenceIds}),this._bufferNewSeenStoryReferenceIds=[]}),300))}resetAllBuckets(){this._recentViewed={},this._recentHighPriorityViewed={},it(ro),it(co)}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 s={location:t,sourceType:n,sourceId:a},o="linkClicked";this.markAs({uniqueId:`${e.productId}.linkClicked.${t}`,contentId:e.productId,contentType:"product",activityType:o,metadata:s})}markProductAsViewed(e,t,n,a){const s={location:t,sourceType:n,sourceId:a},o="view";this.markAs({uniqueId:`${e.productId}.view.${t}`,contentId:e.productId,contentType:"product",activityType:o,metadata:s})}}class mo{constructor(){this._client=Ge(),this._eventCapturer=new ho,this._eventSyncer=new uo}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 go;var po=()=>(go||(go=new mo),go),yo=()=>{const e=po();return e.established(),bn((t=>{"established"===t?e.established():e.handleTokenExpired()})),()=>{e.destroy()}};class vo{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=Ge(),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=tt(["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=nt(["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=Ge();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],s=null===(t=nt(a))||void 0===t?void 0:t.data;at(a,Object.assign(Object.assign({},s),{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],s=null===(n=nt(a))||void 0===n?void 0:n.data;s&&("number"!=typeof s.readToSegment||t>s.readToSegment)&&(s.readToSegment=t,s.unreadCount=Math.max(s.lastSegment-t,0),at(a,s),xt("local.channelUnread.updated",[s])),this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const a=null===(n=nt(["readReceipt",e]))||void 0===n?void 0:n.data;if(a){if(a.latestSegment<t)at(["readReceipt",e],Object.assign(Object.assign({},a),{latestSegment:t}));else if(a.latestSyncSegment>=t)return}else{at(["readReceipt",e],{channelId:e,latestSegment:t,latestSyncSegment:0})}let s=this.getSyncJob(e);null===s||"syncing"===s.syncState?(s={channelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(s)):s.segment<t&&(s.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 fo=null;var bo=()=>(fo||(fo=new vo),fo),Io=()=>{const e=bo();return e.startSyncReadReceipt(),bn((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};class Co{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=Ge(),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=tt(["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=nt(["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:s}=n,o=await(async({subChannelId:e,readToSegment:t})=>{const n=Ge();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:s});if(o){this.removeSynedReceipt(e.subChannelId,e.segment);const n=null===(t=nt(["legacyReadReceipt",a]))||void 0===t?void 0:t.data;at(["legacyReadReceipt",a],Object.assign(Object.assign({},n),{latestSyncSegment:s}))}else o||(n.retryCount>this.MAX_RETRY?this.removeJobFromQueue(n):(n.retryCount+=1,n.syncState="create"))}removeSynedReceipt(e,t){this.jobQueue.forEach((n=>{n.subChannelId===e&&n.segment<=t&&this.removeJobFromQueue(n)}))}startObservingReadReceiptQueue(){this.client.isUnreadCountEnabled&&(this.isActive=!0,this.startSyncReadReceipt())}stopObservingReadReceiptQueue(){this.isActive=!1;this.jobQueue.map((e=>"syncing"===e.syncState?Object.assign(Object.assign({},e),{syncState:"create"}):e)),this.timer&&clearInterval(this.timer)}onSessionEstablished(){this.startObservingReadReceiptQueue()}onSessionDestroyed(){this.stopObservingReadReceiptQueue(),this.jobQueue=[]}onTokenExpired(){this.stopObservingReadReceiptQueue()}onNetworkOffline(){this.stopObservingReadReceiptQueue()}onNetworkOnline(){this.startObservingReadReceiptQueue()}markRead(e,t){var n;const a=["subChannelUnreadInfo","get",e],s=null===(n=nt(a))||void 0===n?void 0:n.data;if(s&&t>s.readToSegment){s.readToSegment=t,s.unreadCount=Math.max(s.lastSegment-t,0);const e=ea(s.channelId);xt("local.channelUnreadInfo.updated",e),at(a,s),xt("local.subChannelUnread.updated",s)}this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const a=null===(n=nt(["legacyReadReceipt",e]))||void 0===n?void 0:n.data;if(a){if(a.latestSegment<t)at(["legacyReadReceipt",e],Object.assign(Object.assign({},a),{latestSegment:t}));else if(a.latestSyncSegment>=t)return}else{at(["legacyReadReceipt",e],{subChannelId:e,latestSegment:t,latestSyncSegment:0})}let s=this.getSyncJob(e);null===s||"syncing"===s.syncState?(s={subChannelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(s)):s.segment<t&&(s.segment=t)}getSyncJob(e){return this.jobQueue.find((t=>t.subChannelId===e))||null}enqueueJob(e){this.jobQueue.length<this.JOB_QUEUE_SIZE||this.jobQueue.shift(),this.jobQueue.push(e)}removeJobFromQueue(e){const t=this.jobQueue.indexOf(e);t>-1&&this.jobQueue.splice(t,1)}}let wo=null;var So=()=>(wo||(wo=new Co),wo),Oo=()=>{const e=So();return e.startSyncReadReceipt(),bn((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};const To=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")},Ao=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")},Ro=async e=>{const t=Ge();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=>{Re(null==t?void 0:t.code)&&Fn("channel",e)})),t}const s=await Da(a);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await ka(a);const o=t.cache&&Date.now();return t.cache&&Nn(s,{cachedAt:o}),xt("local.channel.fetched",s.channels),{data:s.channels,cachedAt:o}};Ro.locally=e=>{var t,n;const a=Ge();if(a.log("channel/getChannelByIds.locally",e),!a.cache)return;const s=null===(t=tt(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!s||(null==s?void 0:s.length)<e.length)return;return{data:s.map((({data:e})=>e)),cachedAt:(null===(n=s.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0]).cachedAt}};class Po{constructor(){this.TIMER_INTERVAL_MS=be,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(To((()=>{this.isConnected=!0}))),this.connectionListener.push(Ao((()=>{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 Ro(e);const s=null!==(a=null===(n=null===(t=tt(["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:[];xt("local.channel.resolved",s)})(e),t.length>0&&(async e=>{const t=await Ua(e),{feedMarkers:n,userFeedMarkers:a}=t;ta({feedMarkers:n,userFeedMarkers:a}),xt("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 Do=null;var Uo=()=>(Do||(Do=new Po),Do),ko=()=>{const e=Uo();return e.startResolver(),bn((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};class jo{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(To((()=>{this.isConnected=!0}))),this.connectionListener.push(Ao((()=>{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,s=_n(t,["roomId","streamId"]),o=a?"liveStream":"room",i=null!=a?a:n;return e[i]||(e[i]={referenceType:o,reactions:[]}),e[i].reactions.push(s),e}),{});Object.entries(t).forEach((([t,n])=>{(async({reactions:e,liveStreamId:t,roomId:n})=>{const a=Ge();a.log("live_reaction/addReaction",e);const{data:s}=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 Eo;var Mo=()=>(Eo||(Eo=new jo),Eo);function qo(e){const{users:t,follows:n}=e,a=_n(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 xo{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=Ge(),{data:t}=await e.http.get("/api/v4/me/user-blocks",{params:{options:{limit:100},isDeleted:!1}}),n=e.cache&&Date.now(),a=qo(t);e.cache&&Nn(a,{cachedAt:n}),this.lastFetchedAt=Date.now()}getCachedUsers(){var e;const t=Ge();if(!t.cache)return[];const{userId:n}=t;return(null!==(e=tt(["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=nt(["user","get",e.to]))||void 0===t?void 0:t.data})).filter((e=>null!=e&&!0!==e.isDeleted)).slice(0,100).map(_t)}}let Ko=null;var No=()=>(Ko||(Ko=new xo),Ko);function Fo(e){const{users:t,follows:n}=e,a=_n(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 _o{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=Ge(),{data:t}=await e.http.get("/api/v4/me/blockers",{params:{options:{limit:100},isDeleted:!1}}),n=e.cache&&Date.now(),a=Fo(t);e.cache&&Nn(a,{cachedAt:n}),this.lastFetchedAt=Date.now()}getCachedUsers(){var e;const t=Ge();if(!t.cache)return[];const{userId:n}=t;return(null!==(e=tt(["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=nt(["user","get",e.from]))||void 0===t?void 0:t.data})).filter((e=>null!=e&&!0!==e.isDeleted)).slice(0,100).map(_t)}}let Bo=null;var $o=()=>(Bo||(Bo=new _o),Bo);function Lo(e){const{users:t,follows:n}=e,a=_n(e,["users","follows"]);return Object.assign(Object.assign({},a),{follows:n,users:t.map(ga)})}function Qo(e){const{users:t,follows:n}=e,a=_n(e,["users","follows"]);return Object.assign(Object.assign({},a),{follows:n,users:t.map(ga)})}function Jo(e){const{follows:t}=e,n=_n(e,["follows"]);return Object.assign(Object.assign({},n),{follows:t})}const Vo=(e,t)=>{const n=Ge();return qt(n,e,e,(e=>{const a=Lo(e);n.cache&&Nn(a),t(a.follows[0])}))},Ho=e=>Vo("user.didBlock",e),zo=e=>Vo("user.didUnblock",e);class Go{constructor(e,t){this.networkId=e,this.userId=t}static current(){try{const e=Bt();if(!e)return null;const t=Qt(e),{userId:n}=e;return t&&n?new Go(t,n):null}catch(e){return null}}static isExpired(e){return Date.now()>=e}static clearOnLogout(){return bn((e=>{var t;"terminated"===e&&(null===(t=Go.current())||void 0===t||t.clear())}))}get key(){return`amity:forYouFeed:cursor:${this.networkId}:${this.userId}`}async get(){const e=await Dn(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 Pn(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 Pn(this.key,"")}}const Yo=["disconnected","error","connect_error","reconnect_error","reconnect_failed"],Wo=e=>{const t=Ge(),n=Yo.map((n=>qt(t,`client/onConnectionError(${n})`,n,(t=>{const a=(null==t?void 0:t.code)?new Le(t.message,t.code,"fatal"):new Ve(n);e(a)}))));return()=>{n.forEach((e=>e()))}},Xo=e=>{const t=Ge();return qt(t,"client/onConnectionError(user.didGlobalBan)","user.didGlobalBan",e)},Zo=e=>{const t=Ge();return qt(t,"client/onTokenExpired","tokenExpired",e)},ei=e=>{const t=Ge();return qt(t,"client/onTokenTerminated","tokenTerminated",e)},ti=e=>{const t=Xe("channelMarker")({userId:Dt()._id,entityId:e.channelId});it(["channelMarker","get",t],!0)},ni=e=>{const t=Ge(),n=[];return n.push(Xo((t=>{to("globalBan"),n.forEach((e=>e())),e()})),ei((t=>{to(),n.forEach((e=>e())),e()})),io((a=>{a.userId===t.userId&&(to("userDeleted"),n.forEach((e=>e())),e())})),Zo((e=>{fn().setSessionState(e),eo(),n.forEach((e=>e()))})),Ga(ti),ms(ti),xs(),yo(),ko(),(()=>{const e=Mo();return e.startReactionsSync(),bn((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=No();return bn((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=$o();return bn((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=[Ho((()=>{})),zo((()=>{}))];return()=>e.forEach((e=>e()))})(),bn((e=>{"established"!==e&&Tn().reset()})),Go.clearOnLogout()),t.useLegacyUnreadCount?n.push(Io()):n.push(Oo()),n};let ai=[];const si=async(e,t,n)=>{const a=Ge();let s;a.log("client/api/connectClient",Object.assign({apiKey:a.apiKey,sessionState:a.sessionState},e)),a.userId&&a.userId!==e.userId&&(await eo(),ai.forEach((e=>e())),ai=[]);const o=await jn();try{const{users:n,userType:i}=await Xs({params:Object.assign(Object.assign({},e),{displayName:null==e?void 0:e.displayName,deviceId:(null==e?void 0:e.deviceId)||o}),options:{setAccessTokenCookie:!0}}),r=n.find((t=>t.userId===e.userId));if(null==r)throw new Le(`${e.userId} has not been founded`,8e5,"error");if(r.isDeleted)return to("userDeleted"),!1;if(r.isGlobalBan)return to("globalBan"),!1;a.userId=r.userId,a.sessionHandler=t,a.loginType="userId",s=a.accessTokenExpiryWatcher(),so({user:r,userType:i})}catch(e){throw fn().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await Ft()}(),await Fs(),0===ai.length&&(ai=ni(s)),!0},oi=[],ii=async e=>{const t=Ge();let n;t.log("client/api/connectClient",Object.assign({apiKey:t.apiKey,sessionState:t.sessionState},e));const a=await jn();let s;try{const{users:o,userType:i}=await Zs({params:Object.assign(Object.assign({},e),{deviceId:a}),options:{setAccessTokenCookie:!0}});[s]=o,t.userId=s.userId,t.sessionHandler=e.sessionHandler,t.loginType="userId",n=t.accessTokenExpiryWatcher(),so({user:s,userType:i})}catch(e){throw fn().setSessionState("notLoggedIn"),e}return await Fs(),0===oi.length&&oi.push(ei((e=>{to(),oi.forEach((e=>e())),n()})),Zo((e=>{fn().setSessionState(e),eo(),oi.forEach((e=>e()))}))),!0},ri=()=>{let e,t=!1;const n=Ge();n.log("initiating access token renewal");const a=async a=>{const{userId:s,displayName:o}=Dt(),i={userId:s,displayName:o,authToken:a,deviceId:await jn()};"tokenExpired"===n.sessionState&&n.sessionHandler?await si(i,n.sessionHandler):await Xs({params:i,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(ri())}),Ie)},renewWithAuthSignature:a=>{t?console.log("'renew' method can be called only once per renewal instance"):(async({authSignature:a,authSignatureExpiresAt:s})=>{const o=await jn();"tokenExpired"===n.sessionState&&n.sessionHandler?await ii({sessionHandler:n.sessionHandler}):await Zs({params:{authSignature:a,authSignatureExpiresAt:s,deviceId:o},options:{setAccessTokenCookie:!0}}),t=!0,e&&clearTimeout(e)})(a)},unableToRetrieveAuthSignature:()=>{e=setTimeout((()=>{var e;null===(e=n.sessionHandler)||void 0===e||e.sessionWillRenewAccessToken(ri())}),Ie)}}},ci=async({token:e,userId:t})=>{const n=Ge();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}`}}),s=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,s},di=e=>{var t;const n=Ge(),a=A.default(e);return(null===(t=null==a?void 0:a.user)||void 0===t?void 0:t.publicUserId)===n.userId};let li=[];const ui=async e=>{var t,n;const a=Ge();let s,o;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{o=A.default(e)}catch(e){throw new Le("Invalid access token format",400100,"error")}const i=(null===(t=null==o?void 0:o.user)||void 0===t?void 0:t.publicUserId)||(null===(n=null==o?void 0:o.user)||void 0===n?void 0:n.userId);if(!i)throw new Le("Access token does not contain userId",400100,"error");if(a.userId){di(e)||await eo()}try{Ys("establishing");const t={accessToken:e,issuedAt:o.iat?new Date(1e3*o.iat).toISOString():(new Date).toISOString(),expiresAt:new Date(1e3*o.exp).toISOString()},n=await ci({token:t,userId:i});if(null==n)throw Ys("notLoggedIn"),new Le(`User ${i} has not been found`,8e5,"error");if(n.isDeleted)throw Ys("notLoggedIn"),new Le(`User ${i} has been deleted`,8e5,"error");if(n.isGlobalBanned)throw Ys("notLoggedIn"),new Le(`User ${i} is globally banned`,8e5,"error");a.userId=n.userId,a.loginType="accessToken",Ut(n),s=a.accessTokenExpiryWatcher(),Ys("established")}catch(e){if(Ys("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 Ft()}(),await Fs(),0===li.length&&(li=ni(s)),!0},hi=async e=>{var t,n;const a=Ge();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 s;try{s=A.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){di(e)||await eo()}const i={accessToken:e,issuedAt:s.iat?new Date(1e3*s.iat).toISOString():(new Date).toISOString(),expiresAt:new Date(1e3*s.exp).toISOString()};"tokenExpired"===a.sessionState&&a.sessionHandler?await ui(e):await ci({token:i,userId:o})},mi=async({useScheduledTask:e=!1})=>{const t=Ge();if(t.userId&&t.accessTokenHandler)try{const n=await t.accessTokenHandler.onTokenRenew(t.userId);e?Et((()=>hi(n))):hi(n)}catch(e){t.log("Proactive token renewal failed, will retry when token expires",e)}},gi=3e5,pi=()=>{const e=setInterval((async()=>{const e=Ge(),{sessionHandler:t,accessTokenHandler:n,loginType:a}=e;if(!e.token||!e.userId)return;const{issuedAt:s,expiresAt:o}=e.token;if((e=>Date.now()>Date.parse(e)-gi)(o))return xt("tokenExpired","tokenExpired"),void("accessToken"===a&&n?await mi({useScheduledTask:!1}):"userId"===a&&t&&Et((()=>t.sessionWillRenewAccessToken(ri()))));(e=>{const{expiresAt:t,issuedAt:n}=e,a=Date.parse(t),s=Date.parse(n),o=Date.now();return o>s+.8*(a-s-gi)&&o<a})({expiresAt:o,issuedAt:s})&&("accessToken"===a&&n?await mi({useScheduledTask:!1}):"userId"===a&&t&&t.sessionWillRenewAccessToken(ri()))}),Ie);return()=>clearInterval(e)},yi=e=>{if(Ge().useLegacyUnreadCount){bo().markRead(e.channelId,e.channelSegment)}else{So().markRead(e.subChannelId,e.channelSegment)}},vi=e=>{const t=Ge(),n=Dt(),a=[qt(t,"message/onMessageCreated","message.created",(async a=>{const s=await ua(a);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&a.messages.forEach((e=>{(e=>{var t;const n=Ge(),a=["subChannelUnreadInfo","get",e.messageFeedId],s=null===(t=nt(a))||void 0===t?void 0:t.data;if(!s)return;const o=s.lastSegment<e.segment?e.segment:s.lastSegment,i=o-s.readToSegment;let{lastMentionSegment:r}=s;e.mentionedUsers&&e.mentionedUsers.length>0&&e.mentionedUsers.forEach((t=>{("channel"===t.type||"user"===t.type&&n.userId&&t.userPublicIds.includes(n.userId))&&(r=e.segment)}));const c=Object.assign(Object.assign({},s),{lastMentionSegment:r,lastSegment:o,isMentioned:!(s.readToSegment>=r),unreadCount:Math.max(i,0)});at(a,c)})(e),ea(e.channelId)})),t.useLegacyUnreadCount&&a.messages.forEach((e=>{var n,a,s;const o=null===(n=nt(["channelUnread","get",e.channelId]))||void 0===n?void 0:n.data;if(!o||o.lastSegment>=e.segment)return;const i=e.segment,r=(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:o.lastMentionedSegment,c=null!==(s=o.readToSegment)&&void 0!==s?s:0,d=Object.assign(Object.assign({},o),{lastSegment:i,unreadCount:Math.max(i-c,0),lastMentionedSegment:r,isMentioned:"number"==typeof r&&c<r});at(["channelUnread","get",e.channelId],d),xt("local.channelUnread.updated",[d])})),Nn(s),s.messages.forEach((t=>{t.creatorPrivateId===n._id&&yi(t),e(t)}))}))];return()=>{a.forEach((e=>e()))}},fi=e=>{const t=Ge(),n=[qt(t,"message/onMessageCreated","local.message.created",(async t=>(Nn(t),t.messages.forEach((t=>{e(t)})))))];return()=>{n.forEach((e=>e()))}},bi=e=>{const t=Ge();return qt(t,"onSubChannelCreated","message-feed.created",(async n=>{const a=await va(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&n.messageFeeds.forEach((e=>{(e=>{const{channelId:t,subChannelId:n,createdAt:a,updatedAt:s}=e,o={channelId:t,subChannelId:n,unreadCount:0,readToSegment:0,lastMentionSegment:0,lastSegment:0,isMentioned:!1,isDeleted:!1,createdAt:a,updatedAt:s};at(["subChannelUnreadInfo","get",o.subChannelId],o)})({channelId:e.channelId,subChannelId:e.messageFeedId,createdAt:e.createdAt,updatedAt:e.updatedAt})})),Nn(a),e(a.messageFeeds[0])}))},Ii=e=>{const t=Ge(),n=[qt(t,"onSubChannelDeleted","message-feed.deleted",(async n=>{const a=await va(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&a.messageFeeds.forEach((e=>{(e=>{var t;const n=["subChannelUnreadInfo","get",e],a=null===(t=nt(n))||void 0===t?void 0:t.data;a&&at(n,Object.assign(Object.assign({},a),{isDeleted:!0}))})(e.subChannelId),ea(e.channelId)})),Nn(a),e(a.messageFeeds[0])})),qt(t,"local.message-feed.deleted","local.message-feed.deleted",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}},Ci=async e=>{const t=Ge();t.log("channel/markerSync");const{data:n}=await t.http.post("/api/v1/markers/sync",{deviceLastSyncAt:e}),{userEntityMarkers:a,userFeedMarkers:s,feedMarkers:o,userMarkers:i}=n,r=Qn(a),c=Jn(s),d=t.cache&&Date.now();return t.cache&&Nn({userEntityMarkers:r,userFeedMarkers:c,feedMarkers:o,userMarkers:i},{cachedAt:d}),xt("local.feedMarker.fetched",{feedMarkers:o}),xt("local.channelMarker.fetched",{userEntityMarkers:r}),xt("local.subChannelMarker.fetched",{userFeedMarkers:c}),xt("local.userMarker.fetched",{userMarkers:i}),{data:n,hasMore:n.feedMarkers.length>0}};let wi=!1,Si=[],Oi=!1;let Ti=null;let Ai=[];const Ri=e=>{Ai=e},Pi=async()=>{var e;if(!Oi&&0!==Ai.length)try{Oi=!0,Ai=[];const t=await Ci((null==Ti?new Date:Ti).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)&&(!Ti||e.getTime()>Ti.getTime())&&(Ti=e),t.hasMore&&Ai.push("has_more")}catch(e){}finally{Oi&&(Oi=!1)}};ks((async()=>{wi&&await Pi()}),2e3);const Di=()=>true,Ui=e=>{var t;const n=Ge();if(n.mqtt)return null===(t=n.mqtt)||void 0===t?void 0:t.listen(e)},ki=async()=>{const e=Ge(),t=await jn(),{data:{status:n,error:a}}=await e.http.delete("/v1/notification",{params:{deviceId:t},headers:{"X-API-Key":e.apiKey}});if(a)throw new Qe(a,5e5,"error");return"success"===n};let ji=[];var Ei;class Mi{constructor(){Ei.set(this,e.FileAccessTypeEnum.PUBLIC)}setFileAccessType(e){!function(e,t,n,a,s){if("m"===a)throw new TypeError("Private method is not writable");if("a"===a&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===a?s.call(e,n):s?s.value=n:t.set(e,n)}(this,Ei,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,Ei,"f")}}let qi;Ei=new WeakMap;var xi=()=>(qi||(qi=new Mi),qi);const Ki={[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"}},Ni=async e=>{const t=Ge();Ys("establishing");const{accessToken:n,users:a,expiresAt:s,issuedAt:o,userType:i,files:r}=await(async({params:e,options:t})=>{const n=Ge();n.log("client/api/getBotToken");const a=En(),{data:s}=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 s})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:o,expiresAt:s},Ys("established"),Nn(Ws({users:a,files:r})),{accessToken:n,users:a,userType:i}},Fi=[];function _i(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 Bi(t){return(null==t?void 0:t.type)===e.NotificationRolesFilterTypeEnum.ONLY?{listenFromRoleIds:t.roleIds}:{listenFromRoleIds:[]}}class $i{constructor(e){this.channelId=e}async enable(){const t=Ge(),n={level:e.NotificationSettingsLevelEnum.CHANNEL,channelId:this.channelId,isPushNotifiable:!0};await t.http.post("/api/v3/notification/setting",n)}async disable(){const t=Ge(),n={level:e.NotificationSettingsLevelEnum.CHANNEL,channelId:this.channelId,isPushNotifiable:!1};await t.http.post("/api/v3/notification/setting",n)}async getSettings(){const t=Ge(),{data:n}=await t.http.get(`/api/v3/notification/setting?level=${e.NotificationSettingsLevelEnum.CHANNEL}&channelId=${encodeURIComponent(this.channelId)}`);return{isEnabled:n.isPushNotifiable}}}class Li{async enable(t){var n;const a=Ge(),s=null!==(n=null==t?void 0:t.map((e=>Object.assign({moduleName:e.moduleName,isPushNotifiable:e.isEnabled},Bi(e.rolesFilter)))))&&void 0!==n?n:[],o={level:e.NotificationSettingsLevelEnum.USER,isPushNotifiable:!0,notifiableEvents:s};await a.http.post("/api/v3/notification/setting",o)}async disableAllNotifications(){const t=Ge(),n={level:e.NotificationSettingsLevelEnum.USER,isPushNotifiable:!1,notifiableEvents:[]};await t.http.post("/api/v3/notification/setting",n)}async getSettings(){var t;const n=Ge(),{data:a}=await n.http.get(`/api/v3/notification/setting?level=${e.NotificationSettingsLevelEnum.USER}`),s=Object.values(e.UserNotificationModuleNameEnum),o=(null!==(t=a.notifiableEvents)&&void 0!==t?t:[]).filter((e=>null!=e.moduleName&&s.includes(e.moduleName))).map((e=>({moduleName:e.moduleName,isEnabled:e.isPushNotifiable,rolesFilter:_i(e.listenFromRoleIds,e.ignoreFromRoleIds)})));return{isEnabled:a.isPushNotifiable,modules:o}}}class Qi{constructor(e){this.communityId=e}async enable(t){var n;const a=Ge(),s=null!==(n=null==t?void 0:t.map((t=>Object.assign({moduleName:e.UserNotificationModuleNameEnum.SOCIAL,name:t.eventName,isPushNotifiable:t.isEnabled},Bi(t.rolesFilter)))))&&void 0!==n?n:[],o={level:e.NotificationSettingsLevelEnum.COMMUNITY,communityId:this.communityId,isPushNotifiable:!0,notifiableEvents:s};await a.http.post("/api/v3/notification/setting",o)}async disable(){const t=Ge(),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=Ge(),{data:a}=await n.http.get(`/api/v3/notification/setting?level=${e.NotificationSettingsLevelEnum.COMMUNITY}&communityId=${encodeURIComponent(this.communityId)}`),s=Object.values(e.CommunityNotificationEventNameEnum),o=(null!==(t=a.notifiableEvents)&&void 0!==t?t:[]).filter((e=>null!=e.name&&s.includes(e.name))).map((e=>({eventName:e.name,isEnabled:e.isPushNotifiable,isNetworkEnabled:e.isNetworkEnabled,rolesFilter:_i(e.listenFromRoleIds,e.ignoreFromRoleIds)})));return{isEnabled:a.isPushNotifiable,events:o}}}class Ji{user(){return new Li}community(e){return new Qi(e)}channel(e){return new $i(e)}}const Vi=e=>{const t=Ge();return qt(t,"channelMarker/onChannelMarkerFetched","local.channelMarker.fetched",(t=>{t.userEntityMarkers.forEach((t=>{e(t)}))}))},Hi=e=>{const t=Ge();return qt(t,"subChannelMarker/onSubChannelMarkerFetched","local.subChannelMarker.fetched",(t=>{t.userFeedMarkers.forEach(e)}))},zi=e=>{const t=Ge();return qt(t,"subChannelMarker/onSubChannelMarkerUpdated","local.subChannelMarker.updated",(t=>{e(t.userFeedMarkers)}))},Gi=e=>{const t=Ge();return qt(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers)}))},Yi=e=>{const t=Ge();return qt(t,"messageMarker/onMessageMarkerFetched","local.messageMarker.fetched",(t=>{e(t.contentMarkers[0])}))},Wi=e=>{const t=Ge();return qt(t,"messageMarker/onMessageMarked","marker.marked-message",(t=>{var n,a,s;Nn(t);const o=tt(["message","collection"]),{contentMarkers:i,feedMarkers:r}=t;if(o&&(null==o?void 0:o.length)>0&&(null==r?void 0:r.length)>0){const e=o.filter((e=>{var t,n;return(null===(n=null===(t=e.data)||void 0===t?void 0:t.query)||void 0===n?void 0:n.subChannelId)===r[0].feedId}));if(e.length>0&&(null==i?void 0:i.length)>0){(null!==(s=null===(a=null===(n=e[0].data)||void 0===n?void 0:n.data)||void 0===a?void 0:a.map((e=>nt(["message","get",e]))).map((({data:e})=>e)).filter(Boolean))&&void 0!==s?s:[]).forEach((e=>{var t,n;const a=["messageMarker","get",Xe("messageMarker")({creatorId:e.creatorPrivateId,feedId:e.subChannelId,contentId:e.messageId})],s=null===(t=nt(a))||void 0===t?void 0:t.data;if(!s)return;const o=i[0].feedId===s.feedId,r=i[0].readCount>s.readCount,c=(null===(n=i[0])||void 0===n?void 0:n.deliveredCount)>s.deliveredCount;if(o){const e=Object.assign(Object.assign({},s),{readCount:r?i[0].readCount:s.readCount,deliveredCount:c?i[0].deliveredCount:s.deliveredCount});at(a,e)}}))}}e(t.contentMarkers[0])}))};function Xi(e){return"object"==typeof e&&null!==e}const Zi=e=>{if(!Xi(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)},er=e=>{if(!Xi(e))return e;const t=Object.entries(e).map((([e,t])=>"function"==typeof t?[e,void 0]:[e,t]));return Object.fromEntries(t)};var tr=Object.freeze({__proto__:null,getActiveClient:Ge,getActiveUser:Dt,setActiveUser:Ut,createClient:(e,t=sn.SG,{debugSession:n="amity",apiEndpoint:a,prefixDeviceIdKey:s,rteEnabled:o=!0}={})=>{var i,r,c;const d=(e=>{const t=`${null==e?void 0:e.trim()}`.length>0&&!an,n=I.default(e),a=(e,...a)=>{t&&n(e,a)};return a.__instance__=n,a})(n);d("client/api/createClient",{apiKey:e.replace(/.{5}$/g,"xxxxx"),apiRegion:t});const l=null!==(i=null==a?void 0:a.http)&&void 0!==i?i:rn("http",t),u=null!==(r=null==a?void 0:a.upload)&&void 0!==r?r:rn("upload",t),h=null!==(c=null==a?void 0:a.mqtt)&&void 0!==c?c:rn("mqtt",t),m=pn(l),g=pn(u);let p;o&&(p=xn(h));const y=b.default(),v={version:`${he}`,apiKey:e,log:d,cache:{data:{}},http:m,ws:undefined,mqtt:p,upload:g,emitter:y,sessionState:"notLoggedIn",accessTokenExpiryWatcher:pi,sessionHandler:undefined,hasPermission:Js,validateUrls:Vs,validateTexts:Hs,getFeedSettings:zs,getCoreUserSettings:Bs,getSocialSettings:_s,getChatSettings:Kn,getVisitorDeviceId:jn,getMessagePreviewSetting:Ns,onRTEConnectionStateChange:Ui,use:()=>Ye(v),isUnreadCountEnabled:!1,useLegacyUnreadCount:!0,getMarkerSyncConsistentMode:Di,getProductCatalogueSetting:$s,getForYouFeedSetting:Ls,prefixDeviceIdKey:s};try{const t=Ge();if(t.apiKey===e)return t;Ye(v)}catch(e){Ye(v)}return v},login:si,loginWithAccessToken:ui,logout:eo,secureLogout:async()=>{const e=Ge();try{await ki()}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 eo()},resumeSession:async(e,t,n)=>{const a=Ge();let s;a.log("client/api/resumeSession",Object.assign({apiKey:a.apiKey,sessionState:a.sessionState},e)),a.userId&&(a.userId===e.userId&&di(e.token.accessToken)?(a.mqtt&&a.mqtt.connected&&a.mqtt.disconnect(),ji.forEach((e=>e())),ji=[]):(await eo(),ji.forEach((e=>e())),ji=[]));try{Ys("establishing");const n=await ci(e);if(null==n)throw new Le(`${e.userId} has not been found`,8e5,"error");if(n.isDeleted)return to("userDeleted"),!1;if(n.isGlobalBanned)return to("globalBan"),!1;a.userId=n.userId,a.sessionHandler=t,s=a.accessTokenExpiryWatcher(t),Ut(n)}catch(e){throw fn().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await Ft()}(),await Fs(),0===ji.length&&(ji.push(Xo((e=>{to("globalBan"),ji.forEach((e=>e())),s()})),ei((e=>{to(),ji.forEach((e=>e())),s()})),io((e=>{e.userId===a.userId&&(to("userDeleted"),ji.forEach((e=>e())),s())})),Zo((e=>{fn().setSessionState(e),eo(),ji.forEach((e=>e()))})),Ga(ti),ms(ti),xs(),yo(),ko()),a.useLegacyUnreadCount?ji.push(Io()):ji.push(Oo())),!0},isConnected:()=>{var e,t;const n=Ge();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:zs,renewal:ri,markerSync:Ci,enableUnreadCount:()=>!0,setUploadedFileAccessType:function(e){xi().setFileAccessType(e)},registerPushNotification:async e=>{const t=Ge();let n;if("ios"!==l.Platform.OS&&"android"!==l.Platform.OS)throw new He("Unsupported platform");n=l.Platform.OS;const a=await jn(),{data:{status:s,error:o}}=await t.http.post("/v1/notification",{userId:t.userId,deviceId:a,platform:n,token:e},{headers:{"X-API-Key":t.apiKey}});if(o)throw new Qe(o,5e5,"error");return"success"===s},unregisterPushNotification:ki,onRTEConnectionStateChange:Ui,fetchLinkPreview:async e=>{const t=Ge();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=Ge(),{data:n}=await t.http.get(`/api/v1/link-preview?url=${e}`);return n},getSocialSettings:_s,getShareableLinkConfiguration:async()=>{var e,t;const n=Ge(),{data:a}=await n.http.get("/api/v3/network-settings/shareable-deep-links"),s=null!==(e=a.domain)&&void 0!==e?e:"",o=null!==(t=a.patterns)&&void 0!==t?t:{};return{domain:s,patterns:o,isEnabled(e){const{key:t}=Ki[e];return!!s&&!!o[t]},getPattern(e){const{key:t}=Ki[e];return o[t]||null},generateLink(e,t){const{key:n,placeholder:a}=Ki[e];return s&&o[n]?s+o[n].replace(`{${a}}`,t):null}}},getProductCatalogueSetting:$s,getForYouFeedSetting:Ls,loginAsVisitor:ii,loginAsBot:async e=>{const t=Ge();let n;t.log("client/api/connectClient",{apiKey:t.apiKey,sessionState:t.sessionState});const a=await jn();let s;try{const{users:o,userType:i}=await Ni({params:{deviceId:a},options:{setAccessTokenCookie:!0}});[s]=o,t.userId=s.userId,t.sessionHandler=e.sessionHandler,t.loginType="userId",n=t.accessTokenExpiryWatcher(),so({user:s,userType:i})}catch(e){throw fn().setSessionState("notLoggedIn"),e}return await Fs(),0===Fi.length&&Fi.push(ei((e=>{to(),Fi.forEach((e=>e())),n()})),Zo((e=>{fn().setSessionState(e),eo(),Fi.forEach((e=>e()))}))),!0},getCurrentUser:Bt,getCurrentUserType:()=>{if(!no)throw new Le("Connect client first",8e5,"fatal");return no},setCurrentUserType:ao,setAccessTokenHandler:e=>{const t=Ge();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:Kn,getCoreUserSettings:Bs,notifications:()=>new Ji,enableAutoSubscriptions:e=>{const t=Tn();e.forEach((e=>t.subscribe(e)))},disableAutoSubscriptions:e=>{const t=Tn();e.forEach((e=>t.unsubscribe(e)))},autoSubscriptions:()=>Tn().subscriptions(),onConnectionError:Wo,onClientDisconnected:e=>Wo((({code:t})=>{800211===t&&e()})),onClientBanned:Xo,onSessionStateChange:bn,onNetworkActivities:e=>un().onNetworkActivities(e),onVisitorUsageLimitReached:e=>{const t=Ge();return qt(t,"client/onVisitorUsageLimitReached","visitorUsageLimitReached",e)},getUserUnread:e=>{const{_id:t}=Dt();if(!t)throw new Le("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:a}=Ge();a||console.log("For using Live Object feature you need to enable Cache!");n(`liveUserUnread(tmpid: ${Date.now()}) > listen`);const s=[];let o,i=!1;const r=t=>{const{data:n}=t,a=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;o=a?Zi(a):a,e({data:a?Object.assign(Object.assign({},a),{isMentioned:a.isMentioned}):a,loading:t.loading,error:t.error})};return s.push(Gi((e=>(e=>{var n;const a=e.filter((e=>t===e.userId)),s=a.reduce(((e,t)=>null==e||new Date(t.lastSyncAt).getTime()>new Date(e.lastSyncAt).getTime()?t:e),null),i={unreadCount:null!==(n=null==s?void 0:s.unreadCount)&&void 0!==n?n:0,isMentioned:a.some((e=>!!e.isMentioned))};Na(o,i)||r({loading:!1,data:i})})(e)))),(()=>{const e=Fe(na);Be(e,(({error:e,data:t,loading:n,origin:a,cachedAt:o})=>{!function(e){return null!=e&&null!=e}(t)?r({loading:n,data:void 0,origin:a,error:e}):(o===fe?(r({data:t,origin:a,loading:!1,error:new Qe(ve,800800,"error")}),i=!0,s.forEach((e=>e()))):i||r({loading:n,data:t,origin:a,error:e}),e&&s.forEach((e=>e())))}))})(),()=>{s.forEach((e=>e()))}},getMarkerSyncEvents:()=>Ai,setMarkerSyncEvents:Ri,pushMarkerSyncEvent:e=>Ai.push(e),markerSyncTrigger:Pi,startMarkerSync:async()=>Promise.resolve(),startUnreadSync:async()=>Promise.resolve(),stopUnreadSync:()=>{wi=!1,Ri([]),Si.forEach((e=>e())),Si=[]},getMarkerSyncConsistentMode:Di});const nr=(e,t)=>{const n=Ge();return qt(n,e,e,(e=>{const a=Lo(e);n.cache?(Nn(a),t(a.follows[0])):t(a.follows[0])}))},ar=(e,t)=>{const n=Ge();return qt(n,e,e,(e=>{const a=Jo(e);n.cache?(Nn(a),t(a.follows[0])):t(a.follows[0])}))},sr=e=>nr("follow.created",e),or=e=>nr("follow.unfollowed",e),ir=e=>nr("follow.followerDeleted",e),rr=e=>nr("follow.requested",e),cr=e=>nr("follow.requestCanceled",e),dr=e=>nr("follow.accepted",e),lr=e=>nr("follow.requestDeclined",e),ur=async e=>{var t,n;const a=Ge();a.log("follow/getFollowInfo",e);const{data:s}=await a.http.get(a.userId===e?"/api/v4/me/followInfo":`/api/v5/users/${e}/followInfo`),o=a.cache&&Date.now(),i="follows"in s?Object.assign(Object.assign({},s.followCounts[0]),{status:null===(n=null===(t=s.follows)||void 0===t?void 0:t[0])||void 0===n?void 0:n.status}):s.followCounts[0];return a.cache&&at(["followInfo","get",e],i,{cachedAt:o}),{data:i,cachedAt:o}};ur.locally=e=>{const t=Ge();if(t.log("follow/getFollowInfo.locally",e),!t.cache)return;const n=nt(["followInfo","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const hr=e=>{const t=async t=>{const[{data:n},{data:a}]=await Promise.all([ur(t.from),ur(t.to)]);e(n),e(a)},n=[nr("follow.created",t),nr("follow.requested",t),nr("follow.accepted",t),nr("follow.unfollowed",t),nr("follow.requestCanceled",t),nr("follow.requestDeclined",t),nr("follow.followerDeleted",t),ar("local.follow.created",t),ar("local.follow.requested",t),ar("local.follow.accepted",t),ar("local.follow.unfollowed",t),ar("local.follow.requestDeclined",t)];return()=>{n.forEach((e=>e()))}},mr=e=>ar("local.follow.created",e),gr=e=>ar("local.follow.unfollowed",e),pr=e=>ar("local.follow.requested",e),yr=e=>ar("local.follow.accepted",e),vr=e=>ar("local.follow.requestDeclined",e);class fr{constructor(e){const{http:t}=Ge();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,s;if("prev"===e&&!this.previousToken)return;if("next"===e&&!this.nextToken)return;let o;"prev"===e&&(o=this.previousToken),"next"===e&&(o=this.nextToken);const i=await this.getRequest(this.queryParams,o);return"first"===e&&(this.nextToken=null===(t=i.paging)||void 0===t?void 0:t.next,this.previousToken=null===(n=i.paging)||void 0===n?void 0:n.previous),"prev"===e&&(this.previousToken=null===(a=i.paging)||void 0===a?void 0:a.previous),"next"===e&&(this.nextToken=null===(s=i.paging)||void 0===s?void 0:s.next),i}getNextToken(){return this.nextToken}getPrevToken(){return this.previousToken}}class br extends fr{async getRequest(e,t){const{limit:n=me,userId:a}=e,s=_n(e,["limit","userId"]),o=t?{token:t}:{limit:n},i=Ge().userId===a?"/api/v4/me/followers":`/api/v4/users/${a}/followers`,{data:r}=await this.http.get(i,{params:Object.assign(Object.assign({},s),{options:o,isDeleted:!1})});return r}}class Ir{constructor(e,t){this.query=e,this.cacheKey=t}}var Cr;!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"}(Cr||(Cr={}));class wr extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.follows.map(Xe("follow"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(Xe("follow"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.to&&a){switch(e){case Cr.OnDeclined:case Cr.OnCanceled:case Cr.OnUnfollowed:case Cr.OnDeleted:a.data=a.data.filter((e=>e!==Xe("follow")(t)));break;case Cr.OnRequested:case Cr.OnAccepted:case Cr.OnFollowed:a.data=[...new Set([Xe("follow")(t),...a.data])]}at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Sr{constructor(e){const{http:t}=Ge();this.queryParams=e,this.http=t}async onFetch(){return await this.getRequest(this.queryParams)}}class Or{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 Sr?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 Sr)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 Sr)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(Zi).map(er);return!Na(this.snapshot,t)&&(this.snapshot=t,!0)}getCacheKey(){return this.cacheKey}}function Tr(e){return null!=e}const Ar=({userId:e})=>t=>{const n=Ge();return qt(n,"user.deleted","user.deleted",(n=>{const a=Ws(n);Nn(a);const s=nt(["follow","get",Xe("follow")({from:a.users[0].userId,to:e})]);s&&t(null==s?void 0:s.data)}))};class Rr extends Or{constructor(e,t){const n=R.default(Object.assign(Object.assign({},e),{type:"follower"})),a=["follow","collection",n];super(new br(e),n,a,t),this.query=e,this.queryStreamController=new wr(this.query,this.cacheKey,this.notifyChange.bind(this),Lo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:sr,action:Cr.OnFollowed},{fn:or,action:Cr.OnUnfollowed},{fn:dr,action:Cr.OnAccepted},{fn:lr,action:Cr.OnDeclined},{fn:cr,action:Cr.OnCanceled},{fn:ir,action:Cr.OnDeleted},{fn:yr,action:Cr.OnAccepted},{fn:vr,action:Cr.OnDeclined},{fn:mr,action:Cr.OnFollowed},{fn:gr,action:Cr.OnUnfollowed},{fn:Ar({userId:this.query.userId}),action:Cr.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["follow","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,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=nt(["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 Pr extends fr{async getRequest(e,t){const{limit:n=me,userId:a}=e,s=_n(e,["limit","userId"]),o=t?{token:t}:{limit:n},i=Ge().userId===a?"/api/v4/me/following":`/api/v4/users/${a}/following`,{data:r}=await this.http.get(i,{params:Object.assign(Object.assign({},s),{options:o,isDeleted:!1})});return r}}class Dr extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.follows.map(Xe("follow"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(Xe("follow"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.from&&a){switch(e){case Cr.OnDeclined:case Cr.OnCanceled:case Cr.OnUnfollowed:case Cr.OnDeleted:a.data=a.data.filter((e=>e!==Xe("follow")(t)));break;case Cr.OnRequested:case Cr.OnAccepted:case Cr.OnFollowed:a.data=[...new Set([Xe("follow")(t),...a.data])]}at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Ur=({userId:e})=>t=>{const n=Ge();return qt(n,"user.deleted","user.deleted",(n=>{const a=Ws(n);Nn(a);const s=nt(["follow","get",Xe("follow")({from:e,to:a.users[0].userId})]);s&&t(null==s?void 0:s.data)}))};class kr extends Or{constructor(e,t){const n=R.default(Object.assign(Object.assign({},e),{type:"following"})),a=["follow","collection",n];super(new Pr(e),n,a,t),this.query=e,this.queryStreamController=new Dr(this.query,this.cacheKey,this.notifyChange.bind(this),Qo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:rr,action:Cr.OnRequested},{fn:dr,action:Cr.OnAccepted},{fn:lr,action:Cr.OnDeclined},{fn:cr,action:Cr.OnCanceled},{fn:sr,action:Cr.OnFollowed},{fn:or,action:Cr.OnUnfollowed},{fn:ir,action:Cr.OnDeleted},{fn:pr,action:Cr.OnRequested},{fn:yr,action:Cr.OnAccepted},{fn:vr,action:Cr.OnDeclined},{fn:mr,action:Cr.OnFollowed},{fn:gr,action:Cr.OnUnfollowed},{fn:Ur({userId:this.query.userId}),action:Cr.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["follow","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,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=nt(["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 jr=(e,t,n,a,s,o)=>{const{forceDispatch:i,callbackDataSelector:r,callbackFilter:c}=Object.assign({forceDispatch:!1,callbackDataSelector:e=>e},o),{cache:d}=Ge();let l;d||console.log("For using Live Object feature you need to enable Cache!");let u=!1;const h=[],m=e=>{const{data:n}=e,a=_n(e,["data"]);c&&!c(n,l)||t(Object.assign({data:r(n)},a)),l=Zi(n)};return h.push(...s.map((t=>t((t=>((t,a=!1)=>{e===t[n]&&(l&&!a&&Na(l,t)||m({loading:!1,data:t,origin:"event"}))})(t,i)))))),(()=>{const t=Fe(a,e,!0);Be(t,(({error:e,data:t,loading:n,origin:a,cachedAt:s})=>{s===fe?(m({data:t,origin:a,loading:!1,error:new Qe(ve,800800,"error")}),u=!0,h.forEach((e=>e()))):u||m({loading:n,data:t,origin:a,error:e}),e&&h.forEach((e=>e()))}))})(),()=>{h.forEach((e=>e()))}};var Er=Object.freeze({__proto__:null,blockUser:async e=>{const t=Ge();t.log("user/blockUser",e);const{data:n}=await t.http.post(`/api/v4/me/user-blocks/${e}`),a=t.cache&&Date.now(),{follows:s,followCounts:o}=n,i={follows:s};t.cache&&(Nn(i,{cachedAt:a}),ot(["followInfo","get",e],o[0],{cachedAt:a}));const r={follows:s.map((e=>{const t=Object.assign(Object.assign({},e),{to:e.from,from:e.to,status:"none"});return"blocked"===e.status?t:e}))},c=Jo(r);return xt("local.follow.unfollowed",c),n},unBlockUser:async e=>{const t=Ge();t.log("user/unBlockUser",e);const{data:n}=await t.http.delete(`/api/v4/me/user-blocks/${e}`),a=t.cache&&Date.now(),{follows:s,followCounts:o}=n,i={follows:s};t.cache&&(Nn(i,{cachedAt:a}),ot(["followInfo","get",e],o[0],{cachedAt:a}));const r=Jo(i);return xt("local.follow.created",r),n},onUserDidBlock:Ho,onUserDidUnblock:zo,follow:async e=>{const t=Ge();t.log("follow/follow",e);const{data:n}=await t.http.post(`/api/v4/me/following/${e}`),a=t.cache&&Date.now();t.cache&&Nn(n,{cachedAt:a});const s=Jo(n);return"accepted"===n.follows[0].status?xt("local.follow.created",s):xt("local.follow.requested",s),{data:n.follows[0],cachedAt:a}},unfollow:async e=>{const t=Ge();t.log("follow/unfollow",e);const{data:n}=await t.http.delete(`/api/v4/me/following/${e}`);t.cache&&Nn(n);const a=Jo(n);return xt("local.follow.unfollowed",a),!0},acceptMyFollower:async e=>{const t=Ge();t.log("follow/acceptMyFollower",e);const{data:n}=await t.http.post(`/api/v4/me/followers/${e}`);t.cache&&Nn(n);const a=Jo(n);return xt("local.follow.accepted",a),!0},declineMyFollower:async e=>{const t=Ge();t.log("follow/declineMyFollower",e);const{data:n}=await t.http.delete(`/api/v4/me/followers/${e}`);t.cache&&Nn(n);const a=Jo(n);return xt("local.follow.requestDeclined",a),!0},onUserFollowed:sr,onUserUnfollowed:or,onFollowerDeleted:ir,onFollowerRequested:rr,onFollowRequestCanceled:cr,onFollowRequestAccepted:dr,onFollowRequestDeclined:lr,onFollowInfoUpdated:hr,onLocalUserFollowed:mr,onLocalUserUnfollowed:gr,onLocalFollowerRequested:pr,onLocalFollowRequestAccepted:yr,onLocalFollowRequestDeclined:vr,getFollowers:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getFollowers(tmpid: ${o}) > listen`);const i=new Rr(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getFollowers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getFollowings:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log("For using Live Collection feature you need to enable Cache!");const o=Date.now();a(`getFollowings(tmpid: ${o}) > listen`);const i=new kr(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getFollowings(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getFollowInfo:(e,t)=>jr(e,t,"userId",ur,[hr],{forceDispatch:!0}),getMyFollowInfo:e=>{const{userId:t}=Dt();return jr(t,e,"userId",ur,[hr],{forceDispatch:!0})}});function Mr(e,t){return e.map((e=>{const n=nt(["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}=Dt();return e.communityId===t.communityId&&t.userId===n}(e,t)&&"none"!==t.communityMembership));return Object.assign(Object.assign({},e),{isJoined:a})}))}const qr=e=>{var t;return null!==(t=Object.keys(x).find((t=>e.needApprovalOnPostCreation===x[t].needApprovalOnPostCreation&&e.onlyAdminCanPost===x[t].onlyAdminCanPost)))&&void 0!==t?t:K};function xr({communities:e}){return e.map((e=>{var{needApprovalOnPostCreation:t,onlyAdminCanPost:n}=e,a=_n(e,["needApprovalOnPostCreation","onlyAdminCanPost"]);return Object.assign({postSetting:qr({needApprovalOnPostCreation:t,onlyAdminCanPost:n})},a)}))}const Kr=e=>{const t=xr({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})})),s=Mr(t,a);return Object.assign(Object.assign({},e),{users:e.users.map(ga),communities:s,communityUsers:a})},Nr=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})},Fr=e=>{const t=xr({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=Mr(t,n);return Object.assign(Object.assign({},e),{communities:a,communityUsers:n})},_r=e=>{const{postSetting:t,storySetting:n}=e,a=_n(e,["postSetting","storySetting"]);return Object.assign(Object.assign(Object.assign({},a),t?x[t]:void 0),{allowCommentInStory:"boolean"!=typeof(null==n?void 0:n.enableComment)||n.enableComment})},Br=e=>{var t=_n(e,["searchResult"]);const n=Kr(t);return Object.assign({},n)},$r=e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=nt(["user","get",e.requestorPublicId]))||void 0===t?void 0:t.data;if(n)return _t(n)},cancel:async()=>{await(async e=>{var t;const n=Ge();n.log("joinRequest/cancelJoinRequest",e.joinRequestId);const{data:a}=await n.http.delete(`/api/v4/communities/${e.targetId}/join`),s=null===(t=nt(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return s&&(ot(["joinRequest","get",e.joinRequestId],{status:"cancelled"}),xt("local.joinRequest.deleted",[s])),a.success})(e)},approve:async()=>{await(async e=>{var t;const n=Ge();n.log("joinRequest/approveJoinRequest",e.joinRequestId);const{data:a}=await n.http.post(`/api/v4/communities/${e.targetId}/join/approve`,{userId:e.requestorInternalId}),s=null===(t=nt(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return s&&(ot(["joinRequest","get",e.joinRequestId],{status:"approved"}),xt("local.joinRequest.updated",[s])),a.success})(e)},reject:async()=>{await(async e=>{var t;const n=Ge();n.log("joinRequest/rejectJoinRequest",e.joinRequestId);const{data:a}=await n.http.post(`/api/v4/communities/${e.targetId}/join/reject`,{userId:e.requestorInternalId}),s=null===(t=nt(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return s&&(ot(["joinRequest","get",e.joinRequestId],{status:"rejected"}),xt("local.joinRequest.updated",[s])),a.success})(e)}});class Lr extends fr{async getRequest(e,t){const{limit:n=20,communityId:a}=e,s=_n(e,["limit","communityId"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get(`/api/v4/communities/${a}/join`,{params:Object.assign(Object.assign({},s),{options:o})});return i}}var Qr;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(Qr||(Qr={}));class Jr extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.joinRequests.map((e=>Xe("joinRequest")({joinRequestId:e._id})))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>Xe("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===Qr.OnLocalJoinRequestUpdated){if(!a.data.find((e=>e===t[0].joinRequestId)))return}e===Qr.OnLocalJoinRequestCreated&&(a.data=[...new Set([...t.map((e=>e.joinRequestId)),...a.data])]),e===Qr.OnLocalJoinRequestDeleted&&(a.data=a.data.filter((e=>e!==t[0].joinRequestId))),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Vr=e=>{const t=Ge(),n=[qt(t,"onJoinRequestCreated","local.joinRequest.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Hr=e=>{const t=Ge(),n=[qt(t,"onJoinRequestUpdated","local.joinRequest.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},zr=e=>{const t=Ge(),n=[qt(t,"onJoinRequestDeleted","local.joinRequest.deleted",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class Gr extends Or{constructor(e,t){const n=R.default(e),a=["joinRequest","collection",n];super(new Lr(e),n,a,t),this.query=e,this.queryStreamController=new Jr(this.query,this.cacheKey,this.notifyChange.bind(this),Nr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:Vr,action:Qr.OnLocalJoinRequestCreated},{fn:Hr,action:Qr.OnLocalJoinRequestUpdated},{fn:zr,action:Qr.OnLocalJoinRequestDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a;const s=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(s.data.map((e=>nt(["joinRequest","get",e]))).filter(Tr).map((({data:e})=>e)).map($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.status&&(t=t.filter((e=>e.status===this.query.status)));const n=(()=>"firstCreated"===this.query.sortBy?It:wt)();return t=t.sort(n),t}}const Yr=e=>Object.assign(Object.assign({},e),{createdById:e.createdBy}),Wr=e=>Object.assign(Object.assign({},e),{invitations:e.invitations.map(Yr),users:e.users.map(ga)}),Xr=async e=>{const t=Ge();t.log("invitation/createInvitations",e);const{data:n}=await t.http.post("/api/v1/invitations",e),a=Wr(n),s=t.cache&&Date.now();return t.cache&&Nn(a,{cachedAt:s}),xt("local.invitation.created",a.invitations),{data:a.invitations,cachedAt:s}},Zr=e=>Object.assign(Object.assign({},e),{users:e.users.map(ga),invitations:e.invitations.map(Yr)}),ec=e=>Object.assign(Object.assign({},e),{get user(){const t=nt(["user","get",e.invitedUserPublicId]);if(null==t?void 0:t.data)return _t(t.data)},get createdBy(){const t=nt(["user","get",e.inviterUserPublicId]);if(null==t?void 0:t.data)return _t(t.data)},get target(){if("community"===e.targetType){const t=nt(["community","get",e.targetId]);return(null==t?void 0:t.data)?t.data:void 0}},accept:async()=>{await(async e=>{var t;const n=Ge();n.log("invitation/acceptInvitation",e);const{data:a}=await n.http.post(`/api/v1/invitations/${e}/accept`),s=null===(t=nt(["invitation","get",e]))||void 0===t?void 0:t.data;return s&&(ot(["invitation","get",e],{status:"approved"}),xt("local.invitation.updated",[s])),a.success})(e._id)},reject:async()=>{await(async e=>{var t;const n=Ge();n.log("invitation/rejectInvitation",e);const{data:a}=await n.http.post(`/api/v1/invitations/${e}/reject`),s=null===(t=nt(["invitation","get",e]))||void 0===t?void 0:t.data;return s&&(ot(["invitation","get",e],{status:"rejected"}),xt("local.invitation.updated",[s])),a.success})(e._id)}}),tc=async e=>{const t=Ge();t.log("invitation/getInvitation",e.targetType,e.targetId,e.type);const{data:n}=await t.http.get("/api/v1/invitations/me",{params:e}),a=Zr(n),s=t.cache&&Date.now();return t.cache&&Nn(a,{cachedAt:s}),{data:a.invitations[0]?ec(a.invitations[0]):void 0,cachedAt:s}};var nc;!function(e){e.OnLocalInvitationCreated="onLocalInvitationCreated",e.OnLocalInvitationUpdated="onLocalInvitationUpdated",e.OnLocalInvitationCanceled="onLocalInvitationCanceled"}(nc||(nc={}));class ac extends fr{async getRequest(e,t){const{limit:n=me}=e,a=_n(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/invitations",{params:Object.assign(Object.assign({},a),{options:s})});return o}}class sc extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.invitations.map(Xe("invitation"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(Xe("invitation"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===nc.OnLocalInvitationUpdated){if(!a.data.find((e=>e===t[0].invitationId)))return}e===nc.OnLocalInvitationCreated&&(a.data=[...new Set([...t.map((e=>e.invitationId)),...a.data])]),e===nc.OnLocalInvitationDeleted&&(a.data=a.data.filter((e=>e!==t[0].invitationId))),at(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=Ge(),n=[qt(t,"onLocalInvitationCreated","local.invitation.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},ic=e=>{const t=Ge(),n=[qt(t,"onLocalInvitationUpdated","local.invitation.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},rc=e=>{const t=Ge(),n=[qt(t,"onLocalInvitationCanceled","local.invitation.canceled",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class cc extends Or{constructor(e,t){const n=R.default(e),a=["invitation","collection",n];super(new ac(e),n,a,t),this.query=e,this.queryStreamController=new sc(this.query,this.cacheKey,this.notifyChange.bind(this),Wr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:oc,action:nc.OnLocalInvitationCreated},{fn:ic,action:nc.OnLocalInvitationUpdated},{fn:rc,action:nc.OnLocalInvitationCanceled}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["invitation","get",e]))).filter(Tr).map((({data:e})=>ec(e))))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,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?It:wt)();return t=t.sort(n),t}}const dc=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=nt(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),lc=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=nt(["category","get",e]);if(null==t?void 0:t.data)return dc(t.data)})).filter((e=>!!e))},get avatar(){var t;if(!e.avatarFileId)return;return null===(t=nt(["file","get",e.avatarFileId]))||void 0===t?void 0:t.data},createInvitations:async t=>{await Xr({type:"communityMemberInvite",targetType:"community",targetId:e.communityId,userIds:t})},getMemberInvitations:(t,n)=>((e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getInvitations: (tmpid: ${o}) > listen`);const i=new cc(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{it(c)})),()=>{a(`getInvitations (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}})(Object.assign(Object.assign({},t),{targetId:e.communityId,targetType:"community",type:"communityMemberInvite"}),n),getInvitation:async()=>{const{data:t}=await tc({targetType:"community",targetId:e.communityId});return t},join:async()=>(async e=>{var t;const n=Ge();n.log("community/joinRequest",e);const{data:a}=await n.http.post(`/api/v4/communities/${e}/join`),s=Nr(a),o=n.cache&&Date.now();n.cache&&Nn(s,{cachedAt:o});const i="approved"===s.joinRequests[0].status?"success":"pending";if("success"===i&&n.cache){const n=null===(t=nt(["community","get",e]))||void 0===t?void 0:t.data;if(n){const t=Object.assign(Object.assign({},n),{isJoined:!0});ot(["community","get",e],t)}}return xt("v4.local.community.joined",s.joinRequests),"success"===i?{status:i}:{status:i,request:$r(s.joinRequests[0])}})(e.communityId),getJoinRequests:(t,n)=>((e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getJoinRequests: (tmpid: ${o}) > listen`);const i=new Gr(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{it(c)})),()=>{a(`getJoinRequests (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}})(Object.assign(Object.assign({},t),{communityId:e.communityId}),n),getMyJoinRequest:async()=>{const{data:t}=await(async e=>{const t=Ge();t.log("community/myJoinRequest",e);const{data:n}=await t.http.get(`/api/v4/communities/${e}/join/me`),a=Nr(n),s=t.cache&&Date.now();return t.cache&&Nn(a,{cachedAt:s}),{data:a.joinRequests[0]?$r(a.joinRequests[0]):void 0,cachedAt:s}})(e.communityId);return t}});class uc{constructor(e,t,n){this._syncingStoriesCount=0,this._errorStoriesCount=0,this._targetId=e,this._lastStoryExpiresAt=t,this._lastStorySeenExpiresAt=n,this.cacheStoryExpireTime=nt(["story-expire",this._targetId]),this.cacheStoreSeenTime=nt(["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=nt(["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 nt(["story-sync-state",this._targetId]),this.isContainUnSyncedStory?this.localLastStoryExpires>e&&this.localLastStoryExpires>t:this.lastStoryExpiresAt>e&&this.lastStoryExpiresAt>t}getTotalStoryByStatus(){const e=tt(["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:s}}=t;return n!==this._targetId||s||(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 hc=e=>{const{targetType:t,targetId:n,lastStoryExpiresAt:a,lastStorySeenExpiresAt:s,targetUpdatedAt:o,localFilter:i}=e,r=new uc(n,a,s);return{targetType:t,targetId:n,lastStoryExpiresAt:a,updatedAt:o,hasUnseen:r.getHasUnseenFlag(),syncingStoriesCount:r.syncingStoriesCount,failedStoriesCount:r.failedStoriesCount,localFilter:i,localLastExpires:r.localLastStoryExpires,localLastSeen:r.localLastStorySeenExpiresAt,localSortingDate:r.getLocalLastSortingDate()}},mc=async e=>{const t=Ge();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,s=_n(e,["isPublic"]);n=await t.http.post("/api/v3/channels",Object.assign(Object.assign({},s),{isPublic:"community"===(null==e?void 0:e.type)?a:void 0}))}const a=await Da(n.data),s=t.cache&&Date.now();t.cache&&Nn(a,{cachedAt:s});const{channels:o}=a;return{data:Ds(o[0]),cachedAt:s}},gc=async e=>{const t=Ge();let n;t.log("channel/getChannel",e),Zn("channel",e);try{const{data:a}=await t.http.get(`/api/v3/channels/${encodeURIComponent(e)}`);n=await Da(a),t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&ka(a)}catch(t){throw Re(null==t?void 0:t.code)&&Fn("channel",e),t}const a=t.cache&&Date.now();t.cache&&Nn(n,{cachedAt:a});const{channels:s}=n;return{data:s.find((t=>t.channelId===e)),cachedAt:a}};gc.locally=e=>{var t;const n=Ge();if(n.log("channel/getChannel.locally",e),!n.cache)return;const a=null===(t=tt(["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 pc=Symbol("getWatcherUrls"),yc=e=>Object.assign(Object.assign({},e),{get moderation(){var t;return null===(t=nt(["streamModeration","get",e.streamId]))||void 0===t?void 0:t.data},get post(){var t;if("post"===e.referenceType)return null===(t=nt(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=nt(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;return null===(t=nt(["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=nt(["stream","get",e]))||void 0===t?void 0:t.data;if(n)return yc(n)})).filter(Tr):[]},getLiveChat:()=>(async e=>{var t;const n=Ge();if(n.log("stream/getLiveChat",e.streamId),e.channelId){const n=null===(t=nt(["channel","get",e.channelId]))||void 0===t?void 0:t.data;if(n)return Ps(Ds(n));const{data:a}=await gc(e.channelId);return Ps(Ds(a))}if(e.userId===n.userId){const{data:t}=await mc({type:"live",postId:e.postId,videoStreamId:e.streamId});return st(["stream","get",e.streamId],{channelId:t.channelId}),t}})(e),isBanned:!e.watcherUrl,watcherUrl:null,get[pc](){return e.watcherUrl}}),vc=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=nt(["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=nt(["user","get",e.userId]);if(null==t?void 0:t.data)return _t(t.data)},get childrenComment(){return e.children.map((e=>{const t=nt(["comment","get",e]);if(null==t?void 0:t.data)return null==t?void 0:t.data})).filter(Tr).map((e=>vc(e)))}});function fc(e){return!!(e.data&&"string"!=typeof e.data&&"videoFileId"in e.data&&"thumbnailFileId"in e.data&&"video"===e.dataType)}function bc(e){return!(!e.data||"string"==typeof e.data||!("streamId"in e.data)||"liveStream"!==e.dataType)}class Ic{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 Cc=null;const wc=()=>(Cc||(Cc=new Ic),Cc),Sc={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},Oc="-----BEGIN PRIVATE KEY-----";function Tc(e){const n=new Uint8Array(e);let a="";return n.forEach((e=>{a+=String.fromCharCode(e)})),t.btoa(a)}function Ac(e){return e<128?new Uint8Array([e]):e<256?new Uint8Array([129,e]):new Uint8Array([130,e>>8&255,255&e])}async function Rc(e){let n=e;n=e.includes(Oc)?e.substring(Oc.length,e.length-"-----END PRIVATE KEY-----".length).replace(/\s/g,""):e.replace(/\s/g,"");const a=t.atob(n),s=new Uint8Array(a.length);for(let e=0;e<a.length;e+=1)s[e]=a.charCodeAt(e);const o=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=Ac(e.length),s=n.length+t.length+1+a.length+e.length,o=Ac(s),i=new Uint8Array(1+o.length+s);let r=0;return i[r]=48,r+=1,i.set(o,r),r+=o.length,i.set(n,r),r+=n.length,i.set(t,r),r+=t.length,i[r]=4,r+=1,i.set(a,r),r+=a.length,i.set(e,r),i}(s);return await crypto.subtle.importKey("pkcs8",o.buffer,Sc,!1,["sign"])}async function Pc({timestamp:e,rooms:t}){const n=t.map((e=>Object.keys(e).sort().map((t=>`${t}=${e[t]}`)).join("&"))).join(";"),a=T.default.v4(),s=`nonceStr=${a}&timestamp=${e}&data=${n}==`,o=(new TextEncoder).encode(s),i=await Rc("-----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:Tc(await crypto.subtle.sign(Sc,i,o)),nonceStr:a}}async function Dc(){const e=wc(),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():""}))),s=await Pc({timestamp:n,rooms:a});if(!s||!s.signature)throw new Error("Signature is undefined");t.forEach((t=>{e.updateSession(t.sessionId,{syncState:"SYNCING"})}));const o={signature:s.signature,nonceStr:s.nonceStr,timestamp:n,rooms:a},i=Ge();return await i.http.post("/api/v3/user-event/room",o),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 Uc=["live","recorded"];class kc{constructor(e){this.storage=wc(),this.client=Ge(),this.room=e}async createWatchSession(e){if(!Uc.includes(this.room.status))throw new Qe("room is not in watchable state",5e5,"error");const t=("live"===this.room.status?"room_":"room_playback_")+T.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 Dc(),this.client.log("room/RoomAnalytics: syncWatchSessions completed")}catch(e){console.error("Failed to sync watch sessions:",e)}}),e)}}const jc=e=>Object.assign(Object.assign({},e),{get post(){var t;if("post"===e.referenceType)return null===(t=nt(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=nt(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;const n=null===(t=nt(["user","get",e.createdBy]))||void 0===t?void 0:t.data;return n?_t(n):n},get childRooms(){return e.childRoomIds&&0!==e.childRoomIds.length?e.childRoomIds.map((e=>{var t;const n=null===(t=nt(["room","get",e]))||void 0===t?void 0:t.data;if(n)return jc(n)})).filter(Tr):[]},participants:e.participants.map((e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=nt(["user","get",e.userId]))||void 0===t?void 0:t.data;return n?_t(n):n}}))),getLiveChat:()=>(async e=>{var t;const n=Ge();if(n.log("room/getLiveChat",e.roomId),e.liveChannelId){const n=null===(t=nt(["channel","get",e.liveChannelId]))||void 0===t?void 0:t.data;if(n)return Ps(Ds(n));const{data:a}=await gc(e.liveChannelId);return Ps(Ds(a))}if(e.createdBy===n.userId){const{data:t}=await mc({type:"live",postId:e.referenceId,roomId:e.roomId});return st(["room","get",e.roomId],{liveChannelId:t.channelId}),t}})(e),createInvitation:t=>Xr({type:"livestreamCohostInvite",targetType:"room",targetId:e.roomId,userIds:[t]}),getInvitations:async()=>{const{data:t}=await tc({targetId:e.roomId,targetType:"room",type:"livestreamCohostInvite"});return t},analytics(){return new kc(this)}}),Ec=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=nt(["file","get",e.fileId]))||void 0===t?void 0:t.data}})))}),Mc=e=>{const t=po();return Object.assign(Object.assign({},e),{analytics:{markAsClicked:(n,a,s)=>{t.markProductAsClicked(e,n,a,s)},markAsViewed:(n,a,s)=>{t.markProductAsViewed(e,n,a,s)}}})},qc=e=>Wn(e,{childrenPosts:e.children.map((e=>{var t;return null===(t=nt(["post","get",e]))||void 0===t?void 0:t.data})).filter(Tr).map(qc),analytics:{markAsViewed:()=>{po().markPostAsViewed(e.postId)},markAsMeaningfullyViewed:t=>{po().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=nt(["product","get",e.productId]))||void 0===t?void 0:t.data;return Object.assign(Object.assign({},e),{product:n?Mc(n):void 0})})(e))))&&void 0!==n?n:[]},get latestComments(){return e.comments&&e.comments.map((e=>{var t;const n=null===(t=nt(["comment","get",e]))||void 0===t?void 0:t.data;return n?vc(n):null})).filter(Boolean)||[]},get creator(){const t=nt(["user","get",e.postedUserId]);if(null==t?void 0:t.data)return _t(t.data)},get targetCommunity(){var t;const n=null===(t=nt(["community","get",e.targetId]))||void 0===t?void 0:t.data;if(n)return lc(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=nt(["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 fc(e)?null===(a=nt(["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 fc(e)?null===(n=nt(["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=nt(["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(!bc(e))return;const a=null===(n=nt(["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?yc(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=nt(["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?Ec(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=nt(["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=nt(["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=nt(["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?jc(a):void 0}}),xc=(e,t)=>{"message"===e?xt("local.message.updated",{messages:[t]}):"post"===e?xt("post.updated",{posts:[t]}):"comment"===e?xt("comment.updated",{comments:[t]}):"story"===e&&xt("story.updated",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[t]})},Kc=async(e,t,n,a)=>{var s,o,i;const r=Ge();if(r.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Qe("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:c}=await r.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:a});if(r.cache){const a=nt([e,"get",t]);if(!a||(null===(s=a.data.myReactions)||void 0===s?void 0:s.includes(n)))return!0;const d=Object.assign(Object.assign({},a.data),{reactionsCount:a.data.reactionsCount+1,myReactions:[...null!==(o=a.data.myReactions)&&void 0!==o?o:[],n],reactions:Object.assign(Object.assign({},a.data.reactions),{[n]:(null!==(i=a.data.reactions[n])&&void 0!==i?i:0)+1}),updatedAt:(new Date).toISOString()});if("comment"===e)return xt("local.comment.addReaction",{comment:d,reactor:{userId:r.userId,reactionName:n,reactionId:c.addedId}}),!0;if("post"===e)return xt("local.post.addReaction",{post:d,reactor:{userId:r.userId,reactionName:n,reactionId:c.addedId}}),!0;if("story"===e)return xt("local.story.reactionAdded",{story:d,reactor:{userId:r.userId,reactionName:n,reactionId:c.addedId}}),!0;if("message"===e)return ot(["message","get",t],d),xt("local.message.updated",{messages:[d]}),!0}return!0};Kc.optimistically=(e,t,n)=>{var a,s,o,i,r;const c=Ge();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const d=nt([e,"get",t]);if(!(null==d?void 0:d.data)||(null===(a=d.data.myReactions)||void 0===a?void 0:a.includes(n)))return;const l=Object.assign(Object.assign({},d.data),{reactionsCount:d.data.reactionsCount+1,myReactions:[...null!==(s=d.data.myReactions)&&void 0!==s?s:[],n],reactions:Object.assign(Object.assign({},d.data.reactions),{[n]:(null!==(o=d.data.reactions[n])&&void 0!==o?o:0)+1})});return ot([e,"get",t],l,{cachedAt:fe}),xc(e,l),null!==(r=null===(i=null==l?void 0:l.myReactions)||void 0===i?void 0:i.includes(n))&&void 0!==r&&r};const Nc=(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=nt(["messageMarker","get",Xe("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 s,o;const i=Ge();if(i.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Qe("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:r}=await i.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:a}});if(i.cache){const a=nt([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!==(s=a.data.myReactions)&&void 0!==s?s:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},a.data.reactions),{[n]:Math.max(0,(null!==(o=a.data.reactions[n])&&void 0!==o?o:0)-1)}),updatedAt:(new Date).toISOString()});if("comment"===e)return xt("local.comment.removeReaction",{comment:c,reactor:{reactionId:r.removedId,reactionName:n,userId:i.userId}}),!0;if("post"===e)return xt("local.post.removeReaction",{post:c,reactor:{reactionId:r.removedId,reactionName:n,userId:i.userId}}),!0;if("story"===e)return xt("local.story.reactionRemoved",{story:c,reactor:{userId:i.userId,reactionName:n,reactionId:r.removedId}}),!0;if("message"===e)return ot(["message","get",t],c),xt("local.message.updated",{messages:[c]}),!0}return!0})("message",n?t.publicId:t.messageId,e,n?3:5)},_c=e=>Object.assign(Object.assign({},e),{users:e.users.map(ga)}),Bc=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=nt(["event","get",e.eventId]);if(null==t?void 0:t.data)return t.data},get user(){const t=nt(["user","get",e.userId]);if(null==t?void 0:t.data)return _t(t.data)}}),$c=e=>Object.assign(Object.assign({},e),{users:e.users.map(ga)}),Lc=(e,t)=>{const n=Ge();return qt(n,e,e,(e=>{const a=$c(e);if(n.cache){Nn(a);const e=nt(["event","get",a.events[0].eventId]);t(e.data)}else t(a.events[0])}))},Qc=(e,t)=>{const n=Ge();return qt(n,e,e,(e=>{const a=_c(e);if(n.cache){Nn(a);const e=nt(["eventResponse","get",a.eventResponses[0].userId]);t(e.data)}else t(a.eventResponses[0])}))},Jc=async e=>{const t=Ge();t.log("event/getMyRSVP",e);const{data:n}=await t.http.get(`/api/v1/events/${e}/me/rsvp`),a=_c(n),s=t.cache&&Date.now();return t.cache&&Nn(a,{cachedAt:s}),{data:Bc(a.eventResponses[0]),cachedAt:s}};var Vc;Jc.locally=e=>{const t=Ge();if(t.log("event/getMyRSVP.locally",e),!t.cache)return;const n=nt(["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"}(Vc||(Vc={}));class Hc extends fr{async getRequest(e,t){const{limit:n=me,eventId:a}=e,s=_n(e,["limit","eventId"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get(`/api/v1/events/${a}/rsvp`,{params:Object.assign(Object.assign({},s),{options:o})});return i}}class zc extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.eventResponses.map(Xe("eventResponse"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.eventResponses.map(Xe("eventResponse"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===Vc.OnRSVPCreated&&(a.data=[...new Set([t.userId,...a.data])]),e===Vc.OnEventDeleted&&(a.data=a.data.filter((e=>e!==t.eventId))),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Gc=e=>Lc("event.created",e),Yc=e=>Lc("event.updated",e),Wc=e=>Lc("event.deleted",e),Xc=e=>Lc("local.event.created",e),Zc=e=>Lc("local.event.updated",e),ed=e=>Lc("local.event.deleted",e),td=e=>Qc("event.rsvp.created",e),nd=e=>Qc("event.rsvp.updated",e),ad=e=>Qc("local.rsvp.created",e),sd=e=>Qc("local.rsvp.updated",e);class od extends Or{constructor(e,t){const n=R.default(e),a=["eventResponse","collection",n];super(new Hc(e),n,a,t),this.query=e,this.queryStreamController=new zc(this.query,this.cacheKey,this.notifyChange.bind(this),_c),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:td,action:Vc.OnRSVPCreated},{fn:nd,action:Vc.OnRSVPUpdated},{fn:ad,action:Vc.OnRSVPCreated},{fn:sd,action:Vc.OnRSVPUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a;const s=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=s.data.map((e=>nt(["eventResponse","get",e]))).filter(Tr).map((({data:e})=>Bc(e)));(this.shouldNotify(o)||"event"!==e)&&this.callback({data:o,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}const id=(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getRSVPs: (tmpid: ${o}) > listen`);const i=new od(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getRSVPs (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},rd=e=>Object.assign(Object.assign({},e),{get creator(){const t=nt(["user","get",e.userId]);if(null==t?void 0:t.data)return _t(t.data)},get targetCommunity(){if(!e.originId)return;const t=nt(["community","get",e.originId]);return(null==t?void 0:t.data)?lc(t.data):void 0},get coverImage(){if(!e.coverImageFileId)return;const t=nt(["file","get",e.coverImageFileId]);return(null==t?void 0:t.data)?t.data:void 0},get post(){if(!e.postId)return;const t=nt(["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=tt(["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?jc(n[0].data):void 0},createRSVP:async t=>{const{data:n}=await(async(e,t)=>{const n=Ge();n.log("event/createRSVP",e,t);const{data:a}=await n.http.post(`/api/v1/events/${e}/rsvp`,{status:t});xt("local.rsvp.created",a);const s=_c(a),o=n.cache&&Date.now();return n.cache&&Nn(s,{cachedAt:o}),{data:Bc(s.eventResponses[0]),cachedAt:o}})(e.eventId,t);return n},updateRSVP:async t=>{const{data:n}=await(async(e,t)=>{const n=Ge();n.log("event/updateRSVP",e,t);const{data:a}=await n.http.put(`/api/v1/events/${e}/rsvp`,{status:t});xt("local.rsvp.updated",a);const s=_c(a),o=n.cache&&Date.now();return n.cache&&Nn(s,{cachedAt:o}),{data:Bc(s.eventResponses[0]),cachedAt:o}})(e.eventId,t);return n},getMyRSVP:async()=>{const{data:t}=await Jc(e.eventId);return t},getRSVPs:(t,n)=>id(Object.assign({eventId:e.eventId},t),n)}),cd={ad:e=>{const t=po(),{image9_16:n,image1_1:a}=e,s=_n(e,["image9_16","image1_1"]);return Object.assign(Object.assign({},s),{analytics:{markAsSeen:n=>{t.markAdAsViewed(e,n)},markLinkAsClicked:n=>{t.markAdAsClicked(e,n)}},get advertiser(){var t,n;const a=null===(t=nt(["advertiser","get",e.advertiserId]))||void 0===t?void 0:t.data;if(!a)return;const s=null===(n=nt(["file","get",a.avatarFileId]))||void 0===n?void 0:n.data;return Object.assign(Object.assign({},a),{avatar:s})},get image1_1(){const e=nt(["file","get",a]);if(e)return e.data||void 0},get image9_16(){const e=nt(["file","get",n]);if(e)return e.data||void 0}})},comment:vc,post:qc,user:_t,category:dc,stream:yc,story:e=>{const t=po(),n=nt(["storyTarget","get",e.targetId]),a=nt(["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=nt(["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:s}=a;return s||void 0},get imageData(){var t,n;if(!(null===(t=e.data)||void 0===t?void 0:t.fileId))return;const a=nt(["file","get",null===(n=e.data)||void 0===n?void 0:n.fileId]);if(!a)return;const{data:s}=a;return s?Object.assign(Object.assign({},s),{fileUrl:`${s.fileUrl}?size=full`}):void 0},get community(){if("community"===e.targetType&&(null==a?void 0:a.data))return lc(a.data)},get communityCategories(){if("community"!==e.targetType)return;if(!a)return;const{data:{categoryIds:t}}=a;return 0!==t.length?t.map((e=>{const t=nt(["category","get",e]);return(null==t?void 0:t.data)||void 0})).filter((e=>void 0!==e)):void 0},get creator(){const t=nt(["user","get",e.creatorPublicId]);if(null==t?void 0:t.data)return _t(t.data)},get storyTarget(){if(null==n?void 0:n.data)return hc(n.data)},get isSeen(){const t=nt(["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,s=new Date(null==n?void 0:n.data.lastStorySeenExpiresAt).getTime()||0,o=new Date(e.expiresAt).getTime();return Math.max(a,s)>=o}})},storyTarget:hc,message:e=>{const t=_n(e,["creatorPrivateId"]);return Object.assign(Object.assign({},t),{get readCount(){return Nc(e).readCount},get deliveredCount(){return Nc(e).deliveredCount},get creator(){var t;return null===(t=nt(["user","get",e.creatorId]))||void 0===t?void 0:t.data},markRead:()=>yi(e),addReaction:t=>((e,t)=>{const n=t.publicId!==t.messageId;return Kc("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=nt(["user","get",e.userId]))||void 0===t?void 0:t.data;if(n)return _t(n)}}),channel:Ps,pinnedPost:e=>{var t;const n=nt(["post","get",e.referenceId]),a=null===(t=tt(["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=nt(["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})=>nt(["user","get",e]))).filter(Tr).map((({data:e})=>e)).map((e=>_t(e))),get event(){const t=nt(["event","get",e.actionReferenceId]);if(null==t?void 0:t.data)return t.data}}),community:lc,invitation:ec,joinRequest:$r,channelMember:xa,room:jc,event:rd,eventResponse:Bc,product:Mc,poll:Ec},dd=async e=>{const t=Ge();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}}),s=Ws(a),o=t.cache&&Date.now();return t.cache&&Nn(s,{cachedAt:o}),xt("user.fetched",a),{data:s.users.map((e=>cd.user(e))),cachedAt:o}};dd.locally=e=>{var t;const n=Ge();if(n.log("user/getUsers.locally",e),!n.cache)return;const a=e.map((e=>nt(["user","get",e]))).filter(Boolean),s=a.map((({data:e})=>cd.user(e))),o=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:s,cachedAt:o.cachedAt}};const ld=async(e,t)=>{var n;const a=Ge();a.log("user/flagUser",{userId:e,options:t});const s=(e=>{if(!e)return;const t={};return void 0!==e.reportType&&(t.reportType=e.reportType),void 0!==e.reason&&(t.reason=e.reason),void 0!==e.comment&&(t.comment=e.comment),Object.keys(t).length>0?t:void 0})(t),{data:o}=await a.http.post(`/api/v4/me/flags/${encodeURIComponent(e)}`,s),i=Ws(o);return a.cache&&Nn(i),xt("user.flagged",o),null!==(n=i.users.find((t=>t.userId===e)))&&void 0!==n?n:i.users[0]},ud=e=>oo("user.updated",e),hd=e=>oo("user.flagged",e),md=e=>oo("user.unflagged",e),gd=e=>oo("user.flagCleared",e),pd=e=>oo("user.fetched",e),yd=async e=>{const t=Ge();t.log("user/getUser",e),Zn("user",e);try{const{data:n}=await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`),a=t.cache&&Date.now(),s=Ws(n);return t.cache&&Nn(s,{cachedAt:a}),xt("user.fetched",n),{data:s.users.find((t=>t.userId===e)),cachedAt:a}}catch(t){throw Re(null==t?void 0:t.code)&&Fn("user",e),t}};yd.locally=e=>{const t=Ge();if(t.log("user/getUser.locally",e),!t.cache)return;const n=nt(["user","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class vd extends fr{async getRequest(e,t){const{limit:n=me}=e,a=_n(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},a),{options:s,isDeleted:!1})});return o}}class fd extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.users.map(Xe("user"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Xe("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=nt(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],at(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var bd;!function(e){e.OnUserDeleted="onUserDeleted",e.OnUserUpdated="onUserUpdated",e.OnUserFlagged="onUserFlagged",e.OnUserUnflagged="onUserUnflagged",e.OnUserFlagCleared="onUserFlagCleared"}(bd||(bd={}));class Id extends Or{constructor(e,t){const n=R.default(e),a=["user","collection",n];super(new vd(e),n,a,t),this.query=e,this.queryStreamController=new fd(this.query,this.cacheKey,this.notifyChange.bind(this),Ws),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:io,action:bd.OnUserDeleted},{fn:ud,action:bd.OnUserUpdated},{fn:hd,action:bd.OnUserFlagged},{fn:md,action:bd.OnUserUnflagged},{fn:gd,action:bd.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["user","get",e]))).filter(Tr).map((({data:e})=>e)).map(cd.user))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;const n=(()=>"firstCreated"===this.query.sortBy?It:wt)();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 Cd extends fr{async getRequest(e,t){const{limit:n=me}=e,a=_n(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v4/me/user-blocks",{params:Object.assign(Object.assign({},a),{options:s,isDeleted:!1})});return o}}var wd;!function(e){e.OnBlocked="onBlocked",e.OnUnblocked="onUnblocked"}(wd||(wd={}));class Sd extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.users.map(Xe("user"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Xe("user"))])]}))}}reactor(e){return t=>{var n,a;const s=e===Cr.OnFollowed||e===wd.OnUnblocked,o=e===wd.OnBlocked;if(s||o){const e=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data,s=null!==(a=null==e?void 0:e.data)&&void 0!==a?a:[],i=o?[...new Set([...s,t.userId])]:s.filter((e=>e!==t.userId));at(this.cacheKey,Object.assign(Object.assign({},e),{data:i}))}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Od=(e,t,n)=>a=>e((e=>{var s;if(!e)return e;const o=[n,"get",`${e[t]}`],i=null===(s=nt(o))||void 0===s?void 0:s.data;return i?a(i):void 0}));class Td extends Or{constructor(e,t){const n=R.default(e),a=["blockedUsers","collection",n];super(new Cd(e),n,a,t),this.query=e,this.queryStreamController=new Sd(this.query,this.cacheKey,this.notifyChange.bind(this),qo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:io,action:bd.OnUserDeleted},{fn:Od(mr,"to","user"),action:Cr.OnFollowed},{fn:Od(sr,"to","user"),action:Cr.OnFollowed},{fn:e=>Ho((t=>{var n;if(t.from!==Ge().userId)return;const a=null===(n=nt(["user","get",t.to]))||void 0===n?void 0:n.data;a&&e(a)})),action:wd.OnBlocked},{fn:e=>zo((t=>{var n;if(t.from!==Ge().userId)return;const a=null===(n=nt(["user","get",t.to]))||void 0===n?void 0:n.data;a&&e(a)})),action:wd.OnUnblocked}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["user","get",e]))).filter(Tr).map((({data:e})=>e)).map(cd.user))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,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 Ad extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.users.map(Xe("user"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Xe("user"))])]}))}}reactor(e){return t=>{var n,a;if(t&&(e===wd.OnBlocked||e===wd.OnUnblocked)){const s=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data,o=null!==(a=null==s?void 0:s.data)&&void 0!==a?a:[],i=e===wd.OnBlocked?[...new Set([...o,t.userId])]:o.filter((e=>e!==t.userId));at(this.cacheKey,Object.assign(Object.assign({},s),{data:i}))}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Rd extends fr{async getRequest(e,t){const{limit:n=ge}=e,a=_n(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v4/me/blockers",{params:Object.assign(Object.assign({},a),{options:s,isDeleted:!1})});return o}}class Pd extends Or{constructor(e){const t=`blocking-users-${Ge().userId}`,n={},a=["blockingUsers","collection",t];super(new Rd(n),t,a,e),this.queryStreamController=new Ad(n,this.cacheKey,this.notifyChange.bind(this),Fo),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:io,action:bd.OnUserDeleted},{fn:e=>Ho((t=>{var n;if(t.to!==Ge().userId)return;const a=null===(n=nt(["user","get",t.from]))||void 0===n?void 0:n.data;a&&e(a)})),action:wd.OnBlocked},{fn:e=>zo((t=>{var n;if(t.to!==Ge().userId)return;const a=null===(n=nt(["user","get",t.from]))||void 0===n?void 0:n.data;a&&e(a)})),action:wd.OnUnblocked}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["user","get",e]))).filter(Tr).map((({data:e})=>e)).map(cd.user))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,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 Dd extends fr{async getRequest(e,t){const{limit:n=me,displayName:a}=e,s=_n(e,["limit","displayName"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},s),{keyword:a,options:o,isDeleted:!1})});return i}}class Ud extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.users.map(Xe("user"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Xe("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=nt(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],at(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class kd extends Or{constructor(e,t){var n;const a=R.default(e),s=["user","collection",a];super(new Dd(e),a,s,t),this.query=Object.assign(Object.assign({},e),{filter:null!==(n=e.filter)&&void 0!==n?n:"all"}),this.queryStreamController=new Ud(this.query,this.cacheKey,this.notifyChange.bind(this),Ws),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:io,action:bd.OnUserDeleted},{fn:ud,action:bd.OnUserUpdated},{fn:hd,action:bd.OnUserFlagged},{fn:md,action:bd.OnUserUnflagged},{fn:gd,action:bd.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["user","get",e]))).filter(Tr).map((({data:e})=>e)).map(cd.user))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,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 jd=async({viewId:e,viewedType:t,limit:n,token:a})=>{const s=Ge(),o={};a?o.token=a:o.limit=n;const i=`/api/v1/analytics/views/${"post"===t?"posts":"stories"}/${e}/users`,r=await s.http.get(i,{params:o});return Nn(r.data),r.data};var Ed;!function(e){e.DEFAULT="default",e.PARTIAL="partial"}(Ed||(Ed={}));var Md=Object.freeze({__proto__:null,Relationship:Er,getUserByIds:dd,updateUser:async(e,t)=>{const n=Ge();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})),s=Ws(a),o=n.cache&&Date.now();return n.cache&&Nn(s,{cachedAt:o}),xt("user.updated",a),{data:s.users.find((t=>t.userId===e)),cachedAt:o}},flagUser:ld,unflagUser:async e=>{const t=Ge();t.log("user/unflag",e);const{data:n}=await t.http.delete(`/api/v4/me/flags/${encodeURIComponent(e)}`),a=Ws(n);return t.cache&&Nn(a),xt("user.unflagged",n),!!a},isUserFlaggedByMe:async e=>{const t=Ge();t.log("user/isUserFlaggedByMe",e);const{data:{isFlagByMe:n}}=await t.http.get(`/api/v3/users/${e}/isFlagByMe`);return n},getAllBlockedUsers:async()=>{Ge().log("user/getAllBlockedUsers");const e=No();return await e.ensureFetched(),e.getCachedUsers()},getAllBlockingUsers:async()=>{Ge().log("user/getAllBlockingUsers");const e=$o();return await e.ensureFetched(),e.getCachedUsers()},onUserUpdated:ud,onUserDeleted:io,onUserFlagged:hd,onUserUnflagged:md,onUserFlagCleared:gd,getUser:(e,t)=>jr(e,(e=>t(Object.assign(Object.assign({},e),{data:e.data?cd.user(e.data):e.data}))),"userId",yd,[pd,ud,io,hd,md,gd]),getUsers:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`liveUsers(tmpid: ${o}) > listen`);const i=new Id(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`liveUsers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getBlockedUsers:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getBlockedUsers(tmpid: ${o}) > listen`);const i=new Td(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getBlockedUsers(tmpid: ${o}) > dispose`),r.forEach((e=>e())),it(c)}},getBlockingUsers:e=>{const{log:t,cache:n}=Ge();n||console.log(ye);const a=Date.now();t(`getBlockingUsers(tmpid: ${a}) > listen`);const s=new Pd(e),o=s.startSubscription(),i=s.getCacheKey();return o.push((()=>it(i))),()=>{t(`getBlockingUsers(tmpid: ${a}) > dispose`),o.forEach((e=>e())),it(i)}},searchUserByDisplayName:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`liveSearchUsers(tmpid: ${o}) > listen`);const i=new kd(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`liveSearchUsers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getReachedUsers:(e,t)=>{let n=(e=!1)=>{};const{log:a,cache:s}=Ge(),o=["viewedUsers","collection",{viewId:e.viewId,viewedType:e.viewedType}];s||console.log(ye);const i=Date.now();a(`getReachUsers(tmpid: ${i}) > listen`);const{limit:r,viewId:c,viewedType:d}=e;return n=(e=!1)=>{var a,s,i;const l=null===(a=nt(o))||void 0===a?void 0:a.data,u=null!==(s=null==l?void 0:l.data)&&void 0!==s?s:[];if(!e&&u.length>0&&!(null==l?void 0:l.params.page))return;const h=Fe(jd,{viewId:c,viewedType:d,limit:r||10,token:e||null===(i=null==l?void 0:l.params.page)||void 0===i?void 0:i.next});Be(h,(e=>{var a,s,i,r,c;let d=null!==(i=null===(s=null===(a=nt(o))||void 0===a?void 0:a.data)||void 0===s?void 0:s.data)&&void 0!==i?i:[];(null===(r=e.data)||void 0===r?void 0:r.users)&&(d=[...new Set([...d,...e.data.users.map((({userId:e})=>e))])]);const l={loading:e.loading,params:{page:null===(c=e.data)||void 0===c?void 0:c.paging},data:d||[]};at(o,l),(e=>{var a,s;let o=[];(null==e?void 0:e.data)&&(o=e.data.map((e=>nt(["user","get",e]))).filter(Boolean).map((e=>null==e?void 0:e.data))||[]),t({onNextPage:n,data:o,hasNextPage:!!(null===(s=null===(a=e.params)||void 0===a?void 0:a.page)||void 0===s?void 0:s.next),loading:e.loading||!1})})(l)}),_e(pe,2e3))},n(!0),()=>{a(`getReachUsers(tmpid: ${i}) > dispose`),it(o)}},get AmityUserSearchMatchType(){return Ed}});const qd=async e=>{const t=Ge();t.log("file/getFile",e);const{data:n}=await t.http.get(`/api/v3/files/${e}`),a=t.cache&&Date.now();return t.cache&&Nn({files:[n]},{cachedAt:a}),{data:n,cachedAt:a}};qd.locally=e=>{const t=Ge();if(t.log("file/getFile.locally",e),!t.cache)return;const n=nt(["file","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const xd=async(e,t,n)=>{const a=Ge();a.log("file/uploadVideo",e);const s=e.getAll("files");if(!s.length)throw new Error("The formData object must have a `files` key.");const o=xi().getFileAccessType();e.append("accessType",o),e.append("preferredFilename",s[0].name),t&&e.append("feedType",t);const i="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:r}=await a.upload.post("/api/v4/videos",e,{headers:i,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),c=a.cache&&Date.now();return a.cache&&Nn({files:r},{cachedAt:c}),{data:r,cachedAt:c}},Kd=async(e,t,n)=>{const a=Ge();a.log("file/uploadImage",e);const s=e.getAll("files");if(null==s?void 0:s.length)console.warn("Deprecation Warning: `files` is deprecated, please use `file` instead."),e.append("preferredFilename",s[0].name);else{const t=e.get("file");if(!t)throw new Error("The formData object must have a `file` or `files` key");e.append("preferredFilename",t.name),n&&e.append("altText",n)}const o=xi().getFileAccessType();e.append("accessType",o);const i="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:r}=await a.upload.post("/api/v4/images",e,{headers:i,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),c=a.cache&&Date.now();return a.cache&&Nn({files:r},{cachedAt:c}),{data:r,cachedAt:c}};var Nd=Object.freeze({__proto__:null,getFile:qd,uploadFile:async(e,t)=>{const n=Ge();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 s=xi().getFileAccessType();e.append("accessType",s),e.append("preferredFilename",a[0].name);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await n.upload.post("/api/v4/files",e,{headers:o,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),r=n.cache&&Date.now();return n.cache&&Nn({files:i},{cachedAt:r}),{data:i,cachedAt:r}},deleteFile:async e=>{const t=Ge();return t.log("file/deleteFile",e),await t.http.delete(`/api/v3/files/${e}`),it(["file","get",e],!0),{success:!0}},fileUrlWithSize:(e,t)=>`${e}?size=${t}`,uploadVideo:xd,uploadImage:Kd,updateAltText:async(e,t)=>{const n=Ge();n.log("file/updateAltText",t);const{data:a}=await n.http.put(`/api/v3/files/${e}`,{altText:t}),s=n.cache&&Date.now();return n.cache&&Nn({files:[a]},{cachedAt:s}),!0},uploadClip:async(e,t,n)=>{const a=Ge();a.log("file/uploadClip",e);const s=e.get("files");if(!s)throw new Error("The formData object must have a `files` key.");const o=xi().getFileAccessType();e.append("accessType",o),e.append("preferredFilename",s.name),t&&e.append("feedType",t);const i="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:r}=await a.upload.post("/api/v4/clips",e,{headers:i,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),c=a.cache&&Date.now();return a.cache&&Nn({files:r},{cachedAt:c}),{data:r,cachedAt:c}},uploadAudio:async(e,t)=>{const n=Ge();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 s=a[0],o=xi().getFileAccessType();e.append("accessType",o),e.append("preferredFilename",s.name);const{data:i}=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))}}),r=n.cache&&Date.now();return n.cache&&Nn({files:i},{cachedAt:r}),{data:i,cachedAt:r}}});const Fd=async e=>{const t=Ge();t.log("role/queryRoles",e);const n=null!=e?e:{},{limit:a=10,queryToken:s,displayName:o,sortBy:i}=n,r=_n(n,["limit","queryToken","displayName","sortBy"]),c=s?{token:s}:a?{limit:a}:void 0,{data:d}=await t.http.get("/api/v3/roles",{params:Object.assign(Object.assign({},r),{keyword:o,sortBy:i,options:c})}),{paging:l}=d,u=_n(d,["paging"]),{roles:h}=u,m=t.cache&&Date.now();t.cache&&Nn(u,{cachedAt:m});const g=Ee(l.next);return{data:h,cachedAt:m,prevPage:Ee(l.previous),nextPage:g,paging:l}};Fd.locally=e=>{Ge().log("role/queryRoles.locally",e)};const _d=async e=>{const t=Ge();t.log("role/getRole",e);const{data:n}=await t.http.get(`/api/v3/roles/${e}`),a=t.cache&&Date.now();return t.cache&&Nn({roles:n},{cachedAt:a}),{data:n.find((t=>t.roleId===e)),cachedAt:a}};_d.locally=e=>{const t=Ge();if(t.log("role/getRole.locally",e),!t.cache)return;const n=nt(["role","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Bd=async(e,t=!1)=>{const n=Ge();let a;n.log("message/getMessage",e),Zn("message",e);try{const{data:t}=await n.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);a=await ua(t)}catch(t){throw Re(null==t?void 0:t.code)&&Fn("message",e),t}const s=n.cache&&Date.now();n.cache&&Nn(a,{cachedAt:s});const{messages:o}=a;return xt("local.message.fetched",{messages:o}),{data:o.find((t=>t.messageId===e)),cachedAt:s}};Bd.locally=e=>{const t=Ge();if(t.log("message/getMessage.locally",e),!t.cache)return;const n=nt(["message","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class $d{constructor(e,t,n){this.postId=e,this.latestCreatedAt=t,this.serverCommentCount=n}}class Ld{constructor(e,t,n){this.postId=e,this.commentId=t,this.createdAt=n}}class Qd{constructor(e,t){this.postId=e,this.commentId=t}}class Jd{constructor(e,t){this.latestCommentCreatedAt=e,this.serverCommentCount=t,this.createdCommentIds=new Set,this.deletedCommentIds=new Set}}class Vd{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,Vd.BATCH_SIZE),t=new Set;e.forEach((e=>{let n=!1;e instanceof $d?n=this.processResetTaskInternal(e):e instanceof Ld?n=this.processCreateTaskInternal(e):e instanceof Qd&&(n=this.processDeleteTaskInternal(e)),n&&t.add(e.postId)})),t.forEach((e=>{const t=this.computeCommentCount(e);Vd.publishUpdate(e,t)})),this.isProcessing=!1,this.tasks.length>0&&this.processCommentChangeTask()}processResetTaskInternal(e){return this.commentChangeTracker.set(e.postId,new Jd(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];st(a,{localCommentCount:t});const s=null===(n=nt(a))||void 0===n?void 0:n.data;s&&xt("local.post.updated",{posts:[s]})}}let Hd;Vd.BATCH_SIZE=50;var zd=()=>(Hd||(Hd=new Vd),Hd);const Gd=e=>{const{posts:t,postChildren:n,videoStreamings:a}=e,s=_n(e,["posts","postChildren","videoStreamings"]),o=xr({communities:s.communities}),i=s.communityUsers.map((e=>{const t=s.users.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),r=Mr(o,i);let c=[];const d=t.map((t=>{var n,o,i,r;const d=null===(n=s.feeds.find((e=>e.feedId===t.feedId)))||void 0===n?void 0:n.feedType,l=e.postChildren.filter((e=>e.parentPostId===t.postId));var u,h,m;l.length>0&&bc(l[0])&&(u=a,h=null===(o=l[0].data)||void 0===o?void 0:o.streamId,m=t.postId,c=h?u.map((e=>e.streamId===h?Object.assign(Object.assign({},e),{referenceType:"post",referenceId:m,postId:m}):e)):u);const g=(e.comments||[]).filter((e=>"post"===e.referenceType&&e.referenceId===t.postId)),p=0===g.length?(new Date).toISOString():g.map((e=>e.createdAt)).sort().at(-1);return zd().queueCommentChangeTask(new $d(t.postId,p,null!==(i=t.commentsCount)&&void 0!==i?i:0)),Object.assign(Object.assign({},t),{childPosts:l,feedType:d,localCommentCount:null!==(r=t.localCommentCount)&&void 0!==r?r:t.commentsCount,pinnedProductId:null==t?void 0:t.pinnedProductId})}));return Object.assign(Object.assign({},s),{postChildren:n,videoStreamings:c,posts:d,communities:r,communityUsers:i})},Yd=e=>{var{searchResult:t,polls:n}=e,a=_n(e,["searchResult","polls"]);const s=Gd(a);return Object.assign(Object.assign({},s),{polls:n})},Wd=async e=>{const t=Ge();let n;t.log("post/getPost",e),Zn("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw Re(null==t?void 0:t.code)&&Fn("post",e),t}const a=Gd(n),s=t.cache&&Date.now();t.cache&&Nn(a,{cachedAt:s});const{posts:o}=a;return{data:o.find((t=>t.postId===e)),cachedAt:s}};Wd.locally=e=>{const t=Ge();if(t.log("post/getPost.locally",e),!t.cache)return;const n=nt(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Xd=async e=>{const t=Ge();let n;t.log("comment/getComment",e),Zn("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw Re(null==t?void 0:t.code)&&Fn("comment",e),t}const a=t.cache&&Date.now();t.cache&&Nn(n,{cachedAt:a});const{comments:s}=n;return{data:cd.comment(s.find((t=>t.commentId===e))),cachedAt:a}};Xd.locally=e=>{const t=Ge();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=nt(["comment","get",e]);return n?{data:cd.comment(n.data),cachedAt:n.cachedAt}:void 0};const Zd=(e,t)=>{var n,a;let s,o;if("post"===t)o="post",s=e.posts[0].postId;else if("comment"===t)o="comment",s=e.comments[0].commentId;else{if("story"!==t)throw new Error("Unknown event type");o="story",s=e.stories[0].referenceId}return(null===(a=null===(n=nt([o,"get",s]))||void 0===n?void 0:n.data)||void 0===a?void 0:a.myReactions)||[]},el=(e,t,n)=>{const[a]=e[t];return Object.assign(Object.assign({},e),{[t]:[Object.assign(Object.assign({},a),{myReactions:n})]})},tl=(e,t,n,a=[])=>{const s=e.split(".")[1];let o=a;if(Ge().userId===t)if(["addReaction","reactionAdded"].includes(s))o.includes(n)||o.push(n);else{if(!["removeReaction","reactionRemoved"].includes(s))throw new Error(`Unknown event type: ${s}`);o=o.filter((e=>e!==n))}return o},nl=(e,t)=>{const n=e.split(".")[0],a=Zd(t,n),s=tl(e,t.reactor.userId,t.reactor.reactionName,a);return el(t,`${n}s`,s)},al=(e,t)=>{var n,a;const s=e.split(".")[0];let o=Zd(t,s);(null==t?void 0:t.reactions)&&t.reactions.length>0&&(o=tl(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,o));const i=el(t,"stories",o);if(!(null==t?void 0:t.communities)||!(null==t?void 0:t.communityUsers))return i;const r=Mr(t.communities,t.communityUsers);return Object.assign(Object.assign({},i),{communities:r})},sl=async(e,t,n)=>{var a,s,o;const i=Ge();if(i.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Qe("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:r}=await i.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0});if(i.cache){const c=nt([e,"get",t]);if(!c||(null===(a=c.data.myReactions)||void 0===a?void 0:a.includes(n)))return!0;const d=Object.assign(Object.assign({},c.data),{reactionsCount:c.data.reactionsCount+1,myReactions:[...null!==(s=c.data.myReactions)&&void 0!==s?s:[],n],reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:(null!==(o=c.data.reactions[n])&&void 0!==o?o:0)+1}),updatedAt:(new Date).toISOString()});if("comment"===e)return xt("local.comment.addReaction",{comment:d,reactor:{userId:i.userId,reactionName:n,reactionId:r.addedId}}),!0;if("post"===e)return xt("local.post.addReaction",{post:d,reactor:{userId:i.userId,reactionName:n,reactionId:r.addedId}}),!0;if("story"===e)return xt("local.story.reactionAdded",{story:d,reactor:{userId:i.userId,reactionName:n,reactionId:r.addedId}}),!0}return!0};sl.optimistically=(e,t,n)=>{var a,s,o,i,r;const c=Ge();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const d=nt([e,"get",t]);if(!(null==d?void 0:d.data)||(null===(a=d.data.myReactions)||void 0===a?void 0:a.includes(n)))return;const l=Object.assign(Object.assign({},d.data),{reactionsCount:d.data.reactionsCount+1,myReactions:[...null!==(s=d.data.myReactions)&&void 0!==s?s:[],n],reactions:Object.assign(Object.assign({},d.data.reactions),{[n]:(null!==(o=d.data.reactions[n])&&void 0!==o?o:0)+1})});return ot([e,"get",t],l,{cachedAt:fe}),xc(e,l),null!==(r=null===(i=null==l?void 0:l.myReactions)||void 0===i?void 0:i.includes(n))&&void 0!==r&&r};const ol=async(e,t,n)=>{var a,s;const o=Ge();if(o.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Qe("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:"message"===e?5:void 0}});if(o.cache){const r=nt([e,"get",t]);if(!r)return!0;const c=Object.assign(Object.assign({},r.data),{reactionsCount:Math.max(0,r.data.reactionsCount-1),myReactions:(null!==(a=r.data.myReactions)&&void 0!==a?a:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},r.data.reactions),{[n]:Math.max(0,(null!==(s=r.data.reactions[n])&&void 0!==s?s:0)-1)}),updatedAt:(new Date).toISOString()});if("comment"===e)return xt("local.comment.removeReaction",{comment:c,reactor:{reactionId:i.removedId,reactionName:n,userId:o.userId}}),!0;if("post"===e)return xt("local.post.removeReaction",{post:c,reactor:{reactionId:i.removedId,reactionName:n,userId:o.userId}}),!0;if("story"===e)return xt("local.story.reactionRemoved",{story:c,reactor:{userId:o.userId,reactionName:n,reactionId:i.removedId}}),!0}return!0};ol.optimistically=(e,t,n)=>{var a,s,o,i;const r=Ge();if(r.log("reaction/removeReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!r.cache)return;const c=nt([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 d=Object.assign(Object.assign({},c.data),{reactionsCount:Math.max(0,c.data.reactionsCount-1),myReactions:(null!==(s=c.data.myReactions)&&void 0!==s?s:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:Math.max(0,(null!==(o=c.data.reactions[n])&&void 0!==o?o:0)-1)})});return ot([e,"get",t],d,{cachedAt:fe}),xc(e,d),!(null===(i=null==d?void 0:d.myReactions)||void 0===i?void 0:i.includes(n))};const il=e=>{var t;const n=e.posts[0];if(n.parentId){const e=null===(t=nt(["post","get",n.parentPostId]))||void 0===t?void 0:t.data;if(!e)return;at(["post","get",e.postId],Object.assign(Object.assign({},e),{children:e.children.filter((e=>e!==n.postId))}))}else n.children.forEach((e=>st(["post","get",e],{isDeleted:!0})))},rl=(e,t)=>{const n=Ge();return qt(n,e,e,(a=>{var s;if(n.cache){const o=Gd(a),{communities:i}=o;if(Nn(o,void 0,!1),(null==i?void 0:i[0])&&!["post.updated"].includes(e)&&xt("community.updated",{communities:i,categories:[],communityUsers:o.communityUsers,feeds:[],files:[],users:[]}),"post.deleted"===e){const{postId:e,postedUserId:s}=a.posts[0];il(a);try{Zn("post",e)}catch(e){return}return s!==n.userId&&it(["post","get",e]),t(a.posts[0])}const r=nt(["post","get",a.posts[0].postId]);if(["post.created","post.approved","post.declined"].includes(e)){let t=null===(s=tt(["post","query"]))||void 0===s?void 0:s.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.targetId)===r.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})=>ot(e,t,{cachedAt:-1})))}"post.created"===e&&(e=>{var t;const n=e.posts[0];if(!n.parentId)return;const a=null===(t=nt(["post","get",n.parentPostId]))||void 0===t?void 0:t.data;a&&at(["post","get",a.postId],Object.assign(Object.assign({},a),{children:[...new Set([n.postId,...a.children])]}))})(a),t(r.data)}else t(a.posts[0])}))},cl=(e,t)=>{const n=Ge();return qt(n,e,e,(a=>{if(n.cache){const{communities:n}=a;(null==n?void 0:n[0])&&!["local.post.updated"].includes(e)&&xt("community.updated",{communities:n,categories:[],communityUsers:a.communityUsers,feeds:[],files:[],users:[]});const s=nt(["post","get",a.posts[0].postId]);"local.post.deleted"===e&&il(a),t(s.data)}else t(a.posts[0])}))},dl=e=>rl("post.created",e),ll=e=>rl("post.updated",e),ul=e=>rl("post.deleted",e),hl=e=>rl("post.approved",e),ml=e=>rl("post.declined",e),gl=e=>rl("post.flagged",e),pl=e=>rl("post.unflagged",e),yl=e=>{const t=Ge();return qt(t,"post.addReaction","post.addReaction",(n=>{if(t.cache){const t=_n(nl("post.addReaction",n),["reactor"]);Nn(t);const a=nt(["post","get",n.posts[0].postId]);e(a.data)}else e(n.posts[0])}))},vl=e=>{const t=Ge();return qt(t,"post.removeReaction","post.removeReaction",(n=>{if(t.cache){const t=_n(nl("post.removeReaction",n),["reactor"]);Nn(t);const a=nt(["post","get",n.posts[0].postId]);e(a.data)}else e(n.posts[0])}))},fl=(e,t)=>{const n=Ge();return qt(n,e,e,(a=>{var s;if(n.cache){const n=["comment.flagged","comment.unflagged"].includes(e)?(e=>{const t=Zd(e,"comment");return el(e,"comments",t)})(a):a;Nn(n,void 0,!1);const{comments:o}=n;if(o.length>0){const n=nt(["comment","get",o[0].commentId]);if(["comment.created"].includes(e)&&o[0].parentId){const e=nt(["comment","get",o[0].parentId]);(null==e?void 0:e.data)&&(e.data.children.includes(o[0].commentId)||at(["comment","get",o[0].parentId],Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,o[0].commentId])]})))}if(["comment.deleted"].includes(e)){if(o[0].parentId){const e=nt(["comment","get",o[0].parentId]);if((null==e?void 0:e.data)&&e.data.children.includes(o[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber-1,children:[...new Set([...e.data.children.filter((e=>e!==o[0].commentId))])]});at(["comment","get",o[0].parentId],t)}}const e=null===(s=tt(["comment","query"]))||void 0===s?void 0:s.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===n.data.referenceId}));null==e||e.map((({key:e,data:t})=>ot(e,t,{cachedAt:-1})))}t(cd.comment(n.data))}}else t(cd.comment(a.comments[0]))}))},bl=(e,t)=>{const n=Ge();return qt(n,e,e,(a=>{var s,o,i,r,c;if(n.cache){const n=a;Nn(n);const{comments:d}=n;if(d.length>0){const n=nt(["comment","get",d[0].commentId]);if(["local.comment.created"].includes(e)){if(d[0].parentId){const e=nt(["comment","get",d[0].parentId]);if((null==e?void 0:e.data)&&!e.data.children.includes(d[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,d[0].commentId])]});at(["comment","get",d[0].parentId],t),setTimeout((()=>{xt("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}else{const e=["post","get",d[0].referenceId],t=null===(s=nt(e))||void 0===s?void 0:s.data;if(t){const n=Object.assign(Object.assign({},t),{comments:[...t.comments,null===(o=d[0])||void 0===o?void 0:o.commentId]});at(e,n)}}const e=null===(i=tt(["comment","query"]))||void 0===i?void 0:i.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})=>ot(e,t,{cachedAt:-1})))}if(["local.comment.deleted"].includes(e)){if(d[0].parentId){const e=nt(["comment","get",d[0].parentId]);if((null==e?void 0:e.data)&&e.data.children.includes(d[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber-1,children:[...new Set([...e.data.children.filter((e=>e!==d[0].commentId))])]});at(["comment","get",d[0].parentId],t),setTimeout((()=>{xt("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}else{const e=["post","get",d[0].referenceId],t=null===(r=nt(e))||void 0===r?void 0:r.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=d[0])||void 0===t?void 0:t.commentId)}))});at(e,n)}}const e=null===(c=tt(["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})=>ot(e,t,{cachedAt:-1})))}t(cd.comment(n.data))}}else t(cd.comment(a.comments[0]))}))},Il=e=>fl("comment.created",e),Cl=e=>fl("comment.updated",e),wl=e=>fl("comment.deleted",e),Sl=e=>fl("comment.flagged",e),Ol=e=>fl("comment.unflagged",e),Tl=e=>{const t=Ge();return qt(t,"comment.addReaction","comment.addReaction",(n=>{if(t.cache){const t=_n(nl("comment.addReaction",n),["reactor"]);Nn(t);const a=nt(["comment","get",n.comments[0].commentId]);e(cd.comment(a.data))}else e(cd.comment(n.comments[0]))}))},Al=e=>{const t=Ge();return qt(t,"comment.removeReaction","comment.removeReaction",(n=>{if(t.cache){const t=_n(nl("comment.removeReaction",n),["reactor"]);Nn(t);const a=nt(["comment","get",n.comments[0].commentId]);e(cd.comment(a.data))}else e(cd.comment(n.comments[0]))}))},Rl=(e,t,n)=>{const a=Ge(),s=(a,s,o)=>{a===e&&s===t&&n(o)};if("message"===e){return qt(a,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await ua(e);t.reactions[0]&&(Nn(t),Nn({reactors:t.reactions}),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return qt(a,"post.addReaction","post.addReaction",(e=>{const{reactor:t}=e,n=_n(e,["reactor"]);Nn(n),Nn({reactions:[t]}),s("post",e.posts[0].postId,t)}))}if("story"===e){return qt(a,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=_n(e,["reactions"]);Nn(n),Nn({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}))}return qt(a,"comment.addReaction","comment.addReaction",(e=>{const{reactor:t}=e,n=_n(e,["reactor"]);Nn(n),Nn({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))},Pl=(e,t,n)=>{const a=Ge(),s=(a,s,o)=>{a===e&&s===t&&n(o)};if("message"===e){return qt(a,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await ua(e);t.reactions[0]&&(Nn(t),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return qt(a,"post.removeReaction","post.removeReaction",(e=>{const{reactor:t}=e,n=_n(e,["reactor"]);Nn(n),Nn({reactions:[t]}),s("post",e.posts[0].postId,t)}))}if("story"===e){return qt(a,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=_n(e,["reactions"]);Nn(n),Nn({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}))}return qt(a,"comment.removeReaction","comment.removeReaction",(e=>{const{reactor:t}=e,n=_n(e,["reactor"]);Nn(n),Nn({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))};class Dl extends fr{async getRequest(e,t){const{limit:n=me,referenceType:a}=e,s=_n(e,["limit","referenceType"]),o=t?{token:t}:{limit:n};Ge().log("reaction/queryReactions",e);if(!["post","comment","story","message"].includes(a))throw new Qe("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:i}=await this.http.get("/api/v3/reactions",{params:Object.assign(Object.assign({},s),{referenceType:a,referenceVersion:"message"===a?5:void 0,options:o})});return i}}class Ul extends Ir{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=Ge(),s=a.cache&&Date.now();if(a.cache){const{reactions:e}=n,a=_n(n,["reactions"]);Nn(Object.assign(Object.assign({},a),{reactions:e,reactors:null===(t=e[0])||void 0===t?void 0:t.reactors}),{cachedAt:s})}}appendToQueryStream(e,t,n=!1){var a,s,o,i;const r=null!==(s=null===(a=e.reactions[0])||void 0===a?void 0:a.reactors)&&void 0!==s?s:[];if(n)at(this.cacheKey,{data:r.map(Xe("reactor"))});else{const e=null===(o=nt(this.cacheKey))||void 0===o?void 0:o.data,t=null!==(i=null==e?void 0:e.data)&&void 0!==i?i:[];at(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...r.map(Xe("reactor"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(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))),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class kl extends Or{constructor(e,t){const n=R.default(e),a=["reaction","collection",n];super(new Dl(e),n,a,t),this.query=e,this.queryStreamController=new Ul(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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=>Rl(this.query.referenceType,this.query.referenceId,e),action:"onAdded"},{fn:e=>Pl(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const a=Ge(),s=(a,s,o)=>{a===e&&s===t&&n(o)};if("message"===e)return qt(a,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await ua(e);t.reactions[0]&&(Nn(t),s("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return qt(a,"local.post.removeReaction","local.post.removeReaction",(e=>{s("post",e.post.postId,e.reactor)}));if("story"===e)return qt(a,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=_n(e,["reactions"]);Nn(n),Nn({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}));return qt(a,"local.comment.removeReaction","local.comment.removeReaction",(e=>{s("comment",e.comment.commentId,e.reactor)}))})(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const a=Ge(),s=(a,s,o)=>{a===e&&s===t&&n(o)};if("message"===e)return qt(a,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await ua(e);t.reactions[0]&&(Nn(t),Nn({reactors:t.reactions}),s("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return qt(a,"local.post.addReaction","local.post.addReaction",(e=>{s("post",e.post.postId,e.reactor)}));if("story"===e)return qt(a,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=_n(e,["reactions"]);Nn(n),Nn({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}));return qt(a,"local.comment.addReaction","local.comment.addReaction",(e=>{s("comment",e.comment.commentId,e.reactor)}))})(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>nt(["reactor","get",e]))).filter(Boolean).map((({data:e})=>cd.reactor(e))))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var jl=Object.freeze({__proto__:null,addReaction:sl,removeReaction:ol,onReactionAdded:(e,t,n)=>{const a=a=>{Xe(e)(a)===t&&n(a)};if("message"===e){const e=Ge(),t=async e=>{var t;const n=await ua(e),s=nt(["message","get",n.messages[0].messageId]),o=(null===(t=null==s?void 0:s.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Nn(n),o&&a(n.messages[0])};return qt(e,"reaction/onReactionAdded","message.updated",t)}return"post"===e?yl(a):Tl(a)},onReactionRemoved:(e,t,n)=>{const a=a=>{Xe(e)(a)===t&&n(a)};if("message"===e){const e=Ge(),t=async e=>{var t;const n=await ua(e),s=nt(["message","get",n.messages[0].messageId]),o=(null===(t=null==s?void 0:s.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Nn(n),o&&a(n.messages[0])};return qt(e,"reaction/onReactionRemoved","message.updated",t)}return"post"===e?vl(a):Al(a)},onReactorAdded:Rl,onReactorRemoved:Pl,getReactions:(e,t,n)=>{const{log:a,cache:s}=Ge(),o=Date.now();a(`getReactions(tmpid: ${o}) > listen`);const i=new kl(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{it(c)})),()=>{a(`getReactions(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});function El(e){const{comments:t}=e;return Object.assign(Object.assign({},e),{comments:t.map((e=>e.hasOwnProperty("myReactions")?e:Object.assign({myReactions:[]},e)))})}const Ml=async()=>{var e;const t=Ge();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&&(it(["archivedChannel","get"]),a.forEach((e=>{e.channelId&&at(["archivedChannel","get",e.channelId],e)}))),a.map((e=>e.channelId)).filter((e=>!!e))},ql=e=>{const t=Ge(),n=[qt(t,"onMessageUpdated","message.updated",(async t=>{const n=await ua(t);Nn(n),e(n.messages[0])})),qt(t,"onMessageUpdated","local.message.updated",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},xl=e=>{const t=Ge(),n=[qt(t,"message/onMessageDeleted","message.deleted",(async t=>{const n=await ua(t);Nn(n),e(n.messages[0])})),qt(t,"message/onMessageDeleted","local.message.deleted",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},Kl=e=>{const t=Ge(),n=[qt(t,"onSubChannelUpdated","message-feed.updated",(async t=>{const n=await va(t);Nn(n),e(n.messageFeeds[0])})),qt(t,"onSubChannelUpdated","local.message-feed.updated",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}};function Nl(e,t){at(["channel","get",e.channelId],Wn(e,t))}const Fl=e=>{const t=Ge();return qt(t,"channelMarker/onChannelMarkerUpdated","local.channelMarker.updated",(t=>{e(t.userEntityMarkers[0])}))},_l=async(e,t=!1)=>{const n=Ge(),a=await fa(e);await n.http.delete(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{params:{permanent:t}});const s=Object.assign(Object.assign({},a.data),{isDeleted:!0,updatedAt:et(a.data.updatedAt)});return t?setTimeout((()=>{Fn("subChannel",e)}),0):ot(["subChannel","get",e],s),xt("local.message-feed.deleted",{messageFeeds:[s]}),s},Bl=e=>qt(Ge(),"onSubChannelFetched","local.message-feed.fetched",(t=>e(t.messageFeeds[0]))),$l=()=>`LOCAL_${Un()}`;let Ll;const Ql=async(e,t)=>{const n=Ge();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)}`,ha(t)),s=await ua(a),o=n.cache&&Date.now();n.cache&&Nn(s,{cachedAt:o});const{messages:i}=s;return xt("local.message.updated",{messages:i}),{data:cd.message(i.find((t=>t.messageId===e))),cachedAt:o}};Ql.optimistically=(e,t)=>{const n=Ge();if(n.log("message/updateMessage.optimistically",t),!n.cache)return;const a=nt(["message","get",e]);if(!a)return;const s=Object.assign(Object.assign(Object.assign({},a.data),t),{updatedAt:(new Date).toISOString()});return ot(["message","get",e],s,{cachedAt:-1}),xt("local.message.updated",{messages:[s]}),{data:cd.message(s),cachedAt:-1}};const Jl=async(e,t)=>{const n=Ge();n.log("message/editMessage",t);const{data:a}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,ha(t)),s=await ua(a),o=n.cache&&Date.now();n.cache&&Nn(s,{cachedAt:o});const{messages:i}=s;return xt("local.message.updated",{messages:i}),{data:cd.message(i.find((t=>t.messageId===e))),cachedAt:o}};Jl.optimistically=(e,t)=>{const n=Ge();if(n.log("message/editMessage.optimistically",t),!n.cache)return;const a=nt(["message","get",e]);if(!a)return;const s=Object.assign(Object.assign(Object.assign({},a.data),t),{updatedAt:(new Date).toISOString()});return ot(["message","get",e],s,{cachedAt:-1}),xt("local.message.updated",{messages:[s]}),{data:cd.message(s),cachedAt:-1}};const Vl=async e=>{var t;const n=Ge();if(n.log("message/deleteMessage",e),e.includes("LOCAL_")){const n=null===(t=nt(["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 xt("local.message.deleted",{messages:[a]}),cd.message(a)}const{data:a}=await n.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`),s=await ua(a);return xt("local.message.deleted",{messages:[s.messages[0]]}),cd.message(s.messages[0])};Vl.optimistically=e=>{Ge().log("message/deleteMessage.optimistically",e);const t=nt(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return ot(["message","get",e],n,{cachedAt:-1}),xt("local.message.deleted",{messages:[n]}),{data:cd.message(n),cachedAt:-1}};const Hl=async e=>{const t=Ge();t.log("message/softDeleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const n=await Bd(e);return xt("local.message.deleted",{messages:[n.data]}),cd.message(n.data)};Hl.optimistically=e=>{Ge().log("message/softDeleteMessage.optimistically",e);const t=nt(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return ot(["message","get",e],n,{cachedAt:-1}),xt("local.message.deleted",{messages:[n]}),{data:cd.message(n),cachedAt:-1}};const zl=async e=>{const t=Ge();t.log("user/getReadUsers",e);const{page:n,messageId:a}=e,s=_n(e,["page","messageId"]),{data:o}=await t.http.get(`/api/v1/markers/messages/${a}/read-users`,{params:Object.assign(Object.assign({},s),{options:{token:je(n,"afterbeforeraw")}})}),{paging:i,publicUserIds:r,userFeedMarkers:c}=o,d=_n(o,["paging","publicUserIds","userFeedMarkers"]),l=t.cache&&Date.now();if(t.cache){Nn(Object.assign(Object.assign({},d),{userFeedMarkers:Jn(c)}),{cachedAt:l});const e=["read-user","query",Object.assign(Object.assign({messageId:a},s),{options:Object.assign({},n)})];at(e,{users:r,paging:i})}let u=[];r.length>0&&({data:u}=await dd(r));return{data:u,cachedAt:l,prevPage:Ee(i.previous),nextPage:Ee(i.next)}};zl.locally=e=>{var t;const n=Ge();if(n.log("user/getReadUsers.locally",e),!n.cache)return;const{page:a}=e,s=_n(e,["page"]),o=["read-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},a)})],{data:i,cachedAt:r}=null!==(t=nt(o))&&void 0!==t?t:{},c=null==i?void 0:i.users.map((e=>{var t;return null===(t=nt(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:r,prevPage:Ee(null==i?void 0:i.paging.previous),nextPage:Ee(null==i?void 0:i.paging.next)}};const Gl=async e=>{const t=Ge();t.log("user/getDeliveredUsers",e);const{page:n,messageId:a}=e,s=_n(e,["page","messageId"]),{data:o}=await t.http.get(`/api/v1/markers/messages/${a}/delivered-users`,{params:Object.assign(Object.assign({},s),{options:{token:je(n,"afterbeforeraw")}})}),{paging:i,publicUserIds:r,userFeedMarkers:c}=o,d=_n(o,["paging","publicUserIds","userFeedMarkers"]),l=t.cache&&Date.now();if(t.cache){Nn(Object.assign(Object.assign({},d),{userFeedMarkers:Jn(c)}),{cachedAt:l});const e=["delivered-user","query",Object.assign(Object.assign({messageId:a},s),{options:Object.assign({},n)})];at(e,{users:r,paging:i})}let u=[];r.length>0&&({data:u}=await dd(r));return{data:u,cachedAt:l,prevPage:Ee(i.previous),nextPage:Ee(i.next)}};Gl.locally=e=>{var t;const n=Ge();if(n.log("user/getDeliveredUsers.locally",e),!n.cache)return;const{page:a}=e,s=_n(e,["page"]),o=["delivered-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},a)})],{data:i,cachedAt:r}=null!==(t=nt(o))&&void 0!==t?t:{},c=null==i?void 0:i.users.map((e=>{var t;return null===(t=nt(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:r,prevPage:Ee(null==i?void 0:i.paging.previous),nextPage:Ee(null==i?void 0:i.paging.next)}};const Yl=e=>{const t=Ge();return qt(t,"onMessageFlagged","message.flagged",(async t=>{const n=await ua(t);Nn(n),e(n.messages[0])}))},Wl=e=>{const t=Ge();return qt(t,"onMessageUnflagged","message.unflagged",(async t=>{const n=await ua(t);Nn(n),e(n.messages[0])}))},Xl=e=>{const t=Ge();return qt(t,"onMessageFlagCleared","message.flagCleared",(async t=>{const n=await ua(t);Nn(n),e(n.messages[0])}))},Zl=e=>{const t=Ge();return qt(t,"onMessageReactionAdded","message.reactionAdded",(async t=>{const n=await ua(t,"message.reactionAdded");Nn(n),e(n.messages[0])}))},eu=e=>{const t=Ge();return qt(t,"onMessageReactionRemoved","message.reactionRemoved",(async t=>{const n=await ua(t,"message.reactionRemoved");Nn(n),e(n.messages[0])}))},tu=e=>{const t=Ge();return qt(t,"message/onMessageFetched","local.message.fetched",(t=>{Nn(t),e(t.messages[0])}))},nu=e=>{const t=Ge();return qt(t,"stream/onStreamViewerDidBan","video-streaming.viewerDidBan",(t=>{var n;const{list:a}=t;a.forEach((e=>{var t;st(["stream","get",e.streamId],{watcherUrl:null});const n=null===(t=tt(["message","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.creatorId===e.userId));null==n||n.forEach((e=>{st(e.key,{isDeleted:!0})}))}));const s=null===(n=nt(["stream","get",a[0].streamId]))||void 0===n?void 0:n.data;s&&e(s)}))};class au extends Ir{constructor(e,t,n,a,s){super(e,t),this.notifyChange=n,this.preparePayload=a,this.paginationController=s}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.messages.map(Xe("message")),query:this.query});else{const n=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,o=null!==(s=null==n?void 0:n.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},n),{data:"next"===t?[...new Set([...o,...e.messages.map(Xe("message"))])]:[...new Set([...e.messages.map(Xe("message")),...o])]}))}}reactor(e){return t=>{var n,a,s,o;if("onCreate"===e){const e=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data,{referenceId:o}=t;if(!e)return;if(this.query.subChannelId!==(null==t?void 0:t.subChannelId)||!e)return;if(this.query.type&&this.query.type!==t.dataType)return;if(this.query.excludingTags&&(null===(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===(s=this.query.includingTags)||void 0===s?void 0:s.some((e=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.includes(e)}))))return;this.query.sortBy&&"segmentDesc"!==this.query.sortBy||this.paginationController.getPrevToken()||(e.data=[...new Set([null!=o?o:t.messageId,...e.data])]),"segmentAsc"!==this.query.sortBy||this.paginationController.getNextToken()||(e.data=[...new Set([...e.data,null!=o?o:t.messageId])]),at(this.cacheKey,e)}if("onDelete"===e&&"error"===t.syncState){const e=null===(o=nt(this.cacheKey))||void 0===o?void 0:o.data;if(!e)return;if(e.data.includes(t.messageId)){const n=e.data.filter((e=>e!==t.messageId));at(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 fr{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 Or{constructor(e,t){const n=R.default(e),a=["message","collection",n];super(new su(e),n,a,t),this.query=e,this.queryStreamController=new au(this.query,this.cacheKey,this.notifyChange.bind(this),ua,this.paginationController),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:vi,action:"onCreate"},{fn:fi,action:"onCreate"},{fn:xl,action:"onDelete"},{fn:ql,action:"onUpdate"},{fn:Yl,action:"onFlagged"},{fn:Wl,action:"onUnflagged"},{fn:Xl,action:"onFlagCleared"},{fn:Zl,action:"onReactionAdded"},{fn:eu,action:"onReactionRemoved"},{fn:Od(Yi,"contentId","message"),action:"onUpdate"},{fn:Od(Wi,"contentId","message"),action:"onUpdate"},{fn:Od(nu,"channelId","message"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>aa(e))).filter(Boolean).map((e=>cd.message(e))))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),onPrevPage:()=>this.loadPage({direction:"prev"}),data:i,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=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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 fr{async getRequest(e,t){const{query:n,exactMatch:a,channelId:s,messageFeedId:o,userIds:i,tags:r,types:c,sortBy:d,orderBy:l,limit:u=me}=e,h=t?{token:t}:{limit:u,sortBy:d,orderBy:l},{data:m}=await this.http.get("/api/v2/search/messages",{params:{query:n,exactMatch:a,channelId:s,messageFeedId:o,userIds:i,tags:r,types:c,options:h}});return m}}class ru extends Ir{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){var t;const n=await ua(e),a=Ge(),s=a.cache&&Date.now();a.cache&&(Nn(n,{cachedAt:s}),(null===(t=e.channels)||void 0===t?void 0:t.length)&&e.channels.forEach((e=>{at(["channel","get",e.channelId],e,{cachedAt:s})})))}appendToQueryStream(e,t,n=!1){var a,s;if(n)return void at(this.cacheKey,{data:e.messages.map(Xe("message"))});const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,i=null!==(s=null==o?void 0:o.data)&&void 0!==s?s:[],r=e.messages.map(Xe("message"));at(this.cacheKey,Object.assign(Object.assign({},o),{data:"prev"===t?[...new Set([...r,...i])]:[...new Set([...i,...r])]}))}}class cu extends Or{constructor(e,t){const n=R.default(e),a=["message","search",n];super(new iu(e),n,a,t),this.queryStreamController=new ru(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,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>aa(e))).filter(Tr).map((e=>cd.message(e))))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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=Ge();t.log("message/createMessage",e);const n=(e=>{var t,n;const a=Ge();if(!a.cache)return;Ll=e.referenceId||$l();const s=Object.assign({messageId:Ll,uniqueId:Ll},e);a.log("message/createMessage.optimistically",s);const o=nt(["subChannel","get",e.subChannelId]);if(o&&(ot(["subChannel","get",e.subChannelId],Object.assign(Object.assign({},o.data),{messageCount:o.data.messageCount+1})),o.data.channelId===o.data.subChannelId)){const e=nt(["channel","get",o.data.channelId]);(null==e?void 0:e.data)&&ot(["channel","get",o.data.channelId],Object.assign(Object.assign({},e.data),{messageCount:(null!==(t=e.data.messageCount)&&void 0!==t?t:0)+1}))}const i=(new Date).toISOString(),r=Object.assign({creatorId:a.userId,creatorPrivateId:Dt()._id,channelSegment:(null!==(n=null==o?void 0:o.data.messageCount)&&void 0!==n?n:0)+1,childrenNumber:0,createdAt:i,updatedAt:i,syncState:"syncing",isDeleted:!1},s);return at(["message","get",r.messageId],r,{cachedAt:-5}),xt("local.message.created",{messages:[r]}),r})(e),a=e.referenceId||Ll||$l();Ll=void 0;try{const{data:n}=await t.http.post("/api/v5/messages",Object.assign(Object.assign({},ha(e)),{referenceId:a})),s=await ua(n),{messages:o}=s,i=t.cache&&Date.now();return t.cache&&Nn(s,{cachedAt:i}),xt("local.message.created",{messages:[Object.assign(Object.assign({},o[0]),{syncState:"synced"})]}),{data:cd.message(o[0]),cachedAt:i}}catch(e){throw xt("local.message.created",{messages:[Object.assign(Object.assign({},n),{syncState:"error"})]}),e}},updateMessage:Ql,editMessage:Jl,deleteMessage:Vl,softDeleteMessage:Hl,markAsDelivered:async(e,t)=>{const n=Ge();n.log("message/markAsDelivered",e,t);const{data:a}=await n.http.put(`/api/v1/markers/message-feeds/${e}/mark-delivering`,{messageId:t}),{userMarkers:s,userEntityMarkers:o,userFeedMarkers:i}=a,r=_n(a,["userMarkers","userEntityMarkers","userFeedMarkers"]),c=n.cache&&Date.now();return n.cache&&Nn(Object.assign({userMarkers:s,userEntityMarkers:Qn(o),userFeedMarkers:Jn(i)},r),{cachedAt:c}),!0},getReadUsers:zl,getDeliveredUsers:Gl,flagMessage:async(t,n)=>{const a=Ge();a.log("message/flag",t);const s=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,a])=>t!==e.ContentFlagReasonEnum.Others&&a===n)),o={reason:s?n:e.ContentFlagReasonEnum.Others,detail:s?"":n},{data:i}=await a.http.post(`/api/v5/messages/${encodeURIComponent(t)}/flags`,o);if(a.cache){const e=await ua(i);Nn(e)}return xt("message.flagged",i),!!i},unflagMessage:async e=>{const t=Ge();t.log("message/unflag",e);const{data:n}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await ua(n);Nn(e)}return xt("message.unflagged",n),!!n},isMessageFlaggedByMe:async e=>{const t=Ge();t.log("message/isMessageFlaggedByMe",e);const{data:n}=await t.http.get(`/api/v5/messages/${encodeURIComponent(e)}/flags`);return n.result},onMessageCreatedMqtt:vi,onMessageCreatedLocal:fi,onMessageUpdated:ql,onMessageDeleted:xl,onMessageFlagged:Yl,onMessageUnflagged:Wl,onMessageFlagCleared:Xl,onMessageReactionAdded:Zl,onMessageReactionRemoved:eu,onMessageFetched:tu,getMessage:(e,t)=>jr(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?cd.message(e.data):n}))}),"messageId",Bd,[tu,ql,xl,Yl,Wl,Xl,Zl,eu,Od(Yi,"contentId","message"),Od(Wi,"contentId","message"),Od(nu,"channelId","message")]),getMessages:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getMessages(tmpid: ${o}) > listen`);const i=new ou(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{it(c)})),()=>{a(`getMessages(tmpid: ${o}) > dispose`),r.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}=Ge();a||console.log(ye);const s=Date.now();n(`searchMessage(tmpid: ${s}) > listen`);const o=new cu(e,t),i=o.startSubscription(),r=o.getCacheKey();return i.push((()=>{it(r)})),()=>{n(`searchMessage(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},convertFromRaw:da,prepareMessagePayload:ua,convertParams:ha,convertQueryParams:ma});const lu=e=>{const t=Ge();return qt(t,"subChannelMarker/onSubChannelUnreadUpdatedLocal","local.subChannelUnread.updated",(t=>{e(t)}))};class uu extends fr{async getRequest(e,t){var n;const{limit:a=me}=e,s=null!==(n=function(e){var{excludeDefaultSubChannel:t}=e,n=_n(e,["excludeDefaultSubChannel"]);const a=Object.assign({},n);return void 0!==t&&(a.excludeDefaultMessageFeed=t),a}(_n(e,["limit"])))&&void 0!==n?n:{},{channelId:o,includeDeleted:i}=s,r=_n(s,["channelId","includeDeleted"]),c=t?{token:t}:{limit:a},{data:d}=await this.http.get(`/api/v5/message-feeds/channel/${o}`,{params:Object.assign(Object.assign({},r),{isDeleted:sa(i),options:c})});return d}}class hu extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.messageFeeds.map((({messageFeedId:e})=>e))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(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=nt(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])]),at(this.cacheKey,a)}this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class mu extends Or{constructor(e,t){const n=R.default(e),a=["subChannel","collection",n];super(new uu(e),n,a,t),this.query=e,this.queryStreamController=new hu(this.query,this.cacheKey,this.notifyChange.bind(this),va),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:Bl,action:"onCreate"},{fn:bi,action:"onCreate"},{fn:Ii,action:"onDelete"},{fn:e=>Kl((async t=>{if(!this.isRelatedCollection(t.subChannelId))return;const n=Ge();if("no-message-preview"!==await n.getMessagePreviewSetting(!1)){const e=zn(t.subChannelId);(null==e?void 0:e.subChannelId)===t.subChannelId&&Hn(t.updatedAt)>Hn(e.subChannelUpdatedAt)&&at(["messagePreviewSubChannel","get",t.subChannelId],Object.assign(Object.assign({},e),{subChannelName:t.displayName,subChannelUpdatedAt:t.updatedAt}))}e(t)})),action:"onUpdate"},{fn:Od((e=>vi((async t=>{this.isRelatedCollection(t.subChannelId)&&(await Ia(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Od((e=>fi((async t=>{this.isRelatedCollection(t.subChannelId)&&(await Ia(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:e=>zi((t=>{var n;const a=null!==(n=t.map((({feedId:e})=>nt(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];0!==a.length&&e(a)})),action:"onUpdate"},{fn:Od(Hi,"feedId","subChannel"),action:"onUpdate"},{fn:Od((e=>ql((async t=>{var n;const a=Ge();if("no-message-preview"===await a.getMessagePreviewSetting(!1))return;const s=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;s&&s.data.includes(t.subChannelId)&&(Ca(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Od((e=>xl((async t=>{const n=Ge(),a=await n.getMessagePreviewSetting(!1);"no-message-preview"!==a&&this.isRelatedCollection(t.subChannelId)&&("message-preview-not-include-deleted"===a?await fa(t.subChannelId):await Ca(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Od(lu,"subChannelId","subChannel"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(Gn))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.includeDeleted||(t=rt(e,"isDeleted",!1)),t.sort(Tt),t}isRelatedCollection(e){var t;const n=null===(t=nt(this.cacheKey))||void 0===t?void 0:t.data;return n&&n.data.includes(e)}}const gu={},pu=async e=>{const t=await(async e=>{const t=fa.locally(e);if(t)return t.data.channelId;const{data:n}=await fa(e);return n.channelId})(e),n=Ht({channelId:t,subChannelId:e});gu[e]=Zt(n)};var yu=Object.freeze({__proto__:null,getSubChannelByIds:Ks,createSubChannel:async e=>{const t=Ge();t.log("user/createSubChannel",e);const n=await t.http.post("/api/v5/message-feeds",{channelId:e.channelId,name:e.displayName}),a=await va(n.data),s=t.cache&&Date.now();return t.cache&&Nn(a,{cachedAt:s}),xt("message-feed.created",n.data),{data:a.messageFeeds[0],cachedAt:s}},updateSubChannel:async(e,t)=>{const n=Ge();n.log("channel/updateSubChannel",e,t);const a=await n.http.put(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{name:t.displayName}),s=await va(a.data),o=n.cache&&Date.now();return n.cache&&Nn(s,{cachedAt:o}),xt("message-feed.updated",a.data),{data:s.messageFeeds[0],cachedAt:o}},deleteSubChannel:_l,hardDeleteSubChannel:async e=>{Ge().log("channel/hardDeleteSubChannel",e);return await _l(e,!0)},softDeleteSubChannel:async e=>{Ge().log("channel/softDeleteSubChannel",e);return await _l(e,!1)},onSubChannelCreated:bi,onSubChannelUpdated:Kl,onSubChannelDeleted:Ii,getSubChannel:(e,t)=>{const n=Ge();let a;return jr(e,(e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:Gn(e.data)}),s=_n(n,["origin"]);return Na(a,s)?void 0:(a=s,t(n))}),"subChannelId",fa,[Bl,t=>Kl((async a=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(Oa(a),a.subChannelId===e&&t(a))})),Ii,Od(Hi,"feedId","subChannel"),t=>zi((n=>{var a;if(!n.find((({feedId:t})=>t===e)))return;const s=null===(a=nt(["subChannel","get",e]))||void 0===a?void 0:a.data;s&&t(s)})),Od((t=>vi((async n=>{n.subChannelId===e&&(await Ia(n),t(n))}))),"subChannelId","subChannel"),Od((t=>fi((async n=>{n.subChannelId===e&&(await Ia(n),t(n))}))),"subChannelId","subChannel"),Od((t=>ql((async a=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&a.subChannelId===e&&(Ca(a),t(a))}))),"subChannelId","subChannel"),Od((t=>xl((async a=>{const s=await n.getMessagePreviewSetting(!1);"no-message-preview"!==s&&a.subChannelId===e&&("message-preview-include-deleted"===s&&await Ca(a),"message-preview-not-include-deleted"===s&&await fa(a.subChannelId),t(a))}))),"subChannelId","subChannel"),Od(lu,"subChannelId","subChannel")],{forceDispatch:!0})},getSubChannels:(e,t,n)=>{const{log:a,cache:s}=Ge(),o=Date.now();a(`getSubChannels(tmpid: ${o}) > listen`),s||console.log(ye);const i=new mu(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{it(c)})),()=>{a(`getSubChannels(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},markReadEngineOnLoginHandler:xs,startMessageReceiptSync:async e=>(await pu(e),!0),stopMessageReceiptSync:e=>(gu[e]&&gu[e](),!0)});const vu=e=>{const t=Ge();return qt(t,"channelMarker/onChannelUnreadInfoUpdatedLocal","local.channelUnreadInfo.updated",(t=>{e(t)}))},fu=e=>{const t=Ge();return qt(t,"channel/onChannelUnreadUpdatedLocal","local.channelUnread.updated",(t=>{e(t)}))};class bu extends fr{async getRequest(e,t){const{limit:n=me,displayName:a,membership:s}=e,o=_n(e,["limit","displayName","membership"]),i=t?{token:t}:{limit:n},{data:r}=await this.http.get("/api/v3/channels",{params:Object.assign(Object.assign({},o),{keyword:a,filter:s,options:i})});return r}}class Iu extends Sr{async getRequest(e){const{data:t}=await this.http.get("/api/v3/channels/list",{params:Object.assign({},e)});return t}}class Cu extends Ir{constructor(e,t,n,a,s){super(e,t),this.notifyChange=n,this.preparePayload=a,this.paginationController=s}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.channels.map(Xe("channel"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channels.map(Xe("channel"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(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(Xe("channel")),...a.data])]:a.data=[...new Set([t.channelInternalId,...a.data])]),"onArchived"===e){const e=Array.isArray(t)?t.map(Xe("channel")):[Xe("channel")(t)];a.data=a.data.filter((t=>!e.includes(t)))}at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const wu=e=>{const t=Ge();if(t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()){Uo().resolve(e.channelId,"userMessageFeedMarker")}},Su=e=>{const t=Ge();return qt(t,"onChannelResolved","local.channel.resolved",(async t=>{e(t)}))},Ou=e=>{const t=Ge();return qt(t,"userMessageFeedMarker/onUserMessageFeedMarkerResolved","local.userMessageFeedMarkers.resolved",(t=>{e(t)}))};class Tu extends Or{constructor(e,t){const n=R.default(e),a=["channel","collection",n],s=Tu.getPaginationController(e);super(s,n,a,t),this.query=e,this.queryStreamController=new Cu(this.query,this.cacheKey,this.notifyChange.bind(this),(async e=>{try{const t=Ge();t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await ka(e)}catch(e){console.error("Error while preparing unread count info",e)}return Da(e)}),s),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;let i=null!==(s=o.data.map((e=>nt(["channel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(Ds))&&void 0!==s?s:[];this.paginationController instanceof bu&&(i=this.applyFilter(i)),(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:this.paginationController instanceof bu?()=>this.loadPage({direction:"next"}):void 0,data:i,hasNextPage:this.paginationController instanceof bu&&!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Ge();let n=e;switch(n=rt(n,"isDeleted",this.query.isDeleted),n=ct(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=lt(n,this.query.membership,t)),this.query.sortBy){case"firstCreated":n=n.sort(It);break;case"lastCreated":n=n.sort(wt);break;case"displayName":n=n.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(ft);break;default:n=n.sort(Tt)}return n}shouldAbort(e){var t,n;const a=null===(t=nt(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 Ge().getMessagePreviewSetting(!1)}static getPaginationController(e){return e.channelIds&&e.channelIds.length>0?new Iu(e):new bu(e)}getSubscriptions(){const e=[{fn:Od((e=>vi((t=>{var n,a;const s=Uo();(null===(n=nt(["subChannelUnreadInfo","get",t.subChannelId]))||void 0===n?void 0:n.data)||s.resolve(t.subChannelId,"userMessageFeedMarker");const o=null===(a=nt(["channel","get",t.channelId]))||void 0===a?void 0:a.data;o?(Nl(o,{lastActivity:t.createdAt}),e(t)):s.resolve(t.channelId,"channel")}))),"channelId","channel"),action:"onUpdate"},{fn:Od((e=>fi((t=>{var n;const a=null===(n=nt(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Nl(a,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ga,action:"onDelete"},{fn:Qa,action:"onUpdate"},{fn:ss,action:"onMute"},{fn:e=>Xa((t=>{wu(t),e(t)})),action:"onJoin"},{fn:e=>ts(((t,n)=>{var a,s;const{userId:o}=Ge();if("member"===this.query.membership&&o===n.userId){const e=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;at(this.cacheKey,Object.assign(Object.assign({},e),{data:null!==(s=null==e?void 0:e.data.filter((e=>e!==t.channelId)))&&void 0!==s?s:[]}))}return e(t)})),action:"onLeft"},{fn:rs,action:"onMemberAdded"},{fn:ls,action:"onMemberRemoved"},{fn:e=>Ss((t=>{const n=t.archives.map((e=>{var t;return null===(t=nt(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onArchived"},{fn:e=>Os((t=>{const n=t.archives.map((e=>{var t;return null===(t=nt(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onUnarchived"},{fn:Od(Vi,"entityId","channel"),action:"onUpdate"},{fn:Od(Fl,"entityId","channel"),action:"onUpdate"},{fn:Od((e=>vi((async t=>{var n;if("no-message-preview"===await Tu.getMessagePreviewSetting())return;if(wa(t),this.shouldAbort(t.channelId))return;const a=null===(n=nt(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Nl(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Od((e=>fi((async t=>{var n;if("no-message-preview"===await Tu.getMessagePreviewSetting())return;if(wa(t),this.shouldAbort(t.channelId))return;const a=null===(n=nt(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Nl(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Od((e=>ql((async t=>{"no-message-preview"!==await Tu.getMessagePreviewSetting()&&(await Sa(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Od((e=>xl((async t=>{const n=await Tu.getMessagePreviewSetting();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await Sa(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&await gc(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:Od((e=>Ii((async t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(!a)return;a.data.find((e=>{const n=Vn(e);return(null==n?void 0:n.subChannelId)===t.subChannelId}))&&(await gc(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Od((e=>Kl((async t=>{var n;if("no-message-preview"===await Tu.getMessagePreviewSetting())return;(null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data)&&(await Oa(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Od(bi,"channelId","channel"),action:"onUpdate"},{fn:Su,action:"onResolveChannel"},{fn:e=>Ou((async t=>{if(t.feedMarkers){const n=t.feedMarkers.map((e=>{var t;return null===(t=nt(["channel","get",e.entityId]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"OnResolveUnread"},{fn:Od(vu,"channelId","channel"),action:"onUpdate"},{fn:Od((e=>fu((t=>{t.forEach(e)}))),"channelId","channel"),action:"onUpdate"}];return this.paginationController instanceof fr?[...e,{fn:e=>Ba((t=>{wu(t),e(t)})),action:"onCreate"}]:e}}const Au=()=>{var e;const t=Ge();t.log("channel/getTotalChannelsUnread.locally");const n=(null===(e=tt(["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 Ru extends fr{async getRequest(e,t){var n,a;const s=null!==(n=e.limit)&&void 0!==n?n:me,o=t?Number.parseInt(t,10):0;0===o&&await Ml();const i=(null!==(a=tt(["archivedChannel","get"]))&&void 0!==a?a:[]).map((e=>e.data)).slice().sort(((e,t)=>Number(new Date(t.archivedAt))-Number(new Date(e.archivedAt)))),r=o*s,c=r+s,d=i.slice(r,c),l=c<i.length;return d.length>0&&await Us(d.map((e=>e.channelId))),{archives:d,paging:{next:l?String(o+1):void 0,previous:void 0}}}}class Pu extends Ir{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){}appendToQueryStream(e,t,n=!1){var a,s;const o=e.archives.map((e=>e.channelId));if(n)return void at(this.cacheKey,{data:o,params:{}});const i=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,r=null!==(s=null==i?void 0:i.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},i),{data:"prev"===t?[...new Set([...o,...r])]:[...new Set([...r,...o])]}))}reactor(e){return t=>{var n;const a=null===(n=nt(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)))),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Du extends Or{constructor(e,t){const n=R.default(e),a=["archivedChannel","collection",n];super(new Ru(e),n,a,t),this.queryStreamController=new Pu(e,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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=>Ss((t=>e(t.archives.map((e=>e.channelId))))),action:"onArchived"},{fn:e=>Os((t=>e(t.archives.map((e=>e.channelId))))),action:"onUnarchived"},{fn:e=>Qa((t=>e([t.channelId]))),action:"onUpdate"},{fn:e=>Ga((t=>e([t.channelId]))),action:"onDelete"}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>nt(["channel","get",e]))).filter((e=>Boolean(e))).map((({data:e})=>e)).map(Ds))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class Uu extends fr{async getRequest(e,t){const{query:n,exactMatch:a,isMemberOnly:s,types:o,tags:i,sortBy:r,orderBy:c,limit:d=ge}=e,l=t?{token:t}:{limit:Math.min(100,Math.max(1,d))},{data:u}=await this.http.get("/api/v2/search/channels",{params:{query:n,exactMatch:a,isMemberOnly:s,types:o,tags:i,sortBy:r,orderBy:c,options:l}});return u}}class ku extends Ir{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){const t=await Da(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)return void at(this.cacheKey,{data:e.channels.map(Xe("channel"))});const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,i=null!==(s=null==o?void 0:o.data)&&void 0!==s?s:[],r=e.channels.map(Xe("channel"));at(this.cacheKey,Object.assign(Object.assign({},o),{data:"prev"===t?[...new Set([...r,...i])]:[...new Set([...i,...r])]}))}reactor(){return()=>this.notifyChange({origin:"event",loading:!1})}subscribeRTE(e){return e.map((e=>e.fn(this.reactor())))}}const ju=()=>Ge().getMessagePreviewSetting(!1);class Eu extends Or{constructor(e,t){const n=R.default(e),a=["channel","search",n];super(new Uu(e),n,a,t),this.queryStreamController=new ku(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,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>nt(["channel","get",e]))).filter(Boolean).map((e=>Ds(e.data))))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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=nt(this.cacheKey))||void 0===t?void 0:t.data;return!n||!n.data.find((t=>t===e))}getSubscriptions(){return[{fn:Od((e=>vi((t=>{var n;const a=null===(n=nt(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Nl(a,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Od((e=>fi((t=>{var n;const a=null===(n=nt(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Nl(a,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ga,action:"onDelete"},{fn:Qa,action:"onUpdate"},{fn:ss,action:"onMute"},{fn:e=>Ss((t=>{const n=t.archives.map((e=>{var t;return null===(t=nt(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onArchived"},{fn:e=>Os((t=>{const n=t.archives.map((e=>{var t;return null===(t=nt(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onUnarchived"},{fn:Od(Vi,"entityId","channel"),action:"onUpdate"},{fn:Od(Fl,"entityId","channel"),action:"onUpdate"},{fn:Od((e=>vi((async t=>{var n;if("no-message-preview"===await ju())return;if(wa(t),this.shouldAbort(t.channelId))return;const a=null===(n=nt(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Nl(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Od((e=>fi((async t=>{var n;if("no-message-preview"===await ju())return;if(wa(t),this.shouldAbort(t.channelId))return;const a=null===(n=nt(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Nl(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Od((e=>ql((async t=>{"no-message-preview"!==await ju()&&(await Sa(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Od((e=>xl((async t=>{const n=await ju();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await Sa(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&await gc(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:Od((e=>Ii((async t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(!a)return;a.data.find((e=>{const n=Vn(e);return(null==n?void 0:n.subChannelId)===t.subChannelId}))&&(await gc(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Od((e=>Kl((async t=>{var n;if("no-message-preview"===await ju())return;(null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data)&&(await Oa(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:e=>Ou((async t=>{if(t.feedMarkers){const n=t.feedMarkers.map((e=>{var t;return null===(t=nt(["channel","get",e.entityId]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"OnResolveUnread"},{fn:Od(vu,"channelId","channel"),action:"onUpdate"},{fn:Od((e=>fu((t=>{t.forEach(e)}))),"channelId","channel"),action:"onUpdate"}]}}class Mu extends fr{async getRequest(e,t){const{limit:n=me,includeDeleted:a}=e,s=_n(e,["limit","includeDeleted"]),o=t?{token:t}:{limit:n},i=!1!==a&&void 0,{data:r}=await this.http.get(`/api/v4/channels/${encodeURIComponent(s.channelId)}/users`,{params:Object.assign(Object.assign({},s),{options:o,isDeleted:i})});return r}}class qu extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.channelUsers.map((({channelId:e,userId:t})=>Xe("channelUsers")({channelId:e,userId:t})))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channelUsers.map((({channelId:e,userId:t})=>Xe("channelUsers")({channelId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;if(this.query.channelId!==t.channelId)return;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(!a)return;const s=Xe("channelUsers")({channelId:this.query.channelId,userId:t.userId}),o=this.query.memberships,i=!o||o.includes(t.membership);"none"!==t.membership&&i?a.data.includes(s)||(a.data=[s,...a.data]):a.data=a.data.filter((e=>e!==s)),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class xu extends Or{constructor(e,t){const n=R.default(e),a=["channelUsers","collection",n];super(new Mu(e),n,a,t),this.query=e,this.queryStreamController=new qu(this.query,this.cacheKey,this.notifyChange.bind(this),Da),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:Xa,action:"onJoin"},{fn:ts,action:"onLeft"},{fn:rs,action:"onMemberAdded"},{fn:ls,action:"onMemberRemoved"},{fn:ms,action:"onChannelMemberBanned"},{fn:ys,action:"onChannelMemberUnbanned"},{fn:bs,action:"onChannelMemberRoleAdded"},{fn:ws,action:"onChannelMemberRoleRemoved"},{fn:Rs,action:"onChannelSetUserMuted"},{fn:(e=this.query.channelId,t=>{const n=Ge();return qt(n,"user.deleted","user.deleted",(n=>{var a,s;const o=Ws(n);if(0===o.users.length)return;const i=o.users[0];Nn(o);const r=Xe("channelUsers")({channelId:e,userId:i.userId}),c=null===(a=nt(["channelUsers","get",r]))||void 0===a?void 0:a.data;ot(["channelUsers","get",r],Object.assign(Object.assign({},c),{user:i}));const d=null===(s=nt(["channel","get",e]))||void 0===s?void 0:s.data;d&&t(d,c)}))}),action:"onChannelMemberChanged"}]);var e}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["channelUsers","get",e]))).filter(Boolean).map((({data:e})=>e)).map(cd.channelMember))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=dt(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?wt:It),t}}const Ku=(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getMembers(tmpid: ${o}) > listen`);const i=new xu(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{it(c)})),()=>{a(`getMembers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}};var Nu=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=Ge();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=>xt("channel.membersAdded",Object.assign(Object.assign({},a),{channelUsers:a.channelUsers.filter((t=>t.userId===e))}))));const s=await Da(a);n.cache&&Nn(s);const{channelUsers:o}=s;return!!o.find((t=>t.channelId===e&&"member"===t.membership))},removeMembers:async(e,t)=>{const n=Ge();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=>xt("channel.membersRemoved",Object.assign(Object.assign({},a),{channelUsers:a.channelUsers.filter((t=>t.userId===e))}))));const s=await Da(a);n.cache&&Nn(s);const{channelUsers:o}=s;return!!o.find((t=>t.channelId===e&&"member"!==t.membership))},applyFilter:(e,t)=>{let n=dt(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?wt:It),n},getMembers:Ku,searchMembers:(e,t,n)=>Ku(e,t)});var Fu=Object.freeze({__proto__:null,addRole:async(e,t,n)=>{const a=Ge();a.log("channel/addRole",e,t,n);const{data:s}=await a.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{channelId:e,role:t,userIds:n}),o=await Da(s);a.cache&&Nn(o),xt("local.channel-moderator.role-added",o);const{channelUsers:i}=o;return!!i.find((n=>n.channelId===e&&n.roles.includes(t)))},removeRole:async(e,t,n)=>{const a=Ge();a.log("channel/removeRole",e,t,n);const{data:s}=await a.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{data:{channelId:e,role:t,userIds:n}}),o=await Da(s);a.cache&&Nn(o),xt("local.channel-moderator.role-removed",o);const{channelUsers:i}=o;return!!i.find((n=>n.channelId===e&&!n.roles.includes(t)))},banMembers:async(e,t)=>{const n=Ge();n.log("channel/banMembers",{userIds:t,channelId:e});const{data:a}=await n.http.put(`/api/v3/channels/${e}/users/ban`,{userIds:t}),s=await Da(a),{channelUsers:o}=s,i=n.cache&&Date.now();return n.cache&&Nn(s,{cachedAt:i}),xt("channel.banned",a),{data:null==o?void 0:o.filter((e=>"banned"===e.membership)),cachedAt:i}},unbanMembers:async(e,t)=>{const n=Ge();n.log("channel/unbanMembers",{userIds:t,channelId:e});const{data:a}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}/users/unban`,{userIds:t}),s=await Da(a),o=n.cache&&Date.now();n.cache&&Nn(s,{cachedAt:o}),xt("channel.unbanned",a);const{channelUsers:i}=s;return{data:null==i?void 0:i.filter((e=>"member"===e.membership)),cachedAt:o}},muteMembers:async(e,t,n=-1)=>{var a;const s=Ge();s.log("channel/muteMembers",{userIds:t,channelId:e,mutePeriod:n});const{data:o}=await s.http.put(`/api/v2/channel/${e}/users/mute`,{userIds:t,mutePeriod:-1===n?n:1e3*n}),{success:i}=o,r=-1===n?new Date("9999-12-31T23:59:59.999Z").toISOString():new Date(Date.now()+1e3*n).toISOString();return xt("channel.setMutedUsers",{channelId:e,userIds:t,muteTimeout:r,actor:null!==(a=s.userId)&&void 0!==a?a:""}),i},unmuteMembers:async(e,t)=>{var n;const a=Ge();a.log("channel/unmuteMembers",{userIds:t,channelId:e});const{data:s}=await a.http.put(`/api/v2/channel/${encodeURIComponent(e)}/users/mute`,{userIds:t,mutePeriod:0}),{success:o}=s;return xt("channel.setMutedUsers",{channelId:e,userIds:t,muteTimeout:new Date(0).toISOString(),actor:null!==(n=a.userId)&&void 0!==n?n:""}),o}}),_u=Object.freeze({__proto__:null,Membership:Nu,Moderation:Fu,getChannelByIds:Us,createChannel:mc,updateChannel:async(e,t)=>{const n=Ge();n.log("channel/updateChannel",e,t);const{data:a}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}`,t),s=await Da(a),o=n.cache&&Date.now();n.cache&&Nn(s,{cachedAt:o});const{channels:i}=s;return{data:qa(i.find((t=>t.channelId===e))),cachedAt:o}},deleteChannel:async e=>{const t=Ge();t.log("channel/deleteChannel",e),await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}`);const n=await gc(e);return qa(n.data)},joinChannel:async e=>{const t=Ge();t.log("channel/joinChannel",e);const{data:n}=await t.http.post(`/api/v3/channels/${encodeURIComponent(e)}/join`),a=await Da(n);t.cache&&Nn(a);const{channelUsers:s}=a;return!!s.find((t=>t.channelId===e&&"member"===t.membership))},leaveChannel:async e=>{const t=Ge();t.log("channel/leaveChannel",e);const{data:n}=await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/leave`),a=await Da(n);t.cache&&Nn(a);const{channelUsers:s}=a;return!!s.find((t=>t.channelId===e&&"member"!==t.membership))},muteChannel:async(e,t=-1)=>{const n=Ge();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:s}=a;return s},unmuteChannel:async e=>{const t=Ge();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=Ge();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&&at(["archivedChannel","get",Xe("archivedChannel")(n)],n),xt("local.channel.archived",{archives:[n]})},unarchiveChannel:async e=>{var t;const n=Ge();n.log("channel/unarchiveChannel",e),await n.http.delete(`/api/v1/archives/channels/${encodeURIComponent(e)}`);const a=null===(t=nt(["archivedChannel","get",e]))||void 0===t?void 0:t.data,s=null!=a?a:{channelId:e,archivedAt:(new Date).toISOString()};n.cache&&it(["archivedChannel","get",e],!0),xt("local.channel.unarchived",{archives:[s]})},getArchivedChannelIds:Ml,onChannelCreated:Ba,onChannelUpdated:Qa,onChannelDeleted:Ga,onChannelJoined:Xa,onChannelLeft:ts,onChannelSetMuted:ss,onChannelMemberAdded:rs,onChannelMemberRemoved:ls,onChannelMemberBanned:ms,onChannelMemberUnbanned:ys,onChannelMemberRoleAdded:bs,onChannelMemberRoleRemoved:ws,onChannelArchived:Ss,onChannelUnarchived:Os,getChannel:(e,t)=>{const n=Ge();let a;return jr(e,(async e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:Ds(e.data)}),s=_n(n,["origin"]);return Na(a,s)?void 0:(a=s,t(n))}),"channelId",gc,[Qa,Ga,Xa,ts,rs,ls,ms,ys,ss,Od(Vi,"entityId","channel"),Od(Fl,"entityId","channel"),Od((t=>vi((async a=>{await(async a=>{var s;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await wa(a),a.channelId!==e)return;const o=null===(s=nt(["channel","get",e]))||void 0===s?void 0:s.data;o&&(Nl(o,{messagePreviewId:a.messageId}),t(a))})(a),t(a)}))),"channelId","channel"),Od((t=>fi((async a=>{var s;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await wa(a),a.channelId!==e)return;const o=null===(s=nt(["channel","get",e]))||void 0===s?void 0:s.data;o&&(Nl(o,{messagePreviewId:a.messageId}),t(a))}))),"channelId","channel"),Od((t=>ql((async a=>{var s;const o=null===(s=nt(["channel","get",e]))||void 0===s?void 0:s.data;if(!o||o.messagePreviewId!==a.messageId)return;"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(await Sa(a),t(a))}))),"channelId","channel"),Od((t=>xl((async a=>{var s;const o=null===(s=nt(["channel","get",e]))||void 0===s?void 0:s.data;if(!o||o.messagePreviewId!==a.messageId)return;const i=await n.getMessagePreviewSetting(!1);"no-message-preview"!==i&&("message-preview-not-include-deleted"===i?(it(["messagePreviewChannel","get",e]),await gc(a.channelId)):await Sa(a),t(a))}))),"channelId","channel"),Od((e=>Ii((async t=>{var a,s;const{channelId:o,subChannelId:i}=t,r=null===(a=nt(["messagePreviewChannel","get",o]))||void 0===a?void 0:a.data;if(!r||r.subChannelId!==i)return;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;await gc(o);(null===(s=nt(["channel","get",o]))||void 0===s?void 0:s.data)&&e(t)}))),"channelId","channel"),Od((t=>Kl((async a=>{var s,o;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;Oa(a);const i=null===(s=nt(["messagePreviewChannel","get",e]))||void 0===s?void 0:s.data;if(!i||i.subChannelId!==a.subChannelId)return;(null===(o=nt(["channel","get",e]))||void 0===o?void 0:o.data)&&t(a)}))),"channelId","channel"),Od(bi,"channelId","channel"),Od(vu,"channelId","channel"),Od((e=>fu((t=>{t.forEach(e)}))),"channelId","channel")],{forceDispatch:!0})},getChannels:(e,t,n)=>{const{log:a,cache:s,userId:o}=Ge();s||console.log(ye);const i=Date.now();a(`getChannels(tmpid: ${i}) > listen`);const r=new Tu(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>{it(d)})),()=>{a(`getChannels(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}},getTotalChannelsUnread:e=>{const{_id:t}=Dt();if(!t)throw new Le("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:a}=Ge();a||console.log("For using Live Object feature you need to enable Cache!");n(`liveTotalChannelsUnread(tmpid: ${Date.now()}) > listen`);const s=[];let o,i=!1;const r=t=>{const{data:n}=t,a=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;o=a?Zi(a):a,e({data:a?Object.assign(Object.assign({},a),{isMentioned:a.isMentioned}):a,loading:t.loading,error:t.error})};return s.push(fu((e=>{const{data:t}=Au();Na(o,t)||r({loading:!1,data:t})}))),(()=>{const e=Fe((async()=>Au()));Be(e,(({error:e,data:t,loading:n,origin:a,cachedAt:o})=>{o===fe?(r({data:t,origin:a,loading:!1,error:new Qe(ve,800800,"error")}),i=!0,s.forEach((e=>e()))):i||r({loading:n,data:t,origin:a,error:e}),e&&s.forEach((e=>e()))}))})(),()=>{s.forEach((e=>e()))}},getArchivedChannels:(e,t)=>{const{log:n,cache:a}=Ge();a||console.log(ye);const s=Date.now();n(`getArchivedChannels(tmpid: ${s}) > listen`);const o=new Du(e,t),i=o.startSubscription(),r=o.getCacheKey();return i.push((()=>{it(r)})),()=>{n(`getArchivedChannels(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},searchChannels:(e,t)=>{const{log:n,cache:a}=Ge();a||console.log(ye);const s=Date.now();n(`searchChannels(tmpid: ${s}) > listen`);const o=new Eu(e,t),i=o.startSubscription(),r=o.getCacheKey();return i.push((()=>{it(r)})),()=>{n(`searchChannels(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},MARKER_INCLUDED_CHANNEL_TYPE:Ta,isUnreadCountSupport:Aa,convertFromRaw:Ra,preUpdateChannelCache:Pa,prepareChannelPayload:Da});const Bu=(e,t)=>{0!==e.length&&0!==t.length&&e.forEach((({communityId:e})=>{const n=t.filter((({communityId:t})=>e===t));at(["communityUsers","collection",e],n)}))},$u=async(e,t)=>{const n=Ge();n.log("community/getCommunities",e);const a=e.map((e=>encodeURIComponent(e))),{data:s}=await n.http.get("/api/v3/communities/list",{params:{communityIds:a,includeDiscoverablePrivateCommunity:null==t||t}}),o=Kr(s),i=n.cache&&Date.now();return n.cache&&(Nn(o,{cachedAt:i}),Bu(o.communities,o.communityUsers)),{data:o.communities.map((e=>cd.community(e))),cachedAt:i}};$u.locally=e=>{const t=Ge();if(t.log("community/getCommunities.locally",e),!t.cache)return;const n=e.map((e=>nt(["community","get",e]))).filter(Boolean),a=n.map((({data:e})=>e)),s=n.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1))[0];return n.length<e.length?void 0:{data:a,cachedAt:s.cachedAt}};const Lu=async e=>{const t=Ge();t.log("community/getCommunity",e);const{data:n}=await t.http.get(`/api/v3/communities/${e}`),a=Kr(n),s=t.cache&&Date.now();t.cache&&(Nn(a,{cachedAt:s}),Bu(a.communities,a.communityUsers));const{communities:o}=a;return{data:o.find((t=>t.communityId===e)),cachedAt:s}};Lu.locally=e=>{const t=Ge();if(t.log("community/getCommunity.locally",e),!t.cache)return;const n=nt(["community","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Qu=(e,t)=>{const n=Ge();return qt(n,e,e,(e=>{const a=Kr(e);if(n.cache){Nn(a);const e=nt(["community","get",a.communities[0].communityId]);t(e.data)}else t(a.communities[0])}))},Ju=e=>Qu("community.created",e),Vu=e=>Qu("community.updated",e),Hu=e=>Qu("community.deleted",e);class zu extends fr{async getRequest(e,t){var n;const{limit:a=me}=e,s=_n(e,["limit"]),o=t?{token:t}:{limit:a},{data:i}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},s),{isDeleted:sa(s.includeDeleted),keyword:s.displayName,filter:s.membership,includeDiscoverablePrivateCommunity:null===(n=s.includeDiscoverablePrivateCommunity)||void 0===n||n,options:o})});return i}}class Gu extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.communities.map(Xe("community"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Xe("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=nt(this.cacheKey))||void 0===t?void 0:t.data;n&&(at(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Yu,Wu;!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"}(Wu||(Wu={}));class Xu extends fr{async getRequest(e,t){const{limit:n=me,includeDeleted:a,excludingRoles:s}=e,o=_n(e,["limit","includeDeleted","excludingRoles"]),i=t?{token:t}:{limit:n},r=!1!==a&&void 0,{data:c}=await this.http.get(`/api/v3/communities/${o.communityId}/users`,{params:Object.assign(Object.assign({},o),{options:i,isDeleted:r})});return c}}class Zu extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>Xe("communityUsers")({communityId:e,userId:t})))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>Xe("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;a&&(t.forEach((e=>{var t;const n=Xe("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]}})),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}function eh(e,t,n){return!!e.permissions.some((e=>e===n))||t.communityUsers.find((t=>t.userId===e.userId)).permissions.some((e=>e===n))}function th(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=>!eh(e,t,"BAN_COMMUNITY_USER"))):t.communityUsers.filter((e=>!eh(e,t,"ADD_COMMUNITY_USER")))}const nh=(e,t)=>{const n=Ge();return qt(n,e,e,(a=>{const s=Kr(a),{communities:o,communityUsers:i}=s,r=Mr(o,i);if(s.communities=r,n.cache){Nn(s,void 0,!1);const n=nt(["community","get",s.communities[0].communityId]),a=th(e,s).map((e=>{const t=nt(["communityUsers","get",Xe("communityUsers")(e)]);return null==t?void 0:t.data})).filter(Tr);t(n.data,a)}else t(s.communities[0],th(e,s))}))},ah=(e,t)=>{const n=Ge();return qt(n,e,e,(a=>{const s=Kr(a),{communities:o,communityUsers:i}=s,r=Mr(o,i);if(s.communities=r,n.cache){Nn(s,void 0,!1);const n=nt(["community","get",s.communities[0].communityId]),a=th(e,s).map((e=>{const t=nt(["communityUsers","get",Xe("communityUsers")(e)]);return null==t?void 0:t.data})).filter(Tr);t(n.data,a)}else t(s.communities[0],th(e,s))}))},sh=e=>nh("community.userBanned",e),oh=e=>nh("community.userChanged",e),ih=e=>nh("community.userUnbanned",e),rh=e=>nh("community.roleAdded",e),ch=e=>nh("community.roleRemoved",e),dh=e=>ah("local.community.userAdded",e),lh=e=>ah("local.community.userRemoved",e),uh=e=>nh("community.joined",e),hh=e=>nh("community.left",e),mh=e=>ah("local.community.joined",e),gh=e=>ah("local.community.left",e),ph=e=>{const t=Ge(),n=[qt(t,"onCommunityUpdate","v4.local.community.joined",(async t=>{e(t[0])}))];return()=>{n.forEach((e=>e()))}},yh=e=>{const t=Ge();return qt(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=Ge();return qt(t,"onLocalCommunityRoleAdded","local.community.roleAdded",(async t=>{const{communities:n,communityUsers:a}=t;e(n[0],a.filter((e=>"member"===e.communityMembership)))}))},fh=e=>t=>{const n=Ge();return qt(n,"user.deleted","user.deleted",(n=>{var a,s;const o=Ws(n);if(0===o.users.length)return;const i=o.users[0];Nn(o);const r=Xe("communityUsers")({communityId:e,userId:i.userId}),c=null===(a=nt(["communityUsers","get",r]))||void 0===a?void 0:a.data;at(["communityUsers","get",r],Object.assign(Object.assign({},c),{user:i}));const d=null===(s=nt(["community","get",e]))||void 0===s?void 0:s.data;t(d,[Object.assign(Object.assign({},c),{user:i})])}))};class bh extends Or{constructor(e,t){const n=R.default(e),a=["communityUsers","collection",n];super(new Xu(e),n,a,t),this.query=e,this.queryStreamController=new Zu(this.query,this.cacheKey,this.notifyChange.bind(this),Kr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:uh,action:Wu.OnCommunityJoined},{fn:mh,action:Wu.OnCommunityJoined},{fn:hh,action:Wu.OnCommunityLeft},{fn:gh,action:Wu.OnCommunityLeft},{fn:sh,action:Wu.OnCommunityUserBanned},{fn:oh,action:Wu.OnCommunityUserChanged},{fn:rh,action:Wu.OnCommunityUserRoleAdded},{fn:ch,action:Wu.OnCommunityUserRoleRemoved},{fn:vh,action:Wu.OnCommunityUserRoleAdded},{fn:yh,action:Wu.OnCommunityUserRoleRemoved},{fn:ih,action:Wu.OnCommunityUserUnbanned},{fn:dh,action:Wu.OnCommunityUserAdded},{fn:lh,action:Wu.onCommunityUserRemoved},{fn:fh(this.query.communityId),action:Wu.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["communityUsers","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=dt(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(It);else n=n.sort(wt);return n}}class Ih extends fr{async getRequest(e,t){const{limit:n=me,includeDeleted:a,excludingRoles:s}=e,o=_n(e,["limit","includeDeleted","excludingRoles"]),i=t?{token:t}:{limit:n},r=!1!==a&&void 0,{data:c}=await this.http.get(`/api/v3/communities/${o.communityId}/users`,{params:Object.assign(Object.assign({},o),{options:i,isDeleted:r})});return c}}class Ch extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>Xe("communityUsers")({communityId:e,userId:t})))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>Xe("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;a&&(t.forEach((e=>{const t=Xe("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership&&(a.data=a.data.filter((e=>e!==t)))})),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var wh;!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"}(wh||(wh={}));class Sh extends Or{constructor(e,t){const n=R.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),Kr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:uh,action:wh.OnCommunityJoined},{fn:mh,action:wh.OnCommunityJoined},{fn:hh,action:wh.OnCommunityLeft},{fn:gh,action:wh.OnCommunityLeft},{fn:sh,action:wh.OnCommunityUserBanned},{fn:oh,action:wh.OnCommunityUserChanged},{fn:yh,action:wh.OnCommunityUserRoleRemoved},{fn:ch,action:wh.OnCommunityUserRoleRemoved},{fn:ih,action:wh.OnCommunityUserUnbanned},{fn:fh(this.query.communityId),action:wh.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["communityUsers","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=dt(e,"roles",this.query.roles);return this.query.memberships&&(n=n.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),this.query.search&&(n=gt(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 Oh=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=Ge();n.log("community/moderation/addMembers",e,t);const{data:a}=await n.http.post(`/api/v3/communities/${e}/users`,{communityId:e,userIds:t});xt("local.community.userAdded",a);const s=$n(a,"communityUsers");n.cache&&Nn(s);const{communityUsers:o}=s;return!!o.find((t=>t.communityId===e&&"member"===t.communityMembership))},removeMembers:async(e,t)=>{const n=Ge();n.log("community/moderation/removeMembers",e,t);const{data:a}=await n.http.delete(`/api/v3/communities/${e}/users`,{data:{communityId:e,userIds:t}});xt("local.community.userRemoved",a);const s=$n(a,"communityUsers");n.cache&&Nn(s);const{communityUsers:o}=s;return!!o.find((t=>t.communityId===e&&"member"!==t.communityMembership))},applyFilter:(e,t)=>{var n;let a=dt(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 s=t.sortBy?t.sortBy:"lastCreated";return a=a.sort("lastCreated"===s?wt:It),a},getMembers:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getMembers(tmpid: ${o}) > listen`);const i=new bh(e,(e=>{t(e)})),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{it(c)})),()=>{a(`getMembers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},searchMembers:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getMembers(tmpid: ${o}) > listen`);const i=new Sh(e,(e=>{t(e)})),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{it(c)})),()=>{a(`getMembers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},onCommunityUserAdded:e=>nh("community.userAdded",e),onCommunityUserRemoved:e=>nh("community.userRemoved",e),onCommunityUserBanned:sh,onCommunityUserChanged:oh,onCommunityUserUnbanned:ih,onCommunityUserRoleAdded:rh,onCommunityUserRoleRemoved:ch,onLocalCommunityUserAdded:dh,onLocalCommunityUserRemoved:lh,onCommunityJoined:uh,onCommunityLeft:hh,onLocalCommunityJoined:mh,onLocalCommunityLeft:gh,onLocalCommunityJoin:ph});class Th extends Or{constructor(e,t){const n=R.default(e),a=["community","collection",n];super(new zu(e),n,a,t),this.query=e,this.queryStreamController=new Gu(this.query,this.cacheKey,this.notifyChange.bind(this),Kr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:Hu,action:Yu.OnCommunityDeleted},{fn:Vu,action:Yu.OnCommunityUpdated},{fn:uh,action:Wu.OnCommunityJoined},{fn:hh,action:Wu.OnCommunityLeft},{fn:oh,action:Wu.OnMemberCountChanged},{fn:mh,action:Wu.OnCommunityJoined},{fn:gh,action:Wu.OnCommunityLeft},{fn:Od(ph,"targetId","community"),action:Yu.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["community","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Ge();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=ht(n,this.query.membership,t)),n}}class Ah extends fr{async getRequest(e,t){var n;const{limit:a=me}=e,s=_n(e,["limit"]),o=t?{token:t}:{limit:a},{data:i}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},s),{isDeleted:sa(s.includeDeleted),filter:s.membership,includeDiscoverablePrivateCommunity:null===(n=s.includeDiscoverablePrivateCommunity)||void 0===n||n,options:o})});return i}}class Rh extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&(Nn(t,{cachedAt:a}),Bu(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.communities.map(Xe("community"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Xe("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=nt(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],at(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Ph;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Ph||(Ph={}));class Dh extends Or{constructor(e,t){const n=R.default(e),a=["community","collection",n];super(new Ah(e),n,a,t),this.query=e,this.queryStreamController=new Rh(this.query,this.cacheKey,this.notifyChange.bind(this),Kr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:Ph.OnCommunityCreated},{fn:Hu,action:Ph.OnCommunityDeleted},{fn:Vu,action:Ph.OnCommunityUpdated},{fn:uh,action:Wu.OnCommunityJoined},{fn:hh,action:Wu.OnCommunityLeft},{fn:oh,action:Wu.OnMemberCountChanged},{fn:mh,action:Wu.OnCommunityJoined},{fn:gh,action:Wu.OnCommunityLeft},{fn:Od(ph,"targetId","community"),action:Ph.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>nt(["community","get",e]))).filter(Tr).map((({data:e})=>lc(e))))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Ge();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=ht(n,this.query.membership,t));const a=(()=>"firstCreated"===this.query.sortBy?It:wt)();return n=n.sort(a),n}}class Uh extends fr{async getRequest(e,t){const{limit:n=me,includeDiscoverablePrivateCommunity:a}=e,s=_n(e,["limit","includeDiscoverablePrivateCommunity"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/communities/top-trending",{params:Object.assign(Object.assign({},s),{options:o,includeDiscoverablePrivateCommunity:null==a||a})});return i}}class kh extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&(Nn(t,{cachedAt:a}),Bu(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.communities.map(Xe("community"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Xe("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=nt(this.cacheKey))||void 0===t?void 0:t.data;n&&(at(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 Eh extends Or{constructor(e,t){const n=R.default(e),a=["trendingCommunity","collection",n];super(new Uh(e),n,a,t),this.query=e,this.queryStreamController=new kh(this.query,this.cacheKey,this.notifyChange.bind(this),Kr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:Hu,action:jh.OnCommunityDeleted},{fn:Vu,action:jh.OnCommunityUpdated},{fn:uh,action:Wu.OnCommunityJoined},{fn:hh,action:Wu.OnCommunityLeft},{fn:oh,action:Wu.OnMemberCountChanged},{fn:mh,action:Wu.OnCommunityJoined},{fn:gh,action:Wu.OnCommunityLeft},{fn:Od(ph,"targetId","community"),action:jh.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>nt(["community","get",e]))).filter(Tr).map((({data:e})=>lc(e))))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class Mh extends fr{async getRequest(e,t){const{limit:n=me,includeDiscoverablePrivateCommunity:a}=e,s=_n(e,["limit","includeDiscoverablePrivateCommunity"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/communities/recommended",{params:Object.assign(Object.assign({},s),{options:o,includeDiscoverablePrivateCommunity:null==a||a})});return i}}class qh extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&(Nn(t,{cachedAt:a}),Bu(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.communities.map(Xe("community"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Xe("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=nt(this.cacheKey))||void 0===t?void 0:t.data;n&&(at(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var xh;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated",e.OnLocalCommunityJoin="onLocalCommunityJoin"}(xh||(xh={}));class Kh extends Or{constructor(e,t){const n=R.default(e),a=["community","collection",n];super(new Mh(e),n,a,t),this.query=e,this.queryStreamController=new qh(this.query,this.cacheKey,this.notifyChange.bind(this),Kr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:Hu,action:xh.OnCommunityDeleted},{fn:Vu,action:xh.OnCommunityUpdated},{fn:uh,action:Wu.OnCommunityJoined},{fn:hh,action:Wu.OnCommunityLeft},{fn:oh,action:Wu.OnMemberCountChanged},{fn:mh,action:Wu.OnCommunityJoined},{fn:gh,action:Wu.OnCommunityLeft},{fn:Od(ph,"targetId","community"),action:xh.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>nt(["community","get",e]))).filter(Tr).map((({data:e})=>lc(e))))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class Nh extends fr{async getRequest(e,t){var n;const{limit:a=me,communityMembershipStatus:s}=e,o=_n(e,["limit","communityMembershipStatus"]),i={type:e.limit?"pagination":void 0},r=t?Object.assign(Object.assign({},i),{token:t}):Object.assign(Object.assign({},i),{limit:a}),{data:c}=await this.http.get("/api/v1/semantic-search/communities",{params:Object.assign(Object.assign({},o),{filter:null!=s?s:"all",options:r,includeDiscoverablePrivateCommunity:null===(n=o.includeDiscoverablePrivateCommunity)||void 0===n||n})});return c}}function Fh(e){return e.communities.map((t=>{const n=e.searchResult.find((e=>e.communityId===t.communityId));return`${t.communityId}:${n}`}))}class _h extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:Fh(e)});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...Fh(e)])]}))}}reactor(e){return e=>{var t;const n=null===(t=nt(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],at(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Bh;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Bh||(Bh={}));class $h extends Or{constructor(e,t){const n=R.default(e),a=["community","collection",n];super(new Nh(e),n,a,t),this.query=e,this.queryStreamController=new _h(this.query,this.cacheKey,this.notifyChange.bind(this),Br),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:Bh.OnCommunityCreated},{fn:Hu,action:Bh.OnCommunityDeleted},{fn:Vu,action:Bh.OnCommunityUpdated},{fn:uh,action:Wu.OnCommunityJoined},{fn:hh,action:Wu.OnCommunityLeft},{fn:oh,action:Wu.OnMemberCountChanged},{fn:mh,action:Wu.OnCommunityJoined},{fn:gh,action:Wu.OnCommunityLeft},{fn:Od(ph,"targetId","community"),action:Bh.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>{const[t,n]=e.split(":");return{communityId:t,score:parseFloat(n)}})).sort(((e,t)=>t.score-e.score)).map((({communityId:e})=>nt(["community","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Ge();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=ht(n,this.query.communityMembershipStatus,t)),n}}class Lh extends fr{async getRequest(e,t){const{limit:n=me,communityIds:a}=e,s=_n(e,["limit","communityIds"]),o=t?{token:t}:{limit:n},i=a.map((e=>encodeURIComponent(e))),{data:r}=await this.http.get("/api/v4/communities/join/requests",{params:Object.assign(Object.assign({},s),{options:o,communityIds:i})});return r}}var Qh;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(Qh||(Qh={}));class Jh extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.joinRequests.map((e=>Xe("joinRequest")({joinRequestId:e._id})))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>Xe("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(!a)return;const s=(Array.isArray(t)?t:[t]).map((e=>e.joinRequestId));if(e===Qh.OnLocalJoinRequestUpdated){if(!a.data.find((e=>s.includes(e))))return}e===Qh.OnLocalJoinRequestCreated&&(a.data=[...new Set([...s,...a.data])]),e===Qh.OnLocalJoinRequestDeleted&&(a.data=a.data.filter((e=>!s.includes(e)))),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Vh extends Or{constructor(e,t){const n=R.default(e),a=["joinRequestList","collection",n];super(new Lh(e),n,a,t),this.query=e,this.queryStreamController=new Jh(this.query,this.cacheKey,this.notifyChange.bind(this),Nr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:Vr,action:Qh.OnLocalJoinRequestCreated},{fn:Hr,action:Qh.OnLocalJoinRequestUpdated},{fn:zr,action:Qh.OnLocalJoinRequestUpdated},{fn:ph,action:Qh.OnLocalJoinRequestUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a;const s=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(s.data.map((e=>nt(["joinRequest","get",e]))).filter(Tr).map((({data:e})=>e)).map($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.communityIds&&this.query.communityIds.length>0&&(t=t.filter((e=>this.query.communityIds.some((t=>t===e.targetId)))));const n=(()=>"firstCreated"===this.query.sortBy?It:wt)();return t=t.sort(n),t}}var Hh;!function(e){e.ALL="all",e.MEMBER="member",e.NOT_MEMBER="notMember"}(Hh||(Hh={}));var zh=Object.freeze({__proto__:null,addRoles:async(e,t,n)=>{const a=Ge();a.log("community/moderation/addRoles",e,t,n);const{data:s}=await a.http.post(`/api/v4/communities/${e}/users/roles`,{communityId:e,roles:t,userIds:n}),o=Fr(s);a.cache&&Nn(o),xt("local.community.roleAdded",o);const{communityUsers:i}=o;return!!i.find((n=>n.communityId===e&&t.some((e=>n.roles.includes(e)))))},removeRoles:async(e,t,n)=>{const a=Ge();a.log("community/moderation/removeRoles",e,t,n);const{data:s}=await a.http.delete(`/api/v4/communities/${e}/users/roles`,{data:{communityId:e,roles:t,userIds:n}}),o=Fr(s);a.cache&&Nn(o),xt("local.community.roleRemoved",o);const{communityUsers:i}=o;return!!i.find((n=>n.communityId===e&&!t.some((e=>n.roles.includes(e)))))},banMembers:async(e,t)=>{const n=Ge();n.log("community/banMembers",{userIds:t,communityId:e});const{data:a}=await n.http.put(`/api/v3/communities/${e}/users/ban`,{userIds:t}),s=$n(a,"communityUsers"),o=n.cache&&Date.now();n.cache&&Nn(s,{cachedAt:o});const{communityUsers:i}=s;return{data:i.filter((e=>t.includes(e.userId))),cachedAt:o}},unbanMembers:async(e,t)=>{const n=Ge();n.log("community/unbanMembers",{userIds:t,communityId:e});const{data:a}=await n.http.put(`/api/v3/communities/${e}/users/unban`,{userIds:t}),s=$n(a,"communityUsers"),o=n.cache&&Date.now();n.cache&&Nn(s,{cachedAt:o});const{communityUsers:i}=s;return{data:i.filter((e=>t.includes(e.userId))),cachedAt:o}}}),Gh=Object.freeze({__proto__:null,Moderation:zh,Membership:Oh,getCommunityByIds:$u,createCommunity:async e=>{const t=Ge();t.log("user/createCommunity",e);const{data:n}=await t.http.post("/api/v3/communities/",_r(e));xt("community.created",n);const a=Kr(n),s=t.cache&&Date.now();t.cache&&(Nn(a,{cachedAt:s}),Bu(a.communities,a.communityUsers));const{communities:o}=a;return{data:cd.community(o[0]),cachedAt:s}},updateCommunity:async(e,t)=>{const n=Ge();n.log("community/updateCommunity",e,t);const{data:a}=await n.http.put(`/api/v3/communities/${e}`,_r(t));xt("community.updated",a);const s=Kr(a),o=n.cache&&Date.now();n.cache&&(Nn(s,{cachedAt:o}),Bu(s.communities,s.communityUsers));const{communities:i}=s;return{data:cd.community(i.find((t=>t.communityId===e))),cachedAt:o}},deleteCommunity:async e=>{const t=Ge();t.log("community/deleteCommunity",e),await t.http.delete(`/api/v3/communities/${e}`);const n=await Lu(e);return xt("community.deleted",{communities:[n.data],categories:[],communityUsers:[],feeds:[],files:[],users:[]}),cd.community(n.data)},joinCommunity:async e=>{const t=Ge();t.log("community/joinCommunity",e);const{data:n}=await t.http.post(`/api/v3/communities/${e}/join`);xt("local.community.joined",n);const a=Kr(n),s=t.cache&&Date.now();t.cache&&Nn(a,{cachedAt:s});const{communityUsers:o}=a;return!!o.find((t=>t.communityId===e&&"member"===t.communityMembership))},leaveCommunity:async e=>{const t=Ge();t.log("community/leaveCommunity",e);const{data:n}=await t.http.delete(`/api/v3/communities/${e}/leave`);xt("local.community.left",n);const a=Kr(n),s=t.cache&&Date.now();t.cache&&Nn(a,{cachedAt:s});const{communityUsers:o}=a;return!!o.find((t=>t.communityId===e&&"member"!==t.communityMembership))},onCommunityCreated:Ju,onCommunityUpdated:Vu,onCommunityDeleted:Hu,searchCommunities:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`searchCommunities(tmpid: ${o}) > listen`);const i=new Th(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`searchCommunities(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getCommunities:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getCommunities(tmpid: ${o}) > listen`);const i=new Dh(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getCommunities(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getCommunity:(e,t)=>jr(e,t,"communityId",Lu,[Vu,Hu,uh,hh,mh,gh,sh,ih,oh,Od(ph,"targetId","community")],{callbackDataSelector:e=>e?cd.community(e):e}),getTrendingCommunities:(e,t,n)=>{const{log:a,cache:s,userId:o}=Ge();s||console.log(ye);const i=Date.now();a(`getTrendingCommunities(tmpid: ${i}) > listen`);const r=new Eh(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>it(d))),()=>{a(`getTrendingCommunities(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}},getRecommendedCommunities:(e,t,n)=>{const{log:a,cache:s,userId:o}=Ge();s||console.log(ye);const i=Date.now();a(`getRecommendedCommunities(tmpid: ${i}) > listen`);const r=new Kh(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>it(d))),()=>{a(`getRecommendedCommunities(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}},semanticSearchCommunities:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`semanticSearchCommunities(tmpid: ${o}) > listen`);const i=new $h(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`semanticSearchCommunities(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getJoinRequestList:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getJoinRequestList: (tmpid: ${o}) > listen`);const i=new Vh(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{it(c)})),()=>{a(`getJoinRequestList (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},get AmityCommunityMemberStatusFilter(){return Hh}});const Yh=async e=>{const t=Ge();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&&Nn(n,{cachedAt:a});const{categories:s}=n;return{data:cd.category((null!=s?s:[]).find((t=>t.categoryId===e))),cachedAt:a}};Yh.locally=e=>{const t=Ge();if(t.log("category/getCategory.locally",e),!t.cache)return;const n=nt(["category","get",e]);return n?{data:cd.category(n.data),cachedAt:n.cachedAt}:void 0};const Wh=async e=>{const t=Ge();t.log("category/queryCategories",e);const n=null!=e?e:{},{page:a,limit:s,includeDeleted:o}=n,i=_n(n,["page","limit","includeDeleted"]),r=a?{token:a}:s?{limit:s}:void 0,{data:c}=await t.http.get("/api/v3/community-categories",{params:Object.assign(Object.assign({},i),{isDeleted:sa(o),options:r})}),{paging:d}=c,l=_n(c,["paging"]),{categories:u}=l,h=t.cache&&Date.now();if(t.cache){Nn(l,{cachedAt:h});const e=["category","query",Object.assign(Object.assign({},i),{includeDeleted:o,options:r})];at(e,{categories:null==u?void 0:u.map(Xe("category")),paging:d})}return{data:null!=u?u:[],cachedAt:h,paging:d}};Wh.locally=e=>{var t,n;const a=Ge();if(a.log("category/queryCategories.locally",e),!a.cache)return;const s=null!=e?e:{},{page:o,limit:i=10}=s,r=_n(s,["page","limit"]),c=o?{token:o}:i?{limit:i}:void 0,d=["category","query",Object.assign(Object.assign({},r),{options:c})],{data:l,cachedAt:u}=null!==(t=nt(d))&&void 0!==t?t:{};if(!(null==l?void 0:l.categories.length))return;const h=l.categories.map((e=>nt(["category","get",e]))).filter(Boolean).map((({data:e})=>e)),{paging:m}=l;return h.length===(null===(n=null==l?void 0:l.categories)||void 0===n?void 0:n.length)?{data:h,cachedAt:u,paging:m}:void 0};var Xh=Object.freeze({__proto__:null,getCategory:Yh,getCategories:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getCategories(tmpid: ${o}) > listen`);const{limit:i}=e,r=_n(e,["limit"]),c=null!=i?i:me,{policy:d=pe}=null!=n?n:{},l=[],u=["category","collection",{}],h=(n=!1)=>{var a,s;const o=null===(a=nt(u))||void 0===a?void 0:a.data,i=null!==(s=null==o?void 0:o.data)&&void 0!==s?s:[];if(!n&&i.length>0&&!(null==o?void 0:o.params.page))return;const l=Fe(Wh,Object.assign(Object.assign({},r),{limit:n?c:void 0,page:n||null==o?void 0:o.params.page}));Be(l,(({data:n,error:a,loading:s,paging:o})=>{const r={loading:s,error:a,params:{page:null==o?void 0:o.next},data:i};n&&(r.data=[...new Set([...i,...n.map(Xe("category"))])]),at(u,r),(n=>{var a,s;let o=null!==(a=n.data.map((e=>nt(["category","get",e]))).filter(Boolean).map((({data:e})=>cd.category(e))))&&void 0!==a?a:[];switch(e.includeDeleted||(o=rt(o,"isDeleted",!1)),e.sortBy){case"firstCreated":o=o.sort(It);break;case"lastCreated":o=o.sort(wt);break;default:o=o.sort(bt)}t({onNextPage:h,data:o,hasNextPage:!!(null===(s=n.params)||void 0===s?void 0:s.page),loading:n.loading,error:n.error})})(r)}),_e(d))};return l.push((()=>{})),h(!0),()=>{a(`getCategories(tmpid: ${o}) > dispose`),l.forEach((e=>e()))}}});const Zh=async e=>{const t=Ge();t.log("feed/queryGlobalFeed",e);const n=null!=e?e:{},{queryToken:a,dataTypes:s}=n,o=_n(n,["queryToken","dataTypes"]),i=(()=>{if(a)return{token:a}})(),{data:r}=await t.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},o),{dataTypes:s,resolveParent:!!(s&&s.length>0)||void 0,options:i})}),{paging:c}=r,d=_n(r,["paging"]),l=$n(d,"communityUsers"),{posts:u}=l,{communities:h}=Kr(l),m=t.cache&&Date.now();if(t.cache){Nn(Object.assign(Object.assign({},l),{communitis:h}));const e=["globalFeed","query",Object.assign(Object.assign({},o),{options:i})];at(e,{posts:u.map(Xe("post")),paging:c})}return{data:u.map(cd.post),cachedAt:m,paging:c}};Zh.locally=e=>{var t;const n=Ge();if(n.log("post/queryGlobalFeed.locally",e),!n.cache)return;const a=_n(null!=e?e:{},[]),s=["globalFeed","query",Object.assign({},a)],{data:o,cachedAt:i}=null!==(t=nt(s))&&void 0!==t?t:{};if(!(null==o?void 0:o.posts.length))return;const r=o.posts.map((e=>nt(["post","get",e]))).filter(Boolean).map((({data:e})=>e)).map(cd.post),{paging:c}=o;return r.length===o.posts.length?{data:r,cachedAt:i,paging:c}:void 0};class em extends fr{async getRequest(e,t){const{limit:n}=e,a=_n(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v5/me/global-feeds",{params:Object.assign(Object.assign({},a),{options:s})});return o}}var tm;!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"}(tm||(tm={}));class nm extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.posts.map(Xe("post"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Xe("post"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(a&&(!t.parentPostId||a.data.includes(t.parentPostId))){if(e===tm.OnPostDeleted&&(a.data=a.data.filter((e=>e!==t.postId))),e===tm.OnPostCreated||e===tm.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===tm.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const am=async e=>{const t=Ge();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=>{Re(null==t?void 0:t.code)&&Fn("comment",e)})),t}const s=t.cache&&Date.now();return t.cache&&Nn(a,{cachedAt:s}),{data:a.comments.map((e=>cd.comment(e))),cachedAt:s}};am.locally=e=>{var t;const n=Ge();if(n.log("comment/getCommentByIds.locally",e),!n.cache)return;const a=e.map((e=>nt(["comment","get",e]))).filter(Boolean),s=a.map((({data:e})=>e)),o=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:s.map((e=>cd.comment(e))),cachedAt:o.cachedAt}};const sm=e=>{const t=Ge();if(!t.cache)return;const n=Un();t.log("comment/createComment.optimistically",Object.assign({commentId:n},e));const a=(new Date).toISOString(),s={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 at(["comment","get",s.commentId],s,{cachedAt:-5}),xt("local.comment.created",{comments:[s],commentChildren:[],users:[],files:[],communityUsers:[]}),s},om=(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})},im=async e=>{const t=Ge();t.log("story/getStoryByStoryId",e);const n=nt(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;Zn("story",e)}let a;try{const n=await t.http.get(`/api/v4/stories/${e}`);a=om(n.data)}catch(t){throw Re(null==t?void 0:t.code)&&Fn("story",e),t}const s=t.cache&&Date.now();return t.cache&&Nn(a,{cachedAt:s}),{data:a.stories[0],cachedAt:s}};im.locally=e=>{const t=Ge();t.log("story/getStorybyStoryId",e);const n=nt(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;Zn("story",e)}const a=t.cache&&Date.now(),s=nt(["story","get",e]);if(s)return{data:s.data,cachedAt:a}};const rm=async(e,t=!1)=>{var n,a,s;const o=Ge(),i=null===(n=nt(["comment","get",e]))||void 0===n?void 0:n.data;if("error"===(null==i?void 0:i.syncState)){const t=Object.assign(Object.assign({},i),{isDeleted:!0});return it(["comment","get",e]),xt("local.comment.deleted",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]}),t}const r=await Xd(e);await o.http.delete(`/api/v4/comments/${encodeURIComponent(e)}`,{params:{commentId:e,permanent:t}});const c=Object.assign(Object.assign({},r.data),{isDeleted:!0});if(t?Et((()=>Fn("comment",e))):ot(["comment","get",e],{isDeleted:!0}),"story"===r.data.referenceType){const e=await im(r.data.referenceId);xt("local.story.updated",{stories:[e.data],categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[]})}else{const t=null===(a=nt(["post","get",r.data.referenceId]))||void 0===a?void 0:a.data;if(t){const n=zd();n.queueCommentChangeTask(new Qd(t.postId,e)),!c.parentId&&(null===(s=c.children)||void 0===s?void 0:s.length)>0&&c.children.forEach((e=>{n.queueCommentChangeTask(new Qd(t.postId,e))}))}}return xt("local.comment.deleted",{comments:[c],commentChildren:[],files:[],users:[],communityUsers:[]}),c},cm=async e=>{const t=Ge();let n;t.log("comment/getComment",e),Zn("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw Re(null==t?void 0:t.code)&&Fn("comment",e),t}const a=t.cache&&Date.now();t.cache&&Nn(n,{cachedAt:a});const{comments:s}=n;return{data:s.find((t=>t.commentId===e)),cachedAt:a}};cm.locally=e=>{const t=Ge();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=nt(["comment","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const dm=e=>bl("local.comment.deleted",e),lm=e=>{const t=Ge();return qt(t,"local.comment.addReaction","local.comment.addReaction",(({comment:n})=>{t.cache?(ot(["comment","get",n.commentId],n),e(vc(n))):e(n)}))},um=e=>{const t=Ge();return qt(t,"local.comment.removeReaction","local.comment.removeReaction",(({comment:n})=>{t.cache?(ot(["comment","get",n.commentId],n),e(vc(n))):e(n)}))};class hm extends fr{async getRequest(e,t){var n;const{pageSize:a,limit:s,includeDeleted:o}=e,i=_n(e,["pageSize","limit","includeDeleted"]),r=null!==(n=null!=a?a:s)&&void 0!==n?n:me,c={type:i.sortBy||e.limit||e.pageSize?"pagination":void 0},d=t?Object.assign(Object.assign({},c),{token:t}):Object.assign(Object.assign({},c),{pageSize:r,limit:r}),{data:l}=await this.http.get("/api/v3/comments",{params:Object.assign(Object.assign({},i),{isDeleted:sa(o),options:d})});return l}}var mm;!function(e){e.OnCommentCreated="onCommentCreated",e.OnCommentUpdated="onCommentUpdated",e.OnCommentDeleted="onCommentDeleted",e.OnCommentFlagged="onCommentFlagged",e.OnCommentUnflagged="onCommentUnflagged",e.OnCommentReactionAdded="onCommentReactionAdded",e.OnCommentReactionRemoved="onCommentReactionRemoved"}(mm||(mm={}));class gm extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.comments.map(Xe("comment"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.comments.map(Xe("comment"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(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===mm.OnCommentCreated&&(a.data=[...new Set([t.commentId,...a.data])]),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const pm=e=>bl("local.comment.created",e);class ym extends Or{constructor(e,t){const n=R.default(e),a=["comments","collection",n];super(new hm(e),n,a,t),this.query=e,this.queryStreamController=new gm(this.query,this.cacheKey,this.notifyChange.bind(this),El),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:pm,action:mm.OnCommentCreated},{fn:dm,action:mm.OnCommentDeleted},{fn:Il,action:mm.OnCommentCreated},{fn:Cl,action:mm.OnCommentUpdated},{fn:wl,action:mm.OnCommentDeleted},{fn:Sl,action:mm.OnCommentFlagged},{fn:Ol,action:mm.OnCommentUnflagged},{fn:Tl,action:mm.OnCommentReactionAdded},{fn:Al,action:mm.OnCommentReactionRemoved},{fn:lm,action:mm.OnCommentReactionAdded},{fn:um,action:mm.OnCommentReactionRemoved}]);if(this.query.excludeBlockUserComments){const t=()=>this.notifyChange({origin:"event",loading:!1});e.push(Ho(t),zo(t))}return e}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["comment","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(cd.comment);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,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())||[],s=(null===(n=e.dataTypes)||void 0===n?void 0:n.sort())||[];return s.length===a.length&&a.every(((e,t)=>e===s[t]))}))),"any"===this.query.dataTypes.matchType&&(t=t.filter((e=>{var t;return null===(t=this.query.dataTypes)||void 0===t?void 0:t.values.some((t=>{var n;return null===(n=e.dataTypes)||void 0===n?void 0:n.includes(t)}))})))),this.query.excludeBlockUserComments&&(t=vt(t)),"firstCreated"===this.query.sortBy)t=t.sort(It);else t=t.sort(wt);return t}}var vm=Object.freeze({__proto__:null,getCommentByIds:am,createComment:async e=>{const t=Ge();t.log("comment/createComment",e);const n=sm(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:s}=n;if(0===s.length)throw new Error("Comment not created");const o=t.cache&&Date.now();if(t.cache&&Nn(n,{cachedAt:o}),["post","content"].includes(e.referenceType))zd().queueCommentChangeTask(new Ld(e.referenceId,s[0].commentId,n.comments[0].createdAt));else if("story"===e.referenceType){const t=nt(["story-reference",e.referenceId]);if(null==t?void 0:t.data){const e=nt(["story","get",t.data]);(null==e?void 0:e.data)&&xt("story.updated",{stories:[Object.assign(Object.assign({},e.data),{commentsCount:e.data.commentsCount+1,comments:[...new Set([...e.data.comments,s[0].commentId])]})],categories:[],comments:s,communities:[],communityUsers:n.communityUsers,files:n.files,users:n.users})}}return xt("local.comment.created",{comments:[Object.assign(Object.assign({},s[0]),{syncState:"synced"})],commentChildren:n.commentChildren,users:n.users,files:n.files,communityUsers:n.communityUsers}),{data:cd.comment(s[0]),cachedAt:o}}catch(e){throw n&&xt("local.comment.created",{comments:[Object.assign(Object.assign({},n),{syncState:"error"})],commentChildren:[],users:[],files:[],communityUsers:[]}),e}},updateComment:async(e,t)=>{const n=Ge();n.log("user/updateComment",t);const{data:a}=await n.http.put(`/api/v3/comments/${encodeURIComponent(e)}`,t),s=n.cache&&Date.now();n.cache&&Nn(a,{cachedAt:s}),xt("comment.updated",a);const{comments:o}=a;return{data:cd.comment(o.find((t=>t.commentId===e))),cachedAt:s}},deleteComment:rm,softDeleteComment:async e=>{Ge().log("comment/softDeleteComment",e);return rm(e)},hardDeleteComment:async e=>{Ge().log("comment/hardDeleteComment",e);return rm(e,!0)},flagComment:async(t,n)=>{const a=Ge();a.log("comment/flagComment",t);const s=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,a])=>t!==e.ContentFlagReasonEnum.Others&&a===n)),o={reason:n&&s?n:e.ContentFlagReasonEnum.Others,detail:n&&!s?n:""},{data:i}=await a.http.post(`/api/v3/comments/${encodeURIComponent(t)}/flag`,o);return a.cache&&Nn(i),xt("comment.flagged",i),!!i},unflagComment:async e=>{const t=Ge();t.log("comment/unflagComment",e);const{data:n}=await t.http.delete(`/api/v3/comments/${encodeURIComponent(e)}/unflag`);return t.cache&&Nn(n),xt("comment.unflagged",n),!!n},isCommentFlaggedByMe:async e=>{const t=Ge();t.log("comment/isCommentFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/comments/${e}/isflagbyme`);return n},onCommentCreated:Il,onCommentUpdated:Cl,onCommentDeleted:wl,onCommentFlagged:Sl,onCommentUnflagged:Ol,onCommentReactionAdded:Tl,onCommentReactionRemoved:Al,getComment:(e,t)=>jr(e,t,"commentId",cm,[dm,wl,Sl,Tl,Al,Ol,Cl,lm,um]),getComments:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log("For using Live Collection feature you need to enable Cache!");const o=Date.now();a(`getComments(tmpid: ${o}) > listen`);const i=new ym(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getComments(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});const fm=e=>cl("local.post.deleted",e),bm=e=>{const t=Ge();return qt(t,"local.post.addReaction","local.post.addReaction",(({post:n})=>{t.cache?(ot(["post","get",n.postId],n),e(n)):e(n)}))},Im=e=>{const t=Ge();return qt(t,"local.post.removeReaction","local.post.removeReaction",(({post:n})=>{t.cache?(ot(["post","get",n.postId],n),e(n)):e(n)}))},Cm=e=>cl("local.post.updated",e),wm=e=>[Il,wl,pm,dm].map((t=>({fn:Od((n=>((e,t,n)=>t((async t=>{var a;const s=null===(a=nt(n))||void 0===a?void 0:a.data;s&&s.data.includes(t.referenceId)&&e(t)})))(n,t,e)),"referenceId","post"),action:tm.OnPostUpdated}))),Sm=e=>[{fn:dl,action:tm.OnPostCreated},{fn:ll,action:tm.OnPostUpdated},{fn:Cm,action:tm.OnPostUpdated},{fn:ul,action:tm.OnPostDeleted},{fn:gl,action:tm.OnPostFlagged},{fn:pl,action:tm.OnPostUnflagged},{fn:hl,action:tm.OnPostApproved},{fn:ml,action:tm.OnPostDeclined},{fn:yl,action:tm.OnPostReactionAdded},{fn:vl,action:tm.OnPostReactionRemoved},{fn:bm,action:tm.OnPostReactionAdded},{fn:Im,action:tm.OnPostReactionRemoved},{fn:fm,action:tm.OnPostDeleted},...wm(e)];class Om extends Or{constructor(e,t){const n=R.default(e),a=["customRankingGlobalFeed","collection",n];super(new em(e),n,a,t),this.query=e,this.queryStreamController=new nm(this.query,this.cacheKey,this.notifyChange.bind(this),Gd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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(Sm(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>nt(["post","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(cd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class Tm extends fr{async getRequest(e,t){const{limit:n,dataTypes:a}=e,s=_n(e,["limit","dataTypes"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},s),{dataTypes:a,resolveParent:!!(a&&a.length>0)||void 0,options:o})});return i}}class Am extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.posts.map(Xe("post"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Xe("post"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(a&&(!t.parentPostId||a.data.includes(t.parentPostId))){if(e===tm.OnPostDeleted&&(a.data=a.data.filter((e=>e!==t.postId))),e===tm.OnPostCreated||e===tm.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===tm.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Rm extends Or{constructor(e,t){const n=R.default(e),a=["globalFeed","collection",n];super(new Tm(e),n,a,t),this.query=e,this.queryStreamController=new Am(this.query,this.cacheKey,this.notifyChange.bind(this),Gd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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(Sm(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>nt(["post","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(cd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class Pm extends fr{async getRequest(e,t){const{userId:n,feedSources:a,dataTypes:s,includeDeleted:o,matchingOnlyParentPost:i,limit:r=me,untilAt:c}=e,d=_n(e,["userId","feedSources","dataTypes","includeDeleted","matchingOnlyParentPost","limit","untilAt"]),l=t?{token:t}:{limit:r},{data:u}=await this.http.get(`/api/v4/user-feeds/${n}`,{params:Object.assign(Object.assign({},d),{options:l,dataTypes:(null==s?void 0:s.length)?s:void 0,includePostedFeed:a,isDeleted:sa(o),matchingOnlyParentPost:null!=i?i:!(null==s?void 0:s.length)})});return u}}class Dm extends Ir{constructor(e,t,n,a){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=a,this.validatedUntilAt=e.untilAt?At(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;let o=e.posts;if(n&&(this.boundaryReached=!1),void 0!==this.validatedUntilAt){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated",t=o.filter((t=>!Rt(t.createdAt,this.validatedUntilAt,e)));t.length<o.length&&(this.boundaryReached=!0),o=t}if(n)at(this.cacheKey,{data:o.map(Xe("post"))});else{const e=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,t=null!==(s=null==e?void 0:e.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...o.map(Xe("post"))])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(s&&(this.query.dataTypes&&0!==this.query.dataTypes.length||s.data.includes(t.parentPostId?t.parentPostId:t.postId))){if(void 0!==this.validatedUntilAt&&(e===tm.OnPostCreated||e===tm.OnPostApproved||e===tm.OnPostUpdated)){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";if(Rt(t.createdAt,this.validatedUntilAt,e))return}if(e===tm.OnPostDeleted&&(s.data=s.data.filter((e=>e!==t.postId))),t.parentPostId&&t.isDeleted){const e=null===(a=nt(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),at(["post","get",e.postId],e)}if(e===tm.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e===tm.OnPostCreated||e===tm.OnPostApproved){if(this.query.dataTypes&&this.query.dataTypes.length>0&&!this.query.dataTypes.includes(t.dataType))return;s.data=[...new Set([t.postId,...s.data])]}at(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}hasBoundaryReached(){return this.boundaryReached}}const Um=async e=>{const t=Ge();let n;t.log("post/getPost",e),Zn("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw Re(null==t?void 0:t.code)&&Fn("post",e),t}const a=$n(n,"communityUsers"),s=t.cache&&Date.now();t.cache&&Nn(a,{cachedAt:s});const{posts:o}=a;return{data:o.find((t=>t.postId===e)),cachedAt:s}};Um.locally=e=>{const t=Ge();if(t.log("post/getPost.locally",e),!t.cache)return;const n=nt(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class km extends Or{constructor(e,t){const n=R.default(e),a=["userFeed","collection",n];super(new Pm(e),n,a,t),this.query=e,this.queryStreamController=new Dm(this.query,this.cacheKey,this.notifyChange.bind(this),Gd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:dl,action:tm.OnPostCreated},{fn:ll,action:tm.OnPostUpdated},{fn:Cm,action:tm.OnPostUpdated},{fn:ul,action:tm.OnPostDeleted},{fn:gl,action:tm.OnPostFlagged},{fn:pl,action:tm.OnPostUnflagged},{fn:hl,action:tm.OnPostApproved},{fn:ml,action:tm.OnPostDeclined},{fn:yl,action:tm.OnPostReactionAdded},{fn:vl,action:tm.OnPostReactionRemoved},{fn:bm,action:tm.OnPostReactionAdded},{fn:Im,action:tm.OnPostReactionRemoved},{fn:fm,action:tm.OnPostDeleted},{fn:Od((e=>Il((async t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await Um(t.referenceId),e(t))}))),"referenceId","post"),action:tm.OnPostUpdated},{fn:Od((e=>wl((async t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await Um(t.referenceId),e(t))}))),"referenceId","post"),action:tm.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>nt(["post","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[],r=this.applyFilter(i).map(cd.post);if(!this.shouldNotify(r)&&"event"===e)return;const c=!this.queryStreamController.hasBoundaryReached()&&!!this.paginationController.getNextToken();this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:r,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=mt(n,this.query.dataTypes)),this.query.untilAt){const e=At(this.query.untilAt),t="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";n=n.filter((n=>!Rt(n.createdAt,e,t)))}if("firstCreated"===this.query.sortBy)n=n.sort(It);else n=n.sort(wt);return n}}class jm extends fr{async getRequest(e,t){const{limit:n=me,includeDeleted:a,communityId:s,untilAt:o}=e,i=_n(e,["limit","includeDeleted","communityId","untilAt"]),r=t?{token:t}:{limit:n},{data:c}=await this.http.get("/api/v5/posts",{params:Object.assign(Object.assign({},i),{targetId:s,targetType:"community",isDeleted:sa(a),matchingOnlyParentPost:!0,options:r})});return c}}class Em extends Ir{constructor(e,t,n,a){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=a,this.validatedUntilAt=e.untilAt?At(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;let o=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=o.filter((t=>!Rt(t.createdAt,this.validatedUntilAt,e)));t.length<o.length&&(this.boundaryReached=!0),o=t}if(n)at(this.cacheKey,{data:o.map(Xe("post"))});else{const e=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,t=null!==(s=null==e?void 0:e.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...o.map(Xe("post"))])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(void 0!==this.validatedUntilAt&&(e===tm.OnPostCreated||e===tm.OnPostApproved)&&"firstUpdated"!==this.query.sortBy&&"lastUpdated"!==this.query.sortBy){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";if(Rt(t.createdAt,this.validatedUntilAt,e))return}if(e===tm.OnPostDeleted&&(s.data=s.data.filter((e=>e!==t.postId))),t.parentPostId&&t.isDeleted){const e=null===(a=nt(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),at(["post","get",e.postId],e)}e===tm.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==tm.OnPostCreated&&e!==tm.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),at(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}hasBoundaryReached(){return this.boundaryReached}}const Mm=({cacheKey:e,resolveId:t})=>[Il,wl,pm,dm].map((n=>({fn:Od((a=>((e,t,n,a)=>t((async t=>{var s;const o=null===(s=nt(n))||void 0===s?void 0:s.data;o&&o.data.includes(a?a(t.referenceId):t.referenceId)&&e(t)})))(a,n,e,t)),"referenceId","post"),action:tm.OnPostUpdated}))),qm=e=>[{fn:dl,action:tm.OnPostCreated},{fn:ll,action:tm.OnPostUpdated},{fn:Cm,action:tm.OnPostUpdated},{fn:ul,action:tm.OnPostDeleted},{fn:gl,action:tm.OnPostFlagged},{fn:pl,action:tm.OnPostUnflagged},{fn:hl,action:tm.OnPostApproved},{fn:ml,action:tm.OnPostDeclined},{fn:yl,action:tm.OnPostReactionAdded},{fn:vl,action:tm.OnPostReactionRemoved},{fn:bm,action:tm.OnPostReactionAdded},{fn:Im,action:tm.OnPostReactionRemoved},{fn:fm,action:tm.OnPostDeleted},...Mm({cacheKey:e})],xm=(e,t)=>{var n;return null!==(n=e.map((e=>{const n=t.find((t=>t.postId===e.referenceId));return n?Xe("post")({postId:null==n?void 0:n.postId}):void 0})).filter(Tr))&&void 0!==n?n:[]};class Km extends Or{constructor(e,t){const n=R.default(e),a=["communityFeed","collection",n];super(new jm(e),n,a,t),this.query=e,this.queryStreamController=new Em(this.query,this.cacheKey,this.notifyChange.bind(this),Gd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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(qm(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["post","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(cd.post);if(!this.shouldNotify(i)&&"event"===e)return;const r=!this.queryStreamController.hasBoundaryReached()&&!!this.paginationController.getNextToken();this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:r,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=At(this.query.untilAt),n="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";t=t.filter((t=>!Rt(t.createdAt,e,n)))}switch(this.query.sortBy){case"firstCreated":t=t.sort(It);break;case"firstUpdated":t=t.sort(St);break;case"lastUpdated":t=t.sort(Ot);break;default:t=t.sort(wt)}return t}}class Nm extends Qe{constructor(e="For You feed is not enabled for this network"){super(e,400400,"error"),this.type="AmityForYouFeedDisabledError"}}class Fm extends fr{constructor(e){super(e),this.checkedDisk=!1,this.hasDeliveredPost=!1,this.cursor=Go.current()}async getRequest(e,t){var n,a,s,o,i;const r=void 0===t;let c=null;if(r&&!this.checkedDisk&&this.cursor&&(this.checkedDisk=!0,c=await this.cursor.get(),c&&Go.isExpired(c.expiredAt)&&(await this.cursor.clear(),c=null)),r&&(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 d=r&&c?c.cursor:t,l=await this.fetch(d);if(l.posts.length>0&&(this.hasDeliveredPost=!0),null===(s=l.paging)||void 0===s?void 0:s.next)await this.persistCursor(l);else if(this.hasDeliveredPost&&this.cursor){const e=Date.parse(null!==(i=null===(o=l.paging)||void 0===o?void 0:o.expiredAt)&&void 0!==i?i:"");Number.isNaN(e)||await this.cursor.markReachedEndOfFeed(e)}return l}async fetch(e){const t={limit:ge};e&&(t.token=e);try{const{data:e}=await this.http.get(Ce,{params:{options:t}});return e}catch(t){if(t instanceof Qe&&400300===t.code)throw new Nm;if(t instanceof Qe&&400322===t.code&&void 0!==e){this.cursor&&await this.cursor.clear();const{data:e}=await this.http.get(Ce,{params:{options:{limit:ge}}});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,s=null===(n=e.paging)||void 0===n?void 0:n.expiredAt;if(!a||!s)return;const o=Date.parse(s);Number.isNaN(o)||await this.cursor.set({cursor:a,expiredAt:o})}}class _m extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.posts.map(Xe("post"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Xe("post"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;a&&(t.parentPostId&&!a.data.includes(t.parentPostId)||(e!==tm.OnPostDeleted&&e!==tm.OnPostDeclined||(a.data=a.data.filter((e=>e!==t.postId))),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Bm=["forYouFeed","collection"];class $m extends Or{constructor(e){const t=`for-you-feed-${Ge().userId}`,n={};super(new Fm(n),t,Bm,e),this.queryStreamController=new _m(n,this.cacheKey,this.notifyChange.bind(this),Gd),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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(Sm(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>nt(["post","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(cd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var Lm=Object.freeze({__proto__:null,queryGlobalFeed:Zh,getCustomRankingGlobalFeed:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getCustomRankingGlobalFeed(tmpid: ${o}) > listen`);const i=new Om(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getCustomRankingGlobalFeed(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getGlobalFeed:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getGlobalFeed(tmpid: ${o}) > listen`);const i=new Rm(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getGlobalFeed(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getUserFeed:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getUserFeed(tmpid: ${o}) > listen`);const i=new km(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getUserFeed(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getCommunityFeed:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getCommunityFeed(tmpid: ${o}) > listen`);const i=new Km(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getCommunityFeed(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getForYouFeed:e=>{const{log:t,cache:n}=Ge();n||console.log(ye);const a=Date.now();t(`getForYouFeed(tmpid: ${a}) > listen`);const s=new $m(e),o=s.startSubscription(),i=s.getCacheKey();return o.push((()=>it(i))),()=>{t(`getForYouFeed(tmpid: ${a}) > dispose`),o.forEach((e=>e()))}},AmityForYouFeedDisabledError:Nm});const Qm=async e=>{const t=Ge();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=>{Re(null==t?void 0:t.code)&&Fn("post",e)})),t}const s=$n(a,"communityUsers"),o=t.cache&&Date.now();return t.cache&&Nn(s,{cachedAt:o}),{data:s.posts.map(cd.post),cachedAt:o}};Qm.locally=e=>{var t;const n=Ge();if(n.log("post/getPostByIds.locally",e),!n.cache)return;const a=e.map((e=>nt(["post","get",e]))).filter(Boolean),s=a.map((({data:e})=>e)),o=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:s.map(cd.post),cachedAt:o.cachedAt}};const Jm=async(e,t=!1)=>{var n;const a=Ge(),s=await Wd(e);if(await a.http.delete(`/api/v4/posts/${encodeURIComponent(e)}`,{params:{postId:e,permanent:t}}),"community"===s.data.targetType){const e=await Lu(s.data.targetId),t=(null!==(n=tt(["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));xt("community.updated",{communities:[e.data],categories:[],communityUsers:t,feeds:[],files:[],users:[]})}const o=Object.assign(Object.assign({},s.data),{isDeleted:!0});return t?setTimeout((()=>{Fn("post",e)}),0):ot(["post","get",e],{isDeleted:!0}),xt("local.post.deleted",{posts:[o],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[],videoStreamings:[]}),cd.post(o)};class Vm extends fr{async getRequest(e,t){const{limit:n=me,includeDeleted:a,matchingOnlyParentPost:s,untilAt:o}=e,i=_n(e,["limit","includeDeleted","matchingOnlyParentPost","untilAt"]),{dataTypes:r}=i,c={type:i.sortBy||e.limit?"pagination":void 0},d=t?Object.assign(Object.assign({},c),{token:t}):Object.assign(Object.assign({},c),{limit:n}),{data:l}=await this.http.get("/api/v5/posts",{params:Object.assign(Object.assign({},i),{isDeleted:sa(a),matchingOnlyParentPost:null!=s?s:!(null==r?void 0:r.length),options:d})});return l}}class Hm extends Ir{constructor(e,t,n,a){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=a,this.validatedUntilAt=e.untilAt?At(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;let o=e.posts;if(n&&(this.boundaryReached=!1),void 0!==this.validatedUntilAt){const e=this.query.sortBy||"lastCreated",t=o.filter((t=>!Rt(t.createdAt,this.validatedUntilAt,e)));t.length<o.length&&(this.boundaryReached=!0),o=t}if(n)at(this.cacheKey,{data:o.map(Xe("post"))});else{const e=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,t=null!==(s=null==e?void 0:e.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...o.map(Xe("post"))])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(void 0!==this.validatedUntilAt&&(e===tm.OnPostCreated||e===tm.OnPostApproved)){const e=this.query.sortBy||"lastCreated";if(Rt(t.createdAt,this.validatedUntilAt,e))return}if(t.parentPostId&&t.isDeleted){const e=null===(a=nt(["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)),at(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===tm.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==tm.OnPostCreated&&e!==tm.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),at(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}hasBoundaryReached(){return this.boundaryReached}}class zm extends Or{constructor(e,t){const n=R.default(e),a=["posts","collection",n];super(new Vm(e),n,a,t),this.query=e,this.queryStreamController=new Hm(this.query,this.cacheKey,this.notifyChange.bind(this),Gd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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(qm(this.cacheKey));if(this.query.excludeBlockUserPosts){const t=()=>this.notifyChange({origin:"event",loading:!1});e.push(Ho(t),zo(t))}return e}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["post","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(cd.post);if(!this.shouldNotify(i)&&"event"===e)return;const r=!this.queryStreamController.hasBoundaryReached()&&!!this.paginationController.getNextToken();this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:r,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=ut(n,this.query.feedType)),(null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=mt(n,this.query.dataTypes)),this.query.untilAt){const e=At(this.query.untilAt),t=this.query.sortBy||"lastCreated";n=n.filter((n=>!Rt(n.createdAt,e,t)))}if(this.query.excludeBlockUserPosts&&(n=yt(n)),"firstCreated"===this.query.sortBy)n=n.sort(It);else n=n.sort(wt);return n}}class Gm extends fr{async getRequest(e,t){const n=_n(e,["limit"]),{communityId:a,placement:s}=n,o=_n(n,["communityId","placement"]),i=s?`/api/v1/pinned-posts/communities/${a}/${s}`:`/api/v1/pinned-posts/communities/${a}`,{data:r}=await this.http.get(i,{params:Object.assign({},o)});return r}}class Ym extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=Ge(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users?e.users.map(ga):[]});Nn(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.pins.map(Xe("pin"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(Xe("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===tm.OnPostDeleted&&(a.data=a.data.filter((e=>e!==`global#${t.postId}`))),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Wm extends Or{constructor(e,t){const n=R.default(e),a=["pinnedPosts","collection",n];super(new Gm(e),n,a,t),this.query=e,this.queryStreamController=new Ym(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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(Mm({cacheKey:this.cacheKey,resolveId:e=>`${this.query.placement}#${e}`}))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;let i=(null!==(s=o.data.map((e=>nt(["pin","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(cd.pinnedPost);i=this.applyFilter(i),(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,loading:t,error:n})}applyFilter(e){let t=e;if("lastCreated"===this.query.sortBy)t=t.sort((({post:e},{post:t})=>wt({createdAt:null==e?void 0:e.createdAt},{createdAt:null==t?void 0:t.createdAt})));return t}}class Xm extends fr{async getRequest(e,t){const n=_n(e,["limit"]),{data:a}=await this.http.get("/api/v1/pinned-posts/global",{params:Object.assign({},n)});return a}}class Zm extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=Ge(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users.map(ga)});Nn(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.pins.map(Xe("pin"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(Xe("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===tm.OnPostDeleted&&(a.data=a.data.filter((e=>e!==`global#${t.postId}`))),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class eg extends Or{constructor(e,t){const n=R.default(e),a=["pinnedPosts","collection",n];super(new Xm(e),n,a,t),this.query=e,this.queryStreamController=new Zm(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:fm,action:tm.OnPostDeleted},{fn:ul,action:tm.OnPostDeleted},...Mm({cacheKey:this.cacheKey,resolveId:e=>`global#${e}`})])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>nt(["pin","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(cd.pinnedPost);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,loading:t,error:n})}}class tg extends fr{async getRequest(e,t){const{limit:n=me}=e,a=_n(e,["limit"]),s={type:e.limit?"pagination":void 0},o=t?Object.assign(Object.assign({},s),{token:t}):Object.assign(Object.assign({},s),{limit:n}),{data:i}=await this.http.get("/api/v1/semantic-search/posts",{params:Object.assign(Object.assign({},a),{options:o})});return i}}function ng(e){return e.posts.map((t=>{const n=e.searchResult.find((e=>e.postId===t.postId));return`${t.postId}:${n.score}`}))}function ag(e){return(null!=e?e:[]).map((e=>e.split(":")[0]))}class sg extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:ng(e)});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...ng(e)])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(t.parentPostId&&t.isDeleted){const e=null===(a=nt(["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)),at(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===tm.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==tm.OnPostCreated&&e!==tm.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),at(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class og extends Or{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=R.default(n),s=["posts","collection",a];super(new tg(n),a,s,t),this.query=n,this.queryStreamController=new sg(this.query,this.cacheKey,this.notifyChange.bind(this),Yd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:ll,action:tm.OnPostUpdated},{fn:ul,action:tm.OnPostDeleted},{fn:gl,action:tm.OnPostFlagged},{fn:pl,action:tm.OnPostUnflagged},{fn:hl,action:tm.OnPostApproved},{fn:ml,action:tm.OnPostDeclined},{fn:yl,action:tm.OnPostReactionAdded},{fn:vl,action:tm.OnPostReactionRemoved},{fn:Od((e=>Il((async t=>{const n=nt(this.cacheKey);ag(null==n?void 0:n.data).includes(t.referenceId)||(await Wd(t.referenceId),e(t))}))),"referenceId","post"),action:tm.OnPostUpdated},{fn:Od((e=>wl((async t=>{const n=nt(this.cacheKey);ag(null==n?void 0:n.data).includes(t.referenceId)||(await Wd(t.referenceId),e(t))}))),"referenceId","post"),action:tm.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>{const[t,n]=e.split(":");return{postId:t,score:parseFloat(n)}})).sort(((e,t)=>t.score-e.score)).map((({postId:e})=>nt(["post","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(cd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,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=mt(t,this.query.dataTypes)),t}}class ig extends fr{async getRequest(e,t){const{limit:n=me,matchingOnlyParentPost:a,hashtags:s,dataTypes:o,targetType:i="all"}=e,r=_n(e,["limit","matchingOnlyParentPost","hashtags","dataTypes","targetType"]),c={type:r.sortBy||e.limit?"pagination":void 0},d=t?Object.assign(Object.assign({},c),{token:t}):Object.assign(Object.assign({},c),{limit:n}),{data:l}=await this.http.get("/api/v1/search/posts",{params:Object.assign(Object.assign({},r),{hashtags:s,dataTypes:o,targetType:i,matchingOnlyParentPost:null!=a?a:!(null==o?void 0:o.length),options:d})});return l}}class rg extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.posts.map(Xe("post"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Xe("post"))])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(t.parentPostId&&t.isDeleted){const e=null===(a=nt(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),at(["post","get",e.postId],e)}e===tm.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==tm.OnPostCreated&&e!==tm.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),at(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class cg extends Or{constructor(e,t){const n=R.default(e),a=["posts","collection",n];super(new ig(e),n,a,t),this.query=e,this.queryStreamController=new rg(this.query,this.cacheKey,this.notifyChange.bind(this),Gd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:dl,action:tm.OnPostCreated},{fn:ll,action:tm.OnPostUpdated},{fn:Cm,action:tm.OnPostUpdated},{fn:ul,action:tm.OnPostDeleted},{fn:gl,action:tm.OnPostFlagged},{fn:pl,action:tm.OnPostUnflagged},{fn:hl,action:tm.OnPostApproved},{fn:ml,action:tm.OnPostDeclined},{fn:yl,action:tm.OnPostReactionAdded},{fn:vl,action:tm.OnPostReactionRemoved},{fn:bm,action:tm.OnPostReactionAdded},{fn:Im,action:tm.OnPostReactionRemoved},{fn:fm,action:tm.OnPostDeleted},{fn:Od((e=>Il((async t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await Um(t.referenceId),e(t))}))),"referenceId","post"),action:tm.OnPostUpdated},{fn:Od((e=>wl((async t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await Um(t.referenceId),e(t))}))),"referenceId","post"),action:tm.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["post","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(cd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,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=mt(n,this.query.dataTypes)),"firstCreated"===this.query.sortBy)n=n.sort(It);else n=n.sort(wt);return n}}class dg extends Sr{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 lg extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:xm(e.rooms,e.posts)});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...xm(e.rooms,e.posts)])]}))}}reactor(e){return e=>{var t;const n=null===(t=nt(this.cacheKey))||void 0===t?void 0:t.data;n&&("ended"===e.status&&at(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 ug=e=>{const t=Ge();return qt(t,"room/onRoomStartBroadcasting","room.startBroadcasting",(t=>{Nn(t),e(t.rooms[0])}))},hg=e=>{const t=Ge();return qt(t,"room/onRoomWaitingReconnect","room.waitingReconnect",(t=>{Nn(t),e(t.rooms[0])}))},mg=e=>{const t=Ge();return qt(t,"room/onRoomEndBroadcasting","room.endBroadcasting",(t=>{Nn(t),e(t.rooms[0])}))},gg=e=>{const t=Ge();return qt(t,"room/onRoomRecordedAvailable","room.recordedAvailable",(t=>{Nn(t),e(t.rooms[0])}))},pg=e=>{const t=Ge();return qt(t,"room/onRoomCoHostInvited","room.didCohostInvite",(t=>{const n=Zr(t);Nn(n),e(n.invitations)}))},yg=async e=>{const t=Ge();let n;t.log("room/getRoomById",e),Zn("room",e);try{n=(await t.http.get(`/api/v1/rooms/${e}`)).data}catch(t){throw Re(null==t?void 0:t.code)&&Fn("room",e),t}const a=t.cache&&Date.now();return t.cache&&Nn(n,{cachedAt:a}),{data:n.rooms[0],cachedAt:a}};yg.locally=e=>{const t=Ge();t.log("room/getRoomById.locally",e),Zn("room",e);const n=t.cache&&Date.now(),a=nt(["room","get",e]);if(a)return{data:a.data,cachedAt:n}};const vg=e=>{const t=Ge();return qt(t,"room/onRoomCoHostInviteAccepted","room.didCohostInviteAccept",(async t=>{var n;const a=Zr(t);await yg(null===(n=a.invitations)||void 0===n?void 0:n[0].targetId),Nn(a),e(a.invitations[0])}))},fg=e=>{const t=Ge();return qt(t,"room/onRoomCoHostInviteRejected","room.didCohostInviteReject",(t=>{const n=Zr(t);Nn(n),e(n.invitations)}))},bg=e=>{const t=Ge();return qt(t,"room/onRoomCoHostInviteCanceled","room.didCohostInviteCancel",(t=>{const n=Zr(t);Nn(n),e(n.invitations)}))},Ig=e=>{const t=Ge();return qt(t,"room/onRoomParticipantJoined","room.participantJoined",(t=>{const{rooms:n,users:a}=t;Nn({rooms:n,users:a}),e({room:jc(n[0]),actorInternalId:t.eventActor.userInternalId})}))},Cg=e=>{const t=Ge();return qt(t,"room/onRoomParticipantLeft","room.participantLeft",(t=>{var n;const{rooms:a,users:s}=t;Nn({rooms:a,users:s});const o=t.eventActor.userInternalId;e({room:jc(a[0]),actorInternalId:o,actorUserId:null===(n=null==s?void 0:s.find((e=>e.userInternalId===o)))||void 0===n?void 0:n.userId})}))},wg=e=>{const t=Ge();return qt(t,"room/onRoomParticipantStageJoined","room.participantStageJoined",(t=>{const{rooms:n,users:a}=t;Nn({rooms:n,users:a}),e({room:jc(n[0]),actorInternalId:t.eventActor.userInternalId})}))},Sg=e=>{const t=Ge();return qt(t,"room/onRoomTerminated","room.terminated",(t=>{Nn(t),e(t.rooms[0])}))},Og=e=>{const t=Ge();return qt(t,"room/onRoomDidUpdate","local.room.didUpdate",(t=>{Nn(t),e(t.rooms[0])}))},Tg=e=>{const t=Ge();return qt(t,"room/onRoomParticipantRemoved","room.participantRemoved",(t=>{var n;const{rooms:a,users:s}=t;Nn({rooms:a,users:s});const o=t.eventActor.userInternalId;e({room:jc(a[0]),actorInternalId:o,actorUserId:null===(n=null==s?void 0:s.find((e=>e.userInternalId===o)))||void 0===n?void 0:n.userId})}))},Ag=e=>{const t=Ge();return qt(t,"room/onLocalRoomDidUpdate","room.didUpdate",(t=>{Nn(t),e(t.rooms[0])}))},Rg=e=>{const t=Ge();return qt(t,"room/onRoomParticipantRemoved","local.room.participantRemoved",(t=>{Nn(t),e(t.rooms[0])}))};var Pg;!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"}(Pg||(Pg={}));const Dg=e=>t=>e((e=>{t(e.room)}));class Ug extends fr{async getRequest(e,t){const{limit:n=me,includeDeleted:a}=e,s=_n(e,["limit","includeDeleted"]),o={type:s.sortBy||e.limit?"pagination":void 0},i=t?Object.assign(Object.assign({},o),{token:t}):Object.assign(Object.assign({},o),{limit:n}),{data:r}=await this.http.get("/api/v1/rooms",{params:Object.assign(Object.assign({},s),{isDeleted:sa(a),options:i})});return r}}class kg extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.rooms.map(Xe("room"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.rooms.map(Xe("room"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===Pg.OnRoomDeleted&&(a.data=a.data.filter((e=>e!==t._id))),e===Pg.OnRoomCreated&&(a.data=[...new Set([t._id,...a.data])]),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class jg extends Or{constructor(e,t){const n=R.default(e),a=["rooms","collection",n];super(new Ug(e),n,a,t),this.query=e,this.queryStreamController=new kg(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:ug,action:Pg.OnRoomStartBroadcasting},{fn:mg,action:Pg.OnRoomEndBroadcasting},{fn:gg,action:Pg.OnRoomUpdated},{fn:hg,action:Pg.OnRoomUpdated},{fn:Sg,action:Pg.OnRoomUpdated},{fn:Dg(Ig),action:Pg.OnRoomUpdated},{fn:Dg(Cg),action:Pg.OnRoomUpdated},{fn:Dg(Tg),action:Pg.OnRoomUpdated},{fn:Rg,action:Pg.OnRoomUpdated},{fn:Dg(wg),action:Pg.OnRoomUpdated},{fn:Od(vg,"targetId","room"),action:Pg.OnRoomUpdated},{fn:Og,action:Pg.OnRoomDidUpdate},{fn:Ag,action:Pg.OnRoomDidUpdate}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["room","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(jc);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,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(It);else t=t.sort(wt);return t}}var Eg=Object.freeze({__proto__:null,createRoom:async e=>{const t=Ge();t.log("room/createRoom",e);const{data:n}=await t.http.post("/api/v1/rooms",e);xt("local.room.created",n);const a=t.cache&&Date.now();t.cache&&Nn(n,{cachedAt:a});const{rooms:s}=n;return{data:jc(s[0]),cachedAt:a}},updateRoom:async(e,t)=>{const n=Ge();n.log("room/updateRoom",{roomId:e,bundle:t});const{data:a}=await n.http.put(`/api/v1/rooms/${e}`,t);xt("local.room.updated",a);const s=n.cache&&Date.now();n.cache&&Nn(a,{cachedAt:s});const{rooms:o}=a;return{data:jc(o[0]),cachedAt:s}},deleteRoom:async e=>{const t=Ge();t.log("room/deleteRoom",{roomId:e}),await t.http.delete(`/api/v1/rooms/${e}`),xt("local.room.deleted",{rooms:[{_id:e}]})},stopRoom:async e=>{const t=Ge();t.log("room/stopRoom",{roomId:e});const{data:n}=await t.http.post(`/api/v1/rooms/${e}/stop`);xt("local.room.stopped",n);const a=t.cache&&Date.now();t.cache&&Nn(n,{cachedAt:a});const{rooms:s}=n;return{data:s[0],cachedAt:a}},getBroadcasterData:async e=>{const t=Ge();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=Ge();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=Ge();n.log("room/removeParticipant",{roomId:e,participantUserId:t}),await n.http.delete(`/api/v1/rooms/${e}/participants/${t}`),xt("local.room.participantRemoved",{rooms:[{_id:e}],users:[{_id:t}]})},leaveRoom:async e=>{const t=Ge();t.log("room/leaveRoom",{roomId:e}),await t.http.post(`/api/v1/rooms/${e}/leave`),xt("local.room.left",{rooms:[{_id:e}]})},AmityRoomAnalytics:kc,WatchSessionStorage:Ic,getWatchSessionStorage:wc,syncWatchSessions:Dc,updateCohostPermission:async(e,t,n)=>{const a=Ge();a.log("room/updatedCoHostPermission",{roomId:e,cohostId:t,canManageProductTags:n});const{data:s}=await a.http.put(`/api/v1/rooms/${e}/participants/${t}`,{canManageProductTags:n});xt("local.room.didUpdate",s);const o=a.cache&&Date.now();a.cache&&Nn(s,{cachedAt:o});const{rooms:i}=s;return{data:jc(i[0]),cachedAt:o}},onRoomStartBroadcasting:ug,onRoomWaitingReconnect:hg,onRoomEndBroadcasting:mg,onRoomRecordedAvailable:gg,onRoomCoHostInvited:pg,onRoomCoHostInviteAccepted:vg,onRoomCoHostInviteRejected:fg,onRoomCoHostInviteCanceled:bg,onRoomParticipantJoined:Ig,onRoomParticipantLeft:Cg,onRoomParticipantStageLeft:e=>{const t=Ge();return qt(t,"room/onRoomParticipantStageLeft","room.participantStageLeft",(t=>{const{rooms:n,users:a}=t;Nn({rooms:n,users:a}),e({room:jc(n[0]),actorInternalId:t.eventActor.userInternalId})}))},onRoomParticipantStageJoined:wg,onRoomTerminated:Sg,onRoomDidUpdate:Og,onRoomCreated:e=>{const t=Ge();return qt(t,"room/onRoomCreated","local.room.created",(t=>{Nn(t),e(t.rooms[0])}))},onRoomUpdated:e=>{const t=Ge();return qt(t,"room/onRoomUpdated","local.room.updated",(t=>{Nn(t),e(t.rooms[0])}))},onRoomDeleted:e=>{const t=Ge();return qt(t,"room/onRoomDeleted","local.room.deleted",(t=>{Nn(t),e(t.rooms[0])}))},onRoomStopped:e=>{const t=Ge();return qt(t,"room/onRoomStopped","local.room.stopped",(t=>{Nn(t),e(t.rooms[0])}))},onRoomParticipantRemoved:Tg,onRoomLeft:e=>{const t=Ge();return qt(t,"room/onRoomLeft","local.room.left",(t=>{Nn(t),e(t.rooms[0])}))},onLocalRoomDidUpdate:Ag,getRoom:(e,t)=>jr(e,t,"_id",yg,[mg,ug,hg,Sg,gg,Dg(Ig),Dg(Cg),Dg(Tg),Rg,Dg(wg),Od(vg,"targetId","room"),Og,Ag],{callbackDataSelector:e=>e?cd.room(e):e}),getRooms:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getRooms(tmpid: ${o}) > listen`);const i=new jg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getRooms(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});class Mg extends Or{constructor(e){const t={limit:100},n=R.default(t),a=["liveRoomPosts","collection",n];super(new dg(t),n,a,e),this.query=t,this.queryStreamController=new lg(this.query,this.cacheKey,this.notifyChange.bind(this),Gd),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:mg,action:tm.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["post","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(cd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,loading:t,error:n})}applyFilter(e){return e}}class qg extends Sr{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 xg extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:xm(e.rooms,e.posts)});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...xm(e.rooms,e.posts)])]}))}}reactor(e){return e=>{var t;const n=null===(t=nt(this.cacheKey))||void 0===t?void 0:t.data;n&&("ended"===e.status&&at(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 Kg extends Or{constructor(e,t){const n=R.default(e),a=["communityLiveRoomPosts","collection",n];super(new qg(e),n,a,t),this.query=e,this.queryStreamController=new xg(this.query,this.cacheKey,this.notifyChange.bind(this),Gd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:mg,action:tm.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["post","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(cd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,loading:t,error:n})}applyFilter(e){return e}}var Ng=Object.freeze({__proto__:null,getPostByIds:Qm,createPost:async e=>{const t=Ge();t.log("post/createPost",e),e.dataType&&!["text","image","file","video"].includes(e.dataType)||delete e.dataType;const{attachments:n,attachmentProductTags:a}=e,s=_n(e,["attachments","attachmentProductTags"]),o=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:i}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},s),{attachments:o}));xt("post.created",i);const r=Gd(i),c=t.cache&&Date.now();t.cache&&Nn(r,{cachedAt:c});const{posts:d}=r;return{data:cd.post(d[0]),cachedAt:c}},editPost:async(e,t)=>{const n=Ge();n.log("user/editPost",t);const{attachments:a}=t,s=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:o}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,Object.assign(Object.assign({},t),{attachments:s})),i=$n(o,"communityUsers"),r=n.cache&&Date.now();n.cache&&Nn(i,{cachedAt:r}),xt("local.post.updated",i);const{posts:c}=i;return{data:cd.post(c.find((t=>t.postId===e))),cachedAt:r}},deletePost:Jm,softDeletePost:async e=>{Ge().log("post/softDeletePost",e);const t=await Jm(e,!1);return cd.post(t)},hardDeletePost:async e=>{Ge().log("post/hardDeletePost",e);const t=await Jm(e,!0);return cd.post(t)},approvePost:async e=>{const t=Ge();t.log("post/approvePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/approve`);xt("post.approved",n),"community"===n.posts[0].targetType&&xt("community.updated",n);const a=$n(n,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Nn(a,{cachedAt:s}),{data:cd.post(a.posts.find((t=>t.postId===e))),cachedAt:s}},declinePost:async e=>{const t=Ge();t.log("post/declinePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/decline`);"community"===n.posts[0].targetType&&xt("community.updated",n),xt("post.declined",n);const a=$n(n,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Nn(a,{cachedAt:s}),{data:cd.post(n.posts.find((t=>t.postId===e))),cachedAt:s}},flagPost:async(t,n)=>{const a=Ge();a.log("post/flagPost",t);const s=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,a])=>t!==e.ContentFlagReasonEnum.Others&&a===n)),o={reason:n&&s?n:e.ContentFlagReasonEnum.Others,detail:n&&!s?n:""},{data:i}=await a.http.post(`/api/v3/posts/${encodeURIComponent(t)}/flag`,o);return a.cache&&Nn($n(i,"communityUsers")),xt("post.flagged",i),!!i},unflagPost:async e=>{const t=Ge();t.log("post/unflagPost",e);const{data:n}=await t.http.delete(`/api/v3/posts/${encodeURIComponent(e)}/unflag`);return t.cache&&Nn($n(n,"communityUsers")),xt("post.unflagged",n),!!n},isPostFlaggedByMe:async e=>{const t=Ge();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=Ge();t.log("post/createPost",e);const{attachments:n,attachmentProductTags:a}=e,s=_n(e,["attachments","attachmentProductTags"]),o=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:i}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},s),{attachments:o}));xt("post.created",i);const r=$n(i,"communityUsers"),c=t.cache&&Date.now();t.cache&&Nn(r,{cachedAt:c});const{posts:d}=r;return{data:cd.post(d[0]),cachedAt:c}},createAudioPost:async e=>{const t=Ge();t.log("post/createAudioPost",e);const{attachments:n,attachmentProductTags:a}=e,s=_n(e,["attachments","attachmentProductTags"]),o=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:i}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},s),{attachments:o}));xt("post.created",i);const r=Gd(i),c=t.cache&&Date.now();return t.cache&&Nn(r,{cachedAt:c}),{data:qc(null==r?void 0:r.posts[0]),cachedAt:c}},createMixedMediaPost:async e=>{var t;const n=Ge();n.log("post/createMixedMediaPost",e);const{attachments:a,attachmentProductTags:s}=e,o=_n(e,["attachments","attachmentProductTags"]),i=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:r}=await n.http.post("/api/v4/posts",Object.assign(Object.assign({},o),{attachments:i}));xt("post.created",r);const c=Gd(r),d=n.cache&&Date.now();return n.cache&&Nn(c,{cachedAt:d}),{data:qc(null===(t=null==c?void 0:c.posts)||void 0===t?void 0:t[0]),cachedAt:d}},createRoomPost:async e=>{const t=Ge();t.log("post/createRoomPost",e);const{data:n}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},e),{dataType:"room"}));xt("post.created",n);const a=Gd(n),s=t.cache&&Date.now();t.cache&&Nn(a,{cachedAt:s});const{posts:o}=a;return{data:cd.post(o[0]),cachedAt:s}},pinProduct:async(e,t)=>{const n=Ge();n.log("post/pinProduct",e);const{data:a}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{pinnedProductId:t}),s=Gd(a),o=n.cache&&Date.now();return n.cache&&Nn(a,{cachedAt:o}),xt("local.post.updated",a),{data:qc(null==s?void 0:s.posts[0]),cachedAt:o}},unpinProduct:async e=>{const t=Ge();t.log("post/unpinProduct",e);const{data:n}=await t.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{pinnedProductId:null}),a=Gd(n),s=t.cache&&Date.now();return t.cache&&Nn(n,{cachedAt:s}),xt("local.post.updated",n),{data:qc(null==a?void 0:a.posts[0]),cachedAt:s}},updateProductTags:async(e,t)=>{const n=Ge();n.log("post/updateProductTags",e);const{data:a}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{productTags:t}),s=Gd(a),o=n.cache&&Date.now();return n.cache&&Nn(a,{cachedAt:o}),xt("local.post.updated",a),{data:qc(null==s?void 0:s.posts[0]),cachedAt:o}},onPostCreated:dl,onPostUpdated:ll,onPostDeleted:ul,onPostApproved:hl,onPostDeclined:ml,onPostFlagged:gl,onPostUnflagged:pl,onPostReactionAdded:yl,onPostReactionRemoved:vl,getPost:(e,t)=>jr(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?cd.post(e.data):n}))}),"postId",Wd,[hl,ml,bm,Im,t=>ul((n=>{var a;let s=n;if(n.parentPostId===e&&n.isDeleted){const e=null===(a=nt(["post","get",n.parentPostId]))||void 0===a?void 0:a.data;e&&(e.children=e.children.filter((e=>e!==n.postId)),at(["post","get",e.postId],e),s=e)}t(s)})),gl,e=>yl((t=>{e(t)})),e=>vl((t=>{e(t)})),pl,ll,Cm,fm,Od((t=>Il((async n=>{n.referenceId===e&&(await Wd(e),t(n))}))),"referenceId","post"),Od((t=>wl((async n=>{n.referenceId===e&&(await Wd(e),t(n))}))),"referenceId","post")]),getPosts:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getPosts(tmpid: ${o}) > listen`);const i=new zm(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getPinnedPosts:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getPinnedPosts(tmpid: ${o}) > listen`);const i=new Wm(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getPinnedPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getGlobalPinnedPosts:(e,t,n)=>{const{log:a,cache:s}=Ge(),o=Date.now();a(`getGlobalPinnedPosts(tmpid: ${o}) > listen`);const i=new eg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getGlobalPinnedPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},semanticSearchPosts:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`semanticSearchPosts(tmpid: ${o}) > listen`);const i=new og(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`semanticSearchPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},searchPostsByHashtag:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`searchPostsByHashtag(tmpid: ${o}) > listen`);const i=new cg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`searchPostsByHashtag(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getLiveRoomPosts:e=>{const{log:t,cache:n}=Ge();n||console.log(ye);const a=Date.now();t(`getLiveRoomPosts(tmpid: ${a}) > listen`);const s=new Mg(e),o=s.startSubscription(),i=s.getCacheKey();return o.push((()=>it(i))),()=>{t(`getLiveRoomPosts(tmpid: ${a}) > dispose`),o.forEach((e=>e()))}},getCommunityLiveRoomPosts:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getCommunityLiveRoomPosts(tmpid: ${o}) > listen`);const i=new Kg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getCommunityLiveRoomPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});const Fg=async e=>{const t=Ge();t.log("stream/getStream",e);const{data:n}=await t.http.get(`/api/v3/video-streaming/${e}`),a=t.cache&&Date.now();t.cache&&Nn(n,{cachedAt:a});const{videoStreamings:s}=n;return{data:s.find((t=>t.streamId===e)),cachedAt:a}};Fg.locally=e=>{const t=Ge();if(t.log("stream/getStream",e),!t.cache)return;const n=nt(["stream","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const _g=e=>{const t=Ge();return qt(t,"stream/onStreamStarted","video-streaming.didStart",(t=>{Nn(t),e(t.videoStreamings[0])}))},Bg=e=>{const t=Ge();return qt(t,"stream/onStreamStropped","video-streaming.didStop",(t=>{Nn(t),e(t.videoStreamings[0])}))},$g=e=>{const t=Ge();return qt(t,"stream/onStreamRecorded","video-streaming.didRecord",(t=>{Nn(t),e(t.videoStreamings[0])}))},Lg=e=>{const t=Ge();return qt(t,"stream/onStreamFlagged","video-streaming.didFlag",(t=>{Nn(t),e(t.videoStreamings[0])}))},Qg=e=>{const t=Ge();return qt(t,"stream/onStreamTerminated","video-streaming.didTerminate",(t=>{Nn(t),e(t.videoStreamings[0])}))},Jg=(e,t)=>jr(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?cd.stream(e.data):n}))}),"streamId",Fg,[$g,_g,Bg,Lg,Qg,nu]);Jg.locally=e=>{const t=Ge();if(t.log("stream/getStreamById",e),!t.cache)return;const n=nt(["stream","get",e]);return n?{data:cd.stream(n.data),cachedAt:n.cachedAt}:void 0};const Vg=async e=>{const t=Ge();t.log("stream/queryStreams",e);const n=null!=e?e:{},{page:a,limit:s}=n,o=_n(n,["page","limit"]),i=a?{token:a}:s?{limit:s}:void 0,{data:r}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},o),{options:i})}),{paging:c,results:d}=r,{videoStreamings:l}=d,u=t.cache&&Date.now();return t.cache&&Nn(d,{cachedAt:u}),{data:l,cachedAt:u,paging:c}};var Hg=Object.freeze({__proto__:null,createStream:async e=>{const t=Ge();t.log("stream/createStream",e);const{data:n}=await t.http.post("/api/v3/video-streaming",e),a=t.cache&&Date.now();t.cache&&Nn(n,{cachedAt:a});const{videoStreamings:s}=n;return{data:cd.stream(s[0]),cachedAt:a}},updateStream:async(e,t)=>{const n=Ge();n.log("stream/updateStream",e,t);const{data:a}=await n.http.put(`/api/v3/video-streaming/${e}`,t),s=n.cache&&Date.now();n.cache&&Nn(a,{cachedAt:s});const{videoStreamings:o}=a;return{data:cd.stream(o.find((t=>t.streamId===e))),cachedAt:s}},deleteStream:async e=>{const t=Ge();t.log("stream/deleteStream",e);const n=await Fg(e),{data:a}=await t.http.delete(`/api/v3/video-streaming/${e}`),{success:s}=a,o=Object.assign(Object.assign({},n.data),{isDeleted:!0});return ot(["stream","get",e],o),s},disposeStream:async e=>{const t=Ge();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&&Nn(n,{cachedAt:a});const{videoStreamings:s}=n;return{data:s.find((t=>t.streamId===e)),cachedAt:a}},editStream:async(e,t)=>{const n=Ge();n.log("stream/updateStream",e,t);const{data:a}=await n.http.put(`/api/v3/video-streaming/${e}`,t),s=n.cache&&Date.now();n.cache&&Nn(a,{cachedAt:s});const{videoStreamings:o}=a;return{data:cd.stream(o.find((t=>t.streamId===e))),cachedAt:s}},onStreamStarted:_g,onStreamStopped:Bg,onStreamRecorded:$g,onStreamFlagged:Lg,onStreamTerminated:Qg,onStreamViewerBanned:nu,onStreamViewerUnbanned:e=>{const t=Ge();return qt(t,"stream/onStreamViewerDidUnban","video-streaming.viewerDidUnban",(async t=>{var n;const{list:a}=t;await Promise.all(a.map((({streamId:e})=>Fg(e))));const s=null===(n=nt(["stream","get",a[0].streamId]))||void 0===n?void 0:n.data;s&&e(s)}))},getStreamById:Jg,getStreams:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getStreams(tmpid: ${o}) > listen`);const{limit:i}=e,r=_n(e,["limit"]),c=null!=i?i:me,{policy:d=pe}=null!=n?n:{},l=[],u=["streams","collection",e],h=t=>{let n=rt(t,"isDeleted",e.isDeleted);return n=n.sort("lastCreated"===e.sortBy?wt:It),n},m=(e,n=!1)=>{var a,s;const o=null!==(a=e.data.map((e=>nt(["stream","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==a?a:[];t({onNextPage:p,data:n?h(o):o,hasNextPage:!!(null===(s=e.params)||void 0===s?void 0:s.page),loading:e.loading,error:e.error})},g=e=>e=>{var t;const n=null===(t=nt(u))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.streamId,...n.data])],at(u,n),m(n,!0))},p=(e=!1)=>{var t,n;const a=null===(t=nt(u))||void 0===t?void 0:t.data,s=null!==(n=null==a?void 0:a.data)&&void 0!==n?n:[];if(!e&&s.length>0&&!(null==a?void 0:a.params.page))return;const o=Fe(Vg,Object.assign(Object.assign({},r),{limit:e?c:void 0,page:e||null==a?void 0:a.params.page}));Be(o,(({data:e,error:t,loading:n,paging:a})=>{const o={loading:n,error:t,params:{page:null==a?void 0:a.next},data:s};e&&(o.data=[...new Set([...s,...e.map(Xe("stream"))])]),at(u,o),m(o)}),_e(d))};return l.push($g(g()),_g(g()),Bg(g())),p(!0),()=>{a(`getStreams(tmpid: ${o}) > dispose`),l.forEach((e=>e()))}}});const zg=async()=>{const e=Ge();e.log("presence/getPresenceSetting");const{data:t}=await e.http.get("/api/v1/presence/settings");return at(["get","presenceSetting"],t),t};class Gg{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 Gg.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 zg()}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=Ge();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 Yg=new Map,Wg=e=>{let t=Yg.get(e);return t||(t=new Gg(e),Yg.set(e,t)),t};var Xg=Object.freeze({__proto__:null,getRoomOnlineUsers:async e=>{var t,n,a;const s=Ge();s.log("room/getWatchingUsers",{roomId:e});const{data:o}=await s.http.get(`/api/v1/presence/rooms/${e}/users`),i=null!==(t=null==o?void 0:o.viewers.map((e=>e.userId)))&&void 0!==t?t:[],r=[];for(let e=0;e<i.length;e+=100)r.push(i.slice(e,e+100));const c=await Promise.all(r.map((e=>dd(e)))),d=[];return c.forEach((e=>{e.data&&d.push(...e.data)})),{data:d,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=Ge();t.log("roomPresence/getRoomUserCount",{roomId:e});const{data:n}=await t.http.get(`/api/v1/presence/rooms/${e}/users/count`);return at(["get","watchingCount",e],n),n},startHeartbeat:e=>{Wg(e).start()},stopHeartbeat:e=>{Wg(e).stop(),(e=>{const t=Yg.get(e);t&&(t.destroy(),Yg.delete(e))})(e)}});const Zg=async e=>{const t=Ge();t.log("poll/getPoll",e);const{data:n}=await t.http.get(`/api/v3/polls/${e}`),a=t.cache&&Date.now();t.cache&&Nn(n,{cachedAt:a});const{polls:s}=n,o=s.find((t=>t.pollId===e));return{data:Ec(o),cachedAt:a}};Zg.locally=e=>{const t=Ge();if(t.log("poll/getPoll",e),!t.cache)return;const n=nt(["poll","get",e]);return n?{data:Ec(n.data),cachedAt:n.cachedAt}:void 0};const ep=e=>{const t=Ge();return qt(t,"poll/onPollUpdated","poll.updated",(n=>{t.cache&&Nn(n),e(n.polls[0])}))},tp=e=>{const t=Ge();return qt(t,"poll/onPollDeleted","poll.deleted",(n=>{t.cache&&Nn(n),e(n.polls[0])}))};var np=Object.freeze({__proto__:null,createPoll:async e=>{const t=Ge();t.log("post/createPoll",e);const{data:n}=await t.http.post("/api/v3/polls",e),a=t.cache&&Date.now();t.cache&&Nn(n,{cachedAt:a});const{polls:s}=n;return{data:Ec(s[0]),cachedAt:a}},closePoll:async e=>{const t=Ge();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&&Nn(n,{cachedAt:a}),xt("poll.updated",n);const{polls:s}=n,o=s.find((t=>t.pollId===e));return{data:Ec(o),cachedAt:a}},deletePoll:async e=>{const t=Ge();t.log("poll/deletePoll",e);const n=await Zg(e),{data:a}=await t.http.delete(`/api/v3/polls/${e}`),{success:s}=a,o=Object.assign(Object.assign({},n.data),{isDeleted:!0});return ot(["poll","get",e],o),xt("poll.deleted",{polls:[o],users:[]}),s},votePoll:async(e,t)=>{const n=Ge();n.log("user/votePoll",e);const{data:a}=await n.http.post(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:t}),s=n.cache&&Date.now();n.cache&&Nn(a,{cachedAt:s});const{polls:o}=a,i=o.find((t=>t.pollId===e));return xt("poll.updated",a),{data:Ec(i),cachedAt:s}},unvotePoll:async e=>{const t=Ge();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&&Nn(n,{cachedAt:a}),xt("poll.updated",n)},onPollUpdated:ep,onPollDeleted:tp,getPoll:(e,t)=>jr(e,t,"pollId",Zg,[ep,tp])});class ap{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 s=e();if(s.length)try{const n=(new Date).toISOString(),o=await Pc({timestamp:n,streams:s});if(!o||!o.signature)throw new Error("Signature is undefined");const i={signature:o.signature,nonceStr:o.nonceStr,timestamp:n,streams:s},r=Ge();await r.http.post("/api/v3/user-event/video-streaming",i),t().length||e().length||a()}catch(e){return s.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 sp=null;class op{constructor(e,t,n){this._SDKUnsubscribers=[],this.player=e,this.resolution=t,this._startTime=null,this._usageCollector=sp||(sp=new ap,sp),this._usageCollector.registerStream(e.id),this._sessionId=String(T.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(nu((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 ip=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(!P.default.isSupported())throw new Error("This browswer does not support hls, unable to play stream");const{data:n}=await Fg(t),{watcherUrl:a,status:s,recordings:o=[],resolution:i}=n;if(!a.hls)throw new Error("This stream does not support hls. Unable to play");const r=document.createElement("video");r.id=t,r.controls=!0;const c=new P.default;if(c.attachMedia(r),"recorded"!==s){let{url:e}=a.hls;e=e.replace("http:","https:"),c.loadSource(e)}else{const e=o.find((e=>!!e.mp4));if(!e||!e.mp4)throw new Error("No playable recording available");r.src=e.mp4.url}return new op(r,i,t).registerEvents(),r}});const rp=e=>{const t=(e=>{var t;const n=Ge(),a=new Date,s=a.getTime()+31536e6,o=new Date(s).toISOString();let i=null===(t=nt(["storyTarget","get",e.targetId]))||void 0===t?void 0:t.data;return i||(i={targetType:e.targetType,targetId:e.targetId,lastStoryExpiresAt:o,targetPublicId:e.targetId,targetUpdatedAt:a.toISOString()},Nn({storyTargets:[i]})),{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(s).toISOString()},e)],categories:[],communityUsers:[],comments:[],files:[],users:[],communities:[]}})(e);return Nn(t),t},cp=({payload:e,formData:t,isVideo:n=!1},a)=>{if(t){const s=t.getAll("files")[0]||void 0;if(!s)return;const o=Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileId:void 0,fileData:s.uri})});return n&&(o.data.videoFileId={original:void 0}),a(rp(o))}return a(rp(Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileData:null})})))},dp=async e=>{const t=Ge();t.log("post/createStory",e);const n=await t.http.post("/api/v4/stories",e),a=om(n.data);t.cache&&Nn(a),at(["story-sync-state",e.targetId],"synced"),xt("local.story.created",a);const s=t.cache&&Date.now();return{data:a.stories.length>0?a.stories[0]:void 0,cachedAt:s}},lp=async({targetId:e,targetType:t})=>{var n,a;if(!nt(["storyTarget","get",e])){let s={targetId:e,targetType:t};if("community"===t){const t=await Lu(e);s=Object.assign(Object.assign({},s),{targetPublicId:t.data.communityId,targetUpdatedAt:null!==(n=t.data.updatedAt)&&void 0!==n?n:(new Date).toISOString()})}if("user"===t){const t=await yd(e);s=Object.assign(Object.assign({},s),{targetPublicId:t.data.userPublicId,targetUpdatedAt:null!==(a=t.data.updatedAt)&&void 0!==a?a:(new Date).toISOString()})}at(["storyTarget","get",e],s)}},up=e=>e?nt(["story","get",e]):{data:void 0,cachedAt:void 0},hp=async(e,t=!1)=>{var n,a,s;const o=Ge();let i;if(o.log("story/deleteStory",e),o.cache&&(i=up(e),null==i?void 0:i.data)){const{data:o}=i;if(xt("local.story.deleted",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[Object.assign(Object.assign({},o),{isDeleted:!0})]}),"synced"!==o.syncState){t?it(["story","get",e]):at(["story","get",e],Object.assign(Object.assign({},i.data),{isDeleted:!0}));const a=null===(n=tt(["story","get"]))||void 0===n?void 0:n.filter((e=>"synced"!==e.data.syncState&&e.data.targetId===o.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));at(["story-expire",i.data.targetId],e.toISOString())}else it(["story-expire",i.data.targetId]);return!0}const r=null===(a=nt(["storyTarget","get",o.targetId]))||void 0===a?void 0:a.data,c=null===(s=tt(["story","get"]))||void 0===s?void 0:s.filter((e=>"synced"===e.data.syncState&&e.data.targetId===o.targetId&&!0!==e.data.isDeleted));let d;c&&c.length>0&&(d=null==c?void 0:c.reduce(((e,t)=>{const n=new Date(t.data.expiresAt||0);return n>e?n:e}),new Date(0))),r&&at(["storyTarget","get",o.targetId],Object.assign(Object.assign({},r),{lastStoryExpiresAt:d}))}return(await o.http.delete(`/api/v4/stories/${e}`,{params:{permanent:t}})).data.success},mp=e=>{const t=Ge(),n=[qt(t,"onStoryUpdated","story.updated",(async t=>{const n=om(t);Nn(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},gp=e=>{const t=Ge(),n=[qt(t,"onStoryUpdated","local.story.updated",(async t=>{Nn(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},pp=e=>{const t=Ge(),n=[qt(t,"onStoryReactionAdded","story.reactionAdded",(async t=>{const{reactions:n}=t,a=_n(t,["reactions"]),s=om(a),o=al("story.reactionAdded",Object.assign(Object.assign({},s),{reactions:n}));Nn(o),e(o.stories)}))];return()=>{n.forEach((e=>e()))}},yp=e=>{const t=Ge(),n=[qt(t,"onStoryReactionAdded","local.story.reactionAdded",(async t=>{Nn({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},vp=e=>{const t=Ge(),n=[qt(t,"onStoryReactionRemoved","story.reactionRemoved",(async t=>{const{reactions:n}=t,a=_n(t,["reactions"]),s=om(a),o=al("story.reactionRemoved",Object.assign(Object.assign({},s),{reactions:n}));Nn(o),e(o.stories)}))];return()=>{n.forEach((e=>e()))}},fp=e=>{const t=Ge(),n=[qt(t,"onStoryReactionRemoved","local.story.reactionRemoved",(async t=>{Nn({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},bp=e=>{e.forEach((e=>{const t=nt(["story-expire",e.targetId]),n=new Date(e.expiresAt||0);n<new Date((null==t?void 0:t.data)||0)||at(["story-expire",e.targetId],n.toISOString())}))},Ip=e=>{e.forEach((e=>{at(["story-reference",e.storyId],e.referenceId)}))},Cp=async({targetType:e,targetId:t,options:n})=>{const a=Ge();a.log("story/getActiveStoriesByTarget");const s=a.cache&&Date.now(),o=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"}}}),i=om(o.data);return a.cache&&(Nn(i),bp(i.stories),Ip(i.stories)),{data:i.stories,cachedAt:s,paging:{next:void 0,previous:void 0}}},wp=e=>{const t=Ge(),n=[qt(t,"onStoryCreated","story.created",(async t=>{const n=om(t,!0);Nn(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Sp=e=>{const t=Ge(),n=[qt(t,"onStoryCreated","local.story.created",(async t=>{Nn(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},Op=e=>{const t=Ge(),n=[qt(t,"onStoryDeleted","story.deleted",(async t=>{const n=om(t);Nn(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Tp=e=>{const t=Ge(),n=[qt(t,"onStoryDeleted","local.story.deleted",(async t=>{Nn(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},Ap=e=>{const t=Ge();return qt(t,"onStoryError","local.story.error",(async t=>{Nn(t),e(t.stories)}))},Rp=e=>t=>e((e=>t(e[0]))),Pp=async e=>{const t=Ge();t.log("story/getTargetsByTargetIds",e);const n=await t.http.get("/api/v4/stories/seen",{params:{targets:e}}),{data:a}=n;return t.cache&&Nn(n.data),{data:a.storyTargets,cachedAt:Date.now()}};class Dp extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.paginationController=a}saveToMainDB(e){const t=Ge(),n=t.cache&&Date.now(),a=om(e);t.cache&&(Nn(a,{cachedAt:n}),bp(a.stories),Ip(a.stories))}getStoryReferenceIds(e){return(null==e?void 0:e.referenceId)?e.referenceId:e.storyId}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.stories.map(this.getStoryReferenceIds)});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(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=nt(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])],at(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Up extends Sr{async getRequest(e){const{data:t}=await this.http.get("/api/v4/stories-by-targets",{params:Object.assign({},e)});return t}}class kp extends Or{constructor(e,t){const n=R.default(e),a=["story-target-ids","collection",n],s=new Up(e);super(s,n,a,t),this.query=e,this.queryStreamController=new Dp(this.query,this.cacheKey,this.notifyChange.bind(this),s),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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 s=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;let o=s.data.map((e=>nt(["story","get",e]))).filter(Boolean).map((e=>cd.story(e.data)));(this.shouldNotify(o)||"event"!==e)&&(o=this.applyFilter(o),this.callback({onNextPage:void 0,data:o,hasNextPage:!1,loading:t,error:n}))}applyFilter(e){var t,n;const 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(It):a.sort(wt)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:wp,action:"onCreate"},{fn:mp,action:"onUpdate"},{fn:Op,action:"onDelete"},{fn:Ap,action:"onError"}])}}const jp=(e,t)=>{var n,a;const s=null===(n=nt(e))||void 0===n?void 0:n.data,o=null!==(a=null==s?void 0:s.data)&&void 0!==a?a:[];at(e,Object.assign(Object.assign({},s),{data:[...new Set([...o,...t])]}))};class Ep extends Ir{constructor(e,t,n,a,s){super(e,t),this.notifyChange=n,this.paginationController=a,this.preparePayload=s}saveToMainDB(e){const t=Ge(),n=t.cache&&Date.now(),a=this.preparePayload(e);t.cache&&Nn(a,{cachedAt:n})}appendToQueryStream(e,t,n=!1){n?at(this.cacheKey,{data:e.storyTargets.map((({targetId:e})=>e))}):jp(this.cacheKey,e.storyTargets.map((({targetId:e})=>e)))}reactor(e){return t=>{"onCreate"===e&&"seen"!==this.query.seenState&&jp(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 Mp extends fr{constructor(){super(...arguments),this.smartFilterState="unseen"}async getRequest(e,t){var n;const{limit:a=10,seenState:s="unseen"}=e,o=await this.createRequest({seenState:"smart"===s?this.smartFilterState:s,limit:a,token:t});if(null===(n=o.paging)||void 0===n?void 0:n.next)return o;if("smart"!==s)return o;if("seen"===this.smartFilterState)return o;this.smartFilterState="seen";const i=await this.createRequest({seenState:this.smartFilterState,limit:a});return c=i,{categories:(r=o).categories.concat(c.categories),communities:r.communities.concat(c.communities),communityUsers:r.communityUsers.concat(c.communityUsers),files:r.files.concat(c.files),storyTargets:r.storyTargets.concat(c.storyTargets),users:r.users.concat(c.users),paging:c.paging};var r,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 qp extends Or{constructor(e,t){const n=R.default(e),a=["story-global-feed","collection",n],s=new Mp(e);super(s,n,a,t),this.query=e,this.queryStreamController=new Ep(this.query,this.cacheKey,this.notifyChange.bind(this),s,(e=>{const t=_n(Kr(Object.assign(Object.assign({},e),{feeds:[]})),["feeds"]);return Object.assign(Object.assign({},e),t)})),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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 s=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=s.data,i=tt(["storyTarget"]);i&&(null==i?void 0:i.length)>0&&(null==i||i.forEach((({key:e})=>{s.data.includes(e[2])||o.push(e[2])})));let r=o.map((e=>nt(["storyTarget","get",e]))).filter(Boolean).map((e=>cd.storyTarget(e.data)));(this.shouldNotify(r)||"event"!==e)&&(r=this.applyFilter(r).filter((({localSortingDate:e})=>!!e)).map((e=>_n(e,["localFilter","localLastExpires","localLastSeen","localSortingDate"]))),this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:r,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(Ct);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(Ct)||[],a=t.unseen.sort(Ct)||[],s=t.seen.sort(Ct)||[];return n.concat(a,s)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:wp,action:"onCreate"},{fn:mp,action:"onUpdate"},{fn:Op,action:"onDelete"},{fn:Sp,action:"onCreate"},{fn:gp,action:"onUpdate"},{fn:Tp,action:"onDelete"},{fn:Ap,action:"onError"}])}}var xp=Object.freeze({__proto__:null,createImageStory:async(e,t,n,a={},s="fit",o=[])=>{if(!n.getAll("files").length)throw new Error("The formData object must have a `files` key.");let i={data:{text:"",fileId:void 0,fileData:null,imageDisplayMode:s},syncState:"syncing",referenceId:Un(),dataType:"image",items:o,targetType:e,targetId:t,metadata:a};const r=new Date;at(["story-sync-state",t],"syncing"),at(["story-expire",t],new Date(r.setFullYear(r.getFullYear()+1))),cp({payload:i,formData:n},(e=>{xt("local.story.created",e)}));try{const{data:a}=await Kd(n);if(0===a.length)throw new Error("Failed to upload image");const{fileId:s}=a[0];i=Object.assign(Object.assign({},i),{data:Object.assign(Object.assign({},i.data),{fileId:s})}),lp({targetId:t,targetType:e}),cp({payload:i,formData:n},(e=>{xt("local.story.created",e)}));const o=await dp(i);return o.data?Object.assign(Object.assign({},o),{data:cd.story(o.data)}):o}catch(e){throw at(["story-sync-state",t],"error"),cp({payload:Object.assign(Object.assign({},i),{syncState:"error"}),formData:n},(e=>{xt("local.story.error",e)})),e}},createVideoStory:async(e,t,n,a={},s=[])=>{if(!n.getAll("files").length)throw new Error("The formData object must have a `files` key.");let o={data:{text:"",fileId:void 0,fileData:null},syncState:"syncing",referenceId:Un(),dataType:"video",items:s,targetType:e,targetId:t,metadata:a};const i=new Date;at(["story-sync-state",t],"syncing"),at(["story-expire",t],new Date(i.setFullYear(i.getFullYear()+1))),lp({targetId:t,targetType:e}),cp({payload:o,formData:n,isVideo:!0},(e=>{xt("local.story.created",e)}));try{const{data:e}=await xd(n,F.STORY);if(0===e.length)throw new Error("Failed to upload video");const{fileId:t}=e[0];o=Object.assign(Object.assign({},o),{data:Object.assign(Object.assign({},o.data),{fileId:t,videoFileId:{original:t}})}),cp({payload:o,formData:n,isVideo:!0},(e=>{xt("local.story.created",e)}));const a=await dp(o);return a.data?Object.assign(Object.assign({},a),{data:cd.story(a.data)}):a}catch(e){throw at(["story-sync-state",t],"error"),cp({payload:Object.assign(Object.assign({},o),{syncState:"error"}),formData:n,isVideo:!0},(e=>{xt("local.story.error",e)})),e}},hardDeleteStory:async e=>await hp(e,!0),softDeleteStory:async e=>await hp(e),getActiveStoriesByTarget:(e,t)=>{const{log:n,cache:a}=Ge(),s=[],o=["story-target","collection",e],i=Date.now();n(`getActiveStoriesByTarget(tmpid: ${i}) > listen`),a||console.log(ye);const r=t=>{var n,a;const s=(null===(n=e.options)||void 0===n?void 0:n.sortBy)||"createdAt",o=(null===(a=e.options)||void 0===a?void 0:a.orderBy)||"desc";return 0===t.length?[]:"createdAt"===s?"asc"===o?t.sort(It):t.sort(wt):"asc"===o?t.sort(St):t.sort(Ot)},c=e=>{var n;const a=e.data.map((e=>{const t=up(e);if(null==t?void 0:t.data)return cd.story(t.data)})).filter(Boolean).filter((e=>!!e&&!e.isDeleted)),s=[];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=r(e.get("error")||[]);s.push(...t)}if(e.has("syncing")){const t=r(e.get("syncing")||[]);s.push(...t)}if(e.has("synced")){const t=r(e.get("synced")||[]);s.push(...t)}}t({onNextPage:()=>!1,data:s||a,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading||!1})},d=(t,n,a=!1,s=!1,i=!1)=>{var r;const d=nt(o),l={loading:s,error:i,params:{page:void 0},data:(null==d?void 0:d.data)||[]};if(t)if("onDelete"===n){const e=t.map((({referenceId:e})=>e));l.data=l.data.filter((t=>!e.includes(t)))||[]}else l.data=a?t.map(Xe("story")):[...new Set([...l.data,...t.map(Xe("story"))])];const u=null===(r=tt(["story","get"]))||void 0===r?void 0:r.filter((t=>t.data.targetId===e.targetId&&"synced"!==t.data.syncState)).map((e=>Xe("story")(e.data)));u&&(null==u?void 0:u.length)>0&&u.forEach((e=>{l.data.includes(e)||l.data.push(e)})),at(o,l.data),c(l)},l=e=>t=>{d(t,e)};return(t=>{const n=Fe(Cp,e);Be(n,(({data:e,error:n,loading:a})=>{d(e,"fetch",t,a,n)}))})(!0),s.push(wp(l("onCreate")),mp(l("onUpdate")),Op(l("onDelete")),pp(l("onReactionAdded")),vp(l("onReactionRemoved")),Ap(l("onError")),Sp(l("onCreate")),gp(l("onUpdate")),Tp(l("onDelete")),yp(l("onReactionAdded")),fp(l("onReactionRemoved")),(e=>{const t=Ge();return qt(t,"onStoryLocalDataUpdated","local.story.reload",(t=>{e(t)}))})((e=>{const t=nt(o);if(!t)return;if(0===e.referenceIds.length||0===(null==t?void 0:t.data.length))return;if(!(null==t?void 0:t.data.find((t=>e.referenceIds.includes(t)))))return;const n={loading:!1,error:!1,params:{page:void 0},data:(null==t?void 0:t.data)||[]};c(n)})),(()=>it(o))),()=>{n(`getActiveStoriesByTarget(tmpid: ${i}) > dispose`),s.forEach((e=>e()))}},getStoryByStoryId:(e,t)=>jr(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:cd.story(e.data)})):t(e)}),"storyId",im,[Rp(mp),Rp(Op),Rp(pp),Rp(vp),Rp(Ap),Rp(gp),Rp(Tp),Rp(yp),Rp(fp)]),getTargetById:(e,t)=>jr(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:cd.storyTarget(e.data[0])})):t(e)}),"query",(e=>Pp([e])),[]),getTargetsByTargetIds:(e,t)=>{const{log:n,cache:a}=Ge(),s=[],o=["storyTargets","collection",e],i=Date.now();n(`getTargetsByTargetIds(tmpid: ${i}) > listen`),a||console.log(ye);const r=(e,n=!1,a=!1,s=!1)=>{const i=nt(o),r={loading:a,error:s,params:{page:void 0},data:[]};e&&(r.data=n?e.map(Xe("storyTarget")):[...new Set([...(null==i?void 0:i.data)||[],...e.map(Xe("storyTarget"))])]),at(o,r.data),(e=>{var n;const a=e.data.map((e=>{const t=nt(["storyTarget","get",e]);if(null==t?void 0:t.data)return cd.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})})(r)};return(t=>{const n=Fe(Pp,e);Be(n,(({data:e,error:n,loading:a})=>{r(e,t,a,n)}))})(!0),s.push((()=>it(o))),()=>{n(`getTargetsByTargetIds(tmpid: ${i}) > dispose`),s.forEach((e=>e()))}},getStoriesByTargetIds:(e,t,n)=>{const{log:a,cache:s,userId:o}=Ge();s||console.log(ye);const i=Date.now();a(`getStoriesByTargetIds(tmpid: ${i}) > listen`);const r=new kp(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>{it(d)})),()=>{a(`getStoriesByTargetIds(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}},getGlobalStoryTargets:(e,t,n)=>{const{log:a,cache:s,userId:o}=Ge();s||console.log(ye);const i=Date.now();a(`getGlobalStoryTarget(tmpid: ${i}) > listen`);const r=new qp(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>{it(d)})),()=>{a(`getGlobalStoryTarget(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}}});const Kp=e=>Object.assign(Object.assign({},e),{endAt:e.endAt?e.endAt:null}),Np=e=>Object.assign({},e);var Fp=Object.freeze({__proto__:null,getNetworkAds:async()=>{const e=Ge(),{data:t}=await e.http.get("/api/v1/ads/me"),n=t.ads.map(Kp),a=t.advertisers.map(Np);return Nn({ads:n,advertisers:a,files:t.files}),at(["ad","setting"],t.settings),{ads:n.map(cd.ad),settings:t.settings}}});const _p=async()=>{const e=Ge();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];at(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}};_p.locally=()=>{var e;const t=Ge();if(t.log("notificationTray/getNotificationTraySeen.locally",{}),!t.cache)return;const{data:n,cachedAt:a}=null!==(e=nt(["notificationTraySeen","get"]))&&void 0!==e?e:{};return n?{data:n,cachedAt:a}:void 0};const Bp=e=>{const t=Ge(),n=[qt(t,"onNotificationTraySeenUpdated","local.notificationTraySeen.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class $p extends fr{async getRequest(e,t){const{limit:n=me}=e,a=_n(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/notification-tray",{params:Object.assign(Object.assign({},a),{options:s})});return o}}class Lp extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.notificationTrayItems.map(Xe("notificationTrayItem"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.notificationTrayItems.map(Xe("notificationTrayItem"))])]}))}}}const Qp=e=>{const t=e.users.map(ga);return Object.assign(Object.assign({},e),{users:t})};class Jp extends Or{constructor(e,t){const n=R.default(e),a=["notificationTrayItem","collection",n];super(new $p(e),n,a,t),this.query=e,this.queryStreamController=new Lp(this.query,this.cacheKey,this.notifyChange.bind(this),Qp),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>nt(["notificationTrayItem","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(cd.notificationTray);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var Vp=Object.freeze({__proto__:null,getNotificationTraySeen:e=>{const{userId:t}=Dt();return jr(t,e,"userId",_p,[Bp],{callbackDataSelector:e=>{let t=!0;return(null==e?void 0:e.lastTrayOccurredAt)&&(t=!!e.lastTraySeenAt&&Hn(e.lastTraySeenAt)>Hn(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:s}=Ge();s||console.log(ye);const o=Date.now();a(`getNotificationTrayItems(tmpid: ${o}) > listen`);const i=new Jp(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getNotificationTrayItems(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},markItemsSeen:async e=>{const t=Ge();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=nt(["notificationTrayItem","get",e.id]))||void 0===n?void 0:n.data;if(!a)return;const s=Object.assign(Object.assign({},a),{lastSeenAt:e.lastSeenAt});if(t.cache){const e=Date.now();at(["notificationTrayItem","get"],s,{cachedAt:e})}return s})).filter(Boolean);xt("local.notificationTrayItem.updated",{notificationTrayItems:a})},markTraySeen:async e=>{var t;const n=Ge();n.log("notificationTray/markTraySeen",{});const{data:a}=await n.http.post("api/v1/notification-tray/tray/seen",{lastSeenAt:e}),s=null===(t=nt(["notificationTraySeen","get"]))||void 0===t?void 0:t.data,o={userId:n.userId,lastTraySeenAt:a.lastSeenAt},i=Object.assign(Object.assign({},s),o),r=n.cache&&Date.now();return n.cache&&at(["notificationTraySeen","get",n.userId],i,{cachedAt:r}),xt("local.notificationTraySeen.updated",o),{data:a,cachedAt:r}},onNotificationTraySeenUpdated:Bp});class Hp extends fr{async getRequest(e,t){const{limit:n=me}=e,a=_n(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/invitations/me",{params:Object.assign(Object.assign({},a),{options:s})}),i=o.invitations.filter((e=>"community"===e.targetType&&!!e.communityId)).map((e=>e.communityId));return(null==i?void 0:i.length)>0&&await $u(i),o}}class zp extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.invitations.map(Xe("invitation"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(Xe("invitation"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===nc.OnLocalInvitationUpdated){if(!a.data.find((e=>e===t[0].invitationId)))return}if(e===nc.OnLocalInvitationCreated){const e=Ge(),n=t.filter((t=>t.invitedUserId===e.userId));a.data=[...new Set([...n.map((e=>e.invitationId)),...a.data])]}e===nc.OnLocalInvitationCanceled&&(a.data=a.data.filter((e=>e!==t[0].invitationId))),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Gp extends Or{constructor(e,t){const n=R.default(e),a=["invitation","collection",n];super(new Hp(e),n,a,t),this.query=e,this.queryStreamController=new zp(this.query,this.cacheKey,this.notifyChange.bind(this),Zr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:oc,action:nc.OnLocalInvitationCreated},{fn:ic,action:nc.OnLocalInvitationUpdated},{fn:rc,action:nc.OnLocalInvitationCanceled}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["invitation","get",e]))).filter(Tr).map((({data:e})=>ec(e))))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,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?It:wt)();return t=t.sort(n),t}}var Yp=Object.freeze({__proto__:null,cancelInvitation:async e=>{var t;const n=Ge();n.log("invitation/cancelInvitation",e);const{data:a}=await n.http.delete(`/api/v1/invitations/${e}`),s=null===(t=nt(["invitation","get",e]))||void 0===t?void 0:t.data;return Fn("invitation",e),s&&xt("local.invitation.canceled",[s]),a.success},onLocalInvitationCreated:oc,onLocalInvitationUpdated:ic,onLocalInvitationCanceled:rc,getMyCommunityInvitations:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getMyCommunityInvitations: (tmpid: ${o}) > listen`);const i=new Gp(Object.assign(Object.assign({},e),{targetType:"community",statuses:["pending"]}),t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{it(c)})),()=>{a(`getInvitations (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getInvitations:(e,t)=>{const{_id:n}=Bt();if(!n)throw new Le("The _id has not been defined in ActiveUser",8e5,"error");const{log:a}=Ge(),{targetId:s,targetType:o}=e,i=Date.now();a(`observeInvitations(tmpid: ${i}) > listen for ${o}: ${s}`);const r=[],c=n=>{const a=(Array.isArray(n)?n:[n]).filter((({targetId:t,targetType:n})=>t===e.targetId&&n===e.targetType));(e=>{t(e.map(cd.invitation))})(a)};return"room"===o&&(r.push(pg(c)),r.push(vg(c)),r.push(fg(c)),r.push(bg(c))),()=>{a(`getInvitations(tmpid: ${i}) > dispose for ${o}: ${s}`),r.forEach((e=>e()))}}});const Wp=e=>{const t=Ge();return qt(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 Xp=Object.freeze({__proto__:null,createReaction:async({referenceId:e,referenceType:t,reactionName:n,streamId:a,roomId:s})=>{const o=Ge();if(o.log("live_reaction/createReaction",{referenceId:e,referenceType:t,reactionName:n,streamId:a,roomId:s}),!a&&!s)throw new Le("You have to specify either streamId or roomId",800110,"error");const i=Mo(),r={reactionName:n,referencePublicId:e,referenceType:t,roomId:s,streamId:a,occurredAt:(new Date).toISOString()};return i.createLiveReaction(r),xt("local.liveReaction.created",[Object.assign(Object.assign({},r),{userId:o.userId,referenceId:e})]),!0},onLiveReactionCreated:Wp,getReactions:(e,t)=>{const{_id:n}=Dt();if(!n)throw new Le("The _id has not been defined in ActiveUser",8e5,"error");const{log:a}=Ge();a(`getReactions(tmpid: ${Date.now()}) > listen`);const s=[],o=n=>{(e=>{t(e)})(n.filter((({referenceId:t})=>t===e)))};return s.push(Wp(o)),s.push((e=>{const t=Ge();return qt(t,"live_reaction/onLiveReactionCreated","local.liveReaction.created",e)})(o)),()=>{s.forEach((e=>e()))}}});const Zp=async e=>{const t=Ge();t.log("event/getEvent",e);try{const{data:n}=await t.http.get(`/api/v1/events/${e}`),a=$c(n),s=t.cache&&Date.now();return t.cache&&Nn(a,{cachedAt:s}),{data:a.events.find((t=>t.eventId===e)),cachedAt:s}}catch(n){if(Re(null==n?void 0:n.code)){const a=Zp.locally(e);if(!a)throw n;const s=Object.assign(Object.assign({},null==a?void 0:a.data),{isDeleted:!0});ot(["event","get",e],s);return{data:s,cachedAt:t.cache&&Date.now()}}throw n}};Zp.locally=e=>{const t=Ge();if(t.log("event/getEvent.locally",e),!t.cache)return;const n=nt(["event","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class ey extends fr{async getRequest(e,t){const{limit:n=me}=e,a=_n(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/events",{params:Object.assign(Object.assign({},a),{options:s})});return o}}class ty extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.events.map(Xe("event"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.events.map(Xe("event"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===Vc.OnEventCreated&&(a.data=[...new Set([t.eventId,...a.data])]),e===Vc.OnEventDeleted&&(a.data=a.data.filter((e=>e!==t.eventId))),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class ny extends Or{constructor(e,t){const n=R.default(e),a=["event","collection",n];super(new ey(e),n,a,t),this.query=e,this.queryStreamController=new ty(this.query,this.cacheKey,this.notifyChange.bind(this),$c),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Gc,action:Vc.OnEventCreated},{fn:Yc,action:Vc.OnEventUpdated},{fn:Wc,action:Vc.OnEventDeleted},{fn:Xc,action:Vc.OnEventCreated},{fn:Zc,action:Vc.OnEventUpdated},{fn:ed,action:Vc.OnEventDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>nt(["event","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(cd.event);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}class ay extends fr{async getRequest(e,t){const{limit:n=me}=e,a=_n(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/events/me/rsvps",{params:Object.assign(Object.assign({},a),{options:s})});return o}}class sy extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.events.map(Xe("event"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.events.map(Xe("event"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===Vc.OnEventCreated){if(Ge().userId!==t.userId)return;a.data=[...new Set([t.eventId,...a.data])]}e===Vc.OnEventDeleted&&(a.data=a.data.filter((e=>e!==t.eventId))),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class oy extends Or{constructor(e,t){const n=R.default(e),a=["event","collection",n];super(new ay(e),n,a,t),this.query=e,this.queryStreamController=new sy(this.query,this.cacheKey,this.notifyChange.bind(this),$c),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Gc,action:Vc.OnEventCreated},{fn:Yc,action:Vc.OnEventUpdated},{fn:Wc,action:Vc.OnEventDeleted},{fn:Xc,action:Vc.OnEventCreated},{fn:Zc,action:Vc.OnEventUpdated},{fn:ed,action:Vc.OnEventDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>nt(["event","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(cd.event);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}var iy=Object.freeze({__proto__:null,createEvent:async e=>{const t=Ge();t.log("event/createEvent",e);const{data:n}=await t.http.post("/api/v1/events",e);xt("local.event.created",n);const a=$c(n),s=t.cache&&Date.now();return t.cache&&Nn(a,{cachedAt:s}),{data:rd(a.events[0]),cachedAt:s}},updateEvent:async(e,t)=>{const n=Ge();n.log("event/updateEvent",e,t);const{data:a}=await n.http.put(`/api/v1/events/${e}`,t);xt("local.event.updated",a);const s=$c(a),o=n.cache&&Date.now();return n.cache&&Nn(s,{cachedAt:o}),{data:rd(s.events.find((t=>t.eventId===e))),cachedAt:o}},deleteEvent:async e=>{const t=Ge();t.log("event/deleteEvent",e);const n=await Zp(e);await t.http.delete(`/api/v1/events/${e}`);const a=Object.assign(Object.assign({},n.data),{isDeleted:!0});ot(["event","get",e],a),xt("local.event.deleted",{users:[],files:[],communities:[],posts:[],rooms:[],events:[a]})},onEventCreated:Gc,onEventUpdated:Yc,onEventDeleted:Wc,onLocalEventCreated:Xc,onLocalEventUpdated:Zc,onLocalEventDeleted:ed,onRSVPCreated:td,onRSVPUpdated:nd,onLocalRSVPCreated:ad,onLocalRSVPUpdated:sd,getEvent:(e,t)=>jr(e,t,"eventId",Zp,[Yc,Wc,Zc,ed],{callbackDataSelector:e=>e?rd(e):e}),getEvents:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getEvents: (tmpid: ${o}) > listen`);const i=new ny(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getEvents (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getMyEvents:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getMyEvents: (tmpid: ${o}) > listen`);const i=new oy(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getMyEvents (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getRSVPs:id});const ry=async e=>{const t=Ge();let n;t.log("product/getProduct",e),Zn("product",e);try{n=(await t.http.get(`/api/v1/products/${encodeURIComponent(e)}`)).data}catch(t){throw Re(null==t?void 0:t.code)&&Fn("product",e),t}const a=t.cache&&Date.now();t.cache&&Nn(n,{cachedAt:a});const{products:s}=n;return{data:s.find((t=>t.productId===e)),cachedAt:a}};ry.locally=e=>{const t=Ge();if(t.log("product/getProduct.locally",e),!t.cache)return;const n=nt(["product","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class cy extends fr{async getRequest(e,t){const{limit:n=me}=e,a=_n(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/products/search",{params:Object.assign(Object.assign({},a),{options:s})});return o}}class dy extends Ir{constructor(e,t,n){super(e,t),this.notifyChange=n}saveToMainDB(e){const t=Ge(),n=t.cache&&Date.now();t.cache&&Nn(e,{cachedAt:n})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.products.map(Xe("product"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.products.map(Xe("product"))])]}))}}}class ly extends Or{constructor(e,t){const n=R.default(e),a=["products","collection",n];super(new cy(e),n,a,t),this.query=e,this.queryStreamController=new dy(this.query,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>nt(["product","get",e]))).filter(Tr).map((({data:e})=>e)).map(cd.product))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var uy=Object.freeze({__proto__:null,getProduct:(e,t)=>jr(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?cd.product(n):n}))}),"productId",ry,[]),searchProducts:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`searchProducts(tmpid: ${o}) > listen`);const i=new ly(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`searchProducts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});return e.API_REGIONS=sn,e.AdRepository=Fp,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=Xh,e.ChannelRepository=_u,e.Client=tr,e.CommentRepository=vm,e.CommunityPostSettingMaps=x,e.CommunityPostSettings=q,e.CommunityRepository=Gh,e.ContentFeedType=F,e.DefaultCommunityPostSetting=K,e.EventRepository=iy,e.FeedRepository=Lm,e.FileRepository=Nd,e.FileType=D,e.GET_WATCHER_URLS=pc,e.InvitationRepository=Yp,e.LiveReactionRepository=Xp,e.LiveStreamPlayer=ip,e.MessageContentType=B,e.MessageRepository=du,e.PollRepository=np,e.PostContentType=$,e.PostRepository=Ng,e.PostStructureType=L,e.ProductRepository=uy,e.ReactionRepository=jl,e.RoomPresenceRepository=Xg,e.RoomRepository=Eg,e.StoryRepository=xp,e.StreamRepository=Hg,e.SubChannelRepository=yu,e.UserRepository=Md,e.VERSION=he,e.VideoResolution=U,e.VideoSize=j,e.VideoTranscodingStatus=k,e.backupCache=async(e="amitySdk",t=(e=>e.offline))=>{const{log:n,cache:a,userId:s}=Ge();if(!a)return!1;n("cache/api/backupCache",{storageKey:e});const o=Object.fromEntries(Object.entries(a.data).filter((([e,n])=>t(n))));return!!Object.keys(o).length&&(localStorage&&await localStorage.setItem(`${e}#${s}`,JSON.stringify(o)),!0)},e.createQuery=Fe,e.createReport=async(e,t,n)=>{const a=Ge();return a.log("report/createReport",{referenceType:e,referenceId:t,options:n}),"user"===e?(async({referenceId:e,options:t})=>!!await ld(e,t))({referenceId:t,options:n}):"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 ua(n);Nn(e)}return xt("message.flagged",n),!!n})({client:a,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 Gd(n);Nn(e)}return xt("post.flagged",n),!!n})({client:a,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 El(n);Nn(e)}return xt("comment.flagged",n),!!n})({client:a,referenceId:t})},e.createUserToken=async(e,t,n)=>{const a=await jn(),s=En(),o=pn(rn("http",t)),{data:i}=await o.post("/api/v5/sessions",Object.assign(Object.assign({},n),{deviceId:a,deviceInfo:Object.assign(Object.assign({},s),{model:"token management API on TS-SDK"})}),{headers:{"X-API-Key":e}});return{accessToken:i.accessToken}},e.deleteReport=async(e,t)=>{const n=Ge();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 Ws(n);Nn(e)}return xt("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 ua(n);Nn(e)}return xt("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 Gd(n);Nn(e)}return xt("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 El(n);Nn(e)}return xt("comment.unflagged",n),!!n})({client:n,referenceId:t})},e.disableCache=()=>{const e=Ge();e.cache&&(e.log("cache/api/disableCache"),delete e.cache)},e.dropFromCache=it,e.enableCache=(e={},t)=>{const n=Ge();n.cache||(n.log("cache/api/enableCache"),n.cache={data:e,persistIf:t})},e.exceedsUntilAtBoundary=Rt,e.filterByChannelMembership=lt,e.filterByCommunityMembership=ht,e.filterByFeedType=ut,e.filterByPostDataTypes=mt,e.filterByPropEquality=rt,e.filterByPropInclusion=(e,t,n)=>void 0!==n?e.filter((e=>n.includes(e[t]))):e,e.filterByPropIntersection=dt,e.filterBySearchTerm=gt,e.filterByStringComparePartially=ct,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=vt,e.filterPostsByBlockUsers=yt,e.getBlockUsersId=pt,e.getChannelTopic=e=>`${e.path}/#`,e.getCommentTopic=({path:e})=>e,e.getCommunityStoriesTopic=({targetId:e,targetType:t})=>{const n=Dt();return`${Qt(n)}/social/${t}/${e}/story/#`},e.getCommunityTopic=({path:t},n=e.SubscriptionLevels.COMMUNITY)=>Lt(t,n),e.getLiveReactionTopic=e=>`${e.path}/liveReaction`,e.getLiveStreamTopic=Xt,e.getMarkedMessageTopic=Ht,e.getMarkerUserFeedTopic=()=>{const e=Dt();return`${Qt(e)}/marker/user/${e._id}`},e.getMessageTopic=e=>e.path,e.getMyFollowersTopic=Jt,e.getMyFollowingsTopic=Vt,e.getNetworkId=Qt,e.getNetworkTopic=zt,e.getPostTopic=({path:t},n=e.SubscriptionLevels.POST)=>"comment"===n?`${t}/comment/+`:t,e.getRole=_d,e.getRoomStreamerTopic=e=>{const t=Bt();return`${Qt(t)}/room/${e.roomId}/streamer`},e.getRoomWatcherTopic=e=>{const t=Bt();return`${Qt(t)}/room/${e._id}`},e.getSmartFeedChannelTopic=Gt,e.getSmartFeedMessageTopic=Wt,e.getSmartFeedSubChannelTopic=Yt,e.getStoryTopic=({targetId:e,targetType:t,storyId:n})=>{const a=Dt();return`${Qt(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=De,e.isAfterBeforeRaw=Ue,e.isCachable=Ke,e.isFetcher=Me,e.isFresh=Ne,e.isLocal=e=>Ke(e)&&-1===(null==e?void 0:e.cachedAt),e.isMutator=qe,e.isOffline=xe,e.isPaged=ke,e.isReportedByMe=async(e,t)=>{const n=Ge();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:s,isFlagByMe:o}=null!=a?a:{};return null!==(n=null!=s?s:o)&&void 0!==n&&n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{var n;const{data:a}=await e.http.get(`/api/v5/messages/${encodeURIComponent(t)}/flags`),{result:s,isFlagByMe:o}=null!=a?a:{};return null!==(n=null!=s?s:o)&&void 0!==n&&n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{var n;const{data:a}=await e.http.get(`/api/v3/posts/${t}/isflagbyme`),{result:s,isFlagByMe:o}=null!=a?a:{};return null!==(n=null!=s?s:o)&&void 0!==n&&n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{var n;const{data:a}=await e.http.get(`/api/v3/comments/${t}/isflagbyme`),{result:s,isFlagByMe:o}=null!=a?a:{};return null!==(n=null!=s?s:o)&&void 0!==n&&n})({client:n,referenceId:t})},e.isSkip=Pe,e.mergeInCache=st,e.notificationTray=Vp,e.onChannelMarkerFetched=Vi,e.onFeedMarkerFetched=e=>{const t=Ge();return qt(t,"feedMarker/onFeedMarkerFetched","local.feedMarker.fetched",(t=>{e(t.feedMarkers[0])}))},e.onFeedMarkerUpdated=e=>{const t=Ge();return qt(t,"feedMarker/onFeedMarkerUpdated","marker.feed-updated",(t=>{Nn(t),e(t.feedMarkers[0])}))},e.onMessageMarked=Wi,e.onMessageMarkerFetched=Yi,e.onSubChannelMarkerFetched=Hi,e.onSubChannelMarkerUpdated=zi,e.onUserMarkerFetched=Gi,e.onUserMarkerFetchedLegacy=e=>{const t=Ge();return qt(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers[0])}))},e.pullFromCache=nt,e.pushToCache=at,e.queryCache=tt,e.queryOptions=_e,e.queryRoles=Fd,e.restoreCache=async(e="amitySdk")=>{var t;const n=Ge();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 s={};try{s=JSON.parse(a)}catch(e){}return n.cache.data=Object.assign(Object.assign({},s),n.cache.data),!0},e.runQuery=Be,e.sortByChannelSegment=({channelSegment:e},{channelSegment:t})=>e-t,e.sortByDisplayName=ft,e.sortByFirstCreated=It,e.sortByFirstUpdated=St,e.sortByLastActivity=Tt,e.sortByLastCreated=wt,e.sortByLastUpdated=Ot,e.sortByLocalSortingDate=Ct,e.sortByName=bt,e.sortBySegmentNumber=({segmentNumber:e},{segmentNumber:t})=>e-t,e.subscribeTopic=Zt,e.toPage=Ee,e.toPageRaw=e=>{if(!e)return;const n=JSON.parse(t.decode(e));return Ue(n)?n:void 0},e.toToken=je,e.upsertInCache=ot,e.validateUntilAt=At,e.wipeCache=async(e="amitySdk")=>{const{log:t,cache:n,userId:a}=Ge();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,mqtt,AsyncStorage,uuid$1,jwtDecode,reactNative,hash,Hls);
1
+ var Amity=function(e,t,n,a,s,o,i,r,c,d,l,u,h){"use strict";function m(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var g,p,y,v,f,b=m(n),I=m(a),C=m(s),w=m(o),S=m(i),O=m(r),T=m(c),A=m(d),R=m(u),P=m(h);e.MembershipAcceptanceTypeEnum=void 0,(g=e.MembershipAcceptanceTypeEnum||(e.MembershipAcceptanceTypeEnum={})).AUTOMATIC="automatic",g.INVITATION="invitation",e.AmityAutoSubscription=void 0,(p=e.AmityAutoSubscription||(e.AmityAutoSubscription={})).CHAT="chat",p.NETWORK="network",p.LIVESTREAM="livestream",p.BLOCK="block",e.UserTypeEnum=void 0,(y=e.UserTypeEnum||(e.UserTypeEnum={})).SIGNED_IN="signed-in",y.VISITOR="visitor",y.BOT="bot",e.SearchUsersByEnum=void 0,(v=e.SearchUsersByEnum||(e.SearchUsersByEnum={})).DISPLAY_NAME="displayName",v.PROFILE_HANDLE="profileHandle",v.USER_ID="userId",e.UserReportTypeEnum=void 0,(f=e.UserReportTypeEnum||(e.UserReportTypeEnum={})).DISPLAY_NAME="displayName",f.DESCRIPTION="description",f.AVATAR="avatarFileId",f.BEHAVIOR="behavior";const D=Object.freeze({FILE:"file",IMAGE:"image",VIDEO:"video",CLIP:"clip",AUDIO:"audio"}),U=Object.freeze({"1080P":"1080p","720P":"720p","480P":"480p","360P":"360p",ORIGINAL:"original"}),k=Object.freeze({UPLOADED:"uploaded",TRANSCODING:"transcoding",TRANSCODED:"transcoded",TRANSCODE_FAILED:"transcodeFailed"}),j=Object.freeze({LOW:"low",MEDIUM:"medium",HIGH:"high",ORIGINAL:"original"});var E,M;e.FileAccessTypeEnum=void 0,(E=e.FileAccessTypeEnum||(e.FileAccessTypeEnum={})).PUBLIC="public",E.NETWORK="network",e.AmityChannelNotificationModeEnum=void 0,(M=e.AmityChannelNotificationModeEnum||(e.AmityChannelNotificationModeEnum={})).Default="default",M.Silent="silent",M.Subscribe="subscribe";const q=Object.freeze({ONLY_ADMIN_CAN_POST:"ONLY_ADMIN_CAN_POST",ADMIN_REVIEW_POST_REQUIRED:"ADMIN_REVIEW_POST_REQUIRED",ANYONE_CAN_POST:"ANYONE_CAN_POST"}),x=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}}),K="ONLY_ADMIN_CAN_POST";var N;e.AmityCommunityType=void 0,(N=e.AmityCommunityType||(e.AmityCommunityType={})).Default="default",N.Event="event";const F=Object.freeze({STORY:"story",CLIP:"clip",CHAT:"chat",POST:"post",MESSAGE:"message"});var _;e.ContentFlagReasonEnum=void 0,(_=e.ContentFlagReasonEnum||(e.ContentFlagReasonEnum={})).CommunityGuidelines="Against community guidelines",_.HarassmentOrBullying="Harassment or bullying",_.SelfHarmOrSuicide="Self-harm or suicide",_.ViolenceOrThreateningContent="Violence or threatening content",_.SellingRestrictedItems="Selling and promoting restricted items",_.SexualContentOrNudity="Sexual content or nudity",_.SpamOrScams="Spam or scams",_.FalseInformation="False information or misinformation",_.Others="Others";const B=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",AUDIO:"audio",CUSTOM:"custom"}),$=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 Q,V,J,H,z,G,Y,W,X,Z,ee,te,ne,ae,se,oe,ie,re,ce,de,le,ue;e.InvitationTypeEnum=void 0,(Q=e.InvitationTypeEnum||(e.InvitationTypeEnum={})).CommunityMemberInvite="communityMemberInvite",Q.LivestreamCohostInvite="livestreamCohostInvite",e.InvitationStatusEnum=void 0,(V=e.InvitationStatusEnum||(e.InvitationStatusEnum={})).Pending="pending",V.Approved="approved",V.Rejected="rejected",V.Cancelled="cancelled",e.InvitationSortByEnum=void 0,(J=e.InvitationSortByEnum||(e.InvitationSortByEnum={})).FirstCreated="firstCreated",J.LastCreated="lastCreated",e.InvitationTargetTypeEnum=void 0,(H=e.InvitationTargetTypeEnum||(e.InvitationTargetTypeEnum={})).Community="community",H.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,(G=e.JoinResultStatusEnum||(e.JoinResultStatusEnum={})).Success="success",G.Pending="pending",e.FeedDataTypeEnum=void 0,(Y=e.FeedDataTypeEnum||(e.FeedDataTypeEnum={})).Text="text",Y.Video="video",Y.Image="image",Y.File="file",Y.Audio="audio",Y.LiveStream="liveStream",Y.Clip="clip",Y.Poll="poll",Y.Room="room",e.FeedSortByEnum=void 0,(W=e.FeedSortByEnum||(e.FeedSortByEnum={})).LastCreated="lastCreated",W.FirstCreated="firstCreated",W.LastUpdated="lastUpdated",W.FirstUpdated="firstUpdated",e.FeedSourceEnum=void 0,(X=e.FeedSourceEnum||(e.FeedSourceEnum={})).Community="community",X.User="user",e.FeedTypeEnum=void 0,(Z=e.FeedTypeEnum||(e.FeedTypeEnum={})).Reviewing="reviewing",Z.Published="published",Z.Declined="declined",e.AmityEventType=void 0,(ee=e.AmityEventType||(e.AmityEventType={})).Virtual="virtual",ee.InPerson="in_person",e.AmityEventOriginType=void 0,(te=e.AmityEventOriginType||(e.AmityEventOriginType={})).Community="community",te.User="user",e.AmityEventStatus=void 0,(ne=e.AmityEventStatus||(e.AmityEventStatus={})).Scheduled="scheduled",ne.Live="live",ne.Ended="ended",ne.Cancelled="cancelled",e.AmityEventResponseStatus=void 0,(ae=e.AmityEventResponseStatus||(e.AmityEventResponseStatus={})).Going="going",ae.NotGoing="not_going",e.AmityEventSortOption=void 0,(se=e.AmityEventSortOption||(e.AmityEventSortOption={})).StartTime="startTime",se.CreatedAt="createdAt",e.AmityEventOrderOption=void 0,(oe=e.AmityEventOrderOption||(e.AmityEventOrderOption={})).Ascending="asc",oe.Descending="desc",e.AmitySharableContentType=void 0,(ie=e.AmitySharableContentType||(e.AmitySharableContentType={})).POST="post",ie.COMMUNITY="community",ie.USER="user",ie.LIVESTREAM="livestream",ie.EVENT="event",e.AnalyticsSourceTypeEnum=void 0,(re=e.AnalyticsSourceTypeEnum||(e.AnalyticsSourceTypeEnum={})).POST="post",re.ROOM="room",e.UserNotificationModuleNameEnum=void 0,(ce=e.UserNotificationModuleNameEnum||(e.UserNotificationModuleNameEnum={})).CHAT="chat",ce.SOCIAL="social",ce.VIDEO_STREAMING="video-streaming",e.CommunityNotificationEventNameEnum=void 0,(de=e.CommunityNotificationEventNameEnum||(e.CommunityNotificationEventNameEnum={})).POST_CREATED="post.created",de.POST_REACTED="post.reacted",de.COMMENT_CREATED="comment.created",de.COMMENT_REPLIED="comment.replied",de.COMMENT_REACTED="comment.reacted",de.STORY_CREATED="story.created",de.STORY_REACTED="story.reacted",de.STORY_COMMENT_CREATED="story-comment.created",de.LIVESTREAM_START="video-streaming.didStart",e.NotificationSettingsLevelEnum=void 0,(le=e.NotificationSettingsLevelEnum||(e.NotificationSettingsLevelEnum={})).USER="user",le.COMMUNITY="community",le.CHANNEL="channel",e.NotificationRolesFilterTypeEnum=void 0,(ue=e.NotificationRolesFilterTypeEnum||(e.NotificationRolesFilterTypeEnum={})).ALL="all",ue.ONLY="only";const he=function(){try{return"v7.25.0-umd"}catch(e){return"__dev__"}}(),me=5,ge=20,pe="cache_then_server",ye="For using Live Collection feature you need to enable Cache!",ve="Observing unsynced object is not supported by Live Object.",fe=-5,be=1e3,Ie=6e5,Ce="/api/v1/feeds/for-you",we="dead",Se=6e4,Oe=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})),Te=e=>JSON.parse(e),Ae=(e,t)=>e===t||!(!e||!t)&&("object"==typeof e&&Object.keys(e).every((n=>Ae(e[n],t[n])))),Re=e=>[400400,400300].includes(e),Pe=e=>["skip"].some((t=>t in e)),De=e=>["after","before","first","last","limit"].some((t=>t in e)),Ue=e=>"limit"in e,ke=e=>(null==e?void 0:e.hasOwnProperty("data"))&&(null==e?void 0:e.hasOwnProperty("nextPage"))&&(null==e?void 0:e.hasOwnProperty("prevPage")),je=(e,n)=>{var a;if(!e||!Object.keys(e).length)return;let s={};return"skiplimit"===n?s={skip:null!==(a=e.after)&&void 0!==a?a:0,limit:e.limit}:"afterbefore"===n&&De(e)?((null==e?void 0:e.before)&&(s=Object.assign(Object.assign({},s),{before:e.before})),(null==e?void 0:e.after)&&(s=Object.assign(Object.assign({},s),{after:e.after})),Number.isNaN(Number(null==e?void 0:e.limit))||(s=Object.assign(Object.assign({},s),{limit:e.limit}))):"afterbeforeraw"===n&&(s=e),Object.keys(s).length?t.encode(JSON.stringify(s)):void 0},Ee=e=>{if(!e)return;const n=JSON.parse(t.decode(e));if(Pe(n))return{after:n.skip,limit:n.limit};if(De(n)){if("before"in n)return{before:n.before,limit:n.last};if("after"in n)return{after:n.after,limit:n.first}}},Me=e=>"locally"in e,qe=e=>"optimistically"in e,xe=e=>Me(e)||qe(e),Ke=e=>null==e?void 0:e.hasOwnProperty("cachedAt"),Ne=(e,t=6e4)=>{var n;return Date.now()-(null!==(n=null==e?void 0:e.cachedAt)&&void 0!==n?n:0)<=t},Fe=(e,...t)=>({func:e,args:t}),_e=(e,t=6e4)=>"cache_only"===e?{lifeSpan:1/0}:{lifeSpan:t<Se?Se:t},Be=({func:e,args:t},n,a=_e("cache_then_server"))=>{let s;const{lifeSpan:o}=_e("cache_then_server",a.lifeSpan);if(xe(e)){try{s=qe(e)?e.optimistically(...t):e.locally(...t)}catch(e){null==n||n($e(void 0,{origin:"local",loading:!1,error:e}))}const a=Ke(s)&&Ne(s,o);if(null==n||n($e(s,{origin:"local",loading:!(Me(e)&&a)})),a)return}else null==n||n($e(void 0,{origin:"local",loading:!0}));e(...t).then((e=>{null==n||n($e(e,{origin:"server",loading:!1}))})).catch((e=>{null==n||n($e(void 0,{origin:"server",loading:!1,error:e}))}))};function $e(e,t){return ke(e)||Ke(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 Qe extends Le{constructor(e,t,n){super(e,t,n)}}class Ve extends Le{constructor(e=8e5,t="fatal"){super("Unexpected error",e,t)}}class Je extends Le{constructor(e,t="SDK client is having connection issues"){super(`${t} (${e})`,"disconnected"===e?800211:800210,"error"),this.event=e}}class He extends Le{constructor(e){super(e,800110,"error")}}let ze=null;const Ge=()=>{if(!ze)throw new Le("There is no active client",8e5,"fatal");return ze},Ye=e=>{ze=e},We={user:({userId:e})=>e,file:({fileId:e})=>e,role:({roleId:e})=>e,channel:({channelInternalId:e})=>e,subChannel:({subChannelId:e})=>e,channelUsers:({channelId:e,userId:t})=>`${e}#${t}`,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},Xe=e=>We[e],Ze={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 et(e=(new Date).toISOString()){return new Date(new Date(e).getTime()+1).toISOString()}const tt=e=>{const{log:t,cache:n}=Ge();if(n)return t("cache/api/queryCache",{key:e}),Object.keys(n.data).filter((t=>{const n=Te(t);return Ae(e,n)})).map((e=>n.data[e]))},nt=e=>{const{log:t,cache:n}=Ge();if(!n)return;t("cache/api/pullFromCache",e);const a=Oe(e);return n.data[a]?n.data[a]:void 0},at=(e,t,n={cachedAt:Date.now()})=>{const{log:a,cache:s}=Ge();if(!s)return!1;a("cache/api/pushToCache",{key:e,data:t,options:n}),!(null==n?void 0:n.hasOwnProperty("offline"))&&s.persistIf&&(n.offline=s.persistIf(e,t));const o=Oe(e);return s.data[o]=Object.assign({key:e,data:t},n),!0},st=(e,t,n)=>{const{log:a,cache:s}=Ge();if(!s)return!1;a("cache/api/mergeInCache",{key:e,mutation:t});const o=nt(e);if(!o)return!1;const i="function"==typeof t?t(o.data):Object.assign(Object.assign({},o.data),t);return r=o.data,!("updatedAt"in(c=i)&&"updatedAt"in r&&new Date(c.updatedAt)<new Date(r.updatedAt))&&(at(e,i,n),!0);var r,c},ot=(e,t,n={cachedAt:Date.now()})=>{const{log:a,cache:s}=Ge();if(!s)return!1;a("cache/api/upsertInCache",{key:e,data:t,options:n});return nt(e)?st(e,t,n):at(e,t,n)},it=(e,t=!1)=>{const{log:n,cache:a}=Ge();if(!a)return!1;if(n("cache/api/dropFromCache",{key:e,exact:t}),!t)return Object.keys(a.data).map((e=>Te(e))).filter((t=>Ae(e,t))).map((e=>it(e,!0))).every((e=>e));const s=Oe(e);return s in a.data&&(delete a.data[s],!0)},rt=(e,t,n)=>void 0!==n?e.filter((e=>JSON.stringify(e[t])===JSON.stringify(n))):e,ct=(e,t,n)=>void 0!==n?e.filter((e=>"string"==typeof e[t]&&"string"==typeof n&&String(e[t]).toLowerCase().match(n.toLowerCase()))):e,dt=(e,t,n)=>(null==n?void 0:n.length)?e.filter((e=>Array.isArray(e[t])&&n.some((n=>e[t].includes(n))))):e,lt=(e,t,n)=>"all"===t?e:e.filter((e=>{var a;if("community"===e.type)return!0;const s=Xe("channelUsers")({channelId:e.channelPublicId,userId:n}),o=null===(a=nt(["channelUsers","get",s]))||void 0===a?void 0:a.data;return"member"===t?o&&"none"!==o.membership:!o||"none"===o.membership})),ut=(e,t)=>e.filter((({targetId:e,feedId:n})=>{var a;const s=null===(a=nt(["feed","get",Xe("feed")({targetId:e,feedId:n})]))||void 0===a?void 0:a.data;return s&&s.feedType===t})),ht=(e,t,n)=>"all"===t?e:e.filter((e=>{var a;const s=Xe("communityUsers")({communityId:e.communityId,userId:n}),o=null===(a=nt(["communityUsers","get",s]))||void 0===a?void 0:a.data;return"member"===t?o&&"member"===o.communityMembership:!o||"none"!==o.communityMembership})),mt=(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 s=null===(a=nt(["post","get",n.children[0]]))||void 0===a?void 0:a.data;return(null==t?void 0:t.includes(null==s?void 0:s.dataType))?e:[...e,n]}return e}),[]),gt=(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))}))},pt=()=>{var e;const{userId:t}=Ge(),n=new Set;return(null!==(e=tt(["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},yt=e=>{const t=pt();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)))}))},vt=e=>{const t=pt();return 0===t.size?e:e.filter((e=>!t.has(e.userId)))},ft=({displayName:e},{displayName:t})=>e&&t?e.localeCompare(t):e?-1:1,bt=({name:e},{name:t})=>e&&t?e.localeCompare(t):e?-1:1,It=({createdAt:e},{createdAt:t})=>new Date(e).valueOf()-new Date(t).valueOf(),Ct=({localSortingDate:e},{localSortingDate:t})=>new Date(t).getTime()-new Date(e).getTime(),wt=({createdAt:e},{createdAt:t})=>new Date(t).valueOf()-new Date(e).valueOf(),St=({updatedAt:e=0},{updatedAt:t=0})=>new Date(e).valueOf()-new Date(t).valueOf(),Ot=({updatedAt:e=0},{updatedAt:t=0})=>new Date(t).valueOf()-new Date(e).valueOf(),Tt=({lastActivity:e},{lastActivity:t})=>new Date(t).valueOf()-new Date(e).valueOf(),At=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")},Rt=(e,t,n)=>{const a=new Date(e).valueOf(),s=new Date(t).valueOf();return"firstCreated"===n?a>=s:a<=s};let Pt=null;const Dt=()=>{if(!Pt)throw new Le("Connect client first",8e5,"fatal");return Pt},Ut=e=>{Pt={_id:e._id,userId:e.userId,path:e.path}};let kt,jt=[];const Et=e=>{clearTimeout(kt),jt.push(e),kt=setTimeout((()=>{jt.forEach((e=>e())),jt=[]}),0)},Mt=["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"],qt=(e,t,n,a)=>{const{log:s,emitter:o}=e,i=Date.now();s(`${t}(tmpid: ${i}) > listen`);const r=(...e)=>{s(`${t}(tmpid: ${i}) > trigger`,e);try{a(...e)}catch(e){s(`${t}(tmpid: ${i}) > error`,e)}};return o.on(n,r),()=>{s(`${t}(tmpid: ${i}) > dispose`),o.off(n,r)}},xt=(e,t)=>{const{emitter:n}=Ge();Et((()=>{n.emit(e,t)}))};let Kt,Nt;async function Ft(){var e;const{mqtt:t,emitter:n,token:a}=Ge();if(!t)return;const s=null!==(e=null==a?void 0:a.accessToken)&&void 0!==e?e:"",o=Dt();Kt===s&&Nt===o._id||(Kt=s,Nt=o._id,await t.connect({accessToken:Kt,userId:Nt}),((e,t)=>{Mt.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 _t=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=nt(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),Bt=()=>{var e;const t=Ge();if(!t)throw new Le("Connect client first",8e5,"fatal");const n=null===(e=nt(["user","get",t.userId]))||void 0===e?void 0:e.data;return n?_t(n):null};var $t;e.SubscriptionLevels=void 0,($t=e.SubscriptionLevels||(e.SubscriptionLevels={})).COMMUNITY="community",$t.POST="post",$t.COMMENT="comment",$t.POST_AND_COMMENT="post_and_comment",$t.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}},Qt=e=>e.path.split("/user/")[0],Vt=()=>{const e=Dt();return`${Qt(e)}/membership/${e._id}/+/+`},Jt=()=>{const e=Dt();return`${Qt(e)}/membership/+/${e._id}/+`},Ht=({channelId:e,subChannelId:t})=>{const n=Dt();return`${Qt(n)}/marker/channel/${e}/message/${t}`},zt=()=>Qt(Dt()),Gt=()=>{const e=Dt();return`${Qt(e)}/smartfeed/${e._id}/channels`},Yt=()=>{const e=Dt();return`${Qt(e)}/smartfeed/${e._id}/messagefeeds`},Wt=()=>{const e=Dt();return`${Qt(e)}/smartfeed/${e._id}/messages`},Xt=()=>{const e=Dt();return`${Qt(e)}/videostreaming`};function Zt(e,t){const{mqtt:n}=Ge();return n?(Ft(),n.subscribe(e,t)):()=>null}var en;const tn="object"==typeof globalThis?globalThis:"object"==typeof global?global:window,{process:nn={}}=tn,an="production"===(null===(en=nn.env)||void 0===en?void 0:en.NODE_ENV),sn={EU:"eu",SG:"sg",US:"us"},on={http:"https://apix.{region}.amity.co",upload:"https://upload.{region}.amity.co",mqtt:"wss://sse.{region}.amity.co:443/mqtt"};function rn(e,t){return on[e].replace("{region}",t)}class cn{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 dn;var ln,un=()=>(dn||(dn=new cn),dn);!function(e){e.UserDeleted="User Deleted",e.UserGlobalBanned="User Global Banned",e.TokenExpired="Token Expired"}(ln||(ln={}));let hn=new AbortController;const mn=e=>{switch(e){case ln.UserGlobalBanned:throw new Le(e,400312,"fatal");case ln.UserDeleted:throw new Le(e,400100,"fatal");case ln.TokenExpired:throw xt("tokenExpired","tokenExpired"),new Le(e,800403,"fatal");default:throw new Le("Request Aborted",8e5,"error")}};let gn=0;const pn=e=>{const t={maxSockets:100,maxFreeSockets:10,timeout:6e4,freeSocketTimeout:3e4},n=C.default.create({baseURL:e,httpAgent:new w.default(t),httpsAgent:new o.HttpsAgent(t),signal:hn.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&&(hn.abort(),mn(ln.UserGlobalBanned)),a&&(hn.abort(),mn(ln.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||""),s=null===(t=e.config.method)||void 0===t?void 0:t.toUpperCase(),o={method:s,headers:e.config.headers};return"GET"!==s&&"HEAD"!==s&&(o.body=e.config.data),un().setNetworkActivities(new Request(a,o),{data:e.data,status:e.status,statusText:e.statusText,headers:n}),e}),(e=>{var t,n,a;const{response:s}=e;if(400100===(null==s?void 0:s.data.code)&&xt("tokenTerminated","terminated"),400323===(null===(t=null==s?void 0:s.data)||void 0===t?void 0:t.code))throw function(){const e=Date.now();e-gn<2e3||(gn=e,xt("visitorUsageLimitReached",void 0))}(),new Le("Visitor usage limit exceeded",400323,"error");if((null===(n=null==s?void 0:s.data)||void 0===n?void 0:n.status)&&(e=>{if("success"===e.status)return e.data;if("fail"===e.status)throw new Ve(e.code);if("error"===e.status)throw new Qe(e.message,e.code,"error")})(null==s?void 0:s.data),hn.signal.aborted)throw e;throw new Error(null!==(a=null==s?void 0:s.data)&&void 0!==a?a:e)})),n.defaults.paramsSerializer={encode:e=>encodeURIComponent(e)},n};class yn{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 vn;var fn=()=>(vn||(vn=new yn),vn);const bn=e=>fn().onSessionStateChange(e),In={[e.AmityAutoSubscription.NETWORK]:[zt],[e.AmityAutoSubscription.CHAT]:[Gt,Yt,Wt],[e.AmityAutoSubscription.LIVESTREAM]:[Xt],[e.AmityAutoSubscription.BLOCK]:[Vt,Jt]},Cn=[e.AmityAutoSubscription.CHAT,e.AmityAutoSubscription.NETWORK,e.AmityAutoSubscription.LIVESTREAM,e.AmityAutoSubscription.BLOCK],wn=Object.values(e.AmityAutoSubscription);class Sn{constructor(){this.refCountByFeature=new Map,this.disposers=new Map,this.seed()}seed(){this.refCountByFeature.clear(),Cn.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,In[e].map((e=>Zt(e()))))}unsubscribeTopics(e){var t;(null!==(t=this.disposers.get(e))&&void 0!==t?t:[]).forEach((e=>e())),this.disposers.delete(e)}initialize(){wn.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 wn.map((e=>({feature:e,isActive:this.isActive(e),isSystem:!0,topicCount:In[e].length})))}reset(){wn.forEach((e=>this.unsubscribeTopics(e))),this.disposers.clear(),this.seed()}}let On=null;const Tn=()=>(On||(On=new Sn),On);class An{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 Rn=()=>"undefined"!=typeof window&&window.localStorage?window:{localStorage:new An},Pn=async(e,t)=>"undefined"!=typeof navigator&&"ReactNative"===navigator.product?(await O.default.setItem(e,t),!0):new Promise((n=>{Rn().localStorage.setItem(e,t),n(!0)})),Dn=async e=>{if("undefined"!=typeof navigator&&"ReactNative"===navigator.product){return await O.default.getItem(e)}return new Promise((t=>{t(Rn().localStorage.getItem(e))}))},Un=()=>T.default.v4().toString();let kn=0;if("undefined"!=typeof BroadcastChannel&&"undefined"!=typeof window){const e=Un(),t={},n=new BroadcastChannel("amity_ts_sdk");let a;n.postMessage({type:"startup",tabId:e}),n.onmessage=({data:s})=>{s.tabId!==e&&("startup"===s.type&&n.postMessage({type:"identify",tabId:e,tabIndex:kn}),"identify"===s.type&&void 0!==s.tabIndex&&s.tabId&&(t[s.tabId]=s.tabIndex,a||(a=setTimeout((()=>{const e=Object.values(t).sort();e&&0!==e.length&&(kn=e.reduce(((e,t)=>e<t?e:t+1),0))}),15))))}}const jn=async()=>{var e;const t=`${null!==(e=Ge().prefixDeviceIdKey)&&void 0!==e?e:""}#deviceId`,n=await Dn(t);if(n)return n;const a=`ascWebSdk#${Un()}`;return await Pn(t,a),a},En=()=>{const e=(()=>{var e,t;return(null===(e=nn.versions)||void 0===e?void 0:e.node)?nn.versions.node:navigator?`${navigator.product.toLowerCase()}#${null!==(t=navigator.userAgent)&&void 0!==t?t:"unknown_agent"}`:"unknown_model"})();return{kind:"web",model:e,sdkVersion:he}},Mn=1e3;var qn;!function(e){e[e.IDENTIFIER_REJECTED=2]="IDENTIFIER_REJECTED",e[e.CLIENT_IDENTIFIER_NOT_VALID=133]="CLIENT_IDENTIFIER_NOT_VALID",e[e.BAD_USERNAME_OR_PASSWORD=134]="BAD_USERNAME_OR_PASSWORD",e[e.NOT_AUTHORIZED=135]="NOT_AUTHORIZED"}(qn||(qn={}));const xn=e=>{let t,n="disconnected";const a=new Set,s=e=>{n!==e&&(n=e,a.forEach((t=>{t(e)})))},o=new Map;function i(e,n,a){const s=(t,s)=>{var r;if(t||128===(null===(r=null==s?void 0:s[0])||void 0===r?void 0:r.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 s=setTimeout((()=>{i(e,n+1,a)}),t);o.set(e,{timer:s,callback:a})}else{o.delete(e);const n=t?new Le(t.message,8e5,"error"):new Ve(8e5,"error");console.warn(`Failed to subscribe to topic ${e} after 3 attempts`,n),null==a||a(n)}else o.delete(e),console.log(`Subscribed to topic ${e}`),null==a||a()};t?t.subscribe(e,{qos:0},s):s(new Error("No connection to broker"),[])}return{connect:async function(n){const a=await(async e=>`mqttjs_${await jn()}_${e}_${kn}`)(n.userId);return s("connecting"),t&&(s("disconnecting"),t.removeAllListeners(),t.end(!0)),t=S.default.connect(e,function(e){return Object.assign({clean:!1,clientId:`mqttjs_ + ${Math.random().toString(16).substring(2,10)}`,protocolId:"MQTT",protocolVersion:5,reconnectPeriod:Mn,resubscribe:!0,keepalive:30,properties:{sessionExpiryInterval:4294967295}},e)}({username:n.userId,password:n.accessToken,clientId:a})),t.on("connect",(()=>{t.options.reconnectPeriod=Mn,s("connected"),Tn().initialize()})),t.on("error",(e=>{switch("code"in e?e.code:void 0){case 2:case 133:case 134:case 135:t.end(),s("disconnected")}})),t.on("reconnect",(()=>{s("reconnecting"),t.options.reconnectPeriod=Math.min(2*(t.options.reconnectPeriod||Mn),8e3)})),t.on("close",(()=>{o.forEach((({timer:e})=>clearTimeout(e))),o.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 i(e,0,t),()=>this.unsubscribe(e)},unsubscribe(e){var n;const a=o.get(e);if(void 0!==a){clearTimeout(a.timer),o.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)}}},Kn=async()=>{const e=Ge(),{data:t}=await e.http.get("/api/v3/network-settings/chat");return t},Nn=(e={},t,n=!0)=>{Object.entries(e).forEach((([e,a])=>{const s=Ze[e];if(!s)return;const o=Xe(s);o&&a&&a.forEach((e=>{(n?at:ot)([s,"get",o(e)],e,t)}))}))},Fn=(e,t)=>{const{log:n,cache:a}=Ge(),s=[e,we,t],o={cachedAt:Date.now()};a&&(n("cache/api/pushToTombstone",{cacheKey:s,data:o}),it([e,"get",t],!0),at(s,o))};function _n(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 s=0;for(a=Object.getOwnPropertySymbols(e);s<a.length;s++)t.indexOf(a[s])<0&&Object.prototype.propertyIsEnumerable.call(e,a[s])&&(n[a[s]]=e[a[s]])}return n}const Bn=(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(!Ge().cache)return;return(null===(n=nt(["user","get",e[t]]))||void 0===n?void 0:n.data)||void 0}},e))(e,t,n))))&&void 0!==a?a:e},$n=(e,t,n="userId",a="user")=>{const s=e,o=t,i=s[o],r=_n(s,["symbol"==typeof o?o:o+""]),c=Bn(i,n,a);return Object.assign(Object.assign({},r),{[t]:c})};function Ln(e){return e.map((e=>{var{isMentioned:t}=e,n=_n(e,["isMentioned"]);return Object.assign({hasMentioned:t},n)}))}function Qn(e){return Ln(e)}function Vn(e){return Ln(e)}const Jn=e=>{var t,n;return null!==(n=null===(t=nt(["messagePreviewChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},Hn=e=>new Date(e).getTime(),zn=e=>{var t,n;return null!==(n=null===(t=nt(["messagePreviewSubChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},Gn=e=>{var t;const n=e.messagePreviewId?zn(e.subChannelId):null,a=n?Object.assign(Object.assign({},n),{user:null===(t=nt(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data}):null;return Object.assign(Object.assign({},e),{messagePreview:a})},Yn=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:s,messageFeedId:o,messageId:i,creatorPublicId:r,data:c,dataType:d,isDeleted:l,segment:u,createdAt:h,updatedAt:m}=t;return{messagePreviewId:i,channelId:s,subChannelId:o,data:c,dataType:d,isDeleted:l,segment:u,creatorId:r,createdAt:h,updatedAt:m,subChannelName:null==a?void 0:a.name,subChannelUpdatedAt:null==a?void 0:a.updatedAt}})(t))))&&void 0!==n?n:[]};Nn(a)};function Wn(e,t){return Object.create(Object.getPrototypeOf(e),Object.assign(Object.assign({},Object.getOwnPropertyDescriptors(e)),Object.getOwnPropertyDescriptors(t)))}function Xn(e,t,n){at(["subChannel","get",e],Wn(t,n))}const Zn=(e,t)=>{const{log:n,cache:a}=Ge(),s=[e,we,t];if(!a)return;n("cache/api/isInTombstone",s);const o=nt(s),{lifeSpan:i}=_e("cache_then_server",18e4);if(o&&Ne(o.data,i))throw new Qe("Item not found!",400400,"error")},ea=e=>{var t;const n=["channelUnreadInfo","get",e],a=null===(t=nt(n))||void 0===t?void 0:t.data,s=tt(["subChannelUnreadInfo","get"]);let o=0,i=!1;if(s&&(null==s?void 0:s.length)>0){const t=null==s?void 0:s.filter((({data:t})=>t.channelId===e&&!t.isDeleted));o=t.map((({data:e})=>e.unreadCount)).reduce(((e,t)=>e+t),0),i=t.some((({data:e})=>e.isMentioned))}const r=Object.assign(Object.assign({},null!=a?a:{channelId:e,createdAt:(new Date).toISOString()}),{updatedAt:(new Date).toISOString(),unreadCount:o,isMentioned:i});return at(n,r),r},ta=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,s={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};Nn({subChannelUnreadInfo:[s]}),e.includes(n.entityId)||e.push(n.entityId)}})),e.forEach((e=>{ea(e)}))}},na=async()=>{const e=Ge();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&&Nn({userMarkers:n},{cachedAt:a}),xt("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}},aa=e=>{var t,n;const a=null===(t=nt(["message","get",e]))||void 0===t?void 0:t.data;if(a)return a;const s=tt(["message","get"]);return null===(n=null==s?void 0:s.find((({data:t})=>t.messageId===e)))||void 0===n?void 0:n.data},sa=e=>!0===e&&void 0;function oa(e,t,n){var a,s;if(n)return n.hasMentioned;const o=Ge();if(o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()){const e=null===(a=nt(["subChannelUnreadInfo","get",t]))||void 0===a?void 0:a.data;return!!e&&e.isMentioned}const i={entityId:e,feedId:t,userId:Dt()._id},r=null===(s=nt(["subChannelMarker","get",Xe("subChannelMarker")(i)]))||void 0===s?void 0:s.data;return!!r&&r.hasMentioned}const ia=["broadcast","conversation","community"],ra=({channelType:e})=>ia.includes(e);function ca(e){var{channelId:t,channelPublicId:n,channelType:a,childCount:s,creatorId:o,creatorPublicId:i,lastMessageId:r,lastMessageTimestamp:c,messageFeedId:d,name:l}=e,u=_n(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,s;if(n)return n.unreadCount;const o=Ge();if(o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()){const e=null===(a=nt(["subChannelUnreadInfo","get",t]))||void 0===a?void 0:a.data;return e?e.isDeleted?0:e.unreadCount:0}const i={entityId:e,feedId:t,userId:Dt()._id},r=null===(s=nt(["subChannelMarker","get",Xe("subChannelMarker")(i)]))||void 0===s?void 0:s.data;return r?r.unreadCount:0}(t,d)},get hasMentioned(){return oa(t,d)},get isMentioned(){return oa(t,d)}},u),{channelId:n,creatorId:i,displayName:l,lastActivity:c,latestMessageId:r,messageCount:s,subChannelId:d,isUnreadCountSupport:ra({channelType:a})})}function da(e,t,n){var a;const s=(e=>{var t,n,a;const s=null===(n=null===(t=tt(["message","get"]))||void 0===t?void 0:t.find((({data:t})=>t.messageId===e.messageId)))||void 0===n?void 0:n.data;return s?Object.assign(Object.assign(Object.assign({},s),e),{referenceId:null!==(a=s.referenceId)&&void 0!==a?a:e.referenceId}):e})(e),{channelPublicId:o,childCount:i,creatorPublicId:r,mentionedUsers:c,messageFeedId:d,myReactions:l,reactionCount:u,reactions:h,referenceId:m,segment:g,messageId:p,creatorId:y}=s,v=_n(s,["channelPublicId","childCount","creatorPublicId","mentionedUsers","messageFeedId","myReactions","reactionCount","reactions","referenceId","segment","messageId","creatorId"]);let f;m&&(f=nt(["message","get",m])),f||(f=nt(["message","get",p]));const b=Object.assign(Object.assign({},v),{messageId:p,channelId:o,channelSegment:g,childrenNumber:i,creatorId:r,creatorPrivateId:e.creatorId,reactions:null!=h?h:{},myReactions:l||(null!==(a=null==f?void 0:f.data.myReactions)&&void 0!==a?a:[]),reactionsCount:u,subChannelId:d,uniqueId:f?f.data.uniqueId:p,referenceId:m,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=Ge(),s=aa(e.messageId),o=(null==s?void 0:s.myReactions)||[];Object.assign(e,{myReactions:o});const i=t[0];i&&i.userId===a.userId&&("message.reactionAdded"!==n||o.includes(i.reactionName)||Object.assign(e,{myReactions:[...o,i.reactionName]}),"message.reactionRemoved"===n&&o.includes(i.reactionName)&&Object.assign(e,{myReactions:o.filter((e=>e!==i.reactionName))}))})(b,t,n),b}const la={},ua=async(e,t)=>{const n=e.messages.map((({messageId:e})=>e));if(n.length>0){Nn({messages:(a=e).messages.map((e=>da(e,a.reactions)))});const t=n.join("");la[t]&&clearTimeout(la[t]),la[t]=setTimeout((()=>{try{(async e=>{const t=Ge();t.log("channel/getMessageMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/messages",{params:{messageIds:e}}),{contentMarkers:a,feedMarkers:s,userMarkers:o}=n,i=t.cache&&Date.now();t.cache&&Nn({contentMarkers:a,feedMarkers:s,userMarkers:o},{cachedAt:i}),xt("local.feedMarker.fetched",{feedMarkers:s}),xt("local.messageMarker.fetched",{contentMarkers:a}),xt("local.userMarker.fetched",{userMarkers:o})})(n)}catch(e){}}),2e3)}var a;const{messageFeeds:s}=e,o=_n(e,["messageFeeds"]);return s&&s.length>0&&(null==s||s.forEach((e=>{var t,n;const a=null!==(n=null===(t=nt(["subChannel","get",e.messageFeedId]))||void 0===t?void 0:t.data)&&void 0!==n?n:{},s=_n(ca(e),["unreadCount","isMentioned"]);Xn(e.messageFeedId,a,s)}))),Object.assign(Object.assign({},o),{messages:e.messages.map((n=>da(n,e.reactions,t)))})};function ha(e){var{subChannelId:t,mentionees:n,dataType:a,data:s}=e,o=_n(e,["subChannelId","mentionees","dataType","data"]);return a===B.IMAGE||a===B.FILE?Object.assign({messageFeedId:t,mentionedUsers:n,dataType:a,data:Object.assign({caption:""},s)},o):Object.assign({messageFeedId:t,mentionedUsers:n,dataType:a,data:s},o)}function ma(e){var{sortBy:t,subChannelId:n,includingTags:a,excludingTags:s,includeDeleted:o,aroundMessageId:i,limit:r,type:c}=e,d=_n(e,["sortBy","subChannelId","includingTags","excludingTags","includeDeleted","aroundMessageId","limit","type"]);const l=Object.assign(Object.assign({},d),{messageFeedId:n,isDeleted:sa(o),options:{sortBy:t,limit:r||me,around:i}});return a&&(l.includeTags=a),c&&(l.dataType=c),s&&(l.excludeTags=s),l}function ga(e){return Object.assign(Object.assign({},e),{isGlobalBanned:(null==e?void 0:e.isGlobalBan)||!1})}const pa=["broadcast","conversation","community"],ya=({channelType:e})=>pa.includes(e),va=async e=>{const t=e.messageFeeds.filter(ya).map((({messageFeedId:e})=>e));if(t.length>0){(e=>{Nn({messageFeeds:e.messageFeeds.map((e=>ca(e)))})})(e);try{await(async(e,t={limit:100})=>{const n=Ge();n.log("channel/getSubChannelMarkers",e,t);const{data:a}=await n.http.get("/api/v1/markers/message-feeds",{params:{messageFeedIds:e,options:{token:je(t,"skiplimit")}}}),{paging:s}=a,o=_n(a,["paging"]),{userEntityMarkers:i,userFeedMarkers:r,userMarkers:c,feedMarkers:d}=o;n.isUnreadCountEnabled&&n.getMarkerSyncConsistentMode()&&ta({feedMarkers:d,userFeedMarkers:r});const l=Qn(i),u=Vn(r),h=n.cache&&Date.now();n.cache&&Nn({userEntityMarkers:l,userFeedMarkers:u,userMarkers:c},{cachedAt:h}),xt("local.channelMarker.fetched",{userEntityMarkers:l}),xt("local.subChannelMarker.fetched",{userFeedMarkers:u}),xt("local.userMarker.fetched",{userMarkers:c});const m=Ee(s.next);return{data:u,cachedAt:h,prevPage:Ee(s.previous),nextPage:m}})(t)}catch(e){}}Yn(e);const n=e.messageFeeds.map(ca),a=e.messages.map((e=>da(e))),s=e.users.map(ga);return Object.assign(Object.assign({},e),{messageFeeds:n,messages:a,users:s})};const fa=async e=>{const t=Ge();t.log("channel/getSubChannel",e),Zn("subChannel",e);try{const n=await t.http.get(`/api/v5/message-feeds/${encodeURIComponent(e)}`),a=await va(n.data),s=t.cache&&Date.now();return t.cache&&Nn(a,{cachedAt:s}),xt("local.message-feed.fetched",a),{data:a.messageFeeds[0],cachedAt:s}}catch(t){throw Re(null==t?void 0:t.code)&&Fn("subChannel",e),t}};fa.locally=e=>{const t=Ge();if(t.log("channel/getSubChannel.locally",e),!t.cache)return;const n=nt(["subChannel","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const ba=async e=>{var t;let n=null===(t=nt(["subChannel","get",e]))||void 0===t?void 0:t.data;return n||(n=(await fa(e)).data),n},Ia=async e=>{const t=await(async()=>Ge().getMessagePreviewSetting(!1))(),{channelId:n,messageId:a,creatorId:s,createdAt:o,updatedAt:i,data:r,dataType:c,subChannelId:d,channelSegment:l,isDeleted:u}=e,h=await ba(d);"no-message-preview"!==t?(e=>{var t;const n=null===(t=nt(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;return!n||n.segment<=e.channelSegment||Hn(n.createdAt)<=Hn(e.createdAt)})(e)&&(at(["messagePreviewSubChannel","get",e.subChannelId],{channelId:n,creatorId:s,messagePreviewId:a,createdAt:o,updatedAt:i,subChannelId:d,data:r,dataType:c,segment:l,isDeleted:u,subChannelUpdatedAt:null==h?void 0:h.updatedAt,subChannelName:null==h?void 0:h.displayName}),Xn(e.subChannelId,h,{lastActivity:o,messagePreviewId:a})):Hn(h.lastActivity)<Hn(o)&&Xn(e.subChannelId,h,{lastActivity:o})},Ca=async e=>{var t;const{channelId:n,messageId:a,creatorId:s,createdAt:o,updatedAt:i,data:r,dataType:c,subChannelId:d,channelSegment:l,isDeleted:u}=e,h=null===(t=nt(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await ba(d);at(["messagePreviewSubChannel","get",e.subChannelId],{channelId:n,creatorId:s,messagePreviewId:a,createdAt:o,updatedAt:i,subChannelId:d,data:r,dataType:c,segment:l,isDeleted:u,subChannelUpdatedAt:t.updatedAt,subChannelName:h.subChannelName})}},wa=async e=>{const{channelId:t,messageId:n,creatorId:a,createdAt:s,updatedAt:o,data:i,dataType:r,subChannelId:c,channelSegment:d,isDeleted:l}=e;if((e=>{var t;const n=null===(t=nt(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;return!n||Hn(n.createdAt)<=Hn(e.createdAt)})(e)){const u=await ba(c);at(["messagePreviewChannel","get",e.channelId],{channelId:t,creatorId:a,messagePreviewId:n,createdAt:s,updatedAt:o,subChannelId:c,data:i,dataType:r,segment:d,isDeleted:l,subChannelUpdatedAt:null==u?void 0:u.updatedAt,subChannelName:null==u?void 0:u.displayName})}},Sa=async e=>{var t;const{channelId:n,messageId:a,creatorId:s,createdAt:o,updatedAt:i,data:r,dataType:c,subChannelId:d,channelSegment:l,isDeleted:u}=e,h=null===(t=nt(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await ba(d);at(["messagePreviewChannel","get",e.channelId],{channelId:n,creatorId:s,messagePreviewId:a,createdAt:o,updatedAt:i,subChannelId:d,data:r,dataType:c,segment:l,isDeleted:u,subChannelUpdatedAt:t.updatedAt,subChannelName:h.subChannelName})}},Oa=async e=>{var t,n,a,s;const{channelId:o,subChannelId:i}=e,r=null===(t=nt(["messagePreviewChannel","get",o]))||void 0===t?void 0:t.data;if((null==r?void 0:r.subChannelId)===i){const e=null===(n=nt(["subChannel","get",i]))||void 0===n?void 0:n.data;at(["messagePreviewChannel","get",o],Object.assign(Object.assign({},r),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}const c=null===(a=nt(["messagePreviewSubChannel","get",i]))||void 0===a?void 0:a.data;if(c&&new Date(c.updatedAt).valueOf()>new Date(e.updatedAt).valueOf()){const e=null===(s=nt(["subChannel","get",i]))||void 0===s?void 0:s.data;at(["messagePreviewSubChannel","get",i],Object.assign(Object.assign({},c),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}},Ta=["broadcast","conversation","community"],Aa=({type:e})=>Ta.includes(e);function Ra(e,t={isMessagePreviewUpdated:!0}){var n;let{messagePreviewId:a}=e;const s=null===(n=nt(["messagePreviewChannel","get",e.channelId]))||void 0===n?void 0:n.data;return(null==s?void 0:s.messagePreviewId)&&!t.isMessagePreviewUpdated&&(a=s.messagePreviewId),Object.assign(Object.assign({},e),{defaultSubChannelId:e.channelInternalId,isUnreadCountSupport:Aa(e),messagePreviewId:a})}const Pa=(e,t={isMessagePreviewUpdated:!0})=>{Nn({channels:e.channels.map((e=>Ra(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated})))})},Da=async(e,t={isMessagePreviewUpdated:!0})=>{const n=Ge(),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:s,messageFeedId:o,data:i,dataType:r,isDeleted:c,segment:d,creatorPublicId:l,createdAt:u,updatedAt:h}=t;return{channelId:s,subChannelId:o,data:i,dataType:r,isDeleted:c,segment:d,creatorId:l,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=nt(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;return!n||Hn(n.createdAt)<=Hn(e.createdAt)}));0!==n.length&&Nn({messagePreviewChannel:n})})(e),n.useLegacyUnreadCount)(({currentUserId:e,channels:t,channelUsers:n})=>{var a,s;const o=[];for(let i=0;i<t.length;i+=1)if(Aa(t[i])){const r=["channelUnread","get",t[i].channelId],c=n.find((n=>n.channelId===t[i].channelId&&n.userId===e)),d=null===(a=nt(r))||void 0===a?void 0:a.data,l=Math.max(null!==(s=null==d?void 0:d.lastSegment)&&void 0!==s?s:0,t[i].messageCount);let u=null,h=null,m=0,g=!1;if(c){const e=c.readToSegment,t=c.lastMentionedSegment;u="number"==typeof(null==d?void 0:d.readToSegment)&&("number"!=typeof e||d.readToSegment>e)?d.readToSegment:null!=e?e:null,h="number"==typeof(null==d?void 0:d.lastMentionedSegment)&&("number"!=typeof t||d.lastMentionedSegment>t)?d.lastMentionedSegment:null!=t?t:null;const n=null!=u?u:0;m=Math.max(l-n,0),g="number"==typeof h&&n<h}const p={channelId:t[i].channelId,lastSegment:l,readToSegment:u,lastMentionedSegment:h,unreadCount:m,isMentioned:g,isDeleted:t[i].isDeleted||!1};at(r,p),o.push(p)}o.length>0&&xt("local.channelUnread.updated",o)})({channels:e.channels,channelUsers:e.channelUsers,currentUserId:n.userId});else{const n=e.channels.filter(Aa).map((({channelInternalId:e})=>e));if(n.length>0){Pa(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated});try{await(async e=>{const t=Ge();t.log("channel/getChannelMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/channels",{params:{channelIds:e}}),{userEntityMarkers:a,userMarkers:s}=n,o=Qn(a),i=t.cache&&Date.now();return t.cache&&Nn({userEntityMarkers:o,userMarkers:s},{cachedAt:i}),xt("local.channelMarker.fetched",{userEntityMarkers:o}),xt("local.userMarker.fetched",{userMarkers:s}),{data:o,cachedAt:i}})(n)}catch(e){}}}const s=e.channels.map((e=>Ra(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated}))),o=e.channelUsers.map((e=>{return t=e,Object.assign(Object.assign({},t),{get user(){var e;if(Ge().cache)return(null===(e=nt(["user","get",t.userId]))||void 0===e?void 0:e.data)||void 0}});var t})),i=e.users.map(ga),r=_n(e,["messageFeedsInfo","messagePreviews"]);return Object.assign(Object.assign({},r),{users:i,channels:s,channelUsers:o})},Ua=async e=>{const t=Ge();t.log("channel/getUserMessageFeedMakers",e);const{data:n}=await t.http.get("/api/v1/markers/user-message-feed",{params:{channelIds:e}});return xt("local.userMessageFeedMarker.fetched",{userMessageFeedMarker:n}),n},ka=async e=>{const t=Ge(),n=await Ua(e.channels.map((({channelInternalId:e})=>e))),{feedMarkers:a,userFeedMarkers:s}=n;ta({feedMarkers:a,userFeedMarkers:s}),t.log("channel/prepareUnreadCountInfo",e.channels)},ja=(e,t)=>{var n,a,s,o;const i=Ge();return i.isUnreadCountEnabled&&i.getMarkerSyncConsistentMode()?null!==(a=null===(n=(e=>{var t;return null===(t=nt(["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!==(o=null===(s=(e=>{var t;const n={entityId:e,userId:Dt()._id};return null===(t=nt(["channelMarker","get",Xe("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===s?void 0:s.hasMentioned)&&void 0!==o&&o},Ea=(e,t)=>{var n,a,s,o,i;const r=Ge();return r.isUnreadCountEnabled&&r.getMarkerSyncConsistentMode()?null!==(a=null===(n=(e=>{var t;return null===(t=nt(["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!==(i=null!==(s=null==t?void 0:t.unreadCount)&&void 0!==s?s:null===(o=(e=>{var t;const n={entityId:e,userId:Dt()._id};return null===(t=nt(["channelMarker","get",Xe("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===o?void 0:o.unreadCount)&&void 0!==i?i:0},Ma=e=>{var t;return null===(t=nt(["channelUnread","get",e]))||void 0===t?void 0:t.data},qa=e=>{const t=Ge(),n=_n(e,["messageCount"]);return Wn(n,{get unreadCount(){var e,t;return null!==(t=null===(e=Ma(n.channelId))||void 0===e?void 0:e.unreadCount)&&void 0!==t?t:0},get subChannelsUnreadCount(){return Ea(n)},get isMentioned(){var e,a;return t.useLegacyUnreadCount?null!==(a=null===(e=Ma(n.channelId))||void 0===e?void 0:e.isMentioned)&&void 0!==a&&a:ja(n)}})},xa=e=>Object.assign(Object.assign({},e),{get user(){return(()=>{var t;const n=["user","get",e.userId],a=null===(t=nt(n))||void 0===t?void 0:t.data;return a?_t(a):void 0})()}}),Ka=e=>{const t=Ge();t.log("channel/getMyMembership.locally");const n=nt(["channelUsers","get",`${e}#${t.userId}`]);if(!n)throw new Qe("Item not found!",400400,"error");return{data:n.data,cachedAt:n.cachedAt}};function Na(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(!Na(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=>Na(e[n],t[n])))}const Fa=[];let _a=null;const Ba=e=>{if(0===Fa.length){const e=Ge();_a=qt(e,"onChannelCreated","channel.created",(async e=>{const t=await Da(e);Nn(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==_a||_a())})(e)},$a=[],La=[],Qa=e=>{const t=Ge();if(0===$a.length){const e=async e=>{const t=await Da(e);Nn(t),$a.forEach((e=>e(t.channels[0])))};La.push(qt(t,"onChannelUpdated","channel.updated",e)),La.push(qt(t,"onChannelUpdated","local.channel.updated",(e=>$a.forEach((t=>t(e.channels[0]))))))}return $a.push(e),()=>(e=>{const t=$a.indexOf(e);t>-1&&$a.splice(t,1),0===$a.length&&La.forEach((e=>e()))})(e)},Va=e=>{const t=tt(["subChannelUnreadInfo","get"]);if(t){(null==t?void 0:t.filter((({data:t})=>t.channelId===e))).forEach((({key:e,data:t})=>{at(e,Object.assign(Object.assign({},t),{isDeleted:!0}))}))}},Ja=e=>{var t;const n=["channelUnreadInfo","get",e];(null===(t=nt(n))||void 0===t?void 0:t.data)&&it(n)},Ha=[];let za=null;const Ga=e=>{if(0===Ha.length){const e=Ge(),t=async t=>{const n=await Da(t),a=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,s=e.useLegacyUnreadCount;n.channels.forEach((e=>{if(a)Va(e.channelId),Ja(e.channelId);else if(s){const t=["channelUnread","get",e.channelId],n=nt(t);n&&at(t,Object.assign(Object.assign({},n),{isDeleted:!0}))}})),Nn(n),Ha.forEach((e=>e(n.channels[0])))};za=qt(e,"onChannelDeleted","channel.deleted",t)}return Ha.push(e),()=>(e=>{const t=Ha.indexOf(e);t>-1&&Ha.splice(t,1),0===Ha.length&&(null==za||za())})(e)},Ya=[];let Wa=null;const Xa=e=>{if(0===Ya.length){const e=Ge();Wa=qt(e,"onChannelJoined","channel.joined",(async e=>{const t=await Da(e),{channels:n,channelUsers:a}=t;Nn(t),Ya.forEach((e=>e(n[0],a[0])))}))}return Ya.push(e),()=>(e=>{const t=Ya.indexOf(e);t>-1&&Ya.splice(t,1),0===Ya.length&&(null==Wa||Wa())})(e)},Za=[];let es=null;const ts=e=>{if(0===Za.length){const e=Ge(),t=async t=>{const{userId:n}=Ge(),{channelUsers:a}=t,s=a.some((e=>e.userId===n)),o=await Da(t,{isMessagePreviewUpdated:s}),i=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,r=e.useLegacyUnreadCount;s&&o.channels.forEach((e=>{i?(Va(e.channelId),Ja(e.channelId)):r&&it(["channelUnread","get",e.channelId])}));const{channels:c,channelUsers:d}=o;Nn(o),Za.forEach((e=>e(c[0],d[0])))};es=qt(e,"onChannelLeft","channel.left",t)}return Za.push(e),()=>(e=>{const t=Za.indexOf(e);t>-1&&Za.splice(t,1),0===Za.length&&(null==es||es())})(e)},ns=[];let as=null;const ss=e=>{if(0===ns.length){const e=Ge(),t=async e=>{var t;ot(["channel","get",e.channelId],{isMuted:Date.parse(e.muteTimeout)>Date.now()});const n=null===(t=nt(["channel","get",e.channelId]))||void 0===t?void 0:t.data;n&&ns.forEach((e=>e(n)))};as=qt(e,"onChannelMute","channel.setMuted",t)}return ns.push(e),()=>(e=>{const t=ns.indexOf(e);t>-1&&ns.splice(t,1),0===ns.length&&(null==as||as())})(e)},os=[];let is=null;const rs=e=>{if(0===os.length){const e=Ge();is=qt(e,"onChannelMemberAdded","channel.membersAdded",(async e=>{const t=await Da(e),{channels:n,channelUsers:a}=t;Nn(t),os.forEach((e=>e(n[0],a.find((e=>"member"===e.membership)))))}))}return os.push(e),()=>(e=>{const t=os.indexOf(e);t>-1&&os.splice(t,1),0===os.length&&(null==is||is())})(e)},cs=[];let ds=null;const ls=e=>{if(0===cs.length){const e=Ge();ds=qt(e,"onChannelMemberRemoved","channel.membersRemoved",(async e=>{const t=await Da(e),{channels:n,channelUsers:a}=t;Nn(t),cs.forEach((e=>e(n[0],a[0])))}))}return cs.push(e),()=>(e=>{const t=cs.indexOf(e);t>-1&&cs.splice(t,1),0===cs.length&&(null==ds||ds())})(e)},us=[];let hs=null;const ms=e=>{const t=Ge();return hs=qt(t,"onChannelMemberBanned","channel.banned",(async e=>{const n=await Da(e),{channels:a,channelUsers:s}=n,o=s.some((e=>"banned"===e.membership&&e.userId===t.userId));t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&o&&n.channels.forEach((e=>{Va(e.channelId),Ja(e.channelId)})),Nn(n),us.forEach((e=>e(a[0],s.find((e=>"banned"===e.membership)))))})),us.push(e),()=>(e=>{const t=us.indexOf(e);t>-1&&us.splice(t,1),0===us.length&&(null==hs||hs())})(e)},gs=[];let ps=null;const ys=e=>{if(0===gs.length){const e=Ge();ps=qt(e,"onChannelMemberUnbanned","channel.unbanned",(async e=>{const t=await Da(e),{channels:n,channelUsers:a}=t;Nn(t),gs.forEach((e=>e(n[0],a.find((e=>"none"===e.membership)))))}))}return gs.push(e),()=>(e=>{const t=gs.indexOf(e);t>-1&&gs.splice(t,1),0===gs.length&&(null==ps||ps())})(e)},vs=[];let fs=null;const bs=e=>{if(0===vs.length){const e=Ge();fs=qt(e,"onChannelMemberRoleAdded","local.channel-moderator.role-added",(async e=>{const{channels:t,channelUsers:n}=e;vs.forEach((e=>e(t[0],n.find((e=>"member"===e.membership)))))}))}return vs.push(e),()=>(e=>{const t=vs.indexOf(e);t>-1&&vs.splice(t,1),0===vs.length&&(null==fs||fs())})(e)},Is=[];let Cs=null;const ws=e=>{if(0===Is.length){const e=Ge();Cs=qt(e,"onChannelMemberRoleRemoved","local.channel-moderator.role-removed",(async e=>{const{channels:t,channelUsers:n}=e;Is.forEach((e=>e(t[0],n.find((e=>"member"===e.membership)))))}))}return Is.push(e),()=>(e=>{const t=Is.indexOf(e);t>-1&&Is.splice(t,1),0===Is.length&&(null==Cs||Cs())})(e)},Ss=e=>{const t=Ge();return qt(t,"onChannelArchived","local.channel.archived",(async t=>{e(t)}))},Os=e=>{const t=Ge();return qt(t,"onChannelUnarchived","local.channel.unarchived",(async t=>{e(t)}))},Ts=[];let As=null;const Rs=e=>{if(0===Ts.length){const e=Ge(),t=async e=>{var t,n,a;e.userIds.forEach((t=>ot(["channelUsers","get",`${e.channelId}#${t}`],{isMuted:Date.parse(e.muteTimeout)>Date.now()})));const s=null===(n=null===(t=tt(["channel","get"]))||void 0===t?void 0:t.find((({data:t})=>t.channelPublicId===e.channelId)))||void 0===n?void 0:n.data,o=null===(a=nt(["channelUsers","get",`${e.channelId}#${e.userIds[0]}`]))||void 0===a?void 0:a.data;s&&o&&Ts.forEach((e=>e(s,o)))};As=qt(e,"onChannelUserMute","channel.setMutedUsers",t)}return Ts.push(e),()=>(e=>{const t=Ts.indexOf(e);t>-1&&Ts.splice(t,1),0===Ts.length&&(null==As||As())})(e)},Ps=e=>{var t;let n=[];if(["conversation","community"].includes(e.type)){const a=tt(["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})=>xa(e))))}return Wn(e,{markAsRead:()=>(async e=>{const t=Ge();t.log("channel/markAsRead",e);const{data:n}=await t.http.put(`/api/v1/markers/channels/${e}/mark-read`),{userMarkers:a,userEntityMarkers:s,userFeedMarkers:o}=n,i=_n(n,["userMarkers","userEntityMarkers","userFeedMarkers"]),r=t.cache&&Date.now(),c=Qn(s),d=Vn(o);return t.cache&&Nn(Object.assign({userMarkers:a,userEntityMarkers:c,userFeedMarkers:d},i),{cachedAt:r}),xt("local.channelMarker.updated",{userEntityMarkers:c}),xt("local.subChannelMarker.updated",{userFeedMarkers:d}),!0})(e.channelInternalId),previewMembers:n,myMembership:t=>((e,t)=>{const{_id:n}=Dt();if(!n)throw new Le("The _id has not been defined in ActiveUser",8e5,"error");const{log:a,cache:s}=Ge();s||console.log("This observable object need the cache data!"),a(`liveMymembership(tmpid: ${Date.now()}) > listen`);const o=[];let i=!1;const r=e=>{t(Object.assign(Object.assign({},e),{data:e.data?xa(e.data):e.data}))},c=(t,n)=>{const{data:a}=Ka(e);Na(void 0,a)||r({loading:!1,data:a})};return o.push(ms(c)),o.push(ys(c)),o.push(Rs(c)),(()=>{const t=Fe((async()=>Ka(e)));Be(t,(({error:e,data:t,loading:n,origin:a,cachedAt:s})=>{s===fe?(r({data:t,origin:a,loading:!1,error:new Qe(ve,800800,"error")}),i=!0,o.forEach((e=>e()))):i||r({loading:n,data:t,origin:a,error:e}),e&&o.forEach((e=>e()))}))})(),()=>{o.forEach((e=>e()))}})(e.channelId,t),get avatar(){var t;if(!e.avatarFileId)return;return null===(t=nt(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}})},Ds=e=>Ps(qa((e=>{var t;const n=e.messagePreviewId?Jn(e.channelId):null,a=null===(t=nt(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data,s=n?Object.assign(Object.assign({},n),{user:a?_t(a):void 0}):null;return Object.assign(Object.assign({},e),{messagePreview:s})})(e))),Us=async e=>{const t=Ge();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=>{Re(null==t?void 0:t.code)&&Fn("channel",e)})),t}const s=await Da(a);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await ka(a);const o=t.cache&&Date.now();return t.cache&&Nn(s,{cachedAt:o}),xt("local.channel.fetched",s.channels),{data:s.channels.map((e=>Ds(e))),cachedAt:o}};Us.locally=e=>{var t,n;const a=Ge();if(a.log("channel/getChannelByIds.locally",e),!a.cache)return;const s=null===(t=tt(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!s||(null==s?void 0:s.length)<e.length)return;const o=s.map((({data:e})=>e)),i=null===(n=s.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0];return{data:o.map((e=>Ds(e))),cachedAt:i.cachedAt}};const ks=(e,t)=>{const n=setInterval(e,t);return()=>clearInterval(n)};let js=!1;const Es={},Ms=async()=>{const e=Object.entries(Es).filter((([,e])=>e)).map((([e])=>e));return 0!==e.length&&(async e=>{const t=Ge();t.log("subChannel/readingAPI",e);const{data:n}=await t.http.post("/api/v1/markers/message-feeds/reading",{messageFeedIds:e}),{userEntityMarkers:a,userFeedMarkers:s,feedMarkers:o,userMarkers:i}=n,r=Qn(a),c=Vn(s),d=t.cache&&Date.now();return t.cache&&Nn({userEntityMarkers:r,userFeedMarkers:c,feedMarkers:o,userMarkers:i},{cachedAt:d}),xt("local.feedMarker.fetched",{feedMarkers:o}),xt("local.channelMarker.fetched",{userEntityMarkers:r}),xt("local.subChannelMarker.fetched",{userFeedMarkers:c}),xt("local.userMarker.fetched",{userMarkers:i}),!0})(e)},qs=()=>{js=!1},xs=()=>(js=!0,bn((e=>{"notLoggedIn"===e&&qs()})),()=>{qs()});ks((async()=>{js&&await Ms()}),3e4);const Ks=async e=>{const t=Ge();t.log("channel/getSubChannels",e);const n=await t.http.get("/api/v5/message-feeds/list",{params:{messageFeedIds:e.map(encodeURIComponent)}}),a=await va(n.data),s=t.cache&&Date.now();return t.cache&&Nn(a,{cachedAt:s}),xt("local.message-feed.fetched",a),{data:a.messageFeeds,cachedAt:s}};Ks.locally=e=>{var t;const n=Ge();if(n.log("channel/getSubChannels.locally",e),!n.cache)return;const a=e.map((e=>nt(["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 Ns=async(e=!0)=>{var t;const n=null===(t=nt(["MessagePreviewSetting"]))||void 0===t?void 0:t.data;if(!e&&n)return n;const a=await Kn();var s;return(s=a).messagePreview.enabled?s.messagePreview.isIncludeDeleted?"message-preview-include-deleted":"message-preview-not-include-deleted":"no-message-preview"},Fs=async()=>{var e;const t=await Ns();if(t===(null===(e=nt(["MessagePreviewSetting"]))||void 0===e?void 0:e.data))return;at(["MessagePreviewSetting"],t);const n=[],a=[];if("no-message-preview"===t){const e=tt(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{it(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=tt(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{(null==t?void 0:t.isDeleted)&&(it(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&a.push(t.subChannelId))})),0!==n.length&&await Us(n),0!==a.length&&await Ks(a)}},_s=async()=>{const e=Ge(),{data:t}=await e.http.get("/api/v3/network-settings/social");return t.socialNetworkSetting},Bs=async()=>{const e=Ge(),{data:t}=await e.http.get("/api/v3/network-settings/users");return t},$s=async()=>{const e=Ge(),{data:t}=await e.http.get("/api/v3/network-settings/product");return t},Ls=async()=>{var e,t;const n=Ge(),{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}}},Qs=(e,t)=>{var n;const a=null===(n=nt(["user","get",e]))||void 0===n?void 0:n.data;return!!a&&a.permissions.some((e=>e===t))},Vs=e=>{const{userId:t}=Ge();return{currentUser:()=>Qs(t,e),community:n=>((e,t,n)=>{var a;if(!e)return!1;const s=null===(a=nt(["communityUsers","get",`${n}#${e}`]))||void 0===a?void 0:a.data;return!!s&&(!!s.permissions.some((e=>e===t))||Qs(e,t))})(t,e,n),channel:n=>((e,t,n)=>{var a;if(!e)return!1;const s=null===(a=nt(["channelUsers","get",`${n}#${e}`]))||void 0===a?void 0:a.data;return!!s&&(!!s.permissions.some((e=>e===t))||Qs(e,t))})(t,e,n)}},Js=async e=>{const t=Ge();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},Hs=async e=>{const t=Ge();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},zs=async()=>{const e=Ge(),{data:t}=await e.http.get("/api/v3/network-settings/feed-setting");return Object.fromEntries(t.feedSettings.map((({feedType:e,contentSettings:t})=>[e,t])))},Gs={notLoggedIn:["establishing"],terminated:["establishing"],establishing:["notLoggedIn","established"],established:["notLoggedIn","terminated","tokenExpired","establishing"],tokenExpired:["establishing"]},Ys=(e,t)=>{const n=Ge();n.log("client/api/setSessionState",e,t);const{sessionState:a}=n;if(a===e)return!1;if(!((e,t)=>Gs[e].includes(t))(a,e))throw new Le(`Session state cannot change from ${a} to ${e}`,8e5,"error");return n.sessionState=e,fn().setSessionState(e,t),!0};function Ws(e){return{users:e.users.map(ga),files:e.files}}const Xs=async e=>{const t=Ge();Ys("establishing");const{accessToken:n,users:a,expiresAt:s,issuedAt:o,userType:i,files:r}=await(async({params:e,options:t})=>{const n=Ge();n.log("client/api/getToken",e);const a=En(),{data:s}=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 s})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.upload.defaults.headers.common.Authorization=`Bearer ${n}`,t.upload.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:o,expiresAt:s},Ys("established"),Nn(Ws({users:a,files:r})),{accessToken:n,users:a,userType:i}},Zs=async e=>{const t=Ge();Ys("establishing");const{accessToken:n,users:a,expiresAt:s,issuedAt:o,userType:i,files:r}=await(async({params:e,options:t})=>{const n=Ge();n.log("client/api/getVisitorToken",e);const a=En(),{data:s}=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 s})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:o,expiresAt:s},Ys("established"),Nn(Ws({users:a,files:r})),{accessToken:n,users:a,userType:i}},eo=async()=>{var e;const t=Ge();return t.log("client/api/disconnectClient"),t.mqtt&&t.mqtt.connected&&t.mqtt.disconnect(),"established"===t.sessionState&&Ys("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},to=e=>{const t=Ge();Ys("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,eo()};let no=null;const ao=e=>{no=e},so=({user:e,userType:t})=>{Ut(e),ao(t)},oo=(e,t)=>{const n=Ge();return qt(n,e,e,(e=>{const a=Ws(e);n.cache&&Nn(a),t(a.users[0])}))},io=e=>oo("user.deleted",e),ro=["analytic","normal-priority"],co=["analytic","high-priority"],lo=async e=>{const t=Ge(),n={activities:e};await t.http.post("/api/v1/analytics/activities",n)};class uo{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=nt(ro);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await lo(t),it(ro)}catch(e){this.stop(),it(ro)}}async syncHighPriorityCapturedEvent(){try{const e=nt(co);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await lo(t),it(co)}catch(e){this.stop(),it(co)}}}class ho{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,s=n?this._recentHighPriorityViewed[e]:this._recentViewed[e];if(!s)return!0;return!(a.getTime()-s.getTime()<t)}markAs({uniqueId:e,contentId:t,contentType:n,activityType:a,metadata:s}){if(!this.isAbleToEnqueue({uniqueId:e,expireTime:this._expireTime}))return;const o=new Date,i={event:[]},r=nt(ro);(null==r?void 0:r.data)&&(i.event=r.data.event),i.event.length>=this._poolLimit&&i.event.shift();const c={contentId:t,contentType:n,activityType:a,timestamp:o.toISOString()};s&&(c.metadata=s),i.event.push(c),ot(ro,i),this._recentViewed[e]=o}markPostAsViewed(e){this.markAs({uniqueId:`post.${e}`,contentId:e,contentType:"post",activityType:"view"})}markPostAsMeaningfullyViewed(e,t){var n;const a=null===(n=nt(["feedMetadata","get",e]))||void 0===n?void 0:n.data,s={};void 0!==t&&(s.feedRenderPosition=t),a&&(s.feedSnapshotPosition=a.feedSnapshotPosition,s.feedInjectionType=a.feedInjectionType,s.feedRelevanceScore=a.feedRelevanceScore,s.feedPopularityScore=a.feedPopularityScore,s.feedFreshnessScore=a.feedFreshnessScore,s.feedAffinityScore=a.feedAffinityScore,s.feedFinalScore=a.feedFinalScore,s.feedMmrPenalty=a.feedMmrPenalty),this.markAs({uniqueId:`post.${e}.meaningfulView`,contentId:e,contentType:"post",activityType:"meaningfulView",metadata:Object.keys(s).length>0?s: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 s={event:[]},o=nt(co);if((null==o?void 0:o.data)&&(s.event=o.data.event),s.event.length>=this._poolLimit&&s.event.shift(),s.event.push({contentId:e.storyId,contentType:"story",activityType:t,timestamp:n.toISOString()}),ot(co,s),this._recentHighPriorityViewed[e.storyId]=n,"linkClicked"===t)return;at(["story-seen","get",e.storyId],(new Date).toISOString());const i=nt(["story-last-seen",e.targetId]);(null==i?void 0:i.data)?new Date(i.data).getTime()<new Date(e.expiresAt).getTime()&&at(["story-last-seen",e.targetId],e.expiresAt):at(["story-last-seen",e.targetId],e.expiresAt),this._bufferNewSeenStoryReferenceIds.push(e.referenceId),this._throttleStoryTimer||(this._throttleStoryTimer=setTimeout((()=>{clearTimeout(this._throttleStoryTimer),xt("local.story.reload",{referenceIds:this._bufferNewSeenStoryReferenceIds}),this._bufferNewSeenStoryReferenceIds=[]}),300))}resetAllBuckets(){this._recentViewed={},this._recentHighPriorityViewed={},it(ro),it(co)}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 s={location:t,sourceType:n,sourceId:a},o="linkClicked";this.markAs({uniqueId:`${e.productId}.linkClicked.${t}`,contentId:e.productId,contentType:"product",activityType:o,metadata:s})}markProductAsViewed(e,t,n,a){const s={location:t,sourceType:n,sourceId:a},o="view";this.markAs({uniqueId:`${e.productId}.view.${t}`,contentId:e.productId,contentType:"product",activityType:o,metadata:s})}}class mo{constructor(){this._client=Ge(),this._eventCapturer=new ho,this._eventSyncer=new uo}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 go;var po=()=>(go||(go=new mo),go),yo=()=>{const e=po();return e.established(),bn((t=>{"established"===t?e.established():e.handleTokenExpired()})),()=>{e.destroy()}};class vo{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=Ge(),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=tt(["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=nt(["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=Ge();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],s=null===(t=nt(a))||void 0===t?void 0:t.data;at(a,Object.assign(Object.assign({},s),{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],s=null===(n=nt(a))||void 0===n?void 0:n.data;s&&("number"!=typeof s.readToSegment||t>s.readToSegment)&&(s.readToSegment=t,s.unreadCount=Math.max(s.lastSegment-t,0),at(a,s),xt("local.channelUnread.updated",[s])),this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const a=null===(n=nt(["readReceipt",e]))||void 0===n?void 0:n.data;if(a){if(a.latestSegment<t)at(["readReceipt",e],Object.assign(Object.assign({},a),{latestSegment:t}));else if(a.latestSyncSegment>=t)return}else{at(["readReceipt",e],{channelId:e,latestSegment:t,latestSyncSegment:0})}let s=this.getSyncJob(e);null===s||"syncing"===s.syncState?(s={channelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(s)):s.segment<t&&(s.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 fo=null;var bo=()=>(fo||(fo=new vo),fo),Io=()=>{const e=bo();return e.startSyncReadReceipt(),bn((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};class Co{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=Ge(),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=tt(["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=nt(["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:s}=n,o=await(async({subChannelId:e,readToSegment:t})=>{const n=Ge();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:s});if(o){this.removeSynedReceipt(e.subChannelId,e.segment);const n=null===(t=nt(["legacyReadReceipt",a]))||void 0===t?void 0:t.data;at(["legacyReadReceipt",a],Object.assign(Object.assign({},n),{latestSyncSegment:s}))}else o||(n.retryCount>this.MAX_RETRY?this.removeJobFromQueue(n):(n.retryCount+=1,n.syncState="create"))}removeSynedReceipt(e,t){this.jobQueue.forEach((n=>{n.subChannelId===e&&n.segment<=t&&this.removeJobFromQueue(n)}))}startObservingReadReceiptQueue(){this.client.isUnreadCountEnabled&&(this.isActive=!0,this.startSyncReadReceipt())}stopObservingReadReceiptQueue(){this.isActive=!1;this.jobQueue.map((e=>"syncing"===e.syncState?Object.assign(Object.assign({},e),{syncState:"create"}):e)),this.timer&&clearInterval(this.timer)}onSessionEstablished(){this.startObservingReadReceiptQueue()}onSessionDestroyed(){this.stopObservingReadReceiptQueue(),this.jobQueue=[]}onTokenExpired(){this.stopObservingReadReceiptQueue()}onNetworkOffline(){this.stopObservingReadReceiptQueue()}onNetworkOnline(){this.startObservingReadReceiptQueue()}markRead(e,t){var n;const a=["subChannelUnreadInfo","get",e],s=null===(n=nt(a))||void 0===n?void 0:n.data;if(s&&t>s.readToSegment){s.readToSegment=t,s.unreadCount=Math.max(s.lastSegment-t,0);const e=ea(s.channelId);xt("local.channelUnreadInfo.updated",e),at(a,s),xt("local.subChannelUnread.updated",s)}this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const a=null===(n=nt(["legacyReadReceipt",e]))||void 0===n?void 0:n.data;if(a){if(a.latestSegment<t)at(["legacyReadReceipt",e],Object.assign(Object.assign({},a),{latestSegment:t}));else if(a.latestSyncSegment>=t)return}else{at(["legacyReadReceipt",e],{subChannelId:e,latestSegment:t,latestSyncSegment:0})}let s=this.getSyncJob(e);null===s||"syncing"===s.syncState?(s={subChannelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(s)):s.segment<t&&(s.segment=t)}getSyncJob(e){return this.jobQueue.find((t=>t.subChannelId===e))||null}enqueueJob(e){this.jobQueue.length<this.JOB_QUEUE_SIZE||this.jobQueue.shift(),this.jobQueue.push(e)}removeJobFromQueue(e){const t=this.jobQueue.indexOf(e);t>-1&&this.jobQueue.splice(t,1)}}let wo=null;var So=()=>(wo||(wo=new Co),wo),Oo=()=>{const e=So();return e.startSyncReadReceipt(),bn((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};const To=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")},Ao=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")},Ro=async e=>{const t=Ge();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=>{Re(null==t?void 0:t.code)&&Fn("channel",e)})),t}const s=await Da(a);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await ka(a);const o=t.cache&&Date.now();return t.cache&&Nn(s,{cachedAt:o}),xt("local.channel.fetched",s.channels),{data:s.channels,cachedAt:o}};Ro.locally=e=>{var t,n;const a=Ge();if(a.log("channel/getChannelByIds.locally",e),!a.cache)return;const s=null===(t=tt(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!s||(null==s?void 0:s.length)<e.length)return;return{data:s.map((({data:e})=>e)),cachedAt:(null===(n=s.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0]).cachedAt}};class Po{constructor(){this.TIMER_INTERVAL_MS=be,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(To((()=>{this.isConnected=!0}))),this.connectionListener.push(Ao((()=>{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 Ro(e);const s=null!==(a=null===(n=null===(t=tt(["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:[];xt("local.channel.resolved",s)})(e),t.length>0&&(async e=>{const t=await Ua(e),{feedMarkers:n,userFeedMarkers:a}=t;ta({feedMarkers:n,userFeedMarkers:a}),xt("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 Do=null;var Uo=()=>(Do||(Do=new Po),Do),ko=()=>{const e=Uo();return e.startResolver(),bn((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};class jo{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(To((()=>{this.isConnected=!0}))),this.connectionListener.push(Ao((()=>{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,s=_n(t,["roomId","streamId"]),o=a?"liveStream":"room",i=null!=a?a:n;return e[i]||(e[i]={referenceType:o,reactions:[]}),e[i].reactions.push(s),e}),{});Object.entries(t).forEach((([t,n])=>{(async({reactions:e,liveStreamId:t,roomId:n})=>{const a=Ge();a.log("live_reaction/addReaction",e);const{data:s}=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 Eo;var Mo=()=>(Eo||(Eo=new jo),Eo);function qo(e){const{users:t,follows:n}=e,a=_n(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 xo{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=Ge(),{data:t}=await e.http.get("/api/v4/me/user-blocks",{params:{options:{limit:100},isDeleted:!1}}),n=e.cache&&Date.now(),a=qo(t);e.cache&&Nn(a,{cachedAt:n}),this.lastFetchedAt=Date.now()}getCachedUsers(){var e;const t=Ge();if(!t.cache)return[];const{userId:n}=t;return(null!==(e=tt(["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=nt(["user","get",e.to]))||void 0===t?void 0:t.data})).filter((e=>null!=e&&!0!==e.isDeleted)).slice(0,100).map(_t)}}let Ko=null;var No=()=>(Ko||(Ko=new xo),Ko);function Fo(e){const{users:t,follows:n}=e,a=_n(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 _o{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=Ge(),{data:t}=await e.http.get("/api/v4/me/blockers",{params:{options:{limit:100},isDeleted:!1}}),n=e.cache&&Date.now(),a=Fo(t);e.cache&&Nn(a,{cachedAt:n}),this.lastFetchedAt=Date.now()}getCachedUsers(){var e;const t=Ge();if(!t.cache)return[];const{userId:n}=t;return(null!==(e=tt(["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=nt(["user","get",e.from]))||void 0===t?void 0:t.data})).filter((e=>null!=e&&!0!==e.isDeleted)).slice(0,100).map(_t)}}let Bo=null;var $o=()=>(Bo||(Bo=new _o),Bo);function Lo(e){const{users:t,follows:n}=e,a=_n(e,["users","follows"]);return Object.assign(Object.assign({},a),{follows:n,users:t.map(ga)})}function Qo(e){const{users:t,follows:n}=e,a=_n(e,["users","follows"]);return Object.assign(Object.assign({},a),{follows:n,users:t.map(ga)})}function Vo(e){const{follows:t}=e,n=_n(e,["follows"]);return Object.assign(Object.assign({},n),{follows:t})}const Jo=(e,t)=>{const n=Ge();return qt(n,e,e,(e=>{const a=Lo(e);n.cache&&Nn(a),t(a.follows[0])}))},Ho=e=>Jo("user.didBlock",e),zo=e=>Jo("user.didUnblock",e);class Go{constructor(e,t){this.networkId=e,this.userId=t}static current(){try{const e=Bt();if(!e)return null;const t=Qt(e),{userId:n}=e;return t&&n?new Go(t,n):null}catch(e){return null}}static isExpired(e){return Date.now()>=e}static clearOnLogout(){return bn((e=>{var t;"terminated"===e&&(null===(t=Go.current())||void 0===t||t.clear())}))}get key(){return`amity:forYouFeed:cursor:${this.networkId}:${this.userId}`}async get(){const e=await Dn(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 Pn(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 Pn(this.key,"")}}const Yo=["disconnected","error","connect_error","reconnect_error","reconnect_failed"],Wo=e=>{const t=Ge(),n=Yo.map((n=>qt(t,`client/onConnectionError(${n})`,n,(t=>{const a=(null==t?void 0:t.code)?new Le(t.message,t.code,"fatal"):new Je(n);e(a)}))));return()=>{n.forEach((e=>e()))}},Xo=e=>{const t=Ge();return qt(t,"client/onConnectionError(user.didGlobalBan)","user.didGlobalBan",e)},Zo=e=>{const t=Ge();return qt(t,"client/onTokenExpired","tokenExpired",e)},ei=e=>{const t=Ge();return qt(t,"client/onTokenTerminated","tokenTerminated",e)},ti=e=>{const t=Xe("channelMarker")({userId:Dt()._id,entityId:e.channelId});it(["channelMarker","get",t],!0)},ni=e=>{const t=Ge(),n=[];return n.push(Xo((t=>{to("globalBan"),n.forEach((e=>e())),e()})),ei((t=>{to(),n.forEach((e=>e())),e()})),io((a=>{a.userId===t.userId&&(to("userDeleted"),n.forEach((e=>e())),e())})),Zo((e=>{fn().setSessionState(e),eo(),n.forEach((e=>e()))})),Ga(ti),ms(ti),xs(),yo(),ko(),(()=>{const e=Mo();return e.startReactionsSync(),bn((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=No();return bn((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=$o();return bn((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})(),(()=>{const e=[Ho((()=>{})),zo((()=>{}))];return()=>e.forEach((e=>e()))})(),bn((e=>{"established"!==e&&Tn().reset()})),Go.clearOnLogout()),t.useLegacyUnreadCount?n.push(Io()):n.push(Oo()),n};let ai=[];const si=async(e,t,n)=>{const a=Ge();let s;a.log("client/api/connectClient",Object.assign({apiKey:a.apiKey,sessionState:a.sessionState},e)),a.userId&&a.userId!==e.userId&&(await eo(),ai.forEach((e=>e())),ai=[]);const o=await jn();try{const{users:n,userType:i}=await Xs({params:Object.assign(Object.assign({},e),{displayName:null==e?void 0:e.displayName,deviceId:(null==e?void 0:e.deviceId)||o}),options:{setAccessTokenCookie:!0}}),r=n.find((t=>t.userId===e.userId));if(null==r)throw new Le(`${e.userId} has not been founded`,8e5,"error");if(r.isDeleted)return to("userDeleted"),!1;if(r.isGlobalBan)return to("globalBan"),!1;a.userId=r.userId,a.sessionHandler=t,a.loginType="userId",s=a.accessTokenExpiryWatcher(),so({user:r,userType:i})}catch(e){throw fn().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await Ft()}(),await Fs(),0===ai.length&&(ai=ni(s)),!0},oi=[],ii=async e=>{const t=Ge();let n;t.log("client/api/connectClient",Object.assign({apiKey:t.apiKey,sessionState:t.sessionState},e));const a=await jn();let s;try{const{users:o,userType:i}=await Zs({params:Object.assign(Object.assign({},e),{deviceId:a}),options:{setAccessTokenCookie:!0}});[s]=o,t.userId=s.userId,t.sessionHandler=e.sessionHandler,t.loginType="userId",n=t.accessTokenExpiryWatcher(),so({user:s,userType:i})}catch(e){throw fn().setSessionState("notLoggedIn"),e}return await Fs(),0===oi.length&&oi.push(ei((e=>{to(),oi.forEach((e=>e())),n()})),Zo((e=>{fn().setSessionState(e),eo(),oi.forEach((e=>e()))}))),!0},ri=()=>{let e,t=!1;const n=Ge();n.log("initiating access token renewal");const a=async a=>{const{userId:s,displayName:o}=Dt(),i={userId:s,displayName:o,authToken:a,deviceId:await jn()};"tokenExpired"===n.sessionState&&n.sessionHandler?await si(i,n.sessionHandler):await Xs({params:i,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(ri())}),Ie)},renewWithAuthSignature:a=>{t?console.log("'renew' method can be called only once per renewal instance"):(async({authSignature:a,authSignatureExpiresAt:s})=>{const o=await jn();"tokenExpired"===n.sessionState&&n.sessionHandler?await ii({sessionHandler:n.sessionHandler}):await Zs({params:{authSignature:a,authSignatureExpiresAt:s,deviceId:o},options:{setAccessTokenCookie:!0}}),t=!0,e&&clearTimeout(e)})(a)},unableToRetrieveAuthSignature:()=>{e=setTimeout((()=>{var e;null===(e=n.sessionHandler)||void 0===e||e.sessionWillRenewAccessToken(ri())}),Ie)}}},ci=async({token:e,userId:t})=>{const n=Ge();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}`}}),s=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,s},di=e=>{var t;const n=Ge(),a=A.default(e);return(null===(t=null==a?void 0:a.user)||void 0===t?void 0:t.publicUserId)===n.userId};let li=[];const ui=async e=>{var t,n;const a=Ge();let s,o;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{o=A.default(e)}catch(e){throw new Le("Invalid access token format",400100,"error")}const i=(null===(t=null==o?void 0:o.user)||void 0===t?void 0:t.publicUserId)||(null===(n=null==o?void 0:o.user)||void 0===n?void 0:n.userId);if(!i)throw new Le("Access token does not contain userId",400100,"error");if(a.userId){di(e)||await eo()}try{Ys("establishing");const t={accessToken:e,issuedAt:o.iat?new Date(1e3*o.iat).toISOString():(new Date).toISOString(),expiresAt:new Date(1e3*o.exp).toISOString()},n=await ci({token:t,userId:i});if(null==n)throw Ys("notLoggedIn"),new Le(`User ${i} has not been found`,8e5,"error");if(n.isDeleted)throw Ys("notLoggedIn"),new Le(`User ${i} has been deleted`,8e5,"error");if(n.isGlobalBanned)throw Ys("notLoggedIn"),new Le(`User ${i} is globally banned`,8e5,"error");a.userId=n.userId,a.loginType="accessToken",Ut(n),s=a.accessTokenExpiryWatcher(),Ys("established")}catch(e){if(Ys("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 Ft()}(),await Fs(),0===li.length&&(li=ni(s)),!0},hi=async e=>{var t,n;const a=Ge();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 s;try{s=A.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){di(e)||await eo()}const i={accessToken:e,issuedAt:s.iat?new Date(1e3*s.iat).toISOString():(new Date).toISOString(),expiresAt:new Date(1e3*s.exp).toISOString()};"tokenExpired"===a.sessionState&&a.sessionHandler?await ui(e):await ci({token:i,userId:o})},mi=async({useScheduledTask:e=!1})=>{const t=Ge();if(t.userId&&t.accessTokenHandler)try{const n=await t.accessTokenHandler.onTokenRenew(t.userId);e?Et((()=>hi(n))):hi(n)}catch(e){t.log("Proactive token renewal failed, will retry when token expires",e)}},gi=3e5,pi=()=>{const e=setInterval((async()=>{const e=Ge(),{sessionHandler:t,accessTokenHandler:n,loginType:a}=e;if(!e.token||!e.userId)return;const{issuedAt:s,expiresAt:o}=e.token;if((e=>Date.now()>Date.parse(e)-gi)(o))return xt("tokenExpired","tokenExpired"),void("accessToken"===a&&n?await mi({useScheduledTask:!1}):"userId"===a&&t&&Et((()=>t.sessionWillRenewAccessToken(ri()))));(e=>{const{expiresAt:t,issuedAt:n}=e,a=Date.parse(t),s=Date.parse(n),o=Date.now();return o>s+.8*(a-s-gi)&&o<a})({expiresAt:o,issuedAt:s})&&("accessToken"===a&&n?await mi({useScheduledTask:!1}):"userId"===a&&t&&t.sessionWillRenewAccessToken(ri()))}),Ie);return()=>clearInterval(e)},yi=e=>{if(Ge().useLegacyUnreadCount){bo().markRead(e.channelId,e.channelSegment)}else{So().markRead(e.subChannelId,e.channelSegment)}},vi=e=>{const t=Ge(),n=Dt(),a=[qt(t,"message/onMessageCreated","message.created",(async a=>{const s=await ua(a);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&a.messages.forEach((e=>{(e=>{var t;const n=Ge(),a=["subChannelUnreadInfo","get",e.messageFeedId],s=null===(t=nt(a))||void 0===t?void 0:t.data;if(!s)return;const o=s.lastSegment<e.segment?e.segment:s.lastSegment,i=o-s.readToSegment;let{lastMentionSegment:r}=s;e.mentionedUsers&&e.mentionedUsers.length>0&&e.mentionedUsers.forEach((t=>{("channel"===t.type||"user"===t.type&&n.userId&&t.userPublicIds.includes(n.userId))&&(r=e.segment)}));const c=Object.assign(Object.assign({},s),{lastMentionSegment:r,lastSegment:o,isMentioned:!(s.readToSegment>=r),unreadCount:Math.max(i,0)});at(a,c)})(e),ea(e.channelId)})),t.useLegacyUnreadCount&&a.messages.forEach((e=>{var n,a,s;const o=null===(n=nt(["channelUnread","get",e.channelId]))||void 0===n?void 0:n.data;if(!o||o.lastSegment>=e.segment)return;const i=e.segment,r=(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:o.lastMentionedSegment,c=null!==(s=o.readToSegment)&&void 0!==s?s:0,d=Object.assign(Object.assign({},o),{lastSegment:i,unreadCount:Math.max(i-c,0),lastMentionedSegment:r,isMentioned:"number"==typeof r&&c<r});at(["channelUnread","get",e.channelId],d),xt("local.channelUnread.updated",[d])})),Nn(s),s.messages.forEach((t=>{t.creatorPrivateId===n._id&&yi(t),e(t)}))}))];return()=>{a.forEach((e=>e()))}},fi=e=>{const t=Ge(),n=[qt(t,"message/onMessageCreated","local.message.created",(async t=>(Nn(t),t.messages.forEach((t=>{e(t)})))))];return()=>{n.forEach((e=>e()))}},bi=e=>{const t=Ge();return qt(t,"onSubChannelCreated","message-feed.created",(async n=>{const a=await va(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&n.messageFeeds.forEach((e=>{(e=>{const{channelId:t,subChannelId:n,createdAt:a,updatedAt:s}=e,o={channelId:t,subChannelId:n,unreadCount:0,readToSegment:0,lastMentionSegment:0,lastSegment:0,isMentioned:!1,isDeleted:!1,createdAt:a,updatedAt:s};at(["subChannelUnreadInfo","get",o.subChannelId],o)})({channelId:e.channelId,subChannelId:e.messageFeedId,createdAt:e.createdAt,updatedAt:e.updatedAt})})),Nn(a),e(a.messageFeeds[0])}))},Ii=e=>{const t=Ge(),n=[qt(t,"onSubChannelDeleted","message-feed.deleted",(async n=>{const a=await va(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&a.messageFeeds.forEach((e=>{(e=>{var t;const n=["subChannelUnreadInfo","get",e],a=null===(t=nt(n))||void 0===t?void 0:t.data;a&&at(n,Object.assign(Object.assign({},a),{isDeleted:!0}))})(e.subChannelId),ea(e.channelId)})),Nn(a),e(a.messageFeeds[0])})),qt(t,"local.message-feed.deleted","local.message-feed.deleted",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}},Ci=async e=>{const t=Ge();t.log("channel/markerSync");const{data:n}=await t.http.post("/api/v1/markers/sync",{deviceLastSyncAt:e}),{userEntityMarkers:a,userFeedMarkers:s,feedMarkers:o,userMarkers:i}=n,r=Qn(a),c=Vn(s),d=t.cache&&Date.now();return t.cache&&Nn({userEntityMarkers:r,userFeedMarkers:c,feedMarkers:o,userMarkers:i},{cachedAt:d}),xt("local.feedMarker.fetched",{feedMarkers:o}),xt("local.channelMarker.fetched",{userEntityMarkers:r}),xt("local.subChannelMarker.fetched",{userFeedMarkers:c}),xt("local.userMarker.fetched",{userMarkers:i}),{data:n,hasMore:n.feedMarkers.length>0}};let wi=!1,Si=[],Oi=!1;let Ti=null;let Ai=[];const Ri=e=>{Ai=e},Pi=async()=>{var e;if(!Oi&&0!==Ai.length)try{Oi=!0,Ai=[];const t=await Ci((null==Ti?new Date:Ti).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)&&(!Ti||e.getTime()>Ti.getTime())&&(Ti=e),t.hasMore&&Ai.push("has_more")}catch(e){}finally{Oi&&(Oi=!1)}};ks((async()=>{wi&&await Pi()}),2e3);const Di=()=>true,Ui=e=>{var t;const n=Ge();if(n.mqtt)return null===(t=n.mqtt)||void 0===t?void 0:t.listen(e)},ki=async()=>{const e=Ge(),t=await jn(),{data:{status:n,error:a}}=await e.http.delete("/v1/notification",{params:{deviceId:t},headers:{"X-API-Key":e.apiKey}});if(a)throw new Qe(a,5e5,"error");return"success"===n};let ji=[];var Ei;class Mi{constructor(){Ei.set(this,e.FileAccessTypeEnum.PUBLIC)}setFileAccessType(e){!function(e,t,n,a,s){if("m"===a)throw new TypeError("Private method is not writable");if("a"===a&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===a?s.call(e,n):s?s.value=n:t.set(e,n)}(this,Ei,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,Ei,"f")}}let qi;Ei=new WeakMap;var xi=()=>(qi||(qi=new Mi),qi);const Ki={[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"}},Ni=async e=>{const t=Ge();Ys("establishing");const{accessToken:n,users:a,expiresAt:s,issuedAt:o,userType:i,files:r}=await(async({params:e,options:t})=>{const n=Ge();n.log("client/api/getBotToken");const a=En(),{data:s}=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 s})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.token={accessToken:n,issuedAt:o,expiresAt:s},Ys("established"),Nn(Ws({users:a,files:r})),{accessToken:n,users:a,userType:i}},Fi=[];function _i(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 Bi(t){return(null==t?void 0:t.type)===e.NotificationRolesFilterTypeEnum.ONLY?{listenFromRoleIds:t.roleIds}:{listenFromRoleIds:[]}}class $i{constructor(e){this.channelId=e}async enable(){const t=Ge(),n={level:e.NotificationSettingsLevelEnum.CHANNEL,channelId:this.channelId,isPushNotifiable:!0};await t.http.post("/api/v3/notification/setting",n)}async disable(){const t=Ge(),n={level:e.NotificationSettingsLevelEnum.CHANNEL,channelId:this.channelId,isPushNotifiable:!1};await t.http.post("/api/v3/notification/setting",n)}async getSettings(){const t=Ge(),{data:n}=await t.http.get(`/api/v3/notification/setting?level=${e.NotificationSettingsLevelEnum.CHANNEL}&channelId=${encodeURIComponent(this.channelId)}`);return{isEnabled:n.isPushNotifiable}}}class Li{async enable(t){var n;const a=Ge(),s=null!==(n=null==t?void 0:t.map((e=>Object.assign({moduleName:e.moduleName,isPushNotifiable:e.isEnabled},Bi(e.rolesFilter)))))&&void 0!==n?n:[],o={level:e.NotificationSettingsLevelEnum.USER,isPushNotifiable:!0,notifiableEvents:s};await a.http.post("/api/v3/notification/setting",o)}async disableAllNotifications(){const t=Ge(),n={level:e.NotificationSettingsLevelEnum.USER,isPushNotifiable:!1,notifiableEvents:[]};await t.http.post("/api/v3/notification/setting",n)}async getSettings(){var t;const n=Ge(),{data:a}=await n.http.get(`/api/v3/notification/setting?level=${e.NotificationSettingsLevelEnum.USER}`),s=Object.values(e.UserNotificationModuleNameEnum),o=(null!==(t=a.notifiableEvents)&&void 0!==t?t:[]).filter((e=>null!=e.moduleName&&s.includes(e.moduleName))).map((e=>({moduleName:e.moduleName,isEnabled:e.isPushNotifiable,rolesFilter:_i(e.listenFromRoleIds,e.ignoreFromRoleIds)})));return{isEnabled:a.isPushNotifiable,modules:o}}}class Qi{constructor(e){this.communityId=e}async enable(t){var n;const a=Ge(),s=null!==(n=null==t?void 0:t.map((t=>Object.assign({moduleName:e.UserNotificationModuleNameEnum.SOCIAL,name:t.eventName,isPushNotifiable:t.isEnabled},Bi(t.rolesFilter)))))&&void 0!==n?n:[],o={level:e.NotificationSettingsLevelEnum.COMMUNITY,communityId:this.communityId,isPushNotifiable:!0,notifiableEvents:s};await a.http.post("/api/v3/notification/setting",o)}async disable(){const t=Ge(),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=Ge(),{data:a}=await n.http.get(`/api/v3/notification/setting?level=${e.NotificationSettingsLevelEnum.COMMUNITY}&communityId=${encodeURIComponent(this.communityId)}`),s=Object.values(e.CommunityNotificationEventNameEnum),o=(null!==(t=a.notifiableEvents)&&void 0!==t?t:[]).filter((e=>null!=e.name&&s.includes(e.name))).map((e=>({eventName:e.name,isEnabled:e.isPushNotifiable,isNetworkEnabled:e.isNetworkEnabled,rolesFilter:_i(e.listenFromRoleIds,e.ignoreFromRoleIds)})));return{isEnabled:a.isPushNotifiable,events:o}}}class Vi{user(){return new Li}community(e){return new Qi(e)}channel(e){return new $i(e)}}const Ji=e=>{const t=Ge();return qt(t,"channelMarker/onChannelMarkerFetched","local.channelMarker.fetched",(t=>{t.userEntityMarkers.forEach((t=>{e(t)}))}))},Hi=e=>{const t=Ge();return qt(t,"subChannelMarker/onSubChannelMarkerFetched","local.subChannelMarker.fetched",(t=>{t.userFeedMarkers.forEach(e)}))},zi=e=>{const t=Ge();return qt(t,"subChannelMarker/onSubChannelMarkerUpdated","local.subChannelMarker.updated",(t=>{e(t.userFeedMarkers)}))},Gi=e=>{const t=Ge();return qt(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers)}))},Yi=e=>{const t=Ge();return qt(t,"messageMarker/onMessageMarkerFetched","local.messageMarker.fetched",(t=>{e(t.contentMarkers[0])}))},Wi=e=>{const t=Ge();return qt(t,"messageMarker/onMessageMarked","marker.marked-message",(t=>{var n,a,s;Nn(t);const o=tt(["message","collection"]),{contentMarkers:i,feedMarkers:r}=t;if(o&&(null==o?void 0:o.length)>0&&(null==r?void 0:r.length)>0){const e=o.filter((e=>{var t,n;return(null===(n=null===(t=e.data)||void 0===t?void 0:t.query)||void 0===n?void 0:n.subChannelId)===r[0].feedId}));if(e.length>0&&(null==i?void 0:i.length)>0){(null!==(s=null===(a=null===(n=e[0].data)||void 0===n?void 0:n.data)||void 0===a?void 0:a.map((e=>nt(["message","get",e]))).map((({data:e})=>e)).filter(Boolean))&&void 0!==s?s:[]).forEach((e=>{var t,n;const a=["messageMarker","get",Xe("messageMarker")({creatorId:e.creatorPrivateId,feedId:e.subChannelId,contentId:e.messageId})],s=null===(t=nt(a))||void 0===t?void 0:t.data;if(!s)return;const o=i[0].feedId===s.feedId,r=i[0].readCount>s.readCount,c=(null===(n=i[0])||void 0===n?void 0:n.deliveredCount)>s.deliveredCount;if(o){const e=Object.assign(Object.assign({},s),{readCount:r?i[0].readCount:s.readCount,deliveredCount:c?i[0].deliveredCount:s.deliveredCount});at(a,e)}}))}}e(t.contentMarkers[0])}))};function Xi(e){return"object"==typeof e&&null!==e}const Zi=e=>{if(!Xi(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)},er=e=>{if(!Xi(e))return e;const t=Object.entries(e).map((([e,t])=>"function"==typeof t?[e,void 0]:[e,t]));return Object.fromEntries(t)};var tr=Object.freeze({__proto__:null,getActiveClient:Ge,getActiveUser:Dt,setActiveUser:Ut,createClient:(e,t=sn.SG,{debugSession:n="amity",apiEndpoint:a,prefixDeviceIdKey:s,rteEnabled:o=!0}={})=>{var i,r,c;const d=(e=>{const t=`${null==e?void 0:e.trim()}`.length>0&&!an,n=I.default(e),a=(e,...a)=>{t&&n(e,a)};return a.__instance__=n,a})(n);d("client/api/createClient",{apiKey:e.replace(/.{5}$/g,"xxxxx"),apiRegion:t});const l=null!==(i=null==a?void 0:a.http)&&void 0!==i?i:rn("http",t),u=null!==(r=null==a?void 0:a.upload)&&void 0!==r?r:rn("upload",t),h=null!==(c=null==a?void 0:a.mqtt)&&void 0!==c?c:rn("mqtt",t),m=pn(l),g=pn(u);let p;o&&(p=xn(h));const y=b.default(),v={version:`${he}`,apiKey:e,log:d,cache:{data:{}},http:m,ws:undefined,mqtt:p,upload:g,emitter:y,sessionState:"notLoggedIn",accessTokenExpiryWatcher:pi,sessionHandler:undefined,hasPermission:Vs,validateUrls:Js,validateTexts:Hs,getFeedSettings:zs,getCoreUserSettings:Bs,getSocialSettings:_s,getChatSettings:Kn,getVisitorDeviceId:jn,getMessagePreviewSetting:Ns,onRTEConnectionStateChange:Ui,use:()=>Ye(v),isUnreadCountEnabled:!1,useLegacyUnreadCount:!0,getMarkerSyncConsistentMode:Di,getProductCatalogueSetting:$s,getForYouFeedSetting:Ls,prefixDeviceIdKey:s};try{const t=Ge();if(t.apiKey===e)return t;Ye(v)}catch(e){Ye(v)}return v},login:si,loginWithAccessToken:ui,logout:eo,secureLogout:async()=>{const e=Ge();try{await ki()}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 eo()},resumeSession:async(e,t,n)=>{const a=Ge();let s;a.log("client/api/resumeSession",Object.assign({apiKey:a.apiKey,sessionState:a.sessionState},e)),a.userId&&(a.userId===e.userId&&di(e.token.accessToken)?(a.mqtt&&a.mqtt.connected&&a.mqtt.disconnect(),ji.forEach((e=>e())),ji=[]):(await eo(),ji.forEach((e=>e())),ji=[]));try{Ys("establishing");const n=await ci(e);if(null==n)throw new Le(`${e.userId} has not been found`,8e5,"error");if(n.isDeleted)return to("userDeleted"),!1;if(n.isGlobalBanned)return to("globalBan"),!1;a.userId=n.userId,a.sessionHandler=t,s=a.accessTokenExpiryWatcher(t),Ut(n)}catch(e){throw fn().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await Ft()}(),await Fs(),0===ji.length&&(ji.push(Xo((e=>{to("globalBan"),ji.forEach((e=>e())),s()})),ei((e=>{to(),ji.forEach((e=>e())),s()})),io((e=>{e.userId===a.userId&&(to("userDeleted"),ji.forEach((e=>e())),s())})),Zo((e=>{fn().setSessionState(e),eo(),ji.forEach((e=>e()))})),Ga(ti),ms(ti),xs(),yo(),ko()),a.useLegacyUnreadCount?ji.push(Io()):ji.push(Oo())),!0},isConnected:()=>{var e,t;const n=Ge();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:zs,renewal:ri,markerSync:Ci,enableUnreadCount:()=>!0,setUploadedFileAccessType:function(e){xi().setFileAccessType(e)},registerPushNotification:async e=>{const t=Ge();let n;if("ios"!==l.Platform.OS&&"android"!==l.Platform.OS)throw new He("Unsupported platform");n=l.Platform.OS;const a=await jn(),{data:{status:s,error:o}}=await t.http.post("/v1/notification",{userId:t.userId,deviceId:a,platform:n,token:e},{headers:{"X-API-Key":t.apiKey}});if(o)throw new Qe(o,5e5,"error");return"success"===s},unregisterPushNotification:ki,onRTEConnectionStateChange:Ui,fetchLinkPreview:async e=>{const t=Ge();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=Ge(),{data:n}=await t.http.get(`/api/v1/link-preview?url=${e}`);return n},getSocialSettings:_s,getShareableLinkConfiguration:async()=>{var e,t;const n=Ge(),{data:a}=await n.http.get("/api/v3/network-settings/shareable-deep-links"),s=null!==(e=a.domain)&&void 0!==e?e:"",o=null!==(t=a.patterns)&&void 0!==t?t:{};return{domain:s,patterns:o,isEnabled(e){const{key:t}=Ki[e];return!!s&&!!o[t]},getPattern(e){const{key:t}=Ki[e];return o[t]||null},generateLink(e,t){const{key:n,placeholder:a}=Ki[e];return s&&o[n]?s+o[n].replace(`{${a}}`,t):null}}},getProductCatalogueSetting:$s,getForYouFeedSetting:Ls,loginAsVisitor:ii,loginAsBot:async e=>{const t=Ge();let n;t.log("client/api/connectClient",{apiKey:t.apiKey,sessionState:t.sessionState});const a=await jn();let s;try{const{users:o,userType:i}=await Ni({params:{deviceId:a},options:{setAccessTokenCookie:!0}});[s]=o,t.userId=s.userId,t.sessionHandler=e.sessionHandler,t.loginType="userId",n=t.accessTokenExpiryWatcher(),so({user:s,userType:i})}catch(e){throw fn().setSessionState("notLoggedIn"),e}return await Fs(),0===Fi.length&&Fi.push(ei((e=>{to(),Fi.forEach((e=>e())),n()})),Zo((e=>{fn().setSessionState(e),eo(),Fi.forEach((e=>e()))}))),!0},getCurrentUser:Bt,getCurrentUserType:()=>{if(!no)throw new Le("Connect client first",8e5,"fatal");return no},setCurrentUserType:ao,setAccessTokenHandler:e=>{const t=Ge();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:Kn,getCoreUserSettings:Bs,notifications:()=>new Vi,enableAutoSubscriptions:e=>{const t=Tn();e.forEach((e=>t.subscribe(e)))},disableAutoSubscriptions:e=>{const t=Tn();e.forEach((e=>t.unsubscribe(e)))},autoSubscriptions:()=>Tn().subscriptions(),onConnectionError:Wo,onClientDisconnected:e=>Wo((({code:t})=>{800211===t&&e()})),onClientBanned:Xo,onSessionStateChange:bn,onNetworkActivities:e=>un().onNetworkActivities(e),onVisitorUsageLimitReached:e=>{const t=Ge();return qt(t,"client/onVisitorUsageLimitReached","visitorUsageLimitReached",e)},getUserUnread:e=>{const{_id:t}=Dt();if(!t)throw new Le("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:a}=Ge();a||console.log("For using Live Object feature you need to enable Cache!");n(`liveUserUnread(tmpid: ${Date.now()}) > listen`);const s=[];let o,i=!1;const r=t=>{const{data:n}=t,a=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;o=a?Zi(a):a,e({data:a?Object.assign(Object.assign({},a),{isMentioned:a.isMentioned}):a,loading:t.loading,error:t.error})};return s.push(Gi((e=>(e=>{var n;const a=e.filter((e=>t===e.userId)),s=a.reduce(((e,t)=>null==e||new Date(t.lastSyncAt).getTime()>new Date(e.lastSyncAt).getTime()?t:e),null),i={unreadCount:null!==(n=null==s?void 0:s.unreadCount)&&void 0!==n?n:0,isMentioned:a.some((e=>!!e.isMentioned))};Na(o,i)||r({loading:!1,data:i})})(e)))),(()=>{const e=Fe(na);Be(e,(({error:e,data:t,loading:n,origin:a,cachedAt:o})=>{!function(e){return null!=e&&null!=e}(t)?r({loading:n,data:void 0,origin:a,error:e}):(o===fe?(r({data:t,origin:a,loading:!1,error:new Qe(ve,800800,"error")}),i=!0,s.forEach((e=>e()))):i||r({loading:n,data:t,origin:a,error:e}),e&&s.forEach((e=>e())))}))})(),()=>{s.forEach((e=>e()))}},getMarkerSyncEvents:()=>Ai,setMarkerSyncEvents:Ri,pushMarkerSyncEvent:e=>Ai.push(e),markerSyncTrigger:Pi,startMarkerSync:async()=>Promise.resolve(),startUnreadSync:async()=>Promise.resolve(),stopUnreadSync:()=>{wi=!1,Ri([]),Si.forEach((e=>e())),Si=[]},getMarkerSyncConsistentMode:Di});const nr=(e,t)=>{const n=Ge();return qt(n,e,e,(e=>{const a=Lo(e);n.cache?(Nn(a),t(a.follows[0])):t(a.follows[0])}))},ar=(e,t)=>{const n=Ge();return qt(n,e,e,(e=>{const a=Vo(e);n.cache?(Nn(a),t(a.follows[0])):t(a.follows[0])}))},sr=e=>nr("follow.created",e),or=e=>nr("follow.unfollowed",e),ir=e=>nr("follow.followerDeleted",e),rr=e=>nr("follow.requested",e),cr=e=>nr("follow.requestCanceled",e),dr=e=>nr("follow.accepted",e),lr=e=>nr("follow.requestDeclined",e),ur=async e=>{var t,n;const a=Ge();a.log("follow/getFollowInfo",e);const{data:s}=await a.http.get(a.userId===e?"/api/v4/me/followInfo":`/api/v5/users/${e}/followInfo`),o=a.cache&&Date.now(),i="follows"in s?Object.assign(Object.assign({},s.followCounts[0]),{status:null===(n=null===(t=s.follows)||void 0===t?void 0:t[0])||void 0===n?void 0:n.status}):s.followCounts[0];return a.cache&&at(["followInfo","get",e],i,{cachedAt:o}),{data:i,cachedAt:o}};ur.locally=e=>{const t=Ge();if(t.log("follow/getFollowInfo.locally",e),!t.cache)return;const n=nt(["followInfo","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const hr=e=>{const t=async t=>{const[{data:n},{data:a}]=await Promise.all([ur(t.from),ur(t.to)]);e(n),e(a)},n=[nr("follow.created",t),nr("follow.requested",t),nr("follow.accepted",t),nr("follow.unfollowed",t),nr("follow.requestCanceled",t),nr("follow.requestDeclined",t),nr("follow.followerDeleted",t),ar("local.follow.created",t),ar("local.follow.requested",t),ar("local.follow.accepted",t),ar("local.follow.unfollowed",t),ar("local.follow.requestDeclined",t)];return()=>{n.forEach((e=>e()))}},mr=e=>ar("local.follow.created",e),gr=e=>ar("local.follow.unfollowed",e),pr=e=>ar("local.follow.requested",e),yr=e=>ar("local.follow.accepted",e),vr=e=>ar("local.follow.requestDeclined",e);class fr{constructor(e){const{http:t}=Ge();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,s;if("prev"===e&&!this.previousToken)return;if("next"===e&&!this.nextToken)return;let o;"prev"===e&&(o=this.previousToken),"next"===e&&(o=this.nextToken);const i=await this.getRequest(this.queryParams,o);return"first"===e&&(this.nextToken=null===(t=i.paging)||void 0===t?void 0:t.next,this.previousToken=null===(n=i.paging)||void 0===n?void 0:n.previous),"prev"===e&&(this.previousToken=null===(a=i.paging)||void 0===a?void 0:a.previous),"next"===e&&(this.nextToken=null===(s=i.paging)||void 0===s?void 0:s.next),i}getNextToken(){return this.nextToken}getPrevToken(){return this.previousToken}}class br extends fr{async getRequest(e,t){const{limit:n=me,userId:a}=e,s=_n(e,["limit","userId"]),o=t?{token:t}:{limit:n},i=Ge().userId===a?"/api/v4/me/followers":`/api/v4/users/${a}/followers`,{data:r}=await this.http.get(i,{params:Object.assign(Object.assign({},s),{options:o,isDeleted:!1})});return r}}class Ir{constructor(e,t){this.query=e,this.cacheKey=t}}var Cr;!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"}(Cr||(Cr={}));class wr extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.follows.map(Xe("follow"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(Xe("follow"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.to&&a){switch(e){case Cr.OnDeclined:case Cr.OnCanceled:case Cr.OnUnfollowed:case Cr.OnDeleted:a.data=a.data.filter((e=>e!==Xe("follow")(t)));break;case Cr.OnRequested:case Cr.OnAccepted:case Cr.OnFollowed:a.data=[...new Set([Xe("follow")(t),...a.data])]}at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Sr{constructor(e){const{http:t}=Ge();this.queryParams=e,this.http=t}async onFetch(){return await this.getRequest(this.queryParams)}}class Or{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 Sr?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 Sr)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 Sr)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(Zi).map(er);return!Na(this.snapshot,t)&&(this.snapshot=t,!0)}getCacheKey(){return this.cacheKey}}function Tr(e){return null!=e}const Ar=({userId:e})=>t=>{const n=Ge();return qt(n,"user.deleted","user.deleted",(n=>{const a=Ws(n);Nn(a);const s=nt(["follow","get",Xe("follow")({from:a.users[0].userId,to:e})]);s&&t(null==s?void 0:s.data)}))};class Rr extends Or{constructor(e,t){const n=R.default(Object.assign(Object.assign({},e),{type:"follower"})),a=["follow","collection",n];super(new br(e),n,a,t),this.query=e,this.queryStreamController=new wr(this.query,this.cacheKey,this.notifyChange.bind(this),Lo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:sr,action:Cr.OnFollowed},{fn:or,action:Cr.OnUnfollowed},{fn:dr,action:Cr.OnAccepted},{fn:lr,action:Cr.OnDeclined},{fn:cr,action:Cr.OnCanceled},{fn:ir,action:Cr.OnDeleted},{fn:yr,action:Cr.OnAccepted},{fn:vr,action:Cr.OnDeclined},{fn:mr,action:Cr.OnFollowed},{fn:gr,action:Cr.OnUnfollowed},{fn:Ar({userId:this.query.userId}),action:Cr.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["follow","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,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=nt(["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 Pr extends fr{async getRequest(e,t){const{limit:n=me,userId:a}=e,s=_n(e,["limit","userId"]),o=t?{token:t}:{limit:n},i=Ge().userId===a?"/api/v4/me/following":`/api/v4/users/${a}/following`,{data:r}=await this.http.get(i,{params:Object.assign(Object.assign({},s),{options:o,isDeleted:!1})});return r}}class Dr extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.follows.map(Xe("follow"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(Xe("follow"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.from&&a){switch(e){case Cr.OnDeclined:case Cr.OnCanceled:case Cr.OnUnfollowed:case Cr.OnDeleted:a.data=a.data.filter((e=>e!==Xe("follow")(t)));break;case Cr.OnRequested:case Cr.OnAccepted:case Cr.OnFollowed:a.data=[...new Set([Xe("follow")(t),...a.data])]}at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Ur=({userId:e})=>t=>{const n=Ge();return qt(n,"user.deleted","user.deleted",(n=>{const a=Ws(n);Nn(a);const s=nt(["follow","get",Xe("follow")({from:e,to:a.users[0].userId})]);s&&t(null==s?void 0:s.data)}))};class kr extends Or{constructor(e,t){const n=R.default(Object.assign(Object.assign({},e),{type:"following"})),a=["follow","collection",n];super(new Pr(e),n,a,t),this.query=e,this.queryStreamController=new Dr(this.query,this.cacheKey,this.notifyChange.bind(this),Qo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:rr,action:Cr.OnRequested},{fn:dr,action:Cr.OnAccepted},{fn:lr,action:Cr.OnDeclined},{fn:cr,action:Cr.OnCanceled},{fn:sr,action:Cr.OnFollowed},{fn:or,action:Cr.OnUnfollowed},{fn:ir,action:Cr.OnDeleted},{fn:pr,action:Cr.OnRequested},{fn:yr,action:Cr.OnAccepted},{fn:vr,action:Cr.OnDeclined},{fn:mr,action:Cr.OnFollowed},{fn:gr,action:Cr.OnUnfollowed},{fn:Ur({userId:this.query.userId}),action:Cr.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["follow","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,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=nt(["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 jr=(e,t,n,a,s,o)=>{const{forceDispatch:i,callbackDataSelector:r,callbackFilter:c}=Object.assign({forceDispatch:!1,callbackDataSelector:e=>e},o),{cache:d}=Ge();let l;d||console.log("For using Live Object feature you need to enable Cache!");let u=!1;const h=[],m=e=>{const{data:n}=e,a=_n(e,["data"]);c&&!c(n,l)||t(Object.assign({data:r(n)},a)),l=Zi(n)};return h.push(...s.map((t=>t((t=>((t,a=!1)=>{e===t[n]&&(l&&!a&&Na(l,t)||m({loading:!1,data:t,origin:"event"}))})(t,i)))))),(()=>{const t=Fe(a,e,!0);Be(t,(({error:e,data:t,loading:n,origin:a,cachedAt:s})=>{s===fe?(m({data:t,origin:a,loading:!1,error:new Qe(ve,800800,"error")}),u=!0,h.forEach((e=>e()))):u||m({loading:n,data:t,origin:a,error:e}),e&&h.forEach((e=>e()))}))})(),()=>{h.forEach((e=>e()))}};var Er=Object.freeze({__proto__:null,blockUser:async e=>{const t=Ge();t.log("user/blockUser",e);const{data:n}=await t.http.post(`/api/v4/me/user-blocks/${e}`),a=t.cache&&Date.now(),{follows:s,followCounts:o}=n,i={follows:s};t.cache&&(Nn(i,{cachedAt:a}),ot(["followInfo","get",e],o[0],{cachedAt:a}));const r={follows:s.map((e=>{const t=Object.assign(Object.assign({},e),{to:e.from,from:e.to,status:"none"});return"blocked"===e.status?t:e}))},c=Vo(r);return xt("local.follow.unfollowed",c),n},unBlockUser:async e=>{const t=Ge();t.log("user/unBlockUser",e);const{data:n}=await t.http.delete(`/api/v4/me/user-blocks/${e}`),a=t.cache&&Date.now(),{follows:s,followCounts:o}=n,i={follows:s};t.cache&&(Nn(i,{cachedAt:a}),ot(["followInfo","get",e],o[0],{cachedAt:a}));const r=Vo(i);return xt("local.follow.created",r),n},onUserDidBlock:Ho,onUserDidUnblock:zo,follow:async e=>{const t=Ge();t.log("follow/follow",e);const{data:n}=await t.http.post(`/api/v4/me/following/${e}`),a=t.cache&&Date.now();t.cache&&Nn(n,{cachedAt:a});const s=Vo(n);return"accepted"===n.follows[0].status?xt("local.follow.created",s):xt("local.follow.requested",s),{data:n.follows[0],cachedAt:a}},unfollow:async e=>{const t=Ge();t.log("follow/unfollow",e);const{data:n}=await t.http.delete(`/api/v4/me/following/${e}`);t.cache&&Nn(n);const a=Vo(n);return xt("local.follow.unfollowed",a),!0},acceptMyFollower:async e=>{const t=Ge();t.log("follow/acceptMyFollower",e);const{data:n}=await t.http.post(`/api/v4/me/followers/${e}`);t.cache&&Nn(n);const a=Vo(n);return xt("local.follow.accepted",a),!0},declineMyFollower:async e=>{const t=Ge();t.log("follow/declineMyFollower",e);const{data:n}=await t.http.delete(`/api/v4/me/followers/${e}`);t.cache&&Nn(n);const a=Vo(n);return xt("local.follow.requestDeclined",a),!0},onUserFollowed:sr,onUserUnfollowed:or,onFollowerDeleted:ir,onFollowerRequested:rr,onFollowRequestCanceled:cr,onFollowRequestAccepted:dr,onFollowRequestDeclined:lr,onFollowInfoUpdated:hr,onLocalUserFollowed:mr,onLocalUserUnfollowed:gr,onLocalFollowerRequested:pr,onLocalFollowRequestAccepted:yr,onLocalFollowRequestDeclined:vr,getFollowers:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getFollowers(tmpid: ${o}) > listen`);const i=new Rr(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getFollowers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getFollowings:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log("For using Live Collection feature you need to enable Cache!");const o=Date.now();a(`getFollowings(tmpid: ${o}) > listen`);const i=new kr(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getFollowings(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getFollowInfo:(e,t)=>jr(e,t,"userId",ur,[hr],{forceDispatch:!0}),getMyFollowInfo:e=>{const{userId:t}=Dt();return jr(t,e,"userId",ur,[hr],{forceDispatch:!0})}});function Mr(e,t){return e.map((e=>{const n=nt(["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}=Dt();return e.communityId===t.communityId&&t.userId===n}(e,t)&&"none"!==t.communityMembership));return Object.assign(Object.assign({},e),{isJoined:a})}))}const qr=e=>{var t;return null!==(t=Object.keys(x).find((t=>e.needApprovalOnPostCreation===x[t].needApprovalOnPostCreation&&e.onlyAdminCanPost===x[t].onlyAdminCanPost)))&&void 0!==t?t:K};function xr({communities:e}){return e.map((e=>{var{needApprovalOnPostCreation:t,onlyAdminCanPost:n}=e,a=_n(e,["needApprovalOnPostCreation","onlyAdminCanPost"]);return Object.assign({postSetting:qr({needApprovalOnPostCreation:t,onlyAdminCanPost:n})},a)}))}const Kr=e=>{const t=xr({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})})),s=Mr(t,a);return Object.assign(Object.assign({},e),{users:e.users.map(ga),communities:s,communityUsers:a})},Nr=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})},Fr=e=>{const t=xr({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=Mr(t,n);return Object.assign(Object.assign({},e),{communities:a,communityUsers:n})},_r=e=>{const{postSetting:t,storySetting:n}=e,a=_n(e,["postSetting","storySetting"]);return Object.assign(Object.assign(Object.assign({},a),t?x[t]:void 0),{allowCommentInStory:"boolean"!=typeof(null==n?void 0:n.enableComment)||n.enableComment})},Br=e=>{var t=_n(e,["searchResult"]);const n=Kr(t);return Object.assign({},n)},$r=e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=nt(["user","get",e.requestorPublicId]))||void 0===t?void 0:t.data;if(n)return _t(n)},cancel:async()=>{await(async e=>{var t;const n=Ge();n.log("joinRequest/cancelJoinRequest",e.joinRequestId);const{data:a}=await n.http.delete(`/api/v4/communities/${e.targetId}/join`),s=null===(t=nt(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return s&&(ot(["joinRequest","get",e.joinRequestId],{status:"cancelled"}),xt("local.joinRequest.deleted",[s])),a.success})(e)},approve:async()=>{await(async e=>{var t;const n=Ge();n.log("joinRequest/approveJoinRequest",e.joinRequestId);const{data:a}=await n.http.post(`/api/v4/communities/${e.targetId}/join/approve`,{userId:e.requestorInternalId}),s=null===(t=nt(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return s&&(ot(["joinRequest","get",e.joinRequestId],{status:"approved"}),xt("local.joinRequest.updated",[s])),a.success})(e)},reject:async()=>{await(async e=>{var t;const n=Ge();n.log("joinRequest/rejectJoinRequest",e.joinRequestId);const{data:a}=await n.http.post(`/api/v4/communities/${e.targetId}/join/reject`,{userId:e.requestorInternalId}),s=null===(t=nt(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return s&&(ot(["joinRequest","get",e.joinRequestId],{status:"rejected"}),xt("local.joinRequest.updated",[s])),a.success})(e)}});class Lr extends fr{async getRequest(e,t){const{limit:n=20,communityId:a}=e,s=_n(e,["limit","communityId"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get(`/api/v4/communities/${a}/join`,{params:Object.assign(Object.assign({},s),{options:o})});return i}}var Qr;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(Qr||(Qr={}));class Vr extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.joinRequests.map((e=>Xe("joinRequest")({joinRequestId:e._id})))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>Xe("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===Qr.OnLocalJoinRequestUpdated){if(!a.data.find((e=>e===t[0].joinRequestId)))return}e===Qr.OnLocalJoinRequestCreated&&(a.data=[...new Set([...t.map((e=>e.joinRequestId)),...a.data])]),e===Qr.OnLocalJoinRequestDeleted&&(a.data=a.data.filter((e=>e!==t[0].joinRequestId))),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Jr=e=>{const t=Ge(),n=[qt(t,"onJoinRequestCreated","local.joinRequest.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Hr=e=>{const t=Ge(),n=[qt(t,"onJoinRequestUpdated","local.joinRequest.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},zr=e=>{const t=Ge(),n=[qt(t,"onJoinRequestDeleted","local.joinRequest.deleted",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class Gr extends Or{constructor(e,t){const n=R.default(e),a=["joinRequest","collection",n];super(new Lr(e),n,a,t),this.query=e,this.queryStreamController=new Vr(this.query,this.cacheKey,this.notifyChange.bind(this),Nr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:Jr,action:Qr.OnLocalJoinRequestCreated},{fn:Hr,action:Qr.OnLocalJoinRequestUpdated},{fn:zr,action:Qr.OnLocalJoinRequestDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a;const s=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(s.data.map((e=>nt(["joinRequest","get",e]))).filter(Tr).map((({data:e})=>e)).map($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.status&&(t=t.filter((e=>e.status===this.query.status)));const n=(()=>"firstCreated"===this.query.sortBy?It:wt)();return t=t.sort(n),t}}const Yr=e=>Object.assign(Object.assign({},e),{createdById:e.createdBy}),Wr=e=>Object.assign(Object.assign({},e),{invitations:e.invitations.map(Yr),users:e.users.map(ga)}),Xr=async e=>{const t=Ge();t.log("invitation/createInvitations",e);const{data:n}=await t.http.post("/api/v1/invitations",e),a=Wr(n),s=t.cache&&Date.now();return t.cache&&Nn(a,{cachedAt:s}),xt("local.invitation.created",a.invitations),{data:a.invitations,cachedAt:s}},Zr=e=>Object.assign(Object.assign({},e),{users:e.users.map(ga),invitations:e.invitations.map(Yr)}),ec=e=>Object.assign(Object.assign({},e),{get user(){const t=nt(["user","get",e.invitedUserPublicId]);if(null==t?void 0:t.data)return _t(t.data)},get createdBy(){const t=nt(["user","get",e.inviterUserPublicId]);if(null==t?void 0:t.data)return _t(t.data)},get target(){if("community"===e.targetType){const t=nt(["community","get",e.targetId]);return(null==t?void 0:t.data)?t.data:void 0}},accept:async()=>{await(async e=>{var t;const n=Ge();n.log("invitation/acceptInvitation",e);const{data:a}=await n.http.post(`/api/v1/invitations/${e}/accept`),s=null===(t=nt(["invitation","get",e]))||void 0===t?void 0:t.data;return s&&(ot(["invitation","get",e],{status:"approved"}),xt("local.invitation.updated",[s])),a.success})(e._id)},reject:async()=>{await(async e=>{var t;const n=Ge();n.log("invitation/rejectInvitation",e);const{data:a}=await n.http.post(`/api/v1/invitations/${e}/reject`),s=null===(t=nt(["invitation","get",e]))||void 0===t?void 0:t.data;return s&&(ot(["invitation","get",e],{status:"rejected"}),xt("local.invitation.updated",[s])),a.success})(e._id)}}),tc=async e=>{const t=Ge();t.log("invitation/getInvitation",e.targetType,e.targetId,e.type);const{data:n}=await t.http.get("/api/v1/invitations/me",{params:e}),a=Zr(n),s=t.cache&&Date.now();return t.cache&&Nn(a,{cachedAt:s}),{data:a.invitations[0]?ec(a.invitations[0]):void 0,cachedAt:s}};var nc;!function(e){e.OnLocalInvitationCreated="onLocalInvitationCreated",e.OnLocalInvitationUpdated="onLocalInvitationUpdated",e.OnLocalInvitationCanceled="onLocalInvitationCanceled"}(nc||(nc={}));class ac extends fr{async getRequest(e,t){const{limit:n=me}=e,a=_n(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/invitations",{params:Object.assign(Object.assign({},a),{options:s})});return o}}class sc extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.invitations.map(Xe("invitation"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(Xe("invitation"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===nc.OnLocalInvitationUpdated){if(!a.data.find((e=>e===t[0].invitationId)))return}e===nc.OnLocalInvitationCreated&&(a.data=[...new Set([...t.map((e=>e.invitationId)),...a.data])]),e===nc.OnLocalInvitationDeleted&&(a.data=a.data.filter((e=>e!==t[0].invitationId))),at(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=Ge(),n=[qt(t,"onLocalInvitationCreated","local.invitation.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},ic=e=>{const t=Ge(),n=[qt(t,"onLocalInvitationUpdated","local.invitation.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},rc=e=>{const t=Ge(),n=[qt(t,"onLocalInvitationCanceled","local.invitation.canceled",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class cc extends Or{constructor(e,t){const n=R.default(e),a=["invitation","collection",n];super(new ac(e),n,a,t),this.query=e,this.queryStreamController=new sc(this.query,this.cacheKey,this.notifyChange.bind(this),Wr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:oc,action:nc.OnLocalInvitationCreated},{fn:ic,action:nc.OnLocalInvitationUpdated},{fn:rc,action:nc.OnLocalInvitationCanceled}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["invitation","get",e]))).filter(Tr).map((({data:e})=>ec(e))))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,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?It:wt)();return t=t.sort(n),t}}const dc=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=nt(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),lc=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=nt(["category","get",e]);if(null==t?void 0:t.data)return dc(t.data)})).filter((e=>!!e))},get avatar(){var t;if(!e.avatarFileId)return;return null===(t=nt(["file","get",e.avatarFileId]))||void 0===t?void 0:t.data},createInvitations:async t=>{await Xr({type:"communityMemberInvite",targetType:"community",targetId:e.communityId,userIds:t})},getMemberInvitations:(t,n)=>((e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getInvitations: (tmpid: ${o}) > listen`);const i=new cc(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{it(c)})),()=>{a(`getInvitations (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}})(Object.assign(Object.assign({},t),{targetId:e.communityId,targetType:"community",type:"communityMemberInvite"}),n),getInvitation:async()=>{const{data:t}=await tc({targetType:"community",targetId:e.communityId});return t},join:async()=>(async e=>{var t;const n=Ge();n.log("community/joinRequest",e);const{data:a}=await n.http.post(`/api/v4/communities/${e}/join`),s=Nr(a),o=n.cache&&Date.now();n.cache&&Nn(s,{cachedAt:o});const i="approved"===s.joinRequests[0].status?"success":"pending";if("success"===i&&n.cache){const n=null===(t=nt(["community","get",e]))||void 0===t?void 0:t.data;if(n){const t=Object.assign(Object.assign({},n),{isJoined:!0});ot(["community","get",e],t)}}return xt("v4.local.community.joined",s.joinRequests),"success"===i?{status:i}:{status:i,request:$r(s.joinRequests[0])}})(e.communityId),getJoinRequests:(t,n)=>((e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getJoinRequests: (tmpid: ${o}) > listen`);const i=new Gr(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{it(c)})),()=>{a(`getJoinRequests (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}})(Object.assign(Object.assign({},t),{communityId:e.communityId}),n),getMyJoinRequest:async()=>{const{data:t}=await(async e=>{const t=Ge();t.log("community/myJoinRequest",e);const{data:n}=await t.http.get(`/api/v4/communities/${e}/join/me`),a=Nr(n),s=t.cache&&Date.now();return t.cache&&Nn(a,{cachedAt:s}),{data:a.joinRequests[0]?$r(a.joinRequests[0]):void 0,cachedAt:s}})(e.communityId);return t}});class uc{constructor(e,t,n){this._syncingStoriesCount=0,this._errorStoriesCount=0,this._targetId=e,this._lastStoryExpiresAt=t,this._lastStorySeenExpiresAt=n,this.cacheStoryExpireTime=nt(["story-expire",this._targetId]),this.cacheStoreSeenTime=nt(["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=nt(["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 nt(["story-sync-state",this._targetId]),this.isContainUnSyncedStory?this.localLastStoryExpires>e&&this.localLastStoryExpires>t:this.lastStoryExpiresAt>e&&this.lastStoryExpiresAt>t}getTotalStoryByStatus(){const e=tt(["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:s}}=t;return n!==this._targetId||s||(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 hc=e=>{const{targetType:t,targetId:n,lastStoryExpiresAt:a,lastStorySeenExpiresAt:s,targetUpdatedAt:o,localFilter:i}=e,r=new uc(n,a,s);return{targetType:t,targetId:n,lastStoryExpiresAt:a,updatedAt:o,hasUnseen:r.getHasUnseenFlag(),syncingStoriesCount:r.syncingStoriesCount,failedStoriesCount:r.failedStoriesCount,localFilter:i,localLastExpires:r.localLastStoryExpires,localLastSeen:r.localLastStorySeenExpiresAt,localSortingDate:r.getLocalLastSortingDate()}},mc=async e=>{const t=Ge();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,s=_n(e,["isPublic"]);n=await t.http.post("/api/v3/channels",Object.assign(Object.assign({},s),{isPublic:"community"===(null==e?void 0:e.type)?a:void 0}))}const a=await Da(n.data),s=t.cache&&Date.now();t.cache&&Nn(a,{cachedAt:s});const{channels:o}=a;return{data:Ds(o[0]),cachedAt:s}},gc=async e=>{const t=Ge();let n;t.log("channel/getChannel",e),Zn("channel",e);try{const{data:a}=await t.http.get(`/api/v3/channels/${encodeURIComponent(e)}`);n=await Da(a),t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&ka(a)}catch(t){throw Re(null==t?void 0:t.code)&&Fn("channel",e),t}const a=t.cache&&Date.now();t.cache&&Nn(n,{cachedAt:a});const{channels:s}=n;return{data:s.find((t=>t.channelId===e)),cachedAt:a}};gc.locally=e=>{var t;const n=Ge();if(n.log("channel/getChannel.locally",e),!n.cache)return;const a=null===(t=tt(["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 pc=Symbol("getWatcherUrls"),yc=e=>Object.assign(Object.assign({},e),{get moderation(){var t;return null===(t=nt(["streamModeration","get",e.streamId]))||void 0===t?void 0:t.data},get post(){var t;if("post"===e.referenceType)return null===(t=nt(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=nt(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;return null===(t=nt(["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=nt(["stream","get",e]))||void 0===t?void 0:t.data;if(n)return yc(n)})).filter(Tr):[]},getLiveChat:()=>(async e=>{var t;const n=Ge();if(n.log("stream/getLiveChat",e.streamId),e.channelId){const n=null===(t=nt(["channel","get",e.channelId]))||void 0===t?void 0:t.data;if(n)return Ps(Ds(n));const{data:a}=await gc(e.channelId);return Ps(Ds(a))}if(e.userId===n.userId){const{data:t}=await mc({type:"live",postId:e.postId,videoStreamId:e.streamId});return st(["stream","get",e.streamId],{channelId:t.channelId}),t}})(e),isBanned:!e.watcherUrl,watcherUrl:null,get[pc](){return e.watcherUrl}}),vc=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=nt(["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=nt(["user","get",e.userId]);if(null==t?void 0:t.data)return _t(t.data)},get childrenComment(){return e.children.map((e=>{const t=nt(["comment","get",e]);if(null==t?void 0:t.data)return null==t?void 0:t.data})).filter(Tr).map((e=>vc(e)))}});function fc(e){return!!(e.data&&"string"!=typeof e.data&&"videoFileId"in e.data&&"thumbnailFileId"in e.data&&"video"===e.dataType)}function bc(e){return!(!e.data||"string"==typeof e.data||!("streamId"in e.data)||"liveStream"!==e.dataType)}class Ic{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 Cc=null;const wc=()=>(Cc||(Cc=new Ic),Cc),Sc={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},Oc="-----BEGIN PRIVATE KEY-----";function Tc(e){const n=new Uint8Array(e);let a="";return n.forEach((e=>{a+=String.fromCharCode(e)})),t.btoa(a)}function Ac(e){return e<128?new Uint8Array([e]):e<256?new Uint8Array([129,e]):new Uint8Array([130,e>>8&255,255&e])}async function Rc(e){let n=e;n=e.includes(Oc)?e.substring(Oc.length,e.length-"-----END PRIVATE KEY-----".length).replace(/\s/g,""):e.replace(/\s/g,"");const a=t.atob(n),s=new Uint8Array(a.length);for(let e=0;e<a.length;e+=1)s[e]=a.charCodeAt(e);const o=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=Ac(e.length),s=n.length+t.length+1+a.length+e.length,o=Ac(s),i=new Uint8Array(1+o.length+s);let r=0;return i[r]=48,r+=1,i.set(o,r),r+=o.length,i.set(n,r),r+=n.length,i.set(t,r),r+=t.length,i[r]=4,r+=1,i.set(a,r),r+=a.length,i.set(e,r),i}(s);return await crypto.subtle.importKey("pkcs8",o.buffer,Sc,!1,["sign"])}async function Pc({timestamp:e,rooms:t}){const n=t.map((e=>Object.keys(e).sort().map((t=>`${t}=${e[t]}`)).join("&"))).join(";"),a=T.default.v4(),s=`nonceStr=${a}&timestamp=${e}&data=${n}==`,o=(new TextEncoder).encode(s),i=await Rc("-----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:Tc(await crypto.subtle.sign(Sc,i,o)),nonceStr:a}}async function Dc(){const e=wc(),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():""}))),s=await Pc({timestamp:n,rooms:a});if(!s||!s.signature)throw new Error("Signature is undefined");t.forEach((t=>{e.updateSession(t.sessionId,{syncState:"SYNCING"})}));const o={signature:s.signature,nonceStr:s.nonceStr,timestamp:n,rooms:a},i=Ge();return await i.http.post("/api/v3/user-event/room",o),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 Uc=["live","recorded"];class kc{constructor(e){this.storage=wc(),this.client=Ge(),this.room=e}async createWatchSession(e){if(!Uc.includes(this.room.status))throw new Qe("room is not in watchable state",5e5,"error");const t=("live"===this.room.status?"room_":"room_playback_")+T.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 Dc(),this.client.log("room/RoomAnalytics: syncWatchSessions completed")}catch(e){console.error("Failed to sync watch sessions:",e)}}),e)}}const jc=e=>Object.assign(Object.assign({},e),{get post(){var t;if("post"===e.referenceType)return null===(t=nt(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=nt(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;const n=null===(t=nt(["user","get",e.createdBy]))||void 0===t?void 0:t.data;return n?_t(n):n},get childRooms(){return e.childRoomIds&&0!==e.childRoomIds.length?e.childRoomIds.map((e=>{var t;const n=null===(t=nt(["room","get",e]))||void 0===t?void 0:t.data;if(n)return jc(n)})).filter(Tr):[]},participants:e.participants.map((e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=nt(["user","get",e.userId]))||void 0===t?void 0:t.data;return n?_t(n):n}}))),getLiveChat:()=>(async e=>{var t;const n=Ge();if(n.log("room/getLiveChat",e.roomId),e.liveChannelId){const n=null===(t=nt(["channel","get",e.liveChannelId]))||void 0===t?void 0:t.data;if(n)return Ps(Ds(n));const{data:a}=await gc(e.liveChannelId);return Ps(Ds(a))}if(e.createdBy===n.userId){const{data:t}=await mc({type:"live",postId:e.referenceId,roomId:e.roomId});return st(["room","get",e.roomId],{liveChannelId:t.channelId}),t}})(e),createInvitation:t=>Xr({type:"livestreamCohostInvite",targetType:"room",targetId:e.roomId,userIds:[t]}),getInvitations:async()=>{const{data:t}=await tc({targetId:e.roomId,targetType:"room",type:"livestreamCohostInvite"});return t},analytics(){return new kc(this)}}),Ec=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=nt(["file","get",e.fileId]))||void 0===t?void 0:t.data}})))}),Mc=e=>{const t=po();return Object.assign(Object.assign({},e),{analytics:{markAsClicked:(n,a,s)=>{t.markProductAsClicked(e,n,a,s)},markAsViewed:(n,a,s)=>{t.markProductAsViewed(e,n,a,s)}}})},qc=e=>{var t,n,a;if(!e)return e;if("video"===e.type){const a=null===(n=null===(t=e.attributes)||void 0===t?void 0:t.metadata)||void 0===n?void 0:n.video;return Object.assign(Object.assign({},e),{getWidth:()=>{var e;return null!==(e=null==a?void 0:a.width)&&void 0!==e?e:0},getHeight:()=>{var e;return null!==(e=null==a?void 0:a.height)&&void 0!==e?e:0},getRotation:()=>{var e;return null!==(e=null==a?void 0:a.rotation)&&void 0!==e?e:0}})}if("image"===e.type){const t=null===(a=e.attributes)||void 0===a?void 0:a.metadata;return Object.assign(Object.assign({},e),{getWidth:()=>{var e;return null!==(e=null==t?void 0:t.width)&&void 0!==e?e:0},getHeight:()=>{var e;return null!==(e=null==t?void 0:t.height)&&void 0!==e?e:0}})}return e},xc=e=>Wn(e,{childrenPosts:e.children.map((e=>{var t;return null===(t=nt(["post","get",e]))||void 0===t?void 0:t.data})).filter(Tr).map(xc),analytics:{markAsViewed:()=>{po().markPostAsViewed(e.postId)},markAsMeaningfullyViewed:t=>{po().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=nt(["product","get",e.productId]))||void 0===t?void 0:t.data;return Object.assign(Object.assign({},e),{product:n?Mc(n):void 0})})(e))))&&void 0!==n?n:[]},get latestComments(){return e.comments&&e.comments.map((e=>{var t;const n=null===(t=nt(["comment","get",e]))||void 0===t?void 0:t.data;return n?vc(n):null})).filter(Boolean)||[]},get creator(){const t=nt(["user","get",e.postedUserId]);if(null==t?void 0:t.data)return _t(t.data)},get targetCommunity(){var t;const n=null===(t=nt(["community","get",e.targetId]))||void 0===t?void 0:t.data;if(n)return lc(n)},getImageInfo(){var t,n;return function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"image"!==e.dataType)}(e)?qc(null===(n=nt(["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 fc(e)?qc(null===(a=nt(["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 fc(e)?qc(null===(n=nt(["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=nt(["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(!bc(e))return;const a=null===(n=nt(["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?yc(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=nt(["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?Ec(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=nt(["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=nt(["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=nt(["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?jc(a):void 0}}),Kc=(e,t)=>{"message"===e?xt("local.message.updated",{messages:[t]}):"post"===e?xt("post.updated",{posts:[t]}):"comment"===e?xt("comment.updated",{comments:[t]}):"story"===e&&xt("story.updated",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[t]})},Nc=async(e,t,n,a)=>{var s,o,i;const r=Ge();if(r.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Qe("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:c}=await r.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:a});if(r.cache){const a=nt([e,"get",t]);if(!a||(null===(s=a.data.myReactions)||void 0===s?void 0:s.includes(n)))return!0;const d=Object.assign(Object.assign({},a.data),{reactionsCount:a.data.reactionsCount+1,myReactions:[...null!==(o=a.data.myReactions)&&void 0!==o?o:[],n],reactions:Object.assign(Object.assign({},a.data.reactions),{[n]:(null!==(i=a.data.reactions[n])&&void 0!==i?i:0)+1}),updatedAt:(new Date).toISOString()});if("comment"===e)return xt("local.comment.addReaction",{comment:d,reactor:{userId:r.userId,reactionName:n,reactionId:c.addedId}}),!0;if("post"===e)return xt("local.post.addReaction",{post:d,reactor:{userId:r.userId,reactionName:n,reactionId:c.addedId}}),!0;if("story"===e)return xt("local.story.reactionAdded",{story:d,reactor:{userId:r.userId,reactionName:n,reactionId:c.addedId}}),!0;if("message"===e)return ot(["message","get",t],d),xt("local.message.updated",{messages:[d]}),!0}return!0};Nc.optimistically=(e,t,n)=>{var a,s,o,i,r;const c=Ge();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const d=nt([e,"get",t]);if(!(null==d?void 0:d.data)||(null===(a=d.data.myReactions)||void 0===a?void 0:a.includes(n)))return;const l=Object.assign(Object.assign({},d.data),{reactionsCount:d.data.reactionsCount+1,myReactions:[...null!==(s=d.data.myReactions)&&void 0!==s?s:[],n],reactions:Object.assign(Object.assign({},d.data.reactions),{[n]:(null!==(o=d.data.reactions[n])&&void 0!==o?o:0)+1})});return ot([e,"get",t],l,{cachedAt:fe}),Kc(e,l),null!==(r=null===(i=null==l?void 0:l.myReactions)||void 0===i?void 0:i.includes(n))&&void 0!==r&&r};const Fc=(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=nt(["messageMarker","get",Xe("messageMarker")(a)]))||void 0===n?void 0:n.data})(e))&&void 0!==n?n:{readCount:0,deliveredCount:0}},_c=(e,t)=>{const n=t.publicId!==t.messageId;return(async(e,t,n,a)=>{var s,o;const i=Ge();if(i.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Qe("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:r}=await i.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:a}});if(i.cache){const a=nt([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!==(s=a.data.myReactions)&&void 0!==s?s:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},a.data.reactions),{[n]:Math.max(0,(null!==(o=a.data.reactions[n])&&void 0!==o?o:0)-1)}),updatedAt:(new Date).toISOString()});if("comment"===e)return xt("local.comment.removeReaction",{comment:c,reactor:{reactionId:r.removedId,reactionName:n,userId:i.userId}}),!0;if("post"===e)return xt("local.post.removeReaction",{post:c,reactor:{reactionId:r.removedId,reactionName:n,userId:i.userId}}),!0;if("story"===e)return xt("local.story.reactionRemoved",{story:c,reactor:{userId:i.userId,reactionName:n,reactionId:r.removedId}}),!0;if("message"===e)return ot(["message","get",t],c),xt("local.message.updated",{messages:[c]}),!0}return!0})("message",n?t.publicId:t.messageId,e,n?3:5)},Bc=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=nt(["event","get",e.eventId]);if(null==t?void 0:t.data)return t.data},get user(){const t=nt(["user","get",e.userId]);if(null==t?void 0:t.data)return _t(t.data)}}),Lc=e=>Object.assign(Object.assign({},e),{users:e.users.map(ga)}),Qc=(e,t)=>{const n=Ge();return qt(n,e,e,(e=>{const a=Lc(e);if(n.cache){Nn(a);const e=nt(["event","get",a.events[0].eventId]);t(e.data)}else t(a.events[0])}))},Vc=(e,t)=>{const n=Ge();return qt(n,e,e,(e=>{const a=Bc(e);if(n.cache){Nn(a);const e=nt(["eventResponse","get",a.eventResponses[0].userId]);t(e.data)}else t(a.eventResponses[0])}))},Jc=async e=>{const t=Ge();t.log("event/getMyRSVP",e);const{data:n}=await t.http.get(`/api/v1/events/${e}/me/rsvp`),a=Bc(n),s=t.cache&&Date.now();return t.cache&&Nn(a,{cachedAt:s}),{data:$c(a.eventResponses[0]),cachedAt:s}};var Hc;Jc.locally=e=>{const t=Ge();if(t.log("event/getMyRSVP.locally",e),!t.cache)return;const n=nt(["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"}(Hc||(Hc={}));class zc extends fr{async getRequest(e,t){const{limit:n=me,eventId:a}=e,s=_n(e,["limit","eventId"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get(`/api/v1/events/${a}/rsvp`,{params:Object.assign(Object.assign({},s),{options:o})});return i}}class Gc extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.eventResponses.map(Xe("eventResponse"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.eventResponses.map(Xe("eventResponse"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===Hc.OnRSVPCreated&&(a.data=[...new Set([t.userId,...a.data])]),e===Hc.OnEventDeleted&&(a.data=a.data.filter((e=>e!==t.eventId))),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Yc=e=>Qc("event.created",e),Wc=e=>Qc("event.updated",e),Xc=e=>Qc("event.deleted",e),Zc=e=>Qc("local.event.created",e),ed=e=>Qc("local.event.updated",e),td=e=>Qc("local.event.deleted",e),nd=e=>Vc("event.rsvp.created",e),ad=e=>Vc("event.rsvp.updated",e),sd=e=>Vc("local.rsvp.created",e),od=e=>Vc("local.rsvp.updated",e);class id extends Or{constructor(e,t){const n=R.default(e),a=["eventResponse","collection",n];super(new zc(e),n,a,t),this.query=e,this.queryStreamController=new Gc(this.query,this.cacheKey,this.notifyChange.bind(this),Bc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:nd,action:Hc.OnRSVPCreated},{fn:ad,action:Hc.OnRSVPUpdated},{fn:sd,action:Hc.OnRSVPCreated},{fn:od,action:Hc.OnRSVPUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a;const s=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=s.data.map((e=>nt(["eventResponse","get",e]))).filter(Tr).map((({data:e})=>$c(e)));(this.shouldNotify(o)||"event"!==e)&&this.callback({data:o,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}const rd=(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getRSVPs: (tmpid: ${o}) > listen`);const i=new id(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getRSVPs (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},cd=e=>Object.assign(Object.assign({},e),{get creator(){const t=nt(["user","get",e.userId]);if(null==t?void 0:t.data)return _t(t.data)},get targetCommunity(){if(!e.originId)return;const t=nt(["community","get",e.originId]);return(null==t?void 0:t.data)?lc(t.data):void 0},get coverImage(){if(!e.coverImageFileId)return;const t=nt(["file","get",e.coverImageFileId]);return(null==t?void 0:t.data)?t.data:void 0},get post(){if(!e.postId)return;const t=nt(["post","get",e.postId]);return(null==t?void 0:t.data)?xc(t.data):void 0},get room(){var t;if(!e.postId)return;const n=null===(t=tt(["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?jc(n[0].data):void 0},createRSVP:async t=>{const{data:n}=await(async(e,t)=>{const n=Ge();n.log("event/createRSVP",e,t);const{data:a}=await n.http.post(`/api/v1/events/${e}/rsvp`,{status:t});xt("local.rsvp.created",a);const s=Bc(a),o=n.cache&&Date.now();return n.cache&&Nn(s,{cachedAt:o}),{data:$c(s.eventResponses[0]),cachedAt:o}})(e.eventId,t);return n},updateRSVP:async t=>{const{data:n}=await(async(e,t)=>{const n=Ge();n.log("event/updateRSVP",e,t);const{data:a}=await n.http.put(`/api/v1/events/${e}/rsvp`,{status:t});xt("local.rsvp.updated",a);const s=Bc(a),o=n.cache&&Date.now();return n.cache&&Nn(s,{cachedAt:o}),{data:$c(s.eventResponses[0]),cachedAt:o}})(e.eventId,t);return n},getMyRSVP:async()=>{const{data:t}=await Jc(e.eventId);return t},getRSVPs:(t,n)=>rd(Object.assign({eventId:e.eventId},t),n)}),dd={file:qc,ad:e=>{const t=po(),{image9_16:n,image1_1:a}=e,s=_n(e,["image9_16","image1_1"]);return Object.assign(Object.assign({},s),{analytics:{markAsSeen:n=>{t.markAdAsViewed(e,n)},markLinkAsClicked:n=>{t.markAdAsClicked(e,n)}},get advertiser(){var t,n;const a=null===(t=nt(["advertiser","get",e.advertiserId]))||void 0===t?void 0:t.data;if(!a)return;const s=null===(n=nt(["file","get",a.avatarFileId]))||void 0===n?void 0:n.data;return Object.assign(Object.assign({},a),{avatar:s})},get image1_1(){const e=nt(["file","get",a]);if(e)return e.data||void 0},get image9_16(){const e=nt(["file","get",n]);if(e)return e.data||void 0}})},comment:vc,post:xc,user:_t,category:dc,stream:yc,story:e=>{const t=po(),n=nt(["storyTarget","get",e.targetId]),a=nt(["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=nt(["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:s}=a;return s||void 0},get imageData(){var t,n;if(!(null===(t=e.data)||void 0===t?void 0:t.fileId))return;const a=nt(["file","get",null===(n=e.data)||void 0===n?void 0:n.fileId]);if(!a)return;const{data:s}=a;return s?Object.assign(Object.assign({},s),{fileUrl:`${s.fileUrl}?size=full`}):void 0},get community(){if("community"===e.targetType&&(null==a?void 0:a.data))return lc(a.data)},get communityCategories(){if("community"!==e.targetType)return;if(!a)return;const{data:{categoryIds:t}}=a;return 0!==t.length?t.map((e=>{const t=nt(["category","get",e]);return(null==t?void 0:t.data)||void 0})).filter((e=>void 0!==e)):void 0},get creator(){const t=nt(["user","get",e.creatorPublicId]);if(null==t?void 0:t.data)return _t(t.data)},get storyTarget(){if(null==n?void 0:n.data)return hc(n.data)},get isSeen(){const t=nt(["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,s=new Date(null==n?void 0:n.data.lastStorySeenExpiresAt).getTime()||0,o=new Date(e.expiresAt).getTime();return Math.max(a,s)>=o}})},storyTarget:hc,message:e=>{const t=_n(e,["creatorPrivateId"]);return Object.assign(Object.assign({},t),{get readCount(){return Fc(e).readCount},get deliveredCount(){return Fc(e).deliveredCount},get creator(){var t;return null===(t=nt(["user","get",e.creatorId]))||void 0===t?void 0:t.data},markRead:()=>yi(e),addReaction:t=>((e,t)=>{const n=t.publicId!==t.messageId;return Nc("message",n?t.publicId:t.messageId,e,n?3:5)})(t,e),removeReaction:t=>_c(t,e)})},reactor:e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=nt(["user","get",e.userId]))||void 0===t?void 0:t.data;if(n)return _t(n)}}),channel:Ps,pinnedPost:e=>{var t;const n=nt(["post","get",e.referenceId]),a=null===(t=tt(["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 xc(n.data)},get target(){const e=nt(["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})=>nt(["user","get",e]))).filter(Tr).map((({data:e})=>e)).map((e=>_t(e))),get event(){const t=nt(["event","get",e.actionReferenceId]);if(null==t?void 0:t.data)return t.data}}),community:lc,invitation:ec,joinRequest:$r,channelMember:xa,room:jc,event:cd,eventResponse:$c,product:Mc,poll:Ec},ld=async e=>{const t=Ge();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}}),s=Ws(a),o=t.cache&&Date.now();return t.cache&&Nn(s,{cachedAt:o}),xt("user.fetched",a),{data:s.users.map((e=>dd.user(e))),cachedAt:o}};ld.locally=e=>{var t;const n=Ge();if(n.log("user/getUsers.locally",e),!n.cache)return;const a=e.map((e=>nt(["user","get",e]))).filter(Boolean),s=a.map((({data:e})=>dd.user(e))),o=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:s,cachedAt:o.cachedAt}};const ud=async(e,t)=>{var n;const a=Ge();a.log("user/flagUser",{userId:e,options:t});const s=(e=>{if(!e)return;const t={};return void 0!==e.reportType&&(t.reportType=e.reportType),void 0!==e.reason&&(t.reason=e.reason),void 0!==e.comment&&(t.comment=e.comment),Object.keys(t).length>0?t:void 0})(t),{data:o}=await a.http.post(`/api/v4/me/flags/${encodeURIComponent(e)}`,s),i=Ws(o);return a.cache&&Nn(i),xt("user.flagged",o),null!==(n=i.users.find((t=>t.userId===e)))&&void 0!==n?n:i.users[0]},hd=e=>oo("user.updated",e),md=e=>oo("user.flagged",e),gd=e=>oo("user.unflagged",e),pd=e=>oo("user.flagCleared",e),yd=e=>oo("user.fetched",e),vd=async e=>{const t=Ge();t.log("user/getUser",e),Zn("user",e);try{const{data:n}=await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`),a=t.cache&&Date.now(),s=Ws(n);return t.cache&&Nn(s,{cachedAt:a}),xt("user.fetched",n),{data:s.users.find((t=>t.userId===e)),cachedAt:a}}catch(t){throw Re(null==t?void 0:t.code)&&Fn("user",e),t}};vd.locally=e=>{const t=Ge();if(t.log("user/getUser.locally",e),!t.cache)return;const n=nt(["user","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class fd extends fr{async getRequest(e,t){const{limit:n=me}=e,a=_n(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},a),{options:s,isDeleted:!1})});return o}}class bd extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.users.map(Xe("user"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Xe("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=nt(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],at(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Id;!function(e){e.OnUserDeleted="onUserDeleted",e.OnUserUpdated="onUserUpdated",e.OnUserFlagged="onUserFlagged",e.OnUserUnflagged="onUserUnflagged",e.OnUserFlagCleared="onUserFlagCleared"}(Id||(Id={}));class Cd extends Or{constructor(e,t){const n=R.default(e),a=["user","collection",n];super(new fd(e),n,a,t),this.query=e,this.queryStreamController=new bd(this.query,this.cacheKey,this.notifyChange.bind(this),Ws),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:io,action:Id.OnUserDeleted},{fn:hd,action:Id.OnUserUpdated},{fn:md,action:Id.OnUserFlagged},{fn:gd,action:Id.OnUserUnflagged},{fn:pd,action:Id.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["user","get",e]))).filter(Tr).map((({data:e})=>e)).map(dd.user))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;const n=(()=>"firstCreated"===this.query.sortBy?It:wt)();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 wd extends fr{async getRequest(e,t){const{limit:n=me}=e,a=_n(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v4/me/user-blocks",{params:Object.assign(Object.assign({},a),{options:s,isDeleted:!1})});return o}}var Sd;!function(e){e.OnBlocked="onBlocked",e.OnUnblocked="onUnblocked"}(Sd||(Sd={}));class Od extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.users.map(Xe("user"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Xe("user"))])]}))}}reactor(e){return t=>{var n,a;const s=e===Cr.OnFollowed||e===Sd.OnUnblocked,o=e===Sd.OnBlocked;if(s||o){const e=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data,s=null!==(a=null==e?void 0:e.data)&&void 0!==a?a:[],i=o?[...new Set([...s,t.userId])]:s.filter((e=>e!==t.userId));at(this.cacheKey,Object.assign(Object.assign({},e),{data:i}))}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Td=(e,t,n)=>a=>e((e=>{var s;if(!e)return e;const o=[n,"get",`${e[t]}`],i=null===(s=nt(o))||void 0===s?void 0:s.data;return i?a(i):void 0}));class Ad extends Or{constructor(e,t){const n=R.default(e),a=["blockedUsers","collection",n];super(new wd(e),n,a,t),this.query=e,this.queryStreamController=new Od(this.query,this.cacheKey,this.notifyChange.bind(this),qo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:io,action:Id.OnUserDeleted},{fn:Td(mr,"to","user"),action:Cr.OnFollowed},{fn:Td(sr,"to","user"),action:Cr.OnFollowed},{fn:e=>Ho((t=>{var n;if(t.from!==Ge().userId)return;const a=null===(n=nt(["user","get",t.to]))||void 0===n?void 0:n.data;a&&e(a)})),action:Sd.OnBlocked},{fn:e=>zo((t=>{var n;if(t.from!==Ge().userId)return;const a=null===(n=nt(["user","get",t.to]))||void 0===n?void 0:n.data;a&&e(a)})),action:Sd.OnUnblocked}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["user","get",e]))).filter(Tr).map((({data:e})=>e)).map(dd.user))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,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 Rd extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.users.map(Xe("user"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Xe("user"))])]}))}}reactor(e){return t=>{var n,a;if(t&&(e===Sd.OnBlocked||e===Sd.OnUnblocked)){const s=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data,o=null!==(a=null==s?void 0:s.data)&&void 0!==a?a:[],i=e===Sd.OnBlocked?[...new Set([...o,t.userId])]:o.filter((e=>e!==t.userId));at(this.cacheKey,Object.assign(Object.assign({},s),{data:i}))}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Pd extends fr{async getRequest(e,t){const{limit:n=ge}=e,a=_n(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v4/me/blockers",{params:Object.assign(Object.assign({},a),{options:s,isDeleted:!1})});return o}}class Dd extends Or{constructor(e){const t=`blocking-users-${Ge().userId}`,n={},a=["blockingUsers","collection",t];super(new Pd(n),t,a,e),this.queryStreamController=new Rd(n,this.cacheKey,this.notifyChange.bind(this),Fo),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:io,action:Id.OnUserDeleted},{fn:e=>Ho((t=>{var n;if(t.to!==Ge().userId)return;const a=null===(n=nt(["user","get",t.from]))||void 0===n?void 0:n.data;a&&e(a)})),action:Sd.OnBlocked},{fn:e=>zo((t=>{var n;if(t.to!==Ge().userId)return;const a=null===(n=nt(["user","get",t.from]))||void 0===n?void 0:n.data;a&&e(a)})),action:Sd.OnUnblocked}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["user","get",e]))).filter(Tr).map((({data:e})=>e)).map(dd.user))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,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 Ud extends fr{async getRequest(e,t){const{limit:n=me,displayName:a}=e,s=_n(e,["limit","displayName"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},s),{keyword:a,options:o,isDeleted:!1})});return i}}class kd extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.users.map(Xe("user"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(Xe("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=nt(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],at(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class jd extends Or{constructor(e,t){var n;const a=R.default(e),s=["user","collection",a];super(new Ud(e),a,s,t),this.query=Object.assign(Object.assign({},e),{filter:null!==(n=e.filter)&&void 0!==n?n:"all"}),this.queryStreamController=new kd(this.query,this.cacheKey,this.notifyChange.bind(this),Ws),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:io,action:Id.OnUserDeleted},{fn:hd,action:Id.OnUserUpdated},{fn:md,action:Id.OnUserFlagged},{fn:gd,action:Id.OnUserUnflagged},{fn:pd,action:Id.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["user","get",e]))).filter(Tr).map((({data:e})=>e)).map(dd.user))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,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 Ed=async({viewId:e,viewedType:t,limit:n,token:a})=>{const s=Ge(),o={};a?o.token=a:o.limit=n;const i=`/api/v1/analytics/views/${"post"===t?"posts":"stories"}/${e}/users`,r=await s.http.get(i,{params:o});return Nn(r.data),r.data};var Md;!function(e){e.DEFAULT="default",e.PARTIAL="partial"}(Md||(Md={}));var qd=Object.freeze({__proto__:null,Relationship:Er,getUserByIds:ld,updateUser:async(e,t)=>{const n=Ge();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})),s=Ws(a),o=n.cache&&Date.now();return n.cache&&Nn(s,{cachedAt:o}),xt("user.updated",a),{data:s.users.find((t=>t.userId===e)),cachedAt:o}},flagUser:ud,unflagUser:async e=>{const t=Ge();t.log("user/unflag",e);const{data:n}=await t.http.delete(`/api/v4/me/flags/${encodeURIComponent(e)}`),a=Ws(n);return t.cache&&Nn(a),xt("user.unflagged",n),!!a},isUserFlaggedByMe:async e=>{const t=Ge();t.log("user/isUserFlaggedByMe",e);const{data:{isFlagByMe:n}}=await t.http.get(`/api/v3/users/${e}/isFlagByMe`);return n},getAllBlockedUsers:async()=>{Ge().log("user/getAllBlockedUsers");const e=No();return await e.ensureFetched(),e.getCachedUsers()},getAllBlockingUsers:async()=>{Ge().log("user/getAllBlockingUsers");const e=$o();return await e.ensureFetched(),e.getCachedUsers()},onUserUpdated:hd,onUserDeleted:io,onUserFlagged:md,onUserUnflagged:gd,onUserFlagCleared:pd,getUser:(e,t)=>jr(e,(e=>t(Object.assign(Object.assign({},e),{data:e.data?dd.user(e.data):e.data}))),"userId",vd,[yd,hd,io,md,gd,pd]),getUsers:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`liveUsers(tmpid: ${o}) > listen`);const i=new Cd(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`liveUsers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getBlockedUsers:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getBlockedUsers(tmpid: ${o}) > listen`);const i=new Ad(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getBlockedUsers(tmpid: ${o}) > dispose`),r.forEach((e=>e())),it(c)}},getBlockingUsers:e=>{const{log:t,cache:n}=Ge();n||console.log(ye);const a=Date.now();t(`getBlockingUsers(tmpid: ${a}) > listen`);const s=new Dd(e),o=s.startSubscription(),i=s.getCacheKey();return o.push((()=>it(i))),()=>{t(`getBlockingUsers(tmpid: ${a}) > dispose`),o.forEach((e=>e())),it(i)}},searchUserByDisplayName:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`liveSearchUsers(tmpid: ${o}) > listen`);const i=new jd(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`liveSearchUsers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getReachedUsers:(e,t)=>{let n=(e=!1)=>{};const{log:a,cache:s}=Ge(),o=["viewedUsers","collection",{viewId:e.viewId,viewedType:e.viewedType}];s||console.log(ye);const i=Date.now();a(`getReachUsers(tmpid: ${i}) > listen`);const{limit:r,viewId:c,viewedType:d}=e;return n=(e=!1)=>{var a,s,i;const l=null===(a=nt(o))||void 0===a?void 0:a.data,u=null!==(s=null==l?void 0:l.data)&&void 0!==s?s:[];if(!e&&u.length>0&&!(null==l?void 0:l.params.page))return;const h=Fe(Ed,{viewId:c,viewedType:d,limit:r||10,token:e||null===(i=null==l?void 0:l.params.page)||void 0===i?void 0:i.next});Be(h,(e=>{var a,s,i,r,c;let d=null!==(i=null===(s=null===(a=nt(o))||void 0===a?void 0:a.data)||void 0===s?void 0:s.data)&&void 0!==i?i:[];(null===(r=e.data)||void 0===r?void 0:r.users)&&(d=[...new Set([...d,...e.data.users.map((({userId:e})=>e))])]);const l={loading:e.loading,params:{page:null===(c=e.data)||void 0===c?void 0:c.paging},data:d||[]};at(o,l),(e=>{var a,s;let o=[];(null==e?void 0:e.data)&&(o=e.data.map((e=>nt(["user","get",e]))).filter(Boolean).map((e=>null==e?void 0:e.data))||[]),t({onNextPage:n,data:o,hasNextPage:!!(null===(s=null===(a=e.params)||void 0===a?void 0:a.page)||void 0===s?void 0:s.next),loading:e.loading||!1})})(l)}),_e(pe,2e3))},n(!0),()=>{a(`getReachUsers(tmpid: ${i}) > dispose`),it(o)}},get AmityUserSearchMatchType(){return Md}});const xd=async e=>{const t=Ge();t.log("file/getFile",e);const{data:n}=await t.http.get(`/api/v3/files/${e}`),a=t.cache&&Date.now();return t.cache&&Nn({files:[n]},{cachedAt:a}),{data:qc(n),cachedAt:a}};xd.locally=e=>{const t=Ge();if(t.log("file/getFile.locally",e),!t.cache)return;const n=nt(["file","get",e]);return n?{data:qc(n.data),cachedAt:n.cachedAt}:void 0};const Kd=async(e,t,n)=>{const a=Ge();a.log("file/uploadVideo",e);const s=e.getAll("files");if(!s.length)throw new Error("The formData object must have a `files` key.");const o=xi().getFileAccessType();e.append("accessType",o),e.append("preferredFilename",s[0].name),t&&e.append("feedType",t);const i="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:r}=await a.upload.post("/api/v4/videos",e,{headers:i,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),c=a.cache&&Date.now();return a.cache&&Nn({files:r},{cachedAt:c}),{data:r.map((e=>qc(e))),cachedAt:c}},Nd=async(e,t,n)=>{const a=Ge();a.log("file/uploadImage",e);const s=e.getAll("files");if(null==s?void 0:s.length)console.warn("Deprecation Warning: `files` is deprecated, please use `file` instead."),e.append("preferredFilename",s[0].name);else{const t=e.get("file");if(!t)throw new Error("The formData object must have a `file` or `files` key");e.append("preferredFilename",t.name),n&&e.append("altText",n)}const o=xi().getFileAccessType();e.append("accessType",o);const i="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:r}=await a.upload.post("/api/v4/images",e,{headers:i,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),c=a.cache&&Date.now();return a.cache&&Nn({files:r},{cachedAt:c}),{data:r.map((e=>qc(e))),cachedAt:c}};var Fd=Object.freeze({__proto__:null,getFile:xd,uploadFile:async(e,t)=>{const n=Ge();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 s=xi().getFileAccessType();e.append("accessType",s),e.append("preferredFilename",a[0].name);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await n.upload.post("/api/v4/files",e,{headers:o,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),r=n.cache&&Date.now();return n.cache&&Nn({files:i},{cachedAt:r}),{data:i,cachedAt:r}},deleteFile:async e=>{const t=Ge();return t.log("file/deleteFile",e),await t.http.delete(`/api/v3/files/${e}`),it(["file","get",e],!0),{success:!0}},fileUrlWithSize:(e,t)=>`${e}?size=${t}`,uploadVideo:Kd,uploadImage:Nd,updateAltText:async(e,t)=>{const n=Ge();n.log("file/updateAltText",t);const{data:a}=await n.http.put(`/api/v3/files/${e}`,{altText:t}),s=n.cache&&Date.now();return n.cache&&Nn({files:[a]},{cachedAt:s}),!0},uploadClip:async(e,t,n)=>{const a=Ge();a.log("file/uploadClip",e);const s=e.get("files");if(!s)throw new Error("The formData object must have a `files` key.");const o=xi().getFileAccessType();e.append("accessType",o),e.append("preferredFilename",s.name),t&&e.append("feedType",t);const i="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:r}=await a.upload.post("/api/v4/clips",e,{headers:i,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),c=a.cache&&Date.now();return a.cache&&Nn({files:r},{cachedAt:c}),{data:r,cachedAt:c}},uploadAudio:async(e,t)=>{const n=Ge();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 s=a[0],o=xi().getFileAccessType();e.append("accessType",o),e.append("preferredFilename",s.name);const{data:i}=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))}}),r=n.cache&&Date.now();return n.cache&&Nn({files:i},{cachedAt:r}),{data:i,cachedAt:r}}});const _d=async e=>{const t=Ge();t.log("role/queryRoles",e);const n=null!=e?e:{},{limit:a=10,queryToken:s,displayName:o,sortBy:i}=n,r=_n(n,["limit","queryToken","displayName","sortBy"]),c=s?{token:s}:a?{limit:a}:void 0,{data:d}=await t.http.get("/api/v3/roles",{params:Object.assign(Object.assign({},r),{keyword:o,sortBy:i,options:c})}),{paging:l}=d,u=_n(d,["paging"]),{roles:h}=u,m=t.cache&&Date.now();t.cache&&Nn(u,{cachedAt:m});const g=Ee(l.next);return{data:h,cachedAt:m,prevPage:Ee(l.previous),nextPage:g,paging:l}};_d.locally=e=>{Ge().log("role/queryRoles.locally",e)};const Bd=async e=>{const t=Ge();t.log("role/getRole",e);const{data:n}=await t.http.get(`/api/v3/roles/${e}`),a=t.cache&&Date.now();return t.cache&&Nn({roles:n},{cachedAt:a}),{data:n.find((t=>t.roleId===e)),cachedAt:a}};Bd.locally=e=>{const t=Ge();if(t.log("role/getRole.locally",e),!t.cache)return;const n=nt(["role","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const $d=async(e,t=!1)=>{const n=Ge();let a;n.log("message/getMessage",e),Zn("message",e);try{const{data:t}=await n.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);a=await ua(t)}catch(t){throw Re(null==t?void 0:t.code)&&Fn("message",e),t}const s=n.cache&&Date.now();n.cache&&Nn(a,{cachedAt:s});const{messages:o}=a;return xt("local.message.fetched",{messages:o}),{data:o.find((t=>t.messageId===e)),cachedAt:s}};$d.locally=e=>{const t=Ge();if(t.log("message/getMessage.locally",e),!t.cache)return;const n=nt(["message","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class Ld{constructor(e,t,n){this.postId=e,this.latestCreatedAt=t,this.serverCommentCount=n}}class Qd{constructor(e,t,n){this.postId=e,this.commentId=t,this.createdAt=n}}class Vd{constructor(e,t){this.postId=e,this.commentId=t}}class Jd{constructor(e,t){this.latestCommentCreatedAt=e,this.serverCommentCount=t,this.createdCommentIds=new Set,this.deletedCommentIds=new Set}}class Hd{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,Hd.BATCH_SIZE),t=new Set;e.forEach((e=>{let n=!1;e instanceof Ld?n=this.processResetTaskInternal(e):e instanceof Qd?n=this.processCreateTaskInternal(e):e instanceof Vd&&(n=this.processDeleteTaskInternal(e)),n&&t.add(e.postId)})),t.forEach((e=>{const t=this.computeCommentCount(e);Hd.publishUpdate(e,t)})),this.isProcessing=!1,this.tasks.length>0&&this.processCommentChangeTask()}processResetTaskInternal(e){return this.commentChangeTracker.set(e.postId,new Jd(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];st(a,{localCommentCount:t});const s=null===(n=nt(a))||void 0===n?void 0:n.data;s&&xt("local.post.updated",{posts:[s]})}}let zd;Hd.BATCH_SIZE=50;var Gd=()=>(zd||(zd=new Hd),zd);const Yd=e=>{const{posts:t,postChildren:n,videoStreamings:a}=e,s=_n(e,["posts","postChildren","videoStreamings"]),o=xr({communities:s.communities}),i=s.communityUsers.map((e=>{const t=s.users.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),r=Mr(o,i);let c=[];const d=t.map((t=>{var n,o,i,r;const d=null===(n=s.feeds.find((e=>e.feedId===t.feedId)))||void 0===n?void 0:n.feedType,l=e.postChildren.filter((e=>e.parentPostId===t.postId));var u,h,m;l.length>0&&bc(l[0])&&(u=a,h=null===(o=l[0].data)||void 0===o?void 0:o.streamId,m=t.postId,c=h?u.map((e=>e.streamId===h?Object.assign(Object.assign({},e),{referenceType:"post",referenceId:m,postId:m}):e)):u);const g=(e.comments||[]).filter((e=>"post"===e.referenceType&&e.referenceId===t.postId)),p=0===g.length?(new Date).toISOString():g.map((e=>e.createdAt)).sort().at(-1);return Gd().queueCommentChangeTask(new Ld(t.postId,p,null!==(i=t.commentsCount)&&void 0!==i?i:0)),Object.assign(Object.assign({},t),{childPosts:l,feedType:d,localCommentCount:null!==(r=t.localCommentCount)&&void 0!==r?r:t.commentsCount,pinnedProductId:null==t?void 0:t.pinnedProductId})}));return Object.assign(Object.assign({},s),{postChildren:n,videoStreamings:c,posts:d,communities:r,communityUsers:i})},Wd=e=>{var{searchResult:t,polls:n}=e,a=_n(e,["searchResult","polls"]);const s=Yd(a);return Object.assign(Object.assign({},s),{polls:n})},Xd=async e=>{const t=Ge();let n;t.log("post/getPost",e),Zn("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw Re(null==t?void 0:t.code)&&Fn("post",e),t}const a=Yd(n),s=t.cache&&Date.now();t.cache&&Nn(a,{cachedAt:s});const{posts:o}=a;return{data:o.find((t=>t.postId===e)),cachedAt:s}};Xd.locally=e=>{const t=Ge();if(t.log("post/getPost.locally",e),!t.cache)return;const n=nt(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Zd=async e=>{const t=Ge();let n;t.log("comment/getComment",e),Zn("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw Re(null==t?void 0:t.code)&&Fn("comment",e),t}const a=t.cache&&Date.now();t.cache&&Nn(n,{cachedAt:a});const{comments:s}=n;return{data:dd.comment(s.find((t=>t.commentId===e))),cachedAt:a}};Zd.locally=e=>{const t=Ge();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=nt(["comment","get",e]);return n?{data:dd.comment(n.data),cachedAt:n.cachedAt}:void 0};const el=(e,t)=>{var n,a;let s,o;if("post"===t)o="post",s=e.posts[0].postId;else if("comment"===t)o="comment",s=e.comments[0].commentId;else{if("story"!==t)throw new Error("Unknown event type");o="story",s=e.stories[0].referenceId}return(null===(a=null===(n=nt([o,"get",s]))||void 0===n?void 0:n.data)||void 0===a?void 0:a.myReactions)||[]},tl=(e,t,n)=>{const[a]=e[t];return Object.assign(Object.assign({},e),{[t]:[Object.assign(Object.assign({},a),{myReactions:n})]})},nl=(e,t,n,a=[])=>{const s=e.split(".")[1];let o=a;if(Ge().userId===t)if(["addReaction","reactionAdded"].includes(s))o.includes(n)||o.push(n);else{if(!["removeReaction","reactionRemoved"].includes(s))throw new Error(`Unknown event type: ${s}`);o=o.filter((e=>e!==n))}return o},al=(e,t)=>{const n=e.split(".")[0],a=el(t,n),s=nl(e,t.reactor.userId,t.reactor.reactionName,a);return tl(t,`${n}s`,s)},sl=(e,t)=>{var n,a;const s=e.split(".")[0];let o=el(t,s);(null==t?void 0:t.reactions)&&t.reactions.length>0&&(o=nl(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,o));const i=tl(t,"stories",o);if(!(null==t?void 0:t.communities)||!(null==t?void 0:t.communityUsers))return i;const r=Mr(t.communities,t.communityUsers);return Object.assign(Object.assign({},i),{communities:r})},ol=async(e,t,n)=>{var a,s,o;const i=Ge();if(i.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Qe("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:r}=await i.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0});if(i.cache){const c=nt([e,"get",t]);if(!c||(null===(a=c.data.myReactions)||void 0===a?void 0:a.includes(n)))return!0;const d=Object.assign(Object.assign({},c.data),{reactionsCount:c.data.reactionsCount+1,myReactions:[...null!==(s=c.data.myReactions)&&void 0!==s?s:[],n],reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:(null!==(o=c.data.reactions[n])&&void 0!==o?o:0)+1}),updatedAt:(new Date).toISOString()});if("comment"===e)return xt("local.comment.addReaction",{comment:d,reactor:{userId:i.userId,reactionName:n,reactionId:r.addedId}}),!0;if("post"===e)return xt("local.post.addReaction",{post:d,reactor:{userId:i.userId,reactionName:n,reactionId:r.addedId}}),!0;if("story"===e)return xt("local.story.reactionAdded",{story:d,reactor:{userId:i.userId,reactionName:n,reactionId:r.addedId}}),!0}return!0};ol.optimistically=(e,t,n)=>{var a,s,o,i,r;const c=Ge();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const d=nt([e,"get",t]);if(!(null==d?void 0:d.data)||(null===(a=d.data.myReactions)||void 0===a?void 0:a.includes(n)))return;const l=Object.assign(Object.assign({},d.data),{reactionsCount:d.data.reactionsCount+1,myReactions:[...null!==(s=d.data.myReactions)&&void 0!==s?s:[],n],reactions:Object.assign(Object.assign({},d.data.reactions),{[n]:(null!==(o=d.data.reactions[n])&&void 0!==o?o:0)+1})});return ot([e,"get",t],l,{cachedAt:fe}),Kc(e,l),null!==(r=null===(i=null==l?void 0:l.myReactions)||void 0===i?void 0:i.includes(n))&&void 0!==r&&r};const il=async(e,t,n)=>{var a,s;const o=Ge();if(o.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Qe("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:"message"===e?5:void 0}});if(o.cache){const r=nt([e,"get",t]);if(!r)return!0;const c=Object.assign(Object.assign({},r.data),{reactionsCount:Math.max(0,r.data.reactionsCount-1),myReactions:(null!==(a=r.data.myReactions)&&void 0!==a?a:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},r.data.reactions),{[n]:Math.max(0,(null!==(s=r.data.reactions[n])&&void 0!==s?s:0)-1)}),updatedAt:(new Date).toISOString()});if("comment"===e)return xt("local.comment.removeReaction",{comment:c,reactor:{reactionId:i.removedId,reactionName:n,userId:o.userId}}),!0;if("post"===e)return xt("local.post.removeReaction",{post:c,reactor:{reactionId:i.removedId,reactionName:n,userId:o.userId}}),!0;if("story"===e)return xt("local.story.reactionRemoved",{story:c,reactor:{userId:o.userId,reactionName:n,reactionId:i.removedId}}),!0}return!0};il.optimistically=(e,t,n)=>{var a,s,o,i;const r=Ge();if(r.log("reaction/removeReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!r.cache)return;const c=nt([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 d=Object.assign(Object.assign({},c.data),{reactionsCount:Math.max(0,c.data.reactionsCount-1),myReactions:(null!==(s=c.data.myReactions)&&void 0!==s?s:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:Math.max(0,(null!==(o=c.data.reactions[n])&&void 0!==o?o:0)-1)})});return ot([e,"get",t],d,{cachedAt:fe}),Kc(e,d),!(null===(i=null==d?void 0:d.myReactions)||void 0===i?void 0:i.includes(n))};const rl=e=>{var t;const n=e.posts[0];if(n.parentId){const e=null===(t=nt(["post","get",n.parentPostId]))||void 0===t?void 0:t.data;if(!e)return;at(["post","get",e.postId],Object.assign(Object.assign({},e),{children:e.children.filter((e=>e!==n.postId))}))}else n.children.forEach((e=>st(["post","get",e],{isDeleted:!0})))},cl=(e,t)=>{const n=Ge();return qt(n,e,e,(a=>{var s;if(n.cache){const o=Yd(a),{communities:i}=o;if(Nn(o,void 0,!1),(null==i?void 0:i[0])&&!["post.updated"].includes(e)&&xt("community.updated",{communities:i,categories:[],communityUsers:o.communityUsers,feeds:[],files:[],users:[]}),"post.deleted"===e){const{postId:e,postedUserId:s}=a.posts[0];rl(a);try{Zn("post",e)}catch(e){return}return s!==n.userId&&it(["post","get",e]),t(a.posts[0])}const r=nt(["post","get",a.posts[0].postId]);if(["post.created","post.approved","post.declined"].includes(e)){let t=null===(s=tt(["post","query"]))||void 0===s?void 0:s.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.targetId)===r.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})=>ot(e,t,{cachedAt:-1})))}"post.created"===e&&(e=>{var t;const n=e.posts[0];if(!n.parentId)return;const a=null===(t=nt(["post","get",n.parentPostId]))||void 0===t?void 0:t.data;a&&at(["post","get",a.postId],Object.assign(Object.assign({},a),{children:[...new Set([n.postId,...a.children])]}))})(a),t(r.data)}else t(a.posts[0])}))},dl=(e,t)=>{const n=Ge();return qt(n,e,e,(a=>{if(n.cache){const{communities:n}=a;(null==n?void 0:n[0])&&!["local.post.updated"].includes(e)&&xt("community.updated",{communities:n,categories:[],communityUsers:a.communityUsers,feeds:[],files:[],users:[]});const s=nt(["post","get",a.posts[0].postId]);"local.post.deleted"===e&&rl(a),t(s.data)}else t(a.posts[0])}))},ll=e=>cl("post.created",e),ul=e=>cl("post.updated",e),hl=e=>cl("post.deleted",e),ml=e=>cl("post.approved",e),gl=e=>cl("post.declined",e),pl=e=>cl("post.flagged",e),yl=e=>cl("post.unflagged",e),vl=e=>{const t=Ge();return qt(t,"post.addReaction","post.addReaction",(n=>{if(t.cache){const t=_n(al("post.addReaction",n),["reactor"]);Nn(t);const a=nt(["post","get",n.posts[0].postId]);e(a.data)}else e(n.posts[0])}))},fl=e=>{const t=Ge();return qt(t,"post.removeReaction","post.removeReaction",(n=>{if(t.cache){const t=_n(al("post.removeReaction",n),["reactor"]);Nn(t);const a=nt(["post","get",n.posts[0].postId]);e(a.data)}else e(n.posts[0])}))},bl=(e,t)=>{const n=Ge();return qt(n,e,e,(a=>{var s;if(n.cache){const n=["comment.flagged","comment.unflagged"].includes(e)?(e=>{const t=el(e,"comment");return tl(e,"comments",t)})(a):a;Nn(n,void 0,!1);const{comments:o}=n;if(o.length>0){const n=nt(["comment","get",o[0].commentId]);if(["comment.created"].includes(e)&&o[0].parentId){const e=nt(["comment","get",o[0].parentId]);(null==e?void 0:e.data)&&(e.data.children.includes(o[0].commentId)||at(["comment","get",o[0].parentId],Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,o[0].commentId])]})))}if(["comment.deleted"].includes(e)){if(o[0].parentId){const e=nt(["comment","get",o[0].parentId]);if((null==e?void 0:e.data)&&e.data.children.includes(o[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber-1,children:[...new Set([...e.data.children.filter((e=>e!==o[0].commentId))])]});at(["comment","get",o[0].parentId],t)}}const e=null===(s=tt(["comment","query"]))||void 0===s?void 0:s.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===n.data.referenceId}));null==e||e.map((({key:e,data:t})=>ot(e,t,{cachedAt:-1})))}t(dd.comment(n.data))}}else t(dd.comment(a.comments[0]))}))},Il=(e,t)=>{const n=Ge();return qt(n,e,e,(a=>{var s,o,i,r,c;if(n.cache){const n=a;Nn(n);const{comments:d}=n;if(d.length>0){const n=nt(["comment","get",d[0].commentId]);if(["local.comment.created"].includes(e)){if(d[0].parentId){const e=nt(["comment","get",d[0].parentId]);if((null==e?void 0:e.data)&&!e.data.children.includes(d[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,d[0].commentId])]});at(["comment","get",d[0].parentId],t),setTimeout((()=>{xt("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}else{const e=["post","get",d[0].referenceId],t=null===(s=nt(e))||void 0===s?void 0:s.data;if(t){const n=Object.assign(Object.assign({},t),{comments:[...t.comments,null===(o=d[0])||void 0===o?void 0:o.commentId]});at(e,n)}}const e=null===(i=tt(["comment","query"]))||void 0===i?void 0:i.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})=>ot(e,t,{cachedAt:-1})))}if(["local.comment.deleted"].includes(e)){if(d[0].parentId){const e=nt(["comment","get",d[0].parentId]);if((null==e?void 0:e.data)&&e.data.children.includes(d[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber-1,children:[...new Set([...e.data.children.filter((e=>e!==d[0].commentId))])]});at(["comment","get",d[0].parentId],t),setTimeout((()=>{xt("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}else{const e=["post","get",d[0].referenceId],t=null===(r=nt(e))||void 0===r?void 0:r.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=d[0])||void 0===t?void 0:t.commentId)}))});at(e,n)}}const e=null===(c=tt(["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})=>ot(e,t,{cachedAt:-1})))}t(dd.comment(n.data))}}else t(dd.comment(a.comments[0]))}))},Cl=e=>bl("comment.created",e),wl=e=>bl("comment.updated",e),Sl=e=>bl("comment.deleted",e),Ol=e=>bl("comment.flagged",e),Tl=e=>bl("comment.unflagged",e),Al=e=>{const t=Ge();return qt(t,"comment.addReaction","comment.addReaction",(n=>{if(t.cache){const t=_n(al("comment.addReaction",n),["reactor"]);Nn(t);const a=nt(["comment","get",n.comments[0].commentId]);e(dd.comment(a.data))}else e(dd.comment(n.comments[0]))}))},Rl=e=>{const t=Ge();return qt(t,"comment.removeReaction","comment.removeReaction",(n=>{if(t.cache){const t=_n(al("comment.removeReaction",n),["reactor"]);Nn(t);const a=nt(["comment","get",n.comments[0].commentId]);e(dd.comment(a.data))}else e(dd.comment(n.comments[0]))}))},Pl=(e,t,n)=>{const a=Ge(),s=(a,s,o)=>{a===e&&s===t&&n(o)};if("message"===e){return qt(a,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await ua(e);t.reactions[0]&&(Nn(t),Nn({reactors:t.reactions}),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return qt(a,"post.addReaction","post.addReaction",(e=>{const{reactor:t}=e,n=_n(e,["reactor"]);Nn(n),Nn({reactions:[t]}),s("post",e.posts[0].postId,t)}))}if("story"===e){return qt(a,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=_n(e,["reactions"]);Nn(n),Nn({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}))}return qt(a,"comment.addReaction","comment.addReaction",(e=>{const{reactor:t}=e,n=_n(e,["reactor"]);Nn(n),Nn({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))},Dl=(e,t,n)=>{const a=Ge(),s=(a,s,o)=>{a===e&&s===t&&n(o)};if("message"===e){return qt(a,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await ua(e);t.reactions[0]&&(Nn(t),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return qt(a,"post.removeReaction","post.removeReaction",(e=>{const{reactor:t}=e,n=_n(e,["reactor"]);Nn(n),Nn({reactions:[t]}),s("post",e.posts[0].postId,t)}))}if("story"===e){return qt(a,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=_n(e,["reactions"]);Nn(n),Nn({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}))}return qt(a,"comment.removeReaction","comment.removeReaction",(e=>{const{reactor:t}=e,n=_n(e,["reactor"]);Nn(n),Nn({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))};class Ul extends fr{async getRequest(e,t){const{limit:n=me,referenceType:a}=e,s=_n(e,["limit","referenceType"]),o=t?{token:t}:{limit:n};Ge().log("reaction/queryReactions",e);if(!["post","comment","story","message"].includes(a))throw new Qe("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:i}=await this.http.get("/api/v3/reactions",{params:Object.assign(Object.assign({},s),{referenceType:a,referenceVersion:"message"===a?5:void 0,options:o})});return i}}class kl extends Ir{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=Ge(),s=a.cache&&Date.now();if(a.cache){const{reactions:e}=n,a=_n(n,["reactions"]);Nn(Object.assign(Object.assign({},a),{reactions:e,reactors:null===(t=e[0])||void 0===t?void 0:t.reactors}),{cachedAt:s})}}appendToQueryStream(e,t,n=!1){var a,s,o,i;const r=null!==(s=null===(a=e.reactions[0])||void 0===a?void 0:a.reactors)&&void 0!==s?s:[];if(n)at(this.cacheKey,{data:r.map(Xe("reactor"))});else{const e=null===(o=nt(this.cacheKey))||void 0===o?void 0:o.data,t=null!==(i=null==e?void 0:e.data)&&void 0!==i?i:[];at(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...r.map(Xe("reactor"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(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))),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class jl extends Or{constructor(e,t){const n=R.default(e),a=["reaction","collection",n];super(new Ul(e),n,a,t),this.query=e,this.queryStreamController=new kl(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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=>Pl(this.query.referenceType,this.query.referenceId,e),action:"onAdded"},{fn:e=>Dl(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const a=Ge(),s=(a,s,o)=>{a===e&&s===t&&n(o)};if("message"===e)return qt(a,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await ua(e);t.reactions[0]&&(Nn(t),s("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return qt(a,"local.post.removeReaction","local.post.removeReaction",(e=>{s("post",e.post.postId,e.reactor)}));if("story"===e)return qt(a,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=_n(e,["reactions"]);Nn(n),Nn({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}));return qt(a,"local.comment.removeReaction","local.comment.removeReaction",(e=>{s("comment",e.comment.commentId,e.reactor)}))})(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const a=Ge(),s=(a,s,o)=>{a===e&&s===t&&n(o)};if("message"===e)return qt(a,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await ua(e);t.reactions[0]&&(Nn(t),Nn({reactors:t.reactions}),s("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return qt(a,"local.post.addReaction","local.post.addReaction",(e=>{s("post",e.post.postId,e.reactor)}));if("story"===e)return qt(a,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=_n(e,["reactions"]);Nn(n),Nn({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}));return qt(a,"local.comment.addReaction","local.comment.addReaction",(e=>{s("comment",e.comment.commentId,e.reactor)}))})(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>nt(["reactor","get",e]))).filter(Boolean).map((({data:e})=>dd.reactor(e))))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var El=Object.freeze({__proto__:null,addReaction:ol,removeReaction:il,onReactionAdded:(e,t,n)=>{const a=a=>{Xe(e)(a)===t&&n(a)};if("message"===e){const e=Ge(),t=async e=>{var t;const n=await ua(e),s=nt(["message","get",n.messages[0].messageId]),o=(null===(t=null==s?void 0:s.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Nn(n),o&&a(n.messages[0])};return qt(e,"reaction/onReactionAdded","message.updated",t)}return"post"===e?vl(a):Al(a)},onReactionRemoved:(e,t,n)=>{const a=a=>{Xe(e)(a)===t&&n(a)};if("message"===e){const e=Ge(),t=async e=>{var t;const n=await ua(e),s=nt(["message","get",n.messages[0].messageId]),o=(null===(t=null==s?void 0:s.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Nn(n),o&&a(n.messages[0])};return qt(e,"reaction/onReactionRemoved","message.updated",t)}return"post"===e?fl(a):Rl(a)},onReactorAdded:Pl,onReactorRemoved:Dl,getReactions:(e,t,n)=>{const{log:a,cache:s}=Ge(),o=Date.now();a(`getReactions(tmpid: ${o}) > listen`);const i=new jl(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{it(c)})),()=>{a(`getReactions(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});function Ml(e){const{comments:t}=e;return Object.assign(Object.assign({},e),{comments:t.map((e=>e.hasOwnProperty("myReactions")?e:Object.assign({myReactions:[]},e)))})}const ql=async()=>{var e;const t=Ge();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&&(it(["archivedChannel","get"]),a.forEach((e=>{e.channelId&&at(["archivedChannel","get",e.channelId],e)}))),a.map((e=>e.channelId)).filter((e=>!!e))},xl=e=>{const t=Ge(),n=[qt(t,"onMessageUpdated","message.updated",(async t=>{const n=await ua(t);Nn(n),e(n.messages[0])})),qt(t,"onMessageUpdated","local.message.updated",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},Kl=e=>{const t=Ge(),n=[qt(t,"message/onMessageDeleted","message.deleted",(async t=>{const n=await ua(t);Nn(n),e(n.messages[0])})),qt(t,"message/onMessageDeleted","local.message.deleted",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},Nl=e=>{const t=Ge(),n=[qt(t,"onSubChannelUpdated","message-feed.updated",(async t=>{const n=await va(t);Nn(n),e(n.messageFeeds[0])})),qt(t,"onSubChannelUpdated","local.message-feed.updated",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}};function Fl(e,t){at(["channel","get",e.channelId],Wn(e,t))}const _l=e=>{const t=Ge();return qt(t,"channelMarker/onChannelMarkerUpdated","local.channelMarker.updated",(t=>{e(t.userEntityMarkers[0])}))},Bl=async(e,t=!1)=>{const n=Ge(),a=await fa(e);await n.http.delete(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{params:{permanent:t}});const s=Object.assign(Object.assign({},a.data),{isDeleted:!0,updatedAt:et(a.data.updatedAt)});return t?setTimeout((()=>{Fn("subChannel",e)}),0):ot(["subChannel","get",e],s),xt("local.message-feed.deleted",{messageFeeds:[s]}),s},$l=e=>qt(Ge(),"onSubChannelFetched","local.message-feed.fetched",(t=>e(t.messageFeeds[0]))),Ll=()=>`LOCAL_${Un()}`;let Ql;const Vl=async(e,t)=>{const n=Ge();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)}`,ha(t)),s=await ua(a),o=n.cache&&Date.now();n.cache&&Nn(s,{cachedAt:o});const{messages:i}=s;return xt("local.message.updated",{messages:i}),{data:dd.message(i.find((t=>t.messageId===e))),cachedAt:o}};Vl.optimistically=(e,t)=>{const n=Ge();if(n.log("message/updateMessage.optimistically",t),!n.cache)return;const a=nt(["message","get",e]);if(!a)return;const s=Object.assign(Object.assign(Object.assign({},a.data),t),{updatedAt:(new Date).toISOString()});return ot(["message","get",e],s,{cachedAt:-1}),xt("local.message.updated",{messages:[s]}),{data:dd.message(s),cachedAt:-1}};const Jl=async(e,t)=>{const n=Ge();n.log("message/editMessage",t);const{data:a}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,ha(t)),s=await ua(a),o=n.cache&&Date.now();n.cache&&Nn(s,{cachedAt:o});const{messages:i}=s;return xt("local.message.updated",{messages:i}),{data:dd.message(i.find((t=>t.messageId===e))),cachedAt:o}};Jl.optimistically=(e,t)=>{const n=Ge();if(n.log("message/editMessage.optimistically",t),!n.cache)return;const a=nt(["message","get",e]);if(!a)return;const s=Object.assign(Object.assign(Object.assign({},a.data),t),{updatedAt:(new Date).toISOString()});return ot(["message","get",e],s,{cachedAt:-1}),xt("local.message.updated",{messages:[s]}),{data:dd.message(s),cachedAt:-1}};const Hl=async e=>{var t;const n=Ge();if(n.log("message/deleteMessage",e),e.includes("LOCAL_")){const n=null===(t=nt(["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 xt("local.message.deleted",{messages:[a]}),dd.message(a)}const{data:a}=await n.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`),s=await ua(a);return xt("local.message.deleted",{messages:[s.messages[0]]}),dd.message(s.messages[0])};Hl.optimistically=e=>{Ge().log("message/deleteMessage.optimistically",e);const t=nt(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return ot(["message","get",e],n,{cachedAt:-1}),xt("local.message.deleted",{messages:[n]}),{data:dd.message(n),cachedAt:-1}};const zl=async e=>{const t=Ge();t.log("message/softDeleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const n=await $d(e);return xt("local.message.deleted",{messages:[n.data]}),dd.message(n.data)};zl.optimistically=e=>{Ge().log("message/softDeleteMessage.optimistically",e);const t=nt(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return ot(["message","get",e],n,{cachedAt:-1}),xt("local.message.deleted",{messages:[n]}),{data:dd.message(n),cachedAt:-1}};const Gl=async e=>{const t=Ge();t.log("user/getReadUsers",e);const{page:n,messageId:a}=e,s=_n(e,["page","messageId"]),{data:o}=await t.http.get(`/api/v1/markers/messages/${a}/read-users`,{params:Object.assign(Object.assign({},s),{options:{token:je(n,"afterbeforeraw")}})}),{paging:i,publicUserIds:r,userFeedMarkers:c}=o,d=_n(o,["paging","publicUserIds","userFeedMarkers"]),l=t.cache&&Date.now();if(t.cache){Nn(Object.assign(Object.assign({},d),{userFeedMarkers:Vn(c)}),{cachedAt:l});const e=["read-user","query",Object.assign(Object.assign({messageId:a},s),{options:Object.assign({},n)})];at(e,{users:r,paging:i})}let u=[];r.length>0&&({data:u}=await ld(r));return{data:u,cachedAt:l,prevPage:Ee(i.previous),nextPage:Ee(i.next)}};Gl.locally=e=>{var t;const n=Ge();if(n.log("user/getReadUsers.locally",e),!n.cache)return;const{page:a}=e,s=_n(e,["page"]),o=["read-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},a)})],{data:i,cachedAt:r}=null!==(t=nt(o))&&void 0!==t?t:{},c=null==i?void 0:i.users.map((e=>{var t;return null===(t=nt(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:r,prevPage:Ee(null==i?void 0:i.paging.previous),nextPage:Ee(null==i?void 0:i.paging.next)}};const Yl=async e=>{const t=Ge();t.log("user/getDeliveredUsers",e);const{page:n,messageId:a}=e,s=_n(e,["page","messageId"]),{data:o}=await t.http.get(`/api/v1/markers/messages/${a}/delivered-users`,{params:Object.assign(Object.assign({},s),{options:{token:je(n,"afterbeforeraw")}})}),{paging:i,publicUserIds:r,userFeedMarkers:c}=o,d=_n(o,["paging","publicUserIds","userFeedMarkers"]),l=t.cache&&Date.now();if(t.cache){Nn(Object.assign(Object.assign({},d),{userFeedMarkers:Vn(c)}),{cachedAt:l});const e=["delivered-user","query",Object.assign(Object.assign({messageId:a},s),{options:Object.assign({},n)})];at(e,{users:r,paging:i})}let u=[];r.length>0&&({data:u}=await ld(r));return{data:u,cachedAt:l,prevPage:Ee(i.previous),nextPage:Ee(i.next)}};Yl.locally=e=>{var t;const n=Ge();if(n.log("user/getDeliveredUsers.locally",e),!n.cache)return;const{page:a}=e,s=_n(e,["page"]),o=["delivered-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},a)})],{data:i,cachedAt:r}=null!==(t=nt(o))&&void 0!==t?t:{},c=null==i?void 0:i.users.map((e=>{var t;return null===(t=nt(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:r,prevPage:Ee(null==i?void 0:i.paging.previous),nextPage:Ee(null==i?void 0:i.paging.next)}};const Wl=e=>{const t=Ge();return qt(t,"onMessageFlagged","message.flagged",(async t=>{const n=await ua(t);Nn(n),e(n.messages[0])}))},Xl=e=>{const t=Ge();return qt(t,"onMessageUnflagged","message.unflagged",(async t=>{const n=await ua(t);Nn(n),e(n.messages[0])}))},Zl=e=>{const t=Ge();return qt(t,"onMessageFlagCleared","message.flagCleared",(async t=>{const n=await ua(t);Nn(n),e(n.messages[0])}))},eu=e=>{const t=Ge();return qt(t,"onMessageReactionAdded","message.reactionAdded",(async t=>{const n=await ua(t,"message.reactionAdded");Nn(n),e(n.messages[0])}))},tu=e=>{const t=Ge();return qt(t,"onMessageReactionRemoved","message.reactionRemoved",(async t=>{const n=await ua(t,"message.reactionRemoved");Nn(n),e(n.messages[0])}))},nu=e=>{const t=Ge();return qt(t,"message/onMessageFetched","local.message.fetched",(t=>{Nn(t),e(t.messages[0])}))},au=e=>{const t=Ge();return qt(t,"stream/onStreamViewerDidBan","video-streaming.viewerDidBan",(t=>{var n;const{list:a}=t;a.forEach((e=>{var t;st(["stream","get",e.streamId],{watcherUrl:null});const n=null===(t=tt(["message","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.creatorId===e.userId));null==n||n.forEach((e=>{st(e.key,{isDeleted:!0})}))}));const s=null===(n=nt(["stream","get",a[0].streamId]))||void 0===n?void 0:n.data;s&&e(s)}))};class su extends Ir{constructor(e,t,n,a,s){super(e,t),this.notifyChange=n,this.preparePayload=a,this.paginationController=s}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.messages.map(Xe("message")),query:this.query});else{const n=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,o=null!==(s=null==n?void 0:n.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},n),{data:"next"===t?[...new Set([...o,...e.messages.map(Xe("message"))])]:[...new Set([...e.messages.map(Xe("message")),...o])]}))}}reactor(e){return t=>{var n,a,s,o;if("onCreate"===e){const e=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data,{referenceId:o}=t;if(!e)return;if(this.query.subChannelId!==(null==t?void 0:t.subChannelId)||!e)return;if(this.query.type&&this.query.type!==t.dataType)return;if(this.query.excludingTags&&(null===(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===(s=this.query.includingTags)||void 0===s?void 0:s.some((e=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.includes(e)}))))return;this.query.sortBy&&"segmentDesc"!==this.query.sortBy||this.paginationController.getPrevToken()||(e.data=[...new Set([null!=o?o:t.messageId,...e.data])]),"segmentAsc"!==this.query.sortBy||this.paginationController.getNextToken()||(e.data=[...new Set([...e.data,null!=o?o:t.messageId])]),at(this.cacheKey,e)}if("onDelete"===e&&"error"===t.syncState){const e=null===(o=nt(this.cacheKey))||void 0===o?void 0:o.data;if(!e)return;if(e.data.includes(t.messageId)){const n=e.data.filter((e=>e!==t.messageId));at(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 ou extends fr{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 iu extends Or{constructor(e,t){const n=R.default(e),a=["message","collection",n];super(new ou(e),n,a,t),this.query=e,this.queryStreamController=new su(this.query,this.cacheKey,this.notifyChange.bind(this),ua,this.paginationController),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:vi,action:"onCreate"},{fn:fi,action:"onCreate"},{fn:Kl,action:"onDelete"},{fn:xl,action:"onUpdate"},{fn:Wl,action:"onFlagged"},{fn:Xl,action:"onUnflagged"},{fn:Zl,action:"onFlagCleared"},{fn:eu,action:"onReactionAdded"},{fn:tu,action:"onReactionRemoved"},{fn:Td(Yi,"contentId","message"),action:"onUpdate"},{fn:Td(Wi,"contentId","message"),action:"onUpdate"},{fn:Td(au,"channelId","message"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>aa(e))).filter(Boolean).map((e=>dd.message(e))))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),onPrevPage:()=>this.loadPage({direction:"prev"}),data:i,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=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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 ru extends fr{async getRequest(e,t){const{query:n,exactMatch:a,channelId:s,messageFeedId:o,userIds:i,tags:r,types:c,sortBy:d,orderBy:l,limit:u=me}=e,h=t?{token:t}:{limit:u,sortBy:d,orderBy:l},{data:m}=await this.http.get("/api/v2/search/messages",{params:{query:n,exactMatch:a,channelId:s,messageFeedId:o,userIds:i,tags:r,types:c,options:h}});return m}}class cu extends Ir{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){var t;const n=await ua(e),a=Ge(),s=a.cache&&Date.now();a.cache&&(Nn(n,{cachedAt:s}),(null===(t=e.channels)||void 0===t?void 0:t.length)&&e.channels.forEach((e=>{at(["channel","get",e.channelId],e,{cachedAt:s})})))}appendToQueryStream(e,t,n=!1){var a,s;if(n)return void at(this.cacheKey,{data:e.messages.map(Xe("message"))});const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,i=null!==(s=null==o?void 0:o.data)&&void 0!==s?s:[],r=e.messages.map(Xe("message"));at(this.cacheKey,Object.assign(Object.assign({},o),{data:"prev"===t?[...new Set([...r,...i])]:[...new Set([...i,...r])]}))}}class du extends Or{constructor(e,t){const n=R.default(e),a=["message","search",n];super(new ru(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,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>aa(e))).filter(Tr).map((e=>dd.message(e))))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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 lu=Object.freeze({__proto__:null,createMessage:async e=>{const t=Ge();t.log("message/createMessage",e);const n=(e=>{var t,n;const a=Ge();if(!a.cache)return;Ql=e.referenceId||Ll();const s=Object.assign({messageId:Ql,uniqueId:Ql},e);a.log("message/createMessage.optimistically",s);const o=nt(["subChannel","get",e.subChannelId]);if(o&&(ot(["subChannel","get",e.subChannelId],Object.assign(Object.assign({},o.data),{messageCount:o.data.messageCount+1})),o.data.channelId===o.data.subChannelId)){const e=nt(["channel","get",o.data.channelId]);(null==e?void 0:e.data)&&ot(["channel","get",o.data.channelId],Object.assign(Object.assign({},e.data),{messageCount:(null!==(t=e.data.messageCount)&&void 0!==t?t:0)+1}))}const i=(new Date).toISOString(),r=Object.assign({creatorId:a.userId,creatorPrivateId:Dt()._id,channelSegment:(null!==(n=null==o?void 0:o.data.messageCount)&&void 0!==n?n:0)+1,childrenNumber:0,createdAt:i,updatedAt:i,syncState:"syncing",isDeleted:!1},s);return at(["message","get",r.messageId],r,{cachedAt:-5}),xt("local.message.created",{messages:[r]}),r})(e),a=e.referenceId||Ql||Ll();Ql=void 0;try{const{data:n}=await t.http.post("/api/v5/messages",Object.assign(Object.assign({},ha(e)),{referenceId:a})),s=await ua(n),{messages:o}=s,i=t.cache&&Date.now();return t.cache&&Nn(s,{cachedAt:i}),xt("local.message.created",{messages:[Object.assign(Object.assign({},o[0]),{syncState:"synced"})]}),{data:dd.message(o[0]),cachedAt:i}}catch(e){throw xt("local.message.created",{messages:[Object.assign(Object.assign({},n),{syncState:"error"})]}),e}},updateMessage:Vl,editMessage:Jl,deleteMessage:Hl,softDeleteMessage:zl,markAsDelivered:async(e,t)=>{const n=Ge();n.log("message/markAsDelivered",e,t);const{data:a}=await n.http.put(`/api/v1/markers/message-feeds/${e}/mark-delivering`,{messageId:t}),{userMarkers:s,userEntityMarkers:o,userFeedMarkers:i}=a,r=_n(a,["userMarkers","userEntityMarkers","userFeedMarkers"]),c=n.cache&&Date.now();return n.cache&&Nn(Object.assign({userMarkers:s,userEntityMarkers:Qn(o),userFeedMarkers:Vn(i)},r),{cachedAt:c}),!0},getReadUsers:Gl,getDeliveredUsers:Yl,flagMessage:async(t,n)=>{const a=Ge();a.log("message/flag",t);const s=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,a])=>t!==e.ContentFlagReasonEnum.Others&&a===n)),o={reason:s?n:e.ContentFlagReasonEnum.Others,detail:s?"":n},{data:i}=await a.http.post(`/api/v5/messages/${encodeURIComponent(t)}/flags`,o);if(a.cache){const e=await ua(i);Nn(e)}return xt("message.flagged",i),!!i},unflagMessage:async e=>{const t=Ge();t.log("message/unflag",e);const{data:n}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await ua(n);Nn(e)}return xt("message.unflagged",n),!!n},isMessageFlaggedByMe:async e=>{const t=Ge();t.log("message/isMessageFlaggedByMe",e);const{data:n}=await t.http.get(`/api/v5/messages/${encodeURIComponent(e)}/flags`);return n.result},onMessageCreatedMqtt:vi,onMessageCreatedLocal:fi,onMessageUpdated:xl,onMessageDeleted:Kl,onMessageFlagged:Wl,onMessageUnflagged:Xl,onMessageFlagCleared:Zl,onMessageReactionAdded:eu,onMessageReactionRemoved:tu,onMessageFetched:nu,getMessage:(e,t)=>jr(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?dd.message(e.data):n}))}),"messageId",$d,[nu,xl,Kl,Wl,Xl,Zl,eu,tu,Td(Yi,"contentId","message"),Td(Wi,"contentId","message"),Td(au,"channelId","message")]),getMessages:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getMessages(tmpid: ${o}) > listen`);const i=new iu(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{it(c)})),()=>{a(`getMessages(tmpid: ${o}) > dispose`),r.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}=Ge();a||console.log(ye);const s=Date.now();n(`searchMessage(tmpid: ${s}) > listen`);const o=new du(e,t),i=o.startSubscription(),r=o.getCacheKey();return i.push((()=>{it(r)})),()=>{n(`searchMessage(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},convertFromRaw:da,prepareMessagePayload:ua,convertParams:ha,convertQueryParams:ma});const uu=e=>{const t=Ge();return qt(t,"subChannelMarker/onSubChannelUnreadUpdatedLocal","local.subChannelUnread.updated",(t=>{e(t)}))};class hu extends fr{async getRequest(e,t){var n;const{limit:a=me}=e,s=null!==(n=function(e){var{excludeDefaultSubChannel:t}=e,n=_n(e,["excludeDefaultSubChannel"]);const a=Object.assign({},n);return void 0!==t&&(a.excludeDefaultMessageFeed=t),a}(_n(e,["limit"])))&&void 0!==n?n:{},{channelId:o,includeDeleted:i}=s,r=_n(s,["channelId","includeDeleted"]),c=t?{token:t}:{limit:a},{data:d}=await this.http.get(`/api/v5/message-feeds/channel/${o}`,{params:Object.assign(Object.assign({},r),{isDeleted:sa(i),options:c})});return d}}class mu extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.messageFeeds.map((({messageFeedId:e})=>e))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(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=nt(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])]),at(this.cacheKey,a)}this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class gu extends Or{constructor(e,t){const n=R.default(e),a=["subChannel","collection",n];super(new hu(e),n,a,t),this.query=e,this.queryStreamController=new mu(this.query,this.cacheKey,this.notifyChange.bind(this),va),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:$l,action:"onCreate"},{fn:bi,action:"onCreate"},{fn:Ii,action:"onDelete"},{fn:e=>Nl((async t=>{if(!this.isRelatedCollection(t.subChannelId))return;const n=Ge();if("no-message-preview"!==await n.getMessagePreviewSetting(!1)){const e=zn(t.subChannelId);(null==e?void 0:e.subChannelId)===t.subChannelId&&Hn(t.updatedAt)>Hn(e.subChannelUpdatedAt)&&at(["messagePreviewSubChannel","get",t.subChannelId],Object.assign(Object.assign({},e),{subChannelName:t.displayName,subChannelUpdatedAt:t.updatedAt}))}e(t)})),action:"onUpdate"},{fn:Td((e=>vi((async t=>{this.isRelatedCollection(t.subChannelId)&&(await Ia(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Td((e=>fi((async t=>{this.isRelatedCollection(t.subChannelId)&&(await Ia(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:e=>zi((t=>{var n;const a=null!==(n=t.map((({feedId:e})=>nt(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];0!==a.length&&e(a)})),action:"onUpdate"},{fn:Td(Hi,"feedId","subChannel"),action:"onUpdate"},{fn:Td((e=>xl((async t=>{var n;const a=Ge();if("no-message-preview"===await a.getMessagePreviewSetting(!1))return;const s=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;s&&s.data.includes(t.subChannelId)&&(Ca(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Td((e=>Kl((async t=>{const n=Ge(),a=await n.getMessagePreviewSetting(!1);"no-message-preview"!==a&&this.isRelatedCollection(t.subChannelId)&&("message-preview-not-include-deleted"===a?await fa(t.subChannelId):await Ca(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Td(uu,"subChannelId","subChannel"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(Gn))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.includeDeleted||(t=rt(e,"isDeleted",!1)),t.sort(Tt),t}isRelatedCollection(e){var t;const n=null===(t=nt(this.cacheKey))||void 0===t?void 0:t.data;return n&&n.data.includes(e)}}const pu={},yu=async e=>{const t=await(async e=>{const t=fa.locally(e);if(t)return t.data.channelId;const{data:n}=await fa(e);return n.channelId})(e),n=Ht({channelId:t,subChannelId:e});pu[e]=Zt(n)};var vu=Object.freeze({__proto__:null,getSubChannelByIds:Ks,createSubChannel:async e=>{const t=Ge();t.log("user/createSubChannel",e);const n=await t.http.post("/api/v5/message-feeds",{channelId:e.channelId,name:e.displayName}),a=await va(n.data),s=t.cache&&Date.now();return t.cache&&Nn(a,{cachedAt:s}),xt("message-feed.created",n.data),{data:a.messageFeeds[0],cachedAt:s}},updateSubChannel:async(e,t)=>{const n=Ge();n.log("channel/updateSubChannel",e,t);const a=await n.http.put(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{name:t.displayName}),s=await va(a.data),o=n.cache&&Date.now();return n.cache&&Nn(s,{cachedAt:o}),xt("message-feed.updated",a.data),{data:s.messageFeeds[0],cachedAt:o}},deleteSubChannel:Bl,hardDeleteSubChannel:async e=>{Ge().log("channel/hardDeleteSubChannel",e);return await Bl(e,!0)},softDeleteSubChannel:async e=>{Ge().log("channel/softDeleteSubChannel",e);return await Bl(e,!1)},onSubChannelCreated:bi,onSubChannelUpdated:Nl,onSubChannelDeleted:Ii,getSubChannel:(e,t)=>{const n=Ge();let a;return jr(e,(e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:Gn(e.data)}),s=_n(n,["origin"]);return Na(a,s)?void 0:(a=s,t(n))}),"subChannelId",fa,[$l,t=>Nl((async a=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(Oa(a),a.subChannelId===e&&t(a))})),Ii,Td(Hi,"feedId","subChannel"),t=>zi((n=>{var a;if(!n.find((({feedId:t})=>t===e)))return;const s=null===(a=nt(["subChannel","get",e]))||void 0===a?void 0:a.data;s&&t(s)})),Td((t=>vi((async n=>{n.subChannelId===e&&(await Ia(n),t(n))}))),"subChannelId","subChannel"),Td((t=>fi((async n=>{n.subChannelId===e&&(await Ia(n),t(n))}))),"subChannelId","subChannel"),Td((t=>xl((async a=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&a.subChannelId===e&&(Ca(a),t(a))}))),"subChannelId","subChannel"),Td((t=>Kl((async a=>{const s=await n.getMessagePreviewSetting(!1);"no-message-preview"!==s&&a.subChannelId===e&&("message-preview-include-deleted"===s&&await Ca(a),"message-preview-not-include-deleted"===s&&await fa(a.subChannelId),t(a))}))),"subChannelId","subChannel"),Td(uu,"subChannelId","subChannel")],{forceDispatch:!0})},getSubChannels:(e,t,n)=>{const{log:a,cache:s}=Ge(),o=Date.now();a(`getSubChannels(tmpid: ${o}) > listen`),s||console.log(ye);const i=new gu(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{it(c)})),()=>{a(`getSubChannels(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},markReadEngineOnLoginHandler:xs,startMessageReceiptSync:async e=>(await yu(e),!0),stopMessageReceiptSync:e=>(pu[e]&&pu[e](),!0)});const fu=e=>{const t=Ge();return qt(t,"channelMarker/onChannelUnreadInfoUpdatedLocal","local.channelUnreadInfo.updated",(t=>{e(t)}))},bu=e=>{const t=Ge();return qt(t,"channel/onChannelUnreadUpdatedLocal","local.channelUnread.updated",(t=>{e(t)}))};class Iu extends fr{async getRequest(e,t){const{limit:n=me,displayName:a,membership:s}=e,o=_n(e,["limit","displayName","membership"]),i=t?{token:t}:{limit:n},{data:r}=await this.http.get("/api/v3/channels",{params:Object.assign(Object.assign({},o),{keyword:a,filter:s,options:i})});return r}}class Cu extends Sr{async getRequest(e){const{data:t}=await this.http.get("/api/v3/channels/list",{params:Object.assign({},e)});return t}}class wu extends Ir{constructor(e,t,n,a,s){super(e,t),this.notifyChange=n,this.preparePayload=a,this.paginationController=s}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.channels.map(Xe("channel"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channels.map(Xe("channel"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(this.paginationController instanceof Cu)return this.notifyChange({origin:"event",loading:!1});if(["onCreate","onJoin","onResolveChannel","onUnarchived"].includes(e)&&(Array.isArray(t)?a.data=[...new Set([...t.map(Xe("channel")),...a.data])]:a.data=[...new Set([t.channelInternalId,...a.data])]),"onArchived"===e){const e=Array.isArray(t)?t.map(Xe("channel")):[Xe("channel")(t)];a.data=a.data.filter((t=>!e.includes(t)))}at(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=Ge();if(t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()){Uo().resolve(e.channelId,"userMessageFeedMarker")}},Ou=e=>{const t=Ge();return qt(t,"onChannelResolved","local.channel.resolved",(async t=>{e(t)}))},Tu=e=>{const t=Ge();return qt(t,"userMessageFeedMarker/onUserMessageFeedMarkerResolved","local.userMessageFeedMarkers.resolved",(t=>{e(t)}))};class Au extends Or{constructor(e,t){const n=R.default(e),a=["channel","collection",n],s=Au.getPaginationController(e);super(s,n,a,t),this.query=e,this.queryStreamController=new wu(this.query,this.cacheKey,this.notifyChange.bind(this),(async e=>{try{const t=Ge();t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await ka(e)}catch(e){console.error("Error while preparing unread count info",e)}return Da(e)}),s),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;let i=null!==(s=o.data.map((e=>nt(["channel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(Ds))&&void 0!==s?s:[];this.paginationController instanceof Iu&&(i=this.applyFilter(i)),(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:this.paginationController instanceof Iu?()=>this.loadPage({direction:"next"}):void 0,data:i,hasNextPage:this.paginationController instanceof Iu&&!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Ge();let n=e;switch(n=rt(n,"isDeleted",this.query.isDeleted),n=ct(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=lt(n,this.query.membership,t)),this.query.sortBy){case"firstCreated":n=n.sort(It);break;case"lastCreated":n=n.sort(wt);break;case"displayName":n=n.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(ft);break;default:n=n.sort(Tt)}return n}shouldAbort(e){var t,n;const a=null===(t=nt(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 Ge().getMessagePreviewSetting(!1)}static getPaginationController(e){return e.channelIds&&e.channelIds.length>0?new Cu(e):new Iu(e)}getSubscriptions(){const e=[{fn:Td((e=>vi((t=>{var n,a;const s=Uo();(null===(n=nt(["subChannelUnreadInfo","get",t.subChannelId]))||void 0===n?void 0:n.data)||s.resolve(t.subChannelId,"userMessageFeedMarker");const o=null===(a=nt(["channel","get",t.channelId]))||void 0===a?void 0:a.data;o?(Fl(o,{lastActivity:t.createdAt}),e(t)):s.resolve(t.channelId,"channel")}))),"channelId","channel"),action:"onUpdate"},{fn:Td((e=>fi((t=>{var n;const a=null===(n=nt(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Fl(a,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ga,action:"onDelete"},{fn:Qa,action:"onUpdate"},{fn:ss,action:"onMute"},{fn:e=>Xa((t=>{Su(t),e(t)})),action:"onJoin"},{fn:e=>ts(((t,n)=>{var a,s;const{userId:o}=Ge();if("member"===this.query.membership&&o===n.userId){const e=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;at(this.cacheKey,Object.assign(Object.assign({},e),{data:null!==(s=null==e?void 0:e.data.filter((e=>e!==t.channelId)))&&void 0!==s?s:[]}))}return e(t)})),action:"onLeft"},{fn:rs,action:"onMemberAdded"},{fn:ls,action:"onMemberRemoved"},{fn:e=>Ss((t=>{const n=t.archives.map((e=>{var t;return null===(t=nt(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onArchived"},{fn:e=>Os((t=>{const n=t.archives.map((e=>{var t;return null===(t=nt(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onUnarchived"},{fn:Td(Ji,"entityId","channel"),action:"onUpdate"},{fn:Td(_l,"entityId","channel"),action:"onUpdate"},{fn:Td((e=>vi((async t=>{var n;if("no-message-preview"===await Au.getMessagePreviewSetting())return;if(wa(t),this.shouldAbort(t.channelId))return;const a=null===(n=nt(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Fl(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Td((e=>fi((async t=>{var n;if("no-message-preview"===await Au.getMessagePreviewSetting())return;if(wa(t),this.shouldAbort(t.channelId))return;const a=null===(n=nt(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Fl(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Td((e=>xl((async t=>{"no-message-preview"!==await Au.getMessagePreviewSetting()&&(await Sa(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Td((e=>Kl((async t=>{const n=await Au.getMessagePreviewSetting();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await Sa(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&await gc(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:Td((e=>Ii((async t=>{var n;const a=null===(n=nt(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 gc(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Td((e=>Nl((async t=>{var n;if("no-message-preview"===await Au.getMessagePreviewSetting())return;(null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data)&&(await Oa(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Td(bi,"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=nt(["channel","get",e.entityId]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"OnResolveUnread"},{fn:Td(fu,"channelId","channel"),action:"onUpdate"},{fn:Td((e=>bu((t=>{t.forEach(e)}))),"channelId","channel"),action:"onUpdate"}];return this.paginationController instanceof fr?[...e,{fn:e=>Ba((t=>{Su(t),e(t)})),action:"onCreate"}]:e}}const Ru=()=>{var e;const t=Ge();t.log("channel/getTotalChannelsUnread.locally");const n=(null===(e=tt(["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 Pu extends fr{async getRequest(e,t){var n,a;const s=null!==(n=e.limit)&&void 0!==n?n:me,o=t?Number.parseInt(t,10):0;0===o&&await ql();const i=(null!==(a=tt(["archivedChannel","get"]))&&void 0!==a?a:[]).map((e=>e.data)).slice().sort(((e,t)=>Number(new Date(t.archivedAt))-Number(new Date(e.archivedAt)))),r=o*s,c=r+s,d=i.slice(r,c),l=c<i.length;return d.length>0&&await Us(d.map((e=>e.channelId))),{archives:d,paging:{next:l?String(o+1):void 0,previous:void 0}}}}class Du extends Ir{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){}appendToQueryStream(e,t,n=!1){var a,s;const o=e.archives.map((e=>e.channelId));if(n)return void at(this.cacheKey,{data:o,params:{}});const i=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,r=null!==(s=null==i?void 0:i.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},i),{data:"prev"===t?[...new Set([...o,...r])]:[...new Set([...r,...o])]}))}reactor(e){return t=>{var n;const a=null===(n=nt(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)))),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Uu extends Or{constructor(e,t){const n=R.default(e),a=["archivedChannel","collection",n];super(new Pu(e),n,a,t),this.queryStreamController=new Du(e,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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=>Ss((t=>e(t.archives.map((e=>e.channelId))))),action:"onArchived"},{fn:e=>Os((t=>e(t.archives.map((e=>e.channelId))))),action:"onUnarchived"},{fn:e=>Qa((t=>e([t.channelId]))),action:"onUpdate"},{fn:e=>Ga((t=>e([t.channelId]))),action:"onDelete"}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>nt(["channel","get",e]))).filter((e=>Boolean(e))).map((({data:e})=>e)).map(Ds))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class ku extends fr{async getRequest(e,t){const{query:n,exactMatch:a,isMemberOnly:s,types:o,tags:i,sortBy:r,orderBy:c,limit:d=ge}=e,l=t?{token:t}:{limit:Math.min(100,Math.max(1,d))},{data:u}=await this.http.get("/api/v2/search/channels",{params:{query:n,exactMatch:a,isMemberOnly:s,types:o,tags:i,sortBy:r,orderBy:c,options:l}});return u}}class ju extends Ir{constructor(e,t,n){super(e,t),this.notifyChange=n}async saveToMainDB(e){const t=await Da(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)return void at(this.cacheKey,{data:e.channels.map(Xe("channel"))});const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,i=null!==(s=null==o?void 0:o.data)&&void 0!==s?s:[],r=e.channels.map(Xe("channel"));at(this.cacheKey,Object.assign(Object.assign({},o),{data:"prev"===t?[...new Set([...r,...i])]:[...new Set([...i,...r])]}))}reactor(){return()=>this.notifyChange({origin:"event",loading:!1})}subscribeRTE(e){return e.map((e=>e.fn(this.reactor())))}}const Eu=()=>Ge().getMessagePreviewSetting(!1);class Mu extends Or{constructor(e,t){const n=R.default(e),a=["channel","search",n];super(new ku(e),n,a,t),this.queryStreamController=new ju(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,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>nt(["channel","get",e]))).filter(Boolean).map((e=>Ds(e.data))))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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=nt(this.cacheKey))||void 0===t?void 0:t.data;return!n||!n.data.find((t=>t===e))}getSubscriptions(){return[{fn:Td((e=>vi((t=>{var n;const a=null===(n=nt(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Fl(a,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Td((e=>fi((t=>{var n;const a=null===(n=nt(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Fl(a,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ga,action:"onDelete"},{fn:Qa,action:"onUpdate"},{fn:ss,action:"onMute"},{fn:e=>Ss((t=>{const n=t.archives.map((e=>{var t;return null===(t=nt(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onArchived"},{fn:e=>Os((t=>{const n=t.archives.map((e=>{var t;return null===(t=nt(["channel","get",e.channelId]))||void 0===t?void 0:t.data})).filter((e=>Boolean(e)));n.length>0&&e(n)})),action:"onUnarchived"},{fn:Td(Ji,"entityId","channel"),action:"onUpdate"},{fn:Td(_l,"entityId","channel"),action:"onUpdate"},{fn:Td((e=>vi((async t=>{var n;if("no-message-preview"===await Eu())return;if(wa(t),this.shouldAbort(t.channelId))return;const a=null===(n=nt(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Fl(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Td((e=>fi((async t=>{var n;if("no-message-preview"===await Eu())return;if(wa(t),this.shouldAbort(t.channelId))return;const a=null===(n=nt(["channel","get",t.channelId]))||void 0===n?void 0:n.data;a&&(Fl(a,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Td((e=>xl((async t=>{"no-message-preview"!==await Eu()&&(await Sa(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Td((e=>Kl((async t=>{const n=await Eu();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await Sa(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&await gc(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:Td((e=>Ii((async t=>{var n;const a=null===(n=nt(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 gc(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Td((e=>Nl((async t=>{var n;if("no-message-preview"===await Eu())return;(null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data)&&(await Oa(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=nt(["channel","get",e.entityId]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"OnResolveUnread"},{fn:Td(fu,"channelId","channel"),action:"onUpdate"},{fn:Td((e=>bu((t=>{t.forEach(e)}))),"channelId","channel"),action:"onUpdate"}]}}class qu extends fr{async getRequest(e,t){const{limit:n=me,includeDeleted:a}=e,s=_n(e,["limit","includeDeleted"]),o=t?{token:t}:{limit:n},i=!1!==a&&void 0,{data:r}=await this.http.get(`/api/v4/channels/${encodeURIComponent(s.channelId)}/users`,{params:Object.assign(Object.assign({},s),{options:o,isDeleted:i})});return r}}class xu extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.channelUsers.map((({channelId:e,userId:t})=>Xe("channelUsers")({channelId:e,userId:t})))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channelUsers.map((({channelId:e,userId:t})=>Xe("channelUsers")({channelId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;if(this.query.channelId!==t.channelId)return;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(!a)return;const s=Xe("channelUsers")({channelId:this.query.channelId,userId:t.userId}),o=this.query.memberships,i=!o||o.includes(t.membership);"none"!==t.membership&&i?a.data.includes(s)||(a.data=[s,...a.data]):a.data=a.data.filter((e=>e!==s)),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Ku extends Or{constructor(e,t){const n=R.default(e),a=["channelUsers","collection",n];super(new qu(e),n,a,t),this.query=e,this.queryStreamController=new xu(this.query,this.cacheKey,this.notifyChange.bind(this),Da),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:Xa,action:"onJoin"},{fn:ts,action:"onLeft"},{fn:rs,action:"onMemberAdded"},{fn:ls,action:"onMemberRemoved"},{fn:ms,action:"onChannelMemberBanned"},{fn:ys,action:"onChannelMemberUnbanned"},{fn:bs,action:"onChannelMemberRoleAdded"},{fn:ws,action:"onChannelMemberRoleRemoved"},{fn:Rs,action:"onChannelSetUserMuted"},{fn:(e=this.query.channelId,t=>{const n=Ge();return qt(n,"user.deleted","user.deleted",(n=>{var a,s;const o=Ws(n);if(0===o.users.length)return;const i=o.users[0];Nn(o);const r=Xe("channelUsers")({channelId:e,userId:i.userId}),c=null===(a=nt(["channelUsers","get",r]))||void 0===a?void 0:a.data;ot(["channelUsers","get",r],Object.assign(Object.assign({},c),{user:i}));const d=null===(s=nt(["channel","get",e]))||void 0===s?void 0:s.data;d&&t(d,c)}))}),action:"onChannelMemberChanged"}]);var e}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["channelUsers","get",e]))).filter(Boolean).map((({data:e})=>e)).map(dd.channelMember))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=dt(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?wt:It),t}}const Nu=(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getMembers(tmpid: ${o}) > listen`);const i=new Ku(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{it(c)})),()=>{a(`getMembers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}};var Fu=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=Ge();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=>xt("channel.membersAdded",Object.assign(Object.assign({},a),{channelUsers:a.channelUsers.filter((t=>t.userId===e))}))));const s=await Da(a);n.cache&&Nn(s);const{channelUsers:o}=s;return!!o.find((t=>t.channelId===e&&"member"===t.membership))},removeMembers:async(e,t)=>{const n=Ge();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=>xt("channel.membersRemoved",Object.assign(Object.assign({},a),{channelUsers:a.channelUsers.filter((t=>t.userId===e))}))));const s=await Da(a);n.cache&&Nn(s);const{channelUsers:o}=s;return!!o.find((t=>t.channelId===e&&"member"!==t.membership))},applyFilter:(e,t)=>{let n=dt(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?wt:It),n},getMembers:Nu,searchMembers:(e,t,n)=>Nu(e,t)});var _u=Object.freeze({__proto__:null,addRole:async(e,t,n)=>{const a=Ge();a.log("channel/addRole",e,t,n);const{data:s}=await a.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{channelId:e,role:t,userIds:n}),o=await Da(s);a.cache&&Nn(o),xt("local.channel-moderator.role-added",o);const{channelUsers:i}=o;return!!i.find((n=>n.channelId===e&&n.roles.includes(t)))},removeRole:async(e,t,n)=>{const a=Ge();a.log("channel/removeRole",e,t,n);const{data:s}=await a.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{data:{channelId:e,role:t,userIds:n}}),o=await Da(s);a.cache&&Nn(o),xt("local.channel-moderator.role-removed",o);const{channelUsers:i}=o;return!!i.find((n=>n.channelId===e&&!n.roles.includes(t)))},banMembers:async(e,t)=>{const n=Ge();n.log("channel/banMembers",{userIds:t,channelId:e});const{data:a}=await n.http.put(`/api/v3/channels/${e}/users/ban`,{userIds:t}),s=await Da(a),{channelUsers:o}=s,i=n.cache&&Date.now();return n.cache&&Nn(s,{cachedAt:i}),xt("channel.banned",a),{data:null==o?void 0:o.filter((e=>"banned"===e.membership)),cachedAt:i}},unbanMembers:async(e,t)=>{const n=Ge();n.log("channel/unbanMembers",{userIds:t,channelId:e});const{data:a}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}/users/unban`,{userIds:t}),s=await Da(a),o=n.cache&&Date.now();n.cache&&Nn(s,{cachedAt:o}),xt("channel.unbanned",a);const{channelUsers:i}=s;return{data:null==i?void 0:i.filter((e=>"member"===e.membership)),cachedAt:o}},muteMembers:async(e,t,n=-1)=>{var a;const s=Ge();s.log("channel/muteMembers",{userIds:t,channelId:e,mutePeriod:n});const{data:o}=await s.http.put(`/api/v2/channel/${e}/users/mute`,{userIds:t,mutePeriod:-1===n?n:1e3*n}),{success:i}=o,r=-1===n?new Date("9999-12-31T23:59:59.999Z").toISOString():new Date(Date.now()+1e3*n).toISOString();return xt("channel.setMutedUsers",{channelId:e,userIds:t,muteTimeout:r,actor:null!==(a=s.userId)&&void 0!==a?a:""}),i},unmuteMembers:async(e,t)=>{var n;const a=Ge();a.log("channel/unmuteMembers",{userIds:t,channelId:e});const{data:s}=await a.http.put(`/api/v2/channel/${encodeURIComponent(e)}/users/mute`,{userIds:t,mutePeriod:0}),{success:o}=s;return xt("channel.setMutedUsers",{channelId:e,userIds:t,muteTimeout:new Date(0).toISOString(),actor:null!==(n=a.userId)&&void 0!==n?n:""}),o}}),Bu=Object.freeze({__proto__:null,Membership:Fu,Moderation:_u,getChannelByIds:Us,createChannel:mc,updateChannel:async(e,t)=>{const n=Ge();n.log("channel/updateChannel",e,t);const{data:a}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}`,t),s=await Da(a),o=n.cache&&Date.now();n.cache&&Nn(s,{cachedAt:o});const{channels:i}=s;return{data:qa(i.find((t=>t.channelId===e))),cachedAt:o}},deleteChannel:async e=>{const t=Ge();t.log("channel/deleteChannel",e),await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}`);const n=await gc(e);return qa(n.data)},joinChannel:async e=>{const t=Ge();t.log("channel/joinChannel",e);const{data:n}=await t.http.post(`/api/v3/channels/${encodeURIComponent(e)}/join`),a=await Da(n);t.cache&&Nn(a);const{channelUsers:s}=a;return!!s.find((t=>t.channelId===e&&"member"===t.membership))},leaveChannel:async e=>{const t=Ge();t.log("channel/leaveChannel",e);const{data:n}=await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/leave`),a=await Da(n);t.cache&&Nn(a);const{channelUsers:s}=a;return!!s.find((t=>t.channelId===e&&"member"!==t.membership))},muteChannel:async(e,t=-1)=>{const n=Ge();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:s}=a;return s},unmuteChannel:async e=>{const t=Ge();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=Ge();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&&at(["archivedChannel","get",Xe("archivedChannel")(n)],n),xt("local.channel.archived",{archives:[n]})},unarchiveChannel:async e=>{var t;const n=Ge();n.log("channel/unarchiveChannel",e),await n.http.delete(`/api/v1/archives/channels/${encodeURIComponent(e)}`);const a=null===(t=nt(["archivedChannel","get",e]))||void 0===t?void 0:t.data,s=null!=a?a:{channelId:e,archivedAt:(new Date).toISOString()};n.cache&&it(["archivedChannel","get",e],!0),xt("local.channel.unarchived",{archives:[s]})},getArchivedChannelIds:ql,onChannelCreated:Ba,onChannelUpdated:Qa,onChannelDeleted:Ga,onChannelJoined:Xa,onChannelLeft:ts,onChannelSetMuted:ss,onChannelMemberAdded:rs,onChannelMemberRemoved:ls,onChannelMemberBanned:ms,onChannelMemberUnbanned:ys,onChannelMemberRoleAdded:bs,onChannelMemberRoleRemoved:ws,onChannelArchived:Ss,onChannelUnarchived:Os,getChannel:(e,t)=>{const n=Ge();let a;return jr(e,(async e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:Ds(e.data)}),s=_n(n,["origin"]);return Na(a,s)?void 0:(a=s,t(n))}),"channelId",gc,[Qa,Ga,Xa,ts,rs,ls,ms,ys,ss,Td(Ji,"entityId","channel"),Td(_l,"entityId","channel"),Td((t=>vi((async a=>{await(async a=>{var s;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await wa(a),a.channelId!==e)return;const o=null===(s=nt(["channel","get",e]))||void 0===s?void 0:s.data;o&&(Fl(o,{messagePreviewId:a.messageId}),t(a))})(a),t(a)}))),"channelId","channel"),Td((t=>fi((async a=>{var s;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await wa(a),a.channelId!==e)return;const o=null===(s=nt(["channel","get",e]))||void 0===s?void 0:s.data;o&&(Fl(o,{messagePreviewId:a.messageId}),t(a))}))),"channelId","channel"),Td((t=>xl((async a=>{var s;const o=null===(s=nt(["channel","get",e]))||void 0===s?void 0:s.data;if(!o||o.messagePreviewId!==a.messageId)return;"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(await Sa(a),t(a))}))),"channelId","channel"),Td((t=>Kl((async a=>{var s;const o=null===(s=nt(["channel","get",e]))||void 0===s?void 0:s.data;if(!o||o.messagePreviewId!==a.messageId)return;const i=await n.getMessagePreviewSetting(!1);"no-message-preview"!==i&&("message-preview-not-include-deleted"===i?(it(["messagePreviewChannel","get",e]),await gc(a.channelId)):await Sa(a),t(a))}))),"channelId","channel"),Td((e=>Ii((async t=>{var a,s;const{channelId:o,subChannelId:i}=t,r=null===(a=nt(["messagePreviewChannel","get",o]))||void 0===a?void 0:a.data;if(!r||r.subChannelId!==i)return;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;await gc(o);(null===(s=nt(["channel","get",o]))||void 0===s?void 0:s.data)&&e(t)}))),"channelId","channel"),Td((t=>Nl((async a=>{var s,o;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;Oa(a);const i=null===(s=nt(["messagePreviewChannel","get",e]))||void 0===s?void 0:s.data;if(!i||i.subChannelId!==a.subChannelId)return;(null===(o=nt(["channel","get",e]))||void 0===o?void 0:o.data)&&t(a)}))),"channelId","channel"),Td(bi,"channelId","channel"),Td(fu,"channelId","channel"),Td((e=>bu((t=>{t.forEach(e)}))),"channelId","channel")],{forceDispatch:!0})},getChannels:(e,t,n)=>{const{log:a,cache:s,userId:o}=Ge();s||console.log(ye);const i=Date.now();a(`getChannels(tmpid: ${i}) > listen`);const r=new Au(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>{it(d)})),()=>{a(`getChannels(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}},getTotalChannelsUnread:e=>{const{_id:t}=Dt();if(!t)throw new Le("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:a}=Ge();a||console.log("For using Live Object feature you need to enable Cache!");n(`liveTotalChannelsUnread(tmpid: ${Date.now()}) > listen`);const s=[];let o,i=!1;const r=t=>{const{data:n}=t,a=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;o=a?Zi(a):a,e({data:a?Object.assign(Object.assign({},a),{isMentioned:a.isMentioned}):a,loading:t.loading,error:t.error})};return s.push(bu((e=>{const{data:t}=Ru();Na(o,t)||r({loading:!1,data:t})}))),(()=>{const e=Fe((async()=>Ru()));Be(e,(({error:e,data:t,loading:n,origin:a,cachedAt:o})=>{o===fe?(r({data:t,origin:a,loading:!1,error:new Qe(ve,800800,"error")}),i=!0,s.forEach((e=>e()))):i||r({loading:n,data:t,origin:a,error:e}),e&&s.forEach((e=>e()))}))})(),()=>{s.forEach((e=>e()))}},getArchivedChannels:(e,t)=>{const{log:n,cache:a}=Ge();a||console.log(ye);const s=Date.now();n(`getArchivedChannels(tmpid: ${s}) > listen`);const o=new Uu(e,t),i=o.startSubscription(),r=o.getCacheKey();return i.push((()=>{it(r)})),()=>{n(`getArchivedChannels(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},searchChannels:(e,t)=>{const{log:n,cache:a}=Ge();a||console.log(ye);const s=Date.now();n(`searchChannels(tmpid: ${s}) > listen`);const o=new Mu(e,t),i=o.startSubscription(),r=o.getCacheKey();return i.push((()=>{it(r)})),()=>{n(`searchChannels(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},MARKER_INCLUDED_CHANNEL_TYPE:Ta,isUnreadCountSupport:Aa,convertFromRaw:Ra,preUpdateChannelCache:Pa,prepareChannelPayload:Da});const $u=(e,t)=>{0!==e.length&&0!==t.length&&e.forEach((({communityId:e})=>{const n=t.filter((({communityId:t})=>e===t));at(["communityUsers","collection",e],n)}))},Lu=async(e,t)=>{const n=Ge();n.log("community/getCommunities",e);const a=e.map((e=>encodeURIComponent(e))),{data:s}=await n.http.get("/api/v3/communities/list",{params:{communityIds:a,includeDiscoverablePrivateCommunity:null==t||t}}),o=Kr(s),i=n.cache&&Date.now();return n.cache&&(Nn(o,{cachedAt:i}),$u(o.communities,o.communityUsers)),{data:o.communities.map((e=>dd.community(e))),cachedAt:i}};Lu.locally=e=>{const t=Ge();if(t.log("community/getCommunities.locally",e),!t.cache)return;const n=e.map((e=>nt(["community","get",e]))).filter(Boolean),a=n.map((({data:e})=>e)),s=n.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1))[0];return n.length<e.length?void 0:{data:a,cachedAt:s.cachedAt}};const Qu=async e=>{const t=Ge();t.log("community/getCommunity",e);const{data:n}=await t.http.get(`/api/v3/communities/${e}`),a=Kr(n),s=t.cache&&Date.now();t.cache&&(Nn(a,{cachedAt:s}),$u(a.communities,a.communityUsers));const{communities:o}=a;return{data:o.find((t=>t.communityId===e)),cachedAt:s}};Qu.locally=e=>{const t=Ge();if(t.log("community/getCommunity.locally",e),!t.cache)return;const n=nt(["community","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Vu=(e,t)=>{const n=Ge();return qt(n,e,e,(e=>{const a=Kr(e);if(n.cache){Nn(a);const e=nt(["community","get",a.communities[0].communityId]);t(e.data)}else t(a.communities[0])}))},Ju=e=>Vu("community.created",e),Hu=e=>Vu("community.updated",e),zu=e=>Vu("community.deleted",e);class Gu extends fr{async getRequest(e,t){var n;const{limit:a=me}=e,s=_n(e,["limit"]),o=t?{token:t}:{limit:a},{data:i}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},s),{isDeleted:sa(s.includeDeleted),keyword:s.displayName,filter:s.membership,includeDiscoverablePrivateCommunity:null===(n=s.includeDiscoverablePrivateCommunity)||void 0===n||n,options:o})});return i}}class Yu extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.communities.map(Xe("community"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Xe("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=nt(this.cacheKey))||void 0===t?void 0:t.data;n&&(at(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Wu,Xu;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Wu||(Wu={})),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 fr{async getRequest(e,t){const{limit:n=me,includeDeleted:a,excludingRoles:s}=e,o=_n(e,["limit","includeDeleted","excludingRoles"]),i=t?{token:t}:{limit:n},r=!1!==a&&void 0,{data:c}=await this.http.get(`/api/v3/communities/${o.communityId}/users`,{params:Object.assign(Object.assign({},o),{options:i,isDeleted:r})});return c}}class eh extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>Xe("communityUsers")({communityId:e,userId:t})))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>Xe("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;a&&(t.forEach((e=>{var t;const n=Xe("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]}})),at(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=Ge();return qt(n,e,e,(a=>{const s=Kr(a),{communities:o,communityUsers:i}=s,r=Mr(o,i);if(s.communities=r,n.cache){Nn(s,void 0,!1);const n=nt(["community","get",s.communities[0].communityId]),a=nh(e,s).map((e=>{const t=nt(["communityUsers","get",Xe("communityUsers")(e)]);return null==t?void 0:t.data})).filter(Tr);t(n.data,a)}else t(s.communities[0],nh(e,s))}))},sh=(e,t)=>{const n=Ge();return qt(n,e,e,(a=>{const s=Kr(a),{communities:o,communityUsers:i}=s,r=Mr(o,i);if(s.communities=r,n.cache){Nn(s,void 0,!1);const n=nt(["community","get",s.communities[0].communityId]),a=nh(e,s).map((e=>{const t=nt(["communityUsers","get",Xe("communityUsers")(e)]);return null==t?void 0:t.data})).filter(Tr);t(n.data,a)}else t(s.communities[0],nh(e,s))}))},oh=e=>ah("community.userBanned",e),ih=e=>ah("community.userChanged",e),rh=e=>ah("community.userUnbanned",e),ch=e=>ah("community.roleAdded",e),dh=e=>ah("community.roleRemoved",e),lh=e=>sh("local.community.userAdded",e),uh=e=>sh("local.community.userRemoved",e),hh=e=>ah("community.joined",e),mh=e=>ah("community.left",e),gh=e=>sh("local.community.joined",e),ph=e=>sh("local.community.left",e),yh=e=>{const t=Ge(),n=[qt(t,"onCommunityUpdate","v4.local.community.joined",(async t=>{e(t[0])}))];return()=>{n.forEach((e=>e()))}},vh=e=>{const t=Ge();return qt(t,"onLocalCommunityRoleRemoved","local.community.roleRemoved",(async t=>{const{communities:n,communityUsers:a}=t;e(n[0],a.filter((e=>"member"===e.communityMembership)))}))},fh=e=>{const t=Ge();return qt(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=Ge();return qt(n,"user.deleted","user.deleted",(n=>{var a,s;const o=Ws(n);if(0===o.users.length)return;const i=o.users[0];Nn(o);const r=Xe("communityUsers")({communityId:e,userId:i.userId}),c=null===(a=nt(["communityUsers","get",r]))||void 0===a?void 0:a.data;at(["communityUsers","get",r],Object.assign(Object.assign({},c),{user:i}));const d=null===(s=nt(["community","get",e]))||void 0===s?void 0:s.data;t(d,[Object.assign(Object.assign({},c),{user:i})])}))};class Ih extends Or{constructor(e,t){const n=R.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),Kr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:gh,action:Xu.OnCommunityJoined},{fn:mh,action:Xu.OnCommunityLeft},{fn:ph,action:Xu.OnCommunityLeft},{fn:oh,action:Xu.OnCommunityUserBanned},{fn:ih,action:Xu.OnCommunityUserChanged},{fn:ch,action:Xu.OnCommunityUserRoleAdded},{fn:dh,action:Xu.OnCommunityUserRoleRemoved},{fn:fh,action:Xu.OnCommunityUserRoleAdded},{fn:vh,action:Xu.OnCommunityUserRoleRemoved},{fn:rh,action:Xu.OnCommunityUserUnbanned},{fn:lh,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,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["communityUsers","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=dt(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(It);else n=n.sort(wt);return n}}class Ch extends fr{async getRequest(e,t){const{limit:n=me,includeDeleted:a,excludingRoles:s}=e,o=_n(e,["limit","includeDeleted","excludingRoles"]),i=t?{token:t}:{limit:n},r=!1!==a&&void 0,{data:c}=await this.http.get(`/api/v3/communities/${o.communityId}/users`,{params:Object.assign(Object.assign({},o),{options:i,isDeleted:r})});return c}}class wh extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>Xe("communityUsers")({communityId:e,userId:t})))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>Xe("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;a&&(t.forEach((e=>{const t=Xe("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership&&(a.data=a.data.filter((e=>e!==t)))})),at(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 Or{constructor(e,t){const n=R.default(e),a=["communityUsers","collection",n];super(new Ch(e),n,a,t),this.query=e,this.queryStreamController=new wh(this.query,this.cacheKey,this.notifyChange.bind(this),Kr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:gh,action:Sh.OnCommunityJoined},{fn:mh,action:Sh.OnCommunityLeft},{fn:ph,action:Sh.OnCommunityLeft},{fn:oh,action:Sh.OnCommunityUserBanned},{fn:ih,action:Sh.OnCommunityUserChanged},{fn:vh,action:Sh.OnCommunityUserRoleRemoved},{fn:dh,action:Sh.OnCommunityUserRoleRemoved},{fn:rh,action:Sh.OnCommunityUserUnbanned},{fn:bh(this.query.communityId),action:Sh.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["communityUsers","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=dt(e,"roles",this.query.roles);return this.query.memberships&&(n=n.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),this.query.search&&(n=gt(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=Ge();n.log("community/moderation/addMembers",e,t);const{data:a}=await n.http.post(`/api/v3/communities/${e}/users`,{communityId:e,userIds:t});xt("local.community.userAdded",a);const s=$n(a,"communityUsers");n.cache&&Nn(s);const{communityUsers:o}=s;return!!o.find((t=>t.communityId===e&&"member"===t.communityMembership))},removeMembers:async(e,t)=>{const n=Ge();n.log("community/moderation/removeMembers",e,t);const{data:a}=await n.http.delete(`/api/v3/communities/${e}/users`,{data:{communityId:e,userIds:t}});xt("local.community.userRemoved",a);const s=$n(a,"communityUsers");n.cache&&Nn(s);const{communityUsers:o}=s;return!!o.find((t=>t.communityId===e&&"member"!==t.communityMembership))},applyFilter:(e,t)=>{var n;let a=dt(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 s=t.sortBy?t.sortBy:"lastCreated";return a=a.sort("lastCreated"===s?wt:It),a},getMembers:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getMembers(tmpid: ${o}) > listen`);const i=new Ih(e,(e=>{t(e)})),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{it(c)})),()=>{a(`getMembers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},searchMembers:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getMembers(tmpid: ${o}) > listen`);const i=new Oh(e,(e=>{t(e)})),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{it(c)})),()=>{a(`getMembers(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},onCommunityUserAdded:e=>ah("community.userAdded",e),onCommunityUserRemoved:e=>ah("community.userRemoved",e),onCommunityUserBanned:oh,onCommunityUserChanged:ih,onCommunityUserUnbanned:rh,onCommunityUserRoleAdded:ch,onCommunityUserRoleRemoved:dh,onLocalCommunityUserAdded:lh,onLocalCommunityUserRemoved:uh,onCommunityJoined:hh,onCommunityLeft:mh,onLocalCommunityJoined:gh,onLocalCommunityLeft:ph,onLocalCommunityJoin:yh});class Ah extends Or{constructor(e,t){const n=R.default(e),a=["community","collection",n];super(new Gu(e),n,a,t),this.query=e,this.queryStreamController=new Yu(this.query,this.cacheKey,this.notifyChange.bind(this),Kr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:Wu.OnCommunityDeleted},{fn:Hu,action:Wu.OnCommunityUpdated},{fn:hh,action:Xu.OnCommunityJoined},{fn:mh,action:Xu.OnCommunityLeft},{fn:ih,action:Xu.OnMemberCountChanged},{fn:gh,action:Xu.OnCommunityJoined},{fn:ph,action:Xu.OnCommunityLeft},{fn:Td(yh,"targetId","community"),action:Wu.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["community","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Ge();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=ht(n,this.query.membership,t)),n}}class Rh extends fr{async getRequest(e,t){var n;const{limit:a=me}=e,s=_n(e,["limit"]),o=t?{token:t}:{limit:a},{data:i}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},s),{isDeleted:sa(s.includeDeleted),filter:s.membership,includeDiscoverablePrivateCommunity:null===(n=s.includeDiscoverablePrivateCommunity)||void 0===n||n,options:o})});return i}}class Ph extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&(Nn(t,{cachedAt:a}),$u(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.communities.map(Xe("community"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Xe("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=nt(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],at(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Dh;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Dh||(Dh={}));class Uh extends Or{constructor(e,t){const n=R.default(e),a=["community","collection",n];super(new Rh(e),n,a,t),this.query=e,this.queryStreamController=new Ph(this.query,this.cacheKey,this.notifyChange.bind(this),Kr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:Dh.OnCommunityCreated},{fn:zu,action:Dh.OnCommunityDeleted},{fn:Hu,action:Dh.OnCommunityUpdated},{fn:hh,action:Xu.OnCommunityJoined},{fn:mh,action:Xu.OnCommunityLeft},{fn:ih,action:Xu.OnMemberCountChanged},{fn:gh,action:Xu.OnCommunityJoined},{fn:ph,action:Xu.OnCommunityLeft},{fn:Td(yh,"targetId","community"),action:Dh.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>nt(["community","get",e]))).filter(Tr).map((({data:e})=>lc(e))))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Ge();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=ht(n,this.query.membership,t));const a=(()=>"firstCreated"===this.query.sortBy?It:wt)();return n=n.sort(a),n}}class kh extends fr{async getRequest(e,t){const{limit:n=me,includeDiscoverablePrivateCommunity:a}=e,s=_n(e,["limit","includeDiscoverablePrivateCommunity"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/communities/top-trending",{params:Object.assign(Object.assign({},s),{options:o,includeDiscoverablePrivateCommunity:null==a||a})});return i}}class jh extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&(Nn(t,{cachedAt:a}),$u(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.communities.map(Xe("community"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Xe("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=nt(this.cacheKey))||void 0===t?void 0:t.data;n&&(at(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.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Eh||(Eh={}));class Mh extends Or{constructor(e,t){const n=R.default(e),a=["trendingCommunity","collection",n];super(new kh(e),n,a,t),this.query=e,this.queryStreamController=new jh(this.query,this.cacheKey,this.notifyChange.bind(this),Kr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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.OnCommunityDeleted},{fn:Hu,action:Eh.OnCommunityUpdated},{fn:hh,action:Xu.OnCommunityJoined},{fn:mh,action:Xu.OnCommunityLeft},{fn:ih,action:Xu.OnMemberCountChanged},{fn:gh,action:Xu.OnCommunityJoined},{fn:ph,action:Xu.OnCommunityLeft},{fn:Td(yh,"targetId","community"),action:Eh.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>nt(["community","get",e]))).filter(Tr).map((({data:e})=>lc(e))))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class qh extends fr{async getRequest(e,t){const{limit:n=me,includeDiscoverablePrivateCommunity:a}=e,s=_n(e,["limit","includeDiscoverablePrivateCommunity"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/communities/recommended",{params:Object.assign(Object.assign({},s),{options:o,includeDiscoverablePrivateCommunity:null==a||a})});return i}}class xh extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&(Nn(t,{cachedAt:a}),$u(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.communities.map(Xe("community"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(Xe("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=nt(this.cacheKey))||void 0===t?void 0:t.data;n&&(at(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.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated",e.OnLocalCommunityJoin="onLocalCommunityJoin"}(Kh||(Kh={}));class Nh extends Or{constructor(e,t){const n=R.default(e),a=["community","collection",n];super(new qh(e),n,a,t),this.query=e,this.queryStreamController=new xh(this.query,this.cacheKey,this.notifyChange.bind(this),Kr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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.OnCommunityDeleted},{fn:Hu,action:Kh.OnCommunityUpdated},{fn:hh,action:Xu.OnCommunityJoined},{fn:mh,action:Xu.OnCommunityLeft},{fn:ih,action:Xu.OnMemberCountChanged},{fn:gh,action:Xu.OnCommunityJoined},{fn:ph,action:Xu.OnCommunityLeft},{fn:Td(yh,"targetId","community"),action:Kh.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>nt(["community","get",e]))).filter(Tr).map((({data:e})=>lc(e))))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class Fh extends fr{async getRequest(e,t){var n;const{limit:a=me,communityMembershipStatus:s}=e,o=_n(e,["limit","communityMembershipStatus"]),i={type:e.limit?"pagination":void 0},r=t?Object.assign(Object.assign({},i),{token:t}):Object.assign(Object.assign({},i),{limit:a}),{data:c}=await this.http.get("/api/v1/semantic-search/communities",{params:Object.assign(Object.assign({},o),{filter:null!=s?s:"all",options:r,includeDiscoverablePrivateCommunity:null===(n=o.includeDiscoverablePrivateCommunity)||void 0===n||n})});return c}}function _h(e){return e.communities.map((t=>{const n=e.searchResult.find((e=>e.communityId===t.communityId));return`${t.communityId}:${n}`}))}class Bh extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:_h(e)});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,..._h(e)])]}))}}reactor(e){return e=>{var t;const n=null===(t=nt(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],at(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var $h;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}($h||($h={}));class Lh extends Or{constructor(e,t){const n=R.default(e),a=["community","collection",n];super(new Fh(e),n,a,t),this.query=e,this.queryStreamController=new Bh(this.query,this.cacheKey,this.notifyChange.bind(this),Br),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:$h.OnCommunityCreated},{fn:zu,action:$h.OnCommunityDeleted},{fn:Hu,action:$h.OnCommunityUpdated},{fn:hh,action:Xu.OnCommunityJoined},{fn:mh,action:Xu.OnCommunityLeft},{fn:ih,action:Xu.OnMemberCountChanged},{fn:gh,action:Xu.OnCommunityJoined},{fn:ph,action:Xu.OnCommunityLeft},{fn:Td(yh,"targetId","community"),action:$h.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>{const[t,n]=e.split(":");return{communityId:t,score:parseFloat(n)}})).sort(((e,t)=>t.score-e.score)).map((({communityId:e})=>nt(["community","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Ge();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=ht(n,this.query.communityMembershipStatus,t)),n}}class Qh extends fr{async getRequest(e,t){const{limit:n=me,communityIds:a}=e,s=_n(e,["limit","communityIds"]),o=t?{token:t}:{limit:n},i=a.map((e=>encodeURIComponent(e))),{data:r}=await this.http.get("/api/v4/communities/join/requests",{params:Object.assign(Object.assign({},s),{options:o,communityIds:i})});return r}}var Vh;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(Vh||(Vh={}));class Jh extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.joinRequests.map((e=>Xe("joinRequest")({joinRequestId:e._id})))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>Xe("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(!a)return;const s=(Array.isArray(t)?t:[t]).map((e=>e.joinRequestId));if(e===Vh.OnLocalJoinRequestUpdated){if(!a.data.find((e=>s.includes(e))))return}e===Vh.OnLocalJoinRequestCreated&&(a.data=[...new Set([...s,...a.data])]),e===Vh.OnLocalJoinRequestDeleted&&(a.data=a.data.filter((e=>!s.includes(e)))),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Hh extends Or{constructor(e,t){const n=R.default(e),a=["joinRequestList","collection",n];super(new Qh(e),n,a,t),this.query=e,this.queryStreamController=new Jh(this.query,this.cacheKey,this.notifyChange.bind(this),Nr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:Jr,action:Vh.OnLocalJoinRequestCreated},{fn:Hr,action:Vh.OnLocalJoinRequestUpdated},{fn:zr,action:Vh.OnLocalJoinRequestUpdated},{fn:yh,action:Vh.OnLocalJoinRequestUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a;const s=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=this.applyFilter(s.data.map((e=>nt(["joinRequest","get",e]))).filter(Tr).map((({data:e})=>e)).map($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.communityIds&&this.query.communityIds.length>0&&(t=t.filter((e=>this.query.communityIds.some((t=>t===e.targetId)))));const n=(()=>"firstCreated"===this.query.sortBy?It:wt)();return t=t.sort(n),t}}var zh;!function(e){e.ALL="all",e.MEMBER="member",e.NOT_MEMBER="notMember"}(zh||(zh={}));var Gh=Object.freeze({__proto__:null,addRoles:async(e,t,n)=>{const a=Ge();a.log("community/moderation/addRoles",e,t,n);const{data:s}=await a.http.post(`/api/v4/communities/${e}/users/roles`,{communityId:e,roles:t,userIds:n}),o=Fr(s);a.cache&&Nn(o),xt("local.community.roleAdded",o);const{communityUsers:i}=o;return!!i.find((n=>n.communityId===e&&t.some((e=>n.roles.includes(e)))))},removeRoles:async(e,t,n)=>{const a=Ge();a.log("community/moderation/removeRoles",e,t,n);const{data:s}=await a.http.delete(`/api/v4/communities/${e}/users/roles`,{data:{communityId:e,roles:t,userIds:n}}),o=Fr(s);a.cache&&Nn(o),xt("local.community.roleRemoved",o);const{communityUsers:i}=o;return!!i.find((n=>n.communityId===e&&!t.some((e=>n.roles.includes(e)))))},banMembers:async(e,t)=>{const n=Ge();n.log("community/banMembers",{userIds:t,communityId:e});const{data:a}=await n.http.put(`/api/v3/communities/${e}/users/ban`,{userIds:t}),s=$n(a,"communityUsers"),o=n.cache&&Date.now();n.cache&&Nn(s,{cachedAt:o});const{communityUsers:i}=s;return{data:i.filter((e=>t.includes(e.userId))),cachedAt:o}},unbanMembers:async(e,t)=>{const n=Ge();n.log("community/unbanMembers",{userIds:t,communityId:e});const{data:a}=await n.http.put(`/api/v3/communities/${e}/users/unban`,{userIds:t}),s=$n(a,"communityUsers"),o=n.cache&&Date.now();n.cache&&Nn(s,{cachedAt:o});const{communityUsers:i}=s;return{data:i.filter((e=>t.includes(e.userId))),cachedAt:o}}}),Yh=Object.freeze({__proto__:null,Moderation:Gh,Membership:Th,getCommunityByIds:Lu,createCommunity:async e=>{const t=Ge();t.log("user/createCommunity",e);const{data:n}=await t.http.post("/api/v3/communities/",_r(e));xt("community.created",n);const a=Kr(n),s=t.cache&&Date.now();t.cache&&(Nn(a,{cachedAt:s}),$u(a.communities,a.communityUsers));const{communities:o}=a;return{data:dd.community(o[0]),cachedAt:s}},updateCommunity:async(e,t)=>{const n=Ge();n.log("community/updateCommunity",e,t);const{data:a}=await n.http.put(`/api/v3/communities/${e}`,_r(t));xt("community.updated",a);const s=Kr(a),o=n.cache&&Date.now();n.cache&&(Nn(s,{cachedAt:o}),$u(s.communities,s.communityUsers));const{communities:i}=s;return{data:dd.community(i.find((t=>t.communityId===e))),cachedAt:o}},deleteCommunity:async e=>{const t=Ge();t.log("community/deleteCommunity",e),await t.http.delete(`/api/v3/communities/${e}`);const n=await Qu(e);return xt("community.deleted",{communities:[n.data],categories:[],communityUsers:[],feeds:[],files:[],users:[]}),dd.community(n.data)},joinCommunity:async e=>{const t=Ge();t.log("community/joinCommunity",e);const{data:n}=await t.http.post(`/api/v3/communities/${e}/join`);xt("local.community.joined",n);const a=Kr(n),s=t.cache&&Date.now();t.cache&&Nn(a,{cachedAt:s});const{communityUsers:o}=a;return!!o.find((t=>t.communityId===e&&"member"===t.communityMembership))},leaveCommunity:async e=>{const t=Ge();t.log("community/leaveCommunity",e);const{data:n}=await t.http.delete(`/api/v3/communities/${e}/leave`);xt("local.community.left",n);const a=Kr(n),s=t.cache&&Date.now();t.cache&&Nn(a,{cachedAt:s});const{communityUsers:o}=a;return!!o.find((t=>t.communityId===e&&"member"!==t.communityMembership))},onCommunityCreated:Ju,onCommunityUpdated:Hu,onCommunityDeleted:zu,searchCommunities:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`searchCommunities(tmpid: ${o}) > listen`);const i=new Ah(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`searchCommunities(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getCommunities:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getCommunities(tmpid: ${o}) > listen`);const i=new Uh(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getCommunities(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getCommunity:(e,t)=>jr(e,t,"communityId",Qu,[Hu,zu,hh,mh,gh,ph,oh,rh,ih,Td(yh,"targetId","community")],{callbackDataSelector:e=>e?dd.community(e):e}),getTrendingCommunities:(e,t,n)=>{const{log:a,cache:s,userId:o}=Ge();s||console.log(ye);const i=Date.now();a(`getTrendingCommunities(tmpid: ${i}) > listen`);const r=new Mh(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>it(d))),()=>{a(`getTrendingCommunities(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}},getRecommendedCommunities:(e,t,n)=>{const{log:a,cache:s,userId:o}=Ge();s||console.log(ye);const i=Date.now();a(`getRecommendedCommunities(tmpid: ${i}) > listen`);const r=new Nh(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>it(d))),()=>{a(`getRecommendedCommunities(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}},semanticSearchCommunities:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`semanticSearchCommunities(tmpid: ${o}) > listen`);const i=new Lh(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`semanticSearchCommunities(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getJoinRequestList:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getJoinRequestList: (tmpid: ${o}) > listen`);const i=new Hh(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{it(c)})),()=>{a(`getJoinRequestList (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},get AmityCommunityMemberStatusFilter(){return zh}});const Wh=async e=>{const t=Ge();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&&Nn(n,{cachedAt:a});const{categories:s}=n;return{data:dd.category((null!=s?s:[]).find((t=>t.categoryId===e))),cachedAt:a}};Wh.locally=e=>{const t=Ge();if(t.log("category/getCategory.locally",e),!t.cache)return;const n=nt(["category","get",e]);return n?{data:dd.category(n.data),cachedAt:n.cachedAt}:void 0};const Xh=async e=>{const t=Ge();t.log("category/queryCategories",e);const n=null!=e?e:{},{page:a,limit:s,includeDeleted:o}=n,i=_n(n,["page","limit","includeDeleted"]),r=a?{token:a}:s?{limit:s}:void 0,{data:c}=await t.http.get("/api/v3/community-categories",{params:Object.assign(Object.assign({},i),{isDeleted:sa(o),options:r})}),{paging:d}=c,l=_n(c,["paging"]),{categories:u}=l,h=t.cache&&Date.now();if(t.cache){Nn(l,{cachedAt:h});const e=["category","query",Object.assign(Object.assign({},i),{includeDeleted:o,options:r})];at(e,{categories:null==u?void 0:u.map(Xe("category")),paging:d})}return{data:null!=u?u:[],cachedAt:h,paging:d}};Xh.locally=e=>{var t,n;const a=Ge();if(a.log("category/queryCategories.locally",e),!a.cache)return;const s=null!=e?e:{},{page:o,limit:i=10}=s,r=_n(s,["page","limit"]),c=o?{token:o}:i?{limit:i}:void 0,d=["category","query",Object.assign(Object.assign({},r),{options:c})],{data:l,cachedAt:u}=null!==(t=nt(d))&&void 0!==t?t:{};if(!(null==l?void 0:l.categories.length))return;const h=l.categories.map((e=>nt(["category","get",e]))).filter(Boolean).map((({data:e})=>e)),{paging:m}=l;return h.length===(null===(n=null==l?void 0:l.categories)||void 0===n?void 0:n.length)?{data:h,cachedAt:u,paging:m}:void 0};var Zh=Object.freeze({__proto__:null,getCategory:Wh,getCategories:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getCategories(tmpid: ${o}) > listen`);const{limit:i}=e,r=_n(e,["limit"]),c=null!=i?i:me,{policy:d=pe}=null!=n?n:{},l=[],u=["category","collection",{}],h=(n=!1)=>{var a,s;const o=null===(a=nt(u))||void 0===a?void 0:a.data,i=null!==(s=null==o?void 0:o.data)&&void 0!==s?s:[];if(!n&&i.length>0&&!(null==o?void 0:o.params.page))return;const l=Fe(Xh,Object.assign(Object.assign({},r),{limit:n?c:void 0,page:n||null==o?void 0:o.params.page}));Be(l,(({data:n,error:a,loading:s,paging:o})=>{const r={loading:s,error:a,params:{page:null==o?void 0:o.next},data:i};n&&(r.data=[...new Set([...i,...n.map(Xe("category"))])]),at(u,r),(n=>{var a,s;let o=null!==(a=n.data.map((e=>nt(["category","get",e]))).filter(Boolean).map((({data:e})=>dd.category(e))))&&void 0!==a?a:[];switch(e.includeDeleted||(o=rt(o,"isDeleted",!1)),e.sortBy){case"firstCreated":o=o.sort(It);break;case"lastCreated":o=o.sort(wt);break;default:o=o.sort(bt)}t({onNextPage:h,data:o,hasNextPage:!!(null===(s=n.params)||void 0===s?void 0:s.page),loading:n.loading,error:n.error})})(r)}),_e(d))};return l.push((()=>{})),h(!0),()=>{a(`getCategories(tmpid: ${o}) > dispose`),l.forEach((e=>e()))}}});const em=async e=>{const t=Ge();t.log("feed/queryGlobalFeed",e);const n=null!=e?e:{},{queryToken:a,dataTypes:s}=n,o=_n(n,["queryToken","dataTypes"]),i=(()=>{if(a)return{token:a}})(),{data:r}=await t.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},o),{dataTypes:s,resolveParent:!!(s&&s.length>0)||void 0,options:i})}),{paging:c}=r,d=_n(r,["paging"]),l=$n(d,"communityUsers"),{posts:u}=l,{communities:h}=Kr(l),m=t.cache&&Date.now();if(t.cache){Nn(Object.assign(Object.assign({},l),{communitis:h}));const e=["globalFeed","query",Object.assign(Object.assign({},o),{options:i})];at(e,{posts:u.map(Xe("post")),paging:c})}return{data:u.map(dd.post),cachedAt:m,paging:c}};em.locally=e=>{var t;const n=Ge();if(n.log("post/queryGlobalFeed.locally",e),!n.cache)return;const a=_n(null!=e?e:{},[]),s=["globalFeed","query",Object.assign({},a)],{data:o,cachedAt:i}=null!==(t=nt(s))&&void 0!==t?t:{};if(!(null==o?void 0:o.posts.length))return;const r=o.posts.map((e=>nt(["post","get",e]))).filter(Boolean).map((({data:e})=>e)).map(dd.post),{paging:c}=o;return r.length===o.posts.length?{data:r,cachedAt:i,paging:c}:void 0};class tm extends fr{async getRequest(e,t){const{limit:n}=e,a=_n(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v5/me/global-feeds",{params:Object.assign(Object.assign({},a),{options:s})});return o}}var nm;!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"}(nm||(nm={}));class am extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.posts.map(Xe("post"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Xe("post"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(a&&(!t.parentPostId||a.data.includes(t.parentPostId))){if(e===nm.OnPostDeleted&&(a.data=a.data.filter((e=>e!==t.postId))),e===nm.OnPostCreated||e===nm.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===nm.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const sm=async e=>{const t=Ge();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=>{Re(null==t?void 0:t.code)&&Fn("comment",e)})),t}const s=t.cache&&Date.now();return t.cache&&Nn(a,{cachedAt:s}),{data:a.comments.map((e=>dd.comment(e))),cachedAt:s}};sm.locally=e=>{var t;const n=Ge();if(n.log("comment/getCommentByIds.locally",e),!n.cache)return;const a=e.map((e=>nt(["comment","get",e]))).filter(Boolean),s=a.map((({data:e})=>e)),o=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:s.map((e=>dd.comment(e))),cachedAt:o.cachedAt}};const om=e=>{const t=Ge();if(!t.cache)return;const n=Un();t.log("comment/createComment.optimistically",Object.assign({commentId:n},e));const a=(new Date).toISOString(),s={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 at(["comment","get",s.commentId],s,{cachedAt:-5}),xt("local.comment.created",{comments:[s],commentChildren:[],users:[],files:[],communityUsers:[]}),s},im=(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})},rm=async e=>{const t=Ge();t.log("story/getStoryByStoryId",e);const n=nt(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;Zn("story",e)}let a;try{const n=await t.http.get(`/api/v4/stories/${e}`);a=im(n.data)}catch(t){throw Re(null==t?void 0:t.code)&&Fn("story",e),t}const s=t.cache&&Date.now();return t.cache&&Nn(a,{cachedAt:s}),{data:a.stories[0],cachedAt:s}};rm.locally=e=>{const t=Ge();t.log("story/getStorybyStoryId",e);const n=nt(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;Zn("story",e)}const a=t.cache&&Date.now(),s=nt(["story","get",e]);if(s)return{data:s.data,cachedAt:a}};const cm=async(e,t=!1)=>{var n,a,s;const o=Ge(),i=null===(n=nt(["comment","get",e]))||void 0===n?void 0:n.data;if("error"===(null==i?void 0:i.syncState)){const t=Object.assign(Object.assign({},i),{isDeleted:!0});return it(["comment","get",e]),xt("local.comment.deleted",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]}),t}const r=await Zd(e);await o.http.delete(`/api/v4/comments/${encodeURIComponent(e)}`,{params:{commentId:e,permanent:t}});const c=Object.assign(Object.assign({},r.data),{isDeleted:!0});if(t?Et((()=>Fn("comment",e))):ot(["comment","get",e],{isDeleted:!0}),"story"===r.data.referenceType){const e=await rm(r.data.referenceId);xt("local.story.updated",{stories:[e.data],categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[]})}else{const t=null===(a=nt(["post","get",r.data.referenceId]))||void 0===a?void 0:a.data;if(t){const n=Gd();n.queueCommentChangeTask(new Vd(t.postId,e)),!c.parentId&&(null===(s=c.children)||void 0===s?void 0:s.length)>0&&c.children.forEach((e=>{n.queueCommentChangeTask(new Vd(t.postId,e))}))}}return xt("local.comment.deleted",{comments:[c],commentChildren:[],files:[],users:[],communityUsers:[]}),c},dm=async e=>{const t=Ge();let n;t.log("comment/getComment",e),Zn("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw Re(null==t?void 0:t.code)&&Fn("comment",e),t}const a=t.cache&&Date.now();t.cache&&Nn(n,{cachedAt:a});const{comments:s}=n;return{data:s.find((t=>t.commentId===e)),cachedAt:a}};dm.locally=e=>{const t=Ge();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=nt(["comment","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const lm=e=>Il("local.comment.deleted",e),um=e=>{const t=Ge();return qt(t,"local.comment.addReaction","local.comment.addReaction",(({comment:n})=>{t.cache?(ot(["comment","get",n.commentId],n),e(vc(n))):e(n)}))},hm=e=>{const t=Ge();return qt(t,"local.comment.removeReaction","local.comment.removeReaction",(({comment:n})=>{t.cache?(ot(["comment","get",n.commentId],n),e(vc(n))):e(n)}))};class mm extends fr{async getRequest(e,t){var n;const{pageSize:a,limit:s,includeDeleted:o}=e,i=_n(e,["pageSize","limit","includeDeleted"]),r=null!==(n=null!=a?a:s)&&void 0!==n?n:me,c={type:i.sortBy||e.limit||e.pageSize?"pagination":void 0},d=t?Object.assign(Object.assign({},c),{token:t}):Object.assign(Object.assign({},c),{pageSize:r,limit:r}),{data:l}=await this.http.get("/api/v3/comments",{params:Object.assign(Object.assign({},i),{isDeleted:sa(o),options:d})});return l}}var gm;!function(e){e.OnCommentCreated="onCommentCreated",e.OnCommentUpdated="onCommentUpdated",e.OnCommentDeleted="onCommentDeleted",e.OnCommentFlagged="onCommentFlagged",e.OnCommentUnflagged="onCommentUnflagged",e.OnCommentReactionAdded="onCommentReactionAdded",e.OnCommentReactionRemoved="onCommentReactionRemoved"}(gm||(gm={}));class pm extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.comments.map(Xe("comment"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.comments.map(Xe("comment"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(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===gm.OnCommentCreated&&(a.data=[...new Set([t.commentId,...a.data])]),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const ym=e=>Il("local.comment.created",e);class vm extends Or{constructor(e,t){const n=R.default(e),a=["comments","collection",n];super(new mm(e),n,a,t),this.query=e,this.queryStreamController=new pm(this.query,this.cacheKey,this.notifyChange.bind(this),Ml),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:ym,action:gm.OnCommentCreated},{fn:lm,action:gm.OnCommentDeleted},{fn:Cl,action:gm.OnCommentCreated},{fn:wl,action:gm.OnCommentUpdated},{fn:Sl,action:gm.OnCommentDeleted},{fn:Ol,action:gm.OnCommentFlagged},{fn:Tl,action:gm.OnCommentUnflagged},{fn:Al,action:gm.OnCommentReactionAdded},{fn:Rl,action:gm.OnCommentReactionRemoved},{fn:um,action:gm.OnCommentReactionAdded},{fn:hm,action:gm.OnCommentReactionRemoved}]);if(this.query.excludeBlockUserComments){const t=()=>this.notifyChange({origin:"event",loading:!1});e.push(Ho(t),zo(t))}return e}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["comment","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(dd.comment);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,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())||[],s=(null===(n=e.dataTypes)||void 0===n?void 0:n.sort())||[];return s.length===a.length&&a.every(((e,t)=>e===s[t]))}))),"any"===this.query.dataTypes.matchType&&(t=t.filter((e=>{var t;return null===(t=this.query.dataTypes)||void 0===t?void 0:t.values.some((t=>{var n;return null===(n=e.dataTypes)||void 0===n?void 0:n.includes(t)}))})))),this.query.excludeBlockUserComments&&(t=vt(t)),"firstCreated"===this.query.sortBy)t=t.sort(It);else t=t.sort(wt);return t}}var fm=Object.freeze({__proto__:null,getCommentByIds:sm,createComment:async e=>{const t=Ge();t.log("comment/createComment",e);const n=om(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:s}=n;if(0===s.length)throw new Error("Comment not created");const o=t.cache&&Date.now();if(t.cache&&Nn(n,{cachedAt:o}),["post","content"].includes(e.referenceType))Gd().queueCommentChangeTask(new Qd(e.referenceId,s[0].commentId,n.comments[0].createdAt));else if("story"===e.referenceType){const t=nt(["story-reference",e.referenceId]);if(null==t?void 0:t.data){const e=nt(["story","get",t.data]);(null==e?void 0:e.data)&&xt("story.updated",{stories:[Object.assign(Object.assign({},e.data),{commentsCount:e.data.commentsCount+1,comments:[...new Set([...e.data.comments,s[0].commentId])]})],categories:[],comments:s,communities:[],communityUsers:n.communityUsers,files:n.files,users:n.users})}}return xt("local.comment.created",{comments:[Object.assign(Object.assign({},s[0]),{syncState:"synced"})],commentChildren:n.commentChildren,users:n.users,files:n.files,communityUsers:n.communityUsers}),{data:dd.comment(s[0]),cachedAt:o}}catch(e){throw n&&xt("local.comment.created",{comments:[Object.assign(Object.assign({},n),{syncState:"error"})],commentChildren:[],users:[],files:[],communityUsers:[]}),e}},updateComment:async(e,t)=>{const n=Ge();n.log("user/updateComment",t);const{data:a}=await n.http.put(`/api/v3/comments/${encodeURIComponent(e)}`,t),s=n.cache&&Date.now();n.cache&&Nn(a,{cachedAt:s}),xt("comment.updated",a);const{comments:o}=a;return{data:dd.comment(o.find((t=>t.commentId===e))),cachedAt:s}},deleteComment:cm,softDeleteComment:async e=>{Ge().log("comment/softDeleteComment",e);return cm(e)},hardDeleteComment:async e=>{Ge().log("comment/hardDeleteComment",e);return cm(e,!0)},flagComment:async(t,n)=>{const a=Ge();a.log("comment/flagComment",t);const s=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,a])=>t!==e.ContentFlagReasonEnum.Others&&a===n)),o={reason:n&&s?n:e.ContentFlagReasonEnum.Others,detail:n&&!s?n:""},{data:i}=await a.http.post(`/api/v3/comments/${encodeURIComponent(t)}/flag`,o);return a.cache&&Nn(i),xt("comment.flagged",i),!!i},unflagComment:async e=>{const t=Ge();t.log("comment/unflagComment",e);const{data:n}=await t.http.delete(`/api/v3/comments/${encodeURIComponent(e)}/unflag`);return t.cache&&Nn(n),xt("comment.unflagged",n),!!n},isCommentFlaggedByMe:async e=>{const t=Ge();t.log("comment/isCommentFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/comments/${e}/isflagbyme`);return n},onCommentCreated:Cl,onCommentUpdated:wl,onCommentDeleted:Sl,onCommentFlagged:Ol,onCommentUnflagged:Tl,onCommentReactionAdded:Al,onCommentReactionRemoved:Rl,getComment:(e,t)=>jr(e,t,"commentId",dm,[lm,Sl,Ol,Al,Rl,Tl,wl,um,hm]),getComments:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log("For using Live Collection feature you need to enable Cache!");const o=Date.now();a(`getComments(tmpid: ${o}) > listen`);const i=new vm(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getComments(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});const bm=e=>dl("local.post.deleted",e),Im=e=>{const t=Ge();return qt(t,"local.post.addReaction","local.post.addReaction",(({post:n})=>{t.cache?(ot(["post","get",n.postId],n),e(n)):e(n)}))},Cm=e=>{const t=Ge();return qt(t,"local.post.removeReaction","local.post.removeReaction",(({post:n})=>{t.cache?(ot(["post","get",n.postId],n),e(n)):e(n)}))},wm=e=>dl("local.post.updated",e),Sm=e=>[Cl,Sl,ym,lm].map((t=>({fn:Td((n=>((e,t,n)=>t((async t=>{var a;const s=null===(a=nt(n))||void 0===a?void 0:a.data;s&&s.data.includes(t.referenceId)&&e(t)})))(n,t,e)),"referenceId","post"),action:nm.OnPostUpdated}))),Om=e=>[{fn:ll,action:nm.OnPostCreated},{fn:ul,action:nm.OnPostUpdated},{fn:wm,action:nm.OnPostUpdated},{fn:hl,action:nm.OnPostDeleted},{fn:pl,action:nm.OnPostFlagged},{fn:yl,action:nm.OnPostUnflagged},{fn:ml,action:nm.OnPostApproved},{fn:gl,action:nm.OnPostDeclined},{fn:vl,action:nm.OnPostReactionAdded},{fn:fl,action:nm.OnPostReactionRemoved},{fn:Im,action:nm.OnPostReactionAdded},{fn:Cm,action:nm.OnPostReactionRemoved},{fn:bm,action:nm.OnPostDeleted},...Sm(e)];class Tm extends Or{constructor(e,t){const n=R.default(e),a=["customRankingGlobalFeed","collection",n];super(new tm(e),n,a,t),this.query=e,this.queryStreamController=new am(this.query,this.cacheKey,this.notifyChange.bind(this),Yd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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(Om(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>nt(["post","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(dd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class Am extends fr{async getRequest(e,t){const{limit:n,dataTypes:a}=e,s=_n(e,["limit","dataTypes"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},s),{dataTypes:a,resolveParent:!!(a&&a.length>0)||void 0,options:o})});return i}}class Rm extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.posts.map(Xe("post"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Xe("post"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(a&&(!t.parentPostId||a.data.includes(t.parentPostId))){if(e===nm.OnPostDeleted&&(a.data=a.data.filter((e=>e!==t.postId))),e===nm.OnPostCreated||e===nm.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===nm.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Pm extends Or{constructor(e,t){const n=R.default(e),a=["globalFeed","collection",n];super(new Am(e),n,a,t),this.query=e,this.queryStreamController=new Rm(this.query,this.cacheKey,this.notifyChange.bind(this),Yd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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(Om(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>nt(["post","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(dd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class Dm extends fr{async getRequest(e,t){const{userId:n,feedSources:a,dataTypes:s,includeDeleted:o,matchingOnlyParentPost:i,limit:r=me,untilAt:c}=e,d=_n(e,["userId","feedSources","dataTypes","includeDeleted","matchingOnlyParentPost","limit","untilAt"]),l=t?{token:t}:{limit:r},{data:u}=await this.http.get(`/api/v4/user-feeds/${n}`,{params:Object.assign(Object.assign({},d),{options:l,dataTypes:(null==s?void 0:s.length)?s:void 0,includePostedFeed:a,isDeleted:sa(o),matchingOnlyParentPost:null!=i?i:!(null==s?void 0:s.length)})});return u}}class Um extends Ir{constructor(e,t,n,a){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=a,this.validatedUntilAt=e.untilAt?At(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;let o=e.posts;if(n&&(this.boundaryReached=!1),void 0!==this.validatedUntilAt){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated",t=o.filter((t=>!Rt(t.createdAt,this.validatedUntilAt,e)));t.length<o.length&&(this.boundaryReached=!0),o=t}if(n)at(this.cacheKey,{data:o.map(Xe("post"))});else{const e=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,t=null!==(s=null==e?void 0:e.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...o.map(Xe("post"))])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(s&&(this.query.dataTypes&&0!==this.query.dataTypes.length||s.data.includes(t.parentPostId?t.parentPostId:t.postId))){if(void 0!==this.validatedUntilAt&&(e===nm.OnPostCreated||e===nm.OnPostApproved||e===nm.OnPostUpdated)){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";if(Rt(t.createdAt,this.validatedUntilAt,e))return}if(e===nm.OnPostDeleted&&(s.data=s.data.filter((e=>e!==t.postId))),t.parentPostId&&t.isDeleted){const e=null===(a=nt(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),at(["post","get",e.postId],e)}if(e===nm.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e===nm.OnPostCreated||e===nm.OnPostApproved){if(this.query.dataTypes&&this.query.dataTypes.length>0&&!this.query.dataTypes.includes(t.dataType))return;s.data=[...new Set([t.postId,...s.data])]}at(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}hasBoundaryReached(){return this.boundaryReached}}const km=async e=>{const t=Ge();let n;t.log("post/getPost",e),Zn("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw Re(null==t?void 0:t.code)&&Fn("post",e),t}const a=$n(n,"communityUsers"),s=t.cache&&Date.now();t.cache&&Nn(a,{cachedAt:s});const{posts:o}=a;return{data:o.find((t=>t.postId===e)),cachedAt:s}};km.locally=e=>{const t=Ge();if(t.log("post/getPost.locally",e),!t.cache)return;const n=nt(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class jm extends Or{constructor(e,t){const n=R.default(e),a=["userFeed","collection",n];super(new Dm(e),n,a,t),this.query=e,this.queryStreamController=new Um(this.query,this.cacheKey,this.notifyChange.bind(this),Yd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:ll,action:nm.OnPostCreated},{fn:ul,action:nm.OnPostUpdated},{fn:wm,action:nm.OnPostUpdated},{fn:hl,action:nm.OnPostDeleted},{fn:pl,action:nm.OnPostFlagged},{fn:yl,action:nm.OnPostUnflagged},{fn:ml,action:nm.OnPostApproved},{fn:gl,action:nm.OnPostDeclined},{fn:vl,action:nm.OnPostReactionAdded},{fn:fl,action:nm.OnPostReactionRemoved},{fn:Im,action:nm.OnPostReactionAdded},{fn:Cm,action:nm.OnPostReactionRemoved},{fn:bm,action:nm.OnPostDeleted},{fn:Td((e=>Cl((async t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await km(t.referenceId),e(t))}))),"referenceId","post"),action:nm.OnPostUpdated},{fn:Td((e=>Sl((async t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await km(t.referenceId),e(t))}))),"referenceId","post"),action:nm.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>nt(["post","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[],r=this.applyFilter(i).map(dd.post);if(!this.shouldNotify(r)&&"event"===e)return;const c=!this.queryStreamController.hasBoundaryReached()&&!!this.paginationController.getNextToken();this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:r,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=mt(n,this.query.dataTypes)),this.query.untilAt){const e=At(this.query.untilAt),t="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";n=n.filter((n=>!Rt(n.createdAt,e,t)))}if("firstCreated"===this.query.sortBy)n=n.sort(It);else n=n.sort(wt);return n}}class Em extends fr{async getRequest(e,t){const{limit:n=me,includeDeleted:a,communityId:s,untilAt:o}=e,i=_n(e,["limit","includeDeleted","communityId","untilAt"]),r=t?{token:t}:{limit:n},{data:c}=await this.http.get("/api/v5/posts",{params:Object.assign(Object.assign({},i),{targetId:s,targetType:"community",isDeleted:sa(a),matchingOnlyParentPost:!0,options:r})});return c}}class Mm extends Ir{constructor(e,t,n,a){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=a,this.validatedUntilAt=e.untilAt?At(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;let o=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=o.filter((t=>!Rt(t.createdAt,this.validatedUntilAt,e)));t.length<o.length&&(this.boundaryReached=!0),o=t}if(n)at(this.cacheKey,{data:o.map(Xe("post"))});else{const e=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,t=null!==(s=null==e?void 0:e.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...o.map(Xe("post"))])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(void 0!==this.validatedUntilAt&&(e===nm.OnPostCreated||e===nm.OnPostApproved)&&"firstUpdated"!==this.query.sortBy&&"lastUpdated"!==this.query.sortBy){const e="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";if(Rt(t.createdAt,this.validatedUntilAt,e))return}if(e===nm.OnPostDeleted&&(s.data=s.data.filter((e=>e!==t.postId))),t.parentPostId&&t.isDeleted){const e=null===(a=nt(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),at(["post","get",e.postId],e)}e===nm.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==nm.OnPostCreated&&e!==nm.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),at(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}hasBoundaryReached(){return this.boundaryReached}}const qm=({cacheKey:e,resolveId:t})=>[Cl,Sl,ym,lm].map((n=>({fn:Td((a=>((e,t,n,a)=>t((async t=>{var s;const o=null===(s=nt(n))||void 0===s?void 0:s.data;o&&o.data.includes(a?a(t.referenceId):t.referenceId)&&e(t)})))(a,n,e,t)),"referenceId","post"),action:nm.OnPostUpdated}))),xm=e=>[{fn:ll,action:nm.OnPostCreated},{fn:ul,action:nm.OnPostUpdated},{fn:wm,action:nm.OnPostUpdated},{fn:hl,action:nm.OnPostDeleted},{fn:pl,action:nm.OnPostFlagged},{fn:yl,action:nm.OnPostUnflagged},{fn:ml,action:nm.OnPostApproved},{fn:gl,action:nm.OnPostDeclined},{fn:vl,action:nm.OnPostReactionAdded},{fn:fl,action:nm.OnPostReactionRemoved},{fn:Im,action:nm.OnPostReactionAdded},{fn:Cm,action:nm.OnPostReactionRemoved},{fn:bm,action:nm.OnPostDeleted},...qm({cacheKey:e})],Km=(e,t)=>{var n;return null!==(n=e.map((e=>{const n=t.find((t=>t.postId===e.referenceId));return n?Xe("post")({postId:null==n?void 0:n.postId}):void 0})).filter(Tr))&&void 0!==n?n:[]};class Nm extends Or{constructor(e,t){const n=R.default(e),a=["communityFeed","collection",n];super(new Em(e),n,a,t),this.query=e,this.queryStreamController=new Mm(this.query,this.cacheKey,this.notifyChange.bind(this),Yd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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(xm(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["post","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(dd.post);if(!this.shouldNotify(i)&&"event"===e)return;const r=!this.queryStreamController.hasBoundaryReached()&&!!this.paginationController.getNextToken();this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:r,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=At(this.query.untilAt),n="firstCreated"===this.query.sortBy?"firstCreated":"lastCreated";t=t.filter((t=>!Rt(t.createdAt,e,n)))}switch(this.query.sortBy){case"firstCreated":t=t.sort(It);break;case"firstUpdated":t=t.sort(St);break;case"lastUpdated":t=t.sort(Ot);break;default:t=t.sort(wt)}return t}}class Fm extends Qe{constructor(e="For You feed is not enabled for this network"){super(e,400400,"error"),this.type="AmityForYouFeedDisabledError"}}class _m extends fr{constructor(e){super(e),this.checkedDisk=!1,this.hasDeliveredPost=!1,this.cursor=Go.current()}async getRequest(e,t){var n,a,s,o,i;const r=void 0===t;let c=null;if(r&&!this.checkedDisk&&this.cursor&&(this.checkedDisk=!0,c=await this.cursor.get(),c&&Go.isExpired(c.expiredAt)&&(await this.cursor.clear(),c=null)),r&&(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 d=r&&c?c.cursor:t,l=await this.fetch(d);if(l.posts.length>0&&(this.hasDeliveredPost=!0),null===(s=l.paging)||void 0===s?void 0:s.next)await this.persistCursor(l);else if(this.hasDeliveredPost&&this.cursor){const e=Date.parse(null!==(i=null===(o=l.paging)||void 0===o?void 0:o.expiredAt)&&void 0!==i?i:"");Number.isNaN(e)||await this.cursor.markReachedEndOfFeed(e)}return l}async fetch(e){const t={limit:ge};e&&(t.token=e);try{const{data:e}=await this.http.get(Ce,{params:{options:t}});return e}catch(t){if(t instanceof Qe&&400300===t.code)throw new Fm;if(t instanceof Qe&&400322===t.code&&void 0!==e){this.cursor&&await this.cursor.clear();const{data:e}=await this.http.get(Ce,{params:{options:{limit:ge}}});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,s=null===(n=e.paging)||void 0===n?void 0:n.expiredAt;if(!a||!s)return;const o=Date.parse(s);Number.isNaN(o)||await this.cursor.set({cursor:a,expiredAt:o})}}class Bm extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.posts.map(Xe("post"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Xe("post"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;a&&(t.parentPostId&&!a.data.includes(t.parentPostId)||(e!==nm.OnPostDeleted&&e!==nm.OnPostDeclined||(a.data=a.data.filter((e=>e!==t.postId))),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const $m=["forYouFeed","collection"];class Lm extends Or{constructor(e){const t=`for-you-feed-${Ge().userId}`,n={};super(new _m(n),t,$m,e),this.queryStreamController=new Bm(n,this.cacheKey,this.notifyChange.bind(this),Yd),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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(Om(this.cacheKey))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>nt(["post","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(dd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var Qm=Object.freeze({__proto__:null,queryGlobalFeed:em,getCustomRankingGlobalFeed:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getCustomRankingGlobalFeed(tmpid: ${o}) > listen`);const i=new Tm(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getCustomRankingGlobalFeed(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getGlobalFeed:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getGlobalFeed(tmpid: ${o}) > listen`);const i=new Pm(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getGlobalFeed(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getUserFeed:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getUserFeed(tmpid: ${o}) > listen`);const i=new jm(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getUserFeed(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getCommunityFeed:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getCommunityFeed(tmpid: ${o}) > listen`);const i=new Nm(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getCommunityFeed(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getForYouFeed:e=>{const{log:t,cache:n}=Ge();n||console.log(ye);const a=Date.now();t(`getForYouFeed(tmpid: ${a}) > listen`);const s=new Lm(e),o=s.startSubscription(),i=s.getCacheKey();return o.push((()=>it(i))),()=>{t(`getForYouFeed(tmpid: ${a}) > dispose`),o.forEach((e=>e()))}},AmityForYouFeedDisabledError:Fm});const Vm=async e=>{const t=Ge();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=>{Re(null==t?void 0:t.code)&&Fn("post",e)})),t}const s=$n(a,"communityUsers"),o=t.cache&&Date.now();return t.cache&&Nn(s,{cachedAt:o}),{data:s.posts.map(dd.post),cachedAt:o}};Vm.locally=e=>{var t;const n=Ge();if(n.log("post/getPostByIds.locally",e),!n.cache)return;const a=e.map((e=>nt(["post","get",e]))).filter(Boolean),s=a.map((({data:e})=>e)),o=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:s.map(dd.post),cachedAt:o.cachedAt}};const Jm=async(e,t=!1)=>{var n;const a=Ge(),s=await Xd(e);if(await a.http.delete(`/api/v4/posts/${encodeURIComponent(e)}`,{params:{postId:e,permanent:t}}),"community"===s.data.targetType){const e=await Qu(s.data.targetId),t=(null!==(n=tt(["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));xt("community.updated",{communities:[e.data],categories:[],communityUsers:t,feeds:[],files:[],users:[]})}const o=Object.assign(Object.assign({},s.data),{isDeleted:!0});return t?setTimeout((()=>{Fn("post",e)}),0):ot(["post","get",e],{isDeleted:!0}),xt("local.post.deleted",{posts:[o],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[],videoStreamings:[]}),dd.post(o)};class Hm extends fr{async getRequest(e,t){const{limit:n=me,includeDeleted:a,matchingOnlyParentPost:s,untilAt:o}=e,i=_n(e,["limit","includeDeleted","matchingOnlyParentPost","untilAt"]),{dataTypes:r}=i,c={type:i.sortBy||e.limit?"pagination":void 0},d=t?Object.assign(Object.assign({},c),{token:t}):Object.assign(Object.assign({},c),{limit:n}),{data:l}=await this.http.get("/api/v5/posts",{params:Object.assign(Object.assign({},i),{isDeleted:sa(a),matchingOnlyParentPost:null!=s?s:!(null==r?void 0:r.length),options:d})});return l}}class zm extends Ir{constructor(e,t,n,a){super(e,t),this.boundaryReached=!1,this.notifyChange=n,this.preparePayload=a,this.validatedUntilAt=e.untilAt?At(e.untilAt):void 0}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;let o=e.posts;if(n&&(this.boundaryReached=!1),void 0!==this.validatedUntilAt){const e=this.query.sortBy||"lastCreated",t=o.filter((t=>!Rt(t.createdAt,this.validatedUntilAt,e)));t.length<o.length&&(this.boundaryReached=!0),o=t}if(n)at(this.cacheKey,{data:o.map(Xe("post"))});else{const e=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,t=null!==(s=null==e?void 0:e.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...o.map(Xe("post"))])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(void 0!==this.validatedUntilAt&&(e===nm.OnPostCreated||e===nm.OnPostApproved)){const e=this.query.sortBy||"lastCreated";if(Rt(t.createdAt,this.validatedUntilAt,e))return}if(t.parentPostId&&t.isDeleted){const e=null===(a=nt(["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)),at(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===nm.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==nm.OnPostCreated&&e!==nm.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),at(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}hasBoundaryReached(){return this.boundaryReached}}class Gm extends Or{constructor(e,t){const n=R.default(e),a=["posts","collection",n];super(new Hm(e),n,a,t),this.query=e,this.queryStreamController=new zm(this.query,this.cacheKey,this.notifyChange.bind(this),Yd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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(xm(this.cacheKey));if(this.query.excludeBlockUserPosts){const t=()=>this.notifyChange({origin:"event",loading:!1});e.push(Ho(t),zo(t))}return e}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["post","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(dd.post);if(!this.shouldNotify(i)&&"event"===e)return;const r=!this.queryStreamController.hasBoundaryReached()&&!!this.paginationController.getNextToken();this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:r,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=ut(n,this.query.feedType)),(null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=mt(n,this.query.dataTypes)),this.query.untilAt){const e=At(this.query.untilAt),t=this.query.sortBy||"lastCreated";n=n.filter((n=>!Rt(n.createdAt,e,t)))}if(this.query.excludeBlockUserPosts&&(n=yt(n)),"firstCreated"===this.query.sortBy)n=n.sort(It);else n=n.sort(wt);return n}}class Ym extends fr{async getRequest(e,t){const n=_n(e,["limit"]),{communityId:a,placement:s}=n,o=_n(n,["communityId","placement"]),i=s?`/api/v1/pinned-posts/communities/${a}/${s}`:`/api/v1/pinned-posts/communities/${a}`,{data:r}=await this.http.get(i,{params:Object.assign({},o)});return r}}class Wm extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=Ge(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users?e.users.map(ga):[]});Nn(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.pins.map(Xe("pin"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(Xe("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===nm.OnPostDeleted&&(a.data=a.data.filter((e=>e!==`global#${t.postId}`))),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Xm extends Or{constructor(e,t){const n=R.default(e),a=["pinnedPosts","collection",n];super(new Ym(e),n,a,t),this.query=e,this.queryStreamController=new Wm(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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(qm({cacheKey:this.cacheKey,resolveId:e=>`${this.query.placement}#${e}`}))}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;let i=(null!==(s=o.data.map((e=>nt(["pin","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(dd.pinnedPost);i=this.applyFilter(i),(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,loading:t,error:n})}applyFilter(e){let t=e;if("lastCreated"===this.query.sortBy)t=t.sort((({post:e},{post:t})=>wt({createdAt:null==e?void 0:e.createdAt},{createdAt:null==t?void 0:t.createdAt})));return t}}class Zm extends fr{async getRequest(e,t){const n=_n(e,["limit"]),{data:a}=await this.http.get("/api/v1/pinned-posts/global",{params:Object.assign({},n)});return a}}class eg extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=Ge(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users.map(ga)});Nn(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.pins.map(Xe("pin"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(Xe("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===nm.OnPostDeleted&&(a.data=a.data.filter((e=>e!==`global#${t.postId}`))),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class tg extends Or{constructor(e,t){const n=R.default(e),a=["pinnedPosts","collection",n];super(new Zm(e),n,a,t),this.query=e,this.queryStreamController=new eg(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:bm,action:nm.OnPostDeleted},{fn:hl,action:nm.OnPostDeleted},...qm({cacheKey:this.cacheKey,resolveId:e=>`global#${e}`})])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>nt(["pin","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(dd.pinnedPost);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,loading:t,error:n})}}class ng extends fr{async getRequest(e,t){const{limit:n=me}=e,a=_n(e,["limit"]),s={type:e.limit?"pagination":void 0},o=t?Object.assign(Object.assign({},s),{token:t}):Object.assign(Object.assign({},s),{limit:n}),{data:i}=await this.http.get("/api/v1/semantic-search/posts",{params:Object.assign(Object.assign({},a),{options:o})});return i}}function ag(e){return e.posts.map((t=>{const n=e.searchResult.find((e=>e.postId===t.postId));return`${t.postId}:${n.score}`}))}function sg(e){return(null!=e?e:[]).map((e=>e.split(":")[0]))}class og extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:ag(e)});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...ag(e)])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(t.parentPostId&&t.isDeleted){const e=null===(a=nt(["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)),at(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===nm.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==nm.OnPostCreated&&e!==nm.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),at(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class ig extends Or{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=R.default(n),s=["posts","collection",a];super(new ng(n),a,s,t),this.query=n,this.queryStreamController=new og(this.query,this.cacheKey,this.notifyChange.bind(this),Wd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:ul,action:nm.OnPostUpdated},{fn:hl,action:nm.OnPostDeleted},{fn:pl,action:nm.OnPostFlagged},{fn:yl,action:nm.OnPostUnflagged},{fn:ml,action:nm.OnPostApproved},{fn:gl,action:nm.OnPostDeclined},{fn:vl,action:nm.OnPostReactionAdded},{fn:fl,action:nm.OnPostReactionRemoved},{fn:Td((e=>Cl((async t=>{const n=nt(this.cacheKey);sg(null==n?void 0:n.data).includes(t.referenceId)||(await Xd(t.referenceId),e(t))}))),"referenceId","post"),action:nm.OnPostUpdated},{fn:Td((e=>Sl((async t=>{const n=nt(this.cacheKey);sg(null==n?void 0:n.data).includes(t.referenceId)||(await Xd(t.referenceId),e(t))}))),"referenceId","post"),action:nm.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>{const[t,n]=e.split(":");return{postId:t,score:parseFloat(n)}})).sort(((e,t)=>t.score-e.score)).map((({postId:e})=>nt(["post","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(dd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,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=mt(t,this.query.dataTypes)),t}}class rg extends fr{async getRequest(e,t){const{limit:n=me,matchingOnlyParentPost:a,hashtags:s,dataTypes:o,targetType:i="all"}=e,r=_n(e,["limit","matchingOnlyParentPost","hashtags","dataTypes","targetType"]),c={type:r.sortBy||e.limit?"pagination":void 0},d=t?Object.assign(Object.assign({},c),{token:t}):Object.assign(Object.assign({},c),{limit:n}),{data:l}=await this.http.get("/api/v1/search/posts",{params:Object.assign(Object.assign({},r),{hashtags:s,dataTypes:o,targetType:i,matchingOnlyParentPost:null!=a?a:!(null==o?void 0:o.length),options:d})});return l}}class cg extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.posts.map(Xe("post"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(Xe("post"))])]}))}}reactor(e){return t=>{var n,a;const s=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(t.parentPostId&&t.isDeleted){const e=null===(a=nt(["post","get",t.parentPostId]))||void 0===a?void 0:a.data;if(!e)return;e.children=e.children.filter((e=>e!==t.postId)),at(["post","get",e.postId],e)}e===nm.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==nm.OnPostCreated&&e!==nm.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),at(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class dg extends Or{constructor(e,t){const n=R.default(e),a=["posts","collection",n];super(new rg(e),n,a,t),this.query=e,this.queryStreamController=new cg(this.query,this.cacheKey,this.notifyChange.bind(this),Yd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:ll,action:nm.OnPostCreated},{fn:ul,action:nm.OnPostUpdated},{fn:wm,action:nm.OnPostUpdated},{fn:hl,action:nm.OnPostDeleted},{fn:pl,action:nm.OnPostFlagged},{fn:yl,action:nm.OnPostUnflagged},{fn:ml,action:nm.OnPostApproved},{fn:gl,action:nm.OnPostDeclined},{fn:vl,action:nm.OnPostReactionAdded},{fn:fl,action:nm.OnPostReactionRemoved},{fn:Im,action:nm.OnPostReactionAdded},{fn:Cm,action:nm.OnPostReactionRemoved},{fn:bm,action:nm.OnPostDeleted},{fn:Td((e=>Cl((async t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await km(t.referenceId),e(t))}))),"referenceId","post"),action:nm.OnPostUpdated},{fn:Td((e=>Sl((async t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;a&&!a.data.includes(t.referenceId)&&(await km(t.referenceId),e(t))}))),"referenceId","post"),action:nm.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["post","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(dd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,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=mt(n,this.query.dataTypes)),"firstCreated"===this.query.sortBy)n=n.sort(It);else n=n.sort(wt);return n}}class lg extends Sr{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 ug extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:Km(e.rooms,e.posts)});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...Km(e.rooms,e.posts)])]}))}}reactor(e){return e=>{var t;const n=null===(t=nt(this.cacheKey))||void 0===t?void 0:t.data;n&&("ended"===e.status&&at(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 hg=e=>{const t=Ge();return qt(t,"room/onRoomStartBroadcasting","room.startBroadcasting",(t=>{Nn(t),e(t.rooms[0])}))},mg=e=>{const t=Ge();return qt(t,"room/onRoomWaitingReconnect","room.waitingReconnect",(t=>{Nn(t),e(t.rooms[0])}))},gg=e=>{const t=Ge();return qt(t,"room/onRoomEndBroadcasting","room.endBroadcasting",(t=>{Nn(t),e(t.rooms[0])}))},pg=e=>{const t=Ge();return qt(t,"room/onRoomRecordedAvailable","room.recordedAvailable",(t=>{Nn(t),e(t.rooms[0])}))},yg=e=>{const t=Ge();return qt(t,"room/onRoomCoHostInvited","room.didCohostInvite",(t=>{const n=Zr(t);Nn(n),e(n.invitations)}))},vg=async e=>{const t=Ge();let n;t.log("room/getRoomById",e),Zn("room",e);try{n=(await t.http.get(`/api/v1/rooms/${e}`)).data}catch(t){throw Re(null==t?void 0:t.code)&&Fn("room",e),t}const a=t.cache&&Date.now();return t.cache&&Nn(n,{cachedAt:a}),{data:n.rooms[0],cachedAt:a}};vg.locally=e=>{const t=Ge();t.log("room/getRoomById.locally",e),Zn("room",e);const n=t.cache&&Date.now(),a=nt(["room","get",e]);if(a)return{data:a.data,cachedAt:n}};const fg=e=>{const t=Ge();return qt(t,"room/onRoomCoHostInviteAccepted","room.didCohostInviteAccept",(async t=>{var n;const a=Zr(t);await vg(null===(n=a.invitations)||void 0===n?void 0:n[0].targetId),Nn(a),e(a.invitations[0])}))},bg=e=>{const t=Ge();return qt(t,"room/onRoomCoHostInviteRejected","room.didCohostInviteReject",(t=>{const n=Zr(t);Nn(n),e(n.invitations)}))},Ig=e=>{const t=Ge();return qt(t,"room/onRoomCoHostInviteCanceled","room.didCohostInviteCancel",(t=>{const n=Zr(t);Nn(n),e(n.invitations)}))},Cg=e=>{const t=Ge();return qt(t,"room/onRoomParticipantJoined","room.participantJoined",(t=>{const{rooms:n,users:a}=t;Nn({rooms:n,users:a}),e({room:jc(n[0]),actorInternalId:t.eventActor.userInternalId})}))},wg=e=>{const t=Ge();return qt(t,"room/onRoomParticipantLeft","room.participantLeft",(t=>{var n;const{rooms:a,users:s}=t;Nn({rooms:a,users:s});const o=t.eventActor.userInternalId;e({room:jc(a[0]),actorInternalId:o,actorUserId:null===(n=null==s?void 0:s.find((e=>e.userInternalId===o)))||void 0===n?void 0:n.userId})}))},Sg=e=>{const t=Ge();return qt(t,"room/onRoomParticipantStageJoined","room.participantStageJoined",(t=>{const{rooms:n,users:a}=t;Nn({rooms:n,users:a}),e({room:jc(n[0]),actorInternalId:t.eventActor.userInternalId})}))},Og=e=>{const t=Ge();return qt(t,"room/onRoomTerminated","room.terminated",(t=>{Nn(t),e(t.rooms[0])}))},Tg=e=>{const t=Ge();return qt(t,"room/onRoomDidUpdate","local.room.didUpdate",(t=>{Nn(t),e(t.rooms[0])}))},Ag=e=>{const t=Ge();return qt(t,"room/onRoomParticipantRemoved","room.participantRemoved",(t=>{var n;const{rooms:a,users:s}=t;Nn({rooms:a,users:s});const o=t.eventActor.userInternalId;e({room:jc(a[0]),actorInternalId:o,actorUserId:null===(n=null==s?void 0:s.find((e=>e.userInternalId===o)))||void 0===n?void 0:n.userId})}))},Rg=e=>{const t=Ge();return qt(t,"room/onLocalRoomDidUpdate","room.didUpdate",(t=>{Nn(t),e(t.rooms[0])}))},Pg=e=>{const t=Ge();return qt(t,"room/onRoomParticipantRemoved","local.room.participantRemoved",(t=>{Nn(t),e(t.rooms[0])}))};var Dg;!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"}(Dg||(Dg={}));const Ug=e=>t=>e((e=>{t(e.room)}));class kg extends fr{async getRequest(e,t){const{limit:n=me,includeDeleted:a}=e,s=_n(e,["limit","includeDeleted"]),o={type:s.sortBy||e.limit?"pagination":void 0},i=t?Object.assign(Object.assign({},o),{token:t}):Object.assign(Object.assign({},o),{limit:n}),{data:r}=await this.http.get("/api/v1/rooms",{params:Object.assign(Object.assign({},s),{isDeleted:sa(a),options:i})});return r}}class jg extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.rooms.map(Xe("room"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.rooms.map(Xe("room"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===Dg.OnRoomDeleted&&(a.data=a.data.filter((e=>e!==t._id))),e===Dg.OnRoomCreated&&(a.data=[...new Set([t._id,...a.data])]),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Eg extends Or{constructor(e,t){const n=R.default(e),a=["rooms","collection",n];super(new kg(e),n,a,t),this.query=e,this.queryStreamController=new jg(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:hg,action:Dg.OnRoomStartBroadcasting},{fn:gg,action:Dg.OnRoomEndBroadcasting},{fn:pg,action:Dg.OnRoomUpdated},{fn:mg,action:Dg.OnRoomUpdated},{fn:Og,action:Dg.OnRoomUpdated},{fn:Ug(Cg),action:Dg.OnRoomUpdated},{fn:Ug(wg),action:Dg.OnRoomUpdated},{fn:Ug(Ag),action:Dg.OnRoomUpdated},{fn:Pg,action:Dg.OnRoomUpdated},{fn:Ug(Sg),action:Dg.OnRoomUpdated},{fn:Td(fg,"targetId","room"),action:Dg.OnRoomUpdated},{fn:Tg,action:Dg.OnRoomDidUpdate},{fn:Rg,action:Dg.OnRoomDidUpdate}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["room","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(jc);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,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(It);else t=t.sort(wt);return t}}var Mg=Object.freeze({__proto__:null,createRoom:async e=>{const t=Ge();t.log("room/createRoom",e);const{data:n}=await t.http.post("/api/v1/rooms",e);xt("local.room.created",n);const a=t.cache&&Date.now();t.cache&&Nn(n,{cachedAt:a});const{rooms:s}=n;return{data:jc(s[0]),cachedAt:a}},updateRoom:async(e,t)=>{const n=Ge();n.log("room/updateRoom",{roomId:e,bundle:t});const{data:a}=await n.http.put(`/api/v1/rooms/${e}`,t);xt("local.room.updated",a);const s=n.cache&&Date.now();n.cache&&Nn(a,{cachedAt:s});const{rooms:o}=a;return{data:jc(o[0]),cachedAt:s}},deleteRoom:async e=>{const t=Ge();t.log("room/deleteRoom",{roomId:e}),await t.http.delete(`/api/v1/rooms/${e}`),xt("local.room.deleted",{rooms:[{_id:e}]})},stopRoom:async e=>{const t=Ge();t.log("room/stopRoom",{roomId:e});const{data:n}=await t.http.post(`/api/v1/rooms/${e}/stop`);xt("local.room.stopped",n);const a=t.cache&&Date.now();t.cache&&Nn(n,{cachedAt:a});const{rooms:s}=n;return{data:s[0],cachedAt:a}},getBroadcasterData:async e=>{const t=Ge();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=Ge();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=Ge();n.log("room/removeParticipant",{roomId:e,participantUserId:t}),await n.http.delete(`/api/v1/rooms/${e}/participants/${t}`),xt("local.room.participantRemoved",{rooms:[{_id:e}],users:[{_id:t}]})},leaveRoom:async e=>{const t=Ge();t.log("room/leaveRoom",{roomId:e}),await t.http.post(`/api/v1/rooms/${e}/leave`),xt("local.room.left",{rooms:[{_id:e}]})},AmityRoomAnalytics:kc,WatchSessionStorage:Ic,getWatchSessionStorage:wc,syncWatchSessions:Dc,updateCohostPermission:async(e,t,n)=>{const a=Ge();a.log("room/updatedCoHostPermission",{roomId:e,cohostId:t,canManageProductTags:n});const{data:s}=await a.http.put(`/api/v1/rooms/${e}/participants/${t}`,{canManageProductTags:n});xt("local.room.didUpdate",s);const o=a.cache&&Date.now();a.cache&&Nn(s,{cachedAt:o});const{rooms:i}=s;return{data:jc(i[0]),cachedAt:o}},onRoomStartBroadcasting:hg,onRoomWaitingReconnect:mg,onRoomEndBroadcasting:gg,onRoomRecordedAvailable:pg,onRoomCoHostInvited:yg,onRoomCoHostInviteAccepted:fg,onRoomCoHostInviteRejected:bg,onRoomCoHostInviteCanceled:Ig,onRoomParticipantJoined:Cg,onRoomParticipantLeft:wg,onRoomParticipantStageLeft:e=>{const t=Ge();return qt(t,"room/onRoomParticipantStageLeft","room.participantStageLeft",(t=>{const{rooms:n,users:a}=t;Nn({rooms:n,users:a}),e({room:jc(n[0]),actorInternalId:t.eventActor.userInternalId})}))},onRoomParticipantStageJoined:Sg,onRoomTerminated:Og,onRoomDidUpdate:Tg,onRoomCreated:e=>{const t=Ge();return qt(t,"room/onRoomCreated","local.room.created",(t=>{Nn(t),e(t.rooms[0])}))},onRoomUpdated:e=>{const t=Ge();return qt(t,"room/onRoomUpdated","local.room.updated",(t=>{Nn(t),e(t.rooms[0])}))},onRoomDeleted:e=>{const t=Ge();return qt(t,"room/onRoomDeleted","local.room.deleted",(t=>{Nn(t),e(t.rooms[0])}))},onRoomStopped:e=>{const t=Ge();return qt(t,"room/onRoomStopped","local.room.stopped",(t=>{Nn(t),e(t.rooms[0])}))},onRoomParticipantRemoved:Ag,onRoomLeft:e=>{const t=Ge();return qt(t,"room/onRoomLeft","local.room.left",(t=>{Nn(t),e(t.rooms[0])}))},onLocalRoomDidUpdate:Rg,getRoom:(e,t)=>jr(e,t,"_id",vg,[gg,hg,mg,Og,pg,Ug(Cg),Ug(wg),Ug(Ag),Pg,Ug(Sg),Td(fg,"targetId","room"),Tg,Rg],{callbackDataSelector:e=>e?dd.room(e):e}),getRooms:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getRooms(tmpid: ${o}) > listen`);const i=new Eg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getRooms(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});class qg extends Or{constructor(e){const t={limit:100},n=R.default(t),a=["liveRoomPosts","collection",n];super(new lg(t),n,a,e),this.query=t,this.queryStreamController=new ug(this.query,this.cacheKey,this.notifyChange.bind(this),Yd),this.callback=e.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:gg,action:nm.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["post","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(dd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,loading:t,error:n})}applyFilter(e){return e}}class xg extends Sr{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 Kg extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:Km(e.rooms,e.posts)});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...Km(e.rooms,e.posts)])]}))}}reactor(e){return e=>{var t;const n=null===(t=nt(this.cacheKey))||void 0===t?void 0:t.data;n&&("ended"===e.status&&at(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 Ng extends Or{constructor(e,t){const n=R.default(e),a=["communityLiveRoomPosts","collection",n];super(new xg(e),n,a,t),this.query=e,this.queryStreamController=new Kg(this.query,this.cacheKey,this.notifyChange.bind(this),Yd),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:gg,action:nm.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["post","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(dd.post);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,loading:t,error:n})}applyFilter(e){return e}}var Fg=Object.freeze({__proto__:null,getPostByIds:Vm,createPost:async e=>{const t=Ge();t.log("post/createPost",e),e.dataType&&!["text","image","file","video"].includes(e.dataType)||delete e.dataType;const{attachments:n,attachmentProductTags:a}=e,s=_n(e,["attachments","attachmentProductTags"]),o=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:i}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},s),{attachments:o}));xt("post.created",i);const r=Yd(i),c=t.cache&&Date.now();t.cache&&Nn(r,{cachedAt:c});const{posts:d}=r;return{data:dd.post(d[0]),cachedAt:c}},editPost:async(e,t)=>{const n=Ge();n.log("user/editPost",t);const{attachments:a}=t,s=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:o}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,Object.assign(Object.assign({},t),{attachments:s})),i=$n(o,"communityUsers"),r=n.cache&&Date.now();n.cache&&Nn(i,{cachedAt:r}),xt("local.post.updated",i);const{posts:c}=i;return{data:dd.post(c.find((t=>t.postId===e))),cachedAt:r}},deletePost:Jm,softDeletePost:async e=>{Ge().log("post/softDeletePost",e);const t=await Jm(e,!1);return dd.post(t)},hardDeletePost:async e=>{Ge().log("post/hardDeletePost",e);const t=await Jm(e,!0);return dd.post(t)},approvePost:async e=>{const t=Ge();t.log("post/approvePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/approve`);xt("post.approved",n),"community"===n.posts[0].targetType&&xt("community.updated",n);const a=$n(n,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Nn(a,{cachedAt:s}),{data:dd.post(a.posts.find((t=>t.postId===e))),cachedAt:s}},declinePost:async e=>{const t=Ge();t.log("post/declinePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/decline`);"community"===n.posts[0].targetType&&xt("community.updated",n),xt("post.declined",n);const a=$n(n,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Nn(a,{cachedAt:s}),{data:dd.post(n.posts.find((t=>t.postId===e))),cachedAt:s}},flagPost:async(t,n)=>{const a=Ge();a.log("post/flagPost",t);const s=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,a])=>t!==e.ContentFlagReasonEnum.Others&&a===n)),o={reason:n&&s?n:e.ContentFlagReasonEnum.Others,detail:n&&!s?n:""},{data:i}=await a.http.post(`/api/v3/posts/${encodeURIComponent(t)}/flag`,o);return a.cache&&Nn($n(i,"communityUsers")),xt("post.flagged",i),!!i},unflagPost:async e=>{const t=Ge();t.log("post/unflagPost",e);const{data:n}=await t.http.delete(`/api/v3/posts/${encodeURIComponent(e)}/unflag`);return t.cache&&Nn($n(n,"communityUsers")),xt("post.unflagged",n),!!n},isPostFlaggedByMe:async e=>{const t=Ge();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=Ge();t.log("post/createPost",e);const{attachments:n,attachmentProductTags:a}=e,s=_n(e,["attachments","attachmentProductTags"]),o=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:i}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},s),{attachments:o}));xt("post.created",i);const r=$n(i,"communityUsers"),c=t.cache&&Date.now();t.cache&&Nn(r,{cachedAt:c});const{posts:d}=r;return{data:dd.post(d[0]),cachedAt:c}},createAudioPost:async e=>{const t=Ge();t.log("post/createAudioPost",e);const{attachments:n,attachmentProductTags:a}=e,s=_n(e,["attachments","attachmentProductTags"]),o=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:i}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},s),{attachments:o}));xt("post.created",i);const r=Yd(i),c=t.cache&&Date.now();return t.cache&&Nn(r,{cachedAt:c}),{data:xc(null==r?void 0:r.posts[0]),cachedAt:c}},createMixedMediaPost:async e=>{var t;const n=Ge();n.log("post/createMixedMediaPost",e);const{attachments:a,attachmentProductTags:s}=e,o=_n(e,["attachments","attachmentProductTags"]),i=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:r}=await n.http.post("/api/v4/posts",Object.assign(Object.assign({},o),{attachments:i}));xt("post.created",r);const c=Yd(r),d=n.cache&&Date.now();return n.cache&&Nn(c,{cachedAt:d}),{data:xc(null===(t=null==c?void 0:c.posts)||void 0===t?void 0:t[0]),cachedAt:d}},createRoomPost:async e=>{const t=Ge();t.log("post/createRoomPost",e);const{data:n}=await t.http.post("/api/v4/posts",Object.assign(Object.assign({},e),{dataType:"room"}));xt("post.created",n);const a=Yd(n),s=t.cache&&Date.now();t.cache&&Nn(a,{cachedAt:s});const{posts:o}=a;return{data:dd.post(o[0]),cachedAt:s}},pinProduct:async(e,t)=>{const n=Ge();n.log("post/pinProduct",e);const{data:a}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{pinnedProductId:t}),s=Yd(a),o=n.cache&&Date.now();return n.cache&&Nn(a,{cachedAt:o}),xt("local.post.updated",a),{data:xc(null==s?void 0:s.posts[0]),cachedAt:o}},unpinProduct:async e=>{const t=Ge();t.log("post/unpinProduct",e);const{data:n}=await t.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{pinnedProductId:null}),a=Yd(n),s=t.cache&&Date.now();return t.cache&&Nn(n,{cachedAt:s}),xt("local.post.updated",n),{data:xc(null==a?void 0:a.posts[0]),cachedAt:s}},updateProductTags:async(e,t)=>{const n=Ge();n.log("post/updateProductTags",e);const{data:a}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,{productTags:t}),s=Yd(a),o=n.cache&&Date.now();return n.cache&&Nn(a,{cachedAt:o}),xt("local.post.updated",a),{data:xc(null==s?void 0:s.posts[0]),cachedAt:o}},onPostCreated:ll,onPostUpdated:ul,onPostDeleted:hl,onPostApproved:ml,onPostDeclined:gl,onPostFlagged:pl,onPostUnflagged:yl,onPostReactionAdded:vl,onPostReactionRemoved:fl,getPost:(e,t)=>jr(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?dd.post(e.data):n}))}),"postId",Xd,[ml,gl,Im,Cm,t=>hl((n=>{var a;let s=n;if(n.parentPostId===e&&n.isDeleted){const e=null===(a=nt(["post","get",n.parentPostId]))||void 0===a?void 0:a.data;e&&(e.children=e.children.filter((e=>e!==n.postId)),at(["post","get",e.postId],e),s=e)}t(s)})),pl,e=>vl((t=>{e(t)})),e=>fl((t=>{e(t)})),yl,ul,wm,bm,Td((t=>Cl((async n=>{n.referenceId===e&&(await Xd(e),t(n))}))),"referenceId","post"),Td((t=>Sl((async n=>{n.referenceId===e&&(await Xd(e),t(n))}))),"referenceId","post")]),getPosts:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getPosts(tmpid: ${o}) > listen`);const i=new Gm(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getPinnedPosts:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getPinnedPosts(tmpid: ${o}) > listen`);const i=new Xm(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getPinnedPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getGlobalPinnedPosts:(e,t,n)=>{const{log:a,cache:s}=Ge(),o=Date.now();a(`getGlobalPinnedPosts(tmpid: ${o}) > listen`);const i=new tg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getGlobalPinnedPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},semanticSearchPosts:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`semanticSearchPosts(tmpid: ${o}) > listen`);const i=new ig(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`semanticSearchPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},searchPostsByHashtag:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`searchPostsByHashtag(tmpid: ${o}) > listen`);const i=new dg(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`searchPostsByHashtag(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getLiveRoomPosts:e=>{const{log:t,cache:n}=Ge();n||console.log(ye);const a=Date.now();t(`getLiveRoomPosts(tmpid: ${a}) > listen`);const s=new qg(e),o=s.startSubscription(),i=s.getCacheKey();return o.push((()=>it(i))),()=>{t(`getLiveRoomPosts(tmpid: ${a}) > dispose`),o.forEach((e=>e()))}},getCommunityLiveRoomPosts:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getCommunityLiveRoomPosts(tmpid: ${o}) > listen`);const i=new Ng(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getCommunityLiveRoomPosts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});const _g=async e=>{const t=Ge();t.log("stream/getStream",e);const{data:n}=await t.http.get(`/api/v3/video-streaming/${e}`),a=t.cache&&Date.now();t.cache&&Nn(n,{cachedAt:a});const{videoStreamings:s}=n;return{data:s.find((t=>t.streamId===e)),cachedAt:a}};_g.locally=e=>{const t=Ge();if(t.log("stream/getStream",e),!t.cache)return;const n=nt(["stream","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Bg=e=>{const t=Ge();return qt(t,"stream/onStreamStarted","video-streaming.didStart",(t=>{Nn(t),e(t.videoStreamings[0])}))},$g=e=>{const t=Ge();return qt(t,"stream/onStreamStropped","video-streaming.didStop",(t=>{Nn(t),e(t.videoStreamings[0])}))},Lg=e=>{const t=Ge();return qt(t,"stream/onStreamRecorded","video-streaming.didRecord",(t=>{Nn(t),e(t.videoStreamings[0])}))},Qg=e=>{const t=Ge();return qt(t,"stream/onStreamFlagged","video-streaming.didFlag",(t=>{Nn(t),e(t.videoStreamings[0])}))},Vg=e=>{const t=Ge();return qt(t,"stream/onStreamTerminated","video-streaming.didTerminate",(t=>{Nn(t),e(t.videoStreamings[0])}))},Jg=(e,t)=>jr(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?dd.stream(e.data):n}))}),"streamId",_g,[Lg,Bg,$g,Qg,Vg,au]);Jg.locally=e=>{const t=Ge();if(t.log("stream/getStreamById",e),!t.cache)return;const n=nt(["stream","get",e]);return n?{data:dd.stream(n.data),cachedAt:n.cachedAt}:void 0};const Hg=async e=>{const t=Ge();t.log("stream/queryStreams",e);const n=null!=e?e:{},{page:a,limit:s}=n,o=_n(n,["page","limit"]),i=a?{token:a}:s?{limit:s}:void 0,{data:r}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},o),{options:i})}),{paging:c,results:d}=r,{videoStreamings:l}=d,u=t.cache&&Date.now();return t.cache&&Nn(d,{cachedAt:u}),{data:l,cachedAt:u,paging:c}};var zg=Object.freeze({__proto__:null,createStream:async e=>{const t=Ge();t.log("stream/createStream",e);const{data:n}=await t.http.post("/api/v3/video-streaming",e),a=t.cache&&Date.now();t.cache&&Nn(n,{cachedAt:a});const{videoStreamings:s}=n;return{data:dd.stream(s[0]),cachedAt:a}},updateStream:async(e,t)=>{const n=Ge();n.log("stream/updateStream",e,t);const{data:a}=await n.http.put(`/api/v3/video-streaming/${e}`,t),s=n.cache&&Date.now();n.cache&&Nn(a,{cachedAt:s});const{videoStreamings:o}=a;return{data:dd.stream(o.find((t=>t.streamId===e))),cachedAt:s}},deleteStream:async e=>{const t=Ge();t.log("stream/deleteStream",e);const n=await _g(e),{data:a}=await t.http.delete(`/api/v3/video-streaming/${e}`),{success:s}=a,o=Object.assign(Object.assign({},n.data),{isDeleted:!0});return ot(["stream","get",e],o),s},disposeStream:async e=>{const t=Ge();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&&Nn(n,{cachedAt:a});const{videoStreamings:s}=n;return{data:s.find((t=>t.streamId===e)),cachedAt:a}},editStream:async(e,t)=>{const n=Ge();n.log("stream/updateStream",e,t);const{data:a}=await n.http.put(`/api/v3/video-streaming/${e}`,t),s=n.cache&&Date.now();n.cache&&Nn(a,{cachedAt:s});const{videoStreamings:o}=a;return{data:dd.stream(o.find((t=>t.streamId===e))),cachedAt:s}},onStreamStarted:Bg,onStreamStopped:$g,onStreamRecorded:Lg,onStreamFlagged:Qg,onStreamTerminated:Vg,onStreamViewerBanned:au,onStreamViewerUnbanned:e=>{const t=Ge();return qt(t,"stream/onStreamViewerDidUnban","video-streaming.viewerDidUnban",(async t=>{var n;const{list:a}=t;await Promise.all(a.map((({streamId:e})=>_g(e))));const s=null===(n=nt(["stream","get",a[0].streamId]))||void 0===n?void 0:n.data;s&&e(s)}))},getStreamById:Jg,getStreams:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getStreams(tmpid: ${o}) > listen`);const{limit:i}=e,r=_n(e,["limit"]),c=null!=i?i:me,{policy:d=pe}=null!=n?n:{},l=[],u=["streams","collection",e],h=t=>{let n=rt(t,"isDeleted",e.isDeleted);return n=n.sort("lastCreated"===e.sortBy?wt:It),n},m=(e,n=!1)=>{var a,s;const o=null!==(a=e.data.map((e=>nt(["stream","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==a?a:[];t({onNextPage:p,data:n?h(o):o,hasNextPage:!!(null===(s=e.params)||void 0===s?void 0:s.page),loading:e.loading,error:e.error})},g=e=>e=>{var t;const n=null===(t=nt(u))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.streamId,...n.data])],at(u,n),m(n,!0))},p=(e=!1)=>{var t,n;const a=null===(t=nt(u))||void 0===t?void 0:t.data,s=null!==(n=null==a?void 0:a.data)&&void 0!==n?n:[];if(!e&&s.length>0&&!(null==a?void 0:a.params.page))return;const o=Fe(Hg,Object.assign(Object.assign({},r),{limit:e?c:void 0,page:e||null==a?void 0:a.params.page}));Be(o,(({data:e,error:t,loading:n,paging:a})=>{const o={loading:n,error:t,params:{page:null==a?void 0:a.next},data:s};e&&(o.data=[...new Set([...s,...e.map(Xe("stream"))])]),at(u,o),m(o)}),_e(d))};return l.push(Lg(g()),Bg(g()),$g(g())),p(!0),()=>{a(`getStreams(tmpid: ${o}) > dispose`),l.forEach((e=>e()))}}});const Gg=async()=>{const e=Ge();e.log("presence/getPresenceSetting");const{data:t}=await e.http.get("/api/v1/presence/settings");return at(["get","presenceSetting"],t),t};class Yg{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 Yg.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 Gg()}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=Ge();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 Wg=new Map,Xg=e=>{let t=Wg.get(e);return t||(t=new Yg(e),Wg.set(e,t)),t};var Zg=Object.freeze({__proto__:null,getRoomOnlineUsers:async e=>{var t,n,a;const s=Ge();s.log("room/getWatchingUsers",{roomId:e});const{data:o}=await s.http.get(`/api/v1/presence/rooms/${e}/users`),i=null!==(t=null==o?void 0:o.viewers.map((e=>e.userId)))&&void 0!==t?t:[],r=[];for(let e=0;e<i.length;e+=100)r.push(i.slice(e,e+100));const c=await Promise.all(r.map((e=>ld(e)))),d=[];return c.forEach((e=>{e.data&&d.push(...e.data)})),{data:d,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=Ge();t.log("roomPresence/getRoomUserCount",{roomId:e});const{data:n}=await t.http.get(`/api/v1/presence/rooms/${e}/users/count`);return at(["get","watchingCount",e],n),n},startHeartbeat:e=>{Xg(e).start()},stopHeartbeat:e=>{Xg(e).stop(),(e=>{const t=Wg.get(e);t&&(t.destroy(),Wg.delete(e))})(e)}});const ep=async e=>{const t=Ge();t.log("poll/getPoll",e);const{data:n}=await t.http.get(`/api/v3/polls/${e}`),a=t.cache&&Date.now();t.cache&&Nn(n,{cachedAt:a});const{polls:s}=n,o=s.find((t=>t.pollId===e));return{data:Ec(o),cachedAt:a}};ep.locally=e=>{const t=Ge();if(t.log("poll/getPoll",e),!t.cache)return;const n=nt(["poll","get",e]);return n?{data:Ec(n.data),cachedAt:n.cachedAt}:void 0};const tp=e=>{const t=Ge();return qt(t,"poll/onPollUpdated","poll.updated",(n=>{t.cache&&Nn(n),e(n.polls[0])}))},np=e=>{const t=Ge();return qt(t,"poll/onPollDeleted","poll.deleted",(n=>{t.cache&&Nn(n),e(n.polls[0])}))};var ap=Object.freeze({__proto__:null,createPoll:async e=>{const t=Ge();t.log("post/createPoll",e);const{data:n}=await t.http.post("/api/v3/polls",e),a=t.cache&&Date.now();t.cache&&Nn(n,{cachedAt:a});const{polls:s}=n;return{data:Ec(s[0]),cachedAt:a}},closePoll:async e=>{const t=Ge();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&&Nn(n,{cachedAt:a}),xt("poll.updated",n);const{polls:s}=n,o=s.find((t=>t.pollId===e));return{data:Ec(o),cachedAt:a}},deletePoll:async e=>{const t=Ge();t.log("poll/deletePoll",e);const n=await ep(e),{data:a}=await t.http.delete(`/api/v3/polls/${e}`),{success:s}=a,o=Object.assign(Object.assign({},n.data),{isDeleted:!0});return ot(["poll","get",e],o),xt("poll.deleted",{polls:[o],users:[]}),s},votePoll:async(e,t)=>{const n=Ge();n.log("user/votePoll",e);const{data:a}=await n.http.post(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:t}),s=n.cache&&Date.now();n.cache&&Nn(a,{cachedAt:s});const{polls:o}=a,i=o.find((t=>t.pollId===e));return xt("poll.updated",a),{data:Ec(i),cachedAt:s}},unvotePoll:async e=>{const t=Ge();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&&Nn(n,{cachedAt:a}),xt("poll.updated",n)},onPollUpdated:tp,onPollDeleted:np,getPoll:(e,t)=>jr(e,t,"pollId",ep,[tp,np])});class sp{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 s=e();if(s.length)try{const n=(new Date).toISOString(),o=await Pc({timestamp:n,streams:s});if(!o||!o.signature)throw new Error("Signature is undefined");const i={signature:o.signature,nonceStr:o.nonceStr,timestamp:n,streams:s},r=Ge();await r.http.post("/api/v3/user-event/video-streaming",i),t().length||e().length||a()}catch(e){return s.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 op=null;class ip{constructor(e,t,n){this._SDKUnsubscribers=[],this.player=e,this.resolution=t,this._startTime=null,this._usageCollector=op||(op=new sp,op),this._usageCollector.registerStream(e.id),this._sessionId=String(T.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 rp=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(!P.default.isSupported())throw new Error("This browswer does not support hls, unable to play stream");const{data:n}=await _g(t),{watcherUrl:a,status:s,recordings:o=[],resolution:i}=n;if(!a.hls)throw new Error("This stream does not support hls. Unable to play");const r=document.createElement("video");r.id=t,r.controls=!0;const c=new P.default;if(c.attachMedia(r),"recorded"!==s){let{url:e}=a.hls;e=e.replace("http:","https:"),c.loadSource(e)}else{const e=o.find((e=>!!e.mp4));if(!e||!e.mp4)throw new Error("No playable recording available");r.src=e.mp4.url}return new ip(r,i,t).registerEvents(),r}});const cp=e=>{const t=(e=>{var t;const n=Ge(),a=new Date,s=a.getTime()+31536e6,o=new Date(s).toISOString();let i=null===(t=nt(["storyTarget","get",e.targetId]))||void 0===t?void 0:t.data;return i||(i={targetType:e.targetType,targetId:e.targetId,lastStoryExpiresAt:o,targetPublicId:e.targetId,targetUpdatedAt:a.toISOString()},Nn({storyTargets:[i]})),{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(s).toISOString()},e)],categories:[],communityUsers:[],comments:[],files:[],users:[],communities:[]}})(e);return Nn(t),t},dp=({payload:e,formData:t,isVideo:n=!1},a)=>{if(t){const s=t.getAll("files")[0]||void 0;if(!s)return;const o=Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileId:void 0,fileData:s.uri})});return n&&(o.data.videoFileId={original:void 0}),a(cp(o))}return a(cp(Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileData:null})})))},lp=async e=>{const t=Ge();t.log("post/createStory",e);const n=await t.http.post("/api/v4/stories",e),a=im(n.data);t.cache&&Nn(a),at(["story-sync-state",e.targetId],"synced"),xt("local.story.created",a);const s=t.cache&&Date.now();return{data:a.stories.length>0?a.stories[0]:void 0,cachedAt:s}},up=async({targetId:e,targetType:t})=>{var n,a;if(!nt(["storyTarget","get",e])){let s={targetId:e,targetType:t};if("community"===t){const t=await Qu(e);s=Object.assign(Object.assign({},s),{targetPublicId:t.data.communityId,targetUpdatedAt:null!==(n=t.data.updatedAt)&&void 0!==n?n:(new Date).toISOString()})}if("user"===t){const t=await vd(e);s=Object.assign(Object.assign({},s),{targetPublicId:t.data.userPublicId,targetUpdatedAt:null!==(a=t.data.updatedAt)&&void 0!==a?a:(new Date).toISOString()})}at(["storyTarget","get",e],s)}},hp=e=>e?nt(["story","get",e]):{data:void 0,cachedAt:void 0},mp=async(e,t=!1)=>{var n,a,s;const o=Ge();let i;if(o.log("story/deleteStory",e),o.cache&&(i=hp(e),null==i?void 0:i.data)){const{data:o}=i;if(xt("local.story.deleted",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[Object.assign(Object.assign({},o),{isDeleted:!0})]}),"synced"!==o.syncState){t?it(["story","get",e]):at(["story","get",e],Object.assign(Object.assign({},i.data),{isDeleted:!0}));const a=null===(n=tt(["story","get"]))||void 0===n?void 0:n.filter((e=>"synced"!==e.data.syncState&&e.data.targetId===o.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));at(["story-expire",i.data.targetId],e.toISOString())}else it(["story-expire",i.data.targetId]);return!0}const r=null===(a=nt(["storyTarget","get",o.targetId]))||void 0===a?void 0:a.data,c=null===(s=tt(["story","get"]))||void 0===s?void 0:s.filter((e=>"synced"===e.data.syncState&&e.data.targetId===o.targetId&&!0!==e.data.isDeleted));let d;c&&c.length>0&&(d=null==c?void 0:c.reduce(((e,t)=>{const n=new Date(t.data.expiresAt||0);return n>e?n:e}),new Date(0))),r&&at(["storyTarget","get",o.targetId],Object.assign(Object.assign({},r),{lastStoryExpiresAt:d}))}return(await o.http.delete(`/api/v4/stories/${e}`,{params:{permanent:t}})).data.success},gp=e=>{const t=Ge(),n=[qt(t,"onStoryUpdated","story.updated",(async t=>{const n=im(t);Nn(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},pp=e=>{const t=Ge(),n=[qt(t,"onStoryUpdated","local.story.updated",(async t=>{Nn(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},yp=e=>{const t=Ge(),n=[qt(t,"onStoryReactionAdded","story.reactionAdded",(async t=>{const{reactions:n}=t,a=_n(t,["reactions"]),s=im(a),o=sl("story.reactionAdded",Object.assign(Object.assign({},s),{reactions:n}));Nn(o),e(o.stories)}))];return()=>{n.forEach((e=>e()))}},vp=e=>{const t=Ge(),n=[qt(t,"onStoryReactionAdded","local.story.reactionAdded",(async t=>{Nn({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},fp=e=>{const t=Ge(),n=[qt(t,"onStoryReactionRemoved","story.reactionRemoved",(async t=>{const{reactions:n}=t,a=_n(t,["reactions"]),s=im(a),o=sl("story.reactionRemoved",Object.assign(Object.assign({},s),{reactions:n}));Nn(o),e(o.stories)}))];return()=>{n.forEach((e=>e()))}},bp=e=>{const t=Ge(),n=[qt(t,"onStoryReactionRemoved","local.story.reactionRemoved",(async t=>{Nn({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},Ip=e=>{e.forEach((e=>{const t=nt(["story-expire",e.targetId]),n=new Date(e.expiresAt||0);n<new Date((null==t?void 0:t.data)||0)||at(["story-expire",e.targetId],n.toISOString())}))},Cp=e=>{e.forEach((e=>{at(["story-reference",e.storyId],e.referenceId)}))},wp=async({targetType:e,targetId:t,options:n})=>{const a=Ge();a.log("story/getActiveStoriesByTarget");const s=a.cache&&Date.now(),o=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"}}}),i=im(o.data);return a.cache&&(Nn(i),Ip(i.stories),Cp(i.stories)),{data:i.stories,cachedAt:s,paging:{next:void 0,previous:void 0}}},Sp=e=>{const t=Ge(),n=[qt(t,"onStoryCreated","story.created",(async t=>{const n=im(t,!0);Nn(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Op=e=>{const t=Ge(),n=[qt(t,"onStoryCreated","local.story.created",(async t=>{Nn(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},Tp=e=>{const t=Ge(),n=[qt(t,"onStoryDeleted","story.deleted",(async t=>{const n=im(t);Nn(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Ap=e=>{const t=Ge(),n=[qt(t,"onStoryDeleted","local.story.deleted",(async t=>{Nn(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},Rp=e=>{const t=Ge();return qt(t,"onStoryError","local.story.error",(async t=>{Nn(t),e(t.stories)}))},Pp=e=>t=>e((e=>t(e[0]))),Dp=async e=>{const t=Ge();t.log("story/getTargetsByTargetIds",e);const n=await t.http.get("/api/v4/stories/seen",{params:{targets:e}}),{data:a}=n;return t.cache&&Nn(n.data),{data:a.storyTargets,cachedAt:Date.now()}};class Up extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.paginationController=a}saveToMainDB(e){const t=Ge(),n=t.cache&&Date.now(),a=im(e);t.cache&&(Nn(a,{cachedAt:n}),Ip(a.stories),Cp(a.stories))}getStoryReferenceIds(e){return(null==e?void 0:e.referenceId)?e.referenceId:e.storyId}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.stories.map(this.getStoryReferenceIds)});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(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=nt(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])],at(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class kp extends Sr{async getRequest(e){const{data:t}=await this.http.get("/api/v4/stories-by-targets",{params:Object.assign({},e)});return t}}class jp extends Or{constructor(e,t){const n=R.default(e),a=["story-target-ids","collection",n],s=new kp(e);super(s,n,a,t),this.query=e,this.queryStreamController=new Up(this.query,this.cacheKey,this.notifyChange.bind(this),s),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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 s=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;let o=s.data.map((e=>nt(["story","get",e]))).filter(Boolean).map((e=>dd.story(e.data)));(this.shouldNotify(o)||"event"!==e)&&(o=this.applyFilter(o),this.callback({onNextPage:void 0,data:o,hasNextPage:!1,loading:t,error:n}))}applyFilter(e){var t,n;const 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(It):a.sort(wt)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Sp,action:"onCreate"},{fn:gp,action:"onUpdate"},{fn:Tp,action:"onDelete"},{fn:Rp,action:"onError"}])}}const Ep=(e,t)=>{var n,a;const s=null===(n=nt(e))||void 0===n?void 0:n.data,o=null!==(a=null==s?void 0:s.data)&&void 0!==a?a:[];at(e,Object.assign(Object.assign({},s),{data:[...new Set([...o,...t])]}))};class Mp extends Ir{constructor(e,t,n,a,s){super(e,t),this.notifyChange=n,this.paginationController=a,this.preparePayload=s}saveToMainDB(e){const t=Ge(),n=t.cache&&Date.now(),a=this.preparePayload(e);t.cache&&Nn(a,{cachedAt:n})}appendToQueryStream(e,t,n=!1){n?at(this.cacheKey,{data:e.storyTargets.map((({targetId:e})=>e))}):Ep(this.cacheKey,e.storyTargets.map((({targetId:e})=>e)))}reactor(e){return t=>{"onCreate"===e&&"seen"!==this.query.seenState&&Ep(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 qp extends fr{constructor(){super(...arguments),this.smartFilterState="unseen"}async getRequest(e,t){var n;const{limit:a=10,seenState:s="unseen"}=e,o=await this.createRequest({seenState:"smart"===s?this.smartFilterState:s,limit:a,token:t});if(null===(n=o.paging)||void 0===n?void 0:n.next)return o;if("smart"!==s)return o;if("seen"===this.smartFilterState)return o;this.smartFilterState="seen";const i=await this.createRequest({seenState:this.smartFilterState,limit:a});return c=i,{categories:(r=o).categories.concat(c.categories),communities:r.communities.concat(c.communities),communityUsers:r.communityUsers.concat(c.communityUsers),files:r.files.concat(c.files),storyTargets:r.storyTargets.concat(c.storyTargets),users:r.users.concat(c.users),paging:c.paging};var r,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 xp extends Or{constructor(e,t){const n=R.default(e),a=["story-global-feed","collection",n],s=new qp(e);super(s,n,a,t),this.query=e,this.queryStreamController=new Mp(this.query,this.cacheKey,this.notifyChange.bind(this),s,(e=>{const t=_n(Kr(Object.assign(Object.assign({},e),{feeds:[]})),["feeds"]);return Object.assign(Object.assign({},e),t)})),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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 s=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!s)return;const o=s.data,i=tt(["storyTarget"]);i&&(null==i?void 0:i.length)>0&&(null==i||i.forEach((({key:e})=>{s.data.includes(e[2])||o.push(e[2])})));let r=o.map((e=>nt(["storyTarget","get",e]))).filter(Boolean).map((e=>dd.storyTarget(e.data)));(this.shouldNotify(r)||"event"!==e)&&(r=this.applyFilter(r).filter((({localSortingDate:e})=>!!e)).map((e=>_n(e,["localFilter","localLastExpires","localLastSeen","localSortingDate"]))),this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:r,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(Ct);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(Ct)||[],a=t.unseen.sort(Ct)||[],s=t.seen.sort(Ct)||[];return n.concat(a,s)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Sp,action:"onCreate"},{fn:gp,action:"onUpdate"},{fn:Tp,action:"onDelete"},{fn:Op,action:"onCreate"},{fn:pp,action:"onUpdate"},{fn:Ap,action:"onDelete"},{fn:Rp,action:"onError"}])}}var Kp=Object.freeze({__proto__:null,createImageStory:async(e,t,n,a={},s="fit",o=[])=>{if(!n.getAll("files").length)throw new Error("The formData object must have a `files` key.");let i={data:{text:"",fileId:void 0,fileData:null,imageDisplayMode:s},syncState:"syncing",referenceId:Un(),dataType:"image",items:o,targetType:e,targetId:t,metadata:a};const r=new Date;at(["story-sync-state",t],"syncing"),at(["story-expire",t],new Date(r.setFullYear(r.getFullYear()+1))),dp({payload:i,formData:n},(e=>{xt("local.story.created",e)}));try{const{data:a}=await Nd(n);if(0===a.length)throw new Error("Failed to upload image");const{fileId:s}=a[0];i=Object.assign(Object.assign({},i),{data:Object.assign(Object.assign({},i.data),{fileId:s})}),up({targetId:t,targetType:e}),dp({payload:i,formData:n},(e=>{xt("local.story.created",e)}));const o=await lp(i);return o.data?Object.assign(Object.assign({},o),{data:dd.story(o.data)}):o}catch(e){throw at(["story-sync-state",t],"error"),dp({payload:Object.assign(Object.assign({},i),{syncState:"error"}),formData:n},(e=>{xt("local.story.error",e)})),e}},createVideoStory:async(e,t,n,a={},s=[])=>{if(!n.getAll("files").length)throw new Error("The formData object must have a `files` key.");let o={data:{text:"",fileId:void 0,fileData:null},syncState:"syncing",referenceId:Un(),dataType:"video",items:s,targetType:e,targetId:t,metadata:a};const i=new Date;at(["story-sync-state",t],"syncing"),at(["story-expire",t],new Date(i.setFullYear(i.getFullYear()+1))),up({targetId:t,targetType:e}),dp({payload:o,formData:n,isVideo:!0},(e=>{xt("local.story.created",e)}));try{const{data:e}=await Kd(n,F.STORY);if(0===e.length)throw new Error("Failed to upload video");const{fileId:t}=e[0];o=Object.assign(Object.assign({},o),{data:Object.assign(Object.assign({},o.data),{fileId:t,videoFileId:{original:t}})}),dp({payload:o,formData:n,isVideo:!0},(e=>{xt("local.story.created",e)}));const a=await lp(o);return a.data?Object.assign(Object.assign({},a),{data:dd.story(a.data)}):a}catch(e){throw at(["story-sync-state",t],"error"),dp({payload:Object.assign(Object.assign({},o),{syncState:"error"}),formData:n,isVideo:!0},(e=>{xt("local.story.error",e)})),e}},hardDeleteStory:async e=>await mp(e,!0),softDeleteStory:async e=>await mp(e),getActiveStoriesByTarget:(e,t)=>{const{log:n,cache:a}=Ge(),s=[],o=["story-target","collection",e],i=Date.now();n(`getActiveStoriesByTarget(tmpid: ${i}) > listen`),a||console.log(ye);const r=t=>{var n,a;const s=(null===(n=e.options)||void 0===n?void 0:n.sortBy)||"createdAt",o=(null===(a=e.options)||void 0===a?void 0:a.orderBy)||"desc";return 0===t.length?[]:"createdAt"===s?"asc"===o?t.sort(It):t.sort(wt):"asc"===o?t.sort(St):t.sort(Ot)},c=e=>{var n;const a=e.data.map((e=>{const t=hp(e);if(null==t?void 0:t.data)return dd.story(t.data)})).filter(Boolean).filter((e=>!!e&&!e.isDeleted)),s=[];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=r(e.get("error")||[]);s.push(...t)}if(e.has("syncing")){const t=r(e.get("syncing")||[]);s.push(...t)}if(e.has("synced")){const t=r(e.get("synced")||[]);s.push(...t)}}t({onNextPage:()=>!1,data:s||a,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading||!1})},d=(t,n,a=!1,s=!1,i=!1)=>{var r;const d=nt(o),l={loading:s,error:i,params:{page:void 0},data:(null==d?void 0:d.data)||[]};if(t)if("onDelete"===n){const e=t.map((({referenceId:e})=>e));l.data=l.data.filter((t=>!e.includes(t)))||[]}else l.data=a?t.map(Xe("story")):[...new Set([...l.data,...t.map(Xe("story"))])];const u=null===(r=tt(["story","get"]))||void 0===r?void 0:r.filter((t=>t.data.targetId===e.targetId&&"synced"!==t.data.syncState)).map((e=>Xe("story")(e.data)));u&&(null==u?void 0:u.length)>0&&u.forEach((e=>{l.data.includes(e)||l.data.push(e)})),at(o,l.data),c(l)},l=e=>t=>{d(t,e)};return(t=>{const n=Fe(wp,e);Be(n,(({data:e,error:n,loading:a})=>{d(e,"fetch",t,a,n)}))})(!0),s.push(Sp(l("onCreate")),gp(l("onUpdate")),Tp(l("onDelete")),yp(l("onReactionAdded")),fp(l("onReactionRemoved")),Rp(l("onError")),Op(l("onCreate")),pp(l("onUpdate")),Ap(l("onDelete")),vp(l("onReactionAdded")),bp(l("onReactionRemoved")),(e=>{const t=Ge();return qt(t,"onStoryLocalDataUpdated","local.story.reload",(t=>{e(t)}))})((e=>{const t=nt(o);if(!t)return;if(0===e.referenceIds.length||0===(null==t?void 0:t.data.length))return;if(!(null==t?void 0:t.data.find((t=>e.referenceIds.includes(t)))))return;const n={loading:!1,error:!1,params:{page:void 0},data:(null==t?void 0:t.data)||[]};c(n)})),(()=>it(o))),()=>{n(`getActiveStoriesByTarget(tmpid: ${i}) > dispose`),s.forEach((e=>e()))}},getStoryByStoryId:(e,t)=>jr(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:dd.story(e.data)})):t(e)}),"storyId",rm,[Pp(gp),Pp(Tp),Pp(yp),Pp(fp),Pp(Rp),Pp(pp),Pp(Ap),Pp(vp),Pp(bp)]),getTargetById:(e,t)=>jr(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:dd.storyTarget(e.data[0])})):t(e)}),"query",(e=>Dp([e])),[]),getTargetsByTargetIds:(e,t)=>{const{log:n,cache:a}=Ge(),s=[],o=["storyTargets","collection",e],i=Date.now();n(`getTargetsByTargetIds(tmpid: ${i}) > listen`),a||console.log(ye);const r=(e,n=!1,a=!1,s=!1)=>{const i=nt(o),r={loading:a,error:s,params:{page:void 0},data:[]};e&&(r.data=n?e.map(Xe("storyTarget")):[...new Set([...(null==i?void 0:i.data)||[],...e.map(Xe("storyTarget"))])]),at(o,r.data),(e=>{var n;const a=e.data.map((e=>{const t=nt(["storyTarget","get",e]);if(null==t?void 0:t.data)return dd.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})})(r)};return(t=>{const n=Fe(Dp,e);Be(n,(({data:e,error:n,loading:a})=>{r(e,t,a,n)}))})(!0),s.push((()=>it(o))),()=>{n(`getTargetsByTargetIds(tmpid: ${i}) > dispose`),s.forEach((e=>e()))}},getStoriesByTargetIds:(e,t,n)=>{const{log:a,cache:s,userId:o}=Ge();s||console.log(ye);const i=Date.now();a(`getStoriesByTargetIds(tmpid: ${i}) > listen`);const r=new jp(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>{it(d)})),()=>{a(`getStoriesByTargetIds(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}},getGlobalStoryTargets:(e,t,n)=>{const{log:a,cache:s,userId:o}=Ge();s||console.log(ye);const i=Date.now();a(`getGlobalStoryTarget(tmpid: ${i}) > listen`);const r=new xp(e,t),c=r.startSubscription(),d=r.getCacheKey();return c.push((()=>{it(d)})),()=>{a(`getGlobalStoryTarget(tmpid: ${i}) > dispose`),c.forEach((e=>e()))}}});const Np=e=>Object.assign(Object.assign({},e),{endAt:e.endAt?e.endAt:null}),Fp=e=>Object.assign({},e);var _p=Object.freeze({__proto__:null,getNetworkAds:async()=>{const e=Ge(),{data:t}=await e.http.get("/api/v1/ads/me"),n=t.ads.map(Np),a=t.advertisers.map(Fp);return Nn({ads:n,advertisers:a,files:t.files}),at(["ad","setting"],t.settings),{ads:n.map(dd.ad),settings:t.settings}}});const Bp=async()=>{const e=Ge();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];at(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}};Bp.locally=()=>{var e;const t=Ge();if(t.log("notificationTray/getNotificationTraySeen.locally",{}),!t.cache)return;const{data:n,cachedAt:a}=null!==(e=nt(["notificationTraySeen","get"]))&&void 0!==e?e:{};return n?{data:n,cachedAt:a}:void 0};const $p=e=>{const t=Ge(),n=[qt(t,"onNotificationTraySeenUpdated","local.notificationTraySeen.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class Lp extends fr{async getRequest(e,t){const{limit:n=me}=e,a=_n(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/notification-tray",{params:Object.assign(Object.assign({},a),{options:s})});return o}}class Qp extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.notificationTrayItems.map(Xe("notificationTrayItem"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.notificationTrayItems.map(Xe("notificationTrayItem"))])]}))}}}const Vp=e=>{const t=e.users.map(ga);return Object.assign(Object.assign({},e),{users:t})};class Jp extends Or{constructor(e,t){const n=R.default(e),a=["notificationTrayItem","collection",n];super(new Lp(e),n,a,t),this.query=e,this.queryStreamController=new Qp(this.query,this.cacheKey,this.notifyChange.bind(this),Vp),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>nt(["notificationTrayItem","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(dd.notificationTray);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var Hp=Object.freeze({__proto__:null,getNotificationTraySeen:e=>{const{userId:t}=Dt();return jr(t,e,"userId",Bp,[$p],{callbackDataSelector:e=>{let t=!0;return(null==e?void 0:e.lastTrayOccurredAt)&&(t=!!e.lastTraySeenAt&&Hn(e.lastTraySeenAt)>Hn(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:s}=Ge();s||console.log(ye);const o=Date.now();a(`getNotificationTrayItems(tmpid: ${o}) > listen`);const i=new Jp(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getNotificationTrayItems(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},markItemsSeen:async e=>{const t=Ge();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=nt(["notificationTrayItem","get",e.id]))||void 0===n?void 0:n.data;if(!a)return;const s=Object.assign(Object.assign({},a),{lastSeenAt:e.lastSeenAt});if(t.cache){const e=Date.now();at(["notificationTrayItem","get"],s,{cachedAt:e})}return s})).filter(Boolean);xt("local.notificationTrayItem.updated",{notificationTrayItems:a})},markTraySeen:async e=>{var t;const n=Ge();n.log("notificationTray/markTraySeen",{});const{data:a}=await n.http.post("api/v1/notification-tray/tray/seen",{lastSeenAt:e}),s=null===(t=nt(["notificationTraySeen","get"]))||void 0===t?void 0:t.data,o={userId:n.userId,lastTraySeenAt:a.lastSeenAt},i=Object.assign(Object.assign({},s),o),r=n.cache&&Date.now();return n.cache&&at(["notificationTraySeen","get",n.userId],i,{cachedAt:r}),xt("local.notificationTraySeen.updated",o),{data:a,cachedAt:r}},onNotificationTraySeenUpdated:$p});class zp extends fr{async getRequest(e,t){const{limit:n=me}=e,a=_n(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/invitations/me",{params:Object.assign(Object.assign({},a),{options:s})}),i=o.invitations.filter((e=>"community"===e.targetType&&!!e.communityId)).map((e=>e.communityId));return(null==i?void 0:i.length)>0&&await Lu(i),o}}class Gp extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.invitations.map(Xe("invitation"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(Xe("invitation"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===nc.OnLocalInvitationUpdated){if(!a.data.find((e=>e===t[0].invitationId)))return}if(e===nc.OnLocalInvitationCreated){const e=Ge(),n=t.filter((t=>t.invitedUserId===e.userId));a.data=[...new Set([...n.map((e=>e.invitationId)),...a.data])]}e===nc.OnLocalInvitationCanceled&&(a.data=a.data.filter((e=>e!==t[0].invitationId))),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Yp extends Or{constructor(e,t){const n=R.default(e),a=["invitation","collection",n];super(new zp(e),n,a,t),this.query=e,this.queryStreamController=new Gp(this.query,this.cacheKey,this.notifyChange.bind(this),Zr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:oc,action:nc.OnLocalInvitationCreated},{fn:ic,action:nc.OnLocalInvitationUpdated},{fn:rc,action:nc.OnLocalInvitationCanceled}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=this.applyFilter(null!==(s=o.data.map((e=>nt(["invitation","get",e]))).filter(Tr).map((({data:e})=>ec(e))))&&void 0!==s?s:[]);(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,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?It:wt)();return t=t.sort(n),t}}var Wp=Object.freeze({__proto__:null,cancelInvitation:async e=>{var t;const n=Ge();n.log("invitation/cancelInvitation",e);const{data:a}=await n.http.delete(`/api/v1/invitations/${e}`),s=null===(t=nt(["invitation","get",e]))||void 0===t?void 0:t.data;return Fn("invitation",e),s&&xt("local.invitation.canceled",[s]),a.success},onLocalInvitationCreated:oc,onLocalInvitationUpdated:ic,onLocalInvitationCanceled:rc,getMyCommunityInvitations:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getMyCommunityInvitations: (tmpid: ${o}) > listen`);const i=new Yp(Object.assign(Object.assign({},e),{targetType:"community",statuses:["pending"]}),t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>{it(c)})),()=>{a(`getInvitations (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getInvitations:(e,t)=>{const{_id:n}=Bt();if(!n)throw new Le("The _id has not been defined in ActiveUser",8e5,"error");const{log:a}=Ge(),{targetId:s,targetType:o}=e,i=Date.now();a(`observeInvitations(tmpid: ${i}) > listen for ${o}: ${s}`);const r=[],c=n=>{const a=(Array.isArray(n)?n:[n]).filter((({targetId:t,targetType:n})=>t===e.targetId&&n===e.targetType));(e=>{t(e.map(dd.invitation))})(a)};return"room"===o&&(r.push(yg(c)),r.push(fg(c)),r.push(bg(c)),r.push(Ig(c))),()=>{a(`getInvitations(tmpid: ${i}) > dispose for ${o}: ${s}`),r.forEach((e=>e()))}}});const Xp=e=>{const t=Ge();return qt(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 Zp=Object.freeze({__proto__:null,createReaction:async({referenceId:e,referenceType:t,reactionName:n,streamId:a,roomId:s})=>{const o=Ge();if(o.log("live_reaction/createReaction",{referenceId:e,referenceType:t,reactionName:n,streamId:a,roomId:s}),!a&&!s)throw new Le("You have to specify either streamId or roomId",800110,"error");const i=Mo(),r={reactionName:n,referencePublicId:e,referenceType:t,roomId:s,streamId:a,occurredAt:(new Date).toISOString()};return i.createLiveReaction(r),xt("local.liveReaction.created",[Object.assign(Object.assign({},r),{userId:o.userId,referenceId:e})]),!0},onLiveReactionCreated:Xp,getReactions:(e,t)=>{const{_id:n}=Dt();if(!n)throw new Le("The _id has not been defined in ActiveUser",8e5,"error");const{log:a}=Ge();a(`getReactions(tmpid: ${Date.now()}) > listen`);const s=[],o=n=>{(e=>{t(e)})(n.filter((({referenceId:t})=>t===e)))};return s.push(Xp(o)),s.push((e=>{const t=Ge();return qt(t,"live_reaction/onLiveReactionCreated","local.liveReaction.created",e)})(o)),()=>{s.forEach((e=>e()))}}});const ey=async e=>{const t=Ge();t.log("event/getEvent",e);try{const{data:n}=await t.http.get(`/api/v1/events/${e}`),a=Lc(n),s=t.cache&&Date.now();return t.cache&&Nn(a,{cachedAt:s}),{data:a.events.find((t=>t.eventId===e)),cachedAt:s}}catch(n){if(Re(null==n?void 0:n.code)){const a=ey.locally(e);if(!a)throw n;const s=Object.assign(Object.assign({},null==a?void 0:a.data),{isDeleted:!0});ot(["event","get",e],s);return{data:s,cachedAt:t.cache&&Date.now()}}throw n}};ey.locally=e=>{const t=Ge();if(t.log("event/getEvent.locally",e),!t.cache)return;const n=nt(["event","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class ty extends fr{async getRequest(e,t){const{limit:n=me}=e,a=_n(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/events",{params:Object.assign(Object.assign({},a),{options:s})});return o}}class ny extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.events.map(Xe("event"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.events.map(Xe("event"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;a&&(e===Hc.OnEventCreated&&(a.data=[...new Set([t.eventId,...a.data])]),e===Hc.OnEventDeleted&&(a.data=a.data.filter((e=>e!==t.eventId))),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class ay extends Or{constructor(e,t){const n=R.default(e),a=["event","collection",n];super(new ty(e),n,a,t),this.query=e,this.queryStreamController=new ny(this.query,this.cacheKey,this.notifyChange.bind(this),Lc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:Hc.OnEventCreated},{fn:Wc,action:Hc.OnEventUpdated},{fn:Xc,action:Hc.OnEventDeleted},{fn:Zc,action:Hc.OnEventCreated},{fn:ed,action:Hc.OnEventUpdated},{fn:td,action:Hc.OnEventDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>nt(["event","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(dd.event);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}class sy extends fr{async getRequest(e,t){const{limit:n=me}=e,a=_n(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/events/me/rsvps",{params:Object.assign(Object.assign({},a),{options:s})});return o}}class oy extends Ir{constructor(e,t,n,a){super(e,t),this.notifyChange=n,this.preparePayload=a}async saveToMainDB(e){const t=this.preparePayload(e),n=Ge(),a=n.cache&&Date.now();n.cache&&Nn(t,{cachedAt:a})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.events.map(Xe("event"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.events.map(Xe("event"))])]}))}}reactor(e){return t=>{var n;const a=null===(n=nt(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(e===Hc.OnEventCreated){if(Ge().userId!==t.userId)return;a.data=[...new Set([t.eventId,...a.data])]}e===Hc.OnEventDeleted&&(a.data=a.data.filter((e=>e!==t.eventId))),at(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class iy extends Or{constructor(e,t){const n=R.default(e),a=["event","collection",n];super(new sy(e),n,a,t),this.query=e,this.queryStreamController=new oy(this.query,this.cacheKey,this.notifyChange.bind(this),Lc),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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:Hc.OnEventCreated},{fn:Wc,action:Hc.OnEventUpdated},{fn:Xc,action:Hc.OnEventDeleted},{fn:Zc,action:Hc.OnEventCreated},{fn:ed,action:Hc.OnEventUpdated},{fn:td,action:Hc.OnEventDeleted}])}notifyChange({origin:e,loading:t,error:n}){var a,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=(null!==(s=o.data.map((e=>nt(["event","get",e]))).filter(Tr).map((({data:e})=>e)))&&void 0!==s?s:[]).map(dd.event);(this.shouldNotify(i)||"event"!==e)&&this.callback({data:i,error:n,loading:t,hasNextPage:!!this.paginationController.getNextToken(),onNextPage:()=>this.loadPage({direction:"next"})})}}var ry=Object.freeze({__proto__:null,createEvent:async e=>{const t=Ge();t.log("event/createEvent",e);const{data:n}=await t.http.post("/api/v1/events",e);xt("local.event.created",n);const a=Lc(n),s=t.cache&&Date.now();return t.cache&&Nn(a,{cachedAt:s}),{data:cd(a.events[0]),cachedAt:s}},updateEvent:async(e,t)=>{const n=Ge();n.log("event/updateEvent",e,t);const{data:a}=await n.http.put(`/api/v1/events/${e}`,t);xt("local.event.updated",a);const s=Lc(a),o=n.cache&&Date.now();return n.cache&&Nn(s,{cachedAt:o}),{data:cd(s.events.find((t=>t.eventId===e))),cachedAt:o}},deleteEvent:async e=>{const t=Ge();t.log("event/deleteEvent",e);const n=await ey(e);await t.http.delete(`/api/v1/events/${e}`);const a=Object.assign(Object.assign({},n.data),{isDeleted:!0});ot(["event","get",e],a),xt("local.event.deleted",{users:[],files:[],communities:[],posts:[],rooms:[],events:[a]})},onEventCreated:Yc,onEventUpdated:Wc,onEventDeleted:Xc,onLocalEventCreated:Zc,onLocalEventUpdated:ed,onLocalEventDeleted:td,onRSVPCreated:nd,onRSVPUpdated:ad,onLocalRSVPCreated:sd,onLocalRSVPUpdated:od,getEvent:(e,t)=>jr(e,t,"eventId",ey,[Wc,Xc,ed,td],{callbackDataSelector:e=>e?cd(e):e}),getEvents:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getEvents: (tmpid: ${o}) > listen`);const i=new ay(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getEvents (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getMyEvents:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`getMyEvents: (tmpid: ${o}) > listen`);const i=new iy(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`getMyEvents (tmpid: ${o}) > dispose`),r.forEach((e=>e()))}},getRSVPs:rd});const cy=async e=>{const t=Ge();let n;t.log("product/getProduct",e),Zn("product",e);try{n=(await t.http.get(`/api/v1/products/${encodeURIComponent(e)}`)).data}catch(t){throw Re(null==t?void 0:t.code)&&Fn("product",e),t}const a=t.cache&&Date.now();t.cache&&Nn(n,{cachedAt:a});const{products:s}=n;return{data:s.find((t=>t.productId===e)),cachedAt:a}};cy.locally=e=>{const t=Ge();if(t.log("product/getProduct.locally",e),!t.cache)return;const n=nt(["product","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class dy extends fr{async getRequest(e,t){const{limit:n=me}=e,a=_n(e,["limit"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v1/products/search",{params:Object.assign(Object.assign({},a),{options:s})});return o}}class ly extends Ir{constructor(e,t,n){super(e,t),this.notifyChange=n}saveToMainDB(e){const t=Ge(),n=t.cache&&Date.now();t.cache&&Nn(e,{cachedAt:n})}appendToQueryStream(e,t,n=!1){var a,s;if(n)at(this.cacheKey,{data:e.products.map(Xe("product"))});else{const t=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];at(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.products.map(Xe("product"))])]}))}}}class uy extends Or{constructor(e,t){const n=R.default(e),a=["products","collection",n];super(new dy(e),n,a,t),this.query=e,this.queryStreamController=new ly(this.query,this.cacheKey,this.notifyChange.bind(this)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=nt(this.cacheKey))||void 0===e?void 0:e.data)||at(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,s;const o=null===(a=nt(this.cacheKey))||void 0===a?void 0:a.data;if(!o)return;const i=null!==(s=o.data.map((e=>nt(["product","get",e]))).filter(Tr).map((({data:e})=>e)).map(dd.product))&&void 0!==s?s:[];(this.shouldNotify(i)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var hy=Object.freeze({__proto__:null,getProduct:(e,t)=>jr(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?dd.product(n):n}))}),"productId",cy,[]),searchProducts:(e,t,n)=>{const{log:a,cache:s}=Ge();s||console.log(ye);const o=Date.now();a(`searchProducts(tmpid: ${o}) > listen`);const i=new uy(e,t),r=i.startSubscription(),c=i.getCacheKey();return r.push((()=>it(c))),()=>{a(`searchProducts(tmpid: ${o}) > dispose`),r.forEach((e=>e()))}}});return e.API_REGIONS=sn,e.AdRepository=_p,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=Bu,e.Client=tr,e.CommentRepository=fm,e.CommunityPostSettingMaps=x,e.CommunityPostSettings=q,e.CommunityRepository=Yh,e.ContentFeedType=F,e.DefaultCommunityPostSetting=K,e.EventRepository=ry,e.FeedRepository=Qm,e.FileRepository=Fd,e.FileType=D,e.GET_WATCHER_URLS=pc,e.InvitationRepository=Wp,e.LiveReactionRepository=Zp,e.LiveStreamPlayer=rp,e.MessageContentType=B,e.MessageRepository=lu,e.PollRepository=ap,e.PostContentType=$,e.PostRepository=Fg,e.PostStructureType=L,e.ProductRepository=hy,e.ReactionRepository=El,e.RoomPresenceRepository=Zg,e.RoomRepository=Mg,e.StoryRepository=Kp,e.StreamRepository=zg,e.SubChannelRepository=vu,e.UserRepository=qd,e.VERSION=he,e.VideoResolution=U,e.VideoSize=j,e.VideoTranscodingStatus=k,e.backupCache=async(e="amitySdk",t=(e=>e.offline))=>{const{log:n,cache:a,userId:s}=Ge();if(!a)return!1;n("cache/api/backupCache",{storageKey:e});const o=Object.fromEntries(Object.entries(a.data).filter((([e,n])=>t(n))));return!!Object.keys(o).length&&(localStorage&&await localStorage.setItem(`${e}#${s}`,JSON.stringify(o)),!0)},e.createQuery=Fe,e.createReport=async(e,t,n)=>{const a=Ge();return a.log("report/createReport",{referenceType:e,referenceId:t,options:n}),"user"===e?(async({referenceId:e,options:t})=>!!await ud(e,t))({referenceId:t,options:n}):"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 ua(n);Nn(e)}return xt("message.flagged",n),!!n})({client:a,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 Yd(n);Nn(e)}return xt("post.flagged",n),!!n})({client:a,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 Ml(n);Nn(e)}return xt("comment.flagged",n),!!n})({client:a,referenceId:t})},e.createUserToken=async(e,t,n)=>{const a=await jn(),s=En(),o=pn(rn("http",t)),{data:i}=await o.post("/api/v5/sessions",Object.assign(Object.assign({},n),{deviceId:a,deviceInfo:Object.assign(Object.assign({},s),{model:"token management API on TS-SDK"})}),{headers:{"X-API-Key":e}});return{accessToken:i.accessToken}},e.deleteReport=async(e,t)=>{const n=Ge();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 Ws(n);Nn(e)}return xt("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 ua(n);Nn(e)}return xt("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 Yd(n);Nn(e)}return xt("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 Ml(n);Nn(e)}return xt("comment.unflagged",n),!!n})({client:n,referenceId:t})},e.disableCache=()=>{const e=Ge();e.cache&&(e.log("cache/api/disableCache"),delete e.cache)},e.dropFromCache=it,e.enableCache=(e={},t)=>{const n=Ge();n.cache||(n.log("cache/api/enableCache"),n.cache={data:e,persistIf:t})},e.exceedsUntilAtBoundary=Rt,e.filterByChannelMembership=lt,e.filterByCommunityMembership=ht,e.filterByFeedType=ut,e.filterByPostDataTypes=mt,e.filterByPropEquality=rt,e.filterByPropInclusion=(e,t,n)=>void 0!==n?e.filter((e=>n.includes(e[t]))):e,e.filterByPropIntersection=dt,e.filterBySearchTerm=gt,e.filterByStringComparePartially=ct,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=vt,e.filterPostsByBlockUsers=yt,e.getBlockUsersId=pt,e.getChannelTopic=e=>`${e.path}/#`,e.getCommentTopic=({path:e})=>e,e.getCommunityStoriesTopic=({targetId:e,targetType:t})=>{const n=Dt();return`${Qt(n)}/social/${t}/${e}/story/#`},e.getCommunityTopic=({path:t},n=e.SubscriptionLevels.COMMUNITY)=>Lt(t,n),e.getLiveReactionTopic=e=>`${e.path}/liveReaction`,e.getLiveStreamTopic=Xt,e.getMarkedMessageTopic=Ht,e.getMarkerUserFeedTopic=()=>{const e=Dt();return`${Qt(e)}/marker/user/${e._id}`},e.getMessageTopic=e=>e.path,e.getMyFollowersTopic=Vt,e.getMyFollowingsTopic=Jt,e.getNetworkId=Qt,e.getNetworkTopic=zt,e.getPostTopic=({path:t},n=e.SubscriptionLevels.POST)=>"comment"===n?`${t}/comment/+`:t,e.getRole=Bd,e.getRoomStreamerTopic=e=>{const t=Bt();return`${Qt(t)}/room/${e.roomId}/streamer`},e.getRoomWatcherTopic=e=>{const t=Bt();return`${Qt(t)}/room/${e._id}`},e.getSmartFeedChannelTopic=Gt,e.getSmartFeedMessageTopic=Wt,e.getSmartFeedSubChannelTopic=Yt,e.getStoryTopic=({targetId:e,targetType:t,storyId:n})=>{const a=Dt();return`${Qt(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=De,e.isAfterBeforeRaw=Ue,e.isCachable=Ke,e.isFetcher=Me,e.isFresh=Ne,e.isLocal=e=>Ke(e)&&-1===(null==e?void 0:e.cachedAt),e.isMutator=qe,e.isOffline=xe,e.isPaged=ke,e.isReportedByMe=async(e,t)=>{const n=Ge();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:s,isFlagByMe:o}=null!=a?a:{};return null!==(n=null!=s?s:o)&&void 0!==n&&n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{var n;const{data:a}=await e.http.get(`/api/v5/messages/${encodeURIComponent(t)}/flags`),{result:s,isFlagByMe:o}=null!=a?a:{};return null!==(n=null!=s?s:o)&&void 0!==n&&n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{var n;const{data:a}=await e.http.get(`/api/v3/posts/${t}/isflagbyme`),{result:s,isFlagByMe:o}=null!=a?a:{};return null!==(n=null!=s?s:o)&&void 0!==n&&n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{var n;const{data:a}=await e.http.get(`/api/v3/comments/${t}/isflagbyme`),{result:s,isFlagByMe:o}=null!=a?a:{};return null!==(n=null!=s?s:o)&&void 0!==n&&n})({client:n,referenceId:t})},e.isSkip=Pe,e.mergeInCache=st,e.notificationTray=Hp,e.onChannelMarkerFetched=Ji,e.onFeedMarkerFetched=e=>{const t=Ge();return qt(t,"feedMarker/onFeedMarkerFetched","local.feedMarker.fetched",(t=>{e(t.feedMarkers[0])}))},e.onFeedMarkerUpdated=e=>{const t=Ge();return qt(t,"feedMarker/onFeedMarkerUpdated","marker.feed-updated",(t=>{Nn(t),e(t.feedMarkers[0])}))},e.onMessageMarked=Wi,e.onMessageMarkerFetched=Yi,e.onSubChannelMarkerFetched=Hi,e.onSubChannelMarkerUpdated=zi,e.onUserMarkerFetched=Gi,e.onUserMarkerFetchedLegacy=e=>{const t=Ge();return qt(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers[0])}))},e.pullFromCache=nt,e.pushToCache=at,e.queryCache=tt,e.queryOptions=_e,e.queryRoles=_d,e.restoreCache=async(e="amitySdk")=>{var t;const n=Ge();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 s={};try{s=JSON.parse(a)}catch(e){}return n.cache.data=Object.assign(Object.assign({},s),n.cache.data),!0},e.runQuery=Be,e.sortByChannelSegment=({channelSegment:e},{channelSegment:t})=>e-t,e.sortByDisplayName=ft,e.sortByFirstCreated=It,e.sortByFirstUpdated=St,e.sortByLastActivity=Tt,e.sortByLastCreated=wt,e.sortByLastUpdated=Ot,e.sortByLocalSortingDate=Ct,e.sortByName=bt,e.sortBySegmentNumber=({segmentNumber:e},{segmentNumber:t})=>e-t,e.subscribeTopic=Zt,e.toPage=Ee,e.toPageRaw=e=>{if(!e)return;const n=JSON.parse(t.decode(e));return Ue(n)?n:void 0},e.toToken=je,e.upsertInCache=ot,e.validateUntilAt=At,e.wipeCache=async(e="amitySdk")=>{const{log:t,cache:n,userId:a}=Ge();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,mqtt,AsyncStorage,uuid$1,jwtDecode,reactNative,hash,Hls);